code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
#!/usr/bin/env python # coding: utf-8 # ### - Plot BIC and Silhouette scores across all clusters for Cell painting & L1000 # In[1]: from collections import defaultdict import os import requests import pickle import argparse import pandas as pd import numpy as np import re from os import walk from collections import Counter import random import shutil import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') import seaborn as sns sns.set_style("darkgrid") ##sns.set_palette(["red", "green", "orange","blue","gray","purple"]) sns.set_context("talk") import pickle from statistics import median import warnings warnings.simplefilter(action='ignore', category=FutureWarning) np.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning) # In[2]: cp_level4_path = '../cell_painting/cellpainting_lvl4_cpd_replicate_datasets' L1000_level4_path = '../L1000/L1000_lvl4_cpd_replicate_datasets' # In[3]: df_lvl4_L1 = pd.read_csv(os.path.join(L1000_level4_path, 'L1000_level4_cpd_replicates.csv.gz'), compression='gzip',low_memory = False) df_lvl4_cp = pd.read_csv(os.path.join(cp_level4_path, 'cp_level4_cpd_replicates.csv.gz'), compression='gzip',low_memory = False) # In[4]: df_lvl4_cp.shape # In[5]: df_silh_L1000 = pd.read_csv(os.path.join(L1000_level4_path, 'L1000_silhouette_scores.csv')) df_db_L1000 = pd.read_csv(os.path.join(L1000_level4_path, 'L1000_db_scores.csv')) # In[6]: df_silh_cp = pd.read_csv(os.path.join(cp_level4_path, 'cp_silhouette_scores.csv')) df_db_cp = pd.read_csv(os.path.join(cp_level4_path, 'cp_db_scores.csv')) # In[7]: df_cp_bic = pd.read_csv(os.path.join(cp_level4_path, 'cp_bic_scores.csv')) df_L1_bic = pd.read_csv(os.path.join(L1000_level4_path, 'L1000_bic_scores.csv')) # In[8]: dose_recode = {1 : '0.04 uM', 2:'0.12 uM', 3:'0.37 uM', 4: '1.11 uM', 5:'3.33 uM', 6:'10 uM'} # In[9]: df_silh_cp['dose'].unique() # In[10]: df_silh_cp['profile_tech'] = 'Cell painting' df_silh_L1000['profile_tech'] = 'L1000' # In[11]: df_silh_cp['dose'] = df_silh_cp['dose'].map(dose_recode) df_silh_L1000['dose'] = df_silh_L1000['dose'].map(dose_recode) # In[12]: df_cp_bic['profile_tech'] = 'Cell painting' df_L1_bic['profile_tech'] = 'L1000' # In[13]: df_cp_bic['dose'] = df_cp_bic['dose'].map(dose_recode) df_L1_bic['dose'] = df_L1_bic['dose'].map(dose_recode) # In[14]: df_bic = pd.concat([df_cp_bic, df_L1_bic], ignore_index=True) # In[15]: df_silh = pd.concat([df_silh_cp, df_silh_L1000], ignore_index=True) df_db = pd.concat([df_db_cp, df_db_L1000], ignore_index=True) # In[16]: rel_plt = sns.relplot(data=df_silh, x="cluster", y="Average_silhouette_score", col="profile_tech", hue = 'dose', kind="line", palette = 'inferno', style="dose", markers=True, col_wrap=2, height=5.5, aspect=1.3, alpha = 0.8) rel_plt._legend.set_title('') rel_plt.set_axis_labels("Number of clusters", "Average silhouette score") rel_ax = rel_plt.axes.flatten() rel_ax[0].set_title("Cell Painting") rel_ax[1].set_title("L1000") rel_plt.fig.suptitle('Silhouette scores for L1000 and Cell painting') rel_plt.fig.subplots_adjust(top=.87) # In[17]: rel_plt = sns.relplot(data=df_cp_bic, x="cluster", y="BIC_score", hue = 'dose', kind="line", markers=True, style="dose", palette = "magma_r", height=5.5, aspect=1.8) rel_plt._legend.set_title('') rel_plt.set_axis_labels("Number of clusters", "BIC score") rel_plt.fig.suptitle('BIC scores for Cell painting') rel_plt.fig.subplots_adjust(top=.91) # In[18]: rel_plt = sns.relplot(data=df_L1_bic, x="cluster", y="BIC_score", hue = 'dose', kind="line", markers=True, style="dose", palette = "magma_r", height=5.5, aspect=1.8) rel_plt._legend.set_title('') rel_plt.set_axis_labels("Number of clusters", "BIC score") rel_plt.fig.suptitle('BIC scores for L1000') rel_plt.fig.subplots_adjust(top=.91) # In[ ]:
[ "seaborn.set_context", "numpy.warnings.filterwarnings", "os.path.join", "seaborn.set_style", "warnings.simplefilter", "pandas.concat", "seaborn.relplot" ]
[((464, 489), 'seaborn.set_style', 'sns.set_style', (['"""darkgrid"""'], {}), "('darkgrid')\n", (477, 489), True, 'import seaborn as sns\n'), ((559, 582), 'seaborn.set_context', 'sns.set_context', (['"""talk"""'], {}), "('talk')\n", (574, 582), True, 'import seaborn as sns\n'), ((644, 706), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), "(action='ignore', category=FutureWarning)\n", (665, 706), False, 'import warnings\n'), ((707, 782), 'numpy.warnings.filterwarnings', 'np.warnings.filterwarnings', (['"""ignore"""'], {'category': 'np.VisibleDeprecationWarning'}), "('ignore', category=np.VisibleDeprecationWarning)\n", (733, 782), True, 'import numpy as np\n'), ((2444, 2496), 'pandas.concat', 'pd.concat', (['[df_cp_bic, df_L1_bic]'], {'ignore_index': '(True)'}), '([df_cp_bic, df_L1_bic], ignore_index=True)\n', (2453, 2496), True, 'import pandas as pd\n'), ((2521, 2578), 'pandas.concat', 'pd.concat', (['[df_silh_cp, df_silh_L1000]'], {'ignore_index': '(True)'}), '([df_silh_cp, df_silh_L1000], ignore_index=True)\n', (2530, 2578), True, 'import pandas as pd\n'), ((2587, 2640), 'pandas.concat', 'pd.concat', (['[df_db_cp, df_db_L1000]'], {'ignore_index': '(True)'}), '([df_db_cp, df_db_L1000], ignore_index=True)\n', (2596, 2640), True, 'import pandas as pd\n'), ((2665, 2882), 'seaborn.relplot', 'sns.relplot', ([], {'data': 'df_silh', 'x': '"""cluster"""', 'y': '"""Average_silhouette_score"""', 'col': '"""profile_tech"""', 'hue': '"""dose"""', 'kind': '"""line"""', 'palette': '"""inferno"""', 'style': '"""dose"""', 'markers': '(True)', 'col_wrap': '(2)', 'height': '(5.5)', 'aspect': '(1.3)', 'alpha': '(0.8)'}), "(data=df_silh, x='cluster', y='Average_silhouette_score', col=\n 'profile_tech', hue='dose', kind='line', palette='inferno', style=\n 'dose', markers=True, col_wrap=2, height=5.5, aspect=1.3, alpha=0.8)\n", (2676, 2882), True, 'import seaborn as sns\n'), ((3256, 3416), 'seaborn.relplot', 'sns.relplot', ([], {'data': 'df_cp_bic', 'x': '"""cluster"""', 'y': '"""BIC_score"""', 'hue': '"""dose"""', 'kind': '"""line"""', 'markers': '(True)', 'style': '"""dose"""', 'palette': '"""magma_r"""', 'height': '(5.5)', 'aspect': '(1.8)'}), "(data=df_cp_bic, x='cluster', y='BIC_score', hue='dose', kind=\n 'line', markers=True, style='dose', palette='magma_r', height=5.5,\n aspect=1.8)\n", (3267, 3416), True, 'import seaborn as sns\n'), ((3627, 3787), 'seaborn.relplot', 'sns.relplot', ([], {'data': 'df_L1_bic', 'x': '"""cluster"""', 'y': '"""BIC_score"""', 'hue': '"""dose"""', 'kind': '"""line"""', 'markers': '(True)', 'style': '"""dose"""', 'palette': '"""magma_r"""', 'height': '(5.5)', 'aspect': '(1.8)'}), "(data=df_L1_bic, x='cluster', y='BIC_score', hue='dose', kind=\n 'line', markers=True, style='dose', palette='magma_r', height=5.5,\n aspect=1.8)\n", (3638, 3787), True, 'import seaborn as sns\n'), ((976, 1045), 'os.path.join', 'os.path.join', (['L1000_level4_path', '"""L1000_level4_cpd_replicates.csv.gz"""'], {}), "(L1000_level4_path, 'L1000_level4_cpd_replicates.csv.gz')\n", (988, 1045), False, 'import os\n'), ((1137, 1200), 'os.path.join', 'os.path.join', (['cp_level4_path', '"""cp_level4_cpd_replicates.csv.gz"""'], {}), "(cp_level4_path, 'cp_level4_cpd_replicates.csv.gz')\n", (1149, 1200), False, 'import os\n'), ((1338, 1400), 'os.path.join', 'os.path.join', (['L1000_level4_path', '"""L1000_silhouette_scores.csv"""'], {}), "(L1000_level4_path, 'L1000_silhouette_scores.csv')\n", (1350, 1400), False, 'import os\n'), ((1428, 1482), 'os.path.join', 'os.path.join', (['L1000_level4_path', '"""L1000_db_scores.csv"""'], {}), "(L1000_level4_path, 'L1000_db_scores.csv')\n", (1440, 1482), False, 'import os\n'), ((1522, 1578), 'os.path.join', 'os.path.join', (['cp_level4_path', '"""cp_silhouette_scores.csv"""'], {}), "(cp_level4_path, 'cp_silhouette_scores.csv')\n", (1534, 1578), False, 'import os\n'), ((1603, 1651), 'os.path.join', 'os.path.join', (['cp_level4_path', '"""cp_db_scores.csv"""'], {}), "(cp_level4_path, 'cp_db_scores.csv')\n", (1615, 1651), False, 'import os\n'), ((1690, 1739), 'os.path.join', 'os.path.join', (['cp_level4_path', '"""cp_bic_scores.csv"""'], {}), "(cp_level4_path, 'cp_bic_scores.csv')\n", (1702, 1739), False, 'import os\n'), ((1765, 1820), 'os.path.join', 'os.path.join', (['L1000_level4_path', '"""L1000_bic_scores.csv"""'], {}), "(L1000_level4_path, 'L1000_bic_scores.csv')\n", (1777, 1820), False, 'import os\n')]
import numpy as np import networkx as nx import json class SIRNetwork: def __init__(self, datafiles, travel_rate, beta, gamma, travel_infection_rate = 1): self.graph, self.A, self.pos = self.load_graph(datafiles['data'], datafiles['position']) self.nodes = list(self.graph.nodes()) self.node_degree = np.sum(self.A, 0) self.number_of_nodes = self.A.shape[0] self.travel_rate = travel_rate self.beta = beta self.gamma = gamma self.R0 = self.beta/self.gamma self.travel_infection_rate = travel_infection_rate def load_graph(self, file_graph, file_positions): with open(file_graph) as json_file: import_data = json.load(json_file) with open(file_positions) as json_file: import_pos = json.load(json_file) import_graph = nx.node_link_graph(import_data) G = import_graph pos = import_pos n_nodes = nx.number_of_nodes(G) A = nx.to_numpy_array(G) #Save the adjacency matrix of the network return G, A, pos
[ "networkx.node_link_graph", "networkx.to_numpy_array", "numpy.sum", "json.load", "networkx.number_of_nodes" ]
[((331, 348), 'numpy.sum', 'np.sum', (['self.A', '(0)'], {}), '(self.A, 0)\n', (337, 348), True, 'import numpy as np\n'), ((859, 890), 'networkx.node_link_graph', 'nx.node_link_graph', (['import_data'], {}), '(import_data)\n', (877, 890), True, 'import networkx as nx\n'), ((960, 981), 'networkx.number_of_nodes', 'nx.number_of_nodes', (['G'], {}), '(G)\n', (978, 981), True, 'import networkx as nx\n'), ((994, 1014), 'networkx.to_numpy_array', 'nx.to_numpy_array', (['G'], {}), '(G)\n', (1011, 1014), True, 'import networkx as nx\n'), ((720, 740), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (729, 740), False, 'import json\n'), ((814, 834), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (823, 834), False, 'import json\n')]
####################################### import numpy as np import pylab from scipy.interpolate import interp1d from scipy import optimize from numba import jit ####################################### @jit(nopython=True) def qr(t00,Start_time,heatscale): #interior radiogenic heatproduction t = t00 - Start_time*365*24*60*60 u238 = 0.9928 * (0.022e-6) * 9.17e-5 * np.exp(-(np.log(2)/4.46e9)*(t/(365*24*60*60)-4.5e9)) u235 = 0.0072 * (0.022e-6) * 5.75e-4 * np.exp(-(np.log(2)/7.04e8)*(t/(365*24*60*60)-4.5e9)) Th = (0.069e-6) * 2.56e-5 * np.exp(-(np.log(2)/1.4e10)*(t/(365*24*60*60)-4.5e9)) K = 1.17e-4 * (280e-6) * 2.97e-5 * np.exp(-(np.log(2)/1.26e9)*(t/(365*24*60*60)-4.5e9)) Al = 5e-5 * 3.54e-1 * (8650e-6) * np.exp(-(np.log(2)/7.17e5)*(t/(365*24*60*60))) return (heatscale*u238 + heatscale*u235 + heatscale*Th + heatscale*K + Al) @jit(nopython=True) #calcuate mantle viscosity def viscosity_fun(Tp,pm,visc_offset,Tsurf,Tsolidus): visc_rock = visc_offset*3.8e7 * np.exp(350000/(8.314*Tp))/pm visc_liq = 0.00024*np.exp(4600.0 / (Tp - 1000.0))/pm LowerT = Tsolidus UpperT = LowerT + 600.0 if Tp < LowerT+0.000: visc = visc_rock elif Tp > UpperT+0.000: visc = visc_liq else: v1 = np.log10(visc_rock) v2 = np.log10(visc_liq) logvisc = ( v2 * 0.2*(Tp - (LowerT))**5 + v1 * 0.8*(UpperT - Tp)**5) / ( 0.2*(Tp - (LowerT))**5 + 0.8*(UpperT - Tp)**5) visc = 10**logvisc return visc @jit(nopython=True) def f_for_optim(x,kH2O,Mcrystal,Mliq,rp,yH2O_liq,g,MMW): result = (kH2O * x * Mcrystal + x * (Mliq-Mcrystal) + 4.0 *(0.018/MMW)* np.pi * (rp**2/g) * (x / 3.44e-8)**(1.0/0.74) - yH2O_liq) return result def H2O_partition_function( yH2O_liq,Mliq,Mcrystal,rp,g,kH2O,MMW): #partition H2O between magma ocean and atmosphere if (Mliq >0)or(Mliq>0): FH2O = optimize.newton(f_for_optim,0.5,args=(kH2O,Mcrystal,Mliq,rp,yH2O_liq,g,MMW)) Pressure_surface = (FH2O / 3.44e-8)**(1.0/0.74) else: FH2O = 3.44e-8*( yH2O_liq/(4 * (0.018/MMW) * np.pi * (rp**2/g)) ) ** (0.74) Pressure_surface = (FH2O / 3.44e-8)**(1.0/0.74) return [FH2O,Pressure_surface] @jit(nopython=True) def CO2_partition_function( yCO2_liq,Mliq,Mcrystal,rp,g,kCO2,MMW): #partition CO2 between magma ocean and atmosphere if (Mliq>0)or(Mcrystal>0): FCO2 = yCO2_liq / (kCO2 * Mcrystal + (Mliq-Mcrystal) + 4 * (0.044/MMW) * np.pi * (rp**2/g) * (1 /4.4e-12)) Pressure_surface = (FCO2 /4.4e-12) else: FCO2 = 0.0 Pressure_surface = (yCO2_liq*g)/(4.0 *(0.044/MMW)* np.pi * (rp**2)) return [FCO2,Pressure_surface] @jit(nopython=True) def Mliq_fun(y2,rp,rs,pm): #calculate liquid mass of mantle if rs < rp: Mliq = pm * 4./3. * np.pi * (rp**3 - rs**3) else: Mliq = 0.0 return Mliq @jit(nopython=True) def rs_term_fun(r,a1,b1,a2,b2,g,alpha,cp,pm,rp,Tp,Poverburd): #controls solidification radius evolution numerator = 1 + alpha*(g/cp) * (rp - r) e1 = np.exp(1e-5*(-rp+r+100000)) e2 = np.exp(1e-5*(rp-r-100000)) sub_denom = (e1+e2)**2 T1 = (b1+a1*g*pm*(rp-r)+a1*Poverburd) T2 = (b2+a2*g*pm*(rp-r)+a2*Poverburd) sub_num1 = ((-a1*g*pm*e1 + T1*1e-5*e1) + (-a2*g*pm*e2 - T2*1e-5*e2))*(e1+e2) sub_num2 = (T1*e1+T2*e2)*(1e-5*e1-1e-5*e2) everything = (sub_num1 - sub_num2)/sub_denom if r>rp: return 0 else: return numerator /(alpha*g*Tp/cp + everything) @jit(nopython=True) def adiabat(radius,Tp,alpha,g,cp,rp): #mantle adiabat Tr = Tp*(1 + alpha*(g/cp)*(rp-radius)) return Tr @jit(nopython=True) def sol_liq(radius,g,pm,rp,Poverburd,mH2O): #For calculating solidus a1 = 104.42e-9 b1 = 1420+0.000 - 80.0 TS1 = b1 + a1 * g * pm * (rp - radius) + a1 * Poverburd - 4.7e4 * mH2O**0.75 if TS1 < 1170.0: T_sol1 = 1170.0+0*TS1 else: T_sol1 = TS1 a2 = 26.53e-9 b2 = 1825+0.000 TS2 = b2 + a2 * g * pm * (rp -radius) + a2 * Poverburd - 4.7e4 * mH2O**0.75 if TS2 < 1170.0: T_sol2 = 1170.0+0*TS2 else: T_sol2 = TS2 T_sol = (T_sol1 * np.exp(1e-5*( -rp + radius + 100000)) + T_sol2 * np.exp(1e-5*(rp - radius - 100000)))/ (np.exp(1e-5*(-rp + radius + 100000)) + np.exp(1e-5*(rp - radius - 100000))) return T_sol def find_r(r,Tp,alpha,g,cp,pm,rp,Poverburd,mH2O): ## used for finding the solidus radius numerically Tr = adiabat(r,Tp,alpha,g,cp,rp) rr = float(r) T_sol = sol_liq(rr,g,pm,rp,Poverburd,mH2O) return (Tr-T_sol)**2.0 @jit(nopython=True) def temp_meltfrac(rc,rp,alpha,pm,Tp,cp,g,Poverburd,mH2O): #for calculating melt fraction rad = np.linspace(rc,rp,1000) melt_r = np.copy(rad) visc_r = np.copy(rad) vol_r = np.copy(rad)*0 + 4.0*np.pi*(rad[1]-rad[0]) for j in range(0,len(rad)): Tsol = sol_liq(float(rad[j]),g,pm,rp,Poverburd,mH2O) Tliq = Tsol + 600.0 T_r = adiabat(rad[j],Tp,alpha,g,cp,rp) # if T_r>Tliq: melt_r[j] = 1.0 visc_r[j] = 1 vol_r[j] = vol_r[j]*rad[j]**2 elif T_r<Tsol: melt_r[j] = 0.0 visc_r[j] = 1 vol_r[j] = 0.0 else: melt_r[j] = (T_r - Tsol)/(Tliq - Tsol) visc_r[j] = 1 vol_r[j] = vol_r[j]*rad[j]**2 if np.sum(vol_r) == 0.0: return (0.0,0.0,0.0) actual_phi_surf = np.sum(melt_r*vol_r)/np.sum(vol_r) Va = np.sum(vol_r) actual_visc = np.sum(visc_r*vol_r)/np.sum(vol_r) return (actual_phi_surf,actual_visc,Va)
[ "numpy.copy", "numpy.log10", "numpy.log", "scipy.optimize.newton", "numpy.exp", "numpy.sum", "numpy.linspace", "numba.jit" ]
[((210, 228), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (213, 228), False, 'from numba import jit\n'), ((886, 904), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (889, 904), False, 'from numba import jit\n'), ((1534, 1552), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (1537, 1552), False, 'from numba import jit\n'), ((2258, 2276), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (2261, 2276), False, 'from numba import jit\n'), ((2736, 2754), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (2739, 2754), False, 'from numba import jit\n'), ((2942, 2960), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (2945, 2960), False, 'from numba import jit\n'), ((3588, 3606), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (3591, 3606), False, 'from numba import jit\n'), ((3733, 3751), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (3736, 3751), False, 'from numba import jit\n'), ((4723, 4741), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (4726, 4741), False, 'from numba import jit\n'), ((3125, 3159), 'numpy.exp', 'np.exp', (['(1e-05 * (-rp + r + 100000))'], {}), '(1e-05 * (-rp + r + 100000))\n', (3131, 3159), True, 'import numpy as np\n'), ((3163, 3196), 'numpy.exp', 'np.exp', (['(1e-05 * (rp - r - 100000))'], {}), '(1e-05 * (rp - r - 100000))\n', (3169, 3196), True, 'import numpy as np\n'), ((4847, 4872), 'numpy.linspace', 'np.linspace', (['rc', 'rp', '(1000)'], {}), '(rc, rp, 1000)\n', (4858, 4872), True, 'import numpy as np\n'), ((4885, 4897), 'numpy.copy', 'np.copy', (['rad'], {}), '(rad)\n', (4892, 4897), True, 'import numpy as np\n'), ((4912, 4924), 'numpy.copy', 'np.copy', (['rad'], {}), '(rad)\n', (4919, 4924), True, 'import numpy as np\n'), ((5650, 5663), 'numpy.sum', 'np.sum', (['vol_r'], {}), '(vol_r)\n', (5656, 5663), True, 'import numpy as np\n'), ((1931, 2019), 'scipy.optimize.newton', 'optimize.newton', (['f_for_optim', '(0.5)'], {'args': '(kH2O, Mcrystal, Mliq, rp, yH2O_liq, g, MMW)'}), '(f_for_optim, 0.5, args=(kH2O, Mcrystal, Mliq, rp, yH2O_liq,\n g, MMW))\n', (1946, 2019), False, 'from scipy import optimize\n'), ((5530, 5543), 'numpy.sum', 'np.sum', (['vol_r'], {}), '(vol_r)\n', (5536, 5543), True, 'import numpy as np\n'), ((5605, 5627), 'numpy.sum', 'np.sum', (['(melt_r * vol_r)'], {}), '(melt_r * vol_r)\n', (5611, 5627), True, 'import numpy as np\n'), ((5626, 5639), 'numpy.sum', 'np.sum', (['vol_r'], {}), '(vol_r)\n', (5632, 5639), True, 'import numpy as np\n'), ((5685, 5707), 'numpy.sum', 'np.sum', (['(visc_r * vol_r)'], {}), '(visc_r * vol_r)\n', (5691, 5707), True, 'import numpy as np\n'), ((5706, 5719), 'numpy.sum', 'np.sum', (['vol_r'], {}), '(vol_r)\n', (5712, 5719), True, 'import numpy as np\n'), ((1023, 1052), 'numpy.exp', 'np.exp', (['(350000 / (8.314 * Tp))'], {}), '(350000 / (8.314 * Tp))\n', (1029, 1052), True, 'import numpy as np\n'), ((1077, 1107), 'numpy.exp', 'np.exp', (['(4600.0 / (Tp - 1000.0))'], {}), '(4600.0 / (Tp - 1000.0))\n', (1083, 1107), True, 'import numpy as np\n'), ((1303, 1322), 'numpy.log10', 'np.log10', (['visc_rock'], {}), '(visc_rock)\n', (1311, 1322), True, 'import numpy as np\n'), ((1337, 1355), 'numpy.log10', 'np.log10', (['visc_liq'], {}), '(visc_liq)\n', (1345, 1355), True, 'import numpy as np\n'), ((4373, 4412), 'numpy.exp', 'np.exp', (['(1e-05 * (-rp + radius + 100000))'], {}), '(1e-05 * (-rp + radius + 100000))\n', (4379, 4412), True, 'import numpy as np\n'), ((4413, 4451), 'numpy.exp', 'np.exp', (['(1e-05 * (rp - radius - 100000))'], {}), '(1e-05 * (rp - radius - 100000))\n', (4419, 4451), True, 'import numpy as np\n'), ((4938, 4950), 'numpy.copy', 'np.copy', (['rad'], {}), '(rad)\n', (4945, 4950), True, 'import numpy as np\n'), ((4285, 4324), 'numpy.exp', 'np.exp', (['(1e-05 * (-rp + radius + 100000))'], {}), '(1e-05 * (-rp + radius + 100000))\n', (4291, 4324), True, 'import numpy as np\n'), ((4334, 4372), 'numpy.exp', 'np.exp', (['(1e-05 * (rp - radius - 100000))'], {}), '(1e-05 * (rp - radius - 100000))\n', (4340, 4372), True, 'import numpy as np\n'), ((392, 401), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (398, 401), True, 'import numpy as np\n'), ((490, 499), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (496, 499), True, 'import numpy as np\n'), ((577, 586), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (583, 586), True, 'import numpy as np\n'), ((670, 679), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (676, 679), True, 'import numpy as np\n'), ((763, 772), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (769, 772), True, 'import numpy as np\n')]
import os import re import cv2 import numpy as np import pandas as pd from Scripts.Experiments import RESULTS # ------------------------------------------------------------------------------------------------------------------ # # -------------------------------------------------- Restructure UNBC Data ----------------------------------------- # def get_user_number(folder_name): regex = r"\d+(?=-)" matches = re.findall(regex, folder_name) try: return int(matches[0]) except: return "" def get_frame_number(filename): regex = r"\d+(?=.png)" matches = re.findall(regex, filename) try: return int(matches[0]) except: return "" def get_session_id(filename): regex = r"\S+(?=\d{3}.png)" matches = re.findall(regex, filename) try: return matches[0] except: return "" def get_user_number_from_filename(filename): regex = r"\d{3}(?=t)" matches = re.findall(regex, filename) try: return int(matches[0]) except: return "" def read_pain_score_from_file(filepath): try: h = open(filepath, 'r') content = h.readlines() for line in content: return int(float(line.rstrip('\n'))) except: return "" def get_filename_without_extension(filename): regex = r"\S+\d{3}" matches = re.findall(regex, filename) try: return matches[0] except: return "" # ------------------------------------------------------------------------------------------------------------------ # # -------------------------------------------------- Load Pain Data ------------------------------------------------ # def load_and_prepare_pain_data(path, person, pain, model_type): """ Utility function loading pain image data into memory, and preparing the labels for training. Note, this function expects the image files to have the following naming convention: "43_0_0_0_2_original_straight.jpg", to be converted into the following label array: [person, session, culture, frame, pain_level, transformation_1, transformation_2] :param path: string, root path to all images to be loaded :param person: int, index where 'person' appears in the file name converted to an array. :param pain: int, index where 'pain_level' appears in the file name converted to an array. :param model_type: string, specifying the model_type (CNN, or ResNet) :return: data: 4D numpy array, images as numpy array in shape (N, 215, 215, 1) labels_binary: 2D numpy array, one-hot encoded labels [no pain, pain] (N, 2) train_labels_people: 2D numpy array, only including the "person" label [person] (N, 1) labels: 2D numpy array, all labels as described above (N, 7) """ color = 0 if model_type == 'CNN' else 1 data, labels = load_pain_data(path, color=color) labels_ord = labels[:, pain].astype(np.int) labels_binary = reduce_pain_label_categories(labels_ord, max_pain=1) train_labels_people = labels[:, person].astype(np.int) return data, labels_binary, train_labels_people, labels def load_pain_data(train_path, test_path=None, label_type=None, color=0): """ Load function, loading pain dataset into numpy arrays with labels. Either just loads train data, or train and test. :param color: int, if 0 then greyscale, if 1 then color :param train_path: string, root directory :param test_path: string, optional, root test directory :param label_type: string, if not None, only a specific label will be attached to each image :return: """ train_data, train_labels = load_image_data(train_path, color, label_type) print("Normalization") np.divide(train_data, 255.0, out=train_data, dtype=np.float32) if test_path: test_data, test_labels = load_image_data(test_path, label_type) print("Normalization") test_data = np.divide(test_data, 255.0, out=test_data, dtype=np.float32) return train_data, train_labels, test_data, test_labels return train_data, train_labels def load_image_data(path, color=0, label_type=None): """ Utility function, loading all images in a directory and its sub-directories into a numpy array, labeled :param color: int, if 0 then greyscale, if 1 then color :param path: string, root directory or list of strings (image paths) :param label_type: string, if not None, only a specific label will be attached to each image :return: data, labels: tuple of numpy arrays, holding images and labels """ if type(path) is str: img_paths = get_image_paths(path) else: img_paths = path np.random.shuffle(img_paths) data = [] for idx, path in enumerate(img_paths): img = np.expand_dims(cv2.imread(path, color), -1) if color == 0 else cv2.imread(path, color) data.append(img) if not idx % 1000: print("{} images processed".format(idx)) data = np.array(data, dtype=np.float32) labels = np.array(get_labels(img_paths, label_type=label_type)) return data, labels def get_image_paths(root_path, ext='.jpg'): """ Utility function returning all image paths in a directory adn its sub-directories. :param root_path: path from which to start the recursive search :param ext: file extension to look for :return: image_paths: list of paths """ image_paths = [] for dirpath, dirnames, filenames in os.walk(root_path): for file in filenames: f_name, f_ext = os.path.splitext(file) if f_ext == ext: image_paths.append(os.path.join(dirpath, file)) return image_paths def get_labels(image_paths, label_type=None, ext='.png'): """ Utility function turning image paths into a 2D list of labels :param image_paths: list of image paths :param label_type: string, if not None, only a specific label per image will be returned :param ext: string, file extension :return: labels 2D list of labels """ label_types = { 'person': 0, 'session': 1, 'culture': 2, 'frame': 3, 'pain': 4, 'augmented': 5, } labels = [] for path in image_paths: filename = os.path.basename(path) filename, extension = os.path.splitext(filename) if extension == ext: img_labels = filename.split("_") if label_type is None: label = img_labels else: label = int(img_labels[label_types[label_type]]) labels.append(label) return labels def reduce_pain_label_categories(labels, max_pain): """ Utility function reducing ordinal labels to a specified number of labels, e.g. [0,1] binary :param labels: numpy array :param max_pain: int, max label, e.g. if 1 then labels will reduce to [0,1] :return: labels_reduced numpy array """ return np.minimum(labels, max_pain) def create_pain_df(path, pain_gap=(), binarize=True): """ Generate a Pandas DataFrame object that contains all img_paths excluding a specified pain_gap in a given folder path :param path: string, super parent folder path :param pain_gap: tuple of int's, specifying which pain classes to exclude from training :param binarize: bool, if the label "pain" is to be binarized :return: """ # Get image paths and convert file labels to numpy array img_paths = np.array(get_image_paths(path, ext=".png")) labels = np.array(get_labels(img_paths)) # Create dataframe df = pd.DataFrame(labels, columns=['Person', 'Session', 'Culture', 'Frame', 'Pain', 'Trans_1', 'Trans_2']) df[['Person', 'Session', 'Culture', 'Frame', 'Pain']] = df[ ['Person', 'Session', 'Culture', 'Frame', 'Pain']].astype(int) df['img_path'] = img_paths df[['Trans_1', 'Trans_2', 'img_path']] = df[['Trans_1', 'Trans_2', 'img_path']].astype(str) df = df.sort_values(['Person', 'Session', 'Frame', 'Trans_1', 'Trans_2'], ascending=[True, True, True, False, False]).reset_index(drop=True) # Create a unique ID for each entry df['temp_id'] = df['Person'].astype(str) + df['Session'].astype(str) + df['Frame'].astype(str) # Exclude elements in the pain gap df = df[~df['Pain'].isin(pain_gap)] # Binarize Pain label if binarize: df['Pain'] = np.minimum(df['Pain'], 1) return df # ------------------------------------------------ End Load Pain Data ---------------------------------------------- # # ------------------------------------------------------------------------------------------------------------------ # # ------------------------------------------------------------------------------------------------------------------ # # ------------------------------------------------- Split Functions ------------------------------------------------ # def split_data_into_clients_dict(people, *args): """ Utility function, splitting data into clients. :param people: numpy array, contains image clients (set_size, 1) :param args: tuple or list, tuple or list of numpy arrays of the same length as "people" :return: array of dictionaries. each dictionary represents one input array provided by *args, split into a dictionary of clients, where the key is the client number and the value is the data of the input array associated with that client """ array = [] for arg in args: dic = {} for key, value in zip(people, arg): # noinspection PyTypeChecker dic.setdefault(key, []).append(value) for key in dic.keys(): dic[key] = np.array(dic[key]) if len(args) == 1: return dic else: array.append(dic) return tuple(array) def split_data_into_shards(split=None, cumulative=True, array=None): """ Utility function, splitting data into specified subsets of shards. Scales the split array to 100%. :param array: list of arrays to be split into shards :param split: list of percentage split points, e.g. [0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6] :param cumulative: bool, checks if concatenation should be cumulative, e.g. [0], [0, 1] or not [0], [1] :return: list of elements, where each element represents one shard """ split = [int(x / max(split) * len(array[0])) for x in split] array = [np.array_split(elem, split) for elem in array] if cumulative: array = [cumconc(elem) for elem in array] return array def split_data_into_labels(label, all_labels, cumulative, *args): """ Utility function splitting arguments provided in *args into the label provided. :param label: int, labels can be 0-6 each for one index of [person, session, culture, frame, pain, trans_1, trans_2] :param all_labels: 2D numpy array, where each row is of the format above :param cumulative: bool, checks if concatenation should be cumulative, e.g. [0], [0, 1] or not [0], [1] :param args: list, arrays to be split into the label provided :return: tuple of arrays split into the label provided """ arg_array = [np.array([all_labels[all_labels[:, label] == k] for k in np.unique(all_labels[:, label])])] arrays = [np.array([arg[all_labels[:, label] == k] for k in np.unique(all_labels[:, label])]) for arg in args] arg_array.extend(arrays) if cumulative: arg_array = [cumconc(elem) for elem in arg_array] return tuple(arg_array) def train_test_split(test_ratio, *args): """ Ordinary train/test split. :param test_ratio: float, split value e.g. 0.8 means 80% train and 20% test data :param args: tuple of arrays to be split :return: list of split arrays """ split = int(len(args[0]) * test_ratio) return [(elem[:split], elem[split:]) for elem in args] def cumconc(array): """ Utility function creating a cumulatively split view on a split numpy array, e.g. [[0], [1]] to [[0] , [0, 1]] :param array: numpy array :return: array cumulative numpy array """ total = np.concatenate(array) # noinspection PyTypeChecker return np.array([*map(total.__getitem__, map(slice, np.fromiter(map(len, array), int, len(array)).cumsum()))]) # ----------------------------------------------- End Split Functions ---------------------------------------------- # # ------------------------------------------------------------------------------------------------------------------ # # ------------------------------------------------------------------------------------------------------------------ # # ----------------------------------------- Jupyter notebook helper functions -------------------------------------- # def mirror_folder_structure(input_path, output_path): """ Utility function mirroring the folder structure in one folder into another folder. :param input_path: string, input path :param output_path: string, output path :return: """ for dir_path, dir_names, filenames in os.walk(input_path): structure = os.path.join(output_path, dir_path[len(input_path) + 1:]) if not os.path.isdir(structure): os.mkdir(structure) def reset_to_raw(root_path, dest_dir='raw', ext='.jpg'): """ Utility function taking all files of a given type in a specified root folder and moving them to a specified destination folder. :param root_path: string, root_path :param dest_dir: string, destination folder name :param ext: string, file extension to look for :return: """ if not os.path.isdir(os.path.join(root_path, dest_dir)): os.mkdir(os.path.join(root_path, dest_dir)) for dir_path, dir_names, filenames in os.walk(root_path): for file in filenames: if os.path.splitext(file)[1] == ext: src = os.path.join(dir_path, file) dest = os.path.join(root_path, dest_dir, file) os.rename(src, dest) def delete_empty_folders(root_path): """ Utility function deleting all empty folder in a directory and its subdirectories. :param root_path: string, root path :return: """ for dir_path, dir_names, filenames in os.walk(root_path): if not dir_names and not filenames: os.rmdir(dir_path) def create_pivot(path, index, columns, values, pain_level=0, pain_gap=()): """ Create a pivot table showing the test subjects and their pain level per session. :param path: string, file paths, where the images lie :param index: index of the pivot, can be 'Session' or 'Person' :param columns: columns of the pivot, can be 'Session' or 'Person' :param values: values of the pivot, can be 'Session' or 'Person', should equal index :param pain_level: value from where the binary classifier should consider "pain" :param pain_gap: tuple of int's, specifying which pain classes to exclude from training :return: Pandas DataFrame, pivot table """ group_2 = get_image_paths(path) labels = np.array(get_labels(group_2)) cols = ['Person', 'Session', 'Culture', 'Frame', 'Pain', 'Trans_1', 'Trans_2'] df = pd.DataFrame(labels, columns=cols) df[['Person', 'Session', 'Culture', 'Frame', 'Pain']] = df[ ['Person', 'Session', 'Culture', 'Frame', 'Pain']].astype(int) df = df[~df['Pain'].isin(pain_gap)] pivot = ~df[['Person', 'Session']].drop_duplicates().pivot(index=index, columns=columns, values=values).isnull() * 1 pivot['# of ' + columns + 's'] = pivot.sum(1) pivot = pivot.sort_values('# of ' + columns + 's', ascending=False) pivot['Pain'] = 0 pivot['No Pain'] = 0 for person, df_person in df.groupby(index): pivot.at[person, 'No Pain'] = sum(np.array(df_person['Pain'] <= pain_level)) pivot.at[person, 'Pain'] = sum(np.array(df_person['Pain'] > pain_level)) for col in pivot.columns: if type(col) is int: pivot.at[person, col] = sum(np.array(df_person[df_person[columns] == col]['Pain'] > pain_level)) if columns is 'Session': for col in reversed(pivot.columns): if type(col) is int: pivot.rename(columns={col: col}, inplace=True) if index is 'Session': for idx in reversed(pivot.index): pivot.rename(index={idx: idx}, inplace=True) pivot = pivot.append(pivot.sum(0).rename("Total")) pivot['Pain %'] = round(pivot['Pain'] / (pivot['Pain'] + pivot['No Pain']), 2) pivot[pivot == 0] = '' return pivot # --------------------------------------- End Jupyter notebook helper functions ------------------------------------ # # ------------------------------------------------------------------------------------------------------------------ # # ------------------------------------------------------------------------------------------------------------------ # # --------------------------------------------- Data Balancing algorithms ------------------------------------------ # def sample_df(df, threshold): """ Utility function that samples rows from a DataFrame until a provided threshold is reached. :param df: DataFrame with columns ['Person', 'Session', 'Culture', 'Frame', 'Pain', 'Trans_1', 'Trans_2', 'temp_id'] :param threshold: int, threshold that should be sampled to :return: Pandas DataFrame """ if len(df) > threshold: return df.sample(threshold, replace=False) else: return pd.concat((df, df.sample(threshold - len(df), replace=True))) def balance_session(df, threshold): """ Utility function balancing a session so taht equal number of positive and negative examples are included. Only includes a client if there are both positive and negative examples for that client :param df: DataFrame with columns ['Person', 'Session', 'Culture', 'Frame', 'Pain', 'Trans_1', 'Trans_2', 'temp_id'] :param threshold: int, threshold that should be sampled to :return: Resampled Pandas DataFrame or empty DataFrame """ df_train = [] for person, df_person in df.groupby('Person'): df_pain = df_person[df_person['Pain'] == 1] df_no_pain = df_person[df_person['Pain'] == 0] if len(df_pain) > 0 and len(df_no_pain): df_pain = sample_df(df_pain, threshold) df_no_pain = sample_df(df_no_pain, threshold) df_train.append(pd.concat((df_pain, df_no_pain))) return pd.concat(df_train) if len(df_train) > 0 else pd.DataFrame(columns=df.columns) def balance_data(df, threshold): """ A moving window over the pain data, taking preference over more recent additions to the data set, resampling so that an equal number of positive and negative examples is sampled. :param df: DataFrame with columns ['Person', 'Session', 'Culture', 'Frame', 'Pain', 'Trans_1', 'Trans_2', 'temp_id'] :param threshold: int, threshold that should be sampled to :return: Resampled Pandas DataFrame """ df_train = [] for person, df_person in df.groupby('Person'): df_temp_pain = [] df_temp_no_pain = [] for sess, df_sess in reversed(tuple(df_person.groupby('Session'))): df_temp_pain.append(df_sess[df_sess['Pain'] == 1]) df_temp_no_pain.append(df_sess[df_sess['Pain'] == 0]) if len(pd.concat(df_temp_pain)) > threshold and len(pd.concat(df_temp_no_pain)) > threshold: break df_temp_pain.extend(df_temp_no_pain) df_temp = pd.concat(df_temp_pain) df_train.append(df_temp) df_train = pd.concat(df_train) return balance_session(df_train, threshold) def split_and_balance_df(df, ratio, balance_test=False): """ Utility function splitting a data frame into train and test file paths. The train data is balanced, while balancing the test data is optional. If ratio == 1, serves to just balance a data frame, without splitting the data. :param df: Pandas DataFrame, cols: [Person, Session, Culture, Frame, Pain, Trans_1, Trans_2, img_path] :param ratio: float, ratio of train data :param balance_test: bool, whether to balance the test data :return: Tuple of two Pandas DataFrames, one with train img_paths, one with test img_paths """ # Split Original data into ratio (for each person) df_original = df[(df['Trans_1'] == 'original') & (df['Trans_2'] == 'straight')] df_train = df_original.sample(frac=1).groupby('Person', group_keys=False).apply(lambda x: x.sample(frac=ratio)) df_test = df_original.drop(df_train.index) # Balance the training data set (1. get all permutations, 2. get all pain instances of the permutations, # 3. down-sample no-pain to pain number df_train = df[df['temp_id'].isin(df_train['temp_id'])] df_pain = df_train[df_train['Pain'] > 0] df_train = pd.concat((df_pain, df_train[df_train['Pain'] == 0].sample(len(df_pain))), ignore_index=True) if balance_test: df_test = df[df['temp_id'].isin(df_test['temp_id'])] df_pain = df_test[df_test['Pain'] > 0] df_test = pd.concat((df_pain, df_test[df_test['Pain'] == 0].sample(len(df_pain))), ignore_index=True) # Return shuffled dfs return df_train.sample(frac=1), df_test.sample(frac=1) # ------------------------------------------- End Data Balancing algorithms ---------------------------------------- # # ------------------------------------------------------------------------------------------------------------------ # def move_files(target_folder, seed): """ Utility function moving result files into the correct folder. :param target_folder: string, folder where files should be moved to :param seed: int, seed that was run for the experiments, relevant for file renaming :return: """ # Create folder structure target_f_path = os.path.join(RESULTS, 'Thesis', target_folder) if not os.path.isdir(target_f_path): os.mkdir(target_f_path) if not os.path.isdir(os.path.join(target_f_path, 'Plotting')): os.mkdir(os.path.join(target_f_path, 'Plotting')) # Move files and folders elements = [elem for elem in os.listdir(RESULTS) if str(seed) in elem] for elem in elements: f_path = os.path.join(RESULTS, elem) os.rename(f_path, os.path.join(target_f_path, elem)) # Delete Seed number from file and folder names elements = [elem for elem in os.listdir(target_f_path) if "_" + str(seed) in elem] for elem in elements: f_path = os.path.join(target_f_path, elem) new = elem.replace("_" + str(seed), '') os.rename(f_path, os.path.join(target_f_path, new))
[ "numpy.array_split", "numpy.array", "numpy.divide", "os.walk", "os.listdir", "os.path.isdir", "os.mkdir", "numpy.concatenate", "pandas.DataFrame", "os.rename", "os.path.splitext", "re.findall", "cv2.imread", "numpy.minimum", "numpy.unique", "os.path.join", "os.rmdir", "os.path.base...
[((427, 457), 're.findall', 're.findall', (['regex', 'folder_name'], {}), '(regex, folder_name)\n', (437, 457), False, 'import re\n'), ((605, 632), 're.findall', 're.findall', (['regex', 'filename'], {}), '(regex, filename)\n', (615, 632), False, 'import re\n'), ((783, 810), 're.findall', 're.findall', (['regex', 'filename'], {}), '(regex, filename)\n', (793, 810), False, 'import re\n'), ((965, 992), 're.findall', 're.findall', (['regex', 'filename'], {}), '(regex, filename)\n', (975, 992), False, 'import re\n'), ((1375, 1402), 're.findall', 're.findall', (['regex', 'filename'], {}), '(regex, filename)\n', (1385, 1402), False, 'import re\n'), ((3923, 3985), 'numpy.divide', 'np.divide', (['train_data', '(255.0)'], {'out': 'train_data', 'dtype': 'np.float32'}), '(train_data, 255.0, out=train_data, dtype=np.float32)\n', (3932, 3985), True, 'import numpy as np\n'), ((4938, 4966), 'numpy.random.shuffle', 'np.random.shuffle', (['img_paths'], {}), '(img_paths)\n', (4955, 4966), True, 'import numpy as np\n'), ((5241, 5273), 'numpy.array', 'np.array', (['data'], {'dtype': 'np.float32'}), '(data, dtype=np.float32)\n', (5249, 5273), True, 'import numpy as np\n'), ((5797, 5815), 'os.walk', 'os.walk', (['root_path'], {}), '(root_path)\n', (5804, 5815), False, 'import os\n'), ((7411, 7439), 'numpy.minimum', 'np.minimum', (['labels', 'max_pain'], {}), '(labels, max_pain)\n', (7421, 7439), True, 'import numpy as np\n'), ((8092, 8197), 'pandas.DataFrame', 'pd.DataFrame', (['labels'], {'columns': "['Person', 'Session', 'Culture', 'Frame', 'Pain', 'Trans_1', 'Trans_2']"}), "(labels, columns=['Person', 'Session', 'Culture', 'Frame',\n 'Pain', 'Trans_1', 'Trans_2'])\n", (8104, 8197), True, 'import pandas as pd\n'), ((12880, 12901), 'numpy.concatenate', 'np.concatenate', (['array'], {}), '(array)\n', (12894, 12901), True, 'import numpy as np\n'), ((13857, 13876), 'os.walk', 'os.walk', (['input_path'], {}), '(input_path)\n', (13864, 13876), False, 'import os\n'), ((14590, 14608), 'os.walk', 'os.walk', (['root_path'], {}), '(root_path)\n', (14597, 14608), False, 'import os\n'), ((15088, 15106), 'os.walk', 'os.walk', (['root_path'], {}), '(root_path)\n', (15095, 15106), False, 'import os\n'), ((16121, 16155), 'pandas.DataFrame', 'pd.DataFrame', (['labels'], {'columns': 'cols'}), '(labels, columns=cols)\n', (16133, 16155), True, 'import pandas as pd\n'), ((20752, 20771), 'pandas.concat', 'pd.concat', (['df_train'], {}), '(df_train)\n', (20761, 20771), True, 'import pandas as pd\n'), ((23152, 23198), 'os.path.join', 'os.path.join', (['RESULTS', '"""Thesis"""', 'target_folder'], {}), "(RESULTS, 'Thesis', target_folder)\n", (23164, 23198), False, 'import os\n'), ((4127, 4187), 'numpy.divide', 'np.divide', (['test_data', '(255.0)'], {'out': 'test_data', 'dtype': 'np.float32'}), '(test_data, 255.0, out=test_data, dtype=np.float32)\n', (4136, 4187), True, 'import numpy as np\n'), ((6682, 6704), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (6698, 6704), False, 'import os\n'), ((6735, 6761), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (6751, 6761), False, 'import os\n'), ((8910, 8935), 'numpy.minimum', 'np.minimum', (["df['Pain']", '(1)'], {}), "(df['Pain'], 1)\n", (8920, 8935), True, 'import numpy as np\n'), ((11034, 11061), 'numpy.array_split', 'np.array_split', (['elem', 'split'], {}), '(elem, split)\n', (11048, 11061), True, 'import numpy as np\n'), ((19552, 19571), 'pandas.concat', 'pd.concat', (['df_train'], {}), '(df_train)\n', (19561, 19571), True, 'import pandas as pd\n'), ((19598, 19630), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'df.columns'}), '(columns=df.columns)\n', (19610, 19630), True, 'import pandas as pd\n'), ((20680, 20703), 'pandas.concat', 'pd.concat', (['df_temp_pain'], {}), '(df_temp_pain)\n', (20689, 20703), True, 'import pandas as pd\n'), ((23210, 23238), 'os.path.isdir', 'os.path.isdir', (['target_f_path'], {}), '(target_f_path)\n', (23223, 23238), False, 'import os\n'), ((23248, 23271), 'os.mkdir', 'os.mkdir', (['target_f_path'], {}), '(target_f_path)\n', (23256, 23271), False, 'import os\n'), ((23546, 23573), 'os.path.join', 'os.path.join', (['RESULTS', 'elem'], {}), '(RESULTS, elem)\n', (23558, 23573), False, 'import os\n'), ((23818, 23851), 'os.path.join', 'os.path.join', (['target_f_path', 'elem'], {}), '(target_f_path, elem)\n', (23830, 23851), False, 'import os\n'), ((5101, 5124), 'cv2.imread', 'cv2.imread', (['path', 'color'], {}), '(path, color)\n', (5111, 5124), False, 'import cv2\n'), ((5876, 5898), 'os.path.splitext', 'os.path.splitext', (['file'], {}), '(file)\n', (5892, 5898), False, 'import os\n'), ((10247, 10265), 'numpy.array', 'np.array', (['dic[key]'], {}), '(dic[key])\n', (10255, 10265), True, 'import numpy as np\n'), ((13971, 13995), 'os.path.isdir', 'os.path.isdir', (['structure'], {}), '(structure)\n', (13984, 13995), False, 'import os\n'), ((14009, 14028), 'os.mkdir', 'os.mkdir', (['structure'], {}), '(structure)\n', (14017, 14028), False, 'import os\n'), ((14460, 14493), 'os.path.join', 'os.path.join', (['root_path', 'dest_dir'], {}), '(root_path, dest_dir)\n', (14472, 14493), False, 'import os\n'), ((14513, 14546), 'os.path.join', 'os.path.join', (['root_path', 'dest_dir'], {}), '(root_path, dest_dir)\n', (14525, 14546), False, 'import os\n'), ((15164, 15182), 'os.rmdir', 'os.rmdir', (['dir_path'], {}), '(dir_path)\n', (15172, 15182), False, 'import os\n'), ((16714, 16755), 'numpy.array', 'np.array', (["(df_person['Pain'] <= pain_level)"], {}), "(df_person['Pain'] <= pain_level)\n", (16722, 16755), True, 'import numpy as np\n'), ((16796, 16836), 'numpy.array', 'np.array', (["(df_person['Pain'] > pain_level)"], {}), "(df_person['Pain'] > pain_level)\n", (16804, 16836), True, 'import numpy as np\n'), ((23298, 23337), 'os.path.join', 'os.path.join', (['target_f_path', '"""Plotting"""'], {}), "(target_f_path, 'Plotting')\n", (23310, 23337), False, 'import os\n'), ((23357, 23396), 'os.path.join', 'os.path.join', (['target_f_path', '"""Plotting"""'], {}), "(target_f_path, 'Plotting')\n", (23369, 23396), False, 'import os\n'), ((23461, 23480), 'os.listdir', 'os.listdir', (['RESULTS'], {}), '(RESULTS)\n', (23471, 23480), False, 'import os\n'), ((23600, 23633), 'os.path.join', 'os.path.join', (['target_f_path', 'elem'], {}), '(target_f_path, elem)\n', (23612, 23633), False, 'import os\n'), ((23721, 23746), 'os.listdir', 'os.listdir', (['target_f_path'], {}), '(target_f_path)\n', (23731, 23746), False, 'import os\n'), ((23926, 23958), 'os.path.join', 'os.path.join', (['target_f_path', 'new'], {}), '(target_f_path, new)\n', (23938, 23958), False, 'import os\n'), ((5053, 5076), 'cv2.imread', 'cv2.imread', (['path', 'color'], {}), '(path, color)\n', (5063, 5076), False, 'import cv2\n'), ((14712, 14740), 'os.path.join', 'os.path.join', (['dir_path', 'file'], {}), '(dir_path, file)\n', (14724, 14740), False, 'import os\n'), ((14764, 14803), 'os.path.join', 'os.path.join', (['root_path', 'dest_dir', 'file'], {}), '(root_path, dest_dir, file)\n', (14776, 14803), False, 'import os\n'), ((14820, 14840), 'os.rename', 'os.rename', (['src', 'dest'], {}), '(src, dest)\n', (14829, 14840), False, 'import os\n'), ((19507, 19539), 'pandas.concat', 'pd.concat', (['(df_pain, df_no_pain)'], {}), '((df_pain, df_no_pain))\n', (19516, 19539), True, 'import pandas as pd\n'), ((5963, 5990), 'os.path.join', 'os.path.join', (['dirpath', 'file'], {}), '(dirpath, file)\n', (5975, 5990), False, 'import os\n'), ((11929, 11960), 'numpy.unique', 'np.unique', (['all_labels[:, label]'], {}), '(all_labels[:, label])\n', (11938, 11960), True, 'import numpy as np\n'), ((12028, 12059), 'numpy.unique', 'np.unique', (['all_labels[:, label]'], {}), '(all_labels[:, label])\n', (12037, 12059), True, 'import numpy as np\n'), ((14656, 14678), 'os.path.splitext', 'os.path.splitext', (['file'], {}), '(file)\n', (14672, 14678), False, 'import os\n'), ((16949, 17016), 'numpy.array', 'np.array', (["(df_person[df_person[columns] == col]['Pain'] > pain_level)"], {}), "(df_person[df_person[columns] == col]['Pain'] > pain_level)\n", (16957, 17016), True, 'import numpy as np\n'), ((20509, 20532), 'pandas.concat', 'pd.concat', (['df_temp_pain'], {}), '(df_temp_pain)\n', (20518, 20532), True, 'import pandas as pd\n'), ((20554, 20580), 'pandas.concat', 'pd.concat', (['df_temp_no_pain'], {}), '(df_temp_no_pain)\n', (20563, 20580), True, 'import pandas as pd\n')]
"""Visualization for sequential tracks.""" import numpy as np import open3d as o3d from ..data.loadmodels import track_palette def make_geometries_from_dict(tracks, old_track_geometries=None, palette=track_palette): track_line_sets = {} for track_id, points in tracks.items(): points_pos = np.reshape([point[0] for point in points], (-1, 3)) if points_pos.shape[0] > 1: line_set = o3d.geometry.LineSet() line_set.points = o3d.utility.Vector3dVector(points_pos) line_indices = np.column_stack((range(0, len(points) - 1), range(1, len(points)))) line_set.lines = o3d.utility.Vector2iVector(np.asarray(line_indices)) if old_track_geometries: if track_id in old_track_geometries: old_color = np.asarray(old_track_geometries[track_id].colors)[0,:] line_set.paint_uniform_color(old_color) else: line_set.paint_uniform_color(np.asarray(next(palette))) else: line_set.paint_uniform_color(np.asarray(next(palette))) track_line_sets[track_id] = line_set return track_line_sets def init_tracks(visualizer, tracks, palette=track_palette): """Add detections in proper form to open3d visualizer.""" tracks_geometries = make_geometries_from_dict(tracks, palette=palette) for _, geometry in tracks_geometries.items(): visualizer.add_geometry(geometry) return tracks_geometries def update_tracks(visualizer, old_geometries, new_tracks, palette=track_palette): """Update detections that has a previous geometry object.""" for _, geometry in old_geometries.items(): visualizer.remove_geometry(geometry, False) new_geometries = make_geometries_from_dict(new_tracks, old_geometries, palette=palette) for _, geometry in new_geometries.items(): visualizer.add_geometry(geometry, False) return new_geometries
[ "numpy.asarray", "numpy.reshape", "open3d.geometry.LineSet", "open3d.utility.Vector3dVector" ]
[((340, 391), 'numpy.reshape', 'np.reshape', (['[point[0] for point in points]', '(-1, 3)'], {}), '([point[0] for point in points], (-1, 3))\n', (350, 391), True, 'import numpy as np\n'), ((452, 474), 'open3d.geometry.LineSet', 'o3d.geometry.LineSet', ([], {}), '()\n', (472, 474), True, 'import open3d as o3d\n'), ((506, 544), 'open3d.utility.Vector3dVector', 'o3d.utility.Vector3dVector', (['points_pos'], {}), '(points_pos)\n', (532, 544), True, 'import open3d as o3d\n'), ((741, 765), 'numpy.asarray', 'np.asarray', (['line_indices'], {}), '(line_indices)\n', (751, 765), True, 'import numpy as np\n'), ((890, 939), 'numpy.asarray', 'np.asarray', (['old_track_geometries[track_id].colors'], {}), '(old_track_geometries[track_id].colors)\n', (900, 939), True, 'import numpy as np\n')]
import numpy as np import pandas as pd from pyopenms import FeatureMap, FeatureXMLFile def extractNamesAndIntensities(feature_dir, sample_names, database): """ This function takes .featureXML files, the output of SmartPeak pre-processing, and extracts the metabolite's reference and its measured intensity. Furthermore, the peptide references are compared with a database that has also been used for SmartPeak processing. Only metabolites that appear in the database are being used. Their formula is added to the output dataframe. The names of the files that should be processed are added via a SmartPeak sequence file Parameters ---------- feature_dir : path the path to the directory holding the .featureXML files sample_names : string the extracted information from a sequence file database : pandas.DataFrame the organism specific database with the metabolite mapping Returns ------- extracted_data_all : pandas.DataFrame a dataframe containing the extracted information, the 4 columns include the sample name, the peptide reference for the metabolites, their corresponding formulas and the measured intensity """ metabolites_unique = database[0].unique() extracted_data_dict = {} cnt = 0 for name in sample_names: features = FeatureMap() FeatureXMLFile().load( feature_dir + "/" + name + ".featureXML", features ) for f in features: try: peptideRef = f.getMetaValue("PeptideRef").decode("utf-8") except AttributeError: peptideRef = f.getMetaValue("PeptideRef") if peptideRef in metabolites_unique: formula = database[database[0] == peptideRef][1] extracted_data_dict[cnt] = { "sample_group_name": name, "Metabolite": peptideRef, "Formula": list(formula)[0], "Intensity": f.getMetaValue("peak_apex_int"), } cnt = cnt + 1 extracted_data_all = pd.DataFrame.from_dict(extracted_data_dict, "index") return extracted_data_all def calculateMeanVarRSD( extracted_data_all, sample_name_2_replicate_groups, min_reps=3 ): """ The output of the extractNamesAndIntensities() function (or its output after normalization) is processed here to produce a dataframe that includes some basic statistics Parameters ---------- extracted_data_all : pandas.DataFrame the output of the extractNamesAndIntensities() function (or its output after normalization) sample_name_2_replicate_groups : pandas.DataFrame the extracted information from a sequence file reduced to one entry per "sample_group_name" min_reps : int the number of replicates for each sample, corresponds to the file names (replicates should end with the replicate number) Returns ------- stats_all_df : pandas.DataFrame a dataframe with some base statistics. The 6 columns include the sample group name, the metabolite reference, its formula and the mean, variance and relative stdev. """ stats_all_dict = {} cnt = 0 for replicate_group in sample_name_2_replicate_groups[ "replicate_group_name" ].unique(): list_of_compound_intensities = pd.DataFrame( columns=["Metabolite", "Formula", "Intensities"] ) for sample_name_index, sample_name in sample_name_2_replicate_groups[ sample_name_2_replicate_groups["replicate_group_name"] == replicate_group ].iterrows(): for met_index, met in extracted_data_all[ extracted_data_all["sample_group_name"] == sample_name["sample_group_name"] ].iterrows(): list_of_compound_intensities = ( list_of_compound_intensities.append( pd.DataFrame( [ { "Metabolite": met["Metabolite"], "Formula": met["Formula"], "Intensities": met["Intensity"], } ] ), ignore_index=True, ) ) for met_name in list_of_compound_intensities["Metabolite"].unique(): intensities = list_of_compound_intensities[ list_of_compound_intensities["Metabolite"] == met_name ] if len(intensities) >= min_reps: mean = np.mean(intensities["Intensities"]) var = np.var(intensities["Intensities"]) rsd = np.sqrt(var) / mean stats_all_dict[cnt] = { "replicate_group_name": replicate_group, "Metabolite": met_name, "Formula": list( list_of_compound_intensities[ list_of_compound_intensities["Metabolite"] == met_name ]["Formula"] )[0], "Mean": mean, "Variance": var, "RSD": rsd, } cnt = cnt + 1 stats_all_df = pd.DataFrame.from_dict(stats_all_dict, "index") return stats_all_df
[ "pyopenms.FeatureMap", "numpy.mean", "numpy.sqrt", "pyopenms.FeatureXMLFile", "pandas.DataFrame.from_dict", "pandas.DataFrame", "numpy.var" ]
[((2150, 2202), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['extracted_data_dict', '"""index"""'], {}), "(extracted_data_dict, 'index')\n", (2172, 2202), True, 'import pandas as pd\n'), ((5513, 5560), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['stats_all_dict', '"""index"""'], {}), "(stats_all_dict, 'index')\n", (5535, 5560), True, 'import pandas as pd\n'), ((1382, 1394), 'pyopenms.FeatureMap', 'FeatureMap', ([], {}), '()\n', (1392, 1394), False, 'from pyopenms import FeatureMap, FeatureXMLFile\n'), ((3458, 3520), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Metabolite', 'Formula', 'Intensities']"}), "(columns=['Metabolite', 'Formula', 'Intensities'])\n", (3470, 3520), True, 'import pandas as pd\n'), ((1403, 1419), 'pyopenms.FeatureXMLFile', 'FeatureXMLFile', ([], {}), '()\n', (1417, 1419), False, 'from pyopenms import FeatureMap, FeatureXMLFile\n'), ((4798, 4833), 'numpy.mean', 'np.mean', (["intensities['Intensities']"], {}), "(intensities['Intensities'])\n", (4805, 4833), True, 'import numpy as np\n'), ((4856, 4890), 'numpy.var', 'np.var', (["intensities['Intensities']"], {}), "(intensities['Intensities'])\n", (4862, 4890), True, 'import numpy as np\n'), ((4059, 4172), 'pandas.DataFrame', 'pd.DataFrame', (["[{'Metabolite': met['Metabolite'], 'Formula': met['Formula'], 'Intensities':\n met['Intensity']}]"], {}), "([{'Metabolite': met['Metabolite'], 'Formula': met['Formula'],\n 'Intensities': met['Intensity']}])\n", (4071, 4172), True, 'import pandas as pd\n'), ((4913, 4925), 'numpy.sqrt', 'np.sqrt', (['var'], {}), '(var)\n', (4920, 4925), True, 'import numpy as np\n')]
import matplotlib.animation as animation import matplotlib.pyplot as plt import numpy as np import os import sys def save_ani(episode, reward, frames, fps=50, skip_frames=4, out_path='./animations/', mode='train'): if not os.path.exists(out_path): os.makedirs(out_path) fig = plt.figure() plt.title(f'{mode} episode: {episode}, reward: {reward}') plt.axis('off') im = plt.imshow(frames[0], animated=True) def update_fig(frame, *args): im.set_array(frame) return im, ani = animation.FuncAnimation(fig, update_fig, frames=frames[::skip_frames+1]) ani.save(f'{out_path}{mode}_episode_{episode}_reward_{reward}.gif', writer='imagemagick', fps=fps) def save_train_ani(dir_name='./train_stats'): filenames = os.listdir(dir_name) print(filenames) for filename in filenames: frames = np.load(f'./train_stats/{filename}') episode = int(filename.split('_')[2].split('.')[0]) reward = int(filename.split('_')[4].split('.')[0]) save_ani(episode, reward, frames, fps=15, skip_frames=2, out_path='./animations/train/', mode='train')
[ "matplotlib.pyplot.imshow", "os.path.exists", "os.listdir", "os.makedirs", "matplotlib.animation.FuncAnimation", "matplotlib.pyplot.axis", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "numpy.load" ]
[((312, 324), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (322, 324), True, 'import matplotlib.pyplot as plt\n'), ((329, 386), 'matplotlib.pyplot.title', 'plt.title', (['f"""{mode} episode: {episode}, reward: {reward}"""'], {}), "(f'{mode} episode: {episode}, reward: {reward}')\n", (338, 386), True, 'import matplotlib.pyplot as plt\n'), ((391, 406), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (399, 406), True, 'import matplotlib.pyplot as plt\n'), ((417, 453), 'matplotlib.pyplot.imshow', 'plt.imshow', (['frames[0]'], {'animated': '(True)'}), '(frames[0], animated=True)\n', (427, 453), True, 'import matplotlib.pyplot as plt\n'), ((547, 621), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['fig', 'update_fig'], {'frames': 'frames[::skip_frames + 1]'}), '(fig, update_fig, frames=frames[::skip_frames + 1])\n', (570, 621), True, 'import matplotlib.animation as animation\n'), ((813, 833), 'os.listdir', 'os.listdir', (['dir_name'], {}), '(dir_name)\n', (823, 833), False, 'import os\n'), ((241, 265), 'os.path.exists', 'os.path.exists', (['out_path'], {}), '(out_path)\n', (255, 265), False, 'import os\n'), ((275, 296), 'os.makedirs', 'os.makedirs', (['out_path'], {}), '(out_path)\n', (286, 296), False, 'import os\n'), ((904, 940), 'numpy.load', 'np.load', (['f"""./train_stats/{filename}"""'], {}), "(f'./train_stats/{filename}')\n", (911, 940), True, 'import numpy as np\n')]
from __future__ import absolute_import, print_function, division import copy import unittest # Skip test if cuda_ndarray is not available. from nose.plugins.skip import SkipTest import numpy from six.moves import xrange import theano import theano.sandbox.cuda as cuda_ndarray from theano.tensor.basic import _allclose from theano.tests import unittest_tools as utt if not cuda_ndarray.cuda_available: raise SkipTest('Optional package cuda disabled') def advantage(cpu_dt, gpu_dt): """ Return ratio of cpu_dt / gpu_dt, which must be non-negative numbers. If both arguments are zero, return NaN. If only gpu_dt is zero, return Inf. """ assert gpu_dt >= 0 and cpu_dt >= 0 if gpu_dt == 0 and cpu_dt == 0: return numpy.nan elif gpu_dt == 0: return numpy.inf else: return cpu_dt / gpu_dt def test_host_to_device(): # print >>sys.stdout, 'starting test_host_to_dev' for shape in ((), (3,), (2, 3), (3, 4, 5, 6)): a = theano._asarray(numpy.random.rand(*shape), dtype='float32') b = cuda_ndarray.CudaNdarray(a) c = numpy.asarray(b) assert numpy.all(a == c) # test with float32 dtype d = numpy.asarray(b, dtype='float32') assert numpy.all(a == d) # test with not float32 dtype try: numpy.asarray(b, dtype='int8') assert False except TypeError: pass def test_add_iadd_idiv(): for shapes in ([(5, 5), (5, 1)], [(5, 5), (1, 5)], (), (0,), (3,), (2, 3), (1, 10000000), (10000, 1000), (1000000, 10), (4100, 33, 34), (33, 4100, 34), (33, 34, 4100), (4100, 33, 3, 6), (33, 4100, 3, 6), (33, 3, 4100, 6), (33, 3, 6, 4100), (4100, 3, 34, 6), (3, 4100, 34, 6), (3, 34, 4100, 6), (3, 34, 6, 4100), (4100, 3, 4, 36), (3, 4100, 4, 36), (3, 4, 4100, 36), (3, 4, 36, 4100), (0, 0, 0, 0, 0), (3, 34, 35, 36, 37), (33, 34, 3, 36, 37), (33, 34, 35, 36, 3), (0, 0, 0, 0, 0, 0), (3, 34, 35, 36, 37, 2), (33, 34, 3, 36, 37, 2), (33, 34, 35, 36, 3, 2), (3, 4, 5, 6, 7, 1025), (3, 4, 5, 6, 1025, 7), (3, 4, 5, 1025, 6, 7), (3, 4, 1025, 5, 6, 7), (3, 1025, 4, 5, 6, 7), (1025, 3, 4, 5, 6, 7), ): if isinstance(shapes, tuple): shape = shapes shape2 = shapes a0 = theano._asarray(numpy.random.rand(*shape), dtype='float32') a0_orig = a0.copy() a1 = a0.copy() assert numpy.allclose(a0, a1) else: shape = shapes[0] shape2 = shapes[1] a0 = theano._asarray(numpy.random.rand(*shape), dtype='float32') a0_orig = a0.copy() a1 = theano._asarray(numpy.random.rand(*shape2), dtype='float32') b0 = cuda_ndarray.CudaNdarray(a0) b1 = cuda_ndarray.CudaNdarray(a1) assert numpy.allclose(a0, numpy.asarray(b0)) assert numpy.allclose(a1, numpy.asarray(b1)) # add don't support stride if shape == shape2: bsum = b0 + b1 bsum = b0 + b1 asum = a0 + a1 asum = a0 + a1 # print shape, 'adding ', a0.size, 'cpu', cpu_dt, 'advantage', advantage(cpu_dt, gpu_dt) assert numpy.allclose(asum, numpy.asarray(bsum)) # test not contiguous version. # should raise not implemented. a0 = a0_orig.copy() b0 = cuda_ndarray.CudaNdarray(a0) if len(shape) == 0: continue elif len(shape) == 1: _b = b1[::-1] elif len(shape) == 2: _b = b1[::, ::-1] elif len(shape) == 3: _b = b1[::, ::, ::-1] elif len(shape) == 4: _b = b1[::, ::, ::, ::-1] elif len(shape) == 5: _b = b1[::, ::, ::, ::, ::-1] elif len(shape) == 6: _b = b1[::, ::, ::, ::, ::, ::-1] else: raise Exception("You need to modify this case!") # TODO: b0[...,::-1] don't work # test inplace version b0 += b1 a0 += a1 # print shape, 'adding inplace', a0.size, 'cpu', cpu_dt, 'advantage', advantage(cpu_dt, gpu_dt) assert numpy.allclose(a0, numpy.asarray(b0)) assert numpy.allclose(a0, a0_orig + a1) b0 /= b1 a0 /= a1 assert numpy.allclose(a0, numpy.asarray(b0)) assert numpy.allclose(a0, (a0_orig + a1) / a1) # test inplace version # for not contiguous input b0 += _b a0 += a1[..., ::-1] assert numpy.allclose(a0, numpy.asarray(b0)) assert numpy.allclose(a0, (a0_orig + a1) / a1 + a1[..., ::-1]) b0 /= _b a0 /= a1[..., ::-1] assert numpy.allclose(a0, numpy.asarray(b0)) assert numpy.allclose(a0, ((a0_orig + a1) / a1 + a1[..., ::-1]) / a1[..., ::-1]) def test_exp(): # print >>sys.stdout, 'starting test_exp' for shape in ((), (3,), (2, 3), (1, 10000000), (10, 1000000), (100, 100000), (1000, 10000), (10000, 1000)): a0 = theano._asarray(numpy.random.rand(*shape), dtype='float32') a1 = a0.copy() b0 = cuda_ndarray.CudaNdarray(a0) cuda_ndarray.CudaNdarray(a1) bsum = b0.exp() asum = numpy.exp(a1) # print shape, 'adding ', a0.size, 'cpu', cpu_dt, 'advantage', advantage(cpu_dt, gpu_dt) # c = numpy.asarray(b0+b1) if asum.shape: assert numpy.allclose(asum, numpy.asarray(bsum)) def test_copy(): # print >>sys.stdout, 'starting test_copy' shape = (500, 499) a = theano._asarray(numpy.random.rand(*shape), dtype='float32') # print >>sys.stdout, '.. creating device object' b = cuda_ndarray.CudaNdarray(a) # print >>sys.stdout, '.. copy' c = copy.copy(b) # print >>sys.stdout, '.. deepcopy' d = copy.deepcopy(b) # print >>sys.stdout, '.. comparisons' assert numpy.allclose(a, numpy.asarray(b)) assert numpy.allclose(a, numpy.asarray(c)) assert numpy.allclose(a, numpy.asarray(d)) b += b assert numpy.allclose(a + a, numpy.asarray(b)) assert numpy.allclose(a + a, numpy.asarray(c)) assert numpy.allclose(a, numpy.asarray(d)) def test_nvcc_bug(): """ The fct k_elemwise_unary_rowmajor_copy(used by cuda.copy()) in cuda_ndarray.cu is not well compiled with nvcc 3.0 and 3.1 beta. We found a workaround, so it sould work correctly. Without the workaround, this test fail. """ shape = (5, 4) aa = theano._asarray(numpy.random.rand(*shape), dtype='float32') a = aa[::, ::-1] b = cuda_ndarray.CudaNdarray(aa)[::, ::-1] c = copy.copy(b) d = copy.deepcopy(b) assert numpy.allclose(a, numpy.asarray(b)) assert numpy.allclose(a, numpy.asarray(c)) assert numpy.allclose(a, numpy.asarray(d)) b += b assert numpy.allclose(a + a, numpy.asarray(b)) assert numpy.allclose(a + a, numpy.asarray(c)) assert numpy.allclose(a, numpy.asarray(d)) class test_DimShuffle(unittest.TestCase): def test_dimshuffle(self): utt.seed_rng() rng = numpy.random.RandomState(utt.fetch_seed()) # 2d -> 0d a = theano._asarray(rng.randn(1, 1), dtype='float32') b = cuda_ndarray.CudaNdarray(a) assert numpy.allclose(numpy.transpose(a), cuda_ndarray.dimshuffle(b, ())) # Test when we drop a axis that don't have shape 1 a = theano._asarray(rng.randn(2, 1), dtype='float32') b = cuda_ndarray.CudaNdarray(a) self.assertRaises(ValueError, cuda_ndarray.dimshuffle, b, ()) # Test that we can't take a dimensions multiple time a = theano._asarray(rng.randn(2, 1), dtype='float32') b = cuda_ndarray.CudaNdarray(a) self.assertRaises(ValueError, cuda_ndarray.dimshuffle, b, (1, 1)) # 1d a = theano._asarray(rng.randn(3,), dtype='float32') b = cuda_ndarray.CudaNdarray(a) assert numpy.allclose(numpy.transpose(a), cuda_ndarray.dimshuffle(b, (0,))) assert numpy.allclose(a[None, :, None], cuda_ndarray.dimshuffle(b, (-1, 0, -1))) # 2d a = theano._asarray(rng.randn(3, 11), dtype='float32') b = cuda_ndarray.CudaNdarray(a) assert numpy.allclose(numpy.transpose(a), cuda_ndarray.dimshuffle(b, (1, 0))) assert numpy.allclose(numpy.transpose(a)[None, :, None, :, None], cuda_ndarray.dimshuffle(b, (-1, 1, -1, 0, -1))) # 2d -> 1d a = theano._asarray(rng.randn(1, 11), dtype='float32') b = cuda_ndarray.CudaNdarray(a) assert numpy.allclose(a[:], cuda_ndarray.dimshuffle(b, (1,))) a = theano._asarray(rng.randn(11, 1), dtype='float32') b = cuda_ndarray.CudaNdarray(a) assert numpy.allclose(a.reshape((11,)), cuda_ndarray.dimshuffle(b, (0,))) # 3d a = theano._asarray(rng.randn(3, 4, 5), dtype='float32') b = cuda_ndarray.CudaNdarray(a) assert numpy.allclose(a, cuda_ndarray.dimshuffle(b, (0, 1, 2))) assert numpy.allclose(numpy.swapaxes(a, 0, 1), cuda_ndarray.dimshuffle(b, (1, 0, 2))) assert numpy.allclose(numpy.swapaxes(a, 0, 2), cuda_ndarray.dimshuffle(b, (2, 1, 0))) assert numpy.allclose(numpy.swapaxes(a, 1, 2), cuda_ndarray.dimshuffle(b, (0, 2, 1))) assert numpy.allclose(numpy.swapaxes(a, 1, 2)[None, :, None, :, :, None], cuda_ndarray.dimshuffle(b, (-1, 0, -1, 2, 1, -1))) # 4d a = theano._asarray(rng.randn(3, 11, 4, 5), dtype='float32') b = cuda_ndarray.CudaNdarray(a) assert numpy.allclose(numpy.swapaxes(a, 0, 1), cuda_ndarray.dimshuffle(b, (1, 0, 2, 3))) assert numpy.allclose(numpy.swapaxes(a, 0, 2), cuda_ndarray.dimshuffle(b, (2, 1, 0, 3))) assert numpy.allclose(numpy.swapaxes(a, 0, 3), cuda_ndarray.dimshuffle(b, (3, 1, 2, 0))) assert numpy.allclose(numpy.swapaxes(a, 0, 3), cuda_ndarray.dimshuffle(b, (3, 1, 2, 0))) assert numpy.allclose(numpy.swapaxes(a, 0, 3)[None, :, None, :, :, :], cuda_ndarray.dimshuffle(b, (-1, 3, -1, 1, 2, 0))) def test_dot(): # print >>sys.stdout, 'starting test_dot' utt.seed_rng() rng = numpy.random.RandomState(utt.fetch_seed()) a0 = theano._asarray(rng.randn(4, 7), dtype='float32') a1 = theano._asarray(rng.randn(7, 6), dtype='float32') b0 = cuda_ndarray.CudaNdarray(a0) b1 = cuda_ndarray.CudaNdarray(a1) assert _allclose(numpy.dot(a0, a1), cuda_ndarray.dot(b0, b1)) a1 = theano._asarray(rng.randn(6, 7), dtype='float32') b1 = cuda_ndarray.CudaNdarray(a1) numpy_version = numpy.dot(a0, a1.T) transposed = cuda_ndarray.dimshuffle(b1, (1, 0)) cuda_version = cuda_ndarray.dot(b0, transposed) assert _allclose(numpy_version, cuda_version) a1 = theano._asarray(rng.randn(7, 6), dtype='float32') b1 = cuda_ndarray.CudaNdarray(a1) a0 = theano._asarray(rng.randn(7, 4), dtype='float32') b0 = cuda_ndarray.CudaNdarray(a0) assert _allclose(numpy.dot(a0.T, a1), cuda_ndarray.dot( cuda_ndarray.dimshuffle(b0, (1, 0)), b1)) a1 = theano._asarray(rng.randn(6, 7), dtype='float32') b1 = cuda_ndarray.CudaNdarray(a1) assert _allclose( numpy.dot(a0.T, a1.T), cuda_ndarray.dot(cuda_ndarray.dimshuffle(b0, (1, 0)), cuda_ndarray.dimshuffle(b1, (1, 0)))) def test_sum(): shape = (2, 3) a0 = theano._asarray(numpy.arange(shape[0] * shape[1]).reshape(shape), dtype='float32') b0 = cuda_ndarray.CudaNdarray(a0) assert numpy.allclose(a0.sum(), numpy.asarray(b0.reduce_sum([1, 1]))) a0.sum(axis=0) b0.reduce_sum([1, 0]) # print 'asum\n',a0sum # print 'bsum\n',numpy.asarray(b0sum) assert numpy.allclose(a0.sum(axis=0), numpy.asarray(b0.reduce_sum([1, 0]))) assert numpy.allclose(a0.sum(axis=1), numpy.asarray(b0.reduce_sum([0, 1]))) assert numpy.allclose(a0, numpy.asarray(b0.reduce_sum([0, 0]))) shape = (3, 4, 5, 6, 7, 8) a0 = theano._asarray(numpy.arange(3 * 4 * 5 * 6 * 7 * 8).reshape(shape), dtype='float32') b0 = cuda_ndarray.CudaNdarray(a0) assert numpy.allclose(a0.sum(axis=5).sum(axis=3).sum(axis=0), numpy.asarray(b0.reduce_sum([1, 0, 0, 1, 0, 1]))) shape = (16, 2048) a0 = theano._asarray(numpy.arange(16 * 2048).reshape(shape), dtype='float32') b0 = cuda_ndarray.CudaNdarray(a0) assert numpy.allclose(a0.sum(axis=0), numpy.asarray(b0.reduce_sum([1, 0]))) shape = (16, 10) a0 = theano._asarray(numpy.arange(160).reshape(shape), dtype='float32') b0 = cuda_ndarray.CudaNdarray(a0) assert numpy.allclose(a0.sum(), numpy.asarray(b0.reduce_sum([1, 1]))) def test_reshape(): shapelist = [((1, 2, 3), (1, 2, 3)), ((1,), (1,)), ((1, 2, 3), (3, 2, 1)), ((1, 2, 3), (6,)), ((1, 2, 3, 2), (6, 2)), ((2, 3, 2), (6, 2)), ((2, 3, 2), (12,)) ] bad_shapelist = [ ((1, 2, 3), (1, 2, 4)), ((1,), (2,)), ((1, 2, 3), (2, 2, 1)), ((1, 2, 3), (5,)), ((1, 2, 3, 2), (6, 3)), ((2, 3, 2), (5, 2)), ((2, 3, 2), (11,)) ] utt.seed_rng() rng = numpy.random.RandomState(utt.fetch_seed()) def subtest(shape_1, shape_2, rng): # print >> sys.stdout, "INFO: shapes", shape_1, shape_2 a = theano._asarray(rng.randn(*shape_1), dtype='float32') b = cuda_ndarray.CudaNdarray(a) aa = a.reshape(shape_2) bb = b.reshape(shape_2) n_bb = numpy.asarray(bb) # print n_bb assert numpy.all(aa == n_bb) assert aa.shape == n_bb.shape # Test the not contiguous case shape_1_2x = (shape_1[0] * 2,) + shape_1[1:] a = theano._asarray(rng.randn(*shape_1_2x), dtype='float32') b = cuda_ndarray.CudaNdarray(a) a = a[::2] b = b[::2] aa = a.reshape(shape_2) bb = b.reshape(shape_2) n_bb = numpy.asarray(bb) # print n_bb assert numpy.all(aa == n_bb) assert aa.shape == n_bb.shape def bad_subtest(shape_1, shape_2, rng): a = theano._asarray(rng.randn(*shape_1), dtype='float32') b = cuda_ndarray.CudaNdarray(a) try: b.reshape(shape_2) except Exception: return assert False # test working shapes for shape_1, shape_2 in shapelist: subtest(shape_1, shape_2, rng) subtest(shape_2, shape_1, rng) # test shape combinations that should give error for shape_1, shape_2 in bad_shapelist: bad_subtest(shape_1, shape_2, rng) bad_subtest(shape_2, shape_1, rng) def test_getshape(): shapelist = [ ((1, 2, 3), (1, 2, 3)), ((1,), (1,)), ((1, 2, 3), (3, 2, 1)), ((1, 2, 3), (6,)), ((1, 2, 3, 2), (6, 2)), ((2, 3, 2), (6, 2)) ] def subtest(shape): a = theano._asarray(numpy.random.rand(*shape_1), dtype='float32') b = cuda_ndarray.CudaNdarray(a) assert b.shape == a.shape for shape_1, shape_2 in shapelist: subtest(shape_1) subtest(shape_2) def test_stride_manipulation(): a = theano._asarray([[0, 1, 2], [3, 4, 5]], dtype='float32') b = cuda_ndarray.CudaNdarray(a) v = b.view() v._dev_data += 0 c = numpy.asarray(v) assert numpy.all(a == c) sizeof_float = 4 offset = 0 b_strides = b._strides for i in xrange(len(b.shape)): offset += (b.shape[i] - 1) * b_strides[i] v._set_stride(i, -b_strides[i]) v._dev_data += offset * sizeof_float c = numpy.asarray(v) assert numpy.all(c == [[5, 4, 3], [2, 1, 0]]) def test_subtensor_broadcastable(): a = numpy.zeros((2, 7), dtype='float32') cuda_a = cuda_ndarray.CudaNdarray(a) # Will have shape (1, 7), so the stride in the first dim should be 0 sub_a = cuda_a[1:] assert sub_a.shape == (1, 7) assert sub_a._strides[0] == 0 def test_copy_subtensor0(): sizeof_float = 4 a = theano._asarray(numpy.random.rand(30, 20, 5, 5), dtype='float32') cuda_a = cuda_ndarray.CudaNdarray(a) a_view = cuda_a.view() a_view_strides = a_view._strides a_view._set_stride(2, -a_view_strides[2]) a_view._set_stride(3, -a_view_strides[3]) a_view._dev_data += 24 * sizeof_float a_view_copy = copy.deepcopy(a_view) assert numpy.all(a[:, :, ::-1, ::-1] == numpy.asarray(a_view_copy)) def test_mapping_getitem_ellipsis(): a = theano._asarray(numpy.random.rand(5, 4, 3, 2), dtype='float32') a = cuda_ndarray.CudaNdarray(a) b = a[...] assert b._dev_data == a._dev_data assert b._strides == a._strides assert b.shape == a.shape def test_mapping_getitem_reverse_some_dims(): dim = (5, 4, 3, 2) a = theano._asarray(numpy.random.rand(*dim), dtype='float32') _a = cuda_ndarray.CudaNdarray(a) _b = _a[:, :, ::-1, ::-1] b = numpy.asarray(_b) assert numpy.all(b == a[:, :, ::-1, ::-1]) def test_mapping_getitem_w_int(): def _cmp(x, y): assert x.shape == y.shape if not numpy.all(x == y): print(x) print(y) assert numpy.all(x == y) def _cmpf(x, *y): try: x.__getitem__(y) except IndexError: pass else: raise Exception("Did not generate out or bound error") def _cmpfV(x, *y): try: if len(y) == 1: x.__getitem__(*y) else: x.__getitem__(y) except ValueError: pass else: raise Exception("Did not generate out or bound error") dim = (2,) a = theano._asarray(numpy.random.rand(*dim), dtype='float32') _a = cuda_ndarray.CudaNdarray(a) _cmp(numpy.asarray(_a[1]), a[1]) _cmp(numpy.asarray(_a[-1]), a[-1]) _cmp(numpy.asarray(_a[0]), a[0]) _cmp(numpy.asarray(_a[::1]), a[::1]) _cmp(numpy.asarray(_a[::-1]), a[::-1]) _cmp(numpy.asarray(_a[...]), a[...]) _cmpf(_a, 2) dim = () a = theano._asarray(numpy.random.rand(*dim), dtype='float32') _a = cuda_ndarray.CudaNdarray(a) _cmp(numpy.asarray(_a[...]), a[...]) _cmpf(_a, 0) _cmpfV(_a, slice(1)) dim = (5, 4, 3, 2) a = theano._asarray(numpy.random.rand(*dim), dtype='float32') _a = cuda_ndarray.CudaNdarray(a) _cmpf(_a, slice(-1), slice(-1), 10, -10) _cmpf(_a, slice(-1), slice(-1), -10, slice(-1)) _cmpf(_a, 0, slice(0, -1, -20), -10) _cmpf(_a, 10) _cmpf(_a, (10, 0, 0, 0)) _cmpf(_a, -10) # test with integer _cmp(numpy.asarray(_a[1]), a[1]) _cmp(numpy.asarray(_a[-1]), a[-1]) _cmp(numpy.asarray(_a[numpy.int64(1)]), a[numpy.int64(1)]) _cmp(numpy.asarray(_a[numpy.int64(-1)]), a[numpy.int64(-1)]) # test with slice _cmp(numpy.asarray(_a[1:]), a[1:]) _cmp(numpy.asarray(_a[1:2]), a[1:2]) _cmp(numpy.asarray(_a[-1:1]), a[-1:1]) # test with tuple (mix slice, integer, numpy.int64) _cmp(numpy.asarray(_a[:, :, ::numpy.int64(-1), ::-1]), a[:, :, ::-1, ::-1]) _cmp(numpy.asarray(_a[:, :, numpy.int64(1), -1]), a[:, :, 1, -1]) _cmp(numpy.asarray(_a[:, :, ::-1, ::-1]), a[:, :, ::-1, ::-1]) _cmp(numpy.asarray(_a[:, :, ::-10, ::-10]), a[:, :, ::-10, ::-10]) _cmp(numpy.asarray(_a[:, :, 1, -1]), a[:, :, 1, -1]) _cmp(numpy.asarray(_a[:, :, -1, :]), a[:, :, -1, :]) _cmp(numpy.asarray(_a[:, ::-2, -1, :]), a[:, ::-2, -1, :]) _cmp(numpy.asarray(_a[:, ::-20, -1, :]), a[:, ::-20, -1, :]) _cmp(numpy.asarray(_a[:, ::-2, -1]), a[:, ::-2, -1]) _cmp(numpy.asarray(_a[0, ::-2, -1]), a[0, ::-2, -1]) _cmp(numpy.asarray(_a[-1, -1, -1, -2]), a[-1, -1, -1, -2]) _cmp(numpy.asarray(_a[...]), a[...]) def test_gemm_vector_vector(): a = theano._asarray(numpy.random.rand(5, 1), dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray(numpy.random.rand(1, 5), dtype='float32') _b = cuda_ndarray.CudaNdarray(b) _c = cuda_ndarray.dot(_a, _b) assert _c.shape == (5, 5) assert numpy.allclose(_c, numpy.dot(a, b)) _c = cuda_ndarray.dot(_b, _a) assert _c.shape == (1, 1) assert numpy.allclose(_c, numpy.dot(b, a)) # --------------------------------------------------------------------- def test_setitem_matrixscalar0(): a = theano._asarray([[0, 1, 2], [3, 4, 5]], dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray(8, dtype='float32') _b = cuda_ndarray.CudaNdarray(b) # set an element to 8 _a[1, 1] = _b a[1, 1] = b assert numpy.allclose(a, numpy.asarray(_a)) # test direct transfert from numpy _a[1, 1] = theano._asarray(888, dtype='float32') a[1, 1] = theano._asarray(888, dtype='float32') assert numpy.allclose(a, numpy.asarray(_a)) # broadcast a 0 _a[1, 1] = 0 _a[0:2] = 0 _a[1:] = 0 def test_setitem_matrixvector1(): a = theano._asarray([[0, 1, 2], [3, 4, 5]], dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray([8, 9], dtype='float32') _b = cuda_ndarray.CudaNdarray(b) # set second column to 8,9 _a[:, 1] = _b a[:, 1] = b assert numpy.allclose(a, numpy.asarray(_a)) # test direct transfert from numpy _a[:, 1] = b * 100 a[:, 1] = b * 100 assert numpy.allclose(a, numpy.asarray(_a)) row = theano._asarray([777, 888, 999], dtype='float32') _a[1, :] = row a[1, :] = row assert numpy.allclose(a, numpy.asarray(_a)) def test_setitem_matrix_tensor3(): a = numpy.arange(27) a.resize((3, 3, 3)) a = theano._asarray(a, dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray([7, 8, 9], dtype='float32') _b = cuda_ndarray.CudaNdarray(b) # set middle row through cube to 7,8,9 _a[:, 1, 1] = _b a[:, 1, 1] = b assert numpy.allclose(a, numpy.asarray(_a)) # test direct transfert from numpy _a[:, 1, 1] = b * 100 a[:, 1, 1] = b * 100 assert numpy.allclose(a, numpy.asarray(_a)) row = theano._asarray([777, 888, 999], dtype='float32') _a[1, 1, :] = row a[1, 1, :] = row assert numpy.allclose(a, numpy.asarray(_a)) def test_setitem_from_numpy_error(): pass def test_setitem_matrix_bad_shape(): a = numpy.arange(27) a.resize((3, 3, 3)) a = theano._asarray(a, dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray([7, 8], dtype='float32') _b = cuda_ndarray.CudaNdarray(b) try: # attempt to assign the ndarray b with setitem _a[:, 1, 1] = _b assert False except ValueError: # print e assert True # test direct transfert from numpy try: # attempt to assign the ndarray b with setitem _a[1, 1, :] = b assert False except ValueError: # print e assert True def test_setitem_matrix_bad_ndim(): a = numpy.arange(27) a.resize((3, 3, 3)) a = theano._asarray(a, dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray([7, 8], dtype='float32') _b = cuda_ndarray.CudaNdarray(b) try: # attempt to assign the ndarray b with setitem _a[:, :, 1] = _b assert False except ValueError: # print e assert True # test direct transfert from numpy try: # attempt to assign the ndarray b with setitem _a[1, :, :] = b assert False except ValueError: # print e assert True def test_setitem_matrix_bad_type(): a = numpy.arange(27) a.resize((3, 3, 3)) a = theano._asarray(a, dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray([7, 8], dtype='float64') # test direct transfert from numpy try: # attempt to assign the ndarray b with setitem _a[1, :, :] = b assert False except TypeError: # print e assert True def test_setitem_assign_to_slice(): a = numpy.arange(27) a.resize((3, 3, 3)) a = theano._asarray(a, dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray([7, 8, 9], dtype='float32') _b = cuda_ndarray.CudaNdarray(b) # first get a slice of a _c = _a[:, :, 1] # set middle row through cube to 7,8,9 # (this corresponds to middle row of matrix _c) _c[:, 1] = _b a[:, :, 1][:, 1] = b assert numpy.allclose(a, numpy.asarray(_a)) # test direct transfert from numpy _d = _a[1, :, :] _d[1, :] = b * 10 a[1, :, :][1, :] = b * 10 assert numpy.allclose(a, numpy.asarray(_a)) def test_setitem_broadcast(): # test scalar to vector without stride a = numpy.arange(3) a = theano._asarray(a, dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray(9, dtype='float32') _b = cuda_ndarray.CudaNdarray(b) _a[:] = _b.reshape((1,)) a[:] = b.reshape((1,)) assert numpy.allclose(numpy.asarray(_a), a) # test vector to matrice without stride a = numpy.arange(9) a.resize((3, 3)) a = theano._asarray(a, dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray([7, 8, 9], dtype='float32') _b = cuda_ndarray.CudaNdarray(b) _a[:, :] = _b.reshape((1, 3)) a[:, :] = b.reshape((1, 3)) assert numpy.allclose(numpy.asarray(_a), a) # test vector to matrice with stride a = numpy.arange(27) a.resize((3, 3, 3)) a = theano._asarray(a, dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray([[7, 8, 9], [10, 11, 12]], dtype='float32') _b = cuda_ndarray.CudaNdarray(b)[0] b = b[0] _a[:, :, 1] = _b.reshape((1, 3)) a[:, :, 1] = b.reshape((1, 3)) assert numpy.allclose(numpy.asarray(_a), a) def test_setitem_broadcast_numpy(): # test scalar to vector without stride a = numpy.arange(3) a = theano._asarray(a, dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray(9, dtype='float32') _a[:] = b.reshape((1,)) a[:] = b.reshape((1,)) assert numpy.allclose(numpy.asarray(_a), a) # test vector to matrice without stride a = numpy.arange(9) a.resize((3, 3)) a = theano._asarray(a, dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray([7, 8, 9], dtype='float32') _a[:, :] = b.reshape((1, 3)) a[:, :] = b.reshape((1, 3)) assert numpy.allclose(numpy.asarray(_a), a) # test vector to matrice with stride a = numpy.arange(27) a.resize((3, 3, 3)) a = theano._asarray(a, dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray([[7, 8, 9], [10, 11, 12]], dtype='float32') b = b[0] _a[1, :, :] = b.reshape((1, 3)) a[1, :, :] = b.reshape((1, 3)) assert numpy.allclose(numpy.asarray(_a), a) # this also fails for the moment def test_setitem_rightvalue_ndarray_fails(): """ Now we don't automatically add dimensions to broadcast """ a = numpy.arange(3 * 4 * 5) a.resize((3, 4, 5)) a = theano._asarray(a, dtype='float32') _a = cuda_ndarray.CudaNdarray(a) b = theano._asarray([7, 8, 9, 10], dtype='float32') _b = cuda_ndarray.CudaNdarray(b) b5 = theano._asarray([7, 8, 9, 10, 11], dtype='float32') cuda_ndarray.CudaNdarray(b) # attempt to assign the ndarray b with setitem _a[:, :, 1] = _b a[:, :, 1] = b assert numpy.allclose(numpy.asarray(_a), a) # test direct transfert from numpy to contiguous region # attempt to assign the ndarray b with setitem # same number of dim mat = numpy.random.rand(4, 5).astype('float32') _a[2, :, :] = mat a[2, :, :] = mat assert numpy.allclose(numpy.asarray(_a), a) # without same number of dim try: _a[0, :, :] = mat # a[0, :, :] = mat # assert numpy.allclose(numpy.asarray(_a), a) except ValueError: pass # test direct transfert from numpy with broadcast _a[0, :, :] = b5 a[0, :, :] = b5 assert numpy.allclose(numpy.asarray(_a), a) # test direct transfert from numpy to not contiguous region # attempt to assign the ndarray b with setitem _a[:, :, 2] = b a[:, :, 2] = b assert numpy.allclose(numpy.asarray(_a), a) def test_zeros_basic(): for shp in [(3, 4, 5), (300,), (), (0, 7)]: _a = cuda_ndarray.CudaNdarray.zeros(shp) _n = numpy.zeros(shp, dtype="float32") assert numpy.allclose(numpy.asarray(_a), _n) assert _a.shape == _n.shape assert all(_a._strides == numpy.asarray(_n.strides) / 4) # TODO:The following don't have the same stride! # This should be fixed with the new GpuNdArray. for shp in [(3, 0), (4, 1, 5)]: _a = cuda_ndarray.CudaNdarray.zeros(shp) _n = numpy.zeros(shp, dtype="float32") assert numpy.allclose(numpy.asarray(_a), _n) assert _a.shape == _n.shape try: _n = numpy.zeros() except TypeError: pass else: raise Exception("An error was expected!") try: _a = cuda_ndarray.CudaNdarray.zeros() except TypeError: pass else: raise Exception("An error was expected!") def test_base(): # Test that the 'base' attribute of a CudaNdarray is the one # built initially, not an intermediate one. a = cuda_ndarray.CudaNdarray.zeros((3, 4, 5)) for i in xrange(5): b = a[:] assert b.base is a c = a[0] d = c[:, 0] # print d.shape assert c.base is a assert d.base is a e = b.reshape((5, 2, 2, 3)) assert e.base is a def test_set_strides(): a = cuda_ndarray.CudaNdarray.zeros((5, 5)) # Test with tuple new_strides = (a.strides[1], a.strides[0]) a.strides = new_strides assert a.strides == new_strides # Test with list new_strides = (a.strides[1], a.strides[0]) a.strides = [a.strides[1], a.strides[0]] assert a.strides == new_strides try: a.strides = (a.strides[1],) assert False except ValueError: pass try: a.strides = (1, 1, 1) assert False except ValueError: pass def test_is_c_contiguous(): a = cuda_ndarray.CudaNdarray.zeros((3, 4, 5)) assert a.is_c_contiguous() assert a[1].is_c_contiguous() assert not a[::2].is_c_contiguous() if __name__ == '__main__': test_setitem_matrixvector1() test_setitem_matrix_tensor3() test_setitem_assign_to_slice() test_setitem_rightvalue_ndarray_fails()
[ "numpy.random.rand", "theano.sandbox.cuda.CudaNdarray.zeros", "six.moves.xrange", "copy.deepcopy", "theano.tensor.basic._allclose", "copy.copy", "numpy.arange", "theano.sandbox.cuda.CudaNdarray", "theano.sandbox.cuda.dot", "numpy.int64", "numpy.asarray", "theano.tests.unittest_tools.fetch_seed...
[((415, 457), 'nose.plugins.skip.SkipTest', 'SkipTest', (['"""Optional package cuda disabled"""'], {}), "('Optional package cuda disabled')\n", (423, 457), False, 'from nose.plugins.skip import SkipTest\n'), ((6103, 6130), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (6127, 6130), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((6176, 6188), 'copy.copy', 'copy.copy', (['b'], {}), '(b)\n', (6185, 6188), False, 'import copy\n'), ((6237, 6253), 'copy.deepcopy', 'copy.deepcopy', (['b'], {}), '(b)\n', (6250, 6253), False, 'import copy\n'), ((7034, 7046), 'copy.copy', 'copy.copy', (['b'], {}), '(b)\n', (7043, 7046), False, 'import copy\n'), ((7055, 7071), 'copy.deepcopy', 'copy.deepcopy', (['b'], {}), '(b)\n', (7068, 7071), False, 'import copy\n'), ((10988, 11002), 'theano.tests.unittest_tools.seed_rng', 'utt.seed_rng', ([], {}), '()\n', (11000, 11002), True, 'from theano.tests import unittest_tools as utt\n'), ((11185, 11213), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a0'], {}), '(a0)\n', (11209, 11213), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((11223, 11251), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a1'], {}), '(a1)\n', (11247, 11251), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((11388, 11416), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a1'], {}), '(a1)\n', (11412, 11416), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((11438, 11457), 'numpy.dot', 'numpy.dot', (['a0', 'a1.T'], {}), '(a0, a1.T)\n', (11447, 11457), False, 'import numpy\n'), ((11475, 11510), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b1', '(1, 0)'], {}), '(b1, (1, 0))\n', (11498, 11510), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((11530, 11562), 'theano.sandbox.cuda.dot', 'cuda_ndarray.dot', (['b0', 'transposed'], {}), '(b0, transposed)\n', (11546, 11562), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((11575, 11613), 'theano.tensor.basic._allclose', '_allclose', (['numpy_version', 'cuda_version'], {}), '(numpy_version, cuda_version)\n', (11584, 11613), False, 'from theano.tensor.basic import _allclose\n'), ((11683, 11711), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a1'], {}), '(a1)\n', (11707, 11711), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((11781, 11809), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a0'], {}), '(a0)\n', (11805, 11809), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((12028, 12056), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a1'], {}), '(a1)\n', (12052, 12056), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((12400, 12428), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a0'], {}), '(a0)\n', (12424, 12428), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((13087, 13115), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a0'], {}), '(a0)\n', (13111, 13115), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((13398, 13426), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a0'], {}), '(a0)\n', (13422, 13426), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((13614, 13642), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a0'], {}), '(a0)\n', (13638, 13642), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((14261, 14275), 'theano.tests.unittest_tools.seed_rng', 'utt.seed_rng', ([], {}), '()\n', (14273, 14275), True, 'from theano.tests import unittest_tools as utt\n'), ((16293, 16349), 'theano._asarray', 'theano._asarray', (['[[0, 1, 2], [3, 4, 5]]'], {'dtype': '"""float32"""'}), "([[0, 1, 2], [3, 4, 5]], dtype='float32')\n", (16308, 16349), False, 'import theano\n'), ((16358, 16385), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (16382, 16385), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((16432, 16448), 'numpy.asarray', 'numpy.asarray', (['v'], {}), '(v)\n', (16445, 16448), False, 'import numpy\n'), ((16460, 16477), 'numpy.all', 'numpy.all', (['(a == c)'], {}), '(a == c)\n', (16469, 16477), False, 'import numpy\n'), ((16718, 16734), 'numpy.asarray', 'numpy.asarray', (['v'], {}), '(v)\n', (16731, 16734), False, 'import numpy\n'), ((16747, 16785), 'numpy.all', 'numpy.all', (['(c == [[5, 4, 3], [2, 1, 0]])'], {}), '(c == [[5, 4, 3], [2, 1, 0]])\n', (16756, 16785), False, 'import numpy\n'), ((16832, 16868), 'numpy.zeros', 'numpy.zeros', (['(2, 7)'], {'dtype': '"""float32"""'}), "((2, 7), dtype='float32')\n", (16843, 16868), False, 'import numpy\n'), ((16882, 16909), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (16906, 16909), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((17211, 17238), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (17235, 17238), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((17456, 17477), 'copy.deepcopy', 'copy.deepcopy', (['a_view'], {}), '(a_view)\n', (17469, 17477), False, 'import copy\n'), ((17670, 17697), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (17694, 17697), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((17964, 17991), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (17988, 17991), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((18032, 18049), 'numpy.asarray', 'numpy.asarray', (['_b'], {}), '(_b)\n', (18045, 18049), False, 'import numpy\n'), ((18061, 18096), 'numpy.all', 'numpy.all', (['(b == a[:, :, ::-1, ::-1])'], {}), '(b == a[:, :, ::-1, ::-1])\n', (18070, 18096), False, 'import numpy\n'), ((18852, 18879), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (18876, 18879), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((19224, 19251), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (19248, 19251), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((19434, 19461), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (19458, 19461), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((20956, 20983), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (20980, 20983), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((21059, 21086), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['b'], {}), '(b)\n', (21083, 21086), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((21097, 21121), 'theano.sandbox.cuda.dot', 'cuda_ndarray.dot', (['_a', '_b'], {}), '(_a, _b)\n', (21113, 21121), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((21209, 21233), 'theano.sandbox.cuda.dot', 'cuda_ndarray.dot', (['_b', '_a'], {}), '(_b, _a)\n', (21225, 21233), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((21428, 21484), 'theano._asarray', 'theano._asarray', (['[[0, 1, 2], [3, 4, 5]]'], {'dtype': '"""float32"""'}), "([[0, 1, 2], [3, 4, 5]], dtype='float32')\n", (21443, 21484), False, 'import theano\n'), ((21494, 21521), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (21518, 21521), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((21531, 21566), 'theano._asarray', 'theano._asarray', (['(8)'], {'dtype': '"""float32"""'}), "(8, dtype='float32')\n", (21546, 21566), False, 'import theano\n'), ((21576, 21603), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['b'], {}), '(b)\n', (21600, 21603), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((21768, 21805), 'theano._asarray', 'theano._asarray', (['(888)'], {'dtype': '"""float32"""'}), "(888, dtype='float32')\n", (21783, 21805), False, 'import theano\n'), ((21820, 21857), 'theano._asarray', 'theano._asarray', (['(888)'], {'dtype': '"""float32"""'}), "(888, dtype='float32')\n", (21835, 21857), False, 'import theano\n'), ((22019, 22075), 'theano._asarray', 'theano._asarray', (['[[0, 1, 2], [3, 4, 5]]'], {'dtype': '"""float32"""'}), "([[0, 1, 2], [3, 4, 5]], dtype='float32')\n", (22034, 22075), False, 'import theano\n'), ((22085, 22112), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (22109, 22112), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((22122, 22162), 'theano._asarray', 'theano._asarray', (['[8, 9]'], {'dtype': '"""float32"""'}), "([8, 9], dtype='float32')\n", (22137, 22162), False, 'import theano\n'), ((22172, 22199), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['b'], {}), '(b)\n', (22196, 22199), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((22458, 22507), 'theano._asarray', 'theano._asarray', (['[777, 888, 999]'], {'dtype': '"""float32"""'}), "([777, 888, 999], dtype='float32')\n", (22473, 22507), False, 'import theano\n'), ((22638, 22654), 'numpy.arange', 'numpy.arange', (['(27)'], {}), '(27)\n', (22650, 22654), False, 'import numpy\n'), ((22687, 22722), 'theano._asarray', 'theano._asarray', (['a'], {'dtype': '"""float32"""'}), "(a, dtype='float32')\n", (22702, 22722), False, 'import theano\n'), ((22732, 22759), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (22756, 22759), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((22769, 22812), 'theano._asarray', 'theano._asarray', (['[7, 8, 9]'], {'dtype': '"""float32"""'}), "([7, 8, 9], dtype='float32')\n", (22784, 22812), False, 'import theano\n'), ((22822, 22849), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['b'], {}), '(b)\n', (22846, 22849), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((23133, 23182), 'theano._asarray', 'theano._asarray', (['[777, 888, 999]'], {'dtype': '"""float32"""'}), "([777, 888, 999], dtype='float32')\n", (23148, 23182), False, 'import theano\n'), ((23369, 23385), 'numpy.arange', 'numpy.arange', (['(27)'], {}), '(27)\n', (23381, 23385), False, 'import numpy\n'), ((23418, 23453), 'theano._asarray', 'theano._asarray', (['a'], {'dtype': '"""float32"""'}), "(a, dtype='float32')\n", (23433, 23453), False, 'import theano\n'), ((23463, 23490), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (23487, 23490), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((23500, 23540), 'theano._asarray', 'theano._asarray', (['[7, 8]'], {'dtype': '"""float32"""'}), "([7, 8], dtype='float32')\n", (23515, 23540), False, 'import theano\n'), ((23550, 23577), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['b'], {}), '(b)\n', (23574, 23577), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((24006, 24022), 'numpy.arange', 'numpy.arange', (['(27)'], {}), '(27)\n', (24018, 24022), False, 'import numpy\n'), ((24055, 24090), 'theano._asarray', 'theano._asarray', (['a'], {'dtype': '"""float32"""'}), "(a, dtype='float32')\n", (24070, 24090), False, 'import theano\n'), ((24100, 24127), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (24124, 24127), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((24137, 24177), 'theano._asarray', 'theano._asarray', (['[7, 8]'], {'dtype': '"""float32"""'}), "([7, 8], dtype='float32')\n", (24152, 24177), False, 'import theano\n'), ((24187, 24214), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['b'], {}), '(b)\n', (24211, 24214), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((24643, 24659), 'numpy.arange', 'numpy.arange', (['(27)'], {}), '(27)\n', (24655, 24659), False, 'import numpy\n'), ((24692, 24727), 'theano._asarray', 'theano._asarray', (['a'], {'dtype': '"""float32"""'}), "(a, dtype='float32')\n", (24707, 24727), False, 'import theano\n'), ((24737, 24764), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (24761, 24764), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((24774, 24814), 'theano._asarray', 'theano._asarray', (['[7, 8]'], {'dtype': '"""float64"""'}), "([7, 8], dtype='float64')\n", (24789, 24814), False, 'import theano\n'), ((25070, 25086), 'numpy.arange', 'numpy.arange', (['(27)'], {}), '(27)\n', (25082, 25086), False, 'import numpy\n'), ((25119, 25154), 'theano._asarray', 'theano._asarray', (['a'], {'dtype': '"""float32"""'}), "(a, dtype='float32')\n", (25134, 25154), False, 'import theano\n'), ((25164, 25191), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (25188, 25191), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((25201, 25244), 'theano._asarray', 'theano._asarray', (['[7, 8, 9]'], {'dtype': '"""float32"""'}), "([7, 8, 9], dtype='float32')\n", (25216, 25244), False, 'import theano\n'), ((25254, 25281), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['b'], {}), '(b)\n', (25278, 25281), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((25765, 25780), 'numpy.arange', 'numpy.arange', (['(3)'], {}), '(3)\n', (25777, 25780), False, 'import numpy\n'), ((25789, 25824), 'theano._asarray', 'theano._asarray', (['a'], {'dtype': '"""float32"""'}), "(a, dtype='float32')\n", (25804, 25824), False, 'import theano\n'), ((25834, 25861), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (25858, 25861), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((25871, 25906), 'theano._asarray', 'theano._asarray', (['(9)'], {'dtype': '"""float32"""'}), "(9, dtype='float32')\n", (25886, 25906), False, 'import theano\n'), ((25916, 25943), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['b'], {}), '(b)\n', (25940, 25943), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((26101, 26116), 'numpy.arange', 'numpy.arange', (['(9)'], {}), '(9)\n', (26113, 26116), False, 'import numpy\n'), ((26146, 26181), 'theano._asarray', 'theano._asarray', (['a'], {'dtype': '"""float32"""'}), "(a, dtype='float32')\n", (26161, 26181), False, 'import theano\n'), ((26191, 26218), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (26215, 26218), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((26228, 26271), 'theano._asarray', 'theano._asarray', (['[7, 8, 9]'], {'dtype': '"""float32"""'}), "([7, 8, 9], dtype='float32')\n", (26243, 26271), False, 'import theano\n'), ((26281, 26308), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['b'], {}), '(b)\n', (26305, 26308), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((26473, 26489), 'numpy.arange', 'numpy.arange', (['(27)'], {}), '(27)\n', (26485, 26489), False, 'import numpy\n'), ((26522, 26557), 'theano._asarray', 'theano._asarray', (['a'], {'dtype': '"""float32"""'}), "(a, dtype='float32')\n", (26537, 26557), False, 'import theano\n'), ((26567, 26594), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (26591, 26594), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((26604, 26663), 'theano._asarray', 'theano._asarray', (['[[7, 8, 9], [10, 11, 12]]'], {'dtype': '"""float32"""'}), "([[7, 8, 9], [10, 11, 12]], dtype='float32')\n", (26619, 26663), False, 'import theano\n'), ((26926, 26941), 'numpy.arange', 'numpy.arange', (['(3)'], {}), '(3)\n', (26938, 26941), False, 'import numpy\n'), ((26950, 26985), 'theano._asarray', 'theano._asarray', (['a'], {'dtype': '"""float32"""'}), "(a, dtype='float32')\n", (26965, 26985), False, 'import theano\n'), ((26995, 27022), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (27019, 27022), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((27032, 27067), 'theano._asarray', 'theano._asarray', (['(9)'], {'dtype': '"""float32"""'}), "(9, dtype='float32')\n", (27047, 27067), False, 'import theano\n'), ((27224, 27239), 'numpy.arange', 'numpy.arange', (['(9)'], {}), '(9)\n', (27236, 27239), False, 'import numpy\n'), ((27269, 27304), 'theano._asarray', 'theano._asarray', (['a'], {'dtype': '"""float32"""'}), "(a, dtype='float32')\n", (27284, 27304), False, 'import theano\n'), ((27314, 27341), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (27338, 27341), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((27351, 27394), 'theano._asarray', 'theano._asarray', (['[7, 8, 9]'], {'dtype': '"""float32"""'}), "([7, 8, 9], dtype='float32')\n", (27366, 27394), False, 'import theano\n'), ((27558, 27574), 'numpy.arange', 'numpy.arange', (['(27)'], {}), '(27)\n', (27570, 27574), False, 'import numpy\n'), ((27607, 27642), 'theano._asarray', 'theano._asarray', (['a'], {'dtype': '"""float32"""'}), "(a, dtype='float32')\n", (27622, 27642), False, 'import theano\n'), ((27652, 27679), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (27676, 27679), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((27689, 27748), 'theano._asarray', 'theano._asarray', (['[[7, 8, 9], [10, 11, 12]]'], {'dtype': '"""float32"""'}), "([[7, 8, 9], [10, 11, 12]], dtype='float32')\n", (27704, 27748), False, 'import theano\n'), ((28044, 28067), 'numpy.arange', 'numpy.arange', (['(3 * 4 * 5)'], {}), '(3 * 4 * 5)\n', (28056, 28067), False, 'import numpy\n'), ((28100, 28135), 'theano._asarray', 'theano._asarray', (['a'], {'dtype': '"""float32"""'}), "(a, dtype='float32')\n", (28115, 28135), False, 'import theano\n'), ((28145, 28172), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (28169, 28172), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((28182, 28229), 'theano._asarray', 'theano._asarray', (['[7, 8, 9, 10]'], {'dtype': '"""float32"""'}), "([7, 8, 9, 10], dtype='float32')\n", (28197, 28229), False, 'import theano\n'), ((28239, 28266), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['b'], {}), '(b)\n', (28263, 28266), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((28276, 28327), 'theano._asarray', 'theano._asarray', (['[7, 8, 9, 10, 11]'], {'dtype': '"""float32"""'}), "([7, 8, 9, 10, 11], dtype='float32')\n", (28291, 28327), False, 'import theano\n'), ((28332, 28359), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['b'], {}), '(b)\n', (28356, 28359), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((30391, 30432), 'theano.sandbox.cuda.CudaNdarray.zeros', 'cuda_ndarray.CudaNdarray.zeros', (['(3, 4, 5)'], {}), '((3, 4, 5))\n', (30421, 30432), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((30446, 30455), 'six.moves.xrange', 'xrange', (['(5)'], {}), '(5)\n', (30452, 30455), False, 'from six.moves import xrange\n'), ((30683, 30721), 'theano.sandbox.cuda.CudaNdarray.zeros', 'cuda_ndarray.CudaNdarray.zeros', (['(5, 5)'], {}), '((5, 5))\n', (30713, 30721), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((31244, 31285), 'theano.sandbox.cuda.CudaNdarray.zeros', 'cuda_ndarray.CudaNdarray.zeros', (['(3, 4, 5)'], {}), '((3, 4, 5))\n', (31274, 31285), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((1071, 1098), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (1095, 1098), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((1111, 1127), 'numpy.asarray', 'numpy.asarray', (['b'], {}), '(b)\n', (1124, 1127), False, 'import numpy\n'), ((1143, 1160), 'numpy.all', 'numpy.all', (['(a == c)'], {}), '(a == c)\n', (1152, 1160), False, 'import numpy\n'), ((1208, 1241), 'numpy.asarray', 'numpy.asarray', (['b'], {'dtype': '"""float32"""'}), "(b, dtype='float32')\n", (1221, 1241), False, 'import numpy\n'), ((1257, 1274), 'numpy.all', 'numpy.all', (['(a == d)'], {}), '(a == d)\n', (1266, 1274), False, 'import numpy\n'), ((3133, 3161), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a0'], {}), '(a0)\n', (3157, 3161), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((3175, 3203), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a1'], {}), '(a1)\n', (3199, 3203), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((3765, 3793), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a0'], {}), '(a0)\n', (3789, 3793), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((4592, 4624), 'numpy.allclose', 'numpy.allclose', (['a0', '(a0_orig + a1)'], {}), '(a0, a0_orig + a1)\n', (4606, 4624), False, 'import numpy\n'), ((4728, 4767), 'numpy.allclose', 'numpy.allclose', (['a0', '((a0_orig + a1) / a1)'], {}), '(a0, (a0_orig + a1) / a1)\n', (4742, 4767), False, 'import numpy\n'), ((4948, 5003), 'numpy.allclose', 'numpy.allclose', (['a0', '((a0_orig + a1) / a1 + a1[..., ::-1])'], {}), '(a0, (a0_orig + a1) / a1 + a1[..., ::-1])\n', (4962, 5003), False, 'import numpy\n'), ((5118, 5191), 'numpy.allclose', 'numpy.allclose', (['a0', '(((a0_orig + a1) / a1 + a1[..., ::-1]) / a1[..., ::-1])'], {}), '(a0, ((a0_orig + a1) / a1 + a1[..., ::-1]) / a1[..., ::-1])\n', (5132, 5191), False, 'import numpy\n'), ((5548, 5576), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a0'], {}), '(a0)\n', (5572, 5576), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((5585, 5613), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a1'], {}), '(a1)\n', (5609, 5613), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((5653, 5666), 'numpy.exp', 'numpy.exp', (['a1'], {}), '(a1)\n', (5662, 5666), False, 'import numpy\n'), ((5996, 6021), 'numpy.random.rand', 'numpy.random.rand', (['*shape'], {}), '(*shape)\n', (6013, 6021), False, 'import numpy\n'), ((6327, 6343), 'numpy.asarray', 'numpy.asarray', (['b'], {}), '(b)\n', (6340, 6343), False, 'import numpy\n'), ((6374, 6390), 'numpy.asarray', 'numpy.asarray', (['c'], {}), '(c)\n', (6387, 6390), False, 'import numpy\n'), ((6421, 6437), 'numpy.asarray', 'numpy.asarray', (['d'], {}), '(d)\n', (6434, 6437), False, 'import numpy\n'), ((6483, 6499), 'numpy.asarray', 'numpy.asarray', (['b'], {}), '(b)\n', (6496, 6499), False, 'import numpy\n'), ((6534, 6550), 'numpy.asarray', 'numpy.asarray', (['c'], {}), '(c)\n', (6547, 6550), False, 'import numpy\n'), ((6581, 6597), 'numpy.asarray', 'numpy.asarray', (['d'], {}), '(d)\n', (6594, 6597), False, 'import numpy\n'), ((6913, 6938), 'numpy.random.rand', 'numpy.random.rand', (['*shape'], {}), '(*shape)\n', (6930, 6938), False, 'import numpy\n'), ((6987, 7015), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['aa'], {}), '(aa)\n', (7011, 7015), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((7102, 7118), 'numpy.asarray', 'numpy.asarray', (['b'], {}), '(b)\n', (7115, 7118), False, 'import numpy\n'), ((7149, 7165), 'numpy.asarray', 'numpy.asarray', (['c'], {}), '(c)\n', (7162, 7165), False, 'import numpy\n'), ((7196, 7212), 'numpy.asarray', 'numpy.asarray', (['d'], {}), '(d)\n', (7209, 7212), False, 'import numpy\n'), ((7258, 7274), 'numpy.asarray', 'numpy.asarray', (['b'], {}), '(b)\n', (7271, 7274), False, 'import numpy\n'), ((7309, 7325), 'numpy.asarray', 'numpy.asarray', (['c'], {}), '(c)\n', (7322, 7325), False, 'import numpy\n'), ((7356, 7372), 'numpy.asarray', 'numpy.asarray', (['d'], {}), '(d)\n', (7369, 7372), False, 'import numpy\n'), ((7457, 7471), 'theano.tests.unittest_tools.seed_rng', 'utt.seed_rng', ([], {}), '()\n', (7469, 7471), True, 'from theano.tests import unittest_tools as utt\n'), ((7623, 7650), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (7647, 7650), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((7897, 7924), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (7921, 7924), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((8131, 8158), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (8155, 8158), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((8319, 8346), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (8343, 8346), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((8669, 8696), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (8693, 8696), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((9060, 9087), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (9084, 9087), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((9263, 9290), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (9287, 9290), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((9494, 9521), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (9518, 9521), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((10224, 10251), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (10248, 10251), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((11038, 11054), 'theano.tests.unittest_tools.fetch_seed', 'utt.fetch_seed', ([], {}), '()\n', (11052, 11054), True, 'from theano.tests import unittest_tools as utt\n'), ((11274, 11291), 'numpy.dot', 'numpy.dot', (['a0', 'a1'], {}), '(a0, a1)\n', (11283, 11291), False, 'import numpy\n'), ((11293, 11317), 'theano.sandbox.cuda.dot', 'cuda_ndarray.dot', (['b0', 'b1'], {}), '(b0, b1)\n', (11309, 11317), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((11832, 11851), 'numpy.dot', 'numpy.dot', (['a0.T', 'a1'], {}), '(a0.T, a1)\n', (11841, 11851), False, 'import numpy\n'), ((12088, 12109), 'numpy.dot', 'numpy.dot', (['a0.T', 'a1.T'], {}), '(a0.T, a1.T)\n', (12097, 12109), False, 'import numpy\n'), ((14311, 14327), 'theano.tests.unittest_tools.fetch_seed', 'utt.fetch_seed', ([], {}), '()\n', (14325, 14327), True, 'from theano.tests import unittest_tools as utt\n'), ((14512, 14539), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (14536, 14539), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((14621, 14638), 'numpy.asarray', 'numpy.asarray', (['bb'], {}), '(bb)\n', (14634, 14638), False, 'import numpy\n'), ((14677, 14698), 'numpy.all', 'numpy.all', (['(aa == n_bb)'], {}), '(aa == n_bb)\n', (14686, 14698), False, 'import numpy\n'), ((14911, 14938), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (14935, 14938), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((15058, 15075), 'numpy.asarray', 'numpy.asarray', (['bb'], {}), '(bb)\n', (15071, 15075), False, 'import numpy\n'), ((15114, 15135), 'numpy.all', 'numpy.all', (['(aa == n_bb)'], {}), '(aa == n_bb)\n', (15123, 15135), False, 'import numpy\n'), ((15297, 15324), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (15321, 15324), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((16098, 16125), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['a'], {}), '(a)\n', (16122, 16125), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((17148, 17179), 'numpy.random.rand', 'numpy.random.rand', (['(30)', '(20)', '(5)', '(5)'], {}), '(30, 20, 5, 5)\n', (17165, 17179), False, 'import numpy\n'), ((17614, 17643), 'numpy.random.rand', 'numpy.random.rand', (['(5)', '(4)', '(3)', '(2)'], {}), '(5, 4, 3, 2)\n', (17631, 17643), False, 'import numpy\n'), ((17913, 17936), 'numpy.random.rand', 'numpy.random.rand', (['*dim'], {}), '(*dim)\n', (17930, 17936), False, 'import numpy\n'), ((18278, 18295), 'numpy.all', 'numpy.all', (['(x == y)'], {}), '(x == y)\n', (18287, 18295), False, 'import numpy\n'), ((18801, 18824), 'numpy.random.rand', 'numpy.random.rand', (['*dim'], {}), '(*dim)\n', (18818, 18824), False, 'import numpy\n'), ((18889, 18909), 'numpy.asarray', 'numpy.asarray', (['_a[1]'], {}), '(_a[1])\n', (18902, 18909), False, 'import numpy\n'), ((18926, 18947), 'numpy.asarray', 'numpy.asarray', (['_a[-1]'], {}), '(_a[-1])\n', (18939, 18947), False, 'import numpy\n'), ((18965, 18985), 'numpy.asarray', 'numpy.asarray', (['_a[0]'], {}), '(_a[0])\n', (18978, 18985), False, 'import numpy\n'), ((19002, 19024), 'numpy.asarray', 'numpy.asarray', (['_a[::1]'], {}), '(_a[::1])\n', (19015, 19024), False, 'import numpy\n'), ((19043, 19066), 'numpy.asarray', 'numpy.asarray', (['_a[::-1]'], {}), '(_a[::-1])\n', (19056, 19066), False, 'import numpy\n'), ((19086, 19108), 'numpy.asarray', 'numpy.asarray', (['_a[...]'], {}), '(_a[...])\n', (19099, 19108), False, 'import numpy\n'), ((19173, 19196), 'numpy.random.rand', 'numpy.random.rand', (['*dim'], {}), '(*dim)\n', (19190, 19196), False, 'import numpy\n'), ((19261, 19283), 'numpy.asarray', 'numpy.asarray', (['_a[...]'], {}), '(_a[...])\n', (19274, 19283), False, 'import numpy\n'), ((19383, 19406), 'numpy.random.rand', 'numpy.random.rand', (['*dim'], {}), '(*dim)\n', (19400, 19406), False, 'import numpy\n'), ((19701, 19721), 'numpy.asarray', 'numpy.asarray', (['_a[1]'], {}), '(_a[1])\n', (19714, 19721), False, 'import numpy\n'), ((19738, 19759), 'numpy.asarray', 'numpy.asarray', (['_a[-1]'], {}), '(_a[-1])\n', (19751, 19759), False, 'import numpy\n'), ((19928, 19949), 'numpy.asarray', 'numpy.asarray', (['_a[1:]'], {}), '(_a[1:])\n', (19941, 19949), False, 'import numpy\n'), ((19967, 19989), 'numpy.asarray', 'numpy.asarray', (['_a[1:2]'], {}), '(_a[1:2])\n', (19980, 19989), False, 'import numpy\n'), ((20008, 20031), 'numpy.asarray', 'numpy.asarray', (['_a[-1:1]'], {}), '(_a[-1:1])\n', (20021, 20031), False, 'import numpy\n'), ((20258, 20293), 'numpy.asarray', 'numpy.asarray', (['_a[:, :, ::-1, ::-1]'], {}), '(_a[:, :, ::-1, ::-1])\n', (20271, 20293), False, 'import numpy\n'), ((20325, 20362), 'numpy.asarray', 'numpy.asarray', (['_a[:, :, ::-10, ::-10]'], {}), '(_a[:, :, ::-10, ::-10])\n', (20338, 20362), False, 'import numpy\n'), ((20396, 20426), 'numpy.asarray', 'numpy.asarray', (['_a[:, :, 1, -1]'], {}), '(_a[:, :, 1, -1])\n', (20409, 20426), False, 'import numpy\n'), ((20453, 20483), 'numpy.asarray', 'numpy.asarray', (['_a[:, :, -1, :]'], {}), '(_a[:, :, -1, :])\n', (20466, 20483), False, 'import numpy\n'), ((20510, 20543), 'numpy.asarray', 'numpy.asarray', (['_a[:, ::-2, -1, :]'], {}), '(_a[:, ::-2, -1, :])\n', (20523, 20543), False, 'import numpy\n'), ((20573, 20607), 'numpy.asarray', 'numpy.asarray', (['_a[:, ::-20, -1, :]'], {}), '(_a[:, ::-20, -1, :])\n', (20586, 20607), False, 'import numpy\n'), ((20638, 20668), 'numpy.asarray', 'numpy.asarray', (['_a[:, ::-2, -1]'], {}), '(_a[:, ::-2, -1])\n', (20651, 20668), False, 'import numpy\n'), ((20695, 20725), 'numpy.asarray', 'numpy.asarray', (['_a[0, ::-2, -1]'], {}), '(_a[0, ::-2, -1])\n', (20708, 20725), False, 'import numpy\n'), ((20753, 20786), 'numpy.asarray', 'numpy.asarray', (['_a[-1, -1, -1, -2]'], {}), '(_a[-1, -1, -1, -2])\n', (20766, 20786), False, 'import numpy\n'), ((20816, 20838), 'numpy.asarray', 'numpy.asarray', (['_a[...]'], {}), '(_a[...])\n', (20829, 20838), False, 'import numpy\n'), ((20905, 20928), 'numpy.random.rand', 'numpy.random.rand', (['(5)', '(1)'], {}), '(5, 1)\n', (20922, 20928), False, 'import numpy\n'), ((21008, 21031), 'numpy.random.rand', 'numpy.random.rand', (['(1)', '(5)'], {}), '(1, 5)\n', (21025, 21031), False, 'import numpy\n'), ((21182, 21197), 'numpy.dot', 'numpy.dot', (['a', 'b'], {}), '(a, b)\n', (21191, 21197), False, 'import numpy\n'), ((21294, 21309), 'numpy.dot', 'numpy.dot', (['b', 'a'], {}), '(b, a)\n', (21303, 21309), False, 'import numpy\n'), ((21694, 21711), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (21707, 21711), False, 'import numpy\n'), ((21887, 21904), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (21900, 21904), False, 'import numpy\n'), ((22295, 22312), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (22308, 22312), False, 'import numpy\n'), ((22428, 22445), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (22441, 22445), False, 'import numpy\n'), ((22574, 22591), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (22587, 22591), False, 'import numpy\n'), ((22964, 22981), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (22977, 22981), False, 'import numpy\n'), ((23103, 23120), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (23116, 23120), False, 'import numpy\n'), ((23255, 23272), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (23268, 23272), False, 'import numpy\n'), ((25502, 25519), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (25515, 25519), False, 'import numpy\n'), ((25663, 25680), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (25676, 25680), False, 'import numpy\n'), ((26026, 26043), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (26039, 26043), False, 'import numpy\n'), ((26401, 26418), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (26414, 26418), False, 'import numpy\n'), ((26673, 26700), 'theano.sandbox.cuda.CudaNdarray', 'cuda_ndarray.CudaNdarray', (['b'], {}), '(b)\n', (26697, 26700), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((26815, 26832), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (26828, 26832), False, 'import numpy\n'), ((27149, 27166), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (27162, 27166), False, 'import numpy\n'), ((27486, 27503), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (27499, 27503), False, 'import numpy\n'), ((27859, 27876), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (27872, 27876), False, 'import numpy\n'), ((28478, 28495), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (28491, 28495), False, 'import numpy\n'), ((28758, 28775), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (28771, 28775), False, 'import numpy\n'), ((29088, 29105), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (29101, 29105), False, 'import numpy\n'), ((29291, 29308), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (29304, 29308), False, 'import numpy\n'), ((29400, 29435), 'theano.sandbox.cuda.CudaNdarray.zeros', 'cuda_ndarray.CudaNdarray.zeros', (['shp'], {}), '(shp)\n', (29430, 29435), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((29449, 29482), 'numpy.zeros', 'numpy.zeros', (['shp'], {'dtype': '"""float32"""'}), "(shp, dtype='float32')\n", (29460, 29482), False, 'import numpy\n'), ((29797, 29832), 'theano.sandbox.cuda.CudaNdarray.zeros', 'cuda_ndarray.CudaNdarray.zeros', (['shp'], {}), '(shp)\n', (29827, 29832), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((29846, 29879), 'numpy.zeros', 'numpy.zeros', (['shp'], {'dtype': '"""float32"""'}), "(shp, dtype='float32')\n", (29857, 29879), False, 'import numpy\n'), ((29992, 30005), 'numpy.zeros', 'numpy.zeros', ([], {}), '()\n', (30003, 30005), False, 'import numpy\n'), ((30123, 30155), 'theano.sandbox.cuda.CudaNdarray.zeros', 'cuda_ndarray.CudaNdarray.zeros', ([], {}), '()\n', (30153, 30155), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((1015, 1040), 'numpy.random.rand', 'numpy.random.rand', (['*shape'], {}), '(*shape)\n', (1032, 1040), False, 'import numpy\n'), ((1339, 1369), 'numpy.asarray', 'numpy.asarray', (['b'], {'dtype': '"""int8"""'}), "(b, dtype='int8')\n", (1352, 1369), False, 'import numpy\n'), ((2833, 2855), 'numpy.allclose', 'numpy.allclose', (['a0', 'a1'], {}), '(a0, a1)\n', (2847, 2855), False, 'import numpy\n'), ((3238, 3255), 'numpy.asarray', 'numpy.asarray', (['b0'], {}), '(b0)\n', (3251, 3255), False, 'import numpy\n'), ((3291, 3308), 'numpy.asarray', 'numpy.asarray', (['b1'], {}), '(b1)\n', (3304, 3308), False, 'import numpy\n'), ((4558, 4575), 'numpy.asarray', 'numpy.asarray', (['b0'], {}), '(b0)\n', (4571, 4575), False, 'import numpy\n'), ((4694, 4711), 'numpy.asarray', 'numpy.asarray', (['b0'], {}), '(b0)\n', (4707, 4711), False, 'import numpy\n'), ((4914, 4931), 'numpy.asarray', 'numpy.asarray', (['b0'], {}), '(b0)\n', (4927, 4931), False, 'import numpy\n'), ((5084, 5101), 'numpy.asarray', 'numpy.asarray', (['b0'], {}), '(b0)\n', (5097, 5101), False, 'import numpy\n'), ((5468, 5493), 'numpy.random.rand', 'numpy.random.rand', (['*shape'], {}), '(*shape)\n', (5485, 5493), False, 'import numpy\n'), ((7511, 7527), 'theano.tests.unittest_tools.fetch_seed', 'utt.fetch_seed', ([], {}), '()\n', (7525, 7527), True, 'from theano.tests import unittest_tools as utt\n'), ((7681, 7699), 'numpy.transpose', 'numpy.transpose', (['a'], {}), '(a)\n', (7696, 7699), False, 'import numpy\n'), ((7731, 7761), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '()'], {}), '(b, ())\n', (7754, 7761), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((8377, 8395), 'numpy.transpose', 'numpy.transpose', (['a'], {}), '(a)\n', (8392, 8395), False, 'import numpy\n'), ((8427, 8459), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(0,)'], {}), '(b, (0,))\n', (8450, 8459), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((8539, 8578), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(-1, 0, -1)'], {}), '(b, (-1, 0, -1))\n', (8562, 8578), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((8727, 8745), 'numpy.transpose', 'numpy.transpose', (['a'], {}), '(a)\n', (8742, 8745), False, 'import numpy\n'), ((8777, 8811), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(1, 0)'], {}), '(b, (1, 0))\n', (8800, 8811), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((8917, 8963), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(-1, 1, -1, 0, -1)'], {}), '(b, (-1, 1, -1, 0, -1))\n', (8940, 8963), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((9154, 9186), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(1,)'], {}), '(b, (1,))\n', (9177, 9186), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((9369, 9401), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(0,)'], {}), '(b, (0,))\n', (9392, 9401), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((9555, 9592), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(0, 1, 2)'], {}), '(b, (0, 1, 2))\n', (9578, 9592), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((9624, 9647), 'numpy.swapaxes', 'numpy.swapaxes', (['a', '(0)', '(1)'], {}), '(a, 0, 1)\n', (9638, 9647), False, 'import numpy\n'), ((9679, 9716), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(1, 0, 2)'], {}), '(b, (1, 0, 2))\n', (9702, 9716), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((9748, 9771), 'numpy.swapaxes', 'numpy.swapaxes', (['a', '(0)', '(2)'], {}), '(a, 0, 2)\n', (9762, 9771), False, 'import numpy\n'), ((9803, 9840), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(2, 1, 0)'], {}), '(b, (2, 1, 0))\n', (9826, 9840), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((9872, 9895), 'numpy.swapaxes', 'numpy.swapaxes', (['a', '(1)', '(2)'], {}), '(a, 1, 2)\n', (9886, 9895), False, 'import numpy\n'), ((9927, 9964), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(0, 2, 1)'], {}), '(b, (0, 2, 1))\n', (9950, 9964), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((10078, 10127), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(-1, 0, -1, 2, 1, -1)'], {}), '(b, (-1, 0, -1, 2, 1, -1))\n', (10101, 10127), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((10282, 10305), 'numpy.swapaxes', 'numpy.swapaxes', (['a', '(0)', '(1)'], {}), '(a, 0, 1)\n', (10296, 10305), False, 'import numpy\n'), ((10337, 10377), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(1, 0, 2, 3)'], {}), '(b, (1, 0, 2, 3))\n', (10360, 10377), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((10409, 10432), 'numpy.swapaxes', 'numpy.swapaxes', (['a', '(0)', '(2)'], {}), '(a, 0, 2)\n', (10423, 10432), False, 'import numpy\n'), ((10464, 10504), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(2, 1, 0, 3)'], {}), '(b, (2, 1, 0, 3))\n', (10487, 10504), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((10536, 10559), 'numpy.swapaxes', 'numpy.swapaxes', (['a', '(0)', '(3)'], {}), '(a, 0, 3)\n', (10550, 10559), False, 'import numpy\n'), ((10591, 10631), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(3, 1, 2, 0)'], {}), '(b, (3, 1, 2, 0))\n', (10614, 10631), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((10663, 10686), 'numpy.swapaxes', 'numpy.swapaxes', (['a', '(0)', '(3)'], {}), '(a, 0, 3)\n', (10677, 10686), False, 'import numpy\n'), ((10718, 10758), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(3, 1, 2, 0)'], {}), '(b, (3, 1, 2, 0))\n', (10741, 10758), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((10869, 10917), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b', '(-1, 3, -1, 1, 2, 0)'], {}), '(b, (-1, 3, -1, 1, 2, 0))\n', (10892, 10917), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((11917, 11952), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b0', '(1, 0)'], {}), '(b0, (1, 0))\n', (11940, 11952), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((12136, 12171), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b0', '(1, 0)'], {}), '(b0, (1, 0))\n', (12159, 12171), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((12198, 12233), 'theano.sandbox.cuda.dimshuffle', 'cuda_ndarray.dimshuffle', (['b1', '(1, 0)'], {}), '(b1, (1, 0))\n', (12221, 12233), True, 'import theano.sandbox.cuda as cuda_ndarray\n'), ((16040, 16067), 'numpy.random.rand', 'numpy.random.rand', (['*shape_1'], {}), '(*shape_1)\n', (16057, 16067), False, 'import numpy\n'), ((17523, 17549), 'numpy.asarray', 'numpy.asarray', (['a_view_copy'], {}), '(a_view_copy)\n', (17536, 17549), False, 'import numpy\n'), ((18202, 18219), 'numpy.all', 'numpy.all', (['(x == y)'], {}), '(x == y)\n', (18211, 18219), False, 'import numpy\n'), ((19814, 19828), 'numpy.int64', 'numpy.int64', (['(1)'], {}), '(1)\n', (19825, 19828), False, 'import numpy\n'), ((19878, 19893), 'numpy.int64', 'numpy.int64', (['(-1)'], {}), '(-1)\n', (19889, 19893), False, 'import numpy\n'), ((28647, 28670), 'numpy.random.rand', 'numpy.random.rand', (['(4)', '(5)'], {}), '(4, 5)\n', (28664, 28670), False, 'import numpy\n'), ((29513, 29530), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (29526, 29530), False, 'import numpy\n'), ((29910, 29927), 'numpy.asarray', 'numpy.asarray', (['_a'], {}), '(_a)\n', (29923, 29927), False, 'import numpy\n'), ((2711, 2736), 'numpy.random.rand', 'numpy.random.rand', (['*shape'], {}), '(*shape)\n', (2728, 2736), False, 'import numpy\n'), ((2965, 2990), 'numpy.random.rand', 'numpy.random.rand', (['*shape'], {}), '(*shape)\n', (2982, 2990), False, 'import numpy\n'), ((3074, 3100), 'numpy.random.rand', 'numpy.random.rand', (['*shape2'], {}), '(*shape2)\n', (3091, 3100), False, 'import numpy\n'), ((3623, 3642), 'numpy.asarray', 'numpy.asarray', (['bsum'], {}), '(bsum)\n', (3636, 3642), False, 'import numpy\n'), ((5862, 5881), 'numpy.asarray', 'numpy.asarray', (['bsum'], {}), '(bsum)\n', (5875, 5881), False, 'import numpy\n'), ((8843, 8861), 'numpy.transpose', 'numpy.transpose', (['a'], {}), '(a)\n', (8858, 8861), False, 'import numpy\n'), ((9996, 10019), 'numpy.swapaxes', 'numpy.swapaxes', (['a', '(1)', '(2)'], {}), '(a, 1, 2)\n', (10010, 10019), False, 'import numpy\n'), ((10790, 10813), 'numpy.swapaxes', 'numpy.swapaxes', (['a', '(0)', '(3)'], {}), '(a, 0, 3)\n', (10804, 10813), False, 'import numpy\n'), ((12298, 12331), 'numpy.arange', 'numpy.arange', (['(shape[0] * shape[1])'], {}), '(shape[0] * shape[1])\n', (12310, 12331), False, 'import numpy\n'), ((12984, 13019), 'numpy.arange', 'numpy.arange', (['(3 * 4 * 5 * 6 * 7 * 8)'], {}), '(3 * 4 * 5 * 6 * 7 * 8)\n', (12996, 13019), False, 'import numpy\n'), ((13307, 13330), 'numpy.arange', 'numpy.arange', (['(16 * 2048)'], {}), '(16 * 2048)\n', (13319, 13330), False, 'import numpy\n'), ((13554, 13571), 'numpy.arange', 'numpy.arange', (['(160)'], {}), '(160)\n', (13566, 13571), False, 'import numpy\n'), ((19794, 19808), 'numpy.int64', 'numpy.int64', (['(1)'], {}), '(1)\n', (19805, 19808), False, 'import numpy\n'), ((19857, 19872), 'numpy.int64', 'numpy.int64', (['(-1)'], {}), '(-1)\n', (19868, 19872), False, 'import numpy\n'), ((20211, 20225), 'numpy.int64', 'numpy.int64', (['(1)'], {}), '(1)\n', (20222, 20225), False, 'import numpy\n'), ((29606, 29631), 'numpy.asarray', 'numpy.asarray', (['_n.strides'], {}), '(_n.strides)\n', (29619, 29631), False, 'import numpy\n'), ((20133, 20148), 'numpy.int64', 'numpy.int64', (['(-1)'], {}), '(-1)\n', (20144, 20148), False, 'import numpy\n')]
from .base import Strategy, Transform from summit.domain import * from summit.domain import Domain from summit.utils.dataset import DataSet from summit.utils import jsonify_dict, unjsonify_dict import numpy as np import pandas as pd from scipy.optimize import OptimizeResult class NelderMead(Strategy): """Nelder-Mead Simplex A reimplementation of the Nelder-Mead Simplex method adapted for sequential calls. This includes adaptions in terms of reflecting points, dimension reduction and dimension recovery proposed by Cortes-Borda et al. Parameters ---------- domain : :class:`~summit.domain.Domain` The domain of the optimization transform : :class:`~summit.strategies.base.Transform`, optional A transform object. By default no transformation will be done on the input variables or objectives. random_start : bool, optional Whether to start at a random point or the value specified by x_start adaptive : bool, optional Adapt algorithm parameters to dimensionality of problem. Useful for high-dimensional minimization. Default is False. x_start: array_like of shape (1, N), optional Initial center point of simplex Default: empty list that will initialize generation of x_start as geoemetrical center point of bounds Note that x_start is ignored when initial call of suggest_exp contains prev_res and/or prev_param dx: float, optional Parameter for stopping criterion: two points are considered to be different if they differ by at least dx(i) in at least one coordinate i. Default is 1E-5. df: float, optional Parameter for stopping criterion: two function values are considered to be different if they differ by at least df. Default is 1E-5. Notes ----- This is inspired by the work by [Cortés-Borda]_. Implementation partly follows the Nelder-Mead Simplex implementation in `scipy-optimize <https://github.com/scipy/scipy/blob/master/scipy/optimize/optimize.py>`_ After the initialisation, the number of suggested experiments depends on the internal state of Nelder Mead. Usually the algorithm requests 1 point per iteration, e.g., a reflection. In some cases it requests more than 1 point, e.g., for shrinking the simplex. References ---------- .. [Cortés-Borda] <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>.; Truchet, C.; <NAME>.; <NAME>. Optimizing the Heck–Matsuda Reaction in Flow with a Constraint-Adapted Direct Search Algorithm. Organic ProcessResearch & Development 2016,20, 1979–1987 Examples -------- >>> from summit.domain import Domain, ContinuousVariable >>> from summit.strategies import NelderMead >>> domain = Domain() >>> domain += ContinuousVariable(name='temperature', description='reaction temperature in celsius', bounds=[0, 1]) >>> domain += ContinuousVariable(name='flowrate_a', description='flow of reactant a in mL/min', bounds=[0, 1]) >>> domain += ContinuousVariable(name='yield', description='relative conversion to xyz', bounds=[0,100], is_objective=True, maximize=True) >>> strategy = NelderMead(domain) >>> next_experiments = strategy.suggest_experiments() >>> print(next_experiments) NAME temperature flowrate_a strategy TYPE DATA DATA METADATA 0 0.500 0.500 Nelder-Mead Simplex 1 0.625 0.500 Nelder-Mead Simplex 2 0.500 0.625 Nelder-Mead Simplex """ def __init__(self, domain: Domain, transform: Transform = None, **kwargs): Strategy.__init__(self, domain, transform, **kwargs) self._x_start = kwargs.get("x_start", []) self.random_start = kwargs.get("random_start", False) self._dx = kwargs.get("dx", 1e-5) self._df = kwargs.get("df", 1e-5) self._adaptive = kwargs.get("adaptive", False) self.prev_param = None def suggest_experiments(self, prev_res: DataSet = None, **kwargs): """Suggest experiments using Nelder-Mead Simplex method Parameters ---------- prev_res: summit.utils.data.DataSet, optional Dataset with data from previous experiments. If no data is passed, the Nelder-Mead optimization algorithm will be initialized and suggest initial experiments. Returns ------- next_experiments: DataSet A `Dataset` object with the suggested experiments by Nelder-Mead Simplex algorithm Notes ------ After the initialisation, the number of suggested experiments depends on the internal state of Nelder Mead. Usually the algorithm requests 1 point per iteration, e.g., a reflection. In some cases it requests more than 1 point, e.g., for shrinking the simplex. Thus, there is no `num_experiments` keyword argument. """ # get objective name and whether optimization is maximization problem obj_name = None obj_maximize = False for v in self.domain.variables: i = 0 if v.is_objective: i += 1 if i > 1: raise ValueError( "Nelder-Mead is not able to optimize multiple objectives." ) obj_name = v.name if v.maximize: obj_maximize = True # get results from conducted experiments if prev_res is not None: prev_res = prev_res # get parameters from previous iterations inner_prev_param = None if self.prev_param is not None: # get parameters for Nelder-Mead from previous iterations inner_prev_param = self.prev_param[0] # recover invalid experiments from previous iteration if self.prev_param[1] is not None: invalid_res = self.prev_param[1].drop(("constraint", "DATA"), 1) prev_res = pd.concat([prev_res, invalid_res]) ## Generation of new suggested experiments. # An inner function is called loop-wise to get valid experiments and # avoid suggestions of experiments that violate constraints. # If no valid experiment is found after #<inner_iter_tol>, an error is raised. inner_iter_tol = 5 c_iter = 0 valid_next_experiments = False next_experiments = None while not valid_next_experiments and c_iter < inner_iter_tol: valid_next_experiments = False next_experiments, xbest, fbest, param = self._inner_suggest_experiments( prev_res=prev_res, prev_param=inner_prev_param ) # Invalid experiments hidden from data returned to user but stored internally in param invalid_experiments = next_experiments.loc[ next_experiments[("constraint", "DATA")] == False ] next_experiments = next_experiments.loc[ next_experiments[("constraint", "DATA")] != False ] prev_res = prev_res if len(next_experiments) and len(invalid_experiments): valid_next_experiments = True if obj_maximize: invalid_experiments[(obj_name, "DATA")] = float("-inf") else: invalid_experiments[(obj_name, "DATA")] = float("inf") # elif len(invalid_experiments): if obj_maximize: invalid_experiments[(obj_name, "DATA")] = float("-inf") else: invalid_experiments[(obj_name, "DATA")] = float("inf") prev_res = invalid_experiments else: valid_next_experiments = True inner_prev_param = param param = [param, invalid_experiments] c_iter += 1 if c_iter >= inner_iter_tol: raise ValueError( "No new points found. Internal stopping criterion is reached." ) # return only valid experiments (invalid experiments are stored in param[1]) next_experiments = next_experiments.drop(("constraint", "DATA"), 1) objective_dir = -1.0 if obj_maximize else 1.0 self.fbest = objective_dir * fbest self.xbest = xbest self.prev_param = param return next_experiments def reset(self): """Reset internal parameters""" self.prev_param = None def to_dict(self): # Previous param first element is a dictionary of internal parameters # Second element is a dataset with invalid experiments if self.prev_param is not None: prev_param = [ jsonify_dict(self.prev_param[0]), self.prev_param[1].to_dict(), ] else: prev_param = None strategy_params = dict( x_start=self._x_start, random_start=self.random_start, dx=self._dx, df=self._df, adaptive=self._adaptive, prev_param=prev_param, ) return super().to_dict(**strategy_params) @classmethod def from_dict(cls, d): nm = super().from_dict(d) prev_param = d["strategy_params"]["prev_param"] if prev_param is not None: nm.prev_param = [ unjsonify_dict(prev_param[0]), DataSet.from_dict(prev_param[1]), ] return nm def _inner_suggest_experiments(self, prev_res: DataSet = None, prev_param=None): """Inner loop for suggestion of experiments using Nelder-Mead Simplex method Parameters ---------- prev_res: summit.utils.data.DataSet, optional Dataset with data from previous experiments. If no data is passed, the Nelder-Mead optimization algorithm will be initialized and suggest initial experiments. prev_param: Parameters of Nelder-Mead algorithm from previous iterations of a optimization problem. If no data is passed, the Nelder-Mead optimization algorithm will be initialized. """ # intern stay_inner = False # Get bounds of input variables bounds = [] input_var_names = [] output_var_names = [] for v in self.domain.variables: if not v.is_objective: if isinstance(v, ContinuousVariable): bounds.append(v.bounds) input_var_names.append(v.name) elif isinstance(v, CategoricalVariable): if v.ds is not None: descriptor_names = v.ds.data_columns descriptors = np.asarray( [ v.ds.loc[:, [l]].values.tolist() for l in v.ds.data_columns ] ) else: raise ValueError("No descriptors given for {}".format(v.name)) for d in descriptors: bounds.append([np.min(np.asarray(d)), np.max(np.asarray(d))]) input_var_names.extend(descriptor_names) else: raise TypeError( "Nelder-Mead can not handle variable type: {}".format(v.type) ) else: output_var_names.extend(v.name) bounds = np.asarray(bounds, dtype=float) # Extract dimension of input domain dim = len(bounds[:, 0]) # Initialization initial_run = True x0 = [self._x_start] y0 = [] # Get previous results if prev_res is not None: initial_run = False inputs, outputs = self.transform.transform_inputs_outputs( prev_res, categorical_method="descriptors" ) # Set up maximization and minimization for v in self.domain.variables: if v.is_objective and v.maximize: outputs[v.name] = -1 * outputs[v.name] x0 = inputs.data_to_numpy() y0 = outputs.data_to_numpy() elif prev_param is not None: raise ValueError( "Parameter from previous optimization iteration are given but previous results are " "missing!" ) # if no previous results are given initialize center point as geometrical middle point of bounds if len(x0[0]) == 0 and not self.random_start: x0 = np.ones((1, len(bounds))) * 0.5 * ((bounds[:, 1] + bounds[:, 0]).T) elif len(x0[0]) == 0 and self.random_start: weight = np.random.rand() x0 = np.ones((1, len(bounds))) * ( weight * (bounds[:, 1] + (1 - weight) * bounds[:, 0]).T ) """ Set Nelder-Mead parameters, i.e., initialize or include data from previous iterations -------- prev_sim: array-like variable coordinates (points) of simplex from previous run prev_fsim: array-like function values corresponding to points of simplex from previous run x_iter: array-like variable coordinates and corresponding function values of potential new simplex points determined in one iteration of the NMS algorithm; note that within one iteration multiple points need to be evaluated; that's why we have to store the points of an unfinished iteration (start iteration -> request point -> run experiment -> restart same iteration with results of experiment -> request point -> run experiment ... -> finish iteration) red_dim: boolean True if dimension was reduced in one of the previous iteration and has not been recovered yet red_sim: array-like variable coordinates (points) of simplex before dimension was reduced red_fsim: array-like function values of points corresponding to simplex before dimension was reduced rec_dim: boolean True if dimension was revocered in last iteration memory: array-like list of all points for which the function was evaluated """ prev_sim, prev_fsim, x_iter, red_dim, red_sim, red_fsim, rec_dim, memory = ( None, None, None, None, None, None, None, [np.ones(dim) * float("inf")], ) # if this is not the first iteration of the Nelder-Mead algorithm, get parameters from previous iteration if prev_param: prev_sim = prev_param["sim"] red_dim = prev_param["red_dim"] red_sim = prev_param["red_sim"] red_fsim = prev_param["red_fsim"] rec_dim = prev_param["rec_dim"] memory = prev_param["memory"] # if dimension was recovered in last iteration, N functions evaluations were requested # that need to be assigned to the respective points in the simplex if rec_dim: prev_fsim = prev_param["fsim"] for k in range(len(x0)): for s in range(len(prev_sim)): if np.array_equal(prev_sim[s], x0[k]): prev_fsim[s] = y0[k] rec_dim = False # assign function values to respective points elif prev_param["fsim"] is not None: prev_fsim = prev_param["fsim"] x_iter = prev_param["x_iter"] for key, value in x_iter.items(): if value is not None: if key == "x_shrink": for k in range(len(x0)): for j in range(len(value)): if np.array_equal(value[j][0], np.asarray(x0[k])): x_iter[key][j][1] = y0[k] else: for k in range(len(x0)): if np.array_equal(value[0], np.asarray(x0[k])): x_iter[key][1] = y0[k] break else: prev_fsim = y0 # initialize with given simplex points (including function evaluations) for initialization elif prev_res is not None: prev_sim = x0 prev_fsim = y0 for p in x0.astype(float).tolist(): memory.append(p) # Run Nelder-Mead Simplex algorithm for one iteration overfull_simplex = False if not red_dim: request, sim, fsim, x_iter = self._minimize_neldermead( x0=x0[0], bounds=bounds, x_iter=x_iter, f=prev_fsim, sim=prev_sim, adaptive=self._adaptive, ) if not initial_run: ( overfull_simplex, prev_sim, prev_fsim, red_sim, red_fsim, overfull_dim, ) = self.check_overfull(request, sim, fsim, bounds) ## Reduce dimension if n+1 points are located in n-1 dimensions (if either red_dim = True, i.e., # optimization in the reduced dimension space was not finished in the last iteration, or overfull_simplex, i.e., # last Nelder-Mead call (with red_dim = False) lead to an overfull simplex). ## Note that in order to not loose any information, the simplex without dimension reduction is returned even # if the optimization in the reduced dimension space is not finished. ## If the optimization in the reduced dimension space was not finished in the last iteration (red_dim = True), # the simplex will automatically be reduced again. if red_dim or overfull_simplex: # prepare dimension reduction if red_dim: x_iter, overfull_dim = self.upstream_simplex_dim_red(prev_sim, x_iter) else: x_iter = None # save value of dimension reduced save_dim = prev_sim[0][overfull_dim] # delete overfull dimension new_prev_sim = np.delete(prev_sim, overfull_dim, 1) # delete bounds for overfull dimension new_bounds = np.delete(bounds, overfull_dim, 0) # Run one iteration of Nelder-Mead Simplex algorithm for reduced simplex request, sim, fsim, x_iter = self._minimize_neldermead( x0=new_prev_sim[0], x_iter=x_iter, bounds=new_bounds, f=prev_fsim, sim=new_prev_sim, adaptive=self._adaptive, ) overfull_simplex, _, _, _, _, _ = self.check_overfull( request, sim, fsim, bounds ) if overfull_simplex: raise NotImplementedError( "Recursive dimension reduction not implemented yet." ) # recover dimension after Nelder-Mead Simplex run (to return full request for experiment) request = np.insert(request, overfull_dim, save_dim, 1) sim = np.insert(sim, overfull_dim, save_dim, 1) # follow-up of dimension reduction x_iter = self.downstream_simplex_dim_red(x_iter, overfull_dim, save_dim) red_dim = True # if not overfull and no reduced dimension from previous iteration else: red_dim = False # Circle (suggested point that already has been investigated) if any(np.array([np.array(memory == x).all(1).any() for x in request])): ## if dimension is reduced and requested point has already been evaluated, recover dimension with # reflected and translated simplex before dimension reduction if red_dim: sim, fsim, request = self.recover_simplex_dim( sim, red_sim, red_fsim, overfull_dim, bounds, memory, self._dx ) red_dim = False rec_dim = True # raise error else: stay_inner = True # raise NotImplementedError("Circle - point has already been investigated.") ## Only little changes in requested points, xatol = tolerance for changes in x, # or in function values, fatol = tolerance for changes in f ## TODO: add extra threshold to stop reduced dimension problem and recover dimension if not initial_run: xatol = (bounds[:, 1] - bounds[:, 0]) * self._dx fatol = self._df if (np.max(np.abs(sim[1:] - sim[0]), 0) <= xatol).all() or ( np.max(np.abs(fsim[0] - fsim[1:])) <= fatol ).any(): if red_dim: sim, fsim, request = self.recover_simplex_dim( sim, red_sim, red_fsim, overfull_dim, bounds, memory, self._dx ) red_dim = False rec_dim = True else: print( "Warning, internal stopping criterion is reached. " "Either points of simplex or function values of points of simplex are very close to each other." ) # add requested points to memory for p in request.astype(float).tolist(): memory.append(p) # store parameters of iteration as parameter array param = [sim, fsim, x_iter, red_dim, red_sim, red_fsim, rec_dim, memory] param = dict( sim=sim, fsim=fsim, x_iter=x_iter, red_dim=red_dim, red_sim=red_sim, red_fsim=red_fsim, rec_dim=rec_dim, memory=memory, ) # Generate DataSet object with variable values of next experiments next_experiments = {} for i, v in enumerate(input_var_names): next_experiments[v] = request[:, i] next_experiments = DataSet.from_df(pd.DataFrame(data=next_experiments)) # Violate constraint mask_valid_next_experiments = self.check_constraints(next_experiments) if initial_run and not all(mask_valid_next_experiments): raise ValueError( "Default initialization failed due to constraints. Please enter an initial simplex with feasible points" ) if not any(mask_valid_next_experiments): stay_inner = True if stay_inner: # add infinity as next_experiments[("constraint", "DATA")] = False else: # add optimization strategy next_experiments[("constraint", "DATA")] = mask_valid_next_experiments next_experiments[("strategy", "METADATA")] = ["Nelder-Mead Simplex"] * len( request ) x_best = None f_best = float("inf") # fbest corresponds to the transformed function values if not initial_run: x_best = sim[0] f_best = fsim[0] x_best = self.round(x_best, bounds, self._dx) f_best = int(f_best * 10 ** int(np.log10(1 / self._df))) / 10 ** int( np.log10(1 / self._df) ) # next_experiments = np.around(next_experiments, decimals=self._dx) # Do any necessary transformation back next_experiments = self.transform.un_transform( next_experiments, categorical_method="descriptors" ) return next_experiments, x_best, f_best, param # implementation partly follows: https://github.com/scipy/scipy/blob/master/scipy/optimize/optimize.py def _minimize_neldermead( self, x0, bounds, x_iter=None, f=None, sim=None, initial_simplex=None, adaptive=False, **unknown_options ): """ Minimization of scalar function of one or more variables using the Nelder-Mead algorithm. Options ------- x0: array_like of shape (1, N) x_iter: f: sim: initial_simplex : array_like of shape (N + 1, N) Initial simplex. If given, overrides `x0`. ``initial_simplex[j,:]`` should contain the coordinates of the jth vertex of the ``N+1`` vertices in the simplex, where ``N`` is the dimension. adaptive : bool, optional Adapt algorithm parameters to dimensionality of problem. Useful for high-dimensional minimization [1]. References ---------- .. [1] <NAME>. and <NAME>. Implementing the Nelder-Mead simplex algorithm with adaptive parameters. 2012. Computational Optimization and Applications. 51:1, pp. 259-277 """ if adaptive: dim = float(len(x0)) rho = 1 chi = 1 + 2 / dim psi = 0.75 - 1 / (2 * dim) sigma = 1 - 1 / dim else: rho = 1 chi = 2 psi = 0.5 sigma = 0.5 # TODO: discuss hyperparameter, find literature zdelt = 0.25 x0 = np.asfarray(x0).flatten() N = len(x0) # generate N points based on center point, each point varying in # one different variable compared to center point -> initial simplex with N+1 points if initial_simplex is None and sim is None: sim = np.zeros((N + 1, N), dtype=x0.dtype) sim[0] = x0 for k in range(N): y = np.array(x0, copy=True) y[k] = y[k] + zdelt * 1 / 2 * (bounds[k, 1] - bounds[k, 0]) bool, _, _ = self.check_bounds(y, bounds) # if point violates bound restriction, change variable in opposite direction if not bool: y[k] = y[k] - zdelt * (bounds[k, 1] - bounds[k, 0]) # if point violates constraint, try opposite direction # if point violates other constraint or bound, calculate max zdelt <zdelt_mod> that meets # constraint for both direction and choose direction with greater zdelt_mod # TODO: check constraints sim[k + 1] = y return sim, sim, None, None elif sim is None: sim = np.asfarray(initial_simplex).copy() if sim.ndim != 2 or sim.shape[0] != sim.shape[1] + 1: raise ValueError( "`initial_simplex` should be an array of shape (N+1,N)" ) if len(x0) != sim.shape[1]: raise ValueError( "Size of `initial_simplex` is not consistent with `x0`" ) N = sim.shape[1] else: sim = np.asfarray(sim).copy() if sim.ndim != 2 or sim.shape[0] != sim.shape[1] + 1: raise ValueError( "`initial_simplex` should be an array of shape (N+1,N)" ) if len(x0) != sim.shape[1]: raise ValueError( "Size of `initial_simplex` is not consistent with `x0`" ) N = sim.shape[1] one2np1 = list(range(1, N + 1)) fsim = np.zeros((N + 1,), float) for k in range(N + 1): fsim[k] = f[k] ind = np.argsort(fsim) fsim = np.take(fsim, ind, 0) sim = np.take(sim, ind, 0) # Catch information on previous experiment if not x_iter: x_iter = { "xbar": None, "xr": None, "xe": None, "xc": None, "xcc": None, "x_shrink": None, } # Iteration while 1: if not x_iter["xr"]: # Centroid point: xbar xbar = np.add.reduce(sim[:-1], 0) / N xbar = self.round(xbar, bounds, self._dx) x_iter["xbar"] = xbar # Reflection point xr xr = (1 + rho) * xbar - rho * sim[-1] for l in range(len(bounds)): _bool, i, b = self.check_bounds(xr, bounds) if _bool: break else: tmp_rho = np.min( np.max(np.abs((bounds[i][b] - xbar[i]))) / np.max(np.abs((xbar[i] - sim[-1][i]))) ) xr = (1 + tmp_rho) * xbar - tmp_rho * sim[-1] xr = self.round(xr, bounds, self._dx) x_iter["xr"] = [xr, None] return np.asarray([xr]), sim, fsim, x_iter xr = x_iter["xr"][0] fxr = x_iter["xr"][1] doshrink = 0 # if function value of reflected point is better than best point of simplex, determine expansion point if fxr < fsim[0]: if not x_iter["xe"]: # expansion point: xe xbar = x_iter["xbar"] xe = xr + chi * xbar - chi * sim[-1] for l in range(len(bounds)): _bool, i, b = self.check_bounds(xe, bounds) if _bool: break else: tmp_chi = np.min( np.max(np.abs((bounds[i][b] - xr[i]))) / np.max(np.abs((xbar[i] - sim[-1][i]))) ) xe = xr + tmp_chi * xbar - tmp_chi * sim[-1] xe = self.round(xe, bounds, self._dx) if np.array_equal(xe, xr): x_iter["xe"] = [xe, float("inf")] else: x_iter["xe"] = [xe, None] return np.asarray([xe]), sim, fsim, x_iter xe = x_iter["xe"][0] fxe = x_iter["xe"][1] # if expansion point is better than reflected point, # replace worst point of simplex by expansion point if fxe < fxr: sim[-1] = xe fsim[-1] = fxe # if reflected point is better than expansion point, # replace worst point of simplex by reflected point else: sim[-1] = xr fsim[-1] = fxr # if function value of reflected point is not better than best point of simplex... else: # fsim[0] <= fxr # ... but better than second worst point, # replace worst point of simplex by reflected point if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr # ... and not better than second worst point else: # fxr >= fsim[-2] # Perform contraction # if reflected point is better than worst point if fxr < fsim[-1]: # contracted point: xc if not x_iter["xc"]: xbar = x_iter["xbar"] # avoid division with zero (some coordinates of xbar, xr, and sim[-1] may be identical) # by applying np.max and np.min rho = np.min( np.max(np.abs(xr - xbar)) / np.max(np.abs((xbar - sim[-1]))) ) xc = (1 + psi * rho) * xbar - psi * rho * sim[-1] for l in range(len(bounds)): _bool, i, b = self.check_bounds(xc, bounds) if _bool: break else: tmp_psi = np.min( np.max(np.abs((bounds[i][b] - xr[i]))) / np.max(np.abs((xbar[i] - sim[-1][i]))) ) xc = ( 1 + tmp_psi * rho ) * xbar - tmp_psi * rho * sim[-1] xc = self.round(xc, bounds, self._dx) if np.array_equal(xc, xr): x_iter["xc"] = [xc, float("inf")] else: x_iter["xc"] = [xc, None] return np.asarray([xc]), sim, fsim, x_iter xc = x_iter["xc"][0] fxc = x_iter["xc"][1] # if contracted point is better than reflected point if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink = 1 # if reflected point is better than worst point else: # Perform an inside contraction if not x_iter["xcc"]: xbar = x_iter["xbar"] xcc = (1 - psi) * xbar + psi * sim[-1] xcc = self.round(xcc, bounds, self._dx) for l in range(len(bounds)): _bool, i, b = self.check_bounds(xcc, bounds) if _bool: break else: tmp_psi = np.min( np.max(np.abs((bounds[i][b] - xbar[i]))) / np.max(np.abs((sim[-1][i] - xbar[i]))) ) xcc = (1 - tmp_psi) * xbar + tmp_psi * sim[-1] xcc = self.round(xcc, bounds, self._dx) if np.array_equal(xcc, xr): x_iter["xcc"] = [xcc, None] else: x_iter["xcc"] = [xcc, None] return np.asarray([xcc]), sim, fsim, x_iter xcc = x_iter["xcc"][0] fxcc = x_iter["xcc"][1] if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 # shrink simplex for all x if doshrink: x_shrink = [] x_shrink_f = [] if not x_iter["x_shrink"]: for j in one2np1: sim[j] = sim[0] + sigma * (sim[j] - sim[0]) xj = sim[j] xj = self.round(xj, bounds, self._dx) x_shrink.append(xj) x_shrink_f.append([xj, None]) x_iter["x_shrink"] = x_shrink_f return np.asarray(x_shrink), sim, fsim, x_iter for j in one2np1: sim[j] = x_iter["x_shrink"][j - 1][0] fsim[j] = x_iter["x_shrink"][j - 1][1] x_iter = { "xbar": None, "xr": None, "xe": None, "xc": None, "xcc": None, "x_shrink": None, } ind = np.argsort(fsim) sim = np.take(sim, ind, 0) fsim = np.take(fsim, ind, 0) # Function to check whether a point x lies within the variable bounds of the domain def check_bounds(self, x, bounds): for i, b in enumerate(bounds): upper_b = b[1] < x[i] lower_b = b[0] > x[i] # Point violated bound constraints if upper_b or lower_b: if lower_b: return False, i, 0 else: return False, i, 1 return True, None, None # Function to check whether a point meets the constraints of the domain def check_constraints(self, tmp_next_experiments): constr_mask = np.asarray([True] * len(tmp_next_experiments)).T if len(self.domain.constraints) > 0: constr = [c.constraint_type + "0" for c in self.domain.constraints] constr_mask = [ pd.eval(c.lhs + constr[i], resolvers=[tmp_next_experiments]) for i, c in enumerate(self.domain.constraints) ] constr_mask = np.asarray([c.tolist() for c in constr_mask]).T constr_mask = constr_mask.all(1) return constr_mask # Function to check whether a simplex contains only points that are identical in one dimension and the # the variable value fo this dimension corresponds to the bound value def check_overfull(self, tmp_request, tmp_sim, tmp_fsim, bounds): test_sim = np.asarray(tmp_sim[:-1]) overfull_sim_dim = np.all(test_sim == test_sim[0, :], axis=0) for i in range(len(overfull_sim_dim)): if overfull_sim_dim[i]: if tmp_request[0][i] == test_sim[0][i]: if any(bounds[i] == test_sim[0][i]): overfull_dim = i prev_sim = tmp_sim[:-1] prev_fsim = tmp_fsim[:-1] red_sim = tmp_sim red_fsim = tmp_fsim return ( True, prev_sim, prev_fsim, red_sim, red_fsim, overfull_dim, ) else: raise ValueError( "Simplex is overfull in one dimension. Please increase threshold for stopping." ) return False, None, None, None, None, None # Prepare Nelder-Mead parameters and previous results for dimension reduction by removing overfull dimension def upstream_simplex_dim_red(self, tmp_prev_sim, tmp_x_iter): tmp_x_iter = tmp_x_iter overfull_sim_dim = np.all(tmp_prev_sim == tmp_prev_sim[0, :], axis=0) overfull_dim = np.where(overfull_sim_dim)[0][0] if tmp_x_iter: for key, value in tmp_x_iter.items(): if value is not None: if key is "xbar": tmp_x_iter[key] = np.delete(value, overfull_dim) continue if key is "x_shrink": for v in range(len(value)): tmp_x_iter[key][v] = [ np.delete(value[v][0], overfull_dim), value[v][1], ] continue tmp_x_iter[key] = [np.delete(value[0], overfull_dim), value[1]] return tmp_x_iter, overfull_dim else: return None, overfull_dim # Restore simplex after one call of Nelder-Mead with reduced dimension by adding overfull dimension. ## Note that if dimension reduction process is not finished, the simplex will reduced in the # next Nelder-Mead call again. def downstream_simplex_dim_red(self, tmp_x_iter, overfull_dim, save_dim): for key, value in tmp_x_iter.items(): if value is not None: if key is "xbar": tmp_x_iter[key] = np.insert(value, overfull_dim, save_dim) continue if key is "x_shrink": for v in range(len(value)): tmp_x_iter[key][v] = [ np.insert(value[v][0], overfull_dim, save_dim), value[v][1], ] continue tmp_x_iter[key] = [ np.insert(value[0], overfull_dim, save_dim), value[1], ] return tmp_x_iter ## Reflect and translate simplex from iteration before dimension with respect to the point that was found in the # reduced dimension problem. def recover_simplex_dim( self, tmp_sim, tmp_red_sim, tmp_red_fsim, overfull_dim, bounds, memory, dx ): ## Translate all points of the simplex before the reduction along the axis of the reduced dimension # but the one, that caused dimension reduction (translation distance corresponds to distance of point, that # caused the dimension reduction, to the values of all other points at axis of the reduced dimension) xr_red_dim = tmp_red_sim[-1][overfull_dim] - tmp_red_sim[0][overfull_dim] xr_red_dim = self.round( xr_red_dim, np.asarray([len(bounds) * [float("-inf"), float("inf")]]), dx ) new_sim = tmp_red_sim.copy() new_sim[:-1][:, [overfull_dim]] = ( tmp_red_sim[:-1][:, [overfull_dim]] + xr_red_dim ) ## Translate all points of the simplex before the reduction along the remaining axes but the one, that caused # dimension reduction (translation distance corresponds to distance of point, that caused the dimension # reduction, to optimal point found in reduced space optimization) for dim in range(len(tmp_red_sim[0])): if dim == overfull_dim: continue else: xt_red_dim = tmp_red_sim[-1][dim] - tmp_sim[0][dim] xt_red_dim = self.round( xt_red_dim, np.asarray([len(bounds) * [float("-inf"), float("inf")]]), dx, ) for s in range(len(new_sim[:-1])): xs = tmp_red_sim[s][dim] - xt_red_dim # TODO: check bounds here, what happens if more points violate bound constraints) if bounds[dim][0] > xs: xs = bounds[dim][0] elif bounds[dim][1] < xs: xs = bounds[dim][1] new_sim[s][dim] = xs # Alter simplex in case one point is twice into recovered simplex due to bound constraints p = 0 c_i = 0 while p < len(new_sim) and c_i < len(new_sim): l_new_sim = new_sim.tolist() x = l_new_sim.count(l_new_sim[p]) if x > 1: t_x = l_new_sim[p] for dim in range(len(t_x)): if t_x[dim] == bounds[dim, 0]: new_sim[p][dim] = new_sim[p][dim] + 0.25 * 1 / 2 * ( bounds[dim, 1] - bounds[dim, 0] ) new_sim[p] = self.round(new_sim[p], bounds, self._dx) p = 0 c_i += 1 elif t_x[dim] == bounds[dim, 1]: new_sim[p][dim] = new_sim[p][dim] - 0.25 * 1 / 2 * ( bounds[dim, 1] - bounds[dim, 0] ) new_sim[p] = self.round(new_sim[p], bounds, self._dx) p = 0 c_i += 1 else: c_i += 1 else: p += 1 new_sim[-1] = tmp_sim[0] sim = new_sim fsim = tmp_red_fsim fsim[-1] = fsim[0] request = sim[:-1] if any((memory == x).all(1).any() for x in request): len_req = len(request) len_req_mod = len_req i = 0 while i < len_req_mod: if (memory == request[i]).all(1).any(): fsim[i + len_req - len_req_mod] = float("inf") request = np.delete(request, i, 0) len_req_mod -= 1 else: i += 1 if len_req_mod == 0: raise ValueError( "Recovering dimension failed due to error in generating new points. " "Please increase threshold for stopping." ) return sim, fsim, request # adapted from the SQSnobFit package def round(self, x, bounds, dx): """ function x = round(x, bounds, dx) A point x is projected into the interior of [u, v] and x[i] is rounded to the nearest integer multiple of dx[i]. Input: x vector of length n bounds matrix of length nx2 such that bounds[:,0] < bounds[:,1] dx float Output: x projected and rounded version of x """ u = bounds[:, 0] v = bounds[:, 1] x = np.minimum(np.maximum(x, u), v) x = np.round(x / dx) * dx i1 = self.find(x < u) if i1.size > 0: x[i1] = x[i1] + dx i2 = self.find(x > v) if i2.size > 0: x[i2] = x[i2] - dx return x # adapted from the SQSnobFit package def find(self, cond_array): return (np.transpose(np.nonzero(cond_array.flatten()))).astype(int)
[ "numpy.log10", "numpy.random.rand", "numpy.argsort", "numpy.asfarray", "numpy.array", "summit.utils.jsonify_dict", "numpy.add.reduce", "numpy.where", "numpy.delete", "numpy.asarray", "numpy.take", "pandas.DataFrame", "numpy.maximum", "numpy.round", "numpy.abs", "numpy.ones", "summit....
[((11690, 11721), 'numpy.asarray', 'np.asarray', (['bounds'], {'dtype': 'float'}), '(bounds, dtype=float)\n', (11700, 11721), True, 'import numpy as np\n'), ((27909, 27934), 'numpy.zeros', 'np.zeros', (['(N + 1,)', 'float'], {}), '((N + 1,), float)\n', (27917, 27934), True, 'import numpy as np\n'), ((28009, 28025), 'numpy.argsort', 'np.argsort', (['fsim'], {}), '(fsim)\n', (28019, 28025), True, 'import numpy as np\n'), ((28041, 28062), 'numpy.take', 'np.take', (['fsim', 'ind', '(0)'], {}), '(fsim, ind, 0)\n', (28048, 28062), True, 'import numpy as np\n'), ((28077, 28097), 'numpy.take', 'np.take', (['sim', 'ind', '(0)'], {}), '(sim, ind, 0)\n', (28084, 28097), True, 'import numpy as np\n'), ((37960, 37984), 'numpy.asarray', 'np.asarray', (['tmp_sim[:-1]'], {}), '(tmp_sim[:-1])\n', (37970, 37984), True, 'import numpy as np\n'), ((38012, 38054), 'numpy.all', 'np.all', (['(test_sim == test_sim[0, :])'], {'axis': '(0)'}), '(test_sim == test_sim[0, :], axis=0)\n', (38018, 38054), True, 'import numpy as np\n'), ((39255, 39305), 'numpy.all', 'np.all', (['(tmp_prev_sim == tmp_prev_sim[0, :])'], {'axis': '(0)'}), '(tmp_prev_sim == tmp_prev_sim[0, :], axis=0)\n', (39261, 39305), True, 'import numpy as np\n'), ((18737, 18773), 'numpy.delete', 'np.delete', (['prev_sim', 'overfull_dim', '(1)'], {}), '(prev_sim, overfull_dim, 1)\n', (18746, 18773), True, 'import numpy as np\n'), ((18850, 18884), 'numpy.delete', 'np.delete', (['bounds', 'overfull_dim', '(0)'], {}), '(bounds, overfull_dim, 0)\n', (18859, 18884), True, 'import numpy as np\n'), ((19676, 19721), 'numpy.insert', 'np.insert', (['request', 'overfull_dim', 'save_dim', '(1)'], {}), '(request, overfull_dim, save_dim, 1)\n', (19685, 19721), True, 'import numpy as np\n'), ((19740, 19781), 'numpy.insert', 'np.insert', (['sim', 'overfull_dim', 'save_dim', '(1)'], {}), '(sim, overfull_dim, save_dim, 1)\n', (19749, 19781), True, 'import numpy as np\n'), ((22638, 22673), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'next_experiments'}), '(data=next_experiments)\n', (22650, 22673), True, 'import pandas as pd\n'), ((26089, 26125), 'numpy.zeros', 'np.zeros', (['(N + 1, N)'], {'dtype': 'x0.dtype'}), '((N + 1, N), dtype=x0.dtype)\n', (26097, 26125), True, 'import numpy as np\n'), ((36459, 36475), 'numpy.argsort', 'np.argsort', (['fsim'], {}), '(fsim)\n', (36469, 36475), True, 'import numpy as np\n'), ((36494, 36514), 'numpy.take', 'np.take', (['sim', 'ind', '(0)'], {}), '(sim, ind, 0)\n', (36501, 36514), True, 'import numpy as np\n'), ((36534, 36555), 'numpy.take', 'np.take', (['fsim', 'ind', '(0)'], {}), '(fsim, ind, 0)\n', (36541, 36555), True, 'import numpy as np\n'), ((45842, 45858), 'numpy.maximum', 'np.maximum', (['x', 'u'], {}), '(x, u)\n', (45852, 45858), True, 'import numpy as np\n'), ((45875, 45891), 'numpy.round', 'np.round', (['(x / dx)'], {}), '(x / dx)\n', (45883, 45891), True, 'import numpy as np\n'), ((6092, 6126), 'pandas.concat', 'pd.concat', (['[prev_res, invalid_res]'], {}), '([prev_res, invalid_res])\n', (6101, 6126), True, 'import pandas as pd\n'), ((8860, 8892), 'summit.utils.jsonify_dict', 'jsonify_dict', (['self.prev_param[0]'], {}), '(self.prev_param[0])\n', (8872, 8892), False, 'from summit.utils import jsonify_dict, unjsonify_dict\n'), ((9507, 9536), 'summit.utils.unjsonify_dict', 'unjsonify_dict', (['prev_param[0]'], {}), '(prev_param[0])\n', (9521, 9536), False, 'from summit.utils import jsonify_dict, unjsonify_dict\n'), ((9554, 9586), 'summit.utils.dataset.DataSet.from_dict', 'DataSet.from_dict', (['prev_param[1]'], {}), '(prev_param[1])\n', (9571, 9586), False, 'from summit.utils.dataset import DataSet\n'), ((12953, 12969), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (12967, 12969), True, 'import numpy as np\n'), ((25806, 25821), 'numpy.asfarray', 'np.asfarray', (['x0'], {}), '(x0)\n', (25817, 25821), True, 'import numpy as np\n'), ((26201, 26224), 'numpy.array', 'np.array', (['x0'], {'copy': '(True)'}), '(x0, copy=True)\n', (26209, 26224), True, 'import numpy as np\n'), ((37405, 37465), 'pandas.eval', 'pd.eval', (['(c.lhs + constr[i])'], {'resolvers': '[tmp_next_experiments]'}), '(c.lhs + constr[i], resolvers=[tmp_next_experiments])\n', (37412, 37465), True, 'import pandas as pd\n'), ((39329, 39355), 'numpy.where', 'np.where', (['overfull_sim_dim'], {}), '(overfull_sim_dim)\n', (39337, 39355), True, 'import numpy as np\n'), ((14838, 14850), 'numpy.ones', 'np.ones', (['dim'], {}), '(dim)\n', (14845, 14850), True, 'import numpy as np\n'), ((28520, 28546), 'numpy.add.reduce', 'np.add.reduce', (['sim[:-1]', '(0)'], {}), '(sim[:-1], 0)\n', (28533, 28546), True, 'import numpy as np\n'), ((29329, 29345), 'numpy.asarray', 'np.asarray', (['[xr]'], {}), '([xr])\n', (29339, 29345), True, 'import numpy as np\n'), ((30370, 30392), 'numpy.array_equal', 'np.array_equal', (['xe', 'xr'], {}), '(xe, xr)\n', (30384, 30392), True, 'import numpy as np\n'), ((40589, 40629), 'numpy.insert', 'np.insert', (['value', 'overfull_dim', 'save_dim'], {}), '(value, overfull_dim, save_dim)\n', (40598, 40629), True, 'import numpy as np\n'), ((41020, 41063), 'numpy.insert', 'np.insert', (['value[0]', 'overfull_dim', 'save_dim'], {}), '(value[0], overfull_dim, save_dim)\n', (41029, 41063), True, 'import numpy as np\n'), ((44890, 44914), 'numpy.delete', 'np.delete', (['request', 'i', '(0)'], {}), '(request, i, 0)\n', (44899, 44914), True, 'import numpy as np\n'), ((15646, 15680), 'numpy.array_equal', 'np.array_equal', (['prev_sim[s]', 'x0[k]'], {}), '(prev_sim[s], x0[k])\n', (15660, 15680), True, 'import numpy as np\n'), ((23827, 23849), 'numpy.log10', 'np.log10', (['(1 / self._df)'], {}), '(1 / self._df)\n', (23835, 23849), True, 'import numpy as np\n'), ((26979, 27007), 'numpy.asfarray', 'np.asfarray', (['initial_simplex'], {}), '(initial_simplex)\n', (26990, 27007), True, 'import numpy as np\n'), ((27438, 27454), 'numpy.asfarray', 'np.asfarray', (['sim'], {}), '(sim)\n', (27449, 27454), True, 'import numpy as np\n'), ((39553, 39583), 'numpy.delete', 'np.delete', (['value', 'overfull_dim'], {}), '(value, overfull_dim)\n', (39562, 39583), True, 'import numpy as np\n'), ((39979, 40012), 'numpy.delete', 'np.delete', (['value[0]', 'overfull_dim'], {}), '(value[0], overfull_dim)\n', (39988, 40012), True, 'import numpy as np\n'), ((30559, 30575), 'numpy.asarray', 'np.asarray', (['[xe]'], {}), '([xe])\n', (30569, 30575), True, 'import numpy as np\n'), ((33112, 33134), 'numpy.array_equal', 'np.array_equal', (['xc', 'xr'], {}), '(xc, xr)\n', (33126, 33134), True, 'import numpy as np\n'), ((34805, 34828), 'numpy.array_equal', 'np.array_equal', (['xcc', 'xr'], {}), '(xcc, xr)\n', (34819, 34828), True, 'import numpy as np\n'), ((40820, 40866), 'numpy.insert', 'np.insert', (['value[v][0]', 'overfull_dim', 'save_dim'], {}), '(value[v][0], overfull_dim, save_dim)\n', (40829, 40866), True, 'import numpy as np\n'), ((21210, 21234), 'numpy.abs', 'np.abs', (['(sim[1:] - sim[0])'], {}), '(sim[1:] - sim[0])\n', (21216, 21234), True, 'import numpy as np\n'), ((21283, 21309), 'numpy.abs', 'np.abs', (['(fsim[0] - fsim[1:])'], {}), '(fsim[0] - fsim[1:])\n', (21289, 21309), True, 'import numpy as np\n'), ((23773, 23795), 'numpy.log10', 'np.log10', (['(1 / self._df)'], {}), '(1 / self._df)\n', (23781, 23795), True, 'import numpy as np\n'), ((36012, 36032), 'numpy.asarray', 'np.asarray', (['x_shrink'], {}), '(x_shrink)\n', (36022, 36032), True, 'import numpy as np\n'), ((39794, 39830), 'numpy.delete', 'np.delete', (['value[v][0]', 'overfull_dim'], {}), '(value[v][0], overfull_dim)\n', (39803, 39830), True, 'import numpy as np\n'), ((20157, 20178), 'numpy.array', 'np.array', (['(memory == x)'], {}), '(memory == x)\n', (20165, 20178), True, 'import numpy as np\n'), ((29011, 29041), 'numpy.abs', 'np.abs', (['(bounds[i][b] - xbar[i])'], {}), '(bounds[i][b] - xbar[i])\n', (29017, 29041), True, 'import numpy as np\n'), ((29082, 29110), 'numpy.abs', 'np.abs', (['(xbar[i] - sim[-1][i])'], {}), '(xbar[i] - sim[-1][i])\n', (29088, 29110), True, 'import numpy as np\n'), ((33333, 33349), 'numpy.asarray', 'np.asarray', (['[xc]'], {}), '([xc])\n', (33343, 33349), True, 'import numpy as np\n'), ((35023, 35040), 'numpy.asarray', 'np.asarray', (['[xcc]'], {}), '([xcc])\n', (35033, 35040), True, 'import numpy as np\n'), ((11339, 11352), 'numpy.asarray', 'np.asarray', (['d'], {}), '(d)\n', (11349, 11352), True, 'import numpy as np\n'), ((11362, 11375), 'numpy.asarray', 'np.asarray', (['d'], {}), '(d)\n', (11372, 11375), True, 'import numpy as np\n'), ((16510, 16527), 'numpy.asarray', 'np.asarray', (['x0[k]'], {}), '(x0[k])\n', (16520, 16527), True, 'import numpy as np\n'), ((30081, 30109), 'numpy.abs', 'np.abs', (['(bounds[i][b] - xr[i])'], {}), '(bounds[i][b] - xr[i])\n', (30087, 30109), True, 'import numpy as np\n'), ((30154, 30182), 'numpy.abs', 'np.abs', (['(xbar[i] - sim[-1][i])'], {}), '(xbar[i] - sim[-1][i])\n', (30160, 30182), True, 'import numpy as np\n'), ((32142, 32159), 'numpy.abs', 'np.abs', (['(xr - xbar)'], {}), '(xr - xbar)\n', (32148, 32159), True, 'import numpy as np\n'), ((32202, 32224), 'numpy.abs', 'np.abs', (['(xbar - sim[-1])'], {}), '(xbar - sim[-1])\n', (32208, 32224), True, 'import numpy as np\n'), ((16281, 16298), 'numpy.asarray', 'np.asarray', (['x0[k]'], {}), '(x0[k])\n', (16291, 16298), True, 'import numpy as np\n'), ((32692, 32720), 'numpy.abs', 'np.abs', (['(bounds[i][b] - xr[i])'], {}), '(bounds[i][b] - xr[i])\n', (32698, 32720), True, 'import numpy as np\n'), ((32773, 32801), 'numpy.abs', 'np.abs', (['(xbar[i] - sim[-1][i])'], {}), '(xbar[i] - sim[-1][i])\n', (32779, 32801), True, 'import numpy as np\n'), ((34470, 34500), 'numpy.abs', 'np.abs', (['(bounds[i][b] - xbar[i])'], {}), '(bounds[i][b] - xbar[i])\n', (34476, 34500), True, 'import numpy as np\n'), ((34553, 34581), 'numpy.abs', 'np.abs', (['(sim[-1][i] - xbar[i])'], {}), '(sim[-1][i] - xbar[i])\n', (34559, 34581), True, 'import numpy as np\n')]
import json from time import process_time import numpy as np from matplotlib import pyplot as plt from sklearn.metrics import accuracy_score from PCA.reductionPCA import reductionPCA, plotting, standardise from RBFN.classifierRBFN import train_data, make_prediction, get_XY, amount_centroids, plot_centroids from Resources.functions import * """ GLOBAL VARIABLES If any needed change do it here """ accuracy = 0.995 # Accuracy for the PCA test_val_size = 0.02 # Percentage assigned to # Accuracy per amount of centroid cent_max = 100 step = 1 init_cent = 2 root = os.getcwd() file_all = '/data/allData.csv' file_noisy = '/data/allNoisyData.csv' # One noisy tests file_noisy2 = '/data/allNoisyData2.csv' # Two noisy tests file_merged = '/results/mergedData(' + str(accuracy) + ').csv' file_train = '/results/trainData(' + str(accuracy) + ').csv' file_val = '/results/validationData(' + str(accuracy) + ').csv' file_test = '/results/testData(' + str(accuracy) + ').csv' # The noisy data file to be used file_used = file_noisy2 """ CHECK IF FILES EXIST If not execute download_file_from_google_drive """ # Retrieve Files retrieve_files(root, file_all, file_noisy, file_noisy2) # Generate folders create_folders() if not os.path.exists(root + file_val) or not os.path.exists(root + file_train) \ or not os.path.exists(root + file_test): # Importing Datasets and group them df = get_df(root + file_all) print("Number of non-noisy samples: " + str(len(df.index))) dfn = get_df(root + file_used) print("Number of noisy samples: " + str(len(dfn.index))) df_all = pd.concat([df, dfn], ignore_index=True) # Preprocessing X, Y = preprocess_data(df_all) """ STANDARDISATION Standardisation process were data is standardised to mean 0 and var 1 If don't want to implement standardisation comment this part """ X = standardise(X) """ PCA If don't want to implement PCA comment this part """ pc_X, explained_variance, amount_pcs = reductionPCA(X, accuracy) columns = ['PC' + str(i) for i in range(1, amount_pcs + 1)] X = pd.DataFrame(data=pc_X, columns=columns) """ SEPARATE DATA Data samples are separated in train, validation and test data """ X_train, Y_train, X_val, Y_val, X_test, Y_test = set_train_validation_testData(X, Y, test_val_size) print("Total amount of samples: ", X.shape[0]) print("Amount of Train samples: ", X_train.shape[0]) print("Amount of Validation samples: ", X_val.shape[0]) print("Amount of Test samples: ", X_test.shape[0]) save_csv_file(file_train, pd.concat([X_train, Y_train], axis=1)) save_csv_file(file_val, pd.concat([X_val, Y_val], axis=1)) save_csv_file(file_test, pd.concat([X_test, Y_test], axis=1)) save_csv_file(file_merged, pd.concat([X, Y], axis=1)) else: X, Y = read_csv_data(root + file_merged) X_train, Y_train = read_csv_data(root + file_train) X_val, Y_val = read_csv_data(root + file_val) X_test, Y_test = read_csv_data(root + file_test) amount_pcs = len(X_train.columns) print("Amount of PCs:", amount_pcs) """ PCA Matrix Generate 'PCA' matrix """ pca_all = pca_df(X, Y) pca_train = pca_df(X_train, Y_train) pca_validation = pca_df(X_val, Y_val) pca_test = pca_df(X_test, Y_test) # print("Training PCA") # print(pca_train) # Plotting PCA training data fig, ax = plotting(pca_all) ax.set_title('PCA All Data', fontsize=20) ax.legend(['Non-Faulty', 'Faulty']) fig.show() fig.savefig('results/3D/3d-PCA_All(' + str(accuracy) + ').png') """ RBFN Instead of validation use test data If don't want to implement RBFN comment this part until end """ json_file = root + "/results/score_cent(" + str(init_cent) + "-" + str(cent_max) + "-" + str(accuracy) + "-" \ + str(amount_pcs) + ").json" try: with open(json_file, 'r') as f: data = json.load(f) c_all = data['amountCentroids'] scores = data['accuracy'] except IOError: scores, c_all = amount_centroids(pca_train, pca_validation, amount_pcs, cent_max, step=step) data = {'amountCentroids': c_all, 'accuracy': scores} with open(json_file, "w") as f: json.dump(data, f) # Plotting accuracy per Amount of Centroids fig, ax = plt.subplots() ax.plot(c_all, scores) plt.xlim(init_cent, cent_max) plt.ylim(top=100) plt.title('Accuracy per Amount of Centroids', fontsize=14) plt.xlabel('Amount of Centroids', fontsize=14) plt.ylabel('Accuracy [%]', fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.grid() plt.show() fig.savefig("results/Accuracy-Centroids(" + str(init_cent) + "-" + str(cent_max) + "-" + str(accuracy) + "-" + str(amount_pcs) + ").png") """ RBFN Accuracy with Test data """ # Train X_pca_train, Y_pca_train = get_XY(pca_train, amount_pcs) n_cent = c_all[scores.index(max(scores))] print("Amount of Centroids:", n_cent) # Save or retrieve centroids json_file = root + "/results/rbfn_data(" + str(n_cent) + "-" + str(accuracy) + "-" + str(amount_pcs) + ").json" try: with open(json_file, 'r') as f: data = json.load(f) centroids = np.array(data['Centroids']) W = np.array(data['W']) sigma = data['sigma'] except IOError: centroids, W, sigma = train_data(X_pca_train, Y_pca_train, n_centroids=n_cent) data = {'Centroids': centroids.tolist(), 'W': W.tolist(), 'sigma': sigma} with open(json_file, "w") as f: json.dump(data, f) # Test # All together X_pca_test, Y_pca_test = get_XY(pca_test, amount_pcs) t1_start = process_time() prediction = make_prediction(X_pca_test, centroids, W, sigma) score = accuracy_score(prediction, Y_pca_test) * 100 t1_stop = process_time() f = open("results/testResults(" + str(n_cent) + "-" + str(accuracy) + "-" + str(amount_pcs) + ").txt", 'w+') f.write("%d centroids, %d amount of PCs, not noisy + 2 noisy data tests\nAll test samples together\nTesting time in " "seconds: %.7f\n" % (n_cent, amount_pcs, t1_stop - t1_start)) f.write("Accuracy: " + str(score) + "%\r\n") print("Testing time in seconds: ", t1_stop - t1_start) print("Accuracy: " + str(score) + "%") # One sample at a time times = [] test_scores = [] for i in range(len(pca_test.index)): X_pca_test, Y_pca_test = get_XY(pca_test.loc[pca_test.index == i], amount_pcs) t1_start = process_time() prediction = make_prediction(X_pca_test, centroids, W, sigma) score = int(prediction == Y_pca_test) * 100 t1_stop = process_time() times.append(t1_stop - t1_start) test_scores.append(score) print("Mean testing time in seconds per sample: ", np.mean(times)) print("Mean accuracy: " + str(np.mean(test_scores)) + "%") f.write("One test sample at a time\nTesting time in seconds: %.7f\n" % np.mean(times)) f.write("Accuracy: " + str(np.mean(test_scores)) + "%\r\n") f.close() # Plotting centroids fig = plot_centroids(pca_train, centroids, 'Centroids and Training data', 'results/CentroidsTrain-Optimal(' + str(n_cent) + '-' + str(accuracy) + '-' + str(amount_pcs) + ').png') fig.show() fig = plot_centroids(pca_test, centroids, 'Centroids and Testing data', 'results/CentroidsTest-Optimal(' + str(n_cent) + '-' + str(accuracy) + '-' + str(amount_pcs) + ').png') fig.show()
[ "matplotlib.pyplot.grid", "matplotlib.pyplot.ylabel", "numpy.array", "RBFN.classifierRBFN.train_data", "time.process_time", "numpy.mean", "PCA.reductionPCA.plotting", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.yticks", "matplotlib.pyplot.ylim", "PCA.reductionPCA.reductionPCA", "matplotlib....
[((3380, 3397), 'PCA.reductionPCA.plotting', 'plotting', (['pca_all'], {}), '(pca_all)\n', (3388, 3397), False, 'from PCA.reductionPCA import reductionPCA, plotting, standardise\n'), ((4237, 4251), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (4249, 4251), True, 'from matplotlib import pyplot as plt\n'), ((4275, 4304), 'matplotlib.pyplot.xlim', 'plt.xlim', (['init_cent', 'cent_max'], {}), '(init_cent, cent_max)\n', (4283, 4304), True, 'from matplotlib import pyplot as plt\n'), ((4305, 4322), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {'top': '(100)'}), '(top=100)\n', (4313, 4322), True, 'from matplotlib import pyplot as plt\n'), ((4323, 4381), 'matplotlib.pyplot.title', 'plt.title', (['"""Accuracy per Amount of Centroids"""'], {'fontsize': '(14)'}), "('Accuracy per Amount of Centroids', fontsize=14)\n", (4332, 4381), True, 'from matplotlib import pyplot as plt\n'), ((4382, 4428), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Amount of Centroids"""'], {'fontsize': '(14)'}), "('Amount of Centroids', fontsize=14)\n", (4392, 4428), True, 'from matplotlib import pyplot as plt\n'), ((4429, 4468), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy [%]"""'], {'fontsize': '(14)'}), "('Accuracy [%]', fontsize=14)\n", (4439, 4468), True, 'from matplotlib import pyplot as plt\n'), ((4469, 4492), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(14)'}), '(fontsize=14)\n', (4479, 4492), True, 'from matplotlib import pyplot as plt\n'), ((4493, 4516), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(14)'}), '(fontsize=14)\n', (4503, 4516), True, 'from matplotlib import pyplot as plt\n'), ((4517, 4527), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (4525, 4527), True, 'from matplotlib import pyplot as plt\n'), ((4528, 4538), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4536, 4538), True, 'from matplotlib import pyplot as plt\n'), ((4762, 4791), 'RBFN.classifierRBFN.get_XY', 'get_XY', (['pca_train', 'amount_pcs'], {}), '(pca_train, amount_pcs)\n', (4768, 4791), False, 'from RBFN.classifierRBFN import train_data, make_prediction, get_XY, amount_centroids, plot_centroids\n'), ((5481, 5509), 'RBFN.classifierRBFN.get_XY', 'get_XY', (['pca_test', 'amount_pcs'], {}), '(pca_test, amount_pcs)\n', (5487, 5509), False, 'from RBFN.classifierRBFN import train_data, make_prediction, get_XY, amount_centroids, plot_centroids\n'), ((5521, 5535), 'time.process_time', 'process_time', ([], {}), '()\n', (5533, 5535), False, 'from time import process_time\n'), ((5549, 5597), 'RBFN.classifierRBFN.make_prediction', 'make_prediction', (['X_pca_test', 'centroids', 'W', 'sigma'], {}), '(X_pca_test, centroids, W, sigma)\n', (5564, 5597), False, 'from RBFN.classifierRBFN import train_data, make_prediction, get_XY, amount_centroids, plot_centroids\n'), ((5661, 5675), 'time.process_time', 'process_time', ([], {}), '()\n', (5673, 5675), False, 'from time import process_time\n'), ((1881, 1895), 'PCA.reductionPCA.standardise', 'standardise', (['X'], {}), '(X)\n', (1892, 1895), False, 'from PCA.reductionPCA import reductionPCA, plotting, standardise\n'), ((2017, 2042), 'PCA.reductionPCA.reductionPCA', 'reductionPCA', (['X', 'accuracy'], {}), '(X, accuracy)\n', (2029, 2042), False, 'from PCA.reductionPCA import reductionPCA, plotting, standardise\n'), ((5606, 5644), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['prediction', 'Y_pca_test'], {}), '(prediction, Y_pca_test)\n', (5620, 5644), False, 'from sklearn.metrics import accuracy_score\n'), ((6231, 6284), 'RBFN.classifierRBFN.get_XY', 'get_XY', (['pca_test.loc[pca_test.index == i]', 'amount_pcs'], {}), '(pca_test.loc[pca_test.index == i], amount_pcs)\n', (6237, 6284), False, 'from RBFN.classifierRBFN import train_data, make_prediction, get_XY, amount_centroids, plot_centroids\n'), ((6300, 6314), 'time.process_time', 'process_time', ([], {}), '()\n', (6312, 6314), False, 'from time import process_time\n'), ((6332, 6380), 'RBFN.classifierRBFN.make_prediction', 'make_prediction', (['X_pca_test', 'centroids', 'W', 'sigma'], {}), '(X_pca_test, centroids, W, sigma)\n', (6347, 6380), False, 'from RBFN.classifierRBFN import train_data, make_prediction, get_XY, amount_centroids, plot_centroids\n'), ((6443, 6457), 'time.process_time', 'process_time', ([], {}), '()\n', (6455, 6457), False, 'from time import process_time\n'), ((6577, 6591), 'numpy.mean', 'np.mean', (['times'], {}), '(times)\n', (6584, 6591), True, 'import numpy as np\n'), ((3869, 3881), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3878, 3881), False, 'import json\n'), ((3984, 4060), 'RBFN.classifierRBFN.amount_centroids', 'amount_centroids', (['pca_train', 'pca_validation', 'amount_pcs', 'cent_max'], {'step': 'step'}), '(pca_train, pca_validation, amount_pcs, cent_max, step=step)\n', (4000, 4060), False, 'from RBFN.classifierRBFN import train_data, make_prediction, get_XY, amount_centroids, plot_centroids\n'), ((5070, 5082), 'json.load', 'json.load', (['f'], {}), '(f)\n', (5079, 5082), False, 'import json\n'), ((5103, 5130), 'numpy.array', 'np.array', (["data['Centroids']"], {}), "(data['Centroids'])\n", (5111, 5130), True, 'import numpy as np\n'), ((5143, 5162), 'numpy.array', 'np.array', (["data['W']"], {}), "(data['W'])\n", (5151, 5162), True, 'import numpy as np\n'), ((5235, 5291), 'RBFN.classifierRBFN.train_data', 'train_data', (['X_pca_train', 'Y_pca_train'], {'n_centroids': 'n_cent'}), '(X_pca_train, Y_pca_train, n_centroids=n_cent)\n', (5245, 5291), False, 'from RBFN.classifierRBFN import train_data, make_prediction, get_XY, amount_centroids, plot_centroids\n'), ((6723, 6737), 'numpy.mean', 'np.mean', (['times'], {}), '(times)\n', (6730, 6737), True, 'import numpy as np\n'), ((4163, 4181), 'json.dump', 'json.dump', (['data', 'f'], {}), '(data, f)\n', (4172, 4181), False, 'import json\n'), ((5414, 5432), 'json.dump', 'json.dump', (['data', 'f'], {}), '(data, f)\n', (5423, 5432), False, 'import json\n'), ((6623, 6643), 'numpy.mean', 'np.mean', (['test_scores'], {}), '(test_scores)\n', (6630, 6643), True, 'import numpy as np\n'), ((6766, 6786), 'numpy.mean', 'np.mean', (['test_scores'], {}), '(test_scores)\n', (6773, 6786), True, 'import numpy as np\n')]
import os import tempfile import mock import numpy as np from yt.testing import assert_equal, fake_random_ds from yt.units.unit_object import Unit def setup(): from yt.config import ytcfg ytcfg["yt", "__withintesting"] = "True" def teardown_func(fns): for fn in fns: try: os.remove(fn) except OSError: pass @mock.patch("yt.visualization._mpl_imports.FigureCanvasAgg.print_figure") def test_slice(pf): fns = [] grid_eps = np.finfo(np.float64).eps for nprocs in [8, 1]: # We want to test both 1 proc and 8 procs, to make sure that # parallelism isn't broken ds = fake_random_ds(64, nprocs=nprocs) dims = ds.domain_dimensions xn, yn, zn = ds.domain_dimensions dx = ds.arr(1.0 / (ds.domain_dimensions * 2), "code_length") xi, yi, zi = ds.domain_left_edge + dx xf, yf, zf = ds.domain_right_edge - dx coords = np.mgrid[xi : xf : xn * 1j, yi : yf : yn * 1j, zi : zf : zn * 1j] uc = [np.unique(c) for c in coords] slc_pos = 0.5 # Some simple slice tests with single grids for ax in range(3): xax = ds.coordinates.x_axis[ax] yax = ds.coordinates.y_axis[ax] slc = ds.slice(ax, slc_pos) shifted_slc = ds.slice(ax, slc_pos + grid_eps) assert_equal(slc["ones"].sum(), slc["ones"].size) assert_equal(slc["ones"].min(), 1.0) assert_equal(slc["ones"].max(), 1.0) assert_equal(np.unique(slc["px"]), uc[xax]) assert_equal(np.unique(slc["py"]), uc[yax]) assert_equal(np.unique(slc["pdx"]), 0.5 / dims[xax]) assert_equal(np.unique(slc["pdy"]), 0.5 / dims[yax]) pw = slc.to_pw(fields="density") for p in pw.plots.values(): tmpfd, tmpname = tempfile.mkstemp(suffix=".png") os.close(tmpfd) p.save(name=tmpname) fns.append(tmpname) for width in [(1.0, "unitary"), 1.0, ds.quan(0.5, "code_length")]: frb = slc.to_frb(width, 64) shifted_frb = shifted_slc.to_frb(width, 64) for slc_field in ["ones", "density"]: fi = ds._get_field_info(slc_field) assert_equal(frb[slc_field].info["data_source"], slc.__str__()) assert_equal(frb[slc_field].info["axis"], ax) assert_equal(frb[slc_field].info["field"], slc_field) assert_equal(frb[slc_field].units, Unit(fi.units)) assert_equal(frb[slc_field].info["xlim"], frb.bounds[:2]) assert_equal(frb[slc_field].info["ylim"], frb.bounds[2:]) assert_equal(frb[slc_field].info["center"], slc.center) assert_equal(frb[slc_field].info["coord"], slc_pos) assert_equal(frb[slc_field], shifted_frb[slc_field]) teardown_func(fns) def test_slice_over_edges(): ds = fake_random_ds(64, nprocs=8, fields=["density"], negative=[False]) slc = ds.slice(0, 0.0) slc["density"] slc = ds.slice(1, 0.5) slc["density"] def test_slice_over_outer_boundary(): ds = fake_random_ds(64, nprocs=8, fields=["density"], negative=[False]) slc = ds.slice(2, 1.0) slc["density"] assert_equal(slc["density"].size, 0)
[ "mock.patch", "yt.testing.assert_equal", "numpy.unique", "os.close", "yt.testing.fake_random_ds", "yt.units.unit_object.Unit", "numpy.finfo", "tempfile.mkstemp", "os.remove" ]
[((369, 441), 'mock.patch', 'mock.patch', (['"""yt.visualization._mpl_imports.FigureCanvasAgg.print_figure"""'], {}), "('yt.visualization._mpl_imports.FigureCanvasAgg.print_figure')\n", (379, 441), False, 'import mock\n'), ((3032, 3098), 'yt.testing.fake_random_ds', 'fake_random_ds', (['(64)'], {'nprocs': '(8)', 'fields': "['density']", 'negative': '[False]'}), "(64, nprocs=8, fields=['density'], negative=[False])\n", (3046, 3098), False, 'from yt.testing import assert_equal, fake_random_ds\n'), ((3240, 3306), 'yt.testing.fake_random_ds', 'fake_random_ds', (['(64)'], {'nprocs': '(8)', 'fields': "['density']", 'negative': '[False]'}), "(64, nprocs=8, fields=['density'], negative=[False])\n", (3254, 3306), False, 'from yt.testing import assert_equal, fake_random_ds\n'), ((3357, 3393), 'yt.testing.assert_equal', 'assert_equal', (["slc['density'].size", '(0)'], {}), "(slc['density'].size, 0)\n", (3369, 3393), False, 'from yt.testing import assert_equal, fake_random_ds\n'), ((490, 510), 'numpy.finfo', 'np.finfo', (['np.float64'], {}), '(np.float64)\n', (498, 510), True, 'import numpy as np\n'), ((658, 691), 'yt.testing.fake_random_ds', 'fake_random_ds', (['(64)'], {'nprocs': 'nprocs'}), '(64, nprocs=nprocs)\n', (672, 691), False, 'from yt.testing import assert_equal, fake_random_ds\n'), ((311, 324), 'os.remove', 'os.remove', (['fn'], {}), '(fn)\n', (320, 324), False, 'import os\n'), ((1029, 1041), 'numpy.unique', 'np.unique', (['c'], {}), '(c)\n', (1038, 1041), True, 'import numpy as np\n'), ((1533, 1553), 'numpy.unique', 'np.unique', (["slc['px']"], {}), "(slc['px'])\n", (1542, 1553), True, 'import numpy as np\n'), ((1589, 1609), 'numpy.unique', 'np.unique', (["slc['py']"], {}), "(slc['py'])\n", (1598, 1609), True, 'import numpy as np\n'), ((1645, 1666), 'numpy.unique', 'np.unique', (["slc['pdx']"], {}), "(slc['pdx'])\n", (1654, 1666), True, 'import numpy as np\n'), ((1710, 1731), 'numpy.unique', 'np.unique', (["slc['pdy']"], {}), "(slc['pdy'])\n", (1719, 1731), True, 'import numpy as np\n'), ((1868, 1899), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {'suffix': '""".png"""'}), "(suffix='.png')\n", (1884, 1899), False, 'import tempfile\n'), ((1916, 1931), 'os.close', 'os.close', (['tmpfd'], {}), '(tmpfd)\n', (1924, 1931), False, 'import os\n'), ((2401, 2446), 'yt.testing.assert_equal', 'assert_equal', (["frb[slc_field].info['axis']", 'ax'], {}), "(frb[slc_field].info['axis'], ax)\n", (2413, 2446), False, 'from yt.testing import assert_equal, fake_random_ds\n'), ((2467, 2520), 'yt.testing.assert_equal', 'assert_equal', (["frb[slc_field].info['field']", 'slc_field'], {}), "(frb[slc_field].info['field'], slc_field)\n", (2479, 2520), False, 'from yt.testing import assert_equal, fake_random_ds\n'), ((2612, 2669), 'yt.testing.assert_equal', 'assert_equal', (["frb[slc_field].info['xlim']", 'frb.bounds[:2]'], {}), "(frb[slc_field].info['xlim'], frb.bounds[:2])\n", (2624, 2669), False, 'from yt.testing import assert_equal, fake_random_ds\n'), ((2690, 2747), 'yt.testing.assert_equal', 'assert_equal', (["frb[slc_field].info['ylim']", 'frb.bounds[2:]'], {}), "(frb[slc_field].info['ylim'], frb.bounds[2:])\n", (2702, 2747), False, 'from yt.testing import assert_equal, fake_random_ds\n'), ((2768, 2823), 'yt.testing.assert_equal', 'assert_equal', (["frb[slc_field].info['center']", 'slc.center'], {}), "(frb[slc_field].info['center'], slc.center)\n", (2780, 2823), False, 'from yt.testing import assert_equal, fake_random_ds\n'), ((2844, 2895), 'yt.testing.assert_equal', 'assert_equal', (["frb[slc_field].info['coord']", 'slc_pos'], {}), "(frb[slc_field].info['coord'], slc_pos)\n", (2856, 2895), False, 'from yt.testing import assert_equal, fake_random_ds\n'), ((2916, 2968), 'yt.testing.assert_equal', 'assert_equal', (['frb[slc_field]', 'shifted_frb[slc_field]'], {}), '(frb[slc_field], shifted_frb[slc_field])\n', (2928, 2968), False, 'from yt.testing import assert_equal, fake_random_ds\n'), ((2576, 2590), 'yt.units.unit_object.Unit', 'Unit', (['fi.units'], {}), '(fi.units)\n', (2580, 2590), False, 'from yt.units.unit_object import Unit\n')]
# Copyright 2022 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import numpy as np from cunumeric.array import convert_to_cunumeric_ndarray def run_test(np_arr, num_arr): # We don't support 'K' yet, which will be supported later test_orders = ["C", "F", "A"] for order in test_orders: b = np_arr.flatten(order) c = num_arr.flatten(order) is_equal = True err_arr = [b, c] if len(b) != len(c): is_equal = False err_arr = [b, c] else: for each in zip(b, c): if not np.array_equal(*each): err_arr = each is_equal = False break print_msg = f"np & cunumeric.ndarray({np_arr.shape}).flatten({order}))" assert is_equal, ( f"Failed, {print_msg}\n" f"numpy result: {err_arr[0]}, {b.shape}\n" f"cunumeric_result: {err_arr[1]}, {c.shape}\n" f"cunumeric and numpy shows" f" different result\n" ) print( f"Passed, {print_msg}, np: ({b.shape}, {b.dtype})" f", cunumeric: ({c.shape}, {c.dtype}" ) def test(dim): print("test flatten") # test ndarray.flatten w/ 1D, 2D and 3D arrays input_arr = [ (0,), (0, 10), (1,), (1, 1), (1, 1, 1), (1, dim), (1, dim, 1), (dim, dim), (dim, dim, dim), ] for input_size in input_arr: a = np.random.randint(low=0, high=100, size=(input_size)) b = convert_to_cunumeric_ndarray(a) run_test(a, b) return if __name__ == "__main__": test(10)
[ "numpy.random.randint", "numpy.array_equal", "cunumeric.array.convert_to_cunumeric_ndarray" ]
[((2028, 2079), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(100)', 'size': 'input_size'}), '(low=0, high=100, size=input_size)\n', (2045, 2079), True, 'import numpy as np\n'), ((2094, 2125), 'cunumeric.array.convert_to_cunumeric_ndarray', 'convert_to_cunumeric_ndarray', (['a'], {}), '(a)\n', (2122, 2125), False, 'from cunumeric.array import convert_to_cunumeric_ndarray\n'), ((1098, 1119), 'numpy.array_equal', 'np.array_equal', (['*each'], {}), '(*each)\n', (1112, 1119), True, 'import numpy as np\n')]
#!/anaconda/envs/tensorflow/bin/python # -*- coding: utf-8 -*- """ Yet another one of the simplest implementation of neural network. It supports layer structure configuration via a list. Created on Wed Mar 28 20:07:33 2018 @author: <NAME> """ import numpy as np from LogisticRegression import traincsv2matrix, onezero from pprint import pprint # Activation functions def sigmoid(z): return 1 / (1 + np.exp(-1 * z)) class MuptilayerPerceptron: """ This is a class that defines multi-layer perceptron, i.e. a neural network. For simplicity, only use sigmoid function as activation function and mini batch gradient descent as optimization algorithm. Attributes: .weights: A list of np.matrix, each represents a weight between two layers of a network. biases: A list of np.matrix, each represents a bias to be added to previous layer to calculate the next. hidden: Intermediate calculation result of hidden layer matrix, i.e. activations. """ def __init__(self, layers: list, alpha: float, tol: float, batch_size: int): """ Define the structure of a neural network with a list. Params: layers: A list of integers, each int is number of nodes in a hidden layer. For example: layers = [4, 3, 2] Then, there would be: w1 := 3 x 4 matrix w2 := 2 x 3 matrix b1 := 3 x 1 matrix (column vector) b2 := 2 x 1 matrix (column vector) This defines a neural network such that: 4-feature input layer, 2-class output layerand a hidden layer with 3 nodes. * Must make sure the definition matches the X and y feature. alpha: Learning rate tol: tolerance Return: No return. """ if 0 in layers: raise ValueError("Should not have layer with zero node!") if len(layers) < 2: raise ValueError("Layer size must greater or equal to 2!") # Hyperparemeters: self.layers = layers self.layer_num = len(layers) - 1 self.alpha = alpha self.tol = tol self.batch_size = batch_size # Weights and gradients: self.weights,\ self.biases,\ self.hidden,\ self.grad_w,\ self.grad_b,\ self.grad_h = self._initialize() def _initialize(self) -> (list, list, list, list, list, list): """ Initialize the shape of neural network. Return: A tuple of 6 lists of np.matrix: weights: Weights between layers biases: Intercept two hidden: Hidden layer intermediate calculation results. Shaped as: [batch_size x feature_num] And initial gradients of them respectively. """ weights = list( map( np.matrix, list( map( lambda ls: np.random.rand(*ls) * 2 - 1, list(zip(self.layers[1:], self.layers[:-1])) ) ) ) ) biases = list( map( np.matrix, list( map( lambda ls: np.random.rand(*ls) * 2 - 1, list( zip( [self.batch_size] * (len(self.layers) - 1), self.layers[1:] ) ) ) ) ) ) hidden = list( map( np.matrix, list( map( lambda ls: np.random.rand(*ls) * 2 - 1, list( zip( [self.batch_size] * (len(self.layers) - 1), self.layers[1:] ) ) ) ) ) ) grad_w = list( map( np.matrix, list( map( lambda ls: np.random.rand(*ls) * 2 - 1, list(zip(self.layers[1:], self.layers[:-1])) ) ) ) ) grad_b = list( map( np.matrix, list( map( lambda ls: np.random.rand(*ls) * 2 - 1, list( zip( [self.batch_size] * (len(self.layers) - 1), self.layers[1:] ) ) ) ) ) ) grad_h = list( map( np.matrix, list( map( lambda ls: np.random.rand(*ls) * 2 - 1, list( zip( [self.batch_size] * (len(self.layers) - 1), self.layers[1:] ) ) ) ) ) ) return weights, biases, hidden, grad_w, grad_b, grad_h def forwardprop(self, X: np.matrix, activation) -> np.matrix: """ Vectorized forward propagation phase of neural network. Updates the nodes' value of layers. Pramms: activation: The choice of ctivation function. Return: output: A matrix (as in np.matrix) representing n calculated ŷ. The shape of output is [b_size x (number of output layer nodes)] """ self.hidden[0] = activation(X @ self.weights[0].T + self.biases[0]) for i in range(1, self.layer_num): self.hidden[i] = activation( self.hidden[i - 1] @ self.weights[i].T + self.biases[i] ) # print("self.hidden ->\n", self.hidden) output = onezero(self.hidden[-1]) return output def backprop(self, X: np.matrix, y: np.matrix): """ Back propagation phase of neural network. Updates the weights and biases between layers. Params: X: A batch of X input data y: A batch of corresponding ground truth y """ y_pred = self.forwardprop(X, sigmoid) print("y ->\n", y[:10]) print("y_pred ->\n", y_pred[:10]) loss = (y - y_pred).sum() self.grad_h[-1] = 2 * (y - y_pred) self.grad_w[-1] = self.grad_h[-1].T @ self.hidden[-2] self.grad_b[-1] = self.grad_h[-1] for i in range(self.layer_num - 2, 0, -1): self.grad_h[i] = self.grad_h[i + 1] @ self.weights[i + 1] self.grad_w[i + 1] = self.grad_h[i + 1].T @ self.hidden[i] # voila! self.grad_b[i + 1] = self.grad_h[i + 1] return loss def train(self, X: np.matrix, y: np.matrix, iteration: int): """ Repeatedly calls forwardprop and backprop function to update the weights using gradient descent algorithm. """ for i in range(iteration): loss = self.backprop(X, y) if i % 10000 == 0 and i >= 100: print("Iteration: %s | Loss: %s" % (i, loss)) for j in range(self.layer_num): # print('\tweights[{}] ->'.format(j), self.weights[j].shape) # print('\tbiases[{}] ->'.format(j), self.biases[j].shape) # print('\thidden[{}] ->'.format(j), self.hidden[j].shape) # print('\tgrad_w[{}] ->'.format(j), self.grad_w[j].shape) # print('\tgrad_b[{}] ->'.format(j), self.grad_b[j].shape) # print('\tgrad_h[{}] ->'.format(j), self.grad_h[j].shape) self.biases[j] -= self.alpha * self.grad_b[j] # self.hidden[j] -= self.alpha * self.grad_h[j] self.weights[j] -= self.alpha * self.grad_w[j] # try: # self.weights[j] -= self.grad_w[j] # except ValueError as e: # print(e) # print('\tgrad_w[{}] ->'.format(j), self.grad_w[j].shape) # print('\thidden[{}] ->'.format(j - 1), # self.hidden[j - 1].shape) # else: # print('\tCorrect!') # print('\tgrad_w[{}] =>'.format(j), self.grad_w[j].shape) # print('\thidden[{}] ->'.format(j - 1), # self.hidden[j - 1].shape) # finally: # print('\n-------------Inner {} iter end----------------\n'. # format(j)) # print('\n\n=================Outer {} iter end================\n\n'. # format(i)) def predict(self, test_X: np.matrix) -> np.matrix: """ Predict output given the input column vector using the trained weights. Params: sample: Input sample data, a np.matrix object, could be multiple. Return: result: Output a column vector which is a np.matrix object representing the predicted value given input sample data matrix. """ return self.forwardprop(test_X, sigmoid) if __name__ == "__main__": # Read data: y_train, X_train = traincsv2matrix("diabetes_dataset.csv") mlp = MuptilayerPerceptron([8, 4, 2, 1], 0.01, 0.01, 768) mlp._initialize() pprint(mlp.hidden) mlp.train(X_train, y_train, 20000) pprint(mlp.hidden) # from sklearn.neural_network import MLPClassifier # clf = MLPClassifier(solver='lbfgs', alpha=1e-5, # hidden_layer_sizes=(16, 8), random_state=1) # clf.fit(X_train, np.ravel(y_train)) # print(clf.coefs_)
[ "numpy.random.rand", "LogisticRegression.traincsv2matrix", "numpy.exp", "LogisticRegression.onezero", "pprint.pprint" ]
[((9679, 9718), 'LogisticRegression.traincsv2matrix', 'traincsv2matrix', (['"""diabetes_dataset.csv"""'], {}), "('diabetes_dataset.csv')\n", (9694, 9718), False, 'from LogisticRegression import traincsv2matrix, onezero\n'), ((9809, 9827), 'pprint.pprint', 'pprint', (['mlp.hidden'], {}), '(mlp.hidden)\n', (9815, 9827), False, 'from pprint import pprint\n'), ((9872, 9890), 'pprint.pprint', 'pprint', (['mlp.hidden'], {}), '(mlp.hidden)\n', (9878, 9890), False, 'from pprint import pprint\n'), ((6292, 6316), 'LogisticRegression.onezero', 'onezero', (['self.hidden[-1]'], {}), '(self.hidden[-1])\n', (6299, 6316), False, 'from LogisticRegression import traincsv2matrix, onezero\n'), ((407, 421), 'numpy.exp', 'np.exp', (['(-1 * z)'], {}), '(-1 * z)\n', (413, 421), True, 'import numpy as np\n'), ((3053, 3072), 'numpy.random.rand', 'np.random.rand', (['*ls'], {}), '(*ls)\n', (3067, 3072), True, 'import numpy as np\n'), ((3364, 3383), 'numpy.random.rand', 'np.random.rand', (['*ls'], {}), '(*ls)\n', (3378, 3383), True, 'import numpy as np\n'), ((3849, 3868), 'numpy.random.rand', 'np.random.rand', (['*ls'], {}), '(*ls)\n', (3863, 3868), True, 'import numpy as np\n'), ((4335, 4354), 'numpy.random.rand', 'np.random.rand', (['*ls'], {}), '(*ls)\n', (4349, 4354), True, 'import numpy as np\n'), ((4646, 4665), 'numpy.random.rand', 'np.random.rand', (['*ls'], {}), '(*ls)\n', (4660, 4665), True, 'import numpy as np\n'), ((5131, 5150), 'numpy.random.rand', 'np.random.rand', (['*ls'], {}), '(*ls)\n', (5145, 5150), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Tue Nov 8 20:05:36 2016 @author: JSong """ import os import time import pandas as pd import numpy as np pd.set_option('display.float_format', lambda x: '%.2f' % x) from . import config from .utils import Delaunay2D import matplotlib.image as mpimg import seaborn as sns from pptx import Presentation from pptx.chart.data import ChartData,XyChartData,BubbleChartData from pptx.enum.chart import XL_CHART_TYPE from pptx.util import Inches, Pt, Emu from pptx.enum.chart import XL_LEGEND_POSITION #from pptx.enum.chart import XL_LABEL_POSITION from pptx.dml.color import RGBColor _thisdir = os.path.split(__file__)[0] # default chinese font from matplotlib.font_manager import FontProperties font_path=config.font_path if font_path: myfont=FontProperties(fname=font_path) sns.set(font=myfont.get_name()) # default template of pptx report template_pptx=config.template_pptx __all__=['Report', 'df_to_table', 'df_to_chartdata', 'plot_table', 'plot_textbox', 'plot_chart', 'plot_picture', 'slides_data_gen', 'plot_cover', 'genwordcloud'] chart_list={\ "AREA":[1,"ChartData"],\ "AREA_STACKED":[76,"ChartData"],\ "AREA_STACKED_100":[77,"ChartData"],\ "THREE_D_AREA":[-4098,"ChartData"],\ "THREE_D_AREA_STACKED":[78,"ChartData"],\ "THREE_D_AREA_STACKED_100":[79,"ChartData"],\ "BAR_CLUSTERED":[57,"ChartData"],\ "BAR_TWO_WAY":[57,"ChartData"],\ "BAR_OF_PIE":[71,"ChartData"],\ "BAR_STACKED":[58,"ChartData"],\ "BAR_STACKED_100":[59,"ChartData"],\ "THREE_D_BAR_CLUSTERED":[60,"ChartData"],\ "THREE_D_BAR_STACKED":[61,"ChartData"],\ "THREE_D_BAR_STACKED_100":[62,"ChartData"],\ "BUBBLE":[15,"BubbleChartData"],\ "BUBBLE_THREE_D_EFFECT":[87,"BubbleChartData"],\ "COLUMN_CLUSTERED":[51,"ChartData"],\ "COLUMN_STACKED":[52,"ChartData"],\ "COLUMN_STACKED_100":[53,"ChartData"],\ "THREE_D_COLUMN":[-4100,"ChartData"],\ "THREE_D_COLUMN_CLUSTERED":[54,"ChartData"],\ "THREE_D_COLUMN_STACKED":[55,"ChartData"],\ "THREE_D_COLUMN_STACKED_100":[56,"ChartData"],\ "CYLINDER_BAR_CLUSTERED":[95,"ChartData"],\ "CYLINDER_BAR_STACKED":[96,"ChartData"],\ "CYLINDER_BAR_STACKED_100":[97,"ChartData"],\ "CYLINDER_COL":[98,"ChartData"],\ "CYLINDER_COL_CLUSTERED":[92,"ChartData"],\ "CYLINDER_COL_STACKED":[93,"ChartData"],\ "CYLINDER_COL_STACKED_100":[94,"ChartData"],\ "DOUGHNUT":[-4120,"ChartData"],\ "DOUGHNUT_EXPLODED":[80,"ChartData"],\ "LINE":[4,"ChartData"],\ "LINE_MARKERS":[65,"ChartData"],\ "LINE_MARKERS_STACKED":[66,"ChartData"],\ "LINE_MARKERS_STACKED_100":[67,"ChartData"],\ "LINE_STACKED":[63,"ChartData"],\ "LINE_STACKED_100":[64,"ChartData"],\ "THREE_D_LINE":[-4101,"ChartData"],\ "PIE":[5,"ChartData"],\ "PIE_EXPLODED":[69,"ChartData"],\ "PIE_OF_PIE":[68,"ChartData"],\ "THREE_D_PIE":[-4102,"ChartData"],\ "THREE_D_PIE_EXPLODED":[70,"ChartData"],\ "PYRAMID_BAR_CLUSTERED":[109,"ChartData"],\ "PYRAMID_BAR_STACKED":[110,"ChartData"],\ "PYRAMID_BAR_STACKED_100":[111,"ChartData"],\ "PYRAMID_COL":[112,"ChartData"],\ "PYRAMID_COL_CLUSTERED":[106,"ChartData"],\ "PYRAMID_COL_STACKED":[107,"ChartData"],\ "PYRAMID_COL_STACKED_100":[108,"ChartData"],\ "RADAR":[-4151,"ChartData"],\ "RADAR_FILLED":[82,"ChartData"],\ "RADAR_MARKERS":[81,"ChartData"],\ "STOCK_HLC":[88,"ChartData"],\ "STOCK_OHLC":[89,"ChartData"],\ "STOCK_VHLC":[90,"ChartData"],\ "STOCK_VOHLC":[91,"ChartData"],\ "SURFACE":[83,"ChartData"],\ "SURFACE_TOP_VIEW":[85,"ChartData"],\ "SURFACE_TOP_VIEW_WIREFRAME":[86,"ChartData"],\ "SURFACE_WIREFRAME":[84,"ChartData"],\ "XY_SCATTER":[-4169,"XyChartData"],\ "XY_SCATTER_LINES":[74,"XyChartData"],\ "XY_SCATTER_LINES_NO_MARKERS":[75,"XyChartData"],\ "XY_SCATTER_SMOOTH":[72,"XyChartData"],\ "XY_SCATTER_SMOOTH_NO_MARKERS":[73,"XyChartData"]} def df_to_table(slide,df,left,top,width,height,index_names=False,columns_names=True): '''将pandas数据框添加到slide上,并生成pptx上的表格 输入: slide:PPT的一个页面,由pptx.Presentation().slides.add_slide()给定 df:需要转换的数据框 lef,top: 表格在slide中的位置 width,height: 表格在slide中的大小 index_names: Bool,是否需要显示行类别的名称 columns_names: Bool,是否需要显示列类别的名称 返回: 返回带表格的slide ''' df=pd.DataFrame(df) rows, cols = df.shape res = slide.shapes.add_table(rows+columns_names, cols+index_names, left, top, width, height) # 固定表格的宽度 ''' for c in range(cols+rownames): res.table.columns[c].width = colwidth res.table.rows[c].width = colwidth ''' # Insert the column names if columns_names: for col_index, col_name in enumerate(list(df.columns)): cell=res.table.cell(0,col_index+index_names) #cell.text_frame.fit_text(max_size=12) #cell.text_frame.text='%s'%(col_name) cell.text = '%s'%(col_name) if index_names: for col_index, col_name in enumerate(list(df.index)): cell=res.table.cell(col_index+columns_names,0) cell.text = '%s'%(col_name) #cell.text_frame.fit_text(max_size=12) m = df.as_matrix() for row in range(rows): for col in range(cols): cell=res.table.cell(row+columns_names, col+index_names) if isinstance(m[row, col],float): cell.text = '%.2f'%(m[row, col]) else: cell.text = '%s'%(m[row, col]) #cell.text_frame.fit_text(max_size=12) def df_to_chartdata(df,datatype,number_format=None): ''' 根据给定的图表数据类型生成相应的数据 Chartdata:一般的数据 XyChartData: 散点图数据 BubbleChartData:气泡图数据 ''' if isinstance(df,pd.Series): df=pd.DataFrame(df) df.fillna(0,inplace=True) datatype=datatype.lower() if datatype == 'chartdata': chart_data = ChartData() chart_data.categories = ['%s'%(c) for c in list(df.index)] for col_name in df.columns: chart_data.add_series('%s'%(col_name),list(df[col_name]),number_format) return chart_data if datatype == 'xychartdata': chart_data=XyChartData() if not isinstance(df,list): df=[df] for d in df: series_name='%s'%(d.columns[0])+' vs '+'%s'%(d.columns[1]) series_ = chart_data.add_series(series_name) for i in range(len(d)): series_.add_data_point(d.iloc[i,0], d.iloc[i,1]) return chart_data if datatype == 'bubblechartdata': chart_data=BubbleChartData() if not isinstance(df,list): df=[df] for d in df: series_name='%s'%(d.columns[0])+' vs '+'%s'%(d.columns[1]) series_ = chart_data.add_series(series_name) for i in range(len(d)): series_.add_data_point(d.iloc[i,0],d.iloc[i,1],d.iloc[i,2]) return chart_data def plot_table(prs,df,layouts=[0,5],title=u'我是标题',summary=u'我是简短的结论',footnote=''): '''根据给定的数据,在给定的prs上新增一页表格ppt 输入: prs: PPT文件接口 df: 数据框 layouts: [0]为PPT母版顺序,[1]为母版内的版式顺序 输出: 更新后的prs ''' df=pd.DataFrame(df) slide_width=prs.slide_width slide_height=prs.slide_height # 可能需要修改以适应更多的情形 title_only_slide = prs.slide_masters[layouts[0]].slide_layouts[layouts[1]] slide = prs.slides.add_slide(title_only_slide) #title=u'这里是标题' slide.shapes.title.text = title left,top = Emu(0.05*slide_width), Emu(0.10*slide_height) width,height = Emu(0.7*slide_width), Emu(0.1*slide_height) txBox = slide.shapes.add_textbox(left, top, width, height) #summary=u'这里是一些简短的结论' txBox.text_frame.text=summary # 绘制表格 '''添加自适应的表格大小 默认最大12*6,width=0.80,height=0.70 left=0.1,top=0.25 ''' R,C=df.shape width=max(0.5,min(1,C/6.0))*0.80 height=max(0.5,min(1,R/12.0))*0.70 left=0.5-width/2 top=0.25 left=Emu(left*slide_width) top=Emu(top*slide_height) width=Emu(width*slide_width) height=Emu(height*slide_height) df_to_table(slide,df,left,top,width,height,index_names=True) # 添加脚注 footnote=u'这里是脚注' if footnote: left,top = Emu(0.025*slide_width), Emu(0.95*slide_height) width,height = Emu(0.70*slide_width), Emu(0.10*slide_height) txBox = slide.shapes.add_textbox(left, top, width, height) #p = text_frame.paragraphs[0] p=txBox.text_frame.paragraphs[0] p.text=footnote p.font.size = Pt(10) p.font.language_id = 3076 p.font.name='Microsoft YaHei UI' p.font.color.rgb=RGBColor(127,127,127) try: txBox.text_frame.fit_text(max_size=10) except: pass #print('cannot fit the size of font') return prs def plot_textbox(prs,texts,title=u'我是文本框页标题',summary=u'我是内容',footnote='',layouts=[0,0]): ''' 只绘制一个文本框,用于目录、小结等 ''' slide_width=prs.slide_width slide_height=prs.slide_height # 可能需要修改以适应更多的情形 title_only_slide = prs.slide_masters[layouts[0]].slide_layouts[layouts[1]] slide = prs.slides.add_slide(title_only_slide) #title=u'这里是标题' slide.shapes.title.text = title # 绘制副标题 if summary: left,top = Emu(0.15*slide_width), Emu(0.10*slide_height) width,height = Emu(0.7*slide_width), Emu(0.1*slide_height) txBox = slide.shapes.add_textbox(left, top, width, height) txBox.text_frame.text=summary # 绘制主体 left,top = Emu(0.15*slide_width), Emu(0.20*slide_height) width,height = Emu(0.7*slide_width), Emu(0.7*slide_height) txBox = slide.shapes.add_textbox(left, top, width, height) txBox.text_frame.text=texts # 添加脚注 footnote=u'这里是脚注' if footnote: left,top = Emu(0.025*slide_width), Emu(0.95*slide_height) width,height = Emu(0.70*slide_width), Emu(0.10*slide_height) txBox = slide.shapes.add_textbox(left, top, width, height) #p = text_frame.paragraphs[0] p=txBox.text_frame.paragraphs[0] p.text=footnote p.font.size = Pt(10) p.font.language_id = 3076 p.font.name='Microsoft YaHei UI' p.font.color.rgb=RGBColor(127,127,127) try: txBox.text_frame.fit_text(max_size=10) except: pass #print('cannot fit the size of font') return prs def plot_picture(prs,img_path,layouts=[0,0],title=u'我是文本框页标题',summary='',\ footnote=''): ''' 只插入一张图片,用于目录、小结等 ''' slide_width=prs.slide_width slide_height=prs.slide_height # 可能需要修改以适应更多的情形 title_only_slide = prs.slide_masters[layouts[0]].slide_layouts[layouts[1]] slide = prs.slides.add_slide(title_only_slide) #title=u'这里是标题' slide.shapes.title.text = title if summary: left,top = Emu(0.05*slide_width), Emu(0.10*slide_height) width,height = Emu(0.7*slide_width), Emu(0.1*slide_height) txBox = slide.shapes.add_textbox(left, top, width, height) txBox.text_frame.text=summary left,top = Emu(0.15*slide_width), Emu(0.2*slide_height) height=Emu(0.7*slide_height) slide.shapes.add_picture(img_path, left, top, height=height) # 添加脚注 footnote=u'这里是脚注' if footnote: left,top = Emu(0.025*slide_width), Emu(0.95*slide_height) width,height = Emu(0.70*slide_width), Emu(0.10*slide_height) txBox = slide.shapes.add_textbox(left, top, width, height) #p = text_frame.paragraphs[0] p=txBox.text_frame.paragraphs[0] p.text=footnote p.font.size = Pt(10) p.font.language_id = 3076 p.font.name='Microsoft YaHei UI' p.font.color.rgb=RGBColor(127,127,127) try: txBox.text_frame.fit_text(max_size=10) except: pass #print('cannot fit the size of font') return prs def plot_chart(prs,df,chart_type,title=u'我是标题',summary=u'我是简短的结论',\ footnote=None,chart_format=None,layouts=[0,0],has_data_labels=True): ''' 直接将数据绘制到一张ppt上,且高度定制化 默认都有图例,且图例在下方 默认都有数据标签 ''' slide_width=prs.slide_width slide_height=prs.slide_height # 可能需要修改以适应更多的情形 # layouts[0]代表第几个母版,layouts[1]代表母版中的第几个版式 title_only_slide = prs.slide_masters[layouts[0]].slide_layouts[layouts[1]] slide = prs.slides.add_slide(title_only_slide) # 添加标题 title=u'这里是标题' try: slide.shapes.title.text = title except: print('请检查模板,脚本没有找到合适的slide') return # 添加结论 summary=u'这里是一些简短的结论' #summary_loc=[0.10,0.14,0.80,0.15] left,top = Emu(config.summary_loc[0]*slide_width), Emu(config.summary_loc[1]*slide_height) width,height = Emu(config.summary_loc[2]*slide_width), Emu(config.summary_loc[3]*slide_height) txBox = slide.shapes.add_textbox(left, top, width, height) txBox.text_frame.text=summary txBox.text_frame.paragraphs[0].font.language_id = 3076 try: txBox.text_frame.fit_text(max_size=12) except: pass #print('cannot fit the size of font') # 添加脚注 footnote=u'这里是脚注' if footnote: left,top = Emu(0.025*slide_width), Emu(0.95*slide_height) width,height = Emu(0.70*slide_width), Emu(0.10*slide_height) txBox = slide.shapes.add_textbox(left, top, width, height) #p = text_frame.paragraphs[0] p=txBox.text_frame.paragraphs[0] p.text=footnote p.font.size = Pt(10) p.font.language_id = 3076 p.font.name='Microsoft YaHei UI' p.font.color.rgb=RGBColor(127,127,127) try: txBox.text_frame.fit_text(max_size=10) except: pass #print('cannot fit the size of font') # 插入图表 chart_type_code=chart_list[chart_type][1] chart_data=df_to_chartdata(df,chart_type_code) #left, top = Emu(0.05*slide_width), Emu(0.20*slide_height) #width, height = Emu(0.85*slide_width), Emu(0.70*slide_height) #chart_loc=[0.10,0.30,0.80,0.60] left, top = Emu(config.chart_loc[0]*slide_width), Emu(config.chart_loc[1]*slide_height) width, height = Emu(config.chart_loc[2]*slide_width), Emu(config.chart_loc[3]*slide_height) chart=slide.shapes.add_chart(chart_list[chart_type.upper()][0], \ left, top, width, height, chart_data).chart if chart_type_code in [-4169,72,73,74,75]: return font_default_size=Pt(10) # 添加图例 if (df.shape[1]>1) or (chart_type=='PIE'): chart.has_legend = True chart.legend.font.size=font_default_size chart.legend.position = XL_LEGEND_POSITION.BOTTOM chart.legend.include_in_layout = False try: chart.category_axis.tick_labels.font.size=font_default_size except: pass#暂时不知道怎么处理 try: chart.value_axis.tick_labels.font.size=font_default_size except: pass # 添加数据标签 non_available_list=['BUBBLE','BUBBLE_THREE_D_EFFECT','XY_SCATTER',\ 'XY_SCATTER_LINES','PIE'] # 大致检测是否采用百分比 # 1、单选题每列的和肯定是100,顶多相差+-5 # 2、多选题每一列的和大于100,但单个的小于100.此处可能会有误判,但暂时无解 # 3、可能会有某一列全为0,此时单独考虑 if ((df.sum()[df.sum()!=0]>90).all()) and ((df<=100).all().all()) and (u'总体' not in df.index): # 数据条的数据标签格式 #number_format1='0.0"%"' number_format1=config.number_format_data # 坐标轴的数据标签格式 #number_format2='0"%"' number_format2=config.number_format_tick else: number_format1='0.00' number_format2='0.0' if (chart_type not in non_available_list) or (chart_type == 'PIE'): plot = chart.plots[0] plot.has_data_labels = True plot.data_labels.font.size = font_default_size plot.data_labels.number_format = number_format1 #plot.data_labels.number_format_is_linked=True #data_labels = plot.data_labels #plot.data_labels.position = XL_LABEL_POSITION.BEST_FIT if (chart_type not in non_available_list): #chart.value_axis.maximum_scale = 1 if df.shape[1]==1: chart.value_axis.has_major_gridlines = False else: chart.value_axis.has_major_gridlines = True tick_labels = chart.value_axis.tick_labels tick_labels.number_format = number_format2 tick_labels.font.size = font_default_size # 修改纵坐标格式 ''' tick_labels = chart.value_axis.tick_labels tick_labels.number_format = '0"%"' tick_labels.font.bold = True tick_labels.font.size = Pt(10) ''' # 填充系列的颜色 ''' 最好的方法还是修改母版文件中的主题颜色,这里只提供方法 if df.shape[1]==1: chart.series[0].fill() ''' # 自定义format if chart_format: for k in chart_format: exec('chart.'+k+'='+'%s'%(chart_format[k])) return prs ''' if chart_type == 'BAR_TWO_WAY': chart ''' def plot_cover(prs,title=u'reportgen工具包封面',layouts=[0,0],xspace=8,yspace=6): slide_width=prs.slide_width slide_height=prs.slide_height # 可能需要修改以适应更多的情形 title_only_slide = prs.slide_masters[layouts[0]].slide_layouts[layouts[1]] slide = prs.slides.add_slide(title_only_slide) ## 随机生成连接点 seeds=np.round(np.dot(np.random.rand((xspace-1)*(yspace-1),2),np.diag([slide_width,slide_height]))) # 添加左边点 tmp=np.linspace(0,slide_height,yspace) seeds=np.concatenate((seeds,np.array([[0]*len(tmp),tmp]).T)) # 添加上边点 tmp=np.linspace(0,slide_width,xspace)[1:] seeds=np.concatenate((seeds,np.array([tmp,[0]*len(tmp)]).T)) # 添加右边点 tmp=np.linspace(0,slide_height,yspace)[1:] seeds=np.concatenate((seeds,np.array([[slide_width]*len(tmp),tmp]).T)) # 添加下边点 tmp=np.linspace(0,slide_width,xspace)[1:-1] seeds=np.concatenate((seeds,np.array([tmp,[slide_height]*len(tmp)]).T)) # 构造三角剖分,生成相应的三角形和平面图数据 center = np.mean(seeds, axis=0) t=np.sqrt(slide_width**2+slide_height**2)/2 dt = Delaunay2D(center, 2**(np.floor(np.log2(t))+1)) for s in seeds: dt.AddPoint(s) tri=dt.exportTriangles() graph=np.zeros((len(seeds),len(seeds))) for t in tri: graph[t[0],t[1]]=1 graph[t[1],t[2]]=1 graph[t[0],t[2]]=1 graph[t[1],t[0]]=1 graph[t[2],t[1]]=1 graph[t[2],t[1]]=1 from pptx.enum.shapes import MSO_CONNECTOR from pptx.enum.shapes import MSO_SHAPE shapes = slide.shapes # 添加连接线 for i in range(len(seeds)): for j in range(len(seeds)): if (i<j) and graph[i,j]==1: shapes.add_connector( MSO_CONNECTOR.STRAIGHT, Emu(seeds[i,0]), Emu(seeds[i,1]), Emu(seeds[j,0]), Emu(seeds[j,1])) # 添加圆点,原点的半径符合高斯分布 radius=slide_width/100 for i in range(len(seeds)): eps=np.random.normal(scale=radius*0.2) left=Emu(seeds[i,0])-radius-eps top=Emu(seeds[i,1])-radius-eps width=height=2*(radius+eps) shape=shapes.add_shape( MSO_SHAPE.OVAL,left, top, width, height) shape.line.width=Emu(0) fill = shape.fill fill.solid() fill.fore_color.rgb = RGBColor(218,227,243) # 添加标题 left,top = Emu(0), Emu(0.4*slide_height) width,height = Emu(1*slide_width), Emu(0.2*slide_height) shape=shapes.add_shape( MSO_SHAPE.RECTANGLE,left, top, width, height) shape.line.width=Emu(0) fill = shape.fill fill.solid() fill.fore_color.rgb = RGBColor(0,176,240) shape.text=title # 添加脚注 left,top = Emu(0.72*slide_width), Emu(0.93*slide_height) width,height = Emu(0.25*slide_width), Emu(0.07*slide_height) txBox = slide.shapes.add_textbox(left, top, width, height) txBox.text_frame.text='POWERED BY REPORTGEN' # 添加LOGO logo_path=os.path.join(_thisdir,'images','logo.png') if os.path.exists(logo_path): left,top = Emu(0.65*slide_width), Emu(0.94*slide_height) height=Emu(0.06*slide_height) slide.shapes.add_picture(logo_path, left, top, height=height) return prs def slides_data_gen(slides_data,chart_type_default='COLUMN_CLUSTERED'): '''自动补全pptx数据信息 slides_data: 默认需可迭代 每一页PPT设定为四个元素:标题、结论、主题、脚注 return ------ slides_data: 每一页ppt所需要的元素[ {title:,#标题 summary:,#结论 data:,# DataFrame数据、文本数据、图片地址等 slide_type:,#chart、table、text chart_type:图表类型 data_config:,#字典格式,绘制data其他所需要的相关参数,保留字段,暂时不用 footnote:,#脚注 layouts:#该slide使用的ppt版式 },] filename: 缺省以时间命名 template:使用的模板 ''' title='' summary='' footnote='' # 处理slides_data数据 if (not isinstance(slides_data,list)) and (not isinstance(slides_data,tuple)): slides_data=[slides_data] # 自动计算图表的格式 #np.issubdtype(a.as_matrix().dtype,np.number) # 补全相关信息 slides_data_new=[] for i in range(len(slides_data)): slide=slides_data[i] # 补全相关信息,数据处理部分待定 if not isinstance(slide,dict): slide={'data':slide} slide['title']=title slide['summary']=summary slide['footnote']=footnote slide['layouts']='auto' slide['data_config']=None if isinstance(slide['data'],pd.core.frame.DataFrame): slide['slide_type']='chart' slide['chart_type']=chart_type_default elif isinstance(slide['data'],pd.core.series.Series): slide['data']=pd.DataFrame(slide['data']) slide['slide_type']='chart' slide['chart_type']=chart_type_default elif isinstance(slide['data'],str) and os.path.exists(slide['data']): slide['slide_type']='picture' slide['chart_type']=None elif isinstance(slide['data'],str) and not(os.path.exists(slide['data'])): slide['slide_type']='textbox' slide['chart_type']='' else: print('未知的数据格式,请检查数据') slide['slide_type']=None slide['chart_type']=None continue elif isinstance(slide,dict): if 'data' not in slide: print('没有找到需要的数据,请检查') slide['slide_type']=None slide['chart_type']=None continue if isinstance(slide['data'],pd.core.series.Series): slide['data']=pd.DataFrame(slide['data']) if 'title' not in slide: slide['title']=title if 'summary' not in slide: slide['summary']=summary if 'footnote' not in slide: slide['footnote']=footnote if 'layouts' not in slide: slide['layouts']='auto' if 'data_config' not in slide: slide['data_config']=None slide['chart_type']=None if 'chart_type' not in slide else slide['chart_type'] if 'slide_type' not in slide: if isinstance(slide['data'],pd.core.frame.DataFrame): slide['slide_type']='chart' slide['chart_type']=chart_type_default elif isinstance(slide['data'],str) and os.path.exists(slide['data']): print('test') slide['slide_type']='picture' slide['chart_type']='' elif isinstance(slide['data'],str) and not(os.path.exists(slide['data'])): slide['slide_type']='textbox' slide['chart_type']='' else: print('未知的数据格式,请检查数据') slide['slide_type']=None slide['chart_type']=None continue slides_data_new.append(slide) return slides_data_new def genwordcloud(texts,mask=None,font_path=None,background_color='white'): '''生成词云 parameter ---------- mask: RGBA模式数组,最后一个分量是alpha通道, 默认会生成一个900*1200的椭圆 font_path: 采用的字体,建议采用安卓默认字体DroidSansFallback.ttf return ------- img:可以直接img.save('test.png') ''' from PIL import Image try: from wordcloud import WordCloud except: #raise Exception('wordcloud need install wordcloud package.') print('wordcloud need install wordcloud package.') return None if mask is None: tmp=np.zeros((900,1200),dtype=np.uint8) for i in range(tmp.shape[0]): for j in range(tmp.shape[1]): if (i-449.5)**2/(430**2)+(j-599.5)**2/(580**2)>1: tmp[i,j]=255 mask=np.zeros((900,1200,4),dtype=np.uint8) mask[:,:,0]=tmp mask[:,:,1]=tmp mask[:,:,2]=tmp mask[:,:,3]=255 else: mask=np.array(Image.open(mask)) wordcloud = WordCloud(background_color = background_color,font_path=font_path, mask = mask) wordcloud.generate(texts) img=wordcloud.to_image() return img class Report(): ''' 底层的类,负责一个 pptx 报告的相关接口 parameters: ----------- filename: pptx 文件路径,若无则新建一个文件 chart_type_default: 默认的图表类型 layouts_default: 新建slide时默认使用的 pptx 模板 title: 报告的名称 author: 报告的作者 example: --------- >>>r=Report(filename='') >>>r.add_cover(title='reportgen') >>>r.add_slides([]) >>>r.save() ''' def __init__(self,filename=None,chart_type_default='COLUMN_CLUSTERED',**kwargs): self.title=None self.author=None # self.filename = filename #导入一个存在的pptx文件 self.chart_type_default=chart_type_default if filename is None: if os.path.exists('template.pptx'): prs=Presentation('template.pptx') elif template_pptx is not None: prs=Presentation(template_pptx) else: prs=Presentation() else : # 分离出路径中的文件名 self.title=os.path.splitext(os.path.split(filename)[1])[0] prs=Presentation(filename) self.prs=prs title_only_slide=self._layouts() if title_only_slide: layouts=title_only_slide[0] else: layouts=[0,0] self.layouts_default=layouts for k in kwargs: setattr(self,k.lower(),kwargs[k]) def _layouts(self): '''给定pptx文件,自动识别标题等版式 ''' slide_width=self.prs.slide_width slide_height=self.prs.slide_height title_only_slide=[] #blank_slide=[] for i in range(len(self.prs.slide_masters)): slides=self.prs.slide_masters[i] #print('第{}个有{}个版式'.format(i,len(slides.slide_layouts))) for j in range(len(slides.slide_layouts)): slide=slides.slide_layouts[j] title_slide=0 placeholder_size=0 for k in range(len(slide.shapes)): shape=slide.shapes[k] if shape.is_placeholder and shape.has_text_frame: left,top=shape.left/slide_width,shape.top/slide_height height=shape.height/slide_height if left<1 and top<1 and height<1 and left>0 and top>0 and height>0: placeholder_size+=1 #print('left={:.2f},top={:.2f},height={:.2f}'.format(left,top,height)) if left<0.15 and top<0.15 and height <0.25: title_slide+=1 #print('{}个文本占位符,{}个title'.format(placeholder_size,title_slide)) if placeholder_size==1 and title_slide==1: title_only_slide.append([i,j]) #if placeholder_size==0: #blank_slide.append((i,j))s return title_only_slide def get_texts(self): # one for each text run in presentation text_runs = [] for slide in self.prs.slides: for shape in slide.shapes: if not shape.has_text_frame: continue for paragraph in shape.text_frame.paragraphs: for run in paragraph.runs: text_runs.append(run.text) return text_runs def get_images(self): try: from PIL import Image as PIL_Image from io import BytesIO except: print('please install the PIL.') return if not os.path.exists('.\\images'): os.mkdir('.\\images') n_images=0 for slide in self.prs.slides: for shape in slide.shapes: if 'Image' in str(type(shape)) or 'Picture' in str(type(shape)): n_images+=1 shape_image=shape.image #filename='.\\images\\'+shape_image.filename #r=str(np.random.randint(99)).zfill(2) filename='.\\images\\image%d'%n_images+'.'+shape_image.ext p = PIL_Image.open(BytesIO(shape_image.blob)) p.save(filename) #print('save {}'.format(shape_image.filename)) def add_slides(self,slides_data,chart_type_default=None): '''!使用的接口和下方的add_slide不一样,建议使用add_slide slides_data: 每一页ppt所需要的元素[ {title:,#标题 summary:,#结论 data:,# DataFrame数据、文本数据、图片地址等 slide_type:,#chart、table、text chart_type:图表类型 data_config:,#字典格式,绘制data其他所需要的相关参数,保留字段,暂时不用 footnote:,#脚注 layouts:#该slide使用的ppt版式 },] ''' if chart_type_default is None: chart_type_default=self.chart_type_default slides_data=slides_data_gen(slides_data,chart_type_default) for slide in slides_data: slide_type=slide['slide_type'] title=slide['title'] summary=slide['summary'] footnote=slide['footnote'] layouts=self.layouts_default if slide['layouts'] == 'auto' else slide['layouts'] data=slide['data'] chart_type=slide['chart_type'] if 'chart_type' in slide else None #data_config=slide['data_config']#暂时没有用该参数 if (slide_type is None) or (not isinstance(slide_type,str)): continue if slide_type == 'chart': self.prs=plot_chart(self.prs,data,chart_type=chart_type,layouts=layouts,\ title=title,summary=summary,footnote=footnote); elif slide_type == 'table': self.prs=plot_table(self.prs,data,layouts=layouts,title=title,summary=summary,\ footnote=footnote); elif slide_type in ['textbox','text']: self.prs=plot_textbox(self.prs,data,layouts=layouts,title=title,summary=summary,\ footnote=footnote); elif slide_type in ['picture','figure']: self.prs=plot_picture(self.prs,data,layouts=layouts,title=title,summary=summary,\ footnote=footnote); def add_cover(self,title='',author='',style='default',layouts='auto',size=[8,6]): if len(title) == 0: title = 'Analysis Report Powered by reportgen' if self.title is None else self.title if len(author) == 0: author='' if self.author is None else self.author title=title+'\n作者: '+author if len(author)>0 else title layouts=self.layouts_default if layouts == 'auto' else layouts if style == 'default': self.prs=plot_cover(self.prs,title=title,layouts=layouts,xspace=size[0],yspace=size[1]); def location_suggest(self,num=1,rate=0.78,data=None,summary=None): '''统一管理slides各个模块的位置 parameter -------- num: 主体内容(如图、外链图片、文本框等)的个数,默认从左到右依次排列 rate: 主体内容的宽度综合 data: list,通过数据类型智能判断位置,如有,则 num 失效 summary:如果summary为空,则非图表等位置都会上移动 return ----- locations: dict格式. l代表left,t代表top,w代表width,h代表height ''' slide_width,slide_height=self.prs.slide_width,self.prs.slide_height if 'summary_loc' in config.__dict__: summary_loc=config.summary_loc else: summary_loc=[0.10,0.14,0.80,0.15] if 'footnote_loc' in config.__dict__: footnote_loc=config.footnote_loc else: footnote_loc=[0.025,0.95,0.70,0.06] if 'data_loc' in config.__dict__: data_loc=config.data_loc else: data_loc=[0.11,0.30,0.78,0.60] num=len(data) if isinstance(data,list) else num locations={} locations['summary']={'l':Emu(summary_loc[0]*slide_width),'t':Emu(summary_loc[1]*slide_height),\ 'w':Emu(summary_loc[2]*slide_width),'h':Emu(summary_loc[3]*slide_height)} locations['footnote']={'l':Emu(footnote_loc[0]*slide_width),'t':Emu(footnote_loc[1]*slide_height),\ 'w':Emu(footnote_loc[2]*slide_width),'h':Emu(footnote_loc[3]*slide_height)} # 主体部分只有一个的情形 ''' 控制主体的宽度为78%,且居中显示。 ''' if (summary is not None) and len(summary)==0: data_loc[1]=data_loc[1]*0.84 if num>1: left=[(1-rate)*(i+1)/(float(num)+1)+rate*i/float(num) for i in range(num)] top=[data_loc[1]]*num width=[rate/float(num)]*num height=[data_loc[3]]*num locations['data']=[{'l':Emu(left[i]*slide_width),'t':Emu(top[i]*slide_height),\ 'w':Emu(width[i]*slide_width),'h':Emu(height[i]*slide_height)} for i in range(num)] else: # 暂时只修正单张图片常常不居中的问题,后期会修正多张图片 if data[0]['slide_type'] == 'picture': imgdata=mpimg.imread(data[0]['data']) img_height,img_width=imgdata.shape[:2] img_width_in_pptx=data_loc[3]*slide_height*img_width/img_height/slide_width data_loc[0]=0.5-img_width_in_pptx/2 locations['data']=[{'l':Emu(data_loc[0]*slide_width),'t':Emu(data_loc[1]*slide_height),\ 'w':Emu(data_loc[2]*slide_width),'h':Emu(data_loc[3]*slide_height)}] return locations def add_slide(self,data=[],title='',summary='',footnote='',layouts='auto',**kwarg): '''通用函数,添加一页幻灯片 parameter --------- data=[{'data':,'slide_type':,'type':,},] # 三个是必须字段,其他根据slide_type不同而不同 title: 标题 summary: 小结论 footnote: 脚注 layouts: 使用的母版样式 legend: bool,是否画网格线 data_labels: bool,是否画数据标签 number_format_data: 图的数据标签格式 number_format_tick: 横纵坐标的数据标签格式 ''' #slide_width=self.prs.slide_width #slide_height=self.prs.slide_height # 标准化data格式 if not(isinstance(data,list)): data=[data] for i,d in enumerate(data): if not(isinstance(d,dict)): if isinstance(d,(pd.core.frame.DataFrame,pd.core.frame.Series)): slide_type='chart' chart_type=self.chart_type_default d=pd.DataFrame(d) elif isinstance(d,str) and os.path.exists(d): slide_type='picture' chart_type='' elif isinstance(d,str) and not(os.path.exists(d)): slide_type='textbox' chart_type='' else: print('未知的数据格式,请检查数据') slide_type='' chart_type='' data[i]={'data':d,'slide_type':slide_type,'type':chart_type} # 各个模板的位置 locations=self.location_suggest(data=data,summary=summary) summary_loc=locations['summary'] footnote_loc=locations['footnote'] data_loc=locations['data'] # 选取的板式 if layouts == 'auto': layouts=self.layouts_default title_only_slide = self.prs.slide_masters[layouts[0]].slide_layouts[layouts[1]] slide = self.prs.slides.add_slide(title_only_slide) #输出标题 slide.shapes.title.text = title # 输出副标题 summary if summary: txBox = slide.shapes.add_textbox(summary_loc['l'], summary_loc['t'], summary_loc['w'], summary_loc['h']) txBox.text_frame.text=summary txBox.text_frame.paragraphs[0].font.language_id = 3076 try: txBox.text_frame.fit_text(max_size=12) except: pass # 输出脚注 footnote if footnote: txBox = slide.shapes.add_textbox(footnote_loc['l'], footnote_loc['t'], footnote_loc['w'], footnote_loc['h']) #p = text_frame.paragraphs[0] p=txBox.text_frame.paragraphs[0] p.text=footnote p.font.size = Pt(10) p.font.language_id = 3076 p.font.name='Microsoft YaHei UI' p.font.color.rgb=RGBColor(127,127,127) try: txBox.text_frame.fit_text(max_size=10) except: pass #print('cannot fit the size of font') # 绘制主体部分 for i,dd in enumerate(data): slide_type=dd['slide_type'] left,top=data_loc[i]['l'],data_loc[i]['t'] width,height=data_loc[i]['w'],data_loc[i]['h'] chart_type=dd['type'] if 'type' in dd else self.chart_type_default if slide_type in ['table']: # 绘制表格 '''针对表格大小修正 R,C=dd['data'].shape width=max(0.5,min(1,C/6.0))*width height=max(0.5,min(1,R/12.0))*height left=0.5-width/2 top=0.25 ''' df_to_table(slide,dd['data'],left,top,width,height,index_names=True) elif slide_type in ['textbox']: # 输出文本框 txBox = slide.shapes.add_textbox(left, top, width, height) txBox.text_frame.text=dd['data'] txBox.text_frame.paragraphs[0].font.language_id = 3076 try: txBox.text_frame.fit_text(max_size=12) except: pass elif slide_type in ['picture','figure']: slide.shapes.add_picture(dd['data'], left, top, height=height) elif slide_type in ['chart']: # 插入图表 chart_type_code=chart_list[chart_type][1] if 'pptx.chart.data.ChartData' in str(type(dd['data'])): chart_data=dd['data'] else: chart_data=df_to_chartdata(dd['data'],chart_type_code) chart=slide.shapes.add_chart(chart_list[chart_type.upper()][0],left, top, width, height, chart_data).chart if chart_type_code in [-4169,72,73,74,75]: continue font_default_size=Pt(10) if 'font_default_size' not in config.__dict__ else config.font_default_size # 添加图例 has_legend=kwarg['legend'] if 'legend' in kwarg else True if has_legend and ((dd['data'].shape[1]>1) or (chart_type=='PIE')): chart.has_legend = has_legend chart.legend.font.size=font_default_size chart.legend.position = XL_LEGEND_POSITION.BOTTOM chart.legend.include_in_layout = False try: chart.category_axis.tick_labels.font.size=font_default_size except: pass#暂时不知道怎么处理 try: chart.value_axis.tick_labels.font.size=font_default_size except: pass # 添加数据标签 non_available_list=['BUBBLE','BUBBLE_THREE_D_EFFECT','XY_SCATTER','XY_SCATTER_LINES','PIE'] # 数据标签数值格式 # 大致检测是否采用百分比 # 1、单选题每列的和肯定是100,顶多相差+-5 # 2、多选题每一列的和大于100,但单个的小于100.此处可能会有误判,但暂时无解 # 3、可能会有某一列全为0,此时单独考虑 if isinstance(dd['data'],(pd.core.frame.DataFrame,pd.core.frame.Series)) and ((dd['data'].sum()[dd['data'].sum()!=0]>90).all()) and ((dd['data']<=100).all().all()): # 数据条的数据标签格式 number_format1=config.number_format_data # 坐标轴的数据标签格式 number_format2=config.number_format_tick else: number_format1='0.00' number_format2='0.0' if 'number_format_data' in dd: number_format1=dd['number_format_data'] if 'number_format_tick' in dd: number_format2=dd['number_format_tick'] if 'number_format_data' in kwarg: number_format1=kwarg['number_format_data'] if 'number_format_tick' in kwarg: number_format2=kwarg['number_format_tick'] if 'data_labels' in kwarg: has_data_labels = kwarg['data_labels'] else: has_data_labels=True if (chart_type not in non_available_list) or (chart_type == 'PIE'): plot = chart.plots[0] plot.has_data_labels = has_data_labels if has_data_labels: plot.data_labels.font.size = font_default_size plot.data_labels.number_format = number_format1 #data_labels = plot.data_labels #plot.data_labels.position = XL_LABEL_POSITION.BEST_FIT if (chart_type not in non_available_list): #chart.value_axis.maximum_scale = 1 if dd['data'].shape[1]==1: chart.value_axis.has_major_gridlines = False else: chart.value_axis.has_major_gridlines = True tick_labels = chart.value_axis.tick_labels tick_labels.number_format = number_format2 tick_labels.font.size = font_default_size def save(self,filename=None): assert (filename is not None) or (self.title is not None) filename=self.title+time.strftime('_%Y%m%d%H%M.pptx', time.localtime()) if filename is None else filename filename=os.path.splitext(filename)[0]+'.pptx' self.prs.save(filename)
[ "numpy.sqrt", "numpy.random.rand", "matplotlib.image.imread", "io.BytesIO", "pptx.Presentation", "pptx.chart.data.XyChartData", "numpy.mean", "pptx.dml.color.RGBColor", "os.path.exists", "pptx.util.Emu", "os.path.split", "pandas.set_option", "pptx.chart.data.ChartData", "numpy.linspace", ...
[((147, 206), 'pandas.set_option', 'pd.set_option', (['"""display.float_format"""', "(lambda x: '%.2f' % x)"], {}), "('display.float_format', lambda x: '%.2f' % x)\n", (160, 206), True, 'import pandas as pd\n'), ((634, 657), 'os.path.split', 'os.path.split', (['__file__'], {}), '(__file__)\n', (647, 657), False, 'import os\n'), ((787, 818), 'matplotlib.font_manager.FontProperties', 'FontProperties', ([], {'fname': 'font_path'}), '(fname=font_path)\n', (801, 818), False, 'from matplotlib.font_manager import FontProperties\n'), ((4160, 4176), 'pandas.DataFrame', 'pd.DataFrame', (['df'], {}), '(df)\n', (4172, 4176), True, 'import pandas as pd\n'), ((6970, 6986), 'pandas.DataFrame', 'pd.DataFrame', (['df'], {}), '(df)\n', (6982, 6986), True, 'import pandas as pd\n'), ((7739, 7762), 'pptx.util.Emu', 'Emu', (['(left * slide_width)'], {}), '(left * slide_width)\n', (7742, 7762), False, 'from pptx.util import Inches, Pt, Emu\n'), ((7769, 7792), 'pptx.util.Emu', 'Emu', (['(top * slide_height)'], {}), '(top * slide_height)\n', (7772, 7792), False, 'from pptx.util import Inches, Pt, Emu\n'), ((7801, 7825), 'pptx.util.Emu', 'Emu', (['(width * slide_width)'], {}), '(width * slide_width)\n', (7804, 7825), False, 'from pptx.util import Inches, Pt, Emu\n'), ((7835, 7861), 'pptx.util.Emu', 'Emu', (['(height * slide_height)'], {}), '(height * slide_height)\n', (7838, 7861), False, 'from pptx.util import Inches, Pt, Emu\n'), ((10880, 10903), 'pptx.util.Emu', 'Emu', (['(0.7 * slide_height)'], {}), '(0.7 * slide_height)\n', (10883, 10903), False, 'from pptx.util import Inches, Pt, Emu\n'), ((14118, 14124), 'pptx.util.Pt', 'Pt', (['(10)'], {}), '(10)\n', (14120, 14124), False, 'from pptx.util import Inches, Pt, Emu\n'), ((16940, 16976), 'numpy.linspace', 'np.linspace', (['(0)', 'slide_height', 'yspace'], {}), '(0, slide_height, yspace)\n', (16951, 16976), True, 'import numpy as np\n'), ((17475, 17497), 'numpy.mean', 'np.mean', (['seeds'], {'axis': '(0)'}), '(seeds, axis=0)\n', (17482, 17497), True, 'import numpy as np\n'), ((18956, 18962), 'pptx.util.Emu', 'Emu', (['(0)'], {}), '(0)\n', (18959, 18962), False, 'from pptx.util import Inches, Pt, Emu\n'), ((19028, 19049), 'pptx.dml.color.RGBColor', 'RGBColor', (['(0)', '(176)', '(240)'], {}), '(0, 176, 240)\n', (19036, 19049), False, 'from pptx.dml.color import RGBColor\n'), ((19347, 19391), 'os.path.join', 'os.path.join', (['_thisdir', '"""images"""', '"""logo.png"""'], {}), "(_thisdir, 'images', 'logo.png')\n", (19359, 19391), False, 'import os\n'), ((19397, 19422), 'os.path.exists', 'os.path.exists', (['logo_path'], {}), '(logo_path)\n', (19411, 19422), False, 'import os\n'), ((24342, 24418), 'wordcloud.WordCloud', 'WordCloud', ([], {'background_color': 'background_color', 'font_path': 'font_path', 'mask': 'mask'}), '(background_color=background_color, font_path=font_path, mask=mask)\n', (24351, 24418), False, 'from wordcloud import WordCloud\n'), ((5569, 5585), 'pandas.DataFrame', 'pd.DataFrame', (['df'], {}), '(df)\n', (5581, 5585), True, 'import pandas as pd\n'), ((5699, 5710), 'pptx.chart.data.ChartData', 'ChartData', ([], {}), '()\n', (5708, 5710), False, 'from pptx.chart.data import ChartData, XyChartData, BubbleChartData\n'), ((5977, 5990), 'pptx.chart.data.XyChartData', 'XyChartData', ([], {}), '()\n', (5988, 5990), False, 'from pptx.chart.data import ChartData, XyChartData, BubbleChartData\n'), ((6380, 6397), 'pptx.chart.data.BubbleChartData', 'BubbleChartData', ([], {}), '()\n', (6395, 6397), False, 'from pptx.chart.data import ChartData, XyChartData, BubbleChartData\n'), ((7275, 7298), 'pptx.util.Emu', 'Emu', (['(0.05 * slide_width)'], {}), '(0.05 * slide_width)\n', (7278, 7298), False, 'from pptx.util import Inches, Pt, Emu\n'), ((7298, 7321), 'pptx.util.Emu', 'Emu', (['(0.1 * slide_height)'], {}), '(0.1 * slide_height)\n', (7301, 7321), False, 'from pptx.util import Inches, Pt, Emu\n'), ((7340, 7362), 'pptx.util.Emu', 'Emu', (['(0.7 * slide_width)'], {}), '(0.7 * slide_width)\n', (7343, 7362), False, 'from pptx.util import Inches, Pt, Emu\n'), ((7362, 7385), 'pptx.util.Emu', 'Emu', (['(0.1 * slide_height)'], {}), '(0.1 * slide_height)\n', (7365, 7385), False, 'from pptx.util import Inches, Pt, Emu\n'), ((8303, 8309), 'pptx.util.Pt', 'Pt', (['(10)'], {}), '(10)\n', (8305, 8309), False, 'from pptx.util import Inches, Pt, Emu\n'), ((8410, 8433), 'pptx.dml.color.RGBColor', 'RGBColor', (['(127)', '(127)', '(127)'], {}), '(127, 127, 127)\n', (8418, 8433), False, 'from pptx.dml.color import RGBColor\n'), ((9287, 9310), 'pptx.util.Emu', 'Emu', (['(0.15 * slide_width)'], {}), '(0.15 * slide_width)\n', (9290, 9310), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9310, 9333), 'pptx.util.Emu', 'Emu', (['(0.2 * slide_height)'], {}), '(0.2 * slide_height)\n', (9313, 9333), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9352, 9374), 'pptx.util.Emu', 'Emu', (['(0.7 * slide_width)'], {}), '(0.7 * slide_width)\n', (9355, 9374), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9374, 9397), 'pptx.util.Emu', 'Emu', (['(0.7 * slide_height)'], {}), '(0.7 * slide_height)\n', (9377, 9397), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9865, 9871), 'pptx.util.Pt', 'Pt', (['(10)'], {}), '(10)\n', (9867, 9871), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9972, 9995), 'pptx.dml.color.RGBColor', 'RGBColor', (['(127)', '(127)', '(127)'], {}), '(127, 127, 127)\n', (9980, 9995), False, 'from pptx.dml.color import RGBColor\n'), ((10824, 10847), 'pptx.util.Emu', 'Emu', (['(0.15 * slide_width)'], {}), '(0.15 * slide_width)\n', (10827, 10847), False, 'from pptx.util import Inches, Pt, Emu\n'), ((10847, 10870), 'pptx.util.Emu', 'Emu', (['(0.2 * slide_height)'], {}), '(0.2 * slide_height)\n', (10850, 10870), False, 'from pptx.util import Inches, Pt, Emu\n'), ((11340, 11346), 'pptx.util.Pt', 'Pt', (['(10)'], {}), '(10)\n', (11342, 11346), False, 'from pptx.util import Inches, Pt, Emu\n'), ((11447, 11470), 'pptx.dml.color.RGBColor', 'RGBColor', (['(127)', '(127)', '(127)'], {}), '(127, 127, 127)\n', (11455, 11470), False, 'from pptx.dml.color import RGBColor\n'), ((12335, 12375), 'pptx.util.Emu', 'Emu', (['(config.summary_loc[0] * slide_width)'], {}), '(config.summary_loc[0] * slide_width)\n', (12338, 12375), False, 'from pptx.util import Inches, Pt, Emu\n'), ((12375, 12416), 'pptx.util.Emu', 'Emu', (['(config.summary_loc[1] * slide_height)'], {}), '(config.summary_loc[1] * slide_height)\n', (12378, 12416), False, 'from pptx.util import Inches, Pt, Emu\n'), ((12434, 12474), 'pptx.util.Emu', 'Emu', (['(config.summary_loc[2] * slide_width)'], {}), '(config.summary_loc[2] * slide_width)\n', (12437, 12474), False, 'from pptx.util import Inches, Pt, Emu\n'), ((12474, 12515), 'pptx.util.Emu', 'Emu', (['(config.summary_loc[3] * slide_height)'], {}), '(config.summary_loc[3] * slide_height)\n', (12477, 12515), False, 'from pptx.util import Inches, Pt, Emu\n'), ((13172, 13178), 'pptx.util.Pt', 'Pt', (['(10)'], {}), '(10)\n', (13174, 13178), False, 'from pptx.util import Inches, Pt, Emu\n'), ((13279, 13302), 'pptx.dml.color.RGBColor', 'RGBColor', (['(127)', '(127)', '(127)'], {}), '(127, 127, 127)\n', (13287, 13302), False, 'from pptx.dml.color import RGBColor\n'), ((13741, 13779), 'pptx.util.Emu', 'Emu', (['(config.chart_loc[0] * slide_width)'], {}), '(config.chart_loc[0] * slide_width)\n', (13744, 13779), False, 'from pptx.util import Inches, Pt, Emu\n'), ((13779, 13818), 'pptx.util.Emu', 'Emu', (['(config.chart_loc[1] * slide_height)'], {}), '(config.chart_loc[1] * slide_height)\n', (13782, 13818), False, 'from pptx.util import Inches, Pt, Emu\n'), ((13837, 13875), 'pptx.util.Emu', 'Emu', (['(config.chart_loc[2] * slide_width)'], {}), '(config.chart_loc[2] * slide_width)\n', (13840, 13875), False, 'from pptx.util import Inches, Pt, Emu\n'), ((13875, 13914), 'pptx.util.Emu', 'Emu', (['(config.chart_loc[3] * slide_height)'], {}), '(config.chart_loc[3] * slide_height)\n', (13878, 13914), False, 'from pptx.util import Inches, Pt, Emu\n'), ((17060, 17095), 'numpy.linspace', 'np.linspace', (['(0)', 'slide_width', 'xspace'], {}), '(0, slide_width, xspace)\n', (17071, 17095), True, 'import numpy as np\n'), ((17183, 17219), 'numpy.linspace', 'np.linspace', (['(0)', 'slide_height', 'yspace'], {}), '(0, slide_height, yspace)\n', (17194, 17219), True, 'import numpy as np\n'), ((17317, 17352), 'numpy.linspace', 'np.linspace', (['(0)', 'slide_width', 'xspace'], {}), '(0, slide_width, xspace)\n', (17328, 17352), True, 'import numpy as np\n'), ((17504, 17549), 'numpy.sqrt', 'np.sqrt', (['(slide_width ** 2 + slide_height ** 2)'], {}), '(slide_width ** 2 + slide_height ** 2)\n', (17511, 17549), True, 'import numpy as np\n'), ((18377, 18413), 'numpy.random.normal', 'np.random.normal', ([], {'scale': '(radius * 0.2)'}), '(scale=radius * 0.2)\n', (18393, 18413), True, 'import numpy as np\n'), ((18633, 18639), 'pptx.util.Emu', 'Emu', (['(0)'], {}), '(0)\n', (18636, 18639), False, 'from pptx.util import Inches, Pt, Emu\n'), ((18717, 18740), 'pptx.dml.color.RGBColor', 'RGBColor', (['(218)', '(227)', '(243)'], {}), '(218, 227, 243)\n', (18725, 18740), False, 'from pptx.dml.color import RGBColor\n'), ((18766, 18772), 'pptx.util.Emu', 'Emu', (['(0)'], {}), '(0)\n', (18769, 18772), False, 'from pptx.util import Inches, Pt, Emu\n'), ((18774, 18797), 'pptx.util.Emu', 'Emu', (['(0.4 * slide_height)'], {}), '(0.4 * slide_height)\n', (18777, 18797), False, 'from pptx.util import Inches, Pt, Emu\n'), ((18815, 18835), 'pptx.util.Emu', 'Emu', (['(1 * slide_width)'], {}), '(1 * slide_width)\n', (18818, 18835), False, 'from pptx.util import Inches, Pt, Emu\n'), ((18835, 18858), 'pptx.util.Emu', 'Emu', (['(0.2 * slide_height)'], {}), '(0.2 * slide_height)\n', (18838, 18858), False, 'from pptx.util import Inches, Pt, Emu\n'), ((19096, 19119), 'pptx.util.Emu', 'Emu', (['(0.72 * slide_width)'], {}), '(0.72 * slide_width)\n', (19099, 19119), False, 'from pptx.util import Inches, Pt, Emu\n'), ((19119, 19143), 'pptx.util.Emu', 'Emu', (['(0.93 * slide_height)'], {}), '(0.93 * slide_height)\n', (19122, 19143), False, 'from pptx.util import Inches, Pt, Emu\n'), ((19161, 19184), 'pptx.util.Emu', 'Emu', (['(0.25 * slide_width)'], {}), '(0.25 * slide_width)\n', (19164, 19184), False, 'from pptx.util import Inches, Pt, Emu\n'), ((19184, 19208), 'pptx.util.Emu', 'Emu', (['(0.07 * slide_height)'], {}), '(0.07 * slide_height)\n', (19187, 19208), False, 'from pptx.util import Inches, Pt, Emu\n'), ((19504, 19528), 'pptx.util.Emu', 'Emu', (['(0.06 * slide_height)'], {}), '(0.06 * slide_height)\n', (19507, 19528), False, 'from pptx.util import Inches, Pt, Emu\n'), ((23914, 23951), 'numpy.zeros', 'np.zeros', (['(900, 1200)'], {'dtype': 'np.uint8'}), '((900, 1200), dtype=np.uint8)\n', (23922, 23951), True, 'import numpy as np\n'), ((24142, 24182), 'numpy.zeros', 'np.zeros', (['(900, 1200, 4)'], {'dtype': 'np.uint8'}), '((900, 1200, 4), dtype=np.uint8)\n', (24150, 24182), True, 'import numpy as np\n'), ((7995, 8019), 'pptx.util.Emu', 'Emu', (['(0.025 * slide_width)'], {}), '(0.025 * slide_width)\n', (7998, 8019), False, 'from pptx.util import Inches, Pt, Emu\n'), ((8019, 8043), 'pptx.util.Emu', 'Emu', (['(0.95 * slide_height)'], {}), '(0.95 * slide_height)\n', (8022, 8043), False, 'from pptx.util import Inches, Pt, Emu\n'), ((8065, 8087), 'pptx.util.Emu', 'Emu', (['(0.7 * slide_width)'], {}), '(0.7 * slide_width)\n', (8068, 8087), False, 'from pptx.util import Inches, Pt, Emu\n'), ((8088, 8111), 'pptx.util.Emu', 'Emu', (['(0.1 * slide_height)'], {}), '(0.1 * slide_height)\n', (8091, 8111), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9043, 9066), 'pptx.util.Emu', 'Emu', (['(0.15 * slide_width)'], {}), '(0.15 * slide_width)\n', (9046, 9066), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9066, 9089), 'pptx.util.Emu', 'Emu', (['(0.1 * slide_height)'], {}), '(0.1 * slide_height)\n', (9069, 9089), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9112, 9134), 'pptx.util.Emu', 'Emu', (['(0.7 * slide_width)'], {}), '(0.7 * slide_width)\n', (9115, 9134), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9134, 9157), 'pptx.util.Emu', 'Emu', (['(0.1 * slide_height)'], {}), '(0.1 * slide_height)\n', (9137, 9157), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9557, 9581), 'pptx.util.Emu', 'Emu', (['(0.025 * slide_width)'], {}), '(0.025 * slide_width)\n', (9560, 9581), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9581, 9605), 'pptx.util.Emu', 'Emu', (['(0.95 * slide_height)'], {}), '(0.95 * slide_height)\n', (9584, 9605), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9627, 9649), 'pptx.util.Emu', 'Emu', (['(0.7 * slide_width)'], {}), '(0.7 * slide_width)\n', (9630, 9649), False, 'from pptx.util import Inches, Pt, Emu\n'), ((9650, 9673), 'pptx.util.Emu', 'Emu', (['(0.1 * slide_height)'], {}), '(0.1 * slide_height)\n', (9653, 9673), False, 'from pptx.util import Inches, Pt, Emu\n'), ((10591, 10614), 'pptx.util.Emu', 'Emu', (['(0.05 * slide_width)'], {}), '(0.05 * slide_width)\n', (10594, 10614), False, 'from pptx.util import Inches, Pt, Emu\n'), ((10614, 10637), 'pptx.util.Emu', 'Emu', (['(0.1 * slide_height)'], {}), '(0.1 * slide_height)\n', (10617, 10637), False, 'from pptx.util import Inches, Pt, Emu\n'), ((10660, 10682), 'pptx.util.Emu', 'Emu', (['(0.7 * slide_width)'], {}), '(0.7 * slide_width)\n', (10663, 10682), False, 'from pptx.util import Inches, Pt, Emu\n'), ((10682, 10705), 'pptx.util.Emu', 'Emu', (['(0.1 * slide_height)'], {}), '(0.1 * slide_height)\n', (10685, 10705), False, 'from pptx.util import Inches, Pt, Emu\n'), ((11032, 11056), 'pptx.util.Emu', 'Emu', (['(0.025 * slide_width)'], {}), '(0.025 * slide_width)\n', (11035, 11056), False, 'from pptx.util import Inches, Pt, Emu\n'), ((11056, 11080), 'pptx.util.Emu', 'Emu', (['(0.95 * slide_height)'], {}), '(0.95 * slide_height)\n', (11059, 11080), False, 'from pptx.util import Inches, Pt, Emu\n'), ((11102, 11124), 'pptx.util.Emu', 'Emu', (['(0.7 * slide_width)'], {}), '(0.7 * slide_width)\n', (11105, 11124), False, 'from pptx.util import Inches, Pt, Emu\n'), ((11125, 11148), 'pptx.util.Emu', 'Emu', (['(0.1 * slide_height)'], {}), '(0.1 * slide_height)\n', (11128, 11148), False, 'from pptx.util import Inches, Pt, Emu\n'), ((12864, 12888), 'pptx.util.Emu', 'Emu', (['(0.025 * slide_width)'], {}), '(0.025 * slide_width)\n', (12867, 12888), False, 'from pptx.util import Inches, Pt, Emu\n'), ((12888, 12912), 'pptx.util.Emu', 'Emu', (['(0.95 * slide_height)'], {}), '(0.95 * slide_height)\n', (12891, 12912), False, 'from pptx.util import Inches, Pt, Emu\n'), ((12934, 12956), 'pptx.util.Emu', 'Emu', (['(0.7 * slide_width)'], {}), '(0.7 * slide_width)\n', (12937, 12956), False, 'from pptx.util import Inches, Pt, Emu\n'), ((12957, 12980), 'pptx.util.Emu', 'Emu', (['(0.1 * slide_height)'], {}), '(0.1 * slide_height)\n', (12960, 12980), False, 'from pptx.util import Inches, Pt, Emu\n'), ((16842, 16888), 'numpy.random.rand', 'np.random.rand', (['((xspace - 1) * (yspace - 1))', '(2)'], {}), '((xspace - 1) * (yspace - 1), 2)\n', (16856, 16888), True, 'import numpy as np\n'), ((16882, 16918), 'numpy.diag', 'np.diag', (['[slide_width, slide_height]'], {}), '([slide_width, slide_height])\n', (16889, 16918), True, 'import numpy as np\n'), ((19443, 19466), 'pptx.util.Emu', 'Emu', (['(0.65 * slide_width)'], {}), '(0.65 * slide_width)\n', (19446, 19466), False, 'from pptx.util import Inches, Pt, Emu\n'), ((19466, 19490), 'pptx.util.Emu', 'Emu', (['(0.94 * slide_height)'], {}), '(0.94 * slide_height)\n', (19469, 19490), False, 'from pptx.util import Inches, Pt, Emu\n'), ((24308, 24324), 'PIL.Image.open', 'Image.open', (['mask'], {}), '(mask)\n', (24318, 24324), False, 'from PIL import Image\n'), ((25153, 25184), 'os.path.exists', 'os.path.exists', (['"""template.pptx"""'], {}), "('template.pptx')\n", (25167, 25184), False, 'import os\n'), ((25508, 25530), 'pptx.Presentation', 'Presentation', (['filename'], {}), '(filename)\n', (25520, 25530), False, 'from pptx import Presentation\n'), ((27957, 27984), 'os.path.exists', 'os.path.exists', (['""".\\\\images"""'], {}), "('.\\\\images')\n", (27971, 27984), False, 'import os\n'), ((27998, 28019), 'os.mkdir', 'os.mkdir', (['""".\\\\images"""'], {}), "('.\\\\images')\n", (28006, 28019), False, 'import os\n'), ((32150, 32183), 'pptx.util.Emu', 'Emu', (['(summary_loc[0] * slide_width)'], {}), '(summary_loc[0] * slide_width)\n', (32153, 32183), False, 'from pptx.util import Inches, Pt, Emu\n'), ((32186, 32220), 'pptx.util.Emu', 'Emu', (['(summary_loc[1] * slide_height)'], {}), '(summary_loc[1] * slide_height)\n', (32189, 32220), False, 'from pptx.util import Inches, Pt, Emu\n'), ((32242, 32275), 'pptx.util.Emu', 'Emu', (['(summary_loc[2] * slide_width)'], {}), '(summary_loc[2] * slide_width)\n', (32245, 32275), False, 'from pptx.util import Inches, Pt, Emu\n'), ((32278, 32312), 'pptx.util.Emu', 'Emu', (['(summary_loc[3] * slide_height)'], {}), '(summary_loc[3] * slide_height)\n', (32281, 32312), False, 'from pptx.util import Inches, Pt, Emu\n'), ((32348, 32382), 'pptx.util.Emu', 'Emu', (['(footnote_loc[0] * slide_width)'], {}), '(footnote_loc[0] * slide_width)\n', (32351, 32382), False, 'from pptx.util import Inches, Pt, Emu\n'), ((32385, 32420), 'pptx.util.Emu', 'Emu', (['(footnote_loc[1] * slide_height)'], {}), '(footnote_loc[1] * slide_height)\n', (32388, 32420), False, 'from pptx.util import Inches, Pt, Emu\n'), ((32442, 32476), 'pptx.util.Emu', 'Emu', (['(footnote_loc[2] * slide_width)'], {}), '(footnote_loc[2] * slide_width)\n', (32445, 32476), False, 'from pptx.util import Inches, Pt, Emu\n'), ((32479, 32514), 'pptx.util.Emu', 'Emu', (['(footnote_loc[3] * slide_height)'], {}), '(footnote_loc[3] * slide_height)\n', (32482, 32514), False, 'from pptx.util import Inches, Pt, Emu\n'), ((36283, 36289), 'pptx.util.Pt', 'Pt', (['(10)'], {}), '(10)\n', (36285, 36289), False, 'from pptx.util import Inches, Pt, Emu\n'), ((36402, 36425), 'pptx.dml.color.RGBColor', 'RGBColor', (['(127)', '(127)', '(127)'], {}), '(127, 127, 127)\n', (36410, 36425), False, 'from pptx.dml.color import RGBColor\n'), ((18425, 18441), 'pptx.util.Emu', 'Emu', (['seeds[i, 0]'], {}), '(seeds[i, 0])\n', (18428, 18441), False, 'from pptx.util import Inches, Pt, Emu\n'), ((18464, 18480), 'pptx.util.Emu', 'Emu', (['seeds[i, 1]'], {}), '(seeds[i, 1])\n', (18467, 18480), False, 'from pptx.util import Inches, Pt, Emu\n'), ((25206, 25235), 'pptx.Presentation', 'Presentation', (['"""template.pptx"""'], {}), "('template.pptx')\n", (25218, 25235), False, 'from pptx import Presentation\n'), ((33235, 33264), 'matplotlib.image.imread', 'mpimg.imread', (["data[0]['data']"], {}), "(data[0]['data'])\n", (33247, 33264), True, 'import matplotlib.image as mpimg\n'), ((41971, 41997), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (41987, 41997), False, 'import os\n'), ((17587, 17597), 'numpy.log2', 'np.log2', (['t'], {}), '(t)\n', (17594, 17597), True, 'import numpy as np\n'), ((18215, 18231), 'pptx.util.Emu', 'Emu', (['seeds[i, 0]'], {}), '(seeds[i, 0])\n', (18218, 18231), False, 'from pptx.util import Inches, Pt, Emu\n'), ((18232, 18248), 'pptx.util.Emu', 'Emu', (['seeds[i, 1]'], {}), '(seeds[i, 1])\n', (18235, 18248), False, 'from pptx.util import Inches, Pt, Emu\n'), ((18249, 18265), 'pptx.util.Emu', 'Emu', (['seeds[j, 0]'], {}), '(seeds[j, 0])\n', (18252, 18265), False, 'from pptx.util import Inches, Pt, Emu\n'), ((18266, 18282), 'pptx.util.Emu', 'Emu', (['seeds[j, 1]'], {}), '(seeds[j, 1])\n', (18269, 18282), False, 'from pptx.util import Inches, Pt, Emu\n'), ((21020, 21047), 'pandas.DataFrame', 'pd.DataFrame', (["slide['data']"], {}), "(slide['data'])\n", (21032, 21047), True, 'import pandas as pd\n'), ((21965, 21992), 'pandas.DataFrame', 'pd.DataFrame', (["slide['data']"], {}), "(slide['data'])\n", (21977, 21992), True, 'import pandas as pd\n'), ((25300, 25327), 'pptx.Presentation', 'Presentation', (['template_pptx'], {}), '(template_pptx)\n', (25312, 25327), False, 'from pptx import Presentation\n'), ((25366, 25380), 'pptx.Presentation', 'Presentation', ([], {}), '()\n', (25378, 25380), False, 'from pptx import Presentation\n'), ((32934, 32960), 'pptx.util.Emu', 'Emu', (['(left[i] * slide_width)'], {}), '(left[i] * slide_width)\n', (32937, 32960), False, 'from pptx.util import Inches, Pt, Emu\n'), ((32963, 32989), 'pptx.util.Emu', 'Emu', (['(top[i] * slide_height)'], {}), '(top[i] * slide_height)\n', (32966, 32989), False, 'from pptx.util import Inches, Pt, Emu\n'), ((33015, 33042), 'pptx.util.Emu', 'Emu', (['(width[i] * slide_width)'], {}), '(width[i] * slide_width)\n', (33018, 33042), False, 'from pptx.util import Inches, Pt, Emu\n'), ((33045, 33074), 'pptx.util.Emu', 'Emu', (['(height[i] * slide_height)'], {}), '(height[i] * slide_height)\n', (33048, 33074), False, 'from pptx.util import Inches, Pt, Emu\n'), ((33501, 33531), 'pptx.util.Emu', 'Emu', (['(data_loc[0] * slide_width)'], {}), '(data_loc[0] * slide_width)\n', (33504, 33531), False, 'from pptx.util import Inches, Pt, Emu\n'), ((33534, 33565), 'pptx.util.Emu', 'Emu', (['(data_loc[1] * slide_height)'], {}), '(data_loc[1] * slide_height)\n', (33537, 33565), False, 'from pptx.util import Inches, Pt, Emu\n'), ((33591, 33621), 'pptx.util.Emu', 'Emu', (['(data_loc[2] * slide_width)'], {}), '(data_loc[2] * slide_width)\n', (33594, 33621), False, 'from pptx.util import Inches, Pt, Emu\n'), ((33624, 33655), 'pptx.util.Emu', 'Emu', (['(data_loc[3] * slide_height)'], {}), '(data_loc[3] * slide_height)\n', (33627, 33655), False, 'from pptx.util import Inches, Pt, Emu\n'), ((34589, 34604), 'pandas.DataFrame', 'pd.DataFrame', (['d'], {}), '(d)\n', (34601, 34604), True, 'import pandas as pd\n'), ((41902, 41918), 'time.localtime', 'time.localtime', ([], {}), '()\n', (41916, 41918), False, 'import time\n'), ((21198, 21227), 'os.path.exists', 'os.path.exists', (["slide['data']"], {}), "(slide['data'])\n", (21212, 21227), False, 'import os\n'), ((25461, 25484), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (25474, 25484), False, 'import os\n'), ((28515, 28540), 'io.BytesIO', 'BytesIO', (['shape_image.blob'], {}), '(shape_image.blob)\n', (28522, 28540), False, 'from io import BytesIO\n'), ((34648, 34665), 'os.path.exists', 'os.path.exists', (['d'], {}), '(d)\n', (34662, 34665), False, 'import os\n'), ((22759, 22788), 'os.path.exists', 'os.path.exists', (["slide['data']"], {}), "(slide['data'])\n", (22773, 22788), False, 'import os\n'), ((21371, 21400), 'os.path.exists', 'os.path.exists', (["slide['data']"], {}), "(slide['data'])\n", (21385, 21400), False, 'import os\n'), ((34789, 34806), 'os.path.exists', 'os.path.exists', (['d'], {}), '(d)\n', (34803, 34806), False, 'import os\n'), ((38412, 38418), 'pptx.util.Pt', 'Pt', (['(10)'], {}), '(10)\n', (38414, 38418), False, 'from pptx.util import Inches, Pt, Emu\n'), ((22976, 23005), 'os.path.exists', 'os.path.exists', (["slide['data']"], {}), "(slide['data'])\n", (22990, 23005), False, 'import os\n')]
from keras_audio.library.utility.audio_utils import compute_melgram from keras_audio.library.utility.gtzan_loader import download_gtzan_genres_if_not_found import numpy as np def load_audio_path_label_pairs(max_allowed_pairs=None): download_gtzan_genres_if_not_found('../very_large_data/gtzan') audio_paths = [] with open('../data/lists/test_songs_gtzan_list.txt', 'rt') as file: for line in file: audio_path = '../very_large_data/' + line.strip() audio_paths.append(audio_path) pairs = [] with open('../data/lists/test_gt_gtzan_list.txt', 'rt') as file: for line in file: label = int(line) if max_allowed_pairs is None or len(pairs) < max_allowed_pairs: pairs.append((audio_paths[len(pairs)], label)) else: break return pairs def main(): pairs = load_audio_path_label_pairs() for index, (audio_path, _) in enumerate(pairs): print('{} / {} ...'.format(index+1, len(pairs))) mg = compute_melgram(audio_path) print('max: ', np.max(mg)) print('min: ', np.min(mg)) if __name__ == '__main__': main()
[ "keras_audio.library.utility.gtzan_loader.download_gtzan_genres_if_not_found", "keras_audio.library.utility.audio_utils.compute_melgram", "numpy.min", "numpy.max" ]
[((237, 299), 'keras_audio.library.utility.gtzan_loader.download_gtzan_genres_if_not_found', 'download_gtzan_genres_if_not_found', (['"""../very_large_data/gtzan"""'], {}), "('../very_large_data/gtzan')\n", (271, 299), False, 'from keras_audio.library.utility.gtzan_loader import download_gtzan_genres_if_not_found\n'), ((1038, 1065), 'keras_audio.library.utility.audio_utils.compute_melgram', 'compute_melgram', (['audio_path'], {}), '(audio_path)\n', (1053, 1065), False, 'from keras_audio.library.utility.audio_utils import compute_melgram\n'), ((1089, 1099), 'numpy.max', 'np.max', (['mg'], {}), '(mg)\n', (1095, 1099), True, 'import numpy as np\n'), ((1124, 1134), 'numpy.min', 'np.min', (['mg'], {}), '(mg)\n', (1130, 1134), True, 'import numpy as np\n')]
from copy import deepcopy from ray import tune import numpy as np from softlearning.misc.utils import get_git_rev, deep_update import os DEFAULT_KEY = '__DEFAULT_KEY__' M = 256 N = 2 REPARAMETERIZE = True NUM_COUPLING_LAYERS = 2 """ Policy params """ GAUSSIAN_POLICY_PARAMS_BASE = { 'type': 'GaussianPolicy', 'kwargs': { 'hidden_layer_sizes': (M, ) * N, 'squash': True, 'observation_keys': None, 'observation_preprocessors_params': {} } } GAUSSIAN_POLICY_PARAMS_FOR_DOMAIN = {} POLICY_PARAMS_BASE = { 'GaussianPolicy': GAUSSIAN_POLICY_PARAMS_BASE, } POLICY_PARAMS_BASE.update({ 'gaussian': POLICY_PARAMS_BASE['GaussianPolicy'], }) POLICY_PARAMS_FOR_DOMAIN = { 'GaussianPolicy': GAUSSIAN_POLICY_PARAMS_FOR_DOMAIN, } POLICY_PARAMS_FOR_DOMAIN.update({ 'gaussian': POLICY_PARAMS_FOR_DOMAIN['GaussianPolicy'], }) MAX_PATH_LENGTH_PER_DOMAIN = { DEFAULT_KEY: 100, 'Point2D': 100, 'DClaw': 100, } NUM_EPOCHS_UNIVERSE_DOMAIN_TASK = { 'gym': { 'Point2D': { DEFAULT_KEY: 100, 'Maze-v0': 200, 'BoxWall-v1': 200, }, 'Pusher2D': { DEFAULT_KEY: 300, }, 'DClaw': { DEFAULT_KEY: 500, } }, } """ Algorithm params """ ALGORITHM_PARAMS_BASE = { 'type': 'SAC', 'kwargs': { 'epoch_length': 1000, 'train_every_n_steps': 1, 'n_train_repeat': 1, 'eval_n_episodes': 3, 'eval_deterministic': True, 'save_training_video_frequency': 5, 'discount': 0.99, 'tau': 5e-3, 'reward_scale': 1.0, 'eval_render_kwargs': { 'width': 480, 'height': 480, 'mode': 'rgb_array', }, }, } ALGORITHM_PARAMS_ADDITIONAL = { 'SAC': { 'type': 'SAC', 'kwargs': { 'reparameterize': REPARAMETERIZE, 'lr': 3e-4, 'target_update_interval': 1, 'tau': 5e-3, 'target_entropy': 'auto', 'action_prior': 'uniform', 'n_initial_exploration_steps': int(1e3), 'n_epochs': 200, } }, 'DDL': { 'type': 'DDL', 'kwargs': { 'reparameterize': REPARAMETERIZE, 'lr': 3e-4, 'target_update_interval': 1, 'tau': 5e-3, 'target_entropy': 'auto', 'action_prior': 'uniform', 'n_initial_exploration_steps': int(1e3), 'n_epochs': 200, 'train_distance_fn_every_n_steps': tune.grid_search([16, 64]), 'ext_reward_coeff': tune.grid_search([0.25, 0.5]), 'normalize_ext_reward_gamma': tune.grid_search([1]), 'use_env_intrinsic_reward': tune.grid_search([True]), 'ddl_symmetric': tune.grid_search([False]), # 'ddl_clip_length': tune.grid_search([None, 20, 50]), 'ddl_train_steps': tune.grid_search([2, 4, 10]), 'ddl_batch_size': 256, #'rnd_int_rew_coeff': tune.grid_search([None, 1]), }, 'rnd_params': { 'convnet_params': { 'conv_filters': (16, 32, 64), 'conv_kernel_sizes': (3, 3, 3), 'conv_strides': (2, 2, 2), 'normalization_type': None, }, 'fc_params': { 'hidden_layer_sizes': (256, 256), 'output_size': 512, }, } }, 'DynamicsAwareEmbeddingDDL': { 'type': 'DynamicsAwareEmbeddingDDL', 'kwargs': { 'reparameterize': REPARAMETERIZE, 'lr': 3e-4, 'target_update_interval': 1, 'tau': 5e-3, 'target_entropy': 'auto', 'action_prior': 'uniform', 'n_initial_exploration_steps': int(1e3), 'n_epochs': 200, 'train_distance_fn_every_n_steps': tune.grid_search([16, 64]), 'ddl_batch_size': 256, # 'ext_reward_coeff': tune.grid_search([0.5, 1]), # 'normalize_ext_reward_gamma': tune.grid_search([0.99, 1]), # 'use_env_intrinsic_reward': tune.grid_search([True]), # 'rnd_int_rew_coeff': 0, }, } } DEFAULT_NUM_EPOCHS = 200 NUM_CHECKPOINTS = 10 """ Distance Estimator params """ DISTANCE_FN_PARAMS_BASE = { 'type': 'feedforward_distance_fn', 'kwargs': { 'hidden_layer_sizes': (M, ) * N, 'observation_keys': None, #'classifier_params': { # 'max_distance': tune.grid_search([20, 40, 100]), # 'bins': tune.grid_search([10, 20]), #}, # 'embedding_dim': 2, } } DISTANCE_FN_KWARGS_UNIVERSE_DOMAIN_TASK = { 'gym': { 'Point2D': { **{ key: {'observation_keys': ('state_observation', )} for key in ( 'Fixed-v0', 'SingleWall-v0', 'Maze-v0', 'BoxWall-v1', ) }, **{ key: {'observation_keys': ('onehot_observation', )} for key in ( # 'Fixed-v0', # 'SingleWall-v0', # 'Maze-v0', # 'BoxWall-v1', ) }, }, 'Pusher2D': { **{ key: {'observation_keys': ('object_pos', )} # key: {'observation_keys': ('gripper_qpos', 'object_pos')} for key in ( 'Simple-v0', ) }, }, 'DClaw': { # **{ # key: {'observation_keys': ('object_pos', )} # for key in ( # 'Simple-v0', # ) # }, } } } ENVIRONMENT_PARAMS_PER_UNIVERSE_DOMAIN_TASK_STATE = { 'gym': { 'Point2D': { # === Point Mass === 'Fixed-v0': { 'action_scale': tune.grid_search([0.5]), 'images_are_rgb': True, # 'init_pos_range': ((-2, -2), (-2, -2)), # Fixed reset 'init_pos_range': None, # Random reset 'target_pos_range': ((2, 2), (2, 2)), # Set the goal to (x, y) = (2, 2) # 'target_pos_range': ((0, 0), (0, 0)), # Set the goal to (x, y) = (0, 0) 'render_onscreen': False, # 'n_bins': 10, # 'show_discrete_grid': True, # 'observation_keys': ('onehot_observation', ), 'observation_keys': ('state_observation', ), }, 'SingleWall-v0': { # 'boundary_distance': tune.grid_search([4, 8]), 'action_scale': tune.grid_search([0.5]), 'images_are_rgb': True, 'init_pos_range': None, # Random reset 'target_pos_range': ((0, 3), (0, 3)), # Set the goal to (x, y) = (2, 2) 'render_onscreen': False, 'observation_keys': ('state_observation', ), }, 'BoxWall-v1': { 'action_scale': tune.grid_search([0.5]), 'images_are_rgb': True, 'init_pos_range': ((-3, -3), (-3, -3)), # 'init_pos_range': None, # Random reset # 'target_pos_range': ((3.5, 3.5), (3.5, 3.5)), 'target_pos_range': ((3, 3), (3, 3)), 'render_onscreen': False, 'observation_keys': ('state_observation', ), }, 'Maze-v0': { 'action_scale': tune.grid_search([0.5]), 'images_are_rgb': True, 'reward_type': 'none', 'use_count_reward': tune.grid_search([True]), # 'show_discrete_grid': False, # 'n_bins': 50, # === EASY === # 'wall_shape': 'easy-maze', # 'init_pos_range': ((-2.5, -2.5), (-2.5, -2.5)), # 'target_pos_range': ((2.5, -2.5), (2.5, -2.5)), # === MEDIUM === 'wall_shape': 'medium-maze', 'init_pos_range': ((-3, -3), (-3, -3)), 'target_pos_range': ((3, 3), (3, 3)), # === HARD === # 'wall_shape': 'hard-maze', # 'init_pos_range': ((-3, -3), (-3, -3)), # 'target_pos_range': ((-0.5, 1.25), (-0.5, 1.25)), 'render_onscreen': False, 'observation_keys': ('state_observation', ), }, }, 'Pusher2D': { 'Simple-v0': { 'init_qpos_range': ((0, 0, 0), (0, 0, 0)), 'init_object_pos_range': ((1, 0), (1, 0)), 'target_pos_range': ((2, 2), (2, 2)), 'reset_gripper': True, 'reset_object': True, 'observation_keys': ( 'gripper_qpos', 'gripper_qvel', 'object_pos', # 'target_pos' ), }, }, 'DClaw': { 'LiftDDFixed-v0': { 'init_qpos_range': tune.grid_search([ ((0, 0, 0.041, 1.017, 0, 0), (0, 0, 0.041, 1.017, 0, 0)) ]), 'target_qpos_range': [ (0, 0, 0.045, 0, 0, 0) ], 'reward_keys_and_weights': {'sparse_position_reward': 1}, 'observation_keys': ( 'object_position', 'object_quaternion', 'claw_qpos', 'last_action' ), # Camera settings for video 'camera_settings': { 'distance': 0.35, 'elevation': -15, 'lookat': (0, 0, 0.05), }, }, }, }, } ENVIRONMENT_PARAMS_PER_UNIVERSE_DOMAIN_TASK_VISION = { 'gym': { 'DClaw': {}, }, } """ Helper methods for retrieving universe/domain/task specific params. """ def get_policy_params(universe, domain, task): policy_params = GAUSSIAN_POLICY_PARAMS_BASE.copy() return policy_params def get_max_path_length(universe, domain, task): max_path_length = MAX_PATH_LENGTH_PER_DOMAIN.get(domain) or \ MAX_PATH_LENGTH_PER_DOMAIN[DEFAULT_KEY] return max_path_length def get_num_epochs(universe, domain, task): level_result = NUM_EPOCHS_UNIVERSE_DOMAIN_TASK.copy() for level_key in (universe, domain, task): if isinstance(level_result, int): return level_result level_result = level_result.get(level_key) or level_result[DEFAULT_KEY] return level_result def get_environment_params(universe, domain, task, from_vision): if from_vision: params = ENVIRONMENT_PARAMS_PER_UNIVERSE_DOMAIN_TASK_VISION else: params = ENVIRONMENT_PARAMS_PER_UNIVERSE_DOMAIN_TASK_STATE environment_params = ( params.get(universe, {}).get(domain, {}).get(task, {})) return environment_params def get_distance_fn_params(universe, domain, task): distance_fn_params = DISTANCE_FN_PARAMS_BASE.copy() distance_fn_params['kwargs'].update( DISTANCE_FN_KWARGS_UNIVERSE_DOMAIN_TASK.get( universe, {}).get(domain, {}).get(task, {})) return distance_fn_params def get_checkpoint_frequency(spec): config = spec.get('config', spec) checkpoint_frequency = ( config ['algorithm_params'] ['kwargs'] ['n_epochs'] ) // NUM_CHECKPOINTS return checkpoint_frequency def is_image_env(universe, domain, task, variant_spec): return ('image' in task.lower() or 'image' in domain.lower() or 'pixel_wrapper_kwargs' in ( variant_spec['environment_params']['training']['kwargs'])) """ Preprocessor params """ STATE_PREPROCESSOR_PARAMS = { 'ReplicationPreprocessor': { 'type': 'ReplicationPreprocessor', 'kwargs': { 'n': 0, 'scale_factor': 1, } }, 'RandomNNPreprocessor': { 'type': 'RandomNNPreprocessor', 'kwargs': { 'hidden_layer_sizes': (32, 32), 'activation': 'linear', 'output_activation': 'linear', } }, 'RandomMatrixPreprocessor': { 'type': 'RandomMatrixPreprocessor', 'kwargs': { 'output_size_scale_factor': 1, 'coefficient_range': (-1., 1.), } }, 'None': None, } PIXELS_PREPROCESSOR_PARAMS = { 'RAEPreprocessor': { 'type': 'RAEPreprocessor', 'kwargs': { 'trainable': True, 'image_shape': (32, 32, 3), 'latent_dim': 32, }, 'shared': True, }, 'ConvnetPreprocessor': tune.grid_search([ { 'type': 'ConvnetPreprocessor', 'kwargs': { 'conv_filters': (64, ) * 3, 'conv_kernel_sizes': (3, ) * 3, 'conv_strides': (2, ) * 3, 'normalization_type': normalization_type, 'downsampling_type': 'conv', 'output_kwargs': { 'type': 'flatten', } }, } for normalization_type in (None, ) ]), } """ Configuring variant specs """ def get_variant_spec_base(universe, domain, task, task_eval, policy, algorithm, from_vision): algorithm_params = ALGORITHM_PARAMS_BASE algorithm_params = deep_update( algorithm_params, ALGORITHM_PARAMS_ADDITIONAL.get(algorithm, {}) ) variant_spec = { 'git_sha': get_git_rev(), 'environment_params': { 'training': { 'domain': domain, 'task': task, 'universe': universe, 'kwargs': get_environment_params(universe, domain, task, from_vision), }, 'evaluation': { 'domain': domain, 'task': task_eval, 'universe': universe, 'kwargs': ( tune.sample_from(lambda spec: ( spec.get('config', spec) ['environment_params'] ['training'] .get('kwargs') )) if task == task_eval else get_environment_params(universe, domain, task_eval, from_vision)), }, }, 'policy_params': deep_update( POLICY_PARAMS_BASE[policy], POLICY_PARAMS_FOR_DOMAIN[policy].get(domain, {}) ), 'exploration_policy_params': { 'type': 'UniformPolicy', 'kwargs': { 'observation_keys': tune.sample_from(lambda spec: ( spec.get('config', spec) ['policy_params'] ['kwargs'] .get('observation_keys') )) }, }, 'Q_params': { 'type': 'double_feedforward_Q_function', 'kwargs': { 'hidden_layer_sizes': (M, M), 'observation_keys': tune.sample_from(lambda spec: ( spec.get('config', spec) ['policy_params'] ['kwargs'] .get('observation_keys') )), 'observation_preprocessors_params': {} } }, 'distance_fn_params': get_distance_fn_params(universe, domain, task), 'algorithm_params': algorithm_params, 'replay_pool_params': { 'type': 'SimpleReplayPool', 'kwargs': { # 'max_size': int(5e5), 'max_size': tune.grid_search([int(5e4)]), } }, 'sampler_params': { 'type': 'SimpleSampler', 'kwargs': { 'max_path_length': get_max_path_length(universe, domain, task), 'min_pool_size': 50, 'batch_size': 256, # tune.grid_search([128, 256]), 'store_last_n_paths': 20, } }, 'run_params': { 'seed': tune.sample_from( lambda spec: np.random.randint(0, 10000)), 'checkpoint_at_end': False, 'checkpoint_frequency': tune.sample_from(get_checkpoint_frequency), 'checkpoint_replay_pool': False, }, } # Filter out parts of the state relating to the object when training from pixels env_kwargs = variant_spec['environment_params']['training']['kwargs'] if from_vision and "device_path" not in env_kwargs.keys(): env_obs_keys = env_kwargs.get('observation_keys', tuple()) non_image_obs_keys = tuple(key for key in env_obs_keys if key != 'pixels') variant_spec['replay_pool_params']['kwargs']['obs_save_keys'] = non_image_obs_keys non_object_obs_keys = tuple(key for key in env_obs_keys if 'object' not in key) variant_spec['policy_params']['kwargs']['observation_keys'] = variant_spec[ 'exploration_policy_params']['kwargs']['observation_keys'] = variant_spec[ 'Q_params']['kwargs']['observation_keys'] = variant_spec[ 'distance_fn_params']['kwargs']['observation_keys'] = non_object_obs_keys return variant_spec def get_variant_spec(args): universe, domain = args.universe, args.domain task, task_eval, algorithm = ( args.task, args.task_evaluation, args.algorithm) from_vision = args.vision variant_spec = get_variant_spec_base( universe, domain, task, task_eval, args.policy, algorithm, from_vision) variant_spec['algorithm_params']['kwargs']['n_epochs'] = ( get_num_epochs(universe, domain, task)) preprocessor_type = args.preprocessor_type if is_image_env(universe, domain, task, variant_spec): assert preprocessor_type in PIXELS_PREPROCESSOR_PARAMS preprocessor_params = PIXELS_PREPROCESSOR_PARAMS[preprocessor_type] variant_spec['policy_params']['kwargs']['hidden_layer_sizes'] = (M, ) * N variant_spec['policy_params']['kwargs'][ 'observation_preprocessors_params'] = { 'pixels': deepcopy(preprocessor_params) } variant_spec['Q_params']['kwargs']['hidden_layer_sizes'] = ( tune.sample_from(lambda spec: (deepcopy( spec.get('config', spec) ['policy_params'] ['kwargs'] ['hidden_layer_sizes'] ))) ) variant_spec['Q_params']['kwargs'][ 'observation_preprocessors_params'] = ( tune.sample_from(lambda spec: (deepcopy( spec.get('config', spec) ['policy_params'] ['kwargs'] ['observation_preprocessors_params'] ))) ) variant_spec['distance_fn_params']['kwargs']['hidden_layer_sizes'] = ( tune.sample_from(lambda spec: (deepcopy( spec.get('config', spec) ['policy_params'] ['kwargs'] ['hidden_layer_sizes'] ))) ) variant_spec['distance_fn_params']['kwargs'][ 'observation_preprocessors_params'] = ( tune.sample_from(lambda spec: (deepcopy( spec.get('config', spec) ['policy_params'] ['kwargs'] ['observation_preprocessors_params'] ))) ) if args.checkpoint_replay_pool is not None: variant_spec['run_params']['checkpoint_replay_pool'] = ( args.checkpoint_replay_pool) return variant_spec
[ "ray.tune.sample_from", "ray.tune.grid_search", "numpy.random.randint", "softlearning.misc.utils.get_git_rev", "copy.deepcopy" ]
[((12928, 13230), 'ray.tune.grid_search', 'tune.grid_search', (["[{'type': 'ConvnetPreprocessor', 'kwargs': {'conv_filters': (64,) * 3,\n 'conv_kernel_sizes': (3,) * 3, 'conv_strides': (2,) * 3,\n 'normalization_type': normalization_type, 'downsampling_type': 'conv',\n 'output_kwargs': {'type': 'flatten'}}} for normalization_type in (None,)]"], {}), "([{'type': 'ConvnetPreprocessor', 'kwargs': {'conv_filters':\n (64,) * 3, 'conv_kernel_sizes': (3,) * 3, 'conv_strides': (2,) * 3,\n 'normalization_type': normalization_type, 'downsampling_type': 'conv',\n 'output_kwargs': {'type': 'flatten'}}} for normalization_type in (None,)])\n", (12944, 13230), False, 'from ray import tune\n'), ((13811, 13824), 'softlearning.misc.utils.get_git_rev', 'get_git_rev', ([], {}), '()\n', (13822, 13824), False, 'from softlearning.misc.utils import get_git_rev, deep_update\n'), ((2583, 2609), 'ray.tune.grid_search', 'tune.grid_search', (['[16, 64]'], {}), '([16, 64])\n', (2599, 2609), False, 'from ray import tune\n'), ((2644, 2673), 'ray.tune.grid_search', 'tune.grid_search', (['[0.25, 0.5]'], {}), '([0.25, 0.5])\n', (2660, 2673), False, 'from ray import tune\n'), ((2717, 2738), 'ray.tune.grid_search', 'tune.grid_search', (['[1]'], {}), '([1])\n', (2733, 2738), False, 'from ray import tune\n'), ((2780, 2804), 'ray.tune.grid_search', 'tune.grid_search', (['[True]'], {}), '([True])\n', (2796, 2804), False, 'from ray import tune\n'), ((2835, 2860), 'ray.tune.grid_search', 'tune.grid_search', (['[False]'], {}), '([False])\n', (2851, 2860), False, 'from ray import tune\n'), ((2960, 2988), 'ray.tune.grid_search', 'tune.grid_search', (['[2, 4, 10]'], {}), '([2, 4, 10])\n', (2976, 2988), False, 'from ray import tune\n'), ((3940, 3966), 'ray.tune.grid_search', 'tune.grid_search', (['[16, 64]'], {}), '([16, 64])\n', (3956, 3966), False, 'from ray import tune\n'), ((16531, 16573), 'ray.tune.sample_from', 'tune.sample_from', (['get_checkpoint_frequency'], {}), '(get_checkpoint_frequency)\n', (16547, 16573), False, 'from ray import tune\n'), ((18436, 18465), 'copy.deepcopy', 'deepcopy', (['preprocessor_params'], {}), '(preprocessor_params)\n', (18444, 18465), False, 'from copy import deepcopy\n'), ((6035, 6058), 'ray.tune.grid_search', 'tune.grid_search', (['[0.5]'], {}), '([0.5])\n', (6051, 6058), False, 'from ray import tune\n'), ((6807, 6830), 'ray.tune.grid_search', 'tune.grid_search', (['[0.5]'], {}), '([0.5])\n', (6823, 6830), False, 'from ray import tune\n'), ((7195, 7218), 'ray.tune.grid_search', 'tune.grid_search', (['[0.5]'], {}), '([0.5])\n', (7211, 7218), False, 'from ray import tune\n'), ((7668, 7691), 'ray.tune.grid_search', 'tune.grid_search', (['[0.5]'], {}), '([0.5])\n', (7684, 7691), False, 'from ray import tune\n'), ((7809, 7833), 'ray.tune.grid_search', 'tune.grid_search', (['[True]'], {}), '([True])\n', (7825, 7833), False, 'from ray import tune\n'), ((9251, 9327), 'ray.tune.grid_search', 'tune.grid_search', (['[((0, 0, 0.041, 1.017, 0, 0), (0, 0, 0.041, 1.017, 0, 0))]'], {}), '([((0, 0, 0.041, 1.017, 0, 0), (0, 0, 0.041, 1.017, 0, 0))])\n', (9267, 9327), False, 'from ray import tune\n'), ((16425, 16452), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10000)'], {}), '(0, 10000)\n', (16442, 16452), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # IkaLog # ====== # Copyright (C) 2015 <NAME> # Copyright (C) 2015 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # This source includes modified version of sample codes in OpenCV # distribution, licensed under 3-clause BSD License. # # By downloading, copying, installing or using the software you agree to this license. # If you do not agree to this license, do not download, install, # copy or use the software. # # # License Agreement # For Open Source Computer Vision Library # (3-clause BSD License) # # Copyright (C) 2000-2015, Intel Corporation, all rights reserved. # Copyright (C) 2009-2011, <NAME> Inc., all rights reserved. # Copyright (C) 2009-2015, NVIDIA Corporation, all rights reserved. # Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. # Copyright (C) 2015, OpenCV Foundation, all rights reserved. # Copyright (C) 2015, Itseez Inc., all rights reserved. # Third party copyrights are property of their respective owners. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the names of the copyright holders nor the names of the contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # This software is provided by the copyright holders and contributors "as is" and # any express or implied warranties, including, but not limited to, the implied # warranties of merchantability and fitness for a particular purpose are disclaimed. # In no event shall copyright holders or contributors be liable for any direct, # indirect, incidental, special, exemplary, or consequential damages # (including, but not limited to, procurement of substitute goods or services; # loss of use, data, or profits; or business interruption) however caused # and on any theory of liability, whether in contract, strict liability, # or tort (including negligence or otherwise) arising in any way out of # the use of this software, even if advised of the possibility of such damage. # import os import pickle import cv2 import numpy as np from ikalog.inputs.filters import Filter, WarpFilterModel from ikalog.utils import * class WarpCalibrationException(Exception): pass class WarpCalibrationNotFound(WarpCalibrationException): pass class WarpCalibrationUnacceptableSize(WarpCalibrationException): def __init__(self, shape): self.shape = shape class WarpFilter(Filter): def filter_matches(self, kp1, kp2, matches, ratio=0.75): mkp1, mkp2 = [], [] for m in matches: if len(m) == 2 and m[0].distance < m[1].distance * ratio: m = m[0] mkp1.append(kp1[m.queryIdx]) mkp2.append(kp2[m.trainIdx]) p1 = np.float32([kp.pt for kp in mkp1]) p2 = np.float32([kp.pt for kp in mkp2]) kp_pairs = zip(mkp1, mkp2) return p1, p2, kp_pairs def set_bbox(self, x, y, w, h): corners = np.float32( [[x, y], [x + w, y], [w + x, y + h], [x, y + h]] ) self.pts1 = np.float32(corners) IkaUtils.dprint('pts1: %s' % [self.pts1]) IkaUtils.dprint('pts2: %s' % [self.pts2]) self.M = cv2.getPerspectiveTransform(self.pts1, self.pts2) return True def calibrateWarp(self, capture_image, validation_func=None): capture_image_gray = cv2.cvtColor(capture_image, cv2.COLOR_BGR2GRAY) capture_image_keypoints, capture_image_descriptors = self.detector.detectAndCompute( capture_image_gray, None) print('caputure_image - %d features' % (len(capture_image_keypoints))) print('matching...') raw_matches = self.matcher.knnMatch( self.calibration_image_descriptors, trainDescriptors=capture_image_descriptors, k=2 ) p1, p2, kp_pairs = self.filter_matches( self.calibration_image_keypoints, capture_image_keypoints, raw_matches, ) if len(p1) >= 4: H, status = cv2.findHomography(p1, p2, cv2.RANSAC, 5.0) print('%d / %d inliers/matched' % (np.sum(status), len(status))) else: H, status = None, None print('%d matches found, not enough for homography estimation' % len(p1)) self.calibration_requested = False raise WarpCalibrationNotFound() if H is None: # Should never reach there... self.calibration_requested = False raise WarpCalibrationNotFound() if len(status) < 1000: raise WarpCalibrationNotFound() calibration_image_height, calibration_image_width = self.calibration_image_size corners = np.float32( [[0, 0], [calibration_image_width, 0], [calibration_image_width, calibration_image_height], [0, calibration_image_height]] ) pts1 = np.float32(cv2.perspectiveTransform( corners.reshape(1, -1, 2), H).reshape(-1, 2) + (0, 0)) IkaUtils.dprint('pts1: %s' % [pts1]) IkaUtils.dprint('pts2: %s' % [self.pts2]) if validation_func is not None: if not validation_func(pts1): w = int(pts1[1][0] - pts1[0][0]) h = int(pts1[2][1] - pts1[1][1]) raise WarpCalibrationUnacceptableSize((w, h)) self.M = cv2.getPerspectiveTransform(pts1, self.pts2) return True def tuples2keyPoints(self, tuples): new_l = [] for point in tuples: pt, size, angle, response, octave, class_id = point new_l.append(cv2.KeyPoint( pt[0], pt[1], size, angle, response, octave, class_id)) return new_l def keyPoints2tuples(self, points): new_l = [] for point in points: new_l.append((point.pt, point.size, point.angle, point.response, point.octave, point.class_id)) return new_l def loadModelFromFile(self, file): f = open(file, 'rb') l = pickle.load(f) f.close() self.calibration_image_size = l[0] self.calibration_image_keypoints = self.tuples2keyPoints(l[1]) self.calibration_image_descriptors = l[2] def saveModelToFile(self, file): f = open(file, 'wb') pickle.dump([ self.calibration_image_size, self.keyPoints2tuples(self.calibration_image_keypoints), self.calibration_image_descriptors, ], f) f.close() def initializeCalibration(self): model_object = WarpFilterModel() if not model_object.trained: raise Exception('Could not intialize WarpFilterModel') self.detector = model_object.detector self.norm = model_object.norm self.matcher = model_object.matcher self.calibration_image_size = model_object.calibration_image_size self.calibration_image_keypoints = model_object.calibration_image_keypoints self.calibration_image_descriptors = model_object.calibration_image_descriptors self.reset() def reset(self): # input source w = 1280 h = 720 self.pts2 = np.float32([[0, 0], [w, 0], [w, h], [0, h]]) self.M = cv2.getPerspectiveTransform(self.pts2, self.pts2) def pre_execute(self, frame): return True def execute(self, frame): if not (self.enabled and self.pre_execute(frame)): return frame return cv2.warpPerspective(frame, self.M, (1280, 720)) def __init__(self, parent, debug=False): super().__init__(parent, debug=debug) self.initializeCalibration()
[ "cv2.getPerspectiveTransform", "cv2.findHomography", "pickle.load", "numpy.sum", "cv2.warpPerspective", "cv2.cvtColor", "ikalog.inputs.filters.WarpFilterModel", "cv2.KeyPoint", "numpy.float32" ]
[((3835, 3869), 'numpy.float32', 'np.float32', (['[kp.pt for kp in mkp1]'], {}), '([kp.pt for kp in mkp1])\n', (3845, 3869), True, 'import numpy as np\n'), ((3883, 3917), 'numpy.float32', 'np.float32', (['[kp.pt for kp in mkp2]'], {}), '([kp.pt for kp in mkp2])\n', (3893, 3917), True, 'import numpy as np\n'), ((4040, 4100), 'numpy.float32', 'np.float32', (['[[x, y], [x + w, y], [w + x, y + h], [x, y + h]]'], {}), '([[x, y], [x + w, y], [w + x, y + h], [x, y + h]])\n', (4050, 4100), True, 'import numpy as np\n'), ((4144, 4163), 'numpy.float32', 'np.float32', (['corners'], {}), '(corners)\n', (4154, 4163), True, 'import numpy as np\n'), ((4283, 4332), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['self.pts1', 'self.pts2'], {}), '(self.pts1, self.pts2)\n', (4310, 4332), False, 'import cv2\n'), ((4449, 4496), 'cv2.cvtColor', 'cv2.cvtColor', (['capture_image', 'cv2.COLOR_BGR2GRAY'], {}), '(capture_image, cv2.COLOR_BGR2GRAY)\n', (4461, 4496), False, 'import cv2\n'), ((5818, 5956), 'numpy.float32', 'np.float32', (['[[0, 0], [calibration_image_width, 0], [calibration_image_width,\n calibration_image_height], [0, calibration_image_height]]'], {}), '([[0, 0], [calibration_image_width, 0], [calibration_image_width,\n calibration_image_height], [0, calibration_image_height]])\n', (5828, 5956), True, 'import numpy as np\n'), ((6491, 6535), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['pts1', 'self.pts2'], {}), '(pts1, self.pts2)\n', (6518, 6535), False, 'import cv2\n'), ((7166, 7180), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7177, 7180), False, 'import pickle\n'), ((7703, 7720), 'ikalog.inputs.filters.WarpFilterModel', 'WarpFilterModel', ([], {}), '()\n', (7718, 7720), False, 'from ikalog.inputs.filters import Filter, WarpFilterModel\n'), ((8323, 8367), 'numpy.float32', 'np.float32', (['[[0, 0], [w, 0], [w, h], [0, h]]'], {}), '([[0, 0], [w, 0], [w, h], [0, h]])\n', (8333, 8367), True, 'import numpy as np\n'), ((8385, 8434), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['self.pts2', 'self.pts2'], {}), '(self.pts2, self.pts2)\n', (8412, 8434), False, 'import cv2\n'), ((8621, 8668), 'cv2.warpPerspective', 'cv2.warpPerspective', (['frame', 'self.M', '(1280, 720)'], {}), '(frame, self.M, (1280, 720))\n', (8640, 8668), False, 'import cv2\n'), ((5130, 5173), 'cv2.findHomography', 'cv2.findHomography', (['p1', 'p2', 'cv2.RANSAC', '(5.0)'], {}), '(p1, p2, cv2.RANSAC, 5.0)\n', (5148, 5173), False, 'import cv2\n'), ((6734, 6801), 'cv2.KeyPoint', 'cv2.KeyPoint', (['pt[0]', 'pt[1]', 'size', 'angle', 'response', 'octave', 'class_id'], {}), '(pt[0], pt[1], size, angle, response, octave, class_id)\n', (6746, 6801), False, 'import cv2\n'), ((5222, 5236), 'numpy.sum', 'np.sum', (['status'], {}), '(status)\n', (5228, 5236), True, 'import numpy as np\n')]
# coding=utf-8 # Copyright 2022 HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import tempfile import unittest import numpy as np from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, slow, torch_device from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bart.test_modeling_flax_bart import FlaxBartStandaloneDecoderModelTester from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..gpt2.test_modeling_flax_gpt2 import FlaxGPT2ModelTester from ..wav2vec2.test_modeling_flax_wav2vec2 import FlaxWav2Vec2ModelTester if is_flax_available(): import jax import jax.numpy as jnp from flax.training.common_utils import onehot from flax.traverse_util import flatten_dict from transformers import ( FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig, ) from transformers.modeling_flax_outputs import FlaxBaseModelOutput from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import SpeechEncoderDecoderModel @require_flax class FlaxEncoderDecoderMixin: def get_encoder_decoder_model(self, config, decoder_config): raise NotImplementedError def prepare_config_and_inputs(self): raise NotImplementedError def get_pretrained_model(self): raise NotImplementedError def check_encoder_decoder_model_from_pretrained_configs( self, config, inputs, attention_mask, encoder_hidden_states, decoder_config, decoder_input_ids, decoder_attention_mask, **kwargs ): encoder_decoder_config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) self.assertTrue(encoder_decoder_config.decoder.is_decoder) enc_dec_model = FlaxSpeechEncoderDecoderModel(encoder_decoder_config) self.assertTrue(enc_dec_model.config.is_encoder_decoder) self.assertFalse(enc_dec_model.config.tie_word_embeddings) outputs_encoder_decoder = enc_dec_model( inputs=inputs, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, ) self.assertEqual( outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) ) def check_encoder_decoder_model( self, config, inputs, attention_mask, encoder_hidden_states, decoder_config, decoder_input_ids, decoder_attention_mask, **kwargs ): encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) self.assertTrue(enc_dec_model.config.decoder.is_decoder) self.assertTrue(enc_dec_model.config.decoder.add_cross_attention) self.assertTrue(enc_dec_model.config.is_encoder_decoder) outputs_encoder_decoder = enc_dec_model( inputs=inputs, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, ) self.assertEqual( outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) ) encoder_outputs = FlaxBaseModelOutput(last_hidden_state=outputs_encoder_decoder.encoder_hidden_states[-1]) outputs_encoder_decoder = enc_dec_model( attention_mask, decoder_input_ids, decoder_attention_mask, encoder_outputs=encoder_outputs ) self.assertEqual( outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) ) def check_encoder_decoder_model_from_pretrained( self, config, inputs, attention_mask, encoder_hidden_states, decoder_config, decoder_input_ids, decoder_attention_mask, return_dict, **kwargs ): encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model, "return_dict": return_dict} enc_dec_model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) outputs_encoder_decoder = enc_dec_model( inputs=inputs, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, output_hidden_states=True, return_dict=True, ) self.assertEqual( outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) ) def check_save_and_load( self, config, inputs, attention_mask, encoder_hidden_states, decoder_config, decoder_input_ids, decoder_attention_mask, **kwargs ): encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model} enc_dec_model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) outputs = enc_dec_model( inputs=inputs, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, ) out_2 = np.array(outputs[0]) out_2[np.isnan(out_2)] = 0 with tempfile.TemporaryDirectory() as tmpdirname: enc_dec_model.save_pretrained(tmpdirname) FlaxSpeechEncoderDecoderModel.from_pretrained(tmpdirname) after_outputs = enc_dec_model( inputs=inputs, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, ) out_1 = np.array(after_outputs[0]) out_1[np.isnan(out_1)] = 0 max_diff = np.amax(np.abs(out_1 - out_2)) self.assertLessEqual(max_diff, 4e-2) def check_encoder_decoder_model_from_encoder_decoder_pretrained( self, config, inputs, attention_mask, encoder_hidden_states, decoder_config, decoder_input_ids, decoder_attention_mask, **kwargs ): encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) # assert that loading encoder and decoder models from configs has been correctly executed self.assertEqual(config.add_adapter, encoder_model.config.add_adapter) self.assertEqual(decoder_config.use_cache, decoder_model.config.use_cache) with tempfile.TemporaryDirectory() as enc_tmpdir: with tempfile.TemporaryDirectory() as dec_tmpdir: encoder_model.save_pretrained(enc_tmpdir) decoder_model.save_pretrained(dec_tmpdir) # load a model from pretrained encoder and decoder checkpoints, setting one encoder and one decoder kwarg opposite to that specified in their respective configs enc_dec_model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=enc_tmpdir, decoder_pretrained_model_name_or_path=dec_tmpdir, encoder_add_adapter=not config.add_adapter, decoder_use_cache=not decoder_config.use_cache, ) # assert that setting encoder and decoder kwargs opposite to those in the configs has correctly been applied self.assertNotEqual(config.add_adapter, enc_dec_model.config.encoder.add_adapter) self.assertNotEqual(decoder_config.use_cache, enc_dec_model.config.decoder.use_cache) outputs_encoder_decoder = enc_dec_model( inputs=inputs, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, output_hidden_states=True, return_dict=True, ) self.assertEqual( outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) ) def check_encoder_decoder_model_output_attentions( self, config, inputs, attention_mask, encoder_hidden_states, decoder_config, decoder_input_ids, decoder_attention_mask, **kwargs ): # make the decoder inputs a different shape from the encoder inputs to harden the test decoder_input_ids = decoder_input_ids[:, :-1] decoder_attention_mask = decoder_attention_mask[:, :-1] encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model} enc_dec_model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) outputs_encoder_decoder = enc_dec_model( inputs=inputs, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, output_attentions=True, ) encoder_attentions = outputs_encoder_decoder["encoder_attentions"] self.assertEqual(len(encoder_attentions), config.num_hidden_layers) seq_len = enc_dec_model._get_feat_extract_output_lengths(inputs.shape[1]) self.assertEqual(encoder_attentions[0].shape[-3:], (config.num_attention_heads, seq_len, seq_len)) decoder_attentions = outputs_encoder_decoder["decoder_attentions"] num_decoder_layers = ( decoder_config.num_decoder_layers if hasattr(decoder_config, "num_decoder_layers") else decoder_config.num_hidden_layers ) self.assertEqual(len(decoder_attentions), num_decoder_layers) self.assertEqual( decoder_attentions[0].shape[-3:], (decoder_config.num_attention_heads, decoder_input_ids.shape[-1], decoder_input_ids.shape[-1]), ) cross_attentions = outputs_encoder_decoder["cross_attentions"] self.assertEqual(len(cross_attentions), num_decoder_layers) cross_attention_input_seq_len = decoder_input_ids.shape[-1] self.assertEqual( cross_attentions[0].shape[-3:], (decoder_config.num_attention_heads, cross_attention_input_seq_len, seq_len), ) def check_encoder_decoder_model_generate(self, inputs, config, decoder_config, **kwargs): encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model} enc_dec_model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) pad_token_id = enc_dec_model.config.decoder.pad_token_id eos_token_id = enc_dec_model.config.decoder.eos_token_id decoder_start_token_id = enc_dec_model.config.decoder.decoder_start_token_id # Copied from generation_utils (GPT2 doesn't have `pad_token_id`) if pad_token_id is None and eos_token_id is not None: pad_token_id = eos_token_id if decoder_start_token_id is None: decoder_start_token_id = enc_dec_model.config.decoder.bos_token_id # Bert does not have a bos token id, so use pad_token_id instead # Copied from `test_modeling_encoder_decoder.py` if decoder_start_token_id is None: decoder_start_token_id = pad_token_id generated_output = enc_dec_model.generate( inputs, pad_token_id=pad_token_id, eos_token_id=eos_token_id, decoder_start_token_id=decoder_start_token_id, ) generated_sequences = generated_output.sequences self.assertEqual(generated_sequences.shape, (inputs.shape[0],) + (decoder_config.max_length,)) def check_freeze_feature_encoder( self, config, inputs, attention_mask, encoder_hidden_states, decoder_config, decoder_input_ids, decoder_attention_mask, **kwargs ): encoder_decoder_config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) enc_dec_model = FlaxSpeechEncoderDecoderModel(encoder_decoder_config) params = enc_dec_model.params def cross_entropy(logits, labels): return -jnp.sum(labels * jax.nn.log_softmax(logits, axis=-1), axis=-1) # define a dummy loss function for computing the loss over a forward pass def compute_loss( params, inputs, attention_mask, decoder_input_ids, freeze_feature_encoder: bool = False, ): outputs_enc_dec = enc_dec_model( inputs=inputs, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, freeze_feature_encoder=freeze_feature_encoder, params=params, ) logits = outputs_enc_dec.logits vocab_size = logits.shape[-1] loss = cross_entropy(logits, onehot(labels=decoder_input_ids, num_classes=vocab_size)).sum() return (loss, logits) # transform the loss function to get the gradients grad_fn = jax.value_and_grad(compute_loss, has_aux=True) # compute the loss, logits, and gradients for the unfrozen model (loss, logits), grads = grad_fn( params, inputs, attention_mask, decoder_input_ids, freeze_feature_encoder=False ) # compare to the loss, logits and gradients for the frozen model (loss_frozen, logits_frozen), grads_frozen = grad_fn( params, inputs, attention_mask, decoder_input_ids, freeze_feature_encoder=True ) # ensure that the logits and losses remain precisely equal self.assertTrue((logits == logits_frozen).all()) self.assertEqual(loss, loss_frozen) grads = flatten_dict(grads) grads_frozen = flatten_dict(grads_frozen) # ensure that the dicts of gradients contain the same keys self.assertEqual(grads.keys(), grads_frozen.keys()) # ensure that the gradients of the feature extractor layers are precisely zero when frozen and contain non-zero entries when unfrozen feature_extractor_grads = tuple(grads[k] for k in grads if "feature_extractor" in k) feature_extractor_grads_frozen = tuple(grads_frozen[k] for k in grads_frozen if "feature_extractor" in k) for feature_extractor_grad, feature_extractor_grad_frozen in zip( feature_extractor_grads, feature_extractor_grads_frozen ): self.assertTrue((feature_extractor_grad_frozen == 0.0).all()) self.assertTrue((feature_extractor_grad > 0.0).any()) # ensure that the gradients of all unfrozen layers remain precisely equal, i.e. all layers excluding the frozen 'feature_extractor' grads = tuple(grads[k] for k in grads if "feature_extractor" not in k) grads_frozen = tuple(grads_frozen[k] for k in grads_frozen if "feature_extractor" not in k) for grad, grad_frozen in zip(grads, grads_frozen): self.assertTrue((grad == grad_frozen).all()) def check_pt_flax_equivalence(self, pt_model, fx_model, inputs_dict): pt_model.to(torch_device) pt_model.eval() # prepare inputs flax_inputs = inputs_dict pt_inputs = {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()} with torch.no_grad(): pt_outputs = pt_model(**pt_inputs).to_tuple() fx_outputs = fx_model(**inputs_dict).to_tuple() self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") for fx_output, pt_output in zip(fx_outputs, pt_outputs): self.assert_almost_equals(fx_output, pt_output.numpy(), 1e-5) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(tmpdirname) fx_model_loaded = FlaxSpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_pt=True) fx_outputs_loaded = fx_model_loaded(**inputs_dict).to_tuple() self.assertEqual(len(fx_outputs_loaded), len(pt_outputs), "Output lengths differ between Flax and PyTorch") for fx_output_loaded, pt_output in zip(fx_outputs_loaded, pt_outputs): self.assert_almost_equals(fx_output_loaded, pt_output.numpy(), 1e-5) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(tmpdirname) pt_model_loaded = SpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_flax=True) pt_model_loaded.to(torch_device) pt_model_loaded.eval() with torch.no_grad(): pt_outputs_loaded = pt_model_loaded(**pt_inputs).to_tuple() self.assertEqual(len(fx_outputs), len(pt_outputs_loaded), "Output lengths differ between Flax and PyTorch") for fx_output, pt_output_loaded in zip(fx_outputs, pt_outputs_loaded): self.assert_almost_equals(fx_output, pt_output_loaded.numpy(), 1e-5) def check_equivalence_pt_to_flax(self, config, decoder_config, inputs_dict): encoder_decoder_config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) pt_model = SpeechEncoderDecoderModel(encoder_decoder_config) fx_model = FlaxSpeechEncoderDecoderModel(encoder_decoder_config) fx_state = convert_pytorch_state_dict_to_flax(pt_model.state_dict(), fx_model) fx_model.params = fx_state self.check_pt_flax_equivalence(pt_model, fx_model, inputs_dict) def check_equivalence_flax_to_pt(self, config, decoder_config, inputs_dict): encoder_decoder_config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) pt_model = SpeechEncoderDecoderModel(encoder_decoder_config) fx_model = FlaxSpeechEncoderDecoderModel(encoder_decoder_config) pt_model = load_flax_weights_in_pytorch_model(pt_model, fx_model.params) self.check_pt_flax_equivalence(pt_model, fx_model, inputs_dict) def test_encoder_decoder_model_from_pretrained_configs(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model_from_pretrained_configs(**input_ids_dict) def test_encoder_decoder_model_from_pretrained(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model_from_pretrained(**input_ids_dict, return_dict=False) def test_encoder_decoder_model_from_pretrained_return_dict(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model_from_pretrained(**input_ids_dict, return_dict=True) def test_save_and_load_from_pretrained(self): input_ids_dict = self.prepare_config_and_inputs() self.check_save_and_load(**input_ids_dict) def test_encoder_decoder_model_from_encoder_decoder_pretrained(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model_from_encoder_decoder_pretrained(**input_ids_dict) def test_encoder_decoder_model_output_attentions(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model_output_attentions(**input_ids_dict) def test_freeze_feature_encoder(self): input_ids_dict = self.prepare_config_and_inputs() self.check_freeze_feature_encoder(**input_ids_dict) def test_encoder_decoder_model_generate(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model_generate(**input_ids_dict) def assert_almost_equals(self, a: np.ndarray, b: np.ndarray, tol: float): diff = np.abs((a - b)).max() self.assertLessEqual(diff, tol, f"Difference between torch and flax is {diff} (>= {tol}).") @is_pt_flax_cross_test def test_pt_flax_equivalence(self): config_inputs_dict = self.prepare_config_and_inputs() config = config_inputs_dict.pop("config") decoder_config = config_inputs_dict.pop("decoder_config") inputs_dict = config_inputs_dict # `encoder_hidden_states` is not used in model call/forward del inputs_dict["encoder_hidden_states"] # Avoid the case where a sequence has no place to attend (after combined with the causal attention mask) batch_size = inputs_dict["decoder_attention_mask"].shape[0] inputs_dict["decoder_attention_mask"] = np.concatenate( [np.ones(shape=(batch_size, 1)), inputs_dict["decoder_attention_mask"][:, 1:]], axis=1 ) # Flax models don't use the `use_cache` option and cache is not returned as a default. # So we disable `use_cache` here for PyTorch model. decoder_config.use_cache = False self.assertTrue(decoder_config.cross_attention_hidden_size is None) # check without `enc_to_dec_proj` projection decoder_config.hidden_size = config.hidden_size self.assertTrue(config.hidden_size == decoder_config.hidden_size) self.check_equivalence_pt_to_flax(config, decoder_config, inputs_dict) self.check_equivalence_flax_to_pt(config, decoder_config, inputs_dict) # check `enc_to_dec_proj` work as expected decoder_config.hidden_size = decoder_config.hidden_size * 2 self.assertTrue(config.hidden_size != decoder_config.hidden_size) self.check_equivalence_pt_to_flax(config, decoder_config, inputs_dict) self.check_equivalence_flax_to_pt(config, decoder_config, inputs_dict) # check `add_adapter` works as expected config.add_adapter = True self.assertTrue(config.add_adapter) self.check_equivalence_pt_to_flax(config, decoder_config, inputs_dict) self.check_equivalence_flax_to_pt(config, decoder_config, inputs_dict) @slow def test_real_model_save_load_from_pretrained(self): model_2 = self.get_pretrained_model() inputs = ids_tensor([13, 5], model_2.config.encoder.vocab_size) decoder_input_ids = ids_tensor([13, 1], model_2.config.decoder.vocab_size) attention_mask = ids_tensor([13, 5], vocab_size=2) outputs = model_2( inputs=inputs, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, ) out_2 = np.array(outputs[0]) out_2[np.isnan(out_2)] = 0 with tempfile.TemporaryDirectory() as tmp_dirname: model_2.save_pretrained(tmp_dirname) model_1 = FlaxSpeechEncoderDecoderModel.from_pretrained(tmp_dirname) after_outputs = model_1( inputs=inputs, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, ) out_1 = np.array(after_outputs[0]) out_1[np.isnan(out_1)] = 0 max_diff = np.amax(np.abs(out_1 - out_2)) self.assertLessEqual(max_diff, 4e-2) @require_flax class FlaxWav2Vec2GPT2ModelTest(FlaxEncoderDecoderMixin, unittest.TestCase): def get_pretrained_model_and_inputs(self): model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained( "facebook/wav2vec2-large-lv60", "gpt2-medium" ) batch_size = 13 input_values = floats_tensor([batch_size, 512], scale=1.0) attention_mask = random_attention_mask([batch_size, 512]) decoder_input_ids = ids_tensor([batch_size, 4], model.config.decoder.vocab_size) decoder_attention_mask = random_attention_mask([batch_size, 4]) inputs = { "inputs": input_values, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, } return model, inputs def get_encoder_decoder_model(self, config, decoder_config): encoder_model = FlaxWav2Vec2Model(config) decoder_model = FlaxGPT2LMHeadModel(decoder_config) return encoder_model, decoder_model def prepare_config_and_inputs(self): model_tester_encoder = FlaxWav2Vec2ModelTester(self, batch_size=13) model_tester_decoder = FlaxGPT2ModelTester(self, batch_size=13) encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs() decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs_for_decoder() (config, inputs, attention_mask) = encoder_config_and_inputs ( decoder_config, decoder_input_ids, decoder_attention_mask, encoder_hidden_states, encoder_attention_mask, ) = decoder_config_and_inputs # make sure that cross attention layers are added decoder_config.add_cross_attention = True return { "config": config, "inputs": inputs, "attention_mask": attention_mask, "decoder_config": decoder_config, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "encoder_hidden_states": encoder_hidden_states, } @slow def test_flaxwav2vec2gpt2_pt_flax_equivalence(self): pt_model = SpeechEncoderDecoderModel.from_pretrained("jsnfly/wav2vec2-large-xlsr-53-german-gpt2") fx_model = FlaxSpeechEncoderDecoderModel.from_pretrained( "jsnfly/wav2vec2-large-xlsr-53-german-gpt2", from_pt=True ) pt_model.to(torch_device) pt_model.eval() # prepare inputs batch_size = 13 input_values = floats_tensor([batch_size, 512], scale=1.0) attention_mask = random_attention_mask([batch_size, 512]) decoder_input_ids = ids_tensor([batch_size, 4], fx_model.config.decoder.vocab_size) decoder_attention_mask = random_attention_mask([batch_size, 4]) inputs_dict = { "inputs": input_values, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, } flax_inputs = inputs_dict pt_inputs = {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()} with torch.no_grad(): pt_outputs = pt_model(**pt_inputs) pt_logits = pt_outputs.logits pt_outputs = pt_outputs.to_tuple() fx_outputs = fx_model(**inputs_dict) fx_logits = fx_outputs.logits fx_outputs = fx_outputs.to_tuple() self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") self.assert_almost_equals(fx_logits, pt_logits.numpy(), 4e-2) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(tmpdirname) fx_model_loaded = FlaxSpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_pt=True) fx_outputs_loaded = fx_model_loaded(**inputs_dict) fx_logits_loaded = fx_outputs_loaded.logits fx_outputs_loaded = fx_outputs_loaded.to_tuple() self.assertEqual(len(fx_outputs_loaded), len(pt_outputs), "Output lengths differ between Flax and PyTorch") self.assert_almost_equals(fx_logits_loaded, pt_logits.numpy(), 4e-2) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(tmpdirname) pt_model_loaded = SpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_flax=True) pt_model_loaded.to(torch_device) pt_model_loaded.eval() with torch.no_grad(): pt_outputs_loaded = pt_model_loaded(**pt_inputs) pt_logits_loaded = pt_outputs_loaded.logits pt_outputs_loaded = pt_outputs_loaded.to_tuple() self.assertEqual(len(fx_outputs), len(pt_outputs_loaded), "Output lengths differ between Flax and PyTorch") self.assert_almost_equals(fx_logits, pt_logits_loaded.numpy(), 4e-2) @require_flax class FlaxWav2Vec2BartModelTest(FlaxEncoderDecoderMixin, unittest.TestCase): def get_pretrained_model_and_inputs(self): model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained( "facebook/wav2vec2-large-lv60", "bart-large" ) batch_size = 13 input_values = floats_tensor([batch_size, 512], scale=1.0) attention_mask = random_attention_mask([batch_size, 512]) decoder_input_ids = ids_tensor([batch_size, 4], model.config.decoder.vocab_size) decoder_attention_mask = random_attention_mask([batch_size, 4]) inputs = { "inputs": input_values, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, } return model, inputs def get_encoder_decoder_model(self, config, decoder_config): encoder_model = FlaxWav2Vec2Model(config) decoder_model = FlaxBartForCausalLM(decoder_config) return encoder_model, decoder_model def prepare_config_and_inputs(self): model_tester_encoder = FlaxWav2Vec2ModelTester(self, batch_size=13) model_tester_decoder = FlaxBartStandaloneDecoderModelTester(self, batch_size=13) encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs() decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs_for_decoder() (config, inputs, attention_mask) = encoder_config_and_inputs ( decoder_config, decoder_input_ids, decoder_attention_mask, encoder_hidden_states, encoder_attention_mask, ) = decoder_config_and_inputs # make sure that cross attention layers are added decoder_config.add_cross_attention = True return { "config": config, "inputs": inputs, "attention_mask": attention_mask, "decoder_config": decoder_config, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "encoder_hidden_states": encoder_hidden_states, } @slow def test_flaxwav2vec2bart_pt_flax_equivalence(self): pt_model = SpeechEncoderDecoderModel.from_pretrained("patrickvonplaten/wav2vec2-2-bart-large") fx_model = FlaxSpeechEncoderDecoderModel.from_pretrained( "patrickvonplaten/wav2vec2-2-bart-large", from_pt=True ) pt_model.to(torch_device) pt_model.eval() # prepare inputs batch_size = 13 input_values = floats_tensor([batch_size, 512], scale=1.0) attention_mask = random_attention_mask([batch_size, 512]) decoder_input_ids = ids_tensor([batch_size, 4], fx_model.config.decoder.vocab_size) decoder_attention_mask = random_attention_mask([batch_size, 4]) inputs_dict = { "inputs": input_values, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, } flax_inputs = inputs_dict pt_inputs = {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()} with torch.no_grad(): pt_outputs = pt_model(**pt_inputs) pt_logits = pt_outputs.logits pt_outputs = pt_outputs.to_tuple() fx_outputs = fx_model(**inputs_dict) fx_logits = fx_outputs.logits fx_outputs = fx_outputs.to_tuple() self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") self.assert_almost_equals(fx_logits, pt_logits.numpy(), 4e-2) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(tmpdirname) fx_model_loaded = FlaxSpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_pt=True) fx_outputs_loaded = fx_model_loaded(**inputs_dict) fx_logits_loaded = fx_outputs_loaded.logits fx_outputs_loaded = fx_outputs_loaded.to_tuple() self.assertEqual(len(fx_outputs_loaded), len(pt_outputs), "Output lengths differ between Flax and PyTorch") self.assert_almost_equals(fx_logits_loaded, pt_logits.numpy(), 4e-2) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(tmpdirname) pt_model_loaded = SpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_flax=True) pt_model_loaded.to(torch_device) pt_model_loaded.eval() with torch.no_grad(): pt_outputs_loaded = pt_model_loaded(**pt_inputs) pt_logits_loaded = pt_outputs_loaded.logits pt_outputs_loaded = pt_outputs_loaded.to_tuple() self.assertEqual(len(fx_outputs), len(pt_outputs_loaded), "Output lengths differ between Flax and PyTorch") self.assert_almost_equals(fx_logits, pt_logits_loaded.numpy(), 4e-2) @require_flax class FlaxWav2Vec2BertModelTest(FlaxEncoderDecoderMixin, unittest.TestCase): def get_pretrained_model_and_inputs(self): model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained( "facebook/wav2vec2-large-lv60", "bert-large-uncased" ) batch_size = 13 input_values = floats_tensor([batch_size, 512], model.config.encoder.vocab_size) attention_mask = random_attention_mask([batch_size, 512]) decoder_input_ids = ids_tensor([batch_size, 4], model.config.decoder.vocab_size) decoder_attention_mask = random_attention_mask([batch_size, 4]) inputs = { "inputs": input_values, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, } return model, inputs def get_encoder_decoder_model(self, config, decoder_config): encoder_model = FlaxWav2Vec2Model(config) decoder_model = FlaxBertForCausalLM(decoder_config) return encoder_model, decoder_model def prepare_config_and_inputs(self): model_tester_encoder = FlaxWav2Vec2ModelTester(self, batch_size=13) model_tester_decoder = FlaxBertModelTester(self, batch_size=13) encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs() decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs_for_decoder() (config, inputs, attention_mask) = encoder_config_and_inputs ( decoder_config, decoder_input_ids, decoder_attention_mask, encoder_hidden_states, encoder_attention_mask, ) = decoder_config_and_inputs # make sure that cross attention layers are added decoder_config.add_cross_attention = True return { "config": config, "inputs": inputs, "attention_mask": attention_mask, "decoder_config": decoder_config, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "encoder_hidden_states": encoder_hidden_states, } @slow def test_flaxwav2vec2bert_pt_flax_equivalence(self): pt_model = SpeechEncoderDecoderModel.from_pretrained("speech-seq2seq/wav2vec2-2-bert-large") fx_model = FlaxSpeechEncoderDecoderModel.from_pretrained("speech-seq2seq/wav2vec2-2-bert-large", from_pt=True) pt_model.to(torch_device) pt_model.eval() # prepare inputs batch_size = 13 input_values = floats_tensor([batch_size, 512], fx_model.config.encoder.vocab_size) attention_mask = random_attention_mask([batch_size, 512]) decoder_input_ids = ids_tensor([batch_size, 4], fx_model.config.decoder.vocab_size) decoder_attention_mask = random_attention_mask([batch_size, 4]) inputs_dict = { "inputs": input_values, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, } flax_inputs = inputs_dict pt_inputs = {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()} with torch.no_grad(): pt_outputs = pt_model(**pt_inputs) pt_logits = pt_outputs.logits pt_outputs = pt_outputs.to_tuple() fx_outputs = fx_model(**inputs_dict) fx_logits = fx_outputs.logits fx_outputs = fx_outputs.to_tuple() self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") self.assert_almost_equals(fx_logits, pt_logits.numpy(), 4e-2) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(tmpdirname) fx_model_loaded = FlaxSpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_pt=True) fx_outputs_loaded = fx_model_loaded(**inputs_dict) fx_logits_loaded = fx_outputs_loaded.logits fx_outputs_loaded = fx_outputs_loaded.to_tuple() self.assertEqual(len(fx_outputs_loaded), len(pt_outputs), "Output lengths differ between Flax and PyTorch") self.assert_almost_equals(fx_logits_loaded, pt_logits.numpy(), 4e-2) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(tmpdirname) pt_model_loaded = SpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_flax=True) pt_model_loaded.to(torch_device) pt_model_loaded.eval() with torch.no_grad(): pt_outputs_loaded = pt_model_loaded(**pt_inputs) pt_logits_loaded = pt_outputs_loaded.logits pt_outputs_loaded = pt_outputs_loaded.to_tuple() self.assertEqual(len(fx_outputs), len(pt_outputs_loaded), "Output lengths differ between Flax and PyTorch") self.assert_almost_equals(fx_logits, pt_logits_loaded.numpy(), 4e-2)
[ "transformers.FlaxSpeechEncoderDecoderModel.from_pretrained", "jax.nn.log_softmax", "transformers.FlaxGPT2LMHeadModel", "numpy.array", "transformers.is_flax_available", "transformers.FlaxWav2Vec2Model", "flax.training.common_utils.onehot", "transformers.modeling_flax_pytorch_utils.load_flax_weights_in...
[((1190, 1209), 'transformers.is_flax_available', 'is_flax_available', ([], {}), '()\n', (1207, 1209), False, 'from transformers import is_flax_available, is_torch_available\n'), ((1806, 1826), 'transformers.is_torch_available', 'is_torch_available', ([], {}), '()\n', (1824, 1826), False, 'from transformers import is_flax_available, is_torch_available\n'), ((2497, 2576), 'transformers.SpeechEncoderDecoderConfig.from_encoder_decoder_configs', 'SpeechEncoderDecoderConfig.from_encoder_decoder_configs', (['config', 'decoder_config'], {}), '(config, decoder_config)\n', (2552, 2576), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((2669, 2722), 'transformers.FlaxSpeechEncoderDecoderModel', 'FlaxSpeechEncoderDecoderModel', (['encoder_decoder_config'], {}), '(encoder_decoder_config)\n', (2698, 2722), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((3605, 3676), 'transformers.SpeechEncoderDecoderModel', 'SpeechEncoderDecoderModel', ([], {'encoder': 'encoder_model', 'decoder': 'decoder_model'}), '(encoder=encoder_model, decoder=decoder_model)\n', (3630, 3676), False, 'from transformers import SpeechEncoderDecoderModel\n'), ((4293, 4386), 'transformers.modeling_flax_outputs.FlaxBaseModelOutput', 'FlaxBaseModelOutput', ([], {'last_hidden_state': 'outputs_encoder_decoder.encoder_hidden_states[-1]'}), '(last_hidden_state=outputs_encoder_decoder.\n encoder_hidden_states[-1])\n', (4312, 4386), False, 'from transformers.modeling_flax_outputs import FlaxBaseModelOutput\n'), ((5203, 5274), 'transformers.FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', 'FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', ([], {}), '(**kwargs)\n', (5264, 5274), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((6166, 6237), 'transformers.FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', 'FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', ([], {}), '(**kwargs)\n', (6227, 6237), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((6476, 6496), 'numpy.array', 'np.array', (['outputs[0]'], {}), '(outputs[0])\n', (6484, 6496), True, 'import numpy as np\n'), ((10020, 10091), 'transformers.FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', 'FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', ([], {}), '(**kwargs)\n', (10081, 10091), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((11917, 11988), 'transformers.FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', 'FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', ([], {}), '(**kwargs)\n', (11978, 11988), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((13387, 13466), 'transformers.SpeechEncoderDecoderConfig.from_encoder_decoder_configs', 'SpeechEncoderDecoderConfig.from_encoder_decoder_configs', (['config', 'decoder_config'], {}), '(config, decoder_config)\n', (13442, 13466), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((13491, 13544), 'transformers.FlaxSpeechEncoderDecoderModel', 'FlaxSpeechEncoderDecoderModel', (['encoder_decoder_config'], {}), '(encoder_decoder_config)\n', (13520, 13544), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((14566, 14612), 'jax.value_and_grad', 'jax.value_and_grad', (['compute_loss'], {'has_aux': '(True)'}), '(compute_loss, has_aux=True)\n', (14584, 14612), False, 'import jax\n'), ((15253, 15272), 'flax.traverse_util.flatten_dict', 'flatten_dict', (['grads'], {}), '(grads)\n', (15265, 15272), False, 'from flax.traverse_util import flatten_dict\n'), ((15296, 15322), 'flax.traverse_util.flatten_dict', 'flatten_dict', (['grads_frozen'], {}), '(grads_frozen)\n', (15308, 15322), False, 'from flax.traverse_util import flatten_dict\n'), ((18578, 18657), 'transformers.SpeechEncoderDecoderConfig.from_encoder_decoder_configs', 'SpeechEncoderDecoderConfig.from_encoder_decoder_configs', (['config', 'decoder_config'], {}), '(config, decoder_config)\n', (18633, 18657), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((18678, 18727), 'transformers.SpeechEncoderDecoderModel', 'SpeechEncoderDecoderModel', (['encoder_decoder_config'], {}), '(encoder_decoder_config)\n', (18703, 18727), False, 'from transformers import SpeechEncoderDecoderModel\n'), ((18747, 18800), 'transformers.FlaxSpeechEncoderDecoderModel', 'FlaxSpeechEncoderDecoderModel', (['encoder_decoder_config'], {}), '(encoder_decoder_config)\n', (18776, 18800), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((19113, 19192), 'transformers.SpeechEncoderDecoderConfig.from_encoder_decoder_configs', 'SpeechEncoderDecoderConfig.from_encoder_decoder_configs', (['config', 'decoder_config'], {}), '(config, decoder_config)\n', (19168, 19192), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((19213, 19262), 'transformers.SpeechEncoderDecoderModel', 'SpeechEncoderDecoderModel', (['encoder_decoder_config'], {}), '(encoder_decoder_config)\n', (19238, 19262), False, 'from transformers import SpeechEncoderDecoderModel\n'), ((19282, 19335), 'transformers.FlaxSpeechEncoderDecoderModel', 'FlaxSpeechEncoderDecoderModel', (['encoder_decoder_config'], {}), '(encoder_decoder_config)\n', (19311, 19335), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((19356, 19417), 'transformers.modeling_flax_pytorch_utils.load_flax_weights_in_pytorch_model', 'load_flax_weights_in_pytorch_model', (['pt_model', 'fx_model.params'], {}), '(pt_model, fx_model.params)\n', (19390, 19417), False, 'from transformers.modeling_flax_pytorch_utils import convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model\n'), ((23783, 23803), 'numpy.array', 'np.array', (['outputs[0]'], {}), '(outputs[0])\n', (23791, 23803), True, 'import numpy as np\n'), ((24557, 24670), 'transformers.FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', 'FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', (['"""facebook/wav2vec2-large-lv60"""', '"""gpt2-medium"""'], {}), "(\n 'facebook/wav2vec2-large-lv60', 'gpt2-medium')\n", (24618, 24670), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((25351, 25376), 'transformers.FlaxWav2Vec2Model', 'FlaxWav2Vec2Model', (['config'], {}), '(config)\n', (25368, 25376), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((25401, 25436), 'transformers.FlaxGPT2LMHeadModel', 'FlaxGPT2LMHeadModel', (['decoder_config'], {}), '(decoder_config)\n', (25420, 25436), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((26685, 26776), 'transformers.SpeechEncoderDecoderModel.from_pretrained', 'SpeechEncoderDecoderModel.from_pretrained', (['"""jsnfly/wav2vec2-large-xlsr-53-german-gpt2"""'], {}), "(\n 'jsnfly/wav2vec2-large-xlsr-53-german-gpt2')\n", (26726, 26776), False, 'from transformers import SpeechEncoderDecoderModel\n'), ((26791, 26900), 'transformers.FlaxSpeechEncoderDecoderModel.from_pretrained', 'FlaxSpeechEncoderDecoderModel.from_pretrained', (['"""jsnfly/wav2vec2-large-xlsr-53-german-gpt2"""'], {'from_pt': '(True)'}), "(\n 'jsnfly/wav2vec2-large-xlsr-53-german-gpt2', from_pt=True)\n", (26836, 26900), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((29583, 29695), 'transformers.FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', 'FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', (['"""facebook/wav2vec2-large-lv60"""', '"""bart-large"""'], {}), "(\n 'facebook/wav2vec2-large-lv60', 'bart-large')\n", (29644, 29695), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((30376, 30401), 'transformers.FlaxWav2Vec2Model', 'FlaxWav2Vec2Model', (['config'], {}), '(config)\n', (30393, 30401), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((30426, 30461), 'transformers.FlaxBartForCausalLM', 'FlaxBartForCausalLM', (['decoder_config'], {}), '(decoder_config)\n', (30445, 30461), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((31727, 31815), 'transformers.SpeechEncoderDecoderModel.from_pretrained', 'SpeechEncoderDecoderModel.from_pretrained', (['"""patrickvonplaten/wav2vec2-2-bart-large"""'], {}), "(\n 'patrickvonplaten/wav2vec2-2-bart-large')\n", (31768, 31815), False, 'from transformers import SpeechEncoderDecoderModel\n'), ((31830, 31936), 'transformers.FlaxSpeechEncoderDecoderModel.from_pretrained', 'FlaxSpeechEncoderDecoderModel.from_pretrained', (['"""patrickvonplaten/wav2vec2-2-bart-large"""'], {'from_pt': '(True)'}), "(\n 'patrickvonplaten/wav2vec2-2-bart-large', from_pt=True)\n", (31875, 31936), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((34619, 34739), 'transformers.FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', 'FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', (['"""facebook/wav2vec2-large-lv60"""', '"""bert-large-uncased"""'], {}), "(\n 'facebook/wav2vec2-large-lv60', 'bert-large-uncased')\n", (34680, 34739), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((35442, 35467), 'transformers.FlaxWav2Vec2Model', 'FlaxWav2Vec2Model', (['config'], {}), '(config)\n', (35459, 35467), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((35492, 35527), 'transformers.FlaxBertForCausalLM', 'FlaxBertForCausalLM', (['decoder_config'], {}), '(decoder_config)\n', (35511, 35527), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((36776, 36862), 'transformers.SpeechEncoderDecoderModel.from_pretrained', 'SpeechEncoderDecoderModel.from_pretrained', (['"""speech-seq2seq/wav2vec2-2-bert-large"""'], {}), "(\n 'speech-seq2seq/wav2vec2-2-bert-large')\n", (36817, 36862), False, 'from transformers import SpeechEncoderDecoderModel\n'), ((36877, 36981), 'transformers.FlaxSpeechEncoderDecoderModel.from_pretrained', 'FlaxSpeechEncoderDecoderModel.from_pretrained', (['"""speech-seq2seq/wav2vec2-2-bert-large"""'], {'from_pt': '(True)'}), "(\n 'speech-seq2seq/wav2vec2-2-bert-large', from_pt=True)\n", (36922, 36981), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((6511, 6526), 'numpy.isnan', 'np.isnan', (['out_2'], {}), '(out_2)\n', (6519, 6526), True, 'import numpy as np\n'), ((6546, 6575), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (6573, 6575), False, 'import tempfile\n'), ((6657, 6714), 'transformers.FlaxSpeechEncoderDecoderModel.from_pretrained', 'FlaxSpeechEncoderDecoderModel.from_pretrained', (['tmpdirname'], {}), '(tmpdirname)\n', (6702, 6714), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((6987, 7013), 'numpy.array', 'np.array', (['after_outputs[0]'], {}), '(after_outputs[0])\n', (6995, 7013), True, 'import numpy as np\n'), ((7802, 7831), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (7829, 7831), False, 'import tempfile\n'), ((16822, 16837), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (16835, 16837), False, 'import torch\n'), ((17237, 17266), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (17264, 17266), False, 'import tempfile\n'), ((17361, 17432), 'transformers.FlaxSpeechEncoderDecoderModel.from_pretrained', 'FlaxSpeechEncoderDecoderModel.from_pretrained', (['tmpdirname'], {'from_pt': '(True)'}), '(tmpdirname, from_pt=True)\n', (17406, 17432), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((17815, 17844), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (17842, 17844), False, 'import tempfile\n'), ((17939, 18008), 'transformers.SpeechEncoderDecoderModel.from_pretrained', 'SpeechEncoderDecoderModel.from_pretrained', (['tmpdirname'], {'from_flax': '(True)'}), '(tmpdirname, from_flax=True)\n', (17980, 18008), False, 'from transformers import SpeechEncoderDecoderModel\n'), ((18096, 18111), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (18109, 18111), False, 'import torch\n'), ((23818, 23833), 'numpy.isnan', 'np.isnan', (['out_2'], {}), '(out_2)\n', (23826, 23833), True, 'import numpy as np\n'), ((23853, 23882), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (23880, 23882), False, 'import tempfile\n'), ((23970, 24028), 'transformers.FlaxSpeechEncoderDecoderModel.from_pretrained', 'FlaxSpeechEncoderDecoderModel.from_pretrained', (['tmp_dirname'], {}), '(tmp_dirname)\n', (24015, 24028), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((24232, 24258), 'numpy.array', 'np.array', (['after_outputs[0]'], {}), '(after_outputs[0])\n', (24240, 24258), True, 'import numpy as np\n'), ((27685, 27700), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (27698, 27700), False, 'import torch\n'), ((28172, 28201), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (28199, 28201), False, 'import tempfile\n'), ((28296, 28367), 'transformers.FlaxSpeechEncoderDecoderModel.from_pretrained', 'FlaxSpeechEncoderDecoderModel.from_pretrained', (['tmpdirname'], {'from_pt': '(True)'}), '(tmpdirname, from_pt=True)\n', (28341, 28367), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((28765, 28794), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (28792, 28794), False, 'import tempfile\n'), ((28889, 28958), 'transformers.SpeechEncoderDecoderModel.from_pretrained', 'SpeechEncoderDecoderModel.from_pretrained', (['tmpdirname'], {'from_flax': '(True)'}), '(tmpdirname, from_flax=True)\n', (28930, 28958), False, 'from transformers import SpeechEncoderDecoderModel\n'), ((29046, 29061), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (29059, 29061), False, 'import torch\n'), ((32721, 32736), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (32734, 32736), False, 'import torch\n'), ((33208, 33237), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (33235, 33237), False, 'import tempfile\n'), ((33332, 33403), 'transformers.FlaxSpeechEncoderDecoderModel.from_pretrained', 'FlaxSpeechEncoderDecoderModel.from_pretrained', (['tmpdirname'], {'from_pt': '(True)'}), '(tmpdirname, from_pt=True)\n', (33377, 33403), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((33801, 33830), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (33828, 33830), False, 'import tempfile\n'), ((33925, 33994), 'transformers.SpeechEncoderDecoderModel.from_pretrained', 'SpeechEncoderDecoderModel.from_pretrained', (['tmpdirname'], {'from_flax': '(True)'}), '(tmpdirname, from_flax=True)\n', (33966, 33994), False, 'from transformers import SpeechEncoderDecoderModel\n'), ((34082, 34097), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (34095, 34097), False, 'import torch\n'), ((37769, 37784), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (37782, 37784), False, 'import torch\n'), ((38256, 38285), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (38283, 38285), False, 'import tempfile\n'), ((38380, 38451), 'transformers.FlaxSpeechEncoderDecoderModel.from_pretrained', 'FlaxSpeechEncoderDecoderModel.from_pretrained', (['tmpdirname'], {'from_pt': '(True)'}), '(tmpdirname, from_pt=True)\n', (38425, 38451), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((38849, 38878), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (38876, 38878), False, 'import tempfile\n'), ((38973, 39042), 'transformers.SpeechEncoderDecoderModel.from_pretrained', 'SpeechEncoderDecoderModel.from_pretrained', (['tmpdirname'], {'from_flax': '(True)'}), '(tmpdirname, from_flax=True)\n', (39014, 39042), False, 'from transformers import SpeechEncoderDecoderModel\n'), ((39130, 39145), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (39143, 39145), False, 'import torch\n'), ((7032, 7047), 'numpy.isnan', 'np.isnan', (['out_1'], {}), '(out_1)\n', (7040, 7047), True, 'import numpy as np\n'), ((7084, 7105), 'numpy.abs', 'np.abs', (['(out_1 - out_2)'], {}), '(out_1 - out_2)\n', (7090, 7105), True, 'import numpy as np\n'), ((7864, 7893), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (7891, 7893), False, 'import tempfile\n'), ((8234, 8501), 'transformers.FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', 'FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained', ([], {'encoder_pretrained_model_name_or_path': 'enc_tmpdir', 'decoder_pretrained_model_name_or_path': 'dec_tmpdir', 'encoder_add_adapter': '(not config.add_adapter)', 'decoder_use_cache': '(not decoder_config.use_cache)'}), '(\n encoder_pretrained_model_name_or_path=enc_tmpdir,\n decoder_pretrained_model_name_or_path=dec_tmpdir, encoder_add_adapter=\n not config.add_adapter, decoder_use_cache=not decoder_config.use_cache)\n', (8295, 8501), False, 'from transformers import FlaxBartForCausalLM, FlaxBertForCausalLM, FlaxGPT2LMHeadModel, FlaxSpeechEncoderDecoderModel, FlaxWav2Vec2Model, SpeechEncoderDecoderConfig\n'), ((21146, 21159), 'numpy.abs', 'np.abs', (['(a - b)'], {}), '(a - b)\n', (21152, 21159), True, 'import numpy as np\n'), ((21933, 21963), 'numpy.ones', 'np.ones', ([], {'shape': '(batch_size, 1)'}), '(shape=(batch_size, 1))\n', (21940, 21963), True, 'import numpy as np\n'), ((24277, 24292), 'numpy.isnan', 'np.isnan', (['out_1'], {}), '(out_1)\n', (24285, 24292), True, 'import numpy as np\n'), ((24329, 24350), 'numpy.abs', 'np.abs', (['(out_1 - out_2)'], {}), '(out_1 - out_2)\n', (24335, 24350), True, 'import numpy as np\n'), ((13664, 13699), 'jax.nn.log_softmax', 'jax.nn.log_softmax', (['logits'], {'axis': '(-1)'}), '(logits, axis=-1)\n', (13682, 13699), False, 'import jax\n'), ((14390, 14446), 'flax.training.common_utils.onehot', 'onehot', ([], {'labels': 'decoder_input_ids', 'num_classes': 'vocab_size'}), '(labels=decoder_input_ids, num_classes=vocab_size)\n', (14396, 14446), False, 'from flax.training.common_utils import onehot\n')]
# This contains a catalog of explicit solutions to some SDEs. from sampi.sdes.base import StochDiffEq import numpy as np def basic_linear(a=1, b=1): """Returns a function implementing the explicit solution to the SDE dX_t = a X_t dt + b X_t dW_t. """ drift = lambda x, t : a*x diffusion = lambda x, t : b*x true_sol = lambda x0, t, wt : x0*np.exp( (a - 0.5*b*b)*t + b*wt) return StochDiffEq(drift=drift, diffusion=diffusion, true_sol=true_sol, eqn="dX_t = a X_t dt + b X_t dW_t") def kloeden_4_15(a=1): """Returns a function implementing the explicit solution to the SDE dX_t = 0.5*a*(a-1)*(X_t)^(1 - 2/a) dt + a*(X_t)^(1 - 1/a) dW_t. Taken from (Kloden & Platen, 1992), page 120. """ drift = lambda x, t : 0.5*a*(a-1)*(x**(1 - 2/a)) diffusion = lambda x, t : a*(x**(1 - 1/a)) true_sol = lambda x0, t, wt : (wt + x0**(1/a))**a return StochDiffEq(drift=drift, diffusion=diffusion, true_sol=true_sol, eqn="dX_t = 0.5*a*(a-1)*(X_t)^(1 - 2/a) dt + a*(X_t)^(1 - 1/a) dW_t") def kloeden_4_16(a=1): """Returns a function implementing the explicit solution to the SDE dX_t = 0.5*a^2 X_t dt + a X_t dW_t. Taken from (Kloden & Platen, 1992), page 120. """ drift = lambda x, t : 0.5*a*a*x diffusion = lambda x, t : a*x true_sol = lambda x0, t, wt : x0*np.exp(a*wt) return StochDiffEq(drift=drift, diffusion=diffusion, true_sol=true_sol, eqn="dX_t = 0.5*a^2 X_t dt + a X_t dW_t") def kloeden_4_20(a=1): """Returns a function implementing the explicit solution to the SDE dX_t = -0.5*a^2 X_t dt - a*sqrt(1 - (X_t)^2) dW_t Taken from (Kloden & Platen, 1992), page 121. """ drift = lambda x, t : -0.5*a*a*x diffusion = lambda x, t : -a*np.sqrt(1 - x**2) true_sol = lambda x0, t, wt : np.cos(a*wt + np.arccos(x0)) return StochDiffEq(drift=drift, diffusion=diffusion, true_sol=true_sol, eqn="dX_t = -0.5*a^2 X_t dt - a*sqrt(1 - (X_t)^2) dW_t") def double_well(): """Returns a SDE object implementing the drift and diffusion functions for SDE dX_t = 4*(X_t - (X_t)^3) dt + dW_t Taken from (Saarkk et. al, 2019), page 269. """ drift = lambda x, t : 4*(x - x**3) diffusion = lambda x, t : 1 true_sol = None return StochDiffEq(drift=drift, diffusion=diffusion, true_sol=true_sol, eqn="dX_t = 4*(x - x^3) dt + dW_t") def garcia_m3(): """Returns a SDE object implementing the drift and diffusion functions for the SDE dX_t = -(X_t)**3 dt + (0.2 + x**2) dW_t Taken from (Garcia et. al, 2017). """ drift = lambda x, t : -x**3 diffusion = lambda x, t : (0.2 + x**2) true_sol = None return StochDiffEq(drift=drift, diffusion=diffusion, true_sol=true_sol, eqn="dX_t = -(X_t)**3 dt + (0.2 + x**2) dW_t")
[ "numpy.exp", "numpy.arccos", "numpy.sqrt", "sampi.sdes.base.StochDiffEq" ]
[((422, 527), 'sampi.sdes.base.StochDiffEq', 'StochDiffEq', ([], {'drift': 'drift', 'diffusion': 'diffusion', 'true_sol': 'true_sol', 'eqn': '"""dX_t = a X_t dt + b X_t dW_t"""'}), "(drift=drift, diffusion=diffusion, true_sol=true_sol, eqn=\n 'dX_t = a X_t dt + b X_t dW_t')\n", (433, 527), False, 'from sampi.sdes.base import StochDiffEq\n'), ((923, 1062), 'sampi.sdes.base.StochDiffEq', 'StochDiffEq', ([], {'drift': 'drift', 'diffusion': 'diffusion', 'true_sol': 'true_sol', 'eqn': '"""dX_t = 0.5*a*(a-1)*(X_t)^(1 - 2/a) dt + a*(X_t)^(1 - 1/a) dW_t"""'}), "(drift=drift, diffusion=diffusion, true_sol=true_sol, eqn=\n 'dX_t = 0.5*a*(a-1)*(X_t)^(1 - 2/a) dt + a*(X_t)^(1 - 1/a) dW_t')\n", (934, 1062), False, 'from sampi.sdes.base import StochDiffEq\n'), ((1396, 1507), 'sampi.sdes.base.StochDiffEq', 'StochDiffEq', ([], {'drift': 'drift', 'diffusion': 'diffusion', 'true_sol': 'true_sol', 'eqn': '"""dX_t = 0.5*a^2 X_t dt + a X_t dW_t"""'}), "(drift=drift, diffusion=diffusion, true_sol=true_sol, eqn=\n 'dX_t = 0.5*a^2 X_t dt + a X_t dW_t')\n", (1407, 1507), False, 'from sampi.sdes.base import StochDiffEq\n'), ((1886, 2012), 'sampi.sdes.base.StochDiffEq', 'StochDiffEq', ([], {'drift': 'drift', 'diffusion': 'diffusion', 'true_sol': 'true_sol', 'eqn': '"""dX_t = -0.5*a^2 X_t dt - a*sqrt(1 - (X_t)^2) dW_t"""'}), "(drift=drift, diffusion=diffusion, true_sol=true_sol, eqn=\n 'dX_t = -0.5*a^2 X_t dt - a*sqrt(1 - (X_t)^2) dW_t')\n", (1897, 2012), False, 'from sampi.sdes.base import StochDiffEq\n'), ((2321, 2426), 'sampi.sdes.base.StochDiffEq', 'StochDiffEq', ([], {'drift': 'drift', 'diffusion': 'diffusion', 'true_sol': 'true_sol', 'eqn': '"""dX_t = 4*(x - x^3) dt + dW_t"""'}), "(drift=drift, diffusion=diffusion, true_sol=true_sol, eqn=\n 'dX_t = 4*(x - x^3) dt + dW_t')\n", (2332, 2426), False, 'from sampi.sdes.base import StochDiffEq\n'), ((2737, 2853), 'sampi.sdes.base.StochDiffEq', 'StochDiffEq', ([], {'drift': 'drift', 'diffusion': 'diffusion', 'true_sol': 'true_sol', 'eqn': '"""dX_t = -(X_t)**3 dt + (0.2 + x**2) dW_t"""'}), "(drift=drift, diffusion=diffusion, true_sol=true_sol, eqn=\n 'dX_t = -(X_t)**3 dt + (0.2 + x**2) dW_t')\n", (2748, 2853), False, 'from sampi.sdes.base import StochDiffEq\n'), ((379, 417), 'numpy.exp', 'np.exp', (['((a - 0.5 * b * b) * t + b * wt)'], {}), '((a - 0.5 * b * b) * t + b * wt)\n', (385, 417), True, 'import numpy as np\n'), ((1372, 1386), 'numpy.exp', 'np.exp', (['(a * wt)'], {}), '(a * wt)\n', (1378, 1386), True, 'import numpy as np\n'), ((1794, 1813), 'numpy.sqrt', 'np.sqrt', (['(1 - x ** 2)'], {}), '(1 - x ** 2)\n', (1801, 1813), True, 'import numpy as np\n'), ((1860, 1873), 'numpy.arccos', 'np.arccos', (['x0'], {}), '(x0)\n', (1869, 1873), True, 'import numpy as np\n')]
import bokeh import pandas as pd import numpy as np import os from bokeh import events from bokeh.io import show from bokeh.plotting import figure, output_file, ColumnDataSource from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn,TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter from bokeh.layouts import Column, Row, gridplot, Spacer from bokeh.models import HoverTool, CustomJS, BoxSelectTool, Panel, Tabs, Span, AjaxDataSource, ToolbarBox, Toolbar, Legend, LegendItem, PanTool, TapTool from bokeh.models.glyphs import MultiLine from bokeh.events import ButtonClick, SelectionGeometry, Press, Tap from bokeh.util.compiler import JavaScript import imageio as iio output_file('index.html', title='NaViA v 1.0') # Usual format 1366x768 plot_canvas = figure(plot_width=1366, plot_height=int(768/1), output_backend='canvas', x_axis_label='m/z ', y_axis_label='Rel. Abundance [%]', tools=['box_zoom, reset, pan, wheel_zoom'],hidpi=True, toolbar_location='right') plot_canvas.background_fill_color=None plot_canvas.border_fill_color=None svg_canvas = figure( plot_width=1366, plot_height=768, output_backend='svg', x_axis_label='m/z ', y_axis_label='Rel. Abundance [%]', tools=['save'], hidpi=False, visible=True ) highres_canvas = figure(plot_width=3840, plot_height=int(2160/1), output_backend='canvas', x_axis_label='m/z ', y_axis_label='Rel. Abundance [%]', tools=['save'], toolbar_location='right', visible=True) highres_canvas.axis.axis_label_text_font_size='40px' highres_canvas.axis.major_label_text_font_size='32px' highres_canvas.axis.axis_line_width=3 highres_canvas.axis.axis_line_width=3 highres_canvas.axis.major_tick_line_width=3 highres_canvas.axis.minor_tick_line_width=3 highres_canvas.axis.major_tick_out=14 highres_canvas.axis.minor_tick_out=10 highres_canvas.grid.grid_line_width=2 highres_canvas.background_fill_color=None highres_canvas.border_fill_color=None legend = Legend(items=[]) plot_canvas.add_layout(legend) # Defining colours n_series = 20 series_colours = [ bokeh.palettes.Category20_20[int((2*i%20+np.floor(i/10)))] for i in range(20)] series_cols = {} series_data = {} series_sele = {} series_mz = {} series_mz4k = {} series_mzsvg= {} peak_mz = {} peak_mz4k = {} peak_mzsvg = {} series_names = ['Series {:d}'.format(i_series + 1) for i_series in range(n_series)] for i_series in range(len(series_names)): series_cols[series_names[i_series]] = series_colours[i_series] series_cols['Background']='#000000' for i_series in series_names: series_data[i_series] = AjaxDataSource(data=dict(x_low=[], x_upp=[], x_max=[],max_int=[], charge=[]))# series_sele[i_series] = AjaxDataSource(data=dict(i_low=[], i_upp=[], i_max=[])) series_mz[i_series] = AjaxDataSource(data=dict(Intensity=[], mz=[])) series_mz4k[i_series] = AjaxDataSource(data=dict(Intensity=[], mz=[])) series_mzsvg[i_series]= AjaxDataSource(data=dict(Intensity=[], mz=[])) peak_mz[i_series] = AjaxDataSource(data=dict(xs=[], ys=[])) peak_mz4k[i_series] = AjaxDataSource(data=dict(xs=[], ys=[])) peak_mzsvg[i_series] = AjaxDataSource(data=dict(xs=[], ys=[])) series_masses = AjaxDataSource(data=dict(Series=[], Mass=[], Uncertainty=[], Colour=[])) aser_data = AjaxDataSource(data=dict(x_low=[], x_upp=[], x_max=[],max_int=[], charge=[])) series_dict = AjaxDataSource(data=dict(series=series_names, names=series_names)) groel_data=pd.read_csv('Testdata/siyun_groel.txt', skiprows=10, delimiter='\t') # groel_data.columns.values=[ 'Intensity'] groel_data.rename(columns={'1980.151514':'mz', '0.000000':'Intensity'}, inplace=True) # print(groel_data.columns.values) GroEL_mz = AjaxDataSource(data=groel_data) raw_mz = AjaxDataSource(data=dict(Intensity=[], mz=[])) proc_mz = AjaxDataSource(data=dict(Intensity=[], mz=[])) bg_mz = AjaxDataSource(data=dict(Intensity=[], mz=[])) bg_mz4k = AjaxDataSource(data=dict(Intensity=[], mz=[])) bg_mzsvg = AjaxDataSource(data=dict(Intensity=[], mz=[])) # Define Dataprocessing parameters in DS to make them easier to access etc. DataProcessingParameters= AjaxDataSource(data=dict(mz_low=[0.0], mz_upp=[20000.0], gau_sigma=[0.0], gau_rep=[1], intensity_threshold=[0.0], sub_mode=['Substract Minimum'], sub_value=[0.0])) series_colours_DS= AjaxDataSource(data=dict(series=[x for x in series_cols], colour=[series_cols[x] for x in series_cols])) sel_lines={} sel_lines4k={} sel_linessvg={} peak_lines={} peak_lines4k={} peak_linessvg={} for i_series in series_cols.keys(): sel_lines[i_series] = MultiLine(xs='mz', ys='Intensity', line_color=series_cols[i_series], name=i_series) sel_lines4k[i_series] = MultiLine(xs='mz', ys='Intensity', line_color=series_cols[i_series], name=i_series, line_width=4) sel_linessvg[i_series] = MultiLine(xs='mz', ys='Intensity', line_color=series_cols[i_series], name=i_series) peak_lines[i_series] = MultiLine(xs='xs', ys='ys', line_color=series_cols[i_series], line_alpha=0.5) peak_lines4k[i_series] = MultiLine(xs='xs', ys='ys', line_color=series_cols[i_series], line_width=4, line_alpha=0.5) peak_linessvg[i_series] = MultiLine(xs='xs', ys='ys', line_color=series_cols[i_series], line_alpha=0.5) sel_lines['Background'] = MultiLine(xs='mz', ys='Intensity', line_color=series_cols['Background'], name='Background') sel_lines4k['Background'] = MultiLine(xs='mz', ys='Intensity', line_color=series_cols['Background'], name='Background', line_width=4) sel_linessvg['Background'] = MultiLine(xs='mz', ys='Intensity', line_color=series_cols['Background'], name='Background') # Peak prediction peaks pp_mean_data = AjaxDataSource(data=dict(xs=[], ys=[])) pp_std_data = AjaxDataSource(data=dict(xs=[], ys=[])) pp_mean = MultiLine(xs="xs", ys="ys", name='pp_mean', line_color=bokeh.palettes.Category20_20[0], line_width=2, line_alpha=0.5) pp_std = MultiLine(xs="xs", ys="ys", name='pp_std', line_color=bokeh.palettes.Category20_20[0], line_dash='dashed',line_width=2, line_alpha=0.5) # Selection and show of colour of Active Series ser_act_menu=[('Background (Eraser)', 'Background'), ('New Series', 'New Series')] # ser_act = Select(value='Background', options=['Background', 'New Series'], width=150, height=30) ser_act = Dropdown(label="Create Series", value='Background', menu=ser_act_menu, width=140, height=30) col_cb = CustomJS(args=dict(proc_mz=proc_mz, series_data=series_data, pp_mean_data=pp_mean_data, pp_std_data=pp_std_data, plot_canvas=plot_canvas, peak_lines=peak_lines, peak_lines4k=peak_lines4k, series_colours_DS=series_colours_DS, series_names=series_names, sel_lines=sel_lines, ser_act=ser_act, pp_mean= pp_mean, pp_std=pp_std, series_masses=series_masses) , code=open(os.path.join(os.getcwd(), 'JS_Functions', "navia_functions.js")).read() + open(os.path.join(os.getcwd(), 'JS_Functions', "col_cb.js")).read()) col = ColorPicker(color='black', width=50, height=30, disabled=False, callback=col_cb) ser_match = Select(value='', options=[], title='Stoich. Calculation Series:', width=150, height=45) ser_callback = CustomJS(args=dict(proc_mz=proc_mz,series_colours_DS=series_colours_DS, series_names=series_names, sel_lines=sel_lines, sel_lines4k=sel_lines4k, peak_lines=peak_lines,peak_lines4k=peak_lines4k, col=col, aser_data=aser_data, ser_match=ser_match, series_data=series_data, pp_mean= pp_mean, pp_std=pp_std, pp_mean_data=pp_mean_data, pp_std_data=pp_std_data, series_masses=series_masses, plot_canvas=plot_canvas), code=open(os.path.join(os.getcwd(), 'JS_Functions', "navia_functions.js")).read() + open(os.path.join(os.getcwd(), 'JS_Functions', "ser_cb.js")).read()) # Additional Buttons menu = [("Load spectrum (txt file)", "load_file"), ("Load spectrum (clipboard)", "load_clip"), ("Load example (GroEL)", "load_groel"), None, ("Save session", "save_sess"), ("Load session", "load_sess"), None, ("Save Peaks Table", "save_peaks"), ("Save Masses Table", "save_masses"),None, ("Load Subunit table", "load_SU"), ("Save Subunit table", "save_SU"), None, ("Save Stoichiometry Table", "save_mm")]#, None, ("Load subunit table", "load_suta")] # Further options to implement ("Export SVG","expo_svg"), ("Export high-res PNG","expo_svg")] ser_act.js_on_change('value', ser_callback) posneg_menu=[('Positive Mode','Positive'), ('Negative Mode', 'Negative')] posneg = Dropdown(menu=posneg_menu, value='Positive', label='Instrument Mode: +' , width=160, height=30) graph_opt = Toggle(label='Figure', width=110, height=30) help_alert = CustomJS(args=dict(), code=open(os.path.join(os.getcwd(), 'JS_Functions', "help_cb.js")).read()) mass_finder = Toggle(label='Mass Finder', width=110, height=30) mass_match = Toggle(label='Complex Stoichiometry', width=150, height=30) dt_button = Toggle(label='Data Processing', width=110, height=30) help_button = Button(label='Help', width=90, height=30) help_button.js_on_event(ButtonClick, help_alert) sele_cb = CustomJS(args=dict(peak_mz=peak_mz, bg_mz=bg_mz, proc_mz=proc_mz, ser_act=ser_act, series_sele=series_sele, series_data=series_data, series_mz=series_mz, series_names=series_names, series_masses=series_masses, pp_mean_data=pp_mean_data, pp_std_data=pp_std_data, aser_data=aser_data, posneg=posneg, series_colours_DS=series_colours_DS), code=open(os.path.join(os.getcwd(), 'JS_Functions', "navia_functions.js")).read() + open(os.path.join(os.getcwd(), 'JS_Functions', "sele_cb.js")).read()) correct_cb = CustomJS(args=dict(series_colours_DS=series_colours_DS, peak_mz=peak_mz, bg_mz=bg_mz, proc_mz=proc_mz, ser_act=ser_act, series_sele=series_sele, series_data=series_data, series_mz=series_mz, series_names=series_names, series_masses=series_masses, pp_mean_data=pp_mean_data, pp_std_data=pp_std_data, aser_data=aser_data, posneg=posneg), code=open(os.path.join(os.getcwd(), 'JS_Functions', "navia_functions.js")).read() + open(os.path.join(os.getcwd(), 'JS_Functions', "correct_cb.js")).read()) posneg_cb = CustomJS(args=dict(series_colours_DS=series_colours_DS, peak_mz=peak_mz, bg_mz=bg_mz, proc_mz=proc_mz, ser_act=ser_act, series_sele=series_sele, series_data=series_data, series_mz=series_mz, series_names=series_names, series_masses=series_masses, pp_mean_data=pp_mean_data, pp_std_data=pp_std_data, aser_data=aser_data, posneg=posneg), code=open(os.path.join(os.getcwd(), 'JS_Functions', "navia_functions.js")).read() + open(os.path.join(os.getcwd(), 'JS_Functions', "posneg_cb.js")).read()) posneg.js_on_change('value', posneg_cb) class DQTapTool(TapTool): # language=JavaScript __implementation__ = JavaScript(""" import {TapTool} from "models/tools"; export class DQTapTool extends TapTool { static __name__ = 'DQTapTool' get tooltip() { return 'Correct Peak. \\n (Tap on data point to set value for mass calculation of respective to tapped m/z.)'; } } """) class RenamedBoxSelectTool(BoxSelectTool): # language=JavaScript __implementation__ = JavaScript(""" import {BoxSelectTool} from "models/tools"; export class RenamedBoxSelectTool extends BoxSelectTool { static __name__ = 'RenamedBoxSelectTool' get tooltip() { return 'Mark Peak \\n (Press left mouse button and hold to select range.)'; } } """) box_selectdq = RenamedBoxSelectTool(dimensions='width', callback=sele_cb, name='Select Peak') tapdq = DQTapTool(name='Select Peak', callback=correct_cb) # tapdq.js_on_event(Tap, correct_cb) # Add lines to graph plot_canvas.add_glyph(bg_mz,sel_lines['Background']) highres_canvas.add_glyph(bg_mz4k,sel_lines4k['Background']) svg_canvas.add_glyph(bg_mzsvg,sel_linessvg['Background']) ppml = plot_canvas.add_glyph(pp_mean_data, pp_mean, visible=False) ppsl = plot_canvas.add_glyph(pp_std_data , pp_std , visible=False) plot_canvas.toolbar.active_tap=None plot_canvas.toolbar.active_drag=box_selectdq pp = Toggle(label="Predict adjecent peaks", width=150, height=30) pp.js_link('active', ppml, 'visible') pp.js_link('active', ppsl, 'visible') # pl.js_link('active', plpc, 'visible') # pl.js_link('active', pl4k, 'visible') # Defining Mass Finder mass_finder_line= MultiLine(xs="xs", ys="ys", line_color="#002147", line_width=2, line_alpha=0.5) mass_finder_data=AjaxDataSource(data=dict(xs=[], ys=[])) mfl = plot_canvas.add_glyph(mass_finder_data, mass_finder_line, visible=False) # Define Hovertool hover = HoverTool() hover.tooltips = [("m/z", "$x{5.2f}"), ("Abundance", "$y %")] plot_canvas.add_tools(hover) plot_canvas.add_tools(box_selectdq) plot_canvas.add_tools(tapdq) columns = [ TableColumn(field="x_low", title="Lower m/z", formatter=NumberFormatter(format='0,0.00')), TableColumn(field="x_upp", title="Upper m/z", formatter=NumberFormatter(format='0,0.00')), TableColumn(field="x_max", title="mz of Max", formatter=NumberFormatter(format='0,0.00')), TableColumn(field="max_int", title="Intensity of Maximum", formatter=NumberFormatter(format='0,0.00')), TableColumn(field="charge", title="Charge"), ] showtab = DataTable(source=aser_data, name=i_series, columns=columns, width=580, height=300, editable=False, index_position=None) # show_tab_cb=CustomJS(args=dict(peak_mz=peak_mz, bg_mz=bg_mz, proc_mz=proc_mz, ser_act=ser_act, series_sele=series_sele, series_data=series_data, series_mz=series_mz, # series_names=series_names, series_masses=series_masses, pp_mean_data=pp_mean_data, pp_std_data=pp_std_data, aser_data=aser_data, posneg=posneg), code=open(os.path.join(os.getcwd(), 'JS_Functions', "navia_functions.js")).read() # + open(os.path.join(os.getcwd(), 'JS_Functions', "showtab_cb.js")).read()) # aser_data.js_on_change('patching', show_tab_cb) template=""" <div style="background:<%= (function colorfromint(){ return(Colour) }()) %>; color: <%= (function colorfromint(){ return(Colour) }()) %>;"> <%= value %> </font> </div> """ formatter = HTMLTemplateFormatter(template=template) columns_mass_table = [ TableColumn(field="Colour", title="Colour", formatter=formatter, width=120), TableColumn(field="Series", title="Series"), TableColumn(field="Mass", title="Mass", formatter=NumberFormatter(format='0,0.00')), TableColumn(field="Uncertainty", title="Uncertainty", formatter=NumberFormatter(format='0,0.00')), ] masses_table = DataTable(source=series_masses, name='Mass table', columns=columns_mass_table, width=370, height=300, index_position=None, editable=False) n_complexes = 10 SU_act = AjaxDataSource(dict(name=[],mass=[],min=[],max=[], stride=[])) columns_complex_table = [ TableColumn(field="name", title="Subunit", width=250), TableColumn(field="mass", title="Mass", formatter=NumberFormatter(format='0,0.00'), width=100), TableColumn(field="min", title="Min. #", formatter=NumberFormatter(format='0,0'), width=50), TableColumn(field="max", title="Max. #", formatter=NumberFormatter(format='0,0'), width=50), TableColumn(field="stride", title="Stride", formatter=NumberFormatter(format='0,0'), width=50), ] complex_table = DataTable(source=SU_act, name='Complex table', columns=columns_complex_table, width=450, height=280, index_position=None, editable=True) # Define buttons for adding subunits Add_SU_cb=CustomJS(args=dict(SU_act=SU_act), code=open(os.path.join(os.getcwd(), 'JS_Functions', "Add_SU_cb.js")).read() ) Del_SU_cb=CustomJS(args=dict(SU_act=SU_act), code=open(os.path.join(os.getcwd(), 'JS_Functions', "del_SU_cb.js")).read() ) SU_add_button=Button(label='Add subunit', width=120, height=30, button_type='success') SU_del_button=Button(label='Delete subunit', width=120, height=30, button_type='danger') SU_add_button.js_on_event(ButtonClick, Add_SU_cb) SU_del_button.js_on_event(ButtonClick, Del_SU_cb) comment_window = TextAreaInput(value="Add comments here", width = 340, height= 280) stoich = AjaxDataSource(dict(stoichiometry=[], mass=[], mass_diff=[])) diff_match = TextInput(value= str(1000.0), title='Allowed ΔMass', disabled=False, width=150, height=50) columns_match_table = [ TableColumn(field="stoichiometry", title="Stoichiometry"), TableColumn(field="mass", title="Mass of Combination", formatter=NumberFormatter(format='0,0.00')), TableColumn(field="mass_diff", title="Difference to Measured Mass", formatter=NumberFormatter(format='0,0.00')), ] # Further options to implement ("Export SVG","expo_svg"), ("Export high-res PNG","expo_svg")] match_table = DataTable(source=stoich, name='Complex table', columns=columns_match_table, width=534, height=280, index_position=None) mass_match_cb=CustomJS(args=dict(ser_match=ser_match, diff_match=diff_match,series_masses=series_masses, stoich=stoich, SU_act=SU_act), code=open(os.path.join(os.getcwd(), 'JS_Functions', "MassMatching_cb.js")).read()) mass_match_button=Button(label='Stoichiometry', width=150, height=30, button_type='success') mass_match_button.js_on_event(ButtonClick, mass_match_cb) cropping_slider = RangeSlider(start=0.0, end=100000.0, value=(0.0,100000.0), name='cropping_slider', step=100, width= 150, height=30) gaussian_smooth = Slider(value=0.0, start=0, end=50, step=1, name='gau_sigma', width=150, height=30) #TextInput(value=str(0.0), disabled=False, width=100, height=30) n_smooth = Slider(value=1, start=0, end=10, step=1, name='gau_rep', width=150, height=30) intensity_threshold = Slider(value=0.0, start=0, end=100, step=0.1, name='intensity_threshold', width=150, height=30)#TextInput(value=str(0.0), disabled=False, width=100, height=30) substract = Slider(value=0.0, start=0, end=100, step=1, name='sub_value', width=150, height=30) #TextInput(value=str(0.0), disabled=False, width=100, height=30) # adduct_mass = TextInput(value=str(0.0), disabled=False, width=100, height=30) # data_reduction = TextInput(value=str(0.0), disabled=False, width=100, height=30) toggle_cb=CustomJS(code=''' if (cb_obj.active == true) {cb_obj.label='on'} else {cb_obj.label='off'} ''') ### MASS FINDER ### mass_finder_header = Div(text= " <h2>Mass Finder</h2>", height=45, width=400 ) # mass_finder_range_text = Div(text= " Range mz:", width= 150, height=30 ) mass_finder_range_slider = RangeSlider(start=1.0, end=500.0, value=(1.0,50.0), title='Charge range:',name='mass_finder_range_slider', step=1, width= 250, height=30) # mass_finder_mass_text = Div(text= " Mass of Complex (kDa):", width= 150, height=30 ) mass_finder_mass = Slider(value=100, start=0.0, end=1000.0, step=10.0, title='Mass of Complex (kDa)',name='gau_sigma', width=250, height=30) mass_finder_exact_mass_text = Div(text= "Enter exact Mass (Da)", width= 150, height=30 ) mass_finder_exact_mass_sele = TextInput(value=str(mass_finder_mass.value*1000), disabled=False, width=100, height=30) mass_finder_line_text = Div(text= "Show mz prediction", width= 150, height=30 ) mass_finder_line_sele = Toggle(label='off', active=False, width=100, height=30, callback=toggle_cb) mass_finder_cb =CustomJS(args=dict(mass_finder_line_sele=mass_finder_line_sele, raw_mz=raw_mz, mass_finder_data=mass_finder_data, mass_finder_exact_mass_sele=mass_finder_exact_mass_sele, mass_finder_mass=mass_finder_mass, mass_finder_range_slider=mass_finder_range_slider, mfl=mfl), code=open(os.path.join(os.getcwd(), 'JS_Functions', "mass_finder_cb.js")).read()) mass_finder_exact_cb =CustomJS(args=dict(mass_finder_line_sele=mass_finder_line_sele, mass_finder_exact_mass_sele=mass_finder_exact_mass_sele, mass_finder_mass=mass_finder_mass), code=open(os.path.join(os.getcwd(), 'JS_Functions', "mass_finder_exact_cb.js")).read()) mass_finder_exact_mass_sele.js_on_change('value', mass_finder_exact_cb) mass_finder_column=Column(mass_finder_header,mass_finder_mass, mass_finder_range_slider, Row(mass_finder_exact_mass_text,mass_finder_exact_mass_sele), Row(mass_finder_line_text, mass_finder_line_sele), visible=False) mass_finder.js_link('active', mass_finder_column, 'visible') mass_finder_line_sele.js_link('active', mfl, 'visible') mass_finder_mass.js_on_change('value', mass_finder_cb) mass_finder_line_sele.js_on_change('active', mass_finder_cb) mass_finder_range_slider.js_on_change('value',mass_finder_cb) ### DATA PROCESSING ### cropping = Div(text= " Range mz:", width= 150, height=30 ) # crop_max = Div(text= " ", width= 150, height=30 ) gau_name = Div(text= " Gaussian Smoothing:", width= 150, height=30 ) n_smooth_name = Div(text= " Repeats of Smoothing:", width= 150, height=30 ) # bin_name = Div(text= " Bin Every:", width= 150, height=30 ) int_name = Div(text= " Intensity Threshold (%)", width= 150, height=30 ) sub_name = Select(options=['Substract Minimum', 'Substract Line', 'Substract Curved'], name='sub_mode', value='Substract Minimum', width= 150, height=30 ) # add_name = Div(text= " Adduct Mass (Da)", width= 150, height=30 ) # dat_name = Div(text= " Data Reduction (%)", width= 150, height=30 ) #pro_name = Div(text= " bla", width= 150, height=30 ) dt_name = Div(text= " <h2>Data Processing</h2>", height=45 ) dtp_update=CustomJS(args=dict(DataProcessingParameters=DataProcessingParameters), code=open(os.path.join(os.getcwd(), 'JS_Functions', "DataProcessingParameters_update_cb.js")).read()) cropping_slider.js_on_change('value', dtp_update) n_smooth.js_on_change('value', dtp_update) gaussian_smooth.js_on_change('value', dtp_update) intensity_threshold.js_on_change('value', dtp_update) substract.js_on_change('value', dtp_update) sub_name.js_on_change('value', dtp_update) processing_cb=CustomJS(args=dict(peak_mz=peak_mz, bg_mz=bg_mz, raw_mz=raw_mz, proc_mz=proc_mz, DataProcessingParameters=DataProcessingParameters, series_data=series_data, series_sele=series_sele, series_names=series_names, series_mz=series_mz), code=open(os.path.join(os.getcwd(), 'JS_Functions', "navia_functions.js")).read() + open(os.path.join(os.getcwd(), 'JS_Functions', "data_processing_cb.js")).read()) process_data=Button(label='Process Data', width=100, height=30, button_type='success', callback=processing_cb) reset_cb=CustomJS(args=dict(process_data=process_data, peak_mz=peak_mz, bg_mz=bg_mz, raw_mz=raw_mz, proc_mz=proc_mz, series_data=series_data, series_sele=series_sele, series_names=series_names, series_mz=series_mz), code=open(os.path.join(os.getcwd(), 'JS_Functions', "navia_functions.js")).read() + open(os.path.join(os.getcwd(), 'JS_Functions', "reset_cb.js")).read()) reset_data=Button(label='Reset Processing', width=80, height=30, button_type='danger', callback=reset_cb) dt_names = Column(cropping, gau_name, n_smooth_name ,int_name, sub_name, reset_data)#, pro_name) dt_inp=Column(cropping_slider, gaussian_smooth, n_smooth, intensity_threshold, substract, process_data) grid_text = Div(text= " Show Grid", width= 150, height=30 ) grid_sele = Toggle(label='on', active=True, width=100, height=30, callback=toggle_cb) for x_grid_line in plot_canvas.xgrid: grid_sele.js_link('active', x_grid_line, 'visible') for y_grid_line in plot_canvas.ygrid: grid_sele.js_link('active', y_grid_line, 'visible') for x_grid_line in highres_canvas.xgrid: grid_sele.js_link('active', x_grid_line, 'visible') for y_grid_line in highres_canvas.ygrid: grid_sele.js_link('active', y_grid_line, 'visible') grid_sele.js_link('active', plot_canvas, 'outline_line_alpha') grid_sele.js_link('active', highres_canvas, 'outline_line_alpha') labels_text = Div(text= " Show labels", width= 150, height=30 ) labels_sele = Toggle(label='on', active=True, width=100, height=30, callback=toggle_cb) ticks_text = Div(text= " Show Ticks", width= 150, height=30 ) ticks_sele = Toggle(label='on', active=True, width=100, height=30, callback=toggle_cb) axes_text = Div(text= " Show Axes", width= 150, height=30 ) axes_sele = Toggle(label='on', active=True, width=100, height=30, callback=toggle_cb) for item in plot_canvas.axis + highres_canvas.axis + svg_canvas.axis: labels_sele.js_link('active', item ,'axis_label_text_alpha') labels_sele.js_link('active', item ,'major_label_text_alpha') ticks_sele.js_link('active', item ,'major_tick_line_alpha') ticks_sele.js_link('active', item ,'minor_tick_line_alpha') for item in plot_canvas.axis + highres_canvas.axis + svg_canvas.axis: axes_sele.js_link('active', item ,'axis_line_alpha') fig_text = Div(text= "Note: 4K/SVG figure creation on Safari on MacOS is slow and might crash. Please save high-resolution PNG figures in a different browser. SVG creation takes a few seconds.\n", width= 300, height=70 ) peakmz_text = Div(text= " Show mz of Peaks", width= 150, height=30 ) peakmz_sele = Toggle(label='off', active=False, width=100, height=30, callback=toggle_cb) plpc={} pl4k={} plsvg={} for i_series in series_names: plot_canvas.add_glyph(series_mz[i_series],sel_lines[i_series]) highres_canvas.add_glyph(series_mz4k[i_series], sel_lines4k[i_series]) svg_canvas.add_glyph(series_mzsvg[i_series], sel_linessvg[i_series]) plpc[i_series]=plot_canvas.add_glyph(peak_mz[i_series], peak_lines[i_series], visible=False) pl4k[i_series]=highres_canvas.add_glyph(peak_mz4k[i_series], peak_lines4k[i_series], visible=False) plsvg[i_series]=svg_canvas.add_glyph(peak_mzsvg[i_series], peak_lines[i_series], visible=False) peakmz_sele.js_link('active', plpc[i_series], 'visible') peakmz_sele.js_link('active', pl4k[i_series], 'visible') peakmz_sele.js_link('active', plsvg[i_series], 'visible') save4k_text= Button(label= " Create 4K PNG figure: ", width= 150, height=30, button_type='success') # save4k_text.js_link('active', highres_canvas, 'visible') savesvg_text= Button(label= " Create SVG figure: ", width= 150, height=30, button_type='success' ) # savesvg_text.js_link('active', svg_canvas, 'visible') linew_text= Div(text= " Line width ", width= 150, height=30 ) linew_inp = TextInput(value=str(sel_lines['Background'].line_width), disabled=False, width=100, height=30) save4k = ToolbarBox() save4k.toolbar = Toolbar(tools=highres_canvas.tools, logo=None) save4k.toolbar_location ='above' savesvg = ToolbarBox() savesvg.toolbar = Toolbar(tools=svg_canvas.tools, logo=None) savesvg.toolbar_location ='above' graph_text=Column(grid_text, labels_text, ticks_text, axes_text, peakmz_text, linew_text) graph_act=Column(grid_sele, labels_sele, ticks_sele, axes_sele, peakmz_sele, linew_inp) savesvg.visible=False save4k.visible=False posneg_text = Div(text= " Ion Charge", width= 150, height=30 ) data_header = Div(text= " <h2>Data Processing</h2>", height=45, width=400 ) posneg_header = Div(text= " <h2>Instrument Mode</h2>", height=45, width=400 ) # save4k.toolbar_options={'logo':None} data_text = Div(text= "Note: The data processing might take a couple of seconds. Please stay patient and refrain from pressing the Process Data button repeatedly. \n", width= 300, height=70 ) data_tools= Column(data_header, Row(dt_names, dt_inp), data_text, visible=False, name='Data Processing') row_graphic=Row(graph_text, graph_act, width=150) graph_header = Div(text= " <h2>Graphics options</h2>", height=45, width=400 ) window_header = Div(text= " <h2>Window Range</h2>", height=45, width=400 ) range_spacer=Div(text= "", width= 100, height=20 ) range_min=Div(text= "<b>Min</b>", width= 70, height=20 ) range_max=Div(text= "<b>Max</b>", width= 70, height=20 ) x_range_text=Div(text= " <b>X-Range (m/z)</b>", width= 100, height=30 ) y_range_text=Div(text= " <b>Y-Range (%)</b>", width= 100, height=30 ) x_range_min=TextInput(value=str(1000.0), disabled=False, width=70, height=30) x_range_max=TextInput(value=str(20000.0), disabled=False, width=70, height=30) y_range_min=TextInput(value=str(0.0), disabled=False, width=70, height=30) y_range_max=TextInput(value=str(100.0), disabled=False, width=70, height=30) range_text=Column(range_spacer,x_range_text,y_range_text) range_min=Column(range_min, x_range_min,y_range_min) range_max=Column(range_max, x_range_max,y_range_max) range_row=Row(range_text, range_min, range_max) range_cb=CustomJS(args=dict(plot_canvas=plot_canvas, x_range_min=x_range_min, x_range_max=x_range_max, y_range_min=y_range_min, y_range_max=y_range_max), code=open(os.path.join(os.getcwd(), 'JS_Functions', "range_cb.js")).read()) set_spacer=Div(text= "", width= 100, height=30) set_range=Button(label='Set range', width=150, height=30, button_type='success', callback=range_cb) set_range.js_on_event(ButtonClick, range_cb) graph_layout= Column(graph_header, row_graphic, Row(save4k_text, save4k), Row(savesvg_text, savesvg), fig_text, window_header, range_row, Row(set_spacer, set_range), visible=False) graph_opt.js_link('active', graph_layout, 'visible') fig4k_cb=CustomJS(args=dict(save4k=save4k, plot_canvas=plot_canvas, svg_canvas=svg_canvas, highres_canvas=highres_canvas , series_names=series_names,\ bg_mz=bg_mz, bg_mz4k=bg_mz4k, bg_mzsvg=bg_mzsvg, series_mz4k=series_mz4k, series_mzsvg=series_mzsvg, series_mz=series_mz,save4k_text=save4k_text), code=open(os.path.join(os.getcwd(), 'JS_Functions', "fig4k_cb.js")).read()) figsvg_cb=CustomJS(args=dict(savesvg=savesvg, plot_canvas=plot_canvas, svg_canvas=svg_canvas, highres_canvas=highres_canvas , series_names=series_names,\ bg_mz=bg_mz, bg_mz4k=bg_mz4k, bg_mzsvg=bg_mzsvg, series_mz4k=series_mz4k, series_mzsvg=series_mzsvg, series_mz=series_mz,savesvg_text=savesvg_text), code=open(os.path.join(os.getcwd(), 'JS_Functions', "figsvg_cb.js")).read()) save4k_text.js_on_event(ButtonClick, fig4k_cb) savesvg_text.js_on_event(ButtonClick, figsvg_cb) graphics_cb=CustomJS(args=dict(linew_txt=linew_inp, ticks_sele=ticks_sele, labels_sele=labels_sele, grid_sele=grid_sele, \ plot_canvas=plot_canvas, highres_canvas=highres_canvas, sel_lines=sel_lines, sel_linessvg=sel_linessvg, sel_lines4k=sel_lines4k, series_names=series_names), code=open(os.path.join(os.getcwd(), 'JS_Functions', "graphics_cb.js")).read()) linew_inp.js_on_change('value', graphics_cb) drop_cb = CustomJS(args=dict(GroEL_mz=GroEL_mz, peak_lines=peak_lines, peak_lines4k=peak_lines4k, col=col, sel_lines=sel_lines, sel_lines4k=sel_lines4k, cropping_slider=cropping_slider, gaussian_smooth=gaussian_smooth, \ n_smooth=n_smooth, intensity_threshold=intensity_threshold, process_data=process_data, substract=substract, sub_name=sub_name, ser_match=ser_match, \ ser_act=ser_act, comment_window=comment_window, stoich=stoich, SU_act=SU_act, posneg=posneg, series_colours_DS=series_colours_DS, series_dict=series_dict, \ DataProcessingParameters=DataProcessingParameters, series_names=series_names, series_masses=series_masses, aser_data=aser_data, series_data=series_data, \ series_sele=series_sele, series_mz=series_mz, raw_mz=raw_mz, proc_mz=proc_mz, bg_mz=bg_mz, peak_mz=peak_mz, plot_canvas=plot_canvas, \ pp_mean_data=pp_mean_data, pp_std_data=pp_std_data), \ code=open(os.path.join(os.getcwd(), 'JS_Functions', "navia_functions.js")).read() + open(os.path.join(os.getcwd(), 'JS_Functions', "drop_cb.js")).read()) dropdown = Dropdown(label="File", menu=menu, width=150, height=30, callback=drop_cb) topleftspacer=Spacer(height=30, width=23) row1 = Row(topleftspacer, dropdown, ser_act, col, posneg, mass_match, pp, mass_finder, dt_button, graph_opt, help_button) row2 = Row(plot_canvas,Column(mass_finder_column, data_tools, graph_layout), height=768) row3 = Row(topleftspacer,showtab, masses_table, comment_window)#, row_graphic) SU_header = Div(text= " <h2>Subunits</h2>", height=35, width=580 ) MM_header = Div(text= " <h2>Stoichiometry</h2>", height=35, width=684 ) SU_text = Div(text= "Note: Edit new subunits in the table on the left. Delete Subunits deletes the highlighted subunit.\n", width= 120 ) SU_column=Column(Spacer(height=30), SU_add_button, SU_del_button, SU_text) MM_column=Column(Spacer(height=30), ser_match, diff_match, Spacer(height=10), Row(mass_match_button)) mass_match_and_comment = Row(topleftspacer, Column(Row(SU_header, MM_header), Row(complex_table, SU_column, match_table, MM_column)), visible=False) # collumnasd =[row1, p] # layout=gridplot(collumnasd, ncols=1) left_logo_img = iio.imread(os.path.join(os.getcwd(), 'Logo', 'navia_logo.png')) new_img=[] for i in range(len(left_logo_img)): new_img.append(left_logo_img[len(left_logo_img)-1-i]) left_logo_img=np.array(new_img) right_logo_img = iio.imread(os.path.join(os.getcwd(), 'Logo', 'oxford_rect.png')) new_img=[] for i in range(len(right_logo_img)): new_img.append(right_logo_img[len(right_logo_img)-1-i]) right_logo_img=np.array(new_img) p = figure(width=300, height=100, toolbar_location=None) p.x_range.range_padding = p.y_range.range_padding = 0 # must give a vector of images p.image_rgba(image=[new_img], x=0, y=0, dw=10, dh=10) left_logo = figure(width=300, height=100, toolbar_location=None, tools='') left_logo.x_range.range_padding = left_logo.y_range.range_padding = 0 left_logo.image_rgba(image=[left_logo_img], x=0, y=0, dw=10, dh=10) # left_logo.image_url(url=['navia_logo.png'], x=0, y=1, w=1, h=1) left_logo.xgrid.grid_line_color = None left_logo.ygrid.grid_line_color = None left_logo.outline_line_alpha=0.0 left_logo.axis.minor_tick_line_alpha=0.0 left_logo.axis.major_label_text_alpha=0.0 left_logo.axis.major_tick_line_alpha=0.0 left_logo.axis.axis_line_alpha=0.0 left_logo.axis.axis_label_text_alpha=0.0 right_logo = figure(width=276, height=100, toolbar_location=None, tools='') right_logo.x_range.range_padding = right_logo.y_range.range_padding = 0 right_logo.image_rgba(image=[right_logo_img], x=0, y=0, dw=10, dh=10) # right_logo.image_url(url=['oxford_rect.png'], x=0, y=1, w=1, h=1) right_logo.xgrid.grid_line_color = None right_logo.ygrid.grid_line_color = None right_logo.outline_line_alpha=0.0 right_logo.axis.minor_tick_line_alpha=0.0 right_logo.axis.major_label_text_alpha=0.0 right_logo.axis.major_tick_line_alpha=0.0 right_logo.axis.axis_line_alpha=0.0 right_logo.axis.axis_label_text_alpha=0.0 row0=Row(left_logo, Spacer(width=160), Div(text= "<h> <b>Na</b>tive <b>Vi</b>sual <b>A</b>nalyser </h>", width= 596, height=70 , style={'font-size': '42px', 'color':'#002147'}, align='center'), right_logo) row2b=Row(topleftspacer,Div(text= " <h2>Peaks of Active Series (m/z)</h2>", width= 580, height=35 ),Div(text= " <h2>Masses</h2>", width= 370, height=35 ), Div(text= " <h2>Notes on Spectrum</h2>", width= 280, height=35 )) layout = Column(row0, row1, row2, row2b, row3, mass_match_and_comment) dt_button.js_link('active', data_tools, 'visible') mass_match.js_link('active', mass_match_and_comment, 'visible') highres_text = Div(text= "<b> This is an empty panel for the 4k plot. </b>", width= 300, height=70) svg_text = Div(text= "<b> This is an empty panel for the SVG plot. </b>", width= 300, height=70) tab=Tabs(tabs=[ Panel(child=layout, title='Plot'), Panel(child=Column(highres_text,highres_canvas), title='4k Plot'), Panel(child=Column(svg_text,svg_canvas), title='SVG Plot') ], tabs_location='below') show(tab)
[ "bokeh.models.widgets.Dropdown", "bokeh.plotting.figure", "pandas.read_csv", "bokeh.models.widgets.Slider", "bokeh.layouts.Row", "bokeh.models.widgets.Button", "bokeh.layouts.Column", "numpy.array", "bokeh.models.widgets.Div", "bokeh.models.widgets.NumberFormatter", "bokeh.models.ToolbarBox", ...
[((758, 805), 'bokeh.plotting.output_file', 'output_file', (['"""index.html"""'], {'title': '"""NaViA v 1.0"""'}), "('index.html', title='NaViA v 1.0')\n", (769, 805), False, 'from bokeh.plotting import figure, output_file, ColumnDataSource\n'), ((1177, 1349), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': '(1366)', 'plot_height': '(768)', 'output_backend': '"""svg"""', 'x_axis_label': '"""m/z """', 'y_axis_label': '"""Rel. Abundance [%]"""', 'tools': "['save']", 'hidpi': '(False)', 'visible': '(True)'}), "(plot_width=1366, plot_height=768, output_backend='svg', x_axis_label\n ='m/z ', y_axis_label='Rel. Abundance [%]', tools=['save'], hidpi=\n False, visible=True)\n", (1183, 1349), False, 'from bokeh.plotting import figure, output_file, ColumnDataSource\n'), ((2075, 2091), 'bokeh.models.Legend', 'Legend', ([], {'items': '[]'}), '(items=[])\n', (2081, 2091), False, 'from bokeh.models import HoverTool, CustomJS, BoxSelectTool, Panel, Tabs, Span, AjaxDataSource, ToolbarBox, Toolbar, Legend, LegendItem, PanTool, TapTool\n'), ((3573, 3641), 'pandas.read_csv', 'pd.read_csv', (['"""Testdata/siyun_groel.txt"""'], {'skiprows': '(10)', 'delimiter': '"""\t"""'}), "('Testdata/siyun_groel.txt', skiprows=10, delimiter='\\t')\n", (3584, 3641), True, 'import pandas as pd\n'), ((3817, 3848), 'bokeh.models.AjaxDataSource', 'AjaxDataSource', ([], {'data': 'groel_data'}), '(data=groel_data)\n', (3831, 3848), False, 'from bokeh.models import HoverTool, CustomJS, BoxSelectTool, Panel, Tabs, Span, AjaxDataSource, ToolbarBox, Toolbar, Legend, LegendItem, PanTool, TapTool\n'), ((5362, 5457), 'bokeh.models.glyphs.MultiLine', 'MultiLine', ([], {'xs': '"""mz"""', 'ys': '"""Intensity"""', 'line_color': "series_cols['Background']", 'name': '"""Background"""'}), "(xs='mz', ys='Intensity', line_color=series_cols['Background'],\n name='Background')\n", (5371, 5457), False, 'from bokeh.models.glyphs import MultiLine\n'), ((5482, 5591), 'bokeh.models.glyphs.MultiLine', 'MultiLine', ([], {'xs': '"""mz"""', 'ys': '"""Intensity"""', 'line_color': "series_cols['Background']", 'name': '"""Background"""', 'line_width': '(4)'}), "(xs='mz', ys='Intensity', line_color=series_cols['Background'],\n name='Background', line_width=4)\n", (5491, 5591), False, 'from bokeh.models.glyphs import MultiLine\n'), ((5617, 5712), 'bokeh.models.glyphs.MultiLine', 'MultiLine', ([], {'xs': '"""mz"""', 'ys': '"""Intensity"""', 'line_color': "series_cols['Background']", 'name': '"""Background"""'}), "(xs='mz', ys='Intensity', line_color=series_cols['Background'],\n name='Background')\n", (5626, 5712), False, 'from bokeh.models.glyphs import MultiLine\n'), ((5856, 5978), 'bokeh.models.glyphs.MultiLine', 'MultiLine', ([], {'xs': '"""xs"""', 'ys': '"""ys"""', 'name': '"""pp_mean"""', 'line_color': 'bokeh.palettes.Category20_20[0]', 'line_width': '(2)', 'line_alpha': '(0.5)'}), "(xs='xs', ys='ys', name='pp_mean', line_color=bokeh.palettes.\n Category20_20[0], line_width=2, line_alpha=0.5)\n", (5865, 5978), False, 'from bokeh.models.glyphs import MultiLine\n'), ((5983, 6124), 'bokeh.models.glyphs.MultiLine', 'MultiLine', ([], {'xs': '"""xs"""', 'ys': '"""ys"""', 'name': '"""pp_std"""', 'line_color': 'bokeh.palettes.Category20_20[0]', 'line_dash': '"""dashed"""', 'line_width': '(2)', 'line_alpha': '(0.5)'}), "(xs='xs', ys='ys', name='pp_std', line_color=bokeh.palettes.\n Category20_20[0], line_dash='dashed', line_width=2, line_alpha=0.5)\n", (5992, 6124), False, 'from bokeh.models.glyphs import MultiLine\n'), ((6365, 6461), 'bokeh.models.widgets.Dropdown', 'Dropdown', ([], {'label': '"""Create Series"""', 'value': '"""Background"""', 'menu': 'ser_act_menu', 'width': '(140)', 'height': '(30)'}), "(label='Create Series', value='Background', menu=ser_act_menu,\n width=140, height=30)\n", (6373, 6461), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((6987, 7072), 'bokeh.models.widgets.ColorPicker', 'ColorPicker', ([], {'color': '"""black"""', 'width': '(50)', 'height': '(30)', 'disabled': '(False)', 'callback': 'col_cb'}), "(color='black', width=50, height=30, disabled=False, callback=col_cb\n )\n", (6998, 7072), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((7080, 7171), 'bokeh.models.widgets.Select', 'Select', ([], {'value': '""""""', 'options': '[]', 'title': '"""Stoich. Calculation Series:"""', 'width': '(150)', 'height': '(45)'}), "(value='', options=[], title='Stoich. Calculation Series:', width=150,\n height=45)\n", (7086, 7171), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((8495, 8593), 'bokeh.models.widgets.Dropdown', 'Dropdown', ([], {'menu': 'posneg_menu', 'value': '"""Positive"""', 'label': '"""Instrument Mode: +"""', 'width': '(160)', 'height': '(30)'}), "(menu=posneg_menu, value='Positive', label='Instrument Mode: +',\n width=160, height=30)\n", (8503, 8593), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((8603, 8647), 'bokeh.models.widgets.Toggle', 'Toggle', ([], {'label': '"""Figure"""', 'width': '(110)', 'height': '(30)'}), "(label='Figure', width=110, height=30)\n", (8609, 8647), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((8774, 8823), 'bokeh.models.widgets.Toggle', 'Toggle', ([], {'label': '"""Mass Finder"""', 'width': '(110)', 'height': '(30)'}), "(label='Mass Finder', width=110, height=30)\n", (8780, 8823), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((8837, 8896), 'bokeh.models.widgets.Toggle', 'Toggle', ([], {'label': '"""Complex Stoichiometry"""', 'width': '(150)', 'height': '(30)'}), "(label='Complex Stoichiometry', width=150, height=30)\n", (8843, 8896), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((8909, 8962), 'bokeh.models.widgets.Toggle', 'Toggle', ([], {'label': '"""Data Processing"""', 'width': '(110)', 'height': '(30)'}), "(label='Data Processing', width=110, height=30)\n", (8915, 8962), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((8977, 9018), 'bokeh.models.widgets.Button', 'Button', ([], {'label': '"""Help"""', 'width': '(90)', 'height': '(30)'}), "(label='Help', width=90, height=30)\n", (8983, 9018), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((12261, 12321), 'bokeh.models.widgets.Toggle', 'Toggle', ([], {'label': '"""Predict adjecent peaks"""', 'width': '(150)', 'height': '(30)'}), "(label='Predict adjecent peaks', width=150, height=30)\n", (12267, 12321), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((12520, 12599), 'bokeh.models.glyphs.MultiLine', 'MultiLine', ([], {'xs': '"""xs"""', 'ys': '"""ys"""', 'line_color': '"""#002147"""', 'line_width': '(2)', 'line_alpha': '(0.5)'}), "(xs='xs', ys='ys', line_color='#002147', line_width=2, line_alpha=0.5)\n", (12529, 12599), False, 'from bokeh.models.glyphs import MultiLine\n'), ((12771, 12782), 'bokeh.models.HoverTool', 'HoverTool', ([], {}), '()\n', (12780, 12782), False, 'from bokeh.models import HoverTool, CustomJS, BoxSelectTool, Panel, Tabs, Span, AjaxDataSource, ToolbarBox, Toolbar, Legend, LegendItem, PanTool, TapTool\n'), ((13431, 13554), 'bokeh.models.widgets.DataTable', 'DataTable', ([], {'source': 'aser_data', 'name': 'i_series', 'columns': 'columns', 'width': '(580)', 'height': '(300)', 'editable': '(False)', 'index_position': 'None'}), '(source=aser_data, name=i_series, columns=columns, width=580,\n height=300, editable=False, index_position=None)\n', (13440, 13554), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((14530, 14570), 'bokeh.models.widgets.HTMLTemplateFormatter', 'HTMLTemplateFormatter', ([], {'template': 'template'}), '(template=template)\n', (14551, 14570), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((14954, 15101), 'bokeh.models.widgets.DataTable', 'DataTable', ([], {'source': 'series_masses', 'name': '"""Mass table"""', 'columns': 'columns_mass_table', 'width': '(370)', 'height': '(300)', 'index_position': 'None', 'editable': '(False)'}), "(source=series_masses, name='Mass table', columns=\n columns_mass_table, width=370, height=300, index_position=None,\n editable=False)\n", (14963, 15101), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((15706, 15851), 'bokeh.models.widgets.DataTable', 'DataTable', ([], {'source': 'SU_act', 'name': '"""Complex table"""', 'columns': 'columns_complex_table', 'width': '(450)', 'height': '(280)', 'index_position': 'None', 'editable': '(True)'}), "(source=SU_act, name='Complex table', columns=\n columns_complex_table, width=450, height=280, index_position=None,\n editable=True)\n", (15715, 15851), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((16142, 16214), 'bokeh.models.widgets.Button', 'Button', ([], {'label': '"""Add subunit"""', 'width': '(120)', 'height': '(30)', 'button_type': '"""success"""'}), "(label='Add subunit', width=120, height=30, button_type='success')\n", (16148, 16214), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((16229, 16303), 'bokeh.models.widgets.Button', 'Button', ([], {'label': '"""Delete subunit"""', 'width': '(120)', 'height': '(30)', 'button_type': '"""danger"""'}), "(label='Delete subunit', width=120, height=30, button_type='danger')\n", (16235, 16303), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((16423, 16486), 'bokeh.models.widgets.TextAreaInput', 'TextAreaInput', ([], {'value': '"""Add comments here"""', 'width': '(340)', 'height': '(280)'}), "(value='Add comments here', width=340, height=280)\n", (16436, 16486), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((17108, 17231), 'bokeh.models.widgets.DataTable', 'DataTable', ([], {'source': 'stoich', 'name': '"""Complex table"""', 'columns': 'columns_match_table', 'width': '(534)', 'height': '(280)', 'index_position': 'None'}), "(source=stoich, name='Complex table', columns=columns_match_table,\n width=534, height=280, index_position=None)\n", (17117, 17231), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((17466, 17540), 'bokeh.models.widgets.Button', 'Button', ([], {'label': '"""Stoichiometry"""', 'width': '(150)', 'height': '(30)', 'button_type': '"""success"""'}), "(label='Stoichiometry', width=150, height=30, button_type='success')\n", (17472, 17540), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((17618, 17738), 'bokeh.models.widgets.RangeSlider', 'RangeSlider', ([], {'start': '(0.0)', 'end': '(100000.0)', 'value': '(0.0, 100000.0)', 'name': '"""cropping_slider"""', 'step': '(100)', 'width': '(150)', 'height': '(30)'}), "(start=0.0, end=100000.0, value=(0.0, 100000.0), name=\n 'cropping_slider', step=100, width=150, height=30)\n", (17629, 17738), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((17752, 17838), 'bokeh.models.widgets.Slider', 'Slider', ([], {'value': '(0.0)', 'start': '(0)', 'end': '(50)', 'step': '(1)', 'name': '"""gau_sigma"""', 'width': '(150)', 'height': '(30)'}), "(value=0.0, start=0, end=50, step=1, name='gau_sigma', width=150,\n height=30)\n", (17758, 17838), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((17913, 17991), 'bokeh.models.widgets.Slider', 'Slider', ([], {'value': '(1)', 'start': '(0)', 'end': '(10)', 'step': '(1)', 'name': '"""gau_rep"""', 'width': '(150)', 'height': '(30)'}), "(value=1, start=0, end=10, step=1, name='gau_rep', width=150, height=30)\n", (17919, 17991), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((18014, 18113), 'bokeh.models.widgets.Slider', 'Slider', ([], {'value': '(0.0)', 'start': '(0)', 'end': '(100)', 'step': '(0.1)', 'name': '"""intensity_threshold"""', 'width': '(150)', 'height': '(30)'}), "(value=0.0, start=0, end=100, step=0.1, name='intensity_threshold',\n width=150, height=30)\n", (18020, 18113), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((18186, 18273), 'bokeh.models.widgets.Slider', 'Slider', ([], {'value': '(0.0)', 'start': '(0)', 'end': '(100)', 'step': '(1)', 'name': '"""sub_value"""', 'width': '(150)', 'height': '(30)'}), "(value=0.0, start=0, end=100, step=1, name='sub_value', width=150,\n height=30)\n", (18192, 18273), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((18518, 18619), 'bokeh.models.CustomJS', 'CustomJS', ([], {'code': '""" if (cb_obj.active == true) {cb_obj.label=\'on\'} else {cb_obj.label=\'off\'} """'}), '(code=\n " if (cb_obj.active == true) {cb_obj.label=\'on\'} else {cb_obj.label=\'off\'} "\n )\n', (18526, 18619), False, 'from bokeh.models import HoverTool, CustomJS, BoxSelectTool, Panel, Tabs, Span, AjaxDataSource, ToolbarBox, Toolbar, Legend, LegendItem, PanTool, TapTool\n'), ((18657, 18712), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <h2>Mass Finder</h2>"""', 'height': '(45)', 'width': '(400)'}), "(text=' <h2>Mass Finder</h2>', height=45, width=400)\n", (18660, 18712), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((18817, 18959), 'bokeh.models.widgets.RangeSlider', 'RangeSlider', ([], {'start': '(1.0)', 'end': '(500.0)', 'value': '(1.0, 50.0)', 'title': '"""Charge range:"""', 'name': '"""mass_finder_range_slider"""', 'step': '(1)', 'width': '(250)', 'height': '(30)'}), "(start=1.0, end=500.0, value=(1.0, 50.0), title='Charge range:',\n name='mass_finder_range_slider', step=1, width=250, height=30)\n", (18828, 18959), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((19061, 19188), 'bokeh.models.widgets.Slider', 'Slider', ([], {'value': '(100)', 'start': '(0.0)', 'end': '(1000.0)', 'step': '(10.0)', 'title': '"""Mass of Complex (kDa)"""', 'name': '"""gau_sigma"""', 'width': '(250)', 'height': '(30)'}), "(value=100, start=0.0, end=1000.0, step=10.0, title=\n 'Mass of Complex (kDa)', name='gau_sigma', width=250, height=30)\n", (19067, 19188), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((19214, 19269), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '"""Enter exact Mass (Da)"""', 'width': '(150)', 'height': '(30)'}), "(text='Enter exact Mass (Da)', width=150, height=30)\n", (19217, 19269), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((19416, 19468), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '"""Show mz prediction"""', 'width': '(150)', 'height': '(30)'}), "(text='Show mz prediction', width=150, height=30)\n", (19419, 19468), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((19496, 19571), 'bokeh.models.widgets.Toggle', 'Toggle', ([], {'label': '"""off"""', 'active': '(False)', 'width': '(100)', 'height': '(30)', 'callback': 'toggle_cb'}), "(label='off', active=False, width=100, height=30, callback=toggle_cb)\n", (19502, 19571), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((20826, 20870), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" Range mz:"""', 'width': '(150)', 'height': '(30)'}), "(text=' Range mz:', width=150, height=30)\n", (20829, 20870), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((20937, 20991), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" Gaussian Smoothing:"""', 'width': '(150)', 'height': '(30)'}), "(text=' Gaussian Smoothing:', width=150, height=30)\n", (20940, 20991), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((21011, 21067), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" Repeats of Smoothing:"""', 'width': '(150)', 'height': '(30)'}), "(text=' Repeats of Smoothing:', width=150, height=30)\n", (21014, 21067), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((21144, 21202), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" Intensity Threshold (%)"""', 'width': '(150)', 'height': '(30)'}), "(text=' Intensity Threshold (%)', width=150, height=30)\n", (21147, 21202), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((21217, 21362), 'bokeh.models.widgets.Select', 'Select', ([], {'options': "['Substract Minimum', 'Substract Line', 'Substract Curved']", 'name': '"""sub_mode"""', 'value': '"""Substract Minimum"""', 'width': '(150)', 'height': '(30)'}), "(options=['Substract Minimum', 'Substract Line', 'Substract Curved'],\n name='sub_mode', value='Substract Minimum', width=150, height=30)\n", (21223, 21362), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((21564, 21612), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <h2>Data Processing</h2>"""', 'height': '(45)'}), "(text=' <h2>Data Processing</h2>', height=45)\n", (21567, 21612), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((22509, 22610), 'bokeh.models.widgets.Button', 'Button', ([], {'label': '"""Process Data"""', 'width': '(100)', 'height': '(30)', 'button_type': '"""success"""', 'callback': 'processing_cb'}), "(label='Process Data', width=100, height=30, button_type='success',\n callback=processing_cb)\n", (22515, 22610), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((22989, 23087), 'bokeh.models.widgets.Button', 'Button', ([], {'label': '"""Reset Processing"""', 'width': '(80)', 'height': '(30)', 'button_type': '"""danger"""', 'callback': 'reset_cb'}), "(label='Reset Processing', width=80, height=30, button_type='danger',\n callback=reset_cb)\n", (22995, 23087), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((23095, 23168), 'bokeh.layouts.Column', 'Column', (['cropping', 'gau_name', 'n_smooth_name', 'int_name', 'sub_name', 'reset_data'], {}), '(cropping, gau_name, n_smooth_name, int_name, sub_name, reset_data)\n', (23101, 23168), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((23189, 23289), 'bokeh.layouts.Column', 'Column', (['cropping_slider', 'gaussian_smooth', 'n_smooth', 'intensity_threshold', 'substract', 'process_data'], {}), '(cropping_slider, gaussian_smooth, n_smooth, intensity_threshold,\n substract, process_data)\n', (23195, 23289), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((23299, 23343), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" Show Grid"""', 'width': '(150)', 'height': '(30)'}), "(text=' Show Grid', width=150, height=30)\n", (23302, 23343), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((23359, 23432), 'bokeh.models.widgets.Toggle', 'Toggle', ([], {'label': '"""on"""', 'active': '(True)', 'width': '(100)', 'height': '(30)', 'callback': 'toggle_cb'}), "(label='on', active=True, width=100, height=30, callback=toggle_cb)\n", (23365, 23432), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((23951, 23997), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" Show labels"""', 'width': '(150)', 'height': '(30)'}), "(text=' Show labels', width=150, height=30)\n", (23954, 23997), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((24015, 24088), 'bokeh.models.widgets.Toggle', 'Toggle', ([], {'label': '"""on"""', 'active': '(True)', 'width': '(100)', 'height': '(30)', 'callback': 'toggle_cb'}), "(label='on', active=True, width=100, height=30, callback=toggle_cb)\n", (24021, 24088), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((24104, 24149), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" Show Ticks"""', 'width': '(150)', 'height': '(30)'}), "(text=' Show Ticks', width=150, height=30)\n", (24107, 24149), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((24166, 24239), 'bokeh.models.widgets.Toggle', 'Toggle', ([], {'label': '"""on"""', 'active': '(True)', 'width': '(100)', 'height': '(30)', 'callback': 'toggle_cb'}), "(label='on', active=True, width=100, height=30, callback=toggle_cb)\n", (24172, 24239), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((24252, 24296), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" Show Axes"""', 'width': '(150)', 'height': '(30)'}), "(text=' Show Axes', width=150, height=30)\n", (24255, 24296), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((24312, 24385), 'bokeh.models.widgets.Toggle', 'Toggle', ([], {'label': '"""on"""', 'active': '(True)', 'width': '(100)', 'height': '(30)', 'callback': 'toggle_cb'}), "(label='on', active=True, width=100, height=30, callback=toggle_cb)\n", (24318, 24385), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((25077, 25128), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" Show mz of Peaks"""', 'width': '(150)', 'height': '(30)'}), "(text=' Show mz of Peaks', width=150, height=30)\n", (25080, 25128), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((25146, 25221), 'bokeh.models.widgets.Toggle', 'Toggle', ([], {'label': '"""off"""', 'active': '(False)', 'width': '(100)', 'height': '(30)', 'callback': 'toggle_cb'}), "(label='off', active=False, width=100, height=30, callback=toggle_cb)\n", (25152, 25221), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((25994, 26083), 'bokeh.models.widgets.Button', 'Button', ([], {'label': '""" Create 4K PNG figure: """', 'width': '(150)', 'height': '(30)', 'button_type': '"""success"""'}), "(label=' Create 4K PNG figure: ', width=150, height=30, button_type=\n 'success')\n", (26000, 26083), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((26154, 26241), 'bokeh.models.widgets.Button', 'Button', ([], {'label': '""" Create SVG figure: """', 'width': '(150)', 'height': '(30)', 'button_type': '"""success"""'}), "(label=' Create SVG figure: ', width=150, height=30, button_type=\n 'success')\n", (26160, 26241), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((26311, 26357), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" Line width """', 'width': '(150)', 'height': '(30)'}), "(text=' Line width ', width=150, height=30)\n", (26314, 26357), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((26478, 26490), 'bokeh.models.ToolbarBox', 'ToolbarBox', ([], {}), '()\n', (26488, 26490), False, 'from bokeh.models import HoverTool, CustomJS, BoxSelectTool, Panel, Tabs, Span, AjaxDataSource, ToolbarBox, Toolbar, Legend, LegendItem, PanTool, TapTool\n'), ((26508, 26554), 'bokeh.models.Toolbar', 'Toolbar', ([], {'tools': 'highres_canvas.tools', 'logo': 'None'}), '(tools=highres_canvas.tools, logo=None)\n', (26515, 26554), False, 'from bokeh.models import HoverTool, CustomJS, BoxSelectTool, Panel, Tabs, Span, AjaxDataSource, ToolbarBox, Toolbar, Legend, LegendItem, PanTool, TapTool\n'), ((26598, 26610), 'bokeh.models.ToolbarBox', 'ToolbarBox', ([], {}), '()\n', (26608, 26610), False, 'from bokeh.models import HoverTool, CustomJS, BoxSelectTool, Panel, Tabs, Span, AjaxDataSource, ToolbarBox, Toolbar, Legend, LegendItem, PanTool, TapTool\n'), ((26629, 26671), 'bokeh.models.Toolbar', 'Toolbar', ([], {'tools': 'svg_canvas.tools', 'logo': 'None'}), '(tools=svg_canvas.tools, logo=None)\n', (26636, 26671), False, 'from bokeh.models import HoverTool, CustomJS, BoxSelectTool, Panel, Tabs, Span, AjaxDataSource, ToolbarBox, Toolbar, Legend, LegendItem, PanTool, TapTool\n'), ((26717, 26795), 'bokeh.layouts.Column', 'Column', (['grid_text', 'labels_text', 'ticks_text', 'axes_text', 'peakmz_text', 'linew_text'], {}), '(grid_text, labels_text, ticks_text, axes_text, peakmz_text, linew_text)\n', (26723, 26795), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((26806, 26883), 'bokeh.layouts.Column', 'Column', (['grid_sele', 'labels_sele', 'ticks_sele', 'axes_sele', 'peakmz_sele', 'linew_inp'], {}), '(grid_sele, labels_sele, ticks_sele, axes_sele, peakmz_sele, linew_inp)\n', (26812, 26883), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((26943, 26988), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" Ion Charge"""', 'width': '(150)', 'height': '(30)'}), "(text=' Ion Charge', width=150, height=30)\n", (26946, 26988), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((27006, 27065), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <h2>Data Processing</h2>"""', 'height': '(45)', 'width': '(400)'}), "(text=' <h2>Data Processing</h2>', height=45, width=400)\n", (27009, 27065), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((27084, 27143), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <h2>Instrument Mode</h2>"""', 'height': '(45)', 'width': '(400)'}), "(text=' <h2>Instrument Mode</h2>', height=45, width=400)\n", (27087, 27143), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((27197, 27386), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '"""Note: The data processing might take a couple of seconds. Please stay patient and refrain from pressing the Process Data button repeatedly. \n"""', 'width': '(300)', 'height': '(70)'}), '(text=\n """Note: The data processing might take a couple of seconds. Please stay patient and refrain from pressing the Process Data button repeatedly. \n"""\n , width=300, height=70)\n', (27200, 27386), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((27497, 27534), 'bokeh.layouts.Row', 'Row', (['graph_text', 'graph_act'], {'width': '(150)'}), '(graph_text, graph_act, width=150)\n', (27500, 27534), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((27550, 27610), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <h2>Graphics options</h2>"""', 'height': '(45)', 'width': '(400)'}), "(text=' <h2>Graphics options</h2>', height=45, width=400)\n", (27553, 27610), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((27629, 27685), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <h2>Window Range</h2>"""', 'height': '(45)', 'width': '(400)'}), "(text=' <h2>Window Range</h2>', height=45, width=400)\n", (27632, 27685), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((27702, 27736), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""""""', 'width': '(100)', 'height': '(20)'}), "(text='', width=100, height=20)\n", (27705, 27736), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((27750, 27793), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '"""<b>Min</b>"""', 'width': '(70)', 'height': '(20)'}), "(text='<b>Min</b>', width=70, height=20)\n", (27753, 27793), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((27807, 27850), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '"""<b>Max</b>"""', 'width': '(70)', 'height': '(20)'}), "(text='<b>Max</b>', width=70, height=20)\n", (27810, 27850), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((27868, 27923), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <b>X-Range (m/z)</b>"""', 'width': '(100)', 'height': '(30)'}), "(text=' <b>X-Range (m/z)</b>', width=100, height=30)\n", (27871, 27923), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((27940, 27993), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <b>Y-Range (%)</b>"""', 'width': '(100)', 'height': '(30)'}), "(text=' <b>Y-Range (%)</b>', width=100, height=30)\n", (27943, 27993), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((28320, 28368), 'bokeh.layouts.Column', 'Column', (['range_spacer', 'x_range_text', 'y_range_text'], {}), '(range_spacer, x_range_text, y_range_text)\n', (28326, 28368), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((28377, 28420), 'bokeh.layouts.Column', 'Column', (['range_min', 'x_range_min', 'y_range_min'], {}), '(range_min, x_range_min, y_range_min)\n', (28383, 28420), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((28430, 28473), 'bokeh.layouts.Column', 'Column', (['range_max', 'x_range_max', 'y_range_max'], {}), '(range_max, x_range_max, y_range_max)\n', (28436, 28473), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((28483, 28520), 'bokeh.layouts.Row', 'Row', (['range_text', 'range_min', 'range_max'], {}), '(range_text, range_min, range_max)\n', (28486, 28520), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((28764, 28798), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""""""', 'width': '(100)', 'height': '(30)'}), "(text='', width=100, height=30)\n", (28767, 28798), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((28811, 28904), 'bokeh.models.widgets.Button', 'Button', ([], {'label': '"""Set range"""', 'width': '(150)', 'height': '(30)', 'button_type': '"""success"""', 'callback': 'range_cb'}), "(label='Set range', width=150, height=30, button_type='success',\n callback=range_cb)\n", (28817, 28904), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((31546, 31619), 'bokeh.models.widgets.Dropdown', 'Dropdown', ([], {'label': '"""File"""', 'menu': 'menu', 'width': '(150)', 'height': '(30)', 'callback': 'drop_cb'}), "(label='File', menu=menu, width=150, height=30, callback=drop_cb)\n", (31554, 31619), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((31634, 31661), 'bokeh.layouts.Spacer', 'Spacer', ([], {'height': '(30)', 'width': '(23)'}), '(height=30, width=23)\n', (31640, 31661), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((31669, 31787), 'bokeh.layouts.Row', 'Row', (['topleftspacer', 'dropdown', 'ser_act', 'col', 'posneg', 'mass_match', 'pp', 'mass_finder', 'dt_button', 'graph_opt', 'help_button'], {}), '(topleftspacer, dropdown, ser_act, col, posneg, mass_match, pp,\n mass_finder, dt_button, graph_opt, help_button)\n', (31672, 31787), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((31880, 31937), 'bokeh.layouts.Row', 'Row', (['topleftspacer', 'showtab', 'masses_table', 'comment_window'], {}), '(topleftspacer, showtab, masses_table, comment_window)\n', (31883, 31937), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((31965, 32017), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <h2>Subunits</h2>"""', 'height': '(35)', 'width': '(580)'}), "(text=' <h2>Subunits</h2>', height=35, width=580)\n", (31968, 32017), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((32032, 32089), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <h2>Stoichiometry</h2>"""', 'height': '(35)', 'width': '(684)'}), "(text=' <h2>Stoichiometry</h2>', height=35, width=684)\n", (32035, 32089), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((32102, 32238), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '"""Note: Edit new subunits in the table on the left. Delete Subunits deletes the highlighted subunit.\n"""', 'width': '(120)'}), '(text=\n """Note: Edit new subunits in the table on the left. Delete Subunits deletes the highlighted subunit.\n"""\n , width=120)\n', (32105, 32238), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((32825, 32842), 'numpy.array', 'np.array', (['new_img'], {}), '(new_img)\n', (32833, 32842), True, 'import numpy as np\n'), ((33048, 33065), 'numpy.array', 'np.array', (['new_img'], {}), '(new_img)\n', (33056, 33065), True, 'import numpy as np\n'), ((33073, 33125), 'bokeh.plotting.figure', 'figure', ([], {'width': '(300)', 'height': '(100)', 'toolbar_location': 'None'}), '(width=300, height=100, toolbar_location=None)\n', (33079, 33125), False, 'from bokeh.plotting import figure, output_file, ColumnDataSource\n'), ((33282, 33344), 'bokeh.plotting.figure', 'figure', ([], {'width': '(300)', 'height': '(100)', 'toolbar_location': 'None', 'tools': '""""""'}), "(width=300, height=100, toolbar_location=None, tools='')\n", (33288, 33344), False, 'from bokeh.plotting import figure, output_file, ColumnDataSource\n'), ((33877, 33939), 'bokeh.plotting.figure', 'figure', ([], {'width': '(276)', 'height': '(100)', 'toolbar_location': 'None', 'tools': '""""""'}), "(width=276, height=100, toolbar_location=None, tools='')\n", (33883, 33939), False, 'from bokeh.plotting import figure, output_file, ColumnDataSource\n'), ((34912, 34973), 'bokeh.layouts.Column', 'Column', (['row0', 'row1', 'row2', 'row2b', 'row3', 'mass_match_and_comment'], {}), '(row0, row1, row2, row2b, row3, mass_match_and_comment)\n', (34918, 34973), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((35104, 35190), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '"""<b> This is an empty panel for the 4k plot. </b>"""', 'width': '(300)', 'height': '(70)'}), "(text='<b> This is an empty panel for the 4k plot. </b>', width=300,\n height=70)\n", (35107, 35190), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((35200, 35287), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '"""<b> This is an empty panel for the SVG plot. </b>"""', 'width': '(300)', 'height': '(70)'}), "(text='<b> This is an empty panel for the SVG plot. </b>', width=300,\n height=70)\n", (35203, 35287), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((35502, 35511), 'bokeh.io.show', 'show', (['tab'], {}), '(tab)\n', (35506, 35511), False, 'from bokeh.io import show\n'), ((4679, 4767), 'bokeh.models.glyphs.MultiLine', 'MultiLine', ([], {'xs': '"""mz"""', 'ys': '"""Intensity"""', 'line_color': 'series_cols[i_series]', 'name': 'i_series'}), "(xs='mz', ys='Intensity', line_color=series_cols[i_series], name=\n i_series)\n", (4688, 4767), False, 'from bokeh.models.glyphs import MultiLine\n'), ((4791, 4893), 'bokeh.models.glyphs.MultiLine', 'MultiLine', ([], {'xs': '"""mz"""', 'ys': '"""Intensity"""', 'line_color': 'series_cols[i_series]', 'name': 'i_series', 'line_width': '(4)'}), "(xs='mz', ys='Intensity', line_color=series_cols[i_series], name=\n i_series, line_width=4)\n", (4800, 4893), False, 'from bokeh.models.glyphs import MultiLine\n'), ((4918, 5006), 'bokeh.models.glyphs.MultiLine', 'MultiLine', ([], {'xs': '"""mz"""', 'ys': '"""Intensity"""', 'line_color': 'series_cols[i_series]', 'name': 'i_series'}), "(xs='mz', ys='Intensity', line_color=series_cols[i_series], name=\n i_series)\n", (4927, 5006), False, 'from bokeh.models.glyphs import MultiLine\n'), ((5029, 5106), 'bokeh.models.glyphs.MultiLine', 'MultiLine', ([], {'xs': '"""xs"""', 'ys': '"""ys"""', 'line_color': 'series_cols[i_series]', 'line_alpha': '(0.5)'}), "(xs='xs', ys='ys', line_color=series_cols[i_series], line_alpha=0.5)\n", (5038, 5106), False, 'from bokeh.models.glyphs import MultiLine\n'), ((5136, 5231), 'bokeh.models.glyphs.MultiLine', 'MultiLine', ([], {'xs': '"""xs"""', 'ys': '"""ys"""', 'line_color': 'series_cols[i_series]', 'line_width': '(4)', 'line_alpha': '(0.5)'}), "(xs='xs', ys='ys', line_color=series_cols[i_series], line_width=4,\n line_alpha=0.5)\n", (5145, 5231), False, 'from bokeh.models.glyphs import MultiLine\n'), ((5258, 5335), 'bokeh.models.glyphs.MultiLine', 'MultiLine', ([], {'xs': '"""xs"""', 'ys': '"""ys"""', 'line_color': 'series_cols[i_series]', 'line_alpha': '(0.5)'}), "(xs='xs', ys='ys', line_color=series_cols[i_series], line_alpha=0.5)\n", (5267, 5335), False, 'from bokeh.models.glyphs import MultiLine\n'), ((10834, 11206), 'bokeh.util.compiler.JavaScript', 'JavaScript', (['"""\n \n import {TapTool} from "models/tools";\n \n export class DQTapTool extends TapTool {\n static __name__ = \'DQTapTool\'\n get tooltip() {\n return \'Correct Peak. \\\\n (Tap on data point to set value for mass calculation of respective to tapped m/z.)\';\n }\n } \n """'], {}), '(\n """\n \n import {TapTool} from "models/tools";\n \n export class DQTapTool extends TapTool {\n static __name__ = \'DQTapTool\'\n get tooltip() {\n return \'Correct Peak. \\\\n (Tap on data point to set value for mass calculation of respective to tapped m/z.)\';\n }\n } \n """\n )\n', (10844, 11206), False, 'from bokeh.util.compiler import JavaScript\n'), ((11293, 11663), 'bokeh.util.compiler.JavaScript', 'JavaScript', (['"""\n \n import {BoxSelectTool} from "models/tools";\n \n export class RenamedBoxSelectTool extends BoxSelectTool {\n static __name__ = \'RenamedBoxSelectTool\'\n get tooltip() {\n return \'Mark Peak \\\\n (Press left mouse button and hold to select range.)\';\n }\n } \n """'], {}), '(\n """\n \n import {BoxSelectTool} from "models/tools";\n \n export class RenamedBoxSelectTool extends BoxSelectTool {\n static __name__ = \'RenamedBoxSelectTool\'\n get tooltip() {\n return \'Mark Peak \\\\n (Press left mouse button and hold to select range.)\';\n }\n } \n """\n )\n', (11303, 11663), False, 'from bokeh.util.compiler import JavaScript\n'), ((13369, 13412), 'bokeh.models.widgets.TableColumn', 'TableColumn', ([], {'field': '"""charge"""', 'title': '"""Charge"""'}), "(field='charge', title='Charge')\n", (13380, 13412), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((14603, 14678), 'bokeh.models.widgets.TableColumn', 'TableColumn', ([], {'field': '"""Colour"""', 'title': '"""Colour"""', 'formatter': 'formatter', 'width': '(120)'}), "(field='Colour', title='Colour', formatter=formatter, width=120)\n", (14614, 14678), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((14688, 14731), 'bokeh.models.widgets.TableColumn', 'TableColumn', ([], {'field': '"""Series"""', 'title': '"""Series"""'}), "(field='Series', title='Series')\n", (14699, 14731), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((15219, 15272), 'bokeh.models.widgets.TableColumn', 'TableColumn', ([], {'field': '"""name"""', 'title': '"""Subunit"""', 'width': '(250)'}), "(field='name', title='Subunit', width=250)\n", (15230, 15272), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((16703, 16760), 'bokeh.models.widgets.TableColumn', 'TableColumn', ([], {'field': '"""stoichiometry"""', 'title': '"""Stoichiometry"""'}), "(field='stoichiometry', title='Stoichiometry')\n", (16714, 16760), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((20367, 20428), 'bokeh.layouts.Row', 'Row', (['mass_finder_exact_mass_text', 'mass_finder_exact_mass_sele'], {}), '(mass_finder_exact_mass_text, mass_finder_exact_mass_sele)\n', (20370, 20428), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((20429, 20478), 'bokeh.layouts.Row', 'Row', (['mass_finder_line_text', 'mass_finder_line_sele'], {}), '(mass_finder_line_text, mass_finder_line_sele)\n', (20432, 20478), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((24853, 25072), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '"""Note: 4K/SVG figure creation on Safari on MacOS is slow and might crash. Please save high-resolution PNG figures in a different browser. SVG creation takes a few seconds.\n"""', 'width': '(300)', 'height': '(70)'}), '(text=\n """Note: 4K/SVG figure creation on Safari on MacOS is slow and might crash. Please save high-resolution PNG figures in a different browser. SVG creation takes a few seconds.\n"""\n , width=300, height=70)\n', (24856, 25072), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((27410, 27431), 'bokeh.layouts.Row', 'Row', (['dt_names', 'dt_inp'], {}), '(dt_names, dt_inp)\n', (27413, 27431), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((28995, 29019), 'bokeh.layouts.Row', 'Row', (['save4k_text', 'save4k'], {}), '(save4k_text, save4k)\n', (28998, 29019), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((29021, 29047), 'bokeh.layouts.Row', 'Row', (['savesvg_text', 'savesvg'], {}), '(savesvg_text, savesvg)\n', (29024, 29047), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((29085, 29111), 'bokeh.layouts.Row', 'Row', (['set_spacer', 'set_range'], {}), '(set_spacer, set_range)\n', (29088, 29111), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((31807, 31859), 'bokeh.layouts.Column', 'Column', (['mass_finder_column', 'data_tools', 'graph_layout'], {}), '(mass_finder_column, data_tools, graph_layout)\n', (31813, 31859), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((32247, 32264), 'bokeh.layouts.Spacer', 'Spacer', ([], {'height': '(30)'}), '(height=30)\n', (32253, 32264), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((32322, 32339), 'bokeh.layouts.Spacer', 'Spacer', ([], {'height': '(30)'}), '(height=30)\n', (32328, 32339), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((32364, 32381), 'bokeh.layouts.Spacer', 'Spacer', ([], {'height': '(10)'}), '(height=10)\n', (32370, 32381), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((32383, 32405), 'bokeh.layouts.Row', 'Row', (['mass_match_button'], {}), '(mass_match_button)\n', (32386, 32405), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((34496, 34513), 'bokeh.layouts.Spacer', 'Spacer', ([], {'width': '(160)'}), '(width=160)\n', (34502, 34513), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((34515, 34670), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '"""<h> <b>Na</b>tive <b>Vi</b>sual <b>A</b>nalyser </h>"""', 'width': '(596)', 'height': '(70)', 'style': "{'font-size': '42px', 'color': '#002147'}", 'align': '"""center"""'}), "(text='<h> <b>Na</b>tive <b>Vi</b>sual <b>A</b>nalyser </h>', width=596,\n height=70, style={'font-size': '42px', 'color': '#002147'}, align='center')\n", (34518, 34670), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((34706, 34778), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <h2>Peaks of Active Series (m/z)</h2>"""', 'width': '(580)', 'height': '(35)'}), "(text=' <h2>Peaks of Active Series (m/z)</h2>', width=580, height=35)\n", (34709, 34778), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((34782, 34832), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <h2>Masses</h2>"""', 'width': '(370)', 'height': '(35)'}), "(text=' <h2>Masses</h2>', width=370, height=35)\n", (34785, 34832), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((34837, 34898), 'bokeh.models.widgets.Div', 'Div', ([], {'text': '""" <h2>Notes on Spectrum</h2>"""', 'width': '(280)', 'height': '(35)'}), "(text=' <h2>Notes on Spectrum</h2>', width=280, height=35)\n", (34840, 34898), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((32460, 32485), 'bokeh.layouts.Row', 'Row', (['SU_header', 'MM_header'], {}), '(SU_header, MM_header)\n', (32463, 32485), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((32487, 32540), 'bokeh.layouts.Row', 'Row', (['complex_table', 'SU_column', 'match_table', 'MM_column'], {}), '(complex_table, SU_column, match_table, MM_column)\n', (32490, 32540), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((32666, 32677), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (32675, 32677), False, 'import os\n'), ((32884, 32895), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (32893, 32895), False, 'import os\n'), ((13016, 13048), 'bokeh.models.widgets.NumberFormatter', 'NumberFormatter', ([], {'format': '"""0,0.00"""'}), "(format='0,0.00')\n", (13031, 13048), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((13115, 13147), 'bokeh.models.widgets.NumberFormatter', 'NumberFormatter', ([], {'format': '"""0,0.00"""'}), "(format='0,0.00')\n", (13130, 13147), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((13214, 13246), 'bokeh.models.widgets.NumberFormatter', 'NumberFormatter', ([], {'format': '"""0,0.00"""'}), "(format='0,0.00')\n", (13229, 13246), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((13326, 13358), 'bokeh.models.widgets.NumberFormatter', 'NumberFormatter', ([], {'format': '"""0,0.00"""'}), "(format='0,0.00')\n", (13341, 13358), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((14791, 14823), 'bokeh.models.widgets.NumberFormatter', 'NumberFormatter', ([], {'format': '"""0,0.00"""'}), "(format='0,0.00')\n", (14806, 14823), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((14898, 14930), 'bokeh.models.widgets.NumberFormatter', 'NumberFormatter', ([], {'format': '"""0,0.00"""'}), "(format='0,0.00')\n", (14913, 14930), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((15332, 15364), 'bokeh.models.widgets.NumberFormatter', 'NumberFormatter', ([], {'format': '"""0,0.00"""'}), "(format='0,0.00')\n", (15347, 15364), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((15437, 15466), 'bokeh.models.widgets.NumberFormatter', 'NumberFormatter', ([], {'format': '"""0,0"""'}), "(format='0,0')\n", (15452, 15466), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((15538, 15567), 'bokeh.models.widgets.NumberFormatter', 'NumberFormatter', ([], {'format': '"""0,0"""'}), "(format='0,0')\n", (15553, 15567), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((15642, 15671), 'bokeh.models.widgets.NumberFormatter', 'NumberFormatter', ([], {'format': '"""0,0"""'}), "(format='0,0')\n", (15657, 15671), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((16835, 16867), 'bokeh.models.widgets.NumberFormatter', 'NumberFormatter', ([], {'format': '"""0,0.00"""'}), "(format='0,0.00')\n", (16850, 16867), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((16956, 16988), 'bokeh.models.widgets.NumberFormatter', 'NumberFormatter', ([], {'format': '"""0,0.00"""'}), "(format='0,0.00')\n", (16971, 16988), False, 'from bokeh.models.widgets import ColorPicker, Select, Toggle, Dropdown, DataTable, NumberFormatter, TableColumn, TextInput, Button, TextAreaInput, Slider, Div, RangeSlider, HTMLTemplateFormatter\n'), ((35307, 35340), 'bokeh.models.Panel', 'Panel', ([], {'child': 'layout', 'title': '"""Plot"""'}), "(child=layout, title='Plot')\n", (35312, 35340), False, 'from bokeh.models import HoverTool, CustomJS, BoxSelectTool, Panel, Tabs, Span, AjaxDataSource, ToolbarBox, Toolbar, Legend, LegendItem, PanTool, TapTool\n'), ((2217, 2233), 'numpy.floor', 'np.floor', (['(i / 10)'], {}), '(i / 10)\n', (2225, 2233), True, 'import numpy as np\n'), ((35358, 35394), 'bokeh.layouts.Column', 'Column', (['highres_text', 'highres_canvas'], {}), '(highres_text, highres_canvas)\n', (35364, 35394), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((35429, 35457), 'bokeh.layouts.Column', 'Column', (['svg_text', 'svg_canvas'], {}), '(svg_text, svg_canvas)\n', (35435, 35457), False, 'from bokeh.layouts import Column, Row, gridplot, Spacer\n'), ((8707, 8718), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (8716, 8718), False, 'import os\n'), ((15949, 15960), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (15958, 15960), False, 'import os\n'), ((16072, 16083), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (16081, 16083), False, 'import os\n'), ((17388, 17399), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (17397, 17399), False, 'import os\n'), ((19879, 19890), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (19888, 19890), False, 'import os\n'), ((20140, 20151), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (20149, 20151), False, 'import os\n'), ((21720, 21731), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (21729, 21731), False, 'import os\n'), ((28699, 28710), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (28708, 28710), False, 'import os\n'), ((29522, 29533), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (29531, 29533), False, 'import os\n'), ((29919, 29930), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (29928, 29930), False, 'import os\n'), ((30392, 30403), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (30401, 30403), False, 'import os\n'), ((6850, 6861), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (6859, 6861), False, 'import os\n'), ((6929, 6940), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (6938, 6940), False, 'import os\n'), ((7666, 7677), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (7675, 7677), False, 'import os\n'), ((7745, 7756), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (7754, 7756), False, 'import os\n'), ((9464, 9475), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (9473, 9475), False, 'import os\n'), ((9563, 9574), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (9572, 9574), False, 'import os\n'), ((10013, 10024), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (10022, 10024), False, 'import os\n'), ((10112, 10123), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (10121, 10123), False, 'import os\n'), ((10563, 10574), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (10572, 10574), False, 'import os\n'), ((10662, 10673), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (10671, 10673), False, 'import os\n'), ((22354, 22365), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (22363, 22365), False, 'import os\n'), ((22433, 22444), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (22442, 22444), False, 'import os\n'), ((22846, 22857), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (22855, 22857), False, 'import os\n'), ((22925, 22936), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (22934, 22936), False, 'import os\n'), ((31403, 31414), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (31412, 31414), False, 'import os\n'), ((31482, 31493), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (31491, 31493), False, 'import os\n')]
import netket as nk import numpy as np from numpy import linalg as la import pandas as pd import os from netket.hilbert import Fock from tqdm import tqdm # Model params model = 'mbl' N = 8 seed = 3 W = 15.0 U = 1.0 J = 1.0 dt = 1 gamma = 0.1 # Ansatz params beta = 2 alpha = 2 n_samples = 5000 n_iter = 1000 np.random.seed(seed) cpp_path = f"/media/sf_Work/dl/netket/{model}/test/cpp" save_path = f"/media/sf_Work/dl/netket/{model}/N({N})_rnd({seed})_H({W:0.4f}_{U:0.4f}_{J:0.4f})_D({dt}_{gamma:0.4f})" if not os.path.exists(f"{save_path}"): os.makedirs(f"{save_path}") energies = np.random.uniform(-1.0, 1.0, N) # Hilbert space hi = Fock(n_max=1, n_particles=N//2, N=N) # The Hamiltonian ha = nk.operator.LocalOperator(hi) # List of dissipative jump operators j_ops = [] for boson_id in range(N - 1): ha += W * energies[boson_id] * nk.operator.boson.number(hi, boson_id) ha += U * nk.operator.boson.number(hi, boson_id) * nk.operator.boson.number(hi, boson_id + 1) ha -= J * (nk.operator.boson.create(hi, boson_id) * nk.operator.boson.destroy(hi, boson_id + 1) + nk.operator.boson.create(hi, boson_id + 1) * nk.operator.boson.destroy(hi, boson_id)) if dt == 1: A = (nk.operator.boson.create(hi, boson_id + 1) + nk.operator.boson.create(hi, boson_id)) * (nk.operator.boson.destroy(hi, boson_id + 1) - nk.operator.boson.destroy(hi, boson_id)) elif dt == 0: A = nk.operator.boson.create(hi, boson_id) * nk.operator.boson.destroy(hi, boson_id) j_ops.append(np.sqrt(gamma) * A) ha += W * energies[N - 1] * nk.operator.boson.number(hi, N - 1) if dt == 0: A = nk.operator.boson.create(hi, N - 1) * nk.operator.boson.destroy(hi, N - 1) j_ops.append(np.sqrt(gamma) * A) # Create the Liouvillian lind = nk.operator.LocalLiouvillian(ha, j_ops) # Neural quantum state model: Positive-Definite Neural Density Matrix using the ansatz from Torlai and Melko ndm = nk.models.NDM( alpha=alpha, beta=beta, ) # Metropolis Sampling graph = nk.graph.Hypercube(N, n_dim=1, pbc=False) sa_graph = nk.graph.disjoint_union(graph, graph) sa = nk.sampler.MetropolisExchange(lind.hilbert, graph=sa_graph) # Optimizer op = nk.optimizer.Sgd(0.01) sr = nk.optimizer.SR(diag_shift=0.01) # Variational state vs = nk.vqs.MCMixedState(sa, ndm, n_samples=n_samples) vs.init_parameters(nk.nn.initializers.normal(stddev=0.01)) # Driver ss = nk.SteadyState(lind, op, variational_state=vs, preconditioner=sr) metrics_dict = { 'iteration': np.linspace(1, n_iter, n_iter), 'ldagl_mean': [], 'ldagl_error_of_mean': [], 'norm_rho_diff': [], 'norm_rho_diff_conj': [] } # Calculate exact rho rho_exact = nk.exact.steady_state(lind, method="iterative", sparse=True, tol=1e-10) for it in tqdm(range(n_iter)): out = ss.run(n_iter=1) metrics_dict['ldagl_mean'].append(ss.ldagl.mean) metrics_dict['ldagl_error_of_mean'].append(ss.ldagl.error_of_mean) rho_neural = np.array(ss.state.to_matrix()) rho_diff = rho_exact - rho_neural rho_diff_conj = rho_exact - rho_neural.conjugate() metrics_dict['norm_rho_diff'].append(la.norm(rho_diff)) metrics_dict['norm_rho_diff_conj'].append(la.norm(rho_diff_conj)) metrics_df = pd.DataFrame(metrics_dict) metrics_df.to_excel(f"{save_path}/NDM({alpha}_{beta}_{n_samples}_{n_iter}).xlsx", index=False)
[ "netket.operator.LocalOperator", "numpy.sqrt", "netket.optimizer.Sgd", "netket.models.NDM", "numpy.linalg.norm", "os.path.exists", "netket.graph.disjoint_union", "netket.optimizer.SR", "netket.operator.boson.number", "netket.operator.LocalLiouvillian", "netket.operator.boson.create", "numpy.li...
[((311, 331), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (325, 331), True, 'import numpy as np\n'), ((590, 621), 'numpy.random.uniform', 'np.random.uniform', (['(-1.0)', '(1.0)', 'N'], {}), '(-1.0, 1.0, N)\n', (607, 621), True, 'import numpy as np\n'), ((644, 682), 'netket.hilbert.Fock', 'Fock', ([], {'n_max': '(1)', 'n_particles': '(N // 2)', 'N': 'N'}), '(n_max=1, n_particles=N // 2, N=N)\n', (648, 682), False, 'from netket.hilbert import Fock\n'), ((705, 734), 'netket.operator.LocalOperator', 'nk.operator.LocalOperator', (['hi'], {}), '(hi)\n', (730, 734), True, 'import netket as nk\n'), ((1756, 1795), 'netket.operator.LocalLiouvillian', 'nk.operator.LocalLiouvillian', (['ha', 'j_ops'], {}), '(ha, j_ops)\n', (1784, 1795), True, 'import netket as nk\n'), ((1912, 1949), 'netket.models.NDM', 'nk.models.NDM', ([], {'alpha': 'alpha', 'beta': 'beta'}), '(alpha=alpha, beta=beta)\n', (1925, 1949), True, 'import netket as nk\n'), ((1992, 2033), 'netket.graph.Hypercube', 'nk.graph.Hypercube', (['N'], {'n_dim': '(1)', 'pbc': '(False)'}), '(N, n_dim=1, pbc=False)\n', (2010, 2033), True, 'import netket as nk\n'), ((2045, 2082), 'netket.graph.disjoint_union', 'nk.graph.disjoint_union', (['graph', 'graph'], {}), '(graph, graph)\n', (2068, 2082), True, 'import netket as nk\n'), ((2088, 2147), 'netket.sampler.MetropolisExchange', 'nk.sampler.MetropolisExchange', (['lind.hilbert'], {'graph': 'sa_graph'}), '(lind.hilbert, graph=sa_graph)\n', (2117, 2147), True, 'import netket as nk\n'), ((2166, 2188), 'netket.optimizer.Sgd', 'nk.optimizer.Sgd', (['(0.01)'], {}), '(0.01)\n', (2182, 2188), True, 'import netket as nk\n'), ((2194, 2226), 'netket.optimizer.SR', 'nk.optimizer.SR', ([], {'diag_shift': '(0.01)'}), '(diag_shift=0.01)\n', (2209, 2226), True, 'import netket as nk\n'), ((2253, 2302), 'netket.vqs.MCMixedState', 'nk.vqs.MCMixedState', (['sa', 'ndm'], {'n_samples': 'n_samples'}), '(sa, ndm, n_samples=n_samples)\n', (2272, 2302), True, 'import netket as nk\n'), ((2377, 2442), 'netket.SteadyState', 'nk.SteadyState', (['lind', 'op'], {'variational_state': 'vs', 'preconditioner': 'sr'}), '(lind, op, variational_state=vs, preconditioner=sr)\n', (2391, 2442), True, 'import netket as nk\n'), ((2654, 2725), 'netket.exact.steady_state', 'nk.exact.steady_state', (['lind'], {'method': '"""iterative"""', 'sparse': '(True)', 'tol': '(1e-10)'}), "(lind, method='iterative', sparse=True, tol=1e-10)\n", (2675, 2725), True, 'import netket as nk\n'), ((3194, 3220), 'pandas.DataFrame', 'pd.DataFrame', (['metrics_dict'], {}), '(metrics_dict)\n', (3206, 3220), True, 'import pandas as pd\n'), ((514, 544), 'os.path.exists', 'os.path.exists', (['f"""{save_path}"""'], {}), "(f'{save_path}')\n", (528, 544), False, 'import os\n'), ((550, 577), 'os.makedirs', 'os.makedirs', (['f"""{save_path}"""'], {}), "(f'{save_path}')\n", (561, 577), False, 'import os\n'), ((1555, 1590), 'netket.operator.boson.number', 'nk.operator.boson.number', (['hi', '(N - 1)'], {}), '(hi, N - 1)\n', (1579, 1590), True, 'import netket as nk\n'), ((2322, 2360), 'netket.nn.initializers.normal', 'nk.nn.initializers.normal', ([], {'stddev': '(0.01)'}), '(stddev=0.01)\n', (2347, 2360), True, 'import netket as nk\n'), ((2478, 2508), 'numpy.linspace', 'np.linspace', (['(1)', 'n_iter', 'n_iter'], {}), '(1, n_iter, n_iter)\n', (2489, 2508), True, 'import numpy as np\n'), ((850, 888), 'netket.operator.boson.number', 'nk.operator.boson.number', (['hi', 'boson_id'], {}), '(hi, boson_id)\n', (874, 888), True, 'import netket as nk\n'), ((944, 986), 'netket.operator.boson.number', 'nk.operator.boson.number', (['hi', '(boson_id + 1)'], {}), '(hi, boson_id + 1)\n', (968, 986), True, 'import netket as nk\n'), ((1611, 1646), 'netket.operator.boson.create', 'nk.operator.boson.create', (['hi', '(N - 1)'], {}), '(hi, N - 1)\n', (1635, 1646), True, 'import netket as nk\n'), ((1649, 1685), 'netket.operator.boson.destroy', 'nk.operator.boson.destroy', (['hi', '(N - 1)'], {}), '(hi, N - 1)\n', (1674, 1685), True, 'import netket as nk\n'), ((3091, 3108), 'numpy.linalg.norm', 'la.norm', (['rho_diff'], {}), '(rho_diff)\n', (3098, 3108), True, 'from numpy import linalg as la\n'), ((3156, 3178), 'numpy.linalg.norm', 'la.norm', (['rho_diff_conj'], {}), '(rho_diff_conj)\n', (3163, 3178), True, 'from numpy import linalg as la\n'), ((903, 941), 'netket.operator.boson.number', 'nk.operator.boson.number', (['hi', 'boson_id'], {}), '(hi, boson_id)\n', (927, 941), True, 'import netket as nk\n'), ((1507, 1521), 'numpy.sqrt', 'np.sqrt', (['gamma'], {}), '(gamma)\n', (1514, 1521), True, 'import numpy as np\n'), ((1703, 1717), 'numpy.sqrt', 'np.sqrt', (['gamma'], {}), '(gamma)\n', (1710, 1717), True, 'import numpy as np\n'), ((1002, 1040), 'netket.operator.boson.create', 'nk.operator.boson.create', (['hi', 'boson_id'], {}), '(hi, boson_id)\n', (1026, 1040), True, 'import netket as nk\n'), ((1043, 1086), 'netket.operator.boson.destroy', 'nk.operator.boson.destroy', (['hi', '(boson_id + 1)'], {}), '(hi, boson_id + 1)\n', (1068, 1086), True, 'import netket as nk\n'), ((1089, 1131), 'netket.operator.boson.create', 'nk.operator.boson.create', (['hi', '(boson_id + 1)'], {}), '(hi, boson_id + 1)\n', (1113, 1131), True, 'import netket as nk\n'), ((1134, 1173), 'netket.operator.boson.destroy', 'nk.operator.boson.destroy', (['hi', 'boson_id'], {}), '(hi, boson_id)\n', (1159, 1173), True, 'import netket as nk\n'), ((1204, 1246), 'netket.operator.boson.create', 'nk.operator.boson.create', (['hi', '(boson_id + 1)'], {}), '(hi, boson_id + 1)\n', (1228, 1246), True, 'import netket as nk\n'), ((1249, 1287), 'netket.operator.boson.create', 'nk.operator.boson.create', (['hi', 'boson_id'], {}), '(hi, boson_id)\n', (1273, 1287), True, 'import netket as nk\n'), ((1292, 1335), 'netket.operator.boson.destroy', 'nk.operator.boson.destroy', (['hi', '(boson_id + 1)'], {}), '(hi, boson_id + 1)\n', (1317, 1335), True, 'import netket as nk\n'), ((1338, 1377), 'netket.operator.boson.destroy', 'nk.operator.boson.destroy', (['hi', 'boson_id'], {}), '(hi, boson_id)\n', (1363, 1377), True, 'import netket as nk\n'), ((1409, 1447), 'netket.operator.boson.create', 'nk.operator.boson.create', (['hi', 'boson_id'], {}), '(hi, boson_id)\n', (1433, 1447), True, 'import netket as nk\n'), ((1450, 1489), 'netket.operator.boson.destroy', 'nk.operator.boson.destroy', (['hi', 'boson_id'], {}), '(hi, boson_id)\n', (1475, 1489), True, 'import netket as nk\n')]
import networkx as nx import numpy as np import matplotlib.pyplot as plt def vis_causal_net(adata, key='RDI', layout = 'circular', top_n_edges = 10, edge_color = 'gray', figsize=(6, 6)): """Visualize inferred causal regulatory network This plotting function visualize the inferred causal regulatory network inferred from Scribe. Arguments --------- adata: `Anndata` Annotated Data Frame, an Anndata object. key: `str` (default: `RDI`) The key points to the type of causal network to be used for network visualization. layout: `str` (Default: circular) A string determines the graph layout function supported by networkx. Currently supported layouts include circular, kamada_kawai, planar, random, spectral, spring and shell. top_n_edges: 'int' (default 10) Number of top strongest causal regulation to visualize. edge_color: `str` (Default: gray) The color for the graph edge. figsize: `tuple` (Default: (6, 6)) The tuple of the figure width and height. Returns ------- A figure created by nx.draw and matplotlib. """ if 'causal_net' not in adata.uns.keys(): raise('causal_net is not a key in uns slot. Please first run causal network inference with Scribe.') df_mat = adata.uns['causal_net'][key] ind_mat = np.where(df_mat.values - df_mat.T.values < 0) tmp = np.where(df_mat.values - df_mat.T.values < 0) for i in range(len(tmp[0])): df_mat.iloc[tmp[0][i], tmp[1][i]] = np.nan df_mat = df_mat.stack().reset_index() df_mat.columns = ['source', 'target', 'weight'] if top_n_edges is not None: ind_vec = np.argsort(-df_mat.loc[:, 'weight']) df_mat = df_mat.loc[ind_vec[:top_n_edges], :] G = nx.from_pandas_edgelist(df_mat, source='source', target='target', edge_attr='weight', create_using=nx.DiGraph()) G.nodes() W = [] for n, nbrs in G.adj.items(): for nbr, eattr in nbrs.items(): W.append(eattr['weight']) options = { 'width': 300, 'arrowstyle': '-|>', 'arrowsize': 1000, } plt.figure(figsize=figsize) if layout is None: nx.draw(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options = options) elif layout is "circular": nx.draw_circular(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options = options) elif layout is "kamada_kawai": nx.draw_kamada_kawai(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options = options) elif layout is "planar": nx.draw_planar(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options = options) elif layout is "random": nx.draw_random(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options = options) elif layout is "spectral": nx.draw_spectral(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options = options) elif layout is "spring": nx.draw_spring(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options = options) elif layout is "shell": nx.draw_shell(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options = options) else: raise('layout', layout, ' is not supported.') plt.show()
[ "numpy.where", "networkx.DiGraph", "numpy.max", "numpy.argsort", "matplotlib.pyplot.figure", "matplotlib.pyplot.show" ]
[((1402, 1447), 'numpy.where', 'np.where', (['(df_mat.values - df_mat.T.values < 0)'], {}), '(df_mat.values - df_mat.T.values < 0)\n', (1410, 1447), True, 'import numpy as np\n'), ((1459, 1504), 'numpy.where', 'np.where', (['(df_mat.values - df_mat.T.values < 0)'], {}), '(df_mat.values - df_mat.T.values < 0)\n', (1467, 1504), True, 'import numpy as np\n'), ((2181, 2208), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (2191, 2208), True, 'import matplotlib.pyplot as plt\n'), ((3891, 3901), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3899, 3901), True, 'import matplotlib.pyplot as plt\n'), ((1736, 1772), 'numpy.argsort', 'np.argsort', (["(-df_mat.loc[:, 'weight'])"], {}), "(-df_mat.loc[:, 'weight'])\n", (1746, 1772), True, 'import numpy as np\n'), ((1935, 1947), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (1945, 1947), True, 'import networkx as nx\n'), ((2339, 2348), 'numpy.max', 'np.max', (['W'], {}), '(W)\n', (2345, 2348), True, 'import numpy as np\n'), ((2544, 2553), 'numpy.max', 'np.max', (['W'], {}), '(W)\n', (2550, 2553), True, 'import numpy as np\n'), ((2757, 2766), 'numpy.max', 'np.max', (['W'], {}), '(W)\n', (2763, 2766), True, 'import numpy as np\n'), ((2958, 2967), 'numpy.max', 'np.max', (['W'], {}), '(W)\n', (2964, 2967), True, 'import numpy as np\n'), ((3159, 3168), 'numpy.max', 'np.max', (['W'], {}), '(W)\n', (3165, 3168), True, 'import numpy as np\n'), ((3364, 3373), 'numpy.max', 'np.max', (['W'], {}), '(W)\n', (3370, 3373), True, 'import numpy as np\n'), ((3565, 3574), 'numpy.max', 'np.max', (['W'], {}), '(W)\n', (3571, 3574), True, 'import numpy as np\n'), ((3764, 3773), 'numpy.max', 'np.max', (['W'], {}), '(W)\n', (3770, 3773), True, 'import numpy as np\n')]
from collections import namedtuple import numpy as np import pytest from numpy.testing import assert_allclose from pytest_lazyfixture import lazy_fixture from emukit.quadrature.methods.warpings import IdentityWarping, SquareRootWarping def create_fixture_parameters(): return [pytest.param(lazy_fixture(warping.name), id=warping.name) for warping in warpings] @pytest.fixture def identity_warping(): return IdentityWarping() @pytest.fixture def squarerroot_warping(): offset = 1.0 return SquareRootWarping(offset=offset) @pytest.fixture def inverted_squarerroot_warping(): offset = 1.0 return SquareRootWarping(offset=offset, is_inverted=True) warpings_tuple = namedtuple("WarpingTest", ["name"]) warpings = [ warpings_tuple("identity_warping"), warpings_tuple("squarerroot_warping"), warpings_tuple("inverted_squarerroot_warping"), ] RTOL = 1e-8 ATOL = 1e-6 @pytest.mark.parametrize("warping", create_fixture_parameters()) def test_warping_shapes(warping): Y = np.ones([5, 1]) assert warping.transform(Y).shape == Y.shape assert warping.inverse_transform(Y).shape == Y.shape @pytest.mark.parametrize("warping", create_fixture_parameters()) def test_warping_values(warping): np.random.seed(42) Y = np.random.rand(5, 1) assert_allclose(warping.inverse_transform(warping.transform(Y)), Y, rtol=RTOL, atol=ATOL) def test_squarerroot_warping_update_parameters(squarerroot_warping, inverted_squarerroot_warping): new_offset = 10.0 squarerroot_warping.update_parameters(offset=new_offset) assert squarerroot_warping.offset == new_offset inverted_squarerroot_warping.update_parameters(offset=new_offset) assert inverted_squarerroot_warping.offset == new_offset def test_squarerroot_warping_inverted_flag(squarerroot_warping, inverted_squarerroot_warping): assert not squarerroot_warping.is_inverted assert inverted_squarerroot_warping.is_inverted
[ "collections.namedtuple", "numpy.ones", "numpy.random.rand", "emukit.quadrature.methods.warpings.IdentityWarping", "emukit.quadrature.methods.warpings.SquareRootWarping", "pytest_lazyfixture.lazy_fixture", "numpy.random.seed" ]
[((697, 732), 'collections.namedtuple', 'namedtuple', (['"""WarpingTest"""', "['name']"], {}), "('WarpingTest', ['name'])\n", (707, 732), False, 'from collections import namedtuple\n'), ((421, 438), 'emukit.quadrature.methods.warpings.IdentityWarping', 'IdentityWarping', ([], {}), '()\n', (436, 438), False, 'from emukit.quadrature.methods.warpings import IdentityWarping, SquareRootWarping\n'), ((512, 544), 'emukit.quadrature.methods.warpings.SquareRootWarping', 'SquareRootWarping', ([], {'offset': 'offset'}), '(offset=offset)\n', (529, 544), False, 'from emukit.quadrature.methods.warpings import IdentityWarping, SquareRootWarping\n'), ((627, 677), 'emukit.quadrature.methods.warpings.SquareRootWarping', 'SquareRootWarping', ([], {'offset': 'offset', 'is_inverted': '(True)'}), '(offset=offset, is_inverted=True)\n', (644, 677), False, 'from emukit.quadrature.methods.warpings import IdentityWarping, SquareRootWarping\n'), ((1018, 1033), 'numpy.ones', 'np.ones', (['[5, 1]'], {}), '([5, 1])\n', (1025, 1033), True, 'import numpy as np\n'), ((1245, 1263), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (1259, 1263), True, 'import numpy as np\n'), ((1272, 1292), 'numpy.random.rand', 'np.random.rand', (['(5)', '(1)'], {}), '(5, 1)\n', (1286, 1292), True, 'import numpy as np\n'), ((298, 324), 'pytest_lazyfixture.lazy_fixture', 'lazy_fixture', (['warping.name'], {}), '(warping.name)\n', (310, 324), False, 'from pytest_lazyfixture import lazy_fixture\n')]
import numpy as np from molsysmt import puw def atomic_radius(molecular_system, selection='all', type='vdw'): from molsysmt.basic import get from molsysmt.physico_chemical_properties.atoms.radius import units from molsysmt._private_tools._digestion import digest_target if type=='vdw': from molsysmt.physico_chemical_properties.atoms.radius import vdw as values else: raise NotImplementedError() atom_types = get(molecular_system, target='atom', selection=selection, type=True) output = [] for ii in atom_types: var_aux = values[ii.capitalize()] output.append(var_aux) output = puw.quantity(np.array(output), units) return output
[ "molsysmt.basic.get", "numpy.array" ]
[((454, 522), 'molsysmt.basic.get', 'get', (['molecular_system'], {'target': '"""atom"""', 'selection': 'selection', 'type': '(True)'}), "(molecular_system, target='atom', selection=selection, type=True)\n", (457, 522), False, 'from molsysmt.basic import get\n'), ((667, 683), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (675, 683), True, 'import numpy as np\n')]
import numpy as np import sys from sklearn.metrics import label_ranking_average_precision_score if len(sys.argv) != 4: print("Usage: python compute_lrap.py preds_file test_file all_class_file") exit(-1) preds_file = sys.argv[1] test_file = sys.argv[2] all_class_file = sys.argv[3] class2index = {} with open(all_class_file) as fin: for line in fin: class2index[line.strip()] = len(class2index) y_score = np.loadtxt(preds_file) y_true = np.zeros(y_score.shape) i = 0 with open(test_file) as fin: for line in fin: for c in line.strip().split("\t"): y_true[i, class2index[c]] = 1 i += 1 lrap = label_ranking_average_precision_score(y_true, y_score) print("lrap of {}: {}".format(preds_file, lrap))
[ "numpy.loadtxt", "sklearn.metrics.label_ranking_average_precision_score", "numpy.zeros" ]
[((437, 459), 'numpy.loadtxt', 'np.loadtxt', (['preds_file'], {}), '(preds_file)\n', (447, 459), True, 'import numpy as np\n'), ((469, 492), 'numpy.zeros', 'np.zeros', (['y_score.shape'], {}), '(y_score.shape)\n', (477, 492), True, 'import numpy as np\n'), ((659, 713), 'sklearn.metrics.label_ranking_average_precision_score', 'label_ranking_average_precision_score', (['y_true', 'y_score'], {}), '(y_true, y_score)\n', (696, 713), False, 'from sklearn.metrics import label_ranking_average_precision_score\n')]
# coding: utf-8 # See notebook: # https://github.com/paninski-lab/yass-examples/blob/master/batch/multi_channel_apply_memory.ipynb """ Applying transformations to large files in batches: BatchProcessor.multi_channel_apply lets you apply transformations to batches of data where every batch has observations from every channel. This example show how to extract information from a large file by processing it in batches. """ import logging import os import numpy as np from yass.batch import BatchProcessor # configure logging to get information about the process logging.basicConfig(level=logging.INFO) # raw data file path_to_neuropixel_data = (os.path.expanduser('~/data/ucl-neuropixel' '/rawDataSample.bin')) # on each batch, we find the maximum value in every channel def max_in_channel(batch): """Add one to every element in the batch """ return np.max(batch, axis=0) # create batch processor for the data bp = BatchProcessor(path_to_neuropixel_data, dtype='int16', n_channels=385, data_format='wide', max_memory='10MB') # appply a multi channel transformation, each batch will be a temporal # subset with observations from all selected n_channels, the size # of the subset is calculated depending on max_memory. Results # from every batch are returned in a list res = bp.multi_channel_apply(max_in_channel, mode='memory', channels=[0, 1, 2]) # we have one element per batch len(res) # output for the first batch res[0] # stack results from every batch arr = np.stack(res, axis=0) # let's find the maximum value along every channel in all the dataset np.max(arr, axis=0)
[ "logging.basicConfig", "yass.batch.BatchProcessor", "numpy.max", "numpy.stack", "os.path.expanduser" ]
[((571, 610), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (590, 610), False, 'import logging\n'), ((656, 717), 'os.path.expanduser', 'os.path.expanduser', (['"""~/data/ucl-neuropixel/rawDataSample.bin"""'], {}), "('~/data/ucl-neuropixel/rawDataSample.bin')\n", (674, 717), False, 'import os\n'), ((969, 1082), 'yass.batch.BatchProcessor', 'BatchProcessor', (['path_to_neuropixel_data'], {'dtype': '"""int16"""', 'n_channels': '(385)', 'data_format': '"""wide"""', 'max_memory': '"""10MB"""'}), "(path_to_neuropixel_data, dtype='int16', n_channels=385,\n data_format='wide', max_memory='10MB')\n", (983, 1082), False, 'from yass.batch import BatchProcessor\n'), ((1622, 1643), 'numpy.stack', 'np.stack', (['res'], {'axis': '(0)'}), '(res, axis=0)\n', (1630, 1643), True, 'import numpy as np\n'), ((1716, 1735), 'numpy.max', 'np.max', (['arr'], {'axis': '(0)'}), '(arr, axis=0)\n', (1722, 1735), True, 'import numpy as np\n'), ((902, 923), 'numpy.max', 'np.max', (['batch'], {'axis': '(0)'}), '(batch, axis=0)\n', (908, 923), True, 'import numpy as np\n')]
#!/usr/bin/env python # coding=utf-8 ''' @Author: John @Email: <EMAIL> @Date: 2020-06-12 00:50:49 @LastEditor: John LastEditTime: 2021-12-22 14:01:37 @Discription: @Environment: python 3.7.7 ''' '''off-policy ''' import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import random import math import numpy as np class MLP(nn.Module): def __init__(self, state_dim,action_dim,hidden_dim=128): """ 初始化q网络,为全连接网络 state_dim: 输入的特征数即环境的状态维度 action_dim: 输出的动作维度 """ super(MLP, self).__init__() self.fc1 = nn.Linear(state_dim, hidden_dim) # 输入层 self.fc2 = nn.Linear(hidden_dim,hidden_dim) # 隐藏层 self.fc3 = nn.Linear(hidden_dim, action_dim) # 输出层 def forward(self, x): # 各层对应的激活函数 x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) return self.fc3(x) class ReplayBuffer: def __init__(self, capacity): self.capacity = capacity # 经验回放的容量 self.buffer = [] # 缓冲区 self.position = 0 def push(self, state, action, reward, next_state, done): ''' 缓冲区是一个队列,容量超出时去掉开始存入的转移(transition) ''' if len(self.buffer) < self.capacity: self.buffer.append(None) self.buffer[self.position] = (state, action, reward, next_state, done) self.position = (self.position + 1) % self.capacity def sample(self, batch_size): batch = random.sample(self.buffer, batch_size) # 随机采出小批量转移 state, action, reward, next_state, done = zip(*batch) # 解压成状态,动作等 return state, action, reward, next_state, done def __len__(self): ''' 返回当前存储的量 ''' return len(self.buffer) class DQN: def __init__(self, state_dim, action_dim, cfg): self.action_dim = action_dim # 总的动作个数 self.device = cfg.device # 设备,cpu或gpu等 self.gamma = cfg.gamma # 奖励的折扣因子 # e-greedy策略相关参数 self.frame_idx = 0 # 用于epsilon的衰减计数 self.epsilon = lambda frame_idx: cfg.epsilon_end + \ (cfg.epsilon_start - cfg.epsilon_end) * \ math.exp(-1. * frame_idx / cfg.epsilon_decay) self.batch_size = cfg.batch_size self.policy_net = MLP(state_dim, action_dim,hidden_dim=cfg.hidden_dim).to(self.device) self.target_net = MLP(state_dim, action_dim,hidden_dim=cfg.hidden_dim).to(self.device) for target_param, param in zip(self.target_net.parameters(),self.policy_net.parameters()): # 复制参数到目标网路targe_net target_param.data.copy_(param.data) self.optimizer = optim.Adam(self.policy_net.parameters(), lr=cfg.lr) # 优化器 self.memory = ReplayBuffer(cfg.memory_capacity) # 经验回放 def choose_action(self, state): ''' 选择动作 ''' self.frame_idx += 1 if random.random() > self.epsilon(self.frame_idx): with torch.no_grad(): state = torch.tensor([state], device=self.device, dtype=torch.float32) q_values = self.policy_net(state) action = q_values.max(1)[1].item() # 选择Q值最大的动作 else: action = random.randrange(self.action_dim) return action def update(self): if len(self.memory) < self.batch_size: # 当memory中不满足一个批量时,不更新策略 return # 从经验回放中(replay memory)中随机采样一个批量的转移(transition) state_batch, action_batch, reward_batch, next_state_batch, done_batch = self.memory.sample( self.batch_size) # 转为张量 state_batch = torch.tensor(state_batch, device=self.device, dtype=torch.float) action_batch = torch.tensor(action_batch, device=self.device).unsqueeze(1) reward_batch = torch.tensor(reward_batch, device=self.device, dtype=torch.float) next_state_batch = torch.tensor(next_state_batch, device=self.device, dtype=torch.float) done_batch = torch.tensor(np.float32(done_batch), device=self.device) q_values = self.policy_net(state_batch).gather(dim=1, index=action_batch) # 计算当前状态(s_t,a)对应的Q(s_t, a) next_q_values = self.target_net(next_state_batch).max(1)[0].detach() # 计算下一时刻的状态(s_t_,a)对应的Q值 # 计算期望的Q值,对于终止状态,此时done_batch[0]=1, 对应的expected_q_value等于reward expected_q_values = reward_batch + self.gamma * next_q_values * (1-done_batch) loss = nn.MSELoss()(q_values, expected_q_values.unsqueeze(1)) # 计算均方根损失 # 优化更新模型 self.optimizer.zero_grad() loss.backward() for param in self.policy_net.parameters(): # clip防止梯度爆炸 param.grad.data.clamp_(-1, 1) self.optimizer.step() def save(self, path): torch.save(self.target_net.state_dict(), path+'dqn_checkpoint.pth') def load(self, path): self.target_net.load_state_dict(torch.load(path+'dqn_checkpoint.pth')) for target_param, param in zip(self.target_net.parameters(), self.policy_net.parameters()): param.data.copy_(target_param.data)
[ "random.sample", "random.randrange", "torch.load", "torch.tensor", "torch.nn.MSELoss", "torch.nn.Linear", "torch.no_grad", "random.random", "numpy.float32", "math.exp" ]
[((602, 634), 'torch.nn.Linear', 'nn.Linear', (['state_dim', 'hidden_dim'], {}), '(state_dim, hidden_dim)\n', (611, 634), True, 'import torch.nn as nn\n'), ((660, 693), 'torch.nn.Linear', 'nn.Linear', (['hidden_dim', 'hidden_dim'], {}), '(hidden_dim, hidden_dim)\n', (669, 693), True, 'import torch.nn as nn\n'), ((718, 751), 'torch.nn.Linear', 'nn.Linear', (['hidden_dim', 'action_dim'], {}), '(hidden_dim, action_dim)\n', (727, 751), True, 'import torch.nn as nn\n'), ((1464, 1502), 'random.sample', 'random.sample', (['self.buffer', 'batch_size'], {}), '(self.buffer, batch_size)\n', (1477, 1502), False, 'import random\n'), ((3541, 3605), 'torch.tensor', 'torch.tensor', (['state_batch'], {'device': 'self.device', 'dtype': 'torch.float'}), '(state_batch, device=self.device, dtype=torch.float)\n', (3553, 3605), False, 'import torch\n'), ((3714, 3779), 'torch.tensor', 'torch.tensor', (['reward_batch'], {'device': 'self.device', 'dtype': 'torch.float'}), '(reward_batch, device=self.device, dtype=torch.float)\n', (3726, 3779), False, 'import torch\n'), ((3809, 3878), 'torch.tensor', 'torch.tensor', (['next_state_batch'], {'device': 'self.device', 'dtype': 'torch.float'}), '(next_state_batch, device=self.device, dtype=torch.float)\n', (3821, 3878), False, 'import torch\n'), ((2833, 2848), 'random.random', 'random.random', ([], {}), '()\n', (2846, 2848), False, 'import random\n'), ((3150, 3183), 'random.randrange', 'random.randrange', (['self.action_dim'], {}), '(self.action_dim)\n', (3166, 3183), False, 'import random\n'), ((3913, 3935), 'numpy.float32', 'np.float32', (['done_batch'], {}), '(done_batch)\n', (3923, 3935), True, 'import numpy as np\n'), ((4343, 4355), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (4353, 4355), True, 'import torch.nn as nn\n'), ((4795, 4834), 'torch.load', 'torch.load', (["(path + 'dqn_checkpoint.pth')"], {}), "(path + 'dqn_checkpoint.pth')\n", (4805, 4834), False, 'import torch\n'), ((2898, 2913), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2911, 2913), False, 'import torch\n'), ((2939, 3001), 'torch.tensor', 'torch.tensor', (['[state]'], {'device': 'self.device', 'dtype': 'torch.float32'}), '([state], device=self.device, dtype=torch.float32)\n', (2951, 3001), False, 'import torch\n'), ((3629, 3675), 'torch.tensor', 'torch.tensor', (['action_batch'], {'device': 'self.device'}), '(action_batch, device=self.device)\n', (3641, 3675), False, 'import torch\n'), ((2137, 2183), 'math.exp', 'math.exp', (['(-1.0 * frame_idx / cfg.epsilon_decay)'], {}), '(-1.0 * frame_idx / cfg.epsilon_decay)\n', (2145, 2183), False, 'import math\n')]
# Copyright 1999-2021 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import pandas as pd import pytest from mars import opcodes from mars.config import options, option_context from mars.core import OutputType, tile from mars.core.operand import OperandStage from mars.dataframe import eval as mars_eval, cut, to_numeric from mars.dataframe.base import to_gpu, to_cpu, astype from mars.dataframe.core import DATAFRAME_TYPE, SERIES_TYPE, SERIES_CHUNK_TYPE, \ INDEX_TYPE, CATEGORICAL_TYPE, CATEGORICAL_CHUNK_TYPE from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df from mars.dataframe.datasource.series import from_pandas as from_pandas_series from mars.dataframe.datasource.index import from_pandas as from_pandas_index from mars.tensor.core import TENSOR_TYPE def test_to_gpu(): # test dataframe data = pd.DataFrame(np.random.rand(10, 10), index=np.random.randint(-100, 100, size=(10,)), columns=[np.random.bytes(10) for _ in range(10)]) df = from_pandas_df(data) cdf = to_gpu(df) assert df.index_value == cdf.index_value assert df.columns_value == cdf.columns_value assert cdf.op.gpu is True pd.testing.assert_series_equal(df.dtypes, cdf.dtypes) df, cdf = tile(df, cdf) assert df.nsplits == cdf.nsplits assert df.chunks[0].index_value == cdf.chunks[0].index_value assert df.chunks[0].columns_value == cdf.chunks[0].columns_value assert cdf.chunks[0].op.gpu is True pd.testing.assert_series_equal(df.chunks[0].dtypes, cdf.chunks[0].dtypes) assert cdf is to_gpu(cdf) # test series sdata = data.iloc[:, 0] series = from_pandas_series(sdata) cseries = to_gpu(series) assert series.index_value == cseries.index_value assert cseries.op.gpu is True series, cseries = tile(series, cseries) assert series.nsplits == cseries.nsplits assert series.chunks[0].index_value == cseries.chunks[0].index_value assert cseries.chunks[0].op.gpu is True assert cseries is to_gpu(cseries) def test_to_cpu(): data = pd.DataFrame(np.random.rand(10, 10), index=np.random.randint(-100, 100, size=(10,)), columns=[np.random.bytes(10) for _ in range(10)]) df = from_pandas_df(data) cdf = to_gpu(df) df2 = to_cpu(cdf) assert df.index_value == df2.index_value assert df.columns_value == df2.columns_value assert df2.op.gpu is False pd.testing.assert_series_equal(df.dtypes, df2.dtypes) df, df2 = tile(df, df2) assert df.nsplits == df2.nsplits assert df.chunks[0].index_value == df2.chunks[0].index_value assert df.chunks[0].columns_value == df2.chunks[0].columns_value assert df2.chunks[0].op.gpu is False pd.testing.assert_series_equal(df.chunks[0].dtypes, df2.chunks[0].dtypes) assert df2 is to_cpu(df2) def test_rechunk(): raw = pd.DataFrame(np.random.rand(10, 10)) df = from_pandas_df(raw, chunk_size=3) df2 = tile(df.rechunk(4)) assert df2.shape == (10, 10) assert len(df2.chunks) == 9 assert df2.chunks[0].shape == (4, 4) pd.testing.assert_index_equal(df2.chunks[0].index_value.to_pandas(), pd.RangeIndex(4)) pd.testing.assert_index_equal(df2.chunks[0].columns_value.to_pandas(), pd.RangeIndex(4)) pd.testing.assert_series_equal(df2.chunks[0].dtypes, raw.dtypes[:4]) assert df2.chunks[2].shape == (4, 2) pd.testing.assert_index_equal(df2.chunks[2].index_value.to_pandas(), pd.RangeIndex(4)) pd.testing.assert_index_equal(df2.chunks[2].columns_value.to_pandas(), pd.RangeIndex(8, 10)) pd.testing.assert_series_equal(df2.chunks[2].dtypes, raw.dtypes[-2:]) assert df2.chunks[-1].shape == (2, 2) pd.testing.assert_index_equal(df2.chunks[-1].index_value.to_pandas(), pd.RangeIndex(8, 10)) pd.testing.assert_index_equal(df2.chunks[-1].columns_value.to_pandas(), pd.RangeIndex(8, 10)) pd.testing.assert_series_equal(df2.chunks[-1].dtypes, raw.dtypes[-2:]) for c in df2.chunks: assert c.shape[1] == len(c.dtypes) assert len(c.columns_value.to_pandas()) == len(c.dtypes) columns = [np.random.bytes(10) for _ in range(10)] index = np.random.randint(-100, 100, size=(4,)) raw = pd.DataFrame(np.random.rand(4, 10), index=index, columns=columns) df = from_pandas_df(raw, chunk_size=3) df2 = tile(df.rechunk(6)) assert df2.shape == (4, 10) assert len(df2.chunks) == 2 assert df2.chunks[0].shape == (4, 6) pd.testing.assert_index_equal(df2.chunks[0].index_value.to_pandas(), df.index_value.to_pandas()) pd.testing.assert_index_equal(df2.chunks[0].columns_value.to_pandas(), pd.Index(columns[:6])) pd.testing.assert_series_equal(df2.chunks[0].dtypes, raw.dtypes[:6]) assert df2.chunks[1].shape == (4, 4) pd.testing.assert_index_equal(df2.chunks[1].index_value.to_pandas(), df.index_value.to_pandas()) pd.testing.assert_index_equal(df2.chunks[1].columns_value.to_pandas(), pd.Index(columns[6:])) pd.testing.assert_series_equal(df2.chunks[1].dtypes, raw.dtypes[-4:]) for c in df2.chunks: assert c.shape[1] == len(c.dtypes) assert len(c.columns_value.to_pandas()) == len(c.dtypes) # test Series rechunk series = from_pandas_series(pd.Series(np.random.rand(10,)), chunk_size=3) series2 = tile(series.rechunk(4)) assert series2.shape == (10,) assert len(series2.chunks) == 3 pd.testing.assert_index_equal(series2.index_value.to_pandas(), pd.RangeIndex(10)) assert series2.chunk_shape == (3,) assert series2.nsplits == ((4, 4, 2), ) assert series2.chunks[0].shape == (4,) pd.testing.assert_index_equal(series2.chunks[0].index_value.to_pandas(), pd.RangeIndex(4)) assert series2.chunks[1].shape == (4,) pd.testing.assert_index_equal(series2.chunks[1].index_value.to_pandas(), pd.RangeIndex(4, 8)) assert series2.chunks[2].shape == (2,) pd.testing.assert_index_equal(series2.chunks[2].index_value.to_pandas(), pd.RangeIndex(8, 10)) series2 = tile(series.rechunk(1)) assert series2.shape == (10,) assert len(series2.chunks) == 10 pd.testing.assert_index_equal(series2.index_value.to_pandas(), pd.RangeIndex(10)) assert series2.chunk_shape == (10,) assert series2.nsplits == ((1,) * 10, ) assert series2.chunks[0].shape == (1,) pd.testing.assert_index_equal(series2.chunks[0].index_value.to_pandas(), pd.RangeIndex(1)) # no need to rechunk series2 = tile(series.rechunk(3)) series = tile(series) assert series2.chunk_shape == series.chunk_shape assert series2.nsplits == series.nsplits def test_data_frame_apply(): cols = [chr(ord('A') + i) for i in range(10)] df_raw = pd.DataFrame(dict((c, [i ** 2 for i in range(20)]) for c in cols)) old_chunk_store_limit = options.chunk_store_limit try: options.chunk_store_limit = 20 df = from_pandas_df(df_raw, chunk_size=5) def df_func_with_err(v): assert len(v) > 2 return v.sort_values() with pytest.raises(TypeError): df.apply(df_func_with_err) r = df.apply(df_func_with_err, output_type='dataframe', dtypes=df_raw.dtypes) assert r.shape == (np.nan, df.shape[-1]) assert r.op._op_type_ == opcodes.APPLY assert r.op.output_types[0] == OutputType.dataframe assert r.op.elementwise is False r = df.apply('ffill') assert r.op._op_type_ == opcodes.FILL_NA r = tile(df.apply(np.sqrt)) assert all(v == np.dtype('float64') for v in r.dtypes) is True assert r.shape == df.shape assert r.op._op_type_ == opcodes.APPLY assert r.op.output_types[0] == OutputType.dataframe assert r.op.elementwise is True r = tile(df.apply(lambda x: pd.Series([1, 2]))) assert all(v == np.dtype('int64') for v in r.dtypes) is True assert r.shape == (np.nan, df.shape[1]) assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (np.nan, 1) assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE assert r.op.elementwise is False r = tile(df.apply(np.sum, axis='index')) assert np.dtype('int64') == r.dtype assert r.shape == (df.shape[1],) assert r.op.output_types[0] == OutputType.series assert r.chunks[0].shape == (20 // df.shape[0],) assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE assert r.op.elementwise is False r = tile(df.apply(np.sum, axis='columns')) assert np.dtype('int64') == r.dtype assert r.shape == (df.shape[0],) assert r.op.output_types[0] == OutputType.series assert r.chunks[0].shape == (20 // df.shape[1],) assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE assert r.op.elementwise is False r = tile(df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1)) assert all(v == np.dtype('int64') for v in r.dtypes) is True assert r.shape == (df.shape[0], np.nan) assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (20 // df.shape[1], np.nan) assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE assert r.op.elementwise is False r = tile(df.apply(lambda x: [1, 2], axis=1, result_type='expand')) assert all(v == np.dtype('int64') for v in r.dtypes) is True assert r.shape == (df.shape[0], np.nan) assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (20 // df.shape[1], np.nan) assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE assert r.op.elementwise is False r = tile(df.apply(lambda x: list(range(10)), axis=1, result_type='reduce')) assert np.dtype('object') == r.dtype assert r.shape == (df.shape[0],) assert r.op.output_types[0] == OutputType.series assert r.chunks[0].shape == (20 // df.shape[1],) assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE assert r.op.elementwise is False r = tile(df.apply(lambda x: list(range(10)), axis=1, result_type='broadcast')) assert all(v == np.dtype('int64') for v in r.dtypes) is True assert r.shape == (df.shape[0], np.nan) assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (20 // df.shape[1], np.nan) assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE assert r.op.elementwise is False finally: options.chunk_store_limit = old_chunk_store_limit raw = pd.DataFrame({'a': [np.array([1, 2, 3]), np.array([4, 5, 6])]}) df = from_pandas_df(raw) df2 = df.apply(lambda x: x['a'].astype(pd.Series), axis=1, output_type='dataframe', dtypes=pd.Series([np.dtype(float)] * 3)) assert df2.ndim == 2 def test_series_apply(): idxes = [chr(ord('A') + i) for i in range(20)] s_raw = pd.Series([i ** 2 for i in range(20)], index=idxes) series = from_pandas_series(s_raw, chunk_size=5) r = tile(series.apply('add', args=(1,))) assert r.op._op_type_ == opcodes.ADD r = tile(series.apply(np.sqrt)) assert np.dtype('float64') == r.dtype assert r.shape == series.shape assert r.op._op_type_ == opcodes.APPLY assert r.op.output_types[0] == OutputType.series assert r.chunks[0].shape == (5,) assert r.chunks[0].inputs[0].shape == (5,) r = tile(series.apply('sqrt')) assert np.dtype('float64') == r.dtype assert r.shape == series.shape assert r.op._op_type_ == opcodes.APPLY assert r.op.output_types[0] == OutputType.series assert r.chunks[0].shape == (5,) assert r.chunks[0].inputs[0].shape == (5,) r = tile(series.apply(lambda x: [x, x + 1], convert_dtype=False)) assert np.dtype('object') == r.dtype assert r.shape == series.shape assert r.op._op_type_ == opcodes.APPLY assert r.op.output_types[0] == OutputType.series assert r.chunks[0].shape == (5,) assert r.chunks[0].inputs[0].shape == (5,) s_raw2 = pd.Series([np.array([1, 2, 3]), np.array([4, 5, 6])]) series = from_pandas_series(s_raw2) r = series.apply(np.sum) assert r.dtype == np.dtype(object) r = series.apply(lambda x: pd.Series([1]), output_type='dataframe') expected = s_raw2.apply(lambda x: pd.Series([1])) pd.testing.assert_series_equal(r.dtypes, expected.dtypes) dtypes = pd.Series([np.dtype(float)] * 3) r = series.apply(pd.Series, output_type='dataframe', dtypes=dtypes) assert r.ndim == 2 pd.testing.assert_series_equal(r.dtypes, dtypes) assert r.shape == (2, 3) r = series.apply(pd.Series, output_type='dataframe', dtypes=dtypes, index=pd.RangeIndex(2)) assert r.ndim == 2 pd.testing.assert_series_equal(r.dtypes, dtypes) assert r.shape == (2, 3) with pytest.raises(AttributeError, match='abc'): series.apply('abc') with pytest.raises(TypeError): # dtypes not provided series.apply(lambda x: x.tolist(), output_type='dataframe') def test_transform(): cols = [chr(ord('A') + i) for i in range(10)] df_raw = pd.DataFrame(dict((c, [i ** 2 for i in range(20)]) for c in cols)) df = from_pandas_df(df_raw, chunk_size=5) idxes = [chr(ord('A') + i) for i in range(20)] s_raw = pd.Series([i ** 2 for i in range(20)], index=idxes) series = from_pandas_series(s_raw, chunk_size=5) def rename_fn(f, new_name): f.__name__ = new_name return f old_chunk_store_limit = options.chunk_store_limit try: options.chunk_store_limit = 20 # DATAFRAME CASES # test transform with infer failure def transform_df_with_err(v): assert len(v) > 2 return v.sort_values() with pytest.raises(TypeError): df.transform(transform_df_with_err) r = tile(df.transform(transform_df_with_err, dtypes=df_raw.dtypes)) assert r.shape == df.shape assert r.op._op_type_ == opcodes.TRANSFORM assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (df.shape[0], 20 // df.shape[0]) assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE # test transform scenarios on data frames r = tile(df.transform(lambda x: list(range(len(x))))) assert all(v == np.dtype('int64') for v in r.dtypes) is True assert r.shape == df.shape assert r.op._op_type_ == opcodes.TRANSFORM assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (df.shape[0], 20 // df.shape[0]) assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE r = tile(df.transform(lambda x: list(range(len(x))), axis=1)) assert all(v == np.dtype('int64') for v in r.dtypes) is True assert r.shape == df.shape assert r.op._op_type_ == opcodes.TRANSFORM assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (20 // df.shape[1], df.shape[1]) assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE r = tile(df.transform(['cumsum', 'cummax', lambda x: x + 1])) assert all(v == np.dtype('int64') for v in r.dtypes) is True assert r.shape == (df.shape[0], df.shape[1] * 3) assert r.op._op_type_ == opcodes.TRANSFORM assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (df.shape[0], 20 // df.shape[0] * 3) assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE r = tile(df.transform({'A': 'cumsum', 'D': ['cumsum', 'cummax'], 'F': lambda x: x + 1})) assert all(v == np.dtype('int64') for v in r.dtypes) is True assert r.shape == (df.shape[0], 4) assert r.op._op_type_ == opcodes.TRANSFORM assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (df.shape[0], 1) assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE # test agg scenarios on series r = tile(df.transform(lambda x: x.iloc[:-1], _call_agg=True)) assert all(v == np.dtype('int64') for v in r.dtypes) is True assert r.shape == (np.nan, df.shape[1]) assert r.op._op_type_ == opcodes.TRANSFORM assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (np.nan, 1) assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE r = tile(df.transform(lambda x: x.iloc[:-1], axis=1, _call_agg=True)) assert all(v == np.dtype('int64') for v in r.dtypes) is True assert r.shape == (df.shape[0], np.nan) assert r.op._op_type_ == opcodes.TRANSFORM assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (2, np.nan) assert r.chunks[0].inputs[0].shape[1] == df_raw.shape[1] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE fn_list = [rename_fn(lambda x: x.iloc[1:].reset_index(drop=True), 'f1'), lambda x: x.iloc[:-1].reset_index(drop=True)] r = tile(df.transform(fn_list, _call_agg=True)) assert all(v == np.dtype('int64') for v in r.dtypes) is True assert r.shape == (np.nan, df.shape[1] * 2) assert r.op._op_type_ == opcodes.TRANSFORM assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (np.nan, 2) assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE r = tile(df.transform(lambda x: x.sum(), _call_agg=True)) assert r.dtype == np.dtype('int64') assert r.shape == (df.shape[1],) assert r.op._op_type_ == opcodes.TRANSFORM assert r.op.output_types[0] == OutputType.series assert r.chunks[0].shape == (20 // df.shape[0],) assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE fn_dict = { 'A': rename_fn(lambda x: x.iloc[1:].reset_index(drop=True), 'f1'), 'D': [rename_fn(lambda x: x.iloc[1:].reset_index(drop=True), 'f1'), lambda x: x.iloc[:-1].reset_index(drop=True)], 'F': lambda x: x.iloc[:-1].reset_index(drop=True), } r = tile(df.transform(fn_dict, _call_agg=True)) assert all(v == np.dtype('int64') for v in r.dtypes) is True assert r.shape == (np.nan, 4) assert r.op._op_type_ == opcodes.TRANSFORM assert r.op.output_types[0] == OutputType.dataframe assert r.chunks[0].shape == (np.nan, 1) assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0] assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE # SERIES CASES # test transform scenarios on series r = tile(series.transform(lambda x: x + 1)) assert np.dtype('int64') == r.dtype assert r.shape == series.shape assert r.op._op_type_ == opcodes.TRANSFORM assert r.op.output_types[0] == OutputType.series assert r.chunks[0].shape == (5,) assert r.chunks[0].inputs[0].shape == (5,) finally: options.chunk_store_limit = old_chunk_store_limit def test_string_method(): s = pd.Series(['a', 'b', 'c'], name='s') series = from_pandas_series(s, chunk_size=2) with pytest.raises(AttributeError): _ = series.str.non_exist r = series.str.contains('c') assert r.dtype == np.bool_ assert r.name == s.name pd.testing.assert_index_equal(r.index_value.to_pandas(), s.index) assert r.shape == s.shape r = tile(r) for i, c in enumerate(r.chunks): assert c.index == (i,) assert c.dtype == np.bool_ assert c.name == s.name pd.testing.assert_index_equal(c.index_value.to_pandas(), s.index[i * 2: (i + 1) * 2]) assert c.shape == (2,) if i == 0 else (1,) r = series.str.split(',', expand=True, n=1) assert r.op.output_types[0] == OutputType.dataframe assert r.shape == (3, 2) pd.testing.assert_index_equal(r.index_value.to_pandas(), s.index) pd.testing.assert_index_equal(r.columns_value.to_pandas(), pd.RangeIndex(2)) r = tile(r) for i, c in enumerate(r.chunks): assert c.index == (i, 0) pd.testing.assert_index_equal(c.index_value.to_pandas(), s.index[i * 2: (i + 1) * 2]) pd.testing.assert_index_equal(c.columns_value.to_pandas(), pd.RangeIndex(2)) assert c.shape == (2, 2) if i == 0 else (1, 2) with pytest.raises(TypeError): _ = series.str.cat([['1', '2']]) with pytest.raises(ValueError): _ = series.str.cat(['1', '2']) with pytest.raises(ValueError): _ = series.str.cat(',') with pytest.raises(TypeError): _ = series.str.cat({'1', '2', '3'}) r = series.str.cat(sep=',') assert r.op.output_types[0] == OutputType.scalar assert r.dtype == s.dtype r = tile(r) assert len(r.chunks) == 1 assert r.chunks[0].op.output_types[0] == OutputType.scalar assert r.chunks[0].dtype == s.dtype r = series.str.extract(r'[ab](\d)', expand=False) assert r.op.output_types[0] == OutputType.series assert r.dtype == s.dtype r = tile(r) for i, c in enumerate(r.chunks): assert c.index == (i,) assert c.dtype == s.dtype assert c.name == s.name pd.testing.assert_index_equal(c.index_value.to_pandas(), s.index[i * 2: (i + 1) * 2]) assert c.shape == (2,) if i == 0 else (1,) r = series.str.extract(r'[ab](\d)', expand=True) assert r.op.output_types[0] == OutputType.dataframe assert r.shape == (3, 1) pd.testing.assert_index_equal(r.index_value.to_pandas(), s.index) pd.testing.assert_index_equal(r.columns_value.to_pandas(), pd.RangeIndex(1)) r = tile(r) for i, c in enumerate(r.chunks): assert c.index == (i, 0) pd.testing.assert_index_equal(c.index_value.to_pandas(), s.index[i * 2: (i + 1) * 2]) pd.testing.assert_index_equal(c.columns_value.to_pandas(), pd.RangeIndex(1)) assert c.shape == (2, 1) if i == 0 else (1, 1) assert 'lstrip' in dir(series.str) def test_datetime_method(): s = pd.Series([pd.Timestamp('2020-1-1'), pd.Timestamp('2020-2-1'), pd.Timestamp('2020-3-1')], name='ss') series = from_pandas_series(s, chunk_size=2) r = series.dt.year assert r.dtype == s.dt.year.dtype pd.testing.assert_index_equal(r.index_value.to_pandas(), s.index) assert r.shape == s.shape assert r.op.output_types[0] == OutputType.series assert r.name == s.dt.year.name r = tile(r) for i, c in enumerate(r.chunks): assert c.index == (i,) assert c.dtype == s.dt.year.dtype assert c.op.output_types[0] == OutputType.series assert r.name == s.dt.year.name pd.testing.assert_index_equal(c.index_value.to_pandas(), s.index[i * 2: (i + 1) * 2]) assert c.shape == (2,) if i == 0 else (1,) with pytest.raises(AttributeError): _ = series.dt.non_exist assert 'ceil' in dir(series.dt) def test_series_isin(): # one chunk in multiple chunks a = from_pandas_series(pd.Series([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), chunk_size=10) b = from_pandas_series(pd.Series([2, 1, 9, 3]), chunk_size=2) r = tile(a.isin(b)) for i, c in enumerate(r.chunks): assert c.index == (i,) assert c.dtype == np.dtype('bool') assert c.shape == (10,) assert len(c.op.inputs) == 2 assert c.op.output_types[0] == OutputType.series assert c.op.inputs[0].index == (i,) assert c.op.inputs[0].shape == (10,) assert c.op.inputs[1].index == (0,) assert c.op.inputs[1].shape == (4,) # has been rechunked # multiple chunk in one chunks a = from_pandas_series(pd.Series([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), chunk_size=2) b = from_pandas_series(pd.Series([2, 1, 9, 3]), chunk_size=4) r = tile(a.isin(b)) for i, c in enumerate(r.chunks): assert c.index == (i,) assert c.dtype == np.dtype('bool') assert c.shape == (2,) assert len(c.op.inputs) == 2 assert c.op.output_types[0] == OutputType.series assert c.op.inputs[0].index == (i,) assert c.op.inputs[0].shape == (2,) assert c.op.inputs[1].index == (0,) assert c.op.inputs[1].shape == (4,) # multiple chunk in multiple chunks a = from_pandas_series(pd.Series([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), chunk_size=2) b = from_pandas_series(pd.Series([2, 1, 9, 3]), chunk_size=2) r = tile(a.isin(b)) for i, c in enumerate(r.chunks): assert c.index == (i,) assert c.dtype == np.dtype('bool') assert c.shape == (2,) assert len(c.op.inputs) == 2 assert c.op.output_types[0] == OutputType.series assert c.op.inputs[0].index == (i,) assert c.op.inputs[0].shape == (2,) assert c.op.inputs[1].index == (0,) assert c.op.inputs[1].shape == (4,) # has been rechunked with pytest.raises(TypeError): _ = a.isin('sth') with pytest.raises(TypeError): _ = a.to_frame().isin('sth') def test_cut(): s = from_pandas_series(pd.Series([1., 2., 3., 4.]), chunk_size=2) with pytest.raises(ValueError): _ = cut(s, -1) with pytest.raises(ValueError): _ = cut([[1, 2], [3, 4]], 3) with pytest.raises(ValueError): _ = cut([], 3) r, b = cut(s, [1.5, 2.5], retbins=True) assert isinstance(r, SERIES_TYPE) assert isinstance(b, TENSOR_TYPE) r = tile(r) assert len(r.chunks) == 2 for c in r.chunks: assert isinstance(c, SERIES_CHUNK_TYPE) assert c.shape == (2,) r = cut(s.to_tensor(), [1.5, 2.5]) assert isinstance(r, CATEGORICAL_TYPE) assert len(r) == len(s) assert 'Categorical' in repr(r) r = tile(r) assert len(r.chunks) == 2 for c in r.chunks: assert isinstance(c, CATEGORICAL_CHUNK_TYPE) assert c.shape == (2,) assert c.ndim == 1 r = cut([0, 1, 1, 2], bins=4, labels=False) assert isinstance(r, TENSOR_TYPE) e = pd.cut([0, 1, 1, 2], bins=4, labels=False) assert r.dtype == e.dtype def test_to_numeric(): raw = pd.DataFrame({"a": [1.0, 2, 3, -3]}) df = from_pandas_df(raw, chunk_size=2) with pytest.raises(ValueError): _ = to_numeric(df) with pytest.raises(ValueError): _ = to_numeric([['1.0', 1]]) with pytest.raises(ValueError): _ = to_numeric([]) s = from_pandas_series(pd.Series(['1.0', '2.0', 1, -2]), chunk_size=2) r = tile(to_numeric(s)) assert len(r.chunks) == 2 assert isinstance(r, SERIES_TYPE) r = tile(to_numeric(['1.0', '2.0', 1, -2])) assert isinstance(r, TENSOR_TYPE) def test_astype(): s = from_pandas_series(pd.Series([1, 2, 1, 2], name='a'), chunk_size=2) with pytest.raises(KeyError): astype(s, {'b': 'str'}) df = from_pandas_df(pd.DataFrame({'a': [1, 2, 1, 2], 'b': ['a', 'b', 'a', 'b']}), chunk_size=2) with pytest.raises(KeyError): astype(df, {'c': 'str', 'a': 'str'}) def test_drop(): # test dataframe drop rs = np.random.RandomState(0) raw = pd.DataFrame(rs.randint(1000, size=(20, 8)), columns=['c' + str(i + 1) for i in range(8)]) df = from_pandas_df(raw, chunk_size=8) with pytest.raises(KeyError): df.drop(columns=['c9']) with pytest.raises(NotImplementedError): df.drop(columns=from_pandas_series(pd.Series(['c9']))) r = df.drop(columns=['c1']) pd.testing.assert_index_equal(r.index_value.to_pandas(), raw.index) tiled = tile(r) start = 0 for c in tiled.chunks: raw_index = raw.index[start: start + c.shape[0]] start += c.shape[0] pd.testing.assert_index_equal(raw_index, c.index_value.to_pandas()) df = from_pandas_df(raw, chunk_size=3) columns = ['c2', 'c4', 'c5', 'c6'] index = [3, 6, 7] r = df.drop(columns=columns, index=index) assert isinstance(r, DATAFRAME_TYPE) # test series drop raw = pd.Series(rs.randint(1000, size=(20,))) series = from_pandas_series(raw, chunk_size=3) r = series.drop(index=index) assert isinstance(r, SERIES_TYPE) # test index drop ser = pd.Series(range(20)) rs.shuffle(ser) raw = pd.Index(ser) idx = from_pandas_index(raw) r = idx.drop(index) assert isinstance(r, INDEX_TYPE) def test_drop_duplicates(): rs = np.random.RandomState(0) raw = pd.DataFrame(rs.randint(1000, size=(20, 7)), columns=['c' + str(i + 1) for i in range(7)]) raw['c7'] = [f's{j}' for j in range(20)] df = from_pandas_df(raw, chunk_size=10) with pytest.raises(ValueError): df.drop_duplicates(method='unknown') with pytest.raises(KeyError): df.drop_duplicates(subset='c8') # test auto method selection assert tile(df.drop_duplicates()).chunks[0].op.method == 'tree' # subset size less than chunk_store_limit assert tile(df.drop_duplicates(subset=['c1', 'c3'])).chunks[0].op.method == 'subset_tree' with option_context({'chunk_store_limit': 5}): # subset size greater than chunk_store_limit assert tile(df.drop_duplicates(subset=['c1', 'c3'])).chunks[0].op.method == 'tree' assert tile(df.drop_duplicates(subset=['c1', 'c7'])).chunks[0].op.method == 'tree' assert tile(df['c7'].drop_duplicates()).chunks[0].op.method == 'tree' s = df['c7'] with pytest.raises(ValueError): s.drop_duplicates(method='unknown') def test_memory_usage(): dtypes = ['int64', 'float64', 'complex128', 'object', 'bool'] data = dict([(t, np.ones(shape=500).astype(t)) for t in dtypes]) raw = pd.DataFrame(data) df = from_pandas_df(raw, chunk_size=(500, 2)) r = tile(df.memory_usage()) assert isinstance(r, SERIES_TYPE) assert r.shape == (6,) assert len(r.chunks) == 3 assert r.chunks[0].op.stage is None df = from_pandas_df(raw, chunk_size=(100, 3)) r = tile(df.memory_usage(index=True)) assert isinstance(r, SERIES_TYPE) assert r.shape == (6,) assert len(r.chunks) == 2 assert r.chunks[0].op.stage == OperandStage.reduce r = tile(df.memory_usage(index=False)) assert isinstance(r, SERIES_TYPE) assert r.shape == (5,) assert len(r.chunks) == 2 assert r.chunks[0].op.stage == OperandStage.reduce raw = pd.Series(np.ones(shape=500).astype('object'), name='s') series = from_pandas_series(raw) r = tile(series.memory_usage()) assert isinstance(r, TENSOR_TYPE) assert r.shape == () assert len(r.chunks) == 1 assert r.chunks[0].op.stage is None series = from_pandas_series(raw, chunk_size=100) r = tile(series.memory_usage()) assert isinstance(r, TENSOR_TYPE) assert r.shape == () assert len(r.chunks) == 1 assert r.chunks[0].op.stage == OperandStage.reduce def test_shift(): rs = np.random.RandomState(0) raw = pd.DataFrame(rs.randint(1000, size=(10, 8)), columns=['col' + str(i + 1) for i in range(8)], index=pd.date_range('2021-1-1', periods=10)) df = from_pandas_df(raw, chunk_size=5) df2 = df.shift(1) df2 = tile(df2) for c in df2.chunks: pd.testing.assert_index_equal(c.dtypes.index, c.columns_value.to_pandas()) df2 = df.shift(1, freq='D') df2 = tile(df2) for c in df2.chunks: pd.testing.assert_index_equal(c.dtypes.index, c.columns_value.to_pandas()) def test_eval_query(): rs = np.random.RandomState(0) raw = pd.DataFrame({'a': rs.rand(100), 'b': rs.rand(100), 'c c': rs.rand(100)}) df = from_pandas_df(raw, chunk_size=(10, 2)) with pytest.raises(NotImplementedError): mars_eval('df.a * 2', engine='numexpr') with pytest.raises(NotImplementedError): mars_eval('df.a * 2', parser='pandas') with pytest.raises(TypeError): df.eval(df) with pytest.raises(SyntaxError): df.query(""" a + b a + `c c` """) with pytest.raises(SyntaxError): df.eval(""" def a(): return v a() """) with pytest.raises(SyntaxError): df.eval("a + `c") with pytest.raises(KeyError): df.eval("a + c") with pytest.raises(ValueError): df.eval("p, q = a + c") with pytest.raises(ValueError): df.query("p = a + c") def test_empty(): # for DataFrame assert from_pandas_df(pd.DataFrame()).empty == pd.DataFrame().empty assert from_pandas_df(pd.DataFrame({})).empty == pd.DataFrame({}).empty assert from_pandas_df(pd.DataFrame({'a': []})).empty == pd.DataFrame({'a': []}).empty assert from_pandas_df(pd.DataFrame({'a': [1]})).empty == pd.DataFrame({'a': [1]}).empty assert from_pandas_df( pd.DataFrame({'a': [1], 'b': [2]})).empty == pd.DataFrame({'a': [1], 'b': [2]}).empty assert from_pandas_df( pd.DataFrame(np.empty(shape=(4, 0)))).empty == pd.DataFrame(np.empty(shape=(4, 0))).empty # for Series assert from_pandas_series(pd.Series()).empty == pd.Series().empty assert from_pandas_series(pd.Series({})).empty == pd.Series({}).empty assert from_pandas_series(pd.Series({'a': []})).empty == pd.Series({'a': []}).empty assert from_pandas_series(pd.Series({'a': [1]})).empty == pd.Series({'a': [1]}).empty # Maybe fail due to lazy evaluation with pytest.raises(ValueError): a = from_pandas_df(pd.DataFrame(np.random.rand(10, 2))) assert a[a > 0].empty with pytest.raises(ValueError): a = from_pandas_series(pd.Series(np.random.rand(10))) assert a[a > 0].empty
[ "numpy.random.bytes", "numpy.random.rand", "mars.config.option_context", "mars.core.tile", "pandas.Index", "numpy.array", "pandas.RangeIndex", "numpy.random.RandomState", "pandas.date_range", "mars.dataframe.base.astype", "numpy.empty", "pandas.DataFrame", "numpy.dtype", "mars.dataframe.da...
[((1558, 1578), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['data'], {}), '(data)\n', (1572, 1578), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((1589, 1599), 'mars.dataframe.base.to_gpu', 'to_gpu', (['df'], {}), '(df)\n', (1595, 1599), False, 'from mars.dataframe.base import to_gpu, to_cpu, astype\n'), ((1729, 1782), 'pandas.testing.assert_series_equal', 'pd.testing.assert_series_equal', (['df.dtypes', 'cdf.dtypes'], {}), '(df.dtypes, cdf.dtypes)\n', (1759, 1782), True, 'import pandas as pd\n'), ((1798, 1811), 'mars.core.tile', 'tile', (['df', 'cdf'], {}), '(df, cdf)\n', (1802, 1811), False, 'from mars.core import OutputType, tile\n'), ((2028, 2101), 'pandas.testing.assert_series_equal', 'pd.testing.assert_series_equal', (['df.chunks[0].dtypes', 'cdf.chunks[0].dtypes'], {}), '(df.chunks[0].dtypes, cdf.chunks[0].dtypes)\n', (2058, 2101), True, 'import pandas as pd\n'), ((2193, 2218), 'mars.dataframe.datasource.series.from_pandas', 'from_pandas_series', (['sdata'], {}), '(sdata)\n', (2211, 2218), True, 'from mars.dataframe.datasource.series import from_pandas as from_pandas_series\n'), ((2233, 2247), 'mars.dataframe.base.to_gpu', 'to_gpu', (['series'], {}), '(series)\n', (2239, 2247), False, 'from mars.dataframe.base import to_gpu, to_cpu, astype\n'), ((2359, 2380), 'mars.core.tile', 'tile', (['series', 'cseries'], {}), '(series, cseries)\n', (2363, 2380), False, 'from mars.core import OutputType, tile\n'), ((2783, 2803), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['data'], {}), '(data)\n', (2797, 2803), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((2814, 2824), 'mars.dataframe.base.to_gpu', 'to_gpu', (['df'], {}), '(df)\n', (2820, 2824), False, 'from mars.dataframe.base import to_gpu, to_cpu, astype\n'), ((2835, 2846), 'mars.dataframe.base.to_cpu', 'to_cpu', (['cdf'], {}), '(cdf)\n', (2841, 2846), False, 'from mars.dataframe.base import to_gpu, to_cpu, astype\n'), ((2977, 3030), 'pandas.testing.assert_series_equal', 'pd.testing.assert_series_equal', (['df.dtypes', 'df2.dtypes'], {}), '(df.dtypes, df2.dtypes)\n', (3007, 3030), True, 'import pandas as pd\n'), ((3046, 3059), 'mars.core.tile', 'tile', (['df', 'df2'], {}), '(df, df2)\n', (3050, 3059), False, 'from mars.core import OutputType, tile\n'), ((3277, 3350), 'pandas.testing.assert_series_equal', 'pd.testing.assert_series_equal', (['df.chunks[0].dtypes', 'df2.chunks[0].dtypes'], {}), '(df.chunks[0].dtypes, df2.chunks[0].dtypes)\n', (3307, 3350), True, 'import pandas as pd\n'), ((3460, 3493), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['raw'], {'chunk_size': '(3)'}), '(raw, chunk_size=3)\n', (3474, 3493), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((3820, 3888), 'pandas.testing.assert_series_equal', 'pd.testing.assert_series_equal', (['df2.chunks[0].dtypes', 'raw.dtypes[:4]'], {}), '(df2.chunks[0].dtypes, raw.dtypes[:4])\n', (3850, 3888), True, 'import pandas as pd\n'), ((4123, 4192), 'pandas.testing.assert_series_equal', 'pd.testing.assert_series_equal', (['df2.chunks[2].dtypes', 'raw.dtypes[-2:]'], {}), '(df2.chunks[2].dtypes, raw.dtypes[-2:])\n', (4153, 4192), True, 'import pandas as pd\n'), ((4434, 4504), 'pandas.testing.assert_series_equal', 'pd.testing.assert_series_equal', (['df2.chunks[-1].dtypes', 'raw.dtypes[-2:]'], {}), '(df2.chunks[-1].dtypes, raw.dtypes[-2:])\n', (4464, 4504), True, 'import pandas as pd\n'), ((4707, 4746), 'numpy.random.randint', 'np.random.randint', (['(-100)', '(100)'], {'size': '(4,)'}), '(-100, 100, size=(4,))\n', (4724, 4746), True, 'import numpy as np\n'), ((4832, 4865), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['raw'], {'chunk_size': '(3)'}), '(raw, chunk_size=3)\n', (4846, 4865), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((5206, 5274), 'pandas.testing.assert_series_equal', 'pd.testing.assert_series_equal', (['df2.chunks[0].dtypes', 'raw.dtypes[:6]'], {}), '(df2.chunks[0].dtypes, raw.dtypes[:6])\n', (5236, 5274), True, 'import pandas as pd\n'), ((5520, 5589), 'pandas.testing.assert_series_equal', 'pd.testing.assert_series_equal', (['df2.chunks[1].dtypes', 'raw.dtypes[-4:]'], {}), '(df2.chunks[1].dtypes, raw.dtypes[-4:])\n', (5550, 5589), True, 'import pandas as pd\n'), ((7026, 7038), 'mars.core.tile', 'tile', (['series'], {}), '(series)\n', (7030, 7038), False, 'from mars.core import OutputType, tile\n'), ((11754, 11773), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['raw'], {}), '(raw)\n', (11768, 11773), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((12103, 12142), 'mars.dataframe.datasource.series.from_pandas', 'from_pandas_series', (['s_raw'], {'chunk_size': '(5)'}), '(s_raw, chunk_size=5)\n', (12121, 12142), True, 'from mars.dataframe.datasource.series import from_pandas as from_pandas_series\n'), ((13225, 13251), 'mars.dataframe.datasource.series.from_pandas', 'from_pandas_series', (['s_raw2'], {}), '(s_raw2)\n', (13243, 13251), True, 'from mars.dataframe.datasource.series import from_pandas as from_pandas_series\n'), ((13452, 13509), 'pandas.testing.assert_series_equal', 'pd.testing.assert_series_equal', (['r.dtypes', 'expected.dtypes'], {}), '(r.dtypes, expected.dtypes)\n', (13482, 13509), True, 'import pandas as pd\n'), ((13677, 13725), 'pandas.testing.assert_series_equal', 'pd.testing.assert_series_equal', (['r.dtypes', 'dtypes'], {}), '(r.dtypes, dtypes)\n', (13707, 13725), True, 'import pandas as pd\n'), ((13900, 13948), 'pandas.testing.assert_series_equal', 'pd.testing.assert_series_equal', (['r.dtypes', 'dtypes'], {}), '(r.dtypes, dtypes)\n', (13930, 13948), True, 'import pandas as pd\n'), ((14357, 14393), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['df_raw'], {'chunk_size': '(5)'}), '(df_raw, chunk_size=5)\n', (14371, 14393), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((14523, 14562), 'mars.dataframe.datasource.series.from_pandas', 'from_pandas_series', (['s_raw'], {'chunk_size': '(5)'}), '(s_raw, chunk_size=5)\n', (14541, 14562), True, 'from mars.dataframe.datasource.series import from_pandas as from_pandas_series\n'), ((20880, 20916), 'pandas.Series', 'pd.Series', (["['a', 'b', 'c']"], {'name': '"""s"""'}), "(['a', 'b', 'c'], name='s')\n", (20889, 20916), True, 'import pandas as pd\n'), ((20930, 20965), 'mars.dataframe.datasource.series.from_pandas', 'from_pandas_series', (['s'], {'chunk_size': '(2)'}), '(s, chunk_size=2)\n', (20948, 20965), True, 'from mars.dataframe.datasource.series import from_pandas as from_pandas_series\n'), ((21242, 21249), 'mars.core.tile', 'tile', (['r'], {}), '(r)\n', (21246, 21249), False, 'from mars.core import OutputType, tile\n'), ((21862, 21869), 'mars.core.tile', 'tile', (['r'], {}), '(r)\n', (21866, 21869), False, 'from mars.core import OutputType, tile\n'), ((22639, 22646), 'mars.core.tile', 'tile', (['r'], {}), '(r)\n', (22643, 22646), False, 'from mars.core import OutputType, tile\n'), ((22927, 22934), 'mars.core.tile', 'tile', (['r'], {}), '(r)\n', (22931, 22934), False, 'from mars.core import OutputType, tile\n'), ((23551, 23558), 'mars.core.tile', 'tile', (['r'], {}), '(r)\n', (23555, 23558), False, 'from mars.core import OutputType, tile\n'), ((24149, 24184), 'mars.dataframe.datasource.series.from_pandas', 'from_pandas_series', (['s'], {'chunk_size': '(2)'}), '(s, chunk_size=2)\n', (24167, 24184), True, 'from mars.dataframe.datasource.series import from_pandas as from_pandas_series\n'), ((24445, 24452), 'mars.core.tile', 'tile', (['r'], {}), '(r)\n', (24449, 24452), False, 'from mars.core import OutputType, tile\n'), ((27328, 27360), 'mars.dataframe.cut', 'cut', (['s', '[1.5, 2.5]'], {'retbins': '(True)'}), '(s, [1.5, 2.5], retbins=True)\n', (27331, 27360), False, 'from mars.dataframe import eval as mars_eval, cut, to_numeric\n'), ((27446, 27453), 'mars.core.tile', 'tile', (['r'], {}), '(r)\n', (27450, 27453), False, 'from mars.core import OutputType, tile\n'), ((27743, 27750), 'mars.core.tile', 'tile', (['r'], {}), '(r)\n', (27747, 27750), False, 'from mars.core import OutputType, tile\n'), ((27925, 27964), 'mars.dataframe.cut', 'cut', (['[0, 1, 1, 2]'], {'bins': '(4)', 'labels': '(False)'}), '([0, 1, 1, 2], bins=4, labels=False)\n', (27928, 27964), False, 'from mars.dataframe import eval as mars_eval, cut, to_numeric\n'), ((28011, 28053), 'pandas.cut', 'pd.cut', (['[0, 1, 1, 2]'], {'bins': '(4)', 'labels': '(False)'}), '([0, 1, 1, 2], bins=4, labels=False)\n', (28017, 28053), True, 'import pandas as pd\n'), ((28119, 28155), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': [1.0, 2, 3, -3]}"], {}), "({'a': [1.0, 2, 3, -3]})\n", (28131, 28155), True, 'import pandas as pd\n'), ((28165, 28198), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['raw'], {'chunk_size': '(2)'}), '(raw, chunk_size=2)\n', (28179, 28198), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((29096, 29120), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (29117, 29120), True, 'import numpy as np\n'), ((29255, 29288), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['raw'], {'chunk_size': '(8)'}), '(raw, chunk_size=8)\n', (29269, 29288), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((29582, 29589), 'mars.core.tile', 'tile', (['r'], {}), '(r)\n', (29586, 29589), False, 'from mars.core import OutputType, tile\n'), ((29802, 29835), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['raw'], {'chunk_size': '(3)'}), '(raw, chunk_size=3)\n', (29816, 29835), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((30072, 30109), 'mars.dataframe.datasource.series.from_pandas', 'from_pandas_series', (['raw'], {'chunk_size': '(3)'}), '(raw, chunk_size=3)\n', (30090, 30109), True, 'from mars.dataframe.datasource.series import from_pandas as from_pandas_series\n'), ((30266, 30279), 'pandas.Index', 'pd.Index', (['ser'], {}), '(ser)\n', (30274, 30279), True, 'import pandas as pd\n'), ((30291, 30313), 'mars.dataframe.datasource.index.from_pandas', 'from_pandas_index', (['raw'], {}), '(raw)\n', (30308, 30313), True, 'from mars.dataframe.datasource.index import from_pandas as from_pandas_index\n'), ((30415, 30439), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (30436, 30439), True, 'import numpy as np\n'), ((30619, 30653), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['raw'], {'chunk_size': '(10)'}), '(raw, chunk_size=10)\n', (30633, 30653), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((31693, 31711), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (31705, 31711), True, 'import pandas as pd\n'), ((31722, 31762), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['raw'], {'chunk_size': '(500, 2)'}), '(raw, chunk_size=(500, 2))\n', (31736, 31762), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((31941, 31981), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['raw'], {'chunk_size': '(100, 3)'}), '(raw, chunk_size=(100, 3))\n', (31955, 31981), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((32452, 32475), 'mars.dataframe.datasource.series.from_pandas', 'from_pandas_series', (['raw'], {}), '(raw)\n', (32470, 32475), True, 'from mars.dataframe.datasource.series import from_pandas as from_pandas_series\n'), ((32660, 32699), 'mars.dataframe.datasource.series.from_pandas', 'from_pandas_series', (['raw'], {'chunk_size': '(100)'}), '(raw, chunk_size=100)\n', (32678, 32699), True, 'from mars.dataframe.datasource.series import from_pandas as from_pandas_series\n'), ((32914, 32938), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (32935, 32938), True, 'import numpy as np\n'), ((33142, 33175), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['raw'], {'chunk_size': '(5)'}), '(raw, chunk_size=5)\n', (33156, 33175), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((33209, 33218), 'mars.core.tile', 'tile', (['df2'], {}), '(df2)\n', (33213, 33218), False, 'from mars.core import OutputType, tile\n'), ((33371, 33380), 'mars.core.tile', 'tile', (['df2'], {}), '(df2)\n', (33375, 33380), False, 'from mars.core import OutputType, tile\n'), ((33524, 33548), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (33545, 33548), True, 'import numpy as np\n'), ((33690, 33729), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['raw'], {'chunk_size': '(10, 2)'}), '(raw, chunk_size=(10, 2))\n', (33704, 33729), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((1403, 1425), 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)'], {}), '(10, 10)\n', (1417, 1425), True, 'import numpy as np\n'), ((2121, 2132), 'mars.dataframe.base.to_gpu', 'to_gpu', (['cdf'], {}), '(cdf)\n', (2127, 2132), False, 'from mars.dataframe.base import to_gpu, to_cpu, astype\n'), ((2567, 2582), 'mars.dataframe.base.to_gpu', 'to_gpu', (['cseries'], {}), '(cseries)\n', (2573, 2582), False, 'from mars.dataframe.base import to_gpu, to_cpu, astype\n'), ((2628, 2650), 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)'], {}), '(10, 10)\n', (2642, 2650), True, 'import numpy as np\n'), ((3370, 3381), 'mars.dataframe.base.to_cpu', 'to_cpu', (['df2'], {}), '(df2)\n', (3376, 3381), False, 'from mars.dataframe.base import to_gpu, to_cpu, astype\n'), ((3427, 3449), 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)'], {}), '(10, 10)\n', (3441, 3449), True, 'import numpy as np\n'), ((3705, 3721), 'pandas.RangeIndex', 'pd.RangeIndex', (['(4)'], {}), '(4)\n', (3718, 3721), True, 'import pandas as pd\n'), ((3798, 3814), 'pandas.RangeIndex', 'pd.RangeIndex', (['(4)'], {}), '(4)\n', (3811, 3814), True, 'import pandas as pd\n'), ((4004, 4020), 'pandas.RangeIndex', 'pd.RangeIndex', (['(4)'], {}), '(4)\n', (4017, 4020), True, 'import pandas as pd\n'), ((4097, 4117), 'pandas.RangeIndex', 'pd.RangeIndex', (['(8)', '(10)'], {}), '(8, 10)\n', (4110, 4117), True, 'import pandas as pd\n'), ((4310, 4330), 'pandas.RangeIndex', 'pd.RangeIndex', (['(8)', '(10)'], {}), '(8, 10)\n', (4323, 4330), True, 'import pandas as pd\n'), ((4408, 4428), 'pandas.RangeIndex', 'pd.RangeIndex', (['(8)', '(10)'], {}), '(8, 10)\n', (4421, 4428), True, 'import pandas as pd\n'), ((4655, 4674), 'numpy.random.bytes', 'np.random.bytes', (['(10)'], {}), '(10)\n', (4670, 4674), True, 'import numpy as np\n'), ((4770, 4791), 'numpy.random.rand', 'np.random.rand', (['(4)', '(10)'], {}), '(4, 10)\n', (4784, 4791), True, 'import numpy as np\n'), ((5179, 5200), 'pandas.Index', 'pd.Index', (['columns[:6]'], {}), '(columns[:6])\n', (5187, 5200), True, 'import pandas as pd\n'), ((5493, 5514), 'pandas.Index', 'pd.Index', (['columns[6:]'], {}), '(columns[6:])\n', (5501, 5514), True, 'import pandas as pd\n'), ((6005, 6022), 'pandas.RangeIndex', 'pd.RangeIndex', (['(10)'], {}), '(10)\n', (6018, 6022), True, 'import pandas as pd\n'), ((6228, 6244), 'pandas.RangeIndex', 'pd.RangeIndex', (['(4)'], {}), '(4)\n', (6241, 6244), True, 'import pandas as pd\n'), ((6366, 6385), 'pandas.RangeIndex', 'pd.RangeIndex', (['(4)', '(8)'], {}), '(4, 8)\n', (6379, 6385), True, 'import pandas as pd\n'), ((6507, 6527), 'pandas.RangeIndex', 'pd.RangeIndex', (['(8)', '(10)'], {}), '(8, 10)\n', (6520, 6527), True, 'import pandas as pd\n'), ((6707, 6724), 'pandas.RangeIndex', 'pd.RangeIndex', (['(10)'], {}), '(10)\n', (6720, 6724), True, 'import pandas as pd\n'), ((6931, 6947), 'pandas.RangeIndex', 'pd.RangeIndex', (['(1)'], {}), '(1)\n', (6944, 6947), True, 'import pandas as pd\n'), ((7415, 7451), 'mars.dataframe.datasource.dataframe.from_pandas', 'from_pandas_df', (['df_raw'], {'chunk_size': '(5)'}), '(df_raw, chunk_size=5)\n', (7429, 7451), True, 'from mars.dataframe.datasource.dataframe import from_pandas as from_pandas_df\n'), ((12278, 12297), 'numpy.dtype', 'np.dtype', (['"""float64"""'], {}), "('float64')\n", (12286, 12297), True, 'import numpy as np\n'), ((12571, 12590), 'numpy.dtype', 'np.dtype', (['"""float64"""'], {}), "('float64')\n", (12579, 12590), True, 'import numpy as np\n'), ((12899, 12917), 'numpy.dtype', 'np.dtype', (['"""object"""'], {}), "('object')\n", (12907, 12917), True, 'import numpy as np\n'), ((13304, 13320), 'numpy.dtype', 'np.dtype', (['object'], {}), '(object)\n', (13312, 13320), True, 'import numpy as np\n'), ((13988, 14030), 'pytest.raises', 'pytest.raises', (['AttributeError'], {'match': '"""abc"""'}), "(AttributeError, match='abc')\n", (14001, 14030), False, 'import pytest\n'), ((14070, 14094), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (14083, 14094), False, 'import pytest\n'), ((20976, 21005), 'pytest.raises', 'pytest.raises', (['AttributeError'], {}), '(AttributeError)\n', (20989, 21005), False, 'import pytest\n'), ((21835, 21851), 'pandas.RangeIndex', 'pd.RangeIndex', (['(2)'], {}), '(2)\n', (21848, 21851), True, 'import pandas as pd\n'), ((22222, 22246), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (22235, 22246), False, 'import pytest\n'), ((22299, 22324), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (22312, 22324), False, 'import pytest\n'), ((22375, 22400), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (22388, 22400), False, 'import pytest\n'), ((22444, 22468), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (22457, 22468), False, 'import pytest\n'), ((23524, 23540), 'pandas.RangeIndex', 'pd.RangeIndex', (['(1)'], {}), '(1)\n', (23537, 23540), True, 'import pandas as pd\n'), ((24853, 24882), 'pytest.raises', 'pytest.raises', (['AttributeError'], {}), '(AttributeError)\n', (24866, 24882), False, 'import pytest\n'), ((25041, 25082), 'pandas.Series', 'pd.Series', (['[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'], {}), '([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n', (25050, 25082), True, 'import pandas as pd\n'), ((25126, 25149), 'pandas.Series', 'pd.Series', (['[2, 1, 9, 3]'], {}), '([2, 1, 9, 3])\n', (25135, 25149), True, 'import pandas as pd\n'), ((25689, 25730), 'pandas.Series', 'pd.Series', (['[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'], {}), '([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n', (25698, 25730), True, 'import pandas as pd\n'), ((25773, 25796), 'pandas.Series', 'pd.Series', (['[2, 1, 9, 3]'], {}), '([2, 1, 9, 3])\n', (25782, 25796), True, 'import pandas as pd\n'), ((26317, 26358), 'pandas.Series', 'pd.Series', (['[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'], {}), '([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n', (26326, 26358), True, 'import pandas as pd\n'), ((26401, 26424), 'pandas.Series', 'pd.Series', (['[2, 1, 9, 3]'], {}), '([2, 1, 9, 3])\n', (26410, 26424), True, 'import pandas as pd\n'), ((26909, 26933), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (26922, 26933), False, 'import pytest\n'), ((26971, 26995), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (26984, 26995), False, 'import pytest\n'), ((27079, 27110), 'pandas.Series', 'pd.Series', (['[1.0, 2.0, 3.0, 4.0]'], {}), '([1.0, 2.0, 3.0, 4.0])\n', (27088, 27110), True, 'import pandas as pd\n'), ((27132, 27157), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (27145, 27157), False, 'import pytest\n'), ((27171, 27181), 'mars.dataframe.cut', 'cut', (['s', '(-1)'], {}), '(s, -1)\n', (27174, 27181), False, 'from mars.dataframe import eval as mars_eval, cut, to_numeric\n'), ((27192, 27217), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (27205, 27217), False, 'import pytest\n'), ((27231, 27255), 'mars.dataframe.cut', 'cut', (['[[1, 2], [3, 4]]', '(3)'], {}), '([[1, 2], [3, 4]], 3)\n', (27234, 27255), False, 'from mars.dataframe import eval as mars_eval, cut, to_numeric\n'), ((27266, 27291), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (27279, 27291), False, 'import pytest\n'), ((27305, 27315), 'mars.dataframe.cut', 'cut', (['[]', '(3)'], {}), '([], 3)\n', (27308, 27315), False, 'from mars.dataframe import eval as mars_eval, cut, to_numeric\n'), ((28209, 28234), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (28222, 28234), False, 'import pytest\n'), ((28248, 28262), 'mars.dataframe.to_numeric', 'to_numeric', (['df'], {}), '(df)\n', (28258, 28262), False, 'from mars.dataframe import eval as mars_eval, cut, to_numeric\n'), ((28273, 28298), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (28286, 28298), False, 'import pytest\n'), ((28312, 28336), 'mars.dataframe.to_numeric', 'to_numeric', (["[['1.0', 1]]"], {}), "([['1.0', 1]])\n", (28322, 28336), False, 'from mars.dataframe import eval as mars_eval, cut, to_numeric\n'), ((28347, 28372), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (28360, 28372), False, 'import pytest\n'), ((28386, 28400), 'mars.dataframe.to_numeric', 'to_numeric', (['[]'], {}), '([])\n', (28396, 28400), False, 'from mars.dataframe import eval as mars_eval, cut, to_numeric\n'), ((28429, 28461), 'pandas.Series', 'pd.Series', (["['1.0', '2.0', 1, -2]"], {}), "(['1.0', '2.0', 1, -2])\n", (28438, 28461), True, 'import pandas as pd\n'), ((28490, 28503), 'mars.dataframe.to_numeric', 'to_numeric', (['s'], {}), '(s)\n', (28500, 28503), False, 'from mars.dataframe import eval as mars_eval, cut, to_numeric\n'), ((28587, 28620), 'mars.dataframe.to_numeric', 'to_numeric', (["['1.0', '2.0', 1, -2]"], {}), "(['1.0', '2.0', 1, -2])\n", (28597, 28620), False, 'from mars.dataframe import eval as mars_eval, cut, to_numeric\n'), ((28708, 28741), 'pandas.Series', 'pd.Series', (['[1, 2, 1, 2]'], {'name': '"""a"""'}), "([1, 2, 1, 2], name='a')\n", (28717, 28741), True, 'import pandas as pd\n'), ((28766, 28789), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (28779, 28789), False, 'import pytest\n'), ((28799, 28822), 'mars.dataframe.base.astype', 'astype', (['s', "{'b': 'str'}"], {}), "(s, {'b': 'str'})\n", (28805, 28822), False, 'from mars.dataframe.base import to_gpu, to_cpu, astype\n'), ((28848, 28908), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': [1, 2, 1, 2], 'b': ['a', 'b', 'a', 'b']}"], {}), "({'a': [1, 2, 1, 2], 'b': ['a', 'b', 'a', 'b']})\n", (28860, 28908), True, 'import pandas as pd\n'), ((28972, 28995), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (28985, 28995), False, 'import pytest\n'), ((29005, 29041), 'mars.dataframe.base.astype', 'astype', (['df', "{'c': 'str', 'a': 'str'}"], {}), "(df, {'c': 'str', 'a': 'str'})\n", (29011, 29041), False, 'from mars.dataframe.base import to_gpu, to_cpu, astype\n'), ((29299, 29322), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (29312, 29322), False, 'import pytest\n'), ((29365, 29399), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {}), '(NotImplementedError)\n', (29378, 29399), False, 'import pytest\n'), ((30663, 30688), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (30676, 30688), False, 'import pytest\n'), ((30744, 30767), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (30757, 30767), False, 'import pytest\n'), ((31060, 31100), 'mars.config.option_context', 'option_context', (["{'chunk_store_limit': 5}"], {}), "({'chunk_store_limit': 5})\n", (31074, 31100), False, 'from mars.config import options, option_context\n'), ((31434, 31459), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (31447, 31459), False, 'import pytest\n'), ((33740, 33774), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {}), '(NotImplementedError)\n', (33753, 33774), False, 'import pytest\n'), ((33784, 33823), 'mars.dataframe.eval', 'mars_eval', (['"""df.a * 2"""'], {'engine': '"""numexpr"""'}), "('df.a * 2', engine='numexpr')\n", (33793, 33823), True, 'from mars.dataframe import eval as mars_eval, cut, to_numeric\n'), ((33833, 33867), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {}), '(NotImplementedError)\n', (33846, 33867), False, 'import pytest\n'), ((33877, 33915), 'mars.dataframe.eval', 'mars_eval', (['"""df.a * 2"""'], {'parser': '"""pandas"""'}), "('df.a * 2', parser='pandas')\n", (33886, 33915), True, 'from mars.dataframe import eval as mars_eval, cut, to_numeric\n'), ((33925, 33949), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (33938, 33949), False, 'import pytest\n'), ((33980, 34006), 'pytest.raises', 'pytest.raises', (['SyntaxError'], {}), '(SyntaxError)\n', (33993, 34006), False, 'import pytest\n'), ((34083, 34109), 'pytest.raises', 'pytest.raises', (['SyntaxError'], {}), '(SyntaxError)\n', (34096, 34109), False, 'import pytest\n'), ((34203, 34229), 'pytest.raises', 'pytest.raises', (['SyntaxError'], {}), '(SyntaxError)\n', (34216, 34229), False, 'import pytest\n'), ((34266, 34289), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (34279, 34289), False, 'import pytest\n'), ((34325, 34350), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (34338, 34350), False, 'import pytest\n'), ((34393, 34418), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (34406, 34418), False, 'import pytest\n'), ((35456, 35481), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (35469, 35481), False, 'import pytest\n'), ((35586, 35611), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (35599, 35611), False, 'import pytest\n'), ((1433, 1473), 'numpy.random.randint', 'np.random.randint', (['(-100)', '(100)'], {'size': '(10,)'}), '(-100, 100, size=(10,))\n', (1450, 1473), True, 'import numpy as np\n'), ((2658, 2698), 'numpy.random.randint', 'np.random.randint', (['(-100)', '(100)'], {'size': '(10,)'}), '(-100, 100, size=(10,))\n', (2675, 2698), True, 'import numpy as np\n'), ((5793, 5811), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (5807, 5811), True, 'import numpy as np\n'), ((7565, 7589), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (7578, 7589), False, 'import pytest\n'), ((8831, 8848), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (8839, 8848), True, 'import numpy as np\n'), ((9261, 9278), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (9269, 9278), True, 'import numpy as np\n'), ((10727, 10745), 'numpy.dtype', 'np.dtype', (['"""object"""'], {}), "('object')\n", (10735, 10745), True, 'import numpy as np\n'), ((13169, 13188), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (13177, 13188), True, 'import numpy as np\n'), ((13190, 13209), 'numpy.array', 'np.array', (['[4, 5, 6]'], {}), '([4, 5, 6])\n', (13198, 13209), True, 'import numpy as np\n'), ((13353, 13367), 'pandas.Series', 'pd.Series', (['[1]'], {}), '([1])\n', (13362, 13367), True, 'import pandas as pd\n'), ((13432, 13446), 'pandas.Series', 'pd.Series', (['[1]'], {}), '([1])\n', (13441, 13446), True, 'import pandas as pd\n'), ((13855, 13871), 'pandas.RangeIndex', 'pd.RangeIndex', (['(2)'], {}), '(2)\n', (13868, 13871), True, 'import pandas as pd\n'), ((14935, 14959), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (14948, 14959), False, 'import pytest\n'), ((19229, 19246), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (19237, 19246), True, 'import numpy as np\n'), ((20505, 20522), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (20513, 20522), True, 'import numpy as np\n'), ((22139, 22155), 'pandas.RangeIndex', 'pd.RangeIndex', (['(2)'], {}), '(2)\n', (22152, 22155), True, 'import pandas as pd\n'), ((23828, 23844), 'pandas.RangeIndex', 'pd.RangeIndex', (['(1)'], {}), '(1)\n', (23841, 23844), True, 'import pandas as pd\n'), ((23990, 24014), 'pandas.Timestamp', 'pd.Timestamp', (['"""2020-1-1"""'], {}), "('2020-1-1')\n", (24002, 24014), True, 'import pandas as pd\n'), ((24035, 24059), 'pandas.Timestamp', 'pd.Timestamp', (['"""2020-2-1"""'], {}), "('2020-2-1')\n", (24047, 24059), True, 'import pandas as pd\n'), ((24080, 24104), 'pandas.Timestamp', 'pd.Timestamp', (['"""2020-3-1"""'], {}), "('2020-3-1')\n", (24092, 24104), True, 'import pandas as pd\n'), ((25284, 25300), 'numpy.dtype', 'np.dtype', (['"""bool"""'], {}), "('bool')\n", (25292, 25300), True, 'import numpy as np\n'), ((25931, 25947), 'numpy.dtype', 'np.dtype', (['"""bool"""'], {}), "('bool')\n", (25939, 25947), True, 'import numpy as np\n'), ((26559, 26575), 'numpy.dtype', 'np.dtype', (['"""bool"""'], {}), "('bool')\n", (26567, 26575), True, 'import numpy as np\n'), ((33094, 33131), 'pandas.date_range', 'pd.date_range', (['"""2021-1-1"""'], {'periods': '(10)'}), "('2021-1-1', periods=10)\n", (33107, 33131), True, 'import pandas as pd\n'), ((34541, 34555), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (34553, 34555), True, 'import pandas as pd\n'), ((34615, 34631), 'pandas.DataFrame', 'pd.DataFrame', (['{}'], {}), '({})\n', (34627, 34631), True, 'import pandas as pd\n'), ((34698, 34721), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': []}"], {}), "({'a': []})\n", (34710, 34721), True, 'import pandas as pd\n'), ((34789, 34813), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': [1]}"], {}), "({'a': [1]})\n", (34801, 34813), True, 'import pandas as pd\n'), ((34900, 34934), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': [1], 'b': [2]}"], {}), "({'a': [1], 'b': [2]})\n", (34912, 34934), True, 'import pandas as pd\n'), ((35136, 35147), 'pandas.Series', 'pd.Series', ([], {}), '()\n', (35145, 35147), True, 'import pandas as pd\n'), ((35208, 35221), 'pandas.Series', 'pd.Series', (['{}'], {}), '({})\n', (35217, 35221), True, 'import pandas as pd\n'), ((35289, 35309), 'pandas.Series', 'pd.Series', (["{'a': []}"], {}), "({'a': []})\n", (35298, 35309), True, 'import pandas as pd\n'), ((35378, 35399), 'pandas.Series', 'pd.Series', (["{'a': [1]}"], {}), "({'a': [1]})\n", (35387, 35399), True, 'import pandas as pd\n'), ((1508, 1527), 'numpy.random.bytes', 'np.random.bytes', (['(10)'], {}), '(10)\n', (1523, 1527), True, 'import numpy as np\n'), ((2733, 2752), 'numpy.random.bytes', 'np.random.bytes', (['(10)'], {}), '(10)\n', (2748, 2752), True, 'import numpy as np\n'), ((11701, 11720), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (11709, 11720), True, 'import numpy as np\n'), ((11722, 11741), 'numpy.array', 'np.array', (['[4, 5, 6]'], {}), '([4, 5, 6])\n', (11730, 11741), True, 'import numpy as np\n'), ((13535, 13550), 'numpy.dtype', 'np.dtype', (['float'], {}), '(float)\n', (13543, 13550), True, 'import numpy as np\n'), ((32391, 32409), 'numpy.ones', 'np.ones', ([], {'shape': '(500)'}), '(shape=500)\n', (32398, 32409), True, 'import numpy as np\n'), ((34516, 34530), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (34528, 34530), True, 'import pandas as pd\n'), ((34588, 34604), 'pandas.DataFrame', 'pd.DataFrame', (['{}'], {}), '({})\n', (34600, 34604), True, 'import pandas as pd\n'), ((34664, 34687), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': []}"], {}), "({'a': []})\n", (34676, 34687), True, 'import pandas as pd\n'), ((34754, 34778), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': [1]}"], {}), "({'a': [1]})\n", (34766, 34778), True, 'import pandas as pd\n'), ((34855, 34889), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': [1], 'b': [2]}"], {}), "({'a': [1], 'b': [2]})\n", (34867, 34889), True, 'import pandas as pd\n'), ((35036, 35058), 'numpy.empty', 'np.empty', ([], {'shape': '(4, 0)'}), '(shape=(4, 0))\n', (35044, 35058), True, 'import numpy as np\n'), ((35114, 35125), 'pandas.Series', 'pd.Series', ([], {}), '()\n', (35123, 35125), True, 'import pandas as pd\n'), ((35184, 35197), 'pandas.Series', 'pd.Series', (['{}'], {}), '({})\n', (35193, 35197), True, 'import pandas as pd\n'), ((35258, 35278), 'pandas.Series', 'pd.Series', (["{'a': []}"], {}), "({'a': []})\n", (35267, 35278), True, 'import pandas as pd\n'), ((35346, 35367), 'pandas.Series', 'pd.Series', (["{'a': [1]}"], {}), "({'a': [1]})\n", (35355, 35367), True, 'import pandas as pd\n'), ((35523, 35544), 'numpy.random.rand', 'np.random.rand', (['(10)', '(2)'], {}), '(10, 2)\n', (35537, 35544), True, 'import numpy as np\n'), ((35654, 35672), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (35668, 35672), True, 'import numpy as np\n'), ((8342, 8359), 'pandas.Series', 'pd.Series', (['[1, 2]'], {}), '([1, 2])\n', (8351, 8359), True, 'import pandas as pd\n'), ((9661, 9700), 'pandas.Series', 'pd.Series', (['[1, 2]'], {'index': "['foo', 'bar']"}), "([1, 2], index=['foo', 'bar'])\n", (9670, 9700), True, 'import pandas as pd\n'), ((29444, 29461), 'pandas.Series', 'pd.Series', (["['c9']"], {}), "(['c9'])\n", (29453, 29461), True, 'import pandas as pd\n'), ((34989, 35011), 'numpy.empty', 'np.empty', ([], {'shape': '(4, 0)'}), '(shape=(4, 0))\n', (34997, 35011), True, 'import numpy as np\n'), ((8076, 8095), 'numpy.dtype', 'np.dtype', (['"""float64"""'], {}), "('float64')\n", (8084, 8095), True, 'import numpy as np\n'), ((8386, 8403), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (8394, 8403), True, 'import numpy as np\n'), ((9735, 9752), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (9743, 9752), True, 'import numpy as np\n'), ((10231, 10248), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (10239, 10248), True, 'import numpy as np\n'), ((11203, 11220), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (11211, 11220), True, 'import numpy as np\n'), ((11899, 11914), 'numpy.dtype', 'np.dtype', (['float'], {}), '(float)\n', (11907, 11914), True, 'import numpy as np\n'), ((15576, 15593), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (15584, 15593), True, 'import numpy as np\n'), ((16069, 16086), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (16077, 16086), True, 'import numpy as np\n'), ((16562, 16579), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (16570, 16579), True, 'import numpy as np\n'), ((17108, 17125), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (17116, 17125), True, 'import numpy as np\n'), ((17632, 17649), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (17640, 17649), True, 'import numpy as np\n'), ((18125, 18142), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (18133, 18142), True, 'import numpy as np\n'), ((18742, 18759), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (18750, 18759), True, 'import numpy as np\n'), ((19989, 20006), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (19997, 20006), True, 'import numpy as np\n'), ((31619, 31637), 'numpy.ones', 'np.ones', ([], {'shape': '(500)'}), '(shape=500)\n', (31626, 31637), True, 'import numpy as np\n')]
__author__ = 'jparedes' import numpy as np from itertools import combinations, product, chain from .support_filter import support_basic_premises, support_premises_derived from .similarity_filter import similarity_basic_premises, similarity_derived_premises from .pcd_filter import pcd_basic_premises, pcd_derived_premises class Formulation: def __init__(self, ux, c_bin, ref_attributes, p_by_attribute, np_by_attribute, attributes_contain_negation): # ------- Received parameters from Fuzzification -------------- self.ux = ux self.c_bin = c_bin self.tnorm = [] self.np_by_attribute = np_by_attribute self.p_by_attribute = p_by_attribute self.attributes_contain_negation = attributes_contain_negation self.ref_attributes = ref_attributes # ------- Parameters given by user ----------------------- self.maximum_size_premise = [] # ordem_premisas # Parameters of area filter self.criteria_support = [] # 'cardinalidade relativa', 'frequencia relativa' self.threshold_support = [] # tolerancia da area # Parameters of overlapping filter self.isEnableSimilarityPremisesBase = [] self.isEnableSimilarityPremisesDerived = [] self.threshold_similarity = [] # Parameters of PCD filter self.isEnablePCDpremisesBase = [] self.isEnablePCDpremisesDerived = [] def load_filter_parameters(self, par_area, par_overlapping, par_pcd): # Load area parameters self.criteria_support = par_area[0] self.threshold_support = par_area[1] # Load overlapping parameters self.isEnableSimilarityPremisesBase = par_overlapping[0][0] self.isEnableSimilarityPremisesDerived = par_overlapping[0][1] self.threshold_similarity = par_overlapping[1] # Load logic enable of PCD self.isEnablePCDpremisesBase = par_pcd[0] self.isEnablePCDpremisesDerived = par_pcd[1] def get_basic_premises(self): """ Se obtiene las premisas de orden 1 que han de generar posteriomente las premisas compuestas :return: premisas sobrevivientes agrupadas en los atributos que pertenecen [(0,1,2), (5,6), (9,11,13)] """ # Filter area aux = support_basic_premises(self.ref_attributes, self.p_by_attribute, self.np_by_attribute, self.ux, self.criteria_support, self.threshold_support, self.attributes_contain_negation) new_ref_attribute, new_premises, new_num_premises_by_attrib, new_ux = aux # Filter PCD if self.isEnablePCDpremisesBase: aux1 = pcd_basic_premises(new_ref_attribute, new_premises, new_num_premises_by_attrib, new_ux, self.c_bin) new_ref_attribute, new_premises, new_num_premises_by_attrib, new_ux = aux1 # Filter overlapping if self.isEnableSimilarityPremisesBase and len(new_num_premises_by_attrib) > 1: aux2 = similarity_basic_premises(new_ref_attribute, new_premises, new_num_premises_by_attrib, new_ux, self.threshold_similarity) new_ref_attribute, new_premises, new_num_premises_by_attrib, new_ux = aux2 return new_ref_attribute, new_premises, new_ux # [(0, 1), (3,), (7, 8)] def gen_ARB(self, ordem_premisas, tnorm, par_area, par_overlapping, par_pcd): """ Genera premisas de orden 1 a m :param ordem_premisas: 2,3,4,5 :param tnorm: 'min' or 'prod' :param par_area: [criteria, threshold_area] :param par_overlapping: [isEnableOverlapping, threshold_similarity] :param par_pcd: [isEnablePCD] :return: premisas y sus correspondientes uX arbol = [ [p1, uXp1], [p2, uXp2], ...[pm, uXpm]] """ self.maximum_size_premise = ordem_premisas # 1,2,3,4,5.... self.tnorm = tnorm self.load_filter_parameters(par_area, par_overlapping, par_pcd) # Getting seed of premises ref_premises, basic_premises, u_base = self.get_basic_premises() # [(0,1,2), (5,6), (9,11,13)] # Save single premises: p1 = [(x,) for x in list(chain(*basic_premises))] # [(0,), (1,), (2,), (5,), (6,), (9,), (11,), (13,)] arbol = [[p1, u_base]] # Seed # Generate premises of length 2 and their references ref_comb = list(combinations(ref_premises, 2)) ref_p2 = [] p2 = [] for i in ref_comb: i2 = [basic_premises[ref_premises.index(j)] for j in i] # [basic_premises[j] for j in i] p2_i = list(product(*i2)) p2 += p2_i ref_p2 += [i] * len(p2_i) ref_p2_survivors, p2_survivors, ux_p2_survivors = self.premises_validation(ref_p2, p2) arbol.append([p2_survivors, ux_p2_survivors]) if self.maximum_size_premise > 2: p_i, ref_i = p2_survivors[:], ref_p2_survivors[:] for i in range(2, self.maximum_size_premise): ref_next, p_next = self.premises_next_level(basic_premises, ref_premises, p_i, ref_i) # --- # new_premises, ref_next ref_pi_survivors, pi_survivors, ux_pi_survivors = self.premises_validation(ref_next, p_next) arbol.append([pi_survivors, ux_pi_survivors]) p_i, ref_i = p_next[:], ref_next[:] return arbol def premises_validation(self, ref_premises, premises): ref_valid_premises = [] valid_premises = [] new_ux_prev = [] number_rows = self.ux.shape[0] for i in range(len(premises)): # Building the new premise temp = self.ux[:, premises[i]] if self.tnorm == 'prod': temp2 = temp.prod(axis=1) else: # 'min' temp2 = temp.min(axis=1) # Area validation if support_premises_derived(temp2, self.threshold_support, self.criteria_support): new_ux_prev.append(temp2.reshape(number_rows, 1)) valid_premises.append(premises[i]) ref_valid_premises.append(ref_premises[i]) if valid_premises: new_ux = np.hstack(new_ux_prev) # np.array(new_ux) # PCD validation if self.isEnablePCDpremisesDerived and ref_valid_premises: ref_valid_premises, valid_premises, new_ux = pcd_derived_premises(ref_valid_premises[:], valid_premises, new_ux, self.c_bin) # Overlapping validation if self.isEnableSimilarityPremisesDerived and len(ref_valid_premises) != 0: aux = similarity_derived_premises(ref_valid_premises[:], valid_premises, new_ux, self.threshold_similarity) ref_valid_premises, valid_premises, new_ux = aux else: new_ux = [] return ref_valid_premises, valid_premises, new_ux @staticmethod def premises_next_level(p1, ref_p1, pn, ref_pn): next_premises = [] ref_next_premises = [] for i in range(len(pn)): atributos_x_misturar = set(ref_p1) - set(ref_pn[i]) for j in atributos_x_misturar: prem = p1[ref_p1.index(j)] for k in prem: bar = pn[i] candidate = tuple(sorted(bar + (k,))) if candidate not in next_premises: next_premises.append(candidate) ref_next_premises.append(ref_pn[i] + (j,)) # tuple(sorted(apn[i] + (j,))) return ref_next_premises, next_premises # next_premises, ref_next_premises --- def main(): print ("Module 3 <<Formulation>>") print ('==========') if __name__ == '__main__': main()
[ "itertools.combinations", "itertools.chain", "itertools.product", "numpy.hstack" ]
[((4456, 4485), 'itertools.combinations', 'combinations', (['ref_premises', '(2)'], {}), '(ref_premises, 2)\n', (4468, 4485), False, 'from itertools import combinations, product, chain\n'), ((6264, 6286), 'numpy.hstack', 'np.hstack', (['new_ux_prev'], {}), '(new_ux_prev)\n', (6273, 6286), True, 'import numpy as np\n'), ((4676, 4688), 'itertools.product', 'product', (['*i2'], {}), '(*i2)\n', (4683, 4688), False, 'from itertools import combinations, product, chain\n'), ((4252, 4274), 'itertools.chain', 'chain', (['*basic_premises'], {}), '(*basic_premises)\n', (4257, 4274), False, 'from itertools import combinations, product, chain\n')]
import chord_recognition import numpy as np import miditoolkit import copy # parameters for input DEFAULT_VELOCITY_BINS = np.linspace(0, 128, 32+1, dtype=np.int) DEFAULT_FRACTION = 16 DEFAULT_DURATION_BINS = np.arange(60, 3841, 60, dtype=int) DEFAULT_TEMPO_INTERVALS = [range(30, 90), range(90, 150), range(150, 210)] # parameters for output DEFAULT_RESOLUTION = 480 # define "Item" for general storage class Item(object): def __init__(self, name, start, end, velocity, pitch): self.name = name self.start = start self.end = end self.velocity = velocity self.pitch = pitch def __repr__(self): return 'Item(name={}, start={}, end={}, velocity={}, pitch={})'.format( self.name, self.start, self.end, self.velocity, self.pitch) # read notes and tempo changes from midi (assume there is only one track) def read_items(file_path): midi_obj = miditoolkit.midi.parser.MidiFile(file_path) # note note_items = [] notes = midi_obj.instruments[0].notes notes.sort(key=lambda x: (x.start, x.pitch)) for note in notes: note_items.append(Item( name='Note', start=note.start, end=note.end, velocity=note.velocity, pitch=note.pitch)) note_items.sort(key=lambda x: x.start) # tempo tempo_items = [] for tempo in midi_obj.tempo_changes: tempo_items.append(Item( name='Tempo', start=tempo.time, end=None, velocity=None, pitch=int(tempo.tempo))) tempo_items.sort(key=lambda x: x.start) # expand to all beat max_tick = tempo_items[-1].start existing_ticks = {item.start: item.pitch for item in tempo_items} wanted_ticks = np.arange(0, max_tick+1, DEFAULT_RESOLUTION) output = [] for tick in wanted_ticks: if tick in existing_ticks: output.append(Item( name='Tempo', start=tick, end=None, velocity=None, pitch=existing_ticks[tick])) else: output.append(Item( name='Tempo', start=tick, end=None, velocity=None, pitch=output[-1].pitch)) tempo_items = output return note_items, tempo_items # quantize items def quantize_items(items, ticks=120): # grid grids = np.arange(0, items[-1].start, ticks, dtype=int) # process for item in items: index = np.argmin(abs(grids - item.start)) shift = grids[index] - item.start item.start += shift item.end += shift return items # extract chord def extract_chords(items): method = chord_recognition.MIDIChord() chords = method.extract(notes=items) output = [] for chord in chords: output.append(Item( name='Chord', start=chord[0], end=chord[1], velocity=None, pitch=chord[2].split('/')[0])) return output # group items def group_items(items, max_time, ticks_per_bar=DEFAULT_RESOLUTION*4): items.sort(key=lambda x: x.start) downbeats = np.arange(0, max_time+ticks_per_bar, ticks_per_bar) groups = [] for db1, db2 in zip(downbeats[:-1], downbeats[1:]): insiders = [] for item in items: if (item.start >= db1) and (item.start < db2): insiders.append(item) overall = [db1] + insiders + [db2] groups.append(overall) return groups # define "Event" for event storage class Event(object): def __init__(self, name, time, value, text): self.name = name self.time = time self.value = value self.text = text def __repr__(self): return 'Event(name={}, time={}, value={}, text={})'.format( self.name, self.time, self.value, self.text) # item to event def item2event(groups): events = [] n_downbeat = 0 for i in range(len(groups)): if 'Note' not in [item.name for item in groups[i][1:-1]]: continue bar_st, bar_et = groups[i][0], groups[i][-1] n_downbeat += 1 events.append(Event( name='Bar', time=None, value=None, text='{}'.format(n_downbeat))) for item in groups[i][1:-1]: # position flags = np.linspace(bar_st, bar_et, DEFAULT_FRACTION, endpoint=False) index = np.argmin(abs(flags-item.start)) events.append(Event( name='Position', time=item.start, value='{}/{}'.format(index+1, DEFAULT_FRACTION), text='{}'.format(item.start))) if item.name == 'Note': # velocity velocity_index = np.searchsorted( DEFAULT_VELOCITY_BINS, item.velocity, side='right') - 1 events.append(Event( name='Note Velocity', time=item.start, value=velocity_index, text='{}/{}'.format(item.velocity, DEFAULT_VELOCITY_BINS[velocity_index]))) # pitch events.append(Event( name='Note On', time=item.start, value=item.pitch, text='{}'.format(item.pitch))) # duration duration = item.end - item.start index = np.argmin(abs(DEFAULT_DURATION_BINS-duration)) events.append(Event( name='Note Duration', time=item.start, value=index, text='{}/{}'.format(duration, DEFAULT_DURATION_BINS[index]))) elif item.name == 'Chord': events.append(Event( name='Chord', time=item.start, value=item.pitch, text='{}'.format(item.pitch))) elif item.name == 'Tempo': tempo = item.pitch if tempo in DEFAULT_TEMPO_INTERVALS[0]: tempo_style = Event('Tempo Class', item.start, 'slow', None) tempo_value = Event('Tempo Value', item.start, tempo-DEFAULT_TEMPO_INTERVALS[0].start, None) elif tempo in DEFAULT_TEMPO_INTERVALS[1]: tempo_style = Event('Tempo Class', item.start, 'mid', None) tempo_value = Event('Tempo Value', item.start, tempo-DEFAULT_TEMPO_INTERVALS[1].start, None) elif tempo in DEFAULT_TEMPO_INTERVALS[2]: tempo_style = Event('Tempo Class', item.start, 'fast', None) tempo_value = Event('Tempo Value', item.start, tempo-DEFAULT_TEMPO_INTERVALS[2].start, None) elif tempo < DEFAULT_TEMPO_INTERVALS[0].start: tempo_style = Event('Tempo Class', item.start, 'slow', None) tempo_value = Event('Tempo Value', item.start, 0, None) elif tempo > DEFAULT_TEMPO_INTERVALS[2].stop: tempo_style = Event('Tempo Class', item.start, 'fast', None) tempo_value = Event('Tempo Value', item.start, 59, None) events.append(tempo_style) events.append(tempo_value) return events ############################################################################################# # WRITE MIDI ############################################################################################# def word_to_event(words, word2event): events = [] for word in words: event_name, event_value = word2event.get(word).split('_') events.append(Event(event_name, None, event_value, None)) return events def write_midi(words, word2event, output_path, prompt_path=None): events = word_to_event(words, word2event) # get downbeat and note (no time) temp_notes = [] temp_chords = [] temp_tempos = [] for i in range(len(events)-3): if events[i].name == 'Bar' and i > 0: temp_notes.append('Bar') temp_chords.append('Bar') temp_tempos.append('Bar') elif events[i].name == 'Position' and \ events[i+1].name == 'Note Velocity' and \ events[i+2].name == 'Note On' and \ events[i+3].name == 'Note Duration': # start time and end time from position position = int(events[i].value.split('/')[0]) - 1 # velocity index = int(events[i+1].value) velocity = int(DEFAULT_VELOCITY_BINS[index]) # pitch pitch = int(events[i+2].value) # duration index = int(events[i+3].value) duration = DEFAULT_DURATION_BINS[index] # adding temp_notes.append([position, velocity, pitch, duration]) elif events[i].name == 'Position' and events[i+1].name == 'Chord': position = int(events[i].value.split('/')[0]) - 1 temp_chords.append([position, events[i+1].value]) elif events[i].name == 'Position' and \ events[i+1].name == 'Tempo Class' and \ events[i+2].name == 'Tempo Value': position = int(events[i].value.split('/')[0]) - 1 if events[i+1].value == 'slow': tempo = DEFAULT_TEMPO_INTERVALS[0].start + int(events[i+2].value) elif events[i+1].value == 'mid': tempo = DEFAULT_TEMPO_INTERVALS[1].start + int(events[i+2].value) elif events[i+1].value == 'fast': tempo = DEFAULT_TEMPO_INTERVALS[2].start + int(events[i+2].value) temp_tempos.append([position, tempo]) # get specific time for notes ticks_per_beat = DEFAULT_RESOLUTION ticks_per_bar = DEFAULT_RESOLUTION * 4 # assume 4/4 notes = [] current_bar = 0 for note in temp_notes: if note == 'Bar': current_bar += 1 else: position, velocity, pitch, duration = note # position (start time) current_bar_st = current_bar * ticks_per_bar current_bar_et = (current_bar + 1) * ticks_per_bar flags = np.linspace(current_bar_st, current_bar_et, DEFAULT_FRACTION, endpoint=False, dtype=int) st = flags[position] # duration (end time) et = st + duration notes.append(miditoolkit.Note(velocity, pitch, st, et)) # get specific time for chords if len(temp_chords) > 0: chords = [] current_bar = 0 for chord in temp_chords: if chord == 'Bar': current_bar += 1 else: position, value = chord # position (start time) current_bar_st = current_bar * ticks_per_bar current_bar_et = (current_bar + 1) * ticks_per_bar flags = np.linspace(current_bar_st, current_bar_et, DEFAULT_FRACTION, endpoint=False, dtype=int) st = flags[position] chords.append([st, value]) # get specific time for tempos tempos = [] current_bar = 0 for tempo in temp_tempos: if tempo == 'Bar': current_bar += 1 else: position, value = tempo # position (start time) current_bar_st = current_bar * ticks_per_bar current_bar_et = (current_bar + 1) * ticks_per_bar flags = np.linspace(current_bar_st, current_bar_et, DEFAULT_FRACTION, endpoint=False, dtype=int) st = flags[position] tempos.append([int(st), value]) # write if prompt_path: midi = miditoolkit.midi.parser.MidiFile(prompt_path) # last_time = DEFAULT_RESOLUTION * 4 * 4 # note shift for note in notes: note.start += last_time note.end += last_time midi.instruments[0].notes.extend(notes) # tempo changes temp_tempos = [] for tempo in midi.tempo_changes: if tempo.time < DEFAULT_RESOLUTION*4*4: temp_tempos.append(tempo) else: break for st, bpm in tempos: st += last_time temp_tempos.append(miditoolkit.midi.containers.TempoChange(bpm, st)) midi.tempo_changes = temp_tempos # write chord into marker if len(temp_chords) > 0: for c in chords: midi.markers.append( miditoolkit.midi.containers.Marker(text=c[1], time=c[0]+last_time)) else: midi = miditoolkit.midi.parser.MidiFile() midi.ticks_per_beat = DEFAULT_RESOLUTION # write instrument inst = miditoolkit.midi.containers.Instrument(0, is_drum=False) inst.notes = notes midi.instruments.append(inst) # write tempo tempo_changes = [] for st, bpm in tempos: tempo_changes.append(miditoolkit.midi.containers.TempoChange(bpm, st)) midi.tempo_changes = tempo_changes # write chord into marker if len(temp_chords) > 0: for c in chords: midi.markers.append( miditoolkit.midi.containers.Marker(text=c[1], time=c[0])) # write midi.dump(output_path)
[ "miditoolkit.Note", "miditoolkit.midi.containers.TempoChange", "numpy.searchsorted", "chord_recognition.MIDIChord", "miditoolkit.midi.containers.Marker", "numpy.linspace", "miditoolkit.midi.containers.Instrument", "miditoolkit.midi.parser.MidiFile", "numpy.arange" ]
[((123, 164), 'numpy.linspace', 'np.linspace', (['(0)', '(128)', '(32 + 1)'], {'dtype': 'np.int'}), '(0, 128, 32 + 1, dtype=np.int)\n', (134, 164), True, 'import numpy as np\n'), ((209, 243), 'numpy.arange', 'np.arange', (['(60)', '(3841)', '(60)'], {'dtype': 'int'}), '(60, 3841, 60, dtype=int)\n', (218, 243), True, 'import numpy as np\n'), ((914, 957), 'miditoolkit.midi.parser.MidiFile', 'miditoolkit.midi.parser.MidiFile', (['file_path'], {}), '(file_path)\n', (946, 957), False, 'import miditoolkit\n'), ((1774, 1820), 'numpy.arange', 'np.arange', (['(0)', '(max_tick + 1)', 'DEFAULT_RESOLUTION'], {}), '(0, max_tick + 1, DEFAULT_RESOLUTION)\n', (1783, 1820), True, 'import numpy as np\n'), ((2433, 2480), 'numpy.arange', 'np.arange', (['(0)', 'items[-1].start', 'ticks'], {'dtype': 'int'}), '(0, items[-1].start, ticks, dtype=int)\n', (2442, 2480), True, 'import numpy as np\n'), ((2745, 2774), 'chord_recognition.MIDIChord', 'chord_recognition.MIDIChord', ([], {}), '()\n', (2772, 2774), False, 'import chord_recognition\n'), ((3192, 3245), 'numpy.arange', 'np.arange', (['(0)', '(max_time + ticks_per_bar)', 'ticks_per_bar'], {}), '(0, max_time + ticks_per_bar, ticks_per_bar)\n', (3201, 3245), True, 'import numpy as np\n'), ((11863, 11908), 'miditoolkit.midi.parser.MidiFile', 'miditoolkit.midi.parser.MidiFile', (['prompt_path'], {}), '(prompt_path)\n', (11895, 11908), False, 'import miditoolkit\n'), ((12783, 12817), 'miditoolkit.midi.parser.MidiFile', 'miditoolkit.midi.parser.MidiFile', ([], {}), '()\n', (12815, 12817), False, 'import miditoolkit\n'), ((12909, 12965), 'miditoolkit.midi.containers.Instrument', 'miditoolkit.midi.containers.Instrument', (['(0)'], {'is_drum': '(False)'}), '(0, is_drum=False)\n', (12947, 12965), False, 'import miditoolkit\n'), ((4409, 4470), 'numpy.linspace', 'np.linspace', (['bar_st', 'bar_et', 'DEFAULT_FRACTION'], {'endpoint': '(False)'}), '(bar_st, bar_et, DEFAULT_FRACTION, endpoint=False)\n', (4420, 4470), True, 'import numpy as np\n'), ((10387, 10480), 'numpy.linspace', 'np.linspace', (['current_bar_st', 'current_bar_et', 'DEFAULT_FRACTION'], {'endpoint': '(False)', 'dtype': 'int'}), '(current_bar_st, current_bar_et, DEFAULT_FRACTION, endpoint=\n False, dtype=int)\n', (10398, 10480), True, 'import numpy as np\n'), ((11650, 11743), 'numpy.linspace', 'np.linspace', (['current_bar_st', 'current_bar_et', 'DEFAULT_FRACTION'], {'endpoint': '(False)', 'dtype': 'int'}), '(current_bar_st, current_bar_et, DEFAULT_FRACTION, endpoint=\n False, dtype=int)\n', (11661, 11743), True, 'import numpy as np\n'), ((10599, 10640), 'miditoolkit.Note', 'miditoolkit.Note', (['velocity', 'pitch', 'st', 'et'], {}), '(velocity, pitch, st, et)\n', (10615, 10640), False, 'import miditoolkit\n'), ((11098, 11191), 'numpy.linspace', 'np.linspace', (['current_bar_st', 'current_bar_et', 'DEFAULT_FRACTION'], {'endpoint': '(False)', 'dtype': 'int'}), '(current_bar_st, current_bar_et, DEFAULT_FRACTION, endpoint=\n False, dtype=int)\n', (11109, 11191), True, 'import numpy as np\n'), ((12446, 12494), 'miditoolkit.midi.containers.TempoChange', 'miditoolkit.midi.containers.TempoChange', (['bpm', 'st'], {}), '(bpm, st)\n', (12485, 12494), False, 'import miditoolkit\n'), ((13144, 13192), 'miditoolkit.midi.containers.TempoChange', 'miditoolkit.midi.containers.TempoChange', (['bpm', 'st'], {}), '(bpm, st)\n', (13183, 13192), False, 'import miditoolkit\n'), ((4832, 4899), 'numpy.searchsorted', 'np.searchsorted', (['DEFAULT_VELOCITY_BINS', 'item.velocity'], {'side': '"""right"""'}), "(DEFAULT_VELOCITY_BINS, item.velocity, side='right')\n", (4847, 4899), True, 'import numpy as np\n'), ((12690, 12758), 'miditoolkit.midi.containers.Marker', 'miditoolkit.midi.containers.Marker', ([], {'text': 'c[1]', 'time': '(c[0] + last_time)'}), '(text=c[1], time=c[0] + last_time)\n', (12724, 12758), False, 'import miditoolkit\n'), ((13390, 13446), 'miditoolkit.midi.containers.Marker', 'miditoolkit.midi.containers.Marker', ([], {'text': 'c[1]', 'time': 'c[0]'}), '(text=c[1], time=c[0])\n', (13424, 13446), False, 'import miditoolkit\n')]
import numpy as np import math from data_parser import loadData def c(t): return math.cos(math.radians(t)) def s(t): return math.sin(math.radians(t)) def generate_angles(num_dofs): angles = np.random.uniform(low = -360, high = 360, size = (num_dofs,)) return angles #TODO find the right implementation of getting the rotation angles def getRotations(r): roll = math.atan2(r[2][1],r[2][2]) pitch = math.atan2(r[1][0],r[0][0]) if math.cos(pitch) == 0: yaw = math.atan2(-r[2][0],r[1][0]/math.sin(r)) else: yaw = math.atan2(-r[2][0],r[1][0]/math.cos(pitch)) return roll,pitch,yaw #return math.degrees(roll),math.degrees(pitch),math.degrees(yaw) def getTransformation(dh): T0_3 = np.array( [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) Temp = [] l = len(dh) // 4 for i in range(1, (l + 1)): t = dh["t" + str(i)] q = dh["q" + str(i)] d = dh["d" + str(i)] a = dh["a" + str(i)] Temp = np.array( [[c(t), -s(t) * c(q), s(t) * s(q), a * c(t)], [s(t), c(t) * c(q), -c(t) * s(q), a * s(t)], [0, s(q), c(q), d], [0, 0, 0, 1]]) T0_3 = T0_3 @ Temp x = T0_3[0][3] y = T0_3[1][3] z = T0_3[2][3] roll, pitch, yaw = getRotations(T0_3) # print("x = " + str(x)) # print("y = " + str(y)) # print("z = " + str(z)) # # print("\nT matrix: \n") # # print(T0_3) return x,y,z,roll,pitch,yaw # generates one example inputs and outputs to files : inputs.txt / outputs.txt def generate_inputs_and_outputs(dh_params): x, y, z, roll, pitch, yaw = getTransformation(dh_params) inputs = str(x) + "," + str(y) + "," + str(z) + "," + str(roll) + "," + str(pitch) + "," + str(yaw) + "\n" outputs = str(joint_angles[0]) + "," + str(joint_angles[1]) + "," + str(joint_angles[2]) + "\n" with open("inputs.txt", 'a') as in_file: in_file.write(inputs) with open("outputs.txt", 'a') as out_file: out_file.write(outputs) # ==================================================== Main ========================================================= #erasing files contents with open("inputs.txt",'w') as i: i.write("") with open("outputs.txt",'w') as o: o.write("") #lines lengths l = [7,7,9] #number of rotating joints num_dofs = 3 num_examples = 10000 print("generating data ..... ") for i in range(num_examples): # randomly generated joint angles for one example joint_angles = generate_angles(num_dofs) # DH parameters dh_params = {"q1": 90, "a1": 0, "d1": l[0], "t1": joint_angles[0], "q2": 0, "a2": l[1], "d2": 0, "t2": joint_angles[1], "q3": 0, "a3": l[2], "d3": 0, "t3": -joint_angles[2] } generate_inputs_and_outputs(dh_params) print("Done generating data ! ") # load and print data : X,Y = loadData("inputs.txt","outputs.txt") print("inputs: ") print(X.shape) # print(X) print("\noutputs: ") print(Y.shape) # print(Y)
[ "data_parser.loadData", "math.radians", "math.cos", "numpy.array", "math.atan2", "numpy.random.uniform", "math.sin" ]
[((3186, 3223), 'data_parser.loadData', 'loadData', (['"""inputs.txt"""', '"""outputs.txt"""'], {}), "('inputs.txt', 'outputs.txt')\n", (3194, 3223), False, 'from data_parser import loadData\n'), ((214, 269), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-360)', 'high': '(360)', 'size': '(num_dofs,)'}), '(low=-360, high=360, size=(num_dofs,))\n', (231, 269), True, 'import numpy as np\n'), ((401, 429), 'math.atan2', 'math.atan2', (['r[2][1]', 'r[2][2]'], {}), '(r[2][1], r[2][2])\n', (411, 429), False, 'import math\n'), ((445, 473), 'math.atan2', 'math.atan2', (['r[1][0]', 'r[0][0]'], {}), '(r[1][0], r[0][0])\n', (455, 473), False, 'import math\n'), ((801, 867), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n', (809, 867), True, 'import numpy as np\n'), ((99, 114), 'math.radians', 'math.radians', (['t'], {}), '(t)\n', (111, 114), False, 'import math\n'), ((151, 166), 'math.radians', 'math.radians', (['t'], {}), '(t)\n', (163, 166), False, 'import math\n'), ((485, 500), 'math.cos', 'math.cos', (['pitch'], {}), '(pitch)\n', (493, 500), False, 'import math\n'), ((557, 568), 'math.sin', 'math.sin', (['r'], {}), '(r)\n', (565, 568), False, 'import math\n'), ((634, 649), 'math.cos', 'math.cos', (['pitch'], {}), '(pitch)\n', (642, 649), False, 'import math\n')]
""" Classes for visualizing echo data """ import numpy as np import matplotlib.colors as colors # import datetime as dt from matplotlib.dates import date2num from collections import defaultdict import echopype_model # Colormap: multi-frequency availability from Jech & Michaels 2006 MF_COLORS = np.array([[0,0,0],\ [86,25,148],\ [28,33,179],\ [0,207,239],\ [41,171,71],\ [51,204,51],\ [255,239,0],\ [255,51,0]])/255. MF_CMAP_TMP = colors.ListedColormap(MF_COLORS) MF_CMAP = colors.BoundaryNorm(range(MF_COLORS.shape[0]+1),MF_CMAP_TMP.N) # Colormap: standard EK60 EK60_COLORS = np.array([[255, 255, 255],\ [159, 159, 159],\ [ 95, 95, 95],\ [ 0, 0, 255],\ [ 0, 0, 127],\ [ 0, 191, 0],\ [ 0, 127, 0],\ [255, 255, 0],\ [255, 127, 0],\ [255, 0, 191],\ [255, 0, 0],\ [166, 83, 60],\ [120, 60, 40]])/255. EK60_CMAP_TH = [-80,-30] EK60_CMAP_TMP = colors.ListedColormap(EK60_COLORS) EK60_CMAP_BOUNDS = np.linspace(EK60_CMAP_TH[0],EK60_CMAP_TH[1],EK60_CMAP_TMP.N+1) EK60_CMAP = colors.BoundaryNorm(EK60_CMAP_BOUNDS,EK60_CMAP_TMP.N) # Default plot echogram params ECHOGRAM_PARAMS = defaultdict(list) ECHOGRAM_PARAMS['hour_spacing'] = 1 # spacing: in [hour] ECHOGRAM_PARAMS['depth_ticks_num'] = 5 # number of tick marks on y-axis ECHOGRAM_PARAMS['depth_min'] = 0 # min depth to plot [m] ECHOGRAM_PARAMS['depth_max'] = 200 # max depth to plot [m] ECHOGRAM_PARAMS['cmap_min'] = -80 # min of color scale ECHOGRAM_PARAMS['cmap_max'] = -30 # max of color scale ECHOGRAM_PARAMS['c_ticks_spacing'] # number of ticks in colorbar class EchoDataViewer(object): ''' Class to view echo data. Input can be a EchoDataRaw (now) or EchoDataMVBS (future) ''' def __init__(self,echo_object='',fig_size=[15,8],cmap='viridis'): self.fig_size = fig_size self.cmap = cmap if echo_object=='': self.echo_data_type = '' self.echo_vals = [] self.frequency = [] self.depth_bin = [] self.ping_bin = [] self.ping_time = [] else: self.echo_object = echo_object self.load_echo_info() # Emtpy attributes that will only be evaluated when associated methods called by user self.date_range = [] # Methods to set/get critical attributes def load_echo_info(self): if isinstance(self.echo_object,(echopype_model.EchoDataRaw)): self.echo_data_type = 'EchoDataRaw' self.echo_vals = self.echo_object.Sv_corrected self.depth_bin = self.echo_object.bin_size # this is for Sv data else: self.echo_data_type = 'others' # add other types later self.echo_vals = [] self.depth_bin = self.echo_object.depth_bin # this is for MVBS self.frequency = [float(x) for x in self.echo_object.Sv_corrected.keys()] # get frequency info self.ping_bin = self.echo_object.ping_bin self.ping_time = self.echo_object.ping_time def set_date_range(self,date_range): self.date_range = date_range def set_fig_size(self,fig_size): self.fig_size = fig_size def set_cmap(self,cmap): self.cmap = cmap # Methods for visualization def echogram(self,ax,echogram_params,freq_select): ''' Plot echogram for selected frequencies INPUT: ax axis the echogram to be plot on echogram_params plotting parameters freq_select selected frequency (dtype=float) ''' freq_idx = self.find_freq_seq(freq_select) sz = self.echo_vals[str(self.frequency[freq_idx])].shape # Getting start and end ping indices if self.date_range=='': print('No data range set. Use set_date_range to select date range to plot') return else: date_num_range = date2num(self.date_range) ping_idx_start = np.searchsorted(self.ping_time, date_num_range[0], side="left") ping_idx_end = np.searchsorted(self.ping_time, date_num_range[1], side="right") if ping_idx_end>=self.ping_time.shape[0]: ping_idx_end = self.ping_time.shape[0]-1 # Getting start and end depth indices depth_vec = np.arange(sz[0])*self.depth_bin # list of depth bins [m] depth_idx_start = np.searchsorted(depth_vec, echogram_params['depth_min'], side="left") depth_idx_end = np.searchsorted(depth_vec, echogram_params['depth_max'], side="right") if depth_idx_end>=depth_vec.shape[0]: depth_idx_end = depth_vec.shape[0]-1 # Set up xticks -- day del_time = (self.date_range[1]-self.date_range[0]) x_ticks_num = (del_time.days*24+del_time.seconds/60/60)/echogram_params['hour_spacing'] x_ticks_spacing = sz[1]/(x_ticks_num) x_ticks = np.arange(0,sz[1],x_ticks_spacing) x_ticks_label = np.arange(x_ticks.shape[0])*echogram_params['hour_spacing'] # this probably should be outside of the function # Set up yticks -- depth y_ticks_spacing = sz[0]/(echogram_params['depth_ticks_num']-1) y_ticks = np.arange(echogram_params['depth_ticks_num'])*y_ticks_spacing depth_spacing = np.around((echogram_params['depth_max']-\ echogram_params['depth_min'])/(echogram_params['depth_ticks_num']-1),decimals=1) depth_label = np.around(np.arange(echogram_params['depth_ticks_num'])*depth_spacing,decimals=1) # Plot # -- plot echo_vals upside-down axim = ax.imshow(self.echo_vals[str(self.frequency[freq_idx])][::-1,:],aspect='auto',\ vmax=echogram_params['cmap_max'],vmin=echogram_params['cmap_min'],cmap=self.cmap) ax.set_yticks(y_ticks) ax.set_yticklabels(depth_label) ax.set_xticks(x_ticks) ax.set_xticklabels(x_ticks_label) return axim def find_freq_seq(self,freq_select): '''Find the sequence of transducer of a particular freq''' return int(np.where(np.array(self.frequency)==freq_select)[0])
[ "matplotlib.dates.date2num", "numpy.searchsorted", "matplotlib.colors.ListedColormap", "numpy.array", "numpy.linspace", "collections.defaultdict", "numpy.around", "matplotlib.colors.BoundaryNorm", "numpy.arange" ]
[((588, 620), 'matplotlib.colors.ListedColormap', 'colors.ListedColormap', (['MF_COLORS'], {}), '(MF_COLORS)\n', (609, 620), True, 'import matplotlib.colors as colors\n'), ((1338, 1372), 'matplotlib.colors.ListedColormap', 'colors.ListedColormap', (['EK60_COLORS'], {}), '(EK60_COLORS)\n', (1359, 1372), True, 'import matplotlib.colors as colors\n'), ((1392, 1458), 'numpy.linspace', 'np.linspace', (['EK60_CMAP_TH[0]', 'EK60_CMAP_TH[1]', '(EK60_CMAP_TMP.N + 1)'], {}), '(EK60_CMAP_TH[0], EK60_CMAP_TH[1], EK60_CMAP_TMP.N + 1)\n', (1403, 1458), True, 'import numpy as np\n'), ((1467, 1521), 'matplotlib.colors.BoundaryNorm', 'colors.BoundaryNorm', (['EK60_CMAP_BOUNDS', 'EK60_CMAP_TMP.N'], {}), '(EK60_CMAP_BOUNDS, EK60_CMAP_TMP.N)\n', (1486, 1521), True, 'import matplotlib.colors as colors\n'), ((1572, 1589), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1583, 1589), False, 'from collections import defaultdict\n'), ((298, 427), 'numpy.array', 'np.array', (['[[0, 0, 0], [86, 25, 148], [28, 33, 179], [0, 207, 239], [41, 171, 71], [51,\n 204, 51], [255, 239, 0], [255, 51, 0]]'], {}), '([[0, 0, 0], [86, 25, 148], [28, 33, 179], [0, 207, 239], [41, 171,\n 71], [51, 204, 51], [255, 239, 0], [255, 51, 0]])\n', (306, 427), True, 'import numpy as np\n'), ((736, 944), 'numpy.array', 'np.array', (['[[255, 255, 255], [159, 159, 159], [95, 95, 95], [0, 0, 255], [0, 0, 127],\n [0, 191, 0], [0, 127, 0], [255, 255, 0], [255, 127, 0], [255, 0, 191],\n [255, 0, 0], [166, 83, 60], [120, 60, 40]]'], {}), '([[255, 255, 255], [159, 159, 159], [95, 95, 95], [0, 0, 255], [0, \n 0, 127], [0, 191, 0], [0, 127, 0], [255, 255, 0], [255, 127, 0], [255, \n 0, 191], [255, 0, 0], [166, 83, 60], [120, 60, 40]])\n', (744, 944), True, 'import numpy as np\n'), ((4841, 4910), 'numpy.searchsorted', 'np.searchsorted', (['depth_vec', "echogram_params['depth_min']"], {'side': '"""left"""'}), "(depth_vec, echogram_params['depth_min'], side='left')\n", (4856, 4910), True, 'import numpy as np\n'), ((4935, 5005), 'numpy.searchsorted', 'np.searchsorted', (['depth_vec', "echogram_params['depth_max']"], {'side': '"""right"""'}), "(depth_vec, echogram_params['depth_max'], side='right')\n", (4950, 5005), True, 'import numpy as np\n'), ((5352, 5388), 'numpy.arange', 'np.arange', (['(0)', 'sz[1]', 'x_ticks_spacing'], {}), '(0, sz[1], x_ticks_spacing)\n', (5361, 5388), True, 'import numpy as np\n'), ((5731, 5863), 'numpy.around', 'np.around', (["((echogram_params['depth_max'] - echogram_params['depth_min']) / (\n echogram_params['depth_ticks_num'] - 1))"], {'decimals': '(1)'}), "((echogram_params['depth_max'] - echogram_params['depth_min']) / (\n echogram_params['depth_ticks_num'] - 1), decimals=1)\n", (5740, 5863), True, 'import numpy as np\n'), ((4368, 4393), 'matplotlib.dates.date2num', 'date2num', (['self.date_range'], {}), '(self.date_range)\n', (4376, 4393), False, 'from matplotlib.dates import date2num\n'), ((4423, 4486), 'numpy.searchsorted', 'np.searchsorted', (['self.ping_time', 'date_num_range[0]'], {'side': '"""left"""'}), "(self.ping_time, date_num_range[0], side='left')\n", (4438, 4486), True, 'import numpy as np\n'), ((4514, 4578), 'numpy.searchsorted', 'np.searchsorted', (['self.ping_time', 'date_num_range[1]'], {'side': '"""right"""'}), "(self.ping_time, date_num_range[1], side='right')\n", (4529, 4578), True, 'import numpy as np\n'), ((4757, 4773), 'numpy.arange', 'np.arange', (['sz[0]'], {}), '(sz[0])\n', (4766, 4773), True, 'import numpy as np\n'), ((5411, 5438), 'numpy.arange', 'np.arange', (['x_ticks.shape[0]'], {}), '(x_ticks.shape[0])\n', (5420, 5438), True, 'import numpy as np\n'), ((5645, 5690), 'numpy.arange', 'np.arange', (["echogram_params['depth_ticks_num']"], {}), "(echogram_params['depth_ticks_num'])\n", (5654, 5690), True, 'import numpy as np\n'), ((5910, 5955), 'numpy.arange', 'np.arange', (["echogram_params['depth_ticks_num']"], {}), "(echogram_params['depth_ticks_num'])\n", (5919, 5955), True, 'import numpy as np\n'), ((6536, 6560), 'numpy.array', 'np.array', (['self.frequency'], {}), '(self.frequency)\n', (6544, 6560), True, 'import numpy as np\n')]
# =========================================================================== # This module is created based on the code from 2 libraries: Lasagne and keras # Original work Copyright (c) 2014-2015 keras contributors # Original work Copyright (c) 2014-2015 Lasagne contributors # Modified work Copyright 2016-2017 TrungNT # =========================================================================== from __future__ import division, absolute_import, print_function import numpy as np import scipy as sp from ..config import floatX # =========================================================================== # RandomStates # =========================================================================== _MAGIC_SEED = 12082518 _SEED_GENERATOR = np.random.RandomState(_MAGIC_SEED) def set_magic_seed(seed): global _MAGIC_SEED, _SEED_GENERATOR _MAGIC_SEED = seed _SEED_GENERATOR = np.random.RandomState(_MAGIC_SEED) def get_magic_seed(): return _MAGIC_SEED def get_random_magic_seed(): return _SEED_GENERATOR.randint(10e6) def get_random_generator(): return _SEED_GENERATOR # =========================================================================== # Main # =========================================================================== def is_ndarray(x): return isinstance(x, np.ndarray) def np_masked_output(X, X_mask): ''' Example ------- X: [[1,2,3,0,0], [4,5,0,0,0]] X_mask: [[1,2,3,0,0], [4,5,0,0,0]] return: [[1,2,3],[4,5]] ''' res = [] for x, mask in zip(X, X_mask): x = x[np.nonzero(mask)] res.append(x.tolist()) return res def np_one_hot(y, n_classes=None): '''Convert class vector (integers from 0 to nb_classes) to binary class matrix, for use with categorical_crossentropy ''' y = np.asarray(y, dtype='int32') if not n_classes: n_classes = np.max(y) + 1 Y = np.zeros((len(y), n_classes)) for i in range(len(y)): Y[i, y[i]] = 1. return Y def np_split_chunks(a, maxlen, overlap): ''' Example ------- >>> print(split_chunks(np.array([1, 2, 3, 4, 5, 6, 7, 8]), 5, 1)) >>> [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8]] ''' chunks = [] nchunks = int((max(a.shape) - maxlen) / (maxlen - overlap)) + 1 for i in xrange(nchunks): start = i * (maxlen - overlap) chunks.append(a[start: start + maxlen]) # ====== Some spare frames at the end ====== # wasted = max(a.shape) - start - maxlen if wasted >= (maxlen - overlap) / 2: chunks.append(a[-maxlen:]) return chunks def np_ordered_set(seq): seen = {} result = [] for marker in seq: if marker in seen: continue seen[marker] = 1 result.append(marker) return np.asarray(result) def np_shrink_labels(labels, maxdist=1): ''' Example ------- >>> print(shrink_labels(np.array([0, 0, 1, 0, 1, 1, 0, 0, 4, 5, 4, 6, 6, 0, 0]), 1)) >>> [0, 1, 0, 1, 0, 4, 5, 4, 6, 0] >>> print(shrink_labels(np.array([0, 0, 1, 0, 1, 1, 0, 0, 4, 5, 4, 6, 6, 0, 0]), 2)) >>> [0, 1, 0, 4, 6, 0] Notes ----- Different from ordered_set, the resulted array still contain duplicate if they a far away each other. ''' maxdist = max(1, maxdist) out = [] l = len(labels) i = 0 while i < l: out.append(labels[i]) last_val = labels[i] dist = min(maxdist, l - i - 1) j = 1 while (i + j < l and labels[i + j] == last_val) or (j < dist): j += 1 i += j return out # =========================================================================== # Special random algorithm for weights initialization # =========================================================================== def np_normal(shape, mean=0., std=1.): return np.cast[floatX()]( get_random_generator().normal(mean, std, size=shape)) def np_uniform(shape, range=0.05): if isinstance(range, (int, float, long)): range = (-abs(range), abs(range)) return np.cast[floatX()]( get_random_generator().uniform(low=range[0], high=range[1], size=shape)) def np_constant(shape, val=0.): return np.cast[floatX()](np.zeros(shape) + val) def np_symmetric_uniform(shape, range=0.01, std=None, mean=0.0): if std is not None: a = mean - np.sqrt(3) * std b = mean + np.sqrt(3) * std else: try: a, b = range # range is a tuple except TypeError: a, b = -range, range # range is a number return np.cast[floatX()]( get_random_generator().uniform(low=a, high=b, size=shape)) def np_glorot_uniform(shape, gain=1.0, c01b=False): orig_shape = shape if c01b: if len(shape) != 4: raise RuntimeError( "If c01b is True, only shapes of length 4 are accepted") n1, n2 = shape[0], shape[3] receptive_field_size = shape[1] * shape[2] else: if len(shape) < 2: shape = (1,) + tuple(shape) n1, n2 = shape[:2] receptive_field_size = np.prod(shape[2:]) std = gain * np.sqrt(2.0 / ((n1 + n2) * receptive_field_size)) a = 0.0 - np.sqrt(3) * std b = 0.0 + np.sqrt(3) * std return np.cast[floatX()]( get_random_generator().uniform(low=a, high=b, size=orig_shape)) def np_glorot_normal(shape, gain=1.0, c01b=False): orig_shape = shape if c01b: if len(shape) != 4: raise RuntimeError( "If c01b is True, only shapes of length 4 are accepted") n1, n2 = shape[0], shape[3] receptive_field_size = shape[1] * shape[2] else: if len(shape) < 2: shape = (1,) + tuple(shape) n1, n2 = shape[:2] receptive_field_size = np.prod(shape[2:]) std = gain * np.sqrt(2.0 / ((n1 + n2) * receptive_field_size)) return np.cast[floatX()]( get_random_generator().normal(0.0, std, size=orig_shape)) def np_he_normal(shape, gain=1.0, c01b=False): if gain == 'relu': gain = np.sqrt(2) if c01b: if len(shape) != 4: raise RuntimeError( "If c01b is True, only shapes of length 4 are accepted") fan_in = np.prod(shape[:3]) else: if len(shape) <= 2: fan_in = shape[0] elif len(shape) > 2: fan_in = np.prod(shape[1:]) std = gain * np.sqrt(1.0 / fan_in) return np.cast[floatX()]( get_random_generator().normal(0.0, std, size=shape)) def np_he_uniform(shape, gain=1.0, c01b=False): if gain == 'relu': gain = np.sqrt(2) if c01b: if len(shape) != 4: raise RuntimeError( "If c01b is True, only shapes of length 4 are accepted") fan_in = np.prod(shape[:3]) else: if len(shape) <= 2: fan_in = shape[0] elif len(shape) > 2: fan_in = np.prod(shape[1:]) std = gain * np.sqrt(1.0 / fan_in) a = 0.0 - np.sqrt(3) * std b = 0.0 + np.sqrt(3) * std return np.cast[floatX()]( get_random_generator().uniform(low=a, high=b, size=shape)) def np_orthogonal(shape, gain=1.0): if gain == 'relu': gain = np.sqrt(2) if len(shape) < 2: raise RuntimeError("Only shapes of length 2 or more are supported.") flat_shape = (shape[0], np.prod(shape[1:])) a = get_random_generator().normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) # pick the one with the correct shape q = u if u.shape == flat_shape else v q = q.reshape(shape) return np.cast[floatX()](gain * q)
[ "numpy.prod", "numpy.sqrt", "numpy.asarray", "numpy.max", "numpy.zeros", "numpy.nonzero", "numpy.linalg.svd", "numpy.random.RandomState" ]
[((745, 779), 'numpy.random.RandomState', 'np.random.RandomState', (['_MAGIC_SEED'], {}), '(_MAGIC_SEED)\n', (766, 779), True, 'import numpy as np\n'), ((893, 927), 'numpy.random.RandomState', 'np.random.RandomState', (['_MAGIC_SEED'], {}), '(_MAGIC_SEED)\n', (914, 927), True, 'import numpy as np\n'), ((1848, 1876), 'numpy.asarray', 'np.asarray', (['y'], {'dtype': '"""int32"""'}), "(y, dtype='int32')\n", (1858, 1876), True, 'import numpy as np\n'), ((2813, 2831), 'numpy.asarray', 'np.asarray', (['result'], {}), '(result)\n', (2823, 2831), True, 'import numpy as np\n'), ((7485, 7522), 'numpy.linalg.svd', 'np.linalg.svd', (['a'], {'full_matrices': '(False)'}), '(a, full_matrices=False)\n', (7498, 7522), True, 'import numpy as np\n'), ((5129, 5147), 'numpy.prod', 'np.prod', (['shape[2:]'], {}), '(shape[2:])\n', (5136, 5147), True, 'import numpy as np\n'), ((5166, 5215), 'numpy.sqrt', 'np.sqrt', (['(2.0 / ((n1 + n2) * receptive_field_size))'], {}), '(2.0 / ((n1 + n2) * receptive_field_size))\n', (5173, 5215), True, 'import numpy as np\n'), ((5824, 5842), 'numpy.prod', 'np.prod', (['shape[2:]'], {}), '(shape[2:])\n', (5831, 5842), True, 'import numpy as np\n'), ((5861, 5910), 'numpy.sqrt', 'np.sqrt', (['(2.0 / ((n1 + n2) * receptive_field_size))'], {}), '(2.0 / ((n1 + n2) * receptive_field_size))\n', (5868, 5910), True, 'import numpy as np\n'), ((6094, 6104), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (6101, 6104), True, 'import numpy as np\n'), ((6269, 6287), 'numpy.prod', 'np.prod', (['shape[:3]'], {}), '(shape[:3])\n', (6276, 6287), True, 'import numpy as np\n'), ((6443, 6464), 'numpy.sqrt', 'np.sqrt', (['(1.0 / fan_in)'], {}), '(1.0 / fan_in)\n', (6450, 6464), True, 'import numpy as np\n'), ((6644, 6654), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (6651, 6654), True, 'import numpy as np\n'), ((6819, 6837), 'numpy.prod', 'np.prod', (['shape[:3]'], {}), '(shape[:3])\n', (6826, 6837), True, 'import numpy as np\n'), ((6993, 7014), 'numpy.sqrt', 'np.sqrt', (['(1.0 / fan_in)'], {}), '(1.0 / fan_in)\n', (7000, 7014), True, 'import numpy as np\n'), ((7250, 7260), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (7257, 7260), True, 'import numpy as np\n'), ((7391, 7409), 'numpy.prod', 'np.prod', (['shape[1:]'], {}), '(shape[1:])\n', (7398, 7409), True, 'import numpy as np\n'), ((1605, 1621), 'numpy.nonzero', 'np.nonzero', (['mask'], {}), '(mask)\n', (1615, 1621), True, 'import numpy as np\n'), ((1919, 1928), 'numpy.max', 'np.max', (['y'], {}), '(y)\n', (1925, 1928), True, 'import numpy as np\n'), ((4253, 4268), 'numpy.zeros', 'np.zeros', (['shape'], {}), '(shape)\n', (4261, 4268), True, 'import numpy as np\n'), ((5230, 5240), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (5237, 5240), True, 'import numpy as np\n'), ((5261, 5271), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (5268, 5271), True, 'import numpy as np\n'), ((7029, 7039), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (7036, 7039), True, 'import numpy as np\n'), ((7060, 7070), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (7067, 7070), True, 'import numpy as np\n'), ((4386, 4396), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (4393, 4396), True, 'import numpy as np\n'), ((4422, 4432), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (4429, 4432), True, 'import numpy as np\n'), ((6406, 6424), 'numpy.prod', 'np.prod', (['shape[1:]'], {}), '(shape[1:])\n', (6413, 6424), True, 'import numpy as np\n'), ((6956, 6974), 'numpy.prod', 'np.prod', (['shape[1:]'], {}), '(shape[1:])\n', (6963, 6974), True, 'import numpy as np\n')]
''' Collection of algorithms for transforming coordinates commoly used in Geophysics. Glossary: --------- Geocentric Geodetic Coordinates (GGC) Geocentric Geodetic System (GGS) Geocentric Cartesian Coordinates (GCC) Geocentric Cartesian System (GCS) Geocentric Spherical Coordinates (GSC) Geocentric Spherical System (GSS) Topocentric Cartesian Coordinates (TCC) Topocentric Cartesian System (TCS) ''' import numpy as np from . import utils def GGC2GCC(height, latitude, longitude, major_semiaxis, minor_semiaxis): ''' Transform GGC into GCC. Parameters: ----------- height: numpy array 1D Vector containing the geometric height (in meters). latitude: numpy array 1D Vector containing the latitude (in degrees). longitude: numpy array 1D Vector containing the longitude (in degrees). major_semiaxis: float Major semiaxis of the reference ellipsoid (in meters). minor_semiaxis: float Minor semiaxis of the reference ellipsoid (in meters). Returns: -------- X: numpy array 1D Vector containing the X component of the Cartesian coordinates (in meters). Y: numpy array 1D Vector containing the X component of the Cartesian coordinates (in meters). Z: numpy array 1D Vector containing the Z component of the Cartesian coordinates (in meters). ''' h = np.asarray(height) lat = np.asarray(latitude) lon = np.asarray(longitude) assert (h.size == lat.size == lon.size), 'height, latitude \ and longitude must have the same number of elements' assert (major_semiaxis > minor_semiaxis), 'major_semiaxis must be greater \ than the minor_semiaxis' #Prime vertical radius of curvature N = utils.prime_vertical_curv(major_semiaxis, minor_semiaxis, lat) # convert degrees to radians lat = np.deg2rad(lat) lon = np.deg2rad(lon) aux = N + height # squared first eccentricity e2 = (major_semiaxis**2. - minor_semiaxis**2.)/(major_semiaxis**2.) clat = np.cos(lat) slat = np.sin(lat) clon = np.cos(lon) slon = np.sin(lon) X = aux*clat*clon Y = aux*clat*slon Z = (N*(1 - e2) + height)*slat return X, Y, Z def GCC2GGC(X, Y, Z, major_semiaxis, minor_semiaxis, itmax = 5): ''' Convert GCC into GGC by using the Hirvonen-Moritz algorithm (Hofmann-Wellenhof and Moritz, 2005, p. 193). Parameters: ----------- X: numpy array 1D or float Vector containing the x component of the Cartesian coordinates (in meters). Y: numpy array 1D or float Vector containing the y component of the Cartesian coordinates (in meters). Z: numpy array 1D or float Vector containing the z component of the Cartesian coordinates (in meters). major_semiaxis: float Major semiaxis of the reference ellipsoid (in meters). minor_semiaxis: float Minor semiaxis of the reference ellipsoid (in meters). itmax: int Maximum number of iterations in the Hirvonen-Moritz algorithm. Default is 5. Returns: -------- height: numpy array 1D Vector containing the geometric height (in meters). latitude: numpy array 1D Vector containing the latitude (in degrees). longitude: numpy array 1D Vector containing the longitude (in degrees). ''' x = np.asarray(X) y = np.asarray(Y) z = np.asarray(Z) assert (x.size == y.size == z.size), \ 'x, y and z must have the same number of elements' assert (major_semiaxis > minor_semiaxis), 'major_semiaxis must be greater \ than the minor_semiaxis' # horizontal distance p = np.sqrt(x**2. + y**2.) # null and non-null horizontal distances p_non_null = (p >= 1e-8) p_null = np.logical_not(p_non_null) lon = np.zeros_like(x) lat = np.zeros_like(x) height = np.zeros_like(x) # squared first eccentricity e2 = (major_semiaxis**2. - minor_semiaxis**2.)/(major_semiaxis**2.) aux1 = z[p_non_null]/p[p_non_null] aux2 = 1.- e2 # define the coordinates for null horizontal distances lon[p_null] = 0. height[p_null] = np.abs(z[p_null]) - minor_semiaxis lat[p_null] = np.sign(z[p_null])*np.pi*0.5 # first iteration lat[p_non_null] = np.arctan(aux1/aux2) sinlat = np.sin(lat[p_non_null]) N = major_semiaxis/np.sqrt(1 - e2*sinlat*sinlat) height[p_non_null] = p[p_non_null]/np.cos(lat[p_non_null]) - N for i in range(itmax): aux3 = e2*N/(N + height[p_non_null]) lat[p_non_null] = np.arctan(aux1/(1.-aux3)) sinlat = np.sin(lat[p_non_null]) N = major_semiaxis/np.sqrt(1 - e2*sinlat*sinlat) height[p_non_null] = p[p_non_null]/np.cos(lat[p_non_null]) - N lon[p_non_null] = np.arctan2(y[p_non_null], x[p_non_null]) # convert latitude and longitude from radians to degrees latitude = np.rad2deg(lat) longitude = np.rad2deg(lon) return height, latitude, longitude def GCC2GGC_approx(X, Y, Z, major_semiaxis, minor_semiaxis): ''' Convert GCC into GGC by using an approximated formula (Hofmann-Wellenhof and Moritz, 2005, p. 196). Parameters: ----------- X: numpy array 1D or float Vector containing the x component of the Cartesian coordinates (in meters). Y: numpy array 1D or float Vector containing the y component of the Cartesian coordinates (in meters). Z: numpy array 1D or float Vector containing the z component of the Cartesian coordinates (in meters). major_semiaxis: float Major semiaxis of the reference ellipsoid (in meters). minor_semiaxis: float Minor semiaxis of the reference ellipsoid (in meters). Returns: -------- height: numpy array 1D Vector containing the geometric height (in meters). latitude: numpy array 1D Vector containing the latitude (in degrees). longitude: numpy array 1D Vector containing the longitude (in degrees). ''' x = np.asarray(X) y = np.asarray(Y) z = np.asarray(Z) assert (x.size == y.size == z.size), \ 'x, y and z must have the same number of elements' assert (major_semiaxis > minor_semiaxis), 'major_semiaxis must be greater \ than the minor_semiaxis' # horizontal distance p = np.sqrt(x**2. + y**2.) # null and non-null horizontal distances p_non_null = (p >= 1e-8) p_null = np.logical_not(p_non_null) lon = np.zeros_like(x) lat = np.zeros_like(x) height = np.zeros_like(x) # define the coordinates for null horizontal distances lon[p_null] = 0. height[p_null] = np.abs(z[p_null]) - minor_semiaxis lat[p_null] = np.sign(z[p_null])*np.pi*0.5 # squared first eccentricity e2 = (major_semiaxis**2. - minor_semiaxis**2.)/(major_semiaxis**2.) # squared second eccentricity elinha2 = (major_semiaxis**2. - minor_semiaxis**2.)/(minor_semiaxis**2.) # auxiliary variable theta = np.arctan( z[p_non_null]*major_semiaxis/(p[p_non_null]*minor_semiaxis) ) sintheta = np.sin(theta) costheta = np.cos(theta) aux1 = z[p_non_null] + elinha2*minor_semiaxis*sintheta*sintheta*sintheta aux2 = p[p_non_null] - e2*major_semiaxis*costheta*costheta*costheta #lat[p_non_null] = np.arctan(aux1/aux2) lat[p_non_null] = np.arctan2(aux1, aux2) #lon[p_non_null] = np.arctan(y[p_non_null]/x[p_non_null]) lon[p_non_null] = np.arctan2(y[p_non_null], x[p_non_null]) sinlat = np.sin(lat[p_non_null]) N = major_semiaxis/np.sqrt(1 - e2*sinlat*sinlat) height[p_non_null] = p[p_non_null]/np.cos(lat[p_non_null]) - N # convert latitude and longitude from radians to degrees latitude = np.rad2deg(lat) longitude = np.rad2deg(lon) return height, latitude, longitude def GCC2TCC(X, Y, Z, X0, Y0, Z0, latitude_0, longitude_0): ''' Convert GCC into TCC with origin at a point Q = (X0, Y0, Z0). The point Q has latitude and longitude given by latitude_0 and longitude_0, respectively. This TCS has axis x pointing to north, axis z pointing to the inward normal and axis y completing the right-handed system. If latitude_0 is geodetic, then the computed normal is defined with respect to the referrence elipsoid. If latitude_0 is spherical, then the normal is defined with respect to a sphere. The transformation is computed as follows: x = vX*(X - X0) + vY*(Y - Y0) + vZ*(Z - Z0) y = wX*(X - X0) + wY*(Y - Y0) z = -uX*(X - X0) - uY*(Y - Y0) - uZ*(Z - Z0) where uX, uY, uZ, vX, vY, vZ, wX, and wy are components of the unit vectors (referred to the GCS) pointing to the orthogonal directions of the GGS at the point Q. Parameters: ----------- X, Y, Z: numpy arrays 1D Vectors containing the coordinates x, y and z (in meters), respectively, of the points referred to the GCS. X0, Y0, Z0: floats Coordinates of the origin in the GCS. latitude_0: float Latitude (in degrees) of the origin Q. longitude_0: float Longitude (in degrees) of the origin Q. Returns: -------- x: numpy array 1D Vector containing the x component of TCC (in meters). y: numpy array 1D Vector containing the y component of TCC (in meters). z: numpy array 1D Vector containing the z component of TCC (in meters). ''' X = np.asarray(X) Y = np.asarray(Y) Z = np.asarray(Z) assert (X.shape == Y.shape == Z.shape), 'X, Y and Z must have the same \ shape' assert np.isscalar(X0), 'X0 must be a scalar' assert np.isscalar(Y0), 'Y0 must be a scalar' assert np.isscalar(Z0), 'Z0 must be a scalar' assert np.isscalar(latitude_0), 'latitude_0 must be a scalar' assert np.isscalar(longitude_0), 'longitude_0 must be a scalar' # Differences in Geocentric Cartesian Coordinates DX = X - X0 DY = Y - Y0 DZ = Z - Z0 # Unit vectors pointing to the orthogonal directions of the # Geocentric Geodetic System at the origin Q uX, uY, uZ = utils.unit_vector_normal(latitude_0, longitude_0) vX, vY, vZ = utils.unit_vector_latitude(latitude_0, longitude_0) wX, wY = utils.unit_vector_longitude(longitude_0) # Coordinates in the Topocentric Cartesian System with origin at Q x = vX*DX + vY*DY + vZ*DZ y = wX*DX + wY*DY z = -uX*DX - uY*DY - uZ*DZ return x, y, z def TCC2GCC(x, y, z, X0, Y0, Z0, latitude_0, longitude_0): ''' Convert TCC with origin at a point Q into GCC. The point Q has GCC coordinates (X0, Y0, Z0) and also the coordinates latitude_0 and longitude_0. This TCS has axis x pointing to north, axis z pointing to the inward normal and axis y completing the right-handed system. If latitude_0 is defined in the GGS, then the computed normal is defined with respect to the referrence elipsoid. If latitude_0 is defined in the GSS, then the normal is defined with respect to a sphere. The transformation is computed as follows: X = vX*x + wX*y - uX*z + X0 Y = vY*x + wY*y - uY*z + Y0 Z = vZ*x - uZ*z + Z0 where uX, uY, uZ, vX, vY, vZ, wX, and wy are components of the unit vectors (referred to the GCS) pointing to the orthogonal directions of the GGS at the point Q. Parameters: ----------- x, y, z: numpy arrays 1D Vectors containing the coordinates x, y and z (in meters), respectively, of the points referred to the TCS. X0, Y0, Z0: floats Coordinates of the TGCS origin in the GCS. latitude_0: float Latitude (in degrees) of the origin Q. longitude_0: float Longitude (in degrees) of the origin Q. Returns: -------- X, Y, Z: numpy arrays 1D Vectors containing the coordinates X, Y and Z (in meters), respectively, of the points referred to the GCS. ''' x = np.asarray(x) y = np.asarray(y) z = np.asarray(z) assert (x.size == y.size == z.size), 'x, y and z must have the same size' assert np.isscalar(X0), 'X0 must be a scalar' assert np.isscalar(Y0), 'Y0 must be a scalar' assert np.isscalar(Z0), 'Z0 must be a scalar' assert np.isscalar(latitude_0), 'latitude_0 must be a scalar' assert np.isscalar(longitude_0), 'longitude_0 must be a scalar' # Unit vectors pointing to the orthogonal directions of the # Geocentric Geodetic System at the origin Q uX, uY, uZ = utils.unit_vector_normal(latitude_0, longitude_0) vX, vY, vZ = utils.unit_vector_latitude(latitude_0, longitude_0) wX, wY = utils.unit_vector_longitude(longitude_0) # Coordinates in the GCS X = vX*x + wX*y - uX*z + X0 Y = vY*x + wY*y - uY*z + Y0 Z = vZ*x - uZ*z + Z0 return X, Y, Z def GSC2GCC(radius, latitude, longitude): ''' Transform GSC into GCC. For each point, the tranformation is given by: X = radius * cos(latitude) * cos(longitude) Y = radius * cos(latitude) * sin(longitude) Z = radius * sin(latitude) Parameters: ----------- radius: numpy array 1D float Radial coordinates (in meters) to be transformed. latitude, longitude: numpy arrays 1D Spherical latitude and longitude (in degrees) to be transformed. Returns: -------- X, Y, Z: numpy arrays 1D Computed Cartesian coordinates (in meters). ''' radius = np.asarray(radius) latitude = np.asarray(latitude) longitude = np.asarray(longitude) assert radius.size == latitude.size == longitude.size, 'radius, latitude \ and longitude must have the same number of elements' latitude_max = np.max(latitude) latitude_min = np.min(latitude) assert latitude_max <= 90, 'maximum latitude must be <= 90 degrees' assert latitude_min >= -90, 'minimum latitude must be >= -90 degrees' # convert degrees to radian lat = np.deg2rad(latitude) lon = np.deg2rad(longitude) cos_lat = np.cos(lat) sin_lat = np.sin(lat) cos_lon = np.cos(lon) sin_lon = np.sin(lon) X = radius*cos_lat*cos_lon Y = radius*cos_lat*sin_lon Z = radius*sin_lat return X, Y, Z def GCC2GSC(X, Y, Z): ''' Transform GCC into GSC. For each point, the tranformation is given by: radius = sqrt(X**2 + Y**2 + Z**2) latitude = arcsin(Z/sqrt(X**2 + Y**2 + Z**2)) longitude = arctan(Y/X) Parameters: ----------- X, Y, Z: numpy arrays 1D Cartesian coordinates (in meters) to be transformed. Returns: -------- radius: numpy array 1D float Computed radial coordinates (in meters). latitude, longitude: numpy arrays 1D Computed spherical latitude and longitude (in degrees). ''' X = np.asarray(X) Y = np.asarray(Y) Z = np.asarray(Z) assert X.size == Y.size == Z.size, 'X, Y and Z must have the same number \ of elements' # squared horizontal component h2 = X*X + Y*Y radius = np.sqrt(h2 + Z*Z) latitude = np.rad2deg(np.arcsin(Z/radius)) longitude = np.rad2deg(np.arctan2(Y, X)) return radius, latitude, longitude def geodetic2geocentric_latitude(geodetic_latitude, major_semiaxis, minor_semiaxis): ''' Transform geodetic into geocentric latitude. Parameters: ----------- geodetic_latitude: numpy array 1D or float Geodetic latitude (in degrees) to be transformed. major_semiaxis: float Major semiaxis of the reference ellipsoid (in meters). minor_semiaxis: float Minor semiaxis of the reference ellipsoid (in meters). Returns: -------- geocentric_latitude: numpy array 1D or float Computed geocentric latitude (in degrees). ''' assert np.isscalar(major_semiaxis), 'major_semiaxis must be a scalar' assert np.isscalar(minor_semiaxis), 'minor_semiaxis must be a scalar' assert (major_semiaxis > minor_semiaxis), 'major_semiaxis must be greater \ than the minor_semiaxis' latitude = np.deg2rad(geodetic_latitude) aux = (minor_semiaxis*minor_semiaxis)/(major_semiaxis*major_semiaxis) geocentric_latitude = np.rad2deg(np.arctan(aux*np.tan(latitude))) return geocentric_latitude def geocentric2geodetic_latitude(geocentric_latitude, major_semiaxis, minor_semiaxis): ''' Transform geocentric into geodetic latitude. Parameters: ----------- geocentric_latitude: numpy array 1D or float Geocentric latitude (in degrees) to be transformed. major_semiaxis: float Major semiaxis of the reference ellipsoid (in meters). minor_semiaxis: float Minor semiaxis of the reference ellipsoid (in meters). Returns: -------- geodetic_latitude: numpy array 1D or float Computed geodetic latitude (in degrees). ''' assert np.isscalar(major_semiaxis), 'major_semiaxis must be a scalar' assert np.isscalar(minor_semiaxis), 'minor_semiaxis must be a scalar' assert (major_semiaxis > minor_semiaxis), 'major_semiaxis must be greater \ than the minor_semiaxis' latitude = np.deg2rad(geocentric_latitude) aux = (minor_semiaxis*minor_semiaxis)/(major_semiaxis*major_semiaxis) geodetic_latitude = np.rad2deg(np.arctan(np.tan(latitude)/aux)) return geodetic_latitude def molodensky_complete( height1, latitude1, longitude1, major_semiaxis1, flattening1, major_semiaxis2, flattening2, dX, dY, dZ ): ''' Transform GGC (height1, latitude1, longitude1) referred to an ellispoid 1 into GGC (height2, latitude2, longitude2) referred to an ellispoid 2 by using the complete Molodensky's formulas (Rapp, 1993, p. 79). Parameters: ----------- height1: numpy array 1D Vector containing heights referred to ellipsoid 1 (in meters). latitude1: numpy array 1D Vector containing latitudes referred to ellipsoid 1 (in degrees). longitude1: numpy array 1D Vector containing longitudes referred to ellipsoid 1 (in degrees). major_semiaxis1: float Major semiaxis of ellipsoid 1 (in meters). flattening1: float Flattening of ellipsoid 1 (in meters). major_semiaxis2: float Major semiaxis of ellipsoid 2 (in meters). flattening2: float Flattening of ellipsoid 2 (in meters). dX: float Translation of ellipsoid 2 with relative to ellipsoid 1 (in meters) along X axis of GCS. dY: float Translation of ellipsoid 2 with relative to ellipsoid 1 (in meters) along Y axis of GCS. dZ: float Translation of ellipsoid 2 with relative to ellipsoid 1 (in meters) along Z axis of GCS. Returns: -------- height2: numpy array 1D Vector containing heights referred to ellipsoid 2 (in meters). latitude2: numpy array 1D Vector containing latitudes referred to ellipsoid 2 (in degrees). longitude2: numpy array 1D Vector containing longitudes referred to ellipsoid 2 (in degrees). ''' assert (height1.size == latitude1.size == longitude1.size), \ 'height1, latitude1, andlongitude1 must have the same size' assert (flattening1 < major_semiaxis1), 'flattening1 must be smaller than \ major_semiaxis1' assert (flattening2 < major_semiaxis2), 'flattening2 must be smaller than \ major_semiaxis2' sinlat = np.sin(np.deg2rad(latitude1)) coslat = np.cos(np.deg2rad(latitude1)) sinlon = np.sin(np.deg2rad(longitude1)) coslon = np.cos(np.deg2rad(longitude1)) da = major_semiaxis2 - major_semiaxis1 df = flattening2 - flattening1 a = major_semiaxis1 + 0.5*da f = flattening1 + 0.5*df b = (1. - f)*a e2 = (a**2. - b**2.)/a**2. W = np.sqrt(1. - e2*(sinlat**2.)) W[W < 1e-10] == 1e-10 M = a*(1. - e2)/(W**3.) N = a/W dlat_dX = -sinlat*coslon dlat_dY = -sinlat*sinlon dlat_dZ = coslat dlat_da = e2*sinlat*coslat/W dlat_df = sinlat*coslat*(M*a/b + N*b/a) dlon_dX = -sinlon dlon_dY = coslon dh_dX = coslat*coslon dh_dY = coslat*sinlon dh_dZ = sinlat dh_da = -W dh_df = a*(1. - f)*(sinlat**2.)/W dlat = (dlat_dX*dX + dlat_dY*dY + dlat_dZ*dZ + dlat_da*da + dlat_df*df) dlat /= (M + height1) dlon = (dlon_dX*dX + dlon_dY*dY)/((N + height1)*coslat) dh = dh_dX*dX + dh_dY*dY + dh_dZ*dZ + dh_da*da + dh_df*df height2 = height1 + dh latitude2 = latitude1 + dlat longitude2 = longitude1 + dlon return height2, latitude2, longitude2
[ "numpy.abs", "numpy.sqrt", "numpy.isscalar", "numpy.tan", "numpy.logical_not", "numpy.asarray", "numpy.arcsin", "numpy.max", "numpy.deg2rad", "numpy.arctan2", "numpy.cos", "numpy.sign", "numpy.min", "numpy.sin", "numpy.rad2deg", "numpy.zeros_like", "numpy.arctan" ]
[((1405, 1423), 'numpy.asarray', 'np.asarray', (['height'], {}), '(height)\n', (1415, 1423), True, 'import numpy as np\n'), ((1434, 1454), 'numpy.asarray', 'np.asarray', (['latitude'], {}), '(latitude)\n', (1444, 1454), True, 'import numpy as np\n'), ((1465, 1486), 'numpy.asarray', 'np.asarray', (['longitude'], {}), '(longitude)\n', (1475, 1486), True, 'import numpy as np\n'), ((1867, 1882), 'numpy.deg2rad', 'np.deg2rad', (['lat'], {}), '(lat)\n', (1877, 1882), True, 'import numpy as np\n'), ((1893, 1908), 'numpy.deg2rad', 'np.deg2rad', (['lon'], {}), '(lon)\n', (1903, 1908), True, 'import numpy as np\n'), ((2049, 2060), 'numpy.cos', 'np.cos', (['lat'], {}), '(lat)\n', (2055, 2060), True, 'import numpy as np\n'), ((2072, 2083), 'numpy.sin', 'np.sin', (['lat'], {}), '(lat)\n', (2078, 2083), True, 'import numpy as np\n'), ((2095, 2106), 'numpy.cos', 'np.cos', (['lon'], {}), '(lon)\n', (2101, 2106), True, 'import numpy as np\n'), ((2118, 2129), 'numpy.sin', 'np.sin', (['lon'], {}), '(lon)\n', (2124, 2129), True, 'import numpy as np\n'), ((3404, 3417), 'numpy.asarray', 'np.asarray', (['X'], {}), '(X)\n', (3414, 3417), True, 'import numpy as np\n'), ((3426, 3439), 'numpy.asarray', 'np.asarray', (['Y'], {}), '(Y)\n', (3436, 3439), True, 'import numpy as np\n'), ((3448, 3461), 'numpy.asarray', 'np.asarray', (['Z'], {}), '(Z)\n', (3458, 3461), True, 'import numpy as np\n'), ((3697, 3725), 'numpy.sqrt', 'np.sqrt', (['(x ** 2.0 + y ** 2.0)'], {}), '(x ** 2.0 + y ** 2.0)\n', (3704, 3725), True, 'import numpy as np\n'), ((3808, 3834), 'numpy.logical_not', 'np.logical_not', (['p_non_null'], {}), '(p_non_null)\n', (3822, 3834), True, 'import numpy as np\n'), ((3846, 3862), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (3859, 3862), True, 'import numpy as np\n'), ((3873, 3889), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (3886, 3889), True, 'import numpy as np\n'), ((3903, 3919), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (3916, 3919), True, 'import numpy as np\n'), ((4313, 4335), 'numpy.arctan', 'np.arctan', (['(aux1 / aux2)'], {}), '(aux1 / aux2)\n', (4322, 4335), True, 'import numpy as np\n'), ((4347, 4370), 'numpy.sin', 'np.sin', (['lat[p_non_null]'], {}), '(lat[p_non_null])\n', (4353, 4370), True, 'import numpy as np\n'), ((4808, 4848), 'numpy.arctan2', 'np.arctan2', (['y[p_non_null]', 'x[p_non_null]'], {}), '(y[p_non_null], x[p_non_null])\n', (4818, 4848), True, 'import numpy as np\n'), ((4926, 4941), 'numpy.rad2deg', 'np.rad2deg', (['lat'], {}), '(lat)\n', (4936, 4941), True, 'import numpy as np\n'), ((4958, 4973), 'numpy.rad2deg', 'np.rad2deg', (['lon'], {}), '(lon)\n', (4968, 4973), True, 'import numpy as np\n'), ((6071, 6084), 'numpy.asarray', 'np.asarray', (['X'], {}), '(X)\n', (6081, 6084), True, 'import numpy as np\n'), ((6093, 6106), 'numpy.asarray', 'np.asarray', (['Y'], {}), '(Y)\n', (6103, 6106), True, 'import numpy as np\n'), ((6115, 6128), 'numpy.asarray', 'np.asarray', (['Z'], {}), '(Z)\n', (6125, 6128), True, 'import numpy as np\n'), ((6364, 6392), 'numpy.sqrt', 'np.sqrt', (['(x ** 2.0 + y ** 2.0)'], {}), '(x ** 2.0 + y ** 2.0)\n', (6371, 6392), True, 'import numpy as np\n'), ((6475, 6501), 'numpy.logical_not', 'np.logical_not', (['p_non_null'], {}), '(p_non_null)\n', (6489, 6501), True, 'import numpy as np\n'), ((6513, 6529), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (6526, 6529), True, 'import numpy as np\n'), ((6540, 6556), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (6553, 6556), True, 'import numpy as np\n'), ((6570, 6586), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (6583, 6586), True, 'import numpy as np\n'), ((7027, 7103), 'numpy.arctan', 'np.arctan', (['(z[p_non_null] * major_semiaxis / (p[p_non_null] * minor_semiaxis))'], {}), '(z[p_non_null] * major_semiaxis / (p[p_non_null] * minor_semiaxis))\n', (7036, 7103), True, 'import numpy as np\n'), ((7127, 7140), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (7133, 7140), True, 'import numpy as np\n'), ((7156, 7169), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (7162, 7169), True, 'import numpy as np\n'), ((7387, 7409), 'numpy.arctan2', 'np.arctan2', (['aux1', 'aux2'], {}), '(aux1, aux2)\n', (7397, 7409), True, 'import numpy as np\n'), ((7494, 7534), 'numpy.arctan2', 'np.arctan2', (['y[p_non_null]', 'x[p_non_null]'], {}), '(y[p_non_null], x[p_non_null])\n', (7504, 7534), True, 'import numpy as np\n'), ((7549, 7572), 'numpy.sin', 'np.sin', (['lat[p_non_null]'], {}), '(lat[p_non_null])\n', (7555, 7572), True, 'import numpy as np\n'), ((7771, 7786), 'numpy.rad2deg', 'np.rad2deg', (['lat'], {}), '(lat)\n', (7781, 7786), True, 'import numpy as np\n'), ((7803, 7818), 'numpy.rad2deg', 'np.rad2deg', (['lon'], {}), '(lon)\n', (7813, 7818), True, 'import numpy as np\n'), ((9464, 9477), 'numpy.asarray', 'np.asarray', (['X'], {}), '(X)\n', (9474, 9477), True, 'import numpy as np\n'), ((9486, 9499), 'numpy.asarray', 'np.asarray', (['Y'], {}), '(Y)\n', (9496, 9499), True, 'import numpy as np\n'), ((9508, 9521), 'numpy.asarray', 'np.asarray', (['Z'], {}), '(Z)\n', (9518, 9521), True, 'import numpy as np\n'), ((9618, 9633), 'numpy.isscalar', 'np.isscalar', (['X0'], {}), '(X0)\n', (9629, 9633), True, 'import numpy as np\n'), ((9668, 9683), 'numpy.isscalar', 'np.isscalar', (['Y0'], {}), '(Y0)\n', (9679, 9683), True, 'import numpy as np\n'), ((9718, 9733), 'numpy.isscalar', 'np.isscalar', (['Z0'], {}), '(Z0)\n', (9729, 9733), True, 'import numpy as np\n'), ((9768, 9791), 'numpy.isscalar', 'np.isscalar', (['latitude_0'], {}), '(latitude_0)\n', (9779, 9791), True, 'import numpy as np\n'), ((9834, 9858), 'numpy.isscalar', 'np.isscalar', (['longitude_0'], {}), '(longitude_0)\n', (9845, 9858), True, 'import numpy as np\n'), ((11961, 11974), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (11971, 11974), True, 'import numpy as np\n'), ((11983, 11996), 'numpy.asarray', 'np.asarray', (['y'], {}), '(y)\n', (11993, 11996), True, 'import numpy as np\n'), ((12005, 12018), 'numpy.asarray', 'np.asarray', (['z'], {}), '(z)\n', (12015, 12018), True, 'import numpy as np\n'), ((12109, 12124), 'numpy.isscalar', 'np.isscalar', (['X0'], {}), '(X0)\n', (12120, 12124), True, 'import numpy as np\n'), ((12159, 12174), 'numpy.isscalar', 'np.isscalar', (['Y0'], {}), '(Y0)\n', (12170, 12174), True, 'import numpy as np\n'), ((12209, 12224), 'numpy.isscalar', 'np.isscalar', (['Z0'], {}), '(Z0)\n', (12220, 12224), True, 'import numpy as np\n'), ((12259, 12282), 'numpy.isscalar', 'np.isscalar', (['latitude_0'], {}), '(latitude_0)\n', (12270, 12282), True, 'import numpy as np\n'), ((12325, 12349), 'numpy.isscalar', 'np.isscalar', (['longitude_0'], {}), '(longitude_0)\n', (12336, 12349), True, 'import numpy as np\n'), ((13455, 13473), 'numpy.asarray', 'np.asarray', (['radius'], {}), '(radius)\n', (13465, 13473), True, 'import numpy as np\n'), ((13489, 13509), 'numpy.asarray', 'np.asarray', (['latitude'], {}), '(latitude)\n', (13499, 13509), True, 'import numpy as np\n'), ((13526, 13547), 'numpy.asarray', 'np.asarray', (['longitude'], {}), '(longitude)\n', (13536, 13547), True, 'import numpy as np\n'), ((13700, 13716), 'numpy.max', 'np.max', (['latitude'], {}), '(latitude)\n', (13706, 13716), True, 'import numpy as np\n'), ((13736, 13752), 'numpy.min', 'np.min', (['latitude'], {}), '(latitude)\n', (13742, 13752), True, 'import numpy as np\n'), ((13942, 13962), 'numpy.deg2rad', 'np.deg2rad', (['latitude'], {}), '(latitude)\n', (13952, 13962), True, 'import numpy as np\n'), ((13973, 13994), 'numpy.deg2rad', 'np.deg2rad', (['longitude'], {}), '(longitude)\n', (13983, 13994), True, 'import numpy as np\n'), ((14010, 14021), 'numpy.cos', 'np.cos', (['lat'], {}), '(lat)\n', (14016, 14021), True, 'import numpy as np\n'), ((14036, 14047), 'numpy.sin', 'np.sin', (['lat'], {}), '(lat)\n', (14042, 14047), True, 'import numpy as np\n'), ((14062, 14073), 'numpy.cos', 'np.cos', (['lon'], {}), '(lon)\n', (14068, 14073), True, 'import numpy as np\n'), ((14088, 14099), 'numpy.sin', 'np.sin', (['lon'], {}), '(lon)\n', (14094, 14099), True, 'import numpy as np\n'), ((14784, 14797), 'numpy.asarray', 'np.asarray', (['X'], {}), '(X)\n', (14794, 14797), True, 'import numpy as np\n'), ((14806, 14819), 'numpy.asarray', 'np.asarray', (['Y'], {}), '(Y)\n', (14816, 14819), True, 'import numpy as np\n'), ((14828, 14841), 'numpy.asarray', 'np.asarray', (['Z'], {}), '(Z)\n', (14838, 14841), True, 'import numpy as np\n'), ((15004, 15023), 'numpy.sqrt', 'np.sqrt', (['(h2 + Z * Z)'], {}), '(h2 + Z * Z)\n', (15011, 15023), True, 'import numpy as np\n'), ((15794, 15821), 'numpy.isscalar', 'np.isscalar', (['major_semiaxis'], {}), '(major_semiaxis)\n', (15805, 15821), True, 'import numpy as np\n'), ((15868, 15895), 'numpy.isscalar', 'np.isscalar', (['minor_semiaxis'], {}), '(minor_semiaxis)\n', (15879, 15895), True, 'import numpy as np\n'), ((16052, 16081), 'numpy.deg2rad', 'np.deg2rad', (['geodetic_latitude'], {}), '(geodetic_latitude)\n', (16062, 16081), True, 'import numpy as np\n'), ((16900, 16927), 'numpy.isscalar', 'np.isscalar', (['major_semiaxis'], {}), '(major_semiaxis)\n', (16911, 16927), True, 'import numpy as np\n'), ((16974, 17001), 'numpy.isscalar', 'np.isscalar', (['minor_semiaxis'], {}), '(minor_semiaxis)\n', (16985, 17001), True, 'import numpy as np\n'), ((17158, 17189), 'numpy.deg2rad', 'np.deg2rad', (['geocentric_latitude'], {}), '(geocentric_latitude)\n', (17168, 17189), True, 'import numpy as np\n'), ((19783, 19816), 'numpy.sqrt', 'np.sqrt', (['(1.0 - e2 * sinlat ** 2.0)'], {}), '(1.0 - e2 * sinlat ** 2.0)\n', (19790, 19816), True, 'import numpy as np\n'), ((4186, 4203), 'numpy.abs', 'np.abs', (['z[p_null]'], {}), '(z[p_null])\n', (4192, 4203), True, 'import numpy as np\n'), ((4394, 4427), 'numpy.sqrt', 'np.sqrt', (['(1 - e2 * sinlat * sinlat)'], {}), '(1 - e2 * sinlat * sinlat)\n', (4401, 4427), True, 'import numpy as np\n'), ((4590, 4620), 'numpy.arctan', 'np.arctan', (['(aux1 / (1.0 - aux3))'], {}), '(aux1 / (1.0 - aux3))\n', (4599, 4620), True, 'import numpy as np\n'), ((4633, 4656), 'numpy.sin', 'np.sin', (['lat[p_non_null]'], {}), '(lat[p_non_null])\n', (4639, 4656), True, 'import numpy as np\n'), ((6689, 6706), 'numpy.abs', 'np.abs', (['z[p_null]'], {}), '(z[p_null])\n', (6695, 6706), True, 'import numpy as np\n'), ((7596, 7629), 'numpy.sqrt', 'np.sqrt', (['(1 - e2 * sinlat * sinlat)'], {}), '(1 - e2 * sinlat * sinlat)\n', (7603, 7629), True, 'import numpy as np\n'), ((15048, 15069), 'numpy.arcsin', 'np.arcsin', (['(Z / radius)'], {}), '(Z / radius)\n', (15057, 15069), True, 'import numpy as np\n'), ((15096, 15112), 'numpy.arctan2', 'np.arctan2', (['Y', 'X'], {}), '(Y, X)\n', (15106, 15112), True, 'import numpy as np\n'), ((19428, 19449), 'numpy.deg2rad', 'np.deg2rad', (['latitude1'], {}), '(latitude1)\n', (19438, 19449), True, 'import numpy as np\n'), ((19471, 19492), 'numpy.deg2rad', 'np.deg2rad', (['latitude1'], {}), '(latitude1)\n', (19481, 19492), True, 'import numpy as np\n'), ((19515, 19537), 'numpy.deg2rad', 'np.deg2rad', (['longitude1'], {}), '(longitude1)\n', (19525, 19537), True, 'import numpy as np\n'), ((19559, 19581), 'numpy.deg2rad', 'np.deg2rad', (['longitude1'], {}), '(longitude1)\n', (19569, 19581), True, 'import numpy as np\n'), ((4239, 4257), 'numpy.sign', 'np.sign', (['z[p_null]'], {}), '(z[p_null])\n', (4246, 4257), True, 'import numpy as np\n'), ((4463, 4486), 'numpy.cos', 'np.cos', (['lat[p_non_null]'], {}), '(lat[p_non_null])\n', (4469, 4486), True, 'import numpy as np\n'), ((4684, 4717), 'numpy.sqrt', 'np.sqrt', (['(1 - e2 * sinlat * sinlat)'], {}), '(1 - e2 * sinlat * sinlat)\n', (4691, 4717), True, 'import numpy as np\n'), ((6742, 6760), 'numpy.sign', 'np.sign', (['z[p_null]'], {}), '(z[p_null])\n', (6749, 6760), True, 'import numpy as np\n'), ((7666, 7689), 'numpy.cos', 'np.cos', (['lat[p_non_null]'], {}), '(lat[p_non_null])\n', (7672, 7689), True, 'import numpy as np\n'), ((4757, 4780), 'numpy.cos', 'np.cos', (['lat[p_non_null]'], {}), '(lat[p_non_null])\n', (4763, 4780), True, 'import numpy as np\n'), ((16207, 16223), 'numpy.tan', 'np.tan', (['latitude'], {}), '(latitude)\n', (16213, 16223), True, 'import numpy as np\n'), ((17309, 17325), 'numpy.tan', 'np.tan', (['latitude'], {}), '(latitude)\n', (17315, 17325), True, 'import numpy as np\n')]
import pandas as pd import numpy as np from PIL import Image, ImageDraw, ImageFont import h5py import os from sortedcontainers import SortedDict from scipy.ndimage.filters import gaussian_filter import scipy.spatial from itertools import islice def generate_gaussian_kernels(round_decimals=3, sigma_threshold=4, sigma_min=0, sigma_max=20, num_sigmas=801): """ Computing gaussian filter kernel for sigmas in linspace(sigma_min, sigma_max, num_sigmas) and saving them to a dictionary. The key-value pair is sigma:kernel. """ kernels_dict = dict() sigma_space = np.linspace(sigma_min, sigma_max, num_sigmas) for sigma in sigma_space: sigma = np.round(sigma, decimals=round_decimals) kernel_size = (np.ceil(sigma * sigma_threshold).astype(int) * 2) + 1 img_shape = (kernel_size, kernel_size) img_center = (img_shape[0] // 2, img_shape[1] // 2) arr = np.zeros(img_shape) arr[img_center] = 1 arr = gaussian_filter(arr, sigma, mode='constant') kernel = arr / arr.sum() kernels_dict[sigma] = kernel return SortedDict(kernels_dict) def gaussian_filter_density(non_zero_points, map_h, map_w, distances=None, kernels_dict=None, min_sigma=2, method=1, const_sigma=15): """ Fast gaussian filter implementation : using precomputed distances and kernels """ gt_count = non_zero_points.shape[0] density_map = np.zeros((map_h, map_w), dtype=np.float32) for i in range(gt_count): point_y, point_x = non_zero_points[i] sigma = compute_sigma(gt_count, distances[i], min_sigma=min_sigma, method=method, fixed_sigma=const_sigma) closest_sigma = find_closest_key(kernels_dict, sigma) kernel = kernels_dict[closest_sigma] full_kernel_size = kernel.shape[0] kernel_size = full_kernel_size // 2 # get min and max x and y coordinates for kernel around point min_img_x = max(0, point_x - kernel_size) min_img_y = max(0, point_y - kernel_size) max_img_x = min(point_x + kernel_size + 1, map_h - 1) max_img_y = min(point_y + kernel_size + 1, map_w - 1) # get slice coordinates of kernel if kernal goes over image boundary kernel_x_min = kernel_size - point_x if point_x <= kernel_size else 0 kernel_y_min = kernel_size - point_y if point_y <= kernel_size else 0 kernel_x_max = kernel_x_min + max_img_x - min_img_x kernel_y_max = kernel_y_min + max_img_y - min_img_y # Apply kernel density_map[min_img_x:max_img_x, min_img_y:max_img_y] += kernel[kernel_x_min:kernel_x_max, kernel_y_min:kernel_y_max] return density_map def compute_sigma(gt_count, distance=None, min_sigma=1, method=1, fixed_sigma=15): """ Compute sigma for gaussian kernel with different methods : * method = 1 : sigma = (mean of distance to 3 nearest neighbors) / 10 * method = 2 : sigma = distance to nearest neighbor * method = 3 : sigma = fixed value ** if sigma lower than threshold 'min_sigma', then 'min_sigma' will be used ** in case of one point on the image sigma = 'fixed_sigma' """ if gt_count > 1 and distance is not None: if method == 1: sigma = np.mean(distance[1:4]) * 0.1 elif method == 2: sigma = distance[1] elif method == 3: sigma = fixed_sigma else: sigma = fixed_sigma if sigma < min_sigma: sigma = min_sigma return sigma def find_closest_key(sorted_dict, key): """ Find closest key in sorted_dict to 'key' """ keys = list(islice(sorted_dict.irange(minimum=key), 1)) keys.extend(islice(sorted_dict.irange(maximum=key, reverse=True), 1)) return min(keys, key=lambda k: abs(key - k)) def save_computed_density(density_map, out_path): """ Save density map to h5py format """ with h5py.File(out_path, 'w') as hf: hf['density'] = density_map print(f'{out_path} saved.') def compute_distances(points_dct, n_neighbors = 4, leafsize=1024): """ Approximates the nearest 3 neighbours to each tree """ distances_dct = dict() for full_img_path, points in points_dct.items(): # build kdtree tree = scipy.spatial.KDTree(points.copy(), leafsize=leafsize) # query kdtree distances, _ = tree.query(points, k=n_neighbors) distances_dct[full_img_path] = distances return distances_dct def generate_points_dct(img_gt_paths): """ Generate dictionary of all points for all images """ points_dct ={} for img_path, gt_path in img_gt_paths.copy(): points = pd.read_csv(gt_path, header=None, index_col=None).values points_dct[img_path ] =points return points_dct def generate_gt_den_maps(img_gt_paths, points_dct, distances_dct, kernels_dct, method=3, const_sigma=15, file='h5', min_sigma=2): """ Generates density map file """ for img_filepath, _ in img_gt_paths: extension = os.path.splitext(img_filepath)[-1] # load img and map img = Image.open(img_filepath) width, height = img.size gt_points = points_dct[img_filepath] distances = distances_dct[img_filepath] # Generate image density map density_map = gaussian_filter_density( gt_points, height, width, distances, kernels_dct, min_sigma=min_sigma, method=method, const_sigma=const_sigma ) # Save den_path = img_filepath.replace('img', 'gt_map_gaus') if file == 'csv': den_path = den_path.replace(extension, '.csv') pd.DataFrame(density_map).to_csv(den_path, index=None, header=None) if file == 'h5': den_path = den_path.replace(extension, '.h5') with h5py.File(den_path, 'w') as hf: hf['density'] = density_map filename = os.path.split(den_path)[-1] print(f'{filename} saved.')
[ "numpy.mean", "numpy.ceil", "PIL.Image.open", "scipy.ndimage.filters.gaussian_filter", "pandas.read_csv", "os.path.splitext", "h5py.File", "os.path.split", "numpy.linspace", "numpy.zeros", "pandas.DataFrame", "sortedcontainers.SortedDict", "numpy.round" ]
[((620, 665), 'numpy.linspace', 'np.linspace', (['sigma_min', 'sigma_max', 'num_sigmas'], {}), '(sigma_min, sigma_max, num_sigmas)\n', (631, 665), True, 'import numpy as np\n'), ((1144, 1168), 'sortedcontainers.SortedDict', 'SortedDict', (['kernels_dict'], {}), '(kernels_dict)\n', (1154, 1168), False, 'from sortedcontainers import SortedDict\n'), ((1517, 1559), 'numpy.zeros', 'np.zeros', (['(map_h, map_w)'], {'dtype': 'np.float32'}), '((map_h, map_w), dtype=np.float32)\n', (1525, 1559), True, 'import numpy as np\n'), ((712, 752), 'numpy.round', 'np.round', (['sigma'], {'decimals': 'round_decimals'}), '(sigma, decimals=round_decimals)\n', (720, 752), True, 'import numpy as np\n'), ((954, 973), 'numpy.zeros', 'np.zeros', (['img_shape'], {}), '(img_shape)\n', (962, 973), True, 'import numpy as np\n'), ((1017, 1061), 'scipy.ndimage.filters.gaussian_filter', 'gaussian_filter', (['arr', 'sigma'], {'mode': '"""constant"""'}), "(arr, sigma, mode='constant')\n", (1032, 1061), False, 'from scipy.ndimage.filters import gaussian_filter\n'), ((4015, 4039), 'h5py.File', 'h5py.File', (['out_path', '"""w"""'], {}), "(out_path, 'w')\n", (4024, 4039), False, 'import h5py\n'), ((5242, 5266), 'PIL.Image.open', 'Image.open', (['img_filepath'], {}), '(img_filepath)\n', (5252, 5266), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((4782, 4831), 'pandas.read_csv', 'pd.read_csv', (['gt_path'], {'header': 'None', 'index_col': 'None'}), '(gt_path, header=None, index_col=None)\n', (4793, 4831), True, 'import pandas as pd\n'), ((5165, 5195), 'os.path.splitext', 'os.path.splitext', (['img_filepath'], {}), '(img_filepath)\n', (5181, 5195), False, 'import os\n'), ((6061, 6084), 'os.path.split', 'os.path.split', (['den_path'], {}), '(den_path)\n', (6074, 6084), False, 'import os\n'), ((3364, 3386), 'numpy.mean', 'np.mean', (['distance[1:4]'], {}), '(distance[1:4])\n', (3371, 3386), True, 'import numpy as np\n'), ((5965, 5989), 'h5py.File', 'h5py.File', (['den_path', '"""w"""'], {}), "(den_path, 'w')\n", (5974, 5989), False, 'import h5py\n'), ((5797, 5822), 'pandas.DataFrame', 'pd.DataFrame', (['density_map'], {}), '(density_map)\n', (5809, 5822), True, 'import pandas as pd\n'), ((776, 808), 'numpy.ceil', 'np.ceil', (['(sigma * sigma_threshold)'], {}), '(sigma * sigma_threshold)\n', (783, 808), True, 'import numpy as np\n')]
# this file contains the invert() function that defines the right-side # vector of the normal equations and calls the conjugate-gradient solver from conj_grad import cg_solve from operators import (forward_w,forward_beta,adjoint_w,adjoint_beta,Hc, adjoint_Ub,adjoint_Uw,adjoint_Vb,adjoint_Vw,forward_U,forward_V,h_wt,u_wt) import numpy as np from scipy.fft import fft2,ifft2 def invert(data,vel_locs,inv_w,inv_beta,eps_w,eps_beta): # invert for w, beta, or m given the observed elevation change h_obs # and possibly horizontal surface velocity (u_obs,v_obs) defined at locations vel_locs # # data = [h_obs,u_obs,v_obs] dim = inv_w + inv_beta vel_data = np.max(vel_locs) print('Solving normal equations with CG....\n') if inv_w == 1 and dim==1: if vel_data == 0: b = adjoint_w(fft2(data[0])) elif vel_data == 1: b = h_wt*adjoint_w(fft2(data[0]))+u_wt*vel_locs*(adjoint_Uw(fft2(data[1]))+adjoint_Vw(fft2(data[2]))) sol = cg_solve(b,inv_w,inv_beta,eps_w,eps_beta,vel_locs) fwd = ifft2(forward_w(sol)).real elif inv_beta == 1 and dim==1: if vel_data == 0: b = h_wt*adjoint_beta(fft2(data[0])) elif vel_data == 1: b = h_wt*adjoint_beta(fft2(data[0]))+u_wt*vel_locs*(adjoint_Ub(fft2(data[1]))+adjoint_Vb(fft2(data[2]))) sol = cg_solve(b,inv_w,inv_beta,eps_w,eps_beta,vel_locs) fwd = ifft2(forward_beta(sol)).real elif dim == 2: if vel_data == 1: b1 = h_wt*adjoint_w(fft2(data[0]))+u_wt*vel_locs*(adjoint_Uw(fft2(data[1]))+adjoint_Vw(fft2(data[2]))) b2 = h_wt*adjoint_beta(fft2(data[0]))+u_wt*vel_locs*(adjoint_Ub(fft2(data[1]))+adjoint_Vb(fft2(data[2]))) elif vel_data == 0: b1 = adjoint_w(fft2(data[0])) b2 = adjoint_beta(fft2(data[0])) b = np.array([b1,b2]) sol = cg_solve(b,inv_w,inv_beta,eps_w,eps_beta,vel_locs) h = ifft2(Hc(sol)).real u = ifft2(forward_U(sol[0],sol[1])).real v = ifft2(forward_V(sol[0],sol[1])).real fwd = np.array([h,u,v]) return sol,fwd
[ "conj_grad.cg_solve", "operators.forward_U", "scipy.fft.fft2", "operators.forward_beta", "numpy.max", "numpy.array", "operators.Hc", "operators.forward_V", "operators.forward_w" ]
[((705, 721), 'numpy.max', 'np.max', (['vel_locs'], {}), '(vel_locs)\n', (711, 721), True, 'import numpy as np\n'), ((1030, 1085), 'conj_grad.cg_solve', 'cg_solve', (['b', 'inv_w', 'inv_beta', 'eps_w', 'eps_beta', 'vel_locs'], {}), '(b, inv_w, inv_beta, eps_w, eps_beta, vel_locs)\n', (1038, 1085), False, 'from conj_grad import cg_solve\n'), ((1393, 1448), 'conj_grad.cg_solve', 'cg_solve', (['b', 'inv_w', 'inv_beta', 'eps_w', 'eps_beta', 'vel_locs'], {}), '(b, inv_w, inv_beta, eps_w, eps_beta, vel_locs)\n', (1401, 1448), False, 'from conj_grad import cg_solve\n'), ((857, 870), 'scipy.fft.fft2', 'fft2', (['data[0]'], {}), '(data[0])\n', (861, 870), False, 'from scipy.fft import fft2, ifft2\n'), ((1101, 1115), 'operators.forward_w', 'forward_w', (['sol'], {}), '(sol)\n', (1110, 1115), False, 'from operators import forward_w, forward_beta, adjoint_w, adjoint_beta, Hc, adjoint_Ub, adjoint_Uw, adjoint_Vb, adjoint_Vw, forward_U, forward_V, h_wt, u_wt\n'), ((1895, 1913), 'numpy.array', 'np.array', (['[b1, b2]'], {}), '([b1, b2])\n', (1903, 1913), True, 'import numpy as np\n'), ((1927, 1982), 'conj_grad.cg_solve', 'cg_solve', (['b', 'inv_w', 'inv_beta', 'eps_w', 'eps_beta', 'vel_locs'], {}), '(b, inv_w, inv_beta, eps_w, eps_beta, vel_locs)\n', (1935, 1982), False, 'from conj_grad import cg_solve\n'), ((2122, 2141), 'numpy.array', 'np.array', (['[h, u, v]'], {}), '([h, u, v])\n', (2130, 2141), True, 'import numpy as np\n'), ((1464, 1481), 'operators.forward_beta', 'forward_beta', (['sol'], {}), '(sol)\n', (1476, 1481), False, 'from operators import forward_w, forward_beta, adjoint_w, adjoint_beta, Hc, adjoint_Ub, adjoint_Uw, adjoint_Vb, adjoint_Vw, forward_U, forward_V, h_wt, u_wt\n'), ((1218, 1231), 'scipy.fft.fft2', 'fft2', (['data[0]'], {}), '(data[0])\n', (1222, 1231), False, 'from scipy.fft import fft2, ifft2\n'), ((1996, 2003), 'operators.Hc', 'Hc', (['sol'], {}), '(sol)\n', (1998, 2003), False, 'from operators import forward_w, forward_beta, adjoint_w, adjoint_beta, Hc, adjoint_Ub, adjoint_Uw, adjoint_Vb, adjoint_Vw, forward_U, forward_V, h_wt, u_wt\n'), ((2028, 2053), 'operators.forward_U', 'forward_U', (['sol[0]', 'sol[1]'], {}), '(sol[0], sol[1])\n', (2037, 2053), False, 'from operators import forward_w, forward_beta, adjoint_w, adjoint_beta, Hc, adjoint_Ub, adjoint_Uw, adjoint_Vb, adjoint_Vw, forward_U, forward_V, h_wt, u_wt\n'), ((2077, 2102), 'operators.forward_V', 'forward_V', (['sol[0]', 'sol[1]'], {}), '(sol[0], sol[1])\n', (2086, 2102), False, 'from operators import forward_w, forward_beta, adjoint_w, adjoint_beta, Hc, adjoint_Ub, adjoint_Uw, adjoint_Vb, adjoint_Vw, forward_U, forward_V, h_wt, u_wt\n'), ((932, 945), 'scipy.fft.fft2', 'fft2', (['data[0]'], {}), '(data[0])\n', (936, 945), False, 'from scipy.fft import fft2, ifft2\n'), ((1822, 1835), 'scipy.fft.fft2', 'fft2', (['data[0]'], {}), '(data[0])\n', (1826, 1835), False, 'from scipy.fft import fft2, ifft2\n'), ((1867, 1880), 'scipy.fft.fft2', 'fft2', (['data[0]'], {}), '(data[0])\n', (1871, 1880), False, 'from scipy.fft import fft2, ifft2\n'), ((973, 986), 'scipy.fft.fft2', 'fft2', (['data[1]'], {}), '(data[1])\n', (977, 986), False, 'from scipy.fft import fft2, ifft2\n'), ((999, 1012), 'scipy.fft.fft2', 'fft2', (['data[2]'], {}), '(data[2])\n', (1003, 1012), False, 'from scipy.fft import fft2, ifft2\n'), ((1295, 1308), 'scipy.fft.fft2', 'fft2', (['data[0]'], {}), '(data[0])\n', (1299, 1308), False, 'from scipy.fft import fft2, ifft2\n'), ((1566, 1579), 'scipy.fft.fft2', 'fft2', (['data[0]'], {}), '(data[0])\n', (1570, 1579), False, 'from scipy.fft import fft2, ifft2\n'), ((1684, 1697), 'scipy.fft.fft2', 'fft2', (['data[0]'], {}), '(data[0])\n', (1688, 1697), False, 'from scipy.fft import fft2, ifft2\n'), ((1336, 1349), 'scipy.fft.fft2', 'fft2', (['data[1]'], {}), '(data[1])\n', (1340, 1349), False, 'from scipy.fft import fft2, ifft2\n'), ((1362, 1375), 'scipy.fft.fft2', 'fft2', (['data[2]'], {}), '(data[2])\n', (1366, 1375), False, 'from scipy.fft import fft2, ifft2\n'), ((1607, 1620), 'scipy.fft.fft2', 'fft2', (['data[1]'], {}), '(data[1])\n', (1611, 1620), False, 'from scipy.fft import fft2, ifft2\n'), ((1633, 1646), 'scipy.fft.fft2', 'fft2', (['data[2]'], {}), '(data[2])\n', (1637, 1646), False, 'from scipy.fft import fft2, ifft2\n'), ((1725, 1738), 'scipy.fft.fft2', 'fft2', (['data[1]'], {}), '(data[1])\n', (1729, 1738), False, 'from scipy.fft import fft2, ifft2\n'), ((1751, 1764), 'scipy.fft.fft2', 'fft2', (['data[2]'], {}), '(data[2])\n', (1755, 1764), False, 'from scipy.fft import fft2, ifft2\n')]
## regression.py ## scalar regression ## note that `calcMargiProb`, `calcJointProb`, `calcCondiProb`, and `estEntropy` aren't currently used in any methods. import numpy as np import pandas as pd import tensorflow as tf import itertools as it import scipy.special as ss import time def eNet(alpha, lam, v): """Elastic-net regularization penalty""" return lam * (alpha * tf.reduce_sum(tf.abs(v)) + (1-alpha) * tf.reduce_sum(tf.square(v))) def calcMargiProb(cadId, M): """Returns p(M=j) in vector form""" return np.array([np.sum(cadId == m) for m in range(M)]) / cadId.shape[0] def calcJointProb(G, cadId, M): """Returns p(M=j, x in C_i) in matrix form""" jointProbMat = np.zeros((M,M)) # p(M=j, x in C_i) for i,j in it.product(range(M), range(M)): jointProbMat[i,j] = np.sum(G[cadId==i,j]) jointProbMat /= G.shape[0] return jointProbMat def calcCondiProb(jointProb, margProb): """Returns p(M = j | x in C_i)""" return np.divide(jointProb, margProb[:,None], out=np.zeros_like(jointProb), where=margProb[:,None]!=0) def estEntropy(condProb): """Returns estimated entropy for each cadre""" return -np.sum(ss.xlogy(condProb, condProb), axis=1) / np.log(2) class regressionCadreModel(object): def __init__(self, M=2, gamma=10., lambda_d=0.01, lambda_W=0.01, alpha_d=0.9, alpha_W=0.9, Tmax=10000, record=100, eta=1e-3, Nba=50, eps=1e-3): ## hyperparameters / structure self.M = M # number of cadres self.gamma = gamma # cadre assignment sharpness self.lambda_d = lambda_d # regularization strengths self.lambda_W = lambda_W self.alpha_d = alpha_d # elastic net mixing weights self.alpha_W = alpha_W self.fitted = False ## optimization settings self.Tmax = Tmax # maximum iterations self.record = record # record points self.eta = eta # initial stepsize self.Nba = Nba # minibatch size self.eps = eps # convergence tolerance ## parameters self.W = 0 # regression weights self.w0 = 0 # regression biases self.C = 0 # cadre centers self.d = 0 # cadre assignment weights ## data self.data = None # copy of data self.features = None # names of features self.target = None # name of target ## outputs self.loss = [] # loss trajectory self.mse = [] # MSE trajectory for training data self.mseVa = [] # MSE trajectory for validation data self.time = [] # optimization times by step def get_params(self, deep=True): return {'M': self.M, 'gamma': self.gamma, 'lambda_d': self.lambda_d, 'lambda_W': self.lambda_W, 'alpha_d': self.alpha_d, 'alpha_W': self.alpha_W, 'Tmax': self.Tmax, 'record': self.record, 'eta': self.eta, 'Nba': self.Nba, 'eps': self.eps} def set_params(self, **parameters): for parameter, value in parameters.items(): setattr(self, parameter, value) return self def fit(self, Dtr, features, target, Dva=None, inits=dict(), seed=16162, progress=False, store=False): np.random.seed(seed) """Fit regression cadre model""" self.features = features self.target = target Ntr, P = Dtr.shape[0], features.shape[0] # number of training observations, number of features self.fitted = True if store: self.data = Dtr ## extract values from pd.DataFrames for faster access data_mat = Dtr.loc[:,features].values target_mat = Dtr.loc[:,[target]].values if Dva is not None: data_mat_va = Dva.loc[:,features].values target_mat_va = Dva.loc[:,[target]].values ############################################ ## tensorflow parameters and placeholders ## ############################################ tf.reset_default_graph() ## cadre centers parameter if inits is not None and 'C' in inits: C = tf.Variable(inits['C'], dtype=tf.float32, name='C') else: C = tf.Variable(np.random.normal(loc=0., scale=0.1, size=(P,self.M)), dtype=tf.float32, name='C') ## cadre determination weights parameter if inits is not None and 'd' in inits: d = tf.Variable(inits['d'], dtype=tf.float32, name='d') else: d = tf.Variable(np.random.uniform(size=(P,)), dtype=tf.float32, name='d') ## regression hyperplane weights parameter if inits is not None and 'W' in inits: W = tf.Variable(inits['W'], dtype=tf.float32, name='W') else: W = tf.Variable(np.random.normal(loc=0., scale=0.1, size=(P,self.M)), dtype=tf.float32, name='W') ## regression hyperplane bias parameter if inits is not None and 'w0' in inits: w0 = tf.Variable(inits['w0'], dtype=tf.float32, name='w0') else: w0 = tf.Variable(tf.zeros(shape=(self.M,), dtype=tf.float32), dtype=tf.float32, name='w0') X = tf.placeholder(dtype=tf.float32, shape=(None,P), name='X') Y = tf.placeholder(dtype=tf.float32, shape=(None,1), name='Y') eta = tf.placeholder(dtype=tf.float32, shape=(), name='eta') ## T[n,m] = ||x^n - c^m||^2_D T = tf.einsum('npm,p->nm', tf.square(tf.map_fn(lambda x: tf.expand_dims(x,1) - C, X)), d) ## G[n,m] = g_m(x^n) ## = 1 / sum_m' exp(gamma(T[n,m] - T[n,m'])) G = 1 / tf.map_fn(lambda t: tf.reduce_sum(tf.exp(self.gamma*(tf.expand_dims(t,1) - tf.expand_dims(t,0))), axis=1), T, name='G') ## E[n,m] = e_m(x^n) E = tf.add(tf.matmul(X, W), w0, name='E') ## F[n] = f(x^n) = sum_m g_m(x^n) e_m(x^n) F = tf.reduce_sum(G * E, axis=1, keepdims=True) ## L = 1 / N sum_n sum_m g_m(x^n) * (e_m(x^n) - y_n) ^2 MSE = tf.reduce_mean( (F - Y)**2 ) l2_d = self.lambda_d * (1 - self.alpha_d) * tf.reduce_sum(d**2) l2_W = self.lambda_W * (1 - self.alpha_W) * tf.reduce_sum(W**2) l1_d = self.lambda_d * self.alpha_d * tf.reduce_sum(tf.abs(d)) l1_W = self.lambda_W * self.alpha_W * tf.reduce_sum(tf.abs(W)) l2_C = 1e-7 * tf.reduce_sum(C**2) loss_smooth = MSE + l2_d + l2_W + l2_C optimizer = tf.train.AdamOptimizer(learning_rate=self.eta).minimize(loss_smooth) loss_full = loss_smooth + l1_d + l1_W ## proximal gradient steps thresh_W = tf.assign(W, tf.sign(W) * (tf.abs(W) - eta * self.lambda_W * self.alpha_W) * tf.cast(tf.abs(W) > eta * self.lambda_W * self.alpha_W, tf.float32)) thresh_d = tf.assign(d, tf.maximum(0., tf.sign(d) * (tf.abs(d) - eta * self.lambda_d * self.alpha_d) * tf.cast(tf.abs(d) > eta * self.lambda_d * self.alpha_d, tf.float32))) #################### ## learning model ## #################### with tf.Session() as sess: tf.global_variables_initializer().run() t0 = time.time() ## perform optimization for t in range(self.Tmax): inds = np.random.choice(Ntr, self.Nba, replace=False) ## take gradient step sess.run(optimizer, feed_dict={X: data_mat[inds,:], Y: target_mat[inds,:]}) ## take proximal step sess.run([thresh_d, thresh_W], feed_dict={eta: self.eta}) # record-keeping if not t % self.record: [l, mse_tr] = sess.run([loss_full, MSE], feed_dict={X: data_mat, Y: target_mat}) self.loss.append(l) self.mse.append(mse_tr) if Dva is not None: mse_va = MSE.eval(feed_dict={X: data_mat_va, Y: target_mat_va}) self.mseVa.append(mse_va) self.time.append(time.time() - t0) if progress: if len(self.time) and Dva is not None: print(t, self.loss[-1], self.mse[-1], self.mseVa[-1], self.time[-1]) elif len(self.time): print(t, self.loss[-1], self.mse[-1], self.time[-1]) else: print(t) self.C, self.d, self.W, self.w0 = C.eval(), d.eval(), W.eval(), w0.eval() self.C = pd.DataFrame(self.C, index=self.features) self.d = pd.DataFrame(self.d, index=self.features) self.W = pd.DataFrame(self.W, index=self.features) return self def predictFull(self, Dnew): """Returns predicted values, cadre weights, and cadre estimates for new data""" if not self.fitted: print('warning: model not yet fit') tf.reset_default_graph() C = tf.Variable(self.C.values, dtype=tf.float64, name='C') d = tf.Variable(self.d.values[:,0], dtype=tf.float64, name='d') W = tf.Variable(self.W.values, dtype=tf.float64, name='W') w0 = tf.Variable(self.w0, dtype=tf.float64, name='w0') X = tf.placeholder(dtype=tf.float64, shape=(None,len(self.features)), name='X') ## T[n,m] = ||x^n - c^m||^2_D T = tf.einsum('npm,p->nm', tf.square(tf.map_fn(lambda x: tf.expand_dims(x,1) - C, X)), d) ## G[n,m] = g_m(x^n) ## = 1 / sum_m' exp(gamma(T[n,m] - T[n,m'])) G = 1 / tf.map_fn(lambda t: tf.reduce_sum(tf.exp(self.gamma*(tf.expand_dims(t,1) - tf.expand_dims(t,0))), axis=1), T, name='G') ## E[n,m] = e_m(x^n) E = tf.add(tf.matmul(X, W), w0, name='E') ## f[n] = f(x^n) F = tf.reduce_sum(G * E, axis=1, name='F') # this won't work if minibatch size 1 is used bstCd = tf.argmax(G, axis=1, name='bestCadre') with tf.Session() as sess: tf.global_variables_initializer().run() Fnew, Gnew, mNew = sess.run([F, G, bstCd], feed_dict={X: Dnew[self.features].values}) return Fnew, Gnew, mNew def predict(self, Dnew): """Returns predicted values for new data""" return self.predictFull(Dnew)[0] def score(self, Dnew): """Returns average sum-of-squares for new data""" Fnew = self.predict(Dnew) return ((Fnew - Dnew[self.target].values)**2).mean()
[ "scipy.special.xlogy", "tensorflow.reduce_sum", "numpy.log", "tensorflow.reduce_mean", "tensorflow.sign", "tensorflow.placeholder", "tensorflow.Session", "numpy.random.seed", "tensorflow.matmul", "tensorflow.square", "pandas.DataFrame", "tensorflow.train.AdamOptimizer", "tensorflow.zeros", ...
[((744, 760), 'numpy.zeros', 'np.zeros', (['(M, M)'], {}), '((M, M))\n', (752, 760), True, 'import numpy as np\n'), ((856, 880), 'numpy.sum', 'np.sum', (['G[cadId == i, j]'], {}), '(G[cadId == i, j])\n', (862, 880), True, 'import numpy as np\n'), ((1270, 1279), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (1276, 1279), True, 'import numpy as np\n'), ((3412, 3432), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (3426, 3432), True, 'import numpy as np\n'), ((4229, 4253), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (4251, 4253), True, 'import tensorflow as tf\n'), ((5502, 5561), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '(None, P)', 'name': '"""X"""'}), "(dtype=tf.float32, shape=(None, P), name='X')\n", (5516, 5561), True, 'import tensorflow as tf\n'), ((5574, 5633), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '(None, 1)', 'name': '"""Y"""'}), "(dtype=tf.float32, shape=(None, 1), name='Y')\n", (5588, 5633), True, 'import tensorflow as tf\n'), ((5648, 5702), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '()', 'name': '"""eta"""'}), "(dtype=tf.float32, shape=(), name='eta')\n", (5662, 5702), True, 'import tensorflow as tf\n'), ((6375, 6418), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(G * E)'], {'axis': '(1)', 'keepdims': '(True)'}), '(G * E, axis=1, keepdims=True)\n', (6388, 6418), True, 'import tensorflow as tf\n'), ((6505, 6533), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['((F - Y) ** 2)'], {}), '((F - Y) ** 2)\n', (6519, 6533), True, 'import tensorflow as tf\n'), ((9605, 9629), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (9627, 9629), True, 'import tensorflow as tf\n'), ((9644, 9698), 'tensorflow.Variable', 'tf.Variable', (['self.C.values'], {'dtype': 'tf.float64', 'name': '"""C"""'}), "(self.C.values, dtype=tf.float64, name='C')\n", (9655, 9698), True, 'import tensorflow as tf\n'), ((9713, 9773), 'tensorflow.Variable', 'tf.Variable', (['self.d.values[:, 0]'], {'dtype': 'tf.float64', 'name': '"""d"""'}), "(self.d.values[:, 0], dtype=tf.float64, name='d')\n", (9724, 9773), True, 'import tensorflow as tf\n'), ((9787, 9841), 'tensorflow.Variable', 'tf.Variable', (['self.W.values'], {'dtype': 'tf.float64', 'name': '"""W"""'}), "(self.W.values, dtype=tf.float64, name='W')\n", (9798, 9841), True, 'import tensorflow as tf\n'), ((9856, 9905), 'tensorflow.Variable', 'tf.Variable', (['self.w0'], {'dtype': 'tf.float64', 'name': '"""w0"""'}), "(self.w0, dtype=tf.float64, name='w0')\n", (9867, 9905), True, 'import tensorflow as tf\n'), ((10632, 10670), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(G * E)'], {'axis': '(1)', 'name': '"""F"""'}), "(G * E, axis=1, name='F')\n", (10645, 10670), True, 'import tensorflow as tf\n'), ((10734, 10772), 'tensorflow.argmax', 'tf.argmax', (['G'], {'axis': '(1)', 'name': '"""bestCadre"""'}), "(G, axis=1, name='bestCadre')\n", (10743, 10772), True, 'import tensorflow as tf\n'), ((1076, 1100), 'numpy.zeros_like', 'np.zeros_like', (['jointProb'], {}), '(jointProb)\n', (1089, 1100), True, 'import numpy as np\n'), ((4361, 4412), 'tensorflow.Variable', 'tf.Variable', (["inits['C']"], {'dtype': 'tf.float32', 'name': '"""C"""'}), "(inits['C'], dtype=tf.float32, name='C')\n", (4372, 4412), True, 'import tensorflow as tf\n'), ((4684, 4735), 'tensorflow.Variable', 'tf.Variable', (["inits['d']"], {'dtype': 'tf.float32', 'name': '"""d"""'}), "(inits['d'], dtype=tf.float32, name='d')\n", (4695, 4735), True, 'import tensorflow as tf\n'), ((4955, 5006), 'tensorflow.Variable', 'tf.Variable', (["inits['W']"], {'dtype': 'tf.float32', 'name': '"""W"""'}), "(inits['W'], dtype=tf.float32, name='W')\n", (4966, 5006), True, 'import tensorflow as tf\n'), ((5279, 5332), 'tensorflow.Variable', 'tf.Variable', (["inits['w0']"], {'dtype': 'tf.float32', 'name': '"""w0"""'}), "(inits['w0'], dtype=tf.float32, name='w0')\n", (5290, 5332), True, 'import tensorflow as tf\n'), ((6269, 6284), 'tensorflow.matmul', 'tf.matmul', (['X', 'W'], {}), '(X, W)\n', (6278, 6284), True, 'import tensorflow as tf\n'), ((6587, 6608), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(d ** 2)'], {}), '(d ** 2)\n', (6600, 6608), True, 'import tensorflow as tf\n'), ((6660, 6681), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(W ** 2)'], {}), '(W ** 2)\n', (6673, 6681), True, 'import tensorflow as tf\n'), ((6847, 6868), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(C ** 2)'], {}), '(C ** 2)\n', (6860, 6868), True, 'import tensorflow as tf\n'), ((7570, 7582), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (7580, 7582), True, 'import tensorflow as tf\n'), ((7663, 7674), 'time.time', 'time.time', ([], {}), '()\n', (7672, 7674), False, 'import time\n'), ((9187, 9228), 'pandas.DataFrame', 'pd.DataFrame', (['self.C'], {'index': 'self.features'}), '(self.C, index=self.features)\n', (9199, 9228), True, 'import pandas as pd\n'), ((9251, 9292), 'pandas.DataFrame', 'pd.DataFrame', (['self.d'], {'index': 'self.features'}), '(self.d, index=self.features)\n', (9263, 9292), True, 'import pandas as pd\n'), ((9315, 9356), 'pandas.DataFrame', 'pd.DataFrame', (['self.W'], {'index': 'self.features'}), '(self.W, index=self.features)\n', (9327, 9356), True, 'import pandas as pd\n'), ((10552, 10567), 'tensorflow.matmul', 'tf.matmul', (['X', 'W'], {}), '(X, W)\n', (10561, 10567), True, 'import tensorflow as tf\n'), ((10797, 10809), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (10807, 10809), True, 'import tensorflow as tf\n'), ((582, 600), 'numpy.sum', 'np.sum', (['(cadId == m)'], {}), '(cadId == m)\n', (588, 600), True, 'import numpy as np\n'), ((1230, 1258), 'scipy.special.xlogy', 'ss.xlogy', (['condProb', 'condProb'], {}), '(condProb, condProb)\n', (1238, 1258), True, 'import scipy.special as ss\n'), ((4457, 4511), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0.0)', 'scale': '(0.1)', 'size': '(P, self.M)'}), '(loc=0.0, scale=0.1, size=(P, self.M))\n', (4473, 4511), True, 'import numpy as np\n'), ((4780, 4808), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(P,)'}), '(size=(P,))\n', (4797, 4808), True, 'import numpy as np\n'), ((5051, 5105), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0.0)', 'scale': '(0.1)', 'size': '(P, self.M)'}), '(loc=0.0, scale=0.1, size=(P, self.M))\n', (5067, 5105), True, 'import numpy as np\n'), ((5378, 5421), 'tensorflow.zeros', 'tf.zeros', ([], {'shape': '(self.M,)', 'dtype': 'tf.float32'}), '(shape=(self.M,), dtype=tf.float32)\n', (5386, 5421), True, 'import tensorflow as tf\n'), ((6741, 6750), 'tensorflow.abs', 'tf.abs', (['d'], {}), '(d)\n', (6747, 6750), True, 'import tensorflow as tf\n'), ((6813, 6822), 'tensorflow.abs', 'tf.abs', (['W'], {}), '(W)\n', (6819, 6822), True, 'import tensorflow as tf\n'), ((6946, 6992), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'self.eta'}), '(learning_rate=self.eta)\n', (6968, 6992), True, 'import tensorflow as tf\n'), ((7790, 7836), 'numpy.random.choice', 'np.random.choice', (['Ntr', 'self.Nba'], {'replace': '(False)'}), '(Ntr, self.Nba, replace=False)\n', (7806, 7836), True, 'import numpy as np\n'), ((409, 418), 'tensorflow.abs', 'tf.abs', (['v'], {}), '(v)\n', (415, 418), True, 'import tensorflow as tf\n'), ((468, 480), 'tensorflow.square', 'tf.square', (['v'], {}), '(v)\n', (477, 480), True, 'import tensorflow as tf\n'), ((7141, 7151), 'tensorflow.sign', 'tf.sign', (['W'], {}), '(W)\n', (7148, 7151), True, 'import tensorflow as tf\n'), ((7605, 7638), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (7636, 7638), True, 'import tensorflow as tf\n'), ((10832, 10865), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (10863, 10865), True, 'import tensorflow as tf\n'), ((7155, 7164), 'tensorflow.abs', 'tf.abs', (['W'], {}), '(W)\n', (7161, 7164), True, 'import tensorflow as tf\n'), ((7213, 7222), 'tensorflow.abs', 'tf.abs', (['W'], {}), '(W)\n', (7219, 7222), True, 'import tensorflow as tf\n'), ((7322, 7332), 'tensorflow.sign', 'tf.sign', (['d'], {}), '(d)\n', (7329, 7332), True, 'import tensorflow as tf\n'), ((5838, 5858), 'tensorflow.expand_dims', 'tf.expand_dims', (['x', '(1)'], {}), '(x, 1)\n', (5852, 5858), True, 'import tensorflow as tf\n'), ((7336, 7345), 'tensorflow.abs', 'tf.abs', (['d'], {}), '(d)\n', (7342, 7345), True, 'import tensorflow as tf\n'), ((7394, 7403), 'tensorflow.abs', 'tf.abs', (['d'], {}), '(d)\n', (7400, 7403), True, 'import tensorflow as tf\n'), ((8623, 8634), 'time.time', 'time.time', ([], {}), '()\n', (8632, 8634), False, 'import time\n'), ((10130, 10150), 'tensorflow.expand_dims', 'tf.expand_dims', (['x', '(1)'], {}), '(x, 1)\n', (10144, 10150), True, 'import tensorflow as tf\n'), ((6082, 6102), 'tensorflow.expand_dims', 'tf.expand_dims', (['t', '(1)'], {}), '(t, 1)\n', (6096, 6102), True, 'import tensorflow as tf\n'), ((6151, 6171), 'tensorflow.expand_dims', 'tf.expand_dims', (['t', '(0)'], {}), '(t, 0)\n', (6165, 6171), True, 'import tensorflow as tf\n'), ((10374, 10394), 'tensorflow.expand_dims', 'tf.expand_dims', (['t', '(1)'], {}), '(t, 1)\n', (10388, 10394), True, 'import tensorflow as tf\n'), ((10434, 10454), 'tensorflow.expand_dims', 'tf.expand_dims', (['t', '(0)'], {}), '(t, 0)\n', (10448, 10454), True, 'import tensorflow as tf\n')]
import torch import random import numpy as np # MAX_SEQ = 200 # MIN_SEQ = 3 # SEED = 2021 def set_random_seeds(seed=0): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) random.seed(seed) np.random.seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False
[ "torch.cuda.manual_seed_all", "torch.manual_seed", "random.seed", "numpy.random.seed", "torch.cuda.manual_seed" ]
[((126, 149), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (143, 149), False, 'import torch\n'), ((154, 182), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (176, 182), False, 'import torch\n'), ((187, 219), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (213, 219), False, 'import torch\n'), ((224, 241), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (235, 241), False, 'import random\n'), ((246, 266), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (260, 266), True, 'import numpy as np\n')]
import os import cv2 import matplotlib.pyplot as plt import numpy as np import pykitti import torch import torchvision.transforms.functional as F from torch import hub from torchvision.datasets import Cityscapes from autolabeling import autolabel from autolabeling.classes import get_lidar_colormap from lilanet.utils import colorize_seg def get_cityscapes_colormap(): cmap = torch.zeros([256, 3], dtype=torch.uint8) for cls in Cityscapes.classes: cmap[cls.id, :] = torch.tensor(cls.color) return cmap def convert_train_id_to_id(target): target_copy = target.clone() for cls in Cityscapes.classes: target_copy[target == cls.train_id] = cls.id return target_copy def show_lidar_on_image(points, image, segmentation, T_cam0, K_cam0): points_2d = autolabel.pinhole_projection(points, T_cam0, K_cam0) cmap = get_cityscapes_colormap() segmentation = convert_train_id_to_id(segmentation) vis = colorize_seg(segmentation.cpu(), cmap) height, width = segmentation.shape for i in range(points.shape[0]): img_x = points_2d[i, 0] img_y = points_2d[i, 1] img_x = np.clip(img_x, 0, width - 1) img_y = np.clip(img_y, 0, height - 1) color = vis[:, img_y, img_x].tolist() cv2.circle(image, (img_x, img_y), 2, color=tuple(color), thickness=-1) return image def show_lidar_depth_on_image(pc_velo, img, T_cam0, K_cam0): points_2d = autolabel.pinhole_projection(pc_velo, T_cam0, K_cam0) cmap = plt.cm.get_cmap('hsv', 256) cmap = np.array([cmap(i) for i in range(256)])[:, :3] * 255 for i in range(pc_velo.shape[0]): depth = np.sqrt(pc_velo[i, 0] ** 2 + pc_velo[i, 1] ** 2 + pc_velo[i, 2] ** 2) idx = np.clip(int(640.0 / depth), 0, 255) color = cmap[idx, :] img_x = points_2d[i, 0] img_y = points_2d[i, 1] cv2.circle(img, (img_x, img_y), 2, color=tuple(color), thickness=-1) return img def plot_images(file_name, distance, reflectivity, label, segmentation, img, proj_img): cmap = get_lidar_colormap() cs_cmap = get_cityscapes_colormap() def _normalize(x): return (x - x.min()) / (x.max() - x.min()) distance_map = F.to_pil_image(_normalize(distance.squeeze())) reflectivity_map = F.to_pil_image(_normalize(reflectivity.squeeze())) label_map = F.to_pil_image(colorize_seg(label.squeeze(), cmap).cpu()) segmentation = convert_train_id_to_id(segmentation) segmentation_map = F.to_pil_image(colorize_seg(segmentation.squeeze(), cs_cmap).cpu()) fig = plt.figure(figsize=(10, 5)) plt.subplot(231) plt.title("Camera Image") plt.imshow(img) plt.subplot(232) plt.title("Semantic Image") plt.imshow(segmentation_map) plt.subplot(233) plt.title("Semantic Transfer") plt.imshow(proj_img) plt.subplot(234) plt.title("Distance") plt.imshow(distance_map) plt.subplot(235) plt.title("Reflectivity") plt.imshow(reflectivity_map) plt.subplot(236) plt.title("Label") plt.imshow(label_map) plt.tight_layout() plt.show() fig.savefig(file_name, dpi=200) if __name__ == '__main__': torch.cuda.empty_cache() basedir = '../data/kitti_raw' date = '2011_09_26' drive = '0005' device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') dataset = pykitti.raw(basedir, date, drive) idx = 16 file_name = "{}_{}_{}.png".format(date, drive, os.path.basename(dataset.cam2_files[idx])[:-4]) model = hub.load('TheCodez/pytorch-GoogLeNet-FCN', 'googlenet_fcn', pretrained='cityscapes') model = model.to(device) model.eval() img = dataset.get_cam2(idx) pc_velo = dataset.get_velo(idx) print("Inference") pred = autolabel.semantic_segmentation(model, img, device) pc_velo = autolabel.get_points_in_fov_90(pc_velo) print("Transferring labels") pc_labels = autolabel.transfer_labels(pc_velo, pred, dataset.calib.T_cam0_velo, dataset.calib.K_cam0) print("Spherical projection") lidar = autolabel.spherical_projection(pc_labels) proj_img = show_lidar_on_image(pc_velo, np.array(img), pred, dataset.calib.T_cam0_velo, dataset.calib.K_cam0) record = torch.as_tensor(lidar, dtype=torch.float32).permute(2, 0, 1).contiguous() reflectivity = record[3, :, :] distance = record[4, :, :] label = record[5, :, :] plot_images(file_name, distance, reflectivity, label, pred, img, proj_img)
[ "numpy.clip", "torch.as_tensor", "autolabeling.autolabel.get_points_in_fov_90", "numpy.sqrt", "autolabeling.autolabel.transfer_labels", "autolabeling.autolabel.semantic_segmentation", "numpy.array", "torch.cuda.is_available", "matplotlib.pyplot.imshow", "autolabeling.autolabel.spherical_projection...
[((384, 424), 'torch.zeros', 'torch.zeros', (['[256, 3]'], {'dtype': 'torch.uint8'}), '([256, 3], dtype=torch.uint8)\n', (395, 424), False, 'import torch\n'), ((800, 852), 'autolabeling.autolabel.pinhole_projection', 'autolabel.pinhole_projection', (['points', 'T_cam0', 'K_cam0'], {}), '(points, T_cam0, K_cam0)\n', (828, 852), False, 'from autolabeling import autolabel\n'), ((1451, 1504), 'autolabeling.autolabel.pinhole_projection', 'autolabel.pinhole_projection', (['pc_velo', 'T_cam0', 'K_cam0'], {}), '(pc_velo, T_cam0, K_cam0)\n', (1479, 1504), False, 'from autolabeling import autolabel\n'), ((1517, 1544), 'matplotlib.pyplot.cm.get_cmap', 'plt.cm.get_cmap', (['"""hsv"""', '(256)'], {}), "('hsv', 256)\n", (1532, 1544), True, 'import matplotlib.pyplot as plt\n'), ((2071, 2091), 'autolabeling.classes.get_lidar_colormap', 'get_lidar_colormap', ([], {}), '()\n', (2089, 2091), False, 'from autolabeling.classes import get_lidar_colormap\n'), ((2581, 2608), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (2591, 2608), True, 'import matplotlib.pyplot as plt\n'), ((2613, 2629), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(231)'], {}), '(231)\n', (2624, 2629), True, 'import matplotlib.pyplot as plt\n'), ((2634, 2659), 'matplotlib.pyplot.title', 'plt.title', (['"""Camera Image"""'], {}), "('Camera Image')\n", (2643, 2659), True, 'import matplotlib.pyplot as plt\n'), ((2664, 2679), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (2674, 2679), True, 'import matplotlib.pyplot as plt\n'), ((2685, 2701), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(232)'], {}), '(232)\n', (2696, 2701), True, 'import matplotlib.pyplot as plt\n'), ((2706, 2733), 'matplotlib.pyplot.title', 'plt.title', (['"""Semantic Image"""'], {}), "('Semantic Image')\n", (2715, 2733), True, 'import matplotlib.pyplot as plt\n'), ((2738, 2766), 'matplotlib.pyplot.imshow', 'plt.imshow', (['segmentation_map'], {}), '(segmentation_map)\n', (2748, 2766), True, 'import matplotlib.pyplot as plt\n'), ((2772, 2788), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(233)'], {}), '(233)\n', (2783, 2788), True, 'import matplotlib.pyplot as plt\n'), ((2793, 2823), 'matplotlib.pyplot.title', 'plt.title', (['"""Semantic Transfer"""'], {}), "('Semantic Transfer')\n", (2802, 2823), True, 'import matplotlib.pyplot as plt\n'), ((2828, 2848), 'matplotlib.pyplot.imshow', 'plt.imshow', (['proj_img'], {}), '(proj_img)\n', (2838, 2848), True, 'import matplotlib.pyplot as plt\n'), ((2854, 2870), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(234)'], {}), '(234)\n', (2865, 2870), True, 'import matplotlib.pyplot as plt\n'), ((2875, 2896), 'matplotlib.pyplot.title', 'plt.title', (['"""Distance"""'], {}), "('Distance')\n", (2884, 2896), True, 'import matplotlib.pyplot as plt\n'), ((2901, 2925), 'matplotlib.pyplot.imshow', 'plt.imshow', (['distance_map'], {}), '(distance_map)\n', (2911, 2925), True, 'import matplotlib.pyplot as plt\n'), ((2931, 2947), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(235)'], {}), '(235)\n', (2942, 2947), True, 'import matplotlib.pyplot as plt\n'), ((2952, 2977), 'matplotlib.pyplot.title', 'plt.title', (['"""Reflectivity"""'], {}), "('Reflectivity')\n", (2961, 2977), True, 'import matplotlib.pyplot as plt\n'), ((2982, 3010), 'matplotlib.pyplot.imshow', 'plt.imshow', (['reflectivity_map'], {}), '(reflectivity_map)\n', (2992, 3010), True, 'import matplotlib.pyplot as plt\n'), ((3016, 3032), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(236)'], {}), '(236)\n', (3027, 3032), True, 'import matplotlib.pyplot as plt\n'), ((3037, 3055), 'matplotlib.pyplot.title', 'plt.title', (['"""Label"""'], {}), "('Label')\n", (3046, 3055), True, 'import matplotlib.pyplot as plt\n'), ((3060, 3081), 'matplotlib.pyplot.imshow', 'plt.imshow', (['label_map'], {}), '(label_map)\n', (3070, 3081), True, 'import matplotlib.pyplot as plt\n'), ((3087, 3105), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3103, 3105), True, 'import matplotlib.pyplot as plt\n'), ((3110, 3120), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3118, 3120), True, 'import matplotlib.pyplot as plt\n'), ((3190, 3214), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (3212, 3214), False, 'import torch\n'), ((3385, 3418), 'pykitti.raw', 'pykitti.raw', (['basedir', 'date', 'drive'], {}), '(basedir, date, drive)\n', (3396, 3418), False, 'import pykitti\n'), ((3544, 3633), 'torch.hub.load', 'hub.load', (['"""TheCodez/pytorch-GoogLeNet-FCN"""', '"""googlenet_fcn"""'], {'pretrained': '"""cityscapes"""'}), "('TheCodez/pytorch-GoogLeNet-FCN', 'googlenet_fcn', pretrained=\n 'cityscapes')\n", (3552, 3633), False, 'from torch import hub\n'), ((3779, 3830), 'autolabeling.autolabel.semantic_segmentation', 'autolabel.semantic_segmentation', (['model', 'img', 'device'], {}), '(model, img, device)\n', (3810, 3830), False, 'from autolabeling import autolabel\n'), ((3846, 3885), 'autolabeling.autolabel.get_points_in_fov_90', 'autolabel.get_points_in_fov_90', (['pc_velo'], {}), '(pc_velo)\n', (3876, 3885), False, 'from autolabeling import autolabel\n'), ((3936, 4030), 'autolabeling.autolabel.transfer_labels', 'autolabel.transfer_labels', (['pc_velo', 'pred', 'dataset.calib.T_cam0_velo', 'dataset.calib.K_cam0'], {}), '(pc_velo, pred, dataset.calib.T_cam0_velo, dataset\n .calib.K_cam0)\n', (3961, 4030), False, 'from autolabeling import autolabel\n'), ((4073, 4114), 'autolabeling.autolabel.spherical_projection', 'autolabel.spherical_projection', (['pc_labels'], {}), '(pc_labels)\n', (4103, 4114), False, 'from autolabeling import autolabel\n'), ((487, 510), 'torch.tensor', 'torch.tensor', (['cls.color'], {}), '(cls.color)\n', (499, 510), False, 'import torch\n'), ((1153, 1181), 'numpy.clip', 'np.clip', (['img_x', '(0)', '(width - 1)'], {}), '(img_x, 0, width - 1)\n', (1160, 1181), True, 'import numpy as np\n'), ((1198, 1227), 'numpy.clip', 'np.clip', (['img_y', '(0)', '(height - 1)'], {}), '(img_y, 0, height - 1)\n', (1205, 1227), True, 'import numpy as np\n'), ((1664, 1733), 'numpy.sqrt', 'np.sqrt', (['(pc_velo[i, 0] ** 2 + pc_velo[i, 1] ** 2 + pc_velo[i, 2] ** 2)'], {}), '(pc_velo[i, 0] ** 2 + pc_velo[i, 1] ** 2 + pc_velo[i, 2] ** 2)\n', (1671, 1733), True, 'import numpy as np\n'), ((4160, 4173), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (4168, 4173), True, 'import numpy as np\n'), ((3332, 3357), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3355, 3357), False, 'import torch\n'), ((3483, 3524), 'os.path.basename', 'os.path.basename', (['dataset.cam2_files[idx]'], {}), '(dataset.cam2_files[idx])\n', (3499, 3524), False, 'import os\n'), ((4244, 4287), 'torch.as_tensor', 'torch.as_tensor', (['lidar'], {'dtype': 'torch.float32'}), '(lidar, dtype=torch.float32)\n', (4259, 4287), False, 'import torch\n')]
''' Psychophysics.py: Script containing functions to measure relevant psychophysical metrics for various tasks. ''' import matplotlib.pyplot as plt import numpy as np import numpy.random as npr import time def dRSG_metronomic(RNN, ntrials=1, threshold=0.1, showtrialplots=1, **kwargs): ''' Function designed for the delayed ready-set-go (dRSG) task. The network should be trained using the RHY task, with n_ints=1 and cont=1 (one interval, varying continuously). The function will plot the "metronomic" curve for the task, showing the relationship between the sampled interval (t_s) and the produced interval (t_p). The function draws values of t_s from the default range for the RHY function. Inputs: RNN: The trained JazNet. ntrials: Number of trials to use per t_s. threshold: Error threshold for considering a trial to be a "success" showtrialplots: Determines if a plot is created showing the network's output for each condition. Outputs: ts: Array with ntrials columns, where each row is a different interval, containing sample intervals tp: Same as above for produced intervals Also produces a scatter plot showing the "metronomic curve" (ts vs tp) ''' from JazNets.Tasks import RHY import inspect # Initialize network RNN.initialize_act() init_trials = 3 print('Initializing',end="") for init_trial in range(init_trials): inp = RHY(n_ints=1, cont=1, **kwargs)[0] RNN.run(inp) print('.',end="") print("") # Set values of the intervals (based on defaults from Tasks.RHY) argspecs = inspect.getfullargspec(RHY) int_min = [argspecs.defaults[i] for i in range(len(argspecs)) if argspecs.args[i]=='int_min'] int_max = [argspecs.defaults[i] for i in range(len(argspecs)) if argspecs.args[i]=='int_max'] int_times = np.linspace(int_min,int_max,11) npatterns = len(int_times) # Initialize outputs ts = np.zeros((npatterns,ntrials)) tp = np.zeros((npatterns,ntrials)) dt = RNN.p['dt'] if showtrialplots: out_fig = plt.figure() out_ax = out_fig.add_subplot(111) for pat_idx in range(npatterns): # Iterate over interval patterns pat = int_times[pat_idx] if showtrialplots: inp, targ = RHY(ints=[pat], **kwargs)[0:2] trig = np.argmax(inp[:,1]) out_ax.plot(inp[trig:], 'g--') out_ax.plot(1+targ[trig:], 'r--') else: print('Interval: %gs' % pat, end="") for trial in range(ntrials): s = 0 nopes=0 while not s: # If you aren't successful at training inp, targ = RHY(ints=[pat], **kwargs)[0:2] out = RNN.run(inp)[0] error = np.mean((targ-out)**2)/np.mean((targ)**2) #print(error) # Use this line to see the error if the network is failing a lot if error<threshold: # Consider it a success if you are below some threshold s=1 ts[pat_idx,trial] = (np.argmax(targ[:,1]) - np.argmax(targ[:,0]))*dt tp[pat_idx,trial] = (np.argmax(out[:,1])-np.argmax(out[:,0]))*dt if showtrialplots: trig = np.argmax(inp[:,1]) out_ax.plot(1+out[trig:], 'b', alpha=0.2) out_ax.set_title(pat) out_fig.canvas.draw() elif not trial % (ntrials/50): print('.',end="") else: print(',',end="") nopes += 1 if nopes>100: raise RuntimeError('Cannot get a successful run! (error too high)') if not showtrialplots: print("") # Make metronomic curve plt.figure() plt.scatter(ts.flatten(), tp.flatten(), alpha=0.1, marker='.') plt.plot(ts[:,0],ts[:,0],'--') plt.title('Metronomic curve') plt.xlabel('$t_s$') plt.ylabel('$t_p$') plt.show() return ts, tp
[ "numpy.mean", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.argmax", "inspect.getfullargspec", "numpy.linspace", "matplotlib.pyplot.figure", "numpy.zeros", "JazNets.Tasks.RHY", "matplotlib.pyplot.title", "matplotlib.pyplot.show" ]
[((1646, 1673), 'inspect.getfullargspec', 'inspect.getfullargspec', (['RHY'], {}), '(RHY)\n', (1668, 1673), False, 'import inspect\n'), ((1921, 1954), 'numpy.linspace', 'np.linspace', (['int_min', 'int_max', '(11)'], {}), '(int_min, int_max, 11)\n', (1932, 1954), True, 'import numpy as np\n'), ((2023, 2053), 'numpy.zeros', 'np.zeros', (['(npatterns, ntrials)'], {}), '((npatterns, ntrials))\n', (2031, 2053), True, 'import numpy as np\n'), ((2062, 2092), 'numpy.zeros', 'np.zeros', (['(npatterns, ntrials)'], {}), '((npatterns, ntrials))\n', (2070, 2092), True, 'import numpy as np\n'), ((3955, 3967), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3965, 3967), True, 'import matplotlib.pyplot as plt\n'), ((4039, 4073), 'matplotlib.pyplot.plot', 'plt.plot', (['ts[:, 0]', 'ts[:, 0]', '"""--"""'], {}), "(ts[:, 0], ts[:, 0], '--')\n", (4047, 4073), True, 'import matplotlib.pyplot as plt\n'), ((4074, 4103), 'matplotlib.pyplot.title', 'plt.title', (['"""Metronomic curve"""'], {}), "('Metronomic curve')\n", (4083, 4103), True, 'import matplotlib.pyplot as plt\n'), ((4108, 4127), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$t_s$"""'], {}), "('$t_s$')\n", (4118, 4127), True, 'import matplotlib.pyplot as plt\n'), ((4132, 4151), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$t_p$"""'], {}), "('$t_p$')\n", (4142, 4151), True, 'import matplotlib.pyplot as plt\n'), ((4156, 4166), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4164, 4166), True, 'import matplotlib.pyplot as plt\n'), ((2160, 2172), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2170, 2172), True, 'import matplotlib.pyplot as plt\n'), ((1461, 1492), 'JazNets.Tasks.RHY', 'RHY', ([], {'n_ints': '(1)', 'cont': '(1)'}), '(n_ints=1, cont=1, **kwargs)\n', (1464, 1492), False, 'from JazNets.Tasks import RHY\n'), ((2426, 2446), 'numpy.argmax', 'np.argmax', (['inp[:, 1]'], {}), '(inp[:, 1])\n', (2435, 2446), True, 'import numpy as np\n'), ((2376, 2401), 'JazNets.Tasks.RHY', 'RHY', ([], {'ints': '[pat]'}), '(ints=[pat], **kwargs)\n', (2379, 2401), False, 'from JazNets.Tasks import RHY\n'), ((2766, 2791), 'JazNets.Tasks.RHY', 'RHY', ([], {'ints': '[pat]'}), '(ints=[pat], **kwargs)\n', (2769, 2791), False, 'from JazNets.Tasks import RHY\n'), ((2859, 2885), 'numpy.mean', 'np.mean', (['((targ - out) ** 2)'], {}), '((targ - out) ** 2)\n', (2866, 2885), True, 'import numpy as np\n'), ((2882, 2900), 'numpy.mean', 'np.mean', (['(targ ** 2)'], {}), '(targ ** 2)\n', (2889, 2900), True, 'import numpy as np\n'), ((3379, 3399), 'numpy.argmax', 'np.argmax', (['inp[:, 1]'], {}), '(inp[:, 1])\n', (3388, 3399), True, 'import numpy as np\n'), ((3155, 3176), 'numpy.argmax', 'np.argmax', (['targ[:, 1]'], {}), '(targ[:, 1])\n', (3164, 3176), True, 'import numpy as np\n'), ((3178, 3199), 'numpy.argmax', 'np.argmax', (['targ[:, 0]'], {}), '(targ[:, 0])\n', (3187, 3199), True, 'import numpy as np\n'), ((3244, 3264), 'numpy.argmax', 'np.argmax', (['out[:, 1]'], {}), '(out[:, 1])\n', (3253, 3264), True, 'import numpy as np\n'), ((3264, 3284), 'numpy.argmax', 'np.argmax', (['out[:, 0]'], {}), '(out[:, 0])\n', (3273, 3284), True, 'import numpy as np\n')]
from functools import partial from typing import Callable, Union import numpy as np from numpy.typing import NDArray from scipy import ndimage from scipy.sparse import lil_matrix from sklearn.ensemble import IsolationForest from sklearn.ensemble._iforest import _average_path_length from sklearn.utils import check_X_y try: from functools import cached_property except ImportError: from backports.cached_property import cached_property _LABEL_LEAF_REDUCER_T = Callable[[NDArray[np.float64]], float] _LABEL_LEAVES_REDUCER_T = Callable[[NDArray[np.float64], NDArray[np.int64], NDArray[np.int64]], NDArray[np.float64]] class SemiSupervisedIsolationForest(IsolationForest): """ Biased Isolation Forest The variant of the Isolation Forest (Liu et al 2008) which introduces artificial changes of depths of leaves containing labeled data. Parameters ---------- label_reducer : str or callable, optional How to reduce multiple labels accrued in a single leaf. Could be: 1) a callable with signature `f(labels)` where `labels` is a 1-D array built from `y` values, the callable must return a single floating number 2) a string with a name of pre-defined reducer, could be one of: - 'random' (default) gives random label - 'mean' gives mean of all values - 'sum' gives sum of all values - 'absmax' gives label with maximum absolute value """ X = None y = None def __init__(self, *, label_reducer: Union[str, _LABEL_LEAF_REDUCER_T] = 'random', **iforest_kwargs): super().__init__(**iforest_kwargs) self.rng = np.random.default_rng(iforest_kwargs.get('random_state', None)) self.label_reducer: _LABEL_LEAVES_REDUCER_T = self._get_label_reducer(label_reducer) def _mean_reducer(self, values: NDArray[np.float64], indices: NDArray[np.int64], unique_indices: NDArray[np.int64]) -> NDArray[np.float64]: return ndimage.mean( values, labels=indices, index=unique_indices, ) def _sum_reducer(self, values: NDArray[np.float64], indices: NDArray[np.int64], unique_indices: NDArray[np.int64]) -> NDArray[np.float64]: return ndimage.sum_labels( values, labels=indices, index=unique_indices, ) @staticmethod def _reducer(values: NDArray[np.float64], indices: NDArray[np.int64], unique_indices: NDArray[np.int64], func: _LABEL_LEAF_REDUCER_T) -> NDArray[np.float64]: return ndimage.labeled_comprehension( values, labels=indices, index=unique_indices, func=func, out_dtype=np.float64, default=None, ) def _absmax_reducer(self, values: NDArray[np.float64], indices: NDArray[np.int64], unique_indices: NDArray[np.int64]) -> NDArray[np.float64]: return self._reducer(values, indices, unique_indices, func=lambda x: x[np.argmax(np.abs(x))]) def _random_reducer(self, values: NDArray[np.float64], indices: NDArray[np.int64], unique_indices: NDArray[np.int64]) -> NDArray[np.float64]: return self._reducer(values, indices, unique_indices, func=lambda x: self.rng.choice(x)) def _get_label_reducer(self, x: Union[str, _LABEL_LEAF_REDUCER_T]) -> _LABEL_LEAVES_REDUCER_T: if callable(x): return partial(self._reducer, func=x) return getattr(self, f'_{x}_reducer') def fit(self, X, y, sample_weight=None): """ Fit estimator. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Use ``dtype=np.float32`` for maximum efficiency. Sparse matrices are also supported, use sparse ``csc_matrix`` for maximum efficiency. y : {array-like} of shape (n_samples,) Input anomality labels, use zero for non-labeled data, positive values for known anomalies and negative values for known non-anomalies. It is assumed that most of the data is unlabeled, so the most of the elements must be zero. The typical absolute values of labels are between unity and `np.log2(y.shape[0]) / 2` sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Returns ------- self : object Fitted estimator. """ X, y = check_X_y(X, y, accept_sparse=['csc'], y_numeric=True) if np.all(y == 0): raise ValueError('All labels are zero, use scikit.ensemble.IsolationForest instead') self.X = X self.y = y return super().fit(X, y=None, sample_weight=sample_weight) @cached_property def leaf_impacts_(self): impact_idx = self.y != 0 sample_impact = self.y[impact_idx] leaf_impacts_ = [] for tree, features in zip(self.estimators_, self.estimators_features_): X_subset = self.X[impact_idx, features] if self._max_features != self.X.shape[1] else self.X[impact_idx] leaves_index = tree.apply(X_subset) unique_leaves_index = np.unique(leaves_index) impacts = lil_matrix((1, tree.tree_.n_node_samples.shape[0]), dtype=self.y.dtype) impacts[0, unique_leaves_index] = self.label_reducer(sample_impact, leaves_index, unique_leaves_index) leaf_impacts_.append(impacts) return leaf_impacts_ def _compute_score_samples(self, X, subsample_features): scores = super()._compute_score_samples(X, subsample_features) depths = np.zeros(X.shape[0], order="f") for tree, features, impacts in zip(self.estimators_, self.estimators_features_, self.leaf_impacts_): X_subset = X[:, features] if subsample_features else X leaves_index = tree.apply(X_subset) depths += -np.ravel(impacts[0, leaves_index].toarray()) scores *= 2 ** ( -depths / (len(self.estimators_) * _average_path_length([self.max_samples_])) ) return scores
[ "numpy.abs", "scipy.sparse.lil_matrix", "numpy.unique", "sklearn.ensemble._iforest._average_path_length", "sklearn.utils.check_X_y", "scipy.ndimage.mean", "numpy.zeros", "functools.partial", "scipy.ndimage.sum_labels", "scipy.ndimage.labeled_comprehension", "numpy.all" ]
[((2063, 2121), 'scipy.ndimage.mean', 'ndimage.mean', (['values'], {'labels': 'indices', 'index': 'unique_indices'}), '(values, labels=indices, index=unique_indices)\n', (2075, 2121), False, 'from scipy import ndimage\n'), ((2391, 2455), 'scipy.ndimage.sum_labels', 'ndimage.sum_labels', (['values'], {'labels': 'indices', 'index': 'unique_indices'}), '(values, labels=indices, index=unique_indices)\n', (2409, 2455), False, 'from scipy import ndimage\n'), ((2750, 2876), 'scipy.ndimage.labeled_comprehension', 'ndimage.labeled_comprehension', (['values'], {'labels': 'indices', 'index': 'unique_indices', 'func': 'func', 'out_dtype': 'np.float64', 'default': 'None'}), '(values, labels=indices, index=unique_indices,\n func=func, out_dtype=np.float64, default=None)\n', (2779, 2876), False, 'from scipy import ndimage\n'), ((4874, 4928), 'sklearn.utils.check_X_y', 'check_X_y', (['X', 'y'], {'accept_sparse': "['csc']", 'y_numeric': '(True)'}), "(X, y, accept_sparse=['csc'], y_numeric=True)\n", (4883, 4928), False, 'from sklearn.utils import check_X_y\n'), ((4940, 4954), 'numpy.all', 'np.all', (['(y == 0)'], {}), '(y == 0)\n', (4946, 4954), True, 'import numpy as np\n'), ((6048, 6079), 'numpy.zeros', 'np.zeros', (['X.shape[0]'], {'order': '"""f"""'}), "(X.shape[0], order='f')\n", (6056, 6079), True, 'import numpy as np\n'), ((3736, 3766), 'functools.partial', 'partial', (['self._reducer'], {'func': 'x'}), '(self._reducer, func=x)\n', (3743, 3766), False, 'from functools import partial\n'), ((5592, 5615), 'numpy.unique', 'np.unique', (['leaves_index'], {}), '(leaves_index)\n', (5601, 5615), True, 'import numpy as np\n'), ((5638, 5709), 'scipy.sparse.lil_matrix', 'lil_matrix', (['(1, tree.tree_.n_node_samples.shape[0])'], {'dtype': 'self.y.dtype'}), '((1, tree.tree_.n_node_samples.shape[0]), dtype=self.y.dtype)\n', (5648, 5709), False, 'from scipy.sparse import lil_matrix\n'), ((6484, 6525), 'sklearn.ensemble._iforest._average_path_length', '_average_path_length', (['[self.max_samples_]'], {}), '([self.max_samples_])\n', (6504, 6525), False, 'from sklearn.ensemble._iforest import _average_path_length\n'), ((3264, 3273), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (3270, 3273), True, 'import numpy as np\n')]
# import unittest import numpy as np # require: pip install flaml[blendsearch, ray] # require: pip install flaml[ray] import time from flaml import tune def evaluate_config(config): """evaluate a hyperparameter configuration""" # we uss a toy example with 2 hyperparameters metric = (round(config["x"]) - 85000) ** 2 - config["x"] / config["y"] # usually the evaluation takes an non-neglible cost # and the cost could be related to certain hyperparameters # in this example, we assume it's proportional to x time.sleep(config["x"] / 100000) # use tune.report to report the metric to optimize tune.report(metric=metric) config_search_space = { "x": tune.lograndint(lower=1, upper=100000), "y": tune.randint(lower=1, upper=100000), } low_cost_partial_config = {"x": 1} def setup_searcher(searcher_name): from flaml.searcher.blendsearch import BlendSearch, CFO, RandomSearch if "cfo" in searcher_name: searcher = CFO( space=config_search_space, low_cost_partial_config=low_cost_partial_config ) elif searcher_name == "bs": searcher = BlendSearch( metric="metric", mode="min", space=config_search_space, low_cost_partial_config=low_cost_partial_config, ) elif searcher_name == "random": searcher = RandomSearch(space=config_search_space) else: return None return searcher def _test_flaml_raytune_consistency( num_samples=-1, max_concurrent_trials=1, searcher_name="cfo" ): try: from ray import tune as raytune except ImportError: print( "skip _test_flaml_raytune_consistency because ray tune cannot be imported." ) return np.random.seed(100) searcher = setup_searcher(searcher_name) analysis = tune.run( evaluate_config, # the function to evaluate a config config=config_search_space, # the search space low_cost_partial_config=low_cost_partial_config, # a initial (partial) config with low cost metric="metric", # the name of the metric used for optimization mode="min", # the optimization mode, 'min' or 'max' num_samples=num_samples, # the maximal number of configs to try, -1 means infinite time_budget_s=None, # the time budget in seconds local_dir="logs/", # the local directory to store logs search_alg=searcher, # verbose=0, # verbosity # use_ray=True, # uncomment when performing parallel tuning using ray ) flaml_best_config = analysis.best_config flaml_config_in_results = [v["config"] for v in analysis.results.values()] flaml_time_in_results = [v["time_total_s"] for v in analysis.results.values()] print(analysis.best_trial.last_result) # the best trial's result np.random.seed(100) searcher = setup_searcher(searcher_name) from ray.tune.suggest import ConcurrencyLimiter search_alg = ConcurrencyLimiter(searcher, max_concurrent_trials) analysis = raytune.run( evaluate_config, # the function to evaluate a config config=config_search_space, metric="metric", # the name of the metric used for optimization mode="min", # the optimization mode, 'min' or 'max' num_samples=num_samples, # the maximal number of configs to try, -1 means infinite local_dir="logs/", # the local directory to store logs # max_concurrent_trials=max_concurrent_trials, # resources_per_trial={"cpu": max_concurrent_trials, "gpu": 0}, search_alg=search_alg, ) ray_best_config = analysis.best_config ray_config_in_results = [v["config"] for v in analysis.results.values()] ray_time_in_results = [v["time_total_s"] for v in analysis.results.values()] print(analysis.best_trial.last_result) # the best trial's result print("time_total_s in flaml", flaml_time_in_results) # the best trial's result print("time_total_s in ray", ray_time_in_results) # the best trial's result print("best flaml", searcher_name, flaml_best_config) # the best config print("ray best", searcher_name, ray_best_config) # the best config print("flaml config in results", searcher_name, flaml_config_in_results) print("ray config in results", searcher_name, ray_config_in_results) assert ray_best_config == flaml_best_config, "best config should be the same" assert ( flaml_config_in_results == ray_config_in_results ), "results from raytune and flaml should be the same" def test_consistency(): _test_flaml_raytune_consistency( num_samples=5, max_concurrent_trials=1, searcher_name="random" ) _test_flaml_raytune_consistency( num_samples=5, max_concurrent_trials=1, searcher_name="cfo" ) _test_flaml_raytune_consistency( num_samples=5, max_concurrent_trials=1, searcher_name="bs" ) if __name__ == "__main__": # unittest.main() test_consistency()
[ "flaml.tune.lograndint", "flaml.tune.run", "ray.tune.suggest.ConcurrencyLimiter", "time.sleep", "flaml.searcher.blendsearch.RandomSearch", "flaml.searcher.blendsearch.CFO", "flaml.searcher.blendsearch.BlendSearch", "numpy.random.seed", "flaml.tune.randint", "ray.tune.run", "flaml.tune.report" ]
[((539, 571), 'time.sleep', 'time.sleep', (["(config['x'] / 100000)"], {}), "(config['x'] / 100000)\n", (549, 571), False, 'import time\n'), ((631, 657), 'flaml.tune.report', 'tune.report', ([], {'metric': 'metric'}), '(metric=metric)\n', (642, 657), False, 'from flaml import tune\n'), ((693, 731), 'flaml.tune.lograndint', 'tune.lograndint', ([], {'lower': '(1)', 'upper': '(100000)'}), '(lower=1, upper=100000)\n', (708, 731), False, 'from flaml import tune\n'), ((742, 777), 'flaml.tune.randint', 'tune.randint', ([], {'lower': '(1)', 'upper': '(100000)'}), '(lower=1, upper=100000)\n', (754, 777), False, 'from flaml import tune\n'), ((1765, 1784), 'numpy.random.seed', 'np.random.seed', (['(100)'], {}), '(100)\n', (1779, 1784), True, 'import numpy as np\n'), ((1845, 2074), 'flaml.tune.run', 'tune.run', (['evaluate_config'], {'config': 'config_search_space', 'low_cost_partial_config': 'low_cost_partial_config', 'metric': '"""metric"""', 'mode': '"""min"""', 'num_samples': 'num_samples', 'time_budget_s': 'None', 'local_dir': '"""logs/"""', 'search_alg': 'searcher'}), "(evaluate_config, config=config_search_space,\n low_cost_partial_config=low_cost_partial_config, metric='metric', mode=\n 'min', num_samples=num_samples, time_budget_s=None, local_dir='logs/',\n search_alg=searcher)\n", (1853, 2074), False, 'from flaml import tune\n'), ((2859, 2878), 'numpy.random.seed', 'np.random.seed', (['(100)'], {}), '(100)\n', (2873, 2878), True, 'import numpy as np\n'), ((2994, 3045), 'ray.tune.suggest.ConcurrencyLimiter', 'ConcurrencyLimiter', (['searcher', 'max_concurrent_trials'], {}), '(searcher, max_concurrent_trials)\n', (3012, 3045), False, 'from ray.tune.suggest import ConcurrencyLimiter\n'), ((3061, 3222), 'ray.tune.run', 'raytune.run', (['evaluate_config'], {'config': 'config_search_space', 'metric': '"""metric"""', 'mode': '"""min"""', 'num_samples': 'num_samples', 'local_dir': '"""logs/"""', 'search_alg': 'search_alg'}), "(evaluate_config, config=config_search_space, metric='metric',\n mode='min', num_samples=num_samples, local_dir='logs/', search_alg=\n search_alg)\n", (3072, 3222), True, 'from ray import tune as raytune\n'), ((979, 1058), 'flaml.searcher.blendsearch.CFO', 'CFO', ([], {'space': 'config_search_space', 'low_cost_partial_config': 'low_cost_partial_config'}), '(space=config_search_space, low_cost_partial_config=low_cost_partial_config)\n', (982, 1058), False, 'from flaml.searcher.blendsearch import BlendSearch, CFO, RandomSearch\n'), ((1132, 1252), 'flaml.searcher.blendsearch.BlendSearch', 'BlendSearch', ([], {'metric': '"""metric"""', 'mode': '"""min"""', 'space': 'config_search_space', 'low_cost_partial_config': 'low_cost_partial_config'}), "(metric='metric', mode='min', space=config_search_space,\n low_cost_partial_config=low_cost_partial_config)\n", (1143, 1252), False, 'from flaml.searcher.blendsearch import BlendSearch, CFO, RandomSearch\n'), ((1363, 1402), 'flaml.searcher.blendsearch.RandomSearch', 'RandomSearch', ([], {'space': 'config_search_space'}), '(space=config_search_space)\n', (1375, 1402), False, 'from flaml.searcher.blendsearch import BlendSearch, CFO, RandomSearch\n')]
import numpy as numpy a = numpy.arange(10) b = a[5] c = a[2:] d = a[2:5] print (b) print (c) print (d)
[ "numpy.arange" ]
[((27, 43), 'numpy.arange', 'numpy.arange', (['(10)'], {}), '(10)\n', (39, 43), True, 'import numpy as numpy\n')]
""" **Description** A principal component model analyzes an incident signal to define transformation matrices which consume an incident signal to produce a reference signal, normalized and ordered to define orthogonal axes of descending variance. A principal component model is a supervised learning model which analyzes an incident signal representing a training set to learn a mean vector, standard deviation vector, and a collection of eigenvectors associated with an incident signal. .. math:: \\vec{\mu_{i}} = \matrix{\ \\frac{\sum_{n=0}^{N}\\vec{x_{i,n}}}{N}} .. math:: \\vec{\sigma_{i}} = \matrix{\ \\frac{\sum_{n=0}^{N}(\ \\vec{x_{i,n}} - \\vec{\mu_{i}}\ )^{2}}{N}}^{0.5} .. math:: \Lambda_{n} = eig\matrix{\ cov\matrix{\ \matrix{\\frac{\ X_{n}^{T} - \\vec{\mu}\ }{\\vec{\sigma}}\ }\ }^{T}\ }^{T} An incident signal which is not a part of an inital training set is transformed without modifying a principal component model, by translation, normalization, and rotation to produce a reference signal which is a candidate for dimension reduction, in which higher order dimensions are discarded, reducing the order of the reference signal, while preserving significant and often sufficient information. .. math:: Y_{n} = \Lambda_{n} \ \matrix{\\frac{\ X_{n}^{T} - \\vec{\mu}\ }{\\vec{\sigma}}\ }^{T} Principal component analysis and dimension reduction has application in clustering, classification, pattern recognition, and visualization. **Example** :: from diamondback import PrincipalComponentModel # Create an instance. obj = PrincipalComponentModel( ) # Model an incident signal and extract eigenvalue, standard deviation, means, and rotation arrays. x = numpy.random.rand( 3, 32 ) y = obj.model( x ) e, s, u, v = obj.e, obj.s, obj.u, obj.v **License** `BSD-3C. <https://github.com/larryturner/diamondback/blob/master/license>`_ © 2018 - 2021 <NAME>, Schneider Electric Industries SAS. All rights reserved. **Author** <NAME>, Schneider Electric, Analytics & AI, 2019-01-25. """ from diamondback.interfaces.IClear import IClear from diamondback.interfaces.IS import IS from typing import List, Union import numpy class PrincipalComponentModel( IClear, IS ) : """ Principal component model. """ @property def e( self ) : """ e : numpy.ndarray - eigenvalues. """ return self._e @property def u( self ) : """ mean : numpy.ndarray. """ return self._u @property def v( self ) : """ rotation : numpy.ndarray """ return self._v def __init__( self ) -> None : """ Initialize. """ super( ).__init__( ) self._e, self._u, self._v = numpy.array( [ ] ), numpy.array( [ ] ), numpy.array( [ ] ) self.s = numpy.array( [ ] ) def clear( self ) -> None : """ Clears an instance. """ self._e, self._u, self._v = numpy.array( [ ] ), numpy.array( [ ] ), numpy.array( [ ] ) self.s = numpy.array( [ ] ) def model( self, x : Union[ List, numpy.ndarray ] ) -> numpy.ndarray : """ Models an incident signal and produces a reference signal. Arguments : x : Union[ List, numpy.ndarray ] - incident signal. Returns : y : numpy.ndarray - reference signal. """ if ( ( not numpy.isscalar( x ) ) and ( not isinstance( x, numpy.ndarray ) ) ) : x = numpy.array( list( x ) ) if ( ( len( x.shape ) != 2 ) or ( not len( x ) ) ) : raise ValueError( f'X = {x}' ) if ( not len( self.s ) ) : self._u = x.mean( 1 ) self.s = x.std( 1 ) z = ( ( x.T - self.u ) / self.s ).T self._e, self._v = numpy.linalg.eig( numpy.matmul( z, z.T ) / z.shape[ 1 ] ) self._v = self._v.T else : z = ( ( x.T - self.u ) / self.s ).T rows, cols = x.shape if ( ( rows != len( self._u ) ) or ( ( rows, rows ) != self._v.shape ) or ( cols <= 0 ) ): raise ValueError( f'Rows = {rows} Columns = {cols}' ) return numpy.matmul( self.v, z )
[ "numpy.array", "numpy.matmul", "numpy.isscalar" ]
[((3129, 3144), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (3140, 3144), False, 'import numpy\n'), ((3339, 3354), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (3350, 3354), False, 'import numpy\n'), ((4464, 4487), 'numpy.matmul', 'numpy.matmul', (['self.v', 'z'], {}), '(self.v, z)\n', (4476, 4487), False, 'import numpy\n'), ((3053, 3068), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (3064, 3068), False, 'import numpy\n'), ((3073, 3088), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (3084, 3088), False, 'import numpy\n'), ((3093, 3108), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (3104, 3108), False, 'import numpy\n'), ((3263, 3278), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (3274, 3278), False, 'import numpy\n'), ((3283, 3298), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (3294, 3298), False, 'import numpy\n'), ((3303, 3318), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (3314, 3318), False, 'import numpy\n'), ((3708, 3725), 'numpy.isscalar', 'numpy.isscalar', (['x'], {}), '(x)\n', (3722, 3725), False, 'import numpy\n'), ((4120, 4140), 'numpy.matmul', 'numpy.matmul', (['z', 'z.T'], {}), '(z, z.T)\n', (4132, 4140), False, 'import numpy\n')]
""" Challenge Exercises for Chapter 4. """ import timeit from algs.modeling import numpy_error from algs.table import DataTable, ExerciseNum, comma, caption from algs.modeling import n_log_n_model def merged_arrays(heap1, heap2): """Return combined array with sorted values.""" result = [None] * (heap1.N + heap2.N) idx = len(result)-1 while idx >= 0: if heap1.is_empty(): result[idx] = heap2.dequeue() elif heap2.is_empty(): result[idx] = heap1.dequeue() else: if heap1.peek().priority > heap2.peek().priority: result[idx] = heap1.dequeue() else: result[idx] = heap2.dequeue() idx -= 1 return result # Executes 3*N/2 add operations and 3*N/2 remove_max operations for a total of 3*N def run_merge_trial(m, n): """Generate data for Merge Sort results.""" return min(timeit.repeat(stmt='merged_arrays(heap1, heap2)', setup = ''' import random from ch04.heap import PQ from ch04.challenge import merged_arrays heap1 = PQ({0}) heap2 = PQ({1}) random.seed({0}) for _ in range({0}): r1 = random.randint(0,16777216) heap1.enqueue(r1,r1) random.seed({1}) for _ in range({1}): r2 = random.randint(0,16777216) heap2.enqueue(r2,r2)'''.format(m,n), repeat=5, number=1)) def combined_sorted(lo=8, hi=12, output=True): """Generate results for different sorting trials.""" tbl = DataTable([8] * (hi-lo+1), ['N'] + [comma(2**k) for k in range(lo,hi)], output=output) for n in [2**k for k in range(lo,hi)]: row = [n] for m in [2**k for k in range(lo,hi)]: row.append(run_merge_trial(m,n)) tbl.row(row) # Diagonal values are for 2*M*log(M) so divide in HALF for accurate one # build model ONLY for first five values x = [2**k for k in range(lo,min(lo+5,hi))] y = [tbl.entry(r,comma(r)) for r in [2**k for k in range(lo,min(lo+5,hi))]] if numpy_error: a = 0 else: import numpy as np from scipy.optimize import curve_fit from scipy.stats.stats import pearsonr (coeffs,_) = curve_fit(n_log_n_model, np.array(x), np.array(y)) a = coeffs[0] / 2 y_fit = [n_log_n_model(r,a) for r in [2**k for k in range(lo,min(lo+5,hi))]] print() print(pearsonr(y, y_fit)) print() print('Prediction') model = DataTable([8] * (hi-lo+1), ['N'] + [comma(2**k) for k in range(lo,hi)], output=output) for n in [2**k for k in range(lo,hi)]: row = [n] for m in [2**k for k in range(lo,hi)]: row.append(n_log_n_model(n,a) + n_log_n_model(m,a)) model.row(row) return tbl def k_smallest(A, k): """ Super-efficient (and easy to write) k-smallest selection for an arbitrary iterable. Time (and space) will be proportional to O(log k). """ from ch04.heap import PQ pq = PQ(k) # pq is a regular Max Binary Heap. Enqueue first k elements. If any # subsequent value is LARGER than our largest, it can be ignored, otherwise # remove the largest (since one is now smaller) and enqueue it. for v in A: if pq.N < k: pq.enqueue(v, v) else: if v < pq.peek().priority: # There is a chance to replace one of k-smallest values with this one pq.dequeue() pq.enqueue(v,v) result = [] while pq: result.append(pq.dequeue()) return list(reversed(result)) def random_trial_k_smallest(n, k): """Conduct a random k_smallest trial.""" from random import shuffle vals = list(range(n)) shuffle(vals) return k_smallest(vals, k) def iterator(pq): """ Provides a Python-generator over a PQ, using a PQ to do it! Each entry in the pqit iterator has (value, priority) where value is an index position into the original pq, while its priority is the priority if the entry. You can add capability for fail-fast iterators IF the heap actively increments a count in its pq.storage[0] which is unused anyway. Returned values include both the (value, priority) for maximum flexibility. """ from ch04.heap import PQ N = len(pq) # This works with INDEX positions into the heap pqit = PQ(N) pqit.enqueue(1, pq.peek().priority) while pqit: idx = pqit.dequeue() yield (pq.storage[idx].value, pq.storage[idx].priority) child = 2*idx if child <= pq.N: pqit.enqueue(child, pq.storage[child].priority) child += 1 if child <= pq.N: pqit.enqueue(child, pq.storage[child].priority) def iterator_trial(): """Generate a sample Priority Queue and show iterator capability.""" from ch04.heap import PQ import random # populate pq = PQ(63) pq2 = PQ(63) for _ in range(63): prior = random.randint(0, 100) pq.enqueue(prior, prior) pq2.enqueue(prior, prior) for p in iterator(pq2): vp = pq.dequeue() if p[0] != vp: raise RuntimeError('Unexpected that iterator is different.') def inspect_heap_array(): """ After inserting N elements in ascending order, is there a pattern in the values in the arrays in the heap? Same for inserting in descending order. """ from ch04.heap import PQ num=31 pq = PQ(num) for i in range(1,num+1): pq.enqueue(i, i) i = 1 rights = [] while i <= num: rights.append(pq.storage[i].value) i = (i*2) + 1 print(rights) print([i.value for i in pq.storage[1:]]) pq = PQ(num) for i in range(num, 0, -1): pq.enqueue(i, i) ####################################################################### if __name__ == '__main__': chapter = 4 with ExerciseNum(1) as exercise_number: print('implementation in ch04.circular_queue') print(caption(chapter, exercise_number), 'Circular Queue') print() with ExerciseNum(2) as exercise_number: inspect_heap_array() print('When inserting N=2^k-1 values in ascending order, right most values') print('in each of the k levels contains largest. When inserting in reverse') print('order, each value remains where it was inserted, so all are descending.') print(caption(chapter, exercise_number),'Values in heap') print() with ExerciseNum(3) as exercise_number: combined_sorted(hi=16) print(caption(chapter, exercise_number), 'Merging two heaps in O(M*log(M) + N*log(N)') print() with ExerciseNum(4) as exercise_number: print(random_trial_k_smallest(5, 2**20), 'are the 5 smallest values in 0 .. 2**20') print(caption(chapter, exercise_number), 'Find k smallest values from a collection in time O(log k).') print() with ExerciseNum(5) as exercise_number: from ch04.timing import trial_factorial_heap trial_factorial_heap() print(caption(chapter, exercise_number), 'Factorial Heap.') print() with ExerciseNum(6) as exercise_number: print(caption(chapter, exercise_number), 'standard extension of Heap to dynamically resize.') print() with ExerciseNum(7) as exercise_number: iterator_trial() print(caption(chapter, exercise_number), 'Non-destructive iterator for a max binary heap.') print()
[ "random.shuffle", "ch04.heap.PQ", "algs.modeling.n_log_n_model", "algs.table.caption", "ch04.timing.trial_factorial_heap", "numpy.array", "algs.table.ExerciseNum", "scipy.stats.stats.pearsonr", "random.randint", "algs.table.comma" ]
[((2968, 2973), 'ch04.heap.PQ', 'PQ', (['k'], {}), '(k)\n', (2970, 2973), False, 'from ch04.heap import PQ\n'), ((3705, 3718), 'random.shuffle', 'shuffle', (['vals'], {}), '(vals)\n', (3712, 3718), False, 'from random import shuffle\n'), ((4351, 4356), 'ch04.heap.PQ', 'PQ', (['N'], {}), '(N)\n', (4353, 4356), False, 'from ch04.heap import PQ\n'), ((4888, 4894), 'ch04.heap.PQ', 'PQ', (['(63)'], {}), '(63)\n', (4890, 4894), False, 'from ch04.heap import PQ\n'), ((4905, 4911), 'ch04.heap.PQ', 'PQ', (['(63)'], {}), '(63)\n', (4907, 4911), False, 'from ch04.heap import PQ\n'), ((5441, 5448), 'ch04.heap.PQ', 'PQ', (['num'], {}), '(num)\n', (5443, 5448), False, 'from ch04.heap import PQ\n'), ((5688, 5695), 'ch04.heap.PQ', 'PQ', (['num'], {}), '(num)\n', (5690, 5695), False, 'from ch04.heap import PQ\n'), ((4952, 4974), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (4966, 4974), False, 'import random\n'), ((5879, 5893), 'algs.table.ExerciseNum', 'ExerciseNum', (['(1)'], {}), '(1)\n', (5890, 5893), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((6062, 6076), 'algs.table.ExerciseNum', 'ExerciseNum', (['(2)'], {}), '(2)\n', (6073, 6076), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((6477, 6491), 'algs.table.ExerciseNum', 'ExerciseNum', (['(3)'], {}), '(3)\n', (6488, 6491), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((6678, 6692), 'algs.table.ExerciseNum', 'ExerciseNum', (['(4)'], {}), '(4)\n', (6689, 6692), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((6956, 6970), 'algs.table.ExerciseNum', 'ExerciseNum', (['(5)'], {}), '(5)\n', (6967, 6970), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((7052, 7074), 'ch04.timing.trial_factorial_heap', 'trial_factorial_heap', ([], {}), '()\n', (7072, 7074), False, 'from ch04.timing import trial_factorial_heap\n'), ((7183, 7197), 'algs.table.ExerciseNum', 'ExerciseNum', (['(6)'], {}), '(6)\n', (7194, 7197), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((7360, 7374), 'algs.table.ExerciseNum', 'ExerciseNum', (['(7)'], {}), '(7)\n', (7371, 7374), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((1887, 1895), 'algs.table.comma', 'comma', (['r'], {}), '(r)\n', (1892, 1895), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((2156, 2167), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2164, 2167), True, 'import numpy as np\n'), ((2169, 2180), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (2177, 2180), True, 'import numpy as np\n'), ((2226, 2245), 'algs.modeling.n_log_n_model', 'n_log_n_model', (['r', 'a'], {}), '(r, a)\n', (2239, 2245), False, 'from algs.modeling import n_log_n_model\n'), ((2325, 2343), 'scipy.stats.stats.pearsonr', 'pearsonr', (['y', 'y_fit'], {}), '(y, y_fit)\n', (2333, 2343), False, 'from scipy.stats.stats import pearsonr\n'), ((5983, 6016), 'algs.table.caption', 'caption', (['chapter', 'exercise_number'], {}), '(chapter, exercise_number)\n', (5990, 6016), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((6399, 6432), 'algs.table.caption', 'caption', (['chapter', 'exercise_number'], {}), '(chapter, exercise_number)\n', (6406, 6432), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((6557, 6590), 'algs.table.caption', 'caption', (['chapter', 'exercise_number'], {}), '(chapter, exercise_number)\n', (6564, 6590), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((6819, 6852), 'algs.table.caption', 'caption', (['chapter', 'exercise_number'], {}), '(chapter, exercise_number)\n', (6826, 6852), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((7089, 7122), 'algs.table.caption', 'caption', (['chapter', 'exercise_number'], {}), '(chapter, exercise_number)\n', (7096, 7122), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((7232, 7265), 'algs.table.caption', 'caption', (['chapter', 'exercise_number'], {}), '(chapter, exercise_number)\n', (7239, 7265), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((7434, 7467), 'algs.table.caption', 'caption', (['chapter', 'exercise_number'], {}), '(chapter, exercise_number)\n', (7441, 7467), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((1471, 1484), 'algs.table.comma', 'comma', (['(2 ** k)'], {}), '(2 ** k)\n', (1476, 1484), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((2441, 2454), 'algs.table.comma', 'comma', (['(2 ** k)'], {}), '(2 ** k)\n', (2446, 2454), False, 'from algs.table import DataTable, ExerciseNum, comma, caption\n'), ((2665, 2684), 'algs.modeling.n_log_n_model', 'n_log_n_model', (['n', 'a'], {}), '(n, a)\n', (2678, 2684), False, 'from algs.modeling import n_log_n_model\n'), ((2686, 2705), 'algs.modeling.n_log_n_model', 'n_log_n_model', (['m', 'a'], {}), '(m, a)\n', (2699, 2705), False, 'from algs.modeling import n_log_n_model\n')]
import sys import tensorflow as tf from tensorflow.python.ops import summary_ops_v2 from tensorflow.python.eager import context import numpy as np from VOClabelcolormap import color_map from common import blend_from_3d_one_hots class MyTensorBoardCallback(tf.keras.callbacks.TensorBoard): def __init__(self, args, test_input_fn, log_dir='logs', histogram_freq=0, write_graph=True, write_images=False, update_freq='epoch', profile_batch=2, embeddings_freq=0, embeddings_metadata=None, **kwargs): super().__init__(log_dir, histogram_freq, write_graph, write_images, update_freq, profile_batch, embeddings_freq, embeddings_metadata, **kwargs) self.args = args self.cmap = color_map() self.last_training_epoch = 0 self.last_test_image_prediction_epoch = -1 it = iter(test_input_fn) self.images_to_predict = next(it).numpy() @staticmethod def _parse_args(args): header_row = 'Parameter | Value\n' \ '----------|------\n' args_dict = vars(args) # TODO: Move logic below out of this class if not args_dict['comment']: del args_dict['comment'] if not args_dict['use_early_stopping']: del args_dict['early_stopping_patience'] del args_dict['early_stopping_min_delta'] if not args_dict['reduce_on_plateu_patience']: del args_dict['reduce_on_plateu_factor'] del args_dict['reduce_on_plateu_epsilon'] sys_arguments = ["{}=\"{}\"".format(argument.split('=')[0], argument.split('=')[1]) if " " in argument and "=" in argument else argument for argument in sys.argv[1:]] args_dict['command'] = 'python train.py {}'.format(" ".join(sys_arguments)) table_body = ["{} | {}".format(key, value) for key, value in args_dict.items()] markdown = header_row + "\n".join(table_body) return markdown def on_epoch_begin(self, epoch, logs=None): super().on_epoch_begin(epoch, logs) self.last_training_epoch = epoch def on_train_begin(self, logs=None): super().on_train_begin(logs) writer_name = self._train_run_name with context.eager_mode(): with summary_ops_v2.always_record_summaries(): writer = self._get_writer(writer_name) with writer.as_default(): tensor = tf.convert_to_tensor(self._parse_args(self.args)) tf.summary.text("run_settings", tensor, step=1) def on_test_batch_begin(self, batch, logs=None): super().on_test_batch_begin(batch, logs) if self.last_training_epoch == self.last_test_image_prediction_epoch: return annotations = self.model.predict(self.images_to_predict, steps=1) blended_examples = [blend_from_3d_one_hots(image, annotation, self.cmap, alpha=0.5) for image, annotation in zip(self.images_to_predict, annotations)] writer_name = self._validation_run_name with context.eager_mode(): with summary_ops_v2.always_record_summaries(): writer = self._get_writer(writer_name) with writer.as_default(): tensor = tf.convert_to_tensor(np.array(blended_examples)) tf.summary.image("test_image", tensor, step=self.last_training_epoch, max_outputs=len(blended_examples)) self.last_test_image_prediction_epoch = self.last_training_epoch
[ "tensorflow.python.eager.context.eager_mode", "tensorflow.python.ops.summary_ops_v2.always_record_summaries", "numpy.array", "tensorflow.summary.text", "common.blend_from_3d_one_hots", "VOClabelcolormap.color_map" ]
[((745, 756), 'VOClabelcolormap.color_map', 'color_map', ([], {}), '()\n', (754, 756), False, 'from VOClabelcolormap import color_map\n'), ((2315, 2335), 'tensorflow.python.eager.context.eager_mode', 'context.eager_mode', ([], {}), '()\n', (2333, 2335), False, 'from tensorflow.python.eager import context\n'), ((2945, 3008), 'common.blend_from_3d_one_hots', 'blend_from_3d_one_hots', (['image', 'annotation', 'self.cmap'], {'alpha': '(0.5)'}), '(image, annotation, self.cmap, alpha=0.5)\n', (2967, 3008), False, 'from common import blend_from_3d_one_hots\n'), ((3194, 3214), 'tensorflow.python.eager.context.eager_mode', 'context.eager_mode', ([], {}), '()\n', (3212, 3214), False, 'from tensorflow.python.eager import context\n'), ((2354, 2394), 'tensorflow.python.ops.summary_ops_v2.always_record_summaries', 'summary_ops_v2.always_record_summaries', ([], {}), '()\n', (2392, 2394), False, 'from tensorflow.python.ops import summary_ops_v2\n'), ((3233, 3273), 'tensorflow.python.ops.summary_ops_v2.always_record_summaries', 'summary_ops_v2.always_record_summaries', ([], {}), '()\n', (3271, 3273), False, 'from tensorflow.python.ops import summary_ops_v2\n'), ((2592, 2639), 'tensorflow.summary.text', 'tf.summary.text', (['"""run_settings"""', 'tensor'], {'step': '(1)'}), "('run_settings', tensor, step=1)\n", (2607, 2639), True, 'import tensorflow as tf\n'), ((3422, 3448), 'numpy.array', 'np.array', (['blended_examples'], {}), '(blended_examples)\n', (3430, 3448), True, 'import numpy as np\n')]
########################################################################## # NSAp - Copyright (C) CEA, 2013 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for details. ########################################################################## """ Utility Python functions to load diffusion metadata. """ # System import import numpy import math import os import numpy as np import nibabel def extract_dwi_shells(dwi_nii_path, bvals_path, bvecs_path, outdir): """ Convert a multi-shell serie to multiple single shell series. Parameters ---------- dwi_nii_path: str path to the diffusion volume file. bvals_path: str path to the diffusion b-values file. bvecs_path: str path to the diffusion b-vectors file. outdir: str path to the destination folder. Returns ------- nodiff_file: str path to the mean b0 file. dwis: dict path the each shell 'dwi', 'bvals' and 'bvecs' files: b-values are the keys of this dictionary. """ # Load input data dwi = nibabel.load(dwi_nii_path) dwi_array = dwi.get_data() real_bvals, real_bvecs, nb_shells, nb_nodiff = read_bvals_bvecs( bvals_path, bvecs_path, min_bval=100.) # Detect shell indices bvals = real_bvals.copy() bvecs = real_bvecs.copy() b0_indices = numpy.where(bvals < 50)[0].tolist() bvals[b0_indices] = 0 bvals = [int(round(bval, -2)) for bval in bvals] bvals_set = set(bvals) - {0} # Create mean b0 image b0 = numpy.mean(dwi_array[..., b0_indices], axis=3) im = nibabel.Nifti1Image(b0, affine=dwi.get_affine()) nodiff_file = os.path.join(outdir, "nodiff.nii.gz") nibabel.save(im, nodiff_file) b0.shape += (1, ) # Create dwi for each shell dwis = {} bvals = numpy.asarray(bvals) for bval in bvals_set: # Get shell indices bval_outdir = os.path.join(outdir, str(bval)) if not os.path.isdir(bval_outdir): os.mkdir(bval_outdir) shell_indices = numpy.where(bvals == bval)[0].tolist() # Create single shell dwi shell_dwi = dwi_array[..., shell_indices] shell_dwi = numpy.concatenate((b0, shell_dwi), axis=3) im = nibabel.Nifti1Image(shell_dwi, affine=dwi.get_affine()) dwi_file = os.path.join(bval_outdir, "dwi.nii.gz") nibabel.save(im, dwi_file) # Create associated bvecs/bvals shell_bvecs = real_bvecs[shell_indices] shell_bvecs = numpy.concatenate((numpy.zeros((1, 3)), shell_bvecs), axis=0) bvecs_file = os.path.join(bval_outdir, "bvecs") numpy.savetxt(bvecs_file, shell_bvecs) shell_bvals = real_bvals[shell_indices] shell_bvals = numpy.concatenate((numpy.zeros((1, )), shell_bvals)) bvals_file = os.path.join(bval_outdir, "bvals") numpy.savetxt(bvals_file, shell_bvals) # Update output structure dwis[bval] = { "bvals": bvals_file, "bvecs": bvecs_file, "dwi": dwi_file } return nodiff_file, dwis def read_bvals_bvecs(bvals_path, bvecs_path, min_bval=200.): """ Read b-values and associated b-vectors. Parameters ---------- bvals_path: str or list of str path to the diffusion b-values file(s). bvecs_path: str or list of str path to the diffusion b-vectors file(s). min_bval: float, optional if a b-value under this threshold is detected raise an ValueError. Returns ------- bvals: array (N, ) array containing the diffusion b-values. bvecs: array (N, 3) array containing the diffusion b-vectors. nb_shells: int the number of shells. nb_nodiff: int the number of no diffusion weighted images. Raises ------ ValueError: if the b-values or the corresponding b-vectors have not matching sizes this exception is raised. """ # Format input path if not isinstance(bvals_path, list): bvals_path = [bvals_path] if not isinstance(bvecs_path, list): bvecs_path = [bvecs_path] # Read .bval & .bvecs files bvals = None bvecs = None for bvalfile, bvecfile in zip(bvals_path, bvecs_path): if bvals is None: bvals = np.loadtxt(bvalfile) else: bvals = np.concatenate((bvals, np.loadtxt(bvalfile))) if bvecs is None: bvecs = np.loadtxt(bvecfile) else: axis = bvecs.shape.index(max(bvecs.shape)) bvecs = np.concatenate((bvecs, np.loadtxt(bvecfile)), axis=axis) # Check consistency between bvals and associated bvecs if bvecs.ndim != 2: raise ValueError("b-vectors file should be saved as a two dimensional " "array: '{0}'.".format(bvecs_path)) if bvals.ndim != 1: raise ValueError("b-values file should be saved as a one dimensional " "array: '{0}'.".format(bvals_path)) if bvecs.shape[1] > bvecs.shape[0]: bvecs = bvecs.T if bvals.shape[0] != bvecs.shape[0]: raise ValueError("b-values and b-vectors shapes do not correspond.") # Infer nb of T2 and nb of shells. nb_nodiff = np.sum(bvals <= 50) # nb of volumes where bvalue<50 b0_set = set(bvals[bvals <= 50]) bvals_set = set(bvals) - b0_set # set of non-zero bvalues bvals_set = set([int(round(bval, -2)) for bval in list(bvals_set)]) nb_shells = len(bvals_set) if min(bvals_set) < min_bval: raise ValueError("Small b-values detected (<{0}) in '{1}'.".format( min_bval, bvals_path)) return bvals, bvecs, nb_shells, nb_nodiff
[ "numpy.mean", "nibabel.save", "nibabel.load", "numpy.where", "numpy.asarray", "os.path.join", "numpy.sum", "numpy.zeros", "os.path.isdir", "os.mkdir", "numpy.concatenate", "numpy.savetxt", "numpy.loadtxt" ]
[((1205, 1231), 'nibabel.load', 'nibabel.load', (['dwi_nii_path'], {}), '(dwi_nii_path)\n', (1217, 1231), False, 'import nibabel\n'), ((1669, 1715), 'numpy.mean', 'numpy.mean', (['dwi_array[..., b0_indices]'], {'axis': '(3)'}), '(dwi_array[..., b0_indices], axis=3)\n', (1679, 1715), False, 'import numpy\n'), ((1792, 1829), 'os.path.join', 'os.path.join', (['outdir', '"""nodiff.nii.gz"""'], {}), "(outdir, 'nodiff.nii.gz')\n", (1804, 1829), False, 'import os\n'), ((1834, 1863), 'nibabel.save', 'nibabel.save', (['im', 'nodiff_file'], {}), '(im, nodiff_file)\n', (1846, 1863), False, 'import nibabel\n'), ((1945, 1965), 'numpy.asarray', 'numpy.asarray', (['bvals'], {}), '(bvals)\n', (1958, 1965), False, 'import numpy\n'), ((5405, 5424), 'numpy.sum', 'np.sum', (['(bvals <= 50)'], {}), '(bvals <= 50)\n', (5411, 5424), True, 'import numpy as np\n'), ((2321, 2363), 'numpy.concatenate', 'numpy.concatenate', (['(b0, shell_dwi)'], {'axis': '(3)'}), '((b0, shell_dwi), axis=3)\n', (2338, 2363), False, 'import numpy\n'), ((2452, 2491), 'os.path.join', 'os.path.join', (['bval_outdir', '"""dwi.nii.gz"""'], {}), "(bval_outdir, 'dwi.nii.gz')\n", (2464, 2491), False, 'import os\n'), ((2500, 2526), 'nibabel.save', 'nibabel.save', (['im', 'dwi_file'], {}), '(im, dwi_file)\n', (2512, 2526), False, 'import nibabel\n'), ((2761, 2795), 'os.path.join', 'os.path.join', (['bval_outdir', '"""bvecs"""'], {}), "(bval_outdir, 'bvecs')\n", (2773, 2795), False, 'import os\n'), ((2804, 2842), 'numpy.savetxt', 'numpy.savetxt', (['bvecs_file', 'shell_bvecs'], {}), '(bvecs_file, shell_bvecs)\n', (2817, 2842), False, 'import numpy\n'), ((2987, 3021), 'os.path.join', 'os.path.join', (['bval_outdir', '"""bvals"""'], {}), "(bval_outdir, 'bvals')\n", (2999, 3021), False, 'import os\n'), ((3030, 3068), 'numpy.savetxt', 'numpy.savetxt', (['bvals_file', 'shell_bvals'], {}), '(bvals_file, shell_bvals)\n', (3043, 3068), False, 'import numpy\n'), ((2091, 2117), 'os.path.isdir', 'os.path.isdir', (['bval_outdir'], {}), '(bval_outdir)\n', (2104, 2117), False, 'import os\n'), ((2131, 2152), 'os.mkdir', 'os.mkdir', (['bval_outdir'], {}), '(bval_outdir)\n', (2139, 2152), False, 'import os\n'), ((4464, 4484), 'numpy.loadtxt', 'np.loadtxt', (['bvalfile'], {}), '(bvalfile)\n', (4474, 4484), True, 'import numpy as np\n'), ((4611, 4631), 'numpy.loadtxt', 'np.loadtxt', (['bvecfile'], {}), '(bvecfile)\n', (4621, 4631), True, 'import numpy as np\n'), ((1484, 1507), 'numpy.where', 'numpy.where', (['(bvals < 50)'], {}), '(bvals < 50)\n', (1495, 1507), False, 'import numpy\n'), ((2657, 2676), 'numpy.zeros', 'numpy.zeros', (['(1, 3)'], {}), '((1, 3))\n', (2668, 2676), False, 'import numpy\n'), ((2932, 2949), 'numpy.zeros', 'numpy.zeros', (['(1,)'], {}), '((1,))\n', (2943, 2949), False, 'import numpy\n'), ((2177, 2203), 'numpy.where', 'numpy.where', (['(bvals == bval)'], {}), '(bvals == bval)\n', (2188, 2203), False, 'import numpy\n'), ((4542, 4562), 'numpy.loadtxt', 'np.loadtxt', (['bvalfile'], {}), '(bvalfile)\n', (4552, 4562), True, 'import numpy as np\n'), ((4744, 4764), 'numpy.loadtxt', 'np.loadtxt', (['bvecfile'], {}), '(bvecfile)\n', (4754, 4764), True, 'import numpy as np\n')]
# -*- encoding: utf-8 -*- # # Copyright © 2017-2018 Red Hat, Inc. # Copyright © 2014-2015 eNovance # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import collections import functools import operator import daiquiri import numpy import six from gnocchi.carbonara import TIMESERIES_ARRAY_DTYPE from gnocchi import exceptions from gnocchi import utils LOG = daiquiri.getLogger(__name__) Measure = collections.namedtuple("Measure", ['timestamp', 'value']) class ReportGenerationError(Exception): pass class SackDetectionError(Exception): pass @functools.total_ordering class Sack(object): """A sack is a recipient that contains measures for a group of metrics. It is identified by a positive integer called `number`. """ # Use slots to make them as small as possible since we can create a ton of # those. __slots__ = [ "number", "total", "name", ] def __init__(self, number, total, name): """Create a new sack. :param number: The sack number, identifying it. :param total: The total number of sacks. :param name: The sack name. """ self.number = number self.total = total self.name = name def __str__(self): return self.name def __repr__(self): return "<%s(%d/%d) %s>" % ( self.__class__.__name__, self.number, self.total, str(self), ) def _compare(self, op, other): if isinstance(other, Sack): if self.total != other.total: raise TypeError( "Cannot compare %s with different total number" % self.__class__.__name__) return op(self.number, other.number) raise TypeError("Cannot compare %r with %r" % (self, other)) def __lt__(self, other): return self._compare(operator.lt, other) def __eq__(self, other): return self._compare(operator.eq, other) def __ne__(self, other): # neither total_ordering nor py2 sets ne as the opposite of eq return self._compare(operator.ne, other) def __hash__(self): return hash(self.name) class IncomingDriver(object): MEASURE_PREFIX = "measure" SACK_NAME_FORMAT = "incoming{total}-{number}" CFG_PREFIX = 'gnocchi-config' CFG_SACKS = 'sacks' @property def NUM_SACKS(self): if not hasattr(self, '_num_sacks'): try: self._num_sacks = int(self._get_storage_sacks()) except Exception as e: raise SackDetectionError(e) return self._num_sacks def __init__(self, conf, greedy=True): self._sacks = None def upgrade(self, num_sacks): try: self.NUM_SACKS except SackDetectionError: self.set_storage_settings(num_sacks) @staticmethod def set_storage_settings(num_sacks): raise exceptions.NotImplementedError @staticmethod def remove_sack_group(num_sacks): raise exceptions.NotImplementedError @staticmethod def get_storage_sacks(): """Return the number of sacks in storage. None if not set.""" raise exceptions.NotImplementedError def _make_measures_array(self): return numpy.array([], dtype=TIMESERIES_ARRAY_DTYPE) @staticmethod def _array_concatenate(arrays): if arrays: return numpy.concatenate(arrays) return arrays def _unserialize_measures(self, measure_id, data): try: return numpy.frombuffer(data, dtype=TIMESERIES_ARRAY_DTYPE) except ValueError: LOG.error( "Unable to decode measure %s, possible data corruption", measure_id) raise def _encode_measures(self, measures): return numpy.array(list(measures), dtype=TIMESERIES_ARRAY_DTYPE).tobytes() def add_measures(self, metric_id, measures): """Add a measure to a metric. :param metric_id: The metric measured. :param measures: The actual measures. """ self.add_measures_batch({metric_id: measures}) def add_measures_batch(self, metrics_and_measures): """Add a batch of measures for some metrics. :param metrics_and_measures: A dict where keys are metric objects and values are a list of :py:class:`gnocchi.incoming.Measure`. """ utils.parallel_map( self._store_new_measures, ((metric_id, self._encode_measures(measures)) for metric_id, measures in six.iteritems(metrics_and_measures))) @staticmethod def _store_new_measures(metric_id, data): raise exceptions.NotImplementedError def measures_report(self, details=True): """Return a report of pending to process measures. Only useful for drivers that process measurements in background :return: {'summary': {'metrics': count, 'measures': count}, 'details': {metric_id: pending_measures_count}} """ metrics, measures, full_details = self._build_report(details) report = {'summary': {'metrics': metrics, 'measures': measures}} if full_details is not None: report['details'] = full_details return report @staticmethod def _build_report(details): raise exceptions.NotImplementedError @staticmethod def list_metric_with_measures_to_process(sack): raise exceptions.NotImplementedError @staticmethod def delete_unprocessed_measures_for_metric(metric_id): raise exceptions.NotImplementedError @staticmethod def process_measure_for_metrics(metric_id): raise exceptions.NotImplementedError @staticmethod def has_unprocessed(metric_id): raise exceptions.NotImplementedError def _get_sack_name(self, number): return self.SACK_NAME_FORMAT.format( total=self.NUM_SACKS, number=number) def _make_sack(self, i): return Sack(i, self.NUM_SACKS, self._get_sack_name(i)) def sack_for_metric(self, metric_id): return self._make_sack(metric_id.int % self.NUM_SACKS) def iter_sacks(self): return (self._make_sack(i) for i in six.moves.range(self.NUM_SACKS)) @staticmethod def iter_on_sacks_to_process(): """Return an iterable of sack that got new measures to process.""" raise exceptions.NotImplementedError @staticmethod def finish_sack_processing(sack): """Mark sack processing has finished.""" pass @utils.retry_on_exception_and_log("Unable to initialize incoming driver") def get_driver(conf): """Return configured incoming driver only :param conf: incoming configuration only (not global) """ return utils.get_driver_class('gnocchi.incoming', conf.incoming)( conf.incoming, conf.metricd.greedy)
[ "gnocchi.utils.get_driver_class", "collections.namedtuple", "six.moves.range", "numpy.array", "daiquiri.getLogger", "numpy.concatenate", "numpy.frombuffer", "six.iteritems", "gnocchi.utils.retry_on_exception_and_log" ]
[((857, 885), 'daiquiri.getLogger', 'daiquiri.getLogger', (['__name__'], {}), '(__name__)\n', (875, 885), False, 'import daiquiri\n'), ((898, 955), 'collections.namedtuple', 'collections.namedtuple', (['"""Measure"""', "['timestamp', 'value']"], {}), "('Measure', ['timestamp', 'value'])\n", (920, 955), False, 'import collections\n'), ((7173, 7245), 'gnocchi.utils.retry_on_exception_and_log', 'utils.retry_on_exception_and_log', (['"""Unable to initialize incoming driver"""'], {}), "('Unable to initialize incoming driver')\n", (7205, 7245), False, 'from gnocchi import utils\n'), ((3763, 3808), 'numpy.array', 'numpy.array', (['[]'], {'dtype': 'TIMESERIES_ARRAY_DTYPE'}), '([], dtype=TIMESERIES_ARRAY_DTYPE)\n', (3774, 3808), False, 'import numpy\n'), ((7392, 7449), 'gnocchi.utils.get_driver_class', 'utils.get_driver_class', (['"""gnocchi.incoming"""', 'conf.incoming'], {}), "('gnocchi.incoming', conf.incoming)\n", (7414, 7449), False, 'from gnocchi import utils\n'), ((3902, 3927), 'numpy.concatenate', 'numpy.concatenate', (['arrays'], {}), '(arrays)\n', (3919, 3927), False, 'import numpy\n'), ((4038, 4090), 'numpy.frombuffer', 'numpy.frombuffer', (['data'], {'dtype': 'TIMESERIES_ARRAY_DTYPE'}), '(data, dtype=TIMESERIES_ARRAY_DTYPE)\n', (4054, 4090), False, 'import numpy\n'), ((6843, 6874), 'six.moves.range', 'six.moves.range', (['self.NUM_SACKS'], {}), '(self.NUM_SACKS)\n', (6858, 6874), False, 'import six\n'), ((5173, 5208), 'six.iteritems', 'six.iteritems', (['metrics_and_measures'], {}), '(metrics_and_measures)\n', (5186, 5208), False, 'import six\n')]
#!/usr/bin/env python3 -u # coding: utf-8 # copyright: sktime developers, BSD-3-Clause License (see LICENSE file) __all__ = ["NaiveForecaster"] __author__ = "<NAME>" from warnings import warn import numpy as np from sktime.forecasting.base._base import DEFAULT_ALPHA from sktime.forecasting.base._sktime import BaseLastWindowForecaster from sktime.forecasting.base._sktime import OptionalForecastingHorizonMixin from sktime.utils.validation.forecasting import check_sp from sktime.utils.validation.forecasting import check_window_length class NaiveForecaster(OptionalForecastingHorizonMixin, BaseLastWindowForecaster): """ NaiveForecaster is a forecaster that makes forecasts using simple strategies. Parameters ---------- strategy : str{"last", "mean", "seasonal_last"}, optional (default="last") Strategy used to make forecasts: * "last": forecast the last value in the training series * "mean": forecast the mean of (a given window) of the training series * "seasonal_last": forecasts the last value of the same season in the training series window_length : int or None, optional (default=None) Window length to use in the `mean` strategy. If None, entire training series will be used. """ def __init__(self, strategy="last", window_length=None, sp=None): super(NaiveForecaster, self).__init__() # input checks # allowed strategies to include: last, constant, seasonal-last, # mean, median allowed_strategies = ("last", "mean", "seasonal_last") if strategy not in allowed_strategies: raise ValueError( f"Unknown strategy: {strategy}; expected one of " f"{allowed_strategies}") self.strategy = strategy self.sp = sp self.window_length = window_length self.sp_ = None def fit(self, y_train, fh=None, X_train=None): """Fit to training data. Parameters ---------- y_train : pd.Series Target time series to which to fit the forecaster. fh : int, list or np.array, optional (default=None) The forecasters horizon with the steps ahead to to predict. X_train : pd.DataFrame, optional (default=None) Exogenous variables are ignored Returns ------- self : returns an instance of self. """ # X_train is ignored self._set_oh(y_train) self._set_fh(fh) if self.strategy in ("last", "seasonal_last"): if self.window_length is not None: warn("For the `last` and `seasonal_last` strategy, " "the `window_length_` value will be ignored.") if self.strategy in ("last", "mean"): if self.sp is not None: warn("For the `last` and `mean` strategy, " "the `sp` value will be ignored.") if self.strategy == "last": self.window_length_ = 1 if self.strategy == "seasonal_last": if self.sp is None: raise NotImplementedError( "Automatic estimation of the seasonal periodicity `sp` " "from the data is not implemented yet; " "please specify the `sp` value.") self.sp_ = check_sp(self.sp) # window length we need for forecasts is just the # length of seasonal periodicity self.window_length_ = self.sp_ if self.strategy == "mean": self.window_length_ = check_window_length(self.window_length) # if not given, set default window length for the mean strategy if self.strategy == "mean" and self.window_length is None: self.window_length_ = len(y_train) # check window length if self.window_length_ > len(self.oh): param = "sp" if self.strategy == "seasonal_last" else \ "window_length_" raise ValueError( f"The {param}: {self.window_length_} is larger than " f"the training series.") self._is_fitted = True return self def _predict_last_window(self, fh, X=None, return_pred_int=False, alpha=DEFAULT_ALPHA): """Internal predict""" last_window = self._get_last_window() # if last window only contains missing values, return nan if np.all(np.isnan(last_window)) or len(last_window) == 0: return self._predict_nan(fh) elif self.strategy == "last": return np.repeat(last_window[-1], len(fh)) elif self.strategy == "seasonal_last": # we need to replicate the last window if max(fh) is larger than # sp, # so that we still make forecasts by repeating the last value # for that season, # assume fh is sorted, i.e. max(fh) == fh[-1] if fh[-1] > self.sp_: reps = np.int(np.ceil(fh[-1] / self.sp_)) last_window = np.tile(last_window, reps=reps) # get zero-based index by subtracting the minimum fh_idx = fh.index_like(self.cutoff) return last_window[fh_idx] elif self.strategy == "mean": return np.repeat(np.nanmean(last_window), len(fh))
[ "numpy.tile", "numpy.ceil", "sktime.utils.validation.forecasting.check_sp", "numpy.nanmean", "sktime.utils.validation.forecasting.check_window_length", "numpy.isnan", "warnings.warn" ]
[((3381, 3398), 'sktime.utils.validation.forecasting.check_sp', 'check_sp', (['self.sp'], {}), '(self.sp)\n', (3389, 3398), False, 'from sktime.utils.validation.forecasting import check_sp\n'), ((3621, 3660), 'sktime.utils.validation.forecasting.check_window_length', 'check_window_length', (['self.window_length'], {}), '(self.window_length)\n', (3640, 3660), False, 'from sktime.utils.validation.forecasting import check_window_length\n'), ((2652, 2758), 'warnings.warn', 'warn', (['"""For the `last` and `seasonal_last` strategy, the `window_length_` value will be ignored."""'], {}), "(\n 'For the `last` and `seasonal_last` strategy, the `window_length_` value will be ignored.'\n )\n", (2656, 2758), False, 'from warnings import warn\n'), ((2872, 2947), 'warnings.warn', 'warn', (['"""For the `last` and `mean` strategy, the `sp` value will be ignored."""'], {}), "('For the `last` and `mean` strategy, the `sp` value will be ignored.')\n", (2876, 2947), False, 'from warnings import warn\n'), ((4505, 4526), 'numpy.isnan', 'np.isnan', (['last_window'], {}), '(last_window)\n', (4513, 4526), True, 'import numpy as np\n'), ((5117, 5148), 'numpy.tile', 'np.tile', (['last_window'], {'reps': 'reps'}), '(last_window, reps=reps)\n', (5124, 5148), True, 'import numpy as np\n'), ((5059, 5085), 'numpy.ceil', 'np.ceil', (['(fh[-1] / self.sp_)'], {}), '(fh[-1] / self.sp_)\n', (5066, 5085), True, 'import numpy as np\n'), ((5367, 5390), 'numpy.nanmean', 'np.nanmean', (['last_window'], {}), '(last_window)\n', (5377, 5390), True, 'import numpy as np\n')]
import os import logging from xml.dom.pulldom import parseString import IPython.display as ipyd import matplotlib.animation as animation import matplotlib.pyplot as plt import numpy as np import plotly.express as px import plotly.graph_objects as go from sklearn.feature_extraction import img_to_graph import torchvision.utils as vutils from PIL import Image logger = logging.getLogger(__name__) def plot_against( first, second, third=None, title="", xlabel="", ylabel="", labels=("", "", ""), save_path=None ): if third is not None: x = list(range(max(len(first), len(second), len(third)))) else: x = list(range(max(len(first), len(second)))) plt.plot(x, first, label=labels[0]) plt.plot(x, second, label=labels[1]) if third is not None: plt.plot(x, third, label=labels[2]) plt.grid() plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.xlim([min(x), max(x)]) plt.legend() if save_path is None: plt.show() else: with save_path.open("wb") as file: plt.savefig(file, bbox_inches="tight") plt.close() logger.info( "Saved plot with title: %s on path: %s", title, save_path ) def as_grayscale_image(array, save_path=None): # convert tensor pixel values from [0 , 1] to [0, 255] array = (((array - array.min()) / (array.max() - array.min())) * 255.9) # convert the pixels from float type to int type array = np.array(array, dtype=np.uint8) # convert to image from array img = Image.fromarray(array) # save image if save_path is None: img.show() else: with save_path.open("wb") as file: img.save(file) def as_3d_surface(array, save_path=False): fig = go.Figure(data=[go.Surface(z=array)]) if save_path is None: fig.show() else: with save_path.open("wb") as file: fig.write_image(file) def animate_epochs(batches_of_tensors, indices=None, save_path=None, **kwargs): fig = plt.figure(figsize=(8, 8)) axes = fig.add_subplot(111) plt.axis("off") artists = [] for index, batch_of_tensors in enumerate(batches_of_tensors, start=1): if indices: batch_of_tensors = [batch_of_tensors[index] for index in indices] grid = vutils.make_grid(batch_of_tensors, padding=2, normalize=True) artists.append( [ plt.imshow( np.transpose(grid, (1, 2, 0)), animated=True, ), plt.text( 0.5, 1.01, "Epoch %02d" % (index,), horizontalalignment="center", verticalalignment="bottom", transform=axes.transAxes, fontsize=16, ), ] ) if os.name != "nt": plt.close() try: ani = animation.ArtistAnimation( fig, artists, interval=kwargs.get("interval", 1000), repeat_delay=kwargs.get("repeat_delay", 1000), blit=kwargs.get("blit", True), ) ipyd.display(ipyd.HTML(ani.to_jshtml())) if save_path is not None: # Set up formatting for the movie files Writer = animation.writers["ffmpeg"] writer = Writer(fps=kwargs.get("fps", 15), bitrate=kwargs.get("bitrate", 1800)) ani.save(str(save_path), writer=writer) except Exception as execErr: logger.info( "OS error: %s", execErr )
[ "logging.getLogger", "plotly.graph_objects.Surface", "PIL.Image.fromarray", "matplotlib.pyplot.grid", "matplotlib.pyplot.savefig", "matplotlib.pyplot.text", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.axis", "matplotlib.pyplot.close", "n...
[((370, 397), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (387, 397), False, 'import logging\n'), ((681, 716), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'first'], {'label': 'labels[0]'}), '(x, first, label=labels[0])\n', (689, 716), True, 'import matplotlib.pyplot as plt\n'), ((721, 757), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'second'], {'label': 'labels[1]'}), '(x, second, label=labels[1])\n', (729, 757), True, 'import matplotlib.pyplot as plt\n'), ((834, 844), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (842, 844), True, 'import matplotlib.pyplot as plt\n'), ((849, 865), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (858, 865), True, 'import matplotlib.pyplot as plt\n'), ((870, 888), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (880, 888), True, 'import matplotlib.pyplot as plt\n'), ((893, 911), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (903, 911), True, 'import matplotlib.pyplot as plt\n'), ((949, 961), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (959, 961), True, 'import matplotlib.pyplot as plt\n'), ((1508, 1539), 'numpy.array', 'np.array', (['array'], {'dtype': 'np.uint8'}), '(array, dtype=np.uint8)\n', (1516, 1539), True, 'import numpy as np\n'), ((1584, 1606), 'PIL.Image.fromarray', 'Image.fromarray', (['array'], {}), '(array)\n', (1599, 1606), False, 'from PIL import Image\n'), ((2067, 2093), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (2077, 2093), True, 'import matplotlib.pyplot as plt\n'), ((2131, 2146), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2139, 2146), True, 'import matplotlib.pyplot as plt\n'), ((793, 828), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'third'], {'label': 'labels[2]'}), '(x, third, label=labels[2])\n', (801, 828), True, 'import matplotlib.pyplot as plt\n'), ((997, 1007), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1005, 1007), True, 'import matplotlib.pyplot as plt\n'), ((1121, 1132), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1130, 1132), True, 'import matplotlib.pyplot as plt\n'), ((2354, 2415), 'torchvision.utils.make_grid', 'vutils.make_grid', (['batch_of_tensors'], {'padding': '(2)', 'normalize': '(True)'}), '(batch_of_tensors, padding=2, normalize=True)\n', (2370, 2415), True, 'import torchvision.utils as vutils\n'), ((2963, 2974), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2972, 2974), True, 'import matplotlib.pyplot as plt\n'), ((1073, 1111), 'matplotlib.pyplot.savefig', 'plt.savefig', (['file'], {'bbox_inches': '"""tight"""'}), "(file, bbox_inches='tight')\n", (1084, 1111), True, 'import matplotlib.pyplot as plt\n'), ((1820, 1839), 'plotly.graph_objects.Surface', 'go.Surface', ([], {'z': 'array'}), '(z=array)\n', (1830, 1839), True, 'import plotly.graph_objects as go\n'), ((2604, 2749), 'matplotlib.pyplot.text', 'plt.text', (['(0.5)', '(1.01)', "('Epoch %02d' % (index,))"], {'horizontalalignment': '"""center"""', 'verticalalignment': '"""bottom"""', 'transform': 'axes.transAxes', 'fontsize': '(16)'}), "(0.5, 1.01, 'Epoch %02d' % (index,), horizontalalignment='center',\n verticalalignment='bottom', transform=axes.transAxes, fontsize=16)\n", (2612, 2749), True, 'import matplotlib.pyplot as plt\n'), ((2503, 2532), 'numpy.transpose', 'np.transpose', (['grid', '(1, 2, 0)'], {}), '(grid, (1, 2, 0))\n', (2515, 2532), True, 'import numpy as np\n')]
import numpy as np from warnings import warn from typing import List, Callable from desdeo_emo.selection.SelectionBase import SelectionBase from desdeo_emo.population.Population import Population from desdeo_emo.othertools.ReferenceVectors import ReferenceVectors from typing import TYPE_CHECKING from desdeo_emo.othertools.ProbabilityWrong import Probability_wrong import os os.environ["OMP_NUM_THREADS"] = "1" if TYPE_CHECKING: from pyRVEA.allclasses import ReferenceVectors class Prob_Hybrid_APD_Select_v3_1(SelectionBase): """The selection operator for the RVEA algorithm. Read the following paper for more details. <NAME>, <NAME>, <NAME> and <NAME>, A Reference Vector Guided Evolutionary Algorithm for Many-objective Optimization, IEEE Transactions on Evolutionary Computation, 2016 Parameters ---------- pop : Population The population instance time_penalty_function : Callable A function that returns the time component in the penalty function. alpha : float, optional The RVEA alpha parameter, by default 2 """ def __init__( self, pop: Population, time_penalty_function: Callable, alpha: float = 2 ): self.time_penalty_function = time_penalty_function self.alpha = alpha self.n_of_objectives = pop.problem.n_of_objectives def do(self, pop: Population, vectors: ReferenceVectors) -> List[int]: """Select individuals for mating on basis of APD and probabilistic APD. Args: fitness (list): Fitness of the current population. uncertainty (list) : Uncertainty of the predicted objective values vectors (ReferenceVectors): Class containing reference vectors. penalty_factor (float): Multiplier of angular deviation from Reference vectors. See RVEA paper for details. ideal (list): ideal point for the population. Uses the min fitness value if None. Returns: [type]: A list of indices of the selected individuals. """ fitness = pop.fitness uncertainty = pop.uncertainity penalty_factor = self._partial_penalty_factor() refV = vectors.neighbouring_angles_current # Normalization - There may be problems here fmin = np.amin(fitness, axis=0) translated_fitness = fitness - fmin fitness_norm = np.linalg.norm(translated_fitness, axis=1) fitness_norm = np.repeat(fitness_norm, len(translated_fitness[0, :])).reshape( len(fitness), len(fitness[0, :]) ) normalized_fitness = np.divide(translated_fitness, fitness_norm) # Checked, works. cosine = np.dot(normalized_fitness, np.transpose(vectors.values)) if cosine[np.where(cosine > 1)].size: #print( # "RVEA.py line 60 cosine larger than 1 decreased to 1:" #) cosine[np.where(cosine > 1)] = 1 if cosine[np.where(cosine < 0)].size: #print( # "RVEA.py line 64 cosine smaller than 0 decreased to 0:" #) cosine[np.where(cosine < 0)] = 0 # Calculation of angles between reference vectors and solutions theta = np.arccos(cosine) # Reference vector asub_population_indexssignment assigned_vectors = np.argmax(cosine, axis=1) selection = np.array([], dtype=int) ######################################################### refV = vectors.neighbouring_angles_current fmin = np.amin(fitness, axis=0) # fmin = np.array([0,0]) translated_fitness = fitness - fmin pwrong = Probability_wrong(mean_values=translated_fitness, stddev_values=uncertainty, n_samples=1000) pwrong.vect_sample_f() fitness_norm = np.linalg.norm(pwrong.f_samples, axis=1) fitness_norm = np.repeat(np.reshape(fitness_norm, (len(fitness), 1, pwrong.n_samples)), len(fitness[0, :]), axis=1) normalized_fitness = np.divide(pwrong.f_samples, fitness_norm) # Checked, works. cosine = np.tensordot(normalized_fitness, np.transpose(vectors.values), axes=([1], [0])) cosine = np.transpose(cosine, (0, 2, 1)) if cosine[np.where(cosine > 1)].size: #print( # "RVEA.py line 60 cosine larger than 1 decreased to 1:" #) cosine[np.where(cosine > 1)] = 1 if cosine[np.where(cosine < 0)].size: #print( # "RVEA.py line 64 cosine smaller than 0 decreased to 0:" #) cosine[np.where(cosine < 0)] = 0 # Calculation of angles between reference vectors and solutions theta2 = np.arccos(cosine) # Reference vector asub_population_indexssignment # pwrong.compute_pdf(cosine) # Compute rank of cos theta (to be vectorized) rank_cosine = np.mean(cosine, axis=2) # print("Rank cosine:") # print(rank_cosine) assigned_vectors2 = np.argmax(rank_cosine, axis=1) selection = np.array([], dtype=int) # Selection vector_selection = None # fig = plt.figure(1, figsize=(6, 6)) # ax = fig.add_subplot(111) for i in range(0, len(vectors.values)): sub_population_index = np.atleast_1d( np.squeeze(np.where(assigned_vectors == i)) ) sub_population_fitness = pwrong.f_samples[sub_population_index] #sub_population_fitness = translated_fitness[sub_population_index] if len(sub_population_fitness > 0): angles = theta2[sub_population_index, i] angles = np.divide(angles, refV[i]) # This is correct. # You have done this calculation before. Check with fitness_norm # Remove this horrible line sub_pop_fitness_magnitude = np.sqrt( np.sum(np.power(sub_population_fitness, 2), axis=1) ) sub_popfm = np.reshape(sub_pop_fitness_magnitude, (1, len(sub_pop_fitness_magnitude[:, 0]), pwrong.n_samples)) angles = np.reshape(angles, (1, len(angles), pwrong.n_samples)) #apd = np.multiply( # np.mean(sub_popfm,axis=2), # (1 + np.dot(penalty_factor, np.mean(angles, axis=2))), #) #rank_apd = apd apd = np.multiply( sub_popfm, (1 + np.dot(penalty_factor, angles))) rank_apd = np.mean(apd, axis=2) minidx = np.where(rank_apd[0] == np.nanmin(rank_apd[0])) ######## sub_population_fitness = translated_fitness[sub_population_index] # APD Calculation angles = theta[sub_population_index, i] angles = np.divide(angles, refV[i]) # This is correct. # You have done this calculation before. Check with fitness_norm # Remove this horrible line sub_pop_fitness_magnitude = np.sqrt( np.sum(np.power(sub_population_fitness, 2), axis=1) ) apd = np.multiply( np.transpose(sub_pop_fitness_magnitude), (1 + np.dot(penalty_factor, angles)), ) minidx2 = np.where(apd == np.nanmin(apd)) ######## if np.isnan(apd).all(): continue if minidx[0][0] == minidx2[0][0]: selx = sub_population_index[[minidx[0][0]]] else: selx = sub_population_index[[minidx[0][0],minidx2[0][0]]] if selection.shape[0] == 0: selection = np.reshape(np.hstack((selection, np.transpose(selx))),(np.shape(selx)[0],1)) vector_selection = np.asarray(i) else: selection = np.vstack((selection, np.reshape(selx, (np.shape(selx)[0], 1)))) vector_selection = np.hstack((vector_selection, i)) while selection.shape[0] == 1: rand_select = np.random.randint(len(fitness), size=1) #selection = np.vstack((selection, np.transpose(rand_select[0]))) selection = np.union1d(selection,np.transpose(rand_select[0])) print(selection.squeeze()) return selection.squeeze() def _partial_penalty_factor(self) -> float: """Calculate and return the partial penalty factor for APD calculation. This calculation does not include the angle related terms, hence the name. If the calculated penalty is outside [0, 1], it will round it up/down to 0/1 Returns ------- float The partial penalty value """ penalty = ((self.time_penalty_function()) ** self.alpha) * self.n_of_objectives if penalty < 0: penalty = 0 if penalty > 1: penalty = 1 return penalty
[ "numpy.mean", "numpy.arccos", "numpy.amin", "numpy.hstack", "numpy.where", "numpy.power", "numpy.asarray", "numpy.argmax", "desdeo_emo.othertools.ProbabilityWrong.Probability_wrong", "numpy.array", "numpy.dot", "numpy.isnan", "numpy.linalg.norm", "numpy.nanmin", "numpy.shape", "numpy.t...
[((2344, 2368), 'numpy.amin', 'np.amin', (['fitness'], {'axis': '(0)'}), '(fitness, axis=0)\n', (2351, 2368), True, 'import numpy as np\n'), ((2436, 2478), 'numpy.linalg.norm', 'np.linalg.norm', (['translated_fitness'], {'axis': '(1)'}), '(translated_fitness, axis=1)\n', (2450, 2478), True, 'import numpy as np\n'), ((2650, 2693), 'numpy.divide', 'np.divide', (['translated_fitness', 'fitness_norm'], {}), '(translated_fitness, fitness_norm)\n', (2659, 2693), True, 'import numpy as np\n'), ((3272, 3289), 'numpy.arccos', 'np.arccos', (['cosine'], {}), '(cosine)\n', (3281, 3289), True, 'import numpy as np\n'), ((3375, 3400), 'numpy.argmax', 'np.argmax', (['cosine'], {'axis': '(1)'}), '(cosine, axis=1)\n', (3384, 3400), True, 'import numpy as np\n'), ((3421, 3444), 'numpy.array', 'np.array', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (3429, 3444), True, 'import numpy as np\n'), ((3580, 3604), 'numpy.amin', 'np.amin', (['fitness'], {'axis': '(0)'}), '(fitness, axis=0)\n', (3587, 3604), True, 'import numpy as np\n'), ((3699, 3795), 'desdeo_emo.othertools.ProbabilityWrong.Probability_wrong', 'Probability_wrong', ([], {'mean_values': 'translated_fitness', 'stddev_values': 'uncertainty', 'n_samples': '(1000)'}), '(mean_values=translated_fitness, stddev_values=uncertainty,\n n_samples=1000)\n', (3716, 3795), False, 'from desdeo_emo.othertools.ProbabilityWrong import Probability_wrong\n'), ((3847, 3887), 'numpy.linalg.norm', 'np.linalg.norm', (['pwrong.f_samples'], {'axis': '(1)'}), '(pwrong.f_samples, axis=1)\n', (3861, 3887), True, 'import numpy as np\n'), ((4042, 4083), 'numpy.divide', 'np.divide', (['pwrong.f_samples', 'fitness_norm'], {}), '(pwrong.f_samples, fitness_norm)\n', (4051, 4083), True, 'import numpy as np\n'), ((4219, 4250), 'numpy.transpose', 'np.transpose', (['cosine', '(0, 2, 1)'], {}), '(cosine, (0, 2, 1))\n', (4231, 4250), True, 'import numpy as np\n'), ((4738, 4755), 'numpy.arccos', 'np.arccos', (['cosine'], {}), '(cosine)\n', (4747, 4755), True, 'import numpy as np\n'), ((4928, 4951), 'numpy.mean', 'np.mean', (['cosine'], {'axis': '(2)'}), '(cosine, axis=2)\n', (4935, 4951), True, 'import numpy as np\n'), ((5041, 5071), 'numpy.argmax', 'np.argmax', (['rank_cosine'], {'axis': '(1)'}), '(rank_cosine, axis=1)\n', (5050, 5071), True, 'import numpy as np\n'), ((5092, 5115), 'numpy.array', 'np.array', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (5100, 5115), True, 'import numpy as np\n'), ((2757, 2785), 'numpy.transpose', 'np.transpose', (['vectors.values'], {}), '(vectors.values)\n', (2769, 2785), True, 'import numpy as np\n'), ((4155, 4183), 'numpy.transpose', 'np.transpose', (['vectors.values'], {}), '(vectors.values)\n', (4167, 4183), True, 'import numpy as np\n'), ((2805, 2825), 'numpy.where', 'np.where', (['(cosine > 1)'], {}), '(cosine > 1)\n', (2813, 2825), True, 'import numpy as np\n'), ((2959, 2979), 'numpy.where', 'np.where', (['(cosine > 1)'], {}), '(cosine > 1)\n', (2967, 2979), True, 'import numpy as np\n'), ((3003, 3023), 'numpy.where', 'np.where', (['(cosine < 0)'], {}), '(cosine < 0)\n', (3011, 3023), True, 'import numpy as np\n'), ((3158, 3178), 'numpy.where', 'np.where', (['(cosine < 0)'], {}), '(cosine < 0)\n', (3166, 3178), True, 'import numpy as np\n'), ((4270, 4290), 'numpy.where', 'np.where', (['(cosine > 1)'], {}), '(cosine > 1)\n', (4278, 4290), True, 'import numpy as np\n'), ((4424, 4444), 'numpy.where', 'np.where', (['(cosine > 1)'], {}), '(cosine > 1)\n', (4432, 4444), True, 'import numpy as np\n'), ((4468, 4488), 'numpy.where', 'np.where', (['(cosine < 0)'], {}), '(cosine < 0)\n', (4476, 4488), True, 'import numpy as np\n'), ((4623, 4643), 'numpy.where', 'np.where', (['(cosine < 0)'], {}), '(cosine < 0)\n', (4631, 4643), True, 'import numpy as np\n'), ((5712, 5738), 'numpy.divide', 'np.divide', (['angles', 'refV[i]'], {}), '(angles, refV[i])\n', (5721, 5738), True, 'import numpy as np\n'), ((6634, 6654), 'numpy.mean', 'np.mean', (['apd'], {'axis': '(2)'}), '(apd, axis=2)\n', (6641, 6654), True, 'import numpy as np\n'), ((6952, 6978), 'numpy.divide', 'np.divide', (['angles', 'refV[i]'], {}), '(angles, refV[i])\n', (6961, 6978), True, 'import numpy as np\n'), ((8433, 8461), 'numpy.transpose', 'np.transpose', (['rand_select[0]'], {}), '(rand_select[0])\n', (8445, 8461), True, 'import numpy as np\n'), ((5378, 5409), 'numpy.where', 'np.where', (['(assigned_vectors == i)'], {}), '(assigned_vectors == i)\n', (5386, 5409), True, 'import numpy as np\n'), ((7322, 7361), 'numpy.transpose', 'np.transpose', (['sub_pop_fitness_magnitude'], {}), '(sub_pop_fitness_magnitude)\n', (7334, 7361), True, 'import numpy as np\n'), ((7999, 8012), 'numpy.asarray', 'np.asarray', (['i'], {}), '(i)\n', (8009, 8012), True, 'import numpy as np\n'), ((8171, 8203), 'numpy.hstack', 'np.hstack', (['(vector_selection, i)'], {}), '((vector_selection, i))\n', (8180, 8203), True, 'import numpy as np\n'), ((5964, 5999), 'numpy.power', 'np.power', (['sub_population_fitness', '(2)'], {}), '(sub_population_fitness, 2)\n', (5972, 5999), True, 'import numpy as np\n'), ((6574, 6604), 'numpy.dot', 'np.dot', (['penalty_factor', 'angles'], {}), '(penalty_factor, angles)\n', (6580, 6604), True, 'import numpy as np\n'), ((6705, 6727), 'numpy.nanmin', 'np.nanmin', (['rank_apd[0]'], {}), '(rank_apd[0])\n', (6714, 6727), True, 'import numpy as np\n'), ((7204, 7239), 'numpy.power', 'np.power', (['sub_population_fitness', '(2)'], {}), '(sub_population_fitness, 2)\n', (7212, 7239), True, 'import numpy as np\n'), ((7388, 7418), 'numpy.dot', 'np.dot', (['penalty_factor', 'angles'], {}), '(penalty_factor, angles)\n', (7394, 7418), True, 'import numpy as np\n'), ((7481, 7495), 'numpy.nanmin', 'np.nanmin', (['apd'], {}), '(apd)\n', (7490, 7495), True, 'import numpy as np\n'), ((7542, 7555), 'numpy.isnan', 'np.isnan', (['apd'], {}), '(apd)\n', (7550, 7555), True, 'import numpy as np\n'), ((7916, 7934), 'numpy.transpose', 'np.transpose', (['selx'], {}), '(selx)\n', (7928, 7934), True, 'import numpy as np\n'), ((7938, 7952), 'numpy.shape', 'np.shape', (['selx'], {}), '(selx)\n', (7946, 7952), True, 'import numpy as np\n'), ((8107, 8121), 'numpy.shape', 'np.shape', (['selx'], {}), '(selx)\n', (8115, 8121), True, 'import numpy as np\n')]
from ..utils import to_value, len_batch from .callback_tensorboard import CallbackTensorboardBased from ..train import utilities from ..train import outputs_trw as O import functools import collections import torch import numpy as np import logging logger = logging.getLogger(__name__) def get_as_image(images): """ Return the images as (N, C, H, W) or None if not an image TODO: smarter image detection! :param images: the object to check :return: None if not an image, or images with format (N, C, H, W) """ if isinstance(images, (np.ndarray, torch.Tensor)): if len(images.shape) == 4 and (images.shape[1] == 1 or images.shape[1] == 3): return images return None def keep_small_features(feature_name, feature_value): """ Keep only the small features (e.g., len(shape) == 1) for the embedding infos :return: if True, keep the feature else discard it """ if isinstance(feature_value, torch.Tensor) and len(feature_value.shape) > 1: return False return True def is_batch_vector(value, batch_size): """ Return true if a vector like :param value: the value to test :param batch_size: the expected size of the batch """ vector_size = 0 is_vector = False if isinstance(value, (torch.Tensor, np.ndarray)): is_vector = True if len(value.shape) != 0: vector_size = value.shape[0] elif isinstance(value, list): is_vector = True vector_size = len(value) return is_vector and vector_size == batch_size def add_classification_strings_from_output(dataset_name, split_name, output, datasets_infos, prefix=''): """ Special classification helper: add the class name (output and output_truth) as a string using the class mapping contained in `datasets_infos` :param dataset_name: the dataset name :param split_name: the split name :param output: the output :param datasets_infos: should contain the mapping :param prefix: the output and output_truth will be prefixed with `prefix` :return: the additional strings in a dictionary """ output_dict = {} is_classification = False output_ref = output.get('output_ref') if output_ref is not None: is_classification = isinstance(output_ref, O.OutputClassification) if is_classification: # special handling of the classification node: add class names in string too so it is easier # to review the results, specially when we have many classes mapping = utilities.get_classification_mapping(datasets_infos, dataset_name, split_name, output_ref.classes_name) if mapping is not None: output_values = output.get('output') nb_samples = len(output_values) output_strs = [] output_truth_strs = [] for n in range(nb_samples): output_str = utilities.get_class_name(mapping, output_values[n]) output_truth_values = output.get('output_truth') output_truth_str = utilities.get_class_name(mapping, output_truth_values[n]) output_strs.append(output_str) output_truth_strs.append(output_truth_str) output_dict[prefix + 'output_str'] = output_strs output_dict[prefix + 'output_truth_str'] = output_truth_strs return output_dict class CallbackTensorboardEmbedding(CallbackTensorboardBased): """ This callback records the embedding to be displayed with tensorboard Note: we must recalculate the embedding as we need to associate a specific input (i.e., we can't store everything in memory so we need to collect what we need batch by batch) """ def __init__(self, embedding_name, dataset_name=None, split_name=None, image_name=None, maximum_samples=2000, keep_features_fn=keep_small_features): """ :param embedding_name: the name of the embedding to be used :param dataset_name: the name of the dataset to export the embedding. If `None`, we will try to find the best match :param split_name: the split of the dataset to export the embedding. if :param image_name: the image name to be used in tensorboard. If `None`, we will try to find an image like tensor to be used. If the `image_name` is not None but is not found in the batch, no image will be exported :param maximum_samples: the maximum number of samples to be exported for this embedding """ self.embedding_name = embedding_name self.dataset_name = dataset_name self.split_name = split_name self.image_name = image_name self.maximum_samples = maximum_samples self.keep_features_fn = keep_features_fn self.features_to_discard = ['output_ref'] def first_time(self, datasets, options): self.dataset_name, self.split_name = utilities.find_default_dataset_and_split_names( datasets, default_dataset_name=self.dataset_name, default_split_name=self.split_name, train_split_name=options.workflow_options.train_split ) if self.dataset_name is None: return if self.image_name is None: # try to find a tensor that has the shape of images for batch in datasets[self.dataset_name][self.split_name]: for feature_name, feature in batch.items(): as_image = get_as_image(feature) if as_image is not None: self.image_name = feature_name break break if self.image_name is None: # we haven't found a suitable image for the given dataset/split # so use an impossible name self.image_name = '' def __call__(self, options, history, model, losses, outputs, datasets, datasets_infos, callbacks_per_batch, **kwargs): root = options.workflow_options.current_logging_directory logger.info('root={}, nb_samples={}'.format(root, self.maximum_samples)) logger_tb = CallbackTensorboardBased.create_logger(root) if logger_tb is None: return if self.dataset_name is None or self.image_name is None: self.first_time(datasets, options) if self.dataset_name is None or self.image_name is None: logger.info('embedding can not be calculated: dataset={}, split={}'.format(self.dataset_name, self.split_name)) return None if datasets.get(self.dataset_name) is None or datasets[self.dataset_name].get(self.split_name) is None: logger.info('embedding can not be calculated: dataset={}, split={}'.format(self.dataset_name, self.split_name)) return logger.info('parameters: dataset={}, split={}, embedding={}, image_name={}'.format(self.dataset_name, self.split_name, self.embedding_name, self.image_name)) device = options.workflow_options.device logger.info('collecting embeddings') # here collect the embeddings and images embedding = collections.defaultdict(list) nb_samples_collected = 0 def fill_embedding(batch_size, output, prefix='', output_name=None): # special handling of the classification node: add class names in string too so it is easier # to review the results, specially when we have many classes additional_strings = add_classification_strings_from_output( self.dataset_name, self.split_name, output, datasets_infos, prefix=prefix ) for name, value in additional_strings.items(): embedding[name].append(value) # record the output metrics for feature_name, feature_values in output.items(): if feature_name == self.image_name: continue if not self.keep_features_fn(feature_name, feature_values): continue if feature_name in self.features_to_discard: continue # if we have a vector, it means it is a per-sample feature # else a global feature (e.g., learning rate, dropout rate...) full_name = prefix + feature_name if is_batch_vector(feature_values, batch_size): embedding[full_name].append(to_value(feature_values)) def collect_embedding(dataset_name, split_name, batch, loss_terms, embedding, embedding_name, image_name, **kwargs): batch_size = len_batch(batch) embedding_values = loss_terms.get(embedding_name) if embedding_values is not None: embedding['output'].append(to_value(embedding_values['output'])) for output_name, output in loss_terms.items(): if output_name == embedding_name: continue fill_embedding(batch_size, output, prefix=output_name + '-', output_name=output_name) images = batch.get(image_name) if images is not None: images = get_as_image(images) embedding['images'].append(to_value(images)) fill_embedding(batch_size, batch) nonlocal nb_samples_collected if nb_samples_collected >= self.maximum_samples: # we have exceeded the number of samples to collect, stop the loop raise StopIteration() nb_samples_collected += batch_size from ..train.trainer import eval_loop eval_loop( device, self.dataset_name, self.split_name, datasets[self.dataset_name][self.split_name], model, losses[self.dataset_name], history, callbacks_per_batch=callbacks_per_batch, callbacks_per_batch_loss_terms=[functools.partial(collect_embedding, embedding=embedding, embedding_name=self.embedding_name, image_name=self.image_name)] ) logger.info('collecting embeddings done!') # merge the batches merged_embedding = {} for name, values in embedding.items(): merged_embedding[name] = np.concatenate(values) embedding_values = merged_embedding.get('output') if embedding_values is None: logger.info('No embedding `output` could be found!') return images = merged_embedding.get('images') if images is not None: assert len(images.shape) == 4 and (images.shape[1] == 1 or images.shape[1] == 3), \ 'Expected images format (N, C, H, W), got shape={}'.format(images.shape) images = torch.Tensor(images) # export the metada metadata_header = [] metadata = [] for name, values in merged_embedding.items(): if name != 'output' and name != 'images': metadata_header.append(name) values_str = [str(v).replace('\n', ' ').replace('\t', ' ') for v in values] metadata.append(values_str) if len(metadata_header) != 0: metadata = np.stack(metadata, axis=1) # export the embedding to the tensorboard log logger.info('adding embedding...') logger_tb.add_embedding( embedding_values, label_img=images, global_step=len(history) - 1, metadata=metadata.tolist(), metadata_header=metadata_header) logger.info('embedding successfully added!')
[ "logging.getLogger", "torch.Tensor", "numpy.stack", "collections.defaultdict", "functools.partial", "numpy.concatenate" ]
[((260, 287), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (277, 287), False, 'import logging\n'), ((7154, 7183), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (7177, 7183), False, 'import collections\n'), ((10363, 10385), 'numpy.concatenate', 'np.concatenate', (['values'], {}), '(values)\n', (10377, 10385), True, 'import numpy as np\n'), ((10852, 10872), 'torch.Tensor', 'torch.Tensor', (['images'], {}), '(images)\n', (10864, 10872), False, 'import torch\n'), ((11304, 11330), 'numpy.stack', 'np.stack', (['metadata'], {'axis': '(1)'}), '(metadata, axis=1)\n', (11312, 11330), True, 'import numpy as np\n'), ((10027, 10153), 'functools.partial', 'functools.partial', (['collect_embedding'], {'embedding': 'embedding', 'embedding_name': 'self.embedding_name', 'image_name': 'self.image_name'}), '(collect_embedding, embedding=embedding, embedding_name=\n self.embedding_name, image_name=self.image_name)\n', (10044, 10153), False, 'import functools\n')]
from __future__ import division import numpy as np from dolo.algos.dtcscc.simulations import simulate from dolo.numeric.discretization.quadrature import gauss_hermite_nodes from dolo.numeric.misc import mlinspace class EulerErrors(dict): @property def max_errors(self): return self['max_errors'] @property def mean_errors(self): return self['ergodic'] @property def time_weighted(self): return self['time_weighted'] def __repr__(self): measures = ['max_errors', 'ergodic'] measures += ['time_weighted'] if 'time_weighted' in self else [] s = 'Euler Errors:\n' for m in measures: s += '- {:15}: {}\n'.format(m, self[m]) return s class DenHaanErrors(dict): @property def max_errors(self): return self['max_errors'] @property def mean_errors(self): return self['mean_errors'] def __repr__(self): measures = ['max_errors', 'mean_errors'] s = 'Den Haan errors:\n' for m in measures: s += '- {:15}: {}\n'.format(m, self[m]) return s def omega(model, dr, n_exp=10000, grid={}, bounds=None, n_draws=100, seed=0, horizon=50, s0=None, solve_expectations=False, time_discount=None): assert(model.model_type == 'dtcscc') f = model.functions['arbitrage'] g = model.functions['transition'] distrib = model.get_distribution() sigma = distrib.sigma parms = model.calibration['parameters'] mean = np.zeros(sigma.shape[0]) np.random.seed(seed) epsilons = np.random.multivariate_normal(mean, sigma, n_draws) weights = np.ones(epsilons.shape[0])/n_draws approx = model.get_grid(**grid) a = approx.a b = approx.b orders = approx.orders bounds = np.row_stack([a, b]) domain = RectangularDomain(a, b, orders) grid = domain.grid n_s = len(model.symbols['states']) errors = test_residuals(grid, dr, f, g, parms, epsilons, weights) errors = abs(errors) if s0 is None: s0 = model.calibration['states'] simul = simulate(model, dr, s0, n_exp=n_exp, horizon=horizon+1, discard=True, solve_expectations=solve_expectations, return_array=True) s_simul = simul[:, :, :n_s] densities = [domain.compute_density(s_simul[t, :, :]) for t in range(horizon)] ergo_dens = densities[-1] max_error = np.max(errors, axis=0) # maximum errors ergo_error = np.dot(ergo_dens, errors) # weighted by erg. distr. d = dict( errors=errors, densities=densities, bounds=bounds, max_errors=max_error, ergodic=ergo_error, domain=domain ) if time_discount is not None: beta = time_discount time_weighted_errors = max_error*0 for i in range(horizon): err = np.dot(densities[i], errors) time_weighted_errors += beta**i * err time_weighted_errors /= (1-beta**(horizon-1))/(1-beta) d['time_weighted'] = time_weighted_errors return EulerErrors(d) def denhaanerrors(model, dr, s0=None, horizon=100, n_sims=10, seed=0, integration_orders=None): assert(model.model_type == 'dtcscc') n_x = len(model.symbols['controls']) n_s = len(model.symbols['states']) distrib = model.get_distribution() sigma = distrib.sigma mean = sigma[0, :]*0 if integration_orders is None: integration_orders = [5]*len(mean) [nodes, weights] = gauss_hermite_nodes(integration_orders, sigma) if s0 is None: s0 = model.calibration['states'] # standard simulation simul = simulate(model, dr, s0, horizon=horizon, n_exp=n_sims, seed=seed, solve_expectations=False, return_array=True) simul_se = simulate(model, dr, s0, horizon=horizon, n_exp=n_sims, seed=seed, solve_expectations=True, nodes=nodes, weights=weights, return_array=True) x_simul = simul[:, n_s:n_s+n_x, :] x_simul_se = simul_se[:, n_s:n_s+n_x, :] diff = abs(x_simul_se - x_simul) error_1 = (diff).max(axis=0).mean(axis=1) error_2 = (diff).mean(axis=0).mean(axis=1) d = dict( max_errors=error_1, mean_errors=error_2, horizon=horizon, n_sims=n_sims ) return DenHaanErrors(d) class RectangularDomain: def __init__(self, a, b, orders): self.d = len(a) self.a = a self.b = b self.bounds = np.row_stack([a, b]) self.orders = np.array(orders, dtype=int) nodes = [np.linspace(a[i], b[i], orders[i]) for i in range(len(orders))] self.nodes = nodes self.grid = mlinspace(a, b, orders) def find_cell(self, x): """ @param x: Nxd array @return: Nxd array with line i containing the indices of cell containing x[i, :] """ inf = self.a sup = self.b N = x.shape[0] indices = np.zeros((N, self.d), dtype=int) for i in range(self.d): xi = (x[:, i] - inf[i])/(sup[i]-inf[i]) ni = np.floor(xi*self.orders[i]) ni = np.minimum(np.maximum(ni, 0), self.orders[i]-1) indices[:, i] = ni return np.ravel_multi_index(indices.T, self.orders) def compute_density(self, x): import time t1 = time.time() cell_indices = self.find_cell(x) t2 = time.time() keep = np.isfinite(cell_indices) cell_linear_indices = cell_indices[keep] npoints = cell_indices.shape[0] counts = np.bincount(cell_linear_indices, minlength=self.orders.prod()) dens = counts/npoints t3 = time.time() return dens # TODO: this logic is repeated at least here and in time_iteration.py def test_residuals(s, dr, f, g, parms, epsilons, weights): n_draws = epsilons.shape[0] x = dr(s) [N, n_x] = x.shape ss = np.tile(s, (n_draws, 1)) xx = np.tile(x, (n_draws, 1)) ee = np.repeat(epsilons, N, axis=0) ssnext = g(ss, xx, ee, parms) xxnext = dr(ssnext) val = f(ss, xx, ee, ssnext, xxnext, parms) res = np.zeros((N, n_x)) for i in range(n_draws): res += weights[i] * val[N*i:N*(i+1), :] return res
[ "numpy.ravel_multi_index", "numpy.array", "numpy.isfinite", "numpy.row_stack", "numpy.repeat", "numpy.max", "numpy.dot", "numpy.linspace", "numpy.random.seed", "numpy.maximum", "numpy.tile", "numpy.ones", "numpy.random.multivariate_normal", "numpy.floor", "time.time", "dolo.numeric.mis...
[((1533, 1557), 'numpy.zeros', 'np.zeros', (['sigma.shape[0]'], {}), '(sigma.shape[0])\n', (1541, 1557), True, 'import numpy as np\n'), ((1563, 1583), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1577, 1583), True, 'import numpy as np\n'), ((1599, 1650), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mean', 'sigma', 'n_draws'], {}), '(mean, sigma, n_draws)\n', (1628, 1650), True, 'import numpy as np\n'), ((1811, 1831), 'numpy.row_stack', 'np.row_stack', (['[a, b]'], {}), '([a, b])\n', (1823, 1831), True, 'import numpy as np\n'), ((2112, 2245), 'dolo.algos.dtcscc.simulations.simulate', 'simulate', (['model', 'dr', 's0'], {'n_exp': 'n_exp', 'horizon': '(horizon + 1)', 'discard': '(True)', 'solve_expectations': 'solve_expectations', 'return_array': '(True)'}), '(model, dr, s0, n_exp=n_exp, horizon=horizon + 1, discard=True,\n solve_expectations=solve_expectations, return_array=True)\n', (2120, 2245), False, 'from dolo.algos.dtcscc.simulations import simulate\n'), ((2442, 2464), 'numpy.max', 'np.max', (['errors'], {'axis': '(0)'}), '(errors, axis=0)\n', (2448, 2464), True, 'import numpy as np\n'), ((2506, 2531), 'numpy.dot', 'np.dot', (['ergo_dens', 'errors'], {}), '(ergo_dens, errors)\n', (2512, 2531), True, 'import numpy as np\n'), ((3574, 3620), 'dolo.numeric.discretization.quadrature.gauss_hermite_nodes', 'gauss_hermite_nodes', (['integration_orders', 'sigma'], {}), '(integration_orders, sigma)\n', (3593, 3620), False, 'from dolo.numeric.discretization.quadrature import gauss_hermite_nodes\n'), ((3721, 3835), 'dolo.algos.dtcscc.simulations.simulate', 'simulate', (['model', 'dr', 's0'], {'horizon': 'horizon', 'n_exp': 'n_sims', 'seed': 'seed', 'solve_expectations': '(False)', 'return_array': '(True)'}), '(model, dr, s0, horizon=horizon, n_exp=n_sims, seed=seed,\n solve_expectations=False, return_array=True)\n', (3729, 3835), False, 'from dolo.algos.dtcscc.simulations import simulate\n'), ((3868, 4011), 'dolo.algos.dtcscc.simulations.simulate', 'simulate', (['model', 'dr', 's0'], {'horizon': 'horizon', 'n_exp': 'n_sims', 'seed': 'seed', 'solve_expectations': '(True)', 'nodes': 'nodes', 'weights': 'weights', 'return_array': '(True)'}), '(model, dr, s0, horizon=horizon, n_exp=n_sims, seed=seed,\n solve_expectations=True, nodes=nodes, weights=weights, return_array=True)\n', (3876, 4011), False, 'from dolo.algos.dtcscc.simulations import simulate\n'), ((6090, 6114), 'numpy.tile', 'np.tile', (['s', '(n_draws, 1)'], {}), '(s, (n_draws, 1))\n', (6097, 6114), True, 'import numpy as np\n'), ((6124, 6148), 'numpy.tile', 'np.tile', (['x', '(n_draws, 1)'], {}), '(x, (n_draws, 1))\n', (6131, 6148), True, 'import numpy as np\n'), ((6158, 6188), 'numpy.repeat', 'np.repeat', (['epsilons', 'N'], {'axis': '(0)'}), '(epsilons, N, axis=0)\n', (6167, 6188), True, 'import numpy as np\n'), ((6307, 6325), 'numpy.zeros', 'np.zeros', (['(N, n_x)'], {}), '((N, n_x))\n', (6315, 6325), True, 'import numpy as np\n'), ((1665, 1691), 'numpy.ones', 'np.ones', (['epsilons.shape[0]'], {}), '(epsilons.shape[0])\n', (1672, 1691), True, 'import numpy as np\n'), ((4576, 4596), 'numpy.row_stack', 'np.row_stack', (['[a, b]'], {}), '([a, b])\n', (4588, 4596), True, 'import numpy as np\n'), ((4619, 4646), 'numpy.array', 'np.array', (['orders'], {'dtype': 'int'}), '(orders, dtype=int)\n', (4627, 4646), True, 'import numpy as np\n'), ((4793, 4816), 'dolo.numeric.misc.mlinspace', 'mlinspace', (['a', 'b', 'orders'], {}), '(a, b, orders)\n', (4802, 4816), False, 'from dolo.numeric.misc import mlinspace\n'), ((5088, 5120), 'numpy.zeros', 'np.zeros', (['(N, self.d)'], {'dtype': 'int'}), '((N, self.d), dtype=int)\n', (5096, 5120), True, 'import numpy as np\n'), ((5362, 5406), 'numpy.ravel_multi_index', 'np.ravel_multi_index', (['indices.T', 'self.orders'], {}), '(indices.T, self.orders)\n', (5382, 5406), True, 'import numpy as np\n'), ((5476, 5487), 'time.time', 'time.time', ([], {}), '()\n', (5485, 5487), False, 'import time\n'), ((5543, 5554), 'time.time', 'time.time', ([], {}), '()\n', (5552, 5554), False, 'import time\n'), ((5571, 5596), 'numpy.isfinite', 'np.isfinite', (['cell_indices'], {}), '(cell_indices)\n', (5582, 5596), True, 'import numpy as np\n'), ((5845, 5856), 'time.time', 'time.time', ([], {}), '()\n', (5854, 5856), False, 'import time\n'), ((2923, 2951), 'numpy.dot', 'np.dot', (['densities[i]', 'errors'], {}), '(densities[i], errors)\n', (2929, 2951), True, 'import numpy as np\n'), ((4664, 4698), 'numpy.linspace', 'np.linspace', (['a[i]', 'b[i]', 'orders[i]'], {}), '(a[i], b[i], orders[i])\n', (4675, 4698), True, 'import numpy as np\n'), ((5222, 5251), 'numpy.floor', 'np.floor', (['(xi * self.orders[i])'], {}), '(xi * self.orders[i])\n', (5230, 5251), True, 'import numpy as np\n'), ((5278, 5295), 'numpy.maximum', 'np.maximum', (['ni', '(0)'], {}), '(ni, 0)\n', (5288, 5295), True, 'import numpy as np\n')]
import numpy as np import os import paddle.fluid as fluid import logging import args import random import time from evaluator import BiRNN logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger("fluid") logger.setLevel(logging.INFO) user_id = 0 class Dataset(object): def _reader_creator(self): def reader(): global user_id user_slot_name = [] for j in range(args.batch_size): user_slot_name.append([user_id]) user_id += 1 item_slot_name = np.random.randint(args.item_vocab, size=(args.batch_size, args.item_len)).tolist() lenght = [args.item_len]*args.batch_size label = np.random.randint(2, size=(args.batch_size, args.item_len)).tolist() output = [] output.append(user_slot_name) output.append(item_slot_name) output.append(lenght) output.append(label) yield output return reader def get_train_data(self): return self._reader_creator() def train(args): model = BiRNN() inputs = model.input_data(args.item_len) loss, auc_val, batch_auc, auc_states = model.net(inputs, args.hidden_size, args.batch_size*args.sample_size, args.item_vocab, args.embd_dim) optimizer = fluid.optimizer.Adam(learning_rate=args.base_lr, epsilon=1e-4) optimizer.minimize(loss) place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace() exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) train_data_generator = Dataset() train_reader = fluid.io.batch(train_data_generator.get_train_data(), batch_size=args.batch_size) loader = fluid.io.DataLoader.from_generator(feed_list=inputs, capacity=args.batch_size, iterable=True) loader.set_sample_list_generator(train_reader, places=place) for epoch in range(args.epochs): for i in range(args.sample_size): for batch_id, data in enumerate(loader()): begin = time.time() loss_val, auc = exe.run(program=fluid.default_main_program(), feed=data, fetch_list=[loss.name, auc_val], return_numpy=True) end = time.time() logger.info("epoch: {}, batch_id: {}, batch_time: {:.5f}s, loss: {:.5f}, auc: {:.5f}".format( epoch, batch_id, end-begin, float(np.array(loss_val)), float(np.array(auc)))) #save model model_dir = os.path.join(args.model_dir, 'epoch_' + str(1), "checkpoint") main_program = fluid.default_main_program() fluid.save(main_program, model_dir) if __name__ == "__main__": args = args.parse_args() logger.info("use_gpu: {}, batch_size: {}, model_dir: {}, embd_dim: {}, hidden_size: {}, item_vocab: {}, user_vocab: {},\ item_len: {}, sample_size: {}, base_lr: {}".format(args.use_gpu, args.batch_size, args.model_dir, args.embd_dim, args.hidden_size, args.item_vocab, args.user_vocab, args.item_len, args.sample_size, args.base_lr)) train(args)
[ "logging.basicConfig", "evaluator.BiRNN", "logging.getLogger", "paddle.fluid.save", "paddle.fluid.io.DataLoader.from_generator", "paddle.fluid.default_startup_program", "time.time", "paddle.fluid.CPUPlace", "paddle.fluid.default_main_program", "numpy.random.randint", "paddle.fluid.Executor", "...
[((140, 211), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(levelname)s - %(message)s"""'}), "(format='%(asctime)s - %(levelname)s - %(message)s')\n", (159, 211), False, 'import logging\n'), ((221, 247), 'logging.getLogger', 'logging.getLogger', (['"""fluid"""'], {}), "('fluid')\n", (238, 247), False, 'import logging\n'), ((1137, 1144), 'evaluator.BiRNN', 'BiRNN', ([], {}), '()\n', (1142, 1144), False, 'from evaluator import BiRNN\n'), ((1352, 1416), 'paddle.fluid.optimizer.Adam', 'fluid.optimizer.Adam', ([], {'learning_rate': 'args.base_lr', 'epsilon': '(0.0001)'}), '(learning_rate=args.base_lr, epsilon=0.0001)\n', (1372, 1416), True, 'import paddle.fluid as fluid\n'), ((1524, 1545), 'paddle.fluid.Executor', 'fluid.Executor', (['place'], {}), '(place)\n', (1538, 1545), True, 'import paddle.fluid as fluid\n'), ((1747, 1845), 'paddle.fluid.io.DataLoader.from_generator', 'fluid.io.DataLoader.from_generator', ([], {'feed_list': 'inputs', 'capacity': 'args.batch_size', 'iterable': '(True)'}), '(feed_list=inputs, capacity=args.\n batch_size, iterable=True)\n', (1781, 1845), True, 'import paddle.fluid as fluid\n'), ((2653, 2681), 'paddle.fluid.default_main_program', 'fluid.default_main_program', ([], {}), '()\n', (2679, 2681), True, 'import paddle.fluid as fluid\n'), ((2686, 2721), 'paddle.fluid.save', 'fluid.save', (['main_program', 'model_dir'], {}), '(main_program, model_dir)\n', (2696, 2721), True, 'import paddle.fluid as fluid\n'), ((2761, 2778), 'args.parse_args', 'args.parse_args', ([], {}), '()\n', (2776, 2778), False, 'import args\n'), ((1457, 1475), 'paddle.fluid.CUDAPlace', 'fluid.CUDAPlace', (['(0)'], {}), '(0)\n', (1472, 1475), True, 'import paddle.fluid as fluid\n'), ((1497, 1513), 'paddle.fluid.CPUPlace', 'fluid.CPUPlace', ([], {}), '()\n', (1511, 1513), True, 'import paddle.fluid as fluid\n'), ((1558, 1589), 'paddle.fluid.default_startup_program', 'fluid.default_startup_program', ([], {}), '()\n', (1587, 1589), True, 'import paddle.fluid as fluid\n'), ((2064, 2075), 'time.time', 'time.time', ([], {}), '()\n', (2073, 2075), False, 'import time\n'), ((2311, 2322), 'time.time', 'time.time', ([], {}), '()\n', (2320, 2322), False, 'import time\n'), ((590, 663), 'numpy.random.randint', 'np.random.randint', (['args.item_vocab'], {'size': '(args.batch_size, args.item_len)'}), '(args.item_vocab, size=(args.batch_size, args.item_len))\n', (607, 663), True, 'import numpy as np\n'), ((746, 805), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': '(args.batch_size, args.item_len)'}), '(2, size=(args.batch_size, args.item_len))\n', (763, 805), True, 'import numpy as np\n'), ((2124, 2152), 'paddle.fluid.default_main_program', 'fluid.default_main_program', ([], {}), '()\n', (2150, 2152), True, 'import paddle.fluid as fluid\n'), ((2487, 2505), 'numpy.array', 'np.array', (['loss_val'], {}), '(loss_val)\n', (2495, 2505), True, 'import numpy as np\n'), ((2514, 2527), 'numpy.array', 'np.array', (['auc'], {}), '(auc)\n', (2522, 2527), True, 'import numpy as np\n')]
#!/usr/bin/env python3 import logging import random as rnd import numpy as np import cliffords import copy import itertools import gates from sequence import Sequence log = logging.getLogger('LabberDriver') import os path_currentdir = os.path.dirname(os.path.realpath(__file__)) # curret directory def CheckIdentity(matrix): """ Check whether the matrix is identity by calculating it numerically. Parameters ---------- matrix: 4x4 np.matrix matrix Returns ------- result: bool True, if identity. """ #Check all the diagonal entries. if ((np.abs(np.abs(matrix[0,0])-1)< 1e-6) and (np.abs(np.abs(matrix[1,1])-1)< 1e-6) and (np.abs(np.abs(matrix[2,2])-1)< 1e-6) and (np.abs(np.abs(matrix[3,3])-1)< 1e-6) and (np.abs(matrix[1,1]/matrix[0,0]-1)<1e-6) and (np.abs(matrix[2,2]/matrix[0,0]-1)<1e-6) and (np.abs(matrix[3,3]/matrix[0,0]-1)<1e-6)): return True else: return False def add_singleQ_clifford(index, gate_seq, pad_with_I=True): """Add single qubit clifford (24).""" length_before = len(gate_seq) # Paulis if index == 0: gate_seq.append(gates.I) elif index == 1: gate_seq.append(gates.Xp) elif index == 2: gate_seq.append(gates.Yp) elif index == 3: gate_seq.append(gates.Yp) gate_seq.append(gates.Xp) # 2pi/3 rotations elif index == 4: gate_seq.append(gates.X2p) gate_seq.append(gates.Y2p) elif index == 5: gate_seq.append(gates.X2p) gate_seq.append(gates.Y2m) elif index == 6: gate_seq.append(gates.X2m) gate_seq.append(gates.Y2p) elif index == 7: gate_seq.append(gates.X2m) gate_seq.append(gates.Y2m) elif index == 8: gate_seq.append(gates.Y2p) gate_seq.append(gates.X2p) elif index == 9: gate_seq.append(gates.Y2p) gate_seq.append(gates.X2m) elif index == 10: gate_seq.append(gates.Y2m) gate_seq.append(gates.X2p) elif index == 11: gate_seq.append(gates.Y2m) gate_seq.append(gates.X2m) # pi/2 rotations elif index == 12: gate_seq.append(gates.X2p) elif index == 13: gate_seq.append(gates.X2m) elif index == 14: gate_seq.append(gates.Y2p) elif index == 15: gate_seq.append(gates.Y2m) elif index == 16: gate_seq.append(gates.X2m) gate_seq.append(gates.Y2p) gate_seq.append(gates.X2p) elif index == 17: gate_seq.append(gates.X2m) gate_seq.append(gates.Y2m) gate_seq.append(gates.X2p) # Hadamard-Like elif index == 18: gate_seq.append(gates.Xp) gate_seq.append(gates.Y2p) elif index == 19: gate_seq.append(gates.Xp) gate_seq.append(gates.Y2m) elif index == 20: gate_seq.append(gates.Yp) gate_seq.append(gates.X2p) elif index == 21: gate_seq.append(gates.Yp) gate_seq.append(gates.X2m) elif index == 22: gate_seq.append(gates.X2p) gate_seq.append(gates.Y2p) gate_seq.append(gates.X2p) elif index == 23: gate_seq.append(gates.X2m) gate_seq.append(gates.Y2p) gate_seq.append(gates.X2m) else: raise ValueError( 'index is out of range. it should be smaller than 24 and greater' ' or equal to 0: ', str(index)) length_after = len(gate_seq) if pad_with_I: # Force the clifford to have a length of 3 gates for i in range(3-(length_after-length_before)): gate_seq.append(gates.I) def add_twoQ_clifford(index, gate_seq_1, gate_seq_2, generator = 'CZ'): """Add single qubit clifford (11520 = 576 + 5184 + 5184 + 576).""" if (index < 0): raise ValueError( 'index is out of range. it should be smaller than 11520 and ' 'greater or equal to 0: ', str(index)) elif (index < 576): add_singleQ_based_twoQ_clifford(index, gate_seq_1, gate_seq_2) elif (index < 5184 + 576): add_CNOT_like_twoQ_clifford(index, gate_seq_1, gate_seq_2, generator = generator) elif (index < 5184 + 5184 + 576): add_iSWAP_like_twoQ_clifford(index, gate_seq_1, gate_seq_2, generator = generator) elif (index < 576 + 5184 + 5184 + 576): add_SWAP_like_twoQ_clifford(index, gate_seq_1, gate_seq_2, generator = generator) else: raise ValueError( 'index is out of range. it should be smaller than 11520 and ' 'greater or equal to 0: ', str(index)) pass def add_singleQ_S1(index, gate_seq): """Add single qubit clifford from S1. (I-like-subset of single qubit clifford group) (3) """ if index == 0: gate_seq.append(gates.I) gate_seq.append(gates.I) # auxiliary gate_seq.append(gates.I) # auxiliary elif index == 1: gate_seq.append(gates.Y2p) gate_seq.append(gates.X2p) gate_seq.append(gates.I) # auxiliary elif index == 2: gate_seq.append(gates.X2m) gate_seq.append(gates.Y2m) gate_seq.append(gates.I) # auxiliary def add_singleQ_S1_X2p(index, gate_seq): """Add single qubit clifford from S1_X2p. (X2p-like-subset of single qubit clifford group) (3) """ if index == 0: gate_seq.append(gates.X2p) gate_seq.append(gates.I) # auxiliary gate_seq.append(gates.I) # auxiliary elif index == 1: gate_seq.append(gates.X2p) gate_seq.append(gates.Y2p) gate_seq.append(gates.X2p) elif index == 2: gate_seq.append(gates.Y2m) gate_seq.append(gates.I) # auxiliary gate_seq.append(gates.I) # auxiliary def add_singleQ_S1_Y2p(index, gate_seq): """Add single qubit clifford from S1_Y2p. (Y2p-like-subset of single qubit clifford group) (3) """ if index == 0: gate_seq.append(gates.Y2p) gate_seq.append(gates.I) # auxiliary gate_seq.append(gates.I) # auxiliary elif index == 1: gate_seq.append(gates.Yp) gate_seq.append(gates.X2p) gate_seq.append(gates.I) # auxiliary elif index == 2: gate_seq.append(gates.X2m) gate_seq.append(gates.Y2m) gate_seq.append(gates.X2p) def add_singleQ_S1_Z2p(index, gate_seq): """Add single qubit clifford from S1_Z2p. (Z2p-like-subset of single qubit clifford group) (3) """ if index == 0: gate_seq.append(gates.X2m) gate_seq.append(gates.Y2m) gate_seq.append(gates.X2p) elif index == 1: gate_seq.append(gates.Y2p) gate_seq.append(gates.I) # auxiliary gate_seq.append(gates.I) # auxiliary elif index == 2: gate_seq.append(gates.X2m) gate_seq.append(gates.Ym) gate_seq.append(gates.I) # auxiliary def add_singleQ_based_twoQ_clifford(index, gate_seq_1, gate_seq_2, **kwargs): """Add single-qubit-gates-only-based two Qubit Clifford. (24*24 = 576) (gate_seq_1: gate seq. of qubit #1, gate_seq_t: gate seq. of qubit #2) """ # randomly sample from single qubit cliffords (24) index_1 = index % 24 # randomly sample from single qubit cliffords (24) index_2 = (index // 24) % 24 add_singleQ_clifford(index_1, gate_seq_1) add_singleQ_clifford(index_2, gate_seq_2) def add_CNOT_like_twoQ_clifford(index, gate_seq_1, gate_seq_2, **kwargs): """Add CNOT like two Qubit Clifford. (24*24*3*3 = 5184) (gate_seq_1: gate seq. of qubit #1, gate_seq_t: gate seq. of qubit #2) """ # randomly sample from single qubit cliffords (24) index_1 = index % 24 # randomly sample from single qubit cliffords (24) index_2 = (index // 24) % 24 # randomly sample from S1 (3) index_3 = (index // 24 // 24) % 3 # randomly sample from S1_Y2p (3) or S1_Z2p (3) index_4 = (index // 24 // 24 // 3) % 3 generator = kwargs.get('generator', 'CZ') if generator == 'CZ': add_singleQ_clifford(index_1, gate_seq_1) add_singleQ_clifford(index_2, gate_seq_2) gate_seq_1.append(gates.I) gate_seq_2.append(gates.CZ) add_singleQ_S1(index_3, gate_seq_1) add_singleQ_S1_Y2p(index_4, gate_seq_2) elif generator == 'iSWAP': add_singleQ_clifford(index_1, gate_seq_1) add_singleQ_clifford(index_2, gate_seq_2) gate_seq_1.append(gates.I) gate_seq_2.append(gates.iSWAP) gate_seq_1.append(gates.X2p) gate_seq_2.append(gates.I) gate_seq_1.append(gates.I) gate_seq_2.append(gates.iSWAP) add_singleQ_S1(index_3, gate_seq_1) add_singleQ_S1_Z2p(index_4, gate_seq_2) def add_iSWAP_like_twoQ_clifford(index, gate_seq_1, gate_seq_2, **kwargs): """Add iSWAP like two Qubit Clifford. (24*24*3*3 = 5184) (gate_seq_1: gate seq. of qubit #1, gate_seq_t: gate seq. of qubit #2) """ generator = kwargs.get('generator', 'CZ') # randomly sample from single qubit cliffords (24) index_1 = index % 24 # randomly sample from single qubit cliffords (24) index_2 = (index // 24) % 24 # randomly sample from S1_Y2p (3) or S1 (3) index_3 = (index // 24 // 24) % 3 # randomly sample from S1_X2p (3) or S1 (3) index_4 = (index // 24 // 24 // 3) % 3 if generator == 'CZ': add_singleQ_clifford(index_1, gate_seq_1) add_singleQ_clifford(index_2, gate_seq_2) gate_seq_1.append(gates.I) gate_seq_2.append(gates.CZ) gate_seq_1.append(gates.Y2p) gate_seq_2.append(gates.X2m) gate_seq_1.append(gates.I) gate_seq_2.append(gates.CZ) add_singleQ_S1_Y2p(index_3, gate_seq_1) add_singleQ_S1_X2p(index_4, gate_seq_2) elif generator == 'iSWAP': add_singleQ_clifford(index_1, gate_seq_1) add_singleQ_clifford(index_2, gate_seq_2) gate_seq_1.append(gates.I) gate_seq_2.append(gates.iSWAP) add_singleQ_S1(index_3, gate_seq_1) add_singleQ_S1(index_4, gate_seq_2) def add_SWAP_like_twoQ_clifford(index, gate_seq_1, gate_seq_2, **kwargs): """Add SWAP like two Qubit Clifford. (24*24*= 576) (gate_seq_1: gate seq. of qubit #1, gate_seq_t: gate seq. of qubit #2) """ # randomly sample from single qubit cliffords (24) index_1 = index % 24 # randomly sample from single qubit cliffords (24) index_2 = (index // 24) % 24 generator = kwargs.get('generator', 'CZ') if generator == 'CZ': add_singleQ_clifford(index_1, gate_seq_1) add_singleQ_clifford(index_2, gate_seq_2) gate_seq_1.append(gates.I) gate_seq_2.append(gates.CZ) gate_seq_1.append(gates.Y2m) gate_seq_2.append(gates.Y2p) gate_seq_1.append(gates.I) gate_seq_2.append(gates.CZ) gate_seq_1.append(gates.Y2p) gate_seq_2.append(gates.Y2m) gate_seq_1.append(gates.I) gate_seq_2.append(gates.CZ) gate_seq_1.append(gates.I) gate_seq_2.append(gates.Y2p) elif generator == 'iSWAP': add_singleQ_clifford(index_1, gate_seq_1) add_singleQ_clifford(index_2, gate_seq_2) gate_seq_1.append(gates.I) gate_seq_2.append(gates.iSWAP) gate_seq_1.append(gates.I) gate_seq_2.append(gates.X2m) gate_seq_1.append(gates.I) gate_seq_2.append(gates.iSWAP) gate_seq_1.append(gates.X2m) gate_seq_2.append(gates.I) gate_seq_1.append(gates.I) gate_seq_2.append(gates.iSWAP) gate_seq_1.append(gates.I) gate_seq_2.append(gates.X2m) class SingleQubit_RB(Sequence): """Single qubit randomized benchmarking.""" prev_randomize = np.inf # store the previous value prev_N_cliffords = np.inf # store the previous value prev_interleave = np.inf # store the previous value prev_interleaved_gate = np.inf # store the previous value prev_sequence = '' prev_gate_seq = [] def generate_sequence(self, config): """Generate sequence by adding gates/pulses to waveforms.""" # get parameters sequence = config['Sequence'] # Number of Cliffords to generate N_cliffords = int(config['Number of Cliffords']) randomize = config['Randomize'] interleave = config['Interleave 1-QB Gate'] multi_seq = config.get('Output multiple sequences', False) write_seq = config.get('Write sequence as txt file', False) log.info('Assign seed %d' %(randomize)) rnd.seed(randomize) if interleave is True: interleaved_gate = config['Interleaved 1-QB Gate'] else: interleaved_gate = np.inf # generate new randomized clifford gates only if configuration changes if (self.prev_sequence != sequence or self.prev_randomize != randomize or self.prev_N_cliffords != N_cliffords or self.prev_interleave != interleave or multi_seq or self.prev_interleaved_gate != interleaved_gate or self.prev_n_qubit != self.n_qubit): self.prev_randomize = randomize self.prev_N_cliffords = N_cliffords self.prev_interleave = interleave self.prev_sequence = sequence self.prev_n_qubit = self.n_qubit multi_gate_seq = [] for n in range(self.n_qubit): # Generate 1QB RB sequence single_gate_seq = [] for i in range(N_cliffords): rndnum = rnd.randint(0, 23) log.info('Random number %d' %(rndnum)) add_singleQ_clifford(rndnum, single_gate_seq, pad_with_I=False) # If interleave gate, if interleave is True: self.prev_interleaved_gate = interleaved_gate # To step over "Reference Randomized Benchmarking" 05/15/2019 if interleaved_gate == 'Ref': pass else: single_gate_seq.append(getattr(gates, interleaved_gate)) recovery_gate = self.get_recovery_gate(single_gate_seq) # print 1QB-RB sequence if write_seq == True: import os from datetime import datetime directory = os.path.join(path_currentdir,'1QB_RBseq') if not os.path.exists(directory): os.makedirs(directory) filename = datetime.now().strftime('%Y-%m-%d %H-%M-%S-f')[:-3] + '_qbNum=%d_N_cliffords=%d_seed=%d.txt'%(n, N_cliffords,randomize) filepath = os.path.join(directory,filename) log.info('make file: ' + filepath) with open(filepath, "w") as text_file: print('New Sequence', file=text_file) for i in range(len(single_gate_seq)): print("CliffordIndex: %d, Gate: ["%(i) + cliffords.Gate_to_strGate(single_gate_seq[i]) +"]", file=text_file) print("Corresponding recovery sequence:") print("Recovery Gate: [" + cliffords.Gate_to_strGate(recovery_gate) +"]", file=text_file) single_gate_seq.append(recovery_gate) multi_gate_seq.append(single_gate_seq) # transpose list of lists # - (06/23/2019 Update) Fill identity gates to the shorter sequence at the end -> at the beginning multi_gate_seq_reversed = [i[::-1] for i in multi_gate_seq] multi_gate_seq_reversed_tr = list(map(list, itertools.zip_longest(*multi_gate_seq_reversed, fillvalue=gates.I))) # Not to chop multi_gate_seq = multi_gate_seq_reversed_tr[::-1] self.add_gates(multi_gate_seq) self.prev_gate_seq = multi_gate_seq else: self.add_gates(self.prev_gate_seq) def evaluate_sequence(self, gate_seq): """ Evaluate a single qubit gate sequence. (Reference: http://www.vcpc.univie.ac.at/~ian/hotlist/qc/talks/bloch-sphere-rotations.pdf) Parameters ---------- gate_seq_1: list of class Gate (defined in "gates.py") The gate sequence applied to a qubit Returns ------- singleQ_gate: np.matrix The evaulation result. """ singleQ_gate = np.matrix([[1, 0], [0, 1]]) for i in range(len(gate_seq)): if (gate_seq[i] == gates.I): pass elif (gate_seq[i] == gates.X2p): singleQ_gate = np.matmul( np.matrix([[1, -1j], [-1j, 1]]) / np.sqrt(2), singleQ_gate) elif (gate_seq[i] == gates.X2m): singleQ_gate = np.matmul( np.matrix([[1, 1j], [1j, 1]]) / np.sqrt(2), singleQ_gate) elif (gate_seq[i] == gates.Y2p): singleQ_gate = np.matmul( np.matrix([[1, -1], [1, 1]]) / np.sqrt(2), singleQ_gate) elif (gate_seq[i] == gates.Y2m): singleQ_gate = np.matmul( np.matrix([[1, 1], [-1, 1]]) / np.sqrt(2), singleQ_gate) elif (gate_seq[i] == gates.Xp): singleQ_gate = np.matmul( np.matrix([[0, -1j], [-1j, 0]]), singleQ_gate) elif (gate_seq[i] == gates.Xm): singleQ_gate = np.matmul( np.matrix([[0, 1j], [1j, 0]]), singleQ_gate) elif (gate_seq[i] == gates.Yp): singleQ_gate = np.matmul( np.matrix([[0, -1], [1, 0]]), singleQ_gate) elif (gate_seq[i] == gates.Ym): singleQ_gate = np.matmul( np.matrix([[0, 1], [-1, 0]]), singleQ_gate) elif (gate_seq[i] in (gates.Zp, gates.VZp)): singleQ_gate = np.matmul( np.matrix([[-1j, 0], [0, 1j]]), singleQ_gate) return singleQ_gate def get_recovery_gate(self, gate_seq): """ Get the recovery (the inverse) gate Parameters ---------- gate_seq: list of class Gate The gate sequence applied to a qubit Returns ------- recovery_gate: Gate The recovery gate """ qubit_state = np.matrix('1; 0') # initial state: ground state, following the QC community's convention qubit_state = np.matmul(self.evaluate_sequence(gate_seq), qubit_state) # find recovery gate which makes qubit_state return to initial state if (np.abs(np.linalg.norm(qubit_state.item((0, 0))) - 1) < 0.1): # ground state -> I recovery_gate = gates.I elif (np.abs(np.linalg.norm(qubit_state.item((1, 0))) - 1) < 0.1): # excited state -> X Pi recovery_gate = gates.Xp elif (np.linalg.norm(qubit_state.item((1, 0)) / qubit_state.item((0, 0)) + 1) < 0.1): # X State -> Y +Pi/2 recovery_gate = gates.Y2p elif (np.linalg.norm(qubit_state.item((1, 0)) / qubit_state.item((0, 0)) - 1) < 0.1): # -X State -> Y -Pi/2 recovery_gate = gates.Y2m elif (np.linalg.norm(qubit_state.item((1, 0)) / qubit_state.item((0, 0)) + 1j) < 0.1): # Y State -> X -Pi/2 recovery_gate = gates.X2m elif (np.linalg.norm(qubit_state.item((1, 0)) / qubit_state.item((0, 0)) - 1j) < 0.1): # -Y State -> X +Pi/2 recovery_gate = gates.X2p else: raise InstrumentDriver.Error( 'Error in calculating recovery gates. qubit state:' + str(qubit_state)) return recovery_gate class TwoQubit_RB(Sequence): """Two qubit randomized benchmarking.""" prev_randomize = np.inf # store the previous value prev_N_cliffords = np.inf # store the previous value prev_interleave = np.inf # store the previous value prev_interleaved_gate = np.inf # store the previous value prev_sequence = '' prev_gate_seq = [] filepath_lookup_table = "" # def __init__(self, *args, **kwargs): # log.info(str(args)+ str(kwargs)) # super(Sequence, self).__init__(*args, **kwargs) # self.filepath_lookup_table = "" def generate_sequence(self, config): """ Generate sequence by adding gates/pulses to waveforms. Parameters ---------- config: dict configuration Returns ------- """ # get parameters sequence = config['Sequence'] qubits_to_benchmark = [int(config['Qubits to Benchmark'][0]) - 1, int(config['Qubits to Benchmark'][2]) - 1] # Number of Cliffords to generate N_cliffords = int(config['Number of Cliffords']) randomize = config['Randomize'] interleave = config['Interleave 2-QB Gate'] multi_seq = config.get('Output multiple sequences', False) write_seq = config.get('Write sequence as txt file', False) generator = config.get('Native 2-QB gate', 'CZ') rnd.seed(randomize) if interleave is True: interleaved_gate = config['Interleaved 2-QB Gate'] else: interleaved_gate = np.inf # generate new randomized clifford gates only if configuration changes if (self.prev_sequence != sequence or self.prev_randomize != randomize or self.prev_N_cliffords != N_cliffords or self.prev_interleave != interleave or multi_seq or self.prev_interleaved_gate != interleaved_gate or self.generator != generator): self.prev_randomize = randomize self.prev_N_cliffords = N_cliffords self.prev_interleave = interleave self.prev_sequence = sequence self.generator = generator multi_gate_seq = [] # Generate 2QB RB sequence cliffordSeq1 = [] cliffordSeq2 = [] for j in range(N_cliffords): log.info('Seed number: %d'%(randomize)) rndnum = rnd.randint(0, 11519) # rndnum = rnd.randint(0, 576) #Only applying single qubit gates add_twoQ_clifford(rndnum, cliffordSeq1, cliffordSeq2, generator = generator) # If interleave gate, if interleave is True: self.prev_interleaved_gate = interleaved_gate if interleaved_gate == 'CZ': cliffordSeq1.append(gates.I) cliffordSeq2.append(gates.CZ) elif interleaved_gate == 'CZEcho': # CZEcho is a composite gate, so get each gate gate = gates.CZEcho for g in gate.sequence: cliffordSeq1.append(g[1]) cliffordSeq2.append(g[0]) elif interleaved_gate == 'iSWAP': gate = gates.iSWAP for g in gate.sequence: cliffordSeq1.append(g[1]) cliffordSeq2.append(g[0]) elif interleaved_gate == 'I': # TBA: adjust the duration of I gates? # log.info('Qubits to benchmark: ' + str(qubits_to_benchmark)) # gate = gates.I(width = self.pulses_2qb[qubit]).value I_2QB = gates.IdentityGate(width =config.get('Width, 2QB')) cliffordSeq1.append(I_2QB) cliffordSeq2.append(I_2QB) # cliffordSeq1.append(gates.I) # cliffordSeq2.append(gates.I) # remove redundant Identity gates for cliffordSeq1 index_identity_clifford = [] # find where Identity gates are for p in range(len(cliffordSeq1)): if (cliffordSeq1[p] == gates.I and cliffordSeq2[p] == gates.I): index_identity_clifford.append(p) cliffordSeq1 = [m for n, m in enumerate(cliffordSeq1) if n not in index_identity_clifford] cliffordSeq2 = [m for n, m in enumerate(cliffordSeq2) if n not in index_identity_clifford] # get recovery gate seq (recoverySeq1, recoverySeq2) = self.get_recovery_gate( cliffordSeq1, cliffordSeq2, config, generator = generator) # Remove redundant identity gates in recovery gate seq index_identity_recovery = [] # find where Identity gates are for p in range(len(recoverySeq1)): if (recoverySeq1[p] == gates.I and recoverySeq2[p] == gates.I): index_identity_recovery.append(p) recoverySeq1 = [m for n, m in enumerate(recoverySeq1) if n not in index_identity_recovery] recoverySeq2 = [m for n, m in enumerate(recoverySeq2) if n not in index_identity_recovery] # Construct the total gate sequence. gateSeq1 = [] gateSeq2 = [] gateSeq1.extend(cliffordSeq1) gateSeq1.extend(recoverySeq1) gateSeq2.extend(cliffordSeq2) gateSeq2.extend(recoverySeq2) # Avoid Error: zero-size array to reduction operation maximum which has no identity (05/05/2019) if (gateSeq1 == [] and gateSeq2 == []): gateSeq1.append(gates.I) gateSeq2.append(gates.I) # test the recovery gate psi_gnd = np.matrix('1; 0; 0; 0') # ground state |00> if write_seq == True: import os from datetime import datetime directory = os.path.join(path_currentdir,'2QB_RBseq') if not os.path.exists(directory): os.makedirs(directory) filename = datetime.now().strftime('%Y-%m-%d %H-%M-%S-f')[:-3] + '_N_cliffords=%d_seed=%d.txt'%(N_cliffords,randomize) # filename = datetime.now().strftime('%Y-%m-%d %H-%M-%S-%f')[:-3] + '_N_cliffords=%d_seed=%d.txt'%(N_cliffords,randomize) filepath = os.path.join(directory,filename) log.info('make file: ' + filepath) with open(filepath, "w") as text_file: print('New Sequence', file=text_file) for i in range(len(gateSeq1)): print("Index: %d, Gate: ["%(i) + cliffords.Gate_to_strGate(gateSeq1[i]) + ", " + cliffords.Gate_to_strGate(gateSeq2[i]) +']', file=text_file) for i in range(len(cliffordSeq1)): print("CliffordIndex: %d, Gate: ["%(i) + cliffords.Gate_to_strGate(cliffordSeq1[i]) + ", " + cliffords.Gate_to_strGate(cliffordSeq2[i]) +']', file=text_file) for i in range(len(recoverySeq1)): print("RecoveryIndex: %d, Gate: ["%(i) + cliffords.Gate_to_strGate(recoverySeq1[i]) + ", " + cliffords.Gate_to_strGate(recoverySeq2[i]) +']', file=text_file) psi = np.matmul(self.evaluate_sequence(gateSeq1, gateSeq2), psi_gnd) np.set_printoptions(precision=2) log.info('The matrix of the overall gate sequence:') log.info(self.evaluate_sequence(gateSeq1, gateSeq2)) log.info('--- TESTING THE RECOVERY GATE ---') log.info('The probability amplitude of the final state vector: ' + str(np.matrix(psi).flatten())) log.info('The population of the ground state after the gate sequence: %.4f'%(np.abs(psi[0,0])**2)) log.info('-------------------------------------------') # Assign two qubit gate sequence to where we want # for i in range(qubits_to_benchmark[0] - 1): # multi_gate_seq.append([None] * len(gateSeq1)) multi_gate_seq.append(gateSeq2) multi_gate_seq.append(gateSeq1) # for i in range(self.n_qubit - qubits_to_benchmark[1]): # multi_gate_seq.append([None] * len(gateSeq1)) # transpose list of lists multi_gate_seq = list(map(list, itertools.zip_longest(*multi_gate_seq, fillvalue=gates.I))) # Not to chop # self.add_gates(multi_gate_seq) for gate_seq in multi_gate_seq: if ((gate_seq[0] == gates.CZ) or (gate_seq[0] == gates.iSWAP)): self.add_gate(qubit=qubits_to_benchmark, gate=gate_seq[0]) else: self.add_gate(qubit=qubits_to_benchmark, gate=gate_seq) self.prev_gate_seq = multi_gate_seq else: for gate_seq in self.prev_gate_seq: if gate_seq[0] == gates.CZ: self.add_gate(qubit=qubits_to_benchmark, gate=gate_seq[0]) else: self.add_gate(qubit=qubits_to_benchmark, gate=gate_seq) def evaluate_sequence(self, gate_seq_1, gate_seq_2, generator = 'CZ'): """ Evaluate the two qubit gate sequence. Parameters ---------- gate_seq_1: list of class Gate (defined in "gates.py") The gate sequence applied to Qubit "1" gate_seq_2: list of class Gate (defined in "gates.py") The gate sequence applied to Qubit "2" Returns ------- twoQ_gate: np.matrix (shape = (4,4)) The evaulation result. """ twoQ_gate = np.matrix( [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) for i in range(len(gate_seq_1)): gate_1 = np.matrix([[1, 0], [0, 1]]) gate_2 = np.matrix([[1, 0], [0, 1]]) if (gate_seq_1[i] == gates.I): pass elif (gate_seq_1[i] == gates.X2p): gate_1 = np.matmul( np.matrix([[1, -1j], [-1j, 1]]) / np.sqrt(2), gate_1) elif (gate_seq_1[i] == gates.X2m): gate_1 = np.matmul( np.matrix([[1, 1j], [1j, 1]]) / np.sqrt(2), gate_1) elif (gate_seq_1[i] == gates.Y2p): gate_1 = np.matmul( np.matrix([[1, -1], [1, 1]]) / np.sqrt(2), gate_1) elif (gate_seq_1[i] == gates.Y2m): gate_1 = np.matmul( np.matrix([[1, 1], [-1, 1]]) / np.sqrt(2), gate_1) elif (gate_seq_1[i] == gates.Xp): gate_1 = np.matmul(np.matrix([[0, -1j], [-1j, 0]]), gate_1) elif (gate_seq_1[i] == gates.Xm): gate_1 = np.matmul(np.matrix([[0, 1j], [1j, 0]]), gate_1) elif (gate_seq_1[i] == gates.Yp): gate_1 = np.matmul(np.matrix([[0, -1], [1, 0]]), gate_1) elif (gate_seq_1[i] == gates.Ym): gate_1 = np.matmul(np.matrix([[0, 1], [-1, 0]]), gate_1) if (gate_seq_2[i] == gates.I): pass elif (gate_seq_2[i] == gates.X2p): gate_2 = np.matmul( np.matrix([[1, -1j], [-1j, 1]]) / np.sqrt(2), gate_2) elif (gate_seq_2[i] == gates.X2m): gate_2 = np.matmul( np.matrix([[1, 1j], [1j, 1]]) / np.sqrt(2), gate_2) elif (gate_seq_2[i] == gates.Y2p): gate_2 = np.matmul( np.matrix([[1, -1], [1, 1]]) / np.sqrt(2), gate_2) elif (gate_seq_2[i] == gates.Y2m): gate_2 = np.matmul( np.matrix([[1, 1], [-1, 1]]) / np.sqrt(2), gate_2) elif (gate_seq_2[i] == gates.Xp): gate_2 = np.matmul(np.matrix([[0, -1j], [-1j, 0]]), gate_2) elif (gate_seq_2[i] == gates.Xm): gate_2 = np.matmul(np.matrix([[0, 1j], [1j, 0]]), gate_2) elif (gate_seq_2[i] == gates.Yp): gate_2 = np.matmul(np.matrix([[0, -1], [1, 0]]), gate_2) elif (gate_seq_2[i] == gates.Ym): gate_2 = np.matmul(np.matrix([[0, 1], [-1, 0]]), gate_2) gate_12 = np.kron(gate_1, gate_2) if generator == 'CZ': if (gate_seq_1[i] == gates.CZ or gate_seq_2[i] == gates.CZ): gate_12 = np.matmul( np.matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]), gate_12) elif generator == 'iSWAP': if (gate_seq_1[i] == gates.iSWAP or gate_seq_2[i] == gates.iSWAP): gate_12 = np.matmul( np.matrix([[1, 0, 0, 0], [0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1]]), gate_12) twoQ_gate = np.matmul(gate_12, twoQ_gate) # log.info('two qubit gate: ' + str(twoQ_gate)) return twoQ_gate def get_recovery_gate(self, gate_seq_1, gate_seq_2, config, generator = 'CZ'): """ Get the recovery (the inverse) gate Parameters ---------- gate_seq_1: list of class Gate The gate sequence applied to Qubit "1" gate_seq_2: list of class Gate The gate sequence applied to Qubit "2" config: dict The configuration generator: string Type of Native 2QB gate (optional) Returns ------- (recovery_seq_1, recovery_seq_2): tuple of the lists The recovery gate """ qubit_state = np.matrix( '1; 0; 0; 0') # initial state: ground state |00> qubit_state = np.matmul(self.evaluate_sequence( gate_seq_1, gate_seq_2, generator = generator), qubit_state) # find recovery gate which makes qubit_state return to initial state total_num_cliffords = 11520 recovery_seq_1 = [] recovery_seq_2 = [] # Search the recovery gate in two Qubit clifford group find_cheapest = config['Find the cheapest recovery Clifford'] cheapest_recovery_seq_1 = [] cheapest_recovery_seq_2 = [] log.info('*** get recovery gate *** ') if (find_cheapest == True): min_N_2QB_gate = np.inf min_N_1QB_gate = np.inf max_N_I_gate = -np.inf cheapest_index = None use_lookup_table = config['Use a look-up table'] if (use_lookup_table == True): filepath_lookup_table = config['File path of the look-up table'] if len(filepath_lookup_table) == 0: if (generator == 'CZ'): filepath_lookup_table = os.path.join(path_currentdir, 'recovery_rb_table.pickle') elif (generator == 'iSWAP'): filepath_lookup_table = os.path.join(path_currentdir, 'recovery_rb_table_iSWAP.pickle') if filepath_lookup_table != self.filepath_lookup_table: log.info("Load Look-up table.") self.filepath_lookup_table = filepath_lookup_table self.dict_lookup_table = cliffords.loadData(filepath_lookup_table) stabilizer = cliffords.get_stabilizer(qubit_state) for index, item in enumerate(self.dict_lookup_table['psi_stabilizer']): if stabilizer == item: seq1 = self.dict_lookup_table['recovery_gates_QB1'][index] for str_Gate in seq1: cheapest_recovery_seq_1.append(cliffords.strGate_to_Gate(str_Gate)) seq2 = self.dict_lookup_table['recovery_gates_QB2'][index] for str_Gate in seq2: cheapest_recovery_seq_2.append(cliffords.strGate_to_Gate(str_Gate)) log.info("=== FOUND THE CHEAPEST RECOVERY GATE IN THE LOOK-UP TABLE. ===") log.info("QB1 recovery gate sequence: " + str(seq1)) log.info("QB2 recovery gate sequence: " + str(seq2)) log.info("=================================================") return(cheapest_recovery_seq_1, cheapest_recovery_seq_2) log.info("--- COULDN'T FIND THE RECOVERY GATE IN THE LOOK-UP TABLE... ---") # Calculate the matrix of the clifford sequence matrix_cliffords = self.evaluate_sequence(gate_seq_1,gate_seq_2, generator = generator) for i in range(total_num_cliffords): recovery_seq_1 = [] recovery_seq_2 = [] add_twoQ_clifford(i, recovery_seq_1, recovery_seq_2, generator = generator) # Calculate the matrix of the recovery clifford matrix_recovery = self.evaluate_sequence(recovery_seq_1, recovery_seq_2, generator = generator) # Calculate the matrix of the total clifford sequence matrix_total = np.matmul(matrix_recovery,matrix_cliffords) if (CheckIdentity(matrix_total)): if (find_cheapest == True): # Less 2QB Gates, Less 1QB Gates, and More I Gates = the cheapest gates. # The priority: less 2QB gates > less 1QB gates > more I gates N_2QB_gate = 0 N_1QB_gate = 0 N_I_gate = 0 # count the numbers of the gates for j in range(len(recovery_seq_1)): if (recovery_seq_1[j] == gates.CZ or recovery_seq_2[j] == gates.CZ): N_2QB_gate += 1 elif (recovery_seq_1[j] == gates.iSWAP or recovery_seq_2[j] == gates.iSWAP): N_2QB_gate += 1 else: N_1QB_gate += 2 if (recovery_seq_1[j] == gates.I): N_I_gate += 1 if (recovery_seq_2[j] == gates.I): N_I_gate += 1 if (N_2QB_gate <= min_N_2QB_gate): # if it has less 2QB gates, always update it min_N_2QB_gate, min_N_1QB_gate, max_N_I_gate, cheapest_index = (N_2QB_gate, N_1QB_gate, N_I_gate, j) if (N_1QB_gate <= min_N_1QB_gate): # *only if it has less 2QB gates*, check whether it has less 1QB gates min_N_2QB_gate, min_N_1QB_gate, max_N_I_gate, cheapest_index = (N_2QB_gate, N_1QB_gate, N_I_gate, j) if (N_I_gate >= max_N_I_gate): # *only if it has less 2QB gates & only if it has less 1QB gates*, check whether it has more I gates min_N_2QB_gate, min_N_1QB_gate, max_N_I_gate, cheapest_index = (N_2QB_gate, N_1QB_gate, N_I_gate, j) # check whether it is the cheapest # if it has less 2QB gates, always update it. if (N_2QB_gate < min_N_2QB_gate): min_N_2QB_gate, min_N_1QB_gate, max_N_I_gate, cheapest_index = (N_2QB_gate, N_1QB_gate, N_I_gate, j) log.info('the cheapest sequence update! [N_2QB_gate, N_1QB_gate, N_I_gate, seq. index] ' + str([min_N_2QB_gate, min_N_1QB_gate, max_N_I_gate, cheapest_index])) else: # if it has equal # of 2QB gates and less 1QB gates, update it. if (N_2QB_gate == min_N_2QB_gate and N_1QB_gate < min_N_1QB_gate): min_N_2QB_gate, min_N_1QB_gate, max_N_I_gate, cheapest_index = (N_2QB_gate, N_1QB_gate, N_I_gate, j) log.info('the cheapest sequence update! [N_2QB_gate, N_1QB_gate, N_I_gate, seq. index] ' + str([min_N_2QB_gate, min_N_1QB_gate, max_N_I_gate, cheapest_index])) else: # if it has equal # of 2QB & 1QB gates, and more 1QB gates, update it. if (N_2QB_gate == min_N_2QB_gate and N_1QB_gate == min_N_1QB_gate and N_I_gate >= max_N_I_gate): min_N_2QB_gate, min_N_1QB_gate, max_N_I_gate, cheapest_index = (N_2QB_gate, N_1QB_gate, N_I_gate, j) log.info('the cheapest sequence update! [N_2QB_gate, N_1QB_gate, N_I_gate, seq. index] ' + str([min_N_2QB_gate, min_N_1QB_gate, max_N_I_gate, cheapest_index])) else: return(recovery_seq_1,recovery_seq_2) if (find_cheapest == True): recovery_seq_1 = [] recovery_seq_2 = [] log.info('The index of the cheapest recovery clifford: %d'%(cheapest_index)) add_twoQ_clifford(cheapest_index, recovery_seq_1, recovery_seq_2, generator = generator) if (recovery_seq_1 == [] and recovery_seq_2 == []): recovery_seq_1 = [None] recovery_seq_2 = [None] return (recovery_seq_1, recovery_seq_2) if __name__ == '__main__': pass
[ "logging.getLogger", "numpy.sqrt", "os.path.exists", "numpy.matmul", "random.randint", "numpy.abs", "cliffords.strGate_to_Gate", "cliffords.loadData", "itertools.zip_longest", "numpy.kron", "numpy.set_printoptions", "os.makedirs", "os.path.join", "random.seed", "cliffords.get_stabilizer"...
[((177, 210), 'logging.getLogger', 'logging.getLogger', (['"""LabberDriver"""'], {}), "('LabberDriver')\n", (194, 210), False, 'import logging\n'), ((256, 282), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (272, 282), False, 'import os\n'), ((12591, 12610), 'random.seed', 'rnd.seed', (['randomize'], {}), '(randomize)\n', (12599, 12610), True, 'import random as rnd\n'), ((16645, 16672), 'numpy.matrix', 'np.matrix', (['[[1, 0], [0, 1]]'], {}), '([[1, 0], [0, 1]])\n', (16654, 16672), True, 'import numpy as np\n'), ((18582, 18599), 'numpy.matrix', 'np.matrix', (['"""1; 0"""'], {}), "('1; 0')\n", (18591, 18599), True, 'import numpy as np\n'), ((21531, 21550), 'random.seed', 'rnd.seed', (['randomize'], {}), '(randomize)\n', (21539, 21550), True, 'import random as rnd\n'), ((29953, 30020), 'numpy.matrix', 'np.matrix', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n', (29962, 30020), True, 'import numpy as np\n'), ((33923, 33946), 'numpy.matrix', 'np.matrix', (['"""1; 0; 0; 0"""'], {}), "('1; 0; 0; 0')\n", (33932, 33946), True, 'import numpy as np\n'), ((807, 846), 'numpy.abs', 'np.abs', (['(matrix[1, 1] / matrix[0, 0] - 1)'], {}), '(matrix[1, 1] / matrix[0, 0] - 1)\n', (813, 846), True, 'import numpy as np\n'), ((860, 899), 'numpy.abs', 'np.abs', (['(matrix[2, 2] / matrix[0, 0] - 1)'], {}), '(matrix[2, 2] / matrix[0, 0] - 1)\n', (866, 899), True, 'import numpy as np\n'), ((913, 952), 'numpy.abs', 'np.abs', (['(matrix[3, 3] / matrix[0, 0] - 1)'], {}), '(matrix[3, 3] / matrix[0, 0] - 1)\n', (919, 952), True, 'import numpy as np\n'), ((26057, 26080), 'numpy.matrix', 'np.matrix', (['"""1; 0; 0; 0"""'], {}), "('1; 0; 0; 0')\n", (26066, 26080), True, 'import numpy as np\n'), ((27654, 27686), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (27673, 27686), True, 'import numpy as np\n'), ((30096, 30123), 'numpy.matrix', 'np.matrix', (['[[1, 0], [0, 1]]'], {}), '([[1, 0], [0, 1]])\n', (30105, 30123), True, 'import numpy as np\n'), ((30145, 30172), 'numpy.matrix', 'np.matrix', (['[[1, 0], [0, 1]]'], {}), '([[1, 0], [0, 1]])\n', (30154, 30172), True, 'import numpy as np\n'), ((32525, 32548), 'numpy.kron', 'np.kron', (['gate_1', 'gate_2'], {}), '(gate_1, gate_2)\n', (32532, 32548), True, 'import numpy as np\n'), ((33166, 33195), 'numpy.matmul', 'np.matmul', (['gate_12', 'twoQ_gate'], {}), '(gate_12, twoQ_gate)\n', (33175, 33195), True, 'import numpy as np\n'), ((37354, 37398), 'numpy.matmul', 'np.matmul', (['matrix_recovery', 'matrix_cliffords'], {}), '(matrix_recovery, matrix_cliffords)\n', (37363, 37398), True, 'import numpy as np\n'), ((22601, 22622), 'random.randint', 'rnd.randint', (['(0)', '(11519)'], {}), '(0, 11519)\n', (22612, 22622), True, 'import random as rnd\n'), ((26235, 26277), 'os.path.join', 'os.path.join', (['path_currentdir', '"""2QB_RBseq"""'], {}), "(path_currentdir, '2QB_RBseq')\n", (26247, 26277), False, 'import os\n'), ((26670, 26703), 'os.path.join', 'os.path.join', (['directory', 'filename'], {}), '(directory, filename)\n', (26682, 26703), False, 'import os\n'), ((35610, 35647), 'cliffords.get_stabilizer', 'cliffords.get_stabilizer', (['qubit_state'], {}), '(qubit_state)\n', (35634, 35647), False, 'import cliffords\n'), ((614, 634), 'numpy.abs', 'np.abs', (['matrix[0, 0]'], {}), '(matrix[0, 0])\n', (620, 634), True, 'import numpy as np\n'), ((664, 684), 'numpy.abs', 'np.abs', (['matrix[1, 1]'], {}), '(matrix[1, 1])\n', (670, 684), True, 'import numpy as np\n'), ((714, 734), 'numpy.abs', 'np.abs', (['matrix[2, 2]'], {}), '(matrix[2, 2])\n', (720, 734), True, 'import numpy as np\n'), ((764, 784), 'numpy.abs', 'np.abs', (['matrix[3, 3]'], {}), '(matrix[3, 3])\n', (770, 784), True, 'import numpy as np\n'), ((13647, 13665), 'random.randint', 'rnd.randint', (['(0)', '(23)'], {}), '(0, 23)\n', (13658, 13665), True, 'import random as rnd\n'), ((14558, 14600), 'os.path.join', 'os.path.join', (['path_currentdir', '"""1QB_RBseq"""'], {}), "(path_currentdir, '1QB_RBseq')\n", (14570, 14600), False, 'import os\n'), ((14883, 14916), 'os.path.join', 'os.path.join', (['directory', 'filename'], {}), '(directory, filename)\n', (14895, 14916), False, 'import os\n'), ((15858, 15924), 'itertools.zip_longest', 'itertools.zip_longest', (['*multi_gate_seq_reversed'], {'fillvalue': 'gates.I'}), '(*multi_gate_seq_reversed, fillvalue=gates.I)\n', (15879, 15924), False, 'import itertools\n'), ((26300, 26325), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (26314, 26325), False, 'import os\n'), ((26347, 26369), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (26358, 26369), False, 'import os\n'), ((28654, 28711), 'itertools.zip_longest', 'itertools.zip_longest', (['*multi_gate_seq'], {'fillvalue': 'gates.I'}), '(*multi_gate_seq, fillvalue=gates.I)\n', (28675, 28711), False, 'import itertools\n'), ((35539, 35580), 'cliffords.loadData', 'cliffords.loadData', (['filepath_lookup_table'], {}), '(filepath_lookup_table)\n', (35557, 35580), False, 'import cliffords\n'), ((14627, 14652), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (14641, 14652), False, 'import os\n'), ((14678, 14700), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (14689, 14700), False, 'import os\n'), ((28075, 28092), 'numpy.abs', 'np.abs', (['psi[0, 0]'], {}), '(psi[0, 0])\n', (28081, 28092), True, 'import numpy as np\n'), ((32725, 32793), 'numpy.matrix', 'np.matrix', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]])\n', (32734, 32793), True, 'import numpy as np\n'), ((35059, 35116), 'os.path.join', 'os.path.join', (['path_currentdir', '"""recovery_rb_table.pickle"""'], {}), "(path_currentdir, 'recovery_rb_table.pickle')\n", (35071, 35116), False, 'import os\n'), ((16881, 16916), 'numpy.matrix', 'np.matrix', (['[[1, -1.0j], [-1.0j, 1]]'], {}), '([[1, -1.0j], [-1.0j, 1]])\n', (16890, 16916), True, 'import numpy as np\n'), ((16915, 16925), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (16922, 16925), True, 'import numpy as np\n'), ((30340, 30375), 'numpy.matrix', 'np.matrix', (['[[1, -1.0j], [-1.0j, 1]]'], {}), '([[1, -1.0j], [-1.0j, 1]])\n', (30349, 30375), True, 'import numpy as np\n'), ((30374, 30384), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (30381, 30384), True, 'import numpy as np\n'), ((31505, 31540), 'numpy.matrix', 'np.matrix', (['[[1, -1.0j], [-1.0j, 1]]'], {}), '([[1, -1.0j], [-1.0j, 1]])\n', (31514, 31540), True, 'import numpy as np\n'), ((31539, 31549), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (31546, 31549), True, 'import numpy as np\n'), ((33026, 33099), 'numpy.matrix', 'np.matrix', (['[[1, 0, 0, 0], [0, 0, 1.0j, 0], [0, 1.0j, 0, 0], [0, 0, 0, 1]]'], {}), '([[1, 0, 0, 0], [0, 0, 1.0j, 0], [0, 1.0j, 0, 0], [0, 0, 0, 1]])\n', (33035, 33099), True, 'import numpy as np\n'), ((35214, 35277), 'os.path.join', 'os.path.join', (['path_currentdir', '"""recovery_rb_table_iSWAP.pickle"""'], {}), "(path_currentdir, 'recovery_rb_table_iSWAP.pickle')\n", (35226, 35277), False, 'import os\n'), ((17048, 17081), 'numpy.matrix', 'np.matrix', (['[[1, 1.0j], [1.0j, 1]]'], {}), '([[1, 1.0j], [1.0j, 1]])\n', (17057, 17081), True, 'import numpy as np\n'), ((17080, 17090), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (17087, 17090), True, 'import numpy as np\n'), ((26397, 26411), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (26409, 26411), False, 'from datetime import datetime\n'), ((27959, 27973), 'numpy.matrix', 'np.matrix', (['psi'], {}), '(psi)\n', (27968, 27973), True, 'import numpy as np\n'), ((30497, 30530), 'numpy.matrix', 'np.matrix', (['[[1, 1.0j], [1.0j, 1]]'], {}), '([[1, 1.0j], [1.0j, 1]])\n', (30506, 30530), True, 'import numpy as np\n'), ((30529, 30539), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (30536, 30539), True, 'import numpy as np\n'), ((31662, 31695), 'numpy.matrix', 'np.matrix', (['[[1, 1.0j], [1.0j, 1]]'], {}), '([[1, 1.0j], [1.0j, 1]])\n', (31671, 31695), True, 'import numpy as np\n'), ((31694, 31704), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (31701, 31704), True, 'import numpy as np\n'), ((35967, 36002), 'cliffords.strGate_to_Gate', 'cliffords.strGate_to_Gate', (['str_Gate'], {}), '(str_Gate)\n', (35992, 36002), False, 'import cliffords\n'), ((36192, 36227), 'cliffords.strGate_to_Gate', 'cliffords.strGate_to_Gate', (['str_Gate'], {}), '(str_Gate)\n', (36217, 36227), False, 'import cliffords\n'), ((14732, 14746), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (14744, 14746), False, 'from datetime import datetime\n'), ((15409, 15449), 'cliffords.Gate_to_strGate', 'cliffords.Gate_to_strGate', (['recovery_gate'], {}), '(recovery_gate)\n', (15434, 15449), False, 'import cliffords\n'), ((17213, 17241), 'numpy.matrix', 'np.matrix', (['[[1, -1], [1, 1]]'], {}), '([[1, -1], [1, 1]])\n', (17222, 17241), True, 'import numpy as np\n'), ((17244, 17254), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (17251, 17254), True, 'import numpy as np\n'), ((27023, 27061), 'cliffords.Gate_to_strGate', 'cliffords.Gate_to_strGate', (['gateSeq2[i]'], {}), '(gateSeq2[i])\n', (27048, 27061), False, 'import cliffords\n'), ((27257, 27299), 'cliffords.Gate_to_strGate', 'cliffords.Gate_to_strGate', (['cliffordSeq2[i]'], {}), '(cliffordSeq2[i])\n', (27282, 27299), False, 'import cliffords\n'), ((27495, 27537), 'cliffords.Gate_to_strGate', 'cliffords.Gate_to_strGate', (['recoverySeq2[i]'], {}), '(recoverySeq2[i])\n', (27520, 27537), False, 'import cliffords\n'), ((30652, 30680), 'numpy.matrix', 'np.matrix', (['[[1, -1], [1, 1]]'], {}), '([[1, -1], [1, 1]])\n', (30661, 30680), True, 'import numpy as np\n'), ((30683, 30693), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (30690, 30693), True, 'import numpy as np\n'), ((31817, 31845), 'numpy.matrix', 'np.matrix', (['[[1, -1], [1, 1]]'], {}), '([[1, -1], [1, 1]])\n', (31826, 31845), True, 'import numpy as np\n'), ((31848, 31858), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (31855, 31858), True, 'import numpy as np\n'), ((15224, 15269), 'cliffords.Gate_to_strGate', 'cliffords.Gate_to_strGate', (['single_gate_seq[i]'], {}), '(single_gate_seq[i])\n', (15249, 15269), False, 'import cliffords\n'), ((17377, 17405), 'numpy.matrix', 'np.matrix', (['[[1, 1], [-1, 1]]'], {}), '([[1, 1], [-1, 1]])\n', (17386, 17405), True, 'import numpy as np\n'), ((17408, 17418), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (17415, 17418), True, 'import numpy as np\n'), ((17540, 17575), 'numpy.matrix', 'np.matrix', (['[[0, -1.0j], [-1.0j, 0]]'], {}), '([[0, -1.0j], [-1.0j, 0]])\n', (17549, 17575), True, 'import numpy as np\n'), ((30806, 30834), 'numpy.matrix', 'np.matrix', (['[[1, 1], [-1, 1]]'], {}), '([[1, 1], [-1, 1]])\n', (30815, 30834), True, 'import numpy as np\n'), ((30837, 30847), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (30844, 30847), True, 'import numpy as np\n'), ((30938, 30973), 'numpy.matrix', 'np.matrix', (['[[0, -1.0j], [-1.0j, 0]]'], {}), '([[0, -1.0j], [-1.0j, 0]])\n', (30947, 30973), True, 'import numpy as np\n'), ((31971, 31999), 'numpy.matrix', 'np.matrix', (['[[1, 1], [-1, 1]]'], {}), '([[1, 1], [-1, 1]])\n', (31980, 31999), True, 'import numpy as np\n'), ((32002, 32012), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (32009, 32012), True, 'import numpy as np\n'), ((32103, 32138), 'numpy.matrix', 'np.matrix', (['[[0, -1.0j], [-1.0j, 0]]'], {}), '([[0, -1.0j], [-1.0j, 0]])\n', (32112, 32138), True, 'import numpy as np\n'), ((17693, 17726), 'numpy.matrix', 'np.matrix', (['[[0, 1.0j], [1.0j, 0]]'], {}), '([[0, 1.0j], [1.0j, 0]])\n', (17702, 17726), True, 'import numpy as np\n'), ((26975, 27013), 'cliffords.Gate_to_strGate', 'cliffords.Gate_to_strGate', (['gateSeq1[i]'], {}), '(gateSeq1[i])\n', (27000, 27013), False, 'import cliffords\n'), ((27205, 27247), 'cliffords.Gate_to_strGate', 'cliffords.Gate_to_strGate', (['cliffordSeq1[i]'], {}), '(cliffordSeq1[i])\n', (27230, 27247), False, 'import cliffords\n'), ((27443, 27485), 'cliffords.Gate_to_strGate', 'cliffords.Gate_to_strGate', (['recoverySeq1[i]'], {}), '(recoverySeq1[i])\n', (27468, 27485), False, 'import cliffords\n'), ((31060, 31093), 'numpy.matrix', 'np.matrix', (['[[0, 1.0j], [1.0j, 0]]'], {}), '([[0, 1.0j], [1.0j, 0]])\n', (31069, 31093), True, 'import numpy as np\n'), ((32225, 32258), 'numpy.matrix', 'np.matrix', (['[[0, 1.0j], [1.0j, 0]]'], {}), '([[0, 1.0j], [1.0j, 0]])\n', (32234, 32258), True, 'import numpy as np\n'), ((17844, 17872), 'numpy.matrix', 'np.matrix', (['[[0, -1], [1, 0]]'], {}), '([[0, -1], [1, 0]])\n', (17853, 17872), True, 'import numpy as np\n'), ((31180, 31208), 'numpy.matrix', 'np.matrix', (['[[0, -1], [1, 0]]'], {}), '([[0, -1], [1, 0]])\n', (31189, 31208), True, 'import numpy as np\n'), ((32345, 32373), 'numpy.matrix', 'np.matrix', (['[[0, -1], [1, 0]]'], {}), '([[0, -1], [1, 0]])\n', (32354, 32373), True, 'import numpy as np\n'), ((17994, 18022), 'numpy.matrix', 'np.matrix', (['[[0, 1], [-1, 0]]'], {}), '([[0, 1], [-1, 0]])\n', (18003, 18022), True, 'import numpy as np\n'), ((31299, 31327), 'numpy.matrix', 'np.matrix', (['[[0, 1], [-1, 0]]'], {}), '([[0, 1], [-1, 0]])\n', (31308, 31327), True, 'import numpy as np\n'), ((32464, 32492), 'numpy.matrix', 'np.matrix', (['[[0, 1], [-1, 0]]'], {}), '([[0, 1], [-1, 0]])\n', (32473, 32492), True, 'import numpy as np\n'), ((18157, 18191), 'numpy.matrix', 'np.matrix', (['[[-1.0j, 0], [0, 1.0j]]'], {}), '([[-1.0j, 0], [0, 1.0j]])\n', (18166, 18191), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint from matplotlib.animation import FuncAnimation from functools import partial #system def kuramoto(theta, t, A, N): difference_matrix = np.column_stack([theta - theta[k] for k in range(N)]) theta_prime = np.array([np.dot(A[:, k], difference_matrix[:, k]) for k in range(N)]) return 0.7*theta_prime #initialize window for blitting def init(fig, axes, scatter, N, points_map, A): plt.xlim([-1.5, 1.5]) plt.ylim([-1.5, 1.5]) plt.grid(False) plt.axis("off") #axes.patch.set_facecolor("black") #we draw the line connecting vertices once for i in range(N): curr = points_map[i] row = A[i] for j, connected in enumerate(row): if connected: conn_point = points_map[j] plt.plot([curr[0], conn_point[0]], [curr[1], conn_point[1]], color="black", markersize=1.0) return scatter, #animates one frame def animate(t, sols, scatter): print(t) scatter.set_array((sols[t] - 0.03*t) % 2*np.pi) return scatter, #point generation N = 20 axis = np.linspace(0.0, 2*np.pi, N+1)[0 : N] points = np.column_stack([np.cos(axis), np.sin(axis)]) points_map = dict(zip(range(N), zip(points[:, 0], points[:, 1]))) #connecting vertices np.random.seed(1000) rand = np.random.rand(N, N) A = np.zeros((N, N)) for i in range(N): for j in range(i, N): if rand[i, j] > 0.75: A[i, j], A[j, i] = 1, 1 #solving total = 5.0 delta = 0.01 M = int(total/delta) t = np.linspace(0.0, total, M) sols = odeint(kuramoto, axis, t, args=tuple([A, N])) #setup fig, axes = plt.figure(), plt.axes(frameon=True) scatter = plt.scatter(points[:, 0], points[:, 1], animated=True, c=axis, vmin=0.0, vmax=2*np.pi, cmap="rainbow", s=100) anim = FuncAnimation(fig, func=animate, frames=M, init_func=partial(init, fig, axes, scatter, N, points_map, A), blit=True, fargs=(sols, scatter), repeat=False) anim.save("out.mp4", fps=40)
[ "numpy.dot", "matplotlib.pyplot.grid", "numpy.random.rand", "numpy.sin", "matplotlib.pyplot.plot", "matplotlib.pyplot.axis", "numpy.linspace", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.random.seed", "matplotlib.pyplot.scatter", "matplotlib.pyplot.axes", "numpy.cos", "matplotlib.pyp...
[((1329, 1349), 'numpy.random.seed', 'np.random.seed', (['(1000)'], {}), '(1000)\n', (1343, 1349), True, 'import numpy as np\n'), ((1357, 1377), 'numpy.random.rand', 'np.random.rand', (['N', 'N'], {}), '(N, N)\n', (1371, 1377), True, 'import numpy as np\n'), ((1382, 1398), 'numpy.zeros', 'np.zeros', (['(N, N)'], {}), '((N, N))\n', (1390, 1398), True, 'import numpy as np\n'), ((1570, 1596), 'numpy.linspace', 'np.linspace', (['(0.0)', 'total', 'M'], {}), '(0.0, total, M)\n', (1581, 1596), True, 'import numpy as np\n'), ((1717, 1832), 'matplotlib.pyplot.scatter', 'plt.scatter', (['points[:, 0]', 'points[:, 1]'], {'animated': '(True)', 'c': 'axis', 'vmin': '(0.0)', 'vmax': '(2 * np.pi)', 'cmap': '"""rainbow"""', 's': '(100)'}), "(points[:, 0], points[:, 1], animated=True, c=axis, vmin=0.0,\n vmax=2 * np.pi, cmap='rainbow', s=100)\n", (1728, 1832), True, 'import matplotlib.pyplot as plt\n'), ((481, 502), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[-1.5, 1.5]'], {}), '([-1.5, 1.5])\n', (489, 502), True, 'import matplotlib.pyplot as plt\n'), ((507, 528), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-1.5, 1.5]'], {}), '([-1.5, 1.5])\n', (515, 528), True, 'import matplotlib.pyplot as plt\n'), ((533, 548), 'matplotlib.pyplot.grid', 'plt.grid', (['(False)'], {}), '(False)\n', (541, 548), True, 'import matplotlib.pyplot as plt\n'), ((553, 568), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (561, 568), True, 'import matplotlib.pyplot as plt\n'), ((1148, 1182), 'numpy.linspace', 'np.linspace', (['(0.0)', '(2 * np.pi)', '(N + 1)'], {}), '(0.0, 2 * np.pi, N + 1)\n', (1159, 1182), True, 'import numpy as np\n'), ((1670, 1682), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1680, 1682), True, 'import matplotlib.pyplot as plt\n'), ((1684, 1706), 'matplotlib.pyplot.axes', 'plt.axes', ([], {'frameon': '(True)'}), '(frameon=True)\n', (1692, 1706), True, 'import matplotlib.pyplot as plt\n'), ((1212, 1224), 'numpy.cos', 'np.cos', (['axis'], {}), '(axis)\n', (1218, 1224), True, 'import numpy as np\n'), ((1226, 1238), 'numpy.sin', 'np.sin', (['axis'], {}), '(axis)\n', (1232, 1238), True, 'import numpy as np\n'), ((1887, 1938), 'functools.partial', 'partial', (['init', 'fig', 'axes', 'scatter', 'N', 'points_map', 'A'], {}), '(init, fig, axes, scatter, N, points_map, A)\n', (1894, 1938), False, 'from functools import partial\n'), ((308, 348), 'numpy.dot', 'np.dot', (['A[:, k]', 'difference_matrix[:, k]'], {}), '(A[:, k], difference_matrix[:, k])\n', (314, 348), True, 'import numpy as np\n'), ((856, 951), 'matplotlib.pyplot.plot', 'plt.plot', (['[curr[0], conn_point[0]]', '[curr[1], conn_point[1]]'], {'color': '"""black"""', 'markersize': '(1.0)'}), "([curr[0], conn_point[0]], [curr[1], conn_point[1]], color='black',\n markersize=1.0)\n", (864, 951), True, 'import matplotlib.pyplot as plt\n')]
import numpy as np from matplotlib import pyplot as plt from time import time as t def sieve(n): prime = np.array([True for i in range(n+1)]) p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 numbers = {i for i in range(n+1) if prime[i]} numbers.remove(0) return numbers def build_prime_grid(size, primes): grid = np.zeros([size, size], dtype=int) number = 0 for y in range(size): for x in range(size): if number in primes: grid[y, x] = 1 primes.remove(number) else: grid[y, x] = 0 number += 1 return grid def build_spiral(size, primes): grid = np.zeros([size, size], dtype=int) center = (size // 2, size // 2) y, x = center grid[center]= -1 x += 1 number = 1 direction = 'right' not_in_the_box = False while not not_in_the_box: try: if number in primes: grid[y, x] = 1 primes.remove(number) else: grid[y, x] = -1 number += 1 if direction == 'down': y += 1 if grid[y, x+1] == 0: direction = 'reset' if direction == 'left': x -= 1 if grid[y+1, x] == 0: direction = 'down' if direction == 'up': y -= 1 if grid[y, x-1] == 0: direction = 'left' if direction == 'right': x += 1 if grid[y-1, x] == 0: direction = 'up' if direction == 'reset': direction = 'right' except(IndexError): not_in_the_box = True return grid t0 = t() grid_size = 50001 primes = sieve(grid_size*grid_size) prime_grid = build_prime_grid(grid_size, primes) runtime = t() - t0 print('runtime : ' + str(runtime)) plt.imsave(f'./pg_tests/pg{grid_size}.pdf', prime_grid)
[ "matplotlib.pyplot.imsave", "time.time", "numpy.zeros" ]
[((2118, 2121), 'time.time', 't', ([], {}), '()\n', (2119, 2121), True, 'from time import time as t\n'), ((2288, 2343), 'matplotlib.pyplot.imsave', 'plt.imsave', (['f"""./pg_tests/pg{grid_size}.pdf"""', 'prime_grid'], {}), "(f'./pg_tests/pg{grid_size}.pdf', prime_grid)\n", (2298, 2343), True, 'from matplotlib import pyplot as plt\n'), ((489, 522), 'numpy.zeros', 'np.zeros', (['[size, size]'], {'dtype': 'int'}), '([size, size], dtype=int)\n', (497, 522), True, 'import numpy as np\n'), ((864, 897), 'numpy.zeros', 'np.zeros', (['[size, size]'], {'dtype': 'int'}), '([size, size], dtype=int)\n', (872, 897), True, 'import numpy as np\n'), ((2239, 2242), 'time.time', 't', ([], {}), '()\n', (2240, 2242), True, 'from time import time as t\n')]
import unittest import os from os.path import exists, join import numpy as np from test_helper import TESTDIR, TESTDATA, TMPDATA import datetime from copy import copy import warnings from karta.vector import shp, read_shapefile from karta.vector.geometry import (Point, Line, Polygon, Multipoint, Multiline, Multipolygon) from karta.crs import LonLatWGS84 class TestShapefile(unittest.TestCase): def setUp(self): self.points = [Point((1, 1), properties={"species": "T. officianale"}, crs=LonLatWGS84), Point((3, 1), properties={"species": "C. tectorum"}, crs=LonLatWGS84), Point((4, 3), properties={"species": "M. alba"}, crs=LonLatWGS84), Point((2, 2), properties={"species": "V. cracca"}, crs=LonLatWGS84)] self.multipoint = Multipoint([(1,1), (3,1), (4,3), (2,2)], data={"species": ["T. officianale", "C. tectorum", "M. alba", "V. cracca"]}, crs=LonLatWGS84) self.line = Line([(1.0,5.0),(5.0,5.0),(5.0,1.0),(3.0,3.0),(1.0,1.0)], properties={"geom_id": 27, "name": "test line"}, crs=LonLatWGS84) self.polygon = Polygon([(1.0,5.0),(5.0,5.0),(5.0,1.0),(3.0,3.0),(1.0,1.0)], crs=LonLatWGS84) self.points3 = [Point((1, 1, 0), crs=LonLatWGS84), Point((3, 1, 3), crs=LonLatWGS84), Point((4, 3, 2), crs=LonLatWGS84), Point((2, 2, -1), crs=LonLatWGS84)] self.line3 = Line([(1,5,2),(5,5,-1),(5,1,3),(3,3,1),(1,1,0)], crs=LonLatWGS84) self.polygon3 = Polygon([(1,5,2),(5,5,-1),(5,1,3),(3,3,1),(1,1,0)], crs=LonLatWGS84) testfiles = ["points.shp", "line.shp", "polygon.shp"] if any(not exists(join(TMPDATA, "shapefiles/", fnm)) for fnm in testfiles): self.saveTestData() def saveTestData(self): testfiles = [(self.multipoint, "points"), (self.line, "line"), (self.polygon, "polygon")] if not os.path.isdir(os.path.join(TMPDATA, "shapefiles")): os.makedirs(os.path.join(TMPDATA, "shapefiles")) for (geom, fnm) in testfiles: geom.to_shapefile(os.path.join(TMPDATA, "shapefiles", fnm)) def test_write_point(self): point = self.points[0] point.to_shapefile(os.path.join(TESTDIR, "data/point")) for fnm in ("point.shx", "point.shx", "point.dbf", "point.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) def test_write_points(self): points = self.points shp.write_shapefile(os.path.join(TESTDIR, "data/points.shp"), *points) for fnm in ("points.shx", "points.shx", "points.dbf", "points.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) def test_write_line(self): self.line.to_shapefile(os.path.join(TESTDIR, "data/line")) for fnm in ("line.shx", "line.shx", "line.dbf", "line.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) def test_write_poly(self): self.polygon.to_shapefile(os.path.join(TESTDIR, "data/polygon")) for fnm in ("polygon.shx", "polygon.shx", "polygon.dbf", "polygon.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) def test_write_points3(self): mp = Multipoint(self.points3) mp.to_shapefile(os.path.join(TESTDIR, "data/multipointz")) for fnm in ("multipointz.shx", "multipointz.shx", "multipointz.dbf", "multipointz.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) def test_write_line3(self): self.line3.to_shapefile(os.path.join(TESTDIR, "data/linez")) for fnm in ("linez.shx", "linez.shx", "linez.dbf", "linez.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) def test_write_poly3(self): self.polygon3.to_shapefile(os.path.join(TESTDIR, "data/polygonz")) for fnm in ("polygonz.shx", "polygonz.shx", "polygonz.dbf", "polygonz.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) def test_write_multipoint(self): mp = Multipoint(self.points) mp.to_shapefile(os.path.join(TESTDIR, "data/multipoint")) for fnm in ("multipoint.shx", "multipoint.shx", "multipoint.dbf", "multipoint.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) def test_write_multiline(self): g = Multiline([[(0,0), (1,1), (2,2)], [(1,0), (2,1), (3,2)], [(2,0), (1,1), (0,2)]], crs=LonLatWGS84) g.to_shapefile(os.path.join(TESTDIR, "data/multiline")) for fnm in ("multiline.shx", "multiline.shx", "multiline.dbf", "multiline.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) def test_write_multipolygon(self): g = Multipolygon([[[(0,0), (2,2), (1,3)]], [[(2,0), (4,2), (3,3)]], [[(2,-2), (1,0), (-1,-1)]]], crs=LonLatWGS84) g.to_shapefile(os.path.join(TESTDIR, "data/multipoly")) for fnm in ("multipoly.shx", "multipoly.shx", "multipoly.dbf", "multipoly.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) def test_write_collection_multipoint(self): mp = Multipoint(self.points) mp0 = copy(mp) mp1 = copy(mp.shift((4, 2))) mp2 = copy(mp.shift((-2, 3))) shp.write_shapefile(os.path.join(TESTDIR, "data/mp_collection.shp"), mp0, mp1, mp2) for fnm in ("mp_collection.shx", "mp_collection.shx", "mp_collection.dbf", "mp_collection.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) def test_write_collection_lines(self): line0 = copy(self.line) line1 = copy(self.line.shift((4, 2))) line2 = copy(self.line.shift((-2, 3))) shp.write_shapefile(os.path.join(TESTDIR, "data/line_collection.shp"), line0, line1, line2) for fnm in ("line_collection.shx", "line_collection.shx", "line_collection.dbf", "line_collection.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) def test_read_points(self): points = read_shapefile(os.path.join(TESTDATA, "shapefile", "points")) self.assertEqual(len(points), 4) pt = points[0] self.assertTrue("+proj=lonlat" in pt.crs.get_proj4()) self.assertTrue("+a=6378137.0" in pt.crs.get_proj4()) self.assertTrue("+f=0.00335281" in pt.crs.get_proj4()) mp = Multipoint(points) self.assertEqual(mp.d["species"], ['T. officianale', 'C. tectorum', 'M. alba', 'V. cracca']) self.assertEqual(mp.d["ID"], ['0', '1', '2', '3']) x, y = mp.coords() self.assertTrue(np.all(x == np.array((1.0, 3.0, 4.0, 2.0)))) self.assertTrue(np.all(y == np.array((1.0, 1.0, 3.0, 2.0)))) def test_read_line(self): line = read_shapefile(os.path.join(TESTDATA, "shapefile", "line"))[0] self.assertTrue("+proj=lonlat" in line.crs.get_proj4()) self.assertTrue("+a=6378137.0" in line.crs.get_proj4()) self.assertTrue("+f=0.00335281" in line.crs.get_proj4()) x, y = line.coords() self.assertTrue(np.all(x == np.array([1.0, 5.0, 5.0, 3.0, 1.0]))) self.assertTrue(np.all(y == np.array([5.0, 5.0, 1.0, 3.0, 1.0]))) def test_read_polygon(self): polygon = read_shapefile(os.path.join(TESTDATA, "shapefile", "polygon"))[0] self.assertTrue("+proj=lonlat" in polygon.crs.get_proj4()) self.assertTrue("+a=6378137.0" in polygon.crs.get_proj4()) self.assertTrue("+f=0.00335281" in polygon.crs.get_proj4()) x, y = polygon.coords() self.assertTrue(np.all(x == np.array([1.0, 5.0, 5.0, 3.0, 1.0]))) self.assertTrue(np.all(y == np.array([5.0, 5.0, 1.0, 3.0, 1.0]))) def test_read_points_newp(self): # Read a multipoint with a projected cooridnate system newp = read_shapefile(os.path.join(TESTDATA, "shapefile", "newp_nsidc_north")) proj4 = ('+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 ' '+y_0=0 +a=6378273 +b=6356889.449 +units=m +no_defs') for part in proj4.split(): self.assertTrue(part[:8] in newp[0].crs.get_proj4()) coords = list(zip(*[pt.vertex()[:2] for pt in newp])) self.assertEqual(coords, [(521236.8297444395, 521236.8297444395, 521236.8297444395, 547490.4452879033, 547490.4452879033, 547490.4452879033, 587584.1578033275, 587584.1578033275, 587584.1578033275, 571828.4918982167, 571828.4918982167), (-888853.1384770898, -888853.1384770898, -888853.1384770898, -902049.3617542256, -902049.3617542256, -902049.3617542256, -871214.0673764511, -871214.0673764511, -871214.0673764511, -850080.914674058, -850080.914674058)]) meterno = [pt.properties["meterno"] for pt in newp] self.assertEqual(meterno, ['IMS1/1', 'IMS2/1', '5952/2', 'IMS4/1', '5953/2', '1963/13', 'IMS5/1', '5213/A', '2121/13', 'IMS3/1', '3613/2']) depth = [pt.properties["depth_m"] for pt in newp] self.assertEqual(depth, ['73', '143', '247', '86', '147', '250', '74', '142', '235', '150', '248']) class ShapefileAttributeTests(unittest.TestCase): def test_infer_ogr_fieldtype(self): self.assertEqual(shp.ogr_get_fieldtype(1), (0, 32)) self.assertEqual(shp.ogr_get_fieldtype([1, 2]), (1, 1000)) self.assertEqual(shp.ogr_get_fieldtype(1.0), (2, 32)) self.assertEqual(shp.ogr_get_fieldtype([1.0, 1.5]), (3, 1000)) # everything should be interpretted as WideString self.assertEqual(shp.ogr_get_fieldtype("hello"), (4, 180)) self.assertEqual(shp.ogr_get_fieldtype(["list","of","strings"]),(5, 1000)) # doesn't work on Python 2 #self.assertEqual(shp.ogr_get_fieldtype(b'0b110001'), 8) # dates self.assertEqual(shp.ogr_get_fieldtype(datetime.date(2013, 11, 17)), (9, 32)) self.assertEqual(shp.ogr_get_fieldtype(datetime.time(8, 30, 0)), (10, 32)) self.assertEqual(shp.ogr_get_fieldtype(datetime.datetime(2013, 11, 17, 8, 30, 0)), (11, 64)) def test_long_attribute_names(self): line = Line([(1.0,5.0),(5.0,5.0),(5.0,1.0),(3.0,3.0),(1.0,1.0)], properties={ "geom_id": 27, "name": "test line", "description": "line for testing", "description_en": "Line for testing." }, crs=LonLatWGS84) with warnings.catch_warnings(): warnings.simplefilter("ignore") line.to_shapefile(os.path.join(TESTDIR, "data/line_truncated_attr")) for fnm in ("line_truncated_attr.shx", "line_truncated_attr.shx", "line_truncated_attr.dbf", "line_truncated_attr.prj"): self.assertTrue(os.path.isfile(os.path.join(TESTDIR, "data", fnm))) line2 = read_shapefile(os.path.join(TESTDIR, "data", "line_truncated_attr"))[0] self.assertTrue("DESCRIPTIO" in line2.properties) self.assertTrue("DESCRIPTI2" in line2.properties) self.assertTrue("GEOM_ID" in line2.properties) self.assertTrue("NAME" in line2.properties) class ShapelibTestSuite(unittest.TestCase): """ Open and verify the shapefiles provided with the shapelib testsuite. """ def setUp(self): self.dirname = os.path.join(TESTDATA, "shapefile", "shapelib") def test_(self): res = read_shapefile(os.path.join(self.dirname, "test.shp")) def test_0(self): res = read_shapefile(os.path.join(self.dirname, "test0.shp")) def test_1(self): res = read_shapefile(os.path.join(self.dirname, "test1.shp")) self.assertEqual(type(res[0]), Point) self.assertEqual(len(res), 2) def test_2(self): res = read_shapefile(os.path.join(self.dirname, "test2.shp")) self.assertEqual(type(res[0]), Point) self.assertEqual(len(res), 2) def test_3(self): res = read_shapefile(os.path.join(self.dirname, "test3.shp")) self.assertEqual(type(res[0]), Point) self.assertEqual(len(res), 2) def test_4(self): res = read_shapefile(os.path.join(self.dirname, "test4.shp")) self.assertEqual(type(res[0]), Multipoint) self.assertEqual(len(res), 3) def test_5(self): res = read_shapefile(os.path.join(self.dirname, "test5.shp")) self.assertEqual(type(res[0]), Multipoint) self.assertEqual(len(res), 3) def test_6(self): res = read_shapefile(os.path.join(self.dirname, "test6.shp")) self.assertEqual(type(res[0]), Multipoint) self.assertEqual(len(res), 3) def test_7(self): res = read_shapefile(os.path.join(self.dirname, "test7.shp")) self.assertEqual(type(res[0]), Line) self.assertEqual(type(res[3]), Multiline) self.assertEqual(len(res), 4) def test_8(self): res = read_shapefile(os.path.join(self.dirname, "test8.shp")) self.assertEqual(type(res[0]), Line) self.assertEqual(len(res), 4) def test_9(self): res = read_shapefile(os.path.join(self.dirname, "test9.shp")) self.assertEqual(type(res[0]), Line) self.assertEqual(len(res), 4) def test_10(self): res = read_shapefile(os.path.join(self.dirname, "test10.shp")) self.assertEqual(type(res[0]), Polygon) self.assertEqual(len(res), 4) def test_11(self): res = read_shapefile(os.path.join(self.dirname, "test11.shp")) self.assertEqual(type(res[0]), Polygon) self.assertEqual(len(res), 4) def test_12(self): res = read_shapefile(os.path.join(self.dirname, "test12.shp")) self.assertEqual(type(res[0]), Polygon) self.assertEqual(len(res), 4) def test_13(self): res = read_shapefile(os.path.join(self.dirname, "test13.shp")) self.assertEqual(type(res[0]), Multipolygon) self.assertEqual(len(res), 4) if __name__ == "__main__": unittest.main()
[ "datetime.datetime", "datetime.time", "karta.vector.geometry.Polygon", "karta.vector.geometry.Line", "karta.vector.geometry.Multiline", "os.path.join", "warnings.catch_warnings", "karta.vector.geometry.Point", "numpy.array", "warnings.simplefilter", "datetime.date", "karta.vector.geometry.Mult...
[((15145, 15160), 'unittest.main', 'unittest.main', ([], {}), '()\n', (15158, 15160), False, 'import unittest\n'), ((1003, 1146), 'karta.vector.geometry.Multipoint', 'Multipoint', (['[(1, 1), (3, 1), (4, 3), (2, 2)]'], {'data': "{'species': ['T. officianale', 'C. tectorum', 'M. alba', 'V. cracca']}", 'crs': 'LonLatWGS84'}), "([(1, 1), (3, 1), (4, 3), (2, 2)], data={'species': [\n 'T. officianale', 'C. tectorum', 'M. alba', 'V. cracca']}, crs=LonLatWGS84)\n", (1013, 1146), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((1288, 1424), 'karta.vector.geometry.Line', 'Line', (['[(1.0, 5.0), (5.0, 5.0), (5.0, 1.0), (3.0, 3.0), (1.0, 1.0)]'], {'properties': "{'geom_id': 27, 'name': 'test line'}", 'crs': 'LonLatWGS84'}), "([(1.0, 5.0), (5.0, 5.0), (5.0, 1.0), (3.0, 3.0), (1.0, 1.0)],\n properties={'geom_id': 27, 'name': 'test line'}, crs=LonLatWGS84)\n", (1292, 1424), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((1486, 1577), 'karta.vector.geometry.Polygon', 'Polygon', (['[(1.0, 5.0), (5.0, 5.0), (5.0, 1.0), (3.0, 3.0), (1.0, 1.0)]'], {'crs': 'LonLatWGS84'}), '([(1.0, 5.0), (5.0, 5.0), (5.0, 1.0), (3.0, 3.0), (1.0, 1.0)], crs=\n LonLatWGS84)\n', (1493, 1577), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((1855, 1934), 'karta.vector.geometry.Line', 'Line', (['[(1, 5, 2), (5, 5, -1), (5, 1, 3), (3, 3, 1), (1, 1, 0)]'], {'crs': 'LonLatWGS84'}), '([(1, 5, 2), (5, 5, -1), (5, 1, 3), (3, 3, 1), (1, 1, 0)], crs=LonLatWGS84)\n', (1859, 1934), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((1946, 2033), 'karta.vector.geometry.Polygon', 'Polygon', (['[(1, 5, 2), (5, 5, -1), (5, 1, 3), (3, 3, 1), (1, 1, 0)]'], {'crs': 'LonLatWGS84'}), '([(1, 5, 2), (5, 5, -1), (5, 1, 3), (3, 3, 1), (1, 1, 0)], crs=\n LonLatWGS84)\n', (1953, 2033), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((3743, 3767), 'karta.vector.geometry.Multipoint', 'Multipoint', (['self.points3'], {}), '(self.points3)\n', (3753, 3767), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((4591, 4614), 'karta.vector.geometry.Multipoint', 'Multipoint', (['self.points'], {}), '(self.points)\n', (4601, 4614), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((4903, 5013), 'karta.vector.geometry.Multiline', 'Multiline', (['[[(0, 0), (1, 1), (2, 2)], [(1, 0), (2, 1), (3, 2)], [(2, 0), (1, 1), (0, 2)]]'], {'crs': 'LonLatWGS84'}), '([[(0, 0), (1, 1), (2, 2)], [(1, 0), (2, 1), (3, 2)], [(2, 0), (1,\n 1), (0, 2)]], crs=LonLatWGS84)\n', (4912, 5013), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((5309, 5431), 'karta.vector.geometry.Multipolygon', 'Multipolygon', (['[[[(0, 0), (2, 2), (1, 3)]], [[(2, 0), (4, 2), (3, 3)]], [[(2, -2), (1, 0),\n (-1, -1)]]]'], {'crs': 'LonLatWGS84'}), '([[[(0, 0), (2, 2), (1, 3)]], [[(2, 0), (4, 2), (3, 3)]], [[(2,\n -2), (1, 0), (-1, -1)]]], crs=LonLatWGS84)\n', (5321, 5431), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((5766, 5789), 'karta.vector.geometry.Multipoint', 'Multipoint', (['self.points'], {}), '(self.points)\n', (5776, 5789), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((5804, 5812), 'copy.copy', 'copy', (['mp'], {}), '(mp)\n', (5808, 5812), False, 'from copy import copy\n'), ((6253, 6268), 'copy.copy', 'copy', (['self.line'], {}), '(self.line)\n', (6257, 6268), False, 'from copy import copy\n'), ((7059, 7077), 'karta.vector.geometry.Multipoint', 'Multipoint', (['points'], {}), '(points)\n', (7069, 7077), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((11218, 11437), 'karta.vector.geometry.Line', 'Line', (['[(1.0, 5.0), (5.0, 5.0), (5.0, 1.0), (3.0, 3.0), (1.0, 1.0)]'], {'properties': "{'geom_id': 27, 'name': 'test line', 'description': 'line for testing',\n 'description_en': 'Line for testing.'}", 'crs': 'LonLatWGS84'}), "([(1.0, 5.0), (5.0, 5.0), (5.0, 1.0), (3.0, 3.0), (1.0, 1.0)],\n properties={'geom_id': 27, 'name': 'test line', 'description':\n 'line for testing', 'description_en': 'Line for testing.'}, crs=LonLatWGS84\n )\n", (11222, 11437), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((12497, 12544), 'os.path.join', 'os.path.join', (['TESTDATA', '"""shapefile"""', '"""shapelib"""'], {}), "(TESTDATA, 'shapefile', 'shapelib')\n", (12509, 12544), False, 'import os\n'), ((478, 550), 'karta.vector.geometry.Point', 'Point', (['(1, 1)'], {'properties': "{'species': 'T. officianale'}", 'crs': 'LonLatWGS84'}), "((1, 1), properties={'species': 'T. officianale'}, crs=LonLatWGS84)\n", (483, 550), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((612, 681), 'karta.vector.geometry.Point', 'Point', (['(3, 1)'], {'properties': "{'species': 'C. tectorum'}", 'crs': 'LonLatWGS84'}), "((3, 1), properties={'species': 'C. tectorum'}, crs=LonLatWGS84)\n", (617, 681), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((743, 808), 'karta.vector.geometry.Point', 'Point', (['(4, 3)'], {'properties': "{'species': 'M. alba'}", 'crs': 'LonLatWGS84'}), "((4, 3), properties={'species': 'M. alba'}, crs=LonLatWGS84)\n", (748, 808), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((870, 937), 'karta.vector.geometry.Point', 'Point', (['(2, 2)'], {'properties': "{'species': 'V. cracca'}", 'crs': 'LonLatWGS84'}), "((2, 2), properties={'species': 'V. cracca'}, crs=LonLatWGS84)\n", (875, 937), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((1620, 1653), 'karta.vector.geometry.Point', 'Point', (['(1, 1, 0)'], {'crs': 'LonLatWGS84'}), '((1, 1, 0), crs=LonLatWGS84)\n', (1625, 1653), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((1679, 1712), 'karta.vector.geometry.Point', 'Point', (['(3, 1, 3)'], {'crs': 'LonLatWGS84'}), '((3, 1, 3), crs=LonLatWGS84)\n', (1684, 1712), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((1738, 1771), 'karta.vector.geometry.Point', 'Point', (['(4, 3, 2)'], {'crs': 'LonLatWGS84'}), '((4, 3, 2), crs=LonLatWGS84)\n', (1743, 1771), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((1797, 1831), 'karta.vector.geometry.Point', 'Point', (['(2, 2, -1)'], {'crs': 'LonLatWGS84'}), '((2, 2, -1), crs=LonLatWGS84)\n', (1802, 1831), False, 'from karta.vector.geometry import Point, Line, Polygon, Multipoint, Multiline, Multipolygon\n'), ((2692, 2727), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/point"""'], {}), "(TESTDIR, 'data/point')\n", (2704, 2727), False, 'import os\n'), ((2973, 3013), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/points.shp"""'], {}), "(TESTDIR, 'data/points.shp')\n", (2985, 3013), False, 'import os\n'), ((3244, 3278), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/line"""'], {}), "(TESTDIR, 'data/line')\n", (3256, 3278), False, 'import os\n'), ((3495, 3532), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/polygon"""'], {}), "(TESTDIR, 'data/polygon')\n", (3507, 3532), False, 'import os\n'), ((3792, 3833), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/multipointz"""'], {}), "(TESTDIR, 'data/multipointz')\n", (3804, 3833), False, 'import os\n'), ((4077, 4112), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/linez"""'], {}), "(TESTDIR, 'data/linez')\n", (4089, 4112), False, 'import os\n'), ((4335, 4373), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/polygonz"""'], {}), "(TESTDIR, 'data/polygonz')\n", (4347, 4373), False, 'import os\n'), ((4639, 4679), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/multipoint"""'], {}), "(TESTDIR, 'data/multipoint')\n", (4651, 4679), False, 'import os\n'), ((5047, 5086), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/multiline"""'], {}), "(TESTDIR, 'data/multiline')\n", (5059, 5086), False, 'import os\n'), ((5494, 5533), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/multipoly"""'], {}), "(TESTDIR, 'data/multipoly')\n", (5506, 5533), False, 'import os\n'), ((5916, 5963), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/mp_collection.shp"""'], {}), "(TESTDIR, 'data/mp_collection.shp')\n", (5928, 5963), False, 'import os\n'), ((6390, 6439), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/line_collection.shp"""'], {}), "(TESTDIR, 'data/line_collection.shp')\n", (6402, 6439), False, 'import os\n'), ((6748, 6793), 'os.path.join', 'os.path.join', (['TESTDATA', '"""shapefile"""', '"""points"""'], {}), "(TESTDATA, 'shapefile', 'points')\n", (6760, 6793), False, 'import os\n'), ((8513, 8568), 'os.path.join', 'os.path.join', (['TESTDATA', '"""shapefile"""', '"""newp_nsidc_north"""'], {}), "(TESTDATA, 'shapefile', 'newp_nsidc_north')\n", (8525, 8568), False, 'import os\n'), ((10328, 10352), 'karta.vector.shp.ogr_get_fieldtype', 'shp.ogr_get_fieldtype', (['(1)'], {}), '(1)\n', (10349, 10352), False, 'from karta.vector import shp, read_shapefile\n'), ((10388, 10417), 'karta.vector.shp.ogr_get_fieldtype', 'shp.ogr_get_fieldtype', (['[1, 2]'], {}), '([1, 2])\n', (10409, 10417), False, 'from karta.vector import shp, read_shapefile\n'), ((10456, 10482), 'karta.vector.shp.ogr_get_fieldtype', 'shp.ogr_get_fieldtype', (['(1.0)'], {}), '(1.0)\n', (10477, 10482), False, 'from karta.vector import shp, read_shapefile\n'), ((10518, 10551), 'karta.vector.shp.ogr_get_fieldtype', 'shp.ogr_get_fieldtype', (['[1.0, 1.5]'], {}), '([1.0, 1.5])\n', (10539, 10551), False, 'from karta.vector import shp, read_shapefile\n'), ((10648, 10678), 'karta.vector.shp.ogr_get_fieldtype', 'shp.ogr_get_fieldtype', (['"""hello"""'], {}), "('hello')\n", (10669, 10678), False, 'from karta.vector import shp, read_shapefile\n'), ((10715, 10763), 'karta.vector.shp.ogr_get_fieldtype', 'shp.ogr_get_fieldtype', (["['list', 'of', 'strings']"], {}), "(['list', 'of', 'strings'])\n", (10736, 10763), False, 'from karta.vector import shp, read_shapefile\n'), ((11592, 11617), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (11615, 11617), False, 'import warnings\n'), ((11631, 11662), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (11652, 11662), False, 'import warnings\n'), ((12596, 12634), 'os.path.join', 'os.path.join', (['self.dirname', '"""test.shp"""'], {}), "(self.dirname, 'test.shp')\n", (12608, 12634), False, 'import os\n'), ((12688, 12727), 'os.path.join', 'os.path.join', (['self.dirname', '"""test0.shp"""'], {}), "(self.dirname, 'test0.shp')\n", (12700, 12727), False, 'import os\n'), ((12781, 12820), 'os.path.join', 'os.path.join', (['self.dirname', '"""test1.shp"""'], {}), "(self.dirname, 'test1.shp')\n", (12793, 12820), False, 'import os\n'), ((12958, 12997), 'os.path.join', 'os.path.join', (['self.dirname', '"""test2.shp"""'], {}), "(self.dirname, 'test2.shp')\n", (12970, 12997), False, 'import os\n'), ((13135, 13174), 'os.path.join', 'os.path.join', (['self.dirname', '"""test3.shp"""'], {}), "(self.dirname, 'test3.shp')\n", (13147, 13174), False, 'import os\n'), ((13312, 13351), 'os.path.join', 'os.path.join', (['self.dirname', '"""test4.shp"""'], {}), "(self.dirname, 'test4.shp')\n", (13324, 13351), False, 'import os\n'), ((13494, 13533), 'os.path.join', 'os.path.join', (['self.dirname', '"""test5.shp"""'], {}), "(self.dirname, 'test5.shp')\n", (13506, 13533), False, 'import os\n'), ((13676, 13715), 'os.path.join', 'os.path.join', (['self.dirname', '"""test6.shp"""'], {}), "(self.dirname, 'test6.shp')\n", (13688, 13715), False, 'import os\n'), ((13858, 13897), 'os.path.join', 'os.path.join', (['self.dirname', '"""test7.shp"""'], {}), "(self.dirname, 'test7.shp')\n", (13870, 13897), False, 'import os\n'), ((14084, 14123), 'os.path.join', 'os.path.join', (['self.dirname', '"""test8.shp"""'], {}), "(self.dirname, 'test8.shp')\n", (14096, 14123), False, 'import os\n'), ((14260, 14299), 'os.path.join', 'os.path.join', (['self.dirname', '"""test9.shp"""'], {}), "(self.dirname, 'test9.shp')\n", (14272, 14299), False, 'import os\n'), ((14437, 14477), 'os.path.join', 'os.path.join', (['self.dirname', '"""test10.shp"""'], {}), "(self.dirname, 'test10.shp')\n", (14449, 14477), False, 'import os\n'), ((14618, 14658), 'os.path.join', 'os.path.join', (['self.dirname', '"""test11.shp"""'], {}), "(self.dirname, 'test11.shp')\n", (14630, 14658), False, 'import os\n'), ((14799, 14839), 'os.path.join', 'os.path.join', (['self.dirname', '"""test12.shp"""'], {}), "(self.dirname, 'test12.shp')\n", (14811, 14839), False, 'import os\n'), ((14980, 15020), 'os.path.join', 'os.path.join', (['self.dirname', '"""test13.shp"""'], {}), "(self.dirname, 'test13.shp')\n", (14992, 15020), False, 'import os\n'), ((2392, 2427), 'os.path.join', 'os.path.join', (['TMPDATA', '"""shapefiles"""'], {}), "(TMPDATA, 'shapefiles')\n", (2404, 2427), False, 'import os\n'), ((2454, 2489), 'os.path.join', 'os.path.join', (['TMPDATA', '"""shapefiles"""'], {}), "(TMPDATA, 'shapefiles')\n", (2466, 2489), False, 'import os\n'), ((2559, 2599), 'os.path.join', 'os.path.join', (['TMPDATA', '"""shapefiles"""', 'fnm'], {}), "(TMPDATA, 'shapefiles', fnm)\n", (2571, 2599), False, 'import os\n'), ((7464, 7507), 'os.path.join', 'os.path.join', (['TESTDATA', '"""shapefile"""', '"""line"""'], {}), "(TESTDATA, 'shapefile', 'line')\n", (7476, 7507), False, 'import os\n'), ((7949, 7995), 'os.path.join', 'os.path.join', (['TESTDATA', '"""shapefile"""', '"""polygon"""'], {}), "(TESTDATA, 'shapefile', 'polygon')\n", (7961, 7995), False, 'import os\n'), ((10938, 10965), 'datetime.date', 'datetime.date', (['(2013)', '(11)', '(17)'], {}), '(2013, 11, 17)\n', (10951, 10965), False, 'import datetime\n'), ((11024, 11047), 'datetime.time', 'datetime.time', (['(8)', '(30)', '(0)'], {}), '(8, 30, 0)\n', (11037, 11047), False, 'import datetime\n'), ((11107, 11148), 'datetime.datetime', 'datetime.datetime', (['(2013)', '(11)', '(17)', '(8)', '(30)', '(0)'], {}), '(2013, 11, 17, 8, 30, 0)\n', (11124, 11148), False, 'import datetime\n'), ((11693, 11742), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data/line_truncated_attr"""'], {}), "(TESTDIR, 'data/line_truncated_attr')\n", (11705, 11742), False, 'import os\n'), ((12046, 12098), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', '"""line_truncated_attr"""'], {}), "(TESTDIR, 'data', 'line_truncated_attr')\n", (12058, 12098), False, 'import os\n'), ((2845, 2879), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (2857, 2879), False, 'import os\n'), ((3144, 3178), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (3156, 3178), False, 'import os\n'), ((3392, 3426), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (3404, 3426), False, 'import os\n'), ((3658, 3692), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (3670, 3692), False, 'import os\n'), ((3975, 4009), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (3987, 4009), False, 'import os\n'), ((4230, 4264), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (4242, 4264), False, 'import os\n'), ((4503, 4537), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (4515, 4537), False, 'import os\n'), ((4817, 4851), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (4829, 4851), False, 'import os\n'), ((5220, 5254), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (5232, 5254), False, 'import os\n'), ((5667, 5701), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (5679, 5701), False, 'import os\n'), ((6156, 6190), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (6168, 6190), False, 'import os\n'), ((6646, 6680), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (6658, 6680), False, 'import os\n'), ((7301, 7331), 'numpy.array', 'np.array', (['(1.0, 3.0, 4.0, 2.0)'], {}), '((1.0, 3.0, 4.0, 2.0))\n', (7309, 7331), True, 'import numpy as np\n'), ((7370, 7400), 'numpy.array', 'np.array', (['(1.0, 1.0, 3.0, 2.0)'], {}), '((1.0, 1.0, 3.0, 2.0))\n', (7378, 7400), True, 'import numpy as np\n'), ((7770, 7805), 'numpy.array', 'np.array', (['[1.0, 5.0, 5.0, 3.0, 1.0]'], {}), '([1.0, 5.0, 5.0, 3.0, 1.0])\n', (7778, 7805), True, 'import numpy as np\n'), ((7844, 7879), 'numpy.array', 'np.array', (['[5.0, 5.0, 1.0, 3.0, 1.0]'], {}), '([5.0, 5.0, 1.0, 3.0, 1.0])\n', (7852, 7879), True, 'import numpy as np\n'), ((8270, 8305), 'numpy.array', 'np.array', (['[1.0, 5.0, 5.0, 3.0, 1.0]'], {}), '([1.0, 5.0, 5.0, 3.0, 1.0])\n', (8278, 8305), True, 'import numpy as np\n'), ((8344, 8379), 'numpy.array', 'np.array', (['[5.0, 5.0, 1.0, 3.0, 1.0]'], {}), '([5.0, 5.0, 1.0, 3.0, 1.0])\n', (8352, 8379), True, 'import numpy as np\n'), ((11977, 12011), 'os.path.join', 'os.path.join', (['TESTDIR', '"""data"""', 'fnm'], {}), "(TESTDIR, 'data', fnm)\n", (11989, 12011), False, 'import os\n'), ((2104, 2137), 'os.path.join', 'join', (['TMPDATA', '"""shapefiles/"""', 'fnm'], {}), "(TMPDATA, 'shapefiles/', fnm)\n", (2108, 2137), False, 'from os.path import exists, join\n')]
import numpy as np from mapper_0000 import Mapper_0000 class Cartridge: def __init__(self, name: str): # Variables for values about the cartridge self.bImageValid = False self.nMapperID = np.uint8(0) self.nPRGBanks = np.uint8(0) self.nCHRBanks = np.uint8(0) self.mirror = "horizontal" # Variable for holding the Mapper class self.mapper = None # Arrys holding the cartrige memories self.vPRGMemory = [] self.vCHRMemory = [] # Call function for reading cartridge self.readCartridge(name) """ Function for reading the cartridge from file """ def readCartridge(self, name: str): loaded = np.fromfile(name,dtype='uint8') read_from = 0 self.name = loaded[read_from:4] read_from = 4 self.prg_rom_chunks = loaded[read_from] read_from += 1 self.chr_rom_chunks = loaded[read_from] read_from += 1 self.mapper1 = loaded[read_from] read_from += 1 self.mapper2 = loaded[read_from] read_from += 1 self.prg_ram_size = loaded[read_from] read_from += 1 self.tv_system1 = loaded[read_from] read_from += 1 self.tv_system2 = loaded[read_from] read_from += 1 read_from += 5 # IF there is a trainer: if self.mapper1 & 0x04: read_from += 512 self.nMapperID = ((self.mapper2 >> 4) << 4) | (self.mapper1 >> 4) self.mirror = "vertical" if (self.mapper1 & 0x01) else "horizontal" nFileType = 1 if nFileType == 0: pass if nFileType == 1: self.nPRGBanks = self.chr_rom_chunks self.vPRGMemory = loaded[read_from:read_from+16384] read_from += 16384 self.nCHRBanks = self.chr_rom_chunks self.vCHRMemory = loaded[read_from:read_from+8192] read_from += 8129 if nFileType == 2: pass if self.nMapperID == 0: self.mapper = Mapper_0000(self.nPRGBanks, self.nCHRBanks) self.bImageValid = True """ Function for checking the validity of the cart """ def imageValid(self) -> bool: return self.bImageValid """ Functions for reading and writing """ def cpuRead(self, addr: np.uint16) -> [bool, np.uint8]: mapped_addr = 0 is_mapped, mapped_addr = self.mapper.cpuMapRead(addr, mapped_addr) if is_mapped: data = self.vPRGMemory[mapped_addr] return True, data else: return False, 0 def cpuWrite(self, addr: np.uint16, data: np.uint8) -> bool: mapped_addr = 0 is_mapped, mapped_addr = self.mapper.cpuMapWrite(addr, mapped_addr) if is_mapped: self.vPRGMemory[mapped_addr] = data return True else: return False def ppuRead(self, addr: np.uint16) -> [bool, np.uint8]: mapped_addr = 0 is_mapped, mapped_addr = self.mapper.ppuMapRead(addr, mapped_addr) if is_mapped: data = self.vCHRMemory[mapped_addr] return True, data else: return False, 0 def ppuWrite(self, addr: np.uint16, data: np.uint8) -> bool: mapped_addr = 0 is_mapped, mapped_addr = self.mapper.ppuMapWrite(addr, mapped_addr) if is_mapped: self.vCHRMemory[mapped_addr] = data return True else: return False if __name__ == "__main__": cart = Cartridge("../branch_timing_tests/1.Branch_Basics.nes")
[ "numpy.uint8", "numpy.fromfile", "mapper_0000.Mapper_0000" ]
[((228, 239), 'numpy.uint8', 'np.uint8', (['(0)'], {}), '(0)\n', (236, 239), True, 'import numpy as np\n'), ((266, 277), 'numpy.uint8', 'np.uint8', (['(0)'], {}), '(0)\n', (274, 277), True, 'import numpy as np\n'), ((304, 315), 'numpy.uint8', 'np.uint8', (['(0)'], {}), '(0)\n', (312, 315), True, 'import numpy as np\n'), ((770, 802), 'numpy.fromfile', 'np.fromfile', (['name'], {'dtype': '"""uint8"""'}), "(name, dtype='uint8')\n", (781, 802), True, 'import numpy as np\n'), ((2172, 2215), 'mapper_0000.Mapper_0000', 'Mapper_0000', (['self.nPRGBanks', 'self.nCHRBanks'], {}), '(self.nPRGBanks, self.nCHRBanks)\n', (2183, 2215), False, 'from mapper_0000 import Mapper_0000\n')]
# -*- coding: utf-8 -*- import numpy as np import operator import matplotlib.pyplot as plt from os import listdir # 《机器学习实战》 - 第2章 - k-近邻算法 def classify0(inX, dataSet, labels, k): """ 利用k-近邻算法实现分类,采用欧式距离 inX: 用于分类的输入向量 dataSet: 训练集 labels: 标签向量 k: 选择最近邻数目 """ dataSetSize = dataSet.shape[0] # 将输入向量按行复制,与训练集相减得到差值 diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet # 各个差值分别平方 sqDiffMat = diffMat ** 2 # 按行对结果求和 sqDistances = sqDiffMat.sum(axis = 1) # 再开方即可得到距离 distances = sqDistances ** 0.5 # argsort()方法将向量中每个元素进行排序,结果是元素的索引形成的向量 # 如argsort([1,3,2]) -> ([0,2,1]) sortedDistIndicies = distances.argsort() classCount = {} for i in range(k): # 找到该样本的类型 voteIlabel = labels[sortedDistIndicies[i]] # 在字典中将该类型+1 # 字典的get()方法 # 如:list.get(k,d)get相当于一条if...else...语句 # 参数k在字典中,字典将返回list[k] # 如果参数k不在字典中则返回参数d,如果K在字典中则返回k对应的value值 classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 # 字典的 items()方法,以列表返回可遍历的(key,value)元组 # sorted()中的第2个参数key=operator.itemgetter(1)表示按第2个元素进行排序 sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True) # 返回第0个tuple的第0个参数,由于是逆序排序所以返回的是出现次数最多的类型 return sortedClassCount[0][0] # 示例1: 使用k-近邻算法改进约会网站的配对效果 def file2matrix(filename): """ 导入约会网站数据 """ fr = open(filename) arrayOLines = fr.readlines() numberOfLines = len(arrayOLines) returnMat = np.zeros((numberOfLines,3)) classLabelVector = [] index = 0 for line in arrayOLines: line = line.strip() listFromLine = line.split('\t') returnMat[index, :] = listFromLine[0:3] classLabelVector.append(int(listFromLine[-1])) index += 1 return returnMat, classLabelVector """ # 对数据进行可视化 datingDataMat, datingLabels = file2matrix('datingTestSET.txt') fig = plt.figure() ax = fig.add_subplot(111) #ax.scatter(datingDataMat[:, 0], datingDataMat[:, 1], 15.0*np.array(datingLabels), 15.0*np.array(datingLabels),edgecolors= 'black') ax.scatter(datingDataMat[:, 1], datingDataMat[:, 2], 15.0*np.array(datingLabels), 15.0*np.array(datingLabels),edgecolors= 'black') plt.show() """ def autoNorm(dataSet): """ 数据归一化(Min-Max Scaling) """ minVals = dataSet.min(0) maxVals = dataSet.max(0) ranges = maxVals - minVals normDataSet = np.zeros(np.shape(dataSet)) m = dataSet.shape[0] normDataSet = dataSet - np.tile(minVals, (m, 1)) normDataSet = normDataSet/np.tile(ranges, (m, 1)) return normDataSet, ranges, minVals def dataingClassTest(): """ 测试kNN优化后约会网站的配对效果 """ hoRatio = 0.10 # 测试集比例 datingDataMat, datingLabels = file2matrix('datingTestSet.txt') normMat, ranges, minVals = autoNorm(datingDataMat) # 数据归一化 m = normMat.shape[0] # 训练样本量 numTestVecs = int(m * hoRatio) errorCount = 0.0 for i in range(numTestVecs): classifierResult = classify0(normMat[i, :], normMat[numTestVecs:m, :], datingLabels[numTestVecs:m], 3) print("the classifier came back with: %d, the real answer is: %d" % (classifierResult, datingLabels[i])) if (classifierResult != datingLabels[i]): errorCount += 1.0 print("the total error rate is: %f" % (errorCount / float(numTestVecs))) print("the total error count is:",errorCount) # 测试kNN在约会网站的配对的错误率 # dataingClassTest() def classifyPerson(): """ 约会网站预测 """ resultList = ['not at all', 'in small doses', 'in large doses'] percentTats = float(input("percentage of time spent playing video games ?")) ffMiles = float(input("frequent filer miles earned per year?")) iceCream = float(input("liters of ice cream consumed per year?")) datingDataMat, datingLabels = file2matrix('datingTestSet.txt') normMat, ranges, minVals = autoNorm(datingDataMat) inArr = np.array([ffMiles, percentTats, iceCream]) classifierResult = classify0((inArr-minVals)/ranges,normMat,datingLabels, 3) print("You will probably like this person: ", resultList[classifierResult - 1]) # 测试约会网站预测 # classifyPerson() # 示例2: 使用k-近邻算法进行手写数字识别 """ 思路: 1. 将每个32*32的图像数据转换为1*1024的向量 再将每个单列向量分别存入一个矩阵A中 矩阵A中每一列对应一张图片信息,m张图片对应的矩阵A的大小即为m*1024 2. 将测试图片也转换为1*1024的向量后与矩阵A中每一列求欧式距离 将一一对应的距离存入一个数组中,取出距离数组中最小的k个训练集索引 3. 索引出现次数最多的值就是预测数值 PS: kNN要分类的话每张图片都得和全部训练集计算距离,时间复杂度就是O(M*N) 虽然简单但是遇到数据集很大时会变得效率非常低 """ def img2vector(filename): """ 将32*32的图像数据转换为1*1024的向量 循环读出文件的前32行,并将每行的前32个值存储在1*1024的numpy数组中 """ returnVect = np.zeros((1,1024)) fr = open(filename) for i in range(32): lineStr = fr.readline() for j in range(32): returnVect[0,32*i+j] = int(lineStr[j]) return returnVect def handwritingClassTest(): """ kNN手写数字识别测试 """ # 导入训练集 hwLabels = [] trainingFileList = listdir('trainingDigits') m = len(trainingFileList) trainingMat = np.zeros((m, 1024)) for i in range(m): fileNameStr = trainingFileList[i] fileStr = fileNameStr.split('.')[0] classNumStr = int(fileStr.split('_')[0]) hwLabels.append(classNumStr) trainingMat[i, :] = img2vector('trainingDigits/%s' % fileNameStr) # 导入测试集 testFileList = listdir('testDigits') errorCount = 0.0 mTest = len(testFileList) for i in range(mTest): fileNameStr = testFileList[i] fileStr = fileNameStr.split('.')[0] classNumStr = int(fileStr.split('_')[0]) vectorUnderTest = img2vector('testDigits/%s' % fileNameStr) classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3) print("the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr)) if (classifierResult != classNumStr): errorCount += 1.0 print("\nthe total number of errors is: %d" % errorCount) print("\nthe total correct rate is: %f" % (1-(errorCount / float(mTest)))) # 测试手写数字识别正确率 # handwritingClassTest()
[ "numpy.tile", "os.listdir", "numpy.array", "numpy.zeros", "operator.itemgetter", "numpy.shape" ]
[((1504, 1532), 'numpy.zeros', 'np.zeros', (['(numberOfLines, 3)'], {}), '((numberOfLines, 3))\n', (1512, 1532), True, 'import numpy as np\n'), ((3883, 3925), 'numpy.array', 'np.array', (['[ffMiles, percentTats, iceCream]'], {}), '([ffMiles, percentTats, iceCream])\n', (3891, 3925), True, 'import numpy as np\n'), ((4549, 4568), 'numpy.zeros', 'np.zeros', (['(1, 1024)'], {}), '((1, 1024))\n', (4557, 4568), True, 'import numpy as np\n'), ((4863, 4888), 'os.listdir', 'listdir', (['"""trainingDigits"""'], {}), "('trainingDigits')\n", (4870, 4888), False, 'from os import listdir\n'), ((4937, 4956), 'numpy.zeros', 'np.zeros', (['(m, 1024)'], {}), '((m, 1024))\n', (4945, 4956), True, 'import numpy as np\n'), ((5258, 5279), 'os.listdir', 'listdir', (['"""testDigits"""'], {}), "('testDigits')\n", (5265, 5279), False, 'from os import listdir\n'), ((366, 396), 'numpy.tile', 'np.tile', (['inX', '(dataSetSize, 1)'], {}), '(inX, (dataSetSize, 1))\n', (373, 396), True, 'import numpy as np\n'), ((2415, 2432), 'numpy.shape', 'np.shape', (['dataSet'], {}), '(dataSet)\n', (2423, 2432), True, 'import numpy as np\n'), ((2487, 2511), 'numpy.tile', 'np.tile', (['minVals', '(m, 1)'], {}), '(minVals, (m, 1))\n', (2494, 2511), True, 'import numpy as np\n'), ((2542, 2565), 'numpy.tile', 'np.tile', (['ranges', '(m, 1)'], {}), '(ranges, (m, 1))\n', (2549, 2565), True, 'import numpy as np\n'), ((1191, 1213), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (1210, 1213), False, 'import operator\n')]
# -*- coding: utf-8 -*- """ ![LeNet Architecture](lenet.png) Source: <NAME> """ from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from sklearn.utils import shuffle from tensorflow.keras.datasets import mnist from tensorflow.keras.datasets import fashion_mnist from tensorflow.contrib.layers import flatten import sys import csv import os import time np.random.seed(1) tf.set_random_seed(2) # Load Dataset if len(sys.argv) > 2: data_set = sys.argv[2] if sys.argv[2] == 'mnist': d_set = mnist elif sys.argv[2] == 'fashion_mnist': d_set = fashion_mnist else: data_set = 'mnist' d_set = mnist # confirm Dataset print("Dataset is: ", data_set) (X_train, y_train), (X_test, y_test) = d_set.load_data() X_train = np.expand_dims(X_train, axis=3) # (60000, 28, 28, 1) X_test = np.expand_dims(X_test, axis=3) # (10000, 28, 28, 1) assert(len(X_train) == len(y_train)) assert(len(X_test) == len(y_test)) # X_train = X_train[:128] # y_train = y_train[:128] # X_test = X_test[:128] # y_test = y_test[:128] print("\nImage Shape: {}\n".format(X_train[0].shape)) print("Training Set: {} samples".format(len(X_train))) print("Test Set: {} samples".format(len(X_test))) """The MNIST data that TensorFlow pre-loads comes as 28x28x1 images. However, the LeNet architecture only accepts 32x32xC images, where C is the number of color channels. In order to reformat the MNIST data into a shape that LeNet will accept, we pad the data with two rows of zeros on the top and bottom, and two columns of zeros on the left and right (28+2+2 = 32). You do not need to modify this section. """ # Pad images with 0s X_train = np.pad(X_train, ((0, 0), (2, 2), (2, 2), (0, 0)), 'constant') X_test = np.pad(X_test, ((0, 0), (2, 2), (2, 2), (0, 0)), 'constant') print("Updated Image Shape: {}".format(X_train[0].shape)) """## Setup TensorFlow The `EPOCH` and `BATCH_SIZE` values affect the training speed and model accuracy. """ EPOCHS = 30 BATCH_SIZE = 128 print('Total epochs:', EPOCHS) # Set Posit data types if len(sys.argv) > 1: data_t = sys.argv[1] if sys.argv[1] == 'posit32': eps = 1e-8 posit = np.posit32 tf_type = tf.posit32 elif sys.argv[1] == 'posit16': eps = 1e-4 posit = np.posit16 tf_type = tf.posit16 elif sys.argv[1] == 'posit8': eps = 0.015625 posit = np.posit8 tf_type = tf.posit8 elif sys.argv[1] == 'float16': eps = 1e-4 posit = np.float16 tf_type = tf.float16 elif sys.argv[1] == 'float32': eps = 1e-8 posit = np.float32 tf_type = tf.float32 else: eps = 1e-8 data_t = 'float32' posit = np.float32 tf_type = tf.float32 # confirm dtype print("\nType is: ", data_t) # Normalize data # X_train = (X_train/255.).astype(posit) # [0,1] normalization # X_test = (X_test/255.).astype(posit) X_train = ((X_train-127.5)/127.5).astype(posit) # [-1,1] normalization X_test = ((X_test-127.5)/127.5).astype(posit) print("Input data type: {}".format(type(X_train[0, 0, 0, 0]))) """## Implementation of LeNet-5 Implement the [LeNet-5](http://yann.lecun.com/exdb/lenet/) neural network architecture. This is the only cell you need to edit. # Input The LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since MNIST images are grayscale, C is 1 in this case. # Architecture **Layer 1: Convolutional.** The output shape should be 28x28x6. **Activation.** Your choice of activation function. **Pooling.** The output shape should be 14x14x6. **Layer 2: Convolutional.** The output shape should be 10x10x16. **Activation.** Your choice of activation function. **Pooling.** The output shape should be 5x5x16. **Flatten.** Flatten the output shape of the final pooling layer such that it's 1D instead of 3D. The easiest way to do is by using `tf.contrib.layers.flatten`, which is already imported for you. **Layer 3: Fully Connected.** This should have 120 outputs. **Activation.** Your choice of activation function. **Layer 4: Fully Connected.** This should have 84 outputs. **Activation.** Your choice of activation function. **Layer 5: Fully Connected (Logits).** This should have 10 outputs. # Output Return the result of the 2nd fully connected layer. """ def LeNet(x): # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer mu = 0 sigma = 0.1 # Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6. conv1_W = tf.Variable(tf.truncated_normal( shape=(5, 5, 1, 6), mean=mu, stddev=sigma, dtype=tf_type)) conv1_b = tf.Variable(tf.zeros(6, dtype=tf_type)) conv1 = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b # Activation. conv1 = tf.nn.relu(conv1) # Pooling. Input = 28x28x6. Output = 14x14x6. conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID') # Dropout #conv1 = tf.nn.dropout(conv1, keep_prob) # Layer 2: Convolutional. Output = 10x10x16. conv2_W = tf.Variable(tf.truncated_normal( shape=(5, 5, 6, 16), mean=mu, stddev=sigma, dtype=tf_type)) conv2_b = tf.Variable(tf.zeros(16, dtype=tf_type)) conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b # Activation. conv2 = tf.nn.relu(conv2) # Pooling. Input = 10x10x16. Output = 5x5x16. conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID') # Dropout #conv2 = tf.nn.dropout(conv2, keep_prob) # Flatten. Input = 5x5x16. Output = 400. fc0 = flatten(conv2) #fc0 = tf.reshape(conv2, [-1]) # Layer 3: Fully Connected. Input = 400. Output = 120. fc1_W = tf.Variable(tf.truncated_normal( shape=(400, 120), mean=mu, stddev=sigma, dtype=tf_type)) fc1_b = tf.Variable(tf.zeros(120, dtype=tf_type)) fc1 = tf.matmul(fc0, fc1_W) + fc1_b # Activation. fc1 = tf.nn.relu(fc1) # Dropout #fc1 = tf.nn.dropout(fc1, keep_prob) # Layer 4: Fully Connected. Input = 120. Output = 84. fc2_W = tf.Variable(tf.truncated_normal( shape=(120, 84), mean=mu, stddev=sigma, dtype=tf_type)) fc2_b = tf.Variable(tf.zeros(84, dtype=tf_type)) fc2 = tf.matmul(fc1, fc2_W) + fc2_b # Activation. fc2 = tf.nn.relu(fc2) # Dropout #fc2 = tf.nn.dropout(fc2, keep_prob) # Layer 5: Fully Connected. Input = 84. Output = 10. fc3_W = tf.Variable(tf.truncated_normal( shape=(84, 10), mean=mu, stddev=sigma, dtype=tf_type)) fc3_b = tf.Variable(tf.zeros(10, dtype=tf_type)) logits = tf.matmul(fc2, fc3_W) + fc3_b return logits """## Features and Labels Train LeNet to classify [MNIST](http://yann.lecun.com/exdb/mnist/) data. `x` is a placeholder for a batch of input images. `y` is a placeholder for a batch of output labels. """ x = tf.placeholder(tf_type, (None, 32, 32, 1), name='inputs') y = tf.placeholder(tf.int32, (None), name='labels') #keep_prob = tf.placeholder(tf_type, (None)) """## Training Pipeline Create a training pipeline that uses the model to classify MNIST data. """ rate = posit(0.001) logits = tf.identity(LeNet(x), name="logits") # cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits( labels=y, logits=logits) loss_operation = tf.reduce_mean(cross_entropy, name="loss_operation") optimizer = tf.train.AdamOptimizer(learning_rate=rate, beta1=posit( 0.9), beta2=posit(0.999), epsilon=posit(eps)) training_operation = optimizer.minimize( loss_operation, name="training_operation") """## Model Evaluation Evaluate how well the loss and accuracy of the model for a given dataset. """ # correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1)) correct_prediction = tf.equal(tf.argmax(logits, 1, output_type=tf.int32), y) accuracy_operation = tf.reduce_mean( tf.cast(correct_prediction, tf.float32), name="accuracy_operation") in_top5 = tf.nn.in_top_k(tf.cast(logits, tf.float32), y, k=5) top5_operation = tf.reduce_mean(tf.cast(in_top5, tf.float32)) saver = tf.train.Saver() def evaluate(X_data, y_data): num_examples = len(X_data) total_accuracy = 0 total_top5 = 0 sess = tf.get_default_session() for offset in range(0, num_examples, BATCH_SIZE): batch_x, batch_y = X_data[offset:offset + BATCH_SIZE], y_data[offset:offset+BATCH_SIZE] accuracy, top5 = sess.run([accuracy_operation, top5_operation], feed_dict={ x: batch_x, y: batch_y}) total_accuracy += (accuracy * len(batch_x)) total_top5 += (top5 * len(batch_x)) return (total_accuracy / num_examples, total_top5 / num_examples) def get_top5(X_data, y_data): num_examples = len(X_data) total_top5 = 0 sess = tf.get_default_session() for offset in range(0, num_examples, BATCH_SIZE): batch_x, batch_y = X_data[offset:offset + BATCH_SIZE], y_data[offset:offset+BATCH_SIZE] top5 = sess.run(top5_operation, feed_dict={x: batch_x, y: batch_y}) total_top5 += (top5 * len(batch_x)) return (total_top5 / num_examples) def validate(X_data, y_data): num_examples = len(X_data) total_loss = 0 total_accuracy = 0 sess = tf.get_default_session() for offset in range(0, num_examples, BATCH_SIZE): batch_x, batch_y = X_data[offset:offset + BATCH_SIZE], y_data[offset:offset+BATCH_SIZE] _loss, _acc = sess.run([loss_operation, accuracy_operation], feed_dict={ x: batch_x, y: batch_y}) total_accuracy += (_acc * len(batch_x)) total_loss += (_loss * len(batch_x)) return (total_loss / num_examples, total_accuracy / num_examples) """## Train the Model Run the training data through the training pipeline to train the model. Before each epoch, shuffle the training set. After each epoch, measure the loss and accuracy of the validation set. Save the model after training. """ hist = {} # Adding list as value hist["loss"] = [] hist["acc"] = [] hist["val_loss"] = [] hist["val_acc"] = [] files_path = './train_results/lenet5/' + data_set + '/' directory = os.path.dirname(files_path) if not os.path.exists(directory): os.makedirs(directory) tic = time.time() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) num_examples = len(X_train) print("Training...") print() for i in range(EPOCHS): X_train, y_train = shuffle(X_train, y_train) epoch_loss = 0 epoch_acc = 0 for offset in range(0, num_examples, BATCH_SIZE): end = offset + BATCH_SIZE batch_x, batch_y = X_train[offset:end], y_train[offset:end] _, _loss, _acc = sess.run( [training_operation, loss_operation, accuracy_operation], feed_dict={x: batch_x, y: batch_y}) # print('Batch compleated') # print(_loss) epoch_loss += (_loss * len(batch_x)) epoch_acc += (_acc * len(batch_x)) print("EPOCH {} ...".format(i+1)) epoch_loss /= num_examples epoch_acc /= num_examples print("Training Loss = {:.4f}".format(epoch_loss)) hist["loss"].append(epoch_loss) print("Training Accuracy = {:.4f}".format(epoch_acc)) hist["acc"].append(epoch_acc) # Compute val_loss & val_acc val_loss, val_acc = validate(X_test, y_test) print("Test Loss = {:.4f}".format(val_loss)) hist["val_loss"].append(val_loss) print("Test Accuracy = {:.4f}".format(val_acc)) hist["val_acc"].append(val_acc) print() # Save the entire model as a SavedModel. # if (data_t == 'float32'): # tf.saved_model.simple_save( # sess, # export_dir=files_path, # inputs={"in_placeholder": x}, # outputs={"prediction": logits}, # ) # Save the graph proto to a file. f_name = data_t + '.pb' tf.train.write_graph( sess.graph_def, files_path, f_name, as_text=False) # proto # Save the variables to disk (checkpoint file) saver = tf.train.Saver(tf.global_variables()) # model_name = files_path + "checkpoint.data" # saver.save(sess, model_name) model_name = files_path + data_t + '.ckpt' save_path = saver.save(sess, model_name) print("Model saved in path: %s" % save_path) toc = time.time() """## Evaluate the Model Once you are completely satisfied with your model, evaluate the performance of the model on the test set. Be sure to only do this once! If you were to measure the performance of your trained model on the test set, then improve your model, and then measure the performance of your model on the test set again, that would invalidate your test results. You wouldn't get a true measure of how well your model would perform against real data. """ with tf.Session() as sess: #saver.restore(sess, tf.train.latest_checkpoint('.')) saver.restore(sess, model_name) test_top5 = get_top5(X_test, y_test) print("Test Top-5 = {:.4f}".format(test_top5)) results_path = files_path + data_t + '.csv' zd = zip(*hist.values()) with open(results_path, 'w') as file: writer = csv.writer(file, delimiter=',') writer.writerow(hist.keys()) writer.writerows(zd) f = open(files_path + 'top5.txt', "a+") f.write("%s: %s\n" % (data_t, test_top5)) f.close() send_mail = True if(send_mail): PACKAGE_PARENT = '..' SCRIPT_DIR = os.path.dirname(os.path.realpath( os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) from other.mail import send_mail s = int(toc-tic) m, s = divmod(s, 60) h, m = divmod(m, 60) subject = 'CNN Training compleated' body = 'The training phase with data type %s on TensorFlow (%s) has finished after %s h, min, sec!\n\nThe Top-5 is %s and training history is:\n%s' % ( posit, data_set, (h, m, s), test_top5, hist) path = os.path.abspath('../other/credentials.txt') send_mail(subject=subject, mail_body=body, credentials=path)
[ "tensorflow.contrib.layers.flatten", "tensorflow.get_default_session", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.train.write_graph", "tensorflow.reduce_mean", "tensorflow.cast", "tensorflow.set_random_seed", "os.path.exists", "tensorflow.placeholder", "tensorflow.Sessio...
[((416, 433), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (430, 433), True, 'import numpy as np\n'), ((434, 455), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(2)'], {}), '(2)\n', (452, 455), True, 'import tensorflow as tf\n'), ((811, 842), 'numpy.expand_dims', 'np.expand_dims', (['X_train'], {'axis': '(3)'}), '(X_train, axis=3)\n', (825, 842), True, 'import numpy as np\n'), ((874, 904), 'numpy.expand_dims', 'np.expand_dims', (['X_test'], {'axis': '(3)'}), '(X_test, axis=3)\n', (888, 904), True, 'import numpy as np\n'), ((1717, 1778), 'numpy.pad', 'np.pad', (['X_train', '((0, 0), (2, 2), (2, 2), (0, 0))', '"""constant"""'], {}), "(X_train, ((0, 0), (2, 2), (2, 2), (0, 0)), 'constant')\n", (1723, 1778), True, 'import numpy as np\n'), ((1788, 1848), 'numpy.pad', 'np.pad', (['X_test', '((0, 0), (2, 2), (2, 2), (0, 0))', '"""constant"""'], {}), "(X_test, ((0, 0), (2, 2), (2, 2), (0, 0)), 'constant')\n", (1794, 1848), True, 'import numpy as np\n'), ((7096, 7153), 'tensorflow.placeholder', 'tf.placeholder', (['tf_type', '(None, 32, 32, 1)'], {'name': '"""inputs"""'}), "(tf_type, (None, 32, 32, 1), name='inputs')\n", (7110, 7153), True, 'import tensorflow as tf\n'), ((7158, 7203), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', 'None'], {'name': '"""labels"""'}), "(tf.int32, None, name='labels')\n", (7172, 7203), True, 'import tensorflow as tf\n'), ((7526, 7597), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'y', 'logits': 'logits'}), '(labels=y, logits=logits)\n', (7572, 7597), True, 'import tensorflow as tf\n'), ((7620, 7672), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['cross_entropy'], {'name': '"""loss_operation"""'}), "(cross_entropy, name='loss_operation')\n", (7634, 7672), True, 'import tensorflow as tf\n'), ((8379, 8395), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (8393, 8395), True, 'import tensorflow as tf\n'), ((10547, 10574), 'os.path.dirname', 'os.path.dirname', (['files_path'], {}), '(files_path)\n', (10562, 10574), False, 'import os\n'), ((10644, 10655), 'time.time', 'time.time', ([], {}), '()\n', (10653, 10655), False, 'import time\n'), ((12791, 12802), 'time.time', 'time.time', ([], {}), '()\n', (12800, 12802), False, 'import time\n'), ((4906, 4923), 'tensorflow.nn.relu', 'tf.nn.relu', (['conv1'], {}), '(conv1)\n', (4916, 4923), True, 'import tensorflow as tf\n'), ((4987, 5072), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['conv1'], {'ksize': '[1, 2, 2, 1]', 'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID'\n )\n", (5001, 5072), True, 'import tensorflow as tf\n'), ((5521, 5538), 'tensorflow.nn.relu', 'tf.nn.relu', (['conv2'], {}), '(conv2)\n', (5531, 5538), True, 'import tensorflow as tf\n'), ((5602, 5687), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['conv2'], {'ksize': '[1, 2, 2, 1]', 'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""'}), "(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID'\n )\n", (5616, 5687), True, 'import tensorflow as tf\n'), ((5826, 5840), 'tensorflow.contrib.layers.flatten', 'flatten', (['conv2'], {}), '(conv2)\n', (5833, 5840), False, 'from tensorflow.contrib.layers import flatten\n'), ((6169, 6184), 'tensorflow.nn.relu', 'tf.nn.relu', (['fc1'], {}), '(fc1)\n', (6179, 6184), True, 'import tensorflow as tf\n'), ((6531, 6546), 'tensorflow.nn.relu', 'tf.nn.relu', (['fc2'], {}), '(fc2)\n', (6541, 6546), True, 'import tensorflow as tf\n'), ((8091, 8133), 'tensorflow.argmax', 'tf.argmax', (['logits', '(1)'], {'output_type': 'tf.int32'}), '(logits, 1, output_type=tf.int32)\n', (8100, 8133), True, 'import tensorflow as tf\n'), ((8179, 8218), 'tensorflow.cast', 'tf.cast', (['correct_prediction', 'tf.float32'], {}), '(correct_prediction, tf.float32)\n', (8186, 8218), True, 'import tensorflow as tf\n'), ((8272, 8299), 'tensorflow.cast', 'tf.cast', (['logits', 'tf.float32'], {}), '(logits, tf.float32)\n', (8279, 8299), True, 'import tensorflow as tf\n'), ((8341, 8369), 'tensorflow.cast', 'tf.cast', (['in_top5', 'tf.float32'], {}), '(in_top5, tf.float32)\n', (8348, 8369), True, 'import tensorflow as tf\n'), ((8512, 8536), 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), '()\n', (8534, 8536), True, 'import tensorflow as tf\n'), ((9123, 9147), 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), '()\n', (9145, 9147), True, 'import tensorflow as tf\n'), ((9607, 9631), 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), '()\n', (9629, 9631), True, 'import tensorflow as tf\n'), ((10583, 10608), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (10597, 10608), False, 'import os\n'), ((10614, 10636), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (10625, 10636), False, 'import os\n'), ((10661, 10673), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (10671, 10673), True, 'import tensorflow as tf\n'), ((12367, 12438), 'tensorflow.train.write_graph', 'tf.train.write_graph', (['sess.graph_def', 'files_path', 'f_name'], {'as_text': '(False)'}), '(sess.graph_def, files_path, f_name, as_text=False)\n', (12387, 12438), True, 'import tensorflow as tf\n'), ((13279, 13291), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (13289, 13291), True, 'import tensorflow as tf\n'), ((13611, 13642), 'csv.writer', 'csv.writer', (['file'], {'delimiter': '""","""'}), "(file, delimiter=',')\n", (13621, 13642), False, 'import csv\n'), ((14422, 14465), 'os.path.abspath', 'os.path.abspath', (['"""../other/credentials.txt"""'], {}), "('../other/credentials.txt')\n", (14437, 14465), False, 'import os\n'), ((14470, 14530), 'other.mail.send_mail', 'send_mail', ([], {'subject': 'subject', 'mail_body': 'body', 'credentials': 'path'}), '(subject=subject, mail_body=body, credentials=path)\n', (14479, 14530), False, 'from other.mail import send_mail\n'), ((4622, 4699), 'tensorflow.truncated_normal', 'tf.truncated_normal', ([], {'shape': '(5, 5, 1, 6)', 'mean': 'mu', 'stddev': 'sigma', 'dtype': 'tf_type'}), '(shape=(5, 5, 1, 6), mean=mu, stddev=sigma, dtype=tf_type)\n', (4641, 4699), True, 'import tensorflow as tf\n'), ((4736, 4762), 'tensorflow.zeros', 'tf.zeros', (['(6)'], {'dtype': 'tf_type'}), '(6, dtype=tf_type)\n', (4744, 4762), True, 'import tensorflow as tf\n'), ((4776, 4839), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['x', 'conv1_W'], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID')\n", (4788, 4839), True, 'import tensorflow as tf\n'), ((5231, 5309), 'tensorflow.truncated_normal', 'tf.truncated_normal', ([], {'shape': '(5, 5, 6, 16)', 'mean': 'mu', 'stddev': 'sigma', 'dtype': 'tf_type'}), '(shape=(5, 5, 6, 16), mean=mu, stddev=sigma, dtype=tf_type)\n', (5250, 5309), True, 'import tensorflow as tf\n'), ((5346, 5373), 'tensorflow.zeros', 'tf.zeros', (['(16)'], {'dtype': 'tf_type'}), '(16, dtype=tf_type)\n', (5354, 5373), True, 'import tensorflow as tf\n'), ((5387, 5454), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['conv1', 'conv2_W'], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID')\n", (5399, 5454), True, 'import tensorflow as tf\n'), ((5960, 6035), 'tensorflow.truncated_normal', 'tf.truncated_normal', ([], {'shape': '(400, 120)', 'mean': 'mu', 'stddev': 'sigma', 'dtype': 'tf_type'}), '(shape=(400, 120), mean=mu, stddev=sigma, dtype=tf_type)\n', (5979, 6035), True, 'import tensorflow as tf\n'), ((6070, 6098), 'tensorflow.zeros', 'tf.zeros', (['(120)'], {'dtype': 'tf_type'}), '(120, dtype=tf_type)\n', (6078, 6098), True, 'import tensorflow as tf\n'), ((6110, 6131), 'tensorflow.matmul', 'tf.matmul', (['fc0', 'fc1_W'], {}), '(fc0, fc1_W)\n', (6119, 6131), True, 'import tensorflow as tf\n'), ((6324, 6398), 'tensorflow.truncated_normal', 'tf.truncated_normal', ([], {'shape': '(120, 84)', 'mean': 'mu', 'stddev': 'sigma', 'dtype': 'tf_type'}), '(shape=(120, 84), mean=mu, stddev=sigma, dtype=tf_type)\n', (6343, 6398), True, 'import tensorflow as tf\n'), ((6433, 6460), 'tensorflow.zeros', 'tf.zeros', (['(84)'], {'dtype': 'tf_type'}), '(84, dtype=tf_type)\n', (6441, 6460), True, 'import tensorflow as tf\n'), ((6472, 6493), 'tensorflow.matmul', 'tf.matmul', (['fc1', 'fc2_W'], {}), '(fc1, fc2_W)\n', (6481, 6493), True, 'import tensorflow as tf\n'), ((6685, 6758), 'tensorflow.truncated_normal', 'tf.truncated_normal', ([], {'shape': '(84, 10)', 'mean': 'mu', 'stddev': 'sigma', 'dtype': 'tf_type'}), '(shape=(84, 10), mean=mu, stddev=sigma, dtype=tf_type)\n', (6704, 6758), True, 'import tensorflow as tf\n'), ((6793, 6820), 'tensorflow.zeros', 'tf.zeros', (['(10)'], {'dtype': 'tf_type'}), '(10, dtype=tf_type)\n', (6801, 6820), True, 'import tensorflow as tf\n'), ((6835, 6856), 'tensorflow.matmul', 'tf.matmul', (['fc2', 'fc3_W'], {}), '(fc2, fc3_W)\n', (6844, 6856), True, 'import tensorflow as tf\n'), ((10696, 10729), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (10727, 10729), True, 'import tensorflow as tf\n'), ((10856, 10881), 'sklearn.utils.shuffle', 'shuffle', (['X_train', 'y_train'], {}), '(X_train, y_train)\n', (10863, 10881), False, 'from sklearn.utils import shuffle\n'), ((12536, 12557), 'tensorflow.global_variables', 'tf.global_variables', ([], {}), '()\n', (12555, 12557), True, 'import tensorflow as tf\n'), ((14007, 14047), 'os.path.join', 'os.path.join', (['SCRIPT_DIR', 'PACKAGE_PARENT'], {}), '(SCRIPT_DIR, PACKAGE_PARENT)\n', (14019, 14047), False, 'import os\n'), ((13925, 13936), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (13934, 13936), False, 'import os\n'), ((13938, 13966), 'os.path.expanduser', 'os.path.expanduser', (['__file__'], {}), '(__file__)\n', (13956, 13966), False, 'import os\n')]
""" Implementation of Exercises/Examples from Chapter 6 of Sutton and Barto's "Reinforcement Learning" """ from gridworld import WindyGridworld import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm #%% def gen_zero_q_table(env): ''' Generate q table with zeros as initial values Returns ------- q_table : dict dict with states as keys and q-values each action as values. ''' q_table = {} for state in env.states: q_table[state] = np.zeros((len(env.action_space()))) return q_table #%% def plot(num_episodes, Returns): plt.figure() plt.plot(range(num_episodes), Returns) plt.xlabel("Episode") plt.ylabel("Steps per episode") #%% SARSA def SARSA(env, num_episodes, epsilon, epsilon_decay, alpha, gamma): """ SARSA algorithm for solving windy gridworld example 6.5 from chapter 6 of "Reinforcement learning" by Sutton and Barto """ q_table = gen_zero_q_table(env) Returns = [] for episode in tqdm(range(1, num_episodes+1)): done = False Return = 0 state = env.reset() if epsilon < np.random.uniform(0,1,1): action = np.argmax(q_table[state]) else: action = np.random.choice(env.action_space()) while not done: next_state, reward, done, final_state = env.step(state, action) if epsilon < np.random.uniform(0,1,1): next_action = np.argmax(q_table[state]) else: next_action = np.random.randint(0, len(env.action_space())) q_current = q_table[state][action] q_next = q_table[next_state][next_action] if final_state: q_new = 0 else: q_new = q_current + alpha*(reward + gamma*q_next - q_current) q_table[state][action] = q_new state = next_state action = next_action Return += reward # plot grid_world if episode == (num_episodes-1): env.render(state) epsilon *=epsilon_decay Returns.append(Return) return Returns #%% if __name__ == "__main__": num_episodes = 5000 epsilon = 0.1 epsilon_decay = 0.999 alpha = 0.5 gamma = 1 kings_moves = True x_dim = 10 y_dim = 7 initial_state = (0, 3) terminal_state = (6, 3) stochastic_wind = True env = WindyGridworld(x_dim, y_dim, kings_moves, stochastic_wind, initial_state, terminal_state) Returns = SARSA(env, num_episodes, epsilon, epsilon_decay, alpha, gamma) plot(num_episodes, Returns)
[ "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.argmax", "matplotlib.pyplot.figure", "gridworld.WindyGridworld", "numpy.random.uniform" ]
[((615, 627), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (625, 627), True, 'import matplotlib.pyplot as plt\n'), ((679, 700), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Episode"""'], {}), "('Episode')\n", (689, 700), True, 'import matplotlib.pyplot as plt\n'), ((705, 736), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Steps per episode"""'], {}), "('Steps per episode')\n", (715, 736), True, 'import matplotlib.pyplot as plt\n'), ((2616, 2709), 'gridworld.WindyGridworld', 'WindyGridworld', (['x_dim', 'y_dim', 'kings_moves', 'stochastic_wind', 'initial_state', 'terminal_state'], {}), '(x_dim, y_dim, kings_moves, stochastic_wind, initial_state,\n terminal_state)\n', (2630, 2709), False, 'from gridworld import WindyGridworld\n'), ((1178, 1204), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', '(1)'], {}), '(0, 1, 1)\n', (1195, 1204), True, 'import numpy as np\n'), ((1225, 1250), 'numpy.argmax', 'np.argmax', (['q_table[state]'], {}), '(q_table[state])\n', (1234, 1250), True, 'import numpy as np\n'), ((1466, 1492), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', '(1)'], {}), '(0, 1, 1)\n', (1483, 1492), True, 'import numpy as np\n'), ((1522, 1547), 'numpy.argmax', 'np.argmax', (['q_table[state]'], {}), '(q_table[state])\n', (1531, 1547), True, 'import numpy as np\n')]
# Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License: BSD (3-clause) import numpy as np from ..utils import logger, verbose from ..fixes import Counter from ..parallel import parallel_func from .. import pick_types, pick_info @verbose def compute_ems(epochs, conditions=None, picks=None, n_jobs=1, verbose=None): """Compute event-matched spatial filter on epochs This version operates on the entire time course. No time window needs to be specified. The result is a spatial filter at each time point and a corresponding time course. Intuitively, the result gives the similarity between the filter at each time point and the data vector (sensors) at that time point. References ---------- [1] <NAME>, <NAME>, and <NAME>, "Reducing multi-sensor data to a single time course that reveals experimental effects", BMC Neuroscience 2013, 14:122 Parameters ---------- epochs : instance of mne.Epochs The epochs. conditions : list of str | None If a list of strings, strings must match the epochs.event_id's key as well as the number of conditions supported by the objective_function. If None keys in epochs.event_id are used. picks : array-like of int | None Channels to be included. If None only good data channels are used. Defaults to None n_jobs : int Number of jobs to run in parallel. verbose : bool, str, int, or None If not None, override default verbose level (see mne.verbose). Defaults to self.verbose. Returns ------- surrogate_trials : ndarray, shape (trials, n_trials, n_time_points) The trial surrogates. mean_spatial_filter : ndarray, shape (n_channels, n_times) The set of spatial filters. conditions : ndarray, shape (n_epochs,) The conditions used. Values correspond to original event ids. """ logger.info('...computing surrogate time series. This can take some time') if picks is None: picks = pick_types(epochs.info, meg=True, eeg=True) if not len(set(Counter(epochs.events[:, 2]).values())) == 1: raise ValueError('The same number of epochs is required by ' 'this function. Please consider ' '`epochs.equalize_event_counts`') if conditions is None: conditions = epochs.event_id.keys() epochs = epochs.copy() else: epochs = epochs[conditions] epochs.drop_bad() if len(conditions) != 2: raise ValueError('Currently this function expects exactly 2 ' 'conditions but you gave me %i' % len(conditions)) ev = epochs.events[:, 2] # special care to avoid path dependent mappings and orders conditions = list(sorted(conditions)) cond_idx = [np.where(ev == epochs.event_id[k])[0] for k in conditions] info = pick_info(epochs.info, picks) data = epochs.get_data()[:, picks] # Scale (z-score) the data by channel type for ch_type in ['mag', 'grad', 'eeg']: if ch_type in epochs: if ch_type == 'eeg': this_picks = pick_types(info, meg=False, eeg=True) else: this_picks = pick_types(info, meg=ch_type, eeg=False) data[:, this_picks] /= np.std(data[:, this_picks]) try: from sklearn.model_selection import LeaveOneOut except: # XXX support sklearn < 0.18 from sklearn.cross_validation import LeaveOneOut def _iter_cv(n): # XXX support sklearn < 0.18 if hasattr(LeaveOneOut, 'split'): cv = LeaveOneOut() return cv.split(np.zeros((n, 1))) else: cv = LeaveOneOut(len(data)) return cv parallel, p_func, _ = parallel_func(_run_ems, n_jobs=n_jobs) out = parallel(p_func(_ems_diff, data, cond_idx, train, test) for train, test in _iter_cv(len(data))) surrogate_trials, spatial_filter = zip(*out) surrogate_trials = np.array(surrogate_trials) spatial_filter = np.mean(spatial_filter, axis=0) return surrogate_trials, spatial_filter, epochs.events[:, 2] def _ems_diff(data0, data1): """default diff objective function""" return np.mean(data0, axis=0) - np.mean(data1, axis=0) def _run_ems(objective_function, data, cond_idx, train, test): d = objective_function(*(data[np.intersect1d(c, train)] for c in cond_idx)) d /= np.sqrt(np.sum(d ** 2, axis=0))[None, :] # compute surrogates return np.sum(data[test[0]] * d, axis=0), d
[ "numpy.mean", "numpy.intersect1d", "numpy.where", "numpy.array", "numpy.sum", "numpy.zeros", "sklearn.cross_validation.LeaveOneOut", "numpy.std" ]
[((4052, 4078), 'numpy.array', 'np.array', (['surrogate_trials'], {}), '(surrogate_trials)\n', (4060, 4078), True, 'import numpy as np\n'), ((4100, 4131), 'numpy.mean', 'np.mean', (['spatial_filter'], {'axis': '(0)'}), '(spatial_filter, axis=0)\n', (4107, 4131), True, 'import numpy as np\n'), ((4282, 4304), 'numpy.mean', 'np.mean', (['data0'], {'axis': '(0)'}), '(data0, axis=0)\n', (4289, 4304), True, 'import numpy as np\n'), ((4307, 4329), 'numpy.mean', 'np.mean', (['data1'], {'axis': '(0)'}), '(data1, axis=0)\n', (4314, 4329), True, 'import numpy as np\n'), ((4561, 4594), 'numpy.sum', 'np.sum', (['(data[test[0]] * d)'], {'axis': '(0)'}), '(data[test[0]] * d, axis=0)\n', (4567, 4594), True, 'import numpy as np\n'), ((2864, 2898), 'numpy.where', 'np.where', (['(ev == epochs.event_id[k])'], {}), '(ev == epochs.event_id[k])\n', (2872, 2898), True, 'import numpy as np\n'), ((3348, 3375), 'numpy.std', 'np.std', (['data[:, this_picks]'], {}), '(data[:, this_picks])\n', (3354, 3375), True, 'import numpy as np\n'), ((3652, 3665), 'sklearn.cross_validation.LeaveOneOut', 'LeaveOneOut', ([], {}), '()\n', (3663, 3665), False, 'from sklearn.cross_validation import LeaveOneOut\n'), ((4492, 4514), 'numpy.sum', 'np.sum', (['(d ** 2)'], {'axis': '(0)'}), '(d ** 2, axis=0)\n', (4498, 4514), True, 'import numpy as np\n'), ((3694, 3710), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (3702, 3710), True, 'import numpy as np\n'), ((4429, 4453), 'numpy.intersect1d', 'np.intersect1d', (['c', 'train'], {}), '(c, train)\n', (4443, 4453), True, 'import numpy as np\n')]
""" This script goes along my blog post: 'Keras Cats Dogs Tutorial' (https://jkjung-avt.github.io/keras-tutorial/) """ import argparse import glob import os import sys import numpy as np from keras import backend as K from keras.applications.resnet50 import preprocess_input from keras.models import load_model from keras.preprocessing import image def parse_args(): """Parse input arguments. """ parser = argparse.ArgumentParser() parser.add_argument('path') args = parser.parse_args() return args def get_files(path): if os.path.isdir(path): files = glob.glob(os.path.join(path, '*')) elif path.find('*') > 0: files = glob.glob(path) else: files = [path] files = [f for f in files if f.endswith('JPG') or f.endswith('jpg')] if not len(files): sys.exit('No images found by the given path!') return files if __name__ == '__main__': args = parse_args() files = get_files(args.path) cls_list = ['cats', 'dogs'] # load the trained model net = load_model('model-resnet50-final.h5') # loop through all files and make predictions for i, f in enumerate(files): img = image.load_img(f, target_size=(224, 224)) if img is None: continue x = image.img_to_array(img) x = preprocess_input(x) x = np.expand_dims(x, axis=0) pred = net.predict(x)[0] pred_prob = pred[0] pred_cls = cls_list[int(round(pred_prob))] if os.path.basename(f)[:3] != pred_cls[:3]: print(i, f) print(' {:.3f} {}'.format(pred_prob, pred_cls))
[ "keras.preprocessing.image.img_to_array", "keras.models.load_model", "argparse.ArgumentParser", "keras.applications.resnet50.preprocess_input", "os.path.join", "os.path.isdir", "os.path.basename", "numpy.expand_dims", "sys.exit", "glob.glob", "keras.preprocessing.image.load_img" ]
[((423, 448), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (446, 448), False, 'import argparse\n'), ((558, 577), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (571, 577), False, 'import os\n'), ((1053, 1090), 'keras.models.load_model', 'load_model', (['"""model-resnet50-final.h5"""'], {}), "('model-resnet50-final.h5')\n", (1063, 1090), False, 'from keras.models import load_model\n'), ((830, 876), 'sys.exit', 'sys.exit', (['"""No images found by the given path!"""'], {}), "('No images found by the given path!')\n", (838, 876), False, 'import sys\n'), ((1190, 1231), 'keras.preprocessing.image.load_img', 'image.load_img', (['f'], {'target_size': '(224, 224)'}), '(f, target_size=(224, 224))\n', (1204, 1231), False, 'from keras.preprocessing import image\n'), ((1289, 1312), 'keras.preprocessing.image.img_to_array', 'image.img_to_array', (['img'], {}), '(img)\n', (1307, 1312), False, 'from keras.preprocessing import image\n'), ((1325, 1344), 'keras.applications.resnet50.preprocess_input', 'preprocess_input', (['x'], {}), '(x)\n', (1341, 1344), False, 'from keras.applications.resnet50 import preprocess_input\n'), ((1357, 1382), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (1371, 1382), True, 'import numpy as np\n'), ((605, 628), 'os.path.join', 'os.path.join', (['path', '"""*"""'], {}), "(path, '*')\n", (617, 628), False, 'import os\n'), ((675, 690), 'glob.glob', 'glob.glob', (['path'], {}), '(path)\n', (684, 690), False, 'import glob\n'), ((1506, 1525), 'os.path.basename', 'os.path.basename', (['f'], {}), '(f)\n', (1522, 1525), False, 'import os\n')]
import numpy.random import milk.unsupervised.pca import numpy as np def test_pca(): numpy.random.seed(123) X = numpy.random.rand(10,4) X[:,1] += numpy.random.rand(10)**2*X[:,0] X[:,1] += numpy.random.rand(10)**2*X[:,0] X[:,2] += numpy.random.rand(10)**2*X[:,0] Y,V = milk.unsupervised.pca(X) Xn = milk.unsupervised.normalise.zscore(X) assert X.shape == Y.shape assert ((np.dot(V[:4].T,Y[:,:4].T).T-Xn)**2).sum()/(Xn**2).sum() < .3 def test_mds(): from milk.unsupervised import pdist np.random.seed(232) for _ in xrange(12): features = np.random.random_sample((12,4)) X = milk.unsupervised.mds(features,4) D = pdist(features) D2 = pdist(X) assert np.mean( (D - D2) ** 2) < 10e-4
[ "numpy.mean", "numpy.random.random_sample", "milk.unsupervised.pdist", "numpy.dot", "numpy.random.seed" ]
[((532, 551), 'numpy.random.seed', 'np.random.seed', (['(232)'], {}), '(232)\n', (546, 551), True, 'import numpy as np\n'), ((596, 628), 'numpy.random.random_sample', 'np.random.random_sample', (['(12, 4)'], {}), '((12, 4))\n', (619, 628), True, 'import numpy as np\n'), ((686, 701), 'milk.unsupervised.pdist', 'pdist', (['features'], {}), '(features)\n', (691, 701), False, 'from milk.unsupervised import pdist\n'), ((715, 723), 'milk.unsupervised.pdist', 'pdist', (['X'], {}), '(X)\n', (720, 723), False, 'from milk.unsupervised import pdist\n'), ((739, 761), 'numpy.mean', 'np.mean', (['((D - D2) ** 2)'], {}), '((D - D2) ** 2)\n', (746, 761), True, 'import numpy as np\n'), ((410, 437), 'numpy.dot', 'np.dot', (['V[:4].T', 'Y[:, :4].T'], {}), '(V[:4].T, Y[:, :4].T)\n', (416, 437), True, 'import numpy as np\n')]
### Code by <NAME> ### ### import pyautogui import PIL def average_image_color(image): """ Code by olooney on GitHub > https://gist.github.com/olooney/1246268 Returns the average color from a given image (PIL) """ i = image h = i.histogram() # split into red, green, blue r = h[0:256] g = h[256:256*2] b = h[256*2: 256*3] # perform the weighted average of each channel: # the *index* is the channel value, and the *value* is its weight return [ sum( i*w for i, w in enumerate(r) ) / sum(r), sum( i*w for i, w in enumerate(g) ) / sum(g), sum( i*w for i, w in enumerate(b) ) / sum(b) ] if __name__ == '__main__': import sys import numpy as np import matplotlib.pyplot as plt import os os.system('cls' if os.name == 'nt' else 'clear') if len(sys.argv) > 1: refresh_rate = int(sys.argv[1]) else: refresh_rate = 10 print('Chosen refresh rate: ' + str(refresh_rate)) plt.ion() fig = plt.gcf() fig.show() fig.canvas.draw() iteration = 0 plt.title('Average Screen Color') while True: iteration += 1 image = pyautogui.screenshot() rgb = average_image_color(image) #VIZUALIZATION spikes = np.random.random(1) #To show a rectangle plt.xlabel('Average Color (RGB): ' + str(rgb)) plt.eventplot(spikes, orientation='horizontal', linelengths=0.9, linewidths=1000, color = [(rgb[0]/255, rgb[1]/255, rgb[2]/255)]) if iteration > refresh_rate: iteration = 0 plt.clf() plt.title('Average Screen Color') fig.canvas.draw() plt.pause(0.000001) def get_average_screen_color(): ''' Returns the current screen average color. ''' image = pyautogui.screenshot() rgb = average_image_color(image) return rgb
[ "matplotlib.pyplot.title", "numpy.random.random", "matplotlib.pyplot.gcf", "pyautogui.screenshot", "matplotlib.pyplot.eventplot", "matplotlib.pyplot.clf", "matplotlib.pyplot.ion", "os.system", "matplotlib.pyplot.pause" ]
[((731, 779), 'os.system', 'os.system', (["('cls' if os.name == 'nt' else 'clear')"], {}), "('cls' if os.name == 'nt' else 'clear')\n", (740, 779), False, 'import os\n'), ((941, 950), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (948, 950), True, 'import matplotlib.pyplot as plt\n'), ((962, 971), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (969, 971), True, 'import matplotlib.pyplot as plt\n'), ((1032, 1065), 'matplotlib.pyplot.title', 'plt.title', (['"""Average Screen Color"""'], {}), "('Average Screen Color')\n", (1041, 1065), True, 'import matplotlib.pyplot as plt\n'), ((1756, 1778), 'pyautogui.screenshot', 'pyautogui.screenshot', ([], {}), '()\n', (1776, 1778), False, 'import pyautogui\n'), ((1122, 1144), 'pyautogui.screenshot', 'pyautogui.screenshot', ([], {}), '()\n', (1142, 1144), False, 'import pyautogui\n'), ((1227, 1246), 'numpy.random.random', 'np.random.random', (['(1)'], {}), '(1)\n', (1243, 1246), True, 'import numpy as np\n'), ((1332, 1470), 'matplotlib.pyplot.eventplot', 'plt.eventplot', (['spikes'], {'orientation': '"""horizontal"""', 'linelengths': '(0.9)', 'linewidths': '(1000)', 'color': '[(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255)]'}), "(spikes, orientation='horizontal', linelengths=0.9, linewidths\n =1000, color=[(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255)])\n", (1345, 1470), True, 'import matplotlib.pyplot as plt\n'), ((1629, 1645), 'matplotlib.pyplot.pause', 'plt.pause', (['(1e-06)'], {}), '(1e-06)\n', (1638, 1645), True, 'import matplotlib.pyplot as plt\n'), ((1538, 1547), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1545, 1547), True, 'import matplotlib.pyplot as plt\n'), ((1560, 1593), 'matplotlib.pyplot.title', 'plt.title', (['"""Average Screen Color"""'], {}), "('Average Screen Color')\n", (1569, 1593), True, 'import matplotlib.pyplot as plt\n')]
# This file contains all the training functionality including # dataset parsing and snapshot export # Author: <NAME>, 2018, Chemnitz University of Technology import os import operator import time import numpy as np from sklearn.utils import shuffle import config as cfg from model import lasagne_net as birdnet from model import learning_rate as lr from model import lasagne_io as io from utils import image from utils import batch_generator as bg from utils import stats from utils import metrics from utils import log ################### DATASAT HANDLING #################### def isValidClass(c, path): # Do we have noise samples we want to include? if c in ['Noise']: return True # Class in S2N interval? if (int(path.split('_')[0]) >= cfg.S2N_INTERVAL[0] and int(path.split('_')[0]) <= cfg.S2N_INTERVAL[1]): return True else: return False def parseDataset(): # Random Seed random = cfg.getRandomState() # We use subfolders as class labels classes = [folder for folder in sorted(os.listdir(cfg.DATASET_PATH)) if folder in cfg.CLASS_WHITELIST or len(cfg.CLASS_WHITELIST) == 0] if not cfg.SORT_CLASSES_ALPHABETICALLY: classes = shuffle(classes, random_state=random) classes = classes[:cfg.MAX_CLASSES] # Now we enlist all image paths for each class images = [] tclasses = [] sample_count = {} for c in classes: c_images = [os.path.join(cfg.DATASET_PATH, c, path) for path in shuffle(os.listdir(os.path.join(cfg.DATASET_PATH, c)), random_state=random) if isValidClass(c, path)][:cfg.MAX_SAMPLES_PER_CLASS] sample_count[c] = len(c_images) images += c_images # Do we want to correct class imbalance? # This will affect validation scores as we use some samples in TRAIN and VAL while sample_count[c] < cfg.MIN_SAMPLES_PER_CLASS: images += [c_images[random.randint(0, len(c_images))]] sample_count[c] += 1 # Add labels to image paths for i in range(len(images)): path = images[i] label = images[i].split(os.sep)[-2] images[i] = (path, label) # Shuffle image paths images = shuffle(images, random_state=random) # Validation split vsplit = int(len(images) * cfg.VAL_SPLIT) train = images[:-vsplit] val = images[-vsplit:] # Show some stats log.i(("CLASSES:", len(classes))) log.i(( "CLASS LABELS:", sorted(sample_count.items(), key=operator.itemgetter(1)))) log.i(("TRAINING IMAGES:", len(train))) log.i(("VALIDATION IMAGES:", len(val))) return classes, train, val ####################### TRAINING ######################## def train(NET, TRAIN, VAL): # Random Seed random = cfg.getRandomState() image.resetRandomState() # Load pretrained model if cfg.PRETRAINED_MODEL_NAME: snapshot = io.loadModel(cfg.PRETRAINED_MODEL_NAME) NET = io.loadParams(NET, snapshot['params']) # Load teacher models teach_funcs = [] if len(cfg.TEACHER) > 0: for t in cfg.TEACHER: snapshot = io.loadModel(t) TEACHER = snapshot['net'] teach_funcs.append(birdnet.test_function(TEACHER, hasTargets=False)) # Compile Theano functions train_net = birdnet.train_function(NET) test_net = birdnet.test_function(NET) # Status log.i("START TRAINING...") # Train for some epochs... for epoch in range(cfg.EPOCH_START, cfg.EPOCHS + 1): try: # Stop? if cfg.DO_BREAK: break # Clear stats for every epoch stats.clearStats() stats.setValue('sample_count', len(TRAIN) + len(VAL)) # Start timer stats.tic('epoch_time') # Shuffle dataset (this way we get "new" batches every epoch) TRAIN = shuffle(TRAIN, random_state=random) # Iterate over TRAIN batches of images for image_batch, target_batch in bg.nextBatch(TRAIN): # Show progress stats.showProgress(epoch) # If we have a teacher, we use that model to get new targets if len(teach_funcs) > 0: target_batch = np.zeros((len(teach_funcs), target_batch.shape[0], target_batch.shape[1]), dtype='float32') for i in range(len(teach_funcs)): target_batch[i] = teach_funcs[i](image_batch) target_batch = np.mean(target_batch, axis=0) # Calling the training functions returns the current loss loss = train_net(image_batch, target_batch, lr.dynamicLearningRate(cfg.LR_SCHEDULE, epoch)) stats.setValue('train loss', loss, 'append') stats.setValue('batch_count', 1, 'add') # Stop? if cfg.DO_BREAK: break # Iterate over VAL batches of images for image_batch, target_batch in bg.nextBatch(VAL, False, True): # Calling the test function returns the net output, loss and accuracy prediction_batch, loss, acc = test_net(image_batch, target_batch) stats.setValue('val loss', loss, 'append') stats.setValue('val acc', acc, 'append') stats.setValue('batch_count', 1, 'add') stats.setValue('lrap', [metrics.lrap(prediction_batch, target_batch)], 'add') # Show progress stats.showProgress(epoch) # Stop? if cfg.DO_BREAK: break # Show stats for epoch stats.showProgress(epoch, done=True) stats.toc('epoch_time') log.r(('TRAIN LOSS:', np.mean(stats.getValue('train loss'))), new_line=False) log.r(('VAL LOSS:', np.mean(stats.getValue('val loss'))), new_line=False) log.r(('VAL ACC:', int(np.mean(stats.getValue('val acc')) * 10000) / 100.0, '%'), new_line=False) log.r(('MLRAP:', int(np.mean(stats.getValue('lrap')) * 1000) / 1000.0), new_line=False) log.r(('TIME:', stats.getValue('epoch_time'), 's')) # Save snapshot? if not epoch % cfg.SNAPSHOT_EPOCHS: io.saveModel(NET, cfg.CLASSES, epoch) print('vish') io.saveParams(NET, cfg.CLASSES, epoch) # New best net? if np.mean(stats.getValue('lrap')) > stats.getValue('best_mlrap'): stats.setValue('best_net', NET, static=True) stats.setValue('best_epoch', epoch, static=True) stats.setValue('best_mlrap', np.mean(stats.getValue('lrap')), static=True) # Early stopping? if epoch - stats.getValue('best_epoch') >= cfg.EARLY_STOPPING_WAIT: log.i('EARLY STOPPING!') break # Stop? if cfg.DO_BREAK: break except KeyboardInterrupt: log.i('KeyboardInterrupt') cfg.DO_BREAK = True break # Status log.i('TRAINING DONE!') log.r(('BEST MLRAP:', stats.getValue('best_mlrap'), 'EPOCH:', stats.getValue('best_epoch'))) # Save best model and return io.saveParams(stats.getValue('best_net'), cfg.CLASSES, stats.getValue('best_epoch')) print('in training vish') return io.saveModel(stats.getValue('best_net'), cfg.CLASSES, stats.getValue('best_epoch')) if __name__ == '__main__': cfg.CLASSES, TRAIN, VAL = parseDataset() NET = birdnet.build_model() net_name = train(NET, TRAIN, VAL)
[ "utils.log.i", "model.lasagne_io.loadModel", "utils.metrics.lrap", "utils.stats.tic", "model.lasagne_io.saveParams", "operator.itemgetter", "model.learning_rate.dynamicLearningRate", "utils.stats.getValue", "numpy.mean", "os.listdir", "model.lasagne_io.saveModel", "model.lasagne_net.build_mode...
[((946, 966), 'config.getRandomState', 'cfg.getRandomState', ([], {}), '()\n', (964, 966), True, 'import config as cfg\n'), ((2207, 2243), 'sklearn.utils.shuffle', 'shuffle', (['images'], {'random_state': 'random'}), '(images, random_state=random)\n', (2214, 2243), False, 'from sklearn.utils import shuffle\n'), ((2758, 2778), 'config.getRandomState', 'cfg.getRandomState', ([], {}), '()\n', (2776, 2778), True, 'import config as cfg\n'), ((2783, 2807), 'utils.image.resetRandomState', 'image.resetRandomState', ([], {}), '()\n', (2805, 2807), False, 'from utils import image\n'), ((3296, 3323), 'model.lasagne_net.train_function', 'birdnet.train_function', (['NET'], {}), '(NET)\n', (3318, 3323), True, 'from model import lasagne_net as birdnet\n'), ((3339, 3365), 'model.lasagne_net.test_function', 'birdnet.test_function', (['NET'], {}), '(NET)\n', (3360, 3365), True, 'from model import lasagne_net as birdnet\n'), ((3384, 3410), 'utils.log.i', 'log.i', (['"""START TRAINING..."""'], {}), "('START TRAINING...')\n", (3389, 3410), False, 'from utils import log\n'), ((7192, 7215), 'utils.log.i', 'log.i', (['"""TRAINING DONE!"""'], {}), "('TRAINING DONE!')\n", (7197, 7215), False, 'from utils import log\n'), ((7645, 7666), 'model.lasagne_net.build_model', 'birdnet.build_model', ([], {}), '()\n', (7664, 7666), True, 'from model import lasagne_net as birdnet\n'), ((1210, 1247), 'sklearn.utils.shuffle', 'shuffle', (['classes'], {'random_state': 'random'}), '(classes, random_state=random)\n', (1217, 1247), False, 'from sklearn.utils import shuffle\n'), ((2890, 2929), 'model.lasagne_io.loadModel', 'io.loadModel', (['cfg.PRETRAINED_MODEL_NAME'], {}), '(cfg.PRETRAINED_MODEL_NAME)\n', (2902, 2929), True, 'from model import lasagne_io as io\n'), ((2944, 2982), 'model.lasagne_io.loadParams', 'io.loadParams', (['NET', "snapshot['params']"], {}), "(NET, snapshot['params'])\n", (2957, 2982), True, 'from model import lasagne_io as io\n'), ((7365, 7391), 'utils.stats.getValue', 'stats.getValue', (['"""best_net"""'], {}), "('best_net')\n", (7379, 7391), False, 'from utils import stats\n'), ((7406, 7434), 'utils.stats.getValue', 'stats.getValue', (['"""best_epoch"""'], {}), "('best_epoch')\n", (7420, 7434), False, 'from utils import stats\n'), ((7490, 7516), 'utils.stats.getValue', 'stats.getValue', (['"""best_net"""'], {}), "('best_net')\n", (7504, 7516), False, 'from utils import stats\n'), ((7531, 7559), 'utils.stats.getValue', 'stats.getValue', (['"""best_epoch"""'], {}), "('best_epoch')\n", (7545, 7559), False, 'from utils import stats\n'), ((3113, 3128), 'model.lasagne_io.loadModel', 'io.loadModel', (['t'], {}), '(t)\n', (3125, 3128), True, 'from model import lasagne_io as io\n'), ((3641, 3659), 'utils.stats.clearStats', 'stats.clearStats', ([], {}), '()\n', (3657, 3659), False, 'from utils import stats\n'), ((3765, 3788), 'utils.stats.tic', 'stats.tic', (['"""epoch_time"""'], {}), "('epoch_time')\n", (3774, 3788), False, 'from utils import stats\n'), ((3896, 3931), 'sklearn.utils.shuffle', 'shuffle', (['TRAIN'], {'random_state': 'random'}), '(TRAIN, random_state=random)\n', (3903, 3931), False, 'from sklearn.utils import shuffle\n'), ((4029, 4048), 'utils.batch_generator.nextBatch', 'bg.nextBatch', (['TRAIN'], {}), '(TRAIN)\n', (4041, 4048), True, 'from utils import batch_generator as bg\n'), ((5055, 5085), 'utils.batch_generator.nextBatch', 'bg.nextBatch', (['VAL', '(False)', '(True)'], {}), '(VAL, False, True)\n', (5067, 5085), True, 'from utils import batch_generator as bg\n'), ((5729, 5765), 'utils.stats.showProgress', 'stats.showProgress', (['epoch'], {'done': '(True)'}), '(epoch, done=True)\n', (5747, 5765), False, 'from utils import stats\n'), ((5778, 5801), 'utils.stats.toc', 'stats.toc', (['"""epoch_time"""'], {}), "('epoch_time')\n", (5787, 5801), False, 'from utils import stats\n'), ((7242, 7270), 'utils.stats.getValue', 'stats.getValue', (['"""best_mlrap"""'], {}), "('best_mlrap')\n", (7256, 7270), False, 'from utils import stats\n'), ((7282, 7310), 'utils.stats.getValue', 'stats.getValue', (['"""best_epoch"""'], {}), "('best_epoch')\n", (7296, 7310), False, 'from utils import stats\n'), ((1051, 1079), 'os.listdir', 'os.listdir', (['cfg.DATASET_PATH'], {}), '(cfg.DATASET_PATH)\n', (1061, 1079), False, 'import os\n'), ((1438, 1477), 'os.path.join', 'os.path.join', (['cfg.DATASET_PATH', 'c', 'path'], {}), '(cfg.DATASET_PATH, c, path)\n', (1450, 1477), False, 'import os\n'), ((3198, 3246), 'model.lasagne_net.test_function', 'birdnet.test_function', (['TEACHER'], {'hasTargets': '(False)'}), '(TEACHER, hasTargets=False)\n', (3219, 3246), True, 'from model import lasagne_net as birdnet\n'), ((4099, 4124), 'utils.stats.showProgress', 'stats.showProgress', (['epoch'], {}), '(epoch)\n', (4117, 4124), False, 'from utils import stats\n'), ((4775, 4819), 'utils.stats.setValue', 'stats.setValue', (['"""train loss"""', 'loss', '"""append"""'], {}), "('train loss', loss, 'append')\n", (4789, 4819), False, 'from utils import stats\n'), ((4836, 4875), 'utils.stats.setValue', 'stats.setValue', (['"""batch_count"""', '(1)', '"""add"""'], {}), "('batch_count', 1, 'add')\n", (4850, 4875), False, 'from utils import stats\n'), ((5272, 5314), 'utils.stats.setValue', 'stats.setValue', (['"""val loss"""', 'loss', '"""append"""'], {}), "('val loss', loss, 'append')\n", (5286, 5314), False, 'from utils import stats\n'), ((5331, 5371), 'utils.stats.setValue', 'stats.setValue', (['"""val acc"""', 'acc', '"""append"""'], {}), "('val acc', acc, 'append')\n", (5345, 5371), False, 'from utils import stats\n'), ((5388, 5427), 'utils.stats.setValue', 'stats.setValue', (['"""batch_count"""', '(1)', '"""add"""'], {}), "('batch_count', 1, 'add')\n", (5402, 5427), False, 'from utils import stats\n'), ((5571, 5596), 'utils.stats.showProgress', 'stats.showProgress', (['epoch'], {}), '(epoch)\n', (5589, 5596), False, 'from utils import stats\n'), ((6356, 6393), 'model.lasagne_io.saveModel', 'io.saveModel', (['NET', 'cfg.CLASSES', 'epoch'], {}), '(NET, cfg.CLASSES, epoch)\n', (6368, 6393), True, 'from model import lasagne_io as io\n'), ((6440, 6478), 'model.lasagne_io.saveParams', 'io.saveParams', (['NET', 'cfg.CLASSES', 'epoch'], {}), '(NET, cfg.CLASSES, epoch)\n', (6453, 6478), True, 'from model import lasagne_io as io\n'), ((6557, 6585), 'utils.stats.getValue', 'stats.getValue', (['"""best_mlrap"""'], {}), "('best_mlrap')\n", (6571, 6585), False, 'from utils import stats\n'), ((6603, 6647), 'utils.stats.setValue', 'stats.setValue', (['"""best_net"""', 'NET'], {'static': '(True)'}), "('best_net', NET, static=True)\n", (6617, 6647), False, 'from utils import stats\n'), ((6664, 6712), 'utils.stats.setValue', 'stats.setValue', (['"""best_epoch"""', 'epoch'], {'static': '(True)'}), "('best_epoch', epoch, static=True)\n", (6678, 6712), False, 'from utils import stats\n'), ((6931, 6955), 'utils.log.i', 'log.i', (['"""EARLY STOPPING!"""'], {}), "('EARLY STOPPING!')\n", (6936, 6955), False, 'from utils import log\n'), ((7097, 7123), 'utils.log.i', 'log.i', (['"""KeyboardInterrupt"""'], {}), "('KeyboardInterrupt')\n", (7102, 7123), False, 'from utils import log\n'), ((2493, 2515), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (2512, 2515), False, 'import operator\n'), ((4530, 4559), 'numpy.mean', 'np.mean', (['target_batch'], {'axis': '(0)'}), '(target_batch, axis=0)\n', (4537, 4559), True, 'import numpy as np\n'), ((4711, 4757), 'model.learning_rate.dynamicLearningRate', 'lr.dynamicLearningRate', (['cfg.LR_SCHEDULE', 'epoch'], {}), '(cfg.LR_SCHEDULE, epoch)\n', (4733, 4757), True, 'from model import learning_rate as lr\n'), ((6226, 6254), 'utils.stats.getValue', 'stats.getValue', (['"""epoch_time"""'], {}), "('epoch_time')\n", (6240, 6254), False, 'from utils import stats\n'), ((6531, 6553), 'utils.stats.getValue', 'stats.getValue', (['"""lrap"""'], {}), "('lrap')\n", (6545, 6553), False, 'from utils import stats\n'), ((6858, 6886), 'utils.stats.getValue', 'stats.getValue', (['"""best_epoch"""'], {}), "('best_epoch')\n", (6872, 6886), False, 'from utils import stats\n'), ((5468, 5512), 'utils.metrics.lrap', 'metrics.lrap', (['prediction_batch', 'target_batch'], {}), '(prediction_batch, target_batch)\n', (5480, 5512), False, 'from utils import metrics\n'), ((5844, 5872), 'utils.stats.getValue', 'stats.getValue', (['"""train loss"""'], {}), "('train loss')\n", (5858, 5872), False, 'from utils import stats\n'), ((5932, 5958), 'utils.stats.getValue', 'stats.getValue', (['"""val loss"""'], {}), "('val loss')\n", (5946, 5958), False, 'from utils import stats\n'), ((6766, 6788), 'utils.stats.getValue', 'stats.getValue', (['"""lrap"""'], {}), "('lrap')\n", (6780, 6788), False, 'from utils import stats\n'), ((1509, 1542), 'os.path.join', 'os.path.join', (['cfg.DATASET_PATH', 'c'], {}), '(cfg.DATASET_PATH, c)\n', (1521, 1542), False, 'import os\n'), ((6021, 6046), 'utils.stats.getValue', 'stats.getValue', (['"""val acc"""'], {}), "('val acc')\n", (6035, 6046), False, 'from utils import stats\n'), ((6139, 6161), 'utils.stats.getValue', 'stats.getValue', (['"""lrap"""'], {}), "('lrap')\n", (6153, 6161), False, 'from utils import stats\n')]
import cv2 import sys import numpy as np import scipy.spatial.distance as ssd from tstab import * def get_bijective_pairs(pairs,costmat): bij_pairs = bij_pairs_one_dim(pairs, costmat,0) bij_pairs = bij_pairs_one_dim(bij_pairs, costmat.T,1) return bij_pairs def bij_pairs_one_dim(pairs, costmat, left_or_right): bij_pairs = [] ids1 = np.unique(pairs[:,left_or_right]) for ii in range(len(ids1)): curr_pairs = pairs[pairs[:,left_or_right]==ids1[ii],:].astype(np.int) curr_costs = costmat[curr_pairs[:,left_or_right], curr_pairs[:,1-left_or_right]] b = np.argmin(curr_costs) bij_pairs.append(curr_pairs[b]) return np.array(bij_pairs) def hist_cost_2(BH1,BH2): nsamp1,nbins=BH1.shape nsamp2,nbins=BH2.shape eps = 2.2204e-16 BH1n = BH1 / (np.sum(BH1,axis=1,keepdims=True)+eps) BH2n = BH2 / (np.sum(BH2,axis=1,keepdims=True)+eps) tmp1 = np.tile(np.transpose(np.atleast_3d(BH1n),[0,2,1]),(1,nsamp2,1)) tmp2 = np.tile(np.transpose(np.atleast_3d(BH2n.T),[2,1,0]),(nsamp1,1,1)) HC = 0.5*np.sum((tmp1-tmp2)**2/(tmp1+tmp2+eps),axis=2) return HC def sc_compute(Bsamp,Tsamp,mean_dist,nbins_theta,nbins_r,r_inner,r_outer,out_vec): in_vec = (out_vec==0).ravel() nsamp = Bsamp.shape[1] r_array=ssd.squareform(ssd.pdist(Bsamp.T)).T theta_array_abs0=Bsamp[1,:].reshape(-1,1).dot(np.ones((1,nsamp))) - \ np.ones((nsamp,1)).dot(Bsamp[1,:].reshape(1,-1)) theta_array_abs1=Bsamp[0,:].reshape(-1,1).dot(np.ones((1,nsamp))) - \ np.ones((nsamp,1)).dot(Bsamp[0,:].reshape(1,-1)) theta_array_abs = np.arctan2(theta_array_abs0,theta_array_abs1).T theta_array=theta_array_abs-Tsamp.T.dot(np.ones((1,nsamp))) if mean_dist is None: mean_dist = np.mean(r_array[in_vec].T[in_vec].T) r_array_n = r_array / mean_dist r_bin_edges=np.logspace(np.log10(r_inner),np.log10(r_outer),nbins_r) r_array_q=np.zeros((nsamp,nsamp)) for m in range(int(nbins_r)): r_array_q=r_array_q+(r_array_n<r_bin_edges[m]) fz = r_array_q > 0 theta_array_2 = np.fmod(np.fmod(theta_array,2*np.pi)+2*np.pi,2*np.pi) theta_array_q = 1+np.floor(theta_array_2/(2*np.pi/nbins_theta)) nbins=nbins_theta*nbins_r BH=np.zeros((nsamp,nbins)) count = 0 for n in range(nsamp): fzn=fz[n]&in_vec Sn = np.zeros((nbins_theta,nbins_r)) coords = np.hstack((theta_array_q[n,fzn].reshape(-1,1), r_array_q[n,fzn].astype(np.int).reshape(-1,1))) # SLOW... #for i,j in coords: #Sn[i-1,j-1] += 1 # FASTER ids = np.ravel_multi_index((coords.T-1).astype(np.int),Sn.shape) Sn = np.bincount(ids.ravel(),minlength = np.prod(Sn.shape)).reshape(Sn.shape) BH[n,:] = Sn.T[:].ravel() return BH.astype(np.int),mean_dist def db_eval_t_stab(fgmask,ground_truth,timing=True): """ Calculates the temporal stability index between two masks Arguments: fgmask (ndarray): Foreground Object mask at frame t ground_truth (ndarray): Foreground Object mask at frame t+1 Return: T (ndarray): Temporal (in-)stability raw_results (ndarray): Supplemental values """ cont_th = 3 cont_th_up = 3 # Shape context parameters r_inner = 1.0/8.0 r_outer = 2.0 nbins_r = 5.0 nbins_theta = 12.0 poly1 = mask2poly(fgmask,cont_th) poly2 = mask2poly(ground_truth,cont_th) if len(poly1.contour_coords) == 0 or \ len(poly2.contour_coords) == 0: return np.nan Cs1 = get_longest_cont(poly1.contour_coords) Cs2 = get_longest_cont(poly2.contour_coords) upCs1 = contour_upsample(Cs1,cont_th_up) upCs2 = contour_upsample(Cs2,cont_th_up) scs1,_=sc_compute(upCs1.T,np.zeros((1,upCs1.shape[0])),None, nbins_theta,nbins_r,r_inner,r_outer,np.zeros((1,upCs1.shape[0]))) scs2,_=sc_compute(upCs2.T,np.zeros((1,upCs2.shape[0])),None, nbins_theta,nbins_r,r_inner,r_outer,np.zeros((1,upCs2.shape[0]))) # Match with the 0-0 alignment costmat = hist_cost_2(scs1,scs2) pairs ,max_sx,max_sy = match_dijkstra(np.ascontiguousarray(costmat)) # Shift costmat costmat2 = np.roll(costmat ,-(max_sy+1),axis=1) costmat2 = np.roll(costmat2,-(max_sx+1),axis=0) # Redo again with the correct alignment pairs,_,_ = match_dijkstra(costmat2) # Put the pairs back to the original place pairs[:,0] = np.mod(pairs[:,0]+max_sx+1, costmat.shape[0]) pairs[:,1] = np.mod(pairs[:,1]+max_sy+1, costmat.shape[1]) pairs = get_bijective_pairs(pairs,costmat) pairs_cost = costmat[pairs[:,0], pairs[:,1]] min_cost = np.average(pairs_cost) return min_cost
[ "numpy.mean", "numpy.prod", "numpy.log10", "numpy.roll", "numpy.unique", "numpy.ones", "numpy.average", "scipy.spatial.distance.pdist", "numpy.floor", "numpy.ascontiguousarray", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.arctan2", "numpy.fmod", "numpy.argmin", "numpy.mod", "...
[((347, 381), 'numpy.unique', 'np.unique', (['pairs[:, left_or_right]'], {}), '(pairs[:, left_or_right])\n', (356, 381), True, 'import numpy as np\n'), ((637, 656), 'numpy.array', 'np.array', (['bij_pairs'], {}), '(bij_pairs)\n', (645, 656), True, 'import numpy as np\n'), ((1827, 1851), 'numpy.zeros', 'np.zeros', (['(nsamp, nsamp)'], {}), '((nsamp, nsamp))\n', (1835, 1851), True, 'import numpy as np\n'), ((2121, 2145), 'numpy.zeros', 'np.zeros', (['(nsamp, nbins)'], {}), '((nsamp, nbins))\n', (2129, 2145), True, 'import numpy as np\n'), ((3924, 3963), 'numpy.roll', 'np.roll', (['costmat', '(-(max_sy + 1))'], {'axis': '(1)'}), '(costmat, -(max_sy + 1), axis=1)\n', (3931, 3963), True, 'import numpy as np\n'), ((3973, 4013), 'numpy.roll', 'np.roll', (['costmat2', '(-(max_sx + 1))'], {'axis': '(0)'}), '(costmat2, -(max_sx + 1), axis=0)\n', (3980, 4013), True, 'import numpy as np\n'), ((4149, 4199), 'numpy.mod', 'np.mod', (['(pairs[:, 0] + max_sx + 1)', 'costmat.shape[0]'], {}), '(pairs[:, 0] + max_sx + 1, costmat.shape[0])\n', (4155, 4199), True, 'import numpy as np\n'), ((4209, 4259), 'numpy.mod', 'np.mod', (['(pairs[:, 1] + max_sy + 1)', 'costmat.shape[1]'], {}), '(pairs[:, 1] + max_sy + 1, costmat.shape[1])\n', (4215, 4259), True, 'import numpy as np\n'), ((4361, 4383), 'numpy.average', 'np.average', (['pairs_cost'], {}), '(pairs_cost)\n', (4371, 4383), True, 'import numpy as np\n'), ((572, 593), 'numpy.argmin', 'np.argmin', (['curr_costs'], {}), '(curr_costs)\n', (581, 593), True, 'import numpy as np\n'), ((1016, 1072), 'numpy.sum', 'np.sum', (['((tmp1 - tmp2) ** 2 / (tmp1 + tmp2 + eps))'], {'axis': '(2)'}), '((tmp1 - tmp2) ** 2 / (tmp1 + tmp2 + eps), axis=2)\n', (1022, 1072), True, 'import numpy as np\n'), ((1527, 1573), 'numpy.arctan2', 'np.arctan2', (['theta_array_abs0', 'theta_array_abs1'], {}), '(theta_array_abs0, theta_array_abs1)\n', (1537, 1573), True, 'import numpy as np\n'), ((1674, 1710), 'numpy.mean', 'np.mean', (['r_array[in_vec].T[in_vec].T'], {}), '(r_array[in_vec].T[in_vec].T)\n', (1681, 1710), True, 'import numpy as np\n'), ((1771, 1788), 'numpy.log10', 'np.log10', (['r_inner'], {}), '(r_inner)\n', (1779, 1788), True, 'import numpy as np\n'), ((1789, 1806), 'numpy.log10', 'np.log10', (['r_outer'], {}), '(r_outer)\n', (1797, 1806), True, 'import numpy as np\n'), ((2043, 2094), 'numpy.floor', 'np.floor', (['(theta_array_2 / (2 * np.pi / nbins_theta))'], {}), '(theta_array_2 / (2 * np.pi / nbins_theta))\n', (2051, 2094), True, 'import numpy as np\n'), ((2206, 2238), 'numpy.zeros', 'np.zeros', (['(nbins_theta, nbins_r)'], {}), '((nbins_theta, nbins_r))\n', (2214, 2238), True, 'import numpy as np\n'), ((3507, 3536), 'numpy.zeros', 'np.zeros', (['(1, upCs1.shape[0])'], {}), '((1, upCs1.shape[0]))\n', (3515, 3536), True, 'import numpy as np\n'), ((3581, 3610), 'numpy.zeros', 'np.zeros', (['(1, upCs1.shape[0])'], {}), '((1, upCs1.shape[0]))\n', (3589, 3610), True, 'import numpy as np\n'), ((3639, 3668), 'numpy.zeros', 'np.zeros', (['(1, upCs2.shape[0])'], {}), '((1, upCs2.shape[0]))\n', (3647, 3668), True, 'import numpy as np\n'), ((3713, 3742), 'numpy.zeros', 'np.zeros', (['(1, upCs2.shape[0])'], {}), '((1, upCs2.shape[0]))\n', (3721, 3742), True, 'import numpy as np\n'), ((3862, 3891), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['costmat'], {}), '(costmat)\n', (3882, 3891), True, 'import numpy as np\n'), ((768, 802), 'numpy.sum', 'np.sum', (['BH1'], {'axis': '(1)', 'keepdims': '(True)'}), '(BH1, axis=1, keepdims=True)\n', (774, 802), True, 'import numpy as np\n'), ((821, 855), 'numpy.sum', 'np.sum', (['BH2'], {'axis': '(1)', 'keepdims': '(True)'}), '(BH2, axis=1, keepdims=True)\n', (827, 855), True, 'import numpy as np\n'), ((889, 908), 'numpy.atleast_3d', 'np.atleast_3d', (['BH1n'], {}), '(BH1n)\n', (902, 908), True, 'import numpy as np\n'), ((961, 982), 'numpy.atleast_3d', 'np.atleast_3d', (['BH2n.T'], {}), '(BH2n.T)\n', (974, 982), True, 'import numpy as np\n'), ((1237, 1255), 'scipy.spatial.distance.pdist', 'ssd.pdist', (['Bsamp.T'], {}), '(Bsamp.T)\n', (1246, 1255), True, 'import scipy.spatial.distance as ssd\n'), ((1307, 1326), 'numpy.ones', 'np.ones', (['(1, nsamp)'], {}), '((1, nsamp))\n', (1314, 1326), True, 'import numpy as np\n'), ((1431, 1450), 'numpy.ones', 'np.ones', (['(1, nsamp)'], {}), '((1, nsamp))\n', (1438, 1450), True, 'import numpy as np\n'), ((1616, 1635), 'numpy.ones', 'np.ones', (['(1, nsamp)'], {}), '((1, nsamp))\n', (1623, 1635), True, 'import numpy as np\n'), ((1978, 2009), 'numpy.fmod', 'np.fmod', (['theta_array', '(2 * np.pi)'], {}), '(theta_array, 2 * np.pi)\n', (1985, 2009), True, 'import numpy as np\n'), ((1334, 1353), 'numpy.ones', 'np.ones', (['(nsamp, 1)'], {}), '((nsamp, 1))\n', (1341, 1353), True, 'import numpy as np\n'), ((1458, 1477), 'numpy.ones', 'np.ones', (['(nsamp, 1)'], {}), '((nsamp, 1))\n', (1465, 1477), True, 'import numpy as np\n'), ((2526, 2543), 'numpy.prod', 'np.prod', (['Sn.shape'], {}), '(Sn.shape)\n', (2533, 2543), True, 'import numpy as np\n')]
import cmocean import matplotlib.pyplot as plt import numpy as np from matplotlib import cm from scipy import interpolate cmap = cm.ScalarMappable(cmap=cmocean.cm.phase) cmap.to_rgba([0., 0.5, 1.]) def make_item(c, f, n=None): theta = [0] clr = cmap.to_rgba(c) if not n: n = np.random.randint(3, 9) m = 2 * np.pi / n for j in range(n): a = (j * m) + (np.random.rand() * m) theta.append(a) theta.append(2 * np.pi) theta = np.array(theta) + np.random.uniform(0, 2 * np.pi) r = np.random.uniform(0.2, 1, len(theta)) r[-1] = r[0] x = r * np.cos(theta) y = r * np.sin(theta) tck, u = interpolate.splprep([x, y], s=0, t=1) unew = np.arange(0, 1.01, 0.01) out = interpolate.splev(unew, tck) theta = np.linspace(0, 2 * np.pi, 100) # the radius of the circle r = np.sqrt(0.6) # compute x1 and x2 x = r * np.cos(theta) y = r * np.sin(theta) fig, ax = plt.subplots(1, figsize=(1, 1)) ax.plot(out[0], out[1], "k", lw=2) ax.fill(out[0], out[1], c=clr) # ax.plot(x, y, "k", lw=2) # ax.fill(x, y, c=clr) plt.tick_params( left=False, labelleft=False, right=False, bottom=False, labelbottom=False ) plt.box(False) plt.tight_layout(0) p = "/Users/sm2286/Documents/Projects/Charlie2/charlie2/stimuli/visual/visualmemory/" f = p + f plt.savefig(f, transparent=True) plt.close(fig) if __name__ == "__main__": for load in [4]: for trial in range(30): # n_ = list(range(5, 12)) # np.random.shuffle(n_) clrs = [] for item in range(load): # if item == 0: # clrs.append(np.random.uniform(0, 1)) # c = clrs[0] # else: # while any(abs(c - c_) <= 0.01 for c_ in clrs): c = np.random.uniform(0, 1) # clrs.append(c) f = "l%i_t%i_i%i.png" % (load, trial, item) make_item(c, f) if item == 0: if c > 0.5: c -= 0.5 else: c += 0.5 f = "l%i_t%i_i%i_r.png" % (load, trial, item) make_item(c, f)
[ "matplotlib.pyplot.box", "numpy.sqrt", "matplotlib.pyplot.savefig", "scipy.interpolate.splprep", "numpy.random.rand", "numpy.sin", "matplotlib.pyplot.tick_params", "matplotlib.pyplot.close", "numpy.array", "numpy.linspace", "matplotlib.cm.ScalarMappable", "scipy.interpolate.splev", "numpy.ra...
[((130, 170), 'matplotlib.cm.ScalarMappable', 'cm.ScalarMappable', ([], {'cmap': 'cmocean.cm.phase'}), '(cmap=cmocean.cm.phase)\n', (147, 170), False, 'from matplotlib import cm\n'), ((654, 691), 'scipy.interpolate.splprep', 'interpolate.splprep', (['[x, y]'], {'s': '(0)', 't': '(1)'}), '([x, y], s=0, t=1)\n', (673, 691), False, 'from scipy import interpolate\n'), ((703, 727), 'numpy.arange', 'np.arange', (['(0)', '(1.01)', '(0.01)'], {}), '(0, 1.01, 0.01)\n', (712, 727), True, 'import numpy as np\n'), ((738, 766), 'scipy.interpolate.splev', 'interpolate.splev', (['unew', 'tck'], {}), '(unew, tck)\n', (755, 766), False, 'from scipy import interpolate\n'), ((780, 810), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(100)'], {}), '(0, 2 * np.pi, 100)\n', (791, 810), True, 'import numpy as np\n'), ((851, 863), 'numpy.sqrt', 'np.sqrt', (['(0.6)'], {}), '(0.6)\n', (858, 863), True, 'import numpy as np\n'), ((956, 987), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {'figsize': '(1, 1)'}), '(1, figsize=(1, 1))\n', (968, 987), True, 'import matplotlib.pyplot as plt\n'), ((1125, 1219), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'left': '(False)', 'labelleft': '(False)', 'right': '(False)', 'bottom': '(False)', 'labelbottom': '(False)'}), '(left=False, labelleft=False, right=False, bottom=False,\n labelbottom=False)\n', (1140, 1219), True, 'import matplotlib.pyplot as plt\n'), ((1234, 1248), 'matplotlib.pyplot.box', 'plt.box', (['(False)'], {}), '(False)\n', (1241, 1248), True, 'import matplotlib.pyplot as plt\n'), ((1253, 1272), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', (['(0)'], {}), '(0)\n', (1269, 1272), True, 'import matplotlib.pyplot as plt\n'), ((1381, 1413), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f'], {'transparent': '(True)'}), '(f, transparent=True)\n', (1392, 1413), True, 'import matplotlib.pyplot as plt\n'), ((1418, 1432), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (1427, 1432), True, 'import matplotlib.pyplot as plt\n'), ((298, 321), 'numpy.random.randint', 'np.random.randint', (['(3)', '(9)'], {}), '(3, 9)\n', (315, 321), True, 'import numpy as np\n'), ((476, 491), 'numpy.array', 'np.array', (['theta'], {}), '(theta)\n', (484, 491), True, 'import numpy as np\n'), ((494, 525), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(2 * np.pi)'], {}), '(0, 2 * np.pi)\n', (511, 525), True, 'import numpy as np\n'), ((601, 614), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (607, 614), True, 'import numpy as np\n'), ((627, 640), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (633, 640), True, 'import numpy as np\n'), ((901, 914), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (907, 914), True, 'import numpy as np\n'), ((927, 940), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (933, 940), True, 'import numpy as np\n'), ((390, 406), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (404, 406), True, 'import numpy as np\n'), ((1887, 1910), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (1904, 1910), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = '<NAME>' # built-in modules import logging import argparse # Standard modules import cv2 import numpy as np import skimage import skimage.measure import skimage.segmentation # Custom modules import scripts logger = logging.getLogger('main') def get_masks(img, n_seg=250): """ Old version mask creator w/ SLIC (Simple Linear Iterative Clustering) :param img: image :param n_seg: number of segments """ logger.debug('SLIC segmentation initialised') segments = skimage.segmentation.slic(img, n_segments=n_seg, compactness=10, sigma=1) logger.debug('SLIC segmentation complete') logger.debug('contour extraction...') masks = [[np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8), None]] for region in skimage.measure.regionprops(segments): masks.append([masks[0][0].copy(), region.bbox]) x_min, y_min, x_max, y_max = region.bbox masks[-1][0][x_min:x_max, y_min:y_max] = skimage.img_as_ubyte(region.convex_image) logger.debug('contours extracted') return masks[1:] def blur_mask_old(img): """ Old version for masking :param img: image """ assert isinstance(img, np.ndarray), 'img_col must be a numpy array' assert img.ndim == 3, 'img_col must be a color image ({0} dimensions currently)'.format(img.ndim) blur_mask = np.zeros(img.shape[:2], dtype=np.uint8) for mask, loc in get_masks(img): logger.debug('Checking Mask: {0}'.format(np.unique(mask))) logger.debug('SuperPixel Mask Percentage: {0}%'.format(int((100.0 / 255.0) * (np.sum(mask) / mask.size)))) _, _, blurry = blur_detector(img[loc[0]:loc[2], loc[1]:loc[3]]) logger.debug('Blurry: {0}'.format(blurry)) if blurry: blur_mask = cv2.add(blur_mask, mask) result = np.sum(blur_mask) / (255.0 * blur_mask.size) logger.info('{0}% of input image is blurry'.format(int(100 * result))) return blur_mask, result def morphology(msk): """ Apply erosion and dilation operators :param msk: mask """ assert isinstance(msk, np.ndarray), 'msk must be a numpy array' assert msk.ndim == 2, 'msk must be a greyscale image' kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) msk = cv2.erode(msk, kernel, iterations=1) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) msk = cv2.morphologyEx(msk, cv2.MORPH_CLOSE, kernel) msk[msk < 128] = 0 msk[msk > 127] = 255 return msk def remove_border(msk, width=50): """ Whiten mask borders :param msk: mask :param width: width to remove """ assert isinstance(msk, np.ndarray), 'msk must be a numpy array' assert msk.ndim == 2, 'msk must be a greyscale image' dh, dw = map(lambda i: i // width, msk.shape) h, w = msk.shape msk[:dh, :] = 255 msk[h-dh:, :] = 255 msk[:, :dw] = 255 msk[:, w-dw:] = 255 return msk def blur_mask(img): """ Get blur mask in image :param img: image """ assert isinstance(img, np.ndarray), 'img_col must be a numpy array' assert img.ndim == 3, 'img_col must be a color image ({0} dimensions currently)'.format(img.ndim) msk, _, blurry = blur_detector(img) logger.debug('inverting img_fft') msk = cv2.convertScaleAbs(255 - (255 * msk / np.max(msk))) msk[msk < 50] = 0 msk[msk > 127] = 255 logger.debug('removing border') msk = remove_border(msk) logger.debug('applying erosion and dilation operators') msk = morphology(msk) logger.debug('evaluation complete') result = np.sum(msk) / (255.0 * msk.size) logger.info('{0}% of input image is blurry'.format(int(100 * result))) return msk, result, blurry def evaluate(img_col, args): """ Evaluate blur within image :param img_col: image :param args: arguments """ np.seterr(all='ignore') assert isinstance(img_col, np.ndarray), 'img_col must be a numpy array' assert img_col.ndim == 3, 'img_col must be a color image ({0} dimensions currently)'.format(img_col.ndim) assert isinstance(args, argparse.Namespace), 'args must be of type argparse.Namespace not {0}'.format(type(args)) img_gry = cv2.cvtColor(img_col, cv2.COLOR_RGB2GRAY) rows, cols = img_gry.shape crow, ccol = rows // 2, cols // 2 f = np.fft.fft2(img_gry) fshift = np.fft.fftshift(f) fshift[crow-75:crow+75, ccol-75:ccol+75] = 0 f_ishift = np.fft.ifftshift(fshift) img_fft = np.fft.ifft2(f_ishift) img_fft = 20 * np.log(np.abs(img_fft)) if args.display and not args.testing: cv2.destroyAllWindows() scripts.display('img_fft', img_fft) scripts.display('img_col', img_col) cv2.waitKey(0) result = np.mean(img_fft) return img_fft, result, result < args.thresh def blur_detector(img_col, thresh=10, mask=False): """ Detect blurs :param img_col: image :param thresh: threshold :param mask: if mask """ assert isinstance(img_col, np.ndarray), 'img_col must be a numpy array' assert img_col.ndim == 3, 'img_col must be a color image ({0} dimensions currently)'.format(img_col.ndim) args = scripts.gen_args() args.thresh = thresh if mask: return blur_mask(img_col) else: return evaluate(img_col=img_col, args=args)
[ "logging.getLogger", "cv2.destroyAllWindows", "cv2.getStructuringElement", "numpy.mean", "cv2.erode", "numpy.fft.fft2", "numpy.max", "skimage.img_as_ubyte", "cv2.waitKey", "cv2.add", "numpy.abs", "skimage.measure.regionprops", "cv2.morphologyEx", "scripts.gen_args", "cv2.cvtColor", "nu...
[((276, 301), 'logging.getLogger', 'logging.getLogger', (['"""main"""'], {}), "('main')\n", (293, 301), False, 'import logging\n'), ((549, 622), 'skimage.segmentation.slic', 'skimage.segmentation.slic', (['img'], {'n_segments': 'n_seg', 'compactness': '(10)', 'sigma': '(1)'}), '(img, n_segments=n_seg, compactness=10, sigma=1)\n', (574, 622), False, 'import skimage\n'), ((812, 849), 'skimage.measure.regionprops', 'skimage.measure.regionprops', (['segments'], {}), '(segments)\n', (839, 849), False, 'import skimage\n'), ((1399, 1438), 'numpy.zeros', 'np.zeros', (['img.shape[:2]'], {'dtype': 'np.uint8'}), '(img.shape[:2], dtype=np.uint8)\n', (1407, 1438), True, 'import numpy as np\n'), ((2270, 2322), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_ELLIPSE', '(5, 5)'], {}), '(cv2.MORPH_ELLIPSE, (5, 5))\n', (2295, 2322), False, 'import cv2\n'), ((2333, 2369), 'cv2.erode', 'cv2.erode', (['msk', 'kernel'], {'iterations': '(1)'}), '(msk, kernel, iterations=1)\n', (2342, 2369), False, 'import cv2\n'), ((2383, 2435), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_ELLIPSE', '(3, 3)'], {}), '(cv2.MORPH_ELLIPSE, (3, 3))\n', (2408, 2435), False, 'import cv2\n'), ((2446, 2492), 'cv2.morphologyEx', 'cv2.morphologyEx', (['msk', 'cv2.MORPH_CLOSE', 'kernel'], {}), '(msk, cv2.MORPH_CLOSE, kernel)\n', (2462, 2492), False, 'import cv2\n'), ((3928, 3951), 'numpy.seterr', 'np.seterr', ([], {'all': '"""ignore"""'}), "(all='ignore')\n", (3937, 3951), True, 'import numpy as np\n'), ((4275, 4316), 'cv2.cvtColor', 'cv2.cvtColor', (['img_col', 'cv2.COLOR_RGB2GRAY'], {}), '(img_col, cv2.COLOR_RGB2GRAY)\n', (4287, 4316), False, 'import cv2\n'), ((4394, 4414), 'numpy.fft.fft2', 'np.fft.fft2', (['img_gry'], {}), '(img_gry)\n', (4405, 4414), True, 'import numpy as np\n'), ((4428, 4446), 'numpy.fft.fftshift', 'np.fft.fftshift', (['f'], {}), '(f)\n', (4443, 4446), True, 'import numpy as np\n'), ((4511, 4535), 'numpy.fft.ifftshift', 'np.fft.ifftshift', (['fshift'], {}), '(fshift)\n', (4527, 4535), True, 'import numpy as np\n'), ((4550, 4572), 'numpy.fft.ifft2', 'np.fft.ifft2', (['f_ishift'], {}), '(f_ishift)\n', (4562, 4572), True, 'import numpy as np\n'), ((4824, 4840), 'numpy.mean', 'np.mean', (['img_fft'], {}), '(img_fft)\n', (4831, 4840), True, 'import numpy as np\n'), ((5258, 5276), 'scripts.gen_args', 'scripts.gen_args', ([], {}), '()\n', (5274, 5276), False, 'import scripts\n'), ((1005, 1046), 'skimage.img_as_ubyte', 'skimage.img_as_ubyte', (['region.convex_image'], {}), '(region.convex_image)\n', (1025, 1046), False, 'import skimage\n'), ((1876, 1893), 'numpy.sum', 'np.sum', (['blur_mask'], {}), '(blur_mask)\n', (1882, 1893), True, 'import numpy as np\n'), ((3654, 3665), 'numpy.sum', 'np.sum', (['msk'], {}), '(msk)\n', (3660, 3665), True, 'import numpy as np\n'), ((4671, 4694), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (4692, 4694), False, 'import cv2\n'), ((4703, 4738), 'scripts.display', 'scripts.display', (['"""img_fft"""', 'img_fft'], {}), "('img_fft', img_fft)\n", (4718, 4738), False, 'import scripts\n'), ((4747, 4782), 'scripts.display', 'scripts.display', (['"""img_col"""', 'img_col'], {}), "('img_col', img_col)\n", (4762, 4782), False, 'import scripts\n'), ((4791, 4805), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (4802, 4805), False, 'import cv2\n'), ((726, 780), 'numpy.zeros', 'np.zeros', (['(img.shape[0], img.shape[1])'], {'dtype': 'np.uint8'}), '((img.shape[0], img.shape[1]), dtype=np.uint8)\n', (734, 780), True, 'import numpy as np\n'), ((1833, 1857), 'cv2.add', 'cv2.add', (['blur_mask', 'mask'], {}), '(blur_mask, mask)\n', (1840, 1857), False, 'import cv2\n'), ((4599, 4614), 'numpy.abs', 'np.abs', (['img_fft'], {}), '(img_fft)\n', (4605, 4614), True, 'import numpy as np\n'), ((1525, 1540), 'numpy.unique', 'np.unique', (['mask'], {}), '(mask)\n', (1534, 1540), True, 'import numpy as np\n'), ((3389, 3400), 'numpy.max', 'np.max', (['msk'], {}), '(msk)\n', (3395, 3400), True, 'import numpy as np\n'), ((1629, 1641), 'numpy.sum', 'np.sum', (['mask'], {}), '(mask)\n', (1635, 1641), True, 'import numpy as np\n')]
# Use Streamlit in Sagemaker Studio Lab # Author: https://github.com/machinelearnear # import dependencies import streamlit as st import numpy as np import requests import io import json import base64 import matplotlib.pyplot as plt from PIL import Image from pathlib import Path from layers import BilinearUpSampling2D from tensorflow.keras.models import load_model from huggingface_hub import from_pretrained_keras from utils import load_images, predict from streamlit_image_comparison import image_comparison # helper funcs def infer(model, image): inputs = load_images([image]) outputs = predict(model, inputs) plasma = plt.get_cmap('plasma') rescaled = outputs[0][:, :, 0] rescaled = rescaled - np.min(rescaled) rescaled = rescaled / np.max(rescaled) image_out = plasma(rescaled)[:, :, :3] return image_out def show_images(input_img, output_img): f = plt.figure(figsize=(20,20)) f.add_subplot(1,2,1) plt.imshow(input_img) f.add_subplot(1,2,2) plt.imshow(output_img) plt.show(block=True) st.pyplot(bbox_inches='tight') @st.cache(allow_output_mutation=True) def load_model(keras_model="keras-io/monocular-depth-estimation"): custom_objects = {'BilinearUpSampling2D': BilinearUpSampling2D, 'depth_loss_function': None} model = from_pretrained_keras(keras_model, custom_objects=custom_objects, compile=False) return model with st.spinner(text='Loading model into Keras..'): model = load_model() # first things, first.. load your model # streamlit app # ----------------------------------------------------------- def main(): st.title('Monocular Depth Estimation') st.header('Introduction') st.markdown(''' Depth estimation is a crucial step towards inferring scene geometry from 2D images. The goal in monocular depth estimation is to predict the depth value of each pixel or inferring depth information, given only a single RGB image as input. This example will show an approach to build a depth estimation model with a convnet and simple loss functions. This demo is a Keras implementation of U-Net architecture with DenseNet201 backbone for estimating monocular depth from RGB images. ''') st.image( 'https://cs.nyu.edu/~silberman/images/nyu_depth_v2_web.jpg', caption='Source: Indoor Segmentation and Support Inference from RGBD Images ECCV 2012 (NYU Depth Dataset V2)', use_column_width=True) # read input image st.header('Read input image') options = st.radio('Please choose any of the following options', ( 'Choose example from library', 'Download image from URL', 'Upload your own image', ) ) input_image = None if options == 'Choose example from library': image_files = list(sorted([x for x in Path('examples').rglob('*.png')])) selected_file = st.selectbox( 'Select an image file from the list', image_files ) st.write(f'You have selected `{selected_file}`') input_image = Image.open(selected_file) elif options == 'Download image from URL': image_url = st.text_input('Image URL') try: r = requests.get(image_url) input_image = Image.open(io.BytesIO(r.content)) except Exception: st.error('There was an error downloading the image. Please check the URL again.') elif options == 'Upload your own image': uploaded_file = st.file_uploader("Choose file to upload") if uploaded_file: input_image = Image.open(io.BytesIO(uploaded_file.decode())) st.success('Image was successfully uploaded') if input_image: st.image(input_image, use_column_width=True) st.info('Note: Larger images will take longer to process.') else: st.warning('There is no image loaded.') # model inference st.header('Run your model prediction') st.write('') if input_image and st.button('Submit'): try: with st.spinner(): output = infer(model, np.asarray(input_image)) output_image = Image.fromarray((output * 255).astype(np.uint8)) image_comparison( img1=input_image, img2=output_image, label1='Original', label2='Depth Estimation', ) except Exception as e: st.error(e) st.error('There was an error processing the input image') if not input_image: st.warning('There is no image loaded') # footer st.header('References') st.markdown(''' - https://github.com/machinelearnear/use-gradio-streamlit-sagemaker-studiolab - https://github.com/nicolasmetallo/deploy-streamlit-on-fargate-with-aws-cdk - https://keras.io/examples/vision/depth_estimation/ ''') # run application # ----------------------------------------------------------- if __name__ == '__main__': main()
[ "streamlit.image", "streamlit.button", "io.BytesIO", "streamlit_image_comparison.image_comparison", "tensorflow.keras.models.load_model", "streamlit.text_input", "streamlit.header", "streamlit.title", "matplotlib.pyplot.imshow", "streamlit.cache", "pathlib.Path", "streamlit.warning", "utils....
[((1089, 1125), 'streamlit.cache', 'st.cache', ([], {'allow_output_mutation': '(True)'}), '(allow_output_mutation=True)\n', (1097, 1125), True, 'import streamlit as st\n'), ((568, 588), 'utils.load_images', 'load_images', (['[image]'], {}), '([image])\n', (579, 588), False, 'from utils import load_images, predict\n'), ((603, 625), 'utils.predict', 'predict', (['model', 'inputs'], {}), '(model, inputs)\n', (610, 625), False, 'from utils import load_images, predict\n'), ((639, 661), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""plasma"""'], {}), "('plasma')\n", (651, 661), True, 'import matplotlib.pyplot as plt\n'), ((896, 924), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (906, 924), True, 'import matplotlib.pyplot as plt\n'), ((953, 974), 'matplotlib.pyplot.imshow', 'plt.imshow', (['input_img'], {}), '(input_img)\n', (963, 974), True, 'import matplotlib.pyplot as plt\n'), ((1004, 1026), 'matplotlib.pyplot.imshow', 'plt.imshow', (['output_img'], {}), '(output_img)\n', (1014, 1026), True, 'import matplotlib.pyplot as plt\n'), ((1031, 1051), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(True)'}), '(block=True)\n', (1039, 1051), True, 'import matplotlib.pyplot as plt\n'), ((1056, 1086), 'streamlit.pyplot', 'st.pyplot', ([], {'bbox_inches': '"""tight"""'}), "(bbox_inches='tight')\n", (1065, 1086), True, 'import streamlit as st\n'), ((1302, 1387), 'huggingface_hub.from_pretrained_keras', 'from_pretrained_keras', (['keras_model'], {'custom_objects': 'custom_objects', 'compile': '(False)'}), '(keras_model, custom_objects=custom_objects, compile=False\n )\n', (1323, 1387), False, 'from huggingface_hub import from_pretrained_keras\n'), ((1406, 1451), 'streamlit.spinner', 'st.spinner', ([], {'text': '"""Loading model into Keras.."""'}), "(text='Loading model into Keras..')\n", (1416, 1451), True, 'import streamlit as st\n'), ((1465, 1477), 'tensorflow.keras.models.load_model', 'load_model', ([], {}), '()\n', (1475, 1477), False, 'from tensorflow.keras.models import load_model\n'), ((1613, 1651), 'streamlit.title', 'st.title', (['"""Monocular Depth Estimation"""'], {}), "('Monocular Depth Estimation')\n", (1621, 1651), True, 'import streamlit as st\n'), ((1656, 1681), 'streamlit.header', 'st.header', (['"""Introduction"""'], {}), "('Introduction')\n", (1665, 1681), True, 'import streamlit as st\n'), ((1686, 2239), 'streamlit.markdown', 'st.markdown', (['"""\n Depth estimation is a crucial step towards inferring scene geometry from 2D images. \n The goal in monocular depth estimation is to predict the depth value of each pixel \n or inferring depth information, given only a single RGB image as input. \n This example will show an approach to build a depth estimation model with a \n convnet and simple loss functions.\n \n This demo is a Keras implementation of U-Net architecture with DenseNet201 backbone for\n estimating monocular depth from RGB images.\n """'], {}), '(\n """\n Depth estimation is a crucial step towards inferring scene geometry from 2D images. \n The goal in monocular depth estimation is to predict the depth value of each pixel \n or inferring depth information, given only a single RGB image as input. \n This example will show an approach to build a depth estimation model with a \n convnet and simple loss functions.\n \n This demo is a Keras implementation of U-Net architecture with DenseNet201 backbone for\n estimating monocular depth from RGB images.\n """\n )\n', (1697, 2239), True, 'import streamlit as st\n'), ((2235, 2452), 'streamlit.image', 'st.image', (['"""https://cs.nyu.edu/~silberman/images/nyu_depth_v2_web.jpg"""'], {'caption': '"""Source: Indoor Segmentation and Support Inference from RGBD Images ECCV 2012 (NYU Depth Dataset V2)"""', 'use_column_width': '(True)'}), "('https://cs.nyu.edu/~silberman/images/nyu_depth_v2_web.jpg',\n caption=\n 'Source: Indoor Segmentation and Support Inference from RGBD Images ECCV 2012 (NYU Depth Dataset V2)'\n , use_column_width=True)\n", (2243, 2452), True, 'import streamlit as st\n'), ((2492, 2521), 'streamlit.header', 'st.header', (['"""Read input image"""'], {}), "('Read input image')\n", (2501, 2521), True, 'import streamlit as st\n'), ((2536, 2684), 'streamlit.radio', 'st.radio', (['"""Please choose any of the following options"""', "('Choose example from library', 'Download image from URL',\n 'Upload your own image')"], {}), "('Please choose any of the following options', (\n 'Choose example from library', 'Download image from URL',\n 'Upload your own image'))\n", (2544, 2684), True, 'import streamlit as st\n'), ((3943, 3981), 'streamlit.header', 'st.header', (['"""Run your model prediction"""'], {}), "('Run your model prediction')\n", (3952, 3981), True, 'import streamlit as st\n'), ((3986, 3998), 'streamlit.write', 'st.write', (['""""""'], {}), "('')\n", (3994, 3998), True, 'import streamlit as st\n'), ((4615, 4638), 'streamlit.header', 'st.header', (['"""References"""'], {}), "('References')\n", (4624, 4638), True, 'import streamlit as st\n'), ((4643, 4897), 'streamlit.markdown', 'st.markdown', (['"""\n - https://github.com/machinelearnear/use-gradio-streamlit-sagemaker-studiolab\n - https://github.com/nicolasmetallo/deploy-streamlit-on-fargate-with-aws-cdk\n - https://keras.io/examples/vision/depth_estimation/\n """'], {}), '(\n """\n - https://github.com/machinelearnear/use-gradio-streamlit-sagemaker-studiolab\n - https://github.com/nicolasmetallo/deploy-streamlit-on-fargate-with-aws-cdk\n - https://keras.io/examples/vision/depth_estimation/\n """\n )\n', (4654, 4897), True, 'import streamlit as st\n'), ((723, 739), 'numpy.min', 'np.min', (['rescaled'], {}), '(rescaled)\n', (729, 739), True, 'import numpy as np\n'), ((766, 782), 'numpy.max', 'np.max', (['rescaled'], {}), '(rescaled)\n', (772, 782), True, 'import numpy as np\n'), ((2914, 2977), 'streamlit.selectbox', 'st.selectbox', (['"""Select an image file from the list"""', 'image_files'], {}), "('Select an image file from the list', image_files)\n", (2926, 2977), True, 'import streamlit as st\n'), ((3008, 3056), 'streamlit.write', 'st.write', (['f"""You have selected `{selected_file}`"""'], {}), "(f'You have selected `{selected_file}`')\n", (3016, 3056), True, 'import streamlit as st\n'), ((3079, 3104), 'PIL.Image.open', 'Image.open', (['selected_file'], {}), '(selected_file)\n', (3089, 3104), False, 'from PIL import Image\n'), ((3729, 3773), 'streamlit.image', 'st.image', (['input_image'], {'use_column_width': '(True)'}), '(input_image, use_column_width=True)\n', (3737, 3773), True, 'import streamlit as st\n'), ((3782, 3841), 'streamlit.info', 'st.info', (['"""Note: Larger images will take longer to process."""'], {}), "('Note: Larger images will take longer to process.')\n", (3789, 3841), True, 'import streamlit as st\n'), ((3860, 3899), 'streamlit.warning', 'st.warning', (['"""There is no image loaded."""'], {}), "('There is no image loaded.')\n", (3870, 3899), True, 'import streamlit as st\n'), ((4022, 4041), 'streamlit.button', 'st.button', (['"""Submit"""'], {}), "('Submit')\n", (4031, 4041), True, 'import streamlit as st\n'), ((4554, 4592), 'streamlit.warning', 'st.warning', (['"""There is no image loaded"""'], {}), "('There is no image loaded')\n", (4564, 4592), True, 'import streamlit as st\n'), ((3172, 3198), 'streamlit.text_input', 'st.text_input', (['"""Image URL"""'], {}), "('Image URL')\n", (3185, 3198), True, 'import streamlit as st\n'), ((3228, 3251), 'requests.get', 'requests.get', (['image_url'], {}), '(image_url)\n', (3240, 3251), False, 'import requests\n'), ((3501, 3542), 'streamlit.file_uploader', 'st.file_uploader', (['"""Choose file to upload"""'], {}), "('Choose file to upload')\n", (3517, 3542), True, 'import streamlit as st\n'), ((4073, 4085), 'streamlit.spinner', 'st.spinner', ([], {}), '()\n', (4083, 4085), True, 'import streamlit as st\n'), ((4246, 4349), 'streamlit_image_comparison.image_comparison', 'image_comparison', ([], {'img1': 'input_image', 'img2': 'output_image', 'label1': '"""Original"""', 'label2': '"""Depth Estimation"""'}), "(img1=input_image, img2=output_image, label1='Original',\n label2='Depth Estimation')\n", (4262, 4349), False, 'from streamlit_image_comparison import image_comparison\n'), ((4448, 4459), 'streamlit.error', 'st.error', (['e'], {}), '(e)\n', (4456, 4459), True, 'import streamlit as st\n'), ((4472, 4529), 'streamlit.error', 'st.error', (['"""There was an error processing the input image"""'], {}), "('There was an error processing the input image')\n", (4480, 4529), True, 'import streamlit as st\n'), ((3289, 3310), 'io.BytesIO', 'io.BytesIO', (['r.content'], {}), '(r.content)\n', (3299, 3310), False, 'import io\n'), ((3350, 3436), 'streamlit.error', 'st.error', (['"""There was an error downloading the image. Please check the URL again."""'], {}), "(\n 'There was an error downloading the image. Please check the URL again.')\n", (3358, 3436), True, 'import streamlit as st\n'), ((3654, 3699), 'streamlit.success', 'st.success', (['"""Image was successfully uploaded"""'], {}), "('Image was successfully uploaded')\n", (3664, 3699), True, 'import streamlit as st\n'), ((4125, 4148), 'numpy.asarray', 'np.asarray', (['input_image'], {}), '(input_image)\n', (4135, 4148), True, 'import numpy as np\n'), ((2855, 2871), 'pathlib.Path', 'Path', (['"""examples"""'], {}), "('examples')\n", (2859, 2871), False, 'from pathlib import Path\n')]
# coding: utf-8 # pylint: disable=too-many-branches """Initialization helper for mxnet""" from __future__ import absolute_import import re import logging import numpy as np from .base import string_types from .ndarray import NDArray, load from . import random class Initializer(object): """Base class for Initializer.""" def __call__(self, name, arr): """Override () function to do Initialization Parameters ---------- name : str name of corrosponding ndarray arr : NDArray ndarray to be Initialized """ if not isinstance(name, string_types): raise TypeError('name must be string') if not isinstance(arr, NDArray): raise TypeError('arr must be NDArray') if name.startswith('upsampling'): self._init_bilinear(name, arr) elif name.startswith('stn_loc') and name.endswith('weight'): self._init_zero(name, arr) elif name.startswith('stn_loc') and name.endswith('bias'): self._init_loc_bias(name, arr) elif name.endswith('bias'): self._init_bias(name, arr) elif name.endswith('gamma'): self._init_gamma(name, arr) elif name.endswith('beta'): self._init_beta(name, arr) elif name.endswith('weight'): self._init_weight(name, arr) elif name.endswith("moving_mean"): self._init_zero(name, arr) elif name.endswith("moving_var"): self._init_one(name, arr) elif name.endswith("moving_inv_var"): self._init_zero(name, arr) elif name.endswith("moving_avg"): self._init_zero(name, arr) elif name.endswith("center_vec"): self._init_zero(name, arr) elif name.endswith("center_diff"): self._init_zero(name, arr) elif name.endswith("label_count"): self._init_zero(name, arr) else: self._init_default(name, arr) # pylint: disable=no-self-use, missing-docstring, invalid-name def _init_bilinear(self, _, arr): weight = np.zeros(np.prod(arr.shape), dtype='float32') shape = arr.shape f = np.ceil(shape[3] / 2.) c = (2 * f - 1 - f % 2) / (2. * f) for i in range(np.prod(shape)): x = i % shape[3] y = (i / shape[3]) % shape[2] weight[i] = (1 - abs(x / f - c)) * (1 - abs(y / f - c)) arr[:] = weight.reshape(shape) def _init_loc_bias(self, _, arr): shape = arr.shape assert(shape[0] == 6) arr[:] = np.array([1.0, 0, 0, 0, 1.0, 0]) def _init_zero(self, _, arr): arr[:] = 0.0 def _init_one(self, _, arr): arr[:] = 1.0 def _init_bias(self, _, arr): arr[:] = 0.0 def _init_gamma(self, _, arr): arr[:] = 1.0 def _init_beta(self, _, arr): arr[:] = 0.0 def _init_weight(self, name, arr): """Abstruct method to Initialize weight""" raise NotImplementedError("Must override it") def _init_default(self, name, _): raise ValueError('Unknown initialization pattern for %s' % name) # pylint: enable=no-self-use, missing-docstring, invalid-name class Load(object): """Initialize by loading pretrained param from file or dict Parameters ---------- param: str or dict of str->NDArray param file or dict mapping name to NDArray. default_init: Initializer default initializer when name is not found in param. verbose: bool log source when initializing. """ def __init__(self, param, default_init=None, verbose=False): if isinstance(param, str): param = load(param) assert isinstance(param, dict) self.param = {} for name, arr in param.items(): if name.startswith('arg:') or name.startswith('aux:'): self.param[name[4:]] = arr else: self.param[name] = arr self.default_init = default_init self.verbose = verbose def __call__(self, name, arr): if name in self.param: assert arr.shape == self.param[name].shape, \ 'Parameter %s cannot be initialized from loading. '%name + \ 'Shape mismatch, target %s vs loaded %s'%(str(arr.shape), self.param[name].shape) arr[:] = self.param[name] if self.verbose: logging.info('Initialized %s by loading', name) else: assert self.default_init is not None, \ "Cannot Initialize %s. Not found in loaded param "%name + \ "and no default Initializer is provided." self.default_init(name, arr) if self.verbose: logging.info('Initialized %s by default', name) class Mixed(object): """Initialize with mixed Initializer Parameters ---------- patterns: list of str list of regular expression patterns to match parameter names. initializers: list of Initializer list of Initializer corrosponding to patterns """ def __init__(self, patterns, initializers): assert len(patterns) == len(initializers) self.map = list(zip([re.compile(p) for p in patterns], initializers)) def __call__(self, name, arr): for prog, init in self.map: if prog.match(name): init(name, arr) return raise ValueError('Parameter name %s did not match any pattern. Consider' + 'add a ".*" pattern at the and with default Initializer.') class Uniform(Initializer): """Initialize the weight with uniform [-scale, scale] Parameters ---------- scale : float, optional The scale of uniform distribution """ def __init__(self, scale=0.07): self.scale = scale def _init_weight(self, _, arr): random.uniform(-self.scale, self.scale, out=arr) class Normal(Initializer): """Initialize the weight with normal(0, sigma) Parameters ---------- sigma : float, optional Standard deviation for gaussian distribution. """ def __init__(self, sigma=0.01): self.sigma = sigma def _init_weight(self, _, arr): random.normal(0, self.sigma, out=arr) class Orthogonal(Initializer): """Intialize weight as Orthogonal matrix Parameters ---------- scale : float optional scaling factor of weight rand_type: string optional use "uniform" or "normal" random number to initialize weight Reference --------- Exact solutions to the nonlinear dynamics of learning in deep linear neural networks arXiv preprint arXiv:1312.6120 (2013). """ def __init__(self, scale=1.414, rand_type="uniform"): self.scale = scale self.rand_type = rand_type # pylint: disable=invalid-name def _init_weight(self, _, arr): nout = arr.shape[0] nin = np.prod(arr.shape[1:]) if self.rand_type == "uniform": tmp = np.random.uniform(-1.0, 1.0, (nout, nin)) elif self.rand_type == "normal": tmp = np.random.normal(0.0, 1.0, (nout, nin)) u, _, v = np.linalg.svd(tmp, full_matrices=False) if u.shape == tmp.shape: q = u else: q = v q = self.scale * q.reshape(arr.shape) arr[:] = q class Xavier(Initializer): """Initialize the weight with Xavier or similar initialization scheme. Parameters ---------- rnd_type: str, optional Use ```gaussian``` or ```uniform``` to init factor_type: str, optional Use ```avg```, ```in```, or ```out``` to init magnitude: float, optional scale of random number range """ def __init__(self, rnd_type="uniform", factor_type="avg", magnitude=3): self.rnd_type = rnd_type self.factor_type = factor_type self.magnitude = float(magnitude) def _init_weight(self, _, arr): shape = arr.shape hw_scale = 1. if len(shape) > 2: hw_scale = np.prod(shape[2:]) fan_in, fan_out = shape[1] * hw_scale, shape[0] * hw_scale factor = 1. if self.factor_type == "avg": factor = (fan_in + fan_out) / 2.0 elif self.factor_type == "in": factor = fan_in elif self.factor_type == "out": factor = fan_out else: raise ValueError("Incorrect factor type") scale = np.sqrt(self.magnitude / factor) if self.rnd_type == "uniform": random.uniform(-scale, scale, out=arr) elif self.rnd_type == "gaussian": random.normal(0, scale, out=arr) else: raise ValueError("Unknown random type") class MSRAPrelu(Xavier): """Initialize the weight with initialization scheme from Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification. Parameters ---------- factor_type: str, optional Use ```avg```, ```in```, or ```out``` to init slope: float, optional initial slope of any PReLU (or similar) nonlinearities. """ def __init__(self, factor_type="avg", slope=0.25): magnitude = 2. / (1 + slope ** 2) super(MSRAPrelu, self).__init__("gaussian", factor_type, magnitude)
[ "numpy.random.normal", "numpy.prod", "numpy.ceil", "numpy.sqrt", "re.compile", "numpy.array", "numpy.random.uniform", "numpy.linalg.svd", "logging.info" ]
[((2223, 2246), 'numpy.ceil', 'np.ceil', (['(shape[3] / 2.0)'], {}), '(shape[3] / 2.0)\n', (2230, 2246), True, 'import numpy as np\n'), ((2619, 2651), 'numpy.array', 'np.array', (['[1.0, 0, 0, 0, 1.0, 0]'], {}), '([1.0, 0, 0, 0, 1.0, 0])\n', (2627, 2651), True, 'import numpy as np\n'), ((7083, 7105), 'numpy.prod', 'np.prod', (['arr.shape[1:]'], {}), '(arr.shape[1:])\n', (7090, 7105), True, 'import numpy as np\n'), ((7323, 7362), 'numpy.linalg.svd', 'np.linalg.svd', (['tmp'], {'full_matrices': '(False)'}), '(tmp, full_matrices=False)\n', (7336, 7362), True, 'import numpy as np\n'), ((8625, 8657), 'numpy.sqrt', 'np.sqrt', (['(self.magnitude / factor)'], {}), '(self.magnitude / factor)\n', (8632, 8657), True, 'import numpy as np\n'), ((2148, 2166), 'numpy.prod', 'np.prod', (['arr.shape'], {}), '(arr.shape)\n', (2155, 2166), True, 'import numpy as np\n'), ((2312, 2326), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (2319, 2326), True, 'import numpy as np\n'), ((7164, 7205), 'numpy.random.uniform', 'np.random.uniform', (['(-1.0)', '(1.0)', '(nout, nin)'], {}), '(-1.0, 1.0, (nout, nin))\n', (7181, 7205), True, 'import numpy as np\n'), ((8215, 8233), 'numpy.prod', 'np.prod', (['shape[2:]'], {}), '(shape[2:])\n', (8222, 8233), True, 'import numpy as np\n'), ((4533, 4580), 'logging.info', 'logging.info', (['"""Initialized %s by loading"""', 'name'], {}), "('Initialized %s by loading', name)\n", (4545, 4580), False, 'import logging\n'), ((4867, 4914), 'logging.info', 'logging.info', (['"""Initialized %s by default"""', 'name'], {}), "('Initialized %s by default', name)\n", (4879, 4914), False, 'import logging\n'), ((7265, 7304), 'numpy.random.normal', 'np.random.normal', (['(0.0)', '(1.0)', '(nout, nin)'], {}), '(0.0, 1.0, (nout, nin))\n', (7281, 7304), True, 'import numpy as np\n'), ((5333, 5346), 're.compile', 're.compile', (['p'], {}), '(p)\n', (5343, 5346), False, 'import re\n')]
""" ScanNet This file help you generate point clouds from RGB_D images. """ from __future__ import division import numpy as np import os, cv2, time, math, scipy import scipy.io as io import argparse def CameraParameterRead(dir): intrinsic_color_path = dir + 'intrinsic_color.txt' intrinsic_depth_path = dir + 'intrinsic_depth.txt' extrinsic_color_path = dir + 'extrinsic_color.txt' extrinsic_depth_path = dir + 'extrinsic_depth.txt' intrinsic_color = [] intrinsic_depth = [] extrinsic_color = [] extrinsic_depth = [] f = open(intrinsic_color_path) for j in range(4): line = f.readline() tmp = line.split() intrinsic_color.append(tmp) intrinsic_color = np.array(intrinsic_color, dtype=np.float32) f = open(intrinsic_depth_path) for j in range(4): line = f.readline() tmp = line.split() intrinsic_depth.append(tmp) intrinsic_depth = np.array(intrinsic_depth, dtype=np.float32) f = open(extrinsic_color_path) for j in range(4): line = f.readline() tmp = line.split() extrinsic_color.append(tmp) extrinsic_color = np.array(extrinsic_color, dtype=np.float32) f = open(extrinsic_depth_path) for j in range(4): line = f.readline() tmp = line.split() extrinsic_depth.append(tmp) extrinsic_depth = np.array(extrinsic_depth, dtype=np.float32) return intrinsic_color, intrinsic_depth, extrinsic_color, extrinsic_depth def CameraPoseRead(camera_name): camera_pose_path = camera_name camera_pose = [] f = open(camera_pose_path) for i in range(4): line = f.readline() tmp = line.split() camera_pose.append(tmp) camera_pose = np.array(camera_pose, dtype=np.float32) return camera_pose def projection(image, depth, intrinsic_matrix, extrinsic_matrix, position_image): # pixel coordinates system, origin at image's top left height, weight, channel = image.shape pixel_position = np.ones([4, height*weight]) v = np.array(position_image[0]) u = np.array(position_image[1]) depth = depth[v, u] image = np.transpose(image[v, u]) pixel_position[0, :] = u*depth pixel_position[1, :] = v*depth pixel_position[2, :] = depth transform_matrix = extrinsic_matrix.dot(np.linalg.inv(intrinsic_matrix)) # discard invalid depth position depth_mask = np.where(depth != 0.0)[0] pixel_position = pixel_position[:, depth_mask] position_color = image[:, depth_mask] #image-to-world position_in_world = transform_matrix.dot(pixel_position) return position_in_world, depth_mask, position_color def combine(dir, num_files, remove=True): st = time.time() point_clouds_all = np.zeros([4, 0]) point_clouds_colors_all = np.zeros([3, 0]) for j in range(num_files): if not os.path.isfile(dir + 'point_clouds_%s.mat' % j): continue content = io.loadmat(dir + 'point_clouds_%s.mat' % j) point_clouds = content['point_clouds'] content1 = io.loadmat(dir + 'point_clouds_colors_%s.mat' % j) point_clouds_colors = content1['point_clouds_color'] point_clouds_all = np.concatenate([point_clouds_all, point_clouds], axis=1) point_clouds_colors_all = np.concatenate([point_clouds_colors_all, point_clouds_colors], axis=1) # print('load point clouds: %ss' % (time.time() - st)) num_point = point_clouds_all.shape[1] target = open(out_root + "point_clouds.ply", 'w') target.write("ply\n") target.write("format ascii 1.0\n") target.write("element vertex %s\n" % num_point) target.write("property float32 x\nproperty float32 y\nproperty float32 z\nproperty uchar red\nproperty uchar green\nproperty uchar blue\n") target.write("end_header\n") for i in range(num_point): target.write('%.4f %.4f %.4f %s %s %s\n' % ( point_clouds_all[0, i], point_clouds_all[1, i], point_clouds_all[2, i], int(point_clouds_colors_all[2, i]), int(point_clouds_colors_all[1, i]), int(point_clouds_colors_all[0, i]))) target.close() print('%ss, Combination done! ' % (time.time() - st)) # remove intermediate .mat files if remove: for j in range(num_files): if not os.path.isfile(dir + 'point_clouds_%s.mat' % j): continue os.remove(dir + 'point_clouds_%s.mat' % j) os.remove(dir + 'point_clouds_colors_%s.mat' % j) return 0 if __name__ == '__main__': scene = 'scene0010_00' # which scene used to generate point clouds. dir1 = '../data/ScanNet/%s/color/' % scene # color image path dir2 = '../data/ScanNet/%s/depth/' % scene # depth image path dir3 = '../data/ScanNet/%s/intrinsic/' % scene # intrinsic parameter path dir4 = '../data/ScanNet/%s/pose/' % scene # camera pose path out_root = '../pre_processing_results/ScanNet/%s/' % scene # output path random_select = True # Do not use all pixels, just randomly select. random_select_proportion = 1/15 # Proportion used to generate point clouds; large is better but need more resource. resize = True # From 1296*968 (color image shape) to 640*480 (depth_image shape) target_h = 480 target_w = 640 position_image = np.where(np.zeros([target_h, target_w]) == 0) # u, v image_list = os.listdir(dir1) num_image = len(image_list) # Total number of images. batch_num = 200 # Due to the limitation of memory and speed. We divide whole images into small batches. ####################################################################################################################### intrinsic_color, intrinsic_depth, _, _ = CameraParameterRead(dir3) if resize: scale1_c = (1296 - 1) / (target_w - 1) scale2_c = (968 - 1) / (target_h - 1) scale1_d = (640 - 1) / (target_w - 1) scale2_d = (480 - 1) / (target_h - 1) intrinsic_color[0:1, :] = intrinsic_color[0:1, :] / scale1_c intrinsic_color[1:2, :] = intrinsic_color[1:2, :] / scale2_c intrinsic_depth[0:1, :] = intrinsic_depth[0:1, :] / scale1_d intrinsic_depth[1:2, :] = intrinsic_depth[1:2, :] / scale2_d cnt = 0 CNT = 0 point_clouds = np.empty([4, 0], dtype=np.float32) point_clouds_colors = np.empty([3, 0], dtype=np.float32) depth_masks = np.empty([1, 0], dtype=np.float32) st = time.time() for i in range(num_image): image_name = dir1 + '%s.jpg' % i depth_name = dir2 + '%s.png' % i camera_name = dir4 + '%s.txt' % i if not (os.path.isfile(image_name) and os.path.isfile(depth_name) and os.path.isfile(camera_name)): print('missing files!') cnt = cnt + 1 continue image = cv2.resize(cv2.imread(image_name, -1), (target_w, target_h)) depth = cv2.resize(cv2.imread(depth_name, -1), (target_w, target_h)) / 1000 # shift 1000 extrinsic_matrix = CameraPoseRead(camera_name) if extrinsic_matrix[0, 0] < -1e10: # avoid invalid pose (-Inf) in ScanNet print('invalid camera') cnt = cnt + 1 continue if random_select: tmp = np.random.uniform(0, 1.0, depth.shape) random_map = np.ones_like(tmp) random_map[np.where(tmp > random_select_proportion)] = 0 depth = depth * random_map # project 2D images into 3D space. intrinsic_matrix = intrinsic_color world_coordinates, depth_mask, point_clouds_color = projection(image, depth, intrinsic_matrix, extrinsic_matrix, position_image) point_clouds = np.concatenate((point_clouds, world_coordinates), axis=1) point_clouds_colors = np.concatenate((point_clouds_colors, point_clouds_color), axis=1) depth_masks = np.concatenate((depth_masks, np.reshape(depth_mask, (1, depth_mask.shape[0]))), axis=1) cnt = cnt + 1 if (cnt == batch_num or i == (num_image - 1)): if not os.path.isdir(out_root): os.makedirs(out_root) io.savemat(out_root + 'point_clouds_%s.mat' % CNT, {'point_clouds': point_clouds}) io.savemat(out_root + 'point_clouds_colors_%s.mat' % CNT, {'point_clouds_color': point_clouds_colors}) print('one batch finished %ss' %(time.time() - st)) cnt = 0 CNT = CNT + 1 point_clouds = np.empty([4, 0], dtype=np.float32) point_clouds_colors = np.empty([3, 0], dtype=np.float32) depth_masks = np.empty([1, 0], dtype=np.float32) print('Generate point clouds: %ss' % (time.time() - st)) print('Combining batches ...') combine(dir=out_root, num_files=(num_image//batch_num + 1), remove=True)
[ "scipy.io.savemat", "scipy.io.loadmat", "numpy.array", "os.remove", "os.listdir", "numpy.reshape", "numpy.where", "os.path.isdir", "numpy.empty", "numpy.concatenate", "numpy.ones", "os.path.isfile", "numpy.transpose", "cv2.imread", "time.time", "numpy.ones_like", "os.makedirs", "nu...
[((727, 770), 'numpy.array', 'np.array', (['intrinsic_color'], {'dtype': 'np.float32'}), '(intrinsic_color, dtype=np.float32)\n', (735, 770), True, 'import numpy as np\n'), ((944, 987), 'numpy.array', 'np.array', (['intrinsic_depth'], {'dtype': 'np.float32'}), '(intrinsic_depth, dtype=np.float32)\n', (952, 987), True, 'import numpy as np\n'), ((1161, 1204), 'numpy.array', 'np.array', (['extrinsic_color'], {'dtype': 'np.float32'}), '(extrinsic_color, dtype=np.float32)\n', (1169, 1204), True, 'import numpy as np\n'), ((1378, 1421), 'numpy.array', 'np.array', (['extrinsic_depth'], {'dtype': 'np.float32'}), '(extrinsic_depth, dtype=np.float32)\n', (1386, 1421), True, 'import numpy as np\n'), ((1754, 1793), 'numpy.array', 'np.array', (['camera_pose'], {'dtype': 'np.float32'}), '(camera_pose, dtype=np.float32)\n', (1762, 1793), True, 'import numpy as np\n'), ((2025, 2054), 'numpy.ones', 'np.ones', (['[4, height * weight]'], {}), '([4, height * weight])\n', (2032, 2054), True, 'import numpy as np\n'), ((2061, 2088), 'numpy.array', 'np.array', (['position_image[0]'], {}), '(position_image[0])\n', (2069, 2088), True, 'import numpy as np\n'), ((2097, 2124), 'numpy.array', 'np.array', (['position_image[1]'], {}), '(position_image[1])\n', (2105, 2124), True, 'import numpy as np\n'), ((2161, 2186), 'numpy.transpose', 'np.transpose', (['image[v, u]'], {}), '(image[v, u])\n', (2173, 2186), True, 'import numpy as np\n'), ((2737, 2748), 'time.time', 'time.time', ([], {}), '()\n', (2746, 2748), False, 'import os, cv2, time, math, scipy\n'), ((2772, 2788), 'numpy.zeros', 'np.zeros', (['[4, 0]'], {}), '([4, 0])\n', (2780, 2788), True, 'import numpy as np\n'), ((2819, 2835), 'numpy.zeros', 'np.zeros', (['[3, 0]'], {}), '([3, 0])\n', (2827, 2835), True, 'import numpy as np\n'), ((5389, 5405), 'os.listdir', 'os.listdir', (['dir1'], {}), '(dir1)\n', (5399, 5405), False, 'import os, cv2, time, math, scipy\n'), ((6289, 6323), 'numpy.empty', 'np.empty', (['[4, 0]'], {'dtype': 'np.float32'}), '([4, 0], dtype=np.float32)\n', (6297, 6323), True, 'import numpy as np\n'), ((6350, 6384), 'numpy.empty', 'np.empty', (['[3, 0]'], {'dtype': 'np.float32'}), '([3, 0], dtype=np.float32)\n', (6358, 6384), True, 'import numpy as np\n'), ((6403, 6437), 'numpy.empty', 'np.empty', (['[1, 0]'], {'dtype': 'np.float32'}), '([1, 0], dtype=np.float32)\n', (6411, 6437), True, 'import numpy as np\n'), ((6448, 6459), 'time.time', 'time.time', ([], {}), '()\n', (6457, 6459), False, 'import os, cv2, time, math, scipy\n'), ((2336, 2367), 'numpy.linalg.inv', 'np.linalg.inv', (['intrinsic_matrix'], {}), '(intrinsic_matrix)\n', (2349, 2367), True, 'import numpy as np\n'), ((2424, 2446), 'numpy.where', 'np.where', (['(depth != 0.0)'], {}), '(depth != 0.0)\n', (2432, 2446), True, 'import numpy as np\n'), ((2973, 3016), 'scipy.io.loadmat', 'io.loadmat', (["(dir + 'point_clouds_%s.mat' % j)"], {}), "(dir + 'point_clouds_%s.mat' % j)\n", (2983, 3016), True, 'import scipy.io as io\n'), ((3083, 3133), 'scipy.io.loadmat', 'io.loadmat', (["(dir + 'point_clouds_colors_%s.mat' % j)"], {}), "(dir + 'point_clouds_colors_%s.mat' % j)\n", (3093, 3133), True, 'import scipy.io as io\n'), ((3223, 3279), 'numpy.concatenate', 'np.concatenate', (['[point_clouds_all, point_clouds]'], {'axis': '(1)'}), '([point_clouds_all, point_clouds], axis=1)\n', (3237, 3279), True, 'import numpy as np\n'), ((3314, 3384), 'numpy.concatenate', 'np.concatenate', (['[point_clouds_colors_all, point_clouds_colors]'], {'axis': '(1)'}), '([point_clouds_colors_all, point_clouds_colors], axis=1)\n', (3328, 3384), True, 'import numpy as np\n'), ((7690, 7747), 'numpy.concatenate', 'np.concatenate', (['(point_clouds, world_coordinates)'], {'axis': '(1)'}), '((point_clouds, world_coordinates), axis=1)\n', (7704, 7747), True, 'import numpy as np\n'), ((7778, 7843), 'numpy.concatenate', 'np.concatenate', (['(point_clouds_colors, point_clouds_color)'], {'axis': '(1)'}), '((point_clouds_colors, point_clouds_color), axis=1)\n', (7792, 7843), True, 'import numpy as np\n'), ((2884, 2931), 'os.path.isfile', 'os.path.isfile', (["(dir + 'point_clouds_%s.mat' % j)"], {}), "(dir + 'point_clouds_%s.mat' % j)\n", (2898, 2931), False, 'import os, cv2, time, math, scipy\n'), ((4393, 4435), 'os.remove', 'os.remove', (["(dir + 'point_clouds_%s.mat' % j)"], {}), "(dir + 'point_clouds_%s.mat' % j)\n", (4402, 4435), False, 'import os, cv2, time, math, scipy\n'), ((4448, 4497), 'os.remove', 'os.remove', (["(dir + 'point_clouds_colors_%s.mat' % j)"], {}), "(dir + 'point_clouds_colors_%s.mat' % j)\n", (4457, 4497), False, 'import os, cv2, time, math, scipy\n'), ((5326, 5356), 'numpy.zeros', 'np.zeros', (['[target_h, target_w]'], {}), '([target_h, target_w])\n', (5334, 5356), True, 'import numpy as np\n'), ((6837, 6863), 'cv2.imread', 'cv2.imread', (['image_name', '(-1)'], {}), '(image_name, -1)\n', (6847, 6863), False, 'import os, cv2, time, math, scipy\n'), ((7252, 7290), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1.0)', 'depth.shape'], {}), '(0, 1.0, depth.shape)\n', (7269, 7290), True, 'import numpy as np\n'), ((7316, 7333), 'numpy.ones_like', 'np.ones_like', (['tmp'], {}), '(tmp)\n', (7328, 7333), True, 'import numpy as np\n'), ((8129, 8215), 'scipy.io.savemat', 'io.savemat', (["(out_root + 'point_clouds_%s.mat' % CNT)", "{'point_clouds': point_clouds}"], {}), "(out_root + 'point_clouds_%s.mat' % CNT, {'point_clouds':\n point_clouds})\n", (8139, 8215), True, 'import scipy.io as io\n'), ((8224, 8331), 'scipy.io.savemat', 'io.savemat', (["(out_root + 'point_clouds_colors_%s.mat' % CNT)", "{'point_clouds_color': point_clouds_colors}"], {}), "(out_root + 'point_clouds_colors_%s.mat' % CNT, {\n 'point_clouds_color': point_clouds_colors})\n", (8234, 8331), True, 'import scipy.io as io\n'), ((8466, 8500), 'numpy.empty', 'np.empty', (['[4, 0]'], {'dtype': 'np.float32'}), '([4, 0], dtype=np.float32)\n', (8474, 8500), True, 'import numpy as np\n'), ((8535, 8569), 'numpy.empty', 'np.empty', (['[3, 0]'], {'dtype': 'np.float32'}), '([3, 0], dtype=np.float32)\n', (8543, 8569), True, 'import numpy as np\n'), ((8596, 8630), 'numpy.empty', 'np.empty', (['[1, 0]'], {'dtype': 'np.float32'}), '([1, 0], dtype=np.float32)\n', (8604, 8630), True, 'import numpy as np\n'), ((4180, 4191), 'time.time', 'time.time', ([], {}), '()\n', (4189, 4191), False, 'import os, cv2, time, math, scipy\n'), ((4307, 4354), 'os.path.isfile', 'os.path.isfile', (["(dir + 'point_clouds_%s.mat' % j)"], {}), "(dir + 'point_clouds_%s.mat' % j)\n", (4321, 4354), False, 'import os, cv2, time, math, scipy\n'), ((6634, 6660), 'os.path.isfile', 'os.path.isfile', (['image_name'], {}), '(image_name)\n', (6648, 6660), False, 'import os, cv2, time, math, scipy\n'), ((6665, 6691), 'os.path.isfile', 'os.path.isfile', (['depth_name'], {}), '(depth_name)\n', (6679, 6691), False, 'import os, cv2, time, math, scipy\n'), ((6696, 6723), 'os.path.isfile', 'os.path.isfile', (['camera_name'], {}), '(camera_name)\n', (6710, 6723), False, 'import os, cv2, time, math, scipy\n'), ((6914, 6940), 'cv2.imread', 'cv2.imread', (['depth_name', '(-1)'], {}), '(depth_name, -1)\n', (6924, 6940), False, 'import os, cv2, time, math, scipy\n'), ((7357, 7397), 'numpy.where', 'np.where', (['(tmp > random_select_proportion)'], {}), '(tmp > random_select_proportion)\n', (7365, 7397), True, 'import numpy as np\n'), ((7895, 7943), 'numpy.reshape', 'np.reshape', (['depth_mask', '(1, depth_mask.shape[0])'], {}), '(depth_mask, (1, depth_mask.shape[0]))\n', (7905, 7943), True, 'import numpy as np\n'), ((8053, 8076), 'os.path.isdir', 'os.path.isdir', (['out_root'], {}), '(out_root)\n', (8066, 8076), False, 'import os, cv2, time, math, scipy\n'), ((8094, 8115), 'os.makedirs', 'os.makedirs', (['out_root'], {}), '(out_root)\n', (8105, 8115), False, 'import os, cv2, time, math, scipy\n'), ((8675, 8686), 'time.time', 'time.time', ([], {}), '()\n', (8684, 8686), False, 'import os, cv2, time, math, scipy\n'), ((8373, 8384), 'time.time', 'time.time', ([], {}), '()\n', (8382, 8384), False, 'import os, cv2, time, math, scipy\n')]
# Copyright (c) 2020, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from coremltools.converters.mil.mil import Builder as mb from coremltools.converters.mil.testing_utils import ( assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check, ) import unittest import pytest import numpy as np np.random.seed(1984) class TransposeOptimizationPass(unittest.TestCase): """""" """ Input graph: input -----> transpose(axis=[1,0]) -----> transpose(axis=[1,0]) ---> out Output graph: input -----> relu -----> out """ def test_simple_consecutive_ops_fusion_direct_output(self): @mb.program(input_specs=[mb.TensorSpec(shape=(10, 20))]) def prog(x): x = mb.transpose(x=x, perm=[1, 0]) x = mb.transpose(x=x, perm=[1, 0]) return x prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "transpose"] ) self.assertEqual(get_op_types_in_program(prog), ["identity"]) assert_model_is_valid( prog, {"x": (10, 20)}, expected_output_shapes={block.outputs[0].name: (10, 20)}, ) """ Input graph: input -----> transpose(axis=[1,0]) -----> transpose(axis=[1,0]) ----> relu ---> out Output graph: input -----> relu -----> out """ def test_simple_consecutive_ops_fusion(self): @mb.program(input_specs=[mb.TensorSpec(shape=(10, 20))]) def prog(x): x = mb.transpose(x=x, perm=[1, 0]) x = mb.transpose(x=x, perm=[1, 0]) x = mb.relu(x=x) return x prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "transpose", "relu"] ) self.assertEqual(get_op_types_in_program(prog), ["relu"]) assert_model_is_valid( prog, {"x": (10, 20)}, expected_output_shapes={block.outputs[0].name: (10, 20)}, ) """ Input graph: input---->transpose(axis=[0,3,1,2])---->relu---->log--->transpose(axis=[0,2,3,1])--->relu--->out Output graph: input----->relu----->log----->relu--->out """ def test_linear_graph_two_op_fusion(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 3, 4))]) def prog(x): x = mb.transpose(x=x, perm=[0, 3, 1, 2]) x = mb.relu(x=x) x = mb.log(x=x) x = mb.transpose(x=x, perm=[0, 2, 3, 1]) x = mb.relu(x=x) return x prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "relu", "log", "transpose", "relu"], ) self.assertEqual(get_op_types_in_program(prog), ["relu", "log", "relu"]) assert_model_is_valid( prog, {"x": (1, 2, 3, 4)}, expected_output_shapes={block.outputs[0].name: (1, 2, 3, 4)}, ) """ Input graph: input---->transpose(axis=[0,3,1,2])---->relu---->identity--->transpose(axis=[0,2,3,1])--->relu--->out Output graph: input----->relu----->identity----->relu--->out """ def test_linear_graph_two_op_fusion_1(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 3, 4))]) def prog(x): x = mb.transpose(x=x, perm=[0, 3, 1, 2]) x = mb.relu(x=x) x = mb.identity(x=x) x = mb.transpose(x=x, perm=[0, 2, 3, 1]) x = mb.relu(x=x) return x prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "relu", "identity", "transpose", "relu"], ) self.assertEqual(get_op_types_in_program(prog), ["relu", "identity", "relu"]) assert_model_is_valid( prog, {"x": (1, 2, 3, 4)}, expected_output_shapes={block.outputs[0].name: (1, 2, 3, 4)}, ) """ Input graph: input(shape=1,2,3,4)---->transpose(axis=[0,3,1,2])---->relu---->log--->transpose(axis=[0,2,3,1])--->relu--->out1(shape=1,2,3,4) | v out2(shape=1,4,2,3) Output graph: input(shape=1,2,3,4)---->relu---->log--->relu--->out1(shape=1,2,3,4) | |----->transpose(axis=[0,3,1,2])----->out2(shape=1,4,2,3) """ def test_fusion_with_output_edge_inbetween(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 3, 4))]) def prog(x): x = mb.transpose(x=x, perm=[0, 3, 1, 2]) x1 = mb.relu(x=x) x2 = mb.log(x=x1) x3 = mb.transpose(x=x2, perm=[0, 2, 3, 1]) x4 = mb.relu(x=x3) return x4, x1 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "relu", "log", "transpose", "relu"], ) self.assertEqual( get_op_types_in_program(prog), ["relu", "log", "relu", "transpose"] ) assert_model_is_valid( prog, {"x": (1, 2, 3, 4)}, expected_output_shapes={ block.outputs[0].name: (1, 2, 3, 4), block.outputs[1].name: (1, 4, 2, 3), }, ) """ Input graph: input---->transpose(axis=[0,3,1,2])---->relu---->transpose(axis=[0,2,3,1])--->out Output graph: input----->relu----->out """ def test_linear_graph_two_op_fusion_with_last_op_removal(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 3, 4))]) def prog(x): x = mb.transpose(x=x, perm=[0, 3, 1, 2]) x = mb.relu(x=x) x = mb.transpose(x=x, perm=[0, 2, 3, 1]) return x prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "relu", "transpose"] ) self.assertEqual(get_op_types_in_program(prog), ["relu"]) assert_model_is_valid( prog, {"x": (1, 2, 3, 4)}, expected_output_shapes={block.outputs[0].name: (1, 2, 3, 4)}, ) """ Input graph: input(shape=10,2,3)--->transpose(axis=[0,2,1])----->relu---->transpose(axis=[0,2,1])---->out1 | | --->relu----->log---->transpose(axis=[0,2,1])---->out2 Output graph: input(shape=10,2,3)----->relu---->out1 | | --->relu----->log---->out2 """ def test_multiple_fusions(self): @mb.program(input_specs=[mb.TensorSpec(shape=(10, 2, 3))]) def prog(x): x = mb.transpose(x=x, perm=[0, 2, 1]) x1 = mb.relu(x=x) x2 = mb.relu(x=x) y1 = mb.transpose(x=x1, perm=[0, 2, 1]) x3 = mb.log(x=x2) y2 = mb.transpose(x=x3, perm=[0, 2, 1]) return y1, y2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "relu", "relu", "transpose", "log", "transpose"], ) self.assertEqual(get_op_types_in_program(prog), ["relu", "relu", "log"]) assert ( prev_block.inputs["x"] == prev_block.find_ops(op_type="transpose")[0].inputs["x"] ) assert block.find_ops(op_type="log")[0].outputs[0] in block.outputs assert_model_is_valid( prog, {"x": (10, 2, 3)}, expected_output_shapes={ block.outputs[0].name: (10, 2, 3), block.outputs[1].name: (10, 2, 3), }, ) """ Input graph: input(shape=10,2,3,5)--->transpose(axis=[0,2,3,1])----->relu---->pool----->out1 | | --->relu----->log---->transpose(axis=[0,3,1,2])---->out2 Output graph: input(shape=10,2,3,5)----->relu---->transpose(axis=[0,2,3,1])---->pool----->out1 | | --->relu----->log---->out2 """ def test_partial_fusion_0(self): @mb.program(input_specs=[mb.TensorSpec(shape=(10, 2, 3, 5))]) def prog(x): x = mb.transpose(x=x, perm=[0, 2, 3, 1]) x1 = mb.relu(x=x) x2 = mb.relu(x=x) y1 = mb.avg_pool( x=x1, kernel_sizes=[1, 1], strides=[1, 1], pad_type="valid" ) x3 = mb.log(x=x2) y2 = mb.transpose(x=x3, perm=[0, 3, 1, 2]) return y1, y2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "relu", "relu", "avg_pool", "log", "transpose"], ) self.assertEqual( get_op_types_in_program(prog), ["relu", "relu", "transpose", "avg_pool", "log"], ) assert ( prev_block.inputs["x"] == prev_block.find_ops(op_type="transpose")[0].inputs["x"] ) assert block.find_ops(op_type="log")[0].outputs[0] == block.outputs[1] assert ( block.find_ops(op_type="transpose")[0].outputs[0] == block.find_ops(op_type="avg_pool")[0].inputs["x"] ) assert list(block.find_ops(op_type="transpose")[0].perm.val) == [0, 2, 3, 1] assert_model_is_valid( prog, {"x": (10, 2, 3, 5)}, expected_output_shapes={ block.outputs[0].name: (10, 3, 5, 2), block.outputs[1].name: (10, 2, 3, 5), }, ) """ Input graph: input(shape=10,2,3,5)--->transpose(axis=[0,2,1,3])----->relu---->transpose(axis=[0,2,1,3])---->out1 | | --->pool--->log---->transpose(axis=[0,2,1,3])---->out2 Output graph: input(shape=10,2,3,5)----->relu---->out1 | | --->transpose(axis=[0,2,1,3])---->pool----->log---->transpose(axis=[0,2,1,3])---->out2 """ def test_partial_fusion_1(self): @mb.program(input_specs=[mb.TensorSpec(shape=(10, 2, 3, 5))]) def prog(x): x = mb.transpose(x=x, perm=[0, 2, 1, 3]) x1 = mb.relu(x=x) x2 = mb.avg_pool(x=x, kernel_sizes=[1, 1], strides=[1, 1], pad_type="valid") y1 = mb.transpose(x=x1, perm=[0, 2, 1, 3]) x3 = mb.log(x=x2) y2 = mb.transpose(x=x3, perm=[0, 2, 1, 3]) return y1, y2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "relu", "avg_pool", "transpose", "log", "transpose"], ) self.assertEqual( get_op_types_in_program(prog), ["relu", "transpose", "avg_pool", "log", "transpose"], ) assert block.inputs["x"] == block.find_ops(op_type="relu")[0].inputs["x"] assert block.outputs[0] == block.find_ops(op_type="relu")[0].outputs[0] assert_model_is_valid( prog, {"x": (10, 2, 3, 5)}, expected_output_shapes={ block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 2, 3, 5), }, ) """ Input graph: |-------> transpose(axis=[0,2,1,3]) ---->out1(shape=10,2,3,5) | input(shape=10,2,3,5)-->relu-->transpose(axis=[0,2,1,3])--->relu--->transpose(axis=[0,2,1,3]) ---->out2(shape=10,2,3,5) | |----->pool--------------->out3(shape=10,3,2,5) | |----->pool--------------->out4(shape=10.3.2.5) Output graph: |---->out1(shape=10,2,3,5) | input---->relu---------->relu------->out2(shape=10,2,3,5) | |----->transpose(axis=[0,2,1,3])--->pool---->out3(shape=10,3,2,5) | |----->transpose(axis=[0,2,1,3])---->pool--->out4(shape=10.3.2.5) """ def test_partial_fusion_2(self): @mb.program(input_specs=[mb.TensorSpec(shape=(10, 2, 3, 5))]) def prog(x): x = mb.relu(x=x) x = mb.transpose(x=x, perm=[0, 2, 1, 3]) y1 = mb.transpose(x=x, perm=[0, 2, 1, 3]) x1 = mb.relu(x=x) y2 = mb.transpose(x=x1, perm=[0, 2, 1, 3]) y3 = mb.avg_pool( x=x1, kernel_sizes=[1, 1], strides=[1, 1], pad_type="valid" ) y4 = mb.avg_pool( x=x1, kernel_sizes=[1, 1], strides=[1, 1], pad_type="valid" ) return y1, y2, y3, y4 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), [ "relu", "transpose", "transpose", "relu", "transpose", "avg_pool", "avg_pool", ], ) self.assertEqual( get_op_types_in_program(prog), ["relu", "relu", "transpose", "avg_pool", "transpose", "avg_pool"], ) assert block.outputs[0] == block.find_ops(op_type="relu")[0].outputs[0] assert block.outputs[1] == block.find_ops(op_type="relu")[1].outputs[0] assert_model_is_valid( prog, {"x": (10, 2, 3, 5)}, expected_output_shapes={ block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 2, 3, 5), block.outputs[2].name: (10, 3, 2, 5), block.outputs[3].name: (10, 3, 2, 5), }, ) """ Input graph: input(shape=10,2,3,5)-->relu--->transpose(axis=[0,2,1,3])----->transpose(axis=[0,2,1,3])---->out1(shape=10,2,3,5) | ---->relu------>out2(shape=10,3,2,5) Output graph: input(shape=10,2,3,5)-->relu---->out1(shape=10,2,3,5) | ---->relu--->transpose(axis=[0,2,1,3])------>out2(shape=10,3,2,5) """ def test_partial_fusion_3(self): @mb.program(input_specs=[mb.TensorSpec(shape=(10, 2, 3, 5))]) def prog(x): x = mb.relu(x=x) x = mb.transpose(x=x, perm=[0, 2, 1, 3]) x1 = mb.transpose(x=x, perm=[0, 2, 1, 3]) x2 = mb.relu(x=x) return x1, x2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["relu", "transpose", "transpose", "relu"], ) self.assertEqual(get_op_types_in_program(prog), ["relu", "relu", "transpose"]) assert block.outputs[0] == block.find_ops(op_type="relu")[0].outputs[0] assert_model_is_valid( prog, {"x": (10, 2, 3, 5)}, expected_output_shapes={ block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 3, 2, 5), }, ) """ Input graph: input(shape=10,2,3,5)-->relu--->transpose(axis=[0,2,1,3])----->transpose(axis=[0,2,1,3])---->out1(shape=10,2,3,5) | ------>out2(shape=10,3,2,5) Output graph: same as input graph as one of the optimizing transpose is connected to model output """ def test_partial_fusion_4(self): @mb.program(input_specs=[mb.TensorSpec(shape=(10, 2, 3, 5))]) def prog(x): x = mb.relu(x=x) out2 = mb.transpose(x=x, perm=[0, 2, 1, 3]) out1 = mb.transpose(x=out2, perm=[0, 2, 1, 3]) return out1, out2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["relu", "transpose", "transpose"] ) self.assertEqual( get_op_types_in_program(prog), ["relu", "transpose", "transpose"] ) assert block.outputs[1] == block.find_ops(op_type="transpose")[0].outputs[0] assert_model_is_valid( prog, {"x": (10, 2, 3, 5)}, expected_output_shapes={ block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 3, 2, 5), }, ) """ Input graph: input(shape=10,2,3,5)-->relu-->transpose(axis=[0,2,1,3])--->relu--->transpose(axis=[0,2,1,3]) ---->out1(shape=10,2,3,5) | |--->relu-->pool--------------->out2(shape=10,3,2,5) | |----->pool--------------->out3(shape=10.3.2.5) Output graph: same as the input graph as materialization ops are greater than cancel ops """ def test_no_fusion_more_materialization_ops(self): @mb.program(input_specs=[mb.TensorSpec(shape=(10, 2, 3, 5))]) def prog(x): x = mb.relu(x=x) x = mb.transpose(x=x, perm=[0, 2, 1, 3]) x1 = mb.relu(x=x) y2 = mb.transpose(x=x1, perm=[0, 2, 1, 3]) x2 = mb.relu(x=x1) y3 = mb.avg_pool( x=x2, kernel_sizes=[1, 1], strides=[1, 1], pad_type="valid" ) y4 = mb.avg_pool( x=x1, kernel_sizes=[1, 1], strides=[1, 1], pad_type="valid" ) return y2, y3, y4 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["relu", "transpose", "relu", "transpose", "relu", "avg_pool", "avg_pool"], ) self.assertEqual( get_op_types_in_program(prog), ["relu", "transpose", "relu", "transpose", "relu", "avg_pool", "avg_pool"], ) assert_model_is_valid( prog, {"x": (10, 2, 3, 5)}, expected_output_shapes={ block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 3, 2, 5), block.outputs[2].name: (10, 3, 2, 5), }, ) """ Input graph: input(shape=10,2,3)--->transpose(axis=[0,2,1])----->relu---->transpose(axis=[0,2,1])---->out1 | | --->reduce(axis=2)----->log---->transpose(axis=[0,2,1])---->out2 Output graph: input(shape=10,2,3)----->relu---->out1 | | --->reduce(axis=1)----->log---->out2 """ def test_fusion_with_axis_op(self): @mb.program(input_specs=[mb.TensorSpec(shape=(10, 2, 3))]) def prog(x): x = mb.transpose(x=x, perm=[0, 2, 1]) x1 = mb.relu(x=x) x2 = mb.reduce_mean(x=x, axes=[2], keep_dims=True) y1 = mb.transpose(x=x1, perm=[0, 2, 1]) x3 = mb.log(x=x2) y2 = mb.transpose(x=x3, perm=[0, 2, 1]) return y1, y2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "relu", "reduce_mean", "transpose", "log", "transpose"], ) self.assertEqual(get_op_types_in_program(prog), ["relu", "reduce_mean", "log"]) assert list(block.find_ops(op_type="reduce_mean")[0].inputs["axes"].val) == [1] assert_model_is_valid( prog, {"x": (10, 2, 3)}, expected_output_shapes={ block.outputs[0].name: (10, 2, 3), block.outputs[1].name: (10, 1, 3), }, ) """ Input graph: input(shape=11,2,3,6)--->transpose(axis=[0,3,1,2])--- | | --->pad(pad=[0,0,0,0,1,2,3,4]) | |-->log--->transpose(axis=[0,2,3,1])-->out1(shape=11,5,10,6) Output graph: same as input graph, as transpose cannot be pushed through the pad op since "reflect" mode is only supported along the last two axis """ def test_fusion_with_pad_reflective_op_0(self): @mb.program(input_specs=[mb.TensorSpec(shape=(11, 2, 3, 6))]) def prog(x): x = mb.transpose(x=x, perm=[0, 3, 1, 2]) x2 = mb.pad(x=x, pad=[0, 0, 0, 0, 1, 2, 3, 4], mode="reflect") x3 = mb.log(x=x2) y2 = mb.transpose(x=x3, perm=[0, 2, 3, 1]) return y2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "pad", "log", "transpose"] ) self.assertEqual( get_op_types_in_program(prog), ["transpose", "pad", "log", "transpose"] ) assert list(block.find_ops(op_type="pad")[0].inputs["pad"].val.flatten()) == [ 0, 0, 0, 0, 1, 2, 3, 4, ] assert_model_is_valid( prog, {"x": (11, 2, 3, 6)}, expected_output_shapes={block.outputs[0].name: (11, 5, 10, 6)}, ) """ Input graph: input(shape=11,2,3,6)--->transpose(axis=[0,1,3,2])--- | | --->pad(pad=[0,0,0,0,1,2,3,4]) | |-->log--->transpose(axis=[0,1,3,2])-->out1(shape=11,2,10,9) Output graph: input(shape=11,2,3,6)--->pad(pad=[0,0,0,0,3,4,1,2])-->log-->out1(shape=11,2,10,9) """ def test_fusion_with_pad_reflective_op_1(self): @mb.program(input_specs=[mb.TensorSpec(shape=(11, 2, 3, 6))]) def prog(x): x = mb.transpose(x=x, perm=[0, 1, 3, 2]) x2 = mb.pad(x=x, pad=[0, 0, 0, 0, 1, 2, 3, 4], mode="reflect") x3 = mb.log(x=x2) y2 = mb.transpose(x=x3, perm=[0, 1, 3, 2]) return y2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "pad", "log", "transpose"] ) self.assertEqual(get_op_types_in_program(prog), ["pad", "log"]) assert list(block.find_ops(op_type="pad")[0].inputs["pad"].val.flatten()) == [ 0, 0, 0, 0, 3, 4, 1, 2, ] assert_model_is_valid( prog, {"x": (11, 2, 3, 6)}, expected_output_shapes={block.outputs[0].name: (11, 2, 10, 9)}, ) """ Input graph: input(shape=11,2,3,6)--->transpose(axis=[0,3,1,2])--- | | --->pad(pad=[0,0,0,0,1,2,3,4]) | |-->log--->transpose(axis=[0,2,3,1])-->out1(shape=11,5,10,6) Output graph: input(shape=11,2,3,6)--->pad(pad=[0,0,1,2,3,4,0,0])-->log-->out1(shape=11,5,10,6) """ def test_fusion_with_pad_constant_op(self): @mb.program(input_specs=[mb.TensorSpec(shape=(11, 2, 3, 6))]) def prog(x): x = mb.transpose(x=x, perm=[0, 3, 1, 2]) x2 = mb.pad( x=x, pad=[0, 0, 0, 0, 1, 2, 3, 4], mode="constant", constant_val=3.0 ) x3 = mb.log(x=x2) y2 = mb.transpose(x=x3, perm=[0, 2, 3, 1]) return y2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "pad", "log", "transpose"] ) self.assertEqual(get_op_types_in_program(prog), ["pad", "log"]) assert list(block.find_ops(op_type="pad")[0].inputs["pad"].val.flatten()) == [ 0, 0, 1, 2, 3, 4, 0, 0, ] assert_model_is_valid( prog, {"x": (11, 2, 3, 6)}, expected_output_shapes={block.outputs[0].name: (11, 5, 10, 6)}, ) """ Input graph: const(shape=2) | V input(shape=1,2,5,5)--->transpose(axis=[0,2,3,1])--->add---->transpose(axis=[0,3,1,2])--->out(shape=1,2,5,5) Output graph: const(shape=1,2,1,1) | V input(shape=1,2,5,5)--->add--->out(shape=1,2,5,5) """ def test_fusion_with_add_constant_op(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 5, 5))]) def prog(x): x = mb.transpose(x=x, perm=[0, 2, 3, 1]) x = mb.add(x=x, y=np.array([10, 100])) x = mb.transpose(x=x, perm=[0, 3, 1, 2]) return x prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "add", "transpose"] ) self.assertEqual(get_op_types_in_program(prog), ["add"]) assert_model_is_valid( prog, {"x": (1, 2, 5, 5)}, expected_output_shapes={block.outputs[0].name: (1, 2, 5, 5)}, ) """ Input graph: const(scalar) | V input(shape=1,2,5,5)--->transpose(axis=[0,2,3,1])--->add---->transpose(axis=[0,3,1,2])--->out(shape=1,2,5,5) Output graph: const(scalar) | V input(shape=1,2,5,5)--->add--->out(shape=1,2,5,5) """ def test_fusion_with_add_scalar_constant_op(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 5, 5))]) def prog(x): x = mb.transpose(x=x, perm=[0, 2, 3, 1]) x = mb.add(x=5, y=x) x = mb.transpose(x=x, perm=[0, 3, 1, 2]) return x prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "add", "transpose"] ) self.assertEqual(get_op_types_in_program(prog), ["add"]) assert_model_is_valid( prog, {"x": (1, 2, 5, 5)}, expected_output_shapes={block.outputs[0].name: (1, 2, 5, 5)}, ) """ Input graph: input(shape=1,2,5,5)----->transpose(axis=[0,2,3,1])--->add---->transpose(axis=[0,3,1,2])--->out(shape=1,2,5,5) | ^ | | |---->relu---->transpose(axis=[0,2,3,1]) Output graph: input(shape=1,2,5,5)----->add--->out(shape=1,2,5,5) | ^ | | |------>relu """ def test_fusion_with_add_broadcastable_0(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 5, 5))]) def prog(x): x1 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x2 = mb.relu(x=x) x2 = mb.transpose(x=x2, perm=[0, 2, 3, 1]) x3 = mb.add(x=x1, y=x2) y = mb.transpose(x=x3, perm=[0, 3, 1, 2]) return y prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "relu", "transpose", "add", "transpose"], ) self.assertEqual(get_op_types_in_program(prog), ["relu", "add"]) assert block.find_ops(op_type="relu")[0].inputs["x"] == block.inputs["x"] assert block.find_ops(op_type="add")[0].inputs["x"] == block.inputs["x"] assert ( block.find_ops(op_type="add")[0].inputs["y"] == block.find_ops(op_type="relu")[0].outputs[0] ) assert_model_is_valid( prog, {"x": (1, 2, 5, 5)}, expected_output_shapes={block.outputs[0].name: (1, 2, 5, 5)}, ) """ Input graph: input(shape=1,2,5,5)----->transpose(axis=[0,2,3,1])--->add---->transpose(axis=[0,3,1,2])--->out(shape=1,2,5,5) | ^ | | |----------------------->transpose(axis=[0,2,3,1]) Output graph: input(shape=1,2,5,5)----->add--->out(shape=1,2,5,5) | ^ | | |--------- """ def test_fusion_with_add_broadcastable_1(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 5, 5))]) def prog(x): x1 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x2 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x3 = mb.add(x=x1, y=x2) y = mb.transpose(x=x3, perm=[0, 3, 1, 2]) return y prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "transpose", "add", "transpose"], ) self.assertEqual(get_op_types_in_program(prog), ["add"]) assert block.find_ops(op_type="add")[0].inputs["x"] == block.inputs["x"] assert block.find_ops(op_type="add")[0].inputs["y"] == block.inputs["x"] assert_model_is_valid( prog, {"x": (1, 2, 5, 5)}, expected_output_shapes={block.outputs[0].name: (1, 2, 5, 5)}, ) """ Input graph: input(shape=1,2,5,5)--->transpose(axis=[0,2,3,1])---> relu---->concat(axis=3)----->transpose(axis=[0,3,1,2])----->out1(shape=1,4,5,5) | ^ | | |->transpose(axis=[0,2,3,1])--->relu------------ Output graph: input(shape=1,2,5,5)------> relu---->concat(axis=1)--->out1(shape=1,4,5,5) | ^ | | |---->relu------------ """ def test_concat_pattern_0(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 5, 5))]) def prog(x): x1 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x2 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x1 = mb.relu(x=x1) x2 = mb.relu(x=x2) x3 = mb.concat(values=[x1, x2], axis=3) x4 = mb.transpose(x=x3, perm=[0, 3, 1, 2]) return x4 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "transpose", "relu", "relu", "concat", "transpose"], ) self.assertEqual(get_op_types_in_program(prog), ["relu", "relu", "concat"]) assert_model_is_valid( prog, {"x": (1, 2, 5, 5)}, expected_output_shapes={block.outputs[0].name: (1, 4, 5, 5)}, ) """ Input graph: input(shape=1,2,5,5)--->transpose(axis=[0,2,3,1])---> relu---->concat(axis=3)----->transpose(axis=[0,3,1,2])----->out1(shape=1,4,5,5) | ^ | | |->transpose(axis=[0,2,3,1])------->relu-------- | V pool--->out2(shape=1,5,5,2) Output graph: input(shape=1,2,5,5)------> relu---->concat(axis=1)--->out1(shape=1,4,5,5) | ^ | | |---->relu------------ | |--->transpose(axis=[0,2,3,1])---->pool--->out2(shape=1,5,5,2) """ def test_concat_pattern_1(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 5, 5))]) def prog(x): x1 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x2 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x1 = mb.relu(x=x1) x2 = mb.relu(x=x2) x3 = mb.concat(values=[x1, x2], axis=3) x4 = mb.transpose(x=x3, perm=[0, 3, 1, 2]) x5 = mb.avg_pool( x=x2, kernel_sizes=[1, 1], strides=[1, 1], pad_type="valid" ) return x4, x5 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), [ "transpose", "transpose", "relu", "relu", "concat", "transpose", "avg_pool", ], ) self.assertEqual( get_op_types_in_program(prog), ["relu", "relu", "concat", "transpose", "avg_pool"], ) assert_model_is_valid( prog, {"x": (1, 2, 5, 5)}, expected_output_shapes={ block.outputs[0].name: (1, 4, 5, 5), block.outputs[1].name: (1, 5, 5, 2), }, ) """ Input graph: input(shape=1,2,5,5)--->transpose(axis=[0,2,3,1])---> relu---->concat(axis=3)----->transpose(axis=[0,3,1,2])----->out1(shape=1,4,5,5) | ^ | | |->transpose(axis=[0,2,3,1])------->relu-------- | V relu--->out2(shape=1,5,5,2) Output graph: input(shape=1,2,5,5)------> relu---->concat(axis=1)--->out1(shape=1,4,5,5) | ^ | | |---->relu------------ | |--->relu---->transpose(axis=[0,2,3,1])---->out2(shape=1,5,5,2) """ def test_concat_pattern_2(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 5, 5))]) def prog(x): x1 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x2 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x1 = mb.relu(x=x1) x2 = mb.relu(x=x2) x3 = mb.concat(values=[x1, x2], axis=3) x4 = mb.transpose(x=x3, perm=[0, 3, 1, 2]) x5 = mb.relu(x=x2) return x4, x5 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "transpose", "relu", "relu", "concat", "transpose", "relu"], ) self.assertEqual( get_op_types_in_program(prog), ["relu", "relu", "concat", "relu", "transpose"], ) assert_model_is_valid( prog, {"x": (1, 2, 5, 5)}, expected_output_shapes={ block.outputs[0].name: (1, 4, 5, 5), block.outputs[1].name: (1, 5, 5, 2), }, ) """ Input graph: input(shape=1,2,5,5)--->transpose(axis=[0,2,3,1])---> relu---->concat(axis=3)----->transpose(axis=[0,3,1,2])----->out1(shape=1,4,5,5) | ^ | | |->transpose(axis=[0,2,3,1])------->relu-------- | V out2(shape=1,5,5,2) Output graph: input(shape=1,2,5,5)------> relu---->concat(axis=1)--->out1(shape=1,4,5,5) | ^ | | |---->relu------------ | |--->transpose(axis=[0,2,3,1])---->out2(shape=1,5,5,2) """ def test_concat_pattern_3(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 5, 5))]) def prog(x): x1 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x2 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x1 = mb.relu(x=x1) x2 = mb.relu(x=x2) x3 = mb.concat(values=[x1, x2], axis=3) x4 = mb.transpose(x=x3, perm=[0, 3, 1, 2]) return x4, x2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "transpose", "relu", "relu", "concat", "transpose"], ) self.assertEqual( get_op_types_in_program(prog), ["relu", "relu", "concat", "transpose"] ) assert_model_is_valid( prog, {"x": (1, 2, 5, 5)}, expected_output_shapes={ block.outputs[0].name: (1, 4, 5, 5), block.outputs[1].name: (1, 5, 5, 2), }, ) """ Input graph: input(shape=1,2,5,5)--->transpose(axis=[0,2,3,1])---> relu---->concat(axis=3)----->transpose(axis=[0,3,1,2])----->out1(shape=1,4,5,5) | ^ | | |->transpose(axis=[0,2,3,1])------->relu-------- | V transpose(axis=[0,3,1,2]) -----> out2(shape=1,2,5,5) Output graph: input(shape=1,2,5,5)---> relu---->concat(axis=1)----->out1(shape=1,4,5,5) | ^ | | |------------------->relu-------->out2(shape=1,2,5,5) """ def test_concat_pattern_4(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 5, 5))]) def prog(x): x1 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x2 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x1 = mb.relu(x=x1) x2 = mb.relu(x=x2) x3 = mb.concat(values=[x1, x2], axis=3) x4 = mb.transpose(x=x3, perm=[0, 3, 1, 2]) x5 = mb.transpose(x=x2, perm=[0, 3, 1, 2]) return x4, x5 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), [ "transpose", "transpose", "relu", "relu", "concat", "transpose", "transpose", ], ) self.assertEqual(get_op_types_in_program(prog), ["relu", "relu", "concat"]) assert_model_is_valid( prog, {"x": (1, 2, 5, 5)}, expected_output_shapes={ block.outputs[0].name: (1, 4, 5, 5), block.outputs[1].name: (1, 2, 5, 5), }, ) """ Input graph: constant(shape=[30,10,5]) | V input(shape=10,20,30)--->transpose(axis=[2,0,1])--->concat(axis=2)----->transpose(axis=[1,2,0])----->out1(shape=10,25,30) Output graph: constant(shape=[10,5,30]) | V input(shape=10,20,30)--->concat(axis=1)----->out1(shape=10,25,30) """ def test_concat_pattern_5(self): const = np.random.rand(30, 10, 5) @mb.program(input_specs=[mb.TensorSpec(shape=(10, 20, 30))]) def prog(x): x1 = mb.transpose(x=x, perm=[2, 0, 1]) c = mb.const(val=const) x2 = mb.concat(values=[x1, c], axis=2) x3 = mb.transpose(x=x2, perm=[1, 2, 0]) return x3 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "concat", "transpose"] ) self.assertEqual(get_op_types_in_program(prog), ["concat"]) assert_model_is_valid( prog, {"x": (10, 20, 30)}, expected_output_shapes={block.outputs[0].name: (10, 25, 30)}, ) """ Input graph: input2(shape=30,10,20)-----| | input(shape=10,20,30)--->transpose(axis=[2,0,1])----->relu-----|----->concat(axis=2)------>out1(shape=90,10,20) | | |-->relu-----| | |-->relu---->transpose(axis=[1,2,0])---->out2(shape=10,20,30) | |-->relu---->transpose(axis=[1,2,0])---->out3(shape=10,20,30) | |-->relu---->transpose(axis=[1,2,0])---->out4(shape=10,20,30) Output graph: input2(shape=30,10,20)-----| | input(shape=10,20,30)----->relu--->transpose(axis=[2,0,1])-----|----->concat(axis=2)------>out1(shape=90,10,20) | | |-->relu--->transpose(axis=[2,0,1])-----| | |-->relu---->out2(shape=10,20,30) | |-->relu---->out3(shape=10,20,30) | |-->relu---->out4(shape=10,20,30) Output graph: """ def test_concat_pattern_6(self): @mb.program( input_specs=[ mb.TensorSpec(shape=(10, 20, 30)), mb.TensorSpec(shape=(30, 10, 20)), ] ) def prog(x, y): x1 = mb.transpose(x=x, perm=[2, 0, 1]) r1 = mb.relu(x=x1) r2 = mb.relu(x=x1) r3 = mb.relu(x=x1) r4 = mb.relu(x=x1) r5 = mb.relu(x=x1) x2 = mb.concat(values=[r1, r2, y], axis=0) x3 = mb.transpose(x=r3, perm=[1, 2, 0]) x4 = mb.transpose(x=r4, perm=[1, 2, 0]) x5 = mb.transpose(x=r5, perm=[1, 2, 0]) return x2, x3, x4, x5 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), [ "transpose", "relu", "relu", "relu", "relu", "relu", "concat", "transpose", "transpose", "transpose", ], ) self.assertEqual( get_op_types_in_program(prog), [ "relu", "relu", "relu", "relu", "relu", "transpose", "transpose", "concat", ], ) assert_model_is_valid( prog, {"x": (10, 20, 30), "y": (30, 10, 20)}, expected_output_shapes={ block.outputs[0].name: (90, 10, 20), block.outputs[1].name: (10, 20, 30), block.outputs[2].name: (10, 20, 30), block.outputs[3].name: (10, 20, 30), }, ) """ Input graph: input(shape=1,4,5,6)--->transpose(axis=[0,3,2,1])--->relu---->split(axis=1, num_splits=2)----->transpose(axis=[0,3,2,1])----->out1(shape=1,4,5,3) | v transpose(axis[0,3,2,1])-------------------------->out2(shape=1,4,5,3) Output graph: input(shape=1,4,5,6)------> relu ---->split(axis=3)--->out1(shape=1,4,5,3) | v out2(shape=1,4,5,3) """ def test_split_nd_pattern_0(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 4, 5, 6))]) def prog(x): x1 = mb.transpose(x=x, perm=[0, 3, 2, 1]) x1 = mb.relu(x=x1) x2, x3 = mb.split(x=x1, axis=1, num_splits=2) x4 = mb.transpose(x=x2, perm=[0, 3, 2, 1]) x5 = mb.transpose(x=x3, perm=[0, 3, 2, 1]) return x4, x5 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "relu", "split", "transpose", "transpose"], ) self.assertEqual(get_op_types_in_program(prog), ["relu", "split"]) assert_model_is_valid( prog, {"x": (1, 4, 5, 6)}, expected_output_shapes={block.outputs[0].name: (1, 4, 5, 3), block.outputs[1].name: (1, 4, 5, 3)}, ) self.assertEqual(block.find_ops(op_type="split")[0].axis.val, 3) """ Input graph: input(shape=1,4,5,6)--->transpose(axis=[0,3,2,1])--->relu---->splitd(axis=1, num_splits=6)----->transpose(axis=[0,3,2,1])----->out1(shape=1,4,5,3) | v transpose(axis[0,3,2,1])-------------------------------------->out2(shape=1,4,5,3) Output graph: input(shape=1,4,5,6)------>relu---->split(axis=3)--->out1(shape=1,4,5,3) | v out2(shape=1,4,5,3) """ def test_split_nd_pattern_1(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 4, 5, 6))]) def prog(x): x1 = mb.transpose(x=x, perm=[0, 3, 2, 1]) x1 = mb.relu(x=x1) x2, x3, x4, x5, x6, x7 = mb.split(x=x1, axis=1, num_splits=6) x2 = mb.transpose(x=x2, perm=[0, 3, 2, 1]) x3 = mb.transpose(x=x3, perm=[0, 3, 2, 1]) x4 = mb.transpose(x=x4, perm=[0, 3, 2, 1]) x5 = mb.transpose(x=x5, perm=[0, 3, 2, 1]) x6 = mb.transpose(x=x6, perm=[0, 3, 2, 1]) x7 = mb.transpose(x=x7, perm=[0, 3, 2, 1]) return x2, x3, x4, x5, x6, x7 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "relu", "split", "transpose", "transpose", "transpose", "transpose", "transpose", "transpose"], ) self.assertEqual(get_op_types_in_program(prog), ["relu", "split"]) assert_model_is_valid( prog, {"x": (1, 4, 5, 6)}, expected_output_shapes={block.outputs[0].name: (1, 4, 5, 1), block.outputs[1].name: (1, 4, 5, 1), block.outputs[2].name: (1, 4, 5, 1), block.outputs[3].name: (1, 4, 5, 1), block.outputs[4].name: (1, 4, 5, 1), block.outputs[5].name: (1, 4, 5, 1)}, ) self.assertEqual(block.find_ops(op_type="split")[0].axis.val, 3) """ Input graph: input(shape=1,4,5,6)--->transpose(axis=[0,3,2,1])---> split(axis=1, num_splits=2) ----> concat(axis=1) ----->transpose(axis=[0,3,2,1]) ----->out1(shape=1,4,5,6) | ^ v | relu() ---------------------- Output graph: input(shape=1,4,5,6)------>split(axis=3)--->concat(axis=3) -------> out1(shape=1,4,5,6) | ^ v | relu() -------------- """ def test_split_nd_pattern_2(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 4, 5, 6))]) def prog(x): x1 = mb.transpose(x=x, perm=[0, 3, 2, 1]) x2, x3 = mb.split(x=x1, axis=1, num_splits=2) x4 = mb.relu(x=x2) x5 = mb.concat(values=[x4, x3], axis=1) x6 = mb.transpose(x=x5, perm=[0, 3, 2, 1]) return x6 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "split", "relu", "concat", "transpose"] ) self.assertEqual(get_op_types_in_program(prog), ["split", "relu", "concat"]) assert_model_is_valid( prog, {"x": (1, 4, 5, 6)}, expected_output_shapes={block.outputs[0].name: (1, 4, 5, 6)}, ) self.assertEqual(block.find_ops(op_type="split")[0].axis.val, 3) """ Input graph: input(shape=1,5,5,3)----->transpose(axis=[0,3,1,2]) | ---->relu-------------->transpose(axis=[0,2,3,1]) | | | V | relu | | | V | transpose(axis=[0,3,1,2]) | | | V ----------------> add --------> relu---->pool---->out(shape=1,3,5,5) Output graph: input(shape=1,5,5,3)---->relu------------------------> relu | | | V ----------------> add | V relu | V transpose(axis=[0,3,1,2])-->pool---->out(shape=1,3,5,5) """ def test_skip_connection_pattern_0(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 5, 5, 3))]) def prog(x): x = mb.transpose(x=x, perm=[0, 3, 1, 2]) x = mb.relu(x=x) x1 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x2 = mb.relu(x=x1) x3 = mb.transpose(x=x2, perm=[0, 3, 1, 2]) x4 = mb.add(x=x, y=x3) x5 = mb.relu(x=x4) x6 = mb.avg_pool( x=x5, kernel_sizes=[1, 1], strides=[1, 1], pad_type="valid" ) return x6 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), [ "transpose", "relu", "transpose", "relu", "transpose", "add", "relu", "avg_pool", ], ) self.assertEqual( get_op_types_in_program(prog), ["relu", "relu", "add", "relu", "transpose", "avg_pool"], ) assert_model_is_valid( prog, {"x": (1, 5, 5, 3)}, expected_output_shapes={block.outputs[0].name: (1, 3, 5, 5)}, ) """ Input graph: input(shape=1,5,5,3)----->transpose(axis=[0,3,1,2]) | ---->relu-------------->transpose(axis=[0,2,3,1]) | | | V | relu | | | V | transpose(axis=[0,3,1,2]) | | | V ----------------> add -->transpose(axis=[0,2,3,1]) | V relu---->pool---->out(shape=1,5,5,3) Output graph: input(shape=1,5,5,3)---->relu------------------------> relu | | | V ----------------> add | V relu | V pool---->out(shape=1,5,5,3) """ def test_skip_connection_pattern_1(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 5, 5, 3))]) def prog(x): x = mb.transpose(x=x, perm=[0, 3, 1, 2]) x = mb.relu(x=x) x1 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x2 = mb.relu(x=x1) x3 = mb.transpose(x=x2, perm=[0, 3, 1, 2]) x4 = mb.add(x=x, y=x3) x4 = mb.transpose(x=x4, perm=[0, 2, 3, 1]) x5 = mb.relu(x=x4) x6 = mb.avg_pool( x=x5, kernel_sizes=[1, 1], strides=[1, 1], pad_type="valid" ) return x6 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), [ "transpose", "relu", "transpose", "relu", "transpose", "add", "transpose", "relu", "avg_pool", ], ) self.assertEqual( get_op_types_in_program(prog), ["relu", "relu", "add", "relu", "avg_pool"] ) assert_model_is_valid( prog, {"x": (1, 5, 5, 3)}, expected_output_shapes={block.outputs[0].name: (1, 5, 5, 3)}, ) """ Input graph: input(shape=2,5)--->transpose(axis=[1,0])--->transpose(axis=[1,0])-->reduce(axis=1) | | | V | transpose(axis=[1,0]) | | | V -------------------------------------------->add------->out(shape=5,2) Output graph: input(shape=2,5)--->reduce(axis=1)---->add---->transpose(axis=[1,0])--->out(shape=5,2) | ^ | | ------------------------ """ def test_residual_with_unmaterialized_output(self): @mb.program(input_specs=[mb.TensorSpec(shape=(2, 5))]) def prog(x): x1 = mb.transpose(x=x, perm=[1,0]) t1 = mb.transpose(x=x1, perm=[1,0]) x2 = mb.reduce_mean(x=t1, axes=[1], keep_dims=True) t2 = mb.transpose(x=x2, perm=[1,0]) return mb.add(x=x1, y=t2) prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), [ 'transpose', 'transpose', 'reduce_mean', 'transpose', 'add' ] ) self.assertEqual( get_op_types_in_program(prog), ['reduce_mean', 'add', 'transpose'] ) assert_model_is_valid( prog, {'x': (2, 5)}, expected_output_shapes={block.outputs[0].name: (5,2)} ) """ Input graph: input(shape=2,5)--->transpose(axis=[1,0])--->transpose(axis=[1,0])-->reduce(axis=1) | | | V | transpose(axis=[1,0]) | | | V -------------------------------------------->add------->out1(shape=5,2) | V relu------->out2(shape=5,2) Output graph: input(shape=2,5)--->reduce(axis=1)----> add ----->transpose(axis=[1,0])----->out1(shape=5,2) | | | V ---------------------> relu----->transpose(axis=[1,0])----->out2(shape=5,2) """ def test_residual_with_unmaterialized_multiple_output(self): @mb.program(input_specs=[mb.TensorSpec(shape=(2, 5))]) def prog(x): x1 = mb.transpose(x=x, perm=[1,0]) t1 = mb.transpose(x=x1, perm=[1,0]) x2 = mb.reduce_mean(x=t1, axes=[1], keep_dims=True) t2 = mb.transpose(x=x2, perm=[1,0]) out1 = mb.add(x=x1, y=t2) out2 = mb.relu(x=out1) return out1, out2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), [ 'transpose', 'transpose', 'reduce_mean', 'transpose', 'add', 'relu' ] ) self.assertEqual( get_op_types_in_program(prog), ['reduce_mean', 'add', 'relu', 'transpose', 'transpose'] ) assert_model_is_valid( prog, {'x': (2, 5)}, expected_output_shapes={block.outputs[0].name: (5,2), block.outputs[1].name: (5,2)} ) """ Input graph: input(shape=2,5)---->transpose(axis=[1,0])------>relu----->transpose(axis=[1,0])------>out2(shape=2,5) | ------->out1(shape=5,2) Output graph: input(shape=2,5)---->relu-----> out2(shape=2,5) | V transpose(axis=[1,0]) -----> out1(shape=5,2) """ def test_materialized_output_reuse(self): @mb.program(input_specs=[mb.TensorSpec(shape=(2, 5))]) def prog(x): x1 = mb.transpose(x=x, perm=[1,0]) y1 = mb.relu(x=x1) y2 = mb.transpose(x=y1, perm=[1,0]) return y1, y2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), [ 'transpose', 'relu', 'transpose', ] ) self.assertEqual( get_op_types_in_program(prog), ['relu', 'transpose'] ) assert_model_is_valid( prog, {'x': (2, 5)}, expected_output_shapes={block.outputs[0].name: (5,2), block.outputs[1].name: (2,5)} ) """ Input graph: input(shape=1,2,5,5)----->transpose(axis=[0,2,3,1])------->add------------>transpose(axis=[0,3,1,2])--->out1(shape=1,2,5,5) | ^ | | | | ---->relu ----->transpose(axis=[0,3,1,2])--->out2(shape=1,2,5,5) Output graph: input(shape=1,2,5,5)----->add------->out1(shape=1,2,5,5) | ^ | | | | |------>relu ------identity(renaming)---->out2(shape=1,2,5,5) """ def test_fusion_with_double_outputs(self): @mb.program(input_specs=[mb.TensorSpec(shape=(1, 2, 5, 5))]) def prog(x): x1 = mb.transpose(x=x, perm=[0, 2, 3, 1]) x2 = mb.relu(x=x1) x3 = mb.add(x=x1, y=x2) y1 = mb.transpose(x=x3, perm=[0, 3, 1, 2]) y2 = mb.transpose(x=x3, perm=[0, 3, 1, 2]) return y1, y2 prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "relu", "add", "transpose", "transpose"], ) self.assertEqual(get_op_types_in_program(prog), ["relu", "add", "identity"]) assert block.find_ops(op_type="relu")[0].inputs["x"] == block.inputs["x"] assert block.find_ops(op_type="add")[0].inputs["x"] == block.inputs["x"] assert ( block.find_ops(op_type="add")[0].inputs["y"] == block.find_ops(op_type="relu")[0].outputs[0] ) assert_model_is_valid( prog, {"x": (1, 2, 5, 5)}, expected_output_shapes={block.outputs[0].name: (1, 2, 5, 5)}, ) def test_pass_through_broadcasted_binary_op(self): """ Input graph: const | input --> transpose --> add --> transpose --> relu Output graph: const | input --> add --> relu Note: the `const` op is of shape (1, 1, 1, 3) which is pre-broadcasted. """ @mb.program(input_specs=[mb.TensorSpec(shape=(1, 4, 3, 2))]) def prog(x): x = mb.transpose(x=x, perm=[0, 3, 1, 2]) x = mb.add(x=x, y=np.array(np.ones(shape=(1, 1, 1, 3)))) x = mb.transpose(x=x, perm=[0, 2, 3, 1]) x = mb.relu(x=x) return x prev_prog, prev_block, block = apply_pass_and_basic_check( prog, "common::reduce_transposes" ) self.assertEqual( get_op_types_in_program(prev_prog), ["transpose", "add", "transpose", "relu"], ) self.assertEqual(get_op_types_in_program(prog), ["add", "relu"]) assert_model_is_valid( prog, {"x": (1, 4, 3, 2)}, expected_output_shapes={block.outputs[0].name: (1, 4, 3, 2)}, )
[ "numpy.random.rand", "coremltools.converters.mil.testing_utils.apply_pass_and_basic_check", "numpy.array", "coremltools.converters.mil.testing_utils.get_op_types_in_program", "coremltools.converters.mil.mil.Builder.TensorSpec", "coremltools.converters.mil.mil.Builder.identity", "numpy.random.seed", "c...
[((499, 519), 'numpy.random.seed', 'np.random.seed', (['(1984)'], {}), '(1984)\n', (513, 519), True, 'import numpy as np\n'), ((1054, 1115), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (1080, 1115), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((1327, 1434), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (10, 20)}"], {'expected_output_shapes': '{block.outputs[0].name: (10, 20)}'}), "(prog, {'x': (10, 20)}, expected_output_shapes={block.\n outputs[0].name: (10, 20)})\n", (1348, 1434), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((1972, 2033), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (1998, 2033), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((2249, 2356), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (10, 20)}"], {'expected_output_shapes': '{block.outputs[0].name: (10, 20)}'}), "(prog, {'x': (10, 20)}, expected_output_shapes={block.\n outputs[0].name: (10, 20)})\n", (2270, 2356), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((2990, 3051), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (3016, 3051), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((3310, 3425), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 3, 4)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 2, 3, 4)}'}), "(prog, {'x': (1, 2, 3, 4)}, expected_output_shapes={\n block.outputs[0].name: (1, 2, 3, 4)})\n", (3331, 3425), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((4076, 4137), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (4102, 4137), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((4406, 4521), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 3, 4)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 2, 3, 4)}'}), "(prog, {'x': (1, 2, 3, 4)}, expected_output_shapes={\n block.outputs[0].name: (1, 2, 3, 4)})\n", (4427, 4521), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((5568, 5629), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (5594, 5629), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((5923, 6075), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 3, 4)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 2, 3, 4), block.outputs[1].name: (1, 4, 2, 3)}'}), "(prog, {'x': (1, 2, 3, 4)}, expected_output_shapes={\n block.outputs[0].name: (1, 2, 3, 4), block.outputs[1].name: (1, 4, 2, 3)})\n", (5944, 6075), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((6688, 6749), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (6714, 6749), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((6965, 7080), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 3, 4)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 2, 3, 4)}'}), "(prog, {'x': (1, 2, 3, 4)}, expected_output_shapes={\n block.outputs[0].name: (1, 2, 3, 4)})\n", (6986, 7080), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((8071, 8132), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (8097, 8132), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((8614, 8760), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (10, 2, 3)}"], {'expected_output_shapes': '{block.outputs[0].name: (10, 2, 3), block.outputs[1].name: (10, 2, 3)}'}), "(prog, {'x': (10, 2, 3)}, expected_output_shapes={\n block.outputs[0].name: (10, 2, 3), block.outputs[1].name: (10, 2, 3)})\n", (8635, 8760), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((9924, 9985), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (9950, 9985), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((10768, 10928), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (10, 2, 3, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (10, 3, 5, 2), block.outputs[1].name: (10, 2, 3, 5)}'}), "(prog, {'x': (10, 2, 3, 5)}, expected_output_shapes={\n block.outputs[0].name: (10, 3, 5, 2), block.outputs[1].name: (10, 2, 3, 5)}\n )\n", (10789, 10928), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((12121, 12182), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (12147, 12182), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((12686, 12846), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (10, 2, 3, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 2, 3, 5)}'}), "(prog, {'x': (10, 2, 3, 5)}, expected_output_shapes={\n block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 2, 3, 5)}\n )\n", (12707, 12846), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((14756, 14817), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (14782, 14817), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((15472, 15711), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (10, 2, 3, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 2, 3, 5),\n block.outputs[2].name: (10, 3, 2, 5), block.outputs[3].name: (10, 3, 2, 5)}'}), "(prog, {'x': (10, 2, 3, 5)}, expected_output_shapes={\n block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 2, 3,\n 5), block.outputs[2].name: (10, 3, 2, 5), block.outputs[3].name: (10, 3,\n 2, 5)})\n", (15493, 15711), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((16719, 16780), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (16745, 16780), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((17119, 17279), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (10, 2, 3, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 3, 2, 5)}'}), "(prog, {'x': (10, 2, 3, 5)}, expected_output_shapes={\n block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 3, 2, 5)}\n )\n", (17140, 17279), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((18123, 18184), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (18149, 18184), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((18534, 18694), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (10, 2, 3, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 3, 2, 5)}'}), "(prog, {'x': (10, 2, 3, 5)}, expected_output_shapes={\n block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 3, 2, 5)}\n )\n", (18555, 18694), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((20072, 20133), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (20098, 20133), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((20504, 20701), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (10, 2, 3, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 3, 2, 5),\n block.outputs[2].name: (10, 3, 2, 5)}'}), "(prog, {'x': (10, 2, 3, 5)}, expected_output_shapes={\n block.outputs[0].name: (10, 2, 3, 5), block.outputs[1].name: (10, 3, 2,\n 5), block.outputs[2].name: (10, 3, 2, 5)})\n", (20525, 20701), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((21807, 21868), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (21833, 21868), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((22243, 22389), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (10, 2, 3)}"], {'expected_output_shapes': '{block.outputs[0].name: (10, 2, 3), block.outputs[1].name: (10, 1, 3)}'}), "(prog, {'x': (10, 2, 3)}, expected_output_shapes={\n block.outputs[0].name: (10, 2, 3), block.outputs[1].name: (10, 1, 3)})\n", (22264, 22389), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((23538, 23599), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (23564, 23599), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((24093, 24211), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (11, 2, 3, 6)}"], {'expected_output_shapes': '{block.outputs[0].name: (11, 5, 10, 6)}'}), "(prog, {'x': (11, 2, 3, 6)}, expected_output_shapes={\n block.outputs[0].name: (11, 5, 10, 6)})\n", (24114, 24211), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((25258, 25319), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (25284, 25319), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((25765, 25883), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (11, 2, 3, 6)}"], {'expected_output_shapes': '{block.outputs[0].name: (11, 2, 10, 9)}'}), "(prog, {'x': (11, 2, 3, 6)}, expected_output_shapes={\n block.outputs[0].name: (11, 2, 10, 9)})\n", (25786, 25883), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((26975, 27036), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (27001, 27036), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((27482, 27600), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (11, 2, 3, 6)}"], {'expected_output_shapes': '{block.outputs[0].name: (11, 5, 10, 6)}'}), "(prog, {'x': (11, 2, 3, 6)}, expected_output_shapes={\n block.outputs[0].name: (11, 5, 10, 6)})\n", (27503, 27600), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((28514, 28575), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (28540, 28575), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((28790, 28905), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 5, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 2, 5, 5)}'}), "(prog, {'x': (1, 2, 5, 5)}, expected_output_shapes={\n block.outputs[0].name: (1, 2, 5, 5)})\n", (28811, 28905), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((29800, 29861), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (29826, 29861), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((30076, 30191), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 5, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 2, 5, 5)}'}), "(prog, {'x': (1, 2, 5, 5)}, expected_output_shapes={\n block.outputs[0].name: (1, 2, 5, 5)})\n", (30097, 30191), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((31183, 31244), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (31209, 31244), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((31809, 31924), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 5, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 2, 5, 5)}'}), "(prog, {'x': (1, 2, 5, 5)}, expected_output_shapes={\n block.outputs[0].name: (1, 2, 5, 5)})\n", (31830, 31924), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((32893, 32954), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (32919, 32954), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((33358, 33473), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 5, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 2, 5, 5)}'}), "(prog, {'x': (1, 2, 5, 5)}, expected_output_shapes={\n block.outputs[0].name: (1, 2, 5, 5)})\n", (33379, 33473), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((34619, 34680), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (34645, 34680), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((34959, 35074), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 5, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 4, 5, 5)}'}), "(prog, {'x': (1, 2, 5, 5)}, expected_output_shapes={\n block.outputs[0].name: (1, 4, 5, 5)})\n", (34980, 35074), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((36660, 36721), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (36686, 36721), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((37198, 37350), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 5, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 4, 5, 5), block.outputs[1].name: (1, 5, 5, 2)}'}), "(prog, {'x': (1, 2, 5, 5)}, expected_output_shapes={\n block.outputs[0].name: (1, 4, 5, 5), block.outputs[1].name: (1, 5, 5, 2)})\n", (37219, 37350), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((38895, 38956), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (38921, 38956), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((39299, 39451), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 5, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 4, 5, 5), block.outputs[1].name: (1, 5, 5, 2)}'}), "(prog, {'x': (1, 2, 5, 5)}, expected_output_shapes={\n block.outputs[0].name: (1, 4, 5, 5), block.outputs[1].name: (1, 5, 5, 2)})\n", (39320, 39451), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((40948, 41009), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (40974, 41009), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((41323, 41475), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 5, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 4, 5, 5), block.outputs[1].name: (1, 5, 5, 2)}'}), "(prog, {'x': (1, 2, 5, 5)}, expected_output_shapes={\n block.outputs[0].name: (1, 4, 5, 5), block.outputs[1].name: (1, 5, 5, 2)})\n", (41344, 41475), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((42960, 43021), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (42986, 43021), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((43440, 43592), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 5, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 4, 5, 5), block.outputs[1].name: (1, 2, 5, 5)}'}), "(prog, {'x': (1, 2, 5, 5)}, expected_output_shapes={\n block.outputs[0].name: (1, 4, 5, 5), block.outputs[1].name: (1, 2, 5, 5)})\n", (43461, 43592), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((44306, 44331), 'numpy.random.rand', 'np.random.rand', (['(30)', '(10)', '(5)'], {}), '(30, 10, 5)\n', (44320, 44331), True, 'import numpy as np\n'), ((44675, 44736), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (44701, 44736), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((44957, 45072), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (10, 20, 30)}"], {'expected_output_shapes': '{block.outputs[0].name: (10, 25, 30)}'}), "(prog, {'x': (10, 20, 30)}, expected_output_shapes={\n block.outputs[0].name: (10, 25, 30)})\n", (44978, 45072), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((47485, 47546), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (47511, 47546), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((48265, 48518), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (10, 20, 30), 'y': (30, 10, 20)}"], {'expected_output_shapes': '{block.outputs[0].name: (90, 10, 20), block.outputs[1].name: (10, 20, 30),\n block.outputs[2].name: (10, 20, 30), block.outputs[3].name: (10, 20, 30)}'}), "(prog, {'x': (10, 20, 30), 'y': (30, 10, 20)},\n expected_output_shapes={block.outputs[0].name: (90, 10, 20), block.\n outputs[1].name: (10, 20, 30), block.outputs[2].name: (10, 20, 30),\n block.outputs[3].name: (10, 20, 30)})\n", (48286, 48518), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((49810, 49871), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (49836, 49871), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((50132, 50284), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 4, 5, 6)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 4, 5, 3), block.outputs[1].name: (1, 4, 5, 3)}'}), "(prog, {'x': (1, 4, 5, 6)}, expected_output_shapes={\n block.outputs[0].name: (1, 4, 5, 3), block.outputs[1].name: (1, 4, 5, 3)})\n", (50153, 50284), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((51878, 51939), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (51904, 51939), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((52252, 52566), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 4, 5, 6)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 4, 5, 1), block.outputs[1].name: (1, 4, 5, 1),\n block.outputs[2].name: (1, 4, 5, 1), block.outputs[3].name: (1, 4, 5, 1\n ), block.outputs[4].name: (1, 4, 5, 1), block.outputs[5].name: (1, 4, 5, 1)\n }'}), "(prog, {'x': (1, 4, 5, 6)}, expected_output_shapes={\n block.outputs[0].name: (1, 4, 5, 1), block.outputs[1].name: (1, 4, 5, 1\n ), block.outputs[2].name: (1, 4, 5, 1), block.outputs[3].name: (1, 4, 5,\n 1), block.outputs[4].name: (1, 4, 5, 1), block.outputs[5].name: (1, 4, \n 5, 1)})\n", (52273, 52566), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((54089, 54150), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (54115, 54150), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((54417, 54532), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 4, 5, 6)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 4, 5, 6)}'}), "(prog, {'x': (1, 4, 5, 6)}, expected_output_shapes={\n block.outputs[0].name: (1, 4, 5, 6)})\n", (54438, 54532), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((56822, 56883), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (56848, 56883), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((57386, 57501), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 5, 5, 3)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 3, 5, 5)}'}), "(prog, {'x': (1, 5, 5, 3)}, expected_output_shapes={\n block.outputs[0].name: (1, 3, 5, 5)})\n", (57407, 57501), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((59993, 60054), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (60019, 60054), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((60560, 60675), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 5, 5, 3)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 5, 5, 3)}'}), "(prog, {'x': (1, 5, 5, 3)}, expected_output_shapes={\n block.outputs[0].name: (1, 5, 5, 3)})\n", (60581, 60675), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((62028, 62089), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (62054, 62089), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((62488, 62591), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (2, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (5, 2)}'}), "(prog, {'x': (2, 5)}, expected_output_shapes={block.\n outputs[0].name: (5, 2)})\n", (62509, 62591), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((64340, 64401), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (64366, 64401), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((64845, 64979), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (2, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (5, 2), block.outputs[1].name: (5, 2)}'}), "(prog, {'x': (2, 5)}, expected_output_shapes={block.\n outputs[0].name: (5, 2), block.outputs[1].name: (5, 2)})\n", (64866, 64979), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((65849, 65910), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (65875, 65910), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((66237, 66371), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (2, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (5, 2), block.outputs[1].name: (2, 5)}'}), "(prog, {'x': (2, 5)}, expected_output_shapes={block.\n outputs[0].name: (5, 2), block.outputs[1].name: (2, 5)})\n", (66258, 66371), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((67563, 67624), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (67589, 67624), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((68201, 68316), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 2, 5, 5)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 2, 5, 5)}'}), "(prog, {'x': (1, 2, 5, 5)}, expected_output_shapes={\n block.outputs[0].name: (1, 2, 5, 5)})\n", (68222, 68316), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((69127, 69188), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::reduce_transposes"""'], {}), "(prog, 'common::reduce_transposes')\n", (69153, 69188), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((69419, 69534), 'coremltools.converters.mil.testing_utils.assert_model_is_valid', 'assert_model_is_valid', (['prog', "{'x': (1, 4, 3, 2)}"], {'expected_output_shapes': '{block.outputs[0].name: (1, 4, 3, 2)}'}), "(prog, {'x': (1, 4, 3, 2)}, expected_output_shapes={\n block.outputs[0].name: (1, 4, 3, 2)})\n", (69440, 69534), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((915, 945), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[1, 0]'}), '(x=x, perm=[1, 0])\n', (927, 945), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((962, 992), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[1, 0]'}), '(x=x, perm=[1, 0])\n', (974, 992), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((1176, 1210), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (1199, 1210), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((1274, 1303), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (1297, 1303), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((1804, 1834), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[1, 0]'}), '(x=x, perm=[1, 0])\n', (1816, 1834), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((1851, 1881), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[1, 0]'}), '(x=x, perm=[1, 0])\n', (1863, 1881), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((1898, 1910), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (1905, 1910), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((2094, 2128), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (2117, 2128), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((2200, 2229), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (2223, 2229), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((2753, 2789), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 1, 2]'}), '(x=x, perm=[0, 3, 1, 2])\n', (2765, 2789), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((2806, 2818), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (2813, 2818), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((2835, 2846), 'coremltools.converters.mil.mil.Builder.log', 'mb.log', ([], {'x': 'x'}), '(x=x)\n', (2841, 2846), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((2863, 2899), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (2875, 2899), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((2916, 2928), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (2923, 2928), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((3112, 3146), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (3135, 3146), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((3246, 3275), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (3269, 3275), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((3834, 3870), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 1, 2]'}), '(x=x, perm=[0, 3, 1, 2])\n', (3846, 3870), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((3887, 3899), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (3894, 3899), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((3916, 3932), 'coremltools.converters.mil.mil.Builder.identity', 'mb.identity', ([], {'x': 'x'}), '(x=x)\n', (3927, 3932), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((3949, 3985), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (3961, 3985), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((4002, 4014), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (4009, 4014), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((4198, 4232), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (4221, 4232), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((4337, 4366), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (4360, 4366), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((5319, 5355), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 1, 2]'}), '(x=x, perm=[0, 3, 1, 2])\n', (5331, 5355), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((5373, 5385), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (5380, 5385), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((5403, 5415), 'coremltools.converters.mil.mil.Builder.log', 'mb.log', ([], {'x': 'x1'}), '(x=x1)\n', (5409, 5415), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((5433, 5470), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x2', 'perm': '[0, 2, 3, 1]'}), '(x=x2, perm=[0, 2, 3, 1])\n', (5445, 5470), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((5488, 5501), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x3'}), '(x=x3)\n', (5495, 5501), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((5690, 5724), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (5713, 5724), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((5837, 5866), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (5860, 5866), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((6508, 6544), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 1, 2]'}), '(x=x, perm=[0, 3, 1, 2])\n', (6520, 6544), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((6561, 6573), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (6568, 6573), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((6590, 6626), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (6602, 6626), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((6810, 6844), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (6833, 6844), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((6916, 6945), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (6939, 6945), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((7777, 7810), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 1]'}), '(x=x, perm=[0, 2, 1])\n', (7789, 7810), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((7828, 7840), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (7835, 7840), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((7858, 7870), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (7865, 7870), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((7888, 7922), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x1', 'perm': '[0, 2, 1]'}), '(x=x1, perm=[0, 2, 1])\n', (7900, 7922), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((7940, 7952), 'coremltools.converters.mil.mil.Builder.log', 'mb.log', ([], {'x': 'x2'}), '(x=x2)\n', (7946, 7952), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((7970, 8004), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 2, 1]'}), '(x=x3, perm=[0, 2, 1])\n', (7982, 8004), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((8193, 8227), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (8216, 8227), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((8340, 8369), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (8363, 8369), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((9556, 9592), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (9568, 9592), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((9610, 9622), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (9617, 9622), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((9640, 9652), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (9647, 9652), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((9670, 9742), 'coremltools.converters.mil.mil.Builder.avg_pool', 'mb.avg_pool', ([], {'x': 'x1', 'kernel_sizes': '[1, 1]', 'strides': '[1, 1]', 'pad_type': '"""valid"""'}), "(x=x1, kernel_sizes=[1, 1], strides=[1, 1], pad_type='valid')\n", (9681, 9742), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((9790, 9802), 'coremltools.converters.mil.mil.Builder.log', 'mb.log', ([], {'x': 'x2'}), '(x=x2)\n', (9796, 9802), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((9820, 9857), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 3, 1, 2]'}), '(x=x3, perm=[0, 3, 1, 2])\n', (9832, 9857), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((10046, 10080), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (10069, 10080), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((10205, 10234), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (10228, 10234), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((11759, 11795), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 1, 3]'}), '(x=x, perm=[0, 2, 1, 3])\n', (11771, 11795), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((11813, 11825), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (11820, 11825), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((11843, 11914), 'coremltools.converters.mil.mil.Builder.avg_pool', 'mb.avg_pool', ([], {'x': 'x', 'kernel_sizes': '[1, 1]', 'strides': '[1, 1]', 'pad_type': '"""valid"""'}), "(x=x, kernel_sizes=[1, 1], strides=[1, 1], pad_type='valid')\n", (11854, 11914), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((11932, 11969), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x1', 'perm': '[0, 2, 1, 3]'}), '(x=x1, perm=[0, 2, 1, 3])\n', (11944, 11969), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((11987, 11999), 'coremltools.converters.mil.mil.Builder.log', 'mb.log', ([], {'x': 'x2'}), '(x=x2)\n', (11993, 11999), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((12017, 12054), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 2, 1, 3]'}), '(x=x3, perm=[0, 2, 1, 3])\n', (12029, 12054), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((12243, 12277), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (12266, 12277), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((12407, 12436), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (12430, 12436), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((14237, 14249), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (14244, 14249), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((14266, 14302), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 1, 3]'}), '(x=x, perm=[0, 2, 1, 3])\n', (14278, 14302), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((14320, 14356), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 1, 3]'}), '(x=x, perm=[0, 2, 1, 3])\n', (14332, 14356), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((14374, 14386), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (14381, 14386), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((14404, 14441), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x1', 'perm': '[0, 2, 1, 3]'}), '(x=x1, perm=[0, 2, 1, 3])\n', (14416, 14441), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((14459, 14531), 'coremltools.converters.mil.mil.Builder.avg_pool', 'mb.avg_pool', ([], {'x': 'x1', 'kernel_sizes': '[1, 1]', 'strides': '[1, 1]', 'pad_type': '"""valid"""'}), "(x=x1, kernel_sizes=[1, 1], strides=[1, 1], pad_type='valid')\n", (14470, 14531), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((14579, 14651), 'coremltools.converters.mil.mil.Builder.avg_pool', 'mb.avg_pool', ([], {'x': 'x1', 'kernel_sizes': '[1, 1]', 'strides': '[1, 1]', 'pad_type': '"""valid"""'}), "(x=x1, kernel_sizes=[1, 1], strides=[1, 1], pad_type='valid')\n", (14590, 14651), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((14878, 14912), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (14901, 14912), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((15182, 15211), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (15205, 15211), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((16503, 16515), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (16510, 16515), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((16532, 16568), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 1, 3]'}), '(x=x, perm=[0, 2, 1, 3])\n', (16544, 16568), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((16586, 16622), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 1, 3]'}), '(x=x, perm=[0, 2, 1, 3])\n', (16598, 16622), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((16640, 16652), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (16647, 16652), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((16841, 16875), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (16864, 16875), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((16968, 16997), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (16991, 16997), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((17925, 17937), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (17932, 17937), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((17957, 17993), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 1, 3]'}), '(x=x, perm=[0, 2, 1, 3])\n', (17969, 17993), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((18013, 18052), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'out2', 'perm': '[0, 2, 1, 3]'}), '(x=out2, perm=[0, 2, 1, 3])\n', (18025, 18052), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((18245, 18279), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (18268, 18279), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((18364, 18393), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (18387, 18393), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((19580, 19592), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (19587, 19592), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((19609, 19645), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 1, 3]'}), '(x=x, perm=[0, 2, 1, 3])\n', (19621, 19645), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((19663, 19675), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (19670, 19675), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((19693, 19730), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x1', 'perm': '[0, 2, 1, 3]'}), '(x=x1, perm=[0, 2, 1, 3])\n', (19705, 19730), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((19748, 19761), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (19755, 19761), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((19779, 19851), 'coremltools.converters.mil.mil.Builder.avg_pool', 'mb.avg_pool', ([], {'x': 'x2', 'kernel_sizes': '[1, 1]', 'strides': '[1, 1]', 'pad_type': '"""valid"""'}), "(x=x2, kernel_sizes=[1, 1], strides=[1, 1], pad_type='valid')\n", (19790, 19851), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((19899, 19971), 'coremltools.converters.mil.mil.Builder.avg_pool', 'mb.avg_pool', ([], {'x': 'x1', 'kernel_sizes': '[1, 1]', 'strides': '[1, 1]', 'pad_type': '"""valid"""'}), "(x=x1, kernel_sizes=[1, 1], strides=[1, 1], pad_type='valid')\n", (19910, 19971), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((20194, 20228), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (20217, 20228), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((20366, 20395), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (20389, 20395), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((21480, 21513), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 1]'}), '(x=x, perm=[0, 2, 1])\n', (21492, 21513), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((21531, 21543), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (21538, 21543), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((21561, 21606), 'coremltools.converters.mil.mil.Builder.reduce_mean', 'mb.reduce_mean', ([], {'x': 'x', 'axes': '[2]', 'keep_dims': '(True)'}), '(x=x, axes=[2], keep_dims=True)\n', (21575, 21606), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((21624, 21658), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x1', 'perm': '[0, 2, 1]'}), '(x=x1, perm=[0, 2, 1])\n', (21636, 21658), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((21676, 21688), 'coremltools.converters.mil.mil.Builder.log', 'mb.log', ([], {'x': 'x2'}), '(x=x2)\n', (21682, 21688), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((21706, 21740), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 2, 1]'}), '(x=x3, perm=[0, 2, 1])\n', (21718, 21740), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((21929, 21963), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (21952, 21963), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((22083, 22112), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (22106, 22112), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((23279, 23315), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 1, 2]'}), '(x=x, perm=[0, 3, 1, 2])\n', (23291, 23315), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((23333, 23390), 'coremltools.converters.mil.mil.Builder.pad', 'mb.pad', ([], {'x': 'x', 'pad': '[0, 0, 0, 0, 1, 2, 3, 4]', 'mode': '"""reflect"""'}), "(x=x, pad=[0, 0, 0, 0, 1, 2, 3, 4], mode='reflect')\n", (23339, 23390), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((23408, 23420), 'coremltools.converters.mil.mil.Builder.log', 'mb.log', ([], {'x': 'x2'}), '(x=x2)\n', (23414, 23420), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((23438, 23475), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 2, 3, 1]'}), '(x=x3, perm=[0, 2, 3, 1])\n', (23450, 23475), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((23660, 23694), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (23683, 23694), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((23785, 23814), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (23808, 23814), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((24999, 25035), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 1, 3, 2]'}), '(x=x, perm=[0, 1, 3, 2])\n', (25011, 25035), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((25053, 25110), 'coremltools.converters.mil.mil.Builder.pad', 'mb.pad', ([], {'x': 'x', 'pad': '[0, 0, 0, 0, 1, 2, 3, 4]', 'mode': '"""reflect"""'}), "(x=x, pad=[0, 0, 0, 0, 1, 2, 3, 4], mode='reflect')\n", (25059, 25110), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((25128, 25140), 'coremltools.converters.mil.mil.Builder.log', 'mb.log', ([], {'x': 'x2'}), '(x=x2)\n', (25134, 25140), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((25158, 25195), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 1, 3, 2]'}), '(x=x3, perm=[0, 1, 3, 2])\n', (25170, 25195), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((25380, 25414), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (25403, 25414), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((25492, 25521), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (25515, 25521), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((26667, 26703), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 1, 2]'}), '(x=x, perm=[0, 3, 1, 2])\n', (26679, 26703), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((26721, 26797), 'coremltools.converters.mil.mil.Builder.pad', 'mb.pad', ([], {'x': 'x', 'pad': '[0, 0, 0, 0, 1, 2, 3, 4]', 'mode': '"""constant"""', 'constant_val': '(3.0)'}), "(x=x, pad=[0, 0, 0, 0, 1, 2, 3, 4], mode='constant', constant_val=3.0)\n", (26727, 26797), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((26845, 26857), 'coremltools.converters.mil.mil.Builder.log', 'mb.log', ([], {'x': 'x2'}), '(x=x2)\n', (26851, 26857), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((26875, 26912), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 2, 3, 1]'}), '(x=x3, perm=[0, 2, 3, 1])\n', (26887, 26912), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((27097, 27131), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (27120, 27131), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((27209, 27238), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (27232, 27238), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((28312, 28348), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (28324, 28348), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((28416, 28452), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 1, 2]'}), '(x=x, perm=[0, 3, 1, 2])\n', (28428, 28452), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((28636, 28670), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (28659, 28670), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((28741, 28770), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (28764, 28770), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((29616, 29652), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (29628, 29652), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((29669, 29685), 'coremltools.converters.mil.mil.Builder.add', 'mb.add', ([], {'x': '(5)', 'y': 'x'}), '(x=5, y=x)\n', (29675, 29685), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((29702, 29738), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 1, 2]'}), '(x=x, perm=[0, 3, 1, 2])\n', (29714, 29738), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((29922, 29956), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (29945, 29956), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((30027, 30056), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (30050, 30056), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((30910, 30946), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (30922, 30946), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((30964, 30976), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (30971, 30976), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((30994, 31031), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x2', 'perm': '[0, 2, 3, 1]'}), '(x=x2, perm=[0, 2, 3, 1])\n', (31006, 31031), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((31049, 31067), 'coremltools.converters.mil.mil.Builder.add', 'mb.add', ([], {'x': 'x1', 'y': 'x2'}), '(x=x1, y=x2)\n', (31055, 31067), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((31084, 31121), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 3, 1, 2]'}), '(x=x3, perm=[0, 3, 1, 2])\n', (31096, 31121), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((31305, 31339), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (31328, 31339), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((31444, 31473), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (31467, 31473), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((32651, 32687), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (32663, 32687), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((32705, 32741), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (32717, 32741), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((32759, 32777), 'coremltools.converters.mil.mil.Builder.add', 'mb.add', ([], {'x': 'x1', 'y': 'x2'}), '(x=x1, y=x2)\n', (32765, 32777), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((32794, 32831), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 3, 1, 2]'}), '(x=x3, perm=[0, 3, 1, 2])\n', (32806, 32831), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((33015, 33049), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (33038, 33049), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((33146, 33175), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (33169, 33175), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((34297, 34333), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (34309, 34333), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((34351, 34387), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (34363, 34387), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((34405, 34418), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (34412, 34418), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((34436, 34449), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x2'}), '(x=x2)\n', (34443, 34449), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((34467, 34501), 'coremltools.converters.mil.mil.Builder.concat', 'mb.concat', ([], {'values': '[x1, x2]', 'axis': '(3)'}), '(values=[x1, x2], axis=3)\n', (34476, 34501), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((34519, 34556), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 3, 1, 2]'}), '(x=x3, perm=[0, 3, 1, 2])\n', (34531, 34556), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((34741, 34775), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (34764, 34775), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((34891, 34920), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (34914, 34920), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((36214, 36250), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (36226, 36250), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((36268, 36304), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (36280, 36304), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((36322, 36335), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (36329, 36335), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((36353, 36366), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x2'}), '(x=x2)\n', (36360, 36366), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((36384, 36418), 'coremltools.converters.mil.mil.Builder.concat', 'mb.concat', ([], {'values': '[x1, x2]', 'axis': '(3)'}), '(values=[x1, x2], axis=3)\n', (36393, 36418), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((36436, 36473), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 3, 1, 2]'}), '(x=x3, perm=[0, 3, 1, 2])\n', (36448, 36473), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((36491, 36563), 'coremltools.converters.mil.mil.Builder.avg_pool', 'mb.avg_pool', ([], {'x': 'x2', 'kernel_sizes': '[1, 1]', 'strides': '[1, 1]', 'pad_type': '"""valid"""'}), "(x=x2, kernel_sizes=[1, 1], strides=[1, 1], pad_type='valid')\n", (36502, 36563), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((36782, 36816), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (36805, 36816), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((37084, 37113), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (37107, 37113), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((38538, 38574), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (38550, 38574), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((38592, 38628), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (38604, 38628), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((38646, 38659), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (38653, 38659), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((38677, 38690), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x2'}), '(x=x2)\n', (38684, 38690), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((38708, 38742), 'coremltools.converters.mil.mil.Builder.concat', 'mb.concat', ([], {'values': '[x1, x2]', 'axis': '(3)'}), '(values=[x1, x2], axis=3)\n', (38717, 38742), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((38760, 38797), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 3, 1, 2]'}), '(x=x3, perm=[0, 3, 1, 2])\n', (38772, 38797), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((38815, 38828), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x2'}), '(x=x2)\n', (38822, 38828), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((39017, 39051), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (39040, 39051), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((39188, 39217), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (39211, 39217), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((40622, 40658), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (40634, 40658), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((40676, 40712), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (40688, 40712), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((40730, 40743), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (40737, 40743), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((40761, 40774), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x2'}), '(x=x2)\n', (40768, 40774), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((40792, 40826), 'coremltools.converters.mil.mil.Builder.concat', 'mb.concat', ([], {'values': '[x1, x2]', 'axis': '(3)'}), '(values=[x1, x2], axis=3)\n', (40801, 40826), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((40844, 40881), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 3, 1, 2]'}), '(x=x3, perm=[0, 3, 1, 2])\n', (40856, 40881), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((41070, 41104), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (41093, 41104), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((41233, 41262), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (41256, 41262), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((42579, 42615), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (42591, 42615), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((42633, 42669), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (42645, 42669), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((42687, 42700), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (42694, 42700), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((42718, 42731), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x2'}), '(x=x2)\n', (42725, 42731), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((42749, 42783), 'coremltools.converters.mil.mil.Builder.concat', 'mb.concat', ([], {'values': '[x1, x2]', 'axis': '(3)'}), '(values=[x1, x2], axis=3)\n', (42758, 42783), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((42801, 42838), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 3, 1, 2]'}), '(x=x3, perm=[0, 3, 1, 2])\n', (42813, 42838), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((42856, 42893), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x2', 'perm': '[0, 3, 1, 2]'}), '(x=x2, perm=[0, 3, 1, 2])\n', (42868, 42893), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((43082, 43116), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (43105, 43116), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((43372, 43401), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (43395, 43401), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((44440, 44473), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[2, 0, 1]'}), '(x=x, perm=[2, 0, 1])\n', (44452, 44473), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((44490, 44509), 'coremltools.converters.mil.mil.Builder.const', 'mb.const', ([], {'val': 'const'}), '(val=const)\n', (44498, 44509), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((44527, 44560), 'coremltools.converters.mil.mil.Builder.concat', 'mb.concat', ([], {'values': '[x1, c]', 'axis': '(2)'}), '(values=[x1, c], axis=2)\n', (44536, 44560), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((44578, 44612), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x2', 'perm': '[1, 2, 0]'}), '(x=x2, perm=[1, 2, 0])\n', (44590, 44612), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((44797, 44831), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (44820, 44831), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((44905, 44934), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (44928, 44934), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((47010, 47043), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[2, 0, 1]'}), '(x=x, perm=[2, 0, 1])\n', (47022, 47043), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((47061, 47074), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (47068, 47074), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((47092, 47105), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (47099, 47105), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((47123, 47136), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (47130, 47136), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((47154, 47167), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (47161, 47167), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((47185, 47198), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (47192, 47198), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((47217, 47254), 'coremltools.converters.mil.mil.Builder.concat', 'mb.concat', ([], {'values': '[r1, r2, y]', 'axis': '(0)'}), '(values=[r1, r2, y], axis=0)\n', (47226, 47254), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((47272, 47306), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'r3', 'perm': '[1, 2, 0]'}), '(x=r3, perm=[1, 2, 0])\n', (47284, 47306), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((47324, 47358), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'r4', 'perm': '[1, 2, 0]'}), '(x=r4, perm=[1, 2, 0])\n', (47336, 47358), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((47376, 47410), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'r5', 'perm': '[1, 2, 0]'}), '(x=r5, perm=[1, 2, 0])\n', (47388, 47410), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((47607, 47641), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (47630, 47641), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((47982, 48011), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (48005, 48011), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((49508, 49544), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 2, 1]'}), '(x=x, perm=[0, 3, 2, 1])\n', (49520, 49544), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((49562, 49575), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (49569, 49575), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((49597, 49633), 'coremltools.converters.mil.mil.Builder.split', 'mb.split', ([], {'x': 'x1', 'axis': '(1)', 'num_splits': '(2)'}), '(x=x1, axis=1, num_splits=2)\n', (49605, 49633), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((49651, 49688), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x2', 'perm': '[0, 3, 2, 1]'}), '(x=x2, perm=[0, 3, 2, 1])\n', (49663, 49688), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((49706, 49743), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 3, 2, 1]'}), '(x=x3, perm=[0, 3, 2, 1])\n', (49718, 49743), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((49932, 49966), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (49955, 49966), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((50073, 50102), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (50096, 50102), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((51324, 51360), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 2, 1]'}), '(x=x, perm=[0, 3, 2, 1])\n', (51336, 51360), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((51378, 51391), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (51385, 51391), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((51429, 51465), 'coremltools.converters.mil.mil.Builder.split', 'mb.split', ([], {'x': 'x1', 'axis': '(1)', 'num_splits': '(6)'}), '(x=x1, axis=1, num_splits=6)\n', (51437, 51465), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((51483, 51520), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x2', 'perm': '[0, 3, 2, 1]'}), '(x=x2, perm=[0, 3, 2, 1])\n', (51495, 51520), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((51538, 51575), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 3, 2, 1]'}), '(x=x3, perm=[0, 3, 2, 1])\n', (51550, 51575), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((51593, 51630), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x4', 'perm': '[0, 3, 2, 1]'}), '(x=x4, perm=[0, 3, 2, 1])\n', (51605, 51630), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((51648, 51685), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x5', 'perm': '[0, 3, 2, 1]'}), '(x=x5, perm=[0, 3, 2, 1])\n', (51660, 51685), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((51703, 51740), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x6', 'perm': '[0, 3, 2, 1]'}), '(x=x6, perm=[0, 3, 2, 1])\n', (51715, 51740), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((51758, 51795), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x7', 'perm': '[0, 3, 2, 1]'}), '(x=x7, perm=[0, 3, 2, 1])\n', (51770, 51795), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((52000, 52034), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (52023, 52034), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((52193, 52222), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (52216, 52222), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((53782, 53818), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 2, 1]'}), '(x=x, perm=[0, 3, 2, 1])\n', (53794, 53818), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((53840, 53876), 'coremltools.converters.mil.mil.Builder.split', 'mb.split', ([], {'x': 'x1', 'axis': '(1)', 'num_splits': '(2)'}), '(x=x1, axis=1, num_splits=2)\n', (53848, 53876), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((53894, 53907), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x2'}), '(x=x2)\n', (53901, 53907), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((53925, 53959), 'coremltools.converters.mil.mil.Builder.concat', 'mb.concat', ([], {'values': '[x4, x3]', 'axis': '(1)'}), '(values=[x4, x3], axis=1)\n', (53934, 53959), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((53977, 54014), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x5', 'perm': '[0, 3, 2, 1]'}), '(x=x5, perm=[0, 3, 2, 1])\n', (53989, 54014), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((54211, 54245), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (54234, 54245), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((54348, 54377), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (54371, 54377), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((56368, 56404), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 1, 2]'}), '(x=x, perm=[0, 3, 1, 2])\n', (56380, 56404), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((56421, 56433), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (56428, 56433), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((56451, 56487), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (56463, 56487), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((56505, 56518), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (56512, 56518), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((56536, 56573), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x2', 'perm': '[0, 3, 1, 2]'}), '(x=x2, perm=[0, 3, 1, 2])\n', (56548, 56573), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((56591, 56608), 'coremltools.converters.mil.mil.Builder.add', 'mb.add', ([], {'x': 'x', 'y': 'x3'}), '(x=x, y=x3)\n', (56597, 56608), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((56626, 56639), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x4'}), '(x=x4)\n', (56633, 56639), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((56657, 56729), 'coremltools.converters.mil.mil.Builder.avg_pool', 'mb.avg_pool', ([], {'x': 'x5', 'kernel_sizes': '[1, 1]', 'strides': '[1, 1]', 'pad_type': '"""valid"""'}), "(x=x5, kernel_sizes=[1, 1], strides=[1, 1], pad_type='valid')\n", (56668, 56729), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((56944, 56978), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (56967, 56978), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((57267, 57296), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (57290, 57296), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((59484, 59520), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 1, 2]'}), '(x=x, perm=[0, 3, 1, 2])\n', (59496, 59520), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((59537, 59549), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (59544, 59549), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((59567, 59603), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (59579, 59603), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((59621, 59634), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (59628, 59634), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((59652, 59689), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x2', 'perm': '[0, 3, 1, 2]'}), '(x=x2, perm=[0, 3, 1, 2])\n', (59664, 59689), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((59707, 59724), 'coremltools.converters.mil.mil.Builder.add', 'mb.add', ([], {'x': 'x', 'y': 'x3'}), '(x=x, y=x3)\n', (59713, 59724), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((59742, 59779), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x4', 'perm': '[0, 2, 3, 1]'}), '(x=x4, perm=[0, 2, 3, 1])\n', (59754, 59779), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((59797, 59810), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x4'}), '(x=x4)\n', (59804, 59810), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((59828, 59900), 'coremltools.converters.mil.mil.Builder.avg_pool', 'mb.avg_pool', ([], {'x': 'x5', 'kernel_sizes': '[1, 1]', 'strides': '[1, 1]', 'pad_type': '"""valid"""'}), "(x=x5, kernel_sizes=[1, 1], strides=[1, 1], pad_type='valid')\n", (59839, 59900), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((60115, 60149), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (60138, 60149), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((60467, 60496), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (60490, 60496), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((61760, 61790), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[1, 0]'}), '(x=x, perm=[1, 0])\n', (61772, 61790), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((61807, 61838), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x1', 'perm': '[1, 0]'}), '(x=x1, perm=[1, 0])\n', (61819, 61838), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((61855, 61901), 'coremltools.converters.mil.mil.Builder.reduce_mean', 'mb.reduce_mean', ([], {'x': 't1', 'axes': '[1]', 'keep_dims': '(True)'}), '(x=t1, axes=[1], keep_dims=True)\n', (61869, 61901), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((61919, 61950), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x2', 'perm': '[1, 0]'}), '(x=x2, perm=[1, 0])\n', (61931, 61950), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((61969, 61987), 'coremltools.converters.mil.mil.Builder.add', 'mb.add', ([], {'x': 'x1', 'y': 't2'}), '(x=x1, y=t2)\n', (61975, 61987), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((62150, 62184), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (62173, 62184), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((62402, 62431), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (62425, 62431), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((64007, 64037), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[1, 0]'}), '(x=x, perm=[1, 0])\n', (64019, 64037), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((64054, 64085), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x1', 'perm': '[1, 0]'}), '(x=x1, perm=[1, 0])\n', (64066, 64085), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((64102, 64148), 'coremltools.converters.mil.mil.Builder.reduce_mean', 'mb.reduce_mean', ([], {'x': 't1', 'axes': '[1]', 'keep_dims': '(True)'}), '(x=t1, axes=[1], keep_dims=True)\n', (64116, 64148), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((64166, 64197), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x2', 'perm': '[1, 0]'}), '(x=x2, perm=[1, 0])\n', (64178, 64197), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((64216, 64234), 'coremltools.converters.mil.mil.Builder.add', 'mb.add', ([], {'x': 'x1', 'y': 't2'}), '(x=x1, y=t2)\n', (64222, 64234), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((64254, 64269), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'out1'}), '(x=out1)\n', (64261, 64269), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((64462, 64496), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (64485, 64496), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((64738, 64767), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (64761, 64767), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((65674, 65704), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[1, 0]'}), '(x=x, perm=[1, 0])\n', (65686, 65704), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((65721, 65734), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (65728, 65734), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((65752, 65783), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'y1', 'perm': '[1, 0]'}), '(x=y1, perm=[1, 0])\n', (65764, 65783), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((65971, 66005), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (65994, 66005), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((66165, 66194), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (66188, 66194), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((67283, 67319), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (67295, 67319), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((67337, 67350), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x1'}), '(x=x1)\n', (67344, 67350), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((67368, 67386), 'coremltools.converters.mil.mil.Builder.add', 'mb.add', ([], {'x': 'x1', 'y': 'x2'}), '(x=x1, y=x2)\n', (67374, 67386), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((67404, 67441), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 3, 1, 2]'}), '(x=x3, perm=[0, 3, 1, 2])\n', (67416, 67441), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((67459, 67496), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x3', 'perm': '[0, 3, 1, 2]'}), '(x=x3, perm=[0, 3, 1, 2])\n', (67471, 67496), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((67685, 67719), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (67708, 67719), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((67824, 67853), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (67847, 67853), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((68878, 68914), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 3, 1, 2]'}), '(x=x, perm=[0, 3, 1, 2])\n', (68890, 68914), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((69000, 69036), 'coremltools.converters.mil.mil.Builder.transpose', 'mb.transpose', ([], {'x': 'x', 'perm': '[0, 2, 3, 1]'}), '(x=x, perm=[0, 2, 3, 1])\n', (69012, 69036), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((69053, 69065), 'coremltools.converters.mil.mil.Builder.relu', 'mb.relu', ([], {'x': 'x'}), '(x=x)\n', (69060, 69065), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((69249, 69283), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prev_prog'], {}), '(prev_prog)\n', (69272, 69283), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((69363, 69392), 'coremltools.converters.mil.testing_utils.get_op_types_in_program', 'get_op_types_in_program', (['prog'], {}), '(prog)\n', (69386, 69392), False, 'from coremltools.converters.mil.testing_utils import assert_op_count_match, assert_model_is_valid, get_op_types_in_program, apply_pass_and_basic_check\n'), ((846, 875), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(10, 20)'}), '(shape=(10, 20))\n', (859, 875), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((1735, 1764), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(10, 20)'}), '(shape=(10, 20))\n', (1748, 1764), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((2680, 2713), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 3, 4)'}), '(shape=(1, 2, 3, 4))\n', (2693, 2713), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((3761, 3794), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 3, 4)'}), '(shape=(1, 2, 3, 4))\n', (3774, 3794), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((5246, 5279), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 3, 4)'}), '(shape=(1, 2, 3, 4))\n', (5259, 5279), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((6435, 6468), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 3, 4)'}), '(shape=(1, 2, 3, 4))\n', (6448, 6468), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((7706, 7737), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(10, 2, 3)'}), '(shape=(10, 2, 3))\n', (7719, 7737), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((9482, 9516), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(10, 2, 3, 5)'}), '(shape=(10, 2, 3, 5))\n', (9495, 9516), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((11685, 11719), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(10, 2, 3, 5)'}), '(shape=(10, 2, 3, 5))\n', (11698, 11719), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((14163, 14197), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(10, 2, 3, 5)'}), '(shape=(10, 2, 3, 5))\n', (14176, 14197), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((16429, 16463), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(10, 2, 3, 5)'}), '(shape=(10, 2, 3, 5))\n', (16442, 16463), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((17851, 17885), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(10, 2, 3, 5)'}), '(shape=(10, 2, 3, 5))\n', (17864, 17885), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((19506, 19540), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(10, 2, 3, 5)'}), '(shape=(10, 2, 3, 5))\n', (19519, 19540), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((21409, 21440), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(10, 2, 3)'}), '(shape=(10, 2, 3))\n', (21422, 21440), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((23205, 23239), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(11, 2, 3, 6)'}), '(shape=(11, 2, 3, 6))\n', (23218, 23239), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((24925, 24959), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(11, 2, 3, 6)'}), '(shape=(11, 2, 3, 6))\n', (24938, 24959), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((26593, 26627), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(11, 2, 3, 6)'}), '(shape=(11, 2, 3, 6))\n', (26606, 26627), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((28379, 28398), 'numpy.array', 'np.array', (['[10, 100]'], {}), '([10, 100])\n', (28387, 28398), True, 'import numpy as np\n'), ((28239, 28272), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 5, 5)'}), '(shape=(1, 2, 5, 5))\n', (28252, 28272), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((29543, 29576), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 5, 5)'}), '(shape=(1, 2, 5, 5))\n', (29556, 29576), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((30836, 30869), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 5, 5)'}), '(shape=(1, 2, 5, 5))\n', (30849, 30869), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((32577, 32610), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 5, 5)'}), '(shape=(1, 2, 5, 5))\n', (32590, 32610), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((34223, 34256), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 5, 5)'}), '(shape=(1, 2, 5, 5))\n', (34236, 34256), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((36140, 36173), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 5, 5)'}), '(shape=(1, 2, 5, 5))\n', (36153, 36173), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((38464, 38497), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 5, 5)'}), '(shape=(1, 2, 5, 5))\n', (38477, 38497), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((40548, 40581), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 5, 5)'}), '(shape=(1, 2, 5, 5))\n', (40561, 40581), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((42505, 42538), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 5, 5)'}), '(shape=(1, 2, 5, 5))\n', (42518, 42538), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((44366, 44399), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(10, 20, 30)'}), '(shape=(10, 20, 30))\n', (44379, 44399), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((46859, 46892), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(10, 20, 30)'}), '(shape=(10, 20, 30))\n', (46872, 46892), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((46910, 46943), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(30, 10, 20)'}), '(shape=(30, 10, 20))\n', (46923, 46943), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((49434, 49467), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 4, 5, 6)'}), '(shape=(1, 4, 5, 6))\n', (49447, 49467), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((51250, 51283), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 4, 5, 6)'}), '(shape=(1, 4, 5, 6))\n', (51263, 51283), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((53708, 53741), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 4, 5, 6)'}), '(shape=(1, 4, 5, 6))\n', (53721, 53741), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((56295, 56328), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 5, 5, 3)'}), '(shape=(1, 5, 5, 3))\n', (56308, 56328), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((59411, 59444), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 5, 5, 3)'}), '(shape=(1, 5, 5, 3))\n', (59424, 59444), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((61692, 61719), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(2, 5)'}), '(shape=(2, 5))\n', (61705, 61719), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((63939, 63966), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(2, 5)'}), '(shape=(2, 5))\n', (63952, 63966), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((65606, 65633), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(2, 5)'}), '(shape=(2, 5))\n', (65619, 65633), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((67209, 67242), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 2, 5, 5)'}), '(shape=(1, 2, 5, 5))\n', (67222, 67242), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((68805, 68838), 'coremltools.converters.mil.mil.Builder.TensorSpec', 'mb.TensorSpec', ([], {'shape': '(1, 4, 3, 2)'}), '(shape=(1, 4, 3, 2))\n', (68818, 68838), True, 'from coremltools.converters.mil.mil import Builder as mb\n'), ((68954, 68981), 'numpy.ones', 'np.ones', ([], {'shape': '(1, 1, 1, 3)'}), '(shape=(1, 1, 1, 3))\n', (68961, 68981), True, 'import numpy as np\n')]
import os import cv2 import math import shutil import pytesseract import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec #Module to detect whether the object in the video sequence is moving or not. def MovementDetection(VideoPath): if(os.path.exists(VideoPath) == False): print("Error(In MovementDetection): Path does not exists") return [] cap =cv2.VideoCapture(VideoPath) ret, frame1 = cap.read() ret, frame2 = cap.read() image_list=[] #For storing image frames while(cap.isOpened()): original_frame1=frame1.copy() #Computes absoulute difference between two consecutive frames diff = cv2.absdiff(frame2, frame1) #Converts the frame obtained to grayscale gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) #Preprocessing of the frame blur = cv2.GaussianBlur(gray, (5,5), 0) _,thresh=cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) dilated = cv2.dilate(thresh, None, iterations=3) contours, _=cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) frame1=cv2.line(frame1, (0, 290), (640, 290), (0,255,0), 2) for contour in contours: (x, y, w, h) = cv2.boundingRect(contour) if(cv2.contourArea(contour) < 800): continue else: #Region of Interest(ROI) if((y>=250) and (y<= 275)): image_list.append(original_frame1) frame1=frame2 ret, frame2 = cap.read() if not ret: break; ret, frame=cap.read() cap.release() return image_list # Vehicle Detection def DetectVehicle(img, net, classes): layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] colors = np.random.uniform(0, 255, size=(len(classes), 3)) #img = cv2.imread(image) img = cv2.resize(img, None, fx=1, fy=1) height, width, channels = img.shape blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False) net.setInput(blob) outs = net.forward(output_layers) class_ids = [] confidences = [] boxes = [] for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) x = int(center_x - w / 2) y = int(center_y - h / 2) boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) #print(indexes) font = cv2.FONT_HERSHEY_PLAIN flag = False x,y,w,h=0,0,0,0 for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) if label == "car": flag = True break return flag,(x,y,w,h) def Validation_And_RatioTest(objectArea): (x,y),(width,height),angle=objectArea aspectRatio=0 if width>height: aspectRatio=width/height else: aspectRatio=height/width if aspectRatio<3 or aspectRatio>10: return False return True def width_greater_(contour): maxLength=contour[0][0][0] minLength=contour[0][0][0] maxWidth=contour[0][0][1] minWidth=contour[0][0][1] for i in contour: if maxLength<i[0][0]: maxLength=i[0][0] elif minLength>i[0][0]: minLength=i[0][0] if maxWidth<i[0][1]: maxWidth=i[0][1] elif minWidth>i[0][1]: maxWidth=i[0][1] length=maxLength-minLength width=maxWidth-minWidth if length < width or length<100 or width>50 or length>250: return True return False; # Returning license_plate from this function def plate_detection(img): #blurring to remove high frequency component imgBlurred = cv2.GaussianBlur(img, (5,5), 0) #color to greyscale image gray = cv2.cvtColor(imgBlurred, cv2.COLOR_BGR2GRAY) rectKern = cv2.getStructuringElement(cv2.MORPH_RECT, (13, 5)) blackhat = cv2.morphologyEx(gray, cv2.MORPH_BLACKHAT, rectKern) #otsu thresolding ret2,threshold_img = cv2.threshold(blackhat,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) morph_img_threshold = threshold_img.copy() # rectangular kernel for morphological operation element = cv2.getStructuringElement(shape=cv2.MORPH_RECT, ksize=(20, 1)) #(20,10) #morphological operation(dilation) cv2.morphologyEx(src=threshold_img, op=cv2.MORPH_CLOSE, kernel=element, dst=morph_img_threshold) #added new thresh = cv2.erode(morph_img_threshold, None, iterations=2) thresh = cv2.dilate(thresh, None, iterations=2) contours, hierarchy= cv2.findContours(morph_img_threshold,mode=cv2.RETR_EXTERNAL,method=cv2.CHAIN_APPROX_NONE) #2 with Validation # i is count index, cnt is coordinates of 1 whole object for i,cnt in enumerate(contours): #it is observed that for most of image , number of coordinates number plate region lies between 300-500 if(len(cnt)>200): if width_greater_(cnt): continue; objectArea=cv2.minAreaRect(cnt) if Validation_And_RatioTest(objectArea): x, y, w, h = cv2.boundingRect(cnt) license_plate = img[y:y + h + 5, x-5:x + w] #cv2.imwrite("plate.png", license_plate) return license_plate # Functions needed to be loaded only once for many all the recognitions.. ''' Function used to rotate the image by angle along the center using warp affine ''' def rotate_image(image, angle): image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR) return result ''' Sorting the contours from top to bottom, left to right using bounding boxes ''' def sort_contours(cnts,reverse = False): boundingBoxes = [cv2.boundingRect(c) for c in cnts] boundingBoxes = sorted(boundingBoxes, key=lambda b:b[0]+b[1], reverse=False) return boundingBoxes ''' Predicting label for image size 128*128 ''' def predict_from_model_128(image,model,labels): image = cv2.resize(image,(128,128)) image = np.stack((image,)*3, axis=-1) prediction = labels.inverse_transform([np.argmax(model.predict(image[np.newaxis,:]))]) return prediction ''' Predicting label for image size 80*80 ''' def predict_from_model_80(image,model,labels): image = cv2.resize(image,(80,80)) image = np.stack((image,)*3, axis=-1) prediction = labels.inverse_transform([np.argmax(model.predict(image[np.newaxis,:]))]) return prediction ''' Using outlier detection technique to remove all the contours except the character contours. ''' def minimum_character(input_list): if len(input_list) == 0: return -1 A = np.array(sorted(input_list)) #print(A) z = np.abs(stats.zscore(A)) A_clean = np.array([A[i] for i in range(len(z)) if z[i] < 2]) return A_clean[0] ''' recognize_char function is combination of hough transform alogrithm, character segmentation, character recognition. ''' def recognize_char(input_img, first_letter_model,first_letter_labels, second_letter_model, second_letter_labels,digit_model, digit_labels, model, labels): ''' Pre-processing the image to maintain the edges of the characters while supressing the noise in the image. Obtaining the canny edge image for the gray scaled image. ''' blur = cv2.bilateralFilter(input_img,9,95,95) blur = cv2.detailEnhance(blur, 5, 0.95) gray_img = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY) canny_edges = cv2.Canny(gray_img,220, 250, None, 5) ''' Using hough transform over the image to get all the lines between +- 15 degrees of the lines to obtain the skew in the image. ''' cv2.imwrite("PlateImg.png", input_img) lines = cv2.HoughLines(canny_edges, 1, np.pi / 180, 50, None, 0, 0) avg_theta = 0 theta =0 line_count = 0 if lines is not None: for i in range(0, len(lines)): theta = lines[i][0][1] angle = (180*theta/3.1415926 - 90) if -15<=angle<=15: avg_theta += angle line_count += 1 if line_count != 0: avg_theta = avg_theta/line_count img_rotated = rotate_image(input_img, avg_theta) else: img_rotated = rotate_image(input_img, 0) ''' Pre-processing the rotated image as before. ''' enhanced_img = cv2.detailEnhance(img_rotated, 9, 10, 0.5) enhanced_gray_img = cv2.cvtColor(enhanced_img, cv2.COLOR_BGR2GRAY) blur_enhanced_gray_img = cv2.bilateralFilter(enhanced_gray_img, 9,10,10) binary_image = cv2.threshold(blur_enhanced_gray_img, 100,255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] ''' Getting the external hierarchy contours on the image. ''' cont, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) char_segmented = [] char_w = 96 char_h = 96 char_ratio_list = [] sorted_bounding_boxes = sort_contours(cont) ''' Using the ratio of h/w for removal of outlier contours. ''' for box in sorted_bounding_boxes: (x, y, w, h) = box ratio = h/w if 1<=ratio<=5: char_ratio_list.append(h/img_rotated.shape[0]) mini_char = minimum_character(char_ratio_list) print(mini_char) if mini_char == -1: flag = False else: flag = True if(flag): ''' Segmenting each character.. ''' for box in sorted_bounding_boxes: (x, y, w, h) = box ratio = h/w if 1<=ratio<=5: if 0.3 <= h/img_rotated.shape[0] <= 0.9: curr_num = binary_image[y:y+h,x:x+w] curr_num = cv2.resize(curr_num, dsize=(char_w, char_h)) _, curr_num = cv2.threshold(curr_num, 90, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) char_segmented.append(curr_num) if len(char_segmented) < 5: return "ERROR_CHAR_LEN" ''' Using the indian number plate constraints to recognize the characters and generating the final string.. ''' final_string = '' title = np.array2string(predict_from_model_128(char_segmented[0],first_letter_model,first_letter_labels)) final_string +=title.strip("'[]") title = np.array2string(predict_from_model_128(char_segmented[1],second_letter_model,second_letter_labels)) final_string +=title.strip("'[]") title = np.array2string(predict_from_model_128(char_segmented[2],digit_model,digit_labels)) final_string +=title.strip("'[]") title = np.array2string(predict_from_model_128(char_segmented[3],digit_model,digit_labels)) final_string +=title.strip("'[]") for i in range(4,len(char_segmented)-4): title = np.array2string(predict_from_model_80(char_segmented[i],model,labels)) final_string+=title.strip("'[]") for i in range(len(char_segmented)-4,len(char_segmented)): title = np.array2string(predict_from_model_128(char_segmented[i],digit_model,digit_labels)) final_string+=title.strip("'[]") return final_string else: return pytesseract.image_to_string(blur_enhanced_gray_img)
[ "numpy.array", "cv2.HoughLines", "cv2.dnn.NMSBoxes", "os.path.exists", "cv2.threshold", "cv2.erode", "cv2.line", "cv2.contourArea", "cv2.minAreaRect", "numpy.stack", "cv2.dnn.blobFromImage", "cv2.warpAffine", "numpy.argmax", "cv2.morphologyEx", "scipy.stats.zscore", "cv2.cvtColor", "...
[((437, 464), 'cv2.VideoCapture', 'cv2.VideoCapture', (['VideoPath'], {}), '(VideoPath)\n', (453, 464), False, 'import cv2\n'), ((1981, 2014), 'cv2.resize', 'cv2.resize', (['img', 'None'], {'fx': '(1)', 'fy': '(1)'}), '(img, None, fx=1, fy=1)\n', (1991, 2014), False, 'import cv2\n'), ((2067, 2143), 'cv2.dnn.blobFromImage', 'cv2.dnn.blobFromImage', (['img', '(0.00392)', '(416, 416)', '(0, 0, 0)', '(True)'], {'crop': '(False)'}), '(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)\n', (2088, 2143), False, 'import cv2\n'), ((2902, 2948), 'cv2.dnn.NMSBoxes', 'cv2.dnn.NMSBoxes', (['boxes', 'confidences', '(0.5)', '(0.4)'], {}), '(boxes, confidences, 0.5, 0.4)\n', (2918, 2948), False, 'import cv2\n'), ((4294, 4326), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['img', '(5, 5)', '(0)'], {}), '(img, (5, 5), 0)\n', (4310, 4326), False, 'import cv2\n'), ((4368, 4412), 'cv2.cvtColor', 'cv2.cvtColor', (['imgBlurred', 'cv2.COLOR_BGR2GRAY'], {}), '(imgBlurred, cv2.COLOR_BGR2GRAY)\n', (4380, 4412), False, 'import cv2\n'), ((4428, 4478), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(13, 5)'], {}), '(cv2.MORPH_RECT, (13, 5))\n', (4453, 4478), False, 'import cv2\n'), ((4494, 4546), 'cv2.morphologyEx', 'cv2.morphologyEx', (['gray', 'cv2.MORPH_BLACKHAT', 'rectKern'], {}), '(gray, cv2.MORPH_BLACKHAT, rectKern)\n', (4510, 4546), False, 'import cv2\n'), ((4595, 4663), 'cv2.threshold', 'cv2.threshold', (['blackhat', '(0)', '(255)', '(cv2.THRESH_BINARY + cv2.THRESH_OTSU)'], {}), '(blackhat, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n', (4608, 4663), False, 'import cv2\n'), ((4775, 4837), 'cv2.getStructuringElement', 'cv2.getStructuringElement', ([], {'shape': 'cv2.MORPH_RECT', 'ksize': '(20, 1)'}), '(shape=cv2.MORPH_RECT, ksize=(20, 1))\n', (4800, 4837), False, 'import cv2\n'), ((4892, 4993), 'cv2.morphologyEx', 'cv2.morphologyEx', ([], {'src': 'threshold_img', 'op': 'cv2.MORPH_CLOSE', 'kernel': 'element', 'dst': 'morph_img_threshold'}), '(src=threshold_img, op=cv2.MORPH_CLOSE, kernel=element, dst\n =morph_img_threshold)\n', (4908, 4993), False, 'import cv2\n'), ((5018, 5068), 'cv2.erode', 'cv2.erode', (['morph_img_threshold', 'None'], {'iterations': '(2)'}), '(morph_img_threshold, None, iterations=2)\n', (5027, 5068), False, 'import cv2\n'), ((5083, 5121), 'cv2.dilate', 'cv2.dilate', (['thresh', 'None'], {'iterations': '(2)'}), '(thresh, None, iterations=2)\n', (5093, 5121), False, 'import cv2\n'), ((5148, 5244), 'cv2.findContours', 'cv2.findContours', (['morph_img_threshold'], {'mode': 'cv2.RETR_EXTERNAL', 'method': 'cv2.CHAIN_APPROX_NONE'}), '(morph_img_threshold, mode=cv2.RETR_EXTERNAL, method=cv2.\n CHAIN_APPROX_NONE)\n', (5164, 5244), False, 'import cv2\n'), ((6132, 6181), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['image_center', 'angle', '(1.0)'], {}), '(image_center, angle, 1.0)\n', (6155, 6181), False, 'import cv2\n'), ((6195, 6269), 'cv2.warpAffine', 'cv2.warpAffine', (['image', 'rot_mat', 'image.shape[1::-1]'], {'flags': 'cv2.INTER_LINEAR'}), '(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)\n', (6209, 6269), False, 'import cv2\n'), ((6686, 6715), 'cv2.resize', 'cv2.resize', (['image', '(128, 128)'], {}), '(image, (128, 128))\n', (6696, 6715), False, 'import cv2\n'), ((6726, 6757), 'numpy.stack', 'np.stack', (['((image,) * 3)'], {'axis': '(-1)'}), '((image,) * 3, axis=-1)\n', (6734, 6757), True, 'import numpy as np\n'), ((6976, 7003), 'cv2.resize', 'cv2.resize', (['image', '(80, 80)'], {}), '(image, (80, 80))\n', (6986, 7003), False, 'import cv2\n'), ((7014, 7045), 'numpy.stack', 'np.stack', (['((image,) * 3)'], {'axis': '(-1)'}), '((image,) * 3, axis=-1)\n', (7022, 7045), True, 'import numpy as np\n'), ((7995, 8036), 'cv2.bilateralFilter', 'cv2.bilateralFilter', (['input_img', '(9)', '(95)', '(95)'], {}), '(input_img, 9, 95, 95)\n', (8014, 8036), False, 'import cv2\n'), ((8045, 8077), 'cv2.detailEnhance', 'cv2.detailEnhance', (['blur', '(5)', '(0.95)'], {}), '(blur, 5, 0.95)\n', (8062, 8077), False, 'import cv2\n'), ((8093, 8131), 'cv2.cvtColor', 'cv2.cvtColor', (['blur', 'cv2.COLOR_BGR2GRAY'], {}), '(blur, cv2.COLOR_BGR2GRAY)\n', (8105, 8131), False, 'import cv2\n'), ((8150, 8188), 'cv2.Canny', 'cv2.Canny', (['gray_img', '(220)', '(250)', 'None', '(5)'], {}), '(gray_img, 220, 250, None, 5)\n', (8159, 8188), False, 'import cv2\n'), ((8340, 8378), 'cv2.imwrite', 'cv2.imwrite', (['"""PlateImg.png"""', 'input_img'], {}), "('PlateImg.png', input_img)\n", (8351, 8378), False, 'import cv2\n'), ((8391, 8450), 'cv2.HoughLines', 'cv2.HoughLines', (['canny_edges', '(1)', '(np.pi / 180)', '(50)', 'None', '(0)', '(0)'], {}), '(canny_edges, 1, np.pi / 180, 50, None, 0, 0)\n', (8405, 8450), False, 'import cv2\n'), ((9012, 9054), 'cv2.detailEnhance', 'cv2.detailEnhance', (['img_rotated', '(9)', '(10)', '(0.5)'], {}), '(img_rotated, 9, 10, 0.5)\n', (9029, 9054), False, 'import cv2\n'), ((9079, 9125), 'cv2.cvtColor', 'cv2.cvtColor', (['enhanced_img', 'cv2.COLOR_BGR2GRAY'], {}), '(enhanced_img, cv2.COLOR_BGR2GRAY)\n', (9091, 9125), False, 'import cv2\n'), ((9155, 9204), 'cv2.bilateralFilter', 'cv2.bilateralFilter', (['enhanced_gray_img', '(9)', '(10)', '(10)'], {}), '(enhanced_gray_img, 9, 10, 10)\n', (9174, 9204), False, 'import cv2\n'), ((9402, 9476), 'cv2.findContours', 'cv2.findContours', (['binary_image', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n', (9418, 9476), False, 'import cv2\n'), ((305, 330), 'os.path.exists', 'os.path.exists', (['VideoPath'], {}), '(VideoPath)\n', (319, 330), False, 'import os\n'), ((720, 747), 'cv2.absdiff', 'cv2.absdiff', (['frame2', 'frame1'], {}), '(frame2, frame1)\n', (731, 747), False, 'import cv2\n'), ((813, 851), 'cv2.cvtColor', 'cv2.cvtColor', (['diff', 'cv2.COLOR_BGR2GRAY'], {}), '(diff, cv2.COLOR_BGR2GRAY)\n', (825, 851), False, 'import cv2\n'), ((904, 937), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['gray', '(5, 5)', '(0)'], {}), '(gray, (5, 5), 0)\n', (920, 937), False, 'import cv2\n'), ((954, 1001), 'cv2.threshold', 'cv2.threshold', (['blur', '(20)', '(255)', 'cv2.THRESH_BINARY'], {}), '(blur, 20, 255, cv2.THRESH_BINARY)\n', (967, 1001), False, 'import cv2\n'), ((1020, 1058), 'cv2.dilate', 'cv2.dilate', (['thresh', 'None'], {'iterations': '(3)'}), '(thresh, None, iterations=3)\n', (1030, 1058), False, 'import cv2\n'), ((1080, 1145), 'cv2.findContours', 'cv2.findContours', (['dilated', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (1096, 1145), False, 'import cv2\n'), ((1161, 1215), 'cv2.line', 'cv2.line', (['frame1', '(0, 290)', '(640, 290)', '(0, 255, 0)', '(2)'], {}), '(frame1, (0, 290), (640, 290), (0, 255, 0), 2)\n', (1169, 1215), False, 'import cv2\n'), ((6436, 6455), 'cv2.boundingRect', 'cv2.boundingRect', (['c'], {}), '(c)\n', (6452, 6455), False, 'import cv2\n'), ((7407, 7422), 'scipy.stats.zscore', 'stats.zscore', (['A'], {}), '(A)\n', (7419, 7422), True, 'import scipy.stats as stats\n'), ((9222, 9315), 'cv2.threshold', 'cv2.threshold', (['blur_enhanced_gray_img', '(100)', '(255)', '(cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)'], {}), '(blur_enhanced_gray_img, 100, 255, cv2.THRESH_BINARY_INV + cv2\n .THRESH_OTSU)\n', (9235, 9315), False, 'import cv2\n'), ((11846, 11897), 'pytesseract.image_to_string', 'pytesseract.image_to_string', (['blur_enhanced_gray_img'], {}), '(blur_enhanced_gray_img)\n', (11873, 11897), False, 'import pytesseract\n'), ((1275, 1300), 'cv2.boundingRect', 'cv2.boundingRect', (['contour'], {}), '(contour)\n', (1291, 1300), False, 'import cv2\n'), ((2370, 2387), 'numpy.argmax', 'np.argmax', (['scores'], {}), '(scores)\n', (2379, 2387), True, 'import numpy as np\n'), ((5587, 5607), 'cv2.minAreaRect', 'cv2.minAreaRect', (['cnt'], {}), '(cnt)\n', (5602, 5607), False, 'import cv2\n'), ((6084, 6112), 'numpy.array', 'np.array', (['image.shape[1::-1]'], {}), '(image.shape[1::-1])\n', (6092, 6112), True, 'import numpy as np\n'), ((1316, 1340), 'cv2.contourArea', 'cv2.contourArea', (['contour'], {}), '(contour)\n', (1331, 1340), False, 'import cv2\n'), ((5690, 5711), 'cv2.boundingRect', 'cv2.boundingRect', (['cnt'], {}), '(cnt)\n', (5706, 5711), False, 'import cv2\n'), ((10352, 10396), 'cv2.resize', 'cv2.resize', (['curr_num'], {'dsize': '(char_w, char_h)'}), '(curr_num, dsize=(char_w, char_h))\n', (10362, 10396), False, 'import cv2\n'), ((10431, 10500), 'cv2.threshold', 'cv2.threshold', (['curr_num', '(90)', '(255)', '(cv2.THRESH_BINARY + cv2.THRESH_OTSU)'], {}), '(curr_num, 90, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n', (10444, 10500), False, 'import cv2\n')]
#!/usr/bin/env python # coding: utf-8 import numpy as np import pandas as pd from pytorch_transformers import (WEIGHTS_NAME, BertConfig, BertForSequenceClassification, BertTokenizer, XLMConfig, XLMForSequenceClassification, XLMTokenizer, XLNetConfig, XLNetForSequenceClassification, XLNetTokenizer, RobertaConfig, RobertaForSequenceClassification, RobertaTokenizer) from keras.preprocessing.sequence import pad_sequences from sklearn.model_selection import train_test_split import torch from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from pytorch_transformers import AdamW as BertAdam from tqdm import tqdm, trange import pickle as pkl import math import argparse parser = argparse.ArgumentParser() parser.add_argument('-t', action="store", dest="test_folder", help="folder containing test data") parser.add_argument('-p', action="store", dest="part", help="part number") parser.add_argument('-l', action="store_true", dest="load_input", help="whether to load input or not") parser.add_argument('-e', action="store_true", dest="evaluate_input", help="will evaluate and rank when on, will only rank when off") parser.add_argument('-i', action="store", dest="input_id_folder", help="folder to load input from") parser.add_argument('-r', action="store", dest="logits_folder", help="folder to load/store logits from, load when -e off, store otherwise") parser.add_argument('-m', action="store", dest="model_file", help="file to load model from") parser.add_argument('-n', action="store", dest="model_name", help="name of model, logits is named based on this") parser.add_argument('-o', action="store", dest="trec_folder", help="folder to generate trecinput in") results = parser.parse_args() test_folder = results.test_folder part = results.part load_input = results.load_input evaluate_input = results.evaluate_input input_id_folder = results.input_id_folder logits_folder = results.logits_folder model_file = results.model_file model_name = results.model_name query_doc_file = test_folder + '/part' + part + '.query.doc.csv' query_doc_id_file = test_folder + '/id.part' + part + '.query.doc.csv' input_id_file = input_id_folder + '/eval_input_id_' + part + '.pkl' logits_file = logits_folder +'/logits_' + model_name + part + '.pkl' trec_input_file = trec_folder + '/trecinput_' + model_name + '_' + part + '.txt' df = pd.read_csv(query_doc_file, delimiter='\t', header=None) train_data = df.values df_id = pd.read_csv(query_doc_id_file, delimiter='\t', header=None) train_id = df_id.values queries = train_data[:,0:1].flatten() passages = train_data[:,1:2].flatten() query_ids = train_id[:,0:1].flatten() passsage_ids = train_id[:,1:2].flatten() if (evaluate_input): print ("Print loading model") file = open(model_file,"rb") model = pkl.load(file) file.close() model.cuda() tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True) def customtok(max_len, texts, sentid): if(sentid==0): texts = ["[CLS] " + text + " [SEP]" for text in texts] else: texts = [text + " [SEP]" for text in texts] tokenized_texts = [tokenizer.tokenize(text) for text in texts] templ = [tokenizer.convert_tokens_to_ids(text) for text in tokenized_texts] input_ids = pad_sequences(templ, maxlen=max_len, dtype="long", truncating="post", padding="post") return input_ids MAX_LENGTH_QUERY = 32 MAX_LENGTH_PASSAGE = 96 if (load_input): print ("Loading saved test input ids") file = open(input_id_file, "rb") input_id = pkl.load(file) else: print ("Creating input ids from raw test data") input_id_query = customtok(MAX_LENGTH_QUERY, queries, 0) input_id_passage = customtok(MAX_LENGTH_PASSAGE, passages, 1) input_id_query = np.array(input_id_query) input_id_passage = np.array(input_id_passage) input_id = np.concatenate((input_id_query, input_id_passage), axis=1) print ("Saving the created input ids for fast load next time") file = open(input_id_file, "wb") pkl.dump(input_id, file) file.close() attention_mask = input_id.copy() attention_mask[attention_mask > 0] = 1 segment1 = np.zeros((len(input_id), MAX_LENGTH_QUERY)) segment2 = input_id[:,MAX_LENGTH_QUERY:].copy() segment2[segment2 > 0] = 1 segment_mask = np.concatenate((segment1, segment2), axis=1) eval_inputs = input_id eval_masks = attention_mask eval_segments = segment_mask eval_inputs = torch.tensor(eval_inputs, dtype=torch.long) eval_masks = torch.tensor(eval_masks, dtype=torch.long) eval_segments = torch.tensor(eval_segments, dtype=torch.long) batch_size = 1024 eval_data = TensorDataset(eval_inputs, eval_masks, eval_segments) eval_sampler = SequentialSampler(eval_data) eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=batch_size) torch.cuda.get_device_name(0) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") n_gpu = torch.cuda.device_count() torch.cuda.get_device_name(0) model.eval() eval_loss, eval_accuracy = 0, 0 nb_eval_steps, nb_eval_examples = 0, 0 print ("Beginning testing") logitsall = np.empty((0,2)) for batch in eval_dataloader: batch = tuple(t.to(device) for t in batch) b_input_ids, b_input_mask, b_input_segment = batch with torch.no_grad(): (logits,) = model(b_input_ids, attention_mask=b_input_mask, token_type_ids=b_input_segment) logits = logits.detach().cpu().numpy() logitsall = np.append(logitsall,logits, axis=0) nb_eval_steps += 1 print(nb_eval_steps*batch_size) print ("Saving logits") file = open(logits_file, "wb") pkl.dump(logitsall, file) file.close() else: print ("Using saved logits") file = open(logits_file,"rb") model = pkl.load(file) file.close() def extractinfofromlogit(logits_eval): relevantscore = logits_eval[:,1] return relevantscore def rankedfromlogit(logits_eval, qidl,aidl): relevantscore = extractinfofromlogit(logits_eval) scoremap = {} rankmap = {} for qid, aid, score in zip(qidl, aidl, relevantscore): if qid not in scoremap: scoremap[qid] = [] scoremap[qid].append((aid,score)) for qid, zipaidscore in scoremap.items(): scorearr = [(-x[1]) for x in zipaidscore] sortedindex = np.argsort(scorearr) rankarr = [zipaidscore[x][0] for x in sortedindex] scorearrcorres = [zipaidscore[x][1] for x in sortedindex] rankmap[qid] = (rankarr,scorearrcorres) return rankmap def writeToFile(filename, rankmap): f = open(filename, "w") for qid, val in rankmap.items(): (pidarr, scorearr) = val for i in range(0,len(pidarr)): tempstr = str(qid)+ " 0 "+str(pidarr[i])+" "+str(i+1)+" "+str(math.exp(scorearr[i]))+" s\n" f.write(tempstr) f.close() print ("Creating rankings") rankmap = rankedfromlogit(logitsall, query_ids, passsage_ids) print ("Writing to file") writeToFile(trec_input_file, rankmap)
[ "pandas.read_csv", "torch.cuda.device_count", "numpy.argsort", "numpy.array", "torch.cuda.is_available", "keras.preprocessing.sequence.pad_sequences", "math.exp", "argparse.ArgumentParser", "numpy.empty", "numpy.concatenate", "pickle.load", "torch.utils.data.SequentialSampler", "torch.utils....
[((820, 845), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (843, 845), False, 'import argparse\n'), ((2467, 2523), 'pandas.read_csv', 'pd.read_csv', (['query_doc_file'], {'delimiter': '"""\t"""', 'header': 'None'}), "(query_doc_file, delimiter='\\t', header=None)\n", (2478, 2523), True, 'import pandas as pd\n'), ((2555, 2614), 'pandas.read_csv', 'pd.read_csv', (['query_doc_id_file'], {'delimiter': '"""\t"""', 'header': 'None'}), "(query_doc_id_file, delimiter='\\t', header=None)\n", (2566, 2614), True, 'import pandas as pd\n'), ((2891, 2905), 'pickle.load', 'pkl.load', (['file'], {}), '(file)\n', (2899, 2905), True, 'import pickle as pkl\n'), ((2953, 3023), 'pytorch_transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['"""bert-base-uncased"""'], {'do_lower_case': '(True)'}), "('bert-base-uncased', do_lower_case=True)\n", (2982, 3023), False, 'from pytorch_transformers import WEIGHTS_NAME, BertConfig, BertForSequenceClassification, BertTokenizer, XLMConfig, XLMForSequenceClassification, XLMTokenizer, XLNetConfig, XLNetForSequenceClassification, XLNetTokenizer, RobertaConfig, RobertaForSequenceClassification, RobertaTokenizer\n'), ((4417, 4461), 'numpy.concatenate', 'np.concatenate', (['(segment1, segment2)'], {'axis': '(1)'}), '((segment1, segment2), axis=1)\n', (4431, 4461), True, 'import numpy as np\n'), ((4566, 4609), 'torch.tensor', 'torch.tensor', (['eval_inputs'], {'dtype': 'torch.long'}), '(eval_inputs, dtype=torch.long)\n', (4578, 4609), False, 'import torch\n'), ((4625, 4667), 'torch.tensor', 'torch.tensor', (['eval_masks'], {'dtype': 'torch.long'}), '(eval_masks, dtype=torch.long)\n', (4637, 4667), False, 'import torch\n'), ((4686, 4731), 'torch.tensor', 'torch.tensor', (['eval_segments'], {'dtype': 'torch.long'}), '(eval_segments, dtype=torch.long)\n', (4698, 4731), False, 'import torch\n'), ((4768, 4821), 'torch.utils.data.TensorDataset', 'TensorDataset', (['eval_inputs', 'eval_masks', 'eval_segments'], {}), '(eval_inputs, eval_masks, eval_segments)\n', (4781, 4821), False, 'from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler\n'), ((4839, 4867), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['eval_data'], {}), '(eval_data)\n', (4856, 4867), False, 'from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler\n'), ((4888, 4954), 'torch.utils.data.DataLoader', 'DataLoader', (['eval_data'], {'sampler': 'eval_sampler', 'batch_size': 'batch_size'}), '(eval_data, sampler=eval_sampler, batch_size=batch_size)\n', (4898, 4954), False, 'from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler\n'), ((4958, 4987), 'torch.cuda.get_device_name', 'torch.cuda.get_device_name', (['(0)'], {}), '(0)\n', (4984, 4987), False, 'import torch\n'), ((5071, 5096), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (5094, 5096), False, 'import torch\n'), ((5099, 5128), 'torch.cuda.get_device_name', 'torch.cuda.get_device_name', (['(0)'], {}), '(0)\n', (5125, 5128), False, 'import torch\n'), ((5266, 5282), 'numpy.empty', 'np.empty', (['(0, 2)'], {}), '((0, 2))\n', (5274, 5282), True, 'import numpy as np\n'), ((5777, 5802), 'pickle.dump', 'pkl.dump', (['logitsall', 'file'], {}), '(logitsall, file)\n', (5785, 5802), True, 'import pickle as pkl\n'), ((5898, 5912), 'pickle.load', 'pkl.load', (['file'], {}), '(file)\n', (5906, 5912), True, 'import pickle as pkl\n'), ((3387, 3476), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['templ'], {'maxlen': 'max_len', 'dtype': '"""long"""', 'truncating': '"""post"""', 'padding': '"""post"""'}), "(templ, maxlen=max_len, dtype='long', truncating='post',\n padding='post')\n", (3400, 3476), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((3662, 3676), 'pickle.load', 'pkl.load', (['file'], {}), '(file)\n', (3670, 3676), True, 'import pickle as pkl\n'), ((3886, 3910), 'numpy.array', 'np.array', (['input_id_query'], {}), '(input_id_query)\n', (3894, 3910), True, 'import numpy as np\n'), ((3934, 3960), 'numpy.array', 'np.array', (['input_id_passage'], {}), '(input_id_passage)\n', (3942, 3960), True, 'import numpy as np\n'), ((3976, 4034), 'numpy.concatenate', 'np.concatenate', (['(input_id_query, input_id_passage)'], {'axis': '(1)'}), '((input_id_query, input_id_passage), axis=1)\n', (3990, 4034), True, 'import numpy as np\n'), ((4144, 4168), 'pickle.dump', 'pkl.dump', (['input_id', 'file'], {}), '(input_id, file)\n', (4152, 4168), True, 'import pickle as pkl\n'), ((5614, 5650), 'numpy.append', 'np.append', (['logitsall', 'logits'], {'axis': '(0)'}), '(logitsall, logits, axis=0)\n', (5623, 5650), True, 'import numpy as np\n'), ((6447, 6467), 'numpy.argsort', 'np.argsort', (['scorearr'], {}), '(scorearr)\n', (6457, 6467), True, 'import numpy as np\n'), ((5023, 5048), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5046, 5048), False, 'import torch\n'), ((5431, 5446), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5444, 5446), False, 'import torch\n'), ((6903, 6924), 'math.exp', 'math.exp', (['scorearr[i]'], {}), '(scorearr[i])\n', (6911, 6924), False, 'import math\n')]
import re import os import glob import subprocess from subprocess import Popen, PIPE import numpy as np # generates the string with the selected integrator def set_integrator(scene, integrator_str): start = '##INTEGRATOR-DEF-START' end = '##INTEGRATOR-DEF-END' replacement = integrator_str match = re.match(r'(.+%s\s*).+?(\s*%s.+)' % (start, end), scene, re.DOTALL) return match.group(1) + replacement + match.group(2) def set_sampler(scene, sampler_str): start = '##SAMPLER-DEF-START' end = '##SAMPLER-DEF-END' replacement = sampler_str match = re.match(r'(.+%s\s*).+?(\s*%s.+)' % (start, end), scene, re.DOTALL) return match.group(1) + replacement + match.group(2) def run_and_time(args, workingDir, repeats=1): totalTime = 0.0 var = 0.0 mean = 0.0 n = 0 for k in range(repeats): p = Popen(args, cwd=workingDir, stdin=PIPE, stdout=PIPE, stderr=PIPE) output, err = p.communicate() # Format of our implementation renderTime = re.findall(r'Total rendering time: (\d+\.\d+) seconds.', output.decode('utf-8')) overheadTime = re.findall(r'Overhead: (\d+\.\d+) seconds.', output.decode('utf-8')) trialTime = 0.0 if not renderTime: # Format of the optimal MIS implementation renderTime = re.findall(r'Rendering stats: samples \d+, time (\d+\.\d+) s', output.decode('utf-8')) if not renderTime: # Fallback: Hijack PBRT progress reporter # Accuracy below 0.5 seconds!! # Might also be printing the full time multiple times, # the first output is right after Done() was called and should be most accurate times = re.findall(r'\+\+\] \((\d+\.\d+)s\)', output.decode('utf-8')) times = np.array(times, dtype=np.float32) trialTime = times[0] print("Warning: time measurement fallback option triggered, accuracy < 0.5s!") else: trialTime = float(renderTime[0]) else: trialTime = float(renderTime[0]) n += 1 if n == 1: mean = trialTime else: newMean = mean + (trialTime - mean) / n var += (trialTime - mean) * (trialTime - newMean) mean = newMean if n > 1: var /= n-1 twoStandardDevs = np.sqrt(var) * 2 import math roundToN = lambda x, n: round(x, -int(math.floor(math.log10(x))) + (n-1)) return (roundToN(mean, 3), 0.0 if repeats == 1 else roundToN(twoStandardDevs, 3)) def run_tests(ref_name, ref_integrator, ref_sampler, tester_fn, scenes): filenames = [] for scene_name, scene_desc in scenes.items(): scene_path = scene_desc['path'] if not os.path.exists('./' + scene_name): os.makedirs('./' + scene_name) # load the scene template and render the reference (if it does not exist already) with open(scene_path + scene_desc['template'], 'r') as f: scene = f.read() refpath = scene_name + '/' + ref_name if not os.path.isfile(refpath): sc = set_integrator(scene, ref_integrator) sc = set_sampler(sc, ref_sampler) with open(scene_path + 'scene.pbrtgen', 'w') as f: f.write(sc) subprocess.call(['./pbrt', scene_path + 'scene.pbrtgen', '--outfile', refpath]) filenames.append(refpath) filenames.extend(tester_fn(scene_name, scene, scene_path)) return filenames def show_results(filenames): # separate out the stratification factors factorImages = [] for name in filenames: if 'stratfactor-d' in name: factorImages.append(name) for name in factorImages: filenames.remove(name) # open all images, assumes tev is in the path try: viewer = ['tev'] viewer += filenames subprocess.call(viewer) except Exception: # tev was not found. Maybe we are on WSL and tev is a Windows .exe? viewer = ['tev.exe'] viewer += filenames try: subprocess.call(viewer) except: print('"tev" not found in path, proceeding without showing images')
[ "os.path.exists", "numpy.sqrt", "os.makedirs", "subprocess.Popen", "re.match", "os.path.isfile", "numpy.array", "subprocess.call", "math.log10" ]
[((315, 383), 're.match', 're.match', (["('(.+%s\\\\s*).+?(\\\\s*%s.+)' % (start, end))", 'scene', 're.DOTALL'], {}), "('(.+%s\\\\s*).+?(\\\\s*%s.+)' % (start, end), scene, re.DOTALL)\n", (323, 383), False, 'import re\n'), ((584, 652), 're.match', 're.match', (["('(.+%s\\\\s*).+?(\\\\s*%s.+)' % (start, end))", 'scene', 're.DOTALL'], {}), "('(.+%s\\\\s*).+?(\\\\s*%s.+)' % (start, end), scene, re.DOTALL)\n", (592, 652), False, 'import re\n'), ((859, 924), 'subprocess.Popen', 'Popen', (['args'], {'cwd': 'workingDir', 'stdin': 'PIPE', 'stdout': 'PIPE', 'stderr': 'PIPE'}), '(args, cwd=workingDir, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n', (864, 924), False, 'from subprocess import Popen, PIPE\n'), ((2399, 2411), 'numpy.sqrt', 'np.sqrt', (['var'], {}), '(var)\n', (2406, 2411), True, 'import numpy as np\n'), ((3936, 3959), 'subprocess.call', 'subprocess.call', (['viewer'], {}), '(viewer)\n', (3951, 3959), False, 'import subprocess\n'), ((2795, 2828), 'os.path.exists', 'os.path.exists', (["('./' + scene_name)"], {}), "('./' + scene_name)\n", (2809, 2828), False, 'import os\n'), ((2842, 2872), 'os.makedirs', 'os.makedirs', (["('./' + scene_name)"], {}), "('./' + scene_name)\n", (2853, 2872), False, 'import os\n'), ((3121, 3144), 'os.path.isfile', 'os.path.isfile', (['refpath'], {}), '(refpath)\n', (3135, 3144), False, 'import os\n'), ((3350, 3429), 'subprocess.call', 'subprocess.call', (["['./pbrt', scene_path + 'scene.pbrtgen', '--outfile', refpath]"], {}), "(['./pbrt', scene_path + 'scene.pbrtgen', '--outfile', refpath])\n", (3365, 3429), False, 'import subprocess\n'), ((1832, 1865), 'numpy.array', 'np.array', (['times'], {'dtype': 'np.float32'}), '(times, dtype=np.float32)\n', (1840, 1865), True, 'import numpy as np\n'), ((4140, 4163), 'subprocess.call', 'subprocess.call', (['viewer'], {}), '(viewer)\n', (4155, 4163), False, 'import subprocess\n'), ((2486, 2499), 'math.log10', 'math.log10', (['x'], {}), '(x)\n', (2496, 2499), False, 'import math\n')]
# RS_SGS100A.py class, to perform the communication between the Wrapper and the device # <NAME> <<EMAIL>>, 2015 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA from instrument import Instrument import visa import types import logging import numpy as np class RS_SGS100A(Instrument): ''' RF generator. Usage: Initialize with <name> = instruments.create('<name>', 'RS_SGS100A', address='<VISA address>, reset=<bool>') ''' def __init__(self, name, address, reset=False): ''' Initializes the RS_SGS100A, and communicates with the wrapper. Input: name (string) : name of the instrument address (string) : VISA address reset (bool) : resets to default values, default=False ''' logging.info(__name__ + ' : Initializing instrument RS_SGS100A') Instrument.__init__(self, name, tags=['physical']) # Add some global constants self._address = address self._visainstrument = visa.ResourceManager().open_resource(self._address, timeout=2000) try: self._visainstrument.read_termination = '\n' self._visainstrument.write_termination = '\n' self.add_parameter('idn', flags=Instrument.FLAG_GET, type=types.StringType, format='%.10s') self.add_parameter('power', flags=Instrument.FLAG_GETSET|Instrument.FLAG_GET_AFTER_SET, units='dBm', minval=-120, maxval=22, type=types.FloatType) self.add_parameter('frequency', format='%.09e', flags=Instrument.FLAG_GETSET|Instrument.FLAG_GET_AFTER_SET, units='Hz', minval=1e6, maxval=12.75e9, type=types.FloatType) self.add_parameter('timebase', type=types.StringType, flags=Instrument.FLAG_GETSET|Instrument.FLAG_GET_AFTER_SET, format_map={'INT':'internal', 'EXT':'external'}) self.add_parameter('timebase_external_input_frequency', type=types.IntType, flags=Instrument.FLAG_GETSET|Instrument.FLAG_GET_AFTER_SET, format_map={10:'10 MHz', 100:'100 MHz', 1000:'1000 MHz'}) self.add_parameter('status', flags=Instrument.FLAG_GETSET|Instrument.FLAG_GET_AFTER_SET, type=types.StringType, format_map={'on': 'output on', 'off': 'output off'}) self.add_parameter('mod_pulse', flags=Instrument.FLAG_GETSET, type=types.StringType, format_map={'on': 'pulsing/gating on', 'off': 'pulsing/gating off'}) self.add_parameter('pulse_source', flags=Instrument.FLAG_GETSET, type=types.StringType, format_map={'int': 'internal', 'ext': 'external'}) self.add_parameter('pulse_inverted_polarity', flags=Instrument.FLAG_GETSET, type=types.BooleanType) self.add_function('reset') self.add_function ('get_all') if (reset): self.reset() else: self.get_all() except: self._visainstrument.close() raise def reset(self): ''' Resets the instrument to default values Input: None Output: None ''' logging.info(__name__ + ' : resetting instrument') self._visainstrument.write('*RST') self.get_all() def get_all(self): ''' Reads all implemented parameters from the instrument, and updates the wrapper. Input: None Output: None ''' logging.info(__name__ + ' : get all') self.get_idn() self.get_power() self.get_frequency() self.get_status() self.get_timebase() self.get_timebase_external_input_frequency() self.get_mod_pulse() self.get_pulse_inverted_polarity() self.get_pulse_source() def __to_rounded_string(self, x, decimals, significant_figures): ''' Round x to the specified number of decimals and significant figures. Output a warning if rounded value is not equal to x. ''' rounded = ('%.{0}e'.format(significant_figures-1)) % ( np.round(x, decimals=decimals) ) if np.abs(float(rounded) - x) > np.finfo(np.float).tiny: logging.warn('Rounding the requested value (%.20e) to %s (i.e. by %.20e).' % (x, rounded, x - float(rounded))) return rounded def do_get_idn(self): ''' Get a string identifying the instrument. ''' return self._visainstrument.query('*IDN?') def do_get_power(self): ''' Reads the power of the signal from the instrument. ''' logging.debug(__name__ + ' : get power') return float(self._visainstrument.query('POW?')) def do_set_power(self, amp): ''' Set the power of the signal. ''' logging.debug(__name__ + ' : set power to %f' % amp) self._visainstrument.write('POW %s' % self.__to_rounded_string(amp, 2, 20)) def do_get_frequency(self): ''' Reads the frequency of the signal from the instrument. ''' logging.debug(__name__ + ' : get frequency') return float(self._visainstrument.query('FREQ?')) def do_set_frequency(self, freq): ''' Set the frequency of the instrument. ''' logging.debug(__name__ + ' : set frequency to %f' % freq) self._visainstrument.write('FREQ %s' % ( self.__to_rounded_string(freq, decimals=3, significant_figures=20) )) def do_get_status(self): ''' Whether the RF output is on or not. ''' logging.debug(__name__ + ' : get status') stat = self._visainstrument.query('OUTP?').strip().lower() return 'on' if (stat in ['1', 'on']) else 'off' def do_set_status(self, status): ''' Set whether the RF output is on or not. ''' logging.debug(__name__ + ' : set status to %s' % status) self._visainstrument.write('OUTP %s' % status.upper()) def do_get_timebase(self): ''' Reference oscillator (internal/external). ''' logging.debug(__name__ + ' : get timebase') tbase = self._visainstrument.query('ROSC:SOUR?').upper()[:3] return tbase def do_set_timebase(self, val): ''' Reference oscillator (internal/external). ''' logging.debug(__name__ + ' : set timebase to %s' % val) tbase = val.upper()[:3] assert tbase in ['INT', 'EXT'] self._visainstrument.write('ROSC:SOUR %s' % tbase) def do_get_timebase_external_input_frequency(self): ''' Reference oscillator frequency (10/100/1000 MHz). ''' logging.debug(__name__ + ' : get timebase freq') f = self._visainstrument.query('ROSC:EXT:FREQ?').strip().upper() assert f[-3:] == 'MHZ', f return f[:-3] def do_set_timebase_external_input_frequency(self, val): ''' Reference oscillator frequency (10/100/1000 MHz). ''' logging.debug(__name__ + ' : set timebase freq') self._visainstrument.write('ROSC:EXT:FREQ %sMHZ' % val) def do_get_mod_pulse(self): stat = self._visainstrument.query(':PULM:STAT?') return 'on' if (stat.lower().strip() in ['1', 'on']) else 'off' def do_set_mod_pulse(self, status): #self.set_pulse_inverted_polarity(False) self._visainstrument.write(':PULM:STAT %s' % (status.upper())) def do_get_pulse_inverted_polarity(self): stat = self._visainstrument.query(':PULM:POL?') return stat.lower().strip().startswith('inv') def do_set_pulse_inverted_polarity(self, val): self._visainstrument.write(':PULM:POL %s' % ('INV' if val else 'NORM')) def do_get_pulse_source(self): stat = self._visainstrument.query(':PULM:SOUR?').lower() return stat def do_set_pulse_source(self, state): self._visainstrument.write( ':PULM:SOUR %s' % (state.upper()) )
[ "logging.debug", "visa.ResourceManager", "instrument.Instrument.__init__", "numpy.finfo", "logging.info", "numpy.round" ]
[((1437, 1501), 'logging.info', 'logging.info', (["(__name__ + ' : Initializing instrument RS_SGS100A')"], {}), "(__name__ + ' : Initializing instrument RS_SGS100A')\n", (1449, 1501), False, 'import logging\n'), ((1510, 1560), 'instrument.Instrument.__init__', 'Instrument.__init__', (['self', 'name'], {'tags': "['physical']"}), "(self, name, tags=['physical'])\n", (1529, 1560), False, 'from instrument import Instrument\n'), ((4129, 4179), 'logging.info', 'logging.info', (["(__name__ + ' : resetting instrument')"], {}), "(__name__ + ' : resetting instrument')\n", (4141, 4179), False, 'import logging\n'), ((4464, 4501), 'logging.info', 'logging.info', (["(__name__ + ' : get all')"], {}), "(__name__ + ' : get all')\n", (4476, 4501), False, 'import logging\n'), ((5587, 5627), 'logging.debug', 'logging.debug', (["(__name__ + ' : get power')"], {}), "(__name__ + ' : get power')\n", (5600, 5627), False, 'import logging\n'), ((5788, 5840), 'logging.debug', 'logging.debug', (["(__name__ + ' : set power to %f' % amp)"], {}), "(__name__ + ' : set power to %f' % amp)\n", (5801, 5840), False, 'import logging\n'), ((6053, 6097), 'logging.debug', 'logging.debug', (["(__name__ + ' : get frequency')"], {}), "(__name__ + ' : get frequency')\n", (6066, 6097), False, 'import logging\n'), ((6272, 6329), 'logging.debug', 'logging.debug', (["(__name__ + ' : set frequency to %f' % freq)"], {}), "(__name__ + ' : set frequency to %f' % freq)\n", (6285, 6329), False, 'import logging\n'), ((6584, 6625), 'logging.debug', 'logging.debug', (["(__name__ + ' : get status')"], {}), "(__name__ + ' : get status')\n", (6597, 6625), False, 'import logging\n'), ((6867, 6923), 'logging.debug', 'logging.debug', (["(__name__ + ' : set status to %s' % status)"], {}), "(__name__ + ' : set status to %s' % status)\n", (6880, 6923), False, 'import logging\n'), ((7101, 7144), 'logging.debug', 'logging.debug', (["(__name__ + ' : get timebase')"], {}), "(__name__ + ' : get timebase')\n", (7114, 7144), False, 'import logging\n'), ((7354, 7409), 'logging.debug', 'logging.debug', (["(__name__ + ' : set timebase to %s' % val)"], {}), "(__name__ + ' : set timebase to %s' % val)\n", (7367, 7409), False, 'import logging\n'), ((7687, 7735), 'logging.debug', 'logging.debug', (["(__name__ + ' : get timebase freq')"], {}), "(__name__ + ' : get timebase freq')\n", (7700, 7735), False, 'import logging\n'), ((8017, 8065), 'logging.debug', 'logging.debug', (["(__name__ + ' : set timebase freq')"], {}), "(__name__ + ' : set timebase freq')\n", (8030, 8065), False, 'import logging\n'), ((5074, 5104), 'numpy.round', 'np.round', (['x'], {'decimals': 'decimals'}), '(x, decimals=decimals)\n', (5082, 5104), True, 'import numpy as np\n'), ((1661, 1683), 'visa.ResourceManager', 'visa.ResourceManager', ([], {}), '()\n', (1681, 1683), False, 'import visa\n'), ((5147, 5165), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (5155, 5165), True, 'import numpy as np\n')]
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """ Module for rotating frame handling classes. """ from typing import Union, List, Optional import numpy as np from scipy.sparse import issparse, csr_matrix from qiskit import QiskitError from qiskit.quantum_info.operators import Operator from qiskit.quantum_info.operators.predicates import is_hermitian_matrix from qiskit_dynamics.array import Array from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type try: import jax.numpy as jnp from jax.experimental import sparse as jsparse jsparse_matmul = jsparse.sparsify(jnp.matmul) except ImportError: pass class RotatingFrame: r"""Class for representing a rotation frame transformation. This class provides functionality for transforming various objects into or out-of a rotating frame specified by an anti-Hermitian operator :math:`F = -iH`. For example: * Bringing a "state" into/out of the frame: :math:`t, y \mapsto e^{\mp tF}y` * Bringing an "operator" into/out of the frame: :math:`t, A \mapsto e^{\mp tF}Ae^{\pm tF}` * Bringing a generator for a BMDE into/out of the frame: :math:`t, G \mapsto e^{\mp tF}Ge^{\pm tF} - F` This class also contains functions for bringing states/operators into/out of the basis in which :math:`F` is diagonalized, which we refer to as the "frame basis". All previously mentioned functions also include optional arguments specifying whether the input/output are meant to be in the frame basis. .. note:: :class:`~qiskit_dynamics.models.RotatingFrame` can be instantiated with a 1d array, which is understood to correspond to the diagonal entries of a diagonal :math:`H` or :math:`F = -i H`. """ def __init__( self, frame_operator: Union[Array, Operator], atol: float = 1e-10, rtol: float = 1e-10, ): """Initialize with a frame operator. Args: frame_operator: The frame operator, must be either Hermitian or anti-Hermitian. atol: Absolute tolerance when verifying that the frame_operator is Hermitian or anti-Hermitian. rtol: Relative tolerance when verifying that the frame_operator is Hermitian or anti-Hermitian. """ if isinstance(frame_operator, RotatingFrame): frame_operator = frame_operator.frame_operator self._frame_operator = frame_operator frame_operator = to_array(frame_operator) if frame_operator is None: self._dim = None self._frame_diag = None self._frame_basis = None self._frame_basis_adjoint = None # if frame_operator is a 1d array, assume already diagonalized elif frame_operator.ndim == 1: # verify Hermitian or anti-Hermitian # if Hermitian convert to anti-Hermitian frame_operator = _is_herm_or_anti_herm(frame_operator, atol=atol, rtol=rtol) self._frame_diag = Array(frame_operator) self._frame_basis = None self._frame_basis_adjoint = None self._dim = len(self._frame_diag) # if not, diagonalize it else: # verify Hermitian or anti-Hermitian # if Hermitian convert to anti-Hermitian frame_operator = _is_herm_or_anti_herm(frame_operator, atol=atol, rtol=rtol) # diagonalize with eigh, utilizing assumption of anti-hermiticity frame_diag, frame_basis = np.linalg.eigh(1j * frame_operator) self._frame_diag = Array(-1j * frame_diag) self._frame_basis = Array(frame_basis) self._frame_basis_adjoint = frame_basis.conj().transpose() self._dim = len(self._frame_diag) # lazily evaluate change-of-basis matrices for vectorized operators. self._vectorized_frame_basis = None self._vectorized_frame_basis_adjoint = None @property def dim(self) -> int: """The dimension of the frame.""" return self._dim @property def frame_operator(self) -> Array: """The original frame operator.""" return self._frame_operator @property def frame_diag(self) -> Array: """Diagonal of the frame operator.""" return self._frame_diag @property def frame_basis(self) -> Array: """Array containing diagonalizing unitary.""" return self._frame_basis @property def frame_basis_adjoint(self) -> Array: """Adjoint of the diagonalizing unitary.""" return self._frame_basis_adjoint def state_into_frame_basis(self, y: Array) -> Array: r"""Take a state into the frame basis, i.e. return ``self.frame_basis_adjoint @ y``. Args: y: The state. Returns: Array: The state in the frame basis. """ y = to_numeric_matrix_type(y) if self.frame_basis_adjoint is None: return y return self.frame_basis_adjoint @ y def state_out_of_frame_basis(self, y: Array) -> Array: r"""Take a state out of the frame basis, i.e. ``return self.frame_basis @ y``. Args: y: The state. Returns: Array: The state in the frame basis. """ y = to_numeric_matrix_type(y) if self.frame_basis is None: return y return self.frame_basis @ y def operator_into_frame_basis( self, op: Union[Operator, List[Operator], Array, csr_matrix, None] ) -> Array: r"""Take an operator into the frame basis, i.e. return ``self.frame_basis_adjoint @ A @ self.frame_basis`` Args: op: The operator or array of operators. Returns: Array: The operator in the frame basis. """ op = to_numeric_matrix_type(op) if self.frame_basis is None or op is None: return op if type(op).__name__ == "BCOO": return self.frame_basis_adjoint @ jsparse_matmul(op, self.frame_basis.data) else: # parentheses are necessary for sparse op evaluation return self.frame_basis_adjoint @ (op @ self.frame_basis) def operator_out_of_frame_basis( self, op: Union[Operator, List[Operator], Array, csr_matrix, None] ) -> Array: r"""Take an operator out of the frame basis, i.e. return ``self.frame_basis @ to_array(op) @ self.frame_basis_adjoint``. Args: op: The operator or array of operators. Returns: Array: The operator in the frame basis. """ op = to_numeric_matrix_type(op) if self.frame_basis is None or op is None: return op if type(op).__name__ == "BCOO": return self.frame_basis @ jsparse_matmul(op, self.frame_basis_adjoint.data) else: # parentheses are necessary for sparse op evaluation return self.frame_basis @ (op @ self.frame_basis_adjoint) def state_into_frame( self, t: float, y: Array, y_in_frame_basis: Optional[bool] = False, return_in_frame_basis: Optional[bool] = False, ): """Take a state into the rotating frame, i.e. return exp(-tF) @ y. Args: t: Time. y: State (array of appropriate size). y_in_frame_basis: Whether or not the array y is already in the basis in which the frame is diagonal. return_in_frame_basis: Whether or not to return the result in the frame basis. Returns: Array: State in frame. """ y = to_numeric_matrix_type(y) if self._frame_operator is None: return y out = y # if not in frame basis convert it if not y_in_frame_basis: out = self.state_into_frame_basis(out) # go into the frame using fast diagonal matrix multiplication out = (np.exp(self.frame_diag * (-t)) * out.transpose()).transpose() # = e^{tF}out # if output is requested to not be in the frame basis, convert it if not return_in_frame_basis: out = self.state_out_of_frame_basis(out) return out def state_out_of_frame( self, t: float, y: Array, y_in_frame_basis: Optional[bool] = False, return_in_frame_basis: Optional[bool] = False, ) -> Array: r"""Take a state out of the rotating frame, i.e. ``return exp(tF) @ y``. Calls ``self.state_into_frame`` with time reversed. Args: t: Time. y: State (array of appropriate size). y_in_frame_basis: Whether or not the array y is already in the basis in which the frame is diagonal. return_in_frame_basis: Whether or not to return the result in the frame basis. Returns: Array: State out of frame. """ return self.state_into_frame(-t, y, y_in_frame_basis, return_in_frame_basis) def _conjugate_and_add( self, t: float, operator: Union[Array, csr_matrix], op_to_add_in_fb: Optional[Array] = None, operator_in_frame_basis: Optional[bool] = False, return_in_frame_basis: Optional[bool] = False, vectorized_operators: Optional[bool] = False, ) -> Union[Array, csr_matrix]: r"""General helper function for computing :math:`\exp(-tF)G\exp(tF) + B`. Note: B is added in the frame basis before any potential final change out of the frame basis. Note: There are two conventions for passing multiple operators at the same time. For evaluation with vectorized_operators=False, these operators should be passed as (k, dim, dim) Array objects, with the :math:`i^{th}` operator being stored as the [i,:,:] entry. For vectorized_operators = True, these (vectorized) operators should be passed as a (dim**2, k) Array, with the :math:`i^{th}` vectorized operator stored as the [:,i] entry. Args: t: Time. operator: The operator G. op_to_add_in_fb: The additional operator B. operator_in_fame_basis: Whether ``operator`` is already in the basis in which the frame operator is diagonal. vectorized_operators: Whether ``operator`` is passed as a vectorized, ``(dim^2,)`` Array, rather than a ``(dim,dim)`` Array. Returns: Array of newly conjugated operator. """ operator = to_numeric_matrix_type(operator) op_to_add_in_fb = to_numeric_matrix_type(op_to_add_in_fb) if vectorized_operators: # If passing vectorized operator, undo vectorization temporarily if self._frame_operator is None: if op_to_add_in_fb is None: return operator else: return operator + op_to_add_in_fb if len(operator.shape) == 2: operator = operator.T operator = operator.reshape(operator.shape[:-1] + (self.dim, self.dim), order="F") if self._frame_operator is None: if op_to_add_in_fb is None: return operator else: if op_to_add_in_fb is not None: if issparse(operator): op_to_add_in_fb = csr_matrix(op_to_add_in_fb) elif type(operator).__name__ == "BCOO": op_to_add_in_fb = to_BCOO(op_to_add_in_fb) return operator + op_to_add_in_fb out = operator # if not in frame basis convert it if not operator_in_frame_basis: out = self.operator_into_frame_basis(out) # get frame transformation matrix in diagonal basis # assumption that F is anti-Hermitian implies conjugation of # diagonal gives inversion exp_freq = np.exp(self.frame_diag * t) frame_mat = exp_freq.conj().reshape(self.dim, 1) * exp_freq if issparse(out): out = out.multiply(frame_mat) elif type(out).__name__ == "BCOO": out = out * frame_mat.data else: out = frame_mat * out if op_to_add_in_fb is not None: if issparse(out): op_to_add_in_fb = csr_matrix(op_to_add_in_fb) elif type(out).__name__ == "BCOO": op_to_add_in_fb = to_BCOO(op_to_add_in_fb) out = out + op_to_add_in_fb # if output is requested to not be in the frame basis, convert it if not return_in_frame_basis: out = self.operator_out_of_frame_basis(out) if vectorized_operators: # If a vectorized output is required, reshape correctly out = out.reshape(out.shape[:-2] + (self.dim ** 2,), order="F") if len(out.shape) == 2: out = out.T return out def operator_into_frame( self, t: float, operator: Union[Operator, Array, csr_matrix], operator_in_frame_basis: Optional[bool] = False, return_in_frame_basis: Optional[bool] = False, vectorized_operators: Optional[bool] = False, ) -> Array: r"""Bring an operator into the frame, i.e. return ``exp(-tF) @ operator @ exp(tF)``. Default implementation is to use ``self._conjugate_and_add``. Args: t: Time. operator: Array of appropriate size. operator_in_frame_basis: Whether or not the operator is already in the basis in which the frame is diagonal. return_in_frame_basis: Whether or not to return the result in the frame basis. vectorized_operators: Whether ``operator`` is passed as a vectorized, ``(dim^2,)`` Array, rather than a ``(dim,dim)`` Array. Returns: Array: operator in frame. """ return self._conjugate_and_add( t, operator, operator_in_frame_basis=operator_in_frame_basis, return_in_frame_basis=return_in_frame_basis, vectorized_operators=vectorized_operators, ) def operator_out_of_frame( self, t: float, operator: Union[Operator, Array, csr_matrix], operator_in_frame_basis: Optional[bool] = False, return_in_frame_basis: Optional[bool] = False, vectorized_operators: Optional[bool] = False, ): r"""Bring an operator into the rotating frame, i.e. return ``exp(tF) @ operator @ exp(-tF)``. Default implmentation is to use `self.operator_into_frame`. Args: t: Time. operator: Array of appropriate size. operator_in_frame_basis: Whether or not the operator is already in the basis in which the frame is diagonal. return_in_frame_basis: Whether or not to return the result in the frame basis. vectorized_operators: Whether ``operator`` is passed as a vectorized, ``(dim^2,)`` Array, rather than a ``(dim,dim)`` Array. Returns: Array: operator out of frame. """ return self.operator_into_frame( -t, operator, operator_in_frame_basis=operator_in_frame_basis, return_in_frame_basis=return_in_frame_basis, vectorized_operators=vectorized_operators, ) def generator_into_frame( self, t: float, operator: Union[Operator, Array, csr_matrix], operator_in_frame_basis: Optional[bool] = False, return_in_frame_basis: Optional[bool] = False, vectorized_operators: Optional[bool] = False, ): r"""Take an generator into the rotating frame, i.e. return ``exp(-tF) @ operator @ exp(tF) - F``. Default implementation is to use `self._conjugate_and_add`. Args: t: Time. operator: Generator (array of appropriate size). operator_in_frame_basis: Whether or not the generator is already in the basis in which the frame is diagonal. return_in_frame_basis: Whether or not to return the result in the frame basis. vectorized_operators: Whether ``operator`` is passed as a vectorized, ``(dim^2,)`` Array, rather than a ``(dim,dim)`` Array. Returns: Array: Generator in frame. """ if self.frame_operator is None: return to_numeric_matrix_type(operator) else: # conjugate and subtract the frame diagonal return self._conjugate_and_add( t, operator, op_to_add_in_fb=-np.diag(self.frame_diag), operator_in_frame_basis=operator_in_frame_basis, return_in_frame_basis=return_in_frame_basis, vectorized_operators=vectorized_operators, ) def generator_out_of_frame( self, t: float, operator: Union[Operator, Array, csr_matrix], operator_in_frame_basis: Optional[bool] = False, return_in_frame_basis: Optional[bool] = False, ) -> Array: r"""Take an operator out of the frame, i.e. return ``exp(tF) @ operator @ exp(-tF) + F``. Default implementation is to use `self._conjugate_and_add`. Args: t: Time operator: Generator (array of appropriate size). operator_in_frame_basis: Whether or not the operator is already in the basis in which the frame is diagonal. return_in_frame_basis: Whether or not to return the result in the frame basis. Returns: Array: Generator out of frame. """ if self.frame_operator is None: return to_numeric_matrix_type(operator) else: # conjugate and add the frame diagonal return self._conjugate_and_add( -t, operator, op_to_add_in_fb=Array(np.diag(self.frame_diag)), operator_in_frame_basis=operator_in_frame_basis, return_in_frame_basis=return_in_frame_basis, ) @property def vectorized_frame_basis(self): """Lazily evaluated operator for mapping vectorized operators into the frame basis.""" if self.frame_basis is None: return None if self._vectorized_frame_basis is None: self._vectorized_frame_basis = np.kron(self.frame_basis.conj(), self.frame_basis) self._vectorized_frame_basis_adjoint = self._vectorized_frame_basis.conj().transpose() return self._vectorized_frame_basis @property def vectorized_frame_basis_adjoint(self): """Lazily evaluated operator for mapping vectorized operators out of the frame basis.""" if self.frame_basis is None: return None if self._vectorized_frame_basis_adjoint is None: # trigger lazy evaluation of vectorized_frame_basis # pylint: disable=pointless-statement self.vectorized_frame_basis return self._vectorized_frame_basis_adjoint def vectorized_map_into_frame( self, time: float, op: Array, operator_in_frame_basis: Optional[bool] = False, return_in_frame_basis: Optional[bool] = False, ) -> Array: r"""Given an operator `op` of dimension `dim**2` assumed to represent vectorized linear map in column stacking convention, returns: .. math:: ((e^{tF})^T \otimes e^{-tF}) \times op \times ((e^{-tF})^T \otimes e^{tF}). Utilizes element-wise multiplication :math:`op \to \Delta\otimes\bar{\Delta} \odot op`, where :math:`\Delta_{ij}=\exp((-d_i+d_j)t)` is the frame difference matrix, as well as caches array :math:`\bar{C}\otimes C`, where ``C = self.frame_basis`` for future use. Args: time: The time t. op: The (dim^2,dim^2) Array. operator_in_frame_basis: Whether the operator is in the frame basis. return_in_frame_basis: Whether the operator should be returned in the frame basis. Returns: op in the frame. """ if self.frame_diag is not None: # Put the vectorized operator into the frame basis if not operator_in_frame_basis and self.frame_basis is not None: op = self.vectorized_frame_basis_adjoint @ (op @ self.vectorized_frame_basis) expvals = np.exp(self.frame_diag * time) # = e^{td_i} = e^{it*Im(d_i)} # = kron(e^{-it*Im(d_i)},e^{it*Im(d_i)}), but ~3x faster temp_outer = (expvals.conj().reshape(self.dim, 1) * expvals).flatten() delta_bar_otimes_delta = np.outer( temp_outer.conj(), temp_outer ) # = kron(delta.conj(),delta) but >3x faster if issparse(op): op = op.multiply(delta_bar_otimes_delta) else: op = delta_bar_otimes_delta * op # hadamard product if not return_in_frame_basis and self.frame_basis is not None: op = self.vectorized_frame_basis @ (op @ self.vectorized_frame_basis_adjoint) return op def _is_herm_or_anti_herm(mat: Array, atol: Optional[float] = 1e-10, rtol: Optional[float] = 1e-10): r"""Given `mat`, the logic of this function is: - if `mat` is hermitian, return `-1j * mat` - if `mat` is anti-hermitian, return `mat` - otherwise: - if `mat.backend == 'jax'` return `jnp.inf * mat` - otherwise raise an error The main purpose of this function is to hide the pecularities of the implementing the above logic in a compileable way in `jax`. Args: mat: array to check atol: absolute tolerance rtol: relative tolerance Returns: Array: anti-hermitian version of `mat` if applicable Raises: ImportError: if backend is jax and jax is not installed. QiskitError: if `mat` is not Hermitian or anti-Hermitian """ mat = to_array(mat) mat = Array(mat, dtype=complex) if mat.backend == "jax": from jax.lax import cond mat = mat.data if mat.ndim == 1: # this function checks if pure imaginary. If yes it returns the # array, otherwise it multiplies it by jnp.nan to raise an error # Note: pathways in conditionals in jax cannot raise Exceptions def anti_herm_conditional(b): aherm_pred = jnp.allclose(b, -b.conj(), atol=atol, rtol=rtol) return cond(aherm_pred, lambda A: A, lambda A: jnp.nan * A, b) # Check if it is purely real, if not apply anti_herm_conditional herm_pred = jnp.allclose(mat, mat.conj(), atol=atol, rtol=rtol) return Array(cond(herm_pred, lambda A: -1j * A, anti_herm_conditional, mat)) else: # this function checks if anti-hermitian, if yes returns the array, # otherwise it multiplies it by jnp.nan def anti_herm_conditional(b): aherm_pred = jnp.allclose(b, -b.conj().transpose(), atol=atol, rtol=rtol) return cond(aherm_pred, lambda A: A, lambda A: jnp.nan * A, b) # the following lines check if a is hermitian, otherwise it feeds # it into the anti_herm_conditional herm_pred = jnp.allclose(mat, mat.conj().transpose(), atol=atol, rtol=rtol) return Array(cond(herm_pred, lambda A: -1j * A, anti_herm_conditional, mat)) else: if mat.ndim == 1: if np.allclose(mat, mat.conj(), atol=atol, rtol=rtol): return -1j * mat elif np.allclose(mat, -mat.conj(), atol=atol, rtol=rtol): return mat else: if is_hermitian_matrix(mat, rtol=rtol, atol=atol): return -1j * mat elif is_hermitian_matrix(1j * mat, rtol=rtol, atol=atol): return mat # raise error if execution has made it this far raise QiskitError( """frame_operator must be either a Hermitian or anti-Hermitian matrix.""" )
[ "qiskit_dynamics.type_utils.to_array", "qiskit_dynamics.type_utils.to_numeric_matrix_type", "scipy.sparse.issparse", "numpy.diag", "numpy.exp", "qiskit.QiskitError", "scipy.sparse.csr_matrix", "qiskit_dynamics.type_utils.to_BCOO", "numpy.linalg.eigh", "jax.experimental.sparse.sparsify", "qiskit....
[((1052, 1080), 'jax.experimental.sparse.sparsify', 'jsparse.sparsify', (['jnp.matmul'], {}), '(jnp.matmul)\n', (1068, 1080), True, 'from jax.experimental import sparse as jsparse\n'), ((23189, 23202), 'qiskit_dynamics.type_utils.to_array', 'to_array', (['mat'], {}), '(mat)\n', (23197, 23202), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n'), ((23213, 23238), 'qiskit_dynamics.array.Array', 'Array', (['mat'], {'dtype': 'complex'}), '(mat, dtype=complex)\n', (23218, 23238), False, 'from qiskit_dynamics.array import Array\n'), ((3039, 3063), 'qiskit_dynamics.type_utils.to_array', 'to_array', (['frame_operator'], {}), '(frame_operator)\n', (3047, 3063), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n'), ((5470, 5495), 'qiskit_dynamics.type_utils.to_numeric_matrix_type', 'to_numeric_matrix_type', (['y'], {}), '(y)\n', (5492, 5495), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n'), ((5893, 5918), 'qiskit_dynamics.type_utils.to_numeric_matrix_type', 'to_numeric_matrix_type', (['y'], {}), '(y)\n', (5915, 5918), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n'), ((6425, 6451), 'qiskit_dynamics.type_utils.to_numeric_matrix_type', 'to_numeric_matrix_type', (['op'], {}), '(op)\n', (6447, 6451), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n'), ((7230, 7256), 'qiskit_dynamics.type_utils.to_numeric_matrix_type', 'to_numeric_matrix_type', (['op'], {}), '(op)\n', (7252, 7256), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n'), ((8304, 8329), 'qiskit_dynamics.type_utils.to_numeric_matrix_type', 'to_numeric_matrix_type', (['y'], {}), '(y)\n', (8326, 8329), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n'), ((11288, 11320), 'qiskit_dynamics.type_utils.to_numeric_matrix_type', 'to_numeric_matrix_type', (['operator'], {}), '(operator)\n', (11310, 11320), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n'), ((11347, 11386), 'qiskit_dynamics.type_utils.to_numeric_matrix_type', 'to_numeric_matrix_type', (['op_to_add_in_fb'], {}), '(op_to_add_in_fb)\n', (11369, 11386), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n'), ((12690, 12717), 'numpy.exp', 'np.exp', (['(self.frame_diag * t)'], {}), '(self.frame_diag * t)\n', (12696, 12717), True, 'import numpy as np\n'), ((12797, 12810), 'scipy.sparse.issparse', 'issparse', (['out'], {}), '(out)\n', (12805, 12810), False, 'from scipy.sparse import issparse, csr_matrix\n'), ((25198, 25321), 'qiskit.QiskitError', 'QiskitError', (['"""frame_operator must be either a Hermitian or\n anti-Hermitian matrix."""'], {}), '(\n """frame_operator must be either a Hermitian or\n anti-Hermitian matrix."""\n )\n', (25209, 25321), False, 'from qiskit import QiskitError\n'), ((13040, 13053), 'scipy.sparse.issparse', 'issparse', (['out'], {}), '(out)\n', (13048, 13053), False, 'from scipy.sparse import issparse, csr_matrix\n'), ((17456, 17488), 'qiskit_dynamics.type_utils.to_numeric_matrix_type', 'to_numeric_matrix_type', (['operator'], {}), '(operator)\n', (17478, 17488), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n'), ((18833, 18865), 'qiskit_dynamics.type_utils.to_numeric_matrix_type', 'to_numeric_matrix_type', (['operator'], {}), '(operator)\n', (18855, 18865), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n'), ((21601, 21631), 'numpy.exp', 'np.exp', (['(self.frame_diag * time)'], {}), '(self.frame_diag * time)\n', (21607, 21631), True, 'import numpy as np\n'), ((21982, 21994), 'scipy.sparse.issparse', 'issparse', (['op'], {}), '(op)\n', (21990, 21994), False, 'from scipy.sparse import issparse, csr_matrix\n'), ((24949, 24995), 'qiskit.quantum_info.operators.predicates.is_hermitian_matrix', 'is_hermitian_matrix', (['mat'], {'rtol': 'rtol', 'atol': 'atol'}), '(mat, rtol=rtol, atol=atol)\n', (24968, 24995), False, 'from qiskit.quantum_info.operators.predicates import is_hermitian_matrix\n'), ((3581, 3602), 'qiskit_dynamics.array.Array', 'Array', (['frame_operator'], {}), '(frame_operator)\n', (3586, 3602), False, 'from qiskit_dynamics.array import Array\n'), ((4087, 4124), 'numpy.linalg.eigh', 'np.linalg.eigh', (['(1.0j * frame_operator)'], {}), '(1.0j * frame_operator)\n', (4101, 4124), True, 'import numpy as np\n'), ((4155, 4180), 'qiskit_dynamics.array.Array', 'Array', (['(-1.0j * frame_diag)'], {}), '(-1.0j * frame_diag)\n', (4160, 4180), False, 'from qiskit_dynamics.array import Array\n'), ((4211, 4229), 'qiskit_dynamics.array.Array', 'Array', (['frame_basis'], {}), '(frame_basis)\n', (4216, 4229), False, 'from qiskit_dynamics.array import Array\n'), ((13089, 13116), 'scipy.sparse.csr_matrix', 'csr_matrix', (['op_to_add_in_fb'], {}), '(op_to_add_in_fb)\n', (13099, 13116), False, 'from scipy.sparse import issparse, csr_matrix\n'), ((23726, 23781), 'jax.lax.cond', 'cond', (['aherm_pred', '(lambda A: A)', '(lambda A: jnp.nan * A)', 'b'], {}), '(aherm_pred, lambda A: A, lambda A: jnp.nan * A, b)\n', (23730, 23781), False, 'from jax.lax import cond\n'), ((23961, 24025), 'jax.lax.cond', 'cond', (['herm_pred', '(lambda A: -1.0j * A)', 'anti_herm_conditional', 'mat'], {}), '(herm_pred, lambda A: -1.0j * A, anti_herm_conditional, mat)\n', (23965, 24025), False, 'from jax.lax import cond\n'), ((24326, 24381), 'jax.lax.cond', 'cond', (['aherm_pred', '(lambda A: A)', '(lambda A: jnp.nan * A)', 'b'], {}), '(aherm_pred, lambda A: A, lambda A: jnp.nan * A, b)\n', (24330, 24381), False, 'from jax.lax import cond\n'), ((24622, 24686), 'jax.lax.cond', 'cond', (['herm_pred', '(lambda A: -1.0j * A)', 'anti_herm_conditional', 'mat'], {}), '(herm_pred, lambda A: -1.0j * A, anti_herm_conditional, mat)\n', (24626, 24686), False, 'from jax.lax import cond\n'), ((25047, 25100), 'qiskit.quantum_info.operators.predicates.is_hermitian_matrix', 'is_hermitian_matrix', (['(1.0j * mat)'], {'rtol': 'rtol', 'atol': 'atol'}), '(1.0j * mat, rtol=rtol, atol=atol)\n', (25066, 25100), False, 'from qiskit.quantum_info.operators.predicates import is_hermitian_matrix\n'), ((8623, 8651), 'numpy.exp', 'np.exp', (['(self.frame_diag * -t)'], {}), '(self.frame_diag * -t)\n', (8629, 8651), True, 'import numpy as np\n'), ((12076, 12094), 'scipy.sparse.issparse', 'issparse', (['operator'], {}), '(operator)\n', (12084, 12094), False, 'from scipy.sparse import issparse, csr_matrix\n'), ((13198, 13222), 'qiskit_dynamics.type_utils.to_BCOO', 'to_BCOO', (['op_to_add_in_fb'], {}), '(op_to_add_in_fb)\n', (13205, 13222), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n'), ((12138, 12165), 'scipy.sparse.csr_matrix', 'csr_matrix', (['op_to_add_in_fb'], {}), '(op_to_add_in_fb)\n', (12148, 12165), False, 'from scipy.sparse import issparse, csr_matrix\n'), ((17681, 17705), 'numpy.diag', 'np.diag', (['self.frame_diag'], {}), '(self.frame_diag)\n', (17688, 17705), True, 'import numpy as np\n'), ((19059, 19083), 'numpy.diag', 'np.diag', (['self.frame_diag'], {}), '(self.frame_diag)\n', (19066, 19083), True, 'import numpy as np\n'), ((12268, 12292), 'qiskit_dynamics.type_utils.to_BCOO', 'to_BCOO', (['op_to_add_in_fb'], {}), '(op_to_add_in_fb)\n', (12275, 12292), False, 'from qiskit_dynamics.type_utils import to_array, to_BCOO, to_numeric_matrix_type\n')]
import gym import numpy as np from metaworlds.core import Serializable from metaworlds.envs import Step from metaworlds.misc.overrides import overrides class SlidingMemEnv(gym.Wrapper, Serializable): def __init__( self, env, n_steps=4, axis=0, ): super().__init__(env) self.n_steps = n_steps self.axis = axis self.buffer = None # Always call Serializable constructor last Serializable.quick_init(self, locals()) def reset_buffer(self, new_): assert self.axis == 0 self.buffer = np.zeros(self.observation_space.shape, dtype=np.float32) self.buffer[0:] = new_ def add_to_buffer(self, new_): assert self.axis == 0 self.buffer[1:] = self.buffer[:-1] self.buffer[:1] = new_ @property def observation_space(self): origin = self.env.observation_space low = origin.low[np.newaxis, ...] high = origin.high[np.newaxis, ...] return gym.spaces.Box( np.repeat(low, self.n_steps, axis=self.axis), np.repeat(high, self.n_steps, axis=self.axis), dtype=np.float32) @observation_space.setter def observation_space(self, obs_space): # Since gym.Wrapper sets this property in SlidingMemEnv.__init__(), # this void setter is required to avoid an AttributeError. return @overrides def reset(self): obs = self.env.reset() self.reset_buffer(obs) return self.buffer @overrides def step(self, action): next_obs, reward, done, info = self.env.step(action) self.add_to_buffer(next_obs) return Step(self.buffer, reward, done, **info)
[ "numpy.zeros", "numpy.repeat", "metaworlds.envs.Step" ]
[((608, 664), 'numpy.zeros', 'np.zeros', (['self.observation_space.shape'], {'dtype': 'np.float32'}), '(self.observation_space.shape, dtype=np.float32)\n', (616, 664), True, 'import numpy as np\n'), ((1708, 1747), 'metaworlds.envs.Step', 'Step', (['self.buffer', 'reward', 'done'], {}), '(self.buffer, reward, done, **info)\n', (1712, 1747), False, 'from metaworlds.envs import Step\n'), ((1057, 1101), 'numpy.repeat', 'np.repeat', (['low', 'self.n_steps'], {'axis': 'self.axis'}), '(low, self.n_steps, axis=self.axis)\n', (1066, 1101), True, 'import numpy as np\n'), ((1115, 1160), 'numpy.repeat', 'np.repeat', (['high', 'self.n_steps'], {'axis': 'self.axis'}), '(high, self.n_steps, axis=self.axis)\n', (1124, 1160), True, 'import numpy as np\n')]
from __future__ import annotations import pyqtgraph as pg from pyqtgraph import colormap as cmap from typing import Generic, Iterator, Sequence, TypeVar, overload, MutableSequence import numpy as np from ._utils import convert_color_code, to_rgba from .components import Legend, Region, ScaleBar, TextItem from .graph_items import BarPlot, Curve, FillBetween, InfLine, LayerItem, Scatter, Histogram, TextGroup from .mouse_event import MouseClickEvent from ._doc import write_docs from ...widgets.utils import FreeWidget BOTTOM = "bottom" LEFT = "left" class LayerList(MutableSequence[LayerItem]): """A napari-like layer list for plot item handling.""" def __init__(self, parent: HasDataItems): self.parent = parent def __getitem__(self, key: int | str) -> LayerItem: if isinstance(key, int): return self.parent._items[key] elif isinstance(key, str): for item in self.parent._items: if item.name == key: return item else: raise ValueError(f"Item '{key}' not found.") else: raise TypeError(f"Cannot use type {type(key)} as a key.") def __setitem__(self, key, value): raise NotImplementedError("Can't set item") def __delitem__(self, key: int | str): return self.parent._remove_item(key) def append(self, item: LayerItem): if not isinstance(item, LayerItem): raise TypeError(f"Cannot append type {type(item)}.") self.parent._add_item(item) def insert(self, pos: int, item: LayerItem): if not isinstance(item, LayerItem): raise TypeError(f"Cannot insert type {type(item)}.") self.parent._insert_item(pos, item) def __len__(self): return len(self.parent._items) def clear(self): for _ in range(len(self)): self.parent._remove_item(-1) def swap(self, pos0: int, pos1: int): return self.parent._swap_items(pos0, pos1) def move(self, source: int, destination: int): return self.parent._move_item(source, destination) class HasDataItems: _items: list[LayerItem] @property def _graphics(self) -> pg.GraphicsWidget: """Target widget to add graphics items.""" raise NotImplementedError() @property def layers(self) -> LayerList: return LayerList(self) @overload def add_curve(self, x: Sequence[float], **kwargs): ... @overload def add_curve(self, x: Sequence[float], y: Sequence[float], **kwargs): ... @write_docs def add_curve(self, x=None, y=None, face_color = None, edge_color = None, color = None, size: float = 7, name: str | None = None, lw: float = 1, ls: str = "-", symbol=None): """ Add a line plot like ``plt.plot(x, y)``. Parameters ---------- {x} {y} {face_color} {edge_color} {color} size: float, default is 7 Symbol size. {name} {lw} {ls} {symbol} Returns ------- Curve A plot item of a curve. """ x, y = _check_xy(x, y) name = self._find_unique_name((name or "Curve")) face_color, edge_color = _check_colors(face_color, edge_color, color) item = Curve(x, y, face_color=face_color, edge_color=edge_color, size=size, name=name, lw=lw, ls=ls, symbol=symbol) self._add_item(item) return item @overload def add_scatter(self, x: Sequence[float], **kwargs): ... @overload def add_scatter(self, x: Sequence[float], y: Sequence[float], **kwargs): ... @write_docs def add_scatter(self, x=None, y=None, face_color = None, edge_color = None, color = None, size: float = 7, name: str | None = None, lw: float = 1, ls: str = "-", symbol="o"): """ Add scatter plot like ``plt.scatter(x, y)``. Parameters ---------- {x} {y} {face_color} {edge_color} {color} size: float, default is 7 Symbol size. {name} {lw} {ls} {symbol} Returns ------- Scatter A plot item of the scatter plot. """ x, y = _check_xy(x, y) name = self._find_unique_name((name or "Scatter")) face_color, edge_color = _check_colors(face_color, edge_color, color) item = Scatter(x, y, face_color=face_color, edge_color=edge_color, size=size, name=name, lw=lw, ls=ls, symbol=symbol) self._add_item(item) return item @write_docs def add_hist(self, data: Sequence[float], bins: int | Sequence | str = 10, range=None, density: bool = False, face_color = None, edge_color = None, color = None, name: str | None = None, lw: float = 1, ls: str = "-", ): """ Add histogram like ``plt.hist(data)``. Parameters ---------- data : array-like Data for histogram constrction. bins : int, sequence of float or str, default is 10 Bin numbers. See ``np.histogram`` for detail. range : two floats, optional Bin ranges. See ``np.histogram`` for detail. density : bool, default is False If true, plot the density instead of the counts. See ``np.histogram`` for detail. {face_color} {edge_color} {color} {name} {lw} {ls} Returns ------- Histogram A plot item of the histogram. """ name = self._find_unique_name((name or "Histogram")) face_color, edge_color = _check_colors(face_color, edge_color, color) item = Histogram(data, bins=bins, range=range, density=density, face_color=face_color, edge_color=edge_color, name=name, lw=lw, ls=ls) self._add_item(item) return item @overload def add_bar(self, x: Sequence[float], **kwargs): ... @overload def add_bar(self, x: Sequence[float], y: Sequence[float], **kwargs): ... @write_docs def add_bar(self, x=None, y=None, width: float = 0.6, face_color = None, edge_color = None, color = None, name: str | None = None, lw: float = 1, ls: str = "-"): """ Add a bar plot like ``plt.bar(x, y)``. Parameters ---------- {x} {y} width : float, default is 0.6 Width of each bar. {face_color} {edge_color} {color} {name} {lw} {ls} Returns ------- BarPlot A plot item of the bar plot. """ x, y = _check_xy(x, y) name = self._find_unique_name((name or "Bar")) face_color, edge_color = _check_colors(face_color, edge_color, color) item = BarPlot(x, y, width=width, face_color=face_color, edge_color=edge_color, name=name, lw=lw, ls=ls) self._add_item(item) return item @overload def add_fillbetween(self, x: Sequence[float], **kwargs): ... @overload def add_fillbetween(self, x: Sequence[float], y: Sequence[float], **kwargs): ... @write_docs def add_fillbetween(self, x=None, y1=None, y2=None, face_color = None, edge_color = None, color = None, name: str | None = None, lw: float = 1, ls: str = "-"): x, y1 = _check_xy(x, y1) name = self._find_unique_name((name or "FillBetween")) face_color, edge_color = _check_colors(face_color, edge_color, color) item = FillBetween(x, y1, y2, face_color=face_color, edge_color=edge_color, name=name, lw=lw, ls=ls) self._add_item(item) @overload def add_infline(self, slope: float, intercept: float, color = None, name: str | None = None, lw: float = 1, ls: str = "-"): ... @overload def add_infline(self, pos: tuple[float, float], degree: float, color = None, name: str | None = None, lw: float = 1, ls: str = "-"): ... def add_infline(self, *args, color = None, name: str | None = None, lw: float = 1, ls: str = "-", **kwargs): if kwargs: if args: raise TypeError("Cannot mix args and kwargs for infinite line parameters.") keys = set(kwargs.keys()) if keys <= {"pos", "angle"}: args = (kwargs.get("pos", (0, 0)), kwargs.get("angle", 0)) elif keys <= {"slope", "intercept"}: args = (kwargs.get("slope", (0, 0)), kwargs.get("intercept", 0)) else: raise ValueError(f"{kwargs} is invalid input.") nargs = len(args) if nargs == 1: arg0 = args[0] if np.isscalar(arg0): angle = np.rad2deg(np.arctan(arg0)) pos = (0, 0) else: pos = arg0 angle = 90 elif nargs == 2: arg0, arg1 = args if np.isscalar(arg0): angle = np.rad2deg(np.arctan(arg0)) pos = (0, arg1) else: pos = arg0 angle = arg1 else: raise TypeError( "Arguments of 'add_infline' should be either 'add_infline(slope, intercept)' " "or 'add_infline(pos, degree)'." ) item = InfLine(pos, angle, edge_color=color, name=name, lw=lw, ls=ls) self._add_item(item) @overload def add_text(self, x: float, y: float, text: str, **kwargs): ... @overload def add_text(self, x: Sequence[float], y: Sequence[float], text: Sequence[str], **kwargs): ... def add_text(self, x, y, text, color=None, name=None): if np.isscalar(x) and np.isscalar(y): x = [x] y = [y] text = [text] item = TextGroup(x, y, text, color, name) self._add_item(item) def _add_item(self, item: LayerItem): item.zorder = len(self._items) self._graphics.addItem(item.native) self._items.append(item) def _insert_item(self, pos: int, item: LayerItem): self._graphics.addItem(item.native) self._items.insert(pos, item) self._reorder() def _swap_items(self, pos0: int, pos1: int): item0 = self._items[pos0] item1 = self._items[pos1] self._items[pos0] = item1 self._items[pos1] = item0 self._reorder() def _move_item(self, source: int, destination: int): if source < destination: destination -= 1 item = self._items.pop(source) self._items.insert(destination, item) self._reorder() def _remove_item(self, item: LayerItem | int | str): if isinstance(item, LayerItem): i = self._items.index(item) elif isinstance(item, int): if item < 0: item += len(self._items) i = item elif isinstance(item, str): for i, each in enumerate(self._items): if each.name == item: break else: raise ValueError(f"No item named {item}") if i < 0: raise ValueError(f"Item {item} not found") item = self._items.pop(i) self._graphics.removeItem(item.native) def _reorder(self): for i, item in enumerate(self._items): item.zorder = i return None def _find_unique_name(self, prefix: str): existing_names = [item.name for item in self._items] name = prefix i = 0 while name in existing_names: name = f"{prefix}-{i}" i += 1 return name class HasViewBox(HasDataItems): def __init__(self, viewbox: pg.ViewBox): self._viewbox = viewbox self._items: list[LayerItem] = [] # prepare mouse event self.mouse_click_callbacks = [] # This ROI is not editable. Mouse click event will use it to determine # the origin of the coordinate system. self._coordinate_fiducial = pg.ROI((0, 0)) self._coordinate_fiducial.setVisible(False) self._viewbox.addItem(self._coordinate_fiducial, ignoreBounds=True) self._enabled = True def _mouse_clicked(self, e): # NOTE: Mouse click event needs a reference item to map coordinates. # Here plot items always have a linear region item as a default one, # we can use it as the referene. ev = MouseClickEvent(e, self._coordinate_fiducial) x, y = ev.pos() [xmin, xmax], [ymin, ymax] = self._viewbox.viewRange() if xmin <= x <= xmax and ymin <= y <= ymax: for callback in self.mouse_click_callbacks: callback(ev) @property def xlim(self): """Range limits of X-axis.""" (xmin, xmax), _ = self._viewbox.viewRange() return xmin, xmax @xlim.setter def xlim(self, value: tuple[float, float]): self._viewbox.setXRange(*value) @property def ylim(self): """Range limits of Y-axis.""" _, (ymin, ymax) = self._viewbox.viewRange() return ymin, ymax @ylim.setter def ylim(self, value: tuple[float, float]): self._viewbox.setYRange(*value) @property def enabled(self) -> bool: """Mouse interactivity""" return self._enabled @enabled.setter def enabled(self, value: bool): self._viewbox.setMouseEnabled(value, value) self._enabled = value interactive = enabled @property def background_color(self): rgba = self._viewbox.background.brush().color().getRgb() return np.array(rgba)/255 @background_color.setter def background_color(self, value): value = convert_color_code(value) self._viewbox.setBackgroundColor(pg.mkBrush(value).color()) def _update_scene(self): raise NotImplementedError() @property def border(self): return to_rgba(self._viewbox.border) @border.setter def border(self, value): value = convert_color_code(value) self._viewbox.setBorder(value) class SimpleViewBox(HasViewBox): def __init__(self): super().__init__(pg.ViewBox()) @property def _graphics(self): return self._viewbox class PlotItem(HasViewBox): """ A 1-D plot item that has similar API as napari Viewer. """ def __init__(self, viewbox: pg.ViewBox | None = None): if viewbox is None: viewbox = pg.ViewBox() self.pgitem = pg.PlotItem(viewBox=viewbox) super().__init__(self.pgitem.vb) # prepare region item self._region = Region() self._region.visible = False self.pgitem.addItem(self._region.native, ignoreBounds=True) # prepare legend item self._legend = Legend() self._legend.native.setParentItem(self._viewbox) self.pgitem.legend = self._legend.native # initialize private attributes self._xlabel = "" self._ylabel = "" @property def _graphics(self): return self.pgitem @property def region(self) -> Region: """Linear region item.""" return self._region @property def legend(self) -> Legend: """Legend item.""" return self._legend @property def xlabel(self): """Label of X-axis.""" return self._xlabel @xlabel.setter def xlabel(self, label: str) -> str: self.pgitem.setLabel(BOTTOM, label) self._xlabel = label @property def ylabel(self) -> str: """Label of Y-axis.""" return self._ylabel @ylabel.setter def ylabel(self, label: str): self.pgitem.setLabel(LEFT, label) self._ylabel = label @property def title(self) -> str: return self.pgitem.titleLabel.text @title.setter def title(self, value: str): value = str(value) self.pgitem.setTitle(value) def _update_scene(self): # Since plot item does not have graphics scene before being added to # a graphical layout, mouse event should be connected afterward. self.pgitem.scene().sigMouseClicked.connect(self._mouse_clicked) class ViewBoxExt(pg.ViewBox): def __init__(self, parent=None, border=None, lockAspect=False, enableMouse=True, invertY=False, enableMenu=True, name=None, invertX=False, defaultPadding=0.02): pg.ViewBox.__init__(**locals()) from pyqtgraph import icons self.button = pg.ButtonItem(icons.getGraphPixmap("ctrl"), 14, self) self.button.hide() def hoverEvent(self, ev): try: if ev.enter: self.button.show() if ev.exit: self.button.hide() except RuntimeError: pass class ImageItem(HasViewBox): def __init__(self, viewbox: pg.ViewBox | None = None, lock_contrast_limits: bool = False ): if viewbox is None: viewbox = ViewBoxExt(lockAspect=True, invertY=True) self._lock_contrast_limits = lock_contrast_limits super().__init__(viewbox) self._image_item = pg.ImageItem() tr = self._image_item.transform().translate(-0.5, -0.5) self._image_item.setTransform(tr) self._viewbox.addItem(self._image_item) # prepare text overlay self._text_overlay = TextItem(text="", color="gray") self._text_overlay.native.setParentItem(self._viewbox) # prepare scale bar self._scale_bar = ScaleBar() self._scale_bar.visible = False self._scale_bar.native.setParentItem(self._viewbox) self._scale_bar.native.anchor((1, 1), (1, 1), offset=(-20, -20)) # prepare title and labels self._title = TextItem(text="", color="white", anchor=(0.5, 1.1)) self._title.pos = [1, 0] self._viewbox.addItem(self._title.native) self._title.visible = False self._xlabel = TextItem(text="", color="white", anchor=(0.5, -0.1)) self._xlabel.pos = [1, 1] self._viewbox.addItem(self._xlabel.native) self._xlabel.visible = False self._ylabel = TextItem(text="", color="white", anchor=(0.5, 1.1), angle=90) self._ylabel.pos = [0, 1] self._viewbox.addItem(self._ylabel.native) self._ylabel.visible = False if isinstance(viewbox, ViewBoxExt): # prepare LUT histogram self._hist = pg.HistogramLUTItem(orientation="horizontal") self._hist.vb.setBackgroundColor([0, 0, 0, 0.2]) self._hist.setParentItem(self._viewbox) self._hist.setVisible(False) @viewbox.button.clicked.connect def _(e): visible = not self._hist.isVisible() self._hist.setVisible(visible) if visible: self._hist._updateView() width = min(160, self._viewbox.width()) self._hist.setFixedWidth(width) self._cmap = "gray" def _update_scene(self): # Since plot item does not have graphics scene before being added to # a graphical layout, mouse event should be connected afterward. self._image_item.scene().sigMouseClicked.connect(self._mouse_clicked) @property def text_overlay(self) -> TextItem: """Text overlay on the image.""" return self._text_overlay @property def title(self) -> str: return self._title.text @title.setter def title(self, value: str): self._title.text = value @property def xlabel(self) -> str: return self._xlabel.text @xlabel.setter def xlabel(self, value: str): self._xlabel.text = value @property def ylabel(self) -> str: return self._ylabel.text @xlabel.setter def ylabel(self, value: str): self._ylabel.text = value @property def scale_bar(self) -> ScaleBar: """Scale bar on the image.""" return self._scale_bar @property def lock_contrast_limits(self): return self._lock_contrast_limits @lock_contrast_limits.setter def lock_contrast_limits(self, value: bool): self._lock_contrast_limits = bool(value) @property def _graphics(self): return self._viewbox @property def image(self) -> np.ndarray | None: """Image data""" if self._image_item.image is None: return None else: return self._image_item.image.T @image.setter def image(self, image: np.ndarray): no_image = self._image_item.image is None if no_image: auto_levels = True else: auto_levels = not self._lock_contrast_limits clims = self.contrast_limits img = np.asarray(image) self._image_item.setImage(img.T, autoLevels=auto_levels) self._hist.setImageItem(self._image_item) self._hist._updateView() if no_image: self._viewbox.autoRange() if not auto_levels: self.contrast_limits = clims sy, sx = img.shape[-2:] self._title.pos = [sx/2, self._title.pos[1]] self._title.visible = True self._xlabel.pos = [sx/2, sy] self._xlabel.visible = True self._ylabel.pos = [0, sy/2] self._ylabel.visible = True @image.deleter def image(self): self._image_item.clear() self._title.visible = False self._xlabel.visible = False self._ylabel.visible = False @property def contrast_limits(self) -> list[float, float]: """Contrast limits of image""" return self._image_item.levels @contrast_limits.setter def contrast_limits(self, value: tuple[float, float]): self._hist.setLevels(*value) @property def cmap(self): """Color map""" return self._cmap @cmap.setter def cmap(self, value): if isinstance(value, str): _cmap = cmap.get(value, source="matplotlib") else: _cmap = value self._hist.gradient.setColorMap(_cmap) self._cmap = value class QtPlotCanvas(FreeWidget, PlotItem): """ A 1-D data viewer that have similar API as napari Viewer. """ def __init__(self, **kwargs): # prepare widget PlotItem.__init__(self) self.layoutwidget = pg.GraphicsLayoutWidget() self.layoutwidget.addItem(self.pgitem) self._update_scene() super().__init__(**kwargs) self.set_widget(self.layoutwidget) class QtImageCanvas(FreeWidget, ImageItem): def __init__(self, lock_contrast_limits: bool = False, **kwargs): # prepare widget ImageItem.__init__(self, lock_contrast_limits=lock_contrast_limits) self.layoutwidget = pg.GraphicsLayoutWidget() self.layoutwidget.addItem(self._viewbox) self._update_scene() super().__init__(**kwargs) self.set_widget(self.layoutwidget) class Qt2YPlotCanvas(FreeWidget): def __init__(self, **kwargs): self.layoutwidget = pg.GraphicsLayoutWidget() item_l = PlotItem() item_r = SimpleViewBox() self.layoutwidget.addItem(item_l.pgitem) item_l.pgitem.scene().addItem(item_r._viewbox) item_l.pgitem.getAxis("right").linkToView(item_r._viewbox) item_r._viewbox.setXLink(item_l.pgitem) item_l._update_scene() item_l.pgitem.showAxis("right") self._plot_items: tuple[PlotItem, SimpleViewBox] = (item_l, item_r) self.updateViews() item_l.pgitem.vb.sigResized.connect(self.updateViews) super().__init__(**kwargs) self.set_widget(self.layoutwidget) def __getitem__(self, k: int) -> PlotItem: return self._plot_items[k] def updateViews(self): item_l ,item_r = self._plot_items item_r._viewbox.setGeometry(item_l._viewbox.sceneBoundingRect()) item_r._viewbox.linkedViewChanged(item_l._viewbox, item_r._viewbox.XAxis) _C = TypeVar("_C", bound=HasViewBox) class _MultiPlot(FreeWidget, Generic[_C]): _base_item_class: type[_C] def __init__(self, nrows: int = 0, ncols: int = 0, sharex: bool = False, sharey: bool = False, **kwargs): """ Multi-axes ``pyqtgraph`` canvas widget. Can contain multiple objects of {cls}. Parameters ---------- nrows : int, default is 0 Initial rows of axes. ncols : int, default is 0 Initail columns of axes. sharex : bool, default is False If true, all the x-axes will be linked. sharey : bool, default is False If true, all the y-axes will be linked. """ self.layoutwidget = pg.GraphicsLayoutWidget() self._axes: list[_C] = [] self._sharex = sharex self._sharey = sharey super().__init__(**kwargs) self.set_widget(self.layoutwidget) if nrows * ncols > 0: for r in range(nrows): for c in range(ncols): self.addaxis(r, c) def __init_subclass__(cls) -> None: """Update doc.""" init = cls.__init__ init.__doc__ = init.__doc__.format( cls=cls._base_item_class.__name__ ) def addaxis(self, row: int | None = None, col: int | None = None, rowspan: int = 1, colspan: int = 1) -> _C: """Add a new axis to widget.""" item = self._base_item_class() self._axes.append(item) self.layoutwidget.addItem(item._graphics, row, col, rowspan, colspan) item._update_scene() if self._sharex and len(self._axes) > 1: item._viewbox.setXLink(self._axes[0]._viewbox) if self._sharey and len(self._axes) > 1: item._viewbox.setYLink(self._axes[0]._viewbox) return item def __getitem__(self, k: int) -> _C: return self._axes[k] def __delitem__(self, k: int): item = self._axes[k] self.layoutwidget.removeItem(item._graphics) def __iter__(self) -> Iterator[_C]: return iter(self._axes) class QtMultiPlotCanvas(_MultiPlot[PlotItem]): """A pyqtgraph-based canvas with multiple plot.""" _base_item_class = PlotItem class QtMultiImageCanvas(_MultiPlot[ImageItem]): """A pyqtgraph-based canvas with multiple images.""" _base_item_class = ImageItem def _check_xy(x, y): if y is None: if x is None: x = [] y = [] else: y = x x = np.arange(len(y)) return x, y def _check_colors(face_color, edge_color, color): if color is None: return face_color, edge_color else: if face_color is None and edge_color is None: return color, color else: raise ValueError("Cannot set 'color' and either 'face_color' or " "'edge_color' at the same time.")
[ "pyqtgraph.icons.getGraphPixmap", "pyqtgraph.colormap.get", "numpy.isscalar", "pyqtgraph.PlotItem", "pyqtgraph.ROI", "pyqtgraph.ImageItem", "numpy.asarray", "pyqtgraph.HistogramLUTItem", "pyqtgraph.mkBrush", "numpy.array", "numpy.arctan", "pyqtgraph.GraphicsLayoutWidget", "pyqtgraph.ViewBox"...
[((26167, 26198), 'typing.TypeVar', 'TypeVar', (['"""_C"""'], {'bound': 'HasViewBox'}), "('_C', bound=HasViewBox)\n", (26174, 26198), False, 'from typing import Generic, Iterator, Sequence, TypeVar, overload, MutableSequence\n'), ((13600, 13614), 'pyqtgraph.ROI', 'pg.ROI', (['(0, 0)'], {}), '((0, 0))\n', (13606, 13614), True, 'import pyqtgraph as pg\n'), ((16193, 16221), 'pyqtgraph.PlotItem', 'pg.PlotItem', ([], {'viewBox': 'viewbox'}), '(viewBox=viewbox)\n', (16204, 16221), True, 'import pyqtgraph as pg\n'), ((18979, 18993), 'pyqtgraph.ImageItem', 'pg.ImageItem', ([], {}), '()\n', (18991, 18993), True, 'import pyqtgraph as pg\n'), ((22787, 22804), 'numpy.asarray', 'np.asarray', (['image'], {}), '(image)\n', (22797, 22804), True, 'import numpy as np\n'), ((24420, 24445), 'pyqtgraph.GraphicsLayoutWidget', 'pg.GraphicsLayoutWidget', ([], {}), '()\n', (24443, 24445), True, 'import pyqtgraph as pg\n'), ((24854, 24879), 'pyqtgraph.GraphicsLayoutWidget', 'pg.GraphicsLayoutWidget', ([], {}), '()\n', (24877, 24879), True, 'import pyqtgraph as pg\n'), ((25143, 25168), 'pyqtgraph.GraphicsLayoutWidget', 'pg.GraphicsLayoutWidget', ([], {}), '()\n', (25166, 25168), True, 'import pyqtgraph as pg\n'), ((26984, 27009), 'pyqtgraph.GraphicsLayoutWidget', 'pg.GraphicsLayoutWidget', ([], {}), '()\n', (27007, 27009), True, 'import pyqtgraph as pg\n'), ((10152, 10169), 'numpy.isscalar', 'np.isscalar', (['arg0'], {}), '(arg0)\n', (10163, 10169), True, 'import numpy as np\n'), ((11193, 11207), 'numpy.isscalar', 'np.isscalar', (['x'], {}), '(x)\n', (11204, 11207), True, 'import numpy as np\n'), ((11212, 11226), 'numpy.isscalar', 'np.isscalar', (['y'], {}), '(y)\n', (11223, 11226), True, 'import numpy as np\n'), ((15256, 15270), 'numpy.array', 'np.array', (['rgba'], {}), '(rgba)\n', (15264, 15270), True, 'import numpy as np\n'), ((15844, 15856), 'pyqtgraph.ViewBox', 'pg.ViewBox', ([], {}), '()\n', (15854, 15856), True, 'import pyqtgraph as pg\n'), ((16145, 16157), 'pyqtgraph.ViewBox', 'pg.ViewBox', ([], {}), '()\n', (16155, 16157), True, 'import pyqtgraph as pg\n'), ((18304, 18332), 'pyqtgraph.icons.getGraphPixmap', 'icons.getGraphPixmap', (['"""ctrl"""'], {}), "('ctrl')\n", (18324, 18332), False, 'from pyqtgraph import icons\n'), ((20342, 20387), 'pyqtgraph.HistogramLUTItem', 'pg.HistogramLUTItem', ([], {'orientation': '"""horizontal"""'}), "(orientation='horizontal')\n", (20361, 20387), True, 'import pyqtgraph as pg\n'), ((24016, 24052), 'pyqtgraph.colormap.get', 'cmap.get', (['value'], {'source': '"""matplotlib"""'}), "(value, source='matplotlib')\n", (24024, 24052), True, 'from pyqtgraph import colormap as cmap\n'), ((10394, 10411), 'numpy.isscalar', 'np.isscalar', (['arg0'], {}), '(arg0)\n', (10405, 10411), True, 'import numpy as np\n'), ((10206, 10221), 'numpy.arctan', 'np.arctan', (['arg0'], {}), '(arg0)\n', (10215, 10221), True, 'import numpy as np\n'), ((15431, 15448), 'pyqtgraph.mkBrush', 'pg.mkBrush', (['value'], {}), '(value)\n', (15441, 15448), True, 'import pyqtgraph as pg\n'), ((10448, 10463), 'numpy.arctan', 'np.arctan', (['arg0'], {}), '(arg0)\n', (10457, 10463), True, 'import numpy as np\n')]
""" Name: coloredComponents Date: Jun 2019 Programmer: <NAME>, <NAME> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% If you use the 'NMF toolbox' please refer to: [1] <NAME>, <NAME>, <NAME>, and <NAME> NMF Toolbox: Music Processing Applications of Nonnegative Matrix Factorization In Proceedings of the International Conference on Digital Audio Effects (DAFx), 2019. License: This file is part of 'NMF toolbox'. https://www.audiolabs-erlangen.de/resources/MIR/NMFtoolbox/ 'NMF toolbox' is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 'NMF toolbox' is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with 'NMF toolbox'. If not, see http://www.gnu.org/licenses/. """ import numpy as np from matplotlib.colors import rgb_to_hsv, hsv_to_rgb, to_rgb import matplotlib.cm as cm from nmfTools.utils import EPS def coloredComponents(compA, colVec=None): """Maps a list containing parallel component spectrograms into a color-coded spectrogram image, similar to Fig. 10 in [1]. Works best for three components corresponding to RGB. References ---------- [2] <NAME> and <NAME> -- Reverse Engineering the Amen Break - Score-informed Separation and Restoration applied to Drum Recordings" IEEE/ACM Transactions on Audio, Speech, and Language Processing, 24(9): 1531-1543, 2016. Parameters ---------- compA: array-like List with the component spectrograms, all should have the same dimensions colVec: Returns ------- rgbA: array-like color-coded spectrogram """ numComp = len(compA) numBins, numFrames = compA[0].shape colorSlice = np.zeros((numBins, numFrames, 3)) if colVec: colVec = rgb_to_hsv(colVec) else: if numComp == 1: pass elif numComp == 2: colVec = [[1, 0, 0], [0, 1, 1]] elif numComp == 3: colVec = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] elif numComp == 4: colVec = [[1, 0, 0], [0.5, 1, 0], [0, 1, 1], [0.5, 0, 1]] else: colVec = [to_rgb(cm.hsv(i * 1 / numComp, 1)) for i in range(0, numComp)] rgbA = np.zeros((numBins, numFrames, 3)) for k in range(numComp): maxVal = compA[k].max() if maxVal < EPS: maxVal = 1.0 intensity = 1 - compA[k] / maxVal for g in range(3): colorSlice[:, :, g] = colVec[k][g] * intensity rgbA += colorSlice # convert to HSV space hsvA = rgb_to_hsv(rgbA) # invert luminance hsvA[:, :, 2] /= hsvA[:, :, 2].max(0).max(0) # shift hue circularly hsvA[:, :, 0] = np.mod((1/(numComp-1)) + hsvA[:, :, 0], 1) # convert to RGB space rgbA = hsv_to_rgb(hsvA) return rgbA
[ "matplotlib.colors.rgb_to_hsv", "matplotlib.cm.hsv", "numpy.zeros", "matplotlib.colors.hsv_to_rgb", "numpy.mod" ]
[((2195, 2228), 'numpy.zeros', 'np.zeros', (['(numBins, numFrames, 3)'], {}), '((numBins, numFrames, 3))\n', (2203, 2228), True, 'import numpy as np\n'), ((2696, 2729), 'numpy.zeros', 'np.zeros', (['(numBins, numFrames, 3)'], {}), '((numBins, numFrames, 3))\n', (2704, 2729), True, 'import numpy as np\n'), ((3040, 3056), 'matplotlib.colors.rgb_to_hsv', 'rgb_to_hsv', (['rgbA'], {}), '(rgbA)\n', (3050, 3056), False, 'from matplotlib.colors import rgb_to_hsv, hsv_to_rgb, to_rgb\n'), ((3178, 3222), 'numpy.mod', 'np.mod', (['(1 / (numComp - 1) + hsvA[:, :, 0])', '(1)'], {}), '(1 / (numComp - 1) + hsvA[:, :, 0], 1)\n', (3184, 3222), True, 'import numpy as np\n'), ((3260, 3276), 'matplotlib.colors.hsv_to_rgb', 'hsv_to_rgb', (['hsvA'], {}), '(hsvA)\n', (3270, 3276), False, 'from matplotlib.colors import rgb_to_hsv, hsv_to_rgb, to_rgb\n'), ((2262, 2280), 'matplotlib.colors.rgb_to_hsv', 'rgb_to_hsv', (['colVec'], {}), '(colVec)\n', (2272, 2280), False, 'from matplotlib.colors import rgb_to_hsv, hsv_to_rgb, to_rgb\n'), ((2628, 2654), 'matplotlib.cm.hsv', 'cm.hsv', (['(i * 1 / numComp)', '(1)'], {}), '(i * 1 / numComp, 1)\n', (2634, 2654), True, 'import matplotlib.cm as cm\n')]
# coding: utf-8 # # Mask R-CNN - Train on Shapes Dataset # # # This notebook shows how to train Mask R-CNN on your own dataset. To keep things simple we use a synthetic dataset of shapes (squares, triangles, and circles) which enables fast training. You'd still need a GPU, though, because the network backbone is a Resnet101, which would be too slow to train on a CPU. On a GPU, you can start to get okay-ish results in a few minutes, and good results in less than an hour. # # The code of the *Shapes* dataset is included below. It generates images on the fly, so it doesn't require downloading any data. And it can generate images of any size, so we pick a small image size to train faster. from IPython import get_ipython # get_ipython().run_line_magic('matplotlib', 'inline') # get_ipython().run_line_magic('load_ext', 'autoreload') # get_ipython().run_line_magic('autoreload', '2') import os import sys import random import math import re import time import numpy as np import cv2 import matplotlib import matplotlib.pyplot as plt # sys.path.append('../') from mrcnn.config import Config import mrcnn.model as modellib import mrcnn.visualize as visualize from mrcnn.model import log import mrcnn.shapes as shapes from mrcnn.dataset import Dataset # Root directory of the project ROOT_DIR = os.getcwd() MODEL_PATH = '../../Models' # Directory to save logs and trained model MODEL_DIR = os.path.join(MODEL_PATH, "mrcnn_logs") # Path to COCO trained weights COCO_MODEL_PATH = os.path.join(MODEL_PATH, "mask_rcnn_coco.h5") RESNET_MODEL_PATH = os.path.join(MODEL_PATH,"resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5") import tensorflow as tf import keras print("Tensorflow Version: {} Keras Version : {} ".format(tf.__version__,keras.__version__)) # ## Configurations config = shapes.ShapesConfig() config.display() # ## Notebook Preferences def get_ax(rows=1, cols=1, size=8): """Return a Matplotlib Axes array to be used in all visualizations in the notebook. Provide a central point to control graph sizes. Change the default size attribute to control the size of rendered images """ _, ax = plt.subplots(rows, cols, figsize=(size*cols, size*rows)) return ax # ## Dataset # # Create a synthetic dataset # # Extend the Dataset class and add a method to load the shapes dataset, `load_shapes()`, and override the following methods: # # * load_image() # * load_mask() # * image_reference() # Training dataset # generate 500 shapes dataset_train = shapes.ShapesDataset() dataset_train.load_shapes(500, config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1]) dataset_train.prepare() # Validation dataset dataset_val = shapes.ShapesDataset() dataset_val.load_shapes(50, config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1]) dataset_val.prepare() # In[29]: # Load and display random samples image_ids = np.random.choice(dataset_train.image_ids, 12) #for image_id in image_ids: # image = dataset_train.load_image(image_id) # mask, class_ids = dataset_train.load_mask(image_id) # visualize.display_top_masks(image, mask, class_ids, dataset_train.class_names) # ## Create Model # import importlib # importlib.reload(model) # Create model in training mode # MODEL_DIR = os.path.join(MODEL_PATH, "mrcnn_logs") model = modellib.MaskRCNN(mode="training", config=config, model_dir=MODEL_DIR) print(MODEL_PATH) print(COCO_MODEL_PATH) print(RESNET_MODEL_PATH) print(MODEL_DIR) print(model.find_last()) # Which weights to start with? init_with = "last" # imagenet, coco, or last if init_with == "imagenet": # loc=model.load_weights(model.get_imagenet_weights(), by_name=True) loc=model.load_weights(RESNET_MODEL_PATH, by_name=True) elif init_with == "coco": # Load weights trained on MS COCO, but skip layers that # are different due to the different number of classes # See README for instructions to download the COCO weights loc=model.load_weights(COCO_MODEL_PATH, by_name=True, exclude=["mrcnn_class_logits", "mrcnn_bbox_fc", "mrcnn_bbox", "mrcnn_mask"]) elif init_with == "last": # Load the last model you trained and continue training loc= model.load_weights(model.find_last()[1], by_name=True) # ## Training # # Train in two stages: # 1. Only the heads. Here we're freezing all the backbone layers and training only the randomly initialized layers (i.e. the ones that we didn't use pre-trained weights from MS COCO). To train only the head layers, pass `layers='heads'` to the `train()` function. # # 2. Fine-tune all layers. For this simple example it's not necessary, but we're including it to show the process. Simply pass `layers="all` to train all layers. # Train the head branches # Passing layers="heads" freezes all layers except the head # layers. You can also pass a regular expression to select # which layers to train by name pattern. model.train(dataset_train, dataset_val, learning_rate=config.LEARNING_RATE, epochs=1, layers='heads') # Fine tune all layers # Passing layers="all" trains all layers. You can also # pass a regular expression to select which layers to # train by name pattern. model.train(dataset_train, dataset_val, learning_rate=config.LEARNING_RATE / 10, epochs=2, layers="all") # Save weights # Typically not needed because callbacks save after every epoch # Uncomment to save manually model_path = os.path.join(MODEL_DIR, "mask_rcnn_shapes.h5") model.keras_model.save_weights(model_path) # ## Detection # class InferenceConfig(ShapesConfig): # GPU_COUNT = 1 # IMAGES_PER_GPU = 1 # inference_config = InferenceConfig() # Recreate the model in inference mode # model = modellib.MaskRCNN(mode="inference", # config=inference_config, # model_dir=MODEL_DIR) # Get path to saved weights # Either set a specific path or find last trained weights # model_path = os.path.join(ROOT_DIR, ".h5 file name here") # model_path = model.find_last()[1] # Load trained weights (fill in path to trained weights here) # assert model_path != "", "Provide path to trained weights" # print("Loading weights from ", model_path) # model.load_weights(model_path, by_name=True) # Test on a random image # image_id = random.choice(dataset_val.image_ids) # original_image, image_meta, gt_class_id, gt_bbox, gt_mask = \ # modellib.load_image_gt(dataset_val, inference_config, image_id, use_mini_mask=False) # log("original_image", original_image) # log("image_meta", image_meta) # log("gt_class_id", gt_bbox) # log("gt_bbox", gt_bbox) # log("gt_mask", gt_mask) # visualize.display_instances(original_image, gt_bbox, gt_mask, gt_class_id, # dataset_train.class_names, figsize=(8, 8)) # results = model.detect([original_image], verbose=1) # r = results[0] # visualize.display_instances(original_image, r['rois'], r['masks'], r['class_ids'], # dataset_val.class_names, r['scores'], ax=get_ax()) # ## Evaluation # Compute VOC-Style mAP @ IoU=0.5 # Running on 10 images. Increase for better accuracy. # image_ids = np.random.choice(dataset_val.image_ids, 10) # APs = [] # for image_id in image_ids: # Load image and ground truth data # image, image_meta, gt_class_id, gt_bbox, gt_mask = modellib.load_image_gt(dataset_val, inference_config, # image_id, use_mini_mask=False) # molded_images = np.expand_dims(modellib.mold_image(image, inference_config), 0) # Run object detection # results = model.detect([image], verbose=0) # r = results[0] # Compute AP # AP, precisions, recalls, overlaps = utils.compute_ap(gt_bbox, gt_class_id, # r["rois"], r["class_ids"], r["scores"]) # APs.append(AP) # print("mAP: ", np.mean(APs))
[ "mrcnn.model.MaskRCNN", "numpy.random.choice", "os.path.join", "os.getcwd", "mrcnn.shapes.ShapesDataset", "mrcnn.shapes.ShapesConfig", "matplotlib.pyplot.subplots" ]
[((1305, 1316), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1314, 1316), False, 'import os\n'), ((1400, 1438), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""mrcnn_logs"""'], {}), "(MODEL_PATH, 'mrcnn_logs')\n", (1412, 1438), False, 'import os\n'), ((1489, 1534), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""mask_rcnn_coco.h5"""'], {}), "(MODEL_PATH, 'mask_rcnn_coco.h5')\n", (1501, 1534), False, 'import os\n'), ((1555, 1640), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5"""'], {}), "(MODEL_PATH, 'resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'\n )\n", (1567, 1640), False, 'import os\n'), ((1799, 1820), 'mrcnn.shapes.ShapesConfig', 'shapes.ShapesConfig', ([], {}), '()\n', (1818, 1820), True, 'import mrcnn.shapes as shapes\n'), ((2516, 2538), 'mrcnn.shapes.ShapesDataset', 'shapes.ShapesDataset', ([], {}), '()\n', (2536, 2538), True, 'import mrcnn.shapes as shapes\n'), ((2676, 2698), 'mrcnn.shapes.ShapesDataset', 'shapes.ShapesDataset', ([], {}), '()\n', (2696, 2698), True, 'import mrcnn.shapes as shapes\n'), ((2855, 2900), 'numpy.random.choice', 'np.random.choice', (['dataset_train.image_ids', '(12)'], {}), '(dataset_train.image_ids, 12)\n', (2871, 2900), True, 'import numpy as np\n'), ((3276, 3346), 'mrcnn.model.MaskRCNN', 'modellib.MaskRCNN', ([], {'mode': '"""training"""', 'config': 'config', 'model_dir': 'MODEL_DIR'}), "(mode='training', config=config, model_dir=MODEL_DIR)\n", (3293, 3346), True, 'import mrcnn.model as modellib\n'), ((5497, 5543), 'os.path.join', 'os.path.join', (['MODEL_DIR', '"""mask_rcnn_shapes.h5"""'], {}), "(MODEL_DIR, 'mask_rcnn_shapes.h5')\n", (5509, 5543), False, 'import os\n'), ((2153, 2213), 'matplotlib.pyplot.subplots', 'plt.subplots', (['rows', 'cols'], {'figsize': '(size * cols, size * rows)'}), '(rows, cols, figsize=(size * cols, size * rows))\n', (2165, 2213), True, 'import matplotlib.pyplot as plt\n')]
import pandas as pd import numpy as np from pandas.api.types import is_numeric_dtype from datetime import date, datetime import calendar def add_datetime_features(df, datetime_columns: list, add_time_features=False, scale_0_to_1=True, cos_sin_transform=True, return_new_cols=True) -> pd.DataFrame: """ Create common date and time features out of given datetime-columns. Optional to scale between 0 and 1. """ new_cols = [] if cos_sin_transform: scale_0_to_1 = True # loop through all columns for col in datetime_columns: # make sure column has a datetime- df[col] = pd.to_datetime(df[col]) df[f'ft_{col}_year'] = df[col].dt.year df[f'ft_{col}_month'] = df[col].dt.month df[f'ft_{col}_week'] = df[col].dt.week df[f'ft_{col}_day'] = df[col].dt.day df[f'ft_{col}_dayofweek'] = df[col].dt.dayofweek df[f'ft_{col}_dayofyear'] = df[col].dt.dayofyear df[f'ft_{col}_daysinmonth'] = df[col].dt.daysinmonth # new_cols.extend([f'ft_{col}_year', f'ft_{col}_month', f'ft_{col}_week', # f'ft_{col}_day', f'ft_{col}_dayofweek', # f'ft_{col}_dayofyear', f'ft_{col}_daysinmonth']) if add_time_features: df[f'ft_{col}_hour'] = df[col].dt.hour df[f'ft_{col}_min'] = df[col].dt.minute df[f'ft_{col}_sec'] = df[col].dt.second if scale_0_to_1: max_year = df[f'ft_{col}_year'].max() min_year = df[f'ft_{col}_year'].min() df[f'ft_{col}_year'] = (df[f'ft_{col}_year'] - min_year) / (max_year - min_year) df[f'ft_{col}_month'] = df[f'ft_{col}_month'] / 12 df[f'ft_{col}_week'] = df[f'ft_{col}_week'] / 52 df[f'ft_{col}_dayofweek'] = df[f'ft_{col}_dayofweek'] / 7 df[f'ft_{col}_day'] = df[f'ft_{col}_day'] / df[f'ft_{col}_daysinmonth'] df[f'ft_{col}_dayofyear'] = df[f'ft_{col}_dayofyear'] / 366 df[f'ft_{col}_daysinmonth'] = df[f'ft_{col}_daysinmonth'] / 31 if add_time_features: df[f'ft_{col}_hour'] = df[f'ft_{col}_hour'] / 24 df[f'ft_{col}_min'] = df[f'ft_{col}_min'] / 60 df[f'ft_{col}_sec'] = df[f'ft_{col}_sec'] / 60 if cos_sin_transform: for seasonal_part in ['month', 'week', 'dayofweek']: df[f'ft_{col}_{seasonal_part}_cos'] = np.round(np.cos(df[f'ft_{col}_{seasonal_part}'] * 2 * np.pi), 4) df[f'ft_{col}_{seasonal_part}_sin'] = np.round(np.sin(df[f'ft_{col}_{seasonal_part}'] * 2 * np.pi), 4) if add_time_features: for seasonal_part in ['hour', 'min', 'sec']: df[f'ft_{col}_{seasonal_part}_cos'] = np.round(np.cos(df[f'ft_{col}_{seasonal_part}'] * 2 * np.pi), 4) df[f'ft_{col}_{seasonal_part}_sin'] = np.round(np.sin(df[f'ft_{col}_{seasonal_part}'] * 2 * np.pi), 4) new_cols = [col for col in df.columns if col.find(f'ft_{col}_')==0] if return_new_cols: return df, new_cols else: return df
[ "numpy.sin", "numpy.cos", "pandas.to_datetime" ]
[((670, 693), 'pandas.to_datetime', 'pd.to_datetime', (['df[col]'], {}), '(df[col])\n', (684, 693), True, 'import pandas as pd\n'), ((2722, 2773), 'numpy.cos', 'np.cos', (["(df[f'ft_{col}_{seasonal_part}'] * 2 * np.pi)"], {}), "(df[f'ft_{col}_{seasonal_part}'] * 2 * np.pi)\n", (2728, 2773), True, 'import numpy as np\n'), ((2847, 2898), 'numpy.sin', 'np.sin', (["(df[f'ft_{col}_{seasonal_part}'] * 2 * np.pi)"], {}), "(df[f'ft_{col}_{seasonal_part}'] * 2 * np.pi)\n", (2853, 2898), True, 'import numpy as np\n'), ((3083, 3134), 'numpy.cos', 'np.cos', (["(df[f'ft_{col}_{seasonal_part}'] * 2 * np.pi)"], {}), "(df[f'ft_{col}_{seasonal_part}'] * 2 * np.pi)\n", (3089, 3134), True, 'import numpy as np\n'), ((3212, 3263), 'numpy.sin', 'np.sin', (["(df[f'ft_{col}_{seasonal_part}'] * 2 * np.pi)"], {}), "(df[f'ft_{col}_{seasonal_part}'] * 2 * np.pi)\n", (3218, 3263), True, 'import numpy as np\n')]
"""tests the NastranIO class""" import os from copy import deepcopy import unittest import numpy as np try: import matplotlib matplotlib.use('Agg') IS_MATPLOTLIB = True except ModuleNotFoundError: # pyparsing is missing IS_MATPLOTLIB = False #except ImportError: #pass import vtk from cpylog import SimpleLogger import pyNastran from pyNastran.bdf.bdf import BDF from pyNastran.bdf.cards.test.test_aero import get_zona_model from pyNastran.bdf.errors import DuplicateIDsError from pyNastran.gui.testing_methods import FakeGUIMethods from pyNastran.converters.nastran.gui.nastran_io import NastranIO from pyNastran.converters.nastran.nastran_to_vtk import nastran_to_vtk RED = (1., 0., 0.) class NastranGUI(NastranIO, FakeGUIMethods): def __init__(self, inputs=None): FakeGUIMethods.__init__(self, inputs=inputs) NastranIO.__init__(self) self.build_fmts(['nastran'], stop_on_failure=True) PKG_PATH = pyNastran.__path__[0] STL_PATH = os.path.join(PKG_PATH, 'converters', 'stl') MODEL_PATH = os.path.join(PKG_PATH, '..', 'models') class TestNastranGUI(unittest.TestCase): def test_settings(self): from qtpy import QtCore settings = QtCore.QSettings() test = NastranGUI() is_loaded = test.settings.load(settings) assert is_loaded is True test.settings.save(settings, is_testing=True) is_loaded = test.settings.load(settings) assert is_loaded is True test.settings.set_annotation_size_color(size=10, color=None) #test.settings.set_annotation_size_color(size=10, color=RED) test.settings.set_coord_scale(2.0, render=True) test.settings.set_coord_text_scale(10, render=True) test.settings.update_coord_scale(coord_scale=None, render=True) test.settings.set_background_color_to_white(render=True) color = RED opacity = 0.4 test.settings.set_background_color(color, render=True) test.settings.set_background_color2(color, render=True) test.settings.set_highlight_color(color) test.settings.set_highlight_opacity(opacity) test.settings.set_text_color(color, render=True) test.settings.set_text_size(10) test.settings.set_magnify(magnify=4) #self.settings.s def test_solid_shell_bar_obj(self): bdf_filename = os.path.join(MODEL_PATH, 'sol_101_elements', 'static_solid_shell_bar.bdf') obj_filename = os.path.join(MODEL_PATH, 'sol_101_elements', 'static_solid_shell_bar.obj') model = BDF() model.read_bdf(bdf_filename) model.save(obj_filename, unxref=True) test = NastranGUI() test.load_nastran_geometry(obj_filename) @unittest.skipIf(IS_MATPLOTLIB is False, 'No matplotlib') def test_solid_shell_bar_01(self): bdf_filename = os.path.join(MODEL_PATH, 'sol_101_elements', 'static_solid_shell_bar.bdf') op2_filename = os.path.join(MODEL_PATH, 'sol_101_elements', 'static_solid_shell_bar.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) test.cycle_results() test.on_rcycle_results() #print('test.result_cases', test.result_cases) #gpforce = test.model.grid_point_forces[1] icase_gpforce = None for icase, (case, dummy) in test.result_cases.items(): if hasattr(case, 'gpforce_array'): icase_gpforce = icase break else: raise RuntimeError('missing gpforce') case, (unused_i, unused_name) = test.result_cases[icase_gpforce] str(case) gpforce = case.gpforce_array model_name = 'main' p1 = [0., 0., 0.] p3 = [1., 0., 0.] p2 = [0., 1., 0.] zaxis = [0., 0., 1.] force_sum, moment_sum = test.shear_moment_torque_obj.plot_shear_moment_torque( model_name, gpforce, p1, p2, p3, zaxis, method='Z-Axis Projection', cid_p1=0, cid_p2=0, cid_p3=0, cid_zaxis=0, nplanes=5, plane_color=None, plane_opacity=0.5, csv_filename=None, show=False, stop_on_failure=True) assert np.allclose(np.abs(force_sum).max(), 0.000732421875), np.abs(force_sum).max() assert np.allclose(np.abs(moment_sum).max(), 0.000244140625), np.abs(moment_sum).max() p1 = np.array([0., 0., 0.]) # origin p2 = np.array([1., 0., 0.]) # xaxis p3 = np.array([1., 0., 0.]) # end zaxis = np.array([0., 0., 1.]) #idir = 0 test.shear_moment_torque_obj.plot_shear_moment_torque( model_name, gpforce, p1, p2, p3, zaxis, method='Z-Axis Projection', cid_p1=0, cid_p2=0, cid_p3=0, cid_zaxis=0, nplanes=5, plane_color=None, plane_opacity=0.5, csv_filename=None, show=False, stop_on_failure=True) with self.assertRaises(TypeError): # we need to set the case to a grid point force result test.cutting_plane_obj.make_cutting_plane( model_name, p1, p2, zaxis, method='Z-Axis Projection', cid_p1=0, cid_p2=0, cid_zaxis=0, ytol=1., plane_atol=1e-5, plane_color=None, plane_opacity=0.5, csv_filename=None, show=False, stop_on_failure=True) # setting the case to a grid point force result test.icase_fringe = icase_gpforce test._cycle_results(icase_gpforce) test.cutting_plane_obj.make_cutting_plane( model_name, p1, p2, zaxis, method='Z-Axis Projection', cid_p1=0, cid_p2=0, cid_zaxis=0, ytol=1., plane_atol=1e-5, plane_color=None, plane_opacity=0.5, csv_filename=None, show=False, stop_on_failure=True) test.icase_fringe = 0 #with self.assertRaises(RuntimeError): test.cutting_plane_obj.make_cutting_plane( model_name, p1, p2, zaxis, method='Z-Axis Projection', cid_p1=0, cid_p2=0, cid_zaxis=0, ytol=1., plane_atol=1e-5, plane_color=None, plane_opacity=0.5, csv_filename=None, show=False, stop_on_failure=True) def test_solid_shell_bar_02(self): bdf_filename = os.path.join(MODEL_PATH, 'sol_101_elements', 'mode_solid_shell_bar.bdf') op2_filename = os.path.join(MODEL_PATH, 'sol_101_elements', 'mode_solid_shell_bar.op2') test = NastranGUI() test.legend_obj.set_legend_menu() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) assert len(test.models['main'].elements) > 0 test.on_rcycle_results() test.on_update_legend( title='Title', min_value=0., max_value=1., scale=0.0, phase=0.0, arrow_scale=1., data_format='%.0f', is_low_to_high=True, is_discrete=True, is_horizontal=True, nlabels=None, labelsize=None, ncolors=None, colormap=None, is_shown=True, render=True) test.on_update_legend( title='Title', min_value=0., max_value=1., scale=0.0, phase=0.0, arrow_scale=1., data_format='%.0f', is_low_to_high=True, is_discrete=True, is_horizontal=False, nlabels=None, labelsize=None, ncolors=None, colormap='viridis', is_shown=True, render=True) test.legend_obj.set_legend_menu() test.on_set_camera_data( {'distance': 15.23729238729831, 'prallel_proj': None, 'view_angle': 30.0, 'parallel_scale': 3.9437014656284517, 'position': (-8.279127062822164, 4.306812025814127, 11.191236382055052), 'view_up': (0.14388395111701072, 0.9587296714789404, -0.245224031523912), 'clip_range': (7.44295814719721, 25.085506595796954), 'focal_point': (0.49249999999999994, 0.0, -0.5)} ) test.settings.reset_settings() test.on_set_font_size(8) test.on_increase_font_size() test.on_decrease_font_size() labels_list = [] text = 'text' x, y, z = 0., 0., 0. labels_list.append(test.create_annotation(text, x, y, z)) cell_id = 1 world_position = [0., 0., 1.] res_name, result_values, xyz = test.get_result_by_cell_id( cell_id, world_position, icase=0) assert res_name == 'NodeID', 'res_name=%r' % res_name assert result_values == 2, 'result_values=%r' % result_values assert isinstance(xyz, list), xyz #node_xyz = None cell_id = 5 #out = test.mark_actions.get_result_by_xyz_cell_id(node_xyz, cell_id) #result_name, result_values, node_id, xyz = out eids = [1, 2] icase_result = 2 icase_to_apply = 3 test.label_actors[2] = [] test.label_actors[3] = [] test.mark_actions.mark_elements_by_different_case( eids, icase_result, icase_to_apply, stop_on_failure=True, ) #eids = [1, 2] with self.assertRaises(NotImplementedError): test.mark_actions.highlight_elements(eids, model_name='main') nids = [1, 2] icase = 1 test.label_actors[1] = [] text = 'cat' test.mark_actions.mark_nodes(nids, icase, text) with self.assertRaises(RuntimeError): # icase_to_apply=166 doesn't exist test.mark_elements(eids, stop_on_failure=True, show_command=True) #test.mark_elements_by_case(eids, stop_on_failure=True, show_command=True) test.icase = 2 # PropertyID test.mark_elements(eids, stop_on_failure=True, show_command=True) test.mark_elements_by_case(eids, stop_on_failure=True, show_command=True) #for key, obj in test.result_cases.items(): #print(key) #print(obj) # fail mapping strain energy because we're on NodeID test.icase = 0 # NodeID test.icase_fringe = 0 # NodeID is_passed = test.map_element_centroid_to_node_fringe_result(update_limits=True, show_msg=True) obj, (itime, name) = test.result_cases[test.icase] str(obj) assert is_passed == False, f'map_element_centroid_to_node_fringe_result should fail for NodeID\n{obj}' # map strain energy keys = list(test.result_cases.keys()) assert len(keys) == 689, len(keys) icase = keys[-1] obj, (itime, name) = test.result_cases[icase] test.icase_fringe = icase str(obj) title = obj.get_title(itime, name) assert title == 'Strain Energy Density', str(obj) is_passed = test.map_element_centroid_to_node_fringe_result(update_limits=True, show_msg=False) assert is_passed == True, 'map_element_centroid_to_node_fringe_result failed' def test_solid_shell_bar_02b(self): bdf_filename = os.path.join(MODEL_PATH, 'sol_101_elements', 'mode_solid_shell_bar.bdf') test = NastranGUI() test.on_load_geometry(infile_name=bdf_filename, geometry_format='nastran', name='main', plot=True, raise_error=True) def test_solid_shell_bar_03(self): bdf_filename = os.path.join(MODEL_PATH, 'sol_101_elements', 'buckling_solid_shell_bar.bdf') op2_filename = os.path.join(MODEL_PATH, 'sol_101_elements', 'buckling_solid_shell_bar.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) def test_solid_bending(self): bdf_filename = os.path.join(MODEL_PATH, 'solid_bending', 'solid_bending.bdf') #op2_filename = os.path.join(MODEL_PATH, 'solid_bending', 'solid_bending_ogs.op2') deflection_filename1 = os.path.join(MODEL_PATH, 'solid_bending', 'solid_bending_multi_deflection_node.txt') deflection_filename2 = os.path.join(MODEL_PATH, 'solid_bending', 'solid_bending_multi_deflection_node_short.txt') test = NastranGUI() test.load_nastran_geometry(bdf_filename) #test.load_nastran_results(op2_filename) nresult_cases = len(test.result_cases) icase = max(test.result_cases) # these are the two cases we're checking were added test.on_load_custom_results(out_filename=deflection_filename1, restype='Deflection') test.on_load_custom_results(out_filename=deflection_filename1, restype='Force') dresult_cases = len(test.result_cases) - nresult_cases icase_final = max(test.result_cases) dcase = icase_final - icase assert dresult_cases == 2, dresult_cases assert dcase == 2, dcase assert (icase_final - 1) in test.label_actors assert icase_final in test.label_actors assert len(test.label_actors[icase_final]) == 0 nids = [1, 2, 3, 5] icase = icase_final text = 'word' test.mark_nodes(nids, icase, text) assert len(test.label_actors[icase_final]) == 4, len(test.label_actors[icase_final]) # test nodal results #'node', 'element', 'deflection', 'force', 'patran_nod', csv_filename1 = os.path.join(MODEL_PATH, 'solid_bending', 'solid_bending_multi_node.csv') csv_filename2 = os.path.join(MODEL_PATH, 'solid_bending', 'solid_bending_multi_node_extra.txt') csv_filename3 = os.path.join(MODEL_PATH, 'solid_bending', 'solid_bending_multi_node_short.txt') # missing/extra nodes test.on_load_custom_results(out_filename=csv_filename1, restype='node', stop_on_failure=True) test.on_load_custom_results(out_filename=csv_filename2, restype='node', stop_on_failure=True) test.on_load_custom_results(out_filename=csv_filename3, restype='node', stop_on_failure=True) # missing nodes test.on_load_custom_results(out_filename=deflection_filename2, restype='Deflection') def test_beam_modes_01(self): """CBAR/CBEAM - PARAM,POST,-1""" bdf_filename = os.path.join(MODEL_PATH, 'beam_modes', 'beam_modes.dat') op2_filename = os.path.join(MODEL_PATH, 'beam_modes', 'beam_modes_m1.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) def test_beam_modes_02(self): """CBAR/CBEAM - PARAM,POST,-2""" bdf_filename = os.path.join(MODEL_PATH, 'beam_modes', 'beam_modes.dat') op2_filename = os.path.join(MODEL_PATH, 'beam_modes', 'beam_modes_m2.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) def test_beam_modes_03(self): dirname = os.path.join(MODEL_PATH, 'beam_modes') bdf_filename = os.path.join(dirname, 'beam_modes.dat') op2_filename = os.path.join(dirname, 'beam_modes_m1.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) #test.load_nastran_results(op2_filename) test.load_nastran_geometry(bdf_filename) #test.load_nastran_results(op2_filename) test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) def test_beam_modes_04(self): dirname = os.path.join(MODEL_PATH, 'beam_modes') bdf_filename = os.path.join(dirname, 'beam_modes.dat') op2_filename = os.path.join(dirname, 'beam_modes_m2.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) test.load_nastran_geometry(bdf_filename) #@unittest.expectedFailure #def test_contact(self): #"""this test fails because of a misparsed card""" #bdf_filename = os.path.join(MODEL_PATH, 'contact', 'contact.bdf') #op2_filename = os.path.join(MODEL_PATH, 'contact', 'contact.op2') #test = NastranGUI() #test.load_nastran_geometry(bdf_filename) #test.load_nastran_results(op2_filename) def test_fsi(self): """tests -1 coordinate systems (flag for a fluid contact face)""" bdf_filename = os.path.join(MODEL_PATH, 'fsi', 'fsi.bdf') op2_filename = os.path.join(MODEL_PATH, 'fsi', 'fsi.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) def test_thermal_01(self): """runs models/thermal/thermal_test_153""" dirname = os.path.join(MODEL_PATH, 'thermal') bdf_filename = os.path.join(dirname, 'thermal_test_153.bdf') op2_filename = os.path.join(dirname, 'thermal_test_153.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) def test_bwb_gui(self): bdf_filename = os.path.join(MODEL_PATH, 'bwb', 'bwb_saero.bdf') test = NastranGUI() #test.log = get_logger2() test.load_nastran_geometry(bdf_filename) test.group_actions.create_groups_by_property_id() test.group_actions.create_groups_by_visible_result(nlimit=50) test.toggle_conms() def test_femap_rougv1_01(self): """tests the exhaust manifold and it's funny eigenvectors""" dirname = os.path.join(MODEL_PATH, 'femap_exhaust') #bdf_filename = os.path.join(dirname, 'modal_example.bdf') op2_filename = os.path.join(dirname, 'modal_example.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) def test_aero_op2(self): """tests the freedlm model (OP2 with aero)""" #bdf_filename = os.path.join(MODEL_PATH, 'aero', 'freedlm', 'freedlm.bdf') op2_filename = os.path.join(MODEL_PATH, 'aero', 'freedlm', 'freedlm.op2') test = NastranGUI() #test.log.level = 'debug' #test.load_nastran_geometry(bdf_filename) test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) assert len(test.result_cases) == 218, len(test.result_cases) #print(test.result_cases) def test_aero(self): """tests the bah_plane""" bdf_filename = os.path.join(MODEL_PATH, 'aero', 'bah_plane', 'bah_plane.bdf') op2_filename = os.path.join(MODEL_PATH, 'aero', 'bah_plane', 'bah_plane.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) out_datai = deepcopy(test.geometry_properties) test.on_update_geometry_properties_override_dialog(out_datai) out_data = { 'clicked_ok' : True, 'Global XYZ' : out_datai['Global XYZ'], 'conm2' : out_datai['conm2'], 'bar_z' : out_datai['bar_z'], 'caero' : out_datai['caero'], } #print(test.geometry_properties) coord = out_data['Global XYZ'] coord.is_visible = False str(coord) #print('coord = %r' % coord) conm2 = out_data['conm2'] conm2.point_size = 10 barz = out_data['bar_z'] barz.bar_scale = 0.5 barz.is_visible = True #print(barz) caero = test.geometry_properties['caero'] str(caero) caero.color = (255, 0, 0) caero.line_width = 10 caero.opacity = 0.8 caero.is_visible = False #print(caero) #print(out_data) test.on_update_geometry_properties(out_data, name='caero', write_log=True) def test_gui_elements_01(self): """tests forces/pressure in SOL 101""" bdf_filename = os.path.join(MODEL_PATH, 'elements', 'static_elements.bdf') op2_filename = os.path.join(MODEL_PATH, 'elements', 'static_elements.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) idisp = None iforce_xyz = None for key, case_data in test.result_cases.items(): case, data = case_data #print(key, case) if idisp is None and case.uname == 'Displacement': idisp = key elif idisp is not None and iforce_xyz is None and case.uname == 'LoadVectors': iforce_xyz = key break elif key > 70: break ifringe = len(test.result_cases) - 1 # Strain Energy Density test.on_fringe(icase=ifringe, stop_on_failure=True) with self.assertRaises(ValueError): test.on_vector(icase=ifringe, stop_on_failure=True) with self.assertRaises(ValueError): test.on_disp(icase=ifringe, stop_on_failure=True) # disp test.on_fringe(icase=iforce_xyz, stop_on_failure=True) test.on_vector(icase=iforce_xyz, stop_on_failure=True) test.on_disp(icase=idisp, stop_on_failure=True) # disp test.on_clear_results() test.on_fringe(icase=iforce_xyz, stop_on_failure=True) test.on_vector(icase=iforce_xyz, stop_on_failure=True) # force_xyz test.on_disp(icase=idisp, stop_on_failure=True) # disp test.on_fringe(icase=37, update_legend_window=True, show_msg=True) # normal #op2_filename = os.path.join(MODEL_PATH, 'elements', 'static_elements.op2') vtk_filename = os.path.join(MODEL_PATH, 'elements', 'static_elements.vtu') nastran_to_vtk(op2_filename, vtk_filename) assert os.path.exists(vtk_filename), vtk_filename def test_gui_elements_01b(self): bdf_filename = os.path.join(MODEL_PATH, 'elements', 'static_elements.bdf') op2_filename = os.path.join(MODEL_PATH, 'elements', 'static_elements.op2') #model = read_bdf(bdf_filename) model = BDF() model.disable_cards(['CHEXA', 'CTETRA', 'CPENTA', 'CROD', 'PLOTEL', 'CBAR', 'CBEAM', 'CTRIA3', 'CQUAD4', 'CQUADR', 'CTRIAR', 'CQUAD8', 'CTRIA6', 'CSHEAR', 'CTUBE', 'CONM2', 'CVISC', #'CONROD', 'CELAS1', 'CELAS2', 'CELAS3', 'CELAS4', 'CDAMP1', 'CDAMP2', 'CDAMP3', 'CDAMP4', 'PLOAD1', 'PLOAD2', 'PLOAD4', ]) model.read_bdf(bdf_filename) #print(model.elements) test2 = NastranGUI() test2.load_nastran_geometry(model) test2.load_nastran_results(op2_filename) def test_gui_elements_02(self): """tests a large number of elements and results in SOL 101""" #bdf_filename = os.path.join(MODEL_PATH, 'elements', 'static_elements.bdf') op2_filename = os.path.join(MODEL_PATH, 'elements', 'static_elements.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) #test = NastranGUI() test.settings.nastran_create_coords = False test.settings.nastran_is_bar_axes = False test.settings.nastran_is_3d_bars = False test.settings.nastran_is_3d_bars_update = False test.settings.nastran_is_element_quality = False test.settings.nastran_is_properties = False test.load_nastran_geometry(op2_filename) def test_gui_elements_03(self): """tests a large number of elements and results in SOL 103-modes""" #bdf_filename = os.path.join(MODEL_PATH, 'elements', 'modes_elements.bdf') op2_filename = os.path.join(MODEL_PATH, 'elements', 'modes_elements.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) #test.create_groups_by_property_id() test.create_groups_by_visible_result() def test_gui_elements_04(self): """tests a large number of elements and results in SOL 108-freq""" #bdf_filename = os.path.join(MODEL_PATH, 'elements', 'freq_elements.bdf') op2_filename = os.path.join(MODEL_PATH, 'elements', 'freq_elements.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) icase = 33 name = 'Normal' subcase_id = -1 test.set_normal_result(icase, name, subcase_id) test.setup_fake_text_actors() icase = 0 icase2 = icase + 1 while icase2 < len(test.result_cases): #test.on_cycle_results(case=icase2, show_msg=True) unused_result_name = 'dummy' test._set_case(unused_result_name, icase2, explicit=False, cycle=False, skip_click_check=False, min_value=None, max_value=None, is_legend_shown=None, show_msg=True) icase2 += 1 def test_gui_elements_05(self): """tests a large number of elements and results in SOL 108-freq""" #bdf_filename = os.path.join(MODEL_PATH, 'elements', 'freq_elements2.bdf') op2_filename = os.path.join(MODEL_PATH, 'elements', 'freq_elements2.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) def test_gui_elements_06(self): """tests a large number of elements and results in SOL 106-loadstep""" #bdf_filename = os.path.join(MODEL_PATH, 'elements', 'loadstep_elements.bdf') op2_filename = os.path.join(MODEL_PATH, 'elements', 'loadstep_elements.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) def test_gui_elements_07(self): """tests a large number of elements and results in SOL 107-complex modes""" #bdf_filename = os.path.join(MODEL_PATH, 'elements', 'modes_elements.bdf') op2_filename = os.path.join(MODEL_PATH, 'elements', 'modes_complex_elements.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) def test_gui_elements_08(self): """tests a large number of elements and results in SOL 109-linear time""" bdf_filename = os.path.join(MODEL_PATH, 'elements', 'modes_elements.bdf') op2_filename = os.path.join(MODEL_PATH, 'elements', 'time_elements.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) def test_gui_pload_01(self): """tests a PLOAD4/CTETRA""" #bdf_filename = os.path.join(MODEL_PATH, 'elements', 'ctetra.bdf') op2_filename = os.path.join(MODEL_PATH, 'unit', 'pload4', 'ctetra.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) def test_gui_pload_02(self): """tests a PLOAD4/CHEXA""" #bdf_filename = os.path.join(MODEL_PATH, 'elements', 'chexa.bdf') op2_filename = os.path.join(MODEL_PATH, 'unit', 'pload4', 'chexa.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) def test_gui_pload_03(self): """tests a PLOAD4/CPENTA""" #bdf_filename = os.path.join(MODEL_PATH, 'elements', 'cpenta.bdf') op2_filename = os.path.join(MODEL_PATH, 'unit', 'pload4', 'cpenta.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) def test_gui_pload_04(self): """tests a PLOAD4/CQUAD4""" #bdf_filename = os.path.join(MODEL_PATH, 'elements', 'cquad4.bdf') op2_filename = os.path.join(MODEL_PATH, 'unit', 'pload4', 'cquad4.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) def test_gui_pload_05(self): """tests a PLOAD4/CTRIA3""" #bdf_filename = os.path.join(MODEL_PATH, 'elements', 'ctria3.bdf') op2_filename = os.path.join(MODEL_PATH, 'unit', 'pload4', 'ctria3.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) #def test_gui_pload_06(self): #"""tests a PLOAD1/CBAR""" #bdf_filename = os.path.join(MODEL_PATH, 'elements', 'pload1.bdf') #op2_filename = os.path.join(MODEL_PATH, 'unit', 'pload4', 'pload1.op2') #test = NastranGUI() #test.load_nastran_geometry(op2_filename) #test.load_nastran_results(op2_filename) #def test_gui_bar_rod(self): #"""tests a PBARL/ROD""" #bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_rod.bdf') #test = NastranGUI() #test.load_nastran_geometry(bdf_filename) #def test_gui_bar_tube2(self): def test_gui_bar_tube(self): """tests a PBARL/TUBE""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_tube.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) def test_gui_bar_chan(self): """tests a PBARL/CHAN""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_chan.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.on_pan_left(None) test.on_pan_right(None) test.on_pan_up(None) test.on_pan_down(None) test.on_increase_magnification() test.on_decrease_magnification() test.zoom(1.2) test.on_rotate_clockwise() test.on_rotate_cclockwise() test.rotate(15.0) test.set_focal_point([0., 1., 2.]) test.export_case_data(icases=[0, 1]) test.update_camera('+x') test.update_camera('-x') test.update_camera('+y') test.update_camera('-y') test.update_camera('+z') test.update_camera('-z') test._update_camera() camera_data = test.get_camera_data() test.on_set_camera_data(camera_data, show_log=True) csv_filename = os.path.join(MODEL_PATH, 'custom_geom.csv') test.on_load_user_geom(csv_filename=csv_filename, name=None, color=None) stl_filename = os.path.join(STL_PATH, 'sphere.stl') test.on_load_user_geom(csv_filename=stl_filename, name=None, color=None) test.clear_labels() test.reset_labels() with open('xyz1.csv', 'w') as xyz_file: xyz_file.write('1., 2., 3.\n') xyz_file.write('4., 5., 6.\n') csv_filename = 'xyz1.csv' # os.path.join(MODEL_PATH, 'xyz1.csv') test.on_load_csv_points(csv_filename=csv_filename, name=None, color=None) os.remove(csv_filename) with open('xyz2.csv', 'w') as xyz_file: xyz_file.write('10., 20., 30.') csv_filename = 'xyz2.csv' # os.path.join(MODEL_PATH, 'xyz2.csv') test.on_load_csv_points(csv_filename=csv_filename, name=None, color=None) os.remove(csv_filename) #test.on_wireframe() #test.on_surface() os.remove('0_NodeID.csv') os.remove('1_ElementID.csv') with open('rotate.py', 'w') as pyfile: pyfile.write('self.rotate(20.)\n') test.on_run_script('rotate.py') os.remove('rotate.py') def test_gui_screenshot(self): bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_chan.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) magnify = None render_large = vtk.vtkRenderLargeImage() test.run_vtk = True #test.create_corner_axis() # faking coordinate system axes_actor = vtk.vtkAxesActor() test.corner_axis = vtk.vtkOrientationMarkerWidget() test.corner_axis.SetOrientationMarker(axes_actor) #test.on_take_screenshot(fname='chan.png', magnify=None, show_msg=True) out = test.tool_actions._screenshot_setup(magnify, render_large) line_widths0, point_sizes0, coord_scale0, coord_text_scale0, linewidth0, fake_axes_actor, magnify = out test.tool_actions._screenshot_teardown( line_widths0, point_sizes0, coord_scale0, coord_text_scale0, linewidth0, axes_actor) def test_gui_bar_chan1(self): """tests a PBARL/CHAN1""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_chan1.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) #def test_gui_bar_chan2(self): def test_gui_bar_bar(self): """tests a PBARL/BAR""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_bar.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) def test_gui_bar_box(self): """tests a PBARL/BOX""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_box.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) def test_gui_bar_z(self): """tests a PBARL/Z""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_z.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) def test_gui_bar_t(self): """tests a PBARL/T""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_t.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) def test_gui_bar_t1(self): """tests a PBARL/T1""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_t1.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) str(test.geometry_properties) T1z = deepcopy(test.geometry_properties['T1_z']) T1z.line_width = 4 T1z.color = (255, 0, 0) T1z.opacity = 0.6 T1z.bar_scale = 0.20 test.edit_geometry_properties_obj.on_update_geometry_properties({'T1_z' : T1z}, name=None, write_log=True) test.edit_geometry_properties_obj.on_update_geometry_properties({'T1_z' : T1z}, name='T1_z', write_log=True) def test_gui_bar_t2(self): """tests a PBARL/T2""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_t2.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) def test_gui_bar_hexa(self): """tests a PBARL/HEXA""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_hexa.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) def test_gui_bar_hat(self): """tests a PBARL/HAT""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_hat.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) def test_gui_bar_i(self): """tests a PBARL/I""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_i.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) def test_gui_bar_i1(self): """tests a PBARL/I1""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_i1.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) def test_gui_bar_h(self): """tests a PBARL/H""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbarl_h.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) def test_gui_beam_l(self): """tests a PBEAML/L""" bdf_filename = os.path.join(MODEL_PATH, 'unit', 'bars', 'pbeaml_l.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) total_length = test.model.get_length_breakdown()[100] assert np.allclose(total_length, 100.) def test_gui_thermal_01(self): """tests thermal""" #bdf_filename = os.path.join(MODEL_PATH, 'thermal', 'thermal_test_153.bdf') op2_filename = os.path.join(MODEL_PATH, 'thermal', 'thermal_test_153.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) def test_gui_thermal_02(self): """tests thermal""" bdf_filename = os.path.join(MODEL_PATH, 'thermal', 'hd15901.bdf') op2_filename = os.path.join(MODEL_PATH, 'thermal', 'hd15901.op2') test = NastranGUI() with self.assertRaises(DuplicateIDsError): test.load_nastran_geometry(op2_filename) test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) def test_gui_thermal_03(self): """tests thermal""" #bdf_filename = os.path.join(MODEL_PATH, 'other', 'hd15306.bdf') op2_filename = os.path.join(MODEL_PATH, 'other', 'hd15306.op2') test = NastranGUI() test.load_nastran_geometry(op2_filename) test.load_nastran_results(op2_filename) def test_gui_superelement_1(self): """tests flyswatter""" bdf_filename = os.path.join(MODEL_PATH, 'superelements', 'flyswatter', 'flyswatter_renumber.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) #test.load_nastran_results(op2_filename) def test_gui_superelement_2(self): """tests superelement mirror/shift/renumber""" bdf_filename = os.path.join(MODEL_PATH, 'superelements', 'see103q4.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) os.remove('spike.bdf') os.remove('super_12.bdf') os.remove('super_13.bdf') os.remove('super_15.bdf') def test_gui_dvprel(self): """tests dvprel""" bdf_filename = os.path.join(MODEL_PATH, 'other', 'dofm12.bdf') #op2_filename = os.path.join(MODEL_PATH, 'other', 'dofm12.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) #test.load_nastran_results(op2_filename) def test_gui_optimization_mcpads4(self): """tests mcpads4.bdf, which tests *.des and convergence""" bdf_filename = os.path.join(MODEL_PATH, 'other', 'mcpads4.bdf') op2_filename = os.path.join(MODEL_PATH, 'other', 'mcpads4.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) def test_gui_patran(self): """tests patran format""" bdf_filename = os.path.join(MODEL_PATH, 'patran_fmt', '0012_20.bdf') nod_filename = os.path.join(MODEL_PATH, 'patran_fmt', 'normals.nod') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(nod_filename) def test_gui_patran2(self): """tests patran format""" bdf_filename = os.path.join(MODEL_PATH, 'patran_fmt', '0012_20.bdf') nod_filename = os.path.join(MODEL_PATH, 'patran_fmt', 'normals.nod') test = NastranGUI() test.on_load_geometry(bdf_filename, geometry_format='nastran', raise_error=True) test.on_load_custom_results(out_filename=nod_filename, restype='Patran_nod') def test_gui_axi(self): """tests axisymmetric elements""" bdf_filename = os.path.join(MODEL_PATH, 'axisymmetric', 'model.bdf') test = NastranGUI() test.load_nastran_geometry(bdf_filename) def test_gui_ogs(self): """ tests ogs.op2: - GridPointSurfaceStressesArray """ bdf_filename = os.path.join(MODEL_PATH, 'ogs', 'ogs.bdf') op2_filename = os.path.join(MODEL_PATH, 'ogs', 'ogs.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) def test_gui_bdf_op2_other_23(self): """ tests ehbus69.op2: - RealBush1DStressArray - GridPointStressesVolumeDirectArray - GridPointStressesVolumePrincipalArray - GridPointStressesSurfaceDiscontinutiesArray """ # TODO: support these results... bdf_filename = os.path.join(MODEL_PATH, 'other', 'ehbus69.bdf') op2_filename = os.path.join(MODEL_PATH, 'other', 'ehbus69.op2') test = NastranGUI() test.load_nastran_geometry(bdf_filename) test.load_nastran_results(op2_filename) def test_gui_zona_model_1(self): bdf_filename = os.path.join(MODEL_PATH, 'aero', 'f16_ma41.bdf') test = NastranGUI() test.log = SimpleLogger(level='error', encoding='utf-8', log_func=None) test.load_nastran_geometry(bdf_filename) def test_gui_zona_model_2(self): bdf_file = get_zona_model() test = NastranGUI() test.log = SimpleLogger(level='error', encoding='utf-8', log_func=None) test.load_nastran_geometry(bdf_file) #def test_bottle(): # pragma: no cover #""" #Tests Nastran GUI loading #""" #test = NastranGUI() #test.load_nastran_geometry('bottle_shell_w_holes_pmc.bdf', '') #test.load_nastran_results('bottle_shell_w_holes_pmc.op2', '') #keys = test.result_cases.keys() #assert (1, 'Stress1', 1, 'centroid', '%.3f') in keys, keys if __name__ == '__main__': # pragma: no cover unittest.main()
[ "unittest.skipIf", "numpy.array", "copy.deepcopy", "unittest.main", "os.remove", "os.path.exists", "cpylog.SimpleLogger", "vtk.vtkRenderLargeImage", "pyNastran.gui.testing_methods.FakeGUIMethods.__init__", "vtk.vtkAxesActor", "pyNastran.converters.nastran.nastran_to_vtk.nastran_to_vtk", "numpy...
[((987, 1030), 'os.path.join', 'os.path.join', (['PKG_PATH', '"""converters"""', '"""stl"""'], {}), "(PKG_PATH, 'converters', 'stl')\n", (999, 1030), False, 'import os\n'), ((1044, 1082), 'os.path.join', 'os.path.join', (['PKG_PATH', '""".."""', '"""models"""'], {}), "(PKG_PATH, '..', 'models')\n", (1056, 1082), False, 'import os\n'), ((135, 156), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (149, 156), False, 'import matplotlib\n'), ((2731, 2787), 'unittest.skipIf', 'unittest.skipIf', (['(IS_MATPLOTLIB is False)', '"""No matplotlib"""'], {}), "(IS_MATPLOTLIB is False, 'No matplotlib')\n", (2746, 2787), False, 'import unittest\n'), ((41207, 41222), 'unittest.main', 'unittest.main', ([], {}), '()\n', (41220, 41222), False, 'import unittest\n'), ((805, 849), 'pyNastran.gui.testing_methods.FakeGUIMethods.__init__', 'FakeGUIMethods.__init__', (['self'], {'inputs': 'inputs'}), '(self, inputs=inputs)\n', (828, 849), False, 'from pyNastran.gui.testing_methods import FakeGUIMethods\n'), ((858, 882), 'pyNastran.converters.nastran.gui.nastran_io.NastranIO.__init__', 'NastranIO.__init__', (['self'], {}), '(self)\n', (876, 882), False, 'from pyNastran.converters.nastran.gui.nastran_io import NastranIO\n'), ((1207, 1225), 'qtpy.QtCore.QSettings', 'QtCore.QSettings', ([], {}), '()\n', (1223, 1225), False, 'from qtpy import QtCore\n'), ((2369, 2443), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""sol_101_elements"""', '"""static_solid_shell_bar.bdf"""'], {}), "(MODEL_PATH, 'sol_101_elements', 'static_solid_shell_bar.bdf')\n", (2381, 2443), False, 'import os\n'), ((2467, 2541), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""sol_101_elements"""', '"""static_solid_shell_bar.obj"""'], {}), "(MODEL_PATH, 'sol_101_elements', 'static_solid_shell_bar.obj')\n", (2479, 2541), False, 'import os\n'), ((2558, 2563), 'pyNastran.bdf.bdf.BDF', 'BDF', ([], {}), '()\n', (2561, 2563), False, 'from pyNastran.bdf.bdf import BDF\n'), ((2850, 2924), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""sol_101_elements"""', '"""static_solid_shell_bar.bdf"""'], {}), "(MODEL_PATH, 'sol_101_elements', 'static_solid_shell_bar.bdf')\n", (2862, 2924), False, 'import os\n'), ((2948, 3022), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""sol_101_elements"""', '"""static_solid_shell_bar.op2"""'], {}), "(MODEL_PATH, 'sol_101_elements', 'static_solid_shell_bar.op2')\n", (2960, 3022), False, 'import os\n'), ((4422, 4447), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (4430, 4447), True, 'import numpy as np\n'), ((4467, 4492), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (4475, 4492), True, 'import numpy as np\n'), ((4511, 4536), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (4519, 4536), True, 'import numpy as np\n'), ((4556, 4581), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (4564, 4581), True, 'import numpy as np\n'), ((6387, 6459), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""sol_101_elements"""', '"""mode_solid_shell_bar.bdf"""'], {}), "(MODEL_PATH, 'sol_101_elements', 'mode_solid_shell_bar.bdf')\n", (6399, 6459), False, 'import os\n'), ((6483, 6555), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""sol_101_elements"""', '"""mode_solid_shell_bar.op2"""'], {}), "(MODEL_PATH, 'sol_101_elements', 'mode_solid_shell_bar.op2')\n", (6495, 6555), False, 'import os\n'), ((11060, 11132), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""sol_101_elements"""', '"""mode_solid_shell_bar.bdf"""'], {}), "(MODEL_PATH, 'sol_101_elements', 'mode_solid_shell_bar.bdf')\n", (11072, 11132), False, 'import os\n'), ((11380, 11456), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""sol_101_elements"""', '"""buckling_solid_shell_bar.bdf"""'], {}), "(MODEL_PATH, 'sol_101_elements', 'buckling_solid_shell_bar.bdf')\n", (11392, 11456), False, 'import os\n'), ((11480, 11556), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""sol_101_elements"""', '"""buckling_solid_shell_bar.op2"""'], {}), "(MODEL_PATH, 'sol_101_elements', 'buckling_solid_shell_bar.op2')\n", (11492, 11556), False, 'import os\n'), ((11741, 11803), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""solid_bending"""', '"""solid_bending.bdf"""'], {}), "(MODEL_PATH, 'solid_bending', 'solid_bending.bdf')\n", (11753, 11803), False, 'import os\n'), ((11926, 12014), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""solid_bending"""', '"""solid_bending_multi_deflection_node.txt"""'], {}), "(MODEL_PATH, 'solid_bending',\n 'solid_bending_multi_deflection_node.txt')\n", (11938, 12014), False, 'import os\n'), ((12042, 12136), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""solid_bending"""', '"""solid_bending_multi_deflection_node_short.txt"""'], {}), "(MODEL_PATH, 'solid_bending',\n 'solid_bending_multi_deflection_node_short.txt')\n", (12054, 12136), False, 'import os\n'), ((13306, 13379), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""solid_bending"""', '"""solid_bending_multi_node.csv"""'], {}), "(MODEL_PATH, 'solid_bending', 'solid_bending_multi_node.csv')\n", (13318, 13379), False, 'import os\n'), ((13404, 13483), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""solid_bending"""', '"""solid_bending_multi_node_extra.txt"""'], {}), "(MODEL_PATH, 'solid_bending', 'solid_bending_multi_node_extra.txt')\n", (13416, 13483), False, 'import os\n'), ((13508, 13587), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""solid_bending"""', '"""solid_bending_multi_node_short.txt"""'], {}), "(MODEL_PATH, 'solid_bending', 'solid_bending_multi_node_short.txt')\n", (13520, 13587), False, 'import os\n'), ((14143, 14199), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""beam_modes"""', '"""beam_modes.dat"""'], {}), "(MODEL_PATH, 'beam_modes', 'beam_modes.dat')\n", (14155, 14199), False, 'import os\n'), ((14223, 14282), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""beam_modes"""', '"""beam_modes_m1.op2"""'], {}), "(MODEL_PATH, 'beam_modes', 'beam_modes_m1.op2')\n", (14235, 14282), False, 'import os\n'), ((14508, 14564), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""beam_modes"""', '"""beam_modes.dat"""'], {}), "(MODEL_PATH, 'beam_modes', 'beam_modes.dat')\n", (14520, 14564), False, 'import os\n'), ((14588, 14647), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""beam_modes"""', '"""beam_modes_m2.op2"""'], {}), "(MODEL_PATH, 'beam_modes', 'beam_modes_m2.op2')\n", (14600, 14647), False, 'import os\n'), ((14827, 14865), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""beam_modes"""'], {}), "(MODEL_PATH, 'beam_modes')\n", (14839, 14865), False, 'import os\n'), ((14889, 14928), 'os.path.join', 'os.path.join', (['dirname', '"""beam_modes.dat"""'], {}), "(dirname, 'beam_modes.dat')\n", (14901, 14928), False, 'import os\n'), ((14952, 14994), 'os.path.join', 'os.path.join', (['dirname', '"""beam_modes_m1.op2"""'], {}), "(dirname, 'beam_modes_m1.op2')\n", (14964, 14994), False, 'import os\n'), ((15372, 15410), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""beam_modes"""'], {}), "(MODEL_PATH, 'beam_modes')\n", (15384, 15410), False, 'import os\n'), ((15434, 15473), 'os.path.join', 'os.path.join', (['dirname', '"""beam_modes.dat"""'], {}), "(dirname, 'beam_modes.dat')\n", (15446, 15473), False, 'import os\n'), ((15497, 15539), 'os.path.join', 'os.path.join', (['dirname', '"""beam_modes_m2.op2"""'], {}), "(dirname, 'beam_modes_m2.op2')\n", (15509, 15539), False, 'import os\n'), ((16336, 16378), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""fsi"""', '"""fsi.bdf"""'], {}), "(MODEL_PATH, 'fsi', 'fsi.bdf')\n", (16348, 16378), False, 'import os\n'), ((16402, 16444), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""fsi"""', '"""fsi.op2"""'], {}), "(MODEL_PATH, 'fsi', 'fsi.op2')\n", (16414, 16444), False, 'import os\n'), ((16672, 16707), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""thermal"""'], {}), "(MODEL_PATH, 'thermal')\n", (16684, 16707), False, 'import os\n'), ((16731, 16776), 'os.path.join', 'os.path.join', (['dirname', '"""thermal_test_153.bdf"""'], {}), "(dirname, 'thermal_test_153.bdf')\n", (16743, 16776), False, 'import os\n'), ((16800, 16845), 'os.path.join', 'os.path.join', (['dirname', '"""thermal_test_153.op2"""'], {}), "(dirname, 'thermal_test_153.op2')\n", (16812, 16845), False, 'import os\n'), ((17024, 17072), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""bwb"""', '"""bwb_saero.bdf"""'], {}), "(MODEL_PATH, 'bwb', 'bwb_saero.bdf')\n", (17036, 17072), False, 'import os\n'), ((17464, 17505), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""femap_exhaust"""'], {}), "(MODEL_PATH, 'femap_exhaust')\n", (17476, 17505), False, 'import os\n'), ((17596, 17638), 'os.path.join', 'os.path.join', (['dirname', '"""modal_example.op2"""'], {}), "(dirname, 'modal_example.op2')\n", (17608, 17638), False, 'import os\n'), ((17955, 18013), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""aero"""', '"""freedlm"""', '"""freedlm.op2"""'], {}), "(MODEL_PATH, 'aero', 'freedlm', 'freedlm.op2')\n", (17967, 18013), False, 'import os\n'), ((18409, 18471), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""aero"""', '"""bah_plane"""', '"""bah_plane.bdf"""'], {}), "(MODEL_PATH, 'aero', 'bah_plane', 'bah_plane.bdf')\n", (18421, 18471), False, 'import os\n'), ((18495, 18557), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""aero"""', '"""bah_plane"""', '"""bah_plane.op2"""'], {}), "(MODEL_PATH, 'aero', 'bah_plane', 'bah_plane.op2')\n", (18507, 18557), False, 'import os\n'), ((18703, 18737), 'copy.deepcopy', 'deepcopy', (['test.geometry_properties'], {}), '(test.geometry_properties)\n', (18711, 18737), False, 'from copy import deepcopy\n'), ((19876, 19935), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""static_elements.bdf"""'], {}), "(MODEL_PATH, 'elements', 'static_elements.bdf')\n", (19888, 19935), False, 'import os\n'), ((19959, 20018), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""static_elements.op2"""'], {}), "(MODEL_PATH, 'elements', 'static_elements.op2')\n", (19971, 20018), False, 'import os\n'), ((21568, 21627), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""static_elements.vtu"""'], {}), "(MODEL_PATH, 'elements', 'static_elements.vtu')\n", (21580, 21627), False, 'import os\n'), ((21636, 21678), 'pyNastran.converters.nastran.nastran_to_vtk.nastran_to_vtk', 'nastran_to_vtk', (['op2_filename', 'vtk_filename'], {}), '(op2_filename, vtk_filename)\n', (21650, 21678), False, 'from pyNastran.converters.nastran.nastran_to_vtk import nastran_to_vtk\n'), ((21694, 21722), 'os.path.exists', 'os.path.exists', (['vtk_filename'], {}), '(vtk_filename)\n', (21708, 21722), False, 'import os\n'), ((21798, 21857), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""static_elements.bdf"""'], {}), "(MODEL_PATH, 'elements', 'static_elements.bdf')\n", (21810, 21857), False, 'import os\n'), ((21881, 21940), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""static_elements.op2"""'], {}), "(MODEL_PATH, 'elements', 'static_elements.op2')\n", (21893, 21940), False, 'import os\n'), ((21997, 22002), 'pyNastran.bdf.bdf.BDF', 'BDF', ([], {}), '()\n', (22000, 22002), False, 'from pyNastran.bdf.bdf import BDF\n'), ((22895, 22954), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""static_elements.op2"""'], {}), "(MODEL_PATH, 'elements', 'static_elements.op2')\n", (22907, 22954), False, 'import os\n'), ((23694, 23752), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""modes_elements.op2"""'], {}), "(MODEL_PATH, 'elements', 'modes_elements.op2')\n", (23706, 23752), False, 'import os\n'), ((24187, 24244), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""freq_elements.op2"""'], {}), "(MODEL_PATH, 'elements', 'freq_elements.op2')\n", (24199, 24244), False, 'import os\n'), ((25201, 25259), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""freq_elements2.op2"""'], {}), "(MODEL_PATH, 'elements', 'freq_elements2.op2')\n", (25213, 25259), False, 'import os\n'), ((25610, 25671), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""loadstep_elements.op2"""'], {}), "(MODEL_PATH, 'elements', 'loadstep_elements.op2')\n", (25622, 25671), False, 'import os\n'), ((26024, 26090), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""modes_complex_elements.op2"""'], {}), "(MODEL_PATH, 'elements', 'modes_complex_elements.op2')\n", (26036, 26090), False, 'import os\n'), ((26358, 26416), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""modes_elements.bdf"""'], {}), "(MODEL_PATH, 'elements', 'modes_elements.bdf')\n", (26370, 26416), False, 'import os\n'), ((26440, 26497), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""elements"""', '"""time_elements.op2"""'], {}), "(MODEL_PATH, 'elements', 'time_elements.op2')\n", (26452, 26497), False, 'import os\n'), ((26791, 26847), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""pload4"""', '"""ctetra.op2"""'], {}), "(MODEL_PATH, 'unit', 'pload4', 'ctetra.op2')\n", (26803, 26847), False, 'import os\n'), ((27139, 27194), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""pload4"""', '"""chexa.op2"""'], {}), "(MODEL_PATH, 'unit', 'pload4', 'chexa.op2')\n", (27151, 27194), False, 'import os\n'), ((27488, 27544), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""pload4"""', '"""cpenta.op2"""'], {}), "(MODEL_PATH, 'unit', 'pload4', 'cpenta.op2')\n", (27500, 27544), False, 'import os\n'), ((27838, 27894), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""pload4"""', '"""cquad4.op2"""'], {}), "(MODEL_PATH, 'unit', 'pload4', 'cquad4.op2')\n", (27850, 27894), False, 'import os\n'), ((28188, 28244), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""pload4"""', '"""ctria3.op2"""'], {}), "(MODEL_PATH, 'unit', 'pload4', 'ctria3.op2')\n", (28200, 28244), False, 'import os\n'), ((29077, 29135), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_tube.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_tube.bdf')\n", (29089, 29135), False, 'import os\n'), ((29303, 29361), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_chan.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_chan.bdf')\n", (29315, 29361), False, 'import os\n'), ((30210, 30253), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""custom_geom.csv"""'], {}), "(MODEL_PATH, 'custom_geom.csv')\n", (30222, 30253), False, 'import os\n'), ((30359, 30395), 'os.path.join', 'os.path.join', (['STL_PATH', '"""sphere.stl"""'], {}), "(STL_PATH, 'sphere.stl')\n", (30371, 30395), False, 'import os\n'), ((30831, 30854), 'os.remove', 'os.remove', (['csv_filename'], {}), '(csv_filename)\n', (30840, 30854), False, 'import os\n'), ((31111, 31134), 'os.remove', 'os.remove', (['csv_filename'], {}), '(csv_filename)\n', (31120, 31134), False, 'import os\n'), ((31201, 31226), 'os.remove', 'os.remove', (['"""0_NodeID.csv"""'], {}), "('0_NodeID.csv')\n", (31210, 31226), False, 'import os\n'), ((31235, 31263), 'os.remove', 'os.remove', (['"""1_ElementID.csv"""'], {}), "('1_ElementID.csv')\n", (31244, 31263), False, 'import os\n'), ((31407, 31429), 'os.remove', 'os.remove', (['"""rotate.py"""'], {}), "('rotate.py')\n", (31416, 31429), False, 'import os\n'), ((31489, 31547), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_chan.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_chan.bdf')\n", (31501, 31547), False, 'import os\n'), ((31673, 31698), 'vtk.vtkRenderLargeImage', 'vtk.vtkRenderLargeImage', ([], {}), '()\n', (31696, 31698), False, 'import vtk\n'), ((31819, 31837), 'vtk.vtkAxesActor', 'vtk.vtkAxesActor', ([], {}), '()\n', (31835, 31837), False, 'import vtk\n'), ((31865, 31897), 'vtk.vtkOrientationMarkerWidget', 'vtk.vtkOrientationMarkerWidget', ([], {}), '()\n', (31895, 31897), False, 'import vtk\n'), ((32459, 32518), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_chan1.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_chan1.bdf')\n", (32471, 32518), False, 'import os\n'), ((32719, 32776), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_bar.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_bar.bdf')\n", (32731, 32776), False, 'import os\n'), ((32942, 32999), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_box.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_box.bdf')\n", (32954, 32999), False, 'import os\n'), ((33161, 33216), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_z.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_z.bdf')\n", (33173, 33216), False, 'import os\n'), ((33378, 33433), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_t.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_t.bdf')\n", (33390, 33433), False, 'import os\n'), ((33597, 33653), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_t1.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_t1.bdf')\n", (33609, 33653), False, 'import os\n'), ((33784, 33826), 'copy.deepcopy', 'deepcopy', (["test.geometry_properties['T1_z']"], {}), "(test.geometry_properties['T1_z'])\n", (33792, 33826), False, 'from copy import deepcopy\n'), ((34259, 34315), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_t2.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_t2.bdf')\n", (34271, 34315), False, 'import os\n'), ((34483, 34541), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_hexa.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_hexa.bdf')\n", (34495, 34541), False, 'import os\n'), ((34707, 34764), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_hat.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_hat.bdf')\n", (34719, 34764), False, 'import os\n'), ((34926, 34981), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_i.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_i.bdf')\n", (34938, 34981), False, 'import os\n'), ((35145, 35201), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_i1.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_i1.bdf')\n", (35157, 35201), False, 'import os\n'), ((35363, 35418), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbarl_h.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbarl_h.bdf')\n", (35375, 35418), False, 'import os\n'), ((35582, 35638), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""unit"""', '"""bars"""', '"""pbeaml_l.bdf"""'], {}), "(MODEL_PATH, 'unit', 'bars', 'pbeaml_l.bdf')\n", (35594, 35638), False, 'import os\n'), ((35793, 35825), 'numpy.allclose', 'np.allclose', (['total_length', '(100.0)'], {}), '(total_length, 100.0)\n', (35804, 35825), True, 'import numpy as np\n'), ((35996, 36055), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""thermal"""', '"""thermal_test_153.op2"""'], {}), "(MODEL_PATH, 'thermal', 'thermal_test_153.op2')\n", (36008, 36055), False, 'import os\n'), ((36268, 36318), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""thermal"""', '"""hd15901.bdf"""'], {}), "(MODEL_PATH, 'thermal', 'hd15901.bdf')\n", (36280, 36318), False, 'import os\n'), ((36342, 36392), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""thermal"""', '"""hd15901.op2"""'], {}), "(MODEL_PATH, 'thermal', 'hd15901.op2')\n", (36354, 36392), False, 'import os\n'), ((36782, 36830), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""other"""', '"""hd15306.op2"""'], {}), "(MODEL_PATH, 'other', 'hd15306.op2')\n", (36794, 36830), False, 'import os\n'), ((37050, 37136), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""superelements"""', '"""flyswatter"""', '"""flyswatter_renumber.bdf"""'], {}), "(MODEL_PATH, 'superelements', 'flyswatter',\n 'flyswatter_renumber.bdf')\n", (37062, 37136), False, 'import os\n'), ((37377, 37434), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""superelements"""', '"""see103q4.bdf"""'], {}), "(MODEL_PATH, 'superelements', 'see103q4.bdf')\n", (37389, 37434), False, 'import os\n'), ((37520, 37542), 'os.remove', 'os.remove', (['"""spike.bdf"""'], {}), "('spike.bdf')\n", (37529, 37542), False, 'import os\n'), ((37551, 37576), 'os.remove', 'os.remove', (['"""super_12.bdf"""'], {}), "('super_12.bdf')\n", (37560, 37576), False, 'import os\n'), ((37585, 37610), 'os.remove', 'os.remove', (['"""super_13.bdf"""'], {}), "('super_13.bdf')\n", (37594, 37610), False, 'import os\n'), ((37619, 37644), 'os.remove', 'os.remove', (['"""super_15.bdf"""'], {}), "('super_15.bdf')\n", (37628, 37644), False, 'import os\n'), ((37727, 37774), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""other"""', '"""dofm12.bdf"""'], {}), "(MODEL_PATH, 'other', 'dofm12.bdf')\n", (37739, 37774), False, 'import os\n'), ((38109, 38157), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""other"""', '"""mcpads4.bdf"""'], {}), "(MODEL_PATH, 'other', 'mcpads4.bdf')\n", (38121, 38157), False, 'import os\n'), ((38181, 38229), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""other"""', '"""mcpads4.op2"""'], {}), "(MODEL_PATH, 'other', 'mcpads4.op2')\n", (38193, 38229), False, 'import os\n'), ((38444, 38497), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""patran_fmt"""', '"""0012_20.bdf"""'], {}), "(MODEL_PATH, 'patran_fmt', '0012_20.bdf')\n", (38456, 38497), False, 'import os\n'), ((38521, 38574), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""patran_fmt"""', '"""normals.nod"""'], {}), "(MODEL_PATH, 'patran_fmt', 'normals.nod')\n", (38533, 38574), False, 'import os\n'), ((38790, 38843), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""patran_fmt"""', '"""0012_20.bdf"""'], {}), "(MODEL_PATH, 'patran_fmt', '0012_20.bdf')\n", (38802, 38843), False, 'import os\n'), ((38867, 38920), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""patran_fmt"""', '"""normals.nod"""'], {}), "(MODEL_PATH, 'patran_fmt', 'normals.nod')\n", (38879, 38920), False, 'import os\n'), ((39217, 39270), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""axisymmetric"""', '"""model.bdf"""'], {}), "(MODEL_PATH, 'axisymmetric', 'model.bdf')\n", (39229, 39270), False, 'import os\n'), ((39488, 39530), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""ogs"""', '"""ogs.bdf"""'], {}), "(MODEL_PATH, 'ogs', 'ogs.bdf')\n", (39500, 39530), False, 'import os\n'), ((39554, 39596), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""ogs"""', '"""ogs.op2"""'], {}), "(MODEL_PATH, 'ogs', 'ogs.op2')\n", (39566, 39596), False, 'import os\n'), ((40062, 40110), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""other"""', '"""ehbus69.bdf"""'], {}), "(MODEL_PATH, 'other', 'ehbus69.bdf')\n", (40074, 40110), False, 'import os\n'), ((40134, 40182), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""other"""', '"""ehbus69.op2"""'], {}), "(MODEL_PATH, 'other', 'ehbus69.op2')\n", (40146, 40182), False, 'import os\n'), ((40370, 40418), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""aero"""', '"""f16_ma41.bdf"""'], {}), "(MODEL_PATH, 'aero', 'f16_ma41.bdf')\n", (40382, 40418), False, 'import os\n'), ((40466, 40526), 'cpylog.SimpleLogger', 'SimpleLogger', ([], {'level': '"""error"""', 'encoding': '"""utf-8"""', 'log_func': 'None'}), "(level='error', encoding='utf-8', log_func=None)\n", (40478, 40526), False, 'from cpylog import SimpleLogger\n'), ((40633, 40649), 'pyNastran.bdf.cards.test.test_aero.get_zona_model', 'get_zona_model', ([], {}), '()\n', (40647, 40649), False, 'from pyNastran.bdf.cards.test.test_aero import get_zona_model\n'), ((40697, 40757), 'cpylog.SimpleLogger', 'SimpleLogger', ([], {'level': '"""error"""', 'encoding': '"""utf-8"""', 'log_func': 'None'}), "(level='error', encoding='utf-8', log_func=None)\n", (40709, 40757), False, 'from cpylog import SimpleLogger\n'), ((4289, 4306), 'numpy.abs', 'np.abs', (['force_sum'], {}), '(force_sum)\n', (4295, 4306), True, 'import numpy as np\n'), ((4383, 4401), 'numpy.abs', 'np.abs', (['moment_sum'], {}), '(moment_sum)\n', (4389, 4401), True, 'import numpy as np\n'), ((4247, 4264), 'numpy.abs', 'np.abs', (['force_sum'], {}), '(force_sum)\n', (4253, 4264), True, 'import numpy as np\n'), ((4340, 4358), 'numpy.abs', 'np.abs', (['moment_sum'], {}), '(moment_sum)\n', (4346, 4358), True, 'import numpy as np\n')]
from time import time from random import randrange, seed import numpy as np #import pandas as pd import cv2 #import sys from sklearn.cluster import KMeans from scipy.optimize import linear_sum_assignment from scipy.spatial.distance import cdist #from random import randrange, seed class Tracktor(): def __init__(self, id="NO_ID", colour=None, block_size=51, offset=20, min_area=100, max_area=5000, scaling=1.0 ): try: # Returns True if OpenCL is present ocl = cv2.ocl.haveOpenCL() # Prints whether OpenCL is present print("OpenCL Supported?: ", end='') print(ocl) print() # Enables use of OpenCL by OpenCV if present if ocl == True: print('Now enabling OpenCL support') cv2.ocl.setUseOpenCL(True) print("Has OpenCL been Enabled?: ", end='') print(cv2.ocl.useOpenCL()) except cv2.error as e: print('Error:') # colours is a vector of BGR values which are used to identify individuals in the video # id is spider id and is also used for individual identification # number of elements in colours should be greater than n_inds (THIS IS NECESSARY FOR VISUALISATION ONLY) # number of elements in id should be greater than n_inds (THIS IS NECESSARY TO GET INDIVIDUAL-SPECIFIC DATA) #where each tracktor takes care of one individual, we do not need this. #self.n_inds = n_inds self.id = id if colour is None: seed(time()) colour = (randrange(0, 255, 1), randrange(0, 255, 1), randrange(0, 255, 1)) self.colour = colour # this is the block_size and offset used for adaptive thresholding (block_size should always be odd) # these values are critical for tracking performance if block_size % 2 != 1: self.block_size = block_size + 1 else: self.block_size = block_size self.offset = offset # minimum area and maximum area occupied by the animal in number of pixels # this parameter is used to get rid of other objects in view that might be hard to threshold out but are differently sized # in this case, the range is wide because males vastly smaller than females self.min_area = min_area self.max_area = max_area self.area = 0 self.clicked = (-1, -1) # the scaling parameter can be used to speed up tracking if video resolution is too high (use value 0-1) self.scaling = scaling # kernel for erosion and dilation # useful since thin spider limbs are sometimes detected as separate objects self.kernel = np.ones((5, 5), np.uint8) # mot determines whether the tracker is being used in noisy conditions to track a single object or for multi-object # using this will enable k-means clustering to force n_inds number of animals self.mot = False #List of data for pandas dataframe df = [] codec = 'DIVX' # try other codecs if the default doesn't work ('DIVX', 'avc1', 'XVID') note: this list is non-exhaustive ## Video writer class to output video with contour and centroid of tracked object(s) # make sure the frame size matches size of array 'final' fourcc = cv2.VideoWriter_fourcc(*codec) #output_framesize = (int(cap.read()[1].shape[1]*scaling), int(cap.read()[1].shape[0]*scaling)) #out = cv2.VideoWriter(filename = output_vidpath, fourcc = fourcc, fps = 60.0, frameSize = output_framesize, isColor = True) ## Individual location(s) measured in the last and current step self.meas_last = list(np.zeros((1, 2))) self.meas_now = list(np.zeros((1, 2))) #data frame? self.df = [] def colour_to_thresh(self, frame): """ This function retrieves a video frame and preprocesses it for object tracking. The code blurs image to reduce noise, converts it to greyscale and then returns a thresholded version of the original image. Parameters ---------- frame: ndarray, shape(n_rows, n_cols, 3) source image containing all three colour channels block_size: int(optional), default = 31 block_size determines the width of the kernel used for adaptive thresholding. Note: block_size must be odd. If even integer is used, the programme will add 1 to the block_size to make it odd. offset: int(optional), default = 25 constant subtracted from the mean value within the block Returns ------- thresh: ndarray, shape(n_rows, n_cols, 1) binarised(0, 255) image """ blur = cv2.blur(frame, (5, 5)) gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY) thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, self.block_size, self.offset) return thresh def detect_and_draw_contours(self, frame, thresh): """ This function detects contours, thresholds them based on area and draws them. Parameters ---------- frame: ndarray, shape(n_rows, n_cols, 3) source image containing all three colour channels thresh: ndarray, shape(n_rows, n_cols, 1) binarised(0, 255) image meas_last: array_like, dtype=float individual's location on previous frame meas_now: array_like, dtype=float individual's location on current frame min_area: int minimum area threhold used to detect the object of interest max_area: int maximum area threhold used to detect the object of interest Returns ------- final: ndarray, shape(n_rows, n_cols, 3) final output image composed of the input frame with object contours and centroids overlaid on it contours: list a list of all detected contours that pass the area based threhold criterion meas_last: array_like, dtype=float individual's location on previous frame meas_now: array_like, dtype=float individual's location on current frame """ # Detect contours and draw them based on specified area thresholds contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # img = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR) # final = frame.copy() i = 0 self.meas_last = self.meas_now.copy() #del self.meas_now[:] #assigning to empty doesn't crash, less efficient but a size of 2 wont make a difference self.meas_now = [] while i < len(contours): #if we clicked this frame if self.clicked != (-1, -1): #check if the position we clicked is inside of the contour dist = cv2.pointPolygonTest(contours[i], self.clicked, False) #if it is not (-1 if not, 1 if it is) we delete the contour if dist == -1.0: del contours[i] continue #if there exists a last position (x) elif self.meas_last[0][0]: #determine the distance from our last point to all contours dist = cv2.pointPolygonTest(contours[i], (self.meas_last[0][0], self.meas_last[0][1]), True) #delete all contours that exist outside max_area max_radius = int(np.sqrt(self.max_area/np.pi)) if abs(dist) > max_radius: del contours[i] continue area = cv2.contourArea(contours[i]) if area < self.min_area or area > self.max_area: del contours[i] else: cv2.drawContours(frame, contours, i, (0, 0, 255), 1) M = cv2.moments(contours[i]) if M['m00'] != 0: contour_x = M['m10']/M['m00'] contour_y = M['m01']/M['m00'] else: contour_x = 0 contour_y = 0 self.meas_now.append([contour_x, contour_y]) i += 1 self.clicked = (-1, -1) return frame, contours def apply_k_means(self, contours): """ This function applies the k-means clustering algorithm to separate merged contours. The algorithm is applied when detected contours are fewer than expected objects(number of animals) in the scene. Parameters ---------- contours: list a list of all detected contours that pass the area based threhold criterion n_inds: int total number of individuals being tracked meas_now: array_like, dtype=float individual's location on current frame Returns ------- contours: list a list of all detected contours that pass the area based threhold criterion meas_now: array_like, dtype=float individual's location on current frame """ #del self.meas_now[:] self.meas_now = [] # Clustering contours to separate individuals myarray = np.vstack(contours) print(myarray) myarray = myarray.reshape(myarray.shape[0], myarray.shape[2]) kmeans = KMeans(n_clusters=1, random_state=0, n_init=50).fit(myarray) l = len(kmeans.cluster_centers_) for i in range(l): x = int(tuple(kmeans.cluster_centers_[i])[0]) y = int(tuple(kmeans.cluster_centers_[i])[1]) self.meas_now.append([x, y]) return contours def hungarian_algorithm(self): """ The hungarian algorithm is a combinatorial optimisation algorithm used to solve assignment problems. Here, we use the algorithm to reduce noise due to ripples and to maintain individual identity. This is accomplished by minimising a cost function; in this case, euclidean distances between points measured in previous and current step. The algorithm here is written to be flexible as the number of contours detected between successive frames changes. However, an error will be returned if zero contours are detected. Parameters ---------- self.meas_last: array_like, dtype=float individual's location on previous frame meas_now: array_like, dtype=float individual's location on current frame Returns ------- row_ind: array, dtype=int64 individual identites arranged according to input ``meas_last`` col_ind: array, dtype=int64 individual identities rearranged based on matching locations from ``meas_last`` to ``meas_now`` by minimising the cost function """ self.meas_last = np.array(self.meas_last) self.meas_now = np.array(self.meas_now) if self.meas_now.shape != self.meas_last.shape: if self.meas_now.shape[0] < self.meas_last.shape[0]: while self.meas_now.shape[0] != self.meas_last.shape[0]: self.meas_last = np.delete(self.meas_last, self.meas_last.shape[0]-1, 0) else: result = np.zeros(self.meas_now.shape) result[:self.meas_last.shape[0], :self.meas_last.shape[1]] = self.meas_last self.meas_last = result self.meas_last = list(self.meas_last) self.meas_now = list(self.meas_now) cost = cdist(self.meas_last, self.meas_now) #reduce the length of cost if it gets too long... (takes a long time to process) if len(cost) > 100: cost = cost[:100] row_ind, col_ind = linear_sum_assignment(cost) return row_ind, col_ind def reorder_and_draw(self, final, col_ind, fr_no): """ This function reorders the measurements in the current frame to match identity from previous frame. This is done by using the results of the hungarian algorithm from the array col_inds. Parameters ---------- final: ndarray, shape(n_rows, n_cols, 3) final output image composed of the input frame with object contours and centroids overlaid on it colours: list, tuple list of tuples that represent colours used to assign individual identities n_inds: int total number of individuals being tracked col_ind: array, dtype=int64 individual identities rearranged based on matching locations from ``meas_last`` to ``meas_now`` by minimising the cost function meas_now: array_like, dtype=float individual's location on current frame df: pandas.core.frame.DataFrame this dataframe holds tracked coordinates i.e. the tracking results mot: bool this boolean determines if we apply the alogrithm to a multi-object tracking problem Returns ------- final: ndarray, shape(n_rows, n_cols, 3) final output image composed of the input frame with object contours and centroids overlaid on it meas_now: array_like, dtype=float individual's location on current frame df: pandas.DataFrame this dataframe holds tracked coordinates i.e. the tracking results """ # Reorder contours based on results of the hungarian algorithm equal = np.array_equal(col_ind, list(range(len(col_ind)))) if equal is False: current_ids = col_ind.copy() reordered = [i[0] for i in sorted(enumerate(current_ids), key=lambda x: x[1])] self.meas_now = [x for (y, x) in sorted(zip(reordered, self.meas_now))] for i in range(1): cv2.circle(final, tuple([int(x) for x in self.meas_now[i]]), 3, self.colour, -1, cv2.LINE_AA) #circle for area (A = pi*r^2) => r = sqrt(A/pi) min_radius = int(np.sqrt(self.min_area/np.pi)) cv2.circle(final, tuple([int(x) for x in self.meas_now[i]]), min_radius, (255, 255, 255), 1, cv2.LINE_AA) max_radius = int(np.sqrt(self.max_area/np.pi)) cv2.circle(final, tuple([int(x) for x in self.meas_now[i]]), max_radius, (0, 0, 255), 1, cv2.LINE_AA) # add frame number font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX #cv2.putText(final, str(int(fr_no)), (5, 30), font, 1, (255, 255, 255), 2) return final def reject_outliers(self, data, m): """ This function removes any outliers from presented data. Parameters ---------- data: pandas.Series a column from a pandas dataframe that needs smoothing m: float standard deviation cutoff beyond which, datapoint is considered as an outlier Returns ------- index: ndarray an array of indices of points that are not outliers """ d = np.abs(data - np.nanmedian(data)) mdev = np.nanmedian(d) s = d/mdev if mdev else 0. return np.where(s < m)
[ "numpy.sqrt", "numpy.array", "cv2.ocl.useOpenCL", "cv2.ocl.setUseOpenCL", "scipy.optimize.linear_sum_assignment", "numpy.where", "numpy.delete", "cv2.contourArea", "numpy.vstack", "cv2.VideoWriter_fourcc", "cv2.blur", "cv2.drawContours", "numpy.ones", "random.randrange", "cv2.cvtColor", ...
[((2861, 2886), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.uint8'], {}), '((5, 5), np.uint8)\n', (2868, 2886), True, 'import numpy as np\n'), ((3489, 3519), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (['*codec'], {}), '(*codec)\n', (3511, 3519), False, 'import cv2\n'), ((4933, 4956), 'cv2.blur', 'cv2.blur', (['frame', '(5, 5)'], {}), '(frame, (5, 5))\n', (4941, 4956), False, 'import cv2\n'), ((4972, 5010), 'cv2.cvtColor', 'cv2.cvtColor', (['blur', 'cv2.COLOR_BGR2GRAY'], {}), '(blur, cv2.COLOR_BGR2GRAY)\n', (4984, 5010), False, 'import cv2\n'), ((5028, 5146), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['gray', '(255)', 'cv2.ADAPTIVE_THRESH_MEAN_C', 'cv2.THRESH_BINARY_INV', 'self.block_size', 'self.offset'], {}), '(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.\n THRESH_BINARY_INV, self.block_size, self.offset)\n', (5049, 5146), False, 'import cv2\n'), ((9492, 9511), 'numpy.vstack', 'np.vstack', (['contours'], {}), '(contours)\n', (9501, 9511), True, 'import numpy as np\n'), ((11155, 11179), 'numpy.array', 'np.array', (['self.meas_last'], {}), '(self.meas_last)\n', (11163, 11179), True, 'import numpy as np\n'), ((11204, 11227), 'numpy.array', 'np.array', (['self.meas_now'], {}), '(self.meas_now)\n', (11212, 11227), True, 'import numpy as np\n'), ((11825, 11861), 'scipy.spatial.distance.cdist', 'cdist', (['self.meas_last', 'self.meas_now'], {}), '(self.meas_last, self.meas_now)\n', (11830, 11861), False, 'from scipy.spatial.distance import cdist\n'), ((12037, 12064), 'scipy.optimize.linear_sum_assignment', 'linear_sum_assignment', (['cost'], {}), '(cost)\n', (12058, 12064), False, 'from scipy.optimize import linear_sum_assignment\n'), ((15446, 15461), 'numpy.nanmedian', 'np.nanmedian', (['d'], {}), '(d)\n', (15458, 15461), True, 'import numpy as np\n'), ((15512, 15527), 'numpy.where', 'np.where', (['(s < m)'], {}), '(s < m)\n', (15520, 15527), True, 'import numpy as np\n'), ((611, 631), 'cv2.ocl.haveOpenCL', 'cv2.ocl.haveOpenCL', ([], {}), '()\n', (629, 631), False, 'import cv2\n'), ((3859, 3875), 'numpy.zeros', 'np.zeros', (['(1, 2)'], {}), '((1, 2))\n', (3867, 3875), True, 'import numpy as np\n'), ((3906, 3922), 'numpy.zeros', 'np.zeros', (['(1, 2)'], {}), '((1, 2))\n', (3914, 3922), True, 'import numpy as np\n'), ((7896, 7924), 'cv2.contourArea', 'cv2.contourArea', (['contours[i]'], {}), '(contours[i])\n', (7911, 7924), False, 'import cv2\n'), ((925, 951), 'cv2.ocl.setUseOpenCL', 'cv2.ocl.setUseOpenCL', (['(True)'], {}), '(True)\n', (945, 951), False, 'import cv2\n'), ((1691, 1697), 'time.time', 'time', ([], {}), '()\n', (1695, 1697), False, 'from time import time\n'), ((1721, 1741), 'random.randrange', 'randrange', (['(0)', '(255)', '(1)'], {}), '(0, 255, 1)\n', (1730, 1741), False, 'from random import randrange, seed\n'), ((1743, 1763), 'random.randrange', 'randrange', (['(0)', '(255)', '(1)'], {}), '(0, 255, 1)\n', (1752, 1763), False, 'from random import randrange, seed\n'), ((1765, 1785), 'random.randrange', 'randrange', (['(0)', '(255)', '(1)'], {}), '(0, 255, 1)\n', (1774, 1785), False, 'from random import randrange, seed\n'), ((7136, 7190), 'cv2.pointPolygonTest', 'cv2.pointPolygonTest', (['contours[i]', 'self.clicked', '(False)'], {}), '(contours[i], self.clicked, False)\n', (7156, 7190), False, 'import cv2\n'), ((8053, 8105), 'cv2.drawContours', 'cv2.drawContours', (['frame', 'contours', 'i', '(0, 0, 255)', '(1)'], {}), '(frame, contours, i, (0, 0, 255), 1)\n', (8069, 8105), False, 'import cv2\n'), ((8126, 8150), 'cv2.moments', 'cv2.moments', (['contours[i]'], {}), '(contours[i])\n', (8137, 8150), False, 'import cv2\n'), ((9623, 9670), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(1)', 'random_state': '(0)', 'n_init': '(50)'}), '(n_clusters=1, random_state=0, n_init=50)\n', (9629, 9670), False, 'from sklearn.cluster import KMeans\n'), ((11557, 11586), 'numpy.zeros', 'np.zeros', (['self.meas_now.shape'], {}), '(self.meas_now.shape)\n', (11565, 11586), True, 'import numpy as np\n'), ((14346, 14376), 'numpy.sqrt', 'np.sqrt', (['(self.min_area / np.pi)'], {}), '(self.min_area / np.pi)\n', (14353, 14376), True, 'import numpy as np\n'), ((14548, 14578), 'numpy.sqrt', 'np.sqrt', (['(self.max_area / np.pi)'], {}), '(self.max_area / np.pi)\n', (14555, 14578), True, 'import numpy as np\n'), ((15411, 15429), 'numpy.nanmedian', 'np.nanmedian', (['data'], {}), '(data)\n', (15423, 15429), True, 'import numpy as np\n'), ((1034, 1053), 'cv2.ocl.useOpenCL', 'cv2.ocl.useOpenCL', ([], {}), '()\n', (1051, 1053), False, 'import cv2\n'), ((7554, 7644), 'cv2.pointPolygonTest', 'cv2.pointPolygonTest', (['contours[i]', '(self.meas_last[0][0], self.meas_last[0][1])', '(True)'], {}), '(contours[i], (self.meas_last[0][0], self.meas_last[0][\n 1]), True)\n', (7574, 7644), False, 'import cv2\n'), ((11458, 11515), 'numpy.delete', 'np.delete', (['self.meas_last', '(self.meas_last.shape[0] - 1)', '(0)'], {}), '(self.meas_last, self.meas_last.shape[0] - 1, 0)\n', (11467, 11515), True, 'import numpy as np\n'), ((7738, 7768), 'numpy.sqrt', 'np.sqrt', (['(self.max_area / np.pi)'], {}), '(self.max_area / np.pi)\n', (7745, 7768), True, 'import numpy as np\n')]
# functions that implement transformations using the sineModel import numpy as np from scipy.interpolate import interp1d def sineTimeScaling(sfreq, smag, timeScaling): """ Time scaling of sinusoidal tracks sfreq, smag: frequencies and magnitudes of input sinusoidal tracks timeScaling: scaling factors, in time-value pairs returns ysfreq, ysmag: frequencies and magnitudes of output sinusoidal tracks """ if (timeScaling.size % 2 != 0): # raise exception if array not even length raise ValueError("Time scaling array does not have an even size") L = sfreq.shape[0] # number of input frames maxInTime = max(timeScaling[::2]) # maximum value used as input times maxOutTime = max(timeScaling[1::2]) # maximum value used in output times outL = int(L*maxOutTime/maxInTime) # number of output frames inFrames = (L-1)*timeScaling[::2]/maxInTime # input time values in frames outFrames = outL*timeScaling[1::2]/maxOutTime # output time values in frames timeScalingEnv = interp1d(outFrames, inFrames, fill_value=0) # interpolation function indexes = timeScalingEnv(np.arange(outL)) # generate frame indexes for the output ysfreq = sfreq[int(round(indexes[0])),:] # first output frame ysmag = smag[int(round(indexes[0])),:] # first output frame for l in indexes[1:]: # generate frames for output sine tracks ysfreq = np.vstack((ysfreq, sfreq[int(round(l)),:])) # get closest frame to scaling value ysmag = np.vstack((ysmag, smag[int(round(l)),:])) # get closest frame to scaling value return ysfreq, ysmag def sineFreqScaling(sfreq, freqScaling): """ Frequency scaling of sinusoidal tracks sfreq: frequencies of input sinusoidal tracks freqScaling: scaling factors, in time-value pairs (value of 1 is no scaling) returns ysfreq: frequencies of output sinusoidal tracks """ if (freqScaling.size % 2 != 0): # raise exception if array not even length raise ValueError("Frequency scaling array does not have an even size") L = sfreq.shape[0] # number of input frames # create interpolation object from the scaling values freqScalingEnv = np.interp(np.arange(L), L*freqScaling[::2]/freqScaling[-2], freqScaling[1::2]) ysfreq = np.zeros_like(sfreq) # create empty output matrix for l in range(L): # go through all frames ind_valid = np.where(sfreq[l,:]!=0)[0] # check if there are frequency values if ind_valid.size == 0: # if no values go to next frame continue ysfreq[l,ind_valid] = sfreq[l,ind_valid] * freqScalingEnv[l] # scale of frequencies return ysfreq
[ "numpy.where", "numpy.zeros_like", "numpy.arange", "scipy.interpolate.interp1d" ]
[((1122, 1165), 'scipy.interpolate.interp1d', 'interp1d', (['outFrames', 'inFrames'], {'fill_value': '(0)'}), '(outFrames, inFrames, fill_value=0)\n', (1130, 1165), False, 'from scipy.interpolate import interp1d\n'), ((2456, 2476), 'numpy.zeros_like', 'np.zeros_like', (['sfreq'], {}), '(sfreq)\n', (2469, 2476), True, 'import numpy as np\n'), ((1220, 1235), 'numpy.arange', 'np.arange', (['outL'], {}), '(outL)\n', (1229, 1235), True, 'import numpy as np\n'), ((2376, 2388), 'numpy.arange', 'np.arange', (['L'], {}), '(L)\n', (2385, 2388), True, 'import numpy as np\n'), ((2625, 2651), 'numpy.where', 'np.where', (['(sfreq[l, :] != 0)'], {}), '(sfreq[l, :] != 0)\n', (2633, 2651), True, 'import numpy as np\n')]
import numpy as np import tensorflow as tf from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort from mnist import module as model from cnocr import CnOcr import mxnet as mx from werkzeug.utils import secure_filename import datetime import random import os import base64 # import os class Pic_str: def create_uuid(self): #生成唯一的图片的名称字符串,防止图片显示时的重名问题 nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S"); # 生成当前时间 randomNum = random.randint(0, 100); # 生成的随机整数n,其中0<=n<=100 if randomNum <= 10: randomNum = str(0) + str(randomNum); uniqueNum = str(nowTime) + str(randomNum); return uniqueNum; # os.environ["CUDA_VISIBLE_DEVICES"] = "1" # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.9) # # 0.9表示可以使用GPU 90%的资源进行训练,可以任意修改 # sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) config = tf.ConfigProto(allow_soft_placement=True) # 最多占gpu资源的70% gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.7) # 开始不会给tensorflow全部gpu资源 而是按需增加 config.gpu_options.allow_growth = True x = tf.placeholder("float", [None, 784]) sess = tf.Session(config=config) with tf.variable_scope("regression"): print(model.regression(x)) y1, variables = model.regression(x) saver = tf.train.Saver(variables) regression_file = tf.train.latest_checkpoint("mnist/data/regreesion.ckpt") if regression_file is not None: saver.restore(sess, regression_file) with tf.variable_scope("convolutional"): keep_prob = tf.placeholder("float") y2, variables = model.convolutional(x, keep_prob) sess.run(tf.global_variables_initializer()) saver = tf.train.Saver(variables) convolutional_file = tf.train.latest_checkpoint( "mnist/data/convolutional.ckpt") if convolutional_file is not None: saver.restore(sess, convolutional_file) def regression(input): return sess.run(y1, feed_dict={x: input}).flatten().tolist() def convolutional(input): return sess.run( y2, feed_dict={ x: input, keep_prob: 1.0 }).flatten().tolist() app = Flask(__name__) app.config['JSON_AS_ASCII'] = False UPLOAD_FOLDER = 'upload' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER basedir = os.path.abspath(os.path.dirname(__file__)) ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'gif', 'GIF']) def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/upload') def upload_test(): return render_template('up.html') ## 上传 文件 前后端已经联通(可以实现批量上传,只是前端禁用了批量上传, 这里逻辑是单个和批量上传都可以) by hly # 上传文件 @app.route('/up_photo', methods=['POST'], strict_slashes=False) def api_upload(): file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER']) if not os.path.exists(file_dir): os.makedirs(file_dir) choose_ckpt = request.values.get("ckpt") print(choose_ckpt) f_list = request.files.getlist('photo') for f in f_list: print("filename:"+f.filename) if f and allowed_file(f.filename): fname = secure_filename(f.filename) print(fname) ext = fname.rsplit('.', 1)[1] new_filename = Pic_str().create_uuid() + '.' + ext f.save(os.path.join(file_dir, new_filename)) # ocr = CnOcr() # img_fp = os.path.join(file_dir, new_filename) # img = mx.image.imread(img_fp, 1) # res = ocr.ocr(img) # print("Predicted Chars:", res) # return jsonify({"success": 0, "msg": res}) # return jsonify({"success": 0, "msg": "success"}) # return jsonify({"success": 0, "msg": "上传成功"}) # else: # return jsonify({"error": 1001, "msg": "上传失败"}) return jsonify({"success": 0, "msg": "success"}) @app.route('/download/<string:filename>', methods=['GET']) def download(filename): if request.method == "GET": if os.path.isfile(os.path.join('upload', filename)): return send_from_directory('upload', filename, as_attachment=True) pass # show photo @app.route('/show/<string:filename>', methods=['GET']) def show_photo(filename): file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER']) if request.method == 'GET': if filename is None: pass else: image_data = open(os.path.join(file_dir, '%s' % filename), "rb").read() response = make_response(image_data) response.headers['Content-Type'] = 'image/png' return response else: pass # 路由 @app.route("/api/mnist", methods=['post']) def mnist(): input = ((255 - np.array(request.json, dtype=np.uint8)) / 255.0).reshape( 1, 784) output1 = regression(input) output2 = convolutional(input) return jsonify(results=[output1, output2]) ############################################################################### # 上传训练数据集 # 已实现 批量上传数据 到指定 数据集 @app.route('/up_train_data', methods=['POST'], strict_slashes=False) def api_upload_train_data(): file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER']) # 上传同时,前端会发送数据源Id,根据不同Id,保存到不同数据源 # dataSourceId=-1,说明是新建的数据源 # **** 还 需要实现 保存已有数据源的信息,有哪些数据源, # 有了数据源后,新建训练就可以选择不同数据源来训练 dataSourceName = request.values.get("dataSourceName") dataSourceId = request.values.get("dataSourceId") print('dataSourceName:'+dataSourceName) print('dataSourceId:' + dataSourceId) print('file_dir:'+file_dir) file_dir = os.path.join(file_dir,'dataSourceId',dataSourceId) if not os.path.exists(file_dir): os.makedirs(file_dir) f_list = request.files.getlist('upData') for f in f_list: print("filename:"+f.filename) if f and allowed_file(f.filename): fname = secure_filename(f.filename) print(fname) ext = fname.rsplit('.', 1)[1] new_filename = Pic_str().create_uuid() + '.' + ext f.save(os.path.join(file_dir, new_filename)) # ocr = CnOcr() # img_fp = os.path.join(file_dir, new_filename) # img = mx.image.imread(img_fp, 1) # res = ocr.ocr(img) # print("Predicted Chars:", res) # return jsonify({"success": 0, "msg": res}) # return jsonify({"success": 0, "msg": "success"}) # return jsonify({"success": 0, "msg": "上传成功"}) # else: # return jsonify({"error": 1001, "msg": "上传失败"}) return jsonify({"success": 0, "msg": "success"}) ## 开始训练 # 待完善 @app.route("/start_train", methods=['POST']) def start_train(): # dataSourceId是必须存在的, 根据dataSourceId 得到训练的数据集Id # 而 ckptId可以没有(前端传来<0,说明不要ckpt),不需要ckpt就是从新开始,如果有就是从这个ckpt开始训练。 dataSourceId = request.values.get("dataSourceId") ckptId = request.values.get("ckptId") print("start_train-- dataSourceId:"+str(dataSourceId)+" ckptId:"+str(ckptId)) ## 模拟开始训练过程 return jsonify({"success": 0, "msg": "接收到参数,开始训练!"}) ## 前往 某个训练记录 详情页面 #待完善 @app.route("/record/<int:recordId>") def record(recordId): ## recordId是 某个训练记录Id print("recordId:"+str(recordId)) ## 前端显示 这个训练 的 状态 , 所用数据集, 总运行时间,训练进度,准确率, 每轮chart 等。 详见前端显示 ## 模拟 生成 训练记录 详情 return render_template("record.html") # ********** 下面只设置了 获取 dataSource list和 check point list route请求, # ****** 还未设置某个dataSource、某个data、某个ckpt的 CRUD 的route, 前端已经实现了crud效果,这里看情况是否添加 ## 前端ajax传递获取 数据集列表请求 # 待完善 @app.route("/get_ds_list") def get_dataSource_list(): ## 模拟获取 数据集列表 return jsonify({"success": 0, "msg": "DataSource List!"}) ## 前往 某个数据集详情页面 #待完善 @app.route("/ds/<int:dataSourceId>") def dataSource(dataSourceId): # 前端传递 dataSourceId 数据集 Id # 根据 dataSourceId , 往前端发送 这个数据集 的详情(图片和label列表) print("dataSourceId:"+str(dataSourceId)) ## 模拟 生成 这个dataSourceId的数据集列表详情(图片和label列表) return render_template("data.html") ## 前端ajax传递获取 checkpoint 列表请求 # 待完善 @app.route("/get_ckpt_list") def get_ckpt_list(): ## 模拟获取 checkpoint 列表 return jsonify({"success": 0, "msg": "checkpoint List!"}) ## 前往 控制面板页面 # 待完善 @app.route("/dashboard") def dashboard(): ## 控制面板显示 总的 训练概览 详见前端显示 return render_template("dashboard.html") ## 前往 生成训练页面 @app.route("/train") def train(): return render_template("train.html") ## 前往 数据集列表页面 @app.route("/datalist") def datalist(): return render_template("datalist.html") ##################################################################################### @app.route("/") def main(): return render_template("index.html") if __name__ == "__main__": app.debug = True app.run(host='0.0.0.0', port=8000)
[ "flask.render_template", "flask.Flask", "numpy.array", "werkzeug.utils.secure_filename", "tensorflow.GPUOptions", "flask.jsonify", "os.path.exists", "flask.send_from_directory", "mnist.module.convolutional", "tensorflow.placeholder", "tensorflow.Session", "tensorflow.ConfigProto", "random.ra...
[((931, 972), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), '(allow_soft_placement=True)\n', (945, 972), True, 'import tensorflow as tf\n'), ((1003, 1053), 'tensorflow.GPUOptions', 'tf.GPUOptions', ([], {'per_process_gpu_memory_fraction': '(0.7)'}), '(per_process_gpu_memory_fraction=0.7)\n', (1016, 1053), True, 'import tensorflow as tf\n'), ((1131, 1167), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[None, 784]'], {}), "('float', [None, 784])\n", (1145, 1167), True, 'import tensorflow as tf\n'), ((1175, 1200), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (1185, 1200), True, 'import tensorflow as tf\n'), ((1320, 1345), 'tensorflow.train.Saver', 'tf.train.Saver', (['variables'], {}), '(variables)\n', (1334, 1345), True, 'import tensorflow as tf\n'), ((1364, 1420), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['"""mnist/data/regreesion.ckpt"""'], {}), "('mnist/data/regreesion.ckpt')\n", (1390, 1420), True, 'import tensorflow as tf\n'), ((1682, 1707), 'tensorflow.train.Saver', 'tf.train.Saver', (['variables'], {}), '(variables)\n', (1696, 1707), True, 'import tensorflow as tf\n'), ((1729, 1788), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['"""mnist/data/convolutional.ckpt"""'], {}), "('mnist/data/convolutional.ckpt')\n", (1755, 1788), True, 'import tensorflow as tf\n'), ((2123, 2138), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (2128, 2138), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((1208, 1239), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""regression"""'], {}), "('regression')\n", (1225, 1239), True, 'import tensorflow as tf\n'), ((1292, 1311), 'mnist.module.regression', 'model.regression', (['x'], {}), '(x)\n', (1308, 1311), True, 'from mnist import module as model\n'), ((1500, 1534), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""convolutional"""'], {}), "('convolutional')\n", (1517, 1534), True, 'import tensorflow as tf\n'), ((1552, 1575), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""'], {}), "('float')\n", (1566, 1575), True, 'import tensorflow as tf\n'), ((1596, 1629), 'mnist.module.convolutional', 'model.convolutional', (['x', 'keep_prob'], {}), '(x, keep_prob)\n', (1615, 1629), True, 'from mnist import module as model\n'), ((1639, 1672), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1670, 1672), True, 'import tensorflow as tf\n'), ((2271, 2296), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2286, 2296), False, 'import os\n'), ((2531, 2557), 'flask.render_template', 'render_template', (['"""up.html"""'], {}), "('up.html')\n", (2546, 2557), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((2727, 2777), 'os.path.join', 'os.path.join', (['basedir', "app.config['UPLOAD_FOLDER']"], {}), "(basedir, app.config['UPLOAD_FOLDER'])\n", (2739, 2777), False, 'import os\n'), ((2863, 2889), 'flask.request.values.get', 'request.values.get', (['"""ckpt"""'], {}), "('ckpt')\n", (2881, 2889), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((2926, 2956), 'flask.request.files.getlist', 'request.files.getlist', (['"""photo"""'], {}), "('photo')\n", (2947, 2956), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((3777, 3818), 'flask.jsonify', 'jsonify', (["{'success': 0, 'msg': 'success'}"], {}), "({'success': 0, 'msg': 'success'})\n", (3784, 3818), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((4199, 4249), 'os.path.join', 'os.path.join', (['basedir', "app.config['UPLOAD_FOLDER']"], {}), "(basedir, app.config['UPLOAD_FOLDER'])\n", (4211, 4249), False, 'import os\n'), ((4820, 4855), 'flask.jsonify', 'jsonify', ([], {'results': '[output1, output2]'}), '(results=[output1, output2])\n', (4827, 4855), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((5084, 5134), 'os.path.join', 'os.path.join', (['basedir', "app.config['UPLOAD_FOLDER']"], {}), "(basedir, app.config['UPLOAD_FOLDER'])\n", (5096, 5134), False, 'import os\n'), ((5296, 5332), 'flask.request.values.get', 'request.values.get', (['"""dataSourceName"""'], {}), "('dataSourceName')\n", (5314, 5332), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((5352, 5386), 'flask.request.values.get', 'request.values.get', (['"""dataSourceId"""'], {}), "('dataSourceId')\n", (5370, 5386), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((5520, 5572), 'os.path.join', 'os.path.join', (['file_dir', '"""dataSourceId"""', 'dataSourceId'], {}), "(file_dir, 'dataSourceId', dataSourceId)\n", (5532, 5572), False, 'import os\n'), ((5652, 5683), 'flask.request.files.getlist', 'request.files.getlist', (['"""upData"""'], {}), "('upData')\n", (5673, 5683), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((6504, 6545), 'flask.jsonify', 'jsonify', (["{'success': 0, 'msg': 'success'}"], {}), "({'success': 0, 'msg': 'success'})\n", (6511, 6545), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((6768, 6802), 'flask.request.values.get', 'request.values.get', (['"""dataSourceId"""'], {}), "('dataSourceId')\n", (6786, 6802), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((6816, 6844), 'flask.request.values.get', 'request.values.get', (['"""ckptId"""'], {}), "('ckptId')\n", (6834, 6844), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((6957, 7002), 'flask.jsonify', 'jsonify', (["{'success': 0, 'msg': '接收到参数,开始训练!'}"], {}), "({'success': 0, 'msg': '接收到参数,开始训练!'})\n", (6964, 7002), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((7250, 7280), 'flask.render_template', 'render_template', (['"""record.html"""'], {}), "('record.html')\n", (7265, 7280), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((7542, 7592), 'flask.jsonify', 'jsonify', (["{'success': 0, 'msg': 'DataSource List!'}"], {}), "({'success': 0, 'msg': 'DataSource List!'})\n", (7549, 7592), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((7871, 7899), 'flask.render_template', 'render_template', (['"""data.html"""'], {}), "('data.html')\n", (7886, 7899), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((8024, 8074), 'flask.jsonify', 'jsonify', (["{'success': 0, 'msg': 'checkpoint List!'}"], {}), "({'success': 0, 'msg': 'checkpoint List!'})\n", (8031, 8074), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((8180, 8213), 'flask.render_template', 'render_template', (['"""dashboard.html"""'], {}), "('dashboard.html')\n", (8195, 8213), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((8273, 8302), 'flask.render_template', 'render_template', (['"""train.html"""'], {}), "('train.html')\n", (8288, 8302), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((8369, 8401), 'flask.render_template', 'render_template', (['"""datalist.html"""'], {}), "('datalist.html')\n", (8384, 8401), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((8530, 8559), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (8545, 8559), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((503, 525), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (517, 525), False, 'import random\n'), ((1251, 1270), 'mnist.module.regression', 'model.regression', (['x'], {}), '(x)\n', (1267, 1270), True, 'from mnist import module as model\n'), ((2789, 2813), 'os.path.exists', 'os.path.exists', (['file_dir'], {}), '(file_dir)\n', (2803, 2813), False, 'import os\n'), ((2823, 2844), 'os.makedirs', 'os.makedirs', (['file_dir'], {}), '(file_dir)\n', (2834, 2844), False, 'import os\n'), ((5582, 5606), 'os.path.exists', 'os.path.exists', (['file_dir'], {}), '(file_dir)\n', (5596, 5606), False, 'import os\n'), ((5616, 5637), 'os.makedirs', 'os.makedirs', (['file_dir'], {}), '(file_dir)\n', (5627, 5637), False, 'import os\n'), ((3079, 3106), 'werkzeug.utils.secure_filename', 'secure_filename', (['f.filename'], {}), '(f.filename)\n', (3094, 3106), False, 'from werkzeug.utils import secure_filename\n'), ((3961, 3993), 'os.path.join', 'os.path.join', (['"""upload"""', 'filename'], {}), "('upload', filename)\n", (3973, 3993), False, 'import os\n'), ((4015, 4074), 'flask.send_from_directory', 'send_from_directory', (['"""upload"""', 'filename'], {'as_attachment': '(True)'}), "('upload', filename, as_attachment=True)\n", (4034, 4074), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((4449, 4474), 'flask.make_response', 'make_response', (['image_data'], {}), '(image_data)\n', (4462, 4474), False, 'from flask import Flask, render_template, jsonify, request, make_response, send_from_directory, abort\n'), ((5806, 5833), 'werkzeug.utils.secure_filename', 'secure_filename', (['f.filename'], {}), '(f.filename)\n', (5821, 5833), False, 'from werkzeug.utils import secure_filename\n'), ((423, 446), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (444, 446), False, 'import datetime\n'), ((3256, 3292), 'os.path.join', 'os.path.join', (['file_dir', 'new_filename'], {}), '(file_dir, new_filename)\n', (3268, 3292), False, 'import os\n'), ((5983, 6019), 'os.path.join', 'os.path.join', (['file_dir', 'new_filename'], {}), '(file_dir, new_filename)\n', (5995, 6019), False, 'import os\n'), ((4668, 4706), 'numpy.array', 'np.array', (['request.json'], {'dtype': 'np.uint8'}), '(request.json, dtype=np.uint8)\n', (4676, 4706), True, 'import numpy as np\n'), ((4372, 4411), 'os.path.join', 'os.path.join', (['file_dir', "('%s' % filename)"], {}), "(file_dir, '%s' % filename)\n", (4384, 4411), False, 'import os\n')]
import numpy as np import cv2 # This file is a set of commonly used functions by the viz scripts. It # is not meant to be run on its own def unblockshaped(arr, h, w, rgb=False): if rgb: n, nrows, ncols, nchannels = arr.shape return (arr.reshape(h//nrows, -1, nrows, ncols, nchannels) .swapaxes(1,2) .reshape(h, w, 3)) n, nrows, ncols = arr.shape return (arr.reshape(h//nrows, -1, nrows, ncols) .swapaxes(1,2) .reshape(h, w)) def reshape_to_row(arr, side=28, rgb=False): if rgb: grid = np.array([np.reshape(img, (side, side, 3)) for img in arr]) else: grid = np.array([np.reshape(img, (side, side)) for img in arr]) return unblockshaped(grid, int(side), int(side * grid.shape[0]), rgb=rgb) def reshape_to_grid(arr, side=28, rgb=False): if rgb: grid = np.array([np.reshape(img, (side, side, 3)) for img in arr]) else: grid = np.array([np.reshape(img, (side, side)) for img in arr]) size = int(side * np.sqrt(grid.shape[0])) return unblockshaped(grid, size, size, rgb=rgb)
[ "numpy.sqrt", "numpy.reshape" ]
[((1030, 1052), 'numpy.sqrt', 'np.sqrt', (['grid.shape[0]'], {}), '(grid.shape[0])\n', (1037, 1052), True, 'import numpy as np\n'), ((582, 614), 'numpy.reshape', 'np.reshape', (['img', '(side, side, 3)'], {}), '(img, (side, side, 3))\n', (592, 614), True, 'import numpy as np\n'), ((667, 696), 'numpy.reshape', 'np.reshape', (['img', '(side, side)'], {}), '(img, (side, side))\n', (677, 696), True, 'import numpy as np\n'), ((876, 908), 'numpy.reshape', 'np.reshape', (['img', '(side, side, 3)'], {}), '(img, (side, side, 3))\n', (886, 908), True, 'import numpy as np\n'), ((961, 990), 'numpy.reshape', 'np.reshape', (['img', '(side, side)'], {}), '(img, (side, side))\n', (971, 990), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ 201901, Dr. <NAME>, Beijing & Xinglong, NAOC Light_Curve """ import numpy as np import astropy.io.fits as fits from .utils import loadlist, datestr, logfile, conf, meanclip from .cata import match def offset(ini_file, sci_lst, catalog_suffix, offset_file, ref_id=0, out_path="", log=None): """ photometry :param ini_file: :param sci_lst: list file of scientific fits files :param catalog_suffix: suffix of catalog files :param offset_file: offset file :param ref_id: the file chosen as the reference base :param out_path: path of out files :param log: :return: """ ini = conf(ini_file) lf = logfile(log, level=ini["log_level"]) # load list catf = loadlist(sci_lst, middlefix=catalog_suffix, changepath=out_path) nf = len(catf) lf.show("{:03d} catalog files".format(nf), logfile.DEBUG) # prepare an empty catalog cube xy_off = np.zeros((6, nf)) n_off = np.zeros(nf, dtype=int) cat_ref = fits.getdata(catf[ref_id], 2) goodix = np.where(cat_ref[ini["se_err"]] < ini["good_err"])[0] x_ref = cat_ref[goodix][ini["se_x"]] y_ref = cat_ref[goodix][ini["se_y"]] m_ref = cat_ref[goodix][ini["se_mag"]] lf.show("Load {:03d}/{:03d}: N={:4d}/{:4d} Reference {}".format( ref_id, nf, len(goodix), len(cat_ref), catf[ref_id]), logfile.DEBUG) # load images and process for f in range(nf): if f != ref_id: cat_k = fits.getdata(catf[f], 2) goodix = np.where(cat_k[ini["se_err"]] < ini["good_err"])[0] x_k = cat_k[goodix][ini["se_x"]] y_k = cat_k[goodix][ini["se_y"]] m_k = cat_k[goodix][ini["se_mag"]] lim = ini["offset_max"] lf.show("Load {:3d}/{:3d}: N={:4d}/{:4d} {}".format( f, nf, len(goodix), len(cat_k), catf[f]), logfile.DEBUG) r = 0 dxm, dxs = dym, dys = dmm, dms = drm, drs = 0.0, np.nan n = 0 while lim > ini["offset_min"] and r < ini["offset_iter"]: r += 1 ix_r, ix_k, dis = match(x_ref, y_ref, x_k + xy_off[0, f], y_k + xy_off[2, f], lim) n = len(ix_r) dx = x_ref[ix_r] - x_k[ix_k] dy = y_ref[ix_r] - y_k[ix_k] dm = m_ref[ix_r] - m_k[ix_k] dr = np.sqrt(dx * dx + dy * dy) dxm, dxs = meanclip(dx) dym, dys = meanclip(dy) dmm, dms = meanclip(dm) drm, drs = meanclip(dr) lf.show(" K={:1d} N={:4d} X={:7.3f}+-{:7.4f} Y={:7.3f}+-{:7.4f} R={:7.3f}+-{:7.4f} Mag={:7.3f}+-{:7.4f}".format( r, n, dxm, dxs, dym, dys, drm, drs, dmm, dms), logfile.DEBUG) lim = drs * ini["offset_factor"] xy_off[:, f] = dxm, dxs, dym, dys, dmm, dms n_off[f] = n with open(offset_file, "w") as ff: for f in range(nf): ff.write("{:3d} {:40s} {:4d} {:7.3f} {:7.4f} {:7.3f} {:7.4f} {:7.3f} {:7.4f}\n".format( f, catf[f], n_off[f], xy_off[0, f], xy_off[1, f], xy_off[2, f], xy_off[3, f], xy_off[4, f], xy_off[5, f] )) lf.show("Report save to {}".format(offset_file), logfile.DEBUG) lf.close()
[ "numpy.where", "numpy.zeros", "numpy.sqrt", "astropy.io.fits.getdata" ]
[((944, 961), 'numpy.zeros', 'np.zeros', (['(6, nf)'], {}), '((6, nf))\n', (952, 961), True, 'import numpy as np\n'), ((974, 997), 'numpy.zeros', 'np.zeros', (['nf'], {'dtype': 'int'}), '(nf, dtype=int)\n', (982, 997), True, 'import numpy as np\n'), ((1012, 1041), 'astropy.io.fits.getdata', 'fits.getdata', (['catf[ref_id]', '(2)'], {}), '(catf[ref_id], 2)\n', (1024, 1041), True, 'import astropy.io.fits as fits\n'), ((1055, 1105), 'numpy.where', 'np.where', (["(cat_ref[ini['se_err']] < ini['good_err'])"], {}), "(cat_ref[ini['se_err']] < ini['good_err'])\n", (1063, 1105), True, 'import numpy as np\n'), ((1479, 1503), 'astropy.io.fits.getdata', 'fits.getdata', (['catf[f]', '(2)'], {}), '(catf[f], 2)\n', (1491, 1503), True, 'import astropy.io.fits as fits\n'), ((1525, 1573), 'numpy.where', 'np.where', (["(cat_k[ini['se_err']] < ini['good_err'])"], {}), "(cat_k[ini['se_err']] < ini['good_err'])\n", (1533, 1573), True, 'import numpy as np\n'), ((2370, 2396), 'numpy.sqrt', 'np.sqrt', (['(dx * dx + dy * dy)'], {}), '(dx * dx + dy * dy)\n', (2377, 2396), True, 'import numpy as np\n')]
# This is functions to repick import numpy as np # generate recombined spots def generate_recombined_spots(repeat_cand_spots, repeat_ids, original_cand_spots, original_ids): """Function to re-assemble fitted original candidate spots and repeat candidate spots to perform spot repick to determine relabeling spots """ ## check inputs if len(repeat_cand_spots) != len(repeat_ids): raise IndexError(f"Wrong length of repeat candidate spots") if len(original_cand_spots) != len(original_ids): raise IndexError(f"Wrong length of original candidate spots") # initialize recombined spots recombined_cand_spots = [_pts for _pts in original_cand_spots] # loop through repeated spots for _id, _spots in zip(repeat_ids, repeat_cand_spots): _ind = np.where(np.array(original_ids)==_id)[0] if len(_ind) == 1: _ind = _ind[0] else: raise ValueError(f"index for region {_id} has {_ind} matches, not unique!") recombined_cand_spots[_ind] = _spots return recombined_cand_spots
[ "numpy.array" ]
[((822, 844), 'numpy.array', 'np.array', (['original_ids'], {}), '(original_ids)\n', (830, 844), True, 'import numpy as np\n')]
import numpy as np import scipy # from sksparse.cholmod import cholesky # It works (from Terminal). from scipy.sparse.linalg import spsolve import time import sys, os sys.path.append(os.path.dirname(sys.path[0])) from elementLibrary import stiffnessMatrix, shapeFunction from otherFunctions import numericalIntegration from linearSolvers import AMORE from meshTools import toDC def lowerOrderFE(inputData): """The solver for lower order finite elements (4-node quads & 3-node triangles).""" startTime=time.time() parameters=inputData[0] # Material matrices. materialList=inputData[6] materialMatrix=[None]*len(materialList) for i in range(len(materialList)): materialMatrix[i]=twoDMaterialMatrix(materialList[i],parameters[1]) # Assemble stiffness matrix. coordinates=inputData[5] meshes=inputData[3] materialMeshList=inputData[4] Iglo=[] Jglo=[] Vglo=[] for i in range(len(meshes[0])): coord=AMORE.getCoord(coordinates,meshes[0][i]) if len(meshes[0][i])==3: Kloc=stiffnessMatrix.triFE(coord,materialMatrix[materialMeshList[0][i]]) elif len(meshes[0][i])==4: Kloc=stiffnessMatrix.quadFE(coord,materialMatrix[materialMeshList[0][i]]) else: raise ValueError("Wrong element numbering!") Iloc,Jloc,Vloc=stiffnessMatrix.sparsifyElementMatrix(Kloc,meshes[0][i]) Iglo.extend(Iloc) Jglo.extend(Jloc) Vglo.extend(Vloc) Iglo=np.array(Iglo,dtype=int) Jglo=np.array(Jglo,dtype=int) Vglo=np.array(Vglo,dtype='d') Kglo=scipy.sparse.coo_matrix((Vglo,(Iglo,Jglo)),shape=(2*len(coordinates),2*len(coordinates))).tocsr() print("Assembling stiffness matrix costs %s seconds."%(time.time()-startTime)) startTime=time.time() # Force term. indForce=inputData[-2] if indForce[0]: # Body force is imposed. pass forceList=inputData[-1] nInt=2 if indForce[1]: nInt+=3 # Customized boundary force. pos,wei=numericalIntegration.gaussQuad(nInt) fglo=np.zeros((2*len(coordinates),1)) for i in range(len(forceList)//2): node1=forceList[2*i][0] node2=forceList[2*i+1][0] length=lenEdge(coordinates[node1],coordinates[node2]) force1=np.array([forceList[2*i][1:3]]).transpose() force2=np.array([forceList[2*i+1][1:3]]).transpose() floc=np.zeros((4,1)) for j in range(nInt): Nmat=shapeFunction.oneDLinear(pos[j]) force=Nmat[0,0]*force1+Nmat[0,2]*force2 floc+=0.5*wei[j]*length*np.matmul(Nmat.transpose(),force) fglo[2*node1:2*node1+2,0]+=floc[0:2,0] fglo[2*node2:2*node2+2,0]+=floc[2:4,0] print("Calculating force term costs %s seconds."%(time.time()-startTime)) startTime=time.time() # Impose constraints. fixList=np.zeros((2*len(coordinates),1)) fixIndexList=np.zeros((2*len(coordinates),1),dtype=int) constraintList=inputData[-3] # Very important!!! Sort the constraints!!! constraintList.sort(key=lambda item:item[0]) for i in constraintList: if i[1]: fixList[2*i[0]]=i[3] fixIndexList[2*i[0]]=1 if i[2]: fixList[2*i[0]+1]=i[4] fixIndexList[2*i[0]+1]=1 # Solve. fglo-=(Kglo.dot(fixList)) Kglo_complete=Kglo.copy() Kglo=Kglo.tolil() count=0 for i in constraintList: if i[1]: delete_row_lil(Kglo,2*i[0]-count) fglo=np.delete(fglo,2*i[0]-count) count+=1 if i[2]: delete_row_lil(Kglo,2*i[0]+1-count) fglo=np.delete(fglo,2*i[0]+1-count) count+=1 Kglo=Kglo.transpose() count=0 for i in constraintList: if i[1]: delete_row_lil(Kglo,2*i[0]-count) count+=1 if i[2]: delete_row_lil(Kglo,2*i[0]+1-count) count+=1 print("Imposing constraints costs %s seconds."%(time.time()-startTime)) startTime=time.time() Kglo=Kglo.tocsc() print("Number of non-zero sparse matrix entries = %s."%Kglo.count_nonzero()) # factor=cholesky(Kglo) # disp=factor(fglo) disp=spsolve(Kglo,fglo) print("Solving the linear system costs %s seconds."%(time.time()-startTime)) # The complete displacement solution: displacement=np.zeros((2*len(coordinates),1)) count=0 for i in range(2*len(coordinates)): if fixIndexList[i]: displacement[i]=fixList[i] count+=1 else: displacement[i]=disp[i-count] energy=0.5*displacement.transpose()@Kglo_complete@displacement return displacement,energy def ICMFE(inputData): """The solver for (4-node) ICM finite elements. Warning: The code is only for squares. For general quadrilaterals, the formulation needs to be modified to pass patch tests.""" startTime=time.time() parameters=inputData[0] # Material matrices. materialList=inputData[6] materialMatrix=[None]*len(materialList) for i in range(len(materialList)): materialMatrix[i]=twoDMaterialMatrix(materialList[i],parameters[1]) # Assemble stiffness matrix. coordinates=inputData[5] meshes=inputData[3] materialMeshList=inputData[4] Iglo=[] Jglo=[] Vglo=[] for i in range(len(meshes[0])): coord=AMORE.getCoord(coordinates,meshes[0][i]) if len(meshes[0][i])==4: Kloc,_,_=stiffnessMatrix.ICMFE(coord,materialMatrix[materialMeshList[0][i]]) else: raise ValueError("Wrong element numbering!") Iloc,Jloc,Vloc=stiffnessMatrix.sparsifyElementMatrix(Kloc,meshes[0][i]) Iglo.extend(Iloc) Jglo.extend(Jloc) Vglo.extend(Vloc) Iglo=np.array(Iglo,dtype=int) Jglo=np.array(Jglo,dtype=int) Vglo=np.array(Vglo,dtype='d') Kglo=scipy.sparse.coo_matrix((Vglo,(Iglo,Jglo)),shape=(2*len(coordinates),2*len(coordinates))).tocsr() print("Assembling stiffness matrix costs %s seconds."%(time.time()-startTime)) startTime=time.time() # Force term. indForce=inputData[-2] if indForce[0]: # Body force is imposed. pass forceList=inputData[-1] nInt=2 if indForce[1]: nInt+=3 # Customized boundary force. pos,wei=numericalIntegration.gaussQuad(nInt) fglo=np.zeros((2*len(coordinates),1)) for i in range(len(forceList)//2): node1=forceList[2*i][0] node2=forceList[2*i+1][0] length=lenEdge(coordinates[node1],coordinates[node2]) force1=np.array([forceList[2*i][1:3]]).transpose() force2=np.array([forceList[2*i+1][1:3]]).transpose() floc=np.zeros((4,1)) for j in range(nInt): Nmat=shapeFunction.oneDLinear(pos[j]) force=Nmat[0,0]*force1+Nmat[0,2]*force2 floc+=0.5*wei[j]*length*np.matmul(Nmat.transpose(),force) fglo[2*node1:2*node1+2,0]+=floc[0:2,0] fglo[2*node2:2*node2+2,0]+=floc[2:4,0] print("Calculating force term costs %s seconds."%(time.time()-startTime)) startTime=time.time() # Impose constraints. fixList=np.zeros((2*len(coordinates),1)) fixIndexList=np.zeros((2*len(coordinates),1),dtype=int) constraintList=inputData[-3] # Very important!!! Sort the constraints!!! constraintList.sort(key=lambda item:item[0]) for i in constraintList: if i[1]: fixList[2*i[0]]=i[3] fixIndexList[2*i[0]]=1 if i[2]: fixList[2*i[0]+1]=i[4] fixIndexList[2*i[0]+1]=1 # Solve. fglo-=(Kglo.dot(fixList)) Kglo_complete=Kglo.copy() Kglo=Kglo.tolil() count=0 for i in constraintList: if i[1]: delete_row_lil(Kglo,2*i[0]-count) fglo=np.delete(fglo,2*i[0]-count) count+=1 if i[2]: delete_row_lil(Kglo,2*i[0]+1-count) fglo=np.delete(fglo,2*i[0]+1-count) count+=1 Kglo=Kglo.transpose() count=0 for i in constraintList: if i[1]: delete_row_lil(Kglo,2*i[0]-count) count+=1 if i[2]: delete_row_lil(Kglo,2*i[0]+1-count) count+=1 print("Imposing constraints costs %s seconds."%(time.time()-startTime)) startTime=time.time() Kglo=Kglo.tocsc() print("Number of non-zero sparse matrix entries = %s."%Kglo.count_nonzero()) # factor=cholesky(Kglo) # disp=factor(fglo) disp=spsolve(Kglo,fglo) print("Solving the linear system costs %s seconds."%(time.time()-startTime)) # The complete displacement solution: displacement=np.zeros((2*len(coordinates),1)) count=0 for i in range(2*len(coordinates)): if fixIndexList[i]: displacement[i]=fixList[i] count+=1 else: displacement[i]=disp[i-count] energy=0.5*displacement.transpose()@Kglo_complete@displacement return displacement,energy def quadraticFE(inputData): """The solver for second order finite elements (9-node quads & 6-node triangles).""" startTime=time.time() parameters=inputData[0] # Material matrices. materialList=inputData[6] materialMatrix=[None]*len(materialList) for i in range(len(materialList)): materialMatrix[i]=twoDMaterialMatrix(materialList[i],parameters[1]) # Assemble stiffness matrix. coordinates=inputData[5] meshes=inputData[3] materialMeshList=inputData[4] nodeElements=toDC.nodeElementList(coordinates,meshes) Iglo=[] Jglo=[] Vglo=[] for i in range(len(meshes[0])): coord=AMORE.getCoord(coordinates,meshes[0][i]) if len(meshes[0][i])==6: Kloc=stiffnessMatrix.triQuadFE(coord,materialMatrix[materialMeshList[0][i]]) elif len(meshes[0][i])==9: Kloc=stiffnessMatrix.quadQuadFE(coord,materialMatrix[materialMeshList[0][i]]) else: raise ValueError("Wrong element numbering!") Iloc,Jloc,Vloc=stiffnessMatrix.sparsifyElementMatrix(Kloc,meshes[0][i]) Iglo.extend(Iloc) Jglo.extend(Jloc) Vglo.extend(Vloc) Iglo=np.array(Iglo,dtype=int) Jglo=np.array(Jglo,dtype=int) Vglo=np.array(Vglo,dtype='d') Kglo=scipy.sparse.coo_matrix((Vglo,(Iglo,Jglo)),shape=(2*len(coordinates),2*len(coordinates))).tocsr() print("Assembling stiffness matrix costs %s seconds."%(time.time()-startTime)) startTime=time.time() # Force term. indForce=inputData[-2] if indForce[0]: # Body force is imposed. pass forceList=inputData[-1] nInt=3 if indForce[1]: nInt+=2 # Customized boundary force. pos,wei=numericalIntegration.gaussQuad(nInt) fglo=np.zeros((2*len(coordinates),1)) for i in range(len(forceList)//2): node1=forceList[2*i][0] node2=forceList[2*i+1][0] # length=lenEdge(coordinates[node1],coordinates[node2]) # Find the element. elementPosition=(set(nodeElements[node1]) & set(nodeElements[node2])).pop() numbering=meshes[elementPosition[0]][elementPosition[1]] node3=findMidNode(numbering,node1,node2) force1=np.array([forceList[2*i][1:3]]).transpose() force2=np.array([forceList[2*i+1][1:3]]).transpose() floc=np.zeros((6,1)) coord=np.array([coordinates[node1],coordinates[node2],[0.0,0.0]]) if coordinates[node3]: coord[2,:]=np.array(coordinates[node3]) else: coord[2,:]=0.5*(coord[0,:]+coord[1,:]) for j in range(nInt): # Only support linear force distribution. # Otherwise, use customized boundary force. Nmat=shapeFunction.oneDLinear(pos[j]) force=Nmat[0,0]*force1+Nmat[0,2]*force2 quadNmat,Jacobian=shapeFunction.oneDQuadratic(pos[j],coord) floc+=wei[j]*Jacobian*np.matmul(quadNmat.transpose(),force) fglo[2*node1:2*node1+2,0]+=floc[0:2,0] fglo[2*node2:2*node2+2,0]+=floc[2:4,0] fglo[2*node3:2*node3+2,0]+=floc[4:6,0] print("Calculating force term costs %s seconds."%(time.time()-startTime)) startTime=time.time() # Impose constraints. fixList=np.zeros((2*len(coordinates),1)) fixIndexList=np.zeros((2*len(coordinates),1),dtype=int) constraintList=inputData[-3] # Very important!!! Sort the constraints!!! constraintList.sort(key=lambda item:item[0]) for i in constraintList: if i[1]: fixList[2*i[0]]=i[3] fixIndexList[2*i[0]]=1 if i[2]: fixList[2*i[0]+1]=i[4] fixIndexList[2*i[0]+1]=1 # Solve. fglo-=(Kglo.dot(fixList)) Kglo_complete=Kglo.copy() Kglo=Kglo.tolil() count=0 for i in constraintList: if i[1]: delete_row_lil(Kglo,2*i[0]-count) fglo=np.delete(fglo,2*i[0]-count) count+=1 if i[2]: delete_row_lil(Kglo,2*i[0]+1-count) fglo=np.delete(fglo,2*i[0]+1-count) count+=1 Kglo=Kglo.transpose() count=0 for i in constraintList: if i[1]: delete_row_lil(Kglo,2*i[0]-count) count+=1 if i[2]: delete_row_lil(Kglo,2*i[0]+1-count) count+=1 print("Imposing constraints costs %s seconds."%(time.time()-startTime)) startTime=time.time() Kglo=Kglo.tocsc() # factor=cholesky(Kglo) # disp=factor(fglo) disp=spsolve(Kglo,fglo) print("Solving the linear system costs %s seconds."%(time.time()-startTime)) # The complete displacement solution: displacement=np.zeros((2*len(coordinates),1)) count=0 for i in range(2*len(coordinates)): if fixIndexList[i]: displacement[i]=fixList[i] count+=1 else: displacement[i]=disp[i-count] energy=0.5*displacement.transpose()@Kglo_complete@displacement return displacement,energy def findMidNode(numbering,node1,node2): if len(numbering)==6: temp=[1,2,0] for i in range(3): if (numbering[i]==node1 and numbering[temp[i]]==node2) or \ (numbering[i]==node2 and numbering[temp[i]]==node1): return numbering[i+3] elif len(numbering)==9: temp=[1,2,3,0] for i in range(4): if (numbering[i]==node1 and numbering[temp[i]]==node2) or \ (numbering[i]==node2 and numbering[temp[i]]==node1): return numbering[i+4] return None def twoDMaterialMatrix(material,problemType): """Input: material: [E,nu]; problemType: 1 -- Plane stress; 2 -- Plane strain.""" if problemType==1: # Plane stress Dmat=np.array([[material[0]/(1.0-material[1]**2),material[0]*material[1]/(1.0-material[1]**2),0.0],\ [material[0]*material[1]/(1.0-material[1]**2),material[0]/(1.0-material[1]**2),0.0],\ [0.0,0.0,material[0]/2.0/(1.0+material[1])]]) elif problemType==2: #Plane strain cc=material[0]*(1.0-material[1])/(1.0+material[1])/(1.0-2.0*material[1]) Dmat=np.array([[cc,cc*material[1]/(1.0-material[1]),0.0],\ [cc*material[1]/(1.0-material[1]),cc,0.0],\ [0.0,0.0,cc*(1.0-2.0*material[1])/(2.0*(1.0-material[1]))]]) else: raise ValueError("No such problem type!") return Dmat def lenEdge(coord1,coord2): return ((coord1[0]-coord2[0])**2+(coord1[1]-coord2[1])**2)**0.5 def delete_row_lil(matrix,i): if not isinstance(matrix,scipy.sparse.lil_matrix): raise ValueError("The matrix should be in LIL format!") matrix.rows=np.delete(matrix.rows,i) matrix.data=np.delete(matrix.data,i) matrix._shape=(matrix._shape[0]-1,matrix._shape[1]) if __name__=="__main__": pass
[ "scipy.sparse.linalg.spsolve", "meshTools.toDC.nodeElementList", "elementLibrary.stiffnessMatrix.triFE", "numpy.delete", "elementLibrary.stiffnessMatrix.quadFE", "elementLibrary.shapeFunction.oneDQuadratic", "elementLibrary.stiffnessMatrix.triQuadFE", "os.path.dirname", "numpy.array", "numpy.zeros...
[((184, 212), 'os.path.dirname', 'os.path.dirname', (['sys.path[0]'], {}), '(sys.path[0])\n', (199, 212), False, 'import sys, os\n'), ((511, 522), 'time.time', 'time.time', ([], {}), '()\n', (520, 522), False, 'import time\n'), ((1499, 1524), 'numpy.array', 'np.array', (['Iglo'], {'dtype': 'int'}), '(Iglo, dtype=int)\n', (1507, 1524), True, 'import numpy as np\n'), ((1533, 1558), 'numpy.array', 'np.array', (['Jglo'], {'dtype': 'int'}), '(Jglo, dtype=int)\n', (1541, 1558), True, 'import numpy as np\n'), ((1567, 1592), 'numpy.array', 'np.array', (['Vglo'], {'dtype': '"""d"""'}), "(Vglo, dtype='d')\n", (1575, 1592), True, 'import numpy as np\n'), ((1802, 1813), 'time.time', 'time.time', ([], {}), '()\n', (1811, 1813), False, 'import time\n'), ((2029, 2065), 'otherFunctions.numericalIntegration.gaussQuad', 'numericalIntegration.gaussQuad', (['nInt'], {}), '(nInt)\n', (2059, 2065), False, 'from otherFunctions import numericalIntegration\n'), ((2823, 2834), 'time.time', 'time.time', ([], {}), '()\n', (2832, 2834), False, 'import time\n'), ((4045, 4056), 'time.time', 'time.time', ([], {}), '()\n', (4054, 4056), False, 'import time\n'), ((4227, 4246), 'scipy.sparse.linalg.spsolve', 'spsolve', (['Kglo', 'fglo'], {}), '(Kglo, fglo)\n', (4234, 4246), False, 'from scipy.sparse.linalg import spsolve\n'), ((4941, 4952), 'time.time', 'time.time', ([], {}), '()\n', (4950, 4952), False, 'import time\n'), ((5812, 5837), 'numpy.array', 'np.array', (['Iglo'], {'dtype': 'int'}), '(Iglo, dtype=int)\n', (5820, 5837), True, 'import numpy as np\n'), ((5846, 5871), 'numpy.array', 'np.array', (['Jglo'], {'dtype': 'int'}), '(Jglo, dtype=int)\n', (5854, 5871), True, 'import numpy as np\n'), ((5880, 5905), 'numpy.array', 'np.array', (['Vglo'], {'dtype': '"""d"""'}), "(Vglo, dtype='d')\n", (5888, 5905), True, 'import numpy as np\n'), ((6115, 6126), 'time.time', 'time.time', ([], {}), '()\n', (6124, 6126), False, 'import time\n'), ((6342, 6378), 'otherFunctions.numericalIntegration.gaussQuad', 'numericalIntegration.gaussQuad', (['nInt'], {}), '(nInt)\n', (6372, 6378), False, 'from otherFunctions import numericalIntegration\n'), ((7136, 7147), 'time.time', 'time.time', ([], {}), '()\n', (7145, 7147), False, 'import time\n'), ((8358, 8369), 'time.time', 'time.time', ([], {}), '()\n', (8367, 8369), False, 'import time\n'), ((8540, 8559), 'scipy.sparse.linalg.spsolve', 'spsolve', (['Kglo', 'fglo'], {}), '(Kglo, fglo)\n', (8547, 8559), False, 'from scipy.sparse.linalg import spsolve\n'), ((9164, 9175), 'time.time', 'time.time', ([], {}), '()\n', (9173, 9175), False, 'import time\n'), ((9565, 9606), 'meshTools.toDC.nodeElementList', 'toDC.nodeElementList', (['coordinates', 'meshes'], {}), '(coordinates, meshes)\n', (9585, 9606), False, 'from meshTools import toDC\n'), ((10219, 10244), 'numpy.array', 'np.array', (['Iglo'], {'dtype': 'int'}), '(Iglo, dtype=int)\n', (10227, 10244), True, 'import numpy as np\n'), ((10253, 10278), 'numpy.array', 'np.array', (['Jglo'], {'dtype': 'int'}), '(Jglo, dtype=int)\n', (10261, 10278), True, 'import numpy as np\n'), ((10287, 10312), 'numpy.array', 'np.array', (['Vglo'], {'dtype': '"""d"""'}), "(Vglo, dtype='d')\n", (10295, 10312), True, 'import numpy as np\n'), ((10522, 10533), 'time.time', 'time.time', ([], {}), '()\n', (10531, 10533), False, 'import time\n'), ((10749, 10785), 'otherFunctions.numericalIntegration.gaussQuad', 'numericalIntegration.gaussQuad', (['nInt'], {}), '(nInt)\n', (10779, 10785), False, 'from otherFunctions import numericalIntegration\n'), ((12202, 12213), 'time.time', 'time.time', ([], {}), '()\n', (12211, 12213), False, 'import time\n'), ((13428, 13439), 'time.time', 'time.time', ([], {}), '()\n', (13437, 13439), False, 'import time\n'), ((13529, 13548), 'scipy.sparse.linalg.spsolve', 'spsolve', (['Kglo', 'fglo'], {}), '(Kglo, fglo)\n', (13536, 13548), False, 'from scipy.sparse.linalg import spsolve\n'), ((15728, 15753), 'numpy.delete', 'np.delete', (['matrix.rows', 'i'], {}), '(matrix.rows, i)\n', (15737, 15753), True, 'import numpy as np\n'), ((15769, 15794), 'numpy.delete', 'np.delete', (['matrix.data', 'i'], {}), '(matrix.data, i)\n', (15778, 15794), True, 'import numpy as np\n'), ((982, 1023), 'linearSolvers.AMORE.getCoord', 'AMORE.getCoord', (['coordinates', 'meshes[0][i]'], {}), '(coordinates, meshes[0][i])\n', (996, 1023), False, 'from linearSolvers import AMORE\n'), ((1354, 1411), 'elementLibrary.stiffnessMatrix.sparsifyElementMatrix', 'stiffnessMatrix.sparsifyElementMatrix', (['Kloc', 'meshes[0][i]'], {}), '(Kloc, meshes[0][i])\n', (1391, 1411), False, 'from elementLibrary import stiffnessMatrix, shapeFunction\n'), ((2411, 2427), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {}), '((4, 1))\n', (2419, 2427), True, 'import numpy as np\n'), ((5412, 5453), 'linearSolvers.AMORE.getCoord', 'AMORE.getCoord', (['coordinates', 'meshes[0][i]'], {}), '(coordinates, meshes[0][i])\n', (5426, 5453), False, 'from linearSolvers import AMORE\n'), ((5667, 5724), 'elementLibrary.stiffnessMatrix.sparsifyElementMatrix', 'stiffnessMatrix.sparsifyElementMatrix', (['Kloc', 'meshes[0][i]'], {}), '(Kloc, meshes[0][i])\n', (5704, 5724), False, 'from elementLibrary import stiffnessMatrix, shapeFunction\n'), ((6724, 6740), 'numpy.zeros', 'np.zeros', (['(4, 1)'], {}), '((4, 1))\n', (6732, 6740), True, 'import numpy as np\n'), ((9694, 9735), 'linearSolvers.AMORE.getCoord', 'AMORE.getCoord', (['coordinates', 'meshes[0][i]'], {}), '(coordinates, meshes[0][i])\n', (9708, 9735), False, 'from linearSolvers import AMORE\n'), ((10074, 10131), 'elementLibrary.stiffnessMatrix.sparsifyElementMatrix', 'stiffnessMatrix.sparsifyElementMatrix', (['Kloc', 'meshes[0][i]'], {}), '(Kloc, meshes[0][i])\n', (10111, 10131), False, 'from elementLibrary import stiffnessMatrix, shapeFunction\n'), ((11360, 11376), 'numpy.zeros', 'np.zeros', (['(6, 1)'], {}), '((6, 1))\n', (11368, 11376), True, 'import numpy as np\n'), ((11390, 11452), 'numpy.array', 'np.array', (['[coordinates[node1], coordinates[node2], [0.0, 0.0]]'], {}), '([coordinates[node1], coordinates[node2], [0.0, 0.0]])\n', (11398, 11452), True, 'import numpy as np\n'), ((14792, 15071), 'numpy.array', 'np.array', (['[[material[0] / (1.0 - material[1] ** 2), material[0] * material[1] / (1.0 -\n material[1] ** 2), 0.0], [material[0] * material[1] / (1.0 - material[1\n ] ** 2), material[0] / (1.0 - material[1] ** 2), 0.0], [0.0, 0.0, \n material[0] / 2.0 / (1.0 + material[1])]]'], {}), '([[material[0] / (1.0 - material[1] ** 2), material[0] * material[1\n ] / (1.0 - material[1] ** 2), 0.0], [material[0] * material[1] / (1.0 -\n material[1] ** 2), material[0] / (1.0 - material[1] ** 2), 0.0], [0.0, \n 0.0, material[0] / 2.0 / (1.0 + material[1])]])\n', (14800, 15071), True, 'import numpy as np\n'), ((1074, 1142), 'elementLibrary.stiffnessMatrix.triFE', 'stiffnessMatrix.triFE', (['coord', 'materialMatrix[materialMeshList[0][i]]'], {}), '(coord, materialMatrix[materialMeshList[0][i]])\n', (1095, 1142), False, 'from elementLibrary import stiffnessMatrix, shapeFunction\n'), ((2475, 2507), 'elementLibrary.shapeFunction.oneDLinear', 'shapeFunction.oneDLinear', (['pos[j]'], {}), '(pos[j])\n', (2499, 2507), False, 'from elementLibrary import stiffnessMatrix, shapeFunction\n'), ((3531, 3564), 'numpy.delete', 'np.delete', (['fglo', '(2 * i[0] - count)'], {}), '(fglo, 2 * i[0] - count)\n', (3540, 3564), True, 'import numpy as np\n'), ((3663, 3700), 'numpy.delete', 'np.delete', (['fglo', '(2 * i[0] + 1 - count)'], {}), '(fglo, 2 * i[0] + 1 - count)\n', (3672, 3700), True, 'import numpy as np\n'), ((5508, 5576), 'elementLibrary.stiffnessMatrix.ICMFE', 'stiffnessMatrix.ICMFE', (['coord', 'materialMatrix[materialMeshList[0][i]]'], {}), '(coord, materialMatrix[materialMeshList[0][i]])\n', (5529, 5576), False, 'from elementLibrary import stiffnessMatrix, shapeFunction\n'), ((6788, 6820), 'elementLibrary.shapeFunction.oneDLinear', 'shapeFunction.oneDLinear', (['pos[j]'], {}), '(pos[j])\n', (6812, 6820), False, 'from elementLibrary import stiffnessMatrix, shapeFunction\n'), ((7844, 7877), 'numpy.delete', 'np.delete', (['fglo', '(2 * i[0] - count)'], {}), '(fglo, 2 * i[0] - count)\n', (7853, 7877), True, 'import numpy as np\n'), ((7976, 8013), 'numpy.delete', 'np.delete', (['fglo', '(2 * i[0] + 1 - count)'], {}), '(fglo, 2 * i[0] + 1 - count)\n', (7985, 8013), True, 'import numpy as np\n'), ((9786, 9858), 'elementLibrary.stiffnessMatrix.triQuadFE', 'stiffnessMatrix.triQuadFE', (['coord', 'materialMatrix[materialMeshList[0][i]]'], {}), '(coord, materialMatrix[materialMeshList[0][i]])\n', (9811, 9858), False, 'from elementLibrary import stiffnessMatrix, shapeFunction\n'), ((11492, 11520), 'numpy.array', 'np.array', (['coordinates[node3]'], {}), '(coordinates[node3])\n', (11500, 11520), True, 'import numpy as np\n'), ((11732, 11764), 'elementLibrary.shapeFunction.oneDLinear', 'shapeFunction.oneDLinear', (['pos[j]'], {}), '(pos[j])\n', (11756, 11764), False, 'from elementLibrary import stiffnessMatrix, shapeFunction\n'), ((11848, 11890), 'elementLibrary.shapeFunction.oneDQuadratic', 'shapeFunction.oneDQuadratic', (['pos[j]', 'coord'], {}), '(pos[j], coord)\n', (11875, 11890), False, 'from elementLibrary import stiffnessMatrix, shapeFunction\n'), ((12914, 12947), 'numpy.delete', 'np.delete', (['fglo', '(2 * i[0] - count)'], {}), '(fglo, 2 * i[0] - count)\n', (12923, 12947), True, 'import numpy as np\n'), ((13046, 13083), 'numpy.delete', 'np.delete', (['fglo', '(2 * i[0] + 1 - count)'], {}), '(fglo, 2 * i[0] + 1 - count)\n', (13055, 13083), True, 'import numpy as np\n'), ((15193, 15388), 'numpy.array', 'np.array', (['[[cc, cc * material[1] / (1.0 - material[1]), 0.0], [cc * material[1] / (\n 1.0 - material[1]), cc, 0.0], [0.0, 0.0, cc * (1.0 - 2.0 * material[1]) /\n (2.0 * (1.0 - material[1]))]]'], {}), '([[cc, cc * material[1] / (1.0 - material[1]), 0.0], [cc * material\n [1] / (1.0 - material[1]), cc, 0.0], [0.0, 0.0, cc * (1.0 - 2.0 *\n material[1]) / (2.0 * (1.0 - material[1]))]])\n', (15201, 15388), True, 'import numpy as np\n'), ((1194, 1263), 'elementLibrary.stiffnessMatrix.quadFE', 'stiffnessMatrix.quadFE', (['coord', 'materialMatrix[materialMeshList[0][i]]'], {}), '(coord, materialMatrix[materialMeshList[0][i]])\n', (1216, 1263), False, 'from elementLibrary import stiffnessMatrix, shapeFunction\n'), ((1764, 1775), 'time.time', 'time.time', ([], {}), '()\n', (1773, 1775), False, 'import time\n'), ((2292, 2325), 'numpy.array', 'np.array', (['[forceList[2 * i][1:3]]'], {}), '([forceList[2 * i][1:3]])\n', (2300, 2325), True, 'import numpy as np\n'), ((2351, 2388), 'numpy.array', 'np.array', (['[forceList[2 * i + 1][1:3]]'], {}), '([forceList[2 * i + 1][1:3]])\n', (2359, 2388), True, 'import numpy as np\n'), ((2785, 2796), 'time.time', 'time.time', ([], {}), '()\n', (2794, 2796), False, 'import time\n'), ((4007, 4018), 'time.time', 'time.time', ([], {}), '()\n', (4016, 4018), False, 'import time\n'), ((4304, 4315), 'time.time', 'time.time', ([], {}), '()\n', (4313, 4315), False, 'import time\n'), ((6077, 6088), 'time.time', 'time.time', ([], {}), '()\n', (6086, 6088), False, 'import time\n'), ((6605, 6638), 'numpy.array', 'np.array', (['[forceList[2 * i][1:3]]'], {}), '([forceList[2 * i][1:3]])\n', (6613, 6638), True, 'import numpy as np\n'), ((6664, 6701), 'numpy.array', 'np.array', (['[forceList[2 * i + 1][1:3]]'], {}), '([forceList[2 * i + 1][1:3]])\n', (6672, 6701), True, 'import numpy as np\n'), ((7098, 7109), 'time.time', 'time.time', ([], {}), '()\n', (7107, 7109), False, 'import time\n'), ((8320, 8331), 'time.time', 'time.time', ([], {}), '()\n', (8329, 8331), False, 'import time\n'), ((8617, 8628), 'time.time', 'time.time', ([], {}), '()\n', (8626, 8628), False, 'import time\n'), ((9910, 9983), 'elementLibrary.stiffnessMatrix.quadQuadFE', 'stiffnessMatrix.quadQuadFE', (['coord', 'materialMatrix[materialMeshList[0][i]]'], {}), '(coord, materialMatrix[materialMeshList[0][i]])\n', (9936, 9983), False, 'from elementLibrary import stiffnessMatrix, shapeFunction\n'), ((10484, 10495), 'time.time', 'time.time', ([], {}), '()\n', (10493, 10495), False, 'import time\n'), ((11241, 11274), 'numpy.array', 'np.array', (['[forceList[2 * i][1:3]]'], {}), '([forceList[2 * i][1:3]])\n', (11249, 11274), True, 'import numpy as np\n'), ((11300, 11337), 'numpy.array', 'np.array', (['[forceList[2 * i + 1][1:3]]'], {}), '([forceList[2 * i + 1][1:3]])\n', (11308, 11337), True, 'import numpy as np\n'), ((12164, 12175), 'time.time', 'time.time', ([], {}), '()\n', (12173, 12175), False, 'import time\n'), ((13390, 13401), 'time.time', 'time.time', ([], {}), '()\n', (13399, 13401), False, 'import time\n'), ((13606, 13617), 'time.time', 'time.time', ([], {}), '()\n', (13615, 13617), False, 'import time\n')]
import numpy as np def l2_regularization(W, reg_strength): ''' Computes L2 regularization loss on weights and its gradient Arguments: W, np array - weights reg_strength - float value Returns: loss, single value - l2 regularization loss gradient, np.array same shape as W - gradient of weight by l2 loss ''' # TODO: implement l2 regularization and gradient # Your final implementation shouldn't have any loops # regularization_strength * sumij W[i, j]2 # loss = reg_strength * np.trace(np.dot(W.T, W)) # L2(W) = λ * tr(W.T * W) loss = reg_strength * np.sum(W * W) grad = 2 * reg_strength * W # dL2(W)/dW = 2 * λ * W return loss, grad def softmax(_predictions): ''' Computes probabilities from scores Arguments: predictions, np array, shape is either (N) or (batch_size, N) - classifier outp¬ut Returns: probs, np array of the same shape as predictions - probability for every class, 0..1 ''' # TODO implement softmax # Your final implementation shouldn't have any loops predictions = _predictions.copy() if len(predictions.shape) == 1: predictions -= np.max(predictions) # , axis=1)[:,None] values = np.exp(predictions) probs = values / np.sum(values) # , axis=1)[:, None] else: predictions -= np.max(predictions, axis=1)[:, None] values = np.exp(predictions) probs = values / np.sum(values, axis=1)[:, None] return probs def cross_entropy_loss(probs, target_index): ''' Computes cross-entropy loss Arguments: probs, np array, shape is either (N) or (batch_size, N) - probabilities for every class target_index: np array of int, shape is (1) or (batch_size) - index of the true class for given sample(s) Returns: loss: single value ''' # TODO implement cross-entropy # Your final implementation shouldn't have any loops old_result = cross_entropy_loss_old(probs, target_index) if isinstance(target_index, int) or len(probs.shape) == 1: return -np.log(probs[target_index]) else: target_probs = probs[np.arange(len(target_index)), target_index.flatten()] value = -np.log(target_probs) result = np.mean(value) assert old_result == result return result def cross_entropy_loss_old(probs, target_index): ''' Computes cross-entropy loss Arguments: probs, np array, shape is either (N) or (batch_size, N) - probabilities for every class target_index: np array of int, shape is (1) or (batch_size) - index of the true class for given sample(s) Returns: loss: single value ''' rows = np.arange(target_index.shape[0]) cols = target_index return np.mean(-np.log(probs[rows, cols])) # L def softmax_with_cross_entropy(predictions, target_index): ''' Computes softmax and cross-entropy loss for model predictions, including the gradient Arguments: predictions, np array, shape is either (N) or (batch_size, N) - classifier output target_index: np array of int, shape is (1) or (batch_size) - index of the true class for given sample(s) Returns: loss, single value - cross-entropy loss dprediction, np array same shape as predictions - gradient of predictions by loss value ''' # TODO implement softmax with cross-entropy probs = softmax(predictions) loss = cross_entropy_loss(probs, target_index) # Your final implementation shouldn't have any loops dprediction = probs.copy() if len(predictions.shape) == 1: dprediction[target_index] -= 1 # dL/dZ = (S - 1(y)) else: dprediction[np.arange(len(dprediction)), target_index.flatten()] -= 1 dprediction = dprediction / target_index.shape[0] return loss, dprediction class Param: """ Trainable parameter of the model Captures both parameter value and the gradient """ def __init__(self, value): self.value = value self.grad = np.zeros_like(value) def reset_grad(self): self.grad = np.zeros_like(self.value) def __str__(self) -> str: super().__str__() return f'value: {self.value}, gradient: {self.grad}' def ReLU(X): return (X + np.abs(X)) / 2 class ReLULayer: def __init__(self): self.positive = None self.x = None pass def forward(self, X): # TODO: Implement forward pass # Hint: you'll need to save some information about X # to use it later in the backward pass self.x = X self.mask = (X > 0) # result = ReLU(X) return X * self.mask def backward(self, d_out): """ Backward pass Arguments: d_out, np array (batch_size, num_features) - gradient of loss function with respect to output Returns: d_result: np array (batch_size, num_features) - gradient with respect to input """ # TODO: Implement backward pass # Your final implementation shouldn't have any loops d_result = self.mask * d_out return d_result def params(self): # ReLU Doesn't have any parameters return {} class FullyConnectedLayer: def __init__(self, n_input, n_output): self.W = Param(0.001 * np.random.randn(n_input, n_output)) self.B = Param(0.001 * np.random.randn(1, n_output)) self.X = None def forward(self, X): # TODO: Implement forward pass # Your final implementation shouldn't have any loops self.X = X.copy() result = np.dot(X, self.W.value) + self.B.value return result def backward(self, d_out): """ Backward pass Computes gradient with respect to input and accumulates gradients within self.W and self.B Arguments: d_out, np array (batch_size, n_output) - gradient of loss function with respect to output Returns: d_result: np array (batch_size, n_input) - gradient with respect to input """ # TODO: Implement backward pass # Compute both gradient with respect to input # and gradients with respect to W and B # Add gradients of W and B to their `grad` attribute # It should be pretty similar to linear classifier from # n_input, n_output # X = (batch_size, input_features) # batch_size, n_output # the previous assignment dw = np.dot(self.X.T, d_out) self.W.grad += dw E = np.ones(shape=(1, self.X.shape[0])) # 1 x batch_size * batch_size x n_output db = np.dot(E, d_out) self.B.grad += db d_input = np.dot(d_out, self.W.value.T) return d_input def params(self): return {'W': self.W, 'B': self.B}
[ "numpy.mean", "numpy.abs", "numpy.ones", "numpy.log", "numpy.max", "numpy.exp", "numpy.sum", "numpy.dot", "numpy.random.randn", "numpy.zeros_like", "numpy.arange" ]
[((2301, 2315), 'numpy.mean', 'np.mean', (['value'], {}), '(value)\n', (2308, 2315), True, 'import numpy as np\n'), ((2738, 2770), 'numpy.arange', 'np.arange', (['target_index.shape[0]'], {}), '(target_index.shape[0])\n', (2747, 2770), True, 'import numpy as np\n'), ((621, 634), 'numpy.sum', 'np.sum', (['(W * W)'], {}), '(W * W)\n', (627, 634), True, 'import numpy as np\n'), ((1207, 1226), 'numpy.max', 'np.max', (['predictions'], {}), '(predictions)\n', (1213, 1226), True, 'import numpy as np\n'), ((1265, 1284), 'numpy.exp', 'np.exp', (['predictions'], {}), '(predictions)\n', (1271, 1284), True, 'import numpy as np\n'), ((1434, 1453), 'numpy.exp', 'np.exp', (['predictions'], {}), '(predictions)\n', (1440, 1453), True, 'import numpy as np\n'), ((2267, 2287), 'numpy.log', 'np.log', (['target_probs'], {}), '(target_probs)\n', (2273, 2287), True, 'import numpy as np\n'), ((4097, 4117), 'numpy.zeros_like', 'np.zeros_like', (['value'], {}), '(value)\n', (4110, 4117), True, 'import numpy as np\n'), ((4165, 4190), 'numpy.zeros_like', 'np.zeros_like', (['self.value'], {}), '(self.value)\n', (4178, 4190), True, 'import numpy as np\n'), ((6606, 6629), 'numpy.dot', 'np.dot', (['self.X.T', 'd_out'], {}), '(self.X.T, d_out)\n', (6612, 6629), True, 'import numpy as np\n'), ((6668, 6703), 'numpy.ones', 'np.ones', ([], {'shape': '(1, self.X.shape[0])'}), '(shape=(1, self.X.shape[0]))\n', (6675, 6703), True, 'import numpy as np\n'), ((6766, 6782), 'numpy.dot', 'np.dot', (['E', 'd_out'], {}), '(E, d_out)\n', (6772, 6782), True, 'import numpy as np\n'), ((6827, 6856), 'numpy.dot', 'np.dot', (['d_out', 'self.W.value.T'], {}), '(d_out, self.W.value.T)\n', (6833, 6856), True, 'import numpy as np\n'), ((1310, 1324), 'numpy.sum', 'np.sum', (['values'], {}), '(values)\n', (1316, 1324), True, 'import numpy as np\n'), ((1380, 1407), 'numpy.max', 'np.max', (['predictions'], {'axis': '(1)'}), '(predictions, axis=1)\n', (1386, 1407), True, 'import numpy as np\n'), ((2132, 2159), 'numpy.log', 'np.log', (['probs[target_index]'], {}), '(probs[target_index])\n', (2138, 2159), True, 'import numpy as np\n'), ((2816, 2841), 'numpy.log', 'np.log', (['probs[rows, cols]'], {}), '(probs[rows, cols])\n', (2822, 2841), True, 'import numpy as np\n'), ((4340, 4349), 'numpy.abs', 'np.abs', (['X'], {}), '(X)\n', (4346, 4349), True, 'import numpy as np\n'), ((5703, 5726), 'numpy.dot', 'np.dot', (['X', 'self.W.value'], {}), '(X, self.W.value)\n', (5709, 5726), True, 'import numpy as np\n'), ((1479, 1501), 'numpy.sum', 'np.sum', (['values'], {'axis': '(1)'}), '(values, axis=1)\n', (1485, 1501), True, 'import numpy as np\n'), ((5414, 5448), 'numpy.random.randn', 'np.random.randn', (['n_input', 'n_output'], {}), '(n_input, n_output)\n', (5429, 5448), True, 'import numpy as np\n'), ((5481, 5509), 'numpy.random.randn', 'np.random.randn', (['(1)', 'n_output'], {}), '(1, n_output)\n', (5496, 5509), True, 'import numpy as np\n')]
import numpy as np import torch from rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims from rlpyt.models.mlp import MlpModel from rlpyt.utils.collections import namedarraytuple RnnState = namedarraytuple("RnnState", ["h", "c"]) class MujocoLstmModel(torch.nn.Module): def __init__( self, observation_shape, action_size, hidden_sizes=None, # None for default (see below). lstm_size=256, nonlinearity=torch.nn.ReLU, ): super().__init__() self._obs_n_dim = len(observation_shape) self._action_size = action_size hidden_sizes = hidden_sizes or [256, 256] mlp_input_size = int(np.prod(observation_shape)) self.mlp = MlpModel( input_size=mlp_input_size, hidden_sizes=hidden_sizes, output_size=None, nonlinearity=nonlinearity, ) mlp_output_size = hidden_sizes[-1] if hidden_sizes else mlp_input_size self.lstm = torch.nn.LSTM(mlp_output_size + action_size + 1, lstm_size) self.head = torch.nn.Linear(lstm_size, action_size * 2 + 1) def forward(self, observation, prev_action, prev_reward, init_rnn_state): """Feedforward layers process as [T*B,H]. Return same leading dims as input, can be [T,B], [B], or [].""" # Infer (presence of) leading dimensions: [T,B], [B], or []. lead_dim, T, B, _ = infer_leading_dims(observation, self._obs_n_dim) mlp_out = self.mlp(observation.view(T * B, -1)) lstm_input = torch.cat([ mlp_out.view(T, B, -1), prev_action.view(T, B, -1), prev_reward.view(T, B, 1), ], dim=2) init_rnn_state = None if init_rnn_state is None else tuple(init_rnn_state) lstm_out, (hn, cn) = self.lstm(lstm_input, init_rnn_state) outputs = self.head(lstm_out) mu = outputs[:, :self._action_size] log_std = outputs[:, self._action_size:-1] v = outputs[:, -1].squeeze(-1) # Restore leading dimensions: [T,B], [B], or [], as input. mu, log_std, v = restore_leading_dims((mu, log_std, v), lead_dim, T, B) # Model should always leave B-dimension in rnn state: [N,B,H] next_rnn_state = RnnState(h=hn, c=cn) return mu, log_std, v, next_rnn_state
[ "numpy.prod", "rlpyt.utils.tensor.restore_leading_dims", "rlpyt.models.mlp.MlpModel", "torch.nn.LSTM", "rlpyt.utils.tensor.infer_leading_dims", "torch.nn.Linear", "rlpyt.utils.collections.namedarraytuple" ]
[((208, 247), 'rlpyt.utils.collections.namedarraytuple', 'namedarraytuple', (['"""RnnState"""', "['h', 'c']"], {}), "('RnnState', ['h', 'c'])\n", (223, 247), False, 'from rlpyt.utils.collections import namedarraytuple\n'), ((771, 883), 'rlpyt.models.mlp.MlpModel', 'MlpModel', ([], {'input_size': 'mlp_input_size', 'hidden_sizes': 'hidden_sizes', 'output_size': 'None', 'nonlinearity': 'nonlinearity'}), '(input_size=mlp_input_size, hidden_sizes=hidden_sizes, output_size=\n None, nonlinearity=nonlinearity)\n', (779, 883), False, 'from rlpyt.models.mlp import MlpModel\n'), ((1037, 1096), 'torch.nn.LSTM', 'torch.nn.LSTM', (['(mlp_output_size + action_size + 1)', 'lstm_size'], {}), '(mlp_output_size + action_size + 1, lstm_size)\n', (1050, 1096), False, 'import torch\n'), ((1117, 1164), 'torch.nn.Linear', 'torch.nn.Linear', (['lstm_size', '(action_size * 2 + 1)'], {}), '(lstm_size, action_size * 2 + 1)\n', (1132, 1164), False, 'import torch\n'), ((1464, 1512), 'rlpyt.utils.tensor.infer_leading_dims', 'infer_leading_dims', (['observation', 'self._obs_n_dim'], {}), '(observation, self._obs_n_dim)\n', (1482, 1512), False, 'from rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims\n'), ((2155, 2209), 'rlpyt.utils.tensor.restore_leading_dims', 'restore_leading_dims', (['(mu, log_std, v)', 'lead_dim', 'T', 'B'], {}), '((mu, log_std, v), lead_dim, T, B)\n', (2175, 2209), False, 'from rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims\n'), ((724, 750), 'numpy.prod', 'np.prod', (['observation_shape'], {}), '(observation_shape)\n', (731, 750), True, 'import numpy as np\n')]
#!/usr/bin/env python from __future__ import print_function # Copyright 2019 <NAME> - juliane.mai(at)uwaterloo.ca # # License # This file is part of the EEE code library for "Computationally inexpensive identification # of noninformative model parameters by sequential screening: Efficient Elementary Effects (EEE)". # # The EEE code library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # The MVA code library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with The EEE code library. # If not, see <https://github.com/julemai/EEE/blob/master/LICENSE>. # # If you use this method in a publication please cite: # # <NAME> & <NAME> et al. (2015). # Computationally inexpensive identification of noninformative model parameters by sequential screening. # Water Resources Research, 51, 6417-6441. # https://doi.org/10.1002/2015WR016907. # # An example calling sequence to derive model outputs for previously sampled parameter sets stored # in an ASCII file (option -i) where some lines might be skipped (option -s). The final model outputs # are stored in a pickle file (option -o). The model outputs are stored as dictionaries. Multiple # model outputs are possible. # # python 2_run_model_raven-hmets.py \ # -i parameter_sets_1_scaled_para21_M.dat \ # -s XXX # -o model_output.pkl """ Runs a model for a bunch of parameter sets and stores model outputs in a pickle file. History ------- Written, JM, Mar 2019 """ # ------------------------------------------------------------------------- # Command line arguments - if script # # Comment|Uncomment - Begin #if __name__ == '__main__': # ----------------------- # add subolder scripts/lib to search path # ----------------------- import sys import os dir_path = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.abspath(dir_path+'/lib')) sys.path.append(os.path.abspath(dir_path+'/../examples/raven-hmets/model')) import argparse import numpy as np import scipy.stats as stats import copy import pickle from pathlib2 import Path import subprocess import shutil from raven_templates import RVI, RVT, RVP, RVH, RVC # in examples/raven-hmets/model/ from raven_common import writeString, makeDirectories # in examples/raven-hmets/model/ from fread import fread # in lib/ infile = 'example_raven-hmets/parameter_sets_1_scaled_para15_M.dat' # name of file containing sampled parameter sets to run the model outfile = 'example_raven-hmets/model_output.pkl' # name of file used to save (scalar) model outputs skip = None # number of lines to skip in input file parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description='''An example calling sequence to derive model outputs for previously sampled parameter sets stored in an ASCII file (option -i) where some lines might be skipped (option -s). The final model outputs are stored in a pickle file (option -o). The model outputs are stored as dictionaries. Multiple model outputs are possible..''') parser.add_argument('-i', '--infile', action='store', default=infile, dest='infile', metavar='infile', help="Name of file containing sampled SCALED parameter sets to run the model (default: 'parameter_sets.out').") parser.add_argument('-s', '--skip', action='store', default=skip, dest='skip', metavar='skip', help="Number of lines to skip in input file (default: None).") parser.add_argument('-o', '--outfile', action='store', default=outfile, dest='outfile', metavar='outfile', help="Name of file used to save (scalar) model outputs in a pickle file (default: 'model_output.pkl').") args = parser.parse_args() infile = args.infile outfile = args.outfile skip = args.skip del parser, args def model_function(paras, run_id=None): # input: # paras ... list of model parameters scaled to their range; # values for all N model parameters have to be provided # example: # [ x1, x2, x3, x4, .... ] # run_id ... optional name of this run (to, e.g., print or store in a file) # example: # run_aset_001 # output: # model output in dictionary # example: # model['out'] = 7.4 if not(run_id is None): print("Run ID: ",run_id) # --------------- # derive some parameters # --------------- dict_dparas = {} dict_dparas['sum_x05_x06'] = paras[4]+paras[5] # MAX_MELT_FACTOR > MIN_MELT_FACTOR dict_dparas['sum_x09_x10'] = paras[8]+paras[9] # SNOW_SWI_MAX > SNOW_SWI_MIN dict_dparas['half_x20'] = paras[19] * 0.5 * 1000 # half the value but in [mm] not [m] dict_dparas['half_x21'] = paras[20] * 0.5 * 1000 # half the value but in [mm] not [m] # --------------- # paste all paras into template files # --------------- # ex.: string = "parameter x01 = {par[x01]} and another parameter x02 = {par[x02]}" # keys = ['x01','x02'] # vals = [1.0,3.0] # string.format(par=dict(zip(keys,vals))) # # --> 'parameter x01 = 1.0 and another parameter x02 = 3.0' # # to replace patterns: {par[x01]} by parameter value paras[0] # {par[x02]} by parameter value paras[1] # ... if len(paras) > 9 and len(paras) < 100: keys_paras = ["x{:02d}".format(ii) for ii in range(1,len(paras)+1) ] elif len(paras) > 99 and len(paras) < 1000: keys_paras = ["x{:03d}".format(ii) for ii in range(1,len(paras)+1) ] elif len(paras) <= 9: keys_paras = ["x{:01d}".format(ii) for ii in range(1,len(paras)+1) ] else: raise ValueError("More than 999 parameters are not implemented yet!") vals_paras = paras dict_paras = dict(zip(keys_paras,vals_paras)) # fill in to templates # templates need to have patterns: # {par[x01]}, {par[x02]}, ... for parameters # {dpar[something]}, {dpar[somethingelse]}, ... for derived parameters # --------------- # create a run folder # --------------- tmp_folder = "/tmp/eee-analysis/"+str(run_id) # "/tmp/juletest" # TODO a generic folder name in /tmp raven_exe_name = os.path.abspath(dir_path+"/../"+"examples/raven-hmets/model/Raven.exe") raven_obs_folder = os.path.abspath(dir_path+"/../"+"examples/raven-hmets/model/data_obs") if os.path.exists(tmp_folder): shutil.rmtree(tmp_folder) # all RAVEN setup files writeString( Path(tmp_folder,"raven_hmets.rvi"), RVI.format(par=dict_paras,dpar=dict_dparas) ) writeString( Path(tmp_folder,"raven_hmets.rvp"), RVP.format(par=dict_paras,dpar=dict_dparas) ) writeString( Path(tmp_folder,"raven_hmets.rvh"), RVH.format(par=dict_paras,dpar=dict_dparas) ) writeString( Path(tmp_folder,"raven_hmets.rvt"), RVT.format(par=dict_paras,dpar=dict_dparas) ) writeString( Path(tmp_folder,"raven_hmets.rvc"), RVC.format(par=dict_paras,dpar=dict_dparas) ) # link executable if not(os.path.exists(str(Path(tmp_folder,os.path.basename(raven_exe_name))))): print("from: ",os.path.realpath(raven_exe_name)) print("to: ",str(Path(tmp_folder,os.path.basename(raven_exe_name)))) os.symlink(os.path.realpath(raven_exe_name), str(Path(tmp_folder,os.path.basename(raven_exe_name)))) # link observations folder if not(os.path.exists(str(Path(tmp_folder,os.path.basename(raven_obs_folder))))): os.symlink(os.path.realpath(raven_obs_folder), str(Path(tmp_folder,os.path.basename(raven_obs_folder)))) # create ouput folder out_folder = str(Path(tmp_folder,"output")) os.makedirs(out_folder) # --------------- # run the model with these input rv* files # --------------- cmd = [str(Path(tmp_folder,os.path.basename(raven_exe_name))),str(Path(tmp_folder,"raven_hmets")),"-o",str(Path(tmp_folder,"output"))+'/'] print("run cmd: ",' '.join(cmd)) process = subprocess.Popen(cmd, stdout=subprocess.PIPE) print("") print("Raven standard output:") for line in process.stdout: print(">>> ",line.rstrip()) # rstrip removes trailing \n if not(os.path.exists(str(Path(tmp_folder,"output","Diagnostics.csv")))): print("") print("ERROR: No Diagnostics.csv produced") print("") print("Raven error file content:") ff = open(str(Path(tmp_folder,"output","Raven_errors.txt")), "r") lines = ff.readlines() ff.close() for line in lines: print(">>> ",line.rstrip()) # rstrip removes trailing \n raise ValueError("ERROR: No Diagnostics.csv produced (scroll up to see content of error file)") model = {} # --------------- # extract model output: Diagnostics: NSE # --------------- model['nse'] = 0.0 ff = open(str(Path(tmp_folder,"output","Diagnostics.csv")), "r") lines = ff.readlines() ff.close() nse = np.float(lines[-1].strip().split(',')[2]) print("NSE: ",nse) model['nse'] = nse print("") # --------------- # extract model output: Hydrographs: simulated Q # --------------- model['Q'] = 0.0 warmup = 2*365 # 1 # model timestep 1 day and want to skip 2 years # first day 1991-01-01 00:00:00.00 (checked) model['Q'] = np.transpose(fread(str(Path(tmp_folder,"output","Hydrographs.csv")),skip=warmup+1,cskip=4,nc=1))[0] print("Q: ",model['Q'][0:4],"...",model['Q'][-4:]) print("Q_range: [",np.min(model['Q']),",",np.max(model['Q']),"]") print("shape Q: ",np.shape(model['Q'])) print("") # --------------- # extract model output: BETWEEN_PONDED_WATER_AND_SOIL[0]_Daily_Average_BySubbasin.csv: accumulated infiltration volume # --------------- model['infiltration'] = 0.0 warmup = 2*365 # 1 # model timestep 1 day and want to skip 2 years # first day 1990-12-31 00:00:00.00 (checked) But all timesteps are shifted by 1 day... # # de-accumulated infiltration volume model['infiltration'] = np.transpose(fread(str(Path(tmp_folder,"output","BETWEEN_PONDED_WATER_AND_SOIL[0]_Daily_Average_BySubbasin.csv")),skip=warmup,cskip=2,nc=1))[0] model['infiltration'] = np.diff(model['infiltration']) print("Infiltration I: ",model['infiltration'][0:4],"...",model['infiltration'][-4:]) print("I_range: [",np.min(model['infiltration']),",",np.max(model['infiltration']),"]") print("shape I: ",np.shape(model['infiltration'])) print("") # --------------- # cleanup # --------------- if os.path.exists(tmp_folder): shutil.rmtree(tmp_folder) return model # read parameter sets ff = open(infile, "r") parasets = ff.readlines() ff.close() if skip is None: skip = np.int(parasets[0].strip().split(':')[1]) else: skip = np.int(skip) parasets = parasets[skip:] model_output = {} # this loop could be easily parallized and modified such that it # actually submits multiple tasks to a HPC for iparaset,paraset in enumerate(parasets): paraset = list(map(float,paraset.strip().split())) model = model_function(paraset,run_id='run_set_'+str(iparaset)) if iparaset == 0: for ikey in model.keys(): model_output[ikey] = [] for ikey in model.keys(): model_output[ikey].append(model[ikey]) pickle.dump( model_output, open( outfile, "wb" ) ) print("wrote: '"+outfile+"'")
[ "raven_templates.RVH.format", "raven_templates.RVP.format", "raven_templates.RVC.format", "os.path.exists", "raven_templates.RVT.format", "argparse.ArgumentParser", "subprocess.Popen", "raven_templates.RVI.format", "numpy.diff", "numpy.max", "pathlib2.Path", "numpy.min", "numpy.shape", "nu...
[((3253, 3682), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.RawDescriptionHelpFormatter', 'description': '"""An example calling sequence to derive model outputs for previously sampled parameter sets stored in an ASCII file (option -i) where some lines might be skipped (option -s). The final model outputs are stored in a pickle file (option -o). The model outputs are stored as dictionaries. Multiple model outputs are possible.."""'}), "(formatter_class=argparse.\n RawDescriptionHelpFormatter, description=\n 'An example calling sequence to derive model outputs for previously sampled parameter sets stored in an ASCII file (option -i) where some lines might be skipped (option -s). The final model outputs are stored in a pickle file (option -o). The model outputs are stored as dictionaries. Multiple model outputs are possible..'\n )\n", (3276, 3682), False, 'import argparse\n'), ((2275, 2301), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (2291, 2301), False, 'import os\n'), ((2319, 2353), 'os.path.abspath', 'os.path.abspath', (["(dir_path + '/lib')"], {}), "(dir_path + '/lib')\n", (2334, 2353), False, 'import os\n'), ((2369, 2429), 'os.path.abspath', 'os.path.abspath', (["(dir_path + '/../examples/raven-hmets/model')"], {}), "(dir_path + '/../examples/raven-hmets/model')\n", (2384, 2429), False, 'import os\n'), ((7138, 7213), 'os.path.abspath', 'os.path.abspath', (["(dir_path + '/../' + 'examples/raven-hmets/model/Raven.exe')"], {}), "(dir_path + '/../' + 'examples/raven-hmets/model/Raven.exe')\n", (7153, 7213), False, 'import os\n'), ((7233, 7307), 'os.path.abspath', 'os.path.abspath', (["(dir_path + '/../' + 'examples/raven-hmets/model/data_obs')"], {}), "(dir_path + '/../' + 'examples/raven-hmets/model/data_obs')\n", (7248, 7307), False, 'import os\n'), ((7312, 7338), 'os.path.exists', 'os.path.exists', (['tmp_folder'], {}), '(tmp_folder)\n', (7326, 7338), False, 'import os\n'), ((8560, 8583), 'os.makedirs', 'os.makedirs', (['out_folder'], {}), '(out_folder)\n', (8571, 8583), False, 'import os\n'), ((8871, 8916), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'stdout': 'subprocess.PIPE'}), '(cmd, stdout=subprocess.PIPE)\n', (8887, 8916), False, 'import subprocess\n'), ((11140, 11170), 'numpy.diff', 'np.diff', (["model['infiltration']"], {}), "(model['infiltration'])\n", (11147, 11170), True, 'import numpy as np\n'), ((11504, 11530), 'os.path.exists', 'os.path.exists', (['tmp_folder'], {}), '(tmp_folder)\n', (11518, 11530), False, 'import os\n'), ((11755, 11767), 'numpy.int', 'np.int', (['skip'], {}), '(skip)\n', (11761, 11767), True, 'import numpy as np\n'), ((7348, 7373), 'shutil.rmtree', 'shutil.rmtree', (['tmp_folder'], {}), '(tmp_folder)\n', (7361, 7373), False, 'import shutil\n'), ((7420, 7455), 'pathlib2.Path', 'Path', (['tmp_folder', '"""raven_hmets.rvi"""'], {}), "(tmp_folder, 'raven_hmets.rvi')\n", (7424, 7455), False, 'from pathlib2 import Path\n'), ((7456, 7500), 'raven_templates.RVI.format', 'RVI.format', ([], {'par': 'dict_paras', 'dpar': 'dict_dparas'}), '(par=dict_paras, dpar=dict_dparas)\n', (7466, 7500), False, 'from raven_templates import RVI, RVT, RVP, RVH, RVC\n'), ((7519, 7554), 'pathlib2.Path', 'Path', (['tmp_folder', '"""raven_hmets.rvp"""'], {}), "(tmp_folder, 'raven_hmets.rvp')\n", (7523, 7554), False, 'from pathlib2 import Path\n'), ((7555, 7599), 'raven_templates.RVP.format', 'RVP.format', ([], {'par': 'dict_paras', 'dpar': 'dict_dparas'}), '(par=dict_paras, dpar=dict_dparas)\n', (7565, 7599), False, 'from raven_templates import RVI, RVT, RVP, RVH, RVC\n'), ((7618, 7653), 'pathlib2.Path', 'Path', (['tmp_folder', '"""raven_hmets.rvh"""'], {}), "(tmp_folder, 'raven_hmets.rvh')\n", (7622, 7653), False, 'from pathlib2 import Path\n'), ((7654, 7698), 'raven_templates.RVH.format', 'RVH.format', ([], {'par': 'dict_paras', 'dpar': 'dict_dparas'}), '(par=dict_paras, dpar=dict_dparas)\n', (7664, 7698), False, 'from raven_templates import RVI, RVT, RVP, RVH, RVC\n'), ((7717, 7752), 'pathlib2.Path', 'Path', (['tmp_folder', '"""raven_hmets.rvt"""'], {}), "(tmp_folder, 'raven_hmets.rvt')\n", (7721, 7752), False, 'from pathlib2 import Path\n'), ((7753, 7797), 'raven_templates.RVT.format', 'RVT.format', ([], {'par': 'dict_paras', 'dpar': 'dict_dparas'}), '(par=dict_paras, dpar=dict_dparas)\n', (7763, 7797), False, 'from raven_templates import RVI, RVT, RVP, RVH, RVC\n'), ((7816, 7851), 'pathlib2.Path', 'Path', (['tmp_folder', '"""raven_hmets.rvc"""'], {}), "(tmp_folder, 'raven_hmets.rvc')\n", (7820, 7851), False, 'from pathlib2 import Path\n'), ((7852, 7896), 'raven_templates.RVC.format', 'RVC.format', ([], {'par': 'dict_paras', 'dpar': 'dict_dparas'}), '(par=dict_paras, dpar=dict_dparas)\n', (7862, 7896), False, 'from raven_templates import RVI, RVT, RVP, RVH, RVC\n'), ((8529, 8555), 'pathlib2.Path', 'Path', (['tmp_folder', '"""output"""'], {}), "(tmp_folder, 'output')\n", (8533, 8555), False, 'from pathlib2 import Path\n'), ((10420, 10438), 'numpy.min', 'np.min', (["model['Q']"], {}), "(model['Q'])\n", (10426, 10438), True, 'import numpy as np\n'), ((10443, 10461), 'numpy.max', 'np.max', (["model['Q']"], {}), "(model['Q'])\n", (10449, 10461), True, 'import numpy as np\n'), ((10496, 10516), 'numpy.shape', 'np.shape', (["model['Q']"], {}), "(model['Q'])\n", (10504, 10516), True, 'import numpy as np\n'), ((11293, 11322), 'numpy.min', 'np.min', (["model['infiltration']"], {}), "(model['infiltration'])\n", (11299, 11322), True, 'import numpy as np\n'), ((11327, 11356), 'numpy.max', 'np.max', (["model['infiltration']"], {}), "(model['infiltration'])\n", (11333, 11356), True, 'import numpy as np\n'), ((11391, 11422), 'numpy.shape', 'np.shape', (["model['infiltration']"], {}), "(model['infiltration'])\n", (11399, 11422), True, 'import numpy as np\n'), ((11540, 11565), 'shutil.rmtree', 'shutil.rmtree', (['tmp_folder'], {}), '(tmp_folder)\n', (11553, 11565), False, 'import shutil\n'), ((8028, 8060), 'os.path.realpath', 'os.path.realpath', (['raven_exe_name'], {}), '(raven_exe_name)\n', (8044, 8060), False, 'import os\n'), ((8160, 8192), 'os.path.realpath', 'os.path.realpath', (['raven_exe_name'], {}), '(raven_exe_name)\n', (8176, 8192), False, 'import os\n'), ((8387, 8421), 'os.path.realpath', 'os.path.realpath', (['raven_obs_folder'], {}), '(raven_obs_folder)\n', (8403, 8421), False, 'import os\n'), ((8746, 8777), 'pathlib2.Path', 'Path', (['tmp_folder', '"""raven_hmets"""'], {}), "(tmp_folder, 'raven_hmets')\n", (8750, 8777), False, 'from pathlib2 import Path\n'), ((9747, 9792), 'pathlib2.Path', 'Path', (['tmp_folder', '"""output"""', '"""Diagnostics.csv"""'], {}), "(tmp_folder, 'output', 'Diagnostics.csv')\n", (9751, 9792), False, 'from pathlib2 import Path\n'), ((8707, 8739), 'os.path.basename', 'os.path.basename', (['raven_exe_name'], {}), '(raven_exe_name)\n', (8723, 8739), False, 'import os\n'), ((8787, 8813), 'pathlib2.Path', 'Path', (['tmp_folder', '"""output"""'], {}), "(tmp_folder, 'output')\n", (8791, 8813), False, 'from pathlib2 import Path\n'), ((9096, 9141), 'pathlib2.Path', 'Path', (['tmp_folder', '"""output"""', '"""Diagnostics.csv"""'], {}), "(tmp_folder, 'output', 'Diagnostics.csv')\n", (9100, 9141), False, 'from pathlib2 import Path\n'), ((9297, 9343), 'pathlib2.Path', 'Path', (['tmp_folder', '"""output"""', '"""Raven_errors.txt"""'], {}), "(tmp_folder, 'output', 'Raven_errors.txt')\n", (9301, 9343), False, 'from pathlib2 import Path\n'), ((7967, 7999), 'os.path.basename', 'os.path.basename', (['raven_exe_name'], {}), '(raven_exe_name)\n', (7983, 7999), False, 'import os\n'), ((8105, 8137), 'os.path.basename', 'os.path.basename', (['raven_exe_name'], {}), '(raven_exe_name)\n', (8121, 8137), False, 'import os\n'), ((8214, 8246), 'os.path.basename', 'os.path.basename', (['raven_exe_name'], {}), '(raven_exe_name)\n', (8230, 8246), False, 'import os\n'), ((8328, 8362), 'os.path.basename', 'os.path.basename', (['raven_obs_folder'], {}), '(raven_obs_folder)\n', (8344, 8362), False, 'import os\n'), ((8443, 8477), 'os.path.basename', 'os.path.basename', (['raven_obs_folder'], {}), '(raven_obs_folder)\n', (8459, 8477), False, 'import os\n'), ((10243, 10288), 'pathlib2.Path', 'Path', (['tmp_folder', '"""output"""', '"""Hydrographs.csv"""'], {}), "(tmp_folder, 'output', 'Hydrographs.csv')\n", (10247, 10288), False, 'from pathlib2 import Path\n'), ((10991, 11086), 'pathlib2.Path', 'Path', (['tmp_folder', '"""output"""', '"""BETWEEN_PONDED_WATER_AND_SOIL[0]_Daily_Average_BySubbasin.csv"""'], {}), "(tmp_folder, 'output',\n 'BETWEEN_PONDED_WATER_AND_SOIL[0]_Daily_Average_BySubbasin.csv')\n", (10995, 11086), False, 'from pathlib2 import Path\n')]
# -*- coding: utf-8 -*- import argparse import logging from array import array from pathlib import Path import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import LinearSegmentedColormap from pylab import contour, contourf from il2fb.maps.heightmaps.constants import HEIGHT_PACK_FORMAT from il2fb.maps.heightmaps.constants import MAP_SCALE from il2fb.maps.heightmaps.logging import setup_logging LOG = logging.getLogger(__name__) ISOHYPSE_COLOR = "#303030" ISOHYPSE_WIDTH = 0.2 CMAP_DATA = ( (0.27058823529411763, 0.45882352941176469, 0.70588235294117652), (0.45490196078431372, 0.67843137254901964, 0.81960784313725488), (0.6705882352941176 , 0.85098039215686272, 0.9137254901960784 ), (0.8784313725490196 , 0.95294117647058818, 0.97254901960784312), (1.0 , 1.0 , 0.74901960784313726), (0.99607843137254903, 0.8784313725490196 , 0.56470588235294117), (0.99215686274509807, 0.68235294117647061, 0.38039215686274508), (0.95686274509803926, 0.42745098039215684, 0.2627450980392157 ), (0.84313725490196079, 0.18823529411764706, 0.15294117647058825), (0.6470588235294118 , 0.0 , 0.14901960784313725), ) CMAP = LinearSegmentedColormap.from_list('il2fb-heights', CMAP_DATA, 256) def load_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description=( "Render heightmap of a given location of " "«IL-2 Sturmovik: Forgotten Battles»" ), ) parser.add_argument( '--height', dest='height', type=int, required=True, help=f"Map height in meters. Must be proportional to {MAP_SCALE}", ) parser.add_argument( '--width', dest='width', type=int, required=True, help=f"Map width in meters. Must be proportional to {MAP_SCALE}", ) parser.add_argument( '-i', '--in', dest='input_file_path', type=lambda x: Path(x).resolve(), default="heightmap.raw", help="Input file path. Default: 'heightmap.raw'", ) parser.add_argument( '-o', '--out', dest='output_file_path', type=lambda x: Path(x).resolve(), default="heightmap.png", help="Output file path. Default: 'heightmap.png'", ) parser.add_argument( '--isostep', dest='isostep', type=int, default=200, help="Step in meters between isohypses. Default: 200", ) parser.add_argument( '-r', '--dpi', dest='dpi', type=int, default=48, help="Output resolution in DPI. Default: 48", ) args = parser.parse_args() if args.height % MAP_SCALE != 0: parser.error(f"Map height must be proportional to {MAP_SCALE}") if args.width % MAP_SCALE != 0: parser.error(f"Map width must be proportional to {MAP_SCALE}") return args def render( src: array, height: int, width: int, isostep: int, dpi: int, output_file_path: Path, ) -> None: height = height // MAP_SCALE width = width // MAP_SCALE image_size = ( (width / dpi), (height / dpi), ) data = np.array(src).reshape((height, width)) isohypses = list(range(0, data.max(), isostep)) plt.clf() plt.axis('off') plt.figure(dpi=dpi) fig = plt.figure(figsize=image_size, frameon=False) fig.add_axes([0, 0, 1, 1]) contourf(data, 256, cmap=CMAP) contour(data, isohypses, colors=ISOHYPSE_COLOR, linewidths=ISOHYPSE_WIDTH) output_file_path.parent.parent.mkdir(parents=True, exist_ok=True) plt.savefig(str(output_file_path), bbox_inches=0, dpi=dpi) def main() -> None: setup_logging() args = load_args() src = array(HEIGHT_PACK_FORMAT) with args.input_file_path.open('rb') as f: src.frombytes(f.read()) render( src=src, height=args.height, width=args.width, isostep=args.isostep, dpi=args.dpi, output_file_path=args.output_file_path, ) if __name__ == '__main__': main()
[ "logging.getLogger", "pylab.contourf", "array.array", "argparse.ArgumentParser", "pathlib.Path", "matplotlib.pyplot.clf", "il2fb.maps.heightmaps.logging.setup_logging", "numpy.array", "matplotlib.pyplot.figure", "pylab.contour", "matplotlib.pyplot.axis", "matplotlib.colors.LinearSegmentedColor...
[((432, 459), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (449, 459), False, 'import logging\n'), ((1223, 1289), 'matplotlib.colors.LinearSegmentedColormap.from_list', 'LinearSegmentedColormap.from_list', (['"""il2fb-heights"""', 'CMAP_DATA', '(256)'], {}), "('il2fb-heights', CMAP_DATA, 256)\n", (1256, 1289), False, 'from matplotlib.colors import LinearSegmentedColormap\n'), ((1344, 1468), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Render heightmap of a given location of «IL-2 Sturmovik: Forgotten Battles»"""'}), "(description=\n 'Render heightmap of a given location of «IL-2 Sturmovik: Forgotten Battles»'\n )\n", (1367, 1468), False, 'import argparse\n'), ((3319, 3328), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (3326, 3328), True, 'import matplotlib.pyplot as plt\n'), ((3333, 3348), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (3341, 3348), True, 'import matplotlib.pyplot as plt\n'), ((3353, 3372), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'dpi': 'dpi'}), '(dpi=dpi)\n', (3363, 3372), True, 'import matplotlib.pyplot as plt\n'), ((3384, 3429), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'image_size', 'frameon': '(False)'}), '(figsize=image_size, frameon=False)\n', (3394, 3429), True, 'import matplotlib.pyplot as plt\n'), ((3466, 3496), 'pylab.contourf', 'contourf', (['data', '(256)'], {'cmap': 'CMAP'}), '(data, 256, cmap=CMAP)\n', (3474, 3496), False, 'from pylab import contour, contourf\n'), ((3501, 3575), 'pylab.contour', 'contour', (['data', 'isohypses'], {'colors': 'ISOHYPSE_COLOR', 'linewidths': 'ISOHYPSE_WIDTH'}), '(data, isohypses, colors=ISOHYPSE_COLOR, linewidths=ISOHYPSE_WIDTH)\n', (3508, 3575), False, 'from pylab import contour, contourf\n'), ((3736, 3751), 'il2fb.maps.heightmaps.logging.setup_logging', 'setup_logging', ([], {}), '()\n', (3749, 3751), False, 'from il2fb.maps.heightmaps.logging import setup_logging\n'), ((3786, 3811), 'array.array', 'array', (['HEIGHT_PACK_FORMAT'], {}), '(HEIGHT_PACK_FORMAT)\n', (3791, 3811), False, 'from array import array\n'), ((3223, 3236), 'numpy.array', 'np.array', (['src'], {}), '(src)\n', (3231, 3236), True, 'import numpy as np\n'), ((1992, 1999), 'pathlib.Path', 'Path', (['x'], {}), '(x)\n', (1996, 1999), False, 'from pathlib import Path\n'), ((2212, 2219), 'pathlib.Path', 'Path', (['x'], {}), '(x)\n', (2216, 2219), False, 'from pathlib import Path\n')]
from __future__ import division import os import time from shutil import copyfile from glob import glob import tensorflow as tf import numpy as np # import config from collections import namedtuple # from module import * # from utils import * # from ops import * # from metrics import * import tensorflow_addons as tfa import tensorflow.keras.backend as kb from tensorflow.keras.optimizers import Adam import matplotlib.pyplot as plt import pandas as pd # os.environ["CUDA_VISIBLE_DEVICES"] = os.environ['SGE_GPU'] import matplotlib.pyplot as plt from PIL import Image from tensorflow import keras as keras class Generator(object): def __init__(self,input_dim): self.input_dim = input_dim self.output_channel = self.input_dim[2] self.model = self.build_model() def build_model(self,num_res_net_blocks = 10): def residue_block(input_data, filters, conv_size,strides=1): p = int((conv_size - 1) / 2) x = tf.pad(input_data, [[0, 0], [p, p], [p, p], [0, 0]], "REFLECT") x = keras.layers.Conv2D(filters=filters, kernel_size=conv_size, strides=strides,activation='relu', padding='VALID')(x) x = tfa.layers.InstanceNormalization()(x) x = tf.pad(x, [[0, 0], [p, p], [p, p], [0, 0]], "REFLECT") x = keras.layers.Conv2D(filters, conv_size, activation='relu', padding='VALID')(x) x = tfa.layers.InstanceNormalization()(x) x = keras.layers.Add()([x, input_data]) x = keras.layers.Activation('relu')(x) return x # 3 conv input = keras.Input(shape=(self.input_dim)) c0 = tf.pad(input, [[0, 0], [3, 3], [3, 3], [0, 0]], "REFLECT") # c0 is (# of images * 262 * 262 * 3) c1 = keras.layers.Conv2D(filters=64, kernel_size=7, strides=1,activation='relu', padding='VALID')(c0) c1 = tfa.layers.InstanceNormalization()(c1) # c1 is (# of images * 256 * 256 * 64) c2 = keras.layers.Conv2D(filters=128, kernel_size=3, strides=2, activation='relu', padding ='SAME')(c1) c2 = tfa.layers.InstanceNormalization()(c2) # c2 is (# of images * 128 * 128 * 128) c3 = keras.layers.Conv2D(filters=256, kernel_size=3, strides=2, activation='relu',padding ='SAME')(c2) c3 = tfa.layers.InstanceNormalization()(c3) # c3 is (# of images * 64 * 64 * 256) res = None # 10 resnet for i in range(num_res_net_blocks): res = residue_block(c3, 256, 3) #3 deconv d1 = keras.layers.Conv2DTranspose(filters=128, kernel_size=3, strides=2,activation='relu',padding = 'SAME',name = 'g_d1')(res) d1 = tfa.layers.InstanceNormalization()(d1) d2 = keras.layers.Conv2DTranspose(filters=64, kernel_size=3, strides=2, activation='relu',padding = 'SAME',name = 'g_d2')(d1) d2 = tfa.layers.InstanceNormalization()(d2) d3 = tf.pad(d2, [[0, 0], [3, 3], [3, 3], [0, 0]], "REFLECT",name = 'g_d3') output = keras.layers.Conv2D(filters=self.output_channel, kernel_size=7, strides=1, activation='sigmoid')(d3) model = keras.Model(input,output) model.summary() return model def trainable(self,trainable = True): self.model.trainable = trainable def save(self,path): self.model.save(path) def load(self,path): self.model = keras.models.load_model(path) def train_on_batch(self, X, y): print("generator trainable weight",self.model.trainable_weights) return self.model.train_on_batch(X, y) def translate_domain(self,input_data): return self.model.predict(input_data) class Discriminator(object): def __init__(self,input_dim): self.input_dim = input_dim self.output_channel = self.input_dim[2] self.model = self.build_model() def build_model(self): model = keras.Sequential() model.add(keras.layers.Conv2D(filters=64, kernel_size=4, strides=2,padding = 'SAME',input_shape=self.input_dim)) model.add(keras.layers.LeakyReLU(alpha=0.3)) model.add(keras.layers.Conv2D(filters=256, kernel_size=4, strides=2,padding = 'SAME')) model.add(keras.layers.LeakyReLU(alpha=0.3)) model.add(tfa.layers.InstanceNormalization()) model.add(keras.layers.Conv2D(filters=self.output_channel, kernel_size=1, strides=1)) model.compile(loss='mse', optimizer=Adam(lr=0.0002, beta_1=0.5), loss_weights=[0.5]) model.summary() return model # def train(self): # def trainable(self,trainable = True): self.model.trainable = trainable def save(self,path): self.model.save(path) def load(self,path): keras.models.load_model(path) def predict(self,input_data): return self.model.predict(input_data) def train_on_batch(self,X,y): # print("discriminator trainable weight",len(self.model.trainable_weights)) return self.model.train_on_batch(X,y) class CycleGan(object): def __init__(self, sess, batch_size, crop_size,generatorAtoB,generatorBtoA, discriminatorA,discriminatorB, discriminatorAandM = None,discriminatorBandM = None, generator_weight_factor = 10,discriminator_weight_factor = 10, use_D_M = False, gamma = 0.9,lamda = 0.9): self.sess = sess self.batch_size = batch_size self.image_size = crop_size # cropped size # self.input_c_dim = input_channels # number of input image channels # self.output_c_dim = output_channels # number of output image channels self.generatorAToB = generatorAtoB self.generatorBToA = generatorBtoA self.discriminatorA = discriminatorA self.discriminatorB = discriminatorB self.use_D_M = use_D_M self.discriminatorAandM = discriminatorAandM self.discriminatorBandM = discriminatorBandM self.gamma = gamma self.lamda = lamda self.composite_model_A = self.build_composite_generator_network(self.generatorAToB,self.generatorBToA,self.discriminatorA) self.composite_model_B = self.build_composite_generator_network(self.generatorBToA,self.generatorAToB,self.discriminatorB) def build_composite_generator_network(self,generatorAtoB,generatorBtoA,discriminatorB): # ensure the model we're updating is trainable generatorAtoB.trainable() # mark discriminator as not trainable generatorBtoA.trainable(False) # mark other generator model as not trainable discriminatorB.trainable(False) input_real_A = keras.Input(shape=self.image_size) input_real_B = keras.Input(shape=self.image_size) # discriminator element fake_B = generatorAtoB.model(input_real_A) dis_B = discriminatorB.model(fake_B) #compare A vs Fake A through A->B->A fake_A_ = generatorBtoA.model(fake_B) # compare B vs Fake B through B->A->B fake_A = generatorBtoA.model(input_real_B) fake_B_ = generatorAtoB.model(fake_A) # define model graph model = keras.Model([input_real_A, input_real_B], [dis_B, fake_A_, fake_B_]) # define optimization algorithm configuration opt = Adam(lr=0.0002, beta_1=0.5) # compile model with weighting of least squares loss and L1 loss model.compile(loss=['mse', 'mae', 'mae'], loss_weights=[1, 10, 10], optimizer=opt) return model # def build_composite_discriminator_network(self, generatorAtoB, generatorBtoA, discriminatorB,discriminatorBandM): def generate_real_samples_batch(self,dataset,batch_size,output_shape,channel_shape): # choose random instances ix = np.random.randint(0, dataset.shape[0], batch_size) # retrieve selected images X = dataset[ix] # generate 'real' class labels (1) y = np.ones((batch_size, output_shape, output_shape, channel_shape)) return X, y # generate a batch of images, returns images and targets def generate_fake_samples_batch(self,generator_model, dataset, output_shape,channel_shape): # generate fake instance X = generator_model.translate_domain(dataset) # create 'fake' class labels (0) y = np.zeros((len(X), output_shape, output_shape, channel_shape)) return X, y def generate_mix_sample_batch(self,datasetA,datasetB,batch_size,output_shape,channel_shape): ix_A = np.random.randint(0, datasetA.shape[0], int(batch_size/2)) X_A = datasetA[ix_A] ix_B = np.random.randint(0, datasetB.shape[0], int(batch_size /2)) X_B = datasetA[ix_B] y = np.ones((batch_size, output_shape, output_shape, channel_shape)) print ( np.concatenate((X_A,X_B),axis=0).shape) return [np.concatenate((X_A,X_B),axis=0),y] # save the generator models to file def save_models(self,epoch, generator_model_AtoB, generator_model_BtoA,path): # save the first generator model folder = os.path.join(path,str(epoch)) if not os.path.isdir(folder): os.makedirs(folder) filename1 = 'g_model_AtoB_.h5' filename1 = os.path.join(folder,filename1) generator_model_AtoB.save(filename1) # save the second generator model filename2 = 'g_model_BtoA_.h5' filename2 = os.path.join(folder, filename2) generator_model_BtoA.save(filename2) print('>Saved: %s and %s' % (filename1, filename2)) def load_models(self,path,filename1,filename2): filename1 = os.path.join(path, filename1) self.generatorAToB.load(filename1) filename2 = os.path.join(path, filename2) self.generatorBToA.load(filename2) # generate samples and save as a plot and save the model def summarize_performance(self,epochs, g_model, trainX, name, n_samples=5): # select a sample of input images X_in, _ = self.generate_real_samples_batch(trainX, n_samples, 0) # generate translated images X_out, _ = self.generate_fake_samples_batch(g_model, X_in, 0) # scale all pixels from [-1,1] to [0,1] X_in = (X_in + 1) / 2.0 X_out = (X_out + 1) / 2.0 # plot real images for i in range(n_samples): plt.subplot(2, n_samples, 1 + i) plt.axis('off') plt.imshow(X_in[i]) # plot translated image for i in range(n_samples): plt.subplot(2, n_samples, 1 + n_samples + i) plt.axis('off') plt.imshow(X_out[i]) # save plot to file filename1 = '%s_generated_plot_%06d.png' % (name, (step + 1)) plt.savefig(filename1) plt.close() def update_image_pool(self,pool, images, max_size=50): selected = list() for image in images: if len(pool) < max_size: # stock the pool pool.append(image) selected.append(image) elif np.random.rand() < 0.5: # use image, but don't add it to the pool selected.append(image) else: # replace an existing image and use replaced image ix = np.random.randint(0, len(pool)) selected.append(pool[ix]) pool[ix] = image return np.asarray(selected) def summarize(self, tag_value_pairs, step): with self.writer.as_default(): for tag, value in tag_value_pairs: tf.summary.scalar(tag, value, step=step) self.writer.flush() def train(self,epochs,batches,datasetA,datasetB,save_path = "",summary_folder = "logs/scalars/",history_path = "history_log",model_save_frequenly = 10): # summary_folder = "logs/scalars/" self.writer = tf.summary.create_file_writer(summary_folder) #discriminator output square shape d_output_shape = self.discriminatorA.model.output_shape[1] channel_num = self.discriminatorA.model.output_shape[3] data_pool_A,data_pool_B = list(),list() # batch_per_epoch = int(len(datasetA)/batches) # calculate the number of training iterations n_steps = int(len(datasetA)/batches) # manually enumerate list_epoch_g_loss = [] list_epoch_d_loss = [] list_epoch_g_A_to_B_loss = [] list_epoch_g_B_to_A_loss = [] list_epoch_d_A__loss = [] list_epoch_d_B__loss = [] list_epoch_d_A_M_loss = [] list_epoch_d_B_M_loss = [] for e in range(epochs): epoch_g_loss = 0 epoch_d_loss = 0 epoch_g_A_to_B_loss = 0 epoch_g_B_to_A_loss = 0 epoch_d_A__loss = 0 epoch_d_B__loss = 0 epoch_d_A_M_loss = 0 epoch_d_B_M_loss = 0 for i in range(n_steps): # select a batch of real samples X_realA, y_realA = self.generate_real_samples_batch(datasetA, batches, d_output_shape,channel_num) X_realB, y_realB = self.generate_real_samples_batch(datasetB, batches, d_output_shape,channel_num) # generate a batch of fake samples X_fakeA, y_fakeA = self.generate_fake_samples_batch(self.generatorBToA, X_realB, d_output_shape,channel_num) X_fakeB, y_fakeB = self.generate_fake_samples_batch(self.generatorAToB, X_realA, d_output_shape,channel_num) # update fakes from pool # X_fakeA = self.update_image_pool(data_pool_A, X_fakeA) # X_fakeB = self.update_image_pool(data_pool_B, X_fakeB) # update generator B->A via adversarial and cycle loss # print("step : ",i) # print("A->B trainable weight : ",len(self.generatorAToB.model.trainable_weights)) # print("B->A trainable weight : ",len(self.generatorBToA.model.trainable_weights)) g_loss2, cycle_loss_2, _,_ = self.composite_model_B.train_on_batch([X_realB, X_realA], [y_realA, X_realB, X_realA]) self.generatorBToA.trainable(False) self.generatorAToB.trainable(True) # print("A->B trainable weight : ", len(self.generatorAToB.model.trainable_weights)) # print("B->A trainable weight : ", len(self.generatorBToA.model.trainable_weights)) # update discriminator for A -> [real/fake] self.discriminatorA.trainable(True) dA_loss1 = self.discriminatorA.train_on_batch(X_realA, y_realA) dA_loss2 = self.discriminatorA.train_on_batch(X_fakeA, y_fakeA) self.discriminatorA.trainable(False) dA_loss = (dA_loss1+dA_loss2)/2 # update generator A->B via adversarial and cycle loss # print("A->B trainable weight : ", len(self.generatorAToB.model.trainable_weights)) # print("B->A trainable weight : ", len(self.generatorBToA.model.trainable_weights)) g_loss1, cycle_loss_1, _, _ = self.composite_model_A.train_on_batch([X_realA, X_realB], [y_realB, X_realA, X_realB]) self.generatorBToA.trainable(True) self.generatorAToB.trainable(False) # print("A->B trainable weight : ", len(self.generatorAToB.model.trainable_weights)) # print("B->A trainable weight : ", len(self.generatorBToA.model.trainable_weights)) # update discriminator for B -> [real/fake] self.discriminatorB.trainable(True) dB_loss1 = self.discriminatorB.train_on_batch(X_realB, y_realB) dB_loss2 = self.discriminatorB.train_on_batch(X_fakeB, y_fakeB) self.discriminatorB.trainable(False) dB_loss = (dB_loss1+dB_loss2)/2 epoch_g_A_to_B_loss += g_loss1 epoch_g_B_to_A_loss += g_loss2 epoch_d_A__loss += dA_loss epoch_d_B__loss += dB_loss epoch_g_loss = epoch_g_loss+g_loss1+g_loss2+self.lamda*(cycle_loss_1+cycle_loss_2) epoch_d_loss = epoch_d_loss+dA_loss+dB_loss if self.use_D_M: # print("fake shahep :",X_fakeA.shape) X_real_mix_M,y_real_mix_M = self.generate_mix_sample_batch(datasetA,datasetB,batches,d_output_shape,channel_num) dAM_loss1 = self.discriminatorAandM.train_on_batch(X_real_mix_M, y_real_mix_M) dAM_loss2 = self.discriminatorAandM.train_on_batch(X_fakeA, y_fakeA) dAM_loss = (dAM_loss1+dAM_loss2)/2 dBM_loss1 = self.discriminatorBandM.train_on_batch(X_real_mix_M, y_real_mix_M) dBM_loss2 = self.discriminatorBandM.train_on_batch(X_fakeB, y_fakeB) dBM_loss = (dBM_loss1 + dBM_loss2) / 2 epoch_d_A_M_loss += dAM_loss epoch_d_B_M_loss += dBM_loss epoch_d_loss = epoch_d_loss +self.gamma*(dAM_loss+dBM_loss) # print("at epoch : ", e) # print("at step :", i) # print("generator loss : ", epoch_g_loss/(i+1)) # print("discriminator loss : ", epoch_g_loss/(i+1)) print('For epoch {} batch {}/{} , G_Loss is {:7.2f}, D_Loss is {:7.2f}.'.format(e,(i+1),n_steps,epoch_g_loss/(i+1),epoch_d_loss/(i+1))) #save model epoch_g_A_to_B_loss /= n_steps epoch_g_B_to_A_loss /= n_steps epoch_d_A__loss /= n_steps epoch_d_B__loss /= n_steps epoch_d_A_M_loss /= n_steps epoch_d_B_M_loss /= n_steps epoch_g_loss /= n_steps epoch_d_loss /= n_steps #summary log list_tag_values = { ("generatorA_to_B loss", epoch_g_A_to_B_loss), ("generatorB_to_A loss", epoch_g_B_to_A_loss), ("discriminator B loss", epoch_d_B__loss), ("discriminator A loss", epoch_d_A__loss), ("epoch discriminators loss", epoch_d_loss), ("epoch generators loss", epoch_g_loss) } self.summarize(list_tag_values, e) #save history data list_epoch_g_loss.append(epoch_g_loss) list_epoch_d_loss.append(epoch_d_loss) list_epoch_g_A_to_B_loss.append(epoch_g_A_to_B_loss) list_epoch_g_B_to_A_loss.append(epoch_g_B_to_A_loss) list_epoch_d_A__loss.append(epoch_d_A__loss) list_epoch_d_B__loss.append(epoch_d_B__loss) list_epoch_d_A_M_loss.append(epoch_d_A_M_loss) list_epoch_d_B_M_loss.append(epoch_d_B_M_loss) # # print("at epoch : ",e) # print("generator loss : ",epoch_g_loss) # print("discriminator loss : ", epoch_g_loss) if (e+1)%model_save_frequenly == 0: self.save_models(e,self.generatorAToB,self.generatorBToA,save_path) history = { "generatorA_to_B loss":list_epoch_g_A_to_B_loss, "generatorB_to_A loss":list_epoch_g_B_to_A_loss, "discriminator B loss": list_epoch_d_B__loss, "discriminator A loss":list_epoch_d_A__loss, "discriminator B_M loss":list_epoch_d_B_M_loss, "discriminator A_M loss": list_epoch_d_A_M_loss, "epoch discriminators loss": list_epoch_d_loss, "epoch generators loss": list_epoch_g_loss } history_table = pd.DataFrame(history) history_table.to_csv(os.path.join(history_path,"history_record.csv"),index=False) def translate_A_to_B(self,inputs): return self.generatorAToB.translate_domain(inputs) def translate_B_to_A(self,inputs): return self.generatorBToA.translate_domain(inputs) # def load_models(self,path): # self.generatorAToB.load(path) # self.generatorBToA.load(path) # self.discriminatorA.load(path) # self.discriminatorB.load(path) # # def save_model(self,path): # self.generatorAToB.save(path) # self.generatorBToA.save(path) # self.discriminatorA.save(path) # self.discriminatorB.save(path) # # # def test(self): # # def generate_result(self,domain): # def generate_result(): class StyleClassifier: def __init__(self,input_dim,lr = 0.0002,beta_1 = 0.5,loss_weight = 0.5): self.input_dim = input_dim self.output_channel = self.input_dim[2] self.lr = lr self.beta_1 = beta_1 self.loss_weight = loss_weight self.model = self.build_model() def build_model(self): input = keras.Input(shape=(self.input_dim)) c1 = keras.layers.Conv2D(filters=64, kernel_size=[1,12], strides=[1,12])(input) c1 = keras.layers.LeakyReLU(alpha=0.3)(c1) c2 = keras.layers.Conv2D(filters=128, kernel_size=[4, 1], strides=[4, 1])(c1) c2 = keras.layers.LeakyReLU(alpha=0.3)(c2) c2 = tfa.layers.InstanceNormalization()(c2) c3 = keras.layers.Conv2D(filters=256, kernel_size=[2, 1], strides=[2, 1])(c2) c3 = keras.layers.LeakyReLU(alpha=0.3)(c3) c3 = tfa.layers.InstanceNormalization()(c3) c4 = keras.layers.Conv2D(filters=512, kernel_size=[8, 1], strides=[8, 1])(c3) c4 = keras.layers.LeakyReLU(alpha=0.3)(c4) c4 = tfa.layers.InstanceNormalization()(c4) c5 = keras.layers.Conv2D(filters=2, kernel_size=[1, 7], strides=[1, 7])(c4) c5 = keras.layers.LeakyReLU(alpha=0.3)(c5) c5 = tfa.layers.InstanceNormalization()(c5) c6 = keras.layers.Flatten()(c5) c6 = keras.layers.Dense(2,activation = 'softmax')(c6) model = keras.Model(input,c6) model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=self.lr, beta_1=self.beta_1), loss_weights=[self.loss_weight]) model.summary() return model # def train(self): # def trainable(self, trainable=True): self.model.trainable = trainable def save(self, path): model_name = 'classifier_model.h5' path = os.path.join(path,model_name) self.model.save(path) def load(self, path): model_name = 'classifier_model.h5' path = os.path.join(path, model_name) self.model = keras.models.load_model(path) def predict(self, input_data): return self.model.predict(input_data) def train(self,train_X,train_Y,test_X,test_Y,batch,num_epochs): return self.model.fit(train_X, train_Y, batch_size=batch, epochs=num_epochs, verbose=1,validation_split=0.2) # def test(self,testA,testB): def main(): # directory_path_A = '../Input_Data_Small_Test/datasetA/npy/' # directory_path_B= '../Input_Data_Small_Test/datasetB/npy/' directory_path_A = 'dataset2/pia2vio_example/trainA/' directory_path_B = 'dataset2/pia2vio_example/trainB/' # directory_path_B = '../dataset/CP_P/test/' datasetA = [] datasetB = [] normalizeA = 14.0 normalizeB = 15.0 # print(np_vars.shape) max = 0 min = 270 for files in os.listdir(directory_path_A): path = os.path.join(directory_path_A,files) data = np.load(path) data = data[:,:,0:256] #only use first channel data = data[0:1, :, :] data = data.reshape((256, 256, 1)) #shrink data to 256 max = np.maximum(max,np.max(data)) min = np.minimum(max,np.min(data)) datasetA.append(data) print("current ata Max ", max) print("current data min : ", min) max = 0 min = 270 for files in os.listdir(directory_path_B): path = os.path.join(directory_path_B,files) data = np.load(path) data = data[:,:,0:256] data = data[0:1,:,:] data = data.reshape((256,256,1)) # print(data) # print("fresh data sbape : ",data.shape) # print("max : ",np.amax(data)) # print("min : ",np.min(data)) # print("process data sbape : ", data.shape) max = np.maximum(max, np.max(data)) min = np.minimum(max, np.min(data)) datasetB.append(data) print("current ata Max ",max) print("current data min : ",min) datasetA = np.array(datasetA)/normalizeA datasetB = np.array(datasetB)/normalizeB datasetA = datasetA datasetB = datasetB print(datasetA.shape) print(np.max(datasetA)) print(np.min(datasetA)) print(datasetB.shape) print(np.max(datasetB)) print(np.min(datasetB)) image_dim = datasetA[0].shape Generator_A_to_B = Generator(input_dim=image_dim) Generator_B_to_A = Generator(input_dim=image_dim) Discriminator_B = Discriminator(input_dim=image_dim) Discriminator_A = Discriminator(input_dim=image_dim) Discriminator_B_M = Discriminator(input_dim=image_dim) Discriminator_A_M = Discriminator(input_dim=image_dim) use_D_M = True batch_size = 24 # with tf.compat.v1.Session() as sess: gan = CycleGan(None,batch_size,image_dim,Generator_A_to_B,Generator_B_to_A,Discriminator_A,Discriminator_B, use_D_M=use_D_M,discriminatorAandM=Discriminator_A_M,discriminatorBandM=Discriminator_B_M) Classifier = StyleClassifier(input_dim=image_dim) save_path = "classifier_model/model_1" Classifier.load(save_path) epoch = 30 model_version = "model_4" save_model_path = "save_model" save_model_path = os.path.join(model_version,save_model_path) log_path = "logs/scalars/" log_path = os.path.join(model_version,log_path) history_path = "history_log" history_path = os.path.join(model_version,history_path) if not os.path.isdir(save_model_path): os.makedirs(save_model_path) if not os.path.isdir(log_path): os.makedirs(log_path) if not os.path.isdir(history_path): os.makedirs(history_path) save_model_frequenly = 5 # gan.train(epoch,batch_size,datasetA,datasetB,save_model_path,log_path,history_path,save_model_frequenly) #test the model path = "model_3/save_model/19/" generator_A_to_B_path = "g_model_AtoB_.h5" generator_B_to_A_path = "g_model_BtoA_.h5" gan.load_models(path,generator_A_to_B_path,generator_B_to_A_path) directory_path_A_test = 'dataset2/pia2vio_example/testA/' directory_path_B_test = 'dataset2/pia2vio_example/testB/' test_A = [] test_B = [] test_A_to_B_result_file_name = [] test_B_to_A_result_file_name = [] result_path = 'result/model_3' path_A_to_B = os.path.join(result_path,'A_to_B') path_B_to_A = os.path.join(result_path,'B_to_A') if not os.path.isdir(path_A_to_B): os.makedirs(path_A_to_B) if not os.path.isdir(path_B_to_A): os.makedirs(path_B_to_A) max = 0 min = 270 for files in os.listdir(directory_path_A_test): path = os.path.join(directory_path_A_test,files) data = np.load(path) data = data[:,:,0:256] data = data[0:1, :, :] data = data.reshape((256, 256, 1)) max = np.maximum(max, np.max(data)) min = np.minimum(max, np.min(data)) test_A.append(data) newfile = "convert_"+files output_path = os.path.join(path_A_to_B, newfile) test_A_to_B_result_file_name.append(output_path) print("current ata Max ", max) print("current data min : ", min) max = 0 min = 270 for files in os.listdir(directory_path_B_test): path = os.path.join(directory_path_B_test,files) data = np.load(path) data = data[:,:,0:256] data = data[0:1, :, :] data = data.reshape((256, 256, 1)) max = np.maximum(max, np.max(data)) min = np.minimum(max, np.min(data)) test_B.append(data) newfile = "convert_" + files output_path = os.path.join(path_B_to_A,newfile) test_B_to_A_result_file_name.append(output_path) print("current ata Max ", max) print("current data min : ", min) # # testA = np.array(test_A)/normalizeA testB = np.array(test_B)/normalizeA # # result_A_to_B = gan.translate_A_to_B(testA) result_B_to_A = gan.translate_B_to_A(testB) # result_A_to_B = result_A_to_B*normalizeA result_B_to_A = result_B_to_A*normalizeA # # testA = testA*normalize_metric # testB = testB*normalize_metric # # for i_A in range(len(test_A_to_B_result_file_name)): current = result_A_to_B[i_A] current = current.reshape((256,256)) print("test shape : ",current.shape) np.save(test_A_to_B_result_file_name[i_A],current) for i_B in range(len(test_B_to_A_result_file_name)): current = result_B_to_A[i_B] current = current.reshape((256,256)) print(current.shape) np.save(test_B_to_A_result_file_name[i_B],current) # sample_A = testA[0].reshape(256,256,4) # A_to_B = result_A_to_B[0].reshape(256,256,4) # # sample_A = sample_A*255.0 # A_to_B = A_to_B*255.0 # # print(np.max(sample_A[:,:,0])) # print(np.max(A_to_B[:, :, 0])) # # new_im = Image.fromarray((sample_A[:,:,0]).astype(np.float32)).convert('RGB') # new_im.save("numpy_altered_sampleA.png") # new_im = Image.fromarray((A_to_B[:,:,0]).astype(np.float32)).convert('RGB') # new_im.save("numpy_altered_A_to_B.png") # sample_A = datasetA[0] # generate_B = gan.translate_A_to_B(sample_A.reshape(1,sample_A.shape[0],sample_A.shape[1],sample_A.shape[2])).reshape(sample_A.shape) # # sample_B = datasetB[0] # generate_A = gan.translate_B_to_A(sample_B.reshape(1,sample_B.shape[0],sample_B.shape[1],sample_B.shape[2])).reshape(sample_B.shape) # max = np.max(sample_B) # min = np.min(sample_B) # for s in datasetB: # # max = np.maximum(np.max(s),max) # min = np.minimum(np.min(s),min) # for s in datasetA: # # max = np.maximum(np.max(s),max) # min = np.minimum(np.min(s),min) # # # print("max : ",max) # print("min : ",min) # print(np.max(sample)) # print(np.min(sample)) # print(np.max(generate_B)) # print(np.min(generate_B)) # plt.imshow(sample) # plt.show() # # print(generate_B.shape) # plt.imshow(generate_B) # plt.show() # print(generate_A.shape) # plt.imshow(generate_A) # plt.show() # print(sample_A) # print(generate_B) # # sample_A = (sample_A/28) # # new_im = Image.fromarray((sample_A*255).astype(np.uint8)).convert('RGB') # new_im.save("numpy_altered_sample1.png") # new_im = Image.fromarray((generate_B * 255).astype(np.uint8)).convert('RGB') # new_im.save("numpy_altered_sample2.png") # new_im = Image.fromarray((sample_B * 255).astype(np.uint8)).convert('RGB') # new_im.save("numpy_altered_sample3.png") # main() def train_classifier(): directory_path_A = 'dataset2/pia2vio_example/trainA/' directory_path_B = 'dataset2/pia2vio_example/trainB/' save_path = "classifier_model/model_1" if not os.path.isdir(save_path): os.makedirs(save_path) datasetA = [] datasetB = [] normalizeA = 14.0 normalizeB = 15.0 for files in os.listdir(directory_path_A): path = os.path.join(directory_path_A, files) data = np.load(path) data = data[:, :, 0:256] # only use first channel data = data[0:1, :, :] data = data.reshape((256, 256, 1)) # shrink data to 256 datasetA.append(data) for files in os.listdir(directory_path_B): path = os.path.join(directory_path_B, files) data = np.load(path) data = data[:, :, 0:256] data = data[0:1, :, :] data = data.reshape((256, 256, 1)) datasetB.append(data) datasetA = np.array(datasetA) / normalizeA datasetB = np.array(datasetB) / normalizeB datasetA = datasetA image_dim = datasetA[0].shape Y_A = np.zeros((len(datasetA),2)) Y_A[:,1] = np.ones(len(datasetA)) print(Y_A.shape) print(Y_A[3]) datasetB = datasetB Y_B = np.zeros((len(datasetA),2)) Y_B[:,0] = np.ones(len(datasetA)) print(datasetA.shape) print(datasetB.shape) X = np.concatenate((datasetA,datasetB),axis=0) Y = np.concatenate((Y_A,Y_B),axis=0) print(X.shape) print(Y.shape) from sklearn.model_selection import train_test_split train_X,test_X,train_Y,test_Y = train_test_split(X, Y, test_size = 0.05, random_state = 42) Classifier = StyleClassifier(input_dim=image_dim) batch = 32 epoch = 50 # history = Classifier.train(train_X,train_Y,test_X,test_Y,num_epochs=epoch,batch=batch) # print(history['val']) # Classifier.save(save_path) Classifier.load(save_path) results = Classifier.predict(train_X) results[results > 0.5] = 1 results[results <= 0.5] = 0 result_vector = np.argmax(results,axis=1) target_vector = np.argmax(train_Y,axis=1) # print(np.argmax(results,axis=1)[:10]) # print(results[:20]) # print(train_Y[:20]) print(np.mean(result_vector==target_vector)) # train_classifier() def convert_hot_encode_to_vector(results): results[results > 0.5] = 1 results[results <= 0.5] = 0 result_vector = np.argmax(results, axis=1) return result_vector def test_classifier(): normalizeA = 14.0 normalizeB = 15.0 image_dim = (256,256,1) Generator_A_to_B = Generator(input_dim=image_dim) Generator_B_to_A = Generator(input_dim=image_dim) Discriminator_B = Discriminator(input_dim=image_dim) Discriminator_A = Discriminator(input_dim=image_dim) Discriminator_B_M = Discriminator(input_dim=image_dim) Discriminator_A_M = Discriminator(input_dim=image_dim) use_D_M = True batch_size = 24 gan = CycleGan(None, batch_size, image_dim, Generator_A_to_B, Generator_B_to_A, Discriminator_A, Discriminator_B, use_D_M=use_D_M, discriminatorAandM=Discriminator_A_M, discriminatorBandM=Discriminator_B_M) path = "model_2/save_model/19/" generator_A_to_B_path = "g_model_AtoB_.h5" generator_B_to_A_path = "g_model_BtoA_.h5" gan.load_models(path, generator_A_to_B_path, generator_B_to_A_path) # directory_path_A_test = 'dataset2/pia2vio_example/testA/' # directory_path_B_test = 'dataset2/pia2vio_example/testB/' directory_path_A_test = 'dataset2/pia2vio_example/trainA/' directory_path_B_test = 'dataset2/pia2vio_example/trainB/' test_A = [] test_B = [] test_A_to_B_result_file_name = [] test_B_to_A_result_file_name = [] result_path = 'result/model_3' path_A_to_B = os.path.join(result_path, 'A_to_B') path_B_to_A = os.path.join(result_path, 'B_to_A') if not os.path.isdir(path_A_to_B): os.makedirs(path_A_to_B) if not os.path.isdir(path_B_to_A): os.makedirs(path_B_to_A) for files in os.listdir(directory_path_A_test): path = os.path.join(directory_path_A_test, files) data = np.load(path) data = data[:, :, 0:256] data = data[0:1, :, :] data = data.reshape((256, 256, 1)) test_A.append(data) newfile = "convert_" + files output_path = os.path.join(path_A_to_B, newfile) test_A_to_B_result_file_name.append(output_path) for files in os.listdir(directory_path_B_test): path = os.path.join(directory_path_B_test, files) data = np.load(path) data = data[:, :, 0:256] data = data[0:1, :, :] data = data.reshape((256, 256, 1)) test_B.append(data) newfile = "convert_" + files output_path = os.path.join(path_B_to_A, newfile) test_B_to_A_result_file_name.append(output_path) testA = np.array(test_A) / normalizeA testB = np.array(test_B) / normalizeA result_A_to_B = gan.translate_A_to_B(testA) result_B_to_A = gan.translate_A_to_B(testB) result_A_to_B = result_A_to_B * normalizeA result_B_to_A = result_B_to_A * normalizeA testA = testA*normalizeA testB = testB*normalizeA #classifier save_path = "classifier_model/model_1" Classifier = StyleClassifier(input_dim=image_dim) Classifier.load(save_path) Y_testA = np.zeros((len(testA), 2)) Y_testA[:, 1] = np.ones(len(testA)) # print(Y_testA.shape) # print(Y_testA[3]) Y_testB = np.zeros((len(testB), 2)) Y_testB[:, 0] = np.ones(len(testB)) Y_result_A_to_B = np.zeros((len(result_A_to_B), 2)) Y_result_A_to_B[:, 0] = np.ones(len(result_A_to_B)) Y_result_B_to_A = np.zeros((len(result_B_to_A), 2)) Y_result_B_to_A[:, 1] = np.ones(len(result_B_to_A)) predict_testA =Classifier.predict(testA) predict_testB = Classifier.predict(testB) predict_result_A_to_B = Classifier.predict(result_A_to_B) predict_result_B_to_A = Classifier.predict(result_B_to_A) predict_testA =convert_hot_encode_to_vector(predict_testA) predict_testB = convert_hot_encode_to_vector(predict_testB) predict_result_A_to_B = convert_hot_encode_to_vector(predict_result_A_to_B) predict_result_B_to_A = convert_hot_encode_to_vector(predict_result_B_to_A) Y_testA = convert_hot_encode_to_vector(Y_testA) Y_testB = convert_hot_encode_to_vector(Y_testB) Y_result_A_to_B = convert_hot_encode_to_vector(Y_result_A_to_B) Y_result_B_to_A = convert_hot_encode_to_vector(Y_result_B_to_A) print(np.mean(Y_testA == predict_testA)) print(np.mean(Y_testB == predict_testB)) print(np.mean(Y_result_A_to_B == predict_result_A_to_B)) print(np.mean(Y_result_B_to_A == predict_result_B_to_A)) # test_classifier()
[ "tensorflow.pad", "numpy.random.rand", "numpy.array", "tensorflow.keras.layers.Dense", "tensorflow.keras.models.load_model", "numpy.save", "matplotlib.pyplot.imshow", "numpy.mean", "os.listdir", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.Sequential", "numpy.asarray", "numpy.max", ...
[((23309, 23337), 'os.listdir', 'os.listdir', (['directory_path_A'], {}), '(directory_path_A)\n', (23319, 23337), False, 'import os\n'), ((23818, 23846), 'os.listdir', 'os.listdir', (['directory_path_B'], {}), '(directory_path_B)\n', (23828, 23846), False, 'import os\n'), ((25643, 25687), 'os.path.join', 'os.path.join', (['model_version', 'save_model_path'], {}), '(model_version, save_model_path)\n', (25655, 25687), False, 'import os\n'), ((25733, 25770), 'os.path.join', 'os.path.join', (['model_version', 'log_path'], {}), '(model_version, log_path)\n', (25745, 25770), False, 'import os\n'), ((25822, 25863), 'os.path.join', 'os.path.join', (['model_version', 'history_path'], {}), '(model_version, history_path)\n', (25834, 25863), False, 'import os\n'), ((26730, 26765), 'os.path.join', 'os.path.join', (['result_path', '"""A_to_B"""'], {}), "(result_path, 'A_to_B')\n", (26742, 26765), False, 'import os\n'), ((26783, 26818), 'os.path.join', 'os.path.join', (['result_path', '"""B_to_A"""'], {}), "(result_path, 'B_to_A')\n", (26795, 26818), False, 'import os\n'), ((27005, 27038), 'os.listdir', 'os.listdir', (['directory_path_A_test'], {}), '(directory_path_A_test)\n', (27015, 27038), False, 'import os\n'), ((27613, 27646), 'os.listdir', 'os.listdir', (['directory_path_B_test'], {}), '(directory_path_B_test)\n', (27623, 27646), False, 'import os\n'), ((31387, 31415), 'os.listdir', 'os.listdir', (['directory_path_A'], {}), '(directory_path_A)\n', (31397, 31415), False, 'import os\n'), ((31716, 31744), 'os.listdir', 'os.listdir', (['directory_path_B'], {}), '(directory_path_B)\n', (31726, 31744), False, 'import os\n'), ((32395, 32439), 'numpy.concatenate', 'np.concatenate', (['(datasetA, datasetB)'], {'axis': '(0)'}), '((datasetA, datasetB), axis=0)\n', (32409, 32439), True, 'import numpy as np\n'), ((32446, 32480), 'numpy.concatenate', 'np.concatenate', (['(Y_A, Y_B)'], {'axis': '(0)'}), '((Y_A, Y_B), axis=0)\n', (32460, 32480), True, 'import numpy as np\n'), ((32610, 32665), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.05)', 'random_state': '(42)'}), '(X, Y, test_size=0.05, random_state=42)\n', (32626, 32665), False, 'from sklearn.model_selection import train_test_split\n'), ((33064, 33090), 'numpy.argmax', 'np.argmax', (['results'], {'axis': '(1)'}), '(results, axis=1)\n', (33073, 33090), True, 'import numpy as np\n'), ((33110, 33136), 'numpy.argmax', 'np.argmax', (['train_Y'], {'axis': '(1)'}), '(train_Y, axis=1)\n', (33119, 33136), True, 'import numpy as np\n'), ((33430, 33456), 'numpy.argmax', 'np.argmax', (['results'], {'axis': '(1)'}), '(results, axis=1)\n', (33439, 33456), True, 'import numpy as np\n'), ((34807, 34842), 'os.path.join', 'os.path.join', (['result_path', '"""A_to_B"""'], {}), "(result_path, 'A_to_B')\n", (34819, 34842), False, 'import os\n'), ((34861, 34896), 'os.path.join', 'os.path.join', (['result_path', '"""B_to_A"""'], {}), "(result_path, 'B_to_A')\n", (34873, 34896), False, 'import os\n'), ((35058, 35091), 'os.listdir', 'os.listdir', (['directory_path_A_test'], {}), '(directory_path_A_test)\n', (35068, 35091), False, 'import os\n'), ((35483, 35516), 'os.listdir', 'os.listdir', (['directory_path_B_test'], {}), '(directory_path_B_test)\n', (35493, 35516), False, 'import os\n'), ((1595, 1628), 'tensorflow.keras.Input', 'keras.Input', ([], {'shape': 'self.input_dim'}), '(shape=self.input_dim)\n', (1606, 1628), True, 'from tensorflow import keras as keras\n'), ((1644, 1702), 'tensorflow.pad', 'tf.pad', (['input', '[[0, 0], [3, 3], [3, 3], [0, 0]]', '"""REFLECT"""'], {}), "(input, [[0, 0], [3, 3], [3, 3], [0, 0]], 'REFLECT')\n", (1650, 1702), True, 'import tensorflow as tf\n'), ((2916, 2984), 'tensorflow.pad', 'tf.pad', (['d2', '[[0, 0], [3, 3], [3, 3], [0, 0]]', '"""REFLECT"""'], {'name': '"""g_d3"""'}), "(d2, [[0, 0], [3, 3], [3, 3], [0, 0]], 'REFLECT', name='g_d3')\n", (2922, 2984), True, 'import tensorflow as tf\n'), ((3120, 3146), 'tensorflow.keras.Model', 'keras.Model', (['input', 'output'], {}), '(input, output)\n', (3131, 3146), True, 'from tensorflow import keras as keras\n'), ((3379, 3408), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['path'], {}), '(path)\n', (3402, 3408), True, 'from tensorflow import keras as keras\n'), ((3887, 3905), 'tensorflow.keras.Sequential', 'keras.Sequential', ([], {}), '()\n', (3903, 3905), True, 'from tensorflow import keras as keras\n'), ((4715, 4744), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['path'], {}), '(path)\n', (4738, 4744), True, 'from tensorflow import keras as keras\n'), ((6596, 6630), 'tensorflow.keras.Input', 'keras.Input', ([], {'shape': 'self.image_size'}), '(shape=self.image_size)\n', (6607, 6630), True, 'from tensorflow import keras as keras\n'), ((6654, 6688), 'tensorflow.keras.Input', 'keras.Input', ([], {'shape': 'self.image_size'}), '(shape=self.image_size)\n', (6665, 6688), True, 'from tensorflow import keras as keras\n'), ((7100, 7168), 'tensorflow.keras.Model', 'keras.Model', (['[input_real_A, input_real_B]', '[dis_B, fake_A_, fake_B_]'], {}), '([input_real_A, input_real_B], [dis_B, fake_A_, fake_B_])\n', (7111, 7168), True, 'from tensorflow import keras as keras\n'), ((7237, 7264), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0002)', 'beta_1': '(0.5)'}), '(lr=0.0002, beta_1=0.5)\n', (7241, 7264), False, 'from tensorflow.keras.optimizers import Adam\n'), ((7708, 7758), 'numpy.random.randint', 'np.random.randint', (['(0)', 'dataset.shape[0]', 'batch_size'], {}), '(0, dataset.shape[0], batch_size)\n', (7725, 7758), True, 'import numpy as np\n'), ((7873, 7937), 'numpy.ones', 'np.ones', (['(batch_size, output_shape, output_shape, channel_shape)'], {}), '((batch_size, output_shape, output_shape, channel_shape))\n', (7880, 7937), True, 'import numpy as np\n'), ((8655, 8719), 'numpy.ones', 'np.ones', (['(batch_size, output_shape, output_shape, channel_shape)'], {}), '((batch_size, output_shape, output_shape, channel_shape))\n', (8662, 8719), True, 'import numpy as np\n'), ((9170, 9201), 'os.path.join', 'os.path.join', (['folder', 'filename1'], {}), '(folder, filename1)\n', (9182, 9201), False, 'import os\n'), ((9347, 9378), 'os.path.join', 'os.path.join', (['folder', 'filename2'], {}), '(folder, filename2)\n', (9359, 9378), False, 'import os\n'), ((9557, 9586), 'os.path.join', 'os.path.join', (['path', 'filename1'], {}), '(path, filename1)\n', (9569, 9586), False, 'import os\n'), ((9650, 9679), 'os.path.join', 'os.path.join', (['path', 'filename2'], {}), '(path, filename2)\n', (9662, 9679), False, 'import os\n'), ((10659, 10681), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename1'], {}), '(filename1)\n', (10670, 10681), True, 'import matplotlib.pyplot as plt\n'), ((10690, 10701), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (10699, 10701), True, 'import matplotlib.pyplot as plt\n'), ((11327, 11347), 'numpy.asarray', 'np.asarray', (['selected'], {}), '(selected)\n', (11337, 11347), True, 'import numpy as np\n'), ((11795, 11840), 'tensorflow.summary.create_file_writer', 'tf.summary.create_file_writer', (['summary_folder'], {}), '(summary_folder)\n', (11824, 11840), True, 'import tensorflow as tf\n'), ((20850, 20883), 'tensorflow.keras.Input', 'keras.Input', ([], {'shape': 'self.input_dim'}), '(shape=self.input_dim)\n', (20861, 20883), True, 'from tensorflow import keras as keras\n'), ((21904, 21926), 'tensorflow.keras.Model', 'keras.Model', (['input', 'c6'], {}), '(input, c6)\n', (21915, 21926), True, 'from tensorflow import keras as keras\n'), ((22312, 22342), 'os.path.join', 'os.path.join', (['path', 'model_name'], {}), '(path, model_name)\n', (22324, 22342), False, 'import os\n'), ((22457, 22487), 'os.path.join', 'os.path.join', (['path', 'model_name'], {}), '(path, model_name)\n', (22469, 22487), False, 'import os\n'), ((22509, 22538), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['path'], {}), '(path)\n', (22532, 22538), True, 'from tensorflow import keras as keras\n'), ((23354, 23391), 'os.path.join', 'os.path.join', (['directory_path_A', 'files'], {}), '(directory_path_A, files)\n', (23366, 23391), False, 'import os\n'), ((23406, 23419), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (23413, 23419), True, 'import numpy as np\n'), ((23863, 23900), 'os.path.join', 'os.path.join', (['directory_path_B', 'files'], {}), '(directory_path_B, files)\n', (23875, 23900), False, 'import os\n'), ((23915, 23928), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (23922, 23928), True, 'import numpy as np\n'), ((24440, 24458), 'numpy.array', 'np.array', (['datasetA'], {}), '(datasetA)\n', (24448, 24458), True, 'import numpy as np\n'), ((24485, 24503), 'numpy.array', 'np.array', (['datasetB'], {}), '(datasetB)\n', (24493, 24503), True, 'import numpy as np\n'), ((24601, 24617), 'numpy.max', 'np.max', (['datasetA'], {}), '(datasetA)\n', (24607, 24617), True, 'import numpy as np\n'), ((24629, 24645), 'numpy.min', 'np.min', (['datasetA'], {}), '(datasetA)\n', (24635, 24645), True, 'import numpy as np\n'), ((24683, 24699), 'numpy.max', 'np.max', (['datasetB'], {}), '(datasetB)\n', (24689, 24699), True, 'import numpy as np\n'), ((24711, 24727), 'numpy.min', 'np.min', (['datasetB'], {}), '(datasetB)\n', (24717, 24727), True, 'import numpy as np\n'), ((25874, 25904), 'os.path.isdir', 'os.path.isdir', (['save_model_path'], {}), '(save_model_path)\n', (25887, 25904), False, 'import os\n'), ((25914, 25942), 'os.makedirs', 'os.makedirs', (['save_model_path'], {}), '(save_model_path)\n', (25925, 25942), False, 'import os\n'), ((25954, 25977), 'os.path.isdir', 'os.path.isdir', (['log_path'], {}), '(log_path)\n', (25967, 25977), False, 'import os\n'), ((25987, 26008), 'os.makedirs', 'os.makedirs', (['log_path'], {}), '(log_path)\n', (25998, 26008), False, 'import os\n'), ((26020, 26047), 'os.path.isdir', 'os.path.isdir', (['history_path'], {}), '(history_path)\n', (26033, 26047), False, 'import os\n'), ((26057, 26082), 'os.makedirs', 'os.makedirs', (['history_path'], {}), '(history_path)\n', (26068, 26082), False, 'import os\n'), ((26829, 26855), 'os.path.isdir', 'os.path.isdir', (['path_A_to_B'], {}), '(path_A_to_B)\n', (26842, 26855), False, 'import os\n'), ((26865, 26889), 'os.makedirs', 'os.makedirs', (['path_A_to_B'], {}), '(path_A_to_B)\n', (26876, 26889), False, 'import os\n'), ((26901, 26927), 'os.path.isdir', 'os.path.isdir', (['path_B_to_A'], {}), '(path_B_to_A)\n', (26914, 26927), False, 'import os\n'), ((26937, 26961), 'os.makedirs', 'os.makedirs', (['path_B_to_A'], {}), '(path_B_to_A)\n', (26948, 26961), False, 'import os\n'), ((27055, 27097), 'os.path.join', 'os.path.join', (['directory_path_A_test', 'files'], {}), '(directory_path_A_test, files)\n', (27067, 27097), False, 'import os\n'), ((27112, 27125), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (27119, 27125), True, 'import numpy as np\n'), ((27404, 27438), 'os.path.join', 'os.path.join', (['path_A_to_B', 'newfile'], {}), '(path_A_to_B, newfile)\n', (27416, 27438), False, 'import os\n'), ((27663, 27705), 'os.path.join', 'os.path.join', (['directory_path_B_test', 'files'], {}), '(directory_path_B_test, files)\n', (27675, 27705), False, 'import os\n'), ((27720, 27733), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (27727, 27733), True, 'import numpy as np\n'), ((28014, 28048), 'os.path.join', 'os.path.join', (['path_B_to_A', 'newfile'], {}), '(path_B_to_A, newfile)\n', (28026, 28048), False, 'import os\n'), ((28198, 28214), 'numpy.array', 'np.array', (['test_A'], {}), '(test_A)\n', (28206, 28214), True, 'import numpy as np\n'), ((28238, 28254), 'numpy.array', 'np.array', (['test_B'], {}), '(test_B)\n', (28246, 28254), True, 'import numpy as np\n'), ((28750, 28801), 'numpy.save', 'np.save', (['test_A_to_B_result_file_name[i_A]', 'current'], {}), '(test_A_to_B_result_file_name[i_A], current)\n', (28757, 28801), True, 'import numpy as np\n'), ((28977, 29028), 'numpy.save', 'np.save', (['test_B_to_A_result_file_name[i_B]', 'current'], {}), '(test_B_to_A_result_file_name[i_B], current)\n', (28984, 29028), True, 'import numpy as np\n'), ((31233, 31257), 'os.path.isdir', 'os.path.isdir', (['save_path'], {}), '(save_path)\n', (31246, 31257), False, 'import os\n'), ((31267, 31289), 'os.makedirs', 'os.makedirs', (['save_path'], {}), '(save_path)\n', (31278, 31289), False, 'import os\n'), ((31432, 31469), 'os.path.join', 'os.path.join', (['directory_path_A', 'files'], {}), '(directory_path_A, files)\n', (31444, 31469), False, 'import os\n'), ((31485, 31498), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (31492, 31498), True, 'import numpy as np\n'), ((31761, 31798), 'os.path.join', 'os.path.join', (['directory_path_B', 'files'], {}), '(directory_path_B, files)\n', (31773, 31798), False, 'import os\n'), ((31814, 31827), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (31821, 31827), True, 'import numpy as np\n'), ((31981, 31999), 'numpy.array', 'np.array', (['datasetA'], {}), '(datasetA)\n', (31989, 31999), True, 'import numpy as np\n'), ((32028, 32046), 'numpy.array', 'np.array', (['datasetB'], {}), '(datasetB)\n', (32036, 32046), True, 'import numpy as np\n'), ((33242, 33281), 'numpy.mean', 'np.mean', (['(result_vector == target_vector)'], {}), '(result_vector == target_vector)\n', (33249, 33281), True, 'import numpy as np\n'), ((34908, 34934), 'os.path.isdir', 'os.path.isdir', (['path_A_to_B'], {}), '(path_A_to_B)\n', (34921, 34934), False, 'import os\n'), ((34944, 34968), 'os.makedirs', 'os.makedirs', (['path_A_to_B'], {}), '(path_A_to_B)\n', (34955, 34968), False, 'import os\n'), ((34980, 35006), 'os.path.isdir', 'os.path.isdir', (['path_B_to_A'], {}), '(path_B_to_A)\n', (34993, 35006), False, 'import os\n'), ((35016, 35040), 'os.makedirs', 'os.makedirs', (['path_B_to_A'], {}), '(path_B_to_A)\n', (35027, 35040), False, 'import os\n'), ((35108, 35150), 'os.path.join', 'os.path.join', (['directory_path_A_test', 'files'], {}), '(directory_path_A_test, files)\n', (35120, 35150), False, 'import os\n'), ((35166, 35179), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (35173, 35179), True, 'import numpy as np\n'), ((35374, 35408), 'os.path.join', 'os.path.join', (['path_A_to_B', 'newfile'], {}), '(path_A_to_B, newfile)\n', (35386, 35408), False, 'import os\n'), ((35533, 35575), 'os.path.join', 'os.path.join', (['directory_path_B_test', 'files'], {}), '(directory_path_B_test, files)\n', (35545, 35575), False, 'import os\n'), ((35591, 35604), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (35598, 35604), True, 'import numpy as np\n'), ((35799, 35833), 'os.path.join', 'os.path.join', (['path_B_to_A', 'newfile'], {}), '(path_B_to_A, newfile)\n', (35811, 35833), False, 'import os\n'), ((35904, 35920), 'numpy.array', 'np.array', (['test_A'], {}), '(test_A)\n', (35912, 35920), True, 'import numpy as np\n'), ((35946, 35962), 'numpy.array', 'np.array', (['test_B'], {}), '(test_B)\n', (35954, 35962), True, 'import numpy as np\n'), ((37564, 37597), 'numpy.mean', 'np.mean', (['(Y_testA == predict_testA)'], {}), '(Y_testA == predict_testA)\n', (37571, 37597), True, 'import numpy as np\n'), ((37609, 37642), 'numpy.mean', 'np.mean', (['(Y_testB == predict_testB)'], {}), '(Y_testB == predict_testB)\n', (37616, 37642), True, 'import numpy as np\n'), ((37655, 37704), 'numpy.mean', 'np.mean', (['(Y_result_A_to_B == predict_result_A_to_B)'], {}), '(Y_result_A_to_B == predict_result_A_to_B)\n', (37662, 37704), True, 'import numpy as np\n'), ((37716, 37765), 'numpy.mean', 'np.mean', (['(Y_result_B_to_A == predict_result_B_to_A)'], {}), '(Y_result_B_to_A == predict_result_B_to_A)\n', (37723, 37765), True, 'import numpy as np\n'), ((968, 1031), 'tensorflow.pad', 'tf.pad', (['input_data', '[[0, 0], [p, p], [p, p], [0, 0]]', '"""REFLECT"""'], {}), "(input_data, [[0, 0], [p, p], [p, p], [0, 0]], 'REFLECT')\n", (974, 1031), True, 'import tensorflow as tf\n'), ((1233, 1287), 'tensorflow.pad', 'tf.pad', (['x', '[[0, 0], [p, p], [p, p], [0, 0]]', '"""REFLECT"""'], {}), "(x, [[0, 0], [p, p], [p, p], [0, 0]], 'REFLECT')\n", (1239, 1287), True, 'import tensorflow as tf\n'), ((1763, 1860), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': '(64)', 'kernel_size': '(7)', 'strides': '(1)', 'activation': '"""relu"""', 'padding': '"""VALID"""'}), "(filters=64, kernel_size=7, strides=1, activation='relu',\n padding='VALID')\n", (1782, 1860), True, 'from tensorflow import keras as keras\n'), ((1873, 1907), 'tensorflow_addons.layers.InstanceNormalization', 'tfa.layers.InstanceNormalization', ([], {}), '()\n', (1905, 1907), True, 'import tensorflow_addons as tfa\n'), ((1973, 2071), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': '(128)', 'kernel_size': '(3)', 'strides': '(2)', 'activation': '"""relu"""', 'padding': '"""SAME"""'}), "(filters=128, kernel_size=3, strides=2, activation=\n 'relu', padding='SAME')\n", (1992, 2071), True, 'from tensorflow import keras as keras\n'), ((2085, 2119), 'tensorflow_addons.layers.InstanceNormalization', 'tfa.layers.InstanceNormalization', ([], {}), '()\n', (2117, 2119), True, 'import tensorflow_addons as tfa\n'), ((2186, 2284), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': '(256)', 'kernel_size': '(3)', 'strides': '(2)', 'activation': '"""relu"""', 'padding': '"""SAME"""'}), "(filters=256, kernel_size=3, strides=2, activation=\n 'relu', padding='SAME')\n", (2205, 2284), True, 'from tensorflow import keras as keras\n'), ((2297, 2331), 'tensorflow_addons.layers.InstanceNormalization', 'tfa.layers.InstanceNormalization', ([], {}), '()\n', (2329, 2331), True, 'import tensorflow_addons as tfa\n'), ((2542, 2661), 'tensorflow.keras.layers.Conv2DTranspose', 'keras.layers.Conv2DTranspose', ([], {'filters': '(128)', 'kernel_size': '(3)', 'strides': '(2)', 'activation': '"""relu"""', 'padding': '"""SAME"""', 'name': '"""g_d1"""'}), "(filters=128, kernel_size=3, strides=2,\n activation='relu', padding='SAME', name='g_d1')\n", (2570, 2661), True, 'from tensorflow import keras as keras\n'), ((2677, 2711), 'tensorflow_addons.layers.InstanceNormalization', 'tfa.layers.InstanceNormalization', ([], {}), '()\n', (2709, 2711), True, 'import tensorflow_addons as tfa\n'), ((2729, 2847), 'tensorflow.keras.layers.Conv2DTranspose', 'keras.layers.Conv2DTranspose', ([], {'filters': '(64)', 'kernel_size': '(3)', 'strides': '(2)', 'activation': '"""relu"""', 'padding': '"""SAME"""', 'name': '"""g_d2"""'}), "(filters=64, kernel_size=3, strides=2,\n activation='relu', padding='SAME', name='g_d2')\n", (2757, 2847), True, 'from tensorflow import keras as keras\n'), ((2863, 2897), 'tensorflow_addons.layers.InstanceNormalization', 'tfa.layers.InstanceNormalization', ([], {}), '()\n', (2895, 2897), True, 'import tensorflow_addons as tfa\n'), ((3003, 3103), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': 'self.output_channel', 'kernel_size': '(7)', 'strides': '(1)', 'activation': '"""sigmoid"""'}), "(filters=self.output_channel, kernel_size=7, strides=1,\n activation='sigmoid')\n", (3022, 3103), True, 'from tensorflow import keras as keras\n'), ((3924, 4029), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': '(64)', 'kernel_size': '(4)', 'strides': '(2)', 'padding': '"""SAME"""', 'input_shape': 'self.input_dim'}), "(filters=64, kernel_size=4, strides=2, padding='SAME',\n input_shape=self.input_dim)\n", (3943, 4029), True, 'from tensorflow import keras as keras\n'), ((4045, 4078), 'tensorflow.keras.layers.LeakyReLU', 'keras.layers.LeakyReLU', ([], {'alpha': '(0.3)'}), '(alpha=0.3)\n', (4067, 4078), True, 'from tensorflow import keras as keras\n'), ((4098, 4172), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': '(256)', 'kernel_size': '(4)', 'strides': '(2)', 'padding': '"""SAME"""'}), "(filters=256, kernel_size=4, strides=2, padding='SAME')\n", (4117, 4172), True, 'from tensorflow import keras as keras\n'), ((4193, 4226), 'tensorflow.keras.layers.LeakyReLU', 'keras.layers.LeakyReLU', ([], {'alpha': '(0.3)'}), '(alpha=0.3)\n', (4215, 4226), True, 'from tensorflow import keras as keras\n'), ((4246, 4280), 'tensorflow_addons.layers.InstanceNormalization', 'tfa.layers.InstanceNormalization', ([], {}), '()\n', (4278, 4280), True, 'import tensorflow_addons as tfa\n'), ((4300, 4374), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': 'self.output_channel', 'kernel_size': '(1)', 'strides': '(1)'}), '(filters=self.output_channel, kernel_size=1, strides=1)\n', (4319, 4374), True, 'from tensorflow import keras as keras\n'), ((8794, 8828), 'numpy.concatenate', 'np.concatenate', (['(X_A, X_B)'], {'axis': '(0)'}), '((X_A, X_B), axis=0)\n', (8808, 8828), True, 'import numpy as np\n'), ((9056, 9077), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (9069, 9077), False, 'import os\n'), ((9091, 9110), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (9102, 9110), False, 'import os\n'), ((10275, 10307), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', 'n_samples', '(1 + i)'], {}), '(2, n_samples, 1 + i)\n', (10286, 10307), True, 'import matplotlib.pyplot as plt\n'), ((10320, 10335), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (10328, 10335), True, 'import matplotlib.pyplot as plt\n'), ((10348, 10367), 'matplotlib.pyplot.imshow', 'plt.imshow', (['X_in[i]'], {}), '(X_in[i])\n', (10358, 10367), True, 'import matplotlib.pyplot as plt\n'), ((10447, 10491), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', 'n_samples', '(1 + n_samples + i)'], {}), '(2, n_samples, 1 + n_samples + i)\n', (10458, 10491), True, 'import matplotlib.pyplot as plt\n'), ((10504, 10519), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (10512, 10519), True, 'import matplotlib.pyplot as plt\n'), ((10532, 10552), 'matplotlib.pyplot.imshow', 'plt.imshow', (['X_out[i]'], {}), '(X_out[i])\n', (10542, 10552), True, 'import matplotlib.pyplot as plt\n'), ((20900, 20969), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': '(64)', 'kernel_size': '[1, 12]', 'strides': '[1, 12]'}), '(filters=64, kernel_size=[1, 12], strides=[1, 12])\n', (20919, 20969), True, 'from tensorflow import keras as keras\n'), ((20988, 21021), 'tensorflow.keras.layers.LeakyReLU', 'keras.layers.LeakyReLU', ([], {'alpha': '(0.3)'}), '(alpha=0.3)\n', (21010, 21021), True, 'from tensorflow import keras as keras\n'), ((21040, 21108), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': '(128)', 'kernel_size': '[4, 1]', 'strides': '[4, 1]'}), '(filters=128, kernel_size=[4, 1], strides=[4, 1])\n', (21059, 21108), True, 'from tensorflow import keras as keras\n'), ((21126, 21159), 'tensorflow.keras.layers.LeakyReLU', 'keras.layers.LeakyReLU', ([], {'alpha': '(0.3)'}), '(alpha=0.3)\n', (21148, 21159), True, 'from tensorflow import keras as keras\n'), ((21177, 21211), 'tensorflow_addons.layers.InstanceNormalization', 'tfa.layers.InstanceNormalization', ([], {}), '()\n', (21209, 21211), True, 'import tensorflow_addons as tfa\n'), ((21230, 21298), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': '(256)', 'kernel_size': '[2, 1]', 'strides': '[2, 1]'}), '(filters=256, kernel_size=[2, 1], strides=[2, 1])\n', (21249, 21298), True, 'from tensorflow import keras as keras\n'), ((21316, 21349), 'tensorflow.keras.layers.LeakyReLU', 'keras.layers.LeakyReLU', ([], {'alpha': '(0.3)'}), '(alpha=0.3)\n', (21338, 21349), True, 'from tensorflow import keras as keras\n'), ((21367, 21401), 'tensorflow_addons.layers.InstanceNormalization', 'tfa.layers.InstanceNormalization', ([], {}), '()\n', (21399, 21401), True, 'import tensorflow_addons as tfa\n'), ((21420, 21488), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': '(512)', 'kernel_size': '[8, 1]', 'strides': '[8, 1]'}), '(filters=512, kernel_size=[8, 1], strides=[8, 1])\n', (21439, 21488), True, 'from tensorflow import keras as keras\n'), ((21506, 21539), 'tensorflow.keras.layers.LeakyReLU', 'keras.layers.LeakyReLU', ([], {'alpha': '(0.3)'}), '(alpha=0.3)\n', (21528, 21539), True, 'from tensorflow import keras as keras\n'), ((21557, 21591), 'tensorflow_addons.layers.InstanceNormalization', 'tfa.layers.InstanceNormalization', ([], {}), '()\n', (21589, 21591), True, 'import tensorflow_addons as tfa\n'), ((21610, 21676), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': '(2)', 'kernel_size': '[1, 7]', 'strides': '[1, 7]'}), '(filters=2, kernel_size=[1, 7], strides=[1, 7])\n', (21629, 21676), True, 'from tensorflow import keras as keras\n'), ((21694, 21727), 'tensorflow.keras.layers.LeakyReLU', 'keras.layers.LeakyReLU', ([], {'alpha': '(0.3)'}), '(alpha=0.3)\n', (21716, 21727), True, 'from tensorflow import keras as keras\n'), ((21745, 21779), 'tensorflow_addons.layers.InstanceNormalization', 'tfa.layers.InstanceNormalization', ([], {}), '()\n', (21777, 21779), True, 'import tensorflow_addons as tfa\n'), ((21798, 21820), 'tensorflow.keras.layers.Flatten', 'keras.layers.Flatten', ([], {}), '()\n', (21818, 21820), True, 'from tensorflow import keras as keras\n'), ((21838, 21881), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(2)'], {'activation': '"""softmax"""'}), "(2, activation='softmax')\n", (21856, 21881), True, 'from tensorflow import keras as keras\n'), ((23614, 23626), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (23620, 23626), True, 'import numpy as np\n'), ((23657, 23669), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (23663, 23669), True, 'import numpy as np\n'), ((24264, 24276), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (24270, 24276), True, 'import numpy as np\n'), ((24308, 24320), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (24314, 24320), True, 'import numpy as np\n'), ((27261, 27273), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (27267, 27273), True, 'import numpy as np\n'), ((27305, 27317), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (27311, 27317), True, 'import numpy as np\n'), ((27869, 27881), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (27875, 27881), True, 'import numpy as np\n'), ((27913, 27925), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (27919, 27925), True, 'import numpy as np\n'), ((1048, 1164), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', ([], {'filters': 'filters', 'kernel_size': 'conv_size', 'strides': 'strides', 'activation': '"""relu"""', 'padding': '"""VALID"""'}), "(filters=filters, kernel_size=conv_size, strides=strides,\n activation='relu', padding='VALID')\n", (1067, 1164), True, 'from tensorflow import keras as keras\n'), ((1179, 1213), 'tensorflow_addons.layers.InstanceNormalization', 'tfa.layers.InstanceNormalization', ([], {}), '()\n', (1211, 1213), True, 'import tensorflow_addons as tfa\n'), ((1304, 1379), 'tensorflow.keras.layers.Conv2D', 'keras.layers.Conv2D', (['filters', 'conv_size'], {'activation': '"""relu"""', 'padding': '"""VALID"""'}), "(filters, conv_size, activation='relu', padding='VALID')\n", (1323, 1379), True, 'from tensorflow import keras as keras\n'), ((1399, 1433), 'tensorflow_addons.layers.InstanceNormalization', 'tfa.layers.InstanceNormalization', ([], {}), '()\n', (1431, 1433), True, 'import tensorflow_addons as tfa\n'), ((1453, 1471), 'tensorflow.keras.layers.Add', 'keras.layers.Add', ([], {}), '()\n', (1469, 1471), True, 'from tensorflow import keras as keras\n'), ((1505, 1536), 'tensorflow.keras.layers.Activation', 'keras.layers.Activation', (['"""relu"""'], {}), "('relu')\n", (1528, 1536), True, 'from tensorflow import keras as keras\n'), ((4420, 4447), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0002)', 'beta_1': '(0.5)'}), '(lr=0.0002, beta_1=0.5)\n', (4424, 4447), False, 'from tensorflow.keras.optimizers import Adam\n'), ((8737, 8771), 'numpy.concatenate', 'np.concatenate', (['(X_A, X_B)'], {'axis': '(0)'}), '((X_A, X_B), axis=0)\n', (8751, 8771), True, 'import numpy as np\n'), ((11499, 11539), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['tag', 'value'], {'step': 'step'}), '(tag, value, step=step)\n', (11516, 11539), True, 'import tensorflow as tf\n'), ((19664, 19685), 'pandas.DataFrame', 'pd.DataFrame', (['history'], {}), '(history)\n', (19676, 19685), True, 'import pandas as pd\n'), ((21991, 22027), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': 'self.lr', 'beta_1': 'self.beta_1'}), '(lr=self.lr, beta_1=self.beta_1)\n', (21995, 22027), False, 'from tensorflow.keras.optimizers import Adam\n'), ((10978, 10994), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (10992, 10994), True, 'import numpy as np\n'), ((19724, 19772), 'os.path.join', 'os.path.join', (['history_path', '"""history_record.csv"""'], {}), "(history_path, 'history_record.csv')\n", (19736, 19772), False, 'import os\n')]
import numpy as np import matplotlib.pyplot as plt import numpy.fft as nf from dataset import data_load feat = 'O3' def plotfft(arr): plt.subplot(2, 1, 1) plt.plot(arr) plt.subplot(2, 1, 2) plt.ylim([0,400]) plt.xlim([0,300]) comp_arr = nf.fft(arr) y2 = nf.ifft(comp_arr).real freqs = nf.fftfreq(arr.size, 1/24/24) pows = np.abs(comp_arr) # 复数的模 plt.plot(freqs[freqs > 0], pows[freqs > 0], color='orangered', label='frequency') plt.show() def main(): df = data_load('A_h_CW_detection') arr = np.array(df[feat]) arr = (arr - arr.min())/(arr.max()-arr.min()) plotfft(arr) def main2(): x = np.linspace(-2 * np.pi, 2 * np.pi, 1000) y = np.zeros(x.size) for i in range(1, 1000): y += 4 * np.pi / (2 * i - 1) * np.sin((2 * i - 1) * x) plt.figure('FFT', facecolor='lightgray') plt.subplot(121) plt.title('Time Domain', fontsize=16) plt.grid(linestyle=':') plt.plot( x,y, label=r'$y$') # 针对方波y做fft comp_arr = nf.fft(y) y2 = nf.ifft(comp_arr).real plt.plot(x, y2, color='orangered', linewidth=5, alpha=0.5, label=r'$y$') # 绘制频域图形 plt.subplot(122) freqs = nf.fftfreq(y.size, x[1] - x[0]) pows = np.abs(comp_arr) # 复数的模 plt.title('Frequency Domain', fontsize=16) plt.grid(linestyle=':') plt.plot(freqs[freqs > 0], pows[freqs > 0], color='orangered', label='frequency') plt.legend() plt.savefig('fft.png') plt.show() if __name__ == '__main__': main()
[ "matplotlib.pyplot.grid", "numpy.array", "numpy.sin", "matplotlib.pyplot.plot", "numpy.fft.fft", "numpy.linspace", "matplotlib.pyplot.ylim", "numpy.abs", "matplotlib.pyplot.savefig", "dataset.data_load", "matplotlib.pyplot.title", "matplotlib.pyplot.xlim", "numpy.fft.ifft", "matplotlib.pyp...
[((141, 161), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (152, 161), True, 'import matplotlib.pyplot as plt\n'), ((166, 179), 'matplotlib.pyplot.plot', 'plt.plot', (['arr'], {}), '(arr)\n', (174, 179), True, 'import matplotlib.pyplot as plt\n'), ((184, 204), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (195, 204), True, 'import matplotlib.pyplot as plt\n'), ((210, 228), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 400]'], {}), '([0, 400])\n', (218, 228), True, 'import matplotlib.pyplot as plt\n'), ((232, 250), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, 300]'], {}), '([0, 300])\n', (240, 250), True, 'import matplotlib.pyplot as plt\n'), ((266, 277), 'numpy.fft.fft', 'nf.fft', (['arr'], {}), '(arr)\n', (272, 277), True, 'import numpy.fft as nf\n'), ((322, 355), 'numpy.fft.fftfreq', 'nf.fftfreq', (['arr.size', '(1 / 24 / 24)'], {}), '(arr.size, 1 / 24 / 24)\n', (332, 355), True, 'import numpy.fft as nf\n'), ((363, 379), 'numpy.abs', 'np.abs', (['comp_arr'], {}), '(comp_arr)\n', (369, 379), True, 'import numpy as np\n'), ((392, 478), 'matplotlib.pyplot.plot', 'plt.plot', (['freqs[freqs > 0]', 'pows[freqs > 0]'], {'color': '"""orangered"""', 'label': '"""frequency"""'}), "(freqs[freqs > 0], pows[freqs > 0], color='orangered', label=\n 'frequency')\n", (400, 478), True, 'import matplotlib.pyplot as plt\n'), ((479, 489), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (487, 489), True, 'import matplotlib.pyplot as plt\n'), ((511, 540), 'dataset.data_load', 'data_load', (['"""A_h_CW_detection"""'], {}), "('A_h_CW_detection')\n", (520, 540), False, 'from dataset import data_load\n'), ((552, 570), 'numpy.array', 'np.array', (['df[feat]'], {}), '(df[feat])\n', (560, 570), True, 'import numpy as np\n'), ((662, 702), 'numpy.linspace', 'np.linspace', (['(-2 * np.pi)', '(2 * np.pi)', '(1000)'], {}), '(-2 * np.pi, 2 * np.pi, 1000)\n', (673, 702), True, 'import numpy as np\n'), ((711, 727), 'numpy.zeros', 'np.zeros', (['x.size'], {}), '(x.size)\n', (719, 727), True, 'import numpy as np\n'), ((825, 865), 'matplotlib.pyplot.figure', 'plt.figure', (['"""FFT"""'], {'facecolor': '"""lightgray"""'}), "('FFT', facecolor='lightgray')\n", (835, 865), True, 'import matplotlib.pyplot as plt\n'), ((870, 886), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (881, 886), True, 'import matplotlib.pyplot as plt\n'), ((891, 928), 'matplotlib.pyplot.title', 'plt.title', (['"""Time Domain"""'], {'fontsize': '(16)'}), "('Time Domain', fontsize=16)\n", (900, 928), True, 'import matplotlib.pyplot as plt\n'), ((933, 956), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'linestyle': '""":"""'}), "(linestyle=':')\n", (941, 956), True, 'import matplotlib.pyplot as plt\n'), ((961, 988), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {'label': '"""$y$"""'}), "(x, y, label='$y$')\n", (969, 988), True, 'import matplotlib.pyplot as plt\n'), ((1021, 1030), 'numpy.fft.fft', 'nf.fft', (['y'], {}), '(y)\n', (1027, 1030), True, 'import numpy.fft as nf\n'), ((1067, 1138), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y2'], {'color': '"""orangered"""', 'linewidth': '(5)', 'alpha': '(0.5)', 'label': '"""$y$"""'}), "(x, y2, color='orangered', linewidth=5, alpha=0.5, label='$y$')\n", (1075, 1138), True, 'import matplotlib.pyplot as plt\n'), ((1157, 1173), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (1168, 1173), True, 'import matplotlib.pyplot as plt\n'), ((1186, 1217), 'numpy.fft.fftfreq', 'nf.fftfreq', (['y.size', '(x[1] - x[0])'], {}), '(y.size, x[1] - x[0])\n', (1196, 1217), True, 'import numpy.fft as nf\n'), ((1229, 1245), 'numpy.abs', 'np.abs', (['comp_arr'], {}), '(comp_arr)\n', (1235, 1245), True, 'import numpy as np\n'), ((1258, 1300), 'matplotlib.pyplot.title', 'plt.title', (['"""Frequency Domain"""'], {'fontsize': '(16)'}), "('Frequency Domain', fontsize=16)\n", (1267, 1300), True, 'import matplotlib.pyplot as plt\n'), ((1305, 1328), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'linestyle': '""":"""'}), "(linestyle=':')\n", (1313, 1328), True, 'import matplotlib.pyplot as plt\n'), ((1333, 1419), 'matplotlib.pyplot.plot', 'plt.plot', (['freqs[freqs > 0]', 'pows[freqs > 0]'], {'color': '"""orangered"""', 'label': '"""frequency"""'}), "(freqs[freqs > 0], pows[freqs > 0], color='orangered', label=\n 'frequency')\n", (1341, 1419), True, 'import matplotlib.pyplot as plt\n'), ((1420, 1432), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1430, 1432), True, 'import matplotlib.pyplot as plt\n'), ((1437, 1459), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""fft.png"""'], {}), "('fft.png')\n", (1448, 1459), True, 'import matplotlib.pyplot as plt\n'), ((1464, 1474), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1472, 1474), True, 'import matplotlib.pyplot as plt\n'), ((287, 304), 'numpy.fft.ifft', 'nf.ifft', (['comp_arr'], {}), '(comp_arr)\n', (294, 304), True, 'import numpy.fft as nf\n'), ((1040, 1057), 'numpy.fft.ifft', 'nf.ifft', (['comp_arr'], {}), '(comp_arr)\n', (1047, 1057), True, 'import numpy.fft as nf\n'), ((796, 819), 'numpy.sin', 'np.sin', (['((2 * i - 1) * x)'], {}), '((2 * i - 1) * x)\n', (802, 819), True, 'import numpy as np\n')]
from __future__ import division import numpy as np import scipy.sparse as sp import numpy.polynomial.legendre as leg from scipy.linalg import lu import scipy.interpolate as intpl from pymg.collocation_base import CollBase class CollGaussLegendre(CollBase): """ Implements Gauss-Legendre Quadrature by deriving from CollBase and implementing Gauss-Legendre nodes -> actually already part of CollBase, this is just for consistency """ def __init__(self, num_nodes, tleft, tright): super(CollGaussLegendre, self).__init__(num_nodes, tleft, tright) assert num_nodes > 1, "Number of nodes should be at least 1 for Gauss-Legendre, but is %d" % num_nodes self.order = 2 * self.num_nodes self.nodes = self._getNodes self.weights = self._getWeights(tleft, tright) self.Qmat = self._gen_Qmatrix self.Smat = self._gen_Smatrix self.QDmat = self._gen_QDmatrix self.delta_m = self._gen_deltas self.left_is_node = False self.right_is_node = False @property def _getNodes(self): """ Computes nodes for the Gauss-Legendre quadrature of order :math:`n>1` on :math:`[-1,+1]`. (ported from MATLAB code, reference see below, original commend from MATLAB code:) .. epigraph:: Unlike many publicly available functions, this function is valid for :math:`n>=46`. This is due to the fact that it does not rely on MATLAB's build-in 'root' routines to determine the roots of the Legendre polynomial, but finds the roots by looking for the eigenvalues of an alternative version of the companion matrix of the n'th degree Legendre polynomial. The companion matrix is constructed as a symmetrical matrix, guaranteeing that all the eigenvalues (roots) will be real. On the contrary, MATLAB's 'roots' function uses a general form for the companion matrix, which becomes unstable at higher orders :math:`n`, leading to complex roots. -- original MATLAB function by: <NAME> <<EMAIL>> (February 21, 2010) Python version by <NAME>, 2014 :return: Gauss-Legendre nodes """ M = self.num_nodes a = self.tleft b = self.tright # Building the companion matrix comp_mat with det(nodes*I-comp_mat)=P_n(nodes), where P_n is the # Legendre polynomial under consideration. comp_mat will be constructed in such a way that it is symmetric. linspace = np.linspace(1, M - 1, M - 1) v = linspace / np.sqrt(4.0 * linspace ** 2 - 1.0) comp_mat = np.diag(v, 1) + np.diag(v, -1) # Determining the abscissas (nodes) - since det(nodesI-comp_mat)=P_n(nodes), the abscissas are the roots # of the characteristic polynomial, i.e. the eigenvalues of comp_mat [eig_vals, _] = np.linalg.eig(comp_mat) indizes = np.argsort(eig_vals) nodes = eig_vals[indizes] # take real part and shift from [-1,1] to [a,b] nodes = nodes.real nodes = (a * (1 - nodes) + b * (1 + nodes)) / 2 return nodes class CollGaussLobatto(CollBase): """ Implements Gauss-Lobatto Quadrature by deriving from CollBase and implementing Gauss-Lobatto nodes """ def __init__(self, num_nodes, tleft, tright): super(CollGaussLobatto, self).__init__(num_nodes, tleft, tright) assert num_nodes > 1, "Number of nodes should be at least 2 for Gauss-Lobatto, but is %d" % num_nodes self.order = 2 * self.num_nodes - 2 self.nodes = self._getNodes self.weights = self._getWeights(tleft, tright) self.Qmat = self._gen_Qmatrix self.Smat = self._gen_Smatrix self.delta_m = self._gen_deltas self.left_is_node = True self.right_is_node = True self.QDmat = self._gen_QDmatrix @property def _getNodes(self): """ Copyright by <NAME>, 2014 Computes Gauss-Lobatto integration nodes. Calculates the Gauss-Lobatto integration nodes via a root calculation of derivatives of the legendre polynomials. Note that the precision of float 64 is not guarantied. """ M = self.num_nodes a = self.tleft b = self.tright roots = leg.legroots(leg.legder(np.array([0] * (M - 1) + [1], dtype=np.float64))) nodes = np.array(np.append([-1.0], np.append(roots, [1.0])), dtype=np.float64) nodes = (a * (1 - nodes) + b * (1 + nodes)) / 2 return nodes class CollGaussRadau_Right(CollBase): """ Implements Gauss-Radau Quadrature by deriving from CollBase and implementing Gauss-Radau nodes """ def __init__(self, num_nodes, tleft, tright): super(CollGaussRadau_Right, self).__init__(num_nodes, tleft, tright) assert num_nodes > 1, "Number of nodes should be at least 2 for Gauss-Radau, but is %d" % num_nodes self.order = 2 * self.num_nodes - 1 self.nodes = self._getNodes self.weights = self._getWeights(tleft, tright) self.Qmat = self._gen_Qmatrix self.Smat = self._gen_Smatrix self.delta_m = self._gen_deltas self.left_is_node = False self.right_is_node = True self.QDmat = self._gen_QDmatrix @property def _getNodes(self): """ Copyright by <NAME> (who copied this from somewhere else), 2014 Computes Gauss-Radau integration nodes with right point included. """ M = self.num_nodes a = self.tleft b = self.tright alpha = 1.0 beta = 0.0 diag = np.zeros(M - 1) subdiag = np.zeros(M - 2) diag[0] = (beta - alpha) / (2 + alpha + beta) for jj in range(1, M - 1): diag[jj] = (beta - alpha) * (alpha + beta) / (2 * jj + 2 + alpha + beta) / (2 * jj + alpha + beta) subdiag[jj - 1] = np.sqrt(4 * jj * (jj + alpha) * (jj + beta) * (jj + alpha + beta)) \ / np.sqrt( (2 * jj - 1 + alpha + beta) * (2 * jj + alpha + beta) ** 2 * (2 * jj + 1 + alpha + beta)) subdiag1 = np.zeros(M - 1) subdiag2 = np.zeros(M - 1) subdiag1[0:-1] = subdiag subdiag2[1:] = subdiag Mat = sp.spdiags(data=[subdiag1, diag, subdiag2], diags=[-1, 0, 1], m=M - 1, n=M - 1).todense() x = np.sort(np.linalg.eigvals(Mat)) nodes = np.concatenate((x, [1.0])) nodes = (a * (1 - nodes) + b * (1 + nodes)) / 2 return nodes class CollGaussRadau_Left(CollBase): """ Implements Gauss-Radau Quadrature by deriving from CollBase and implementing Gauss-Radau nodes """ def __init__(self, num_nodes, tleft, tright): super(CollGaussRadau_Left, self).__init__(num_nodes, tleft, tright) assert num_nodes > 1, "Number of nodes should be at least 2 for Gauss-Radau, but is %d" % num_nodes self.order = 2 * self.num_nodes - 1 self.nodes = self._getNodes self.weights = self._getWeights(tleft, tright) self.Qmat = self._gen_Qmatrix self.Smat = self._gen_Smatrix self.delta_m = self._gen_deltas self.left_is_node = True self.right_is_node = False self.QDmat = self._gen_QDmatrix @property def _getNodes(self): """ Copyright by <NAME> (who copied this from somewhere else), 2014 Computes Gauss-Radau integration nodes with left point included. """ M = self.num_nodes a = self.tleft b = self.tright alpha = 0.0 beta = 1.0 diag = np.zeros(M - 1) subdiag = np.zeros(M - 2) diag[0] = (beta - alpha) / (2 + alpha + beta) for jj in range(1, M - 1): diag[jj] = (beta - alpha) * (alpha + beta) / (2 * jj + 2 + alpha + beta) / (2 * jj + alpha + beta) subdiag[jj - 1] = np.sqrt(4 * jj * (jj + alpha) * (jj + beta) * (jj + alpha + beta)) \ / np.sqrt( (2 * jj - 1 + alpha + beta) * (2 * jj + alpha + beta) ** 2 * (2 * jj + 1 + alpha + beta)) subdiag1 = np.zeros(M - 1) subdiag2 = np.zeros(M - 1) subdiag1[0:-1] = subdiag subdiag2[1:] = subdiag Mat = sp.spdiags(data=[subdiag1, diag, subdiag2], diags=[-1, 0, 1], m=M - 1, n=M - 1).todense() x = np.sort(np.linalg.eigvals(Mat)) nodes = np.concatenate(([-1.0], x)) nodes = (a * (1 - nodes) + b * (1 + nodes)) / 2 print('WARNING: GaussRadau_Left untested, use at own risk!') return nodes class CollGaussRadau_Right_LU_Trick(CollGaussRadau_Right): """ Implements Gauss-Radau Quadrature by deriving from CollBase and implementing Gauss-Radau nodes and as preconditioner we implement the LU_Trick """ def __init__(self, num_nodes, tleft, tright): super(CollGaussRadau_Right_LU_Trick, self).__init__(num_nodes, tleft, tright) Q = self.Qmat p, l, u = lu(Q[1:, 1:].transpose()) # print np.diag(l) self.QDmat = u.transpose() class CollSplineRight(CollBase): """ If a spectral quadrature method is used a order higher than 15 is not applicable, because the underlying interpolation numerically losses the stability. This collocation class uses spline functions to achieve arbitrary big Q matrices with a band structure. """ def __init__(self, num_nodes, tleft, tright, order=3): super(CollSplineRight, self).__init__(num_nodes, tleft, tright) self.Q = np.zeros((num_nodes, num_nodes)) self.nodes = self._getNodes # get the defining tck's for each spline basis function circ_one = np.zeros(self.num_nodes) circ_one[0] = 1.0 self.tcks = [] for i in range(self.num_nodes): tck = intpl.splrep(self.nodes, np.roll(circ_one, i), xb=tleft, xe=tright, k=order, s=0.0) self.tcks.append(tck) self.order = order self.nodes = self._getNodes self.weights = self._getWeights(tleft, tright) self.Qmat = self._gen_Qmatrix self.Smat = self._gen_Smatrix self.delta_m = self._gen_deltas self.left_is_node = False self.right_is_node = True self.QDmat = self._gen_QDmatrix @property def _getNodes(self): return np.linspace(self.tleft + 1.0 / self.num_nodes, self.tright, self.num_nodes, endpoint=True) def _getWeights(self, a, b): weights = np.zeros(self.num_nodes) for i in range(self.num_nodes): weights[i] = intpl.splint(a, b, self.tcks[i]) return weights
[ "numpy.sqrt", "numpy.linalg.eig", "numpy.roll", "scipy.interpolate.splint", "numpy.diag", "numpy.argsort", "numpy.linalg.eigvals", "numpy.linspace", "numpy.zeros", "numpy.array", "numpy.append", "numpy.concatenate", "scipy.sparse.spdiags" ]
[((2538, 2566), 'numpy.linspace', 'np.linspace', (['(1)', '(M - 1)', '(M - 1)'], {}), '(1, M - 1, M - 1)\n', (2549, 2566), True, 'import numpy as np\n'), ((2890, 2913), 'numpy.linalg.eig', 'np.linalg.eig', (['comp_mat'], {}), '(comp_mat)\n', (2903, 2913), True, 'import numpy as np\n'), ((2932, 2952), 'numpy.argsort', 'np.argsort', (['eig_vals'], {}), '(eig_vals)\n', (2942, 2952), True, 'import numpy as np\n'), ((5651, 5666), 'numpy.zeros', 'np.zeros', (['(M - 1)'], {}), '(M - 1)\n', (5659, 5666), True, 'import numpy as np\n'), ((5685, 5700), 'numpy.zeros', 'np.zeros', (['(M - 2)'], {}), '(M - 2)\n', (5693, 5700), True, 'import numpy as np\n'), ((6169, 6184), 'numpy.zeros', 'np.zeros', (['(M - 1)'], {}), '(M - 1)\n', (6177, 6184), True, 'import numpy as np\n'), ((6204, 6219), 'numpy.zeros', 'np.zeros', (['(M - 1)'], {}), '(M - 1)\n', (6212, 6219), True, 'import numpy as np\n'), ((6451, 6477), 'numpy.concatenate', 'np.concatenate', (['(x, [1.0])'], {}), '((x, [1.0]))\n', (6465, 6477), True, 'import numpy as np\n'), ((7644, 7659), 'numpy.zeros', 'np.zeros', (['(M - 1)'], {}), '(M - 1)\n', (7652, 7659), True, 'import numpy as np\n'), ((7678, 7693), 'numpy.zeros', 'np.zeros', (['(M - 2)'], {}), '(M - 2)\n', (7686, 7693), True, 'import numpy as np\n'), ((8162, 8177), 'numpy.zeros', 'np.zeros', (['(M - 1)'], {}), '(M - 1)\n', (8170, 8177), True, 'import numpy as np\n'), ((8197, 8212), 'numpy.zeros', 'np.zeros', (['(M - 1)'], {}), '(M - 1)\n', (8205, 8212), True, 'import numpy as np\n'), ((8444, 8471), 'numpy.concatenate', 'np.concatenate', (['([-1.0], x)'], {}), '(([-1.0], x))\n', (8458, 8471), True, 'import numpy as np\n'), ((9584, 9616), 'numpy.zeros', 'np.zeros', (['(num_nodes, num_nodes)'], {}), '((num_nodes, num_nodes))\n', (9592, 9616), True, 'import numpy as np\n'), ((9737, 9761), 'numpy.zeros', 'np.zeros', (['self.num_nodes'], {}), '(self.num_nodes)\n', (9745, 9761), True, 'import numpy as np\n'), ((10385, 10479), 'numpy.linspace', 'np.linspace', (['(self.tleft + 1.0 / self.num_nodes)', 'self.tright', 'self.num_nodes'], {'endpoint': '(True)'}), '(self.tleft + 1.0 / self.num_nodes, self.tright, self.num_nodes,\n endpoint=True)\n', (10396, 10479), True, 'import numpy as np\n'), ((10528, 10552), 'numpy.zeros', 'np.zeros', (['self.num_nodes'], {}), '(self.num_nodes)\n', (10536, 10552), True, 'import numpy as np\n'), ((2590, 2624), 'numpy.sqrt', 'np.sqrt', (['(4.0 * linspace ** 2 - 1.0)'], {}), '(4.0 * linspace ** 2 - 1.0)\n', (2597, 2624), True, 'import numpy as np\n'), ((2644, 2657), 'numpy.diag', 'np.diag', (['v', '(1)'], {}), '(v, 1)\n', (2651, 2657), True, 'import numpy as np\n'), ((2660, 2674), 'numpy.diag', 'np.diag', (['v', '(-1)'], {}), '(v, -1)\n', (2667, 2674), True, 'import numpy as np\n'), ((6410, 6432), 'numpy.linalg.eigvals', 'np.linalg.eigvals', (['Mat'], {}), '(Mat)\n', (6427, 6432), True, 'import numpy as np\n'), ((8403, 8425), 'numpy.linalg.eigvals', 'np.linalg.eigvals', (['Mat'], {}), '(Mat)\n', (8420, 8425), True, 'import numpy as np\n'), ((10618, 10650), 'scipy.interpolate.splint', 'intpl.splint', (['a', 'b', 'self.tcks[i]'], {}), '(a, b, self.tcks[i])\n', (10630, 10650), True, 'import scipy.interpolate as intpl\n'), ((4345, 4392), 'numpy.array', 'np.array', (['([0] * (M - 1) + [1])'], {'dtype': 'np.float64'}), '([0] * (M - 1) + [1], dtype=np.float64)\n', (4353, 4392), True, 'import numpy as np\n'), ((4438, 4461), 'numpy.append', 'np.append', (['roots', '[1.0]'], {}), '(roots, [1.0])\n', (4447, 4461), True, 'import numpy as np\n'), ((5933, 5999), 'numpy.sqrt', 'np.sqrt', (['(4 * jj * (jj + alpha) * (jj + beta) * (jj + alpha + beta))'], {}), '(4 * jj * (jj + alpha) * (jj + beta) * (jj + alpha + beta))\n', (5940, 5999), True, 'import numpy as np\n'), ((6034, 6135), 'numpy.sqrt', 'np.sqrt', (['((2 * jj - 1 + alpha + beta) * (2 * jj + alpha + beta) ** 2 * (2 * jj + 1 +\n alpha + beta))'], {}), '((2 * jj - 1 + alpha + beta) * (2 * jj + alpha + beta) ** 2 * (2 *\n jj + 1 + alpha + beta))\n', (6041, 6135), True, 'import numpy as np\n'), ((6299, 6378), 'scipy.sparse.spdiags', 'sp.spdiags', ([], {'data': '[subdiag1, diag, subdiag2]', 'diags': '[-1, 0, 1]', 'm': '(M - 1)', 'n': '(M - 1)'}), '(data=[subdiag1, diag, subdiag2], diags=[-1, 0, 1], m=M - 1, n=M - 1)\n', (6309, 6378), True, 'import scipy.sparse as sp\n'), ((7926, 7992), 'numpy.sqrt', 'np.sqrt', (['(4 * jj * (jj + alpha) * (jj + beta) * (jj + alpha + beta))'], {}), '(4 * jj * (jj + alpha) * (jj + beta) * (jj + alpha + beta))\n', (7933, 7992), True, 'import numpy as np\n'), ((8027, 8128), 'numpy.sqrt', 'np.sqrt', (['((2 * jj - 1 + alpha + beta) * (2 * jj + alpha + beta) ** 2 * (2 * jj + 1 +\n alpha + beta))'], {}), '((2 * jj - 1 + alpha + beta) * (2 * jj + alpha + beta) ** 2 * (2 *\n jj + 1 + alpha + beta))\n', (8034, 8128), True, 'import numpy as np\n'), ((8292, 8371), 'scipy.sparse.spdiags', 'sp.spdiags', ([], {'data': '[subdiag1, diag, subdiag2]', 'diags': '[-1, 0, 1]', 'm': '(M - 1)', 'n': '(M - 1)'}), '(data=[subdiag1, diag, subdiag2], diags=[-1, 0, 1], m=M - 1, n=M - 1)\n', (8302, 8371), True, 'import scipy.sparse as sp\n'), ((9894, 9914), 'numpy.roll', 'np.roll', (['circ_one', 'i'], {}), '(circ_one, i)\n', (9901, 9914), True, 'import numpy as np\n')]
import pandas as pd from matplotlib import pyplot as plt import datetime import pickle import matplotlib.dates as mdates # Read the files dfsonde = pd.read_csv('sonde.txt', #skiprows= 10, #header = 11, #use the second row (index 1) as column headings parse_dates={'datetime': [0, 1]}, #convert text to dates/times where possible #index_col = 9 #read dates from column 9 into the index ) dfsonde = dfsonde.set_index('datetime') dfsu1 = pd.read_csv('datalogCTD_su1.txt', #skiprows= 10, #header = 11, #use the second row (index 1) as column headings parse_dates={'datetime': [0, 1]}, #convert text to dates/times where possible #index_col = 9 #read dates from column 9 into the index ) dfsu1 = dfsu1.set_index('datetime') dfsu2 = pd.read_csv('datalogCTD_su2.txt', #skiprows= 10, #header = 11, #use the second row (index 1) as column headings parse_dates={'datetime': [0, 1]}, #convert text to dates/times where possible #index_col = 9 #read dates from column 9 into the index ) dfsu2 = dfsu2.set_index('datetime') dfsu3 = pd.read_csv('datalogCTD_su3.txt', #skiprows= 10, #header = 11, #use the second row (index 1) as column headings parse_dates={'datetime': [0, 1]}, #convert text to dates/times where possible #index_col = 9 #read dates from column 9 into the index ) dfsu3 = dfsu3.set_index('datetime') dfsu5 = pd.read_csv('datalogCTD_su5_processed.txt', #skiprows= 10, #header = 11, #use the second row (index 1) as column headings parse_dates={'datetime': [0, 1]}, #convert text to dates/times where possible #index_col = 9 #read dates from column 9 into the index ) dfsu5 = dfsu5.set_index('datetime') #define cell constants from calibration data (micro S) #k_su2 = 0.7114 #k_su3 = 0.3064 #k_su4 = 0.298 #compute an average resistance and conductance dfsu1['R']=(dfsu1['r1']+dfsu1['r2'])/2 dfsu1['conductance']=0.625*(1000/dfsu1['R'])**0.889-8.69 dfsu2['R']=(dfsu2['r1']+dfsu2['r2'])/2 dfsu2['conductance']=.712*(1000/dfsu2['R'])**1.01 dfsu3['R']=(dfsu3['r1']+dfsu3['r2'])/2 dfsu3['conductance']=.335*(1000/dfsu3['R'])**.993 dfsu5['R']=(dfsu5['r1']+dfsu5['r2'])/2 dfsu5['conductance']=0.577*(1000/dfsu5['R'])**1.00 #compute depth dfsu1['depth'] = (dfsu1['pressure']*100-101300)/9810 dfsu2['depth'] = (dfsu2['pressure']*100-101300)/9810 dfsu3['depth'] = (dfsu3['pressure']*100-101300)/9810 dfsu5['depth'] = (dfsu5['pressure']*100-101300)/9810 dfsonde['depth'] = (dfsonde['Pressure psi a']*6.8947*1000)/9810 #compute depth offset and correct depths start = '2021-04-01 14:45' end = '2021-04-01 14:55' dfsu1_cor = dfsu1[(dfsu1.index>start) & (dfsu1.index<end)]['depth'].mean() dfsu2_cor = dfsu2[(dfsu2.index>start) & (dfsu2.index<end)]['depth'].mean() dfsu3_cor = dfsu3[(dfsu3.index>start) & (dfsu3.index<end)]['depth'].mean() dfsu5_cor = dfsu5[(dfsu5.index>start) & (dfsu5.index<end)]['depth'].mean() dfsonde_cor = dfsonde[(dfsonde.index>start) & (dfsonde.index<end)]['depth'].mean() dfsu1['depth']=dfsu1['depth']-dfsu1_cor dfsu2['depth']=dfsu2['depth']-dfsu2_cor dfsu3['depth']=dfsu3['depth']-dfsu3_cor dfsu5['depth']=dfsu5['depth']-dfsu5_cor dfsonde['depth']=dfsonde['depth']-dfsonde_cor dfsonde['conductance']=dfsonde['Cond uS/cm']/1000 #dfsu4['depth'] = (dfsu4['pressure']*100-101300)/9810 #correct temperatures using offset from sonde during night of April 2 dfsu1_sub = dfsu1.loc['2021-4-2 00:00':'2021-4-2 8:00'] dfsu2_sub = dfsu2.loc['2021-4-2 00:00':'2021-4-2 8:00'] dfsu3_sub = dfsu3.loc['2021-4-2 00:00':'2021-4-2 8:00'] dfsu5_sub = dfsu5.loc['2021-4-2 00:00':'2021-4-2 8:00'] dfsonde_sub = dfsonde.loc['2021-4-2 00:00':'2021-4-2 8:00'] Toffset_su1_therm = dfsonde_sub['Temp C'].mean()-dfsu1_sub['therm_T'].mean() Toffset_su2_therm = dfsonde_sub['Temp C'].mean()-dfsu2_sub['therm_T'].mean() Toffset_su3_therm = dfsonde_sub['Temp C'].mean()-dfsu3_sub['therm_T'].mean() Toffset_su1_MS = dfsonde_sub['Temp C'].mean()-dfsu1_sub['MS5803_T'].mean() Toffset_su2_MS = dfsonde_sub['Temp C'].mean()-dfsu2_sub['MS5803_T'].mean() Toffset_su3_MS = dfsonde_sub['Temp C'].mean()-dfsu3_sub['MS5803_T'].mean() Toffset_su5_MS = dfsonde_sub['Temp C'].mean()-dfsu5_sub['MS5803_T'].mean() dfsu1['therm_T corrected']=dfsu1['therm_T']+Toffset_su1_therm dfsu2['therm_T corrected']=dfsu2['therm_T']+Toffset_su2_therm dfsu3['therm_T corrected']=dfsu3['therm_T']+Toffset_su3_therm dfsu1['MS5803_T corrected']=dfsu1['MS5803_T']+Toffset_su1_MS dfsu2['MS5803_T corrected']=dfsu2['MS5803_T']+Toffset_su2_MS dfsu3['MS5803_T corrected']=dfsu3['MS5803_T']+Toffset_su3_MS dfsu5['MS5803_T corrected']=dfsu5['MS5803_T']+Toffset_su5_MS #set up the figures and subfigures (aka axes) fig, axs = plt.subplots(3, sharex = True) import numpy as np def plot_CDT_data(dfs,start1,end1,start2,end2,color_t,label_t,linewidth_t,linestyle_t,axs): for i in range(len(dfs)): df = dfs[i] mask = (((df.index > start1) & (df.index < end1)) | ((df.index >= start2) & (df.index < end2))) x_values = np.array(df.index) #Plot a line on each figure y_values_masked = np.ma.masked_where(mask, df) line = axs[i].plot(x_values,y_values_masked, color = color_t, label = label_t, linewidth = linewidth_t, linestyle = linestyle_t ) start1 = '2021-4-2 14:20' end1 = '2021-4-3 16:40' start2 = '2021-4-4 17:00' end2 = '2021-4-4 18:40' dfs = (dfsu1['therm_T corrected'], dfsu1['conductance'], dfsu1['depth']) plot_CDT_data(dfs, start1, end1, start2, end2,'b','SU1',0.3,'-',axs) dfs = (dfsu3['therm_T corrected'], dfsu3['conductance'], dfsu3['depth']) plot_CDT_data(dfs, start1, end1, start2, end2,'lime','SU3',0.3,'-',axs) dfs = (dfsu5['MS5803_T corrected'], dfsu5['conductance'], dfsu5['depth']) plot_CDT_data(dfs, start1, end1, start2, end2,'gray','SU5',0.3,'-',axs) dfs = (dfsonde['Temp C'], dfsonde['conductance'], dfsonde['depth']) plot_CDT_data(dfs, start1, end1, start2, end2,'black','EXO3',1,'--',axs) dfs = (dfsu2['therm_T corrected'], dfsu2['conductance'], dfsu2['depth']) plot_CDT_data(dfs, start1, end1, start2, end2,'r','SU2',0.3,'-',axs) handles,labels = axs[0].get_legend_handles_labels() handles = [handles[0],handles[4],handles[1],handles[2],handles[3]] #Set the axis limits axs[0].set_xlim(xmin=datetime.datetime(2021, 4, 1, hour=15, minute = 15), xmax=datetime.datetime(2021, 4, 5, hour=19)) axs[0].set_ylim(ymin = 8, ymax = 13) axs[1].set_ylim(ymin = 0, ymax = 35) axs[2].set_ylim(ymin = 0, ymax = 4) #set the figure title #fig.suptitle('May 9-10 Deployment') #show the legend handles,labels = axs[0].get_legend_handles_labels() handles = [handles[0],handles[4],handles[1],handles[2],handles[3]] labels = [labels[0],labels[4],labels[1],labels[2],labels[3]] axs[0].legend(handles,labels,fontsize = 8, ncol=len(axs[2].lines), frameon=False) #Set up the y axis labels axs[0].set_ylabel('T (°C)', fontsize = 9) axs[1].set_ylabel('EC (mS/cm)', fontsize = 9) axs[2].set_ylabel('Depth (m)',fontsize = 9) #p = pickle.dumps(fig) #format the x axis dates locator = mdates.AutoDateLocator(minticks=3, maxticks=7) formatter = mdates.ConciseDateFormatter(locator) axs[0].xaxis.set_major_locator(locator) axs[0].xaxis.set_major_formatter(formatter) axs[0].tick_params(axis='both', which = 'major', labelsize =8) axs[1].tick_params(axis='both', which = 'major', labelsize =8) axs[2].tick_params(axis='both', which = 'major', labelsize =8) #fig.align_labels() #the following is an altnernate way to format dates myFmt = mdates.DateFormatter('%d %h %H:%M') axs[0].xaxis.set_major_formatter(myFmt) #copy the old figure to a new figure using pickle #ig2 is now not a reference to fig, so changes to fig2 won't affect fig p = pickle.dumps(fig) fig2 = pickle.loads(p) fig2.show() start1 = '2021-4-1 10:20' end1 = '2021-4-1 14:50' start2 = '2021-4-3 17:00' end2 = '2021-4-4 18:40' axs2 = fig2.get_axes() dfs = (dfsu1['therm_T corrected'], dfsu1['conductance'], dfsu1['depth']) plot_CDT_data(dfs, start1, end1, start2, end2,'b','SU1',0.3,'-',axs2) dfs = (dfsu3['therm_T corrected'], dfsu3['conductance'], dfsu3['depth']) plot_CDT_data(dfs, start1, end1, start2, end2,'lime','SU3',0.3,'-',axs2) dfs = (dfsu5['MS5803_T corrected'], dfsu5['conductance'], dfsu5['depth']) plot_CDT_data(dfs, start1, end1, start2, end2,'gray','SU5',0.3,'-',axs2) dfs = (dfsonde['Temp C'], dfsonde['conductance'], dfsonde['depth']) plot_CDT_data(dfs, start1, end1, start2, end2,'black','EXO3',1,'--',axs2) dfs = (dfsu2['therm_T corrected'], dfsu2['conductance'], dfsu2['depth']) plot_CDT_data(dfs, start1, end1, start2, end2,'r','SU2',0.3,'-',axs2) #change order of labesl in legend handles,labels = axs2[0].get_legend_handles_labels() handles = [handles[0],handles[4],handles[1],handles[2],handles[3]] labels = [labels[0],labels[4],labels[1],labels[2],labels[3]] axs2[0].legend(handles,labels,fontsize = 8, ncol=len(axs[2].lines), frameon=False) #the following is an altnernate way to format dates locator = mdates.AutoDateLocator(minticks=3, maxticks=7) formatter = mdates.ConciseDateFormatter(locator) axs2[0].xaxis.set_major_locator(locator) axs2[0].xaxis.set_major_formatter(formatter) myFmt = mdates.DateFormatter('%d %h %H:%M') axs2[0].xaxis.set_major_formatter(myFmt) #ReSet the axis limits axs2[0].set_xlim(xmin=datetime.datetime(2021, 4, 2, hour=16), xmax=datetime.datetime(2021, 4, 3, hour=16)) axs2[0].set_ylim(8,16) axs2[1].set_ylim(0,30) #ax[2].set_ylim(0,3) #Reset the title #fig2.suptitle('April 2-3 Deployment') fig3, ((SU1,SU2),(SU3,SU5)) = plt.subplots(2,2) start1 = '2021-4-1 14:50' end1 = '2021-4-2 14:20' start2 = '2021-4-3 17:00' end2 = '2021-4-4 17:00' start3 = '2021-4-4 18:40' end3 = '2021-4-5 19:00' def plot_validation_data(x,y,start1,end1,start2,end2,start3,end3,axs): y_r = y.loc[((y.index > start1) & (y.index < end1)) | ((y.index > start2) & (y.index < end2)) | ((y.index > start3) & (y.index < end3))] #interpolate the values of the sonde onto the recorded data from #the other sensor. x_r = x.reindex(x.index.union(y_r.index)).interpolate(method='index').reindex(y_r.index) y_r['sonde_cond']=x_r['conductance'] y_r['error']=y_r['sonde_cond']-y['conductance'] y_r['sq_error']=y_r['error']**2 y_r['rel_error']=y_r['error']/y_r['sonde_cond'] y_r['sq_rel_error']=y_r['rel_error']**2 RMSE = (y_r['sq_error'].mean())**0.5 RMSRE = (y_r['sq_rel_error'].mean())**0.5 ME = y_r['error'].mean() MRE = y_r['rel_error'].mean() #plot points = axs.plot(y_r['sonde_cond'],y_r['conductance'], color = 'black', markeredgewidth=0.5, marker = 'o', linestyle = 'none', markersize = '1', fillstyle = 'none' ) text = "ME=%4.2f\nMRE=%4.2f\nRMSE=%4.2f\nRMSRE=%4.3f" %(ME,MRE,RMSE,RMSRE) axs.text(0.05,.9, text, fontsize=7, transform = axs.transAxes, verticalalignment='top') x = [0.05,y_r['sonde_cond'].max()*1.1] line = axs.plot(x,x, color = 'black', linestyle = '-', linewidth = 1) axs.set_xlim(xmin = 0.05, xmax = y_r['sonde_cond'].max()*1.2) axs.set_ylim(ymin = 0.05, ymax = y_r['sonde_cond'].max()*1.2) axs.set_xscale('log') axs.set_yscale('log') #fig4, ax = plt.subplots() #ax.plot(y_r.index,y_r['sonde_cond'], # color = 'black', # linestyle = '-') plot_validation_data(dfsonde,dfsu1,start1,end1,start2,end2,start3,end3,SU1) plot_validation_data(dfsonde,dfsu2,start1,end1,start2,end2,start3,end3,SU2) plot_validation_data(dfsonde,dfsu3,start1,end1,start2,end2,start3,end3,SU3) plot_validation_data(dfsonde,dfsu5,start1,end1,start2,end2,start3,end3,SU5) SU1.set_ylabel('sensor EC (mS/cm)', fontsize = 9) SU3.set_ylabel('sensor EC (mS/cm)', fontsize = 9) SU3.set_xlabel('EXO EC (mS/cm)', fontsize = 9) SU5.set_xlabel('EXO EC (mS/cm)', fontsize = 9) SU1.set_title('SU1', fontsize=9) SU2.set_title('SU2', fontsize=9) SU3.set_title('SU3', fontsize=9) SU5.set_title('SU5', fontsize=9) fig3.tight_layout()
[ "matplotlib.dates.ConciseDateFormatter", "datetime.datetime", "pandas.read_csv", "pickle.dumps", "matplotlib.dates.DateFormatter", "numpy.ma.masked_where", "numpy.array", "pickle.loads", "matplotlib.dates.AutoDateLocator", "matplotlib.pyplot.subplots" ]
[((149, 207), 'pandas.read_csv', 'pd.read_csv', (['"""sonde.txt"""'], {'parse_dates': "{'datetime': [0, 1]}"}), "('sonde.txt', parse_dates={'datetime': [0, 1]})\n", (160, 207), True, 'import pandas as pd\n'), ((558, 625), 'pandas.read_csv', 'pd.read_csv', (['"""datalogCTD_su1.txt"""'], {'parse_dates': "{'datetime': [0, 1]}"}), "('datalogCTD_su1.txt', parse_dates={'datetime': [0, 1]})\n", (569, 625), True, 'import pandas as pd\n'), ((972, 1039), 'pandas.read_csv', 'pd.read_csv', (['"""datalogCTD_su2.txt"""'], {'parse_dates': "{'datetime': [0, 1]}"}), "('datalogCTD_su2.txt', parse_dates={'datetime': [0, 1]})\n", (983, 1039), True, 'import pandas as pd\n'), ((1386, 1453), 'pandas.read_csv', 'pd.read_csv', (['"""datalogCTD_su3.txt"""'], {'parse_dates': "{'datetime': [0, 1]}"}), "('datalogCTD_su3.txt', parse_dates={'datetime': [0, 1]})\n", (1397, 1453), True, 'import pandas as pd\n'), ((1800, 1877), 'pandas.read_csv', 'pd.read_csv', (['"""datalogCTD_su5_processed.txt"""'], {'parse_dates': "{'datetime': [0, 1]}"}), "('datalogCTD_su5_processed.txt', parse_dates={'datetime': [0, 1]})\n", (1811, 1877), True, 'import pandas as pd\n'), ((5198, 5226), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)'], {'sharex': '(True)'}), '(3, sharex=True)\n', (5210, 5226), True, 'from matplotlib import pyplot as plt\n'), ((7620, 7666), 'matplotlib.dates.AutoDateLocator', 'mdates.AutoDateLocator', ([], {'minticks': '(3)', 'maxticks': '(7)'}), '(minticks=3, maxticks=7)\n', (7642, 7666), True, 'import matplotlib.dates as mdates\n'), ((7679, 7715), 'matplotlib.dates.ConciseDateFormatter', 'mdates.ConciseDateFormatter', (['locator'], {}), '(locator)\n', (7706, 7715), True, 'import matplotlib.dates as mdates\n'), ((8070, 8105), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%d %h %H:%M"""'], {}), "('%d %h %H:%M')\n", (8090, 8105), True, 'import matplotlib.dates as mdates\n'), ((8273, 8290), 'pickle.dumps', 'pickle.dumps', (['fig'], {}), '(fig)\n', (8285, 8290), False, 'import pickle\n'), ((8298, 8313), 'pickle.loads', 'pickle.loads', (['p'], {}), '(p)\n', (8310, 8313), False, 'import pickle\n'), ((9541, 9587), 'matplotlib.dates.AutoDateLocator', 'mdates.AutoDateLocator', ([], {'minticks': '(3)', 'maxticks': '(7)'}), '(minticks=3, maxticks=7)\n', (9563, 9587), True, 'import matplotlib.dates as mdates\n'), ((9600, 9636), 'matplotlib.dates.ConciseDateFormatter', 'mdates.ConciseDateFormatter', (['locator'], {}), '(locator)\n', (9627, 9636), True, 'import matplotlib.dates as mdates\n'), ((9731, 9766), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%d %h %H:%M"""'], {}), "('%d %h %H:%M')\n", (9751, 9766), True, 'import matplotlib.dates as mdates\n'), ((10095, 10113), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {}), '(2, 2)\n', (10107, 10113), True, 'from matplotlib import pyplot as plt\n'), ((5533, 5551), 'numpy.array', 'np.array', (['df.index'], {}), '(df.index)\n', (5541, 5551), True, 'import numpy as np\n'), ((5619, 5647), 'numpy.ma.masked_where', 'np.ma.masked_where', (['mask', 'df'], {}), '(mask, df)\n', (5637, 5647), True, 'import numpy as np\n'), ((6852, 6901), 'datetime.datetime', 'datetime.datetime', (['(2021)', '(4)', '(1)'], {'hour': '(15)', 'minute': '(15)'}), '(2021, 4, 1, hour=15, minute=15)\n', (6869, 6901), False, 'import datetime\n'), ((6910, 6948), 'datetime.datetime', 'datetime.datetime', (['(2021)', '(4)', '(5)'], {'hour': '(19)'}), '(2021, 4, 5, hour=19)\n', (6927, 6948), False, 'import datetime\n'), ((9855, 9893), 'datetime.datetime', 'datetime.datetime', (['(2021)', '(4)', '(2)'], {'hour': '(16)'}), '(2021, 4, 2, hour=16)\n', (9872, 9893), False, 'import datetime\n'), ((9900, 9938), 'datetime.datetime', 'datetime.datetime', (['(2021)', '(4)', '(3)'], {'hour': '(16)'}), '(2021, 4, 3, hour=16)\n', (9917, 9938), False, 'import datetime\n')]