code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import numpy as np import pandas as pd import matplotlib.pyplot as plt import heartpy as hp import wfdb from wfdb import processing from heartpy.datautils import rolling_mean, _sliding_window from heartpy.peakdetection import detect_peaks from feature_extractions import Feature_Extractor #get_features_matrix, import utils # from utils import window, transform_y, load_visualise, calculate_peaks_wfdb, bandpass, RR_intervals from heartpy.analysis import calc_rr, calc_fd_measures from scipy.signal import resample class Spider_Data_Loader: def __init__(self) -> None: pass #Loading the spider data def load_physiodata(self, instance, db = 'drivedb'): signals, fields = wfdb.rdsamp(instance, pn_dir=db) #Loading Auto Stress Data for Driver 3 from Physionet patient_data = pd.DataFrame(signals, columns=fields['sig_name'], dtype='float') #Store it into Dataframe patient_data.dropna(inplace=True) #Clean data by removing nans ecg = np.asarray(patient_data['ECG']) #Transform into numpy array gsr = np.asarray(patient_data['foot GSR']) sr = fields['fs'] #Isolate sample_rate for later processing return ecg, gsr, sr def runner(self): ppl = wfdb.io.get_record_list(db_dir = 'drivedb', records='all') #drivedb for p in ppl: try: print("LOADING DATA FOR", p) ecg, gsr, sr = self.load_physiodata(p) # print(sr) wd, m = hp.process(ecg, sample_rate = sr) peaks = wd['RR_list'] data = utils.load_visualise(ecg, peaks) extractor = Feature_Extractor(ecg, sr, [], apply_bandpass=False) #Initialize Extractor features = extractor.feature_matrix_from_whole_sample(gsr = gsr, to_csv=p) print("LOADED DATA FOR", p, "SIZE", features.shape) except(): print(p, "DIDNT WORK")
[ "heartpy.process", "utils.load_visualise", "numpy.asarray", "feature_extractions.Feature_Extractor", "wfdb.io.get_record_list", "pandas.DataFrame", "wfdb.rdsamp" ]
[((713, 745), 'wfdb.rdsamp', 'wfdb.rdsamp', (['instance'], {'pn_dir': 'db'}), '(instance, pn_dir=db)\n', (724, 745), False, 'import wfdb\n'), ((823, 887), 'pandas.DataFrame', 'pd.DataFrame', (['signals'], {'columns': "fields['sig_name']", 'dtype': '"""float"""'}), "(signals, columns=fields['sig_name'], dtype='float')\n", (835, 887), True, 'import pandas as pd\n'), ((998, 1029), 'numpy.asarray', 'np.asarray', (["patient_data['ECG']"], {}), "(patient_data['ECG'])\n", (1008, 1029), True, 'import numpy as np\n'), ((1073, 1109), 'numpy.asarray', 'np.asarray', (["patient_data['foot GSR']"], {}), "(patient_data['foot GSR'])\n", (1083, 1109), True, 'import numpy as np\n'), ((1248, 1304), 'wfdb.io.get_record_list', 'wfdb.io.get_record_list', ([], {'db_dir': '"""drivedb"""', 'records': '"""all"""'}), "(db_dir='drivedb', records='all')\n", (1271, 1304), False, 'import wfdb\n'), ((1509, 1540), 'heartpy.process', 'hp.process', (['ecg'], {'sample_rate': 'sr'}), '(ecg, sample_rate=sr)\n', (1519, 1540), True, 'import heartpy as hp\n'), ((1604, 1636), 'utils.load_visualise', 'utils.load_visualise', (['ecg', 'peaks'], {}), '(ecg, peaks)\n', (1624, 1636), False, 'import utils\n'), ((1665, 1717), 'feature_extractions.Feature_Extractor', 'Feature_Extractor', (['ecg', 'sr', '[]'], {'apply_bandpass': '(False)'}), '(ecg, sr, [], apply_bandpass=False)\n', (1682, 1717), False, 'from feature_extractions import Feature_Extractor\n')]
# Analytical solution for scattering of a plane wave by a sound-hard circle, # i.e., with the Neumann data set to zero on the circle boundary. # <NAME> # Cambridge, 20/11/19 from numba import njit, prange def sound_hard_circle(k, rad, plot_grid): # from pylab import find from scipy.special import jv, hankel1 import numpy as np x = np.vstack((plot_grid[0].ravel(), plot_grid[1].ravel())) points = x fem_xx = points[0, :] fem_xy = points[1, :] r = np.sqrt(fem_xx * fem_xx + fem_xy * fem_xy) theta = np.arctan2(fem_xy, fem_xx) npts = np.size(fem_xx, 0) a = rad n_terms = np.int(30 + (k * a)**1.01) k0 = k Nx = plot_grid.shape[1] Ny = plot_grid.shape[2] u_inc = np.exp(1j * k0 * fem_xx) n_int = np.where(r < a) u_inc[n_int] = 0.0 u_plot = u_inc.reshape(Nx, Ny) u_sc = np.zeros((npts), dtype=np.complex128) for n in range(-n_terms, n_terms): bessel_deriv = jv(n-1, k0*a) - n/(k0*a) * jv(n, k0*a) hankel_deriv = n/(k0*a)*hankel1(n, k0*a) - hankel1(n+1, k0*a) u_sc += -(1j)**(n) * (bessel_deriv/hankel_deriv) * hankel1(n, k0*r) * \ np.exp(1j*n*theta) u_sc[n_int] = 0.0 u_scat = u_sc.reshape(Nx, Ny) u_tot = u_scat + u_plot return u_tot def sound_soft_circle(k, rad, plot_grid): # from pylab import find from scipy.special import jv, hankel1 import numpy as np x = np.vstack((plot_grid[0].ravel(), plot_grid[1].ravel())) points = x fem_xx = points[0, :] fem_xy = points[1, :] r = np.sqrt(fem_xx * fem_xx + fem_xy * fem_xy) theta = np.arctan2(fem_xy, fem_xx) npts = np.size(fem_xx, 0) a = rad n_terms = np.int(30 + (k * a)**1.01) k0 = k Nx = plot_grid.shape[1] Ny = plot_grid.shape[2] u_inc = np.exp(1j * k0 * fem_xx) n_int = np.where(r < a) u_inc[n_int] = 0.0 u_plot = u_inc.reshape(Nx, Ny) u_sc = np.zeros((npts), dtype=np.complex128) for n in range(-n_terms, n_terms): u_sc += -(1j)**(n) * (jv(n, k0*a)/hankel1(n, k0*a)) * \ hankel1(n, k0*r) * np.exp(1j*n*theta) u_sc[n_int] = 0.0 u_scat = u_sc.reshape(Nx, Ny) u_tot = u_scat + u_plot return u_tot def penetrable_circle(k0, k1, rad, plot_grid): # from pylab import find from scipy.special import jv, hankel1 import numpy as np x = np.vstack((plot_grid[0].ravel(), plot_grid[1].ravel())) points = x fem_xx = points[0, :] fem_xy = points[1, :] r = np.sqrt(fem_xx * fem_xx + fem_xy * fem_xy) theta = np.arctan2(fem_xy, fem_xx) npts = np.size(fem_xx, 0) a = rad n_terms = np.max([200, np.int(55 + (k0 * a)**1.01)]) Nx = plot_grid.shape[1] Ny = plot_grid.shape[2] u_inc = np.exp(1j * k0 * fem_xx) n_int = np.where(r < a) n_ext = np.where(r >= a) u_inc[n_int] = 0.0 u_plot = u_inc.reshape(Nx, Ny) u_int = np.zeros(npts, dtype=np.complex128) u_ext = np.zeros(npts, dtype=np.complex128) for n in range(-n_terms, n_terms): bessel_k0 = jv(n, k0 * rad) bessel_k1 = jv(n, k1 * rad) hankel_k0 = hankel1(n, k0 * rad) bessel_deriv_k0 = jv(n-1, k0 * rad) - n/(k0 * rad) * jv(n, k0 * rad) bessel_deriv_k1 = jv(n-1, k1 * rad) - n/(k1 * rad) * jv(n, k1 * rad) hankel_deriv_k0 = n/(k0 * rad) * hankel_k0 - hankel1(n+1, k0 * rad) a_n = (1j**n) * (k1 * bessel_deriv_k1 * bessel_k0 - k0 * bessel_k1 * bessel_deriv_k0) / \ (k0 * hankel_deriv_k0 * bessel_k1 - k1 * bessel_deriv_k1 * hankel_k0) b_n = (a_n * hankel_k0 + (1j**n) * bessel_k0) / bessel_k1 u_ext += a_n * hankel1(n, k0 * r) * np.exp(1j * n * theta) u_int += b_n * jv(n, k1 * r) * np.exp(1j * n * theta) u_int[n_ext] = 0.0 u_ext[n_int] = 0.0 u_sc = u_int + u_ext u_scat = u_sc.reshape(Nx, Ny) u_tot = u_scat + u_plot return u_tot # FIXME: attempt at numba implementation. Not working currently. def penetrable_circle_numba(k0, k1, rad, plot_grid): # from pylab import find from scipy.special import jv, hankel1 import numpy as np x = np.vstack((plot_grid[0].ravel(), plot_grid[1].ravel())) points = x fem_xx = points[0, :] fem_xy = points[1, :] r = np.sqrt(fem_xx * fem_xx + fem_xy * fem_xy) theta = np.arctan2(fem_xy, fem_xx) npts = np.size(fem_xx, 0) a = rad n_terms = np.max([200, np.int(55 + (k0 * a)**1.01)]) Nx = plot_grid.shape[1] Ny = plot_grid.shape[2] u_inc = np.exp(1j * k0 * fem_xx) n_int = np.where(r < a) n_ext = np.where(r >= a) u_inc[n_int] = 0.0 u_plot = u_inc.reshape(Nx, Ny) # u_int = np.zeros(npts, dtype=np.complex128) # u_ext = np.zeros(npts, dtype=np.complex128) @njit(parallel=True) def summation(k0): u_int_arr = np.zeros((npts, 2*n_terms+1), dtype=np.complex128) u_ext_arr = np.zeros((npts, 2*n_terms+1), dtype=np.complex128) for n in prange(-n_terms, n_terms): bessel_k0 = jv(n, k0 * rad) bessel_k1 = jv(n, k1 * rad) hankel_k0 = hankel1(n, k0 * rad) bessel_deriv_k0 = jv(n-1, k0 * rad) - n/(k0 * rad) * jv(n, k0 * rad) bessel_deriv_k1 = jv(n-1, k1 * rad) - n/(k1 * rad) * jv(n, k1 * rad) hankel_deriv_k0 = n/(k0 * rad) * hankel_k0 - hankel1(n+1, k0 * rad) a_n = (1j**n) * (k1 * bessel_deriv_k1 * bessel_k0 - k0 * bessel_k1 * bessel_deriv_k0) / \ (k0 * hankel_deriv_k0 * bessel_k1 - k1 * bessel_deriv_k1 * hankel_k0) b_n = (a_n * hankel_k0 + (1j**n) * bessel_k0) / bessel_k1 u_ext_arr[:, n] = a_n * hankel1(n, k0 * r) * np.exp(1j * n * theta) u_int_arr[:, n] = b_n * jv(n, k1 * r) * np.exp(1j * n * theta) # u_ext += a_n * hankel1(n, k0 * r) * np.exp(1j * n * theta) # u_int += b_n * jv(n, k1 * r) * np.exp(1j * n * theta) u_ext = np.sum(u_ext_arr, axis=1) u_int = np.sum(u_int_arr, axis=1) return u_ext, u_int u_ext, u_int = summation(k0) u_int[n_ext] = 0.0 u_ext[n_int] = 0.0 u_sc = u_int + u_ext u_scat = u_sc.reshape(Nx, Ny) u_tot = u_scat + u_plot return u_tot
[ "numpy.sqrt", "scipy.special.hankel1", "numba.prange", "numpy.where", "numpy.size", "numba.njit", "numpy.exp", "numpy.sum", "numpy.zeros", "numpy.arctan2", "scipy.special.jv", "numpy.int" ]
[((481, 523), 'numpy.sqrt', 'np.sqrt', (['(fem_xx * fem_xx + fem_xy * fem_xy)'], {}), '(fem_xx * fem_xx + fem_xy * fem_xy)\n', (488, 523), True, 'import numpy as np\n'), ((536, 562), 'numpy.arctan2', 'np.arctan2', (['fem_xy', 'fem_xx'], {}), '(fem_xy, fem_xx)\n', (546, 562), True, 'import numpy as np\n'), ((574, 592), 'numpy.size', 'np.size', (['fem_xx', '(0)'], {}), '(fem_xx, 0)\n', (581, 592), True, 'import numpy as np\n'), ((620, 648), 'numpy.int', 'np.int', (['(30 + (k * a) ** 1.01)'], {}), '(30 + (k * a) ** 1.01)\n', (626, 648), True, 'import numpy as np\n'), ((728, 754), 'numpy.exp', 'np.exp', (['(1.0j * k0 * fem_xx)'], {}), '(1.0j * k0 * fem_xx)\n', (734, 754), True, 'import numpy as np\n'), ((765, 780), 'numpy.where', 'np.where', (['(r < a)'], {}), '(r < a)\n', (773, 780), True, 'import numpy as np\n'), ((851, 886), 'numpy.zeros', 'np.zeros', (['npts'], {'dtype': 'np.complex128'}), '(npts, dtype=np.complex128)\n', (859, 886), True, 'import numpy as np\n'), ((1551, 1593), 'numpy.sqrt', 'np.sqrt', (['(fem_xx * fem_xx + fem_xy * fem_xy)'], {}), '(fem_xx * fem_xx + fem_xy * fem_xy)\n', (1558, 1593), True, 'import numpy as np\n'), ((1606, 1632), 'numpy.arctan2', 'np.arctan2', (['fem_xy', 'fem_xx'], {}), '(fem_xy, fem_xx)\n', (1616, 1632), True, 'import numpy as np\n'), ((1644, 1662), 'numpy.size', 'np.size', (['fem_xx', '(0)'], {}), '(fem_xx, 0)\n', (1651, 1662), True, 'import numpy as np\n'), ((1690, 1718), 'numpy.int', 'np.int', (['(30 + (k * a) ** 1.01)'], {}), '(30 + (k * a) ** 1.01)\n', (1696, 1718), True, 'import numpy as np\n'), ((1798, 1824), 'numpy.exp', 'np.exp', (['(1.0j * k0 * fem_xx)'], {}), '(1.0j * k0 * fem_xx)\n', (1804, 1824), True, 'import numpy as np\n'), ((1835, 1850), 'numpy.where', 'np.where', (['(r < a)'], {}), '(r < a)\n', (1843, 1850), True, 'import numpy as np\n'), ((1921, 1956), 'numpy.zeros', 'np.zeros', (['npts'], {'dtype': 'np.complex128'}), '(npts, dtype=np.complex128)\n', (1929, 1956), True, 'import numpy as np\n'), ((2501, 2543), 'numpy.sqrt', 'np.sqrt', (['(fem_xx * fem_xx + fem_xy * fem_xy)'], {}), '(fem_xx * fem_xx + fem_xy * fem_xy)\n', (2508, 2543), True, 'import numpy as np\n'), ((2556, 2582), 'numpy.arctan2', 'np.arctan2', (['fem_xy', 'fem_xx'], {}), '(fem_xy, fem_xx)\n', (2566, 2582), True, 'import numpy as np\n'), ((2594, 2612), 'numpy.size', 'np.size', (['fem_xx', '(0)'], {}), '(fem_xx, 0)\n', (2601, 2612), True, 'import numpy as np\n'), ((2753, 2779), 'numpy.exp', 'np.exp', (['(1.0j * k0 * fem_xx)'], {}), '(1.0j * k0 * fem_xx)\n', (2759, 2779), True, 'import numpy as np\n'), ((2790, 2805), 'numpy.where', 'np.where', (['(r < a)'], {}), '(r < a)\n', (2798, 2805), True, 'import numpy as np\n'), ((2818, 2834), 'numpy.where', 'np.where', (['(r >= a)'], {}), '(r >= a)\n', (2826, 2834), True, 'import numpy as np\n'), ((2906, 2941), 'numpy.zeros', 'np.zeros', (['npts'], {'dtype': 'np.complex128'}), '(npts, dtype=np.complex128)\n', (2914, 2941), True, 'import numpy as np\n'), ((2954, 2989), 'numpy.zeros', 'np.zeros', (['npts'], {'dtype': 'np.complex128'}), '(npts, dtype=np.complex128)\n', (2962, 2989), True, 'import numpy as np\n'), ((4318, 4360), 'numpy.sqrt', 'np.sqrt', (['(fem_xx * fem_xx + fem_xy * fem_xy)'], {}), '(fem_xx * fem_xx + fem_xy * fem_xy)\n', (4325, 4360), True, 'import numpy as np\n'), ((4373, 4399), 'numpy.arctan2', 'np.arctan2', (['fem_xy', 'fem_xx'], {}), '(fem_xy, fem_xx)\n', (4383, 4399), True, 'import numpy as np\n'), ((4411, 4429), 'numpy.size', 'np.size', (['fem_xx', '(0)'], {}), '(fem_xx, 0)\n', (4418, 4429), True, 'import numpy as np\n'), ((4570, 4596), 'numpy.exp', 'np.exp', (['(1.0j * k0 * fem_xx)'], {}), '(1.0j * k0 * fem_xx)\n', (4576, 4596), True, 'import numpy as np\n'), ((4607, 4622), 'numpy.where', 'np.where', (['(r < a)'], {}), '(r < a)\n', (4615, 4622), True, 'import numpy as np\n'), ((4635, 4651), 'numpy.where', 'np.where', (['(r >= a)'], {}), '(r >= a)\n', (4643, 4651), True, 'import numpy as np\n'), ((4817, 4836), 'numba.njit', 'njit', ([], {'parallel': '(True)'}), '(parallel=True)\n', (4821, 4836), False, 'from numba import njit, prange\n'), ((3049, 3064), 'scipy.special.jv', 'jv', (['n', '(k0 * rad)'], {}), '(n, k0 * rad)\n', (3051, 3064), False, 'from scipy.special import jv, hankel1\n'), ((3085, 3100), 'scipy.special.jv', 'jv', (['n', '(k1 * rad)'], {}), '(n, k1 * rad)\n', (3087, 3100), False, 'from scipy.special import jv, hankel1\n'), ((3122, 3142), 'scipy.special.hankel1', 'hankel1', (['n', '(k0 * rad)'], {}), '(n, k0 * rad)\n', (3129, 3142), False, 'from scipy.special import jv, hankel1\n'), ((4880, 4934), 'numpy.zeros', 'np.zeros', (['(npts, 2 * n_terms + 1)'], {'dtype': 'np.complex128'}), '((npts, 2 * n_terms + 1), dtype=np.complex128)\n', (4888, 4934), True, 'import numpy as np\n'), ((4951, 5005), 'numpy.zeros', 'np.zeros', (['(npts, 2 * n_terms + 1)'], {'dtype': 'np.complex128'}), '((npts, 2 * n_terms + 1), dtype=np.complex128)\n', (4959, 5005), True, 'import numpy as np\n'), ((5019, 5044), 'numba.prange', 'prange', (['(-n_terms)', 'n_terms'], {}), '(-n_terms, n_terms)\n', (5025, 5044), False, 'from numba import njit, prange\n'), ((6058, 6083), 'numpy.sum', 'np.sum', (['u_ext_arr'], {'axis': '(1)'}), '(u_ext_arr, axis=1)\n', (6064, 6083), True, 'import numpy as np\n'), ((6100, 6125), 'numpy.sum', 'np.sum', (['u_int_arr'], {'axis': '(1)'}), '(u_int_arr, axis=1)\n', (6106, 6125), True, 'import numpy as np\n'), ((951, 968), 'scipy.special.jv', 'jv', (['(n - 1)', '(k0 * a)'], {}), '(n - 1, k0 * a)\n', (953, 968), False, 'from scipy.special import jv, hankel1\n'), ((1041, 1063), 'scipy.special.hankel1', 'hankel1', (['(n + 1)', '(k0 * a)'], {}), '(n + 1, k0 * a)\n', (1048, 1063), False, 'from scipy.special import jv, hankel1\n'), ((1152, 1176), 'numpy.exp', 'np.exp', (['(1.0j * n * theta)'], {}), '(1.0j * n * theta)\n', (1158, 1176), True, 'import numpy as np\n'), ((2097, 2121), 'numpy.exp', 'np.exp', (['(1.0j * n * theta)'], {}), '(1.0j * n * theta)\n', (2103, 2121), True, 'import numpy as np\n'), ((2653, 2682), 'numpy.int', 'np.int', (['(55 + (k0 * a) ** 1.01)'], {}), '(55 + (k0 * a) ** 1.01)\n', (2659, 2682), True, 'import numpy as np\n'), ((3170, 3189), 'scipy.special.jv', 'jv', (['(n - 1)', '(k0 * rad)'], {}), '(n - 1, k0 * rad)\n', (3172, 3189), False, 'from scipy.special import jv, hankel1\n'), ((3247, 3266), 'scipy.special.jv', 'jv', (['(n - 1)', '(k1 * rad)'], {}), '(n - 1, k1 * rad)\n', (3249, 3266), False, 'from scipy.special import jv, hankel1\n'), ((3352, 3376), 'scipy.special.hankel1', 'hankel1', (['(n + 1)', '(k0 * rad)'], {}), '(n + 1, k0 * rad)\n', (3359, 3376), False, 'from scipy.special import jv, hankel1\n'), ((3729, 3753), 'numpy.exp', 'np.exp', (['(1.0j * n * theta)'], {}), '(1.0j * n * theta)\n', (3735, 3753), True, 'import numpy as np\n'), ((3791, 3815), 'numpy.exp', 'np.exp', (['(1.0j * n * theta)'], {}), '(1.0j * n * theta)\n', (3797, 3815), True, 'import numpy as np\n'), ((4470, 4499), 'numpy.int', 'np.int', (['(55 + (k0 * a) ** 1.01)'], {}), '(55 + (k0 * a) ** 1.01)\n', (4476, 4499), True, 'import numpy as np\n'), ((5070, 5085), 'scipy.special.jv', 'jv', (['n', '(k0 * rad)'], {}), '(n, k0 * rad)\n', (5072, 5085), False, 'from scipy.special import jv, hankel1\n'), ((5110, 5125), 'scipy.special.jv', 'jv', (['n', '(k1 * rad)'], {}), '(n, k1 * rad)\n', (5112, 5125), False, 'from scipy.special import jv, hankel1\n'), ((5151, 5171), 'scipy.special.hankel1', 'hankel1', (['n', '(k0 * rad)'], {}), '(n, k0 * rad)\n', (5158, 5171), False, 'from scipy.special import jv, hankel1\n'), ((978, 991), 'scipy.special.jv', 'jv', (['n', '(k0 * a)'], {}), '(n, k0 * a)\n', (980, 991), False, 'from scipy.special import jv, hankel1\n'), ((1022, 1040), 'scipy.special.hankel1', 'hankel1', (['n', '(k0 * a)'], {}), '(n, k0 * a)\n', (1029, 1040), False, 'from scipy.special import jv, hankel1\n'), ((1119, 1137), 'scipy.special.hankel1', 'hankel1', (['n', '(k0 * r)'], {}), '(n, k0 * r)\n', (1126, 1137), False, 'from scipy.special import jv, hankel1\n'), ((2078, 2096), 'scipy.special.hankel1', 'hankel1', (['n', '(k0 * r)'], {}), '(n, k0 * r)\n', (2085, 2096), False, 'from scipy.special import jv, hankel1\n'), ((3205, 3220), 'scipy.special.jv', 'jv', (['n', '(k0 * rad)'], {}), '(n, k0 * rad)\n', (3207, 3220), False, 'from scipy.special import jv, hankel1\n'), ((3282, 3297), 'scipy.special.jv', 'jv', (['n', '(k1 * rad)'], {}), '(n, k1 * rad)\n', (3284, 3297), False, 'from scipy.special import jv, hankel1\n'), ((3708, 3726), 'scipy.special.hankel1', 'hankel1', (['n', '(k0 * r)'], {}), '(n, k0 * r)\n', (3715, 3726), False, 'from scipy.special import jv, hankel1\n'), ((3775, 3788), 'scipy.special.jv', 'jv', (['n', '(k1 * r)'], {}), '(n, k1 * r)\n', (3777, 3788), False, 'from scipy.special import jv, hankel1\n'), ((5203, 5222), 'scipy.special.jv', 'jv', (['(n - 1)', '(k0 * rad)'], {}), '(n - 1, k0 * rad)\n', (5205, 5222), False, 'from scipy.special import jv, hankel1\n'), ((5284, 5303), 'scipy.special.jv', 'jv', (['(n - 1)', '(k1 * rad)'], {}), '(n - 1, k1 * rad)\n', (5286, 5303), False, 'from scipy.special import jv, hankel1\n'), ((5393, 5417), 'scipy.special.hankel1', 'hankel1', (['(n + 1)', '(k0 * rad)'], {}), '(n + 1, k0 * rad)\n', (5400, 5417), False, 'from scipy.special import jv, hankel1\n'), ((5801, 5825), 'numpy.exp', 'np.exp', (['(1.0j * n * theta)'], {}), '(1.0j * n * theta)\n', (5807, 5825), True, 'import numpy as np\n'), ((5876, 5900), 'numpy.exp', 'np.exp', (['(1.0j * n * theta)'], {}), '(1.0j * n * theta)\n', (5882, 5900), True, 'import numpy as np\n'), ((5238, 5253), 'scipy.special.jv', 'jv', (['n', '(k0 * rad)'], {}), '(n, k0 * rad)\n', (5240, 5253), False, 'from scipy.special import jv, hankel1\n'), ((5319, 5334), 'scipy.special.jv', 'jv', (['n', '(k1 * rad)'], {}), '(n, k1 * rad)\n', (5321, 5334), False, 'from scipy.special import jv, hankel1\n'), ((5780, 5798), 'scipy.special.hankel1', 'hankel1', (['n', '(k0 * r)'], {}), '(n, k0 * r)\n', (5787, 5798), False, 'from scipy.special import jv, hankel1\n'), ((5860, 5873), 'scipy.special.jv', 'jv', (['n', '(k1 * r)'], {}), '(n, k1 * r)\n', (5862, 5873), False, 'from scipy.special import jv, hankel1\n'), ((2028, 2041), 'scipy.special.jv', 'jv', (['n', '(k0 * a)'], {}), '(n, k0 * a)\n', (2030, 2041), False, 'from scipy.special import jv, hankel1\n'), ((2040, 2058), 'scipy.special.hankel1', 'hankel1', (['n', '(k0 * a)'], {}), '(n, k0 * a)\n', (2047, 2058), False, 'from scipy.special import jv, hankel1\n')]
import numpy as np import tensorflow.keras.layers as layers from invoke.context import Context from tensorflow.keras.models import Sequential import config as cfg from ennclave import Enclave import ennclave_inference def build_library(model: Enclave, mode: str): model.generate_state() model.generate_forward(mode, ) context = Context() with context.cd(cfg.get_ennclave_home()): if mode == 'sgx': model.generate_config() context.run('build/backend_sgx_encryptor') with context.cd("build"): # TODO: make more robust context.run(f"make backend_{mode}") def common_test_basis(model: Sequential, use_sgx: bool): # TODO: seed with current date (for consistent results within a day) rng = np.random.default_rng() input_shape = model.input_shape[1:] inputs = rng.normal(loc=0., scale=2., size=( input_shape)).astype(np.float32) inputs = np.expand_dims(inputs, 0) size = np.prod(inputs.shape) expected_result = model(inputs).numpy().flatten() output_size = np.prod(expected_result.shape) ennclave_model = Enclave(model.layers) build_library(ennclave_model, "sgx" if use_sgx else "native") if use_sgx: test_bytes = ennclave_inference.sgx_forward( inputs.tobytes(), size, output_size) else: test_bytes = ennclave_inference.native_forward( inputs.tobytes(), size, output_size) test_result = np.frombuffer(test_bytes, dtype=np.float32) np.testing.assert_almost_equal(test_result, expected_result, decimal=5) if __name__ == '__main__': test_shape = (1, 5) test_input = np.arange(test_shape[1]).reshape((1,) + test_shape) test_model = Sequential(layers.Dense(5, input_shape=test_shape)) test_model(test_input) common_test_basis(test_model, False) print("Generated code returns the same result :)")
[ "numpy.prod", "numpy.random.default_rng", "config.get_ennclave_home", "numpy.testing.assert_almost_equal", "invoke.context.Context", "tensorflow.keras.layers.Dense", "numpy.expand_dims", "numpy.frombuffer", "ennclave.Enclave", "numpy.arange" ]
[((343, 352), 'invoke.context.Context', 'Context', ([], {}), '()\n', (350, 352), False, 'from invoke.context import Context\n'), ((767, 790), 'numpy.random.default_rng', 'np.random.default_rng', ([], {}), '()\n', (788, 790), True, 'import numpy as np\n'), ((935, 960), 'numpy.expand_dims', 'np.expand_dims', (['inputs', '(0)'], {}), '(inputs, 0)\n', (949, 960), True, 'import numpy as np\n'), ((972, 993), 'numpy.prod', 'np.prod', (['inputs.shape'], {}), '(inputs.shape)\n', (979, 993), True, 'import numpy as np\n'), ((1067, 1097), 'numpy.prod', 'np.prod', (['expected_result.shape'], {}), '(expected_result.shape)\n', (1074, 1097), True, 'import numpy as np\n'), ((1120, 1141), 'ennclave.Enclave', 'Enclave', (['model.layers'], {}), '(model.layers)\n', (1127, 1141), False, 'from ennclave import Enclave\n'), ((1461, 1504), 'numpy.frombuffer', 'np.frombuffer', (['test_bytes'], {'dtype': 'np.float32'}), '(test_bytes, dtype=np.float32)\n', (1474, 1504), True, 'import numpy as np\n'), ((1509, 1580), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['test_result', 'expected_result'], {'decimal': '(5)'}), '(test_result, expected_result, decimal=5)\n', (1539, 1580), True, 'import numpy as np\n'), ((1732, 1771), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['(5)'], {'input_shape': 'test_shape'}), '(5, input_shape=test_shape)\n', (1744, 1771), True, 'import tensorflow.keras.layers as layers\n'), ((373, 396), 'config.get_ennclave_home', 'cfg.get_ennclave_home', ([], {}), '()\n', (394, 396), True, 'import config as cfg\n'), ((1652, 1676), 'numpy.arange', 'np.arange', (['test_shape[1]'], {}), '(test_shape[1])\n', (1661, 1676), True, 'import numpy as np\n')]
################################## Define Some Useful Functions ############################### import numpy as np import torch as t from decimal import * import scipy # import sympy import math # from pynverse import inversefunc # import cvxpy as cp def indicator(K): # This function is used to generate indicators to obtain a specific variable ''' @K: number of users ''' return t.eye(5*K) def gamma(p, H, W, sigmma): # This function is used to compute SINR of all users with a batchsize for downlink scenerio ''' @p: downlink power vector of all users, its dimmension is (batchsize, K) @H: channel coefficients of a batchsize, its dimmension is (batchsize, K, Nt) @W: beamforming vector matrix of a batchsize, its dimmension is (batchsize, Nt, K), where Nt is the antenna number of BS @sigmma: Gaussian noise, suppose the values of all users are the same. Its dimmension is (1,1) ''' H_bar = H / sigmma HW_tmp = t.abs(t.bmm(H_bar, W)) # (batchsize, K, K) # print("solution1",t.pow(t.abs(H_bar.conj()[0,0,:]@W[0,:,0]),2)) # print("solution2:",t.pow(t.abs((H_bar[0,0].conj()@W[0,:,0])),2)) # print("solution3",HW_tmp[0,0,0]) # print("HW_tmp:",HW_tmp[0,0,0]**2) HW_abs_2 = t.pow(HW_tmp, 2) # (batchsize, K, K) HW_abs_tmp = t.zeros(len(H), len(H[0])) # (batchsize, K) for i in range(len(HW_tmp)): HW_abs_tmp[i] = t.diag(HW_abs_2[i]) gamma_top = p * HW_abs_tmp # (batchsize, K) gamma_botom = t.sum(p.unsqueeze(-2) * HW_abs_2, -1) - gamma_top + 1 # (batchsize, K) gamma_output = gamma_top / gamma_botom # (batchsize, K) return gamma_output def leftrow_gamma(q, H, W, sigmma): # This function is used to compute SINR of all users with a batchsize for uplink scenerio ''' @q: uplink power vector of all users, its dimmension is (batchsize, K) @H: channel coefficients of a batchsize, its dimmension is (batchsize, Nt, K) @W: beamforming vector matrix of a batchsize, its dimmension is (batchsize, Nt, K), where Nt is the antenna number of BS @sigmma: Gaussian noise, suppose the values of all users are the same. Its dimmension is (1,1) ''' H_bar = H / sigmma HW_tmp = t.zeros(len(H_bar), len(H_bar[0][0]), len(H_bar[0][0])) # (batchsize, K, K) for i in range(len(HW_tmp)): HW_tmp[i] = t.abs(t.mm(H_bar[i].T, W[i])) HW_abs_pow = t.pow(HW_tmp, 2) HW_abs_tmp = t.zeros(len(H), len(H[0][0])) # (batchsize, K) for i in range(len(HW_tmp)): HW_abs_tmp[i] = t.diag(HW_abs_pow[i]) gamma_top = q * HW_abs_tmp # (batchsize, K) gamma_botom = t.sum(q.unsqueeze(-1) * HW_abs_pow, -1) - gamma_top + 1 # (batchsize, K) gamma_output = gamma_top / gamma_botom # (batchsize, K) return gamma_output def B_func(n, z): # subfunction of W_func # n determins B_func takes the sum of the first n-1 items, ‘z’ is the variable of B_func tmp1 = 0 for k in range(n): tmp1 = tmp1 + ( math.factorial(n-1+k) / ( math.factorial(k) * \ math.factorial(n-1-k))) * ((z/2)**k) return tmp1 def W_func(t1, t2, a, n): # where t1 = 2\vartheta, t2 = -2\vartheta, a = -4*β^2*\vartheta^2, n denotes W_func takes # the sum of the first n items tmp = 0 for k in range(1, n+1): tmp = tmp + (1.0 / (k * math.factorial(k))) * ((a * k * np.exp(-t1)) \ / (t2-t1))**k * B_func(k, -2.0/(k*(t2-t1))) return t1 - tmp def k_star(beta, vartheta): # this function is used to obtain the solution of equation e^k * (k-2u)(k+2u) = -4beta^2u^2 t1 = 2 * vartheta t2 = -2 * vartheta a = -4 * beta * beta * vartheta * vartheta k_star_output = W_func(t1, t2, a, 10) return k_star_output def nu2(beta, vartheta): # this function is used to obatin the solution of R(\gamma) = 0 sol_k = k_star(beta, vartheta) sol_output = t.exp(sol_k/2) - 1 return sol_output def nu3(D, n, vartheta): # this function is used to obtain the solution of R(\gamma) = D/n * ln(2) ''' @D: the number of transmitting data bits @n: finite blocklength @vartheta: vartheta = Q^{-1}(spsilon) / sqrt(n) ''' alpha = D/n * np.log(2) beta = np.exp(-alpha) sol_k = k_star(beta, vartheta) sol_output = np.exp(alpha + sol_k/2) - 1 return sol_output def R(gamma, vartheta): # this function is used to obtain the achievable rate ''' @gamma: the achivable sum rate, i.e., SINR. Its dimmension is (batchsize, K) ''' one = t.ones_like(gamma) output = t.log(1+gamma) - vartheta * t.sqrt(1 - 1 / ((1+gamma) * (1+gamma))) return output def tilde_gamma(P, H, sigmma): # this function is used to obtain tilde_gamma ''' @P: the maximum power constraint, its dimmension is (1) @H: channel coefficient, its dimmension is (batchsize, Nt, K) @sigmma: gaussian noise, suppose all users' sigmma is the same, its dimmesion is (1) ''' HW_tmp = t.abs(H) * t.abs(H) # (batchsize, Nt, K) HW = t.sum(HW_tmp, 1) # (batchsize, K) output = P * HW / sigmma # (batchsize, K) return output def bar_psi(x_k, x_k_1): # this function is used to compute bar_psi(psi_k) ''' @x_k: output of the k-th layer, its dimmension is (batchsize, 2*K*K+3K) @x_k_1: output of the (k-1)-th layer, its dimmension is (batchsize, 2*K*K+3K) ''' output = (1 - 2*x_k_1 + x_k) / ((1 - x_k_1) * (1 - x_k_1)) # (batchsize, 2*K*K+3K) return output def mu_psi(x_k, x_k_1): # this function is used to compute mu(psi_k) ''' @x_k: output of the k-th layer, its dimmension is (batchsize, 2*K*K+3K) @x_k_1: output of the (k-1)-th layer, its dimmension is (batchsize, 2*K*K+3K) ''' output = t.sqrt(x_k_1) / 2 + x_k / (2 * t.sqrt(x_k_1)) # (batchsize, 2*K*K+3K) return output def gradient_g(K, x_k, x_k_1, mu_k): # this function is used to compute the gradient of function g at x_k ''' @K: number of users @x_k: the output of the k-th layer, (batchsize, 2*K*K+3*K) @x_k_1: the output of the (k-1)-th layer, (batchsize, 2*K*K+3*K) @mu_k: the barrier parameter outputted by the k-th layer ''' Delta = indicator(K) # indicator matrix, (K, K) # output = t.zeros_like(x_k) for i in range(K): m_i = 1 / ((1 - t.sum(Delta[2*K+i] * x_k_1, -1)) * (1 - t.sum(Delta[2*K+i] * x_k_1, -1))) # (batchsize) tmp_top = t.mm(m_i.unsqueeze(-1), Delta[2*K+i].unsqueeze(0)) - t.mm(2 * (1 + \ t.sum(Delta[3*K+i] * x_k, -1)).unsqueeze(-1), Delta[2*K+i].unsqueeze(0)) # (batchsize, 2*K*K+3*K) tmp_down = 2 * m_i - m_i * m_i + m_i * t.sum(Delta[2*K+i] * x_k, -1) - (1 + \ t.sum(Delta[3*K+i] * x_k, -1)) * (1 + t.sum(Delta[3*K+i] * x_k, -1)) # (batch, ) if i == 0: output = tmp_top / tmp_down.unsqueeze(-1) # (batchsize, 2*K*K+3*K) else: output = output + tmp_top / tmp_down.unsqueeze(-1) # (batchsize, 2*K*K+3*K) output = -mu_k * output return output def prox_h1(x_k_t, alpha, Delta, lambda_k_t): # this function is used to compute the proximity operator of function h1 at x_k_t ''' @x_k_t: output of the t-th sub-iteration of the k-th layer, (batchsize, M, 2*K*K+3*K) @alpha: prior weight of users, (2*K*K+3*K) @Delta: the i-th indicator vector, (2*K*K+3*K, 2*K*K+3*K) @lambda_k_t: stepsize of the t-th sub-iteration of the k-th layer, (batchsize, ) ''' # prox_x = t.zeros_like(x_k_t) with t.no_grad(): prox_x = x_k_t for i in range(len(x_k_t)): for j in range(len(x_k_t[0])): coe = (1 + t.sum(x_k_t[i, j] * Delta[j], -1)) + t.sqrt( t.pow(1+t.sum(x_k_t[i, j] \ * Delta[j], -1), 2) + 4*lambda_k_t[i]*alpha[j]) coe = coe / 2 # t.norm(Delta) is 1 prox_x[i, j] = x_k_t[i, j] + coe * Delta[j] # (batchsize, 2*K*K+3*K, 2*K*K+3*K) return prox_x def prox_h2(x_k_t, vartheta, alpha, Delta, lambda_k_t): # this function is used to compute the proximity operator of function h2 at x_k_t ''' @x_k_t: output of the t-th sub-iteration of the k-th layer, (batchsize, M, 2*K*K+3*K) @vartheta: constant parameter @alpha: prior weight of users, (2*K*K+3*K, ) @Delta: the i-th indicator vector, (2*K*K+3*K, 2*K*K+3*K) @lambda_k_t: stepsize of the t-th sub-iteration of the k-th layer, (batchsize,) ''' # prox_x = t.zeros_like(x_k_t) # (batchsize, 2*K*K+3*K, 2*K*K+3*K) with t.no_grad(): prox_x = x_k_t for i in range(len(x_k_t)): for j in range(len(x_k_t[0])): prox_x[i, j] = x_k_t[i, j] - lambda_k_t[i] * vartheta * alpha[j] * Delta[j] return prox_x def prox_h3(x_k_t, A, b, lambda_k_t, mu_k): # this function is used to compute the proximity operator of function h3 at x_k_t ''' @x_k_t: output of the t-th sub-iteration of the k-th layer, (batchsize, M, 2*K*K+3*K), where M is the number of affine constraints @A: left coefficient of a affine constraint, (batchsize, M, 2*K*K+3*K) @b: right coefficient of a affine constraint, (batchsize, M) @lambda_k_t: stepsize of the t-th sub-iteration of the k-th layer, (batchsize, ) @mu_k: barrier parameter of the k-th layer ''' tmp = b - t.sum(A * x_k_t, -1) # (batchsize, M) row_norm_A = t.sum(A * A, -1) # (batchsize, M) coe = tmp + t.sqrt(tmp * tmp + 4 * lambda_k_t * mu_k * row_norm_A) # (batchsize, M) coe = coe / (2 * row_norm_A) # (batchsize, M) prox_x = x_k_t + coe.unsqueeze(-1) * A # (batchsize, M, 2*K*K+3*K) return prox_x def prox_h4(x_k_t): # this function is used to compute the proximity operator of the function h4 at x_k_t ''' @x_k_t: output of the t-th sub-ieration of the k-th layer, (batchsize, M, 2*K*K+3*K) ''' return x_k_t def generate_layout(d0, Cell_radius, K): # this function is used to generate Cell network topology ''' @d0: Reference distance d0 @Cell_radius: Cell radius @K: number of users ''' BS_x = Cell_radius; BS_y = Cell_radius # coordinate of BS user_xs = np.zeros((K+1, 1)); user_ys = np.zeros((K+1, 1)) # coordinate of all users distance = [] # distance between BS and users user_xs[0] = BS_x; user_ys[0] = BS_y for i in range(K): pair_distance = np.random.uniform(low = d0, high = Cell_radius) pair_angles = np.random.uniform(low = 0, high = np.pi * 2) user_x = BS_x + pair_distance * np.cos(pair_angles) user_y = BS_y + pair_distance * np.sin(pair_angles) user_xs[i+1] = user_x user_ys[i+1] = user_y distance.append(pair_distance) layout = np.concatenate((user_xs, user_ys), axis = 1) return layout, distance def generate_h(num_h, K, Nt, d0, Cell_radius): # this function is used to generate CSI ''' @num_h: number of samples @K: number of users @Nt: number of transimite antennas @d0: Reference distance d0 @Cell_radius: Cell radius ''' dst = np.zeros((num_h, K)) layout = np.zeros((num_h, K+1, 2)) for loop in range(num_h): layout_sample, dst_sample = generate_layout(d0, Cell_radius, K) layout[loop] = layout_sample dst[loop] = dst_sample # H = np.zeros((num_h, K, Nt)) # (num_h, K, Nt) tilde_H = (np.random.randn(num_h, K, Nt) + 1j * np.random.randn(num_h, K, Nt)) / np.sqrt(2) rho = 1 / (1 + np.power(dst / d0, 3)) H = np.sqrt(rho).reshape(len(rho), len(rho[0]), 1) * tilde_H # note that the dtype of H is 'complex128', which should be transformed to 'complex64' return H.astype('complex64'), dst, layout def PHI(H, W0, p0, sigmma): # this function is used to generate matrix Phi, which is used to implement initialization operations ''' @H: CSI, (batchsize, K, Nt) @W0: beamforming vector, (batchsize, Nt, K) @p0: initial power, (batchsize, K) @sigmma: gaussian noise ''' bar_gamma = gamma(p0, H, W0, sigmma) # (batchsize, K) # H = H.conj() # obtain the conjugate of H HW = t.abs(t.bmm(H, W0)) # (batchsize, K, K) HW_2 = t.pow(HW, 2) eyes = t.empty_like(HW) # used to remove non-diag items of HW for i in range(len(HW)): eyes[i] = t.eye(len(HW[0]), len(HW[0])) HW_negative = -HW_2 HW_diag = HW_2 * eyes / bar_gamma.unsqueeze(-2) HW_negative = HW_negative * (1 - eyes) Phi = HW_negative + HW_diag # (batchsize, K, K) return Phi def tilde_q(Phi): # this function is used to compute tilde_q ''' @Phi: matrix Phi, which is used to generate tilde_q, (batchsize, K, K) ''' inv_Phi = np.linalg.pinv(Phi.numpy()) # inv_Phi = t.inverse(Phi) # obtain the inverse of Phi tilde_q_output = t.sum(t.from_numpy(inv_Phi), -1) # (batchsize, K) return tilde_q_output def tilde_V(phi): # this function is used to compute tilde_V(phi) ''' @phi: variable phi, (batchsize, K) ''' phi_tmp = (1 + phi) * (1 + phi) output = 1 - 1 / phi_tmp return output def W_star(H, q, sigmma): # this function is used to compute w_star ''' @H: CSI, (batchsize, K, Nt) @q: power of all users, (batchsize, K) @sigmma: gaussian noise ''' bar_H = H / sigmma # (batchsize, K, Nt) # bar_H_conj = bar_H.conj() # (batchsize, K, Nt) bar_H_conj = bar_H bar_H_usq = bar_H.unsqueeze(-1) # (batchsize, K, Nt, 1) bar_H_conj = bar_H_conj.unsqueeze(-2) # (batchsize, K, 1, Nt) HH = t.matmul(bar_H_usq, bar_H_conj) # (batchsize, K, Nt, Nt) HH_q = HH * q.unsqueeze(-1).unsqueeze(-1) # (batchsize, K, Nt, Nt) HH_sum = t.sum(HH, dim = -3) # (batchsize, Nt, Nt) for i in range(len(HH_sum[0,0])): HH_sum[:, i, i] = HH_sum[:, i, i] + 1 coe_matrix = HH_sum # (batchsize, Nt, Nt) coe_matrix_inv = t.inverse(coe_matrix) # obtain the inverse of coe_matrix bar_H_T = bar_H.permute(0, 2, 1) # (batchsize, Nt, K) W_star_top = t.bmm(coe_matrix_inv, bar_H_T) # (batchsize, Nt, K) W_star_down = t.sqrt(t.sum(t.abs(W_star_top) * t.abs(W_star_top), 1)).unsqueeze(-2) # (batchsize, 1, K) W_star_output = W_star_top / W_star_down # (batchsize, Nt, K) return W_star_output ## test the feasible of functions if __name__ == "__main__": H = t.randn(3, 4) + 1j * t.randn(3, 4) W0 = t.randn(2, 4, 3) + 1j * t.randn(2, 4, 3) W = t.randn(2, 4, 3) + 1j * t.randn(2, 4, 3) p0 = t.randn(2, 3) sigmma = 1 p = t.randn(2, 3) D = 256 n = 128 vartheta = 0.377 x = t.abs(t.randn(2, 27)) K = 3 P = 40 nu3_val = nu3(D, n, vartheta) print(nu3_val)
[ "numpy.sqrt", "numpy.log", "torch.sqrt", "torch.pow", "torch.exp", "torch.from_numpy", "torch.sum", "torch.bmm", "numpy.sin", "torch.eye", "numpy.exp", "torch.matmul", "numpy.concatenate", "torch.randn", "torch.ones_like", "torch.abs", "math.factorial", "torch.empty_like", "numpy...
[((435, 447), 'torch.eye', 't.eye', (['(5 * K)'], {}), '(5 * K)\n', (440, 447), True, 'import torch as t\n'), ((1425, 1441), 'torch.pow', 't.pow', (['HW_tmp', '(2)'], {}), '(HW_tmp, 2)\n', (1430, 1441), True, 'import torch as t\n'), ((2910, 2926), 'torch.pow', 't.pow', (['HW_tmp', '(2)'], {}), '(HW_tmp, 2)\n', (2915, 2926), True, 'import torch as t\n'), ((4951, 4965), 'numpy.exp', 'np.exp', (['(-alpha)'], {}), '(-alpha)\n', (4957, 4965), True, 'import numpy as np\n'), ((5278, 5296), 'torch.ones_like', 't.ones_like', (['gamma'], {}), '(gamma)\n', (5289, 5296), True, 'import torch as t\n'), ((5872, 5888), 'torch.sum', 't.sum', (['HW_tmp', '(1)'], {}), '(HW_tmp, 1)\n', (5877, 5888), True, 'import torch as t\n'), ((10968, 10984), 'torch.sum', 't.sum', (['(A * A)', '(-1)'], {}), '(A * A, -1)\n', (10973, 10984), True, 'import torch as t\n'), ((12052, 12072), 'numpy.zeros', 'np.zeros', (['(K + 1, 1)'], {}), '((K + 1, 1))\n', (12060, 12072), True, 'import numpy as np\n'), ((12082, 12102), 'numpy.zeros', 'np.zeros', (['(K + 1, 1)'], {}), '((K + 1, 1))\n', (12090, 12102), True, 'import numpy as np\n'), ((12726, 12768), 'numpy.concatenate', 'np.concatenate', (['(user_xs, user_ys)'], {'axis': '(1)'}), '((user_xs, user_ys), axis=1)\n', (12740, 12768), True, 'import numpy as np\n'), ((13172, 13192), 'numpy.zeros', 'np.zeros', (['(num_h, K)'], {}), '((num_h, K))\n', (13180, 13192), True, 'import numpy as np\n'), ((13207, 13234), 'numpy.zeros', 'np.zeros', (['(num_h, K + 1, 2)'], {}), '((num_h, K + 1, 2))\n', (13215, 13234), True, 'import numpy as np\n'), ((14524, 14536), 'torch.pow', 't.pow', (['HW', '(2)'], {}), '(HW, 2)\n', (14529, 14536), True, 'import torch as t\n'), ((14549, 14565), 'torch.empty_like', 't.empty_like', (['HW'], {}), '(HW)\n', (14561, 14565), True, 'import torch as t\n'), ((16431, 16462), 'torch.matmul', 't.matmul', (['bar_H_usq', 'bar_H_conj'], {}), '(bar_H_usq, bar_H_conj)\n', (16439, 16462), True, 'import torch as t\n'), ((16673, 16690), 'torch.sum', 't.sum', (['HH'], {'dim': '(-3)'}), '(HH, dim=-3)\n', (16678, 16690), True, 'import torch as t\n'), ((16999, 17020), 'torch.inverse', 't.inverse', (['coe_matrix'], {}), '(coe_matrix)\n', (17008, 17020), True, 'import torch as t\n'), ((17239, 17269), 'torch.bmm', 't.bmm', (['coe_matrix_inv', 'bar_H_T'], {}), '(coe_matrix_inv, bar_H_T)\n', (17244, 17269), True, 'import torch as t\n'), ((17820, 17833), 'torch.randn', 't.randn', (['(2)', '(3)'], {}), '(2, 3)\n', (17827, 17833), True, 'import torch as t\n'), ((17859, 17872), 'torch.randn', 't.randn', (['(2)', '(3)'], {}), '(2, 3)\n', (17866, 17872), True, 'import torch as t\n'), ((1106, 1121), 'torch.bmm', 't.bmm', (['H_bar', 'W'], {}), '(H_bar, W)\n', (1111, 1121), True, 'import torch as t\n'), ((1687, 1706), 'torch.diag', 't.diag', (['HW_abs_2[i]'], {}), '(HW_abs_2[i])\n', (1693, 1706), True, 'import torch as t\n'), ((3094, 3115), 'torch.diag', 't.diag', (['HW_abs_pow[i]'], {}), '(HW_abs_pow[i])\n', (3100, 3115), True, 'import torch as t\n'), ((4583, 4599), 'torch.exp', 't.exp', (['(sol_k / 2)'], {}), '(sol_k / 2)\n', (4588, 4599), True, 'import torch as t\n'), ((4929, 4938), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (4935, 4938), True, 'import numpy as np\n'), ((5020, 5045), 'numpy.exp', 'np.exp', (['(alpha + sol_k / 2)'], {}), '(alpha + sol_k / 2)\n', (5026, 5045), True, 'import numpy as np\n'), ((5311, 5327), 'torch.log', 't.log', (['(1 + gamma)'], {}), '(1 + gamma)\n', (5316, 5327), True, 'import torch as t\n'), ((5766, 5774), 'torch.abs', 't.abs', (['H'], {}), '(H)\n', (5771, 5774), True, 'import torch as t\n'), ((5777, 5785), 'torch.abs', 't.abs', (['H'], {}), '(H)\n', (5782, 5785), True, 'import torch as t\n'), ((8826, 8837), 'torch.no_grad', 't.no_grad', ([], {}), '()\n', (8835, 8837), True, 'import torch as t\n'), ((9987, 9998), 'torch.no_grad', 't.no_grad', ([], {}), '()\n', (9996, 9998), True, 'import torch as t\n'), ((10859, 10879), 'torch.sum', 't.sum', (['(A * x_k_t)', '(-1)'], {}), '(A * x_k_t, -1)\n', (10864, 10879), True, 'import torch as t\n'), ((11073, 11127), 'torch.sqrt', 't.sqrt', (['(tmp * tmp + 4 * lambda_k_t * mu_k * row_norm_A)'], {}), '(tmp * tmp + 4 * lambda_k_t * mu_k * row_norm_A)\n', (11079, 11127), True, 'import torch as t\n'), ((12366, 12409), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': 'd0', 'high': 'Cell_radius'}), '(low=d0, high=Cell_radius)\n', (12383, 12409), True, 'import numpy as np\n'), ((12437, 12477), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0)', 'high': '(np.pi * 2)'}), '(low=0, high=np.pi * 2)\n', (12454, 12477), True, 'import numpy as np\n'), ((13598, 13608), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (13605, 13608), True, 'import numpy as np\n'), ((14433, 14445), 'torch.bmm', 't.bmm', (['H', 'W0'], {}), '(H, W0)\n', (14438, 14445), True, 'import torch as t\n'), ((15328, 15349), 'torch.from_numpy', 't.from_numpy', (['inv_Phi'], {}), '(inv_Phi)\n', (15340, 15349), True, 'import torch as t\n'), ((17674, 17687), 'torch.randn', 't.randn', (['(3)', '(4)'], {}), '(3, 4)\n', (17681, 17687), True, 'import torch as t\n'), ((17719, 17735), 'torch.randn', 't.randn', (['(2)', '(4)', '(3)'], {}), '(2, 4, 3)\n', (17726, 17735), True, 'import torch as t\n'), ((17769, 17785), 'torch.randn', 't.randn', (['(2)', '(4)', '(3)'], {}), '(2, 4, 3)\n', (17776, 17785), True, 'import torch as t\n'), ((17936, 17950), 'torch.randn', 't.randn', (['(2)', '(27)'], {}), '(2, 27)\n', (17943, 17950), True, 'import torch as t\n'), ((2862, 2884), 'torch.mm', 't.mm', (['H_bar[i].T', 'W[i]'], {}), '(H_bar[i].T, W[i])\n', (2866, 2884), True, 'import torch as t\n'), ((5339, 5382), 'torch.sqrt', 't.sqrt', (['(1 - 1 / ((1 + gamma) * (1 + gamma)))'], {}), '(1 - 1 / ((1 + gamma) * (1 + gamma)))\n', (5345, 5382), True, 'import torch as t\n'), ((6795, 6808), 'torch.sqrt', 't.sqrt', (['x_k_1'], {}), '(x_k_1)\n', (6801, 6808), True, 'import torch as t\n'), ((13527, 13556), 'numpy.random.randn', 'np.random.randn', (['num_h', 'K', 'Nt'], {}), '(num_h, K, Nt)\n', (13542, 13556), True, 'import numpy as np\n'), ((13629, 13650), 'numpy.power', 'np.power', (['(dst / d0)', '(3)'], {}), '(dst / d0, 3)\n', (13637, 13650), True, 'import numpy as np\n'), ((17695, 17708), 'torch.randn', 't.randn', (['(3)', '(4)'], {}), '(3, 4)\n', (17702, 17708), True, 'import torch as t\n'), ((17743, 17759), 'torch.randn', 't.randn', (['(2)', '(4)', '(3)'], {}), '(2, 4, 3)\n', (17750, 17759), True, 'import torch as t\n'), ((17793, 17809), 'torch.randn', 't.randn', (['(2)', '(4)', '(3)'], {}), '(2, 4, 3)\n', (17800, 17809), True, 'import torch as t\n'), ((6826, 6839), 'torch.sqrt', 't.sqrt', (['x_k_1'], {}), '(x_k_1)\n', (6832, 6839), True, 'import torch as t\n'), ((12523, 12542), 'numpy.cos', 'np.cos', (['pair_angles'], {}), '(pair_angles)\n', (12529, 12542), True, 'import numpy as np\n'), ((12584, 12603), 'numpy.sin', 'np.sin', (['pair_angles'], {}), '(pair_angles)\n', (12590, 12603), True, 'import numpy as np\n'), ((13565, 13594), 'numpy.random.randn', 'np.random.randn', (['num_h', 'K', 'Nt'], {}), '(num_h, K, Nt)\n', (13580, 13594), True, 'import numpy as np\n'), ((13661, 13673), 'numpy.sqrt', 'np.sqrt', (['rho'], {}), '(rho)\n', (13668, 13673), True, 'import numpy as np\n'), ((3670, 3695), 'math.factorial', 'math.factorial', (['(n - 1 + k)'], {}), '(n - 1 + k)\n', (3684, 3695), False, 'import math\n'), ((7455, 7490), 'torch.sum', 't.sum', (['(Delta[2 * K + i] * x_k_1)', '(-1)'], {}), '(Delta[2 * K + i] * x_k_1, -1)\n', (7460, 7490), True, 'import torch as t\n'), ((7495, 7530), 'torch.sum', 't.sum', (['(Delta[2 * K + i] * x_k_1)', '(-1)'], {}), '(Delta[2 * K + i] * x_k_1, -1)\n', (7500, 7530), True, 'import torch as t\n'), ((7813, 7846), 'torch.sum', 't.sum', (['(Delta[2 * K + i] * x_k)', '(-1)'], {}), '(Delta[2 * K + i] * x_k, -1)\n', (7818, 7846), True, 'import torch as t\n'), ((7874, 7907), 'torch.sum', 't.sum', (['(Delta[3 * K + i] * x_k)', '(-1)'], {}), '(Delta[3 * K + i] * x_k, -1)\n', (7879, 7907), True, 'import torch as t\n'), ((7912, 7945), 'torch.sum', 't.sum', (['(Delta[3 * K + i] * x_k)', '(-1)'], {}), '(Delta[3 * K + i] * x_k, -1)\n', (7917, 7945), True, 'import torch as t\n'), ((8962, 8995), 'torch.sum', 't.sum', (['(x_k_t[i, j] * Delta[j])', '(-1)'], {}), '(x_k_t[i, j] * Delta[j], -1)\n', (8967, 8995), True, 'import torch as t\n'), ((3696, 3713), 'math.factorial', 'math.factorial', (['k'], {}), '(k)\n', (3710, 3713), False, 'import math\n'), ((3734, 3759), 'math.factorial', 'math.factorial', (['(n - 1 - k)'], {}), '(n - 1 - k)\n', (3748, 3759), False, 'import math\n'), ((17368, 17385), 'torch.abs', 't.abs', (['W_star_top'], {}), '(W_star_top)\n', (17373, 17385), True, 'import torch as t\n'), ((17388, 17405), 'torch.abs', 't.abs', (['W_star_top'], {}), '(W_star_top)\n', (17393, 17405), True, 'import torch as t\n'), ((4011, 4028), 'math.factorial', 'math.factorial', (['k'], {}), '(k)\n', (4025, 4028), False, 'import math\n'), ((4043, 4054), 'numpy.exp', 'np.exp', (['(-t1)'], {}), '(-t1)\n', (4049, 4054), True, 'import numpy as np\n'), ((7660, 7693), 'torch.sum', 't.sum', (['(Delta[3 * K + i] * x_k)', '(-1)'], {}), '(Delta[3 * K + i] * x_k, -1)\n', (7665, 7693), True, 'import torch as t\n'), ((9015, 9048), 'torch.sum', 't.sum', (['(x_k_t[i, j] * Delta[j])', '(-1)'], {}), '(x_k_t[i, j] * Delta[j], -1)\n', (9020, 9048), True, 'import torch as t\n')]
import numpy as np import copy from util.util import * from heuristics.greedy_tsp import greedy as greedy_tsp from graph.graph import Graph from util.prim import * # prefer concorde try: from concorde.tsp import TSPSolver CONCORDE_AVAILABLE = True #CONCORDE_AVAILABLE = False except ImportError: CONCORDE_AVAILABLE = False if CONCORDE_AVAILABLE == False: try: from python_tsp.heuristics import solve_tsp_simulated_annealing as solve_tsp_lib SOLVER_AVAILABLE = False except ImportError: SOLVER_AVAILABLE = False def generate_random_tour(nvert, rng_seed=None, kind="Euclidean"): # set up tour gen = np.random.default_rng(seed=rng_seed) graph = Graph.fully_connected([f"v{i}" for i in range(nvert)]) if kind == "Euclidean": # randomly place vertices in the unit square positions = {v: gen.uniform(size=2) for v in graph.vertices} graph.place_vertices(positions) elif kind == "Unit": graph.weights = {e: gen.uniform(low=0, high=1) for e in graph.edges} # symmetrize #for u, v in graph.edges: # graph.weights[frozenset((u, v))] = graph.weights[frozenset((v, u))] # randomly generate initial tour tour = copy.deepcopy(graph.vertices) tour = list(map(frozenset, zip(tour, tour[1:] + [tour[0]]))) return graph, tour def generate_ktree(nvert, k, rng_seed=None, kind="Euclidean"): gen = np.random.RandomState(seed=rng_seed) assert k <= nvert + 1 base_vertices = [f"v{i}" for i in range(k+1)] # identify the subset of vertices to which all added # vertices will be neighbors subset = base_vertices[:k-2] graph = Graph.fully_connected(copy.deepcopy(base_vertices)) for i in range(k+1, nvert): # add new vertex graph.vertices.append(f"v{i}") # add edges to create a k-tree # for each new vertex v, connect it to exactly k-2 vertices S # from the base graph in such a way that S and {v} together # form a clique. # connect each new vertex to exactly k-2 of the base vertices graph.edges += [frozenset({f"v{i}", v}) for v in subset] # finally, connect all added vertices in a cycle added_vs = [f"v{i}" for i in range(k+1, nvert)] cycle = copy.deepcopy(added_vs) graph.edges += [frozenset({u, v}) for u, v in zip(cycle, cycle[1:])] + [frozenset({cycle[-1], cycle[0]})] # a hamiltonian cycle is given by the outer cycle excepting one edge, plus an edge to v0, plus a hamiltonian # path through the original graph ending at any vertex of the neighbor subset tour = cycle start = subset[0] end = subset[1] tour.append(start) remaining = subset[2:] tour += remaining tour += base_vertices[k-2:] tour.append(end) tour = [frozenset({u, v}) for u, v in zip(tour, tour[1:])] + [frozenset({tour[-1], tour[0]})] if kind == "Unit": for edge in graph.edges: graph.set_weight(gen.uniform(low=0, high=1), edge) elif kind == "Euclidean": positions = {v: gen.uniform(size=2) for v in graph.vertices} graph.place_vertices(positions) else: raise ValueError("Weight distribution not supported") return graph, tour def solve_tsp(graph, tour, optimizer, it_max=1000): #tour, weights, it_max=1000): for i in range(it_max): new_tour = optimizer(tour, graph.weights) if path_length(tour, graph.weights) <= path_length(new_tour, graph.weights): break else: tour = new_tour return new_tour, i + 1 def solve_ensemble(optimizer, num_tours, nvert, seeds=None, greedy=False, compute_lb=True, kind="Euclidean", tour_generator=generate_random_tour): if not seeds: seeds = [None]*num_tours len_original = np.zeros(num_tours) len_optimal = np.zeros(num_tours) dts = np.zeros(num_tours) lower_bounds = np.zeros(num_tours) for i in range(num_tours): graph, tour = tour_generator(nvert, rng_seed=seeds[i], kind=kind) if compute_lb: if CONCORDE_AVAILABLE: lb = path_length(tsp_concorde(graph), graph.weights) elif SOLVER_AVAILABLE: lb = path_length(tsp_solver(graph), graph.weights) else: lb = tsp_lower_bound(graph) else: lb = np.inf if greedy: tour = greedy_tsp(graph.vertices, graph.weights) len_original[i] = path_length(tour, graph.weights) optimal_tour, dt = solve_tsp(graph, tour, optimizer) len_optimal[i] = path_length(optimal_tour, graph.weights) lower_bounds[i] = lb dts[i] = dt return len_original, len_optimal, dts, lower_bounds def average_case_time(num_tours, nverts, optimizer, greedy=False, kind="Euclidean", tour_generator=generate_random_tour): dts = np.zeros(nverts.shape) for i, nv in enumerate(nverts): seeds = list(range(i*num_tours, (i+1)*num_tours)) len_orig, len_optimal, dt, lower_bounds \ = solve_ensemble(optimizer, num_tours, nv, seeds=seeds, greedy=greedy, compute_lb=False, kind=kind, tour_generator=tour_generator) dts[i] = np.mean(dt) return dts def average_case_ratio(num_tours, nverts, optimizer, greedy=False, kind="Euclidean"): ratios = np.zeros(nverts.shape) for i, nv in enumerate(nverts): seeds = list(range(i*num_tours, (i+1)*num_tours)) len_orig, len_optimal, dt, lbs = solve_ensemble(optimizer, num_tours, nv, seeds=seeds, greedy=greedy, kind=kind) ratios[i] = np.mean(len_optimal / lbs) return ratios def tsp_concorde(graph): # solve with concorde pos = np.array(list(graph.positions.values())) xs = pos[:, 0] ys = pos[:, 1] solver = TSPSolver.from_data(xs, ys, norm="GEO") sol = solver.solve(verbose=False) optimal_tour = [graph.vertices[i] for i in sol.tour] return list(map(frozenset, list(zip(optimal_tour, optimal_tour[1:])) + [(optimal_tour[-1], optimal_tour[0])])) def tsp_solver(graph): distance_matrix = np.zeros((len(graph.vertices), len(graph.vertices))) for i, u in enumerate(graph.vertices): for j, v in enumerate(graph.vertices): if i == j: distance_matrix[i, i] == 0 else: distance_matrix[i, j] = graph.weights[frozenset({u, v})] perm, distance = solve_tsp_lib(distance_matrix) tour = [graph.vertices[i] for i in perm] tour = [frozenset({u, v}) for u, v in zip(tour, tour[1:])] + [frozenset({tour[-1], tour[0]})] return tour
[ "numpy.mean", "python_tsp.heuristics.solve_tsp_simulated_annealing", "numpy.random.default_rng", "concorde.tsp.TSPSolver.from_data", "heuristics.greedy_tsp.greedy", "numpy.zeros", "copy.deepcopy", "numpy.random.RandomState" ]
[((661, 697), 'numpy.random.default_rng', 'np.random.default_rng', ([], {'seed': 'rng_seed'}), '(seed=rng_seed)\n', (682, 697), True, 'import numpy as np\n'), ((1253, 1282), 'copy.deepcopy', 'copy.deepcopy', (['graph.vertices'], {}), '(graph.vertices)\n', (1266, 1282), False, 'import copy\n'), ((1447, 1483), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': 'rng_seed'}), '(seed=rng_seed)\n', (1468, 1483), True, 'import numpy as np\n'), ((2309, 2332), 'copy.deepcopy', 'copy.deepcopy', (['added_vs'], {}), '(added_vs)\n', (2322, 2332), False, 'import copy\n'), ((3843, 3862), 'numpy.zeros', 'np.zeros', (['num_tours'], {}), '(num_tours)\n', (3851, 3862), True, 'import numpy as np\n'), ((3881, 3900), 'numpy.zeros', 'np.zeros', (['num_tours'], {}), '(num_tours)\n', (3889, 3900), True, 'import numpy as np\n'), ((3911, 3930), 'numpy.zeros', 'np.zeros', (['num_tours'], {}), '(num_tours)\n', (3919, 3930), True, 'import numpy as np\n'), ((3950, 3969), 'numpy.zeros', 'np.zeros', (['num_tours'], {}), '(num_tours)\n', (3958, 3969), True, 'import numpy as np\n'), ((4924, 4946), 'numpy.zeros', 'np.zeros', (['nverts.shape'], {}), '(nverts.shape)\n', (4932, 4946), True, 'import numpy as np\n'), ((5381, 5403), 'numpy.zeros', 'np.zeros', (['nverts.shape'], {}), '(nverts.shape)\n', (5389, 5403), True, 'import numpy as np\n'), ((5842, 5881), 'concorde.tsp.TSPSolver.from_data', 'TSPSolver.from_data', (['xs', 'ys'], {'norm': '"""GEO"""'}), "(xs, ys, norm='GEO')\n", (5861, 5881), False, 'from concorde.tsp import TSPSolver\n'), ((6466, 6496), 'python_tsp.heuristics.solve_tsp_simulated_annealing', 'solve_tsp_lib', (['distance_matrix'], {}), '(distance_matrix)\n', (6479, 6496), True, 'from python_tsp.heuristics import solve_tsp_simulated_annealing as solve_tsp_lib\n'), ((1720, 1748), 'copy.deepcopy', 'copy.deepcopy', (['base_vertices'], {}), '(base_vertices)\n', (1733, 1748), False, 'import copy\n'), ((5252, 5263), 'numpy.mean', 'np.mean', (['dt'], {}), '(dt)\n', (5259, 5263), True, 'import numpy as np\n'), ((5640, 5666), 'numpy.mean', 'np.mean', (['(len_optimal / lbs)'], {}), '(len_optimal / lbs)\n', (5647, 5666), True, 'import numpy as np\n'), ((4453, 4494), 'heuristics.greedy_tsp.greedy', 'greedy_tsp', (['graph.vertices', 'graph.weights'], {}), '(graph.vertices, graph.weights)\n', (4463, 4494), True, 'from heuristics.greedy_tsp import greedy as greedy_tsp\n')]
import numpy as np import plac import os @plac.annotations( idsfile=("file with the ids", "positional"), linenumsfile=("file containing linenums", "positional"), nlines=("the size of the sample", "option", None, int) ) def main (idsfile, linenumsfile, nlines=100000): np.random.seed (100) with open (idsfile) as fin: ids = [line.strip() for line in fin] nids = len (ids) linenums = np.random.choice (nids, nlines, replace=False) with open (linenumsfile, "w") as fout: for linenum in linenums: fout.write ("{0}\n".format (linenum)) if __name__ == "__main__": plac.call(main)
[ "numpy.random.choice", "numpy.random.seed", "plac.annotations", "plac.call" ]
[((43, 227), 'plac.annotations', 'plac.annotations', ([], {'idsfile': "('file with the ids', 'positional')", 'linenumsfile': "('file containing linenums', 'positional')", 'nlines': "('the size of the sample', 'option', None, int)"}), "(idsfile=('file with the ids', 'positional'), linenumsfile=\n ('file containing linenums', 'positional'), nlines=(\n 'the size of the sample', 'option', None, int))\n", (59, 227), False, 'import plac\n'), ((273, 292), 'numpy.random.seed', 'np.random.seed', (['(100)'], {}), '(100)\n', (287, 292), True, 'import numpy as np\n'), ((393, 438), 'numpy.random.choice', 'np.random.choice', (['nids', 'nlines'], {'replace': '(False)'}), '(nids, nlines, replace=False)\n', (409, 438), True, 'import numpy as np\n'), ((578, 593), 'plac.call', 'plac.call', (['main'], {}), '(main)\n', (587, 593), False, 'import plac\n')]
""" Tests for the data augmentation methods in gprof_nn.augmentation. """ from pathlib import Path import numpy as np import xarray as xr from gprof_nn import sensors from gprof_nn.data import get_test_data_path from gprof_nn.augmentation import ( Swath, get_center_pixels, get_transformation_coordinates, get_center_pixel_input, M, N ) from gprof_nn.data.training_data import decompress_and_load DATA_PATH = get_test_data_path() def test_gmi_geometry(): """ Assert that coordinate transformation function for GMI viewing geometry are reversible. """ i = np.arange(0, 221, 10) j = np.arange(0, 221, 10) ij = np.stack(np.meshgrid(i, j)) geometry = sensors.GMI.viewing_geometry xy = geometry.pixel_coordinates_to_euclidean(ij) ij_r = geometry.euclidean_to_pixel_coordinates(xy) assert np.all(np.isclose(ij, ij_r)) def test_mhs_geometry(): """ Assert that coordinate transformation function for GMI viewing geometry are reversible. """ i = np.arange(0, 90, 10) j = np.arange(0, 90, 10) ij = np.stack(np.meshgrid(i, j)) geometry = sensors.MHS.viewing_geometry xy = geometry.pixel_coordinates_to_euclidean(ij) ij_r = geometry.euclidean_to_pixel_coordinates(xy) assert np.all(np.isclose(ij, ij_r)) def test_swath_geometry(): """ Assert that coordinate transformation function for GMI viewing geometry are reversible. """ input_file = DATA_PATH / "mhs" / "gprof_nn_mhs_era5.nc.gz" input_data = decompress_and_load(input_file) lats = input_data.latitude.data[0] lons = input_data.longitude.data[0] i = np.arange(0, 221, 10) j = np.arange(0, 221, 10) ij = np.stack(np.meshgrid(i, j)) swath = Swath(lats, lons) xy = swath.pixel_coordinates_to_euclidean(ij) ij_r = swath.euclidean_to_pixel_coordinates(xy) assert np.all(np.isclose(ij, ij_r)) def test_interpolation_weights(): """ Ensure that all interpolation weights are positive and sum to 1. """ geometry = sensors.MHS.viewing_geometry weights = geometry.get_interpolation_weights(sensors.MHS.angles) assert np.all(weights.sum(-1) == 1.0) assert np.all(weights >= 0) def test_inputer_center(): """ Ensures that the calculated window always contains the center of the GMI swath. """ l = get_center_pixel_input(0.0, 64) assert l + 32 == 110 r = get_center_pixel_input(1.0, 64) assert r - 32 == 110 def test_transformation_coordinates(): """ Ensure that transformation coordinates correspond to identity mapping for when input and output window are located at the center of the swath. """ input_file = DATA_PATH / "mhs" / "gprof_nn_mhs_era5.nc.gz" input_data = decompress_and_load(input_file) lats = input_data.latitude.data[0] lons = input_data.longitude.data[0] geometry = sensors.GMI.viewing_geometry c = get_transformation_coordinates( lats, lons, geometry, 64, 64, 0.5, 0.5, 0.5 ) assert np.all(np.isclose(c[1, 0, :], np.arange(110 - 32, 110 + 32), atol=2.0))
[ "numpy.isclose", "gprof_nn.augmentation.get_transformation_coordinates", "gprof_nn.augmentation.get_center_pixel_input", "gprof_nn.augmentation.Swath", "gprof_nn.data.training_data.decompress_and_load", "gprof_nn.data.get_test_data_path", "numpy.meshgrid", "numpy.all", "numpy.arange" ]
[((437, 457), 'gprof_nn.data.get_test_data_path', 'get_test_data_path', ([], {}), '()\n', (455, 457), False, 'from gprof_nn.data import get_test_data_path\n'), ((605, 626), 'numpy.arange', 'np.arange', (['(0)', '(221)', '(10)'], {}), '(0, 221, 10)\n', (614, 626), True, 'import numpy as np\n'), ((635, 656), 'numpy.arange', 'np.arange', (['(0)', '(221)', '(10)'], {}), '(0, 221, 10)\n', (644, 656), True, 'import numpy as np\n'), ((1033, 1053), 'numpy.arange', 'np.arange', (['(0)', '(90)', '(10)'], {}), '(0, 90, 10)\n', (1042, 1053), True, 'import numpy as np\n'), ((1062, 1082), 'numpy.arange', 'np.arange', (['(0)', '(90)', '(10)'], {}), '(0, 90, 10)\n', (1071, 1082), True, 'import numpy as np\n'), ((1533, 1564), 'gprof_nn.data.training_data.decompress_and_load', 'decompress_and_load', (['input_file'], {}), '(input_file)\n', (1552, 1564), False, 'from gprof_nn.data.training_data import decompress_and_load\n'), ((1654, 1675), 'numpy.arange', 'np.arange', (['(0)', '(221)', '(10)'], {}), '(0, 221, 10)\n', (1663, 1675), True, 'import numpy as np\n'), ((1684, 1705), 'numpy.arange', 'np.arange', (['(0)', '(221)', '(10)'], {}), '(0, 221, 10)\n', (1693, 1705), True, 'import numpy as np\n'), ((1756, 1773), 'gprof_nn.augmentation.Swath', 'Swath', (['lats', 'lons'], {}), '(lats, lons)\n', (1761, 1773), False, 'from gprof_nn.augmentation import Swath, get_center_pixels, get_transformation_coordinates, get_center_pixel_input, M, N\n'), ((2205, 2225), 'numpy.all', 'np.all', (['(weights >= 0)'], {}), '(weights >= 0)\n', (2211, 2225), True, 'import numpy as np\n'), ((2367, 2398), 'gprof_nn.augmentation.get_center_pixel_input', 'get_center_pixel_input', (['(0.0)', '(64)'], {}), '(0.0, 64)\n', (2389, 2398), False, 'from gprof_nn.augmentation import Swath, get_center_pixels, get_transformation_coordinates, get_center_pixel_input, M, N\n'), ((2432, 2463), 'gprof_nn.augmentation.get_center_pixel_input', 'get_center_pixel_input', (['(1.0)', '(64)'], {}), '(1.0, 64)\n', (2454, 2463), False, 'from gprof_nn.augmentation import Swath, get_center_pixels, get_transformation_coordinates, get_center_pixel_input, M, N\n'), ((2781, 2812), 'gprof_nn.data.training_data.decompress_and_load', 'decompress_and_load', (['input_file'], {}), '(input_file)\n', (2800, 2812), False, 'from gprof_nn.data.training_data import decompress_and_load\n'), ((2945, 3020), 'gprof_nn.augmentation.get_transformation_coordinates', 'get_transformation_coordinates', (['lats', 'lons', 'geometry', '(64)', '(64)', '(0.5)', '(0.5)', '(0.5)'], {}), '(lats, lons, geometry, 64, 64, 0.5, 0.5, 0.5)\n', (2975, 3020), False, 'from gprof_nn.augmentation import Swath, get_center_pixels, get_transformation_coordinates, get_center_pixel_input, M, N\n'), ((675, 692), 'numpy.meshgrid', 'np.meshgrid', (['i', 'j'], {}), '(i, j)\n', (686, 692), True, 'import numpy as np\n'), ((864, 884), 'numpy.isclose', 'np.isclose', (['ij', 'ij_r'], {}), '(ij, ij_r)\n', (874, 884), True, 'import numpy as np\n'), ((1101, 1118), 'numpy.meshgrid', 'np.meshgrid', (['i', 'j'], {}), '(i, j)\n', (1112, 1118), True, 'import numpy as np\n'), ((1290, 1310), 'numpy.isclose', 'np.isclose', (['ij', 'ij_r'], {}), '(ij, ij_r)\n', (1300, 1310), True, 'import numpy as np\n'), ((1724, 1741), 'numpy.meshgrid', 'np.meshgrid', (['i', 'j'], {}), '(i, j)\n', (1735, 1741), True, 'import numpy as np\n'), ((1895, 1915), 'numpy.isclose', 'np.isclose', (['ij', 'ij_r'], {}), '(ij, ij_r)\n', (1905, 1915), True, 'import numpy as np\n'), ((3084, 3113), 'numpy.arange', 'np.arange', (['(110 - 32)', '(110 + 32)'], {}), '(110 - 32, 110 + 32)\n', (3093, 3113), True, 'import numpy as np\n')]
import numpy as np def prepareData(train, dev, embeddings): ''' Almacenamiento de palabras en nuestro vocabulario -> Añadimos al vocabulario aquellas palabras que estén en el subconjunto de los embeddings seleccionados (200000) + 2 de padding y unkown ''' vocabulary = {} vocabulary["PADDING"] = len(vocabulary) vocabulary["UNKOWN"] = len(vocabulary) #Matriz de embeddings del vocabulario embeddings_matrix = [] embeddings_matrix.append(np.zeros(300)) embeddings_matrix.append(np.random.uniform(-0.25, 0.25, 300)) for word in embeddings.wv.vocab: vocabulary[word] = len(vocabulary) #Al mismo tiempo creamos matrix de embeddings embeddings_matrix.append(embeddings[word]) train_idx = [] dev_idx = [] for sentence in train: wordIndices = [] for word in sentence: #Si la palabra está en el vocabulario, asignamos su índice en él if word in vocabulary: wordIndices.append(vocabulary[word]) else: #Padding if word == "-": wordIndices.append(vocabulary["PADDING"]) #Desconocida else: wordIndices.append(vocabulary["UNKOWN"]) train_idx.append(np.array(wordIndices)) for sentence in dev: wordIndices = [] for word in sentence: #Si tenemos embedding para la palabra if word in vocabulary: wordIndices.append(vocabulary[word]) else: #Padding if word == "-": wordIndices.append(vocabulary["PADDING"]) #Desconocida else: wordIndices.append(vocabulary["UNKOWN"]) dev_idx.append(np.array(wordIndices)) return (train_idx, dev_idx, embeddings_matrix, vocabulary) def prepareDataTest(data_test, vocabulary): ''' Preparación de conjunto de test. ''' data_test_idx = [] for sentence in data_test: wordIndices = [] for word in sentence: #Si tenemos embedding para la palabra if word in vocabulary: wordIndices.append(vocabulary[word]) else: #Padding if word == "-": wordIndices.append(vocabulary["PADDING"]) #Desconocida else: wordIndices.append(vocabulary["UNKOWN"]) data_test_idx.append(np.array(wordIndices)) return np.array(data_test_idx) def writeOutput(y_pred, id_, fichero): ''' Generación de fichero de salida ''' y_pred_tag = ["UNSAFE" if pred==0 else "SAFE" for pred in np.argmax(y_pred,axis=1)] output_data = zip(id_, y_pred_tag) with(open(fichero, 'w')) as f_test_out: s_buff = "\n".join(["\t".join(list(label_pair)) for label_pair in output_data]) f_test_out.write(s_buff)
[ "numpy.array", "numpy.zeros", "numpy.argmax", "numpy.random.uniform" ]
[((2084, 2107), 'numpy.array', 'np.array', (['data_test_idx'], {}), '(data_test_idx)\n', (2092, 2107), True, 'import numpy as np\n'), ((453, 466), 'numpy.zeros', 'np.zeros', (['(300)'], {}), '(300)\n', (461, 466), True, 'import numpy as np\n'), ((494, 529), 'numpy.random.uniform', 'np.random.uniform', (['(-0.25)', '(0.25)', '(300)'], {}), '(-0.25, 0.25, 300)\n', (511, 529), True, 'import numpy as np\n'), ((1113, 1134), 'numpy.array', 'np.array', (['wordIndices'], {}), '(wordIndices)\n', (1121, 1134), True, 'import numpy as np\n'), ((1490, 1511), 'numpy.array', 'np.array', (['wordIndices'], {}), '(wordIndices)\n', (1498, 1511), True, 'import numpy as np\n'), ((2052, 2073), 'numpy.array', 'np.array', (['wordIndices'], {}), '(wordIndices)\n', (2060, 2073), True, 'import numpy as np\n'), ((2254, 2279), 'numpy.argmax', 'np.argmax', (['y_pred'], {'axis': '(1)'}), '(y_pred, axis=1)\n', (2263, 2279), True, 'import numpy as np\n')]
import os from glob import glob import numpy as np import matplotlib.pyplot as plt import astropy.units as u from crabby import (generate_master_flat_and_dark, photometry, PhotometryResults, PCA_light_curve, params_e, transit_model_e) # Image paths image_paths = sorted(glob('/Users/bmmorris/data/saintex/2019_55cnc/20190427/Raw/*.fts'))[10:] dark_paths = glob('/Users/bmmorris/data/saintex/2019_55cnc/20190427/Dark/*.fts') flat_paths = glob('/Users/bmmorris/data/saintex/2019_55cnc/20190427/Flat/*.fts') master_flat_path = 'outputs/masterflat_20190427.fits' master_dark_path = 'outputs/masterdark_20190427.fits' # Photometry settings target_centroid = np.array([[1111], [1111]]) comparison_flux_threshold = 0.01 aperture_radii = np.arange(20, 30, 2) centroid_stamp_half_width = 30 psf_stddev_init = 30 aperture_annulus_radius = 10 transit_parameters = params_e star_positions = np.array([[1096, 1093], [1378, 1719]]) output_path = 'outputs/55cnc_20190427.npz' force_recompute_photometry = False #True # Calculate master dark/flat: if not os.path.exists(master_dark_path) or not os.path.exists(master_flat_path): print('Calculating master flat:') generate_master_flat_and_dark(flat_paths, dark_paths, master_flat_path, master_dark_path) # Do photometry: if not os.path.exists(output_path) or force_recompute_photometry: print('Calculating photometry:') phot_results = photometry(image_paths, master_dark_path, master_flat_path, target_centroid, comparison_flux_threshold, aperture_radii, centroid_stamp_half_width, psf_stddev_init, aperture_annulus_radius, output_path, star_positions) else: phot_results = PhotometryResults.load(output_path) print(phot_results.xcentroids.shape) # print('Calculating PCA...') # plt.plot(phot_results.times, phot_results.fluxes[:, 1, :5]) # plt.show() lcs = phot_results.fluxes[:, 0, :]/phot_results.fluxes[:, 1, :] std = np.std(lcs, axis=0) start = 50 stop = -1 light_curve = lcs[start:stop, std.argmax()] not_cloudy = np.ones_like(light_curve).astype(bool) minus_airmass = 1 - phot_results.airmass[start:stop] dx = phot_results.xcentroids[start:stop, 0] - phot_results.xcentroids[:, 0].mean() dy = phot_results.ycentroids[start:stop, 0] - phot_results.ycentroids[:, 0].mean() X = np.vstack([light_curve, minus_airmass, minus_airmass**2, dx, dy, phot_results.background_median[start:stop] ]).T c = np.linalg.lstsq(X, np.ones(X.shape[0]))[0] detrended_light_curve = X @ c plt.plot(phot_results.times[start:stop], detrended_light_curve, '.', color='gray') plt.show()
[ "crabby.PhotometryResults.load", "os.path.exists", "numpy.ones_like", "numpy.ones", "numpy.arange", "matplotlib.pyplot.plot", "numpy.array", "crabby.photometry", "crabby.generate_master_flat_and_dark", "numpy.vstack", "numpy.std", "glob.glob", "matplotlib.pyplot.show" ]
[((400, 467), 'glob.glob', 'glob', (['"""/Users/bmmorris/data/saintex/2019_55cnc/20190427/Dark/*.fts"""'], {}), "('/Users/bmmorris/data/saintex/2019_55cnc/20190427/Dark/*.fts')\n", (404, 467), False, 'from glob import glob\n'), ((481, 548), 'glob.glob', 'glob', (['"""/Users/bmmorris/data/saintex/2019_55cnc/20190427/Flat/*.fts"""'], {}), "('/Users/bmmorris/data/saintex/2019_55cnc/20190427/Flat/*.fts')\n", (485, 548), False, 'from glob import glob\n'), ((698, 724), 'numpy.array', 'np.array', (['[[1111], [1111]]'], {}), '([[1111], [1111]])\n', (706, 724), True, 'import numpy as np\n'), ((775, 795), 'numpy.arange', 'np.arange', (['(20)', '(30)', '(2)'], {}), '(20, 30, 2)\n', (784, 795), True, 'import numpy as np\n'), ((924, 962), 'numpy.array', 'np.array', (['[[1096, 1093], [1378, 1719]]'], {}), '([[1096, 1093], [1378, 1719]])\n', (932, 962), True, 'import numpy as np\n'), ((2084, 2103), 'numpy.std', 'np.std', (['lcs'], {'axis': '(0)'}), '(lcs, axis=0)\n', (2090, 2103), True, 'import numpy as np\n'), ((2716, 2803), 'matplotlib.pyplot.plot', 'plt.plot', (['phot_results.times[start:stop]', 'detrended_light_curve', '"""."""'], {'color': '"""gray"""'}), "(phot_results.times[start:stop], detrended_light_curve, '.', color=\n 'gray')\n", (2724, 2803), True, 'import matplotlib.pyplot as plt\n'), ((2800, 2810), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2808, 2810), True, 'import matplotlib.pyplot as plt\n'), ((1202, 1295), 'crabby.generate_master_flat_and_dark', 'generate_master_flat_and_dark', (['flat_paths', 'dark_paths', 'master_flat_path', 'master_dark_path'], {}), '(flat_paths, dark_paths, master_flat_path,\n master_dark_path)\n', (1231, 1295), False, 'from crabby import generate_master_flat_and_dark, photometry, PhotometryResults, PCA_light_curve, params_e, transit_model_e\n'), ((1467, 1692), 'crabby.photometry', 'photometry', (['image_paths', 'master_dark_path', 'master_flat_path', 'target_centroid', 'comparison_flux_threshold', 'aperture_radii', 'centroid_stamp_half_width', 'psf_stddev_init', 'aperture_annulus_radius', 'output_path', 'star_positions'], {}), '(image_paths, master_dark_path, master_flat_path, target_centroid,\n comparison_flux_threshold, aperture_radii, centroid_stamp_half_width,\n psf_stddev_init, aperture_annulus_radius, output_path, star_positions)\n', (1477, 1692), False, 'from crabby import generate_master_flat_and_dark, photometry, PhotometryResults, PCA_light_curve, params_e, transit_model_e\n'), ((1831, 1866), 'crabby.PhotometryResults.load', 'PhotometryResults.load', (['output_path'], {}), '(output_path)\n', (1853, 1866), False, 'from crabby import generate_master_flat_and_dark, photometry, PhotometryResults, PCA_light_curve, params_e, transit_model_e\n'), ((2448, 2563), 'numpy.vstack', 'np.vstack', (['[light_curve, minus_airmass, minus_airmass ** 2, dx, dy, phot_results.\n background_median[start:stop]]'], {}), '([light_curve, minus_airmass, minus_airmass ** 2, dx, dy,\n phot_results.background_median[start:stop]])\n', (2457, 2563), True, 'import numpy as np\n'), ((314, 380), 'glob.glob', 'glob', (['"""/Users/bmmorris/data/saintex/2019_55cnc/20190427/Raw/*.fts"""'], {}), "('/Users/bmmorris/data/saintex/2019_55cnc/20190427/Raw/*.fts')\n", (318, 380), False, 'from glob import glob\n'), ((1086, 1118), 'os.path.exists', 'os.path.exists', (['master_dark_path'], {}), '(master_dark_path)\n', (1100, 1118), False, 'import os\n'), ((1126, 1158), 'os.path.exists', 'os.path.exists', (['master_flat_path'], {}), '(master_flat_path)\n', (1140, 1158), False, 'import os\n'), ((1352, 1379), 'os.path.exists', 'os.path.exists', (['output_path'], {}), '(output_path)\n', (1366, 1379), False, 'import os\n'), ((2184, 2209), 'numpy.ones_like', 'np.ones_like', (['light_curve'], {}), '(light_curve)\n', (2196, 2209), True, 'import numpy as np\n'), ((2660, 2679), 'numpy.ones', 'np.ones', (['X.shape[0]'], {}), '(X.shape[0])\n', (2667, 2679), True, 'import numpy as np\n')]
import numpy as np def norm_to_zscore(img_array, cer_arr, max_z_score=4.0): temp_cer_mask = (cer_arr > 0) temp_masked_img = img_array[temp_cer_mask] temp_avg_img = np.mean(temp_masked_img) temp_std_img = np.std(temp_masked_img) img_array[temp_cer_mask] = (img_array[temp_cer_mask] - temp_avg_img) / temp_std_img img_array[temp_cer_mask == 0] = 0 img_array[img_array > max_z_score] = max_z_score del temp_masked_img, temp_avg_img, temp_std_img return img_array
[ "numpy.mean", "numpy.std" ]
[((190, 214), 'numpy.mean', 'np.mean', (['temp_masked_img'], {}), '(temp_masked_img)\n', (197, 214), True, 'import numpy as np\n'), ((238, 261), 'numpy.std', 'np.std', (['temp_masked_img'], {}), '(temp_masked_img)\n', (244, 261), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ : Project - RGANet : calculate statistics : Author - <NAME> : Institute - University of Kansas : Date - 5/20/2021 : HowTo: Set "Choice", evaluation file is a must-be for calculating statistics """ import torch from pathlib import Path import numpy as np from thop import profile Choice = { "COUNT_PARAMS": 0, # Set True to see comparision on parameters "CAL_STATS": 1, # Show statistics, NOTE: "evaluation.txt" is necessary "EVA_DIR": r"D:\RGANet\results_acrt_suction\evaluation\evaluation.txt", # path to "evalutation.txt" "PERCENTI": np.linspace(5, 100, 19, dtype=int, endpoint=False), # set percentile, 0-100, can either be a number "SAVE_STATS": 0, # set True to save statistic results to the same folder # ignored by setting CLA_STATS to 0 "SHOW_MACs": 0, # set true to show GFLOPs info of model using thop "MODEL": "acrt" # choose model to calculate GFLOPs between "acrt" and "fast" } # get network parameters def cal_param(_net): return { "total": sum(item.numel() for item in _net.parameters()) / 1e6, "train": sum(item.numel() for item in _net.parameters() if item.requires_grad) / 1e6 } if __name__ == '__main__': # calculate parameters if Choice["COUNT_PARAMS"]: # from utils.network import GANet_sep, GANet_shared, GANet_shared_ga_realtime, \ # GANet_shared_ga_accurate, GANet_dense_ga_accurate from utils.network import GANet_dense_ga_accurate_small_link, GANet_dense_ga_realtime from torchvision.models.segmentation import fcn_resnet50, fcn_resnet101, deeplabv3_resnet50, \ deeplabv3_resnet101, deeplabv3_mobilenet_v3_large, lraspp_mobilenet_v3_large modelLList = torch.nn.ModuleDict({ "RGA_accurate": GANet_dense_ga_accurate_small_link(20), "RGA_realtime": GANet_dense_ga_realtime(), "FCN_resnet50": fcn_resnet50(), "FCN_resnet101": fcn_resnet101(), "DeepLabv3_resnet50": deeplabv3_resnet50(), "DeepLabv3_resnet101": deeplabv3_resnet101(), "DeepLabv3_mobilenetv3_large": deeplabv3_mobilenet_v3_large(), "LR-ASPP_mobilenet_v3_large": lraspp_mobilenet_v3_large() }) print("\n============== RGANet Statistics: Parameters ==============\n") for key in modelLList.keys(): stats = cal_param(modelLList[key]) print(f"Model: {key}\nTotal: {stats['total']: .2f}M\n" f"Trainable: {stats['train']: .2f}M\n") # stats of evaluation performance for all metrics if Choice["CAL_STATS"]: textDir = Path.resolve(Path(Choice["EVA_DIR"])) assert textDir.is_file(), "Cannot find evaluation file" print("\n============== RGANet Statistics: evaluation ==============") with open(textDir, "rt") as f: Lines = f.read().splitlines() assert len(Lines) > 0, "Empty evaluation file" varDict = {"name": [], "iou":[], "acc": [], "dice":[], "precision": [], "recall":[], "mgrid": [], "tpr": [], "fpr":[], "mcc": []} for l in Lines: items = l.split(" ") varDict["name"].append(items[0]) for item in items[1:]: varDict[item.split(":")[0]].append(float(item.split(":")[1])) All = dict() for key in varDict.keys(): if key != "name" and len(varDict[key]): All[key] = np.array(varDict[key]) All["STEP"] = Choice["PERCENTI"] for key in All.keys(): if key != "STEP": All[key] = { "range": All[key].ptp(), "percenti": np.percentile(All[key], All["STEP"]), "mean": All[key].mean(), "median": np.median(All[key]), "var": All[key].var(), "std": All[key].std() } print(f"\n***** {key} *****\n" f"Range: {All[key]['range']:.2f}\n" f"Mean: {All[key]['mean']:.2f}\n" f"Std: {All[key]['std']:.2f}\n" f"Median: {All[key]['median']:.2f}\n" f"Var: {All[key]['var']:.2f}\n" f"Step:\n{All['STEP']}\n" f"Percentile:\n{All[key]['percenti']}\n") # save results if Choice["SAVE_STATS"]: statsDir = textDir.parent.joinpath("statistics.txt") print(f"\nSaving statistic results to:\n{statsDir}\n") with open(statsDir, "a+") as f: f.write(f"\n\n\n\nevaluation file:\n{textDir.resolve()}\n") f.write(f"\nPercentile percentages:\n{All['STEP']}\n") for key in All.keys(): if key != "STEP": f.write(f"\n***** {key} *****\n" f"Range: {All[key]['range']:.2f}\n" f"Mean: {All[key]['mean']:.2f}\n" f"Std: {All[key]['std']:.2f}\n" f"Median: {All[key]['median']:.2f}\n" f"Var: {All[key]['var']:.2f}\n" f"Percentile:\n{All[key]['percenti']}\n") print(f"Done!\n") # show MACs info if Choice["SHOW_MACs"]: assert Choice["MODEL"] in ["acrt", "fast"] if Choice["MODEL"] == "acrt": from utils.network import GANet_dense_ga_accurate_small_link model = GANet_dense_ga_accurate_small_link(20) elif Choice["MODEL"] == "fast": from utils.network import GANet_dense_ga_realtime model = GANet_dense_ga_realtime input_ = torch.randn(1, 3, 512, 1024) macs = profile(model, inputs=(input_,)) print(f"\n{'RGANet_'+Choice['MODEL']}:\n" f"{macs[0]/5e8:.4f}G\n" f"{macs[1]/1e6:.4f}M parameters\n")
[ "torchvision.models.segmentation.fcn_resnet50", "torchvision.models.segmentation.deeplabv3_resnet101", "torchvision.models.segmentation.lraspp_mobilenet_v3_large", "numpy.median", "torchvision.models.segmentation.fcn_resnet101", "utils.network.GANet_dense_ga_accurate_small_link", "pathlib.Path", "thop...
[((647, 697), 'numpy.linspace', 'np.linspace', (['(5)', '(100)', '(19)'], {'dtype': 'int', 'endpoint': '(False)'}), '(5, 100, 19, dtype=int, endpoint=False)\n', (658, 697), True, 'import numpy as np\n'), ((6026, 6054), 'torch.randn', 'torch.randn', (['(1)', '(3)', '(512)', '(1024)'], {}), '(1, 3, 512, 1024)\n', (6037, 6054), False, 'import torch\n'), ((6070, 6102), 'thop.profile', 'profile', (['model'], {'inputs': '(input_,)'}), '(model, inputs=(input_,))\n', (6077, 6102), False, 'from thop import profile\n'), ((2884, 2907), 'pathlib.Path', 'Path', (["Choice['EVA_DIR']"], {}), "(Choice['EVA_DIR'])\n", (2888, 2907), False, 'from pathlib import Path\n'), ((5823, 5861), 'utils.network.GANet_dense_ga_accurate_small_link', 'GANet_dense_ga_accurate_small_link', (['(20)'], {}), '(20)\n', (5857, 5861), False, 'from utils.network import GANet_dense_ga_accurate_small_link\n'), ((1960, 1998), 'utils.network.GANet_dense_ga_accurate_small_link', 'GANet_dense_ga_accurate_small_link', (['(20)'], {}), '(20)\n', (1994, 1998), False, 'from utils.network import GANet_dense_ga_accurate_small_link\n'), ((2036, 2061), 'utils.network.GANet_dense_ga_realtime', 'GANet_dense_ga_realtime', ([], {}), '()\n', (2059, 2061), False, 'from utils.network import GANet_dense_ga_realtime\n'), ((2099, 2113), 'torchvision.models.segmentation.fcn_resnet50', 'fcn_resnet50', ([], {}), '()\n', (2111, 2113), False, 'from torchvision.models.segmentation import fcn_resnet50, fcn_resnet101, deeplabv3_resnet50, deeplabv3_resnet101, deeplabv3_mobilenet_v3_large, lraspp_mobilenet_v3_large\n'), ((2152, 2167), 'torchvision.models.segmentation.fcn_resnet101', 'fcn_resnet101', ([], {}), '()\n', (2165, 2167), False, 'from torchvision.models.segmentation import fcn_resnet50, fcn_resnet101, deeplabv3_resnet50, deeplabv3_resnet101, deeplabv3_mobilenet_v3_large, lraspp_mobilenet_v3_large\n'), ((2211, 2231), 'torchvision.models.segmentation.deeplabv3_resnet50', 'deeplabv3_resnet50', ([], {}), '()\n', (2229, 2231), False, 'from torchvision.models.segmentation import fcn_resnet50, fcn_resnet101, deeplabv3_resnet50, deeplabv3_resnet101, deeplabv3_mobilenet_v3_large, lraspp_mobilenet_v3_large\n'), ((2276, 2297), 'torchvision.models.segmentation.deeplabv3_resnet101', 'deeplabv3_resnet101', ([], {}), '()\n', (2295, 2297), False, 'from torchvision.models.segmentation import fcn_resnet50, fcn_resnet101, deeplabv3_resnet50, deeplabv3_resnet101, deeplabv3_mobilenet_v3_large, lraspp_mobilenet_v3_large\n'), ((2350, 2380), 'torchvision.models.segmentation.deeplabv3_mobilenet_v3_large', 'deeplabv3_mobilenet_v3_large', ([], {}), '()\n', (2378, 2380), False, 'from torchvision.models.segmentation import fcn_resnet50, fcn_resnet101, deeplabv3_resnet50, deeplabv3_resnet101, deeplabv3_mobilenet_v3_large, lraspp_mobilenet_v3_large\n'), ((2432, 2459), 'torchvision.models.segmentation.lraspp_mobilenet_v3_large', 'lraspp_mobilenet_v3_large', ([], {}), '()\n', (2457, 2459), False, 'from torchvision.models.segmentation import fcn_resnet50, fcn_resnet101, deeplabv3_resnet50, deeplabv3_resnet101, deeplabv3_mobilenet_v3_large, lraspp_mobilenet_v3_large\n'), ((3697, 3719), 'numpy.array', 'np.array', (['varDict[key]'], {}), '(varDict[key])\n', (3705, 3719), True, 'import numpy as np\n'), ((3938, 3974), 'numpy.percentile', 'np.percentile', (['All[key]', "All['STEP']"], {}), "(All[key], All['STEP'])\n", (3951, 3974), True, 'import numpy as np\n'), ((4059, 4078), 'numpy.median', 'np.median', (['All[key]'], {}), '(All[key])\n', (4068, 4078), True, 'import numpy as np\n')]
# adapted from https://github.com/berenslab/mini-atlas/blob/master/code/patch-seq-data-load.ipynb import numpy as np import scanpy as sc import math #import pylab as plt #import seaborn as sns import pandas as pd import pickle import scipy.sparse import scipy import time import warnings import os OUTPUT_FOLDER = './data/transformed/1_refformated' # Read metadata meta = pd.read_csv('./data/original/m1_patchseq_meta_data.csv', sep='\t') cells = meta['Cell'].values meta.set_index("Cell", inplace=True) # TRANSCRIPTOMIC DATA: read counts data_exons = pd.read_csv('./data/original/m1_patchseq_exon_counts.csv.gz', na_filter=False, index_col=0) exonCounts = data_exons.values.transpose() exonCounts = scipy.sparse.csr_matrix(exonCounts) assert(all(cells==data_exons.columns)) genes = np.array(data_exons.index) data_introns = pd.read_csv('./data/original/m1_patchseq_intron_counts.csv.gz', na_filter=False, index_col=0) intronCounts = data_introns.values.transpose() intronCounts = scipy.sparse.csr_matrix(intronCounts) assert(all(cells==data_introns.columns)) assert(all(data_introns.index==data_exons.index)) # EPHYS DATA ephysData = pd.read_csv('./data/original/m1_patchseq_ephys_features.csv', index_col=0) # MORPH DATA morphometrics = pd.read_csv('./data/original/m1_patchseq_morph_features.csv', index_col=0) # Read tsnes tsne_general = pd.read_csv("./data/original/coverage-tsnes.csv", index_col=0).dropna() tsne_features = pd.read_csv("./data/original/morpho-electric-tsnes.csv", index_col=0) # Correct "/" in column names for i in meta.columns: if "/" in i: meta.rename(columns={i:i.replace('/', '')}, inplace=True) general = sc.AnnData(exonCounts + intronCounts, obs=meta, var=pd.DataFrame(genes, columns=['gene_symbol']).set_index("gene_symbol")) #general['exons'] = sc.AnnData(exonCounts, obs=meta, var=pd.DataFrame(genes, columns=['gene_symbol']).set_index("gene_symbol")) #general['inrons'] = sc.AnnData(intronCounts, obs=meta, var=pd.DataFrame(genes, columns = ['gene_symbol']).set_index("gene_symbol")) # Save merged data with 10x AIBS for neuron_type in tsne_general["Which t-SNE"].drop_duplicates(): tsne = tsne_general.loc[tsne_general['Which t-SNE'] == neuron_type,["t-SNE position x", "t-SNE position y"]] x = general x = x[tsne.index,] x.obsm["X_tsne"] = tsne.to_numpy() neuron_type = neuron_type.replace("/", "") x.write_h5ad(os.path.join(OUTPUT_FOLDER, "patchseq_nonMorpho_" + neuron_type + ".h5ad"), compression='gzip') # Save electro physiological h5ad current_tsne = tsne_features[["Ephys t-SNE x", "Ephys t-SNE y"]].dropna() x = general x = x[current_tsne.index,] x.obs = x.obs.join(ephysData) x.obsm["X_tsne"] = current_tsne.to_numpy() x.write_h5ad(os.path.join(OUTPUT_FOLDER, "patchseq_electro_phys.h5ad"), compression='gzip') # Save morphological h5ad current_tsne = tsne_features[["Morph t-SNE x", "Moprh t-SNE y"]].dropna() x = general x = x[current_tsne.index,] x.obs = x.obs.join(morphometrics) x.obsm["X_tsne"] = current_tsne.to_numpy() x.write_h5ad(os.path.join(OUTPUT_FOLDER, "patchseq_morphological.h5ad"), compression='gzip') # Save morphoelectro h5ad current_tsne = tsne_features[["Morphoelectric t-SNE x", "Morphoelectric t-SNE y"]].dropna() x = general x = x[current_tsne.index,] x.obs = x.obs.join(ephysData) x.obs = x.obs.join(morphometrics) x.obsm["X_tsne"] = current_tsne.to_numpy() x.write_h5ad(os.path.join(OUTPUT_FOLDER, "patchseq_morpholphys.h5ad"), compression='gzip')
[ "pandas.read_csv", "os.path.join", "numpy.array", "pandas.DataFrame", "scipy.sparse.csr_matrix" ]
[((375, 441), 'pandas.read_csv', 'pd.read_csv', (['"""./data/original/m1_patchseq_meta_data.csv"""'], {'sep': '"""\t"""'}), "('./data/original/m1_patchseq_meta_data.csv', sep='\\t')\n", (386, 441), True, 'import pandas as pd\n'), ((557, 653), 'pandas.read_csv', 'pd.read_csv', (['"""./data/original/m1_patchseq_exon_counts.csv.gz"""'], {'na_filter': '(False)', 'index_col': '(0)'}), "('./data/original/m1_patchseq_exon_counts.csv.gz', na_filter=\n False, index_col=0)\n", (568, 653), True, 'import pandas as pd\n'), ((705, 740), 'scipy.sparse.csr_matrix', 'scipy.sparse.csr_matrix', (['exonCounts'], {}), '(exonCounts)\n', (728, 740), False, 'import scipy\n'), ((788, 814), 'numpy.array', 'np.array', (['data_exons.index'], {}), '(data_exons.index)\n', (796, 814), True, 'import numpy as np\n'), ((831, 929), 'pandas.read_csv', 'pd.read_csv', (['"""./data/original/m1_patchseq_intron_counts.csv.gz"""'], {'na_filter': '(False)', 'index_col': '(0)'}), "('./data/original/m1_patchseq_intron_counts.csv.gz', na_filter=\n False, index_col=0)\n", (842, 929), True, 'import pandas as pd\n'), ((987, 1024), 'scipy.sparse.csr_matrix', 'scipy.sparse.csr_matrix', (['intronCounts'], {}), '(intronCounts)\n', (1010, 1024), False, 'import scipy\n'), ((1143, 1217), 'pandas.read_csv', 'pd.read_csv', (['"""./data/original/m1_patchseq_ephys_features.csv"""'], {'index_col': '(0)'}), "('./data/original/m1_patchseq_ephys_features.csv', index_col=0)\n", (1154, 1217), True, 'import pandas as pd\n'), ((1249, 1323), 'pandas.read_csv', 'pd.read_csv', (['"""./data/original/m1_patchseq_morph_features.csv"""'], {'index_col': '(0)'}), "('./data/original/m1_patchseq_morph_features.csv', index_col=0)\n", (1260, 1323), True, 'import pandas as pd\n'), ((1450, 1519), 'pandas.read_csv', 'pd.read_csv', (['"""./data/original/morpho-electric-tsnes.csv"""'], {'index_col': '(0)'}), "('./data/original/morpho-electric-tsnes.csv', index_col=0)\n", (1461, 1519), True, 'import pandas as pd\n'), ((2754, 2811), 'os.path.join', 'os.path.join', (['OUTPUT_FOLDER', '"""patchseq_electro_phys.h5ad"""'], {}), "(OUTPUT_FOLDER, 'patchseq_electro_phys.h5ad')\n", (2766, 2811), False, 'import os\n'), ((3071, 3129), 'os.path.join', 'os.path.join', (['OUTPUT_FOLDER', '"""patchseq_morphological.h5ad"""'], {}), "(OUTPUT_FOLDER, 'patchseq_morphological.h5ad')\n", (3083, 3129), False, 'import os\n'), ((3436, 3492), 'os.path.join', 'os.path.join', (['OUTPUT_FOLDER', '"""patchseq_morpholphys.h5ad"""'], {}), "(OUTPUT_FOLDER, 'patchseq_morpholphys.h5ad')\n", (3448, 3492), False, 'import os\n'), ((1362, 1424), 'pandas.read_csv', 'pd.read_csv', (['"""./data/original/coverage-tsnes.csv"""'], {'index_col': '(0)'}), "('./data/original/coverage-tsnes.csv', index_col=0)\n", (1373, 1424), True, 'import pandas as pd\n'), ((2421, 2495), 'os.path.join', 'os.path.join', (['OUTPUT_FOLDER', "('patchseq_nonMorpho_' + neuron_type + '.h5ad')"], {}), "(OUTPUT_FOLDER, 'patchseq_nonMorpho_' + neuron_type + '.h5ad')\n", (2433, 2495), False, 'import os\n'), ((1729, 1773), 'pandas.DataFrame', 'pd.DataFrame', (['genes'], {'columns': "['gene_symbol']"}), "(genes, columns=['gene_symbol'])\n", (1741, 1773), True, 'import pandas as pd\n')]
from flask import Blueprint, current_app, abort, request, jsonify from functools import wraps from app.db import db, User, Hex, QuestionList, World from datetime import datetime, timedelta import numpy bp = Blueprint('interface', __name__) def validate_request(f): @wraps(f) def decorated_function(*args, **kwargs): data = request.headers.get('handshake') if not data == current_app.config['SECRET']: abort(401) return f(*args, **kwargs) return decorated_function @bp.route('/') def status(): return 'True' @bp.route('/user/<username>') def user(username): user = User.query.filter_by(username=username).first() if user is None: abort(404) return '', 200 @bp.route('/world/<seed>/check/<position>') def check_hex(seed, position): t = Hex.query.filter_by(position=position, world_seed=seed).first() if t is None: abort(404) if t.broken is None: t.broken = (datetime.now() - timedelta(seconds=60)).timestamp() db.session.commit() if datetime.now() - datetime.utcfromtimestamp(t.broken) > timedelta(seconds=60): return jsonify(True) else: return jsonify(False) @bp.route('/user/<username>/set_position/<position>') def set_position(username, position): user = User.query.filter_by(username=username).first() if user is None: abort(404) user.position = position db.session.commit() return '', 200 @bp.route('/world/<seed>/break/<id>') def break_hex(id): t = Hex.query.filter_by(position=id, world_seed=seed).first() if t is None: abort(404) t = Hex(broken=datetime.now().timestamp()) db.session.add(t) db.session.commit() return '', 200 @bp.route('/initialise/<seed>') def create_world(seed): seed = int(seed) world = World.query.filter_by(seed=seed).first() if world is None: world = World(seed=seed) hexes = world.hexes.all() if len(hexes) != 1000: numpy.random.seed(seed=seed) dummy_list = [] for i in range(1000): position = numpy.random.randint(0,10000) if position not in dummy_list: h = Hex(position=i,broken=(datetime.now()-timedelta(seconds=60)).timestamp(), world=world) dummy_list.append(position) db.session.add(h) db.session.commit() return jsonify(dummy_list), 200 @bp.route('/questions/get_lists') def get_question_lists(): qlists = QuestionList.query.all() if qlists is None: abort(404) lists = {} for qlist in qlists: lists[qlist.id] = qlist.title return jsonify(lists) @bp.route('/questions/get_list/<id>') def get_question_list(id): qlist = QuestionList.query.filter_by(id=id).first() if qlist is None: abort(404) questions = [] for question in qlist.questions: questions.append({'question': question.question, 'answer': question.answer}) return jsonify(questions) @bp.route('/questions/get_flavour_text/<id>') def get_flavour_text_list(id): qlist = QuestionList.query.filter_by(id=id).first() if qlist is None: abort(404) flavour_texts = [] for flavour_text in qlist.flavour_text: flavour_texts.append({'flavour_text': flavour_text.text, 'category': flavour_text.category}) return jsonify(flavour_texts) # cheese routes are for testing basic RESTful IO @bp.route('/new_cheese', methods=['POST']) def new_cheese(): global cheese cheese = request.form["newCheese"] return "Now the cheese is " + cheese + "!" @bp.route('/cheese') def cheese(): return cheese
[ "datetime.datetime.utcfromtimestamp", "app.db.World.query.filter_by", "app.db.QuestionList.query.all", "app.db.Hex.query.filter_by", "app.db.db.session.commit", "app.db.User.query.filter_by", "app.db.World", "functools.wraps", "datetime.timedelta", "datetime.datetime.now", "numpy.random.randint"...
[((209, 241), 'flask.Blueprint', 'Blueprint', (['"""interface"""', '__name__'], {}), "('interface', __name__)\n", (218, 241), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((273, 281), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (278, 281), False, 'from functools import wraps\n'), ((1426, 1445), 'app.db.db.session.commit', 'db.session.commit', ([], {}), '()\n', (1443, 1445), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((1678, 1695), 'app.db.db.session.add', 'db.session.add', (['t'], {}), '(t)\n', (1692, 1695), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((1700, 1719), 'app.db.db.session.commit', 'db.session.commit', ([], {}), '()\n', (1717, 1719), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((2443, 2467), 'app.db.QuestionList.query.all', 'QuestionList.query.all', ([], {}), '()\n', (2465, 2467), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((2599, 2613), 'flask.jsonify', 'jsonify', (['lists'], {}), '(lists)\n', (2606, 2613), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((2930, 2948), 'flask.jsonify', 'jsonify', (['questions'], {}), '(questions)\n', (2937, 2948), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((3304, 3326), 'flask.jsonify', 'jsonify', (['flavour_texts'], {}), '(flavour_texts)\n', (3311, 3326), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((342, 374), 'flask.request.headers.get', 'request.headers.get', (['"""handshake"""'], {}), "('handshake')\n", (361, 374), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((705, 715), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (710, 715), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((910, 920), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (915, 920), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((1026, 1045), 'app.db.db.session.commit', 'db.session.commit', ([], {}), '()\n', (1043, 1045), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((1108, 1129), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(60)'}), '(seconds=60)\n', (1117, 1129), False, 'from datetime import datetime, timedelta\n'), ((1146, 1159), 'flask.jsonify', 'jsonify', (['(True)'], {}), '(True)\n', (1153, 1159), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((1185, 1199), 'flask.jsonify', 'jsonify', (['(False)'], {}), '(False)\n', (1192, 1199), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((1382, 1392), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (1387, 1392), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((1616, 1626), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (1621, 1626), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((1909, 1925), 'app.db.World', 'World', ([], {'seed': 'seed'}), '(seed=seed)\n', (1914, 1925), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((1988, 2016), 'numpy.random.seed', 'numpy.random.seed', ([], {'seed': 'seed'}), '(seed=seed)\n', (2005, 2016), False, 'import numpy\n'), ((2312, 2331), 'app.db.db.session.commit', 'db.session.commit', ([], {}), '()\n', (2329, 2331), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((2343, 2362), 'flask.jsonify', 'jsonify', (['dummy_list'], {}), '(dummy_list)\n', (2350, 2362), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((2499, 2509), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (2504, 2509), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((2767, 2777), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (2772, 2777), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((3114, 3124), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (3119, 3124), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((440, 450), 'flask.abort', 'abort', (['(401)'], {}), '(401)\n', (445, 450), False, 'from flask import Blueprint, current_app, abort, request, jsonify\n'), ((628, 667), 'app.db.User.query.filter_by', 'User.query.filter_by', ([], {'username': 'username'}), '(username=username)\n', (648, 667), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((820, 875), 'app.db.Hex.query.filter_by', 'Hex.query.filter_by', ([], {'position': 'position', 'world_seed': 'seed'}), '(position=position, world_seed=seed)\n', (839, 875), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((1053, 1067), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1065, 1067), False, 'from datetime import datetime, timedelta\n'), ((1070, 1105), 'datetime.datetime.utcfromtimestamp', 'datetime.utcfromtimestamp', (['t.broken'], {}), '(t.broken)\n', (1095, 1105), False, 'from datetime import datetime, timedelta\n'), ((1305, 1344), 'app.db.User.query.filter_by', 'User.query.filter_by', ([], {'username': 'username'}), '(username=username)\n', (1325, 1344), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((1532, 1581), 'app.db.Hex.query.filter_by', 'Hex.query.filter_by', ([], {'position': 'id', 'world_seed': 'seed'}), '(position=id, world_seed=seed)\n', (1551, 1581), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((1830, 1862), 'app.db.World.query.filter_by', 'World.query.filter_by', ([], {'seed': 'seed'}), '(seed=seed)\n', (1851, 1862), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((2082, 2112), 'numpy.random.randint', 'numpy.random.randint', (['(0)', '(10000)'], {}), '(0, 10000)\n', (2102, 2112), False, 'import numpy\n'), ((2693, 2728), 'app.db.QuestionList.query.filter_by', 'QuestionList.query.filter_by', ([], {'id': 'id'}), '(id=id)\n', (2721, 2728), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((3040, 3075), 'app.db.QuestionList.query.filter_by', 'QuestionList.query.filter_by', ([], {'id': 'id'}), '(id=id)\n', (3068, 3075), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((2289, 2306), 'app.db.db.session.add', 'db.session.add', (['h'], {}), '(h)\n', (2303, 2306), False, 'from app.db import db, User, Hex, QuestionList, World\n'), ((966, 980), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (978, 980), False, 'from datetime import datetime, timedelta\n'), ((983, 1004), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(60)'}), '(seconds=60)\n', (992, 1004), False, 'from datetime import datetime, timedelta\n'), ((1646, 1660), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1658, 1660), False, 'from datetime import datetime, timedelta\n'), ((2183, 2197), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2195, 2197), False, 'from datetime import datetime, timedelta\n'), ((2198, 2219), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(60)'}), '(seconds=60)\n', (2207, 2219), False, 'from datetime import datetime, timedelta\n')]
import numpy as np import torch class Cutout(object): """Randomly mask out one or more patches from an image. please refer to https://github.com/uoguelph-mlrg/Cutout/blob/master/util/cutout.py Args: n_holes (int): Number of patches to cut out of each image. length (int): The length (in pixels) of each square patch. """ def __init__(self, n_holes, length): self.n_holes = n_holes self.length = length def __call__(self, img): """ Args: img (Tensor): Tensor image of size (C, H, W). Returns: Tensor: Image with n_holes of dimension length x length cut out of it. """ if isinstance(img, np.ndarray): h = img.shape[1] w = img.shape[2] else: h = img.size(1) w = img.size(2) mask = np.ones((h, w), np.float32) for n in range(self.n_holes): # center point of the cutout region y = np.random.randint(h) x = np.random.randint(w) width = int(self.length / 2) y1 = np.clip(y - width, 0, h) y2 = np.clip(y + width, 0, h) x1 = np.clip(x - width, 0, w) x2 = np.clip(x + width, 0, w) mask[y1: y2, x1: x2] = 0.0 if isinstance(img, np.ndarray): mask = np.expand_dims(mask, axis=0) else: mask = torch.from_numpy(mask) mask = mask.expand_as(img) return img * mask class PostNormRandomHorizontalFlip(object): """ Random horizontal flip after normalization """ def __init__(self, flip_prob=0.5): self.flip_prob = flip_prob def __call__(self, img): """ Args: img (Tensor): Tensor image of size (C, H, W). Returns: Tensor: Image after random horizontal flip. """ if np.random.random_sample() < self.flip_prob: np_img = img.numpy() # C, H, W np_img = np_img[:, :, ::-1].copy() img = torch.from_numpy(np_img).float() return img class PostNormRandomCrop(object): """ Random crop after normalization """ def __init__(self, pad=4): self.pad = pad def __call__(self, img): """ Args: img (Tensor): Tensor image of size (C, H, W). Returns: Tensor: Image after random horizontal flip. """ np_img = img.numpy() # C, H, W init_shape = np_img.shape new_shape = [init_shape[0], init_shape[1] + self.pad * 2, init_shape[2] + self.pad * 2] zeros_padded = np.zeros(new_shape) zeros_padded[:, self.pad:init_shape[1] + self.pad, self.pad:init_shape[2] + self.pad] = np_img # randomly crop to original size init_x = np.random.randint(0, self.pad * 2) init_y = np.random.randint(0, self.pad * 2) cropped = zeros_padded[:, init_x: init_x + init_shape[1], init_y: init_y + init_shape[2]] img = torch.from_numpy(cropped).float() return img
[ "numpy.clip", "numpy.random.random_sample", "numpy.ones", "torch.from_numpy", "numpy.zeros", "numpy.random.randint", "numpy.expand_dims" ]
[((731, 758), 'numpy.ones', 'np.ones', (['(h, w)', 'np.float32'], {}), '((h, w), np.float32)\n', (738, 758), True, 'import numpy as np\n'), ((2223, 2242), 'numpy.zeros', 'np.zeros', (['new_shape'], {}), '(new_shape)\n', (2231, 2242), True, 'import numpy as np\n'), ((2387, 2421), 'numpy.random.randint', 'np.random.randint', (['(0)', '(self.pad * 2)'], {}), '(0, self.pad * 2)\n', (2404, 2421), True, 'import numpy as np\n'), ((2433, 2467), 'numpy.random.randint', 'np.random.randint', (['(0)', '(self.pad * 2)'], {}), '(0, self.pad * 2)\n', (2450, 2467), True, 'import numpy as np\n'), ((838, 858), 'numpy.random.randint', 'np.random.randint', (['h'], {}), '(h)\n', (855, 858), True, 'import numpy as np\n'), ((866, 886), 'numpy.random.randint', 'np.random.randint', (['w'], {}), '(w)\n', (883, 886), True, 'import numpy as np\n'), ((928, 952), 'numpy.clip', 'np.clip', (['(y - width)', '(0)', 'h'], {}), '(y - width, 0, h)\n', (935, 952), True, 'import numpy as np\n'), ((961, 985), 'numpy.clip', 'np.clip', (['(y + width)', '(0)', 'h'], {}), '(y + width, 0, h)\n', (968, 985), True, 'import numpy as np\n'), ((994, 1018), 'numpy.clip', 'np.clip', (['(x - width)', '(0)', 'w'], {}), '(x - width, 0, w)\n', (1001, 1018), True, 'import numpy as np\n'), ((1027, 1051), 'numpy.clip', 'np.clip', (['(x + width)', '(0)', 'w'], {}), '(x + width, 0, w)\n', (1034, 1051), True, 'import numpy as np\n'), ((1128, 1156), 'numpy.expand_dims', 'np.expand_dims', (['mask'], {'axis': '(0)'}), '(mask, axis=0)\n', (1142, 1156), True, 'import numpy as np\n'), ((1175, 1197), 'torch.from_numpy', 'torch.from_numpy', (['mask'], {}), '(mask)\n', (1191, 1197), False, 'import torch\n'), ((1573, 1598), 'numpy.random.random_sample', 'np.random.random_sample', ([], {}), '()\n', (1596, 1598), True, 'import numpy as np\n'), ((2592, 2617), 'torch.from_numpy', 'torch.from_numpy', (['cropped'], {}), '(cropped)\n', (2608, 2617), False, 'import torch\n'), ((1699, 1723), 'torch.from_numpy', 'torch.from_numpy', (['np_img'], {}), '(np_img)\n', (1715, 1723), False, 'import torch\n')]
import warnings import numpy as np import networkx as nx from scipy.stats import logistic from mossspider.estimators.utils import fast_exp_map def uniform_network(n, degree, pr_w=0.35, seed=None): """Generates a uniform random graph for a set number of nodes (n) and specified max and min degree (degree). Additionally, assigns a binary baseline covariate, W, to each observation. Parameters ---------- n : int Number of nodes in the generated network degree : list, set, array An array of two elements. The first element is the minimum degree and the second element is the maximum degree. pr_w : float, optional Probability of W=1. W is a binary baseline covariate assigned to each unit. seed : int, None, optional Random seed to use. Default is None. Returns ------- networkx.Graph Examples -------- Loading the necessary functions >>> from mossspider.dgm import uniform_network Generating the uniform network >>> G = uniform_network(n=500, degree=[0, 2]) """ rng = np.random.default_rng(seed) # Processing degree data if len(degree) > 2: warnings.warn('It looks like your specified bounds is more than two floats. Only the first two ' 'specified bounds are used by the bound statement. So only ' + str(degree[0:2]) + ' will be used', UserWarning) if type(degree) is float or type(degree) is int or type(degree) is str: raise ValueError("degree must be a container of integers") elif degree[0] > degree[1]: raise ValueError('degree thresholds must be listed in ascending order') elif type(degree[0]) is str or type(degree[1]) is str: raise ValueError('degree must be integers') elif type(degree[0]) is float or type(degree[1]) is float: raise ValueError('degree must be integers') elif degree[0] < 0 or degree[1] < 0: raise ValueError('Both degree values must be positive values') else: # Completed all checks pass # checking if even sum for degrees, since needed sum = 1 while sum % 2 != 0: # Degree distribution must be even degree_dist = list(rng.integers(degree[0], # ... proposed degree distribution for min degree degree[1]+1, # ... and max degree (+1 to be inclusive) size=n)) # ... for the n units sum = np.sum(degree_dist) # ... update the sum value to see if valid # Generate network with proposed degree distribution G = nx.configuration_model(degree_dist, # Generate network seed=seed) # ... with seed for consistency # Removing multiple edges! G = nx.Graph(G) # No multi-loops in networks we consider here # Removing self-loops G.remove_edges_from(nx.selfloop_edges(G)) # No self-loops in networks we consider here # Generating baseline covariate W w = rng.binomial(n=1, p=pr_w, size=n) # Generate W for node in G.nodes(): # Adding W to the network node attributes G.nodes[node]['W'] = w[node] # ... via simple indexing # Returning the completed graph return G def clustered_power_law_network(n_cluster, edges=3, pr_cluster=0.75, pr_between=0.0007, pr_w=0.35, seed=None): """Generate a graph with the following features: follows a power-law degree distribution, high(er) clustering coefficient, and an underlying community structure. This graph is created by generating a number of subgraphs with power-law distributions and clustering. The subgraphs are generated using ``networkx.powerlaw_cluster_graph(n=n_cluster[...], m=edges, p=p_cluster)``. This process is repeated for each element in the ``n_cluster`` argument. Then the subgraphs are then randomly connected by creating random edges between nodes of the subgraphs. Parameters ---------- n_cluster : list, set, array, ndarray Specify the N for each subgraph in the clustered power-law network via a list. List should be positive integers that correspond to the N for each subgraph. edges : int, optional Number of edges to generate within each cluster. Equivalent to the ``m`` argument in ``networkx.powerlaw_cluster_graph``. pr_cluster : float, optional Probability of a new node forming a triad with neighbors of connected nodes pr_between : float, optional Probability of an edge between nodes of each cluster. Evaluated for all node pairs, so should be relatively low to keep a high community structure. Default is 0.0007. pr_w : float, optional Probability of the binary baseline covariate W for the network. Default is 0.35. seed : int, None, optional Random seed. Default is None. Returns ------- networkx.Graph Examples -------- Loading the necessary functions >>> from mossspider.dgm import clustered_power_law_network Generating the clustered power-law network >>> G = clustered_power_law_network(n_cluster=[50, 50, 50, 50]) """ # Prep environment rng = np.random.default_rng(seed) N = nx.Graph() for i in range(len(n_cluster)): # Generate the component / subgraph G = nx.powerlaw_cluster_graph(int(n_cluster[i]), m=edges, p=pr_cluster, seed=int(rng.integers(10000, 500000, size=1)[0])) # Re-label nodes so no corresponding overlaps between node labels if i == 0: start_label = 0 else: start_label = np.sum(n_cluster[:i]) mapping = {} for j in range(n_cluster[i]): mapping[j] = start_label + j H = nx.relabel_nodes(G, mapping) # Adding component / subgraph to overall network N.add_nodes_from(H.nodes) N.add_edges_from(H.edges) # Creating some random connections across groups for i in range(len(n_cluster)): # Gettings IDs for the subgraph first_id = int(np.sum(n_cluster[:i])) last_id = int(np.sum(n_cluster[:i + 1])) # Only adding edges to > last_id for j in range(first_id + 1, last_id + 1): for n in list(N.nodes()): if n > last_id: if rng.uniform(0, 1) < pr_between: N.add_edge(j, n) # Generating baseline covariate W w = rng.binomial(n=1, p=pr_w, size=np.sum(n_cluster)) # Generate W for node in N.nodes(): # Adding W to the network node attributes N.nodes[node]['W'] = w[node] # ... via simple indexing # Returning the generated network return N def generate_observed(graph, seed=None): r"""Simulates the exposure and outcome for the uniform random graph (following mechanisms are from Sofrygin & van <NAME> 2017). .. math:: A = \text{Bernoulli}(\text{expit}(-1.2 + 1.5 W + 0.6 W^s)) \\ Y = \text{Bernoulli}(\text{expit}(-2.5 + 0.5 A + 1.5 A^s + 1.5 W + 1.5 W^s)) Parameters ---------- graph : Graph Graph generated by the `uniform_network` function. seed : int, None, optional Random seed to use. Default is None. Returns ------- Network object with node attributes Examples -------- Loading the necessary functions >>> from mossspider.dgm import uniform_network, generate_observed Generating the uniform network >>> G = uniform_network(n=500, degree=[0, 2]) Generating exposure A and outcome Y for network >>> H = generate_observed(graph=G) References ---------- <NAME>, & <NAME>. (2017). Semi-parametric estimation and inference for the mean outcome of the single time-point intervention in a causally connected population. *Journal of Causal Inference*, 5(1). """ rng = np.random.default_rng(seed) n = len(graph.nodes()) w = np.array([d['W'] for n, d in graph.nodes(data=True)]) adj_mat = nx.adjacency_matrix(graph) # Calculating map(W), generating A, and adding to network w_s = fast_exp_map(adj_mat, w, measure='sum') a = rng.binomial(n=1, p=logistic.cdf(-1.2 + 1.5*w + 0.6*w_s), size=n) for node in graph.nodes(): graph.nodes[node]['A'] = a[node] # Calculating map(A), generating Y, and adding to network a_s = fast_exp_map(adj_mat, a, measure='sum') y = rng.binomial(n=1, p=logistic.cdf(-2.5 + 1.5*w + 0.5*a + 1.5*a_s + 1.5*w_s), size=n) for node in graph.nodes(): graph.nodes[node]['Y'] = y[node] return graph def generate_truth(graph, p): """Simulates the true conditional mean outcome for a given network, distribution of W, and policy. The true mean under the policy is simulated as .. math:: A = Bernoulli(p) \\ Y = Bernoulli(expit(-2.5 + 1.5*W + 0.5*A + 1.5*map(A) + 1.5*map(W))) Returns ------- float Examples -------- Loading the necessary functions >>> from mossspider.dgm import uniform_network, generate_truth Generating the uniform network >>> G = uniform_network(n=500, degree=[0, 2]) Calculating truth for a policy via a large number of replicates >>> true_p = [] >>> for i in range(1000): >>> y_mean = generate_truth(graph=G, p=0.5) >>> true_p.append(y_mean) >>> np.mean(true_p) # 'true' value for the stochastic policy To reduce random error, a large number of replicates should be used """ n = len(graph.nodes()) w = np.array([d['W'] for n, d in graph.nodes(data=True)]) # Calculating map(W), generating A, and adding to network a = np.random.binomial(n=1, p=p, size=n) for node in graph.nodes(): graph.nodes[node]['A'] = a[node] # Calculating map(A), generating Y, and adding to network adj_mat = nx.adjacency_matrix(graph) w_s = fast_exp_map(adj_mat, w, measure='sum') a_s = fast_exp_map(adj_mat, a, measure='sum') y = np.random.binomial(n=1, p=logistic.cdf(-2.5 + 1.5*w + 0.5*a + 1.5*a_s + 1.5*w_s), size=n) return np.mean(y)
[ "numpy.mean", "networkx.relabel_nodes", "mossspider.estimators.utils.fast_exp_map", "numpy.random.default_rng", "networkx.adjacency_matrix", "networkx.selfloop_edges", "scipy.stats.logistic.cdf", "networkx.Graph", "numpy.sum", "networkx.configuration_model", "numpy.random.binomial" ]
[((1085, 1112), 'numpy.random.default_rng', 'np.random.default_rng', (['seed'], {}), '(seed)\n', (1106, 1112), True, 'import numpy as np\n'), ((2689, 2735), 'networkx.configuration_model', 'nx.configuration_model', (['degree_dist'], {'seed': 'seed'}), '(degree_dist, seed=seed)\n', (2711, 2735), True, 'import networkx as nx\n'), ((2888, 2899), 'networkx.Graph', 'nx.Graph', (['G'], {}), '(G)\n', (2896, 2899), True, 'import networkx as nx\n'), ((5404, 5431), 'numpy.random.default_rng', 'np.random.default_rng', (['seed'], {}), '(seed)\n', (5425, 5431), True, 'import numpy as np\n'), ((5440, 5450), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (5448, 5450), True, 'import networkx as nx\n'), ((8232, 8259), 'numpy.random.default_rng', 'np.random.default_rng', (['seed'], {}), '(seed)\n', (8253, 8259), True, 'import numpy as np\n'), ((8364, 8390), 'networkx.adjacency_matrix', 'nx.adjacency_matrix', (['graph'], {}), '(graph)\n', (8383, 8390), True, 'import networkx as nx\n'), ((8464, 8503), 'mossspider.estimators.utils.fast_exp_map', 'fast_exp_map', (['adj_mat', 'w'], {'measure': '"""sum"""'}), "(adj_mat, w, measure='sum')\n", (8476, 8503), False, 'from mossspider.estimators.utils import fast_exp_map\n'), ((8769, 8808), 'mossspider.estimators.utils.fast_exp_map', 'fast_exp_map', (['adj_mat', 'a'], {'measure': '"""sum"""'}), "(adj_mat, a, measure='sum')\n", (8781, 8808), False, 'from mossspider.estimators.utils import fast_exp_map\n'), ((10111, 10147), 'numpy.random.binomial', 'np.random.binomial', ([], {'n': '(1)', 'p': 'p', 'size': 'n'}), '(n=1, p=p, size=n)\n', (10129, 10147), True, 'import numpy as np\n'), ((10297, 10323), 'networkx.adjacency_matrix', 'nx.adjacency_matrix', (['graph'], {}), '(graph)\n', (10316, 10323), True, 'import networkx as nx\n'), ((10334, 10373), 'mossspider.estimators.utils.fast_exp_map', 'fast_exp_map', (['adj_mat', 'w'], {'measure': '"""sum"""'}), "(adj_mat, w, measure='sum')\n", (10346, 10373), False, 'from mossspider.estimators.utils import fast_exp_map\n'), ((10430, 10469), 'mossspider.estimators.utils.fast_exp_map', 'fast_exp_map', (['adj_mat', 'a'], {'measure': '"""sum"""'}), "(adj_mat, a, measure='sum')\n", (10442, 10469), False, 'from mossspider.estimators.utils import fast_exp_map\n'), ((10625, 10635), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (10632, 10635), True, 'import numpy as np\n'), ((2536, 2555), 'numpy.sum', 'np.sum', (['degree_dist'], {}), '(degree_dist)\n', (2542, 2555), True, 'import numpy as np\n'), ((3035, 3055), 'networkx.selfloop_edges', 'nx.selfloop_edges', (['G'], {}), '(G)\n', (3052, 3055), True, 'import networkx as nx\n'), ((6072, 6100), 'networkx.relabel_nodes', 'nx.relabel_nodes', (['G', 'mapping'], {}), '(G, mapping)\n', (6088, 6100), True, 'import networkx as nx\n'), ((5938, 5959), 'numpy.sum', 'np.sum', (['n_cluster[:i]'], {}), '(n_cluster[:i])\n', (5944, 5959), True, 'import numpy as np\n'), ((6380, 6401), 'numpy.sum', 'np.sum', (['n_cluster[:i]'], {}), '(n_cluster[:i])\n', (6386, 6401), True, 'import numpy as np\n'), ((6425, 6450), 'numpy.sum', 'np.sum', (['n_cluster[:i + 1]'], {}), '(n_cluster[:i + 1])\n', (6431, 6450), True, 'import numpy as np\n'), ((6789, 6806), 'numpy.sum', 'np.sum', (['n_cluster'], {}), '(n_cluster)\n', (6795, 6806), True, 'import numpy as np\n'), ((8578, 8618), 'scipy.stats.logistic.cdf', 'logistic.cdf', (['(-1.2 + 1.5 * w + 0.6 * w_s)'], {}), '(-1.2 + 1.5 * w + 0.6 * w_s)\n', (8590, 8618), False, 'from scipy.stats import logistic\n'), ((8883, 8945), 'scipy.stats.logistic.cdf', 'logistic.cdf', (['(-2.5 + 1.5 * w + 0.5 * a + 1.5 * a_s + 1.5 * w_s)'], {}), '(-2.5 + 1.5 * w + 0.5 * a + 1.5 * a_s + 1.5 * w_s)\n', (8895, 8945), False, 'from scipy.stats import logistic\n'), ((10550, 10612), 'scipy.stats.logistic.cdf', 'logistic.cdf', (['(-2.5 + 1.5 * w + 0.5 * a + 1.5 * a_s + 1.5 * w_s)'], {}), '(-2.5 + 1.5 * w + 0.5 * a + 1.5 * a_s + 1.5 * w_s)\n', (10562, 10612), False, 'from scipy.stats import logistic\n')]
# -*- coding: utf-8 -*- """turtles.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1Wl6WD8ntb-XqJEb1m4CfYfHvWXR-99ok """ import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from IPython.display import HTML import matplotlib import random matplotlib.rcParams["animation.embed_limit"] = 75 N = 4 R = 30 v = 2 vx = 0.03 frames = 1500 dt = 1 class finish: finished = False real_time = frames fig, ax = plt.subplots() ax = plt.axis([-40, 40, -40, 40]) tracks = [] dots = [] curr_coord = [ [R * np.cos((2 * np.pi * i) / N), R * np.sin((2 * np.pi * i) / N)] for i in range(N) ] rand_coord = [ [random.random()*R, random.random()*R] for i in range(N) ] curr_coord1 = [list(i) for i in curr_coord] #curr_coord = rand_coord #curr_coord1 = [list(i) for i in rand_coord] for x, y in curr_coord: (dot,) = plt.plot([x], [y], "o") dots.append(dot) tracks.append([x]) tracks.append([y]) for i in range(frames): x,y = 0, 0 for k in range(N): if k != N - 1: x = curr_coord1[k + 1][0] - curr_coord1[k][0] y = curr_coord1[k + 1][1] - curr_coord1[k][1] else: x = curr_coord1[0][0] - curr_coord1[k][0] y = curr_coord1[0][1] - curr_coord1[k][1] norm = np.linalg.norm([x, y]) curr_coord1[k][0] += x / norm * vx * dt curr_coord1[k][1] += y / norm * vx * dt tracks[2 * k].append(curr_coord1[k][0]) tracks[2 * k + 1].append(curr_coord1[k][1]) for i in range(N): plt.plot(tracks[2 * i], tracks[2 * i + 1]) def animate(i): if i % 100 == 0: print("{}% prepared".format(1.*i/frames)) for k, dot in zip(range(N), dots): curr_coord[k][0] = tracks[2 * k][i] curr_coord[k][1] = tracks[2 * k + 1][i] dot.set_data(curr_coord[k][0], curr_coord[k][1]) if round(curr_coord[0][0],1) == round(curr_coord[1][0],1) and round(curr_coord[0][1],1) == round(curr_coord[1][1],1) and not finish.finished: finish.finished = True finish.real_time = i return dots myAnimation = animation.FuncAnimation( fig, animate, frames=frames, blit=True, repeat=False ) HTML(myAnimation.to_jshtml(embed_frames=frames)) print('real_time = ',finish.real_time) theor_time = R/(vx*np.sin(np.pi/N)) print('theor_time = ',theor_time) import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from IPython.display import HTML import matplotlib import random matplotlib.rcParams["animation.embed_limit"] = 75 N = 6 R = 30 v = 2 vx = 0.03 frames = 2500 dt = 1 class finish: finished = False real_time = frames fig, ax = plt.subplots() ax = plt.axis([-40, 40, -40, 40]) tracks = [] dots = [] curr_coord = [ [R * np.cos((2 * np.pi * i) / N), R * np.sin((2 * np.pi * i) / N)] for i in range(N) ] rand_coord = [ [random.random()*R, random.random()*R] for i in range(N) ] curr_coord1 = [list(i) for i in curr_coord] #curr_coord = rand_coord #curr_coord1 = [list(i) for i in rand_coord] for x, y in curr_coord: (dot,) = plt.plot([x], [y], "o") dots.append(dot) tracks.append([x]) tracks.append([y]) for i in range(frames): x,y = 0, 0 for k in range(N): if k != N - 1: x = curr_coord1[k + 1][0] - curr_coord1[k][0] y = curr_coord1[k + 1][1] - curr_coord1[k][1] else: x = curr_coord1[0][0] - curr_coord1[k][0] y = curr_coord1[0][1] - curr_coord1[k][1] norm = np.linalg.norm([x, y]) curr_coord1[k][0] += x / norm * vx * dt curr_coord1[k][1] += y / norm * vx * dt tracks[2 * k].append(curr_coord1[k][0]) tracks[2 * k + 1].append(curr_coord1[k][1]) for i in range(N): plt.plot(tracks[2 * i], tracks[2 * i + 1]) def animate(i): if i % 100 == 0: print("{}% prepared".format(1.*i/frames)) for k, dot in zip(range(N), dots): curr_coord[k][0] = tracks[2 * k][i] curr_coord[k][1] = tracks[2 * k + 1][i] dot.set_data(curr_coord[k][0], curr_coord[k][1]) if round(curr_coord[0][0],1) == round(curr_coord[1][0],1) and round(curr_coord[0][1],1) == round(curr_coord[1][1],1) and not finish.finished: finish.finished = True finish.real_time = i return dots myAnimation = animation.FuncAnimation( fig, animate, frames=frames, blit=True, repeat=False ) HTML(myAnimation.to_jshtml(embed_frames=frames)) print('real_time = ',finish.real_time) theor_time = R/(vx*np.sin(np.pi/N)) print('theor_time = ',theor_time)
[ "matplotlib.animation.FuncAnimation", "matplotlib.pyplot.plot", "numpy.cos", "numpy.linalg.norm", "numpy.sin", "matplotlib.pyplot.axis", "random.random", "matplotlib.pyplot.subplots" ]
[((524, 538), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (536, 538), True, 'import matplotlib.pyplot as plt\n'), ((544, 572), 'matplotlib.pyplot.axis', 'plt.axis', (['[-40, 40, -40, 40]'], {}), '([-40, 40, -40, 40])\n', (552, 572), True, 'import matplotlib.pyplot as plt\n'), ((2162, 2239), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['fig', 'animate'], {'frames': 'frames', 'blit': '(True)', 'repeat': '(False)'}), '(fig, animate, frames=frames, blit=True, repeat=False)\n', (2185, 2239), True, 'import matplotlib.animation as animation\n'), ((2736, 2750), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2748, 2750), True, 'import matplotlib.pyplot as plt\n'), ((2756, 2784), 'matplotlib.pyplot.axis', 'plt.axis', (['[-40, 40, -40, 40]'], {}), '([-40, 40, -40, 40])\n', (2764, 2784), True, 'import matplotlib.pyplot as plt\n'), ((4374, 4451), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['fig', 'animate'], {'frames': 'frames', 'blit': '(True)', 'repeat': '(False)'}), '(fig, animate, frames=frames, blit=True, repeat=False)\n', (4397, 4451), True, 'import matplotlib.animation as animation\n'), ((934, 957), 'matplotlib.pyplot.plot', 'plt.plot', (['[x]', '[y]', '"""o"""'], {}), "([x], [y], 'o')\n", (942, 957), True, 'import matplotlib.pyplot as plt\n'), ((1607, 1649), 'matplotlib.pyplot.plot', 'plt.plot', (['tracks[2 * i]', 'tracks[2 * i + 1]'], {}), '(tracks[2 * i], tracks[2 * i + 1])\n', (1615, 1649), True, 'import matplotlib.pyplot as plt\n'), ((3146, 3169), 'matplotlib.pyplot.plot', 'plt.plot', (['[x]', '[y]', '"""o"""'], {}), "([x], [y], 'o')\n", (3154, 3169), True, 'import matplotlib.pyplot as plt\n'), ((3819, 3861), 'matplotlib.pyplot.plot', 'plt.plot', (['tracks[2 * i]', 'tracks[2 * i + 1]'], {}), '(tracks[2 * i], tracks[2 * i + 1])\n', (3827, 3861), True, 'import matplotlib.pyplot as plt\n'), ((1364, 1386), 'numpy.linalg.norm', 'np.linalg.norm', (['[x, y]'], {}), '([x, y])\n', (1378, 1386), True, 'import numpy as np\n'), ((2355, 2372), 'numpy.sin', 'np.sin', (['(np.pi / N)'], {}), '(np.pi / N)\n', (2361, 2372), True, 'import numpy as np\n'), ((3576, 3598), 'numpy.linalg.norm', 'np.linalg.norm', (['[x, y]'], {}), '([x, y])\n', (3590, 3598), True, 'import numpy as np\n'), ((4567, 4584), 'numpy.sin', 'np.sin', (['(np.pi / N)'], {}), '(np.pi / N)\n', (4573, 4584), True, 'import numpy as np\n'), ((619, 644), 'numpy.cos', 'np.cos', (['(2 * np.pi * i / N)'], {}), '(2 * np.pi * i / N)\n', (625, 644), True, 'import numpy as np\n'), ((652, 677), 'numpy.sin', 'np.sin', (['(2 * np.pi * i / N)'], {}), '(2 * np.pi * i / N)\n', (658, 677), True, 'import numpy as np\n'), ((722, 737), 'random.random', 'random.random', ([], {}), '()\n', (735, 737), False, 'import random\n'), ((741, 756), 'random.random', 'random.random', ([], {}), '()\n', (754, 756), False, 'import random\n'), ((2831, 2856), 'numpy.cos', 'np.cos', (['(2 * np.pi * i / N)'], {}), '(2 * np.pi * i / N)\n', (2837, 2856), True, 'import numpy as np\n'), ((2864, 2889), 'numpy.sin', 'np.sin', (['(2 * np.pi * i / N)'], {}), '(2 * np.pi * i / N)\n', (2870, 2889), True, 'import numpy as np\n'), ((2934, 2949), 'random.random', 'random.random', ([], {}), '()\n', (2947, 2949), False, 'import random\n'), ((2953, 2968), 'random.random', 'random.random', ([], {}), '()\n', (2966, 2968), False, 'import random\n')]
import numpy as np import matplotlib.pyplot as plt from pyad.nn import NeuralNet from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn import preprocessing np.random.seed(0) X, y = load_boston(return_X_y=True) X_scaled = preprocessing.scale(X) y_scaled = preprocessing.scale(y) X_train, X_test, y_train, y_test = train_test_split( X_scaled, y_scaled, test_size=0.2, random_state=0 ) nn = NeuralNet(loss_fn='mse') nn.add_layer(X_train.shape[1], 20, activation='linear') nn.add_layer(20, 20, activation='relu') nn.add_layer(20, 1, activation='linear') print('Pre-train loss on train data:', nn.score(X_train, y_train).value) print('Pre-train loss on test data:', nn.score(X_test, y_test).value) epochs = [0] train_loss = [nn.score(X_train, y_train).value] test_loss = [nn.score(X_test, y_test).value] for i in range(100): nn.train( X_train, y_train, X_test, y_test, batch_size=20, epochs=1, learning_rate=1e-1, verbose=False ) epochs.append(i) train_loss.append(nn.score(X_train, y_train).value) test_loss.append(nn.score(X_test, y_test).value) if (i + 1) % 10 == 0: print(f'{i + 1}/100 loops completed') plt.plot(epochs, train_loss) plt.plot(epochs, test_loss) plt.title('Loss over time') plt.legend(['Train', 'Test'], loc='upper left') plt.xlabel('Epochs') plt.ylabel('Loss (mean squared error)') print('\nFinal loss on train data:', nn.score(X_train, y_train).value) print('Final loss on test data:', nn.score(X_test, y_test).value) def compute_r2(x, y): predictions = nn.predict(x) tss = np.sum((y - np.mean(y)) ** 2) ess = np.sum((y - predictions) ** 2) return 1 - ess/tss print('\nFinal R^2 on train data:', compute_r2(X_train, y_train)) print('Final R^2 on test data:', compute_r2(X_test, y_test)) plt.show()
[ "numpy.mean", "matplotlib.pyplot.ylabel", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.legend", "matplotlib.pyplot.xlabel", "sklearn.datasets.load_boston", "matplotlib.pyplot.plot", "pyad.nn.NeuralNet", "numpy.sum", "numpy.random.seed", "matplotlib.pyplot.title", "sklearn.pre...
[((211, 228), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (225, 228), True, 'import numpy as np\n'), ((237, 265), 'sklearn.datasets.load_boston', 'load_boston', ([], {'return_X_y': '(True)'}), '(return_X_y=True)\n', (248, 265), False, 'from sklearn.datasets import load_boston\n'), ((277, 299), 'sklearn.preprocessing.scale', 'preprocessing.scale', (['X'], {}), '(X)\n', (296, 299), False, 'from sklearn import preprocessing\n'), ((311, 333), 'sklearn.preprocessing.scale', 'preprocessing.scale', (['y'], {}), '(y)\n', (330, 333), False, 'from sklearn import preprocessing\n'), ((370, 437), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X_scaled', 'y_scaled'], {'test_size': '(0.2)', 'random_state': '(0)'}), '(X_scaled, y_scaled, test_size=0.2, random_state=0)\n', (386, 437), False, 'from sklearn.model_selection import train_test_split\n'), ((451, 475), 'pyad.nn.NeuralNet', 'NeuralNet', ([], {'loss_fn': '"""mse"""'}), "(loss_fn='mse')\n", (460, 475), False, 'from pyad.nn import NeuralNet\n'), ((1220, 1248), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'train_loss'], {}), '(epochs, train_loss)\n', (1228, 1248), True, 'import matplotlib.pyplot as plt\n'), ((1249, 1276), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'test_loss'], {}), '(epochs, test_loss)\n', (1257, 1276), True, 'import matplotlib.pyplot as plt\n'), ((1278, 1305), 'matplotlib.pyplot.title', 'plt.title', (['"""Loss over time"""'], {}), "('Loss over time')\n", (1287, 1305), True, 'import matplotlib.pyplot as plt\n'), ((1306, 1353), 'matplotlib.pyplot.legend', 'plt.legend', (["['Train', 'Test']"], {'loc': '"""upper left"""'}), "(['Train', 'Test'], loc='upper left')\n", (1316, 1353), True, 'import matplotlib.pyplot as plt\n'), ((1354, 1374), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (1364, 1374), True, 'import matplotlib.pyplot as plt\n'), ((1375, 1414), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss (mean squared error)"""'], {}), "('Loss (mean squared error)')\n", (1385, 1414), True, 'import matplotlib.pyplot as plt\n'), ((1842, 1852), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1850, 1852), True, 'import matplotlib.pyplot as plt\n'), ((1659, 1689), 'numpy.sum', 'np.sum', (['((y - predictions) ** 2)'], {}), '((y - predictions) ** 2)\n', (1665, 1689), True, 'import numpy as np\n'), ((1631, 1641), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (1638, 1641), True, 'import numpy as np\n')]
import numpy as np import unittest from partitura import EXAMPLE_MUSICXML from partitura import load_musicxml from partitura.musicanalysis import estimate_spelling def compare_spelling(spelling, notes): comparisons = np.zeros((len(spelling), 3)) for i, (n, s) in enumerate(zip(notes, spelling)): comparisons[i, 0] = int(n.step == s["step"]) if n.alter is None and s["alter"] == 0: comparisons[i, 1] = 1 else: comparisons[i, 1] = int(n.alter == s["alter"]) comparisons[i, 2] = int(n.octave == s["octave"]) return comparisons class TestKeyEstimation(unittest.TestCase): """ Test key estimation """ score = load_musicxml(EXAMPLE_MUSICXML) def test_part(self): spelling = estimate_spelling(self.score) comparisons = compare_spelling(spelling, self.score.notes) self.assertTrue(np.all(comparisons), "Incorrect spelling") def test_note_array(self): spelling = estimate_spelling(self.score.note_array) comparisons = compare_spelling(spelling, self.score.notes) self.assertTrue(np.all(comparisons), "Incorrect spelling")
[ "partitura.load_musicxml", "numpy.all", "partitura.musicanalysis.estimate_spelling" ]
[((694, 725), 'partitura.load_musicxml', 'load_musicxml', (['EXAMPLE_MUSICXML'], {}), '(EXAMPLE_MUSICXML)\n', (707, 725), False, 'from partitura import load_musicxml\n'), ((771, 800), 'partitura.musicanalysis.estimate_spelling', 'estimate_spelling', (['self.score'], {}), '(self.score)\n', (788, 800), False, 'from partitura.musicanalysis import estimate_spelling\n'), ((986, 1026), 'partitura.musicanalysis.estimate_spelling', 'estimate_spelling', (['self.score.note_array'], {}), '(self.score.note_array)\n', (1003, 1026), False, 'from partitura.musicanalysis import estimate_spelling\n'), ((892, 911), 'numpy.all', 'np.all', (['comparisons'], {}), '(comparisons)\n', (898, 911), True, 'import numpy as np\n'), ((1118, 1137), 'numpy.all', 'np.all', (['comparisons'], {}), '(comparisons)\n', (1124, 1137), True, 'import numpy as np\n')]
from argparse import ArgumentParser from operator import itemgetter import matplotlib.pyplot as plt import pandas as pd import numpy as np import sys from itertools import combinations from scaffold import Longreads parser = ArgumentParser() parser.add_argument("inputfiles", help="Input Files in Error-Rate or PAF format", nargs="+") parser.add_argument("summaryfile", help="Contig distance summary file") parser.add_argument("linename", help="Name of cell line") parser.add_argument("--blacklistfile", help="File containing long read ids where certain contig mappings should be ignored.") parser.add_argument("--include_ambigious", help="Include ambigious contigs", action="store_true", default=False) args = parser.parse_args() reads = {} greads = {} cgreads = [] ambigious_contigs = set() blacklist = {} blacklist_fullread = set() blacklist_contigs = set() if args.blacklistfile: with open(args.blacklistfile) as f: for line in f: sline = line.split() if sline[0] == "contig": blacklist_contigs.add(sline[1]) if sline[1] == "all": blacklist_fullread.add(sline[0]) else: blacklist[sline[0]] = sline[1] lrs = Longreads(args.inputfiles, blacklist, args.linename) lrs.filter_contigcounts(2) lrs.turn_longreads_around() lrs.sort_contigs_in_reads() lrs = lrs.lreads #print(greads) distances = {} # get distances of all neighbouring overlaps ''' for rid in greads: oviter = iter(greads[rid]["overlaps"]) #print(ov) try: ovold = next(oviter) if ovold["contig"].startswith("chr"): continue except StopIteration: continue while True: try: ovnew = next(oviter) if ovnew["contig"].startswith("chr"): continue except StopIteration: break #print("distance between " + ovold["contig"] + " and " + ovnew["contig"] + ": " + str(ovnew["scr"] - ovold["ecr"]- ovold["lc"] + ovold["ecc"] - ovnew["scc"])) if ovnew["contig"] == ovold["contig"]: continue if ovnew["strand"] == ovold["strand"]: distance = ovnew["scr"] - ovold["ecr"]- (ovold["lc"] - ovold["ecc"]) - ovnew["scc"] + 1 else: continue if int(ovold["contig"].rstrip(args.linename)) < int(ovnew["contig"].rstrip(args.linename)): cstring = ovold["contig"] + "_" + ovnew["contig"] else: cstring = ovnew["contig"] + "_" + ovold["contig"] if cstring in distances: distances[cstring].append(distance) else: distances[cstring] = [distance] ovold = ovnew ''' # get distances of all overlaps for rid in lrs: for item in combinations(lrs[rid]['maps'], 2): ovold, ovnew = item if ovnew["name"].startswith("chr") or ovold["name"].startswith("chr"): continue if ovnew["name"] in ambigious_contigs or ovold["name"] in ambigious_contigs: continue if "_" in ovnew["name"] or "_" in ovold["name"]: continue if ovnew["name"] == ovold["name"]: continue if ovnew["strand"] == 1 or ovold["strand"] == 1: continue distance = ovnew["scr"] - ovold["ecr"]- (ovold["lenc"] - ovold["ecc"]) - ovnew["scc"] + 1 cstring = ovold["name"] + "_" + ovnew["name"] if cstring in distances: distances[cstring].append(distance) else: distances[cstring] = [distance] #print(combo) for key, value in distances.items(): #print(str(key) + " " + str(value)) if len(value)>1: #print(str(key) + "\t" + str(value)) pass distances2 = {} with open(args.summaryfile) as f: for line in f: sline = line.split() ctg1 = sline[0].split("_")[0].strip("+").strip("-") ctg2 = sline[0].split("_")[1].strip("+").strip("-") if line.startswith("-"): continue if sline[1] == "NA": continue if float(sline[4]) > 2: continue moddist = float(sline[1]) #if int(ctg1.rstrip(args.linename)) < int(ctg2.rstrip(args.linename)): cstr = ctg1+"_"+ctg2 #else: # cstr = ctg2+"_"+ctg1 if cstr in distances2: if abs(moddist) < abs(distances2[cstr]): distances2[cstr] = moddist else: distances2[cstr] = moddist for name, dist in distances.items(): if name in distances2: dist2 = distances2[name] else: dist2 = "-" name1, name2 = name.split("_") print("\t".join([name1, name2, str(dist), str(dist2)])) df = pd.DataFrame.from_dict([distances, distances2]) #df.rename(index= dc = df.T.rename(columns={0:'longread',1:'shortread'}) dc["longread_mean"] = dc.longread.apply(np.mean) #dc['longread'] = np.mean(dc.longread) dd = dc.dropna() #get interesting differences #print(dd[abs(dd['longread_mean'] - dd['shortread']) > 150]) #print(dd) sthsth = [] for item in dd['longread_mean']: sthsth.append(item < 0) for idx, item in enumerate(dd['shortread']): sthsth[idx] = sthsth[idx] or item < 0 #for name in dd[sthsth].index.values: # print(name) #print(dd[dd['longread_mean'] <= -20]) #print(dd.index.values) plt.scatter(dd['longread_mean'], dd['shortread'],s= 6, alpha = 0.7) plt.xlabel("Long Read Distances (mean: " + "{:.3f}".format(np.mean(dd['longread_mean'])) + ")") #plt.xlabel("Long Read Distances") plt.ylabel("Short Read Distances (mean: " + "{:.3f}".format(np.mean(dd['shortread'])) + ")") #plt.ylabel("Short Read Distances") plt.savefig('distances_scatter.pdf')
[ "numpy.mean", "matplotlib.pyplot.savefig", "argparse.ArgumentParser", "pandas.DataFrame.from_dict", "scaffold.Longreads", "itertools.combinations", "matplotlib.pyplot.scatter" ]
[((228, 244), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (242, 244), False, 'from argparse import ArgumentParser\n'), ((1228, 1280), 'scaffold.Longreads', 'Longreads', (['args.inputfiles', 'blacklist', 'args.linename'], {}), '(args.inputfiles, blacklist, args.linename)\n', (1237, 1280), False, 'from scaffold import Longreads\n'), ((4752, 4799), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['[distances, distances2]'], {}), '([distances, distances2])\n', (4774, 4799), True, 'import pandas as pd\n'), ((5362, 5427), 'matplotlib.pyplot.scatter', 'plt.scatter', (["dd['longread_mean']", "dd['shortread']"], {'s': '(6)', 'alpha': '(0.7)'}), "(dd['longread_mean'], dd['shortread'], s=6, alpha=0.7)\n", (5373, 5427), True, 'import matplotlib.pyplot as plt\n'), ((5690, 5726), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""distances_scatter.pdf"""'], {}), "('distances_scatter.pdf')\n", (5701, 5726), True, 'import matplotlib.pyplot as plt\n'), ((2775, 2808), 'itertools.combinations', 'combinations', (["lrs[rid]['maps']", '(2)'], {}), "(lrs[rid]['maps'], 2)\n", (2787, 2808), False, 'from itertools import combinations\n'), ((5489, 5517), 'numpy.mean', 'np.mean', (["dd['longread_mean']"], {}), "(dd['longread_mean'])\n", (5496, 5517), True, 'import numpy as np\n'), ((5621, 5645), 'numpy.mean', 'np.mean', (["dd['shortread']"], {}), "(dd['shortread'])\n", (5628, 5645), True, 'import numpy as np\n')]
from setuptools import Extension, setup from Cython.Build import cythonize import numpy as np include_dirs = [np.get_include()] extensions = [ # cython blas Extension("struntho.utils._cython_blas", ["struntho/utils/_cython_blas.pyx"] # source files of extensiom ), # cython inference Extension("struntho.utils._cython_inference", ["struntho/utils/_cython_inference.pyx"] ), # maxmin spmp multiclass Extension("struntho.inference._maxmin_spmp_multiclass", ["struntho/inference/_maxmin_spmp_multiclass.pyx"], # source files include_dirs=include_dirs ), # sum product for chains Extension("struntho.inference._sum_product_chain", ["struntho/inference/_sum_product_chain.pyx"], # source files include_dirs=include_dirs ), # maxmin spmp multiclass Extension("struntho.inference._maxmin_spmp_sequence", ["struntho/inference/_maxmin_spmp_sequence.pyx"], # source files include_dirs=include_dirs ) ] setup( name="struntho", ext_modules=cythonize(extensions), # ext_modules=extensions, packages=['struntho', 'struntho.learners', 'struntho.inference', 'struntho.models', 'struntho.utils', 'struntho.datasets', 'struntho.tests', 'struntho.tests.test_learners', 'struntho.tests.test_models', 'struntho.tests.test_inference', 'struntho.tests.test_utils'] )
[ "setuptools.Extension", "Cython.Build.cythonize", "numpy.get_include" ]
[((111, 127), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (125, 127), True, 'import numpy as np\n'), ((175, 252), 'setuptools.Extension', 'Extension', (['"""struntho.utils._cython_blas"""', "['struntho/utils/_cython_blas.pyx']"], {}), "('struntho.utils._cython_blas', ['struntho/utils/_cython_blas.pyx'])\n", (184, 252), False, 'from setuptools import Extension, setup\n'), ((343, 435), 'setuptools.Extension', 'Extension', (['"""struntho.utils._cython_inference"""', "['struntho/utils/_cython_inference.pyx']"], {}), "('struntho.utils._cython_inference', [\n 'struntho/utils/_cython_inference.pyx'])\n", (352, 435), False, 'from setuptools import Extension, setup\n'), ((498, 642), 'setuptools.Extension', 'Extension', (['"""struntho.inference._maxmin_spmp_multiclass"""', "['struntho/inference/_maxmin_spmp_multiclass.pyx']"], {'include_dirs': 'include_dirs'}), "('struntho.inference._maxmin_spmp_multiclass', [\n 'struntho/inference/_maxmin_spmp_multiclass.pyx'], include_dirs=\n include_dirs)\n", (507, 642), False, 'from setuptools import Extension, setup\n'), ((735, 864), 'setuptools.Extension', 'Extension', (['"""struntho.inference._sum_product_chain"""', "['struntho/inference/_sum_product_chain.pyx']"], {'include_dirs': 'include_dirs'}), "('struntho.inference._sum_product_chain', [\n 'struntho/inference/_sum_product_chain.pyx'], include_dirs=include_dirs)\n", (744, 864), False, 'from setuptools import Extension, setup\n'), ((954, 1089), 'setuptools.Extension', 'Extension', (['"""struntho.inference._maxmin_spmp_sequence"""', "['struntho/inference/_maxmin_spmp_sequence.pyx']"], {'include_dirs': 'include_dirs'}), "('struntho.inference._maxmin_spmp_sequence', [\n 'struntho/inference/_maxmin_spmp_sequence.pyx'], include_dirs=include_dirs)\n", (963, 1089), False, 'from setuptools import Extension, setup\n'), ((1183, 1204), 'Cython.Build.cythonize', 'cythonize', (['extensions'], {}), '(extensions)\n', (1192, 1204), False, 'from Cython.Build import cythonize\n')]
# -*- coding: utf-8 -*- import numpy as np from sklearn.feature_extraction import image from PIL import Image from sklearn.preprocessing import normalize from sklearn.neural_network import MLPClassifier from sklearn.model_selection import cross_val_score from sklearn import decomposition from sklearn import datasets import csv def lerImagem(prefixo, classe): im = [] if classe: im = Image.open('Class1\Image_1_' + str(prefixo) + '.tif') else: im = Image.open('Class0\Image_0_' + str(prefixo) + '.tif') return im.getdata() def lerImagens(classe, imagensTreino, imagensTeste, targetTreino, targetTeste): for i in range(1, 30): imagensTreino.append(lerImagem(i, classe)) imagensTeste.append(lerImagem(i + 29, classe)) targetTeste.append(classe) targetTreino.append(classe) def lerDados(): imagensTreino = [] imagensTeste = [] targetTreino = [] targetTeste = [] lerImagens(0, imagensTreino, imagensTeste, targetTreino, targetTeste) lerImagens(1, imagensTreino, imagensTeste, targetTreino, targetTeste) imagensTreino = np.array(imagensTreino) imagensTeste = np.array(imagensTeste) targetTreino = np.array(targetTreino) targetTeste = np.array(targetTeste) imagensTreino = imagensTreino.reshape(len(imagensTreino), 400 * 400) imagensTeste = imagensTeste.reshape(len(imagensTeste), 400 * 400) return imagensTreino, imagensTeste, targetTeste, targetTreino def pca(ar, numeroDeComponentes): pca = decomposition.PCA(n_components=numeroDeComponentes) pca.fit(ar) ar = pca.transform(ar) return ar def avaliar(avaliador, imagensTreino, targetTreino, imagensTeste, targetTeste): print("# Solver: " + avaliador) clf = MLPClassifier(solver=avaliador, alpha=1e-5, random_state=1) clf.fit(imagensTreino, targetTreino) predito = clf.predict(imagensTeste) print("# Resultado: " + str(np.mean(predito == targetTeste))) #partial_fit(training_set, training_result, classes=cls) scores = cross_val_score(clf, imagensTeste, targetTeste, cv = 5, verbose = 0, scoring='accuracy') print("# Validacao cruzada: " + str(np.mean(scores))) return np.mean(scores), np.mean(predito == targetTeste) imagensTreino = [] imagensTreinoPCA = [] imagensTeste = [] imagensTestePCA = [] targetTreino = [] targetTeste = [] [imagensTreino, imagensTeste, targetTeste, targetTreino] = lerDados() print("Imagens:") print("\t Treino: " + str(imagensTreino.shape)) print("\t Teste: " + str(imagensTeste.shape)) print("Target:") print("\t Treino: " + str(targetTreino.shape)) print("\t Teste: " + str(targetTeste.shape)) csv_file = open("resultados.csv", 'wb') writer = csv.writer(csv_file) writer.writerow(["PCA", "VC - LBFGS", "Media - LBFGS", "VC - SGD", "Media - SGD", "VC - ADAM", "Media - ADAM"]) for i in range(1, 101): imagensTreinoPCA = pca(imagensTreino, i) imagensTestePCA = pca(imagensTeste, i) print("\n###########################################################\n#") print("# Usando PCA com " + str(i) + " componentes.") print("#\n#----------------------------------------------------------\n#") [cross_val_lbfgs, mean_lbfgs] = avaliar("lbfgs", imagensTreinoPCA, targetTreino, imagensTestePCA, targetTeste) print("#\n#----------------------------------------------------------\n#") [cross_val_sgd, mean_sgd] = avaliar("sgd", imagensTreinoPCA, targetTreino, imagensTestePCA, targetTeste) print("#\n#----------------------------------------------------------\n#") [cross_val_adam, mean_adam] = avaliar("adam", imagensTreinoPCA, targetTreino, imagensTestePCA, targetTeste) writer.writerow([i, cross_val_lbfgs, mean_lbfgs, cross_val_sgd, mean_sgd, cross_val_adam, mean_adam]) print("#\n###########################################################\n")
[ "numpy.mean", "sklearn.neural_network.MLPClassifier", "sklearn.decomposition.PCA", "csv.writer", "numpy.array", "sklearn.model_selection.cross_val_score" ]
[((2590, 2610), 'csv.writer', 'csv.writer', (['csv_file'], {}), '(csv_file)\n', (2600, 2610), False, 'import csv\n'), ((1051, 1074), 'numpy.array', 'np.array', (['imagensTreino'], {}), '(imagensTreino)\n', (1059, 1074), True, 'import numpy as np\n'), ((1091, 1113), 'numpy.array', 'np.array', (['imagensTeste'], {}), '(imagensTeste)\n', (1099, 1113), True, 'import numpy as np\n'), ((1130, 1152), 'numpy.array', 'np.array', (['targetTreino'], {}), '(targetTreino)\n', (1138, 1152), True, 'import numpy as np\n'), ((1168, 1189), 'numpy.array', 'np.array', (['targetTeste'], {}), '(targetTeste)\n', (1176, 1189), True, 'import numpy as np\n'), ((1436, 1487), 'sklearn.decomposition.PCA', 'decomposition.PCA', ([], {'n_components': 'numeroDeComponentes'}), '(n_components=numeroDeComponentes)\n', (1453, 1487), False, 'from sklearn import decomposition\n'), ((1658, 1718), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {'solver': 'avaliador', 'alpha': '(1e-05)', 'random_state': '(1)'}), '(solver=avaliador, alpha=1e-05, random_state=1)\n', (1671, 1718), False, 'from sklearn.neural_network import MLPClassifier\n'), ((1930, 2019), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['clf', 'imagensTeste', 'targetTeste'], {'cv': '(5)', 'verbose': '(0)', 'scoring': '"""accuracy"""'}), "(clf, imagensTeste, targetTeste, cv=5, verbose=0, scoring=\n 'accuracy')\n", (1945, 2019), False, 'from sklearn.model_selection import cross_val_score\n'), ((2082, 2097), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (2089, 2097), True, 'import numpy as np\n'), ((2099, 2130), 'numpy.mean', 'np.mean', (['(predito == targetTeste)'], {}), '(predito == targetTeste)\n', (2106, 2130), True, 'import numpy as np\n'), ((1826, 1857), 'numpy.mean', 'np.mean', (['(predito == targetTeste)'], {}), '(predito == targetTeste)\n', (1833, 1857), True, 'import numpy as np\n'), ((2056, 2071), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (2063, 2071), True, 'import numpy as np\n')]
import torch import numpy as np import json from collections import Counter class TranslationDatasetTorch(torch.utils.data.Dataset): def __init__(self, file_name, source_field='src', target_filed='tgt', unk_idx=1, sos_idx=2, eos_idx=3, first_index=4, device='cpu'): super(TranslationDatasetTorch, self).__init__() self.source_field = source_field self.target_filed = target_filed self.unk_idx = unk_idx self.sos_idx = sos_idx self.eos_idx = eos_idx self.device = device src_vocab = Counter() tgt_vocab = Counter() data_tmp = [] with open(file_name) as f: for l in f: obj = json.loads(l) src_vocab += Counter(obj['src']) tgt_vocab += Counter(obj['tgt']) data_tmp.append(obj) self.stoi_src = {w[0]: c for c, w in enumerate( src_vocab.most_common(len(src_vocab)), first_index)} self.stoi_tgt = {w[0]: c for c, w in enumerate( tgt_vocab.most_common(len(tgt_vocab)), first_index)} self.data = [] for obj in data_tmp: src = obj[source_field] tgt = obj[target_filed] src = [sos_idx] + \ [self.stoi_src.get(w, unk_idx) for w in src] + [eos_idx] tgt = [sos_idx] + \ [self.stoi_tgt.get(w, unk_idx) for w in tgt] + [eos_idx] self.data.append([src, tgt]) def __getitem__(self, index): src, tgt = self.data[index] src = torch.from_numpy(np.array(src)).to(self.device) tgt = torch.from_numpy(np.array(tgt)).to(self.device) src_len = torch.from_numpy( np.array(src.size()[0])).unsqueeze(-1).to(self.device) return src, src_len, tgt def __len__(self): return len(self.data) def collate_fn(inputs): src_seqs, src_lens, tgt_seqs = zip(*inputs) src_lens = torch.stack(src_lens) order = torch.argsort(src_lens, dim=0, descending=True).squeeze(-1) max_len_src = max([x.size(0) for x in src_seqs]) max_len_tgt = max([x.size(0) for x in tgt_seqs]) src_seqs = [torch.cat([e, torch.zeros((max_len_src - e.size(0),), dtype=torch.long, device=e.device)]) for e in src_seqs] tgt_seqs = [torch.cat([e, torch.zeros((max_len_tgt - e.size(0),), dtype=torch.long, device=e.device)]) for e in tgt_seqs] src_lens = src_lens[order] src_seqs = torch.stack(src_seqs)[order] tgt_seqs = torch.stack(tgt_seqs)[order] return src_seqs, src_lens, tgt_seqs
[ "json.loads", "torch.stack", "collections.Counter", "numpy.array", "torch.argsort" ]
[((2078, 2099), 'torch.stack', 'torch.stack', (['src_lens'], {}), '(src_lens)\n', (2089, 2099), False, 'import torch\n'), ((690, 699), 'collections.Counter', 'Counter', ([], {}), '()\n', (697, 699), False, 'from collections import Counter\n'), ((720, 729), 'collections.Counter', 'Counter', ([], {}), '()\n', (727, 729), False, 'from collections import Counter\n'), ((2613, 2634), 'torch.stack', 'torch.stack', (['src_seqs'], {}), '(src_seqs)\n', (2624, 2634), False, 'import torch\n'), ((2657, 2678), 'torch.stack', 'torch.stack', (['tgt_seqs'], {}), '(tgt_seqs)\n', (2668, 2678), False, 'import torch\n'), ((2112, 2159), 'torch.argsort', 'torch.argsort', (['src_lens'], {'dim': '(0)', 'descending': '(True)'}), '(src_lens, dim=0, descending=True)\n', (2125, 2159), False, 'import torch\n'), ((834, 847), 'json.loads', 'json.loads', (['l'], {}), '(l)\n', (844, 847), False, 'import json\n'), ((877, 896), 'collections.Counter', 'Counter', (["obj['src']"], {}), "(obj['src'])\n", (884, 896), False, 'from collections import Counter\n'), ((926, 945), 'collections.Counter', 'Counter', (["obj['tgt']"], {}), "(obj['tgt'])\n", (933, 945), False, 'from collections import Counter\n'), ((1706, 1719), 'numpy.array', 'np.array', (['src'], {}), '(src)\n', (1714, 1719), True, 'import numpy as np\n'), ((1768, 1781), 'numpy.array', 'np.array', (['tgt'], {}), '(tgt)\n', (1776, 1781), True, 'import numpy as np\n')]
import sympy from sympy import * import numpy from numpy import * from numpy.linalg import matrix_rank from sympy.parsing.sympy_parser import * from sympy.matrices import * import csv import os import random from random import shuffle def Reduce(eq): for el in ['kPDK1', 'kAkt']: el=parse_expr(el) if(eq.subs(el,0)==0): eq=expand(simplify(eq/el)) return expand(eq) def LCS(s1, s2): m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))] longest, x_longest = 0, 0 for x in xrange(1, 1 + len(s1)): for y in xrange(1, 1 + len(s2)): if s1[x - 1] == s2[y - 1]: m[x][y] = m[x - 1][y - 1] + 1 if m[x][y] > longest: longest = m[x][y] x_longest = x else: m[x][y] = 0 return s1[x_longest - longest: x_longest] def SolveSymbLES(A,b): dim=shape(A)[0] Asave=A[:] Asave=Matrix(dim, dim, Asave) #printmatrix(Asave) #print(b) determinant=Asave.det() if(determinant==0): #print('Determinant of LCL-calculation is zero! Try to specify LCLs yourself!') return([]) result=[] for i in range(dim): A=Matrix(dim,dim,Asave) A.col_del(i) A=A.col_insert(i,b) result.append(simplify(A.det()/determinant)) return(result) def CutStringListatSymbol(liste, symbol): out=[] for el in liste: if(symbol in el): add=el.split(symbol) else: add=[el] out=out+add return(out) def FillwithRanNum(M): dimx=len(M.row(0)) dimy=len(M.col(0)) ranM=zeros(dimy, dimx) parlist=[] ranlist=[] for i in M[:]: if(i!=0): if(str(i)[0]=='-'): parlist.append(str(i)[1:]) else: parlist.append(str(i)) parlist=list(set(parlist)) for symbol in [' - ', ' + ', '*', '/', '(',')']: parlist=CutStringListatSymbol(parlist,symbol) parlist=list(set(parlist)) temp=[] for i in parlist: if(i!=''): if(not is_number(i)): temp.append(i) ranlist.append(random.random()) parlist=temp for i in range(dimy): for j in range(dimx): ranM[i,j]=M[i,j] if(ranM[i,j]!=0): for p in range(len(parlist)): ranM[i,j]=ranM[i,j].subs(parse_expr(parlist[p]),ranlist[p]) return(ranM) def FindLinDep(M, tol=1e-12): ranM=FillwithRanNum(M) Q,R=numpy.linalg.qr(ranM) for i in range(shape(R)[0]): for j in range(shape(R)[1]): if(abs(R[i,j]) < tol): R[i,j]=0.0 LinDepList=[] for i in range(shape(R)[0]): if(R[i][i]==0): LinDepList.append(i) return(LinDepList) def FindLCL(M, X): LCL=[] LinDepList=FindLinDep(M) i=0 counter=0 deleted_rows=[] states=Matrix(X[:]) while(LinDepList!=[]): i=LinDepList[0] testM=FillwithRanNum(M) rowliste=list(numpy.nonzero(testM[:,i])[0]) colliste=[i] for z in range(i): for k in rowliste: for j in range(i): jliste=list(numpy.nonzero(testM[:,j])[0]) if(k in jliste): rowliste=rowliste+jliste colliste=colliste+[j] rowliste=list(set(rowliste)) colliste=list(set(colliste)) rowliste.sort() colliste.sort() colliste.pop() rowlisteTry=rowliste[0:(len(colliste))] vec=SolveSymbLES(M[rowlisteTry,colliste],M[rowlisteTry,i]) shufflecounter=0 while(vec==[] and shufflecounter < 100): shuffle(rowliste) shufflecounter=shufflecounter+1 rowlisteTry=rowliste[0:(len(colliste))] vec=SolveSymbLES(M[rowlisteTry,colliste],M[rowlisteTry,i]) if(shufflecounter==100): print('Problems while finding conserved quantities!') return(0,0) counter=counter+1 try: mat=[states[l] for l in colliste] test=parse_expr('0') for v in range(0,len(vec)): test=test-parse_expr(str(vec[v]))*parse_expr(str(mat[v])) except: return([],0) partStr=str(test)+' + '+str(states[i]) partStr=partStr.split(' + ') partStr2=[] for index in range(len(partStr)): partStr2=partStr2+partStr[index].split('-') partStr=partStr2 if(len(partStr) > 1): CLString=LCS(str(partStr[0]),str(partStr[1])) for ps in range(2,len(partStr)): CLString=LCS(CLString,str(partStr[ps])) else: CLString=str(partStr[0]) if(CLString==''): CLString=str(counter) LCL.append(str(test)+' + '+str(states[i])+' = '+'total'+CLString) M.col_del(i) states.row_del(i) deleted_rows.append(i+counter-1) LinDepList=FindLinDep(M) return(LCL, deleted_rows) def printmatrix(M): lengths=[] for i in range(len(M.row(0))): lengths.append(0) for j in range(len(M.col(0))): lengths[i]=max(lengths[i],len(str(M.col(i)[j]))) string=''.ljust(5) string2=''.ljust(5) for j in range(len(M.row(0))): string=string+(str(j)).ljust(lengths[j]+2) for k in range(lengths[j]+2): string2=string2+('-') print(string) print(string2) for i in range(len(M.col(0))): string=str(i).ljust(4) + '[' for j in range(len(M.row(0))): if(j==len(M.row(0))-1): string=string+str(M.row(i)[j]).ljust(lengths[j]) else: string=string+(str(M.row(i)[j])+', ').ljust(lengths[j]+2) print(string+']') return() def is_number(s): try: float(s) return True except ValueError: return False def checkNegRows(M): NegRows=[] if((M==Matrix(0,0,[])) | (M==Matrix(0,1,[])) | (M==Matrix(1,0,[]))): return(NegRows) else: for i in range(len(M.col(0))): foundPos=False for j in range(len(M.row(i))): if(M[i,j]>0): foundPos=True if(foundPos==False): NegRows.append(i) return(NegRows) def checkPosRows(M): PosRows=[] if((M==Matrix(0,0,[])) | (M==Matrix(0,1,[])) | (M==Matrix(1,0,[]))): return(PosRows) else: for i in range(len(M.col(0))): foundNeg=False for j in range(len(M.row(i))): if(M[i,j]<0): foundNeg=True if(foundNeg==False): PosRows.append(i) return(PosRows) def find_cycle(graph, start, end, path=[]): path = path + [start] if not graph.has_key(start): return None if ((start == end) & (path!=[start])): return path for node in graph[start]: if node==end: return (path+[end]) if node not in path: #print(node) newpath = find_cycle(graph, node, end, path) if newpath: return newpath return None def ChooseOptimalFlux(eq, SM, F, compromise1, compromise2): anzneg=str(eq.args).count('-') anzpos=len(eq.args)-anzneg #print(anzneg) #print(anzpos) #print(eq) eq=expand(eq) if(anzneg==1): for arg in eq.args: counter=0 if((str(arg)[0:2]=='2*') or (str(arg)[0:3]=='-2*')): arg=arg/2 for i in range(len(SM.col(0))): if(SM[i,list(F).index(parse_expr(str(arg).replace('-','')))]!=0): counter=counter+1 #print(counter) if(('-' in str(arg)) & (counter==1)): return(arg) if(anzpos==1): for arg in eq.args: #print(arg) counter=0 if((str(arg)[0:2]=='2*') or (str(arg)[0:3]=='-2*')): arg=arg/2 #printmatrix(SM) #print(F) for i in range(len(SM.col(0))): if(SM[i,list(F).index(parse_expr(str(arg).replace('-','')))]!=0): counter=counter+1 #print(counter) if(('-' not in str(arg)) & (counter==1)): return(arg) if(compromise1): for arg in eq.args: counter=0 #print(arg) for i in range(len(SM.col(0))): if(SM[i,list(F).index(parse_expr(str(arg).replace('-','')))]!=0): counter=counter+1 if(counter==1): return(arg) if(compromise1 & compromise2): return(eq.args[0]) return None def FindNodeToSolve(graph): for el in graph: if(graph[el]==[]): return(el) return(None) def SuggestTrafos(eqOut, UsedVars): out=[] for i in range(len(eqOut)): eq=eqOut[i] #print(eq) if('-' in eq): print('Finding trafo...') foundTrafo=False rs=parse_expr(eq.split(' = ')[1]) if(('1/' in str(rs.args[0])) & (len(rs.args)>=2)): args=(rs.args[-1]).args else: args=rs.args #print(args) anzneg=str(args).count('-') anzpos=len(args)-anzneg #print(anzpos) if(anzneg==1): for arg in args: if('-' in str(arg)): for var in arg.atoms(): if((not is_number(str(var))) & (var not in UsedVars) & (not foundTrafo)): sol=solve(rs, var, simplify=False)[0] foundTrafo=True trafo=parse_expr('('+str(sol)+')/(1+r_'+str(var)+')') trafoVar=var out.append(str(trafoVar)+' = '+str(trafo)) if((anzpos==1) & (not foundTrafo)): for arg in args: if('-' not in str(arg)): for var in arg.atoms(): if((not is_number(str(var))) & (var not in UsedVars) & (not foundTrafo)): sol=solve(rs, var, simplify=False)[0] foundTrafo=True trafo=parse_expr('('+str(sol)+')*(1+r_'+str(var)+')') trafoVar=var out.append(str(trafoVar)+' = '+str(trafo)) if((anzpos > 1) & (anzneg > 1)): negliste=[] posliste=[] posges='' anzmal=0 for arg in args: if('-' in str(arg)): negliste.append(arg) else: posges=posges+str(arg) posliste.append(arg) anzmal=anzmal+str(arg).count('*') if(str(simplify(parse_expr(posges))).count('*')!=anzmal): var=parse_expr(posges.split('*')[0]) if(var not in UsedVars): sol=solve(rs, var)[0] foundTrafo=True trafo=parse_expr('('+str(sol)+')*(1+r_'+str(var)+')') trafoVar=var out.append(str(trafoVar)+' = '+str(trafo)) if(not foundTrafo): print('Alles Mist') else: #print(trafoVar) #print(out[-1]) for j in range(len(eqOut)): if(j >= i): ls,rs=eqOut[j].split(' = ') eqOut[j]=ls+' = '+str(simplify(parse_expr(rs).subs(trafoVar, trafo))) out.append(eqOut[i]) #print(out) return(out) def ODESS(filename, injections=[], forbidden=[], ausgabe="R"): filename=str(filename) file=csv.reader(open(filename), delimiter=',') print('Reading csv-file ...') L=[] nrrow=0 nrcol=0 for row in file: nrrow=nrrow+1 nrcol=len(row) L.append(row) nrspecies=nrcol-2 ##### Remove injections counter=0 for i in range(1,len(L)): if(L[i-counter][1] in injections): L.remove(L[i-counter]) counter=counter+1 ##### Define flux vector F F=[] for i in range(1,len(L)): F.append(L[i][1]) #print(F) F[i-1]=F[i-1].replace('^','**') F[i-1]=parse_expr(F[i-1]) for inj in injections: F[i-1]=F[i-1].subs(parse_expr(inj),0) F=Matrix(F) print(F) ##### Define state vector X X=[] X=L[0][2:] for i in range(len(X)): X[i]=parse_expr(X[i]) X=Matrix(X) ##### Define stoichiometry matrix SM SM=[] for i in range(len(L)-1): SM.append(L[i+1][2:]) for i in range(len(SM)): for j in range(len(SM[0])): if (SM[i][j]==''): SM[i][j]='0' SM[i][j]=parse_expr(SM[i][j]) SM=Matrix(SM) SM=SM.T ##### Read forbidden rates UsedRC=[] for el in forbidden: UsedRC.append(parse_expr(el)) ##### Check for zero fluxes icounter=0 jcounter=0 for i in range(len(F)): if(F[i-icounter]==0): F.row_del(i-icounter) for j in range(len(SM.col(i-icounter))): if(SM[j-jcounter,i-icounter]!=0): #UsedRC.append(X[j-jcounter]) X.row_del(j-jcounter) SM.row_del(j-jcounter) jcounter=jcounter+1 SM.col_del(i-icounter) icounter=icounter+1 print('Removed '+str(icounter)+' zero fluxes!') nrspecies=nrspecies-icounter printmatrix(SM) print(F) print(X) #print(UsedRC) #####Check if some species are zero and remove them from the system zeroStates=[] NegRows=checkNegRows(SM) PosRows=checkPosRows(SM) print(PosRows) print(NegRows) while((NegRows!=[]) | (PosRows!=[])): print(PosRows) print(NegRows) if(NegRows!=[]): row=NegRows[0] zeroStates.append(X[row]) counter=0 for i in range(len(F)): if(F[i-counter].subs(X[row],1)!=F[i-counter]): F.row_del(i-counter) SM.col_del(i-counter) counter=counter+1 X.row_del(row) SM.row_del(row) else: row=PosRows[0] zeroFluxes=[] for j in range(len(SM.row(row))): if(SM.row(row)[j]!=0): zeroFluxes.append(F[j]) for k in zeroFluxes: StateinFlux=[] for state in X: if(k.subs(state,1)!=k): StateinFlux.append(state) if(len(StateinFlux)==1): zeroStates.append(StateinFlux[0]) row=list(X).index(StateinFlux[0]) counter=0 for i in range(len(F)): if(F[i-counter].subs(X[row],1)!=F[i-counter]): if(F[i-counter].subs(X[row],0)==0): F.row_del(i-counter) SM.col_del(i-counter) else: F[i-counter]=F[i-counter].subs(X[row],0) counter=counter+1 #printmatrix(SM) NegRows=checkNegRows(SM) PosRows=checkPosRows(SM) nrspecies=nrspecies-len(zeroStates) if(nrspecies==0): print('All states are zero!') return(0) else: print('These states are zero:') for state in zeroStates: print(state) nrspecies=nrspecies+len(zeroStates) ##### Identify linearities, bilinearities and multilinearities Xsquared=[] for i in range(len(X)): Xsquared.append(X[i]*X[i]) Xsquared=Matrix(Xsquared) BLList=[] MLList=[] for i in range(len(SM*F)): LHS=str(expand((SM*F)[i])) LHS=LHS.replace(' ','') LHS=LHS.replace('-','+') LHS=LHS.replace('**2','tothepowerof2') LHS=LHS.replace('**3','tothepowerof3') exprList=LHS.split('+') for expr in exprList: VarList=expr.split('*') counter=0 factors=[] for j in range(len(X)): anz=0 if(str(X[j]) in VarList): anz=1 factors.append(X[j]) if((str(X[j])+'tothepowerof2') in VarList): anz=2 factors.append(X[j]) factors.append(X[j]) if((str(X[j])+'tothepowerof3') in VarList): anz=3 factors.append(X[j]) factors.append(X[j]) factors.append(X[j]) counter=counter+anz if(counter==2): string='' for l in range(len(factors)): if(l==len(factors)-1): string=string+str(factors[l]) else: string=string+str(factors[l])+'*' if(not(string in BLList)): BLList.append(string) if(counter>2): string='' for l in range(len(factors)): if(l==len(factors)-1): string=string+str(factors[l]) else: string=string+str(factors[l])+'*' if(not(string in MLList)): MLList.append(string) COPlusLIPlusBL=[] for i in range(len(SM*F)): COPlusLIPlusBL.append((SM*F)[i]) for j in range(len(MLList)): ToSubs=expand((SM*F)[i]).coeff(MLList[j]) COPlusLIPlusBL[i]=expand(COPlusLIPlusBL[i]-ToSubs*parse_expr(MLList[j])) COPlusLI=[] for i in range(len(COPlusLIPlusBL)): COPlusLI.append(COPlusLIPlusBL[i]) for j in range(len(BLList)): ToSubs=expand((COPlusLIPlusBL)[i]).coeff(BLList[j]) COPlusLI[i]=expand(COPlusLI[i]-ToSubs*parse_expr(BLList[j])) ##### C*X contains linear terms C=zeros(len(COPlusLI),len(X)) for i in range(len(COPlusLI)): for j in range(len(X)): C[i*len(X)+j]=expand((COPlusLI)[i]).coeff(X[j]) ##### ML contains multilinearities ML=expand(Matrix(SM*F)-Matrix(COPlusLIPlusBL)) ##### BL contains bilinearities BL=expand(Matrix(COPlusLIPlusBL)-Matrix(COPlusLI)) #### CM is coefficient matrix of linearities CM=C #####CMBL gives coefficient matrix of bilinearities CMBL=[] if(BLList!=[]): for i in range(len(BLList)): CVBL=[] for k in range(len(BL)): CVBL.append(BL[k].coeff(BLList[i])) CMBL.append(CVBL) else: CVBL=[] for k in range(len(BL)): CVBL.append(0) CMBL.append(CVBL) CMBL=Matrix(CMBL).T #####CMML gives coefficient matrix of multilinearities #####Summarize multilinearities and bilinearities if(MLList!=[]): CMML=[] for i in range(len(MLList)): CVML=[] for k in range(len(ML)): CVML.append(expand(ML[k]).coeff(MLList[i])) CMML.append(CVML) CMML=Matrix(CMML).T BLList=BLList+MLList CMBL=Matrix(concatenate((CMBL,CMML),axis=1)) for i in range(len(BLList)): BLList[i]=parse_expr(BLList[i]) if(BLList!=[]): CMbig=Matrix(concatenate((CM,CMBL),axis=1)) else: CMbig=Matrix(CM) #### Save ODE equations for testing solutions at the end print('Rank of SM is '+str(SM.rank())) ODE=SM*F #### Find conserved quantities print('Finding conserved quantities ...') #printmatrix(CMbig) #print(X) LCLs, rowsToDel=FindLCL(CMbig.transpose(), X) print(LCLs) #### Define graph structure print('Define graph structure ...\n') graph={} for i in range(len(SM*F)): liste=[] for j in range(len(X)): if((SM*F)[i]!=((SM*F)[i]).subs(X[j],1)): if(j==i): In=((SM*F)[i]).subs(X[j],0) Out=simplify(((SM*F)[i]-In)/X[j]) if(Out!=Out.subs(X[j],1)): liste.append(str(X[j])) else: liste.append(str(X[j])) graph[str(X[i])]=liste #### Remove cycles step by step gesnew=0 noCycle=False #UsedRC=[] UsedStates=[] eqOut=[] DependentRates=[] DependentOn=[] counter=0 while(not noCycle): i=0 changeposneg=False counter=counter+1 foundCycle=False print(graph) while((not foundCycle) & (not noCycle)): cycle=find_cycle(graph, str(X[i]), str(X[i])) if cycle is None: i=i+1 if(i==len(X)): noCycle=True print('There is no cycle in the system!\n') else: print('Removing cycle '+str(counter)) foundCycle=True CycleCanBeDoneByCL=False if(not noCycle): print(cycle) for node in cycle: for LCL in LCLs: if(not CycleCanBeDoneByCL): ls=parse_expr(LCL.split(' = ')[0]) if(ls.subs(parse_expr(node),1)!=ls): CycleCanBeDoneByCL=True LCLToRemove=LCL UsedStates.append(parse_expr(node)) nodeToRep=node print(' '+str(nodeToRep)+' --> '+'Done by CL') if(CycleCanBeDoneByCL): LCLs.remove(LCLToRemove) indexToRep=list(X).index(parse_expr(nodeToRep)) eqOut.append(str(nodeToRep)+' = '+str(nodeToRep)) X.row_del(indexToRep) SM.row_del(indexToRep) if((not noCycle) & (not CycleCanBeDoneByCL)): compromise=False compromise2=False foundOptNodeAndFlux=False for node in cycle: if((not foundOptNodeAndFlux) & (parse_expr(node) in list(X))): nodeToRep=node eq=Reduce((SM*F)[list(X).index(parse_expr(nodeToRep))]) FluxToTake=ChooseOptimalFlux(eq,SM,F, compromise1=False, compromise2=False) if(not FluxToTake is None): foundOptNodeAndFlux=True #print(foundOptNodeAndFlux) if(not foundOptNodeAndFlux): eq=Reduce(expand((SM*F)[i])) l0=len(str(eq)) nodeToRep=str(X[i]) for node in cycle: l=len(str((SM*F)[list(X).index(parse_expr(node))])) if(l<l0): eq=Reduce((SM*F)[list(X).index(parse_expr(node))]) nodeToRep=node print(' Do compromise for: '+nodeToRep) print(eq) compromise=True trafoList=[] negs=parse_expr('0') poss=parse_expr('0') anzneg=0 anzpos=0 for arg in eq.args: if('-' in str(arg)): anzneg=anzneg+1 negs=negs-arg else: anzpos=anzpos+1 poss=poss+arg if(anzpos == 1 and anzneg == 1): trafoList.append(str(poss)+'='+str(negs)) else: if(anzneg==1): nenner=1 gesnew=gesnew+(anzneg-1) for j in range(anzneg): if(j>0): nenner=nenner+parse_expr('r_'+nodeToRep+'_'+str(j)) trafoList.append(str(negs)+'=('+str(poss)+')*1/('+str(nenner)+')') else: if(anzpos==1): nenner=1 gesnew=gesnew+(anzpos-1) for j in range(anzpos): if(j>0): nenner=nenner+parse_expr('r_'+nodeToRep+'_'+str(j)) trafoList.append(str(poss)+'=('+str(negs)+')*1/('+str(nenner)+')') else: if((anzpos > anzneg) & (not changeposneg)): nenner=1 gesnew=gesnew+(anzneg-1) for j in range(anzneg): if(j>0): nenner=nenner+parse_expr('r_'+nodeToRep+'_'+str(j)) for j in range(anzneg): if(j==0): trafoList.append(str(negs.args[j])+'=('+str(poss)+')*1/('+str(nenner)+')') else: trafoList.append(str(negs.args[j])+'=('+str(poss)+')*'+'r_'+nodeToRep+'_'+str(j)+'/('+str(nenner)+')') else: nenner=1 #print(poss) #print(poss.args) gesnew=gesnew+(anzpos-1) for j in range(anzpos): if(j>0): nenner=nenner+parse_expr('r_'+nodeToRep+'_'+str(j)) for j in range(anzpos): if(j==0): trafoList.append(str(poss.args[j])+'=('+str(negs)+')*1/('+str(nenner)+')') else: trafoList.append(str(poss.args[j])+'=('+str(negs)+')*'+'r_'+nodeToRep+'_'+str(j)+'/('+str(nenner)+')') tempcounter=0 #print(trafoList) for trafo in trafoList: #print(trafo) lstrafo,rstrafo=trafo.split('=') lstrafo=parse_expr(lstrafo) rstrafo=parse_expr(rstrafo) foundRateConst=False for var in list(lstrafo.atoms()): if((var not in X) & (var not in UsedStates) & (var not in UsedRC) & (not is_number(str(var))) & (not foundRateConst)): RC=var UsedRC.append(RC) foundRateConst=True if(foundRateConst): rest=lstrafo/RC sol=rstrafo/rest eqOut.append(str(RC)+' = '+str(sol)) DependentRates.append(RC) DependentOn.append(list(sol.atoms())) tempcounter=tempcounter+1 else: compromise2=True if(compromise2): print('Did not find appropriate transformation!') for temp in range(tempcounter): eqOut.pop() DependentRates.pop() DependentOn.pop() UsedRC.pop() if(not compromise2): indexToRep=list(X).index(parse_expr(nodeToRep)) X.row_del(indexToRep) SM.row_del(indexToRep) for temp in range(tempcounter): eq=eqOut[-(temp+1)] RC=parse_expr(eq.split('=')[0]) sol=parse_expr(eq.split('=')[1]) for f in range(len(F)): F[f]=F[f].subs(RC, sol) print(' '+str(RC)+' --> '+str(sol)) leaveCompromiseLoop=False lcycle=len(cycle) cyclecounter=0 while((leaveCompromiseLoop==False) & (cyclecounter < lcycle) & compromise2): nodeToRep=cycle[cyclecounter] eq=expand((SM*F)[list(X).index(parse_expr(nodeToRep))]) #print(eq) cyclecounter=cyclecounter+1 #print(cycle) #print(nodeToRep) print(cyclecounter) print(' Do compromise 2') compromise2=False trafoList=[] negs=parse_expr('0') poss=parse_expr('0') anzneg=0 anzpos=0 for arg in eq.args: if('-' in str(arg)): anzneg=anzneg+1 negs=negs-arg else: anzpos=anzpos+1 poss=poss+arg if((anzpos > anzneg) & (not changeposneg)): nenner=1 gesnew=gesnew+(anzneg-1) for j in range(anzneg): if(j>0): nenner=nenner+parse_expr('r_'+nodeToRep+'_'+str(j)) for j in range(anzneg): if(j==0): trafoList.append(str(negs.args[j])+'=('+str(poss)+')*1/('+str(nenner)+')') else: trafoList.append(str(negs.args[j])+'=('+str(poss)+')*'+'r_'+nodeToRep+'_'+str(j)+'/('+str(nenner)+')') else: nenner=1 gesnew=gesnew+(anzpos-1) for j in range(anzpos): if(j>0): nenner=nenner+parse_expr('r_'+nodeToRep+'_'+str(j)) for j in range(anzpos): if(j==0): trafoList.append(str(poss.args[j])+'=('+str(negs)+')*1/('+str(nenner)+')') else: trafoList.append(str(poss.args[j])+'=('+str(negs)+')*'+'r_'+nodeToRep+'_'+str(j)+'/('+str(nenner)+')') tempcounter=0 for trafo in trafoList: #print(trafo) lstrafo,rstrafo=trafo.split('=') lstrafo=parse_expr(lstrafo) rstrafo=parse_expr(rstrafo) foundRateConst=False for var in list(lstrafo.atoms()): if((var not in X) & (var not in UsedStates) & (var not in UsedRC) & (not is_number(str(var))) & (not foundRateConst)): RC=var UsedRC.append(RC) foundRateConst=True if(foundRateConst): rest=lstrafo/RC sol=rstrafo/rest eqOut.append(str(RC)+' = '+str(sol)) DependentRates.append(RC) DependentOn.append(list(sol.atoms())) tempcounter=tempcounter+1 else: compromise2=True if(compromise2): #print(eq) #print(nodeToRep) print('Did not find appropriate transformation!') for temp in range(tempcounter): eqOut.pop() DependentRates.pop() DependentOn.pop() UsedRC.pop() if(not compromise2): leaveCompromiseLoop=True indexToRep=list(X).index(parse_expr(nodeToRep)) X.row_del(indexToRep) SM.row_del(indexToRep) for temp in range(tempcounter): eq=eqOut[-(temp+1)] RC=parse_expr(eq.split('=')[0]) sol=parse_expr(eq.split('=')[1]) for f in range(len(F)): F[f]=F[f].subs(RC, sol) print('\t'+str(RC)+' --> '+str(sol)) if((lcycle==cyclecounter) & (changeposneg==False)): changeposneg=True cyclecounter=0 print('Change pos and neg!') if((changeposneg) & (cyclecounter==lcycle)): print('Have to use equation with minus signs!') print(eq) sol=solve(eq,parse_expr(nodeToRep))[0] eqOut.append(nodeToRep+' = '+str(sol)) indexToRep=list(X).index(parse_expr(nodeToRep)) X.row_del(indexToRep) SM.row_del(indexToRep) DependentRates.append(parse_expr(nodeToRep)) DependentOn.append(list(sol.atoms())) for f in range(len(F)): F[f]=F[f].subs(parse_expr(nodeToRep), sol) if((not compromise) & (not compromise2)): indexToRep=list(X).index(parse_expr(nodeToRep)) foundRateConst=False #print(UsedStates) for var in list(FluxToTake.atoms()): if((var not in X) & (var not in UsedStates) & (var not in UsedRC) & (not is_number(str(var))) & (not foundRateConst)): RC=var UsedRC.append(RC) UsedStates.append(parse_expr(nodeToRep)) foundRateConst=True print(' '+str(nodeToRep)+' --> '+str(RC)) if(foundRateConst): #print(' '+str(len(str(eq)))) sol=solve(eq, RC, simplify=False)[0] eqOut.append(str(RC)+' = '+str(sol)) X.row_del(indexToRep) SM.row_del(indexToRep) #print(' '+str(len(str(sol)))) DependentRates.append(RC) DependentOn.append(list(sol.atoms())) for f in range(len(F)): F[f]=F[f].subs(RC, sol) graph={} for i in range(len(SM*F)): liste=[] for rate in DependentRates: if((SM*F)[i]!=((SM*F)[i]).subs(rate,1)): for var in DependentOn[DependentRates.index(rate)]: if((not is_number(str(var))) & (var!=X[i])): liste.append(str(var)) for j in range(len(X)): if(j==i): argus=expand((SM*F)[i]).args negs=[] poss=[] append=False for arg in argus: if('-' in str(arg)): negs.append(arg) else: poss.append(arg) for el in poss: if(el.subs(X[j],1)!=el): append=True for el in negs: if(el.subs(X[j],0)!=0): append=True if(not append): In=((SM*F)[i]).subs(X[j],0) Out=simplify(((SM*F)[i]-In)/X[j]) #print(Out) if(Out!=Out.subs(X[j],1)): liste.append(str(X[j])) else: liste.append(str(X[j])) else: if((SM*F)[i]!=((SM*F)[i]).subs(X[j],1)): liste.append(str(X[j])) graph[str(X[i])]=liste #### Solve remaining equations eqOut.reverse() #print(eqOut) print('Solving remaining equations ...\n') UsedVars=UsedRC+UsedStates graph={} for i in range(len(SM*F)): liste=[] for j in range(len(X)): if(j==i): argus=expand((SM*F)[i]).args negs=[] poss=[] append=False for arg in argus: if('-' in str(arg)): negs.append(arg) else: poss.append(arg) for el in poss: if(el.subs(X[j],1)!=el): append=True for el in negs: if(el.subs(X[j],0)!=0): append=True if(not append): In=((SM*F)[i]).subs(X[j],0) Out=simplify(((SM*F)[i]-In)/X[j]) #print(Out) if(Out!=Out.subs(X[j],1)): liste.append(str(X[j])) else: liste.append(str(X[j])) else: if((SM*F)[i]!=((SM*F)[i]).subs(X[j],1)): liste.append(str(X[j])) graph[str(X[i])]=liste while(graph!={}): print(graph) node=FindNodeToSolve(graph) print(node) index=list(X).index(parse_expr(node)) #print((SM*F)[index]) sol=solve((SM*F)[index],parse_expr(node), simplify=True) #print(sol) if(sol==[]): foundVarToSolveFor=False for el in ((SM*F)[index]).atoms(): if((not is_number(str(el))) & (el not in UsedRC) & (not foundVarToSolveFor)): sol=solve((SM*F)[index],el, simplify=True)[0] var=el foundVarToSolveFor=True eqOut.insert(0,str(var)+' = '+str(sol)) for f in range(len(F)): F[f]=F[f].subs(var, sol) #print('Inserted') UsedVars.append(var) #print(str((SM*F)[index])+' = 0') else: eqOut.insert(0,node+' = '+str(sol[0])) for f in range(len(F)): F[f]=F[f].subs(parse_expr(node), sol[0]) #print(node+' = '+str(sol[0])) for el in graph: if(node in graph[el]): graph[el].remove(node) graph.pop(node) #### Find appropriate transformations to avoid negative steady state solutions #eqOut=SuggestTrafos(eqOut, UsedVars) #### Test Solution print('Testing Steady State...\n') NonSteady=False for i in range(len(ODE)): expr=parse_expr(str(ODE[i])) for j in range(len(zeroStates)): zeroState=zeroStates[j] expr=expr.subs(zeroState, 0) for j in range(len(eqOut)): ls, rs = eqOut[-(j+1)].split('=') ls=parse_expr(ls) rs=parse_expr(rs) expr=expr.subs(ls, rs) expr=simplify(expr) print(expr) if(expr!=0): print('\t'+str(ODE[i])) print('\t'+str(expr)) NonSteady=True if(NonSteady): print('Solution is wrong!\n') else: print('Solution is correct!\n') #### Print Equations print('I obtained the following equations:\n') if(ausgabe=='M'): for state in zeroStates: print('\tinit_'+str(state)+' "0"'+'\n') eqOutReturn=[] for i in range(len(eqOut)): ls, rs = eqOut[i].split('=') ls=parse_expr(ls) rs=parse_expr(rs) for j in range(i,len(eqOut)): ls2, rs2 = eqOut[j].split('=') rs2=parse_expr(rs2) rs2=rs2.subs(ls,rs) eqOut[j]=str(ls2)+'='+str(rs2) for state in Xo: ls=ls.subs(state, parse_expr('init_'+str(state))) rs=rs.subs(state, parse_expr('init_'+str(state))) eqOut[i]=str(ls)+' "'+str(rs)+'"' for i in range(len(eqOut)): eqOut[i]=eqOut[i].replace('**','^') for eq in eqOut: print('\t'+eq+'\n') eqOutReturn.append(eq) else: for state in zeroStates: print('\t'+str(state)+' = 0'+'\n') eqOutReturn=[] for eq in eqOut: print('\t'+eq+'\n') ls, rs = eq.split(' = ') eqOutReturn.append(ls+'='+rs) print('Number of Species: '+str(nrspecies)) print('Number of Equations: '+str(len(eqOut)+len(zeroStates))) print('Number of new introduced variables: '+str(gesnew)) return(eqOutReturn)
[ "random.random", "numpy.linalg.qr", "random.shuffle", "numpy.nonzero" ]
[((2546, 2567), 'numpy.linalg.qr', 'numpy.linalg.qr', (['ranM'], {}), '(ranM)\n', (2561, 2567), False, 'import numpy\n'), ((3804, 3821), 'random.shuffle', 'shuffle', (['rowliste'], {}), '(rowliste)\n', (3811, 3821), False, 'from random import shuffle\n'), ((3088, 3114), 'numpy.nonzero', 'numpy.nonzero', (['testM[:, i]'], {}), '(testM[:, i])\n', (3101, 3114), False, 'import numpy\n'), ((2189, 2204), 'random.random', 'random.random', ([], {}), '()\n', (2202, 2204), False, 'import random\n'), ((3280, 3306), 'numpy.nonzero', 'numpy.nonzero', (['testM[:, j]'], {}), '(testM[:, j])\n', (3293, 3306), False, 'import numpy\n')]
import collections import re import string import numpy import six import cupy def calc_single_view(ioperand, subscript): """Calculates 'ii->i' by cupy.diagonal if needed. Args: ioperand (cupy.ndarray): Array to be calculated diagonal. subscript (str): Specifies the subscripts. If the same label appears more than once, calculate diagonal for those axes. """ assert ioperand.ndim == len(subscript) labels = set(subscript) label_to_axis = collections.defaultdict(list) for i, label in enumerate(subscript): label_to_axis[label].append(i) result = ioperand count_dict = collections.Counter(subscript) for label in labels: if count_dict[label] == 1: continue axes_to_diag = [] for i, char in enumerate(subscript): if char == label: axes_to_diag.append(i) for axis in reversed(axes_to_diag[1:]): shape_a = result.shape[axis] shape_b = result.shape[axes_to_diag[0]] if shape_a != shape_b: raise ValueError('dimensions in operand 0 for collapsing' ' index \'{0}\' don\'t match' ' ({1} != {2})'.format(label, shape_a, shape_b)) result = result.diagonal(0, axis, axes_to_diag[0]) result = cupy.rollaxis(result, -1, axes_to_diag[0]) subscript = subscript[:axis] + subscript[axis + 1:] return result, subscript def calc_summed_view(ioperand, input_subscript, output_subscript): """Calculates 'i->' by cupy.sum if needed. Args: ioperand (cupy.ndarray): Array to be summed. input_subscript (str): Specifies the subscripts for input array. output_subscript (str): Specifies the subscripts for output array. If one label exists in input_subscript but not in output_subscript, this label will be summed. """ assert len(set(input_subscript)) == len(input_subscript) assert len(set(output_subscript)) == len(output_subscript) assert set(output_subscript).issubset(set(input_subscript)) subscript = input_subscript label_to_summed = set(input_subscript) - set(output_subscript) axes_to_summed = [] for i, label in enumerate(input_subscript): if label in label_to_summed: axes_to_summed.append(i) if axes_to_summed: result = ioperand.sum(axis=tuple(axes_to_summed)). \ astype(ioperand) else: result = ioperand for label in label_to_summed: subscript = subscript.replace(label, '') return result, subscript def calc_transposed_view(ioperand, input_subscript, output_subscript): """Calculates 'ij->ji' by cupy.transpose if needed. Args: ioperand (cupy.ndarray): Array to be transpose. input_subscript (str): Specifies the subscripts for input arrays. output_subscript (str): Specifies the subscripts for output arrays. If input does not match output, ``operand`` is transposed so that it matches. """ assert len(set(output_subscript)) == len(output_subscript) assert set(input_subscript) == set(output_subscript) transpose_orders = [] for label in output_subscript: transpose_orders.append(input_subscript.find(label)) if transpose_orders == sorted(transpose_orders): return ioperand else: return ioperand.transpose(transpose_orders) def calc_combined_view(ioperands, subscripts): """Calculates 'i,j->ij' by cupy.tensordot. Args: ioperands (sequence of arrays): Arrays to be combined. subscripts (sequence of str): Specifies the subscripts. """ result = ioperands[0] for ioperand in ioperands[1:]: # TODO(fukatani): add up at here if enable. result = cupy.tensordot(result, ioperand, axes=0) return result, ''.join(subscripts) def get_dummy_labels(label_list): dummy_label_set = set() count_dict = collections.Counter(label_list) for label, count in six.iteritems(count_dict): if count >= 2: dummy_label_set.add(label) return dummy_label_set def einsum(*operands): """einsum(subscripts, *operands) Evaluates the Einstein summation convention on the operands. Using the Einstein summation convention, many common multi-dimensional array operations can be represented in a simple fashion. This function provides a way to compute such summations. .. note:: ``out``, ``order``, ``dtype``, ``casting`` and ``optimize`` options are not supported. Args: subscripts (str): Specifies the subscripts for summation. operands (sequence of arrays): These are the arrays for the operation. Returns: cupy.ndarray: The calculation based on the Einstein summation convention. .. seealso:: :func:`numpy.einsum` """ # TODO(fukatani): Support 'out', 'order', 'dtype', 'casting', 'optimize' if not operands: raise ValueError('must specify the einstein sum subscripts string and ' 'at least one operand, or at least one operand and ' 'its corresponding subscripts list') subscripts = operands[0] ioperands = operands[1:] if not isinstance(subscripts, str): raise TypeError('Current cupy einsum support only string subscripts') # TODO(fukatani): Support '...' if '.' in subscripts: raise TypeError('Current cupy einsum does not support \'...\' ' 'ellipsis') subscripts = subscripts.replace(' ', '') irregular_chars = set(subscripts) - set(string.ascii_letters) - set('->,') if irregular_chars: pickup = list(irregular_chars)[0] raise ValueError('invalid subscript \'{}\' in einstein sum subscripts ' 'string, subscripts must be letters'.format(pickup)) converted_inputs = [] dtype = numpy.result_type(*ioperands) for a in ioperands: if isinstance(a, cupy.ndarray): converted_inputs.append(a.astype(dtype)) else: converted_inputs.append(cupy.asarray(a, dtype=dtype)) match = re.match('^([a-zA-Z,]+)(->[a-zA-Z]*)?$', subscripts) if not match: raise ValueError('einstein sum subscript string does not contain ' 'proper \'->\' output specified') input_subscripts = match.group(1) if match.group(2): output_subscript = match.group(2)[2:] irregular_chars = set(output_subscript) - set(input_subscripts) if irregular_chars: pickup = list(irregular_chars)[0] raise ValueError('einstein sum subscripts string included output ' 'subscript \'{}\' which never appeared in an ' 'input'.format(pickup)) count_dict = collections.Counter(output_subscript) for key in count_dict: if count_dict[key] == 1: continue raise ValueError('einstein sum subscripts string includes output ' 'subscript \'{}\' multiple times'.format(key)) else: label_list = list(input_subscripts.replace(',', '')) out_label_set = set(label_list) - get_dummy_labels(label_list) output_subscript = ''.join(sorted(list(out_label_set))) input_subscripts_list = input_subscripts.split(',') if len(input_subscripts_list) < len(converted_inputs): raise ValueError('fewer operands provided to einstein sum function ' 'than specified in the subscripts string') if len(input_subscripts_list) > len(converted_inputs): raise ValueError('more operands provided to einstein sum function ' 'than specified in the subscripts string') single_views = [] for i in six.moves.range(len(input_subscripts_list)): subscript = input_subscripts_list[i] ioperand = converted_inputs[i] if len(subscript) > ioperand.ndim: raise ValueError('einstein sum subscripts string contains too ' 'many subscripts for operand {}'.format(i)) if len(subscript) < ioperand.ndim: raise ValueError('operand has more dimensions than subscripts' ' given in einstein sum, but no \'...\' ellipsis' ' provided to broadcast the extra dimensions.') result, subscript = calc_single_view(ioperand, subscript) single_views.append((result, subscript)) if len(converted_inputs) >= 2: results = [view[0] for view in single_views] subscripts = [view[1] for view in single_views] result, subscript = calc_combined_view(results, subscripts) result, subscript = calc_single_view(result, subscript) else: result, subscript = single_views[0] result, subscript = calc_summed_view(result, subscript, output_subscript) return calc_transposed_view(result, subscript, output_subscript)
[ "cupy.tensordot", "numpy.result_type", "re.match", "collections.Counter", "collections.defaultdict", "cupy.rollaxis", "six.iteritems", "cupy.asarray" ]
[((510, 539), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (533, 539), False, 'import collections\n'), ((661, 691), 'collections.Counter', 'collections.Counter', (['subscript'], {}), '(subscript)\n', (680, 691), False, 'import collections\n'), ((4122, 4153), 'collections.Counter', 'collections.Counter', (['label_list'], {}), '(label_list)\n', (4141, 4153), False, 'import collections\n'), ((4178, 4203), 'six.iteritems', 'six.iteritems', (['count_dict'], {}), '(count_dict)\n', (4191, 4203), False, 'import six\n'), ((6105, 6134), 'numpy.result_type', 'numpy.result_type', (['*ioperands'], {}), '(*ioperands)\n', (6122, 6134), False, 'import numpy\n'), ((6345, 6397), 're.match', 're.match', (['"""^([a-zA-Z,]+)(->[a-zA-Z]*)?$"""', 'subscripts'], {}), "('^([a-zA-Z,]+)(->[a-zA-Z]*)?$', subscripts)\n", (6353, 6397), False, 'import re\n'), ((3961, 4001), 'cupy.tensordot', 'cupy.tensordot', (['result', 'ioperand'], {'axes': '(0)'}), '(result, ioperand, axes=0)\n', (3975, 4001), False, 'import cupy\n'), ((7035, 7072), 'collections.Counter', 'collections.Counter', (['output_subscript'], {}), '(output_subscript)\n', (7054, 7072), False, 'import collections\n'), ((1448, 1490), 'cupy.rollaxis', 'cupy.rollaxis', (['result', '(-1)', 'axes_to_diag[0]'], {}), '(result, -1, axes_to_diag[0])\n', (1461, 1490), False, 'import cupy\n'), ((6302, 6330), 'cupy.asarray', 'cupy.asarray', (['a'], {'dtype': 'dtype'}), '(a, dtype=dtype)\n', (6314, 6330), False, 'import cupy\n')]
import cv2 import numpy as np from PIL import Image from scipy import ndimage from skimage.filters import threshold_local def resize(image, canvas_size): # type: (np.array, tuple) -> np.array """Resize an image to specified size while preserving the aspect ratio. The longer side of the image is made equal to the output length of that side, and the other side is scaled in accordance with the aspect ratio. :param image: the image to be resized :param canvas_size: maximum size of the output image in pixels """ ih, iw = image.shape aspect = iw / ih out_w, out_h = canvas_size if out_w < out_h: out_h = int(out_w / aspect) if out_h > canvas_size[1]: out_h = canvas_size[1] out_w = int(out_h * aspect) else: out_w = int(out_h * aspect) if out_w > canvas_size[0]: out_w = canvas_size[0] out_h = int(out_w / aspect) return np.array(Image.fromarray(image).resize((out_w, out_h), Image.BICUBIC)) def center_inside(im, canvas_size): # type: (np.array, tuple) -> np.array """Centers an image inside a canvas. Image is resized to fit on a black canvas while preserving the aspect ratio. Parameters: im (np.array) : the image to be resized canvas_size (tuple): the size (w,h) of the canvas Returns: input image centred on a black canvas of given size """ out_w, out_h = canvas_size canvas = np.zeros(shape=(out_h, out_w)).astype('uint8') * 255 im = resize(im, canvas_size) ih, iw = im.shape pad_x = int((out_w - iw) / 2) pad_y = int((out_h - ih) / 2) canvas[pad_y:pad_y + ih, pad_x:pad_x + iw] = im return canvas def threshold_and_crop(im): """Removes signature background and padding. The image is thresholded using the OTSU's algorithm, and the background pixels are set to white (intensity 255), leaving the foreground pixels in grayscale. The image is then inverted such that the background is zero-valued. Parameters: im (np.array) : the signature image array to be thresholded Returns: thresholded and cropped signature image """ # Threshold using OTSU's method retval, thresh = cv2.threshold(im, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) # Crop the original image with a tight box around signature r, c = np.where(thresh != 0) cropped = thresh[r.min(): r.max(), c.min(): c.max()] return cropped def preprocess_signature(im, canvas_size): """Preprocesses a signature image. Parameters: im (np.array) : the image to be preprocessed canvas_size (tuple) : the size (w,h) of the resize canvas Returns: the preprocessed image as an numpy array """ im = threshold_and_crop(im) im = center_inside(im, canvas_size) return im
[ "cv2.threshold", "PIL.Image.fromarray", "numpy.zeros", "numpy.where" ]
[((2264, 2330), 'cv2.threshold', 'cv2.threshold', (['im', '(0)', '(255)', '(cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)'], {}), '(im, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n', (2277, 2330), False, 'import cv2\n'), ((2405, 2426), 'numpy.where', 'np.where', (['(thresh != 0)'], {}), '(thresh != 0)\n', (2413, 2426), True, 'import numpy as np\n'), ((968, 990), 'PIL.Image.fromarray', 'Image.fromarray', (['image'], {}), '(image)\n', (983, 990), False, 'from PIL import Image\n'), ((1482, 1512), 'numpy.zeros', 'np.zeros', ([], {'shape': '(out_h, out_w)'}), '(shape=(out_h, out_w))\n', (1490, 1512), True, 'import numpy as np\n')]
import numpy as np def apple_p(feature_vector,model): processed_vector = np.array(feature_vector).reshape(1, -1) output = model.predict(processed_vector) output = int(output) label_dict = {0 :'Apple___healthy', 1: 'Apple___Apple_scab', 2: 'Apple___Black_rot', 3: 'Apple___Cedar_apple_rust'} output = label_dict[output] return output def corn_p(feature_vector,model): processed_vector = np.array(feature_vector).reshape(1, -1) output = model.predict(processed_vector) output = int(output) label_dict = {0: 'Corn_(maize)___healthy', 1: 'Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot', 2: 'Corn_(maize)__Common_rust', 3: 'Corn_(maize)___Northern_Leaf_Blight'} output = label_dict[output] return output def grapes_p(feature_vector,model): processed_vector = np.array(feature_vector).reshape(1, -1) output = model.predict(processed_vector) output = int(output) label_dict = {0 : 'Grape___healthy', 1 : 'Grape___Black_rot', 2 : 'Grape___Esca_(Black_Measles)', 3 : 'Grape___Leaf_blight_(Isariopsis_Leaf_Spot)'} output = label_dict[output] return output def potato_p(feature_vector,model): processed_vector = np.array(feature_vector).reshape(1, -1) output = model.predict(processed_vector) output = int(output) label_dict = {0: 'Potato___healthy', 1: 'Potato___Early_blight', 2: 'Potato___Late_blight'} output = label_dict[output] return output def tomato_p(feature_vector,model): processed_vector = np.array(feature_vector).reshape(1, -1) output = model.predict(processed_vector) output = int(output) label_dict = {0 : 'Tomato___healthy', 1 : 'Tomato___Bacterial_spot', 2 : 'Tomato___Early_blight', 3 : 'Tomato___Late_blight', 4 : 'Tomato___Leaf_Mold', 5 : 'Tomato___Septoria_leaf_spot', 6 : 'Tomato___Spider_mites Two-spotted_spider_mite', 7 : 'Tomato___Target_Spot', 8 : 'Tomato___Tomato_Yellow_Leaf_Curl_Virus', 9 : 'Tomato___Tomato_mosaic_virus'} output = label_dict[output] return output
[ "numpy.array" ]
[((75, 99), 'numpy.array', 'np.array', (['feature_vector'], {}), '(feature_vector)\n', (83, 99), True, 'import numpy as np\n'), ((395, 419), 'numpy.array', 'np.array', (['feature_vector'], {}), '(feature_vector)\n', (403, 419), True, 'import numpy as np\n'), ((778, 802), 'numpy.array', 'np.array', (['feature_vector'], {}), '(feature_vector)\n', (786, 802), True, 'import numpy as np\n'), ((1135, 1159), 'numpy.array', 'np.array', (['feature_vector'], {}), '(feature_vector)\n', (1143, 1159), True, 'import numpy as np\n'), ((1435, 1459), 'numpy.array', 'np.array', (['feature_vector'], {}), '(feature_vector)\n', (1443, 1459), True, 'import numpy as np\n')]
import os import logging import numpy as np import pandas as pd from collections import OrderedDict from model_learning.algorithms.max_entropy import THETA_STR from model_learning.clustering.evaluation import evaluate_clustering from model_learning.util.io import create_clear_dir, change_log_handler from model_learning.util.plot import plot_bar from model_learning.clustering.linear import cluster_linear_rewards, get_clusters_means, save_mean_cluster_weights, \ save_clusters_info, plot_clustering_dendrogram, plot_clustering_distances from atomic.parsing.replayer import SUBJECT_ID_TAG, COND_MAP_TAG, TRIAL_TAG, COND_TRAIN_TAG from atomic.definitions.world_map import WorldMap from atomic.model_learning.linear.rewards import create_reward_vector from atomic.model_learning.linear.analyzer import RewardModelAnalyzer __author__ = '<NAME>' __email__ = '<EMAIL>' DEF_DIST_THRESHOLD = 1 # .8 # .6 DEF_STDS = 1.5 # 3 DEF_LINKAGE = 'ward' def load_cluster_reward_weights(file_path): """ Loads the linear reward weights for a set of clusters from a CSV file. :param str file_path: the path to the file from which to load the reward weights. :rtype: dict[str, np.ndarray] :return: a dictionary containing entries in the form `cluster_id` -> `reward_weights`. """ assert os.path.isfile(file_path), 'Could not found CSV file at {}'.format(file_path) data = pd.read_csv(file_path, index_col=0) return {idx: np.array(row) for idx, row in data.iterrows()} def load_datapoints_clusters(file_path): """ Loads the clustering results for a set of datapoints from a CSV file. :param str file_path: the path to the file from which to load the clusters. :rtype: dict[str, int] :return: a dictionary containing the cluster id assigned to each datapoint, i.e., entries in the form `datapoint filename` -> `cluster idx`. """ assert os.path.isfile(file_path), 'Could not found CSV file at {}'.format(file_path) data = pd.read_csv(file_path, index_col=2) # index='Filename' return {idx: row['Cluster'] for idx, row in data.iterrows()} def cluster_reward_weights(analyzer, output_dir, linkage='ward', dist_threshold=DEF_DIST_THRESHOLD, stds=DEF_STDS, clear=False, verbosity=1): """ Analyzes the reward functions resulting from IRL optimization for each player log file. Performs clustering of reward functions based on the weight vectors and computes the mean rewards in each cluster. :param RewardModelAnalyzer analyzer: the reward model analyzer containing the necessary data. :param str output_dir: the directory in which to save the results. :param str linkage: the clustering linkage criterion. :param float dist_threshold: the distance above which clusters are not merged. :param float stds: the number of standard deviations above the gradient mean used for automatic cluster detection. :param bool clear: whether to clear the directory before processing. :param int verbosity: the verbosity level of the log file. :return: """ create_clear_dir(output_dir, clear) change_log_handler(os.path.join(output_dir, 'post-process.log'), verbosity) file_names = list(analyzer.results) logging.info('\n=================================') logging.info('Analyzing models\' reward weights for {} results...'.format(len(file_names))) # performs clustering of reward weights results = [analyzer.results[filename] for filename in file_names] clustering, thetas = cluster_linear_rewards(results, linkage, dist_threshold, stds) # gets rwd feature names with dummy info agent_name = analyzer.agent_names[file_names[0]] agent = analyzer.trajectories[file_names[0]][-1][0].agents[agent_name] locations = analyzer.map_tables[file_names[0]].rooms_list rwd_feat_names = create_reward_vector(agent, locations, WorldMap.get_move_actions(agent)).names # overall weight mean data = np.array([np.mean(thetas, axis=0), np.std(thetas, axis=0) / len(thetas)]).T.tolist() plot_bar(OrderedDict(zip(rwd_feat_names, data)), 'Overall Mean Weights', os.path.join(output_dir, 'weights-mean.{}'.format(analyzer.img_format)), plot_mean=False) # mean weights within each cluster clusters, cluster_weights = get_clusters_means(clustering, thetas) logging.info('Found {} clusters at max. distance: {:.2f}'.format( clustering.n_clusters_, clustering.distance_threshold)) for cluster in sorted(cluster_weights.keys()): idxs = clusters[cluster] data = cluster_weights[cluster] data[1] = data[1] / len(idxs) with np.printoptions(precision=2, suppress=True): logging.info('\tCluster {}: {}, \n\tmean: {}\n'.format(cluster, idxs, data[0])) plot_bar(OrderedDict(zip(rwd_feat_names, data.T.tolist())), 'Mean Weights for Cluster {}'.format(cluster), os.path.join(output_dir, 'weights-mean-{}.{}'.format(cluster, analyzer.img_format)), plot_mean=False) subject_ids = [analyzer.get_player_name(file_name) for file_name in file_names] player_names = [analyzer.agent_names[file_name] for file_name in file_names] save_mean_cluster_weights(cluster_weights, os.path.join(output_dir, 'cluster-weights.csv'), rwd_feat_names) extra_info = OrderedDict({ 'Internal subject ID': subject_ids, 'File name': file_names, 'Game player name': player_names}) save_clusters_info(clustering, extra_info, thetas, os.path.join(output_dir, 'clusters.csv'), rwd_feat_names) # individual rwd weights thetas = np.array([result.stats[THETA_STR] for result in results]) ind_df = pd.DataFrame(list(zip(file_names, *thetas.T.tolist())), columns=['File name'] + rwd_feat_names) ind_df.to_csv(os.path.join(output_dir, 'individual-weights.csv'), index=False) # cluster sizes cluster_sizes = OrderedDict({str(cluster): len(clusters[cluster]) for cluster in sorted(clusters.keys())}) plot_bar(cluster_sizes, 'Clusters Size', os.path.join(output_dir, 'sizes.{}'.format(analyzer.img_format))) # dendrogram plot_clustering_dendrogram( clustering, os.path.join(output_dir, 'weights-dendrogram.{}'.format(analyzer.img_format))) # player_names) plot_clustering_distances( clustering, os.path.join(output_dir, 'weights-distance.{}'.format(analyzer.img_format))) # gets different data partitions according to maps, conditions, subjects, etc gt_labels = { 'Subject': [analyzer.trial_conditions[file_name][SUBJECT_ID_TAG] for file_name in file_names], 'Map Condition': [analyzer.trial_conditions[file_name][COND_MAP_TAG][0] for file_name in file_names], 'Dynamic Map Cond.': [analyzer.trial_conditions[file_name][COND_MAP_TAG][1] for file_name in file_names], 'Train Condition': [analyzer.trial_conditions[file_name][COND_TRAIN_TAG] for file_name in file_names] } subject_min_trials = {} for i, file_name in enumerate(file_names): subj_label = gt_labels['Subject'][i] subj_trial = int(analyzer.trial_conditions[file_name][TRIAL_TAG]) if subj_label not in subject_min_trials or subj_trial < subject_min_trials[subj_label]: subject_min_trials[subj_label] = subj_trial gt_labels['Trial'] = [ int(analyzer.trial_conditions[file_name][TRIAL_TAG]) - subject_min_trials[gt_labels['Subject'][i]] for i, file_name in enumerate(file_names)] # performs clustering evaluation according to the different gt partitions and combinations thereof evaluate_clustering(clustering, gt_labels, output_dir, analyzer.img_format, 3)
[ "model_learning.clustering.linear.get_clusters_means", "numpy.mean", "collections.OrderedDict", "pandas.read_csv", "os.path.join", "os.path.isfile", "numpy.array", "model_learning.clustering.evaluation.evaluate_clustering", "atomic.definitions.world_map.WorldMap.get_move_actions", "model_learning....
[((1306, 1331), 'os.path.isfile', 'os.path.isfile', (['file_path'], {}), '(file_path)\n', (1320, 1331), False, 'import os\n'), ((1395, 1430), 'pandas.read_csv', 'pd.read_csv', (['file_path'], {'index_col': '(0)'}), '(file_path, index_col=0)\n', (1406, 1430), True, 'import pandas as pd\n'), ((1895, 1920), 'os.path.isfile', 'os.path.isfile', (['file_path'], {}), '(file_path)\n', (1909, 1920), False, 'import os\n'), ((1984, 2019), 'pandas.read_csv', 'pd.read_csv', (['file_path'], {'index_col': '(2)'}), '(file_path, index_col=2)\n', (1995, 2019), True, 'import pandas as pd\n'), ((3112, 3147), 'model_learning.util.io.create_clear_dir', 'create_clear_dir', (['output_dir', 'clear'], {}), '(output_dir, clear)\n', (3128, 3147), False, 'from model_learning.util.io import create_clear_dir, change_log_handler\n'), ((3273, 3327), 'logging.info', 'logging.info', (['"""\n================================="""'], {}), '("""\n=================================""")\n', (3285, 3327), False, 'import logging\n'), ((3561, 3623), 'model_learning.clustering.linear.cluster_linear_rewards', 'cluster_linear_rewards', (['results', 'linkage', 'dist_threshold', 'stds'], {}), '(results, linkage, dist_threshold, stds)\n', (3583, 3623), False, 'from model_learning.clustering.linear import cluster_linear_rewards, get_clusters_means, save_mean_cluster_weights, save_clusters_info, plot_clustering_dendrogram, plot_clustering_distances\n'), ((4348, 4386), 'model_learning.clustering.linear.get_clusters_means', 'get_clusters_means', (['clustering', 'thetas'], {}), '(clustering, thetas)\n', (4366, 4386), False, 'from model_learning.clustering.linear import cluster_linear_rewards, get_clusters_means, save_mean_cluster_weights, save_clusters_info, plot_clustering_dendrogram, plot_clustering_distances\n'), ((5396, 5508), 'collections.OrderedDict', 'OrderedDict', (["{'Internal subject ID': subject_ids, 'File name': file_names,\n 'Game player name': player_names}"], {}), "({'Internal subject ID': subject_ids, 'File name': file_names,\n 'Game player name': player_names})\n", (5407, 5508), False, 'from collections import OrderedDict\n'), ((5693, 5750), 'numpy.array', 'np.array', (['[result.stats[THETA_STR] for result in results]'], {}), '([result.stats[THETA_STR] for result in results])\n', (5701, 5750), True, 'import numpy as np\n'), ((7666, 7744), 'model_learning.clustering.evaluation.evaluate_clustering', 'evaluate_clustering', (['clustering', 'gt_labels', 'output_dir', 'analyzer.img_format', '(3)'], {}), '(clustering, gt_labels, output_dir, analyzer.img_format, 3)\n', (7685, 7744), False, 'from model_learning.clustering.evaluation import evaluate_clustering\n'), ((1448, 1461), 'numpy.array', 'np.array', (['row'], {}), '(row)\n', (1456, 1461), True, 'import numpy as np\n'), ((3171, 3215), 'os.path.join', 'os.path.join', (['output_dir', '"""post-process.log"""'], {}), "(output_dir, 'post-process.log')\n", (3183, 3215), False, 'import os\n'), ((5314, 5361), 'os.path.join', 'os.path.join', (['output_dir', '"""cluster-weights.csv"""'], {}), "(output_dir, 'cluster-weights.csv')\n", (5326, 5361), False, 'import os\n'), ((5592, 5632), 'os.path.join', 'os.path.join', (['output_dir', '"""clusters.csv"""'], {}), "(output_dir, 'clusters.csv')\n", (5604, 5632), False, 'import os\n'), ((5878, 5928), 'os.path.join', 'os.path.join', (['output_dir', '"""individual-weights.csv"""'], {}), "(output_dir, 'individual-weights.csv')\n", (5890, 5928), False, 'import os\n'), ((3920, 3952), 'atomic.definitions.world_map.WorldMap.get_move_actions', 'WorldMap.get_move_actions', (['agent'], {}), '(agent)\n', (3945, 3952), False, 'from atomic.definitions.world_map import WorldMap\n'), ((4696, 4739), 'numpy.printoptions', 'np.printoptions', ([], {'precision': '(2)', 'suppress': '(True)'}), '(precision=2, suppress=True)\n', (4711, 4739), True, 'import numpy as np\n'), ((4008, 4031), 'numpy.mean', 'np.mean', (['thetas'], {'axis': '(0)'}), '(thetas, axis=0)\n', (4015, 4031), True, 'import numpy as np\n'), ((4033, 4055), 'numpy.std', 'np.std', (['thetas'], {'axis': '(0)'}), '(thetas, axis=0)\n', (4039, 4055), True, 'import numpy as np\n')]
import os import zipfile import json from collections import OrderedDict from collections import namedtuple from enum import Enum import gi import numpy gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf from mxdc.utils import colors from mxdc.conf import load_cache, save_cache from mxdc.utils.misc import slugify from mxdc.conf import SHARE_DIR class GUIFile(object): """ GUI Resource File object :param name: Resource name (without the extension) :param root: top-level (root) """ def __init__(self, name, root=None): self.name = name self.root = root self.wTree = Gtk.Builder() self.ui_path = '/org/mxdc/{}.ui'.format(self.name) if self.root is not None: self.wTree.add_objects_from_resource(self.ui_path, [self.root]) else: self.wTree.add_from_resource(self.ui_path) def get_object(self, name): """ Get a widget by name from the resource file. :param name: widget name :return: widget """ return self.wTree.get_object(name) class BuilderMixin(object): gui_roots = { 'relative/path/to/file_without_extension': ['root_object'] } def setup_gui(self): """ Initial setup of the GUI based on the class attribute (gui_roots) :return: """ self.gui_objects = { root: GUIFile(path, root) for path, roots in list(self.gui_roots.items()) for root in roots } def get_builder(self): return list(self.gui_objects.values())[0].wTree def build_gui(self): pass def clone(self): """ Make a copy of the Widget """ if self.gui_objects: builder = Builder({ root: GUIFile(path, root) for path, roots in list(self.gui_roots.items()) for root in roots }) builder.gui_top = self.gui_top builder.gui_roots = self.gui_roots return builder def __getattr__(self, item): if self.gui_objects: for root in list(self.gui_objects.values()): obj = root.get_object(item) if obj: return obj obj = root.get_object(item.replace('_', '-')) if obj: return obj raise AttributeError('{} does not have attribute: {}'.format(self, item)) class Builder(BuilderMixin): def __init__(self, objects=None): if not objects: self.setup_gui() else: self.gui_objects = objects RowSpec = namedtuple('ColRow', ['data', 'title', 'type', 'text', 'expand']) class ColumnSpec(object): def __init__(self, *columns): """Columns should be a list of 4-tupes ColumnNo(int), Title(str), renderer, Format(eg '{0.2f}' """ self.specs = [ RowSpec(*row) for row in columns ] self.info = OrderedDict( [(col.data, col) for col in self.specs] ) def __getitem__(self, item): return self.info[item] def items(self): return list(self.info.items()) def keys(self): return list(self.info.keys()) def values(self): return list(self.info.values()) class ColumnType(object): TEXT = 'text' TOGGLE = 'toggle' ICON = 'pixbuf' NUMBER = 'number' COLORSCALE = 'colorscale' class TreeManager(GObject.GObject): class Data(Enum): A, B = list(range(2)) Types = [int, int] Columns = ColumnSpec( (Data.A, 'A', ColumnType.TEXT, '{}', True), (Data.B, 'B', ColumnType.TOGGLE, '{:0.3f}', False), ) Icons = { # (icon-name, color) Data.A: ('', '#770000'), Data.B: ('', '#770000'), } tooltips = None parent = Data.A # The column used to group items under the same parent flat = False # whether tree is flat single level or not single_click = False select_multiple = False def __init__(self, view, model=None, colormap=None): super().__init__() if not model: self.model = Gtk.TreeStore(*self.Types) # make a new model if none is provided else: self.model = model self.view = view self.colormap = colormap or colors.PERCENT_COLORMAP self.view.set_model(self.model) self.add_columns() self.selection = self.view.get_selection() if self.select_multiple: self.selection.set_mode(Gtk.SelectionMode.MULTIPLE) self.selection.connect('changed', self.do_selection_changed) self.model.connect('row-changed', self.row_changed) self.model.connect('row-deleted', self.row_deleted) self.model.connect('row-inserted', self.row_inserted) self.view.props.activate_on_single_click = self.single_click self.view.connect('row-activated', self.row_activated) self.keys = [item.name.lower() for item in self.Data] def add_item(self, item, add_parent=True): """ Add an item to the tree :param item: a dict :return: a tuple of Gtk.TreePath objects for (parent, child), parent path is None for flat trees """ if not self.flat: parent_path = None parent_itr = self.find_parent_iter(item) if parent_itr: if not self.model.iter_has_child(parent_itr) and add_parent: row = list(self.model[parent_itr]) self.model.append(parent_itr, row=row) parent_path = self.model.get_path(parent_itr) else: parent_itr = parent_path = None row = [item.get(key) for key in self.keys] child_itr = self.model.append(parent_itr, row=row) child_path = self.model.get_path(child_itr) return parent_path, child_path def find_parent_iter(self, item): """ Find the parent row for a given item. :param item: a dict of values for the item about to be added :return: a Gtk.TreeItr or None pointing to the parent row """ parent_key = self.keys[self.parent.value] parent = self.model.get_iter_first() while parent: if self.model[parent][self.parent.value] == item.get(parent_key): break parent = self.model.iter_next(parent) return parent def add_items(self, items): """ Add a list of items to the data store :param items: a list of dicts corresponding to the items :return: number of groups added """ groups = set() for item in items: parent_path, child_path = self.add_item(item) groups.add(parent_path) return len(groups) def row_to_dict(self, row): """ Convert a model row into a dictionary :param row: TreeModelRow :return: dict representing the item """ return dict(list(zip(self.keys, row))) def get_item(self, itr): """ Retrieve the item pointed to by itr :param itr: Gtk.TreeItr :return: dict representing the item """ return self.row_to_dict(self.model[itr]) def get_items(self, itr): """ Retrieve all items under the given parent, if itr is a child, retrieve all siblings. For flat Trees, the list will contain a single item. :param itr: Gtk.TreeItr :return: a list of dicts representing the children or siblings """ runs = [] if not self.flat: if self.model.iter_has_child(itr): parent_itr = itr else: parent_itr = self.model.iter_parent(itr) itr = self.model.iter_children(parent_itr) while itr: item = self.get_item(itr) itr = self.model.iter_next(itr) runs.append(item) else: item = self.get_item(itr) runs.append(item) return runs def clear(self): """ Remove all items from the data store """ self.model.clear() def clear_selection(self): """Remove all selected items""" model, selected = self.selection.get_selected_rows() for path in selected: row = model[path] model.remove(row.iter) def make_parent(self, row): """ Make a parent item for a given item :param row: a dict for an item :return: a dict suitable for adding to the model as a parent """ parent_row = ['']*len(self.keys) parent_row[list(self.Columns.keys())[0].value] = row[self.parent.value] return parent_row def add_columns(self): """ Add Columns to the TreeView and link all signals """ for data, spec in list(self.Columns.items()): if spec.type == ColumnType.TOGGLE: renderer = Gtk.CellRendererToggle(activatable=True) renderer.connect('toggled', self.row_toggled, spec) column = Gtk.TreeViewColumn(title=spec.title, cell_renderer=renderer, active=spec.data.value) column.props.sizing = Gtk.TreeViewColumnSizing.FIXED column.set_fixed_width(32) self.view.append_column(column) elif spec.type == ColumnType.COLORSCALE: renderer = Gtk.CellRendererText() column = Gtk.TreeViewColumn(title=spec.title, cell_renderer=renderer) column.props.sizing = Gtk.TreeViewColumnSizing.FIXED column.set_fixed_width(32) column.set_cell_data_func(renderer, self.format_colorscale, spec) self.view.append_column(column) elif spec.type == ColumnType.ICON: renderer = Gtk.CellRendererPixbuf() column = Gtk.TreeViewColumn(title=spec.title, cell_renderer=renderer) column.props.sizing = Gtk.TreeViewColumnSizing.FIXED column.set_fixed_width(32) column.set_cell_data_func(renderer, self.format_icon, spec) self.view.append_column(column) elif spec.type in [ColumnType.TEXT, ColumnType.NUMBER]: renderer = Gtk.CellRendererText() column = Gtk.TreeViewColumn(title=spec.title, cell_renderer=renderer, text=spec.data.value) column.props.sizing = Gtk.TreeViewColumnSizing.FIXED renderer.props.ellipsize = Pango.EllipsizeMode.END column.set_expand(spec.expand) column.set_sort_column_id(spec.data.value) column.set_cell_data_func(renderer, self.format_cell, spec) if spec.type == ColumnType.NUMBER: renderer.set_alignment(0.8, 0.5) #renderer.props.family = 'Monospace' self.view.append_column(column) if self.tooltips: self.view.set_tooltip_column(self.tooltips.value) def format_colorscale(self, column, renderer, model, itr,spec): """ Format a colorscale color based on a percentage value :param column: Gtk.TreeViewColumn :param renderer: Gtk.CellRenderer :param model: Gtk.TreeModel :param itr: Gtk.TreeIter :param spec: RowSpec :return: """ if model.iter_has_child(itr): renderer.set_property('text', '') else: value = model[itr][spec.data.value] color = Gdk.RGBA(**self.colormap.rgba(value)) renderer.set_property("foreground-rgba", color) renderer.set_property("text", "\u25a0") def format_icon(self, column, renderer, model, itr, spec): """ Format an icon based on a field value :param column: Gtk.TreeViewColumn :param renderer: Gtk.CellRenderer :param model: Gtk.TreeModel :param itr: Gtk.TreeIter :param spec: RowSpec :return: """ if model.iter_has_child(itr): renderer.set_property('icon-name', None) else: value = model[itr][spec.data.value] name, color = self.Icons.get(value, (None, '#ffffff')) rgba = Gdk.RGBA() rgba.parse(color) theme = Gtk.IconTheme.get_default() info = theme.lookup_icon(name, 16, Gtk.IconLookupFlags.FORCE_SYMBOLIC) icon, is_symbolic = info.load_symbolic(rgba, None, None, None) renderer.props.pixbuf = icon def format_cell(self, column, renderer, model, itr, spec): """ Method to format cell when values change :param column: Gtk.TreeViewColumn :param renderer: Gtk.CellRenderer :param model: Gtk.TreeModel :param itr: Gtk.TreeIter :param spec: RowSpec :return: """ if model.iter_has_child(itr): parent_row = self.make_parent(model[itr]) renderer.set_property('text', parent_row[spec.data.value]) else: renderer.set_property('text', spec.text.format(model[itr][spec.data.value])) def row_toggled(self, cell, path, spec): """ Method to handle toggling of cells :param cell: Gtk.CellRendererToggle :param path: Gtk.TreePath :param spec: RowSpec :return: """ model = self.view.get_model() model[path][spec.data.value] = not self.model[path][spec.data.value] def do_selection_changed(self, selection): """ Handle changes to the selection :param selection: Gtk.TreeSelection :return: """ if selection.get_mode() != Gtk.SelectionMode.MULTIPLE: model, itr = selection.get_selected() return self.selection_changed(model, itr) def selection_changed(self, model, itr): """ Handle changes to the selection :param selection: Gtk.TreeModel :param itr: Gtk.TreeIter :return: """ pass def row_activated(self, view, path, column): """ Handle activation of rows :param view: Gtk.TreeView :param path: Gtk.TreePath :param column: Gtk.TreeViewColumn :return: """ def row_changed(self, model, path, itr): """ :param model: Gtk.TreeModel :param path: Gtk.TreePath :param itr: Gtk.TreeIter :return: """ def row_inserted(self, model, path, itr): """ :param model: Gtk.TreeModel :param path: Gtk.TreePath :param itr: Gtk.TreeIter :return: """ parent_itr = model.iter_parent(itr) if parent_itr: parent = model.get_path(parent_itr) self.view.expand_row(parent, False) child = model.get_path(itr) self.view.scroll_to_cell(child, None, True, 0.5, 0.5) def row_deleted(self, model, path): """ :param model: Gtk.TreeModel :param path: Gtk.TreePath :return: """ class FilteredTreeManager(TreeManager): def __init__(self, view, model=None, colormap=None): super().__init__(view, model=model, colormap=colormap) if not model: self.src_model = Gtk.TreeStore(*self.Types) # make a new model if none is provided else: self.src_model = model self.view = view self.colormap = colormap or colors.PERCENT_COLORMAP self.view.set_model(self.model) self.add_columns() self.selection = self.view.get_selection() self.selection.connect('changed', self.do_selection_changed) self.model.connect('row-changed', self.row_changed) self.view.props.activate_on_single_click = self.single_click self.view.connect('row-activated', self.row_activated) self.keys = [item.name.lower() for item in self.Data] class Validator(object): """ Collection of Field Validation Converters """ class Clip(object): """ Convert a value to the specified type and clip it between the specified limits """ def __init__(self, dtype, lo, hi, default=None): self.dtype = dtype self.lo = lo self.hi = hi self.default = self.lo if default is None else default def __call__(self, val): try: if self.lo is None and self.hi is None: return self.dtype(val) elif self.lo is None: return min(self.dtype(val), self.hi) elif self.hi is None: return max(self.lo, self.dtype(val)) else: return min(max(self.lo, self.dtype(val)), self.hi) except (TypeError, ValueError): return self.default class Float(Clip): """ Convert a value to the specified type and clip it between the specified limits """ def __init__(self, lo, hi, default=None): super().__init__(float, lo, hi, default) class AngleFrac(Float): def fix(self, val): return 180. / round(180. / val) def __call__(self, val): val = super().__call__(val) return self.fix(val) class Int(Clip): """ Convert a value to the specified type and clip it between the specified limits """ def __init__(self, lo, hi, default=None): super().__init__(int, lo, hi, default) class String(object): """ Enforce maximum string length """ def __init__(self, max_length, default=''): self.max_length = max_length self.default = default def __call__(self, val): return str(val)[:self.max_length] class Slug(String): def __init__(self, max_length, default=''): super().__init__(max_length, default) def __call__(self, val): return slugify(str(val)[:self.max_length]) class Enum(object): """ Make sure integer value is within the valid values for an emum type """ def __init__(self, dtype, default=None): self.dtype = dtype if isinstance(default, self.dtype): self.default = default.value else: try: self.default = self.dtype(default).value except ValueError: self.default = list(self.dtype)[0].value def __call__(self, val): if isinstance(val, self.dtype): return val.value else: try: return self.dtype(int(val)).value except (TypeError, ValueError): return self.default class Bool(object): """ Convert a value to the specified type """ def __init__(self, default=False): self.default = default def __call__(self, val): try: return bool(val) except (TypeError, ValueError): return self.default class Value(object): """ Convert a value to the specified type """ def __init__(self, dtype, default=None): self.dtype = dtype self.default = default def __call__(self, val): try: return self.dtype(val) except (TypeError, ValueError): return self.default class Pass(object): def __call__(self, val): return val class FieldSpec(object): """ Detailed Specification of a single config field in a GUI. """ def __init__(self, name, suffix, text_format, converter=Validator.Pass): """ :param name: field name :param suffix: field suffix type :param text_format: text format :param converter: validator or converter """ self.name = name self.suffix = suffix self.text_format = text_format self.converter = converter def set_converter(self, converter): """ Change the converter of the field :param converter: """ self.converter = converter def field_from(self, builder, prefix): """ Get reference to GUI input widget referenced by the field spec. :param builder: The GUI builder containing the widget :param prefix: the prefix or the widget """ field_name = f'{prefix}_{self.name}_{self.suffix}' return getattr(builder, field_name, None) def value_from(self, builder, prefix): """ Get the value contained in the GUI input widget referenced by the field spec :param builder: The GUI builder containing the widget :param prefix: the prefix or the widget """ field = self.field_from(builder, prefix) if field: if self.suffix == 'entry': raw_value = field.get_text() elif self.suffix in ['switch', 'check']: raw_value = field.get_active() elif self.suffix == 'cbox': raw_value = field.get_active_id() elif self.suffix == 'spin': raw_value = field.get_value() elif self.suffix == 'mbox' and field.get_model(): raw_value = field.get_active() else: raw_value = None return self.converter(raw_value) def update_to(self, builder, prefix, value): """ Validate and Update the value contained in the GUI input widget referenced by the field spec :param builder: The GUI builder containing the widget :param prefix: the prefix or the widget :param value: New value to update to """ field = self.field_from(builder, prefix) new_value = self.converter(value) if field: if self.suffix == 'entry': field.set_text(self.text_format.format(new_value)) elif self.suffix in ['switch', 'check']: field.set_active(new_value) elif self.suffix == 'cbox': field.set_active_id(str(new_value)) elif self.suffix == 'spin': field.set_value(new_value) elif self.suffix == 'mbox' and field.get_model(): new_value = -1 if new_value in [0, None] else new_value field.set_active(new_value) def connect_to(self, builder, prefix, callback): """ Connect the field to a given callback :param builder: The GUI builder containing the widget :param prefix: the prefix or the widget :param callback: callback function :return: source id of connection """ field = self.field_from(builder, prefix) if field: if self.suffix in ['switch']: return field.connect('activate', callback, self.name) elif self.suffix in ['cbox', 'mbox']: return field.connect('changed', callback, None, self.name) elif self.suffix == 'spin': return field.connect('value-changed', callback, None, self.name) else: field.connect('focus-out-event', callback, self.name) return field.connect('activate', callback, None, self.name) class FormManager(object): """ A controller which manages a set of fields in a form within a user interface monitoring, validating inputs and managing persistence between application instances. """ def __init__(self, builder, fields=(), prefix='widget', disabled=(), persist=False): """ :param builder: widget collection :param fields: a list of FieldSpec objects :param prefix: widget prefix :param disabled: tuple of disabled field names :param persist: Persist the configuration between instances """ self.builder = builder self.fields = { spec.name: spec for spec in fields } self.persist = persist self.prefix = prefix self.disabled = disabled self.handlers = {} for name, spec in self.fields.items(): field = spec.field_from(self.builder, self.prefix) if field: self.handlers[spec.name] = spec.connect_to(self.builder, self.prefix, self.on_change) if name in self.disabled: field.set_sensitive(False) # see if values exist in cache if self.persist: info = load_cache(self.prefix) if info: self.set_values(info) def set_value(self, name, value, propagate=False): """ Set the value of a field by name :param name: name of field :param value: value to set :param propagate: re-process the form data to update linked fields """ spec = self.fields[name] field = spec.field_from(self.builder, self.prefix) if field: with field.handler_block(self.handlers[name]): spec.update_to(self.builder, self.prefix, value) if propagate: self.on_change(field, None, name) def get_value(self, name): """ Get the value of a field by name :param name: :return: value """ spec = self.fields[name] return spec.value_from(self.builder, self.prefix) def set_values(self, info, propagate=False): """ Set the values of the fields :param info: Dictionary of name value pairs to set. Only pairs present are set :param propagate: re-process the form data to update linked fields """ for name, value in info.items(): if name in self.fields: self.set_value(name, value, propagate=propagate) def get_values(self): """ Get the dictionary of all name value pairs """ return { name: spec.value_from(self.builder, self.prefix) for name, spec in self.fields.items() } def get_defaults(self): """ Return default values :return: dictionary """ return { name: spec.converter.default for name, spec in self.fields.items() if hasattr(spec.converter, 'default') } def on_change(self, field, event, name): """ Handle the change event and validate the field, updating accordingly :param field: the field that emitted the event :param event: change event data or None :param name: name of field """ spec = self.fields.get(name) if spec: value = spec.value_from(self.builder, self.prefix) with field.handler_block(self.handlers[name]): spec.update_to(self.builder, self.prefix, value) if self.persist: self.save() def get_field(self, name): """ Fetch the field by name :param name: name of field :return: widget containing the field """ spec = self.fields.get(name) if spec: return spec.field_from(self.builder, self.prefix) def save(self): """ Save the state of the Form """ save_cache(self.get_values(), self.prefix) def color_palette(colormap): data = 255 * numpy.array(colormap.colors) data[-1] = [255, 255, 255] return data.ravel().astype(numpy.uint8) def get_symbol(name, catalog, size=None): cat_file = os.path.join(SHARE_DIR, 'data', f'{catalog}.sym') with zipfile.ZipFile(cat_file, 'r') as sym: index = json.loads(sym.read('symbol.json')) if name in index: data = sym.read(name) stream = Gio.MemoryInputStream.new_from_bytes(GLib.Bytes.new(data)) if size is not None: pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale( stream, *size, True ) else: pixbuf = GdkPixbuf.Pixbuf.new_from_stream(stream, None) return pixbuf def register_icons(): """ Register named icons """ theme = Gtk.IconTheme.get_default() theme.add_resource_path('/org/mxdc/data/icons')
[ "gi.repository.GdkPixbuf.Pixbuf.new_from_stream", "collections.OrderedDict", "collections.namedtuple", "gi.repository.GdkPixbuf.Pixbuf.new_from_stream_at_scale", "zipfile.ZipFile", "gi.repository.Gtk.Builder", "gi.repository.Gtk.TreeStore", "gi.repository.Gdk.RGBA", "gi.repository.Gtk.CellRendererPi...
[((155, 187), 'gi.require_version', 'gi.require_version', (['"""Gtk"""', '"""3.0"""'], {}), "('Gtk', '3.0')\n", (173, 187), False, 'import gi\n'), ((2683, 2748), 'collections.namedtuple', 'namedtuple', (['"""ColRow"""', "['data', 'title', 'type', 'text', 'expand']"], {}), "('ColRow', ['data', 'title', 'type', 'text', 'expand'])\n", (2693, 2748), False, 'from collections import namedtuple\n'), ((27901, 27950), 'os.path.join', 'os.path.join', (['SHARE_DIR', '"""data"""', 'f"""{catalog}.sym"""'], {}), "(SHARE_DIR, 'data', f'{catalog}.sym')\n", (27913, 27950), False, 'import os\n'), ((28544, 28571), 'gi.repository.Gtk.IconTheme.get_default', 'Gtk.IconTheme.get_default', ([], {}), '()\n', (28569, 28571), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((678, 691), 'gi.repository.Gtk.Builder', 'Gtk.Builder', ([], {}), '()\n', (689, 691), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((3037, 3089), 'collections.OrderedDict', 'OrderedDict', (['[(col.data, col) for col in self.specs]'], {}), '([(col.data, col) for col in self.specs])\n', (3048, 3089), False, 'from collections import OrderedDict\n'), ((27738, 27766), 'numpy.array', 'numpy.array', (['colormap.colors'], {}), '(colormap.colors)\n', (27749, 27766), False, 'import numpy\n'), ((27960, 27990), 'zipfile.ZipFile', 'zipfile.ZipFile', (['cat_file', '"""r"""'], {}), "(cat_file, 'r')\n", (27975, 27990), False, 'import zipfile\n'), ((4200, 4226), 'gi.repository.Gtk.TreeStore', 'Gtk.TreeStore', (['*self.Types'], {}), '(*self.Types)\n', (4213, 4226), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((12394, 12404), 'gi.repository.Gdk.RGBA', 'Gdk.RGBA', ([], {}), '()\n', (12402, 12404), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((12455, 12482), 'gi.repository.Gtk.IconTheme.get_default', 'Gtk.IconTheme.get_default', ([], {}), '()\n', (12480, 12482), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((15434, 15460), 'gi.repository.Gtk.TreeStore', 'Gtk.TreeStore', (['*self.Types'], {}), '(*self.Types)\n', (15447, 15460), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((24859, 24882), 'mxdc.conf.load_cache', 'load_cache', (['self.prefix'], {}), '(self.prefix)\n', (24869, 24882), False, 'from mxdc.conf import load_cache, save_cache\n'), ((9066, 9106), 'gi.repository.Gtk.CellRendererToggle', 'Gtk.CellRendererToggle', ([], {'activatable': '(True)'}), '(activatable=True)\n', (9088, 9106), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((9200, 9289), 'gi.repository.Gtk.TreeViewColumn', 'Gtk.TreeViewColumn', ([], {'title': 'spec.title', 'cell_renderer': 'renderer', 'active': 'spec.data.value'}), '(title=spec.title, cell_renderer=renderer, active=spec.\n data.value)\n', (9218, 9289), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((28169, 28189), 'gi.repository.GLib.Bytes.new', 'GLib.Bytes.new', (['data'], {}), '(data)\n', (28183, 28189), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((28249, 28311), 'gi.repository.GdkPixbuf.Pixbuf.new_from_stream_at_scale', 'GdkPixbuf.Pixbuf.new_from_stream_at_scale', (['stream', '*size', '(True)'], {}), '(stream, *size, True)\n', (28290, 28311), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((28393, 28439), 'gi.repository.GdkPixbuf.Pixbuf.new_from_stream', 'GdkPixbuf.Pixbuf.new_from_stream', (['stream', 'None'], {}), '(stream, None)\n', (28425, 28439), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((9525, 9547), 'gi.repository.Gtk.CellRendererText', 'Gtk.CellRendererText', ([], {}), '()\n', (9545, 9547), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((9573, 9633), 'gi.repository.Gtk.TreeViewColumn', 'Gtk.TreeViewColumn', ([], {'title': 'spec.title', 'cell_renderer': 'renderer'}), '(title=spec.title, cell_renderer=renderer)\n', (9591, 9633), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((9950, 9974), 'gi.repository.Gtk.CellRendererPixbuf', 'Gtk.CellRendererPixbuf', ([], {}), '()\n', (9972, 9974), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((10000, 10060), 'gi.repository.Gtk.TreeViewColumn', 'Gtk.TreeViewColumn', ([], {'title': 'spec.title', 'cell_renderer': 'renderer'}), '(title=spec.title, cell_renderer=renderer)\n', (10018, 10060), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((10392, 10414), 'gi.repository.Gtk.CellRendererText', 'Gtk.CellRendererText', ([], {}), '()\n', (10412, 10414), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n'), ((10440, 10527), 'gi.repository.Gtk.TreeViewColumn', 'Gtk.TreeViewColumn', ([], {'title': 'spec.title', 'cell_renderer': 'renderer', 'text': 'spec.data.value'}), '(title=spec.title, cell_renderer=renderer, text=spec.data\n .value)\n', (10458, 10527), False, 'from gi.repository import Gtk, GObject, Gdk, Pango, Gio, GLib, GdkPixbuf\n')]
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import unittest import numpy as np from generator import generator, generate from openvino.tools.mo.middle.L2NormFusing import L2NormToNorm from openvino.tools.mo.front.common.partial_infer.utils import int64_array from openvino.tools.mo.utils.ir_engine.compare_graphs import compare_graphs from unit_tests.utils.graph import build_graph_with_attrs # A list with nodes attributes used to build various graphs. nodes = [ ('l2_normalize_mul', dict(kind='op', op='Mul', name='l2_norm_name')), ('l2_normalize_mul_data', dict(kind='data')), ('maximum', dict(kind='op', op='Maximum')), ('maximum_data', dict(kind='data')), ('maximum_y_const', dict(kind='op', op='Const', value=np.array(12.e-13, dtype=np.float32))), ('maximum_y_data', dict(kind='data', value=np.array(12.e-13, dtype=np.float32))), ('rsqrt_pow', dict(kind='data', value=-0.5)), ('rsqrt', dict(kind='op', op='Pow')), ('rsqrt_data', dict(kind='data')), ('square_pow', dict(kind='op', op='Const', value=2.)), ('square_pow_data', dict(kind='data', value=2.)), ('square', dict(kind='op', op='Pow')), ('sum', dict(kind='op', op='ReduceSum')), ('sum_data', dict(kind='data')), ('sum_axes', dict(kind='op', op='Const')), # nodes added after replacement ('normalize_node', dict(kind='op', op='NormalizeL2')), ('weights_node', dict(kind='op', op='Const')), ('result', dict(kind='op', op='Result')) ] edges = [ ('input', 'input_data', {'out': 0}), ('input_data', 'square', {'in': 0}), ('square_pow', 'square_pow_data', {'out': 0}), ('square_pow_data', 'square', {'in': 1}), ('square', 'square_data'), ('square_data', 'sum'), ('sum_axes', 'sum_axes_data'), ('sum_axes_data', 'sum'), ('sum', 'sum_data'), ('maximum_y_const', 'maximum_y_data'), ('maximum_y_data', 'maximum'), ('sum_data', 'maximum'), ('maximum', 'maximum_data'), ('maximum_data', 'rsqrt', {'in': 0}), ('rsqrt_pow', 'rsqrt', {'in': 1}), ('rsqrt', 'rsqrt_data'), ('rsqrt_data', 'l2_normalize_mul'), ('input_data', 'l2_normalize_mul'), ('l2_normalize_mul', 'l2_normalize_mul_data'), ('l2_normalize_mul_data', 'result'), ] edges_after_replacement = [ ('input', 'input_data', {'out': 0}), ('input_data', 'normalize_node'), ('weights_node', 'weights_node_data'), ('weights_node_data', 'normalize_node'), ('normalize_node', 'l2_normalize_mul_data'), ('l2_normalize_mul_data', 'result'), ] @generator class L2NormToNormTest(unittest.TestCase): @generate(*[(int64_array([2, 3]), int64_array([1]), 'NCHW'), # NC layout, normalize C dimension (int64_array([2, 3]), int64_array([1]), 'NHWC'), # NC layout, normalize C dimension (int64_array([2, 3, 5]), int64_array([1]), 'NCHW'), # NCH layout, normalize C dimension (int64_array([2, 3, 5]), int64_array([1]), 'NHWC'), # NCH layout, normalize C dimension (int64_array([2, 3, 5]), int64_array([-1, -2]), 'NHWC'), # NCH layout, normalize CH dimensions (int64_array([2, 3, 5]), int64_array([-1, -2]), 'NCHW'), # NCH layout, normalize CH dimensions (int64_array([2, 3, 5]), int64_array([1, 2]), 'NCHW'), # NCH layout, normalize CH dimensions (int64_array([2, 3, 5]), int64_array([1, 2]), 'NHWC'), # NCH layout, normalize CH dimensions (int64_array([2, 3, 5, 7]), int64_array([1]), 'NCHW'), # NCHW layout, normalize C dimension (int64_array([2, 3, 5, 7]), int64_array([-1]), 'NHWC'), # NHWC layout, normalize C dimension (int64_array([2, 3, 5, 7]), int64_array([3]), 'NHWC'), # NCHW layout, normalize C dimension (int64_array([2, 3, 5, 7]), int64_array([-1, 1, 2]), 'NCHW'), # NCHW layout, normalize CHW dimensions (int64_array([2, 3, 5, 7]), int64_array([-3, -2, -1]), 'NHWC'), # NCHW layout, normalize HWC dimensions ]) def test_positive(self, input_shape, axes, layout): graph = build_graph_with_attrs(nodes + [ ('input', dict(kind='op', shape=input_shape, op='Parameter', data_type=np.float32)), ('input_data', dict(kind='data', shape=input_shape, data_type=np.float32)), ('square_data', dict(kind='data', shape=input_shape)), ('sum_axes_data', dict(kind='data', value=axes, shape=None)), ], edges, nodes_with_edges_only=True) graph.stage = 'middle' graph.graph['layout'] = layout L2NormToNorm().find_and_replace_pattern(graph) graph_ref = build_graph_with_attrs(nodes + [ ('input', dict(kind='op', shape=input_shape, op='Parameter', data_type=np.float32)), ('input_data', dict(kind='data', shape=input_shape, data_type=np.float32)), ('weights_node_data', dict(kind='data', value=axes.sort())), ], edges_after_replacement, nodes_with_edges_only=True) (flag, resp) = compare_graphs(graph, graph_ref, 'result', check_op_attrs=True) self.assertTrue(graph.node[graph.get_nodes_with_attributes(type='NormalizeL2')[0]]['name'] == 'l2_norm_name') self.assertTrue(flag, resp) @generate(*[(int64_array([2]), int64_array([0]), 'NCHW'), (int64_array([2, 3]), int64_array([0]), 'NCHW'), (int64_array([2, 3]), int64_array([0]), 'NHWC'), (int64_array([2, 3]), int64_array([0, 1]), 'NCHW'), (int64_array([2, 3]), int64_array([0, 1]), 'NHWC'), (int64_array([2, 3, 5]), int64_array([0]), 'NCHW'), (int64_array([2, 3, 5]), int64_array([0]), 'NHWC'), (int64_array([2, 3, 5]), int64_array([-1]), 'NCHW'), (int64_array([2, 3, 5]), int64_array([-1]), 'NHWC'), (int64_array([2, 3, 5]), int64_array([0, 1]), 'NCHW'), (int64_array([2, 3, 5]), int64_array([0, 1]), 'NHWC'), (int64_array([2, 3, 5]), int64_array([0, 2]), 'NCHW'), (int64_array([2, 3, 5]), int64_array([0, 2]), 'NHWC'), (int64_array([2, 3, 5, 7]), int64_array([0]), 'NCHW'), (int64_array([2, 3, 5, 7]), int64_array([0]), 'NHWC'), (int64_array([2, 3, 5, 7]), int64_array([2]), 'NCHW'), (int64_array([2, 3, 5, 7]), int64_array([2]), 'NHWC'), (int64_array([2, 3, 5, 7]), int64_array([3]), 'NCHW'), (int64_array([2, 3, 5, 7]), int64_array([1]), 'NHWC'), (int64_array([2, 3, 5, 7]), int64_array([1, 2]), 'NCHW'), (int64_array([2, 3, 5, 7]), int64_array([1, -1]), 'NHWC'), (int64_array([2, 3, 5, 7]), int64_array([1, -1]), 'NCHW'), (int64_array([2, 3, 5, 7]), int64_array([-2, -1]), 'NHWC'), (int64_array([2, 3, 5, 7]), int64_array([1, 3]), 'NCHW'), (int64_array([2, 3, 5, 7]), int64_array([2, 3]), 'NHWC'), (int64_array([2, 3, 5, 7]), int64_array([0, 1, 2]), 'NCHW'), (int64_array([2, 3, 5, 7]), int64_array([0, 1, 2]), 'NHWC'), (int64_array([2, 3, 5, 7]), int64_array([0, 2, 3]), 'NCHW'), (int64_array([2, 3, 5, 7]), int64_array([0, 2, 3]), 'NHWC'), (int64_array([2, 3, 5, 7]), int64_array([0, 1, 2, 3]), 'NCHW'), (int64_array([2, 3, 5, 7]), int64_array([0, 1, 2, 3]), 'NHWC'), (int64_array([2, 3, 5, 7, 9]), int64_array([1]), 'NCHW'), (int64_array([2, 3, 5, 7, 9]), int64_array([-1]), 'NHWC'), (int64_array([2, 3, 5, 7, 9]), int64_array([1, 2, 3, 4]), 'NCHW'), (int64_array([2, 3, 5, 7, 9]), int64_array([-1, -2, -3, -4]), 'NHWC'), ]) def test_negative(self, input_shape, axes, layout): graph = build_graph_with_attrs(nodes + [ ('input', dict(kind='op', shape=input_shape, op='Parameter', data_type=np.float32)), ('input_data', dict(kind='data', shape=input_shape, data_type=np.float32)), ('square_data', dict(kind='data', shape=input_shape)), ('sum_axes_data', dict(kind='data', value=axes, shape=None)), ], edges, nodes_with_edges_only=True) graph.stage = 'middle' graph.graph['layout'] = layout L2NormToNorm().find_and_replace_pattern(graph) graph_ref = build_graph_with_attrs(nodes + [ ('input', dict(kind='op', shape=input_shape, op='Parameter', data_type=np.float32)), ('input_data', dict(kind='data', shape=input_shape, data_type=np.float32)), ('square_data', dict(kind='data', shape=input_shape)), ('sum_axes_data', dict(kind='data', value=axes, shape=None)), ], edges, nodes_with_edges_only=True) (flag, resp) = compare_graphs(graph, graph_ref, 'result', check_op_attrs=True) self.assertTrue(flag, resp)
[ "openvino.tools.mo.utils.ir_engine.compare_graphs.compare_graphs", "numpy.array", "openvino.tools.mo.middle.L2NormFusing.L2NormToNorm", "openvino.tools.mo.front.common.partial_infer.utils.int64_array" ]
[((5065, 5128), 'openvino.tools.mo.utils.ir_engine.compare_graphs.compare_graphs', 'compare_graphs', (['graph', 'graph_ref', '"""result"""'], {'check_op_attrs': '(True)'}), "(graph, graph_ref, 'result', check_op_attrs=True)\n", (5079, 5128), False, 'from openvino.tools.mo.utils.ir_engine.compare_graphs import compare_graphs\n'), ((8903, 8966), 'openvino.tools.mo.utils.ir_engine.compare_graphs.compare_graphs', 'compare_graphs', (['graph', 'graph_ref', '"""result"""'], {'check_op_attrs': '(True)'}), "(graph, graph_ref, 'result', check_op_attrs=True)\n", (8917, 8966), False, 'from openvino.tools.mo.utils.ir_engine.compare_graphs import compare_graphs\n'), ((777, 812), 'numpy.array', 'np.array', (['(1.2e-12)'], {'dtype': 'np.float32'}), '(1.2e-12, dtype=np.float32)\n', (785, 812), True, 'import numpy as np\n'), ((863, 898), 'numpy.array', 'np.array', (['(1.2e-12)'], {'dtype': 'np.float32'}), '(1.2e-12, dtype=np.float32)\n', (871, 898), True, 'import numpy as np\n'), ((4618, 4632), 'openvino.tools.mo.middle.L2NormFusing.L2NormToNorm', 'L2NormToNorm', ([], {}), '()\n', (4630, 4632), False, 'from openvino.tools.mo.middle.L2NormFusing import L2NormToNorm\n'), ((8406, 8420), 'openvino.tools.mo.middle.L2NormFusing.L2NormToNorm', 'L2NormToNorm', ([], {}), '()\n', (8418, 8420), False, 'from openvino.tools.mo.middle.L2NormFusing import L2NormToNorm\n'), ((2636, 2655), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3]'], {}), '([2, 3])\n', (2647, 2655), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((2657, 2673), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1]'], {}), '([1])\n', (2668, 2673), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((2737, 2756), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3]'], {}), '([2, 3])\n', (2748, 2756), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((2758, 2774), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1]'], {}), '([1])\n', (2769, 2774), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((2838, 2860), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (2849, 2860), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((2862, 2878), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1]'], {}), '([1])\n', (2873, 2878), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((2943, 2965), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (2954, 2965), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((2967, 2983), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1]'], {}), '([1])\n', (2978, 2983), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3048, 3070), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (3059, 3070), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3072, 3093), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[-1, -2]'], {}), '([-1, -2])\n', (3083, 3093), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3160, 3182), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (3171, 3182), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3184, 3205), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[-1, -2]'], {}), '([-1, -2])\n', (3195, 3205), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3272, 3294), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (3283, 3294), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3296, 3315), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 2]'], {}), '([1, 2])\n', (3307, 3315), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3382, 3404), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (3393, 3404), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3406, 3425), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 2]'], {}), '([1, 2])\n', (3417, 3425), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3492, 3517), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (3503, 3517), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3519, 3535), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1]'], {}), '([1])\n', (3530, 3535), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3601, 3626), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (3612, 3626), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3628, 3645), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[-1]'], {}), '([-1])\n', (3639, 3645), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3711, 3736), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (3722, 3736), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3738, 3754), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[3]'], {}), '([3])\n', (3749, 3754), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3820, 3845), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (3831, 3845), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3847, 3870), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[-1, 1, 2]'], {}), '([-1, 1, 2])\n', (3858, 3870), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3939, 3964), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (3950, 3964), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((3966, 3991), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[-3, -2, -1]'], {}), '([-3, -2, -1])\n', (3977, 3991), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5301, 5317), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2]'], {}), '([2])\n', (5312, 5317), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5319, 5335), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0]'], {}), '([0])\n', (5330, 5335), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5363, 5382), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3]'], {}), '([2, 3])\n', (5374, 5382), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5384, 5400), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0]'], {}), '([0])\n', (5395, 5400), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5428, 5447), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3]'], {}), '([2, 3])\n', (5439, 5447), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5449, 5465), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0]'], {}), '([0])\n', (5460, 5465), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5493, 5512), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3]'], {}), '([2, 3])\n', (5504, 5512), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5514, 5533), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0, 1]'], {}), '([0, 1])\n', (5525, 5533), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5561, 5580), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3]'], {}), '([2, 3])\n', (5572, 5580), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5582, 5601), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0, 1]'], {}), '([0, 1])\n', (5593, 5601), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5629, 5651), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (5640, 5651), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5653, 5669), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0]'], {}), '([0])\n', (5664, 5669), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5697, 5719), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (5708, 5719), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5721, 5737), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0]'], {}), '([0])\n', (5732, 5737), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5765, 5787), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (5776, 5787), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5789, 5806), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[-1]'], {}), '([-1])\n', (5800, 5806), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5834, 5856), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (5845, 5856), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5858, 5875), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[-1]'], {}), '([-1])\n', (5869, 5875), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5903, 5925), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (5914, 5925), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5927, 5946), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0, 1]'], {}), '([0, 1])\n', (5938, 5946), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5974, 5996), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (5985, 5996), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((5998, 6017), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0, 1]'], {}), '([0, 1])\n', (6009, 6017), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6045, 6067), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (6056, 6067), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6069, 6088), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0, 2]'], {}), '([0, 2])\n', (6080, 6088), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6116, 6138), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5]'], {}), '([2, 3, 5])\n', (6127, 6138), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6140, 6159), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0, 2]'], {}), '([0, 2])\n', (6151, 6159), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6187, 6212), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (6198, 6212), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6214, 6230), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0]'], {}), '([0])\n', (6225, 6230), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6258, 6283), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (6269, 6283), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6285, 6301), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0]'], {}), '([0])\n', (6296, 6301), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6329, 6354), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (6340, 6354), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6356, 6372), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2]'], {}), '([2])\n', (6367, 6372), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6400, 6425), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (6411, 6425), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6427, 6443), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2]'], {}), '([2])\n', (6438, 6443), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6471, 6496), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (6482, 6496), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6498, 6514), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[3]'], {}), '([3])\n', (6509, 6514), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6542, 6567), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (6553, 6567), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6569, 6585), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1]'], {}), '([1])\n', (6580, 6585), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6613, 6638), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (6624, 6638), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6640, 6659), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 2]'], {}), '([1, 2])\n', (6651, 6659), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6687, 6712), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (6698, 6712), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6714, 6734), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, -1]'], {}), '([1, -1])\n', (6725, 6734), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6762, 6787), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (6773, 6787), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6789, 6809), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, -1]'], {}), '([1, -1])\n', (6800, 6809), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6837, 6862), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (6848, 6862), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6864, 6885), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[-2, -1]'], {}), '([-2, -1])\n', (6875, 6885), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6913, 6938), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (6924, 6938), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6940, 6959), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 3]'], {}), '([1, 3])\n', (6951, 6959), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((6987, 7012), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (6998, 7012), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7014, 7033), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3]'], {}), '([2, 3])\n', (7025, 7033), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7061, 7086), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (7072, 7086), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7088, 7110), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (7099, 7110), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7138, 7163), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (7149, 7163), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7165, 7187), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (7176, 7187), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7215, 7240), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (7226, 7240), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7242, 7264), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0, 2, 3]'], {}), '([0, 2, 3])\n', (7253, 7264), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7292, 7317), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (7303, 7317), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7319, 7341), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0, 2, 3]'], {}), '([0, 2, 3])\n', (7330, 7341), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7369, 7394), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (7380, 7394), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7396, 7421), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0, 1, 2, 3]'], {}), '([0, 1, 2, 3])\n', (7407, 7421), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7449, 7474), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7]'], {}), '([2, 3, 5, 7])\n', (7460, 7474), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7476, 7501), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[0, 1, 2, 3]'], {}), '([0, 1, 2, 3])\n', (7487, 7501), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7529, 7557), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7, 9]'], {}), '([2, 3, 5, 7, 9])\n', (7540, 7557), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7559, 7575), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1]'], {}), '([1])\n', (7570, 7575), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7603, 7631), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7, 9]'], {}), '([2, 3, 5, 7, 9])\n', (7614, 7631), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7633, 7650), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[-1]'], {}), '([-1])\n', (7644, 7650), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7678, 7706), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7, 9]'], {}), '([2, 3, 5, 7, 9])\n', (7689, 7706), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7708, 7733), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (7719, 7733), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7761, 7789), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[2, 3, 5, 7, 9]'], {}), '([2, 3, 5, 7, 9])\n', (7772, 7789), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n'), ((7791, 7820), 'openvino.tools.mo.front.common.partial_infer.utils.int64_array', 'int64_array', (['[-1, -2, -3, -4]'], {}), '([-1, -2, -3, -4])\n', (7802, 7820), False, 'from openvino.tools.mo.front.common.partial_infer.utils import int64_array\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # Copyright (c) 2017 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ============================================================================= # DOC # ============================================================================= """""" # ============================================================================= # IMPORTS # ============================================================================= import numpy as np from .core import Extractor # ============================================================================= # EXTRACTOR CLASS # ============================================================================= class Q31(Extractor): r""" **Q31** (:math:`Q_{3-1}`) :math:`Q_{3-1}` is the difference between the third quartile, :math:`Q_3`, and the first quartile, :math:`Q_1`, of a raw light curve. :math:`Q_1` is a split between the lowest 25% and the highest 75% of data. :math:`Q_3` is a split between the lowest 75% and the highest 25% of data. .. code-block:: pycon >>> fs = feets.FeatureSpace(only=['Q31']) >>> features, values = fs.extract(**lc_normal) >>> dict(zip(features, values)) {'Q31': 1.3320376563134508} References ---------- .. [kim2014epoch] <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2014). The EPOCH Project: I. Periodic Variable Stars in the EROS-2 LMC Database. arXiv preprint Doi:10.1051/0004-6361/201323252. """ data = ["magnitude"] features = ["Q31"] def fit(self, magnitude): q31 = np.percentile(magnitude, 75) - np.percentile(magnitude, 25) return {"Q31": q31} class Q31Color(Extractor): r""" **Q31_color** (:math:`Q_{3-1|B-R}`) :math:`Q_{3-1}` applied to the difference between both bands of a light curve (B-R). .. code-block:: pycon >>> fs = feets.FeatureSpace(only=['Q31_color']) >>> features, values = fs.extract(**lc_normal) >>> dict(zip(features, values)) {'Q31_color': 1.8840489594535512} References ---------- .. [kim2014epoch] <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2014). The EPOCH Project: I. Periodic Variable Stars in the EROS-2 LMC Database. arXiv preprint Doi:10.1051/0004-6361/201323252. """ data = ["aligned_magnitude", "aligned_magnitude2"] features = ["Q31_color"] def fit(self, aligned_magnitude, aligned_magnitude2): N = len(aligned_magnitude) b_r = aligned_magnitude[:N] - aligned_magnitude2[:N] q31_color = np.percentile(b_r, 75) - np.percentile(b_r, 25) return {"Q31_color": q31_color}
[ "numpy.percentile" ]
[((2676, 2704), 'numpy.percentile', 'np.percentile', (['magnitude', '(75)'], {}), '(magnitude, 75)\n', (2689, 2704), True, 'import numpy as np\n'), ((2707, 2735), 'numpy.percentile', 'np.percentile', (['magnitude', '(25)'], {}), '(magnitude, 25)\n', (2720, 2735), True, 'import numpy as np\n'), ((3695, 3717), 'numpy.percentile', 'np.percentile', (['b_r', '(75)'], {}), '(b_r, 75)\n', (3708, 3717), True, 'import numpy as np\n'), ((3720, 3742), 'numpy.percentile', 'np.percentile', (['b_r', '(25)'], {}), '(b_r, 25)\n', (3733, 3742), True, 'import numpy as np\n')]
from cluster.preprocess.pre_node_feed import PreNodeFeed from master.workflow.preprocess.workflow_feed_fr2auto import WorkflowFeedFr2Auto import pandas as pd import warnings import numpy as np from functools import reduce from konlpy.tag import Mecab from common.utils import * class PreNodeFeedFr2Auto(PreNodeFeed): """ """ def run(self, conf_data): """ override init class """ super(PreNodeFeedFr2Auto, self).run(conf_data) self._init_node_parm(conf_data['node_id']) def _get_node_parm(self, node_id): """ return conf master class :return: """ return WorkflowFeedFr2Auto(node_id) def _init_node_parm(self, node_id): """ :param node_id: :return: """ try: wf_conf = WorkflowFeedFr2Auto(node_id) self.wf_conf = wf_conf self.preprocess_type = wf_conf.get_preprocess_type() if (self.preprocess_type in ['frame']): self._init_frame_node_parm(wf_conf) elif (self.preprocess_type in ['mecab', 'kkma', 'twitter']): self._init_nlp_node_parm(wf_conf) insert_dict = {} for key in list(self.__dict__.keys()) : if key in ['preprocess_type','encode_col', 'encode_len', 'embed_type', 'word_vector_size', 'input_size','encode_dtype'] : insert_dict[key] = self.__dict__[key] wf_conf.update_view_obj(node_id, insert_dict) except Exception as e: raise Exception(e) def _init_frame_node_parm(self, wf_conf): """ init parms when data type is frame :param wf_conf: :return: """ self.encode_col = wf_conf.get_encode_column() self.encode_len = {} self.encode_dtype = {} self.encode_onehot = {} self.embed_type = wf_conf.get_embed_type() self.word_vector_size = wf_conf.get_vocab_size() + 4 self.input_size = 0 if (self.embed_type == 'onehot'): if(wf_conf.get_vocab_list()) : encoder_value_list = wf_conf.get_vocab_list() for col_name in list(encoder_value_list.keys()): self.encode_onehot[col_name] = OneHotEncoder(self.word_vector_size) self.encode_onehot[col_name].restore(encoder_value_list.get(col_name)) self._init_frame_node_parm_with_data() def _init_frame_node_parm_with_data(self): """ init pamr s need to be calculated :return:s """ try : store = pd.HDFStore(self.input_paths[0]) chunk = store.select('table1', start=0, stop=100) for col_name in self.encode_col: if (self.encode_len.get(col_name) == None): if (chunk[col_name].dtype in ['int', 'float']): self.encode_len[col_name] = 1 self.input_size = self.input_size + 1 else: self.encode_len[col_name] = self.word_vector_size self.input_size = self.input_size + self.word_vector_size self.encode_onehot[col_name] = OneHotEncoder(self.word_vector_size) self.encode_dtype[col_name] = str(chunk[col_name].dtype) except Exception as e : raise Exception ("error on wcnn feed parm prepare : {0}".format(e)) def _init_nlp_node_parm(self, wf_conf): """ init parms when data type is nlp :param wf_conf: :return: """ self.encode_col = wf_conf.get_encode_column() self.encode_len = wf_conf.get_encode_len() self.embed_type = wf_conf.get_embed_type() self.word_vector_size = wf_conf.get_vocab_size() + 4 self.input_size = int(self.encode_len) * int(self.word_vector_size) if (self.embed_type == 'onehot'): self.onehot_encoder = OneHotEncoder(self.word_vector_size) if (wf_conf.get_vocab_list()): self.onehot_encoder.restore(wf_conf.get_vocab_list()) def _convert_data_format(self, file_path, index): """ convert variois data to matrix fit to autoencoder :param obj: :param index: :return: """ if(self.preprocess_type in ['frame']) : return self._frame_parser(file_path, index) elif(self.preprocess_type in ['mecab', 'kkma', 'twitter']) : return self._nlp_parser(file_path, index) def _frame_parser(self, file_path, index): """ parse nlp data :return: """ try : store = pd.HDFStore(file_path) chunk = store.select('table1', start=index.start, stop=index.stop) input_vector = [] count = index.stop - index.start for col_name in self.encode_col: if (chunk[col_name].dtype == 'O'): input_vector.append(list(map(lambda x: self.encode_onehot[col_name].get_vector(x), chunk[col_name][0:count].tolist()))) else : input_vector.append(np.array(list(map(lambda x: [self._filter_nan(x)], chunk[col_name][0:count].tolist())))) return self._flat_data(input_vector, len(chunk[col_name][0:count].tolist())) except Exception as e : raise Exception (e) finally: store.close() def _filter_nan(self, x): """ map nan to 0 :param x: :return: """ import math if(math.isnan(x)) : return 0.0 else : return x def _flat_data(self, input_vector, count): """ :param input_vector: :return: """ try : result = [] for i in range(count) : row = [] for col in input_vector : row = row + col[i].tolist() result.append(row) return np.array(result, dtype='f') except Exception as e : raise Exception ("wcnn data prepare flat_data error : {0}".format(e)) def _nlp_parser(self, file_path, index): """ parse nlp data :return: """ try : store = pd.HDFStore(file_path) chunk = store.select('table1', start=index.start, stop=index.stop) count = index.stop - index.start if (self.encode_col in chunk): encode = self.encode_pad(self._preprocess(chunk[self.encode_col].values)[0:count], max_len=self.encode_len) return self._word_embed_data(self.embed_type, encode) else: warnings.warn("not exists column names requested !!") return [['#'] * self.encode_len] except Exception as e : raise Exception (e) finally: store.close() def _preprocess(self, input_data): """ :param input_data: :return: """ if(self.preprocess_type == 'mecab') : return self._mecab_parse(input_data) elif (self.preprocess_type == 'kkma'): return self._mecab_parse(input_data) elif (self.preprocess_type == 'twitter'): return self._mecab_parse(input_data) else : return input_data def data_size(self): """ get data array size of this calss :return: """ try : store = pd.HDFStore(self.input_paths[self.pointer]) table_data = store.select('table1') return table_data[table_data.columns.values[0]].count() except Exception as e : raise Exception (e) finally: store.close() def has_next(self): """ check if hdf5 file pointer has next :return: """ if(len(self.input_paths) > self.pointer) : return True else : if (self.preprocess_type in ['frame']): if (self.embed_type == 'onehot'): save_dic = {} for col_name in self.encode_col: save_dic[col_name] = self.encode_onehot[col_name].dics() self.wf_conf.set_vocab_list(save_dic) return False elif (self.preprocess_type in ['mecab', 'kkma', 'twitter']): if (self.embed_type == 'onehot'): self.wf_conf.set_vocab_list(self.onehot_encoder.dics()) return False
[ "numpy.array", "master.workflow.preprocess.workflow_feed_fr2auto.WorkflowFeedFr2Auto", "warnings.warn", "pandas.HDFStore", "math.isnan" ]
[((653, 681), 'master.workflow.preprocess.workflow_feed_fr2auto.WorkflowFeedFr2Auto', 'WorkflowFeedFr2Auto', (['node_id'], {}), '(node_id)\n', (672, 681), False, 'from master.workflow.preprocess.workflow_feed_fr2auto import WorkflowFeedFr2Auto\n'), ((5819, 5832), 'math.isnan', 'math.isnan', (['x'], {}), '(x)\n', (5829, 5832), False, 'import math\n'), ((824, 852), 'master.workflow.preprocess.workflow_feed_fr2auto.WorkflowFeedFr2Auto', 'WorkflowFeedFr2Auto', (['node_id'], {}), '(node_id)\n', (843, 852), False, 'from master.workflow.preprocess.workflow_feed_fr2auto import WorkflowFeedFr2Auto\n'), ((2655, 2687), 'pandas.HDFStore', 'pd.HDFStore', (['self.input_paths[0]'], {}), '(self.input_paths[0])\n', (2666, 2687), True, 'import pandas as pd\n'), ((4804, 4826), 'pandas.HDFStore', 'pd.HDFStore', (['file_path'], {}), '(file_path)\n', (4815, 4826), True, 'import pandas as pd\n'), ((6257, 6284), 'numpy.array', 'np.array', (['result'], {'dtype': '"""f"""'}), "(result, dtype='f')\n", (6265, 6284), True, 'import numpy as np\n'), ((6543, 6565), 'pandas.HDFStore', 'pd.HDFStore', (['file_path'], {}), '(file_path)\n', (6554, 6565), True, 'import pandas as pd\n'), ((7865, 7908), 'pandas.HDFStore', 'pd.HDFStore', (['self.input_paths[self.pointer]'], {}), '(self.input_paths[self.pointer])\n', (7876, 7908), True, 'import pandas as pd\n'), ((7068, 7121), 'warnings.warn', 'warnings.warn', (['"""not exists column names requested !!"""'], {}), "('not exists column names requested !!')\n", (7081, 7121), False, 'import warnings\n')]
import turbpy.multiConst as mc import numpy as np def bulkRichardson(airTemp, # air temperature (K) sfcTemp, # surface temperature (K) windspd, # wind speed (m s-1) mHeight, # measurement height (m) ): # ------------------------------------------------------------------------------------------------------- # Local variables if np.max(airTemp) < 200: airTemp = airTemp + 273.15 if np.max(sfcTemp) < 200: sfcTemp = sfcTemp + 273.15 T_grad = airTemp - sfcTemp T_mean = 0.5 * (airTemp + sfcTemp) RiMult = (mc.gravity * mHeight) / (windspd**2.) # compute the Richardson number RiBulk = (T_grad / T_mean) * RiMult return (RiBulk) # bulk Richardson number (-)
[ "numpy.max" ]
[((486, 501), 'numpy.max', 'np.max', (['airTemp'], {}), '(airTemp)\n', (492, 501), True, 'import numpy as np\n'), ((551, 566), 'numpy.max', 'np.max', (['sfcTemp'], {}), '(sfcTemp)\n', (557, 566), True, 'import numpy as np\n')]
import argparse import os import numpy as np from PIL import Image from imgaug import augmenters as iaa ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Input image path") ap.add_argument("-o", "--output", required=False, default="prspt-transf", help="Output folder") args = vars(ap.parse_args()) imagefile = args["image"] if not os.path.exists(imagefile): print("Not found {}...".format(imagefile)) exit(1) original = Image.open(imagefile) original = np.array(original)[48:481, :] original = np.array(Image.fromarray(original).resize((512, 256))) image = original.copy() seq = iaa.Sequential([ iaa.PerspectiveTransform(scale=(0.01, 0.1)) ]) image = seq.augment_image(image) Image.fromarray(original).show() Image.fromarray(image).show() if input("Save? ") in ["yes", "y", "yep"]: os.makedirs(args["output"], exist_ok=True) id = "" if input("Identifier (yes/no)? ") in ["yes", "y", "yep"]: id = input("\tEnter id: ") outname = os.path.join(args["output"], id + os.path.basename(imagefile)) print("Saving at {}".format(outname)) Image.fromarray(image).save(outname) print("Done...")
[ "os.path.exists", "PIL.Image.fromarray", "PIL.Image.open", "os.makedirs", "argparse.ArgumentParser", "numpy.array", "imgaug.augmenters.PerspectiveTransform", "os.path.basename" ]
[((111, 136), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (134, 136), False, 'import argparse\n'), ((469, 490), 'PIL.Image.open', 'Image.open', (['imagefile'], {}), '(imagefile)\n', (479, 490), False, 'from PIL import Image\n'), ((371, 396), 'os.path.exists', 'os.path.exists', (['imagefile'], {}), '(imagefile)\n', (385, 396), False, 'import os\n'), ((502, 520), 'numpy.array', 'np.array', (['original'], {}), '(original)\n', (510, 520), True, 'import numpy as np\n'), ((842, 884), 'os.makedirs', 'os.makedirs', (["args['output']"], {'exist_ok': '(True)'}), "(args['output'], exist_ok=True)\n", (853, 884), False, 'import os\n'), ((650, 693), 'imgaug.augmenters.PerspectiveTransform', 'iaa.PerspectiveTransform', ([], {'scale': '(0.01, 0.1)'}), '(scale=(0.01, 0.1))\n', (674, 693), True, 'from imgaug import augmenters as iaa\n'), ((731, 756), 'PIL.Image.fromarray', 'Image.fromarray', (['original'], {}), '(original)\n', (746, 756), False, 'from PIL import Image\n'), ((764, 786), 'PIL.Image.fromarray', 'Image.fromarray', (['image'], {}), '(image)\n', (779, 786), False, 'from PIL import Image\n'), ((552, 577), 'PIL.Image.fromarray', 'Image.fromarray', (['original'], {}), '(original)\n', (567, 577), False, 'from PIL import Image\n'), ((1044, 1071), 'os.path.basename', 'os.path.basename', (['imagefile'], {}), '(imagefile)\n', (1060, 1071), False, 'import os\n'), ((1120, 1142), 'PIL.Image.fromarray', 'Image.fromarray', (['image'], {}), '(image)\n', (1135, 1142), False, 'from PIL import Image\n')]
from rllab.envs.mujoco.ant_env_rand_crippled_joints import AntEnvRandDisable import numpy as np env = AntEnvRandDisable() init_state = env.reset(reset_args= 3) new_obs = init_state for i in range(8000): env.render() action = np.random.uniform(-1.0, 1.0, env.action_space.shape[0]) print(env.model.geom_size) #env.reset(init_state=new_obs) new_obs, reward, _, _ = env.step(action) #print(new_obs[0])
[ "rllab.envs.mujoco.ant_env_rand_crippled_joints.AntEnvRandDisable", "numpy.random.uniform" ]
[((103, 122), 'rllab.envs.mujoco.ant_env_rand_crippled_joints.AntEnvRandDisable', 'AntEnvRandDisable', ([], {}), '()\n', (120, 122), False, 'from rllab.envs.mujoco.ant_env_rand_crippled_joints import AntEnvRandDisable\n'), ((235, 290), 'numpy.random.uniform', 'np.random.uniform', (['(-1.0)', '(1.0)', 'env.action_space.shape[0]'], {}), '(-1.0, 1.0, env.action_space.shape[0])\n', (252, 290), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Date created: 03 August 2016 @author : <NAME> @description : Velocity magnitudes calculator """ import numpy as np import csv # 1 xyz = np.zeros([0,3]) # Replace '3' with the number of columns in your csv file # 2 with open ('hemeLB-csv-file-name') as csvfile: file = csv.reader(csvfile) # 3 for row in file: xyz = np.vstack([xyz,[float(row[0]), float(row[1]), float(row[2])]]) """ For more than 1 column: x = np.vstack([x,[float(row[0]), float(row[1]), ...(..)]]) ! The number inside [float(row[number])] indicates the index number of columns. ! Remember that index number in computer start from 0 """ #4 magnitudes = np.sqrt(xyz[:,0]*xyz[:,0] + xyz[:,1]*xyz[:,1] + xyz[:,2]*xyz[:,2]) print(magnitudes)
[ "numpy.zeros", "numpy.sqrt", "csv.reader" ]
[((182, 198), 'numpy.zeros', 'np.zeros', (['[0, 3]'], {}), '([0, 3])\n', (190, 198), True, 'import numpy as np\n'), ((769, 847), 'numpy.sqrt', 'np.sqrt', (['(xyz[:, 0] * xyz[:, 0] + xyz[:, 1] * xyz[:, 1] + xyz[:, 2] * xyz[:, 2])'], {}), '(xyz[:, 0] * xyz[:, 0] + xyz[:, 1] * xyz[:, 1] + xyz[:, 2] * xyz[:, 2])\n', (776, 847), True, 'import numpy as np\n'), ((323, 342), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (333, 342), False, 'import csv\n')]
import matplotlib.pyplot as plt import pandas as pd import numpy as np import os from biopandas.pdb import PandasPdb from scipy.spatial.distance import squareform, pdist def remove_ipynb_checkpoints(path): flag = False for i in range(len(os.listdir(path))): if (os.listdir(path)[i] == '.ipynb_checkpoints'): flag = True if flag: os.rmdir(f'{path}/.ipynb_checkpoints') def pdb_to_coords(path, index): # Generate data from from a chosen dirrectory ppdb = PandasPdb().read_pdb(f'{path}/{os.listdir(path)[index]}') protein_df = ppdb.df['ATOM'] df_new = protein_df[(protein_df['atom_name'] == 'CA') & (protein_df['residue_name'] == amino_acid) & (protein_df['chain_id'] == chain_id)] # Pull the 3D coordinates out of the dataframe # 11:14 are the columns with the x, y, z coordinates. monomer_coords = df_new.values[:, 11:14] return monomer_coords # Generate symmetry mate def generate_dimer_coords(coords, matrix, ajustment): # List comprehension anti_coords = [np.dot(matrix, coord) for coord in coords] # # Old method # anti_coords = [] # for coord in coords: # anti_coords.append(np.dot(matrix, coord)) # Convert to numpy array anti_coords = np.array(anti_coords) mirror_coords = anti_coords + ajustment dimer_coords = np.append(coords, mirror_coords, axis=0) return dimer_coords def calc_dist(coords, cutoff): # dist is a square 2D numpy array (i.e. a matrix with the same # of rows and columns) # dist has a diagonal of zeros and is symmetric (has duplicate values on either side of the diagonal) dist = squareform(pdist(coords, 'euclidean')) # dist looks like: # [0, 1, 2] # [1, 0, 3] # [2, 3, 0] # Remove the duplicate values by extracting the upper triangle of the dist matrix upper_triangle = np.triu(dist) # upper_triangle looks like: # [0, 1, 2] # [0, 0, 3] # [0, 0, 0] # Remove zeros distances = upper_triangle[upper_triangle != 0] # distances looks like: [1, 2, 3] distances = distances[distances < cutoff] return distances def display_hist(distances, histo_bins, hist_color, title): plt.hist(distances, bins = histo_bins, density = True, color = hist_color) plt.xlabel("Distance in angstroms") plt.ylabel("Number of occurrences") plt.title(title) plt.show() # Parameters amino_acid = 'ASN' taxa = 'psychro' # You can find the following two parameter on a pdb code at REMARK 350 # Rotational symmetry operator matrix_1ab4 = np.array([[-1, 0, 0], [0, -1, 0], [0, 0, 1]]) # Translational symmetry operator ajustment_1ab4 = [119.63, 119.63, 0] # defaults chain_id = 'A' atomic_dist_cutoff = 20 histo_bins = 20 hist_color = 'turquoise' distances_combined = [] pdb_directory = f'/Users/averyhill/MyDocuments/schoeffler_research_summer_2021/pdbs/{taxa}philes/{taxa}_gyra_pdb_folder' pdb_count = len(os.listdir(pdb_directory)) # Jupyter notebook will often put checkipoints into folders, this functions removes them remove_ipynb_checkpoints(pdb_directory) for i in range(pdb_count): # Get monomer coordinates from pdb_to_coords() monomer_coords = pdb_to_coords(pdb_directory, i) # Dimerize the monomer coordinates using generate_dimer() dimer_coords = generate_dimer_coords(monomer_coords, matrix_1ab4, ajustment_1ab4) # Convert numpy array to dataframe because calc_dist only accepts dataframes dimer_coord_array = pd.DataFrame(dimer_coords, columns = ['x_coord','y_coord','z_coord']) # Calculate the distance between the coordinates using calc_dist() distances = calc_dist(dimer_coord_array, atomic_dist_cutoff) # Sum the distances distances_combined = np.append(distances_combined, distances) # Show the histogram of the summed distances using display_hist display_hist(distances_combined, histo_bins, hist_color, taxa)
[ "os.listdir", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel", "scipy.spatial.distance.pdist", "matplotlib.pyplot.xlabel", "numpy.append", "numpy.array", "os.rmdir", "numpy.dot", "pandas.DataFrame", "matplotlib.pyplot.title", "biopandas.pdb.PandasPdb", "numpy.triu", "matplotlib.pyplot...
[((2590, 2635), 'numpy.array', 'np.array', (['[[-1, 0, 0], [0, -1, 0], [0, 0, 1]]'], {}), '([[-1, 0, 0], [0, -1, 0], [0, 0, 1]])\n', (2598, 2635), True, 'import numpy as np\n'), ((1267, 1288), 'numpy.array', 'np.array', (['anti_coords'], {}), '(anti_coords)\n', (1275, 1288), True, 'import numpy as np\n'), ((1354, 1394), 'numpy.append', 'np.append', (['coords', 'mirror_coords'], {'axis': '(0)'}), '(coords, mirror_coords, axis=0)\n', (1363, 1394), True, 'import numpy as np\n'), ((1884, 1897), 'numpy.triu', 'np.triu', (['dist'], {}), '(dist)\n', (1891, 1897), True, 'import numpy as np\n'), ((2229, 2297), 'matplotlib.pyplot.hist', 'plt.hist', (['distances'], {'bins': 'histo_bins', 'density': '(True)', 'color': 'hist_color'}), '(distances, bins=histo_bins, density=True, color=hist_color)\n', (2237, 2297), True, 'import matplotlib.pyplot as plt\n'), ((2308, 2343), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Distance in angstroms"""'], {}), "('Distance in angstroms')\n", (2318, 2343), True, 'import matplotlib.pyplot as plt\n'), ((2348, 2383), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of occurrences"""'], {}), "('Number of occurrences')\n", (2358, 2383), True, 'import matplotlib.pyplot as plt\n'), ((2388, 2404), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2397, 2404), True, 'import matplotlib.pyplot as plt\n'), ((2409, 2419), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2417, 2419), True, 'import matplotlib.pyplot as plt\n'), ((3013, 3038), 'os.listdir', 'os.listdir', (['pdb_directory'], {}), '(pdb_directory)\n', (3023, 3038), False, 'import os\n'), ((3557, 3626), 'pandas.DataFrame', 'pd.DataFrame', (['dimer_coords'], {'columns': "['x_coord', 'y_coord', 'z_coord']"}), "(dimer_coords, columns=['x_coord', 'y_coord', 'z_coord'])\n", (3569, 3626), True, 'import pandas as pd\n'), ((3814, 3854), 'numpy.append', 'np.append', (['distances_combined', 'distances'], {}), '(distances_combined, distances)\n', (3823, 3854), True, 'import numpy as np\n'), ((375, 413), 'os.rmdir', 'os.rmdir', (['f"""{path}/.ipynb_checkpoints"""'], {}), "(f'{path}/.ipynb_checkpoints')\n", (383, 413), False, 'import os\n'), ((1054, 1075), 'numpy.dot', 'np.dot', (['matrix', 'coord'], {}), '(matrix, coord)\n', (1060, 1075), True, 'import numpy as np\n'), ((1676, 1702), 'scipy.spatial.distance.pdist', 'pdist', (['coords', '"""euclidean"""'], {}), "(coords, 'euclidean')\n", (1681, 1702), False, 'from scipy.spatial.distance import squareform, pdist\n'), ((252, 268), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (262, 268), False, 'import os\n'), ((508, 519), 'biopandas.pdb.PandasPdb', 'PandasPdb', ([], {}), '()\n', (517, 519), False, 'from biopandas.pdb import PandasPdb\n'), ((284, 300), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (294, 300), False, 'import os\n'), ((539, 555), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (549, 555), False, 'import os\n')]
# Authors: <NAME> # <NAME> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.size']=6 from scipy import linalg import pandas as pd from sklearn.decomposition import PCA, FactorAnalysis from sklearn.covariance import ShrunkCovariance, LedoitWolf from sklearn.model_selection import cross_val_score from sklearn.model_selection import GridSearchCV print(__doc__) import os root_path = os.path.dirname(os.path.abspath('__file__')) root_path = os.path.abspath(os.path.join(root_path,os.path.pardir)) # For run in CMD graphs_path = root_path+'\\results_analysis\\graphs\\' # ############################################################################# # Create the data def model_select_pca(station,decomposer,predict_pattern,ax=None,wavelet_level='db10-2'): # Set project parameters STATION = station DECOMPOSER = decomposer PREDICT_PATTERN = predict_pattern # hindcast or forecast SIGNALS = STATION+'_'+DECOMPOSER # Set parameters for PCA # load one-step one-month forecast or hindcast samples and the normalization indicators if decomposer=='dwt': train = pd.read_csv(root_path+'/'+SIGNALS+'/data/'+wavelet_level+'/'+PREDICT_PATTERN+'/minmax_unsample_train.csv') dev = pd.read_csv(root_path+'/'+SIGNALS+'/data/'+wavelet_level+'/'+PREDICT_PATTERN+'/minmax_unsample_dev.csv') test = pd.read_csv(root_path+'/'+SIGNALS+'/data/'+wavelet_level+'/'+PREDICT_PATTERN+'/minmax_unsample_test.csv') norm_id = pd.read_csv(root_path+'/'+SIGNALS+'/data/'+wavelet_level+'/'+PREDICT_PATTERN+'/norm_unsample_id.csv') else: train = pd.read_csv(root_path+'/'+SIGNALS+'/data/'+PREDICT_PATTERN+'/minmax_unsample_train.csv') dev = pd.read_csv(root_path+'/'+SIGNALS+'/data/'+PREDICT_PATTERN+'/minmax_unsample_dev.csv') test = pd.read_csv(root_path+'/'+SIGNALS+'/data/'+PREDICT_PATTERN+'/minmax_unsample_test.csv') norm_id = pd.read_csv(root_path+'/'+SIGNALS+'/data/'+PREDICT_PATTERN+'/norm_unsample_id.csv') sMax = (norm_id['series_max']).values sMin = (norm_id['series_min']).values # Conncat the training, development and testing samples samples = pd.concat([train,dev,test],axis=0) samples = samples.reset_index(drop=True) # Renormalized the entire samples samples = np.multiply(samples + 1,sMax - sMin) / 2 + sMin y = samples['Y'] X = samples.drop('Y',axis=1) # ############################################################################# # Fit the models n_features = X.shape[1] print("Number of features:{}".format(n_features)) n_components = np.arange(0, n_features, 5) # options for n_components def compute_scores(X): pca = PCA(svd_solver='full') fa = FactorAnalysis() pca_scores, fa_scores = [], [] for n in n_components: pca.n_components = n fa.n_components = n pca_scores.append(np.mean(cross_val_score(pca, X, cv=5))) fa_scores.append(np.mean(cross_val_score(fa, X, cv=5))) return pca_scores, fa_scores def shrunk_cov_score(X): shrinkages = np.logspace(-2, 0, 30) cv = GridSearchCV(ShrunkCovariance(), {'shrinkage': shrinkages}, cv=5) return np.mean(cross_val_score(cv.fit(X).best_estimator_, X, cv=5)) def lw_score(X): return np.mean(cross_val_score(LedoitWolf(), X, cv=5)) pca_scores, fa_scores = compute_scores(X) n_components_pca = n_components[np.argmax(pca_scores)] n_components_fa = n_components[np.argmax(fa_scores)] pca = PCA(svd_solver='full', n_components='mle') pca.fit(X) n_components_pca_mle = pca.n_components_ print("best n_components by PCA CV = %d" % n_components_pca) print("best n_components by FactorAnalysis CV = %d" % n_components_fa) print("best n_components by PCA MLE = %d" % n_components_pca_mle) if ax==None: plt.figure(figsize=(5.5139,3.5139)) plt.plot(n_components, pca_scores, 'b', label='PCA scores') plt.plot(n_components, fa_scores, 'r', label='FA scores') plt.axvline(n_components_pca, color='b', label='PCA CV: %d' % n_components_pca, linestyle='--') plt.axvline(n_components_fa, color='r', label='FactorAnalysis CV: %d' % n_components_fa, linestyle='--') plt.axvline(n_components_pca_mle, color='k', label='PCA MLE: %d' % n_components_pca_mle, linestyle='--') # compare with other covariance estimators plt.axhline(shrunk_cov_score(X), color='violet', label='Shrunk Covariance MLE', linestyle='-.') plt.axhline(lw_score(X), color='orange', label='LedoitWolf MLE' % n_components_pca_mle, linestyle='-.') plt.xlabel('Number of components') plt.ylabel('CV scores') plt.legend(loc='lower right') plt.tight_layout() plt.savefig(graphs_path+"two_stage_pca_fa_analysis_"+station+"_"+decomposer+".eps",format="EPS",dpi=2000) plt.savefig(graphs_path+"two_stage_pca_fa_analysis_"+station+"_"+decomposer+".tif",format="TIFF",dpi=1200) plt.show() else: ax.plot(n_components, pca_scores, 'b', label='PCA scores') ax.plot(n_components, fa_scores, 'r', label='FA scores') ax.axvline(n_components_pca, color='b', label='PCA CV: %d' % n_components_pca, linestyle='--') ax.axvline(n_components_fa, color='r', label='FactorAnalysis CV: %d' % n_components_fa, linestyle='--') ax.axvline(n_components_pca_mle, color='k', label='PCA MLE: %d' % n_components_pca_mle, linestyle='--') # compare with other covariance estimators ax.axhline(shrunk_cov_score(X), color='violet', label='Shrunk Covariance MLE', linestyle='-.') ax.axhline(lw_score(X), color='orange', label='LedoitWolf MLE' % n_components_pca_mle, linestyle='-.') ax.set_xlabel('Number of components') ax.set_ylabel('CV scores') ax.legend(loc='lower right') plt.tight_layout() # plt.savefig(graphs_path+"two_stage_pca_fa_analysis_"+station+"_"+decomposer+".eps",format="EPS",dpi=2000) # plt.savefig(graphs_path+"two_stage_pca_fa_analysis_"+station+"_"+decomposer+".tif",format="TIFF",dpi=1200) # plt.show() return ax if __name__ == "__main__": plt.figure(figsize=(7.48,7.48)) ax1=plt.subplot(3,4,1) ax2=plt.subplot(3,4,2) ax3=plt.subplot(3,4,3) ax4=plt.subplot(3,4,4) ax5=plt.subplot(3,4,5) ax6=plt.subplot(3,4,6) ax7=plt.subplot(3,4,7) ax8=plt.subplot(3,4,8) ax9=plt.subplot(3,4,9) ax10=plt.subplot(3,4,10) ax11=plt.subplot(3,4,11) ax12=plt.subplot(3,4,12) model_select_pca(station='Huaxian',decomposer='eemd',predict_pattern='one_step_1_month_forecast',ax=ax1) model_select_pca(station='Huaxian',decomposer='ssa',predict_pattern='one_step_1_month_forecast',ax=ax2) model_select_pca(station='Huaxian',decomposer='vmd',predict_pattern='one_step_1_month_forecast',ax=ax3) model_select_pca(station='Huaxian',decomposer='dwt',predict_pattern='one_step_1_month_forecast',ax=ax4) model_select_pca(station='Xianyang',decomposer='eemd',predict_pattern='one_step_1_month_forecast',ax=ax5) model_select_pca(station='Xianyang',decomposer='ssa',predict_pattern='one_step_1_month_forecast',ax=ax6) model_select_pca(station='Xianyang',decomposer='vmd',predict_pattern='one_step_1_month_forecast',ax=ax7) model_select_pca(station='Xianyang',decomposer='dwt',predict_pattern='one_step_1_month_forecast',ax=ax8) model_select_pca(station='Zhangjiashan',decomposer='eemd',predict_pattern='one_step_1_month_forecast',ax=ax9) model_select_pca(station='Zhangjiashan',decomposer='ssa',predict_pattern='one_step_1_month_forecast',ax=ax10) model_select_pca(station='Zhangjiashan',decomposer='vmd',predict_pattern='one_step_1_month_forecast',ax=ax11) model_select_pca(station='Zhangjiashan',decomposer='dwt',predict_pattern='one_step_1_month_forecast',ax=ax12) plt.savefig(graphs_path+"PCA_FA_analysis.eps",format="EPS",dpi=2000) plt.savefig(graphs_path+"PCA_FA_analysis.tif",format="TIFF",dpi=1200) plt.show()
[ "pandas.read_csv", "matplotlib.pyplot.ylabel", "sklearn.covariance.ShrunkCovariance", "numpy.arange", "numpy.multiply", "sklearn.decomposition.PCA", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "pandas.concat", "numpy.logspace", "sklearn.model_selection.cross_val_score", "matplotlib.p...
[((456, 483), 'os.path.abspath', 'os.path.abspath', (['"""__file__"""'], {}), "('__file__')\n", (471, 483), False, 'import os\n'), ((513, 552), 'os.path.join', 'os.path.join', (['root_path', 'os.path.pardir'], {}), '(root_path, os.path.pardir)\n', (525, 552), False, 'import os\n'), ((2201, 2238), 'pandas.concat', 'pd.concat', (['[train, dev, test]'], {'axis': '(0)'}), '([train, dev, test], axis=0)\n', (2210, 2238), True, 'import pandas as pd\n'), ((2647, 2674), 'numpy.arange', 'np.arange', (['(0)', 'n_features', '(5)'], {}), '(0, n_features, 5)\n', (2656, 2674), True, 'import numpy as np\n'), ((3607, 3649), 'sklearn.decomposition.PCA', 'PCA', ([], {'svd_solver': '"""full"""', 'n_components': '"""mle"""'}), "(svd_solver='full', n_components='mle')\n", (3610, 3649), False, 'from sklearn.decomposition import PCA, FactorAnalysis\n'), ((6521, 6553), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(7.48, 7.48)'}), '(figsize=(7.48, 7.48))\n', (6531, 6553), True, 'import matplotlib.pyplot as plt\n'), ((6561, 6581), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(1)'], {}), '(3, 4, 1)\n', (6572, 6581), True, 'import matplotlib.pyplot as plt\n'), ((6588, 6608), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(2)'], {}), '(3, 4, 2)\n', (6599, 6608), True, 'import matplotlib.pyplot as plt\n'), ((6615, 6635), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(3)'], {}), '(3, 4, 3)\n', (6626, 6635), True, 'import matplotlib.pyplot as plt\n'), ((6642, 6662), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(4)'], {}), '(3, 4, 4)\n', (6653, 6662), True, 'import matplotlib.pyplot as plt\n'), ((6669, 6689), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(5)'], {}), '(3, 4, 5)\n', (6680, 6689), True, 'import matplotlib.pyplot as plt\n'), ((6696, 6716), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(6)'], {}), '(3, 4, 6)\n', (6707, 6716), True, 'import matplotlib.pyplot as plt\n'), ((6723, 6743), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(7)'], {}), '(3, 4, 7)\n', (6734, 6743), True, 'import matplotlib.pyplot as plt\n'), ((6750, 6770), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(8)'], {}), '(3, 4, 8)\n', (6761, 6770), True, 'import matplotlib.pyplot as plt\n'), ((6777, 6797), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(9)'], {}), '(3, 4, 9)\n', (6788, 6797), True, 'import matplotlib.pyplot as plt\n'), ((6805, 6826), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(10)'], {}), '(3, 4, 10)\n', (6816, 6826), True, 'import matplotlib.pyplot as plt\n'), ((6834, 6855), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(11)'], {}), '(3, 4, 11)\n', (6845, 6855), True, 'import matplotlib.pyplot as plt\n'), ((6863, 6884), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(12)'], {}), '(3, 4, 12)\n', (6874, 6884), True, 'import matplotlib.pyplot as plt\n'), ((8213, 8285), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(graphs_path + 'PCA_FA_analysis.eps')"], {'format': '"""EPS"""', 'dpi': '(2000)'}), "(graphs_path + 'PCA_FA_analysis.eps', format='EPS', dpi=2000)\n", (8224, 8285), True, 'import matplotlib.pyplot as plt\n'), ((8286, 8359), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(graphs_path + 'PCA_FA_analysis.tif')"], {'format': '"""TIFF"""', 'dpi': '(1200)'}), "(graphs_path + 'PCA_FA_analysis.tif', format='TIFF', dpi=1200)\n", (8297, 8359), True, 'import matplotlib.pyplot as plt\n'), ((8360, 8370), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8368, 8370), True, 'import matplotlib.pyplot as plt\n'), ((1155, 1279), 'pandas.read_csv', 'pd.read_csv', (["(root_path + '/' + SIGNALS + '/data/' + wavelet_level + '/' +\n PREDICT_PATTERN + '/minmax_unsample_train.csv')"], {}), "(root_path + '/' + SIGNALS + '/data/' + wavelet_level + '/' +\n PREDICT_PATTERN + '/minmax_unsample_train.csv')\n", (1166, 1279), True, 'import pandas as pd\n'), ((1276, 1398), 'pandas.read_csv', 'pd.read_csv', (["(root_path + '/' + SIGNALS + '/data/' + wavelet_level + '/' +\n PREDICT_PATTERN + '/minmax_unsample_dev.csv')"], {}), "(root_path + '/' + SIGNALS + '/data/' + wavelet_level + '/' +\n PREDICT_PATTERN + '/minmax_unsample_dev.csv')\n", (1287, 1398), True, 'import pandas as pd\n'), ((1396, 1519), 'pandas.read_csv', 'pd.read_csv', (["(root_path + '/' + SIGNALS + '/data/' + wavelet_level + '/' +\n PREDICT_PATTERN + '/minmax_unsample_test.csv')"], {}), "(root_path + '/' + SIGNALS + '/data/' + wavelet_level + '/' +\n PREDICT_PATTERN + '/minmax_unsample_test.csv')\n", (1407, 1519), True, 'import pandas as pd\n'), ((1520, 1639), 'pandas.read_csv', 'pd.read_csv', (["(root_path + '/' + SIGNALS + '/data/' + wavelet_level + '/' +\n PREDICT_PATTERN + '/norm_unsample_id.csv')"], {}), "(root_path + '/' + SIGNALS + '/data/' + wavelet_level + '/' +\n PREDICT_PATTERN + '/norm_unsample_id.csv')\n", (1531, 1639), True, 'import pandas as pd\n'), ((1648, 1750), 'pandas.read_csv', 'pd.read_csv', (["(root_path + '/' + SIGNALS + '/data/' + PREDICT_PATTERN +\n '/minmax_unsample_train.csv')"], {}), "(root_path + '/' + SIGNALS + '/data/' + PREDICT_PATTERN +\n '/minmax_unsample_train.csv')\n", (1659, 1750), True, 'import pandas as pd\n'), ((1751, 1851), 'pandas.read_csv', 'pd.read_csv', (["(root_path + '/' + SIGNALS + '/data/' + PREDICT_PATTERN +\n '/minmax_unsample_dev.csv')"], {}), "(root_path + '/' + SIGNALS + '/data/' + PREDICT_PATTERN +\n '/minmax_unsample_dev.csv')\n", (1762, 1851), True, 'import pandas as pd\n'), ((1853, 1954), 'pandas.read_csv', 'pd.read_csv', (["(root_path + '/' + SIGNALS + '/data/' + PREDICT_PATTERN +\n '/minmax_unsample_test.csv')"], {}), "(root_path + '/' + SIGNALS + '/data/' + PREDICT_PATTERN +\n '/minmax_unsample_test.csv')\n", (1864, 1954), True, 'import pandas as pd\n'), ((1959, 2056), 'pandas.read_csv', 'pd.read_csv', (["(root_path + '/' + SIGNALS + '/data/' + PREDICT_PATTERN +\n '/norm_unsample_id.csv')"], {}), "(root_path + '/' + SIGNALS + '/data/' + PREDICT_PATTERN +\n '/norm_unsample_id.csv')\n", (1970, 2056), True, 'import pandas as pd\n'), ((2744, 2766), 'sklearn.decomposition.PCA', 'PCA', ([], {'svd_solver': '"""full"""'}), "(svd_solver='full')\n", (2747, 2766), False, 'from sklearn.decomposition import PCA, FactorAnalysis\n'), ((2780, 2796), 'sklearn.decomposition.FactorAnalysis', 'FactorAnalysis', ([], {}), '()\n', (2794, 2796), False, 'from sklearn.decomposition import PCA, FactorAnalysis\n'), ((3169, 3191), 'numpy.logspace', 'np.logspace', (['(-2)', '(0)', '(30)'], {}), '(-2, 0, 30)\n', (3180, 3191), True, 'import numpy as np\n'), ((3517, 3538), 'numpy.argmax', 'np.argmax', (['pca_scores'], {}), '(pca_scores)\n', (3526, 3538), True, 'import numpy as np\n'), ((3575, 3595), 'numpy.argmax', 'np.argmax', (['fa_scores'], {}), '(fa_scores)\n', (3584, 3595), True, 'import numpy as np\n'), ((3946, 3982), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5.5139, 3.5139)'}), '(figsize=(5.5139, 3.5139))\n', (3956, 3982), True, 'import matplotlib.pyplot as plt\n'), ((3990, 4049), 'matplotlib.pyplot.plot', 'plt.plot', (['n_components', 'pca_scores', '"""b"""'], {'label': '"""PCA scores"""'}), "(n_components, pca_scores, 'b', label='PCA scores')\n", (3998, 4049), True, 'import matplotlib.pyplot as plt\n'), ((4058, 4115), 'matplotlib.pyplot.plot', 'plt.plot', (['n_components', 'fa_scores', '"""r"""'], {'label': '"""FA scores"""'}), "(n_components, fa_scores, 'r', label='FA scores')\n", (4066, 4115), True, 'import matplotlib.pyplot as plt\n'), ((4124, 4223), 'matplotlib.pyplot.axvline', 'plt.axvline', (['n_components_pca'], {'color': '"""b"""', 'label': "('PCA CV: %d' % n_components_pca)", 'linestyle': '"""--"""'}), "(n_components_pca, color='b', label='PCA CV: %d' %\n n_components_pca, linestyle='--')\n", (4135, 4223), True, 'import matplotlib.pyplot as plt\n'), ((4248, 4356), 'matplotlib.pyplot.axvline', 'plt.axvline', (['n_components_fa'], {'color': '"""r"""', 'label': "('FactorAnalysis CV: %d' % n_components_fa)", 'linestyle': '"""--"""'}), "(n_components_fa, color='r', label='FactorAnalysis CV: %d' %\n n_components_fa, linestyle='--')\n", (4259, 4356), True, 'import matplotlib.pyplot as plt\n'), ((4401, 4509), 'matplotlib.pyplot.axvline', 'plt.axvline', (['n_components_pca_mle'], {'color': '"""k"""', 'label': "('PCA MLE: %d' % n_components_pca_mle)", 'linestyle': '"""--"""'}), "(n_components_pca_mle, color='k', label='PCA MLE: %d' %\n n_components_pca_mle, linestyle='--')\n", (4412, 4509), True, 'import matplotlib.pyplot as plt\n'), ((4841, 4875), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of components"""'], {}), "('Number of components')\n", (4851, 4875), True, 'import matplotlib.pyplot as plt\n'), ((4884, 4907), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""CV scores"""'], {}), "('CV scores')\n", (4894, 4907), True, 'import matplotlib.pyplot as plt\n'), ((4916, 4945), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (4926, 4945), True, 'import matplotlib.pyplot as plt\n'), ((4954, 4972), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4970, 4972), True, 'import matplotlib.pyplot as plt\n'), ((4981, 5102), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(graphs_path + 'two_stage_pca_fa_analysis_' + station + '_' + decomposer +\n '.eps')"], {'format': '"""EPS"""', 'dpi': '(2000)'}), "(graphs_path + 'two_stage_pca_fa_analysis_' + station + '_' +\n decomposer + '.eps', format='EPS', dpi=2000)\n", (4992, 5102), True, 'import matplotlib.pyplot as plt\n'), ((5095, 5217), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(graphs_path + 'two_stage_pca_fa_analysis_' + station + '_' + decomposer +\n '.tif')"], {'format': '"""TIFF"""', 'dpi': '(1200)'}), "(graphs_path + 'two_stage_pca_fa_analysis_' + station + '_' +\n decomposer + '.tif', format='TIFF', dpi=1200)\n", (5106, 5217), True, 'import matplotlib.pyplot as plt\n'), ((5210, 5220), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5218, 5220), True, 'import matplotlib.pyplot as plt\n'), ((6201, 6219), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (6217, 6219), True, 'import matplotlib.pyplot as plt\n'), ((2333, 2370), 'numpy.multiply', 'np.multiply', (['(samples + 1)', '(sMax - sMin)'], {}), '(samples + 1, sMax - sMin)\n', (2344, 2370), True, 'import numpy as np\n'), ((3218, 3236), 'sklearn.covariance.ShrunkCovariance', 'ShrunkCovariance', ([], {}), '()\n', (3234, 3236), False, 'from sklearn.covariance import ShrunkCovariance, LedoitWolf\n'), ((3409, 3421), 'sklearn.covariance.LedoitWolf', 'LedoitWolf', ([], {}), '()\n', (3419, 3421), False, 'from sklearn.covariance import ShrunkCovariance, LedoitWolf\n'), ((2971, 3000), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['pca', 'X'], {'cv': '(5)'}), '(pca, X, cv=5)\n', (2986, 3000), False, 'from sklearn.model_selection import cross_val_score\n'), ((3040, 3068), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['fa', 'X'], {'cv': '(5)'}), '(fa, X, cv=5)\n', (3055, 3068), False, 'from sklearn.model_selection import cross_val_score\n')]
#!/usr/bin/env python # This program is re-implementation of getHeightmaps.m from __future__ import division from __future__ import print_function import glob import os import os.path as osp import warnings import numpy as np import skimage.io import tqdm from grasp_fusion_lib.contrib import grasp_fusion def get_heightmaps(grasp_type='suction'): print('Grasp type: {}'.format(grasp_type)) pinch_dir = grasp_fusion.datasets.PinchDataset('train').root_dir suction_dir = grasp_fusion.datasets.SuctionDataset('train').root_dir if grasp_type == 'pinch': dataset_dir = pinch_dir else: assert grasp_type == 'suction' dataset_dir = suction_dir # List colot images from dataset color_dir = osp.join(dataset_dir, 'color-input') if grasp_type == 'pinch': color_files = sorted(glob.glob(osp.join(color_dir, '*-0.png'))) else: color_files = sorted(glob.glob(osp.join(color_dir, '*.png'))) # Create directory to save height_maps heightmap_color_dir = osp.join(dataset_dir, 'heightmap-color2') heightmap_depth_dir = osp.join(dataset_dir, 'heightmap-depth2') try: os.mkdir(heightmap_color_dir) os.mkdir(heightmap_depth_dir) except OSError: pass print('Created: {}'.format(heightmap_color_dir)) print('Created: {}'.format(heightmap_depth_dir)) if grasp_type == 'suction': heightmap_suction_dir = osp.join(dataset_dir, 'heightmap-suction2') try: os.mkdir(heightmap_suction_dir) except OSError: pass print('Created: {}'.format(heightmap_suction_dir)) # Read fixed position of bin w.r.t. world coordinates bin_position_file = osp.join(pinch_dir, 'bin-position.txt') bin_middle_bottom = np.loadtxt(bin_position_file) # Assumes fixed orientation bin_rot = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) # Offset w.r.t. bin coordinates grid_origin = bin_middle_bottom - np.dot(bin_rot, np.array([0.3, 0.2, 0])) # Loop through all sample and generate height maps for sample_idx in tqdm.tqdm(range(len(color_files))): sample_name = color_files[sample_idx][:-6].split('/')[-1] heightmaps = [] missing_heightmaps = [] heightmaps_color = [] heightmaps_suction = [] # Use every two RGB-D images (captured from two different cameras) to # construct a unified height map for cam_idx in [0, 1]: basename = '{:s}-{:d}'.format(sample_name, cam_idx) color_img_path = osp.join( dataset_dir, 'color-input', basename + '.png') depth_img_path = osp.join( dataset_dir, 'depth-input', basename + '.png') bg_color_img_path = osp.join( dataset_dir, 'color-background', basename + '.png') bg_depth_img_path = osp.join( dataset_dir, 'depth-background', basename + '.png') cam_intrinsics_path = osp.join( dataset_dir, 'camera-intrinsics', basename + '.txt') cam_pose_path = osp.join( dataset_dir, 'camera-pose', basename + '.txt') suction_img_path = None if grasp_type == 'suction': suction_img_path = osp.join( dataset_dir, 'label', basename + '.png') if not osp.exists(color_img_path): continue # Read RGB-D image files color_img = skimage.io.imread(color_img_path) / 255 depth_img = skimage.io.imread(depth_img_path) / 10000 bg_color_img = skimage.io.imread(bg_color_img_path) / 255 bg_depth_img = skimage.io.imread(bg_depth_img_path) / 10000 cam_intrinsics = np.loadtxt(cam_intrinsics_path) cam_pose = np.loadtxt(cam_pose_path) suction_img = None if suction_img_path is not None: suction_img = skimage.io.imread(suction_img_path) / 255 heightmap_color, heightmap, missing_heightmap, heightmap_suction \ = grasp_fusion.utils.get_heightmap( color_img, depth_img, bg_color_img, bg_depth_img, cam_intrinsics, cam_pose, grid_origin, bin_rot, suction_img, voxel_size=0.002, ) heightmaps_color.append(heightmap_color) heightmaps.append(heightmap) missing_heightmaps.append(missing_heightmap) heightmaps_suction.append(heightmap_suction) del heightmap_color, heightmap, missing_heightmap, \ heightmap_suction n_view = len(heightmaps_color) assert n_view == len(heightmaps) == len(missing_heightmaps) \ == len(heightmaps_suction) assert n_view in [1, 2] if n_view == 2: heightmap_color = np.maximum( heightmaps_color[0], heightmaps_color[1] ) heightmap = np.maximum(heightmaps[0], heightmaps[1]) missing_heightmap = missing_heightmaps[0] & missing_heightmaps[1] if grasp_type == 'suction': heightmap_suction = np.maximum( heightmaps_suction[0], heightmaps_suction[1] ) else: heightmap_color = heightmaps_color[0] heightmap = heightmaps[0] missing_heightmap = missing_heightmaps[0] if grasp_type == 'suction': heightmap_suction = heightmaps_suction[0] del heightmaps_color, heightmaps, missing_heightmaps color_data, depth_data \ = grasp_fusion.utils.heightmap_postprocess( heightmap_color, heightmap, missing_heightmap, ) if grasp_type == 'suction': heightmap_suction = heightmap_suction.reshape( heightmap.shape[0], heightmap.shape[1], ) suction_data = np.zeros((224, 320), dtype=np.uint8) suction_data[12:212, 10:310] = heightmap_suction * 255 heightmap_color_file = osp.join( heightmap_color_dir, sample_name + '.png') heightmap_depth_file = osp.join( heightmap_depth_dir, sample_name + '.png') with warnings.catch_warnings(): warnings.simplefilter("ignore") skimage.io.imsave(heightmap_color_file, color_data) skimage.io.imsave(heightmap_depth_file, depth_data) if grasp_type == 'suction': heightmap_suction_file = osp.join( heightmap_suction_dir, sample_name + '.png') skimage.io.imsave(heightmap_suction_file, suction_data) if __name__ == '__main__': for grasp_type in ['pinch', 'suction']: get_heightmaps(grasp_type)
[ "os.path.exists", "grasp_fusion_lib.contrib.grasp_fusion.utils.heightmap_postprocess", "os.path.join", "grasp_fusion_lib.contrib.grasp_fusion.datasets.SuctionDataset", "warnings.catch_warnings", "grasp_fusion_lib.contrib.grasp_fusion.datasets.PinchDataset", "numpy.array", "grasp_fusion_lib.contrib.gra...
[((745, 781), 'os.path.join', 'osp.join', (['dataset_dir', '"""color-input"""'], {}), "(dataset_dir, 'color-input')\n", (753, 781), True, 'import os.path as osp\n'), ((1034, 1075), 'os.path.join', 'osp.join', (['dataset_dir', '"""heightmap-color2"""'], {}), "(dataset_dir, 'heightmap-color2')\n", (1042, 1075), True, 'import os.path as osp\n'), ((1102, 1143), 'os.path.join', 'osp.join', (['dataset_dir', '"""heightmap-depth2"""'], {}), "(dataset_dir, 'heightmap-depth2')\n", (1110, 1143), True, 'import os.path as osp\n'), ((1717, 1756), 'os.path.join', 'osp.join', (['pinch_dir', '"""bin-position.txt"""'], {}), "(pinch_dir, 'bin-position.txt')\n", (1725, 1756), True, 'import os.path as osp\n'), ((1781, 1810), 'numpy.loadtxt', 'np.loadtxt', (['bin_position_file'], {}), '(bin_position_file)\n', (1791, 1810), True, 'import numpy as np\n'), ((1857, 1900), 'numpy.array', 'np.array', (['[[1, 0, 0], [0, 1, 0], [0, 0, 1]]'], {}), '([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n', (1865, 1900), True, 'import numpy as np\n'), ((419, 462), 'grasp_fusion_lib.contrib.grasp_fusion.datasets.PinchDataset', 'grasp_fusion.datasets.PinchDataset', (['"""train"""'], {}), "('train')\n", (453, 462), False, 'from grasp_fusion_lib.contrib import grasp_fusion\n'), ((490, 535), 'grasp_fusion_lib.contrib.grasp_fusion.datasets.SuctionDataset', 'grasp_fusion.datasets.SuctionDataset', (['"""train"""'], {}), "('train')\n", (526, 535), False, 'from grasp_fusion_lib.contrib import grasp_fusion\n'), ((1161, 1190), 'os.mkdir', 'os.mkdir', (['heightmap_color_dir'], {}), '(heightmap_color_dir)\n', (1169, 1190), False, 'import os\n'), ((1199, 1228), 'os.mkdir', 'os.mkdir', (['heightmap_depth_dir'], {}), '(heightmap_depth_dir)\n', (1207, 1228), False, 'import os\n'), ((1433, 1476), 'os.path.join', 'osp.join', (['dataset_dir', '"""heightmap-suction2"""'], {}), "(dataset_dir, 'heightmap-suction2')\n", (1441, 1476), True, 'import os.path as osp\n'), ((5786, 5877), 'grasp_fusion_lib.contrib.grasp_fusion.utils.heightmap_postprocess', 'grasp_fusion.utils.heightmap_postprocess', (['heightmap_color', 'heightmap', 'missing_heightmap'], {}), '(heightmap_color, heightmap,\n missing_heightmap)\n', (5826, 5877), False, 'from grasp_fusion_lib.contrib import grasp_fusion\n'), ((6266, 6317), 'os.path.join', 'osp.join', (['heightmap_color_dir', "(sample_name + '.png')"], {}), "(heightmap_color_dir, sample_name + '.png')\n", (6274, 6317), True, 'import os.path as osp\n'), ((6362, 6413), 'os.path.join', 'osp.join', (['heightmap_depth_dir', "(sample_name + '.png')"], {}), "(heightmap_depth_dir, sample_name + '.png')\n", (6370, 6413), True, 'import os.path as osp\n'), ((1502, 1533), 'os.mkdir', 'os.mkdir', (['heightmap_suction_dir'], {}), '(heightmap_suction_dir)\n', (1510, 1533), False, 'import os\n'), ((1991, 2014), 'numpy.array', 'np.array', (['[0.3, 0.2, 0]'], {}), '([0.3, 0.2, 0])\n', (1999, 2014), True, 'import numpy as np\n'), ((2559, 2614), 'os.path.join', 'osp.join', (['dataset_dir', '"""color-input"""', "(basename + '.png')"], {}), "(dataset_dir, 'color-input', basename + '.png')\n", (2567, 2614), True, 'import os.path as osp\n'), ((2661, 2716), 'os.path.join', 'osp.join', (['dataset_dir', '"""depth-input"""', "(basename + '.png')"], {}), "(dataset_dir, 'depth-input', basename + '.png')\n", (2669, 2716), True, 'import os.path as osp\n'), ((2766, 2826), 'os.path.join', 'osp.join', (['dataset_dir', '"""color-background"""', "(basename + '.png')"], {}), "(dataset_dir, 'color-background', basename + '.png')\n", (2774, 2826), True, 'import os.path as osp\n'), ((2876, 2936), 'os.path.join', 'osp.join', (['dataset_dir', '"""depth-background"""', "(basename + '.png')"], {}), "(dataset_dir, 'depth-background', basename + '.png')\n", (2884, 2936), True, 'import os.path as osp\n'), ((2988, 3049), 'os.path.join', 'osp.join', (['dataset_dir', '"""camera-intrinsics"""', "(basename + '.txt')"], {}), "(dataset_dir, 'camera-intrinsics', basename + '.txt')\n", (2996, 3049), True, 'import os.path as osp\n'), ((3095, 3150), 'os.path.join', 'osp.join', (['dataset_dir', '"""camera-pose"""', "(basename + '.txt')"], {}), "(dataset_dir, 'camera-pose', basename + '.txt')\n", (3103, 3150), True, 'import os.path as osp\n'), ((3763, 3794), 'numpy.loadtxt', 'np.loadtxt', (['cam_intrinsics_path'], {}), '(cam_intrinsics_path)\n', (3773, 3794), True, 'import numpy as np\n'), ((3818, 3843), 'numpy.loadtxt', 'np.loadtxt', (['cam_pose_path'], {}), '(cam_pose_path)\n', (3828, 3843), True, 'import numpy as np\n'), ((4091, 4260), 'grasp_fusion_lib.contrib.grasp_fusion.utils.get_heightmap', 'grasp_fusion.utils.get_heightmap', (['color_img', 'depth_img', 'bg_color_img', 'bg_depth_img', 'cam_intrinsics', 'cam_pose', 'grid_origin', 'bin_rot', 'suction_img'], {'voxel_size': '(0.002)'}), '(color_img, depth_img, bg_color_img,\n bg_depth_img, cam_intrinsics, cam_pose, grid_origin, bin_rot,\n suction_img, voxel_size=0.002)\n', (4123, 4260), False, 'from grasp_fusion_lib.contrib import grasp_fusion\n'), ((5026, 5078), 'numpy.maximum', 'np.maximum', (['heightmaps_color[0]', 'heightmaps_color[1]'], {}), '(heightmaps_color[0], heightmaps_color[1])\n', (5036, 5078), True, 'import numpy as np\n'), ((5133, 5173), 'numpy.maximum', 'np.maximum', (['heightmaps[0]', 'heightmaps[1]'], {}), '(heightmaps[0], heightmaps[1])\n', (5143, 5173), True, 'import numpy as np\n'), ((6130, 6166), 'numpy.zeros', 'np.zeros', (['(224, 320)'], {'dtype': 'np.uint8'}), '((224, 320), dtype=np.uint8)\n', (6138, 6166), True, 'import numpy as np\n'), ((6440, 6465), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (6463, 6465), False, 'import warnings\n'), ((6479, 6510), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (6500, 6510), False, 'import warnings\n'), ((851, 881), 'os.path.join', 'osp.join', (['color_dir', '"""*-0.png"""'], {}), "(color_dir, '*-0.png')\n", (859, 881), True, 'import os.path as osp\n'), ((933, 961), 'os.path.join', 'osp.join', (['color_dir', '"""*.png"""'], {}), "(color_dir, '*.png')\n", (941, 961), True, 'import os.path as osp\n'), ((3280, 3329), 'os.path.join', 'osp.join', (['dataset_dir', '"""label"""', "(basename + '.png')"], {}), "(dataset_dir, 'label', basename + '.png')\n", (3288, 3329), True, 'import os.path as osp\n'), ((3371, 3397), 'os.path.exists', 'osp.exists', (['color_img_path'], {}), '(color_img_path)\n', (3381, 3397), True, 'import os.path as osp\n'), ((5328, 5384), 'numpy.maximum', 'np.maximum', (['heightmaps_suction[0]', 'heightmaps_suction[1]'], {}), '(heightmaps_suction[0], heightmaps_suction[1])\n', (5338, 5384), True, 'import numpy as np\n'), ((6720, 6773), 'os.path.join', 'osp.join', (['heightmap_suction_dir', "(sample_name + '.png')"], {}), "(heightmap_suction_dir, sample_name + '.png')\n", (6728, 6773), True, 'import os.path as osp\n')]
# TODO # - train an LFP decoder # - run an LFP decoder # - CLDA import matplotlib.pyplot as plt import os import pyaudio import serial import pandas as pd import numpy as np import unittest import time import tables from features.hdf_features import SaveHDF from riglib import experiment from riglib import sink from features import serial_port_sensor from riglib import source from built_in_tasks.passivetasks import TargetCaptureVFB2DWindow class SimLFPSensor(serial_port_sensor.SerialPortSource): dtype = np.dtype([("ts", "f8"), ("lfp", "f8")]) default_response = np.zeros((1,), dtype=dtype) START_CMD = b'a\n' STOP_CMD = b'b\n' def start(self): super(SimLFPSensor, self).start() time.sleep(1) print("sending start command") self.port.write(self.START_CMD) def stop(self): time.sleep(1) print("sending stop command") self.port.write(self.STOP_CMD) super(SimLFPSensor, self).stop() class SimLFPSensorFeature(object): def init(self): super().init() self.sensor_src = source.DataSource(SimLFPSensor, send_data_to_sink_manager=True, port="/dev/cu.usbmodem1A121", baudrate=115200, name="sim_lfp") sink.sinks.register(self.sensor_src) def run(self): self.sensor_src.start() try: super().run() finally: self.sensor_src.stop() class SimLFPOutput(object): # audio_duration = 0.1 # update amplitudes/frequencies of outputs at 10 Hz audio_fs = 44100 # sampling rate, Hz, must be integer def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not hasattr(self, 'fps'): self.fps = 60 self.audio_duration = 1.0/self.fps * 8 # TODO why is this factor necessary? self.samples_all = [] def init(self): super().init() os.environ["OBJC_DISABLE_INITIALIZE_FORK_SAFETY"] = "YES" fs = self.audio_fs self.audio_p = pyaudio.PyAudio() self.audio_stream = self.audio_p.open(format=pyaudio.paFloat32, channels=1, rate=fs, output=True) self.audio_t = np.arange(fs*self.audio_duration) * 1.0/fs self.phase = 0 def _cycle(self): # frequency should be modulated by direction, amplitude should be modulated by speed vel = self.decoder[['hand_vx', 'hand_vz']] speed = np.linalg.norm(vel) direction = vel / speed angle = np.arctan2(direction[1], direction[0]) if np.isnan(angle): angle = 0 amp = speed / 7.5 if amp > 0.75: amp = 0.75 freq_modulation_range = 40 # Hz freq_base = 370 f = angle / np.pi * freq_modulation_range/2 + freq_base wave_period = 1.0/f samples = amp * np.sin(2 * np.pi * f * self.audio_t + self.phase) self.phase += ((self.audio_duration / wave_period) % 1) * 2*np.pi self.samples_all.append(samples) self.phase = self.phase % (2 * np.pi) # old version, fixed frequency # samples = 0 # if self.cycle_count < 300: # freq = 280 # else: # freq = 240 # for f, amp in [(freq, 0.75)]: # samples += amp * np.sin(2 * np.pi * f * self.audio_t) samples = samples.astype(np.float32) # play the audio self.audio_stream.write(samples) # self.audio_t += self.audio_duration super()._cycle() def run(self): super().run() self.audio_stream.stop_stream() self.audio_stream.close() self.audio_p.terminate() TestFeat = experiment.make(TargetCaptureVFB2DWindow, feats=[SaveHDF, SimLFPSensorFeature, SimLFPOutput]) # TestFeat.fps = 5 seq = TargetCaptureVFB2DWindow.centerout_2D_discrete(nblocks=2, ntargets=8) feat = TestFeat(seq, window_size=(480, 240)) feat.run_sync() time.sleep(1) hdf = tables.open_file(feat.h5file.name) os.rename(feat.h5file.name, "test_vfb_real_time_audio_feedback.hdf") saved_msgs = [x.decode('utf-8') for x in hdf.root.task_msgs[:]["msg"]] lfp = hdf.root.sim_lfp[:]['lfp'][:] ts = hdf.root.sim_lfp[:]['ts'] plt.figure() plt.plot(hdf.root.sim_lfp[:]['lfp']) plt.show() plt.figure() plt.plot(np.log(np.abs(np.fft.fft(hdf.root.sim_lfp[:]['lfp'])))) plt.show() plt.figure() plt.specgram(lfp, Fs=1.0/(np.mean(ts) * 1e-6)) plt.show() samples_all = np.hstack(feat.samples_all) plt.figure() plt.plot(samples_all)
[ "numpy.hstack", "built_in_tasks.passivetasks.TargetCaptureVFB2DWindow.centerout_2D_discrete", "time.sleep", "riglib.sink.sinks.register", "numpy.arctan2", "numpy.linalg.norm", "numpy.sin", "riglib.source.DataSource", "numpy.arange", "numpy.mean", "matplotlib.pyplot.plot", "numpy.fft.fft", "n...
[((3693, 3790), 'riglib.experiment.make', 'experiment.make', (['TargetCaptureVFB2DWindow'], {'feats': '[SaveHDF, SimLFPSensorFeature, SimLFPOutput]'}), '(TargetCaptureVFB2DWindow, feats=[SaveHDF,\n SimLFPSensorFeature, SimLFPOutput])\n', (3708, 3790), False, 'from riglib import experiment\n'), ((3812, 3881), 'built_in_tasks.passivetasks.TargetCaptureVFB2DWindow.centerout_2D_discrete', 'TargetCaptureVFB2DWindow.centerout_2D_discrete', ([], {'nblocks': '(2)', 'ntargets': '(8)'}), '(nblocks=2, ntargets=8)\n', (3858, 3881), False, 'from built_in_tasks.passivetasks import TargetCaptureVFB2DWindow\n'), ((3946, 3959), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (3956, 3959), False, 'import time\n'), ((3966, 4000), 'tables.open_file', 'tables.open_file', (['feat.h5file.name'], {}), '(feat.h5file.name)\n', (3982, 4000), False, 'import tables\n'), ((4001, 4069), 'os.rename', 'os.rename', (['feat.h5file.name', '"""test_vfb_real_time_audio_feedback.hdf"""'], {}), "(feat.h5file.name, 'test_vfb_real_time_audio_feedback.hdf')\n", (4010, 4069), False, 'import os\n'), ((4211, 4223), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4221, 4223), True, 'import matplotlib.pyplot as plt\n'), ((4224, 4260), 'matplotlib.pyplot.plot', 'plt.plot', (["hdf.root.sim_lfp[:]['lfp']"], {}), "(hdf.root.sim_lfp[:]['lfp'])\n", (4232, 4260), True, 'import matplotlib.pyplot as plt\n'), ((4261, 4271), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4269, 4271), True, 'import matplotlib.pyplot as plt\n'), ((4273, 4285), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4283, 4285), True, 'import matplotlib.pyplot as plt\n'), ((4353, 4363), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4361, 4363), True, 'import matplotlib.pyplot as plt\n'), ((4365, 4377), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4375, 4377), True, 'import matplotlib.pyplot as plt\n'), ((4425, 4435), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4433, 4435), True, 'import matplotlib.pyplot as plt\n'), ((4453, 4480), 'numpy.hstack', 'np.hstack', (['feat.samples_all'], {}), '(feat.samples_all)\n', (4462, 4480), True, 'import numpy as np\n'), ((4585, 4597), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4595, 4597), True, 'import matplotlib.pyplot as plt\n'), ((4598, 4619), 'matplotlib.pyplot.plot', 'plt.plot', (['samples_all'], {}), '(samples_all)\n', (4606, 4619), True, 'import matplotlib.pyplot as plt\n'), ((516, 555), 'numpy.dtype', 'np.dtype', (["[('ts', 'f8'), ('lfp', 'f8')]"], {}), "([('ts', 'f8'), ('lfp', 'f8')])\n", (524, 555), True, 'import numpy as np\n'), ((579, 606), 'numpy.zeros', 'np.zeros', (['(1,)'], {'dtype': 'dtype'}), '((1,), dtype=dtype)\n', (587, 606), True, 'import numpy as np\n'), ((725, 738), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (735, 738), False, 'import time\n'), ((847, 860), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (857, 860), False, 'import time\n'), ((1102, 1233), 'riglib.source.DataSource', 'source.DataSource', (['SimLFPSensor'], {'send_data_to_sink_manager': '(True)', 'port': '"""/dev/cu.usbmodem1A121"""', 'baudrate': '(115200)', 'name': '"""sim_lfp"""'}), "(SimLFPSensor, send_data_to_sink_manager=True, port=\n '/dev/cu.usbmodem1A121', baudrate=115200, name='sim_lfp')\n", (1119, 1233), False, 'from riglib import source\n'), ((1251, 1287), 'riglib.sink.sinks.register', 'sink.sinks.register', (['self.sensor_src'], {}), '(self.sensor_src)\n', (1270, 1287), False, 'from riglib import sink\n'), ((2036, 2053), 'pyaudio.PyAudio', 'pyaudio.PyAudio', ([], {}), '()\n', (2051, 2053), False, 'import pyaudio\n'), ((2433, 2452), 'numpy.linalg.norm', 'np.linalg.norm', (['vel'], {}), '(vel)\n', (2447, 2452), True, 'import numpy as np\n'), ((2501, 2539), 'numpy.arctan2', 'np.arctan2', (['direction[1]', 'direction[0]'], {}), '(direction[1], direction[0])\n', (2511, 2539), True, 'import numpy as np\n'), ((2551, 2566), 'numpy.isnan', 'np.isnan', (['angle'], {}), '(angle)\n', (2559, 2566), True, 'import numpy as np\n'), ((2852, 2901), 'numpy.sin', 'np.sin', (['(2 * np.pi * f * self.audio_t + self.phase)'], {}), '(2 * np.pi * f * self.audio_t + self.phase)\n', (2858, 2901), True, 'import numpy as np\n'), ((4310, 4348), 'numpy.fft.fft', 'np.fft.fft', (["hdf.root.sim_lfp[:]['lfp']"], {}), "(hdf.root.sim_lfp[:]['lfp'])\n", (4320, 4348), True, 'import numpy as np\n'), ((2184, 2219), 'numpy.arange', 'np.arange', (['(fs * self.audio_duration)'], {}), '(fs * self.audio_duration)\n', (2193, 2219), True, 'import numpy as np\n'), ((4404, 4415), 'numpy.mean', 'np.mean', (['ts'], {}), '(ts)\n', (4411, 4415), True, 'import numpy as np\n')]
""" Leontis-Westhof Nomenclature ============================ In this example we plot a secondary structure diagram annotated with Leontis-Westhof nomenclature :footcite:`Leontis2001` of the sarcin-ricin loop from E. coli (PDB ID: 6ZYB). """ # Code source: <NAME> # License: BSD 3 clause from tempfile import gettempdir import biotite import biotite.structure.io.pdb as pdb import biotite.database.rcsb as rcsb import biotite.structure as struc import biotite.structure.graphics as graphics import matplotlib.pyplot as plt import numpy as np # Download the PDB file and read the structure pdb_file_path = rcsb.fetch("6ZYB", "pdb", gettempdir()) pdb_file = pdb.PDBFile.read(pdb_file_path) atom_array = pdb.get_structure(pdb_file)[0] nucleotides = atom_array[struc.filter_nucleotides(atom_array)] # Compute the base pairs and the Leontis-Westhof nomenclature base_pairs = struc.base_pairs(nucleotides) glycosidic_bonds = struc.base_pairs_glycosidic_bond(nucleotides, base_pairs) edges = struc.base_pairs_edge(nucleotides, base_pairs) base_pairs = struc.get_residue_positions( nucleotides, base_pairs.flatten() ).reshape(base_pairs.shape) # Get the one-letter-codes of the bases base_labels = [] for base in struc.residue_iter(nucleotides): base_labels.append(base.res_name[0]) # Color canonical Watson-Crick base pairs with a darker orange and # non-canonical base pairs with a lighter orange colors = np.full(base_pairs.shape[0], biotite.colors['brightorange']) for i, (base1, base2) in enumerate(base_pairs): name1 = base_labels[base1] name2 = base_labels[base2] if sorted([name1, name2]) in [["A", "U"], ["C", "G"]]: colors[i] = biotite.colors["dimorange"] # Use the base labels to indicate the Leontis-Westhof nomenclature for bases, edge_types, orientation in zip(base_pairs, edges, glycosidic_bonds): for base, edge in zip(bases, edge_types): if orientation == 1: annotation = "c" else: annotation = "t" if edge == 1: annotation += "W" elif edge == 2: annotation += "H" else: annotation += "S" base_labels[base] = annotation # Create a matplotlib pyplot fig, ax = plt.subplots(figsize=(8.0, 8.0)) # Plot the secondary structure graphics.plot_nucleotide_secondary_structure( ax, base_labels, base_pairs, struc.get_residue_count(nucleotides), bond_color=colors ) # Display the plot plt.show() ######################################################################## # The sarcin-ricin loop is part of the 23s rRNA and is considered # crucial to the ribosome‘s activity. The incorporation of the # Leontis-Westhof nomenclature into the 2D-plot shows how the individual # base pairs are oriented and how their glycosidic bonds are oriented # relative to each other. # # This visualization enables one to see a pattern that cannot be # communicated through the 2D structure alone. The upper part of the # sarcin-ricin loop consists of only cis (c) oriented glycosidic bonds. # All bases interact through their Watson-Crick edge (W). On the other # hand, the lower part of the sarcin ricin loop looks strikingly # different. The glycosidic bonds are oriented in cis (c) and trans (t) # orientation. The bases interact through all three edges: Watson-Crick # (W), Hoogsteen (H), and Sugar (S). # # Thus, it can be concluded that the upper part of the sarcin ricin loop # represents a highly organized helix, while the lower part of the loop # is comparatively unorganized. # # References # ---------- # # .. footbibliography::
[ "biotite.structure.base_pairs", "biotite.structure.residue_iter", "biotite.structure.io.pdb.get_structure", "tempfile.gettempdir", "matplotlib.pyplot.subplots", "biotite.structure.filter_nucleotides", "biotite.structure.get_residue_count", "numpy.full", "biotite.structure.base_pairs_edge", "biotit...
[((662, 693), 'biotite.structure.io.pdb.PDBFile.read', 'pdb.PDBFile.read', (['pdb_file_path'], {}), '(pdb_file_path)\n', (678, 693), True, 'import biotite.structure.io.pdb as pdb\n'), ((877, 906), 'biotite.structure.base_pairs', 'struc.base_pairs', (['nucleotides'], {}), '(nucleotides)\n', (893, 906), True, 'import biotite.structure as struc\n'), ((926, 983), 'biotite.structure.base_pairs_glycosidic_bond', 'struc.base_pairs_glycosidic_bond', (['nucleotides', 'base_pairs'], {}), '(nucleotides, base_pairs)\n', (958, 983), True, 'import biotite.structure as struc\n'), ((992, 1038), 'biotite.structure.base_pairs_edge', 'struc.base_pairs_edge', (['nucleotides', 'base_pairs'], {}), '(nucleotides, base_pairs)\n', (1013, 1038), True, 'import biotite.structure as struc\n'), ((1217, 1248), 'biotite.structure.residue_iter', 'struc.residue_iter', (['nucleotides'], {}), '(nucleotides)\n', (1235, 1248), True, 'import biotite.structure as struc\n'), ((1417, 1477), 'numpy.full', 'np.full', (['base_pairs.shape[0]', "biotite.colors['brightorange']"], {}), "(base_pairs.shape[0], biotite.colors['brightorange'])\n", (1424, 1477), True, 'import numpy as np\n'), ((2219, 2251), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8.0, 8.0)'}), '(figsize=(8.0, 8.0))\n', (2231, 2251), True, 'import matplotlib.pyplot as plt\n'), ((2445, 2455), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2453, 2455), True, 'import matplotlib.pyplot as plt\n'), ((637, 649), 'tempfile.gettempdir', 'gettempdir', ([], {}), '()\n', (647, 649), False, 'from tempfile import gettempdir\n'), ((707, 734), 'biotite.structure.io.pdb.get_structure', 'pdb.get_structure', (['pdb_file'], {}), '(pdb_file)\n', (724, 734), True, 'import biotite.structure.io.pdb as pdb\n'), ((763, 799), 'biotite.structure.filter_nucleotides', 'struc.filter_nucleotides', (['atom_array'], {}), '(atom_array)\n', (787, 799), True, 'import biotite.structure as struc\n'), ((2363, 2399), 'biotite.structure.get_residue_count', 'struc.get_residue_count', (['nucleotides'], {}), '(nucleotides)\n', (2386, 2399), True, 'import biotite.structure as struc\n')]
import os import sys import argparse import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import (MultipleLocator, NullFormatter, ScalarFormatter) if __name__ == '__main__': parser = argparse.ArgumentParser(description = "Build haplotypes and make scatter plot for vizualization") db_p = parser.add_argument_group('Sample name parameters') db_p.add_argument('-gm', '--gmm_file', required=True, help='Tab separated file with IBS and non_IBS categorized by GMM model') db_p.add_argument('-db', '--db_file', required=True, help='Tab separated file with variations genetared by IBSpy output') db_p.add_argument('-rf', '--refId', required=True, help='Name of the genome reference used') db_p.add_argument('-qr', '--qryId', required=True, help='Name of the query sample') db_p.add_argument('-chr', '--chrNme', required=True, help='Chromosome name to be plotted') db_p.add_argument('-cl', '--chr_length_file', required=True, help='Reference chromosome lenghts file') hap_block_p = parser.add_argument_group('Haplotype blocks parameters') hap_block_p.add_argument('-w', '--windSize', required=True, help='Windows size to count variations within') hap_block_p.add_argument('-vf', '--varfltr', required=True, help='Filter variations above this threshold to compute GMM model') hap_block_p.add_argument('-st', '--StitchVarNum', required=True, help='Stitching haplotypes: number of non-IBS "outliers" that must a appear consecutively in a windows to be called non-IBS') out_files = parser.add_argument_group('Output files') out_files.add_argument('-o','--out_img_file', help='Output scatter plot and bars with haplotypes in ".jpg" format ') args = parser.parse_args() gmm_file = args.gmm_file db_file = args.db_file refId = args.refId qryId = args.qryId chrNme = args.chrNme chr_length_file = args.chr_length_file windSize = int(args.windSize) varfltr = int(args.varfltr) StitchVarNum = int(args.StitchVarNum) out_img_file = args.out_img_file #### GMM input file #### ''' It is a temporary file where IBS and non-IBS were computed (to 1 as IBS, and 0 non-IBS) using the number of variations found in a windows of a size employing the GMM model. ''' inFile = pd.read_csv(gmm_file, delimiter='\t') byChrDf = inFile[inFile['seqname'] == chrNme].copy() byChrDf.reset_index(drop=True, inplace=True) #### stitching haplotypes: number of non-IBS "outliers" that must a appear consecutively in a windows to be called non-IBS #### def stitch_haplotypes(byChrDf): gmmDta = byChrDf['gauss_mx_IBS'].copy() for i in range(len(gmmDta)): if gmmDta[i] == 1: if i < (len(gmmDta) - StitchVarNum): count = 0 for n in range(1, (StitchVarNum+1)): if gmmDta[i+n] == 0: count += 1 if count == StitchVarNum: continue else: gmmDta[i+1] = 1 hapBlock = gmmDta hapBlock = pd.Series(hapBlock) # final haplotype block after stitching byChrDf['hap_block'] = hapBlock.values # new column for stitched haplotypes return byChrDf #### put back the k-mer variations Data Base file with all variations count per windows position #### hapCntFile = pd.read_csv(db_file, delimiter='\t') hapCntFile = hapCntFile[['seqname', 'start', 'variations']].copy() hapCntFile = hapCntFile[hapCntFile['seqname'] == chrNme].copy() byChrDf = stitch_haplotypes(byChrDf) byChrDf = pd.merge(hapCntFile, byChrDf, left_on='start', right_on='start', how='left') byChrDf.loc[:,'gauss_mx_IBS':'hap_block'] = np.where(byChrDf.loc[:, 'gauss_mx_IBS':'hap_block'] == 1, 1, 0) byChrDf.rename(columns={'seqname_x':'seqname', 'variations_x':'variations'}, inplace=True) byChrDf = byChrDf[['seqname', 'start', 'variations', 'gauss_mx_IBS', 'hap_block']].copy() ######## plots ######## #### GMM stitched #### IBS = byChrDf[byChrDf['hap_block'] == 1].copy() strtIbsCln = np.array(IBS['start']) hapBlkIbsCln = np.array(IBS['hap_block']) hapArrIbsCln = np.vstack((strtIbsCln, hapBlkIbsCln)) non_IBS = byChrDf[byChrDf['hap_block'] == 0].copy() chr_st_non_IBS = np.array(non_IBS['start']) hp_blk_non_IBS = np.array(non_IBS['hap_block']) chr_hp_arr_non_IBS = np.vstack((chr_st_non_IBS, hp_blk_non_IBS)) #### GMM before stitching #### IBS_org = byChrDf[byChrDf['gauss_mx_IBS'] == 1].copy() strtIbsCln_org = np.array(IBS_org['start']) IBS_org = np.array(IBS_org['gauss_mx_IBS']) hapArrIbsCln_org = np.vstack((strtIbsCln_org, IBS_org)) non_IBS_org = byChrDf[byChrDf['gauss_mx_IBS'] == 0].copy() chr_st_non_IBS_org = np.array(non_IBS_org['start']) non_IBS_org = np.array(non_IBS_org['gauss_mx_IBS']) chr_hp_arr_non_IBS_org = np.vstack((chr_st_non_IBS_org, non_IBS_org)) #### base subplots #### fig, axs = plt.subplots(3, figsize=(20, 7), sharex=True, gridspec_kw={'height_ratios': [1, 1,3]}) fig.suptitle(f'{chrNme}: {refId} vs {qryId}, {windSize} bp windows, stitched var: {StitchVarNum}, filter: {varfltr}', fontweight="bold", fontsize=25) #### horizontal bar plot #### ### GMM_stitched axs[0].eventplot(hapArrIbsCln, colors='darkcyan', alpha=1, lineoffsets=[1,1], linelengths=1.5) axs[0].eventplot(chr_hp_arr_non_IBS, colors='goldenrod', lineoffsets=[1,1], linelengths=1) ### GMM_original (before stitching) ### axs[1].eventplot(hapArrIbsCln_org, colors='darkcyan', alpha=1, lineoffsets=[1,1], linelengths=1.5) axs[1].eventplot(chr_hp_arr_non_IBS_org, colors='goldenrod', lineoffsets=[1,1], linelengths=1) ### scatter plot ### IBS_block = byChrDf[(byChrDf['hap_block'] == 1)] x = IBS_block['start'] y = IBS_block['variations'] axs[2].scatter(x,y, c="darkcyan", alpha=0.5, s=4, label='IBS') non_IBS_block = byChrDf[(byChrDf['hap_block'] == 0)] a = non_IBS_block['start'] b = non_IBS_block['variations'] axs[2].scatter(a,b, c="goldenrod", alpha=0.6, s=4, marker='>', label='non-IBS') axs[2].set_yscale('symlog') axs[2].set_ylabel('Variations count', fontweight="bold", fontsize=17) axs[2].set_xlabel('Chromosome position [Mbp]', fontweight="bold", fontsize=17) axs[2].yaxis.set_major_formatter(ScalarFormatter()) ### get chromosome length to plot X_axis limits ### chr_file = pd.read_csv(chr_length_file, delimiter='\t', header=None) chr_length = int(chr_file[chr_file[0] == chrNme][1].values) + 10000000 #### labels and axis limits #### names = ['gmm_stitched', 'gmm_origin'] for axs, names in zip(axs, names): axs.text(-0.01, 0.5, names, va='center', ha='right', fontweight= "bold", fontsize=17, transform=axs.transAxes) plt.grid(True, color='gray', linestyle='--', linewidth=0.5) axs.set_xlim(0,chr_length) x_labels = list(range(0,chr_length,20000000)) # one label every 20 Mb list_labels = int(chr_length/1000000) # transform to Mb to reduce number size x_ticklabels = list(range(0,list_labels,20)) # use tranformed labels every 20 Mb plt.xticks(x_labels, x_ticklabels, rotation=45, fontsize=15) axs.yaxis.set_major_formatter(ScalarFormatter()) plt.yticks([1,2,3,10,20,40,100,300,1000,2000,5000], fontsize = 15) plt.legend(prop={'size': 10}, markerscale=4, borderaxespad=0.3, handletextpad=0.1) axs.set_axis_off() fig.savefig(out_img_file, format='jpg', dpi=150, bbox_inches='tight')
[ "pandas.Series", "matplotlib.pyplot.grid", "pandas.read_csv", "argparse.ArgumentParser", "numpy.where", "matplotlib.pyplot.xticks", "pandas.merge", "numpy.array", "matplotlib.ticker.ScalarFormatter", "matplotlib.pyplot.yticks", "numpy.vstack", "matplotlib.pyplot.subplots", "matplotlib.pyplot...
[((2305, 2342), 'pandas.read_csv', 'pd.read_csv', (['gmm_file'], {'delimiter': '"""\t"""'}), "(gmm_file, delimiter='\\t')\n", (2316, 2342), True, 'import pandas as pd\n'), ((3352, 3388), 'pandas.read_csv', 'pd.read_csv', (['db_file'], {'delimiter': '"""\t"""'}), "(db_file, delimiter='\\t')\n", (3363, 3388), True, 'import pandas as pd\n'), ((3568, 3644), 'pandas.merge', 'pd.merge', (['hapCntFile', 'byChrDf'], {'left_on': '"""start"""', 'right_on': '"""start"""', 'how': '"""left"""'}), "(hapCntFile, byChrDf, left_on='start', right_on='start', how='left')\n", (3576, 3644), True, 'import pandas as pd\n'), ((3689, 3752), 'numpy.where', 'np.where', (["(byChrDf.loc[:, 'gauss_mx_IBS':'hap_block'] == 1)", '(1)', '(0)'], {}), "(byChrDf.loc[:, 'gauss_mx_IBS':'hap_block'] == 1, 1, 0)\n", (3697, 3752), True, 'import numpy as np\n'), ((4045, 4067), 'numpy.array', 'np.array', (["IBS['start']"], {}), "(IBS['start'])\n", (4053, 4067), True, 'import numpy as np\n'), ((4083, 4109), 'numpy.array', 'np.array', (["IBS['hap_block']"], {}), "(IBS['hap_block'])\n", (4091, 4109), True, 'import numpy as np\n'), ((4125, 4162), 'numpy.vstack', 'np.vstack', (['(strtIbsCln, hapBlkIbsCln)'], {}), '((strtIbsCln, hapBlkIbsCln))\n', (4134, 4162), True, 'import numpy as np\n'), ((4233, 4259), 'numpy.array', 'np.array', (["non_IBS['start']"], {}), "(non_IBS['start'])\n", (4241, 4259), True, 'import numpy as np\n'), ((4277, 4307), 'numpy.array', 'np.array', (["non_IBS['hap_block']"], {}), "(non_IBS['hap_block'])\n", (4285, 4307), True, 'import numpy as np\n'), ((4329, 4372), 'numpy.vstack', 'np.vstack', (['(chr_st_non_IBS, hp_blk_non_IBS)'], {}), '((chr_st_non_IBS, hp_blk_non_IBS))\n', (4338, 4372), True, 'import numpy as np\n'), ((4477, 4503), 'numpy.array', 'np.array', (["IBS_org['start']"], {}), "(IBS_org['start'])\n", (4485, 4503), True, 'import numpy as np\n'), ((4514, 4547), 'numpy.array', 'np.array', (["IBS_org['gauss_mx_IBS']"], {}), "(IBS_org['gauss_mx_IBS'])\n", (4522, 4547), True, 'import numpy as np\n'), ((4567, 4603), 'numpy.vstack', 'np.vstack', (['(strtIbsCln_org, IBS_org)'], {}), '((strtIbsCln_org, IBS_org))\n', (4576, 4603), True, 'import numpy as np\n'), ((4685, 4715), 'numpy.array', 'np.array', (["non_IBS_org['start']"], {}), "(non_IBS_org['start'])\n", (4693, 4715), True, 'import numpy as np\n'), ((4730, 4767), 'numpy.array', 'np.array', (["non_IBS_org['gauss_mx_IBS']"], {}), "(non_IBS_org['gauss_mx_IBS'])\n", (4738, 4767), True, 'import numpy as np\n'), ((4793, 4837), 'numpy.vstack', 'np.vstack', (['(chr_st_non_IBS_org, non_IBS_org)'], {}), '((chr_st_non_IBS_org, non_IBS_org))\n', (4802, 4837), True, 'import numpy as np\n'), ((4875, 4966), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)'], {'figsize': '(20, 7)', 'sharex': '(True)', 'gridspec_kw': "{'height_ratios': [1, 1, 3]}"}), "(3, figsize=(20, 7), sharex=True, gridspec_kw={'height_ratios':\n [1, 1, 3]})\n", (4887, 4966), True, 'import matplotlib.pyplot as plt\n'), ((6252, 6309), 'pandas.read_csv', 'pd.read_csv', (['chr_length_file'], {'delimiter': '"""\t"""', 'header': 'None'}), "(chr_length_file, delimiter='\\t', header=None)\n", (6263, 6309), True, 'import pandas as pd\n'), ((230, 330), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Build haplotypes and make scatter plot for vizualization"""'}), "(description=\n 'Build haplotypes and make scatter plot for vizualization')\n", (253, 330), False, 'import argparse\n'), ((3076, 3095), 'pandas.Series', 'pd.Series', (['hapBlock'], {}), '(hapBlock)\n', (3085, 3095), True, 'import pandas as pd\n'), ((6169, 6186), 'matplotlib.ticker.ScalarFormatter', 'ScalarFormatter', ([], {}), '()\n', (6184, 6186), False, 'from matplotlib.ticker import MultipleLocator, NullFormatter, ScalarFormatter\n'), ((6616, 6675), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {'color': '"""gray"""', 'linestyle': '"""--"""', 'linewidth': '(0.5)'}), "(True, color='gray', linestyle='--', linewidth=0.5)\n", (6624, 6675), True, 'import matplotlib.pyplot as plt\n'), ((6981, 7041), 'matplotlib.pyplot.xticks', 'plt.xticks', (['x_labels', 'x_ticklabels'], {'rotation': '(45)', 'fontsize': '(15)'}), '(x_labels, x_ticklabels, rotation=45, fontsize=15)\n', (6991, 7041), True, 'import matplotlib.pyplot as plt\n'), ((7107, 7181), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[1, 2, 3, 10, 20, 40, 100, 300, 1000, 2000, 5000]'], {'fontsize': '(15)'}), '([1, 2, 3, 10, 20, 40, 100, 300, 1000, 2000, 5000], fontsize=15)\n', (7117, 7181), True, 'import matplotlib.pyplot as plt\n'), ((7182, 7268), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'prop': "{'size': 10}", 'markerscale': '(4)', 'borderaxespad': '(0.3)', 'handletextpad': '(0.1)'}), "(prop={'size': 10}, markerscale=4, borderaxespad=0.3,\n handletextpad=0.1)\n", (7192, 7268), True, 'import matplotlib.pyplot as plt\n'), ((7080, 7097), 'matplotlib.ticker.ScalarFormatter', 'ScalarFormatter', ([], {}), '()\n', (7095, 7097), False, 'from matplotlib.ticker import MultipleLocator, NullFormatter, ScalarFormatter\n')]
import numpy as np import pandas as pd import os import matplotlib.pyplot as plt from sklearn.utils import shuffle import tensorflow as tf from tensorflow.keras.models import load_model from functions.sub_data_prep import create_trainingdata_baseline from functions.tf_model_base import create_baseline_model_ffn, create_baseline_model_rnn, transfer_weights_dense2simpleRNN from functions.sub_backtesting import check_if_rnn_version from global_vars import T_MAX # max age in baseline survival table; used for scaling from global_vars import path_models_baseline_transfer, path_dav # Optional: global plotting parameters # parameters = {'axes.labelsize': 16, 'xtick.labelsize':14, 'ytick.labelsize': 14, 'legend.fontsize': 14, 'axes.titlesize': 16, 'figure.titlesize': 18} # plt.rcParams.update(parameters) def lr_schedule(epoch, lr): ''' Custom learning rate schedule. Note: Too rapids decay has shown to harm the quality of prediction, particularly for low ages where we see high, relative but low absolute differences in death probability ''' if (epoch>=10000) and (epoch % 500==0): return lr*0.9 else: return lr def ES(): return tf.keras.callbacks.EarlyStopping(monitor='mape', patience=10000, restore_best_weights=True) def run_main(baseline_sex, bool_train, bool_plot = False): ''' Load (or train; currently disabled due to safety reasons) baseline model. Perform various visual analysis of the model, e.g of the training behaviour and the final fit ''' callbacks = [tf.keras.callbacks.LearningRateScheduler(lr_schedule), ES()] p_survive = pd.read_csv(os.path.join(path_dav,r'DAV2008T{}.csv'.format(baseline_sex)), delimiter=';', header=None ).loc[:,0].values.reshape((-1,1)) assert(T_MAX==len(p_survive)-1) # table starts at age 0 if baseline_sex == 'female': p_other_sex = pd.read_csv(os.path.join(path_dav,r'DAV2008T{}.csv'.format('male')), delimiter = ';', header=None ).loc[:,0].values.reshape((-1,1)) tag_other_sex = 'DAVT2008male' elif baseline_sex == 'male': p_other_sex = pd.read_csv(os.path.join(path_dav,r'DAV2008T{}.csv'.format('female')), delimiter = ';', header=None ).loc[:,0].values.reshape((-1,1)) tag_other_sex = 'DAVT2008female' else: raise ValueError('Unknown baseline_sex') print('\t tensorflow-version: ', tf.__version__) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' print('\t tensorflow-warnings: off') #print("\t GPU Available: ", tf.test.is_gpu_available()) # <--- enable if GPU devices are (expected to be) available; disabled for local CPU pre-training print('------------------------------------------------') freqs = [1,1/2, 1/3, 1/6, 1/12] # data generation modulized by create_trainingdata_baseline() x, y = create_trainingdata_baseline(frequencies = freqs, surv_probs=p_survive, age_scale=T_MAX) x, y = shuffle(x, y) BATCH = 32 # 1024 #min(1024, len(x)) LRATE = 0.001 EPOCHS = 30000 WIDTHS = [40,40,20]#[20,20,20] # n_in = x.shape[1] n_out = 2 if bool_train: print('------------------------------------------------') print('\t NOTE: baseline surv-model will be trained!') print('\t This is currently manually disabled, as it will require a full recallibration of the subsequent, residual network.') print('\t To activate a retraining of the baseline model, uncomment ValueError in subsequent line.') raise ValueError('Training of baseline model deactivated!') print('------------------------------------------------') model = create_baseline_model_ffn(n_in=n_in, n_out=n_out, h_units=WIDTHS, h_actv= ['relu']*(len(WIDTHS)-1)+['tanh'], tf_loss_function = tf.keras.losses.KLDivergence(),#'mae', #'mean_squared_logarithmic_error', # optimizer=tf.keras.optimizers.Adam(lr=LRATE)) model.fit(x, y, batch_size=BATCH, epochs= EPOCHS, verbose=1, callbacks=callbacks) history = np.stack([np.array(model.history.history['loss']), np.array(model.history.history['mae'])], axis = 0) #np.array(model.history.history, ndmin=2) model.save(os.path.join(path_models_baseline_transfer, r'ffn_davT{}.h5'.format(baseline_sex))) np.save(os.path.join(path_models_baseline_transfer , r'hist_{}.npy'.format(baseline_sex)), history) # transfer weights to rnn-type model (for later use) # sequential character benefitial to non-Markovian HMC-objective model_rnn = create_baseline_model_rnn(input_shape=(None, n_in), n_out= n_out, hidden_layers=[40,40,20]) transfer_weights_dense2simpleRNN(dense_model= model, rnn_model = model_rnn) model_rnn.save(os.path.join(path_models_baseline_transfer, r'rnn_davT{}.h5'.format(baseline_sex))) print('Weights transferred from ffn to rnn!') assert (check_if_rnn_version(model_ffn=model, model_rnn=model_rnn)==True).all() print('FFN evaluated: ', model.evaluate(x,y, batch_size=1024, verbose = 0)) print('RNN evaluated: ', model_rnn.evaluate(x.reshape(1,-1,n_in),y.reshape(1,-1,n_out), batch_size=1024, verbose = 0)) else: # model = load_model(path_models_baseline_transfer, r'survival_baseline_{}.h5'.format(baseline_sex)) model = load_model(os.path.join(path_models_baseline_transfer, r'ffn_davT{}.h5'.format(baseline_sex))) history = np.load(os.path.join(path_models_baseline_transfer , r'hist_{}.npy'.format(baseline_sex)), allow_pickle= True)#.item() model_rnn = load_model(os.path.join(path_models_baseline_transfer, r'rnn_davT{}.h5'.format(baseline_sex))) print(model.summary()) print(model.evaluate(x,y, batch_size=1024, verbose = 0)) # visualize training process of FNN-model if bool_plot: _, ax = plt.subplots(1,2,figsize=(10,4)) if type(history) == type({}): ax[0].plot(history['loss']) ax[1].plot(history['mae']) else: ax[0].plot(history[0]) ax[1].plot(history[1]) ax[0].set_ylabel('loss') ax[1].set_ylabel('mae') ax[0].set_xlabel('iteration') ax[1].set_xlabel('iteration') ax[0].set_yscale('log') ax[1].set_yscale('log') plt.tight_layout() plt.show() # visualize fit of FFN vs baseline-DAV-table x, y = create_trainingdata_baseline(frequencies = freqs, surv_probs=p_survive, age_scale=T_MAX) # do not shuffle to preserve order for ploting for k in range(len(freqs)): # note: invert the iter_prod of age and freq plt.plot(x[k:-1:len(freqs),0]*T_MAX, y[k:-1:len(freqs),1], linestyle = '-', color = 'black') # plt.plot(x[k:-1:len(freqs),0]*T_MAX, y[k:-1:len(freqs),1], linestyle = '-', color = 'gray') plt.plot(x[k:-1:len(freqs),0]*T_MAX, model.predict(x[k:-1:len(freqs),:])[:,1], linestyle = '--', color = 'orange') # plt.plot(x[k:-1:len(freqs),0]*T_MAX, model.predict(x[k:-1:len(freqs),:])[:,1], linestyle = '--', color = 'green') plt.yscale('log') plt.xlabel('age') #, fontsize = 'x-large') # create labels plt.plot(x[k:-1:len(freqs),0]*T_MAX, y[k:-1:len(freqs),1], linestyle = '-', color = 'black', label = r'$\mathcal{D}_{DAV}($' + baseline_sex+r')') plt.plot(x[k:-1:len(freqs),0]*T_MAX, model.predict(x[k:-1:len(freqs),:])[:,1], linestyle = '--', color = 'orange', label = r'$\hat{\pi}_{base}$') plt.legend() plt.tight_layout() plt.savefig(os.path.join(path_models_baseline_transfer, 'baseline_fit_{}.eps'.format(baseline_sex)), format = 'eps', dpi = 400) # plt.show() plt.close() if bool_plot: # visualize fit of FFN and RNN vs baseline-DAV-table plt.plot(x[:,0]*T_MAX, model.predict(x)[:,0], 'xg', alpha = .5, label='ffn') plt.plot(x[:,0]*T_MAX, model_rnn.predict(x.reshape(1,-1,n_in))[0,:,0].flatten(), 'ob', alpha = .2, label='rnn') plt.plot(x[:,0]*T_MAX, y[:,0], linestyle = 'None', marker = '_', color = 'red', label='DAV') plt.plot(x[:,0]*T_MAX, model.predict(x)[:,1], 'xg', alpha = .5) plt.plot(x[:,0]*T_MAX, model_rnn.predict(x.reshape(1,-1,n_in))[0,:,1].flatten(), 'ob', alpha = .2) plt.plot(x[:,0]*T_MAX, y[:,1], linestyle = 'None', marker = '_', color = 'red',) plt.yscale('log') plt.title('Fit - FFN vs. RNN vs DAVT2008{}'.format(baseline_sex)) plt.legend() plt.show() if __name__ == '__main__': bool_train = False for baseline_sex in ['male', 'female']: run_main(baseline_sex, bool_train)
[ "functions.tf_model_base.transfer_weights_dense2simpleRNN", "tensorflow.keras.losses.KLDivergence", "functions.sub_backtesting.check_if_rnn_version", "tensorflow.keras.callbacks.LearningRateScheduler", "sklearn.utils.shuffle", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "functions.sub_data_p...
[((1231, 1326), 'tensorflow.keras.callbacks.EarlyStopping', 'tf.keras.callbacks.EarlyStopping', ([], {'monitor': '"""mape"""', 'patience': '(10000)', 'restore_best_weights': '(True)'}), "(monitor='mape', patience=10000,\n restore_best_weights=True)\n", (1263, 1326), True, 'import tensorflow as tf\n'), ((2884, 2974), 'functions.sub_data_prep.create_trainingdata_baseline', 'create_trainingdata_baseline', ([], {'frequencies': 'freqs', 'surv_probs': 'p_survive', 'age_scale': 'T_MAX'}), '(frequencies=freqs, surv_probs=p_survive,\n age_scale=T_MAX)\n', (2912, 2974), False, 'from functions.sub_data_prep import create_trainingdata_baseline\n'), ((2984, 2997), 'sklearn.utils.shuffle', 'shuffle', (['x', 'y'], {}), '(x, y)\n', (2991, 2997), False, 'from sklearn.utils import shuffle\n'), ((6546, 6636), 'functions.sub_data_prep.create_trainingdata_baseline', 'create_trainingdata_baseline', ([], {'frequencies': 'freqs', 'surv_probs': 'p_survive', 'age_scale': 'T_MAX'}), '(frequencies=freqs, surv_probs=p_survive,\n age_scale=T_MAX)\n', (6574, 6636), False, 'from functions.sub_data_prep import create_trainingdata_baseline\n'), ((7225, 7242), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (7235, 7242), True, 'import matplotlib.pyplot as plt\n'), ((7247, 7264), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""age"""'], {}), "('age')\n", (7257, 7264), True, 'import matplotlib.pyplot as plt\n'), ((7615, 7627), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (7625, 7627), True, 'import matplotlib.pyplot as plt\n'), ((7632, 7650), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (7648, 7650), True, 'import matplotlib.pyplot as plt\n'), ((7804, 7815), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (7813, 7815), True, 'import matplotlib.pyplot as plt\n'), ((1595, 1648), 'tensorflow.keras.callbacks.LearningRateScheduler', 'tf.keras.callbacks.LearningRateScheduler', (['lr_schedule'], {}), '(lr_schedule)\n', (1635, 1648), True, 'import tensorflow as tf\n'), ((4660, 4756), 'functions.tf_model_base.create_baseline_model_rnn', 'create_baseline_model_rnn', ([], {'input_shape': '(None, n_in)', 'n_out': 'n_out', 'hidden_layers': '[40, 40, 20]'}), '(input_shape=(None, n_in), n_out=n_out,\n hidden_layers=[40, 40, 20])\n', (4685, 4756), False, 'from functions.tf_model_base import create_baseline_model_ffn, create_baseline_model_rnn, transfer_weights_dense2simpleRNN\n'), ((4760, 4832), 'functions.tf_model_base.transfer_weights_dense2simpleRNN', 'transfer_weights_dense2simpleRNN', ([], {'dense_model': 'model', 'rnn_model': 'model_rnn'}), '(dense_model=model, rnn_model=model_rnn)\n', (4792, 4832), False, 'from functions.tf_model_base import create_baseline_model_ffn, create_baseline_model_rnn, transfer_weights_dense2simpleRNN\n'), ((5996, 6031), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(10, 4)'}), '(1, 2, figsize=(10, 4))\n', (6008, 6031), True, 'import matplotlib.pyplot as plt\n'), ((6443, 6461), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (6459, 6461), True, 'import matplotlib.pyplot as plt\n'), ((6470, 6480), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6478, 6480), True, 'import matplotlib.pyplot as plt\n'), ((8122, 8217), 'matplotlib.pyplot.plot', 'plt.plot', (['(x[:, 0] * T_MAX)', 'y[:, 0]'], {'linestyle': '"""None"""', 'marker': '"""_"""', 'color': '"""red"""', 'label': '"""DAV"""'}), "(x[:, 0] * T_MAX, y[:, 0], linestyle='None', marker='_', color=\n 'red', label='DAV')\n", (8130, 8217), True, 'import matplotlib.pyplot as plt\n'), ((8411, 8488), 'matplotlib.pyplot.plot', 'plt.plot', (['(x[:, 0] * T_MAX)', 'y[:, 1]'], {'linestyle': '"""None"""', 'marker': '"""_"""', 'color': '"""red"""'}), "(x[:, 0] * T_MAX, y[:, 1], linestyle='None', marker='_', color='red')\n", (8419, 8488), True, 'import matplotlib.pyplot as plt\n'), ((8500, 8517), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (8510, 8517), True, 'import matplotlib.pyplot as plt\n'), ((8600, 8612), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (8610, 8612), True, 'import matplotlib.pyplot as plt\n'), ((8621, 8631), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8629, 8631), True, 'import matplotlib.pyplot as plt\n'), ((3869, 3899), 'tensorflow.keras.losses.KLDivergence', 'tf.keras.losses.KLDivergence', ([], {}), '()\n', (3897, 3899), True, 'import tensorflow as tf\n'), ((3991, 4025), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'lr': 'LRATE'}), '(lr=LRATE)\n', (4015, 4025), True, 'import tensorflow as tf\n'), ((4145, 4184), 'numpy.array', 'np.array', (["model.history.history['loss']"], {}), "(model.history.history['loss'])\n", (4153, 4184), True, 'import numpy as np\n'), ((4186, 4224), 'numpy.array', 'np.array', (["model.history.history['mae']"], {}), "(model.history.history['mae'])\n", (4194, 4224), True, 'import numpy as np\n'), ((5018, 5076), 'functions.sub_backtesting.check_if_rnn_version', 'check_if_rnn_version', ([], {'model_ffn': 'model', 'model_rnn': 'model_rnn'}), '(model_ffn=model, model_rnn=model_rnn)\n', (5038, 5076), False, 'from functions.sub_backtesting import check_if_rnn_version\n')]
# @Author: <NAME> <arthur> # @Date: 09.05.2021 # @Filename: test_gdt.py # @Last modified by: arthur # @Last modified time: 15.09.2021 import pyrexMD.misc as misc import pyrexMD.analysis.gdt as gdt from pyrexMD.analysis.analyze import get_Distance_Matrices import MDAnalysis as mda import numpy as np from numpy.testing import assert_allclose from unittest.mock import patch import pathlib import pytest import os # find main directory of pyrexMD posixpath = pathlib.Path(".").rglob("*core.py") # generator for matching paths pathname = posixpath.send(None).as_posix() # get first path name main_dir = os.path.relpath(os.path.realpath(pathname).rstrip("core.py")) # main directory of pyrexMD # set up test paths cwd = os.getcwd() print(f"cwd: {cwd}") pre = f"{main_dir}/tests/files/1l2y" pdb = f"{pre}/1l2y_ref.pdb" tpr = f"{pre}/traj.tpr" xtc = f"{pre}/traj.xtc" def test_get_array_percent(): p, ndx = gdt.get_array_percent(np.load(f"{pre}/DIST_ARR.npy"), cutoff=1.0) v1, v2 = np.load(f"{pre}/array_percent_1.npy", allow_pickle=True) assert assert_allclose(p, v1) == None assert assert_allclose(ndx, v2) == None p, ndx = gdt.get_array_percent(np.load(f"{pre}/DIST_ARR.npy"), cutoff=2.0) v1, v2 = np.load(f"{pre}/array_percent_2.npy", allow_pickle=True) assert assert_allclose(p, v1) == None assert assert_allclose(ndx, v2) == None p, ndx = gdt.get_array_percent(np.load(f"{pre}/DIST_ARR.npy"), cutoff=4.0) v1, v2 = np.load(f"{pre}/array_percent_4.npy", allow_pickle=True) assert assert_allclose(p, v1) == None assert assert_allclose(ndx, v2) == None return def test_get_Pair_Distances(): mobile = mda.Universe(tpr, xtc, tpr_resid_from_one=True) ref = mda.Universe(pdb) PAIR_DISTANCES, RMSD, resids_mobile, resids_ref = gdt.get_Pair_Distances(mobile, ref) assert assert_allclose(PAIR_DISTANCES, np.load(f"{pre}/PAIR_DISTANCES.npy")) == None assert assert_allclose(RMSD, np.load(f"{pre}/RMSD.npy")) == None assert assert_allclose(resids_mobile, np.load(f"{pre}/resids_mobile.npy")) == None assert assert_allclose(resids_ref, np.load(f"{pre}/resids_ref.npy")) == None return def test_HELP_sss_None2int(): mobile = mda.Universe(tpr, xtc, tpr_resid_from_one=True) cfg = misc.CONFIG({"sss": [None, None, None], "start": None, "stop": None, "step": None}) expected = misc.CONFIG({"sss": [0, 21, 1], "start": 0, "stop": 21, "step": 1}) val = gdt._HELP_sss_None2int(mobile, cfg) assert val.items() == expected.items() ############################################################################ mobile = mda.Universe(tpr, xtc, tpr_resid_from_one=True) DM = get_Distance_Matrices(mobile, stop=10) cfg = misc.CONFIG({"sss": [None, None, None], "start": None, "stop": None, "step": None}) expected = misc.CONFIG({"sss": [0, 10, 1], "start": 0, "stop": 10, "step": 1}) val = gdt._HELP_sss_None2int(DM, cfg) assert val.items() == expected.items() return def test_GDT(): mobile = mda.Universe(tpr, xtc, tpr_resid_from_one=True) ref = mda.Universe(pdb) GDT_percent, GDT_resids, GDT_cutoff, RMSD, FRAME = gdt.GDT(mobile, ref) assert assert_allclose(GDT_percent, np.load(f"{pre}/GDT_percent.npy")) == None assert assert_allclose(GDT_cutoff, np.load(f"{pre}/GDT_cutoff.npy")) == None assert assert_allclose(RMSD, np.load(f"{pre}/GDT_RMSD.npy")) == None assert assert_allclose(FRAME, np.load(f"{pre}/GDT_FRAME.npy")) == None # GDT_resids has complicated structure with changing data types flat1 = misc.flatten_array(GDT_resids) flat2 = misc.flatten_array(np.load(f"{pre}/GDT_resids.npy", allow_pickle=True)) for i in range(len(flat1)): assert (flat1[i] == flat2[i]).all() return def test_GDT_rna(): mobile = mda.Universe(tpr, xtc, tpr_resid_from_one=True) ref = mda.Universe(pdb) GDT_percent, GDT_resids, GDT_cutoff, RMSD, FRAME = gdt.GDT_rna(mobile, ref, sel1="protein and name CA", sel2="protein and name CA", cutoff=[0.5, 10, 0.5]) assert assert_allclose(GDT_percent, np.load(f"{pre}/GDT_percent.npy")) == None assert assert_allclose(GDT_cutoff, np.load(f"{pre}/GDT_cutoff.npy")) == None assert assert_allclose(RMSD, np.load(f"{pre}/GDT_RMSD.npy")) == None assert assert_allclose(FRAME, np.load(f"{pre}/GDT_FRAME.npy")) == None # GDT_resids has complicated structure with changing data types flat1 = misc.flatten_array(GDT_resids) flat2 = misc.flatten_array(np.load(f"{pre}/GDT_resids.npy", allow_pickle=True)) for i in range(len(flat1)): assert (flat1[i] == flat2[i]).all() return def test_GDT_match_cutoff_dim(): GDT_cutoff = [1, 2] # random test data GDT_percent = [[100, 80], [80, 40]] # random test data expected = [[[100, 80], [80, 40]], [[100, 80], [80, 40]]] val = gdt.GDT_match_cutoff_dim(GDT_cutoff, GDT_percent) assert val == expected @patch("matplotlib.pyplot.show") def test_plot_GDT(mock_show): mobile = mda.Universe(tpr, xtc, tpr_resid_from_one=True) ref = mda.Universe(pdb) GDT_percent, GDT_resids, GDT_cutoff, RMSD, FRAME = gdt.GDT(mobile, ref) fig, ax = gdt.plot_GDT(GDT_percent, GDT_cutoff) assert fig != None assert ax != None return def test_get_GDT_TS(): GDT_percent = np.load(f"{pre}/GDT_percent.npy") GDT_TS = gdt.get_GDT_TS(GDT_percent) assert assert_allclose(GDT_TS, np.load(f"{pre}/GDT_TS.npy")) == None return def test_get_GDT_HA(): GDT_percent = np.load(f"{pre}/GDT_percent.npy") GDT_HA = gdt.get_GDT_HA(GDT_percent) assert assert_allclose(GDT_HA, np.load(f"{pre}/GDT_HA.npy")) == None return def test_rank_scores(): GDT_TS = np.load(f"{pre}/GDT_TS.npy") GDT_HA = np.load(f"{pre}/GDT_HA.npy") rank_scores = gdt.rank_scores(GDT_TS, GDT_HA) assert (rank_scores == np.load(f"{pre}/rank_scores.npy")).all() assert (rank_scores == np.load(f"{pre}/GDT_rank_scores.npy")).all() # coverage gdt.rank_scores(GDT_TS, GDT_HA, ranking_order="GDT_HA") gdt.rank_scores(GDT_TS, GDT_HA, ranking_order=None) with pytest.raises(ValueError): gdt.rank_scores(GDT_TS, GDT_HA, ranking_order="invalid_value") return def test_GDT_rank_scores(): GDT_percent = np.load(f"{pre}/GDT_percent.npy") GDT_rank_scores = gdt.GDT_rank_scores(GDT_percent) assert (GDT_rank_scores == np.load(f"{pre}/GDT_rank_scores.npy")).all() assert (GDT_rank_scores == np.load(f"{pre}/rank_scores.npy")).all() return def test_GDT_rank_percent(): GDT_percent = np.load(f"{pre}/GDT_percent.npy") GDT_rank_percent = gdt.GDT_rank_percent(GDT_percent) assert assert_allclose(GDT_rank_percent, np.load(f"{pre}/GDT_rank_percent.npy")) == None # coverage gdt.GDT_rank_percent(GDT_percent, norm=False) return def test_get_continous_segments(): continous_segments = gdt.get_continuous_segments([1, 2, 3, 22, 23, 50, 51, 52]) assert (continous_segments == [[1, 2, 3], [22, 23], [50, 51, 52]]) return def test_GDT_continous_segments(): GDT_resids = np.load(f"{pre}/GDT_resids.npy", allow_pickle=True) GDT_continous_segments = gdt.GDT_continuous_segments(GDT_resids) assert (GDT_continous_segments == np.load(f"{pre}/GDT_continous_segments.npy", allow_pickle=True)).all() return @ patch("matplotlib.pyplot.show") def test_plot_LA(mock_show): mobile = mda.Universe(tpr, xtc, tpr_resid_from_one=True) ref = mda.Universe(pdb) GDT = gdt.GDT(mobile, ref) GDT_percent, GDT_resids, GDT_cutoff, RMSD, FRAME = GDT SCORES = gdt.GDT_rank_scores(GDT_percent, ranking_order="GDT_TS", verbose=False) GDT_TS_ranked, GDT_HA_ranked, GDT_ndx_ranked = SCORES fig, ax, LA_data = gdt.plot_LA(mobile, ref, SCORES[0], SCORES[1], SCORES[2]) assert fig != None assert ax != None assert LA_data != None # coverage gdt.plot_LA(mobile, ref, SCORES[0], SCORES[1], SCORES[2], show_frames=True, show_scores=True, cbar_min=0, cbar_max=2) gdt.plot_LA(mobile, ref, SCORES[0], SCORES[1], SCORES[2], show_frames=True, show_scores=False, show_cbar=False, save_as="./temp.png") misc.rm("./temp.png") return @ patch("matplotlib.pyplot.show") def test_plot_LA_rna(mock_show): mobile = mda.Universe(tpr, xtc, tpr_resid_from_one=True) ref = mda.Universe(pdb) GDT = gdt.GDT(mobile, ref) GDT_percent, GDT_resids, GDT_cutoff, RMSD, FRAME = GDT SCORES = gdt.GDT_rank_scores(GDT_percent, ranking_order="GDT_TS", verbose=False) GDT_TS_ranked, GDT_HA_ranked, GDT_ndx_ranked = SCORES fig, ax, LA_data = gdt.plot_LA_rna(mobile, ref, SCORES[0], SCORES[1], SCORES[2], sel1="protein and name CA", sel2="protein and name CA", cmap="GDT_TS") assert fig != None assert ax != None assert LA_data != None return
[ "pyrexMD.analysis.gdt.plot_GDT", "pyrexMD.analysis.gdt.GDT_continuous_segments", "pyrexMD.analysis.gdt.get_GDT_TS", "pyrexMD.analysis.gdt.GDT_rank_percent", "pyrexMD.analysis.gdt.get_continuous_segments", "pyrexMD.analysis.gdt.plot_LA", "unittest.mock.patch", "pathlib.Path", "numpy.testing.assert_al...
[((735, 746), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (744, 746), False, 'import os\n'), ((5264, 5295), 'unittest.mock.patch', 'patch', (['"""matplotlib.pyplot.show"""'], {}), "('matplotlib.pyplot.show')\n", (5269, 5295), False, 'from unittest.mock import patch\n'), ((7661, 7692), 'unittest.mock.patch', 'patch', (['"""matplotlib.pyplot.show"""'], {}), "('matplotlib.pyplot.show')\n", (7666, 7692), False, 'from unittest.mock import patch\n'), ((8515, 8546), 'unittest.mock.patch', 'patch', (['"""matplotlib.pyplot.show"""'], {}), "('matplotlib.pyplot.show')\n", (8520, 8546), False, 'from unittest.mock import patch\n'), ((1005, 1061), 'numpy.load', 'np.load', (['f"""{pre}/array_percent_1.npy"""'], {'allow_pickle': '(True)'}), "(f'{pre}/array_percent_1.npy', allow_pickle=True)\n", (1012, 1061), True, 'import numpy as np\n'), ((1241, 1297), 'numpy.load', 'np.load', (['f"""{pre}/array_percent_2.npy"""'], {'allow_pickle': '(True)'}), "(f'{pre}/array_percent_2.npy', allow_pickle=True)\n", (1248, 1297), True, 'import numpy as np\n'), ((1477, 1533), 'numpy.load', 'np.load', (['f"""{pre}/array_percent_4.npy"""'], {'allow_pickle': '(True)'}), "(f'{pre}/array_percent_4.npy', allow_pickle=True)\n", (1484, 1533), True, 'import numpy as np\n'), ((1677, 1724), 'MDAnalysis.Universe', 'mda.Universe', (['tpr', 'xtc'], {'tpr_resid_from_one': '(True)'}), '(tpr, xtc, tpr_resid_from_one=True)\n', (1689, 1724), True, 'import MDAnalysis as mda\n'), ((1735, 1752), 'MDAnalysis.Universe', 'mda.Universe', (['pdb'], {}), '(pdb)\n', (1747, 1752), True, 'import MDAnalysis as mda\n'), ((1807, 1842), 'pyrexMD.analysis.gdt.get_Pair_Distances', 'gdt.get_Pair_Distances', (['mobile', 'ref'], {}), '(mobile, ref)\n', (1829, 1842), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((2226, 2273), 'MDAnalysis.Universe', 'mda.Universe', (['tpr', 'xtc'], {'tpr_resid_from_one': '(True)'}), '(tpr, xtc, tpr_resid_from_one=True)\n', (2238, 2273), True, 'import MDAnalysis as mda\n'), ((2284, 2371), 'pyrexMD.misc.CONFIG', 'misc.CONFIG', (["{'sss': [None, None, None], 'start': None, 'stop': None, 'step': None}"], {}), "({'sss': [None, None, None], 'start': None, 'stop': None, 'step':\n None})\n", (2295, 2371), True, 'import pyrexMD.misc as misc\n'), ((2452, 2519), 'pyrexMD.misc.CONFIG', 'misc.CONFIG', (["{'sss': [0, 21, 1], 'start': 0, 'stop': 21, 'step': 1}"], {}), "({'sss': [0, 21, 1], 'start': 0, 'stop': 21, 'step': 1})\n", (2463, 2519), True, 'import pyrexMD.misc as misc\n'), ((2615, 2650), 'pyrexMD.analysis.gdt._HELP_sss_None2int', 'gdt._HELP_sss_None2int', (['mobile', 'cfg'], {}), '(mobile, cfg)\n', (2637, 2650), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((2788, 2835), 'MDAnalysis.Universe', 'mda.Universe', (['tpr', 'xtc'], {'tpr_resid_from_one': '(True)'}), '(tpr, xtc, tpr_resid_from_one=True)\n', (2800, 2835), True, 'import MDAnalysis as mda\n'), ((2845, 2883), 'pyrexMD.analysis.analyze.get_Distance_Matrices', 'get_Distance_Matrices', (['mobile'], {'stop': '(10)'}), '(mobile, stop=10)\n', (2866, 2883), False, 'from pyrexMD.analysis.analyze import get_Distance_Matrices\n'), ((2894, 2981), 'pyrexMD.misc.CONFIG', 'misc.CONFIG', (["{'sss': [None, None, None], 'start': None, 'stop': None, 'step': None}"], {}), "({'sss': [None, None, None], 'start': None, 'stop': None, 'step':\n None})\n", (2905, 2981), True, 'import pyrexMD.misc as misc\n'), ((3062, 3129), 'pyrexMD.misc.CONFIG', 'misc.CONFIG', (["{'sss': [0, 10, 1], 'start': 0, 'stop': 10, 'step': 1}"], {}), "({'sss': [0, 10, 1], 'start': 0, 'stop': 10, 'step': 1})\n", (3073, 3129), True, 'import pyrexMD.misc as misc\n'), ((3224, 3255), 'pyrexMD.analysis.gdt._HELP_sss_None2int', 'gdt._HELP_sss_None2int', (['DM', 'cfg'], {}), '(DM, cfg)\n', (3246, 3255), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((3341, 3388), 'MDAnalysis.Universe', 'mda.Universe', (['tpr', 'xtc'], {'tpr_resid_from_one': '(True)'}), '(tpr, xtc, tpr_resid_from_one=True)\n', (3353, 3388), True, 'import MDAnalysis as mda\n'), ((3399, 3416), 'MDAnalysis.Universe', 'mda.Universe', (['pdb'], {}), '(pdb)\n', (3411, 3416), True, 'import MDAnalysis as mda\n'), ((3472, 3492), 'pyrexMD.analysis.gdt.GDT', 'gdt.GDT', (['mobile', 'ref'], {}), '(mobile, ref)\n', (3479, 3492), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((3887, 3917), 'pyrexMD.misc.flatten_array', 'misc.flatten_array', (['GDT_resids'], {}), '(GDT_resids)\n', (3905, 3917), True, 'import pyrexMD.misc as misc\n'), ((4124, 4171), 'MDAnalysis.Universe', 'mda.Universe', (['tpr', 'xtc'], {'tpr_resid_from_one': '(True)'}), '(tpr, xtc, tpr_resid_from_one=True)\n', (4136, 4171), True, 'import MDAnalysis as mda\n'), ((4182, 4199), 'MDAnalysis.Universe', 'mda.Universe', (['pdb'], {}), '(pdb)\n', (4194, 4199), True, 'import MDAnalysis as mda\n'), ((4255, 4363), 'pyrexMD.analysis.gdt.GDT_rna', 'gdt.GDT_rna', (['mobile', 'ref'], {'sel1': '"""protein and name CA"""', 'sel2': '"""protein and name CA"""', 'cutoff': '[0.5, 10, 0.5]'}), "(mobile, ref, sel1='protein and name CA', sel2=\n 'protein and name CA', cutoff=[0.5, 10, 0.5])\n", (4266, 4363), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((4753, 4783), 'pyrexMD.misc.flatten_array', 'misc.flatten_array', (['GDT_resids'], {}), '(GDT_resids)\n', (4771, 4783), True, 'import pyrexMD.misc as misc\n'), ((5184, 5233), 'pyrexMD.analysis.gdt.GDT_match_cutoff_dim', 'gdt.GDT_match_cutoff_dim', (['GDT_cutoff', 'GDT_percent'], {}), '(GDT_cutoff, GDT_percent)\n', (5208, 5233), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((5339, 5386), 'MDAnalysis.Universe', 'mda.Universe', (['tpr', 'xtc'], {'tpr_resid_from_one': '(True)'}), '(tpr, xtc, tpr_resid_from_one=True)\n', (5351, 5386), True, 'import MDAnalysis as mda\n'), ((5397, 5414), 'MDAnalysis.Universe', 'mda.Universe', (['pdb'], {}), '(pdb)\n', (5409, 5414), True, 'import MDAnalysis as mda\n'), ((5470, 5490), 'pyrexMD.analysis.gdt.GDT', 'gdt.GDT', (['mobile', 'ref'], {}), '(mobile, ref)\n', (5477, 5490), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((5505, 5542), 'pyrexMD.analysis.gdt.plot_GDT', 'gdt.plot_GDT', (['GDT_percent', 'GDT_cutoff'], {}), '(GDT_percent, GDT_cutoff)\n', (5517, 5542), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((5642, 5675), 'numpy.load', 'np.load', (['f"""{pre}/GDT_percent.npy"""'], {}), "(f'{pre}/GDT_percent.npy')\n", (5649, 5675), True, 'import numpy as np\n'), ((5689, 5716), 'pyrexMD.analysis.gdt.get_GDT_TS', 'gdt.get_GDT_TS', (['GDT_percent'], {}), '(GDT_percent)\n', (5703, 5716), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((5844, 5877), 'numpy.load', 'np.load', (['f"""{pre}/GDT_percent.npy"""'], {}), "(f'{pre}/GDT_percent.npy')\n", (5851, 5877), True, 'import numpy as np\n'), ((5891, 5918), 'pyrexMD.analysis.gdt.get_GDT_HA', 'gdt.get_GDT_HA', (['GDT_percent'], {}), '(GDT_percent)\n', (5905, 5918), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((6042, 6070), 'numpy.load', 'np.load', (['f"""{pre}/GDT_TS.npy"""'], {}), "(f'{pre}/GDT_TS.npy')\n", (6049, 6070), True, 'import numpy as np\n'), ((6084, 6112), 'numpy.load', 'np.load', (['f"""{pre}/GDT_HA.npy"""'], {}), "(f'{pre}/GDT_HA.npy')\n", (6091, 6112), True, 'import numpy as np\n'), ((6131, 6162), 'pyrexMD.analysis.gdt.rank_scores', 'gdt.rank_scores', (['GDT_TS', 'GDT_HA'], {}), '(GDT_TS, GDT_HA)\n', (6146, 6162), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((6323, 6378), 'pyrexMD.analysis.gdt.rank_scores', 'gdt.rank_scores', (['GDT_TS', 'GDT_HA'], {'ranking_order': '"""GDT_HA"""'}), "(GDT_TS, GDT_HA, ranking_order='GDT_HA')\n", (6338, 6378), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((6383, 6434), 'pyrexMD.analysis.gdt.rank_scores', 'gdt.rank_scores', (['GDT_TS', 'GDT_HA'], {'ranking_order': 'None'}), '(GDT_TS, GDT_HA, ranking_order=None)\n', (6398, 6434), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((6601, 6634), 'numpy.load', 'np.load', (['f"""{pre}/GDT_percent.npy"""'], {}), "(f'{pre}/GDT_percent.npy')\n", (6608, 6634), True, 'import numpy as np\n'), ((6657, 6689), 'pyrexMD.analysis.gdt.GDT_rank_scores', 'gdt.GDT_rank_scores', (['GDT_percent'], {}), '(GDT_percent)\n', (6676, 6689), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((6898, 6931), 'numpy.load', 'np.load', (['f"""{pre}/GDT_percent.npy"""'], {}), "(f'{pre}/GDT_percent.npy')\n", (6905, 6931), True, 'import numpy as np\n'), ((6955, 6988), 'pyrexMD.analysis.gdt.GDT_rank_percent', 'gdt.GDT_rank_percent', (['GDT_percent'], {}), '(GDT_percent)\n', (6975, 6988), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((7102, 7147), 'pyrexMD.analysis.gdt.GDT_rank_percent', 'gdt.GDT_rank_percent', (['GDT_percent'], {'norm': '(False)'}), '(GDT_percent, norm=False)\n', (7122, 7147), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((7221, 7279), 'pyrexMD.analysis.gdt.get_continuous_segments', 'gdt.get_continuous_segments', (['[1, 2, 3, 22, 23, 50, 51, 52]'], {}), '([1, 2, 3, 22, 23, 50, 51, 52])\n', (7248, 7279), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((7416, 7467), 'numpy.load', 'np.load', (['f"""{pre}/GDT_resids.npy"""'], {'allow_pickle': '(True)'}), "(f'{pre}/GDT_resids.npy', allow_pickle=True)\n", (7423, 7467), True, 'import numpy as np\n'), ((7497, 7536), 'pyrexMD.analysis.gdt.GDT_continuous_segments', 'gdt.GDT_continuous_segments', (['GDT_resids'], {}), '(GDT_resids)\n', (7524, 7536), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((7735, 7782), 'MDAnalysis.Universe', 'mda.Universe', (['tpr', 'xtc'], {'tpr_resid_from_one': '(True)'}), '(tpr, xtc, tpr_resid_from_one=True)\n', (7747, 7782), True, 'import MDAnalysis as mda\n'), ((7793, 7810), 'MDAnalysis.Universe', 'mda.Universe', (['pdb'], {}), '(pdb)\n', (7805, 7810), True, 'import MDAnalysis as mda\n'), ((7821, 7841), 'pyrexMD.analysis.gdt.GDT', 'gdt.GDT', (['mobile', 'ref'], {}), '(mobile, ref)\n', (7828, 7841), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((7914, 7985), 'pyrexMD.analysis.gdt.GDT_rank_scores', 'gdt.GDT_rank_scores', (['GDT_percent'], {'ranking_order': '"""GDT_TS"""', 'verbose': '(False)'}), "(GDT_percent, ranking_order='GDT_TS', verbose=False)\n", (7933, 7985), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((8068, 8125), 'pyrexMD.analysis.gdt.plot_LA', 'gdt.plot_LA', (['mobile', 'ref', 'SCORES[0]', 'SCORES[1]', 'SCORES[2]'], {}), '(mobile, ref, SCORES[0], SCORES[1], SCORES[2])\n', (8079, 8125), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((8218, 8339), 'pyrexMD.analysis.gdt.plot_LA', 'gdt.plot_LA', (['mobile', 'ref', 'SCORES[0]', 'SCORES[1]', 'SCORES[2]'], {'show_frames': '(True)', 'show_scores': '(True)', 'cbar_min': '(0)', 'cbar_max': '(2)'}), '(mobile, ref, SCORES[0], SCORES[1], SCORES[2], show_frames=True,\n show_scores=True, cbar_min=0, cbar_max=2)\n', (8229, 8339), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((8340, 8477), 'pyrexMD.analysis.gdt.plot_LA', 'gdt.plot_LA', (['mobile', 'ref', 'SCORES[0]', 'SCORES[1]', 'SCORES[2]'], {'show_frames': '(True)', 'show_scores': '(False)', 'show_cbar': '(False)', 'save_as': '"""./temp.png"""'}), "(mobile, ref, SCORES[0], SCORES[1], SCORES[2], show_frames=True,\n show_scores=False, show_cbar=False, save_as='./temp.png')\n", (8351, 8477), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((8478, 8499), 'pyrexMD.misc.rm', 'misc.rm', (['"""./temp.png"""'], {}), "('./temp.png')\n", (8485, 8499), True, 'import pyrexMD.misc as misc\n'), ((8593, 8640), 'MDAnalysis.Universe', 'mda.Universe', (['tpr', 'xtc'], {'tpr_resid_from_one': '(True)'}), '(tpr, xtc, tpr_resid_from_one=True)\n', (8605, 8640), True, 'import MDAnalysis as mda\n'), ((8651, 8668), 'MDAnalysis.Universe', 'mda.Universe', (['pdb'], {}), '(pdb)\n', (8663, 8668), True, 'import MDAnalysis as mda\n'), ((8679, 8699), 'pyrexMD.analysis.gdt.GDT', 'gdt.GDT', (['mobile', 'ref'], {}), '(mobile, ref)\n', (8686, 8699), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((8772, 8843), 'pyrexMD.analysis.gdt.GDT_rank_scores', 'gdt.GDT_rank_scores', (['GDT_percent'], {'ranking_order': '"""GDT_TS"""', 'verbose': '(False)'}), "(GDT_percent, ranking_order='GDT_TS', verbose=False)\n", (8791, 8843), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((8926, 9063), 'pyrexMD.analysis.gdt.plot_LA_rna', 'gdt.plot_LA_rna', (['mobile', 'ref', 'SCORES[0]', 'SCORES[1]', 'SCORES[2]'], {'sel1': '"""protein and name CA"""', 'sel2': '"""protein and name CA"""', 'cmap': '"""GDT_TS"""'}), "(mobile, ref, SCORES[0], SCORES[1], SCORES[2], sel1=\n 'protein and name CA', sel2='protein and name CA', cmap='GDT_TS')\n", (8941, 9063), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((465, 482), 'pathlib.Path', 'pathlib.Path', (['"""."""'], {}), "('.')\n", (477, 482), False, 'import pathlib\n'), ((948, 978), 'numpy.load', 'np.load', (['f"""{pre}/DIST_ARR.npy"""'], {}), "(f'{pre}/DIST_ARR.npy')\n", (955, 978), True, 'import numpy as np\n'), ((1073, 1095), 'numpy.testing.assert_allclose', 'assert_allclose', (['p', 'v1'], {}), '(p, v1)\n', (1088, 1095), False, 'from numpy.testing import assert_allclose\n'), ((1115, 1139), 'numpy.testing.assert_allclose', 'assert_allclose', (['ndx', 'v2'], {}), '(ndx, v2)\n', (1130, 1139), False, 'from numpy.testing import assert_allclose\n'), ((1184, 1214), 'numpy.load', 'np.load', (['f"""{pre}/DIST_ARR.npy"""'], {}), "(f'{pre}/DIST_ARR.npy')\n", (1191, 1214), True, 'import numpy as np\n'), ((1309, 1331), 'numpy.testing.assert_allclose', 'assert_allclose', (['p', 'v1'], {}), '(p, v1)\n', (1324, 1331), False, 'from numpy.testing import assert_allclose\n'), ((1351, 1375), 'numpy.testing.assert_allclose', 'assert_allclose', (['ndx', 'v2'], {}), '(ndx, v2)\n', (1366, 1375), False, 'from numpy.testing import assert_allclose\n'), ((1420, 1450), 'numpy.load', 'np.load', (['f"""{pre}/DIST_ARR.npy"""'], {}), "(f'{pre}/DIST_ARR.npy')\n", (1427, 1450), True, 'import numpy as np\n'), ((1545, 1567), 'numpy.testing.assert_allclose', 'assert_allclose', (['p', 'v1'], {}), '(p, v1)\n', (1560, 1567), False, 'from numpy.testing import assert_allclose\n'), ((1587, 1611), 'numpy.testing.assert_allclose', 'assert_allclose', (['ndx', 'v2'], {}), '(ndx, v2)\n', (1602, 1611), False, 'from numpy.testing import assert_allclose\n'), ((3949, 4000), 'numpy.load', 'np.load', (['f"""{pre}/GDT_resids.npy"""'], {'allow_pickle': '(True)'}), "(f'{pre}/GDT_resids.npy', allow_pickle=True)\n", (3956, 4000), True, 'import numpy as np\n'), ((4815, 4866), 'numpy.load', 'np.load', (['f"""{pre}/GDT_resids.npy"""'], {'allow_pickle': '(True)'}), "(f'{pre}/GDT_resids.npy', allow_pickle=True)\n", (4822, 4866), True, 'import numpy as np\n'), ((6444, 6469), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6457, 6469), False, 'import pytest\n'), ((6479, 6541), 'pyrexMD.analysis.gdt.rank_scores', 'gdt.rank_scores', (['GDT_TS', 'GDT_HA'], {'ranking_order': '"""invalid_value"""'}), "(GDT_TS, GDT_HA, ranking_order='invalid_value')\n", (6494, 6541), True, 'import pyrexMD.analysis.gdt as gdt\n'), ((633, 659), 'os.path.realpath', 'os.path.realpath', (['pathname'], {}), '(pathname)\n', (649, 659), False, 'import os\n'), ((1887, 1923), 'numpy.load', 'np.load', (['f"""{pre}/PAIR_DISTANCES.npy"""'], {}), "(f'{pre}/PAIR_DISTANCES.npy')\n", (1894, 1923), True, 'import numpy as np\n'), ((1966, 1992), 'numpy.load', 'np.load', (['f"""{pre}/RMSD.npy"""'], {}), "(f'{pre}/RMSD.npy')\n", (1973, 1992), True, 'import numpy as np\n'), ((2044, 2079), 'numpy.load', 'np.load', (['f"""{pre}/resids_mobile.npy"""'], {}), "(f'{pre}/resids_mobile.npy')\n", (2051, 2079), True, 'import numpy as np\n'), ((2128, 2160), 'numpy.load', 'np.load', (['f"""{pre}/resids_ref.npy"""'], {}), "(f'{pre}/resids_ref.npy')\n", (2135, 2160), True, 'import numpy as np\n'), ((3534, 3567), 'numpy.load', 'np.load', (['f"""{pre}/GDT_percent.npy"""'], {}), "(f'{pre}/GDT_percent.npy')\n", (3541, 3567), True, 'import numpy as np\n'), ((3616, 3648), 'numpy.load', 'np.load', (['f"""{pre}/GDT_cutoff.npy"""'], {}), "(f'{pre}/GDT_cutoff.npy')\n", (3623, 3648), True, 'import numpy as np\n'), ((3691, 3721), 'numpy.load', 'np.load', (['f"""{pre}/GDT_RMSD.npy"""'], {}), "(f'{pre}/GDT_RMSD.npy')\n", (3698, 3721), True, 'import numpy as np\n'), ((3765, 3796), 'numpy.load', 'np.load', (['f"""{pre}/GDT_FRAME.npy"""'], {}), "(f'{pre}/GDT_FRAME.npy')\n", (3772, 3796), True, 'import numpy as np\n'), ((4400, 4433), 'numpy.load', 'np.load', (['f"""{pre}/GDT_percent.npy"""'], {}), "(f'{pre}/GDT_percent.npy')\n", (4407, 4433), True, 'import numpy as np\n'), ((4482, 4514), 'numpy.load', 'np.load', (['f"""{pre}/GDT_cutoff.npy"""'], {}), "(f'{pre}/GDT_cutoff.npy')\n", (4489, 4514), True, 'import numpy as np\n'), ((4557, 4587), 'numpy.load', 'np.load', (['f"""{pre}/GDT_RMSD.npy"""'], {}), "(f'{pre}/GDT_RMSD.npy')\n", (4564, 4587), True, 'import numpy as np\n'), ((4631, 4662), 'numpy.load', 'np.load', (['f"""{pre}/GDT_FRAME.npy"""'], {}), "(f'{pre}/GDT_FRAME.npy')\n", (4638, 4662), True, 'import numpy as np\n'), ((5752, 5780), 'numpy.load', 'np.load', (['f"""{pre}/GDT_TS.npy"""'], {}), "(f'{pre}/GDT_TS.npy')\n", (5759, 5780), True, 'import numpy as np\n'), ((5954, 5982), 'numpy.load', 'np.load', (['f"""{pre}/GDT_HA.npy"""'], {}), "(f'{pre}/GDT_HA.npy')\n", (5961, 5982), True, 'import numpy as np\n'), ((7034, 7072), 'numpy.load', 'np.load', (['f"""{pre}/GDT_rank_percent.npy"""'], {}), "(f'{pre}/GDT_rank_percent.npy')\n", (7041, 7072), True, 'import numpy as np\n'), ((6190, 6223), 'numpy.load', 'np.load', (['f"""{pre}/rank_scores.npy"""'], {}), "(f'{pre}/rank_scores.npy')\n", (6197, 6223), True, 'import numpy as np\n'), ((6258, 6295), 'numpy.load', 'np.load', (['f"""{pre}/GDT_rank_scores.npy"""'], {}), "(f'{pre}/GDT_rank_scores.npy')\n", (6265, 6295), True, 'import numpy as np\n'), ((6721, 6758), 'numpy.load', 'np.load', (['f"""{pre}/GDT_rank_scores.npy"""'], {}), "(f'{pre}/GDT_rank_scores.npy')\n", (6728, 6758), True, 'import numpy as np\n'), ((6797, 6830), 'numpy.load', 'np.load', (['f"""{pre}/rank_scores.npy"""'], {}), "(f'{pre}/rank_scores.npy')\n", (6804, 6830), True, 'import numpy as np\n'), ((7575, 7638), 'numpy.load', 'np.load', (['f"""{pre}/GDT_continous_segments.npy"""'], {'allow_pickle': '(True)'}), "(f'{pre}/GDT_continous_segments.npy', allow_pickle=True)\n", (7582, 7638), True, 'import numpy as np\n')]
import logging import time from typing import Dict, List, Union import numpy as np from pymatgen.electronic_structure.core import Spin from amset.constants import int_to_spin, numeric_types from amset.electronic_structure.symmetry import ( rotation_matrix_to_su2, similarity_transformation, ) from amset.log import log_time_taken from amset.util import get_progress_bar __author__ = "<NAME>" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" logger = logging.getLogger(__name__) def sample_random_kpoints( nspins: int, ikpoints: List[int], nband: Dict[Spin, Union[List[int], int]], n_samples: int, ): spin_idxs = [] band_idxs = [] kpoint_idxs = [] for spin_idx in range(nspins): spin = int_to_spin[spin_idx] spin_iband = nband[spin] if isinstance(spin_iband, numeric_types): spin_iband = np.arange(spin_iband, dtype=int) s_idxs = [spin_idx] * n_samples b_idxs = np.random.randint(min(spin_iband), max(spin_iband) + 1, n_samples) k_idxs = np.random.choice(ikpoints, n_samples) spin_idxs.append(s_idxs) band_idxs.append(b_idxs) kpoint_idxs.append(k_idxs) spin_idxs = np.concatenate(spin_idxs) band_idxs = np.concatenate(band_idxs) kpoint_idxs = np.concatenate(kpoint_idxs) return np.stack([spin_idxs, band_idxs, kpoint_idxs], axis=1) def desymmetrize_coefficients( coeffs, gpoints, kpoints, structure, rotations, translations, is_tr, op_mapping, kp_mapping, pbar=True, ): logger.info("Desymmetrizing wavefunction coefficients") t0 = time.perf_counter() ncl = is_ncl(coeffs) rots = rotations[op_mapping] taus = translations[op_mapping] trs = is_tr[op_mapping] su2s = None if ncl: # get cartesian rotation matrix r_cart = [ similarity_transformation(structure.lattice.matrix.T, r.T) for r in rotations ] # calculate SU(2) su2_no_dagger = np.array([rotation_matrix_to_su2(r) for r in r_cart]) # calculate SU(2)^{dagger} su2 = np.conjugate(su2_no_dagger).transpose((0, 2, 1)) su2s = su2[op_mapping] g_mesh = (np.abs(gpoints).max(axis=0) + 3) * 2 g1, g2, g3 = (gpoints + g_mesh / 2).astype(int).T # indices of g-points to keep all_rot_coeffs = {} for spin, spin_coeffs in coeffs.items(): coeff_shape = (len(spin_coeffs), len(rots)) + tuple(g_mesh) if ncl: coeff_shape += (2,) rot_coeffs = np.zeros(coeff_shape, dtype=complex) state_idxs = list(range(len(rots))) if pbar: state_idxs = get_progress_bar(state_idxs, desc="progress") for k_idx in state_idxs: map_idx = kp_mapping[k_idx] rot = rots[k_idx] tau = taus[k_idx] tr = trs[k_idx] kpoint = kpoints[map_idx] rot_kpoint = np.dot(rot, kpoint) kdiff = np.around(rot_kpoint) rot_kpoint -= kdiff edges = np.around(rot_kpoint, 5) == -0.5 rot_kpoint += edges kdiff -= edges rot_gpoints = np.dot(rot, gpoints.T).T rot_gpoints = np.around(rot_gpoints).astype(int) rot_gpoints += kdiff.astype(int) if tr: tau = -tau factor = np.exp(-1j * 2 * np.pi * np.dot(rot_gpoints + rot_kpoint, tau)) rg1, rg2, rg3 = (rot_gpoints + g_mesh / 2).astype(int).T if ncl: # perform rotation in spin space su2 = su2s[k_idx] rc = np.zeros_like(spin_coeffs[:, map_idx]) rc[:, :, 0] = ( su2[0, 0] * spin_coeffs[:, map_idx, :, 0] + su2[0, 1] * spin_coeffs[:, map_idx, :, 1] ) rc[:, :, 1] = ( su2[1, 0] * spin_coeffs[:, map_idx, :, 0] + su2[1, 1] * spin_coeffs[:, map_idx, :, 1] ) rot_coeffs[:, k_idx, rg1, rg2, rg3] = factor[None, :, None] * rc else: rot_coeffs[:, k_idx, rg1, rg2, rg3] = spin_coeffs[:, map_idx] * factor if tr and not ncl: rot_coeffs[:, k_idx] = np.conjugate(rot_coeffs[:, k_idx]) all_rot_coeffs[spin] = rot_coeffs[:, :, g1, g2, g3] log_time_taken(t0) return all_rot_coeffs def get_gpoints(reciprocal_lattice, nbmax, encut, kpoint=(0, 0, 0)): all_g = np.array(list(np.ndindex(tuple(2 * nbmax[::-1] + 1)))) all_g = all_g[:, [2, 1, 0]] # swap columns all_g[all_g[:, 2] > nbmax[2], 2] -= 2 * nbmax[2] + 1 all_g[all_g[:, 1] > nbmax[1], 1] -= 2 * nbmax[1] + 1 all_g[all_g[:, 0] > nbmax[0], 0] -= 2 * nbmax[0] + 1 cart_g = np.dot(all_g + kpoint, reciprocal_lattice) norm_g = np.linalg.norm(cart_g, axis=1) ener_g = norm_g**2 / 0.262465831 return all_g[ener_g <= encut] def get_min_gpoints(nbmax): min_gpoint = -nbmax num_gpoint = nbmax * 2 + 1 return min_gpoint, num_gpoint def get_gpoint_indices(gpoints, min_gpoint, num_gpoint): shifted_g = gpoints - min_gpoint nyz = num_gpoint[1] * num_gpoint[2] nz = num_gpoint[2] indices = shifted_g[:, 0] * nyz + shifted_g[:, 1] * nz + shifted_g[:, 2] return indices.astype(int) def is_ncl(coefficients): return len(list(coefficients.values())[0].shape) == 4 def get_overlap(origin, final): if len(origin.shape) == 2: # ncl return ( np.abs( np.dot(np.conj(origin[:, 0]), final[:, :, 0].T) + np.dot(np.conj(origin[:, 1]), final[:, :, 1].T) ) ** 2 ) else: return np.abs(np.dot(np.conj(origin), final.T)) ** 2
[ "logging.getLogger", "numpy.abs", "amset.electronic_structure.symmetry.rotation_matrix_to_su2", "numpy.random.choice", "numpy.conj", "numpy.conjugate", "time.perf_counter", "amset.electronic_structure.symmetry.similarity_transformation", "amset.util.get_progress_bar", "numpy.stack", "numpy.dot",...
[((461, 488), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (478, 488), False, 'import logging\n'), ((1202, 1227), 'numpy.concatenate', 'np.concatenate', (['spin_idxs'], {}), '(spin_idxs)\n', (1216, 1227), True, 'import numpy as np\n'), ((1244, 1269), 'numpy.concatenate', 'np.concatenate', (['band_idxs'], {}), '(band_idxs)\n', (1258, 1269), True, 'import numpy as np\n'), ((1288, 1315), 'numpy.concatenate', 'np.concatenate', (['kpoint_idxs'], {}), '(kpoint_idxs)\n', (1302, 1315), True, 'import numpy as np\n'), ((1327, 1380), 'numpy.stack', 'np.stack', (['[spin_idxs, band_idxs, kpoint_idxs]'], {'axis': '(1)'}), '([spin_idxs, band_idxs, kpoint_idxs], axis=1)\n', (1335, 1380), True, 'import numpy as np\n'), ((1630, 1649), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (1647, 1649), False, 'import time\n'), ((4390, 4408), 'amset.log.log_time_taken', 'log_time_taken', (['t0'], {}), '(t0)\n', (4404, 4408), False, 'from amset.log import log_time_taken\n'), ((4807, 4849), 'numpy.dot', 'np.dot', (['(all_g + kpoint)', 'reciprocal_lattice'], {}), '(all_g + kpoint, reciprocal_lattice)\n', (4813, 4849), True, 'import numpy as np\n'), ((4863, 4893), 'numpy.linalg.norm', 'np.linalg.norm', (['cart_g'], {'axis': '(1)'}), '(cart_g, axis=1)\n', (4877, 4893), True, 'import numpy as np\n'), ((1045, 1082), 'numpy.random.choice', 'np.random.choice', (['ikpoints', 'n_samples'], {}), '(ikpoints, n_samples)\n', (1061, 1082), True, 'import numpy as np\n'), ((2552, 2588), 'numpy.zeros', 'np.zeros', (['coeff_shape'], {'dtype': 'complex'}), '(coeff_shape, dtype=complex)\n', (2560, 2588), True, 'import numpy as np\n'), ((870, 902), 'numpy.arange', 'np.arange', (['spin_iband'], {'dtype': 'int'}), '(spin_iband, dtype=int)\n', (879, 902), True, 'import numpy as np\n'), ((1873, 1931), 'amset.electronic_structure.symmetry.similarity_transformation', 'similarity_transformation', (['structure.lattice.matrix.T', 'r.T'], {}), '(structure.lattice.matrix.T, r.T)\n', (1898, 1931), False, 'from amset.electronic_structure.symmetry import rotation_matrix_to_su2, similarity_transformation\n'), ((2676, 2721), 'amset.util.get_progress_bar', 'get_progress_bar', (['state_idxs'], {'desc': '"""progress"""'}), "(state_idxs, desc='progress')\n", (2692, 2721), False, 'from amset.util import get_progress_bar\n'), ((2949, 2968), 'numpy.dot', 'np.dot', (['rot', 'kpoint'], {}), '(rot, kpoint)\n', (2955, 2968), True, 'import numpy as np\n'), ((2989, 3010), 'numpy.around', 'np.around', (['rot_kpoint'], {}), '(rot_kpoint)\n', (2998, 3010), True, 'import numpy as np\n'), ((2034, 2059), 'amset.electronic_structure.symmetry.rotation_matrix_to_su2', 'rotation_matrix_to_su2', (['r'], {}), '(r)\n', (2056, 2059), False, 'from amset.electronic_structure.symmetry import rotation_matrix_to_su2, similarity_transformation\n'), ((2128, 2155), 'numpy.conjugate', 'np.conjugate', (['su2_no_dagger'], {}), '(su2_no_dagger)\n', (2140, 2155), True, 'import numpy as np\n'), ((3064, 3088), 'numpy.around', 'np.around', (['rot_kpoint', '(5)'], {}), '(rot_kpoint, 5)\n', (3073, 3088), True, 'import numpy as np\n'), ((3183, 3205), 'numpy.dot', 'np.dot', (['rot', 'gpoints.T'], {}), '(rot, gpoints.T)\n', (3189, 3205), True, 'import numpy as np\n'), ((3641, 3679), 'numpy.zeros_like', 'np.zeros_like', (['spin_coeffs[:, map_idx]'], {}), '(spin_coeffs[:, map_idx])\n', (3654, 3679), True, 'import numpy as np\n'), ((4289, 4323), 'numpy.conjugate', 'np.conjugate', (['rot_coeffs[:, k_idx]'], {}), '(rot_coeffs[:, k_idx])\n', (4301, 4323), True, 'import numpy as np\n'), ((2223, 2238), 'numpy.abs', 'np.abs', (['gpoints'], {}), '(gpoints)\n', (2229, 2238), True, 'import numpy as np\n'), ((3234, 3256), 'numpy.around', 'np.around', (['rot_gpoints'], {}), '(rot_gpoints)\n', (3243, 3256), True, 'import numpy as np\n'), ((3408, 3445), 'numpy.dot', 'np.dot', (['(rot_gpoints + rot_kpoint)', 'tau'], {}), '(rot_gpoints + rot_kpoint, tau)\n', (3414, 3445), True, 'import numpy as np\n'), ((5764, 5779), 'numpy.conj', 'np.conj', (['origin'], {}), '(origin)\n', (5771, 5779), True, 'import numpy as np\n'), ((5577, 5598), 'numpy.conj', 'np.conj', (['origin[:, 0]'], {}), '(origin[:, 0])\n', (5584, 5598), True, 'import numpy as np\n'), ((5643, 5664), 'numpy.conj', 'np.conj', (['origin[:, 1]'], {}), '(origin[:, 1])\n', (5650, 5664), True, 'import numpy as np\n')]
#!/usr/bin/env python #%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%# #%!%!% ----------------------------- FPTE_Result_Stress_2nd ----------------------------- %!%!%# #%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%# # # AUTHORs: # <NAME> # <EMAIL> # # <NAME> # <EMAIL> # # DATE: # July 01 00:00:00 2018 # # SYNTAX: # python FPTE_Result_Stress_2nd.py # FPTE_Result_Stress_2nd # # EXPLANATION: # #__________________________________________________________________________________________________ from sys import stdin # from numpy import * import numpy as np import subprocess import os.path import shutil import math import time import sys import os def fpte_results(): #%!%!%--- Dictionaries ---%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!% head = {\ 'CI':'\ for, space group-number between 207 and 230, Cubic I structure. \n\n\ C11 C12 C12 0 0 0 \n\ C12 C11 C12 0 0 0 \n\ C12 C12 C11 0 0 0 \n\ 0 0 0 C44 0 0 \n\ 0 0 0 0 C44 0 \n\ 0 0 0 0 0 C44 \n',\ 'CII':'\ for, space group-number between 195 and 206, Cubic II structure. \n\n\ C11 C12 C12 0 0 0 \n\ C12 C11 C12 0 0 0 \n\ C12 C12 C11 0 0 0 \n\ 0 0 0 C44 0 0 \n\ 0 0 0 0 C44 0 \n\ 0 0 0 0 0 C44 \n',\ 'HI':'\ for, space group-number between 177 and 194, Hexagonal I structure. \n\n\ C11 C12 C13 0 0 0 \n\ C12 C11 C13 0 0 0 \n\ C13 C13 C33 0 0 0 \n\ 0 0 0 C44 0 0 \n\ 0 0 0 0 C44 0 \n\ 0 0 0 0 0 (C11-C12)/2 \n',\ 'HII':'\ for, space group-number between 168 and 176, Hexagonal II structure. \n\n\ C11 C12 C13 0 0 0 \n\ C12 C11 C13 0 0 0 \n\ C13 C13 C33 0 0 0 \n\ 0 0 0 C44 0 0 \n\ 0 0 0 0 C44 0 \n\ 0 0 0 0 0 (C11-C12)/2 \n',\ 'RI':'\ for, space group-number between 149 and 167, Rhombohedral I structure. \n\n\ C11 C12 C13 C14 0 0 \n\ C12 C11 C13 -C14 0 0 \n\ C13 C13 C33 0 0 0 \n\ C14 -C14 0 C44 0 0 \n\ 0 0 0 0 C44 C14 \n\ 0 0 0 0 C14 (C11-C12)/2 \n',\ 'RII':'\ for, space group-number between 143 and 148, Rhombohedral II structure.\n\n\ C11 C12 C13 C14 C15 0 \n\ C12 C11 C13 -C14 -C15 0 \n\ C13 C13 C33 0 0 0 \n\ C14 -C14 0 C44 0 -C15 \n\ C15 -C15 0 0 C44 C14 \n\ 0 0 0 -C15 C14 (C11-C12)/2 \n',\ 'TI':'\ for, space group-number between 89 and 142, Tetragonal I structure. \n\n\ C11 C12 C13 0 0 0 \n\ C12 C11 C13 0 0 0 \n\ C13 C13 C33 0 0 0 \n\ 0 0 0 C44 0 0 \n\ 0 0 0 0 C44 0 \n\ 0 0 0 0 0 C66 \n',\ 'TII':'\ for, space group-number between 75 and 88, Tetragonal II structure. \n\n\ C11 C12 C13 0 0 C16 \n\ C12 C11 C13 0 0 -C16 \n\ C13 C13 C33 0 0 0 \n\ 0 0 0 C44 0 0 \n\ 0 0 0 0 C44 0 \n\ C16 -C16 0 0 0 C66 \n',\ 'O':'\ for, space group-number between 16 and 74, Orthorhombic structure. \n\n\ C11 C12 C13 0 0 0 \n\ C12 C22 C23 0 0 0 \n\ C13 C23 C33 0 0 0 \n\ 0 0 0 C44 0 0 \n\ 0 0 0 0 C55 0 \n\ 0 0 0 0 0 C66 \n',\ 'M':'\ for, space group-number between 3 and 15, Monoclinic structure. \n\n\ C11 C12 C13 0 0 C16 \n\ C12 C22 C23 0 0 C26 \n\ C13 C23 C33 0 0 C36 \n\ 0 0 0 C44 C45 0 \n\ 0 0 0 C45 C55 0 \n\ C16 C26 C36 0 0 C66 \n',\ 'N':'\ for, space group-number between 1 and 2, Triclinic structure. \n\n\ C11 C12 C13 C14 C15 C16 \n\ C12 C22 C23 C24 C25 C26 \n\ C13 C23 C33 C34 C35 C36 \n\ C14 C24 C34 C44 C45 C46 \n\ C15 C25 C35 C45 C55 C56 \n\ C16 C26 C36 C46 C56 C66 \n'} #-------------------------------------------------------------------------------------------------- #%!%!%--- Reading the "INFO_FPTE" file ---%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%! INFO=open('INFO_FPTE', 'r') l1 = INFO.readline() ordr= int(l1.split()[-1]) if (ordr != 2 and ordr != 3): sys.exit('\n.... Oops ERROR: The order of the elastic constant is NOT clear !?!?!?'\ '\n Something is WRONG in the "INFO_FPTE" file.\n') l2 = INFO.readline() mthd= l2.split()[-1] if (mthd != 'Stress' and mthd != 'Energy'): sys.exit('\n.... Oops ERROR: The method of the calculation is NOT clear !?!?!?'\ '\n Something is WRONG in the "INFO_FPTE" file.\n') l3 = INFO.readline() cod = l3.split()[-1] if (cod != 'WIEN2k' and cod != 'exciting' and cod != 'ESPRESSO' and cod != 'VASP'): sys.exit('\n.... Oops ERROR: The DFT code is NOT clear !?!?!?'\ '\n Something is WRONG in the "INFO_FPTE" file.\n') #l5 = INFO.readline() #V0 = float(l5.split()[-2]) l6 = INFO.readline() mdr = float(l6.split()[-1]) l7 = INFO.readline() NoP = int(l7.split()[-1]) l4 = INFO.readline() SGN = int(l4.split()[-1]) INFO.close() #-------------------------------------------------------------------------------------------------- #%%%--- Calculating the Space-Group Number and classifying it ---%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%! # NoD = Number of Deformation if (1 <= SGN and SGN <= 2): # Triclinic LC = 'N' NoD= 6 elif(3 <= SGN and SGN <= 15): # Monoclinic LC = 'M' NoD= 5 elif(16 <= SGN and SGN <= 74): # Orthorhombic LC = 'O' NoD= 3 elif(75 <= SGN and SGN <= 88): # Tetragonal II LC = 'TII' NoD= 2 elif(89 <= SGN and SGN <= 142): # Tetragonal I LC = 'TI' NoD= 2 elif(143 <= SGN and SGN <= 148): # Rhombohedral II LC = 'RII' NoD= 2 elif(149 <= SGN and SGN <= 167): # Rhombohedral I LC = 'RI' NoD= 2 elif(168 <= SGN and SGN <= 176): # Hexagonal II LC = 'HII' NoD= 2 elif(177 <= SGN and SGN <= 194): # Hexagonal I LC = 'HI' NoD= 2 elif(195 <= SGN and SGN <= 206): # Cubic II LC = 'CII' NoD= 1 elif(207 <= SGN and SGN <= 230): # Cubic I LC = 'CI' NoD= 1 else: sys.exit('\n.... Oops ERROR: WRONG Space-Group Number !?!?!? \n') #-------------------------------------------------------------------------------------------------- lineseparator=' ' for i in range(0,79): lineseparator=lineseparator+'%' #%%%--- Making the Matrix ---%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!% if (LC == 'CI' or \ LC == 'CII'): Matrix = np.mat([[1.0, 5.0, 0.0], [2.0, 4.0, 0.0], [3.0, 3.0, 0.0], [0.0, 0.0, 4.0], [0.0, 0.0, 5.0], [0.0, 0.0, 6.0]]) if (LC == 'HI' or \ LC == 'HII'): Matrix = np.mat([[ 1, 2, 3, 0, 0], [ 2, 1, 3, 0, 0], [ 0, 0, 3, 3, 0], [ 0, 0, 0, 0, 4], [ 0, 0, 0, 0, 5], [ 3,-3, 0, 0, 0], [ 3,-5,-1, 0, 0], [-5, 3,-1, 0, 0], [ 0, 0,-2,-1, 0], [ 0, 0, 0, 0, 6], [ 0, 0, 0, 0, 2], [-2, 2, 0, 0, 0]]) if (LC == 'RI'): Matrix = np.mat([[ 1, 2, 3, 4, 0, 0], [ 2, 1, 3,-4, 0, 0], [ 0, 0, 3, 0, 3, 0], [ 0, 0, 0,-1, 0, 4], [ 0, 0, 0, 6, 0, 5], [ 3,-3, 0, 5, 0, 0], [ 3,-5,-1, 6, 0, 0], [-5, 3,-1,-6, 0, 0], [ 0, 0,-2, 0,-1, 0], [ 0, 0, 0, 8, 0, 6], [ 0, 0, 0,-4, 0, 2], [-2, 2, 0, 2, 0, 0]]) if (LC == 'RII'): Matrix = np.mat([[ 1, 2, 3, 4, 5, 0, 0], [ 2, 1, 3,-4,-5, 0, 0], [ 0, 0, 3, 0, 0, 3, 0], [ 0, 0, 0,-1,-6, 0, 4], [ 0, 0, 0, 6,-1, 0, 5], [ 3,-3, 0, 5,-4, 0, 0], [ 3,-5,-1, 6, 2, 0, 0], [-5, 3,-1,-6,-2, 0, 0], [ 0, 0,-2, 0, 0,-1, 0], [ 0, 0, 0, 8, 4, 0, 6], [ 0, 0, 0,-4, 8, 0, 2], [-2, 2, 0, 2,-6, 0, 0]]) if (LC == 'TI'): Matrix = np.mat([[ 1, 2, 3, 0, 0, 0], [ 2, 1, 3, 0, 0, 0], [ 0, 0, 3, 3, 0, 0], [ 0, 0, 0, 0, 4, 0], [ 0, 0, 0, 0, 5, 0], [ 0, 0, 0, 0, 0, 6], [ 3,-5,-1, 0, 0, 0], [-5, 3,-1, 0, 0, 0], [ 0, 0,-2,-1, 0, 0], [ 0, 0, 0, 0, 6, 0], [ 0, 0, 0, 0, 2, 0], [ 0, 0, 0, 0, 0,-4]]) if (LC == 'TII'): Matrix = np.mat([[ 1, 2, 3, 6, 0, 0, 0], [ 2, 1, 3,-6, 0, 0, 0], [ 0, 0, 3, 0, 3, 0, 0], [ 0, 0, 0, 0, 0, 4, 0], [ 0, 0, 0, 0, 0, 5, 0], [ 0, 0, 0,-1, 0, 0, 6], [ 3,-5,-1,-4, 0, 0, 0], [-5, 3,-1, 4, 0, 0, 0], [ 0, 0,-2, 0,-1, 0, 0], [ 0, 0, 0, 0, 0, 6, 0], [ 0, 0, 0, 0, 0, 2, 0], [ 0, 0, 0, 8, 0, 0,-4]]) if (LC == 'O'): Matrix = np.mat([[1, 2, 3, 0, 0, 0, 0, 0, 0], [0, 1, 0, 2, 3, 0, 0, 0, 0], [0, 0, 1, 0, 2, 3, 0, 0, 0], [0, 0, 0, 0, 0, 0, 4, 0, 0], [0, 0, 0, 0, 0, 0, 0, 5, 0], [0, 0, 0, 0, 0, 0, 0, 0, 6], [3,-5,-1, 0, 0, 0, 0, 0, 0], [0, 3, 0,-5,-1, 0, 0, 0, 0], [0, 0, 3, 0,-5,-1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 6, 0, 0], [0, 0, 0, 0, 0, 0, 0, 2, 0], [0, 0, 0, 0, 0, 0, 0, 0,-4], [5, 4, 6, 0, 0, 0, 0, 0, 0], [0, 5, 0, 4, 6, 0, 0, 0, 0], [0, 0, 5, 0, 4, 6, 0, 0, 0], [0, 0, 0, 0, 0, 0,-2, 0, 0], [0, 0, 0, 0, 0, 0, 0,-1, 0], [0, 0, 0, 0, 0, 0, 0, 0,-3]]) if (LC == 'M'): Matrix = np.mat([[ 1, 2, 3, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 1, 0, 0, 2, 3, 6, 0, 0, 0, 0, 0, 0], [ 0, 0, 1, 0, 0, 2, 0, 3, 6, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 0], [ 0, 0, 0, 1, 0, 0, 2, 0, 3, 0, 0, 0, 6], [-2, 1, 4,-5, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0,-2, 0, 0, 1, 4,-5, 0, 0, 0, 0, 0, 0], [ 0, 0,-2, 0, 0, 1, 0, 4,-5, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0,-3, 6, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-3, 6, 0], [ 0, 0, 0,-2, 0, 0, 1, 0, 4, 0, 0,-5, 0], [ 3,-5,-1,-4, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 3, 0, 0,-5,-1,-4, 0, 0, 0, 0, 0, 0], [ 0, 0, 3, 0, 0,-5, 0,-1,-4, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 0], [ 0, 0, 0, 3, 0, 0,-5, 0,-1, 0, 0,-4, 0], [-4,-6, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0,-4, 0, 0,-6, 5, 2, 0, 0, 0, 0, 0, 0], [ 0, 0,-4, 0, 0,-6, 0, 5, 2, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,-3, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,-3, 0], [ 0, 0, 0,-4, 0, 0,-6, 0, 5, 0, 0, 2, 0], [ 5, 4, 6,-3, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 5, 0, 0, 4, 6,-3, 0, 0, 0, 0, 0, 0], [ 0, 0, 5, 0, 0, 4, 0, 6,-3, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0,-2,-1, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-2,-1, 0], [ 0, 0, 0, 5, 0, 0, 4, 0, 6, 0, 0,-3, 0]]) if (LC == 'N'): Matrix = np.mat([[ 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 1, 0, 0, 0, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 4, 5, 6, 0, 0, 0], [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 4, 0, 5, 6, 0], [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 4, 0, 5, 6], [-2, 1, 4,-3, 6,-5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0,-2, 0, 0, 0, 0, 1, 4,-3, 6,-5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0,-2, 0, 0, 0, 0, 1, 0, 0, 0, 4,-3, 6,-5, 0, 0, 0, 0, 0, 0], [ 0, 0, 0,-2, 0, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0,-3, 6,-5, 0, 0, 0], [ 0, 0, 0, 0,-2, 0, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0,-3, 0, 6,-5, 0], [ 0, 0, 0, 0, 0,-2, 0, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0,-3, 0, 6,-5], [ 3,-5,-1, 6, 2,-4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 3, 0, 0, 0, 0,-5,-1, 6, 2,-4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 3, 0, 0, 0, 0,-5, 0, 0, 0,-1, 6, 2,-4, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 3, 0, 0, 0, 0,-5, 0, 0, 0,-1, 0, 0, 6, 2,-4, 0, 0, 0], [ 0, 0, 0, 0, 3, 0, 0, 0, 0,-5, 0, 0, 0,-1, 0, 0, 6, 0, 2,-4, 0], [ 0, 0, 0, 0, 0, 3, 0, 0, 0, 0,-5, 0, 0, 0,-1, 0, 0, 6, 0, 2,-4], [-4,-6, 5, 1,-3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0,-4, 0, 0, 0, 0,-6, 5, 1,-3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0,-4, 0, 0, 0, 0,-6, 0, 0, 0, 5, 1,-3, 2, 0, 0, 0, 0, 0, 0], [ 0, 0, 0,-4, 0, 0, 0, 0,-6, 0, 0, 0, 5, 0, 0, 1,-3, 2, 0, 0, 0], [ 0, 0, 0, 0,-4, 0, 0, 0, 0,-6, 0, 0, 0, 5, 0, 0, 1, 0,-3, 2, 0], [ 0, 0, 0, 0, 0,-4, 0, 0, 0, 0,-6, 0, 0, 0, 5, 0, 0, 1, 0,-3, 2], [ 5, 4, 6,-2,-1,-3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 5, 0, 0, 0, 0, 4, 6,-2,-1,-3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 6,-2,-1,-3, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 6, 0, 0,-2,-1,-3, 0, 0, 0], [ 0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 6, 0, 0,-2, 0,-1,-3, 0], [ 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 6, 0, 0,-2, 0,-1,-3], [-6, 3,-2, 5,-4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0,-6, 0, 0, 0, 0, 3,-2, 5,-4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0,-6, 0, 0, 0, 0, 3, 0, 0, 0,-2, 5,-4, 1, 0, 0, 0, 0, 0, 0], [ 0, 0, 0,-6, 0, 0, 0, 0, 3, 0, 0, 0,-2, 0, 0, 5,-4, 1, 0, 0, 0], [ 0, 0, 0, 0,-6, 0, 0, 0, 0, 3, 0, 0, 0,-2, 0, 0, 5, 0,-4, 1, 0], [ 0, 0, 0, 0, 0,-6, 0, 0, 0, 0, 3, 0, 0, 0,-2, 0, 0, 5, 0,-4, 1]]) #%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%# #%!%!% ------------ Calculating the second derivative and Cross-Validation Error ----------- %!%!%# #%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%# OBJ = open('FPTE_2nd.in', 'r') # RoD = Range of Deformation RoD = OBJ.read().strip().split() if (len(RoD) != 13*NoD): sys.exit('\n.... Oops ERROR: Something is WRONG in the "FPTE_2nd.in" file !?!?!?\n') os.chdir('Stress-vs-Strain') sigma = [] for i in range(1, NoD+1): if (i<10): Dstn ='Deform0'+str(i) else: Dstn ='Deform' +str(i) for j in range(0, 13*NoD-1, 13): if (RoD[j] == Dstn): mdr1 = abs(float(RoD[j+1])) mdr2 = abs(float(RoD[j+2])) mdr3 = abs(float(RoD[j+3])) mdr4 = abs(float(RoD[j+4])) mdr5 = abs(float(RoD[j+5])) mdr6 = abs(float(RoD[j+6])) ordr1= abs(int(float(RoD[j+7]))) ordr2= abs(int(float(RoD[j+8]))) ordr3= abs(int(float(RoD[j+9]))) ordr4= abs(int(float(RoD[j+10]))) ordr5= abs(int(float(RoD[j+11]))) ordr6= abs(int(float(RoD[j+12]))) if (os.path.exists(Dstn+'_Lagrangian-stress.dat') == False): sys.exit('\n.... Oops ERROR: Where is the "'+Dstn+'_Lagrangian-stress.dat" !?!?!?\n') eta_strs = open(Dstn+'_Lagrangian-stress.dat', 'r') eta_strs.readline() eta_strs.readline() str1= [] str2= [] str3= [] str4= [] str5= [] str6= [] ls1 = [] ls2 = [] ls3 = [] ls4 = [] ls5 = [] ls6 = [] while True: line = eta_strs.readline() line = line.strip() if (len(line) == 0): break eta, lsxx, lsyy, lszz, lsyz, lsxz, lsxy = line.split() if (-mdr1 <= float(eta) and float(eta) <= mdr1): str1.append(float(eta)) ls1.append(float(lsxx)) if (-mdr2 <= float(eta) and float(eta) <= mdr2): str2.append(float(eta)) ls2.append(float(lsyy)) if (-mdr3 <= float(eta) and float(eta) <= mdr3): str3.append(float(eta)) ls3.append(float(lszz)) if (-mdr4 <= float(eta) and float(eta) <= mdr4): str4.append(float(eta)) ls4.append(float(lsyz)) if (-mdr5 <= float(eta) and float(eta) <= mdr5): str5.append(float(eta)) ls5.append(float(lsxz)) if (-mdr6 <= float(eta) and float(eta) <= mdr6): str6.append(float(eta)) ls6.append(float(lsxy)) num_eta1 = len(str1) if (num_eta1 < ordr1+1): sys.exit('\n.... Oops ERROR: NOT enough stress points in "'+Dstn+'_Lagrangian-stress.dat"'\ '\n for '+str(ordr1)+' order polynomial fit.\n') num_eta2 = len(str2) if (num_eta2 < ordr2+1): sys.exit('\n.... Oops ERROR: NOT enough stress points in "'+Dstn+'_Lagrangian-stress.dat"'\ '\n for '+str(ordr2)+' order polynomial fit.\n') num_eta3 = len(str3) if (num_eta3 < ordr3+1): sys.exit('\n.... Oops ERROR: NOT enough stress points in "'+Dstn+'_Lagrangian-stress.dat"'\ '\n for '+str(ordr3)+' order polynomial fit.\n') num_eta4 = len(str4) if (num_eta4 < ordr4+1): sys.exit('\n.... Oops ERROR: NOT enough stress points in "'+Dstn+'_Lagrangian-stress.dat"'\ '\n for '+str(ordr4)+' order polynomial fit.\n') num_eta5 = len(str5) if (num_eta5 < ordr5+1): sys.exit('\n.... Oops ERROR: NOT enough stress points in "'+Dstn+'_Lagrangian-stress.dat"'\ '\n for '+str(ordr5)+' order polynomial fit.\n') num_eta6 = len(str6) if (num_eta6 < ordr6+1): sys.exit('\n.... Oops ERROR: NOT enough stress points in "'+Dstn+'_Lagrangian-stress.dat"'\ '\n for '+str(ordr6)+' order polynomial fit.\n') coeff1 = [] coeff1 = np.polyfit(str1, ls1, ordr1) sigma.append(float(coeff1[ordr1-1])) coeff2 = [] coeff2 = np.polyfit(str2, ls2, ordr2) sigma.append(float(coeff2[ordr2-1])) coeff3 = [] coeff3 = np.polyfit(str3, ls3, ordr3) sigma.append(float(coeff3[ordr3-1])) coeff4 = [] coeff4 = np.polyfit(str4, ls4, ordr4) sigma.append(float(coeff4[ordr4-1])) coeff5 = [] coeff5 = np.polyfit(str5, ls5, ordr5) sigma.append(float(coeff5[ordr5-1])) coeff6 = [] coeff6 = np.polyfit(str6, ls6, ordr6) sigma.append(float(coeff6[ordr6-1])) #%%%--- Calculating the elastic constant and writing the output file ---%!%!%!%!%!%!%!%!%!%!%!%!%!% if (len(sigma) != 6*NoD): sys.exit('\n.... Oops ERROR: Something is WRONG in the "FPTE_2nd.in" file !?!?!?\n') sigma = np.array(sigma) ci = np.linalg.lstsq(Matrix,sigma) C = np.zeros((6,6)) #-- Cubic structures ------------------------------------------------------------------------------ if (LC == 'CI' or \ LC == 'CII'): C[0,0]=ci[0][0] C[0,1]=ci[0][1] C[3,3]=ci[0][2] C[1,1]=C[0,0] C[2,2]=C[0,0] C[0,2]=C[0,1] C[1,2]=C[0,1] C[4,4]=C[3,3] C[5,5]=C[3,3] #-- Hexagonal Structures -------------------------------------------------------------------------- if (LC == 'HI' or \ LC == 'HII'): C[0,0]=ci[0][0] C[0,1]=ci[0][1] C[0,2]=ci[0][2] C[2,2]=ci[0][3] C[3,3]=ci[0][4] C[1,1]=C[0,0] C[1,2]=C[0,2] C[4,4]=C[3,3] C[5,5]=0.5*(C[0,0]-C[0,1]) #-- Rhombohedral I Structures --------------------------------------------------------------------- if (LC == 'RI'): C[0,0]= ci[0][0] C[0,1]= ci[0][1] C[0,2]= ci[0][2] C[0,3]= ci[0][3] C[2,2]= ci[0][4] C[3,3]= ci[0][5] C[1,1]= C[0,0] C[1,2]= C[0,2] C[1,3]=-C[0,3] C[4,5]= C[0,3] C[4,4]= C[3,3] C[5,5]=0.5*(C[0,0]-C[0,1]) #-- Rhombohedral II Structures -------------------------------------------------------------------- if (LC == 'RII'): C[0,0]= ci[0][0] C[0,1]= ci[0][1] C[0,2]= ci[0][2] C[0,3]= ci[0][3] C[0,4]= ci[0][4] C[2,2]= ci[0][5] C[3,3]= ci[0][6] C[1,1]= C[0,0] C[1,2]= C[0,2] C[1,3]=-C[0,3] C[4,5]= C[0,3] C[1,4]=-C[0,4] C[3,5]=-C[0,4] C[4,4]= C[3,3] C[5,5]=0.5*(C[0,0]-C[0,1]) #-- Tetragonal I Structures ----------------------------------------------------------------------- if (LC == 'TI'): C[0,0]= ci[0][0] C[0,1]= ci[0][1] C[0,2]= ci[0][2] C[2,2]= ci[0][3] C[3,3]= ci[0][4] C[5,5]= ci[0][5] C[1,1]= C[0,0] C[1,2]= C[0,2] C[4,4]= C[3,3] #-- Tetragonal II Structures ---------------------------------------------------------------------- if (LC == 'TII'): C[0,0]= ci[0][0] C[0,1]= ci[0][1] C[0,2]= ci[0][2] C[0,5]= ci[0][3] C[2,2]= ci[0][4] C[3,3]= ci[0][5] C[5,5]= ci[0][6] C[1,1]= C[0,0] C[1,2]= C[0,2] C[1,5]=-C[0,5] C[4,4]= C[3,3] #-- Orthorhombic Structures ----------------------------------------------------------------------- if (LC == 'O'): C[0,0]=ci[0][0] C[0,1]=ci[0][1] C[0,2]=ci[0][2] C[1,1]=ci[0][3] C[1,2]=ci[0][4] C[2,2]=ci[0][5] C[3,3]=ci[0][6] C[4,4]=ci[0][7] C[5,5]=ci[0][8] #-- Monoclinic Structures ------------------------------------------------------------------------- if (LC == 'M'): C[0,0]=ci[0][0] C[0,1]=ci[0][1] C[0,2]=ci[0][2] C[0,5]=ci[0][3] C[1,1]=ci[0][4] C[1,2]=ci[0][5] C[1,5]=ci[0][6] C[2,2]=ci[0][7] C[2,5]=ci[0][8] C[3,3]=ci[0][9] C[3,4]=ci[0][10] C[4,4]=ci[0][11] C[5,5]=ci[0][12] #-- Triclinic Structures -------------------------------------------------------------------------- if (LC == 'N'): C[0,0]=ci[0][0] C[0,1]=ci[0][1] C[0,2]=ci[0][2] C[0,3]=ci[0][3] C[0,4]=ci[0][4] C[0,5]=ci[0][5] C[1,1]=ci[0][6] C[1,2]=ci[0][7] C[1,3]=ci[0][8] C[1,4]=ci[0][9] C[1,5]=ci[0][10] C[2,2]=ci[0][11] C[2,3]=ci[0][12] C[2,4]=ci[0][13] C[2,5]=ci[0][14] C[3,3]=ci[0][15] C[3,4]=ci[0][16] C[3,5]=ci[0][17] C[4,4]=ci[0][18] C[4,5]=ci[0][19] C[5,5]=ci[0][20] #-------------------------------------------------------------------------------------------------- #%%%--- Calculating the elastic moduli ---%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!% if (cod == 'WIEN2k' ): CONV = 1. if (cod == 'exciting'): CONV = 1. if (cod == 'ESPRESSO'): CONV =-1./10. if (cod == 'VASP'): CONV =-1./10. for i in range(5): for j in range(i+1,6): C[j,i] = C[i,j] C = C * CONV BV = (C[0,0]+C[1,1]+C[2,2]+2*(C[0,1]+C[0,2]+C[1,2]))/9 GV = ((C[0,0]+C[1,1]+C[2,2])-(C[0,1]+C[0,2]+C[1,2])+3*(C[3,3]+C[4,4]+C[5,5]))/15 EV = (9*BV*GV)/(3*BV+GV) nuV= (1.5*BV-GV)/(3*BV+GV) S = np.linalg.inv(C) BR = 1/(S[0,0]+S[1,1]+S[2,2]+2*(S[0,1]+S[0,2]+S[1,2])) GR =15/(4*(S[0,0]+S[1,1]+S[2,2])-4*(S[0,1]+S[0,2]+S[1,2])+3*(S[3,3]+S[4,4]+S[5,5])) ER = (9*BR*GR)/(3*BR+GR) nuR= (1.5*BR-GR)/(3*BR+GR) BH = 0.50*(BV+BR) GH = 0.50*(GV+GR) EH = (9.*BH*GH)/(3.*BH+GH) nuH= (1.5*BH-GH)/(3.*BH+GH) AVR= 100.*(GV-GR)/(GV+GR) #-------------------------------------------------------------------------------------------------- #%%%--- Writing the output file ---%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%! fo = open('FPTE_2nd.out', 'w') fo.write(' The output of FPTE code \n'\ ' Today is '+ time.asctime() + '\n'\ '\n'\ ' Symmetry of the second-order elastic constant matrix in Voigt notation. \n'\ + head[LC] + '\n'\ ' Elastic constant (stiffness) matrix in GPa: \n') for i in range(0,6): for j in range(0,6): fo.write('%11.1f'%(C[i,j])) fo.write(' \n') fo.write('\n\n Elastic compliance matrix in 1/GPa: \n') for i in range(0,6): for j in range(0,6): fo.write('%11.5f'%(S[i,j])) fo.write('\n') fo.write('\n'+ lineseparator +'\n') fo.write(' Voigt bulk modulus, B_V = {0} GPa'.format('%8.2f'%(BV))) fo.write(' Voigt shear modulus, G_V = {0} GPa'.format('%8.2f'%(GV)) + '\n') fo.write(' Reuss bulk modulus, B_R = {0} GPa'.format('%8.2f'%(BR))) fo.write(' Reuss shear modulus, G_R = {0} GPa'.format('%8.2f'%(GR)) + '\n') fo.write(' Hill bulk modulus, B_H = {0} GPa'.format('%8.2f'%(BH))) fo.write(' Hill shear modulus, G_H = {0} GPa'.format('%8.2f'%(GH))) fo.write('\n'+ lineseparator +'\n') fo.write(' Voigt Young modulus, E_V = {0} GPa'.format('%8.2f'%(EV))) fo.write(' Voigt Poisson ratio, nu_V = {0}' .format('%8.2f'%(nuV)) + '\n') fo.write(' Reuss Young modulus, E_R = {0} GPa'.format('%8.2f'%(ER))) fo.write(' Reuss Poisson ratio, nu_R = {0}' .format('%8.2f'%(nuR)) + '\n') fo.write(' Hill Young modulus, E_H = {0} GPa'.format('%8.2f'%(EH))) fo.write(' Hill Poisson ratio, nu_H = {0}' .format('%8.2f'%(nuH))) fo.write('\n'+ lineseparator +'\n') fo.write(' Elastic Anisotropy in polycrystalline, AVR = {0} %'.format('%8.3f'%(AVR))) fo.write('\n'+ lineseparator +'\n') fo.write(' Eigenvalues of elastic constant (stiffness) matrix: \n') eigval = np.linalg.eig(C) for i in range(6): fo.write('%16.1f' % float(eigval[0][i])) fo.write('\n ... Have a G00D Day, Week, Month, Year, and Century (if you are lucky) ... '\ '\n Bye-Bye! Tschuess! Ciao! Poka! Zia Jian! KhodaHafez! \n') fo.close() #%%%--- Writing Cij in stdout ---%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%! print( ' \n'\ ' Symmetry of the second-order elastic constant matrix in Voigt notation. \n'\ + head[LC] + '\n'\ ' Elastic constant (stiffness) matrix in GPa: \n') for i in range(0,6): print('%13.3f'%C[i][0]+'%13.3f'%C[i][1]+'%13.3f'%C[i][2]+'%13.3f'%C[i][3]+'%13.3f'%C[i][4]+'%13.3f'%C[i][5]) print('\n') print('For more information see the FPTE_2nd.out file.') #-------------------------------------------------------------------------------------------------- os.chdir('../') os.system('cp -f Stress-vs-Strain/FPTE_2nd.out .') if __name__ == "__main__": fpte_results()
[ "numpy.mat", "os.path.exists", "time.asctime", "numpy.linalg.eig", "numpy.polyfit", "os.chdir", "numpy.array", "numpy.zeros", "numpy.linalg.inv", "numpy.linalg.lstsq", "sys.exit", "os.system" ]
[((19581, 19609), 'os.chdir', 'os.chdir', (['"""Stress-vs-Strain"""'], {}), "('Stress-vs-Strain')\n", (19589, 19609), False, 'import os\n'), ((24612, 24627), 'numpy.array', 'np.array', (['sigma'], {}), '(sigma)\n', (24620, 24627), True, 'import numpy as np\n'), ((24640, 24670), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['Matrix', 'sigma'], {}), '(Matrix, sigma)\n', (24655, 24670), True, 'import numpy as np\n'), ((24682, 24698), 'numpy.zeros', 'np.zeros', (['(6, 6)'], {}), '((6, 6))\n', (24690, 24698), True, 'import numpy as np\n'), ((29223, 29239), 'numpy.linalg.inv', 'np.linalg.inv', (['C'], {}), '(C)\n', (29236, 29239), True, 'import numpy as np\n'), ((32030, 32046), 'numpy.linalg.eig', 'np.linalg.eig', (['C'], {}), '(C)\n', (32043, 32046), True, 'import numpy as np\n'), ((33136, 33151), 'os.chdir', 'os.chdir', (['"""../"""'], {}), "('../')\n", (33144, 33151), False, 'import os\n'), ((33156, 33206), 'os.system', 'os.system', (['"""cp -f Stress-vs-Strain/FPTE_2nd.out ."""'], {}), "('cp -f Stress-vs-Strain/FPTE_2nd.out .')\n", (33165, 33206), False, 'import os\n'), ((7610, 7769), 'sys.exit', 'sys.exit', (['"""\n.... Oops ERROR: The order of the elastic constant is NOT clear !?!?!?\n Something is WRONG in the "INFO_FPTE" file.\n"""'], {}), '(\n """\n.... Oops ERROR: The order of the elastic constant is NOT clear !?!?!?\n Something is WRONG in the "INFO_FPTE" file.\n"""\n )\n', (7618, 7769), False, 'import sys\n'), ((7888, 8043), 'sys.exit', 'sys.exit', (['"""\n.... Oops ERROR: The method of the calculation is NOT clear !?!?!?\n Something is WRONG in the "INFO_FPTE" file.\n"""'], {}), '(\n """\n.... Oops ERROR: The method of the calculation is NOT clear !?!?!?\n Something is WRONG in the "INFO_FPTE" file.\n"""\n )\n', (7896, 8043), False, 'import sys\n'), ((8202, 8340), 'sys.exit', 'sys.exit', (['"""\n.... Oops ERROR: The DFT code is NOT clear !?!?!?\n Something is WRONG in the "INFO_FPTE" file.\n"""'], {}), '(\n """\n.... Oops ERROR: The DFT code is NOT clear !?!?!?\n Something is WRONG in the "INFO_FPTE" file.\n"""\n )\n', (8210, 8340), False, 'import sys\n'), ((10229, 10343), 'numpy.mat', 'np.mat', (['[[1.0, 5.0, 0.0], [2.0, 4.0, 0.0], [3.0, 3.0, 0.0], [0.0, 0.0, 4.0], [0.0, \n 0.0, 5.0], [0.0, 0.0, 6.0]]'], {}), '([[1.0, 5.0, 0.0], [2.0, 4.0, 0.0], [3.0, 3.0, 0.0], [0.0, 0.0, 4.0],\n [0.0, 0.0, 5.0], [0.0, 0.0, 6.0]])\n', (10235, 10343), True, 'import numpy as np\n'), ((10516, 10744), 'numpy.mat', 'np.mat', (['[[1, 2, 3, 0, 0], [2, 1, 3, 0, 0], [0, 0, 3, 3, 0], [0, 0, 0, 0, 4], [0, 0,\n 0, 0, 5], [3, -3, 0, 0, 0], [3, -5, -1, 0, 0], [-5, 3, -1, 0, 0], [0, 0,\n -2, -1, 0], [0, 0, 0, 0, 6], [0, 0, 0, 0, 2], [-2, 2, 0, 0, 0]]'], {}), '([[1, 2, 3, 0, 0], [2, 1, 3, 0, 0], [0, 0, 3, 3, 0], [0, 0, 0, 0, 4],\n [0, 0, 0, 0, 5], [3, -3, 0, 0, 0], [3, -5, -1, 0, 0], [-5, 3, -1, 0, 0],\n [0, 0, -2, -1, 0], [0, 0, 0, 0, 6], [0, 0, 0, 0, 2], [-2, 2, 0, 0, 0]])\n', (10522, 10744), True, 'import numpy as np\n'), ((11000, 11272), 'numpy.mat', 'np.mat', (['[[1, 2, 3, 4, 0, 0], [2, 1, 3, -4, 0, 0], [0, 0, 3, 0, 3, 0], [0, 0, 0, -1,\n 0, 4], [0, 0, 0, 6, 0, 5], [3, -3, 0, 5, 0, 0], [3, -5, -1, 6, 0, 0], [\n -5, 3, -1, -6, 0, 0], [0, 0, -2, 0, -1, 0], [0, 0, 0, 8, 0, 6], [0, 0, \n 0, -4, 0, 2], [-2, 2, 0, 2, 0, 0]]'], {}), '([[1, 2, 3, 4, 0, 0], [2, 1, 3, -4, 0, 0], [0, 0, 3, 0, 3, 0], [0, 0,\n 0, -1, 0, 4], [0, 0, 0, 6, 0, 5], [3, -3, 0, 5, 0, 0], [3, -5, -1, 6, 0,\n 0], [-5, 3, -1, -6, 0, 0], [0, 0, -2, 0, -1, 0], [0, 0, 0, 8, 0, 6], [0,\n 0, 0, -4, 0, 2], [-2, 2, 0, 2, 0, 0]])\n', (11006, 11272), True, 'import numpy as np\n'), ((11521, 11841), 'numpy.mat', 'np.mat', (['[[1, 2, 3, 4, 5, 0, 0], [2, 1, 3, -4, -5, 0, 0], [0, 0, 3, 0, 0, 3, 0], [0,\n 0, 0, -1, -6, 0, 4], [0, 0, 0, 6, -1, 0, 5], [3, -3, 0, 5, -4, 0, 0], [\n 3, -5, -1, 6, 2, 0, 0], [-5, 3, -1, -6, -2, 0, 0], [0, 0, -2, 0, 0, -1,\n 0], [0, 0, 0, 8, 4, 0, 6], [0, 0, 0, -4, 8, 0, 2], [-2, 2, 0, 2, -6, 0, 0]]'], {}), '([[1, 2, 3, 4, 5, 0, 0], [2, 1, 3, -4, -5, 0, 0], [0, 0, 3, 0, 0, 3, \n 0], [0, 0, 0, -1, -6, 0, 4], [0, 0, 0, 6, -1, 0, 5], [3, -3, 0, 5, -4, \n 0, 0], [3, -5, -1, 6, 2, 0, 0], [-5, 3, -1, -6, -2, 0, 0], [0, 0, -2, 0,\n 0, -1, 0], [0, 0, 0, 8, 4, 0, 6], [0, 0, 0, -4, 8, 0, 2], [-2, 2, 0, 2,\n -6, 0, 0]])\n', (11527, 11841), True, 'import numpy as np\n'), ((12077, 12346), 'numpy.mat', 'np.mat', (['[[1, 2, 3, 0, 0, 0], [2, 1, 3, 0, 0, 0], [0, 0, 3, 3, 0, 0], [0, 0, 0, 0, 4,\n 0], [0, 0, 0, 0, 5, 0], [0, 0, 0, 0, 0, 6], [3, -5, -1, 0, 0, 0], [-5, \n 3, -1, 0, 0, 0], [0, 0, -2, -1, 0, 0], [0, 0, 0, 0, 6, 0], [0, 0, 0, 0,\n 2, 0], [0, 0, 0, 0, 0, -4]]'], {}), '([[1, 2, 3, 0, 0, 0], [2, 1, 3, 0, 0, 0], [0, 0, 3, 3, 0, 0], [0, 0, \n 0, 0, 4, 0], [0, 0, 0, 0, 5, 0], [0, 0, 0, 0, 0, 6], [3, -5, -1, 0, 0, \n 0], [-5, 3, -1, 0, 0, 0], [0, 0, -2, -1, 0, 0], [0, 0, 0, 0, 6, 0], [0,\n 0, 0, 0, 2, 0], [0, 0, 0, 0, 0, -4]])\n', (12083, 12346), True, 'import numpy as np\n'), ((12598, 12905), 'numpy.mat', 'np.mat', (['[[1, 2, 3, 6, 0, 0, 0], [2, 1, 3, -6, 0, 0, 0], [0, 0, 3, 0, 3, 0, 0], [0, \n 0, 0, 0, 0, 4, 0], [0, 0, 0, 0, 0, 5, 0], [0, 0, 0, -1, 0, 0, 6], [3, -\n 5, -1, -4, 0, 0, 0], [-5, 3, -1, 4, 0, 0, 0], [0, 0, -2, 0, -1, 0, 0],\n [0, 0, 0, 0, 0, 6, 0], [0, 0, 0, 0, 0, 2, 0], [0, 0, 0, 8, 0, 0, -4]]'], {}), '([[1, 2, 3, 6, 0, 0, 0], [2, 1, 3, -6, 0, 0, 0], [0, 0, 3, 0, 3, 0, 0\n ], [0, 0, 0, 0, 0, 4, 0], [0, 0, 0, 0, 0, 5, 0], [0, 0, 0, -1, 0, 0, 6],\n [3, -5, -1, -4, 0, 0, 0], [-5, 3, -1, 4, 0, 0, 0], [0, 0, -2, 0, -1, 0,\n 0], [0, 0, 0, 0, 0, 6, 0], [0, 0, 0, 0, 0, 2, 0], [0, 0, 0, 8, 0, 0, -4]])\n', (12604, 12905), True, 'import numpy as np\n'), ((13153, 13724), 'numpy.mat', 'np.mat', (['[[1, 2, 3, 0, 0, 0, 0, 0, 0], [0, 1, 0, 2, 3, 0, 0, 0, 0], [0, 0, 1, 0, 2, \n 3, 0, 0, 0], [0, 0, 0, 0, 0, 0, 4, 0, 0], [0, 0, 0, 0, 0, 0, 0, 5, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 6], [3, -5, -1, 0, 0, 0, 0, 0, 0], [0, 3, 0, -\n 5, -1, 0, 0, 0, 0], [0, 0, 3, 0, -5, -1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 6,\n 0, 0], [0, 0, 0, 0, 0, 0, 0, 2, 0], [0, 0, 0, 0, 0, 0, 0, 0, -4], [5, 4,\n 6, 0, 0, 0, 0, 0, 0], [0, 5, 0, 4, 6, 0, 0, 0, 0], [0, 0, 5, 0, 4, 6, 0,\n 0, 0], [0, 0, 0, 0, 0, 0, -2, 0, 0], [0, 0, 0, 0, 0, 0, 0, -1, 0], [0, \n 0, 0, 0, 0, 0, 0, 0, -3]]'], {}), '([[1, 2, 3, 0, 0, 0, 0, 0, 0], [0, 1, 0, 2, 3, 0, 0, 0, 0], [0, 0, 1,\n 0, 2, 3, 0, 0, 0], [0, 0, 0, 0, 0, 0, 4, 0, 0], [0, 0, 0, 0, 0, 0, 0, 5,\n 0], [0, 0, 0, 0, 0, 0, 0, 0, 6], [3, -5, -1, 0, 0, 0, 0, 0, 0], [0, 3, \n 0, -5, -1, 0, 0, 0, 0], [0, 0, 3, 0, -5, -1, 0, 0, 0], [0, 0, 0, 0, 0, \n 0, 6, 0, 0], [0, 0, 0, 0, 0, 0, 0, 2, 0], [0, 0, 0, 0, 0, 0, 0, 0, -4],\n [5, 4, 6, 0, 0, 0, 0, 0, 0], [0, 5, 0, 4, 6, 0, 0, 0, 0], [0, 0, 5, 0, \n 4, 6, 0, 0, 0], [0, 0, 0, 0, 0, 0, -2, 0, 0], [0, 0, 0, 0, 0, 0, 0, -1,\n 0], [0, 0, 0, 0, 0, 0, 0, 0, -3]])\n', (13159, 13724), True, 'import numpy as np\n'), ((14062, 15414), 'numpy.mat', 'np.mat', (['[[1, 2, 3, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 2, 3, 6, 0, 0, 0, 0,\n 0, 0], [0, 0, 1, 0, 0, 2, 0, 3, 6, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0,\n 0, 4, 5, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 0], [0, 0, 0, 1, 0,\n 0, 2, 0, 3, 0, 0, 0, 6], [-2, 1, 4, -5, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0,\n -2, 0, 0, 1, 4, -5, 0, 0, 0, 0, 0, 0], [0, 0, -2, 0, 0, 1, 0, 4, -5, 0,\n 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, -3, 6, 0, 0], [0, 0, 0, 0, 0, 0, \n 0, 0, 0, 0, -3, 6, 0], [0, 0, 0, -2, 0, 0, 1, 0, 4, 0, 0, -5, 0], [3, -\n 5, -1, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 3, 0, 0, -5, -1, -4, 0, 0, 0,\n 0, 0, 0], [0, 0, 3, 0, 0, -5, 0, -1, -4, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0,\n 0, 0, 0, 6, 2, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 0], [0, 0, 0,\n 3, 0, 0, -5, 0, -1, 0, 0, -4, 0], [-4, -6, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0,\n 0], [0, -4, 0, 0, -6, 5, 2, 0, 0, 0, 0, 0, 0], [0, 0, -4, 0, 0, -6, 0, \n 5, 2, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -3, 0, 0], [0, 0, 0, \n 0, 0, 0, 0, 0, 0, 0, 1, -3, 0], [0, 0, 0, -4, 0, 0, -6, 0, 5, 0, 0, 2, \n 0], [5, 4, 6, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 5, 0, 0, 4, 6, -3, 0,\n 0, 0, 0, 0, 0], [0, 0, 5, 0, 0, 4, 0, 6, -3, 0, 0, 0, 0], [0, 0, 0, 0, \n 0, 0, 0, 0, 0, -2, -1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, -1, 0],\n [0, 0, 0, 5, 0, 0, 4, 0, 6, 0, 0, -3, 0]]'], {}), '([[1, 2, 3, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 2, 3, 6, 0, 0,\n 0, 0, 0, 0], [0, 0, 1, 0, 0, 2, 0, 3, 6, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0,\n 0, 0, 0, 4, 5, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 0], [0, 0, 0,\n 1, 0, 0, 2, 0, 3, 0, 0, 0, 6], [-2, 1, 4, -5, 0, 0, 0, 0, 0, 0, 0, 0, 0\n ], [0, -2, 0, 0, 1, 4, -5, 0, 0, 0, 0, 0, 0], [0, 0, -2, 0, 0, 1, 0, 4,\n -5, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, -3, 6, 0, 0], [0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, -3, 6, 0], [0, 0, 0, -2, 0, 0, 1, 0, 4, 0, 0, -5, 0],\n [3, -5, -1, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 3, 0, 0, -5, -1, -4, 0,\n 0, 0, 0, 0, 0], [0, 0, 3, 0, 0, -5, 0, -1, -4, 0, 0, 0, 0], [0, 0, 0, 0,\n 0, 0, 0, 0, 0, 6, 2, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 0], [0,\n 0, 0, 3, 0, 0, -5, 0, -1, 0, 0, -4, 0], [-4, -6, 5, 2, 0, 0, 0, 0, 0, 0,\n 0, 0, 0], [0, -4, 0, 0, -6, 5, 2, 0, 0, 0, 0, 0, 0], [0, 0, -4, 0, 0, -\n 6, 0, 5, 2, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -3, 0, 0], [0, \n 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -3, 0], [0, 0, 0, -4, 0, 0, -6, 0, 5, 0, \n 0, 2, 0], [5, 4, 6, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 5, 0, 0, 4, 6, \n -3, 0, 0, 0, 0, 0, 0], [0, 0, 5, 0, 0, 4, 0, 6, -3, 0, 0, 0, 0], [0, 0,\n 0, 0, 0, 0, 0, 0, 0, -2, -1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, \n -1, 0], [0, 0, 0, 5, 0, 0, 4, 0, 6, 0, 0, -3, 0]])\n', (14068, 15414), True, 'import numpy as np\n'), ((15949, 18543), 'numpy.mat', 'np.mat', (['[[1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0,\n 0, 0, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, \n 0, 0, 2, 0, 0, 0, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, \n 0, 2, 0, 0, 0, 3, 0, 0, 4, 5, 6, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, \n 2, 0, 0, 0, 3, 0, 0, 4, 0, 5, 6, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, \n 0, 0, 0, 3, 0, 0, 4, 0, 5, 6], [-2, 1, 4, -3, 6, -5, 0, 0, 0, 0, 0, 0, \n 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, -2, 0, 0, 0, 0, 1, 4, -3, 6, -5, 0, 0, \n 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, -2, 0, 0, 0, 0, 1, 0, 0, 0, 4, -3, 6, -\n 5, 0, 0, 0, 0, 0, 0], [0, 0, 0, -2, 0, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, -3,\n 6, -5, 0, 0, 0], [0, 0, 0, 0, -2, 0, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, -3, \n 0, 6, -5, 0], [0, 0, 0, 0, 0, -2, 0, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, -3, \n 0, 6, -5], [3, -5, -1, 6, 2, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0], [0, 3, 0, 0, 0, 0, -5, -1, 6, 2, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n 0], [0, 0, 3, 0, 0, 0, 0, -5, 0, 0, 0, -1, 6, 2, -4, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 3, 0, 0, 0, 0, -5, 0, 0, 0, -1, 0, 0, 6, 2, -4, 0, 0, 0], [0,\n 0, 0, 0, 3, 0, 0, 0, 0, -5, 0, 0, 0, -1, 0, 0, 6, 0, 2, -4, 0], [0, 0, \n 0, 0, 0, 3, 0, 0, 0, 0, -5, 0, 0, 0, -1, 0, 0, 6, 0, 2, -4], [-4, -6, 5,\n 1, -3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, -4, 0, 0, 0,\n 0, -6, 5, 1, -3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, -4, 0, 0, 0, \n 0, -6, 0, 0, 0, 5, 1, -3, 2, 0, 0, 0, 0, 0, 0], [0, 0, 0, -4, 0, 0, 0, \n 0, -6, 0, 0, 0, 5, 0, 0, 1, -3, 2, 0, 0, 0], [0, 0, 0, 0, -4, 0, 0, 0, \n 0, -6, 0, 0, 0, 5, 0, 0, 1, 0, -3, 2, 0], [0, 0, 0, 0, 0, -4, 0, 0, 0, \n 0, -6, 0, 0, 0, 5, 0, 0, 1, 0, -3, 2], [5, 4, 6, -2, -1, -3, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0, 4, 6, -2, -1, -3, \n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 6, -2,\n -1, -3, 0, 0, 0, 0, 0, 0], [0, 0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 6, 0, 0,\n -2, -1, -3, 0, 0, 0], [0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 6, 0, 0, \n -2, 0, -1, -3, 0], [0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 6, 0, 0, \n -2, 0, -1, -3], [-6, 3, -2, 5, -4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n 0, 0, 0, 0], [0, -6, 0, 0, 0, 0, 3, -2, 5, -4, 1, 0, 0, 0, 0, 0, 0, 0, \n 0, 0, 0], [0, 0, -6, 0, 0, 0, 0, 3, 0, 0, 0, -2, 5, -4, 1, 0, 0, 0, 0, \n 0, 0], [0, 0, 0, -6, 0, 0, 0, 0, 3, 0, 0, 0, -2, 0, 0, 5, -4, 1, 0, 0, \n 0], [0, 0, 0, 0, -6, 0, 0, 0, 0, 3, 0, 0, 0, -2, 0, 0, 5, 0, -4, 1, 0],\n [0, 0, 0, 0, 0, -6, 0, 0, 0, 0, 3, 0, 0, 0, -2, 0, 0, 5, 0, -4, 1]]'], {}), '([[1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0,\n 1, 0, 0, 0, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, \n 0, 0, 0, 0, 2, 0, 0, 0, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, \n 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 4, 5, 6, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, \n 0, 0, 2, 0, 0, 0, 3, 0, 0, 4, 0, 5, 6, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, \n 0, 2, 0, 0, 0, 3, 0, 0, 4, 0, 5, 6], [-2, 1, 4, -3, 6, -5, 0, 0, 0, 0, \n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, -2, 0, 0, 0, 0, 1, 4, -3, 6, -5, \n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, -2, 0, 0, 0, 0, 1, 0, 0, 0, 4, -3,\n 6, -5, 0, 0, 0, 0, 0, 0], [0, 0, 0, -2, 0, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0,\n -3, 6, -5, 0, 0, 0], [0, 0, 0, 0, -2, 0, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, \n -3, 0, 6, -5, 0], [0, 0, 0, 0, 0, -2, 0, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, \n -3, 0, 6, -5], [3, -5, -1, 6, 2, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0], [0, 3, 0, 0, 0, 0, -5, -1, 6, 2, -4, 0, 0, 0, 0, 0, 0, 0, 0, \n 0, 0], [0, 0, 3, 0, 0, 0, 0, -5, 0, 0, 0, -1, 6, 2, -4, 0, 0, 0, 0, 0, \n 0], [0, 0, 0, 3, 0, 0, 0, 0, -5, 0, 0, 0, -1, 0, 0, 6, 2, -4, 0, 0, 0],\n [0, 0, 0, 0, 3, 0, 0, 0, 0, -5, 0, 0, 0, -1, 0, 0, 6, 0, 2, -4, 0], [0,\n 0, 0, 0, 0, 3, 0, 0, 0, 0, -5, 0, 0, 0, -1, 0, 0, 6, 0, 2, -4], [-4, -6,\n 5, 1, -3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, -4, 0, 0,\n 0, 0, -6, 5, 1, -3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, -4, 0, 0, \n 0, 0, -6, 0, 0, 0, 5, 1, -3, 2, 0, 0, 0, 0, 0, 0], [0, 0, 0, -4, 0, 0, \n 0, 0, -6, 0, 0, 0, 5, 0, 0, 1, -3, 2, 0, 0, 0], [0, 0, 0, 0, -4, 0, 0, \n 0, 0, -6, 0, 0, 0, 5, 0, 0, 1, 0, -3, 2, 0], [0, 0, 0, 0, 0, -4, 0, 0, \n 0, 0, -6, 0, 0, 0, 5, 0, 0, 1, 0, -3, 2], [5, 4, 6, -2, -1, -3, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0, 4, 6, -2, -1, -\n 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 6, \n -2, -1, -3, 0, 0, 0, 0, 0, 0], [0, 0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 6, \n 0, 0, -2, -1, -3, 0, 0, 0], [0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 6, \n 0, 0, -2, 0, -1, -3, 0], [0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0, 0, 0, 6, \n 0, 0, -2, 0, -1, -3], [-6, 3, -2, 5, -4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n 0, 0, 0, 0, 0, 0], [0, -6, 0, 0, 0, 0, 3, -2, 5, -4, 1, 0, 0, 0, 0, 0, \n 0, 0, 0, 0, 0], [0, 0, -6, 0, 0, 0, 0, 3, 0, 0, 0, -2, 5, -4, 1, 0, 0, \n 0, 0, 0, 0], [0, 0, 0, -6, 0, 0, 0, 0, 3, 0, 0, 0, -2, 0, 0, 5, -4, 1, \n 0, 0, 0], [0, 0, 0, 0, -6, 0, 0, 0, 0, 3, 0, 0, 0, -2, 0, 0, 5, 0, -4, \n 1, 0], [0, 0, 0, 0, 0, -6, 0, 0, 0, 0, 3, 0, 0, 0, -2, 0, 0, 5, 0, -4, 1]])\n', (15955, 18543), True, 'import numpy as np\n'), ((19491, 19587), 'sys.exit', 'sys.exit', (['"""\n.... Oops ERROR: Something is WRONG in the "FPTE_2nd.in" file !?!?!?\n"""'], {}), '(\n """\n.... Oops ERROR: Something is WRONG in the "FPTE_2nd.in" file !?!?!?\n"""\n )\n', (19499, 19587), False, 'import sys\n'), ((23737, 23765), 'numpy.polyfit', 'np.polyfit', (['str1', 'ls1', 'ordr1'], {}), '(str1, ls1, ordr1)\n', (23747, 23765), True, 'import numpy as np\n'), ((23849, 23877), 'numpy.polyfit', 'np.polyfit', (['str2', 'ls2', 'ordr2'], {}), '(str2, ls2, ordr2)\n', (23859, 23877), True, 'import numpy as np\n'), ((23961, 23989), 'numpy.polyfit', 'np.polyfit', (['str3', 'ls3', 'ordr3'], {}), '(str3, ls3, ordr3)\n', (23971, 23989), True, 'import numpy as np\n'), ((24073, 24101), 'numpy.polyfit', 'np.polyfit', (['str4', 'ls4', 'ordr4'], {}), '(str4, ls4, ordr4)\n', (24083, 24101), True, 'import numpy as np\n'), ((24185, 24213), 'numpy.polyfit', 'np.polyfit', (['str5', 'ls5', 'ordr5'], {}), '(str5, ls5, ordr5)\n', (24195, 24213), True, 'import numpy as np\n'), ((24297, 24325), 'numpy.polyfit', 'np.polyfit', (['str6', 'ls6', 'ordr6'], {}), '(str6, ls6, ordr6)\n', (24307, 24325), True, 'import numpy as np\n'), ((24514, 24610), 'sys.exit', 'sys.exit', (['"""\n.... Oops ERROR: Something is WRONG in the "FPTE_2nd.in" file !?!?!?\n"""'], {}), '(\n """\n.... Oops ERROR: Something is WRONG in the "FPTE_2nd.in" file !?!?!?\n"""\n )\n', (24522, 24610), False, 'import sys\n'), ((20412, 20459), 'os.path.exists', 'os.path.exists', (["(Dstn + '_Lagrangian-stress.dat')"], {}), "(Dstn + '_Lagrangian-stress.dat')\n", (20426, 20459), False, 'import os\n'), ((20485, 20582), 'sys.exit', 'sys.exit', (['("""\n.... Oops ERROR: Where is the \\"""" + Dstn +\n \'_Lagrangian-stress.dat" !?!?!?\\n\')'], {}), '("""\n.... Oops ERROR: Where is the \\"""" + Dstn +\n \'_Lagrangian-stress.dat" !?!?!?\\n\')\n', (20493, 20582), False, 'import sys\n'), ((29954, 29968), 'time.asctime', 'time.asctime', ([], {}), '()\n', (29966, 29968), False, 'import time\n'), ((9799, 9869), 'sys.exit', 'sys.exit', (['"""\n.... Oops ERROR: WRONG Space-Group Number !?!?!? \n"""'], {}), '("""\n.... Oops ERROR: WRONG Space-Group Number !?!?!? \n""")\n', (9807, 9869), False, 'import sys\n')]
from __future__ import division, absolute_import, print_function from builtins import range import numpy as np import os import sys import esutil import time import matplotlib.pyplot as plt import scipy.optimize from astropy.time import Time from .sharedNumpyMemManager import SharedNumpyMemManager as snmm class FgcmQeSysSlope(object): """ Class which computes the slope of the system QE degredation. Parameters ---------- fgcmConfig: FgcmConfig Config object fgcmPars: FgcmParameters Parameter object fgcmStars: FgcmStars Stars object initialCycle: `bool` Is this the initial cycle? (Force gray computation) """ def __init__(self, fgcmConfig, fgcmPars, fgcmStars): self.fgcmLog = fgcmConfig.fgcmLog self.fgcmLog.debug('Initializing FgcmQeSysSlope') self.outfileBaseWithCycle = fgcmConfig.outfileBaseWithCycle self.plotPath = fgcmConfig.plotPath self.fgcmPars = fgcmPars self.fgcmStars = fgcmStars self.bandFitIndex = fgcmConfig.bandFitIndex self.instrumentParsPerBand = fgcmConfig.instrumentParsPerBand self.instrumentSlopeMinDeltaT = fgcmConfig.instrumentSlopeMinDeltaT self.ccdGrayMaxStarErr = fgcmConfig.ccdGrayMaxStarErr def computeQeSysSlope(self, name): """ Compute QE system slope Parameters ---------- name: `str` Name to put on filenames """ objID = snmm.getArray(self.fgcmStars.objIDHandle) obsObjIDIndex = snmm.getArray(self.fgcmStars.obsObjIDIndexHandle) obsExpIndex = snmm.getArray(self.fgcmStars.obsExpIndexHandle) obsBandIndex = snmm.getArray(self.fgcmStars.obsBandIndexHandle) obsMagStd = snmm.getArray(self.fgcmStars.obsMagStdHandle) obsMagADUModelErr = snmm.getArray(self.fgcmStars.obsMagADUModelErrHandle) # Select good stars and good observations of said stars goodStars = self.fgcmStars.getGoodStarIndices(checkMinObs=True) _, goodObs = self.fgcmStars.getGoodObsIndices(goodStars, expFlag=self.fgcmPars.expFlag, checkBadMag=True) # Further filter good observations ok, = np.where((obsMagADUModelErr[goodObs] < self.ccdGrayMaxStarErr) & (obsMagADUModelErr[goodObs] > 0.0) & (obsMagStd[goodObs] < 90.0)) goodObs = goodObs[ok] # Make copies so we don't overwrite anything obsMagStdGO = obsMagStd[goodObs] obsMagErr2GO = obsMagADUModelErr[goodObs]**2. obsExpIndexGO = obsExpIndex[goodObs] # Remove the previously applied slope deltaQESlopeGO = (self.fgcmPars.compQESysSlopeApplied[obsBandIndex[goodObs], self.fgcmPars.expWashIndex[obsExpIndexGO]] * (self.fgcmPars.expMJD[obsExpIndexGO] - self.fgcmPars.washMJDs[self.fgcmPars.expWashIndex[obsExpIndexGO]])) obsMagStdGO -= deltaQESlopeGO # split per wash interval washH, washRev = esutil.stat.histogram(self.fgcmPars.expWashIndex[obsExpIndexGO], rev=True, min=0) washIndices, = np.where(washH > 0) for washIndex in washIndices: i1a = washRev[washRev[washIndex]: washRev[washIndex + 1]] # Split per band, and compute the delta-T and delta-Mag bandH, bandRev = esutil.stat.histogram(obsBandIndex[goodObs[i1a]], rev=True, min=0) bandIndices, = np.where(bandH > 0) deltaTAll = None for bandIndex in bandIndices: if not self.fgcmPars.hasExposuresInBand[bandIndex]: continue i2a = bandRev[bandRev[bandIndex]: bandRev[bandIndex + 1]] # Now lump the stars together thisObjID = objID[obsObjIDIndex[goodObs[i1a[i2a]]]] thisMjd = self.fgcmPars.expMJD[obsExpIndexGO[i1a[i2a]]] thisMag = obsMagStdGO[i1a[i2a]] thisMagErr2 = obsMagErr2GO[i1a[i2a]] minID = thisObjID.min() maxID = thisObjID.max() # we need to sort and take unique to get the index of the first mjd st = np.argsort(thisMjd) minMjd = np.zeros(maxID - minID + 1) starIndices, firstIndex = np.unique(thisObjID[st] - minID, return_index=True) minMjd[starIndices] = thisMjd[st[firstIndex]] firstMag = np.zeros_like(minMjd, dtype=np.float32) firstMag[starIndices] = thisMag[st[firstIndex]] firstMagErr2 = np.zeros_like(firstMag) firstMagErr2[starIndices] = thisMagErr2[st[firstIndex]] deltaT = thisMjd - minMjd[thisObjID - minID] deltaMag = thisMag - firstMag[thisObjID - minID] deltaMagErr2 = thisMagErr2 + firstMagErr2[thisObjID - minID] okDelta, = np.where((deltaT > self.instrumentSlopeMinDeltaT) & (deltaMagErr2 < self.ccdGrayMaxStarErr)) deltaT = deltaT[okDelta] deltaMag = deltaMag[okDelta] deltaMagErr2 = deltaMagErr2[okDelta] # Check if we are doing one band at a time or lumping together. if not self.instrumentParsPerBand: # Lump all together. Not the most efficient, may need to update. if deltaTAll is None: deltaTAll = deltaT deltaMagAll = deltaMag deltaMagErr2All = deltaMagErr2 elif bandIndex in self.bandFitIndex: # only add if this is one of the fit bands deltaTAll = np.append(deltaTAll, deltaT) deltaMagAll = np.append(deltaMagAll, deltaMag) deltaMagErr2All = np.append(deltaMagErr2All, deltaMagErr2) else: # Do per band if deltaT.size < 500: # Just do no slope extraString = ' (Not enough observations)' slopeMean = 0.0 slopeMeanErr = 0.0 else: extraString = '' slope = deltaMag / deltaT slopeErr2 = deltaMagErr2 / np.abs(deltaT)**2. slopeMean = np.clip(-1 * np.sum(slope / slopeErr2) / np.sum(1. / slopeErr2), -0.001, 0.0) slopeMeanErr = np.sqrt(1. / np.sum(1. / slopeErr2)) self.fgcmLog.info("Wash interval %d, computed qe slope in %s band: %.6f +/- %.6f mmag/day%s" % (washIndex, self.fgcmPars.bands[bandIndex], slopeMean*1000.0, slopeMeanErr*1000.0, extraString)) self.fgcmPars.compQESysSlope[bandIndex, washIndex] = slopeMean if not self.instrumentParsPerBand: # Compute all together if deltaTAll.size < 500: extraString = ' (Not enough observations)' slopeMeanAll = 0.0 slopeMeanErrAll = 0.0 else: extraString = '' slopeAll = deltaMagAll / deltaTAll slopeErr2All = deltaMagErr2All / np.abs(deltaTAll)**2. slopeMeanAll = np.clip(-1 * np.sum(slopeAll / slopeErr2All) / np.sum(1. / slopeErr2All), -0.001, 0.0) slopeMeanErrAll = np.sqrt(1. / np.sum(1. / slopeErr2All)) self.fgcmLog.info("Wash interval %d, computed qe slope in all bands: %.6f +/- %.6f mmag/day%s" % (washIndex, slopeMeanAll*1000.0, slopeMeanErrAll*1000.0, extraString)) self.fgcmPars.compQESysSlope[:, washIndex] = slopeMeanAll if self.plotPath is not None: # Make the plots firstMJD = np.floor(np.min(self.fgcmPars.expMJD)) fig = plt.figure(1, figsize=(8, 6)) fig.clf() ax = fig.add_subplot(111) colors = ['g', 'b', 'r', 'c', 'm', 'y', 'k'] started = False for i in range(self.fgcmPars.nWashIntervals): use, = np.where(self.fgcmPars.expWashIndex == i) if use.size == 0: # There are none in this interval, that's fine continue washMJDRange = [np.min(self.fgcmPars.expMJD[use]), np.max(self.fgcmPars.expMJD[use])] if self.instrumentParsPerBand: # Need to plot all of them one-by-one for j in range(self.fgcmPars.nBands): if not self.fgcmPars.hasExposuresInBand[j]: continue label = self.fgcmPars.bands[j] if not started else None ax.plot(washMJDRange - firstMJD, 1000.0*((washMJDRange - self.fgcmPars.washMJDs[i])*self.fgcmPars.compQESysSlope[j, i] + self.fgcmPars.parQESysIntercept[j, i]), linestyle='--', color=colors[j % len(colors)], linewidth=2, label=label) else: ax.plot(washMJDRange - firstMJD, 1000.0*((washMJDRange - self.fgcmPars.washMJDs[i])*self.fgcmPars.compQESysSlope[0, i] + self.fgcmPars.parQESysIntercept[0, i]), 'r--', linewidth=3) started = True if self.instrumentParsPerBand: ax.legend(loc=3) ax.set_xlabel(r'$\mathrm{MJD}\ -\ %.0f$' % (firstMJD), fontsize=16) ax.set_ylabel('$2.5 \log_{10} (S^{\mathrm{optics}})\,(\mathrm{mmag})$', fontsize=16) ax.tick_params(axis='both', which='major', labelsize=14) # Make the vertical wash markers ylim = ax.get_ylim() for i in range(self.fgcmPars.nWashIntervals): ax.plot([self.fgcmPars.washMJDs[i] - firstMJD, self.fgcmPars.washMJDs[i]-firstMJD], ylim, 'k--') fig.savefig('%s/%s_qesys_washes_%s.png' % (self.plotPath, self.outfileBaseWithCycle, name)) plt.close(fig) def plotQeSysRefStars(self, name): """ Plot reference stars (if available). Compare residuals. Parameters ---------- name: `str` name to give the files """ if not self.fgcmStars.hasRefstars: self.fgcmLog.info("No reference stars for QE sys plots.") return if self.plotPath is None: return plt.set_cmap('viridis') obsObjIDIndex = snmm.getArray(self.fgcmStars.obsObjIDIndexHandle) obsMagStd = snmm.getArray(self.fgcmStars.obsMagStdHandle) obsBandIndex = snmm.getArray(self.fgcmStars.obsBandIndexHandle) obsExpIndex = snmm.getArray(self.fgcmStars.obsExpIndexHandle) objRefIDIndex = snmm.getArray(self.fgcmStars.objRefIDIndexHandle) refMag = snmm.getArray(self.fgcmStars.refMagHandle) goodStars = self.fgcmStars.getGoodStarIndices(checkMinObs=True) _, goodObs = self.fgcmStars.getGoodObsIndices(goodStars, expFlag=self.fgcmPars.expFlag, checkBadMag=True) # Take out the previous slope... obsMagStdGO = obsMagStd[goodObs] obsExpIndexGO = obsExpIndex[goodObs] deltaQESysGO = (self.fgcmPars.parQESysIntercept[obsBandIndex[goodObs], self.fgcmPars.expWashIndex[obsExpIndexGO]] + self.fgcmPars.compQESysSlopeApplied[obsBandIndex[goodObs], self.fgcmPars.expWashIndex[obsExpIndexGO]] * (self.fgcmPars.expMJD[obsExpIndexGO] - self.fgcmPars.washMJDs[self.fgcmPars.expWashIndex[obsExpIndexGO]])) obsMagObsGO = obsMagStdGO - deltaQESysGO goodRefObsGO, = np.where(objRefIDIndex[obsObjIDIndex[goodObs]] >= 0) if goodRefObsGO.size < 100: self.fgcmLog.info("Not enough reference star information to make QE sys plots.") return obsUse, = np.where((obsMagStd[goodObs[goodRefObsGO]] < 90.0) & (refMag[objRefIDIndex[obsObjIDIndex[goodObs[goodRefObsGO]]], obsBandIndex[goodObs[goodRefObsGO]]] < 90.0)) if obsUse.size < 100: self.fgcmLog.info("Not enough good reference star information to make QE sys plots.") return goodRefObsGO = goodRefObsGO[obsUse] EGrayGRO = (refMag[objRefIDIndex[obsObjIDIndex[goodObs[goodRefObsGO]]], obsBandIndex[goodObs[goodRefObsGO]]] - obsMagStdGO[goodRefObsGO]) EGrayObsGRO = (refMag[objRefIDIndex[obsObjIDIndex[goodObs[goodRefObsGO]]], obsBandIndex[goodObs[goodRefObsGO]]] - obsMagObsGO[goodRefObsGO]) mjdGRO = self.fgcmPars.expMJD[obsExpIndexGO[goodRefObsGO]] minMjd = mjdGRO.min() - 5.0 maxMjd = mjdGRO.max() + 5.0 mjdGRO -= minMjd # And get a human-readable time out t = Time(minMjd, format='mjd') t.format = 'datetime' startString = '%04d-%02d-%02d' % (t.value.year, t.value.month, t.value.day) st = np.argsort(EGrayGRO) xMin = 0 xMax = maxMjd - minMjd yMin = EGrayGRO[st[int(0.001 * st.size)]]*1000.0 yMax = EGrayGRO[st[int(0.999 * st.size)]]*1000.0 st = np.argsort(EGrayObsGRO) yMinObs = EGrayObsGRO[st[int(0.001 * st.size)]]*1000.0 yMaxObs = EGrayObsGRO[st[int(0.999 * st.size)]]*1000.0 # which wash dates are within the range... washInRange, = np.where((self.fgcmPars.washMJDs >= minMjd) & (self.fgcmPars.washMJDs <= maxMjd)) for i, band in enumerate(self.fgcmPars.bands): if not self.fgcmPars.hasExposuresInBand[i]: continue use, = np.where(obsBandIndex[goodObs[goodRefObsGO]] == i) if use.size < 100: self.fgcmLog.info("Not enough good reference star information in %s band to make QE sys plots." % (band)) continue fig = plt.figure(1, figsize=(8, 6)) ax = fig.add_subplot(111) ax.hexbin(mjdGRO[use], EGrayGRO[use]*1000.0, bins='log', extent=[xMin, xMax, yMin, yMax]) for washIndex in washInRange: ax.plot([self.fgcmPars.washMJDs[washIndex] - minMjd, self.fgcmPars.washMJDs[washIndex] - minMjd], [yMin, yMax], 'r--', linewidth=2) ax.set_title('%s band' % (band)) ax.set_xlabel('Days since %s (%.0f)' % (startString, minMjd), fontsize=14) ax.set_ylabel('m_ref - m_std (mmag)', fontsize=14) fig.savefig('%s/%s_qesys_refstars-std_%s_%s.png' % (self.plotPath, self.outfileBaseWithCycle, name, band)) plt.close(fig) fig = plt.figure(1, figsize=(8, 6)) ax = fig.add_subplot(111) ax.hexbin(mjdGRO[use], EGrayObsGRO[use]*1000.0, bins='log', extent=[xMin, xMax, yMinObs, yMaxObs]) for washIndex in washInRange: ax.plot([self.fgcmPars.washMJDs[washIndex] - minMjd, self.fgcmPars.washMJDs[washIndex] - minMjd], [yMinObs, yMaxObs], 'r--', linewidth=2) ax.set_title('%s band' % (band)) ax.set_xlabel('Days since %s (%.0f)' % (startString, minMjd), fontsize=14) ax.set_ylabel('m_ref - m_obs (mmag)', fontsize=14) fig.savefig('%s/%s_qesys_refstars-obs_%s_%s.png' % (self.plotPath, self.outfileBaseWithCycle, name, band)) plt.close(fig)
[ "numpy.abs", "numpy.unique", "numpy.where", "numpy.max", "numpy.argsort", "astropy.time.Time", "matplotlib.pyplot.figure", "builtins.range", "matplotlib.pyplot.close", "numpy.zeros", "numpy.append", "numpy.min", "numpy.sum", "matplotlib.pyplot.set_cmap", "numpy.zeros_like", "esutil.sta...
[((2206, 2341), 'numpy.where', 'np.where', (['((obsMagADUModelErr[goodObs] < self.ccdGrayMaxStarErr) & (obsMagADUModelErr\n [goodObs] > 0.0) & (obsMagStd[goodObs] < 90.0))'], {}), '((obsMagADUModelErr[goodObs] < self.ccdGrayMaxStarErr) & (\n obsMagADUModelErr[goodObs] > 0.0) & (obsMagStd[goodObs] < 90.0))\n', (2214, 2341), True, 'import numpy as np\n'), ((3043, 3128), 'esutil.stat.histogram', 'esutil.stat.histogram', (['self.fgcmPars.expWashIndex[obsExpIndexGO]'], {'rev': '(True)', 'min': '(0)'}), '(self.fgcmPars.expWashIndex[obsExpIndexGO], rev=True,\n min=0)\n', (3064, 3128), False, 'import esutil\n'), ((3148, 3167), 'numpy.where', 'np.where', (['(washH > 0)'], {}), '(washH > 0)\n', (3156, 3167), True, 'import numpy as np\n'), ((10837, 10860), 'matplotlib.pyplot.set_cmap', 'plt.set_cmap', (['"""viridis"""'], {}), "('viridis')\n", (10849, 10860), True, 'import matplotlib.pyplot as plt\n'), ((12078, 12130), 'numpy.where', 'np.where', (['(objRefIDIndex[obsObjIDIndex[goodObs]] >= 0)'], {}), '(objRefIDIndex[obsObjIDIndex[goodObs]] >= 0)\n', (12086, 12130), True, 'import numpy as np\n'), ((12298, 12467), 'numpy.where', 'np.where', (['((obsMagStd[goodObs[goodRefObsGO]] < 90.0) & (refMag[objRefIDIndex[\n obsObjIDIndex[goodObs[goodRefObsGO]]], obsBandIndex[goodObs[\n goodRefObsGO]]] < 90.0))'], {}), '((obsMagStd[goodObs[goodRefObsGO]] < 90.0) & (refMag[objRefIDIndex[\n obsObjIDIndex[goodObs[goodRefObsGO]]], obsBandIndex[goodObs[\n goodRefObsGO]]] < 90.0))\n', (12306, 12467), True, 'import numpy as np\n'), ((13327, 13353), 'astropy.time.Time', 'Time', (['minMjd'], {'format': '"""mjd"""'}), "(minMjd, format='mjd')\n", (13331, 13353), False, 'from astropy.time import Time\n'), ((13482, 13502), 'numpy.argsort', 'np.argsort', (['EGrayGRO'], {}), '(EGrayGRO)\n', (13492, 13502), True, 'import numpy as np\n'), ((13680, 13703), 'numpy.argsort', 'np.argsort', (['EGrayObsGRO'], {}), '(EGrayObsGRO)\n', (13690, 13703), True, 'import numpy as np\n'), ((13905, 13990), 'numpy.where', 'np.where', (['((self.fgcmPars.washMJDs >= minMjd) & (self.fgcmPars.washMJDs <= maxMjd))'], {}), '((self.fgcmPars.washMJDs >= minMjd) & (self.fgcmPars.washMJDs <=\n maxMjd))\n', (13913, 13990), True, 'import numpy as np\n'), ((3376, 3442), 'esutil.stat.histogram', 'esutil.stat.histogram', (['obsBandIndex[goodObs[i1a]]'], {'rev': '(True)', 'min': '(0)'}), '(obsBandIndex[goodObs[i1a]], rev=True, min=0)\n', (3397, 3442), False, 'import esutil\n'), ((3470, 3489), 'numpy.where', 'np.where', (['(bandH > 0)'], {}), '(bandH > 0)\n', (3478, 3489), True, 'import numpy as np\n'), ((8056, 8085), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(8, 6)'}), '(1, figsize=(8, 6))\n', (8066, 8085), True, 'import matplotlib.pyplot as plt\n'), ((8254, 8289), 'builtins.range', 'range', (['self.fgcmPars.nWashIntervals'], {}), '(self.fgcmPars.nWashIntervals)\n', (8259, 8289), False, 'from builtins import range\n'), ((10002, 10037), 'builtins.range', 'range', (['self.fgcmPars.nWashIntervals'], {}), '(self.fgcmPars.nWashIntervals)\n', (10007, 10037), False, 'from builtins import range\n'), ((10404, 10418), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (10413, 10418), True, 'import matplotlib.pyplot as plt\n'), ((14176, 14226), 'numpy.where', 'np.where', (['(obsBandIndex[goodObs[goodRefObsGO]] == i)'], {}), '(obsBandIndex[goodObs[goodRefObsGO]] == i)\n', (14184, 14226), True, 'import numpy as np\n'), ((14424, 14453), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(8, 6)'}), '(1, figsize=(8, 6))\n', (14434, 14453), True, 'import matplotlib.pyplot as plt\n'), ((15242, 15256), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (15251, 15256), True, 'import matplotlib.pyplot as plt\n'), ((15276, 15305), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(8, 6)'}), '(1, figsize=(8, 6))\n', (15286, 15305), True, 'import matplotlib.pyplot as plt\n'), ((16109, 16123), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (16118, 16123), True, 'import matplotlib.pyplot as plt\n'), ((4210, 4229), 'numpy.argsort', 'np.argsort', (['thisMjd'], {}), '(thisMjd)\n', (4220, 4229), True, 'import numpy as np\n'), ((4256, 4283), 'numpy.zeros', 'np.zeros', (['(maxID - minID + 1)'], {}), '(maxID - minID + 1)\n', (4264, 4283), True, 'import numpy as np\n'), ((4326, 4377), 'numpy.unique', 'np.unique', (['(thisObjID[st] - minID)'], {'return_index': '(True)'}), '(thisObjID[st] - minID, return_index=True)\n', (4335, 4377), True, 'import numpy as np\n'), ((4468, 4507), 'numpy.zeros_like', 'np.zeros_like', (['minMjd'], {'dtype': 'np.float32'}), '(minMjd, dtype=np.float32)\n', (4481, 4507), True, 'import numpy as np\n'), ((4604, 4627), 'numpy.zeros_like', 'np.zeros_like', (['firstMag'], {}), '(firstMag)\n', (4617, 4627), True, 'import numpy as np\n'), ((4932, 5029), 'numpy.where', 'np.where', (['((deltaT > self.instrumentSlopeMinDeltaT) & (deltaMagErr2 < self.\n ccdGrayMaxStarErr))'], {}), '((deltaT > self.instrumentSlopeMinDeltaT) & (deltaMagErr2 < self.\n ccdGrayMaxStarErr))\n', (4940, 5029), True, 'import numpy as np\n'), ((8007, 8035), 'numpy.min', 'np.min', (['self.fgcmPars.expMJD'], {}), '(self.fgcmPars.expMJD)\n', (8013, 8035), True, 'import numpy as np\n'), ((8314, 8355), 'numpy.where', 'np.where', (['(self.fgcmPars.expWashIndex == i)'], {}), '(self.fgcmPars.expWashIndex == i)\n', (8322, 8355), True, 'import numpy as np\n'), ((8519, 8552), 'numpy.min', 'np.min', (['self.fgcmPars.expMJD[use]'], {}), '(self.fgcmPars.expMJD[use])\n', (8525, 8552), True, 'import numpy as np\n'), ((8554, 8587), 'numpy.max', 'np.max', (['self.fgcmPars.expMJD[use]'], {}), '(self.fgcmPars.expMJD[use])\n', (8560, 8587), True, 'import numpy as np\n'), ((8724, 8751), 'builtins.range', 'range', (['self.fgcmPars.nBands'], {}), '(self.fgcmPars.nBands)\n', (8729, 8751), False, 'from builtins import range\n'), ((5766, 5794), 'numpy.append', 'np.append', (['deltaTAll', 'deltaT'], {}), '(deltaTAll, deltaT)\n', (5775, 5794), True, 'import numpy as np\n'), ((5833, 5865), 'numpy.append', 'np.append', (['deltaMagAll', 'deltaMag'], {}), '(deltaMagAll, deltaMag)\n', (5842, 5865), True, 'import numpy as np\n'), ((5908, 5948), 'numpy.append', 'np.append', (['deltaMagErr2All', 'deltaMagErr2'], {}), '(deltaMagErr2All, deltaMagErr2)\n', (5917, 5948), True, 'import numpy as np\n'), ((7392, 7409), 'numpy.abs', 'np.abs', (['deltaTAll'], {}), '(deltaTAll)\n', (7398, 7409), True, 'import numpy as np\n'), ((7496, 7522), 'numpy.sum', 'np.sum', (['(1.0 / slopeErr2All)'], {}), '(1.0 / slopeErr2All)\n', (7502, 7522), True, 'import numpy as np\n'), ((7587, 7613), 'numpy.sum', 'np.sum', (['(1.0 / slopeErr2All)'], {}), '(1.0 / slopeErr2All)\n', (7593, 7613), True, 'import numpy as np\n'), ((6409, 6423), 'numpy.abs', 'np.abs', (['deltaT'], {}), '(deltaT)\n', (6415, 6423), True, 'import numpy as np\n'), ((6505, 6528), 'numpy.sum', 'np.sum', (['(1.0 / slopeErr2)'], {}), '(1.0 / slopeErr2)\n', (6511, 6528), True, 'import numpy as np\n'), ((6594, 6617), 'numpy.sum', 'np.sum', (['(1.0 / slopeErr2)'], {}), '(1.0 / slopeErr2)\n', (6600, 6617), True, 'import numpy as np\n'), ((7462, 7493), 'numpy.sum', 'np.sum', (['(slopeAll / slopeErr2All)'], {}), '(slopeAll / slopeErr2All)\n', (7468, 7493), True, 'import numpy as np\n'), ((6477, 6502), 'numpy.sum', 'np.sum', (['(slope / slopeErr2)'], {}), '(slope / slopeErr2)\n', (6483, 6502), True, 'import numpy as np\n')]
""" Imbalance metrics. Author: <NAME>, agilescientific.com Licence: Apache 2.0 Copyright 2022 Agile Scientific 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 work is derived from the following reference work: <NAME>, <NAME>, and <NAME> Measuring the Class-imbalance Extent of Multi-class Problems Pattern Recognition Letters 98 (2017) https://doi.org/10.1016/j.patrec.2017.08.002 """ from collections import Counter import numpy as np from .target import * from .utils import * def empirical_distribution(a): """ Compute zeta and e. Equation 5 in Ortigosa-Hernandez et al. (2017). Args: a (array): A list of class labels. Returns: tuple: (zeta, e). """ c = Counter(a) ζ = np.array([v / sum(c.values()) for v in c.values()]) e = np.array([1 / len(c) for _ in c.values()]) return ζ, e def imbalance_ratio(a): """ Compute the IR. Equation 6 in Ortigosa-Hernandez et al. (2017). Args: a (array): A list of class labels. Returns: float: The imbalance ratio. """ ζ, _ = empirical_distribution(a) return max(ζ) / min(ζ) def major_minor(a): """ Returns the number of majority and minority classes. Args: a (array): A list of class labels. Returns: tuple: (maj, min), the number of majority and minority classes. Example: >>> major_minor([1, 1, 2, 2, 3, 3, 3]) (1, 2) """ ζ, e = empirical_distribution(a) return sum(ζ >= e), sum(ζ < e) def divergence(method='hellinger'): """ Compute the divergence between two discrete probability distributions. `method` can be a string from: - hellinger: Recommended. - euclidean: Not recommended. - manhattan: Recommended. - kl: Not recommended. - tv: Recommended. If `method` is a function, this function just hands it back. Args: ζ (array): The actual distribution. e (array): The expected distribution. method (str): The method to use. Returns: function: A divergence function. Reference: Ortigosa-Hernandez et al. (2017) """ functions = { 'hellinger': lambda x, y: np.sqrt(np.sum((np.sqrt(x) - np.sqrt(y))**2)) / np.sqrt(2), 'euclidean': lambda x, y: np.sqrt(np.sum((x - y)**2)), 'manhattan': lambda x, y: np.sum(np.abs(x - y)), 'kl': lambda x, y: np.sum(x * np.log((x + 1e-12) / y)), # Kullback-Leibler. 'tv': lambda x, y: np.sum(np.abs(x - y)) / 2, # Total variation. } return functions.get(method, method) def furthest_distribution(a): """ Compute the IR. Equation 6 in Ortigosa-Hernandez et al. (2017). Args: a (array): A list of class labels. Returns: array: The furthest distribution. Example: >>> furthest_distribution([3,0,0,1,2,3,2,3,2,3,1,1,2,3,3,4,3,4,3,4,]) array([0.8, 0. , 0. , 0.2, 0. ]) """ ζ, e = empirical_distribution(a) # Construct the vector according to Eq 9. i = [ei if ζi >= ei else 0 for ζi, ei in zip(ζ, e)] # Arbitrarily increase one of the non-zero probs to sum to 1. i[np.argmax(i)] += 1 - sum(i) return np.array(i) def imbalance_degree(a, method='manhattan'): r""" Compute IR according to Eq 8 in Ortigosa-Hernandez et al. (2017). .. math:: \mathrm{ID}(\zeta) = \frac{d_\mathrm{\Delta}(\mathbf{\zeta}, \mathbf{e})} {d_\mathrm{\Delta}(\mathbf{\iota}_m, \mathbf{e})} + (m - 1) `method` can be a string from: - 'manhattan': Manhattan distance or L1 norm - 'euclidean': Euclidean distance or L2 norm - 'hellinger': Hellinger distance - 'tv': total variation distance - 'kl': Kullback-Leibner divergence It can also be a function returning a divergence. Args: a (array): A list of class labels. method (str or function): The method to use. Returns: float: The imbalance degree. Examples: >>> ID = imbalance_degree(generate_data([288, 49, 288]), 'tv') >>> round(ID, 2) 0.76 >>> ID = imbalance_degree(generate_data([629, 333, 511]), 'euclidean') >>> round(ID, 2) 0.3 >>> ID = imbalance_degree(generate_data([2, 81, 61, 4]), 'hellinger') >>> round(ID, 2) 1.73 >>> ID = imbalance_degree(generate_data([2, 81, 61, 4]), 'kl') >>> round(ID, 2) 1.65 """ ζ, e = empirical_distribution(a) m = sum(ζ < e) i = furthest_distribution(a) div = divergence(method) return (div(ζ, e) / div(i, e)) + (m - 1) def class_imbalance(a): """ Binary classification: imbalance ratio (number of expected majority class samples to number of expected minority samples). Multiclass classifications: imbalance degree metric, per Ortigosa-Hernandez et al. (2017). Args: a (array): A list of class labels. Returns: float: The imbalance ratio (binary tasks) or imbalance degree (multiclass tasks). Examples: >>> class_imbalance([0, 0, 0, 1, 1, 1, 1, 1, 1]) 2.0 >>> class_imbalance([0, 0, 0, 1, 1, 1, 1, 1, 1, 2]) 1.4 """ if is_binary(a): return imbalance_ratio(a) elif is_multiclass(a): return imbalance_degree(a) else: return None def minority_classes(a): """ Get the minority classes. Args: a (array): A list of class labels. Returns: array: The minority classes. Example: >>> minority_classes([1, 2, 2, 2, 3, 3, 3, 3, 4, 4]) array([1, 4]) """ a = np.asarray(a) ζ, e = empirical_distribution(a) classes = sorted_unique(a) return classes[ζ < e]
[ "numpy.abs", "numpy.sqrt", "numpy.log", "numpy.asarray", "numpy.argmax", "collections.Counter", "numpy.array", "numpy.sum" ]
[((1197, 1207), 'collections.Counter', 'Counter', (['a'], {}), '(a)\n', (1204, 1207), False, 'from collections import Counter\n'), ((3686, 3697), 'numpy.array', 'np.array', (['i'], {}), '(i)\n', (3694, 3697), True, 'import numpy as np\n'), ((6128, 6141), 'numpy.asarray', 'np.asarray', (['a'], {}), '(a)\n', (6138, 6141), True, 'import numpy as np\n'), ((3647, 3659), 'numpy.argmax', 'np.argmax', (['i'], {}), '(i)\n', (3656, 3659), True, 'import numpy as np\n'), ((2739, 2749), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (2746, 2749), True, 'import numpy as np\n'), ((2793, 2813), 'numpy.sum', 'np.sum', (['((x - y) ** 2)'], {}), '((x - y) ** 2)\n', (2799, 2813), True, 'import numpy as np\n'), ((2855, 2868), 'numpy.abs', 'np.abs', (['(x - y)'], {}), '(x - y)\n', (2861, 2868), True, 'import numpy as np\n'), ((2909, 2932), 'numpy.log', 'np.log', (['((x + 1e-12) / y)'], {}), '((x + 1e-12) / y)\n', (2915, 2932), True, 'import numpy as np\n'), ((2990, 3003), 'numpy.abs', 'np.abs', (['(x - y)'], {}), '(x - y)\n', (2996, 3003), True, 'import numpy as np\n'), ((2707, 2717), 'numpy.sqrt', 'np.sqrt', (['x'], {}), '(x)\n', (2714, 2717), True, 'import numpy as np\n'), ((2720, 2730), 'numpy.sqrt', 'np.sqrt', (['y'], {}), '(y)\n', (2727, 2730), True, 'import numpy as np\n')]
import pytest import numpy as np from pyckmeans.io import NucleotideAlignment from pyckmeans.distance.c_interop import \ p_distance,\ jc_distance,\ k2p_distance @pytest.fixture(scope='session') def prepare_alignments(): aln_0 = NucleotideAlignment( ['s0', 's1', 's2', 's3'], np.array([ ['A', 'C', 'T', 'G', 'C', 'C', 'T', 'A', 'G', 'A'], ['T', 'C', '-', 'G', 'C', 'C', 'T', 'T', 'G', 'A'], ['A', 'G', 'T', 'G', 'C', 'C', 'T', 'A', 'G', 'A'], ['A', 'C', 'T', 'A', 'A', 'A', 'T', 'A', 'G', 'A'], ]) ) p_d_0_pd = np.array([ [0.0000000, 0.2222222, 0.1000000, 0.3000000], [0.2222222, 0.0000000, 0.3333333, 0.5555556], [0.1000000, 0.3333333, 0.0000000, 0.4000000], [0.3000000, 0.5555556, 0.4000000, 0.0000000] ]) p_d_0_cd = np.array([ [0.0000000, 0.2222222, 0.1111111, 0.3333333], [0.2222222, 0.0000000, 0.3333333, 0.5555556], [0.1111111, 0.3333333, 0.0000000, 0.4444444], [0.3333333, 0.5555556, 0.4444444, 0.0000000] ]) jc_d_0_pd = np.array([ [0.0000000, 0.2635484, 0.1073256, 0.3831192], [0.2635484, 0.0000000, 0.4408400, 1.0124450], [0.1073256, 0.4408400, 0.0000000, 0.5716050], [0.3831192, 1.0124450, 0.5716050, 0.0000000] ]) jc_d_0_cd = np.array([ [0.0000000, 0.2635484, 0.1202570, 0.4408400], [0.2635484, 0.0000000, 0.4408400, 1.0124450], [0.1202570, 0.4408400, 0.0000000, 0.6734562], [0.4408400, 1.0124450, 0.6734562, 0.0000000] ]) k2p_d_0_pd = np.array([ [0.0000000, 0.2726039, 0.1084661, 0.3831192], [0.2726039, 0.0000000, 0.4773856, 1.0986123], [0.1084661, 0.4773856, 0.0000000, 0.5756463], [0.3831192, 1.0986123, 0.5756463, 0.0000000] ]) k2p_d_0_cd = np.array([ [0.0000000,0.2726039,0.1217201,0.4408400], [0.2726039,0.0000000,0.4773856,1.0986123], [0.1217201,0.4773856,0.0000000,0.6801182], [0.4408400,1.0986123,0.6801182,0.0000000], ]) return ( ( aln_0, { 'p_pd': p_d_0_pd, 'p_cd': p_d_0_cd, 'jc_pd': jc_d_0_pd, 'jc_cd': jc_d_0_cd, 'k2p_pd': k2p_d_0_pd, 'k2p_cd': k2p_d_0_cd, } ), ) def test_p_distance(prepare_alignments): eps = 0.001 aln_0, d_expected_0 = prepare_alignments[0] p_d_0_pd_expected = d_expected_0['p_pd'] p_d_0_cd_expected = d_expected_0['p_cd'] print(aln_0.sequences) p_d_0_pd = p_distance(aln_0.sequences, True) print('p_d_0_pd:', p_d_0_pd) assert np.max(np.abs(p_d_0_pd - p_d_0_pd_expected)) < eps p_d_0_cd = p_distance(aln_0.sequences, False) print('p_d_0_cd:', p_d_0_cd) assert np.max(np.abs(p_d_0_cd - p_d_0_cd_expected)) < eps def test_jc_distance(prepare_alignments): eps = 0.001 aln_0, d_expected_0 = prepare_alignments[0] jc_d_0_pd_expected = d_expected_0['jc_pd'] jc_d_0_cd_expected = d_expected_0['jc_cd'] print(aln_0.sequences) jc_d_0_pd = jc_distance(aln_0.sequences, True) print('jc_d_0_pd:', jc_d_0_pd) assert np.max(np.abs(jc_d_0_pd - jc_d_0_pd_expected)) < eps jc_d_0_cd = jc_distance(aln_0.sequences, False) print('jc_d_0_cd:', jc_d_0_cd) assert np.max(np.abs(jc_d_0_cd - jc_d_0_cd_expected)) < eps def test_k2p_distance(prepare_alignments): eps = 0.001 aln_0, d_expected_0 = prepare_alignments[0] k2p_d_0_pd_expected = d_expected_0['k2p_pd'] k2p_d_0_cd_expected = d_expected_0['k2p_cd'] print(aln_0.sequences) k2p_d_0_pd = k2p_distance(aln_0.sequences, True) print('k2p_d_0_pd:', k2p_d_0_pd) assert np.max(np.abs(k2p_d_0_pd - k2p_d_0_pd_expected)) < eps k2p_d_0_cd = k2p_distance(aln_0.sequences, False) print('k2p_d_0_cd:', k2p_d_0_cd) assert np.max(np.abs(k2p_d_0_cd - k2p_d_0_cd_expected)) < eps
[ "numpy.abs", "pyckmeans.distance.c_interop.jc_distance", "numpy.array", "pyckmeans.distance.c_interop.k2p_distance", "pyckmeans.distance.c_interop.p_distance", "pytest.fixture" ]
[((177, 208), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (191, 208), False, 'import pytest\n'), ((609, 748), 'numpy.array', 'np.array', (['[[0.0, 0.2222222, 0.1, 0.3], [0.2222222, 0.0, 0.3333333, 0.5555556], [0.1, \n 0.3333333, 0.0, 0.4], [0.3, 0.5555556, 0.4, 0.0]]'], {}), '([[0.0, 0.2222222, 0.1, 0.3], [0.2222222, 0.0, 0.3333333, 0.5555556\n ], [0.1, 0.3333333, 0.0, 0.4], [0.3, 0.5555556, 0.4, 0.0]])\n', (617, 748), True, 'import numpy as np\n'), ((857, 1037), 'numpy.array', 'np.array', (['[[0.0, 0.2222222, 0.1111111, 0.3333333], [0.2222222, 0.0, 0.3333333, \n 0.5555556], [0.1111111, 0.3333333, 0.0, 0.4444444], [0.3333333, \n 0.5555556, 0.4444444, 0.0]]'], {}), '([[0.0, 0.2222222, 0.1111111, 0.3333333], [0.2222222, 0.0, \n 0.3333333, 0.5555556], [0.1111111, 0.3333333, 0.0, 0.4444444], [\n 0.3333333, 0.5555556, 0.4444444, 0.0]])\n', (865, 1037), True, 'import numpy as np\n'), ((1106, 1277), 'numpy.array', 'np.array', (['[[0.0, 0.2635484, 0.1073256, 0.3831192], [0.2635484, 0.0, 0.44084, 1.012445\n ], [0.1073256, 0.44084, 0.0, 0.571605], [0.3831192, 1.012445, 0.571605,\n 0.0]]'], {}), '([[0.0, 0.2635484, 0.1073256, 0.3831192], [0.2635484, 0.0, 0.44084,\n 1.012445], [0.1073256, 0.44084, 0.0, 0.571605], [0.3831192, 1.012445, \n 0.571605, 0.0]])\n', (1114, 1277), True, 'import numpy as np\n'), ((1355, 1523), 'numpy.array', 'np.array', (['[[0.0, 0.2635484, 0.120257, 0.44084], [0.2635484, 0.0, 0.44084, 1.012445],\n [0.120257, 0.44084, 0.0, 0.6734562], [0.44084, 1.012445, 0.6734562, 0.0]]'], {}), '([[0.0, 0.2635484, 0.120257, 0.44084], [0.2635484, 0.0, 0.44084, \n 1.012445], [0.120257, 0.44084, 0.0, 0.6734562], [0.44084, 1.012445, \n 0.6734562, 0.0]])\n', (1363, 1523), True, 'import numpy as np\n'), ((1605, 1785), 'numpy.array', 'np.array', (['[[0.0, 0.2726039, 0.1084661, 0.3831192], [0.2726039, 0.0, 0.4773856, \n 1.0986123], [0.1084661, 0.4773856, 0.0, 0.5756463], [0.3831192, \n 1.0986123, 0.5756463, 0.0]]'], {}), '([[0.0, 0.2726039, 0.1084661, 0.3831192], [0.2726039, 0.0, \n 0.4773856, 1.0986123], [0.1084661, 0.4773856, 0.0, 0.5756463], [\n 0.3831192, 1.0986123, 0.5756463, 0.0]])\n', (1613, 1785), True, 'import numpy as np\n'), ((1855, 2029), 'numpy.array', 'np.array', (['[[0.0, 0.2726039, 0.1217201, 0.44084], [0.2726039, 0.0, 0.4773856, \n 1.0986123], [0.1217201, 0.4773856, 0.0, 0.6801182], [0.44084, 1.0986123,\n 0.6801182, 0.0]]'], {}), '([[0.0, 0.2726039, 0.1217201, 0.44084], [0.2726039, 0.0, 0.4773856,\n 1.0986123], [0.1217201, 0.4773856, 0.0, 0.6801182], [0.44084, 1.0986123,\n 0.6801182, 0.0]])\n', (1863, 2029), True, 'import numpy as np\n'), ((2575, 2608), 'pyckmeans.distance.c_interop.p_distance', 'p_distance', (['aln_0.sequences', '(True)'], {}), '(aln_0.sequences, True)\n', (2585, 2608), False, 'from pyckmeans.distance.c_interop import p_distance, jc_distance, k2p_distance\n'), ((2719, 2753), 'pyckmeans.distance.c_interop.p_distance', 'p_distance', (['aln_0.sequences', '(False)'], {}), '(aln_0.sequences, False)\n', (2729, 2753), False, 'from pyckmeans.distance.c_interop import p_distance, jc_distance, k2p_distance\n'), ((3096, 3130), 'pyckmeans.distance.c_interop.jc_distance', 'jc_distance', (['aln_0.sequences', '(True)'], {}), '(aln_0.sequences, True)\n', (3107, 3130), False, 'from pyckmeans.distance.c_interop import p_distance, jc_distance, k2p_distance\n'), ((3246, 3281), 'pyckmeans.distance.c_interop.jc_distance', 'jc_distance', (['aln_0.sequences', '(False)'], {}), '(aln_0.sequences, False)\n', (3257, 3281), False, 'from pyckmeans.distance.c_interop import p_distance, jc_distance, k2p_distance\n'), ((3634, 3669), 'pyckmeans.distance.c_interop.k2p_distance', 'k2p_distance', (['aln_0.sequences', '(True)'], {}), '(aln_0.sequences, True)\n', (3646, 3669), False, 'from pyckmeans.distance.c_interop import p_distance, jc_distance, k2p_distance\n'), ((3790, 3826), 'pyckmeans.distance.c_interop.k2p_distance', 'k2p_distance', (['aln_0.sequences', '(False)'], {}), '(aln_0.sequences, False)\n', (3802, 3826), False, 'from pyckmeans.distance.c_interop import p_distance, jc_distance, k2p_distance\n'), ((310, 536), 'numpy.array', 'np.array', (["[['A', 'C', 'T', 'G', 'C', 'C', 'T', 'A', 'G', 'A'], ['T', 'C', '-', 'G',\n 'C', 'C', 'T', 'T', 'G', 'A'], ['A', 'G', 'T', 'G', 'C', 'C', 'T', 'A',\n 'G', 'A'], ['A', 'C', 'T', 'A', 'A', 'A', 'T', 'A', 'G', 'A']]"], {}), "([['A', 'C', 'T', 'G', 'C', 'C', 'T', 'A', 'G', 'A'], ['T', 'C',\n '-', 'G', 'C', 'C', 'T', 'T', 'G', 'A'], ['A', 'G', 'T', 'G', 'C', 'C',\n 'T', 'A', 'G', 'A'], ['A', 'C', 'T', 'A', 'A', 'A', 'T', 'A', 'G', 'A']])\n", (318, 536), True, 'import numpy as np\n'), ((2660, 2696), 'numpy.abs', 'np.abs', (['(p_d_0_pd - p_d_0_pd_expected)'], {}), '(p_d_0_pd - p_d_0_pd_expected)\n', (2666, 2696), True, 'import numpy as np\n'), ((2805, 2841), 'numpy.abs', 'np.abs', (['(p_d_0_cd - p_d_0_cd_expected)'], {}), '(p_d_0_cd - p_d_0_cd_expected)\n', (2811, 2841), True, 'import numpy as np\n'), ((3184, 3222), 'numpy.abs', 'np.abs', (['(jc_d_0_pd - jc_d_0_pd_expected)'], {}), '(jc_d_0_pd - jc_d_0_pd_expected)\n', (3190, 3222), True, 'import numpy as np\n'), ((3335, 3373), 'numpy.abs', 'np.abs', (['(jc_d_0_cd - jc_d_0_cd_expected)'], {}), '(jc_d_0_cd - jc_d_0_cd_expected)\n', (3341, 3373), True, 'import numpy as np\n'), ((3725, 3765), 'numpy.abs', 'np.abs', (['(k2p_d_0_pd - k2p_d_0_pd_expected)'], {}), '(k2p_d_0_pd - k2p_d_0_pd_expected)\n', (3731, 3765), True, 'import numpy as np\n'), ((3882, 3922), 'numpy.abs', 'np.abs', (['(k2p_d_0_cd - k2p_d_0_cd_expected)'], {}), '(k2p_d_0_cd - k2p_d_0_cd_expected)\n', (3888, 3922), True, 'import numpy as np\n')]
""" @author: <NAME> @file: preprocess_sst_dms.py @time: 2021/5/11 10:17 @description: """ """ DMS: direct multi-step, don't need to predict all predictors """ import os import json import random import numpy as np import tensorflow as tf import netCDF4 as nc from sklearn.preprocessing import StandardScaler, MinMaxScaler, Normalizer from sklearn.model_selection import train_test_split from progress.bar import PixelBar from hparams import Hparams hparams = Hparams() parser = hparams.parser hp = parser.parse_args() # ---------- Helpers ---------- def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _bytes_feature(value): if isinstance(value, type(tf.constant(0))): value = value.numpy() return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _float_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) # ---------- Prepare Data ---------- def parse_npz_and_nc_data(): height = hp.height width = hp.width # train_scope = range(0, 114*12) # 1870.01-1983.12 sst = np.load(f"{hp.multivar}/SODA/npz_data/sst.npz")['sst'] t300 = np.load(f"{hp.multivar}/SODA/npz_data/t300.npz")['t300'] taux = np.load(f"{hp.multivar}/SODA/npz_data/taux.npz")['taux'] tauy = np.load(f"{hp.multivar}/SODA/npz_data/tauy.npz")['tauy'] scaler = MinMaxScaler() # scaler = StandardScaler() # scaler = Normalizer() sst = np.reshape(scaler.fit_transform(np.reshape(sst, (-1, height * width))), (-1, height, width)) t300 = np.reshape(scaler.fit_transform(np.reshape(t300, (-1, height * width))), (-1, height, width)) taux = np.reshape(scaler.fit_transform(np.reshape(taux, (-1, height * width))), (-1, height, width)) tauy = np.reshape(scaler.fit_transform(np.reshape(tauy, (-1, height * width))), (-1, height, width)) data = [] target = [] for i in range(sst.shape[0] - hp.in_seqlen + 1 - hp.lead_time - hp.out_seqlen): data.append({'sst': sst[i:i + hp.in_seqlen].astype(np.float32), 't300': t300[i:i + hp.in_seqlen].astype(np.float32), 'taux': taux[i:i + hp.in_seqlen].astype(np.float32), 'tauy': tauy[i:i + hp.in_seqlen].astype(np.float32)}) target_start = i + hp.in_seqlen + hp.lead_time target.append({'tauy': tauy[target_start].astype(np.float32)}) train_data, test_data, train_target, test_target = train_test_split(data, target, test_size=hp.train_eval_split, random_state=hp.random_seed) print(len(train_data), len(test_data), len(train_target), len(test_target)) return train_data, test_data, train_target, test_target # ---------- IO ---------- def write_records(data, filename): series = data[0] target = data[1] writer = tf.io.TFRecordWriter(f"{hp.rollingPred}/vw/tfRecords/{filename}") bar = PixelBar(r'Generating', max=len(data), suffix='%(percent)d%%') for s, t in zip(series, target): example = tf.train.Example(features=tf.train.Features(feature={ 'input_sst': _bytes_feature(s['sst'].tobytes()), 'input_t300': _bytes_feature(s['t300'].tobytes()), 'input_taux': _bytes_feature(s['taux'].tobytes()), 'input_tauy': _bytes_feature(s['tauy'].tobytes()), 'output_tauy': _bytes_feature(t['tauy'].tobytes()) })) writer.write(example.SerializeToString()) bar.next() writer.close() bar.finish() # ---------- Go! ---------- if __name__ == "__main__": print("Parsing raw data...") train_data, test_data, train_target, test_target = parse_npz_and_nc_data() print("Writing TF Records to file...") write_records((train_data, train_target), f"train-in{hp.in_seqlen}.tfrecords") write_records((test_data, test_target), f"test-in{hp.in_seqlen}.tfrecords") print("Done!")
[ "numpy.reshape", "sklearn.model_selection.train_test_split", "tensorflow.io.TFRecordWriter", "tensorflow.train.Int64List", "hparams.Hparams", "tensorflow.train.BytesList", "tensorflow.constant", "tensorflow.train.FloatList", "numpy.load", "sklearn.preprocessing.MinMaxScaler" ]
[((462, 471), 'hparams.Hparams', 'Hparams', ([], {}), '()\n', (469, 471), False, 'from hparams import Hparams\n'), ((1392, 1406), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (1404, 1406), False, 'from sklearn.preprocessing import StandardScaler, MinMaxScaler, Normalizer\n'), ((2478, 2573), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data', 'target'], {'test_size': 'hp.train_eval_split', 'random_state': 'hp.random_seed'}), '(data, target, test_size=hp.train_eval_split, random_state=\n hp.random_seed)\n', (2494, 2573), False, 'from sklearn.model_selection import train_test_split\n'), ((2900, 2965), 'tensorflow.io.TFRecordWriter', 'tf.io.TFRecordWriter', (['f"""{hp.rollingPred}/vw/tfRecords/{filename}"""'], {}), "(f'{hp.rollingPred}/vw/tfRecords/{filename}')\n", (2920, 2965), True, 'import tensorflow as tf\n'), ((1119, 1166), 'numpy.load', 'np.load', (['f"""{hp.multivar}/SODA/npz_data/sst.npz"""'], {}), "(f'{hp.multivar}/SODA/npz_data/sst.npz')\n", (1126, 1166), True, 'import numpy as np\n'), ((1185, 1233), 'numpy.load', 'np.load', (['f"""{hp.multivar}/SODA/npz_data/t300.npz"""'], {}), "(f'{hp.multivar}/SODA/npz_data/t300.npz')\n", (1192, 1233), True, 'import numpy as np\n'), ((1253, 1301), 'numpy.load', 'np.load', (['f"""{hp.multivar}/SODA/npz_data/taux.npz"""'], {}), "(f'{hp.multivar}/SODA/npz_data/taux.npz')\n", (1260, 1301), True, 'import numpy as np\n'), ((1321, 1369), 'numpy.load', 'np.load', (['f"""{hp.multivar}/SODA/npz_data/tauy.npz"""'], {}), "(f'{hp.multivar}/SODA/npz_data/tauy.npz')\n", (1328, 1369), True, 'import numpy as np\n'), ((621, 654), 'tensorflow.train.Int64List', 'tf.train.Int64List', ([], {'value': '[value]'}), '(value=[value])\n', (639, 654), True, 'import tensorflow as tf\n'), ((715, 729), 'tensorflow.constant', 'tf.constant', (['(0)'], {}), '(0)\n', (726, 729), True, 'import tensorflow as tf\n'), ((802, 835), 'tensorflow.train.BytesList', 'tf.train.BytesList', ([], {'value': '[value]'}), '(value=[value])\n', (820, 835), True, 'import tensorflow as tf\n'), ((905, 938), 'tensorflow.train.FloatList', 'tf.train.FloatList', ([], {'value': '[value]'}), '(value=[value])\n', (923, 938), True, 'import tensorflow as tf\n'), ((1509, 1546), 'numpy.reshape', 'np.reshape', (['sst', '(-1, height * width)'], {}), '(sst, (-1, height * width))\n', (1519, 1546), True, 'import numpy as np\n'), ((1613, 1651), 'numpy.reshape', 'np.reshape', (['t300', '(-1, height * width)'], {}), '(t300, (-1, height * width))\n', (1623, 1651), True, 'import numpy as np\n'), ((1718, 1756), 'numpy.reshape', 'np.reshape', (['taux', '(-1, height * width)'], {}), '(taux, (-1, height * width))\n', (1728, 1756), True, 'import numpy as np\n'), ((1823, 1861), 'numpy.reshape', 'np.reshape', (['tauy', '(-1, height * width)'], {}), '(tauy, (-1, height * width))\n', (1833, 1861), True, 'import numpy as np\n')]
__author__ = 'DafniAntotsiou' import mujoco_py from numpy import array from copy import deepcopy import numpy as np def GetBodyPosDist(bodyId, refbodyId, m): bodyPos = array([0, 0, 0], dtype='f8') if refbodyId < 0: return bodyPos while bodyId > refbodyId: bodyPos += m.body_pos[bodyId] bodyId = m.body_parentid[bodyId] return bodyPos def GetJointBodyDist(jointId, bodyId, m): jointPos = array([0, 0, 0], dtype='f8') if jointId < 0 or bodyId < 0: return jointPos jointPos += m.jnt_pos[jointId] jointPos += GetBodyPosDist(m.jnt_bodyid[jointId], bodyId, m) return jointPos #Quaternion = [w,x,y,z] def GetBodyRotDist(bodyId, refbodyId, m): bodyRot = array([1, 0, 0, 0], dtype='f8') if refbodyId < 0: return bodyRot while bodyId > refbodyId: currRot = m.body_quat[bodyId] tmp = deepcopy(bodyRot) bodyRot[0] = currRot[0] * tmp[0] - currRot[1] * tmp[1] - currRot[2] * tmp[2] - currRot[3] * tmp[3] bodyRot[1] = currRot[0] * tmp[1] - currRot[1] * tmp[0] - currRot[2] * tmp[3] - currRot[3] * tmp[2] bodyRot[2] = currRot[0] * tmp[2] - currRot[1] * tmp[2] - currRot[2] * tmp[0] - currRot[3] * tmp[1] bodyRot[3] = currRot[0] * tmp[3] - currRot[1] * tmp[3] - currRot[2] * tmp[1] - currRot[3] * tmp[0] bodyId = m.body_parentid[bodyId] bodyRot = bodyRot.conjugate() return bodyRot def GetJointBodyRot(jointId, bodyId, m): jointRot = array([1, 0, 0, 0], dtype='f8') if jointId < 0 or bodyId < 0: return jointRot jointRot = GetBodyRotDist(m.jnt_bodyid[jointId], bodyId, m) return jointRot # class that handles mujoco actuators, joints and mocaps class Actuator(object): def __init__(self, m=None, name=None, mjtype=None, palm_name=None): self.type = mjtype self.default_pos = array([0, 0, 0], dtype='f8') self.default_quat = array([1, 0, 0, 0], dtype='f8') self.quat = None self.id = None self.bodyid = None self.value = None self.name = name self.min = -1000 self.max = 1000 if m and name and mjtype and palm_name: main_id = m.body_name2id(palm_name) if mjtype == 'body': self.id = m.body_name2id(name) self.bodyid = self.id if name.find("mocap") >= 0: self.id = m.body_mocapid[self.id] self.quat = array([1, 0, 0, 0]) self.value = array([0, 0, 0], dtype='f8') self.default_pos = GetBodyPosDist(self.id, main_id, m) self.default_quat = GetBodyRotDist(self.id, main_id, m) elif mjtype == 'joint': self.id = m.joint_name2id(name) self.value = np.float64(0) self.default_pos = GetJointBodyDist(self.id, main_id, m) self.default_quat = GetJointBodyRot(self.id, main_id, m) self.min = self.m.jnt_range[self.id][0] self.max = self.m.jnt_range[self.id][1] self.bodyid = m.jnt_bodyid[self.id] elif mjtype == 'actuator': self.id = m.actuator_name2id(name) self.value = np.float64(0) # assume the actuator name is A_ + joint name idx = name.find("A_") if idx >= 0: j_name = name[idx + 2:] joint_id = m.joint_name2id(j_name) self.bodyid = m.jnt_bodyid[joint_id] self.default_pos = GetJointBodyDist(joint_id, main_id, m) self.default_quat = GetJointBodyRot(joint_id, main_id, m) self.min = m.actuator_ctrlrange[self.id][0] self.max = m.actuator_ctrlrange[self.id][1] def set_value(self, val, safe=False, is_quat=False): if self.type == 'body': if not is_quat: self.value = deepcopy(val) else: self.quat = deepcopy(val) elif safe and (self.type == 'actuator' or self.type == 'joint'): self.value = max(val, self.min) self.value = min(self.value, self.max) else: self.value = deepcopy(val) def get_limits(self): return self.min, self.max def get_value(self, is_quat=False): if not is_quat: return deepcopy(self.value) else: return deepcopy(self.quat) def assign(self, sim): self.set_value(self.value, True) if self.type == 'joint': sim.data.qpos[sim.model.jnt_qposadr[self.id]] = deepcopy(self.value) elif self.type == 'actuator': sim.data.ctrl[self.id] = deepcopy(self.value) elif self.type == 'body': sim.data.mocap_pos[self.id] = deepcopy(self.value) sim.data.mocap_quat[self.id] = self.quat return sim def get_id(self): return self.id def get_pos(self): return deepcopy(self.default_pos) def get_quat(self): return deepcopy(self.default_quat) # deep copy of the value and quat attributes def copy(self): res = Actuator() res.value = np.copy(self.value) res.quat = np.copy(self.quat) res.type = self.type res.default_pos = self.default_pos res.default_quat = self.default_quat res.id = self.id return res def get_val_from_sim(self, sim): if self.type == 'joint': self.value = deepcopy(sim.data.qpos[sim.model.jnt_qposadr[self.id]]) elif self.type == 'actuator': self.value = deepcopy(sim.data.ctrl[self.id]) elif self.type == 'body': self.value = deepcopy(sim.data.mocap_pos[self.id]) self.quat = deepcopy(sim.data.mocap_quat[self.id])
[ "numpy.array", "numpy.copy", "numpy.float64", "copy.deepcopy" ]
[((175, 203), 'numpy.array', 'array', (['[0, 0, 0]'], {'dtype': '"""f8"""'}), "([0, 0, 0], dtype='f8')\n", (180, 203), False, 'from numpy import array\n'), ((439, 467), 'numpy.array', 'array', (['[0, 0, 0]'], {'dtype': '"""f8"""'}), "([0, 0, 0], dtype='f8')\n", (444, 467), False, 'from numpy import array\n'), ((732, 763), 'numpy.array', 'array', (['[1, 0, 0, 0]'], {'dtype': '"""f8"""'}), "([1, 0, 0, 0], dtype='f8')\n", (737, 763), False, 'from numpy import array\n'), ((1497, 1528), 'numpy.array', 'array', (['[1, 0, 0, 0]'], {'dtype': '"""f8"""'}), "([1, 0, 0, 0], dtype='f8')\n", (1502, 1528), False, 'from numpy import array\n'), ((895, 912), 'copy.deepcopy', 'deepcopy', (['bodyRot'], {}), '(bodyRot)\n', (903, 912), False, 'from copy import deepcopy\n'), ((1883, 1911), 'numpy.array', 'array', (['[0, 0, 0]'], {'dtype': '"""f8"""'}), "([0, 0, 0], dtype='f8')\n", (1888, 1911), False, 'from numpy import array\n'), ((1940, 1971), 'numpy.array', 'array', (['[1, 0, 0, 0]'], {'dtype': '"""f8"""'}), "([1, 0, 0, 0], dtype='f8')\n", (1945, 1971), False, 'from numpy import array\n'), ((5043, 5069), 'copy.deepcopy', 'deepcopy', (['self.default_pos'], {}), '(self.default_pos)\n', (5051, 5069), False, 'from copy import deepcopy\n'), ((5110, 5137), 'copy.deepcopy', 'deepcopy', (['self.default_quat'], {}), '(self.default_quat)\n', (5118, 5137), False, 'from copy import deepcopy\n'), ((5253, 5272), 'numpy.copy', 'np.copy', (['self.value'], {}), '(self.value)\n', (5260, 5272), True, 'import numpy as np\n'), ((5292, 5310), 'numpy.copy', 'np.copy', (['self.quat'], {}), '(self.quat)\n', (5299, 5310), True, 'import numpy as np\n'), ((4435, 4455), 'copy.deepcopy', 'deepcopy', (['self.value'], {}), '(self.value)\n', (4443, 4455), False, 'from copy import deepcopy\n'), ((4489, 4508), 'copy.deepcopy', 'deepcopy', (['self.quat'], {}), '(self.quat)\n', (4497, 4508), False, 'from copy import deepcopy\n'), ((4672, 4692), 'copy.deepcopy', 'deepcopy', (['self.value'], {}), '(self.value)\n', (4680, 4692), False, 'from copy import deepcopy\n'), ((5570, 5625), 'copy.deepcopy', 'deepcopy', (['sim.data.qpos[sim.model.jnt_qposadr[self.id]]'], {}), '(sim.data.qpos[sim.model.jnt_qposadr[self.id]])\n', (5578, 5625), False, 'from copy import deepcopy\n'), ((2541, 2569), 'numpy.array', 'array', (['[0, 0, 0]'], {'dtype': '"""f8"""'}), "([0, 0, 0], dtype='f8')\n", (2546, 2569), False, 'from numpy import array\n'), ((3995, 4008), 'copy.deepcopy', 'deepcopy', (['val'], {}), '(val)\n', (4003, 4008), False, 'from copy import deepcopy\n'), ((4055, 4068), 'copy.deepcopy', 'deepcopy', (['val'], {}), '(val)\n', (4063, 4068), False, 'from copy import deepcopy\n'), ((4276, 4289), 'copy.deepcopy', 'deepcopy', (['val'], {}), '(val)\n', (4284, 4289), False, 'from copy import deepcopy\n'), ((4768, 4788), 'copy.deepcopy', 'deepcopy', (['self.value'], {}), '(self.value)\n', (4776, 4788), False, 'from copy import deepcopy\n'), ((5689, 5721), 'copy.deepcopy', 'deepcopy', (['sim.data.ctrl[self.id]'], {}), '(sim.data.ctrl[self.id])\n', (5697, 5721), False, 'from copy import deepcopy\n'), ((2492, 2511), 'numpy.array', 'array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (2497, 2511), False, 'from numpy import array\n'), ((2826, 2839), 'numpy.float64', 'np.float64', (['(0)'], {}), '(0)\n', (2836, 2839), True, 'import numpy as np\n'), ((4865, 4885), 'copy.deepcopy', 'deepcopy', (['self.value'], {}), '(self.value)\n', (4873, 4885), False, 'from copy import deepcopy\n'), ((5781, 5818), 'copy.deepcopy', 'deepcopy', (['sim.data.mocap_pos[self.id]'], {}), '(sim.data.mocap_pos[self.id])\n', (5789, 5818), False, 'from copy import deepcopy\n'), ((5843, 5881), 'copy.deepcopy', 'deepcopy', (['sim.data.mocap_quat[self.id]'], {}), '(sim.data.mocap_quat[self.id])\n', (5851, 5881), False, 'from copy import deepcopy\n'), ((3271, 3284), 'numpy.float64', 'np.float64', (['(0)'], {}), '(0)\n', (3281, 3284), True, 'import numpy as np\n')]
import numpy as np import scipy.integrate as integrate from sklearn.neighbors.kde import KernelDensity from scipy.stats import truncnorm import multiprocessing as mp import itertools import matplotlib.pyplot as plt import warnings import statsmodels.api as sm from statsmodels.distributions.empirical_distribution import ECDF from matplotlib import rc from datetime import datetime warnings.filterwarnings("ignore") #rc('font',**{'family':'serif','serif':['Helvetica']}) #rc('text', usetex=True) #plt.rcParams.update({'font.size': 13}) rx = np.zeros((3,2,2)) operator = 'PBI' class Probability_wrong: """Class for computing the probability of wrong selection of a distribution""" def __init__(self, mean_values=None, stddev_values=None, n_samples=1000,p=None): self.mean_values = mean_values self.stddev_values = stddev_values self.n_samples = n_samples self.f_samples = None self.size_f = np.shape(mean_values)[0] self.num_objectives = np.shape(mean_values)[1] self.pdf_list = {} self.ecdf_list = {} self.pdf_grids = None self.cdf_grids = None self.support_grids = None self.pdf_cdf = None self.rank_prob_wrong = None self.lower_bound = None self.upper_bound = None self.apd_mean_samples = {} self.apd_sigma_samples = {} self.mean_samples = None self.sigma_samples = None self.size_rows = None self.size_cols = None self.p = p self.apd_pdf_list = {} self.apd_ecdf_list = {} self.parallel_list = {} def vect_sample_f(self): for i in range(self.size_f): f_temp = None for j in range(self.num_objectives): #sample = truncnorm.rvs(-1.96, 1.96, loc=self.mean_values[i,j], scale=self.stddev_values[i,j], size=self.n_samples) sample = truncnorm.rvs(-3, 3, loc=self.mean_values[i, j], scale=self.stddev_values[i, j], size=self.n_samples) #sample = np.random.normal(self.mean_values[i,j], self.stddev_values[i,j], self.n_samples) sample = np.reshape(sample, (1,1,self.n_samples)) if f_temp is None: f_temp = sample else: f_temp = np.hstack((f_temp, sample)) if self.f_samples is None: self.f_samples = f_temp else: self.f_samples = np.vstack((self.f_samples, f_temp)) def compute_pdf(self, samples=None, bw=None): if samples is None: samples = self.f_samples self.mean_samples = np.mean(samples, axis=2) self.sigma_samples = np.std(samples, axis=2) self.size_rows = np.shape(samples)[0] self.size_cols = np.shape(samples)[1] self.lower_bound = np.min(samples, axis=2) self.upper_bound = np.max(samples, axis=2) if bw is None: bw = 1.06*self.sigma_samples/np.power(self.n_samples, (1/5)) else: bw = np.ones((self.size_rows,self.size_cols))*bw """ print("Bandwidth:") print(bw) print("Mean:") print(self.mean_samples) print("Sigma:") print(self.sigma_samples) """ for i in range(self.size_rows): pdf_temp = [] ecdf_temp = [] for j in range(self.size_cols): sample_temp = samples[i, j, :] kde = KernelDensity(kernel='gaussian', bandwidth=bw[i, j]).fit(np.reshape(sample_temp, (-1, 1))) pdf_temp.append(kde) #sample_temp = self.pdf_predict(sample, kde) ecdf = ECDF(sample_temp) ecdf_temp.append(ecdf) self.pdf_list[str(i)]=pdf_temp self.ecdf_list[str(i)]=ecdf_temp def pdf_predict(self, x, pdf1, mu_B=None): pdf_vals = None if mu_B is None: pdf_vals = np.exp(pdf1.score_samples(np.reshape(x, (-1, 1)))) else: return np.exp(pdf1.score_samples(np.reshape(mu_B-x, (-1, 1)))) pdf_vals[np.where(x < 0)] = 0 return pdf_vals def find_cdf(self, pdf, mu_B, lb_B, ub_B, mu): pdf1 = pdf #lb_set = mu_B - mu #if lb_set > mu_B - lb_B: # return 0 #elif lb_set < mu_B - ub_B: # return 1 #else: return integrate.quad(self.pdf_predict, mu_B - mu, np.inf, args=(pdf1, mu_B))[0] #return integrate.quadrature(self.pdf_predict, mu_B - mu, mu_B - lb_B, args=(pdf1, mu_B), maxiter=10)[0] #return integrate.quadrature(self.pdf_predict, mu_B - mu, mu_B - lb_B, args=(pdf1, mu_B), maxiter=5)[0] #print("LB_INT:") #print(zz) #print("lb_B") #print(lb_B) #print("ub_B") #print(ub_B) #zz = mu_B-lb_B #print("ADJ_INT:") #print(zz) #xx = integrate.quad(self.pdf_predict, mu_B - mu, ub_B, args=(pdf1, mu_B))[0] #if xx < 0.0001 or xx>0.99: # print(mu_B - mu) # print(mu_B-lb_B) # print(mu_B-ub_B) # print("cdf") # print(xx) #return xx #return integrate.quad(self.pdf_predict, mu_B - mu, np.inf, args=(pdf1, mu_B))[0] def prob_mult(self, x, pdf_A, cdf_B): zz = self.pdf_predict(x, pdf_A) #print(zz) #kk = self.find_cdf(pdf_B, mu_B, lb_B, ub_B, mu=x) kk = cdf_B(x) #print("cdf") #print(kk) return zz * kk def compute_probability_wrong(self, pdf_A, pdf_B, mu_B): prob_wrong = integrate.quad(self.prob_mult2, -np.inf, np.inf, args=(pdf_A, pdf_B, mu_B)) #prob_wrong = integrate.quad(self.prob_mult, self.lower_bound-1, self.upper_bound+1, args=(pdf_A, pdf_B, mu_B)) #print(mu_B) print(prob_wrong[0]) return prob_wrong[0] def find_cdf2(self, pdf, mu_B, mu): return integrate.quad(self.pdf_predict, mu_B - mu, np.inf, args=(pdf, mu_B))[0] def prob_mult2(self, x, pdf_A, pdf_B, mu_B): zz = self.pdf_predict(x, pdf_A) #print(zz) kk = self.find_cdf2(pdf_B, mu_B, mu=x) #print("cdf") #print(kk) return zz * kk def compute_probability_wrong2(self, i, j, k): pdf_A, pdf_B, mu_B = \ self.pdf_list[str(i)][j], self.pdf_list[str(i)][k], self.mean_samples[i][k] prob_wrong = integrate.quad(self.prob_mult, -np.inf, np.inf, args=(pdf_A, pdf_B, mu_B)) print(prob_wrong[0]) return prob_wrong[0] def compute_probability_wrong_fast(self, i, j, k): pdf_A, pdf_B, mu_A, mu_B, sigma_A, sigma_B = \ self.pdf_list[str(i)][j], \ self.pdf_list[str(i)][k], \ self.mean_samples[i][j], \ self.mean_samples[i][k], \ self.sigma_samples[i][j], \ self.sigma_samples[i][k] cdf_B = self.ecdf_list[str(i)][k] lb_B = self.lower_bound[i, k] ub_B = self.upper_bound[i, k] lb_A = mu_A - 2.6 * sigma_A ub_A = mu_A + 2.6 * sigma_A #lb_B = mu_B - 2.6 * sigma_B #ub_B = mu_B + 2.6 * sigma_B #lb_B = mu_B-2*sigma_B #ub_B = mu_B + 2 * sigma_B if k<j: return -1 elif j==k: return 0.5 elif (mu_A+3*sigma_A < mu_B-3*sigma_B) and (mu_A < mu_B): return 0 elif (mu_A-3*sigma_A > mu_B+3*sigma_B) and (mu_A > mu_B): return 1 #else: #lb_B = -np.inf #ub_B = np.inf #print("PDFs:") #print(i) #print(j) #print(k) prob_mult_vect = np.vectorize(self.prob_mult) #prob_wrong = integrate.quad(prob_mult_vect, -np.inf, np.inf, args=(pdf_A, pdf_B, mu_B, lb_B, ub_B)) prob_wrong = integrate.quad(prob_mult_vect, 0, np.inf, args=(pdf_A, cdf_B)) #prob_wrong = integrate.quad(self.prob_mult, 0, 1, args=(pdf_A, pdf_B, mu_B, lb_B, ub_B)) """ prob_wrong = integrate.quad(self.prob_mult, self.lower_bound[i,j], # #lb_A, self.upper_bound[i,j], # #ub_A, args=(pdf_A, pdf_B, mu_B, lb_B, ub_B), ) """ #print(mu_B) #print(prob_wrong[0]) return prob_wrong[0] def compute_probability_wrong_blaze(self, i, j, k): pdf_A, pdf_B, mu_A, mu_B, sigma_A, sigma_B = \ self.apd_pdf_list[str(i)]['0'][j], \ self.apd_pdf_list[str(i)]['0'][k], \ self.apd_mean_samples[str(i)][0][j], \ self.apd_mean_samples[str(i)][0][k], \ self.apd_sigma_samples[str(i)][0][j], \ self.apd_sigma_samples[str(i)][0][k] cdf_B = self.apd_ecdf_list[str(i)]['0'][k] if k<j: return -1 elif j==k: return 0.5 elif (mu_A+3*sigma_A < mu_B-3*sigma_B) and (mu_A < mu_B): return 0 elif (mu_A-3*sigma_A > mu_B+3*sigma_B) and (mu_A > mu_B): return 1 prob_mult_vect = np.vectorize(self.prob_mult) prob_wrong = integrate.quad(prob_mult_vect, 0, np.inf, args=(pdf_A, cdf_B)) return prob_wrong[0] def compute_probability_wrong_superfast(self, i, j, k): lb_A = np.min(self.support_grids[i,j]) lb_B = np.min(self.support_grids[i,k]) ub_A = np.max(self.support_grids[i,j]) ub_B = np.max(self.support_grids[i,k]) if lb_A > ub_B: return 1 elif ub_A < lb_B: return 0 elif j==k: return 0.5 else: lb_int = max(lb_A, lb_B) ub_int = min(ub_A, ub_B) integrate.simps(self.pdf_cdf[i,j],) def fun_wrapper(self, indices): return self.compute_probability_wrong(*indices) #return self.compute_probability_wrong_fast(*indices) def fun_wrapper2(self, indices): return self.compute_probability_wrong_fast(*indices) def fun_wrapper3(self, indices): return self.compute_probability_wrong_blaze(*indices) def compute_rank(self): dim1 = self.size_rows dim2 = self.size_cols dim3 = self.size_cols self.rank_prob_wrong = np.zeros((dim1,dim2)) for i in range(self.size_rows): for j in range(self.size_cols): temp_rank = 0 for k in range(self.size_cols): print(i) print(j) print(k) temp_rank += self.compute_probability_wrong( self.pdf_list[str(i)][j], self.pdf_list[str(i)][k], self.mean_samples[i][k]) self.rank_prob_wrong[i, j] = temp_rank - 0.5 def compute_rank_vectorized(self): vect_prob = np.vectorize(self.compute_probability_wrong, otypes=[np.float], cache=False) for i in range(self.size_f): for j in range(self.num_objectives): print(i) print(j) temp_rank = np.asarray(vect_prob(self.pdf_list[str(i)][j], self.pdf_list[str(i)][:], self.mean_samples[i][:])) temp_rank = np.sum(temp_rank) print(temp_rank) self.rank_prob_wrong[i, j] = temp_rank - 0.5 def compute_rank_vectorized2(self): #p = mp.Pool(mp.cpu_count()) p = mp.Pool(1) dim1 = self.size_rows dim2 = self.size_cols dim3 = self.size_cols self.rank_prob_wrong = np.zeros((dim1,dim2,dim3)) #input = ((self.pdf_list[str(i)][j],self.pdf_list[str(i)][k],self.mean_samples[i][k]) for i,j,k in # itertools.combinations_with_replacement(range(dim3), 3) if i < dim1 and j < dim2) """ input = ((self.pdf_list[str(i)][j], self.pdf_list[str(i)][k], self.mean_samples[i][k]) for i, j, k in itertools.product(range(dim1), range(dim2), range(dim3))) results = p.map(self.fun_wrapper, input) p.close() p.join() results = np.reshape(results, (dim1, dim2, dim3)) """ input = ((i, j, k) for i, j, k in itertools.product(range(dim1), range(dim2), range(dim3))) results = p.map(self.fun_wrapper2, input) p.close() p.join() results = np.asarray(results) results = np.reshape(results,(dim1,dim2,dim3)) for i in range(dim1): for j in range(dim2): for k in range(dim3): if k<j: results[i,j,k]=1-results[i,k,j] #print(results) #print(results) self.rank_prob_wrong = np.sum(results, axis=2)-0.5 def compute_rank_vectorized_apd(self, apd_list, indiv_index_list): p = mp.Pool(mp.cpu_count()) dim1 = len(apd_list) for i in apd_list: self.compute_pdf(apd_list[i]) self.apd_pdf_list[i] = self.pdf_list.copy() self.apd_ecdf_list[i] = self.ecdf_list.copy() self.apd_mean_samples[i] = self.mean_samples self.apd_sigma_samples[i] = self.sigma_samples #print("All PDF/CDF computed ...") count = 0 for i in apd_list: for j in range(np.shape((apd_list[i]))[1]): for k in range(np.shape((apd_list[i]))[1]): self.parallel_list[str(count)]=[int(i),j,k] count += 1 input = ((self.parallel_list[i][0], self.parallel_list[i][1], self.parallel_list[i][2]) for i in self.parallel_list) #print("Computing probabilities!") results=p.map(self.fun_wrapper3, input) print("Done!") p.close() p.join() prob_matrix={} results = np.asarray(results) count = 0 for i in apd_list: prob_temp=np.zeros((np.shape((apd_list[i]))[1],np.shape((apd_list[i]))[1])) for j in range(np.shape((apd_list[i]))[1]): for k in range(np.shape((apd_list[i]))[1]): if j > k: prob_temp[j][k] = 1 - prob_temp[k][j] else: prob_temp[j][k] = results[count] count += 1 prob_matrix[i] = prob_temp rank_apd_matrix = {} for i in prob_matrix: rank_apd_matrix[i] = np.sum(prob_matrix[i], axis=1)-0.5 selection = [] for i in rank_apd_matrix: selection = np.append(selection,indiv_index_list[i][np.argmin(rank_apd_matrix[i])]) return selection.astype(int) def plt_density(self, samples): #X_plot = np.linspace(-1, 20, 3000) #plt.rcParams["text.usetex"] = True for i in range(self.size_rows): X_plot = np.linspace(0, np.max(samples[i,:,:]), 1000) for j in range(self.size_cols): #plt.rcParams["text.usetex"] = True fig, ax = plt.subplots() #fig.set_size_inches(5, 5) y = self.pdf_predict(X_plot, self.pdf_list[str(i)][j]) y_2 = self.ecdf_list[str(i)][j](X_plot) #print(i) #print(j) ax.set_xlabel(operator) ax.set_ylabel('Probability density',color='r') #ax.plot(samples[i,j,:], (np.random.rand(samples.shape[2])*-0.02)-0.02, 'g+', ms=10, label='APD samples') ax.plot(samples[i, j, :], (np.random.rand(samples.shape[2])*0.02)+0.02, 'g+', ms=10, label=operator+' samples') ax.plot(X_plot, y, label = 'Estimated PDF of '+operator,color='r') ax.hist(samples[i,j,:],30,alpha=0.5,density=True, label=('Histogram of '+operator+' samples')) ax.tick_params(axis='y',labelcolor='r') ax2=ax.twinx() ax2.set_ylabel('Cumulative density',color='b') ax.plot(X_plot, y_2, label='Empirical CDF of '+operator,color='b') ax2.tick_params(axis='y', labelcolor='b') ax.legend() #ax2.legend() fig.tight_layout() fig.savefig('./Plots/'+operator+'_dist_'+str(int(datetime.timestamp(datetime.now())*1000))+'.pdf') #plt.show() print('Plot!') def cdf_pdf_grids(self): self.pdf_cdf= np.zeros((self.size_rows,self.size_cols,1024)) self.cdf_grids = np.zeros((self.size_rows,self.size_cols,1024)) self.pdf_grids = np.zeros((self.size_rows,self.size_cols,1024)) self.support_grids = np.zeros((self.size_rows,self.size_cols,1024)) for i in range(self.size_rows): for j in range(self.size_cols): dens = sm.nonparametric.KDEUnivariate(self.f_samples[i, j, :]) dens.fit() self.cdf_grids[i,j,:] = dens.cdf self.pdf_grids[i,j,:] = self.pdf_predict(dens.support, self.pdf_list[str(i)][j]) self.support_grids[i,j,:] = dens.support #self.pdf_cdf[i,j,:] = self.pdf_grids[i, j,:] * self.cdf_grids[i, j,:] # %timeit self.compute_probability_wrong(self.pdf_list[str(0)][0],self.pdf_list[str(0)][0],self.mean_samples[0][0]) # %timeit np.asarray(vect_prob([self.pdf_list[str(0)][0]]*self.num_objectives,self.pdf_list[str(0)][:],self.mean_samples[0][:])) def pdf_ecdf(self): for i in range(self.size_rows): for j in range(self.size_cols): self.ecdf_list
[ "numpy.random.rand", "numpy.hstack", "multiprocessing.cpu_count", "numpy.mean", "numpy.reshape", "numpy.where", "numpy.asarray", "numpy.max", "sklearn.neighbors.kde.KernelDensity", "numpy.vstack", "numpy.min", "numpy.argmin", "numpy.ones", "statsmodels.api.nonparametric.KDEUnivariate", "...
[((383, 416), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (406, 416), False, 'import warnings\n'), ((544, 563), 'numpy.zeros', 'np.zeros', (['(3, 2, 2)'], {}), '((3, 2, 2))\n', (552, 563), True, 'import numpy as np\n'), ((2685, 2709), 'numpy.mean', 'np.mean', (['samples'], {'axis': '(2)'}), '(samples, axis=2)\n', (2692, 2709), True, 'import numpy as np\n'), ((2739, 2762), 'numpy.std', 'np.std', (['samples'], {'axis': '(2)'}), '(samples, axis=2)\n', (2745, 2762), True, 'import numpy as np\n'), ((2882, 2905), 'numpy.min', 'np.min', (['samples'], {'axis': '(2)'}), '(samples, axis=2)\n', (2888, 2905), True, 'import numpy as np\n'), ((2933, 2956), 'numpy.max', 'np.max', (['samples'], {'axis': '(2)'}), '(samples, axis=2)\n', (2939, 2956), True, 'import numpy as np\n'), ((5691, 5766), 'scipy.integrate.quad', 'integrate.quad', (['self.prob_mult2', '(-np.inf)', 'np.inf'], {'args': '(pdf_A, pdf_B, mu_B)'}), '(self.prob_mult2, -np.inf, np.inf, args=(pdf_A, pdf_B, mu_B))\n', (5705, 5766), True, 'import scipy.integrate as integrate\n'), ((6508, 6582), 'scipy.integrate.quad', 'integrate.quad', (['self.prob_mult', '(-np.inf)', 'np.inf'], {'args': '(pdf_A, pdf_B, mu_B)'}), '(self.prob_mult, -np.inf, np.inf, args=(pdf_A, pdf_B, mu_B))\n', (6522, 6582), True, 'import scipy.integrate as integrate\n'), ((7736, 7764), 'numpy.vectorize', 'np.vectorize', (['self.prob_mult'], {}), '(self.prob_mult)\n', (7748, 7764), True, 'import numpy as np\n'), ((7895, 7957), 'scipy.integrate.quad', 'integrate.quad', (['prob_mult_vect', '(0)', 'np.inf'], {'args': '(pdf_A, cdf_B)'}), '(prob_mult_vect, 0, np.inf, args=(pdf_A, cdf_B))\n', (7909, 7957), True, 'import scipy.integrate as integrate\n'), ((9276, 9304), 'numpy.vectorize', 'np.vectorize', (['self.prob_mult'], {}), '(self.prob_mult)\n', (9288, 9304), True, 'import numpy as np\n'), ((9327, 9389), 'scipy.integrate.quad', 'integrate.quad', (['prob_mult_vect', '(0)', 'np.inf'], {'args': '(pdf_A, cdf_B)'}), '(prob_mult_vect, 0, np.inf, args=(pdf_A, cdf_B))\n', (9341, 9389), True, 'import scipy.integrate as integrate\n'), ((9499, 9531), 'numpy.min', 'np.min', (['self.support_grids[i, j]'], {}), '(self.support_grids[i, j])\n', (9505, 9531), True, 'import numpy as np\n'), ((9546, 9578), 'numpy.min', 'np.min', (['self.support_grids[i, k]'], {}), '(self.support_grids[i, k])\n', (9552, 9578), True, 'import numpy as np\n'), ((9593, 9625), 'numpy.max', 'np.max', (['self.support_grids[i, j]'], {}), '(self.support_grids[i, j])\n', (9599, 9625), True, 'import numpy as np\n'), ((9640, 9672), 'numpy.max', 'np.max', (['self.support_grids[i, k]'], {}), '(self.support_grids[i, k])\n', (9646, 9672), True, 'import numpy as np\n'), ((9904, 9939), 'scipy.integrate.simps', 'integrate.simps', (['self.pdf_cdf[i, j]'], {}), '(self.pdf_cdf[i, j])\n', (9919, 9939), True, 'import scipy.integrate as integrate\n'), ((10444, 10466), 'numpy.zeros', 'np.zeros', (['(dim1, dim2)'], {}), '((dim1, dim2))\n', (10452, 10466), True, 'import numpy as np\n'), ((11158, 11234), 'numpy.vectorize', 'np.vectorize', (['self.compute_probability_wrong'], {'otypes': '[np.float]', 'cache': '(False)'}), '(self.compute_probability_wrong, otypes=[np.float], cache=False)\n', (11170, 11234), True, 'import numpy as np\n'), ((11848, 11858), 'multiprocessing.Pool', 'mp.Pool', (['(1)'], {}), '(1)\n', (11855, 11858), True, 'import multiprocessing as mp\n'), ((11980, 12008), 'numpy.zeros', 'np.zeros', (['(dim1, dim2, dim3)'], {}), '((dim1, dim2, dim3))\n', (11988, 12008), True, 'import numpy as np\n'), ((12777, 12796), 'numpy.asarray', 'np.asarray', (['results'], {}), '(results)\n', (12787, 12796), True, 'import numpy as np\n'), ((12815, 12854), 'numpy.reshape', 'np.reshape', (['results', '(dim1, dim2, dim3)'], {}), '(results, (dim1, dim2, dim3))\n', (12825, 12854), True, 'import numpy as np\n'), ((14200, 14219), 'numpy.asarray', 'np.asarray', (['results'], {}), '(results)\n', (14210, 14219), True, 'import numpy as np\n'), ((16810, 16858), 'numpy.zeros', 'np.zeros', (['(self.size_rows, self.size_cols, 1024)'], {}), '((self.size_rows, self.size_cols, 1024))\n', (16818, 16858), True, 'import numpy as np\n'), ((16882, 16930), 'numpy.zeros', 'np.zeros', (['(self.size_rows, self.size_cols, 1024)'], {}), '((self.size_rows, self.size_cols, 1024))\n', (16890, 16930), True, 'import numpy as np\n'), ((16954, 17002), 'numpy.zeros', 'np.zeros', (['(self.size_rows, self.size_cols, 1024)'], {}), '((self.size_rows, self.size_cols, 1024))\n', (16962, 17002), True, 'import numpy as np\n'), ((17030, 17078), 'numpy.zeros', 'np.zeros', (['(self.size_rows, self.size_cols, 1024)'], {}), '((self.size_rows, self.size_cols, 1024))\n', (17038, 17078), True, 'import numpy as np\n'), ((942, 963), 'numpy.shape', 'np.shape', (['mean_values'], {}), '(mean_values)\n', (950, 963), True, 'import numpy as np\n'), ((997, 1018), 'numpy.shape', 'np.shape', (['mean_values'], {}), '(mean_values)\n', (1005, 1018), True, 'import numpy as np\n'), ((2788, 2805), 'numpy.shape', 'np.shape', (['samples'], {}), '(samples)\n', (2796, 2805), True, 'import numpy as np\n'), ((2834, 2851), 'numpy.shape', 'np.shape', (['samples'], {}), '(samples)\n', (2842, 2851), True, 'import numpy as np\n'), ((4154, 4169), 'numpy.where', 'np.where', (['(x < 0)'], {}), '(x < 0)\n', (4162, 4169), True, 'import numpy as np\n'), ((4445, 4515), 'scipy.integrate.quad', 'integrate.quad', (['self.pdf_predict', '(mu_B - mu)', 'np.inf'], {'args': '(pdf1, mu_B)'}), '(self.pdf_predict, mu_B - mu, np.inf, args=(pdf1, mu_B))\n', (4459, 4515), True, 'import scipy.integrate as integrate\n'), ((6023, 6092), 'scipy.integrate.quad', 'integrate.quad', (['self.pdf_predict', '(mu_B - mu)', 'np.inf'], {'args': '(pdf, mu_B)'}), '(self.pdf_predict, mu_B - mu, np.inf, args=(pdf, mu_B))\n', (6037, 6092), True, 'import scipy.integrate as integrate\n'), ((13119, 13142), 'numpy.sum', 'np.sum', (['results'], {'axis': '(2)'}), '(results, axis=2)\n', (13125, 13142), True, 'import numpy as np\n'), ((13239, 13253), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (13251, 13253), True, 'import multiprocessing as mp\n'), ((1910, 2015), 'scipy.stats.truncnorm.rvs', 'truncnorm.rvs', (['(-3)', '(3)'], {'loc': 'self.mean_values[i, j]', 'scale': 'self.stddev_values[i, j]', 'size': 'self.n_samples'}), '(-3, 3, loc=self.mean_values[i, j], scale=self.stddev_values[i,\n j], size=self.n_samples)\n', (1923, 2015), False, 'from scipy.stats import truncnorm\n'), ((2183, 2225), 'numpy.reshape', 'np.reshape', (['sample', '(1, 1, self.n_samples)'], {}), '(sample, (1, 1, self.n_samples))\n', (2193, 2225), True, 'import numpy as np\n'), ((2504, 2539), 'numpy.vstack', 'np.vstack', (['(self.f_samples, f_temp)'], {}), '((self.f_samples, f_temp))\n', (2513, 2539), True, 'import numpy as np\n'), ((3021, 3052), 'numpy.power', 'np.power', (['self.n_samples', '(1 / 5)'], {}), '(self.n_samples, 1 / 5)\n', (3029, 3052), True, 'import numpy as np\n'), ((3084, 3125), 'numpy.ones', 'np.ones', (['(self.size_rows, self.size_cols)'], {}), '((self.size_rows, self.size_cols))\n', (3091, 3125), True, 'import numpy as np\n'), ((3730, 3747), 'statsmodels.distributions.empirical_distribution.ECDF', 'ECDF', (['sample_temp'], {}), '(sample_temp)\n', (3734, 3747), False, 'from statsmodels.distributions.empirical_distribution import ECDF\n'), ((11646, 11663), 'numpy.sum', 'np.sum', (['temp_rank'], {}), '(temp_rank)\n', (11652, 11663), True, 'import numpy as np\n'), ((14807, 14837), 'numpy.sum', 'np.sum', (['prob_matrix[i]'], {'axis': '(1)'}), '(prob_matrix[i], axis=1)\n', (14813, 14837), True, 'import numpy as np\n'), ((15235, 15259), 'numpy.max', 'np.max', (['samples[i, :, :]'], {}), '(samples[i, :, :])\n', (15241, 15259), True, 'import numpy as np\n'), ((15387, 15401), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (15399, 15401), True, 'import matplotlib.pyplot as plt\n'), ((17184, 17239), 'statsmodels.api.nonparametric.KDEUnivariate', 'sm.nonparametric.KDEUnivariate', (['self.f_samples[i, j, :]'], {}), '(self.f_samples[i, j, :])\n', (17214, 17239), True, 'import statsmodels.api as sm\n'), ((2346, 2373), 'numpy.hstack', 'np.hstack', (['(f_temp, sample)'], {}), '((f_temp, sample))\n', (2355, 2373), True, 'import numpy as np\n'), ((3575, 3607), 'numpy.reshape', 'np.reshape', (['sample_temp', '(-1, 1)'], {}), '(sample_temp, (-1, 1))\n', (3585, 3607), True, 'import numpy as np\n'), ((4023, 4045), 'numpy.reshape', 'np.reshape', (['x', '(-1, 1)'], {}), '(x, (-1, 1))\n', (4033, 4045), True, 'import numpy as np\n'), ((4107, 4136), 'numpy.reshape', 'np.reshape', (['(mu_B - x)', '(-1, 1)'], {}), '(mu_B - x, (-1, 1))\n', (4117, 4136), True, 'import numpy as np\n'), ((13699, 13720), 'numpy.shape', 'np.shape', (['apd_list[i]'], {}), '(apd_list[i])\n', (13707, 13720), True, 'import numpy as np\n'), ((14380, 14401), 'numpy.shape', 'np.shape', (['apd_list[i]'], {}), '(apd_list[i])\n', (14388, 14401), True, 'import numpy as np\n'), ((14963, 14992), 'numpy.argmin', 'np.argmin', (['rank_apd_matrix[i]'], {}), '(rank_apd_matrix[i])\n', (14972, 14992), True, 'import numpy as np\n'), ((3518, 3570), 'sklearn.neighbors.kde.KernelDensity', 'KernelDensity', ([], {'kernel': '"""gaussian"""', 'bandwidth': 'bw[i, j]'}), "(kernel='gaussian', bandwidth=bw[i, j])\n", (3531, 3570), False, 'from sklearn.neighbors.kde import KernelDensity\n'), ((13759, 13780), 'numpy.shape', 'np.shape', (['apd_list[i]'], {}), '(apd_list[i])\n', (13767, 13780), True, 'import numpy as np\n'), ((14297, 14318), 'numpy.shape', 'np.shape', (['apd_list[i]'], {}), '(apd_list[i])\n', (14305, 14318), True, 'import numpy as np\n'), ((14324, 14345), 'numpy.shape', 'np.shape', (['apd_list[i]'], {}), '(apd_list[i])\n', (14332, 14345), True, 'import numpy as np\n'), ((14440, 14461), 'numpy.shape', 'np.shape', (['apd_list[i]'], {}), '(apd_list[i])\n', (14448, 14461), True, 'import numpy as np\n'), ((15893, 15925), 'numpy.random.rand', 'np.random.rand', (['samples.shape[2]'], {}), '(samples.shape[2])\n', (15907, 15925), True, 'import numpy as np\n'), ((16668, 16682), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (16680, 16682), False, 'from datetime import datetime\n')]
import torch import torch.nn as nn import functools from .simple_layers import SimpleLayerBase, SimpleOutputBase, SimpleModule, SimpleMergeBase from ..layers.utils import div_shape from ..train.outputs_trw import OutputClassification as OutputClassification_train from ..train.outputs_trw import OutputEmbedding as OutputEmbedding_train from ..layers import Flatten as Flatten_layers import numpy as np import collections class Input(SimpleLayerBase): """ Represent an input (i.e., a feature) to a network """ def __init__(self, shape: list, feature_name: str): """ Args: shape: the shape of the input, including the batch size feature_name: the feature name to be used by the network from the batch """ assert isinstance(shape, list) super().__init__(parents=None, shape=shape) self.feature_name = feature_name def get_module(self): # there is no module required for input return None class OutputClassification(SimpleOutputBase): """ Output class for classification """ def __init__(self, node, output_name, classes_name, **kwargs): super().__init__(node=node, output_name=output_name, shape=node.shape) self.module_type = OutputClassification_train self.module_args = kwargs self.classes_name = classes_name def forward(self, inputs, batch): return self.module_type(inputs, batch[self.classes_name], classes_name=self.classes_name, **self.module_args) def get_module(self): # output layer, doesn't have a `Module` implementation return None def return_output(outputs, batch): return outputs class OutputEmbedding(SimpleOutputBase): """ Create an embedding for display purposes """ def __init__(self, node, output_name, functor=None): super().__init__(node=node, output_name=output_name, shape=node.shape) self.module_type = functools.partial(OutputEmbedding_train, functor=functor) def forward(self, inputs, batch): return self.module_type(inputs) def get_module(self): # output layer, doesn't have a `Module` implementation return None class ReLU(SimpleModule): def __init__(self, node): super().__init__(node=node, module=nn.ReLU(), shape=node.shape) class BatchNorm2d(SimpleModule): def __init__(self, node, eps=1e-5, momentum=0.1, affine=True): super().__init__( node=node, module=nn.BatchNorm2d(num_features=node.shape[1], eps=eps, momentum=momentum, affine=affine), shape=node.shape ) class BatchNorm3d(SimpleModule): def __init__(self, node, eps=1e-5, momentum=0.1, affine=True): super().__init__( node=node, module=nn.BatchNorm3d(num_features=node.shape[1], eps=eps, momentum=momentum, affine=affine), shape=node.shape ) class _Reshape(nn.Module): def __init__(self, shape): super().__init__() self.shape = shape def forward(self, x): return torch.reshape(x, self.shape) class Reshape(SimpleModule): """ Reshape a tensor to another shape """ def __init__(self, node, shape): reformated_shape = [s if s is not None else -1 for s in shape] super().__init__(node=node, module=_Reshape(shape=reformated_shape), shape=reformated_shape) class Linear(SimpleModule): def __init__(self, node, out_features): assert len(node.shape) == 2, 'Linear input shape must be 2D, instead got={}'.format(node.shape) module_args = {'in_features': node.shape[1], 'out_features': out_features} super().__init__(node=node, module=nn.Linear(**module_args), shape=[node.shape[0], out_features]) class Flatten(SimpleModule): def __init__(self, node): super().__init__(node=node, module=Flatten_layers(), shape=[node.shape[0], np.prod(node.shape[1:])]) def _conv_2d_shape_fn(node, module_args): assert len(node.shape) == 4, 'must be `Batch size * Channels * Height * Width`' out_channels = module_args['out_channels'] stride = module_args['stride'] return [node.shape[0], out_channels] + div_shape(node.shape[2:], div=stride) class Conv2d(SimpleModule): def __init__(self, node, out_channels, kernel_size, stride=1, padding='same'): module_args = { 'in_channels': node.shape[1], 'out_channels': out_channels, 'kernel_size': kernel_size, 'stride': stride } if padding == 'same': module_args['padding'] = div_shape(kernel_size, 2) elif padding is None: pass else: assert 0, 'padding mode is not handled!' super().__init__(node=node, module=nn.Conv2d(**module_args), shape=_conv_2d_shape_fn(node=node, module_args=module_args)) def _conv_3d_shape_fn(node, module_args): assert len(node.shape) == 5, 'must be `Batch size * Channels * Depth * Height * Width`' out_channels = module_args['out_channels'] stride = module_args['stride'] return [node.shape[0], out_channels] + div_shape(node.shape[2:], div=stride) class Conv3d(SimpleModule): def __init__(self, node, out_channels, kernel_size, stride=1, padding='same'): module_args = { 'in_channels': node.shape[1], 'out_channels': out_channels, 'kernel_size': kernel_size, 'stride': stride } if padding == 'same': module_args['padding'] = div_shape(kernel_size, 2) elif padding is None: pass else: assert 0, 'padding mode is not handled!' super().__init__(node=node, module=nn.Conv3d(**module_args), shape=_conv_3d_shape_fn(node=node, module_args=module_args)) class MaxPool2d(SimpleModule): def __init__(self, node, kernel_size, stride=None): module_args = {'kernel_size': kernel_size, 'stride': stride} super().__init__(node=node, module=nn.MaxPool2d(**module_args), shape=node.shape[0:2] + div_shape(node.shape[2:], 2)) class MaxPool3d(SimpleModule): def __init__(self, node, kernel_size, stride=None): module_args = {'kernel_size': kernel_size, 'stride': stride} super().__init__(node=node, module=nn.MaxPool3d(**module_args), shape=node.shape[0:2] + div_shape(node.shape[2:], 2)) class ConcatChannels(SimpleMergeBase): """ Implement a channel concatenation layer """ def __init__(self, nodes, flatten=False): assert isinstance(nodes, collections.Sequence), 'must be a list! Got={}'.format(type(nodes)) super().__init__(parents=nodes, shape=ConcatChannels.calculate_shape(nodes)) assert len(set(nodes)) == len(nodes), 'a node is duplicated! This is not handled!' self.flatten = flatten self.module = functools.partial(torch.cat, dim=1) @staticmethod def calculate_shape(parents): parent_shapes = [] total_channels = 0 for parent in parents: parent_shapes.append(parent.shape) expected_shape = parent_shapes[0][2:] found_shape = parent.shape[2:] assert expected_shape == found_shape, 'can\'t concate nodes as shape do not match. Expected={}, found={}' total_channels += parent.shape[1] shape = [None, total_channels] + parent_shapes[0][2:] return shape def get_module(self): return self.module
[ "torch.nn.BatchNorm2d", "torch.nn.ReLU", "numpy.prod", "torch.nn.MaxPool3d", "torch.nn.Conv2d", "torch.nn.MaxPool2d", "functools.partial", "torch.nn.Linear", "torch.nn.BatchNorm3d", "torch.reshape", "torch.nn.Conv3d" ]
[((1981, 2038), 'functools.partial', 'functools.partial', (['OutputEmbedding_train'], {'functor': 'functor'}), '(OutputEmbedding_train, functor=functor)\n', (1998, 2038), False, 'import functools\n'), ((3106, 3134), 'torch.reshape', 'torch.reshape', (['x', 'self.shape'], {}), '(x, self.shape)\n', (3119, 3134), False, 'import torch\n'), ((6879, 6914), 'functools.partial', 'functools.partial', (['torch.cat'], {'dim': '(1)'}), '(torch.cat, dim=1)\n', (6896, 6914), False, 'import functools\n'), ((2329, 2338), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (2336, 2338), True, 'import torch.nn as nn\n'), ((2528, 2617), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', ([], {'num_features': 'node.shape[1]', 'eps': 'eps', 'momentum': 'momentum', 'affine': 'affine'}), '(num_features=node.shape[1], eps=eps, momentum=momentum,\n affine=affine)\n', (2542, 2617), True, 'import torch.nn as nn\n'), ((2824, 2913), 'torch.nn.BatchNorm3d', 'nn.BatchNorm3d', ([], {'num_features': 'node.shape[1]', 'eps': 'eps', 'momentum': 'momentum', 'affine': 'affine'}), '(num_features=node.shape[1], eps=eps, momentum=momentum,\n affine=affine)\n', (2838, 2913), True, 'import torch.nn as nn\n'), ((3733, 3757), 'torch.nn.Linear', 'nn.Linear', ([], {}), '(**module_args)\n', (3742, 3757), True, 'import torch.nn as nn\n'), ((4809, 4833), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {}), '(**module_args)\n', (4818, 4833), True, 'import torch.nn as nn\n'), ((5747, 5771), 'torch.nn.Conv3d', 'nn.Conv3d', ([], {}), '(**module_args)\n', (5756, 5771), True, 'import torch.nn as nn\n'), ((6035, 6062), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {}), '(**module_args)\n', (6047, 6062), True, 'import torch.nn as nn\n'), ((6319, 6346), 'torch.nn.MaxPool3d', 'nn.MaxPool3d', ([], {}), '(**module_args)\n', (6331, 6346), True, 'import torch.nn as nn\n'), ((3940, 3963), 'numpy.prod', 'np.prod', (['node.shape[1:]'], {}), '(node.shape[1:])\n', (3947, 3963), True, 'import numpy as np\n')]
import gvar as gv import numpy as np data_file = 'data/a094m400mL6.0trMc_cfgs5-105_srcs0-15.h5' reweight = True rw_files = 'data/a094m400mL6.0trMc_cfgs5-105.h5' rw_path = 'reweighting-factors' fit_states = ['pion', 'proton', 'omega'] bs_seed = 'a094m400mL6.0trMc' # the pion data has a terrible condition number, ~e23 svdcut=5.e-6 corr_lst = { # PROTON 'proton':{ 'dsets' :['spec/proton/nsq_0/spin_par_avg'], 'weights' :[1.], 't_reverse':[False], 'phase' :[1], 'fold' :False, 'normalize':True, 'snks' :['S', 'P'], 'srcs' :['S'], 'xlim' :[0,28.5], 'ylim' :[0.4,0.759], 'colors' :{'SS':'#70bf41','PS':'k'}, 'type' :'exp', 'ztype' :'z_snk z_src', 'z_ylim' :[0.,.1], # fit params 'n_state' :4, 't_range' :np.arange(7,17), 't_sweep' :range(2,16), 'n_sweep' :range(1,6), }, # PION 'pion':{ 'dsets':['spec/piplus/nsq_0'], 'weights' :[1], 't_reverse':[False], 'fold' :True, 'normalize':True, 'snks' :['S', 'P'], 'srcs' :['S'], 'xlim' :[0,48.5], 'ylim' :[0.17,0.26], 'colors' :{'SS':'#70bf41','PS':'k'}, 'type' :'cosh', 'ztype' :'z_snk z_src', 'z_ylim' :[0.0,.1], # fit params 'n_state' :3, 'T' :96, 't_range' :np.arange(8,47), 't_sweep' :range(2,28), 'n_sweep' :range(1,6), 'eff_ylim' :[0.185,0.2] }, # OMEGA 'omega':{ 'dsets':[ 'spec/omega_m/nsq_0/spin_par_avg' ], 'weights' :[1.], 't_reverse':[False], 'phase' :[1], 'fold' :False, 'normalize':True, 'snks' :['S', 'P'], 'srcs' :['S'], 'xlim' :[0,28.5], 'ylim' :[0.55,0.8], 'colors' :{'SS':'#70bf41','PS':'k'}, 'type' :'exp', 'ztype' :'z_snk z_src', 'z_ylim' :[0.,.1], # fit params 'n_state' :4, 't_range' :np.arange(7,17), 't_sweep' :range(2,16), 'n_sweep' :range(1,6), }, } priors = gv.BufferDict() x = dict() priors['proton_E_0'] = gv.gvar(0.56, .06) priors['proton_zS_0'] = gv.gvar(.04, .01) priors['proton_zP_0'] = gv.gvar(.025, .01) priors['pion_E_0'] = gv.gvar(0.195, .02) priors['pion_zS_0'] = gv.gvar(0.07, 0.01) priors['pion_zP_0'] = gv.gvar(0.07, 0.01) priors['omega_E_0'] = gv.gvar(0.7, .07) priors['omega_zS_0'] = gv.gvar(.035, .01) priors['omega_zP_0'] = gv.gvar(.02, .01) for corr in corr_lst: for n in range(1,10): # use 2 mpi splitting for each dE # use log prior to force ordering of dE_n priors['log(%s_dE_%d)' %(corr,n)] = gv.gvar(np.log(2*priors['pion_E_0'].mean), 0.7) # for z_P, no suppression with n, but for S, smaller overlaps priors['%s_zP_%d' %(corr,n)] = gv.gvar(priors['%s_zP_0' %(corr)].mean, 4*priors['%s_zP_0' %(corr)].sdev) zS_0 = priors['%s_zS_0' %(corr)] if n <= 2: priors['%s_zS_%d' %(corr,n)] = gv.gvar(zS_0.mean, 4*zS_0.sdev) else: priors['%s_zS_%d' %(corr,n)] = gv.gvar(zS_0.mean/2, zS_0.mean/2) # x-params for snk in corr_lst[corr]['snks']: sp = snk+corr_lst[corr]['srcs'][0] state = corr+'_'+sp x[state] = dict() x[state]['state'] = corr for k in ['type', 'T', 'n_state', 't_range', 'eff_ylim', 'ztype']: if k in corr_lst[corr]: x[state][k] = corr_lst[corr][k] if 't0' in corr_lst[corr]: x[state]['t0'] = corr_lst[corr]['t0'] else: x[state]['t0'] = 0 x[state]['color'] = corr_lst[corr]['colors'][sp] x[state]['snk'] = snk x[state]['src'] = corr_lst[corr]['srcs'][0]
[ "gvar.gvar", "numpy.log", "gvar.BufferDict", "numpy.arange" ]
[((2284, 2299), 'gvar.BufferDict', 'gv.BufferDict', ([], {}), '()\n', (2297, 2299), True, 'import gvar as gv\n'), ((2341, 2360), 'gvar.gvar', 'gv.gvar', (['(0.56)', '(0.06)'], {}), '(0.56, 0.06)\n', (2348, 2360), True, 'import gvar as gv\n'), ((2384, 2403), 'gvar.gvar', 'gv.gvar', (['(0.04)', '(0.01)'], {}), '(0.04, 0.01)\n', (2391, 2403), True, 'import gvar as gv\n'), ((2426, 2446), 'gvar.gvar', 'gv.gvar', (['(0.025)', '(0.01)'], {}), '(0.025, 0.01)\n', (2433, 2446), True, 'import gvar as gv\n'), ((2468, 2488), 'gvar.gvar', 'gv.gvar', (['(0.195)', '(0.02)'], {}), '(0.195, 0.02)\n', (2475, 2488), True, 'import gvar as gv\n'), ((2510, 2529), 'gvar.gvar', 'gv.gvar', (['(0.07)', '(0.01)'], {}), '(0.07, 0.01)\n', (2517, 2529), True, 'import gvar as gv\n'), ((2552, 2571), 'gvar.gvar', 'gv.gvar', (['(0.07)', '(0.01)'], {}), '(0.07, 0.01)\n', (2559, 2571), True, 'import gvar as gv\n'), ((2596, 2614), 'gvar.gvar', 'gv.gvar', (['(0.7)', '(0.07)'], {}), '(0.7, 0.07)\n', (2603, 2614), True, 'import gvar as gv\n'), ((2637, 2657), 'gvar.gvar', 'gv.gvar', (['(0.035)', '(0.01)'], {}), '(0.035, 0.01)\n', (2644, 2657), True, 'import gvar as gv\n'), ((2679, 2698), 'gvar.gvar', 'gv.gvar', (['(0.02)', '(0.01)'], {}), '(0.02, 0.01)\n', (2686, 2698), True, 'import gvar as gv\n'), ((893, 909), 'numpy.arange', 'np.arange', (['(7)', '(17)'], {}), '(7, 17)\n', (902, 909), True, 'import numpy as np\n'), ((1501, 1517), 'numpy.arange', 'np.arange', (['(8)', '(47)'], {}), '(8, 47)\n', (1510, 1517), True, 'import numpy as np\n'), ((2183, 2199), 'numpy.arange', 'np.arange', (['(7)', '(17)'], {}), '(7, 17)\n', (2192, 2199), True, 'import numpy as np\n'), ((3040, 3113), 'gvar.gvar', 'gv.gvar', (["priors['%s_zP_0' % corr].mean", "(4 * priors['%s_zP_0' % corr].sdev)"], {}), "(priors['%s_zP_0' % corr].mean, 4 * priors['%s_zP_0' % corr].sdev)\n", (3047, 3113), True, 'import gvar as gv\n'), ((2890, 2925), 'numpy.log', 'np.log', (["(2 * priors['pion_E_0'].mean)"], {}), "(2 * priors['pion_E_0'].mean)\n", (2896, 2925), True, 'import numpy as np\n'), ((3217, 3250), 'gvar.gvar', 'gv.gvar', (['zS_0.mean', '(4 * zS_0.sdev)'], {}), '(zS_0.mean, 4 * zS_0.sdev)\n', (3224, 3250), True, 'import gvar as gv\n'), ((3306, 3343), 'gvar.gvar', 'gv.gvar', (['(zS_0.mean / 2)', '(zS_0.mean / 2)'], {}), '(zS_0.mean / 2, zS_0.mean / 2)\n', (3313, 3343), True, 'import gvar as gv\n')]
import numpy as np import matplotlib.pyplot as plt class Signal: def __init__(self, min_value, max_value, length_dots): self.min_value = min_value self.max_value = max_value self.length_dots = length_dots def generate_signal(self): number_array = np.linspace(self.min_value, self.max_value, self.length_dots) x_volts = 10 * np.sin(number_array * (2 * np.pi)) return number_array, x_volts def show_signal(self, number_array, x_volts, title): plt.subplot(3, 1, 1) plt.plot(number_array, x_volts) plt.title('сигнал' + ' ' + title) plt.ylabel('вольты') plt.xlabel('время') plt.show() def generate_random(self, volts_count): return np.random.normal(0, 1, volts_count)
[ "numpy.random.normal", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.linspace", "numpy.sin", "matplotlib.pyplot.title", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show" ]
[((301, 362), 'numpy.linspace', 'np.linspace', (['self.min_value', 'self.max_value', 'self.length_dots'], {}), '(self.min_value, self.max_value, self.length_dots)\n', (312, 362), True, 'import numpy as np\n'), ((529, 549), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(1)', '(1)'], {}), '(3, 1, 1)\n', (540, 549), True, 'import matplotlib.pyplot as plt\n'), ((559, 590), 'matplotlib.pyplot.plot', 'plt.plot', (['number_array', 'x_volts'], {}), '(number_array, x_volts)\n', (567, 590), True, 'import matplotlib.pyplot as plt\n'), ((600, 633), 'matplotlib.pyplot.title', 'plt.title', (["('сигнал' + ' ' + title)"], {}), "('сигнал' + ' ' + title)\n", (609, 633), True, 'import matplotlib.pyplot as plt\n'), ((643, 663), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""вольты"""'], {}), "('вольты')\n", (653, 663), True, 'import matplotlib.pyplot as plt\n'), ((673, 692), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""время"""'], {}), "('время')\n", (683, 692), True, 'import matplotlib.pyplot as plt\n'), ((702, 712), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (710, 712), True, 'import matplotlib.pyplot as plt\n'), ((776, 811), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', 'volts_count'], {}), '(0, 1, volts_count)\n', (792, 811), True, 'import numpy as np\n'), ((387, 421), 'numpy.sin', 'np.sin', (['(number_array * (2 * np.pi))'], {}), '(number_array * (2 * np.pi))\n', (393, 421), True, 'import numpy as np\n')]
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the NiBabel package for the # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """ Image processing functions for: * smoothing * resampling * converting sd to and from FWHM Smoothing and resampling routines need scipy """ import numpy as np import numpy.linalg as npl from .optpkg import optional_package spnd, _, _ = optional_package('scipy.ndimage') from .affines import AffineError, to_matvec, from_matvec, append_diag, rescale_affine from .spaces import vox2out_vox from .nifti1 import Nifti1Image from .orientations import axcodes2ornt, io_orientation, ornt_transform from .imageclasses import spatial_axes_first SIGMA2FWHM = np.sqrt(8 * np.log(2)) def fwhm2sigma(fwhm): """ Convert a FWHM value to sigma in a Gaussian kernel. Parameters ---------- fwhm : array-like FWHM value or values Returns ------- sigma : array or float sigma values corresponding to `fwhm` values Examples -------- >>> sigma = fwhm2sigma(6) >>> sigmae = fwhm2sigma([6, 7, 8]) >>> sigma == sigmae[0] True """ return np.asarray(fwhm) / SIGMA2FWHM def sigma2fwhm(sigma): """ Convert a sigma in a Gaussian kernel to a FWHM value Parameters ---------- sigma : array-like sigma value or values Returns ------- fwhm : array or float fwhm values corresponding to `sigma` values Examples -------- >>> fwhm = sigma2fwhm(3) >>> fwhms = sigma2fwhm([3, 4, 5]) >>> fwhm == fwhms[0] True """ return np.asarray(sigma) * SIGMA2FWHM def adapt_affine(affine, n_dim): """ Adapt input / output dimensions of spatial `affine` for `n_dims` Adapts a spatial (4, 4) affine that is being applied to an image with fewer than 3 spatial dimensions, or more than 3 dimensions. If there are more than three dimensions, assume an identity transformation for these dimensions. Parameters ---------- affine : array-like affine transform. Usually shape (4, 4). For what follows ``N, M = affine.shape`` n_dims : int Number of dimensions of underlying array, and therefore number of input dimensions for affine. Returns ------- adapted : shape (M, n_dims+1) array Affine array adapted to number of input dimensions. Columns of the affine corresponding to missing input dimensions have been dropped, columns corresponding to extra input dimensions have an extra identity column added """ affine = np.asarray(affine) rzs, trans = to_matvec(affine) # For missing input dimensions, drop columns in rzs rzs = rzs[:, :n_dim] adapted = from_matvec(rzs, trans) n_extra_columns = n_dim - adapted.shape[1] + 1 if n_extra_columns > 0: adapted = append_diag(adapted, np.ones((n_extra_columns,))) return adapted def resample_from_to(from_img, to_vox_map, order=3, mode='constant', cval=0., out_class=Nifti1Image): """ Resample image `from_img` to mapped voxel space `to_vox_map` Resample using N-d spline interpolation. Parameters ---------- from_img : object Object having attributes ``dataobj``, ``affine``, ``header`` and ``shape``. If `out_class` is not None, ``img.__class__`` should be able to construct an image from data, affine and header. to_vox_map : image object or length 2 sequence If object, has attributes ``shape`` giving input voxel shape, and ``affine`` giving mapping of input voxels to output space. If length 2 sequence, elements are (shape, affine) with same meaning as above. The affine is a (4, 4) array-like. order : int, optional The order of the spline interpolation, default is 3. The order has to be in the range 0-5 (see ``scipy.ndimage.affine_transform``) mode : str, optional Points outside the boundaries of the input are filled according to the given mode ('constant', 'nearest', 'reflect' or 'wrap'). Default is 'constant' (see ``scipy.ndimage.affine_transform``) cval : scalar, optional Value used for points outside the boundaries of the input if ``mode='constant'``. Default is 0.0 (see ``scipy.ndimage.affine_transform``) out_class : None or SpatialImage class, optional Class of output image. If None, use ``from_img.__class__``. Returns ------- out_img : object Image of instance specified by `out_class`, containing data output from resampling `from_img` into axes aligned to the output space of ``from_img.affine`` """ # This check requires `shape` attribute of image if not spatial_axes_first(from_img): raise ValueError('Cannot predict position of spatial axes for Image ' 'type ' + str(type(from_img))) try: to_shape, to_affine = to_vox_map.shape, to_vox_map.affine except AttributeError: to_shape, to_affine = to_vox_map a_to_affine = adapt_affine(to_affine, len(to_shape)) if out_class is None: out_class = from_img.__class__ from_n_dim = len(from_img.shape) if from_n_dim < 3: raise AffineError('from_img must be at least 3D') a_from_affine = adapt_affine(from_img.affine, from_n_dim) to_vox2from_vox = npl.inv(a_from_affine).dot(a_to_affine) rzs, trans = to_matvec(to_vox2from_vox) data = spnd.affine_transform(from_img.dataobj, rzs, trans, to_shape, order=order, mode=mode, cval=cval) return out_class(data, to_affine, from_img.header) def resample_to_output(in_img, voxel_sizes=None, order=3, mode='constant', cval=0., out_class=Nifti1Image): """ Resample image `in_img` to output voxel axes (world space) Parameters ---------- in_img : object Object having attributes ``dataobj``, ``affine``, ``header``. If `out_class` is not None, ``img.__class__`` should be able to construct an image from data, affine and header. voxel_sizes : None or sequence Gives the diagonal entries of ``out_img.affine` (except the trailing 1 for the homogenous coordinates) (``out_img.affine == np.diag(voxel_sizes + [1])``). If None, return identity `out_img.affine`. If scalar, interpret as vector ``[voxel_sizes] * len(in_img.shape)``. order : int, optional The order of the spline interpolation, default is 3. The order has to be in the range 0-5 (see ``scipy.ndimage.affine_transform``). mode : str, optional Points outside the boundaries of the input are filled according to the given mode ('constant', 'nearest', 'reflect' or 'wrap'). Default is 'constant' (see ``scipy.ndimage.affine_transform``). cval : scalar, optional Value used for points outside the boundaries of the input if ``mode='constant'``. Default is 0.0 (see ``scipy.ndimage.affine_transform``). out_class : None or SpatialImage class, optional Class of output image. If None, use ``in_img.__class__``. Returns ------- out_img : object Image of instance specified by `out_class`, containing data output from resampling `in_img` into axes aligned to the output space of ``in_img.affine`` """ if out_class is None: out_class = in_img.__class__ in_shape = in_img.shape n_dim = len(in_shape) if voxel_sizes is not None: voxel_sizes = np.asarray(voxel_sizes) if voxel_sizes.ndim == 0: # Scalar voxel_sizes = np.repeat(voxel_sizes, n_dim) # Allow 2D images by promoting to 3D. We might want to see what a slice # looks like when resampled into world coordinates if n_dim < 3: # Expand image to 3D, make voxel sizes match new_shape = in_shape + (1,) * (3 - n_dim) data = np.asanyarray(in_img.dataobj).reshape(new_shape) # 2D data should be small in_img = out_class(data, in_img.affine, in_img.header) if voxel_sizes is not None and len(voxel_sizes) == n_dim: # Need to pad out voxel sizes to match new image dimensions voxel_sizes = tuple(voxel_sizes) + (1,) * (3 - n_dim) out_vox_map = vox2out_vox((in_img.shape, in_img.affine), voxel_sizes) return resample_from_to(in_img, out_vox_map, order, mode, cval, out_class) def smooth_image(img, fwhm, mode='nearest', cval=0., out_class=Nifti1Image): """ Smooth image `img` along voxel axes by FWHM `fwhm` millimeters Parameters ---------- img : object Object having attributes ``dataobj``, ``affine``, ``header`` and ``shape``. If `out_class` is not None, ``img.__class__`` should be able to construct an image from data, affine and header. fwhm : scalar or length 3 sequence FWHM *in mm* over which to smooth. The smoothing applies to the voxel axes, not to the output axes, but is in millimeters. The function adjusts the FWHM to voxels using the voxel sizes calculated from the affine. A scalar implies the same smoothing across the spatial dimensions of the image, but 0 smoothing over any further dimensions such as time. A vector should be the same length as the number of image dimensions. mode : str, optional Points outside the boundaries of the input are filled according to the given mode ('constant', 'nearest', 'reflect' or 'wrap'). Default is 'nearest'. This is different from the default for ``scipy.ndimage.affine_transform``, which is 'constant'. 'nearest' might be a better choice when smoothing to the edge of an image where there is still strong brain signal, otherwise this signal will get blurred towards zero. cval : scalar, optional Value used for points outside the boundaries of the input if ``mode='constant'``. Default is 0.0 (see ``scipy.ndimage.affine_transform``). out_class : None or SpatialImage class, optional Class of output image. If None, use ``img.__class__``. Returns ------- smoothed_img : object Image of instance specified by `out_class`, containing data output from smoothing `img` data by given FWHM kernel. """ # This check requires `shape` attribute of image if not spatial_axes_first(img): raise ValueError('Cannot predict position of spatial axes for Image ' 'type ' + str(type(img))) if out_class is None: out_class = img.__class__ n_dim = len(img.shape) # TODO: make sure time axis is last # Pad out fwhm from scalar, adding 0 for fourth etc (time etc) dimensions fwhm = np.asarray(fwhm) if fwhm.size == 1: fwhm_scalar = fwhm fwhm = np.zeros((n_dim,)) fwhm[:3] = fwhm_scalar # Voxel sizes RZS = img.affine[:, :n_dim] vox = np.sqrt(np.sum(RZS ** 2, 0)) # Smoothing in terms of voxels vox_fwhm = fwhm / vox vox_sd = fwhm2sigma(vox_fwhm) # Do the smoothing sm_data = spnd.gaussian_filter(img.dataobj, vox_sd, mode=mode, cval=cval) return out_class(sm_data, img.affine, img.header) def conform(from_img, out_shape=(256, 256, 256), voxel_size=(1.0, 1.0, 1.0), order=3, cval=0.0, orientation='RAS', out_class=None): """ Resample image to ``out_shape`` with voxels of size ``voxel_size``. Using the default arguments, this function is meant to replicate most parts of FreeSurfer's ``mri_convert --conform`` command. Specifically, this function: - Resamples data to ``output_shape`` - Resamples voxel sizes to ``voxel_size`` - Reorients to RAS (``mri_convert --conform`` reorients to LIA) Unlike ``mri_convert --conform``, this command does not: - Transform data to range [0, 255] - Cast to unsigned eight-bit integer Parameters ---------- from_img : object Object having attributes ``dataobj``, ``affine``, ``header`` and ``shape``. If `out_class` is not None, ``img.__class__`` should be able to construct an image from data, affine and header. out_shape : sequence, optional The shape of the output volume. Default is (256, 256, 256). voxel_size : sequence, optional The size in millimeters of the voxels in the resampled output. Default is 1mm isotropic. order : int, optional The order of the spline interpolation, default is 3. The order has to be in the range 0-5 (see ``scipy.ndimage.affine_transform``) cval : scalar, optional Value used for points outside the boundaries of the input if ``mode='constant'``. Default is 0.0 (see ``scipy.ndimage.affine_transform``) orientation : str, optional Orientation of output image. Default is "RAS". out_class : None or SpatialImage class, optional Class of output image. If None, use ``from_img.__class__``. Returns ------- out_img : object Image of instance specified by `out_class`, containing data output from resampling `from_img` into axes aligned to the output space of ``from_img.affine`` """ # Only support 3D images. This can be made more general in the future, once tests # are written. required_ndim = 3 if from_img.ndim != required_ndim: raise ValueError("Only 3D images are supported.") elif len(out_shape) != required_ndim: raise ValueError(f"`out_shape` must have {required_ndim} values") elif len(voxel_size) != required_ndim: raise ValueError(f"`voxel_size` must have {required_ndim} values") start_ornt = io_orientation(from_img.affine) end_ornt = axcodes2ornt(orientation) transform = ornt_transform(start_ornt, end_ornt) # Reorient first to ensure shape matches expectations reoriented = from_img.as_reoriented(transform) out_aff = rescale_affine(reoriented.affine, reoriented.shape, voxel_size, out_shape) # Resample input image. out_img = resample_from_to( from_img=from_img, to_vox_map=(out_shape, out_aff), order=order, mode="constant", cval=cval, out_class=out_class) return out_img
[ "numpy.repeat", "numpy.ones", "numpy.log", "numpy.asarray", "numpy.asanyarray", "numpy.sum", "numpy.zeros", "numpy.linalg.inv" ]
[((2837, 2855), 'numpy.asarray', 'np.asarray', (['affine'], {}), '(affine)\n', (2847, 2855), True, 'import numpy as np\n'), ((11508, 11524), 'numpy.asarray', 'np.asarray', (['fwhm'], {}), '(fwhm)\n', (11518, 11524), True, 'import numpy as np\n'), ((956, 965), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (962, 965), True, 'import numpy as np\n'), ((1386, 1402), 'numpy.asarray', 'np.asarray', (['fwhm'], {}), '(fwhm)\n', (1396, 1402), True, 'import numpy as np\n'), ((1834, 1851), 'numpy.asarray', 'np.asarray', (['sigma'], {}), '(sigma)\n', (1844, 1851), True, 'import numpy as np\n'), ((8201, 8224), 'numpy.asarray', 'np.asarray', (['voxel_sizes'], {}), '(voxel_sizes)\n', (8211, 8224), True, 'import numpy as np\n'), ((11590, 11608), 'numpy.zeros', 'np.zeros', (['(n_dim,)'], {}), '((n_dim,))\n', (11598, 11608), True, 'import numpy as np\n'), ((11708, 11727), 'numpy.sum', 'np.sum', (['(RZS ** 2)', '(0)'], {}), '(RZS ** 2, 0)\n', (11714, 11727), True, 'import numpy as np\n'), ((3128, 3155), 'numpy.ones', 'np.ones', (['(n_extra_columns,)'], {}), '((n_extra_columns,))\n', (3135, 3155), True, 'import numpy as np\n'), ((5742, 5764), 'numpy.linalg.inv', 'npl.inv', (['a_from_affine'], {}), '(a_from_affine)\n', (5749, 5764), True, 'import numpy.linalg as npl\n'), ((8295, 8324), 'numpy.repeat', 'np.repeat', (['voxel_sizes', 'n_dim'], {}), '(voxel_sizes, n_dim)\n', (8304, 8324), True, 'import numpy as np\n'), ((8586, 8615), 'numpy.asanyarray', 'np.asanyarray', (['in_img.dataobj'], {}), '(in_img.dataobj)\n', (8599, 8615), True, 'import numpy as np\n')]
import numpy as np import torch from pgbar import progress_bar class RayS(object): def __init__(self, model, epsilon=0.031, order=np.inf): self.model = model self.ord = order self.epsilon = epsilon self.sgn_t = None self.d_t = None self.x_final = None self.queries = None def get_xadv(self, x, v, d, lb=0., ub=1.): if isinstance(d, int): d = torch.tensor(d).repeat(len(x)).cuda() out = x + d.view(len(x), 1, 1, 1) * v out = torch.clamp(out, lb, ub) return out def attack_hard_label(self, x, y, target=None, query_limit=10000, seed=None): """ Attack the original image and return adversarial example model: (pytorch model) (x, y): original image """ shape = list(x.shape) dim = np.prod(shape[1:]) if seed is not None: np.random.seed(seed) # init variables self.queries = torch.zeros_like(y).cuda() self.sgn_t = torch.sign(torch.ones(shape)).cuda() self.d_t = torch.ones_like(y).float().fill_(float("Inf")).cuda() working_ind = (self.d_t > self.epsilon).nonzero().flatten() stop_queries = self.queries.clone() dist = self.d_t.clone() self.x_final = self.get_xadv(x, self.sgn_t, self.d_t) block_level = 0 block_ind = 0 for i in range(query_limit): block_num = 2 ** block_level block_size = int(np.ceil(dim / block_num)) start, end = block_ind * block_size, min(dim, (block_ind + 1) * block_size) valid_mask = (self.queries < query_limit) attempt = self.sgn_t.clone().view(shape[0], dim) attempt[valid_mask.nonzero().flatten(), start:end] *= -1. attempt = attempt.view(shape) self.binary_search(x, y, target, attempt, valid_mask) block_ind += 1 if block_ind == 2 ** block_level or end == dim: block_level += 1 block_ind = 0 dist = torch.norm((self.x_final - x).view(shape[0], -1), self.ord, 1) stop_queries[working_ind] = self.queries[working_ind] working_ind = (dist > self.epsilon).nonzero().flatten() if torch.sum(self.queries >= query_limit) == shape[0]: print('out of queries') break progress_bar(torch.min(self.queries.float()), query_limit, 'd_t: %.4f | adbd: %.4f | queries: %.4f | rob acc: %.4f | iter: %d' % (torch.mean(self.d_t), torch.mean(dist), torch.mean(self.queries.float()), len(working_ind) / len(x), i + 1)) stop_queries = torch.clamp(stop_queries, 0, query_limit) return self.x_final, stop_queries, dist, (dist <= self.epsilon) # check whether solution is found def search_succ(self, x, y, target, mask): self.queries[mask] += 1 if target: return self.model.predict_label(x[mask]) == target[mask] else: return self.model.predict_label(x[mask]) != y[mask] # binary search for decision boundary along sgn direction def binary_search(self, x, y, target, sgn, valid_mask, tol=1e-3): sgn_norm = torch.norm(sgn.view(len(x), -1), 2, 1) sgn_unit = sgn / sgn_norm.view(len(x), 1, 1, 1) d_start = torch.zeros_like(y).float().cuda() d_end = self.d_t.clone() initial_succ_mask = self.search_succ(self.get_xadv(x, sgn_unit, self.d_t), y, target, valid_mask) to_search_ind = valid_mask.nonzero().flatten()[initial_succ_mask] d_end[to_search_ind] = torch.min(self.d_t, sgn_norm)[to_search_ind] while len(to_search_ind) > 0: d_mid = (d_start + d_end) / 2.0 search_succ_mask = self.search_succ(self.get_xadv(x, sgn_unit, d_mid), y, target, to_search_ind) d_end[to_search_ind[search_succ_mask]] = d_mid[to_search_ind[search_succ_mask]] d_start[to_search_ind[~search_succ_mask]] = d_mid[to_search_ind[~search_succ_mask]] to_search_ind = to_search_ind[((d_end - d_start)[to_search_ind] > tol)] to_update_ind = (d_end < self.d_t).nonzero().flatten() if len(to_update_ind) > 0: self.d_t[to_update_ind] = d_end[to_update_ind] self.x_final[to_update_ind] = self.get_xadv(x, sgn_unit, d_end)[to_update_ind] self.sgn_t[to_update_ind] = sgn[to_update_ind] def __call__(self, data, label, target=None, query_limit=10000): return self.attack_hard_label(data, label, target=target, query_limit=query_limit)
[ "numpy.prod", "numpy.ceil", "torch.ones_like", "torch.mean", "torch.min", "torch.tensor", "torch.sum", "numpy.random.seed", "torch.zeros_like", "torch.clamp", "torch.ones" ]
[((527, 551), 'torch.clamp', 'torch.clamp', (['out', 'lb', 'ub'], {}), '(out, lb, ub)\n', (538, 551), False, 'import torch\n'), ((849, 867), 'numpy.prod', 'np.prod', (['shape[1:]'], {}), '(shape[1:])\n', (856, 867), True, 'import numpy as np\n'), ((2763, 2804), 'torch.clamp', 'torch.clamp', (['stop_queries', '(0)', 'query_limit'], {}), '(stop_queries, 0, query_limit)\n', (2774, 2804), False, 'import torch\n'), ((909, 929), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (923, 929), True, 'import numpy as np\n'), ((3707, 3736), 'torch.min', 'torch.min', (['self.d_t', 'sgn_norm'], {}), '(self.d_t, sgn_norm)\n', (3716, 3736), False, 'import torch\n'), ((979, 998), 'torch.zeros_like', 'torch.zeros_like', (['y'], {}), '(y)\n', (995, 998), False, 'import torch\n'), ((1499, 1523), 'numpy.ceil', 'np.ceil', (['(dim / block_num)'], {}), '(dim / block_num)\n', (1506, 1523), True, 'import numpy as np\n'), ((2293, 2331), 'torch.sum', 'torch.sum', (['(self.queries >= query_limit)'], {}), '(self.queries >= query_limit)\n', (2302, 2331), False, 'import torch\n'), ((1038, 1055), 'torch.ones', 'torch.ones', (['shape'], {}), '(shape)\n', (1048, 1055), False, 'import torch\n'), ((2600, 2620), 'torch.mean', 'torch.mean', (['self.d_t'], {}), '(self.d_t)\n', (2610, 2620), False, 'import torch\n'), ((2622, 2638), 'torch.mean', 'torch.mean', (['dist'], {}), '(dist)\n', (2632, 2638), False, 'import torch\n'), ((3427, 3446), 'torch.zeros_like', 'torch.zeros_like', (['y'], {}), '(y)\n', (3443, 3446), False, 'import torch\n'), ((429, 444), 'torch.tensor', 'torch.tensor', (['d'], {}), '(d)\n', (441, 444), False, 'import torch\n'), ((1083, 1101), 'torch.ones_like', 'torch.ones_like', (['y'], {}), '(y)\n', (1098, 1101), False, 'import torch\n')]
from numpy import array from pybimstab.astar import Astar grid = array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0, 0, 1], [0, 0, 1, 1, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0, 0, 1], [0, 0, 0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 1], [0, 0, 1, 0, 0, 1, 0, 0, 0, 0]]) for heuristic in ['manhattan', 'euclidean']: astar = Astar(grid, startNode=(0, 0), goalNode=(9, 9), heuristic=heuristic, reverseLeft=True, reverseUp=True, preferredPath=None) fig = astar.plot()
[ "numpy.array", "pybimstab.astar.Astar" ]
[((65, 410), 'numpy.array', 'array', (['[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, \n 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0, 0, 1], [0, 0, 1, 1, 0, 1,\n 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0, 0, 1], [0, 0, 0, 0, 1, 0, 0, 1, 0,\n 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 1], [0,\n 0, 1, 0, 0, 1, 0, 0, 0, 0]]'], {}), '([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 1, 0, 0], [1, \n 1, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0, 0, 1], [0, 0, 1, 1,\n 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0, 0, 1], [0, 0, 0, 0, 1, 0, 0,\n 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 1\n ], [0, 0, 1, 0, 0, 1, 0, 0, 0, 0]])\n', (70, 410), False, 'from numpy import array\n'), ((576, 701), 'pybimstab.astar.Astar', 'Astar', (['grid'], {'startNode': '(0, 0)', 'goalNode': '(9, 9)', 'heuristic': 'heuristic', 'reverseLeft': '(True)', 'reverseUp': '(True)', 'preferredPath': 'None'}), '(grid, startNode=(0, 0), goalNode=(9, 9), heuristic=heuristic,\n reverseLeft=True, reverseUp=True, preferredPath=None)\n', (581, 701), False, 'from pybimstab.astar import Astar\n')]
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Any, List, Optional, Type import cv2 import numpy as np from gym import spaces import habitat from habitat.config import Config from habitat.core.dataset import Episode, Dataset from habitat.core.embodied_task import Measurements from habitat.core.simulator import ( Simulator, ShortestPathPoint, SensorTypes, SensorSuite, ) from habitat.tasks.utils import cartesian_to_polar, quaternion_rotate_vector from habitat.utils.visualizations import maps COLLISION_PROXIMITY_TOLERANCE: float = 1e-3 MAP_THICKNESS_SCALAR: int = 1250 def merge_sim_episode_config( sim_config: Config, episode: Type[Episode] ) -> Any: sim_config.defrost() sim_config.SCENE = episode.scene_id sim_config.freeze() if ( episode.start_position is not None and episode.start_rotation is not None ): agent_name = sim_config.AGENTS[sim_config.DEFAULT_AGENT_ID] agent_cfg = getattr(sim_config, agent_name) agent_cfg.defrost() agent_cfg.START_POSITION = episode.start_position agent_cfg.START_ROTATION = episode.start_rotation agent_cfg.IS_SET_START_STATE = True agent_cfg.freeze() return sim_config class NavigationGoal: """Base class for a goal specification hierarchy. """ position: List[float] radius: Optional[float] def __init__( self, position: List[float], radius: Optional[float] = None, **kwargs ) -> None: self.position = position self.radius = radius class ObjectGoal(NavigationGoal): """Object goal that can be specified by object_id or position or object category. """ object_id: str object_name: Optional[str] object_category: Optional[str] room_id: Optional[str] room_name: Optional[str] def __init__( self, object_id: str, room_id: Optional[str] = None, object_name: Optional[str] = None, object_category: Optional[str] = None, room_name: Optional[str] = None, **kwargs ) -> None: super().__init__(**kwargs) self.object_id = object_id self.object_name = object_name self.object_category = object_category self.room_id = room_id self.room_name = room_name class RoomGoal(NavigationGoal): """Room goal that can be specified by room_id or position with radius. """ room_id: str room_name: Optional[str] def __init__( self, room_id: str, room_name: Optional[str] = None, **kwargs ) -> None: super().__init__(**kwargs) # type: ignore self.room_id = room_id self.room_name = room_name class NavigationEpisode(Episode): """Class for episode specification that includes initial position and rotation of agent, scene name, goal and optional shortest paths. An episode is a description of one task instance for the agent. Args: episode_id: id of episode in the dataset, usually episode number scene_id: id of scene in scene dataset start_position: numpy ndarray containing 3 entries for (x, y, z) start_rotation: numpy ndarray with 4 entries for (x, y, z, w) elements of unit quaternion (versor) representing agent 3D orientation. ref: https://en.wikipedia.org/wiki/Versor goals: list of goals specifications start_room: room id shortest_paths: list containing shortest paths to goals """ goals: List[NavigationGoal] start_room: Optional[str] shortest_paths: Optional[List[ShortestPathPoint]] def __init__( self, goals: List[NavigationGoal], start_room: Optional[str] = None, shortest_paths: Optional[List[ShortestPathPoint]] = None, **kwargs ) -> None: super().__init__(**kwargs) self.goals = goals self.shortest_paths = shortest_paths self.start_room = start_room class PointGoalSensor(habitat.Sensor): """ Sensor for PointGoal observations which are used in the PointNav task. For the agent in simulator the forward direction is along negative-z. In polar coordinate format the angle returned is azimuth to the goal. Args: sim: reference to the simulator for calculating task observations. config: config for the PointGoal sensor. Can contain field for GOAL_FORMAT which can be used to specify the format in which the pointgoal is specified. Current options for goal format are cartesian and polar. Attributes: _goal_format: format for specifying the goal which can be done in cartesian or polar coordinates. """ def __init__(self, sim: Simulator, config: Config): self._sim = sim self._goal_format = getattr(config, "GOAL_FORMAT", "CARTESIAN") assert self._goal_format in ["CARTESIAN", "POLAR"] super().__init__(config=config) def _get_uuid(self, *args: Any, **kwargs: Any): return "pointgoal" def _get_sensor_type(self, *args: Any, **kwargs: Any): return SensorTypes.PATH def _get_observation_space(self, *args: Any, **kwargs: Any): if self._goal_format == "CARTESIAN": sensor_shape = (3,) else: sensor_shape = (2,) return spaces.Box( low=np.finfo(np.float32).min, high=np.finfo(np.float32).max, shape=sensor_shape, dtype=np.float32, ) def get_observation(self, observations, episode): agent_state = self._sim.get_agent_state() ref_position = agent_state.position rotation_world_agent = agent_state.rotation direction_vector = ( np.array(episode.goals[0].position, dtype=np.float32) - ref_position ) direction_vector_agent = quaternion_rotate_vector( rotation_world_agent.inverse(), direction_vector ) if self._goal_format == "POLAR": rho, phi = cartesian_to_polar( -direction_vector_agent[2], direction_vector_agent[0] ) direction_vector_agent = np.array([rho, -phi], dtype=np.float32) return direction_vector_agent class StaticPointGoalSensor(habitat.Sensor): """ Sensor for PointGoal observations which are used in the StaticPointNav task. For the agent in simulator the forward direction is along negative-z. In polar coordinate format the angle returned is azimuth to the goal. Args: sim: reference to the simulator for calculating task observations. config: config for the PointGoal sensor. Can contain field for GOAL_FORMAT which can be used to specify the format in which the pointgoal is specified. Current options for goal format are cartesian and polar. Attributes: _goal_format: format for specifying the goal which can be done in cartesian or polar coordinates. """ def __init__(self, sim: Simulator, config: Config): self._sim = sim self._goal_format = getattr(config, "GOAL_FORMAT", "CARTESIAN") assert self._goal_format in ["CARTESIAN", "POLAR"] super().__init__(sim, config) self._initial_vector = None self.current_episode_id = None def _get_uuid(self, *args: Any, **kwargs: Any): return "static_pointgoal" def _get_sensor_type(self, *args: Any, **kwargs: Any): return SensorTypes.PATH def _get_observation_space(self, *args: Any, **kwargs: Any): if self._goal_format == "CARTESIAN": sensor_shape = (3,) else: sensor_shape = (2,) return spaces.Box( low=np.finfo(np.float32).min, high=np.finfo(np.float32).max, shape=sensor_shape, dtype=np.float32, ) def get_observation(self, observations, episode): episode_id = (episode.episode_id, episode.scene_id) if self.current_episode_id != episode_id: # Only compute the direction vector when a new episode is started. self.current_episode_id = episode_id agent_state = self._sim.get_agent_state() ref_position = agent_state.position rotation_world_agent = agent_state.rotation direction_vector = ( np.array(episode.goals[0].position, dtype=np.float32) - ref_position ) direction_vector_agent = quaternion_rotate_vector( rotation_world_agent.inverse(), direction_vector ) if self._goal_format == "POLAR": rho, phi = cartesian_to_polar( -direction_vector_agent[2], direction_vector_agent[0] ) direction_vector_agent = np.array( [rho, -phi], dtype=np.float32 ) self._initial_vector = direction_vector_agent return self._initial_vector class HeadingSensor(habitat.Sensor): """ Sensor for observing the agent's heading in the global coordinate frame. Args: sim: reference to the simulator for calculating task observations. config: config for the sensor. """ def __init__(self, sim: Simulator, config: Config): self._sim = sim super().__init__(config=config) def _get_uuid(self, *args: Any, **kwargs: Any): return "heading" def _get_sensor_type(self, *args: Any, **kwargs: Any): return SensorTypes.HEADING def _get_observation_space(self, *args: Any, **kwargs: Any): return spaces.Box(low=-np.pi, high=np.pi, shape=(1,), dtype=np.float) def get_observation(self, observations, episode): agent_state = self._sim.get_agent_state() rotation_world_agent = agent_state.rotation direction_vector = np.array([0, 0, -1]) heading_vector = quaternion_rotate_vector( rotation_world_agent.inverse(), direction_vector ) phi = cartesian_to_polar(-heading_vector[2], heading_vector[0])[1] return np.array(phi) class ProximitySensor(habitat.Sensor): """ Sensor for observing the distance to the closest obstacle Args: sim: reference to the simulator for calculating task observations. config: config for the sensor. """ def __init__(self, sim, config): self._sim = sim self._max_detection_radius = getattr( config, "MAX_DETECTION_RADIUS", 2.0 ) super().__init__(config=config) def _get_uuid(self, *args: Any, **kwargs: Any): return "proximity" def _get_sensor_type(self, *args: Any, **kwargs: Any): return SensorTypes.TACTILE def _get_observation_space(self, *args: Any, **kwargs: Any): return spaces.Box( low=0.0, high=self._max_detection_radius, shape=(1,), dtype=np.float, ) def get_observation(self, observations, episode): current_position = self._sim.get_agent_state().position return self._sim.distance_to_closest_obstacle( current_position, self._max_detection_radius ) class SPL(habitat.Measure): """SPL (Success weighted by Path Length) ref: On Evaluation of Embodied Agents - Anderson et. al https://arxiv.org/pdf/1807.06757.pdf """ def __init__(self, sim: Simulator, config: Config): self._previous_position = None self._start_end_episode_distance = None self._agent_episode_distance = None self._sim = sim self._config = config super().__init__() def _get_uuid(self, *args: Any, **kwargs: Any): return "spl" def reset_metric(self, episode): self._previous_position = self._sim.get_agent_state().position.tolist() self._start_end_episode_distance = episode.info["geodesic_distance"] self._agent_episode_distance = 0.0 self._metric = None def _euclidean_distance(self, position_a, position_b): return np.linalg.norm( np.array(position_b) - np.array(position_a), ord=2 ) def update_metric(self, episode, action): ep_success = 0 current_position = self._sim.get_agent_state().position.tolist() distance_to_target = self._sim.geodesic_distance( current_position, episode.goals[0].position ) if ( action == self._sim.index_stop_action and distance_to_target < self._config.SUCCESS_DISTANCE ): ep_success = 1 self._agent_episode_distance += self._euclidean_distance( current_position, self._previous_position ) self._previous_position = current_position self._metric = ep_success * ( self._start_end_episode_distance / max( self._start_end_episode_distance, self._agent_episode_distance ) ) class Collisions(habitat.Measure): def __init__(self, sim, config): self._sim = sim self._config = config self._metric = None super().__init__() def _get_uuid(self, *args: Any, **kwargs: Any): return "collisions" def reset_metric(self, episode): self._metric = None def update_metric(self, episode, action): if self._metric is None: self._metric = 0 current_position = self._sim.get_agent_state().position if ( action == self._sim.index_forward_action and self._sim.distance_to_closest_obstacle(current_position) < COLLISION_PROXIMITY_TOLERANCE ): self._metric += 1 class TopDownMap(habitat.Measure): """Top Down Map measure """ def __init__(self, sim: Simulator, config: Config): self._sim = sim self._config = config self._grid_delta = config.MAP_PADDING self._step_count = None self._map_resolution = (config.MAP_RESOLUTION, config.MAP_RESOLUTION) self._num_samples = config.NUM_TOPDOWN_MAP_SAMPLE_POINTS self._ind_x_min = None self._ind_x_max = None self._ind_y_min = None self._ind_y_max = None self._previous_xy_location = None self._coordinate_min = maps.COORDINATE_MIN self._coordinate_max = maps.COORDINATE_MAX self._top_down_map = None self._cell_scale = ( self._coordinate_max - self._coordinate_min ) / self._map_resolution[0] super().__init__() def _get_uuid(self, *args: Any, **kwargs: Any): return "top_down_map" def _check_valid_nav_point(self, point: List[float]): self._sim.is_navigable(point) def get_original_map(self, episode): top_down_map = maps.get_topdown_map( self._sim, self._map_resolution, self._num_samples, self._config.DRAW_BORDER, ) range_x = np.where(np.any(top_down_map, axis=1))[0] range_y = np.where(np.any(top_down_map, axis=0))[0] self._ind_x_min = range_x[0] self._ind_x_max = range_x[-1] self._ind_y_min = range_y[0] self._ind_y_max = range_y[-1] if self._config.DRAW_SOURCE_AND_TARGET: # mark source point s_x, s_y = maps.to_grid( episode.start_position[0], episode.start_position[2], self._coordinate_min, self._coordinate_max, self._map_resolution, ) point_padding = 2 * int( np.ceil(self._map_resolution[0] / MAP_THICKNESS_SCALAR) ) top_down_map[ s_x - point_padding : s_x + point_padding + 1, s_y - point_padding : s_y + point_padding + 1, ] = maps.MAP_SOURCE_POINT_INDICATOR # mark target point t_x, t_y = maps.to_grid( episode.goals[0].position[0], episode.goals[0].position[2], self._coordinate_min, self._coordinate_max, self._map_resolution, ) top_down_map[ t_x - point_padding : t_x + point_padding + 1, t_y - point_padding : t_y + point_padding + 1, ] = maps.MAP_TARGET_POINT_INDICATOR return top_down_map def reset_metric(self, episode): self._step_count = 0 self._metric = None self._top_down_map = self.get_original_map(episode) agent_position = self._sim.get_agent_state().position a_x, a_y = maps.to_grid( agent_position[0], agent_position[2], self._coordinate_min, self._coordinate_max, self._map_resolution, ) self._previous_xy_location = (a_y, a_x) def update_metric(self, episode, action): self._step_count += 1 house_map, map_agent_x, map_agent_y = self.update_map( self._sim.get_agent_state().position ) # Rather than return the whole map which may have large empty regions, # only return the occupied part (plus some padding). house_map = house_map[ self._ind_x_min - self._grid_delta : self._ind_x_max + self._grid_delta, self._ind_y_min - self._grid_delta : self._ind_y_max + self._grid_delta, ] self._metric = { "map": house_map, "agent_map_coord": ( map_agent_x - (self._ind_x_min - self._grid_delta), map_agent_y - (self._ind_y_min - self._grid_delta), ), } def update_map(self, agent_position): a_x, a_y = maps.to_grid( agent_position[0], agent_position[2], self._coordinate_min, self._coordinate_max, self._map_resolution, ) # Don't draw over the source point if self._top_down_map[a_x, a_y] != maps.MAP_SOURCE_POINT_INDICATOR: color = 10 + min( self._step_count * 245 // self._config.MAX_EPISODE_STEPS, 245 ) thickness = int( np.round(self._map_resolution[0] * 2 / MAP_THICKNESS_SCALAR) ) cv2.line( self._top_down_map, self._previous_xy_location, (a_y, a_x), color, thickness=thickness, ) self._previous_xy_location = (a_y, a_x) return self._top_down_map, a_x, a_y class NavigationTask(habitat.EmbodiedTask): def __init__( self, task_config: Config, sim: Simulator, dataset: Optional[Dataset] = None, ) -> None: task_measurements = [] for measurement_name in task_config.MEASUREMENTS: measurement_cfg = getattr(task_config, measurement_name) is_valid_measurement = hasattr( habitat.tasks.nav.nav_task, # type: ignore measurement_cfg.TYPE, ) assert is_valid_measurement, "invalid measurement type {}".format( measurement_cfg.TYPE ) task_measurements.append( getattr( habitat.tasks.nav.nav_task, # type: ignore measurement_cfg.TYPE, )(sim, measurement_cfg) ) self.measurements = Measurements(task_measurements) task_sensors = [] for sensor_name in task_config.SENSORS: sensor_cfg = getattr(task_config, sensor_name) is_valid_sensor = hasattr( habitat.tasks.nav.nav_task, sensor_cfg.TYPE # type: ignore ) assert is_valid_sensor, "invalid sensor type {}".format( sensor_cfg.TYPE ) task_sensors.append( getattr( habitat.tasks.nav.nav_task, sensor_cfg.TYPE # type: ignore )(sim, sensor_cfg) ) self.sensor_suite = SensorSuite(task_sensors) super().__init__(config=task_config, sim=sim, dataset=dataset) def overwrite_sim_config( self, sim_config: Any, episode: Type[Episode] ) -> Any: return merge_sim_episode_config(sim_config, episode)
[ "numpy.ceil", "habitat.core.simulator.SensorSuite", "numpy.round", "habitat.tasks.utils.cartesian_to_polar", "cv2.line", "numpy.any", "gym.spaces.Box", "numpy.array", "numpy.finfo", "habitat.utils.visualizations.maps.to_grid", "habitat.utils.visualizations.maps.get_topdown_map", "habitat.core....
[((9852, 9914), 'gym.spaces.Box', 'spaces.Box', ([], {'low': '(-np.pi)', 'high': 'np.pi', 'shape': '(1,)', 'dtype': 'np.float'}), '(low=-np.pi, high=np.pi, shape=(1,), dtype=np.float)\n', (9862, 9914), False, 'from gym import spaces\n'), ((10100, 10120), 'numpy.array', 'np.array', (['[0, 0, -1]'], {}), '([0, 0, -1])\n', (10108, 10120), True, 'import numpy as np\n'), ((10335, 10348), 'numpy.array', 'np.array', (['phi'], {}), '(phi)\n', (10343, 10348), True, 'import numpy as np\n'), ((11055, 11140), 'gym.spaces.Box', 'spaces.Box', ([], {'low': '(0.0)', 'high': 'self._max_detection_radius', 'shape': '(1,)', 'dtype': 'np.float'}), '(low=0.0, high=self._max_detection_radius, shape=(1,), dtype=np.float\n )\n', (11065, 11140), False, 'from gym import spaces\n'), ((15050, 15152), 'habitat.utils.visualizations.maps.get_topdown_map', 'maps.get_topdown_map', (['self._sim', 'self._map_resolution', 'self._num_samples', 'self._config.DRAW_BORDER'], {}), '(self._sim, self._map_resolution, self._num_samples,\n self._config.DRAW_BORDER)\n', (15070, 15152), False, 'from habitat.utils.visualizations import maps\n'), ((16890, 17010), 'habitat.utils.visualizations.maps.to_grid', 'maps.to_grid', (['agent_position[0]', 'agent_position[2]', 'self._coordinate_min', 'self._coordinate_max', 'self._map_resolution'], {}), '(agent_position[0], agent_position[2], self._coordinate_min,\n self._coordinate_max, self._map_resolution)\n', (16902, 17010), False, 'from habitat.utils.visualizations import maps\n'), ((18037, 18157), 'habitat.utils.visualizations.maps.to_grid', 'maps.to_grid', (['agent_position[0]', 'agent_position[2]', 'self._coordinate_min', 'self._coordinate_max', 'self._map_resolution'], {}), '(agent_position[0], agent_position[2], self._coordinate_min,\n self._coordinate_max, self._map_resolution)\n', (18049, 18157), False, 'from habitat.utils.visualizations import maps\n'), ((19769, 19800), 'habitat.core.embodied_task.Measurements', 'Measurements', (['task_measurements'], {}), '(task_measurements)\n', (19781, 19800), False, 'from habitat.core.embodied_task import Measurements\n'), ((20395, 20420), 'habitat.core.simulator.SensorSuite', 'SensorSuite', (['task_sensors'], {}), '(task_sensors)\n', (20406, 20420), False, 'from habitat.core.simulator import Simulator, ShortestPathPoint, SensorTypes, SensorSuite\n'), ((5931, 5984), 'numpy.array', 'np.array', (['episode.goals[0].position'], {'dtype': 'np.float32'}), '(episode.goals[0].position, dtype=np.float32)\n', (5939, 5984), True, 'import numpy as np\n'), ((6217, 6290), 'habitat.tasks.utils.cartesian_to_polar', 'cartesian_to_polar', (['(-direction_vector_agent[2])', 'direction_vector_agent[0]'], {}), '(-direction_vector_agent[2], direction_vector_agent[0])\n', (6235, 6290), False, 'from habitat.tasks.utils import cartesian_to_polar, quaternion_rotate_vector\n'), ((6358, 6397), 'numpy.array', 'np.array', (['[rho, -phi]'], {'dtype': 'np.float32'}), '([rho, -phi], dtype=np.float32)\n', (6366, 6397), True, 'import numpy as np\n'), ((10259, 10316), 'habitat.tasks.utils.cartesian_to_polar', 'cartesian_to_polar', (['(-heading_vector[2])', 'heading_vector[0]'], {}), '(-heading_vector[2], heading_vector[0])\n', (10277, 10316), False, 'from habitat.tasks.utils import cartesian_to_polar, quaternion_rotate_vector\n'), ((15584, 15721), 'habitat.utils.visualizations.maps.to_grid', 'maps.to_grid', (['episode.start_position[0]', 'episode.start_position[2]', 'self._coordinate_min', 'self._coordinate_max', 'self._map_resolution'], {}), '(episode.start_position[0], episode.start_position[2], self.\n _coordinate_min, self._coordinate_max, self._map_resolution)\n', (15596, 15721), False, 'from habitat.utils.visualizations import maps\n'), ((16191, 16333), 'habitat.utils.visualizations.maps.to_grid', 'maps.to_grid', (['episode.goals[0].position[0]', 'episode.goals[0].position[2]', 'self._coordinate_min', 'self._coordinate_max', 'self._map_resolution'], {}), '(episode.goals[0].position[0], episode.goals[0].position[2],\n self._coordinate_min, self._coordinate_max, self._map_resolution)\n', (16203, 16333), False, 'from habitat.utils.visualizations import maps\n'), ((18599, 18699), 'cv2.line', 'cv2.line', (['self._top_down_map', 'self._previous_xy_location', '(a_y, a_x)', 'color'], {'thickness': 'thickness'}), '(self._top_down_map, self._previous_xy_location, (a_y, a_x), color,\n thickness=thickness)\n', (18607, 18699), False, 'import cv2\n'), ((8580, 8633), 'numpy.array', 'np.array', (['episode.goals[0].position'], {'dtype': 'np.float32'}), '(episode.goals[0].position, dtype=np.float32)\n', (8588, 8633), True, 'import numpy as np\n'), ((8894, 8967), 'habitat.tasks.utils.cartesian_to_polar', 'cartesian_to_polar', (['(-direction_vector_agent[2])', 'direction_vector_agent[0]'], {}), '(-direction_vector_agent[2], direction_vector_agent[0])\n', (8912, 8967), False, 'from habitat.tasks.utils import cartesian_to_polar, quaternion_rotate_vector\n'), ((9047, 9086), 'numpy.array', 'np.array', (['[rho, -phi]'], {'dtype': 'np.float32'}), '([rho, -phi], dtype=np.float32)\n', (9055, 9086), True, 'import numpy as np\n'), ((12335, 12355), 'numpy.array', 'np.array', (['position_b'], {}), '(position_b)\n', (12343, 12355), True, 'import numpy as np\n'), ((12358, 12378), 'numpy.array', 'np.array', (['position_a'], {}), '(position_a)\n', (12366, 12378), True, 'import numpy as np\n'), ((15236, 15264), 'numpy.any', 'np.any', (['top_down_map'], {'axis': '(1)'}), '(top_down_map, axis=1)\n', (15242, 15264), True, 'import numpy as np\n'), ((15296, 15324), 'numpy.any', 'np.any', (['top_down_map'], {'axis': '(0)'}), '(top_down_map, axis=0)\n', (15302, 15324), True, 'import numpy as np\n'), ((18512, 18572), 'numpy.round', 'np.round', (['(self._map_resolution[0] * 2 / MAP_THICKNESS_SCALAR)'], {}), '(self._map_resolution[0] * 2 / MAP_THICKNESS_SCALAR)\n', (18520, 18572), True, 'import numpy as np\n'), ((5547, 5567), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (5555, 5567), True, 'import numpy as np\n'), ((5590, 5610), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (5598, 5610), True, 'import numpy as np\n'), ((7938, 7958), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (7946, 7958), True, 'import numpy as np\n'), ((7981, 8001), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (7989, 8001), True, 'import numpy as np\n'), ((15865, 15920), 'numpy.ceil', 'np.ceil', (['(self._map_resolution[0] / MAP_THICKNESS_SCALAR)'], {}), '(self._map_resolution[0] / MAP_THICKNESS_SCALAR)\n', (15872, 15920), True, 'import numpy as np\n')]
import numpy as np class Graph: def __init__(self, vertices): self._adjMat = np.zeros((vertices, vertices)) self._vertices = vertices def insert_edge(self, u, v, x=1): self._adjMat[u][v] = x def remove_edge(self, u, v): self._adjMat[u][v] = 0 def exist_edge(self, u, v): return self._adjMat[u][v] != 0 def vertex_count(self): return self._vertices def edge_count(self): count = 0 for i in range(self._vertices): for j in range(self._vertices): if self._adjMat[i][j] != 0: count = count + 1 return count def vertices(self): for i in range(self._vertices): print(i,end=' ') print() def edges(self): for i in range(self._vertices): for j in range(self._vertices): if self._adjMat[i][j] != 0: print(i,'--',j) def outdegree(self, v): count = 0 for j in range(self._vertices): if not self._adjMat[v][j] == 0: count = count + 1 return count def indegree(self, v): count = 0 for i in range(self._vertices): if not self._adjMat[i][v] == 0: count = count + 1 return count def display_adjMat(self): print(self._adjMat) G = Graph(4) print('Graph Adjacency Matrix') G.display_adjMat() print('Vertices: ', G.vertex_count()) G.insert_edge(0, 1, 26) G.insert_edge(0, 2, 16) G.insert_edge(1, 2, 12) G.insert_edge(2, 3, 8) print('Graph Adjacency Matrix') G.display_adjMat() print('Edges Count:', G.edge_count()) print('Vertices:') G.vertices() print('Edges:') G.edges() print('Edges between 1--3:', G.exist_edge(1,3)) print('Edges between 1--2:', G.exist_edge(1,2)) print('Edges between 2--1:', G.exist_edge(2,1)) print('Degree of vertex 2:',G.indegree(2)+G.outdegree(2)) print('In-Degree of vertex 2:',G.indegree(2)) print('Out-Degree of vertex 2:',G.outdegree(2)) print('Graph Adjacency Matrix') G.display_adjMat() G.remove_edge(1,2) print('Graph Adjacency Matrix') G.display_adjMat() print('Edges between 1--2:', G.exist_edge(1,2))
[ "numpy.zeros" ]
[((91, 121), 'numpy.zeros', 'np.zeros', (['(vertices, vertices)'], {}), '((vertices, vertices))\n', (99, 121), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ @author: LiuXin @contact: <EMAIL> @Created on: DATE{TIME} """ from __future__ import print_function, division import os from PIL import Image import numpy as np import torch from torch.utils.data import Dataset from mypath import Path from torchvision import transforms from dataloader.transforms_utils import custom_transforms as tr from dataloader.transforms_utils import augment as au from dataloader.transforms_utils import meta_transforms as meta_t class SkmtDataSet(Dataset): """ PascalVoc dataset """ CLASSES = ('background', 'SAS', 'LHB', 'D', 'HH', 'SUB', 'SUP', 'GL', 'GC', 'SCB', 'INF', 'C', 'TM', 'SHB', 'LHT', 'SAC', 'INS','BBLH','LHBT') PALETTE = np.asarray([[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0], [64, 128, 0]]) CLASSES_PIXS_WEIGHTS=(0.7450,0.0501,0.0016,0.0932 ,0.0611 , 0.0085,0.0092,0.0014,0.0073,0.0012,0.0213) #TODO:取消未出现的类 # NUM_CLASSES = len(CLASSES) NUM_CLASSES=11 def __init__(self, args, base_dir=Path.db_root_dir('skmt'), split='train', ): """ :param base_dir: path to VOC dataset directory :param split: train/val :param transform: transform to apply """ super().__init__() self._base_dir = base_dir self._image_dir = os.path.join(self._base_dir, 'JPEGImages') self._cat_dir = os.path.join(self._base_dir, 'SegmentationClass') if isinstance(split, str): self.split = [split] else: split.sort() self.split = split self.args = args _splits_dir = os.path.join(self._base_dir, 'ImageSets') self.im_ids = [] self.images = [] self.categories = [] for splt in self.split: with open(os.path.join(os.path.join(_splits_dir, splt + '.txt')), "r") as f: lines = f.read().splitlines() for ii, line in enumerate(lines): _image = os.path.join(self._image_dir, line + ".jpg") _cat = os.path.join(self._cat_dir, line + ".png") # print(_image) assert os.path.isfile(_image) assert os.path.isfile(_cat) self.im_ids.append(line) self.images.append(_image) self.categories.append(_cat) assert (len(self.images) == len(self.categories)) # Display stats print('Number of images in {}: {:d}'.format(split, len(self.images))) def __len__(self): return len(self.images) def __getitem__(self, index): _img, _target = self._make_img_gt_point_pair(index) _section=self.get_section(index) sample = {'image': _img, 'label': _target,'section':_section} for split in self.split: if split == "train": for key,value in self.transform_tr(sample).items(): sample[key]=value return sample elif split == 'val': for key,value in self.transform_val(sample).items(): sample[key]=value return sample def get_section(self,index): _name=self.images[index].split('/')[-1] _section=_name.split('_')[0][-2] return int(_section) def _make_img_gt_point_pair(self, index): _img = Image.open(self.images[index]).convert('RGB') _target = Image.open(self.categories[index]) return _img, _target def transform_tr(self, sample): #augm = au.Augment() #sample = augm(sample) composed_transforms = transforms.Compose([ tr.RandomHorizontalFlip(), tr.RandomScaleCrop(base_size=self.args.image_size, crop_size=self.args.crop_size), # tr.FixScaleCrop(crop_size=self.args.crop_size), tr.RandomRotate(10), # tr.RandomGaussianBlur(), tr.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)), tr.ToTensor()] ) return composed_transforms(sample) def transform_val(self, sample): composed_transforms = transforms.Compose([ tr.FixedResize(self.args.crop_size), tr.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)), tr.ToTensor()]) return composed_transforms(sample) # get_ISPRS and encode_segmap generate label map[ def count_section(self): """count the section num :param img_list: :return: """ table={} for i in range(len(self.images)): _section=self.get_section(i) if(_section not in table.keys()): table[_section]=0 table[_section]=table[_section]+1 return table @classmethod def encode_segmap(cls, mask): """Encode segmentation label images as pascal classes Args: mask (np.ndarray): raw segmentation label image of dimension (M, N, 3), in which the Pascal classes are encoded as colours. Returns: (np.ndarray): class map with dimensions (M,N), where the value at a given location is the integer denoting the class index. """ mask = mask.astype(int) label_mask = np.zeros((mask.shape[0], mask.shape[1]), dtype=np.int16) for ii, label in enumerate(cls.PALETTE): label_mask[np.where(np.all(mask == label, axis=-1))[:2]] = ii label_mask = label_mask.astype(int) return label_mask @classmethod def decode_segmap(cls, label_mask): """Decode segmentation class labels into a color image Args: label_mask (np.ndarray): an (M,N) array of integer values denoting the class label at each spatial location. plot (bool, optional): whether to show the resulting color image in a figure. Returns: (np.ndarray, optional): the resulting decoded color image. """ label_colours = cls.PALETTE n_classes = len(label_colours) r = label_mask.copy() g = label_mask.copy() b = label_mask.copy() for ll in range(0, n_classes): r[label_mask == ll] = label_colours[ll, 0] g[label_mask == ll] = label_colours[ll, 1] b[label_mask == ll] = label_colours[ll, 2] rgb = np.zeros((label_mask.shape[0], label_mask.shape[1], 3)) rgb[:, :, 0] = r / 255.0 rgb[:, :, 1] = g / 255.0 rgb[:, :, 2] = b / 255.0 return rgb def __str__(self): return 'skmt(split=' + str(self.split) + ')'
[ "numpy.all", "PIL.Image.open", "dataloader.transforms_utils.custom_transforms.FixedResize", "dataloader.transforms_utils.custom_transforms.Normalize", "dataloader.transforms_utils.custom_transforms.RandomScaleCrop", "os.path.join", "numpy.asarray", "mypath.Path.db_root_dir", "dataloader.transforms_u...
[((756, 927), 'numpy.asarray', 'np.asarray', (['[[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], [128, 0, \n 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0], [64, 128, 0]\n ]'], {}), '([[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128],\n [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0],\n [64, 128, 0]])\n', (766, 927), True, 'import numpy as np\n'), ((1229, 1253), 'mypath.Path.db_root_dir', 'Path.db_root_dir', (['"""skmt"""'], {}), "('skmt')\n", (1245, 1253), False, 'from mypath import Path\n'), ((1550, 1592), 'os.path.join', 'os.path.join', (['self._base_dir', '"""JPEGImages"""'], {}), "(self._base_dir, 'JPEGImages')\n", (1562, 1592), False, 'import os\n'), ((1617, 1666), 'os.path.join', 'os.path.join', (['self._base_dir', '"""SegmentationClass"""'], {}), "(self._base_dir, 'SegmentationClass')\n", (1629, 1666), False, 'import os\n'), ((1855, 1896), 'os.path.join', 'os.path.join', (['self._base_dir', '"""ImageSets"""'], {}), "(self._base_dir, 'ImageSets')\n", (1867, 1896), False, 'import os\n'), ((3659, 3693), 'PIL.Image.open', 'Image.open', (['self.categories[index]'], {}), '(self.categories[index])\n', (3669, 3693), False, 'from PIL import Image\n'), ((5532, 5588), 'numpy.zeros', 'np.zeros', (['(mask.shape[0], mask.shape[1])'], {'dtype': 'np.int16'}), '((mask.shape[0], mask.shape[1]), dtype=np.int16)\n', (5540, 5588), True, 'import numpy as np\n'), ((6641, 6696), 'numpy.zeros', 'np.zeros', (['(label_mask.shape[0], label_mask.shape[1], 3)'], {}), '((label_mask.shape[0], label_mask.shape[1], 3))\n', (6649, 6696), True, 'import numpy as np\n'), ((2217, 2261), 'os.path.join', 'os.path.join', (['self._image_dir', "(line + '.jpg')"], {}), "(self._image_dir, line + '.jpg')\n", (2229, 2261), False, 'import os\n'), ((2285, 2327), 'os.path.join', 'os.path.join', (['self._cat_dir', "(line + '.png')"], {}), "(self._cat_dir, line + '.png')\n", (2297, 2327), False, 'import os\n'), ((2383, 2405), 'os.path.isfile', 'os.path.isfile', (['_image'], {}), '(_image)\n', (2397, 2405), False, 'import os\n'), ((2429, 2449), 'os.path.isfile', 'os.path.isfile', (['_cat'], {}), '(_cat)\n', (2443, 2449), False, 'import os\n'), ((3595, 3625), 'PIL.Image.open', 'Image.open', (['self.images[index]'], {}), '(self.images[index])\n', (3605, 3625), False, 'from PIL import Image\n'), ((3884, 3909), 'dataloader.transforms_utils.custom_transforms.RandomHorizontalFlip', 'tr.RandomHorizontalFlip', ([], {}), '()\n', (3907, 3909), True, 'from dataloader.transforms_utils import custom_transforms as tr\n'), ((3923, 4009), 'dataloader.transforms_utils.custom_transforms.RandomScaleCrop', 'tr.RandomScaleCrop', ([], {'base_size': 'self.args.image_size', 'crop_size': 'self.args.crop_size'}), '(base_size=self.args.image_size, crop_size=self.args.\n crop_size)\n', (3941, 4009), True, 'from dataloader.transforms_utils import custom_transforms as tr\n'), ((4080, 4099), 'dataloader.transforms_utils.custom_transforms.RandomRotate', 'tr.RandomRotate', (['(10)'], {}), '(10)\n', (4095, 4099), True, 'from dataloader.transforms_utils import custom_transforms as tr\n'), ((4152, 4219), 'dataloader.transforms_utils.custom_transforms.Normalize', 'tr.Normalize', ([], {'mean': '(0.485, 0.456, 0.406)', 'std': '(0.229, 0.224, 0.225)'}), '(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))\n', (4164, 4219), True, 'from dataloader.transforms_utils import custom_transforms as tr\n'), ((4233, 4246), 'dataloader.transforms_utils.custom_transforms.ToTensor', 'tr.ToTensor', ([], {}), '()\n', (4244, 4246), True, 'from dataloader.transforms_utils import custom_transforms as tr\n'), ((4407, 4442), 'dataloader.transforms_utils.custom_transforms.FixedResize', 'tr.FixedResize', (['self.args.crop_size'], {}), '(self.args.crop_size)\n', (4421, 4442), True, 'from dataloader.transforms_utils import custom_transforms as tr\n'), ((4456, 4523), 'dataloader.transforms_utils.custom_transforms.Normalize', 'tr.Normalize', ([], {'mean': '(0.485, 0.456, 0.406)', 'std': '(0.229, 0.224, 0.225)'}), '(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))\n', (4468, 4523), True, 'from dataloader.transforms_utils import custom_transforms as tr\n'), ((4537, 4550), 'dataloader.transforms_utils.custom_transforms.ToTensor', 'tr.ToTensor', ([], {}), '()\n', (4548, 4550), True, 'from dataloader.transforms_utils import custom_transforms as tr\n'), ((2045, 2085), 'os.path.join', 'os.path.join', (['_splits_dir', "(splt + '.txt')"], {}), "(_splits_dir, splt + '.txt')\n", (2057, 2085), False, 'import os\n'), ((5671, 5701), 'numpy.all', 'np.all', (['(mask == label)'], {'axis': '(-1)'}), '(mask == label, axis=-1)\n', (5677, 5701), True, 'import numpy as np\n')]
from copy import deepcopy import dendropy from iterpop import iterpop as ip import itertools as it import numpy as np from sortedcontainers import SortedSet def dendropy_tree_to_scipy_linkage_matrix(tree: dendropy.Tree) -> np.array: # scipy linkage format # http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html#scipy.cluster.hierarchy.linkage # simplify tree tree = deepcopy(tree) tree.resolve_polytomies() tree.suppress_unifurcations() assert all(len(node.child_nodes()) in [0, 2] for node in tree) for node in tree.postorder_node_iter(): node.num_leaf_descendants = max( sum(chld.num_leaf_descendants for chld in node.child_node_iter()), 1, ) cluster_id_generator = it.count() for leaf in tree.leaf_node_iter(): if not hasattr(leaf, 'cluster_id'): leaf.cluster_id = next(cluster_id_generator) one_leaf_parents = { leaf.parent_node for leaf in tree.leaf_node_iter() if leaf.parent_node is not None and not ip.popsingleton(leaf.sibling_nodes()).is_leaf() } two_leaf_parents = SortedSet( ( leaf.parent_node for leaf in tree.leaf_node_iter() if leaf.parent_node is not None and ip.popsingleton(leaf.sibling_nodes()).is_leaf() ), key=lambda node: sum(n.edge_length for n in node.child_node_iter()), ) res = [] while len(two_leaf_parents): two_leaf_parent = two_leaf_parents.pop(0) if not hasattr(two_leaf_parent, 'cluster_id'): two_leaf_parent.cluster_id = next(cluster_id_generator) if two_leaf_parent.parent_node is not None: if two_leaf_parent.parent_node in one_leaf_parents: one_leaf_parents.remove(two_leaf_parent.parent_node) two_leaf_parents.add(two_leaf_parent.parent_node) else: one_leaf_parents.add(two_leaf_parent.parent_node) child1, child2 = two_leaf_parent.child_node_iter() assert child1 not in two_leaf_parents assert child2 not in two_leaf_parents # see https://stackoverflow.com/a/40983611/17332200 # for explainer on scipy linkage format joined_cluster1 = child1.cluster_id joined_cluster2 = child2.cluster_id assert None not in (joined_cluster1, joined_cluster2) cluster_distance = child1.edge_length + child2.edge_length cluster_size = two_leaf_parent.num_leaf_descendants res.append([ joined_cluster1, joined_cluster2, float(cluster_distance), cluster_size, ]) return np.array(res)
[ "numpy.array", "itertools.count", "copy.deepcopy" ]
[((421, 435), 'copy.deepcopy', 'deepcopy', (['tree'], {}), '(tree)\n', (429, 435), False, 'from copy import deepcopy\n'), ((785, 795), 'itertools.count', 'it.count', ([], {}), '()\n', (793, 795), True, 'import itertools as it\n'), ((2719, 2732), 'numpy.array', 'np.array', (['res'], {}), '(res)\n', (2727, 2732), True, 'import numpy as np\n')]
# coding: utf-8 # Copyright (c) 2021 AkaiKKRteam. # Distributed under the terms of the Apache License, Version 2.0. import numpy as np from pymatgen.analysis.structure_analyzer import VoronoiConnectivity from pymatgen.core import Structure def min_dist_matrix(structure: Structure) -> float: """make minimum distance of the structure from VoronoiConnectivity(structure) Args: structure (pymatgen.core.structure): structure Returns: float: minium distance of the distance matrix """ n = len(structure.sites) min_dist_matrix = np.zeros((n, n)) vorcon = VoronoiConnectivity(structure) for conn in vorcon.get_connections(): i = conn[0] j = conn[1] d = conn[2] min_dist_matrix[i, j] = d # print(min_dist_matrix) return min_dist_matrix
[ "numpy.zeros", "pymatgen.analysis.structure_analyzer.VoronoiConnectivity" ]
[((569, 585), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (577, 585), True, 'import numpy as np\n'), ((599, 629), 'pymatgen.analysis.structure_analyzer.VoronoiConnectivity', 'VoronoiConnectivity', (['structure'], {}), '(structure)\n', (618, 629), False, 'from pymatgen.analysis.structure_analyzer import VoronoiConnectivity\n')]
"""Implementation of Pointer networks: http://arxiv.org/pdf/1506.03134v1.pdf. """ from __future__ import absolute_import, division, print_function import random import numpy as np import tensorflow as tf from dataset import DataGenerator from pointer import pointer_decoder flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_integer('batch_size', 32, 'Batch size. ') flags.DEFINE_integer('max_steps', 10, 'Number of numbers to sort. ') flags.DEFINE_integer('rnn_size', 32, 'RNN size. ') class PointerNetwork(object): def __init__(self, max_len, input_size, size, num_layers, max_gradient_norm, batch_size, learning_rate, learning_rate_decay_factor): """Create the network. A simplified network that handles only sorting. Args: max_len: maximum length of the model. input_size: size of the inputs data. size: number of units in each layer of the model. num_layers: number of layers in the model. max_gradient_norm: gradients will be clipped to maximally this norm. batch_size: the size of the batches used during training; the model construction is independent of batch_size, so it can be changed after initialization if this is convenient, e.g., for decoding. learning_rate: learning rate to start with. learning_rate_decay_factor: decay learning rate by this much when needed. """ self.batch_size = batch_size self.learning_rate = tf.Variable(float(learning_rate), trainable=False) self.learning_rate_decay_op = self.learning_rate.assign( self.learning_rate * learning_rate_decay_factor) self.global_step = tf.Variable(0, trainable=False) cell = tf.contrib.rnn.GRUCell(size) if num_layers > 1: cell = tf.contrib.rnn.MultiRNNCell([single_cell] * num_layers) self.encoder_inputs = [] self.decoder_inputs = [] self.decoder_targets = [] self.target_weights = [] for i in range(max_len): self.encoder_inputs.append(tf.placeholder( tf.float32, [batch_size, input_size], name="EncoderInput%d" % i)) for i in range(max_len + 1): self.decoder_inputs.append(tf.placeholder( tf.float32, [batch_size, input_size], name="DecoderInput%d" % i)) self.decoder_targets.append(tf.placeholder( tf.float32, [batch_size, max_len + 1], name="DecoderTarget%d" % i)) # one hot self.target_weights.append(tf.placeholder( tf.float32, [batch_size, 1], name="TargetWeight%d" % i)) # Encoder # Need for attention encoder_outputs, final_state = tf.contrib.rnn.static_rnn(cell, self.encoder_inputs, dtype=tf.float32) # Need a dummy output to point on it. End of decoding. encoder_outputs = [tf.zeros([FLAGS.batch_size, FLAGS.rnn_size])] + encoder_outputs # First calculate a concatenation of encoder outputs to put attention on. top_states = [tf.reshape(e, [-1, 1, cell.output_size]) for e in encoder_outputs] attention_states = tf.concat(axis=1, values=top_states) with tf.variable_scope("decoder"): outputs, states, _ = pointer_decoder( self.decoder_inputs, final_state, attention_states, cell) with tf.variable_scope("decoder", reuse=True): predictions, _, inps = pointer_decoder( self.decoder_inputs, final_state, attention_states, cell, feed_prev=True) self.predictions = predictions self.outputs = outputs self.inps = inps # move code below to a separate function as in TF examples def create_feed_dict(self, encoder_input_data, decoder_input_data, decoder_target_data): feed_dict = {} for placeholder, data in zip(self.encoder_inputs, encoder_input_data): feed_dict[placeholder] = data for placeholder, data in zip(self.decoder_inputs, decoder_input_data): feed_dict[placeholder] = data for placeholder, data in zip(self.decoder_targets, decoder_target_data): feed_dict[placeholder] = data for placeholder in self.target_weights: feed_dict[placeholder] = np.ones([self.batch_size, 1]) return feed_dict def step(self): loss = 0.0 for output, target, weight in zip(self.outputs, self.decoder_targets, self.target_weights): loss += tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=target) * weight loss = tf.reduce_mean(loss) test_loss = 0.0 for output, target, weight in zip(self.predictions, self.decoder_targets, self.target_weights): test_loss += tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=target) * weight test_loss = tf.reduce_mean(test_loss) optimizer = tf.train.AdamOptimizer() train_op = optimizer.minimize(loss) train_loss_value = 0.0 test_loss_value = 0.0 correct_order = 0 all_order = 0 with tf.Session() as sess: merged = tf.summary.merge_all() writer = tf.summary.FileWriter("/tmp/pointer_logs", sess.graph) init = tf.global_variables_initializer() sess.run(init) for i in range(100000): encoder_input_data, decoder_input_data, targets_data = dataset.next_batch( FLAGS.batch_size, FLAGS.max_steps) # Train feed_dict = self.create_feed_dict( encoder_input_data, decoder_input_data, targets_data) d_x, l = sess.run([loss, train_op], feed_dict=feed_dict) train_loss_value = 0.9 * train_loss_value + 0.1 * d_x if i % 100 == 0: print('Step: %d' % i) print("Train: ", train_loss_value) encoder_input_data, decoder_input_data, targets_data = dataset.next_batch( FLAGS.batch_size, FLAGS.max_steps, train_mode=False) # Test feed_dict = self.create_feed_dict( encoder_input_data, decoder_input_data, targets_data) inps_ = sess.run(self.inps, feed_dict=feed_dict) predictions = sess.run(self.predictions, feed_dict=feed_dict) test_loss_value = 0.9 * test_loss_value + 0.1 * sess.run(test_loss, feed_dict=feed_dict) if i % 100 == 0: print("Test: ", test_loss_value) predictions_order = np.concatenate([np.expand_dims(prediction, 0) for prediction in predictions]) predictions_order = np.argmax(predictions_order, 2).transpose(1, 0)[:, 0:FLAGS.max_steps] input_order = np.concatenate( [np.expand_dims(encoder_input_data_, 0) for encoder_input_data_ in encoder_input_data]) input_order = np.argsort(input_order, 0).squeeze().transpose(1, 0) + 1 correct_order += np.sum(np.all(predictions_order == input_order, axis=1)) all_order += FLAGS.batch_size if i % 100 == 0: print('Correct order / All order: %f' % (correct_order / all_order)) correct_order = 0 all_order = 0 # print(encoder_input_data, decoder_input_data, targets_data) # print(inps_) if __name__ == "__main__": # TODO: replace other with params pointer_network = PointerNetwork(FLAGS.max_steps, 1, FLAGS.rnn_size, 1, 5, FLAGS.batch_size, 1e-2, 0.95) dataset = DataGenerator() pointer_network.step()
[ "numpy.argsort", "tensorflow.contrib.rnn.GRUCell", "pointer.pointer_decoder", "tensorflow.reduce_mean", "tensorflow.Session", "tensorflow.placeholder", "tensorflow.concat", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.train.AdamOptimizer", "tensorflow.zeros", "tensorflow.contri...
[((7849, 7864), 'dataset.DataGenerator', 'DataGenerator', ([], {}), '()\n', (7862, 7864), False, 'from dataset import DataGenerator\n'), ((1747, 1778), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'trainable': '(False)'}), '(0, trainable=False)\n', (1758, 1778), True, 'import tensorflow as tf\n'), ((1795, 1823), 'tensorflow.contrib.rnn.GRUCell', 'tf.contrib.rnn.GRUCell', (['size'], {}), '(size)\n', (1817, 1823), True, 'import tensorflow as tf\n'), ((2772, 2842), 'tensorflow.contrib.rnn.static_rnn', 'tf.contrib.rnn.static_rnn', (['cell', 'self.encoder_inputs'], {'dtype': 'tf.float32'}), '(cell, self.encoder_inputs, dtype=tf.float32)\n', (2797, 2842), True, 'import tensorflow as tf\n'), ((3219, 3255), 'tensorflow.concat', 'tf.concat', ([], {'axis': '(1)', 'values': 'top_states'}), '(axis=1, values=top_states)\n', (3228, 3255), True, 'import tensorflow as tf\n'), ((4668, 4688), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), '(loss)\n', (4682, 4688), True, 'import tensorflow as tf\n'), ((4943, 4968), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['test_loss'], {}), '(test_loss)\n', (4957, 4968), True, 'import tensorflow as tf\n'), ((4990, 5014), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {}), '()\n', (5012, 5014), True, 'import tensorflow as tf\n'), ((1870, 1925), 'tensorflow.contrib.rnn.MultiRNNCell', 'tf.contrib.rnn.MultiRNNCell', (['([single_cell] * num_layers)'], {}), '([single_cell] * num_layers)\n', (1897, 1925), True, 'import tensorflow as tf\n'), ((3103, 3143), 'tensorflow.reshape', 'tf.reshape', (['e', '[-1, 1, cell.output_size]'], {}), '(e, [-1, 1, cell.output_size])\n', (3113, 3143), True, 'import tensorflow as tf\n'), ((3270, 3298), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""decoder"""'], {}), "('decoder')\n", (3287, 3298), True, 'import tensorflow as tf\n'), ((3333, 3406), 'pointer.pointer_decoder', 'pointer_decoder', (['self.decoder_inputs', 'final_state', 'attention_states', 'cell'], {}), '(self.decoder_inputs, final_state, attention_states, cell)\n', (3348, 3406), False, 'from pointer import pointer_decoder\n'), ((3438, 3478), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""decoder"""'], {'reuse': '(True)'}), "('decoder', reuse=True)\n", (3455, 3478), True, 'import tensorflow as tf\n'), ((3515, 3608), 'pointer.pointer_decoder', 'pointer_decoder', (['self.decoder_inputs', 'final_state', 'attention_states', 'cell'], {'feed_prev': '(True)'}), '(self.decoder_inputs, final_state, attention_states, cell,\n feed_prev=True)\n', (3530, 3608), False, 'from pointer import pointer_decoder\n'), ((4356, 4385), 'numpy.ones', 'np.ones', (['[self.batch_size, 1]'], {}), '([self.batch_size, 1])\n', (4363, 4385), True, 'import numpy as np\n'), ((5184, 5196), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (5194, 5196), True, 'import tensorflow as tf\n'), ((5227, 5249), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), '()\n', (5247, 5249), True, 'import tensorflow as tf\n'), ((5271, 5325), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['"""/tmp/pointer_logs"""', 'sess.graph'], {}), "('/tmp/pointer_logs', sess.graph)\n", (5292, 5325), True, 'import tensorflow as tf\n'), ((5345, 5378), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (5376, 5378), True, 'import tensorflow as tf\n'), ((2132, 2211), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[batch_size, input_size]'], {'name': "('EncoderInput%d' % i)"}), "(tf.float32, [batch_size, input_size], name='EncoderInput%d' % i)\n", (2146, 2211), True, 'import tensorflow as tf\n'), ((2307, 2386), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[batch_size, input_size]'], {'name': "('DecoderInput%d' % i)"}), "(tf.float32, [batch_size, input_size], name='DecoderInput%d' % i)\n", (2321, 2386), True, 'import tensorflow as tf\n'), ((2445, 2531), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[batch_size, max_len + 1]'], {'name': "('DecoderTarget%d' % i)"}), "(tf.float32, [batch_size, max_len + 1], name=\n 'DecoderTarget%d' % i)\n", (2459, 2531), True, 'import tensorflow as tf\n'), ((2595, 2665), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[batch_size, 1]'], {'name': "('TargetWeight%d' % i)"}), "(tf.float32, [batch_size, 1], name='TargetWeight%d' % i)\n", (2609, 2665), True, 'import tensorflow as tf\n'), ((2934, 2978), 'tensorflow.zeros', 'tf.zeros', (['[FLAGS.batch_size, FLAGS.rnn_size]'], {}), '([FLAGS.batch_size, FLAGS.rnn_size])\n', (2942, 2978), True, 'import tensorflow as tf\n'), ((4573, 4642), 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'logits': 'output', 'labels': 'target'}), '(logits=output, labels=target)\n', (4612, 4642), True, 'import tensorflow as tf\n'), ((4843, 4912), 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'logits': 'output', 'labels': 'target'}), '(logits=output, labels=target)\n', (4882, 4912), True, 'import tensorflow as tf\n'), ((7166, 7214), 'numpy.all', 'np.all', (['(predictions_order == input_order)'], {'axis': '(1)'}), '(predictions_order == input_order, axis=1)\n', (7172, 7214), True, 'import numpy as np\n'), ((6715, 6744), 'numpy.expand_dims', 'np.expand_dims', (['prediction', '(0)'], {}), '(prediction, 0)\n', (6729, 6744), True, 'import numpy as np\n'), ((6951, 6989), 'numpy.expand_dims', 'np.expand_dims', (['encoder_input_data_', '(0)'], {}), '(encoder_input_data_, 0)\n', (6965, 6989), True, 'import numpy as np\n'), ((6813, 6844), 'numpy.argmax', 'np.argmax', (['predictions_order', '(2)'], {}), '(predictions_order, 2)\n', (6822, 6844), True, 'import numpy as np\n'), ((7068, 7094), 'numpy.argsort', 'np.argsort', (['input_order', '(0)'], {}), '(input_order, 0)\n', (7078, 7094), True, 'import numpy as np\n')]
import cv2 import numpy as np corners = np.array([[0, 0], [0, 1], [2, 0]]) # given corner computer the distance matrix M = get_graph(corners, 1) print(M)
[ "numpy.array" ]
[((41, 75), 'numpy.array', 'np.array', (['[[0, 0], [0, 1], [2, 0]]'], {}), '([[0, 0], [0, 1], [2, 0]])\n', (49, 75), True, 'import numpy as np\n')]
# !/usr/bin/env python # encoding: utf-8 # Copyright 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """Main RLQA retriever training script.""" import argparse import json import os import sys import subprocess import logging from termcolor import colored from tqdm import tqdm import numpy as np import torch from rlqa.retriever import utils, vector, config, data from rlqa.retriever import RLDocRetriever from rlqa import DATA_DIR as RLQA_DATA logger = logging.getLogger() # ------------------------------------------------------------------------------ # Training arguments. # ------------------------------------------------------------------------------ # Defaults DATA_DIR = os.path.join(RLQA_DATA, 'datasets') MODEL_DIR = os.path.join(RLQA_DATA, 'rlmodels') EMBED_DIR = os.path.join(RLQA_DATA, 'embeddings') def str2bool(v): return v.lower() in ('yes', 'true', 't', '1', 'y') def add_train_args(parser): """Adds commandline arguments pertaining to training a model. These are different from the arguments dictating the model architecture. """ parser.register('type', 'bool', str2bool) # Runtime environment runtime = parser.add_argument_group('Environment') runtime.add_argument('--no-cuda', type='bool', default=False, help='Train on CPU, even if GPUs are available.') runtime.add_argument('--gpu', type=int, default=-1, help='Run on a specific GPU') runtime.add_argument('--data-workers', type=int, default=5, help='Number of subprocesses for data loading') runtime.add_argument('--parallel', type='bool', default=False, help='Use DataParallel on all available GPUs') runtime.add_argument('--random-seed', type=int, default=712, help=('Random seed for all numpy/torch/cuda ' 'operations (for reproducibility)')) runtime.add_argument('--num-epochs', type=int, default=100, help='Train data iterations') runtime.add_argument('--batch-size', type=int, default=50, help='Batch size for training') runtime.add_argument('--test-batch-size', type=int, default=10, help='Batch size during validation/testing') # Files files = parser.add_argument_group('Filesystem') files.add_argument('--model-dir', type=str, default=MODEL_DIR, help='Directory for saved models/checkpoints/logs') files.add_argument('--model-name', type=str, default='', help='Unique model identifier (.mdl, .txt, .checkpoint)') files.add_argument('--data-dir', type=str, default=DATA_DIR, help='Directory of training/validation data') files.add_argument('--train-file', type=str, default='SQuAD-v1.1-train-regexp-processed.txt', help='train file') files.add_argument('--dev-file', type=str, default='SQuAD-v1.1-dev-regexp-processed.txt', help='dev file') files.add_argument('--embed-dir', type=str, default=EMBED_DIR, help='Directory of pre-trained embedding files') files.add_argument('--embedding-file', type=str, default='glove.6B.300d.txt', help='Space-separated pretrained embeddings file') # Saving + loading save_load = parser.add_argument_group('Saving/Loading') save_load.add_argument('--checkpoint', type='bool', default=False, help='Save model + optimizer state after each epoch') save_load.add_argument('--pretrained', type=str, default='', help='Path to a pretrained model to warm-start with') save_load.add_argument('--expand-dictionary', type='bool', default=False, help='Expand dictionary of pretrained model to ' + 'include training/dev words of new data') # Data preprocessing preprocess = parser.add_argument_group('Preprocessing') preprocess.add_argument('--uncased-question', type='bool', default=True, help='Question words will be lower-cased') preprocess.add_argument('--uncased-doc', type='bool', default=True, help='Document words will be lower-cased') preprocess.add_argument('--restrict-vocab', type='bool', default=False, help='Only use pre-trained words in embedding_file') preprocess.add_argument('--restrict-vocab-size', type=int, default=None, help='Only use this number of external vocabulary') # General general = parser.add_argument_group('General') general.add_argument('--valid-metric', type=str, default='hit', help='The evaluation metric used for model selection') general.add_argument('--display-iter', type=int, default=25, help='Log state after every <display_iter> epochs') general.add_argument('--metrics', type=str, choices=['precision', 'recall', 'F1', 'map', 'hit', 'hit@5'], help='metrics to display when training', nargs='+', default=['precision', 'hit', 'hit@5']) def set_defaults(args): """Make sure the commandline arguments are initialized properly.""" # Check critical files exist args.train_file = os.path.join(args.data_dir, args.train_file) if not os.path.isfile(args.train_file): raise IOError('No such file: %s' % args.train_file) args.dev_file = os.path.join(args.data_dir, args.dev_file) if not os.path.isfile(args.dev_file): raise IOError('No such file: %s' % args.dev_file) if args.embedding_file: args.embedding_file = os.path.join(args.embed_dir, args.embedding_file) if not os.path.isfile(args.embedding_file): raise IOError('No such file: %s' % args.embedding_file) # Set model directory subprocess.call(['mkdir', '-p', args.model_dir]) # Set model name if not args.model_name: import uuid import time args.model_name = time.strftime("%Y%m%d-") + str(uuid.uuid4())[:8] # Set log + model file names args.log_file = os.path.join(args.model_dir, args.model_name + '.txt') args.model_file = os.path.join(args.model_dir, args.model_name + '.mdl') # Embeddings options if args.embedding_file: with open(args.embedding_file) as f: dim = len(f.readline().strip().split(' ')) - 1 args.embedding_dim = dim elif not args.embedding_dim: raise RuntimeError('Either embedding_file or embedding_dim ' 'needs to be specified.') # Make sure tune_partial and fix_embeddings are consistent. if args.tune_partial > 0 and args.fix_embeddings: logger.warning('WARN: fix_embeddings set to False as tune_partial > 0.') args.fix_embeddings = False # Make sure fix_embeddings and embedding_file are consistent if args.fix_embeddings: if not (args.embedding_file or args.pretrained): logger.warning('WARN: fix_embeddings set to False ' 'as embeddings are random.') args.fix_embeddings = False # Make sure ranker return more docs than candidate docs to return to the reformulator if args.ranker_doc_max < args.candidate_doc_max: raise RuntimeError('ranker-doc-max >= candidate-doc-max.') return args # ------------------------------------------------------------------------------ # Initalization from scratch. # ------------------------------------------------------------------------------ def init_from_scratch(args, train_exs, dev_exs): """New model, new data, new dictionary. """ # Build a dictionary from the pretrained embeddings file logger.info('-' * 100) # Initialize model word_dict = data.Dictionary() # do not use vocabulary in the dataset model = RLDocRetriever(config.get_model_args(args), word_dict) # Load pretrained embeddings for words in dictionary if args.embedding_file: words = utils.index_embedding_words(args.embedding_file) model.expand_dictionary(words) model.load_embeddings(model.word_dict, args.embedding_file) return model # ------------------------------------------------------------------------------ # Train loop. # ------------------------------------------------------------------------------ def train(args, data_loader, model, global_stats): """Run through one epoch of model training with the provided data loader.""" # Initialize meters + timers train_loss = utils.AverageMeter() metrics_names = args.metrics # meters = {k: utils.AverageMeter() for k in metrics_names} epoch_time = utils.Timer() # Run one epoch for idx, ex in enumerate(data_loader): loss, batch_size, metrics = model.update(ex) train_loss.update(loss, batch_size) metrics_first = {k: np.mean([m[k] for m in metrics[0]]).item() for k in metrics_names} metrics_last = {k: np.mean([m[k] for m in metrics[-1]]).item() for k in metrics_names} # [meters[k].update(metrics_first[k], batch_size) for k in meters] if idx % args.display_iter == 0: logger.info(f'train: Epoch = {global_stats["epoch"]} | iter = {idx}/{ len(data_loader)} | ' + f'loss = {train_loss.avg:.2f} | elapsed time = {global_stats["timer"].time():.2f} (s)') metrics_last = {k: colored(f'{metrics_last[k]*100:.2f}%', color='green') if metrics_first[k] < metrics_last[k] else colored(f'{metrics_last[k]*100:.2f}%', color='red') for k in metrics_names} if len(metrics_names): logger.info(f'r0: ' + ' | '.join([f'{k}: {metrics_first[k]*100:.2f}%' for k in metrics_names])) logger.info(f'r{args.reformulate_rounds}: ' + ' | '.join([f'{k}: {metrics_last[k]}' for k in metrics_names])) train_loss.reset() # [meters[k].reset() for k in meters] # [meters_ext[k].reset() for k in meters_ext] logger.info(f'train: Epoch {global_stats["epoch"]} done. Time for epoch = {epoch_time.time():.2f} (s)') # Checkpoint if args.checkpoint: model.checkpoint(args.model_file + '.checkpoint', global_stats['epoch'] + 1) # ------------------------------------------------------------------------------ # Validation loops. Includes functions that # use different metrics and implementations. # ------------------------------------------------------------------------------ def validate(args, data_loader, model, global_stats, mode): """Run one full validation. """ eval_time = utils.Timer() meter = utils.AverageMeter() # Make predictions examples = 0 for idx, ex in tqdm(enumerate(data_loader), total=len(data_loader)): batch_size, metrics = model.retrieve(ex) metrics_last = {k: np.mean([m[k] for m in metrics[-1]]).item() for k in args.metrics} meter.update(metrics_last[args.valid_metric], batch_size) # If getting train accuracies, sample max 10k examples += batch_size if mode == 'train' and examples >= 1e4: break logger.info(f'{mode} valid: Epoch = {global_stats["epoch"]} | {args.valid_metric} = {meter.avg*100:.2f}% | ' + f'examples = {examples} | valid time = {eval_time.time():.2f} (s)') return {args.valid_metric: meter.avg} # ------------------------------------------------------------------------------ # Main. # ------------------------------------------------------------------------------ def main(args): # -------------------------------------------------------------------------- # DATA logger.info('-' * 100) logger.info('Load data files') train_exs = utils.load_data(args.train_file) logger.info('Num train examples = %d' % len(train_exs)) dev_exs = utils.load_data(args.dev_file) logger.info('Num dev examples = %d' % len(dev_exs)) # -------------------------------------------------------------------------- # MODEL logger.info('-' * 100) start_epoch = 0 if args.checkpoint and os.path.isfile(args.model_file + '.checkpoint'): # Just resume training, no modifications. logger.info('Found a checkpoint...') checkpoint_file = args.model_file + '.checkpoint' model, start_epoch = RLDocRetriever.load_checkpoint(checkpoint_file, args) else: # Training starts fresh. But the model state is either pretrained or # newly (randomly) initialized. if args.pretrained: logger.info('Using pretrained model...') model = RLDocRetriever.load(args.pretrained, args) if args.expand_dictionary: logger.info('Expanding dictionary for new data...') # Add words in training + dev examples words = utils.load_words(args, train_exs + dev_exs) added = model.expand_dictionary(words) # Load pretrained embeddings for added words if args.embedding_file: model.load_embeddings(added, args.embedding_file) else: logger.info('Training model from scratch...') model = init_from_scratch(args, train_exs, dev_exs) # Set up partial tuning of embeddings if args.tune_partial > 0: logger.info('-' * 100) logger.info('Counting %d most frequent question words' % args.tune_partial) top_words = utils.top_question_words( args, train_exs, model.word_dict ) for word in top_words[:5]: logger.info(word) logger.info('...') for word in top_words[-6:-1]: logger.info(word) model.tune_embeddings([w[0] for w in top_words]) # Set up optimizer model.init_optimizer() # Use the GPU? if args.cuda: model.cuda() # Use multiple GPUs? if args.parallel: model.parallelize() # -------------------------------------------------------------------------- # DATA ITERATORS # Two datasets: train and dev. If we sort by length it's faster. logger.info('-' * 100) logger.info('Make data loaders') train_dataset = data.RetriverDataset(train_exs) # train_sampler = torch.utils.data.sampler.RandomSampler(train_dataset) train_sampler = torch.utils.data.sampler.SequentialSampler(train_dataset) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=args.batch_size, sampler=train_sampler, num_workers=args.data_workers, collate_fn=vector.batchify, pin_memory=args.cuda, ) train_dev_loader = torch.utils.data.DataLoader( train_dataset, batch_size=args.test_batch_size, sampler=train_sampler, num_workers=args.data_workers, collate_fn=vector.batchify, pin_memory=args.cuda, ) dev_dataset = data.RetriverDataset(dev_exs) dev_sampler = torch.utils.data.sampler.SequentialSampler(dev_dataset) dev_loader = torch.utils.data.DataLoader( dev_dataset, batch_size=args.test_batch_size, sampler=dev_sampler, num_workers=args.data_workers, collate_fn=vector.batchify, pin_memory=args.cuda, ) # ------------------------------------------------------------------------- # PRINT CONFIG logger.info('-' * 100) logger.info('CONFIG:\n%s' % json.dumps(vars(args), indent=4, sort_keys=True)) # -------------------------------------------------------------------------- # TRAIN/VALID LOOP logger.info('-' * 100) logger.info('Starting training...') stats = {'timer': utils.Timer(), 'epoch': 0, 'best_valid': 0} for epoch in range(start_epoch, args.num_epochs): stats['epoch'] = epoch # Train train(args, train_loader, model, stats) # Validate train validate(args, train_dev_loader, model, stats, mode='train') # Validate dev result = validate(args, dev_loader, model, stats, mode='dev') # Save best valid if result[args.valid_metric] > stats['best_valid']: logger.info( colored(f'Best valid: {args.valid_metric} = {result[args.valid_metric]*100:.2f}% ', attrs=['bold']) + colored(f'(epoch {stats["epoch"]}, {model.updates} updates)', attrs=['bold'])) model.save(args.model_file) stats['best_valid'] = result[args.valid_metric] if __name__ == '__main__': # Parse cmdline args and setup environment parser = argparse.ArgumentParser( 'RLQA Document Retriever', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) add_train_args(parser) config.add_model_args(parser) args = parser.parse_args() set_defaults(args) # Set cuda args.cuda = not args.no_cuda and torch.cuda.is_available() if args.cuda: torch.cuda.set_device(args.gpu) # Set random state np.random.seed(args.random_seed) torch.manual_seed(args.random_seed) if args.cuda: torch.cuda.manual_seed(args.random_seed) # Set logging logger.setLevel(logging.DEBUG) fmt = logging.Formatter('%(asctime)s: [ %(message)s ]', '%m/%d/%Y %I:%M:%S %p') console = logging.StreamHandler() console.setFormatter(fmt) logger.addHandler(console) if args.log_file: if args.checkpoint: logfile = logging.FileHandler(args.log_file, 'a') else: logfile = logging.FileHandler(args.log_file, 'w') logfile.setFormatter(fmt) logger.addHandler(logfile) logger.info('COMMAND: %s' % ' '.join(sys.argv)) # Run! main(args)
[ "logging.getLogger", "logging.StreamHandler", "rlqa.retriever.utils.top_question_words", "rlqa.retriever.data.Dictionary", "rlqa.retriever.utils.Timer", "torch.cuda.is_available", "numpy.mean", "rlqa.retriever.RLDocRetriever.load_checkpoint", "argparse.ArgumentParser", "torch.utils.data.sampler.Se...
[((586, 605), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (603, 605), False, 'import logging\n'), ((816, 851), 'os.path.join', 'os.path.join', (['RLQA_DATA', '"""datasets"""'], {}), "(RLQA_DATA, 'datasets')\n", (828, 851), False, 'import os\n'), ((864, 899), 'os.path.join', 'os.path.join', (['RLQA_DATA', '"""rlmodels"""'], {}), "(RLQA_DATA, 'rlmodels')\n", (876, 899), False, 'import os\n'), ((912, 949), 'os.path.join', 'os.path.join', (['RLQA_DATA', '"""embeddings"""'], {}), "(RLQA_DATA, 'embeddings')\n", (924, 949), False, 'import os\n'), ((5625, 5669), 'os.path.join', 'os.path.join', (['args.data_dir', 'args.train_file'], {}), '(args.data_dir, args.train_file)\n', (5637, 5669), False, 'import os\n'), ((5794, 5836), 'os.path.join', 'os.path.join', (['args.data_dir', 'args.dev_file'], {}), '(args.data_dir, args.dev_file)\n', (5806, 5836), False, 'import os\n'), ((6196, 6244), 'subprocess.call', 'subprocess.call', (["['mkdir', '-p', args.model_dir]"], {}), "(['mkdir', '-p', args.model_dir])\n", (6211, 6244), False, 'import subprocess\n'), ((6464, 6518), 'os.path.join', 'os.path.join', (['args.model_dir', "(args.model_name + '.txt')"], {}), "(args.model_dir, args.model_name + '.txt')\n", (6476, 6518), False, 'import os\n'), ((6541, 6595), 'os.path.join', 'os.path.join', (['args.model_dir', "(args.model_name + '.mdl')"], {}), "(args.model_dir, args.model_name + '.mdl')\n", (6553, 6595), False, 'import os\n'), ((8142, 8159), 'rlqa.retriever.data.Dictionary', 'data.Dictionary', ([], {}), '()\n', (8157, 8159), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((8904, 8924), 'rlqa.retriever.utils.AverageMeter', 'utils.AverageMeter', ([], {}), '()\n', (8922, 8924), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((9041, 9054), 'rlqa.retriever.utils.Timer', 'utils.Timer', ([], {}), '()\n', (9052, 9054), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((11102, 11115), 'rlqa.retriever.utils.Timer', 'utils.Timer', ([], {}), '()\n', (11113, 11115), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((11128, 11148), 'rlqa.retriever.utils.AverageMeter', 'utils.AverageMeter', ([], {}), '()\n', (11146, 11148), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((12226, 12258), 'rlqa.retriever.utils.load_data', 'utils.load_data', (['args.train_file'], {}), '(args.train_file)\n', (12241, 12258), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((12333, 12363), 'rlqa.retriever.utils.load_data', 'utils.load_data', (['args.dev_file'], {}), '(args.dev_file)\n', (12348, 12363), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((14769, 14800), 'rlqa.retriever.data.RetriverDataset', 'data.RetriverDataset', (['train_exs'], {}), '(train_exs)\n', (14789, 14800), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((14898, 14955), 'torch.utils.data.sampler.SequentialSampler', 'torch.utils.data.sampler.SequentialSampler', (['train_dataset'], {}), '(train_dataset)\n', (14940, 14955), False, 'import torch\n'), ((14976, 15159), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_dataset'], {'batch_size': 'args.batch_size', 'sampler': 'train_sampler', 'num_workers': 'args.data_workers', 'collate_fn': 'vector.batchify', 'pin_memory': 'args.cuda'}), '(train_dataset, batch_size=args.batch_size,\n sampler=train_sampler, num_workers=args.data_workers, collate_fn=vector\n .batchify, pin_memory=args.cuda)\n', (15003, 15159), False, 'import torch\n'), ((15229, 15417), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_dataset'], {'batch_size': 'args.test_batch_size', 'sampler': 'train_sampler', 'num_workers': 'args.data_workers', 'collate_fn': 'vector.batchify', 'pin_memory': 'args.cuda'}), '(train_dataset, batch_size=args.test_batch_size,\n sampler=train_sampler, num_workers=args.data_workers, collate_fn=vector\n .batchify, pin_memory=args.cuda)\n', (15256, 15417), False, 'import torch\n'), ((15483, 15512), 'rlqa.retriever.data.RetriverDataset', 'data.RetriverDataset', (['dev_exs'], {}), '(dev_exs)\n', (15503, 15512), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((15531, 15586), 'torch.utils.data.sampler.SequentialSampler', 'torch.utils.data.sampler.SequentialSampler', (['dev_dataset'], {}), '(dev_dataset)\n', (15573, 15586), False, 'import torch\n'), ((15604, 15788), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dev_dataset'], {'batch_size': 'args.test_batch_size', 'sampler': 'dev_sampler', 'num_workers': 'args.data_workers', 'collate_fn': 'vector.batchify', 'pin_memory': 'args.cuda'}), '(dev_dataset, batch_size=args.test_batch_size,\n sampler=dev_sampler, num_workers=args.data_workers, collate_fn=vector.\n batchify, pin_memory=args.cuda)\n', (15631, 15788), False, 'import torch\n'), ((17151, 17262), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""RLQA Document Retriever"""'], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "('RLQA Document Retriever', formatter_class=argparse\n .ArgumentDefaultsHelpFormatter)\n", (17174, 17262), False, 'import argparse\n'), ((17311, 17340), 'rlqa.retriever.config.add_model_args', 'config.add_model_args', (['parser'], {}), '(parser)\n', (17332, 17340), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((17560, 17592), 'numpy.random.seed', 'np.random.seed', (['args.random_seed'], {}), '(args.random_seed)\n', (17574, 17592), True, 'import numpy as np\n'), ((17597, 17632), 'torch.manual_seed', 'torch.manual_seed', (['args.random_seed'], {}), '(args.random_seed)\n', (17614, 17632), False, 'import torch\n'), ((17764, 17837), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s: [ %(message)s ]"""', '"""%m/%d/%Y %I:%M:%S %p"""'], {}), "('%(asctime)s: [ %(message)s ]', '%m/%d/%Y %I:%M:%S %p')\n", (17781, 17837), False, 'import logging\n'), ((17880, 17903), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (17901, 17903), False, 'import logging\n'), ((5681, 5712), 'os.path.isfile', 'os.path.isfile', (['args.train_file'], {}), '(args.train_file)\n', (5695, 5712), False, 'import os\n'), ((5848, 5877), 'os.path.isfile', 'os.path.isfile', (['args.dev_file'], {}), '(args.dev_file)\n', (5862, 5877), False, 'import os\n'), ((5995, 6044), 'os.path.join', 'os.path.join', (['args.embed_dir', 'args.embedding_file'], {}), '(args.embed_dir, args.embedding_file)\n', (6007, 6044), False, 'import os\n'), ((8227, 8254), 'rlqa.retriever.config.get_model_args', 'config.get_model_args', (['args'], {}), '(args)\n', (8248, 8254), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((8369, 8417), 'rlqa.retriever.utils.index_embedding_words', 'utils.index_embedding_words', (['args.embedding_file'], {}), '(args.embedding_file)\n', (8396, 8417), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((12588, 12635), 'os.path.isfile', 'os.path.isfile', (["(args.model_file + '.checkpoint')"], {}), "(args.model_file + '.checkpoint')\n", (12602, 12635), False, 'import os\n'), ((12819, 12872), 'rlqa.retriever.RLDocRetriever.load_checkpoint', 'RLDocRetriever.load_checkpoint', (['checkpoint_file', 'args'], {}), '(checkpoint_file, args)\n', (12849, 12872), False, 'from rlqa.retriever import RLDocRetriever\n'), ((16254, 16267), 'rlqa.retriever.utils.Timer', 'utils.Timer', ([], {}), '()\n', (16265, 16267), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((17448, 17473), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (17471, 17473), False, 'import torch\n'), ((17500, 17531), 'torch.cuda.set_device', 'torch.cuda.set_device', (['args.gpu'], {}), '(args.gpu)\n', (17521, 17531), False, 'import torch\n'), ((17659, 17699), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['args.random_seed'], {}), '(args.random_seed)\n', (17681, 17699), False, 'import torch\n'), ((6060, 6095), 'os.path.isfile', 'os.path.isfile', (['args.embedding_file'], {}), '(args.embedding_file)\n', (6074, 6095), False, 'import os\n'), ((6361, 6385), 'time.strftime', 'time.strftime', (['"""%Y%m%d-"""'], {}), "('%Y%m%d-')\n", (6374, 6385), False, 'import time\n'), ((13101, 13143), 'rlqa.retriever.RLDocRetriever.load', 'RLDocRetriever.load', (['args.pretrained', 'args'], {}), '(args.pretrained, args)\n', (13120, 13143), False, 'from rlqa.retriever import RLDocRetriever\n'), ((13989, 14047), 'rlqa.retriever.utils.top_question_words', 'utils.top_question_words', (['args', 'train_exs', 'model.word_dict'], {}), '(args, train_exs, model.word_dict)\n', (14013, 14047), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((18037, 18076), 'logging.FileHandler', 'logging.FileHandler', (['args.log_file', '"""a"""'], {}), "(args.log_file, 'a')\n", (18056, 18076), False, 'import logging\n'), ((18113, 18152), 'logging.FileHandler', 'logging.FileHandler', (['args.log_file', '"""w"""'], {}), "(args.log_file, 'w')\n", (18132, 18152), False, 'import logging\n'), ((13330, 13373), 'rlqa.retriever.utils.load_words', 'utils.load_words', (['args', '(train_exs + dev_exs)'], {}), '(args, train_exs + dev_exs)\n', (13346, 13373), False, 'from rlqa.retriever import utils, vector, config, data\n'), ((6392, 6404), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (6402, 6404), False, 'import uuid\n'), ((9245, 9280), 'numpy.mean', 'np.mean', (['[m[k] for m in metrics[0]]'], {}), '([m[k] for m in metrics[0]])\n', (9252, 9280), True, 'import numpy as np\n'), ((9339, 9375), 'numpy.mean', 'np.mean', (['[m[k] for m in metrics[-1]]'], {}), '([m[k] for m in metrics[-1]])\n', (9346, 9375), True, 'import numpy as np\n'), ((9773, 9828), 'termcolor.colored', 'colored', (['f"""{metrics_last[k] * 100:.2f}%"""'], {'color': '"""green"""'}), "(f'{metrics_last[k] * 100:.2f}%', color='green')\n", (9780, 9828), False, 'from termcolor import colored\n'), ((9926, 9979), 'termcolor.colored', 'colored', (['f"""{metrics_last[k] * 100:.2f}%"""'], {'color': '"""red"""'}), "(f'{metrics_last[k] * 100:.2f}%', color='red')\n", (9933, 9979), False, 'from termcolor import colored\n'), ((11339, 11375), 'numpy.mean', 'np.mean', (['[m[k] for m in metrics[-1]]'], {}), '([m[k] for m in metrics[-1]])\n', (11346, 11375), True, 'import numpy as np\n'), ((16765, 16876), 'termcolor.colored', 'colored', (['f"""Best valid: {args.valid_metric} = {result[args.valid_metric] * 100:.2f}% """'], {'attrs': "['bold']"}), "(\n f'Best valid: {args.valid_metric} = {result[args.valid_metric] * 100:.2f}% '\n , attrs=['bold'])\n", (16772, 16876), False, 'from termcolor import colored\n'), ((16883, 16960), 'termcolor.colored', 'colored', (['f"""(epoch {stats[\'epoch\']}, {model.updates} updates)"""'], {'attrs': "['bold']"}), '(f"(epoch {stats[\'epoch\']}, {model.updates} updates)", attrs=[\'bold\'])\n', (16890, 16960), False, 'from termcolor import colored\n')]
# Copyright 2021 PCL & PKU # 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 os import argparse import numpy as np import time from mindspore import context from mindspore import Tensor from mindspore.nn.optim import LARS, Momentum from mindspore.train.model import Model, ParallelMode from mindspore.train.loss_scale_manager import FixedLossScaleManager from mindspore.communication.management import init import mindspore.dataset as ds import mindspore.dataset.engine as de from mlperf_logging import mllog from dataset import create_dataset from lr_generator import get_lr from resnet import resnet50 from metric import DistAccuracy, ClassifyCorrectCell from callback import StateMonitor from cross_entropy import CrossEntropySmooth from cfg_parser import merge_args import moxing as mox os.environ['MINDSPORE_HCCL_CONFIG_PATH'] = os.getenv('RANK_TABLE_FILE') device_id = int(os.getenv('DEVICE_ID')) # 0 ~ 7 local_rank = int(os.getenv('RANK_ID')) # local_rank device_num = int(os.getenv('RANK_SIZE')) # world_size log_filename = os.path.join(os.getcwd(), "resnet50_rank"+ str(local_rank) +".log") context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=False) context.set_context(device_id=device_id) def parse_args(): parser = argparse.ArgumentParser(description='Image classification') # cloud parser.add_argument('--data_url', type=str, default=None, help='data_url') parser.add_argument('--train_url', type=str, default='./', help='train_url') # train datasets parser.add_argument('--dataset_path', type=str, default='/opt/npu/datasets/imagenet/train', help='Dataset path') parser.add_argument('--train_image_size', type=int, default=224, help='train_image_size') parser.add_argument('--crop_min', type=float, default=0.08, help='Dataset path') parser.add_argument('--batch_size', type=int, default=16, help='batch_size') parser.add_argument('--train_num_workers', type=int, default=12, help='train_num_workers') # eval datasets parser.add_argument('--eval_path', type=str, default='/opt/npu/datasets/imagenet/val', help='Eval dataset path') parser.add_argument('--eval_image_size', type=int, default=224, help='eval_image_size') parser.add_argument('--eval_batch_size', type=int, default=16, help='eval_batch_size') parser.add_argument('--eval_interval', type=int, default=4, help='eval_interval') parser.add_argument('--eval_offset', type=int, default=-1, help='1 means 4*n+1 epochs') parser.add_argument('--eval_num_workers', type=int, default=12, help='eval_num_workers') # network parser.add_argument('--backbone', type=str, default='resnet50', help='resnet50') parser.add_argument('--class_num', type=int, default=1001, help='class_num') parser.add_argument('--conv_init_mode', type=str, default='truncnorm', help='truncnorm/HeNormal/HeUniform') parser.add_argument('--bn_init_mode', type=str, default='adv_bn_init', help='adv_bn_init/conv_bn_init') # lr parser.add_argument('--lr_decay_mode', type=str, default='poly', help='lr_decay_mode') parser.add_argument('--poly_power', type=float, default=2, help='lars_opt_learning_rate_decay_poly_power') parser.add_argument('--lr_init', type=float, default=0.0, help='lr_init') parser.add_argument('--lr_max', type=float, default=0.8, help='lr_max') parser.add_argument('--lr_min', type=float, default=0.0, help='lr_min') parser.add_argument('--max_epoch', type=int, default=33, help='max_epoch') parser.add_argument('--warmup_epochs', type=float, default=1, help='warmup_epochs') # optimizer parser.add_argument('--momentum', type=float, default=0.9, help='momentum') parser.add_argument('--weight_decay', type=float, default=5e-5, help='weight_decay') parser.add_argument('--use_nesterov', type=int, default=0, help='use_nesterov') parser.add_argument('--use_lars', type=int, default=0, help='use_lars') parser.add_argument('--lars_epsilon', type=float, default=0.0, help='lars_epsilon') parser.add_argument('--lars_coefficient', type=float, default=0.001, help='lars_coefficient') # loss parser.add_argument('--loss_scale', type=int, default=1024, help='loss_scale') parser.add_argument('--use_label_smooth', type=int, default=1, help='use_label_smooth') parser.add_argument('--label_smooth_factor', type=float, default=0.1, help='label_smooth_factor') # args_yml_fn parser.add_argument('--args_yml_fn', type=str, default='', help='args_yml_fn') # seed parser.add_argument('--seed', type=int, default=1, help='seed') # gradient_accumulation_steps, set to '1' for resnet parser.add_argument('--gradient_accumulation_steps', type=int, default=1, help='gradient_accumulation_steps') args = parser.parse_args() args = merge_args(args, args.args_yml_fn) args.use_nesterov = (args.use_nesterov == 1) args.weight_decay = float(args.weight_decay) if args.eval_offset < 0: args.eval_offset = args.max_epoch % args.eval_interval args.dataset_path = "/cache_mlperf/imagenet/train" args.eval_path = "/cache_mlperf/imagenet/val" return args if __name__ == '__main__': args = parse_args() np.random.seed(args.seed) context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL, gradients_mean=True) # mllog mllog.config(filename=log_filename) mllog.config( default_namespace="mindspore", default_stack_offset=1, default_clear_line=False, root_dir=os.path.normpath(os.path.dirname(os.path.realpath(__file__)))) mllogger = mllog.get_mllogger() # submission mllogger.event(key=mllog.constants.SUBMISSION_BENCHMARK, value="resnet") mllogger.event(key=mllog.constants.SUBMISSION_DIVISION, value="closed") mllogger.event(key=mllog.constants.SUBMISSION_ORG, value="PCL & PKU") mllogger.event(key=mllog.constants.SUBMISSION_PLATFORM, value="Ascend 910 ProA") mllogger.event(key=mllog.constants.SUBMISSION_STATUS, value="cloud") mllogger.event(key=mllog.constants.CACHE_CLEAR) # init the distribute env init() # network net = resnet50(backbone=args.backbone, class_num=args.class_num, conv_init_mode=args.conv_init_mode, bn_init_mode=args.bn_init_mode) # loss if not args.use_label_smooth: args.label_smooth_factor = 0.0 loss = CrossEntropySmooth(sparse=True, reduction="mean", smooth_factor=args.label_smooth_factor, num_classes=args.class_num) # train dataset epoch_size = args.max_epoch dataset = create_dataset(dataset_path=args.dataset_path, do_train=True, image_size=args.train_image_size, crop_min=args.crop_min, batch_size=args.batch_size, num_workers=args.train_num_workers) ds.config.set_seed(args.seed) de.config.set_prefetch_size(64) step_size = dataset.get_dataset_size() args.steps_per_epoch = step_size # evalutation dataset eval_dataset = create_dataset(dataset_path=args.eval_path, do_train=False, image_size=args.eval_image_size, batch_size=args.eval_batch_size, num_workers=args.eval_num_workers) eval_step_size = eval_dataset.get_dataset_size() # evaluation network dist_eval_network = ClassifyCorrectCell(net) # loss scale loss_scale = FixedLossScaleManager(args.loss_scale, drop_overflow_update=False) # learning rate lr_array = get_lr(global_step=0, lr_init=args.lr_init, lr_end=args.lr_min, lr_max=args.lr_max, warmup_epochs=args.warmup_epochs, total_epochs=epoch_size, steps_per_epoch=step_size, lr_decay_mode=args.lr_decay_mode, poly_power=args.poly_power) lr = Tensor(lr_array) decayed_params = [] no_decayed_params = [] for param in net.trainable_params(): if 'beta' not in param.name and 'gamma' not in param.name and 'bias' not in param.name: decayed_params.append(param) else: no_decayed_params.append(param) group_params = [{'params': decayed_params, 'weight_decay': args.weight_decay}, {'params': no_decayed_params}, {'order_params': net.trainable_params()}] opt = Momentum(group_params, lr, args.momentum, loss_scale=args.loss_scale, use_nesterov=args.use_nesterov) if args.use_lars: opt = LARS(opt, epsilon=args.lars_epsilon, coefficient=args.lars_coefficient, lars_filter=lambda x: 'beta' not in x.name and 'gamma' not in x.name and 'bias' not in x.name) model = Model(net, loss_fn=loss, optimizer=opt, loss_scale_manager=loss_scale, amp_level="O2", keep_batchnorm_fp32=False, metrics={'acc': DistAccuracy(batch_size=args.eval_batch_size, device_num=device_num)}, eval_network=dist_eval_network, total_steps=args.steps_per_epoch*args.max_epoch) # set event mllogger.event(key=mllog.constants.GLOBAL_BATCH_SIZE, value=args.batch_size * device_num) mllogger.event(key="opt_name", value="lars") mllogger.event(key="lars_opt_base_learning_rate", value=args.lr_max) mllogger.event(key="lars_opt_end_learning_rate", value=args.lr_min) mllogger.event(key="lars_opt_learning_rate_decay_poly_power", value=args.poly_power) mllogger.event(key="lars_opt_learning_rate_decay_steps", value=step_size * (epoch_size - args.warmup_epochs)) mllogger.event(key="lars_epsilon", value=args.lars_epsilon) mllogger.event(key="lars_opt_learning_rate_warmup_epochs", value=args.warmup_epochs) mllogger.event(key="lars_opt_momentum", value=args.momentum) mllogger.event(key="lars_opt_weight_decay", value=args.weight_decay) mllogger.event(key="gradient_accumulation_steps", value=args.gradient_accumulation_steps) mllogger.event(key="seed", value=args.seed) state_cb = StateMonitor(data_size=step_size, mllogger=mllogger, tot_batch_size=args.batch_size * device_num, lrs=lr_array, model=model, eval_dataset=eval_dataset, eval_interval=args.eval_interval, eval_offset=args.eval_offset) cb = [state_cb, ] # compile mllogger.start(key=mllog.constants.INIT_START) model._init(dataset, eval_dataset, sink_size=step_size, epoch=epoch_size) mllogger.end(key=mllog.constants.INIT_STOP) sync_path = os.path.join(args.train_url, "sync_compile") if not mox.file.exists(sync_path): mox.file.make_dirs(sync_path) yml_name = os.path.splitext(os.path.split(args.args_yml_fn)[-1])[0] s3_rank_ready_file = os.path.join(sync_path, '{}_{}.txt'.format(yml_name, local_rank)) if mox.file.exists(s3_rank_ready_file): mox.file.remove(s3_rank_ready_file, recursive=False) time.sleep(10) mox.file.write(s3_rank_ready_file, '{}'.format(local_rank)) while local_rank == 0: existed = [] all_rank_exist = True for rank_item in range(device_num): if rank_item not in existed: rank_fn_item = os.path.join(sync_path, '{}_{}.txt'.format(yml_name, rank_item)) if not mox.file.exists(rank_fn_item): print("rank_fn_item:{} is not exist".format(rank_fn_item)) all_rank_exist = False break else: existed.append(rank_item) if all_rank_exist: break else: time.sleep(1) # train and eval mllogger.start(key=mllog.constants.RUN_START) mllogger.event(key="train_samples", value=step_size*device_num*args.batch_size) mllogger.event(key="eval_samples", value=eval_step_size*device_num*args.eval_batch_size) model.train(epoch_size, dataset, callbacks=cb, sink_size=step_size, eval_interval=args.eval_interval) mllogger.event(key=mllog.constants.RUN_STOP, metadata={"status": "success"}) # copy mllog src = log_filename mllog_dir = os.path.join(args.train_url, "mllog") if not mox.file.exists(mllog_dir): mox.file.make_dirs(mllog_dir) dst = os.path.join(mllog_dir, "resnet50_mllog_rank_{}.log".format(local_rank)) mox.file.copy(src, dst)
[ "cfg_parser.merge_args", "moxing.file.make_dirs", "mindspore.train.loss_scale_manager.FixedLossScaleManager", "time.sleep", "mindspore.nn.optim.Momentum", "mlperf_logging.mllog.config", "argparse.ArgumentParser", "moxing.file.exists", "moxing.file.remove", "os.path.split", "mindspore.dataset.con...
[((1416, 1444), 'os.getenv', 'os.getenv', (['"""RANK_TABLE_FILE"""'], {}), "('RANK_TABLE_FILE')\n", (1425, 1444), False, 'import os\n'), ((1691, 1782), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.GRAPH_MODE', 'device_target': '"""Ascend"""', 'save_graphs': '(False)'}), "(mode=context.GRAPH_MODE, device_target='Ascend',\n save_graphs=False)\n", (1710, 1782), False, 'from mindspore import context\n'), ((1779, 1819), 'mindspore.context.set_context', 'context.set_context', ([], {'device_id': 'device_id'}), '(device_id=device_id)\n', (1798, 1819), False, 'from mindspore import context\n'), ((1462, 1484), 'os.getenv', 'os.getenv', (['"""DEVICE_ID"""'], {}), "('DEVICE_ID')\n", (1471, 1484), False, 'import os\n'), ((1513, 1533), 'os.getenv', 'os.getenv', (['"""RANK_ID"""'], {}), "('RANK_ID')\n", (1522, 1533), False, 'import os\n'), ((1568, 1590), 'os.getenv', 'os.getenv', (['"""RANK_SIZE"""'], {}), "('RANK_SIZE')\n", (1577, 1590), False, 'import os\n'), ((1634, 1645), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1643, 1645), False, 'import os\n'), ((1853, 1912), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Image classification"""'}), "(description='Image classification')\n", (1876, 1912), False, 'import argparse\n'), ((5400, 5434), 'cfg_parser.merge_args', 'merge_args', (['args', 'args.args_yml_fn'], {}), '(args, args.args_yml_fn)\n', (5410, 5434), False, 'from cfg_parser import merge_args\n'), ((5807, 5832), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (5821, 5832), True, 'import numpy as np\n'), ((5838, 5962), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'device_num': 'device_num', 'parallel_mode': 'ParallelMode.DATA_PARALLEL', 'gradients_mean': '(True)'}), '(device_num=device_num, parallel_mode=\n ParallelMode.DATA_PARALLEL, gradients_mean=True)\n', (5871, 5962), False, 'from mindspore import context\n'), ((6051, 6086), 'mlperf_logging.mllog.config', 'mllog.config', ([], {'filename': 'log_filename'}), '(filename=log_filename)\n', (6063, 6086), False, 'from mlperf_logging import mllog\n'), ((6305, 6325), 'mlperf_logging.mllog.get_mllogger', 'mllog.get_mllogger', ([], {}), '()\n', (6323, 6325), False, 'from mlperf_logging import mllog\n'), ((6816, 6822), 'mindspore.communication.management.init', 'init', ([], {}), '()\n', (6820, 6822), False, 'from mindspore.communication.management import init\n'), ((6848, 6979), 'resnet.resnet50', 'resnet50', ([], {'backbone': 'args.backbone', 'class_num': 'args.class_num', 'conv_init_mode': 'args.conv_init_mode', 'bn_init_mode': 'args.bn_init_mode'}), '(backbone=args.backbone, class_num=args.class_num, conv_init_mode=\n args.conv_init_mode, bn_init_mode=args.bn_init_mode)\n', (6856, 6979), False, 'from resnet import resnet50\n'), ((7128, 7250), 'cross_entropy.CrossEntropySmooth', 'CrossEntropySmooth', ([], {'sparse': '(True)', 'reduction': '"""mean"""', 'smooth_factor': 'args.label_smooth_factor', 'num_classes': 'args.class_num'}), "(sparse=True, reduction='mean', smooth_factor=args.\n label_smooth_factor, num_classes=args.class_num)\n", (7146, 7250), False, 'from cross_entropy import CrossEntropySmooth\n'), ((7403, 7596), 'dataset.create_dataset', 'create_dataset', ([], {'dataset_path': 'args.dataset_path', 'do_train': '(True)', 'image_size': 'args.train_image_size', 'crop_min': 'args.crop_min', 'batch_size': 'args.batch_size', 'num_workers': 'args.train_num_workers'}), '(dataset_path=args.dataset_path, do_train=True, image_size=\n args.train_image_size, crop_min=args.crop_min, batch_size=args.\n batch_size, num_workers=args.train_num_workers)\n', (7417, 7596), False, 'from dataset import create_dataset\n'), ((7736, 7765), 'mindspore.dataset.config.set_seed', 'ds.config.set_seed', (['args.seed'], {}), '(args.seed)\n', (7754, 7765), True, 'import mindspore.dataset as ds\n'), ((7770, 7801), 'mindspore.dataset.engine.config.set_prefetch_size', 'de.config.set_prefetch_size', (['(64)'], {}), '(64)\n', (7797, 7801), True, 'import mindspore.dataset.engine as de\n'), ((7929, 8099), 'dataset.create_dataset', 'create_dataset', ([], {'dataset_path': 'args.eval_path', 'do_train': '(False)', 'image_size': 'args.eval_image_size', 'batch_size': 'args.eval_batch_size', 'num_workers': 'args.eval_num_workers'}), '(dataset_path=args.eval_path, do_train=False, image_size=args\n .eval_image_size, batch_size=args.eval_batch_size, num_workers=args.\n eval_num_workers)\n', (7943, 8099), False, 'from dataset import create_dataset\n'), ((8329, 8353), 'metric.ClassifyCorrectCell', 'ClassifyCorrectCell', (['net'], {}), '(net)\n', (8348, 8353), False, 'from metric import DistAccuracy, ClassifyCorrectCell\n'), ((8389, 8455), 'mindspore.train.loss_scale_manager.FixedLossScaleManager', 'FixedLossScaleManager', (['args.loss_scale'], {'drop_overflow_update': '(False)'}), '(args.loss_scale, drop_overflow_update=False)\n', (8410, 8455), False, 'from mindspore.train.loss_scale_manager import FixedLossScaleManager\n'), ((8492, 8737), 'lr_generator.get_lr', 'get_lr', ([], {'global_step': '(0)', 'lr_init': 'args.lr_init', 'lr_end': 'args.lr_min', 'lr_max': 'args.lr_max', 'warmup_epochs': 'args.warmup_epochs', 'total_epochs': 'epoch_size', 'steps_per_epoch': 'step_size', 'lr_decay_mode': 'args.lr_decay_mode', 'poly_power': 'args.poly_power'}), '(global_step=0, lr_init=args.lr_init, lr_end=args.lr_min, lr_max=args\n .lr_max, warmup_epochs=args.warmup_epochs, total_epochs=epoch_size,\n steps_per_epoch=step_size, lr_decay_mode=args.lr_decay_mode, poly_power\n =args.poly_power)\n', (8498, 8737), False, 'from lr_generator import get_lr\n'), ((8777, 8793), 'mindspore.Tensor', 'Tensor', (['lr_array'], {}), '(lr_array)\n', (8783, 8793), False, 'from mindspore import Tensor\n'), ((9290, 9395), 'mindspore.nn.optim.Momentum', 'Momentum', (['group_params', 'lr', 'args.momentum'], {'loss_scale': 'args.loss_scale', 'use_nesterov': 'args.use_nesterov'}), '(group_params, lr, args.momentum, loss_scale=args.loss_scale,\n use_nesterov=args.use_nesterov)\n', (9298, 9395), False, 'from mindspore.nn.optim import LARS, Momentum\n'), ((10940, 11170), 'callback.StateMonitor', 'StateMonitor', ([], {'data_size': 'step_size', 'mllogger': 'mllogger', 'tot_batch_size': '(args.batch_size * device_num)', 'lrs': 'lr_array', 'model': 'model', 'eval_dataset': 'eval_dataset', 'eval_interval': 'args.eval_interval', 'eval_offset': 'args.eval_offset'}), '(data_size=step_size, mllogger=mllogger, tot_batch_size=args.\n batch_size * device_num, lrs=lr_array, model=model, eval_dataset=\n eval_dataset, eval_interval=args.eval_interval, eval_offset=args.\n eval_offset)\n', (10952, 11170), False, 'from callback import StateMonitor\n'), ((11584, 11628), 'os.path.join', 'os.path.join', (['args.train_url', '"""sync_compile"""'], {}), "(args.train_url, 'sync_compile')\n", (11596, 11628), False, 'import os\n'), ((11877, 11912), 'moxing.file.exists', 'mox.file.exists', (['s3_rank_ready_file'], {}), '(s3_rank_ready_file)\n', (11892, 11912), True, 'import moxing as mox\n'), ((13172, 13209), 'os.path.join', 'os.path.join', (['args.train_url', '"""mllog"""'], {}), "(args.train_url, 'mllog')\n", (13184, 13209), False, 'import os\n'), ((13374, 13397), 'moxing.file.copy', 'mox.file.copy', (['src', 'dst'], {}), '(src, dst)\n', (13387, 13397), True, 'import moxing as mox\n'), ((9428, 9602), 'mindspore.nn.optim.LARS', 'LARS', (['opt'], {'epsilon': 'args.lars_epsilon', 'coefficient': 'args.lars_coefficient', 'lars_filter': "(lambda x: 'beta' not in x.name and 'gamma' not in x.name and 'bias' not in\n x.name)"}), "(opt, epsilon=args.lars_epsilon, coefficient=args.lars_coefficient,\n lars_filter=lambda x: 'beta' not in x.name and 'gamma' not in x.name and\n 'bias' not in x.name)\n", (9432, 9602), False, 'from mindspore.nn.optim import LARS, Momentum\n'), ((11640, 11666), 'moxing.file.exists', 'mox.file.exists', (['sync_path'], {}), '(sync_path)\n', (11655, 11666), True, 'import moxing as mox\n'), ((11676, 11705), 'moxing.file.make_dirs', 'mox.file.make_dirs', (['sync_path'], {}), '(sync_path)\n', (11694, 11705), True, 'import moxing as mox\n'), ((11922, 11974), 'moxing.file.remove', 'mox.file.remove', (['s3_rank_ready_file'], {'recursive': '(False)'}), '(s3_rank_ready_file, recursive=False)\n', (11937, 11974), True, 'import moxing as mox\n'), ((11983, 11997), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (11993, 11997), False, 'import time\n'), ((13221, 13247), 'moxing.file.exists', 'mox.file.exists', (['mllog_dir'], {}), '(mllog_dir)\n', (13236, 13247), True, 'import moxing as mox\n'), ((13257, 13286), 'moxing.file.make_dirs', 'mox.file.make_dirs', (['mllog_dir'], {}), '(mllog_dir)\n', (13275, 13286), True, 'import moxing as mox\n'), ((12665, 12678), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (12675, 12678), False, 'import time\n'), ((9793, 9861), 'metric.DistAccuracy', 'DistAccuracy', ([], {'batch_size': 'args.eval_batch_size', 'device_num': 'device_num'}), '(batch_size=args.eval_batch_size, device_num=device_num)\n', (9805, 9861), False, 'from metric import DistAccuracy, ClassifyCorrectCell\n'), ((11739, 11770), 'os.path.split', 'os.path.split', (['args.args_yml_fn'], {}), '(args.args_yml_fn)\n', (11752, 11770), False, 'import os\n'), ((6260, 6286), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (6276, 6286), False, 'import os\n'), ((12346, 12375), 'moxing.file.exists', 'mox.file.exists', (['rank_fn_item'], {}), '(rank_fn_item)\n', (12361, 12375), True, 'import moxing as mox\n')]
import codes.my_helper as helper import cv2 import numpy as np import random # TODO: megcsinálni def create_skeleton(labels): skeletons = [] for img in labels: # shape: (256, 320) size = np.size(img) skel = np.zeros(img.shape, np.uint8) ret, img = cv2.threshold(img, 127, 255, 0) element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) done = False while (not done): eroded = cv2.erode(img, element) temp = cv2.dilate(eroded, element) temp = cv2.subtract(img, temp) skel = cv2.bitwise_or(skel, temp) img = eroded.copy() zeros = size - cv2.countNonZero(img) if zeros == size: done = True skeletons.append(skel) # cv2.imshow("skel", skel) # cv2.waitKey(0) # cv2.destroyAllWindows() return skeletons def print_labels(left, right, labels, size): no_polys = len(left) for n in range(0, no_polys): curr_left = left[n] curr_right = right[n] x_fit = np.linspace(0, size[0] - 1, size[0]) y_fit_left = curr_left[0] * x_fit**2 + curr_left[1] * x_fit + curr_left[2] y_fit_right = curr_right[0] * x_fit**2 + curr_right[1] * x_fit + curr_right[2] y_cross = 0 for i in range(0, size[0]): if y_fit_left[i] <= y_fit_right[i]: y_cross = i break if y_cross > 255: y_cross = 255 elif y_cross < 0: y_cross = 0 y_fit_left = y_fit_left[y_cross:] y_fit_right = y_fit_right[y_cross:] x_fit = x_fit[y_cross:] zeros = np.zeros(shape=(size[0], size[1])).astype(np.uint8) new_label = np.dstack((zeros, zeros, zeros)) pts_left = np.array([np.transpose(np.vstack([y_fit_left, x_fit]))]) pts_right = np.array([np.flipud(np.transpose(np.vstack([y_fit_right, x_fit])))]) pts = np.hstack((pts_left, pts_right)) cv2.fillPoly(img=new_label, pts=np.int_([pts]), color=(255, 255, 255)) cv2.imshow('new_label', new_label) cv2.imshow('old label', labels[n]) cv2.waitKey(0) # TODO: cv2.polylines()-t kipróbálni def create_polynoms(skeletons): rows, cols = skeletons[0].shape[0], skeletons[0].shape[1] start_col = cols // 2 start_row = rows // 3 start_center_dist = cols // 6 max_center_dist = cols // 3 left, right = [], [] # for img in skeletons: # img = skeletons[3] for img in skeletons: found_left, found_right = False, False x_left, y_left, x_right, y_right = [], [], [], [] for row in range(start_row, rows): curr_max_center_dist = start_center_dist + (max_center_dist - start_center_dist) * (row - start_row) // ( rows - start_row) for col_offset in range(0, curr_max_center_dist): # print(str(row) + ' ' + str(curr_max_center_dist) + ' ' + str(start_col - col_offset)) if img[row][start_col - col_offset] != 0: found_left = True print("left found") x_left.append(row) y_left.append(start_col - col_offset) if found_left: break if found_left: i = 0 for row in range(x_left[0] + 1, rows): col_center = y_left[i] for col_offset in range(0, 3): if col_center + col_offset != 0: x_left.append(row) y_left.append(col_offset + col_offset) col_center = col_center + col_offset break if col_center - col_offset != 0: x_left.append(row) y_left.append(col_offset + col_offset) col_center = col_center - col_offset break for row in range(start_row, rows): curr_max_center_dist = start_center_dist + (max_center_dist - start_center_dist) * (row - start_row) // ( rows - start_row) for col_offset in range(0, curr_max_center_dist): # print(str(row) + ' ' + str(curr_max_center_dist) + ' ' + str(start_col - col_offset)) if img[row][start_col + col_offset] != 0: found_right = True print("right found") x_right.append(row) y_right.append(start_col - col_offset) if found_right: break if not found_right: print("right not found") if found_left: x_right.append(0) x_right.append(rows) y_right.append(cols) y_right.append(cols) if not found_left: print("left not found") if found_right: x_left.append(0) x_left.append(rows) y_left.append(0) y_left.append(0) if found_right: i = 0 for row in range(x_right[0] + 1, rows): col_center = y_right[i] for col_offset in range(0, 3): if col_center + col_offset != 0: x_right.append(row) y_right.append(col_offset + col_offset) col_center = col_center + col_offset break if col_center - col_offset != 0: x_right.append(row) y_right.append(col_offset + col_offset) col_center = col_center - col_offset break left.append((np.polyfit(x_left, y_left, 2))) right.append((np.polyfit(x_right, y_right, 2))) return left, right def hough_lines(labels): for img in labels: print(img.shape) edges = cv2.Canny(img, 100, 255) threshold = 30 min_line_length = 10 lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold, 0, min_line_length, 10) if not (lines is None or len(lines) == 0): # print lines for curr_line in lines: for line in curr_line: # print line cv2.line(img, (line[0], line[1]), (line[2], line[3]), (0, 255, 255), 2) cv2.imshow('img', img) cv2.waitKey(0) def find_contours(labels): for img in labels: imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(imgray, 250, 255, 0) _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) print(len(contours)) for contour in contours: color = (random.randrange(0, 256, 1), random.randrange(0, 256, 1), random.randrange(0, 256, 1)) cv2.drawContours(img, contour, -1, color, 3) cv2.imshow('img', img) cv2.waitKey(0) def main(): labels = helper.read_images('../datas/images_roma/label/') # , cv2.IMREAD_GRAYSCALE) size = (320, 256) labels = helper.resize_images(labels, size) # skeletons = create_skeleton(labels) # hough_lines(labels) find_contours(labels) # left, right = create_polynoms(skeletons) # print_labels(left, right, labels, (256, 320)) main()
[ "numpy.hstack", "numpy.polyfit", "codes.my_helper.read_images", "cv2.imshow", "cv2.bitwise_or", "cv2.threshold", "cv2.erode", "cv2.line", "numpy.linspace", "numpy.vstack", "cv2.waitKey", "cv2.drawContours", "codes.my_helper.resize_images", "random.randrange", "numpy.size", "cv2.cvtColo...
[((7098, 7147), 'codes.my_helper.read_images', 'helper.read_images', (['"""../datas/images_roma/label/"""'], {}), "('../datas/images_roma/label/')\n", (7116, 7147), True, 'import codes.my_helper as helper\n'), ((7210, 7244), 'codes.my_helper.resize_images', 'helper.resize_images', (['labels', 'size'], {}), '(labels, size)\n', (7230, 7244), True, 'import codes.my_helper as helper\n'), ((214, 226), 'numpy.size', 'np.size', (['img'], {}), '(img)\n', (221, 226), True, 'import numpy as np\n'), ((242, 271), 'numpy.zeros', 'np.zeros', (['img.shape', 'np.uint8'], {}), '(img.shape, np.uint8)\n', (250, 271), True, 'import numpy as np\n'), ((291, 322), 'cv2.threshold', 'cv2.threshold', (['img', '(127)', '(255)', '(0)'], {}), '(img, 127, 255, 0)\n', (304, 322), False, 'import cv2\n'), ((341, 391), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_CROSS', '(3, 3)'], {}), '(cv2.MORPH_CROSS, (3, 3))\n', (366, 391), False, 'import cv2\n'), ((1082, 1118), 'numpy.linspace', 'np.linspace', (['(0)', '(size[0] - 1)', 'size[0]'], {}), '(0, size[0] - 1, size[0])\n', (1093, 1118), True, 'import numpy as np\n'), ((1754, 1786), 'numpy.dstack', 'np.dstack', (['(zeros, zeros, zeros)'], {}), '((zeros, zeros, zeros))\n', (1763, 1786), True, 'import numpy as np\n'), ((1967, 1999), 'numpy.hstack', 'np.hstack', (['(pts_left, pts_right)'], {}), '((pts_left, pts_right))\n', (1976, 1999), True, 'import numpy as np\n'), ((2088, 2122), 'cv2.imshow', 'cv2.imshow', (['"""new_label"""', 'new_label'], {}), "('new_label', new_label)\n", (2098, 2122), False, 'import cv2\n'), ((2131, 2165), 'cv2.imshow', 'cv2.imshow', (['"""old label"""', 'labels[n]'], {}), "('old label', labels[n])\n", (2141, 2165), False, 'import cv2\n'), ((2174, 2188), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (2185, 2188), False, 'import cv2\n'), ((6022, 6046), 'cv2.Canny', 'cv2.Canny', (['img', '(100)', '(255)'], {}), '(img, 100, 255)\n', (6031, 6046), False, 'import cv2\n'), ((6115, 6188), 'cv2.HoughLinesP', 'cv2.HoughLinesP', (['edges', '(1)', '(np.pi / 180)', 'threshold', '(0)', 'min_line_length', '(10)'], {}), '(edges, 1, np.pi / 180, threshold, 0, min_line_length, 10)\n', (6130, 6188), False, 'import cv2\n'), ((6597, 6634), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (6609, 6634), False, 'import cv2\n'), ((6657, 6691), 'cv2.threshold', 'cv2.threshold', (['imgray', '(250)', '(255)', '(0)'], {}), '(imgray, 250, 255, 0)\n', (6670, 6691), False, 'import cv2\n'), ((6725, 6789), 'cv2.findContours', 'cv2.findContours', (['thresh', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (6741, 6789), False, 'import cv2\n'), ((7026, 7048), 'cv2.imshow', 'cv2.imshow', (['"""img"""', 'img'], {}), "('img', img)\n", (7036, 7048), False, 'import cv2\n'), ((7057, 7071), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (7068, 7071), False, 'import cv2\n'), ((460, 483), 'cv2.erode', 'cv2.erode', (['img', 'element'], {}), '(img, element)\n', (469, 483), False, 'import cv2\n'), ((503, 530), 'cv2.dilate', 'cv2.dilate', (['eroded', 'element'], {}), '(eroded, element)\n', (513, 530), False, 'import cv2\n'), ((550, 573), 'cv2.subtract', 'cv2.subtract', (['img', 'temp'], {}), '(img, temp)\n', (562, 573), False, 'import cv2\n'), ((593, 619), 'cv2.bitwise_or', 'cv2.bitwise_or', (['skel', 'temp'], {}), '(skel, temp)\n', (607, 619), False, 'import cv2\n'), ((5820, 5849), 'numpy.polyfit', 'np.polyfit', (['x_left', 'y_left', '(2)'], {}), '(x_left, y_left, 2)\n', (5830, 5849), True, 'import numpy as np\n'), ((5874, 5905), 'numpy.polyfit', 'np.polyfit', (['x_right', 'y_right', '(2)'], {}), '(x_right, y_right, 2)\n', (5884, 5905), True, 'import numpy as np\n'), ((6478, 6500), 'cv2.imshow', 'cv2.imshow', (['"""img"""', 'img'], {}), "('img', img)\n", (6488, 6500), False, 'import cv2\n'), ((6513, 6527), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (6524, 6527), False, 'import cv2\n'), ((6973, 7017), 'cv2.drawContours', 'cv2.drawContours', (['img', 'contour', '(-1)', 'color', '(3)'], {}), '(img, contour, -1, color, 3)\n', (6989, 7017), False, 'import cv2\n'), ((680, 701), 'cv2.countNonZero', 'cv2.countNonZero', (['img'], {}), '(img)\n', (696, 701), False, 'import cv2\n'), ((1682, 1716), 'numpy.zeros', 'np.zeros', ([], {'shape': '(size[0], size[1])'}), '(shape=(size[0], size[1]))\n', (1690, 1716), True, 'import numpy as np\n'), ((2041, 2055), 'numpy.int_', 'np.int_', (['[pts]'], {}), '([pts])\n', (2048, 2055), True, 'import numpy as np\n'), ((6874, 6901), 'random.randrange', 'random.randrange', (['(0)', '(256)', '(1)'], {}), '(0, 256, 1)\n', (6890, 6901), False, 'import random\n'), ((6903, 6930), 'random.randrange', 'random.randrange', (['(0)', '(256)', '(1)'], {}), '(0, 256, 1)\n', (6919, 6930), False, 'import random\n'), ((6932, 6959), 'random.randrange', 'random.randrange', (['(0)', '(256)', '(1)'], {}), '(0, 256, 1)\n', (6948, 6959), False, 'import random\n'), ((1830, 1860), 'numpy.vstack', 'np.vstack', (['[y_fit_left, x_fit]'], {}), '([y_fit_left, x_fit])\n', (1839, 1860), True, 'import numpy as np\n'), ((6394, 6465), 'cv2.line', 'cv2.line', (['img', '(line[0], line[1])', '(line[2], line[3])', '(0, 255, 255)', '(2)'], {}), '(img, (line[0], line[1]), (line[2], line[3]), (0, 255, 255), 2)\n', (6402, 6465), False, 'import cv2\n'), ((1917, 1948), 'numpy.vstack', 'np.vstack', (['[y_fit_right, x_fit]'], {}), '([y_fit_right, x_fit])\n', (1926, 1948), True, 'import numpy as np\n')]
import numpy as np class FDBuffer(object): """A block of possibly-zero frequency-domain samples of a given size. Attributes: is_zero (bool): Are all samples in this block zero? If False, then buffer is not Null. buffer (None or array): Complex samples. """ def __init__(self, block_size): self.block_size = block_size self.is_zero = True self.buffer = None def alloc_buffer(self): if self.buffer is None: self.buffer = np.zeros(self.block_size + 1, dtype=np.complex) def clear(self): self.is_zero = True if self.buffer is not None: self.buffer.fill(0) def __iadd__(self, other): if not other.is_zero: self.alloc_buffer() self.buffer += other.buffer self.is_zero = False return self @classmethod def from_td(cls, block_size, td): b = cls(block_size) if np.any(td): b.is_zero = False b.buffer = np.fft.rfft(td, block_size * 2) return b def to_td(self, td): if not self.is_zero: td[:] = np.fft.irfft(self.buffer)[:self.block_size] def FDBuffers_to_td(buffers): """Turn a list of frequency-domain buffers into an array of time-domain samples of the same shape.""" td = np.zeros((len(buffers), buffers[0].block_size)) for buf, td_channel in zip(buffers, td): buf.to_td(td_channel) return td def fma(x, a, b): """Implement x += a * b for FDBuffer arguments""" if (not a.is_zero) and (not b.is_zero): x.alloc_buffer() x.buffer += a.buffer * b.buffer x.is_zero = False class MatrixBlockConvolver(object): """Apply a matrix of time-domain filters. This can be more efficient than using OverlapSaveConvolver if some input or output channels are reused, as we only need to FFT each input and output channel once. Parameters: block_size (int): time domain block size for input and output blocks n_in (int): number of input channels n_out (int): number of output channels filters (list): Single-channel filters to apply. Each element is a 3-tuple containing the input channel number, output channel number, and a single channel filter. """ class FDConvolverChannel(object): """A single channel of concolution in the frequency domain.""" def __init__(self, block_size, f): self.block_size = block_size self.filter_blocks_fd = [] self.blocks_fd = [] for start in range(0, len(f), self.block_size): end = min(len(f), start + self.block_size) self.filter_blocks_fd.append( FDBuffer.from_td(self.block_size, f[start:end])) self.blocks_fd.append(FDBuffer(self.block_size)) def filter_block(self, in_block_fd): # clear the returned block from the previous frame self.blocks_fd[-1].clear() for filter_block, block in zip(self.filter_blocks_fd, self.blocks_fd): fma(block, filter_block, in_block_fd) self.blocks_fd.append(self.blocks_fd.pop(0)) return self.blocks_fd[-1] def __init__(self, block_size, n_in, n_out, filters): self.block_size = block_size self.filters = [(in_ch, out_ch, self.FDConvolverChannel(block_size, filter)) for in_ch, out_ch, filter in filters] self.input_block = np.zeros((n_in, block_size * 2)) self.out_block_fd = [FDBuffer(block_size) for _ in range(n_out)] @classmethod def per_channel(cls, block_size, nchannels, filters): """Convenience wrapper for per-channel filters. Parameters: block_size (int): time domain block size for input and output blocks nchannels (int): number of input and output channels f (array of (n, nchannels) floats): specification of nchannels length n FIR filters to convolve the input channels with. """ return cls(block_size, nchannels, nchannels, [(i, i, f) for i, f in enumerate(np.array(filters).T)]) def filter_block(self, in_block_td): """Filter a time domain block of samples. Parameters: in_block_td (array of (block_size, n_in) floats): block of time domain input samples Returns: array of (block_size, n_out) floats: block of time domain output samples """ self.input_block[:, self.block_size:] = self.input_block[:, :self. block_size] self.input_block[:, :self.block_size] = in_block_td.T in_block_fd = [ FDBuffer.from_td(self.block_size, ch) for ch in self.input_block ] for out_block in self.out_block_fd: out_block.clear() for in_ch, out_ch, filter in self.filters: self.out_block_fd[out_ch] += filter.filter_block( in_block_fd[in_ch]) return FDBuffers_to_td(self.out_block_fd).T def OverlapSaveConvolver(block_size, nchannels, filters): """Wrapper around MatrixBlockConvolver for per-channel convolution, implementeing the old API. Parameters: block_size (int): time domain block size for input and output blocks nchannels (int): number of channels to process f (array of (n, nchannels) floats): specification of nchannels length n FIR filters to convolve the input channels with. """ return MatrixBlockConvolver.per_channel(block_size, nchannels, filters)
[ "numpy.fft.irfft", "numpy.any", "numpy.fft.rfft", "numpy.array", "numpy.zeros" ]
[((951, 961), 'numpy.any', 'np.any', (['td'], {}), '(td)\n', (957, 961), True, 'import numpy as np\n'), ((3620, 3652), 'numpy.zeros', 'np.zeros', (['(n_in, block_size * 2)'], {}), '((n_in, block_size * 2))\n', (3628, 3652), True, 'import numpy as np\n'), ((503, 550), 'numpy.zeros', 'np.zeros', (['(self.block_size + 1)'], {'dtype': 'np.complex'}), '(self.block_size + 1, dtype=np.complex)\n', (511, 550), True, 'import numpy as np\n'), ((1016, 1047), 'numpy.fft.rfft', 'np.fft.rfft', (['td', '(block_size * 2)'], {}), '(td, block_size * 2)\n', (1027, 1047), True, 'import numpy as np\n'), ((1140, 1165), 'numpy.fft.irfft', 'np.fft.irfft', (['self.buffer'], {}), '(self.buffer)\n', (1152, 1165), True, 'import numpy as np\n'), ((4291, 4308), 'numpy.array', 'np.array', (['filters'], {}), '(filters)\n', (4299, 4308), True, 'import numpy as np\n')]
import unittest import numpy as np from desc.backend import jnp from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative from numpy.random import default_rng class TestDerivative(unittest.TestCase): """Tests Grid classes""" def test_finite_diff_vec(self): def test_fun(x, y, a): return x * y + a x = np.array([1, 5, 0.01, 200]) y = np.array([60, 1, 100, 0.02]) a = -2 jac = FiniteDiffDerivative(test_fun, argnum=0) J = jac.compute(x, y, a) correct_J = np.diag(y) np.testing.assert_allclose(J, correct_J, atol=1e-8) def test_finite_diff_scalar(self): def test_fun(x, y, a): return np.dot(x, y) + a x = np.array([1, 5, 0.01, 200]) y = np.array([60, 1, 100, 0.02]) a = -2 jac = FiniteDiffDerivative(test_fun, argnum=0) J = jac.compute(x, y, a) correct_J = y np.testing.assert_allclose(J, correct_J, atol=1e-8) jac.argnum = 1 J = jac.compute(x, y, a) np.testing.assert_allclose(J, x, atol=1e-8) def test_auto_diff(self): def test_fun(x, y, a): return jnp.cos(x) + x * y + a x = np.array([1, 5, 0.01, 200]) y = np.array([60, 1, 100, 0.02]) a = -2 jac = AutoDiffDerivative(test_fun, argnum=0) J = jac.compute(x, y, a) correct_J = np.diag(-np.sin(x) + y) np.testing.assert_allclose(J, correct_J, atol=1e-8) def test_compare_AD_FD(self): def test_fun(x, y, a): return jnp.cos(x) + x * y + a x = np.array([1, 5, 0.01, 200]) y = np.array([60, 1, 100, 0.02]) a = -2 jac_AD = AutoDiffDerivative(test_fun, argnum=0) J_AD = jac_AD.compute(x, y, a) jac_FD = AutoDiffDerivative(test_fun, argnum=0) J_FD = jac_FD.compute(x, y, a) np.testing.assert_allclose(J_FD, J_AD, atol=1e-8) def test_fd_hessian(self): rando = default_rng(seed=0) n = 5 A = rando.random((n, n)) A = A + A.T g = rando.random(n) def f(x): return 5 + g.dot(x) + x.dot(1 / 2 * A.dot(x)) hess = FiniteDiffDerivative(f, argnum=0, mode="hess") y = rando.random(n) A1 = hess(y) np.testing.assert_allclose(A1, A) def test_block_jacobian(self): rando = default_rng(seed=0) A = rando.random((19, 17)) def fun(x): return jnp.dot(A, x) x = rando.random(17) jac = AutoDiffDerivative(fun, block_size=4, shape=A.shape) np.testing.assert_allclose(jac(x), A) jac = AutoDiffDerivative(fun, num_blocks=3, shape=A.shape) np.testing.assert_allclose(jac(x), A) class TestJVP(unittest.TestCase): @staticmethod def fun(x, c1, c2): Amat = np.arange(12).reshape((4, 3)) return jnp.dot(Amat, (x + c1 * c2) ** 3) x = np.ones(3).astype(float) c1 = np.arange(3).astype(float) c2 = np.arange(3).astype(float) + 2 dx = np.array([1, 2, 3]).astype(float) dc1 = np.array([3, 4, 5]).astype(float) dc2 = np.array([-3, 1, -2]).astype(float) def test_autodiff_jvp(self): df = AutoDiffDerivative.compute_jvp( self.fun, 0, self.dx, self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([1554.0, 4038.0, 6522.0, 9006.0])) df = AutoDiffDerivative.compute_jvp( self.fun, 1, self.dc1, self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([10296.0, 26658.0, 43020.0, 59382.0])) df = AutoDiffDerivative.compute_jvp( self.fun, (0, 2), (self.dx, self.dc2), self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([-342.0, -630.0, -918.0, -1206.0])) def test_finitediff_jvp(self): df = FiniteDiffDerivative.compute_jvp( self.fun, 0, self.dx, self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([1554.0, 4038.0, 6522.0, 9006.0])) df = FiniteDiffDerivative.compute_jvp( self.fun, 1, self.dc1, self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([10296.0, 26658.0, 43020.0, 59382.0])) df = FiniteDiffDerivative.compute_jvp( self.fun, (0, 2), (self.dx, self.dc2), self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([-342.0, -630.0, -918.0, -1206.0])) def test_autodiff_jvp2(self): df = AutoDiffDerivative.compute_jvp2( self.fun, 0, 0, self.dx + 1, self.dx, self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([1440.0, 3852.0, 6264.0, 8676.0])) df = AutoDiffDerivative.compute_jvp2( self.fun, 1, 1, self.dc1 + 1, self.dc1, self.x, self.c1, self.c2 ) np.testing.assert_allclose( df, np.array([56160.0, 147744.0, 239328.0, 330912.0]) ) df = AutoDiffDerivative.compute_jvp2( self.fun, 0, 2, self.dx, self.dc2, self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([-1248.0, -3048.0, -4848.0, -6648.0])) df = AutoDiffDerivative.compute_jvp2( self.fun, 0, (1, 2), self.dx, (self.dc1, self.dc2), self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([5808.0, 15564.0, 25320.0, 35076.0])) df = AutoDiffDerivative.compute_jvp2( self.fun, (1, 2), (1, 2), (self.dc1, self.dc2), (self.dc1, self.dc2), self.x, self.c1, self.c2, ) np.testing.assert_allclose(df, np.array([22368.0, 63066.0, 103764.0, 144462.0])) df = AutoDiffDerivative.compute_jvp2( self.fun, 0, (1, 2), self.dx, (self.dc1, self.dc2), self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([5808.0, 15564.0, 25320.0, 35076.0])) def test_finitediff_jvp2(self): df = FiniteDiffDerivative.compute_jvp2( self.fun, 0, 0, self.dx + 1, self.dx, self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([1440.0, 3852.0, 6264.0, 8676.0])) df = FiniteDiffDerivative.compute_jvp2( self.fun, 1, 1, self.dc1 + 1, self.dc1, self.x, self.c1, self.c2 ) np.testing.assert_allclose( df, np.array([56160.0, 147744.0, 239328.0, 330912.0]) ) df = FiniteDiffDerivative.compute_jvp2( self.fun, 0, 2, self.dx, self.dc2, self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([-1248.0, -3048.0, -4848.0, -6648.0])) df = FiniteDiffDerivative.compute_jvp2( self.fun, 0, (1, 2), self.dx, (self.dc1, self.dc2), self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([5808.0, 15564.0, 25320.0, 35076.0])) df = FiniteDiffDerivative.compute_jvp2( self.fun, (1, 2), (1, 2), (self.dc1, self.dc2), (self.dc1, self.dc2), self.x, self.c1, self.c2, ) np.testing.assert_allclose(df, np.array([22368.0, 63066.0, 103764.0, 144462.0])) df = FiniteDiffDerivative.compute_jvp2( self.fun, 0, (1, 2), self.dx, (self.dc1, self.dc2), self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([5808.0, 15564.0, 25320.0, 35076.0])) def test_autodiff_jvp3(self): df = AutoDiffDerivative.compute_jvp3( self.fun, 0, 0, 0, self.dx + 1, self.dx, self.dx, self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([504.0, 1404.0, 2304.0, 3204.0])) df = AutoDiffDerivative.compute_jvp3( self.fun, 0, 1, 1, self.dx, self.dc1 + 1, self.dc1, self.x, self.c1, self.c2 ) np.testing.assert_allclose(df, np.array([19440.0, 52704.0, 85968.0, 119232.0])) df = AutoDiffDerivative.compute_jvp3( self.fun, 0, 1, 2, self.dx, self.dc1, self.dc2, self.x, self.c1, self.c2 ) np.testing.assert_allclose( df, np.array([-5784.0, -14118.0, -22452.0, -30786.0]) ) df = AutoDiffDerivative.compute_jvp3( self.fun, 0, 0, (1, 2), self.dx, self.dx, (self.dc1, self.dc2), self.x, self.c1, self.c2, ) np.testing.assert_allclose(df, np.array([2040.0, 5676.0, 9312.0, 12948.0])) df = AutoDiffDerivative.compute_jvp3( self.fun, (1, 2), (1, 2), (1, 2), (self.dc1, self.dc2), (self.dc1, self.dc2), (self.dc1, self.dc2), self.x, self.c1, self.c2, ) np.testing.assert_allclose( df, np.array([-33858.0, -55584.0, -77310.0, -99036.0]) ) def test_finitediff_jvp3(self): df = FiniteDiffDerivative.compute_jvp3( self.fun, 0, 0, 0, self.dx + 1, self.dx, self.dx, self.x, self.c1, self.c2 ) np.testing.assert_allclose( df, np.array([504.0, 1404.0, 2304.0, 3204.0]), rtol=1e-4 ) df = FiniteDiffDerivative.compute_jvp3( self.fun, 0, 1, 1, self.dx, self.dc1 + 1, self.dc1, self.x, self.c1, self.c2 ) np.testing.assert_allclose( df, np.array([19440.0, 52704.0, 85968.0, 119232.0]), rtol=1e-4 ) df = FiniteDiffDerivative.compute_jvp3( self.fun, 0, 1, 2, self.dx, self.dc1, self.dc2, self.x, self.c1, self.c2 ) np.testing.assert_allclose( df, np.array([-5784.0, -14118.0, -22452.0, -30786.0]), rtol=1e-4 ) df = FiniteDiffDerivative.compute_jvp3( self.fun, 0, 0, (1, 2), self.dx, self.dx, (self.dc1, self.dc2), self.x, self.c1, self.c2, ) np.testing.assert_allclose( df, np.array([2040.0, 5676.0, 9312.0, 12948.0]), rtol=1e-4 ) df = FiniteDiffDerivative.compute_jvp3( self.fun, (1, 2), (1, 2), (1, 2), (self.dc1, self.dc2), (self.dc1, self.dc2), (self.dc1, self.dc2), self.x, self.c1, self.c2, ) np.testing.assert_allclose( df, np.array([-33858.0, -55584.0, -77310.0, -99036.0]), rtol=1e-4 )
[ "desc.derivatives.FiniteDiffDerivative.compute_jvp3", "desc.derivatives.AutoDiffDerivative.compute_jvp", "numpy.random.default_rng", "desc.derivatives.FiniteDiffDerivative.compute_jvp2", "desc.derivatives.AutoDiffDerivative.compute_jvp3", "numpy.ones", "numpy.arange", "numpy.testing.assert_allclose", ...
[((355, 382), 'numpy.array', 'np.array', (['[1, 5, 0.01, 200]'], {}), '([1, 5, 0.01, 200])\n', (363, 382), True, 'import numpy as np\n'), ((395, 423), 'numpy.array', 'np.array', (['[60, 1, 100, 0.02]'], {}), '([60, 1, 100, 0.02])\n', (403, 423), True, 'import numpy as np\n'), ((454, 494), 'desc.derivatives.FiniteDiffDerivative', 'FiniteDiffDerivative', (['test_fun'], {'argnum': '(0)'}), '(test_fun, argnum=0)\n', (474, 494), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((548, 558), 'numpy.diag', 'np.diag', (['y'], {}), '(y)\n', (555, 558), True, 'import numpy as np\n'), ((568, 620), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['J', 'correct_J'], {'atol': '(1e-08)'}), '(J, correct_J, atol=1e-08)\n', (594, 620), True, 'import numpy as np\n'), ((740, 767), 'numpy.array', 'np.array', (['[1, 5, 0.01, 200]'], {}), '([1, 5, 0.01, 200])\n', (748, 767), True, 'import numpy as np\n'), ((780, 808), 'numpy.array', 'np.array', (['[60, 1, 100, 0.02]'], {}), '([60, 1, 100, 0.02])\n', (788, 808), True, 'import numpy as np\n'), ((839, 879), 'desc.derivatives.FiniteDiffDerivative', 'FiniteDiffDerivative', (['test_fun'], {'argnum': '(0)'}), '(test_fun, argnum=0)\n', (859, 879), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((944, 996), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['J', 'correct_J'], {'atol': '(1e-08)'}), '(J, correct_J, atol=1e-08)\n', (970, 996), True, 'import numpy as np\n'), ((1061, 1105), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['J', 'x'], {'atol': '(1e-08)'}), '(J, x, atol=1e-08)\n', (1087, 1105), True, 'import numpy as np\n'), ((1222, 1249), 'numpy.array', 'np.array', (['[1, 5, 0.01, 200]'], {}), '([1, 5, 0.01, 200])\n', (1230, 1249), True, 'import numpy as np\n'), ((1262, 1290), 'numpy.array', 'np.array', (['[60, 1, 100, 0.02]'], {}), '([60, 1, 100, 0.02])\n', (1270, 1290), True, 'import numpy as np\n'), ((1321, 1359), 'desc.derivatives.AutoDiffDerivative', 'AutoDiffDerivative', (['test_fun'], {'argnum': '(0)'}), '(test_fun, argnum=0)\n', (1339, 1359), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((1446, 1498), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['J', 'correct_J'], {'atol': '(1e-08)'}), '(J, correct_J, atol=1e-08)\n', (1472, 1498), True, 'import numpy as np\n'), ((1619, 1646), 'numpy.array', 'np.array', (['[1, 5, 0.01, 200]'], {}), '([1, 5, 0.01, 200])\n', (1627, 1646), True, 'import numpy as np\n'), ((1659, 1687), 'numpy.array', 'np.array', (['[60, 1, 100, 0.02]'], {}), '([60, 1, 100, 0.02])\n', (1667, 1687), True, 'import numpy as np\n'), ((1721, 1759), 'desc.derivatives.AutoDiffDerivative', 'AutoDiffDerivative', (['test_fun'], {'argnum': '(0)'}), '(test_fun, argnum=0)\n', (1739, 1759), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((1817, 1855), 'desc.derivatives.AutoDiffDerivative', 'AutoDiffDerivative', (['test_fun'], {'argnum': '(0)'}), '(test_fun, argnum=0)\n', (1835, 1855), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((1904, 1954), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['J_FD', 'J_AD'], {'atol': '(1e-08)'}), '(J_FD, J_AD, atol=1e-08)\n', (1930, 1954), True, 'import numpy as np\n'), ((2002, 2021), 'numpy.random.default_rng', 'default_rng', ([], {'seed': '(0)'}), '(seed=0)\n', (2013, 2021), False, 'from numpy.random import default_rng\n'), ((2211, 2257), 'desc.derivatives.FiniteDiffDerivative', 'FiniteDiffDerivative', (['f'], {'argnum': '(0)', 'mode': '"""hess"""'}), "(f, argnum=0, mode='hess')\n", (2231, 2257), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((2317, 2350), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['A1', 'A'], {}), '(A1, A)\n', (2343, 2350), True, 'import numpy as np\n'), ((2403, 2422), 'numpy.random.default_rng', 'default_rng', ([], {'seed': '(0)'}), '(seed=0)\n', (2414, 2422), False, 'from numpy.random import default_rng\n'), ((2557, 2609), 'desc.derivatives.AutoDiffDerivative', 'AutoDiffDerivative', (['fun'], {'block_size': '(4)', 'shape': 'A.shape'}), '(fun, block_size=4, shape=A.shape)\n', (2575, 2609), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((2670, 2722), 'desc.derivatives.AutoDiffDerivative', 'AutoDiffDerivative', (['fun'], {'num_blocks': '(3)', 'shape': 'A.shape'}), '(fun, num_blocks=3, shape=A.shape)\n', (2688, 2722), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((2907, 2940), 'desc.backend.jnp.dot', 'jnp.dot', (['Amat', '((x + c1 * c2) ** 3)'], {}), '(Amat, (x + c1 * c2) ** 3)\n', (2914, 2940), False, 'from desc.backend import jnp\n'), ((3233, 3311), 'desc.derivatives.AutoDiffDerivative.compute_jvp', 'AutoDiffDerivative.compute_jvp', (['self.fun', '(0)', 'self.dx', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, self.dx, self.x, self.c1, self.c2)\n', (3263, 3311), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((3430, 3509), 'desc.derivatives.AutoDiffDerivative.compute_jvp', 'AutoDiffDerivative.compute_jvp', (['self.fun', '(1)', 'self.dc1', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 1, self.dc1, self.x, self.c1, self.c2)\n', (3460, 3509), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((3632, 3732), 'desc.derivatives.AutoDiffDerivative.compute_jvp', 'AutoDiffDerivative.compute_jvp', (['self.fun', '(0, 2)', '(self.dx, self.dc2)', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, (0, 2), (self.dx, self.dc2), self.\n x, self.c1, self.c2)\n', (3662, 3732), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((3884, 3969), 'desc.derivatives.FiniteDiffDerivative.compute_jvp', 'FiniteDiffDerivative.compute_jvp', (['self.fun', '(0)', 'self.dx', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, self.dx, self.x, self.c1, self.c2\n )\n', (3916, 3969), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((4083, 4168), 'desc.derivatives.FiniteDiffDerivative.compute_jvp', 'FiniteDiffDerivative.compute_jvp', (['self.fun', '(1)', 'self.dc1', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 1, self.dc1, self.x, self.c1,\n self.c2)\n', (4115, 4168), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((4287, 4388), 'desc.derivatives.FiniteDiffDerivative.compute_jvp', 'FiniteDiffDerivative.compute_jvp', (['self.fun', '(0, 2)', '(self.dx, self.dc2)', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, (0, 2), (self.dx, self.dc2),\n self.x, self.c1, self.c2)\n', (4319, 4388), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((4540, 4640), 'desc.derivatives.AutoDiffDerivative.compute_jvp2', 'AutoDiffDerivative.compute_jvp2', (['self.fun', '(0)', '(0)', '(self.dx + 1)', 'self.dx', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, 0, self.dx + 1, self.dx, self.\n x, self.c1, self.c2)\n', (4571, 4640), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((4754, 4855), 'desc.derivatives.AutoDiffDerivative.compute_jvp2', 'AutoDiffDerivative.compute_jvp2', (['self.fun', '(1)', '(1)', '(self.dc1 + 1)', 'self.dc1', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 1, 1, self.dc1 + 1, self.dc1,\n self.x, self.c1, self.c2)\n', (4785, 4855), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((4999, 5095), 'desc.derivatives.AutoDiffDerivative.compute_jvp2', 'AutoDiffDerivative.compute_jvp2', (['self.fun', '(0)', '(2)', 'self.dx', 'self.dc2', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, 2, self.dx, self.dc2, self.x,\n self.c1, self.c2)\n', (5030, 5095), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((5214, 5327), 'desc.derivatives.AutoDiffDerivative.compute_jvp2', 'AutoDiffDerivative.compute_jvp2', (['self.fun', '(0)', '(1, 2)', 'self.dx', '(self.dc1, self.dc2)', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, (1, 2), self.dx, (self.dc1,\n self.dc2), self.x, self.c1, self.c2)\n', (5245, 5327), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((5445, 5577), 'desc.derivatives.AutoDiffDerivative.compute_jvp2', 'AutoDiffDerivative.compute_jvp2', (['self.fun', '(1, 2)', '(1, 2)', '(self.dc1, self.dc2)', '(self.dc1, self.dc2)', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, (1, 2), (1, 2), (self.dc1, self.\n dc2), (self.dc1, self.dc2), self.x, self.c1, self.c2)\n', (5476, 5577), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((5782, 5895), 'desc.derivatives.AutoDiffDerivative.compute_jvp2', 'AutoDiffDerivative.compute_jvp2', (['self.fun', '(0)', '(1, 2)', 'self.dx', '(self.dc1, self.dc2)', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, (1, 2), self.dx, (self.dc1,\n self.dc2), self.x, self.c1, self.c2)\n', (5813, 5895), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((6051, 6152), 'desc.derivatives.FiniteDiffDerivative.compute_jvp2', 'FiniteDiffDerivative.compute_jvp2', (['self.fun', '(0)', '(0)', '(self.dx + 1)', 'self.dx', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, 0, self.dx + 1, self.dx,\n self.x, self.c1, self.c2)\n', (6084, 6152), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((6267, 6370), 'desc.derivatives.FiniteDiffDerivative.compute_jvp2', 'FiniteDiffDerivative.compute_jvp2', (['self.fun', '(1)', '(1)', '(self.dc1 + 1)', 'self.dc1', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 1, 1, self.dc1 + 1, self.dc1,\n self.x, self.c1, self.c2)\n', (6300, 6370), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((6514, 6612), 'desc.derivatives.FiniteDiffDerivative.compute_jvp2', 'FiniteDiffDerivative.compute_jvp2', (['self.fun', '(0)', '(2)', 'self.dx', 'self.dc2', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, 2, self.dx, self.dc2, self.x,\n self.c1, self.c2)\n', (6547, 6612), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((6731, 6846), 'desc.derivatives.FiniteDiffDerivative.compute_jvp2', 'FiniteDiffDerivative.compute_jvp2', (['self.fun', '(0)', '(1, 2)', 'self.dx', '(self.dc1, self.dc2)', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, (1, 2), self.dx, (self.dc1,\n self.dc2), self.x, self.c1, self.c2)\n', (6764, 6846), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((6964, 7098), 'desc.derivatives.FiniteDiffDerivative.compute_jvp2', 'FiniteDiffDerivative.compute_jvp2', (['self.fun', '(1, 2)', '(1, 2)', '(self.dc1, self.dc2)', '(self.dc1, self.dc2)', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, (1, 2), (1, 2), (self.dc1, self\n .dc2), (self.dc1, self.dc2), self.x, self.c1, self.c2)\n', (6997, 7098), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((7303, 7418), 'desc.derivatives.FiniteDiffDerivative.compute_jvp2', 'FiniteDiffDerivative.compute_jvp2', (['self.fun', '(0)', '(1, 2)', 'self.dx', '(self.dc1, self.dc2)', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, (1, 2), self.dx, (self.dc1,\n self.dc2), self.x, self.c1, self.c2)\n', (7336, 7418), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((7572, 7683), 'desc.derivatives.AutoDiffDerivative.compute_jvp3', 'AutoDiffDerivative.compute_jvp3', (['self.fun', '(0)', '(0)', '(0)', '(self.dx + 1)', 'self.dx', 'self.dx', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, 0, 0, self.dx + 1, self.dx,\n self.dx, self.x, self.c1, self.c2)\n', (7603, 7683), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((7797, 7910), 'desc.derivatives.AutoDiffDerivative.compute_jvp3', 'AutoDiffDerivative.compute_jvp3', (['self.fun', '(0)', '(1)', '(1)', 'self.dx', '(self.dc1 + 1)', 'self.dc1', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, 1, 1, self.dx, self.dc1 + 1,\n self.dc1, self.x, self.c1, self.c2)\n', (7828, 7910), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((8030, 8140), 'desc.derivatives.AutoDiffDerivative.compute_jvp3', 'AutoDiffDerivative.compute_jvp3', (['self.fun', '(0)', '(1)', '(2)', 'self.dx', 'self.dc1', 'self.dc2', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, 1, 2, self.dx, self.dc1, self.\n dc2, self.x, self.c1, self.c2)\n', (8061, 8140), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((8283, 8409), 'desc.derivatives.AutoDiffDerivative.compute_jvp3', 'AutoDiffDerivative.compute_jvp3', (['self.fun', '(0)', '(0)', '(1, 2)', 'self.dx', 'self.dx', '(self.dc1, self.dc2)', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, 0, (1, 2), self.dx, self.dx, (\n self.dc1, self.dc2), self.x, self.c1, self.c2)\n', (8314, 8409), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((8633, 8798), 'desc.derivatives.AutoDiffDerivative.compute_jvp3', 'AutoDiffDerivative.compute_jvp3', (['self.fun', '(1, 2)', '(1, 2)', '(1, 2)', '(self.dc1, self.dc2)', '(self.dc1, self.dc2)', '(self.dc1, self.dc2)', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, (1, 2), (1, 2), (1, 2), (self.dc1,\n self.dc2), (self.dc1, self.dc2), (self.dc1, self.dc2), self.x, self.c1,\n self.c2)\n', (8664, 8798), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((9086, 9199), 'desc.derivatives.FiniteDiffDerivative.compute_jvp3', 'FiniteDiffDerivative.compute_jvp3', (['self.fun', '(0)', '(0)', '(0)', '(self.dx + 1)', 'self.dx', 'self.dx', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, 0, 0, self.dx + 1, self.dx,\n self.dx, self.x, self.c1, self.c2)\n', (9119, 9199), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((9346, 9461), 'desc.derivatives.FiniteDiffDerivative.compute_jvp3', 'FiniteDiffDerivative.compute_jvp3', (['self.fun', '(0)', '(1)', '(1)', 'self.dx', '(self.dc1 + 1)', 'self.dc1', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, 1, 1, self.dx, self.dc1 + 1,\n self.dc1, self.x, self.c1, self.c2)\n', (9379, 9461), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((9614, 9725), 'desc.derivatives.FiniteDiffDerivative.compute_jvp3', 'FiniteDiffDerivative.compute_jvp3', (['self.fun', '(0)', '(1)', '(2)', 'self.dx', 'self.dc1', 'self.dc2', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, 1, 2, self.dx, self.dc1,\n self.dc2, self.x, self.c1, self.c2)\n', (9647, 9725), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((9880, 10007), 'desc.derivatives.FiniteDiffDerivative.compute_jvp3', 'FiniteDiffDerivative.compute_jvp3', (['self.fun', '(0)', '(0)', '(1, 2)', 'self.dx', 'self.dx', '(self.dc1, self.dc2)', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, 0, 0, (1, 2), self.dx, self.dx,\n (self.dc1, self.dc2), self.x, self.c1, self.c2)\n', (9913, 10007), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((10265, 10433), 'desc.derivatives.FiniteDiffDerivative.compute_jvp3', 'FiniteDiffDerivative.compute_jvp3', (['self.fun', '(1, 2)', '(1, 2)', '(1, 2)', '(self.dc1, self.dc2)', '(self.dc1, self.dc2)', '(self.dc1, self.dc2)', 'self.x', 'self.c1', 'self.c2'], {}), '(self.fun, (1, 2), (1, 2), (1, 2), (self.\n dc1, self.dc2), (self.dc1, self.dc2), (self.dc1, self.dc2), self.x,\n self.c1, self.c2)\n', (10298, 10433), False, 'from desc.derivatives import AutoDiffDerivative, FiniteDiffDerivative\n'), ((2498, 2511), 'desc.backend.jnp.dot', 'jnp.dot', (['A', 'x'], {}), '(A, x)\n', (2505, 2511), False, 'from desc.backend import jnp\n'), ((2950, 2960), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (2957, 2960), True, 'import numpy as np\n'), ((2984, 2996), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (2993, 2996), True, 'import numpy as np\n'), ((3061, 3080), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (3069, 3080), True, 'import numpy as np\n'), ((3105, 3124), 'numpy.array', 'np.array', (['[3, 4, 5]'], {}), '([3, 4, 5])\n', (3113, 3124), True, 'import numpy as np\n'), ((3149, 3170), 'numpy.array', 'np.array', (['[-3, 1, -2]'], {}), '([-3, 1, -2])\n', (3157, 3170), True, 'import numpy as np\n'), ((3373, 3415), 'numpy.array', 'np.array', (['[1554.0, 4038.0, 6522.0, 9006.0]'], {}), '([1554.0, 4038.0, 6522.0, 9006.0])\n', (3381, 3415), True, 'import numpy as np\n'), ((3571, 3617), 'numpy.array', 'np.array', (['[10296.0, 26658.0, 43020.0, 59382.0]'], {}), '([10296.0, 26658.0, 43020.0, 59382.0])\n', (3579, 3617), True, 'import numpy as np\n'), ((3789, 3832), 'numpy.array', 'np.array', (['[-342.0, -630.0, -918.0, -1206.0]'], {}), '([-342.0, -630.0, -918.0, -1206.0])\n', (3797, 3832), True, 'import numpy as np\n'), ((4026, 4068), 'numpy.array', 'np.array', (['[1554.0, 4038.0, 6522.0, 9006.0]'], {}), '([1554.0, 4038.0, 6522.0, 9006.0])\n', (4034, 4068), True, 'import numpy as np\n'), ((4226, 4272), 'numpy.array', 'np.array', (['[10296.0, 26658.0, 43020.0, 59382.0]'], {}), '([10296.0, 26658.0, 43020.0, 59382.0])\n', (4234, 4272), True, 'import numpy as np\n'), ((4446, 4489), 'numpy.array', 'np.array', (['[-342.0, -630.0, -918.0, -1206.0]'], {}), '([-342.0, -630.0, -918.0, -1206.0])\n', (4454, 4489), True, 'import numpy as np\n'), ((4697, 4739), 'numpy.array', 'np.array', (['[1440.0, 3852.0, 6264.0, 8676.0]'], {}), '([1440.0, 3852.0, 6264.0, 8676.0])\n', (4705, 4739), True, 'import numpy as np\n'), ((4926, 4975), 'numpy.array', 'np.array', (['[56160.0, 147744.0, 239328.0, 330912.0]'], {}), '([56160.0, 147744.0, 239328.0, 330912.0])\n', (4934, 4975), True, 'import numpy as np\n'), ((5153, 5199), 'numpy.array', 'np.array', (['[-1248.0, -3048.0, -4848.0, -6648.0]'], {}), '([-1248.0, -3048.0, -4848.0, -6648.0])\n', (5161, 5199), True, 'import numpy as np\n'), ((5385, 5430), 'numpy.array', 'np.array', (['[5808.0, 15564.0, 25320.0, 35076.0]'], {}), '([5808.0, 15564.0, 25320.0, 35076.0])\n', (5393, 5430), True, 'import numpy as np\n'), ((5719, 5767), 'numpy.array', 'np.array', (['[22368.0, 63066.0, 103764.0, 144462.0]'], {}), '([22368.0, 63066.0, 103764.0, 144462.0])\n', (5727, 5767), True, 'import numpy as np\n'), ((5953, 5998), 'numpy.array', 'np.array', (['[5808.0, 15564.0, 25320.0, 35076.0]'], {}), '([5808.0, 15564.0, 25320.0, 35076.0])\n', (5961, 5998), True, 'import numpy as np\n'), ((6210, 6252), 'numpy.array', 'np.array', (['[1440.0, 3852.0, 6264.0, 8676.0]'], {}), '([1440.0, 3852.0, 6264.0, 8676.0])\n', (6218, 6252), True, 'import numpy as np\n'), ((6441, 6490), 'numpy.array', 'np.array', (['[56160.0, 147744.0, 239328.0, 330912.0]'], {}), '([56160.0, 147744.0, 239328.0, 330912.0])\n', (6449, 6490), True, 'import numpy as np\n'), ((6670, 6716), 'numpy.array', 'np.array', (['[-1248.0, -3048.0, -4848.0, -6648.0]'], {}), '([-1248.0, -3048.0, -4848.0, -6648.0])\n', (6678, 6716), True, 'import numpy as np\n'), ((6904, 6949), 'numpy.array', 'np.array', (['[5808.0, 15564.0, 25320.0, 35076.0]'], {}), '([5808.0, 15564.0, 25320.0, 35076.0])\n', (6912, 6949), True, 'import numpy as np\n'), ((7240, 7288), 'numpy.array', 'np.array', (['[22368.0, 63066.0, 103764.0, 144462.0]'], {}), '([22368.0, 63066.0, 103764.0, 144462.0])\n', (7248, 7288), True, 'import numpy as np\n'), ((7476, 7521), 'numpy.array', 'np.array', (['[5808.0, 15564.0, 25320.0, 35076.0]'], {}), '([5808.0, 15564.0, 25320.0, 35076.0])\n', (7484, 7521), True, 'import numpy as np\n'), ((7741, 7782), 'numpy.array', 'np.array', (['[504.0, 1404.0, 2304.0, 3204.0]'], {}), '([504.0, 1404.0, 2304.0, 3204.0])\n', (7749, 7782), True, 'import numpy as np\n'), ((7968, 8015), 'numpy.array', 'np.array', (['[19440.0, 52704.0, 85968.0, 119232.0]'], {}), '([19440.0, 52704.0, 85968.0, 119232.0])\n', (7976, 8015), True, 'import numpy as np\n'), ((8210, 8259), 'numpy.array', 'np.array', (['[-5784.0, -14118.0, -22452.0, -30786.0]'], {}), '([-5784.0, -14118.0, -22452.0, -30786.0])\n', (8218, 8259), True, 'import numpy as np\n'), ((8575, 8618), 'numpy.array', 'np.array', (['[2040.0, 5676.0, 9312.0, 12948.0]'], {}), '([2040.0, 5676.0, 9312.0, 12948.0])\n', (8583, 8618), True, 'import numpy as np\n'), ((8974, 9024), 'numpy.array', 'np.array', (['[-33858.0, -55584.0, -77310.0, -99036.0]'], {}), '([-33858.0, -55584.0, -77310.0, -99036.0])\n', (8982, 9024), True, 'import numpy as np\n'), ((9270, 9311), 'numpy.array', 'np.array', (['[504.0, 1404.0, 2304.0, 3204.0]'], {}), '([504.0, 1404.0, 2304.0, 3204.0])\n', (9278, 9311), True, 'import numpy as np\n'), ((9532, 9579), 'numpy.array', 'np.array', (['[19440.0, 52704.0, 85968.0, 119232.0]'], {}), '([19440.0, 52704.0, 85968.0, 119232.0])\n', (9540, 9579), True, 'import numpy as np\n'), ((9796, 9845), 'numpy.array', 'np.array', (['[-5784.0, -14118.0, -22452.0, -30786.0]'], {}), '([-5784.0, -14118.0, -22452.0, -30786.0])\n', (9804, 9845), True, 'import numpy as np\n'), ((10187, 10230), 'numpy.array', 'np.array', (['[2040.0, 5676.0, 9312.0, 12948.0]'], {}), '([2040.0, 5676.0, 9312.0, 12948.0])\n', (10195, 10230), True, 'import numpy as np\n'), ((10608, 10658), 'numpy.array', 'np.array', (['[-33858.0, -55584.0, -77310.0, -99036.0]'], {}), '([-33858.0, -55584.0, -77310.0, -99036.0])\n', (10616, 10658), True, 'import numpy as np\n'), ((710, 722), 'numpy.dot', 'np.dot', (['x', 'y'], {}), '(x, y)\n', (716, 722), True, 'import numpy as np\n'), ((2862, 2875), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (2871, 2875), True, 'import numpy as np\n'), ((3020, 3032), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (3029, 3032), True, 'import numpy as np\n'), ((1186, 1196), 'desc.backend.jnp.cos', 'jnp.cos', (['x'], {}), '(x)\n', (1193, 1196), False, 'from desc.backend import jnp\n'), ((1422, 1431), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (1428, 1431), True, 'import numpy as np\n'), ((1583, 1593), 'desc.backend.jnp.cos', 'jnp.cos', (['x'], {}), '(x)\n', (1590, 1593), False, 'from desc.backend import jnp\n')]
# -*- coding: utf-8 -*- """ Created on Sat Oct 21 10:18:03 2017 @author: damodara """ import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid import matplotlib.patches as mpatches import os def imshow_grid(images, shape=[2, 8]): """Plot images in a grid of a given shape.""" fig = plt.figure(1) grid = ImageGrid(fig, 111, nrows_ncols=shape, axes_pad=0.05) n_dim = np.shape(images) size = shape[0] * shape[1] for i in range(size): grid[i].axis('off') if len(n_dim)<=3: grid[i].imshow(images[i], cmap=plt.get_cmap('gray')) # The AxesGrid object work as a list of axes. else: grid[i].imshow(images[i]) plt.show() def plot_embedding(X, y, d, title=None, save_fig=0, pname=None): """Plot an embedding X with the class label y colored by the domain d.""" x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) # Plot colors numbers plt.figure(figsize=(10,10)) ax = plt.subplot(111) for i in range(X.shape[0]): # plot colored number # plt.text(X[i, 0], X[i, 1], str(y[i]), # color=plt.cm.bwr(d[i] / 1.), # fontdict={'weight': 'bold', 'size': 9}) if d[i]==0: c = 'red' elif d[i]==1: c = 'green' elif d[i]==2: c = 'blue' plt.text(X[i, 0], X[i, 1], str(y[i]), color= c, fontdict={'weight': 'bold', 'size': 9}) plt.xticks([]), plt.yticks([]) red_patch = mpatches.Patch(color='red', label='Source data') green_patch = mpatches.Patch(color='green', label='Target data') plt.legend(handles=[red_patch, green_patch]) plt.show() if title is not None: plt.title(title) if save_fig: fname = title+'.png' if pname is not None: fname = os.path.join(pname, fname) plt.savefig(fname) def tsne_plot(xs, xt, xs_label, xt_label, map_xs=None, title=None, pname=None): num_test=1000 if map_xs is not None: combined_imgs = np.vstack([xs[0:num_test, :], xt[0:num_test, :], map_xs[0:num_test,:]]) combined_labels = np.vstack([xs_label[0:num_test, :],xt_label[0:num_test, :], xs_label[0:num_test,:]]) combined_labels = combined_labels.astype('int') combined_domain = np.vstack([np.zeros((num_test,1)),np.ones((num_test,1)),np.ones((num_test,1))*2]) from sklearn.manifold import TSNE tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=3000) source_only_tsne = tsne.fit_transform(combined_imgs) plot_embedding(source_only_tsne, combined_labels.argmax(1), combined_domain, title, save_fig=1, pname=pname)
[ "sklearn.manifold.TSNE", "numpy.max", "matplotlib.pyplot.yticks", "numpy.vstack", "mpl_toolkits.axes_grid1.ImageGrid", "numpy.min", "matplotlib.pyplot.savefig", "numpy.ones", "matplotlib.pyplot.xticks", "matplotlib.patches.Patch", "matplotlib.pyplot.title", "numpy.shape", "matplotlib.pyplot....
[((354, 367), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (364, 367), True, 'import matplotlib.pyplot as plt\n'), ((380, 433), 'mpl_toolkits.axes_grid1.ImageGrid', 'ImageGrid', (['fig', '(111)'], {'nrows_ncols': 'shape', 'axes_pad': '(0.05)'}), '(fig, 111, nrows_ncols=shape, axes_pad=0.05)\n', (389, 433), False, 'from mpl_toolkits.axes_grid1 import ImageGrid\n'), ((447, 463), 'numpy.shape', 'np.shape', (['images'], {}), '(images)\n', (455, 463), True, 'import numpy as np\n'), ((770, 780), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (778, 780), True, 'import matplotlib.pyplot as plt\n'), ((1046, 1074), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (1056, 1074), True, 'import matplotlib.pyplot as plt\n'), ((1084, 1100), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (1095, 1100), True, 'import matplotlib.pyplot as plt\n'), ((1660, 1708), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""red"""', 'label': '"""Source data"""'}), "(color='red', label='Source data')\n", (1674, 1708), True, 'import matplotlib.patches as mpatches\n'), ((1728, 1778), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""green"""', 'label': '"""Target data"""'}), "(color='green', label='Target data')\n", (1742, 1778), True, 'import matplotlib.patches as mpatches\n'), ((1784, 1828), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'handles': '[red_patch, green_patch]'}), '(handles=[red_patch, green_patch])\n', (1794, 1828), True, 'import matplotlib.pyplot as plt\n'), ((1834, 1844), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1842, 1844), True, 'import matplotlib.pyplot as plt\n'), ((2616, 2676), 'sklearn.manifold.TSNE', 'TSNE', ([], {'perplexity': '(30)', 'n_components': '(2)', 'init': '"""pca"""', 'n_iter': '(3000)'}), "(perplexity=30, n_components=2, init='pca', n_iter=3000)\n", (2620, 2676), False, 'from sklearn.manifold import TSNE\n'), ((948, 960), 'numpy.min', 'np.min', (['X', '(0)'], {}), '(X, 0)\n', (954, 960), True, 'import numpy as np\n'), ((962, 974), 'numpy.max', 'np.max', (['X', '(0)'], {}), '(X, 0)\n', (968, 974), True, 'import numpy as np\n'), ((1612, 1626), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (1622, 1626), True, 'import matplotlib.pyplot as plt\n'), ((1628, 1642), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (1638, 1642), True, 'import matplotlib.pyplot as plt\n'), ((1881, 1897), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (1890, 1897), True, 'import matplotlib.pyplot as plt\n'), ((2035, 2053), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname'], {}), '(fname)\n', (2046, 2053), True, 'import matplotlib.pyplot as plt\n'), ((2211, 2283), 'numpy.vstack', 'np.vstack', (['[xs[0:num_test, :], xt[0:num_test, :], map_xs[0:num_test, :]]'], {}), '([xs[0:num_test, :], xt[0:num_test, :], map_xs[0:num_test, :]])\n', (2220, 2283), True, 'import numpy as np\n'), ((2310, 2401), 'numpy.vstack', 'np.vstack', (['[xs_label[0:num_test, :], xt_label[0:num_test, :], xs_label[0:num_test, :]]'], {}), '([xs_label[0:num_test, :], xt_label[0:num_test, :], xs_label[0:\n num_test, :]])\n', (2319, 2401), True, 'import numpy as np\n'), ((1998, 2024), 'os.path.join', 'os.path.join', (['pname', 'fname'], {}), '(pname, fname)\n', (2010, 2024), False, 'import os\n'), ((2490, 2513), 'numpy.zeros', 'np.zeros', (['(num_test, 1)'], {}), '((num_test, 1))\n', (2498, 2513), True, 'import numpy as np\n'), ((2513, 2535), 'numpy.ones', 'np.ones', (['(num_test, 1)'], {}), '((num_test, 1))\n', (2520, 2535), True, 'import numpy as np\n'), ((622, 642), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""gray"""'], {}), "('gray')\n", (634, 642), True, 'import matplotlib.pyplot as plt\n'), ((2535, 2557), 'numpy.ones', 'np.ones', (['(num_test, 1)'], {}), '((num_test, 1))\n', (2542, 2557), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Definition of the RL policy (policy based on a neural network value model).""" import os import numpy as np from copy import deepcopy import tensorflow as tf from .policy import Policy, policy_name # _____________________ parameters _____________________ EPSILON = 1e-10 EPSILON_CHOICE = EPSILON # ________________________________________________________ class RLPolicy(Policy): """ An RL policy, that is, a policy based on a value model. Args: env (SourceTracking): an instance of the source-tracking POMDP model (ValueModel): an instance of the neural network model sym_avg (bool, optional): whether to average the value over symmetric duplicates Attributes: env (SourceTracking): source-tracking POMDP model (ValueModel): neural network model policy_index (int): policy index, set to -1 policy_name (str): name of the policy """ def __init__( self, env, model, sym_avg=True, ): super().__init__(policy=-1) # sets policy_index and policy_name self.env = env self.model = model self.sym_avg = sym_avg def _choose_action(self, ): if self.policy_index == -1: assert policy_name(self.policy_index) == "neural network" action_chosen, _ = self._value_policy() else: raise Exception("The policy " + str(self.policy) + " does not exist (yet)!") return action_chosen # __ POLICY DEFINITIONS _______________________________________ def _value_policy(self): """Chooses the action which minimizes the expected value at the next step. Returns: action_chosen (int): the best action, according to the value model expected_value (ndarray): expected value of each action, according to the value model """ inputs = [0] * self.env.Nactions probs = [0] * self.env.Nactions ishape = self.env.NN_input_shape for action in range(self.env.Nactions): inputs[action] = [] probs[action] = [] # moving agent agent_, move_possible = self.env._move(action, self.env.agent) # extracting the evidence matrix for Bayesian inference p_evidence = self.env._extract_N_from_2N(input=self.env.p_Poisson, origin=agent_) # updating p_source by Bayesian inference p_source_ = deepcopy(self.env.p_source) p_source_ = p_source_[np.newaxis, :] * p_evidence for h in range(self.env.Nhits): prob = np.sum(p_source_[h]) # norm is the proba to transit to this state = (1-pend) * p(hit) prob = np.maximum(EPSILON, prob) input = self.env._centeragent(p_source_[h] / prob, agent_) probs[action].append(prob) inputs[action].append(input) inputs = np.asarray(inputs, dtype=np.float32) # (Nactions, Nhits, inputshape) probs = np.asarray(probs, dtype=np.float32) # (Nactions, Nhits) assert inputs.shape == tuple([self.env.Nactions] + [self.env.Nhits] + list(ishape)) assert probs.shape == tuple([self.env.Nactions] + [self.env.Nhits]) inputs_shape = inputs.shape inputs = tf.reshape(inputs, shape=tuple([inputs_shape[0] * inputs_shape[1]] + list(inputs_shape[2:]))) # (Nactions * Nhits, inputshape) assert inputs.shape == tuple([self.env.Nactions * self.env.Nhits] + list(ishape)) values_next = self.model(inputs, sym_avg=self.sym_avg) # (Nactions*Nhits, 1) assert values_next.shape == tuple([self.env.Nactions * self.env.Nhits] + [1]) values_next = tf.reshape(values_next, shape=(inputs_shape[0], inputs_shape[1],)) # (Nactions, Nhits) assert values_next.shape == tuple([self.env.Nactions] + [self.env.Nhits]) assert values_next.shape == probs.shape expected_value = 1.0 + tf.math.reduce_sum(probs * values_next, axis=1) # sum over hits: (Nactions) assert expected_value.shape == tuple([self.env.Nactions]) action_chosen = np.argwhere(np.abs(expected_value - np.min(expected_value)) < EPSILON_CHOICE).flatten()[0] return action_chosen, expected_value.numpy()
[ "tensorflow.reshape", "numpy.asarray", "numpy.min", "numpy.sum", "copy.deepcopy", "tensorflow.math.reduce_sum", "numpy.maximum" ]
[((3151, 3187), 'numpy.asarray', 'np.asarray', (['inputs'], {'dtype': 'np.float32'}), '(inputs, dtype=np.float32)\n', (3161, 3187), True, 'import numpy as np\n'), ((3237, 3272), 'numpy.asarray', 'np.asarray', (['probs'], {'dtype': 'np.float32'}), '(probs, dtype=np.float32)\n', (3247, 3272), True, 'import numpy as np\n'), ((3930, 3995), 'tensorflow.reshape', 'tf.reshape', (['values_next'], {'shape': '(inputs_shape[0], inputs_shape[1])'}), '(values_next, shape=(inputs_shape[0], inputs_shape[1]))\n', (3940, 3995), True, 'import tensorflow as tf\n'), ((2676, 2703), 'copy.deepcopy', 'deepcopy', (['self.env.p_source'], {}), '(self.env.p_source)\n', (2684, 2703), False, 'from copy import deepcopy\n'), ((4180, 4227), 'tensorflow.math.reduce_sum', 'tf.math.reduce_sum', (['(probs * values_next)'], {'axis': '(1)'}), '(probs * values_next, axis=1)\n', (4198, 4227), True, 'import tensorflow as tf\n'), ((2834, 2854), 'numpy.sum', 'np.sum', (['p_source_[h]'], {}), '(p_source_[h])\n', (2840, 2854), True, 'import numpy as np\n'), ((2944, 2969), 'numpy.maximum', 'np.maximum', (['EPSILON', 'prob'], {}), '(EPSILON, prob)\n', (2954, 2969), True, 'import numpy as np\n'), ((4384, 4406), 'numpy.min', 'np.min', (['expected_value'], {}), '(expected_value)\n', (4390, 4406), True, 'import numpy as np\n')]
""" 将原来的数据库,变成一个stock id一个文件的数据库 """ import os import pandas as pd import numpy as np import pickle # 导入行情数据 file_path = 'C:/Users/Administrator/Desktop/program/data/hangqing/' file_list = os.listdir(file_path) columns_name = pd.read_csv(file_path+file_list[0]).columns hangqing_record = [] temp_record = pd.DataFrame(columns=columns_name) for i in range(len(file_list)): now_path = file_path+file_list[i] now_df = pd.read_table(now_path, sep=',') temp_record = pd.concat((temp_record, now_df), axis=0) if (i+1) % 50 == 0 or (i+1) == len(file_list): del temp_record['Unnamed: 0'] del temp_record['Unnamed: 25'] hangqing_record.append(temp_record) temp_record = pd.DataFrame(columns=columns_name) print('all:%s, now:%s' % (len(file_list), i+1)) for i in range(len(hangqing_record)): if i == 0: hangqing_df = hangqing_record[0] else: hangqing_df = pd.concat((hangqing_df, hangqing_record[i]), axis=0) del hangqing_record # 导入多因子 file_path = 'C:/Users/Administrator/Desktop/program/data/duoyinzi/' file_list = os.listdir(file_path) columns_name = pd.read_csv(file_path+file_list[0]).columns duoyinzi_record = [] temp_record = pd.DataFrame(columns=columns_name) for i in range(len(file_list)): now_file = file_list[i] now_path = file_path+now_file tradeDate = now_file[0:4]+'-'+now_file[4:6]+'-'+now_file[6:8] now_df = pd.read_table(now_path, sep=',') now_df['tradeDate'] = tradeDate temp_record = pd.concat((temp_record, now_df), axis=0) if (i+1) % 30 == 0 or (i+1) == len(file_list): del temp_record['Unnamed: 0'] del temp_record['Unnamed: 248'] duoyinzi_record.append(temp_record) temp_record = pd.DataFrame(columns=columns_name) print('all:%s, now:%s' % (len(file_list), i+1)) # 用上面的结果形成以ID为一个文件的数据库 unique_id = np.unique(hangqing_df['secID'].values) duoyinzi_columns = duoyinzi_record[0].columns for i in range(len(unique_id)): now_id = unique_id[i] now_hangqing_df = hangqing_df[hangqing_df['secID'] == now_id] now_duoyinzi_df = pd.DataFrame(columns=duoyinzi_columns) for temp in duoyinzi_record: now_temp = temp[temp['secID'] == now_id] if now_temp.shape[0] != 0: now_duoyinzi_df = pd.concat((now_duoyinzi_df, now_temp), axis=0) now_df = pd.merge(now_hangqing_df, now_duoyinzi_df, on=['secID', 'tradeDate'], how='left') pickle.dump(now_df, open('save/classified by id/'+now_id+'.pkl', 'wb')) print('all:%s, now:%s' % (len(unique_id), i+1))
[ "os.listdir", "numpy.unique", "pandas.read_csv", "pandas.merge", "pandas.read_table", "pandas.DataFrame", "pandas.concat" ]
[((207, 228), 'os.listdir', 'os.listdir', (['file_path'], {}), '(file_path)\n', (217, 228), False, 'import os\n'), ((328, 362), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns_name'}), '(columns=columns_name)\n', (340, 362), True, 'import pandas as pd\n'), ((1129, 1150), 'os.listdir', 'os.listdir', (['file_path'], {}), '(file_path)\n', (1139, 1150), False, 'import os\n'), ((1250, 1284), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns_name'}), '(columns=columns_name)\n', (1262, 1284), True, 'import pandas as pd\n'), ((1922, 1960), 'numpy.unique', 'np.unique', (["hangqing_df['secID'].values"], {}), "(hangqing_df['secID'].values)\n", (1931, 1960), True, 'import numpy as np\n'), ((245, 282), 'pandas.read_csv', 'pd.read_csv', (['(file_path + file_list[0])'], {}), '(file_path + file_list[0])\n', (256, 282), True, 'import pandas as pd\n'), ((449, 481), 'pandas.read_table', 'pd.read_table', (['now_path'], {'sep': '""","""'}), "(now_path, sep=',')\n", (462, 481), True, 'import pandas as pd\n'), ((501, 541), 'pandas.concat', 'pd.concat', (['(temp_record, now_df)'], {'axis': '(0)'}), '((temp_record, now_df), axis=0)\n', (510, 541), True, 'import pandas as pd\n'), ((1167, 1204), 'pandas.read_csv', 'pd.read_csv', (['(file_path + file_list[0])'], {}), '(file_path + file_list[0])\n', (1178, 1204), True, 'import pandas as pd\n'), ((1463, 1495), 'pandas.read_table', 'pd.read_table', (['now_path'], {'sep': '""","""'}), "(now_path, sep=',')\n", (1476, 1495), True, 'import pandas as pd\n'), ((1552, 1592), 'pandas.concat', 'pd.concat', (['(temp_record, now_df)'], {'axis': '(0)'}), '((temp_record, now_df), axis=0)\n', (1561, 1592), True, 'import pandas as pd\n'), ((2160, 2198), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'duoyinzi_columns'}), '(columns=duoyinzi_columns)\n', (2172, 2198), True, 'import pandas as pd\n'), ((2411, 2497), 'pandas.merge', 'pd.merge', (['now_hangqing_df', 'now_duoyinzi_df'], {'on': "['secID', 'tradeDate']", 'how': '"""left"""'}), "(now_hangqing_df, now_duoyinzi_df, on=['secID', 'tradeDate'], how=\n 'left')\n", (2419, 2497), True, 'import pandas as pd\n'), ((741, 775), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns_name'}), '(columns=columns_name)\n', (753, 775), True, 'import pandas as pd\n'), ((962, 1014), 'pandas.concat', 'pd.concat', (['(hangqing_df, hangqing_record[i])'], {'axis': '(0)'}), '((hangqing_df, hangqing_record[i]), axis=0)\n', (971, 1014), True, 'import pandas as pd\n'), ((1793, 1827), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns_name'}), '(columns=columns_name)\n', (1805, 1827), True, 'import pandas as pd\n'), ((2350, 2396), 'pandas.concat', 'pd.concat', (['(now_duoyinzi_df, now_temp)'], {'axis': '(0)'}), '((now_duoyinzi_df, now_temp), axis=0)\n', (2359, 2396), True, 'import pandas as pd\n')]
import io import numpy as np import tensorflow as tf from hparams import hparams from models import create_model from util import audio, textinput class Synthesizer: def load(self, checkpoint_path, model_name='tacotron'): print('Constructing model: %s' % model_name) inputs = tf.placeholder(tf.int32, [1, None], 'inputs') input_lengths = tf.placeholder(tf.int32, [1], 'input_lengths') with tf.variable_scope('model') as scope: self.model = create_model(model_name, hparams) self.model.initialize(inputs, input_lengths) print('Loading checkpoint: %s' % checkpoint_path) self.session = tf.Session() self.session.run(tf.global_variables_initializer()) saver = tf.train.Saver() saver.restore(self.session, checkpoint_path) def synthesize(self, text): seq = textinput.to_sequence(text, force_lowercase=hparams.force_lowercase, expand_abbreviations=hparams.expand_abbreviations) feed_dict = { self.model.inputs: [np.asarray(seq, dtype=np.int32)], self.model.input_lengths: np.asarray([len(seq)], dtype=np.int32) } spec = self.session.run(self.model.linear_outputs[0], feed_dict=feed_dict) out = io.BytesIO() audio.save_wav(audio.inv_spectrogram(spec.T), out) return out.getvalue()
[ "util.textinput.to_sequence", "util.audio.inv_spectrogram", "tensorflow.variable_scope", "tensorflow.placeholder", "tensorflow.train.Saver", "tensorflow.Session", "io.BytesIO", "numpy.asarray", "tensorflow.global_variables_initializer", "models.create_model" ]
[((288, 333), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[1, None]', '"""inputs"""'], {}), "(tf.int32, [1, None], 'inputs')\n", (302, 333), True, 'import tensorflow as tf\n'), ((354, 400), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[1]', '"""input_lengths"""'], {}), "(tf.int32, [1], 'input_lengths')\n", (368, 400), True, 'import tensorflow as tf\n'), ((625, 637), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (635, 637), True, 'import tensorflow as tf\n'), ((706, 722), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (720, 722), True, 'import tensorflow as tf\n'), ((814, 937), 'util.textinput.to_sequence', 'textinput.to_sequence', (['text'], {'force_lowercase': 'hparams.force_lowercase', 'expand_abbreviations': 'hparams.expand_abbreviations'}), '(text, force_lowercase=hparams.force_lowercase,\n expand_abbreviations=hparams.expand_abbreviations)\n', (835, 937), False, 'from util import audio, textinput\n'), ((1190, 1202), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (1200, 1202), False, 'import io\n'), ((410, 436), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""model"""'], {}), "('model')\n", (427, 436), True, 'import tensorflow as tf\n'), ((466, 499), 'models.create_model', 'create_model', (['model_name', 'hparams'], {}), '(model_name, hparams)\n', (478, 499), False, 'from models import create_model\n'), ((659, 692), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (690, 692), True, 'import tensorflow as tf\n'), ((1222, 1251), 'util.audio.inv_spectrogram', 'audio.inv_spectrogram', (['spec.T'], {}), '(spec.T)\n', (1243, 1251), False, 'from util import audio, textinput\n'), ((990, 1021), 'numpy.asarray', 'np.asarray', (['seq'], {'dtype': 'np.int32'}), '(seq, dtype=np.int32)\n', (1000, 1021), True, 'import numpy as np\n')]
import pandas import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn import preprocessing from helper import qda,misc_helper dataFrame = pandas.read_csv('../CSV_Data/dataset_8.csv') sum_acc = 0 sum_confusion = [[0 for x in range(24)] for y in range(24)] for i in range(100): acc,confusion = qda.find_accuracy(dataFrame) sum_acc = sum_acc+ acc sum_confusion = np.add(sum_confusion,confusion) misc_helper.write_matrix(sum_confusion,"conf_matrices/qda_conf.csv") print(sum_acc/100)
[ "numpy.add", "helper.misc_helper.write_matrix", "helper.qda.find_accuracy", "pandas.read_csv" ]
[((255, 299), 'pandas.read_csv', 'pandas.read_csv', (['"""../CSV_Data/dataset_8.csv"""'], {}), "('../CSV_Data/dataset_8.csv')\n", (270, 299), False, 'import pandas\n'), ((526, 595), 'helper.misc_helper.write_matrix', 'misc_helper.write_matrix', (['sum_confusion', '"""conf_matrices/qda_conf.csv"""'], {}), "(sum_confusion, 'conf_matrices/qda_conf.csv')\n", (550, 595), False, 'from helper import qda, misc_helper\n'), ((416, 444), 'helper.qda.find_accuracy', 'qda.find_accuracy', (['dataFrame'], {}), '(dataFrame)\n', (433, 444), False, 'from helper import qda, misc_helper\n'), ((492, 524), 'numpy.add', 'np.add', (['sum_confusion', 'confusion'], {}), '(sum_confusion, confusion)\n', (498, 524), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- #The MIT License (MIT) # #Copyright (c) 2014 <NAME> # #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: # #The above copyright notice and this permission notice shall be included in all #copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. 'Orbitals class' import numpy as np import pandas as pd from chemtools.calculators.gamessus import GamessLogParser, GamessDatParser from chemtools.calculators.gamessreader import DictionaryFile, tri2full class Orbitals(pd.DataFrame): ''' A convenience class for handling GAMESS(US) orbitals. ''' def __init__(self, *args, **kwargs): super(Orbitals, self).__init__(*args, **kwargs) @classmethod def from_files(cls, name=None, logfile=None, dictfile=None, datfile=None): ''' Initialize the `Orbitals` instance based on orbital information parsed from the `logfile` and read from the `dictfile`. Args: name : str One of `hf` or `ci` logfile : str Name of the GAMESS(US) log file dictfile : str Name of the GAMESS(US) dictionary file .F10 datfile : str : Name of the GAMESS(US) dat file ''' if name == 'hf': evec_record = 15 eval_record = 17 syml_record = 255 elif name == 'ci': evec_record = 19 eval_record = 21 syml_record = 256 elif name == 'local': pass else: raise ValueError('name should be one either "hf", "ci" or "local"') if name in ['hf', 'ci']: # parse the number of aos and mos glp = GamessLogParser(logfile) nao = glp.get_number_of_aos() nmo = glp.get_number_of_mos() # read the relevant record from the dictfile df = DictionaryFile(dictfile) # read the orbitals vector = df.read_record(evec_record) vecs = vector[:nao*nmo].reshape((nao, nmo), order='F') # read the eigenvectors evals = df.read_record(eval_record) evals = evals[:nmo] # read symmetry labels symlab = df.read_record(syml_record) symlab = symlab[:nmo] data = dict([ ('symlabels', [s.strip() for s in symlab]), ('eigenvals', evals), ('gindex', range(1, nmo + 1)), ]) elif name == 'local': gdp = GamessDatParser(datfile) vecs = gdp.get_orbitals(name) nao, nmo = vecs.shape data = dict([('gindex', range(1, nmo + 1)),]) dataframe = cls(data=data) dataframe.nao = nao dataframe.nmo = nmo dataframe.name = name dataframe.logfile = logfile dataframe.dictfile = dictfile dataframe.datfile = datfile dataframe.coeffs = pd.DataFrame(data=vecs) return dataframe def assign_lz_values(self, decimals=6, tolv=1.0e-2): ''' Determine the eigenvalues of the Lz operator for each nondegenerate or a combination of degenerate orbitals and assign them to `lzvals` column in the DataFrame The Lz integrals over atomic orbitals are read from the dictionary file record No. 379. Args: decimals : int Number of decimals to keep when comparing float eigenvalues tolv : float Threshold for keeping wights of the eiegenvalues (squared eigenvector components) WARNING: currently this only works if the eigenvalues on input are sorted ''' lzmap = {0: 'sigma', 1: 'pi', 2: 'delta', 3: 'phi'} df = DictionaryFile(self.dictfile) # read Lz integrals from the dictionary file lzvec = df.read_record(379) # expand triangular to square matrix lzints = tri2full(lzvec, sym=False) unq, indices = check_duplicates(self.eigenvals, decimals=decimals) out = [] mos = self.coeffs.values for IG, (i, j) in enumerate(indices, start=1): # transform the integrals to the MO basis lzmo = np.dot(mos[:, i:j].T, np.dot(lzints, mos[:, i:j])) # tranform to complex type lzcplx = np.zeros_like(lzmo, dtype=np.complex128) lzcplx.imag = -lzmo # diagonalize the lzcplx matrix w, v = np.linalg.eig(lzcplx) wij2 = np.multiply(np.abs(v), np.abs(v)) #x, y = np.where(wij2 > tolv) idxs = [np.nonzero(row > tolv)[0] for row in wij2] for row, comp in enumerate(idxs): out.append([(IG, w.real[m], wij2[row, m]*100.0) for m in comp]) evs = [np.unique(np.round(np.abs(np.array([x[1] for x in row])), decimals=1)) for row in out] lzvals = [int(x[0]) if x.size == 1 else np.NaN for x in evs] self['lzvals'] = [int(x[0]) if x.size == 1 else np.NaN for x in evs] self['lzlabels'] = self['lzvals'].map(lzmap) return out def lzmos(self, ETOLLZ=1.0e-6, TOLV=1.0e-2): ''' A python rewrite of the GAMESS(US) LZMOS subroutine (from symorb.src) for analyzing the Lz composition of the orbtials Args: ETOLLZ : float TOLV : float ''' lzmap = {0: 'sigma', 1: 'pi', 2: 'delta', 3: 'phi'} df = DictionaryFile(self.dictfile) # read Lz integrals from the dictionary file lzvec = df.read_record(379) # expand triangular to square matrix lzints = tri2full(lzvec, sym=False) mos = self.coeffs.values ev = self.eigenvals.values out = [] L = 0 ILAST = 0 IG = 0 N = 1 for I in range(1, self.nmo + 1): EI = 0 if I < self.nmo: EI = ev[I] if (abs(ev[I - 1] - EI) > ETOLLZ or I > self.nmo): IG += 1 # transform the integrals to the MO basis lzmo = np.dot(mos[:, ILAST:ILAST+N].T, np.dot(lzints, mos[:, ILAST:ILAST+N])) # tranform to complex type lzcplx = np.zeros_like(lzmo, dtype=np.complex128) lzcplx.imag = -lzmo # diagonalize the lzcplx matrix w, v = np.linalg.eig(lzcplx) for j in range(v.shape[0]): m = -1 temp = [] for k in range(v.shape[1]): wij = np.abs(v[j, k]) if wij*wij > TOLV: m += 1 temp.append(wij*wij*100.0) out.append([(IG, w.real[mi], temp[mi]) for mi in range(m+1)]) ILAST = I N = 1 else: N = N + 1 # should check here if the length of the evs is the same as the number of rows of the dataframe # if somethings wrong probably the ETOLLZ should be adjusted evs = [np.unique(np.round(np.abs(np.array([x[1] for x in row])), decimals=1)) for row in out] lzvals = [int(x[0]) if x.size == 1 else np.NaN for x in evs] self['lzvals'] = [int(x[0]) if x.size == 1 else np.NaN for x in evs] self['lzlabels'] = self['lzvals'].map(lzmap) self['ig'] = [x[0][0] for x in out] return None def fragment_populations(self): ''' Calculate the fragment populations and assign each orbital to a fragment ''' glp = GamessLogParser(self.logfile) self.aoinfo = pd.DataFrame(data=glp.get_ao_labels(orbs=self.name + ' orbs')) idx1 = self.aoinfo.loc[self.aoinfo['center'] == 1, 'index'].values self['center 1 pop'] = (self.coeffs.loc[idx1, :]**2).sum() idx2 = self.aoinfo.loc[self.aoinfo['center'] == 2, 'index'].values self['center 2 pop'] = (self.coeffs.loc[idx2, :]**2).sum() self['fragment'] = np.where(self['center 1 pop'] > self['center 2 pop'], 1, 2) def check_duplicates(a, decimals=6): ''' This funciton assumes that the array `a` is sorted http://stackoverflow.com/questions/25264798/checking-for-and-indexing-non-unique-duplicate-values-in-a-numpy-array http://stackoverflow.com/questions/5426908/find-unique-elements-of-floating-point-array-in-numpy-with-comparison-using-a-d ''' unq, unq_idx, unq_cnt = np.unique(np.round(a, decimals=decimals), return_inverse=True, return_counts=True) indices = np.zeros((len(unq), 2), dtype=np.int) for ig in range(len(unq)): idx = np.nonzero(unq_idx == ig)[0] indices[ig, :] = [np.min(idx), np.max(idx) + 1] return unq, indices
[ "numpy.abs", "numpy.linalg.eig", "chemtools.calculators.gamessreader.DictionaryFile", "numpy.where", "numpy.max", "chemtools.calculators.gamessus.GamessDatParser", "numpy.array", "chemtools.calculators.gamessreader.tri2full", "chemtools.calculators.gamessus.GamessLogParser", "numpy.dot", "numpy....
[((3812, 3835), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'vecs'}), '(data=vecs)\n', (3824, 3835), True, 'import pandas as pd\n'), ((4632, 4661), 'chemtools.calculators.gamessreader.DictionaryFile', 'DictionaryFile', (['self.dictfile'], {}), '(self.dictfile)\n', (4646, 4661), False, 'from chemtools.calculators.gamessreader import DictionaryFile, tri2full\n'), ((4813, 4839), 'chemtools.calculators.gamessreader.tri2full', 'tri2full', (['lzvec'], {'sym': '(False)'}), '(lzvec, sym=False)\n', (4821, 4839), False, 'from chemtools.calculators.gamessreader import DictionaryFile, tri2full\n'), ((6327, 6356), 'chemtools.calculators.gamessreader.DictionaryFile', 'DictionaryFile', (['self.dictfile'], {}), '(self.dictfile)\n', (6341, 6356), False, 'from chemtools.calculators.gamessreader import DictionaryFile, tri2full\n'), ((6508, 6534), 'chemtools.calculators.gamessreader.tri2full', 'tri2full', (['lzvec'], {'sym': '(False)'}), '(lzvec, sym=False)\n', (6516, 6534), False, 'from chemtools.calculators.gamessreader import DictionaryFile, tri2full\n'), ((8464, 8493), 'chemtools.calculators.gamessus.GamessLogParser', 'GamessLogParser', (['self.logfile'], {}), '(self.logfile)\n', (8479, 8493), False, 'from chemtools.calculators.gamessus import GamessLogParser, GamessDatParser\n'), ((8892, 8951), 'numpy.where', 'np.where', (["(self['center 1 pop'] > self['center 2 pop'])", '(1)', '(2)'], {}), "(self['center 1 pop'] > self['center 2 pop'], 1, 2)\n", (8900, 8951), True, 'import numpy as np\n'), ((9347, 9377), 'numpy.round', 'np.round', (['a'], {'decimals': 'decimals'}), '(a, decimals=decimals)\n', (9355, 9377), True, 'import numpy as np\n'), ((2566, 2590), 'chemtools.calculators.gamessus.GamessLogParser', 'GamessLogParser', (['logfile'], {}), '(logfile)\n', (2581, 2590), False, 'from chemtools.calculators.gamessus import GamessLogParser, GamessDatParser\n'), ((2750, 2774), 'chemtools.calculators.gamessreader.DictionaryFile', 'DictionaryFile', (['dictfile'], {}), '(dictfile)\n', (2764, 2774), False, 'from chemtools.calculators.gamessreader import DictionaryFile, tri2full\n'), ((5209, 5249), 'numpy.zeros_like', 'np.zeros_like', (['lzmo'], {'dtype': 'np.complex128'}), '(lzmo, dtype=np.complex128)\n', (5222, 5249), True, 'import numpy as np\n'), ((5346, 5367), 'numpy.linalg.eig', 'np.linalg.eig', (['lzcplx'], {}), '(lzcplx)\n', (5359, 5367), True, 'import numpy as np\n'), ((9518, 9543), 'numpy.nonzero', 'np.nonzero', (['(unq_idx == ig)'], {}), '(unq_idx == ig)\n', (9528, 9543), True, 'import numpy as np\n'), ((9573, 9584), 'numpy.min', 'np.min', (['idx'], {}), '(idx)\n', (9579, 9584), True, 'import numpy as np\n'), ((3392, 3416), 'chemtools.calculators.gamessus.GamessDatParser', 'GamessDatParser', (['datfile'], {}), '(datfile)\n', (3407, 3416), False, 'from chemtools.calculators.gamessus import GamessLogParser, GamessDatParser\n'), ((5119, 5146), 'numpy.dot', 'np.dot', (['lzints', 'mos[:, i:j]'], {}), '(lzints, mos[:, i:j])\n', (5125, 5146), True, 'import numpy as np\n'), ((5400, 5409), 'numpy.abs', 'np.abs', (['v'], {}), '(v)\n', (5406, 5409), True, 'import numpy as np\n'), ((5411, 5420), 'numpy.abs', 'np.abs', (['v'], {}), '(v)\n', (5417, 5420), True, 'import numpy as np\n'), ((7092, 7132), 'numpy.zeros_like', 'np.zeros_like', (['lzmo'], {'dtype': 'np.complex128'}), '(lzmo, dtype=np.complex128)\n', (7105, 7132), True, 'import numpy as np\n'), ((7241, 7262), 'numpy.linalg.eig', 'np.linalg.eig', (['lzcplx'], {}), '(lzcplx)\n', (7254, 7262), True, 'import numpy as np\n'), ((9586, 9597), 'numpy.max', 'np.max', (['idx'], {}), '(idx)\n', (9592, 9597), True, 'import numpy as np\n'), ((5484, 5506), 'numpy.nonzero', 'np.nonzero', (['(row > tolv)'], {}), '(row > tolv)\n', (5494, 5506), True, 'import numpy as np\n'), ((6985, 7024), 'numpy.dot', 'np.dot', (['lzints', 'mos[:, ILAST:ILAST + N]'], {}), '(lzints, mos[:, ILAST:ILAST + N])\n', (6991, 7024), True, 'import numpy as np\n'), ((5695, 5724), 'numpy.array', 'np.array', (['[x[1] for x in row]'], {}), '([x[1] for x in row])\n', (5703, 5724), True, 'import numpy as np\n'), ((7443, 7458), 'numpy.abs', 'np.abs', (['v[j, k]'], {}), '(v[j, k])\n', (7449, 7458), True, 'import numpy as np\n'), ((7982, 8011), 'numpy.array', 'np.array', (['[x[1] for x in row]'], {}), '([x[1] for x in row])\n', (7990, 8011), True, 'import numpy as np\n')]
import unittest import glob import os.path as op def BOLD_FIR_files( analysis_info, experiment, fir_file_reward_list = '', glm_file_mapper_list = '', behavior_file_list = '', mapper_contrast = 'stim', h5_file = '', roi_list = ['V1','V2','V3'] ): """Performs a per-slice FIR deconvolution on nifti-files in_files, with per-slice regressors from slice_regressor_list of nifti files, and per-TR regressors from vol_regressors text file. Uses standard HRF and its time-derivative. Assumes slices to be the last spatial dimension of nifti files, and time to be the last. Parameters ---------- in_file : str Absolute path to nifti-file. slice_regressor_list : list list of absolute paths to per-slice regressor nifti files vol_regressor_list : str absolute path to per-TR regressor text file Returns ------- res_file : str Absolute path to nifti-file containing residuals after regression. rsq_file : str Absolute path to nifti-file containing rsq of regression. beta_file : str Absolute path to nifti-file containing betas from regression. """ import nibabel as nib import numpy as np import numpy.linalg as LA import scipy as sp import os import os.path as op import pandas as pd from spynoza.nodes.utils import get_scaninfo from fir import FIRDeconvolution from hedfpy import HDFEyeOperator import tempfile import bottleneck as bn # from behavior import behavior_timing from utils import roi_data_from_hdf threshold = 1.67 zero_interval = [-2.5,-0.5] # roi data mapper_alias = op.split(glm_file_mapper_list[0])[-1][:-7] + '_logp' # the first file is longer in one or two subjects, so we take the scaninfo of the second file TR, dims, dyns, voxsize, affine = get_scaninfo(fir_file_reward_list[1]) # behavior event_names, all_behav_event_times, rename_dict, which_event_name_rewarded = behavior_timing(experiment, behavior_file_list, dyns, TR) fir_aliases = [op.split(fir_file_reward_list[0])[-1][:-7] + '_%s'%en for en in event_names] out_figures = [] for roi in roi_list: contrast_data = roi_data_from_hdf(data_types_wildcards = [mapper_alias], roi_name_wildcard = roi, hdf5_file = h5_file, folder_alias = 'GLM') fir_data = [roi_data_from_hdf(data_types_wildcards = [fa], roi_name_wildcard = roi, hdf5_file = h5_file, folder_alias = 'GLM') for fa in fir_aliases] deconvolution_interval_timepoints = np.linspace(analysis_info['fir_interval'][0], analysis_info['fir_interval'][1], fir_data[0].shape[-1], endpoint = False) # for experiment 'unpredictable' and 'variable' the masking contrast is the initial mapper if experiment in ['unpredictable', 'variable', 'stream-up']: if mapper_contrast == 'stim': fir_time_course_dict = {en: fd[contrast_data[:,1]>threshold].mean(axis = 0) for en,fd in zip(event_names, fir_data)} elif mapper == 'surround': fir_time_course_dict = {en: fd[contrast_data[:,4]>threshold].mean(axis = 0) for en,fd in zip(event_names, fir_data)} elif experiment == 'predictable': rewarded_location, rewarded_orientation = which_event_name_rewarded.split('_') # check which stimulus was rewarded and implement correct contrast values if rewarded_location == 'left': rsci,nrsci = [1,4], [7,10] elif rewarded_location == 'right': rsci,nrsci = [7,10], [1,4] # create joined contrast values (not averaged just yet - T values should sort-of sum.) if mapper_contrast == 'rewarded_stim': contrast_data_joined = contrast_data[:,rsci[0]] + contrast_data[:,rsci[1]] elif mapper_contrast == 'nonrewarded_stim': contrast_data_joined = contrast_data[:,nrsci[0]] + contrast_data[:,nrsci[1]] else: print('unknown mask type for experiment predictable') # create ROIs with these contrasts fir_time_course_dict = {en: fd[contrast_data_joined>threshold].mean(axis = 0) for en,fd in zip(event_names, fir_data)} if experiment == 'unpredictable': out_figures.append( plot_fir_results_unpredictable(deconvolution_interval_timepoints, event_names, fir_time_course_dict, zero_interval = zero_interval, use_zero_interval = False, suffix = roi )) elif experiment == 'predictable': out_figures.append( plot_fir_results_predictable(deconvolution_interval_timepoints, rename_dict, event_names, fir_time_course_dict, zero_interval = zero_interval, use_zero_interval = False, suffix = roi )) elif experiment == 'variable': out_figures.append( plot_fir_results_variable(deconvolution_interval_timepoints, event_names, fir_time_course_dict, zero_interval = zero_interval, use_zero_interval = False, suffix = roi )) # the derived data types are added in the plot functions, and overwritten such that the no-zero'd data are saved out_values = np.array([np.squeeze(fir_time_course_dict[key]) for key in fir_time_course_dict.iterkeys()]).T out_columns = [key for key in fir_time_course_dict.iterkeys()] out_df = pd.DataFrame(out_values, columns = out_columns, index = deconvolution_interval_timepoints) store = pd.HDFStore(h5_file) store['/fir/'+experiment+'/'+roi+'_'+mapper_contrast] = out_df store.close() return out_figures class FIRTestCase(unittest.TestCase): def setUp(self): import glob import os.path as op from utils.plotting import * from utils.behavior import behavior_timing # standard test path and subject test_path = '/home/shared/-2014/reward/new/' test_sj = 'sub-004' h5_file= glob.glob(op.join(test_path, test_sj, 'h5/*roi.h5'))[0] fir_frequency = 10 fir_interval = [-2.0,7.0] data_type = '_pupil_bp_zscore' lost_signal_rate_threshold = 0.15 method = 'fir' experiment = 'unpredictable' # input files fir_file_reward_list = glob.glob(op.join(test_path, test_sj, 'psc/*-unpredictable_reward*.nii.gz')) fir_file_reward_list.sort() glm_file_mapper_list = glob.glob(op.join(test_path, test_sj, 'psc/*-unpredictable_mapper*.nii.gz')) glm_file_mapper_list.sort() # behavior files behavior_file_list = glob.glob(op.join(test_path, test_sj, 'events/tsv/*-unpredictable_reward*.tsv')) behavior_file_list.sort() experiment = 'predictable' # input files fir_file_reward_list = glob.glob(op.join(test_path, test_sj, 'psc/*-predictable_reward*.nii.gz')) fir_file_reward_list.sort() glm_file_mapper_list = glob.glob(op.join(test_path, test_sj, 'psc/*-predictable_mapper*.nii.gz')) glm_file_mapper_list.sort() # behavior files behavior_file_list = glob.glob(op.join(test_path, test_sj, 'events/tsv/*-predictable_reward*.tsv')) behavior_file_list.sort() experiment = 'variable' # # input files fir_file_reward_list = glob.glob(op.join(test_path, test_sj, 'psc/*-variable_*_reward*.nii.gz')) fir_file_reward_list.sort() glm_file_mapper_list = glob.glob(op.join(test_path, test_sj, 'psc/*-unpredictable_mapper*.nii.gz')) glm_file_mapper_list.sort() # behavior files behavior_file_list = glob.glob(op.join(test_path, test_sj, 'events/tsv/*-variable_*_reward*.tsv')) behavior_file_list.sort() def runTest(self): fit_FIR_nuisances_all_files( example_func = self.example_func, in_files = self.in_files, slice_regressor_lists = self.slice_regressor_lists, vol_regressor_list = self.vol_regressor_list, behavior_file_list = self.behavior_file_list, fir_frequency = 4, fir_interval = [-3.0,15.0] )
[ "utils.behavior.behavior_timing", "pandas.DataFrame", "spynoza.nodes.utils.get_scaninfo", "os.path.join", "os.path.split", "numpy.squeeze", "numpy.linspace", "utils.roi_data_from_hdf", "pandas.HDFStore" ]
[((2062, 2099), 'spynoza.nodes.utils.get_scaninfo', 'get_scaninfo', (['fir_file_reward_list[1]'], {}), '(fir_file_reward_list[1])\n', (2074, 2099), False, 'from spynoza.nodes.utils import get_scaninfo\n'), ((2198, 2255), 'utils.behavior.behavior_timing', 'behavior_timing', (['experiment', 'behavior_file_list', 'dyns', 'TR'], {}), '(experiment, behavior_file_list, dyns, TR)\n', (2213, 2255), False, 'from utils.behavior import behavior_timing\n'), ((2423, 2544), 'utils.roi_data_from_hdf', 'roi_data_from_hdf', ([], {'data_types_wildcards': '[mapper_alias]', 'roi_name_wildcard': 'roi', 'hdf5_file': 'h5_file', 'folder_alias': '"""GLM"""'}), "(data_types_wildcards=[mapper_alias], roi_name_wildcard=\n roi, hdf5_file=h5_file, folder_alias='GLM')\n", (2440, 2544), False, 'from utils import roi_data_from_hdf\n'), ((2750, 2873), 'numpy.linspace', 'np.linspace', (["analysis_info['fir_interval'][0]", "analysis_info['fir_interval'][1]", 'fir_data[0].shape[-1]'], {'endpoint': '(False)'}), "(analysis_info['fir_interval'][0], analysis_info['fir_interval']\n [1], fir_data[0].shape[-1], endpoint=False)\n", (2761, 2873), True, 'import numpy as np\n'), ((6677, 6768), 'pandas.DataFrame', 'pd.DataFrame', (['out_values'], {'columns': 'out_columns', 'index': 'deconvolution_interval_timepoints'}), '(out_values, columns=out_columns, index=\n deconvolution_interval_timepoints)\n', (6689, 6768), True, 'import pandas as pd\n'), ((6785, 6805), 'pandas.HDFStore', 'pd.HDFStore', (['h5_file'], {}), '(h5_file)\n', (6796, 6805), True, 'import pandas as pd\n'), ((2568, 2678), 'utils.roi_data_from_hdf', 'roi_data_from_hdf', ([], {'data_types_wildcards': '[fa]', 'roi_name_wildcard': 'roi', 'hdf5_file': 'h5_file', 'folder_alias': '"""GLM"""'}), "(data_types_wildcards=[fa], roi_name_wildcard=roi,\n hdf5_file=h5_file, folder_alias='GLM')\n", (2585, 2678), False, 'from utils import roi_data_from_hdf\n'), ((7589, 7654), 'os.path.join', 'op.join', (['test_path', 'test_sj', '"""psc/*-unpredictable_reward*.nii.gz"""'], {}), "(test_path, test_sj, 'psc/*-unpredictable_reward*.nii.gz')\n", (7596, 7654), True, 'import os.path as op\n'), ((7733, 7798), 'os.path.join', 'op.join', (['test_path', 'test_sj', '"""psc/*-unpredictable_mapper*.nii.gz"""'], {}), "(test_path, test_sj, 'psc/*-unpredictable_mapper*.nii.gz')\n", (7740, 7798), True, 'import os.path as op\n'), ((7900, 7969), 'os.path.join', 'op.join', (['test_path', 'test_sj', '"""events/tsv/*-unpredictable_reward*.tsv"""'], {}), "(test_path, test_sj, 'events/tsv/*-unpredictable_reward*.tsv')\n", (7907, 7969), True, 'import os.path as op\n'), ((8104, 8167), 'os.path.join', 'op.join', (['test_path', 'test_sj', '"""psc/*-predictable_reward*.nii.gz"""'], {}), "(test_path, test_sj, 'psc/*-predictable_reward*.nii.gz')\n", (8111, 8167), True, 'import os.path as op\n'), ((8246, 8309), 'os.path.join', 'op.join', (['test_path', 'test_sj', '"""psc/*-predictable_mapper*.nii.gz"""'], {}), "(test_path, test_sj, 'psc/*-predictable_mapper*.nii.gz')\n", (8253, 8309), True, 'import os.path as op\n'), ((8411, 8478), 'os.path.join', 'op.join', (['test_path', 'test_sj', '"""events/tsv/*-predictable_reward*.tsv"""'], {}), "(test_path, test_sj, 'events/tsv/*-predictable_reward*.tsv')\n", (8418, 8478), True, 'import os.path as op\n'), ((8612, 8674), 'os.path.join', 'op.join', (['test_path', 'test_sj', '"""psc/*-variable_*_reward*.nii.gz"""'], {}), "(test_path, test_sj, 'psc/*-variable_*_reward*.nii.gz')\n", (8619, 8674), True, 'import os.path as op\n'), ((8753, 8818), 'os.path.join', 'op.join', (['test_path', 'test_sj', '"""psc/*-unpredictable_mapper*.nii.gz"""'], {}), "(test_path, test_sj, 'psc/*-unpredictable_mapper*.nii.gz')\n", (8760, 8818), True, 'import os.path as op\n'), ((8920, 8986), 'os.path.join', 'op.join', (['test_path', 'test_sj', '"""events/tsv/*-variable_*_reward*.tsv"""'], {}), "(test_path, test_sj, 'events/tsv/*-variable_*_reward*.tsv')\n", (8927, 8986), True, 'import os.path as op\n'), ((1872, 1905), 'os.path.split', 'op.split', (['glm_file_mapper_list[0]'], {}), '(glm_file_mapper_list[0])\n', (1880, 1905), True, 'import os.path as op\n'), ((7275, 7316), 'os.path.join', 'op.join', (['test_path', 'test_sj', '"""h5/*roi.h5"""'], {}), "(test_path, test_sj, 'h5/*roi.h5')\n", (7282, 7316), True, 'import os.path as op\n'), ((2275, 2308), 'os.path.split', 'op.split', (['fir_file_reward_list[0]'], {}), '(fir_file_reward_list[0])\n', (2283, 2308), True, 'import os.path as op\n'), ((6503, 6540), 'numpy.squeeze', 'np.squeeze', (['fir_time_course_dict[key]'], {}), '(fir_time_course_dict[key])\n', (6513, 6540), True, 'import numpy as np\n')]
#! /usr/bin/python3 from logging import fatal from math import atan2 import matplotlib.pyplot as plt import numpy as np import cv2 import rospy from rospy.core import rospywarn import tf2_ros import time from std_msgs.msg import Float32 from geometry_msgs.msg import QuaternionStamped from geometry_msgs.msg import PointStamped from transtonumpy import msg_to_se3 import copy class ourFilter(): def __init__(self): rospy.init_node('dataConv', anonymous=True) self.tfBuffer = tf2_ros.Buffer() self.data = [] self.start_time = None self.last_time = rospy.get_time() self.human_velocity = [] #timestamp, speed self.human_dist = [] #timestamp, distance def reciever_of_data(self, msg): laser_point=PointStamped() laser_point.header = msg.header laser_point.point.x = msg.quaternion.x laser_point.point.y = msg.quaternion.y laser_point.point.z = msg.quaternion.z newPoint = copy.deepcopy(laser_point) newPoint2 = copy.deepcopy(laser_point) time_now = msg.header.stamp if self.start_time == None or time_now.to_sec() < self.start_time: self.start_time = time_now.to_sec() self.last_time = time.time() trans2 = None targetFrame = "odom" angleFrame = "base_link" try: trans = self.tfBuffer.lookup_transform(targetFrame, laser_point.header.frame_id, time_now, rospy.Duration(1)) trans = msg_to_se3(trans) newPoint_stuff = np.matmul(trans, np.array([laser_point.point.x, laser_point.point.y, laser_point.point.z, 1]).T ) newPoint.point.x = newPoint_stuff[0] newPoint.point.y = newPoint_stuff[1] newPoint.point.z = newPoint_stuff[2] trans2 = self.tfBuffer.lookup_transform(angleFrame, laser_point.header.frame_id, time_now, rospy.Duration(1)) trans2 = msg_to_se3(trans2) newPoint_stuff = np.matmul(trans2, np.array([laser_point.point.x, laser_point.point.y, laser_point.point.z, 1]).T ) newPoint2.point.x = newPoint_stuff[0] newPoint2.point.y = newPoint_stuff[1] newPoint2.point.z = newPoint_stuff[2] trans3 = self.tfBuffer.lookup_transform(targetFrame, "flat_body", time_now, rospy.Duration(1)) next_tuple = (time_now.to_sec(), newPoint.point.x, newPoint.point.y, newPoint.point.z, trans3.transform.translation.x, trans3.transform.translation.y, trans3.transform.translation.z, atan2(newPoint2.point.y, newPoint2.point.x)) self.data.append(next_tuple) except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException) as e: print(e) print("Noped the fuck out of that transform") def velocity_reciever(self, msg): self.human_velocity.append([rospy.get_time(), msg.data]) def dist_reciever(self, msg): self.human_dist.append([rospy.get_time(), msg.data]) def main(self): self.people_msgs = rospy.Subscriber('/good_detections', QuaternionStamped, self.reciever_of_data) self.human_vel_msgs = rospy.Subscriber('/human_velocity', Float32, self.velocity_reciever) self.human_dist_msgs = rospy.Subscriber('/distance_to_robot', Float32, self.dist_reciever) self.listener = tf2_ros.TransformListener(self.tfBuffer) #new_rate = rospy.Rate(10) while not rospy.is_shutdown(): time.sleep(1) self.data = sorted(self.data, key=lambda a: a[0]) if len(self.data) == 0: return np_data = np.array(self.data) first_time = copy.deepcopy(np_data[0, 0]) np_data[:, 0] = np_data[:, 0] - first_time hu_vel = np.array(self.human_velocity) hu_vel[:, 0] = hu_vel[:, 0] - first_time hu_dist = np.array(self.human_dist) hu_dist[:,0] = hu_dist[:, 0] - first_time all_data = np.zeros((max(np_data.shape[0], hu_vel.shape[0], hu_dist.shape[0]), 12)) all_data[:np_data.shape[0], 0:8] = np_data all_data[:hu_vel.shape[0], 8:10] = hu_vel all_data[:hu_dist.shape[0], 10:12] = hu_dist np.savetxt("foo.csv", all_data, delimiter=",", header="stamp,people_x,people_y,people_z,spot_x,spot_y,spot_z,angle,stamp,human_vel,stamp,human_dist") if __name__=="__main__": myStuff = ourFilter() myStuff.main()
[ "rospy.is_shutdown", "tf2_ros.TransformListener", "rospy.init_node", "rospy.get_time", "transtonumpy.msg_to_se3", "time.sleep", "geometry_msgs.msg.PointStamped", "tf2_ros.Buffer", "numpy.array", "math.atan2", "numpy.savetxt", "copy.deepcopy", "rospy.Duration", "rospy.Subscriber", "time.t...
[((423, 466), 'rospy.init_node', 'rospy.init_node', (['"""dataConv"""'], {'anonymous': '(True)'}), "('dataConv', anonymous=True)\n", (438, 466), False, 'import rospy\n'), ((485, 501), 'tf2_ros.Buffer', 'tf2_ros.Buffer', ([], {}), '()\n', (499, 501), False, 'import tf2_ros\n'), ((563, 579), 'rospy.get_time', 'rospy.get_time', ([], {}), '()\n', (577, 579), False, 'import rospy\n'), ((718, 732), 'geometry_msgs.msg.PointStamped', 'PointStamped', ([], {}), '()\n', (730, 732), False, 'from geometry_msgs.msg import PointStamped\n'), ((903, 929), 'copy.deepcopy', 'copy.deepcopy', (['laser_point'], {}), '(laser_point)\n', (916, 929), False, 'import copy\n'), ((944, 970), 'copy.deepcopy', 'copy.deepcopy', (['laser_point'], {}), '(laser_point)\n', (957, 970), False, 'import copy\n'), ((1130, 1141), 'time.time', 'time.time', ([], {}), '()\n', (1139, 1141), False, 'import time\n'), ((2791, 2869), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/good_detections"""', 'QuaternionStamped', 'self.reciever_of_data'], {}), "('/good_detections', QuaternionStamped, self.reciever_of_data)\n", (2807, 2869), False, 'import rospy\n'), ((2894, 2962), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/human_velocity"""', 'Float32', 'self.velocity_reciever'], {}), "('/human_velocity', Float32, self.velocity_reciever)\n", (2910, 2962), False, 'import rospy\n'), ((2988, 3055), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/distance_to_robot"""', 'Float32', 'self.dist_reciever'], {}), "('/distance_to_robot', Float32, self.dist_reciever)\n", (3004, 3055), False, 'import rospy\n'), ((3074, 3114), 'tf2_ros.TransformListener', 'tf2_ros.TransformListener', (['self.tfBuffer'], {}), '(self.tfBuffer)\n', (3099, 3114), False, 'import tf2_ros\n'), ((3297, 3316), 'numpy.array', 'np.array', (['self.data'], {}), '(self.data)\n', (3305, 3316), True, 'import numpy as np\n'), ((3332, 3360), 'copy.deepcopy', 'copy.deepcopy', (['np_data[0, 0]'], {}), '(np_data[0, 0])\n', (3345, 3360), False, 'import copy\n'), ((3418, 3447), 'numpy.array', 'np.array', (['self.human_velocity'], {}), '(self.human_velocity)\n', (3426, 3447), True, 'import numpy as np\n'), ((3504, 3529), 'numpy.array', 'np.array', (['self.human_dist'], {}), '(self.human_dist)\n', (3512, 3529), True, 'import numpy as np\n'), ((3800, 3959), 'numpy.savetxt', 'np.savetxt', (['"""foo.csv"""', 'all_data'], {'delimiter': '""","""', 'header': '"""stamp,people_x,people_y,people_z,spot_x,spot_y,spot_z,angle,stamp,human_vel,stamp,human_dist"""'}), "('foo.csv', all_data, delimiter=',', header=\n 'stamp,people_x,people_y,people_z,spot_x,spot_y,spot_z,angle,stamp,human_vel,stamp,human_dist'\n )\n", (3810, 3959), True, 'import numpy as np\n'), ((1339, 1356), 'transtonumpy.msg_to_se3', 'msg_to_se3', (['trans'], {}), '(trans)\n', (1349, 1356), False, 'from transtonumpy import msg_to_se3\n'), ((1721, 1739), 'transtonumpy.msg_to_se3', 'msg_to_se3', (['trans2'], {}), '(trans2)\n', (1731, 1739), False, 'from transtonumpy import msg_to_se3\n'), ((3156, 3175), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (3173, 3175), False, 'import rospy\n'), ((3180, 3193), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (3190, 3193), False, 'import time\n'), ((1309, 1326), 'rospy.Duration', 'rospy.Duration', (['(1)'], {}), '(1)\n', (1323, 1326), False, 'import rospy\n'), ((1690, 1707), 'rospy.Duration', 'rospy.Duration', (['(1)'], {}), '(1)\n', (1704, 1707), False, 'import rospy\n'), ((2065, 2082), 'rospy.Duration', 'rospy.Duration', (['(1)'], {}), '(1)\n', (2079, 2082), False, 'import rospy\n'), ((2326, 2369), 'math.atan2', 'atan2', (['newPoint2.point.y', 'newPoint2.point.x'], {}), '(newPoint2.point.y, newPoint2.point.x)\n', (2331, 2369), False, 'from math import atan2\n'), ((2635, 2651), 'rospy.get_time', 'rospy.get_time', ([], {}), '()\n', (2649, 2651), False, 'import rospy\n'), ((2722, 2738), 'rospy.get_time', 'rospy.get_time', ([], {}), '()\n', (2736, 2738), False, 'import rospy\n'), ((1394, 1470), 'numpy.array', 'np.array', (['[laser_point.point.x, laser_point.point.y, laser_point.point.z, 1]'], {}), '([laser_point.point.x, laser_point.point.y, laser_point.point.z, 1])\n', (1402, 1470), True, 'import numpy as np\n'), ((1778, 1854), 'numpy.array', 'np.array', (['[laser_point.point.x, laser_point.point.y, laser_point.point.z, 1]'], {}), '([laser_point.point.x, laser_point.point.y, laser_point.point.z, 1])\n', (1786, 1854), True, 'import numpy as np\n')]
""" 4. How to combine many series to form a dataframe? """ """ Difficulty Level: L1 """ """ Combine ser1 and ser2 to form a dataframe. """ """ Input """ """ import numpy as np ser1 = pd.Series(list('abcedfghijklmnopqrstuvwxyz')) ser2 = pd.Series(np.arange(26)) """ # Input import numpy as np ser1 = pd.Series(list('abcedfghijklmnopqrstuvwxyz')) ser2 = pd.Series(np.arange(26)) # Solution 1 df = pd.concat([ser1, ser2], axis=1) # Solution 2 df = pd.DataFrame({'col1': ser1, 'col2': ser2}) print(df.head())
[ "numpy.arange" ]
[((363, 376), 'numpy.arange', 'np.arange', (['(26)'], {}), '(26)\n', (372, 376), True, 'import numpy as np\n')]
"""Draw a fancy map""" import sys import numpy as np from shapely.wkb import loads from matplotlib.patches import Polygon import matplotlib.colors as mpcolors import matplotlib.pyplot as plt import cartopy.crs as ccrs from pyiem.plot import MapPlot from pyiem.util import get_dbconn def main(): """GO!""" pgconn = get_dbconn("idep") cursor = pgconn.cursor() scenario = int(sys.argv[1]) mp = MapPlot( sector="iowa", axisbg="white", nologo=True, subtitle="1 Jan 2014 thru 31 Dec 2014", caption="Daily Erosion Project", title=( "Harvest Index 0.8 Change in 2014 Soil Delivery " "from Baseline" ), ) cursor.execute( """ with baseline as ( SELECT huc_12, sum(avg_delivery) * 4.463 as loss from results_by_huc12 where valid between '2014-01-01' and '2015-01-01' and scenario = 0 GROUP by huc_12), scenario as ( SELECT huc_12, sum(avg_delivery) * 4.463 as loss from results_by_huc12 where valid between '2014-01-01' and '2015-01-01' and scenario = %s GROUP by huc_12), agg as ( SELECT b.huc_12, b.loss as baseline_loss, s.loss as scenario_loss from baseline b LEFT JOIN scenario s on (b.huc_12 = s.huc_12)) SELECT ST_Transform(simple_geom, 4326), (scenario_loss - baseline_loss) / 1.0 as val, i.huc_12 from huc12 i JOIN agg d on (d.huc_12 = i.huc_12) WHERE i.states ~* 'IA' ORDER by val DESC """, (scenario,), ) # bins = np.arange(0, 101, 10) bins = [-5, -2, -1, -0.5, 0, 0.5, 1, 2, 5] cmap = plt.get_cmap("BrBG_r") cmap.set_under("purple") cmap.set_over("black") norm = mpcolors.BoundaryNorm(bins, cmap.N) for row in cursor: polygon = loads(row[0].decode("hex")) arr = np.asarray(polygon.exterior) points = mp.ax.projection.transform_points( ccrs.Geodetic(), arr[:, 0], arr[:, 1] ) val = float(row[1]) # We have very small negative numbers that should just be near a # positive zero if val < 0 and val > -0.1: val = 0.001 color = cmap(norm([val]))[0] poly = Polygon(points[:, :2], fc=color, ec="k", zorder=2, lw=0.1) mp.ax.add_patch(poly) mp.draw_colorbar(bins, cmap, norm, units="T/a/yr") mp.drawcounties() mp.postprocess(filename="test.png") if __name__ == "__main__": main()
[ "numpy.asarray", "pyiem.util.get_dbconn", "pyiem.plot.MapPlot", "matplotlib.colors.BoundaryNorm", "cartopy.crs.Geodetic", "matplotlib.patches.Polygon", "matplotlib.pyplot.get_cmap" ]
[((325, 343), 'pyiem.util.get_dbconn', 'get_dbconn', (['"""idep"""'], {}), "('idep')\n", (335, 343), False, 'from pyiem.util import get_dbconn\n'), ((415, 619), 'pyiem.plot.MapPlot', 'MapPlot', ([], {'sector': '"""iowa"""', 'axisbg': '"""white"""', 'nologo': '(True)', 'subtitle': '"""1 Jan 2014 thru 31 Dec 2014"""', 'caption': '"""Daily Erosion Project"""', 'title': '"""Harvest Index 0.8 Change in 2014 Soil Delivery from Baseline"""'}), "(sector='iowa', axisbg='white', nologo=True, subtitle=\n '1 Jan 2014 thru 31 Dec 2014', caption='Daily Erosion Project', title=\n 'Harvest Index 0.8 Change in 2014 Soil Delivery from Baseline')\n", (422, 619), False, 'from pyiem.plot import MapPlot\n'), ((1623, 1645), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""BrBG_r"""'], {}), "('BrBG_r')\n", (1635, 1645), True, 'import matplotlib.pyplot as plt\n'), ((1713, 1748), 'matplotlib.colors.BoundaryNorm', 'mpcolors.BoundaryNorm', (['bins', 'cmap.N'], {}), '(bins, cmap.N)\n', (1734, 1748), True, 'import matplotlib.colors as mpcolors\n'), ((1833, 1861), 'numpy.asarray', 'np.asarray', (['polygon.exterior'], {}), '(polygon.exterior)\n', (1843, 1861), True, 'import numpy as np\n'), ((2210, 2268), 'matplotlib.patches.Polygon', 'Polygon', (['points[:, :2]'], {'fc': 'color', 'ec': '"""k"""', 'zorder': '(2)', 'lw': '(0.1)'}), "(points[:, :2], fc=color, ec='k', zorder=2, lw=0.1)\n", (2217, 2268), False, 'from matplotlib.patches import Polygon\n'), ((1926, 1941), 'cartopy.crs.Geodetic', 'ccrs.Geodetic', ([], {}), '()\n', (1939, 1941), True, 'import cartopy.crs as ccrs\n')]
""" POVM effect representation classes for the `statevec_slow` evolution type. """ #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights # in this software. # 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 or in the LICENSE file in the root pyGSTi directory. #*************************************************************************************************** import numpy as _np from pygsti.baseobjs.statespace import StateSpace as _StateSpace class EffectRep(object): def __init__(self, state_space): self.state_space = _StateSpace.cast(state_space) @property def dim(self): return self.state_space.udim def probability(self, state): return abs(self.amplitude(state))**2 def amplitude(self, state): raise NotImplementedError() class EffectRepConjugatedState(EffectRep): def __init__(self, state_rep): self.state_rep = state_rep super(EffectRepConjugatedState, self).__init__(state_rep.state_space) def __str__(self): return str(self.state_rep.data) def to_dense(self, on_space): return self.state_rep.to_dense(on_space) def amplitude(self, state): # can assume state is a StateRep return _np.vdot(self.state_rep.data, state.data) class EffectRepComputational(EffectRep): def __init__(self, zvals, basis, state_space): state_space = _StateSpace.cast(state_space) assert(state_space.num_qudits == len(zvals)) assert(len(zvals) <= 64), "Cannot create a Computational basis rep with >64 qubits!" # Current storage of computational basis states converts zvals -> 64-bit integer # Different than DM counterpart # as each factor only has *1* nonzero element so final state has only a # *single* nonzero element! We just have to figure out where that # single element lies (compute it's index) based on the given zvals. # Assume, like tensorprod, that factor ordering == kron ordering # so nonzer_index = kron( factor[0], factor[1], ... factor[N-1] ). base = 2**(len(zvals) - 1) self.nonzero_index = 0 self.zvals = zvals self.basis = basis for k, v in enumerate(zvals): assert(v in (0, 1)), "zvals must contain only 0s and 1s" self.nonzero_index += base * v base //= 2 # or right shift? super(EffectRepComputational, self).__init__(state_space) def to_dense(self, on_space, outvec, trust_outvec_sparsity=False): # when trust_outvec_sparsity is True, assume we only need to fill in the # non-zero elements of outvec (i.e. that outvec is already zero wherever # this vector is zero). if on_space not in ('minimal', 'Hilbert'): raise ValueError('statevec evotype cannot (yet) generate dense Hilbert-Schmidt effect vectors') if not trust_outvec_sparsity: outvec[:] = 0 # reset everything to zero outvec[self.nonzero_index] = 1.0 return outvec def amplitude(self, state): # allow scratch to be passed in? scratch = _np.empty(self.dim, complex) Edense = self.to_dense('Hilbert', scratch) return _np.vdot(Edense, state.data) class EffectRepTensorProduct(EffectRep): def __init__(self, povm_factors, effect_labels, state_space): #Arrays for speeding up kron product in effect reps max_factor_dim = max(fct.dim for fct in povm_factors) kron_array = _np.ascontiguousarray( _np.empty((len(povm_factors), max_factor_dim), complex)) factordims = _np.ascontiguousarray( _np.array([fct.state_space.udim for fct in povm_factors], _np.int64)) #dim = _np.product(factordims) self.povm_factors = povm_factors self.effect_labels = effect_labels self.kron_array = kron_array self.factor_dims = factordims self.nfactors = len(self.povm_factors) self.max_factor_dim = max_factor_dim # Unused state_space = _StateSpace.cast(state_space) assert(_np.product(factordims) == state_space.udim) super(EffectRepTensorProduct, self).__init__(state_space) self.factor_effects_have_changed() def _fill_fast_kron(self): """ Fills in self._fast_kron_array based on current self.factors """ for i, (factor_dim, Elbl) in enumerate(zip(self._fast_kron_factordims, self.effectLbls)): self.kron_array[i][0:factor_dim] = self.povm_factors[i][Elbl].to_dense('Hilbert') def factor_effects_have_changed(self): self._fill_fast_kron() # updates effect reps def to_dense(self, on_space, scratch=None): #OLD & SLOW: #if len(self.factors) == 0: return _np.empty(0, complex) #factorPOVMs = self.factors #ret = factorPOVMs[0][self.effectLbls[0]].to_dense() #for i in range(1, len(factorPOVMs)): # ret = _np.kron(ret, factorPOVMs[i][self.effectLbls[i]].to_dense()) #return ret if scratch is None: scratch = _np.empty(self.udim, complex) outvec = scratch N = self.udim #Put last factor at end of outvec k = self.nfactors - 1 # last factor off = N - self.factor_dims[k] # offset into outvec for i in range(self.factor_dims[k]): outvec[off + i] = self.kron_array[k, i] sz = self.factor_dims[k] #Repeatedly scale&copy last "sz" elements of outputvec forward # (as many times as there are elements in the current factor array) # - but multiply *in-place* the last "sz" elements. for k in range(self.nfactors - 2, -1, -1): # for all but the last factor off = N - sz * self.factor_dims[k] endoff = N - sz #For all but the final element of self.kron_array[k,:], # mult&copy final sz elements of outvec into position for j in range(self.factor_dims[k] - 1): mult = self.kron_array[k, j] for i in range(sz): outvec[off + i] = mult * outvec[endoff + i] off += sz #Last element: in-place mult #assert(off == endoff) mult = self.kron_array[k, self.factor_dims[k] - 1] for i in range(sz): outvec[endoff + i] *= mult sz *= self.factor_dims[k] return outvec def amplitude(self, state): # allow scratch to be passed in? scratch = _np.empty(self.dim, complex) Edense = self.to_dense('Hilbert', scratch) return _np.vdot(Edense, state.data) class EffectRepComposed(EffectRep): def __init__(self, op_rep, effect_rep, op_id, state_space): self.op_rep = op_rep self.effect_rep = effect_rep self.op_id = op_id self.state_space = _StateSpace.cast(state_space) assert(self.state_space.is_compatible_with(effect_rep.state_space)) super(EffectRepComposed, self).__init__(effect_rep.state_space) #def __reduce__(self): # return (EffectRepComposed, (self.op_rep, self.effect_rep, self.op_id, self.state_space)) def probability(self, state): state = self.op_rep.acton(state) # *not* acton_adjoint return self.effect_rep.probability(state) def amplitude(self, state): # allow scratch to be passed in? state = self.op_rep.acton(state) # *not* acton_adjoint return self.effect_rep.amplitude(state)
[ "numpy.product", "pygsti.baseobjs.statespace.StateSpace.cast", "numpy.vdot", "numpy.array", "numpy.empty" ]
[((944, 973), 'pygsti.baseobjs.statespace.StateSpace.cast', '_StateSpace.cast', (['state_space'], {}), '(state_space)\n', (960, 973), True, 'from pygsti.baseobjs.statespace import StateSpace as _StateSpace\n'), ((1624, 1665), 'numpy.vdot', '_np.vdot', (['self.state_rep.data', 'state.data'], {}), '(self.state_rep.data, state.data)\n', (1632, 1665), True, 'import numpy as _np\n'), ((1782, 1811), 'pygsti.baseobjs.statespace.StateSpace.cast', '_StateSpace.cast', (['state_space'], {}), '(state_space)\n', (1798, 1811), True, 'from pygsti.baseobjs.statespace import StateSpace as _StateSpace\n'), ((3513, 3541), 'numpy.empty', '_np.empty', (['self.dim', 'complex'], {}), '(self.dim, complex)\n', (3522, 3541), True, 'import numpy as _np\n'), ((3608, 3636), 'numpy.vdot', '_np.vdot', (['Edense', 'state.data'], {}), '(Edense, state.data)\n', (3616, 3636), True, 'import numpy as _np\n'), ((4431, 4460), 'pygsti.baseobjs.statespace.StateSpace.cast', '_StateSpace.cast', (['state_space'], {}), '(state_space)\n', (4447, 4460), True, 'from pygsti.baseobjs.statespace import StateSpace as _StateSpace\n'), ((6898, 6926), 'numpy.empty', '_np.empty', (['self.dim', 'complex'], {}), '(self.dim, complex)\n', (6907, 6926), True, 'import numpy as _np\n'), ((6993, 7021), 'numpy.vdot', '_np.vdot', (['Edense', 'state.data'], {}), '(Edense, state.data)\n', (7001, 7021), True, 'import numpy as _np\n'), ((7245, 7274), 'pygsti.baseobjs.statespace.StateSpace.cast', '_StateSpace.cast', (['state_space'], {}), '(state_space)\n', (7261, 7274), True, 'from pygsti.baseobjs.statespace import StateSpace as _StateSpace\n'), ((4038, 4106), 'numpy.array', '_np.array', (['[fct.state_space.udim for fct in povm_factors]', '_np.int64'], {}), '([fct.state_space.udim for fct in povm_factors], _np.int64)\n', (4047, 4106), True, 'import numpy as _np\n'), ((4476, 4499), 'numpy.product', '_np.product', (['factordims'], {}), '(factordims)\n', (4487, 4499), True, 'import numpy as _np\n'), ((5458, 5487), 'numpy.empty', '_np.empty', (['self.udim', 'complex'], {}), '(self.udim, complex)\n', (5467, 5487), True, 'import numpy as _np\n')]
import logging import tensorflow as tf from data_all import get_dataset, get_train_pipeline from training_all import train from model_small import BIGBIGAN_G, BIGBIGAN_D_F, BIGBIGAN_D_H, BIGBIGAN_D_J, BIGBIGAN_E import numpy as np import os from PIL import Image def save_image(img, fname): img = img*255.0 img = Image.fromarray(img.astype(np.uint8)) img.save(fname) def visualize(train_data): out_dir = "images_pos_vis" if not os.path.exists(out_dir): os.makedirs(out_dir) for image, label in train_data: img, img_aug = tf.split(image, 2, axis=-1) images = img.numpy() images_aug = img_aug.numpy() print(images.shape, images_aug.shape, np.min(images), np.max(images), np.min(images_aug), np.max(images_aug)) for idx, (img, img_aug) in enumerate(zip(images, images_aug)): if idx == 10: break save_image(img, os.path.join(out_dir, "img_" + str(idx)+".png")) save_image(img_aug, os.path.join(out_dir, "img_aug_" + str(idx)+".png")) break def set_up_train(config): # Setup tensorflow tf.config.threading.set_inter_op_parallelism_threads(8) tf.config.threading.set_intra_op_parallelism_threads(8) physical_devices = tf.config.experimental.list_physical_devices('GPU') tf.config.experimental.set_memory_growth(physical_devices[0], True) # Load dataset logging.info('Getting dataset...') train_data, _ = get_dataset(config) # setup input pipeline logging.info('Generating input pipeline...') train_data = get_train_pipeline(train_data, config) # visualize(train_data) # get model logging.info('Prepare model for training...') weight_init = tf.initializers.orthogonal() if config.dataset == 'mnist': weight_init = tf.initializers.TruncatedNormal(mean=0.0, stddev=0.02) model_generator = BIGBIGAN_G(config, weight_init) model_discriminator_f = BIGBIGAN_D_F(config, weight_init) model_discriminator_h = BIGBIGAN_D_H(config, weight_init) model_discriminator_j = BIGBIGAN_D_J(config, weight_init) model_encoder = BIGBIGAN_E(config, weight_init) # train logging.info('Start training...') train(config=config, gen=model_generator, disc_f=model_discriminator_f, disc_h=model_discriminator_h, disc_j=model_discriminator_j, model_en=model_encoder, train_data=train_data) # Finished logging.info('Training finished ;)')
[ "model_small.BIGBIGAN_D_H", "tensorflow.split", "logging.info", "os.path.exists", "data_all.get_dataset", "tensorflow.initializers.TruncatedNormal", "tensorflow.initializers.orthogonal", "numpy.max", "tensorflow.config.threading.set_inter_op_parallelism_threads", "model_small.BIGBIGAN_E", "numpy...
[((1145, 1200), 'tensorflow.config.threading.set_inter_op_parallelism_threads', 'tf.config.threading.set_inter_op_parallelism_threads', (['(8)'], {}), '(8)\n', (1197, 1200), True, 'import tensorflow as tf\n'), ((1205, 1260), 'tensorflow.config.threading.set_intra_op_parallelism_threads', 'tf.config.threading.set_intra_op_parallelism_threads', (['(8)'], {}), '(8)\n', (1257, 1260), True, 'import tensorflow as tf\n'), ((1284, 1335), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (1328, 1335), True, 'import tensorflow as tf\n'), ((1340, 1407), 'tensorflow.config.experimental.set_memory_growth', 'tf.config.experimental.set_memory_growth', (['physical_devices[0]', '(True)'], {}), '(physical_devices[0], True)\n', (1380, 1407), True, 'import tensorflow as tf\n'), ((1433, 1467), 'logging.info', 'logging.info', (['"""Getting dataset..."""'], {}), "('Getting dataset...')\n", (1445, 1467), False, 'import logging\n'), ((1488, 1507), 'data_all.get_dataset', 'get_dataset', (['config'], {}), '(config)\n', (1499, 1507), False, 'from data_all import get_dataset, get_train_pipeline\n'), ((1540, 1584), 'logging.info', 'logging.info', (['"""Generating input pipeline..."""'], {}), "('Generating input pipeline...')\n", (1552, 1584), False, 'import logging\n'), ((1602, 1640), 'data_all.get_train_pipeline', 'get_train_pipeline', (['train_data', 'config'], {}), '(train_data, config)\n', (1620, 1640), False, 'from data_all import get_dataset, get_train_pipeline\n'), ((1699, 1744), 'logging.info', 'logging.info', (['"""Prepare model for training..."""'], {}), "('Prepare model for training...')\n", (1711, 1744), False, 'import logging\n'), ((1763, 1791), 'tensorflow.initializers.orthogonal', 'tf.initializers.orthogonal', ([], {}), '()\n', (1789, 1791), True, 'import tensorflow as tf\n'), ((1925, 1956), 'model_small.BIGBIGAN_G', 'BIGBIGAN_G', (['config', 'weight_init'], {}), '(config, weight_init)\n', (1935, 1956), False, 'from model_small import BIGBIGAN_G, BIGBIGAN_D_F, BIGBIGAN_D_H, BIGBIGAN_D_J, BIGBIGAN_E\n'), ((1985, 2018), 'model_small.BIGBIGAN_D_F', 'BIGBIGAN_D_F', (['config', 'weight_init'], {}), '(config, weight_init)\n', (1997, 2018), False, 'from model_small import BIGBIGAN_G, BIGBIGAN_D_F, BIGBIGAN_D_H, BIGBIGAN_D_J, BIGBIGAN_E\n'), ((2047, 2080), 'model_small.BIGBIGAN_D_H', 'BIGBIGAN_D_H', (['config', 'weight_init'], {}), '(config, weight_init)\n', (2059, 2080), False, 'from model_small import BIGBIGAN_G, BIGBIGAN_D_F, BIGBIGAN_D_H, BIGBIGAN_D_J, BIGBIGAN_E\n'), ((2109, 2142), 'model_small.BIGBIGAN_D_J', 'BIGBIGAN_D_J', (['config', 'weight_init'], {}), '(config, weight_init)\n', (2121, 2142), False, 'from model_small import BIGBIGAN_G, BIGBIGAN_D_F, BIGBIGAN_D_H, BIGBIGAN_D_J, BIGBIGAN_E\n'), ((2163, 2194), 'model_small.BIGBIGAN_E', 'BIGBIGAN_E', (['config', 'weight_init'], {}), '(config, weight_init)\n', (2173, 2194), False, 'from model_small import BIGBIGAN_G, BIGBIGAN_D_F, BIGBIGAN_D_H, BIGBIGAN_D_J, BIGBIGAN_E\n'), ((2212, 2245), 'logging.info', 'logging.info', (['"""Start training..."""'], {}), "('Start training...')\n", (2224, 2245), False, 'import logging\n'), ((2251, 2438), 'training_all.train', 'train', ([], {'config': 'config', 'gen': 'model_generator', 'disc_f': 'model_discriminator_f', 'disc_h': 'model_discriminator_h', 'disc_j': 'model_discriminator_j', 'model_en': 'model_encoder', 'train_data': 'train_data'}), '(config=config, gen=model_generator, disc_f=model_discriminator_f,\n disc_h=model_discriminator_h, disc_j=model_discriminator_j, model_en=\n model_encoder, train_data=train_data)\n', (2256, 2438), False, 'from training_all import train\n'), ((2509, 2545), 'logging.info', 'logging.info', (['"""Training finished ;)"""'], {}), "('Training finished ;)')\n", (2521, 2545), False, 'import logging\n'), ((454, 477), 'os.path.exists', 'os.path.exists', (['out_dir'], {}), '(out_dir)\n', (468, 477), False, 'import os\n'), ((487, 507), 'os.makedirs', 'os.makedirs', (['out_dir'], {}), '(out_dir)\n', (498, 507), False, 'import os\n'), ((576, 603), 'tensorflow.split', 'tf.split', (['image', '(2)'], {'axis': '(-1)'}), '(image, 2, axis=-1)\n', (584, 603), True, 'import tensorflow as tf\n'), ((1848, 1902), 'tensorflow.initializers.TruncatedNormal', 'tf.initializers.TruncatedNormal', ([], {'mean': '(0.0)', 'stddev': '(0.02)'}), '(mean=0.0, stddev=0.02)\n', (1879, 1902), True, 'import tensorflow as tf\n'), ((716, 730), 'numpy.min', 'np.min', (['images'], {}), '(images)\n', (722, 730), True, 'import numpy as np\n'), ((732, 746), 'numpy.max', 'np.max', (['images'], {}), '(images)\n', (738, 746), True, 'import numpy as np\n'), ((748, 766), 'numpy.min', 'np.min', (['images_aug'], {}), '(images_aug)\n', (754, 766), True, 'import numpy as np\n'), ((768, 786), 'numpy.max', 'np.max', (['images_aug'], {}), '(images_aug)\n', (774, 786), True, 'import numpy as np\n')]
import os import numpy as np from PIL import Image from tqdm import tqdm # 0.83102435 0.83786940 0.73139444 # 0.27632148 0.20124162 0.29032342 def calc(*paths): imgs = [] for path in paths: for name in tqdm(os.listdir(path)): img = Image.open(os.path.join(path, name)).convert('RGB') img = np.array(img, dtype='float32') # H, W, C img = img / 255.0 img = img.reshape(-1, 3) imgs.append(img) imgs = np.concatenate(imgs, axis=0) # print(imgs.shape) # print(imgs.mean(axis=0, dtype=np.float64)) print(imgs.std(axis=0, dtype=np.float64)) def main(): calc('datasets/tianchi_xray/restricted', 'datasets/tianchi_xray/normal') if __name__ == '__main__': main()
[ "numpy.array", "os.listdir", "os.path.join", "numpy.concatenate" ]
[((481, 509), 'numpy.concatenate', 'np.concatenate', (['imgs'], {'axis': '(0)'}), '(imgs, axis=0)\n', (495, 509), True, 'import numpy as np\n'), ((225, 241), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (235, 241), False, 'import os\n'), ((332, 362), 'numpy.array', 'np.array', (['img'], {'dtype': '"""float32"""'}), "(img, dtype='float32')\n", (340, 362), True, 'import numpy as np\n'), ((273, 297), 'os.path.join', 'os.path.join', (['path', 'name'], {}), '(path, name)\n', (285, 297), False, 'import os\n')]
#!/usr/bin/env python # _*_coding:utf-8_*_ import sys import pandas as pd import numpy as np import rpy2 import rpy2.robjects from rpy2.robjects import numpy2ri numpy2ri.activate() r = rpy2.robjects.r r.library('Peptides') GROUPS_SA = ['ALFCGIVW', 'RKQEND', 'MSPTHY'] #solventaccess GROUPS_HB = ['ILVWAMGT', 'FYSQCN', 'PHKEDR'] # HEIJNE&BLOMBERG1979 def fasta_iter(fname): header = None chunks = [] with open(fname) as f: for line in f: if line[0] == '>': if header is not None: yield header,''.join(chunks) header = line[1:].strip().split()[0] chunks = [] else: chunks.append(line.strip()) if header is not None: yield header, ''.join(chunks) def ctdd(sequence, groups): code = [] for group in groups: for i, aa in enumerate(sequence): if aa in group: code.append((i + 1)/len(sequence) * 100) break else: code.append(0) return code def main(args): if len(args) < 3: sys.stderr.write("This is an internal FACS script and is not meant to be used independently") sys.exit(1) ifile = args[1] ofile = args[2] groups = [set(g) for g in (GROUPS_SA+GROUPS_HB)] seqs = [] headers = [] encodings = [] for h,seq in fasta_iter(ifile): seqs.append(seq) headers.append(h) encodings.append(ctdd(seq, groups)) # We can do this inside the loop so that we are not forced to pre-load all # the sequences into memory. However, it becomes much slower rpy2.robjects.globalenv['seq'] = seqs aaComp = r('aaComp(seq)') rfeatures = r(''' ch <- charge(seq=seq, pH=7, pKscale="EMBOSS") pI <- pI(seq=seq, pKscale="EMBOSS") aIndex <- aIndex(seq=seq) instaIndex <- instaIndex(seq=seq) boman <- boman(seq=seq) hydrophobicity <- hydrophobicity(seq=seq, scale="Eisenberg") hmoment <- hmoment(seq=seq, angle=100, window=11) cbind(ch, pI, aIndex, instaIndex, boman, hydrophobicity, hmoment) ''') aaComp = np.array([np.array(v) for v in aaComp]) aaComp = aaComp[:,:,1] features = np.hstack([aaComp, rfeatures, encodings]) # The column names must match those in the saved model features = pd.DataFrame(features, index=headers, columns=[ "tinyAA", "smallAA", "aliphaticAA", "aromaticAA", "nonpolarAA", "polarAA", "chargedAA", "basicAA", "acidicAA", "charge", "pI", "aindex", "instaindex", "boman", "hydrophobicity", "hmoment", "SA.G1.residue0", "SA.G2.residue0", "SA.G3.residue0", "hb.Group.1.residue0", "hb.Group.2.residue0", "hb.Group.3.residue0", ]) features.insert(0, 'group', 'Unk') features.insert(0, 'sequence', seqs) features.to_csv(ofile, sep='\t', index_label='access') if __name__ == '__main__': main(sys.argv)
[ "numpy.hstack", "sys.stderr.write", "numpy.array", "sys.exit", "pandas.DataFrame", "rpy2.robjects.numpy2ri.activate" ]
[((162, 181), 'rpy2.robjects.numpy2ri.activate', 'numpy2ri.activate', ([], {}), '()\n', (179, 181), False, 'from rpy2.robjects import numpy2ri\n'), ((2226, 2267), 'numpy.hstack', 'np.hstack', (['[aaComp, rfeatures, encodings]'], {}), '([aaComp, rfeatures, encodings])\n', (2235, 2267), True, 'import numpy as np\n'), ((2342, 2721), 'pandas.DataFrame', 'pd.DataFrame', (['features'], {'index': 'headers', 'columns': "['tinyAA', 'smallAA', 'aliphaticAA', 'aromaticAA', 'nonpolarAA', 'polarAA',\n 'chargedAA', 'basicAA', 'acidicAA', 'charge', 'pI', 'aindex',\n 'instaindex', 'boman', 'hydrophobicity', 'hmoment', 'SA.G1.residue0',\n 'SA.G2.residue0', 'SA.G3.residue0', 'hb.Group.1.residue0',\n 'hb.Group.2.residue0', 'hb.Group.3.residue0']"}), "(features, index=headers, columns=['tinyAA', 'smallAA',\n 'aliphaticAA', 'aromaticAA', 'nonpolarAA', 'polarAA', 'chargedAA',\n 'basicAA', 'acidicAA', 'charge', 'pI', 'aindex', 'instaindex', 'boman',\n 'hydrophobicity', 'hmoment', 'SA.G1.residue0', 'SA.G2.residue0',\n 'SA.G3.residue0', 'hb.Group.1.residue0', 'hb.Group.2.residue0',\n 'hb.Group.3.residue0'])\n", (2354, 2721), True, 'import pandas as pd\n'), ((1117, 1220), 'sys.stderr.write', 'sys.stderr.write', (['"""This is an internal FACS script and is not meant to be used independently"""'], {}), "(\n 'This is an internal FACS script and is not meant to be used independently'\n )\n", (1133, 1220), False, 'import sys\n'), ((1219, 1230), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1227, 1230), False, 'import sys\n'), ((2153, 2164), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (2161, 2164), True, 'import numpy as np\n')]
# PyVision License # # Copyright (c) 2006-2008 <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither name of copyright holders nor the names of its 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 THE REGENTS 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. ''' This is a simplified correlation filter implementation used to locate eyes using ASEF correlation filters. This file contains two classes: OpenCVFilterEyeLocator and FilterEyeLocator. The first is the bare minimum required to locate eye and only requires opencv. The second need is a wrapper that includes a nice pyvision compatible interface. This class is not integrated with PyVision. PyVision supplies an interface to this class which cleans up the interface and provides a bridge to many of the PyVision data structures. ''' import cv import math import struct import array import os.path import pyvision as pv import numpy as np import sys __author__ = "<NAME> - Colorado State Univeristy" __version__ = "$Revision: 729 $" if pv.WARN_COMMERCIAL_USE: warning = ''' WARNING: A patent protection is anticipated for ASEF and similar filters by the Colorado State University Research Foundation (CSURF). This module, "FilterEyeLocator.py", my not be suitable for commercial use. Commercial and government users should contact CSURF for additional details: http://www.csurf.org/tto/pdfs/ncs_forms/09-017_csurf_ncs.pdf ''' sys.stderr.write(warning) #TODO: Unknown error - This may be related version 1.0.0 of opencv #Traceback (most recent call last): # File "/home/dbolme/ASEFFilters/python/csu/tools/face_scan.py", line 117, in ? # results = processFaces(im,face_detect,locate_eyes) # File "/home/dbolme/ASEFFilters/python/csu/tools/face_scan.py", line 57, in processFaces # eye1, eye2, corr1, corr2 = locate_eyes.locateEyes(cv_im) # File "/home/dbolme/ASEFFilters/python/csu/face/FilterEyeLocator.py", line 185, in locateEyes # leye = cv.cvMinMaxLoc(self.left_roi)[3] #IndexError: list index out of range #TODO: Add a quality estimate def saveFilterEyeLocator(filename, el, comment="",copyright=""): ''' File Format - Line 1: CFEL - Line 2: <comment> - Line 3: <copyright> - Line 4: ROWS COLS - Line 5: LEFT_RECT - Line 6: RIGHT_RECT - Line 7: BYTE_ORDER(0x41424344 or 'ABCD') - Line 8: <binary data: two single precision floating point arrays of 4*WIDTH*HEIGHT bytes) ''' r,c = el.left_filter.rows,el.left_filter.cols f = open(filename,'wb') f.write("CFEL\n") f.write(comment.strip()+"\n") f.write(copyright.strip()+"\n") f.write("%d %d\n"%(r,c)) f.write("%d %d %d %d\n"%(el.left_rect.x,el.left_rect.y,el.left_rect.width,el.left_rect.height)) f.write("%d %d %d %d\n"%(el.right_rect.x,el.right_rect.y,el.right_rect.width,el.right_rect.height)) f.write("%s\n"%struct.pack("i",0x41424344)) assert len(el.left_filter.imageData) == 4*r*c f.write(el.left_filter.imageData) assert len(el.right_filter.imageData) == 4*r*c f.write(el.right_filter.imageData) def loadFilterEyeLocator(filename,ilog=None): ''' Loads the eye locator from a file.' ''' # open the file f = open(filename,'rb') # Check the first line line = f.readline().strip() assert line == "CFEL" # read past the comment and copyright. f.readline() f.readline() # get the width and the height r,c = f.readline().split() r,c = int(r),int(c) # read in the left bounding rectangle x,y,w,h = f.readline().split() left_rect = (int(x),int(y),int(w),int(h)) # read in the right bounding rectangle x,y,w,h = f.readline().split() right_rect = (int(x),int(y),int(w),int(h)) # read the magic number magic_number = f.readline().strip() assert len(magic_number) == 4 magic_number = struct.unpack('i',magic_number)[0] # Read in the filter data lf = array.array('f') rf = array.array('f') lf.fromfile(f,r*c) rf.fromfile(f,r*c) # Test the magic number and byteswap if necessary. if magic_number == 0x41424344: pass elif magic_number == 0x44434241: lf.byteswap() rf.byteswap() else: raise ValueError("Bad Magic Number: Unknown byte ordering in file") # Create the left and right filters left_filter = cv.CreateMat(r,c,cv.CV_32F) right_filter = cv.CreateMat(r,c,cv.CV_32F) # Copy data into the left and right filters cv.SetData(left_filter, lf.tostring()) cv.SetData(right_filter, rf.tostring()) tmp = pv.OpenCVToNumpy(left_filter) t1 = tmp.mean() t2 = tmp.std() cv.Scale(left_filter,left_filter,1.0/t2,-t1*1.0/t2) tmp = pv.OpenCVToNumpy(right_filter) t1 = tmp.mean() t2 = tmp.std() cv.Scale(right_filter,right_filter,1.0/t2,-t1*1.0/t2) #tmp = pv.OpenCVToNumpy(left_filter) #print tmp.mean(),tmp.std() if ilog != None: #lf = cv.cvCreateMat(r,c,cv.CV_8U) #rf = cv.cvCreateMat(r,c,cv.CV_8U) lf = pv.OpenCVToNumpy(left_filter) rf = pv.OpenCVToNumpy(right_filter) lf = np.fft.fftshift(lf).transpose() rf = np.fft.fftshift(rf).transpose() ilog.log(pv.Image(lf),label="LeftEyeFilter") ilog.log(pv.Image(rf),label="RightEyeFilter") # Return the eye locator return OpenCVFilterEyeLocator(left_filter,right_filter,left_rect,right_rect) class OpenCVFilterEyeLocator: ''' This class is used for someone only interested in locating the eyes in an image using correlation filters. This class does not include any support for training correlation filters. For training see ASEF. This class is written only using OpenCV and is much faster than the ASEF class. For details see the paper: <NAME>, <NAME>, and <NAME>. Average of Synthetic Exact Filters. Submitted to Computer Vision and Pattern Recoginition. 2009. The class uses two ASEF filters to find the eyes. The eyes are located by first computing the correlation of the face tile with each filter. The max value from the correlation plain is returned as the eye coordinate. Also returned is the full correlation output from the image. The images are normalized by computing log transforming the pixel values To improve performance, this class is not thread safe. The class reuses data arrays allocated for each call to use this class for multiple threads you should create an instance for each threads. Also note that each method call may overwrite arrays returned by this application. So if you need the returned data to persist be sure to create a copy. - Left and right eyes are in relation to the location in the image. ''' def __init__(self,left_filter,right_filter, left_rect, right_rect): ''' @param left_filter: is in the Fourier domain where the left eye corresponds to the real output and the right eye corresponds to the imaginary output ''' # Check the input to this function r,c = left_filter.rows,left_filter.cols assert left_filter.width == right_filter.width assert left_filter.height == right_filter.height assert left_filter.channels == 1 assert right_filter.channels == 1 # Create the arrays needed for the computation self.left_filter = cv.CreateMat(r,c,cv.CV_32F) self.right_filter = cv.CreateMat(r,c,cv.CV_32F) self.left_filter_dft = cv.CreateMat(r,c,cv.CV_32F) self.right_filter_dft = cv.CreateMat(r,c,cv.CV_32F) self.image = cv.CreateMat(r,c,cv.CV_32F) self.left_corr = cv.CreateMat(r,c,cv.CV_32F) self.right_corr = cv.CreateMat(r,c,cv.CV_32F) # Populate the spatial filters cv.ConvertScale(left_filter, self.left_filter) cv.ConvertScale(right_filter, self.right_filter) # Compute the filters in the Fourier domain cv.DFT(self.left_filter, self.left_filter_dft, cv.CV_DXT_FORWARD) cv.DFT(self.right_filter, self.right_filter_dft, cv.CV_DXT_FORWARD) # Set up correlation region of interest self.left_rect = left_rect self.right_rect = right_rect self.left_roi = cv.GetSubRect(self.left_corr,self.left_rect) self.right_roi = cv.GetSubRect(self.right_corr,self.right_rect) # Create the look up table for the log transform self.lut = cv.CreateMat(256,1,cv.CV_32F) for i in range(256): self.lut[i,0] = math.log(i+1) def locateEyes(self,image_tile): ''' @param image_tile: is an 32-bit gray scale opencv image tile of a face that is the same size as the filter @type image_tile: 8-bit gray scale opencv image @returns: a tuple consisting of the location of the left and right eyes (opencv 2D points), and the complex correlation plain output @raises AssertionError: is raised if the image is not 8-bit or not the same size as the filter ''' self.correlate(image_tile) leye = cv.MinMaxLoc(self.left_roi)[3] leye = (self.left_rect[0]+leye[0],self.left_rect[1]+leye[1]) reye = cv.MinMaxLoc(self.right_roi)[3] reye = (self.right_rect[0]+reye[0],self.right_rect[1]+reye[1]) return leye,reye,self.left_corr,self.right_corr def _preprocess(self,image_tile): ''' preprocess an image tile. ''' # TODO: This function has problems in opencv 2.2. There appears to be a bug. image_tile = pv.OpenCVToNumpy(image_tile) self.image = pv.NumpyToOpenCV(np.log(image_tile + 1.0).astype(np.float32)) return self.image def correlate(self,image_tile): ''' Correlate the image with the left and right filters. ''' self._preprocess(image_tile) cv.DFT(self.image, self.image, cv.CV_DXT_FORWARD) cv.MulSpectrums( self.image, self.left_filter_dft, self.left_corr, cv.CV_DXT_MUL_CONJ ) cv.MulSpectrums( self.image, self.right_filter_dft, self.right_corr, cv.CV_DXT_MUL_CONJ ) cv.DFT(self.left_corr,self.left_corr,cv.CV_DXT_INV_SCALE) cv.DFT(self.right_corr,self.right_corr,cv.CV_DXT_INV_SCALE) return self.left_corr,self.right_corr class FilterEyeLocator: ''' This class provides a PyVision interface to the ASEF eye locator. ''' def __init__(self,filename=None,ilog=None): ''' Load the eye detector from the file. ''' if filename == None: filename = os.path.join(pv.__path__[0],"config","EyeLocatorASEF128x128.fel") self.fel = loadFilterEyeLocator(filename,ilog=ilog) self.bwtile = cv.CreateMat(128,128,cv.CV_8U) def __call__(self,im,face_rects,ilog=None): return self.locateEyes(im,face_rects,ilog=ilog) def locateEyes(self,im,face_rects,ilog=None): ''' Finds the eyes in the image. @param im: full sized image @param face_rects: list of rectangle which are the output from the cascade face detector. ''' cvim = im.asOpenCVBW() faces = [] for rect in face_rects: faceim = cv.GetSubRect(cvim, rect.asOpenCV()) cv.Resize(faceim,self.bwtile) affine = pv.AffineFromRect(rect,(128,128)) #cv.cvCvtColor( self.cvtile, self.bwtile, cv.CV_BGR2GRAY ) leye,reye,lcp,rcp = self.fel.locateEyes(self.bwtile) le = pv.Point(leye) re = pv.Point(reye) leye = affine.invertPoint(le) reye = affine.invertPoint(re) faces.append([rect,leye,reye]) if ilog != None: ilog.log(pv.Image(self.bwtile),label="FaceDetection") lcp = pv.OpenCVToNumpy(lcp).transpose() lcp = lcp*(lcp > 0.0) rcp = pv.OpenCVToNumpy(rcp).transpose() rcp = rcp*(rcp > 0.0) ilog.log(pv.Image(lcp),label="Left_Corr") ilog.log(pv.Image(rcp),label="Right_Corr") tmp = pv.Image(self.bwtile) tmp.annotatePoint(le) tmp.annotatePoint(re) ilog.log(tmp,"EyeLocations") return faces ############################################################################# # Unit Tests ############################################################################# import unittest import pyvision.face.CascadeDetector as cd from pyvision.analysis.FaceAnalysis.FaceDatabase import ScrapShotsDatabase from pyvision.analysis.FaceAnalysis.EyeDetectionTest import EyeDetectionTest class _TestFilterEyeLocator(unittest.TestCase): def test_ASEFEyeLocalization(self): ''' This trains the FaceFinder on the scraps database. ''' # Load a face database ssdb = ScrapShotsDatabase() # Create a face detector face_detector = cd.CascadeDetector() # Create an eye locator eye_locator = FilterEyeLocator() # Create an eye detection test edt = EyeDetectionTest(name='asef_scraps') #print "Testing..." for face_id in ssdb.keys(): face = ssdb[face_id] im = face.image # Detect the faces faces = face_detector.detect(im) # Detect the eyes pred_eyes = eye_locator(im,faces) truth_eyes = [[face.left_eye,face.right_eye]] pred_eyes = [ [leye,reye] for rect,leye,reye in pred_eyes] # Add to eye detection test edt.addSample(truth_eyes, pred_eyes, im=im, annotate=False) edt.createSummary() self.assertAlmostEqual( edt.face_rate , 0.97109826589595372, places = 3 ) # Updated numbers for OpenCV 2.0 self.assertAlmostEqual( edt.both25_rate , 0.82658959537572252, places = 3 ) self.assertAlmostEqual( edt.both10_rate , 0.47976878612716761, places = 3 ) self.assertAlmostEqual( edt.both05_rate , 0.30635838150289019, places = 3 )
[ "numpy.log", "cv.Scale", "pyvision.OpenCVToNumpy", "math.log", "cv.GetSubRect", "pyvision.face.CascadeDetector.CascadeDetector", "pyvision.Point", "cv.MulSpectrums", "pyvision.analysis.FaceAnalysis.FaceDatabase.ScrapShotsDatabase", "cv.DFT", "cv.Resize", "array.array", "struct.pack", "cv.C...
[((2812, 2837), 'sys.stderr.write', 'sys.stderr.write', (['warning'], {}), '(warning)\n', (2828, 2837), False, 'import sys\n'), ((5396, 5412), 'array.array', 'array.array', (['"""f"""'], {}), "('f')\n", (5407, 5412), False, 'import array\n'), ((5422, 5438), 'array.array', 'array.array', (['"""f"""'], {}), "('f')\n", (5433, 5438), False, 'import array\n'), ((5829, 5858), 'cv.CreateMat', 'cv.CreateMat', (['r', 'c', 'cv.CV_32F'], {}), '(r, c, cv.CV_32F)\n', (5841, 5858), False, 'import cv\n'), ((5876, 5905), 'cv.CreateMat', 'cv.CreateMat', (['r', 'c', 'cv.CV_32F'], {}), '(r, c, cv.CV_32F)\n', (5888, 5905), False, 'import cv\n'), ((6059, 6088), 'pyvision.OpenCVToNumpy', 'pv.OpenCVToNumpy', (['left_filter'], {}), '(left_filter)\n', (6075, 6088), True, 'import pyvision as pv\n'), ((6132, 6192), 'cv.Scale', 'cv.Scale', (['left_filter', 'left_filter', '(1.0 / t2)', '(-t1 * 1.0 / t2)'], {}), '(left_filter, left_filter, 1.0 / t2, -t1 * 1.0 / t2)\n', (6140, 6192), False, 'import cv\n'), ((6195, 6225), 'pyvision.OpenCVToNumpy', 'pv.OpenCVToNumpy', (['right_filter'], {}), '(right_filter)\n', (6211, 6225), True, 'import pyvision as pv\n'), ((6269, 6331), 'cv.Scale', 'cv.Scale', (['right_filter', 'right_filter', '(1.0 / t2)', '(-t1 * 1.0 / t2)'], {}), '(right_filter, right_filter, 1.0 / t2, -t1 * 1.0 / t2)\n', (6277, 6331), False, 'import cv\n'), ((5317, 5349), 'struct.unpack', 'struct.unpack', (['"""i"""', 'magic_number'], {}), "('i', magic_number)\n", (5330, 5349), False, 'import struct\n'), ((6531, 6560), 'pyvision.OpenCVToNumpy', 'pv.OpenCVToNumpy', (['left_filter'], {}), '(left_filter)\n', (6547, 6560), True, 'import pyvision as pv\n'), ((6574, 6604), 'pyvision.OpenCVToNumpy', 'pv.OpenCVToNumpy', (['right_filter'], {}), '(right_filter)\n', (6590, 6604), True, 'import pyvision as pv\n'), ((9017, 9046), 'cv.CreateMat', 'cv.CreateMat', (['r', 'c', 'cv.CV_32F'], {}), '(r, c, cv.CV_32F)\n', (9029, 9046), False, 'import cv\n'), ((9077, 9106), 'cv.CreateMat', 'cv.CreateMat', (['r', 'c', 'cv.CV_32F'], {}), '(r, c, cv.CV_32F)\n', (9089, 9106), False, 'import cv\n'), ((9137, 9166), 'cv.CreateMat', 'cv.CreateMat', (['r', 'c', 'cv.CV_32F'], {}), '(r, c, cv.CV_32F)\n', (9149, 9166), False, 'import cv\n'), ((9197, 9226), 'cv.CreateMat', 'cv.CreateMat', (['r', 'c', 'cv.CV_32F'], {}), '(r, c, cv.CV_32F)\n', (9209, 9226), False, 'import cv\n'), ((9257, 9286), 'cv.CreateMat', 'cv.CreateMat', (['r', 'c', 'cv.CV_32F'], {}), '(r, c, cv.CV_32F)\n', (9269, 9286), False, 'import cv\n'), ((9317, 9346), 'cv.CreateMat', 'cv.CreateMat', (['r', 'c', 'cv.CV_32F'], {}), '(r, c, cv.CV_32F)\n', (9329, 9346), False, 'import cv\n'), ((9377, 9406), 'cv.CreateMat', 'cv.CreateMat', (['r', 'c', 'cv.CV_32F'], {}), '(r, c, cv.CV_32F)\n', (9389, 9406), False, 'import cv\n'), ((9461, 9507), 'cv.ConvertScale', 'cv.ConvertScale', (['left_filter', 'self.left_filter'], {}), '(left_filter, self.left_filter)\n', (9476, 9507), False, 'import cv\n'), ((9517, 9565), 'cv.ConvertScale', 'cv.ConvertScale', (['right_filter', 'self.right_filter'], {}), '(right_filter, self.right_filter)\n', (9532, 9565), False, 'import cv\n'), ((9627, 9692), 'cv.DFT', 'cv.DFT', (['self.left_filter', 'self.left_filter_dft', 'cv.CV_DXT_FORWARD'], {}), '(self.left_filter, self.left_filter_dft, cv.CV_DXT_FORWARD)\n', (9633, 9692), False, 'import cv\n'), ((9703, 9770), 'cv.DFT', 'cv.DFT', (['self.right_filter', 'self.right_filter_dft', 'cv.CV_DXT_FORWARD'], {}), '(self.right_filter, self.right_filter_dft, cv.CV_DXT_FORWARD)\n', (9709, 9770), False, 'import cv\n'), ((9925, 9970), 'cv.GetSubRect', 'cv.GetSubRect', (['self.left_corr', 'self.left_rect'], {}), '(self.left_corr, self.left_rect)\n', (9938, 9970), False, 'import cv\n'), ((9995, 10042), 'cv.GetSubRect', 'cv.GetSubRect', (['self.right_corr', 'self.right_rect'], {}), '(self.right_corr, self.right_rect)\n', (10008, 10042), False, 'import cv\n'), ((10127, 10158), 'cv.CreateMat', 'cv.CreateMat', (['(256)', '(1)', 'cv.CV_32F'], {}), '(256, 1, cv.CV_32F)\n', (10139, 10158), False, 'import cv\n'), ((11347, 11375), 'pyvision.OpenCVToNumpy', 'pv.OpenCVToNumpy', (['image_tile'], {}), '(image_tile)\n', (11363, 11375), True, 'import pyvision as pv\n'), ((11687, 11736), 'cv.DFT', 'cv.DFT', (['self.image', 'self.image', 'cv.CV_DXT_FORWARD'], {}), '(self.image, self.image, cv.CV_DXT_FORWARD)\n', (11693, 11736), False, 'import cv\n'), ((11747, 11837), 'cv.MulSpectrums', 'cv.MulSpectrums', (['self.image', 'self.left_filter_dft', 'self.left_corr', 'cv.CV_DXT_MUL_CONJ'], {}), '(self.image, self.left_filter_dft, self.left_corr, cv.\n CV_DXT_MUL_CONJ)\n', (11762, 11837), False, 'import cv\n'), ((11843, 11935), 'cv.MulSpectrums', 'cv.MulSpectrums', (['self.image', 'self.right_filter_dft', 'self.right_corr', 'cv.CV_DXT_MUL_CONJ'], {}), '(self.image, self.right_filter_dft, self.right_corr, cv.\n CV_DXT_MUL_CONJ)\n', (11858, 11935), False, 'import cv\n'), ((11950, 12009), 'cv.DFT', 'cv.DFT', (['self.left_corr', 'self.left_corr', 'cv.CV_DXT_INV_SCALE'], {}), '(self.left_corr, self.left_corr, cv.CV_DXT_INV_SCALE)\n', (11956, 12009), False, 'import cv\n'), ((12016, 12077), 'cv.DFT', 'cv.DFT', (['self.right_corr', 'self.right_corr', 'cv.CV_DXT_INV_SCALE'], {}), '(self.right_corr, self.right_corr, cv.CV_DXT_INV_SCALE)\n', (12022, 12077), False, 'import cv\n'), ((12587, 12619), 'cv.CreateMat', 'cv.CreateMat', (['(128)', '(128)', 'cv.CV_8U'], {}), '(128, 128, cv.CV_8U)\n', (12599, 12619), False, 'import cv\n'), ((14894, 14914), 'pyvision.analysis.FaceAnalysis.FaceDatabase.ScrapShotsDatabase', 'ScrapShotsDatabase', ([], {}), '()\n', (14912, 14914), False, 'from pyvision.analysis.FaceAnalysis.FaceDatabase import ScrapShotsDatabase\n'), ((14990, 15010), 'pyvision.face.CascadeDetector.CascadeDetector', 'cd.CascadeDetector', ([], {}), '()\n', (15008, 15010), True, 'import pyvision.face.CascadeDetector as cd\n'), ((15147, 15183), 'pyvision.analysis.FaceAnalysis.EyeDetectionTest.EyeDetectionTest', 'EyeDetectionTest', ([], {'name': '"""asef_scraps"""'}), "(name='asef_scraps')\n", (15163, 15183), False, 'from pyvision.analysis.FaceAnalysis.EyeDetectionTest import EyeDetectionTest\n'), ((4284, 4312), 'struct.pack', 'struct.pack', (['"""i"""', '(1094861636)'], {}), "('i', 1094861636)\n", (4295, 4312), False, 'import struct\n'), ((6730, 6742), 'pyvision.Image', 'pv.Image', (['lf'], {}), '(lf)\n', (6738, 6742), True, 'import pyvision as pv\n'), ((6783, 6795), 'pyvision.Image', 'pv.Image', (['rf'], {}), '(rf)\n', (6791, 6795), True, 'import pyvision as pv\n'), ((10223, 10238), 'math.log', 'math.log', (['(i + 1)'], {}), '(i + 1)\n', (10231, 10238), False, 'import math\n'), ((10849, 10876), 'cv.MinMaxLoc', 'cv.MinMaxLoc', (['self.left_roi'], {}), '(self.left_roi)\n', (10861, 10876), False, 'import cv\n'), ((10965, 10993), 'cv.MinMaxLoc', 'cv.MinMaxLoc', (['self.right_roi'], {}), '(self.right_roi)\n', (10977, 10993), False, 'import cv\n'), ((13196, 13226), 'cv.Resize', 'cv.Resize', (['faceim', 'self.bwtile'], {}), '(faceim, self.bwtile)\n', (13205, 13226), False, 'import cv\n'), ((13260, 13295), 'pyvision.AffineFromRect', 'pv.AffineFromRect', (['rect', '(128, 128)'], {}), '(rect, (128, 128))\n', (13277, 13295), True, 'import pyvision as pv\n'), ((13461, 13475), 'pyvision.Point', 'pv.Point', (['leye'], {}), '(leye)\n', (13469, 13475), True, 'import pyvision as pv\n'), ((13493, 13507), 'pyvision.Point', 'pv.Point', (['reye'], {}), '(reye)\n', (13501, 13507), True, 'import pyvision as pv\n'), ((6627, 6646), 'numpy.fft.fftshift', 'np.fft.fftshift', (['lf'], {}), '(lf)\n', (6642, 6646), True, 'import numpy as np\n'), ((6672, 6691), 'numpy.fft.fftshift', 'np.fft.fftshift', (['rf'], {}), '(rf)\n', (6687, 6691), True, 'import numpy as np\n'), ((14100, 14121), 'pyvision.Image', 'pv.Image', (['self.bwtile'], {}), '(self.bwtile)\n', (14108, 14121), True, 'import pyvision as pv\n'), ((11414, 11438), 'numpy.log', 'np.log', (['(image_tile + 1.0)'], {}), '(image_tile + 1.0)\n', (11420, 11438), True, 'import numpy as np\n'), ((13728, 13749), 'pyvision.Image', 'pv.Image', (['self.bwtile'], {}), '(self.bwtile)\n', (13736, 13749), True, 'import pyvision as pv\n'), ((13986, 13999), 'pyvision.Image', 'pv.Image', (['lcp'], {}), '(lcp)\n', (13994, 13999), True, 'import pyvision as pv\n'), ((14044, 14057), 'pyvision.Image', 'pv.Image', (['rcp'], {}), '(rcp)\n', (14052, 14057), True, 'import pyvision as pv\n'), ((13795, 13816), 'pyvision.OpenCVToNumpy', 'pv.OpenCVToNumpy', (['lcp'], {}), '(lcp)\n', (13811, 13816), True, 'import pyvision as pv\n'), ((13889, 13910), 'pyvision.OpenCVToNumpy', 'pv.OpenCVToNumpy', (['rcp'], {}), '(rcp)\n', (13905, 13910), True, 'import pyvision as pv\n')]
# -*- coding: utf-8 -*- # # Developed by <NAME> <<EMAIL>> # # References: # - https://github.com/ultralytics/yolov5/blob/master/utils/datasets.py import os import cv2 import torch import numpy as np from torch.utils.data import Dataset, DataLoader from util.common import exr2normal, exr2depth, img2bgr, pkl2mesh, resize_img, load_mesh_paths, L_RGB, L_DEPTH, \ L_NORMAL, load_img_paths, plot_volumes def create_dataloader(img_path, mesh_path, batch_size=2, used_layers=None, img_size=224, map_size=32, augment=False, workers=8, pin_memory=True, shuffle=True): dataset = BDataset(img_path, mesh_path, used_layers=used_layers, img_size=img_size, map_size=map_size, augment=augment) batch_size = min(batch_size, len(dataset)) nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, workers]) # number of workers dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=nw, pin_memory=pin_memory, shuffle=shuffle) return dataset, dataloader class LoadImages: def __init__(self, path, img_size=244, stride=32, used_layers=None): self.img_size = img_size self.stride = stride if used_layers is None: used_layers = [L_RGB] self.used_layers = used_layers self.layer_files = load_img_paths(path, used_layers) self.img_files = self.layer_files[self.used_layers[0]] self.nf = len(self.img_files) def __iter__(self): self.count = 0 return self def __next__(self): if self.count == self.nf: raise StopIteration path = self.img_files[self.count] layers0, _, _ = load_layers(self.layer_files, self.count, self.used_layers) self.count += 1 print(f'image {self.count}/{self.nf} {path}') assert layers0, f"Cannot load images for layers: {self.used_layers}" layers0 = {k: letterbox(layers0[k], self.img_size, stride=self.stride)[0] for k in layers0} layers = concat_layers(layers0, self.used_layers) img0 = layers0[self.used_layers[0]] img0 = np.ascontiguousarray(img0) return img0, layers, path def __len__(self): return self.nf class BDataset(Dataset): def __init__(self, img_path, mesh_path, used_layers=None, img_size=224, map_size=32, augment=False): super(BDataset, self).__init__() if used_layers is None: used_layers = [L_RGB] self.img_path = img_path self.mesh_path = mesh_path self.used_layers = used_layers self.img_size = img_size self.map_size = map_size self.augment = augment self.layer_files = load_img_paths(self.img_path, used_layers) self.img_files = self.layer_files[self.used_layers[0]] self.mesh_files = load_mesh_paths(self.mesh_path) def __len__(self): return len(self.img_files) def __getitem__(self, index): layers0, volume, (h0, w0), (h, w) = load_data(self, index) layers0 = {k: letterbox(layers0[k], self.img_size, auto=False, scale_up=self.augment)[0] for k in layers0} layers = concat_layers(layers0, self.used_layers) img0 = layers0[self.used_layers[0]] img0 = np.ascontiguousarray(img0) return torch.from_numpy(img0), torch.from_numpy(layers), torch.from_numpy(volume), self.img_files[index] def load_data(self, index): layers0, hw0, hw = load_layers(self.layer_files, index, self.used_layers, self.img_size, self.augment) volume0 = load_volume(self.mesh_files, index, self.map_size) return layers0, volume0, hw0, hw def load_layers(layer_files, index, used_layers, img_size=False, augment=False): layers0 = {} hw0, hw = (0, 0), (0, 0) if L_RGB in used_layers: img0, hw0, hw = load_image(layer_files[L_RGB], index, img_size, augment) layers0[L_RGB] = img0 if L_DEPTH in used_layers: depth0, hw0, hw = load_depth(layer_files[L_DEPTH], index, img_size, augment) layers0[L_DEPTH] = depth0 if L_NORMAL in used_layers: normal0, hw0, hw = load_normal(layer_files[L_NORMAL], index, img_size, augment) layers0[L_NORMAL] = normal0 return layers0, hw0, hw def concat_layers(layers, used_layers): if L_RGB in layers: layers[L_RGB] = layers[L_RGB][:, :, ::-1] layers = {k: layers[k].transpose(2, 0, 1) for k in layers} layers = [layers[k] for k in used_layers] layers = np.concatenate(layers, axis=0).astype(np.float32) / 255.0 layers = np.ascontiguousarray(layers) return layers def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scale_fill=False, scale_up=True, stride=32): # Borrowed from https://github.com/ultralytics/yolov5/blob/master/utils/datasets.py # Resize and pad image while meeting stride-multiple constraints shape = img.shape[:2] # current shape [height, width] if isinstance(new_shape, int): new_shape = (new_shape, new_shape) # Scale ratio (new / old) r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) if not scale_up: # only scale down, do not scale up (for better test mAP) r = min(r, 1.0) # Compute padding ratio = r, r # width, height ratios new_pad = int(round(shape[1] * r)), int(round(shape[0] * r)) dw, dh = new_shape[1] - new_pad[0], new_shape[0] - new_pad[1] # wh padding if auto: # minimum rectangle dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding elif scale_fill: # stretch dw, dh = 0.0, 0.0 new_pad = (new_shape[1], new_shape[0]) ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios dw /= 2 # divide padding into 2 sides dh /= 2 if shape[::-1] != new_pad: # resize img = cv2.resize(img, new_pad, interpolation=cv2.INTER_LINEAR) top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border return img, ratio, (dw, dh) def load_image(layer_files, index, img_size, augment=None): path = layer_files[index] img = img2bgr(path) # BGR assert img is not None, 'Image Not Found ' + path return resize_img(img, img_size, augment) def load_depth(layer_files, index, img_size, augment=None): path = layer_files[index] img = exr2depth(path) # 3 channel depth assert img is not None, 'Image Not Found ' + path return resize_img(img, img_size, augment) def load_normal(layer_files, index, img_size, augment=None): path = layer_files[index] img = exr2normal(path) # 3 channel normal assert img is not None, 'Image Not Found ' + path return resize_img(img, img_size, augment) def load_volume(mesh_files, index, map_size): meshes = pkl2mesh((mesh_files[index])) volumes = [[list(v) + [c + 1] for v in vs] for (c, vs, _) in meshes] voxels = np.concatenate(volumes, axis=0) voxels[:, 0] *= (map_size - 1) / max(np.max(voxels[:, 0]), 1) voxels[:, 1] *= (map_size - 1) / max(np.max(voxels[:, 1]), 1) voxels[:, 2] *= (map_size - 1) / max(np.max(voxels[:, 2]), 1) voxels = np.floor(voxels).astype(dtype=np.int64) voxels = np.unique(voxels, axis=0) volume = np.zeros((map_size, map_size, map_size)).astype(np.int64) volume[voxels[:, 0], voxels[:, 1], voxels[:, 2]] = voxels[:, 3] return volume if __name__ == "__main__": _, dl = create_dataloader("../../bdataset_tiny/images/train", "../../bdataset_tiny/labels/train", batch_size=2, shuffle=False) _, _, vms, img_files = next(iter(dl)) plot_volumes(vms, img_files) ds = LoadImages("../../bdataset_tiny/images/train") _, _, img_files = next(iter(ds))
[ "torch.from_numpy", "numpy.ascontiguousarray", "util.common.pkl2mesh", "os.cpu_count", "numpy.mod", "util.common.exr2depth", "util.common.img2bgr", "util.common.load_mesh_paths", "util.common.resize_img", "numpy.max", "numpy.concatenate", "numpy.floor", "cv2.resize", "numpy.unique", "cv2...
[((901, 1004), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'batch_size', 'num_workers': 'nw', 'pin_memory': 'pin_memory', 'shuffle': 'shuffle'}), '(dataset, batch_size=batch_size, num_workers=nw, pin_memory=\n pin_memory, shuffle=shuffle)\n', (911, 1004), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((4545, 4573), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['layers'], {}), '(layers)\n', (4565, 4573), True, 'import numpy as np\n'), ((6012, 6099), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['img', 'top', 'bottom', 'left', 'right', 'cv2.BORDER_CONSTANT'], {'value': 'color'}), '(img, top, bottom, left, right, cv2.BORDER_CONSTANT,\n value=color)\n', (6030, 6099), False, 'import cv2\n'), ((6244, 6257), 'util.common.img2bgr', 'img2bgr', (['path'], {}), '(path)\n', (6251, 6257), False, 'from util.common import exr2normal, exr2depth, img2bgr, pkl2mesh, resize_img, load_mesh_paths, L_RGB, L_DEPTH, L_NORMAL, load_img_paths, plot_volumes\n'), ((6330, 6364), 'util.common.resize_img', 'resize_img', (['img', 'img_size', 'augment'], {}), '(img, img_size, augment)\n', (6340, 6364), False, 'from util.common import exr2normal, exr2depth, img2bgr, pkl2mesh, resize_img, load_mesh_paths, L_RGB, L_DEPTH, L_NORMAL, load_img_paths, plot_volumes\n'), ((6467, 6482), 'util.common.exr2depth', 'exr2depth', (['path'], {}), '(path)\n', (6476, 6482), False, 'from util.common import exr2normal, exr2depth, img2bgr, pkl2mesh, resize_img, load_mesh_paths, L_RGB, L_DEPTH, L_NORMAL, load_img_paths, plot_volumes\n'), ((6567, 6601), 'util.common.resize_img', 'resize_img', (['img', 'img_size', 'augment'], {}), '(img, img_size, augment)\n', (6577, 6601), False, 'from util.common import exr2normal, exr2depth, img2bgr, pkl2mesh, resize_img, load_mesh_paths, L_RGB, L_DEPTH, L_NORMAL, load_img_paths, plot_volumes\n'), ((6705, 6721), 'util.common.exr2normal', 'exr2normal', (['path'], {}), '(path)\n', (6715, 6721), False, 'from util.common import exr2normal, exr2depth, img2bgr, pkl2mesh, resize_img, load_mesh_paths, L_RGB, L_DEPTH, L_NORMAL, load_img_paths, plot_volumes\n'), ((6807, 6841), 'util.common.resize_img', 'resize_img', (['img', 'img_size', 'augment'], {}), '(img, img_size, augment)\n', (6817, 6841), False, 'from util.common import exr2normal, exr2depth, img2bgr, pkl2mesh, resize_img, load_mesh_paths, L_RGB, L_DEPTH, L_NORMAL, load_img_paths, plot_volumes\n'), ((6903, 6930), 'util.common.pkl2mesh', 'pkl2mesh', (['mesh_files[index]'], {}), '(mesh_files[index])\n', (6911, 6930), False, 'from util.common import exr2normal, exr2depth, img2bgr, pkl2mesh, resize_img, load_mesh_paths, L_RGB, L_DEPTH, L_NORMAL, load_img_paths, plot_volumes\n'), ((7020, 7051), 'numpy.concatenate', 'np.concatenate', (['volumes'], {'axis': '(0)'}), '(volumes, axis=0)\n', (7034, 7051), True, 'import numpy as np\n'), ((7316, 7341), 'numpy.unique', 'np.unique', (['voxels'], {'axis': '(0)'}), '(voxels, axis=0)\n', (7325, 7341), True, 'import numpy as np\n'), ((7707, 7735), 'util.common.plot_volumes', 'plot_volumes', (['vms', 'img_files'], {}), '(vms, img_files)\n', (7719, 7735), False, 'from util.common import exr2normal, exr2depth, img2bgr, pkl2mesh, resize_img, load_mesh_paths, L_RGB, L_DEPTH, L_NORMAL, load_img_paths, plot_volumes\n'), ((1319, 1352), 'util.common.load_img_paths', 'load_img_paths', (['path', 'used_layers'], {}), '(path, used_layers)\n', (1333, 1352), False, 'from util.common import exr2normal, exr2depth, img2bgr, pkl2mesh, resize_img, load_mesh_paths, L_RGB, L_DEPTH, L_NORMAL, load_img_paths, plot_volumes\n'), ((2114, 2140), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['img0'], {}), '(img0)\n', (2134, 2140), True, 'import numpy as np\n'), ((2694, 2736), 'util.common.load_img_paths', 'load_img_paths', (['self.img_path', 'used_layers'], {}), '(self.img_path, used_layers)\n', (2708, 2736), False, 'from util.common import exr2normal, exr2depth, img2bgr, pkl2mesh, resize_img, load_mesh_paths, L_RGB, L_DEPTH, L_NORMAL, load_img_paths, plot_volumes\n'), ((2826, 2857), 'util.common.load_mesh_paths', 'load_mesh_paths', (['self.mesh_path'], {}), '(self.mesh_path)\n', (2841, 2857), False, 'from util.common import exr2normal, exr2depth, img2bgr, pkl2mesh, resize_img, load_mesh_paths, L_RGB, L_DEPTH, L_NORMAL, load_img_paths, plot_volumes\n'), ((3252, 3278), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['img0'], {}), '(img0)\n', (3272, 3278), True, 'import numpy as np\n'), ((5823, 5879), 'cv2.resize', 'cv2.resize', (['img', 'new_pad'], {'interpolation': 'cv2.INTER_LINEAR'}), '(img, new_pad, interpolation=cv2.INTER_LINEAR)\n', (5833, 5879), False, 'import cv2\n'), ((800, 814), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (812, 814), False, 'import os\n'), ((3295, 3317), 'torch.from_numpy', 'torch.from_numpy', (['img0'], {}), '(img0)\n', (3311, 3317), False, 'import torch\n'), ((3319, 3343), 'torch.from_numpy', 'torch.from_numpy', (['layers'], {}), '(layers)\n', (3335, 3343), False, 'import torch\n'), ((3345, 3369), 'torch.from_numpy', 'torch.from_numpy', (['volume'], {}), '(volume)\n', (3361, 3369), False, 'import torch\n'), ((5464, 5482), 'numpy.mod', 'np.mod', (['dw', 'stride'], {}), '(dw, stride)\n', (5470, 5482), True, 'import numpy as np\n'), ((5484, 5502), 'numpy.mod', 'np.mod', (['dh', 'stride'], {}), '(dh, stride)\n', (5490, 5502), True, 'import numpy as np\n'), ((7093, 7113), 'numpy.max', 'np.max', (['voxels[:, 0]'], {}), '(voxels[:, 0])\n', (7099, 7113), True, 'import numpy as np\n'), ((7159, 7179), 'numpy.max', 'np.max', (['voxels[:, 1]'], {}), '(voxels[:, 1])\n', (7165, 7179), True, 'import numpy as np\n'), ((7225, 7245), 'numpy.max', 'np.max', (['voxels[:, 2]'], {}), '(voxels[:, 2])\n', (7231, 7245), True, 'import numpy as np\n'), ((7263, 7279), 'numpy.floor', 'np.floor', (['voxels'], {}), '(voxels)\n', (7271, 7279), True, 'import numpy as np\n'), ((7356, 7396), 'numpy.zeros', 'np.zeros', (['(map_size, map_size, map_size)'], {}), '((map_size, map_size, map_size))\n', (7364, 7396), True, 'import numpy as np\n'), ((4474, 4504), 'numpy.concatenate', 'np.concatenate', (['layers'], {'axis': '(0)'}), '(layers, axis=0)\n', (4488, 4504), True, 'import numpy as np\n')]
import codecs from decomposition import PrincipalComponentAnalysis, LinearDiscriminantAnalysis from retriever.data_collection import DataCollection, EDataType from plot import plot_stuff from sklearn.metrics import precision_recall_fscore_support from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import KFold import numpy as np print('Collecting data...') data_collection = DataCollection('res/promise/') pca = PrincipalComponentAnalysis() lda = LinearDiscriminantAnalysis() knn = KNeighborsClassifier(n_neighbors=9, weights='distance', algorithm='auto') kf = KFold(n_splits=5, shuffle=True) # 80% for training, 20% for testing results = {} for relation in data_collection.documents: file_ = codecs.open('res/results/' + relation + '.txt', 'w+', 'utf-8') results[relation] = {} results[relation]['PCA'] = {} results[relation]['LDA'] = {} print('\nTesting for ' + relation + ' data set') relation_data, relation_labels = data_collection.get_data_label(relation) data_len = len(relation_data) features_amount = relation_data[0].size print('\tTotal data collected: ' + str(data_len)) print('\tTotal of features per data: ' + str(features_amount)) # Only numerical features features_types = data_collection.get_features_types(relation) pca.fit(relation_data) lda.fit(relation_data, relation_labels) pca_precision_mean = [] pca_recall_mean = [] pca_f1_mean = [] lda_precision_mean = [] lda_recall_mean = [] lda_f1_mean = [] for n_components in range(1, features_amount+1): pca_components = pca.transform(relation_data, n_components) lda_components = lda.transform(relation_data, n_components) pca_metrics = [] lda_metrics = [] for train_indexes, test_indexes in kf.split(relation_data): pca_train, pca_test = pca_components[train_indexes], pca_components[test_indexes] lda_train, lda_test = lda_components[train_indexes], lda_components[test_indexes] train_labels, test_labels = relation_labels[train_indexes], relation_labels[test_indexes] # PCA testing knn.fit(pca_train, train_labels) pred_labels = knn.predict(pca_test) pca_metrics.append(precision_recall_fscore_support(test_labels, pred_labels, average='weighted')) # LDA testing knn.fit(lda_train, train_labels) pred_labels = knn.predict(lda_test) lda_metrics.append(precision_recall_fscore_support(test_labels, pred_labels, average='weighted')) pca_precisions = [precision for precision, _, _, _ in pca_metrics] pca_recalls = [recall for _, recall, _, _ in pca_metrics] pca_f1s = [f1 for _, _, f1, _ in pca_metrics] lda_precisions = [precision for precision, _, _, _ in lda_metrics] lda_recalls = [recall for _, recall, _, _ in lda_metrics] lda_f1s = [f1 for _, _, f1, _ in lda_metrics] pca_precision_mean.append(np.mean(pca_precisions)) pca_recall_mean.append(np.mean(pca_recalls)) pca_f1_mean.append(np.mean(pca_f1s)) lda_precision_mean.append(np.mean(lda_precisions)) lda_recall_mean.append(np.mean(lda_recalls)) lda_f1_mean.append(np.mean(lda_f1s)) results[relation]['PCA']['precision'] = pca_precision_mean results[relation]['PCA']['recall'] = pca_recall_mean results[relation]['PCA']['f1'] = pca_f1_mean results[relation]['LDA']['precision'] = lda_precision_mean results[relation]['LDA']['recall'] = lda_recall_mean results[relation]['LDA']['f1'] = lda_f1_mean file_.write('PCA precision:\n' + str(pca_precision_mean)) file_.write('\n\nPCA recall:\n' + str(pca_recall_mean)) file_.write('\n\nPCA f1:\n' + str(pca_f1_mean)) file_.write('\n\nLDA precision:\n' + str(lda_precision_mean)) file_.write('\n\nLDA recall:\n' + str(lda_recall_mean)) file_.write('\n\nLDA f1:\n' + str(lda_f1_mean)) plot_stuff(results[relation], relation, list(range(1, features_amount+1)))
[ "numpy.mean", "retriever.data_collection.DataCollection", "sklearn.metrics.precision_recall_fscore_support", "sklearn.neighbors.KNeighborsClassifier", "decomposition.PrincipalComponentAnalysis", "codecs.open", "sklearn.model_selection.KFold", "decomposition.LinearDiscriminantAnalysis" ]
[((407, 437), 'retriever.data_collection.DataCollection', 'DataCollection', (['"""res/promise/"""'], {}), "('res/promise/')\n", (421, 437), False, 'from retriever.data_collection import DataCollection, EDataType\n'), ((445, 473), 'decomposition.PrincipalComponentAnalysis', 'PrincipalComponentAnalysis', ([], {}), '()\n', (471, 473), False, 'from decomposition import PrincipalComponentAnalysis, LinearDiscriminantAnalysis\n'), ((480, 508), 'decomposition.LinearDiscriminantAnalysis', 'LinearDiscriminantAnalysis', ([], {}), '()\n', (506, 508), False, 'from decomposition import PrincipalComponentAnalysis, LinearDiscriminantAnalysis\n'), ((516, 589), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', ([], {'n_neighbors': '(9)', 'weights': '"""distance"""', 'algorithm': '"""auto"""'}), "(n_neighbors=9, weights='distance', algorithm='auto')\n", (536, 589), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((595, 626), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(5)', 'shuffle': '(True)'}), '(n_splits=5, shuffle=True)\n', (600, 626), False, 'from sklearn.model_selection import KFold\n'), ((732, 794), 'codecs.open', 'codecs.open', (["('res/results/' + relation + '.txt')", '"""w+"""', '"""utf-8"""'], {}), "('res/results/' + relation + '.txt', 'w+', 'utf-8')\n", (743, 794), False, 'import codecs\n'), ((3042, 3065), 'numpy.mean', 'np.mean', (['pca_precisions'], {}), '(pca_precisions)\n', (3049, 3065), True, 'import numpy as np\n'), ((3098, 3118), 'numpy.mean', 'np.mean', (['pca_recalls'], {}), '(pca_recalls)\n', (3105, 3118), True, 'import numpy as np\n'), ((3147, 3163), 'numpy.mean', 'np.mean', (['pca_f1s'], {}), '(pca_f1s)\n', (3154, 3163), True, 'import numpy as np\n'), ((3200, 3223), 'numpy.mean', 'np.mean', (['lda_precisions'], {}), '(lda_precisions)\n', (3207, 3223), True, 'import numpy as np\n'), ((3256, 3276), 'numpy.mean', 'np.mean', (['lda_recalls'], {}), '(lda_recalls)\n', (3263, 3276), True, 'import numpy as np\n'), ((3305, 3321), 'numpy.mean', 'np.mean', (['lda_f1s'], {}), '(lda_f1s)\n', (3312, 3321), True, 'import numpy as np\n'), ((2290, 2367), 'sklearn.metrics.precision_recall_fscore_support', 'precision_recall_fscore_support', (['test_labels', 'pred_labels'], {'average': '"""weighted"""'}), "(test_labels, pred_labels, average='weighted')\n", (2321, 2367), False, 'from sklearn.metrics import precision_recall_fscore_support\n'), ((2520, 2597), 'sklearn.metrics.precision_recall_fscore_support', 'precision_recall_fscore_support', (['test_labels', 'pred_labels'], {'average': '"""weighted"""'}), "(test_labels, pred_labels, average='weighted')\n", (2551, 2597), False, 'from sklearn.metrics import precision_recall_fscore_support\n')]
""" =================== Isotonic Regression =================== An illustration of the isotonic regression on generated data. The isotonic regression finds a non-decreasing approximation of a function while minimizing the mean squared error on the training data. The benefit of such a model is that it does not assume any form for the target function such as linearity. For comparison a linear regression is also presented. """ print(__doc__) # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License: BSD import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from sklearn.linear_model import LinearRegression from sklearn.isotonic import IsotonicRegression from sklearn.utils import check_random_state n = 100 x = np.arange(n) rs = check_random_state(0) y = rs.randint(-50, 50, size=(n,)) + 50. * np.log1p(np.arange(n)) lr = LinearRegression() lr.fit(x[:, np.newaxis], y) # x needs to be 2d for LinearRegression lr_ = LinearRegression(fit_intercept=False) lr_.fit(x[:, np.newaxis], y) # x needs to be 2d for LinearRegression witout intercept # analysis # # coefficient of determination lr_r2 = lr.score(np.expand_dims(x, 1), y) print(lr_r2) lr__r2 = lr_.score(np.expand_dims(x, 1), y) print(lr__r2) # ############################################################################# fig = plt.figure() plt.plot(x, y, 'r.', markersize=6) y_pre = lr.predict(x[:, np.newaxis]) plt.plot(x, y_pre, 'b-') plt.text(x[-1], y_pre[-1], 'r2: {}'.format(round(lr_r2, 2)), ha='center', va='bottom', fontsize=8) y_pre = lr_.predict(x[:, np.newaxis]) plt.plot(x, y_pre, 'r-') plt.text(x[-1], y_pre[-1], 'r2: {}'.format(round(lr__r2, 2)), ha='center', va='bottom', fontsize=8) # plt.gca().add_collection(lc) plt.legend(('Data', 'Linear Fit', 'Linear Fit no Intercept'), loc='lower right') plt.title('Isotonic regression') plt.savefig("./linear_regression/generate/learn_regression.png")
[ "sklearn.utils.check_random_state", "matplotlib.pyplot.savefig", "matplotlib.pyplot.legend", "matplotlib.pyplot.plot", "matplotlib.pyplot.figure", "numpy.expand_dims", "matplotlib.pyplot.title", "sklearn.linear_model.LinearRegression", "numpy.arange" ]
[((774, 786), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (783, 786), True, 'import numpy as np\n'), ((792, 813), 'sklearn.utils.check_random_state', 'check_random_state', (['(0)'], {}), '(0)\n', (810, 813), False, 'from sklearn.utils import check_random_state\n'), ((886, 904), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (902, 904), False, 'from sklearn.linear_model import LinearRegression\n'), ((981, 1018), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {'fit_intercept': '(False)'}), '(fit_intercept=False)\n', (997, 1018), False, 'from sklearn.linear_model import LinearRegression\n'), ((1351, 1363), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1361, 1363), True, 'import matplotlib.pyplot as plt\n'), ((1364, 1398), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""r."""'], {'markersize': '(6)'}), "(x, y, 'r.', markersize=6)\n", (1372, 1398), True, 'import matplotlib.pyplot as plt\n'), ((1436, 1460), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y_pre', '"""b-"""'], {}), "(x, y_pre, 'b-')\n", (1444, 1460), True, 'import matplotlib.pyplot as plt\n'), ((1598, 1622), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y_pre', '"""r-"""'], {}), "(x, y_pre, 'r-')\n", (1606, 1622), True, 'import matplotlib.pyplot as plt\n'), ((1754, 1839), 'matplotlib.pyplot.legend', 'plt.legend', (["('Data', 'Linear Fit', 'Linear Fit no Intercept')"], {'loc': '"""lower right"""'}), "(('Data', 'Linear Fit', 'Linear Fit no Intercept'), loc='lower right'\n )\n", (1764, 1839), True, 'import matplotlib.pyplot as plt\n'), ((1835, 1867), 'matplotlib.pyplot.title', 'plt.title', (['"""Isotonic regression"""'], {}), "('Isotonic regression')\n", (1844, 1867), True, 'import matplotlib.pyplot as plt\n'), ((1868, 1932), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./linear_regression/generate/learn_regression.png"""'], {}), "('./linear_regression/generate/learn_regression.png')\n", (1879, 1932), True, 'import matplotlib.pyplot as plt\n'), ((1168, 1188), 'numpy.expand_dims', 'np.expand_dims', (['x', '(1)'], {}), '(x, 1)\n', (1182, 1188), True, 'import numpy as np\n'), ((1225, 1245), 'numpy.expand_dims', 'np.expand_dims', (['x', '(1)'], {}), '(x, 1)\n', (1239, 1245), True, 'import numpy as np\n'), ((866, 878), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (875, 878), True, 'import numpy as np\n')]
#!/bin/env/python ''' test quijote halo readins ''' import numpy as np from boss_sbi.halos import Quijote_LHC_HR halos = Quijote_LHC_HR(1, z=0.5) print(np.array(halos['Position']))
[ "boss_sbi.halos.Quijote_LHC_HR", "numpy.array" ]
[((125, 149), 'boss_sbi.halos.Quijote_LHC_HR', 'Quijote_LHC_HR', (['(1)'], {'z': '(0.5)'}), '(1, z=0.5)\n', (139, 149), False, 'from boss_sbi.halos import Quijote_LHC_HR\n'), ((156, 183), 'numpy.array', 'np.array', (["halos['Position']"], {}), "(halos['Position'])\n", (164, 183), True, 'import numpy as np\n')]
"""Tests for skio/codec.py""" from skio import intdecode, intencode import pytest import numpy as np from numpy.testing import assert_equal, assert_almost_equal IDAT = np.array(((0, 1, 2), (3, 4, 5))) # Integer data FDAT = np.array(((0.0, 0.5, 1.0), (1.5, 2.0, 2.5))) # Float data FDAT_NEG = np.array(((-2.0, -1.0, 0.0), (1.0, 2.0, 3.0))) # Data with value <0 FDAT_NAN = np.array(((0.0, 0.5, 1.0), (np.nan, 2.0, 2.5))) # Data with nan MDAT = np.array(((False, False, False), (True, False, False))) # Nan Mask def test_intdecode_invalid(): """'intdecode' function: 'invalid' argument""" # None assert_equal(intdecode(IDAT, 0.5, invalid=None), FDAT) # None: Test mask assert not intdecode(IDAT, 0.5, invalid=None, masked=True).mask.any() # Single assert_equal(intdecode(IDAT, 0.5, invalid=3), FDAT_NAN) # Single: Test mask assert_equal(intdecode(IDAT, 0.5, invalid=3, masked=True).mask, MDAT) # Tuple assert_equal(intdecode(IDAT, 0.5, invalid=(1, 4)), np.array(((np.nan, np.nan, 1.0), (1.5, np.nan, np.nan)))) # Tuple: Test mask assert_equal(intdecode(IDAT, 0.5, invalid=(1, 4), masked=True).mask, np.array(((True, True, False), (False, True, True)))) def test_intdecode_dtype(): """'intdecode' function: 'dtype' argument""" # set dtype assert intdecode(IDAT, 0.5, dtype=np.float32).dtype == np.float32 # Not a floating type with pytest.raises(ValueError) as excinfo: intdecode(IDAT, 0.5, dtype=np.int32) assert 'dtype must be a floating data type' in str(excinfo.value) def test_intencode_invalidvalue(): """'intencode' function: 'invalidvalue' argument""" # False : With no invalid data data, factor = intencode(FDAT, np.int16, invalidvalue=False) assert_equal(data, np.array(((0, 6553, 13107), (19660, 26214, 32767)))) assert_almost_equal(factor, 7.6296273689992981e-05) # False : With invalid data data = intencode(FDAT_NAN, np.int16, invalidvalue=False)[0] assert_equal(data.mask, MDAT) assert_equal(data.data, np.array(((0, 6553, 13107), (0, 26214, 32767)))) # None : With signed int assert_equal(intencode(FDAT_NAN, np.int16, invalidvalue=None)[0], np.array(((0, 6553, 13107), (-32768, 26214, 32767)))) # None : With unsigned int assert_equal(intencode(FDAT_NAN, np.uint16, invalidvalue=None)[0], np.array(((0, 13107, 26214), (65535, 52427, 65534)))) # Specified value assert_equal(intencode(FDAT_NAN, np.int16, invalidvalue=-1)[0], np.array(((0, 6553, 13107), (-1, 26214, 32767)))) def test_intencode_rangeminmax(): """'intencode' function: 'rangemin' & 'rangemax' arguments""" # Negative and positive min and max assert_equal(intencode(FDAT_NEG, np.int16, rangemin=-100, rangemax=100)[0], np.array(((-67, -33, 0), (33, 67, 100)))) # Negative and positive min and max with inverted data assert_equal(intencode(FDAT_NEG * -1, np.int16, rangemin=-100, rangemax=100)[0], np.array(((67, 33, 0), (-33, -67, -100)))) # Positive min and max assert_equal(intencode(FDAT_NEG, np.int16, rangemin=100, rangemax=200)[0], np.array(((100, 120, 140), (160, 180, 200)))) # Negative min and max assert_equal(intencode(FDAT_NEG, np.int16, rangemin=-200, rangemax=-100)[0], np.array(((-200, -180, -160), (-140, -120, -100)))) # Too larges values assert_equal(intencode(FDAT_NEG, np.int8, rangemin=-256, rangemax=256)[0], np.array(((-85, -42, 0), (42, 85, 127)))) def test_intencode_keepsign(): """'intencode' function: 'keepsign' argument""" # Keep assert_equal(intencode(FDAT_NEG, np.int16, keepsign=True)[0], np.array(((-21845, -10922, 0), (10922, 21845, 32767)))) # Don't keep assert_equal(intencode(FDAT_NEG, np.int16, keepsign=False)[0], np.array(((0, 6553, 13107), (19660, 26214, 32767)))) # Keep but unsigned assert_equal(intencode(FDAT_NEG, np.uint16, keepsign=True)[0], np.array(((0, 13107, 26214), (39321, 52428, 65535)))) def test_intencode_int_inv_max(): """'intencode' function: 'intfactor', 'maxfactor', 'invfactor' arguments""" # Float assert intencode(FDAT, np.uint8, rangemax=1, intfactor=False)[1] == 2.5 # Float inverted assert_almost_equal(intencode(FDAT, np.uint8, rangemax=1, invfactor=True, intfactor=False)[1], 0.4) # Float inverted maxed assert intencode(FDAT, np.uint8, maxfactor=10, invfactor=True, intfactor=False)[1] == 10 # Float inverted maxed with max = int max assert intencode(FDAT * 1e-5, np.uint8, maxfactor=-1, invfactor=True, intfactor=False)[1] == 255 # Float maxed assert_almost_equal(intencode(FDAT, np.uint8, maxfactor=1e-5, intfactor=False)[1], 1e-5) # Integer assert intencode(FDAT, np.uint8, rangemax=1, intfactor=True)[1] == 3 # Integer inverted assert intencode(FDAT, np.uint8, rangemax=1, invfactor=True, intfactor=True)[1] == 1 # Integer inverted maxed assert intencode(FDAT, np.uint8, maxfactor=10, invfactor=True, intfactor=True)[1] == 10 # Integer maxed assert intencode(FDAT, np.uint8, maxfactor=1, intfactor=True)[1] == 1 def test_intencode_forcefactor(): """'intencode' function: 'forcefactor' argument""" assert intencode(FDAT, np.uint8, forcefactor=42)[1] == 42 def test_intencode_intround(): """'intencode' function: 'intround' argument""" # Round assert_equal(intencode(FDAT_NEG, np.int16, intround=True)[0], np.array(((-21845, -10922, 0), (10922, 21845, 32767)))) # Don't round assert_equal(intencode(FDAT_NEG, np.int16, intround=False)[0], np.array(((-21844, -10922, 0), (10922, 21844, 32767)))) def test_intencode_inttype(): """'intencode' function: character code as int dtype""" # Character code assert_equal(intencode(FDAT, 'h')[0], np.array(((0, 6553, 13107), (19660, 26214, 32767))))
[ "skio.intencode", "numpy.testing.assert_equal", "numpy.array", "numpy.testing.assert_almost_equal", "pytest.raises", "skio.intdecode" ]
[((170, 202), 'numpy.array', 'np.array', (['((0, 1, 2), (3, 4, 5))'], {}), '(((0, 1, 2), (3, 4, 5)))\n', (178, 202), True, 'import numpy as np\n'), ((226, 270), 'numpy.array', 'np.array', (['((0.0, 0.5, 1.0), (1.5, 2.0, 2.5))'], {}), '(((0.0, 0.5, 1.0), (1.5, 2.0, 2.5)))\n', (234, 270), True, 'import numpy as np\n'), ((296, 342), 'numpy.array', 'np.array', (['((-2.0, -1.0, 0.0), (1.0, 2.0, 3.0))'], {}), '(((-2.0, -1.0, 0.0), (1.0, 2.0, 3.0)))\n', (304, 342), True, 'import numpy as np\n'), ((376, 423), 'numpy.array', 'np.array', (['((0.0, 0.5, 1.0), (np.nan, 2.0, 2.5))'], {}), '(((0.0, 0.5, 1.0), (np.nan, 2.0, 2.5)))\n', (384, 423), True, 'import numpy as np\n'), ((448, 503), 'numpy.array', 'np.array', (['((False, False, False), (True, False, False))'], {}), '(((False, False, False), (True, False, False)))\n', (456, 503), True, 'import numpy as np\n'), ((1745, 1790), 'skio.intencode', 'intencode', (['FDAT', 'np.int16'], {'invalidvalue': '(False)'}), '(FDAT, np.int16, invalidvalue=False)\n', (1754, 1790), False, 'from skio import intdecode, intencode\n'), ((1871, 1921), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['factor', '(7.629627368999298e-05)'], {}), '(factor, 7.629627368999298e-05)\n', (1890, 1921), False, 'from numpy.testing import assert_equal, assert_almost_equal\n'), ((2023, 2052), 'numpy.testing.assert_equal', 'assert_equal', (['data.mask', 'MDAT'], {}), '(data.mask, MDAT)\n', (2035, 2052), False, 'from numpy.testing import assert_equal, assert_almost_equal\n'), ((627, 661), 'skio.intdecode', 'intdecode', (['IDAT', '(0.5)'], {'invalid': 'None'}), '(IDAT, 0.5, invalid=None)\n', (636, 661), False, 'from skio import intdecode, intencode\n'), ((795, 826), 'skio.intdecode', 'intdecode', (['IDAT', '(0.5)'], {'invalid': '(3)'}), '(IDAT, 0.5, invalid=3)\n', (804, 826), False, 'from skio import intdecode, intencode\n'), ((965, 1001), 'skio.intdecode', 'intdecode', (['IDAT', '(0.5)'], {'invalid': '(1, 4)'}), '(IDAT, 0.5, invalid=(1, 4))\n', (974, 1001), False, 'from skio import intdecode, intencode\n'), ((1020, 1076), 'numpy.array', 'np.array', (['((np.nan, np.nan, 1.0), (1.5, np.nan, np.nan))'], {}), '(((np.nan, np.nan, 1.0), (1.5, np.nan, np.nan)))\n', (1028, 1076), True, 'import numpy as np\n'), ((1191, 1243), 'numpy.array', 'np.array', (['((True, True, False), (False, True, True))'], {}), '(((True, True, False), (False, True, True)))\n', (1199, 1243), True, 'import numpy as np\n'), ((1445, 1470), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1458, 1470), False, 'import pytest\n'), ((1491, 1527), 'skio.intdecode', 'intdecode', (['IDAT', '(0.5)'], {'dtype': 'np.int32'}), '(IDAT, 0.5, dtype=np.int32)\n', (1500, 1527), False, 'from skio import intdecode, intencode\n'), ((1814, 1865), 'numpy.array', 'np.array', (['((0, 6553, 13107), (19660, 26214, 32767))'], {}), '(((0, 6553, 13107), (19660, 26214, 32767)))\n', (1822, 1865), True, 'import numpy as np\n'), ((1966, 2015), 'skio.intencode', 'intencode', (['FDAT_NAN', 'np.int16'], {'invalidvalue': '(False)'}), '(FDAT_NAN, np.int16, invalidvalue=False)\n', (1975, 2015), False, 'from skio import intdecode, intencode\n'), ((2081, 2128), 'numpy.array', 'np.array', (['((0, 6553, 13107), (0, 26214, 32767))'], {}), '(((0, 6553, 13107), (0, 26214, 32767)))\n', (2089, 2128), True, 'import numpy as np\n'), ((2246, 2298), 'numpy.array', 'np.array', (['((0, 6553, 13107), (-32768, 26214, 32767))'], {}), '(((0, 6553, 13107), (-32768, 26214, 32767)))\n', (2254, 2298), True, 'import numpy as np\n'), ((2419, 2471), 'numpy.array', 'np.array', (['((0, 13107, 26214), (65535, 52427, 65534))'], {}), '(((0, 13107, 26214), (65535, 52427, 65534)))\n', (2427, 2471), True, 'import numpy as np\n'), ((2580, 2628), 'numpy.array', 'np.array', (['((0, 6553, 13107), (-1, 26214, 32767))'], {}), '(((0, 6553, 13107), (-1, 26214, 32767)))\n', (2588, 2628), True, 'import numpy as np\n'), ((2886, 2926), 'numpy.array', 'np.array', (['((-67, -33, 0), (33, 67, 100))'], {}), '(((-67, -33, 0), (33, 67, 100)))\n', (2894, 2926), True, 'import numpy as np\n'), ((3099, 3140), 'numpy.array', 'np.array', (['((67, 33, 0), (-33, -67, -100))'], {}), '(((67, 33, 0), (-33, -67, -100)))\n', (3107, 3140), True, 'import numpy as np\n'), ((3320, 3364), 'numpy.array', 'np.array', (['((100, 120, 140), (160, 180, 200))'], {}), '(((100, 120, 140), (160, 180, 200)))\n', (3328, 3364), True, 'import numpy as np\n'), ((3508, 3558), 'numpy.array', 'np.array', (['((-200, -180, -160), (-140, -120, -100))'], {}), '(((-200, -180, -160), (-140, -120, -100)))\n', (3516, 3558), True, 'import numpy as np\n'), ((3680, 3720), 'numpy.array', 'np.array', (['((-85, -42, 0), (42, 85, 127))'], {}), '(((-85, -42, 0), (42, 85, 127)))\n', (3688, 3720), True, 'import numpy as np\n'), ((3901, 3955), 'numpy.array', 'np.array', (['((-21845, -10922, 0), (10922, 21845, 32767))'], {}), '(((-21845, -10922, 0), (10922, 21845, 32767)))\n', (3909, 3955), True, 'import numpy as np\n'), ((4058, 4109), 'numpy.array', 'np.array', (['((0, 6553, 13107), (19660, 26214, 32767))'], {}), '(((0, 6553, 13107), (19660, 26214, 32767)))\n', (4066, 4109), True, 'import numpy as np\n'), ((4219, 4271), 'numpy.array', 'np.array', (['((0, 13107, 26214), (39321, 52428, 65535))'], {}), '(((0, 13107, 26214), (39321, 52428, 65535)))\n', (4227, 4271), True, 'import numpy as np\n'), ((5879, 5933), 'numpy.array', 'np.array', (['((-21845, -10922, 0), (10922, 21845, 32767))'], {}), '(((-21845, -10922, 0), (10922, 21845, 32767)))\n', (5887, 5933), True, 'import numpy as np\n'), ((6037, 6091), 'numpy.array', 'np.array', (['((-21844, -10922, 0), (10922, 21844, 32767))'], {}), '(((-21844, -10922, 0), (10922, 21844, 32767)))\n', (6045, 6091), True, 'import numpy as np\n'), ((6265, 6316), 'numpy.array', 'np.array', (['((0, 6553, 13107), (19660, 26214, 32767))'], {}), '(((0, 6553, 13107), (19660, 26214, 32767)))\n', (6273, 6316), True, 'import numpy as np\n'), ((879, 923), 'skio.intdecode', 'intdecode', (['IDAT', '(0.5)'], {'invalid': '(3)', 'masked': '(True)'}), '(IDAT, 0.5, invalid=3, masked=True)\n', (888, 923), False, 'from skio import intdecode, intencode\n'), ((1118, 1167), 'skio.intdecode', 'intdecode', (['IDAT', '(0.5)'], {'invalid': '(1, 4)', 'masked': '(True)'}), '(IDAT, 0.5, invalid=(1, 4), masked=True)\n', (1127, 1167), False, 'from skio import intdecode, intencode\n'), ((1351, 1389), 'skio.intdecode', 'intdecode', (['IDAT', '(0.5)'], {'dtype': 'np.float32'}), '(IDAT, 0.5, dtype=np.float32)\n', (1360, 1389), False, 'from skio import intdecode, intencode\n'), ((2176, 2224), 'skio.intencode', 'intencode', (['FDAT_NAN', 'np.int16'], {'invalidvalue': 'None'}), '(FDAT_NAN, np.int16, invalidvalue=None)\n', (2185, 2224), False, 'from skio import intdecode, intencode\n'), ((2348, 2397), 'skio.intencode', 'intencode', (['FDAT_NAN', 'np.uint16'], {'invalidvalue': 'None'}), '(FDAT_NAN, np.uint16, invalidvalue=None)\n', (2357, 2397), False, 'from skio import intdecode, intencode\n'), ((2512, 2558), 'skio.intencode', 'intencode', (['FDAT_NAN', 'np.int16'], {'invalidvalue': '(-1)'}), '(FDAT_NAN, np.int16, invalidvalue=-1)\n', (2521, 2558), False, 'from skio import intdecode, intencode\n'), ((2789, 2847), 'skio.intencode', 'intencode', (['FDAT_NEG', 'np.int16'], {'rangemin': '(-100)', 'rangemax': '(100)'}), '(FDAT_NEG, np.int16, rangemin=-100, rangemax=100)\n', (2798, 2847), False, 'from skio import intdecode, intencode\n'), ((3004, 3067), 'skio.intencode', 'intencode', (['(FDAT_NEG * -1)', 'np.int16'], {'rangemin': '(-100)', 'rangemax': '(100)'}), '(FDAT_NEG * -1, np.int16, rangemin=-100, rangemax=100)\n', (3013, 3067), False, 'from skio import intdecode, intencode\n'), ((3241, 3298), 'skio.intencode', 'intencode', (['FDAT_NEG', 'np.int16'], {'rangemin': '(100)', 'rangemax': '(200)'}), '(FDAT_NEG, np.int16, rangemin=100, rangemax=200)\n', (3250, 3298), False, 'from skio import intdecode, intencode\n'), ((3410, 3469), 'skio.intencode', 'intencode', (['FDAT_NEG', 'np.int16'], {'rangemin': '(-200)', 'rangemax': '(-100)'}), '(FDAT_NEG, np.int16, rangemin=-200, rangemax=-100)\n', (3419, 3469), False, 'from skio import intdecode, intencode\n'), ((3601, 3658), 'skio.intencode', 'intencode', (['FDAT_NEG', 'np.int8'], {'rangemin': '(-256)', 'rangemax': '(256)'}), '(FDAT_NEG, np.int8, rangemin=-256, rangemax=256)\n', (3610, 3658), False, 'from skio import intdecode, intencode\n'), ((3835, 3879), 'skio.intencode', 'intencode', (['FDAT_NEG', 'np.int16'], {'keepsign': '(True)'}), '(FDAT_NEG, np.int16, keepsign=True)\n', (3844, 3879), False, 'from skio import intdecode, intencode\n'), ((3991, 4036), 'skio.intencode', 'intencode', (['FDAT_NEG', 'np.int16'], {'keepsign': '(False)'}), '(FDAT_NEG, np.int16, keepsign=False)\n', (4000, 4036), False, 'from skio import intdecode, intencode\n'), ((4152, 4197), 'skio.intencode', 'intencode', (['FDAT_NEG', 'np.uint16'], {'keepsign': '(True)'}), '(FDAT_NEG, np.uint16, keepsign=True)\n', (4161, 4197), False, 'from skio import intdecode, intencode\n'), ((4412, 4466), 'skio.intencode', 'intencode', (['FDAT', 'np.uint8'], {'rangemax': '(1)', 'intfactor': '(False)'}), '(FDAT, np.uint8, rangemax=1, intfactor=False)\n', (4421, 4466), False, 'from skio import intdecode, intencode\n'), ((4522, 4592), 'skio.intencode', 'intencode', (['FDAT', 'np.uint8'], {'rangemax': '(1)', 'invfactor': '(True)', 'intfactor': '(False)'}), '(FDAT, np.uint8, rangemax=1, invfactor=True, intfactor=False)\n', (4531, 4592), False, 'from skio import intdecode, intencode\n'), ((4674, 4746), 'skio.intencode', 'intencode', (['FDAT', 'np.uint8'], {'maxfactor': '(10)', 'invfactor': '(True)', 'intfactor': '(False)'}), '(FDAT, np.uint8, maxfactor=10, invfactor=True, intfactor=False)\n', (4683, 4746), False, 'from skio import intdecode, intencode\n'), ((4834, 4919), 'skio.intencode', 'intencode', (['(FDAT * 1e-05)', 'np.uint8'], {'maxfactor': '(-1)', 'invfactor': '(True)', 'intfactor': '(False)'}), '(FDAT * 1e-05, np.uint8, maxfactor=-1, invfactor=True, intfactor=False\n )\n', (4843, 4919), False, 'from skio import intdecode, intencode\n'), ((4987, 5046), 'skio.intencode', 'intencode', (['FDAT', 'np.uint8'], {'maxfactor': '(1e-05)', 'intfactor': '(False)'}), '(FDAT, np.uint8, maxfactor=1e-05, intfactor=False)\n', (4996, 5046), False, 'from skio import intdecode, intencode\n'), ((5115, 5168), 'skio.intencode', 'intencode', (['FDAT', 'np.uint8'], {'rangemax': '(1)', 'intfactor': '(True)'}), '(FDAT, np.uint8, rangemax=1, intfactor=True)\n', (5124, 5168), False, 'from skio import intdecode, intencode\n'), ((5211, 5280), 'skio.intencode', 'intencode', (['FDAT', 'np.uint8'], {'rangemax': '(1)', 'invfactor': '(True)', 'intfactor': '(True)'}), '(FDAT, np.uint8, rangemax=1, invfactor=True, intfactor=True)\n', (5220, 5280), False, 'from skio import intdecode, intencode\n'), ((5350, 5421), 'skio.intencode', 'intencode', (['FDAT', 'np.uint8'], {'maxfactor': '(10)', 'invfactor': '(True)', 'intfactor': '(True)'}), '(FDAT, np.uint8, maxfactor=10, invfactor=True, intfactor=True)\n', (5359, 5421), False, 'from skio import intdecode, intencode\n'), ((5483, 5537), 'skio.intencode', 'intencode', (['FDAT', 'np.uint8'], {'maxfactor': '(1)', 'intfactor': '(True)'}), '(FDAT, np.uint8, maxfactor=1, intfactor=True)\n', (5492, 5537), False, 'from skio import intdecode, intencode\n'), ((5648, 5689), 'skio.intencode', 'intencode', (['FDAT', 'np.uint8'], {'forcefactor': '(42)'}), '(FDAT, np.uint8, forcefactor=42)\n', (5657, 5689), False, 'from skio import intdecode, intencode\n'), ((5813, 5857), 'skio.intencode', 'intencode', (['FDAT_NEG', 'np.int16'], {'intround': '(True)'}), '(FDAT_NEG, np.int16, intround=True)\n', (5822, 5857), False, 'from skio import intdecode, intencode\n'), ((5970, 6015), 'skio.intencode', 'intencode', (['FDAT_NEG', 'np.int16'], {'intround': '(False)'}), '(FDAT_NEG, np.int16, intround=False)\n', (5979, 6015), False, 'from skio import intdecode, intencode\n'), ((6223, 6243), 'skio.intencode', 'intencode', (['FDAT', '"""h"""'], {}), "(FDAT, 'h')\n", (6232, 6243), False, 'from skio import intdecode, intencode\n'), ((706, 753), 'skio.intdecode', 'intdecode', (['IDAT', '(0.5)'], {'invalid': 'None', 'masked': '(True)'}), '(IDAT, 0.5, invalid=None, masked=True)\n', (715, 753), False, 'from skio import intdecode, intencode\n')]
# -*- coding: utf-8 -*- """ biosppy.stats --------------- This module provides statistica functions and related tools. :copyright: (c) 2015-2021 by Instituto de Telecomunicacoes :license: BSD 3-clause, see LICENSE for more details. """ # Imports # compat from __future__ import absolute_import, division, print_function import six # local from . import utils # 3rd party import numpy as np import matplotlib.pyplot as plt from scipy.stats import pearsonr, ttest_rel, ttest_ind def pearson_correlation(x=None, y=None): """Compute the Pearson Correlation Coefficient between two signals. The coefficient is given by: .. math:: r_{xy} = \\frac{E[(X - \\mu_X) (Y - \\mu_Y)]}{\\sigma_X \\sigma_Y} Parameters ---------- x : array First input signal. y : array Second input signal. Returns ------- r : float Pearson correlation coefficient, ranging between -1 and +1. pvalue : float Two-tailed p-value. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Raises ------ ValueError If the input signals do not have the same length. """ # check inputs if x is None: raise TypeError("Please specify the first input signal.") if y is None: raise TypeError("Please specify the second input signal.") # ensure numpy x = np.array(x) y = np.array(y) n = len(x) if n != len(y): raise ValueError("Input signals must have the same length.") r, pvalue = pearsonr(x, y) return r, pvalue def linear_regression(x=None, y=None): """Plot the linear regression between two signals and get the equation coefficients. The linear regression uses the least squares method. Parameters ---------- x : array First input signal. y : array Second input signal. Returns ------- coeffs : array Linear regression coefficients: [m, b]. Raises ------ ValueError If the input signals do not have the same length. """ # check inputs if x is None: raise TypeError("Please specify the first input signal.") if y is None: raise TypeError("Please specify the second input signal.") # ensure numpy x = np.array(x) y = np.array(y) n = len(x) if n != len(y): raise ValueError("Input signals must have the same length.") coeffs = np.polyfit(x, y, 1) f = np.poly1d(coeffs) x_min = x.min() x_max = x.max() y_min = f(x_min) y_max = f(x_max) plt.scatter(x, y) plt.plot( [x_min, x_max], [y_min, y_max], c="orange", label="y={:.3f}x+{:.3f}".format(coeffs[0], coeffs[1]), ) plt.title("Linear Regression") plt.xlabel("x") plt.ylabel("y") plt.legend() return coeffs def paired_test(x=None, y=None): """ Perform the Student's paired t-test on the arrays x and y. This is a two-sided test for the null hypothesis that 2 related or repeated samples have identical average (expected) values. Parameters ---------- x : array First input signal. y : array Second input signal. Returns ------- statistic : float t-statistic. The t-statistic is used in a t-test to determine if you should support or reject the null hypothesis. pvalue : float Two-sided p-value. Raises ------ ValueError If the input signals do not have the same length. """ # check inputs if x is None: raise TypeError("Please specify the first input signal.") if y is None: raise TypeError("Please specify the second input signal.") # ensure numpy x = np.array(x) y = np.array(y) n = len(x) if n != len(y): raise ValueError("Input signals must have the same length.") statistic, pvalue = ttest_rel(x, y) return statistic, pvalue def unpaired_test(x=None, y=None): """ Perform the Student's unpaired t-test on the arrays x and y. This is a two-sided test for the null hypothesis that 2 independent samples have identical average (expected) values. This test assumes that the populations have identical variances by default. Parameters ---------- x : array First input signal. y : array Second input signal. Returns ------- statistic : float t-statistic. The t-statistic is used in a t-test to determine if you should support or reject the null hypothesis. pvalue : float Two-sided p-value. Raises ------ ValueError If the input signals do not have the same length. """ # check inputs if x is None: raise TypeError("Please specify the first input signal.") if y is None: raise TypeError("Please specify the second input signal.") # ensure numpy x = np.array(x) y = np.array(y) n = len(x) if n != len(y): raise ValueError("Input signals must have the same length.") statistic, pvalue = ttest_ind(x, y) return statistic, pvalue
[ "numpy.polyfit", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.array", "scipy.stats.ttest_rel", "scipy.stats.ttest_ind", "matplotlib.pyplot.scatter", "scipy.stats.pearsonr", "numpy.poly1d", "matplotlib.pyplot.title", "matplotlib.pyplot.legend" ]
[((1516, 1527), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1524, 1527), True, 'import numpy as np\n'), ((1536, 1547), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (1544, 1547), True, 'import numpy as np\n'), ((1671, 1685), 'scipy.stats.pearsonr', 'pearsonr', (['x', 'y'], {}), '(x, y)\n', (1679, 1685), False, 'from scipy.stats import pearsonr, ttest_rel, ttest_ind\n'), ((2427, 2438), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2435, 2438), True, 'import numpy as np\n'), ((2447, 2458), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (2455, 2458), True, 'import numpy as np\n'), ((2579, 2598), 'numpy.polyfit', 'np.polyfit', (['x', 'y', '(1)'], {}), '(x, y, 1)\n', (2589, 2598), True, 'import numpy as np\n'), ((2607, 2624), 'numpy.poly1d', 'np.poly1d', (['coeffs'], {}), '(coeffs)\n', (2616, 2624), True, 'import numpy as np\n'), ((2714, 2731), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {}), '(x, y)\n', (2725, 2731), True, 'import matplotlib.pyplot as plt\n'), ((2887, 2917), 'matplotlib.pyplot.title', 'plt.title', (['"""Linear Regression"""'], {}), "('Linear Regression')\n", (2896, 2917), True, 'import matplotlib.pyplot as plt\n'), ((2922, 2937), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x"""'], {}), "('x')\n", (2932, 2937), True, 'import matplotlib.pyplot as plt\n'), ((2942, 2957), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y"""'], {}), "('y')\n", (2952, 2957), True, 'import matplotlib.pyplot as plt\n'), ((2962, 2974), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2972, 2974), True, 'import matplotlib.pyplot as plt\n'), ((3897, 3908), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (3905, 3908), True, 'import numpy as np\n'), ((3917, 3928), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (3925, 3928), True, 'import numpy as np\n'), ((4060, 4075), 'scipy.stats.ttest_rel', 'ttest_rel', (['x', 'y'], {}), '(x, y)\n', (4069, 4075), False, 'from scipy.stats import pearsonr, ttest_rel, ttest_ind\n'), ((5085, 5096), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (5093, 5096), True, 'import numpy as np\n'), ((5105, 5116), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (5113, 5116), True, 'import numpy as np\n'), ((5248, 5263), 'scipy.stats.ttest_ind', 'ttest_ind', (['x', 'y'], {}), '(x, y)\n', (5257, 5263), False, 'from scipy.stats import pearsonr, ttest_rel, ttest_ind\n')]
# Copyright 2020 The FastEstimator Authors. All Rights Reserved. # # 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 unittest import numpy as np import tensorflow as tf import torch import fastestimator as fe from fastestimator.test.unittest_util import is_equal class TestPercentile(unittest.TestCase): def test_percentile_tf_input_axis_none(self): with self.subTest("even_elements"): t = tf.constant([1, 2]) obj1 = fe.backend.percentile(t, percentiles=50) obj2 = tf.constant([1]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("two_dimensional"): t = tf.constant([[1, 3, 9], [2, 7, 5], [8, 4, 6]]) obj1 = fe.backend.percentile(t, percentiles=50) obj2 = tf.constant([[5]]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_percentile"): obj1 = fe.backend.percentile(t, percentiles=[0, 50]) obj2 = tf.constant([[[1]], [[5]]]) self.assertTrue(is_equal(obj1, obj2)) def test_percentile_tf_input_axis_not_none(self): with self.subTest("two_dimensional"): t = tf.constant([[1, 3, 9], [2, 7, 5], [8, 4, 6]]) obj1 = fe.backend.percentile(t, percentiles=50, axis=0) obj2 = tf.constant([[2, 4, 6]]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("single_axis"): obj1 = fe.backend.percentile(t, percentiles=50, axis=1) obj2 = tf.constant([[3], [5], [6]]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_axis"): obj1 = fe.backend.percentile(t, percentiles=50, axis=[0, 1]) obj2 = tf.constant([[5]]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_percentile"): obj1 = fe.backend.percentile(t, percentiles=[0, 50], axis=[0, 1]) obj2 = tf.constant([[[1]], [[5]]]) self.assertTrue(is_equal(obj1, obj2)) def test_percentile_tf_input_axis_not_none_keepdims_false(self): with self.subTest("two_dimensional"): t = tf.constant([[1, 3, 9], [2, 7, 5], [8, 4, 6]]) obj1 = fe.backend.percentile(t, percentiles=50, axis=0, keepdims=False) obj2 = tf.constant([2, 4, 6]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("single_axis"): obj1 = fe.backend.percentile(t, percentiles=50, axis=1, keepdims=False) obj2 = tf.constant([3, 5, 6]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_axis"): obj1 = fe.backend.percentile(t, percentiles=50, axis=[0, 1], keepdims=False) obj2 = tf.constant(5) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_percentile"): obj1 = fe.backend.percentile(t, percentiles=[0, 50], axis=[0, 1], keepdims=False) obj2 = tf.constant([1, 5]) self.assertTrue(is_equal(obj1, obj2)) # ------------------------- torch input -------------------------------------- def test_percentile_torch_input_axis_none(self): with self.subTest("even_elements"): t = torch.tensor([1, 2]) obj1 = fe.backend.percentile(t, percentiles=50) obj2 = torch.tensor([1]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("two_dimensional"): t = torch.tensor([[1, 3, 9], [2, 7, 5], [8, 4, 6]]) obj1 = fe.backend.percentile(t, percentiles=50) obj2 = torch.tensor([[5]]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_percentile"): obj1 = fe.backend.percentile(t, percentiles=[0, 50]) obj2 = torch.tensor([[[1]], [[5]]]) self.assertTrue(is_equal(obj1, obj2)) def test_percentile_torch_input_axis_not_none(self): with self.subTest("two_dimensional"): t = torch.tensor([[1, 3, 9], [2, 7, 5], [8, 4, 6]]) obj1 = fe.backend.percentile(t, percentiles=50, axis=0) obj2 = torch.tensor([[2, 4, 6]]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("single_axis"): obj1 = fe.backend.percentile(t, percentiles=50, axis=1) obj2 = torch.tensor([[3], [5], [6]]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_axis"): obj1 = fe.backend.percentile(t, percentiles=50, axis=[0, 1]) obj2 = torch.tensor([[5]]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_percentile"): obj1 = fe.backend.percentile(t, percentiles=[0, 50], axis=[0, 1]) obj2 = torch.tensor([[[1]], [[5]]]) self.assertTrue(is_equal(obj1, obj2)) def test_percentile_torch_input_axis_not_none_keepdims_false(self): with self.subTest("two_dimensional"): t = torch.tensor([[1, 3, 9], [2, 7, 5], [8, 4, 6]]) obj1 = fe.backend.percentile(t, percentiles=50, axis=0, keepdims=False) obj2 = torch.tensor([2, 4, 6]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("single_axis"): obj1 = fe.backend.percentile(t, percentiles=50, axis=1, keepdims=False) obj2 = torch.tensor([3, 5, 6]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_axis"): obj1 = fe.backend.percentile(t, percentiles=50, axis=[0, 1], keepdims=False) obj2 = torch.tensor(5) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_percentile"): obj1 = fe.backend.percentile(t, percentiles=[0, 50], axis=[0, 1], keepdims=False) obj2 = torch.tensor([1, 5]) self.assertTrue(is_equal(obj1, obj2)) # ------------------------- numpy input --------------------------------------- def test_percentile_np_input_axis_none(self): with self.subTest("even_elements"): n = np.array([1, 2]) obj1 = fe.backend.percentile(n, percentiles=50) obj2 = np.array([1]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("two_dimensional"): n = np.array([[1, 3, 9], [2, 7, 5], [8, 4, 6]]) obj1 = fe.backend.percentile(n, percentiles=50) obj2 = np.array([[5]]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_percentile"): obj1 = fe.backend.percentile(n, percentiles=[0, 50]) obj2 = np.array([[[1]], [[5]]]) self.assertTrue(is_equal(obj1, obj2)) def test_percentile_np_input_axis_not_none(self): with self.subTest("two_dimensional"): n = np.array([[1, 3, 9], [2, 7, 5], [8, 4, 6]]) obj1 = fe.backend.percentile(n, percentiles=50, axis=0) obj2 = np.array([[2, 4, 6]]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("single_axis"): obj1 = fe.backend.percentile(n, percentiles=50, axis=1) obj2 = np.array([[3], [5], [6]]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_axis"): obj1 = fe.backend.percentile(n, percentiles=50, axis=[0, 1]) obj2 = np.array([[5]]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_percentile"): obj1 = fe.backend.percentile(n, percentiles=[0, 50], axis=[0, 1]) obj2 = np.array([[[1]], [[5]]]) self.assertTrue(is_equal(obj1, obj2)) def test_percentile_np_input_axis_not_none_keepdims_false(self): with self.subTest("two_dimensional"): n = np.array([[1, 3, 9], [2, 7, 5], [8, 4, 6]]) obj1 = fe.backend.percentile(n, percentiles=50, axis=0, keepdims=False) obj2 = np.array([2, 4, 6]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("single_axis"): obj1 = fe.backend.percentile(n, percentiles=50, axis=1, keepdims=False) obj2 = np.array([3, 5, 6]) self.assertTrue(is_equal(obj1, obj2)) with self.subTest("multi_axis"): obj1 = fe.backend.percentile(n, percentiles=50, axis=[0, 1], keepdims=False) self.assertTrue(is_equal(obj1, 5, assert_type=False)) with self.subTest("multi_percentile"): obj1 = fe.backend.percentile(n, percentiles=[0, 50], axis=[0, 1], keepdims=False) obj2 = np.array([1, 5]) self.assertTrue(is_equal(obj1, obj2))
[ "fastestimator.test.unittest_util.is_equal", "numpy.array", "torch.tensor", "fastestimator.backend.percentile", "tensorflow.constant" ]
[((1000, 1019), 'tensorflow.constant', 'tf.constant', (['[1, 2]'], {}), '([1, 2])\n', (1011, 1019), True, 'import tensorflow as tf\n'), ((1039, 1079), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)'}), '(t, percentiles=50)\n', (1060, 1079), True, 'import fastestimator as fe\n'), ((1099, 1115), 'tensorflow.constant', 'tf.constant', (['[1]'], {}), '([1])\n', (1110, 1115), True, 'import tensorflow as tf\n'), ((1229, 1275), 'tensorflow.constant', 'tf.constant', (['[[1, 3, 9], [2, 7, 5], [8, 4, 6]]'], {}), '([[1, 3, 9], [2, 7, 5], [8, 4, 6]])\n', (1240, 1275), True, 'import tensorflow as tf\n'), ((1295, 1335), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)'}), '(t, percentiles=50)\n', (1316, 1335), True, 'import fastestimator as fe\n'), ((1355, 1373), 'tensorflow.constant', 'tf.constant', (['[[5]]'], {}), '([[5]])\n', (1366, 1373), True, 'import tensorflow as tf\n'), ((1491, 1536), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '[0, 50]'}), '(t, percentiles=[0, 50])\n', (1512, 1536), True, 'import fastestimator as fe\n'), ((1556, 1583), 'tensorflow.constant', 'tf.constant', (['[[[1]], [[5]]]'], {}), '([[[1]], [[5]]])\n', (1567, 1583), True, 'import tensorflow as tf\n'), ((1751, 1797), 'tensorflow.constant', 'tf.constant', (['[[1, 3, 9], [2, 7, 5], [8, 4, 6]]'], {}), '([[1, 3, 9], [2, 7, 5], [8, 4, 6]])\n', (1762, 1797), True, 'import tensorflow as tf\n'), ((1817, 1865), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)', 'axis': '(0)'}), '(t, percentiles=50, axis=0)\n', (1838, 1865), True, 'import fastestimator as fe\n'), ((1885, 1909), 'tensorflow.constant', 'tf.constant', (['[[2, 4, 6]]'], {}), '([[2, 4, 6]])\n', (1896, 1909), True, 'import tensorflow as tf\n'), ((2022, 2070), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)', 'axis': '(1)'}), '(t, percentiles=50, axis=1)\n', (2043, 2070), True, 'import fastestimator as fe\n'), ((2090, 2118), 'tensorflow.constant', 'tf.constant', (['[[3], [5], [6]]'], {}), '([[3], [5], [6]])\n', (2101, 2118), True, 'import tensorflow as tf\n'), ((2230, 2283), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)', 'axis': '[0, 1]'}), '(t, percentiles=50, axis=[0, 1])\n', (2251, 2283), True, 'import fastestimator as fe\n'), ((2303, 2321), 'tensorflow.constant', 'tf.constant', (['[[5]]'], {}), '([[5]])\n', (2314, 2321), True, 'import tensorflow as tf\n'), ((2439, 2497), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '[0, 50]', 'axis': '[0, 1]'}), '(t, percentiles=[0, 50], axis=[0, 1])\n', (2460, 2497), True, 'import fastestimator as fe\n'), ((2517, 2544), 'tensorflow.constant', 'tf.constant', (['[[[1]], [[5]]]'], {}), '([[[1]], [[5]]])\n', (2528, 2544), True, 'import tensorflow as tf\n'), ((2727, 2773), 'tensorflow.constant', 'tf.constant', (['[[1, 3, 9], [2, 7, 5], [8, 4, 6]]'], {}), '([[1, 3, 9], [2, 7, 5], [8, 4, 6]])\n', (2738, 2773), True, 'import tensorflow as tf\n'), ((2793, 2857), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)', 'axis': '(0)', 'keepdims': '(False)'}), '(t, percentiles=50, axis=0, keepdims=False)\n', (2814, 2857), True, 'import fastestimator as fe\n'), ((2877, 2899), 'tensorflow.constant', 'tf.constant', (['[2, 4, 6]'], {}), '([2, 4, 6])\n', (2888, 2899), True, 'import tensorflow as tf\n'), ((3012, 3076), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)', 'axis': '(1)', 'keepdims': '(False)'}), '(t, percentiles=50, axis=1, keepdims=False)\n', (3033, 3076), True, 'import fastestimator as fe\n'), ((3096, 3118), 'tensorflow.constant', 'tf.constant', (['[3, 5, 6]'], {}), '([3, 5, 6])\n', (3107, 3118), True, 'import tensorflow as tf\n'), ((3230, 3299), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)', 'axis': '[0, 1]', 'keepdims': '(False)'}), '(t, percentiles=50, axis=[0, 1], keepdims=False)\n', (3251, 3299), True, 'import fastestimator as fe\n'), ((3319, 3333), 'tensorflow.constant', 'tf.constant', (['(5)'], {}), '(5)\n', (3330, 3333), True, 'import tensorflow as tf\n'), ((3451, 3525), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '[0, 50]', 'axis': '[0, 1]', 'keepdims': '(False)'}), '(t, percentiles=[0, 50], axis=[0, 1], keepdims=False)\n', (3472, 3525), True, 'import fastestimator as fe\n'), ((3545, 3564), 'tensorflow.constant', 'tf.constant', (['[1, 5]'], {}), '([1, 5])\n', (3556, 3564), True, 'import tensorflow as tf\n'), ((3812, 3832), 'torch.tensor', 'torch.tensor', (['[1, 2]'], {}), '([1, 2])\n', (3824, 3832), False, 'import torch\n'), ((3852, 3892), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)'}), '(t, percentiles=50)\n', (3873, 3892), True, 'import fastestimator as fe\n'), ((3912, 3929), 'torch.tensor', 'torch.tensor', (['[1]'], {}), '([1])\n', (3924, 3929), False, 'import torch\n'), ((4043, 4090), 'torch.tensor', 'torch.tensor', (['[[1, 3, 9], [2, 7, 5], [8, 4, 6]]'], {}), '([[1, 3, 9], [2, 7, 5], [8, 4, 6]])\n', (4055, 4090), False, 'import torch\n'), ((4110, 4150), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)'}), '(t, percentiles=50)\n', (4131, 4150), True, 'import fastestimator as fe\n'), ((4170, 4189), 'torch.tensor', 'torch.tensor', (['[[5]]'], {}), '([[5]])\n', (4182, 4189), False, 'import torch\n'), ((4307, 4352), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '[0, 50]'}), '(t, percentiles=[0, 50])\n', (4328, 4352), True, 'import fastestimator as fe\n'), ((4372, 4400), 'torch.tensor', 'torch.tensor', (['[[[1]], [[5]]]'], {}), '([[[1]], [[5]]])\n', (4384, 4400), False, 'import torch\n'), ((4571, 4618), 'torch.tensor', 'torch.tensor', (['[[1, 3, 9], [2, 7, 5], [8, 4, 6]]'], {}), '([[1, 3, 9], [2, 7, 5], [8, 4, 6]])\n', (4583, 4618), False, 'import torch\n'), ((4638, 4686), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)', 'axis': '(0)'}), '(t, percentiles=50, axis=0)\n', (4659, 4686), True, 'import fastestimator as fe\n'), ((4706, 4731), 'torch.tensor', 'torch.tensor', (['[[2, 4, 6]]'], {}), '([[2, 4, 6]])\n', (4718, 4731), False, 'import torch\n'), ((4844, 4892), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)', 'axis': '(1)'}), '(t, percentiles=50, axis=1)\n', (4865, 4892), True, 'import fastestimator as fe\n'), ((4912, 4941), 'torch.tensor', 'torch.tensor', (['[[3], [5], [6]]'], {}), '([[3], [5], [6]])\n', (4924, 4941), False, 'import torch\n'), ((5053, 5106), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)', 'axis': '[0, 1]'}), '(t, percentiles=50, axis=[0, 1])\n', (5074, 5106), True, 'import fastestimator as fe\n'), ((5126, 5145), 'torch.tensor', 'torch.tensor', (['[[5]]'], {}), '([[5]])\n', (5138, 5145), False, 'import torch\n'), ((5263, 5321), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '[0, 50]', 'axis': '[0, 1]'}), '(t, percentiles=[0, 50], axis=[0, 1])\n', (5284, 5321), True, 'import fastestimator as fe\n'), ((5341, 5369), 'torch.tensor', 'torch.tensor', (['[[[1]], [[5]]]'], {}), '([[[1]], [[5]]])\n', (5353, 5369), False, 'import torch\n'), ((5555, 5602), 'torch.tensor', 'torch.tensor', (['[[1, 3, 9], [2, 7, 5], [8, 4, 6]]'], {}), '([[1, 3, 9], [2, 7, 5], [8, 4, 6]])\n', (5567, 5602), False, 'import torch\n'), ((5622, 5686), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)', 'axis': '(0)', 'keepdims': '(False)'}), '(t, percentiles=50, axis=0, keepdims=False)\n', (5643, 5686), True, 'import fastestimator as fe\n'), ((5706, 5729), 'torch.tensor', 'torch.tensor', (['[2, 4, 6]'], {}), '([2, 4, 6])\n', (5718, 5729), False, 'import torch\n'), ((5842, 5906), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)', 'axis': '(1)', 'keepdims': '(False)'}), '(t, percentiles=50, axis=1, keepdims=False)\n', (5863, 5906), True, 'import fastestimator as fe\n'), ((5926, 5949), 'torch.tensor', 'torch.tensor', (['[3, 5, 6]'], {}), '([3, 5, 6])\n', (5938, 5949), False, 'import torch\n'), ((6061, 6130), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '(50)', 'axis': '[0, 1]', 'keepdims': '(False)'}), '(t, percentiles=50, axis=[0, 1], keepdims=False)\n', (6082, 6130), True, 'import fastestimator as fe\n'), ((6150, 6165), 'torch.tensor', 'torch.tensor', (['(5)'], {}), '(5)\n', (6162, 6165), False, 'import torch\n'), ((6283, 6357), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['t'], {'percentiles': '[0, 50]', 'axis': '[0, 1]', 'keepdims': '(False)'}), '(t, percentiles=[0, 50], axis=[0, 1], keepdims=False)\n', (6304, 6357), True, 'import fastestimator as fe\n'), ((6377, 6397), 'torch.tensor', 'torch.tensor', (['[1, 5]'], {}), '([1, 5])\n', (6389, 6397), False, 'import torch\n'), ((6643, 6659), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (6651, 6659), True, 'import numpy as np\n'), ((6679, 6719), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['n'], {'percentiles': '(50)'}), '(n, percentiles=50)\n', (6700, 6719), True, 'import fastestimator as fe\n'), ((6739, 6752), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (6747, 6752), True, 'import numpy as np\n'), ((6866, 6909), 'numpy.array', 'np.array', (['[[1, 3, 9], [2, 7, 5], [8, 4, 6]]'], {}), '([[1, 3, 9], [2, 7, 5], [8, 4, 6]])\n', (6874, 6909), True, 'import numpy as np\n'), ((6929, 6969), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['n'], {'percentiles': '(50)'}), '(n, percentiles=50)\n', (6950, 6969), True, 'import fastestimator as fe\n'), ((6989, 7004), 'numpy.array', 'np.array', (['[[5]]'], {}), '([[5]])\n', (6997, 7004), True, 'import numpy as np\n'), ((7122, 7167), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['n'], {'percentiles': '[0, 50]'}), '(n, percentiles=[0, 50])\n', (7143, 7167), True, 'import fastestimator as fe\n'), ((7187, 7211), 'numpy.array', 'np.array', (['[[[1]], [[5]]]'], {}), '([[[1]], [[5]]])\n', (7195, 7211), True, 'import numpy as np\n'), ((7379, 7422), 'numpy.array', 'np.array', (['[[1, 3, 9], [2, 7, 5], [8, 4, 6]]'], {}), '([[1, 3, 9], [2, 7, 5], [8, 4, 6]])\n', (7387, 7422), True, 'import numpy as np\n'), ((7442, 7490), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['n'], {'percentiles': '(50)', 'axis': '(0)'}), '(n, percentiles=50, axis=0)\n', (7463, 7490), True, 'import fastestimator as fe\n'), ((7510, 7531), 'numpy.array', 'np.array', (['[[2, 4, 6]]'], {}), '([[2, 4, 6]])\n', (7518, 7531), True, 'import numpy as np\n'), ((7644, 7692), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['n'], {'percentiles': '(50)', 'axis': '(1)'}), '(n, percentiles=50, axis=1)\n', (7665, 7692), True, 'import fastestimator as fe\n'), ((7712, 7737), 'numpy.array', 'np.array', (['[[3], [5], [6]]'], {}), '([[3], [5], [6]])\n', (7720, 7737), True, 'import numpy as np\n'), ((7849, 7902), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['n'], {'percentiles': '(50)', 'axis': '[0, 1]'}), '(n, percentiles=50, axis=[0, 1])\n', (7870, 7902), True, 'import fastestimator as fe\n'), ((7922, 7937), 'numpy.array', 'np.array', (['[[5]]'], {}), '([[5]])\n', (7930, 7937), True, 'import numpy as np\n'), ((8055, 8113), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['n'], {'percentiles': '[0, 50]', 'axis': '[0, 1]'}), '(n, percentiles=[0, 50], axis=[0, 1])\n', (8076, 8113), True, 'import fastestimator as fe\n'), ((8133, 8157), 'numpy.array', 'np.array', (['[[[1]], [[5]]]'], {}), '([[[1]], [[5]]])\n', (8141, 8157), True, 'import numpy as np\n'), ((8340, 8383), 'numpy.array', 'np.array', (['[[1, 3, 9], [2, 7, 5], [8, 4, 6]]'], {}), '([[1, 3, 9], [2, 7, 5], [8, 4, 6]])\n', (8348, 8383), True, 'import numpy as np\n'), ((8403, 8467), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['n'], {'percentiles': '(50)', 'axis': '(0)', 'keepdims': '(False)'}), '(n, percentiles=50, axis=0, keepdims=False)\n', (8424, 8467), True, 'import fastestimator as fe\n'), ((8487, 8506), 'numpy.array', 'np.array', (['[2, 4, 6]'], {}), '([2, 4, 6])\n', (8495, 8506), True, 'import numpy as np\n'), ((8619, 8683), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['n'], {'percentiles': '(50)', 'axis': '(1)', 'keepdims': '(False)'}), '(n, percentiles=50, axis=1, keepdims=False)\n', (8640, 8683), True, 'import fastestimator as fe\n'), ((8703, 8722), 'numpy.array', 'np.array', (['[3, 5, 6]'], {}), '([3, 5, 6])\n', (8711, 8722), True, 'import numpy as np\n'), ((8834, 8903), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['n'], {'percentiles': '(50)', 'axis': '[0, 1]', 'keepdims': '(False)'}), '(n, percentiles=50, axis=[0, 1], keepdims=False)\n', (8855, 8903), True, 'import fastestimator as fe\n'), ((9037, 9111), 'fastestimator.backend.percentile', 'fe.backend.percentile', (['n'], {'percentiles': '[0, 50]', 'axis': '[0, 1]', 'keepdims': '(False)'}), '(n, percentiles=[0, 50], axis=[0, 1], keepdims=False)\n', (9058, 9111), True, 'import fastestimator as fe\n'), ((9131, 9147), 'numpy.array', 'np.array', (['[1, 5]'], {}), '([1, 5])\n', (9139, 9147), True, 'import numpy as np\n'), ((1144, 1164), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (1152, 1164), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((1402, 1422), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (1410, 1422), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((1612, 1632), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (1620, 1632), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((1938, 1958), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (1946, 1958), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((2147, 2167), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (2155, 2167), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((2350, 2370), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (2358, 2370), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((2573, 2593), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (2581, 2593), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((2928, 2948), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (2936, 2948), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((3147, 3167), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (3155, 3167), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((3362, 3382), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (3370, 3382), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((3593, 3613), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (3601, 3613), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((3958, 3978), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (3966, 3978), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((4218, 4238), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (4226, 4238), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((4429, 4449), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (4437, 4449), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((4760, 4780), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (4768, 4780), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((4970, 4990), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (4978, 4990), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((5174, 5194), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (5182, 5194), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((5398, 5418), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (5406, 5418), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((5758, 5778), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (5766, 5778), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((5978, 5998), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (5986, 5998), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((6194, 6214), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (6202, 6214), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((6426, 6446), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (6434, 6446), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((6781, 6801), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (6789, 6801), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((7033, 7053), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (7041, 7053), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((7240, 7260), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (7248, 7260), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((7560, 7580), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (7568, 7580), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((7766, 7786), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (7774, 7786), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((7966, 7986), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (7974, 7986), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((8186, 8206), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (8194, 8206), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((8535, 8555), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (8543, 8555), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((8751, 8771), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (8759, 8771), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((8932, 8968), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', '(5)'], {'assert_type': '(False)'}), '(obj1, 5, assert_type=False)\n', (8940, 8968), False, 'from fastestimator.test.unittest_util import is_equal\n'), ((9176, 9196), 'fastestimator.test.unittest_util.is_equal', 'is_equal', (['obj1', 'obj2'], {}), '(obj1, obj2)\n', (9184, 9196), False, 'from fastestimator.test.unittest_util import is_equal\n')]
""" This simple sensor-network environment consists of a few parts: - The node-graph to explore. - Each node has a 'name' vector for directing the traversal, and the node's resource amount (never less than 0). - Each node has directed edges to a few neighbors. - Nodes mostly form a tree, sometimes with random edges, to increase path length. - Nodes usually link back to the starting node, to make sabotaging exploration likely. - Agents that explore nodes. - One agent starts at the starting node. - Each agent knows its current position (a node), the agent's resource amount, and whether consuming resources gives it reward. - Each agent loses some of its resource each step, which is given to some random node. Total resources are always preserved. - Observations: - Agent resource & hunger-ness. - Node resource. - Node 'name'. - All neighbor 'names'. - (`sensornet`'s cell shape should reserve 3 name-parts.) - Actions: - Take resources from the node for ourselves. - Fork. Possibly into an agent that hungers. - Go to a neighbor. 'Which neighbor' is the nearest-neighbor of the received data in node-neighbor 'names'. - Un-fork. Kick the bucket. Bite the dust. If all agents meet their maker, the world resets. - The world can end at each step if chosen, just to make exploration more difficult. Reset with `.reset(**options)` (see `.options` for what can be changed, which is quite a lot), read the desired metric with `.explored()` (0…1). Don't overfit to this metric, this is *exploration*, not *reward*. """ def reset(**opts): """Destroys and recreates the world.""" options.update(default_options) options.update(opts) metrics['nodes'], metrics['explored'], metrics['collected'] = 0, 0, 0 nodes.clear() for name in agents.keys(): agents[name][0].cancel() agents.clear() if not options['stop']: nodes['start'] = _random_name() _create_nodes(nodes['start']) options['please_make_an_agent'] = True metrics['nodes'] = len(nodes['all']) def explored(): return metrics['explored'] / metrics['nodes'] def reachable(): return _reachable(*[agents[a][1] for a in agents.keys()]) # In case `sensornet` is not installed as a package. import sys try: sn = sys.modules['sensornet'] except KeyError: raise ImportError('Please `import sensornet` first') from None options = {} default_options = { # Kill-switch. 'stop': False, # The graph to explore. 'max_nodes': 1000, 'node_name_size': 16, 'child_probabilities': {1:.7, 2:.1, 3:.1, 4:.1}, 'loopback_to_start_probability': .75, 'loopback_to_parent_probability': .25, 'random_connection_probability': .03, 'avg_resource': .1, # The actual initial resource in a node is 0…avg_resource*2. # The top-level-action options. 'can_reset_the_world': True, # If checked, each step has a 50% chance of resetting the world, which only adds to exploration. # Agents that act on the graph. 'max_agents': 16, # 1 to disallow forking. 'allow_suicide': True, # Look at all this proof-of-exploration opportunity. 'allow_fork_with_resource_goal': True, # Exploration that can choose to maximize. 'step_takes_resources': .01, # The resource is moved to a random node, so total resources are conserved. 'resource_consumption_speed': .1, # Verbose output. 'debug': False, } metrics = { 'nodes':0, 'explored':0, 'collected':0, } nodes = { 'all': [], # Node IDs, for random sampling. 'start': '', # Node ID to `[neighbor_ids, name_vec, resource, visited]`. } agents = { # Agent ID (randomly-generated) to `[task, at, resource, hunger]`: # `.cancel()`able task, node ID, 0…1 resource, bool of whether resource-consumption is reward. } import random import asyncio import numpy as np def agent(sn, at=..., resource=1., hunger=False): """Creates an agent, two-way-bound to wander the graph.""" if at is ...: at = nodes['start'] name = _random_name() async def loop(): reward = 0. while name in agents: _, at, resource, hunger = agents[name] neighbors, at_name_vec, at_resource, at_visited = nodes[at] # Keep track of exploration. if not at_visited: nodes[at][3] = True metrics['explored'] += 1 # Send observations. sn.data(name=(name, at, 'agent resource'), data=np.array([resource*2-1, 1. if hunger else -1.]), reward=reward) sn.data(name=(at, 'node resource'), data=np.array([at_resource*2-1]), reward=reward) sn.data(name=(at, 'name_vec'), data=at_name_vec, reward=reward) for i, ng in enumerate(neighbors): sn.data(name=(at, ng, 'neighbor '+str(i)), data=nodes[ng][1], reward=reward) reward = 0. # Receive actions. actions = 4 act = await sn.query(name=(name, at, 'act'), query = options['node_name_size'] + actions) if act is None: continue # Re-send observations on dropped packets. data, acts = act[:-actions], act[-actions:] # Bleed onto a random node. Die if unfortunate. dresource = min(options['step_takes_resources'], resource) resource -= dresource nodes[random.choice(nodes['all'])][2] += dresource at_resource = nodes[at][2] if options['debug']: print('agent tick', name, 'at', at[:8], 'with', len(neighbors), 'neighbors') if resource <= 0: if options['debug']: print('agent DIED', name) del agents[name] break agents[name][2] = resource # Take resources from the cell. if acts[0]>0 and at_resource > 0.: dresource = min(options['resource_consumption_speed'], at_resource, 1. - resource) resource += dresource; agents[name][2] = resource at_resource -= dresource; nodes[at][2] = at_resource if hunger: reward = dresource if options['debug']: print(' agent drew resources at', at[:8]) # Fork. (Casually, as if you see action-space-alteration in RL often.) if acts[1]>0 and len(agents.keys()) < options['max_agents']: ours = .5 agent(sn, at, resource*(1-ours), options['allow_fork_with_resource_goal'] and data[0]>0) resource *= ours; agents[name][2] = resource if options['debug']: print(' agent forked at', at[:8]) # Goto neighbor. if acts[2]>0 and len(neighbors): diffs = data - np.stack([nodes[ng][1] for ng in neighbors]) nearest_neighbor_i = np.argmin(np.sum(np.abs(diffs), -1)) prev_at = at at = neighbors[nearest_neighbor_i] agents[name][1] = at if options['debug']: print(' agent goes to neighbor', prev_at[:8], '→', at[:8], '('+str(nearest_neighbor_i)+'/'+str(len(neighbors))+')') # Un-fork. if acts[3]>0 and options['allow_suicide']: if options['debug']: print(' agent UNFORKED') nodes[at][2] += resource del agents[name] break if not agents: reset(**options) agent(sn) agents[name] = [asyncio.ensure_future(loop()), at, resource, hunger] return name def _random_name(): return ''.join([random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ') for _ in range(16)]) def _create_nodes(start_id): """Creates the node tree-like graph with loopback connections (which decrease the probability of successful exploration) in `nodes`.""" ids = [start_id] nodes['all'] = [] prob = random.random def new_node(parent_id, id = None): if id is None: id = _random_name() if parent_id is not None: nodes[parent_id][0].append(id) # Parents know about children. neighbors = [] if prob() < options['loopback_to_start_probability']: neighbors.append(start_id) if prob() < options['loopback_to_parent_probability'] and parent_id is not None: neighbors.append(parent_id) if prob() < options['random_connection_probability']*.5 and len(nodes['all']): neighbors.append(random.choice(nodes['all'])) if prob() < options['random_connection_probability']*.5 and len(nodes['all']): nodes[random.choice(nodes['all'])][0].append(id) nodes[id] = [ neighbors, np.random.rand(options['node_name_size']), random.uniform(0, options['avg_resource']), False, ] nodes['all'].append(id) ids.append(id) new_node(None, start_id) children_prob_sum = sum(options['child_probabilities'].values()) while len(ids) and len(nodes['all']) < options['max_nodes']: # Take a random id from `ids`, then create children. i = random.randrange(len(ids)) ids[i], ids[-1] = ids[-1], ids[i] id, children = ids.pop(), 0 # Pick the child-count, and create children. p = prob() * children_prob_sum for ch in options['child_probabilities'].keys(): p -= options['child_probabilities'][ch] if p < 0: children = ch break for _ in range(children): if len(nodes['all']) < options['max_nodes']: new_node(id) # Note: we're cutting off at `max_nodes`, so there's a chance for some nodes to have no neighbors and be inescapable black holes. # It's a feature, since this gives a reason for forking to exist. def _reachable(*node_names): stack, visited = list(node_names), set(node_names) while len(stack): name = stack.pop() neighbors = nodes[name][0] for ng in neighbors: if ng not in visited: stack.append(ng) visited.add(ng) return len(visited) / len(nodes['all']) def _maybe_reset_the_world(fb): if fb is not None and (fb[0] > 0).all(): if options['debug']: print('world resets', fb is not None and fb[0]) reset(**options) else: if options['debug']: print('world continues', fb is not None and fb[0], 'agents', list(agents.keys())) def _top_level_actions(sn): if options['can_reset_the_world']: sn.query(name=('world', 'reset'), query=sn.cell_shape[-1], callback=_maybe_reset_the_world) if not options['stop'] and not agents and options['please_make_an_agent']: agent(sn) options['please_make_an_agent'] = False # If you really need many environments, launch many processes, and enjoy the benefits of actual parallelism. reset() sn.sensors.append(_top_level_actions)
[ "numpy.abs", "random.uniform", "random.choice", "numpy.random.rand", "numpy.array", "numpy.stack" ]
[((7623, 7666), 'random.choice', 'random.choice', (['"""ABCDEFGHIJKLMNOPQRSTUVWXYZ"""'], {}), "('ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n", (7636, 7666), False, 'import random\n'), ((8695, 8736), 'numpy.random.rand', 'np.random.rand', (["options['node_name_size']"], {}), "(options['node_name_size'])\n", (8709, 8736), True, 'import numpy as np\n'), ((8750, 8792), 'random.uniform', 'random.uniform', (['(0)', "options['avg_resource']"], {}), "(0, options['avg_resource'])\n", (8764, 8792), False, 'import random\n'), ((8461, 8488), 'random.choice', 'random.choice', (["nodes['all']"], {}), "(nodes['all'])\n", (8474, 8488), False, 'import random\n'), ((4545, 4598), 'numpy.array', 'np.array', (['[resource * 2 - 1, 1.0 if hunger else -1.0]'], {}), '([resource * 2 - 1, 1.0 if hunger else -1.0])\n', (4553, 4598), True, 'import numpy as np\n'), ((4662, 4693), 'numpy.array', 'np.array', (['[at_resource * 2 - 1]'], {}), '([at_resource * 2 - 1])\n', (4670, 4693), True, 'import numpy as np\n'), ((5422, 5449), 'random.choice', 'random.choice', (["nodes['all']"], {}), "(nodes['all'])\n", (5435, 5449), False, 'import random\n'), ((6786, 6830), 'numpy.stack', 'np.stack', (['[nodes[ng][1] for ng in neighbors]'], {}), '([nodes[ng][1] for ng in neighbors])\n', (6794, 6830), True, 'import numpy as np\n'), ((6885, 6898), 'numpy.abs', 'np.abs', (['diffs'], {}), '(diffs)\n', (6891, 6898), True, 'import numpy as np\n'), ((8595, 8622), 'random.choice', 'random.choice', (["nodes['all']"], {}), "(nodes['all'])\n", (8608, 8622), False, 'import random\n')]
# -*- coding: utf-8 -*- from torch.nn import functional as F import torch.nn as nn from PIL import Image import numpy as np from skimage.io import imsave import cv2 import torch.nn as nn import torch from torch.autograd import Variable from torchvision import models from collections import namedtuple import pdb import copy import time import random import asyncio import aiohttp import async_timeout # *************************************************** # Image gradients calculator by the Laplacian filters # *************************************************** def laplacian_filter_tensor(img_tensor, gpu_id): """ :param img_tensor: input image tensor (B, C, H, W) :param gpu_id: obj to the inferring device, GPU or CPU :return: three channels of the obtained gradient tensor """ laplacian_filter = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]) laplacian_conv = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1, bias=False) laplacian_conv.weight = nn.Parameter( torch.from_numpy(laplacian_filter).float().unsqueeze(0).unsqueeze(0).to(gpu_id)) for param in laplacian_conv.parameters(): param.requires_grad = False red_img_tensor = img_tensor[:, 0, :, :].unsqueeze(1) green_img_tensor = img_tensor[:, 1, :, :].unsqueeze(1) blue_img_tensor = img_tensor[:, 2, :, :].unsqueeze(1) red_gradient_tensor = laplacian_conv(red_img_tensor).squeeze(1) green_gradient_tensor = laplacian_conv(green_img_tensor).squeeze(1) blue_gradient_tensor = laplacian_conv(blue_img_tensor).squeeze(1) return red_gradient_tensor, green_gradient_tensor, blue_gradient_tensor def numpy2tensor(np_array, gpu_id): if len(np_array.shape) == 2: tensor = torch.from_numpy(np_array).unsqueeze(0).float().to(gpu_id) else: tensor = torch.from_numpy(np_array).unsqueeze(0).transpose(1, 3).transpose(2, 3).float().to(gpu_id) return tensor def compute_gt_gradient(x_start, y_start, source_img, target_img, mask, gpu_id): # compute source image gradient source_img_tensor = torch.from_numpy(source_img).unsqueeze(0).transpose(1, 3).transpose(2, 3).float().to(gpu_id) red_source_gradient_tensor, green_source_gradient_tensor, blue_source_gradient_tenosr \ = laplacian_filter_tensor(source_img_tensor, gpu_id) red_source_gradient = red_source_gradient_tensor.cpu().data.numpy()[0] green_source_gradient = green_source_gradient_tensor.cpu().data.numpy()[0] blue_source_gradient = blue_source_gradient_tenosr.cpu().data.numpy()[0] # compute target image gradient target_img_tensor = torch.from_numpy(target_img).unsqueeze(0).transpose(1, 3).transpose(2, 3).float().to(gpu_id) red_target_gradient_tensor, green_target_gradient_tensor, blue_target_gradient_tenosr \ = laplacian_filter_tensor(target_img_tensor, gpu_id) red_target_gradient = red_target_gradient_tensor.cpu().data.numpy()[0] green_target_gradient = green_target_gradient_tensor.cpu().data.numpy()[0] blue_target_gradient = blue_target_gradient_tenosr.cpu().data.numpy()[0] # mask and canvas mask canvas_mask = np.zeros((target_img.shape[0], target_img.shape[1])) canvas_mask[x_start:mask.shape[0], y_start:mask.shape[1]] = mask # foreground gradient red_source_gradient = red_source_gradient * mask green_source_gradient = green_source_gradient * mask blue_source_gradient = blue_source_gradient * mask red_foreground_gradient = np.zeros((canvas_mask.shape)) red_foreground_gradient[x_start:mask.shape[0], y_start:mask.shape[1]] = red_source_gradient green_foreground_gradient = np.zeros((canvas_mask.shape)) green_foreground_gradient[x_start:mask.shape[0], y_start:mask.shape[1]] = green_source_gradient blue_foreground_gradient = np.zeros((canvas_mask.shape)) blue_foreground_gradient[x_start:mask.shape[0], y_start:mask.shape[1]] = blue_source_gradient # background gradient red_background_gradient = red_target_gradient * (canvas_mask - 1) * (-1) green_background_gradient = green_target_gradient * (canvas_mask - 1) * (-1) blue_background_gradient = blue_target_gradient * (canvas_mask - 1) * (-1) # add up foreground and background gradient gt_red_gradient = red_foreground_gradient + red_background_gradient gt_green_gradient = green_foreground_gradient + green_background_gradient gt_blue_gradient = blue_foreground_gradient + blue_background_gradient gt_red_gradient = numpy2tensor(gt_red_gradient, gpu_id) gt_green_gradient = numpy2tensor(gt_green_gradient, gpu_id) gt_blue_gradient = numpy2tensor(gt_blue_gradient, gpu_id) gt_gradient = [gt_red_gradient, gt_green_gradient, gt_blue_gradient] return gt_gradient # **************************************** # VGG model for calculating the style loss # **************************************** class Vgg16(torch.nn.Module): def __init__(self, requires_grad=False): super(Vgg16, self).__init__() model = models.vgg16(pretrained=False) model.load_state_dict(torch.load('VGG_Model/vgg16.pth')) vgg_pretrained_features = model.features self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Sequential() self.slice3 = torch.nn.Sequential() self.slice4 = torch.nn.Sequential() for x in range(4): self.slice1.add_module(str(x), vgg_pretrained_features[x]) for x in range(4, 9): self.slice2.add_module(str(x), vgg_pretrained_features[x]) for x in range(9, 16): self.slice3.add_module(str(x), vgg_pretrained_features[x]) for x in range(16, 23): self.slice4.add_module(str(x), vgg_pretrained_features[x]) if not requires_grad: for param in self.parameters(): param.requires_grad = False def forward(self, X): h = self.slice1(X) h_relu1_2 = h h = self.slice2(h) h_relu2_2 = h h = self.slice3(h) h_relu3_3 = h h = self.slice4(h) h_relu4_3 = h vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3']) out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3) return out def gram_matrix(y): (b, ch, h, w) = y.size() features = y.view(b, ch, w * h) features_t = features.transpose(1, 2) gram = features.bmm(features_t) / (ch * h * w) return gram class MeanShift(nn.Conv2d): def __init__(self, gpu_id): super(MeanShift, self).__init__(3, 3, kernel_size=1) rgb_range = 1 rgb_mean = (0.4488, 0.4371, 0.4040) rgb_std = (1.0, 1.0, 1.0) sign = -1 std = torch.Tensor(rgb_std).to(gpu_id) self.weight.data = torch.eye(3).view(3, 3, 1, 1).to(gpu_id) / std.view(3, 1, 1, 1) self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean).to(gpu_id) / std for p in self.parameters(): p.requires_grad = False # ****************************** # Data reading and preprocessing # ****************************** def read_img_from_path(data_dir, img_path, mean, std, device): """ :param data_dir: parents folder to the input images data :param img_path: path to the aligned image :param mean: mean for image normalization :param std: std for image normalization :param device: obj to the inferring device, GPU or CPU :return: preprocessed image (B, C, H, W) with the type of tensor """ img = cv2.imread(data_dir + '/' + img_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255 img = torch.from_numpy(img).to(torch.float32).to(device) img = preprocess(img, mean, std, device) return img def preprocess(im, mean, std, device): if len(im.size()) == 3: im = im.transpose(0, 2).transpose(1, 2).unsqueeze(0) elif len(im.size()) == 4: im = im.transpose(1, 3).transpose(2, 3) mean = torch.tensor(mean).to(device) mean = mean.unsqueeze(0).unsqueeze(-1).unsqueeze(-1) std = torch.tensor(std).to(device) std = std.unsqueeze(0).unsqueeze(-1).unsqueeze(-1) im = (im - mean) / std return im
[ "collections.namedtuple", "torch.nn.Sequential", "torch.eye", "torch.load", "torch.Tensor", "torch.from_numpy", "torch.nn.Conv2d", "numpy.array", "numpy.zeros", "torch.tensor", "cv2.cvtColor", "torchvision.models.vgg16", "cv2.imread" ]
[((830, 877), 'numpy.array', 'np.array', (['[[0, -1, 0], [-1, 4, -1], [0, -1, 0]]'], {}), '([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])\n', (838, 877), True, 'import numpy as np\n'), ((899, 962), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1)', '(1)'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)', 'bias': '(False)'}), '(1, 1, kernel_size=3, stride=1, padding=1, bias=False)\n', (908, 962), True, 'import torch.nn as nn\n'), ((3126, 3178), 'numpy.zeros', 'np.zeros', (['(target_img.shape[0], target_img.shape[1])'], {}), '((target_img.shape[0], target_img.shape[1]))\n', (3134, 3178), True, 'import numpy as np\n'), ((3470, 3497), 'numpy.zeros', 'np.zeros', (['canvas_mask.shape'], {}), '(canvas_mask.shape)\n', (3478, 3497), True, 'import numpy as np\n'), ((3628, 3655), 'numpy.zeros', 'np.zeros', (['canvas_mask.shape'], {}), '(canvas_mask.shape)\n', (3636, 3655), True, 'import numpy as np\n'), ((3789, 3816), 'numpy.zeros', 'np.zeros', (['canvas_mask.shape'], {}), '(canvas_mask.shape)\n', (3797, 3816), True, 'import numpy as np\n'), ((7495, 7532), 'cv2.imread', 'cv2.imread', (["(data_dir + '/' + img_path)"], {}), "(data_dir + '/' + img_path)\n", (7505, 7532), False, 'import cv2\n'), ((4999, 5029), 'torchvision.models.vgg16', 'models.vgg16', ([], {'pretrained': '(False)'}), '(pretrained=False)\n', (5011, 5029), False, 'from torchvision import models\n'), ((5167, 5188), 'torch.nn.Sequential', 'torch.nn.Sequential', ([], {}), '()\n', (5186, 5188), False, 'import torch\n'), ((5211, 5232), 'torch.nn.Sequential', 'torch.nn.Sequential', ([], {}), '()\n', (5230, 5232), False, 'import torch\n'), ((5255, 5276), 'torch.nn.Sequential', 'torch.nn.Sequential', ([], {}), '()\n', (5274, 5276), False, 'import torch\n'), ((5299, 5320), 'torch.nn.Sequential', 'torch.nn.Sequential', ([], {}), '()\n', (5318, 5320), False, 'import torch\n'), ((6088, 6158), 'collections.namedtuple', 'namedtuple', (['"""VggOutputs"""', "['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3']"], {}), "('VggOutputs', ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3'])\n", (6098, 6158), False, 'from collections import namedtuple\n'), ((7543, 7579), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (7555, 7579), False, 'import cv2\n'), ((5060, 5093), 'torch.load', 'torch.load', (['"""VGG_Model/vgg16.pth"""'], {}), "('VGG_Model/vgg16.pth')\n", (5070, 5093), False, 'import torch\n'), ((7927, 7945), 'torch.tensor', 'torch.tensor', (['mean'], {}), '(mean)\n', (7939, 7945), False, 'import torch\n'), ((8024, 8041), 'torch.tensor', 'torch.tensor', (['std'], {}), '(std)\n', (8036, 8041), False, 'import torch\n'), ((6699, 6720), 'torch.Tensor', 'torch.Tensor', (['rgb_std'], {}), '(rgb_std)\n', (6711, 6720), False, 'import torch\n'), ((7596, 7617), 'torch.from_numpy', 'torch.from_numpy', (['img'], {}), '(img)\n', (7612, 7617), False, 'import torch\n'), ((6867, 6889), 'torch.Tensor', 'torch.Tensor', (['rgb_mean'], {}), '(rgb_mean)\n', (6879, 6889), False, 'import torch\n'), ((6759, 6771), 'torch.eye', 'torch.eye', (['(3)'], {}), '(3)\n', (6768, 6771), False, 'import torch\n'), ((1727, 1753), 'torch.from_numpy', 'torch.from_numpy', (['np_array'], {}), '(np_array)\n', (1743, 1753), False, 'import torch\n'), ((1013, 1047), 'torch.from_numpy', 'torch.from_numpy', (['laplacian_filter'], {}), '(laplacian_filter)\n', (1029, 1047), False, 'import torch\n'), ((2065, 2093), 'torch.from_numpy', 'torch.from_numpy', (['source_img'], {}), '(source_img)\n', (2081, 2093), False, 'import torch\n'), ((2603, 2631), 'torch.from_numpy', 'torch.from_numpy', (['target_img'], {}), '(target_img)\n', (2619, 2631), False, 'import torch\n'), ((1813, 1839), 'torch.from_numpy', 'torch.from_numpy', (['np_array'], {}), '(np_array)\n', (1829, 1839), False, 'import torch\n')]
# -*- coding: utf-8 -*- """ The :func:`ground_truth_normalizer()`, :func:`ground_truth_normalize_row` and :class:`TestLocalResponseNormalization2DLayer` implementations contain code from `pylearn2 <http://github.com/lisa-lab/pylearn2>`_, which is covered by the following license: Copyright (c) 2011--2014, Université de Montréal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder nor the names of its 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 THE COPYRIGHT HOLDER 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. """ from mock import Mock import numpy as np import pytest import theano def ground_truth_normalizer(c01b, k, n, alpha, beta): out = np.zeros(c01b.shape) for r in range(out.shape[1]): for c in range(out.shape[2]): for x in range(out.shape[3]): out[:, r, c, x] = ground_truth_normalize_row( row=c01b[:, r, c, x], k=k, n=n, alpha=alpha, beta=beta) return out def ground_truth_normalize_row(row, k, n, alpha, beta): assert row.ndim == 1 out = np.zeros(row.shape) for i in range(row.shape[0]): s = k tot = 0 for j in range(max(0, i-n//2), min(row.shape[0], i+n//2+1)): tot += 1 sq = row[j] ** 2. assert sq > 0. assert s >= k assert alpha > 0. s += alpha * sq assert s >= k assert tot <= n assert s >= k s = s ** beta out[i] = row[i] / s return out class TestLocalResponseNormalization2DLayer: @pytest.fixture def rng(self): return np.random.RandomState([2013, 2]) @pytest.fixture def input_data(self, rng): channels = 15 rows = 3 cols = 4 batch_size = 2 shape = (batch_size, channels, rows, cols) return rng.randn(*shape).astype(theano.config.floatX) @pytest.fixture def input_layer(self, input_data): from lasagne.layers.input import InputLayer shape = list(input_data.shape) shape[0] = None return InputLayer(shape) @pytest.fixture def layer(self, input_layer): from lasagne.layers.normalization import\ LocalResponseNormalization2DLayer layer = LocalResponseNormalization2DLayer(input_layer, alpha=1.5, k=2, beta=0.75, n=5) return layer def test_get_params(self, layer): assert layer.get_params() == [] def test_get_output_shape_for(self, layer): assert layer.get_output_shape_for((1, 2, 3, 4)) == (1, 2, 3, 4) def test_even_n_fails(self, input_layer): from lasagne.layers.normalization import\ LocalResponseNormalization2DLayer with pytest.raises(NotImplementedError): LocalResponseNormalization2DLayer(input_layer, n=4) def test_normalization(self, input_data, input_layer, layer): from lasagne.layers import get_output X = input_layer.input_var lrn = theano.function([X], get_output(layer, X)) out = lrn(input_data) # ground_truth_normalizer assumes c01b input_data_c01b = input_data.transpose([1, 2, 3, 0]) ground_out = ground_truth_normalizer(input_data_c01b, n=layer.n, k=layer.k, alpha=layer.alpha, beta=layer.beta) ground_out = np.transpose(ground_out, [3, 0, 1, 2]) assert out.shape == ground_out.shape assert np.allclose(out, ground_out) class TestBatchNormLayer: @pytest.fixture(params=(False, True), ids=('plain', 'dnn')) def BatchNormLayer(self, request): dnn = request.param if not dnn: from lasagne.layers.normalization import BatchNormLayer elif dnn: try: from lasagne.layers.dnn import ( BatchNormDNNLayer as BatchNormLayer) except ImportError: pytest.skip("cuDNN batch norm not available") return BatchNormLayer @pytest.fixture def init_unique(self): # initializer for a tensor of unique values return lambda shape: np.arange(np.prod(shape)).reshape(shape) def test_init(self, BatchNormLayer, init_unique): input_shape = (2, 3, 4) # default: normalize over all but second axis beta = BatchNormLayer(input_shape, beta=init_unique).beta assert np.allclose(beta.get_value(), init_unique((3,))) # normalize over first axis only beta = BatchNormLayer(input_shape, beta=init_unique, axes=0).beta assert np.allclose(beta.get_value(), init_unique((3, 4))) # normalize over second and third axis try: beta = BatchNormLayer( input_shape, beta=init_unique, axes=(1, 2)).beta assert np.allclose(beta.get_value(), init_unique((2,))) except ValueError as exc: assert "BatchNormDNNLayer only supports" in exc.args[0] @pytest.mark.parametrize('update_averages', [None, True, False]) @pytest.mark.parametrize('use_averages', [None, True, False]) @pytest.mark.parametrize('deterministic', [True, False]) def test_get_output_for(self, BatchNormLayer, deterministic, use_averages, update_averages): input_shape = (20, 30, 40) # random input tensor, beta, gamma, mean, inv_std and alpha input = (np.random.randn(*input_shape).astype(theano.config.floatX) + np.random.randn(1, 30, 1).astype(theano.config.floatX)) beta = np.random.randn(30).astype(theano.config.floatX) gamma = np.random.randn(30).astype(theano.config.floatX) mean = np.random.randn(30).astype(theano.config.floatX) inv_std = np.random.rand(30).astype(theano.config.floatX) alpha = np.random.rand() # create layer (with default axes: normalize over all but second axis) layer = BatchNormLayer(input_shape, beta=beta, gamma=gamma, mean=mean, inv_std=inv_std, alpha=alpha) # call get_output_for() kwargs = {'deterministic': deterministic} if use_averages is not None: kwargs['batch_norm_use_averages'] = use_averages else: use_averages = deterministic if update_averages is not None: kwargs['batch_norm_update_averages'] = update_averages else: update_averages = not deterministic result = layer.get_output_for(theano.tensor.constant(input), **kwargs).eval() # compute expected results and expected updated parameters input_mean = input.mean(axis=(0, 2)) input_inv_std = 1 / np.sqrt(input.var(axis=(0, 2)) + layer.epsilon) if use_averages: use_mean, use_inv_std = mean, inv_std else: use_mean, use_inv_std = input_mean, input_inv_std bcast = (np.newaxis, slice(None), np.newaxis) exp_result = (input - use_mean[bcast]) * use_inv_std[bcast] exp_result = exp_result * gamma[bcast] + beta[bcast] if update_averages: new_mean = (1 - alpha) * mean + alpha * input_mean new_inv_std = (1 - alpha) * inv_std + alpha * input_inv_std else: new_mean, new_inv_std = mean, inv_std # compare expected results to actual results tol = {'atol': 1e-5, 'rtol': 1e-6} assert np.allclose(layer.mean.get_value(), new_mean, **tol) assert np.allclose(layer.inv_std.get_value(), new_inv_std, **tol) assert np.allclose(result, exp_result, **tol) def test_undefined_shape(self, BatchNormLayer): # should work: BatchNormLayer((64, 2, None), axes=(0, 2)) # should not work: with pytest.raises(ValueError) as exc: BatchNormLayer((64, None, 3), axes=(0, 2)) assert 'needs specified input sizes' in exc.value.args[0] def test_skip_linear_transform(self, BatchNormLayer): input_shape = (20, 30, 40) # random input tensor, beta, gamma input = (np.random.randn(*input_shape).astype(theano.config.floatX) + np.random.randn(1, 30, 1).astype(theano.config.floatX)) beta = np.random.randn(30).astype(theano.config.floatX) gamma = np.random.randn(30).astype(theano.config.floatX) # create layers without beta or gamma layer1 = BatchNormLayer(input_shape, beta=None, gamma=gamma) layer2 = BatchNormLayer(input_shape, beta=beta, gamma=None) # check that one parameter is missing assert len(layer1.get_params()) == 3 assert len(layer2.get_params()) == 3 # call get_output_for() result1 = layer1.get_output_for(theano.tensor.constant(input), deterministic=False).eval() result2 = layer2.get_output_for(theano.tensor.constant(input), deterministic=False).eval() # compute expected results and expected updated parameters mean = input.mean(axis=(0, 2)) std = np.sqrt(input.var(axis=(0, 2)) + layer1.epsilon) exp_result = (input - mean[None, :, None]) / std[None, :, None] exp_result1 = exp_result * gamma[None, :, None] # no beta exp_result2 = exp_result + beta[None, :, None] # no gamma # compare expected results to actual results tol = {'atol': 1e-5, 'rtol': 1e-6} assert np.allclose(result1, exp_result1, **tol) assert np.allclose(result2, exp_result2, **tol) @pytest.mark.parametrize('dnn', [False, True]) def test_batch_norm_macro(dnn): if not dnn: from lasagne.layers import (BatchNormLayer, batch_norm) else: try: from lasagne.layers.dnn import ( BatchNormDNNLayer as BatchNormLayer, batch_norm_dnn as batch_norm) except ImportError: pytest.skip("cuDNN batch norm not available") from lasagne.layers import (Layer, NonlinearityLayer) from lasagne.nonlinearities import identity input_shape = (2, 3) obj = object() # check if it steals the nonlinearity layer = Mock(Layer, output_shapes=(input_shape, ), nonlinearity=obj) layer.name = None bnstack = batch_norm(layer) assert isinstance(bnstack, NonlinearityLayer) assert isinstance(bnstack.input_layers[0], BatchNormLayer) assert layer.nonlinearity is identity assert bnstack.nonlinearity is obj # check if it removes the bias layer = Mock(Layer, output_shapes=(input_shape, ), b=obj, params={obj: set()}) layer.name = None bnstack = batch_norm(layer) assert isinstance(bnstack, BatchNormLayer) assert layer.b is None assert obj not in layer.params # check if it can handle an unset bias layer = Mock(Layer, output_shapes=(input_shape, ), b=None, params={obj: set()}) layer.name = None bnstack = batch_norm(layer) assert isinstance(bnstack, BatchNormLayer) assert layer.b is None # check if it passes on kwargs layer = Mock(Layer, output_shapes=(input_shape, )) bnstack = batch_norm(layer, name='foo') assert isinstance(bnstack, BatchNormLayer) assert bnstack.name == 'foo' # check if created layers are named with kwargs name layer = Mock(Layer, output_shapes=(input_shape, ), nonlinearity=obj) layer.name = 'foo' bnstack = batch_norm(layer, name='foo_bnorm') assert isinstance(bnstack, NonlinearityLayer) assert isinstance(bnstack.input_layers[0], BatchNormLayer) assert bnstack.name == 'foo_bnorm_nonlin' assert bnstack.input_layers[0].name == 'foo_bnorm' # check if created layers are named with wrapped layer name layer = Mock(Layer, output_shapes=(input_shape, ), nonlinearity=obj) layer.name = 'foo' bnstack = batch_norm(layer) assert isinstance(bnstack, NonlinearityLayer) assert isinstance(bnstack.input_layers[0], BatchNormLayer) assert bnstack.name == 'foo_bn_nonlin' assert bnstack.input_layers[0].name == 'foo_bn' # check if created layers remain unnamed if no names are given layer = Mock(Layer, output_shapes=(input_shape, ), nonlinearity=obj) layer.name = None bnstack = batch_norm(layer) assert isinstance(bnstack, NonlinearityLayer) assert isinstance(bnstack.input_layers[0], BatchNormLayer) assert bnstack.name is "" assert bnstack.input_layers[0].name is ""
[ "numpy.prod", "theano.tensor.constant", "numpy.allclose", "lasagne.layers.input.InputLayer", "numpy.random.rand", "lasagne.layers.dnn.batch_norm_dnn", "mock.Mock", "lasagne.layers.dnn.BatchNormDNNLayer", "lasagne.layers.get_output", "pytest.mark.parametrize", "numpy.zeros", "lasagne.layers.nor...
[((11165, 11210), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dnn"""', '[False, True]'], {}), "('dnn', [False, True])\n", (11188, 11210), False, 'import pytest\n'), ((1940, 1960), 'numpy.zeros', 'np.zeros', (['c01b.shape'], {}), '(c01b.shape)\n', (1948, 1960), True, 'import numpy as np\n'), ((2350, 2369), 'numpy.zeros', 'np.zeros', (['row.shape'], {}), '(row.shape)\n', (2358, 2369), True, 'import numpy as np\n'), ((5105, 5163), 'pytest.fixture', 'pytest.fixture', ([], {'params': '(False, True)', 'ids': "('plain', 'dnn')"}), "(params=(False, True), ids=('plain', 'dnn'))\n", (5119, 5163), False, 'import pytest\n'), ((6550, 6613), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""update_averages"""', '[None, True, False]'], {}), "('update_averages', [None, True, False])\n", (6573, 6613), False, 'import pytest\n'), ((6619, 6679), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""use_averages"""', '[None, True, False]'], {}), "('use_averages', [None, True, False])\n", (6642, 6679), False, 'import pytest\n'), ((6685, 6740), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""deterministic"""', '[True, False]'], {}), "('deterministic', [True, False])\n", (6708, 6740), False, 'import pytest\n'), ((11789, 11848), 'mock.Mock', 'Mock', (['Layer'], {'output_shapes': '(input_shape,)', 'nonlinearity': 'obj'}), '(Layer, output_shapes=(input_shape,), nonlinearity=obj)\n', (11793, 11848), False, 'from mock import Mock\n'), ((11903, 11920), 'lasagne.layers.dnn.batch_norm_dnn', 'batch_norm', (['layer'], {}), '(layer)\n', (11913, 11920), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer, batch_norm_dnn as batch_norm\n'), ((12287, 12304), 'lasagne.layers.dnn.batch_norm_dnn', 'batch_norm', (['layer'], {}), '(layer)\n', (12297, 12304), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer, batch_norm_dnn as batch_norm\n'), ((12595, 12612), 'lasagne.layers.dnn.batch_norm_dnn', 'batch_norm', (['layer'], {}), '(layer)\n', (12605, 12612), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer, batch_norm_dnn as batch_norm\n'), ((12735, 12776), 'mock.Mock', 'Mock', (['Layer'], {'output_shapes': '(input_shape,)'}), '(Layer, output_shapes=(input_shape,))\n', (12739, 12776), False, 'from mock import Mock\n'), ((12792, 12821), 'lasagne.layers.dnn.batch_norm_dnn', 'batch_norm', (['layer'], {'name': '"""foo"""'}), "(layer, name='foo')\n", (12802, 12821), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer, batch_norm_dnn as batch_norm\n'), ((12972, 13031), 'mock.Mock', 'Mock', (['Layer'], {'output_shapes': '(input_shape,)', 'nonlinearity': 'obj'}), '(Layer, output_shapes=(input_shape,), nonlinearity=obj)\n', (12976, 13031), False, 'from mock import Mock\n'), ((13070, 13105), 'lasagne.layers.dnn.batch_norm_dnn', 'batch_norm', (['layer'], {'name': '"""foo_bnorm"""'}), "(layer, name='foo_bnorm')\n", (13080, 13105), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer, batch_norm_dnn as batch_norm\n'), ((13397, 13456), 'mock.Mock', 'Mock', (['Layer'], {'output_shapes': '(input_shape,)', 'nonlinearity': 'obj'}), '(Layer, output_shapes=(input_shape,), nonlinearity=obj)\n', (13401, 13456), False, 'from mock import Mock\n'), ((13495, 13512), 'lasagne.layers.dnn.batch_norm_dnn', 'batch_norm', (['layer'], {}), '(layer)\n', (13505, 13512), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer, batch_norm_dnn as batch_norm\n'), ((13801, 13860), 'mock.Mock', 'Mock', (['Layer'], {'output_shapes': '(input_shape,)', 'nonlinearity': 'obj'}), '(Layer, output_shapes=(input_shape,), nonlinearity=obj)\n', (13805, 13860), False, 'from mock import Mock\n'), ((13898, 13915), 'lasagne.layers.dnn.batch_norm_dnn', 'batch_norm', (['layer'], {}), '(layer)\n', (13908, 13915), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer, batch_norm_dnn as batch_norm\n'), ((2904, 2936), 'numpy.random.RandomState', 'np.random.RandomState', (['[2013, 2]'], {}), '([2013, 2])\n', (2925, 2936), True, 'import numpy as np\n'), ((3371, 3388), 'lasagne.layers.input.InputLayer', 'InputLayer', (['shape'], {}), '(shape)\n', (3381, 3388), False, 'from lasagne.layers.input import InputLayer\n'), ((3562, 3640), 'lasagne.layers.normalization.LocalResponseNormalization2DLayer', 'LocalResponseNormalization2DLayer', (['input_layer'], {'alpha': '(1.5)', 'k': '(2)', 'beta': '(0.75)', 'n': '(5)'}), '(input_layer, alpha=1.5, k=2, beta=0.75, n=5)\n', (3595, 3640), False, 'from lasagne.layers.normalization import LocalResponseNormalization2DLayer\n'), ((4942, 4980), 'numpy.transpose', 'np.transpose', (['ground_out', '[3, 0, 1, 2]'], {}), '(ground_out, [3, 0, 1, 2])\n', (4954, 4980), True, 'import numpy as np\n'), ((5043, 5071), 'numpy.allclose', 'np.allclose', (['out', 'ground_out'], {}), '(out, ground_out)\n', (5054, 5071), True, 'import numpy as np\n'), ((7396, 7412), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (7410, 7412), True, 'import numpy as np\n'), ((7509, 7606), 'lasagne.layers.dnn.BatchNormDNNLayer', 'BatchNormLayer', (['input_shape'], {'beta': 'beta', 'gamma': 'gamma', 'mean': 'mean', 'inv_std': 'inv_std', 'alpha': 'alpha'}), '(input_shape, beta=beta, gamma=gamma, mean=mean, inv_std=\n inv_std, alpha=alpha)\n', (7523, 7606), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer\n'), ((9166, 9204), 'numpy.allclose', 'np.allclose', (['result', 'exp_result'], {}), '(result, exp_result, **tol)\n', (9177, 9204), True, 'import numpy as np\n'), ((9289, 9331), 'lasagne.layers.dnn.BatchNormDNNLayer', 'BatchNormLayer', (['(64, 2, None)'], {'axes': '(0, 2)'}), '((64, 2, None), axes=(0, 2))\n', (9303, 9331), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer\n'), ((10009, 10060), 'lasagne.layers.dnn.BatchNormDNNLayer', 'BatchNormLayer', (['input_shape'], {'beta': 'None', 'gamma': 'gamma'}), '(input_shape, beta=None, gamma=gamma)\n', (10023, 10060), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer\n'), ((10078, 10128), 'lasagne.layers.dnn.BatchNormDNNLayer', 'BatchNormLayer', (['input_shape'], {'beta': 'beta', 'gamma': 'None'}), '(input_shape, beta=beta, gamma=None)\n', (10092, 10128), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer\n'), ((11065, 11105), 'numpy.allclose', 'np.allclose', (['result1', 'exp_result1'], {}), '(result1, exp_result1, **tol)\n', (11076, 11105), True, 'import numpy as np\n'), ((11121, 11161), 'numpy.allclose', 'np.allclose', (['result2', 'exp_result2'], {}), '(result2, exp_result2, **tol)\n', (11132, 11161), True, 'import numpy as np\n'), ((4223, 4257), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {}), '(NotImplementedError)\n', (4236, 4257), False, 'import pytest\n'), ((4271, 4322), 'lasagne.layers.normalization.LocalResponseNormalization2DLayer', 'LocalResponseNormalization2DLayer', (['input_layer'], {'n': '(4)'}), '(input_layer, n=4)\n', (4304, 4322), False, 'from lasagne.layers.normalization import LocalResponseNormalization2DLayer\n'), ((4505, 4525), 'lasagne.layers.get_output', 'get_output', (['layer', 'X'], {}), '(layer, X)\n', (4515, 4525), False, 'from lasagne.layers import get_output\n'), ((5914, 5959), 'lasagne.layers.dnn.BatchNormDNNLayer', 'BatchNormLayer', (['input_shape'], {'beta': 'init_unique'}), '(input_shape, beta=init_unique)\n', (5928, 5959), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer\n'), ((6085, 6138), 'lasagne.layers.dnn.BatchNormDNNLayer', 'BatchNormLayer', (['input_shape'], {'beta': 'init_unique', 'axes': '(0)'}), '(input_shape, beta=init_unique, axes=0)\n', (6099, 6138), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer\n'), ((9372, 9397), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (9385, 9397), False, 'import pytest\n'), ((9418, 9460), 'lasagne.layers.dnn.BatchNormDNNLayer', 'BatchNormLayer', (['(64, None, 3)'], {'axes': '(0, 2)'}), '((64, None, 3), axes=(0, 2))\n', (9432, 9460), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer\n'), ((6289, 6347), 'lasagne.layers.dnn.BatchNormDNNLayer', 'BatchNormLayer', (['input_shape'], {'beta': 'init_unique', 'axes': '(1, 2)'}), '(input_shape, beta=init_unique, axes=(1, 2))\n', (6303, 6347), True, 'from lasagne.layers.dnn import BatchNormDNNLayer as BatchNormLayer\n'), ((7136, 7155), 'numpy.random.randn', 'np.random.randn', (['(30)'], {}), '(30)\n', (7151, 7155), True, 'import numpy as np\n'), ((7201, 7220), 'numpy.random.randn', 'np.random.randn', (['(30)'], {}), '(30)\n', (7216, 7220), True, 'import numpy as np\n'), ((7265, 7284), 'numpy.random.randn', 'np.random.randn', (['(30)'], {}), '(30)\n', (7280, 7284), True, 'import numpy as np\n'), ((7332, 7350), 'numpy.random.rand', 'np.random.rand', (['(30)'], {}), '(30)\n', (7346, 7350), True, 'import numpy as np\n'), ((9831, 9850), 'numpy.random.randn', 'np.random.randn', (['(30)'], {}), '(30)\n', (9846, 9850), True, 'import numpy as np\n'), ((9896, 9915), 'numpy.random.randn', 'np.random.randn', (['(30)'], {}), '(30)\n', (9911, 9915), True, 'import numpy as np\n'), ((11538, 11583), 'pytest.skip', 'pytest.skip', (['"""cuDNN batch norm not available"""'], {}), "('cuDNN batch norm not available')\n", (11549, 11583), False, 'import pytest\n'), ((6987, 7016), 'numpy.random.randn', 'np.random.randn', (['*input_shape'], {}), '(*input_shape)\n', (7002, 7016), True, 'import numpy as np\n'), ((7065, 7090), 'numpy.random.randn', 'np.random.randn', (['(1)', '(30)', '(1)'], {}), '(1, 30, 1)\n', (7080, 7090), True, 'import numpy as np\n'), ((8076, 8105), 'theano.tensor.constant', 'theano.tensor.constant', (['input'], {}), '(input)\n', (8098, 8105), False, 'import theano\n'), ((9682, 9711), 'numpy.random.randn', 'np.random.randn', (['*input_shape'], {}), '(*input_shape)\n', (9697, 9711), True, 'import numpy as np\n'), ((9760, 9785), 'numpy.random.randn', 'np.random.randn', (['(1)', '(30)', '(1)'], {}), '(1, 30, 1)\n', (9775, 9785), True, 'import numpy as np\n'), ((10339, 10368), 'theano.tensor.constant', 'theano.tensor.constant', (['input'], {}), '(input)\n', (10361, 10368), False, 'import theano\n'), ((10478, 10507), 'theano.tensor.constant', 'theano.tensor.constant', (['input'], {}), '(input)\n', (10500, 10507), False, 'import theano\n'), ((5512, 5557), 'pytest.skip', 'pytest.skip', (['"""cuDNN batch norm not available"""'], {}), "('cuDNN batch norm not available')\n", (5523, 5557), False, 'import pytest\n'), ((5727, 5741), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (5734, 5741), True, 'import numpy as np\n')]
#!/usr/bin/env python3 import numpy as np class KMeans(object): """ Performs the K-Means Clustering algorithm i.e. Lloyd's algorithm a.k.a. Voronoi iteration or relaxation Parameters -------------------------------------------------- k : int the number of clusters to form i.e. the number of centroids to generate seed : int seed used to initialize the pseudo-random number generator iterations: int maximum number of iterations to be performed """ def __init__(self, k = 2, iterations = 100, seed = None): self.k = k self.seed = seed self.iters = iterations self.cost = list() self.classes = None self.centroids = None def fit(self, x): """ Parameters -------------------------------------------------- x: ndarray of shape (n_samples, n_features) Returns -------------------------------------------------- cost : ndarray of shape (iterations, 1) centroids: ndarray of shape (n_features, 1) classes : ndarray of shape (n_samples, 1) """ if (isinstance(x, np.ndarray) == False): raise Exception(f"x should be an ndarray of shape (n_samples, n_features).") np.random.seed(seed = self.seed) m = x.shape[0] classes = np.zeros(m) distances = np.zeros([m, self.k]) min_cost = np.inf centroids = x[np.random.randint(m, size = self.k)] for _ in range(self.iters): for i in range(self.k): distances[:,i] = self.euclidean_distance(centroids[i], x) classes = np.argmin(distances, axis = 1) for i in range(self.k): centroids[i] = np.mean(x[classes == i], axis = 0) curr_cost = self.compute_cost(x, classes, centroids) self.cost.append(curr_cost) if curr_cost < min_cost: min_cost = curr_cost self.classes = classes self.centroids = centroids def predict(self, x): """ Parameters -------------------------------------------------- x: ndarray of shape (n_samples, n_features) Returns -------------------------------------------------- y_pred: ndarray of shape (n_samples, 1) """ m = x.shape[0] dist = np.zeros([m, self.k]) for i in range(self.k): dist[:,i] = self.euclidean_distance(self.centroids[i], x) y_pred = np.argmin(dist, axis = 1) return y_pred def compute_cost(self, x, classes, centroids): """ Parameters -------------------------------------------------- x : ndarray of shape (n_samples, n_features) classes : ndarray of shape (n_samples, 1) centroids: ndarray of shape (n_features, 1) Returns -------------------------------------------------- cost: ndarray of shape (iterations, 1) """ cost = np.array([]) for i in range(self.k): dist = self.euclidean_distance(centroids[i], x[classes == i]) cost = np.append(cost, dist) return np.mean(cost) def euclidean_distance(self, centroid, x): """ Parameters -------------------------------------------------- x : ndarray of shape (n_samples, n_features) centroids: ndarray of shape (n_features, 1) Returns -------------------------------------------------- dist: ndarray of shape (n_samples, k) """ #np.sqrt(np.sum((x[i] - centroid)**2)) dist = np.linalg.norm(x - centroid, axis = 1) return dist class KMedians(KMeans): """ Performs the K-Medians Clustering algorithm. Parameters -------------------------------------------------- k : int the number of clusters to form i.e. the number of centroids to generate seed : int seed used to initialize the pseudo-random number generator iterations: int maximum number of iterations to be performed """ def __init__(self, k = 2, iterations = 100, seed = None): KMeans.__init__( self, k = k, iterations = iterations, seed = seed ) def fit(self, x): """ Parameters -------------------------------------------------- x: ndarray of shape (n_samples, n_features) Returns -------------------------------------------------- cost : ndarray of shape (iterations, 1) centroids: ndarray of shape (n_features, 1) classes : ndarray of shape (n_samples, 1) """ np.random.seed(seed = self.seed) m = x.shape[0] classes = np.zeros(m) distances = np.zeros([m, self.k]) min_cost = np.inf centroids = x[np.random.randint(m, size = self.k)] for _ in range(self.iters): for i in range(self.k): distances[:,i] = self.euclidean_distance(centroids[i], x) classes = np.argmin(distances, axis = 1) for i in range(self.k): centroids[i] = np.median(x[classes == i], axis = 0) curr_cost = self.compute_cost(x, classes, centroids) self.cost.append(curr_cost) if curr_cost < min_cost: min_cost = curr_cost self.classes = classes self.centroids = centroids
[ "numpy.mean", "numpy.median", "numpy.append", "numpy.array", "numpy.zeros", "numpy.random.randint", "numpy.random.seed", "numpy.linalg.norm", "numpy.argmin" ]
[((1335, 1365), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'self.seed'}), '(seed=self.seed)\n', (1349, 1365), True, 'import numpy as np\n'), ((1420, 1431), 'numpy.zeros', 'np.zeros', (['m'], {}), '(m)\n', (1428, 1431), True, 'import numpy as np\n'), ((1452, 1473), 'numpy.zeros', 'np.zeros', (['[m, self.k]'], {}), '([m, self.k])\n', (1460, 1473), True, 'import numpy as np\n'), ((2501, 2522), 'numpy.zeros', 'np.zeros', (['[m, self.k]'], {}), '([m, self.k])\n', (2509, 2522), True, 'import numpy as np\n'), ((2660, 2683), 'numpy.argmin', 'np.argmin', (['dist'], {'axis': '(1)'}), '(dist, axis=1)\n', (2669, 2683), True, 'import numpy as np\n'), ((3180, 3192), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3188, 3192), True, 'import numpy as np\n'), ((3357, 3370), 'numpy.mean', 'np.mean', (['cost'], {}), '(cost)\n', (3364, 3370), True, 'import numpy as np\n'), ((3829, 3865), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - centroid)'], {'axis': '(1)'}), '(x - centroid, axis=1)\n', (3843, 3865), True, 'import numpy as np\n'), ((4941, 4971), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'self.seed'}), '(seed=self.seed)\n', (4955, 4971), True, 'import numpy as np\n'), ((5026, 5037), 'numpy.zeros', 'np.zeros', (['m'], {}), '(m)\n', (5034, 5037), True, 'import numpy as np\n'), ((5058, 5079), 'numpy.zeros', 'np.zeros', (['[m, self.k]'], {}), '([m, self.k])\n', (5066, 5079), True, 'import numpy as np\n'), ((1523, 1556), 'numpy.random.randint', 'np.random.randint', (['m'], {'size': 'self.k'}), '(m, size=self.k)\n', (1540, 1556), True, 'import numpy as np\n'), ((1742, 1770), 'numpy.argmin', 'np.argmin', (['distances'], {'axis': '(1)'}), '(distances, axis=1)\n', (1751, 1770), True, 'import numpy as np\n'), ((3319, 3340), 'numpy.append', 'np.append', (['cost', 'dist'], {}), '(cost, dist)\n', (3328, 3340), True, 'import numpy as np\n'), ((5129, 5162), 'numpy.random.randint', 'np.random.randint', (['m'], {'size': 'self.k'}), '(m, size=self.k)\n', (5146, 5162), True, 'import numpy as np\n'), ((5348, 5376), 'numpy.argmin', 'np.argmin', (['distances'], {'axis': '(1)'}), '(distances, axis=1)\n', (5357, 5376), True, 'import numpy as np\n'), ((1841, 1873), 'numpy.mean', 'np.mean', (['x[classes == i]'], {'axis': '(0)'}), '(x[classes == i], axis=0)\n', (1848, 1873), True, 'import numpy as np\n'), ((5447, 5481), 'numpy.median', 'np.median', (['x[classes == i]'], {'axis': '(0)'}), '(x[classes == i], axis=0)\n', (5456, 5481), True, 'import numpy as np\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns color = sns.color_palette() # %matplotlib inline pd.options.mode.chained_assignment=None def col_count_plot_v1(df, col, create_plot=True): cnt_srs = df[col].value_counts() color=sns.color_palette() plt.figure(figsize=(12, 8)) sns.barplot(cnt_srs.index, cnt_srs.values, alpha=0.8, color=color[1]) plt.ylabel('Number of Occurences', fontsize=12) plt.xlabel('Eval set type', fontsize=12) plt.title('Count of rows in each dataset', fontsize=15) plt.xticks(rotation='vertical') plt.show() def col_count_plot_bar(df, col): cnt_srs = df[col].value_counts() plt.figure(figsize=(8, 4)) color = sns.color_palette() sns.barplot(cnt_srs.index, cnt_srs.values, alpha=0.8, color=color[0]) plt.ylabel('Number of Occurences', fontsize=12) plt.xlabel('bathrooms', fontsize=12) plt.show() # 统计常值的列个数 def constant_unique(train_df): unique_df = train_df.nunique().reset_index() unique_df.columns = ['col_name', 'unique_count'] constant_df = unique_df[unique_df['unique_count'] == 1] return constant_df def unique_count_group(df, col1, col2): """ 根据col2分类,计算col1不重复的个数 :param df: pd.DataFrame :param col1: count to :param col2: by col :return: """ print(df.groupby(col2)[col1].aggregate(lambda x: len(np.unique(x)))) def max_value_group(orders_df, col1, col2, create_plot=True): cnt_srs = orders_df.groupby(col2)[col1].aggregate(np.max).reset_index() cnt_srs = cnt_srs[col1].value_counts() color = sns.color_palette() if create_plot: plt.figure(figsize=(12, 8)) sns.barplot(cnt_srs.index, cnt_srs.values, alpha=0.8, color=color[2]) plt.ylabel('Number of Occurrences', fontsize=12) plt.xlabel('Maximum order number', fontsize=12) plt.xticks(rotation='vertical') plt.show() def mean_value_group(orders_df, col1, col2, create_plot=True): cnt_srs = orders_df.groupby(col2)[col1].aggregate('mean').reset_index() cnt_srs = cnt_srs[col1].value_counts() color = sns.color_palette() if create_plot: plt.figure(figsize=(12, 8)) sns.barplot(cnt_srs.index, cnt_srs.values, alpha=0.8, color=color[2]) plt.ylabel('Number of Occurrences', fontsize=12) plt.xlabel('Mean order number', fontsize=12) plt.xticks(rotation='vertical') plt.show() def count_value_group_pivot(df, col1, col2, create_plot=True): """ :param df: :param col1: 需要统计的列名 :param col2: 两个以上列名 :param create_plot: :return: """ grouped_df = df.groupby(col2)[col1].aggregate('count').reset_index() grouped_df = grouped_df.pivot(col2[0], col2[1], col1) if create_plot: plt.figure(figsize=(12, 6)) sns.heatmap(grouped_df) plt.title('Frequency of Day of week Vs Hour of day') plt.show() if __name__ == "__main__": print('ok') order_products_train_df = pd.read_csv("../input/order_products__train.csv") order_products_prior_df = pd.read_csv("../input/order_products__prior.csv") orders_df = pd.read_csv("../input/orders.csv") products_df = pd.read_csv("../input/products.csv") aisles_df = pd.read_csv("../input/aisles.csv") departments_df = pd.read_csv("../input/departments.csv") col_count_plot_v1(orders_df, 'eval_set') unique_count_group(orders_df, 'user_id', 'eval_set') max_value_group(orders_df, 'order_number', 'user_id') count_value_group_pivot(orders_df, 'order_number', ['order_dow', 'order_hour_of_day'])
[ "numpy.unique", "seaborn.color_palette", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xticks", "pandas.read_csv", "matplotlib.pyplot.xlabel", "seaborn.heatmap", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "seaborn.barplot", "matplotlib.pyplot.show" ]
[((101, 120), 'seaborn.color_palette', 'sns.color_palette', ([], {}), '()\n', (118, 120), True, 'import seaborn as sns\n'), ((283, 302), 'seaborn.color_palette', 'sns.color_palette', ([], {}), '()\n', (300, 302), True, 'import seaborn as sns\n'), ((307, 334), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 8)'}), '(figsize=(12, 8))\n', (317, 334), True, 'import matplotlib.pyplot as plt\n'), ((339, 408), 'seaborn.barplot', 'sns.barplot', (['cnt_srs.index', 'cnt_srs.values'], {'alpha': '(0.8)', 'color': 'color[1]'}), '(cnt_srs.index, cnt_srs.values, alpha=0.8, color=color[1])\n', (350, 408), True, 'import seaborn as sns\n'), ((413, 460), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of Occurences"""'], {'fontsize': '(12)'}), "('Number of Occurences', fontsize=12)\n", (423, 460), True, 'import matplotlib.pyplot as plt\n'), ((465, 505), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Eval set type"""'], {'fontsize': '(12)'}), "('Eval set type', fontsize=12)\n", (475, 505), True, 'import matplotlib.pyplot as plt\n'), ((510, 565), 'matplotlib.pyplot.title', 'plt.title', (['"""Count of rows in each dataset"""'], {'fontsize': '(15)'}), "('Count of rows in each dataset', fontsize=15)\n", (519, 565), True, 'import matplotlib.pyplot as plt\n'), ((570, 601), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '"""vertical"""'}), "(rotation='vertical')\n", (580, 601), True, 'import matplotlib.pyplot as plt\n'), ((606, 616), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (614, 616), True, 'import matplotlib.pyplot as plt\n'), ((693, 719), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (703, 719), True, 'import matplotlib.pyplot as plt\n'), ((732, 751), 'seaborn.color_palette', 'sns.color_palette', ([], {}), '()\n', (749, 751), True, 'import seaborn as sns\n'), ((756, 825), 'seaborn.barplot', 'sns.barplot', (['cnt_srs.index', 'cnt_srs.values'], {'alpha': '(0.8)', 'color': 'color[0]'}), '(cnt_srs.index, cnt_srs.values, alpha=0.8, color=color[0])\n', (767, 825), True, 'import seaborn as sns\n'), ((830, 877), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of Occurences"""'], {'fontsize': '(12)'}), "('Number of Occurences', fontsize=12)\n", (840, 877), True, 'import matplotlib.pyplot as plt\n'), ((882, 918), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""bathrooms"""'], {'fontsize': '(12)'}), "('bathrooms', fontsize=12)\n", (892, 918), True, 'import matplotlib.pyplot as plt\n'), ((923, 933), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (931, 933), True, 'import matplotlib.pyplot as plt\n'), ((1612, 1631), 'seaborn.color_palette', 'sns.color_palette', ([], {}), '()\n', (1629, 1631), True, 'import seaborn as sns\n'), ((2135, 2154), 'seaborn.color_palette', 'sns.color_palette', ([], {}), '()\n', (2152, 2154), True, 'import seaborn as sns\n'), ((3033, 3082), 'pandas.read_csv', 'pd.read_csv', (['"""../input/order_products__train.csv"""'], {}), "('../input/order_products__train.csv')\n", (3044, 3082), True, 'import pandas as pd\n'), ((3113, 3162), 'pandas.read_csv', 'pd.read_csv', (['"""../input/order_products__prior.csv"""'], {}), "('../input/order_products__prior.csv')\n", (3124, 3162), True, 'import pandas as pd\n'), ((3179, 3213), 'pandas.read_csv', 'pd.read_csv', (['"""../input/orders.csv"""'], {}), "('../input/orders.csv')\n", (3190, 3213), True, 'import pandas as pd\n'), ((3232, 3268), 'pandas.read_csv', 'pd.read_csv', (['"""../input/products.csv"""'], {}), "('../input/products.csv')\n", (3243, 3268), True, 'import pandas as pd\n'), ((3285, 3319), 'pandas.read_csv', 'pd.read_csv', (['"""../input/aisles.csv"""'], {}), "('../input/aisles.csv')\n", (3296, 3319), True, 'import pandas as pd\n'), ((3341, 3380), 'pandas.read_csv', 'pd.read_csv', (['"""../input/departments.csv"""'], {}), "('../input/departments.csv')\n", (3352, 3380), True, 'import pandas as pd\n'), ((1661, 1688), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 8)'}), '(figsize=(12, 8))\n', (1671, 1688), True, 'import matplotlib.pyplot as plt\n'), ((1697, 1766), 'seaborn.barplot', 'sns.barplot', (['cnt_srs.index', 'cnt_srs.values'], {'alpha': '(0.8)', 'color': 'color[2]'}), '(cnt_srs.index, cnt_srs.values, alpha=0.8, color=color[2])\n', (1708, 1766), True, 'import seaborn as sns\n'), ((1775, 1823), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of Occurrences"""'], {'fontsize': '(12)'}), "('Number of Occurrences', fontsize=12)\n", (1785, 1823), True, 'import matplotlib.pyplot as plt\n'), ((1832, 1879), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Maximum order number"""'], {'fontsize': '(12)'}), "('Maximum order number', fontsize=12)\n", (1842, 1879), True, 'import matplotlib.pyplot as plt\n'), ((1888, 1919), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '"""vertical"""'}), "(rotation='vertical')\n", (1898, 1919), True, 'import matplotlib.pyplot as plt\n'), ((1928, 1938), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1936, 1938), True, 'import matplotlib.pyplot as plt\n'), ((2184, 2211), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 8)'}), '(figsize=(12, 8))\n', (2194, 2211), True, 'import matplotlib.pyplot as plt\n'), ((2220, 2289), 'seaborn.barplot', 'sns.barplot', (['cnt_srs.index', 'cnt_srs.values'], {'alpha': '(0.8)', 'color': 'color[2]'}), '(cnt_srs.index, cnt_srs.values, alpha=0.8, color=color[2])\n', (2231, 2289), True, 'import seaborn as sns\n'), ((2298, 2346), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of Occurrences"""'], {'fontsize': '(12)'}), "('Number of Occurrences', fontsize=12)\n", (2308, 2346), True, 'import matplotlib.pyplot as plt\n'), ((2355, 2399), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Mean order number"""'], {'fontsize': '(12)'}), "('Mean order number', fontsize=12)\n", (2365, 2399), True, 'import matplotlib.pyplot as plt\n'), ((2408, 2439), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '"""vertical"""'}), "(rotation='vertical')\n", (2418, 2439), True, 'import matplotlib.pyplot as plt\n'), ((2448, 2458), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2456, 2458), True, 'import matplotlib.pyplot as plt\n'), ((2817, 2844), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (2827, 2844), True, 'import matplotlib.pyplot as plt\n'), ((2853, 2876), 'seaborn.heatmap', 'sns.heatmap', (['grouped_df'], {}), '(grouped_df)\n', (2864, 2876), True, 'import seaborn as sns\n'), ((2885, 2937), 'matplotlib.pyplot.title', 'plt.title', (['"""Frequency of Day of week Vs Hour of day"""'], {}), "('Frequency of Day of week Vs Hour of day')\n", (2894, 2937), True, 'import matplotlib.pyplot as plt\n'), ((2946, 2956), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2954, 2956), True, 'import matplotlib.pyplot as plt\n'), ((1401, 1413), 'numpy.unique', 'np.unique', (['x'], {}), '(x)\n', (1410, 1413), True, 'import numpy as np\n')]
#!/usr/bin/env python3 """ This example uses a configuration file in JSON format to process the events and apply pre-selection cuts to the images (charge and number of pixels). An HDF5 file is written with image MC and moment parameters (e.g. length, width, image amplitude, etc.). """ import numpy as np from tqdm import tqdm from ctapipe.core import Tool from ctapipe.core.traits import Unicode, List, Dict, Bool from ctapipe.io import EventSourceFactory, HDF5TableWriter from ctapipe.calib import CameraCalibrator from ctapipe.utils.CutFlow import CutFlow from ctapipe.image import hillas_parameters, tailcuts_clean class SimpleEventWriter(Tool): name = 'ctapipe-simple-event-writer' description = Unicode(__doc__) infile = Unicode(help='input file to read', default='').tag(config=True) outfile = Unicode(help='output file name', default_value='output.h5').tag(config=True) progress = Bool(help='display progress bar', default_value=True).tag(config=True) aliases = Dict({ 'infile': 'EventSourceFactory.input_url', 'outfile': 'SimpleEventWriter.outfile', 'max-events': 'EventSourceFactory.max_events', 'progress': 'SimpleEventWriter.progress' }) classes = List([EventSourceFactory, CameraCalibrator, CutFlow]) def setup(self): self.log.info('Configure EventSourceFactory...') self.event_source = EventSourceFactory.produce( config=self.config, tool=self, product='HESSIOEventSource' ) self.event_source.allowed_tels = self.config['Analysis']['allowed_tels'] self.calibrator = CameraCalibrator( config=self.config, tool=self, eventsource=self.event_source ) self.writer = HDF5TableWriter( filename=self.outfile, group_name='image_infos', overwrite=True ) # Define Pre-selection for images preselcuts = self.config['Preselect'] self.image_cutflow = CutFlow('Image preselection') self.image_cutflow.set_cuts(dict( no_sel=None, n_pixel=lambda s: np.count_nonzero(s) < preselcuts['n_pixel']['min'], image_amplitude=lambda q: q < preselcuts['image_amplitude']['min'] )) # Define Pre-selection for events self.event_cutflow = CutFlow('Event preselection') self.event_cutflow.set_cuts(dict( no_sel=None )) def start(self): self.log.info('Loop on events...') for event in tqdm( self.event_source, desc='EventWriter', total=self.event_source.max_events, disable=~self.progress): self.event_cutflow.count('no_sel') self.calibrator.calibrate(event) for tel_id in event.dl0.tels_with_data: self.image_cutflow.count('no_sel') camera = event.inst.subarray.tel[tel_id].camera dl1_tel = event.dl1.tel[tel_id] # Image cleaning image = dl1_tel.image[0] # Waiting for automatic gain selection mask = tailcuts_clean(camera, image, picture_thresh=10, boundary_thresh=5) cleaned = image.copy() cleaned[~mask] = 0 # Preselection cuts if self.image_cutflow.cut('n_pixel', cleaned): continue if self.image_cutflow.cut('image_amplitude', np.sum(cleaned)): continue # Image parametrisation params = hillas_parameters(camera, cleaned) # Save Ids, MC infos and Hillas informations self.writer.write(camera.cam_id, [event.r0, event.mc, params]) def finish(self): self.log.info('End of job.') self.image_cutflow() self.event_cutflow() self.writer.close() if __name__ == '__main__': tool = SimpleEventWriter() tool.run()
[ "ctapipe.io.EventSourceFactory.produce", "ctapipe.io.HDF5TableWriter", "ctapipe.image.hillas_parameters", "ctapipe.core.traits.Bool", "ctapipe.core.traits.Unicode", "ctapipe.utils.CutFlow.CutFlow", "tqdm.tqdm", "ctapipe.calib.CameraCalibrator", "numpy.count_nonzero", "numpy.sum", "ctapipe.image....
[((713, 729), 'ctapipe.core.traits.Unicode', 'Unicode', (['__doc__'], {}), '(__doc__)\n', (720, 729), False, 'from ctapipe.core.traits import Unicode, List, Dict, Bool\n'), ((1000, 1185), 'ctapipe.core.traits.Dict', 'Dict', (["{'infile': 'EventSourceFactory.input_url', 'outfile':\n 'SimpleEventWriter.outfile', 'max-events':\n 'EventSourceFactory.max_events', 'progress': 'SimpleEventWriter.progress'}"], {}), "({'infile': 'EventSourceFactory.input_url', 'outfile':\n 'SimpleEventWriter.outfile', 'max-events':\n 'EventSourceFactory.max_events', 'progress': 'SimpleEventWriter.progress'})\n", (1004, 1185), False, 'from ctapipe.core.traits import Unicode, List, Dict, Bool\n'), ((1230, 1283), 'ctapipe.core.traits.List', 'List', (['[EventSourceFactory, CameraCalibrator, CutFlow]'], {}), '([EventSourceFactory, CameraCalibrator, CutFlow])\n', (1234, 1283), False, 'from ctapipe.core.traits import Unicode, List, Dict, Bool\n'), ((1392, 1483), 'ctapipe.io.EventSourceFactory.produce', 'EventSourceFactory.produce', ([], {'config': 'self.config', 'tool': 'self', 'product': '"""HESSIOEventSource"""'}), "(config=self.config, tool=self, product=\n 'HESSIOEventSource')\n", (1418, 1483), False, 'from ctapipe.io import EventSourceFactory, HDF5TableWriter\n'), ((1609, 1687), 'ctapipe.calib.CameraCalibrator', 'CameraCalibrator', ([], {'config': 'self.config', 'tool': 'self', 'eventsource': 'self.event_source'}), '(config=self.config, tool=self, eventsource=self.event_source)\n', (1625, 1687), False, 'from ctapipe.calib import CameraCalibrator\n'), ((1733, 1818), 'ctapipe.io.HDF5TableWriter', 'HDF5TableWriter', ([], {'filename': 'self.outfile', 'group_name': '"""image_infos"""', 'overwrite': '(True)'}), "(filename=self.outfile, group_name='image_infos', overwrite=True\n )\n", (1748, 1818), False, 'from ctapipe.io import EventSourceFactory, HDF5TableWriter\n'), ((1954, 1983), 'ctapipe.utils.CutFlow.CutFlow', 'CutFlow', (['"""Image preselection"""'], {}), "('Image preselection')\n", (1961, 1983), False, 'from ctapipe.utils.CutFlow import CutFlow\n'), ((2295, 2324), 'ctapipe.utils.CutFlow.CutFlow', 'CutFlow', (['"""Event preselection"""'], {}), "('Event preselection')\n", (2302, 2324), False, 'from ctapipe.utils.CutFlow import CutFlow\n'), ((2489, 2597), 'tqdm.tqdm', 'tqdm', (['self.event_source'], {'desc': '"""EventWriter"""', 'total': 'self.event_source.max_events', 'disable': '(~self.progress)'}), "(self.event_source, desc='EventWriter', total=self.event_source.\n max_events, disable=~self.progress)\n", (2493, 2597), False, 'from tqdm import tqdm\n'), ((744, 790), 'ctapipe.core.traits.Unicode', 'Unicode', ([], {'help': '"""input file to read"""', 'default': '""""""'}), "(help='input file to read', default='')\n", (751, 790), False, 'from ctapipe.core.traits import Unicode, List, Dict, Bool\n'), ((822, 881), 'ctapipe.core.traits.Unicode', 'Unicode', ([], {'help': '"""output file name"""', 'default_value': '"""output.h5"""'}), "(help='output file name', default_value='output.h5')\n", (829, 881), False, 'from ctapipe.core.traits import Unicode, List, Dict, Bool\n'), ((914, 967), 'ctapipe.core.traits.Bool', 'Bool', ([], {'help': '"""display progress bar"""', 'default_value': '(True)'}), "(help='display progress bar', default_value=True)\n", (918, 967), False, 'from ctapipe.core.traits import Unicode, List, Dict, Bool\n'), ((3107, 3174), 'ctapipe.image.tailcuts_clean', 'tailcuts_clean', (['camera', 'image'], {'picture_thresh': '(10)', 'boundary_thresh': '(5)'}), '(camera, image, picture_thresh=10, boundary_thresh=5)\n', (3121, 3174), False, 'from ctapipe.image import hillas_parameters, tailcuts_clean\n'), ((3552, 3586), 'ctapipe.image.hillas_parameters', 'hillas_parameters', (['camera', 'cleaned'], {}), '(camera, cleaned)\n', (3569, 3586), False, 'from ctapipe.image import hillas_parameters, tailcuts_clean\n'), ((3439, 3454), 'numpy.sum', 'np.sum', (['cleaned'], {}), '(cleaned)\n', (3445, 3454), True, 'import numpy as np\n'), ((2081, 2100), 'numpy.count_nonzero', 'np.count_nonzero', (['s'], {}), '(s)\n', (2097, 2100), True, 'import numpy as np\n')]
import numpy as np from scipy.spatial import distance from scipy.sparse import csgraph from matplotlib import pyplot from matplotlib.widgets import Slider, Button, RadioButtons import linear_utilities as lu def rkm(X, init_W, s, plot_ax=None): """ Regularized K-means for principal path, MINIMIZER. Args: [ndarray float] X: data matrix [ndarray float] init_W: initial waypoints matrix [float] s: regularization parameter [matplotlib.axis.Axes] plot_ax: Axes for the 2D plot (first 2 dim of X), None to avoid plotting Returns: [ndarray float] W: final waypoints matrix [ndarray int] labels: final References: [1] 'Finding Prinicpal Paths in Data Space', M.J.Ferrarotti, W.Rocchia, S.Decherchi, [submitted] [2] 'Design and HPC Implementation of Unsupervised Kernel Methods in the Context of Molecular Dynamics', M.J.Ferrarotti, PhD Thesis. """ #extract useful info from args N = X.shape[0] d = X.shape[1] NC = init_W.shape[0]-2 #construct boundary matrix boundary = init_W[[0,NC+1],:] B=np.zeros([NC,d],float) B[[0,NC-1],:]=boundary #construct regularizer hessian AW = np.diag(np.ones(NC))+np.diag(-0.5*np.ones(NC-1),1)+np.diag(-0.5*np.ones(NC-1),-1) #compute initial labels XW_dst = distance.cdist(X,init_W,'sqeuclidean') u = XW_dst.argmin(1) #iterate the minimizer converged = False it = 0 while(not converged): it = it+1 print('iteration '+repr(it)) #compute cardinality W_card=np.zeros(NC+2,int) for i in range(NC+2): W_card[i] = np.sum(u==i) #compute centroid matrix C = np.ndarray([NC,d],float) for i in range(NC): C[i,:] = np.sum(X[u==i+1,:],0) #construct k-means hessian AX = np.diag(W_card[1:NC+1]) #update waypoints W = np.matmul(np.linalg.pinv(AX+s*AW),C+0.5*s*B) W = np.vstack([boundary[0,:],W,boundary[1,:]]) #compute new labels XW_dst = distance.cdist(X,W,'sqeuclidean') u_new = XW_dst.argmin(1) #check for convergence converged = not np.sum(u_new!=u) u=u_new #plot if(plot_ax is not None): pyplot.sca(plot_ax) pyplot.ion() pyplot.cla() pyplot.title('Annealing, s='+repr(s)) pyplot.plot(X[:,0],X[:,1],'bo') pyplot.plot(W[:,0],W[:,1],'-ro') pyplot.axis('equal') pyplot.pause(1.0/60) return W, u def rkm_cost(X, W, s): """ Regularized K-means for principal path, COST EVALUATION. (most stupid implementation) Args: [ndarray float] X: data matrix [ndarray float] W: waypoints matrix [float] s: regularization parameter Returns: [float] cost_km: K-means part of the cost [float] cost_reg: regularizer part of the cost """ XW_dst = distance.cdist(X,W,'sqeuclidean') u = XW_dst.argmin(1) cost_km=0.0 for i,x in enumerate(X): w = W[u[i],:] cost_km = cost_km + np.dot(x,x) + np.dot(w,w) -2*np.dot(x,w) cost_reg=0.0 for i,w in enumerate(W[0:-1,:]): w_nxt = W[i+1,:] cost_reg = cost_reg + np.dot(w,w) + np.dot(w_nxt,w_nxt) - 2*np.dot(w,w_nxt) cost_reg = s*cost_reg return cost_km, cost_reg def rkm_prefilter(X, boundary_ids, Nf=200, k=5, p=1000, T=0.1, plot_ax=None): """ Regularized K-means for principal path, PREFILTER. Args: [ndarray float] X: data matrix [ndarray int] boundary_ids: start/end waypoints as sample indices [int] Nf: number of filter centroids [int] k: number of nearest neighbor for the penalized graph [float] p: penalty factor for the penalized graph [float] T: filter threshold [matplotlib.axis.Axes] plot_ax: Axes for the 2D plot (first 2 dim of X), None to avoid plotting Returns: [ndarray float] X_filtered [ndarray int] boundary_ids_filtered [ndarray float] X_garbage """ #pick Nf medoids with k-means++ and compute pairwise distance matrix med_ids = lu.initMedoids(X, Nf-2, 'kpp', boundary_ids) med_ids = np.hstack([boundary_ids[0],med_ids,boundary_ids[1]]) medmed_dst = distance.cdist(X[med_ids,:],X[med_ids,:],'sqeuclidean') #build k-nearest-neighbor penalized matrix knn_ids = np.argsort(medmed_dst,1) medmed_dst_p = medmed_dst.copy()*p for i in range(Nf): for j in range(k): k=knn_ids[i,j] medmed_dst_p[i,k] = medmed_dst[i,k] medmed_dst_p[k,i] = medmed_dst[k,i] medmed_dst_p[0,Nf-1]=0 medmed_dst_p[Nf-1,0]=0 #find shortest path using dijkstra [path_dst, path_pre] = csgraph.dijkstra(medmed_dst_p, False, 0,True) path=np.ndarray(0,int) i=Nf-1 while(i != 0): path=np.hstack([i,path]) i = path_pre[i] path=np.hstack([i,path]) #filter out medoids too close to the shortest path T=T*np.mean(medmed_dst) to_filter_ids=np.ndarray(0,int) for i in path: to_filter_ids = np.hstack([np.where(medmed_dst[i,:]<T)[0], to_filter_ids]) to_filter_ids = np.setdiff1d(to_filter_ids,path) to_filter_ids = np.unique(to_filter_ids) to_keep_ids = np.setdiff1d(np.asarray(range(Nf)),to_filter_ids) Xmed_dst = distance.cdist(X,X[med_ids[to_keep_ids],:],'sqeuclidean') u = med_ids[to_keep_ids][Xmed_dst.argmin(1)] N=X.shape[0] filter_mask = np.zeros(N,bool) for i in range(N): if u[i] in med_ids[path]: filter_mask[i]=True #convert boundary indices boundary_ids_filtered = boundary_ids.copy() boundary_ids_filtered[0] = boundary_ids[0] - boundary_ids[0] + np.sum(filter_mask[0:boundary_ids[0]]) boundary_ids_filtered[1] = boundary_ids[1] - boundary_ids[1] + np.sum(filter_mask[0:boundary_ids[1]]) #plot filter figure if(plot_ax is not None): pyplot.sca(plot_ax) pyplot.ion() pyplot.plot(X[np.logical_not(filter_mask),0],X[np.logical_not(filter_mask),1],'yo',label='data filtered out') pyplot.plot(X[filter_mask,0],X[filter_mask,1],'bo',label='data kept') pyplot.plot(X[med_ids,0],X[med_ids,1],'ro',label='filter medoids') pyplot.plot(X[med_ids[to_filter_ids],0],X[med_ids[to_filter_ids],1],'kx',label='filter medoids dropped') pyplot.plot(X[med_ids[path],0],X[med_ids[path],1],'-go',label='filter shortest path') pyplot.plot(X[filter_mask,:][boundary_ids_filtered,0],X[filter_mask,:][boundary_ids_filtered,1],'mo',label='boundary samples') pyplot.legend() pyplot.axis('equal') return X[filter_mask,:], boundary_ids_filtered, X[np.logical_not(filter_mask),:] def rkm_MS_evidence(models, s_span, X): """ Regularized K-means for principal path, MODEL SELECTION, Bayesian Evidence. Args: [ndarray float] models: matrix with path models, shape N_models x N x (NC+2) [ndarray float] s_span: array with values of the reg parameter for each model (sorted in decreasing order, with 0 as last value) [ndarray float] X: data matrix Returns: [ndarray float] logE_s: array with values of log evidence for each model """ if(s_span[-1]>0.0): raise ValueError('In order to evaluate the evidence a model with s=0 has to be provided') #Evaluate unregularized cost cost_ureg=np.sum(rkm_cost(X, models[-1,:,:],s_span[-1])) logE_s = np.ndarray(s_span.size,float) for i,s in enumerate(s_span): N = X.shape[0] W = models[i,:,:] NC = W.shape[0]-2 d = W.shape[1] #Set gamma (empirical rational) and compute lambda gamma = np.sqrt(N)*0.125/np.mean(distance.cdist(X,X,'euclidean')) lambd = s*gamma #Maximum Posterior cost cost_MP=np.sum(rkm_cost(X, W, s)) #Find labels XW_dst = distance.cdist(X,W,'sqeuclidean') u = XW_dst.argmin(1) #Compute cardinality W_card=np.zeros(NC+2,int) for j in range(NC+2): W_card[j] = np.sum(u==j) #Construct boundary matrix boundary = W[[0,NC+1],:] B=np.zeros([NC,d],float) B[[0,NC-1],:]=boundary #Construct regularizer hessian AW = np.diag(np.ones(NC))+np.diag(-0.5*np.ones(NC-1),1)+np.diag(-0.5*np.ones(NC-1),-1) #Construct k-means hessian AX = np.diag(W_card[1:NC+1]) #Compute global hessian A = AX+s*AW #Evaluate log-evidence logE = -0.5*d*np.log(np.sum(np.linalg.eigvals(A))) logE = logE + gamma*(cost_ureg-cost_MP) if(lambd>0): logE = logE + 0.5*d*NC*np.log(lambd) else: logE = logE + 0.5*d*NC*np.log(lambd+np.finfo(np.float).eps) logE = logE - 0.125*lambd*np.trace(np.matmul(B.T,np.matmul(np.linalg.pinv(AW),B))) logE = logE + 0.25*lambd*np.trace(np.matmul(B.T,B)) logE_s[i] = logE return logE_s def rkm_MS_pathlen(models, s_span, X): """ Regularized K-means for principal path, MODEL SELECTION, Path length. Args: [ndarray float] models: matrix with path models, shape N_models x N x (NC+2) [ndarray float] s_span: array with values of the reg parameter for each model (sorted in decreasing order, with 0 as last value) [ndarray float] X: data matrix Returns: [ndarray float] len_s: array with values of path length for each model """ len_s=np.zeros(s_span.size,float) for i,s in enumerate(s_span): W = models[i,:,:] NC = W.shape[0]-2 for j,w in enumerate(W[0:-1,:]): w_nxt = W[j+1,:] len_s[i] = len_s[i] + np.sqrt(np.dot(w,w)+np.dot(w_nxt,w_nxt)-2*np.dot(w,w_nxt)) return len_s def rkm_MS_pathvar(models, s_span, X): """ Regularized K-means for principal path, MODEL SELECTION, variance on waypoints interdistance. Args: [ndarray float] models: matrix with path models, shape N_models x N x (NC+2) [ndarray float] s_span: array with values of the reg parameter for each model (sorted in decreasing order, with 0 as last value) [ndarray float] X: data matrix Returns: [ndarray float] W_dst_var: array with values of variance for each model """ W_dst_var=np.ndarray(models.shape[0],float) for i in range(models.shape[0]): W = models[i,:,:] W_dst=np.linalg.norm(W[1:,:]-W[0:-1,:],axis=1) W_dst_var[i] = np.var(W_dst) return W_dst_var def rkm_MS_ksgm(models, s_span, X): """ Regularized K-means for principal path, MODEL SELECTION, k-segment projection error. Args: [ndarray float] models: matrix with path models, shape N_models x N x (NC+2) [ndarray float] s_span: array with values of the reg parameter for each model (sorted in decreasing order, with 0 as last value) [ndarray float] X: data matrix Returns: [ndarray float] ksgm_s: array with values of k-segment projection error for each model """ N = X.shape[0] KX = np.matmul(X,X.T) ksgm_s = np.zeros(models.shape[0],float) for i in range(models.shape[0]): W = models[i,:,:] NC = W.shape[0] KW = np.matmul(W,W.T) KXW = np.matmul(X,W.T) a2 = np.tile(np.diag(KX)[:,np.newaxis],[1,NC-1]) + np.tile(np.diag(KW)[:-1],[N,1]) - 2*KXW[:,:-1] b2 = np.diag(KW)[:-1]+np.diag(KW)[1:]-2*np.diag(KW,1) ab = KXW[:,1:]-KXW[:,:-1]+np.tile(np.diag(KW)[:-1],[N,1])-np.tile(np.diag(KW,1),[N,1]) if(np.all(b2>0)): dst2 = a2 - ab*ab / b2 else: dst2 = a2 - ab*ab / (b2+np.finfo(np.float).eps) prj_mask = np.logical_and(ab>0,ab<b2) dst2[prj_mask==0] = np.inf prj_mask = np.max(prj_mask,1) dst2_line = np.min(dst2,1) dst2_vrtx = np.min(distance.cdist(X,W,'sqeuclidean'),1) ksgm_s[i] = np.sum(dst2_line[prj_mask])+np.sum(dst2_vrtx[prj_mask==0]) return ksgm_s def rkm_MS_gui(models, s_span, X, X_g=None): N = X.shape[0] d = X.shape[1] #### #GUI #### #Main axis (for data) pyplot.ion() [gui,ax_data] = pyplot.subplots() ax_data.set_title('Interactive Model Exploration') pyplot.subplots_adjust(0.25,0.25,0.75,0.9) #buttons to perform MS ax_MS_ev_btn = pyplot.axes([0.8, 0.85, 0.2, 0.05]) MS_ev_btn = Button(ax_MS_ev_btn, 'MS: evidence') ax_MS_ksgm_btn = pyplot.axes([0.8, 0.75, 0.2, 0.05]) MS_ksgm_btn = Button(ax_MS_ksgm_btn, 'MS: k-segment') ax_MS_len_btn = pyplot.axes([0.8, 0.65, 0.2, 0.05]) MS_len_btn = Button(ax_MS_len_btn, 'MS: path len') ax_MS_var_btn = pyplot.axes([0.8, 0.55, 0.2, 0.05]) MS_var_btn = Button(ax_MS_var_btn, 'MS: path var') #slider to select s ax_s_sld = pyplot.axes([0.25, 0.1, 0.5, 0.03]) ax_s_sld.set_title('[drag to change the value of s]') s_sld = Slider(ax_s_sld, 's', 0, s_span.size-1, valstep=1.0) #### #initial plot #### [X_plt, ] = ax_data.plot(X[:,0],X[:,1],'bo') if(X_g is not None): [X_g_plt, ] = ax_data.plot(X_g[:,0],X_g[:,1],'yo') s_id=0 [W_plt,] = ax_data.plot(models[s_id,:,0],models[s_id,:,1],'-ro') ax_data.axis('equal') #### #event handlers #### #s slider handler def s_sld_onchanged(val): s_id = int(s_span.size-1-val) W_plt.set_data(models[s_id,:,0:2].T) s_sld.valtext.set_text("s={:.2f}\ns_id={:d}".format(s_span[s_id],s_id)) #max evidence button handler def MS_ev_btn_onclicked(ev): logE_s = rkm_MS_evidence(models, s_span, X) s_maxE_id = np.argmax(logE_s) s_sld.set_val(s_span.size-1-s_maxE_id) [fig,(ax1,ax2)]=pyplot.subplots(2,1) #plot evidence vs s ax1.set_title('Model Selection with max Evidence') ax1.set_xlabel('s') ax1.set_ylabel('log(E)') ax1.semilogx(np.flip(s_span,0), np.flip(logE_s,0)) ax1.plot(s_span[s_maxE_id],logE_s[s_maxE_id],'ro') #plot model selected ax2.plot(X[:,0],X[:,1],'bo') if(X_g is not None): ax2.plot(X_g[:,0],X_g[:,1],'yo') ax2.plot(models[s_maxE_id,:,0],models[s_maxE_id,:,1],'-ro') ax2.axis('equal') # k-segment projection error button handler def MS_ksgm_btn_onclicked(ev): ksgm_s = rkm_MS_ksgm(models, s_span, X) i=0 while(i<ksgm_s.size-1 and ksgm_s[i]>ksgm_s[i+1]): i=i+1 s_minksgm_id = i s_sld.set_val(s_span.size-1-s_minksgm_id) #plot k-segment projection error vs s [fig,(ax1,ax2)]=pyplot.subplots(2,1) ax1.set_title('Model Selection with min k-segment projection error') ax1.set_xlabel('s') ax1.set_ylabel('ksgm') ax1.semilogx(np.flip(s_span,0), np.flip(ksgm_s,0)) ax1.plot(s_span[s_minksgm_id],ksgm_s[s_minksgm_id],'ro') #plot model selected ax2.plot(X[:,0],X[:,1],'bo') if(X_g is not None): ax2.plot(X_g[:,0],X_g[:,1],'yo') ax2.plot(models[s_minksgm_id,:,0],models[s_minksgm_id,:,1],'-ro') ax2.axis('equal') #elbow criteria on path length button handler def MS_len_btn_onclicked(ev): len_s = rkm_MS_pathlen(models, s_span, X) s_elb_id = lu.find_elbow(np.stack([s_span,len_s],-1)) s_sld.set_val(s_span.size-1-s_elb_id) #plot path length vs s [fig,(ax1,ax2)]=pyplot.subplots(2,1) ax1.set_title('Model Selection with elbow method on path length') ax1.set_xlabel('s') ax1.set_ylabel('path length') ax1.plot(np.flip(s_span,0), np.flip(len_s,0)) ax1.plot(s_span[s_elb_id],len_s[s_elb_id],'ro') #plot model selected ax2.plot(X[:,0],X[:,1],'bo') if(X_g is not None): ax2.plot(X_g[:,0],X_g[:,1],'yo') ax2.plot(models[s_elb_id,:,0],models[s_elb_id,:,1],'-ro') ax2.axis('equal') #elbow criteria on waypoints distance variance button handler def MS_var_btn_onclicked(ev): W_dst_var=rkm_MS_pathvar(models, s_span, X) s_elb_id = lu.find_elbow(np.stack([s_span,W_dst_var],-1)) s_sld.set_val(s_span.size-1-s_elb_id) #plot waypoints distance variance vs s [fig,(ax1,ax2)]=pyplot.subplots(2,1) ax1.set_title('Model Selection with elbow method on waypoins distance variance') ax1.set_xlabel('s') ax1.set_ylabel('W distance variance') ax1.plot(np.flip(s_span,0), np.flip(W_dst_var,0)) ax1.plot(s_span[s_elb_id],W_dst_var[s_elb_id],'ro') #plot model selected ax2.plot(X[:,0],X[:,1],'bo') if(X_g is not None): ax2.plot(X_g[:,0],X_g[:,1],'yo') ax2.plot(models[s_elb_id,:,0],models[s_elb_id,:,1],'-ro') ax2.axis('equal') #### #register handlers #### s_sld.on_changed(s_sld_onchanged) MS_ev_btn.on_clicked(MS_ev_btn_onclicked) MS_ksgm_btn.on_clicked(MS_ksgm_btn_onclicked) MS_len_btn.on_clicked(MS_len_btn_onclicked) MS_var_btn.on_clicked(MS_var_btn_onclicked) s_sld.set_val(s_span.size/2) pyplot.show() raw_input('select model with GUI then press [enter] to continue') return int(s_span.size-1-s_sld.val)
[ "numpy.sqrt", "numpy.linalg.pinv", "numpy.hstack", "numpy.logical_not", "numpy.log", "scipy.sparse.csgraph.dijkstra", "numpy.argsort", "numpy.linalg.norm", "matplotlib.widgets.Slider", "numpy.mean", "numpy.flip", "numpy.where", "matplotlib.pyplot.plot", "numpy.max", "numpy.stack", "num...
[((1116, 1140), 'numpy.zeros', 'np.zeros', (['[NC, d]', 'float'], {}), '([NC, d], float)\n', (1124, 1140), True, 'import numpy as np\n'), ((1335, 1375), 'scipy.spatial.distance.cdist', 'distance.cdist', (['X', 'init_W', '"""sqeuclidean"""'], {}), "(X, init_W, 'sqeuclidean')\n", (1349, 1375), False, 'from scipy.spatial import distance\n'), ((2996, 3031), 'scipy.spatial.distance.cdist', 'distance.cdist', (['X', 'W', '"""sqeuclidean"""'], {}), "(X, W, 'sqeuclidean')\n", (3010, 3031), False, 'from scipy.spatial import distance\n'), ((4226, 4272), 'linear_utilities.initMedoids', 'lu.initMedoids', (['X', '(Nf - 2)', '"""kpp"""', 'boundary_ids'], {}), "(X, Nf - 2, 'kpp', boundary_ids)\n", (4240, 4272), True, 'import linear_utilities as lu\n'), ((4285, 4339), 'numpy.hstack', 'np.hstack', (['[boundary_ids[0], med_ids, boundary_ids[1]]'], {}), '([boundary_ids[0], med_ids, boundary_ids[1]])\n', (4294, 4339), True, 'import numpy as np\n'), ((4355, 4414), 'scipy.spatial.distance.cdist', 'distance.cdist', (['X[med_ids, :]', 'X[med_ids, :]', '"""sqeuclidean"""'], {}), "(X[med_ids, :], X[med_ids, :], 'sqeuclidean')\n", (4369, 4414), False, 'from scipy.spatial import distance\n'), ((4473, 4498), 'numpy.argsort', 'np.argsort', (['medmed_dst', '(1)'], {}), '(medmed_dst, 1)\n', (4483, 4498), True, 'import numpy as np\n'), ((4832, 4878), 'scipy.sparse.csgraph.dijkstra', 'csgraph.dijkstra', (['medmed_dst_p', '(False)', '(0)', '(True)'], {}), '(medmed_dst_p, False, 0, True)\n', (4848, 4878), False, 'from scipy.sparse import csgraph\n'), ((4887, 4905), 'numpy.ndarray', 'np.ndarray', (['(0)', 'int'], {}), '(0, int)\n', (4897, 4905), True, 'import numpy as np\n'), ((5001, 5021), 'numpy.hstack', 'np.hstack', (['[i, path]'], {}), '([i, path])\n', (5010, 5021), True, 'import numpy as np\n'), ((5124, 5142), 'numpy.ndarray', 'np.ndarray', (['(0)', 'int'], {}), '(0, int)\n', (5134, 5142), True, 'import numpy as np\n'), ((5264, 5297), 'numpy.setdiff1d', 'np.setdiff1d', (['to_filter_ids', 'path'], {}), '(to_filter_ids, path)\n', (5276, 5297), True, 'import numpy as np\n'), ((5317, 5341), 'numpy.unique', 'np.unique', (['to_filter_ids'], {}), '(to_filter_ids)\n', (5326, 5341), True, 'import numpy as np\n'), ((5427, 5487), 'scipy.spatial.distance.cdist', 'distance.cdist', (['X', 'X[med_ids[to_keep_ids], :]', '"""sqeuclidean"""'], {}), "(X, X[med_ids[to_keep_ids], :], 'sqeuclidean')\n", (5441, 5487), False, 'from scipy.spatial import distance\n'), ((5570, 5587), 'numpy.zeros', 'np.zeros', (['N', 'bool'], {}), '(N, bool)\n', (5578, 5587), True, 'import numpy as np\n'), ((7566, 7596), 'numpy.ndarray', 'np.ndarray', (['s_span.size', 'float'], {}), '(s_span.size, float)\n', (7576, 7596), True, 'import numpy as np\n'), ((9589, 9617), 'numpy.zeros', 'np.zeros', (['s_span.size', 'float'], {}), '(s_span.size, float)\n', (9597, 9617), True, 'import numpy as np\n'), ((10421, 10455), 'numpy.ndarray', 'np.ndarray', (['models.shape[0]', 'float'], {}), '(models.shape[0], float)\n', (10431, 10455), True, 'import numpy as np\n'), ((11186, 11203), 'numpy.matmul', 'np.matmul', (['X', 'X.T'], {}), '(X, X.T)\n', (11195, 11203), True, 'import numpy as np\n'), ((11216, 11248), 'numpy.zeros', 'np.zeros', (['models.shape[0]', 'float'], {}), '(models.shape[0], float)\n', (11224, 11248), True, 'import numpy as np\n'), ((12261, 12273), 'matplotlib.pyplot.ion', 'pyplot.ion', ([], {}), '()\n', (12271, 12273), False, 'from matplotlib import pyplot\n'), ((12294, 12311), 'matplotlib.pyplot.subplots', 'pyplot.subplots', ([], {}), '()\n', (12309, 12311), False, 'from matplotlib import pyplot\n'), ((12371, 12416), 'matplotlib.pyplot.subplots_adjust', 'pyplot.subplots_adjust', (['(0.25)', '(0.25)', '(0.75)', '(0.9)'], {}), '(0.25, 0.25, 0.75, 0.9)\n', (12393, 12416), False, 'from matplotlib import pyplot\n'), ((12465, 12500), 'matplotlib.pyplot.axes', 'pyplot.axes', (['[0.8, 0.85, 0.2, 0.05]'], {}), '([0.8, 0.85, 0.2, 0.05])\n', (12476, 12500), False, 'from matplotlib import pyplot\n'), ((12517, 12553), 'matplotlib.widgets.Button', 'Button', (['ax_MS_ev_btn', '"""MS: evidence"""'], {}), "(ax_MS_ev_btn, 'MS: evidence')\n", (12523, 12553), False, 'from matplotlib.widgets import Slider, Button, RadioButtons\n'), ((12576, 12611), 'matplotlib.pyplot.axes', 'pyplot.axes', (['[0.8, 0.75, 0.2, 0.05]'], {}), '([0.8, 0.75, 0.2, 0.05])\n', (12587, 12611), False, 'from matplotlib import pyplot\n'), ((12630, 12669), 'matplotlib.widgets.Button', 'Button', (['ax_MS_ksgm_btn', '"""MS: k-segment"""'], {}), "(ax_MS_ksgm_btn, 'MS: k-segment')\n", (12636, 12669), False, 'from matplotlib.widgets import Slider, Button, RadioButtons\n'), ((12691, 12726), 'matplotlib.pyplot.axes', 'pyplot.axes', (['[0.8, 0.65, 0.2, 0.05]'], {}), '([0.8, 0.65, 0.2, 0.05])\n', (12702, 12726), False, 'from matplotlib import pyplot\n'), ((12744, 12781), 'matplotlib.widgets.Button', 'Button', (['ax_MS_len_btn', '"""MS: path len"""'], {}), "(ax_MS_len_btn, 'MS: path len')\n", (12750, 12781), False, 'from matplotlib.widgets import Slider, Button, RadioButtons\n'), ((12803, 12838), 'matplotlib.pyplot.axes', 'pyplot.axes', (['[0.8, 0.55, 0.2, 0.05]'], {}), '([0.8, 0.55, 0.2, 0.05])\n', (12814, 12838), False, 'from matplotlib import pyplot\n'), ((12856, 12893), 'matplotlib.widgets.Button', 'Button', (['ax_MS_var_btn', '"""MS: path var"""'], {}), "(ax_MS_var_btn, 'MS: path var')\n", (12862, 12893), False, 'from matplotlib.widgets import Slider, Button, RadioButtons\n'), ((12938, 12973), 'matplotlib.pyplot.axes', 'pyplot.axes', (['[0.25, 0.1, 0.5, 0.03]'], {}), '([0.25, 0.1, 0.5, 0.03])\n', (12949, 12973), False, 'from matplotlib import pyplot\n'), ((13044, 13098), 'matplotlib.widgets.Slider', 'Slider', (['ax_s_sld', '"""s"""', '(0)', '(s_span.size - 1)'], {'valstep': '(1.0)'}), "(ax_s_sld, 's', 0, s_span.size - 1, valstep=1.0)\n", (13050, 13098), False, 'from matplotlib.widgets import Slider, Button, RadioButtons\n'), ((17309, 17322), 'matplotlib.pyplot.show', 'pyplot.show', ([], {}), '()\n', (17320, 17322), False, 'from matplotlib import pyplot\n'), ((1586, 1607), 'numpy.zeros', 'np.zeros', (['(NC + 2)', 'int'], {}), '(NC + 2, int)\n', (1594, 1607), True, 'import numpy as np\n'), ((1718, 1744), 'numpy.ndarray', 'np.ndarray', (['[NC, d]', 'float'], {}), '([NC, d], float)\n', (1728, 1744), True, 'import numpy as np\n'), ((1864, 1889), 'numpy.diag', 'np.diag', (['W_card[1:NC + 1]'], {}), '(W_card[1:NC + 1])\n', (1871, 1889), True, 'import numpy as np\n'), ((1984, 2030), 'numpy.vstack', 'np.vstack', (['[boundary[0, :], W, boundary[1, :]]'], {}), '([boundary[0, :], W, boundary[1, :]])\n', (1993, 2030), True, 'import numpy as np\n'), ((2073, 2108), 'scipy.spatial.distance.cdist', 'distance.cdist', (['X', 'W', '"""sqeuclidean"""'], {}), "(X, W, 'sqeuclidean')\n", (2087, 2108), False, 'from scipy.spatial import distance\n'), ((4948, 4968), 'numpy.hstack', 'np.hstack', (['[i, path]'], {}), '([i, path])\n', (4957, 4968), True, 'import numpy as np\n'), ((5085, 5104), 'numpy.mean', 'np.mean', (['medmed_dst'], {}), '(medmed_dst)\n', (5092, 5104), True, 'import numpy as np\n'), ((5826, 5864), 'numpy.sum', 'np.sum', (['filter_mask[0:boundary_ids[0]]'], {}), '(filter_mask[0:boundary_ids[0]])\n', (5832, 5864), True, 'import numpy as np\n'), ((5932, 5970), 'numpy.sum', 'np.sum', (['filter_mask[0:boundary_ids[1]]'], {}), '(filter_mask[0:boundary_ids[1]])\n', (5938, 5970), True, 'import numpy as np\n'), ((6034, 6053), 'matplotlib.pyplot.sca', 'pyplot.sca', (['plot_ax'], {}), '(plot_ax)\n', (6044, 6053), False, 'from matplotlib import pyplot\n'), ((6062, 6074), 'matplotlib.pyplot.ion', 'pyplot.ion', ([], {}), '()\n', (6072, 6074), False, 'from matplotlib import pyplot\n'), ((6201, 6275), 'matplotlib.pyplot.plot', 'pyplot.plot', (['X[filter_mask, 0]', 'X[filter_mask, 1]', '"""bo"""'], {'label': '"""data kept"""'}), "(X[filter_mask, 0], X[filter_mask, 1], 'bo', label='data kept')\n", (6212, 6275), False, 'from matplotlib import pyplot\n'), ((6279, 6350), 'matplotlib.pyplot.plot', 'pyplot.plot', (['X[med_ids, 0]', 'X[med_ids, 1]', '"""ro"""'], {'label': '"""filter medoids"""'}), "(X[med_ids, 0], X[med_ids, 1], 'ro', label='filter medoids')\n", (6290, 6350), False, 'from matplotlib import pyplot\n'), ((6354, 6467), 'matplotlib.pyplot.plot', 'pyplot.plot', (['X[med_ids[to_filter_ids], 0]', 'X[med_ids[to_filter_ids], 1]', '"""kx"""'], {'label': '"""filter medoids dropped"""'}), "(X[med_ids[to_filter_ids], 0], X[med_ids[to_filter_ids], 1],\n 'kx', label='filter medoids dropped')\n", (6365, 6467), False, 'from matplotlib import pyplot\n'), ((6467, 6562), 'matplotlib.pyplot.plot', 'pyplot.plot', (['X[med_ids[path], 0]', 'X[med_ids[path], 1]', '"""-go"""'], {'label': '"""filter shortest path"""'}), "(X[med_ids[path], 0], X[med_ids[path], 1], '-go', label=\n 'filter shortest path')\n", (6478, 6562), False, 'from matplotlib import pyplot\n'), ((6561, 6699), 'matplotlib.pyplot.plot', 'pyplot.plot', (['X[filter_mask, :][boundary_ids_filtered, 0]', 'X[filter_mask, :][boundary_ids_filtered, 1]', '"""mo"""'], {'label': '"""boundary samples"""'}), "(X[filter_mask, :][boundary_ids_filtered, 0], X[filter_mask, :][\n boundary_ids_filtered, 1], 'mo', label='boundary samples')\n", (6572, 6699), False, 'from matplotlib import pyplot\n'), ((6696, 6711), 'matplotlib.pyplot.legend', 'pyplot.legend', ([], {}), '()\n', (6709, 6711), False, 'from matplotlib import pyplot\n'), ((6720, 6740), 'matplotlib.pyplot.axis', 'pyplot.axis', (['"""equal"""'], {}), "('equal')\n", (6731, 6740), False, 'from matplotlib import pyplot\n'), ((8001, 8036), 'scipy.spatial.distance.cdist', 'distance.cdist', (['X', 'W', '"""sqeuclidean"""'], {}), "(X, W, 'sqeuclidean')\n", (8015, 8036), False, 'from scipy.spatial import distance\n'), ((8108, 8129), 'numpy.zeros', 'np.zeros', (['(NC + 2)', 'int'], {}), '(NC + 2, int)\n', (8116, 8129), True, 'import numpy as np\n'), ((8273, 8297), 'numpy.zeros', 'np.zeros', (['[NC, d]', 'float'], {}), '([NC, d], float)\n', (8281, 8297), True, 'import numpy as np\n'), ((8512, 8537), 'numpy.diag', 'np.diag', (['W_card[1:NC + 1]'], {}), '(W_card[1:NC + 1])\n', (8519, 8537), True, 'import numpy as np\n'), ((10532, 10577), 'numpy.linalg.norm', 'np.linalg.norm', (['(W[1:, :] - W[0:-1, :])'], {'axis': '(1)'}), '(W[1:, :] - W[0:-1, :], axis=1)\n', (10546, 10577), True, 'import numpy as np\n'), ((10596, 10609), 'numpy.var', 'np.var', (['W_dst'], {}), '(W_dst)\n', (10602, 10609), True, 'import numpy as np\n'), ((11349, 11366), 'numpy.matmul', 'np.matmul', (['W', 'W.T'], {}), '(W, W.T)\n', (11358, 11366), True, 'import numpy as np\n'), ((11380, 11397), 'numpy.matmul', 'np.matmul', (['X', 'W.T'], {}), '(X, W.T)\n', (11389, 11397), True, 'import numpy as np\n'), ((11672, 11686), 'numpy.all', 'np.all', (['(b2 > 0)'], {}), '(b2 > 0)\n', (11678, 11686), True, 'import numpy as np\n'), ((11816, 11847), 'numpy.logical_and', 'np.logical_and', (['(ab > 0)', '(ab < b2)'], {}), '(ab > 0, ab < b2)\n', (11830, 11847), True, 'import numpy as np\n'), ((11897, 11916), 'numpy.max', 'np.max', (['prj_mask', '(1)'], {}), '(prj_mask, 1)\n', (11903, 11916), True, 'import numpy as np\n'), ((11937, 11952), 'numpy.min', 'np.min', (['dst2', '(1)'], {}), '(dst2, 1)\n', (11943, 11952), True, 'import numpy as np\n'), ((13777, 13794), 'numpy.argmax', 'np.argmax', (['logE_s'], {}), '(logE_s)\n', (13786, 13794), True, 'import numpy as np\n'), ((13867, 13888), 'matplotlib.pyplot.subplots', 'pyplot.subplots', (['(2)', '(1)'], {}), '(2, 1)\n', (13882, 13888), False, 'from matplotlib import pyplot\n'), ((14772, 14793), 'matplotlib.pyplot.subplots', 'pyplot.subplots', (['(2)', '(1)'], {}), '(2, 1)\n', (14787, 14793), False, 'from matplotlib import pyplot\n'), ((15605, 15626), 'matplotlib.pyplot.subplots', 'pyplot.subplots', (['(2)', '(1)'], {}), '(2, 1)\n', (15620, 15626), False, 'from matplotlib import pyplot\n'), ((16458, 16479), 'matplotlib.pyplot.subplots', 'pyplot.subplots', (['(2)', '(1)'], {}), '(2, 1)\n', (16473, 16479), False, 'from matplotlib import pyplot\n'), ((1659, 1673), 'numpy.sum', 'np.sum', (['(u == i)'], {}), '(u == i)\n', (1665, 1673), True, 'import numpy as np\n'), ((1792, 1819), 'numpy.sum', 'np.sum', (['X[u == i + 1, :]', '(0)'], {}), '(X[u == i + 1, :], 0)\n', (1798, 1819), True, 'import numpy as np\n'), ((1937, 1964), 'numpy.linalg.pinv', 'np.linalg.pinv', (['(AX + s * AW)'], {}), '(AX + s * AW)\n', (1951, 1964), True, 'import numpy as np\n'), ((2196, 2214), 'numpy.sum', 'np.sum', (['(u_new != u)'], {}), '(u_new != u)\n', (2202, 2214), True, 'import numpy as np\n'), ((2289, 2308), 'matplotlib.pyplot.sca', 'pyplot.sca', (['plot_ax'], {}), '(plot_ax)\n', (2299, 2308), False, 'from matplotlib import pyplot\n'), ((2321, 2333), 'matplotlib.pyplot.ion', 'pyplot.ion', ([], {}), '()\n', (2331, 2333), False, 'from matplotlib import pyplot\n'), ((2346, 2358), 'matplotlib.pyplot.cla', 'pyplot.cla', ([], {}), '()\n', (2356, 2358), False, 'from matplotlib import pyplot\n'), ((2421, 2456), 'matplotlib.pyplot.plot', 'pyplot.plot', (['X[:, 0]', 'X[:, 1]', '"""bo"""'], {}), "(X[:, 0], X[:, 1], 'bo')\n", (2432, 2456), False, 'from matplotlib import pyplot\n'), ((2465, 2501), 'matplotlib.pyplot.plot', 'pyplot.plot', (['W[:, 0]', 'W[:, 1]', '"""-ro"""'], {}), "(W[:, 0], W[:, 1], '-ro')\n", (2476, 2501), False, 'from matplotlib import pyplot\n'), ((2510, 2530), 'matplotlib.pyplot.axis', 'pyplot.axis', (['"""equal"""'], {}), "('equal')\n", (2521, 2530), False, 'from matplotlib import pyplot\n'), ((2544, 2566), 'matplotlib.pyplot.pause', 'pyplot.pause', (['(1.0 / 60)'], {}), '(1.0 / 60)\n', (2556, 2566), False, 'from matplotlib import pyplot\n'), ((8181, 8195), 'numpy.sum', 'np.sum', (['(u == j)'], {}), '(u == j)\n', (8187, 8195), True, 'import numpy as np\n'), ((11979, 12014), 'scipy.spatial.distance.cdist', 'distance.cdist', (['X', 'W', '"""sqeuclidean"""'], {}), "(X, W, 'sqeuclidean')\n", (11993, 12014), False, 'from scipy.spatial import distance\n'), ((12037, 12064), 'numpy.sum', 'np.sum', (['dst2_line[prj_mask]'], {}), '(dst2_line[prj_mask])\n', (12043, 12064), True, 'import numpy as np\n'), ((12065, 12097), 'numpy.sum', 'np.sum', (['dst2_vrtx[prj_mask == 0]'], {}), '(dst2_vrtx[prj_mask == 0])\n', (12071, 12097), True, 'import numpy as np\n'), ((14062, 14080), 'numpy.flip', 'np.flip', (['s_span', '(0)'], {}), '(s_span, 0)\n', (14069, 14080), True, 'import numpy as np\n'), ((14081, 14099), 'numpy.flip', 'np.flip', (['logE_s', '(0)'], {}), '(logE_s, 0)\n', (14088, 14099), True, 'import numpy as np\n'), ((14950, 14968), 'numpy.flip', 'np.flip', (['s_span', '(0)'], {}), '(s_span, 0)\n', (14957, 14968), True, 'import numpy as np\n'), ((14969, 14987), 'numpy.flip', 'np.flip', (['ksgm_s', '(0)'], {}), '(ksgm_s, 0)\n', (14976, 14987), True, 'import numpy as np\n'), ((15470, 15499), 'numpy.stack', 'np.stack', (['[s_span, len_s]', '(-1)'], {}), '([s_span, len_s], -1)\n', (15478, 15499), True, 'import numpy as np\n'), ((15783, 15801), 'numpy.flip', 'np.flip', (['s_span', '(0)'], {}), '(s_span, 0)\n', (15790, 15801), True, 'import numpy as np\n'), ((15802, 15819), 'numpy.flip', 'np.flip', (['len_s', '(0)'], {}), '(len_s, 0)\n', (15809, 15819), True, 'import numpy as np\n'), ((16303, 16336), 'numpy.stack', 'np.stack', (['[s_span, W_dst_var]', '(-1)'], {}), '([s_span, W_dst_var], -1)\n', (16311, 16336), True, 'import numpy as np\n'), ((16659, 16677), 'numpy.flip', 'np.flip', (['s_span', '(0)'], {}), '(s_span, 0)\n', (16666, 16677), True, 'import numpy as np\n'), ((16678, 16699), 'numpy.flip', 'np.flip', (['W_dst_var', '(0)'], {}), '(W_dst_var, 0)\n', (16685, 16699), True, 'import numpy as np\n'), ((1219, 1230), 'numpy.ones', 'np.ones', (['NC'], {}), '(NC)\n', (1226, 1230), True, 'import numpy as np\n'), ((1275, 1290), 'numpy.ones', 'np.ones', (['(NC - 1)'], {}), '(NC - 1)\n', (1282, 1290), True, 'import numpy as np\n'), ((3165, 3177), 'numpy.dot', 'np.dot', (['w', 'w'], {}), '(w, w)\n', (3171, 3177), True, 'import numpy as np\n'), ((3180, 3192), 'numpy.dot', 'np.dot', (['x', 'w'], {}), '(x, w)\n', (3186, 3192), True, 'import numpy as np\n'), ((3316, 3336), 'numpy.dot', 'np.dot', (['w_nxt', 'w_nxt'], {}), '(w_nxt, w_nxt)\n', (3322, 3336), True, 'import numpy as np\n'), ((3340, 3356), 'numpy.dot', 'np.dot', (['w', 'w_nxt'], {}), '(w, w_nxt)\n', (3346, 3356), True, 'import numpy as np\n'), ((6796, 6823), 'numpy.logical_not', 'np.logical_not', (['filter_mask'], {}), '(filter_mask)\n', (6810, 6823), True, 'import numpy as np\n'), ((7804, 7814), 'numpy.sqrt', 'np.sqrt', (['N'], {}), '(N)\n', (7811, 7814), True, 'import numpy as np\n'), ((7829, 7862), 'scipy.spatial.distance.cdist', 'distance.cdist', (['X', 'X', '"""euclidean"""'], {}), "(X, X, 'euclidean')\n", (7843, 7862), False, 'from scipy.spatial import distance\n'), ((11552, 11566), 'numpy.diag', 'np.diag', (['KW', '(1)'], {}), '(KW, 1)\n', (11559, 11566), True, 'import numpy as np\n'), ((11640, 11654), 'numpy.diag', 'np.diag', (['KW', '(1)'], {}), '(KW, 1)\n', (11647, 11654), True, 'import numpy as np\n'), ((1245, 1260), 'numpy.ones', 'np.ones', (['(NC - 1)'], {}), '(NC - 1)\n', (1252, 1260), True, 'import numpy as np\n'), ((3151, 3163), 'numpy.dot', 'np.dot', (['x', 'x'], {}), '(x, x)\n', (3157, 3163), True, 'import numpy as np\n'), ((3302, 3314), 'numpy.dot', 'np.dot', (['w', 'w'], {}), '(w, w)\n', (3308, 3314), True, 'import numpy as np\n'), ((5196, 5226), 'numpy.where', 'np.where', (['(medmed_dst[i, :] < T)'], {}), '(medmed_dst[i, :] < T)\n', (5204, 5226), True, 'import numpy as np\n'), ((6097, 6124), 'numpy.logical_not', 'np.logical_not', (['filter_mask'], {}), '(filter_mask)\n', (6111, 6124), True, 'import numpy as np\n'), ((6130, 6157), 'numpy.logical_not', 'np.logical_not', (['filter_mask'], {}), '(filter_mask)\n', (6144, 6157), True, 'import numpy as np\n'), ((8388, 8399), 'numpy.ones', 'np.ones', (['NC'], {}), '(NC)\n', (8395, 8399), True, 'import numpy as np\n'), ((8444, 8459), 'numpy.ones', 'np.ones', (['(NC - 1)'], {}), '(NC - 1)\n', (8451, 8459), True, 'import numpy as np\n'), ((8657, 8677), 'numpy.linalg.eigvals', 'np.linalg.eigvals', (['A'], {}), '(A)\n', (8674, 8677), True, 'import numpy as np\n'), ((8784, 8797), 'numpy.log', 'np.log', (['lambd'], {}), '(lambd)\n', (8790, 8797), True, 'import numpy as np\n'), ((9018, 9035), 'numpy.matmul', 'np.matmul', (['B.T', 'B'], {}), '(B.T, B)\n', (9027, 9035), True, 'import numpy as np\n'), ((11517, 11528), 'numpy.diag', 'np.diag', (['KW'], {}), '(KW)\n', (11524, 11528), True, 'import numpy as np\n'), ((11534, 11545), 'numpy.diag', 'np.diag', (['KW'], {}), '(KW)\n', (11541, 11545), True, 'import numpy as np\n'), ((8414, 8429), 'numpy.ones', 'np.ones', (['(NC - 1)'], {}), '(NC - 1)\n', (8421, 8429), True, 'import numpy as np\n'), ((11419, 11430), 'numpy.diag', 'np.diag', (['KX'], {}), '(KX)\n', (11426, 11430), True, 'import numpy as np\n'), ((11465, 11476), 'numpy.diag', 'np.diag', (['KW'], {}), '(KW)\n', (11472, 11476), True, 'import numpy as np\n'), ((11608, 11619), 'numpy.diag', 'np.diag', (['KW'], {}), '(KW)\n', (11615, 11619), True, 'import numpy as np\n'), ((8952, 8970), 'numpy.linalg.pinv', 'np.linalg.pinv', (['AW'], {}), '(AW)\n', (8966, 8970), True, 'import numpy as np\n'), ((9815, 9827), 'numpy.dot', 'np.dot', (['w', 'w'], {}), '(w, w)\n', (9821, 9827), True, 'import numpy as np\n'), ((9827, 9847), 'numpy.dot', 'np.dot', (['w_nxt', 'w_nxt'], {}), '(w_nxt, w_nxt)\n', (9833, 9847), True, 'import numpy as np\n'), ((9849, 9865), 'numpy.dot', 'np.dot', (['w', 'w_nxt'], {}), '(w, w_nxt)\n', (9855, 9865), True, 'import numpy as np\n'), ((11772, 11790), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (11780, 11790), True, 'import numpy as np\n'), ((8860, 8878), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (8868, 8878), True, 'import numpy as np\n')]
import torch import torch.nn as nn from torch.autograd import Variable import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F from torch.optim import lr_scheduler import numpy as np import contextlib import math from medseg.models.segmentation_models.unet import UNet from medseg.common_utils.basic_operations import check_dir # Partially based on: https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/python/training/moving_averages.py class ExponentialMovingAverage: """ Maintains (exponential) moving average of a set of parameters. """ def __init__(self, parameters, decay, use_num_updates=True): """ Args: parameters: Iterable of `torch.nn.Parameter`; usually the result of `model.parameters()`. decay: The exponential decay. use_num_updates: Whether to use number of updates when computing averages. """ if decay < 0.0 or decay > 1.0: raise ValueError('Decay must be between 0 and 1') self.decay = decay self.num_updates = 0 if use_num_updates else None self.shadow_params = [p.clone().detach() for p in parameters if p.requires_grad] self.collected_params = [] def update(self, parameters): """ Update currently maintained parameters. Call this every time the parameters are updated, such as the result of the `optimizer.step()` call. Args: parameters: Iterable of `torch.nn.Parameter`; usually the same set of parameters used to initialize this object. """ decay = self.decay if self.num_updates is not None: self.num_updates += 1 decay = min(decay, (1 + self.num_updates) / (10 + self.num_updates)) one_minus_decay = 1.0 - decay with torch.no_grad(): parameters = [p for p in parameters if p.requires_grad] for s_param, param in zip(self.shadow_params, parameters): s_param.sub_(one_minus_decay * (s_param - param)) def copy_to(self, parameters): """ Copy current parameters into given collection of parameters. Args: parameters: Iterable of `torch.nn.Parameter`; the parameters to be updated with the stored moving averages. """ for s_param, param in zip(self.shadow_params, parameters): if param.requires_grad: param.data.copy_(s_param.data) def store(self, parameters): """ Save the current parameters for restoring later. Args: parameters: Iterable of `torch.nn.Parameter`; the parameters to be temporarily stored. """ self.collected_params = [param.clone() for param in parameters if param.requires_grad] def restore(self, parameters): """ Restore the parameters stored with the `store` method. Useful to validate the model with EMA parameters without affecting the original optimization process. Store the parameters before the `copy_to` method. After validation (or model saving), use this to restore the former parameters. Args: parameters: Iterable of `torch.nn.Parameter`; the parameters to be updated with the stored parameters. """ if len(self.collected_params) > 0: for c_param, param in zip(self.collected_params, parameters): if param.requires_grad: param.data.copy_(c_param.data) else: print('did not find any copy, use the original params') def cross_entropy_2D(input, target, weight=None, size_average=True): n, c, h, w = input.size() log_p = F.log_softmax(input, dim=1) log_p = log_p.transpose(1, 2).transpose(2, 3).contiguous().view(-1, c) if len(target.size()) == 3: target = target.view(target.numel()) if not weight is None: # sum(weight) =C, for numerical stability. weight = torch.softmax(weight, dim=0) * c loss = F.nll_loss(log_p, target, weight=weight, reduction='sum') if size_average: loss /= float(target.numel() + 1e-10) elif len(target.size()) == 4: # ce loss=-qlog(p) reference = F.softmax(target, dim=1) # M,C reference = reference.transpose(1, 2).transpose( 2, 3).contiguous().view(-1, c) # M,C if weight is None: plogq = torch.mean(torch.mean(reference * log_p, dim=1)) else: # sum(weight) =C weight = torch.softmax(weight, dim=0) * c plogq_class_wise = reference * log_p plogq_sum_class = 0. for i in range(plogq_class_wise.size(1)): plogq_sum_class += torch.mean( plogq_class_wise[:, i] * weight[i]) plogq = plogq_sum_class loss = -1 * plogq else: raise NotImplementedError return loss def clip_grad(optimizer): # https://github.com/rosinality/igebm-pytorch/blob/master/train.py # clip the gradient of parameters before optimization. with torch.no_grad(): for group in optimizer.param_groups: for p in group['params']: state = optimizer.state[p] if 'step' not in state or state['step'] < 1: continue step = state['step'] exp_avg_sq = state['exp_avg_sq'] _, beta2 = group['betas'] bound = 3 * torch.sqrt(exp_avg_sq / (1 - beta2 ** step)) + 0.1 p.grad.data.copy_( torch.max(torch.min(p.grad.data, bound), -bound)) def set_model_grad(model, state=False): assert model for p in model.parameters(): # reset requires_grad p.requires_grad = state def set_grad(module, requires_grad=False): for p in module.parameters(): # reset requires_grad p.requires_grad = requires_grad def make_one_hot(y, num_classes=4): batch_size, h, w = y.size(0), y.size(1), y.size(2) flatten_y = y.view(batch_size * h * w, 1) y_onehot = torch.zeros(batch_size * h * w, num_classes, dtype=torch.float32, device=y.device) y_onehot.scatter_(1, flatten_y, 1) y_onehot = y_onehot.view(batch_size, h, w, num_classes) y_onehot = y_onehot.permute(0, 3, 1, 2) y_onehot.requires_grad = False return y_onehot def mask_latent_code_channel_wise(latent_code, decoder_function, label, num_classes=2, percentile=1 / 3.0, random=False, loss_type='corr', if_detach=True, if_soft=False): """ given a latent code return a perturbed code where top % channels are masked Args: latent_code (torch tensor): latent code, z_i or z_s decoder_function (nn.module): a specific decoder function, which maps the latent code to the output space/image space label (torch tensor): targeted output, e.g. image or segmentation label num_classes (int): number of segmentation classes (incl. background), only used when 'label' is a labelmap percentile (float, optional): percentile of masked codes. Defaults to 1/3.0. random (bool, optional): if set to true, then randomly draw a threshold from (0,percentile) to mask. Defaults to False. loss_type (str, optional): name of the loss function. Defaults to 'corr'. if_detach (bool, optional): if false, will directly apply masking to the original code. Defaults to True. if_soft (bool, optional): if true, perform soft masking instead of hard masking. Defaults to False. Returns: [type]: [description] """ ''' ''' use_gpu = True if latent_code.device != torch.device('cpu') else False code = makeVariable(latent_code, use_gpu=use_gpu, type='float', requires_grad=True) feature_channels = code.size(1) num_images = code.size(0) if len(label.size()) < len(code.size()): gt_y = make_one_hot(label, num_classes) else: gt_y = label if loss_type == 'corr': # self-challenging algorithm uses the correlation/similarity loss loss = torch.mean(decoder_function(code) * gt_y) elif loss_type == 'mse': loss = torch.mean((decoder_function(code) - gt_y)**2) elif loss_type == 'ce': logit = decoder_function(code) loss = cross_entropy_2D(input=logit, target=label, weight=None, size_average=True) loss = torch.mean(loss) gradient = torch.autograd.grad(loss, [code])[0] gradient_channel_mean = torch.mean( gradient.view(num_images, feature_channels, -1), dim=2) # select the threshold at top XX percentile # random percentile if random: percentile = np.random.rand() * percentile vector_thresh_percent = int(feature_channels * percentile) vector_thresh_value = torch.sort(gradient_channel_mean, dim=1, descending=True)[ 0][:, vector_thresh_percent] vector_thresh_value = vector_thresh_value.view( num_images, 1).expand(num_images, feature_channels) if if_soft: vector = torch.where(gradient_channel_mean > vector_thresh_value, 0.5 * torch.rand_like(gradient_channel_mean), torch.ones_like(gradient_channel_mean)) else: vector = torch.where(gradient_channel_mean > vector_thresh_value, torch.zeros_like(gradient_channel_mean), torch.ones_like(gradient_channel_mean)) mask_all = vector.view(num_images, feature_channels, 1, 1) if not if_detach: masked_latent_code = latent_code * mask_all else: masked_latent_code = code * mask_all try: decoder_function.zero_grad() except: pass return masked_latent_code, mask_all def mask_latent_code_spatial_wise(latent_code, decoder_function, label, num_classes, percentile=1 / 3.0, random=False, loss_type='corr', if_detach=True, if_soft=False): ''' given a latent code return a perturbed code where top % areas are masked ''' use_gpu = True if latent_code.device != torch.device('cpu') else False code = makeVariable(latent_code, use_gpu=use_gpu, type='float', requires_grad=True) num_images = code.size(0) spatial_size = code.size(2) * code.size(3) H, W = code.size(2), code.size(3) if len(label.size()) < len(code.size()): gt_y = make_one_hot(label, num_classes) else: gt_y = label if loss_type == 'corr': loss = torch.mean(decoder_function(code) * gt_y) elif loss_type == 'mse': loss = torch.mean((decoder_function(code) - gt_y)**2) elif loss_type == 'ce': logit = decoder_function(code) loss = cross_entropy_2D(input=logit, target=label, weight=None, size_average=True) loss = torch.mean(loss) gradient = torch.autograd.grad(loss, [code])[0] # mask gradient with largest response: spatial_mean = torch.mean(gradient, dim=1, keepdim=True) spatial_mean = spatial_mean.squeeze().view(num_images, spatial_size) # select the threshold at top XX percentile if random: percentile = np.random.rand() * percentile vector_thresh_percent = int(spatial_size * percentile) vector_thresh_value = torch.sort(spatial_mean, dim=1, descending=True)[ 0][:, vector_thresh_percent] vector_thresh_value = vector_thresh_value.view( num_images, 1).expand(num_images, spatial_size) if if_soft: vector = torch.where(spatial_mean > vector_thresh_value, 0.5 * torch.rand_like(spatial_mean), torch.ones_like(spatial_mean)) else: vector = torch.where(spatial_mean > vector_thresh_value, torch.zeros_like(spatial_mean), torch.ones_like(spatial_mean)) mask_all = vector.view(num_images, 1, H, W) if not if_detach: masked_latent_code = latent_code * mask_all else: masked_latent_code = code * mask_all try: decoder_function.zero_grad() except: pass return masked_latent_code, mask_all def get_unet_model(model_path, num_classes=2, device=None, model_arch='UNet_16'): ''' init model and load the trained parameters from the disk. model path: string. path to the model checkpoint device: torch device return pytorch nn.module model ''' assert check_dir(model_path) == 1, model_path + ' does not exists' if device is None: device = torch.device("cuda" if torch.cuda.is_available() else "cpu") if model_arch == 'UNet_16': model = UNet(input_channel=1, num_classes=num_classes, feature_scale=4) elif model_arch == 'UNet_64': model = UNet(input_channel=1, num_classes=num_classes, feature_scale=1) else: raise NotImplementedError model.load_state_dict(torch.load(model_path)) model = model.to(device) return model def filter_unlabelled_predictions(predictions, threshold=0.8): ''' given a batch of predictions, find the max prob for each pixel, if exceed the given threshhold return 1 else return 0 return: a batch of confidence maps NCHW, 0,1 ''' # find the maximum prob for each mask foreground_predictions = predictions.detach() max_prob_for_each_image = torch.max(foreground_predictions, dim=1)[0] max_prob_for_each_image = torch.clamp( max_prob_for_each_image - threshold, 0, 1) max_prob_for_each_image[foreground_predictions > 0] = 1 confidence_maps = max_prob_for_each_image.unsqueeze( 1).expand_as(predictions) return confidence_maps def sharpen_predictions(predictions, temperature=0.5): ''' shapen the predictions predictions: N*C*H*W: probabistic predictions (in mixmatch, this is an averaged value) ''' predictions = F.softmax(predictions, dim=1) calibrated_p = predictions**(1 / temperature) return calibrated_p / calibrated_p.sum(axis=1, keepdims=True) def stash_grad(model, grad_dict): for k, v in model.named_parameters(): if v.grad is not None: if k in grad_dict.keys(): grad_dict[k] += v.grad.clone() else: grad_dict[k] = v.grad.clone() model.zero_grad() #print ('gradient stashed') return grad_dict def restore_grad(model, grad_dict): for k, v in model.named_parameters(): if k in grad_dict.keys(): grad = grad_dict[k] if v.grad is None: v.grad = grad else: v.grad += grad #print ('gradient restored') def unit_norm(x, use_p_norm=False): # ## rescale abs_max = torch.max( torch.abs(x.view(x.size(0), -1)), 1, keepdim=True)[0].view( x.size(0), 1, 1, 1) x /= 1e-10 + abs_max # ## normalize if use_p_norm: batch_size = x.size(0) old_size = x.size() x = x.view(batch_size, -1) x = F.normalize(x, p=2, dim=1) x = x.view(old_size) return x @contextlib.contextmanager def _disable_tracking_bn_stats(model): def switch_attr(model, new_state=None, hist_states=None): """[summary] Args: model ([torch.nn.Module]): [description] new_state ([bool], optional): [description]. Defaults to None. hist_states ([type], optional): [description]. Defaults to None. Returns: [type]: [description] """ old_states = {} for name, module in model.named_modules(): if isinstance(module, torch.nn.BatchNorm2d): # print('here batch norm') old_states[name] = module.track_running_stats if hist_states is not None: module.track_running_stats = hist_states[name] # disable optimizing the beta and gamma for feature normalization if hasattr(module, 'weight'): module.weight.requires_grad_(hist_states[name]) if hasattr(module, 'bias'): module.bias.requires_grad_(hist_states[name]) else: if new_state is not None: module.track_running_stats = new_state if hasattr(module, 'weight'): module.weight.requires_grad_(new_state) if hasattr(module, 'bias'): module.bias.requires_grad_(new_state) return old_states old_states = switch_attr(model, False) yield switch_attr(model, hist_states=old_states) class SizeEstimator(object): def __init__(self, model, input_size=(1, 1, 32, 32), bits=32): ''' Estimates the size of PyTorch models in memory for a given input size ''' self.model = model self.input_size = input_size self.bits = 32 return def get_parameter_sizes(self): '''Get sizes of all parameters in `models`''' mods = list(self.model.modules()) sizes = [] for i in range(1, len(mods)): m = mods[i] p = list(m.parameters()) for j in range(len(p)): sizes.append(np.array(p[j].size())) self.param_sizes = sizes return def get_output_sizes(self): '''Run sample input through each layer to get output sizes''' input_ = Variable(torch.FloatTensor(*self.input_size), volatile=True) mods = list(self.model.modules()) out_sizes = [] for i in range(1, len(mods)): m = mods[i] out = m(input_) out_sizes.append(np.array(out.size())) input_ = out self.out_sizes = out_sizes return def calc_param_bits(self): '''Calculate total number of bits to store `models` parameters''' total_bits = 0 for i in range(len(self.param_sizes)): s = self.param_sizes[i] bits = np.prod(np.array(s)) * self.bits total_bits += bits self.param_bits = total_bits return def calc_forward_backward_bits(self): '''Calculate bits to store forward and backward pass''' total_bits = 0 for i in range(len(self.out_sizes)): s = self.out_sizes[i] bits = np.prod(np.array(s)) * self.bits total_bits += bits # multiply by 2 for both forward AND backward self.forward_backward_bits = (total_bits * 2) return def calc_input_bits(self): '''Calculate bits to store input''' self.input_bits = np.prod(np.array(self.input_size)) * self.bits return def estimate_size(self): '''Estimate models size in memory in megabytes and bits''' self.get_parameter_sizes() self.get_output_sizes() self.calc_param_bits() self.calc_forward_backward_bits() self.calc_input_bits() total = self.param_bits + self.forward_backward_bits + self.input_bits total_megabytes = (total / 8) / (1024 ** 2) return total_megabytes, total def save_model_to_file(model_name, model, epoch, optimizer, save_path): state_dict = model.module.state_dict() if isinstance( model, torch.nn.DataParallel) else model.state_dict() state = {'model_name': model_name, 'epoch': epoch + 1, 'model_state': state_dict, 'optimizer_state': optimizer.state_dict() } torch.save(state, save_path) def encode_3D(label_map, n_classes, use_gpu=False): ''' input label as tensor return onehot label N*D*H*W :param label: batch_size*target_z*target_h*target_w :return:label:batch_size*n_classes*target_z*target_h*target_w ''' # create one-hot vector for label map label_map = label_map[:, None, :, :, :] size = label_map.size() # print (size) oneHot_size = (size[0], n_classes, size[2], size[3], size[4]) input_label = torch.zeros(torch.Size(oneHot_size)).float() if use_gpu: input_label = input_label.cuda() input_label = input_label.scatter_(1, label_map.long().cuda(), 1.0) else: input_label = input_label input_label = input_label.scatter_(1, label_map.long(), 1.0) return input_label def encode_2D(label_map, n_classes, use_gpu=False): ''' input label as tensor N*H*W return onehot label N*C*H*W :return:label:batch_size*n_classes*target_z*target_h*target_w ''' # create one-hot vector for label map size = label_map[:, None, :, :].size() oneHot_size = (size[0], n_classes, size[2], size[3]) input_label = torch.zeros(torch.Size(oneHot_size)).float() if use_gpu: input_label = input_label.cuda() input_label = input_label.scatter_( 1, label_map[:, None, :, :].long().cuda(), 1.0) else: input_label = input_label input_label = input_label.scatter_( 1, label_map[:, None, :, :].long(), 1.0) return input_label def lr_poly(base_lr, iter, max_iter, power): return base_lr * ((1 - float(iter) / max_iter) ** (power)) def adjust_learning_rate(optimizer, i_iter, initial_learning_rate, total_steps, power=0.985): lr = lr_poly(initial_learning_rate, i_iter, total_steps, power) print('lr', lr) for param_group in optimizer.param_groups: param_group['lr'] = lr optimizer.param_groups[0]['lr'] = lr if len(optimizer.param_groups) > 1: optimizer.param_groups[1]['lr'] = lr * 10 def makeVariable(tensor, use_gpu=True, type='long', requires_grad=True): # conver type tensor = tensor.data if type == 'long': tensor = tensor.long() elif type == 'float': tensor = tensor.float() else: raise NotImplementedError # make is as Variable if use_gpu: variable = Variable(tensor.cuda(), requires_grad=requires_grad) else: variable = Variable(tensor, requires_grad=requires_grad) return variable def get_scheduler(optimizer, lr_policy, lr_decay_iters=5, epoch_count=None, niter=None, niter_decay=None): print('lr_policy = [{}]'.format(lr_policy)) if lr_policy == 'lambda': def lambda_rule(epoch): lr_l = 1.0 - max(0, epoch + 1 + epoch_count - niter) / float(niter_decay + 1) return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) elif lr_policy == 'step': scheduler = lr_scheduler.StepLR( optimizer, step_size=lr_decay_iters, gamma=0.5) elif lr_policy == 'step2': scheduler = lr_scheduler.StepLR( optimizer, step_size=lr_decay_iters, gamma=0.1) elif lr_policy == 'plateau': print('schedular=plateau') scheduler = lr_scheduler.ReduceLROnPlateau( optimizer, mode='min', factor=0.1, threshold=0.01, patience=5) elif lr_policy == 'plateau2': scheduler = lr_scheduler.ReduceLROnPlateau( optimizer, mode='min', factor=0.2, threshold=0.01, patience=5) elif lr_policy == 'step_warmstart': def lambda_rule(epoch): # print(epoch) if epoch < 5: lr_l = 0.1 elif 5 <= epoch < 100: lr_l = 1 elif 100 <= epoch < 200: lr_l = 0.1 elif 200 <= epoch: lr_l = 0.01 return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) elif lr_policy == 'step_warmstart2': def lambda_rule(epoch): # print(epoch) if epoch < 5: lr_l = 0.1 elif 5 <= epoch < 50: lr_l = 1 elif 50 <= epoch < 100: lr_l = 0.1 elif 100 <= epoch: lr_l = 0.01 return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) else: return NotImplementedError('learning rate policy [%s] is not implemented', lr_policy) return scheduler class HookBasedFeatureExtractor(nn.Module): def __init__(self, submodule, layername, upscale=False): super(HookBasedFeatureExtractor, self).__init__() self.submodule = submodule self.submodule.eval() self.layername = layername self.outputs_size = None self.outputs = None self.inputs = None self.inputs_size = None self.upscale = upscale def get_input_array(self, m, i, o): if isinstance(i, tuple): self.inputs = [i[index].data.clone() for index in range(len(i))] self.inputs_size = [input.size() for input in self.inputs] else: self.inputs = i.data.clone() self.inputs_size = self.input.size() print('Input Array Size: ', self.inputs_size) def get_output_array(self, m, i, o): if isinstance(o, tuple): self.outputs = [o[index].data.clone() for index in range(len(o))] self.outputs_size = [output.size() for output in self.outputs] else: self.outputs = o.data.clone() self.outputs_size = self.outputs.size() print('Output Array Size: ', self.outputs_size) def rescale_output_array(self, newsize): us = nn.Upsample(size=newsize[2:], mode='bilinear') if isinstance(self.outputs, list): for index in range(len(self.outputs)): self.outputs[index] = us(self.outputs[index]).data() else: self.outputs = us(self.outputs).data() def forward(self, x): target_layer = self.submodule._modules.get(self.layername) # Collect the output tensor h_inp = target_layer.register_forward_hook(self.get_input_array) h_out = target_layer.register_forward_hook(self.get_output_array) self.submodule(x) h_inp.remove() h_out.remove() # Rescale the feature-map if it's required if self.upscale: self.rescale_output_array(x.size()) return self.inputs, self.outputs
[ "medseg.models.segmentation_models.unet.UNet", "torch.optim.lr_scheduler.LambdaLR", "numpy.random.rand", "torch.max", "torch.sqrt", "torch.min", "torch.softmax", "numpy.array", "torch.cuda.is_available", "torch.nn.functional.softmax", "torch.nn.functional.nll_loss", "torch.mean", "medseg.com...
[((3932, 3959), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['input'], {'dim': '(1)'}), '(input, dim=1)\n', (3945, 3959), True, 'import torch.nn.functional as F\n'), ((6332, 6419), 'torch.zeros', 'torch.zeros', (['(batch_size * h * w)', 'num_classes'], {'dtype': 'torch.float32', 'device': 'y.device'}), '(batch_size * h * w, num_classes, dtype=torch.float32, device=y.\n device)\n', (6343, 6419), False, 'import torch\n'), ((11291, 11332), 'torch.mean', 'torch.mean', (['gradient'], {'dim': '(1)', 'keepdim': '(True)'}), '(gradient, dim=1, keepdim=True)\n', (11301, 11332), False, 'import torch\n'), ((13769, 13823), 'torch.clamp', 'torch.clamp', (['(max_prob_for_each_image - threshold)', '(0)', '(1)'], {}), '(max_prob_for_each_image - threshold, 0, 1)\n', (13780, 13823), False, 'import torch\n'), ((14220, 14249), 'torch.nn.functional.softmax', 'F.softmax', (['predictions'], {'dim': '(1)'}), '(predictions, dim=1)\n', (14229, 14249), True, 'import torch.nn.functional as F\n'), ((19936, 19964), 'torch.save', 'torch.save', (['state', 'save_path'], {}), '(state, save_path)\n', (19946, 19964), False, 'import torch\n'), ((4268, 4325), 'torch.nn.functional.nll_loss', 'F.nll_loss', (['log_p', 'target'], {'weight': 'weight', 'reduction': '"""sum"""'}), "(log_p, target, weight=weight, reduction='sum')\n", (4278, 4325), True, 'import torch.nn.functional as F\n'), ((5342, 5357), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5355, 5357), False, 'import torch\n'), ((8747, 8780), 'torch.autograd.grad', 'torch.autograd.grad', (['loss', '[code]'], {}), '(loss, [code])\n', (8766, 8780), False, 'import torch\n'), ((11192, 11225), 'torch.autograd.grad', 'torch.autograd.grad', (['loss', '[code]'], {}), '(loss, [code])\n', (11211, 11225), False, 'import torch\n'), ((12784, 12805), 'medseg.common_utils.basic_operations.check_dir', 'check_dir', (['model_path'], {}), '(model_path)\n', (12793, 12805), False, 'from medseg.common_utils.basic_operations import check_dir\n'), ((12994, 13057), 'medseg.models.segmentation_models.unet.UNet', 'UNet', ([], {'input_channel': '(1)', 'num_classes': 'num_classes', 'feature_scale': '(4)'}), '(input_channel=1, num_classes=num_classes, feature_scale=4)\n', (12998, 13057), False, 'from medseg.models.segmentation_models.unet import UNet\n'), ((13242, 13264), 'torch.load', 'torch.load', (['model_path'], {}), '(model_path)\n', (13252, 13264), False, 'import torch\n'), ((13695, 13735), 'torch.max', 'torch.max', (['foreground_predictions'], {'dim': '(1)'}), '(foreground_predictions, dim=1)\n', (13704, 13735), False, 'import torch\n'), ((15352, 15378), 'torch.nn.functional.normalize', 'F.normalize', (['x'], {'p': '(2)', 'dim': '(1)'}), '(x, p=2, dim=1)\n', (15363, 15378), True, 'import torch.nn.functional as F\n'), ((22399, 22444), 'torch.autograd.Variable', 'Variable', (['tensor'], {'requires_grad': 'requires_grad'}), '(tensor, requires_grad=requires_grad)\n', (22407, 22444), False, 'from torch.autograd import Variable\n'), ((22847, 22902), 'torch.optim.lr_scheduler.LambdaLR', 'lr_scheduler.LambdaLR', (['optimizer'], {'lr_lambda': 'lambda_rule'}), '(optimizer, lr_lambda=lambda_rule)\n', (22868, 22902), False, 'from torch.optim import lr_scheduler\n'), ((25765, 25811), 'torch.nn.Upsample', 'nn.Upsample', ([], {'size': 'newsize[2:]', 'mode': '"""bilinear"""'}), "(size=newsize[2:], mode='bilinear')\n", (25776, 25811), True, 'import torch.nn as nn\n'), ((1957, 1972), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1970, 1972), False, 'import torch\n'), ((4482, 4506), 'torch.nn.functional.softmax', 'F.softmax', (['target'], {'dim': '(1)'}), '(target, dim=1)\n', (4491, 4506), True, 'import torch.nn.functional as F\n'), ((7923, 7942), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (7935, 7942), False, 'import torch\n'), ((8996, 9012), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (9010, 9012), True, 'import numpy as np\n'), ((9115, 9172), 'torch.sort', 'torch.sort', (['gradient_channel_mean'], {'dim': '(1)', 'descending': '(True)'}), '(gradient_channel_mean, dim=1, descending=True)\n', (9125, 9172), False, 'import torch\n'), ((9519, 9557), 'torch.ones_like', 'torch.ones_like', (['gradient_channel_mean'], {}), '(gradient_channel_mean)\n', (9534, 9557), False, 'import torch\n'), ((9672, 9711), 'torch.zeros_like', 'torch.zeros_like', (['gradient_channel_mean'], {}), '(gradient_channel_mean)\n', (9688, 9711), False, 'import torch\n'), ((9742, 9780), 'torch.ones_like', 'torch.ones_like', (['gradient_channel_mean'], {}), '(gradient_channel_mean)\n', (9757, 9780), False, 'import torch\n'), ((10395, 10414), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (10407, 10414), False, 'import torch\n'), ((11491, 11507), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (11505, 11507), True, 'import numpy as np\n'), ((11607, 11655), 'torch.sort', 'torch.sort', (['spatial_mean'], {'dim': '(1)', 'descending': '(True)'}), '(spatial_mean, dim=1, descending=True)\n', (11617, 11655), False, 'import torch\n'), ((11980, 12009), 'torch.ones_like', 'torch.ones_like', (['spatial_mean'], {}), '(spatial_mean)\n', (11995, 12009), False, 'import torch\n'), ((12115, 12145), 'torch.zeros_like', 'torch.zeros_like', (['spatial_mean'], {}), '(spatial_mean)\n', (12131, 12145), False, 'import torch\n'), ((12176, 12205), 'torch.ones_like', 'torch.ones_like', (['spatial_mean'], {}), '(spatial_mean)\n', (12191, 12205), False, 'import torch\n'), ((13108, 13171), 'medseg.models.segmentation_models.unet.UNet', 'UNet', ([], {'input_channel': '(1)', 'num_classes': 'num_classes', 'feature_scale': '(1)'}), '(input_channel=1, num_classes=num_classes, feature_scale=1)\n', (13112, 13171), False, 'from medseg.models.segmentation_models.unet import UNet\n'), ((17858, 17893), 'torch.FloatTensor', 'torch.FloatTensor', (['*self.input_size'], {}), '(*self.input_size)\n', (17875, 17893), False, 'import torch\n'), ((22953, 23020), 'torch.optim.lr_scheduler.StepLR', 'lr_scheduler.StepLR', (['optimizer'], {'step_size': 'lr_decay_iters', 'gamma': '(0.5)'}), '(optimizer, step_size=lr_decay_iters, gamma=0.5)\n', (22972, 23020), False, 'from torch.optim import lr_scheduler\n'), ((4220, 4248), 'torch.softmax', 'torch.softmax', (['weight'], {'dim': '(0)'}), '(weight, dim=0)\n', (4233, 4248), False, 'import torch\n'), ((8714, 8730), 'torch.mean', 'torch.mean', (['loss'], {}), '(loss)\n', (8724, 8730), False, 'import torch\n'), ((9450, 9488), 'torch.rand_like', 'torch.rand_like', (['gradient_channel_mean'], {}), '(gradient_channel_mean)\n', (9465, 9488), False, 'import torch\n'), ((11159, 11175), 'torch.mean', 'torch.mean', (['loss'], {}), '(loss)\n', (11169, 11175), False, 'import torch\n'), ((11920, 11949), 'torch.rand_like', 'torch.rand_like', (['spatial_mean'], {}), '(spatial_mean)\n', (11935, 11949), False, 'import torch\n'), ((12907, 12932), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (12930, 12932), False, 'import torch\n'), ((19064, 19089), 'numpy.array', 'np.array', (['self.input_size'], {}), '(self.input_size)\n', (19072, 19089), True, 'import numpy as np\n'), ((20444, 20467), 'torch.Size', 'torch.Size', (['oneHot_size'], {}), '(oneHot_size)\n', (20454, 20467), False, 'import torch\n'), ((21119, 21142), 'torch.Size', 'torch.Size', (['oneHot_size'], {}), '(oneHot_size)\n', (21129, 21142), False, 'import torch\n'), ((23085, 23152), 'torch.optim.lr_scheduler.StepLR', 'lr_scheduler.StepLR', (['optimizer'], {'step_size': 'lr_decay_iters', 'gamma': '(0.1)'}), '(optimizer, step_size=lr_decay_iters, gamma=0.1)\n', (23104, 23152), False, 'from torch.optim import lr_scheduler\n'), ((4679, 4715), 'torch.mean', 'torch.mean', (['(reference * log_p)'], {'dim': '(1)'}), '(reference * log_p, dim=1)\n', (4689, 4715), False, 'import torch\n'), ((4781, 4809), 'torch.softmax', 'torch.softmax', (['weight'], {'dim': '(0)'}), '(weight, dim=0)\n', (4794, 4809), False, 'import torch\n'), ((4985, 5031), 'torch.mean', 'torch.mean', (['(plogq_class_wise[:, i] * weight[i])'], {}), '(plogq_class_wise[:, i] * weight[i])\n', (4995, 5031), False, 'import torch\n'), ((18431, 18442), 'numpy.array', 'np.array', (['s'], {}), '(s)\n', (18439, 18442), True, 'import numpy as np\n'), ((18775, 18786), 'numpy.array', 'np.array', (['s'], {}), '(s)\n', (18783, 18786), True, 'import numpy as np\n'), ((23254, 23352), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'lr_scheduler.ReduceLROnPlateau', (['optimizer'], {'mode': '"""min"""', 'factor': '(0.1)', 'threshold': '(0.01)', 'patience': '(5)'}), "(optimizer, mode='min', factor=0.1, threshold\n =0.01, patience=5)\n", (23284, 23352), False, 'from torch.optim import lr_scheduler\n'), ((5733, 5777), 'torch.sqrt', 'torch.sqrt', (['(exp_avg_sq / (1 - beta2 ** step))'], {}), '(exp_avg_sq / (1 - beta2 ** step))\n', (5743, 5777), False, 'import torch\n'), ((5849, 5878), 'torch.min', 'torch.min', (['p.grad.data', 'bound'], {}), '(p.grad.data, bound)\n', (5858, 5878), False, 'import torch\n'), ((23415, 23513), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'lr_scheduler.ReduceLROnPlateau', (['optimizer'], {'mode': '"""min"""', 'factor': '(0.2)', 'threshold': '(0.01)', 'patience': '(5)'}), "(optimizer, mode='min', factor=0.2, threshold\n =0.01, patience=5)\n", (23445, 23513), False, 'from torch.optim import lr_scheduler\n'), ((23901, 23956), 'torch.optim.lr_scheduler.LambdaLR', 'lr_scheduler.LambdaLR', (['optimizer'], {'lr_lambda': 'lambda_rule'}), '(optimizer, lr_lambda=lambda_rule)\n', (23922, 23956), False, 'from torch.optim import lr_scheduler\n'), ((24335, 24390), 'torch.optim.lr_scheduler.LambdaLR', 'lr_scheduler.LambdaLR', (['optimizer'], {'lr_lambda': 'lambda_rule'}), '(optimizer, lr_lambda=lambda_rule)\n', (24356, 24390), False, 'from torch.optim import lr_scheduler\n')]
"""Generates sets of testing indices for the galaxy classification task. <NAME> The Australian National University 2016 """ import argparse import h5py import numpy from .config import config ATLAS_WIDTH = config['surveys']['atlas']['fits_width'] ATLAS_HEIGHT = config['surveys']['atlas']['fits_height'] ATLAS_SIZE = ATLAS_WIDTH * ATLAS_HEIGHT def get_nearby_galaxies(atlas_vector, radius=1/60): """Gets all nearby galaxy IDs. atlas_vector: crowdastro ATLAS vector. radius: Radius to call a galaxy "nearby", in degrees. Default 1 arcmin. -> list of ints """ return (atlas_vector[2 + ATLAS_SIZE:] <= radius).nonzero()[0] def main(c_h5, t_h5, n, p, add=False, field='cdfs'): ir_survey = c_h5.attrs['ir_survey'] ir_survey_ = t_h5.attrs['ir_survey'] assert ir_survey == ir_survey_ if '/{}/{}/test_sets'.format(ir_survey, field) in c_h5 and not add: raise ValueError('Test sets already exist.') candidates = [] for atlas_id, atlas in enumerate(c_h5['/atlas/{}/numeric'.format(field)]): candidates.append(atlas_id) n_atlas = c_h5['/atlas/{}/numeric'.format(field)].shape[0] # Generate the test sets. test_sets = [] if add: for test_set in c_h5['/{}/{}/test_sets'.format(ir_survey, field)].value: test_sets.append(list(test_set)) assert len(test_sets) == c_h5['/{}/{}/test_sets'.format( ir_survey, field)].shape[0] for i in range(n): # Select at random, without replacement, candidate ATLAS objects. candidates_ = list(set(candidates)) numpy.random.shuffle(candidates_) atlas_test_set = [] for atlas_id in candidates_: if len(atlas_test_set) >= int(n_atlas * p): break atlas_test_set.append(atlas_id) # Get all nearby galaxies and add all nearby galaxies to the test set. test_set = [] for atlas_id in atlas_test_set: nearby = get_nearby_galaxies( c_h5['/atlas/{}/numeric'.format(field)][atlas_id]) test_set.extend(nearby) test_set = sorted(set(test_set)) if test_sets: assert test_sets[-1] != test_set[:len(test_sets[-1])] test_sets.append(test_set) # Because the test sets are galaxy-based but the drawing was radio-based, # we may have unequal length lists, so we'll crop them. min_length = min(len(test_set) for test_set in test_sets) test_sets_ = [] for test_set in test_sets: # Have to reshuffle so we don't bias against later IDs. numpy.random.shuffle(test_set) test_sets_.append(sorted(test_set[:min_length])) test_sets = numpy.array(test_sets_) if add: del c_h5['/{}/{}/test_sets'.format(ir_survey, field)] del t_h5['test_sets'] c_h5.create_dataset('/{}/{}/test_sets'.format(ir_survey, field), data=test_sets) t_h5.create_dataset('test_sets', data=test_sets) def _populate_parser(parser): parser.description = 'Generates sets of testing indices for the galaxy ' \ 'classification task.' parser.add_argument('--crowdastro', default='data/crowdastro.h5', help='Crowdastro HDF5 file') parser.add_argument('--training', default='data/training.h5', help='Training HDF5 file') parser.add_argument('--n', default=5, type=int, help='Number of test sets') parser.add_argument('--p', default=0.5, type=float, help='Percentage size of test sets') parser.add_argument('--field', default='cdfs', help='ATLAS field', choices=('cdfs', 'elais')) parser.add_argument('--add', action='store_true', help='Add new test sets to existing test sets') def _main(args): with h5py.File(args.crowdastro, 'r+') as c_h5: with h5py.File(args.training, 'r+') as t_h5: main(c_h5, t_h5, args.n, args.p, add=args.add, field=args.field) if __name__ == '__main__': parser = argparse.ArgumentParser() _populate_parser(parser) args = parser.parse_args() _main(args)
[ "numpy.array", "h5py.File", "argparse.ArgumentParser", "numpy.random.shuffle" ]
[((2699, 2722), 'numpy.array', 'numpy.array', (['test_sets_'], {}), '(test_sets_)\n', (2710, 2722), False, 'import numpy\n'), ((4099, 4124), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4122, 4124), False, 'import argparse\n'), ((1596, 1629), 'numpy.random.shuffle', 'numpy.random.shuffle', (['candidates_'], {}), '(candidates_)\n', (1616, 1629), False, 'import numpy\n'), ((2594, 2624), 'numpy.random.shuffle', 'numpy.random.shuffle', (['test_set'], {}), '(test_set)\n', (2614, 2624), False, 'import numpy\n'), ((3885, 3917), 'h5py.File', 'h5py.File', (['args.crowdastro', '"""r+"""'], {}), "(args.crowdastro, 'r+')\n", (3894, 3917), False, 'import h5py\n'), ((3940, 3970), 'h5py.File', 'h5py.File', (['args.training', '"""r+"""'], {}), "(args.training, 'r+')\n", (3949, 3970), False, 'import h5py\n')]