code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import math import numpy as _np import numba as _numba import contextlib @contextlib.contextmanager def corrfunction(shape, z, qmax, xcenter=None, ycenter=None): """ CPU based radial Autocorrelation with q correction parameters: shape (tuple) of inputs in pixels z (scalar) distance of detector in pixels qmax (scalar): maximum distance optional xcenter (scalar): position of center in x direction, defaults to shape[0]/2 ycenter (scalar): position of center in x direction, defaults to shape[1]/2 returns a function with signature float[:](float[:,:] image) that does the correlation """ xcenter = xcenter or shape[0] / 2.0 ycenter = ycenter or shape[1] / 2.0 y, x = _np.meshgrid(_np.arange(shape[1], dtype=_np.float64), _np.arange(shape[0], dtype=_np.float64)) x -= xcenter y -= ycenter d = _np.sqrt(x ** 2 + y ** 2 + z ** 2) qx, qy, qz = [(k / d * z) for k in (x, y, z)] del x, y, d def inner(input, qx, qy, qz): out = _np.zeros((shape[0] + 10, qmax), dtype=_np.float64) for refx in _numba.prange(shape[0]): for refy in range(shape[1]): qxr = qx[refx, refy] qyr = qy[refx, refy] qzr = qz[refx, refy] refv = input[refx, refy] for direction in range(2): dqx = 0 x = refx + direction # dont dx=0 it twice while -qmax <= dqx <= qmax and 0 <= x < input.shape[0]: dqy = 0 y = refy while dqy <= qmax and 0 <= y < input.shape[1]: dq = (qx[x, y] - qxr) ** 2 + (qy[x, y] - qyr) ** 2 + (qz[x, y] - qzr) ** 2 qsave = int(round(math.sqrt(dq))) if qsave >= qmax: break val = refv * input[x, y] out[refx, qsave] += val y += 1 x += -1 + 2 * direction return out finner = _numba.njit(inner, parallel=True, fastmath=True).compile("float64[:,:](float64[:,:],float64[:,:],float64[:,:],float64[:,:])") def corr(input): """ Do the correlation """ if finner is None: raise ValueError("already closed, use within with statement") input = _np.asarray(input).astype(_np.float64, copy=False) if not all(i == s for (i, s) in zip(input.shape, shape)): raise ValueError("not the same shape") return _np.sum(finner(input, qx, qy, qz), axis=0) yield corr qx = qy = qz = finner = shape = None for x in locals(): del x
[ "numpy.sqrt", "numba.njit", "numpy.asarray", "math.sqrt", "numpy.zeros", "numba.prange", "numpy.arange" ]
[((864, 898), 'numpy.sqrt', '_np.sqrt', (['(x ** 2 + y ** 2 + z ** 2)'], {}), '(x ** 2 + y ** 2 + z ** 2)\n', (872, 898), True, 'import numpy as _np\n'), ((740, 779), 'numpy.arange', '_np.arange', (['shape[1]'], {'dtype': '_np.float64'}), '(shape[1], dtype=_np.float64)\n', (750, 779), True, 'import numpy as _np\n'), ((781, 820), 'numpy.arange', '_np.arange', (['shape[0]'], {'dtype': '_np.float64'}), '(shape[0], dtype=_np.float64)\n', (791, 820), True, 'import numpy as _np\n'), ((1014, 1065), 'numpy.zeros', '_np.zeros', (['(shape[0] + 10, qmax)'], {'dtype': '_np.float64'}), '((shape[0] + 10, qmax), dtype=_np.float64)\n', (1023, 1065), True, 'import numpy as _np\n'), ((1086, 1109), 'numba.prange', '_numba.prange', (['shape[0]'], {}), '(shape[0])\n', (1099, 1109), True, 'import numba as _numba\n'), ((2120, 2168), 'numba.njit', '_numba.njit', (['inner'], {'parallel': '(True)', 'fastmath': '(True)'}), '(inner, parallel=True, fastmath=True)\n', (2131, 2168), True, 'import numba as _numba\n'), ((2436, 2454), 'numpy.asarray', '_np.asarray', (['input'], {}), '(input)\n', (2447, 2454), True, 'import numpy as _np\n'), ((1799, 1812), 'math.sqrt', 'math.sqrt', (['dq'], {}), '(dq)\n', (1808, 1812), False, 'import math\n')]
from builtins import zip # Gamma-ray burst afterglow metric # <EMAIL> import rubin_sim.maf.metrics as metrics import numpy as np __all__ = ['GRBTransientMetric'] class GRBTransientMetric(metrics.BaseMetric): """Detections for on-axis GRB afterglows decaying as F(t) = F(1min)((t-t0)/1min)^-alpha. No jet break, for now. Derived from TransientMetric, but calculated with reduce functions to enable-band specific counts. Burst parameters taken from 2011PASP..123.1034J. Simplifications: no color variation or evolution encoded yet. no jet breaks. not treating off-axis events. Parameters ---------- alpha : float, temporal decay index Default = 1.0 apparent_mag_1min_mean : float, mean magnitude at 1 minute after burst Default = 15.35 apparent_mag_1min_sigma : float, std of magnitudes at 1 minute after burst Default = 1.59 transDuration : float, optional How long the transient lasts (days). Default 10. surveyDuration : float, optional Length of survey (years). Default 10. surveyStart : float, optional MJD for the survey start date. Default None (uses the time of the first observation). detectM5Plus : float, optional An observation will be used if the light curve magnitude is brighter than m5+detectM5Plus. Default 0. nPerFilter : int, optional Number of separate detections of the light curve above the detectM5Plus theshold (in a single filter) for the light curve to be counted. Default 1. nFilters : int, optional Number of filters that need to be observed nPerFilter times, with differences minDeltaMag, for an object to be counted as detected. Default 1. minDeltaMag : float, optional magnitude difference between detections in the same filter required for second+ detection to be counted. For example, if minDeltaMag = 0.1 mag and two consecutive observations differ only by 0.05 mag, those two detections will only count as one. (Better would be a SNR-based discrimination of lightcurve change.) Default 0. nPhaseCheck : int, optional Sets the number of phases that should be checked. One can imagine pathological cadences where many objects pass the detection criteria, but would not if the observations were offset by a phase-shift. Default 1. """ def __init__(self, alpha=1, apparent_mag_1min_mean=15.35, apparent_mag_1min_sigma=1.59, metricName='GRBTransientMetric', mjdCol='expMJD', m5Col='fiveSigmaDepth', filterCol='filter', transDuration=10., surveyDuration=10., surveyStart=None, detectM5Plus=0., nPerFilter=1, nFilters=1, minDeltaMag=0., nPhaseCheck=1, **kwargs): self.mjdCol = mjdCol self.m5Col = m5Col self.filterCol = filterCol super( GRBTransientMetric, self).__init__( col=[self.mjdCol, self.m5Col, self.filterCol], units='Fraction Detected', metricName=metricName,**kwargs) self.alpha = alpha self.apparent_mag_1min_mean = apparent_mag_1min_mean self.apparent_mag_1min_sigma = apparent_mag_1min_sigma self.transDuration = transDuration self.surveyDuration = surveyDuration self.surveyStart = surveyStart self.detectM5Plus = detectM5Plus self.nPerFilter = nPerFilter self.nFilters = nFilters self.minDeltaMag = minDeltaMag self.nPhaseCheck = nPhaseCheck self.peakTime = 0. self.reduceOrder = {'Bandu':0, 'Bandg':1, 'Bandr':2, 'Bandi':3, 'Bandz':4, 'Bandy':5,'Band1FiltAvg':6,'BandanyNfilters':7} def lightCurve(self, time, filters): """ given the times and filters of an observation, return the magnitudes. """ lcMags = np.zeros(time.size, dtype=float) decline = np.where(time > self.peakTime) apparent_mag_1min = np.random.randn()*self.apparent_mag_1min_sigma + self.apparent_mag_1min_mean lcMags[decline] += apparent_mag_1min + self.alpha * 2.5 * np.log10((time[decline]-self.peakTime)*24.*60.) #for key in self.peaks.keys(): # fMatch = np.where(filters == key) # lcMags[fMatch] += self.peaks[key] return lcMags def run(self, dataSlice, slicePoint=None): """" Calculate the detectability of a transient with the specified lightcurve. Parameters ---------- dataSlice : numpy.array Numpy structured array containing the data related to the visits provided by the slicer. slicePoint : dict, optional Dictionary containing information about the slicepoint currently active in the slicer. Returns ------- float The total number of transients that could be detected. """ # Total number of transients that could go off back-to-back nTransMax = np.floor(self.surveyDuration / (self.transDuration / 365.25)) tshifts = np.arange(self.nPhaseCheck) * self.transDuration / float(self.nPhaseCheck) nDetected = 0 nTransMax = 0 for tshift in tshifts: # Compute the total number of back-to-back transients are possible to detect # given the survey duration and the transient duration. nTransMax += np.floor(self.surveyDuration / (self.transDuration / 365.25)) if tshift != 0: nTransMax -= 1 if self.surveyStart is None: surveyStart = dataSlice[self.mjdCol].min() time = (dataSlice[self.mjdCol] - surveyStart + tshift) % self.transDuration # Which lightcurve does each point belong to lcNumber = np.floor((dataSlice[self.mjdCol] - surveyStart) / self.transDuration) lcMags = self.lightCurve(time, dataSlice[self.filterCol]) # How many criteria needs to be passed detectThresh = 0 # Flag points that are above the SNR limit detected = np.zeros(dataSlice.size, dtype=int) detected[np.where(lcMags < dataSlice[self.m5Col] + self.detectM5Plus)] += 1 bandcounter={'u':0, 'g':0, 'r':0, 'i':0, 'z':0, 'y':0, 'any':0} #define zeroed out counter # make sure things are sorted by time ord = np.argsort(dataSlice[self.mjdCol]) dataSlice = dataSlice[ord] detected = detected[ord] lcNumber = lcNumber[ord] lcMags = lcMags[ord] ulcNumber = np.unique(lcNumber) left = np.searchsorted(lcNumber, ulcNumber) right = np.searchsorted(lcNumber, ulcNumber, side='right') detectThresh += self.nFilters # iterate over the lightcurves for le, ri in zip(left, right): wdet = np.where(detected[le:ri] > 0) ufilters = np.unique(dataSlice[self.filterCol][le:ri][wdet]) nfilts_lci = 0 for filtName in ufilters: wdetfilt = np.where( (dataSlice[self.filterCol][le:ri] == filtName) & detected[le:ri]) lcPoints = lcMags[le:ri][wdetfilt] dlc = np.abs(np.diff(lcPoints)) # number of detections in band, requring that for # nPerFilter > 1 that points have more than minDeltaMag # change nbanddet = np.sum(dlc > self.minDeltaMag) + 1 if nbanddet >= self.nPerFilter: bandcounter[filtName] += 1 nfilts_lci += 1 if nfilts_lci >= self.nFilters: bandcounter['any'] += 1 bandfraction = {} for band in bandcounter.keys(): bandfraction[band] = float(bandcounter[band]) / nTransMax return bandfraction def reduceBand1FiltAvg(self, bandfraction): "Average fraction detected in single filter" return np.mean(list(bandfraction.values())) def reduceBandanyNfilters(self, bandfraction): "Fraction of events detected in Nfilters or more" return bandfraction['any'] def reduceBandu(self, bandfraction): return bandfraction['u'] def reduceBandg(self, bandfraction): return bandfraction['g'] def reduceBandr(self, bandfraction): return bandfraction['r'] def reduceBandi(self, bandfraction): return bandfraction['i'] def reduceBandz(self, bandfraction): return bandfraction['z'] def reduceBandy(self, bandfraction): return bandfraction['y']
[ "numpy.log10", "numpy.unique", "numpy.where", "numpy.searchsorted", "numpy.floor", "numpy.diff", "numpy.argsort", "builtins.zip", "numpy.zeros", "numpy.sum", "numpy.random.randn", "numpy.arange" ]
[((4028, 4060), 'numpy.zeros', 'np.zeros', (['time.size'], {'dtype': 'float'}), '(time.size, dtype=float)\n', (4036, 4060), True, 'import numpy as np\n'), ((4080, 4110), 'numpy.where', 'np.where', (['(time > self.peakTime)'], {}), '(time > self.peakTime)\n', (4088, 4110), True, 'import numpy as np\n'), ((5151, 5212), 'numpy.floor', 'np.floor', (['(self.surveyDuration / (self.transDuration / 365.25))'], {}), '(self.surveyDuration / (self.transDuration / 365.25))\n', (5159, 5212), True, 'import numpy as np\n'), ((5563, 5624), 'numpy.floor', 'np.floor', (['(self.surveyDuration / (self.transDuration / 365.25))'], {}), '(self.surveyDuration / (self.transDuration / 365.25))\n', (5571, 5624), True, 'import numpy as np\n'), ((5953, 6022), 'numpy.floor', 'np.floor', (['((dataSlice[self.mjdCol] - surveyStart) / self.transDuration)'], {}), '((dataSlice[self.mjdCol] - surveyStart) / self.transDuration)\n', (5961, 6022), True, 'import numpy as np\n'), ((6254, 6289), 'numpy.zeros', 'np.zeros', (['dataSlice.size'], {'dtype': 'int'}), '(dataSlice.size, dtype=int)\n', (6262, 6289), True, 'import numpy as np\n'), ((6551, 6585), 'numpy.argsort', 'np.argsort', (['dataSlice[self.mjdCol]'], {}), '(dataSlice[self.mjdCol])\n', (6561, 6585), True, 'import numpy as np\n'), ((6756, 6775), 'numpy.unique', 'np.unique', (['lcNumber'], {}), '(lcNumber)\n', (6765, 6775), True, 'import numpy as np\n'), ((6795, 6831), 'numpy.searchsorted', 'np.searchsorted', (['lcNumber', 'ulcNumber'], {}), '(lcNumber, ulcNumber)\n', (6810, 6831), True, 'import numpy as np\n'), ((6852, 6902), 'numpy.searchsorted', 'np.searchsorted', (['lcNumber', 'ulcNumber'], {'side': '"""right"""'}), "(lcNumber, ulcNumber, side='right')\n", (6867, 6902), True, 'import numpy as np\n'), ((7015, 7031), 'builtins.zip', 'zip', (['left', 'right'], {}), '(left, right)\n', (7018, 7031), False, 'from builtins import zip\n'), ((4139, 4156), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (4154, 4156), True, 'import numpy as np\n'), ((4282, 4337), 'numpy.log10', 'np.log10', (['((time[decline] - self.peakTime) * 24.0 * 60.0)'], {}), '((time[decline] - self.peakTime) * 24.0 * 60.0)\n', (4290, 4337), True, 'import numpy as np\n'), ((5231, 5258), 'numpy.arange', 'np.arange', (['self.nPhaseCheck'], {}), '(self.nPhaseCheck)\n', (5240, 5258), True, 'import numpy as np\n'), ((6311, 6371), 'numpy.where', 'np.where', (['(lcMags < dataSlice[self.m5Col] + self.detectM5Plus)'], {}), '(lcMags < dataSlice[self.m5Col] + self.detectM5Plus)\n', (6319, 6371), True, 'import numpy as np\n'), ((7056, 7085), 'numpy.where', 'np.where', (['(detected[le:ri] > 0)'], {}), '(detected[le:ri] > 0)\n', (7064, 7085), True, 'import numpy as np\n'), ((7113, 7162), 'numpy.unique', 'np.unique', (['dataSlice[self.filterCol][le:ri][wdet]'], {}), '(dataSlice[self.filterCol][le:ri][wdet])\n', (7122, 7162), True, 'import numpy as np\n'), ((7267, 7341), 'numpy.where', 'np.where', (['((dataSlice[self.filterCol][le:ri] == filtName) & detected[le:ri])'], {}), '((dataSlice[self.filterCol][le:ri] == filtName) & detected[le:ri])\n', (7275, 7341), True, 'import numpy as np\n'), ((7480, 7497), 'numpy.diff', 'np.diff', (['lcPoints'], {}), '(lcPoints)\n', (7487, 7497), True, 'import numpy as np\n'), ((7706, 7736), 'numpy.sum', 'np.sum', (['(dlc > self.minDeltaMag)'], {}), '(dlc > self.minDeltaMag)\n', (7712, 7736), True, 'import numpy as np\n')]
import numpy as np from pickle import load import random import os from sklearn.model_selection import train_test_split from keras.models import load_model from sklearn.metrics import cohen_kappa_score from sklearn.metrics import confusion_matrix, classification_report from Model_setup import single_lstm import warnings warnings.filterwarnings('ignore') run_name = 'DL_50' path = os.getcwd() # load tokenizer, get vocab_szie, and load x, y tokenizer = load(open(f'/home/ubuntu/Final-Project-Group1/Models/{run_name}_tokenizer.pkl', 'rb')) vocab_size = len(tokenizer.word_index) + 1 x = np.load(f'/home/ubuntu/Final-Project-Group1/Data/{run_name}_x_train.npy') y = np.load(f'/home/ubuntu/Final-Project-Group1/Data/{run_name}_y_train.npy') # Generating random samples similar to shape of the x_train x_check =[] for i in range(0,len(x)): val = random.sample(range(0,50), 49) x_check.append(val) x_check = np.array(x_check) np.save(f'/home/ubuntu/Final-Project-Group1/Data/{run_name}_dummy_samples.npy', x_check) x = np.load(f'/home/ubuntu/Final-Project-Group1/Data/{run_name}_dummy_samples.npy') y = np.load(f'/home/ubuntu/Final-Project-Group1/Data/{run_name}_y_train.npy') x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=42, test_size=0.2) X_seq_length = x.shape[1] # Model1 - Single Layer LSTM # Hyper parameters N_NEURONS = 200 N_EPOCHS = 10 BATCH_SIZE = 256 EMBEDDING_SIZE = 200 model_name = 'lstm_sample' hyp_para = [BATCH_SIZE, N_EPOCHS, N_NEURONS, EMBEDDING_SIZE] single_lstm(x_train, y_train, x_test, y_test, hyp_para, vocab_size, run_name, model_name) # Model Evaluation model = load_model(f'/home/ubuntu/Final-Project-Group1/Models/{run_name}_{model_name}_model.h5') prediction = model.predict(x_test) accuracy = round((100 * model.evaluate(x_test, y_test)[1]), 3) print(f"Final accuracy on validations set: {accuracy}") ck_score = cohen_kappa_score(y_test.argmax(axis=1), prediction.argmax(axis=1)) print("Cohen kappa score", ck_score) class_report = classification_report(y_true=tokenizer.sequences_to_texts([y_test.argmax(axis=1)])[0].split(' '), y_pred=tokenizer.sequences_to_texts([prediction.argmax(axis=1)])[0].split(' '), labels=list(tokenizer.word_index.keys()), output_dict=True) # Get precision print('Precision:', class_report['weighted avg']['precision']) # Get recall print('Recall:', class_report['weighted avg']['recall']) # Get F1 print('F1:', class_report['weighted avg']['f1-score'])
[ "keras.models.load_model", "sklearn.model_selection.train_test_split", "os.getcwd", "numpy.array", "Model_setup.single_lstm", "numpy.load", "warnings.filterwarnings", "numpy.save" ]
[((322, 355), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (345, 355), False, 'import warnings\n'), ((383, 394), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (392, 394), False, 'import os\n'), ((591, 664), 'numpy.load', 'np.load', (['f"""/home/ubuntu/Final-Project-Group1/Data/{run_name}_x_train.npy"""'], {}), "(f'/home/ubuntu/Final-Project-Group1/Data/{run_name}_x_train.npy')\n", (598, 664), True, 'import numpy as np\n'), ((669, 742), 'numpy.load', 'np.load', (['f"""/home/ubuntu/Final-Project-Group1/Data/{run_name}_y_train.npy"""'], {}), "(f'/home/ubuntu/Final-Project-Group1/Data/{run_name}_y_train.npy')\n", (676, 742), True, 'import numpy as np\n'), ((917, 934), 'numpy.array', 'np.array', (['x_check'], {}), '(x_check)\n', (925, 934), True, 'import numpy as np\n'), ((935, 1027), 'numpy.save', 'np.save', (['f"""/home/ubuntu/Final-Project-Group1/Data/{run_name}_dummy_samples.npy"""', 'x_check'], {}), "(f'/home/ubuntu/Final-Project-Group1/Data/{run_name}_dummy_samples.npy',\n x_check)\n", (942, 1027), True, 'import numpy as np\n'), ((1029, 1108), 'numpy.load', 'np.load', (['f"""/home/ubuntu/Final-Project-Group1/Data/{run_name}_dummy_samples.npy"""'], {}), "(f'/home/ubuntu/Final-Project-Group1/Data/{run_name}_dummy_samples.npy')\n", (1036, 1108), True, 'import numpy as np\n'), ((1113, 1186), 'numpy.load', 'np.load', (['f"""/home/ubuntu/Final-Project-Group1/Data/{run_name}_y_train.npy"""'], {}), "(f'/home/ubuntu/Final-Project-Group1/Data/{run_name}_y_train.npy')\n", (1120, 1186), True, 'import numpy as np\n'), ((1222, 1276), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {'random_state': '(42)', 'test_size': '(0.2)'}), '(x, y, random_state=42, test_size=0.2)\n', (1238, 1276), False, 'from sklearn.model_selection import train_test_split\n'), ((1509, 1602), 'Model_setup.single_lstm', 'single_lstm', (['x_train', 'y_train', 'x_test', 'y_test', 'hyp_para', 'vocab_size', 'run_name', 'model_name'], {}), '(x_train, y_train, x_test, y_test, hyp_para, vocab_size,\n run_name, model_name)\n', (1520, 1602), False, 'from Model_setup import single_lstm\n'), ((1627, 1725), 'keras.models.load_model', 'load_model', (['f"""/home/ubuntu/Final-Project-Group1/Models/{run_name}_{model_name}_model.h5"""'], {}), "(\n f'/home/ubuntu/Final-Project-Group1/Models/{run_name}_{model_name}_model.h5'\n )\n", (1637, 1725), False, 'from keras.models import load_model\n')]
import sys import csv import numpy as np STATES = ["NEU", "NEG", "POS", "BOS"] def build_transition(fpath, num_states): transitions = [] with open(fpath) as f: reader = csv.reader(f) for idx, row in enumerate(reader): #if idx == 3: #break s = row[-5:] s = [STATES.index(x) for x in s] s = [3] + s transitions.append(s) #print(transitions) M = np.zeros((num_states+1, num_states)) #print(M) # collect sum for transition in transitions: for (i,j) in zip(transition, transition[1:]): # get consecutive states M[i][j] += 1 #print(M) #now convert to probabilities: for row in M: s = sum(row) if s > 0: row[:] = [c/s for c in row] # rows correspond to states + BOS and columns states print(STATES) print(M) return M fpath = "../data/rocstories_FULL_sentiment.csv" num_states = 3 M = build_transition(fpath, num_states)
[ "numpy.zeros", "csv.reader" ]
[((457, 495), 'numpy.zeros', 'np.zeros', (['(num_states + 1, num_states)'], {}), '((num_states + 1, num_states))\n', (465, 495), True, 'import numpy as np\n'), ((189, 202), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (199, 202), False, 'import csv\n')]
import numpy as np import time from SWMMSE import SWMMSE def channel(N, num_train, Pmax=1, Pmin=0, var_noise=1, seed=1758): print('Generate Data ... (seed = %d)' % seed) np.random.seed(seed) Pini = Pmax * np.ones(N) X = np.zeros((N ** 2, num_train)) Y = np.zeros((num_train, N )) X_t = np.zeros((num_train, N, N)) total_time = 0.0 for loop in range(num_train): CH = 1 / np.sqrt(2) * (np.random.randn(N, N) + 1j * np.random.randn(N, N)) H = abs(CH) X[:, loop] = np.reshape(H, (N ** 2,), order="F") H = np.reshape(X[:, loop], (N, N), order="F") X_t[loop, :, :] = H mid_time = time.time() Y[loop, :] = SWMMSE(Pini, H, Pmax, var_noise) total_time = total_time + time.time() - mid_time return X_t, Y, total_time
[ "numpy.reshape", "numpy.ones", "numpy.sqrt", "numpy.zeros", "numpy.random.randn", "numpy.random.seed", "SWMMSE.SWMMSE", "time.time" ]
[((179, 199), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (193, 199), True, 'import numpy as np\n'), ((237, 266), 'numpy.zeros', 'np.zeros', (['(N ** 2, num_train)'], {}), '((N ** 2, num_train))\n', (245, 266), True, 'import numpy as np\n'), ((275, 299), 'numpy.zeros', 'np.zeros', (['(num_train, N)'], {}), '((num_train, N))\n', (283, 299), True, 'import numpy as np\n'), ((311, 338), 'numpy.zeros', 'np.zeros', (['(num_train, N, N)'], {}), '((num_train, N, N))\n', (319, 338), True, 'import numpy as np\n'), ((218, 228), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (225, 228), True, 'import numpy as np\n'), ((518, 553), 'numpy.reshape', 'np.reshape', (['H', '(N ** 2,)'], {'order': '"""F"""'}), "(H, (N ** 2,), order='F')\n", (528, 553), True, 'import numpy as np\n'), ((566, 607), 'numpy.reshape', 'np.reshape', (['X[:, loop]', '(N, N)'], {'order': '"""F"""'}), "(X[:, loop], (N, N), order='F')\n", (576, 607), True, 'import numpy as np\n'), ((655, 666), 'time.time', 'time.time', ([], {}), '()\n', (664, 666), False, 'import time\n'), ((688, 720), 'SWMMSE.SWMMSE', 'SWMMSE', (['Pini', 'H', 'Pmax', 'var_noise'], {}), '(Pini, H, Pmax, var_noise)\n', (694, 720), False, 'from SWMMSE import SWMMSE\n'), ((411, 421), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (418, 421), True, 'import numpy as np\n'), ((425, 446), 'numpy.random.randn', 'np.random.randn', (['N', 'N'], {}), '(N, N)\n', (440, 446), True, 'import numpy as np\n'), ((755, 766), 'time.time', 'time.time', ([], {}), '()\n', (764, 766), False, 'import time\n'), ((454, 475), 'numpy.random.randn', 'np.random.randn', (['N', 'N'], {}), '(N, N)\n', (469, 475), True, 'import numpy as np\n')]
# Generate preprocessed image/label datasets from pathlib import Path from random import shuffle from termios import VMIN import numpy as np #from matplotlib import pyplot as plt import torch from torchvision import datasets,transforms Path("./prepped_mnist").mkdir(parents=True, exist_ok=True) #device = torch.device("cuda" if torch.cuda.is_available() else "cpu") vmin = 0 vmax = 0 def makeCentered(): global vmin,vmax print('Downloading MNIST Dataset') train = datasets.MNIST('./mnist', train=True, download=True, transform=transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.1307,), (0.3081,)),])) test = datasets.MNIST('./mnist', train=False, download=True, transform=transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.1307,), (0.3081,)),])) print('train data len: {}'.format(len(train))) print('test data len: {}'.format(len(test))) # serialize dataset tensor to disk print('Creating Centered MNIST Dataset') torch.save(train,'./prepped_mnist/centered_train.dat') torch.save(test,'./prepped_mnist/centered_test.dat') # summary stats t = torch.cat([x for (x,y) in train]) vmin = torch.min(t) vmax = torch.max(t) print('vmin:',vmin) print('vmax:',vmax) # Assumes centered dataset is on disk def makeTranslated(): print('Generating Translated MNIST Dataset') im_sz = 60 def translate_img(x,to_sz): C,H,W = x.size() x_t = -torch.ones(C,to_sz,to_sz) # background of MNIST is mapped to -1 torch.fill_(x_t,vmin) loch = np.random.randint(0,33) locw = np.random.randint(0,33) x_t[:,loch:loch+H,locw:locw+W] = x return x_t train = torch.load('./prepped_mnist/centered_train.dat') test = torch.load('./prepped_mnist/centered_test.dat') new_train = [] for i in range(len(train)): new_train.append( (translate_img(train[i][0],im_sz),train[i][1]) ) new_test = [] for i in range(len(test)): new_test.append( (translate_img(test[i][0],im_sz),test[i][1]) ) torch.save(new_train,'./prepped_mnist/translated_train.dat') torch.save(new_test,'./prepped_mnist/translated_test.dat') # Assumes centered dataset is on disk def makeCluttered(): print('Generating Cluttered MNIST Dataset') num_clutter = 4 clutter_sz = 8 im_sz = 60 def clutter_img(x, N_clutter, clutter_sz, to_sz): C,H,W = x.size() clutter_patches = [] ind = H-clutter_sz+1 for _ in range(N_clutter): [r,c] = np.random.randint(0,ind,2) clutter_patches += [x[:,r:r+clutter_sz,c:c+clutter_sz]] shuffle(clutter_patches) x_t = -torch.ones(C,to_sz,to_sz) # background of MNIST is mapped to -1 torch.fill_(x_t,vmin) ind = to_sz-H+1 ind_ = to_sz-clutter_sz+1 [loch, locw] = np.random.randint(0,ind,2) x_t[:,loch:loch+H,locw:locw+W] = x for _ in range(N_clutter): [r,c] = np.random.randint(0,ind_,2) x_t[:,r:r+clutter_sz,c:c+clutter_sz] = torch.max(x_t[:,r:r+clutter_sz,c:c+clutter_sz], clutter_patches.pop()) return x_t train = torch.load('./prepped_mnist/centered_train.dat') test = torch.load('./prepped_mnist/centered_test.dat') new_train = [] for i in range(len(train)): new_train.append( (clutter_img(train[i][0],num_clutter,clutter_sz,im_sz),train[i][1]) ) new_test = [] for i in range(len(test)): new_test.append( (clutter_img(test[i][0],num_clutter,clutter_sz,im_sz),test[i][1]) ) torch.save(new_train,'./prepped_mnist/cluttered_train.dat') torch.save(new_test,'./prepped_mnist/cluttered_test.dat') if __name__ == "__main__": makeCentered() makeTranslated() makeCluttered() print('Done.')
[ "random.shuffle", "pathlib.Path", "torch.load", "torch.max", "torch.min", "torch.fill_", "numpy.random.randint", "torch.save", "torchvision.transforms.Normalize", "torchvision.transforms.ToTensor", "torch.cat", "torch.ones" ]
[((978, 1033), 'torch.save', 'torch.save', (['train', '"""./prepped_mnist/centered_train.dat"""'], {}), "(train, './prepped_mnist/centered_train.dat')\n", (988, 1033), False, 'import torch\n'), ((1035, 1088), 'torch.save', 'torch.save', (['test', '"""./prepped_mnist/centered_test.dat"""'], {}), "(test, './prepped_mnist/centered_test.dat')\n", (1045, 1088), False, 'import torch\n'), ((1113, 1145), 'torch.cat', 'torch.cat', (['[x for x, y in train]'], {}), '([x for x, y in train])\n', (1122, 1145), False, 'import torch\n'), ((1156, 1168), 'torch.min', 'torch.min', (['t'], {}), '(t)\n', (1165, 1168), False, 'import torch\n'), ((1178, 1190), 'torch.max', 'torch.max', (['t'], {}), '(t)\n', (1187, 1190), False, 'import torch\n'), ((1644, 1692), 'torch.load', 'torch.load', (['"""./prepped_mnist/centered_train.dat"""'], {}), "('./prepped_mnist/centered_train.dat')\n", (1654, 1692), False, 'import torch\n'), ((1702, 1749), 'torch.load', 'torch.load', (['"""./prepped_mnist/centered_test.dat"""'], {}), "('./prepped_mnist/centered_test.dat')\n", (1712, 1749), False, 'import torch\n'), ((1986, 2047), 'torch.save', 'torch.save', (['new_train', '"""./prepped_mnist/translated_train.dat"""'], {}), "(new_train, './prepped_mnist/translated_train.dat')\n", (1996, 2047), False, 'import torch\n'), ((2049, 2108), 'torch.save', 'torch.save', (['new_test', '"""./prepped_mnist/translated_test.dat"""'], {}), "(new_test, './prepped_mnist/translated_test.dat')\n", (2059, 2108), False, 'import torch\n'), ((3004, 3052), 'torch.load', 'torch.load', (['"""./prepped_mnist/centered_train.dat"""'], {}), "('./prepped_mnist/centered_train.dat')\n", (3014, 3052), False, 'import torch\n'), ((3062, 3109), 'torch.load', 'torch.load', (['"""./prepped_mnist/centered_test.dat"""'], {}), "('./prepped_mnist/centered_test.dat')\n", (3072, 3109), False, 'import torch\n'), ((3388, 3448), 'torch.save', 'torch.save', (['new_train', '"""./prepped_mnist/cluttered_train.dat"""'], {}), "(new_train, './prepped_mnist/cluttered_train.dat')\n", (3398, 3448), False, 'import torch\n'), ((3450, 3508), 'torch.save', 'torch.save', (['new_test', '"""./prepped_mnist/cluttered_test.dat"""'], {}), "(new_test, './prepped_mnist/cluttered_test.dat')\n", (3460, 3508), False, 'import torch\n'), ((241, 264), 'pathlib.Path', 'Path', (['"""./prepped_mnist"""'], {}), "('./prepped_mnist')\n", (245, 264), False, 'from pathlib import Path\n'), ((1487, 1509), 'torch.fill_', 'torch.fill_', (['x_t', 'vmin'], {}), '(x_t, vmin)\n', (1498, 1509), False, 'import torch\n'), ((1520, 1544), 'numpy.random.randint', 'np.random.randint', (['(0)', '(33)'], {}), '(0, 33)\n', (1537, 1544), True, 'import numpy as np\n'), ((1555, 1579), 'numpy.random.randint', 'np.random.randint', (['(0)', '(33)'], {}), '(0, 33)\n', (1572, 1579), True, 'import numpy as np\n'), ((2525, 2549), 'random.shuffle', 'shuffle', (['clutter_patches'], {}), '(clutter_patches)\n', (2532, 2549), False, 'from random import shuffle\n'), ((2629, 2651), 'torch.fill_', 'torch.fill_', (['x_t', 'vmin'], {}), '(x_t, vmin)\n', (2640, 2651), False, 'import torch\n'), ((2722, 2750), 'numpy.random.randint', 'np.random.randint', (['(0)', 'ind', '(2)'], {}), '(0, ind, 2)\n', (2739, 2750), True, 'import numpy as np\n'), ((1419, 1446), 'torch.ones', 'torch.ones', (['C', 'to_sz', 'to_sz'], {}), '(C, to_sz, to_sz)\n', (1429, 1446), False, 'import torch\n'), ((2432, 2460), 'numpy.random.randint', 'np.random.randint', (['(0)', 'ind', '(2)'], {}), '(0, ind, 2)\n', (2449, 2460), True, 'import numpy as np\n'), ((2561, 2588), 'torch.ones', 'torch.ones', (['C', 'to_sz', 'to_sz'], {}), '(C, to_sz, to_sz)\n', (2571, 2588), False, 'import torch\n'), ((2833, 2862), 'numpy.random.randint', 'np.random.randint', (['(0)', 'ind_', '(2)'], {}), '(0, ind_, 2)\n', (2850, 2862), True, 'import numpy as np\n'), ((564, 585), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (583, 585), False, 'from torchvision import datasets, transforms\n'), ((586, 628), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.1307,)', '(0.3081,)'], {}), '((0.1307,), (0.3081,))\n', (606, 628), False, 'from torchvision import datasets, transforms\n'), ((730, 751), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (749, 751), False, 'from torchvision import datasets, transforms\n'), ((752, 794), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.1307,)', '(0.3081,)'], {}), '((0.1307,), (0.3081,))\n', (772, 794), False, 'from torchvision import datasets, transforms\n')]
# -*- coding: utf-8 -*- """ Created on Fri Apr 08 09:26:27 2016 @author: <NAME> """ from financepy.finutils.FinTestCases import FinTestCases, globalTestCaseMode from financepy.market.curves.FinPolynomialCurve import FinPolynomialCurve from financepy.finutils.FinDate import FinDate import numpy as np import sys sys.path.append("..//..") ########################################################################## # TODO # Inherit from FinCurve and add df method # Put in a convention for the rate # Use Frequency object ########################################################################## showPlots = True testCases = FinTestCases(__file__, globalTestCaseMode) def test_FinPolynomialCurve(): times = np.linspace(0.00, 10.0, 20) curveDate = FinDate(2019, 2, 2) coeffs = [0.0004, -0.0001, 0.00000010] curve1 = FinPolynomialCurve(curveDate, coeffs) zeros = curve1.zeroRate(times) fwds = curve1.fwd(times) if showPlots: import matplotlib.pyplot as plt plt.figure(figsize=(6, 4)) plt.plot(times, zeros, label="Zeros") plt.plot(times, fwds, label="Forwards") plt.xlabel('Time (years)') plt.ylabel('Zero Rate') plt.legend(loc='best') test_FinPolynomialCurve() testCases.compareTestCases()
[ "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "financepy.finutils.FinTestCases.FinTestCases", "numpy.linspace", "matplotlib.pyplot.figure", "financepy.finutils.FinDate.FinDate", "financepy.market.curves.FinPolynomialCurve.FinPolynomialCurve", "sys.path.append", ...
[((314, 339), 'sys.path.append', 'sys.path.append', (['"""..//.."""'], {}), "('..//..')\n", (329, 339), False, 'import sys\n'), ((629, 671), 'financepy.finutils.FinTestCases.FinTestCases', 'FinTestCases', (['__file__', 'globalTestCaseMode'], {}), '(__file__, globalTestCaseMode)\n', (641, 671), False, 'from financepy.finutils.FinTestCases import FinTestCases, globalTestCaseMode\n'), ((718, 744), 'numpy.linspace', 'np.linspace', (['(0.0)', '(10.0)', '(20)'], {}), '(0.0, 10.0, 20)\n', (729, 744), True, 'import numpy as np\n'), ((762, 781), 'financepy.finutils.FinDate.FinDate', 'FinDate', (['(2019)', '(2)', '(2)'], {}), '(2019, 2, 2)\n', (769, 781), False, 'from financepy.finutils.FinDate import FinDate\n'), ((838, 875), 'financepy.market.curves.FinPolynomialCurve.FinPolynomialCurve', 'FinPolynomialCurve', (['curveDate', 'coeffs'], {}), '(curveDate, coeffs)\n', (856, 875), False, 'from financepy.market.curves.FinPolynomialCurve import FinPolynomialCurve\n'), ((1007, 1033), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 4)'}), '(figsize=(6, 4))\n', (1017, 1033), True, 'import matplotlib.pyplot as plt\n'), ((1042, 1079), 'matplotlib.pyplot.plot', 'plt.plot', (['times', 'zeros'], {'label': '"""Zeros"""'}), "(times, zeros, label='Zeros')\n", (1050, 1079), True, 'import matplotlib.pyplot as plt\n'), ((1088, 1127), 'matplotlib.pyplot.plot', 'plt.plot', (['times', 'fwds'], {'label': '"""Forwards"""'}), "(times, fwds, label='Forwards')\n", (1096, 1127), True, 'import matplotlib.pyplot as plt\n'), ((1136, 1162), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (years)"""'], {}), "('Time (years)')\n", (1146, 1162), True, 'import matplotlib.pyplot as plt\n'), ((1171, 1194), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Zero Rate"""'], {}), "('Zero Rate')\n", (1181, 1194), True, 'import matplotlib.pyplot as plt\n'), ((1203, 1225), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (1213, 1225), True, 'import matplotlib.pyplot as plt\n')]
import argparse import importlib import json import math import os import matplotlib import numpy as np import tensorflow as tf import utils from config_rnn import defaults matplotlib.use('Agg') import matplotlib.pyplot as plt # ----------------------------------------------------------------------------- parser = argparse.ArgumentParser() parser.add_argument('--config_name', type=str, required=True, help='name of the configuration') parser.add_argument('--seq_len', type=int, default=2, help='sequence length') parser.add_argument('--set', type=str, default='train', help='train or test set?') args, _ = parser.parse_known_args() defaults.set_parameters(args) print('input args:\n', json.dumps(vars(args), indent=4, separators=(',', ':'))) gp_model = True if 'gp' in args.config_name else False # ----------------------------------------------------------------------------- def student_pdf_1d(X, mu, var, nu): if nu > 50: return gauss_pdf_1d(X, mu, var) num = math.gamma((1. + nu) / 2.) * pow( 1. + (1. / (nu - 2)) * (1. / var * (X - mu) ** 2), -(1. + nu) / 2.) denom = math.gamma(nu / 2.) * pow((nu - 2) * math.pi * var, 0.5) return num / denom def gauss_pdf_1d(X, mu, var): return 1. / np.sqrt(2. * np.pi * var) * np.exp(- (X - mu) ** 2 / (2. * var)) np.random.seed(seed=42) configs_dir = __file__.split('/')[-2] config = importlib.import_module('%s.%s' % (configs_dir, args.config_name)) # metadata save_dir = utils.find_model_metadata('metadata/', args.config_name) experiment_id = os.path.dirname(save_dir) print('exp_id', experiment_id) # samples target_path = save_dir + '/hists_%s' % args.set utils.autodir(target_path) # create the model model = tf.make_template('model', config.build_model, sampling_mode=False) all_params = tf.trainable_variables() batch_size = 1000 x_in = tf.placeholder(tf.float32, shape=(batch_size,) + config.obs_shape) z_codes = model(x_in)[3] saver = tf.train.Saver() # data iter data_iter = config.test_data_iter if args.set == 'test' else config.train_data_iter data_iter.batch_size = batch_size with tf.Session() as sess: ckpt_file = save_dir + 'params.ckpt' print('restoring parameters from', ckpt_file) saver.restore(sess, tf.train.latest_checkpoint(save_dir)) mu = config.student_layer.mu.eval().flatten() var = config.student_layer.var.eval().flatten() corr = config.student_layer.corr.eval().flatten() if hasattr(config.student_layer, 'nu'): nu = config.student_layer.nu.eval().flatten() else: nu = np.zeros_like(mu) batch_idxs = range(0, 1) all_codes = None for _, x_batch in zip(batch_idxs, data_iter.generate()): codes = sess.run(z_codes, feed_dict={x_in: x_batch}) print(codes.shape) all_codes = codes if all_codes is None else np.concatenate((codes, all_codes), axis=0) all_codes = all_codes[:, 0, :] # take only fist element of each sequence print(all_codes.shape) for i in range(all_codes.shape[-1]): plt.figure() plt.rc('xtick', labelsize=18) plt.rc('ytick', labelsize=18) ax = plt.gca() ax.margins(x=0) x_lim = (np.min(all_codes[:, i]), np.max(all_codes[:, i])) x_lim = (min(mu[i] - 5 * np.sqrt(var[i]), x_lim[0]), max(mu[i] + 5 * np.sqrt(var[i]), x_lim[0])) x_range = np.linspace(x_lim[0], x_lim[1], 1000) if gp_model: y = gauss_pdf_1d(x_range, mu[i], var[i]) else: y = student_pdf_1d(x_range, mu[i], var[i], nu[i]) plt.plot(x_range, y, 'black', label='theory', linewidth=2.5) if gp_model: plt.hist(all_codes[:, i], bins=100, normed=True, alpha=0.5, label='actual') else: plt.hist(all_codes[:, i], bins=100, normed=True, alpha=0.5, range=(x_lim[0], x_lim[1]), label='actual') print(i, np.min(all_codes[:, i]), np.max(all_codes[:, i]), np.argmin(all_codes[:, i]), np.argmax( all_codes[:, i])) plt.legend(loc='upper right', fontsize=18) plt.xlabel('z', fontsize=20) plt.ylabel('p(z)', fontsize=20) plt.title('corr=%s, var=%s, nu=%s' % (corr[i], var[i], nu[i])) plt.savefig(target_path + '/hist_latent_%s.png' % i, bbox_inches='tight', pad_inches=0) plt.close() plt.clf()
[ "numpy.sqrt", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel", "utils.find_model_metadata", "math.gamma", "argparse.ArgumentParser", "tensorflow.placeholder", "tensorflow.Session", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "numpy.max", "numpy.exp", "matplotlib.pyplot.close",...
[((176, 197), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (190, 197), False, 'import matplotlib\n'), ((320, 345), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (343, 345), False, 'import argparse\n'), ((639, 668), 'config_rnn.defaults.set_parameters', 'defaults.set_parameters', (['args'], {}), '(args)\n', (662, 668), False, 'from config_rnn import defaults\n'), ((1306, 1329), 'numpy.random.seed', 'np.random.seed', ([], {'seed': '(42)'}), '(seed=42)\n', (1320, 1329), True, 'import numpy as np\n'), ((1378, 1444), 'importlib.import_module', 'importlib.import_module', (["('%s.%s' % (configs_dir, args.config_name))"], {}), "('%s.%s' % (configs_dir, args.config_name))\n", (1401, 1444), False, 'import importlib\n'), ((1468, 1524), 'utils.find_model_metadata', 'utils.find_model_metadata', (['"""metadata/"""', 'args.config_name'], {}), "('metadata/', args.config_name)\n", (1493, 1524), False, 'import utils\n'), ((1541, 1566), 'os.path.dirname', 'os.path.dirname', (['save_dir'], {}), '(save_dir)\n', (1556, 1566), False, 'import os\n'), ((1657, 1683), 'utils.autodir', 'utils.autodir', (['target_path'], {}), '(target_path)\n', (1670, 1683), False, 'import utils\n'), ((1712, 1778), 'tensorflow.make_template', 'tf.make_template', (['"""model"""', 'config.build_model'], {'sampling_mode': '(False)'}), "('model', config.build_model, sampling_mode=False)\n", (1728, 1778), True, 'import tensorflow as tf\n'), ((1792, 1816), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (1814, 1816), True, 'import tensorflow as tf\n'), ((1843, 1909), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '((batch_size,) + config.obs_shape)'}), '(tf.float32, shape=(batch_size,) + config.obs_shape)\n', (1857, 1909), True, 'import tensorflow as tf\n'), ((1944, 1960), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1958, 1960), True, 'import tensorflow as tf\n'), ((2098, 2110), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2108, 2110), True, 'import tensorflow as tf\n'), ((989, 1017), 'math.gamma', 'math.gamma', (['((1.0 + nu) / 2.0)'], {}), '((1.0 + nu) / 2.0)\n', (999, 1017), False, 'import math\n'), ((1111, 1131), 'math.gamma', 'math.gamma', (['(nu / 2.0)'], {}), '(nu / 2.0)\n', (1121, 1131), False, 'import math\n'), ((1267, 1303), 'numpy.exp', 'np.exp', (['(-(X - mu) ** 2 / (2.0 * var))'], {}), '(-(X - mu) ** 2 / (2.0 * var))\n', (1273, 1303), True, 'import numpy as np\n'), ((2235, 2271), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['save_dir'], {}), '(save_dir)\n', (2261, 2271), True, 'import tensorflow as tf\n'), ((2551, 2568), 'numpy.zeros_like', 'np.zeros_like', (['mu'], {}), '(mu)\n', (2564, 2568), True, 'import numpy as np\n'), ((3028, 3040), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3038, 3040), True, 'import matplotlib.pyplot as plt\n'), ((3049, 3078), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'labelsize': '(18)'}), "('xtick', labelsize=18)\n", (3055, 3078), True, 'import matplotlib.pyplot as plt\n'), ((3087, 3116), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'labelsize': '(18)'}), "('ytick', labelsize=18)\n", (3093, 3116), True, 'import matplotlib.pyplot as plt\n'), ((3130, 3139), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (3137, 3139), True, 'import matplotlib.pyplot as plt\n'), ((3356, 3393), 'numpy.linspace', 'np.linspace', (['x_lim[0]', 'x_lim[1]', '(1000)'], {}), '(x_lim[0], x_lim[1], 1000)\n', (3367, 3393), True, 'import numpy as np\n'), ((3553, 3613), 'matplotlib.pyplot.plot', 'plt.plot', (['x_range', 'y', '"""black"""'], {'label': '"""theory"""', 'linewidth': '(2.5)'}), "(x_range, y, 'black', label='theory', linewidth=2.5)\n", (3561, 3613), True, 'import matplotlib.pyplot as plt\n'), ((4021, 4063), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""', 'fontsize': '(18)'}), "(loc='upper right', fontsize=18)\n", (4031, 4063), True, 'import matplotlib.pyplot as plt\n'), ((4072, 4100), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""z"""'], {'fontsize': '(20)'}), "('z', fontsize=20)\n", (4082, 4100), True, 'import matplotlib.pyplot as plt\n'), ((4109, 4140), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""p(z)"""'], {'fontsize': '(20)'}), "('p(z)', fontsize=20)\n", (4119, 4140), True, 'import matplotlib.pyplot as plt\n'), ((4149, 4211), 'matplotlib.pyplot.title', 'plt.title', (["('corr=%s, var=%s, nu=%s' % (corr[i], var[i], nu[i]))"], {}), "('corr=%s, var=%s, nu=%s' % (corr[i], var[i], nu[i]))\n", (4158, 4211), True, 'import matplotlib.pyplot as plt\n'), ((4220, 4311), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(target_path + '/hist_latent_%s.png' % i)"], {'bbox_inches': '"""tight"""', 'pad_inches': '(0)'}), "(target_path + '/hist_latent_%s.png' % i, bbox_inches='tight',\n pad_inches=0)\n", (4231, 4311), True, 'import matplotlib.pyplot as plt\n'), ((4316, 4327), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4325, 4327), True, 'import matplotlib.pyplot as plt\n'), ((4336, 4345), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (4343, 4345), True, 'import matplotlib.pyplot as plt\n'), ((1239, 1265), 'numpy.sqrt', 'np.sqrt', (['(2.0 * np.pi * var)'], {}), '(2.0 * np.pi * var)\n', (1246, 1265), True, 'import numpy as np\n'), ((2822, 2864), 'numpy.concatenate', 'np.concatenate', (['(codes, all_codes)'], {'axis': '(0)'}), '((codes, all_codes), axis=0)\n', (2836, 2864), True, 'import numpy as np\n'), ((3182, 3205), 'numpy.min', 'np.min', (['all_codes[:, i]'], {}), '(all_codes[:, i])\n', (3188, 3205), True, 'import numpy as np\n'), ((3207, 3230), 'numpy.max', 'np.max', (['all_codes[:, i]'], {}), '(all_codes[:, i])\n', (3213, 3230), True, 'import numpy as np\n'), ((3648, 3723), 'matplotlib.pyplot.hist', 'plt.hist', (['all_codes[:, i]'], {'bins': '(100)', 'normed': '(True)', 'alpha': '(0.5)', 'label': '"""actual"""'}), "(all_codes[:, i], bins=100, normed=True, alpha=0.5, label='actual')\n", (3656, 3723), True, 'import matplotlib.pyplot as plt\n'), ((3750, 3857), 'matplotlib.pyplot.hist', 'plt.hist', (['all_codes[:, i]'], {'bins': '(100)', 'normed': '(True)', 'alpha': '(0.5)', 'range': '(x_lim[0], x_lim[1])', 'label': '"""actual"""'}), "(all_codes[:, i], bins=100, normed=True, alpha=0.5, range=(x_lim[0],\n x_lim[1]), label='actual')\n", (3758, 3857), True, 'import matplotlib.pyplot as plt\n'), ((3893, 3916), 'numpy.min', 'np.min', (['all_codes[:, i]'], {}), '(all_codes[:, i])\n', (3899, 3916), True, 'import numpy as np\n'), ((3918, 3941), 'numpy.max', 'np.max', (['all_codes[:, i]'], {}), '(all_codes[:, i])\n', (3924, 3941), True, 'import numpy as np\n'), ((3943, 3969), 'numpy.argmin', 'np.argmin', (['all_codes[:, i]'], {}), '(all_codes[:, i])\n', (3952, 3969), True, 'import numpy as np\n'), ((3971, 3997), 'numpy.argmax', 'np.argmax', (['all_codes[:, i]'], {}), '(all_codes[:, i])\n', (3980, 3997), True, 'import numpy as np\n'), ((3265, 3280), 'numpy.sqrt', 'np.sqrt', (['var[i]'], {}), '(var[i])\n', (3272, 3280), True, 'import numpy as np\n'), ((3309, 3324), 'numpy.sqrt', 'np.sqrt', (['var[i]'], {}), '(var[i])\n', (3316, 3324), True, 'import numpy as np\n')]
import numpy as np import pandas as pd import struct import os from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() ''' #### Script designed to use 6 cores #### Network configuration are analyzed in serie and stimuli intensitie in parallel #### run from terminal using: 'mpirun -np 6 python get_psth.py' Read simulations output files and get a PSTH trace per each neuron It will create one file per network configuration and stimuli intensity file will be saved in folder "data" ''' ################################################################ ################################################################ N = 1000 ################################################################ stimulis = [400, 600, 800, 1000, 1200, 1400] ################################################################ # histograms functions def get_hist_pop(spk): # collective PTSH dtbin = 0.0002 # 0.2 ms tbin = np.arange(lb, ub, dtbin) bins = len(tbin) return np.histogram(spk, bins=bins, range=hrange)[0] / (nrep * dtbin) ########################################################### def get_hist(spk): # Individual neurons PSTH return np.histogram(spk, bins=bins, range=hrange)[0] / (nrep * dtbin) ################################################################## ############### path to simulations ############## ################################################################## path = '../PSTH_simulations/' ################################################################## ############### Time bin for histograms ############## ################################################################## dtbin = 0.0005 # 0.5 ms lb, ub = -0.025, 0.175 hrange = [lb, ub] tbin = np.arange(lb, ub, dtbin) bins = len(tbin) ################################################################## ############### Barrage disconnected ################# ################################################################## nrep = 100000 ########################################################### for kk, stim in enumerate(stimulis): if rank == kk: print('gcl', rank, kk) ################################################################ hpopulation = get_hist_pop(np.ones(1000)) hneurons = [get_hist(np.ones(1000)) for i in range(N)] # N hist fill with zeros for k, proc in enumerate(range(10)): print('gcl', rank, kk, k) folder = '%s/psth_gcl/psth_gcl_%d_%d' % (path, kk, k) ######################## f = open('%s/Spikes_times.dat' % folder, mode='rb').read() # read spikes file format = '%df' % (len(f) // 4) spk = np.array(struct.unpack(format, f)) hpopulation += get_hist_pop(spk) ################# spkn = np.array(pd.read_csv('%s/Spiking_neurons.dat' % folder, sep='\s+', header=None)) spkn = spkn.reshape(len(spkn)) for j in range(N): hneurons[j] += get_hist(spk[np.where(spkn == j + 1)]) np.save('data/hist_gcl_%d.npy' % kk, hneurons) # np.save('data/hist_gcl_pop_%d.npy' % kk, hpopulation / N) ################################################################## ############### Random Network ####################### ################################################################## nrep = 100000 ########################################################### for kk, stim in enumerate(stimulis): if rank == kk: print('ran', rank, kk) ################################################################ hpopulation = get_hist_pop(np.ones(1000)) hneurons = [get_hist(np.ones(1000)) for i in range(N)] # N hist fill with zeros for k, proc in enumerate(range(10)): print('ran', rank, kk, k) folder = '%s/psth_ran/psth_ran_%d_%d' % (path, kk, k) ######################## f = open('%s/Spikes_times.dat' % folder, mode='rb').read() # read spikes file format = '%df' % (len(f) // 4) spk = np.array(struct.unpack(format, f)) hpopulation += get_hist_pop(spk) ################# spkn = np.array(pd.read_csv('%s/Spiking_neurons.dat' % folder, sep='\s+', header=None)) spkn = spkn.reshape(len(spkn)) for j in range(N): hneurons[j] += get_hist(spk[np.where(spkn == j + 1)]) np.save('data/hist_ran_%d.npy' % kk, hneurons) # np.save('data/hist_ran_pop_%d.npy' % kk, hpopulation / N) ################################################################## ############## Disconnected no barrage ############## ################################################################## nrep = 100000 ########################################################### for kk, stim in enumerate(stimulis): if rank == kk: print('con', rank, kk) ################################################################ hpopulation = get_hist_pop(np.ones(1000)) hneurons = [get_hist(np.ones(1000)) for i in range(N)] # N hist fill with zeros for k, proc in enumerate(range(10)): print('con', rank, kk, k) folder = '%s/psth_con/psth_con_%d_%d' % (path, kk, k) ######################## f = open('%s/Spikes_times.dat' % folder, mode='rb').read() # read spikes file format = '%df' % (len(f) // 4) spk = np.array(struct.unpack(format, f)) hpopulation += get_hist_pop(spk) ################# spkn = np.array(pd.read_csv('%s/Spiking_neurons.dat' % folder, sep='\s+', header=None)) spkn = spkn.reshape(len(spkn)) for j in range(N): hneurons[j] += get_hist(spk[np.where(spkn == j + 1)]) np.save('data/hist_con_%d.npy' % kk, hneurons) # np.save('data/hist_con_pop_%d.npy' % kk, hpopulation / N) ################################################################## ############### Small-world Network ################## ################################################################## nrep = 100000 ########################################################### for kk, stim in enumerate(stimulis): if rank == kk: print('net', rank, kk) ################################################################ hpopulation = get_hist_pop(np.ones(1000)) hneurons = [get_hist(np.ones(1000)) for i in range(N)] # N hist fill with zeros for k, proc in enumerate(range(10)): print('net', rank, kk, k) folder = '%s/psth_net/psth_net_%d_%d' % (path, kk, k) ######################## f = open('%s/Spikes_times.dat' % folder, mode='rb').read() # read spikes file format = '%df' % (len(f) // 4) spk = np.array(struct.unpack(format, f)) hpopulation += get_hist_pop(spk) ################# spkn = np.array(pd.read_csv('%s/Spiking_neurons.dat' % folder, sep='\s+', header=None)) spkn = spkn.reshape(len(spkn)) for j in range(N): hneurons[j] += get_hist(spk[np.where(spkn == j + 1)]) np.save('data/hist_net_%d.npy' % kk, hneurons) # np.save('data/hist_net_pop_%d.npy' % kk, hpopulation / N) # ################################################################
[ "numpy.histogram", "numpy.ones", "pandas.read_csv", "numpy.arange", "numpy.where", "struct.unpack", "numpy.save" ]
[((1727, 1751), 'numpy.arange', 'np.arange', (['lb', 'ub', 'dtbin'], {}), '(lb, ub, dtbin)\n', (1736, 1751), True, 'import numpy as np\n'), ((919, 943), 'numpy.arange', 'np.arange', (['lb', 'ub', 'dtbin'], {}), '(lb, ub, dtbin)\n', (928, 943), True, 'import numpy as np\n'), ((3125, 3171), 'numpy.save', 'np.save', (["('data/hist_gcl_%d.npy' % kk)", 'hneurons'], {}), "('data/hist_gcl_%d.npy' % kk, hneurons)\n", (3132, 3171), True, 'import numpy as np\n'), ((4593, 4639), 'numpy.save', 'np.save', (["('data/hist_ran_%d.npy' % kk)", 'hneurons'], {}), "('data/hist_ran_%d.npy' % kk, hneurons)\n", (4600, 4639), True, 'import numpy as np\n'), ((6064, 6110), 'numpy.save', 'np.save', (["('data/hist_con_%d.npy' % kk)", 'hneurons'], {}), "('data/hist_con_%d.npy' % kk, hneurons)\n", (6071, 6110), True, 'import numpy as np\n'), ((7537, 7583), 'numpy.save', 'np.save', (["('data/hist_net_%d.npy' % kk)", 'hneurons'], {}), "('data/hist_net_%d.npy' % kk, hneurons)\n", (7544, 7583), True, 'import numpy as np\n'), ((976, 1018), 'numpy.histogram', 'np.histogram', (['spk'], {'bins': 'bins', 'range': 'hrange'}), '(spk, bins=bins, range=hrange)\n', (988, 1018), True, 'import numpy as np\n'), ((1156, 1198), 'numpy.histogram', 'np.histogram', (['spk'], {'bins': 'bins', 'range': 'hrange'}), '(spk, bins=bins, range=hrange)\n', (1168, 1198), True, 'import numpy as np\n'), ((2239, 2252), 'numpy.ones', 'np.ones', (['(1000)'], {}), '(1000)\n', (2246, 2252), True, 'import numpy as np\n'), ((3707, 3720), 'numpy.ones', 'np.ones', (['(1000)'], {}), '(1000)\n', (3714, 3720), True, 'import numpy as np\n'), ((5178, 5191), 'numpy.ones', 'np.ones', (['(1000)'], {}), '(1000)\n', (5185, 5191), True, 'import numpy as np\n'), ((6651, 6664), 'numpy.ones', 'np.ones', (['(1000)'], {}), '(1000)\n', (6658, 6664), True, 'import numpy as np\n'), ((2283, 2296), 'numpy.ones', 'np.ones', (['(1000)'], {}), '(1000)\n', (2290, 2296), True, 'import numpy as np\n'), ((2731, 2755), 'struct.unpack', 'struct.unpack', (['format', 'f'], {}), '(format, f)\n', (2744, 2755), False, 'import struct\n'), ((2860, 2931), 'pandas.read_csv', 'pd.read_csv', (["('%s/Spiking_neurons.dat' % folder)"], {'sep': '"""\\\\s+"""', 'header': 'None'}), "('%s/Spiking_neurons.dat' % folder, sep='\\\\s+', header=None)\n", (2871, 2931), True, 'import pandas as pd\n'), ((3751, 3764), 'numpy.ones', 'np.ones', (['(1000)'], {}), '(1000)\n', (3758, 3764), True, 'import numpy as np\n'), ((4199, 4223), 'struct.unpack', 'struct.unpack', (['format', 'f'], {}), '(format, f)\n', (4212, 4223), False, 'import struct\n'), ((4328, 4399), 'pandas.read_csv', 'pd.read_csv', (["('%s/Spiking_neurons.dat' % folder)"], {'sep': '"""\\\\s+"""', 'header': 'None'}), "('%s/Spiking_neurons.dat' % folder, sep='\\\\s+', header=None)\n", (4339, 4399), True, 'import pandas as pd\n'), ((5222, 5235), 'numpy.ones', 'np.ones', (['(1000)'], {}), '(1000)\n', (5229, 5235), True, 'import numpy as np\n'), ((5670, 5694), 'struct.unpack', 'struct.unpack', (['format', 'f'], {}), '(format, f)\n', (5683, 5694), False, 'import struct\n'), ((5799, 5870), 'pandas.read_csv', 'pd.read_csv', (["('%s/Spiking_neurons.dat' % folder)"], {'sep': '"""\\\\s+"""', 'header': 'None'}), "('%s/Spiking_neurons.dat' % folder, sep='\\\\s+', header=None)\n", (5810, 5870), True, 'import pandas as pd\n'), ((6695, 6708), 'numpy.ones', 'np.ones', (['(1000)'], {}), '(1000)\n', (6702, 6708), True, 'import numpy as np\n'), ((7143, 7167), 'struct.unpack', 'struct.unpack', (['format', 'f'], {}), '(format, f)\n', (7156, 7167), False, 'import struct\n'), ((7272, 7343), 'pandas.read_csv', 'pd.read_csv', (["('%s/Spiking_neurons.dat' % folder)"], {'sep': '"""\\\\s+"""', 'header': 'None'}), "('%s/Spiking_neurons.dat' % folder, sep='\\\\s+', header=None)\n", (7283, 7343), True, 'import pandas as pd\n'), ((3091, 3114), 'numpy.where', 'np.where', (['(spkn == j + 1)'], {}), '(spkn == j + 1)\n', (3099, 3114), True, 'import numpy as np\n'), ((4559, 4582), 'numpy.where', 'np.where', (['(spkn == j + 1)'], {}), '(spkn == j + 1)\n', (4567, 4582), True, 'import numpy as np\n'), ((6030, 6053), 'numpy.where', 'np.where', (['(spkn == j + 1)'], {}), '(spkn == j + 1)\n', (6038, 6053), True, 'import numpy as np\n'), ((7503, 7526), 'numpy.where', 'np.where', (['(spkn == j + 1)'], {}), '(spkn == j + 1)\n', (7511, 7526), True, 'import numpy as np\n')]
"""Functions necessary for synthetic seismic modelling (e.g. sim2seis). """ from typing import Any, Literal, List, Sequence import numpy as np import xarray as xr from numpy import typing as npt from scipy.interpolate import interp1d from scipy.signal import fftconvolve import scipy.ndimage from tqdm import tqdm from ._interface import zoeppritz_pdpu_only, zoeppritz_ponly, akirichards def nanfill(x, filter="mean", size=3): filters = {"mean": np.mean} xf = np.where(np.isnan(x), 0, x) xf = scipy.ndimage.generic_filter(xf, filters[filter], size=size) return np.where(np.isnan(x), xf, x) def reflectivity( theta: float, velp: np.ndarray, vels: np.ndarray, rho: np.ndarray, method: Literal["full", "zoep_pud", "ar"] = "full", ) -> np.ndarray: """Reflectivity for theta from acoustic vectors Args: theta: P-wave incidence angle velp: P-wave velcoities vels: S-wave velocities rho: density values method: The modelling method to use Returns: interface reflectivity arrays (padded 0 at front to keep same length as input) """ th = np.full_like(velp[:-1], theta) args = (th, velp[:-1], vels[:-1], rho[:-1], velp[1:], vels[1:], rho[1:]) if method == "zoep_pud": refl = np.array( zoeppritz_pdpu_only(*args), dtype=[ ("Rp", np.float_), ], ) elif method == "full": a = zoeppritz_ponly(*args) refl = np.array( [v for v in zip(*a)], dtype=( [ ("Rp", np.float_), ("Rs", np.float_), ("Tp", np.float_), ("Ts", np.float_), ] ), ) elif method == "ar": refl = np.array( akirichards(*args), dtype=[ ("Rp", np.float_), ], ) for name in refl.dtype.names: refl[name] = np.where(np.isnan(refl[name]), 0, refl[name]) return np.pad(refl, (1, 0)) def reflectivity_vol( ds: xr.Dataset, theta: float, mapping_dims: Sequence[str] = ("xline", "iline"), ) -> xr.Dataset: """Convert elastic properties "vp", "vs" and "density" to reflectivity Args: ds: A Dataset with the properties to depth convert. Has same dims s `twt_vol` mapping_dims: The dimensions over which to map the funciton Returns: The properties of `depth_ds` converted to twt using `twt_vol` """ for dim in mapping_dims: assert dim in ds.dims def _reflectivity_mapper(trace): trace[f"refl_{theta}"] = ( ("twt"), reflectivity( theta, trace.vp.values, trace.vs.values, trace.density.values, method="zoep_pud", )["Rp"], ) return trace def _blocks_reflectivity_mapper(ds): stack = ds.stack({"trace": mapping_dims}) preserve_dim_order = tuple(key for key in ds.dims) refl_block = stack.groupby("trace").map(_reflectivity_mapper).unstack("trace") return refl_block.transpose(*preserve_dim_order) refl_ds = ds.map_blocks(_blocks_reflectivity_mapper, template=ds) return refl_ds def convolution1d_vol( ds: xr.Dataset, reflectivity_key: str, wavelet_amp: np.ndarray, mapping_dims: Sequence[str] = ("xline", "iline"), ) -> xr.Dataset: """Convolved a reflectivity array from a Dataset with a wavelet. Wavelet must have same sample rate as seismic twt Args: ds: A Dataset with the properties to depth convert. Has same dims s `twt_vol` mapping_dims: The dimensions over which to map the funciton Returns: The properties of `depth_ds` converted to twt using `twt_vol` """ for dim in mapping_dims: assert dim in ds.dims def _conv_mapper(trace): trace["amp"] = ( ("twt"), fftconvolve(trace[reflectivity_key].values, wavelet_amp, mode="same"), ) return trace def _blocks_conv_mapper(ds): stack = ds.stack({"trace": mapping_dims}) preserve_dim_order = tuple(key for key in ds.dims) refl_block = stack.groupby("trace").map(_conv_mapper).unstack("trace") return refl_block.transpose(*preserve_dim_order) seis_ds = ds.map_blocks(_blocks_conv_mapper, template=ds) return seis_ds # def _convolution_psf_line_inner( # vp, vs, rho, twt, refl_method=None, th=None, subtwt=None, pbar=None, intp_kwargs={} # ): # reflc_ = np.zeros((vp.shape[0], subtwt.size)) # for j, (vp_, vs_, rho_, twt_) in enumerate(zip(vp, vs, rho, twt)): # if np.all(np.isnan(vp_)): # # empty TWT # reflc_[j, :] = 0.0 # else: # # interpolate values to TWT domain # vp_subtwt = interp1d(twt_, vp_, **intp_kwargs)(subtwt) # vs_subtwt = interp1d(twt_, vs_, **intp_kwargs)(subtwt) # rho_subtwt = interp1d(twt_, rho_, **intp_kwargs)(subtwt) # reflc_[j, :-1] = reflectivity( # th, vp_subtwt, vs_subtwt, rho_subtwt, method=refl_method # ) # if pbar is not None: # pbar.update() # return reflc_ # def convolution_psf( # dataset, # wavelet, # theta, # vp_var, # vs_var, # rho_var, # twt_var, # twt=None, # conv_dt=1, # silent=False, # refl_method="zoep_pud", # maximum_offsets=None, # psf_size=(64, 64, 128), # dask_client=None, # ): # """Perform 1D convolution on a 3D xarray dataset. # Assumes model is in depth rather than time. Although you can set twt_var to # be the k dimension coordinate. # Args: # dataset (xarray.Dataset): Should have dimensions (i, j, k), easiest to # get from etlpy.models.EarthModel # wavelet (etlpy.seismic.Wavelet): wavelet to use for convultion # theta (float/list[float]): A float of list of float angles to perform # convultion modelling over. # vp_var (str): P-velocity variable in dataset to use for modelling. # vs_var (str): S-velocity variable in dataset to use for modelling. # rho_var (str): Density variable in dataset to use for modelling. # twt_var (str): TWT variable in dataset to use for zstick conversion. # twt (array-like): Specify an out twt sampling. # conv_dt (float): The sample rate at which to perform convolution. # silent (bool, optional): Turn off the progress bar. Defaults to False # refl_method (str, optional): The reflectivity calculatio nmethod. # Choose from 'zoep_pud' and 'ar'. Defaults to 'zoep_pud'. # maximum_offset (tuple, optional): A tuple of maximum inline anx xline offsets (m) to # constrain the PSF illumination. # Returns: # (array-like): Synthetic trace volume. # """ # try: # ni, nj, nk = dataset.dims.values() # except ValueError: # raise ValueError(f"expect dimensions (i, j, k) but got {dataset.dims}") # theta = np.atleast_1d(theta) # angles = theta.copy() # theta = np.deg2rad(theta) # if twt is None: # vert_size = dataset.vert.size # twt_min = dataset[twt_var].min() # twt_max = dataset[twt_var].max() # # twt_stick = np.linspace(twt_min, twt_max + conv_dt, vert_size) # twt_sticks = dataset[twt_var].values # subtwt = np.arange(twt_min, twt_max + conv_dt, conv_dt) # else: # vert_size = twt.size # # create a block twt array -> this could potentially be replaced by a sparse array # twt_sticks = ( # np.array([np.asarray(twt)]).repeat(ni * nj, axis=0).reshape(ni, nj, -1) # ) # subtwt = np.arange(twt_sticks.min(), twt_sticks.max(), conv_dt) # reflc_ = np.zeros((ni, nj, subtwt.size)) # preallocate output memory # psfc_ = np.zeros((ni, nj, subtwt.size)) # # psf setup # avgz = np.mean(dataset.vert.values) # if maximum_offsets is not None: # max_il, max_xl = maximum_offsets # max_il = np.degrees(np.arctan(max_il / avgz)) # max_xl = np.degrees(np.arctan(max_xl / avgz)) # else: # no limit # max_il = 90 # max_xl = 90 # # limit the maximum angle of the psf based upon the surface acquisition patch size # if angles.size > 1: # angi = min(angles[-1], max_il) # angx = min(angles[-1], max_xl) # else: # angi = min(angles, max_il) # angx = min(angles, max_xl) # dil, dxl = get_dxdy(dataset) # # wavelet needs to match the psf sampling # wavelet = wavelet.copy() # wavelet.as_miliseconds() # if wavelet.dt != conv_dt: # wavelet.resample(conv_dt) # wavelet.as_seconds() # # create the psf, use any vavg because we convert back to twt anyway. # the_psf = psf(wavelet, dil, dxl, 3000, angi, angx, twt=True, size=psf_size) # intp_kwargs = {"kind": "linear", "bounds_error": False, "assume_sorted": True} # # loop angles to create reflectivities which are convolved with the psf, then summed together # tqdm_th_pbar = tqdm(total=theta.size, desc="Convolving Angle", disable=silent) # for th in theta.ravel(): # if dask_client is None: # tqdm_rfl_pbar = tqdm( # total=ni * nj, desc="Calculating Reflectivity", disable=silent # ) # for i in dataset.iind.values: # trace_s_ = np.s_[i, :, :] # reflc_[i, :, :] = _convolution_psf_line_inner( # dataset[vp_var][trace_s_].values, # dataset[vs_var][trace_s_].values, # dataset[rho_var][trace_s_].values, # dataset[twt_var][trace_s_].values, # subtwt=subtwt, # refl_method=refl_method, # th=th, # pbar=tqdm_rfl_pbar, # intp_kwargs=intp_kwargs, # ) # # for j in dataset.jind.values: # # trace_s_ = np.s_[i, j, :] # # if np.all(np.isnan(dataset[vp_var][trace_s_].values)): # # # empty TWT # # psfc_[i, j, :] = 0.0 # # else: # # # if twt is None: # # # twt_stick = dataset[twt_var][trace_s_].values # # # subtwt = np.arange(twt_stick.min(), twt_stick.max(), conv_dt) # # # interpolate values to TWT domain # # vp_subtwt = interp1d( # # dataset[twt_var][trace_s_].values, # # dataset[vp_var][trace_s_].values, # # **intp_kwargs, # # )(subtwt) # # vs_subtwt = interp1d( # # dataset[twt_var][trace_s_].values, # # dataset[vs_var][trace_s_].values, # # **intp_kwargs, # # )(subtwt) # # rho_subtwt = interp1d( # # dataset[twt_var][trace_s_].values, # # dataset[rho_var][trace_s_].values, # # **intp_kwargs, # # )(subtwt) # # reflc = reflectivity( # # th, vp_subtwt, vs_subtwt, rho_subtwt, method=refl_method # # ) # # reflc_[i, j, :-1] = reflc # tqdm_rfl_pbar.close() # else: # futures = dask_client.map( # _convolution_psf_line_inner, # [dataset[vp_var][i, :, :].values for i in dataset.iind.values], # [dataset[vs_var][i, :, :].values for i in dataset.iind.values], # [dataset[rho_var][i, :, :].values for i in dataset.iind.values], # [dataset[twt_var][i, :, :].values for i in dataset.iind.values], # subtwt=subtwt, # refl_method=refl_method, # th=th, # batch_size=10, # resources={"process": 1}, # key="psf_reflectivity", # ) # secede() # results = dask_client.gather(futures) # rejoin() # reflc_[:, :, :] = np.concatenate(results) # psfc_ = ( # fftconvolve( # reflc_, # the_psf.psf.values, # "same", # ) # + psfc_ # ) # tqdm_th_pbar.update() # tqdm_th_pbar.close() # psfc_ = psfc_ / np.size(theta.ravel()) # del reflc_ # free up some memory # synth = np.zeros((ni, nj, vert_size)) # preallocate output memory # for i in dataset.iind.values: # for j in dataset.jind.values: # # don't interpolate blank traces # if np.all(np.isnan(twt_sticks[i, j, :])): # synth[i, j, :] = 0.0 # else: # synth[i, j, :] = interp1d( # subtwt, # psfc_[i, j, :], # kind="cubic", # bounds_error=False, # fill_value=0.0, # assume_sorted=True, # )(twt_sticks[i, j, :]) # return synth
[ "numpy.pad", "numpy.isnan", "numpy.full_like", "scipy.signal.fftconvolve" ]
[((1191, 1221), 'numpy.full_like', 'np.full_like', (['velp[:-1]', 'theta'], {}), '(velp[:-1], theta)\n', (1203, 1221), True, 'import numpy as np\n'), ((2140, 2160), 'numpy.pad', 'np.pad', (['refl', '(1, 0)'], {}), '(refl, (1, 0))\n', (2146, 2160), True, 'import numpy as np\n'), ((498, 509), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (506, 509), True, 'import numpy as np\n'), ((609, 620), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (617, 620), True, 'import numpy as np\n'), ((2091, 2111), 'numpy.isnan', 'np.isnan', (['refl[name]'], {}), '(refl[name])\n', (2099, 2111), True, 'import numpy as np\n'), ((4176, 4245), 'scipy.signal.fftconvolve', 'fftconvolve', (['trace[reflectivity_key].values', 'wavelet_amp'], {'mode': '"""same"""'}), "(trace[reflectivity_key].values, wavelet_amp, mode='same')\n", (4187, 4245), False, 'from scipy.signal import fftconvolve\n')]
import torch from torch.utils.data import Dataset import numpy as np import pandas as pd import utils class DatasetWithNegativeSampling(Dataset): """ We create new Dataset class because for pairwise ranking loss, an important step is negative sampling. For each user, the items that a user has not interacted with are candidate items (unobserved entries). The following function takes users identity and candidate items as input, and samples negative items randomly for each user from the candidate set of that user. During the training stage, the model ensures that the items that a user likes to be ranked higher than items he dislikes or has not interacted with. """ def __init__(self, train_df, test_df, user_col="user_id", item_col="item_id", train=False, training_pairs_per_user=None, num_positive_in_test=2, k=10): super(DatasetWithNegativeSampling, self).__init__() self.train_df = train_df self.test_df = test_df self.user_col = user_col self.item_col = item_col self.all_items = set(train_df[item_col].values).union(set(test_df[item_col].values)) self.all_users = set(train_df[user_col].values).union(set(test_df[user_col].values)) self.train = train self.training_pairs_per_user = training_pairs_per_user self.num_positive_in_test = num_positive_in_test # Will be used while generating training and test df self.pos_item_col = "pos_item" self.neg_item_col = "neg_item" self.k = k # Run setup methods self.generate_candidates() self.build_new_df() def generate_candidates(self): # Items user interacted with self.interacted_during_training = { int(user_id): set(user_df[self.item_col].values) for user_id, user_df in self.train_df.groupby(self.user_col) } # Items user did not interact with self.unobserved_during_training = { user_id: np.array( list(self.all_items - observed) ) for user_id, observed in self.interacted_during_training.items() } self.pos_items_per_user_in_test = { int(user_id): np.random.choice( user_df[self.item_col].values, self.num_positive_in_test ) for user_id, user_df in self.test_df.groupby(self.user_col) } def build_new_df(self): # Build train tensor for DataLoader with three columns: user_id, pos_item_id, neg_item_id if self.train: # Use all available interacted items for training if None by setting to 0 if self.training_pairs_per_user is None: _users_items_interacted = { uid: len(items) for uid, items in self.interacted_during_training.items() } else: _users_items_interacted = { uid: self.training_pairs_per_user for uid in self.interacted_during_training } _user_id = self.train_df[self.user_col].unique() users = [uid for uid in _user_id for _ in range(_users_items_interacted[uid])] _pos_items = np.array([ np.random.choice( list(self.interacted_during_training[uid]), _users_items_interacted[uid] ) for uid in _user_id ]).flatten() _neg_items = np.array([ np.random.choice( list(self.unobserved_during_training[uid]), _users_items_interacted[uid] ) for uid in _user_id ]).flatten() assert len(_neg_items) == len(_pos_items) == len(users) new_train_df = pd.DataFrame({ self.user_col: users, self.pos_item_col: _pos_items, self.neg_item_col: _neg_items }) self.new_train_df = torch.from_numpy(new_train_df.values) # Build test tensor for DataLoader with three columns: user_id, item_id, is_positive else: _items_for_test = { int(user_id): user_df[self.item_col].values for user_id, user_df in self.test_df.groupby(self.user_col) } _users = [uid for uid in _items_for_test for _ in range(self.k)] # Because we simulate real interaction feedback we'll manually add at least one # Item which will be True in interactions # _items = np.array([ # np.append( # np.random.choice( # _items_for_test[uid], self.k - 1 # ), np.random.choice(self.pos_items_per_user_in_test[uid]) # ) for uid in _items_for_test.keys() # ]).flatten() _items = np.array([ np.random.choice( _items_for_test[uid], self.k ) for uid in _items_for_test.keys() ]).flatten() _is_positive = np.array([ item_id in self.pos_items_per_user_in_test[uid] for item_id, uid in zip(_items, _users) ]) assert len(_users) == len(_items) == len(_is_positive) new_test_df = pd.DataFrame({ self.user_col: _users, self.item_col: _items, "is_positive": _is_positive }) new_test_df["is_positive"] = new_test_df["is_positive"].astype(int) self.new_test_df = torch.from_numpy(new_test_df.values) return def __len__(self): if self.train: return len(self.new_train_df) return len(self.new_test_df) def __getitem__(self, idx): """Get negative candidate for user_id""" if self.train: user_id, pos_item, neg_item = self.new_train_df[idx] return user_id, pos_item, neg_item else: user_id, item_id, is_pos = self.new_test_df[idx] return user_id, item_id, is_pos class ImplicitFeedbackDataset(Dataset): def __init__(self, user_item_tensor, target_tensor): super(ImplicitFeedbackDataset, self).__init__() self.user_item_tensor = user_item_tensor self.target_tensor = target_tensor def __len__(self): return len(self.user_item_tensor) def __getitem__(self, index): return self.user_item_tensor[index], self.target_tensor[index] class SetupImplicitDataset: """ Almost always recommendation systems are built based on implicit feedback . One way to construct such data is to use items users interacted with as positive examples And other items as negative. However, it does not mean that user actually likes item they interacted with, Similarly it does not mean that users don't like items they didn't interact. This Dataset can handle explicit and implicit feedback simultaneously and designed to be used in training Neural networks with BCE loss https://pytorch.org/docs/stable/generated/torch.nn.BCELoss.html#torch.nn.BCELoss So we normalize explicit feedback (ratings) and binarize implicit """ def __init__(self, df, user_col="user_id", item_col="item_id", target_col="rating"): self.df = df self.user_col = user_col self.item_col = item_col self.target_col = target_col self.all_users = set(self.df[self.user_col].unique()) self.all_items = set(self.df[self.item_col].unique()) def binarize_implicit(self, df, num_negatives): interacted_items = df.groupby(self.user_col)[self.item_col].unique().to_dict() unseen_items = { uid: np.random.choice( list(self.all_items.difference(set(interacted))), num_negatives ) for uid, interacted in interacted_items.items() } # Create new df with both positive and negative items new_df = pd.DataFrame({ self.user_col: interacted_items.keys(), "pos_items": interacted_items.values(), "neg_items": unseen_items.values() }) new_df["pos_items"] = new_df["pos_items"].apply(lambda x: list(x)) new_df["neg_items"] = new_df["neg_items"].apply(lambda x: list(x)) new_df[self.item_col] = new_df["pos_items"] + new_df["neg_items"] new_df["pos_flag"] = new_df["pos_items"].apply(lambda x: [True for _ in range(len(x))]) new_df["neg_flag"] = new_df["neg_items"].apply(lambda x: [False for _ in range(len(x))]) new_df[self.target_col] = new_df["pos_flag"] + new_df["neg_flag"] # Drop auxiliary columns new_df = new_df.drop(["pos_items", "neg_items", "pos_flag", "neg_flag"], axis=1) new_df = new_df.explode([self.item_col, self.target_col]) # Cast all columns to float32 for col in new_df.columns: new_df[col] = new_df[col].astype("int32") return new_df def normalize_explicit(self): """Normalize rating values into [0; 1] from [0; max_rating]""" new_df = self.df.copy() max_rating = max(new_df[self.target_col]) new_df[self.target_col] = new_df[self.target_col] / max_rating return new_df[[self.user_col, self.item_col, self.target_col]] def setup(self, feedback_type="implicit", num_negatives=100, shuffle=True, train_size=None, validation_df=False, as_torch_tensor=True): if feedback_type == "implicit": new_df = self.binarize_implicit(self.df, num_negatives) elif feedback_type == "explicit": new_df = self.normalize_explicit() else: raise ValueError(f"feedback_type should be one of 'implicit', 'explicit', got {feedback_type}") # Split the data if validation_df: train_df, val_df, test_df = utils.split_data(new_df, shuffle, train_size, validation_df) if as_torch_tensor: _cols = [[self.user_col, self.item_col], self.target_col] train_tensor = utils.torch_from_pandas(train_df, cols=_cols) val_tensor = utils.torch_from_pandas(val_df, cols=_cols) test_tensor = utils.torch_from_pandas(test_df, cols=_cols) return train_tensor, val_tensor, test_tensor return train_df, val_df, test_df else: train_df, test_df = utils.split_data(new_df, shuffle, train_size, validation_df) if as_torch_tensor: _cols = [[self.user_col, self.item_col], self.target_col] _types = ["int", "float"] train_tensor = utils.torch_from_pandas(train_df, cols=_cols, types=_types) test_tensor = utils.torch_from_pandas(test_df, cols=_cols, types=_types) return train_tensor, test_tensor return train_df, test_df
[ "utils.torch_from_pandas", "numpy.random.choice", "utils.split_data", "torch.from_numpy", "pandas.DataFrame" ]
[((2249, 2323), 'numpy.random.choice', 'np.random.choice', (['user_df[self.item_col].values', 'self.num_positive_in_test'], {}), '(user_df[self.item_col].values, self.num_positive_in_test)\n', (2265, 2323), True, 'import numpy as np\n'), ((3826, 3929), 'pandas.DataFrame', 'pd.DataFrame', (['{self.user_col: users, self.pos_item_col: _pos_items, self.neg_item_col:\n _neg_items}'], {}), '({self.user_col: users, self.pos_item_col: _pos_items, self.\n neg_item_col: _neg_items})\n', (3838, 3929), True, 'import pandas as pd\n'), ((4032, 4069), 'torch.from_numpy', 'torch.from_numpy', (['new_train_df.values'], {}), '(new_train_df.values)\n', (4048, 4069), False, 'import torch\n'), ((5370, 5463), 'pandas.DataFrame', 'pd.DataFrame', (["{self.user_col: _users, self.item_col: _items, 'is_positive': _is_positive}"], {}), "({self.user_col: _users, self.item_col: _items, 'is_positive':\n _is_positive})\n", (5382, 5463), True, 'import pandas as pd\n'), ((5634, 5670), 'torch.from_numpy', 'torch.from_numpy', (['new_test_df.values'], {}), '(new_test_df.values)\n', (5650, 5670), False, 'import torch\n'), ((9962, 10022), 'utils.split_data', 'utils.split_data', (['new_df', 'shuffle', 'train_size', 'validation_df'], {}), '(new_df, shuffle, train_size, validation_df)\n', (9978, 10022), False, 'import utils\n'), ((10509, 10569), 'utils.split_data', 'utils.split_data', (['new_df', 'shuffle', 'train_size', 'validation_df'], {}), '(new_df, shuffle, train_size, validation_df)\n', (10525, 10569), False, 'import utils\n'), ((10161, 10206), 'utils.torch_from_pandas', 'utils.torch_from_pandas', (['train_df'], {'cols': '_cols'}), '(train_df, cols=_cols)\n', (10184, 10206), False, 'import utils\n'), ((10236, 10279), 'utils.torch_from_pandas', 'utils.torch_from_pandas', (['val_df'], {'cols': '_cols'}), '(val_df, cols=_cols)\n', (10259, 10279), False, 'import utils\n'), ((10310, 10354), 'utils.torch_from_pandas', 'utils.torch_from_pandas', (['test_df'], {'cols': '_cols'}), '(test_df, cols=_cols)\n', (10333, 10354), False, 'import utils\n'), ((10749, 10808), 'utils.torch_from_pandas', 'utils.torch_from_pandas', (['train_df'], {'cols': '_cols', 'types': '_types'}), '(train_df, cols=_cols, types=_types)\n', (10772, 10808), False, 'import utils\n'), ((10839, 10897), 'utils.torch_from_pandas', 'utils.torch_from_pandas', (['test_df'], {'cols': '_cols', 'types': '_types'}), '(test_df, cols=_cols, types=_types)\n', (10862, 10897), False, 'import utils\n'), ((4957, 5003), 'numpy.random.choice', 'np.random.choice', (['_items_for_test[uid]', 'self.k'], {}), '(_items_for_test[uid], self.k)\n', (4973, 5003), True, 'import numpy as np\n')]
# import sys # sys.path.append('../../') import numpy as np import pandas as pd import json import copy from plot_helper import coloring_legend, df_col_replace from constant import REPORTDAYS, HEADER_NAME, COLUMNS_TO_DROP, FIRST_ROW_AFTER_BURNIN def single_setting_IQR_json_generator(fpath_pattern_list, outfile_dir, outfile_stgy_tag, threshold): def T01_IQR_reporter_oneset_mostdangtriple(dflist, pattern, threshold): all_100_T01s = [] # in days for onerun in dflist: combined_geno_freq = onerun.filter(regex=pattern, axis=1).sum(axis=1).values # len=361 T01_this_run = float('inf') for idx,val in enumerate(combined_geno_freq): if val > threshold: T01_this_run = REPORTDAYS[idx] break all_100_T01s.append(T01_this_run) assert(len(all_100_T01s)==100) return np.quantile(all_100_T01s, [0.25, 0.5, 0.75]) def T01_IQR_reporter_oneset_mostdangdouble(dflist_arg, drug, threshold): option = 1 most_dang_double_tag = '2-2' if drug == 'DHA-PPQ' else '2-4' all_100_T01s = [] # in days dflist = copy.deepcopy(dflist_arg) # rename all 100 df's by `drug` and sum-up columns for i in range(len(dflist)): dflist[i] = df_col_replace(dflist[i], drug, option) combined_geno_freq = dflist[i][most_dang_double_tag].values # len=361 T01_this_run = float('inf') for idx,val in enumerate(combined_geno_freq): if val > threshold: T01_this_run = REPORTDAYS[idx] break all_100_T01s.append(T01_this_run) assert(len(all_100_T01s)==100) return np.quantile(all_100_T01s, [0.25, 0.5, 0.75]) # Main Driver Code set3_fpath, set4_fpath, set7_fpath, set8_fpath, set11_fpath, set12_fpath = fpath_pattern_list # all rows, all sets iqr_median = {} iqr_25p = {} iqr_75p = {} dflist_set3 = [] dflist_set4 = [] dflist_set7 = [] dflist_set8 = [] dflist_set11 = [] dflist_set12 = [] for i in range(1,101): dflist_set3.append( pd.read_csv(set3_fpath%i, index_col=False, names=HEADER_NAME, sep='\t').drop(columns=COLUMNS_TO_DROP) ) dflist_set4.append( pd.read_csv(set4_fpath%i, index_col=False, names=HEADER_NAME, sep='\t').drop(columns=COLUMNS_TO_DROP) ) dflist_set7.append( pd.read_csv(set7_fpath%i, index_col=False, names=HEADER_NAME, sep='\t').drop(columns=COLUMNS_TO_DROP) ) dflist_set8.append( pd.read_csv(set8_fpath%i, index_col=False, names=HEADER_NAME, sep='\t').drop(columns=COLUMNS_TO_DROP) ) dflist_set11.append( pd.read_csv(set11_fpath%i, index_col=False, names=HEADER_NAME, sep='\t').drop(columns=COLUMNS_TO_DROP) ) dflist_set12.append( pd.read_csv(set12_fpath%i, index_col=False, names=HEADER_NAME, sep='\t').drop(columns=COLUMNS_TO_DROP) ) # initialize with row1 # set3 temp = T01_IQR_reporter_oneset_mostdangtriple(dflist_set3, 'TYY..Y2.', threshold) assert(len(temp)==3) # 25p, median, and 75p values iqr_median['row1'] = [temp[1]] iqr_25p['row1'] = [temp[0]] iqr_75p['row1'] = [temp[2]] # set4 temp = T01_IQR_reporter_oneset_mostdangtriple(dflist_set4, 'TYY..Y2.', threshold) assert(len(temp)==3) iqr_median['row1'].append(temp[1]) iqr_25p['row1'].append(temp[0]) iqr_75p['row1'].append(temp[2]) # set7 temp = T01_IQR_reporter_oneset_mostdangtriple(dflist_set7, 'TYY..Y2.', threshold) assert(len(temp)==3) iqr_median['row1'].append(temp[1]) iqr_25p['row1'].append(temp[0]) iqr_75p['row1'].append(temp[2]) # set8 temp = T01_IQR_reporter_oneset_mostdangtriple(dflist_set8, 'TYY..Y2.', threshold) assert(len(temp)==3) iqr_median['row1'].append(temp[1]) iqr_25p['row1'].append(temp[0]) iqr_75p['row1'].append(temp[2]) # set11 temp = T01_IQR_reporter_oneset_mostdangtriple(dflist_set11, 'TYY..Y2.', threshold) assert(len(temp)==3) iqr_median['row1'].append(temp[1]) iqr_25p['row1'].append(temp[0]) iqr_75p['row1'].append(temp[2]) # set12 temp = T01_IQR_reporter_oneset_mostdangtriple(dflist_set12, 'TYY..Y2.', threshold) assert(len(temp)==3) iqr_median['row1'].append(temp[1]) iqr_25p['row1'].append(temp[0]) iqr_75p['row1'].append(temp[2]) # row2 # set3 temp = T01_IQR_reporter_oneset_mostdangtriple(dflist_set3, 'KNF..Y2.', threshold) assert(len(temp)==3) # 25p, median, and 75p values iqr_median['row2'] = [temp[1]] iqr_25p['row2'] = [temp[0]] iqr_75p['row2'] = [temp[2]] # set4 temp = T01_IQR_reporter_oneset_mostdangtriple(dflist_set4, 'KNF..Y2.', threshold) assert(len(temp)==3) iqr_median['row2'].append(temp[1]) iqr_25p['row2'].append(temp[0]) iqr_75p['row2'].append(temp[2]) # set7 temp = T01_IQR_reporter_oneset_mostdangtriple(dflist_set7, 'KNF..Y2.', threshold) assert(len(temp)==3) iqr_median['row2'].append(temp[1]) iqr_25p['row2'].append(temp[0]) iqr_75p['row2'].append(temp[2]) # set8 temp = T01_IQR_reporter_oneset_mostdangtriple(dflist_set8, 'KNF..Y2.', threshold) assert(len(temp)==3) iqr_median['row2'].append(temp[1]) iqr_25p['row2'].append(temp[0]) iqr_75p['row2'].append(temp[2]) # set11 temp = T01_IQR_reporter_oneset_mostdangtriple(dflist_set11, 'KNF..Y2.', threshold) assert(len(temp)==3) iqr_median['row2'].append(temp[1]) iqr_25p['row2'].append(temp[0]) iqr_75p['row2'].append(temp[2]) # set12 temp = T01_IQR_reporter_oneset_mostdangtriple(dflist_set12, 'KNF..Y2.', threshold) assert(len(temp)==3) iqr_median['row2'].append(temp[1]) iqr_25p['row2'].append(temp[0]) iqr_75p['row2'].append(temp[2]) # row3 # set3 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set3, 'DHA-PPQ', threshold) assert(len(temp)==3) # 25p, median, and 75p values iqr_median['row3'] = [temp[1]] iqr_25p['row3'] = [temp[0]] iqr_75p['row3'] = [temp[2]] # set4 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set4, 'DHA-PPQ', threshold) assert(len(temp)==3) iqr_median['row3'].append(temp[1]) iqr_25p['row3'].append(temp[0]) iqr_75p['row3'].append(temp[2]) # set7 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set7, 'DHA-PPQ', threshold) assert(len(temp)==3) iqr_median['row3'].append(temp[1]) iqr_25p['row3'].append(temp[0]) iqr_75p['row3'].append(temp[2]) # set8 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set8, 'DHA-PPQ', threshold) assert(len(temp)==3) iqr_median['row3'].append(temp[1]) iqr_25p['row3'].append(temp[0]) iqr_75p['row3'].append(temp[2]) # set11 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set11, 'DHA-PPQ', threshold) assert(len(temp)==3) iqr_median['row3'].append(temp[1]) iqr_25p['row3'].append(temp[0]) iqr_75p['row3'].append(temp[2]) # set12 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set12, 'DHA-PPQ', threshold) assert(len(temp)==3) iqr_median['row3'].append(temp[1]) iqr_25p['row3'].append(temp[0]) iqr_75p['row3'].append(temp[2]) # row4 # set3 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set3, 'ASAQ', threshold) assert(len(temp)==3) # 25p, median, and 75p values iqr_median['row4'] = [temp[1]] iqr_25p['row4'] = [temp[0]] iqr_75p['row4'] = [temp[2]] # set4 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set4, 'ASAQ', threshold) assert(len(temp)==3) iqr_median['row4'].append(temp[1]) iqr_25p['row4'].append(temp[0]) iqr_75p['row4'].append(temp[2]) # set7 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set7, 'ASAQ', threshold) assert(len(temp)==3) iqr_median['row4'].append(temp[1]) iqr_25p['row4'].append(temp[0]) iqr_75p['row4'].append(temp[2]) # set8 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set8, 'ASAQ', threshold) assert(len(temp)==3) iqr_median['row4'].append(temp[1]) iqr_25p['row4'].append(temp[0]) iqr_75p['row4'].append(temp[2]) # set11 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set11, 'ASAQ', threshold) assert(len(temp)==3) iqr_median['row4'].append(temp[1]) iqr_25p['row4'].append(temp[0]) iqr_75p['row4'].append(temp[2]) # set12 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set12, 'ASAQ', threshold) assert(len(temp)==3) iqr_median['row4'].append(temp[1]) iqr_25p['row4'].append(temp[0]) iqr_75p['row4'].append(temp[2]) # row5 # set3 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set3, 'AL', threshold) assert(len(temp)==3) # 25p, median, and 75p values iqr_median['row5'] = [temp[1]] iqr_25p['row5'] = [temp[0]] iqr_75p['row5'] = [temp[2]] # set4 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set4, 'AL', threshold) assert(len(temp)==3) iqr_median['row5'].append(temp[1]) iqr_25p['row5'].append(temp[0]) iqr_75p['row5'].append(temp[2]) # set7 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set7, 'AL', threshold) assert(len(temp)==3) iqr_median['row5'].append(temp[1]) iqr_25p['row5'].append(temp[0]) iqr_75p['row5'].append(temp[2]) # set8 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set8, 'AL', threshold) assert(len(temp)==3) iqr_median['row5'].append(temp[1]) iqr_25p['row5'].append(temp[0]) iqr_75p['row5'].append(temp[2]) # set11 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set11, 'AL', threshold) assert(len(temp)==3) iqr_median['row5'].append(temp[1]) iqr_25p['row5'].append(temp[0]) iqr_75p['row5'].append(temp[2]) # set12 temp = T01_IQR_reporter_oneset_mostdangdouble(dflist_set12, 'AL', threshold) assert(len(temp)==3) iqr_median['row5'].append(temp[1]) iqr_25p['row5'].append(temp[0]) iqr_75p['row5'].append(temp[2]) # if directory exist check happening # in main script notebook file with open(outfile_dir+outfile_stgy_tag+'_median.json', 'w') as outfile: json.dump(iqr_median, outfile) with open(outfile_dir+outfile_stgy_tag+'_25p.json', 'w') as outfile: json.dump(iqr_25p, outfile) with open(outfile_dir+outfile_stgy_tag+'_75p.json', 'w') as outfile: json.dump(iqr_75p, outfile)
[ "pandas.read_csv", "plot_helper.df_col_replace", "numpy.quantile", "copy.deepcopy", "json.dump" ]
[((833, 877), 'numpy.quantile', 'np.quantile', (['all_100_T01s', '[0.25, 0.5, 0.75]'], {}), '(all_100_T01s, [0.25, 0.5, 0.75])\n', (844, 877), True, 'import numpy as np\n'), ((1079, 1104), 'copy.deepcopy', 'copy.deepcopy', (['dflist_arg'], {}), '(dflist_arg)\n', (1092, 1104), False, 'import copy\n'), ((1584, 1628), 'numpy.quantile', 'np.quantile', (['all_100_T01s', '[0.25, 0.5, 0.75]'], {}), '(all_100_T01s, [0.25, 0.5, 0.75])\n', (1595, 1628), True, 'import numpy as np\n'), ((9684, 9714), 'json.dump', 'json.dump', (['iqr_median', 'outfile'], {}), '(iqr_median, outfile)\n', (9693, 9714), False, 'import json\n'), ((9790, 9817), 'json.dump', 'json.dump', (['iqr_25p', 'outfile'], {}), '(iqr_25p, outfile)\n', (9799, 9817), False, 'import json\n'), ((9893, 9920), 'json.dump', 'json.dump', (['iqr_75p', 'outfile'], {}), '(iqr_75p, outfile)\n', (9902, 9920), False, 'import json\n'), ((1211, 1250), 'plot_helper.df_col_replace', 'df_col_replace', (['dflist[i]', 'drug', 'option'], {}), '(dflist[i], drug, option)\n', (1225, 1250), False, 'from plot_helper import coloring_legend, df_col_replace\n'), ((1991, 2064), 'pandas.read_csv', 'pd.read_csv', (['(set3_fpath % i)'], {'index_col': '(False)', 'names': 'HEADER_NAME', 'sep': '"""\t"""'}), "(set3_fpath % i, index_col=False, names=HEADER_NAME, sep='\\t')\n", (2002, 2064), True, 'import pandas as pd\n'), ((2129, 2202), 'pandas.read_csv', 'pd.read_csv', (['(set4_fpath % i)'], {'index_col': '(False)', 'names': 'HEADER_NAME', 'sep': '"""\t"""'}), "(set4_fpath % i, index_col=False, names=HEADER_NAME, sep='\\t')\n", (2140, 2202), True, 'import pandas as pd\n'), ((2267, 2340), 'pandas.read_csv', 'pd.read_csv', (['(set7_fpath % i)'], {'index_col': '(False)', 'names': 'HEADER_NAME', 'sep': '"""\t"""'}), "(set7_fpath % i, index_col=False, names=HEADER_NAME, sep='\\t')\n", (2278, 2340), True, 'import pandas as pd\n'), ((2405, 2478), 'pandas.read_csv', 'pd.read_csv', (['(set8_fpath % i)'], {'index_col': '(False)', 'names': 'HEADER_NAME', 'sep': '"""\t"""'}), "(set8_fpath % i, index_col=False, names=HEADER_NAME, sep='\\t')\n", (2416, 2478), True, 'import pandas as pd\n'), ((2544, 2618), 'pandas.read_csv', 'pd.read_csv', (['(set11_fpath % i)'], {'index_col': '(False)', 'names': 'HEADER_NAME', 'sep': '"""\t"""'}), "(set11_fpath % i, index_col=False, names=HEADER_NAME, sep='\\t')\n", (2555, 2618), True, 'import pandas as pd\n'), ((2684, 2758), 'pandas.read_csv', 'pd.read_csv', (['(set12_fpath % i)'], {'index_col': '(False)', 'names': 'HEADER_NAME', 'sep': '"""\t"""'}), "(set12_fpath % i, index_col=False, names=HEADER_NAME, sep='\\t')\n", (2695, 2758), True, 'import pandas as pd\n')]
# Analytic Hierarchy Process import numpy as np # class myAHP class myAHP: # __init__(self) def __init__(self): # print("__init__(self).start...") self.RI_dict = { 1: 0, 2: 0, 3: 0.58, 4: 0.90, 5: 1.12, 6: 1.24, 7: 1.32, 8: 1.41, 9: 1.45, 10: 1.51, 11: 1.54, 12: 1.56, 13: 1.57, 14: 1.59, 15: 1.59, 16: 1.60, 17: 1.61, 18: 1.62, 19: 1.63, 20: 1.64 } self.comparison_matrix = np.array([ [0.50, 0.77, 0.48, 0.68, 0.47, 0.38], [0.23, 0.50, 0.28, 0.45, 0.32, 0.23], [0.52, 0.72, 0.50, 0.75, 0.48, 0.40], [0.32, 0.55, 0.25, 0.50, 0.23, 0.20], [0.53, 0.68, 0.52, 0.77, 0.50, 0.48], [0.62, 0.77, 0.60, 0.80, 0.52, 0.50] ]) # __init__(self) # get_w(array) def get_w(self, array): print("get_w(array).start...") row = array.shape[0] a_axis_0_sum = array.sum(axis=0) # print(a_axis_0_sum) b = array / a_axis_0_sum # new matrix b # print(b) b_axis_0_sum = b.sum(axis=0) b_axis_1_sum = b.sum(axis=1) # print("b_axis_1_sum") print(b_axis_1_sum) w = b_axis_1_sum / row # nw = w * row AW = (w * array).sum(axis=1) print("AW:") print(AW) max_max = sum(AW / (row * w)) print("max_max:") print(max_max) # calculating print("calculating") CI = (max_max - row) / (row - 1) print("CI:") print(CI) print("row:") print(row) print("RI_dictt[row]") print(self.RI_dict[row]) print("/*------------------------*/") CR = CI / self.RI_dict[row] print("over!") if CR < 0.1: print("CR:") print(CR) # print(round(CR, 3)) print('success!!') return w else: print(round(CR, 3)) print('please modify your data') print("get_w(array).end...") # get_w(array) # def main(array) def mainAlgorithm(self, array): print("main(array).start...") if type(array) is np.ndarray: result = self.get_w(array) return result else: print('please input an instance of numpy') print("main(array).start...") # def main(array) # comparison_economic_function() def comparison_function(self): print("comparison_function(self).start...") e = np.array([ [1, 2, 7, 5], [1/2, 1, 4, 3], [1/7, 1/4, 1, 2], [1/5, 1/4, 1/2, 1] ]) a = self.comparison_matrix b = self.comparison_matrix c = self.comparison_matrix d = self.comparison_matrix f = self.comparison_matrix # print("e") e = self.mainAlgorithm(e) # print("e") # print("a") a = self.mainAlgorithm(a) # print("a") # print("b") b = self.mainAlgorithm(b) # print("b") # print("c") c = self.mainAlgorithm(c) # print("c") # print("d") d = self.mainAlgorithm(d) # print("d") try: print("try") # res = np.array([a, b, c, d, f]) res = np.array([a, b, c, d]) # print("res:") # print(res) resT = np.transpose(res) # print("resT:") # print(resT) # print("e:") # print(e) print("ret:") ret = (resT * e).sum(axis=1) print(ret) print("try.end: ret") return ret except TypeError: print('data error') print("comparison_function(self).end...") # comparison_function() # class myAHP # __main__ if __name__ == '__main__': print("MyAHP.py__main__.start...") ahp = myAHP() ahp.comparison_function() print("MyAHP.py__main__.end...") # __main__
[ "numpy.array", "numpy.transpose" ]
[((507, 747), 'numpy.array', 'np.array', (['[[0.5, 0.77, 0.48, 0.68, 0.47, 0.38], [0.23, 0.5, 0.28, 0.45, 0.32, 0.23],\n [0.52, 0.72, 0.5, 0.75, 0.48, 0.4], [0.32, 0.55, 0.25, 0.5, 0.23, 0.2],\n [0.53, 0.68, 0.52, 0.77, 0.5, 0.48], [0.62, 0.77, 0.6, 0.8, 0.52, 0.5]]'], {}), '([[0.5, 0.77, 0.48, 0.68, 0.47, 0.38], [0.23, 0.5, 0.28, 0.45, 0.32,\n 0.23], [0.52, 0.72, 0.5, 0.75, 0.48, 0.4], [0.32, 0.55, 0.25, 0.5, 0.23,\n 0.2], [0.53, 0.68, 0.52, 0.77, 0.5, 0.48], [0.62, 0.77, 0.6, 0.8, 0.52,\n 0.5]])\n', (515, 747), True, 'import numpy as np\n'), ((2579, 2673), 'numpy.array', 'np.array', (['[[1, 2, 7, 5], [1 / 2, 1, 4, 3], [1 / 7, 1 / 4, 1, 2], [1 / 5, 1 / 4, 1 / 2, 1]\n ]'], {}), '([[1, 2, 7, 5], [1 / 2, 1, 4, 3], [1 / 7, 1 / 4, 1, 2], [1 / 5, 1 /\n 4, 1 / 2, 1]])\n', (2587, 2673), True, 'import numpy as np\n'), ((3394, 3416), 'numpy.array', 'np.array', (['[a, b, c, d]'], {}), '([a, b, c, d])\n', (3402, 3416), True, 'import numpy as np\n'), ((3490, 3507), 'numpy.transpose', 'np.transpose', (['res'], {}), '(res)\n', (3502, 3507), True, 'import numpy as np\n')]
import os import numpy as np import torch as T import torch.nn.functional as F from networks import ActorNetwork, CriticNetwork from noise import OUActionNoise from buffer import ReplayBuffer import gym from matplotlib import pyplot as plt class Agent(): def __init__(self, alpha, beta, input_dims, tau, n_actions, gamma=0.9, max_size=5000, fc1_dims=300, fc2_dims=200, batch_size=32): self.gamma = gamma self.tau = tau self.batch_size = batch_size self.alpha = alpha self.beta = beta self.memory = ReplayBuffer(max_size, input_dims, n_actions) self.noise = OUActionNoise(mu=np.zeros(n_actions)) self.actor = ActorNetwork(alpha, input_dims, fc1_dims, fc2_dims, n_actions=n_actions, name='actor') self.critic = CriticNetwork(beta, input_dims, fc1_dims, fc2_dims, n_actions=n_actions, name='critic') self.target_actor = ActorNetwork(alpha, input_dims, fc1_dims, fc2_dims, n_actions=n_actions, name='target_actor') self.target_critic = CriticNetwork(beta, input_dims, fc1_dims, fc2_dims, n_actions=n_actions, name='target_critic') self.update_network_parameters(tau=1) def choose_action(self, observation): self.actor.eval() #启动评估模式,关闭dropout和batchnorm state = T.tensor(observation, dtype=T.float).to(self.actor.device) mu = self.actor.forward(state).to(self.actor.device) self.actor.train() #启动训练模式,开启dropout.... return mu.cpu().detach().numpy()[0] def remember(self, state, action, reward, state_, done): self.memory.store_transition(state, action, reward, state_, done) def save_models(self, path = 'tmp/ddpg'): self.actor.save_checkpoint(chkpt_dir=path) self.target_actor.save_checkpoint(chkpt_dir=path) self.critic.save_checkpoint(chkpt_dir=path) self.target_critic.save_checkpoint(chkpt_dir=path) def load_models(self, path = 'tmp/ddpg'): self.actor.load_checkpoint(chkpt_dir=path) self.target_actor.load_checkpoint(chkpt_dir=path) self.critic.load_checkpoint(chkpt_dir=path) self.target_critic.load_checkpoint(chkpt_dir=path) def learn(self): if self.memory.mem_cntr < self.batch_size: return states, actions, rewards, states_, done = \ self.memory.sample_buffer(self.batch_size) states = T.tensor(states, dtype=T.float).to(self.actor.device) states_ = T.tensor(states_, dtype=T.float).to(self.actor.device) actions = T.tensor(actions, dtype=T.float).to(self.actor.device) rewards = T.tensor(rewards, dtype=T.float).to(self.actor.device) done = T.tensor(done).to(self.actor.device) target_actions = self.target_actor.forward(states_) critic_value_ = self.target_critic.forward(states_, target_actions) critic_value = self.critic.forward(states, actions) critic_value_[done] = 0.0 critic_value_ = critic_value_.view(-1) target = rewards + self.gamma*critic_value_ target = target.view(self.batch_size, 1) self.critic.optimizer.zero_grad() critic_loss = F.mse_loss(target, critic_value) critic_loss.backward() self.critic.optimizer.step() self.actor.optimizer.zero_grad() actor_loss = -self.critic.forward(states, self.actor.forward(states)) actor_loss = T.mean(actor_loss) actor_loss.backward() self.actor.optimizer.step() self.update_network_parameters() def update_network_parameters(self, tau=None): if tau is None: tau = self.tau actor_params = self.actor.named_parameters() critic_params = self.critic.named_parameters() target_actor_params = self.target_actor.named_parameters() target_critic_params = self.target_critic.named_parameters() critic_state_dict = dict(critic_params) actor_state_dict = dict(actor_params) target_critic_state_dict = dict(target_critic_params) target_actor_state_dict = dict(target_actor_params) for name in critic_state_dict: critic_state_dict[name] = tau*critic_state_dict[name].clone() + \ (1-tau)*target_critic_state_dict[name].clone() for name in actor_state_dict: actor_state_dict[name] = tau*actor_state_dict[name].clone() + \ (1-tau)*target_actor_state_dict[name].clone() self.target_critic.load_state_dict(critic_state_dict) self.target_actor.load_state_dict(actor_state_dict) #self.target_critic.load_state_dict(critic_state_dict, strict=False) #self.target_actor.load_state_dict(actor_state_dict, strict=False) if __name__ == '__main__': # gym环境下的测试代码,并产生数据 env = gym.make('Pendulum-v0') agent = Agent(alpha=0.0001, beta=0.001, input_dims=3, tau=0.001, batch_size=64, fc1_dims=400, fc2_dims=300, n_actions=env.action_space.shape[0]) n_games = 300 agent.load_models() best_score = env.reward_range[0] print(best_score) score_history = [] dataset = {"observations":[], "actions":[]} idx = 0 for i in range(n_games): observation = env.reset() done = False score = 0 # agent.noise.reset() while not done: env.render() dataset['observations'].append(observation) action = agent.choose_action(observation) dataset['actions'].append(action) observation_, reward, done, info = env.step([action]) agent.remember(observation, action, reward, observation_, done) # agent.learn() score += reward observation = observation_ idx += 1 print("idx= " + str(idx)) if idx > 10000: dataset["observations"] = np.array(dataset["observations"]).reshape(-1, 3) dataset["actions"] = np.array(dataset["actions"]).reshape(-1, 1) np.save('datasets10000.npy', dataset) break score_history.append(score) avg_score = np.mean(score_history[-100:]) if idx > 10000: break # if score > avg_score: # best_score = avg_score # agent.save_models() print('episode ', i, 'score %.1f' % score, 'average score %.1f' % avg_score) x = [i+1 for i in range(n_games)] # plt.plot(x, score_history) # plt.show()
[ "numpy.mean", "torch.nn.functional.mse_loss", "torch.mean", "torch.tensor", "numpy.zeros", "numpy.array", "networks.CriticNetwork", "buffer.ReplayBuffer", "numpy.save", "gym.make", "networks.ActorNetwork" ]
[((5107, 5130), 'gym.make', 'gym.make', (['"""Pendulum-v0"""'], {}), "('Pendulum-v0')\n", (5115, 5130), False, 'import gym\n'), ((606, 651), 'buffer.ReplayBuffer', 'ReplayBuffer', (['max_size', 'input_dims', 'n_actions'], {}), '(max_size, input_dims, n_actions)\n', (618, 651), False, 'from buffer import ReplayBuffer\n'), ((738, 828), 'networks.ActorNetwork', 'ActorNetwork', (['alpha', 'input_dims', 'fc1_dims', 'fc2_dims'], {'n_actions': 'n_actions', 'name': '"""actor"""'}), "(alpha, input_dims, fc1_dims, fc2_dims, n_actions=n_actions,\n name='actor')\n", (750, 828), False, 'from networks import ActorNetwork, CriticNetwork\n'), ((881, 972), 'networks.CriticNetwork', 'CriticNetwork', (['beta', 'input_dims', 'fc1_dims', 'fc2_dims'], {'n_actions': 'n_actions', 'name': '"""critic"""'}), "(beta, input_dims, fc1_dims, fc2_dims, n_actions=n_actions,\n name='critic')\n", (894, 972), False, 'from networks import ActorNetwork, CriticNetwork\n'), ((1033, 1130), 'networks.ActorNetwork', 'ActorNetwork', (['alpha', 'input_dims', 'fc1_dims', 'fc2_dims'], {'n_actions': 'n_actions', 'name': '"""target_actor"""'}), "(alpha, input_dims, fc1_dims, fc2_dims, n_actions=n_actions,\n name='target_actor')\n", (1045, 1130), False, 'from networks import ActorNetwork, CriticNetwork\n'), ((1192, 1290), 'networks.CriticNetwork', 'CriticNetwork', (['beta', 'input_dims', 'fc1_dims', 'fc2_dims'], {'n_actions': 'n_actions', 'name': '"""target_critic"""'}), "(beta, input_dims, fc1_dims, fc2_dims, n_actions=n_actions,\n name='target_critic')\n", (1205, 1290), False, 'from networks import ActorNetwork, CriticNetwork\n'), ((3408, 3440), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['target', 'critic_value'], {}), '(target, critic_value)\n', (3418, 3440), True, 'import torch.nn.functional as F\n'), ((3656, 3674), 'torch.mean', 'T.mean', (['actor_loss'], {}), '(actor_loss)\n', (3662, 3674), True, 'import torch as T\n'), ((6538, 6567), 'numpy.mean', 'np.mean', (['score_history[-100:]'], {}), '(score_history[-100:])\n', (6545, 6567), True, 'import numpy as np\n'), ((693, 712), 'numpy.zeros', 'np.zeros', (['n_actions'], {}), '(n_actions)\n', (701, 712), True, 'import numpy as np\n'), ((1486, 1522), 'torch.tensor', 'T.tensor', (['observation'], {'dtype': 'T.float'}), '(observation, dtype=T.float)\n', (1494, 1522), True, 'import torch as T\n'), ((2620, 2651), 'torch.tensor', 'T.tensor', (['states'], {'dtype': 'T.float'}), '(states, dtype=T.float)\n', (2628, 2651), True, 'import torch as T\n'), ((2693, 2725), 'torch.tensor', 'T.tensor', (['states_'], {'dtype': 'T.float'}), '(states_, dtype=T.float)\n', (2701, 2725), True, 'import torch as T\n'), ((2767, 2799), 'torch.tensor', 'T.tensor', (['actions'], {'dtype': 'T.float'}), '(actions, dtype=T.float)\n', (2775, 2799), True, 'import torch as T\n'), ((2841, 2873), 'torch.tensor', 'T.tensor', (['rewards'], {'dtype': 'T.float'}), '(rewards, dtype=T.float)\n', (2849, 2873), True, 'import torch as T\n'), ((2912, 2926), 'torch.tensor', 'T.tensor', (['done'], {}), '(done)\n', (2920, 2926), True, 'import torch as T\n'), ((6419, 6456), 'numpy.save', 'np.save', (['"""datasets10000.npy"""', 'dataset'], {}), "('datasets10000.npy', dataset)\n", (6426, 6456), True, 'import numpy as np\n'), ((6269, 6302), 'numpy.array', 'np.array', (["dataset['observations']"], {}), "(dataset['observations'])\n", (6277, 6302), True, 'import numpy as np\n'), ((6356, 6384), 'numpy.array', 'np.array', (["dataset['actions']"], {}), "(dataset['actions'])\n", (6364, 6384), True, 'import numpy as np\n')]
import numpy as np from collections.abc import Sequence from typing import BinaryIO from ..gmxflow import GmxFlow, GmxFlowVersion # Fields expected to be read in the files. __FIELDS = ['X', 'Y', 'N', 'T', 'M', 'U', 'V'] # Fields which represent data in the flow field, excluding positions. __DATA_FIELDS = ['N', 'T', 'M', 'U', 'V'] # List of fields in the order of writing. __FIELDS_ORDERED = ['N', 'T', 'M', 'U', 'V'] def read_flow(filename: str) -> GmxFlow: """Read flow field data from a file. Args: filename (str): File to read data from. Returns: GmxFlow: Flow field data. """ def get_header_field(info, label): try: field = info[label] except KeyError: raise ValueError(f"could not read {label} from `{filename}`") return field data, info = _read_data(filename) shape = get_header_field(info, 'shape') spacing = get_header_field(info, 'spacing') origin = get_header_field(info, 'origin') version_str = get_header_field(info, 'format') if version_str == 'GMX_FLOW_1': version = GmxFlowVersion(1) elif version_str == 'GMX_FLOW_2': version = GmxFlowVersion(2) else: raise ValueError(f"unknown file format `{version_str}`") dtype = [(l, float) for l in data.keys()] num_bins = np.prod(shape) data_new = np.zeros((num_bins, ), dtype=dtype) for key, value in data.items(): data_new[key] = value return GmxFlow( data=data_new, shape=shape, spacing=spacing, version=version, origin=origin, ) def _read_data(filename: str) -> tuple[dict[str, np.ndarray], dict[str, str]]: """Read field data from a file. The data is returned on a regular grid, adding zeros for bins with no values or which are not present in the (possibly not-full) input grid. The `x` and `y` coordinates are bin center positions, not corner. Args: filename (str): A file to read data from. Returns: (dict, dict): 2-tuple of dict's with data and information. """ with open(filename, 'rb') as fp: fields, num_values, info = _read_header(fp) data = _read_values(fp, num_values, fields) x0, y0 = info['origin'] nx, ny = info['shape'] dx, dy = info['spacing'] x = x0 + dx * (np.arange(nx) + 0.5) y = y0 + dy * (np.arange(ny) + 0.5) xs, ys = np.meshgrid(x, y, indexing='ij') grid = np.zeros((nx, ny), dtype=[(l, float) for l in __FIELDS]) grid['X'] = xs grid['Y'] = ys for l in __DATA_FIELDS: grid[l][data['IX'], data['IY']] = data[l] grid = grid.ravel() return {l: grid[l] for l in __FIELDS}, info def _read_values(fp: BinaryIO, num_values: int, fields: Sequence[str], ) -> dict[str, np.ndarray]: """Read the binary data in the given order.""" dtypes = { 'IX': np.uint64, 'IY': np.uint64, 'N': np.float32, 'T': np.float32, 'M': np.float32, 'U': np.float32, 'V': np.float32, } return { l: np.fromfile(fp, dtype=dtypes[l], count=num_values) for l in fields } def _read_header(fp: BinaryIO) -> tuple[list[str], int, dict[str, str]]: """Read header information and forward the pointer to the data.""" def read_shape(line): return tuple(int(v) for v in line.split()[1:3]) def read_spacing(line): return tuple(float(v) for v in line.split()[1:3]) def read_num_values(line): return int(line.split()[1].strip()) def read_format(line): return line.lstrip("FORMAT").strip() def parse_field_labels(line): return line.split()[1:] def read_header_string(fp): buf_size = 1024 header_str = "" while True: buf = fp.read(buf_size) pos = buf.find(b'\0') if pos != -1: header_str += buf[:pos].decode("ascii") offset = buf_size - pos - 1 fp.seek(-offset, 1) break else: header_str += buf.decode("ascii") return header_str info = {} header_str = read_header_string(fp) for line in header_str.splitlines(): line_type = line.split(maxsplit=1)[0].upper() if line_type == "SHAPE": info['shape'] = read_shape(line) elif line_type == "SPACING": info['spacing'] = read_spacing(line) elif line_type == "ORIGIN": info['origin'] = read_spacing(line) elif line_type == "FIELDS": fields = parse_field_labels(line) elif line_type == "NUMDATA": num_values = read_num_values(line) elif line_type == "FORMAT": info['format'] = read_format(line) info['num_bins'] = info['shape'][0] * info['shape'][1] return fields, num_values, info
[ "numpy.prod", "numpy.fromfile", "numpy.zeros", "numpy.meshgrid", "numpy.arange" ]
[((1343, 1357), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (1350, 1357), True, 'import numpy as np\n'), ((1373, 1407), 'numpy.zeros', 'np.zeros', (['(num_bins,)'], {'dtype': 'dtype'}), '((num_bins,), dtype=dtype)\n', (1381, 1407), True, 'import numpy as np\n'), ((2430, 2462), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {'indexing': '"""ij"""'}), "(x, y, indexing='ij')\n", (2441, 2462), True, 'import numpy as np\n'), ((2475, 2531), 'numpy.zeros', 'np.zeros', (['(nx, ny)'], {'dtype': '[(l, float) for l in __FIELDS]'}), '((nx, ny), dtype=[(l, float) for l in __FIELDS])\n', (2483, 2531), True, 'import numpy as np\n'), ((3148, 3198), 'numpy.fromfile', 'np.fromfile', (['fp'], {'dtype': 'dtypes[l]', 'count': 'num_values'}), '(fp, dtype=dtypes[l], count=num_values)\n', (3159, 3198), True, 'import numpy as np\n'), ((2356, 2369), 'numpy.arange', 'np.arange', (['nx'], {}), '(nx)\n', (2365, 2369), True, 'import numpy as np\n'), ((2396, 2409), 'numpy.arange', 'np.arange', (['ny'], {}), '(ny)\n', (2405, 2409), True, 'import numpy as np\n')]
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' \file processData.py \copyright Copyright (c) 2019 Visual Computing group of Ulm University, Germany. See the LICENSE file at the top-level directory of this distribution. \author <NAME> (<EMAIL>) ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' import sys import math import os import numpy as np from os import listdir from os.path import isfile, join ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(ROOT_DIR, 'MCCNN/utils')) from PyUtils import visualize_progress def process_model(modelPath): if not isfile(modelPath[:-4]+".npy"): corrupt = False fileDataArray = [] with open(modelPath, 'r') as modelFile: it = 0 for line in modelFile: line = line.replace("\n", "") if ("nan" not in line) and ("inf" not in line): currPoint = line.split(',') try: fileDataArray.append([float(currVal) for currVal in currPoint]) except ValueError: corrupt = True it+=1 if not(corrupt): np.save(modelPath[:-4]+".npy", np.array(fileDataArray)) return corrupt return False def get_files(): fileList = [] dataFolders = ["ao_data", "gi_data", "sss_data"] datasets = ["training", "evaluation", "test"] for currDataFolder in dataFolders: for currDataSet in datasets: for f in listdir(currDataFolder+"/"+currDataSet) : if isfile(join(currDataFolder+"/"+currDataSet+"/", f)) and f.endswith(".txt"): fileList.append(join(currDataFolder+"/"+currDataSet+"/", f)) return fileList if __name__ == '__main__': fileList = get_files() iter = 0 maxSize = 0.0 corruptFiles = [] for inFile in fileList: if process_model(inFile): corruptFiles.append(inFile) if iter%100==0: visualize_progress(iter, len(fileList)) iter = iter + 1 for currCorruptFile in corruptFiles: print(currCorruptFile) print(len(corruptFiles))
[ "os.listdir", "os.path.join", "os.path.isfile", "numpy.array", "os.path.abspath" ]
[((556, 581), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (571, 581), False, 'import os\n'), ((600, 637), 'os.path.join', 'os.path.join', (['ROOT_DIR', '"""MCCNN/utils"""'], {}), "(ROOT_DIR, 'MCCNN/utils')\n", (612, 637), False, 'import os\n'), ((726, 757), 'os.path.isfile', 'isfile', (["(modelPath[:-4] + '.npy')"], {}), "(modelPath[:-4] + '.npy')\n", (732, 757), False, 'from os.path import isfile, join\n'), ((1695, 1738), 'os.listdir', 'listdir', (["(currDataFolder + '/' + currDataSet)"], {}), "(currDataFolder + '/' + currDataSet)\n", (1702, 1738), False, 'from os import listdir\n'), ((1378, 1401), 'numpy.array', 'np.array', (['fileDataArray'], {}), '(fileDataArray)\n', (1386, 1401), True, 'import numpy as np\n'), ((1764, 1813), 'os.path.join', 'join', (["(currDataFolder + '/' + currDataSet + '/')", 'f'], {}), "(currDataFolder + '/' + currDataSet + '/', f)\n", (1768, 1813), False, 'from os.path import isfile, join\n'), ((1870, 1919), 'os.path.join', 'join', (["(currDataFolder + '/' + currDataSet + '/')", 'f'], {}), "(currDataFolder + '/' + currDataSet + '/', f)\n", (1874, 1919), False, 'from os.path import isfile, join\n')]
import os from base64 import b64encode, b64decode from typing import AnyStr, List, Dict from collections import Counter import numpy as np import cv2 as cv import keras import tensorflow as tf from yolo4.model import yolo4_body from decode_np import Decode __all__ = ("DetectJapan", "detect_japan_obj") session = tf.Session() keras.backend.set_session(session) def get_class(classes_path): classes_path = os.path.expanduser(classes_path) with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names def get_anchors(anchors_path): anchors_path = os.path.expanduser(anchors_path) with open(anchors_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(",")] return np.array(anchors).reshape(-1, 2) class DetectJapan: model_path = "JPY_weight.h5" # Keras model or weights must be a .h5 file. anchors_path = "model_data/yolo4_anchors.txt" classes_path = "model_data/JPY_classes.txt" jpy_classes = ('JPY_500', 'JPY_100', 'JPY_50', 'JPY_10', 'JPY_1', 'JPY_5') def __init__(self, conf_thresh: float = 0.8, nms_thresh: float = 0.8): class_names = get_class(self.classes_path) anchors = get_anchors(self.anchors_path) model_image_size = (416, 416) self._model: keras.Model = yolo4_body( inputs=keras.Input(shape=model_image_size + (3,)), num_anchors=len(anchors) // 3, num_classes=len(class_names), ) self._model.load_weights(os.path.expanduser(self.model_path)) self._decoder: Decode = Decode( obj_threshold=conf_thresh, nms_threshold=nms_thresh, input_shape=model_image_size, _yolo=self._model, all_classes=class_names, ) @property def model(self) -> keras.Model: return self._model @property def decoder(self) -> Decode: return self._decoder def detect(self, image_b64: AnyStr, *, fmt: str = ".png") -> Dict: image_bin: bytes = b64decode(image_b64) image = cv.imdecode(np.frombuffer(image_bin, np.uint8), cv.IMREAD_COLOR) image = cv.resize(image, dsize=(1080, 1080), interpolation=cv.INTER_AREA) with session.as_default(): with session.graph.as_default(): detect_image, *_, classes = self._decoder.detect_image(image, True) is_success, buffer = cv.imencode(fmt, detect_image) return { "img": b64encode(buffer.tobytes()).decode(), "count": self.count(classes) } def count(self, classes: List[int]): counter = Counter(classes) for key in tuple(counter.keys()): # 딕셔너리 키 이름 변경 counter[self.jpy_classes[key]] = counter.pop(key) # for class_ in tuple(counter): # counter[self.jpy_classes[class_]] = counter.pop(class_) return counter detect_japan_obj = DetectJapan()
[ "cv2.imencode", "decode_np.Decode", "tensorflow.Session", "keras.backend.set_session", "base64.b64decode", "collections.Counter", "numpy.array", "keras.Input", "numpy.frombuffer", "cv2.resize", "os.path.expanduser" ]
[((317, 329), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (327, 329), True, 'import tensorflow as tf\n'), ((330, 364), 'keras.backend.set_session', 'keras.backend.set_session', (['session'], {}), '(session)\n', (355, 364), False, 'import keras\n'), ((415, 447), 'os.path.expanduser', 'os.path.expanduser', (['classes_path'], {}), '(classes_path)\n', (433, 447), False, 'import os\n'), ((644, 676), 'os.path.expanduser', 'os.path.expanduser', (['anchors_path'], {}), '(anchors_path)\n', (662, 676), False, 'import os\n'), ((1637, 1775), 'decode_np.Decode', 'Decode', ([], {'obj_threshold': 'conf_thresh', 'nms_threshold': 'nms_thresh', 'input_shape': 'model_image_size', '_yolo': 'self._model', 'all_classes': 'class_names'}), '(obj_threshold=conf_thresh, nms_threshold=nms_thresh, input_shape=\n model_image_size, _yolo=self._model, all_classes=class_names)\n', (1643, 1775), False, 'from decode_np import Decode\n'), ((2096, 2116), 'base64.b64decode', 'b64decode', (['image_b64'], {}), '(image_b64)\n', (2105, 2116), False, 'from base64 import b64encode, b64decode\n'), ((2214, 2279), 'cv2.resize', 'cv.resize', (['image'], {'dsize': '(1080, 1080)', 'interpolation': 'cv.INTER_AREA'}), '(image, dsize=(1080, 1080), interpolation=cv.INTER_AREA)\n', (2223, 2279), True, 'import cv2 as cv\n'), ((2473, 2503), 'cv2.imencode', 'cv.imencode', (['fmt', 'detect_image'], {}), '(fmt, detect_image)\n', (2484, 2503), True, 'import cv2 as cv\n'), ((2690, 2706), 'collections.Counter', 'Counter', (['classes'], {}), '(classes)\n', (2697, 2706), False, 'from collections import Counter\n'), ((806, 823), 'numpy.array', 'np.array', (['anchors'], {}), '(anchors)\n', (814, 823), True, 'import numpy as np\n'), ((1568, 1603), 'os.path.expanduser', 'os.path.expanduser', (['self.model_path'], {}), '(self.model_path)\n', (1586, 1603), False, 'import os\n'), ((2145, 2179), 'numpy.frombuffer', 'np.frombuffer', (['image_bin', 'np.uint8'], {}), '(image_bin, np.uint8)\n', (2158, 2179), True, 'import numpy as np\n'), ((1396, 1438), 'keras.Input', 'keras.Input', ([], {'shape': '(model_image_size + (3,))'}), '(shape=model_image_size + (3,))\n', (1407, 1438), False, 'import keras\n')]
from pathlib import Path import pathlib import numpy as np import pandas as pd import matplotlib.pyplot as plt from typing import Union , Tuple class QuestionnaireAnalysis: def __init__(self, data_fname: Union[pathlib.Path, str]): self.data_fname = pathlib.Path(data_fname).resolve() if not self.data_fname.exists(): raise ValueError("File doesn't exist") def read_data(self): self.data = pd.read_json(self.data_fname) #Q1 def show_age_distrib(self) -> Tuple[np.ndarray, np.ndarray]: df = self.data hist, bins = np.histogram(df['age'], bins = [0,10,20,30,40,50,60,70,80,90,100]) return (hist, bins) #Q2 def remove_rows_without_mail(self) -> pd.DataFrame: df = self.data df = df[df['email'].str.contains(r'[^@]+@[^@]+\.[^@]+')] return df.reset_index() #Q3 def fill_na_with_mean(self) -> Tuple[pd.DataFrame, np.ndarray]: df = self.data mean_row = df.loc[:,['q1','q2','q3','q4','q5']].mean(axis=1) idxval = df.dropna(subset = ['q1','q2','q3','q4','q5']).index.values arr = np.array([i for i in list(df.index.values) if i not in idxval]) df.loc[:,['q1','q2','q3','q4','q5']] = df.loc[:,['q1','q2','q3','q4','q5']].fillna(mean_row[arr],axis=0) return (df , arr) #Q4 def score_subjects(self, maximal_nans_per_sub: int = 1) -> pd.DataFrame: df = self.data df_temp = df.loc[:,['q1','q2','q3','q4','q5']] mean_row = df_temp.mean(axis=1) for i , m in enumerate(mean_row): df_temp.loc[i,:] = df_temp.loc[i,:].fillna(m, limit = 1) df['score'] = df_temp.mean(skipna=False, axis=1).apply(np.floor).astype('UInt8') return df #Q5 def correlate_gender_age(self) -> pd.DataFrame: df = self.data df_filtered = df.loc[:,['gender','age','q1','q2','q3','q4','q5']] df_filtered['age'] = df_filtered['age'].dropna() > 40 grouped = df_filtered.groupby(['gender','age'] , as_index=True).mean() return grouped
[ "numpy.histogram", "pandas.read_json", "pathlib.Path" ]
[((443, 472), 'pandas.read_json', 'pd.read_json', (['self.data_fname'], {}), '(self.data_fname)\n', (455, 472), True, 'import pandas as pd\n'), ((591, 665), 'numpy.histogram', 'np.histogram', (["df['age']"], {'bins': '[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]'}), "(df['age'], bins=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100])\n", (603, 665), True, 'import numpy as np\n'), ((269, 293), 'pathlib.Path', 'pathlib.Path', (['data_fname'], {}), '(data_fname)\n', (281, 293), False, 'import pathlib\n')]
import os import sys import argparse import numpy as np import matplotlib.pyplot as plt from ruamel import yaml # in order to import modules from a folder in path '../cli/' sys.path.insert(1, '../cli/') # insert at 1, 0 is the script path (or '' in REPL) import modules.utilities as utilities import modules.MatplotlibSettings # this will override some of the settings of this script # in favor of the plot settings in the module MatplotlibSettings """ Usage: python3 plottestgrid.py <folder> <distribution name> <distribution type (PDF/FF)> <folder> - output of NangaParbat/tests/GridProduction.cc <distribution name> - distribution name, string that goes in the plot title. <distribution type> - distribution type (PDF or FF), string that goes in the plot title. """ # Parse arguments parser = argparse.ArgumentParser(prog = "plottestgrid.py", usage = " \n python3 plottestgrid.py <folder> <distribution name> <distribution type (PDF/FF)> \n", description = "Script to plot the output of the grid test done with tests/GridPriduction.cc") parser.add_argument('folder', help = 'output folder of NangaParbat/tests/GridProduction.cc') parser.add_argument('distribution name', help = 'string that goes in the plot title.') parser.add_argument('distribution type', help = 'PDF or FF, string that goes in the plot title.') # Print error if the required arguments are not given try: options = parser.parse_args() except: parser.print_help() sys.exit(0) # Arguments fold = sys.argv[1] distname = sys.argv[2] distype = sys.argv[3] # Set folder RunFolder = os.path.dirname(os.path.realpath(__file__)) # Ofolder = fold Ofolder = fold + "/testresults" testfiles = [] for tf in os.listdir(Ofolder): if tf[-4:] == "yaml": # if tf[:4] == "grid": testfiles.append(tf) for file in testfiles: # Read file to plot with open(Ofolder + "/" + file, "r") as test: toplot = yaml.load(test, Loader = yaml.RoundTripLoader) print("Plot from: " + file) if (str(toplot["Grid over direct"][0])[-2:] != "an"): # Exstract data ifl = toplot["ifl"] Q = toplot["Q"] x = toplot["x"] kT = toplot["kT"] tgrid = toplot["Grid interpolation"] direct = toplot["Direct calculation"] gridodir = toplot["Grid over direct"] # Plots fig, (ax1, ax2) = plt.subplots(nrows = 2, ncols = 1, figsize = (14, 8), sharex = "all", gridspec_kw = dict(width_ratios = [1], height_ratios = [4, 1])) plt.subplots_adjust(wspace = 0, hspace = 0) """ wspace = 0.2 # the amount of width reserved for space between subplots, # expressed as a fraction of the average axis width hspace = 0.2 # the amount of height reserved for space between subplots, # expressed as a fraction of the average axis height """ if distype == "FF" or distype == "ff": plt.suptitle("TMDGrids " + distname + " " + distype + "\n fl. = " + str(ifl) + " , Q = " + str(Q) + "[GeV] , z = " + str(x)) elif distype == "PDF" or distype == "pdf": plt.suptitle("TMDGrids " + distname + " " + distype + "\n fl. = " + str(ifl) + " , Q = " + str(Q) + "[GeV] , x = " + str(x)) # Define equally spaced bins and ticks for x axis nticks_x, majorticks, minorticks = utilities.BinsAndTicks(min(kT), max(kT)) # --- Upper plot --- # Labels if distype == "FF" or distype == "ff": ax1.set_ylabel(r"$zD_1(z, p_{\perp}; Q^2)$") elif distype == "PDF" or distype == "pdf": ax1.set_ylabel(r"$xf_1(x, k_T; Q^2)$") # Plot in log scale ax1.set_yscale("log") ax1.plot(kT, tgrid, linewidth = 1.5, color = "r", alpha = 0.6, label = "grid") ax1.plot(kT, tgrid, linewidth = 1.5, color = "r", alpha = 1, marker = 'o', markersize = 3) ax1.plot(kT, direct, linewidth = 1.5, color = "b", alpha = 0.6, label = "direct calculation") ax1.plot(kT, direct, linewidth = 1.5, color = "b", alpha = 1, marker = 'o', markersize = 3) ax1.axhline(0, linewidth = 0.8, color = "black") # Ticks ax1.set_xticks(majorticks) ax1.set_xticks(minorticks, minor=True) # If the folder name contains "_" replace it with the latex underscore if "_" in fold: legendfold = fold.replace("_", "\_") # Create legend ax1.legend(title_fontsize = 12, title = "from " + legendfold) else: # Create legend ax1.legend(title_fontsize = 12, title = "from " + fold) # Start x axis from 0 ax1.set_xlim(left = 0) # --- Lower plot --- # Labels if distype == "FF" or distype == "ff": ax2.set_xlabel(r"$p_{\perp}$ [GeV]") elif distype == "PDF" or distype == "pdf": ax2.set_xlabel(r"$k_T$ [GeV]") ax2.set_ylabel("Grid / Direct") # Plot ax2.plot(kT, gridodir, linewidth = 1.5, color = "g", alpha = 0.6, label = "grid / direct") # ax2.plot(kT, gridodir, linewidth = 1.5, color = "g", alpha = 0.3, label = "grid interpolation / direct") ax2.plot(kT, gridodir, linewidth = 1.5, color = "g", alpha = 1, marker = 'o', markersize = 3) ax2.axhline(1, linewidth = 0.8, color = "black") # Ticks and settings ax2.set_xticks(majorticks) ax2.set_xticks(minorticks, minor=True) # Start x axis from 0 ax2.set_xlim(left = 0) # Ticks for y axis # *** no effect with MatplotlibSettings *** # First tick starts at the multiple of 0.05 nearest to the minimum of the distribution ystart = round(min(gridodir), 2) start_yticks = np.trunc(ystart / 0.05) * 0.05 ax2.set_ylim(bottom = start_yticks, top = max(gridodir) + 0.05) # ***************************************** nticks_y, majorticks_y, minorticks_y = utilities.BinsAndTicks(min(gridodir), max(gridodir)) ax2.set_yticks(majorticks_y, minor = True) ax2.legend() # Create directory for the plots if it does not exist plotspath = fold + "/plots" try: os.mkdir(plotspath) print ("Creating '/plots' directory - plots will be there ...") except FileExistsError: # print ("'/plots' directory already exists - plots will be there ...") pass # Save plot fig.savefig(plotspath + "/" + file[:-5] + ".pdf") plt.close() else: print("Something went wrong, there are 'nan' in the file!") """ # Another way to have automatic ticks custom spaced from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator) # Make a plot with major ticks that are multiples of 20 and minor ticks that # are multiples of 5. Label major ticks with '%d' formatting but don't label # minor ticks. # '%d' formatting for integers, '%.2f' decimals. ax1.xaxis.set_major_locator(MultipleLocator(10)) ax1.xaxis.set_major_formatter(FormatStrFormatter('%d')) # For the minor ticks, use no labels; default NullFormatter. ax1.xaxis.set_minor_locator(MultipleLocator(5)) """
[ "os.listdir", "sys.path.insert", "argparse.ArgumentParser", "ruamel.yaml.load", "numpy.trunc", "os.path.realpath", "matplotlib.pyplot.close", "os.mkdir", "sys.exit", "matplotlib.pyplot.subplots_adjust" ]
[((174, 203), 'sys.path.insert', 'sys.path.insert', (['(1)', '"""../cli/"""'], {}), "(1, '../cli/')\n", (189, 203), False, 'import sys\n'), ((887, 1146), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""plottestgrid.py"""', 'usage': '""" \n python3 plottestgrid.py <folder> <distribution name> <distribution type (PDF/FF)> \n"""', 'description': '"""Script to plot the output of the grid test done with tests/GridPriduction.cc"""'}), '(prog=\'plottestgrid.py\', usage=\n """ \n python3 plottestgrid.py <folder> <distribution name> <distribution type (PDF/FF)> \n"""\n , description=\n \'Script to plot the output of the grid test done with tests/GridPriduction.cc\'\n )\n', (910, 1146), False, 'import argparse\n'), ((1856, 1875), 'os.listdir', 'os.listdir', (['Ofolder'], {}), '(Ofolder)\n', (1866, 1875), False, 'import os\n'), ((1753, 1779), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (1769, 1779), False, 'import os\n'), ((1617, 1628), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (1625, 1628), False, 'import sys\n'), ((2075, 2119), 'ruamel.yaml.load', 'yaml.load', (['test'], {'Loader': 'yaml.RoundTripLoader'}), '(test, Loader=yaml.RoundTripLoader)\n', (2084, 2119), False, 'from ruamel import yaml\n'), ((2677, 2716), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0)', 'hspace': '(0)'}), '(wspace=0, hspace=0)\n', (2696, 2716), True, 'import matplotlib.pyplot as plt\n'), ((6722, 6733), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6731, 6733), True, 'import matplotlib.pyplot as plt\n'), ((5953, 5976), 'numpy.trunc', 'np.trunc', (['(ystart / 0.05)'], {}), '(ystart / 0.05)\n', (5961, 5976), True, 'import numpy as np\n'), ((6406, 6425), 'os.mkdir', 'os.mkdir', (['plotspath'], {}), '(plotspath)\n', (6414, 6425), False, 'import os\n')]
import numpy as np import tflite_runtime.interpreter as tflite import os, fnmatch class ML_Loader(object): def __init__(self, model_info): # Init loader by loading model into the object self.model_info = model_info if (self.model_info["mlinfrastructure"] == "edge"): file_list = os.listdir(model_info["path"]) pattern = "*.tflite" model_file = "" for model in file_list: if fnmatch.fnmatch(model, pattern): model_file = model break self.interpreter = tflite.Interpreter(model_info["path"]+model_file) self.interpreter.allocate_tensors() self.input_details = self.interpreter.get_input_details() self.output_details = self.interpreter.get_output_details() elif (self.model_info["mlinfrastructure"] == "cloud"): import tensorflow as tf self.model = tf.keras.models.load_model(model_info["path"]) def prediction(self,pas_series, batch_size): if (self.model_info["mlinfrastructure"] == "edge"): result = np.empty([batch_size,pas_series.shape[1],pas_series.shape[2]], dtype=float) for i in range(batch_size): input_var = np.array(pas_series[i][np.newaxis,:,:], dtype='f') self.interpreter.set_tensor(self.input_details[0]['index'], input_var) self.interpreter.invoke() result[i] = self.interpreter.get_tensor(self.output_details[0]['index']) return result elif (self.model_info["mlinfrastructure"] == "cloud"): return self.model.predict(pas_series, batch_size=batch_size, verbose=0)
[ "tflite_runtime.interpreter.Interpreter", "os.listdir", "numpy.array", "tensorflow.keras.models.load_model", "numpy.empty", "fnmatch.fnmatch" ]
[((320, 350), 'os.listdir', 'os.listdir', (["model_info['path']"], {}), "(model_info['path'])\n", (330, 350), False, 'import os, fnmatch\n'), ((596, 647), 'tflite_runtime.interpreter.Interpreter', 'tflite.Interpreter', (["(model_info['path'] + model_file)"], {}), "(model_info['path'] + model_file)\n", (614, 647), True, 'import tflite_runtime.interpreter as tflite\n'), ((1144, 1221), 'numpy.empty', 'np.empty', (['[batch_size, pas_series.shape[1], pas_series.shape[2]]'], {'dtype': 'float'}), '([batch_size, pas_series.shape[1], pas_series.shape[2]], dtype=float)\n', (1152, 1221), True, 'import numpy as np\n'), ((467, 498), 'fnmatch.fnmatch', 'fnmatch.fnmatch', (['model', 'pattern'], {}), '(model, pattern)\n', (482, 498), False, 'import os, fnmatch\n'), ((960, 1006), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (["model_info['path']"], {}), "(model_info['path'])\n", (986, 1006), True, 'import tensorflow as tf\n'), ((1288, 1340), 'numpy.array', 'np.array', (['pas_series[i][np.newaxis, :, :]'], {'dtype': '"""f"""'}), "(pas_series[i][np.newaxis, :, :], dtype='f')\n", (1296, 1340), True, 'import numpy as np\n')]
import numpy as np from deepthought.experiments.encoding.experiment_templates.base import NestedCVExperimentTemplate class SVCBaseline(NestedCVExperimentTemplate): def pretrain_encoder(self, *args, **kwargs): def dummy_encoder_fn(indices): if type(indices) == np.ndarray: indices = indices.tolist() # ndarray is not supported as indices # read the chunk of data for the given indices state = self.full_hdf5.open() data = self.full_hdf5.get_data(request=indices, state=state) self.full_hdf5.close(state) # get only the features source source_idx = self.full_hdf5.sources.index('features') data = np.ascontiguousarray(data[source_idx]) # apply optional channel mean if self.hyper_params['ch_mean'] is True: data = data.mean(axis=1) # bc01 format -> will result in b01 format return data return dummy_encoder_fn def run(self, verbose=False): from deepthought.experiments.encoding.classifiers.linear_svc import LinearSVCClassifierFactory super(SVCBaseline, self).run(classifiers=(('linear_svc', LinearSVCClassifierFactory()),), verbose=verbose)
[ "deepthought.experiments.encoding.classifiers.linear_svc.LinearSVCClassifierFactory", "numpy.ascontiguousarray" ]
[((727, 765), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['data[source_idx]'], {}), '(data[source_idx])\n', (747, 765), True, 'import numpy as np\n'), ((1208, 1236), 'deepthought.experiments.encoding.classifiers.linear_svc.LinearSVCClassifierFactory', 'LinearSVCClassifierFactory', ([], {}), '()\n', (1234, 1236), False, 'from deepthought.experiments.encoding.classifiers.linear_svc import LinearSVCClassifierFactory\n')]
##################################################### # This file is a component of ClusterGB # # Copyright (c) 2018 <NAME> # # Released under the MIT License (see distribution) # ##################################################### """ Run `voro++ <http://math.lbl.gov/voro++/>`_ on a set of positions using the voro++ executable listed in the config file. """ import os import yaml from .structure import write_vorin from .osio import run_in_shell from numpy import genfromtxt __author__ = "<NAME>" __copyright__ = "Copyright 2018, <NAME>" __license__ = "MIT" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Production" def voronoi(pos, lx, ly, lz): """ Given a set of n atomic positions in a rectangular prismatic cell, calculates their Voronoi volumes using voro++. .. warning:: All the positions should lie inside the cell, and the calculation is aperiodic, so the cell walls function as Voronoi cell boundaries. .. todo:: Why have a warning when you can just force it to be true by operating on `pos`? Args: pos (np.ndarray): :math:`(n,3)` Cartesian atomic positions to evaluate. lx, ly, lz (float): x-, y-, and z-lengths for rectangular cell. Returns: 7-element tuple containing - (*np.ndarray*) -- :math:`(n,)` Voronoi volumes. - (*np.ndarray*) -- :math:`(n,)` surface areas. - (*np.ndarray*) -- :math:`(n,)` edge lengths. - (*np.ndarray*) -- :math:`(n,)` *int* vertex counts. - (*np.ndarray*) -- :math:`(n,)` *int* face counts. - (*np.ndarray*) -- :math:`(n,)` *int* edge counts. - (*np.ndarray*) -- :math:`(n,3)` offset of the Voronoi centroid from the atom for which it was constructed. """ # Read the executable name config_file_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) with open(os.path.join(config_file_dir, "config.yml"), "r") as f: config = yaml.load(f) voro_exec = config["executables"]["voropp"] # Write a file for voro++ to read vorin = "tmp.vorin" write_vorin(vorin, pos) # Run voro++ command = voro_exec + " -c '%v %F %E %w %s %g %c' -o " + " ".join(str(l) for l in [0, lx, 0, ly, 0, lz]) + " " + \ vorin run_in_shell(command) # Parse the results vorout = vorin + ".vol" voro_data = genfromtxt(vorout) volume = voro_data[:, 0] area = voro_data[:, 1] edge_length = voro_data[:, 2] vertices = voro_data[:, 3].astype(int) faces = voro_data[:, 4].astype(int) edges = voro_data[:, 5].astype(int) offset = voro_data[:, 6:] # Clean up os.remove(vorin) os.remove(vorout) return volume, area, edge_length, vertices, faces, edges, offset
[ "os.path.join", "yaml.load", "os.path.realpath", "numpy.genfromtxt", "os.remove" ]
[((2430, 2448), 'numpy.genfromtxt', 'genfromtxt', (['vorout'], {}), '(vorout)\n', (2440, 2448), False, 'from numpy import genfromtxt\n'), ((2712, 2728), 'os.remove', 'os.remove', (['vorin'], {}), '(vorin)\n', (2721, 2728), False, 'import os\n'), ((2733, 2750), 'os.remove', 'os.remove', (['vorout'], {}), '(vorout)\n', (2742, 2750), False, 'import os\n'), ((2026, 2038), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (2035, 2038), False, 'import yaml\n'), ((1910, 1936), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (1926, 1936), False, 'import os\n'), ((1953, 1996), 'os.path.join', 'os.path.join', (['config_file_dir', '"""config.yml"""'], {}), "(config_file_dir, 'config.yml')\n", (1965, 1996), False, 'import os\n')]
import os import time import argparse import torch import pickle import copy import numpy as np from tqdm import tqdm import rdkit from rdkit.Chem import AllChem from rdkit import Chem from confgf import utils, dataset import multiprocessing from functools import partial def generate_conformers(mol, num_confs): mol = copy.deepcopy(mol) mol.RemoveAllConformers() assert mol.GetNumConformers() == 0 AllChem.EmbedMultipleConfs( mol, numConfs=num_confs, maxAttempts=0, ignoreSmoothingFailures=True, ) if mol.GetNumConformers() != num_confs: print('Warning: Failure cases occured, generated: %d , expected: %d.' % (mol.GetNumConformers(), num_confs, )) return mol if __name__ == '__main__': parser = argparse.ArgumentParser(description='confgf') parser.add_argument('--input', type=str, required=True) parser.add_argument('--output', type=str, required=True) parser.add_argument('--start_idx', type=int, default=0) parser.add_argument('--num_samples', type=int, default=50) parser.add_argument('--eval', action='store_true', default=False) parser.add_argument('--core', type=int, default=6) parser.add_argument('--FF', action='store_true') parser.add_argument('--threshold', type=float, default=0.5) args = parser.parse_args() print(args) with open(args.input, 'rb') as f: data_raw = pickle.load(f) if 'pos_ref' in data_raw[0]: data_list = data_raw else: data_list = dataset.GEOMDataset_PackedConf(data_raw) generated_data_list = [] for i in tqdm(range(args.start_idx, len(data_list))): return_data = copy.deepcopy(data_list[i]) if args.num_samples > 0: num_confs = args.num_samples else: num_confs = -args.num_samples*return_data.num_pos_ref.item() mol = generate_conformers(return_data.rdmol, num_confs=num_confs) num_pos_gen = mol.GetNumConformers() all_pos = [] if num_pos_gen == 0: continue for j in range(num_pos_gen): all_pos.append(torch.tensor(mol.GetConformer(j).GetPositions(), dtype=torch.float32)) return_data.pos_gen = torch.cat(all_pos, 0) # (num_pos_gen * num_node, 3) return_data.num_pos_gen = torch.tensor([len(all_pos)], dtype=torch.long) generated_data_list.append(return_data) with open(args.output, "wb") as fout: pickle.dump(generated_data_list, fout) print('save generated conf to %s done!' % args.output) if args.eval: print('start getting results!') with open(args.output, 'rb') as fin: data_list = pickle.load(fin) bad_case = 0 filtered_data_list = [] for i in tqdm(range(len(data_list))): if '.' in data_list[i].smiles: bad_case += 1 continue filtered_data_list.append(data_list[i]) cnt_conf = 0 for i in range(len(filtered_data_list)): cnt_conf += filtered_data_list[i].num_pos_ref print('%d bad cases, use %d mols with total %d confs' % (bad_case, len(filtered_data_list), cnt_conf)) pool = multiprocessing.Pool(args.core) func = partial(utils.evaluate_conf, useFF=args.FF, threshold=args.threshold) covs = [] mats = [] for result in tqdm(pool.imap(func, filtered_data_list), total=len(filtered_data_list)): covs.append(result[0]) mats.append(result[1]) covs = np.array(covs) mats = np.array(mats) print('Coverage Mean: %.4f | Coverage Median: %.4f | Match Mean: %.4f | Match Median: %.4f' % \ (covs.mean(), np.median(covs), mats.mean(), np.median(mats))) pool.close() pool.join()
[ "numpy.median", "pickle.dump", "argparse.ArgumentParser", "rdkit.Chem.AllChem.EmbedMultipleConfs", "pickle.load", "numpy.array", "confgf.dataset.GEOMDataset_PackedConf", "functools.partial", "multiprocessing.Pool", "copy.deepcopy", "torch.cat" ]
[((329, 347), 'copy.deepcopy', 'copy.deepcopy', (['mol'], {}), '(mol)\n', (342, 347), False, 'import copy\n'), ((422, 522), 'rdkit.Chem.AllChem.EmbedMultipleConfs', 'AllChem.EmbedMultipleConfs', (['mol'], {'numConfs': 'num_confs', 'maxAttempts': '(0)', 'ignoreSmoothingFailures': '(True)'}), '(mol, numConfs=num_confs, maxAttempts=0,\n ignoreSmoothingFailures=True)\n', (448, 522), False, 'from rdkit.Chem import AllChem\n'), ((783, 828), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""confgf"""'}), "(description='confgf')\n", (806, 828), False, 'import argparse\n'), ((1423, 1437), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1434, 1437), False, 'import pickle\n'), ((1698, 1725), 'copy.deepcopy', 'copy.deepcopy', (['data_list[i]'], {}), '(data_list[i])\n', (1711, 1725), False, 'import copy\n'), ((2246, 2267), 'torch.cat', 'torch.cat', (['all_pos', '(0)'], {}), '(all_pos, 0)\n', (2255, 2267), False, 'import torch\n'), ((2480, 2518), 'pickle.dump', 'pickle.dump', (['generated_data_list', 'fout'], {}), '(generated_data_list, fout)\n', (2491, 2518), False, 'import pickle\n'), ((3243, 3274), 'multiprocessing.Pool', 'multiprocessing.Pool', (['args.core'], {}), '(args.core)\n', (3263, 3274), False, 'import multiprocessing\n'), ((3291, 3360), 'functools.partial', 'partial', (['utils.evaluate_conf'], {'useFF': 'args.FF', 'threshold': 'args.threshold'}), '(utils.evaluate_conf, useFF=args.FF, threshold=args.threshold)\n', (3298, 3360), False, 'from functools import partial\n'), ((3580, 3594), 'numpy.array', 'np.array', (['covs'], {}), '(covs)\n', (3588, 3594), True, 'import numpy as np\n'), ((3610, 3624), 'numpy.array', 'np.array', (['mats'], {}), '(mats)\n', (3618, 3624), True, 'import numpy as np\n'), ((1546, 1586), 'confgf.dataset.GEOMDataset_PackedConf', 'dataset.GEOMDataset_PackedConf', (['data_raw'], {}), '(data_raw)\n', (1576, 1586), False, 'from confgf import utils, dataset\n'), ((2718, 2734), 'pickle.load', 'pickle.load', (['fin'], {}), '(fin)\n', (2729, 2734), False, 'import pickle\n'), ((3772, 3787), 'numpy.median', 'np.median', (['covs'], {}), '(covs)\n', (3781, 3787), True, 'import numpy as np\n'), ((3802, 3817), 'numpy.median', 'np.median', (['mats'], {}), '(mats)\n', (3811, 3817), True, 'import numpy as np\n')]
## set up logging import logging, os logging.basicConfig(level=os.environ.get("LOGLEVEL","INFO")) log = logging.getLogger(__name__) ## import modules import octvi.exceptions, octvi.array, gdal from gdalnumeric import * import numpy as np def getDatasetNames(stack_path:str) -> list: """ Returns list of all subdataset names, in format suitable for passing to other functions' 'dataset_name' argument """ ## parsing arguments ext = os.path.splitext(stack_path)[1] if ext == ".hdf": splitter = ":" elif ext == ".h5": splitter = "/" else: raise octvi.exceptions.FileTypeError("File must be of format .hdf or .h5") ## loop over all subdatasets outSds = [] ds = gdal.Open(stack_path,0) # open stack as gdal dataset for sd in ds.GetSubDatasets(): sdName = sd[0].split(splitter)[-1] # split name out of path outSds.append(sdName.strip("\"")) # strip away quotes return outSds def datasetToPath(stack_path,dataset_name) -> str: ## parsing arguments ext = os.path.splitext(stack_path)[1] if ext == ".hdf": splitter = ":" elif ext == ".h5": splitter = "/" else: raise octvi.exceptions.FileTypeError("File must be of format .hdf or .h5") ## searching heirarchy for matching subdataset outSd = None ds = gdal.Open(stack_path,0) # open stack as gdal dataset for sd in ds.GetSubDatasets(): sdName = sd[0].split(splitter)[-1] if sdName.strip("\"") == dataset_name: outSd = sd[0] if outSd is None: raise octvi.exceptions.DatasetNotFoundError(f"Dataset '{dataset_name}' not found in '{os.path.basename(stack_path)}'") return outSd def datasetToArray(stack_path,dataset_name) -> "numpy array": """ This function copies a specified subdataset from a heirarchical format (such as HDF or NetCDF) to a single file such as a Tiff. ... Parameters ---------- stack_path: str Full path to heirarchical file containing the desired subdataset dataset_name: str Name of desired subdataset, as it appears in the heirarchical file """ sd = datasetToPath(stack_path, dataset_name) ## return subdataset as numpy array subDs = gdal.Open(sd, 0) subDs_band = subDs.GetRasterBand(1) return BandReadAsArray(subDs_band) def datasetToRaster(stack_path,dataset_name, out_path,dtype = None, *args, **kwargs) -> None: """ Wrapper for extractAsArray and arrayToRaster which pulls subdataset from hdf or h5 file and saves to new location. ... Arguments --------- stack_path: str dataset_name: str out_path: str """ sd_array = datasetToArray(stack_path, dataset_name) return octvi.array.toRaster(sd_array, out_path, model_file = stack_path,dtype=dtype) def ndviToArray(in_stack) -> "numpy array": """ This function finds the correct Red and NIR bands from a hierarchical file, calculates an NDVI array, and returns the outpus in numpy array format. Valid input formats are MODIS HDF or VIIRS HDF5 (h5). ... Parameters ---------- in_stack: str Full path to input hierarchical file """ suffix = os.path.basename(in_stack).split(".")[0][3:7] # check whether it's an ndvi product if suffix == "09Q4" or suffix == "13Q4": arr_ndvi = datasetToArray(in_stack, "250m 8 days NDVI") elif suffix == "13Q1": arr_ndvi = datasetToArray(in_stack, "250m 16 days NDVI") elif suffix == "09CM": ## determine correct band subdataset names ext = os.path.splitext(in_stack)[1] if ext == ".hdf": sdName_red = "Coarse Resolution Surface Reflectance Band 1" sdName_nir = "Coarse Resolution Surface Reflectance Band 2" elif ext == '.h5': sdName_red = "SurfReflect_I1" sdName_nir = "SurfReflect_I2" ## extract red and nir bands from stack arr_red = datasetToArray(in_stack,sdName_red) arr_nir = datasetToArray(in_stack,sdName_nir) ## perform calculation arr_ndvi = octvi.array.calcNdvi(arr_red,arr_nir) else: ## determine correct band subdataset names ext = os.path.splitext(in_stack)[1] if ext == ".hdf": sdName_red = "sur_refl_b01" sdName_nir = "sur_refl_b02" elif ext == ".h5": sdName_red = "SurfReflect_I1" sdName_nir = "SurfReflect_I2" else: raise octvi.exceptions.FileTypeError("File must be of type .hdf or .h5") ## extract red and nir bands from stack arr_red = datasetToArray(in_stack,sdName_red) arr_nir = datasetToArray(in_stack,sdName_nir) ## perform calculation arr_ndvi = octvi.array.calcNdvi(arr_red,arr_nir) return arr_ndvi def gcviToArray(in_stack:str) -> "numpy array": """ This function finds the correct Green and NIR bands from a hierarchical file, calculates a GCVI array, and returns the outpus in numpy array format. Valid input format is MOD09CMG HDF. ... Parameters ---------- in_stack: str Full path to input hierarchical file """ suffix = os.path.basename(in_stack).split(".")[0][3:7] # check whether it's an ndvi product if suffix == "09CM": ## determine correct band subdataset names ext = os.path.splitext(in_stack)[1] if ext == ".hdf": sdName_green = "Coarse Resolution Surface Reflectance Band 4" sdName_nir = "Coarse Resolution Surface Reflectance Band 2" elif ext == '.h5': sdName_green = "SurfReflect_M4" sdName_nir = "SurfReflect_I2" ## extract red and nir bands from stack arr_green = datasetToArray(in_stack,sdName_green) arr_nir = datasetToArray(in_stack,sdName_nir) ## perform calculation arr_gcvi = octvi.array.calcGcvi(arr_green,arr_nir) elif suffix == "09A1": sdName_green = "sur_refl_b04" sdName_nir = "sur_refl_b02" arr_green = datasetToArray(in_stack,sdName_green) arr_nir = datasetToArray(in_stack,sdName_nir) arr_gcvi = octvi.array.calcGcvi(arr_green,arr_nir) else: raise octvi.exceptions.UnsupportedError("Only MOD09CMG and MOD09A1 imagery is supported for GCVI generation") return arr_gcvi def ndwiToArray(in_stack:str) -> "numpy array": """ This function finds the correct SWIR and NIR bands from a hierarchical file, calculates a NDWI array, and returns the outpus in numpy array format. Valid input format is HDF. ... Parameters ---------- in_stack: str Full path to input hierarchical file """ suffix = os.path.basename(in_stack).split(".")[0][3:7] if suffix == "09A1": sdName_nir = "sur_refl_b02" sdName_swir = "sur_refl_b05" arr_nir = datasetToArray(in_stack, sdName_nir) arr_swir = datasetToArray(in_stack,sdName_swir) arr_ndwi = octvi.array.calcNdwi(arr_nir,arr_swir) else: raise octvi.exceptions.UnsupportedError("Only MOD09A1 imagery is supported for GCVI generation") return arr_ndwi def ndviToRaster(in_stack,out_path,qa_name=None) -> str: """ This function directly converts a hierarchical data file into an NDVI raster. Returns the string path to the output file *** Parameters ---------- in_stack:str out_path:str qa_name (optional):str Name of QA dataset, if included produces two-band tiff """ # create ndvi array ndviArray = ndviToArray(in_stack) # apply cloud, shadow, and water masks ndviArray = octvi.array.mask(ndviArray, in_stack) sample_sd = getDatasetNames(in_stack)[0] #ext = os.path.splitext(in_stack)[1] #if ext == ".hdf": #sample_sd = "sur_refl_b01" #elif ext == ".h5": #sample_sd = "SurfReflect_I1" #else: #raise octvi.exceptions.FileTypeError("File must be of format .hdf or .h5") if qa_name is None: #octvi.array.toRaster(ndviArray,out_path,datasetToPath(in_stack,sample_sd)) octvi.array.toRaster(ndviArray,out_path,in_stack,sample_sd) else: # get qa array qaArray = datasetToArray(in_stack,qa_name) # create multiband at out_path #octvi.array.toRaster(ndviArray,out_path,datasetToPath(in_stack,sample_sd),qa_array = qaArray) octvi.array.toRaster(ndviArray,out_path,in_stack,qa_array = qaArray) return out_path def gcviToRaster(in_stack:str,out_path:str) -> str: """ This function directly converts a hierarchical data file into a GCVI raster. Returns the string path to the output file """ # create gcvi array gcviArray = gcviToArray(in_stack) # apply cloud, shadow, and water masks gcviArray = octvi.array.mask(gcviArray, in_stack) sample_sd = getDatasetNames(in_stack)[0] #ext = os.path.splitext(in_stack)[1] #if ext == ".hdf": #sample_sd = "sur_refl_b01" #elif ext == ".h5": #sample_sd = "SurfReflect_I1" #else: #raise octvi.exceptions.FileTypeError("File must be of format .hdf or .h5") octvi.array.toRaster(gcviArray,out_path,datasetToPath(in_stack,sample_sd)) return out_path def ndwiToRaster(in_stack:str, out_path:str) -> str: """ This function directly converts a hierarchical data file into an NDWI raster. Returns the string path to the output file """ # create gcvi array ndwiArray = ndwiToArray(in_stack) # apply cloud, shadow, and water masks ndwiArray = octvi.array.mask(ndwiArray, in_stack) sample_sd = getDatasetNames(in_stack)[0] octvi.array.toRaster(ndwiArray,out_path,datasetToPath(in_stack,sample_sd)) return out_path def cmgToViewAngArray(source_stack,product="MOD09CMG") -> "numpy array": """ This function takes the path to a M*D CMG file, and returns the view angle of each pixel. Ephemeral water pixels are set to 999, to be used as a last resort in compositing. Returns a numpy array of the same dimensions as the input raster. *** Parameters ---------- source_stack:str Path to the M*D CMG .hdf file on disk """ if product == "MOD09CMG": vang_arr = datasetToArray(source_stack,"Coarse Resolution View Zenith Angle") state_arr = datasetToArray(source_stack,"Coarse Resolution State QA") water = ((state_arr & 0b111000)) # check bits vang_arr[water==32]=9999 # ephemeral water??? vang_arr[vang_arr<=0]=9999 elif product == "VNP09CMG": vang_arr = datasetToArray(source_stack,"SensorZenith") vang_arr[vang_arr<=0]=9999 return vang_arr def cmgListToWaterArray(stacks:list,product="MOD09CMG") -> "numpy array": """ This function takes a list of CMG .hdf files, and returns a binary array, with "0" for non-water pixels and "1" for water pixels. If any file flags water in a pixel, its value is stored as "1" *** Parameters ---------- stacks:list List of hdf filepaths (M*D**CMG) """ water_list = [] for source_stack in stacks: if product == "MOD09CMG": state_arr = datasetToArray(source_stack,"Coarse Resolution State QA") water = ((state_arr & 0b111000)) # check bits water[water==56]=1 # deep ocean water[water==48]=1 # continental/moderate ocean water[water==24]=1 # shallow inland water water[water==40]=1 # deep inland water water[water==0]=1 # shallow ocean water[state_arr==0]=0 water[water!=1]=0 # set non-water to zero elif product == "VNP09CMG": state_arr = datasetToArray(source_stack,"State_QA") water = ((state_arr & 0b111000)) # check bits 3-5 water[water == 40] = 0 # "coastal" = 101 water[water>8]=1 # sea water = 011; inland water = 010 water[water!=1]=0 # set non-water to zero water[water!=0]=1 water_list.append(water) water_final = np.maximum.reduce(water_list) return water_final def cmgToRankArray(source_stack,product="MOD09CMG") -> "numpy array": """ This function takes the path to a MOD**CMG file, and returns the rank of each pixel, as defined on page 7 of the MOD09 user guide (http://modis-sr.ltdri.org/guide/MOD09_UserGuide_v1.4.pdf) Returns a numpy array of the same dimensions as the input raster *** Parameters ---------- source_stack:str Path to the CMG .hdf/.h5 file on disk product:str String of either MOD09CMG or VNP09CMG """ if product == "MOD09CMG": qa_arr = datasetToArray(source_stack,"Coarse Resolution QA") state_arr = datasetToArray(source_stack,"Coarse Resolution State QA") vang_arr = datasetToArray(source_stack,"Coarse Resolution View Zenith Angle") vang_arr[vang_arr<=0]=9999 sang_arr = datasetToArray(source_stack,"Coarse Resolution Solar Zenith Angle") rank_arr = np.full(qa_arr.shape,10) # empty rank array ## perform the ranking! logging.debug("--rank 9: SNOW") SNOW = ((state_arr & 0b1000000000000) | (state_arr & 0b1000000000000000)) # state bit 12 OR 15 rank_arr[SNOW>0]=9 # snow del SNOW logging.debug("--rank 8: HIGHAEROSOL") HIGHAEROSOL=(state_arr & 0b11000000) # state bits 6 AND 7 rank_arr[HIGHAEROSOL==192]=8 del HIGHAEROSOL logging.debug("--rank 7: CLIMAEROSOL") CLIMAEROSOL=(state_arr & 0b11000000) # state bits 6 & 7 #CLIMAEROSOL=(cloudMask & 0b100000000000000) # cloudMask bit 14 rank_arr[CLIMAEROSOL==0]=7 # default aerosol level del CLIMAEROSOL logging.debug("--rank 6: UNCORRECTED") UNCORRECTED = (qa_arr & 0b11) # qa bits 0 AND 1 rank_arr[UNCORRECTED==3]=6 # flagged uncorrected del UNCORRECTED logging.debug("--rank 5: SHADOW") SHADOW = (state_arr & 0b100) # state bit 2 rank_arr[SHADOW==4]=5 # cloud shadow del SHADOW logging.debug("--rank 4: CLOUDY") # set adj to 11 and internal to 12 to verify in qa output CLOUDY = ((state_arr & 0b11)) # state bit 0 OR bit 1 OR bit 10 OR bit 13 #rank_arr[CLOUDY!=0]=4 # cloud pixel del CLOUDY CLOUDADJ = (state_arr & 0b10000000000000) #rank_arr[CLOUDADJ>0]=4 # adjacent to cloud del CLOUDADJ CLOUDINT = (state_arr & 0b10000000000) rank_arr[CLOUDINT>0]=4 del CLOUDINT logging.debug("--rank 3: HIGHVIEW") rank_arr[sang_arr>(85/0.01)]=3 # HIGHVIEW logging.debug("--rank 2: LOWSUN") rank_arr[vang_arr>(60/0.01)]=2 # LOWSUN # BAD pixels logging.debug("--rank 1: BAD pixels") # qa bits (2-5 OR 6-9 == 1110) BAD = ((qa_arr & 0b111100) | (qa_arr & 0b1110000000)) rank_arr[BAD==112]=1 rank_arr[BAD==896]=1 rank_arr[BAD==952]=1 del BAD logging.debug("-building water mask") water = ((state_arr & 0b111000)) # check bits water[water==56]=1 # deep ocean water[water==48]=1 # continental/moderate ocean water[water==24]=1 # shallow inland water water[water==40]=1 # deep inland water water[water==0]=1 # shallow ocean rank_arr[water==1]=0 vang_arr[water==32]=9999 # ephemeral water??? water[state_arr==0]=0 water[water!=1]=0 # set non-water to zero elif product == "VNP09CMG": #print("cmgToRankArray(product='VNP09CMG')") qf2 = datasetToArray(source_stack,"SurfReflect_QF2") qf4 = datasetToArray(source_stack,"SurfReflect_QF4") state_arr = datasetToArray(source_stack,"State_QA") vang_arr = datasetToArray(source_stack,"SensorZenith") vang_arr[vang_arr<=0]=9999 sang_arr = datasetToArray(source_stack,"SolarZenith") rank_arr = np.full(state_arr.shape,10) # empty rank array ## perform the ranking! logging.debug("--rank 9: SNOW") SNOW = (state_arr & 0b1000000000000000) # state bit 15 rank_arr[SNOW>0]=9 # snow del SNOW logging.debug("--rank 8: HIGHAEROSOL") HIGHAEROSOL=(qf2 & 0b10000) # qf2 bit 4 rank_arr[HIGHAEROSOL!=0]=8 del HIGHAEROSOL logging.debug("--rank 7: AEROSOL") CLIMAEROSOL=(state_arr & 0b1000000) # state bit 6 #CLIMAEROSOL=(cloudMask & 0b100000000000000) # cloudMask bit 14 #rank_arr[CLIMAEROSOL==0]=7 # "No" del CLIMAEROSOL # logging.debug("--rank 6: UNCORRECTED") # UNCORRECTED = (qa_arr & 0b11) # qa bits 0 AND 1 # rank_arr[UNCORRECTED==3]=6 # flagged uncorrected # del UNCORRECTED logging.debug("--rank 5: SHADOW") SHADOW = (state_arr & 0b100) # state bit 2 rank_arr[SHADOW!=0]=5 # cloud shadow del SHADOW logging.debug("--rank 4: CLOUDY") # set adj to 11 and internal to 12 to verify in qa output # CLOUDY = ((state_arr & 0b11)) # state bit 0 OR bit 1 OR bit 10 OR bit 13 # rank_arr[CLOUDY!=0]=4 # cloud pixel # del CLOUDY # CLOUDADJ = (state_arr & 0b10000000000) # nonexistent for viirs # #rank_arr[CLOUDADJ>0]=4 # adjacent to cloud # del CLOUDADJ CLOUDINT = (state_arr & 0b10000000000) # state bit 10 rank_arr[CLOUDINT>0]=4 del CLOUDINT logging.debug("--rank 3: HIGHVIEW") rank_arr[sang_arr>(85/0.01)]=3 # HIGHVIEW logging.debug("--rank 2: LOWSUN") rank_arr[vang_arr>(60/0.01)]=2 # LOWSUN # BAD pixels logging.debug("--rank 1: BAD pixels") # qa bits (2-5 OR 6-9 == 1110) BAD = (qf4 & 0b110) rank_arr[BAD!= 0]=1 del BAD logging.debug("-building water mask") water = ((state_arr & 0b111000)) # check bits 3-5 water[water == 40] = 0 # "coastal" = 101 water[water>8]=1 # sea water = 011; inland water = 010 # water[water==16]=1 # inland water = 010 # water[state_arr==0]=0 water[water!=1]=0 # set non-water to zero water[water!=0]=1 rank_arr[water==1]=0 # return the results return rank_arr def cmgBestViPixels(input_stacks:list,vi="NDVI",product = "MOD09CMG",snow_mask=False) -> "numpy array": """ This function takes a list of hdf stack paths, and returns the 'best' VI value for each pixel location, determined through the ranking method (see cmgToRankArray() for details). *** Parameters ---------- input_stacks:list A list of strings, each pointing to a CMG hdf/h5 file on disk product:str A string of either "MOD09CMG" or "VNP09CMG" """ viExtractors = { "NDVI":ndviToArray, "GCVI":gcviToArray } rankArrays = [cmgToRankArray(hdf,product) for hdf in input_stacks] vangArrays = [cmgToViewAngArray(hdf,product) for hdf in input_stacks] try: viArrays = [viExtractors[vi](hdf) for hdf in input_stacks] except KeyError: raise octvi.exceptions.UnsupportedError(f"Index type '{vi}' is not recognized or not currently supported.") # no nodata wanted for i in range(len(rankArrays)): rankArrays[i][viArrays[i] == -3000] = 0 # apply snow mask if requested if snow_mask: for rankArray in rankArrays: rankArray[rankArray==9] = 0 idealRank = np.maximum.reduce(rankArrays) # mask non-ideal view angles for i in range(len(vangArrays)): vangArrays[i][rankArrays[i] != idealRank] = 9998 vangArrays[i][vangArrays[i] == 0] = 9997 idealVang = np.minimum.reduce(vangArrays) #print("Max vang:") #print(np.amax(idealVang)) #octvi.array.toRaster(idealVang,"C:/temp/MOD09CMG.VANG.tif",input_stacks[0]) #octvi.array.toRaster(idealRank,"C:/temp/VNP09CMG.RANK.tif",input_stacks[0]) finalVi = np.full(viArrays[0].shape,-3000) # mask each ndviArray to only where it matches ideal rank for i in range(len(viArrays)): finalVi[vangArrays[i] == idealVang] = viArrays[i][vangArrays[i] == idealVang] # mask out ranks that are too low finalVi[idealRank <=7] = -3000 # mask water water = cmgListToWaterArray(input_stacks,product) finalVi[water==1] = -3000 # return result return finalVi def qaTo8BitArray(stack_path) -> "numpy array": """Returns an 8-bit QA array for the passed image file MODIS and VIIRS use 16-bit QA layers, but many of those bits are redundant or unnecessary for purposes of VI mapping. For example, non-land pixels are masked by default, so the land/ water flag is unused. This function pares down the 16-bit mask into an 8-bit version that retains all necessary functionality. *** Parameters ---------- stack_path:str Full path to input hierarchical file on disk """ log.warning("octvi.extract.qaTo8BitArray() is not implemented!") return None
[ "logging.getLogger", "numpy.maximum.reduce", "gdal.Open", "numpy.minimum.reduce", "logging.debug", "os.environ.get", "os.path.splitext", "os.path.basename", "numpy.full" ]
[((107, 134), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (124, 134), False, 'import logging, os\n'), ((710, 734), 'gdal.Open', 'gdal.Open', (['stack_path', '(0)'], {}), '(stack_path, 0)\n', (719, 734), False, 'import octvi.exceptions, octvi.array, gdal\n'), ((1287, 1311), 'gdal.Open', 'gdal.Open', (['stack_path', '(0)'], {}), '(stack_path, 0)\n', (1296, 1311), False, 'import octvi.exceptions, octvi.array, gdal\n'), ((2154, 2170), 'gdal.Open', 'gdal.Open', (['sd', '(0)'], {}), '(sd, 0)\n', (2163, 2170), False, 'import octvi.exceptions, octvi.array, gdal\n'), ((11311, 11340), 'numpy.maximum.reduce', 'np.maximum.reduce', (['water_list'], {}), '(water_list)\n', (11328, 11340), True, 'import numpy as np\n'), ((18019, 18048), 'numpy.maximum.reduce', 'np.maximum.reduce', (['rankArrays'], {}), '(rankArrays)\n', (18036, 18048), True, 'import numpy as np\n'), ((18229, 18258), 'numpy.minimum.reduce', 'np.minimum.reduce', (['vangArrays'], {}), '(vangArrays)\n', (18246, 18258), True, 'import numpy as np\n'), ((18484, 18517), 'numpy.full', 'np.full', (['viArrays[0].shape', '(-3000)'], {}), '(viArrays[0].shape, -3000)\n', (18491, 18517), True, 'import numpy as np\n'), ((65, 99), 'os.environ.get', 'os.environ.get', (['"""LOGLEVEL"""', '"""INFO"""'], {}), "('LOGLEVEL', 'INFO')\n", (79, 99), False, 'import logging, os\n'), ((461, 489), 'os.path.splitext', 'os.path.splitext', (['stack_path'], {}), '(stack_path)\n', (477, 489), False, 'import logging, os\n'), ((1019, 1047), 'os.path.splitext', 'os.path.splitext', (['stack_path'], {}), '(stack_path)\n', (1035, 1047), False, 'import logging, os\n'), ((12234, 12259), 'numpy.full', 'np.full', (['qa_arr.shape', '(10)'], {}), '(qa_arr.shape, 10)\n', (12241, 12259), True, 'import numpy as np\n'), ((12310, 12341), 'logging.debug', 'logging.debug', (['"""--rank 9: SNOW"""'], {}), "('--rank 9: SNOW')\n", (12323, 12341), False, 'import logging, os\n'), ((12484, 12522), 'logging.debug', 'logging.debug', (['"""--rank 8: HIGHAEROSOL"""'], {}), "('--rank 8: HIGHAEROSOL')\n", (12497, 12522), False, 'import logging, os\n'), ((12638, 12676), 'logging.debug', 'logging.debug', (['"""--rank 7: CLIMAEROSOL"""'], {}), "('--rank 7: CLIMAEROSOL')\n", (12651, 12676), False, 'import logging, os\n'), ((12879, 12917), 'logging.debug', 'logging.debug', (['"""--rank 6: UNCORRECTED"""'], {}), "('--rank 6: UNCORRECTED')\n", (12892, 12917), False, 'import logging, os\n'), ((13043, 13076), 'logging.debug', 'logging.debug', (['"""--rank 5: SHADOW"""'], {}), "('--rank 5: SHADOW')\n", (13056, 13076), False, 'import logging, os\n'), ((13180, 13213), 'logging.debug', 'logging.debug', (['"""--rank 4: CLOUDY"""'], {}), "('--rank 4: CLOUDY')\n", (13193, 13213), False, 'import logging, os\n'), ((13600, 13635), 'logging.debug', 'logging.debug', (['"""--rank 3: HIGHVIEW"""'], {}), "('--rank 3: HIGHVIEW')\n", (13613, 13635), False, 'import logging, os\n'), ((13684, 13717), 'logging.debug', 'logging.debug', (['"""--rank 2: LOWSUN"""'], {}), "('--rank 2: LOWSUN')\n", (13697, 13717), False, 'import logging, os\n'), ((13780, 13817), 'logging.debug', 'logging.debug', (['"""--rank 1: BAD pixels"""'], {}), "('--rank 1: BAD pixels')\n", (13793, 13817), False, 'import logging, os\n'), ((13994, 14031), 'logging.debug', 'logging.debug', (['"""-building water mask"""'], {}), "('-building water mask')\n", (14007, 14031), False, 'import logging, os\n'), ((5071, 5097), 'os.path.splitext', 'os.path.splitext', (['in_stack'], {}), '(in_stack)\n', (5087, 5097), False, 'import logging, os\n'), ((14840, 14868), 'numpy.full', 'np.full', (['state_arr.shape', '(10)'], {}), '(state_arr.shape, 10)\n', (14847, 14868), True, 'import numpy as np\n'), ((14919, 14950), 'logging.debug', 'logging.debug', (['"""--rank 9: SNOW"""'], {}), "('--rank 9: SNOW')\n", (14932, 14950), False, 'import logging, os\n'), ((15053, 15091), 'logging.debug', 'logging.debug', (['"""--rank 8: HIGHAEROSOL"""'], {}), "('--rank 8: HIGHAEROSOL')\n", (15066, 15091), False, 'import logging, os\n'), ((15187, 15221), 'logging.debug', 'logging.debug', (['"""--rank 7: AEROSOL"""'], {}), "('--rank 7: AEROSOL')\n", (15200, 15221), False, 'import logging, os\n'), ((15574, 15607), 'logging.debug', 'logging.debug', (['"""--rank 5: SHADOW"""'], {}), "('--rank 5: SHADOW')\n", (15587, 15607), False, 'import logging, os\n'), ((15711, 15744), 'logging.debug', 'logging.debug', (['"""--rank 4: CLOUDY"""'], {}), "('--rank 4: CLOUDY')\n", (15724, 15744), False, 'import logging, os\n'), ((16178, 16213), 'logging.debug', 'logging.debug', (['"""--rank 3: HIGHVIEW"""'], {}), "('--rank 3: HIGHVIEW')\n", (16191, 16213), False, 'import logging, os\n'), ((16262, 16295), 'logging.debug', 'logging.debug', (['"""--rank 2: LOWSUN"""'], {}), "('--rank 2: LOWSUN')\n", (16275, 16295), False, 'import logging, os\n'), ((16358, 16395), 'logging.debug', 'logging.debug', (['"""--rank 1: BAD pixels"""'], {}), "('--rank 1: BAD pixels')\n", (16371, 16395), False, 'import logging, os\n'), ((16489, 16526), 'logging.debug', 'logging.debug', (['"""-building water mask"""'], {}), "('-building water mask')\n", (16502, 16526), False, 'import logging, os\n'), ((1582, 1610), 'os.path.basename', 'os.path.basename', (['stack_path'], {}), '(stack_path)\n', (1598, 1610), False, 'import logging, os\n'), ((3089, 3115), 'os.path.basename', 'os.path.basename', (['in_stack'], {}), '(in_stack)\n', (3105, 3115), False, 'import logging, os\n'), ((3447, 3473), 'os.path.splitext', 'os.path.splitext', (['in_stack'], {}), '(in_stack)\n', (3463, 3473), False, 'import logging, os\n'), ((4004, 4030), 'os.path.splitext', 'os.path.splitext', (['in_stack'], {}), '(in_stack)\n', (4020, 4030), False, 'import logging, os\n'), ((4905, 4931), 'os.path.basename', 'os.path.basename', (['in_stack'], {}), '(in_stack)\n', (4921, 4931), False, 'import logging, os\n'), ((6320, 6346), 'os.path.basename', 'os.path.basename', (['in_stack'], {}), '(in_stack)\n', (6336, 6346), False, 'import logging, os\n')]
# adapted from https://github.com/JTT94/filterflow/blob/master/scripts/stochastic_volatility.py import enum import os import sys import time from datetime import datetime import random sys.path.append('../') import matplotlib.pyplot as plt import numpy as np import pandas as pd import tensorflow as tf from absl import flags, app import tensorflow_probability as tfp from tensorflow_probability.python.internal.samplers import split_seed from tqdm import tqdm # tf.function = lambda z: z from filterflow.base import State from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, \ CorrectedRegularizedTransform from filterflow.resampling.criterion import NeverResample, AlwaysResample, NeffCriterion from filterflow.resampling.differentiable import PartiallyCorrectedRegularizedTransform from filterflow.resampling.differentiable.loss import SinkhornLoss from filterflow.resampling.differentiable.optimized import OptimizedPointCloud from filterflow.resampling.differentiable.optimizer.sgd import SGD from filterflow.models.adapter import make_filter_multiple_data import quandl from algorithm import VariationalSequentialMonteCarloMultipleData, VariationalMarginalParticleFilterMultipleData, ImportanceWeightedVariationalInferenceMultipleData, VariationalMarginalParticleFilterBiasedGradientsMultipleData from proposal import DenseNeuralNetwork from model import DeepMarkovModelData, DeepMarkovModel, DeepMarkovModelParameters from utils import Logger class ResamplingMethodsEnum(enum.IntEnum): MULTINOMIAL = 0 SYSTEMATIC = 1 STRATIFIED = 2 REGULARIZED = 3 VARIANCE_CORRECTED = 4 OPTIMIZED = 5 CORRECTED = 6 def resampling_method_factory(resampling_method_enum, resampling_kwargs): if resampling_method_enum == ResamplingMethodsEnum.MULTINOMIAL: resampling_method = MultinomialResampler() elif resampling_method_enum == ResamplingMethodsEnum.SYSTEMATIC: resampling_method = SystematicResampler() elif resampling_method_enum == ResamplingMethodsEnum.STRATIFIED: resampling_method = StratifiedResampler() elif resampling_method_enum == ResamplingMethodsEnum.REGULARIZED: resampling_method = RegularisedTransform(**resampling_kwargs) elif resampling_method_enum == ResamplingMethodsEnum.VARIANCE_CORRECTED: regularized_resampler = RegularisedTransform(**resampling_kwargs) resampling_method = PartiallyCorrectedRegularizedTransform(regularized_resampler) elif resampling_method_enum == ResamplingMethodsEnum.OPTIMIZED: lr = resampling_kwargs.pop('lr', resampling_kwargs.pop('learning_rate', 0.1)) decay = resampling_kwargs.pop('lr', 0.95) symmetric = resampling_kwargs.pop('symmetric', True) loss = SinkhornLoss(**resampling_kwargs, symmetric=symmetric) optimizer = SGD(loss, lr=lr, decay=decay) regularized_resampler = RegularisedTransform(**resampling_kwargs) intermediate_resampling_method = PartiallyCorrectedRegularizedTransform(regularized_resampler) resampling_method = OptimizedPointCloud(optimizer, intermediate_resampler=intermediate_resampling_method) elif resampling_method_enum == ResamplingMethodsEnum.CORRECTED: resampling_method = CorrectedRegularizedTransform(**resampling_kwargs) else: raise ValueError(f'resampling_method_name {resampling_method_enum} is not a valid ResamplingMethodsEnum') return resampling_method def routine(pf, initial_state, observations_dataset, T, variables, seed): with tf.GradientTape() as tape: tape.watch(variables) final_state = pf(initial_state, observations_dataset, T, seed=seed, return_final=True) res = -tf.reduce_mean(final_state.log_likelihoods) return res, tape.gradient(res, variables), tf.reduce_mean(final_state.ess) def get_gradient_descent_function(): # This is a trick because tensorflow doesn't allow you to create variables inside a decorated function def gradient_descent(pf, initial_state, train_dataset, test_dataset, valid_dataset, n_iter, optimizers, variables, initial_values, change_seed, seed, large_initial_state, surrogate_smc, logdir, evaluate_period = 10, evaluation_n = 10, final_evaluation_n = 100): n_iters = np.sum(n_iter) reset_operations = [k.assign(v) for k, v in zip(variables, initial_values)] loss = tf.TensorArray(dtype=tf.float32, size=n_iters + 1, dynamic_size=False) ess = tf.TensorArray(dtype=tf.float32, size=n_iters + 1, dynamic_size=False) filter_seed, seed = split_seed(seed, n=2, salt='gradient_descent') with tf.control_dependencies(reset_operations): step = 1 last_time = time.time() best_val = -np.inf best_epoch = 0 for optimizer, n in zip(optimizers, n_iter): for i in tf.range(n): # for var in variables: # tf.print(var) elbos = 0. steps = 0 random.shuffle(train_dataset) for data in tqdm(train_dataset): loss_value, grads, average_ess = routine(pf, initial_state, data, tf.cast(data.cardinality(),tf.int32), variables, seed) # tf.print(loss_value) if change_seed: filter_seed, seed = split_seed(filter_seed, n=2) # ess = ess.write(tf.cast(i, tf.int32), average_ess) # for grad in grads: # tf.print(tf.reduce_max(tf.abs(grad))) # print(grads) # max_grad = tf.reduce_max([tf.reduce_max(tf.abs(grad)) for grad in grads]) # for grad in grads: # tf.print(tf.reduce_max(tf.abs(grad))) optimizer.apply_gradients(zip(grads, variables)) elbos += loss_value steps += data.cardinality().numpy() tf.print('Step', i+step, ', lr: ', optimizer.learning_rate, ', npt: ',-elbos/steps) # tf.print('') if (i+step)%evaluate_period == 0: elbos = 0. steps = 0 for _ in tqdm(range(evaluation_n)): for data in valid_dataset: elbo, _, _ = routine(surrogate_smc, large_initial_state, data, tf.cast(data.cardinality(),tf.int32), variables, seed) elbos += elbo.numpy() steps += data.cardinality().numpy() #loss = loss.write(tf.cast(i + step, tf.int32), tf.reduce_mean(elbos)) current_time = time.time() val_npt = -elbos/steps tf.print('valid npt: ', val_npt, ' time period: ', current_time - last_time) last_time = current_time if val_npt > best_val: saver = tf.train.Checkpoint() saver.listed = variables saver.save(os.path.join(logdir, 'best-ckpt')) tf.print("Saved the best ckpt at step ", i + step) best_val = val_npt best_epoch = i + step if (i+step) % 100 == 0: saver = tf.train.Checkpoint() saver.listed = variables saver.save(os.path.join(logdir, 'middle-ckpt')) step += n return variables#, loss.stack(), ess.stack() return gradient_descent def compile_learning_rates(pf, initial_state, train_dataset, test_dataset, valid_dataset, variables, initial_values, n_iter, optimizer_maker, learning_rates, filter_seed, change_seed, large_initial_state, surrogate_smc, logdir): loss_profiles = [] ess_profiles = [] optimizers = [] for learning_rate in tqdm(learning_rates): optimizer = optimizer_maker(learning_rate=learning_rate) optimizers.append(optimizer) gradient_descent_function = get_gradient_descent_function() final_variables = gradient_descent_function(pf, initial_state, train_dataset, test_dataset, valid_dataset, n_iter, optimizers, variables, initial_values, change_seed, filter_seed, large_initial_state, surrogate_smc, logdir) #loss_profiles.append(-loss_profile.numpy() / T) #ess_profiles.append(ess_profile.numpy()) return #loss_profiles, ess_profiles def plot_losses(loss_profiles_df, filename, savefig, dx, dy, dense, T, change_seed): fig, ax = plt.subplots(figsize=(5, 5)) loss_profiles_df.style.float_format = '${:,.1f}'.format loss_profiles_df.plot(ax=ax, legend=False) # ax.set_ylim(250, 700) ax.legend() fig.tight_layout() if savefig: fig.savefig(os.path.join('./charts/', f'stochvol_lr_loss_{filename}_dx_{dx}_dy_{dy}_dense_{dense}_T_{T}_change_seed_{change_seed}.png')) else: fig.suptitle(f'stochvol_loss_{filename}_dx_{dx}_dy_{dy}_dense_{dense}_T_{T}') plt.show() def plot_losses_vs_ess(loss_profiles_df, ess_profiles_df, filename, savefig, M, n_particles, change_seed, batch_size, n_iter, epsilon): fig, ax = plt.subplots(figsize=(5, 3)) loss_profiles_df.style.float_format = '${:,.1f}'.format loss_profiles_df.plot(ax=ax, legend=False) ax.set_xlim(0, n_iter) ax1 = ax.twinx() ess_profiles_df.plot.area(ax=ax1, legend=False, linestyle='--', alpha=0.33, stacked=False) ax.set_ylim(8, 21) ax1.set_ylim(1, n_particles) # ax.legend() fig.tight_layout() filename = f'stochvol_diff_lr_loss_ess_{filename}_epsilon_{epsilon}_N_{n_particles}__M_{M}_change_seed_{change_seed}_batch_size_{batch_size}' if savefig: fig.savefig(os.path.join('./charts/', filename + '.png')) loss_profiles_df.to_csv(os.path.join('./tables/', filename + '.csv')) else: fig.suptitle(f'stochvol_loss_ess_{filename}_nfactors_M_{M}') plt.show() def plot_variables(variables_df, filename, savefig): fig, ax = plt.subplots(figsize=(5, 5)) variables_df.plot(ax=ax) fig.tight_layout() if savefig: fig.savefig(os.path.join('./charts/', f'stochvol_different_lr_variables_{filename}.png')) else: fig.suptitle(f'stochvol_different_lr_variables_{filename}') plt.show() def main(resampling_method_value, resampling_neff, proposal, dataset, d_h, logdir, learning_rates=(1e-2,), resampling_kwargs=None, batch_size=1, n_particles=4, n_iter=(50, ), savefig=False, filter_seed=0, use_xla=False, change_seed=True, restore=None): model = DeepMarkovModel(DeepMarkovModelParameters(d_l=d_h)) proposal = proposal(model=model) data = DeepMarkovModelData(dataset=dataset) trainable_variables = proposal.get_trainable_variables() trainable_variables.extend(model.get_trainable_variables()) if restore != '': rst = tf.train.Checkpoint() rst.listed = trainable_variables rst.restore(restore).assert_consumed() print('Retrieved from ', restore) train, valid, test = data.get_data() resampling_method_enum = ResamplingMethodsEnum(resampling_method_value) train_dataset = [tf.data.Dataset.from_tensor_slices(y) for y in train] test_dataset = [tf.data.Dataset.from_tensor_slices(y) for y in test] valid_dataset = [tf.data.Dataset.from_tensor_slices(y) for y in valid] if resampling_kwargs is None: resampling_kwargs = {} if resampling_neff == 0.: resampling_criterion = NeverResample() elif resampling_neff == 1.: resampling_criterion = AlwaysResample() else: resampling_criterion = NeffCriterion(resampling_neff, True) if resampling_method_enum == ResamplingMethodsEnum.MULTINOMIAL: resampling_method = MultinomialResampler() elif resampling_method_enum == ResamplingMethodsEnum.SYSTEMATIC: resampling_method = SystematicResampler() elif resampling_method_enum == ResamplingMethodsEnum.STRATIFIED: resampling_method = StratifiedResampler() elif resampling_method_enum == ResamplingMethodsEnum.REGULARIZED: resampling_method = RegularisedTransform(**resampling_kwargs) elif resampling_method_enum == ResamplingMethodsEnum.VARIANCE_CORRECTED: regularized_resampler = RegularisedTransform(**resampling_kwargs) resampling_method = PartiallyCorrectedRegularizedTransform(regularized_resampler) elif resampling_method_enum == ResamplingMethodsEnum.OPTIMIZED: lr = resampling_kwargs.pop('lr', resampling_kwargs.pop('learning_rate', 0.1)) loss = SinkhornLoss(**resampling_kwargs, symmetric=True) optimizer = SGD(loss, lr=lr, decay=0.95) regularized_resampler = RegularisedTransform(**resampling_kwargs) resampling_method = OptimizedPointCloud(optimizer, intermediate_resampler=regularized_resampler) elif resampling_method_enum == ResamplingMethodsEnum.CORRECTED: resampling_method = CorrectedRegularizedTransform(**resampling_kwargs) else: raise ValueError(f'resampling_method_name {resampling_method_enum} is not a valid ResamplingMethodsEnum') # np_random_state = np.random.RandomState(seed=555) # initial_particles = np_random_state.normal(1., 0.5, [batch_size, n_particles, M]).astype(np.float32) # initial_state = State(initial_particles) # # large_initial_particles = np_random_state.normal(1., 0.5, [25, n_particles, M]).astype(np.float32) # large_initial_state = State(large_initial_particles) # # mu_init = -5. * tf.ones(M) # F_init = 0.9 * tf.eye(M) # transition_cov_init = 0.35 * tf.eye(M) # observation_cov_init = 1. * tf.eye(M) # # mu = tf.Variable(mu_init, trainable=True) # F = tf.Variable(F_init, trainable=True) # transition_cov = tf.Variable(transition_cov_init, trainable=True) # observation_cov = tf.Variable(observation_cov_init, trainable=False) smc = make_filter_multiple_data(model, proposal, data, n_particles, resampling_method, resampling_criterion) surrogate_smc = make_filter_multiple_data(model, proposal, data, n_particles, StratifiedResampler(), resampling_criterion) def optimizer_maker(learning_rate): # tf.function doesn't like creating variables. This is a way to create them outside the graph # We can't reuse the same optimizer because it would be giving a warmed-up momentum to the ones run later optimizer = tf.optimizers.Adam(learning_rate=learning_rate) return optimizer #variables = [mu, F, transition_cov] initial_values = [v.value() for v in trainable_variables] initial_state = State(model.initial_state(n_particles)) compile_learning_rates(smc, initial_state, train_dataset, test_dataset, valid_dataset, trainable_variables, initial_values, n_iter, optimizer_maker, learning_rates, filter_seed, change_seed, initial_state, surrogate_smc, logdir=logdir) #losses_df = pd.DataFrame(np.stack(losses).T, columns=np.log10(learning_rates)) #ess_df = pd.DataFrame(np.stack(ess_profiles).T, columns=np.log10(learning_rates)) #losses_df.columns.name = 'log learning rate' #losses_df.columns.epoch = 'epoch' #ess_df.columns.name = 'log learning rate' #ess_df.columns.epoch = 'epoch' # plot_losses(losses_df, resampling_method_enum.name, savefig, dx, dy, dense, T, change_seed) #plot_losses_vs_ess(losses_df, ess_df, resampling_method_enum.name, savefig, M, n_particles, # change_seed, batch_size, n_iter, resampling_kwargs.get("epsilon")) FLAGS = flags.FLAGS flags.DEFINE_integer('resampling_method', ResamplingMethodsEnum.REGULARIZED, 'resampling_method') flags.DEFINE_float('epsilon', 0.5, 'epsilon') flags.DEFINE_float('resampling_neff', 1., 'resampling_neff') flags.DEFINE_float('scaling', 0.9, 'scaling') flags.DEFINE_float('log_learning_rate_min', -2., 'log_learning_rate_min') flags.DEFINE_float('log_learning_rate_max', -3., 'log_learning_rate_max') flags.DEFINE_integer('n_learning_rates', 1, 'log_learning_rate_max') flags.DEFINE_boolean('change_seed', True, 'change seed between each gradient descent step') flags.DEFINE_float('convergence_threshold', 1e-3, 'convergence_threshold') flags.DEFINE_integer('n_particles', 4, 'n_particles', lower_bound=4) flags.DEFINE_integer('batch_size', 1, 'batch_size', lower_bound=1) flags.DEFINE_list('n_iter', [250,250], 'n_iter') flags.DEFINE_integer('max_iter', 10000, 'max_iter', lower_bound=1) flags.DEFINE_boolean('savefig', True, 'Save fig') flags.DEFINE_integer('seed', 222, 'seed') flags.DEFINE_string('proposal','DenseNeuralNetwork','') flags.DEFINE_string('dataset','JSB','') flags.DEFINE_string('model','DeepMarkovModel','') flags.DEFINE_list('lr',[1e-2,1e-3],'') flags.DEFINE_integer('d_h', 64, '') flags.DEFINE_string('restore','','') def flag_main(argb): for name, value in FLAGS.flag_values_dict().items(): print(name, f'{repr(value)}') FLAGS.lr = [float(l) for l in FLAGS.lr] FLAGS.n_iter = [int(n) for n in FLAGS.n_iter] learning_rates = FLAGS.lr proposal = getattr(sys.modules[__name__], FLAGS.proposal) settings = '{dataset}/dpf_{N}'.format(dataset = FLAGS.dataset, N=str(FLAGS.n_particles)) stamp = datetime.now().strftime("%Y%m%d-%H%M%S.%f") logdir = ('final/{}/%s' % stamp).format(settings) writer = tf.summary.create_file_writer(logdir) outfile = os.path.join(logdir, 'stdout') errfile = os.path.join(logdir, 'stderr') sys.stdout = Logger(outfile) sys.stderr = Logger(errfile, sys.stderr) main(FLAGS.resampling_method, resampling_neff=FLAGS.resampling_neff, n_particles=FLAGS.n_particles, batch_size=FLAGS.batch_size, savefig=FLAGS.savefig, n_iter=FLAGS.n_iter, learning_rates=learning_rates, change_seed=FLAGS.change_seed, resampling_kwargs=dict(epsilon=FLAGS.epsilon, scaling=FLAGS.scaling, convergence_threshold=FLAGS.convergence_threshold, max_iter=FLAGS.max_iter), filter_seed=FLAGS.seed, proposal = proposal, dataset = FLAGS.dataset, d_h = FLAGS.d_h, logdir = logdir, restore = FLAGS.restore) if __name__ == '__main__': app.run(flag_main)
[ "tensorflow.train.Checkpoint", "filterflow.resampling.differentiable.loss.SinkhornLoss", "tensorflow.GradientTape", "tensorflow.control_dependencies", "tensorflow.reduce_mean", "filterflow.resampling.RegularisedTransform", "filterflow.resampling.SystematicResampler", "sys.path.append", "filterflow.r...
[((187, 209), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (202, 209), False, 'import sys\n'), ((16436, 16537), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""resampling_method"""', 'ResamplingMethodsEnum.REGULARIZED', '"""resampling_method"""'], {}), "('resampling_method', ResamplingMethodsEnum.REGULARIZED,\n 'resampling_method')\n", (16456, 16537), False, 'from absl import flags, app\n'), ((16534, 16579), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""epsilon"""', '(0.5)', '"""epsilon"""'], {}), "('epsilon', 0.5, 'epsilon')\n", (16552, 16579), False, 'from absl import flags, app\n'), ((16580, 16641), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""resampling_neff"""', '(1.0)', '"""resampling_neff"""'], {}), "('resampling_neff', 1.0, 'resampling_neff')\n", (16598, 16641), False, 'from absl import flags, app\n'), ((16641, 16686), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""scaling"""', '(0.9)', '"""scaling"""'], {}), "('scaling', 0.9, 'scaling')\n", (16659, 16686), False, 'from absl import flags, app\n'), ((16687, 16761), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""log_learning_rate_min"""', '(-2.0)', '"""log_learning_rate_min"""'], {}), "('log_learning_rate_min', -2.0, 'log_learning_rate_min')\n", (16705, 16761), False, 'from absl import flags, app\n'), ((16761, 16835), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""log_learning_rate_max"""', '(-3.0)', '"""log_learning_rate_max"""'], {}), "('log_learning_rate_max', -3.0, 'log_learning_rate_max')\n", (16779, 16835), False, 'from absl import flags, app\n'), ((16835, 16903), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""n_learning_rates"""', '(1)', '"""log_learning_rate_max"""'], {}), "('n_learning_rates', 1, 'log_learning_rate_max')\n", (16855, 16903), False, 'from absl import flags, app\n'), ((16904, 16999), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""change_seed"""', '(True)', '"""change seed between each gradient descent step"""'], {}), "('change_seed', True,\n 'change seed between each gradient descent step')\n", (16924, 16999), False, 'from absl import flags, app\n'), ((16996, 17071), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""convergence_threshold"""', '(0.001)', '"""convergence_threshold"""'], {}), "('convergence_threshold', 0.001, 'convergence_threshold')\n", (17014, 17071), False, 'from absl import flags, app\n'), ((17071, 17139), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""n_particles"""', '(4)', '"""n_particles"""'], {'lower_bound': '(4)'}), "('n_particles', 4, 'n_particles', lower_bound=4)\n", (17091, 17139), False, 'from absl import flags, app\n'), ((17140, 17206), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""batch_size"""', '(1)', '"""batch_size"""'], {'lower_bound': '(1)'}), "('batch_size', 1, 'batch_size', lower_bound=1)\n", (17160, 17206), False, 'from absl import flags, app\n'), ((17207, 17256), 'absl.flags.DEFINE_list', 'flags.DEFINE_list', (['"""n_iter"""', '[250, 250]', '"""n_iter"""'], {}), "('n_iter', [250, 250], 'n_iter')\n", (17224, 17256), False, 'from absl import flags, app\n'), ((17256, 17322), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""max_iter"""', '(10000)', '"""max_iter"""'], {'lower_bound': '(1)'}), "('max_iter', 10000, 'max_iter', lower_bound=1)\n", (17276, 17322), False, 'from absl import flags, app\n'), ((17323, 17372), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""savefig"""', '(True)', '"""Save fig"""'], {}), "('savefig', True, 'Save fig')\n", (17343, 17372), False, 'from absl import flags, app\n'), ((17373, 17414), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""seed"""', '(222)', '"""seed"""'], {}), "('seed', 222, 'seed')\n", (17393, 17414), False, 'from absl import flags, app\n'), ((17415, 17472), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""proposal"""', '"""DenseNeuralNetwork"""', '""""""'], {}), "('proposal', 'DenseNeuralNetwork', '')\n", (17434, 17472), False, 'from absl import flags, app\n'), ((17471, 17512), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""dataset"""', '"""JSB"""', '""""""'], {}), "('dataset', 'JSB', '')\n", (17490, 17512), False, 'from absl import flags, app\n'), ((17511, 17562), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""model"""', '"""DeepMarkovModel"""', '""""""'], {}), "('model', 'DeepMarkovModel', '')\n", (17530, 17562), False, 'from absl import flags, app\n'), ((17561, 17603), 'absl.flags.DEFINE_list', 'flags.DEFINE_list', (['"""lr"""', '[0.01, 0.001]', '""""""'], {}), "('lr', [0.01, 0.001], '')\n", (17578, 17603), False, 'from absl import flags, app\n'), ((17600, 17635), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""d_h"""', '(64)', '""""""'], {}), "('d_h', 64, '')\n", (17620, 17635), False, 'from absl import flags, app\n'), ((17636, 17674), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""restore"""', '""""""', '""""""'], {}), "('restore', '', '')\n", (17655, 17674), False, 'from absl import flags, app\n'), ((8331, 8351), 'tqdm.tqdm', 'tqdm', (['learning_rates'], {}), '(learning_rates)\n', (8335, 8351), False, 'from tqdm import tqdm\n'), ((9146, 9174), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (9158, 9174), True, 'import matplotlib.pyplot as plt\n'), ((9834, 9862), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 3)'}), '(figsize=(5, 3))\n', (9846, 9862), True, 'import matplotlib.pyplot as plt\n'), ((10766, 10794), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (10778, 10794), True, 'import matplotlib.pyplot as plt\n'), ((11443, 11479), 'model.DeepMarkovModelData', 'DeepMarkovModelData', ([], {'dataset': 'dataset'}), '(dataset=dataset)\n', (11462, 11479), False, 'from model import DeepMarkovModelData, DeepMarkovModel, DeepMarkovModelParameters\n'), ((14695, 14801), 'filterflow.models.adapter.make_filter_multiple_data', 'make_filter_multiple_data', (['model', 'proposal', 'data', 'n_particles', 'resampling_method', 'resampling_criterion'], {}), '(model, proposal, data, n_particles,\n resampling_method, resampling_criterion)\n', (14720, 14801), False, 'from filterflow.models.adapter import make_filter_multiple_data\n'), ((18193, 18230), 'tensorflow.summary.create_file_writer', 'tf.summary.create_file_writer', (['logdir'], {}), '(logdir)\n', (18222, 18230), True, 'import tensorflow as tf\n'), ((18245, 18275), 'os.path.join', 'os.path.join', (['logdir', '"""stdout"""'], {}), "(logdir, 'stdout')\n", (18257, 18275), False, 'import os\n'), ((18290, 18320), 'os.path.join', 'os.path.join', (['logdir', '"""stderr"""'], {}), "(logdir, 'stderr')\n", (18302, 18320), False, 'import os\n'), ((18338, 18353), 'utils.Logger', 'Logger', (['outfile'], {}), '(outfile)\n', (18344, 18353), False, 'from utils import Logger\n'), ((18371, 18398), 'utils.Logger', 'Logger', (['errfile', 'sys.stderr'], {}), '(errfile, sys.stderr)\n', (18377, 18398), False, 'from utils import Logger\n'), ((19169, 19187), 'absl.app.run', 'app.run', (['flag_main'], {}), '(flag_main)\n', (19176, 19187), False, 'from absl import flags, app\n'), ((1883, 1905), 'filterflow.resampling.MultinomialResampler', 'MultinomialResampler', ([], {}), '()\n', (1903, 1905), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((3590, 3607), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (3605, 3607), True, 'import tensorflow as tf\n'), ((3848, 3879), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['final_state.ess'], {}), '(final_state.ess)\n', (3862, 3879), True, 'import tensorflow as tf\n'), ((4336, 4350), 'numpy.sum', 'np.sum', (['n_iter'], {}), '(n_iter)\n', (4342, 4350), True, 'import numpy as np\n'), ((4450, 4520), 'tensorflow.TensorArray', 'tf.TensorArray', ([], {'dtype': 'tf.float32', 'size': '(n_iters + 1)', 'dynamic_size': '(False)'}), '(dtype=tf.float32, size=n_iters + 1, dynamic_size=False)\n', (4464, 4520), True, 'import tensorflow as tf\n'), ((4535, 4605), 'tensorflow.TensorArray', 'tf.TensorArray', ([], {'dtype': 'tf.float32', 'size': '(n_iters + 1)', 'dynamic_size': '(False)'}), '(dtype=tf.float32, size=n_iters + 1, dynamic_size=False)\n', (4549, 4605), True, 'import tensorflow as tf\n'), ((4635, 4681), 'tensorflow_probability.python.internal.samplers.split_seed', 'split_seed', (['seed'], {'n': '(2)', 'salt': '"""gradient_descent"""'}), "(seed, n=2, salt='gradient_descent')\n", (4645, 4681), False, 'from tensorflow_probability.python.internal.samplers import split_seed\n'), ((9648, 9658), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9656, 9658), True, 'import matplotlib.pyplot as plt\n'), ((10686, 10696), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10694, 10696), True, 'import matplotlib.pyplot as plt\n'), ((11047, 11057), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11055, 11057), True, 'import matplotlib.pyplot as plt\n'), ((11359, 11393), 'model.DeepMarkovModelParameters', 'DeepMarkovModelParameters', ([], {'d_l': 'd_h'}), '(d_l=d_h)\n', (11384, 11393), False, 'from model import DeepMarkovModelData, DeepMarkovModel, DeepMarkovModelParameters\n'), ((11641, 11662), 'tensorflow.train.Checkpoint', 'tf.train.Checkpoint', ([], {}), '()\n', (11660, 11662), True, 'import tensorflow as tf\n'), ((11933, 11970), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['y'], {}), '(y)\n', (11967, 11970), True, 'import tensorflow as tf\n'), ((12007, 12044), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['y'], {}), '(y)\n', (12041, 12044), True, 'import tensorflow as tf\n'), ((12081, 12118), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['y'], {}), '(y)\n', (12115, 12118), True, 'import tensorflow as tf\n'), ((12263, 12278), 'filterflow.resampling.criterion.NeverResample', 'NeverResample', ([], {}), '()\n', (12276, 12278), False, 'from filterflow.resampling.criterion import NeverResample, AlwaysResample, NeffCriterion\n'), ((12534, 12556), 'filterflow.resampling.MultinomialResampler', 'MultinomialResampler', ([], {}), '()\n', (12554, 12556), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((14880, 14901), 'filterflow.resampling.StratifiedResampler', 'StratifiedResampler', ([], {}), '()\n', (14899, 14901), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((15202, 15249), 'tensorflow.optimizers.Adam', 'tf.optimizers.Adam', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (15220, 15249), True, 'import tensorflow as tf\n'), ((2003, 2024), 'filterflow.resampling.SystematicResampler', 'SystematicResampler', ([], {}), '()\n', (2022, 2024), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((3757, 3800), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['final_state.log_likelihoods'], {}), '(final_state.log_likelihoods)\n', (3771, 3800), True, 'import tensorflow as tf\n'), ((4696, 4737), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['reset_operations'], {}), '(reset_operations)\n', (4719, 4737), True, 'import tensorflow as tf\n'), ((4784, 4795), 'time.time', 'time.time', ([], {}), '()\n', (4793, 4795), False, 'import time\n'), ((9386, 9518), 'os.path.join', 'os.path.join', (['"""./charts/"""', 'f"""stochvol_lr_loss_{filename}_dx_{dx}_dy_{dy}_dense_{dense}_T_{T}_change_seed_{change_seed}.png"""'], {}), "('./charts/',\n f'stochvol_lr_loss_{filename}_dx_{dx}_dy_{dy}_dense_{dense}_T_{T}_change_seed_{change_seed}.png'\n )\n", (9398, 9518), False, 'import os\n'), ((10396, 10440), 'os.path.join', 'os.path.join', (['"""./charts/"""', "(filename + '.png')"], {}), "('./charts/', filename + '.png')\n", (10408, 10440), False, 'import os\n'), ((10507, 10551), 'os.path.join', 'os.path.join', (['"""./tables/"""', "(filename + '.csv')"], {}), "('./tables/', filename + '.csv')\n", (10519, 10551), False, 'import os\n'), ((10883, 10959), 'os.path.join', 'os.path.join', (['"""./charts/"""', 'f"""stochvol_different_lr_variables_{filename}.png"""'], {}), "('./charts/', f'stochvol_different_lr_variables_{filename}.png')\n", (10895, 10959), False, 'import os\n'), ((12342, 12358), 'filterflow.resampling.criterion.AlwaysResample', 'AlwaysResample', ([], {}), '()\n', (12356, 12358), False, 'from filterflow.resampling.criterion import NeverResample, AlwaysResample, NeffCriterion\n'), ((12400, 12436), 'filterflow.resampling.criterion.NeffCriterion', 'NeffCriterion', (['resampling_neff', '(True)'], {}), '(resampling_neff, True)\n', (12413, 12436), False, 'from filterflow.resampling.criterion import NeverResample, AlwaysResample, NeffCriterion\n'), ((12654, 12675), 'filterflow.resampling.SystematicResampler', 'SystematicResampler', ([], {}), '()\n', (12673, 12675), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((18082, 18096), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (18094, 18096), False, 'from datetime import datetime\n'), ((2122, 2143), 'filterflow.resampling.StratifiedResampler', 'StratifiedResampler', ([], {}), '()\n', (2141, 2143), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((4936, 4947), 'tensorflow.range', 'tf.range', (['n'], {}), '(n)\n', (4944, 4947), True, 'import tensorflow as tf\n'), ((12773, 12794), 'filterflow.resampling.StratifiedResampler', 'StratifiedResampler', ([], {}), '()\n', (12792, 12794), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((2242, 2283), 'filterflow.resampling.RegularisedTransform', 'RegularisedTransform', ([], {}), '(**resampling_kwargs)\n', (2262, 2283), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((5114, 5143), 'random.shuffle', 'random.shuffle', (['train_dataset'], {}), '(train_dataset)\n', (5128, 5143), False, 'import random\n'), ((5176, 5195), 'tqdm.tqdm', 'tqdm', (['train_dataset'], {}), '(train_dataset)\n', (5180, 5195), False, 'from tqdm import tqdm\n'), ((6204, 6297), 'tensorflow.print', 'tf.print', (['"""Step"""', '(i + step)', '""", lr: """', 'optimizer.learning_rate', '""", npt: """', '(-elbos / steps)'], {}), "('Step', i + step, ', lr: ', optimizer.learning_rate, ', npt: ', -\n elbos / steps)\n", (6212, 6297), True, 'import tensorflow as tf\n'), ((12893, 12934), 'filterflow.resampling.RegularisedTransform', 'RegularisedTransform', ([], {}), '(**resampling_kwargs)\n', (12913, 12934), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((2393, 2434), 'filterflow.resampling.RegularisedTransform', 'RegularisedTransform', ([], {}), '(**resampling_kwargs)\n', (2413, 2434), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((2463, 2524), 'filterflow.resampling.differentiable.PartiallyCorrectedRegularizedTransform', 'PartiallyCorrectedRegularizedTransform', (['regularized_resampler'], {}), '(regularized_resampler)\n', (2501, 2524), False, 'from filterflow.resampling.differentiable import PartiallyCorrectedRegularizedTransform\n'), ((7011, 7022), 'time.time', 'time.time', ([], {}), '()\n', (7020, 7022), False, 'import time\n'), ((7094, 7170), 'tensorflow.print', 'tf.print', (['"""valid npt: """', 'val_npt', '""" time period: """', '(current_time - last_time)'], {}), "('valid npt: ', val_npt, ' time period: ', current_time - last_time)\n", (7102, 7170), True, 'import tensorflow as tf\n'), ((7704, 7725), 'tensorflow.train.Checkpoint', 'tf.train.Checkpoint', ([], {}), '()\n', (7723, 7725), True, 'import tensorflow as tf\n'), ((13044, 13085), 'filterflow.resampling.RegularisedTransform', 'RegularisedTransform', ([], {}), '(**resampling_kwargs)\n', (13064, 13085), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((13114, 13175), 'filterflow.resampling.differentiable.PartiallyCorrectedRegularizedTransform', 'PartiallyCorrectedRegularizedTransform', (['regularized_resampler'], {}), '(regularized_resampler)\n', (13152, 13175), False, 'from filterflow.resampling.differentiable import PartiallyCorrectedRegularizedTransform\n'), ((2806, 2860), 'filterflow.resampling.differentiable.loss.SinkhornLoss', 'SinkhornLoss', ([], {'symmetric': 'symmetric'}), '(**resampling_kwargs, symmetric=symmetric)\n', (2818, 2860), False, 'from filterflow.resampling.differentiable.loss import SinkhornLoss\n'), ((2882, 2911), 'filterflow.resampling.differentiable.optimizer.sgd.SGD', 'SGD', (['loss'], {'lr': 'lr', 'decay': 'decay'}), '(loss, lr=lr, decay=decay)\n', (2885, 2911), False, 'from filterflow.resampling.differentiable.optimizer.sgd import SGD\n'), ((2945, 2986), 'filterflow.resampling.RegularisedTransform', 'RegularisedTransform', ([], {}), '(**resampling_kwargs)\n', (2965, 2986), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((3028, 3089), 'filterflow.resampling.differentiable.PartiallyCorrectedRegularizedTransform', 'PartiallyCorrectedRegularizedTransform', (['regularized_resampler'], {}), '(regularized_resampler)\n', (3066, 3089), False, 'from filterflow.resampling.differentiable import PartiallyCorrectedRegularizedTransform\n'), ((3119, 3209), 'filterflow.resampling.differentiable.optimized.OptimizedPointCloud', 'OptimizedPointCloud', (['optimizer'], {'intermediate_resampler': 'intermediate_resampling_method'}), '(optimizer, intermediate_resampler=\n intermediate_resampling_method)\n', (3138, 3209), False, 'from filterflow.resampling.differentiable.optimized import OptimizedPointCloud\n'), ((5543, 5571), 'tensorflow_probability.python.internal.samplers.split_seed', 'split_seed', (['filter_seed'], {'n': '(2)'}), '(filter_seed, n=2)\n', (5553, 5571), False, 'from tensorflow_probability.python.internal.samplers import split_seed\n'), ((7303, 7324), 'tensorflow.train.Checkpoint', 'tf.train.Checkpoint', ([], {}), '()\n', (7322, 7324), True, 'import tensorflow as tf\n'), ((7480, 7530), 'tensorflow.print', 'tf.print', (['"""Saved the best ckpt at step """', '(i + step)'], {}), "('Saved the best ckpt at step ', i + step)\n", (7488, 7530), True, 'import tensorflow as tf\n'), ((7810, 7845), 'os.path.join', 'os.path.join', (['logdir', '"""middle-ckpt"""'], {}), "(logdir, 'middle-ckpt')\n", (7822, 7845), False, 'import os\n'), ((13346, 13395), 'filterflow.resampling.differentiable.loss.SinkhornLoss', 'SinkhornLoss', ([], {'symmetric': '(True)'}), '(**resampling_kwargs, symmetric=True)\n', (13358, 13395), False, 'from filterflow.resampling.differentiable.loss import SinkhornLoss\n'), ((13416, 13444), 'filterflow.resampling.differentiable.optimizer.sgd.SGD', 'SGD', (['loss'], {'lr': 'lr', 'decay': '(0.95)'}), '(loss, lr=lr, decay=0.95)\n', (13419, 13444), False, 'from filterflow.resampling.differentiable.optimizer.sgd import SGD\n'), ((13477, 13518), 'filterflow.resampling.RegularisedTransform', 'RegularisedTransform', ([], {}), '(**resampling_kwargs)\n', (13497, 13518), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((13548, 13624), 'filterflow.resampling.differentiable.optimized.OptimizedPointCloud', 'OptimizedPointCloud', (['optimizer'], {'intermediate_resampler': 'regularized_resampler'}), '(optimizer, intermediate_resampler=regularized_resampler)\n', (13567, 13624), False, 'from filterflow.resampling.differentiable.optimized import OptimizedPointCloud\n'), ((3301, 3351), 'filterflow.resampling.CorrectedRegularizedTransform', 'CorrectedRegularizedTransform', ([], {}), '(**resampling_kwargs)\n', (3330, 3351), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n'), ((7417, 7450), 'os.path.join', 'os.path.join', (['logdir', '"""best-ckpt"""'], {}), "(logdir, 'best-ckpt')\n", (7429, 7450), False, 'import os\n'), ((13721, 13771), 'filterflow.resampling.CorrectedRegularizedTransform', 'CorrectedRegularizedTransform', ([], {}), '(**resampling_kwargs)\n', (13750, 13771), False, 'from filterflow.resampling import MultinomialResampler, SystematicResampler, StratifiedResampler, RegularisedTransform, CorrectedRegularizedTransform\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 30 10:54:48 2019 @author: ethan """ import topas2numpy as t2np import numpy as np import matplotlib.pyplot as plt exp_dose = np.genfromtxt('ChrisOBrien_Linac_Data.csv',delimiter=',') field_sizes = [5,20,30,40] for field_size in field_sizes: energy = 6.0 #MV exp_depths = np.arange(0,30.5,0.5) exp_pdd = exp_dose[1:,np.where(exp_dose[0]==field_size)[0]] exp_pdd = exp_pdd/exp_pdd[np.where(exp_depths==10)] cyl1 = t2np.BinnedResult("Historical_Model/PHSP_100_Times/PDDCyl_%sx%sMV.csv" % (field_size,field_size)) # cyl1 = t2np.BinnedResult("PDDCyl_%sx%sMV.csv" % (field_size,field_size)) depth = np.flip(cyl1.dimensions[2].get_bin_centers()) dose = np.squeeze(cyl1.data["Mean"]) percent_dose = dose/dose[np.where(depth==10.025)] fig, ax = plt.subplots() ax.plot(depth, percent_dose,label='%s cm square - 6.0MV' % field_size) ax.plot(exp_depths,exp_pdd,label="Experimental") ax.legend() ax.set_xlabel('Depth (cm)') ax.set_ylabel('Relative Dose (a.u.)') fig.tight_layout() fig.savefig('Dose_Comparison_6.0MV_%scm_square.png' % field_size,dpi=1000) fig.show()
[ "numpy.where", "numpy.squeeze", "topas2numpy.BinnedResult", "numpy.genfromtxt", "matplotlib.pyplot.subplots", "numpy.arange" ]
[((201, 259), 'numpy.genfromtxt', 'np.genfromtxt', (['"""ChrisOBrien_Linac_Data.csv"""'], {'delimiter': '""","""'}), "('ChrisOBrien_Linac_Data.csv', delimiter=',')\n", (214, 259), True, 'import numpy as np\n'), ((370, 393), 'numpy.arange', 'np.arange', (['(0)', '(30.5)', '(0.5)'], {}), '(0, 30.5, 0.5)\n', (379, 393), True, 'import numpy as np\n'), ((533, 636), 'topas2numpy.BinnedResult', 't2np.BinnedResult', (["('Historical_Model/PHSP_100_Times/PDDCyl_%sx%sMV.csv' % (field_size,\n field_size))"], {}), "('Historical_Model/PHSP_100_Times/PDDCyl_%sx%sMV.csv' % (\n field_size, field_size))\n", (550, 636), True, 'import topas2numpy as t2np\n'), ((778, 807), 'numpy.squeeze', 'np.squeeze', (["cyl1.data['Mean']"], {}), "(cyl1.data['Mean'])\n", (788, 807), True, 'import numpy as np\n'), ((886, 900), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (898, 900), True, 'import matplotlib.pyplot as plt\n'), ((486, 512), 'numpy.where', 'np.where', (['(exp_depths == 10)'], {}), '(exp_depths == 10)\n', (494, 512), True, 'import numpy as np\n'), ((837, 862), 'numpy.where', 'np.where', (['(depth == 10.025)'], {}), '(depth == 10.025)\n', (845, 862), True, 'import numpy as np\n'), ((418, 453), 'numpy.where', 'np.where', (['(exp_dose[0] == field_size)'], {}), '(exp_dose[0] == field_size)\n', (426, 453), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt #from skimage.io import imread from keras import backend as K import numpy as np def resize_crop_image(image,scale,cutoff_percent): image = cv2.resize(image,None,fx=scale, fy=scale, interpolation = cv2.INTER_AREA) cut_off_vals = [image.shape[0]*cutoff_percent/100, image.shape[1]*cutoff_percent/100] end_vals = [image.shape[0]-int(cut_off_vals[0]),image.shape[1]-int(cut_off_vals[1])] image =image[int(cut_off_vals[0]):int(end_vals[0]),int(cut_off_vals[1]):int(end_vals[1]) ] #plt.imshow(image) #plt.show() return(image) def rotate_thrice(square): return [square, np.rot90(square, 1), np.rot90(square, 2), np.rot90(square, 3)] def transforms(square): return rotate_thrice(square) + rotate_thrice(np.fliplr(square)) def your_loss(y_true, y_pred): #weights = np.ones(4) #weights = np.array([ 1 , 1, 1, 1]) weights = np.array([ 0.32 , 10, 1.3, 0.06]) #weights = np.array([0.99524712791495196, 0.98911715534979427, 0.015705375514403319]) #weights = np.array([ 0.91640706, 0.5022308, 0.1]) #weights = np.array([ 0.05 , 1.3, 0.55, 4.2]) #weights = np.array([0.00713773, 0.20517703, 0.15813273, 0.62955252]) #weights = np.array([1,,0.1,0.001]) # scale preds so that the class probas of each sample sum to 1 y_pred /= K.sum(y_pred, axis=-1, keepdims=True) # clip y_pred = K.clip(y_pred, K.epsilon(), 1) # calc loss = y_true*K.log(y_pred)*weights loss =-K.sum(loss,-1) return loss def raw_to_labels(image, count): #assert(image.max()==255) #if count <= 5: body = (image[:,:,0]==79) & ( image[:,:,1] ==255) & (image[:,:,2] ==130 ) legs = (image[:,:,0] == 255 ) & ( image[:,:,1] == 0) & (image[:,:,2] == 0) #else: # legs = (image[:,:,0]>=150) & ( image[:,:,1] <= 120) & (image[:,:,2] <= 120 ) # body = (image[:,:,0] <= 120 ) & ( image[:,:,1] <= 120) & (image[:,:,2] >= 130 ) antennae = (image[:,:,0] == 255 ) & ( image[:,:,1] == 225) & (image[:,:,2] == 10 ) background = ~legs & ~antennae & ~body softmax_labeled_image = np.zeros((image.shape[0], image.shape[1], 4)) softmax_labeled_image[body] = [1,0,0,0] softmax_labeled_image[antennae] = [0,1,0,0] softmax_labeled_image[legs] = [0,0,1,0] softmax_labeled_image[background] = [0,0,0,1] return softmax_labeled_image
[ "keras.backend.sum", "numpy.fliplr", "numpy.array", "numpy.zeros", "keras.backend.log", "numpy.rot90", "keras.backend.epsilon" ]
[((883, 914), 'numpy.array', 'np.array', (['[0.32, 10, 1.3, 0.06]'], {}), '([0.32, 10, 1.3, 0.06])\n', (891, 914), True, 'import numpy as np\n'), ((1306, 1343), 'keras.backend.sum', 'K.sum', (['y_pred'], {'axis': '(-1)', 'keepdims': '(True)'}), '(y_pred, axis=-1, keepdims=True)\n', (1311, 1343), True, 'from keras import backend as K\n'), ((2059, 2104), 'numpy.zeros', 'np.zeros', (['(image.shape[0], image.shape[1], 4)'], {}), '((image.shape[0], image.shape[1], 4))\n', (2067, 2104), True, 'import numpy as np\n'), ((617, 636), 'numpy.rot90', 'np.rot90', (['square', '(1)'], {}), '(square, 1)\n', (625, 636), True, 'import numpy as np\n'), ((638, 657), 'numpy.rot90', 'np.rot90', (['square', '(2)'], {}), '(square, 2)\n', (646, 657), True, 'import numpy as np\n'), ((659, 678), 'numpy.rot90', 'np.rot90', (['square', '(3)'], {}), '(square, 3)\n', (667, 678), True, 'import numpy as np\n'), ((1377, 1388), 'keras.backend.epsilon', 'K.epsilon', ([], {}), '()\n', (1386, 1388), True, 'from keras import backend as K\n'), ((1446, 1461), 'keras.backend.sum', 'K.sum', (['loss', '(-1)'], {}), '(loss, -1)\n', (1451, 1461), True, 'from keras import backend as K\n'), ((758, 775), 'numpy.fliplr', 'np.fliplr', (['square'], {}), '(square)\n', (767, 775), True, 'import numpy as np\n'), ((1416, 1429), 'keras.backend.log', 'K.log', (['y_pred'], {}), '(y_pred)\n', (1421, 1429), True, 'from keras import backend as K\n')]
import pandas as pd import numpy as np import umap import pyarrow.parquet as pq from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.model_selection import train_test_split from sklearn.manifold import TSNE from sklearn.pipeline import Pipeline from sklearn.decomposition import PCA from pyensembl import EnsemblRelease import plotly.graph_objects as go from plotly import graph_objs ensemble_data = EnsemblRelease(96) GTEX_EXPRESSIONS_PATH = './data/v8_expressions.parquet' GTEX_SAMPLES_PATH = './data/v8_samples.parquet' TRAIN_SIZE = 4500 TEST_SIZE = 1100 # load gene expression data def get_expressions(path=GTEX_EXPRESSIONS_PATH): if path.endswith(".parquet"): # genes_to_choose = pd.read_csv('data/aging_significant_genes.csv')['ids'].values return pq.read_table(path).to_pandas().set_index("Name") else: # genes_to_choose = pd.read_csv('data/aging_significant_genes.csv')['ids'].values separator = "," if path.endswith(".csv") else "\t" return pd.read_csv(path, sep=separator).set_index("Name") # load additional metadata of the dataset def get_samples(path=GTEX_SAMPLES_PATH): samples = pd.read_parquet(path, engine='pyarrow') samples["Death"].fillna(-1.0, inplace=True) samples = samples.set_index("Name") samples["Sex"].replace([1, 2], ['male', 'female'], inplace=True) samples["Death"].replace([-1, 0, 1, 2, 3, 4], ['alive/NA', 'ventilator case', '<10 min.', '<1 hr', '1-24 hr.', '>1 day'], inplace=True) return samples # load whole dataset def get_gtex_dataset(label='tissue', problem='classification'): samples = get_samples() expressions = get_expressions() first_1000_genes = list(expressions.columns)[:1000] expressions = expressions[first_1000_genes] data = samples.join(expressions, on="Name", how="inner") if label == 'age': if problem == 'classification': Y = data['Age'].values else: Y = data['Avg_age'].values else: Y = data["Tissue"].values # removing labels columns_to_drop = ["Tissue", "Sex", "Age", "Death", "Subtissue", "Avg_age"] valid_columns = data.columns.drop(columns_to_drop) # normalize expression data for nn steps = [('standardization', StandardScaler()), ('normalization', MinMaxScaler())] pre_processing_pipeline = Pipeline(steps) transformed_data = pre_processing_pipeline.fit_transform(data[valid_columns]) # save data to dataframe scaled_df = pd.DataFrame(transformed_data, columns=valid_columns) X = scaled_df.values X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, stratify=Y) gene_names = [ensemble_data.gene_name_of_gene_id(c) for c in list(scaled_df.columns)] return {'train_set': (X_train, Y_train), 'test_set': (X_test, Y_test), 'X_df': scaled_df.values, 'Y': Y, 'gene_names': gene_names} def get_3d_embeddings(method='umap', dataset='real', label='tissue', file_pattern=None, save=False): if dataset == 'real': data = get_gtex_dataset(problem='classification', label=label) x_values = data['X_df'] y_values = data['Y'] else: x_values = pd.read_csv('data/{}_expressions.csv'.format(file_pattern)).values y_values = pd.read_csv('data/{}_labels.csv'.format(file_pattern))['label'].values if method == 'umap': embedding = umap.UMAP(n_components=3).fit_transform(x_values) if method == 'tsne': embedding = TSNE(n_components=3, init='pca').fit_transform(x_values) if method == 'pca': embedding = PCA(n_components=3).fit_transform(x_values) if save: np.save('data/{0}_{1}.npy'.format(method, dataset), embedding) title = '3D embedding of {0} GTEx gene expressions by {1} coloured by {2}'.format(dataset, method, label) return embedding, y_values, title # limit expressions to only 50 genes def get_genes_of_interest(): with open('./data/selected_genes.txt') as f: content = [x.strip() for x in f.readlines()] return content def find_max_latent_space_size(X, components): pca = PCA(n_components=components) pca.fit(X) print('With', components, 'explained variance is', np.sum(pca.explained_variance_ratio_)) def plot_3d_embeddings(x_values, labels, title): uniq_y = list(set(labels)) label_name = 'tissue' if 'tissue' in title else 'age' colors_dict = {} for y in uniq_y: colors_dict[y] = get_random_plotly_color() colors = list(map(lambda y: colors_dict[y], labels)) x_vals = list(np.array(x_values[:, 0:1]).flatten()) y_vals = list(np.array(x_values[:, 1:2]).flatten()) z_vals = list(np.array(x_values[:, 2:3]).flatten()) df = pd.DataFrame(labels, columns=[label_name]) df['x'] = x_vals df['y'] = y_vals df['z'] = z_vals df['color'] = colors fig = go.Figure(data=[go.Scatter3d( x=df[df[label_name] == label]['x'].values, y=df[df[label_name] == label]['y'].values, z=df[df[label_name] == label]['z'].values, name=label, mode='markers', marker=dict( size=5, color=colors_dict[label] ) ) for label in uniq_y], layout=go.Layout( title=title, width=1000, showlegend=True, scene=graph_objs.Scene( xaxis=graph_objs.layout.scene.XAxis(title='x axis title'), yaxis=graph_objs.layout.scene.YAxis(title='y axis title'), zaxis=graph_objs.layout.scene.ZAxis(title='z axis title') ))) fig.show() def get_random_plotly_color(): colors = ''' aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen ''' colors_list = colors.split(',') colors_list = [c.replace('\n', '').replace(' ', '') for c in colors_list] return colors_list[np.random.choice(len(colors_list))] x, y, t = get_3d_embeddings(method='pca', dataset='real', label='tissue', file_pattern='trial_1_embedding') plot_3d_embeddings(x, y, t)
[ "plotly.graph_objs.layout.scene.YAxis", "pyarrow.parquet.read_table", "pandas.read_parquet", "pandas.DataFrame", "sklearn.pipeline.Pipeline", "sklearn.model_selection.train_test_split", "sklearn.decomposition.PCA", "pandas.read_csv", "plotly.graph_objs.layout.scene.XAxis", "sklearn.manifold.TSNE",...
[((424, 442), 'pyensembl.EnsemblRelease', 'EnsemblRelease', (['(96)'], {}), '(96)\n', (438, 442), False, 'from pyensembl import EnsemblRelease\n'), ((1174, 1213), 'pandas.read_parquet', 'pd.read_parquet', (['path'], {'engine': '"""pyarrow"""'}), "(path, engine='pyarrow')\n", (1189, 1213), True, 'import pandas as pd\n'), ((2426, 2441), 'sklearn.pipeline.Pipeline', 'Pipeline', (['steps'], {}), '(steps)\n', (2434, 2441), False, 'from sklearn.pipeline import Pipeline\n'), ((2570, 2623), 'pandas.DataFrame', 'pd.DataFrame', (['transformed_data'], {'columns': 'valid_columns'}), '(transformed_data, columns=valid_columns)\n', (2582, 2623), True, 'import pandas as pd\n'), ((2688, 2737), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.2)', 'stratify': 'Y'}), '(X, Y, test_size=0.2, stratify=Y)\n', (2704, 2737), False, 'from sklearn.model_selection import train_test_split\n'), ((4229, 4257), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'components'}), '(n_components=components)\n', (4232, 4257), False, 'from sklearn.decomposition import PCA\n'), ((4836, 4878), 'pandas.DataFrame', 'pd.DataFrame', (['labels'], {'columns': '[label_name]'}), '(labels, columns=[label_name])\n', (4848, 4878), True, 'import pandas as pd\n'), ((4328, 4365), 'numpy.sum', 'np.sum', (['pca.explained_variance_ratio_'], {}), '(pca.explained_variance_ratio_)\n', (4334, 4365), True, 'import numpy as np\n'), ((2342, 2358), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (2356, 2358), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), ((2379, 2393), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (2391, 2393), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), ((1024, 1056), 'pandas.read_csv', 'pd.read_csv', (['path'], {'sep': 'separator'}), '(path, sep=separator)\n', (1035, 1056), True, 'import pandas as pd\n'), ((3505, 3530), 'umap.UMAP', 'umap.UMAP', ([], {'n_components': '(3)'}), '(n_components=3)\n', (3514, 3530), False, 'import umap\n'), ((3601, 3633), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(3)', 'init': '"""pca"""'}), "(n_components=3, init='pca')\n", (3605, 3633), False, 'from sklearn.manifold import TSNE\n'), ((3703, 3722), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(3)'}), '(n_components=3)\n', (3706, 3722), False, 'from sklearn.decomposition import PCA\n'), ((4676, 4702), 'numpy.array', 'np.array', (['x_values[:, 0:1]'], {}), '(x_values[:, 0:1])\n', (4684, 4702), True, 'import numpy as np\n'), ((4732, 4758), 'numpy.array', 'np.array', (['x_values[:, 1:2]'], {}), '(x_values[:, 1:2])\n', (4740, 4758), True, 'import numpy as np\n'), ((4788, 4814), 'numpy.array', 'np.array', (['x_values[:, 2:3]'], {}), '(x_values[:, 2:3])\n', (4796, 4814), True, 'import numpy as np\n'), ((800, 819), 'pyarrow.parquet.read_table', 'pq.read_table', (['path'], {}), '(path)\n', (813, 819), True, 'import pyarrow.parquet as pq\n'), ((5455, 5506), 'plotly.graph_objs.layout.scene.XAxis', 'graph_objs.layout.scene.XAxis', ([], {'title': '"""x axis title"""'}), "(title='x axis title')\n", (5484, 5506), False, 'from plotly import graph_objs\n'), ((5526, 5577), 'plotly.graph_objs.layout.scene.YAxis', 'graph_objs.layout.scene.YAxis', ([], {'title': '"""y axis title"""'}), "(title='y axis title')\n", (5555, 5577), False, 'from plotly import graph_objs\n'), ((5597, 5648), 'plotly.graph_objs.layout.scene.ZAxis', 'graph_objs.layout.scene.ZAxis', ([], {'title': '"""z axis title"""'}), "(title='z axis title')\n", (5626, 5648), False, 'from plotly import graph_objs\n')]
""" A wrapper for generic and symmetric tensors providing required functionality for PEPS calculations Author: <NAME> <<EMAIL>> Date: January 2020 """ from numpy import float_ from cyclopeps.tools.utils import * try: import symtensor.sym as symlib from symtensor.tools.la import symqr, symsvd except: symlib,symqr,symsvd = None,None,None import copy import itertools import sys import numpy as np import ctf import uuid from shutil import copyfile as _copyfile LETTERS = 'abcdefghijklmnoprstuvwxyz' FLIP = {'+':'-','-':'+'} ########################################################### # Functions ########################################################### def calc_entanglement(S,backend=np): """ Calculate entanglement given a vector of singular values Args: S : 1D Array Singular Values Returns: EE : double The von neumann entanglement entropy EEspec : 1D Array The von neumann entanglement spectrum i.e. EEs[i] = S[i]^2*log_2(S[i]^2) """ # Check to make sure tensors are loaded if not S.in_mem: raise ValueError('tensor not in memory for calculating entanglement') # Create a copy of S S = S.copy() # Ensure correct normalization norm_fact = backend.dot(S,S.conj())**(1./2.)+1e-100 S /= norm_fact # Calc Entanglement Spectrum S += 1e-100 EEspec = -S*S.conj()*backend.log2(S*S.conj()) # Sum to get Entanglement Entropy EE = backend.sum(EEspec) # Return Results return EE,EEspec def qr_ten(ten,split_ind,rq=False,backend=np.linalg): """ Compute the QR Decomposition of an input tensor Args: ten : ctf or np array Array for which the svd will be done split_ind : int The dimension where the split into a matrix will be made Kwargs: rq : bool If True, then RQ decomposition will be done instead of QR decomposition Returns: Q : ctf or np array The resulting Q matrix R : ctf or np array The resulting R matrix """ mpiprint(9,'Performing qr on tensors') # Reshape tensor into matrix ten_shape = ten.shape mpiprint(9,'First, reshape the tensor into a matrix') _ten = ten.copy() _ten = _ten.reshape([int(np.prod(ten_shape[:split_ind])),int(np.prod(ten_shape[split_ind:]))]) # Perform svd mpiprint(9,'Perform actual qr') if not rq: # Do the QR Decomposition Q,R = backend.qr(_ten) # Reshape to match correct tensor format mpiprint(9,'Reshape to match original tensor dimensions') new_dims = ten_shape[:split_ind]+(int(np.prod(Q.shape)/np.prod(ten_shape[:split_ind])),) Q = Q.reshape(new_dims) new_dims = (int(np.prod(R.shape)/np.prod(ten_shape[split_ind:])),)+ten_shape[split_ind:] R = R.reshape(new_dims) # Quick check to see if it worked subscripts = LETTERS[:len(Q.shape)]+','+\ LETTERS[len(Q.shape)-1:len(Q.shape)-1+len(R.shape)]+'->'+\ LETTERS[:len(Q.shape)-1]+LETTERS[len(Q.shape):len(Q.shape)-1+len(R.shape)] #assert(np.allclose(ten,backend.einsum(subscripts,Q,R),rtol=1e-6)) else: raise NotImplementedError() # Return results if rq: return R,Q else: return Q,R def svd_ten(ten,split_ind,truncate_mbd=1e100,return_ent=True,return_wgt=True,backend=np.linalg): """ Compute the Singular Value Decomposition of an input tensor Args: ten : ctf or np array Array for which the svd will be done split_ind : int The dimension where the split into a matrix will be made Kwargs: return_ent : bool Whether or not to return the entanglement entropy and entanglement spectrum Default: True return_wgt : bool Whether or not to return the sum of the discarded weights. Default: True truncate_mbd : int The Maximum retained Bond Dimension Returns: U : ctf or np array The resulting U matrix from the svd S : ctf or np array The resulting singular values from the svd V : ctf or np array The resulting V matrix from the svd EE : float The von neumann entanglement entropy Only returned if return_ent == True EEs : 1D Array of floats The von neumann entanglement spectrum Only returned if return_ent == True wgt : float The sum of the discarded weigths Only returned if return_wgt == True """ mpiprint(8,'Performing svd on tensors') # Reshape tensor into matrix ten_shape = ten.shape mpiprint(9,'First, reshape the tensor into a matrix') ten = ten.reshape([int(np.prod(ten_shape[:split_ind])),int(np.prod(ten_shape[split_ind:]))]) # Perform svd mpiprint(9,'Perform actual svd') U,S,V = backend.svd(ten) # Compute Entanglement mpiprint(9,'Calculate the entanglment') if return_ent or return_wgt: EE,EEs = calc_entanglement(S,backend=backend) # Truncate results (if necessary) D = S.shape[0] # Make sure D is not larger than allowed if truncate_mbd is not None: D = int(min(D,truncate_mbd)) # Compute amount of S discarded wgt = S[D:].sum() # Truncate U,S,V mpiprint(9,'Limit tensor dimensions') U = U[:,:D] S = S[:D] S = backend.diag(S) V = V[:D,:] # Reshape to match correct tensor format mpiprint(9,'Reshape to match original tensor dimensions') new_dims = ten_shape[:split_ind]+(int(np.prod(U.shape)/np.prod(ten_shape[:split_ind])),) U = U.reshape(new_dims) new_dims = (int(np.prod(V.shape)/np.prod(ten_shape[split_ind:])),)+ten_shape[split_ind:] V = V.reshape(new_dims) # Print some results if return_ent or return_wgt: mpiprint(10,'Entanglement Entropy = {}'.format(EE)) mpiprint(12,'EE Spectrum = ') nEEs = EEs.shape[0] for i in range(nEEs): mpiprint(12,' {}'.format(EEs[i])) mpiprint(11,'Discarded weights = {}'.format(wgt)) # Return results if return_wgt and return_ent: return U,S,V,EE,EEs,wgt elif return_wgt: return U,S,V,wgt elif return_ent: return U,S,V,EE,EEs else: return U,S,V def eye(D,Z,is_symmetric=False,backend='numpy',dtype=float_,legs=None,in_mem=True): """ Create an identity tensor Args: D : int The size of each quantum number sector Z : int The number of quantum number sectors Kwargs: backend : str A string indicating the backend to be used for tensor creation and operations. Options include: 'ctf' - a ctf tensor 'numpy' - a numpy tensor dtype : dtype The data type for the tensor, i.e. np.float_,np.complex128,etc. in_mem : bool Whether the tensor should be initially stored in local memory (True) or written to disk (False). Default is True. """ if isinstance(backend,str): backend = load_lib(backend) if not is_symmetric: # Create a dense tensor ten = backend.eye(D,dtype=dtype) ten = GEN_TEN(ten=ten,backend=backend,legs=legs,in_mem=in_mem) return ten else: # Create a symmetric tensor sym = ['+-',[Z,Z],None,None] #if order == '+': # sym = ['+-',[Z,Z],None,None] #else: # sym = ['-+',[Z,Z],None,None] ten = GEN_TEN(shape=(D,D),sym=sym,backend=backend,dtype=dtype,legs=legs) for i in range(ten.ten.array.shape[0]): ten.ten.array[i,:,:] = backend.eye(ten.ten.array.shape[1]) # Write to disk if needed if not in_mem: ten.to_disk() # Return result return ten def rand(shape,sym=None,backend='numpy',dtype=float_,legs=None,in_mem=True): """ Create a random gen_ten tensor Args: shape : tuple The dimensions of each leg of the random tensor created Kwargs: sym : If None, then a non-symmetric tensor will be created (default). Otherwise, this will create a symmetric tensor. sym should be a list of length four with: sym[0] -> str of signs, i.e. '++--', for direction of symmetry arrows sym[1] -> list of ranges, i.e. [range(2)]*4, for number of sectors per tensor leg sym[2] -> integer, i.e. 0, for net value sym[3] -> integer, i.e. 2, for modulo values in the symmetry backend : str A string indicating the backend to be used for tensor creation and operations. Options include: 'ctf' - a ctf tensor 'numpy' - a numpy tensor dtype : dtype The data type for the tensor, i.e. np.float_,np.complex128,etc. in_mem : bool Whether the tensor should be initially stored in local memory (True) or written to disk (False). Default is True. """ if sym is not None: sym = [(sym[0]+',')[:-1],sym[1],sym[2],sym[3]] ten = GEN_TEN(shape=shape, sym=sym, backend=backend, dtype=dtype, legs=legs, in_mem=in_mem) ten.randomize() return ten def ones(shape,sym=None,backend='numpy',dtype=float_,legs=None,in_mem=True): """ Create a gen_ten tensor filled with ones Args: shape : tuple The dimensions of each leg of the random tensor created Kwargs: sym : If None, then a non-symmetric tensor will be created (default). Otherwise, this will create a symmetric tensor. sym should be a list of length four with: sym[0] -> str of signs, i.e. '++--', for direction of symmetry arrows sym[1] -> list of ranges, i.e. [range(2)]*4, for number of sectors per tensor leg sym[2] -> integer, i.e. 0, for net value sym[3] -> integer, i.e. 2, for modulo values in the symmetry backend : str A string indicating the backend to be used for tensor creation and operations. Options include: 'ctf' - a ctf tensor 'numpy' - a numpy tensor dtype : dtype The data type for the tensor, i.e. np.float_,np.complex128,etc. in_mem : bool Whether the tensor should be initially stored in local memory (True) or written to disk (False). Default is True. """ if sym is not None: sym = [(sym[0]+',')[:-1],sym[1],sym[2],sym[3]] ten = GEN_TEN(shape=shape, sym=sym, backend=backend, dtype=dtype, legs=legs, in_mem=in_mem) ten.fill_all(1.) return ten def zeros(shape,sym=None,backend='numpy',dtype=float_,legs=None,in_mem=True): """ Create a gen_ten tensor filled with zeros Args: shape : tuple The dimensions of each leg of the random tensor created Kwargs: sym : If None, then a non-symmetric tensor will be created (default). Otherwise, this will create a symmetric tensor. sym should be a list of length four with: sym[0] -> str of signs, i.e. '++--', for direction of symmetry arrows sym[1] -> list of ranges, i.e. [range(2)]*4, for number of sectors per tensor leg sym[2] -> integer, i.e. 0, for net value sym[3] -> integer, i.e. 2, for modulo values in the symmetry backend : str A string indicating the backend to be used for tensor creation and operations. Options include: 'ctf' - a ctf tensor 'numpy' - a numpy tensor dtype : dtype The data type for the tensor, i.e. np.float_,np.complex128,etc. in_mem : bool Whether the tensor should be initially stored in local memory (True) or written to disk (False). Default is True. """ if sym is not None: sym = [(sym[0]+',')[:-1],sym[1],sym[2],sym[3]] ten = GEN_TEN(shape=shape, sym=sym, backend=backend, dtype=dtype, legs=legs, in_mem=in_mem) ten.fill_all(0.) return ten def find_all(s,ch): """ Find all instances of a character in a string """ return [i for i, ltr in enumerate(s) if ltr == ch] LETTERS = 'abcdefghijklmnoprstuvwxyz' def replace_caps(subscripts): """ Replace all capital letters in a einsum subscript """ unique_chars = list(set(list(subscripts))) for i in range(len(unique_chars)): if (unique_chars[i].isupper()) or (unique_chars[i] == 'q'): # Find all instances of that character charinds = find_all(subscripts,unique_chars[i]) # find a letter to replace it for j in range(len(LETTERS)): if subscripts.find(LETTERS[j]) == -1: subscripts = subscripts.replace(unique_chars[i],LETTERS[j]) break elif j == 25: mpiprint(0,'There are no more strings left!') sys.exit() return subscripts def unmerge_subscripts(subscripts,Alegs,Blegs): """ When doing einsum with merged bonds, this will add additional subscripts for the legs that have been merged into one """ unique_chars = list(set(list(subscripts))) all_unique_chars = ''.join(list(set(list(subscripts)))) unique_chars.remove('-') unique_chars.remove('>') unique_chars.remove(',') [strin,strout] = subscripts.split('->') [strA,strB] = strin.split(',') _strA,_strB,_strout = strA,strB,strout for i in range(len(unique_chars)): # Find how many entries are in that tensor strA_locs = _strA.find(unique_chars[i]) strB_locs = _strB.find(unique_chars[i]) strout_locs = _strout.find(unique_chars[i]) if not (strA_locs == -1): nlegscomb = len(Alegs[strA_locs]) if not (strB_locs == -1): nlegscomb = len(Blegs[strB_locs]) if nlegscomb > 1: replacement_letters = unique_chars[i] for j in range(1,nlegscomb): for k in range(len(LETTERS)): if (all_unique_chars.find(LETTERS[k]) == -1): replacement_letters += LETTERS[k] all_unique_chars += LETTERS[k] break elif k == 25: mpiprint(0,'There are no more letters left!') sys.exit() if not (strA_locs == -1): strA = strA.replace(unique_chars[i],replacement_letters) if not (strB_locs == -1): strB = strB.replace(unique_chars[i],replacement_letters) if not (strout_locs == -1): strout = strout.replace(unique_chars[i],replacement_letters) subscripts = strA+','+strB+'->'+strout return subscripts def einsum(subscripts,opA,opB): """ An einsum for contraction between two general tensors. The only critical addition is the ability to deal with merged indices Args: indstr : string Specifies the subscripts for summation as comma separated list of subscript labels opA : array_like The first array for contraction opB : array_like The second array for contraction Returns: output : ndarray The resulting array from the einsum calculation """ # Check to make sure tensors are loaded if not opA.in_mem: raise ValueError('operator 1 not in memory for doing einsum') if not opB.in_mem: raise ValueError('operator 2 not in memory for doing einsum') # Format String ------------------------------------ _subscripts = subscripts subscripts = replace_caps(subscripts) subscripts = unmerge_subscripts(subscripts,opA.legs,opB.legs) # Do einsum try: res = opA.lib.einsum(subscripts,opA.ten,opB.ten) except Exception as e: if not (opA.lib == opB.lib): raise ValueError("Backends do not match for the two tensors") if opB.sym is None: print('{},{},{},{},{}'.format(subscripts,opA.ten.shape,opB.ten.shape,opA.lib,opB.lib)) else: print('{},{},{},{},{}'.format(subscripts,opA.ten.array.shape,opB.ten.array.shape,type(opA.ten.array),type(opB.ten.array))) res = opA.lib.einsum(subscripts,opA.ten,opB.ten) # Create a new gen_ten (with correctly lumped legs) from the result # Find resulting sym if opA.sym is not None: if hasattr(res,'sym'): sym = res.sym sym = [(sym[0]+',')[:-1],sym[1],sym[2],sym[3]] else: # Constant returned (don't need to put into gen_ten) sym = None #return res else: sym = None # Find resulting legs [strin,strout] = _subscripts.split('->') [strA,strB] = strin.split(',') legs = [] cnt = 0 for i in range(len(strout)): strA_loc = strA.find(strout[i]) strB_loc = strB.find(strout[i]) if not (strA_loc == -1): legs += [list(range(cnt,cnt+len(opA.legs[strA_loc])))] cnt += len(opA.legs[strA_loc]) else: legs += [list(range(cnt,cnt+len(opB.legs[strB_loc])))] cnt += len(opB.legs[strB_loc]) #print('\t\t\tcnt {}, legs {}'.format(cnt,legs)) if not isinstance(res,float): if len(subscripts.split('->')[1]) == 0: # If sized 1 array, convert to float ind = (0,)*len(res.shape) res = res[ind] else: res = GEN_TEN(sym = sym, backend = opA.backend, ten = res, legs = legs) return res ########################################################### # Object ########################################################### class GEN_TEN: """ A generic tensor class """ def __init__(self,shape=None,sym=None,backend='numpy',dtype=float_,ten=None,legs=None, writedir=TMPDIR+DIRID,writename=None,in_mem=True): """ Create a tensor of zeros of the correct tensor type Args: shape : tuple The dimensions of each tensor leg. Note, if using symtensors, the full dimension of each leg will be multiplied by the range of that leg, i.e. Zn Kwargs: backend : str A string indicating the backend to be used for tensor creation and operations. Options include: 'ctf' - a ctf tensor 'numpy' - a numpy tensor sym : bool If True, then a symtensor will be created, otherwise, the tensor will have no symmetry dtype : dtype The data type for the tensor, i.e. np.float_,np.complex128,etc. writedir : str The directory where the file will be written to on disk writename : str The filename where the tensor will be written to on disk in_mem : bool Whether the tensor should be initially stored in local memory (True) or written to disk (False). Default is True. """ # Load Backend if ten is None: self.backend = backend elif sym is None: self.backend = backend else: self.backend = ten.backend self.backend = load_lib(self.backend) # Set Tensor dtype if ten is None: self.dtype = dtype else: self.dtype = ten.dtype # Set Symmetry if sym is not None: self.sym = [(sym[0]+',')[:-1],sym[1],sym[2],sym[3]] else: self.sym = None # Set actual tensor if ten is None: # Create a zero tensor if sym is None: self.ten = self.lib.zeros(shape,dtype=dtype) else: if symlib is None: raise ImportError("Symtensor module not found") self.ten = symlib.zeros(shape,sym=sym,backend=backend,dtype=dtype) else: self.ten = ten try: sym = self.ten.sym self.sym = [(sym[0]+',')[:-1],sym[1],sym[2],sym[3]] except: self.sym = None pass # Create combined index if legs is None: self.legs = [[i] for i in range(self.ten.ndim)] else: self.legs = legs self.nlegs = len(self.legs) # Specify the save location and whether the file is saved or loaded if writename is None: writename = str(uuid.uuid1()) self.writedir = writedir self.saveloc = writedir + '/' + writename self.in_mem = True if not in_mem: self.to_disk() @property def ndim(self): return len(self.legs) @property def lib(self): if self.sym is None: return self.backend else: if symlib is None: raise ImportError("Symtensor module not found") return symlib @property def shape(self): if self.in_mem: return self.ten.shape else: if self.sym is None: return self._saved_shape else: return self._sym_saved_shape @property def full_shape(self): # Find full shape for tensors stored in memory if self.in_mem: # Return shape for dense tensor if self.sym is None: return self.ten.shape # Return shape for symtensor else: shape = list(self.ten.shape) for i in range(len(shape)): shape[i] *= len(self.ten.sym[1][i]) return tuple(shape) # Return saved shape for those not in memory else: return self._saved_shape @property def qn_sectors(self): if self.sym is None: return [range(1)]*len(self.shape) else: return self.sym[1] @property def is_symmetric(self): return (not (self.sym is None)) @property def is_ctf(self): if self.in_mem: if self.is_symmetric: return hasattr(self.ten.array,'write_to_file') else: return hasattr(self.ten,'write_to_file') else: return self._is_ctf def randomize(self): """ Fill the tensor with random elements """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation fill_all') # Replace current tensor values with random values self.ten[:] = 0. if self.sym is None: self.ten += self.backend.random(self.ten.shape) else: self.ten += self.backend.random(self.ten.array.shape) def fill_all(self,value): """ Fill the tensor with a given value """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation fill_all') # Set all tensor values to a single number self.ten[:] = 0. if self.sym is None: self.ten += value*self.backend.ones(self.ten.shape) else: self.ten += value*self.backend.ones(self.ten.array.shape) def make_sparse(self): """ Convert the symmetric tensor into a dense tensor (called make_sparse to match symtensor where sparse refers to a dense tensor filled with many zeros without symmetry, versus a densely stored symmetric tensor) """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation make_sparse') # Return a copy of self if already a full sparse tensor if not self.is_symmetric: return self.copy() # Convert symmetric tensor into a sparse (full dense) version of itself else: # Make a copy of the tensor newten = self.copy() # Convert the tensor to a sparse one nind = len(newten.ten.shape) newten.ten = newten.ten.make_sparse() newten.sym = None # Reshape the resulting sparse tensor order = [] newshape = [] shape = newten.ten.shape for i in range(nind): order += [i,nind+i] newshape += [shape[i]*shape[nind+i]] newten.ten = newten.ten.transpose(order) newten.ten = newten.ten.reshape(newshape) return newten def to_symmetric(self,sym): """ Conver the dense tensor to a symmetric one """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation to_symmetric') # Return a copy of self if already a symtensor if self.is_symmetric: return self.copy() # Convert the full dense (sparse in symtensor lang) to symmetric version else: # Create the new tensor newten = self.ten.copy() assert(len(sym[0]) == len(newten.shape)) # Convert the shape newshape = [] for i in range(len(newten.shape)): newshape.append(len(sym[1][i])) newshape.append(newten.shape[i]/len(sym[1][i])) newten = newten.reshape(newshape) # Do a transpose on the indices order = [] for i in range(len(sym[1])): order.append(2*i) for i in range(len(sym[1])): order.append(2*i+1) newten = newten.transpose(order) # Create a random symtensor newsymten = rand(newten.shape[len(sym[1]):], sym=sym, backend=self.backend, dtype=self.dtype, legs=self.legs, in_mem=self.in_mem) # Contract with delta to get dense irrep delta = newsymten.ten.get_irrep_map() einstr = LETTERS[:len(sym[1])].upper() + \ LETTERS[:len(sym[1])] + ',' + \ LETTERS[:len(sym[1])].upper() + '->' + \ LETTERS[:len(sym[1])-1].upper() + \ LETTERS[:len(sym[1])] newten = newsymten.backend.einsum(einstr,newten,delta) # Put the result into a symtensor newsymten.ten.array = newten # Return result return newsymten def copy(self): """ Return a copy of the gen_ten object """ # Get a copy of a tensor in memory if self.in_mem: newten = self._as_new_tensor(self.ten.copy()) # Get a copy of tensors written to disk else: # Create a new GEN_TEN object with a symtensor array if self.sym: newten = GEN_TEN(shape = self._sym_saved_shape, backend = self.backend, legs = copy.deepcopy(self.legs), dtype = self.dtype, writedir = self.writedir, sym = self.sym, in_mem = False) # Ensure it is written to disk # Create a new GEN_TEN object with dense random array else: newten = GEN_TEN(shape = self._saved_shape, backend = self.backend, legs = copy.deepcopy(self.legs), dtype = self.dtype, writedir = self.writedir, in_mem=False) # Ensure it is written to disk # Copy the saved tensors try: _copyfile(self.saveloc,newten.saveloc) except: _copyfile(self.saveloc+'.npy',newten.saveloc+'.npy') # Update saved values newten._max_val = self._max_val newten._min_val = self._min_val newten._mult_fact = self._mult_fact newten._saved_shape = self._saved_shape newten._sym_saved_shape = self._sym_saved_shape # Return result return newten def _as_new_tensor(self,ten): newten = GEN_TEN(ten=ten.copy(), backend=self.backend, legs=copy.deepcopy(self.legs)) return newten def __str__(self): # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation __str__') # Return result if self.sym: return self.ten.array.__str__() else: return self.ten.__str__() def transpose(self,axes): """ Transpose the tensor """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation transpose') # Get actual transpose indices _axes = [self.legs[i] for i in axes] _axes = list(itertools.chain(*_axes)) newten = self.ten.transpose(*_axes) # Update legs newlegs = [] ind = 0 for i in range(len(axes)): newlegs.append(list(range(ind,ind+len(self.legs[axes[i]])))) ind += len(self.legs[axes[i]]) # Return new gen ten instance return GEN_TEN(ten=newten,backend=self.backend,legs=newlegs) def remove_empty_ind(self,ind): """ Remove an index of size 1 """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation remove_empty_ind') # Get initial tensor shape init_shape = self.ten.shape # Check that we are summing over only one index for i in range(len(self.legs[ind])): assert(init_shape[self.legs[ind][i]] == 1) # Separate cases for tensors with and without symmetry if self.sym is None: # Sum over the single index for tensor without symmetry newten = self.ten.copy() for i in range(len(self.legs[ind]))[::-1]: newten = newten.sum(self.legs[ind][i]) else: # More complex for symtensors sym = self.sym # Special case when ind is not stored in dense tensor if ind == len(self.legs)-1: # Number of indices to be removed ntrunc = len(self.legs[-1]) # Transpose tensor (so removed inds are in fromt neworder = [self.legs[ind]]+self.legs[0:ind] neworder = [item for sublist in neworder for item in sublist] newten = self.ten.copy() newten = newten.transpose(*neworder) newten = newten.array.copy() for i in range(ntrunc): assert(newten.shape[i+len(sym[0])-1] == 1) # Sum over correct legs for i in range(ntrunc): newten = newten.sum(i+len(sym[0])-1) for i in range(ntrunc): newten = newten.sum(i) # Adjust Symmetry Specifications sym[0] = (sym[0]+'.')[:-1] sym[0] = sym[0][:self.legs[ind][0]]+sym[0][self.legs[ind][-1]+1:] sym[1] = sym[1][:self.legs[ind][0]]+sym[1][self.legs[ind][-1]+1:] # Create the correct symtensor if symlib is None: raise ImportError("Symtensor module not found") newten = symlib.SYMtensor(newten, sym=[(self.sym[0]+'.')[:-1], self.sym[1], self.sym[2], self.sym[3]], backend=self.backend) # General case for remaining tensor legs that are stored else: # Copy tensor newten = self.ten.array.copy() for i in range(len(self.legs[ind])): assert(newten.shape[self.legs[ind][i]+len(sym[0])-1] == 1) # Sum over correct legs for i in range(len(self.legs[ind]))[::-1]: newten = newten.sum(self.legs[ind][i]+len(sym[0])-1) for i in range(len(self.legs[ind]))[::-1]: newten = newten.sum(self.legs[ind][i]) # Adjust symmetry specifications sym[0] = (sym[0]+'.')[:-1] sym[0] = sym[0][:self.legs[ind][0]]+sym[0][self.legs[ind][-1]+1:] sym[1] = sym[1][:self.legs[ind][0]]+sym[1][self.legs[ind][-1]+1:] # Create the correct symtensor if symlib is None: raise ImportError("Symtensor module not found") newten = symlib.SYMtensor(newten, sym=[(self.sym[0]+'.')[:-1], self.sym[1], self.sym[2], self.sym[3]], backend=self.backend) # Update legs newlegs = [] cnt = 0 for i in range(len(self.legs)): if not (i == ind): newlegs += [list(range(cnt,cnt+len(self.legs[i])))] cnt += len(self.legs[i]) # Convert to gen tensor and return return GEN_TEN(ten=newten,backend=self.backend,legs=newlegs) def merge_inds(self,combinds): """ Lump multiple indices of a tensor into a single index # Note that we can only combine nearest neighbor indices # Note also, we are not doing any actual tensor manipulation, i.e. reshaping, etc. """ # Make sure we are only combining nearest neighbor indices for i in range(len(combinds)-1): assert(combinds[i+1]-combinds[i]==1) # Legs that are not affected by merging newlegs = [] for i in range(combinds[0]): newlegs.append(self.legs[i]) # Add the merged legs all_comb_inds = [] for j in range(len(combinds)): all_comb_inds += self.legs[combinds[j]] newlegs.append(all_comb_inds) # Add the rest of the unaffected legs for i in range(combinds[-1]+1,len(self.legs)): newlegs.append(self.legs[i]) # Actually change legs self.legs = newlegs def unmerge_ind(self,ind): """ Unlump a single index of a tensor into its component indices # Note also, we are not doing any actual tensor manipulation, i.e. reshaping, etc. """ # Legs that are not affected by merging newlegs = [] cnt = 0 for i in range(ind): newlegs.append(self.legs[i]) cnt += len(self.legs[i]) # Add the unmerged legs for i in range(len(self.legs[ind])): newlegs.append([cnt]) cnt += 1 # Add the rest of the unaffected legs for i in range(ind+1,len(self.legs)): newlegs.append(list(range(cnt,cnt+len(self.legs[i])))) cnt += len(self.legs[i]) # Actually change legs self.legs = newlegs def qr(self,split): """ Returns the Q and R from a qr decomposition of the tensor """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation qr') # Figure out how legs will be split leg_split = split split = self.legs[split][0] # Do qr on non-symmetric tensor if self.sym is None: Q,R = qr_ten(self.ten,split,backend=self.backend) # Do qr on symtensor else: Q,R = symqr(self.ten,[list(range(split)),list(range(split,self.ten.ndim))]) # Convert Q & R back to gen_tens Q = GEN_TEN(ten=Q,backend=self.backend) R = GEN_TEN(ten=R,backend=self.backend) # Update Q legs Qlegs = [] cnt = 0 for i in range(leg_split): Qlegs += [list(range(cnt,cnt+len(self.legs[i])))] cnt += len(self.legs[i]) Qlegs += [[cnt]] Q.legs = Qlegs # Update R legs Rlegs = [[0]] cnt = 1 for i in range(leg_split,len(self.legs)): Rlegs += [list(range(cnt,cnt+len(self.legs[i])))] cnt += len(self.legs[i]) R.legs = Rlegs # Return result return Q,R def svd(self,split,truncate_mbd=1e100,return_ent=True,return_wgt=True): """ Returns the U,S, and V from an svd of the tensor """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation svd') # Figure out how legs will be split leg_split = split split = self.legs[split][0] # Do svd on dense tensor directly if self.sym is None: res = svd_ten(self.ten, split, backend=self.backend, truncate_mbd=truncate_mbd, return_ent=return_ent, return_wgt=return_wgt) # Do SVD on symtensor else: res = symsvd(self.ten, [list(range(split)),list(range(split,self.ten.ndim))], truncate_mbd=truncate_mbd, return_ent=return_ent, return_wgt=return_wgt) # Put results into GEN_TENs U,S,V = res[0],res[1],res[2] U = GEN_TEN(ten=U,backend=self.backend) S = GEN_TEN(ten=S,backend=self.backend) V = GEN_TEN(ten=V,backend=self.backend) # Update U legs Ulegs = [] cnt = 0 for i in range(leg_split): Ulegs += [list(range(cnt,cnt+len(self.legs[i])))] cnt += len(self.legs[i]) Ulegs += [[cnt]] U.legs = Ulegs # Update V legs Vlegs = [[0]] cnt = 1 for i in range(leg_split,len(self.legs)): Vlegs += [list(range(cnt,cnt+len(self.legs[i])))] cnt += len(self.legs[i]) V.legs = Vlegs # Bundle results ret = (U,S,V) for i in range(3,len(res)): ret += (res[i],) return ret def update_signs(self,signs): """ Change the signs of the symtensors """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation flip_signs') # Change signs for symtensor if self.sym is not None: self.sym[0] = signs self.ten.sym[0] = signs def get_signs(self): """ Change the signs of the symtensors """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation flip_signs') # Return result for symtensor if self.sym is not None: return self.sym[0] # Return None for dense tensor else: return None def flip_signs(self): """ Flip all the signs of a symtensor """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation flip_signs') # Do the operation if self.sym is not None: self.sym[0] = ''.join(FLIP[i] for i in self.sym[0]) self.ten.sym[0] = ''.join(FLIP[i] for i in self.ten.sym[0]) def conj(self): # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation conj') # Return result as a new tensor return self._as_new_tensor(self.ten.conj()) def sqrt(self): # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation sqrt') # Do operation for dense tensor if self.sym is not None: return self._as_new_tensor(self.ten**(1./2.)) # Do operation for symtensor else: return self._as_new_tensor(self.ten**(1./2.)) def abs(self): # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation abs') # Return result as a new tensor return self._as_new_tensor(abs(self.ten)) def sum(self): # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation sum') # Do operation for dense tensor if self.sym is None: einstr = 'abcdefghijklmnopqrstuvwxyz'[:len(self.ten.shape)]+'->' res = self.backend.einsum(einstr,self.ten) # Do operation for symtensor else: einstr = 'abcdefghijklmnopqrstuvwxyz'[:len(self.ten.array.shape)]+'->' res = self.backend.einsum(einstr,self.ten.array) # Return result return res def max(self): # Find result for tensor stored in memory if self.in_mem: # Find result for dense tensor if self.sym is None: maxval = self.backend.max(self.ten) # Find result for symtensor else: maxval = self.backend.max(self.ten.array) # Find result for tensor not in memory else: maxval = self._max_val # Return the result return float(maxval) def min(self): # Find result for tensor stored in memory if self.in_mem: # Find result for dense tensor if self.sym is None: minval = self.backend.min(self.ten) # Find result for symtensor else: minval = self.backend.min(self.ten.array) # Find result for tensor not in memory else: minval = self._min_val # Return the result return float(minval) def max_abs(self): """ Returns the maximum of the absolute value of the tensor """ # Find result for tensor stored in memory if self.in_mem: # Find result for Dense tensor if self.sym is None: maxval = max(self.backend.max(self.ten),self.backend.min(self.ten)) # Find result for symtensor else: maxval = max(self.backend.max(self.ten.array),self.backend.min(self.ten.array)) # Find result for tensor not in memory else: maxval = max(self._max_val, self._min_val, key=abs) # Return result return float(maxval) def to_val(self): """ Returns a single valued tensor's value """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation to_val') # Collect the tensor and einsum function if self.sym is not None: tmp = self.ten.array es = self.ten.lib.einsum else: tmp = self.ten es = self.lib.einsum # Repeatedly sum over all indices until we return the result while True: if len(tmp.shape) > 26: tmp = es('abcdefghijklmnopqrstuvwxyz...->...',tmp) else: return es('abcdefghijklmnopqrstuvwxyz'[:len(tmp.shape)]+'->',tmp) def __mul__(self,x): # Actually multiply tensor if in memory if self.in_mem: return self._as_new_tensor(self.ten*x) # Keep constant factor if not in memory else: # Copy the gen_ten newten = self.copy() # Multiply to track the appropriate factor newten.update_mult_fact(1./x) return newten def __rmul__(self,x): return self*x def __neg__(self): return self * (-1.) def __div__(self,x): return self * (1./x) def __truediv__(self,x): return self * (1./x) def __truediv__(self,x): return self * (1./x) def __floordiv__(self,x): raise NotImplementedError('Floordiv not defined for gen_ten arrays') def __rdiv__(self,x): return self * (1./x) def __rtruediv__(self,x): return self * (1./x) def update_mult_fact(self,val): """ If tensor is not in memory, then the multiplication factor is updated """ # Throw error if tensor is loaded if self.in_mem: raise ValueError('Cannot update mult factor for tensor in memory') # Update all params self._mult_fact *= val self._max_val *= val self._min_val *= val def __rfloordiv__(self,x): raise NotImplementedError('Floordiv not defined for gen_ten arrays') def __add__(self,x): # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation __add__') # Write to a new tensor if both tensors are GEN_TENs if isinstance(x,GEN_TEN): return self._as_new_tensor(self.ten+x.ten) # Write to a new tensor if other tensors not GEN_TEN else: return self._as_new_tensor(self.ten+x) def __radd__(self,x): # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation __radd__') # Write to a new tensor if both tensors are GEN_TENs if isinstance(x,GEN_TEN): return self._as_new_tensor(self.ten+x.ten) # Write to a new tensor if other tensors not GEN_TEN else: return self._as_new_tensor(self.ten+x) def __sub__(self,x): # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for operation __sub__') # Write to a new tensor if both tensors are GEN_TENs if isinstance(x,GEN_TEN): return self._as_new_tensor(self.ten-x.ten) # Write to a new tensor if other tensors not GEN_TEN else: return self._as_new_tensor(self.tem-x) def __setitem__(self, key, value): # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for setting item') # Set item for symtensor if self.sym: self.ten.array[key] = value # Set item for standard tensor else: self.ten[key] = value def invert_diag(self): # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for doing invert_diag') # Copy tensor temporarilly newten = self._as_new_tensor(self.ten) # Do Dense tensor if newten.sym is None: assert(len(self.ten.shape) == 2) newten.ten = self.backend.diag(1./self.backend.diag(newten.ten)) # Do sparse tensor else: assert(len(self.ten.array.shape) == 3) for i in range(self.ten.array.shape[0]): newten.ten.array[i] = self.backend.diag(1./self.backend.diag(newten.ten.array[i])) # Return result return newten def square_inv(self, use_full=False, rcond=1e-15): """ Take the inverse of a 'square' tensor, used in ALS for PEPS Full Update """ # Throw error if tensor is not loaded if not self.in_mem: raise ValueError('GEN_TEN not in memory for doing square inverse') # Copy tensor temporarily newten = self._as_new_tensor(self.ten) # Do dense tensor inverse if newten.sym is None: init_shape = self.ten.shape nleg = len(init_shape) assert(nleg%2==0) left_size, right_size = np.prod(init_shape[:int(nleg/2)]), np.prod(init_shape[int(nleg/2):]) mat = self.backend.reshape(self.ten,(left_size,right_size)) inv = self.backend.pinv(mat) newten.ten = self.backend.reshape(inv,init_shape) # Do sparse tensor inverse else: # Ensure the tensor is square nleg = len(self.legs) nleg_2 = int(nleg/2) assert(nleg%2 == 0) if use_full: # Convert to a sparse tensor, then use pinv # function to find inverse # Convert symtensor into full tensor mat = self.ten.make_sparse() # Convert into a matrix tenshape = mat.shape order = [] matshape = [1,1] for i in range(nleg): order += [i,i+nleg] if i < int(nleg/2): matshape[0] *= tenshape[i]*tenshape[i+nleg] else: matshape[1] *= tenshape[i]*tenshape[i+nleg] mat = mat.transpose(order) tenshape = mat.shape mat = mat.reshape(matshape) # Take Inverse inv = self.backend.pinv(mat) # Convert back into a tensor inv = inv.reshape(tenshape) order = [] for i in range(nleg): order += [2*i] for i in range(nleg): order += [2*i+1] inv = inv.transpose(order) # Convert back into a symtensor delta = self.ten.get_irrep_map() einstr = LETTERS[:nleg].upper()+LETTERS[:nleg].lower() + ',' + \ LETTERS[:nleg].upper() + '->' + \ LETTERS[:nleg-1].upper()+LETTERS[:nleg].lower() inv = self.backend.einsum(einstr, inv, delta) newten.ten.array = inv else: # Do a self-implemented pinv function to find # pseudo inverse without using dense tensors # Take the conjugate (in case complex) a = self.conj() # Do the SVD of the tensor U,S,V = a.svd(nleg_2, truncate_mbd=None, return_ent=False, return_wgt=False) # Determine the cutoff value cutoff = rcond * S.max() # Invert S if S.is_ctf: tmpS = S.ten.array.copy().to_nparray() large = tmpS > cutoff tmpS = np.divide(1., tmpS, where=large, out=tmpS) tmpS[~large] = 0 if S.is_ctf: tmpS = ctf.from_nparray(tmpS) S.ten.array = tmpS # Contract to get the inverse einstr = LETTERS[:nleg_2+1] + ',' + \ LETTERS[nleg_2:nleg_2+2] + '->' + \ LETTERS[:nleg_2]+LETTERS[nleg_2+1] inv = einsum(einstr,U,S) einstr = LETTERS[:nleg_2+1] + ',' + \ LETTERS[nleg_2:nleg+1] + '->' + \ LETTERS[:nleg_2]+LETTERS[nleg_2+1:nleg+1] inv = einsum(einstr,inv,V) newten.ten.array = inv.ten.array # Return result return newten def to_disk(self): """ Write the actual gen_ten tensor to disk in location specified by gen_ten.saveloc """ # Only need to write if currently in memory if self.in_mem: # Save some useful information self._max_val = self.max() self._min_val = self.min() self._mult_fact = 1. # Actually write to disk if self.sym is None: self._sym_saved_shape = None self._saved_shape = self.ten.shape # Write ctf tensor if hasattr(self.ten,'write_to_file'): self.ten.write_to_file(self.saveloc) self._is_ctf = True # Write Numpy Tensor else: self.backend.save(self.saveloc,self.ten) self._is_ctf = False # Overwrite tensor with None self.ten = None else: self._sym_saved_shape = self.ten.shape self._saved_shape = self.ten.array.shape # Write ctf tensor if hasattr(self.ten.array,'write_to_file'): self.ten.array.write_to_file(self.saveloc) self._is_ctf = True # Write numpy tensor else: self.backend.save(self.saveloc,self.ten.array) self._is_ctf = False # Overwrite tensor with None self.ten.array = None # Switch flag to indicate no longer stored in memory self.in_mem = False def from_disk(self): """ Read the gen_ten tensor from disk, where it has been previously saved in the location specified by gen_ten.saveloc """ # Only need to load if not already in memory if not self.in_mem: # Load the tensor if self.sym is None: # Load ctf tensor if self._is_ctf:#hasattr(self.ten,'write_to_file'): self.ten = self.backend.zeros(self._saved_shape) self.ten.read_from_file(self.saveloc) # Load numpy tensor else: self.ten = self.backend.load(self.saveloc + '.npy') # Multiply by factor self.ten *= self._mult_fact else: # Load ctf tensor if self._is_ctf:#hasattr(self.ten.array,'write_to_file'): self.ten.array = self.backend.zeros(self._saved_shape) self.ten.array.read_from_file(self.saveloc) # Load Numpy tensor else: self.ten.array = self.backend.load(self.saveloc + '.npy') # Switch flag to indicate stored in memory self.in_mem = True # Overwrite the "useful info" saved with tensor self._min_val = None self._max_val = None self._mult_fact = None self._saved_shape = None self._sym_saved_shape = None
[ "itertools.chain", "numpy.prod", "sys.exit", "symtensor.sym.SYMtensor", "symtensor.sym.zeros", "uuid.uuid1", "ctf.from_nparray", "shutil.copyfile", "copy.deepcopy", "numpy.divide" ]
[((30175, 30198), 'itertools.chain', 'itertools.chain', (['*_axes'], {}), '(*_axes)\n', (30190, 30198), False, 'import itertools\n'), ((2336, 2366), 'numpy.prod', 'np.prod', (['ten_shape[:split_ind]'], {}), '(ten_shape[:split_ind])\n', (2343, 2366), True, 'import numpy as np\n'), ((2372, 2402), 'numpy.prod', 'np.prod', (['ten_shape[split_ind:]'], {}), '(ten_shape[split_ind:])\n', (2379, 2402), True, 'import numpy as np\n'), ((4920, 4950), 'numpy.prod', 'np.prod', (['ten_shape[:split_ind]'], {}), '(ten_shape[:split_ind])\n', (4927, 4950), True, 'import numpy as np\n'), ((4956, 4986), 'numpy.prod', 'np.prod', (['ten_shape[split_ind:]'], {}), '(ten_shape[split_ind:])\n', (4963, 4986), True, 'import numpy as np\n'), ((20805, 20863), 'symtensor.sym.zeros', 'symlib.zeros', (['shape'], {'sym': 'sym', 'backend': 'backend', 'dtype': 'dtype'}), '(shape, sym=sym, backend=backend, dtype=dtype)\n', (20817, 20863), True, 'import symtensor.sym as symlib\n'), ((21435, 21447), 'uuid.uuid1', 'uuid.uuid1', ([], {}), '()\n', (21445, 21447), False, 'import uuid\n'), ((28866, 28905), 'shutil.copyfile', '_copyfile', (['self.saveloc', 'newten.saveloc'], {}), '(self.saveloc, newten.saveloc)\n', (28875, 28905), True, 'from shutil import copyfile as _copyfile\n'), ((29489, 29513), 'copy.deepcopy', 'copy.deepcopy', (['self.legs'], {}), '(self.legs)\n', (29502, 29513), False, 'import copy\n'), ((32713, 32835), 'symtensor.sym.SYMtensor', 'symlib.SYMtensor', (['newten'], {'sym': "[(self.sym[0] + '.')[:-1], self.sym[1], self.sym[2], self.sym[3]]", 'backend': 'self.backend'}), "(newten, sym=[(self.sym[0] + '.')[:-1], self.sym[1], self.\n sym[2], self.sym[3]], backend=self.backend)\n", (32729, 32835), True, 'import symtensor.sym as symlib\n'), ((34056, 34178), 'symtensor.sym.SYMtensor', 'symlib.SYMtensor', (['newten'], {'sym': "[(self.sym[0] + '.')[:-1], self.sym[1], self.sym[2], self.sym[3]]", 'backend': 'self.backend'}), "(newten, sym=[(self.sym[0] + '.')[:-1], self.sym[1], self.\n sym[2], self.sym[3]], backend=self.backend)\n", (34072, 34178), True, 'import symtensor.sym as symlib\n'), ((51965, 52008), 'numpy.divide', 'np.divide', (['(1.0)', 'tmpS'], {'where': 'large', 'out': 'tmpS'}), '(1.0, tmpS, where=large, out=tmpS)\n', (51974, 52008), True, 'import numpy as np\n'), ((5751, 5767), 'numpy.prod', 'np.prod', (['U.shape'], {}), '(U.shape)\n', (5758, 5767), True, 'import numpy as np\n'), ((5768, 5798), 'numpy.prod', 'np.prod', (['ten_shape[:split_ind]'], {}), '(ten_shape[:split_ind])\n', (5775, 5798), True, 'import numpy as np\n'), ((5850, 5866), 'numpy.prod', 'np.prod', (['V.shape'], {}), '(V.shape)\n', (5857, 5866), True, 'import numpy as np\n'), ((5867, 5897), 'numpy.prod', 'np.prod', (['ten_shape[split_ind:]'], {}), '(ten_shape[split_ind:])\n', (5874, 5897), True, 'import numpy as np\n'), ((28941, 28998), 'shutil.copyfile', '_copyfile', (["(self.saveloc + '.npy')", "(newten.saveloc + '.npy')"], {}), "(self.saveloc + '.npy', newten.saveloc + '.npy')\n", (28950, 28998), True, 'from shutil import copyfile as _copyfile\n'), ((52097, 52119), 'ctf.from_nparray', 'ctf.from_nparray', (['tmpS'], {}), '(tmpS)\n', (52113, 52119), False, 'import ctf\n'), ((2703, 2719), 'numpy.prod', 'np.prod', (['Q.shape'], {}), '(Q.shape)\n', (2710, 2719), True, 'import numpy as np\n'), ((2720, 2750), 'numpy.prod', 'np.prod', (['ten_shape[:split_ind]'], {}), '(ten_shape[:split_ind])\n', (2727, 2750), True, 'import numpy as np\n'), ((2810, 2826), 'numpy.prod', 'np.prod', (['R.shape'], {}), '(R.shape)\n', (2817, 2826), True, 'import numpy as np\n'), ((2827, 2857), 'numpy.prod', 'np.prod', (['ten_shape[split_ind:]'], {}), '(ten_shape[split_ind:])\n', (2834, 2857), True, 'import numpy as np\n'), ((13651, 13661), 'sys.exit', 'sys.exit', ([], {}), '()\n', (13659, 13661), False, 'import sys\n'), ((28070, 28094), 'copy.deepcopy', 'copy.deepcopy', (['self.legs'], {}), '(self.legs)\n', (28083, 28094), False, 'import copy\n'), ((28579, 28603), 'copy.deepcopy', 'copy.deepcopy', (['self.legs'], {}), '(self.legs)\n', (28592, 28603), False, 'import copy\n'), ((15089, 15099), 'sys.exit', 'sys.exit', ([], {}), '()\n', (15097, 15099), False, 'import sys\n')]
import itertools from collections import defaultdict import numpy as np from g2o import SE3Quat, CameraParameters from map_processing.as_graph import matrix2measurement, se3_quat_average from map_processing import graph def as_graph(dct, fix_tag_vertices=False): """Convert a dictionary decoded from JSON into a graph. Args: dct (dict): The dictionary to convert to a graph. Returns: A graph derived from the input dictionary. """ pose_data = np.array(dct['pose_data']) if not pose_data.size: pose_data = np.zeros((0, 18)) pose_matrices = pose_data[:, :16].reshape(-1, 4, 4).transpose(0, 2, 1) odom_vertex_estimates = matrix2measurement(pose_matrices, invert=True) tag_size = 0.173 # TODO: need to send this with the tag detection true_3d_points = np.array( [[-tag_size / 2, -tag_size / 2, 1], [tag_size / 2, -tag_size / 2, 1], [tag_size / 2, tag_size / 2, 1], [-tag_size / 2, tag_size / 2, 1]]) true_3d_tag_center = np.array([0, 0, 1]) # The camera axis used to get tag measurements are flipped # relative to the phone frame used for odom measurements camera_to_odom_transform = np.array([ [1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1] ]) # flatten the data into individual numpy arrays that we can operate on if 'tag_data' in dct and len(dct['tag_data']) > 0: tag_pose_flat = np.vstack([[x['tagPose'] for x in tagsFromFrame] for tagsFromFrame in dct['tag_data']]) camera_intrinsics_for_tag = np.vstack([[x['cameraIntrinsics'] for x in tagsFromFrame] for tagsFromFrame in \ dct['tag_data']]) tag_corners = np.vstack([[x['tagCornersPixelCoordinates'] for x in tagsFromFrame] for tagsFromFrame in \ dct['tag_data']]) tag_ids = np.vstack(list(itertools.chain(*[[x['tagId'] for x in tagsFromFrame] for tagsFromFrame in \ dct['tag_data']]))) pose_ids = np.vstack(list(itertools.chain(*[[x['poseId'] for x in tagsFromFrame] for tagsFromFrame in \ dct['tag_data']]))) else: tag_pose_flat = np.zeros((0, 16)) camera_intrinsics_for_tag = np.zeros((0, 4)) tag_corners = np.zeros((0, 8)) tag_ids = np.zeros((0, 1), dtype=np.int) pose_ids = np.zeros((0, 1), dtype=np.int) tag_edge_measurements_matrix = np.matmul( camera_to_odom_transform, tag_pose_flat.reshape(-1, 4, 4)) tag_edge_measurements = matrix2measurement(tag_edge_measurements_matrix) unique_tag_ids = np.unique(tag_ids) tag_vertex_id_by_tag_id = dict( zip(unique_tag_ids, range(0, unique_tag_ids.size * 5, 5))) tag_id_by_tag_vertex_id = dict(zip(tag_vertex_id_by_tag_id.values(), tag_vertex_id_by_tag_id.keys())) tag_corner_ids_by_tag_vertex_id = dict( zip(tag_id_by_tag_vertex_id.keys(), map(lambda tag_vertex_id: list(range(tag_vertex_id + 1, tag_vertex_id + 5)), tag_id_by_tag_vertex_id.keys()))) # Enable lookup of tags by the frame they appear in tag_vertex_id_and_index_by_frame_id = {} for tag_index, (tag_id, tag_frame) in enumerate(np.hstack((tag_ids, pose_ids))): tag_vertex_id = tag_vertex_id_by_tag_id[tag_id] tag_vertex_id_and_index_by_frame_id[tag_frame] = tag_vertex_id_and_index_by_frame_id.get( tag_frame, []) tag_vertex_id_and_index_by_frame_id[tag_frame].append( (tag_vertex_id, tag_index)) waypoint_list_uniform = list(map(lambda x: np.asarray(x[:-1]).reshape((-1, 18)), dct.get('location_data', []))) waypoint_names = list(map(lambda x: x[-1], dct.get('location_data', []))) unique_waypoint_names = np.unique(waypoint_names) if waypoint_list_uniform: waypoint_data_uniform = np.concatenate(waypoint_list_uniform) else: waypoint_data_uniform = np.zeros((0, 18)) waypoint_edge_measurements_matrix = waypoint_data_uniform[:, :16].reshape(-1, 4, 4) waypoint_edge_measurements = matrix2measurement(waypoint_edge_measurements_matrix) waypoint_vertex_id_by_name = dict( zip(unique_waypoint_names, range(unique_tag_ids.size * 5, unique_tag_ids.size * 5 + unique_waypoint_names.size))) waypoint_name_by_vertex_id = dict(zip(waypoint_vertex_id_by_name.values(), waypoint_vertex_id_by_name.keys())) # Enable lookup of waypoints by the frame they appear in waypoint_vertex_id_and_index_by_frame_id = {} for waypoint_index, (waypoint_name, waypoint_frame) in enumerate(zip(waypoint_names, waypoint_data_uniform[:, 17])): waypoint_vertex_id = waypoint_vertex_id_by_name[waypoint_name] waypoint_vertex_id_and_index_by_frame_id[waypoint_frame] = waypoint_vertex_id_and_index_by_frame_id.get( waypoint_name, []) waypoint_vertex_id_and_index_by_frame_id[waypoint_frame].append( (waypoint_vertex_id, waypoint_index)) # Construct the dictionaries of vertices and edges vertices = {} edges = {} vertex_counter = unique_tag_ids.size * 5 + unique_waypoint_names.size edge_counter = 0 previous_vertex = None counted_tag_vertex_ids = set() counted_waypoint_vertex_ids = set() first_odom_processed = False num_tag_edges = 0 # DEBUG: this appears to be counterproductive initialize_with_averages = False tag_transform_estimates = defaultdict(lambda: []) for i, odom_frame in enumerate(pose_data[:, 17]): current_odom_vertex_uid = vertex_counter vertices[current_odom_vertex_uid] = graph.Vertex( mode=graph.VertexType.ODOMETRY, estimate=odom_vertex_estimates[i], fixed=not first_odom_processed, meta_data={'poseId': odom_frame} ) first_odom_processed = True vertex_counter += 1 # Connect odom to tag vertex for tag_vertex_id, tag_index in tag_vertex_id_and_index_by_frame_id.get(int(odom_frame), []): current_tag_transform_estimate = SE3Quat(np.hstack((true_3d_tag_center, [0, 0, 0, 1]))) * SE3Quat( tag_edge_measurements[tag_index]).inverse() * SE3Quat(vertices[current_odom_vertex_uid].estimate) # keep track of estimates in case we want to average them to initialize the graph tag_transform_estimates[tag_vertex_id].append(current_tag_transform_estimate) if tag_vertex_id not in counted_tag_vertex_ids: vertices[tag_vertex_id] = graph.Vertex( mode=graph.VertexType.TAG, estimate=current_tag_transform_estimate.to_vector(), fixed=fix_tag_vertices ) vertices[tag_vertex_id].meta_data['tag_id'] = tag_id_by_tag_vertex_id[tag_vertex_id] for idx, true_point_3d in enumerate(true_3d_points): vertices[tag_corner_ids_by_tag_vertex_id[tag_vertex_id][idx]] = graph.Vertex( mode=graph.VertexType.TAGPOINT, estimate=np.hstack((true_point_3d, [0, 0, 0, 1])), fixed=True ) counted_tag_vertex_ids.add(tag_vertex_id) # adjust the x-coordinates of the detections to account for differences in coordinate systems induced by # the camera_to_odom_transform tag_corners[tag_index][::2] = 2 * camera_intrinsics_for_tag[tag_index][2] - tag_corners[tag_index][::2] # TODO: create proper subclasses for k, point in enumerate(true_3d_points): point_in_camera_frame = SE3Quat(tag_edge_measurements[tag_index]) * (point - np.array([0, 0, 1])) cam = CameraParameters(camera_intrinsics_for_tag[tag_index][0], camera_intrinsics_for_tag[tag_index][2:], 0) # print("chi2", np.sum(np.square(tag_corners[tag_index][2*k : 2*k + 2] - # cam.cam_map(point_in_camera_frame)))) edges[edge_counter] = graph.Edge( startuid=current_odom_vertex_uid, enduid=tag_vertex_id, corner_ids=tag_corner_ids_by_tag_vertex_id[tag_vertex_id], information=np.eye(2), information_prescaling=None, camera_intrinsics=camera_intrinsics_for_tag[tag_index], measurement=tag_corners[tag_index] ) num_tag_edges += 1 edge_counter += 1 # Connect odom to waypoint vertex for waypoint_vertex_id, waypoint_index in waypoint_vertex_id_and_index_by_frame_id.get(int(odom_frame), []): if waypoint_vertex_id not in counted_waypoint_vertex_ids: vertices[waypoint_vertex_id] = graph.Vertex( mode=graph.VertexType.WAYPOINT, estimate=(SE3Quat(vertices[current_odom_vertex_uid].estimate).inverse() * SE3Quat( waypoint_edge_measurements[waypoint_index])).to_vector(), fixed=False ) vertices[waypoint_vertex_id].meta_data['name'] = waypoint_name_by_vertex_id[waypoint_vertex_id] counted_waypoint_vertex_ids.add(waypoint_vertex_id) edges[edge_counter] = graph.Edge( startuid=current_odom_vertex_uid, enduid=waypoint_vertex_id, corner_ids=None, information=np.eye(6), information_prescaling=None, camera_intrinsics=None, measurement=(SE3Quat(vertices[waypoint_vertex_id].estimate) * SE3Quat( vertices[current_odom_vertex_uid].estimate).inverse()).to_vector() ) edge_counter += 1 if previous_vertex: # TODO: might want to consider prescaling based on the magnitude of the change edges[edge_counter] = graph.Edge( startuid=previous_vertex, enduid=current_odom_vertex_uid, corner_ids=None, information=np.eye(6), information_prescaling=None, camera_intrinsics=None, measurement=(SE3Quat(vertices[current_odom_vertex_uid].estimate) * SE3Quat( vertices[previous_vertex].estimate).inverse()).to_vector() ) edge_counter += 1 dummy_node_uid = vertex_counter vertices[dummy_node_uid] = graph.Vertex( mode=graph.VertexType.DUMMY, estimate=np.hstack((np.zeros(3, ), odom_vertex_estimates[i][3:])), fixed=True ) vertex_counter += 1 edges[edge_counter] = graph.Edge( startuid=current_odom_vertex_uid, enduid=dummy_node_uid, corner_ids=None, information=np.eye(6), information_prescaling=None, camera_intrinsics=None, measurement=np.array([0, 0, 0, 0, 0, 0, 1]) ) edge_counter += 1 previous_vertex = current_odom_vertex_uid if initialize_with_averages: for vertex_id, transforms in tag_transform_estimates.items(): vertices[vertex_id].estimate = se3_quat_average(transforms).to_vector() # TODO: Huber delta should probably scale with pixels rather than error resulting_graph = graph.Graph(vertices, edges, gravity_axis='y', is_sparse_bundle_adjustment=True, use_huber=False, huber_delta=None, damping_status=True) return resulting_graph
[ "itertools.chain", "numpy.eye", "numpy.unique", "numpy.hstack", "map_processing.graph.Vertex", "numpy.asarray", "g2o.CameraParameters", "numpy.array", "map_processing.graph.Graph", "numpy.zeros", "collections.defaultdict", "numpy.vstack", "numpy.concatenate", "map_processing.as_graph.se3_q...
[((478, 504), 'numpy.array', 'np.array', (["dct['pose_data']"], {}), "(dct['pose_data'])\n", (486, 504), True, 'import numpy as np\n'), ((673, 719), 'map_processing.as_graph.matrix2measurement', 'matrix2measurement', (['pose_matrices'], {'invert': '(True)'}), '(pose_matrices, invert=True)\n', (691, 719), False, 'from map_processing.as_graph import matrix2measurement, se3_quat_average\n'), ((812, 963), 'numpy.array', 'np.array', (['[[-tag_size / 2, -tag_size / 2, 1], [tag_size / 2, -tag_size / 2, 1], [\n tag_size / 2, tag_size / 2, 1], [-tag_size / 2, tag_size / 2, 1]]'], {}), '([[-tag_size / 2, -tag_size / 2, 1], [tag_size / 2, -tag_size / 2, \n 1], [tag_size / 2, tag_size / 2, 1], [-tag_size / 2, tag_size / 2, 1]])\n', (820, 963), True, 'import numpy as np\n'), ((1002, 1021), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (1010, 1021), True, 'import numpy as np\n'), ((1177, 1245), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]'], {}), '([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])\n', (1185, 1245), True, 'import numpy as np\n'), ((2622, 2670), 'map_processing.as_graph.matrix2measurement', 'matrix2measurement', (['tag_edge_measurements_matrix'], {}), '(tag_edge_measurements_matrix)\n', (2640, 2670), False, 'from map_processing.as_graph import matrix2measurement, se3_quat_average\n'), ((2693, 2711), 'numpy.unique', 'np.unique', (['tag_ids'], {}), '(tag_ids)\n', (2702, 2711), True, 'import numpy as np\n'), ((3863, 3888), 'numpy.unique', 'np.unique', (['waypoint_names'], {}), '(waypoint_names)\n', (3872, 3888), True, 'import numpy as np\n'), ((4170, 4223), 'map_processing.as_graph.matrix2measurement', 'matrix2measurement', (['waypoint_edge_measurements_matrix'], {}), '(waypoint_edge_measurements_matrix)\n', (4188, 4223), False, 'from map_processing.as_graph import matrix2measurement, se3_quat_average\n'), ((5543, 5567), 'collections.defaultdict', 'defaultdict', (['(lambda : [])'], {}), '(lambda : [])\n', (5554, 5567), False, 'from collections import defaultdict\n'), ((11531, 11672), 'map_processing.graph.Graph', 'graph.Graph', (['vertices', 'edges'], {'gravity_axis': '"""y"""', 'is_sparse_bundle_adjustment': '(True)', 'use_huber': '(False)', 'huber_delta': 'None', 'damping_status': '(True)'}), "(vertices, edges, gravity_axis='y', is_sparse_bundle_adjustment=\n True, use_huber=False, huber_delta=None, damping_status=True)\n", (11542, 11672), False, 'from map_processing import graph\n'), ((552, 569), 'numpy.zeros', 'np.zeros', (['(0, 18)'], {}), '((0, 18))\n', (560, 569), True, 'import numpy as np\n'), ((1438, 1530), 'numpy.vstack', 'np.vstack', (["[[x['tagPose'] for x in tagsFromFrame] for tagsFromFrame in dct['tag_data']]"], {}), "([[x['tagPose'] for x in tagsFromFrame] for tagsFromFrame in dct[\n 'tag_data']])\n", (1447, 1530), True, 'import numpy as np\n'), ((1562, 1662), 'numpy.vstack', 'np.vstack', (["[[x['cameraIntrinsics'] for x in tagsFromFrame] for tagsFromFrame in dct[\n 'tag_data']]"], {}), "([[x['cameraIntrinsics'] for x in tagsFromFrame] for tagsFromFrame in\n dct['tag_data']])\n", (1571, 1662), True, 'import numpy as np\n'), ((1730, 1840), 'numpy.vstack', 'np.vstack', (["[[x['tagCornersPixelCoordinates'] for x in tagsFromFrame] for tagsFromFrame in\n dct['tag_data']]"], {}), "([[x['tagCornersPixelCoordinates'] for x in tagsFromFrame] for\n tagsFromFrame in dct['tag_data']])\n", (1739, 1840), True, 'import numpy as np\n'), ((2271, 2288), 'numpy.zeros', 'np.zeros', (['(0, 16)'], {}), '((0, 16))\n', (2279, 2288), True, 'import numpy as np\n'), ((2325, 2341), 'numpy.zeros', 'np.zeros', (['(0, 4)'], {}), '((0, 4))\n', (2333, 2341), True, 'import numpy as np\n'), ((2364, 2380), 'numpy.zeros', 'np.zeros', (['(0, 8)'], {}), '((0, 8))\n', (2372, 2380), True, 'import numpy as np\n'), ((2399, 2429), 'numpy.zeros', 'np.zeros', (['(0, 1)'], {'dtype': 'np.int'}), '((0, 1), dtype=np.int)\n', (2407, 2429), True, 'import numpy as np\n'), ((2449, 2479), 'numpy.zeros', 'np.zeros', (['(0, 1)'], {'dtype': 'np.int'}), '((0, 1), dtype=np.int)\n', (2457, 2479), True, 'import numpy as np\n'), ((3323, 3353), 'numpy.hstack', 'np.hstack', (['(tag_ids, pose_ids)'], {}), '((tag_ids, pose_ids))\n', (3332, 3353), True, 'import numpy as np\n'), ((3951, 3988), 'numpy.concatenate', 'np.concatenate', (['waypoint_list_uniform'], {}), '(waypoint_list_uniform)\n', (3965, 3988), True, 'import numpy as np\n'), ((4031, 4048), 'numpy.zeros', 'np.zeros', (['(0, 18)'], {}), '((0, 18))\n', (4039, 4048), True, 'import numpy as np\n'), ((5715, 5865), 'map_processing.graph.Vertex', 'graph.Vertex', ([], {'mode': 'graph.VertexType.ODOMETRY', 'estimate': 'odom_vertex_estimates[i]', 'fixed': '(not first_odom_processed)', 'meta_data': "{'poseId': odom_frame}"}), "(mode=graph.VertexType.ODOMETRY, estimate=odom_vertex_estimates\n [i], fixed=not first_odom_processed, meta_data={'poseId': odom_frame})\n", (5727, 5865), False, 'from map_processing import graph\n'), ((1905, 2001), 'itertools.chain', 'itertools.chain', (["*[[x['tagId'] for x in tagsFromFrame] for tagsFromFrame in dct['tag_data']]"], {}), "(*[[x['tagId'] for x in tagsFromFrame] for tagsFromFrame in\n dct['tag_data']])\n", (1920, 2001), False, 'import itertools\n'), ((2087, 2184), 'itertools.chain', 'itertools.chain', (["*[[x['poseId'] for x in tagsFromFrame] for tagsFromFrame in dct['tag_data']]"], {}), "(*[[x['poseId'] for x in tagsFromFrame] for tagsFromFrame in\n dct['tag_data']])\n", (2102, 2184), False, 'import itertools\n'), ((6296, 6347), 'g2o.SE3Quat', 'SE3Quat', (['vertices[current_odom_vertex_uid].estimate'], {}), '(vertices[current_odom_vertex_uid].estimate)\n', (6303, 6347), False, 'from g2o import SE3Quat, CameraParameters\n'), ((7855, 7961), 'g2o.CameraParameters', 'CameraParameters', (['camera_intrinsics_for_tag[tag_index][0]', 'camera_intrinsics_for_tag[tag_index][2:]', '(0)'], {}), '(camera_intrinsics_for_tag[tag_index][0],\n camera_intrinsics_for_tag[tag_index][2:], 0)\n', (7871, 7961), False, 'from g2o import SE3Quat, CameraParameters\n'), ((11013, 11022), 'numpy.eye', 'np.eye', (['(6)'], {}), '(6)\n', (11019, 11022), True, 'import numpy as np\n'), ((11125, 11156), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 0, 1]'], {}), '([0, 0, 0, 0, 0, 0, 1])\n', (11133, 11156), True, 'import numpy as np\n'), ((7759, 7800), 'g2o.SE3Quat', 'SE3Quat', (['tag_edge_measurements[tag_index]'], {}), '(tag_edge_measurements[tag_index])\n', (7766, 7800), False, 'from g2o import SE3Quat, CameraParameters\n'), ((8410, 8419), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (8416, 8419), True, 'import numpy as np\n'), ((9624, 9633), 'numpy.eye', 'np.eye', (['(6)'], {}), '(6)\n', (9630, 9633), True, 'import numpy as np\n'), ((10256, 10265), 'numpy.eye', 'np.eye', (['(6)'], {}), '(6)\n', (10262, 10265), True, 'import numpy as np\n'), ((11390, 11418), 'map_processing.as_graph.se3_quat_average', 'se3_quat_average', (['transforms'], {}), '(transforms)\n', (11406, 11418), False, 'from map_processing.as_graph import matrix2measurement, se3_quat_average\n'), ((3688, 3706), 'numpy.asarray', 'np.asarray', (['x[:-1]'], {}), '(x[:-1])\n', (3698, 3706), True, 'import numpy as np\n'), ((6176, 6221), 'numpy.hstack', 'np.hstack', (['(true_3d_tag_center, [0, 0, 0, 1])'], {}), '((true_3d_tag_center, [0, 0, 0, 1]))\n', (6185, 6221), True, 'import numpy as np\n'), ((7812, 7831), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (7820, 7831), True, 'import numpy as np\n'), ((10729, 10740), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (10737, 10740), True, 'import numpy as np\n'), ((6225, 6266), 'g2o.SE3Quat', 'SE3Quat', (['tag_edge_measurements[tag_index]'], {}), '(tag_edge_measurements[tag_index])\n', (6232, 6266), False, 'from g2o import SE3Quat, CameraParameters\n'), ((7186, 7226), 'numpy.hstack', 'np.hstack', (['(true_point_3d, [0, 0, 0, 1])'], {}), '((true_point_3d, [0, 0, 0, 1]))\n', (7195, 7226), True, 'import numpy as np\n'), ((9749, 9795), 'g2o.SE3Quat', 'SE3Quat', (['vertices[waypoint_vertex_id].estimate'], {}), '(vertices[waypoint_vertex_id].estimate)\n', (9756, 9795), False, 'from g2o import SE3Quat, CameraParameters\n'), ((10381, 10432), 'g2o.SE3Quat', 'SE3Quat', (['vertices[current_odom_vertex_uid].estimate'], {}), '(vertices[current_odom_vertex_uid].estimate)\n', (10388, 10432), False, 'from g2o import SE3Quat, CameraParameters\n'), ((9102, 9153), 'g2o.SE3Quat', 'SE3Quat', (['waypoint_edge_measurements[waypoint_index]'], {}), '(waypoint_edge_measurements[waypoint_index])\n', (9109, 9153), False, 'from g2o import SE3Quat, CameraParameters\n'), ((9798, 9849), 'g2o.SE3Quat', 'SE3Quat', (['vertices[current_odom_vertex_uid].estimate'], {}), '(vertices[current_odom_vertex_uid].estimate)\n', (9805, 9849), False, 'from g2o import SE3Quat, CameraParameters\n'), ((10435, 10478), 'g2o.SE3Quat', 'SE3Quat', (['vertices[previous_vertex].estimate'], {}), '(vertices[previous_vertex].estimate)\n', (10442, 10478), False, 'from g2o import SE3Quat, CameraParameters\n'), ((9038, 9089), 'g2o.SE3Quat', 'SE3Quat', (['vertices[current_odom_vertex_uid].estimate'], {}), '(vertices[current_odom_vertex_uid].estimate)\n', (9045, 9089), False, 'from g2o import SE3Quat, CameraParameters\n')]
import os import time import pandas as pd import numpy as np from tqdm import tqdm def warn(*args, **kwargs): pass import warnings warnings.warn = warn from sklearn import metrics from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from skmultiflow.utils import calculate_object_size from utils import sort_alphanumeric def read_data(path: str, file: str): """ Reads file containing the encodings for a given event log Parameters ----------------------- path: str, File path log: str, File name Returns ----------------------- The encoding vectors and their corresponding labels """ df = pd.read_csv(f'{path}/{file}') y = list(df['label']) del df['case'], df['time'], df['label'] vectors = df.to_numpy() del df return vectors, y def compute_memory(obj1, obj2, obj3): """ Calculates the allocated memory of three objects (rf, encodings and labels) Returns ----------------------- Returns an appropriate format to write a csv file """ rf_size = calculate_object_size(obj1) encoding_size = calculate_object_size(obj2) label_size = calculate_object_size(obj3) total_size = rf_size + encoding_size + label_size return [rf_size, encoding_size, label_size, total_size] def compute_metrics(y_true, y_pred, binary=True): """ Computes classification metrics Parameters ----------------------- y_true, List of true instance labels y_pred, List of predicted instance labels binary, Controls the computation of binary only metrics Returns ----------------------- Classification metrics """ accuracy = metrics.accuracy_score(y_true, y_pred) accuracy_balanced = metrics.balanced_accuracy_score(y_true, y_pred) f1_micro = metrics.f1_score(y_true, y_pred, average='micro') f1_macro = metrics.f1_score(y_true, y_pred, average='macro') f1_weighted = metrics.f1_score(y_true, y_pred, average='weighted') precision_micro = metrics.precision_score(y_true, y_pred, average='micro', zero_division=0) precision_macro = metrics.precision_score(y_true, y_pred, average='macro', zero_division=0) precision_weighted = metrics.precision_score(y_true, y_pred, average='weighted', zero_division=0) recall_micro = metrics.recall_score(y_true, y_pred, average='micro', zero_division=0) recall_macro = metrics.recall_score(y_true, y_pred, average='macro', zero_division=0) recall_weighted = metrics.recall_score(y_true, y_pred, average='weighted', zero_division=0) if binary: f1_binary = metrics.f1_score(y_true, y_pred, average='binary', pos_label='normal') precision_binary = metrics.precision_score(y_true, y_pred, average='binary', pos_label='normal') recall_binary = metrics.recall_score(y_true, y_pred, average='binary', pos_label='normal') else: f1_binary = np.nan precision_binary = np.nan recall_binary = np.nan return [accuracy, accuracy_balanced, f1_binary, f1_micro, f1_macro, f1_weighted, precision_binary, precision_micro, precision_macro, precision_weighted, recall_binary, recall_micro, recall_macro, recall_weighted] encodings = sort_alphanumeric(os.listdir('encoding_results')) files = sort_alphanumeric(os.listdir('encoding_results/alignment')) out = [] for file in tqdm(files, total=len(files), desc='Calculating classification metrics'): for encoding in encodings: path = f'encoding_results/{encoding}' vectors, labels = read_data(path, file) metrics_list = [] for i in range(30): start_time = time.time() X_train, X_test, y_train, y_test = train_test_split(vectors, labels, test_size=0.2) rf = RandomForestClassifier(n_jobs=-1).fit(X_train, y_train) y_pred = rf.predict(X_test) if 'all' in file: metrics_ = compute_metrics(y_test, y_pred, False) else: metrics_ = compute_metrics(y_test, y_pred) end_time = time.time() - start_time metrics_.extend([end_time]) metrics_.extend(compute_memory(rf, vectors, labels)) metrics_list.append(metrics_) metrics_array = np.array(metrics_list) metrics_array = list(np.nanmean(metrics_array, axis=0)) file_encoding = [file.split('.csv')[0], encoding] file_encoding.extend(metrics_array) out.append(file_encoding) columns = ['log', 'encoding', 'accuracy', 'accuracy_balanced', 'f1_binary', 'f1_micro', 'f1_macro', 'f1_weighted', 'precision_binary', 'precision_micro', 'precision_macro', 'precision_weighted', 'recall_binary', 'recall_micro', 'recall_macro', 'recall_weighted', 'time', 'mem_rf', 'mem_encoding', 'mem_labels', 'mem_total'] pd.DataFrame(out, columns=columns).to_csv('results.csv', index=False)
[ "sklearn.metrics.f1_score", "os.listdir", "skmultiflow.utils.calculate_object_size", "sklearn.metrics.balanced_accuracy_score", "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.ensemble.RandomForestClassifier", "sklearn.metrics.precision_score", "sklearn.metrics.recall_score",...
[((708, 737), 'pandas.read_csv', 'pd.read_csv', (['f"""{path}/{file}"""'], {}), "(f'{path}/{file}')\n", (719, 737), True, 'import pandas as pd\n'), ((1114, 1141), 'skmultiflow.utils.calculate_object_size', 'calculate_object_size', (['obj1'], {}), '(obj1)\n', (1135, 1141), False, 'from skmultiflow.utils import calculate_object_size\n'), ((1162, 1189), 'skmultiflow.utils.calculate_object_size', 'calculate_object_size', (['obj2'], {}), '(obj2)\n', (1183, 1189), False, 'from skmultiflow.utils import calculate_object_size\n'), ((1207, 1234), 'skmultiflow.utils.calculate_object_size', 'calculate_object_size', (['obj3'], {}), '(obj3)\n', (1228, 1234), False, 'from skmultiflow.utils import calculate_object_size\n'), ((1750, 1788), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (1772, 1788), False, 'from sklearn import metrics\n'), ((1813, 1860), 'sklearn.metrics.balanced_accuracy_score', 'metrics.balanced_accuracy_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (1844, 1860), False, 'from sklearn import metrics\n'), ((1876, 1925), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['y_true', 'y_pred'], {'average': '"""micro"""'}), "(y_true, y_pred, average='micro')\n", (1892, 1925), False, 'from sklearn import metrics\n'), ((1941, 1990), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['y_true', 'y_pred'], {'average': '"""macro"""'}), "(y_true, y_pred, average='macro')\n", (1957, 1990), False, 'from sklearn import metrics\n'), ((2009, 2061), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['y_true', 'y_pred'], {'average': '"""weighted"""'}), "(y_true, y_pred, average='weighted')\n", (2025, 2061), False, 'from sklearn import metrics\n'), ((2084, 2157), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['y_true', 'y_pred'], {'average': '"""micro"""', 'zero_division': '(0)'}), "(y_true, y_pred, average='micro', zero_division=0)\n", (2107, 2157), False, 'from sklearn import metrics\n'), ((2180, 2253), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['y_true', 'y_pred'], {'average': '"""macro"""', 'zero_division': '(0)'}), "(y_true, y_pred, average='macro', zero_division=0)\n", (2203, 2253), False, 'from sklearn import metrics\n'), ((2279, 2355), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['y_true', 'y_pred'], {'average': '"""weighted"""', 'zero_division': '(0)'}), "(y_true, y_pred, average='weighted', zero_division=0)\n", (2302, 2355), False, 'from sklearn import metrics\n'), ((2375, 2445), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['y_true', 'y_pred'], {'average': '"""micro"""', 'zero_division': '(0)'}), "(y_true, y_pred, average='micro', zero_division=0)\n", (2395, 2445), False, 'from sklearn import metrics\n'), ((2465, 2535), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['y_true', 'y_pred'], {'average': '"""macro"""', 'zero_division': '(0)'}), "(y_true, y_pred, average='macro', zero_division=0)\n", (2485, 2535), False, 'from sklearn import metrics\n'), ((2558, 2631), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['y_true', 'y_pred'], {'average': '"""weighted"""', 'zero_division': '(0)'}), "(y_true, y_pred, average='weighted', zero_division=0)\n", (2578, 2631), False, 'from sklearn import metrics\n'), ((3307, 3337), 'os.listdir', 'os.listdir', (['"""encoding_results"""'], {}), "('encoding_results')\n", (3317, 3337), False, 'import os\n'), ((3365, 3405), 'os.listdir', 'os.listdir', (['"""encoding_results/alignment"""'], {}), "('encoding_results/alignment')\n", (3375, 3405), False, 'import os\n'), ((2668, 2738), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['y_true', 'y_pred'], {'average': '"""binary"""', 'pos_label': '"""normal"""'}), "(y_true, y_pred, average='binary', pos_label='normal')\n", (2684, 2738), False, 'from sklearn import metrics\n'), ((2766, 2843), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['y_true', 'y_pred'], {'average': '"""binary"""', 'pos_label': '"""normal"""'}), "(y_true, y_pred, average='binary', pos_label='normal')\n", (2789, 2843), False, 'from sklearn import metrics\n'), ((2868, 2942), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['y_true', 'y_pred'], {'average': '"""binary"""', 'pos_label': '"""normal"""'}), "(y_true, y_pred, average='binary', pos_label='normal')\n", (2888, 2942), False, 'from sklearn import metrics\n'), ((4324, 4346), 'numpy.array', 'np.array', (['metrics_list'], {}), '(metrics_list)\n', (4332, 4346), True, 'import numpy as np\n'), ((4889, 4923), 'pandas.DataFrame', 'pd.DataFrame', (['out'], {'columns': 'columns'}), '(out, columns=columns)\n', (4901, 4923), True, 'import pandas as pd\n'), ((3707, 3718), 'time.time', 'time.time', ([], {}), '()\n', (3716, 3718), False, 'import time\n'), ((3766, 3814), 'sklearn.model_selection.train_test_split', 'train_test_split', (['vectors', 'labels'], {'test_size': '(0.2)'}), '(vectors, labels, test_size=0.2)\n', (3782, 3814), False, 'from sklearn.model_selection import train_test_split\n'), ((4376, 4409), 'numpy.nanmean', 'np.nanmean', (['metrics_array'], {'axis': '(0)'}), '(metrics_array, axis=0)\n', (4386, 4409), True, 'import numpy as np\n'), ((4127, 4138), 'time.time', 'time.time', ([], {}), '()\n', (4136, 4138), False, 'import time\n'), ((3833, 3866), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_jobs': '(-1)'}), '(n_jobs=-1)\n', (3855, 3866), False, 'from sklearn.ensemble import RandomForestClassifier\n')]
import numpy as np import nibabel as nib from scipy import ndimage from utils import * def segment_airway(params, I, I_affine, Mlung): ##################################################### # Initialize parameters ##################################################### Radius = params['airwayRadiusMask'] RadiusX = params['airwayRadiusX'] RadiusZ = params['airwayRadiusZ'] struct_s = ndimage.generate_binary_structure(3, 1) struct_l = ndimage.iterate_structure(struct_s, 3) struct_trachea = generate_structure_trachea(Radius, RadiusX, RadiusZ) ##################################################### # Locate an inital point in trachea ##################################################### slice_no, initLoc = generate_initLoc(params, I, Mlung, Radius, RadiusZ, struct_trachea) ##################################################### # Find airway with closed space diallation ##################################################### Maw = close_space_dilation(params, I, Mlung, Radius, RadiusX, RadiusZ, struct_s, slice_no, initLoc) ##################################################### # Remove airway & save nii ##################################################### Mawtmp = ndimage.binary_dilation(Maw, structure = struct_l, iterations = 1) Mawtmp = np.int8(Mawtmp) Mlung[Maw > 0] = 0 nib.Nifti1Image(Maw,I_affine).to_filename('./result/sample_aw.nii.gz') nib.Nifti1Image(Mlung,I_affine).to_filename('./result/sample_lung.nii.gz') return Mlung, Maw
[ "numpy.int8", "scipy.ndimage.iterate_structure", "scipy.ndimage.generate_binary_structure", "scipy.ndimage.binary_dilation", "nibabel.Nifti1Image" ]
[((421, 460), 'scipy.ndimage.generate_binary_structure', 'ndimage.generate_binary_structure', (['(3)', '(1)'], {}), '(3, 1)\n', (454, 460), False, 'from scipy import ndimage\n'), ((477, 515), 'scipy.ndimage.iterate_structure', 'ndimage.iterate_structure', (['struct_s', '(3)'], {}), '(struct_s, 3)\n', (502, 515), False, 'from scipy import ndimage\n'), ((1233, 1295), 'scipy.ndimage.binary_dilation', 'ndimage.binary_dilation', (['Maw'], {'structure': 'struct_l', 'iterations': '(1)'}), '(Maw, structure=struct_l, iterations=1)\n', (1256, 1295), False, 'from scipy import ndimage\n'), ((1310, 1325), 'numpy.int8', 'np.int8', (['Mawtmp'], {}), '(Mawtmp)\n', (1317, 1325), True, 'import numpy as np\n'), ((1347, 1377), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['Maw', 'I_affine'], {}), '(Maw, I_affine)\n', (1362, 1377), True, 'import nibabel as nib\n'), ((1419, 1451), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['Mlung', 'I_affine'], {}), '(Mlung, I_affine)\n', (1434, 1451), True, 'import nibabel as nib\n')]
import torch from torch.optim import Optimizer from torch.distributions import Normal import numpy as np class SGLD(Optimizer): def __init__(self, params, lr, norm_sigma=0.0, alpha=0.99, eps=1e-8, centered=False, addnoise=True, p=True): weight_decay = 1/(norm_sigma ** 2 + eps) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) defaults = dict(lr=lr, alpha=alpha, weight_decay=weight_decay, eps=eps, centered=centered, addnoise=addnoise, p=p) super(SGLD, self).__init__(params, defaults) def __setstate__(self, state): super(SGLD, self).__setstate__(state) @torch.no_grad() def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue d_p = p.grad.data state = self.state[p] if len(state) == 0: state['step'] = 0 state['square_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format) if group['centered']: state['grad_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format) square_avg = state['square_avg'] alpha = group['alpha'] state['step'] += 1 if group['weight_decay'] != 0: d_p.add_(p.data, alpha=group['weight_decay']) square_avg.mul_(alpha).addcmul_(d_p, d_p, value=1-alpha) if group['centered']: grad_avg = state['grad_avg'] grad_avg.mul_(alpha).add_(d_p, alpha=1-alpha) avg = square_avg.addcmul(grad_avg, grad_avg, value=-1).sqrt_().add_(group['eps']) else: avg = square_avg.sqrt().add_(group['eps']) if group['addnoise']: langevin_noise = p.data.new(p.data.size()).normal_(mean=0, std=1) / np.sqrt(group['lr']) if group['p']: p.data.add_(0.5 * d_p.div_(avg) + langevin_noise / torch.sqrt(avg), alpha=-group['lr']) else: p.data.add_(0.5 * d_p + langevin_noise, alpha=-group['lr']) else: if group['p']: p.data.addcdiv_( 0.5 * d_p, avg, value = -group['lr']) else: p.data.addcdiv_( 0.5 * d_p, value = -group['lr']) return loss
[ "numpy.sqrt", "torch.enable_grad", "torch.sqrt", "torch.no_grad", "torch.zeros_like" ]
[((787, 802), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (800, 802), False, 'import torch\n'), ((910, 929), 'torch.enable_grad', 'torch.enable_grad', ([], {}), '()\n', (927, 929), False, 'import torch\n'), ((1308, 1364), 'torch.zeros_like', 'torch.zeros_like', (['p'], {'memory_format': 'torch.preserve_format'}), '(p, memory_format=torch.preserve_format)\n', (1324, 1364), False, 'import torch\n'), ((1453, 1509), 'torch.zeros_like', 'torch.zeros_like', (['p'], {'memory_format': 'torch.preserve_format'}), '(p, memory_format=torch.preserve_format)\n', (1469, 1509), False, 'import torch\n'), ((2397, 2417), 'numpy.sqrt', 'np.sqrt', (["group['lr']"], {}), "(group['lr'])\n", (2404, 2417), True, 'import numpy as np\n'), ((2530, 2545), 'torch.sqrt', 'torch.sqrt', (['avg'], {}), '(avg)\n', (2540, 2545), False, 'import torch\n')]
import tensorflow as tf import numpy as np from PIL import Image from tensorflow.core.framework import graph_pb2 from tensorflow.python.platform import gfile from tensorflow.python.data.experimental import parallel_interleave from tensorflow.python.data.experimental import map_and_batch def read_graph(input_graph): if not gfile.Exists(input_graph): print("Input graph file '" + input_graph + "' does not exist!") exit(-1) input_graph_def = graph_pb2.GraphDef() with gfile.Open(input_graph, "rb") as f: data = f.read() input_graph_def.ParseFromString(data) return input_graph_def def parse_and_preprocess(serialized_example): # Dense features in Example proto. feature_map = { 'image/encoded': tf.compat.v1.FixedLenFeature([], dtype=tf.string, default_value=''), 'image/object/class/text': tf.compat.v1.VarLenFeature(dtype=tf.string), 'image/source_id': tf.compat.v1.FixedLenFeature([], dtype=tf.string, default_value=''), } sparse_float32 = tf.compat.v1.VarLenFeature(dtype=tf.float32) # Sparse features in Example proto. feature_map.update( {k: sparse_float32 for k in ['image/object/bbox/xmin', 'image/object/bbox/ymin', 'image/object/bbox/xmax', 'image/object/bbox/ymax']}) features = tf.compat.v1.parse_single_example(serialized_example, feature_map) xmin = tf.expand_dims(features['image/object/bbox/xmin'].values, 0) ymin = tf.expand_dims(features['image/object/bbox/ymin'].values, 0) xmax = tf.expand_dims(features['image/object/bbox/xmax'].values, 0) ymax = tf.expand_dims(features['image/object/bbox/ymax'].values, 0) # Note that we impose an ordering of (y, x) just to make life difficult. bbox = tf.concat([ymin, xmin, ymax, xmax], 0) # Force the variable number of bounding boxes into the shape # [1, num_boxes, coords]. bbox = tf.expand_dims(bbox, 0) bbox = tf.transpose(bbox, [0, 2, 1]) encoded_image = features['image/encoded'] image_tensor = tf.image.decode_image(encoded_image, channels=3) image_tensor.set_shape([None, None, 3]) label = features['image/object/class/text'].values image_id = features['image/source_id'] return image_tensor, bbox[0], label, image_id def get_input(data_location, batch_size=1): tfrecord_paths = [data_location] ds = tf.data.TFRecordDataset.list_files(tfrecord_paths) ds = ds.apply( parallel_interleave( tf.data.TFRecordDataset, cycle_length=28, block_length=5, sloppy=True, buffer_output_elements=10000, prefetch_input_elements=10000)) ds = ds.prefetch(buffer_size=10000) ds = ds.apply( map_and_batch( map_func=parse_and_preprocess, batch_size=batch_size, num_parallel_batches=28, num_parallel_calls=None)) ds = ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) ds_iter = tf.compat.v1.data.make_one_shot_iterator(ds) images, bbox, label, image_id = ds_iter.get_next() return images, bbox, label, image_id def letter_box_image(image, output_height, output_width, fill_value): """ Fit image with final image with output_width and output_height. :param image: PILLOW Image object. :param output_height: width of the final image. :param output_width: height of the final image. :param fill_value: fill value for empty area. Can be uint8 or np.ndarray :return: numpy image fit within letterbox. dtype=uint8, shape=(output_height, output_width) """ height_ratio = float(output_height) / image.size[1] width_ratio = float(output_width) / image.size[0] fit_ratio = min(width_ratio, height_ratio) fit_height = int(image.size[1] * fit_ratio) fit_width = int(image.size[0] * fit_ratio) fit_image = np.asarray(image.resize((fit_width, fit_height), resample=Image.BILINEAR)) if isinstance(fill_value, int): fill_value = np.full(fit_image.shape[2], fill_value, fit_image.dtype) to_return = np.tile(fill_value, (output_height, output_width, 1)) pad_top = int(0.5 * (output_height - fit_height)) pad_left = int(0.5 * (output_width - fit_width)) to_return[pad_top: pad_top+fit_height, pad_left: pad_left+fit_width] = fit_image return to_return def _iou(box1, box2): """ Computes Intersection over Union value for 2 bounding boxes :param box1: array of 4 values (top left and bottom right coords): [x0, y0, x1, x2] :param box2: same as box1 :return: IoU """ b1_x0, b1_y0, b1_x1, b1_y1 = box1 b2_x0, b2_y0, b2_x1, b2_y1 = box2 int_x0 = max(b1_x0, b2_x0) int_y0 = max(b1_y0, b2_y0) int_x1 = min(b1_x1, b2_x1) int_y1 = min(b1_y1, b2_y1) int_area = max(int_x1 - int_x0, 0) * max(int_y1 - int_y0, 0) b1_area = (b1_x1 - b1_x0) * (b1_y1 - b1_y0) b2_area = (b2_x1 - b2_x0) * (b2_y1 - b2_y0) # we add small epsilon of 1e-05 to avoid division by 0 iou = int_area / (b1_area + b2_area - int_area + 1e-05) return iou def non_max_suppression(predictions_with_boxes, confidence_threshold, iou_threshold=0.4): """ Applies Non-max suppression to prediction boxes. :param predictions_with_boxes: 3D numpy array, first 4 values in 3rd dimension are bbox attrs, 5th is confidence :param confidence_threshold: the threshold for deciding if prediction is valid :param iou_threshold: the threshold for deciding if two boxes overlap :return: dict: class -> [(box, score)] """ conf_mask = np.expand_dims( (predictions_with_boxes[:, :, 4] > confidence_threshold), -1) predictions = predictions_with_boxes * conf_mask result = {} for i, image_pred in enumerate(predictions): shape = image_pred.shape tmp = image_pred sum_t = np.sum(tmp, axis=1) non_zero_idxs = sum_t != 0 image_pred = image_pred[non_zero_idxs, :] image_pred = image_pred.reshape(-1, shape[-1]) bbox_attrs = image_pred[:, :5] classes = image_pred[:, 5:] classes = np.argmax(classes, axis=-1) unique_classes = list(set(classes.reshape(-1))) for cls in unique_classes: cls_mask = classes == cls cls_boxes = bbox_attrs[np.nonzero(cls_mask)] cls_boxes = cls_boxes[cls_boxes[:, -1].argsort()[::-1]] cls_scores = cls_boxes[:, -1] cls_boxes = cls_boxes[:, :-1] while len(cls_boxes) > 0: box = cls_boxes[0] score = cls_scores[0] if cls not in result: result[cls] = [] result[cls].append((box, score)) cls_boxes = cls_boxes[1:] cls_scores = cls_scores[1:] ious = np.array([_iou(box, x) for x in cls_boxes]) iou_mask = ious < iou_threshold cls_boxes = cls_boxes[np.nonzero(iou_mask)] cls_scores = cls_scores[np.nonzero(iou_mask)] return result def letter_box_pos_to_original_pos(letter_pos, current_size, ori_image_size)-> np.ndarray: """ Parameters should have same shape and dimension space. (Width, Height) or (Height, Width) :param letter_pos: The current position within letterbox image including fill value area. :param current_size: The size of whole image including fill value area. :param ori_image_size: The size of image before being letter boxed. :return: """ letter_pos = np.asarray(letter_pos, dtype=np.float) current_size = np.asarray(current_size, dtype=np.float) ori_image_size = np.asarray(ori_image_size, dtype=np.float) final_ratio = min(current_size[0] / ori_image_size[0], current_size[1] / ori_image_size[1]) pad = 0.5 * (current_size - final_ratio * ori_image_size) pad = pad.astype(np.int32) to_return_pos = (letter_pos - pad) / final_ratio return to_return_pos
[ "tensorflow.transpose", "tensorflow.compat.v1.data.make_one_shot_iterator", "tensorflow.data.TFRecordDataset.list_files", "tensorflow.compat.v1.FixedLenFeature", "tensorflow.core.framework.graph_pb2.GraphDef", "tensorflow.python.data.experimental.map_and_batch", "numpy.asarray", "tensorflow.python.dat...
[((465, 485), 'tensorflow.core.framework.graph_pb2.GraphDef', 'graph_pb2.GraphDef', ([], {}), '()\n', (483, 485), False, 'from tensorflow.core.framework import graph_pb2\n'), ((1100, 1144), 'tensorflow.compat.v1.VarLenFeature', 'tf.compat.v1.VarLenFeature', ([], {'dtype': 'tf.float32'}), '(dtype=tf.float32)\n', (1126, 1144), True, 'import tensorflow as tf\n'), ((1465, 1531), 'tensorflow.compat.v1.parse_single_example', 'tf.compat.v1.parse_single_example', (['serialized_example', 'feature_map'], {}), '(serialized_example, feature_map)\n', (1498, 1531), True, 'import tensorflow as tf\n'), ((1542, 1602), 'tensorflow.expand_dims', 'tf.expand_dims', (["features['image/object/bbox/xmin'].values", '(0)'], {}), "(features['image/object/bbox/xmin'].values, 0)\n", (1556, 1602), True, 'import tensorflow as tf\n'), ((1612, 1672), 'tensorflow.expand_dims', 'tf.expand_dims', (["features['image/object/bbox/ymin'].values", '(0)'], {}), "(features['image/object/bbox/ymin'].values, 0)\n", (1626, 1672), True, 'import tensorflow as tf\n'), ((1682, 1742), 'tensorflow.expand_dims', 'tf.expand_dims', (["features['image/object/bbox/xmax'].values", '(0)'], {}), "(features['image/object/bbox/xmax'].values, 0)\n", (1696, 1742), True, 'import tensorflow as tf\n'), ((1752, 1812), 'tensorflow.expand_dims', 'tf.expand_dims', (["features['image/object/bbox/ymax'].values", '(0)'], {}), "(features['image/object/bbox/ymax'].values, 0)\n", (1766, 1812), True, 'import tensorflow as tf\n'), ((1898, 1936), 'tensorflow.concat', 'tf.concat', (['[ymin, xmin, ymax, xmax]', '(0)'], {}), '([ymin, xmin, ymax, xmax], 0)\n', (1907, 1936), True, 'import tensorflow as tf\n'), ((2038, 2061), 'tensorflow.expand_dims', 'tf.expand_dims', (['bbox', '(0)'], {}), '(bbox, 0)\n', (2052, 2061), True, 'import tensorflow as tf\n'), ((2071, 2100), 'tensorflow.transpose', 'tf.transpose', (['bbox', '[0, 2, 1]'], {}), '(bbox, [0, 2, 1])\n', (2083, 2100), True, 'import tensorflow as tf\n'), ((2163, 2211), 'tensorflow.image.decode_image', 'tf.image.decode_image', (['encoded_image'], {'channels': '(3)'}), '(encoded_image, channels=3)\n', (2184, 2211), True, 'import tensorflow as tf\n'), ((2490, 2540), 'tensorflow.data.TFRecordDataset.list_files', 'tf.data.TFRecordDataset.list_files', (['tfrecord_paths'], {}), '(tfrecord_paths)\n', (2524, 2540), True, 'import tensorflow as tf\n'), ((3058, 3102), 'tensorflow.compat.v1.data.make_one_shot_iterator', 'tf.compat.v1.data.make_one_shot_iterator', (['ds'], {}), '(ds)\n', (3098, 3102), True, 'import tensorflow as tf\n'), ((4147, 4200), 'numpy.tile', 'np.tile', (['fill_value', '(output_height, output_width, 1)'], {}), '(fill_value, (output_height, output_width, 1))\n', (4154, 4200), True, 'import numpy as np\n'), ((5647, 5721), 'numpy.expand_dims', 'np.expand_dims', (['(predictions_with_boxes[:, :, 4] > confidence_threshold)', '(-1)'], {}), '(predictions_with_boxes[:, :, 4] > confidence_threshold, -1)\n', (5661, 5721), True, 'import numpy as np\n'), ((7600, 7638), 'numpy.asarray', 'np.asarray', (['letter_pos'], {'dtype': 'np.float'}), '(letter_pos, dtype=np.float)\n', (7610, 7638), True, 'import numpy as np\n'), ((7658, 7698), 'numpy.asarray', 'np.asarray', (['current_size'], {'dtype': 'np.float'}), '(current_size, dtype=np.float)\n', (7668, 7698), True, 'import numpy as np\n'), ((7720, 7762), 'numpy.asarray', 'np.asarray', (['ori_image_size'], {'dtype': 'np.float'}), '(ori_image_size, dtype=np.float)\n', (7730, 7762), True, 'import numpy as np\n'), ((330, 355), 'tensorflow.python.platform.gfile.Exists', 'gfile.Exists', (['input_graph'], {}), '(input_graph)\n', (342, 355), False, 'from tensorflow.python.platform import gfile\n'), ((495, 524), 'tensorflow.python.platform.gfile.Open', 'gfile.Open', (['input_graph', '"""rb"""'], {}), "(input_graph, 'rb')\n", (505, 524), False, 'from tensorflow.python.platform import gfile\n'), ((752, 819), 'tensorflow.compat.v1.FixedLenFeature', 'tf.compat.v1.FixedLenFeature', (['[]'], {'dtype': 'tf.string', 'default_value': '""""""'}), "([], dtype=tf.string, default_value='')\n", (780, 819), True, 'import tensorflow as tf\n'), ((896, 939), 'tensorflow.compat.v1.VarLenFeature', 'tf.compat.v1.VarLenFeature', ([], {'dtype': 'tf.string'}), '(dtype=tf.string)\n', (922, 939), True, 'import tensorflow as tf\n'), ((966, 1033), 'tensorflow.compat.v1.FixedLenFeature', 'tf.compat.v1.FixedLenFeature', (['[]'], {'dtype': 'tf.string', 'default_value': '""""""'}), "([], dtype=tf.string, default_value='')\n", (994, 1033), True, 'import tensorflow as tf\n'), ((2569, 2730), 'tensorflow.python.data.experimental.parallel_interleave', 'parallel_interleave', (['tf.data.TFRecordDataset'], {'cycle_length': '(28)', 'block_length': '(5)', 'sloppy': '(True)', 'buffer_output_elements': '(10000)', 'prefetch_input_elements': '(10000)'}), '(tf.data.TFRecordDataset, cycle_length=28, block_length=\n 5, sloppy=True, buffer_output_elements=10000, prefetch_input_elements=10000\n )\n', (2588, 2730), False, 'from tensorflow.python.data.experimental import parallel_interleave\n'), ((2820, 2941), 'tensorflow.python.data.experimental.map_and_batch', 'map_and_batch', ([], {'map_func': 'parse_and_preprocess', 'batch_size': 'batch_size', 'num_parallel_batches': '(28)', 'num_parallel_calls': 'None'}), '(map_func=parse_and_preprocess, batch_size=batch_size,\n num_parallel_batches=28, num_parallel_calls=None)\n', (2833, 2941), False, 'from tensorflow.python.data.experimental import map_and_batch\n'), ((4073, 4129), 'numpy.full', 'np.full', (['fit_image.shape[2]', 'fill_value', 'fit_image.dtype'], {}), '(fit_image.shape[2], fill_value, fit_image.dtype)\n', (4080, 4129), True, 'import numpy as np\n'), ((5926, 5945), 'numpy.sum', 'np.sum', (['tmp'], {'axis': '(1)'}), '(tmp, axis=1)\n', (5932, 5945), True, 'import numpy as np\n'), ((6180, 6207), 'numpy.argmax', 'np.argmax', (['classes'], {'axis': '(-1)'}), '(classes, axis=-1)\n', (6189, 6207), True, 'import numpy as np\n'), ((6374, 6394), 'numpy.nonzero', 'np.nonzero', (['cls_mask'], {}), '(cls_mask)\n', (6384, 6394), True, 'import numpy as np\n'), ((7023, 7043), 'numpy.nonzero', 'np.nonzero', (['iou_mask'], {}), '(iou_mask)\n', (7033, 7043), True, 'import numpy as np\n'), ((7085, 7105), 'numpy.nonzero', 'np.nonzero', (['iou_mask'], {}), '(iou_mask)\n', (7095, 7105), True, 'import numpy as np\n')]
# coding:UTF-8 # 2018-10-15 # k-means # python 机器学习算法 import numpy as np def loadData(file_path): '''导入数据 input: file_path(string):文件的存储位置 output: data(mat):数据 ''' f = open(file_path) data = [] for line in f.readlines(): row = [] # 记录每一行 lines = line.strip().split("\t") for x in lines: row.append(float(x)) # 将文本中的特征转换成浮点数 data.append(row) f.close() return np.mat(data) def distance(vecA, vecB): """ 计算两点的欧式距离 """ dist = (vecA - vecB) * (vecA - vecB).T return dist[0, 0] def randCentriod(data, k): """ 随机初始化聚类中心 """ n = np.shape(data)[-1] centriods = np.mat(np.zeros((k, n))) for j in range(n): min_j = np.min(data[:, j]) max_j = np.max(data[:, j]) range_j = max_j - min_j centriods[:, j] = min_j * np.mat(np.ones((k, 1))) + np.random.rand(k, 1) * range_j return centriods def kmeans(data, k, centriods): m, n = np.shape(data) sub_cent = np.mat(np.zeros((m, 2))) change = True while change: change = False # 计算每个样本到聚类中心的距离 for i in range(m): min_dist = np.inf min_index = 0 for j in range(k): dist = distance(data[i, :], centriods[j, :]) if dist < min_dist: min_dist = dist min_index = j if sub_cent[i, 0] != min_index: change = True sub_cent[i, :] = np.mat([min_index, min_dist]) # 重新计算中心 for j in range(k): sum_all = np.mat(np.zeros((1, n))) r = 0 for i in range(m): if sub_cent[i, 0] == j: sum_all += data[i, :] r += 1 for c in range(n): try: centriods[j, c] = sum_all[0, c] / r except: print("r is zero") return centriods, sub_cent if __name__ == "__main__": k = 4 # 聚类中心的个数 file_path = "data.txt" # 1、导入数据 print("loading data...") data = loadData(file_path) # 2、随机初始化k个聚类中心 print("initialize centroids...") centroids = randCentriod(data, k) # 3、聚类计算 print("training...") subCenter, centroids = kmeans(data, k, centroids) # result print("centroids: ", subCenter)
[ "numpy.mat", "numpy.random.rand", "numpy.ones", "numpy.max", "numpy.zeros", "numpy.min", "numpy.shape" ]
[((443, 455), 'numpy.mat', 'np.mat', (['data'], {}), '(data)\n', (449, 455), True, 'import numpy as np\n'), ((927, 941), 'numpy.shape', 'np.shape', (['data'], {}), '(data)\n', (935, 941), True, 'import numpy as np\n'), ((620, 634), 'numpy.shape', 'np.shape', (['data'], {}), '(data)\n', (628, 634), True, 'import numpy as np\n'), ((659, 675), 'numpy.zeros', 'np.zeros', (['(k, n)'], {}), '((k, n))\n', (667, 675), True, 'import numpy as np\n'), ((707, 725), 'numpy.min', 'np.min', (['data[:, j]'], {}), '(data[:, j])\n', (713, 725), True, 'import numpy as np\n'), ((736, 754), 'numpy.max', 'np.max', (['data[:, j]'], {}), '(data[:, j])\n', (742, 754), True, 'import numpy as np\n'), ((961, 977), 'numpy.zeros', 'np.zeros', (['(m, 2)'], {}), '((m, 2))\n', (969, 977), True, 'import numpy as np\n'), ((836, 856), 'numpy.random.rand', 'np.random.rand', (['k', '(1)'], {}), '(k, 1)\n', (850, 856), True, 'import numpy as np\n'), ((1317, 1346), 'numpy.mat', 'np.mat', (['[min_index, min_dist]'], {}), '([min_index, min_dist])\n', (1323, 1346), True, 'import numpy as np\n'), ((1400, 1416), 'numpy.zeros', 'np.zeros', (['(1, n)'], {}), '((1, n))\n', (1408, 1416), True, 'import numpy as np\n'), ((817, 832), 'numpy.ones', 'np.ones', (['(k, 1)'], {}), '((k, 1))\n', (824, 832), True, 'import numpy as np\n')]
#!/usr/bin/env python import rospy import sys import cv2 import numpy as np from cv_bridge import CvBridge, CvBridgeError from geometry_msgs.msg import Twist from sensor_msgs.msg import Image from rgb_hsv import BGR_HSV class LineFollower(object): def __init__(self, rgb_to_track, colour_error = 10.0,colour_cal=False, camera_topic="/mybot/raspicam_node/image_raw", cmd_vel_topic="/mybot/cmd_vel"): self._colour_cal = colour_cal self._colour_error = colour_error self.rgb_hsv = BGR_HSV() self.hsv, hsv_numpy_percentage = self.rgb_hsv.rgb_hsv(rgb=rgb_to_track) # We check which OpenCV version is installed. (self.major, minor, _) = cv2.__version__.split(".") rospy.logwarn("OpenCV Version Installed==>"+str(self.major)) # This way we process only half the frames self.process_this_frame = True self.droped_frames = 0 # 1 LEFT, -1 Right, 0 NO TURN self.last_turn = 0 self.bridge_object = CvBridge() self.image_sub = rospy.Subscriber(camera_topic, Image, self.camera_callback) self.cmd_vel_pub = rospy.Publisher(cmd_vel_topic, Twist, queue_size=1) def camera_callback(self, data): # It seems that making tests, the rapsicam doesnt update the image until 6 frames have passed self.process_this_frame = self.droped_frames >= 2 if self.process_this_frame: # We reset the counter #print("Process Frame, Dropped frame to==" + str(self.droped_frames)) self.droped_frames = 0 try: # We select bgr8 because its the OpenCV encoding by default cv_image = self.bridge_object.imgmsg_to_cv2(data, desired_encoding="bgr8") except CvBridgeError as e: print(e) cv_image = None if cv_image is not None: small_frame = cv2.resize(cv_image, (0, 0), fx=0.1, fy=0.1) height, width, channels = small_frame.shape rospy.logdebug("height=%s, width=%s" % (str(height), str(width))) #descentre = 160 #rows_to_watch = 100 #crop_img = small_frame[(height) / 2 + descentre:(height) / 2 + (descentre + rows_to_watch)][1:width] crop_img = small_frame # Convert from RGB to HSV hsv = cv2.cvtColor(crop_img, cv2.COLOR_BGR2HSV) min_hsv = self.hsv * (1.0-(self._colour_error / 100.0)) max_hsv = self.hsv * (1.0 + (self._colour_error / 100.0)) lower_yellow = np.array(min_hsv) upper_yellow = np.array(max_hsv) # Threshold the HSV image to get only yellow colors mask = cv2.inRange(hsv, lower_yellow, upper_yellow) # Bitwise-AND mask and original image res = cv2.bitwise_and(crop_img, crop_img, mask=mask) if self.major == '3': # If its 3 (_, contours, _) = cv2.findContours(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_L1) else: # If its 2 or 4 (contours, _) = cv2.findContours(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_L1) rospy.logdebug("Number of centroids==>" + str(len(contours))) centres = [] for i in range(len(contours)): moments = cv2.moments(contours[i]) try: centres.append((int(moments['m10'] / moments['m00']), int(moments['m01'] / moments['m00']))) cv2.circle(res, centres[-1], 10, (0, 255, 0), -1) except ZeroDivisionError: pass rospy.logdebug(str(centres)) centroids_detected = [] if len(centres) > 0: try: cx = centres[0][0] cy = centres[0][1] rospy.loginfo("Centroid FOUND ==" + str(cx) + "," + str(cy) + "") except: cy, cx = height / 2, width / 2 centroids_detected.append([cx,cy]) # Draw the centroid in the result image cv2.circle(res, (int(cx), int(cy)), 5, (0, 0, 255), -1) if self._colour_cal: cv2.imshow("Original", small_frame) cv2.waitKey(1) else: cv2.imshow("RES", res) cv2.waitKey(1) # We send data from the first cetroid we get if len(centroids_detected) > 0: cx_final = centroids_detected[0][0] cy_final = centroids_detected[0][1] else: cx_final = None cy_final = None self.move_robot(height, width, cx_final, cy_final) else: pass else: self.droped_frames += 1 #print("Droped Frames==" + str(self.droped_frames)) def move_robot(self, image_dim_y, image_dim_x, cx, cy, linear_vel_base = 0.4, lineal_vel_min= 0.23, angular_vel_base = 0.2, movement_time = 0.02): """ It move the Robot based on the Centroid Data image_dim_x=96, image_dim_y=128 cx, cy = [(77, 71)] """ cmd_vel = Twist() cmd_vel.linear.x = 0.0 cmd_vel.angular.z = 0.0 cmd_vel_simple = Twist() FACTOR_LINEAR = 0.001 FACTOR_ANGULAR = 0.1 delta_left_percentage_not_important = 0.1 min_lin = 0.26 min_ang = 0.7 if cx is not None and cy is not None: origin = [image_dim_x / 2.0, image_dim_y / 2.0] centroid = [cx, cy] delta_left_right = centroid[0] - origin[0] print("delta_left_right===>" + str(delta_left_right)) if delta_left_right <= image_dim_x * delta_left_percentage_not_important: print("delta_left_right TO SMALL <=" + str(image_dim_x* delta_left_percentage_not_important)) delta_left_right = 0.0 delta = [delta_left_right, centroid[1]] # -1 because when delta is positive we want to turn right, which means sending a negative angular cmd_vel.angular.z = angular_vel_base * delta[0] * FACTOR_ANGULAR * -1 # If its further away it has to go faster, closer then slower # We place a minimum based on the real robot. Below this cmd_vel the robot just doesnt move properly cmd_vel.linear.x = linear_vel_base - delta[1] * FACTOR_LINEAR if cmd_vel.angular.z > 0: self.last_turn = 1 elif cmd_vel.angular.z < 0: self.last_turn = -1 elif cmd_vel.angular.z == 0: self.last_turn = 0 else: cmd_vel.linear.x = 0.0 if self.last_turn > 0: cmd_vel.angular.z = -angular_vel_base elif self.last_turn <= 0: cmd_vel.angular.z = angular_vel_base #print("NO CENTROID DETECTED...SEARCHING...") if cmd_vel.linear.x > 0: cmd_vel_simple.linear.x = min_lin elif cmd_vel.linear.x < 0: cmd_vel_simple.linear.x = -min_lin elif cmd_vel.linear.x == 0: cmd_vel_simple.linear.x = 0 if cmd_vel.angular.z > 0: cmd_vel_simple.angular.z = min_ang elif cmd_vel.angular.z < 0: cmd_vel_simple.angular.z = -min_ang elif cmd_vel.angular.z == 0: cmd_vel_simple.angular.z = 0 print("SPEED==>["+str(cmd_vel_simple.linear.x)+","+str(cmd_vel_simple.angular.z)+"]") self.cmd_vel_pub.publish(cmd_vel_simple) # We move for only a fraction of time init_time = rospy.get_time() finished_movement_time = False rate_object = rospy.Rate(10) while not finished_movement_time: now_time = rospy.get_time() delta = now_time - init_time finished_movement_time = delta >= movement_time rate_object.sleep() cmd_vel.linear.x = 0.0 cmd_vel.angular.z = 0.0 self.cmd_vel_pub.publish(cmd_vel) #print("Movement Finished...") def loop(self): rospy.spin() if __name__ == '__main__': rospy.init_node('line_follower_start', anonymous=True) rospy.loginfo(str(len(sys.argv))) rospy.loginfo(str(sys.argv)) if len(sys.argv) > 5: red_value = int(float(sys.argv[1])) green_value = int(float(sys.argv[2])) blue_value = int(float(sys.argv[3])) colour_error_value = float(sys.argv[4]) mode_value = sys.argv[5] is_colour_cal = mode_value == "colour_cal" #rgb_to_track = [255,255,255] rgb_to_track = [red_value, green_value, blue_value] robot_mover = LineFollower(rgb_to_track=rgb_to_track, colour_error= colour_error_value, colour_cal=is_colour_cal) robot_mover.loop()
[ "rospy.init_node", "cv2.imshow", "numpy.array", "rospy.Rate", "cv2.__version__.split", "cv_bridge.CvBridge", "rospy.spin", "rospy.Subscriber", "cv2.waitKey", "geometry_msgs.msg.Twist", "cv2.circle", "cv2.cvtColor", "cv2.moments", "cv2.resize", "rospy.Publisher", "rgb_hsv.BGR_HSV", "r...
[((8524, 8578), 'rospy.init_node', 'rospy.init_node', (['"""line_follower_start"""'], {'anonymous': '(True)'}), "('line_follower_start', anonymous=True)\n", (8539, 8578), False, 'import rospy\n'), ((509, 518), 'rgb_hsv.BGR_HSV', 'BGR_HSV', ([], {}), '()\n', (516, 518), False, 'from rgb_hsv import BGR_HSV\n'), ((686, 712), 'cv2.__version__.split', 'cv2.__version__.split', (['"""."""'], {}), "('.')\n", (707, 712), False, 'import cv2\n'), ((999, 1009), 'cv_bridge.CvBridge', 'CvBridge', ([], {}), '()\n', (1007, 1009), False, 'from cv_bridge import CvBridge, CvBridgeError\n'), ((1035, 1094), 'rospy.Subscriber', 'rospy.Subscriber', (['camera_topic', 'Image', 'self.camera_callback'], {}), '(camera_topic, Image, self.camera_callback)\n', (1051, 1094), False, 'import rospy\n'), ((1122, 1173), 'rospy.Publisher', 'rospy.Publisher', (['cmd_vel_topic', 'Twist'], {'queue_size': '(1)'}), '(cmd_vel_topic, Twist, queue_size=1)\n', (1137, 1173), False, 'import rospy\n'), ((5494, 5501), 'geometry_msgs.msg.Twist', 'Twist', ([], {}), '()\n', (5499, 5501), False, 'from geometry_msgs.msg import Twist\n'), ((5591, 5598), 'geometry_msgs.msg.Twist', 'Twist', ([], {}), '()\n', (5596, 5598), False, 'from geometry_msgs.msg import Twist\n'), ((7997, 8013), 'rospy.get_time', 'rospy.get_time', ([], {}), '()\n', (8011, 8013), False, 'import rospy\n'), ((8075, 8089), 'rospy.Rate', 'rospy.Rate', (['(10)'], {}), '(10)\n', (8085, 8089), False, 'import rospy\n'), ((8479, 8491), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (8489, 8491), False, 'import rospy\n'), ((8155, 8171), 'rospy.get_time', 'rospy.get_time', ([], {}), '()\n', (8169, 8171), False, 'import rospy\n'), ((1910, 1954), 'cv2.resize', 'cv2.resize', (['cv_image', '(0, 0)'], {'fx': '(0.1)', 'fy': '(0.1)'}), '(cv_image, (0, 0), fx=0.1, fy=0.1)\n', (1920, 1954), False, 'import cv2\n'), ((2392, 2433), 'cv2.cvtColor', 'cv2.cvtColor', (['crop_img', 'cv2.COLOR_BGR2HSV'], {}), '(crop_img, cv2.COLOR_BGR2HSV)\n', (2404, 2433), False, 'import cv2\n'), ((2612, 2629), 'numpy.array', 'np.array', (['min_hsv'], {}), '(min_hsv)\n', (2620, 2629), True, 'import numpy as np\n'), ((2661, 2678), 'numpy.array', 'np.array', (['max_hsv'], {}), '(max_hsv)\n', (2669, 2678), True, 'import numpy as np\n'), ((2771, 2815), 'cv2.inRange', 'cv2.inRange', (['hsv', 'lower_yellow', 'upper_yellow'], {}), '(hsv, lower_yellow, upper_yellow)\n', (2782, 2815), False, 'import cv2\n'), ((2893, 2939), 'cv2.bitwise_and', 'cv2.bitwise_and', (['crop_img', 'crop_img'], {'mask': 'mask'}), '(crop_img, crop_img, mask=mask)\n', (2908, 2939), False, 'import cv2\n'), ((3049, 3113), 'cv2.findContours', 'cv2.findContours', (['mask', 'cv2.RETR_CCOMP', 'cv2.CHAIN_APPROX_TC89_L1'], {}), '(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_L1)\n', (3065, 3113), False, 'import cv2\n'), ((3209, 3273), 'cv2.findContours', 'cv2.findContours', (['mask', 'cv2.RETR_CCOMP', 'cv2.CHAIN_APPROX_TC89_L1'], {}), '(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_L1)\n', (3225, 3273), False, 'import cv2\n'), ((3458, 3482), 'cv2.moments', 'cv2.moments', (['contours[i]'], {}), '(contours[i])\n', (3469, 3482), False, 'import cv2\n'), ((4432, 4467), 'cv2.imshow', 'cv2.imshow', (['"""Original"""', 'small_frame'], {}), "('Original', small_frame)\n", (4442, 4467), False, 'import cv2\n'), ((4488, 4502), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (4499, 4502), False, 'import cv2\n'), ((4545, 4567), 'cv2.imshow', 'cv2.imshow', (['"""RES"""', 'res'], {}), "('RES', res)\n", (4555, 4567), False, 'import cv2\n'), ((4588, 4602), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (4599, 4602), False, 'import cv2\n'), ((3649, 3698), 'cv2.circle', 'cv2.circle', (['res', 'centres[-1]', '(10)', '(0, 255, 0)', '(-1)'], {}), '(res, centres[-1], 10, (0, 255, 0), -1)\n', (3659, 3698), False, 'import cv2\n')]
import logging import cv2 import numpy as np import PIL from dice_roller import roll_value from spoilers.abstract_filter import AbstractFilter class TextSpoiler(AbstractFilter): """Dilate text and replace with grey.""" def __init__(self, grey=127, dilate_k=3, **kwargs): super(TextSpoiler, self).__init__(**kwargs) self.grey = grey self.dilate_k = dilate_k def run(self, image): grey = roll_value(self.grey) dilate_k = roll_value(self.dilate_k) logging.debug(f"Running TextSpoilere with grey: {grey} and kernel {dilate_k}") cv_im = np.array(image._img) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (dilate_k, dilate_k)) dilated = cv2.morphologyEx(cv_im, cv2.MORPH_ERODE, kernel) dilated[dilated < 120] = grey pil_im = PIL.Image.fromarray(dilated) image._img = pil_im return image
[ "PIL.Image.fromarray", "logging.debug", "numpy.array", "cv2.morphologyEx", "cv2.getStructuringElement", "dice_roller.roll_value" ]
[((436, 457), 'dice_roller.roll_value', 'roll_value', (['self.grey'], {}), '(self.grey)\n', (446, 457), False, 'from dice_roller import roll_value\n'), ((477, 502), 'dice_roller.roll_value', 'roll_value', (['self.dilate_k'], {}), '(self.dilate_k)\n', (487, 502), False, 'from dice_roller import roll_value\n'), ((511, 589), 'logging.debug', 'logging.debug', (['f"""Running TextSpoilere with grey: {grey} and kernel {dilate_k}"""'], {}), "(f'Running TextSpoilere with grey: {grey} and kernel {dilate_k}')\n", (524, 589), False, 'import logging\n'), ((606, 626), 'numpy.array', 'np.array', (['image._img'], {}), '(image._img)\n', (614, 626), True, 'import numpy as np\n'), ((645, 709), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_CROSS', '(dilate_k, dilate_k)'], {}), '(cv2.MORPH_CROSS, (dilate_k, dilate_k))\n', (670, 709), False, 'import cv2\n'), ((728, 776), 'cv2.morphologyEx', 'cv2.morphologyEx', (['cv_im', 'cv2.MORPH_ERODE', 'kernel'], {}), '(cv_im, cv2.MORPH_ERODE, kernel)\n', (744, 776), False, 'import cv2\n'), ((832, 860), 'PIL.Image.fromarray', 'PIL.Image.fromarray', (['dilated'], {}), '(dilated)\n', (851, 860), False, 'import PIL\n')]
# coding: utf-8 from keras.applications.vgg19 import VGG19 from keras.preprocessing import image from keras.applications.vgg19 import preprocess_input from keras.models import Model import numpy as np base_model = VGG19(weights='imagenet', include_top=True) model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc2').output) img_path = '../mdataset/img_test/p2.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) fc2 = model.predict(x) print(fc2.shape) #(1, 4096)
[ "keras.preprocessing.image.img_to_array", "keras.applications.vgg19.preprocess_input", "keras.applications.vgg19.VGG19", "numpy.expand_dims", "keras.preprocessing.image.load_img" ]
[((214, 257), 'keras.applications.vgg19.VGG19', 'VGG19', ([], {'weights': '"""imagenet"""', 'include_top': '(True)'}), "(weights='imagenet', include_top=True)\n", (219, 257), False, 'from keras.applications.vgg19 import VGG19\n'), ((388, 436), 'keras.preprocessing.image.load_img', 'image.load_img', (['img_path'], {'target_size': '(224, 224)'}), '(img_path, target_size=(224, 224))\n', (402, 436), False, 'from keras.preprocessing import image\n'), ((441, 464), 'keras.preprocessing.image.img_to_array', 'image.img_to_array', (['img'], {}), '(img)\n', (459, 464), False, 'from keras.preprocessing import image\n'), ((469, 494), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (483, 494), True, 'import numpy as np\n'), ((499, 518), 'keras.applications.vgg19.preprocess_input', 'preprocess_input', (['x'], {}), '(x)\n', (515, 518), False, 'from keras.applications.vgg19 import preprocess_input\n')]
import numpy as np from pandas import DataFrame from tensorflow.keras.preprocessing.sequence import pad_sequences import csv import os class ECGDataIterator: def __init__(self, f, subsample=1): self.ifd = open(f, "rb") self._ss = subsample self._offset = 2048 def __next__(self): chIb = self.ifd.read(2) if chIb == b'': self.ifd.close() raise StopIteration chI = int.from_bytes(chIb, byteorder="little") - self._offset chIII = int.from_bytes(self.ifd.read(2), byteorder="little") - self._offset # move pointer 4 bytes times subsampling to next data if self._ss > 1: self.ifd.seek(4*(self._ss-1), 1) return chI, chIII def __iter__(self): return self def extract_data(file_list, sample_rate=125, subsample=1, duration=42): fs = sample_rate // subsample num_samples = duration * fs length = len(file_list) x = np.empty((length, num_samples, 2)) y = np.empty(length) for i, f in enumerate(file_list): data = DataFrame(ECGDataIterator(f, subsample)).to_numpy().T data = pad_sequences(data, maxlen=num_samples, padding='pre', truncating='pre') x[i, :] = data.T y[i] = 0 if 'sinus' in f else 1 return x, y def extract_ecg_file_list(datafolder, csvfile): file_list = list() with open(os.path.join(datafolder, csvfile)) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: file_list.append(os.path.join(datafolder, row[0])) return file_list
[ "os.path.join", "numpy.empty", "csv.reader", "tensorflow.keras.preprocessing.sequence.pad_sequences" ]
[((966, 1000), 'numpy.empty', 'np.empty', (['(length, num_samples, 2)'], {}), '((length, num_samples, 2))\n', (974, 1000), True, 'import numpy as np\n'), ((1009, 1025), 'numpy.empty', 'np.empty', (['length'], {}), '(length)\n', (1017, 1025), True, 'import numpy as np\n'), ((1148, 1220), 'tensorflow.keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['data'], {'maxlen': 'num_samples', 'padding': '"""pre"""', 'truncating': '"""pre"""'}), "(data, maxlen=num_samples, padding='pre', truncating='pre')\n", (1161, 1220), False, 'from tensorflow.keras.preprocessing.sequence import pad_sequences\n'), ((1458, 1493), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (1468, 1493), False, 'import csv\n'), ((1389, 1422), 'os.path.join', 'os.path.join', (['datafolder', 'csvfile'], {}), '(datafolder, csvfile)\n', (1401, 1422), False, 'import os\n'), ((1554, 1586), 'os.path.join', 'os.path.join', (['datafolder', 'row[0]'], {}), '(datafolder, row[0])\n', (1566, 1586), False, 'import os\n')]
from sampi.sdes.util import draw_brownian from sampi.sdes.solvers import euler_maruyama import numpy as np class StochDiffEq(): def __init__(self, drift=lambda x, t : 1, diffusion=lambda x, t : 1, true_sol=None, eqn=""): self.drift = drift self.diffusion = diffusion self.true_sol = true_sol self.eqn = eqn def draw_true(self, x0, t, nsamps=1): wt = draw_brownian(t, nsamps=nsamps) t_copied = np.repeat(t[:, np.newaxis], nsamps, axis=1) return self.true_sol(x0, t_copied, wt) def solve(self, x0, t_end, method="euler-maruyama", nsamps=1, **kwargs): """General solver to call other methods from. Args: y0 (array): the RHS function for the derivative of y (think y' = func(y, t)). t_end (float): the time to solve the ODE up until. method (str): the time to solve the ODE up until. Returns: (y_sol, t): The return value. True for success, False otherwise. """ if method == "euler-maruyama": return euler_maruyama(self.drift, self.diffusion, x0, t_end, nsamps=nsamps, **kwargs)
[ "sampi.sdes.solvers.euler_maruyama", "sampi.sdes.util.draw_brownian", "numpy.repeat" ]
[((402, 433), 'sampi.sdes.util.draw_brownian', 'draw_brownian', (['t'], {'nsamps': 'nsamps'}), '(t, nsamps=nsamps)\n', (415, 433), False, 'from sampi.sdes.util import draw_brownian\n'), ((453, 496), 'numpy.repeat', 'np.repeat', (['t[:, np.newaxis]', 'nsamps'], {'axis': '(1)'}), '(t[:, np.newaxis], nsamps, axis=1)\n', (462, 496), True, 'import numpy as np\n'), ((1113, 1191), 'sampi.sdes.solvers.euler_maruyama', 'euler_maruyama', (['self.drift', 'self.diffusion', 'x0', 't_end'], {'nsamps': 'nsamps'}), '(self.drift, self.diffusion, x0, t_end, nsamps=nsamps, **kwargs)\n', (1127, 1191), False, 'from sampi.sdes.solvers import euler_maruyama\n')]
######################################################################################################################## #WORD2VEC MODEL ######################################################################################################################## # Import libaries from sklearn.manifold import TSNE from random import shuffle import time import datetime import pickle import collections import math import os import random import numpy as np import tensorflow as tf import pandas # Import config file from config import FLAGS class Word2vec(): def __init__(self, embedding_size = 100, skip_window = 5, num_skips = 2, max_vocab_size= 80000, min_occurrences = 5, batch_size = 128, learning_rate= 0.05, num_sampled = 3, sample = 1e-4, dir_vocab = None, dict_words = None): self.embedding_size = embedding_size self.vocab_size = max_vocab_size self.min_occurrences = min_occurrences self.batch_size = batch_size self.learning_rate = learning_rate self.cooccurrence_matrix = None self.embeddings = None self.dir_vocab = dir_vocab self.word_to_id = None self.data_index = 0 self.skip_window = self.left_context = self.right_context = skip_window self.num_skips = num_skips self.num_sampled = num_sampled * self.batch_size self.sample = sample self.word_to_id = dict_words self.words = list(dict_words.keys()) self.prob_vocab = {} print(self.words) print(len(self.words)) print(self.words[:10]) # Load vocabulary if self.dir_vocab != None: with open(self.dir_vocab, 'rb') as f: self.word_to_id = pickle.load(f) self.words = sorted(self.word_to_id, key=self.word_to_id.get) # Output directory self.timestamp = str(int(time.time())) self.out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", self.timestamp)) os.makedirs(self.out_dir) def fit_to_corpus(self, corpus): # Load data and build the graph self.compute_prob(corpus) self.build_sampling(corpus) self.build_graph() def compute_prob(self,corpus): # Count per word counter = collections.Counter([item for sublist in corpus for item in sublist]) special_tab_counter = counter.most_common(3) threshold_count = (sum(counter.values()) - sum(dict(special_tab_counter).values())) * self.sample for w in counter.keys(): v = counter[w] word_probability = (np.sqrt(v / threshold_count) + 1) * (threshold_count / v) if word_probability > 1.0: word_probability = 1.0 self.prob_vocab[w] = word_probability result = pandas.DataFrame(np.transpose(np.vstack((np.array(list(self.prob_vocab.keys())), np.array(list(self.prob_vocab.values())))))) result.to_csv("prob.csv") def build_sampling(self, corpus): batch = [] labels = [] # Reorder the words by frequency # Process each sentence and perform subsampling j = 0 start = time.time() end = time.time() print("Time counting: {}".format(str(end - start))) for sentence in corpus: word_vocabs = [self.word_to_id[w] for w in sentence if self.prob_vocab[w] > np.random.rand()] right_size = left_size = np.random.randint(self.skip_window, size = len(word_vocabs)) + 1 for l_context, word, r_context in context_windows(word_vocabs, left_size, right_size): for i, context_word in enumerate(l_context[::-1]): labels.append(context_word) batch.append(word) for i, context_word in enumerate(r_context): labels.append(context_word) batch.append(word) if j % 100000 == 0: end = time.time() print("Time counting: {}".format(str(end - start))) print(j) start = time.time() j +=1 # Save output self.labels = np.reshape(np.array(labels),(np.array(labels).shape[0], 1)) self.inputs = np.array(batch) def create_batches(self, labels, inputs): # Calculate number of batches self.num_batches = int(labels.shape[0] / self.batch_size) + 1 # Add random sentence to complete batches num_add_integers = ((self.num_batches) * self.batch_size) - labels.shape[0] rand_indices = np.random.choice(labels.shape[0],num_add_integers) self.labels = np.vstack((labels, labels[rand_indices,:])) print(self.labels.shape) self.inputs = np.hstack((inputs, inputs[rand_indices])).flatten() print(self.labels.shape) print(self.inputs.shape) # Split data into batches self.labels = np.split(self.labels, self.num_batches) self.inputs = np.split(self.inputs, self.num_batches) # Step 3: Function to generate a training batch for the skip-gram model. def generate_batch(self,batch_size, num_skips, skip_window): # Assert conditions assert batch_size % num_skips == 0 assert num_skips <= 2 * skip_window # Initialize arrays batch = np.ndarray(shape=(batch_size), dtype=np.int32) labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32) span = 2 * skip_window + 1 # [ skip_window target skip_window ] buffer = collections.deque(maxlen=span) # For loop to get the data for _ in range(span): buffer.append(self.data[self.data_index]) self.data_index = (self.data_index + 1) % len(self.data) # For loop to sample context given a world for i in range(batch_size // num_skips): target = skip_window # target label at the center of the buffer targets_to_avoid = [skip_window] for j in range(num_skips): while target in targets_to_avoid: target = random.randint(0, span - 1) targets_to_avoid.append(target) batch[i * num_skips + j] = buffer[skip_window] labels[i * num_skips + j, 0] = buffer[target] buffer.append(self.data[self.data_index]) self.data_index = (self.data_index + 1) % len(self.data) # Backtrack a little bit to avoid skipping words in the end of a batch self.data_index = (self.data_index + len(self.data) - span) % len(self.data) return batch, labels def build_graph(self): self.graph = tf.Graph() with self.graph.as_default(): # Set random seed tf.set_random_seed(13) # Define inputs self.train_inputs = tf.placeholder(tf.int32, shape=[self.batch_size]) # Define labels self.train_labels = tf.placeholder(tf.int32, shape=[self.batch_size,1]) # Look up embeddings for inputs. self.embeddings = tf.Variable(tf.random_uniform([self.vocab_size, self.embedding_size], -1.0, 1.0)) embed = tf.nn.embedding_lookup(self.embeddings, self.train_inputs) # Construct the variables for the NCE loss nce_weights = tf.Variable(tf.truncated_normal([self.vocab_size, self.embedding_size], stddev=1.0 / math.sqrt(self.embedding_size))) nce_biases = tf.Variable(tf.zeros([self.vocab_size])) # Compute the average NCE loss for the batch. self.total_loss = tf.reduce_mean(tf.nn.nce_loss(weights = nce_weights, biases = nce_biases,labels = self.train_labels, inputs = embed, num_sampled = self.num_sampled, num_classes = self.vocab_size), name = "sum_losses") # Construct the SGD optimizer using a learning rate of 1.0. self.optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(self.total_loss) # Compute the cosine similarity between minibatch examples and all embeddings. norm = tf.sqrt(tf.reduce_sum(tf.square(self.embeddings), 1, keep_dims=True)) self.normalized_embeddings = self.embeddings / norm def train(self): # Lauch tensorflow session with tf.Session(graph=self.graph) as session: # Output directory for models and summaries print("Writing to {}\n".format(self.out_dir)) total_steps = 0 # Summaries for loss loss_summary = tf.summary.scalar("loss", self.total_loss) # Train Summaries train_summary_op = tf.summary.merge([loss_summary]) train_summary_dir = os.path.join(self.out_dir, "summaries", "train") train_summary_writer = tf.summary.FileWriter(train_summary_dir, session.graph) # Checkpoint directory (Tensorflow assumes this directory already exists so we need to create it) checkpoint_dir = os.path.abspath(os.path.join(self.out_dir, "checkpoints")) checkpoint_prefix = os.path.join(checkpoint_dir, "model") if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) saver = tf.train.Saver(max_to_keep=FLAGS.num_checkpoints) # Initialize variables tf.global_variables_initializer().run() session.graph.finalize() # Generate batches self.create_batches(self.labels, self.inputs) # Run training procedure for epoch in range(FLAGS.num_epochs): # Shuffle perm_idx = np.random.permutation(len(self.labels)).tolist() for batch_index in perm_idx: # Define feed dictionary feed_dict = {self.train_inputs: self.inputs[batch_index], self.train_labels: self.labels[batch_index]} # Run optimization _, mean_loss, summaries = session.run([self.optimizer, self.total_loss, train_summary_op], feed_dict=feed_dict) time_str = datetime.datetime.now().isoformat() if total_steps % FLAGS.evaluate_every == 0: train_summary_writer.add_summary(summaries, total_steps) print("{}: step {}, loss {:g}".format(time_str, total_steps, mean_loss)) if total_steps % FLAGS.checkpoint_every == 0: path = saver.save(session, checkpoint_prefix, global_step=total_steps) print("Saved model checkpoint to {}\n".format(path)) total_steps += 1 current_embeddings = self.embeddings.eval() current_embeddings_normalized = self.normalized_embeddings.eval() output_path = os.path.join(self.out_dir, "epoch{:03d}.png".format(epoch + 1)) self.generate_tsne(output_path, embeddings = current_embeddings) # Save output np.save(os.path.join(self.out_dir, "embeddings_word2vec"), current_embeddings) np.save(os.path.join(self.out_dir, "embeddings_word2vec_normalized"), current_embeddings_normalized) def generate_tsne(self, path=None, size=(100, 100), word_count=2500, embeddings=None): if embeddings is None: embeddings = self.embeddings tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000) low_dim_embs = tsne.fit_transform(embeddings[:word_count, :]) labels = self.words[:word_count] return _plot_with_labels(low_dim_embs, labels, path, size) def _plot_with_labels(low_dim_embs, labels, path, size): import matplotlib.pyplot as plt assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings" figure = plt.figure(figsize=size) # in inches for i, label in enumerate(labels): x, y = low_dim_embs[i, :] plt.scatter(x, y) plt.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom') if path is not None: figure.savefig(path) plt.close(figure) def context_windows(region, left_size_window, right_size_window): for i, word in enumerate(region): if left_size_window.shape[0] > 1 or right_size_window.shape[0] > 1: left_size = left_size_window[i] right_size = right_size_window[i] else: left_size = left_size_window right_size = right_size_window start_index = i - left_size end_index = i + right_size left_context = window(region, start_index, i - 1) right_context = window(region, i + 1, end_index) yield (left_context, word, right_context) def window(region, start_index, end_index): """ Returns the list of words starting from `start_index`, going to `end_index` taken from region. If `start_index` is a negative number, or if `end_index` is greater than the index of the last word in region, this function will pad its return value with `NULL_WORD`. """ last_index = len(region) - 1 selected_tokens = region[max(start_index, 0): (min(end_index, last_index) + 1)] return selected_tokens
[ "numpy.sqrt", "numpy.random.rand", "numpy.hstack", "math.sqrt", "numpy.array", "matplotlib.pyplot.annotate", "tensorflow.set_random_seed", "tensorflow.Graph", "tensorflow.nn.embedding_lookup", "os.path.exists", "collections.deque", "tensorflow.placeholder", "tensorflow.Session", "sklearn.m...
[((11881, 11905), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'size'}), '(figsize=size)\n', (11891, 11905), True, 'import matplotlib.pyplot as plt\n'), ((2016, 2041), 'os.makedirs', 'os.makedirs', (['self.out_dir'], {}), '(self.out_dir)\n', (2027, 2041), False, 'import os\n'), ((2296, 2365), 'collections.Counter', 'collections.Counter', (['[item for sublist in corpus for item in sublist]'], {}), '([item for sublist in corpus for item in sublist])\n', (2315, 2365), False, 'import collections\n'), ((3186, 3197), 'time.time', 'time.time', ([], {}), '()\n', (3195, 3197), False, 'import time\n'), ((3212, 3223), 'time.time', 'time.time', ([], {}), '()\n', (3221, 3223), False, 'import time\n'), ((4265, 4280), 'numpy.array', 'np.array', (['batch'], {}), '(batch)\n', (4273, 4280), True, 'import numpy as np\n'), ((4595, 4646), 'numpy.random.choice', 'np.random.choice', (['labels.shape[0]', 'num_add_integers'], {}), '(labels.shape[0], num_add_integers)\n', (4611, 4646), True, 'import numpy as np\n'), ((4668, 4712), 'numpy.vstack', 'np.vstack', (['(labels, labels[rand_indices, :])'], {}), '((labels, labels[rand_indices, :]))\n', (4677, 4712), True, 'import numpy as np\n'), ((4942, 4981), 'numpy.split', 'np.split', (['self.labels', 'self.num_batches'], {}), '(self.labels, self.num_batches)\n', (4950, 4981), True, 'import numpy as np\n'), ((5004, 5043), 'numpy.split', 'np.split', (['self.inputs', 'self.num_batches'], {}), '(self.inputs, self.num_batches)\n', (5012, 5043), True, 'import numpy as np\n'), ((5347, 5391), 'numpy.ndarray', 'np.ndarray', ([], {'shape': 'batch_size', 'dtype': 'np.int32'}), '(shape=batch_size, dtype=np.int32)\n', (5357, 5391), True, 'import numpy as np\n'), ((5411, 5460), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(batch_size, 1)', 'dtype': 'np.int32'}), '(shape=(batch_size, 1), dtype=np.int32)\n', (5421, 5460), True, 'import numpy as np\n'), ((5551, 5581), 'collections.deque', 'collections.deque', ([], {'maxlen': 'span'}), '(maxlen=span)\n', (5568, 5581), False, 'import collections\n'), ((6680, 6690), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (6688, 6690), True, 'import tensorflow as tf\n'), ((11456, 11516), 'sklearn.manifold.TSNE', 'TSNE', ([], {'perplexity': '(30)', 'n_components': '(2)', 'init': '"""pca"""', 'n_iter': '(5000)'}), "(perplexity=30, n_components=2, init='pca', n_iter=5000)\n", (11460, 11516), False, 'from sklearn.manifold import TSNE\n'), ((12000, 12017), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {}), '(x, y)\n', (12011, 12017), True, 'import matplotlib.pyplot as plt\n'), ((12026, 12128), 'matplotlib.pyplot.annotate', 'plt.annotate', (['label'], {'xy': '(x, y)', 'xytext': '(5, 2)', 'textcoords': '"""offset points"""', 'ha': '"""right"""', 'va': '"""bottom"""'}), "(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',\n ha='right', va='bottom')\n", (12038, 12128), True, 'import matplotlib.pyplot as plt\n'), ((12187, 12204), 'matplotlib.pyplot.close', 'plt.close', (['figure'], {}), '(figure)\n', (12196, 12204), True, 'import matplotlib.pyplot as plt\n'), ((1954, 2006), 'os.path.join', 'os.path.join', (['os.path.curdir', '"""runs"""', 'self.timestamp'], {}), "(os.path.curdir, 'runs', self.timestamp)\n", (1966, 2006), False, 'import os\n'), ((4194, 4210), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (4202, 4210), True, 'import numpy as np\n'), ((6771, 6793), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(13)'], {}), '(13)\n', (6789, 6793), True, 'import tensorflow as tf\n'), ((6854, 6903), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[self.batch_size]'}), '(tf.int32, shape=[self.batch_size])\n', (6868, 6903), True, 'import tensorflow as tf\n'), ((6964, 7016), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[self.batch_size, 1]'}), '(tf.int32, shape=[self.batch_size, 1])\n', (6978, 7016), True, 'import tensorflow as tf\n'), ((7194, 7252), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.embeddings', 'self.train_inputs'], {}), '(self.embeddings, self.train_inputs)\n', (7216, 7252), True, 'import tensorflow as tf\n'), ((8317, 8345), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'self.graph'}), '(graph=self.graph)\n', (8327, 8345), True, 'import tensorflow as tf\n'), ((8561, 8603), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""loss"""', 'self.total_loss'], {}), "('loss', self.total_loss)\n", (8578, 8603), True, 'import tensorflow as tf\n'), ((8666, 8698), 'tensorflow.summary.merge', 'tf.summary.merge', (['[loss_summary]'], {}), '([loss_summary])\n', (8682, 8698), True, 'import tensorflow as tf\n'), ((8731, 8779), 'os.path.join', 'os.path.join', (['self.out_dir', '"""summaries"""', '"""train"""'], {}), "(self.out_dir, 'summaries', 'train')\n", (8743, 8779), False, 'import os\n'), ((8815, 8870), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['train_summary_dir', 'session.graph'], {}), '(train_summary_dir, session.graph)\n', (8836, 8870), True, 'import tensorflow as tf\n'), ((9102, 9139), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""model"""'], {}), "(checkpoint_dir, 'model')\n", (9114, 9139), False, 'import os\n'), ((9255, 9304), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'max_to_keep': 'FLAGS.num_checkpoints'}), '(max_to_keep=FLAGS.num_checkpoints)\n', (9269, 9304), True, 'import tensorflow as tf\n'), ((1747, 1761), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1758, 1761), False, 'import pickle\n'), ((1901, 1912), 'time.time', 'time.time', ([], {}), '()\n', (1910, 1912), False, 'import time\n'), ((3979, 3990), 'time.time', 'time.time', ([], {}), '()\n', (3988, 3990), False, 'import time\n'), ((4108, 4119), 'time.time', 'time.time', ([], {}), '()\n', (4117, 4119), False, 'import time\n'), ((4767, 4808), 'numpy.hstack', 'np.hstack', (['(inputs, inputs[rand_indices])'], {}), '((inputs, inputs[rand_indices]))\n', (4776, 4808), True, 'import numpy as np\n'), ((7104, 7172), 'tensorflow.random_uniform', 'tf.random_uniform', (['[self.vocab_size, self.embedding_size]', '(-1.0)', '(1.0)'], {}), '([self.vocab_size, self.embedding_size], -1.0, 1.0)\n', (7121, 7172), True, 'import tensorflow as tf\n'), ((7502, 7529), 'tensorflow.zeros', 'tf.zeros', (['[self.vocab_size]'], {}), '([self.vocab_size])\n', (7510, 7529), True, 'import tensorflow as tf\n'), ((7635, 7798), 'tensorflow.nn.nce_loss', 'tf.nn.nce_loss', ([], {'weights': 'nce_weights', 'biases': 'nce_biases', 'labels': 'self.train_labels', 'inputs': 'embed', 'num_sampled': 'self.num_sampled', 'num_classes': 'self.vocab_size'}), '(weights=nce_weights, biases=nce_biases, labels=self.\n train_labels, inputs=embed, num_sampled=self.num_sampled, num_classes=\n self.vocab_size)\n', (7649, 7798), True, 'import tensorflow as tf\n'), ((9027, 9068), 'os.path.join', 'os.path.join', (['self.out_dir', '"""checkpoints"""'], {}), "(self.out_dir, 'checkpoints')\n", (9039, 9068), False, 'import os\n'), ((9159, 9189), 'os.path.exists', 'os.path.exists', (['checkpoint_dir'], {}), '(checkpoint_dir)\n', (9173, 9189), False, 'import os\n'), ((9207, 9234), 'os.makedirs', 'os.makedirs', (['checkpoint_dir'], {}), '(checkpoint_dir)\n', (9218, 9234), False, 'import os\n'), ((2617, 2645), 'numpy.sqrt', 'np.sqrt', (['(v / threshold_count)'], {}), '(v / threshold_count)\n', (2624, 2645), True, 'import numpy as np\n'), ((6112, 6139), 'random.randint', 'random.randint', (['(0)', '(span - 1)'], {}), '(0, span - 1)\n', (6126, 6139), False, 'import random\n'), ((7936, 7974), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['(1.0)'], {}), '(1.0)\n', (7969, 7974), True, 'import tensorflow as tf\n'), ((8134, 8160), 'tensorflow.square', 'tf.square', (['self.embeddings'], {}), '(self.embeddings)\n', (8143, 8160), True, 'import tensorflow as tf\n'), ((9353, 9386), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (9384, 9386), True, 'import tensorflow as tf\n'), ((11089, 11138), 'os.path.join', 'os.path.join', (['self.out_dir', '"""embeddings_word2vec"""'], {}), "(self.out_dir, 'embeddings_word2vec')\n", (11101, 11138), False, 'import os\n'), ((11184, 11244), 'os.path.join', 'os.path.join', (['self.out_dir', '"""embeddings_word2vec_normalized"""'], {}), "(self.out_dir, 'embeddings_word2vec_normalized')\n", (11196, 11244), False, 'import os\n'), ((3404, 3420), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3418, 3420), True, 'import numpy as np\n'), ((4212, 4228), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (4220, 4228), True, 'import numpy as np\n'), ((7432, 7462), 'math.sqrt', 'math.sqrt', (['self.embedding_size'], {}), '(self.embedding_size)\n', (7441, 7462), False, 'import math\n'), ((10165, 10188), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (10186, 10188), False, 'import datetime\n')]
# -*- coding: utf-8 -*- # @Time : 2020/10/8 14:53 # @Author : Breeze # @Email : <EMAIL> """ 用于与接口交互 1、get到目标图片 2、将目标图片计算出像素值,从而在childIndex中映射得到"坐标",找到原图 3、将原图均分九块,目标图片也均分九块,分别计算每一块的像素值从而确定打乱了的目标图片的编号 4、将此编号返回与ai算法相结合 """ from PK.ai9 import ai as AI import numpy as np import requests import json from utils import getSequence import base64 url = "http://47.102.118.1:8089" def showQuiz(): api = "/api/challenge/list" Url = url + api re = requests.get(Url) te = eval(re.text) print("今天已有{}个赛题被发布".format(len(te))) for i in te: print(i) def showRecod(uid): api = "/api/challenge/record/" + uid Url = url + api re = requests.get(Url) te = eval(re.text) for i in te: print(i) def create(): api = "/api/challenge/create" Url = url + api po = { "teamid": 56, "data": { "letter": "b", "exclude": 9, "challenge": [ [7, 3, 5], [4, 0, 2], [6, 8, 1] ], "step": 7, "swap": [1, 3] }, "token": "<KEY>" } s = json.dumps(po) # print(s) headers = {'Content-Type': 'application/json'} r = requests.post(url=Url, headers=headers, data=s) print(r.text) def fight(uuid): api = "/api/challenge/start/" Url = url + api + uuid data = { "teamid": 56, "token": "<KEY>" } s = json.dumps(data) # print(s) headers = {'Content-Type': 'application/json'} r = requests.post(url=Url, headers=headers, data=s) r.text.replace("true", "none") te = r.text te = json.loads(te) # print(te) print("今日还剩挑战次数:{}".format(te["chanceleft"])) fightData = te["data"] img = base64.b64decode(fightData['img']) with open('test' + '.png', 'wb') as f: f.write(img) f.close() print("get test image successfully") print("saved to : ", './' + 'test' + '.png') origT, testT, step, swap, uuid = getSequence(1, fightData["step"], fightData["swap"], te["uuid"]) o = np.array(origT).reshape(3, 3) t = np.array(testT).reshape(3, 3) o = list(o.tolist()) t = list(t.tolist()) mmap = dict(zip(['MoveUp', 'MoveLeft', 'MoveDown', 'MoveRight'], ['w', 'a', 's', 'd'])) steps, swapped, seq = AI(t, o, swap, step) res = [mmap[i] for i in steps] print(res) p = ''.join(res) if len(seq) != 0: p = seq + p if swapped[0] == -1: swapped = [1, 1] submit(uuid, p, swapped) def submit(uuid, operation, swap): api = "/api/challenge/submit" Url = url + api swap[0] += 1 swap[1] += 1 datas = { "uuid": str(uuid), "teamid": 56, "token": "<KEY>", "answer": { "operations": str(operation), "swap": swap } } s = json.dumps(datas) print(s) headers = {'Content-Type': 'application/json'} r = requests.post(url=Url, headers=headers, data=s) print(r.text) def showRankList(): api = "/api/rank" Url = url + api re = requests.get(Url) te = eval(re.text) for i in te: print(i) def showTeamDetail(teamId): api = "/api/teamdetail/" Url = url + api + str(teamId) re = requests.get(Url) te = eval(re.text) print("当前排名:{}".format(te["rank"])) print("当前总得分{}".format(te['score'])) print("一共通过了{}道题目".format(len(te["success"]))) for i in te["success"]: print(i) print("一共失败了{}次".format(len(te['fail']))) for i in te["fail"]: print(i) def showProblem(teamId): api = "/api/team/problem/" Url = url + api + str(teamId) re = requests.get(Url) for i in eval(re.text): print(i) if __name__ == '__main__': # showQuiz() # print("-------------------------------------") # showProblem(56) # showRecod("05cddeb2-010b-47c9-8289-fababbec0e83") # create() # fight("954dae96-5f4f-4f3c-a09c-3119da0f5e9a") showRankList() # showTeamDetail(56)
[ "json.loads", "requests.post", "utils.getSequence", "json.dumps", "base64.b64decode", "requests.get", "numpy.array", "PK.ai9.ai" ]
[((479, 496), 'requests.get', 'requests.get', (['Url'], {}), '(Url)\n', (491, 496), False, 'import requests\n'), ((688, 705), 'requests.get', 'requests.get', (['Url'], {}), '(Url)\n', (700, 705), False, 'import requests\n'), ((1128, 1142), 'json.dumps', 'json.dumps', (['po'], {}), '(po)\n', (1138, 1142), False, 'import json\n'), ((1217, 1264), 'requests.post', 'requests.post', ([], {'url': 'Url', 'headers': 'headers', 'data': 's'}), '(url=Url, headers=headers, data=s)\n', (1230, 1264), False, 'import requests\n'), ((1437, 1453), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (1447, 1453), False, 'import json\n'), ((1528, 1575), 'requests.post', 'requests.post', ([], {'url': 'Url', 'headers': 'headers', 'data': 's'}), '(url=Url, headers=headers, data=s)\n', (1541, 1575), False, 'import requests\n'), ((1636, 1650), 'json.loads', 'json.loads', (['te'], {}), '(te)\n', (1646, 1650), False, 'import json\n'), ((1754, 1788), 'base64.b64decode', 'base64.b64decode', (["fightData['img']"], {}), "(fightData['img'])\n", (1770, 1788), False, 'import base64\n'), ((1994, 2058), 'utils.getSequence', 'getSequence', (['(1)', "fightData['step']", "fightData['swap']", "te['uuid']"], {}), "(1, fightData['step'], fightData['swap'], te['uuid'])\n", (2005, 2058), False, 'from utils import getSequence\n'), ((2303, 2323), 'PK.ai9.ai', 'AI', (['t', 'o', 'swap', 'step'], {}), '(t, o, swap, step)\n', (2305, 2323), True, 'from PK.ai9 import ai as AI\n'), ((2842, 2859), 'json.dumps', 'json.dumps', (['datas'], {}), '(datas)\n', (2852, 2859), False, 'import json\n'), ((2932, 2979), 'requests.post', 'requests.post', ([], {'url': 'Url', 'headers': 'headers', 'data': 's'}), '(url=Url, headers=headers, data=s)\n', (2945, 2979), False, 'import requests\n'), ((3071, 3088), 'requests.get', 'requests.get', (['Url'], {}), '(Url)\n', (3083, 3088), False, 'import requests\n'), ((3248, 3265), 'requests.get', 'requests.get', (['Url'], {}), '(Url)\n', (3260, 3265), False, 'import requests\n'), ((3656, 3673), 'requests.get', 'requests.get', (['Url'], {}), '(Url)\n', (3668, 3673), False, 'import requests\n'), ((2067, 2082), 'numpy.array', 'np.array', (['origT'], {}), '(origT)\n', (2075, 2082), True, 'import numpy as np\n'), ((2105, 2120), 'numpy.array', 'np.array', (['testT'], {}), '(testT)\n', (2113, 2120), True, 'import numpy as np\n')]
import numpy as np import xml.etree.ElementTree as ET import chainer from chainercv.utils import read_image from os import listdir from os.path import isfile, join from chainercv.datasets import voc_bbox_label_names LABEL_NAMES = ('other', 'berlinerdom', 'brandenburgertor', 'fernsehturm', 'funkturm', 'reichstag', 'rotesrathaus', 'siegessaeule') class XMLDataset(chainer.dataset.DatasetMixin): def __init__(self, data_dir, split='train'): self._img_ids = [join(data_dir, ''.join(f.split('.')[:-1])) for f in listdir(data_dir) if isfile(join(data_dir, f))] self._split = split def __len__(self): return int(len(self._img_ids) / 2) def get_example(self, i): """Returns the i-th example. Returns a color image and bounding boxes. The image is in CHW format. The returned image is RGB. Args: i (int): The index of the example. Returns: tuple of an image and bounding boxes and label """ if self._split == 'train': id_ = self._img_ids[i * 2] else: id_ = self._img_ids[i * 2 + 1] bbox = list() label = list() try: anno = ET.parse(id_ + '.xml') for obj in anno.findall('object'): bndbox_anno = obj.find('bndbox') # subtract 1 to make pixel indexes 0-based bbox.append([ int(bndbox_anno.find(tag).text) - 1 for tag in ('ymin', 'xmin', 'ymax', 'xmax')]) name = obj.find('name').text.lower().strip() label.append(LABEL_NAMES.index(name)) except FileNotFoundError: bbox.append([]) label.append([]) bbox = np.stack(bbox).astype(np.float32) label = np.stack(label).astype(np.int32) # Load a image img_file = id_ + '.jpg' img = read_image(img_file, color=True) return img, bbox, label
[ "os.listdir", "xml.etree.ElementTree.parse", "os.path.join", "numpy.stack", "chainercv.utils.read_image" ]
[((2045, 2077), 'chainercv.utils.read_image', 'read_image', (['img_file'], {'color': '(True)'}), '(img_file, color=True)\n', (2055, 2077), False, 'from chainercv.utils import read_image\n'), ((1341, 1363), 'xml.etree.ElementTree.parse', 'ET.parse', (["(id_ + '.xml')"], {}), "(id_ + '.xml')\n", (1349, 1363), True, 'import xml.etree.ElementTree as ET\n'), ((660, 677), 'os.listdir', 'listdir', (['data_dir'], {}), '(data_dir)\n', (667, 677), False, 'from os import listdir\n'), ((1892, 1906), 'numpy.stack', 'np.stack', (['bbox'], {}), '(bbox)\n', (1900, 1906), True, 'import numpy as np\n'), ((1942, 1957), 'numpy.stack', 'np.stack', (['label'], {}), '(label)\n', (1950, 1957), True, 'import numpy as np\n'), ((688, 705), 'os.path.join', 'join', (['data_dir', 'f'], {}), '(data_dir, f)\n', (692, 705), False, 'from os.path import isfile, join\n')]
import argparse from comet_ml import Experiment import numpy as np import copy import scipy.optimize import pandas as pd import operator import scipy.io import scipy import scipy.sparse import time import sys import os import matplotlib.pyplot as plt #Import mmort modules sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '..', 'mmort'))) import experiments # import optimization_tools # import evaluation import utils from config import configurations import torch import torch.nn.functional as F import torch.optim as optim parser = argparse.ArgumentParser(description='MMORT') parser.add_argument('--config_experiment', default = 'Experiment_1', type = str, help = 'Which experiment to run (Options: Experiment_1, Experiment_2). See config file for details') parser.add_argument('--lr', default=1e-3, type=float, help='Lr for Adam or SGD') parser.add_argument('--num_epochs', default=100, type=int, help='Number of epochs') parser.add_argument('--u_max', default=1000, type=float, help='Upper bound on u') parser.add_argument('--lambda_init', default=1e5, type=float, help='Initial value for lambda') parser.add_argument('--data_name', default = 'ProstateExample_BODY_not_reduced_with_OAR_constraints.mat', type = str) parser.add_argument('--precomputed', action='store_true', help='Use precomputed smoothed u for DVC initial guess') parser.add_argument('--initial_guess_for_dv', action='store_true', help='use initial guess for dvc solution') parser.add_argument('--save_dir', default = 'save_dir', type = str) parser.add_argument('--optimizer', default = 'Adam', type = str, help='Which optimizer to use (SGD, Adam, LBFGS)') #Lagnragian optimization args parser.add_argument('--lagrange', action='store_true', help='use Lagrangian optimization: do alternating grad desc wrt u and ascent wrt lamda') parser.add_argument('--lambda_lr', default=1e-3, type=float, help='Lr for Adam or SGD for Lambda lagrange update') #N optimization args parser.add_argument('--optimize_N', action='store_true', help='Attempt N optimization') parser.add_argument('--tumor_double_time', default=10.0, type=float, help='Tumor doubling time') parser.add_argument('--N_max', default=50.0, type=float, help='Max fractionation') parser.add_argument('--N_lr', default=0.1, type=float, help='Lr for Adam or SGD for N update') def relaxed_loss(epoch, u, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, device = 'cuda', lambdas = None): num_violated = 0 alpha, beta = radbio_dict['Target'] #Linear and quadratic coefficients T = dose_deposition_dict['Target'] tumor_dose = T@u #tumor BE: division to compute average BE, to be on the same scale with max dose loss = -N*(alpha*tumor_dose.sum() + beta*(tumor_dose**2).sum())/T.shape[0] objective = loss.item() experiment.log_metric("Objective", objective, step=epoch) OAR_names = list(dose_deposition_dict.keys())[1:] #Not including Target #Create penalties and add to the loss for oar in OAR_names: H = dose_deposition_dict[oar] oar_dose = H@u constraint_type, constraint_dose, constraint_N = constraint_dict[oar] constraint_dose = constraint_dose/constraint_N #Dose per fraction gamma, delta = radbio_dict[oar] if constraint_type == 'max_dose': max_constraint_BE = constraint_N*(gamma*constraint_dose + delta*constraint_dose**2) max_constr = N*(gamma*oar_dose + delta*oar_dose**2) num_violated += ((max_constr - max_constraint_BE)/max_constraint_BE > 0.05).sum() if oar in lambdas: loss += lambdas[oar]@F.relu(max_constr - max_constraint_BE)**2 else: lambdas[oar] = torch.ones(max_constr.shape[0]).to(device)*args.lambda_init loss += lambdas[oar]@F.relu(max_constr - max_constraint_BE)**2 if constraint_type == 'mean_dose': #Mean constr BE across voxels: mean_constraint_BE = constraint_N*(gamma*constraint_dose + delta*constraint_dose**2) #Mean BE across voxels mean_constr = N*(gamma*oar_dose.sum() + delta*(oar_dose**2).sum())/H.shape[0] num_violated += ((mean_constr - mean_constraint_BE) > 0).sum() if oar in lambdas: loss += lambdas[oar]*F.relu(mean_constr - mean_constraint_BE)**2 else: lambdas[oar] = args.lambda_init loss += lambdas[oar]*F.relu(mean_constr - mean_constraint_BE)**2 #smoothing constraint: experiment.log_metric("Num violated", num_violated, step=epoch) smoothing_constr = S@u num_violated_smoothing = (smoothing_constr > 0).sum() avg_smoothing_violation = (smoothing_constr[smoothing_constr > 0]).max() if 'smoothing' in lambdas: loss += lambdas['smoothing']@F.relu(smoothing_constr)**2 else: lambdas['smoothing'] = torch.ones(S.shape[0]).to(device)*args.lambda_init loss += lambdas['smoothing']@F.relu(smoothing_constr)**2 experiment.log_metric("Num violated smoothing", num_violated_smoothing, step=epoch) experiment.log_metric("Max violation smoothing", avg_smoothing_violation, step=epoch) experiment.log_metric("Loss", loss.item(), step=epoch) return loss, lambdas, num_violated, num_violated_smoothing, objective def relaxed_loss_lagrange(epoch, u, lambdas_var, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, args, device = 'cuda', lambdas = None): """ Lambdas_var is a list of lambda variable tensors correponding to the OAR_names """ num_violated = 0 alpha, beta = radbio_dict['Target'] #Linear and quadratic coefficients T = dose_deposition_dict['Target'] tumor_dose = T@u #tumor BE: division to compute average BE, to be on the same scale with max dose loss = -N*(alpha*tumor_dose.sum() + beta*(tumor_dose**2).sum())/T.shape[0] objective = loss.item() experiment.log_metric("Objective", objective, step=epoch) OAR_names = list(dose_deposition_dict.keys())[1:] #Not including Target #Create penalties and add to the loss for oar_num, oar in enumerate(OAR_names): H = dose_deposition_dict[oar] oar_dose = H@u constraint_type, constraint_dose, constraint_N = constraint_dict[oar] constraint_dose = constraint_dose/constraint_N #Dose per fraction gamma, delta = radbio_dict[oar] if constraint_type == 'max_dose': max_constraint_BE = constraint_N*(gamma*constraint_dose + delta*constraint_dose**2) max_constr = N*(gamma*oar_dose + delta*oar_dose**2) num_violated += ((max_constr - max_constraint_BE)/max_constraint_BE > 0.05).sum() if oar in lambdas: loss += lambdas_var[oar_num]@(max_constr - max_constraint_BE) else: raise ValueError('Lambdas cannot be None for Lagrangian optimization') if constraint_type == 'mean_dose': #Mean constr BE across voxels: mean_constraint_BE = constraint_N*(gamma*constraint_dose + delta*constraint_dose**2) #Mean BE across voxels mean_constr = N*(gamma*oar_dose.sum() + delta*(oar_dose**2).sum())/H.shape[0] num_violated += ((mean_constr - mean_constraint_BE) > 0).sum() if oar in lambdas: loss += lambdas_var[oar_num]*(mean_constr - mean_constraint_BE) else: raise ValueError('Lambdas cannot be None for Lagrangian optimization') #smoothing constraint: should be the last element of lambdas_var experiment.log_metric("Num violated", num_violated, step=epoch) smoothing_constr = S@u num_violated_smoothing = (smoothing_constr > 0).sum() max_smoothing_violation = (smoothing_constr[smoothing_constr > 0]).max() if 'smoothing' in lambdas: loss += lambdas_var[-1]@smoothing_constr else: raise ValueError('Lambdas cannot be None for Lagrangian optimization') experiment.log_metric("Num violated smoothing", num_violated_smoothing.item(), step=epoch) experiment.log_metric("Max violation smoothing", max_smoothing_violation.item(), step=epoch) experiment.log_metric("Loss", loss.item(), step=epoch) experiment.log_metric("Avg lambda", np.mean([lambda_.mean().item() for lambda_ in lambdas_var]), step=epoch) experiment.log_metric("Min lambda", np.min([lambda_.min().item() for lambda_ in lambdas_var]), step=epoch) experiment.log_metric("Max lambda", np.max([lambda_.max().item() for lambda_ in lambdas_var]), step=epoch) experiment.log_metric('Avg u', u.mean().item(), step = epoch) if args.optimize_N: loss = loss + ((N-1)*np.log(2.0)/args.tumor_double_time) return loss, num_violated, num_violated_smoothing, objective def initialize_lambdas(u, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, device = 'cuda'): with torch.no_grad(): lambdas = {} num_violated = 0 alpha, beta = radbio_dict['Target'] #Linear and quadratic coefficients T = dose_deposition_dict['Target'] tumor_dose = T@u #tumor BE: division to compute average BE, to be on the same scale with max dose loss = -N*(alpha*tumor_dose.sum() + beta*(tumor_dose**2).sum())/T.shape[0] objective = loss.item() OAR_names = list(dose_deposition_dict.keys())[1:] #Not including Target #Create penalties and add to the loss for oar in OAR_names: H = dose_deposition_dict[oar] oar_dose = H@u constraint_type, constraint_dose, constraint_N = constraint_dict[oar] constraint_dose = constraint_dose/constraint_N #Dose per fraction gamma, delta = radbio_dict[oar] if constraint_type == 'max_dose': max_constraint_BE = constraint_N*(gamma*constraint_dose + delta*constraint_dose**2) max_constr = N*(gamma*oar_dose + delta*oar_dose**2) num_violated += ((max_constr - max_constraint_BE)/max_constraint_BE > 0.05).sum() lambdas[oar] = torch.zeros_like(max_constr - max_constraint_BE).to(device) if constraint_type == 'mean_dose': #Mean constr BE across voxels: mean_constraint_BE = constraint_N*(gamma*constraint_dose + delta*constraint_dose**2) #Mean BE across voxels mean_constr = N*(gamma*oar_dose.sum() + delta*(oar_dose**2).sum())/H.shape[0] num_violated += ((mean_constr - mean_constraint_BE) > 0).sum() lambdas[oar] = torch.zeros_like(mean_constr - mean_constraint_BE).to(device) #smoothing constraint: smoothing_constr = S@u lambdas['smoothing'] = torch.zeros_like(smoothing_constr).to(device) lambdas_var = [lambdas[constr].requires_grad_() for constr in lambdas] print('\n Initializing Lambdas:') for i, constr in enumerate(lambdas): print('Lambdas:', lambdas[constr].shape) print('Vars:', lambdas_var[i].shape) # raise ValueError('Stop') return lambdas, lambdas_var def create_coefficient_dicts(data, device): """So far only creates coefficients for the first modality""" dose_deposition_dict = {} constraint_dict = {} radbio_dict = {} # coefficient_dict = {} organ_names = [str(i[0]) for i in np.squeeze(data['Organ'])] len_voxels = data['Aphoton'].shape[0] #[:-1] because we don't want the last isolated voxel organ_indices = np.split(np.arange(len_voxels), np.cumsum(np.squeeze(data['num_voxels'])))[:-1] OAR_constr_types = np.squeeze(data['OAR_constraint_types']) OAR_constr_values = np.squeeze(data['OAR_constraint_values']) for organ_number, organ_name in enumerate(organ_names): oar_number = organ_number - 1 #Because Target is also an organ # dose_deposition_dict[organ_name] = torch.from_numpy(data['Aphoton'][organ_indices[organ_number]]) dose_deposition_dict[organ_name] = csr_matrix_to_coo_tensor(data['Aphoton'][organ_indices[organ_number]]).to(device) if organ_name == 'Target': radbio_dict[organ_name] = Alpha[0], Beta[0] #So far, only photons # coefficient_dict[organ_name] = alpha*torch.ones(T.shape[0])@T if organ_name != 'Target': constraint_type = OAR_constr_types[oar_number].strip() constraint_dose = OAR_constr_values[oar_number] constraint_N = 44 constraint_dict[organ_name] = constraint_type, constraint_dose, constraint_N radbio_dict[organ_name] = Gamma[oar_number][0], Delta[oar_number][0] return dose_deposition_dict, constraint_dict, radbio_dict def dv_adjust_coefficient_dicts(data, dose_deposition_dict, dv_to_max_oar_ind_dict, device): """So far only creates coefficients for the first modality""" organ_names = [str(i[0]) for i in np.squeeze(data['Organ'])] len_voxels = data['Aphoton'].shape[0] #[:-1] because we don't want the last isolated voxel organ_indices = np.split(np.arange(len_voxels), np.cumsum(np.squeeze(data['num_voxels'])))[:-1] for organ_number, organ_name in enumerate(organ_names): if organ_name in dv_to_max_oar_ind_dict: print('\n Old len:', dose_deposition_dict[organ_name].shape[0]) dose_matrix = data['Aphoton'][organ_indices[organ_number]][dv_to_max_oar_ind_dict[organ_name]] dose_deposition_dict[organ_name] = csr_matrix_to_coo_tensor(dose_matrix).to(device) print('\n New len:', dose_deposition_dict[organ_name].shape[0]) return dose_deposition_dict def csr_matrix_to_coo_tensor(matrix): coo = scipy.sparse.coo_matrix(matrix) values = coo.data indices = np.vstack((coo.row, coo.col)) i = torch.LongTensor(indices) v = torch.FloatTensor(values) shape = coo.shape return torch.sparse.FloatTensor(i, v, torch.Size(shape)) if __name__ == '__main__': args = parser.parse_args() device = 'cuda' if torch.cuda.is_available() else 'cpu' experiment = Experiment(api_key='<KEY>', project_name='mmort_torch') ######################### ##Load raw data ######################### data_path = os.path.abspath(os.path.join(os.getcwd(), '..', 'data', args.data_name)) data = scipy.io.loadmat(data_path) ########################### #Experimental Setup Part ########################### #Load experimental setup from config experiment_setup = configurations[args.config_experiment] Alpha = experiment_setup['Alpha'] Beta = experiment_setup['Beta'] Gamma = experiment_setup['Gamma'] Delta = experiment_setup['Delta'] modality_names = experiment_setup['modality_names'] print('\nExperimental Setup: \nAlpha={} \nBeta={} \nGamma={} \nDelta={} \nModality Names: {}'.format(Alpha, Beta, Gamma, Delta, modality_names)) num_body_voxels = 683189 data['Aphoton'][-1] = data['Aphoton'][-1]/num_body_voxels data['Aproton'][-1] = data['Aproton'][-1]/num_body_voxels for modality in modality_names: data[modality] = scipy.sparse.csr_matrix(data[modality]) #Data with max dose (to be used with DVC): data_max_dose = copy.deepcopy(data) data_max_dose['OAR_constraint_types'][data_max_dose['OAR_constraint_types'] == 'dose_volume'] = 'max_dose' print('\nData loaded from '+data_path) ################################### ##Solution: photons ################################### #No dose volume N = 44 #Set up smoothing matrix len_voxels = data['Aphoton'].shape[0] beamlet_indices = np.split(np.arange(len_voxels), np.cumsum(np.squeeze(data['num_beamlets'])))[:-1] beams = [data['beamlet_pos'][i] for i in beamlet_indices] S = csr_matrix_to_coo_tensor(utils.construct_smoothing_matrix_relative(beams, 0.25, eps = 5)).to(device) dose_deposition_dict, constraint_dict, radbio_dict = create_coefficient_dicts(data, device) print('\nDose_deposition_dict:', dose_deposition_dict) print('\nConstraint dict:', constraint_dict) print('\nradbio_dict:', radbio_dict) print('\nN:', N) print('\nS shape:', S.shape) #Setup optimization if not args.precomputed: print('\n Running optimization...') Rx = 81 print(data['num_voxels'][0]) LHS1 = data['Aphoton'][:np.squeeze(data['num_voxels'])[0]] RHS1 = np.array([Rx/N]*LHS1.shape[0]) u = torch.Tensor(scipy.optimize.lsq_linear(LHS1, RHS1, bounds = (0, np.inf), tol=1e-4, lsmr_tol=1e-4, max_iter=100, verbose=1).x) u = u.to(device) u.requires_grad_() if args.optimizer == 'SGD': optimizer = optim.SGD([u], lr=args.lr, momentum=0.9, nesterov = True) elif args.optimizer == 'Adam': optimizer = optim.Adam([u], lr=args.lr) elif args.optimizer == 'LBFGS': optimizer = optim.LBFGS([u]) else: raise ValueError('The optimizer option {} is not supported'.format(args.optimizer)) if not args.lagrange: lambdas = {} if args.lagrange: lambdas, lambdas_var = initialize_lambdas(u, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, device = 'cuda') # for constraint in lambdas_var: # lambdas[constraint].requires_grad_() optimizer_lambdas = optim.Adam(lambdas_var, lr=args.lambda_lr) if not args.lagrange: for epoch in range(args.num_epochs): optimizer.zero_grad() loss, lambdas, num_violated, num_violated_smoothing, objective = relaxed_loss(epoch, u, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, device = device, lambdas = lambdas) print('\n Loss {} \n Objective {} \n Num Violated {} \n Num Violated Smoothing {}'.format(loss, objective, num_violated, num_violated_smoothing)) loss.backward() optimizer.step() #Box constraint u.data = torch.maximum(torch.minimum(u, torch.ones_like(u)*args.u_max), torch.zeros_like(u)) if args.lagrange: for epoch in range(args.num_epochs): #Update u: print('\n u step') optimizer.zero_grad() loss, num_violated, num_violated_smoothing, objective = relaxed_loss_lagrange(epoch, u, lambdas_var, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, args, device = device, lambdas = lambdas) print('\n Loss {} \n Objective {} \n Num Violated {} \n Num Violated Smoothing {}'.format(loss, objective, num_violated, num_violated_smoothing)) loss.backward() optimizer.step() #Box constraint u.data = torch.maximum(torch.minimum(u, torch.ones_like(u)*args.u_max), torch.zeros_like(u)) #Update lambdas: print('\n lambdas step') optimizer_lambdas.zero_grad() loss_lambdas, num_violated, num_violated_smoothing, objective = relaxed_loss_lagrange(epoch, u, lambdas_var, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, args, device = device, lambdas = lambdas) loss_lambdas = (-1)*loss_lambdas loss_lambdas.backward() optimizer_lambdas.step() #Box contraint (lambda >= 0) for constraint in range(len(lambdas_var)): lambdas_var[constraint].data = torch.maximum(lambdas_var[constraint], torch.zeros_like(lambdas_var[constraint])) print(u) #To run: python3 projected_gradient_mmort.py --lr 1e-6 --lambda_init 1e3 --num_epochs 10000 if not args.lagrange: utils.save_obj(u.detach().cpu().numpy(), 'u_photon_pytorch') if args.lagrange: utils.save_obj(u.detach().cpu().numpy(), 'u_photon_pytorch_lagrange') if args.precomputed: if not args.lagrange: u = torch.from_numpy(utils.load_obj('u_photon_pytorch', '')) u = u.to(device) u.requires_grad_() if args.lagrange: u = torch.from_numpy(utils.load_obj('u_photon_pytorch_lagrange', '')) u = u.to(device) u.requires_grad_() #################### ##DVC: Photons #################### print('Setting up DVC data...') #Setup input oar_indices, dv_to_max_oar_ind_dict = utils.generate_dose_volume_input_torch(u.detach().cpu().numpy(), np.array([N, 0]), data, Alpha, Beta, Gamma, Delta, photon_only = True, proton_only = False) dose_deposition_dict_dv, constraint_dict_dv, radbio_dict_dv = create_coefficient_dicts(data_max_dose, device) # for organ in dv_to_max_oar_ind_dict: # print('\n DVC organ {} with constr: {}'.format(organ, constraint_dict_dv[organ])) # print('\n Old len:', dose_deposition_dict_dv[organ].shape[0]) # dose_deposition_dict_dv[organ] = dose_deposition_dict_dv[organ][torch.from_numpy(dv_to_max_oar_ind_dict[organ]).to(device)] # print('\n New len:', dose_deposition_dict_dv[organ].shape[0]) dose_deposition_dict_dv = dv_adjust_coefficient_dicts(data_max_dose, dose_deposition_dict_dv, dv_to_max_oar_ind_dict, device) #Compute solution print('Computing DV solution') print('\nDose_deposition_dict:', dose_deposition_dict_dv) print('\nConstraint dict:', constraint_dict_dv) print('\nradbio_dict:', radbio_dict_dv) print('\nN:', N) print('\nS shape:', S.shape) #Setup optimization print('\n Running optimization...') #Uncomment this to setup an initial guess on u from scratch if args.initial_guess_for_dv: Rx = 81 print(data['num_voxels'][0]) LHS1 = data['Aphoton'][:np.squeeze(data['num_voxels'])[0]] RHS1 = np.array([Rx/N]*LHS1.shape[0]) u = torch.Tensor(scipy.optimize.lsq_linear(LHS1, RHS1, bounds = (0, np.inf), tol=1e-4, lsmr_tol=1e-4, max_iter=100, verbose=1).x) u = u.to(device) u.requires_grad_() if args.optimize_N: N = torch.tensor(44.0) N.requires_grad_() if args.optimizer == 'SGD': optimizer = optim.SGD([u], lr=args.lr, momentum=0.9, nesterov = True) elif args.optimizer == 'Adam': if args.optimize_N: optimizer = optim.Adam([{'params': [u]}, {'params': [N], 'lr': args.N_lr}], lr=args.lr) else: optimizer = optim.Adam([u], lr=args.lr) elif args.optimizer == 'LBFGS': optimizer = optim.LBFGS([u]) else: raise ValueError('The optimizer option {} is not supported'.format(args.optimizer)) if not args.lagrange: lambdas = {} if args.lagrange: lambdas, lambdas_var = initialize_lambdas(u, N, dose_deposition_dict_dv, constraint_dict_dv, radbio_dict_dv, S, experiment, device = 'cuda') # for constraint in lambdas: # lambdas[constraint].requires_grad_() optimizer_lambdas = optim.Adam(lambdas_var, lr=args.lambda_lr) # lambdas = {dv_organ: torch.ones(dv_to_max_oar_ind_dict[dv_organ].shape[0]).to(device)*args.lambda_init/10 for dv_organ in dv_to_max_oar_ind_dict}#{} if not args.lagrange: for epoch in range(args.num_epochs): optimizer.zero_grad() loss, lambdas, num_violated, num_violated_smoothing, objective = relaxed_loss(epoch, u, N, dose_deposition_dict_dv, constraint_dict_dv, radbio_dict_dv, S, experiment, device = device, lambdas = lambdas) print('\n Loss {} \n Objective {} \n Num Violated {} \n Num Violated Smoothing {}'.format(loss, objective, num_violated, num_violated_smoothing)) loss.backward() optimizer.step() #Box constraint u.data = torch.maximum(torch.minimum(u, torch.ones_like(u)*args.u_max), torch.zeros_like(u)) if args.lagrange: for epoch in range(args.num_epochs): #Update u: print('\n u step') optimizer.zero_grad() loss, num_violated, num_violated_smoothing, objective = relaxed_loss_lagrange(epoch, u, lambdas_var, N, dose_deposition_dict_dv, constraint_dict_dv, radbio_dict_dv, S, experiment, args, device = device, lambdas = lambdas) print('\n Loss {} \n Objective {} \n Num Violated {} \n Num Violated Smoothing {}'.format(loss, objective, num_violated, num_violated_smoothing)) experiment.log_metric("Loss_u", loss.item(), step=epoch) loss.backward() optimizer.step() #Box constraint u.data = torch.maximum(torch.minimum(u, torch.ones_like(u)*args.u_max), torch.zeros_like(u)) if args.optimize_N: N.data = torch.maximum(torch.minimum(N, torch.ones_like(N)*args.N_max), torch.zeros_like(N)) experiment.log_metric("N", N.item(), step=epoch) #Update lambdas: print('\n lambdas step') optimizer_lambdas.zero_grad() loss_lambdas, num_violated, num_violated_smoothing, objective = relaxed_loss_lagrange(epoch, u, lambdas_var, N, dose_deposition_dict_dv, constraint_dict_dv, radbio_dict_dv, S, experiment, args, device = device, lambdas = lambdas) print('\n Loss {} \n Objective {} \n Num Violated {} \n Num Violated Smoothing {}'.format(loss_lambdas, objective, num_violated, num_violated_smoothing)) loss_lambdas = (-1)*loss_lambdas experiment.log_metric("Loss_l", loss_lambdas.item(), step=epoch) loss_lambdas.backward() optimizer_lambdas.step() #Box contraint (lambda >= 0) for constraint in range(len(lambdas_var)): lambdas_var[constraint].data = torch.maximum(lambdas_var[constraint], torch.zeros_like(lambdas_var[constraint])) print(u) #To run: python3 projected_gradient_mmort.py --lr 1e-6 --lambda_init 1e3 --num_epochs 10000 if not args.lagrange: utils.save_obj(u.detach().cpu().numpy(), 'u_photon_dv_pytorch', args.save_dir) if args.lagrange: utils.save_obj(u.detach().cpu().numpy(), 'u_photon_dv_pytorch_lagrange', args.save_dir) # #TODO: #dvh + #multi-modality #lagrange optimization #IMRT #N optimization is so far implemented only in the second half #Run with faithfully computed init guess for dv
[ "comet_ml.Experiment", "torch.LongTensor", "scipy.io.loadmat", "numpy.log", "numpy.array", "scipy.optimize.lsq_linear", "torch.cuda.is_available", "copy.deepcopy", "numpy.arange", "argparse.ArgumentParser", "numpy.vstack", "scipy.sparse.coo_matrix", "scipy.sparse.csr_matrix", "torch.zeros_...
[((545, 589), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""MMORT"""'}), "(description='MMORT')\n", (568, 589), False, 'import argparse\n'), ((10684, 10724), 'numpy.squeeze', 'np.squeeze', (["data['OAR_constraint_types']"], {}), "(data['OAR_constraint_types'])\n", (10694, 10724), True, 'import numpy as np\n'), ((10746, 10787), 'numpy.squeeze', 'np.squeeze', (["data['OAR_constraint_values']"], {}), "(data['OAR_constraint_values'])\n", (10756, 10787), True, 'import numpy as np\n'), ((12569, 12600), 'scipy.sparse.coo_matrix', 'scipy.sparse.coo_matrix', (['matrix'], {}), '(matrix)\n', (12592, 12600), False, 'import scipy\n'), ((12632, 12661), 'numpy.vstack', 'np.vstack', (['(coo.row, coo.col)'], {}), '((coo.row, coo.col))\n', (12641, 12661), True, 'import numpy as np\n'), ((12668, 12693), 'torch.LongTensor', 'torch.LongTensor', (['indices'], {}), '(indices)\n', (12684, 12693), False, 'import torch\n'), ((12699, 12724), 'torch.FloatTensor', 'torch.FloatTensor', (['values'], {}), '(values)\n', (12716, 12724), False, 'import torch\n'), ((12931, 12986), 'comet_ml.Experiment', 'Experiment', ([], {'api_key': '"""<KEY>"""', 'project_name': '"""mmort_torch"""'}), "(api_key='<KEY>', project_name='mmort_torch')\n", (12941, 12986), False, 'from comet_ml import Experiment\n'), ((13153, 13180), 'scipy.io.loadmat', 'scipy.io.loadmat', (['data_path'], {}), '(data_path)\n', (13169, 13180), False, 'import scipy\n'), ((14011, 14030), 'copy.deepcopy', 'copy.deepcopy', (['data'], {}), '(data)\n', (14024, 14030), False, 'import copy\n'), ((8286, 8301), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8299, 8301), False, 'import torch\n'), ((12784, 12801), 'torch.Size', 'torch.Size', (['shape'], {}), '(shape)\n', (12794, 12801), False, 'import torch\n'), ((12879, 12904), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (12902, 12904), False, 'import torch\n'), ((13909, 13948), 'scipy.sparse.csr_matrix', 'scipy.sparse.csr_matrix', (['data[modality]'], {}), '(data[modality])\n', (13932, 13948), False, 'import scipy\n'), ((15118, 15152), 'numpy.array', 'np.array', (['([Rx / N] * LHS1.shape[0])'], {}), '([Rx / N] * LHS1.shape[0])\n', (15126, 15152), True, 'import numpy as np\n'), ((18650, 18666), 'numpy.array', 'np.array', (['[N, 0]'], {}), '([N, 0])\n', (18658, 18666), True, 'import numpy as np\n'), ((19881, 19915), 'numpy.array', 'np.array', (['([Rx / N] * LHS1.shape[0])'], {}), '([Rx / N] * LHS1.shape[0])\n', (19889, 19915), True, 'import numpy as np\n'), ((20112, 20130), 'torch.tensor', 'torch.tensor', (['(44.0)'], {}), '(44.0)\n', (20124, 20130), False, 'import torch\n'), ((20196, 20251), 'torch.optim.SGD', 'optim.SGD', (['[u]'], {'lr': 'args.lr', 'momentum': '(0.9)', 'nesterov': '(True)'}), '([u], lr=args.lr, momentum=0.9, nesterov=True)\n', (20205, 20251), True, 'import torch.optim as optim\n'), ((20908, 20950), 'torch.optim.Adam', 'optim.Adam', (['lambdas_var'], {'lr': 'args.lambda_lr'}), '(lambdas_var, lr=args.lambda_lr)\n', (20918, 20950), True, 'import torch.optim as optim\n'), ((318, 329), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (327, 329), False, 'import os\n'), ((10447, 10472), 'numpy.squeeze', 'np.squeeze', (["data['Organ']"], {}), "(data['Organ'])\n", (10457, 10472), True, 'import numpy as np\n'), ((10593, 10614), 'numpy.arange', 'np.arange', (['len_voxels'], {}), '(len_voxels)\n', (10602, 10614), True, 'import numpy as np\n'), ((11858, 11883), 'numpy.squeeze', 'np.squeeze', (["data['Organ']"], {}), "(data['Organ'])\n", (11868, 11883), True, 'import numpy as np\n'), ((12004, 12025), 'numpy.arange', 'np.arange', (['len_voxels'], {}), '(len_voxels)\n', (12013, 12025), True, 'import numpy as np\n'), ((13101, 13112), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (13110, 13112), False, 'import os\n'), ((14399, 14420), 'numpy.arange', 'np.arange', (['len_voxels'], {}), '(len_voxels)\n', (14408, 14420), True, 'import numpy as np\n'), ((15369, 15424), 'torch.optim.SGD', 'optim.SGD', (['[u]'], {'lr': 'args.lr', 'momentum': '(0.9)', 'nesterov': '(True)'}), '([u], lr=args.lr, momentum=0.9, nesterov=True)\n', (15378, 15424), True, 'import torch.optim as optim\n'), ((15963, 16005), 'torch.optim.Adam', 'optim.Adam', (['lambdas_var'], {'lr': 'args.lambda_lr'}), '(lambdas_var, lr=args.lambda_lr)\n', (15973, 16005), True, 'import torch.optim as optim\n'), ((4533, 4557), 'torch.nn.functional.relu', 'F.relu', (['smoothing_constr'], {}), '(smoothing_constr)\n', (4539, 4557), True, 'import torch.nn.functional as F\n'), ((4675, 4699), 'torch.nn.functional.relu', 'F.relu', (['smoothing_constr'], {}), '(smoothing_constr)\n', (4681, 4699), True, 'import torch.nn.functional as F\n'), ((9881, 9915), 'torch.zeros_like', 'torch.zeros_like', (['smoothing_constr'], {}), '(smoothing_constr)\n', (9897, 9915), False, 'import torch\n'), ((10626, 10656), 'numpy.squeeze', 'np.squeeze', (["data['num_voxels']"], {}), "(data['num_voxels'])\n", (10636, 10656), True, 'import numpy as np\n'), ((12037, 12067), 'numpy.squeeze', 'np.squeeze', (["data['num_voxels']"], {}), "(data['num_voxels'])\n", (12047, 12067), True, 'import numpy as np\n'), ((14432, 14464), 'numpy.squeeze', 'np.squeeze', (["data['num_beamlets']"], {}), "(data['num_beamlets'])\n", (14442, 14464), True, 'import numpy as np\n'), ((14562, 14623), 'utils.construct_smoothing_matrix_relative', 'utils.construct_smoothing_matrix_relative', (['beams', '(0.25)'], {'eps': '(5)'}), '(beams, 0.25, eps=5)\n', (14603, 14623), False, 'import utils\n'), ((15168, 15283), 'scipy.optimize.lsq_linear', 'scipy.optimize.lsq_linear', (['LHS1', 'RHS1'], {'bounds': '(0, np.inf)', 'tol': '(0.0001)', 'lsmr_tol': '(0.0001)', 'max_iter': '(100)', 'verbose': '(1)'}), '(LHS1, RHS1, bounds=(0, np.inf), tol=0.0001,\n lsmr_tol=0.0001, max_iter=100, verbose=1)\n', (15193, 15283), False, 'import scipy\n'), ((15475, 15502), 'torch.optim.Adam', 'optim.Adam', (['[u]'], {'lr': 'args.lr'}), '([u], lr=args.lr)\n', (15485, 15502), True, 'import torch.optim as optim\n'), ((18221, 18259), 'utils.load_obj', 'utils.load_obj', (['"""u_photon_pytorch"""', '""""""'], {}), "('u_photon_pytorch', '')\n", (18235, 18259), False, 'import utils\n'), ((18347, 18394), 'utils.load_obj', 'utils.load_obj', (['"""u_photon_pytorch_lagrange"""', '""""""'], {}), "('u_photon_pytorch_lagrange', '')\n", (18361, 18394), False, 'import utils\n'), ((19931, 20046), 'scipy.optimize.lsq_linear', 'scipy.optimize.lsq_linear', (['LHS1', 'RHS1'], {'bounds': '(0, np.inf)', 'tol': '(0.0001)', 'lsmr_tol': '(0.0001)', 'max_iter': '(100)', 'verbose': '(1)'}), '(LHS1, RHS1, bounds=(0, np.inf), tol=0.0001,\n lsmr_tol=0.0001, max_iter=100, verbose=1)\n', (19956, 20046), False, 'import scipy\n'), ((20323, 20398), 'torch.optim.Adam', 'optim.Adam', (["[{'params': [u]}, {'params': [N], 'lr': args.N_lr}]"], {'lr': 'args.lr'}), "([{'params': [u]}, {'params': [N], 'lr': args.N_lr}], lr=args.lr)\n", (20333, 20398), True, 'import torch.optim as optim\n'), ((20426, 20453), 'torch.optim.Adam', 'optim.Adam', (['[u]'], {'lr': 'args.lr'}), '([u], lr=args.lr)\n', (20436, 20453), True, 'import torch.optim as optim\n'), ((20501, 20517), 'torch.optim.LBFGS', 'optim.LBFGS', (['[u]'], {}), '([u])\n', (20512, 20517), True, 'import torch.optim as optim\n'), ((21679, 21698), 'torch.zeros_like', 'torch.zeros_like', (['u'], {}), '(u)\n', (21695, 21698), False, 'import torch\n'), ((22387, 22406), 'torch.zeros_like', 'torch.zeros_like', (['u'], {}), '(u)\n', (22403, 22406), False, 'import torch\n'), ((4593, 4615), 'torch.ones', 'torch.ones', (['S.shape[0]'], {}), '(S.shape[0])\n', (4603, 4615), False, 'import torch\n'), ((8067, 8078), 'numpy.log', 'np.log', (['(2.0)'], {}), '(2.0)\n', (8073, 8078), True, 'import numpy as np\n'), ((15074, 15104), 'numpy.squeeze', 'np.squeeze', (["data['num_voxels']"], {}), "(data['num_voxels'])\n", (15084, 15104), True, 'import numpy as np\n'), ((15552, 15568), 'torch.optim.LBFGS', 'optim.LBFGS', (['[u]'], {}), '([u])\n', (15563, 15568), True, 'import torch.optim as optim\n'), ((16583, 16602), 'torch.zeros_like', 'torch.zeros_like', (['u'], {}), '(u)\n', (16599, 16602), False, 'import torch\n'), ((17233, 17252), 'torch.zeros_like', 'torch.zeros_like', (['u'], {}), '(u)\n', (17249, 17252), False, 'import torch\n'), ((19837, 19867), 'numpy.squeeze', 'np.squeeze', (["data['num_voxels']"], {}), "(data['num_voxels'])\n", (19847, 19867), True, 'import numpy as np\n'), ((22507, 22526), 'torch.zeros_like', 'torch.zeros_like', (['N'], {}), '(N)\n', (22523, 22526), False, 'import torch\n'), ((23367, 23408), 'torch.zeros_like', 'torch.zeros_like', (['lambdas_var[constraint]'], {}), '(lambdas_var[constraint])\n', (23383, 23408), False, 'import torch\n'), ((3498, 3536), 'torch.nn.functional.relu', 'F.relu', (['(max_constr - max_constraint_BE)'], {}), '(max_constr - max_constraint_BE)\n', (3504, 3536), True, 'import torch.nn.functional as F\n'), ((3653, 3691), 'torch.nn.functional.relu', 'F.relu', (['(max_constr - max_constraint_BE)'], {}), '(max_constr - max_constraint_BE)\n', (3659, 3691), True, 'import torch.nn.functional as F\n'), ((4074, 4114), 'torch.nn.functional.relu', 'F.relu', (['(mean_constr - mean_constraint_BE)'], {}), '(mean_constr - mean_constraint_BE)\n', (4080, 4114), True, 'import torch.nn.functional as F\n'), ((4188, 4228), 'torch.nn.functional.relu', 'F.relu', (['(mean_constr - mean_constraint_BE)'], {}), '(mean_constr - mean_constraint_BE)\n', (4194, 4228), True, 'import torch.nn.functional as F\n'), ((9309, 9357), 'torch.zeros_like', 'torch.zeros_like', (['(max_constr - max_constraint_BE)'], {}), '(max_constr - max_constraint_BE)\n', (9325, 9357), False, 'import torch\n'), ((9735, 9785), 'torch.zeros_like', 'torch.zeros_like', (['(mean_constr - mean_constraint_BE)'], {}), '(mean_constr - mean_constraint_BE)\n', (9751, 9785), False, 'import torch\n'), ((17819, 17860), 'torch.zeros_like', 'torch.zeros_like', (['lambdas_var[constraint]'], {}), '(lambdas_var[constraint])\n', (17835, 17860), False, 'import torch\n'), ((21647, 21665), 'torch.ones_like', 'torch.ones_like', (['u'], {}), '(u)\n', (21662, 21665), False, 'import torch\n'), ((22355, 22373), 'torch.ones_like', 'torch.ones_like', (['u'], {}), '(u)\n', (22370, 22373), False, 'import torch\n'), ((3568, 3599), 'torch.ones', 'torch.ones', (['max_constr.shape[0]'], {}), '(max_constr.shape[0])\n', (3578, 3599), False, 'import torch\n'), ((16551, 16569), 'torch.ones_like', 'torch.ones_like', (['u'], {}), '(u)\n', (16566, 16569), False, 'import torch\n'), ((17201, 17219), 'torch.ones_like', 'torch.ones_like', (['u'], {}), '(u)\n', (17216, 17219), False, 'import torch\n'), ((22475, 22493), 'torch.ones_like', 'torch.ones_like', (['N'], {}), '(N)\n', (22490, 22493), False, 'import torch\n')]
#!/usr/bin/env python3 # Name: <NAME> and <NAME> # Student ID: 2267883 # Email: <EMAIL> # Course: PHYS220/MATH220/CPSC220 Fall 2017 # Assignment: CLASSWORK 6 import numpy as np import matplotlib.pyplot as plt #Used to plot in python #First Derivative code def derivative(a,b,n): '''derivative(a,b,n) Creating the first-order derivative matrix operator Args: a (int) : first endpoint b (int) : last endpoing n (int) : number of intervals from a to b Returns: D1 : The first derivative matrix operator''' dx = (b-a)/(n-1) D1 = np.eye(n,n,1)-np.eye(n,n,-1) D1[0][0] = -2 D1[0][1] = 2 D1[-1][-1] = 2 D1[-1][-2] = -2 D1 = D1/(2*dx) return D1 #Second Derivative Code def second_derivative(a,b,n): '''derivative(a,b,n) Creating the second-order derivative matrix operator Args: a (int) : first endpoint b (int) : last endpoing n (int) : number of intervals from a to b Returns: D2 : The second derivative matrix operator''' dx = ((b-a)/(n-1)) D2 = np.eye(n,n,2)+np.eye(n,n,-2)-2*np.eye(n) D2[0][0] = 2 D2[0][1] = -4 D2[0][2] = 2 D2[1][0] = 2 D2[1][1] = -3 D2[-1][-1] = 2 D2[-1][-2] = -4 D2[-1][-3] = 2 D2[-2][-1] = 2 D2[-2][-2] = -3 D2 = (D2/(4*dx**2)) return D2 #Plotting xSquared(f): def make_plots_for_xSquared(x, functionResults, myDerivative, mySecondDerivative): #plots the normal function, derivative function, and second derivative function of x^2. plt.ylabel('Y') #labels the y axis plt.xlabel('X') #labels the x axis font = {'size': 16} #adjusts size of font title="Normal, First Derivative, and Second Derivative of x^2" #title of graph plt.title(title) plt.plot(x,functionResults,label="Function Results",color="green") plt.plot(x,myDerivative,label="First Derivative Results",color="blue") plt.plot(x,mySecondDerivative,label="Second Derivative Results", color="red") plt.legend(loc='upper left', frameon=False) #graph's legend plt.show() #Plotting sinX(f) def make_plots_for_sinX(x, functionResults, myDerivative, mySecondDerivative): #plots the normal function, derivative function, and second derivative function of sin(x). plt.ylabel('Y') #labels the y axis plt.xlabel('X') #labels the x axis font = {'size': 16} #adjusts size of font title="Normal, First Derivative, and Second Derivative of sin(x)" #title of graph plt.title(title) plt.plot(x,functionResults,label="Function Results",color="green") plt.plot(x,myDerivative,label="First Derivative Results",color="blue") plt.plot(x,mySecondDerivative,label="Second Derivative Results", color="red") plt.legend(loc='lower right', frameon=False) #graph's legend plt.show() #Plotting expX(f) def make_plots_for_expX(x, functionResults, myDerivative, mySecondDerivative): #plots the normal function, derivative function, and second derivative function of e^((-x^2/2)/(2pi)^(1/2). plt.ylabel('Y') #labels the y axis plt.xlabel('X') #labels the x axis font = {'size': 16} #adjusts size of font title="Normal, First Derivative, and Second Derivative of e^((-x^2/2)/(2pi)^(1/2)" #title of graph plt.title(title) plt.plot(x,functionResults,label="Function Results",color="green") plt.plot(x,myDerivative,label="First Derivative Results",color="blue") plt.plot(x,mySecondDerivative,label="Second Derivative Results", color="red") plt.legend(loc='upper right', frameon=False) #graph's legend plt.show()
[ "numpy.eye", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.title", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((1546, 1561), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Y"""'], {}), "('Y')\n", (1556, 1561), True, 'import matplotlib.pyplot as plt\n'), ((1585, 1600), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""X"""'], {}), "('X')\n", (1595, 1600), True, 'import matplotlib.pyplot as plt\n'), ((1753, 1769), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (1762, 1769), True, 'import matplotlib.pyplot as plt\n'), ((1774, 1843), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'functionResults'], {'label': '"""Function Results"""', 'color': '"""green"""'}), "(x, functionResults, label='Function Results', color='green')\n", (1782, 1843), True, 'import matplotlib.pyplot as plt\n'), ((1845, 1918), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'myDerivative'], {'label': '"""First Derivative Results"""', 'color': '"""blue"""'}), "(x, myDerivative, label='First Derivative Results', color='blue')\n", (1853, 1918), True, 'import matplotlib.pyplot as plt\n'), ((1920, 1999), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'mySecondDerivative'], {'label': '"""Second Derivative Results"""', 'color': '"""red"""'}), "(x, mySecondDerivative, label='Second Derivative Results', color='red')\n", (1928, 1999), True, 'import matplotlib.pyplot as plt\n'), ((2002, 2045), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""', 'frameon': '(False)'}), "(loc='upper left', frameon=False)\n", (2012, 2045), True, 'import matplotlib.pyplot as plt\n'), ((2066, 2076), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2074, 2076), True, 'import matplotlib.pyplot as plt\n'), ((2274, 2289), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Y"""'], {}), "('Y')\n", (2284, 2289), True, 'import matplotlib.pyplot as plt\n'), ((2313, 2328), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""X"""'], {}), "('X')\n", (2323, 2328), True, 'import matplotlib.pyplot as plt\n'), ((2484, 2500), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2493, 2500), True, 'import matplotlib.pyplot as plt\n'), ((2505, 2574), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'functionResults'], {'label': '"""Function Results"""', 'color': '"""green"""'}), "(x, functionResults, label='Function Results', color='green')\n", (2513, 2574), True, 'import matplotlib.pyplot as plt\n'), ((2576, 2649), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'myDerivative'], {'label': '"""First Derivative Results"""', 'color': '"""blue"""'}), "(x, myDerivative, label='First Derivative Results', color='blue')\n", (2584, 2649), True, 'import matplotlib.pyplot as plt\n'), ((2651, 2730), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'mySecondDerivative'], {'label': '"""Second Derivative Results"""', 'color': '"""red"""'}), "(x, mySecondDerivative, label='Second Derivative Results', color='red')\n", (2659, 2730), True, 'import matplotlib.pyplot as plt\n'), ((2733, 2777), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""', 'frameon': '(False)'}), "(loc='lower right', frameon=False)\n", (2743, 2777), True, 'import matplotlib.pyplot as plt\n'), ((2798, 2808), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2806, 2808), True, 'import matplotlib.pyplot as plt\n'), ((3023, 3038), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Y"""'], {}), "('Y')\n", (3033, 3038), True, 'import matplotlib.pyplot as plt\n'), ((3062, 3077), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""X"""'], {}), "('X')\n", (3072, 3077), True, 'import matplotlib.pyplot as plt\n'), ((3250, 3266), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (3259, 3266), True, 'import matplotlib.pyplot as plt\n'), ((3271, 3340), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'functionResults'], {'label': '"""Function Results"""', 'color': '"""green"""'}), "(x, functionResults, label='Function Results', color='green')\n", (3279, 3340), True, 'import matplotlib.pyplot as plt\n'), ((3342, 3415), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'myDerivative'], {'label': '"""First Derivative Results"""', 'color': '"""blue"""'}), "(x, myDerivative, label='First Derivative Results', color='blue')\n", (3350, 3415), True, 'import matplotlib.pyplot as plt\n'), ((3417, 3496), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'mySecondDerivative'], {'label': '"""Second Derivative Results"""', 'color': '"""red"""'}), "(x, mySecondDerivative, label='Second Derivative Results', color='red')\n", (3425, 3496), True, 'import matplotlib.pyplot as plt\n'), ((3499, 3543), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""', 'frameon': '(False)'}), "(loc='upper right', frameon=False)\n", (3509, 3543), True, 'import matplotlib.pyplot as plt\n'), ((3564, 3574), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3572, 3574), True, 'import matplotlib.pyplot as plt\n'), ((583, 598), 'numpy.eye', 'np.eye', (['n', 'n', '(1)'], {}), '(n, n, 1)\n', (589, 598), True, 'import numpy as np\n'), ((597, 613), 'numpy.eye', 'np.eye', (['n', 'n', '(-1)'], {}), '(n, n, -1)\n', (603, 613), True, 'import numpy as np\n'), ((1080, 1095), 'numpy.eye', 'np.eye', (['n', 'n', '(2)'], {}), '(n, n, 2)\n', (1086, 1095), True, 'import numpy as np\n'), ((1094, 1110), 'numpy.eye', 'np.eye', (['n', 'n', '(-2)'], {}), '(n, n, -2)\n', (1100, 1110), True, 'import numpy as np\n'), ((1111, 1120), 'numpy.eye', 'np.eye', (['n'], {}), '(n)\n', (1117, 1120), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt # Generate data n = 500 t = np.linspace(0,20.0*np.pi,n) X = np.sin(t) # X is already between -1 and 1, scaling normally needed
[ "numpy.sin", "numpy.linspace" ]
[((80, 111), 'numpy.linspace', 'np.linspace', (['(0)', '(20.0 * np.pi)', 'n'], {}), '(0, 20.0 * np.pi, n)\n', (91, 111), True, 'import numpy as np\n'), ((112, 121), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (118, 121), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np import os import torchvision from joblib import load from settings import DIR_DATA, DIR_OUTPUT, SYNTHETIC_DIM, SYNTHETIC_SAMPLES, SYNTHETIC_NOISE_VALID, \ SYNTHETIC_DATASPLIT, MNIST_BINARIZATION_CUTOFF, PATTERN_THRESHOLD, K_PATTERN_DIV """ noise 'symmetric': the noise for each pattern basin is symmetric - Q1: does it matter then that each pattern is uncorrelated? should sample noise differently if correlated? sampling 'balanced': 50% of samples drawn from each pattern basin (for 2 patterns) """ def binarize_image_data(numpy_obj, threshold=MNIST_BINARIZATION_CUTOFF): numpy_obj[numpy_obj <= threshold] = 0 numpy_obj[numpy_obj > 0] = 1 # now 0, 1 numpy_obj.astype(int) numpy_obj = 2 * numpy_obj - 1 # +1, -1 convention return numpy_obj def torch_image_to_numpy(torch_tensor, binarize=False): numpy_obj = torch_tensor.numpy()[0] if binarize: numpy_obj = binarize_image_data(numpy_obj) return numpy_obj def data_mnist(binarize=False): # data structure: list of ~60,000 2-tuples: "image" and integer label training = torchvision.datasets.MNIST(root=DIR_DATA, train=True, transform=torchvision.transforms.ToTensor(), download=True) testing = torchvision.datasets.MNIST(root=DIR_DATA, train=False, transform=torchvision.transforms.ToTensor(), download=True) print("Processing MNIST data: numpy_binarize =", binarize) training = [(torch_image_to_numpy(elem[0], binarize=binarize), elem[1]) for elem in training] testing = [(torch_image_to_numpy(elem[0], binarize=binarize), elem[1]) for elem in testing] return training, testing def image_data_collapse(data): if len(data.shape) == 3: return data.reshape(-1, data.shape[-1]) else: assert len(data.shape) == 2 return data.flatten() def samples_per_category(data): category_counts = {} for pair in data: if pair[1] in category_counts.keys(): category_counts[pair[1]] += 1 else: category_counts[pair[1]] = 1 return category_counts def data_dict_mnist(data): data_dimension = data[0][0].shape category_counts = samples_per_category(data) print("category_counts:\n", category_counts) print("Generating MNIST data dict") label_counter = {idx: 0 for idx in range(10)} #data_dict = {idx: np.zeros((data_dimension[0], data_dimension[1], category_counts[idx])) for idx in range(10)} data_dict = {idx: np.zeros((data_dimension[0], data_dimension[1], category_counts[idx])) for idx in category_counts.keys()} for pair in data: label = pair[1] category_idx = label_counter[label] label_counter[label] += 1 category_array = data_dict[label] category_array[:, :, category_idx] = pair[0][:,:] return data_dict, category_counts def data_dict_mnist_inspect(data_dict, category_counts): data_dimension = (28,28) data_dimension_collapsed = data_dimension[0] * data_dimension[1] """ print("CORRELATIONS") tot = len(list(data_dict.keys())) all_data_correlation = np.zeros((tot, tot)) start_idx = [0]*10 for idx in range(1,10): start_idx[idx] = start_idx[idx-1] + category_counts[idx-1] for i in range(10): data_i = data_dict[i].reshape(784, category_counts[i]) i_a = start_idx[i] if i == 9: i_b = len(data) else: i_b = start_idx[i + 1] for j in range(i+1): print(i,j) data_j = data_dict[j].reshape(784, category_counts[j]) corr = np.dot(data_i.T, data_j) j_a = start_idx[j] if j == 9: j_b = len(data) else: j_b = start_idx[j + 1] all_data_correlation[i_a:i_b, j_a:j_b] = corr all_data_correlation[j_a:j_b, i_a:i_b] = corr.T plt.imshow(corr) plt.colorbar() plt.title('%d,%d (corr)' % (i,j)) plt.show() plt.imshow(all_data_correlation) # out of memory error, show only in parts above plt.colorbar() plt.title('all data (corr)') plt.show() """ for idx in range(10): print(idx) category_amount = category_counts[idx] data_idx_collapsed = data_dict[idx].reshape(data_dimension_collapsed, category_amount) # assumes data will be binarized data_idx_collapsed[data_idx_collapsed > MNIST_BINARIZATION_CUTOFF] = 1 data_idx_collapsed[data_idx_collapsed < MNIST_BINARIZATION_CUTOFF] = 0 print("DISTANCES") category_amount_redux = int(category_amount) distance_arr = np.zeros((category_amount_redux, category_amount_redux)) for i in range(category_amount_redux): a = data_idx_collapsed[:, i] for j in range(i + 1): b = data_idx_collapsed[:, j] val = np.count_nonzero(a != b) distance_arr[i, j] = val distance_arr[j, i] = val print("MANUAL DENDROGRAM") from scipy.cluster.hierarchy import dendrogram, linkage from scipy.spatial.distance import squareform condensed_dist = squareform(distance_arr) Z = linkage(condensed_dist, 'ward') fig = plt.figure(figsize=(25, 10)) dn = dendrogram(Z) plt.title(idx) plt.savefig(DIR_OUTPUT + os.sep + 'dend_%d.png' % idx) return def data_dict_mnist_detailed(data_dict, category_counts, k_pattern=K_PATTERN_DIV): """ Idea here is to further divide the patterns into subtypes to aid classification: (7_0, 7_1, etc) - should the binarization already be happening or not yet? Intermediate form of data_dict_detailed: {6: {0: array, 1: array}} (representing 6_0, 6_1 subtypes for example) Returned form: {'6_0': array, '6_1': array} (representing 6_0, 6_1 subtypes for example) """ data_dimension = (28, 28) data_dimension_collapsed = data_dimension[0] * data_dimension[1] #data_dict_detailed = {idx: {} for idx in range(10)} data_dict_detailed = {idx: {} for idx in category_counts.keys()} #for idx in range(10): for idx in category_counts.keys(): print(idx) category_amount = category_counts[idx] data_idx_collapsed = data_dict[idx].reshape(data_dimension_collapsed, category_amount) # assumes data will be biinarized data_idx_collapsed[data_idx_collapsed > MNIST_BINARIZATION_CUTOFF] = 1 data_idx_collapsed[data_idx_collapsed < MNIST_BINARIZATION_CUTOFF] = 0 # LOAD OPTION print("Auto AgglomerativeClustering") # note euclidean is sqrt of 01 flip distance (for binary data), ward seems best, threshold 24 gave 2-5 clusters per digit print(data_idx_collapsed.shape) model_path = 'pickles' + os.sep + 'agglo%d_%d.joblib' % (idx, k_pattern) if os.path.exists(model_path): cluster = load(model_path) cluster_labels = cluster.fit_predict(data_idx_collapsed.T) else: from sklearn.cluster import AgglomerativeClustering cluster = AgglomerativeClustering(n_clusters=k_pattern, affinity='euclidean', linkage='ward', distance_threshold=None) # cluster = AgglomerativeClustering(n_clusters=None, affinity='euclidean', linkage='ward', distance_threshold=24) cluster_labels = cluster.fit_predict(data_idx_collapsed.T) #dump(cluster, model_path) # TODO figure out loading later; doesn't work if distance_threshold is None, which is mutually exclusive with n_clusters usage # pre-allocate subcategory arrays and fill in unique, counts = np.unique(cluster_labels, return_counts=True) sublabeldict = dict(zip(unique, counts)) print(sublabeldict) for k in sublabeldict.keys(): sublabel_indices = np.argwhere(cluster_labels == k) data_dict_detailed[idx][k] = np.squeeze( data_idx_collapsed[:, sublabel_indices] ).reshape(28, 28, len(sublabel_indices)) data_dict_detailed_flat = {} category_counts_detailed_flat = {} #for idx in range(10): for idx in category_counts.keys(): for subkey in data_dict_detailed[idx].keys(): newkey = '%d_%d' % (idx, subkey) data_dict_detailed_flat[newkey] = data_dict_detailed[idx][subkey] category_counts_detailed_flat[newkey] = data_dict_detailed[idx][subkey].shape[2] return data_dict_detailed_flat, category_counts_detailed_flat def hopfield_mnist_patterns(data_dict, category_counts, pattern_threshold=PATTERN_THRESHOLD, onehot_classify=False): """ data: list of tuples (numpy array, labe;) pattern_threshold: threshold for setting value to 1 in the category-specific voting for pixel values onehot_classify: extend visible state space by vector of size num_classes (default: 10 * num_subpatterns) Returns: xi: N x P binary pattern matrix """ keys = sorted(data_dict.keys()) pattern_idx_to_labels = {idx: keys[idx] for idx in range(len(keys))} data_dimension = data_dict[keys[0]].shape[:2] # testing additional pre-binarization step for key in keys: data_dict[key] = binarize_image_data(data_dict[key], threshold=MNIST_BINARIZATION_CUTOFF) print("Forming %d MNIST patterns" % len(keys)) xi_images = np.zeros((*data_dimension, len(keys)), dtype=int) for idx, key in enumerate(keys): samples = data_dict[key] samples_avg = np.sum(samples, axis=2) / category_counts[key] samples_avg[samples_avg <= pattern_threshold] = -1 # samples_avg[samples_avg <= pattern_threshold] = -1 samples_avg[samples_avg > pattern_threshold] = 1 xi_images[:, :, idx] = samples_avg xi_collapsed = image_data_collapse(xi_images) if onehot_classify: blockmode = True if blockmode: print('warning: building onehot patterns with expt flag blockmode') # need to build the onehot class label vectors # concatenate onehot labels onto the NxP arr xi_collapsed (now (N+P) x P) # if the keys are ordered as expected, this is just appending the PxP identity matrix (-1, 1 form) to xi # if blockmode: instead of identity do blocks of 1s for each subclass (i.e. subclass agnostic) N, P = xi_collapsed.shape xi_collapsed_extended = np.zeros((N+P, P), dtype=int) xi_collapsed_extended[0:N, :] = xi_collapsed[:, :] # note this relies on proper sorting of keys above if blockmode: K = int(P / 10) diag_blocks = np.ones((K, K)) xi_append_01 = np.kron(np.eye(10), diag_blocks) xi_append = xi_append_01 * 2 - 1 else: xi_append = np.eye(P) xi_collapsed_extended[N:, :] = xi_append xi_collapsed = xi_collapsed_extended print("xi_collapsed.shape", xi_collapsed.shape) return xi_images, xi_collapsed, pattern_idx_to_labels def data_synthetic_dual(num_samples=SYNTHETIC_SAMPLES, noise='symmetric', sampling='balanced', datasplit='balanced'): # 1. specify patterns assert SYNTHETIC_DIM == 8 # TODO alternative even integers? maybe very large is better (like images)? pattern_A = np.array([1, 1, 1, 1, -1, -1, -1, -1], dtype=int) # label 0 pattern_B = np.array([1, 1, 1, 1, 1, 1, 1, 1], dtype=int) # label 1 # 2. create data distribution with labels -- TODO care # step 1: have some true distribution in mind (e.g. two equal - or not - minima at the patterns; noise matters) # step 2: generate M samples which follow from that distribution data_array = np.zeros((SYNTHETIC_DIM, SYNTHETIC_SAMPLES), dtype=int) data_labels = np.zeros(SYNTHETIC_SAMPLES, dtype=int) if noise == 'symmetric': assert sampling == 'balanced' assert num_samples % 2 == 0 labels_per_pattern = int(num_samples/2) for idx in range(labels_per_pattern): pattern_A_sample = None # TODO data_array[:, idx] = pattern_A_sample data_labels[idx] = 0 pattern_B_sample_idx = labels_per_pattern pattern_B_sample = None # TODO data_array[:, pattern_B_sample_idx] = pattern_B_sample data_labels[pattern_B_sample_idx] = 1 else: assert noise in SYNTHETIC_NOISE_VALID # 3. save the data # TODO save to DIR_DATA subfolder (diff for each noise/size case?) # 4. split into training and testing (symmetrically or not?) if datasplit == 'balanced': # TODO training = None testing = None else: assert datasplit in SYNTHETIC_DATASPLIT return training, testing def label_to_init_vector(label, randomize=True, prespecified=True): assert isinstance(label, int) # TODO alt starting point based on xi pattern? # given class label e.g. '7', # identify sample image from training set of that class # return binarized numpy array 784x1 of pixel values mnist_training, _ = data_mnist(binarize=True) if prespecified: # for alt '1' style try 24 (fancy) or 23 (tilt right) # for alt '2' style try 76 # for alt '3' style try 50, 44 # for alt '4' style try 150 # for alt '6' style try 147 # for alt '7' style try 38 (fancy), 158 (hook) # for alt '8' style try 144 (thinner), 225 (angled) # for alt '9' style try 162 spec = {0: 108, 1: 6, 2: 213, 3: 7, 4: 164, 5: 0, 6: 66, 7: 15, 8: 41, 9: 45} pair = mnist_training[spec[label]] assert pair[1] == label ret = pair[0].reshape(28**2) else: if randomize: # iterate over the list of pairs randomly until example with label is found np.random.shuffle(mnist_training) # iterate over the list of pairs in current order until example with label is found idx = 0; search = True while search: pair = mnist_training[idx] if pair[1] == label: search = False ret = pair[0].reshape(28 ** 2) idx += 1 return ret if __name__ == '__main__': # get data mnist_training, mnist_testing = data_mnist() inspect_data_dict = True if inspect_data_dict: data_dict, category_counts = data_dict_mnist(mnist_training) data_dict_detailed, category_counts_detailed = data_dict_mnist_detailed(data_dict, category_counts) xi_images, xi_collapsed, pattern_idx_to_labels = hopfield_mnist_patterns(data_dict, category_counts, pattern_threshold=0.0) for idx in range(xi_images.shape[-1]): plt.imshow(xi_images[:, :, idx]) simple_pattern_vis = True if simple_pattern_vis: print("Plot hopfield patterns from 'voting'") data_dict, category_counts = data_dict_mnist(mnist_training) xi_mnist, _ = hopfield_mnist_patterns(data_dict, category_counts, pattern_threshold=0.0) for idx in range(10): plt.imshow(xi_mnist[:, :, idx]) plt.colorbar() plt.show() else: thresholds = [-0.3, -0.2, -0.1, 0.0, 0.1] print("Grid of pattern subplots for varying threshold param", thresholds) fig, ax_arr = plt.subplots(len(thresholds), 10) for p, param in enumerate(thresholds): xi_mnist, _ = hopfield_mnist_patterns(data_dict, category_counts, pattern_threshold=param) xi_mnist = xi_mnist.astype(int) for idx in range(10): ax_arr[p, idx].imshow(xi_mnist[:, :, idx], interpolation='none') for i in range(28): for j in range(28): if xi_mnist[i, j, idx] not in [-1,1]: print(xi_mnist[i, j, idx]) ax_arr[p, idx].set_xticklabels([]) ax_arr[p, idx].set_yticklabels([]) plt.suptitle('Top to bottom thresholds: %s' % thresholds) plt.show()
[ "numpy.count_nonzero", "numpy.array", "matplotlib.pyplot.imshow", "os.path.exists", "sklearn.cluster.AgglomerativeClustering", "scipy.cluster.hierarchy.linkage", "joblib.load", "torchvision.transforms.ToTensor", "numpy.eye", "scipy.spatial.distance.squareform", "matplotlib.pyplot.savefig", "nu...
[((11288, 11337), 'numpy.array', 'np.array', (['[1, 1, 1, 1, -1, -1, -1, -1]'], {'dtype': 'int'}), '([1, 1, 1, 1, -1, -1, -1, -1], dtype=int)\n', (11296, 11337), True, 'import numpy as np\n'), ((11365, 11410), 'numpy.array', 'np.array', (['[1, 1, 1, 1, 1, 1, 1, 1]'], {'dtype': 'int'}), '([1, 1, 1, 1, 1, 1, 1, 1], dtype=int)\n', (11373, 11410), True, 'import numpy as np\n'), ((11692, 11747), 'numpy.zeros', 'np.zeros', (['(SYNTHETIC_DIM, SYNTHETIC_SAMPLES)'], {'dtype': 'int'}), '((SYNTHETIC_DIM, SYNTHETIC_SAMPLES), dtype=int)\n', (11700, 11747), True, 'import numpy as np\n'), ((11766, 11804), 'numpy.zeros', 'np.zeros', (['SYNTHETIC_SAMPLES'], {'dtype': 'int'}), '(SYNTHETIC_SAMPLES, dtype=int)\n', (11774, 11804), True, 'import numpy as np\n'), ((2498, 2568), 'numpy.zeros', 'np.zeros', (['(data_dimension[0], data_dimension[1], category_counts[idx])'], {}), '((data_dimension[0], data_dimension[1], category_counts[idx]))\n', (2506, 2568), True, 'import numpy as np\n'), ((4674, 4730), 'numpy.zeros', 'np.zeros', (['(category_amount_redux, category_amount_redux)'], {}), '((category_amount_redux, category_amount_redux))\n', (4682, 4730), True, 'import numpy as np\n'), ((5207, 5231), 'scipy.spatial.distance.squareform', 'squareform', (['distance_arr'], {}), '(distance_arr)\n', (5217, 5231), False, 'from scipy.spatial.distance import squareform\n'), ((5245, 5276), 'scipy.cluster.hierarchy.linkage', 'linkage', (['condensed_dist', '"""ward"""'], {}), "(condensed_dist, 'ward')\n", (5252, 5276), False, 'from scipy.cluster.hierarchy import dendrogram, linkage\n'), ((5291, 5319), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(25, 10)'}), '(figsize=(25, 10))\n', (5301, 5319), True, 'import matplotlib.pyplot as plt\n'), ((5333, 5346), 'scipy.cluster.hierarchy.dendrogram', 'dendrogram', (['Z'], {}), '(Z)\n', (5343, 5346), False, 'from scipy.cluster.hierarchy import dendrogram, linkage\n'), ((5355, 5369), 'matplotlib.pyplot.title', 'plt.title', (['idx'], {}), '(idx)\n', (5364, 5369), True, 'import matplotlib.pyplot as plt\n'), ((5378, 5432), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(DIR_OUTPUT + os.sep + 'dend_%d.png' % idx)"], {}), "(DIR_OUTPUT + os.sep + 'dend_%d.png' % idx)\n", (5389, 5432), True, 'import matplotlib.pyplot as plt\n'), ((6925, 6951), 'os.path.exists', 'os.path.exists', (['model_path'], {}), '(model_path)\n', (6939, 6951), False, 'import os\n'), ((7716, 7761), 'numpy.unique', 'np.unique', (['cluster_labels'], {'return_counts': '(True)'}), '(cluster_labels, return_counts=True)\n', (7725, 7761), True, 'import numpy as np\n'), ((10420, 10451), 'numpy.zeros', 'np.zeros', (['(N + P, P)'], {'dtype': 'int'}), '((N + P, P), dtype=int)\n', (10428, 10451), True, 'import numpy as np\n'), ((15992, 16049), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (["('Top to bottom thresholds: %s' % thresholds)"], {}), "('Top to bottom thresholds: %s' % thresholds)\n", (16004, 16049), True, 'import matplotlib.pyplot as plt\n'), ((16058, 16068), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (16066, 16068), True, 'import matplotlib.pyplot as plt\n'), ((1201, 1234), 'torchvision.transforms.ToTensor', 'torchvision.transforms.ToTensor', ([], {}), '()\n', (1232, 1234), False, 'import torchvision\n'), ((1330, 1363), 'torchvision.transforms.ToTensor', 'torchvision.transforms.ToTensor', ([], {}), '()\n', (1361, 1363), False, 'import torchvision\n'), ((6975, 6991), 'joblib.load', 'load', (['model_path'], {}), '(model_path)\n', (6979, 6991), False, 'from joblib import load\n'), ((7163, 7276), 'sklearn.cluster.AgglomerativeClustering', 'AgglomerativeClustering', ([], {'n_clusters': 'k_pattern', 'affinity': '"""euclidean"""', 'linkage': '"""ward"""', 'distance_threshold': 'None'}), "(n_clusters=k_pattern, affinity='euclidean', linkage\n ='ward', distance_threshold=None)\n", (7186, 7276), False, 'from sklearn.cluster import AgglomerativeClustering\n'), ((7908, 7940), 'numpy.argwhere', 'np.argwhere', (['(cluster_labels == k)'], {}), '(cluster_labels == k)\n', (7919, 7940), True, 'import numpy as np\n'), ((9538, 9561), 'numpy.sum', 'np.sum', (['samples'], {'axis': '(2)'}), '(samples, axis=2)\n', (9544, 9561), True, 'import numpy as np\n'), ((10645, 10660), 'numpy.ones', 'np.ones', (['(K, K)'], {}), '((K, K))\n', (10652, 10660), True, 'import numpy as np\n'), ((10804, 10813), 'numpy.eye', 'np.eye', (['P'], {}), '(P)\n', (10810, 10813), True, 'import numpy as np\n'), ((13862, 13895), 'numpy.random.shuffle', 'np.random.shuffle', (['mnist_training'], {}), '(mnist_training)\n', (13879, 13895), True, 'import numpy as np\n'), ((14747, 14779), 'matplotlib.pyplot.imshow', 'plt.imshow', (['xi_images[:, :, idx]'], {}), '(xi_images[:, :, idx])\n', (14757, 14779), True, 'import matplotlib.pyplot as plt\n'), ((15100, 15131), 'matplotlib.pyplot.imshow', 'plt.imshow', (['xi_mnist[:, :, idx]'], {}), '(xi_mnist[:, :, idx])\n', (15110, 15131), True, 'import matplotlib.pyplot as plt\n'), ((15144, 15158), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (15156, 15158), True, 'import matplotlib.pyplot as plt\n'), ((15171, 15181), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15179, 15181), True, 'import matplotlib.pyplot as plt\n'), ((4921, 4945), 'numpy.count_nonzero', 'np.count_nonzero', (['(a != b)'], {}), '(a != b)\n', (4937, 4945), True, 'import numpy as np\n'), ((10696, 10706), 'numpy.eye', 'np.eye', (['(10)'], {}), '(10)\n', (10702, 10706), True, 'import numpy as np\n'), ((7982, 8033), 'numpy.squeeze', 'np.squeeze', (['data_idx_collapsed[:, sublabel_indices]'], {}), '(data_idx_collapsed[:, sublabel_indices])\n', (7992, 8033), True, 'import numpy as np\n')]
""" Module with interface and default configurations for the used clustering algorithms """ import os import subprocess from warnings import warn import numpy as np from sklearn.cluster import KMeans, DBSCAN, SpectralClustering, AgglomerativeClustering from sklearn.metrics import pairwise_distances # from excut.misc.multicut import dump_scores # clusteringMethods=dict() # # def register(cl,name): # print('registering %s'%name) # clusteringMethods[name]=cl class ClusteringMethod: def __init__(self, **kwargs): self.seed= kwargs['seed'] if 'seed' in kwargs else None # self.distance_metric=distance_metric pass def cluster(self, vectors, clustering_params=None, output_folder=None): pass def _prepare_data(self, X): pass # @register('Kmeans','test') class Kmeans(ClusteringMethod): __name = 'kmeans' def __init__(self, **kwargs): super().__init__(**kwargs) def cluster(self, vectors, clustering_params={'k': 8, 'distance_metric': 'default'}, output_folder=None): # self._prepare_data(vectors) method = clustering_params['distance_metric'] if clustering_params and 'distance_metric' in clustering_params else 'default' # from sklearn if method != 'default': warn("While using Kmeans, distance_metric=%s is ignored" % method) km = KMeans(n_clusters=clustering_params['k'], n_init=20, random_state=self.seed) y_pred = km.fit_predict(vectors) return y_pred def _prepare_data(self, vectors): return vectors def dump_scores(distance_scores, method, sim_filepath): # sim_filepath = out_dir + "/data.tsv.sim_" + method with open(sim_filepath, 'w') as out_file: out_file.write(str(distance_scores.shape[0]) + '\n') for i in range(distance_scores.shape[0]): for j in range(i + 1, distance_scores.shape[1]): out_file.write(str(i) + '\t' + str(j) + '\t' + str(distance_scores[i][j]) + '\n') return sim_filepath class MultiCut(ClusteringMethod): __name = 'multicut' def __init__(self, **kwargs): super().__init__(**kwargs) def cluster(self, vectors, clustering_params={'p': 0.5, 'distance_metric': 'cosine'}, output_folder=None): # self._prepare_data(vectors) # print(clustering_params) cut_prop = clustering_params['p'] method = clustering_params['distance_metric'] # from sklearn method = method if method !='default' else 'cosine' distance_scores = pairwise_distances(vectors, vectors, metric=method, n_jobs=10) / 2 # cut_prop= np.mean(distance_scores) print("Cutting prob: %f" %cut_prop) sim_file = os.path.join(output_folder, 'sim_%s.tsv' % method) sim_filepath = dump_scores(distance_scores, method, sim_file) print("Run multicut code") output_file = os.path.join(output_folder, "multicut_%s.tsv" % method) subprocess.run([os.path.dirname(os.path.realpath(__file__))+"/multicut/find-clustering", "-i", sim_filepath, "-o", output_file, '-p', str(cut_prop)]) y_pred = np.loadtxt(output_file, dtype=np.int) return y_pred def _prepare_data(self, vectors): return vectors class DBScan(ClusteringMethod): __name = 'DBSCAN' def __init__(self, **kwargs): super().__init__(**kwargs) def cluster(self, vectors, clustering_params=None, output_folder=None): # self._prepare_data(vectors) method = clustering_params['distance_metric'] # from sklearn method = method if method != 'default' else 'euclidean' algorithm = DBSCAN(algorithm='auto', eps=0.5, metric=method, metric_params=None) y_pred = algorithm.fit_predict(vectors) return y_pred def _prepare_data(self, vectors): return vectors class Spectral(ClusteringMethod): def __init__(self, **kwargs): super().__init__(**kwargs) def cluster(self, vectors, clustering_params=None, output_folder=None): # self._prepare_data(vectors) method = clustering_params['distance_metric'] # from sklearn if method != 'default': warn("Spectral Clustering ignores distance_metric= %s" % method) n_clusters= clustering_params['k'] if clustering_params['k'] else 8 # the default in the algorithm = SpectralClustering(n_clusters=n_clusters, assign_labels="discretize", random_state=self.seed) y_pred = algorithm.fit_predict(vectors) return y_pred class Hierarchical(ClusteringMethod): def __init__(self, **kwargs): super().__init__(**kwargs) def cluster(self, vectors, clustering_params=None, output_folder=None): # self._prepare_data(vectors) method = clustering_params['distance_metric'] # from sklearn method = method if method != 'default' else 'euclidean' n_clusters= clustering_params['k'] if clustering_params['k'] else 8 # the default in the algorithm = AgglomerativeClustering(n_clusters=n_clusters, affinity='precomputed', linkage='complete') distance_scores = pairwise_distances(vectors, vectors, metric=method, n_jobs=10) y_pred = algorithm.fit_predict(distance_scores) return y_pred def get_clustering_method(method_name: str, seed=0): # TODO Factory design but should be changed method_name = method_name.lower() if method_name == 'kmeans': return Kmeans(seed=seed) elif method_name == 'multicut': return MultiCut(seed=seed) elif method_name == 'dbscan': return DBScan(seed=seed) elif method_name == 'spectral': return Spectral(seed=seed) elif method_name == 'hierarchical': return Hierarchical(seed=seed) else: raise Exception("Method %s not Supported!" % method_name)
[ "sklearn.cluster.KMeans", "sklearn.cluster.SpectralClustering", "sklearn.cluster.AgglomerativeClustering", "os.path.join", "sklearn.metrics.pairwise_distances", "os.path.realpath", "warnings.warn", "numpy.loadtxt", "sklearn.cluster.DBSCAN" ]
[((1371, 1447), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': "clustering_params['k']", 'n_init': '(20)', 'random_state': 'self.seed'}), "(n_clusters=clustering_params['k'], n_init=20, random_state=self.seed)\n", (1377, 1447), False, 'from sklearn.cluster import KMeans, DBSCAN, SpectralClustering, AgglomerativeClustering\n'), ((2715, 2765), 'os.path.join', 'os.path.join', (['output_folder', "('sim_%s.tsv' % method)"], {}), "(output_folder, 'sim_%s.tsv' % method)\n", (2727, 2765), False, 'import os\n'), ((2894, 2949), 'os.path.join', 'os.path.join', (['output_folder', "('multicut_%s.tsv' % method)"], {}), "(output_folder, 'multicut_%s.tsv' % method)\n", (2906, 2949), False, 'import os\n'), ((3126, 3163), 'numpy.loadtxt', 'np.loadtxt', (['output_file'], {'dtype': 'np.int'}), '(output_file, dtype=np.int)\n', (3136, 3163), True, 'import numpy as np\n'), ((3644, 3712), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {'algorithm': '"""auto"""', 'eps': '(0.5)', 'metric': 'method', 'metric_params': 'None'}), "(algorithm='auto', eps=0.5, metric=method, metric_params=None)\n", (3650, 3712), False, 'from sklearn.cluster import KMeans, DBSCAN, SpectralClustering, AgglomerativeClustering\n'), ((4361, 4458), 'sklearn.cluster.SpectralClustering', 'SpectralClustering', ([], {'n_clusters': 'n_clusters', 'assign_labels': '"""discretize"""', 'random_state': 'self.seed'}), "(n_clusters=n_clusters, assign_labels='discretize',\n random_state=self.seed)\n", (4379, 4458), False, 'from sklearn.cluster import KMeans, DBSCAN, SpectralClustering, AgglomerativeClustering\n'), ((5001, 5095), 'sklearn.cluster.AgglomerativeClustering', 'AgglomerativeClustering', ([], {'n_clusters': 'n_clusters', 'affinity': '"""precomputed"""', 'linkage': '"""complete"""'}), "(n_clusters=n_clusters, affinity='precomputed',\n linkage='complete')\n", (5024, 5095), False, 'from sklearn.cluster import KMeans, DBSCAN, SpectralClustering, AgglomerativeClustering\n'), ((5118, 5180), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['vectors', 'vectors'], {'metric': 'method', 'n_jobs': '(10)'}), '(vectors, vectors, metric=method, n_jobs=10)\n', (5136, 5180), False, 'from sklearn.metrics import pairwise_distances\n'), ((1291, 1357), 'warnings.warn', 'warn', (["('While using Kmeans, distance_metric=%s is ignored' % method)"], {}), "('While using Kmeans, distance_metric=%s is ignored' % method)\n", (1295, 1357), False, 'from warnings import warn\n'), ((2540, 2602), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['vectors', 'vectors'], {'metric': 'method', 'n_jobs': '(10)'}), '(vectors, vectors, metric=method, n_jobs=10)\n', (2558, 2602), False, 'from sklearn.metrics import pairwise_distances\n'), ((4179, 4243), 'warnings.warn', 'warn', (["('Spectral Clustering ignores distance_metric= %s' % method)"], {}), "('Spectral Clustering ignores distance_metric= %s' % method)\n", (4183, 4243), False, 'from warnings import warn\n'), ((2990, 3016), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (3006, 3016), False, 'import os\n')]
from pyAudioAnalysis import audioBasicIO from pyAudioAnalysis import audioFeatureExtraction import matplotlib.pyplot as plt import numpy as np from sklearn.model_selection import cross_val_score import io from sklearn.mixture import gaussian_mixture my_dir = ['A','B','C','D'] my_file = ['1.wav','2.wav','3.wav','4.wav','5.wav','6.wav','7.wav','8.wav','9.wav','10.wav','11.wav','12.wav','13.wav','14.wav','15.wav','16.wav'] def init_data(x): A = np.zeros(shape=(x, 1)) B = np.zeros(shape=(x, 1)) C = np.zeros(shape=(x, 1)) D = np.zeros(shape=(x, 1)) return A, B, C, D A = np.zeros(shape=(13, 1)) B = np.zeros(shape=(13, 1)) C = np.zeros(shape=(13, 1)) D = np.zeros(shape=(13, 1)) for ffile in my_file: [Fs, x] = audioBasicIO.readAudioFile("/home/joexu01/PycharmProjects/speak_reg/data/train/A/" + ffile) F = audioFeatureExtraction.stFeatureExtraction_modified(x, Fs, 0.050 * Fs, 0.025 * Fs) f = F[8:21, ] A = np.hstack((A, f)) A = A[:, 1:].T print(A.shape) for ffile in my_file: [Fs, x] = audioBasicIO.readAudioFile("/home/joexu01/PycharmProjects/speak_reg/data/train/B/" + ffile) F = audioFeatureExtraction.stFeatureExtraction_modified(x, Fs, 0.050 * Fs, 0.025 * Fs) f = F[8:21, ] B = np.hstack((B, f)) B = B[:, 1:].T print(B.shape) for ffile in my_file: [Fs, x] = audioBasicIO.readAudioFile("/home/joexu01/PycharmProjects/speak_reg/data/train/C/" + ffile) F = audioFeatureExtraction.stFeatureExtraction_modified(x, Fs, 0.050 * Fs, 0.025 * Fs) f = F[8:21, ] C = np.hstack((C, f)) C = C[:, 1:].T print(C.shape) for ffile in my_file: [Fs, x] = audioBasicIO.readAudioFile("/home/joexu01/PycharmProjects/speak_reg/data/train/D/" + ffile) F = audioFeatureExtraction.stFeatureExtraction_modified(x, Fs, 0.050 * Fs, 0.025 * Fs) f = F[8:21, ] D = np.hstack((D, f)) D = D[:, 1:].T print(D.shape) A = A[:1000, ] # np.savetxt('test01.csv', A, delimiter=',') B = B[:1000, ] C = C[:1000, ] D = D[:1000, ] # 取前1000个数据准备第一轮洗牌 shuffle_index_step1 = np.random.permutation(1000) A = A[shuffle_index_step1] B = B[shuffle_index_step1] C = C[shuffle_index_step1] D = D[shuffle_index_step1] # REST = np.vstack((B,C,D)) # 再取洗牌后的前n_learn个数据进行学习 n_learn = 650 A = A[:n_learn, ] # REST = REST[:1950, ] B = B[:n_learn, ] C = C[:n_learn, ] D = D[:n_learn, ] data_set = np.vstack((A,B,C,D)) data = np.mat(data_set) A_y = np.empty(n_learn, dtype=int) A_y = np.full(A_y.shape, 1) B_y = np.empty(n_learn, dtype=int) B_y = np.full(B_y.shape, 2) C_y = np.empty(n_learn, dtype=int) C_y = np.full(C_y.shape, 3) D_y = np.empty(n_learn, dtype=int) D_y = np.full(D_y.shape, 4) label_set = np.hstack((A_y,B_y,C_y,D_y)) label = np.array(label_set) clf = gaussian_mixture.GaussianMixture(n_components=4, covariance_type='full') clf.fit(data, label) # 预测 my_fflile = ['1.wav','2.wav','3.wav','4.wav'] for mydir in my_dir: print(mydir + '\n') for myfile in my_fflile: [Fs, x] = audioBasicIO.readAudioFile("/home/joexu01/PycharmProjects/speak_reg/data/test/" + mydir + "/" + myfile) F = audioFeatureExtraction.stFeatureExtraction_modified(x, Fs, 0.050 * Fs, 0.025 * Fs) f = F[8:21, ].T result = clf.predict(f) counter = f.shape[0] counter1 = counter2 = counter3 = counter4 = 0 for i in range(0, counter): if result[i] == 1: counter1 += 1 if result[i] == 2: counter2 += 1 if result[i] == 3: counter3 += 1 if result[i] == 4: counter4 += 1 print(counter1, ',', counter2, ',', counter3, ',', counter4, '\n')
[ "pyAudioAnalysis.audioBasicIO.readAudioFile", "numpy.mat", "pyAudioAnalysis.audioFeatureExtraction.stFeatureExtraction_modified", "numpy.hstack", "sklearn.mixture.gaussian_mixture.GaussianMixture", "numpy.array", "numpy.zeros", "numpy.empty", "numpy.vstack", "numpy.full", "numpy.random.permutati...
[((597, 620), 'numpy.zeros', 'np.zeros', ([], {'shape': '(13, 1)'}), '(shape=(13, 1))\n', (605, 620), True, 'import numpy as np\n'), ((625, 648), 'numpy.zeros', 'np.zeros', ([], {'shape': '(13, 1)'}), '(shape=(13, 1))\n', (633, 648), True, 'import numpy as np\n'), ((653, 676), 'numpy.zeros', 'np.zeros', ([], {'shape': '(13, 1)'}), '(shape=(13, 1))\n', (661, 676), True, 'import numpy as np\n'), ((681, 704), 'numpy.zeros', 'np.zeros', ([], {'shape': '(13, 1)'}), '(shape=(13, 1))\n', (689, 704), True, 'import numpy as np\n'), ((2028, 2055), 'numpy.random.permutation', 'np.random.permutation', (['(1000)'], {}), '(1000)\n', (2049, 2055), True, 'import numpy as np\n'), ((2339, 2362), 'numpy.vstack', 'np.vstack', (['(A, B, C, D)'], {}), '((A, B, C, D))\n', (2348, 2362), True, 'import numpy as np\n'), ((2367, 2383), 'numpy.mat', 'np.mat', (['data_set'], {}), '(data_set)\n', (2373, 2383), True, 'import numpy as np\n'), ((2391, 2419), 'numpy.empty', 'np.empty', (['n_learn'], {'dtype': 'int'}), '(n_learn, dtype=int)\n', (2399, 2419), True, 'import numpy as np\n'), ((2426, 2447), 'numpy.full', 'np.full', (['A_y.shape', '(1)'], {}), '(A_y.shape, 1)\n', (2433, 2447), True, 'import numpy as np\n'), ((2454, 2482), 'numpy.empty', 'np.empty', (['n_learn'], {'dtype': 'int'}), '(n_learn, dtype=int)\n', (2462, 2482), True, 'import numpy as np\n'), ((2489, 2510), 'numpy.full', 'np.full', (['B_y.shape', '(2)'], {}), '(B_y.shape, 2)\n', (2496, 2510), True, 'import numpy as np\n'), ((2517, 2545), 'numpy.empty', 'np.empty', (['n_learn'], {'dtype': 'int'}), '(n_learn, dtype=int)\n', (2525, 2545), True, 'import numpy as np\n'), ((2552, 2573), 'numpy.full', 'np.full', (['C_y.shape', '(3)'], {}), '(C_y.shape, 3)\n', (2559, 2573), True, 'import numpy as np\n'), ((2580, 2608), 'numpy.empty', 'np.empty', (['n_learn'], {'dtype': 'int'}), '(n_learn, dtype=int)\n', (2588, 2608), True, 'import numpy as np\n'), ((2615, 2636), 'numpy.full', 'np.full', (['D_y.shape', '(4)'], {}), '(D_y.shape, 4)\n', (2622, 2636), True, 'import numpy as np\n'), ((2649, 2680), 'numpy.hstack', 'np.hstack', (['(A_y, B_y, C_y, D_y)'], {}), '((A_y, B_y, C_y, D_y))\n', (2658, 2680), True, 'import numpy as np\n'), ((2686, 2705), 'numpy.array', 'np.array', (['label_set'], {}), '(label_set)\n', (2694, 2705), True, 'import numpy as np\n'), ((2713, 2785), 'sklearn.mixture.gaussian_mixture.GaussianMixture', 'gaussian_mixture.GaussianMixture', ([], {'n_components': '(4)', 'covariance_type': '"""full"""'}), "(n_components=4, covariance_type='full')\n", (2745, 2785), False, 'from sklearn.mixture import gaussian_mixture\n'), ((453, 475), 'numpy.zeros', 'np.zeros', ([], {'shape': '(x, 1)'}), '(shape=(x, 1))\n', (461, 475), True, 'import numpy as np\n'), ((484, 506), 'numpy.zeros', 'np.zeros', ([], {'shape': '(x, 1)'}), '(shape=(x, 1))\n', (492, 506), True, 'import numpy as np\n'), ((515, 537), 'numpy.zeros', 'np.zeros', ([], {'shape': '(x, 1)'}), '(shape=(x, 1))\n', (523, 537), True, 'import numpy as np\n'), ((546, 568), 'numpy.zeros', 'np.zeros', ([], {'shape': '(x, 1)'}), '(shape=(x, 1))\n', (554, 568), True, 'import numpy as np\n'), ((742, 838), 'pyAudioAnalysis.audioBasicIO.readAudioFile', 'audioBasicIO.readAudioFile', (["('/home/joexu01/PycharmProjects/speak_reg/data/train/A/' + ffile)"], {}), "(\n '/home/joexu01/PycharmProjects/speak_reg/data/train/A/' + ffile)\n", (768, 838), False, 'from pyAudioAnalysis import audioBasicIO\n'), ((842, 927), 'pyAudioAnalysis.audioFeatureExtraction.stFeatureExtraction_modified', 'audioFeatureExtraction.stFeatureExtraction_modified', (['x', 'Fs', '(0.05 * Fs)', '(0.025 * Fs)'], {}), '(x, Fs, 0.05 * Fs, 0.025 *\n Fs)\n', (893, 927), False, 'from pyAudioAnalysis import audioFeatureExtraction\n'), ((951, 968), 'numpy.hstack', 'np.hstack', (['(A, f)'], {}), '((A, f))\n', (960, 968), True, 'import numpy as np\n'), ((1036, 1132), 'pyAudioAnalysis.audioBasicIO.readAudioFile', 'audioBasicIO.readAudioFile', (["('/home/joexu01/PycharmProjects/speak_reg/data/train/B/' + ffile)"], {}), "(\n '/home/joexu01/PycharmProjects/speak_reg/data/train/B/' + ffile)\n", (1062, 1132), False, 'from pyAudioAnalysis import audioBasicIO\n'), ((1136, 1221), 'pyAudioAnalysis.audioFeatureExtraction.stFeatureExtraction_modified', 'audioFeatureExtraction.stFeatureExtraction_modified', (['x', 'Fs', '(0.05 * Fs)', '(0.025 * Fs)'], {}), '(x, Fs, 0.05 * Fs, 0.025 *\n Fs)\n', (1187, 1221), False, 'from pyAudioAnalysis import audioFeatureExtraction\n'), ((1245, 1262), 'numpy.hstack', 'np.hstack', (['(B, f)'], {}), '((B, f))\n', (1254, 1262), True, 'import numpy as np\n'), ((1330, 1426), 'pyAudioAnalysis.audioBasicIO.readAudioFile', 'audioBasicIO.readAudioFile', (["('/home/joexu01/PycharmProjects/speak_reg/data/train/C/' + ffile)"], {}), "(\n '/home/joexu01/PycharmProjects/speak_reg/data/train/C/' + ffile)\n", (1356, 1426), False, 'from pyAudioAnalysis import audioBasicIO\n'), ((1430, 1515), 'pyAudioAnalysis.audioFeatureExtraction.stFeatureExtraction_modified', 'audioFeatureExtraction.stFeatureExtraction_modified', (['x', 'Fs', '(0.05 * Fs)', '(0.025 * Fs)'], {}), '(x, Fs, 0.05 * Fs, 0.025 *\n Fs)\n', (1481, 1515), False, 'from pyAudioAnalysis import audioFeatureExtraction\n'), ((1539, 1556), 'numpy.hstack', 'np.hstack', (['(C, f)'], {}), '((C, f))\n', (1548, 1556), True, 'import numpy as np\n'), ((1624, 1720), 'pyAudioAnalysis.audioBasicIO.readAudioFile', 'audioBasicIO.readAudioFile', (["('/home/joexu01/PycharmProjects/speak_reg/data/train/D/' + ffile)"], {}), "(\n '/home/joexu01/PycharmProjects/speak_reg/data/train/D/' + ffile)\n", (1650, 1720), False, 'from pyAudioAnalysis import audioBasicIO\n'), ((1724, 1809), 'pyAudioAnalysis.audioFeatureExtraction.stFeatureExtraction_modified', 'audioFeatureExtraction.stFeatureExtraction_modified', (['x', 'Fs', '(0.05 * Fs)', '(0.025 * Fs)'], {}), '(x, Fs, 0.05 * Fs, 0.025 *\n Fs)\n', (1775, 1809), False, 'from pyAudioAnalysis import audioFeatureExtraction\n'), ((1833, 1850), 'numpy.hstack', 'np.hstack', (['(D, f)'], {}), '((D, f))\n', (1842, 1850), True, 'import numpy as np\n'), ((2951, 3064), 'pyAudioAnalysis.audioBasicIO.readAudioFile', 'audioBasicIO.readAudioFile', (["('/home/joexu01/PycharmProjects/speak_reg/data/test/' + mydir + '/' + myfile)"], {}), "(\n '/home/joexu01/PycharmProjects/speak_reg/data/test/' + mydir + '/' + myfile\n )\n", (2977, 3064), False, 'from pyAudioAnalysis import audioBasicIO\n'), ((3113, 3198), 'pyAudioAnalysis.audioFeatureExtraction.stFeatureExtraction_modified', 'audioFeatureExtraction.stFeatureExtraction_modified', (['x', 'Fs', '(0.05 * Fs)', '(0.025 * Fs)'], {}), '(x, Fs, 0.05 * Fs, 0.025 *\n Fs)\n', (3164, 3198), False, 'from pyAudioAnalysis import audioFeatureExtraction\n')]
import torch import numpy as np import scipy import scipy.stats import scipy.spatial.distance import seaborn as sns import matplotlib import matplotlib.pyplot as plt device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def mse(x, y): res = (x - y)**2 return res.mean() def diss(divtau, theta): res = divtau * theta return res.mean() def evaluate_mse(alpha, beta, dataset, models): tests_batch = 4 tests_loader = torch.utils.data.DataLoader(dataset, batch_size=tests_batch, shuffle=False) for x in models: x.eval() preds = [None] * len(models) dataset.inputs[:, 3] *= alpha dataset.inputs[:, :3] += beta with torch.no_grad(): for step, batch in enumerate(tests_loader): data, labs = batch if step == 0: for i, x in enumerate(models): preds[i] = x(data) else: for i, x in enumerate(models): preds[i] = torch.cat((preds[i], x(data)), axis=0) dataset.inputs[:, :3] -= beta dataset.inputs[:, 3] /= alpha data, labs = dataset[:] for i, x in enumerate(models): preds[i] = preds[i] / alpha mse_eval = {} for i, x in enumerate(models): mse_eval[x.name] = mse(preds[i][:, 0], labs[:, 0]) return mse_eval def evaluate(dataset, models): tests_batch = 4 tests_loader = torch.utils.data.DataLoader(dataset, batch_size=tests_batch, shuffle=False) for x in models: x.eval() preds = [None] * len(models) with torch.no_grad(): for step, batch in enumerate(tests_loader): data, labs = batch if step == 0: for i, x in enumerate(models): preds[i] = x(data) else: for i, x in enumerate(models): preds[i] = torch.cat((preds[i], x(data)), axis=0) data, labs = dataset[:] mse_eval = {} mse_eval['smag'] = mse(labs[:, 1], labs[:, 0]) mse_eval['rg'] = mse(labs[:, 2], labs[:, 0]) for i, x in enumerate(models): mse_eval[x.name] = mse(preds[i][:, 0], labs[:, 0]) diss_truth = diss(labs[:, 0], data[:, 3]) diss_eval = {} diss_eval['smag'] = (diss(labs[:, 1], data[:, 3]) - diss_truth) diss_eval['rg'] = (diss(labs[:, 2], data[:, 3]) - diss_truth) for i, x in enumerate(models): diss_eval[x.name] = (diss(preds[i][:, 0], data[:, 3]) - diss_truth) # switch to numpy for convenience data = data.detach().cpu().numpy() labs = labs.detach().cpu().numpy() for i in range(0, len(models)): preds[i] = preds[i].detach().cpu().numpy() cc_eval = {} cc_eval['smag'] = scipy.stats.pearsonr(labs[:, 1].flatten(), labs[:, 0].flatten())[0] cc_eval['rg'] = scipy.stats.pearsonr(labs[:, 2].flatten(), labs[:, 0].flatten())[0] for i, x in enumerate(models): cc_eval[x.name] = scipy.stats.pearsonr(preds[i][:, 0].flatten(), labs[:, 0].flatten())[0] # distr rng = [min(labs.min(), min(x.min() for x in preds)), max(labs.max(), max(x.max() for x in preds))] m_h = np.histogram(200 * ((labs[:, 0].flatten() - rng[0]) / (rng[1] - rng[0])) - 100, bins=range(-100, 100), density=True)[0] m_s = np.histogram(200 * ((labs[:, 1].flatten() - rng[0]) / (rng[1] - rng[0])) - 100, bins=range(-100, 100), density=True)[0] m_r = np.histogram(200 * ((labs[:, 2].flatten() - rng[0]) / (rng[1] - rng[0])) - 100, bins=range(-100, 100), density=True)[0] hists = [None] * len(models) for i, x in enumerate(models): hists[i] = np.histogram(200 * ((preds[i][:, 0].flatten() - rng[0]) / (rng[1] - rng[0])) - 100, bins=range(-100, 100), density=True)[0] m_s[m_s == 0] = 1e-12 m_r[m_r == 0] = 1e-12 for h in hists: h[h == 0] = 1e-12 div_eval = {} div_eval['smag'] = scipy.spatial.distance.jensenshannon(m_h, m_s) div_eval['rg'] = scipy.spatial.distance.jensenshannon(m_h, m_r) for i, x in enumerate(models): div_eval[x.name] = scipy.spatial.distance.jensenshannon(m_h, hists[i]) m_s[m_s == 1e-12] = 0 m_r[m_r == 1e-12] = 0 for h in hists: h[h == 1e-12] = 0 ks_eval = {} ks_eval['smag'] = scipy.stats.ks_2samp(labs[:, 1].flatten(), labs[:, 0].flatten())[0] ks_eval['rg'] = scipy.stats.ks_2samp(labs[:, 2].flatten(), labs[:, 0].flatten())[0] for i, x in enumerate(models): ks_eval[x.name] = scipy.stats.ks_2samp(preds[i][:, 0].flatten(), labs[:, 0].flatten())[0] print( '''\t\t MSE (L2) \t\t Dissipation error (I) \t Cross-correlation (P)\n \t Smag \t {} \t {} \t {}\n \t Rg \t {} \t {} \t {}\n'''.format( mse_eval['smag'], diss_eval['smag'], cc_eval['smag'], mse_eval['rg'], diss_eval['rg'], cc_eval['rg'], )) for x in models: print('\t{} \t {} \t {} \t {}\n'.format(x.name, mse_eval[x.name], diss_eval[x.name], cc_eval[x.name])) print( '''\t\t JS distance (J) \t KS test (K)\n \t Smag \t {} \t {}\n \t Rg \t {} \t {}\n'''.format( div_eval['smag'], ks_eval['smag'], div_eval['rg'], ks_eval['rg'] )) for x in models: print('\t{} \t {} \t {}\n'.format(x.name, div_eval[x.name], ks_eval[x.name])) # plots samples = [0, int(dataset.samples * 1 / 4), int(dataset.samples / 2), int(dataset.samples * 3 / 4), dataset.samples - 1] sliceid = int(dataset.size / 2) # div div_fig, div_axes = plt.subplots( nrows=3 + len(models), ncols=5 + 1, figsize=(12.5,(3 + len(models))*2.5), constrained_layout=True, gridspec_kw={"width_ratios": np.append(np.repeat(1, 5), 0.05)} ) div_fig.suptitle(r'$\nabla \cdot \mathbf{s}$', fontsize=20) rng = [ labs[samples[:], 0, sliceid].min(), labs[samples[:], 0, sliceid].max() ] div_axes[0,0].contourf(labs[samples[0], 0, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[0,1].contourf(labs[samples[1], 0, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[0,2].contourf(labs[samples[2], 0, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[0,3].contourf(labs[samples[3], 0, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) c1 = div_axes[0,4].contourf(labs[samples[4], 0, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[1,0].contourf(labs[samples[0], 1, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[1,1].contourf(labs[samples[1], 1, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[1,2].contourf(labs[samples[2], 1, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[1,3].contourf(labs[samples[3], 1, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[1,4].contourf(labs[samples[4], 1, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[2,0].contourf(labs[samples[0], 2, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[2,1].contourf(labs[samples[1], 2, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[2,2].contourf(labs[samples[2], 2, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[2,3].contourf(labs[samples[3], 2, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[2,4].contourf(labs[samples[4], 2, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) for i, x in enumerate(models): div_axes[3+i,0].contourf(preds[i][samples[0], 0, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[3+i,1].contourf(preds[i][samples[1], 0, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[3+i,2].contourf(preds[i][samples[2], 0, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[3+i,3].contourf(preds[i][samples[3], 0, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_axes[3+i,4].contourf(preds[i][samples[4], 0, sliceid], 100, cmap='bwr', vmin=rng[0], vmax=rng[1]) div_fig.colorbar(c1, cax=div_axes[0,5]) div_fig.colorbar(c1, cax=div_axes[1,5]) div_fig.colorbar(c1, cax=div_axes[2,5]) for i, x in enumerate(models): div_fig.colorbar(c1, cax=div_axes[3+i,5]) div_axes[0,0].set_ylabel(r'$\mathcal{M}$', fontsize=15) div_axes[1,0].set_ylabel(r'$\mathcal{M}_{\mathrm{DynSmag}}$', fontsize=15) div_axes[2,0].set_ylabel(r'$\mathcal{M}_{\mathrm{DynRG}}$', fontsize=15) for i, x in enumerate(models): div_axes[3+i,0].set_ylabel(r'$\mathcal{M}_{\mathrm{' + x.name + '}}$', fontsize=15) len_div = 3 + len(models) -1 div_axes[len_div,0].set_xlabel(r'$\mathcal{S}_{' + str((dataset.established + samples[0] + 1) * 500) + r'}$', fontsize=15) div_axes[len_div,1].set_xlabel(r'$\mathcal{S}_{' + str((dataset.established + samples[1] + 1) * 500) + r'}$', fontsize=15) div_axes[len_div,2].set_xlabel(r'$\mathcal{S}_{' + str((dataset.established + samples[2] + 1) * 500) + r'}$', fontsize=15) div_axes[len_div,3].set_xlabel(r'$\mathcal{S}_{' + str((dataset.established + samples[3] + 1) * 500) + r'}$', fontsize=15) div_axes[len_div,4].set_xlabel(r'$\mathcal{S}_{' + str((dataset.established + samples[4] + 1) * 500) + r'}$', fontsize=15) # div error ediv_fig, ediv_axes = plt.subplots( nrows=2 + len(models), ncols=5 + 1, figsize=(12.5,(2 + len(models))*2.5), constrained_layout=True, gridspec_kw={"width_ratios": np.append(np.repeat(1, 5), 0.05)} ) ediv_fig.suptitle(r'$|\nabla \cdot \mathbf{s} - \widehat{\nabla \cdot \mathbf{s}}|$', fontsize=20) ediv_smag = np.abs(labs[:, 0] - labs[:, 1]) ediv_rg = np.abs(labs[:, 0] - labs[:, 2]) errors = [None] * len(models) for i, x in enumerate(models): errors[i] = np.abs(labs[:, 0] - preds[i][:, 0]) rng = [ min( ediv_smag[samples, sliceid].min(), ediv_rg [samples, sliceid].min(), min(x[samples, sliceid].min() for x in errors) ), max( ediv_smag[samples, sliceid].max(), ediv_rg [samples, sliceid].max(), max(x[samples, sliceid].max() for x in errors) ) ] ediv_axes[0,0].contourf(ediv_smag[samples[0], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_axes[0,1].contourf(ediv_smag[samples[1], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_axes[0,2].contourf(ediv_smag[samples[2], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_axes[0,3].contourf(ediv_smag[samples[3], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_axes[0,4].contourf(ediv_smag[samples[4], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_axes[1,0].contourf(ediv_rg [samples[0], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_axes[1,1].contourf(ediv_rg [samples[1], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_axes[1,2].contourf(ediv_rg [samples[2], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_axes[1,3].contourf(ediv_rg [samples[3], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) c1 = ediv_axes[1,4].contourf(ediv_rg[samples[4], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) for i, x in enumerate(models): ediv_axes[2+i,0].contourf(errors[i][samples[0], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_axes[2+i,1].contourf(errors[i][samples[1], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_axes[2+i,2].contourf(errors[i][samples[2], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_axes[2+i,3].contourf(errors[i][samples[3], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_axes[2+i,4].contourf(errors[i][samples[4], sliceid], 100, cmap='coolwarm', vmin=rng[0], vmax=rng[1]) ediv_fig.colorbar(c1, cax=ediv_axes[0,5]) ediv_fig.colorbar(c1, cax=ediv_axes[1,5]) for i, x in enumerate(models): ediv_fig.colorbar(c1, cax=ediv_axes[2+i,5]) ediv_axes[0,0].set_ylabel(r'$\mathcal{M}_{\mathrm{DynSmag}}$', fontsize=15) ediv_axes[1,0].set_ylabel(r'$\mathcal{M}_{\mathrm{DynRG}}$', fontsize=15) for i, x in enumerate(models): ediv_axes[2+i,0].set_ylabel(r'$\mathcal{M}_{\mathrm{' + x.name + '}}$', fontsize=15) len_ediv = 2 + len(models) -1 ediv_axes[len_ediv,0].set_xlabel(r'$\mathcal{S}_{' + str((dataset.established + samples[0] + 1) * 500) + r'}$', fontsize=15) ediv_axes[len_ediv,1].set_xlabel(r'$\mathcal{S}_{' + str((dataset.established + samples[1] + 1) * 500) + r'}$', fontsize=15) ediv_axes[len_ediv,2].set_xlabel(r'$\mathcal{S}_{' + str((dataset.established + samples[2] + 1) * 500) + r'}$', fontsize=15) ediv_axes[len_ediv,3].set_xlabel(r'$\mathcal{S}_{' + str((dataset.established + samples[3] + 1) * 500) + r'}$', fontsize=15) ediv_axes[len_ediv,4].set_xlabel(r'$\mathcal{S}_{' + str((dataset.established + samples[4] + 1) * 500) + r'}$', fontsize=15) pdf_div_fig, pdf_div_axes = plt.subplots( nrows=1, ncols=1, figsize=(5,5), constrained_layout=True ) m_h = np.histogram(labs[:, 0].flatten(), bins=200, density=True) m_s = np.histogram(labs[:, 1].flatten(), bins=200, density=True) m_r = np.histogram(labs[:, 2].flatten(), bins=200, density=True) pdf = [None] * len(models) for i, x in enumerate(models): pdf[i] = np.histogram(preds[i][:, 0].flatten(), bins=200, density=True) pdf_div_axes.plot(m_h[1][1:], m_h[0], label=r'$\mathcal{M}_{\mathrm{DNS}}$') pdf_div_axes.plot(m_s[1][1:], m_s[0], label=r'$\mathcal{M}_{\mathrm{DynSmag}}$') pdf_div_axes.plot(m_r[1][1:], m_r[0], label=r'$\mathcal{M}_{\mathrm{DynRG}}$') for i, x in enumerate(models): pdf_div_axes.plot(pdf[i][1][1:], pdf[i][0], label=r'$\mathcal{M}_{\mathrm{' + x.name + '}}$') pdf_div_axes.set_yscale('log', nonpositive='clip') pdf_div_axes.set_ylim(1e-6, 10) pdf_div_axes.legend(fontsize=15) pdf_div_axes.grid(True, linestyle='--') pdf_div_axes.set_ylabel(r'$pdf$', fontsize=20) pdf_div_axes.set_xlabel(r'$\nabla \cdot \mathbf{s}$', fontsize=20) cdf_div_fig, cdf_div_axes = plt.subplots( nrows=1, ncols=1, figsize=(5,5), constrained_layout=True ) cdf_div_axes.plot(m_h[1][1:], np.cumsum(m_h[0]) / m_h[0].sum(), label=r'$\mathcal{M}_{\mathrm{DNS}}$') cdf_div_axes.plot(m_s[1][1:], np.cumsum(m_s[0]) / m_s[0].sum(), label=r'$\mathcal{M}_{\mathrm{DynSmag}}$') cdf_div_axes.plot(m_r[1][1:], np.cumsum(m_r[0]) / m_r[0].sum(), label=r'$\mathcal{M}_{\mathrm{DynRG}}$') for i, x in enumerate(models): cdf_div_axes.plot(pdf[i][1][1:], np.cumsum(pdf[i][0]) / pdf[i][0].sum(), label=r'$\mathcal{M}_{\mathrm{' + x.name + '}}$') cdf_div_axes.set_yscale('log', nonpositive='clip') cdf_div_axes.set_ylim(1e-6, 5) cdf_div_axes.legend(fontsize=15) cdf_div_axes.grid(True, linestyle='--') cdf_div_axes.set_ylabel(r'$cdf$', fontsize=20) cdf_div_axes.set_xlabel(r'$\nabla \cdot \mathbf{s}$', fontsize=20) qq_stride = int(dataset.samples / 2) qq_div_fig, qq_div_axes = plt.subplots( nrows=1, ncols=1, figsize=(5,5), constrained_layout=True ) _, qq_x = scipy.stats.probplot(labs[:, 0].flatten(), fit=False) m_hv, m_hx, m_hy = np.histogram2d(qq_x, scipy.stats.probplot(labs[:, 1].flatten(), fit=False)[1], bins=400) m_sv, m_sx, m_sy = np.histogram2d(qq_x, scipy.stats.probplot(labs[:, 2].flatten(), fit=False)[1], bins=400) dens = [None] * len(models) for i, x in enumerate(models): dens[i] = np.histogram2d(qq_x, scipy.stats.probplot(preds[i][:, 0].flatten(), fit=False)[1], bins=400) ax_hv = np.where(m_hv != 0) ax_sv = np.where(m_sv != 0) downsp = [None] * len(models) for i, x in enumerate(models): downsp[i] = np.where(dens[i][0] != 0) qq_div_axes.scatter(m_hx[ax_hv[0]], m_hy[ax_hv[1]], 10.0, label=r'$\mathcal{M}_{\mathrm{DynSmag}}$') qq_div_axes.scatter(m_sx[ax_sv[0]], m_sy[ax_sv[1]], 10.0, label=r'$\mathcal{M}_{\mathrm{DynRG}}$') for i, x in enumerate(models): qq_div_axes.scatter(dens[i][1][downsp[i][0]], dens[i][2][downsp[i][1]], 10.0, label=r'$\mathcal{M}_{\mathrm{' + x.name + '}}$') qq_div_axes.plot([np.min(labs[:, 0]), np.max(labs[:, 0])], [np.min(labs[:, 0]), np.max(labs[:, 0])], 'k--') qq_div_axes.legend(fontsize=15) qq_div_axes.grid(True, linestyle='--') qq_div_axes.set_xlabel(r'$cdf^{-1}_{\mathcal{M}_{\mathrm{DNS}}} \, \, \nabla \cdot \mathbf{s}$', fontsize=20) qq_div_axes.set_ylabel(r'$cdf^{-1}_{\mathcal{M}} \, \, \nabla \cdot \mathbf{s}$', fontsize=20)
[ "numpy.abs", "numpy.repeat", "numpy.where", "numpy.min", "numpy.max", "torch.cuda.is_available", "numpy.cumsum", "torch.utils.data.DataLoader", "torch.no_grad", "matplotlib.pyplot.subplots", "scipy.spatial.distance.jensenshannon" ]
[((449, 524), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'tests_batch', 'shuffle': '(False)'}), '(dataset, batch_size=tests_batch, shuffle=False)\n', (476, 524), False, 'import torch\n'), ((1326, 1401), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'tests_batch', 'shuffle': '(False)'}), '(dataset, batch_size=tests_batch, shuffle=False)\n', (1353, 1401), False, 'import torch\n'), ((3717, 3763), 'scipy.spatial.distance.jensenshannon', 'scipy.spatial.distance.jensenshannon', (['m_h', 'm_s'], {}), '(m_h, m_s)\n', (3753, 3763), False, 'import scipy\n'), ((3785, 3831), 'scipy.spatial.distance.jensenshannon', 'scipy.spatial.distance.jensenshannon', (['m_h', 'm_r'], {}), '(m_h, m_r)\n', (3821, 3831), False, 'import scipy\n'), ((9244, 9275), 'numpy.abs', 'np.abs', (['(labs[:, 0] - labs[:, 1])'], {}), '(labs[:, 0] - labs[:, 1])\n', (9250, 9275), True, 'import numpy as np\n'), ((9290, 9321), 'numpy.abs', 'np.abs', (['(labs[:, 0] - labs[:, 2])'], {}), '(labs[:, 0] - labs[:, 2])\n', (9296, 9321), True, 'import numpy as np\n'), ((12580, 12651), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(1)', 'figsize': '(5, 5)', 'constrained_layout': '(True)'}), '(nrows=1, ncols=1, figsize=(5, 5), constrained_layout=True)\n', (12592, 12651), True, 'import matplotlib.pyplot as plt\n'), ((13717, 13788), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(1)', 'figsize': '(5, 5)', 'constrained_layout': '(True)'}), '(nrows=1, ncols=1, figsize=(5, 5), constrained_layout=True)\n', (13729, 13788), True, 'import matplotlib.pyplot as plt\n'), ((14641, 14712), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(1)', 'figsize': '(5, 5)', 'constrained_layout': '(True)'}), '(nrows=1, ncols=1, figsize=(5, 5), constrained_layout=True)\n', (14653, 14712), True, 'import matplotlib.pyplot as plt\n'), ((15217, 15236), 'numpy.where', 'np.where', (['(m_hv != 0)'], {}), '(m_hv != 0)\n', (15225, 15236), True, 'import numpy as np\n'), ((15247, 15266), 'numpy.where', 'np.where', (['(m_sv != 0)'], {}), '(m_sv != 0)\n', (15255, 15266), True, 'import numpy as np\n'), ((203, 228), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (226, 228), False, 'import torch\n'), ((680, 695), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (693, 695), False, 'import torch\n'), ((1481, 1496), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1494, 1496), False, 'import torch\n'), ((3888, 3939), 'scipy.spatial.distance.jensenshannon', 'scipy.spatial.distance.jensenshannon', (['m_h', 'hists[i]'], {}), '(m_h, hists[i])\n', (3924, 3939), False, 'import scipy\n'), ((9404, 9439), 'numpy.abs', 'np.abs', (['(labs[:, 0] - preds[i][:, 0])'], {}), '(labs[:, 0] - preds[i][:, 0])\n', (9410, 9439), True, 'import numpy as np\n'), ((15353, 15378), 'numpy.where', 'np.where', (['(dens[i][0] != 0)'], {}), '(dens[i][0] != 0)\n', (15361, 15378), True, 'import numpy as np\n'), ((13841, 13858), 'numpy.cumsum', 'np.cumsum', (['m_h[0]'], {}), '(m_h[0])\n', (13850, 13858), True, 'import numpy as np\n'), ((13946, 13963), 'numpy.cumsum', 'np.cumsum', (['m_s[0]'], {}), '(m_s[0])\n', (13955, 13963), True, 'import numpy as np\n'), ((14055, 14072), 'numpy.cumsum', 'np.cumsum', (['m_r[0]'], {}), '(m_r[0])\n', (14064, 14072), True, 'import numpy as np\n'), ((15774, 15792), 'numpy.min', 'np.min', (['labs[:, 0]'], {}), '(labs[:, 0])\n', (15780, 15792), True, 'import numpy as np\n'), ((15794, 15812), 'numpy.max', 'np.max', (['labs[:, 0]'], {}), '(labs[:, 0])\n', (15800, 15812), True, 'import numpy as np\n'), ((15816, 15834), 'numpy.min', 'np.min', (['labs[:, 0]'], {}), '(labs[:, 0])\n', (15822, 15834), True, 'import numpy as np\n'), ((15836, 15854), 'numpy.max', 'np.max', (['labs[:, 0]'], {}), '(labs[:, 0])\n', (15842, 15854), True, 'import numpy as np\n'), ((14200, 14220), 'numpy.cumsum', 'np.cumsum', (['pdf[i][0]'], {}), '(pdf[i][0])\n', (14209, 14220), True, 'import numpy as np\n'), ((5448, 5463), 'numpy.repeat', 'np.repeat', (['(1)', '(5)'], {}), '(1, 5)\n', (5457, 5463), True, 'import numpy as np\n'), ((9095, 9110), 'numpy.repeat', 'np.repeat', (['(1)', '(5)'], {}), '(1, 5)\n', (9104, 9110), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D #data = np.loadtxt("data.txt").reshape((2048,2048)) data = np.memmap("DenseOffset.off", dtype=np.float32, mode='r', shape=(100,100,2)) data1=data[:,:,0] print(data1) plt.imshow(data1, cmap=cm.coolwarm) plt.show() #plt.ylim([-2.2,0.2]) #plt.plot(data1[0,0:500]) #plt.show() #pdata= data[:,:,1] #nx, ny = 300, 300 #x = range(nx) #y = range(ny) #hf = plt.figure() #ha = hf.add_subplot(111, projection='3d') #X, Y = np.meshgrid(x, y) # `plot_surface` expects `x` and `y` data to be 2D #ha.plot_surface(X, Y, pdata) #plt.show()
[ "matplotlib.pyplot.imshow", "numpy.memmap", "matplotlib.pyplot.show" ]
[((177, 254), 'numpy.memmap', 'np.memmap', (['"""DenseOffset.off"""'], {'dtype': 'np.float32', 'mode': '"""r"""', 'shape': '(100, 100, 2)'}), "('DenseOffset.off', dtype=np.float32, mode='r', shape=(100, 100, 2))\n", (186, 254), True, 'import numpy as np\n'), ((284, 319), 'matplotlib.pyplot.imshow', 'plt.imshow', (['data1'], {'cmap': 'cm.coolwarm'}), '(data1, cmap=cm.coolwarm)\n', (294, 319), True, 'import matplotlib.pyplot as plt\n'), ((322, 332), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (330, 332), True, 'import matplotlib.pyplot as plt\n')]
# coding: utf-8 import numpy as np import cPickle import utils import h5py import os def convert_files(file_paths, vocabulary, punctuations, output_path): inputs = [] outputs = [] punctuation = " " for file_path in file_paths: with open(file_path, 'r') as corpus: for line in corpus: array = np.zeros(shape=(1, len(vocabulary)), dtype=np.int8) array[0,utils.input_word_index(vocabulary, "<START>")] = 1 inputs.append(array) array = np.zeros(shape=(1, len(punctuations)), dtype=np.int8) array[0,utils.punctuation_index(punctuations, " ")] = 1 outputs.append(array) for token in line.split(): if token in punctuations: punctuation = token continue else: array = np.zeros(shape=(1, len(vocabulary)), dtype=np.int8) array[0,utils.input_word_index(vocabulary, token)] = 1 inputs.append(array) array = np.zeros(shape=(1, len(punctuations)), dtype=np.int8) array[0,utils.punctuation_index(punctuations, punctuation)] = 1 outputs.append(array) punctuation = " " array = np.zeros(shape=(1, len(vocabulary)), dtype=np.int8) array[0,utils.input_word_index(vocabulary, "<END>")] = 1 inputs.append(array) array = np.zeros(shape=(1, len(punctuations)), dtype=np.int8) array[0,utils.punctuation_index(punctuations, punctuation)] = 1 outputs.append(array) assert len(inputs) == len(outputs) inputs = np.array(inputs, dtype=np.int8).reshape((len(inputs), 1, len(vocabulary))) outputs = np.array(outputs, dtype=np.int16).reshape((len(inputs), len(punctuations))) f = h5py.File(output_path + '.h5', "w") dset = f.create_dataset('inputs', data=inputs, dtype='i8') dset = f.create_dataset('outputs',data=outputs, dtype='i8') data = {"vocabulary": vocabulary, "punctuations": punctuations, "total_size": len(inputs)} with open(output_path + '.pkl', 'wb') as output_file: cPickle.dump(data, output_file, protocol=cPickle.HIGHEST_PROTOCOL) PHASE1_TRAIN_PATH = "../data/train1" PHASE1_DEV_PATH = "../data/dev1" PUNCTUATIONS = {" ": 0, ".PERIOD": 1, ",COMMA": 2} VOCABULARY_FILE = "../raw_data/vocab" TRAIN_DATA = "../raw_data/train.txt" DEV_DATA = "../raw_data/dev.txt" if not os.path.exists("../data"): os.makedirs("../data") print("Converting data...") vocabulary = utils.load_vocabulary(VOCABULARY_FILE) convert_files([TRAIN_DATA], vocabulary, PUNCTUATIONS, PHASE1_TRAIN_PATH) convert_files([DEV_DATA], vocabulary, PUNCTUATIONS, PHASE1_DEV_PATH)
[ "os.path.exists", "cPickle.dump", "utils.load_vocabulary", "os.makedirs", "utils.punctuation_index", "h5py.File", "numpy.array", "utils.input_word_index" ]
[((2755, 2793), 'utils.load_vocabulary', 'utils.load_vocabulary', (['VOCABULARY_FILE'], {}), '(VOCABULARY_FILE)\n', (2776, 2793), False, 'import utils\n'), ((2011, 2046), 'h5py.File', 'h5py.File', (["(output_path + '.h5')", '"""w"""'], {}), "(output_path + '.h5', 'w')\n", (2020, 2046), False, 'import h5py\n'), ((2660, 2685), 'os.path.exists', 'os.path.exists', (['"""../data"""'], {}), "('../data')\n", (2674, 2685), False, 'import os\n'), ((2689, 2711), 'os.makedirs', 'os.makedirs', (['"""../data"""'], {}), "('../data')\n", (2700, 2711), False, 'import os\n'), ((2353, 2419), 'cPickle.dump', 'cPickle.dump', (['data', 'output_file'], {'protocol': 'cPickle.HIGHEST_PROTOCOL'}), '(data, output_file, protocol=cPickle.HIGHEST_PROTOCOL)\n', (2365, 2419), False, 'import cPickle\n'), ((1837, 1868), 'numpy.array', 'np.array', (['inputs'], {'dtype': 'np.int8'}), '(inputs, dtype=np.int8)\n', (1845, 1868), True, 'import numpy as np\n'), ((1926, 1959), 'numpy.array', 'np.array', (['outputs'], {'dtype': 'np.int16'}), '(outputs, dtype=np.int16)\n', (1934, 1959), True, 'import numpy as np\n'), ((427, 472), 'utils.input_word_index', 'utils.input_word_index', (['vocabulary', '"""<START>"""'], {}), "(vocabulary, '<START>')\n", (449, 472), False, 'import utils\n'), ((634, 676), 'utils.punctuation_index', 'utils.punctuation_index', (['punctuations', '""" """'], {}), "(punctuations, ' ')\n", (657, 676), False, 'import utils\n'), ((1484, 1527), 'utils.input_word_index', 'utils.input_word_index', (['vocabulary', '"""<END>"""'], {}), "(vocabulary, '<END>')\n", (1506, 1527), False, 'import utils\n'), ((1689, 1739), 'utils.punctuation_index', 'utils.punctuation_index', (['punctuations', 'punctuation'], {}), '(punctuations, punctuation)\n', (1712, 1739), False, 'import utils\n'), ((1029, 1070), 'utils.input_word_index', 'utils.input_word_index', (['vocabulary', 'token'], {}), '(vocabulary, token)\n', (1051, 1070), False, 'import utils\n'), ((1239, 1289), 'utils.punctuation_index', 'utils.punctuation_index', (['punctuations', 'punctuation'], {}), '(punctuations, punctuation)\n', (1262, 1289), False, 'import utils\n')]
import pickle import itertools import os import math from sklearn.preprocessing import normalize import re from operator import add import matplotlib.pyplot as plt import numpy as np import argparse import pylab as pl from utils import compute_embds_matrix if __name__ == "__main__": parser = argparse.ArgumentParser(description='Visualize nearest neighbors') parser.add_argument('--start', required=True, help='Start of the distance threshold for neighbors', type=float) parser.add_argument('--end', required=True, help='End of the distance threshold for neighbors', type=float) parser.add_argument('--step_size', required=True, help='Step size of the epsilon', type=float) #parser.add_argument('--resolution', help='resolution of the trained model', type=int) parser.add_argument('--path', required=True, help='The path for reading embeddings', type=str) args, other_args = parser.parse_known_args() M = 10000 N = 10 #path = os.path.join(args.path, str(args.resolution)) path = args.path A_lst = compute_embds_matrix(os.path.join(path, 'embds'), M, N) for epsilon in list(np.arange(args.start, args.end, args.step_size)): print(epsilon) with open(os.path.join(path, 'neighbors', 'final_neighbors_count_lstoflst_{}.pkl'.format(epsilon)), 'rb') as fp: final_neighbors_count_lstoflst = pickle.load(fp) # final_neighbors_count_lst = final_neighbors_count_lstoflst[0] final_neighbors_count_lst = final_neighbors_count_lstoflst[N-1] print(max(final_neighbors_count_lst)) final_neighbors_count_lst = np.asarray(final_neighbors_count_lst) indices = np.argpartition(final_neighbors_count_lst, -1)[-1:] print(indices) indices = np.asarray(indices) with open(os.path.join(args.path, 'neighbors', 'clustered_indices.pkl'), 'wb') as handle: pickle.dump(list(indices),handle) print(final_neighbors_count_lst[indices]) # A = np.concatenate(A_lst, axis=0) # AT = np.transpose(A) from shutil import copyfile # k = 0 # embds_lst = [] # for ind in indices: # # vec = A[ind] # # dist_arr = np.matmul(vec, AT) # # dist_arr = np.arccos(dist_arr) / math.pi # # index_lst = list(np.nonzero(dist_arr <= epsilon)[0]) # # pair_lst = [(index, dist_arr[index]) for index in index_lst] # # pair_lst = sorted(pair_lst, key=lambda x: x[1]) # # i = 0 # # for index, _ in pair_lst: # # latents_dir = os.path.join('latents', '{}_{}'.format((index // 10000) * 10000, (index // 10000 + 1) * 10000)) # # src = os.path.join(path, latents_dir, '{}_{}.npy'.format((index // 10000) * 10000, (index // 10000 + 1) * 10000)) # # dst = os.path.join(path, 'neighbors', str(epsilon), str(ind), 'collision', 'neighbors_latents') # # if not os.path.exists(dst): # # os.makedirs(dst) # # dst = os.path.join(dst, '{}_{}.npy'.format(index, i)) # # latents = np.load(src) # # np.save(dst, latents[index-(index // 10000) * 10000]) # # i += 1 # # # cluster # #latents_dir = os.path.join('latents', '{}_{}'.format((ind // 10000) * 10000, (ind // 100000 + 1) * 10000)) # latents_dir = os.path.join('latents', '0_1000000') # src = os.path.join(path, latents_dir, '{}_{}.npy'.format((ind // 10000) * 10000, (ind // 10000 + 1) * 10000)) # dst = os.path.join(path, 'neighbors', str(epsilon), 'clustered_latents') # if not os.path.exists(dst): # os.makedirs(dst) # dst = os.path.join(dst, '{}_{}.npy'.format(ind, k)) # latents = np.load(src) # np.save(dst, latents[ind % 10000]) # # # # cluster # # embds_dir = os.path.join('embds', '0_1000000') # # src = os.path.join(path, embds_dir, '{}_{}.pkl'.format((ind // 10000) * 10000, (ind // 10000 + 1) * 10000)) # # dst = os.path.join(path, 'neighbors', str(epsilon), 'clustered_embds') # # if not os.path.exists(dst): # # os.makedirs(dst) # # dst = os.path.join(dst, '{}_{}.pkl'.format(ind, k)) # # embd = pickle.load(open(src, 'rb')) # # embds_lst.append(embd[ind % 10000]) # # pickle.dump(embd[ind % 10000], open(dst, 'wb')) # # # # cluster # # images_dir = os.path.join('images', '{}_{}'.format((ind // 10000) * 10000, (ind // 10000 + 1) * 10000)) # # src = os.path.join(home_dir, images_dir, '{}.png'.format(ind)) # # dst = os.path.join(home_dir, 'neighbors', str(epsilon), 'clustered_images') # # if not os.path.exists(dst): # # os.makedirs(dst) # # dst = os.path.join(dst, '{}_{}.png'.format(ind, k)) # # copyfile(src, dst) # k += 1 # pickle.dump(np.asarray(embds_lst), open(os.path.join(path, 'neighbors', str(epsilon), 'clustered_embds.pkl'), 'wb'))
[ "argparse.ArgumentParser", "numpy.argpartition", "numpy.asarray", "pickle.load", "os.path.join", "numpy.arange" ]
[((301, 367), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Visualize nearest neighbors"""'}), "(description='Visualize nearest neighbors')\n", (324, 367), False, 'import argparse\n'), ((1073, 1100), 'os.path.join', 'os.path.join', (['path', '"""embds"""'], {}), "(path, 'embds')\n", (1085, 1100), False, 'import os\n'), ((1133, 1180), 'numpy.arange', 'np.arange', (['args.start', 'args.end', 'args.step_size'], {}), '(args.start, args.end, args.step_size)\n', (1142, 1180), True, 'import numpy as np\n'), ((1615, 1652), 'numpy.asarray', 'np.asarray', (['final_neighbors_count_lst'], {}), '(final_neighbors_count_lst)\n', (1625, 1652), True, 'import numpy as np\n'), ((1764, 1783), 'numpy.asarray', 'np.asarray', (['indices'], {}), '(indices)\n', (1774, 1783), True, 'import numpy as np\n'), ((1372, 1387), 'pickle.load', 'pickle.load', (['fp'], {}), '(fp)\n', (1383, 1387), False, 'import pickle\n'), ((1671, 1717), 'numpy.argpartition', 'np.argpartition', (['final_neighbors_count_lst', '(-1)'], {}), '(final_neighbors_count_lst, -1)\n', (1686, 1717), True, 'import numpy as np\n'), ((1802, 1863), 'os.path.join', 'os.path.join', (['args.path', '"""neighbors"""', '"""clustered_indices.pkl"""'], {}), "(args.path, 'neighbors', 'clustered_indices.pkl')\n", (1814, 1863), False, 'import os\n')]
import numpy as np class MotionFeatureExtractor: """ Functor for extracting motion features from a detection. """ def __init__(self, stats): """ Constructor. """ ## Dict containing mean and std of motion features. self.stats = stats def __call__(self, det, last=None): """ Extracts motion features from a detection. Inputs: det -- Current detection. last -- Previous detection. """ width = float(det["w"]) height = float(det["h"]) if last is None: features = np.array([0.0, 0.0, width, height]) else: x_diff = float(det["center_x"]) - float(last["center_x"]) y_diff = float(det["center_y"]) - float(last["center_y"]) frame_diff = float(det["frame"]) - float(last["frame"]) if frame_diff == 0.0: features = np.array([0.0, 0.0, width, height]) else: features = np.array([ x_diff / frame_diff, y_diff / frame_diff, width, height]) features = features - self.stats["mean"] features = np.divide(features, self.stats["std"]) return features
[ "numpy.array", "numpy.divide" ]
[((1219, 1257), 'numpy.divide', 'np.divide', (['features', "self.stats['std']"], {}), "(features, self.stats['std'])\n", (1228, 1257), True, 'import numpy as np\n'), ((601, 636), 'numpy.array', 'np.array', (['[0.0, 0.0, width, height]'], {}), '([0.0, 0.0, width, height])\n', (609, 636), True, 'import numpy as np\n'), ((920, 955), 'numpy.array', 'np.array', (['[0.0, 0.0, width, height]'], {}), '([0.0, 0.0, width, height])\n', (928, 955), True, 'import numpy as np\n'), ((1001, 1068), 'numpy.array', 'np.array', (['[x_diff / frame_diff, y_diff / frame_diff, width, height]'], {}), '([x_diff / frame_diff, y_diff / frame_diff, width, height])\n', (1009, 1068), True, 'import numpy as np\n')]
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class QNetwork(nn.Module): """Actor (Policy) Model.""" def __init__(self, state_size, action_size, seed, hidden_layers=[64, 32], drop_p=0.2): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed hidden_layers (list of int): Number of activation units on each layer drop_p (float): dropout probability to apply to each Dropout layer """ super(QNetwork, self).__init__() self.seed = seed self.drop_p = drop_p torch.manual_seed(seed) # hidden layer parameters: (hi, ho) if len(hidden_layers) == 1: layer_sizes = hidden_layers[0] else: layer_sizes = zip(hidden_layers[:-1], hidden_layers[1:]) # Instanciate hidden_layers with input_layer input_layer = nn.Linear(state_size, hidden_layers[0]) self.hidden_layers = nn.ModuleList([input_layer]) self.hidden_layers.extend([nn.Linear(hi, ho) for hi, ho in layer_sizes]) # output layer: regression: a q_est for every action accessible from state s self.out = nn.Linear(hidden_layers[-1], action_size) if self.drop_p is not None: self.dropout = nn.Dropout(p=self.drop_p) def forward(self, state): """Build a network that maps state -> action values.""" x = state for fc in self.hidden_layers: x = fc(x) x = F.relu(x) if self.drop_p is not None: x = self.dropout(x) x = self.out(x) return x class DuelQNetwork(nn.Module): """Actor (Policy) Model. Implement Dueling Q-Network input layer is 2d (batch_size x state_size) tensor """ def __init__(self, state_size, action_size, seed, hidden_layers=[64, 32], drop_p=0.2): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed hidden_layers (list of int): Number of activation units on each layer drop_p (float): dropout probability to apply to each Dropout layer """ super(DuelQNetwork, self).__init__() torch.manual_seed(seed) self.seed = seed self.action_size = action_size self.drop_p = drop_p # hidden layer parameters: (hi, ho) if len(hidden_layers) == 1: layer_sizes = [(hidden_layers[0], hidden_layers[0])] else: layer_sizes = zip(hidden_layers[:-1], hidden_layers[1:]) # Instanciate hidden_layers with input_layer input_layer = nn.Linear(state_size, hidden_layers[0]) self.hidden_layers = nn.ModuleList([input_layer]) self.hidden_layers.extend([nn.Linear(hi, ho) for hi, ho in layer_sizes]) # output layer: # value stream # advantage stream # regression: a q_est for every action accessible from state s self.out_val = nn.Linear(hidden_layers[-1], 1) self.out_adv = nn.Linear(hidden_layers[-1], action_size) if self.drop_p is not None: self.dropout = nn.Dropout(p=self.drop_p) def forward(self, state): """Build a network that maps state -> action values.""" x = state for fc in self.hidden_layers: x = fc(x) x = F.relu(x) if self.drop_p is not None: x = self.dropout(x) x_val = F.relu( self.out_val(x) ).expand(x.size(0), self.action_size) x_adv = F.relu( self.out_adv(x) ) x_adv_mean = x_adv.mean() x_out = x_val + (x_adv - x_adv_mean) return x_out class DDPGActor(nn.Module): """ Actor (Policy) Model. mu(states; theta_mu), output is a vector of dim action_size, where each element is a float, e.g. controlling an elbow, requires a single metric (flexion torque), controlling a wrist, requires: (rotation torque, flexion torque) states should be normalized prior to input output layer is a tanh to be in [-1,+1] """ def __init__(self, state_size, action_size, seed, fc1_units=24, fc2_units=48, add_bn1=False): """Initialize parameters and build model. Params ====== state_size (int): state space dimension action_size (int): action space dimension, e.g. controlling an elbow requires an action of 1 dimension (torque), action vector should be normalized seed (int): Random seed fc1_units (int): Number of nodes in first hidden layer fc2_units (int): Number of nodes in second hidden layer add_bn1 (bool): Add BatchNorm to the first layer """ super(DDPGActor, self).__init__() self.seed = seed self.add_bn1 = add_bn1 torch.manual_seed(seed) self.fc1 = nn.Linear(state_size, fc1_units) if self.add_bn1: self.bn1 = nn.BatchNorm1d(fc1_units) self.fc2 = nn.Linear(fc1_units, fc2_units) # output layer: regression, a deterministic policy mu at state s self.out = nn.Linear(fc2_units, action_size) self.reset_parameters() def forward(self, state): """Build an actor (policy) network that maps states -> actions.""" x = state if self.add_bn1 and len(x.size()) > 1: x = F.relu(self.bn1(self.fc1(x))) else: x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.tanh(self.out(x)) return x def reset_parameters(self): self.fc1.weight.data.uniform_(*hidden_init(self.fc1)) self.fc2.weight.data.uniform_(*hidden_init(self.fc2)) self.out.weight.data.uniform_(-3e-3, 3e-3) class DDPGCritic(nn.Module): """ Critic (Value) Model. Q(states, mu(states; theta_mu); theta_Q) state is inputted in the first layer, the second layer takes this output and actions see DDPGActor to check mu(states; theta_mu) states should be normalized prior to input """ def __init__(self, state_size, action_size, seed, fcs1_units=24, fc2_units=48, add_bn1 = False): """Initialize parameters and build model. Params ====== state_size (int): state space dimension action_size (int): action space dimension, e.g. controlling an elbow requires an action of 1 dimension (torque), action vector should be normalized seed (int): Random seed fcs1_units (int): Number of nodes in the first hidden layer fc2_units (int): Number of nodes in the second hidden layer add_bn1 (bool): Add BatchNorm to the first layer """ super(DDPGCritic, self).__init__() self.seed = seed torch.manual_seed(seed) self.add_bn1 = add_bn1 self.fcs1 = nn.Linear(state_size, fcs1_units) self.fc2 = nn.Linear(fcs1_units + action_size, fc2_units) if self.add_bn1: self.bn1 = nn.BatchNorm1d(fcs1_units) # output layer: regression: a q_est(s) self.out = nn.Linear(fc2_units, 1) self.reset_parameters() def forward(self, state, action): """Build a critic (value) network that maps (state, action) pairs -> Q-values.""" xs = state if self.add_bn1: xs = F.relu(self.bn1(self.fcs1(xs))) else: xs = F.relu(self.fcs1(xs)) x = torch.cat((xs, action), dim=1) x = F.relu(self.fc2(x)) x = self.out(x) return x def reset_parameters(self): self.fcs1.weight.data.uniform_(*hidden_init(self.fcs1)) self.fc2.weight.data.uniform_(*hidden_init(self.fc2)) self.out.weight.data.uniform_(-3e-3, 3e-3) def hidden_init(layer): fan_in = layer.weight.data.size()[0] lim = 1. / np.sqrt(fan_in) return (-lim, lim)
[ "torch.manual_seed", "torch.nn.Dropout", "numpy.sqrt", "torch.nn.ModuleList", "torch.nn.BatchNorm1d", "torch.nn.Linear", "torch.nn.functional.relu", "torch.cat" ]
[((741, 764), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (758, 764), False, 'import torch\n'), ((1048, 1087), 'torch.nn.Linear', 'nn.Linear', (['state_size', 'hidden_layers[0]'], {}), '(state_size, hidden_layers[0])\n', (1057, 1087), True, 'import torch.nn as nn\n'), ((1117, 1145), 'torch.nn.ModuleList', 'nn.ModuleList', (['[input_layer]'], {}), '([input_layer])\n', (1130, 1145), True, 'import torch.nn as nn\n'), ((1332, 1373), 'torch.nn.Linear', 'nn.Linear', (['hidden_layers[-1]', 'action_size'], {}), '(hidden_layers[-1], action_size)\n', (1341, 1373), True, 'import torch.nn as nn\n'), ((2491, 2514), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (2508, 2514), False, 'import torch\n'), ((2911, 2950), 'torch.nn.Linear', 'nn.Linear', (['state_size', 'hidden_layers[0]'], {}), '(state_size, hidden_layers[0])\n', (2920, 2950), True, 'import torch.nn as nn\n'), ((2980, 3008), 'torch.nn.ModuleList', 'nn.ModuleList', (['[input_layer]'], {}), '([input_layer])\n', (2993, 3008), True, 'import torch.nn as nn\n'), ((3259, 3290), 'torch.nn.Linear', 'nn.Linear', (['hidden_layers[-1]', '(1)'], {}), '(hidden_layers[-1], 1)\n', (3268, 3290), True, 'import torch.nn as nn\n'), ((3314, 3355), 'torch.nn.Linear', 'nn.Linear', (['hidden_layers[-1]', 'action_size'], {}), '(hidden_layers[-1], action_size)\n', (3323, 3355), True, 'import torch.nn as nn\n'), ((5148, 5171), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (5165, 5171), False, 'import torch\n'), ((5192, 5224), 'torch.nn.Linear', 'nn.Linear', (['state_size', 'fc1_units'], {}), '(state_size, fc1_units)\n', (5201, 5224), True, 'import torch.nn as nn\n'), ((5318, 5349), 'torch.nn.Linear', 'nn.Linear', (['fc1_units', 'fc2_units'], {}), '(fc1_units, fc2_units)\n', (5327, 5349), True, 'import torch.nn as nn\n'), ((5443, 5476), 'torch.nn.Linear', 'nn.Linear', (['fc2_units', 'action_size'], {}), '(fc2_units, action_size)\n', (5452, 5476), True, 'import torch.nn as nn\n'), ((7108, 7131), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (7125, 7131), False, 'import torch\n'), ((7184, 7217), 'torch.nn.Linear', 'nn.Linear', (['state_size', 'fcs1_units'], {}), '(state_size, fcs1_units)\n', (7193, 7217), True, 'import torch.nn as nn\n'), ((7237, 7283), 'torch.nn.Linear', 'nn.Linear', (['(fcs1_units + action_size)', 'fc2_units'], {}), '(fcs1_units + action_size, fc2_units)\n', (7246, 7283), True, 'import torch.nn as nn\n'), ((7425, 7448), 'torch.nn.Linear', 'nn.Linear', (['fc2_units', '(1)'], {}), '(fc2_units, 1)\n', (7434, 7448), True, 'import torch.nn as nn\n'), ((7769, 7799), 'torch.cat', 'torch.cat', (['(xs, action)'], {'dim': '(1)'}), '((xs, action), dim=1)\n', (7778, 7799), False, 'import torch\n'), ((8166, 8181), 'numpy.sqrt', 'np.sqrt', (['fan_in'], {}), '(fan_in)\n', (8173, 8181), True, 'import numpy as np\n'), ((1438, 1463), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'self.drop_p'}), '(p=self.drop_p)\n', (1448, 1463), True, 'import torch.nn as nn\n'), ((1653, 1662), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (1659, 1662), True, 'import torch.nn.functional as F\n'), ((3420, 3445), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'self.drop_p'}), '(p=self.drop_p)\n', (3430, 3445), True, 'import torch.nn as nn\n'), ((3635, 3644), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (3641, 3644), True, 'import torch.nn.functional as F\n'), ((5273, 5298), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['fc1_units'], {}), '(fc1_units)\n', (5287, 5298), True, 'import torch.nn as nn\n'), ((7332, 7358), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['fcs1_units'], {}), '(fcs1_units)\n', (7346, 7358), True, 'import torch.nn as nn\n'), ((1181, 1198), 'torch.nn.Linear', 'nn.Linear', (['hi', 'ho'], {}), '(hi, ho)\n', (1190, 1198), True, 'import torch.nn as nn\n'), ((3044, 3061), 'torch.nn.Linear', 'nn.Linear', (['hi', 'ho'], {}), '(hi, ho)\n', (3053, 3061), True, 'import torch.nn as nn\n')]
import numpy as np from py.forest import Node class Cube(): def __init__(self, node): assert isinstance(node, Node) self.start = node.start self.end = node.end self.dim = node.dim self.id_string = node.id_string self.split_axis = node.split_axis self.split_vals = node.split_vals self.vol = 1 for i in range(len(self.start)): self.vol = self.vol*(self.end[i] - self.start[i]) self.frac = 0 self.child = [Cube(child_node) for child_node in node.child] def est_density(self, pts, total): self.frac = len(pts)/total if self.split_axis != -1: split_pts = self.split_points(pts) for i in range(len(self.child)): self.child[i].est_density(split_pts[i], total) def split_points(self, pts): _, num_pts = np.shape(pts) indices = [[] for _ in range(len(self.split_vals) + 1)] list_vals = [self.start[self.split_axis]] list_vals.append(self.split_vals) list_vals.append(self.end[self.split_axis]) for i in range(num_pts): for j in range(len(list_vals) -1): if (pts[self.split_axis][i] >= list_vals[j]) and\ (pts[self.split_axis][i] < list_vals[j+1]): indices[j].append(i) split_pts = [] for j in range(len(list_vals) -1): split_pts.append(pts[:, indices[j]]) return split_pts def __str__(self): str_val = "Cube ID: " + str(self.id_string) + "\n" str_val += "Boundary: " for i in range(self.dim): str_val += " [" + str(self.start[i]) + ", " + str(self.end[i]) + "]" if i < self.dim -1: str_val += " x" else: str_val += "\n" if self.split_axis != -1: str_val += "Axis: " + str(self.split_axis) + ", " str_val += "Split Values: " + str(self.split_vals) return str_val def print_cube(self): print_list = [self] while print_list: cube = print_list.pop(0) print(str(cube)) print_list.extend(cube.child)
[ "numpy.shape" ]
[((876, 889), 'numpy.shape', 'np.shape', (['pts'], {}), '(pts)\n', (884, 889), True, 'import numpy as np\n')]
import numpy as np import scipy as sp def mutual_information(signal1, signal2, bins=40): pdf_, _, _ = np.histogram2d(signal1, signal2, bins=bins, normed=True) pdf_ /= np.float(pdf_.sum()) Hxy = joint_entropy(pdf_) Hx = entropy(pdf_.sum(axis=0)) Hy = entropy(pdf_.sum(axis=1)) return ( Hx + Hy - Hxy) def entropy(pdf_): entropy_ = 0. for i in np.arange(pdf_.shape[0]): if pdf_[i] != 0: entropy_ += pdf_[i] * np.log2(pdf_[i]) else: entropy_ += 0 return -1 * entropy_ def joint_entropy(pdf_): entropy_ = 0 for i in range(pdf_.shape[0]): entropy_+= entropy(pdf_[i]) return -1 * entropy_ def correlation(y_true, y_pred): return sp.stats.stats.pearsonr(y_true, y_pred)[0] def ranking_correlation(corr): """From a correlation array returns the index order of absolute correlation magnitude. """ return np.argsort(np.abs(corr))[::-1]
[ "numpy.abs", "scipy.stats.stats.pearsonr", "numpy.histogram2d", "numpy.log2", "numpy.arange" ]
[((112, 168), 'numpy.histogram2d', 'np.histogram2d', (['signal1', 'signal2'], {'bins': 'bins', 'normed': '(True)'}), '(signal1, signal2, bins=bins, normed=True)\n', (126, 168), True, 'import numpy as np\n'), ((426, 450), 'numpy.arange', 'np.arange', (['pdf_.shape[0]'], {}), '(pdf_.shape[0])\n', (435, 450), True, 'import numpy as np\n'), ((805, 844), 'scipy.stats.stats.pearsonr', 'sp.stats.stats.pearsonr', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (828, 844), True, 'import scipy as sp\n'), ((1007, 1019), 'numpy.abs', 'np.abs', (['corr'], {}), '(corr)\n', (1013, 1019), True, 'import numpy as np\n'), ((511, 527), 'numpy.log2', 'np.log2', (['pdf_[i]'], {}), '(pdf_[i])\n', (518, 527), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Tests. """ import unittest from numpy import linspace, sin, pi, amax from bruges.attribute import energy class EnergyTest(unittest.TestCase): def setUp(self): """ Makes a simple sin wave with 1 amplitude to use as test data. """ self.n_samples = 1001 duration = 1.0 freq = 10.0 w = freq * 2 * pi t = linspace(0.0, duration, self.n_samples) self.data = sin(w * t) def test_amplitude(self): """ Tests the basic algorithm returns the right amplitude location. """ amplitude = energy(self.data, self.n_samples) max_amp = amax(amplitude) ms_sin = 0.5 # The MS energy of a sin wave self.assertAlmostEquals(ms_sin, max_amp, places=3) # Check that it is in the right location self.assertAlmostEqual(max_amp, amplitude[501], places=3) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(EnergyTest) unittest.TextTestRunner(verbosity=2).run(suite)
[ "numpy.linspace", "numpy.sin", "bruges.attribute.energy", "numpy.amax", "unittest.TextTestRunner", "unittest.TestLoader" ]
[((400, 439), 'numpy.linspace', 'linspace', (['(0.0)', 'duration', 'self.n_samples'], {}), '(0.0, duration, self.n_samples)\n', (408, 439), False, 'from numpy import linspace, sin, pi, amax\n'), ((461, 471), 'numpy.sin', 'sin', (['(w * t)'], {}), '(w * t)\n', (464, 471), False, 'from numpy import linspace, sin, pi, amax\n'), ((627, 660), 'bruges.attribute.energy', 'energy', (['self.data', 'self.n_samples'], {}), '(self.data, self.n_samples)\n', (633, 660), False, 'from bruges.attribute import energy\n'), ((679, 694), 'numpy.amax', 'amax', (['amplitude'], {}), '(amplitude)\n', (683, 694), False, 'from numpy import linspace, sin, pi, amax\n'), ((963, 984), 'unittest.TestLoader', 'unittest.TestLoader', ([], {}), '()\n', (982, 984), False, 'import unittest\n'), ((1023, 1059), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (1046, 1059), False, 'import unittest\n')]
import time import numpy as np import cupy as cp import acc_image_utils as acc ori_size = 96 new_size = 32 #n1 = np.zeros((ori_size,ori_size,ori_size,ori_size),dtype=np.float32) n1 = np.random.rand(ori_size,ori_size,ori_size,ori_size) loop_tester = 4 t1 = time.time() for ii in range(loop_tester): #real in 0,1 Q in 2,3 n2 = acc.gpu_rot4D(n1,53) n2 = acc.cupy_jit_resizer4D(n2,(new_size,new_size)) n2 = acc.cupy_pad(n2,(ori_size,ori_size)) n2 = cp.transpose(n2,(2,3,0,1)) #real in 2,3 n2 = cp.fft.fftshift(cp.fft.fft2(n2,axes=(-2,-1)),axes=(-2,-1)) #now real is Q' which is 2,3 G = cp.asnumpy(n2) n2 = cp.transpose(n2,(2,3,0,1)) #move original Q to 2,3 and Q' to 0,1 n2 = cp.fft.ifftshift(cp.fft.ifft2(n2,axes=(-2,-1)),axes=(-2,-1)) #now 0,1 is Q' and 2,3 is R' n2 = cp.transpose(n2,(2,3,0,1)) #0,1 is R' and 2,3 is Q' H = cp.asnumpy(n2) t2 = time.time() print((t2 - t1)/loop_tester)
[ "cupy.transpose", "cupy.asnumpy", "numpy.random.rand", "cupy.fft.ifft2", "acc_image_utils.cupy_jit_resizer4D", "acc_image_utils.gpu_rot4D", "acc_image_utils.cupy_pad", "time.time", "cupy.fft.fft2" ]
[((184, 238), 'numpy.random.rand', 'np.random.rand', (['ori_size', 'ori_size', 'ori_size', 'ori_size'], {}), '(ori_size, ori_size, ori_size, ori_size)\n', (198, 238), True, 'import numpy as np\n'), ((257, 268), 'time.time', 'time.time', ([], {}), '()\n', (266, 268), False, 'import time\n'), ((891, 902), 'time.time', 'time.time', ([], {}), '()\n', (900, 902), False, 'import time\n'), ((334, 355), 'acc_image_utils.gpu_rot4D', 'acc.gpu_rot4D', (['n1', '(53)'], {}), '(n1, 53)\n', (347, 355), True, 'import acc_image_utils as acc\n'), ((364, 412), 'acc_image_utils.cupy_jit_resizer4D', 'acc.cupy_jit_resizer4D', (['n2', '(new_size, new_size)'], {}), '(n2, (new_size, new_size))\n', (386, 412), True, 'import acc_image_utils as acc\n'), ((420, 458), 'acc_image_utils.cupy_pad', 'acc.cupy_pad', (['n2', '(ori_size, ori_size)'], {}), '(n2, (ori_size, ori_size))\n', (432, 458), True, 'import acc_image_utils as acc\n'), ((466, 496), 'cupy.transpose', 'cp.transpose', (['n2', '(2, 3, 0, 1)'], {}), '(n2, (2, 3, 0, 1))\n', (478, 496), True, 'import cupy as cp\n'), ((612, 626), 'cupy.asnumpy', 'cp.asnumpy', (['n2'], {}), '(n2)\n', (622, 626), True, 'import cupy as cp\n'), ((636, 666), 'cupy.transpose', 'cp.transpose', (['n2', '(2, 3, 0, 1)'], {}), '(n2, (2, 3, 0, 1))\n', (648, 666), True, 'import cupy as cp\n'), ((811, 841), 'cupy.transpose', 'cp.transpose', (['n2', '(2, 3, 0, 1)'], {}), '(n2, (2, 3, 0, 1))\n', (823, 841), True, 'import cupy as cp\n'), ((871, 885), 'cupy.asnumpy', 'cp.asnumpy', (['n2'], {}), '(n2)\n', (881, 885), True, 'import cupy as cp\n'), ((532, 562), 'cupy.fft.fft2', 'cp.fft.fft2', (['n2'], {'axes': '(-2, -1)'}), '(n2, axes=(-2, -1))\n', (543, 562), True, 'import cupy as cp\n'), ((727, 758), 'cupy.fft.ifft2', 'cp.fft.ifft2', (['n2'], {'axes': '(-2, -1)'}), '(n2, axes=(-2, -1))\n', (739, 758), True, 'import cupy as cp\n')]
""" QA model code. """ from collections import namedtuple import concurrent.futures import glob import json import os import random import sys import featurize import ops import numpy as np import tensorflow as tf from framework import Model from constants import EMBEDDING_DIM, PAD ModelConfig = namedtuple("QAModel", [ "vocab_size", "question_layers", "document_layers", "pick_end_word_layers", "layer_size", "beam_size", "embedding_dropout_prob", "hidden_dropout_prob", "learning_rate", "anneal_every", "anneal_rate", "clip_norm", "l2_scale", "weight_noise", ]) SquadExample = namedtuple("SquadExample", [ "question", "context", "sentence_lengths", "answer_sentence", "answer_start", "answer_end", "same_as_question_word", "repeated_words", "repeated_word_intensity", "id" ]) def load_sample(sample_file): """Load a single example and return it as a SquadExample tuple.""" with open(sample_file, "rt") as handle: sample = json.load(handle) return SquadExample(question=sample["question"], context=sample["context"], sentence_lengths=sample["sent_lengths"], answer_sentence=sample["ans_sentence"], answer_start=sample["ans_start"], answer_end=sample["ans_end"], same_as_question_word=sample["same_as_question_word"], repeated_words=sample["repeated_words"], repeated_word_intensity=sample["repeated_intensity"], id=sample["qa_id"]) def make_batches(samples, augmented_samples, batch_size, cycle=False): """Convert samples from the samples generator into padded batches with `batch_size` as the first dimension.""" current_batch = [] while True: if augmented_samples is not None: augmented = featurize.random_sample(augmented_samples, 10000) epoch_samples = samples + augmented else: epoch_samples = samples random.shuffle(epoch_samples) for idx, sample in enumerate(epoch_samples): current_batch.append(load_sample(sample)) if len(current_batch) == batch_size or idx == len(samples) - 1: questions = ops.lists_to_array( [sample.question for sample in current_batch], padding=-1) contexts = ops.lists_to_array( [sample.context for sample in current_batch], padding=-1) # Auxilary features same_as_question_word = ops.lists_to_array( [sample.same_as_question_word for sample in current_batch], padding=0) repeated_words = ops.lists_to_array( [sample.repeated_words for sample in current_batch], padding=0) repeated_word_intensity = ops.lists_to_array( [sample.repeated_word_intensity for sample in current_batch], padding=0) sent_lengths = ops.lists_to_array( [sample.sentence_lengths for sample in current_batch], padding=0) answer_sentences = np.array( [sample.answer_sentence for sample in current_batch]) answer_starts = np.array( [sample.answer_start for sample in current_batch]) answer_ends = np.array( [sample.answer_end for sample in current_batch]) ids = [sample.id for sample in current_batch] yield [questions, contexts, same_as_question_word, repeated_words, repeated_word_intensity, sent_lengths, answer_sentences, answer_starts, answer_ends, ids] current_batch = [] if not cycle: break def make_eval_batches(path, batch_size): with open(path, "rt") as handle: eval_samples = json.load(handle) current_batch = [] for idx, sample in enumerate(eval_samples): current_batch.append(sample) if len(current_batch) == batch_size or idx == len(eval_samples) - 1: ids, tokenized_context, features = zip(*current_batch) questions, contexts, saq, rw, rwi, lens = zip(*features) questions = ops.lists_to_array(questions, padding=-1) contexts = ops.lists_to_array(contexts, padding=-1) same_as_question = ops.lists_to_array(saq, padding=0) repeated_words = ops.lists_to_array(rw, padding=0) repeated_word_intensity = ops.lists_to_array(rwi, padding=0) sent_lens = ops.lists_to_array(lens, padding=0) yield [ids, tokenized_context, [questions, contexts, same_as_question, repeated_words, repeated_word_intensity, sent_lens]] current_batch = [] def load_input_data(path, batch_size, validation_size, current_iteration): """ Load the input data from the provided directory, splitting it into validation batches and an infinite generator of training batches. Arguments: - path: Directory with one file or subdirectory per training sample. - batch_size: Size of each training batch (per GPU). - validation_size: Size of the validation set (not per GPU). - current_iteration: The number of training batches to skip. Return a tuple of (train data, validation data), where training and validation data are both generators of batches. A batch is a list of NumPy arrays, in the same order as returned by load_sample. """ if not os.path.exists(os.path.join(path, "train")): print("Non-existent directory as input path: {}".format(path), file=sys.stderr) sys.exit(1) # Get paths to all samples that we want to load. train_samples = glob.glob(os.path.join(path, "train", "*")) valid_samples = glob.glob(os.path.join(path, "dev", "*")) augmented_samples = glob.glob(os.path.join(path, "augmented", "*")) # Sort then shuffle to ensure that the random order is deterministic # across runs. train_samples.sort() valid_samples.sort() augmented_samples.sort() random.shuffle(train_samples) random.shuffle(valid_samples) random.shuffle(augmented_samples) train = ops.prefetch_generator(make_batches(train_samples, augmented_samples, batch_size, cycle=True), to_fetch=2 * batch_size) valid = ops.prefetch_generator(make_batches(valid_samples, None, validation_size), to_fetch=validation_size) evals = make_eval_batches(os.path.join(path, "eval.json"), 1) return train, valid, evals def featurize_question(model, questions, embedding_dropout, training): """Embed the question as the final hidden state of a stack of Bi-LSTMs and a "passage-indenpendent" embedding from Rasor. Arguments: model: QA model hyperparameters. questions: Question word indices with shape `[batch, length]`. embedding_dropout: Dropout probability for the inputs to the LSTM. Returns: hiddens: Vector representation for the entire question with shape `[batch, features]`. """ with tf.variable_scope("GloveEmbeddings", reuse=True): embeds = tf.get_variable("GloveEmbeddings") question_embeddings = ops.masked_embedding_lookup(embeds, questions) question_embeddings = tf.nn.dropout(question_embeddings, embedding_dropout) with tf.variable_scope("QuestionLSTMs"): hiddens, final_h, _ = ops.cudnn_lstm(question_embeddings, model.question_layers, model.layer_size, model.weight_noise, training) batch = tf.shape(final_h)[0] final_states = tf.reshape( final_h[:, -2:, :], [batch, 2 * model.layer_size]) with tf.variable_scope("PassageIndependentEmbedding"): features = hiddens.get_shape()[-1].value hiddens = tf.contrib.layers.fully_connected( inputs=hiddens, num_outputs=features, activation_fn=None) sentinel = tf.get_variable( shape=[features, 1], initializer=tf.contrib.layers.variance_scaling_initializer(), name="sentinel") # [batch, words, 1] alphas = ops.semibatch_matmul(hiddens, sentinel) alphas = tf.nn.softmax(alphas, dim=1) passage_indep_embedding = tf.reduce_sum( alphas * hiddens, axis=1) return tf.concat(axis=1, values=[final_states, passage_indep_embedding]) def question_aligned_embeddings(documents, questions, hidden_dimension): def mlp(x, reuse=None): with tf.variable_scope("MLP0", reuse=reuse): h = tf.contrib.layers.fully_connected( inputs=x, num_outputs=hidden_dimension, activation_fn=tf.nn.relu) with tf.variable_scope("MLP1", reuse=reuse): h = tf.contrib.layers.fully_connected( inputs=h, num_outputs=hidden_dimension, activation_fn=None) return h docs = mlp(documents) qs = mlp(questions, reuse=True) # [batch, w_doc, w_ques] scores = tf.matmul(docs, qs, transpose_b=True) alphas = tf.nn.softmax(scores, dim=-1) return tf.matmul(alphas, questions) def featurize_document(model, questions, documents, same_as_question, repeated_words, repeated_word_intensity, question_vector, embedding_dropout, training): """Run a stack of Bi-LSTM's over the document. Arguments: model: QA model hyperparameters. documents: Document word indices with shape `[batch, length]`. same_as_question: Boolean: Does the question contain this word? with shape `[batch, length]` question_vector: Vector representation of the question with shape `[batch, features]` embedding_dropout: Dropout probability for the LSTM inputs. hidden_dropout: Dropout probability for the LSTM hidden states. Returns: hiddens: Vector representation for each word in the document with shape `[batch, length, features]`. """ with tf.variable_scope("GloveEmbeddings", reuse=True): embeds = tf.get_variable("GloveEmbeddings") document_embeddings = ops.masked_embedding_lookup(embeds, documents) question_embeddings = ops.masked_embedding_lookup(embeds, questions) qa_embeds = question_aligned_embeddings( document_embeddings, question_embeddings, model.layer_size) # Tile the question vector across the length of the document. question_vector = tf.tile( tf.expand_dims(question_vector, 1), [1, tf.shape(documents)[1], 1]) same_as_question = tf.expand_dims(same_as_question, 2) repeated_words = tf.expand_dims(repeated_words, 2) repeated_word_intensity = tf.expand_dims(repeated_word_intensity, 2) document_embeddings = tf.concat( axis=2, values=[document_embeddings, same_as_question, repeated_words, repeated_word_intensity, question_vector, qa_embeds]) document_embeddings = tf.nn.dropout(document_embeddings, embedding_dropout) with tf.variable_scope("DocumentLSTMs"): hiddens, _, _ = ops.cudnn_lstm(document_embeddings, model.document_layers, model.layer_size, model.weight_noise, training) return hiddens def score_sentences(model, documents_features, sentence_lengths, hidden_dropout): """Compute logits for selecting each sentence in the document. Arguments: documents_features: Feature representation of the document with shape `[batch, length, features]`. sentence_lengths: Length of each sentence in the document with shape `[batch, num_sentences]`, used for finding sentence boundaries in documents_features. Returns: logits: Scores for each sentence with shape `[batch, num_sentences]`. """ batch_size = tf.shape(documents_features)[0] length = tf.shape(documents_features)[1] features = documents_features.get_shape()[-1].value num_sentences = tf.shape(sentence_lengths)[1] # Find sentence boundary indices. sentence_start_positions = tf.cumsum( sentence_lengths, axis=1, exclusive=True) sentence_end_positions = tf.cumsum(sentence_lengths, axis=1) - 1 # Flatten indices and document to `[batch * length, features]` # in preparation for a gather. offsets = length * tf.expand_dims(tf.range(batch_size), 1) sentence_start_positions = tf.reshape( sentence_start_positions + offsets, [-1]) sentence_end_positions = tf.reshape( sentence_end_positions + offsets, [-1]) documents_features = tf.reshape(documents_features, [-1, features]) # Gather the final hidden state of the forward LSTM at the end # of each sentence. forward_features = documents_features[:, :(features // 2)] forward_states = tf.gather(forward_features, sentence_end_positions) # Gather the first hidden state of the backward LSTM at the # start of sentence (after it was run over the entire sentence). backward_features = documents_features[:, (features // 2):] backward_states = tf.gather(backward_features, sentence_start_positions) # Score each sentence using an MLP. sentence_states = tf.concat(axis=1, values=[forward_states, backward_states]) sentence_states = tf.reshape(sentence_states, [batch_size, num_sentences, features]) with tf.variable_scope("SentenceSelection"): logits = tf.contrib.layers.fully_connected( inputs=tf.nn.dropout(sentence_states, hidden_dropout), num_outputs=1, activation_fn=None) return tf.squeeze(logits, [2]) def slice_sentences(document_features, picks, sentence_lengths): """Extract selected sentence spans from the document features. Arguments: document_features: A `[batch, length, features]` representation of the documents. picks: Sentence to extract with shape `[batch, selections]`. sentence_lengths: Length of each sentence in the document with shape `[batch, num_sentences]`. Returns extracted features for each selected sentence as a tensor with shape `[batch, selections, max_sentence_len, features]` """ sentence_offsets = tf.cumsum( sentence_lengths, axis=1, exclusive=True) starts = ops.gather_from_rows(sentence_offsets, picks) lengths = ops.gather_from_rows(sentence_lengths, picks) sentence_embeddings = ops.slice_fragments( document_features, starts, lengths) return sentence_embeddings def slice_end_of_sentence(sentence_features, start_word_picks, sentence_lengths): """Extract the final span of each sentence after the selected starting words. Arguments: sentence_features: Sentence representation with shape `[batch, k, words, features]`. start_word_picks: Starting word selections with shape `[batch, k]`. sentence_lengths: Length of each sentence in sentence_features of shape `[batch, k]`. Used for masking. Returns extracted sentence spans with shape `[batch, k, max_fragment_len, features]`. """ fragment_lengths = sentence_lengths - start_word_picks # Flatten to `[batch, beam * words, features]`. beams = tf.shape(sentence_features)[1] words = tf.shape(sentence_features)[2] sentence_features = tf.reshape( sentence_features, [tf.shape(sentence_features)[0], beams * words, sentence_features.get_shape()[-1].value]) # Offset the start locations by words * beams to account # for flattening. start_word_picks += words * tf.expand_dims(tf.range(beams), 0) sentence_fragments = ops.slice_fragments( sentence_features, start_word_picks, fragment_lengths) return sentence_fragments def score_start_word(model, document_embeddings, sentence_picks, sentence_lengths, hidden_dropout): """Score each possible span spart word in a sentence by passing it through an MLP. Arguments: model: QA model hyperparameters. document_embeddings: Document representation with shape `[batch, length, features]`. sentence_picks: Selected sentences with shape `[batch, beam_size]`. sentence_lengths: Lengths of each sentence in the document with shape `[batch, num_sentences]`. Returns: logits: [batch, beam_size, length] scores for each start word in the beam, where `length` is the maximum `length` of a selected sentence. """ # [batch, beams, max_sentence_length, features]. sentence_embeddings = slice_sentences( document_embeddings, sentence_picks, sentence_lengths) with tf.variable_scope("StartWordSelection"): logits = tf.contrib.layers.fully_connected( inputs=tf.nn.dropout(sentence_embeddings, hidden_dropout), num_outputs=1, activation_fn=None) return tf.squeeze(logits, [-1]) def score_end_words(model, document_embeddings, sentence_picks, start_word_picks, sentence_lengths, hidden_dropout, training): """Score each possible span end word in the sentence by running a Bi-LSTM over the remaining sentence span and passing the result through an MLP. Arguments: model: QA model hyperparameters document_embeddings: A `[batch, length, features]` representation of a document. sentence_picks: Index of selected sentences in the document with shape `[batch, k]`. start_word_picks: Index of start words in each selected sentence with shape `[batch, k]`. sentence_lengths: Length of each sentence with shape `[batch, num_sentences]`. Returns scores for each possible span end word with shape `[batch, k, max-span-length]`. """ # Slice the document twice to get end word spans. sentence_embeddings = slice_sentences( document_embeddings, sentence_picks, sentence_lengths) picked_sentence_lengths = ops.gather_from_rows(sentence_lengths, sentence_picks) sentence_fragments = slice_end_of_sentence( sentence_embeddings, start_word_picks, picked_sentence_lengths) # Collapse batch and beam dimension batch = tf.shape(sentence_fragments)[0] beam = tf.shape(sentence_fragments)[1] frag_len = tf.shape(sentence_fragments)[2] features = sentence_fragments.get_shape()[-1].value sentence_fragments = tf.reshape( sentence_fragments, [batch * beam, frag_len, features]) with tf.variable_scope("PickEndWordLSTMs"): hiddens, _, _ = ops.cudnn_lstm(sentence_fragments, model.pick_end_word_layers, model.layer_size, model.weight_noise, training) hiddens = tf.reshape( hiddens, [batch, beam, frag_len, hiddens.get_shape()[-1].value]) with tf.variable_scope("EndWordSelection"): logits = tf.contrib.layers.fully_connected( inputs=tf.nn.dropout(hiddens, hidden_dropout), num_outputs=1, activation_fn=None) return tf.squeeze(logits, [-1]) def globally_normalized_loss(beam_states, labels): """Global normalized loss with early updating. Arguments: beam_states: List of previous decisions and current decision scores for each step in the search process, as well as the final beam. Previous decisions are a tensor of indices with shape `[batch, beam_size]` corresponding to the selection at previous time steps and scores has shape `[batch, beam_size, classes]`. labels: List of correct labels at each step in the search process, each with shape `[batch]`. Returns scalar loss averaged across each example in the batch. """ loss, loss_mask = 0., 1. for i, (prev_decisions, scores) in enumerate(reversed(beam_states)): batch = tf.shape(scores)[0] beam = tf.shape(scores)[1] correct = tf.cast(tf.ones((batch, beam)), tf.bool) for decision, label in zip(prev_decisions, labels): correct = tf.logical_and( correct, tf.equal(tf.expand_dims(label, 1), decision)) # Correct is one-hot in each row if previous decisions # were correct. correct_mask = tf.cast(correct, tf.float32) any_correct = tf.cast( tf.reduce_sum(correct_mask, axis=1), tf.bool) if len(prev_decisions) == len(labels): # Final step of the search procedure. Find the correct, # if any, beam and normalize only over the final candidate # set. targets = tf.argmax(correct_mask, axis=1) stage_loss = tf.nn.sparse_softmax_cross_entropy_with_logits( labels=targets, logits=scores) # Avoid Nans stage_loss = tf.where( any_correct, stage_loss, tf.zeros_like(stage_loss)) else: # Early updates: Assuming the previous decisions are # correct for some beam, find the correct answer among # the candidates at this stage and maximize its # log-probability. # Get the labels for this decision and tile for each beam # [batch * k]. targets = labels[len(prev_decisions)] targets = tf.reshape( tf.tile(tf.expand_dims(targets, 1), [1, beam]), [-1]) # Prevent NANs from showing up if the correct start or end word # isn't scored by the model. Any "wrong" targets it introduces will # be masked out since the proceeding choices will be incorrect. targets = tf.minimum(targets, tf.shape(scores)[2] - 1) scores = tf.reshape(scores, [batch * beam, -1]) stage_loss = tf.nn.sparse_softmax_cross_entropy_with_logits( labels=targets, logits=scores) stage_loss = tf.reshape(stage_loss, [batch, beam]) # Avoid Nans stage_loss = tf.where( tf.cast(correct_mask, tf.bool), stage_loss, tf.zeros_like(stage_loss)) stage_loss = tf.reduce_sum(stage_loss, axis=1) # Mask out items of the batch where elements have already # received loss loss += loss_mask * stage_loss # Update the loss mask. Any correct is {0, 1}^{batch} loss_mask *= 1. - tf.cast(any_correct, tf.float32) return tf.reduce_mean(loss) def build_model(model): """Build a Tensorflow graph for the QA model. Return a model.Model for training, evaluation, etc. """ with tf.name_scope("Inputs"): questions = tf.placeholder( tf.int32, name="Questions", shape=[None, None]) documents = tf.placeholder( tf.int32, name="Documents", shape=[None, None]) same_as_question_feature = tf.placeholder( tf.float32, name="SameAsQuestionFeature", shape=[None, None]) repeated_words = tf.placeholder( tf.float32, name="RepeatedWordFeature", shape=[None, None]) repeated_word_intensity = tf.placeholder( tf.float32, name="RepeatedWordIntensity", shape=[None, None]) sentence_lengths = tf.placeholder( tf.int32, name="SentenceOffsets", shape=[None, None]) sentence_labels = tf.placeholder( tf.int32, name="SentenceLabels", shape=[None]) word_start_labels = tf.placeholder( tf.int32, name="WordStartLabels", shape=[None]) word_end_labels = tf.placeholder( tf.int32, name="WordEndLabels", shape=[None]) embedding_dropout = tf.placeholder_with_default( model.embedding_dropout_prob, shape=[]) hidden_dropout = tf.placeholder_with_default( model.hidden_dropout_prob, shape=[]) training = tf.placeholder_with_default( True, shape=[], name="TrainingIndicator") exact_match = tf.placeholder( tf.float32, name="ExactMatch", shape=[]) f1 = tf.placeholder( tf.float32, name="F1", shape=[]) with tf.variable_scope("GloveEmbeddings"): embeddings = tf.get_variable( shape=[model.vocab_size, EMBEDDING_DIM], initializer=tf.zeros_initializer(), trainable=False, name="GloveEmbeddings") embedding_placeholder = tf.placeholder( tf.float32, [model.vocab_size, EMBEDDING_DIM]) embedding_init = embeddings.assign(embedding_placeholder) with tf.name_scope("QuestionEmbeddings"): question_vector = featurize_question(model, questions, embedding_dropout, training) with tf.name_scope("DocumentEmbeddings"): document_embeddings = featurize_document( model, questions, documents, same_as_question_feature, repeated_words, repeated_word_intensity, question_vector, embedding_dropout, training) # Keep track of the beam state at each decision point beam_states = [] with tf.name_scope("PickSentence"): sentence_scores = score_sentences( model, document_embeddings, sentence_lengths, hidden_dropout) beam_states.append(([], tf.expand_dims(sentence_scores, 1))) beam_scores, sentence_picks = tf.nn.top_k( sentence_scores, k=tf.minimum(model.beam_size, tf.shape(sentence_scores)[1]), sorted=True) sentence_correct = tf.reduce_mean( tf.cast(tf.equal(sentence_labels, sentence_picks[:, 0]), tf.float32)) with tf.name_scope("PickStartWord"): start_word_scores = score_start_word( model, document_embeddings, sentence_picks, sentence_lengths, hidden_dropout) beam_scores = tf.expand_dims(beam_scores, 2) + start_word_scores beam_states.append(([sentence_picks], beam_scores)) beam_scores, kept_sentences, start_words = ops.prune_beam( beam_scores, sentence_picks, model.beam_size) start_word_correct = tf.reduce_mean( tf.cast(tf.logical_and( tf.equal(word_start_labels, start_words[:, 0]), tf.equal(sentence_labels, kept_sentences[:, 0])), tf.float32)) with tf.name_scope("PickEndWord"): end_word_scores = score_end_words( model, document_embeddings, kept_sentences, start_words, sentence_lengths, hidden_dropout, training) beam_scores = tf.expand_dims(beam_scores, 2) + end_word_scores beam_states.append(([kept_sentences, start_words], beam_scores)) beam_scores, (kept_sentences, kept_start_words), end_words = ops.prune_beam( beam_scores, [kept_sentences, start_words], model.beam_size) # Also track the final decisions. beam_states.append(([kept_sentences, kept_start_words, end_words], beam_scores)) # Get offset from start word end_word_picks = kept_start_words + end_words final_states = [kept_sentences, kept_start_words, end_word_picks] end_word_correct = tf.reduce_mean( tf.cast(tf.logical_and( tf.logical_and( tf.equal(word_end_labels, end_word_picks[:, 0]), tf.equal(word_start_labels, kept_start_words[:, 0])), tf.equal(sentence_labels, kept_sentences[:, 0])), tf.float32)) with tf.name_scope("Loss"): # End prediction is based on the start word offset. end_labels = word_end_labels - word_start_labels labels = (sentence_labels, word_start_labels, end_labels) loss = globally_normalized_loss(beam_states, labels) l2_penalty = tf.contrib.layers.apply_regularization( tf.contrib.layers.l2_regularizer(model.l2_scale), tf.trainable_variables()) loss += l2_penalty with tf.name_scope("TrainStep"): iteration, (step, loss, gradnorm) = ops.default_train_step( model, loss) with tf.name_scope("TrainSummary"): train_summary = ops.scalar_summaries({ "Train-Loss": loss, "Gradient-Norm": gradnorm, "Sentence-Correct": sentence_correct, "Start-Word-Correct": start_word_correct, "End-Word-Correct": end_word_correct}) with tf.name_scope("ValidSummary"): valid_summary = ops.scalar_summaries({ "Validation-Loss": loss, "Sentence-Correct": sentence_correct, "Start-Word-Correct": start_word_correct, "End-Word-Correct": end_word_correct}) with tf.name_scope("SquadSummary"): squad_summary = ops.scalar_summaries({ "Exact-Match": exact_match, "F1": f1}) return Model( inputs=[questions, documents, same_as_question_feature, repeated_words, repeated_word_intensity, sentence_lengths, sentence_labels, word_start_labels, word_end_labels], outputs=[kept_sentences, kept_start_words, end_word_picks, sentence_correct, start_word_correct, end_word_correct], loss=loss, training=training, dropout=[embedding_dropout, hidden_dropout], gradnorm=gradnorm, step=step, iteration=iteration, train_summary=train_summary, valid_summary=valid_summary, embedding_init=embedding_init, embedding_placeholder=embedding_placeholder, squad_summary=squad_summary, squad_inputs=[exact_match, f1])
[ "tensorflow.equal", "tensorflow.shape", "tensorflow.get_variable", "tensorflow.contrib.layers.l2_regularizer", "tensorflow.reduce_sum", "tensorflow.contrib.layers.variance_scaling_initializer", "ops.scalar_summaries", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "numpy.array", "tensor...
[((299, 575), 'collections.namedtuple', 'namedtuple', (['"""QAModel"""', "['vocab_size', 'question_layers', 'document_layers', 'pick_end_word_layers',\n 'layer_size', 'beam_size', 'embedding_dropout_prob',\n 'hidden_dropout_prob', 'learning_rate', 'anneal_every', 'anneal_rate',\n 'clip_norm', 'l2_scale', 'weight_noise']"], {}), "('QAModel', ['vocab_size', 'question_layers', 'document_layers',\n 'pick_end_word_layers', 'layer_size', 'beam_size',\n 'embedding_dropout_prob', 'hidden_dropout_prob', 'learning_rate',\n 'anneal_every', 'anneal_rate', 'clip_norm', 'l2_scale', 'weight_noise'])\n", (309, 575), False, 'from collections import namedtuple\n'), ((639, 848), 'collections.namedtuple', 'namedtuple', (['"""SquadExample"""', "['question', 'context', 'sentence_lengths', 'answer_sentence',\n 'answer_start', 'answer_end', 'same_as_question_word', 'repeated_words',\n 'repeated_word_intensity', 'id']"], {}), "('SquadExample', ['question', 'context', 'sentence_lengths',\n 'answer_sentence', 'answer_start', 'answer_end',\n 'same_as_question_word', 'repeated_words', 'repeated_word_intensity', 'id']\n )\n", (649, 848), False, 'from collections import namedtuple\n'), ((6340, 6369), 'random.shuffle', 'random.shuffle', (['train_samples'], {}), '(train_samples)\n', (6354, 6369), False, 'import random\n'), ((6374, 6403), 'random.shuffle', 'random.shuffle', (['valid_samples'], {}), '(valid_samples)\n', (6388, 6403), False, 'import random\n'), ((6408, 6441), 'random.shuffle', 'random.shuffle', (['augmented_samples'], {}), '(augmented_samples)\n', (6422, 6441), False, 'import random\n'), ((8992, 9057), 'tensorflow.concat', 'tf.concat', ([], {'axis': '(1)', 'values': '[final_states, passage_indep_embedding]'}), '(axis=1, values=[final_states, passage_indep_embedding])\n', (9001, 9057), True, 'import tensorflow as tf\n'), ((9715, 9752), 'tensorflow.matmul', 'tf.matmul', (['docs', 'qs'], {'transpose_b': '(True)'}), '(docs, qs, transpose_b=True)\n', (9724, 9752), True, 'import tensorflow as tf\n'), ((9766, 9795), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['scores'], {'dim': '(-1)'}), '(scores, dim=-1)\n', (9779, 9795), True, 'import tensorflow as tf\n'), ((9808, 9836), 'tensorflow.matmul', 'tf.matmul', (['alphas', 'questions'], {}), '(alphas, questions)\n', (9817, 9836), True, 'import tensorflow as tf\n'), ((11377, 11412), 'tensorflow.expand_dims', 'tf.expand_dims', (['same_as_question', '(2)'], {}), '(same_as_question, 2)\n', (11391, 11412), True, 'import tensorflow as tf\n'), ((11434, 11467), 'tensorflow.expand_dims', 'tf.expand_dims', (['repeated_words', '(2)'], {}), '(repeated_words, 2)\n', (11448, 11467), True, 'import tensorflow as tf\n'), ((11498, 11540), 'tensorflow.expand_dims', 'tf.expand_dims', (['repeated_word_intensity', '(2)'], {}), '(repeated_word_intensity, 2)\n', (11512, 11540), True, 'import tensorflow as tf\n'), ((11567, 11705), 'tensorflow.concat', 'tf.concat', ([], {'axis': '(2)', 'values': '[document_embeddings, same_as_question, repeated_words,\n repeated_word_intensity, question_vector, qa_embeds]'}), '(axis=2, values=[document_embeddings, same_as_question,\n repeated_words, repeated_word_intensity, question_vector, qa_embeds])\n', (11576, 11705), True, 'import tensorflow as tf\n'), ((11762, 11815), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['document_embeddings', 'embedding_dropout'], {}), '(document_embeddings, embedding_dropout)\n', (11775, 11815), True, 'import tensorflow as tf\n'), ((13168, 13219), 'tensorflow.cumsum', 'tf.cumsum', (['sentence_lengths'], {'axis': '(1)', 'exclusive': '(True)'}), '(sentence_lengths, axis=1, exclusive=True)\n', (13177, 13219), True, 'import tensorflow as tf\n'), ((13495, 13547), 'tensorflow.reshape', 'tf.reshape', (['(sentence_start_positions + offsets)', '[-1]'], {}), '(sentence_start_positions + offsets, [-1])\n', (13505, 13547), True, 'import tensorflow as tf\n'), ((13586, 13636), 'tensorflow.reshape', 'tf.reshape', (['(sentence_end_positions + offsets)', '[-1]'], {}), '(sentence_end_positions + offsets, [-1])\n', (13596, 13636), True, 'import tensorflow as tf\n'), ((13671, 13717), 'tensorflow.reshape', 'tf.reshape', (['documents_features', '[-1, features]'], {}), '(documents_features, [-1, features])\n', (13681, 13717), True, 'import tensorflow as tf\n'), ((13894, 13945), 'tensorflow.gather', 'tf.gather', (['forward_features', 'sentence_end_positions'], {}), '(forward_features, sentence_end_positions)\n', (13903, 13945), True, 'import tensorflow as tf\n'), ((14166, 14220), 'tensorflow.gather', 'tf.gather', (['backward_features', 'sentence_start_positions'], {}), '(backward_features, sentence_start_positions)\n', (14175, 14220), True, 'import tensorflow as tf\n'), ((14284, 14343), 'tensorflow.concat', 'tf.concat', ([], {'axis': '(1)', 'values': '[forward_states, backward_states]'}), '(axis=1, values=[forward_states, backward_states])\n', (14293, 14343), True, 'import tensorflow as tf\n'), ((14366, 14432), 'tensorflow.reshape', 'tf.reshape', (['sentence_states', '[batch_size, num_sentences, features]'], {}), '(sentence_states, [batch_size, num_sentences, features])\n', (14376, 14432), True, 'import tensorflow as tf\n'), ((14706, 14729), 'tensorflow.squeeze', 'tf.squeeze', (['logits', '[2]'], {}), '(logits, [2])\n', (14716, 14729), True, 'import tensorflow as tf\n'), ((15413, 15464), 'tensorflow.cumsum', 'tf.cumsum', (['sentence_lengths'], {'axis': '(1)', 'exclusive': '(True)'}), '(sentence_lengths, axis=1, exclusive=True)\n', (15422, 15464), True, 'import tensorflow as tf\n'), ((15488, 15533), 'ops.gather_from_rows', 'ops.gather_from_rows', (['sentence_offsets', 'picks'], {}), '(sentence_offsets, picks)\n', (15508, 15533), False, 'import ops\n'), ((15548, 15593), 'ops.gather_from_rows', 'ops.gather_from_rows', (['sentence_lengths', 'picks'], {}), '(sentence_lengths, picks)\n', (15568, 15593), False, 'import ops\n'), ((15620, 15675), 'ops.slice_fragments', 'ops.slice_fragments', (['document_features', 'starts', 'lengths'], {}), '(document_features, starts, lengths)\n', (15639, 15675), False, 'import ops\n'), ((17009, 17083), 'ops.slice_fragments', 'ops.slice_fragments', (['sentence_features', 'start_word_picks', 'fragment_lengths'], {}), '(sentence_features, start_word_picks, fragment_lengths)\n', (17028, 17083), False, 'import ops\n'), ((18382, 18406), 'tensorflow.squeeze', 'tf.squeeze', (['logits', '[-1]'], {}), '(logits, [-1])\n', (18392, 18406), True, 'import tensorflow as tf\n'), ((19622, 19676), 'ops.gather_from_rows', 'ops.gather_from_rows', (['sentence_lengths', 'sentence_picks'], {}), '(sentence_lengths, sentence_picks)\n', (19642, 19676), False, 'import ops\n'), ((20105, 20171), 'tensorflow.reshape', 'tf.reshape', (['sentence_fragments', '[batch * beam, frag_len, features]'], {}), '(sentence_fragments, [batch * beam, frag_len, features])\n', (20115, 20171), True, 'import tensorflow as tf\n'), ((20852, 20876), 'tensorflow.squeeze', 'tf.squeeze', (['logits', '[-1]'], {}), '(logits, [-1])\n', (20862, 20876), True, 'import tensorflow as tf\n'), ((24338, 24358), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), '(loss)\n', (24352, 24358), True, 'import tensorflow as tf\n'), ((30602, 31254), 'framework.Model', 'Model', ([], {'inputs': '[questions, documents, same_as_question_feature, repeated_words,\n repeated_word_intensity, sentence_lengths, sentence_labels,\n word_start_labels, word_end_labels]', 'outputs': '[kept_sentences, kept_start_words, end_word_picks, sentence_correct,\n start_word_correct, end_word_correct]', 'loss': 'loss', 'training': 'training', 'dropout': '[embedding_dropout, hidden_dropout]', 'gradnorm': 'gradnorm', 'step': 'step', 'iteration': 'iteration', 'train_summary': 'train_summary', 'valid_summary': 'valid_summary', 'embedding_init': 'embedding_init', 'embedding_placeholder': 'embedding_placeholder', 'squad_summary': 'squad_summary', 'squad_inputs': '[exact_match, f1]'}), '(inputs=[questions, documents, same_as_question_feature,\n repeated_words, repeated_word_intensity, sentence_lengths,\n sentence_labels, word_start_labels, word_end_labels], outputs=[\n kept_sentences, kept_start_words, end_word_picks, sentence_correct,\n start_word_correct, end_word_correct], loss=loss, training=training,\n dropout=[embedding_dropout, hidden_dropout], gradnorm=gradnorm, step=\n step, iteration=iteration, train_summary=train_summary, valid_summary=\n valid_summary, embedding_init=embedding_init, embedding_placeholder=\n embedding_placeholder, squad_summary=squad_summary, squad_inputs=[\n exact_match, f1])\n', (30607, 31254), False, 'from framework import Model\n'), ((1042, 1059), 'json.load', 'json.load', (['handle'], {}), '(handle)\n', (1051, 1059), False, 'import json\n'), ((2103, 2132), 'random.shuffle', 'random.shuffle', (['epoch_samples'], {}), '(epoch_samples)\n', (2117, 2132), False, 'import random\n'), ((4078, 4095), 'json.load', 'json.load', (['handle'], {}), '(handle)\n', (4087, 4095), False, 'import json\n'), ((5900, 5911), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (5908, 5911), False, 'import sys\n'), ((5996, 6028), 'os.path.join', 'os.path.join', (['path', '"""train"""', '"""*"""'], {}), "(path, 'train', '*')\n", (6008, 6028), False, 'import os\n'), ((6060, 6090), 'os.path.join', 'os.path.join', (['path', '"""dev"""', '"""*"""'], {}), "(path, 'dev', '*')\n", (6072, 6090), False, 'import os\n'), ((6126, 6162), 'os.path.join', 'os.path.join', (['path', '"""augmented"""', '"""*"""'], {}), "(path, 'augmented', '*')\n", (6138, 6162), False, 'import os\n'), ((6885, 6916), 'os.path.join', 'os.path.join', (['path', '"""eval.json"""'], {}), "(path, 'eval.json')\n", (6897, 6916), False, 'import os\n'), ((7525, 7573), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""GloveEmbeddings"""'], {'reuse': '(True)'}), "('GloveEmbeddings', reuse=True)\n", (7542, 7573), True, 'import tensorflow as tf\n'), ((7592, 7626), 'tensorflow.get_variable', 'tf.get_variable', (['"""GloveEmbeddings"""'], {}), "('GloveEmbeddings')\n", (7607, 7626), True, 'import tensorflow as tf\n'), ((7657, 7703), 'ops.masked_embedding_lookup', 'ops.masked_embedding_lookup', (['embeds', 'questions'], {}), '(embeds, questions)\n', (7684, 7703), False, 'import ops\n'), ((7734, 7787), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['question_embeddings', 'embedding_dropout'], {}), '(question_embeddings, embedding_dropout)\n', (7747, 7787), True, 'import tensorflow as tf\n'), ((7842, 7876), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""QuestionLSTMs"""'], {}), "('QuestionLSTMs')\n", (7859, 7876), True, 'import tensorflow as tf\n'), ((7908, 8018), 'ops.cudnn_lstm', 'ops.cudnn_lstm', (['question_embeddings', 'model.question_layers', 'model.layer_size', 'model.weight_noise', 'training'], {}), '(question_embeddings, model.question_layers, model.layer_size,\n model.weight_noise, training)\n', (7922, 8018), False, 'import ops\n'), ((8256, 8317), 'tensorflow.reshape', 'tf.reshape', (['final_h[:, -2:, :]', '[batch, 2 * model.layer_size]'], {}), '(final_h[:, -2:, :], [batch, 2 * model.layer_size])\n', (8266, 8317), True, 'import tensorflow as tf\n'), ((8341, 8389), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""PassageIndependentEmbedding"""'], {}), "('PassageIndependentEmbedding')\n", (8358, 8389), True, 'import tensorflow as tf\n'), ((8458, 8553), 'tensorflow.contrib.layers.fully_connected', 'tf.contrib.layers.fully_connected', ([], {'inputs': 'hiddens', 'num_outputs': 'features', 'activation_fn': 'None'}), '(inputs=hiddens, num_outputs=features,\n activation_fn=None)\n', (8491, 8553), True, 'import tensorflow as tf\n'), ((8806, 8845), 'ops.semibatch_matmul', 'ops.semibatch_matmul', (['hiddens', 'sentinel'], {}), '(hiddens, sentinel)\n', (8826, 8845), False, 'import ops\n'), ((8863, 8891), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['alphas'], {'dim': '(1)'}), '(alphas, dim=1)\n', (8876, 8891), True, 'import tensorflow as tf\n'), ((8927, 8966), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(alphas * hiddens)'], {'axis': '(1)'}), '(alphas * hiddens, axis=1)\n', (8940, 8966), True, 'import tensorflow as tf\n'), ((10801, 10849), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""GloveEmbeddings"""'], {'reuse': '(True)'}), "('GloveEmbeddings', reuse=True)\n", (10818, 10849), True, 'import tensorflow as tf\n'), ((10868, 10902), 'tensorflow.get_variable', 'tf.get_variable', (['"""GloveEmbeddings"""'], {}), "('GloveEmbeddings')\n", (10883, 10902), True, 'import tensorflow as tf\n'), ((10933, 10979), 'ops.masked_embedding_lookup', 'ops.masked_embedding_lookup', (['embeds', 'documents'], {}), '(embeds, documents)\n', (10960, 10979), False, 'import ops\n'), ((11010, 11056), 'ops.masked_embedding_lookup', 'ops.masked_embedding_lookup', (['embeds', 'questions'], {}), '(embeds, questions)\n', (11037, 11056), False, 'import ops\n'), ((11277, 11311), 'tensorflow.expand_dims', 'tf.expand_dims', (['question_vector', '(1)'], {}), '(question_vector, 1)\n', (11291, 11311), True, 'import tensorflow as tf\n'), ((11866, 11900), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""DocumentLSTMs"""'], {}), "('DocumentLSTMs')\n", (11883, 11900), True, 'import tensorflow as tf\n'), ((11926, 12036), 'ops.cudnn_lstm', 'ops.cudnn_lstm', (['document_embeddings', 'model.document_layers', 'model.layer_size', 'model.weight_noise', 'training'], {}), '(document_embeddings, model.document_layers, model.layer_size,\n model.weight_noise, training)\n', (11940, 12036), False, 'import ops\n'), ((12915, 12943), 'tensorflow.shape', 'tf.shape', (['documents_features'], {}), '(documents_features)\n', (12923, 12943), True, 'import tensorflow as tf\n'), ((12960, 12988), 'tensorflow.shape', 'tf.shape', (['documents_features'], {}), '(documents_features)\n', (12968, 12988), True, 'import tensorflow as tf\n'), ((13068, 13094), 'tensorflow.shape', 'tf.shape', (['sentence_lengths'], {}), '(sentence_lengths)\n', (13076, 13094), True, 'import tensorflow as tf\n'), ((13258, 13293), 'tensorflow.cumsum', 'tf.cumsum', (['sentence_lengths'], {'axis': '(1)'}), '(sentence_lengths, axis=1)\n', (13267, 13293), True, 'import tensorflow as tf\n'), ((14476, 14514), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""SentenceSelection"""'], {}), "('SentenceSelection')\n", (14493, 14514), True, 'import tensorflow as tf\n'), ((16579, 16606), 'tensorflow.shape', 'tf.shape', (['sentence_features'], {}), '(sentence_features)\n', (16587, 16606), True, 'import tensorflow as tf\n'), ((16622, 16649), 'tensorflow.shape', 'tf.shape', (['sentence_features'], {}), '(sentence_features)\n', (16630, 16649), True, 'import tensorflow as tf\n'), ((18147, 18186), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""StartWordSelection"""'], {}), "('StartWordSelection')\n", (18164, 18186), True, 'import tensorflow as tf\n'), ((19901, 19929), 'tensorflow.shape', 'tf.shape', (['sentence_fragments'], {}), '(sentence_fragments)\n', (19909, 19929), True, 'import tensorflow as tf\n'), ((19944, 19972), 'tensorflow.shape', 'tf.shape', (['sentence_fragments'], {}), '(sentence_fragments)\n', (19952, 19972), True, 'import tensorflow as tf\n'), ((19991, 20019), 'tensorflow.shape', 'tf.shape', (['sentence_fragments'], {}), '(sentence_fragments)\n', (19999, 20019), True, 'import tensorflow as tf\n'), ((20191, 20228), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""PickEndWordLSTMs"""'], {}), "('PickEndWordLSTMs')\n", (20208, 20228), True, 'import tensorflow as tf\n'), ((20254, 20369), 'ops.cudnn_lstm', 'ops.cudnn_lstm', (['sentence_fragments', 'model.pick_end_word_layers', 'model.layer_size', 'model.weight_noise', 'training'], {}), '(sentence_fragments, model.pick_end_word_layers, model.\n layer_size, model.weight_noise, training)\n', (20268, 20369), False, 'import ops\n'), ((20631, 20668), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""EndWordSelection"""'], {}), "('EndWordSelection')\n", (20648, 20668), True, 'import tensorflow as tf\n'), ((22140, 22168), 'tensorflow.cast', 'tf.cast', (['correct', 'tf.float32'], {}), '(correct, tf.float32)\n', (22147, 22168), True, 'import tensorflow as tf\n'), ((24508, 24531), 'tensorflow.name_scope', 'tf.name_scope', (['"""Inputs"""'], {}), "('Inputs')\n", (24521, 24531), True, 'import tensorflow as tf\n'), ((24553, 24615), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""Questions"""', 'shape': '[None, None]'}), "(tf.int32, name='Questions', shape=[None, None])\n", (24567, 24615), True, 'import tensorflow as tf\n'), ((24649, 24711), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""Documents"""', 'shape': '[None, None]'}), "(tf.int32, name='Documents', shape=[None, None])\n", (24663, 24711), True, 'import tensorflow as tf\n'), ((24760, 24836), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""SameAsQuestionFeature"""', 'shape': '[None, None]'}), "(tf.float32, name='SameAsQuestionFeature', shape=[None, None])\n", (24774, 24836), True, 'import tensorflow as tf\n'), ((24875, 24949), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""RepeatedWordFeature"""', 'shape': '[None, None]'}), "(tf.float32, name='RepeatedWordFeature', shape=[None, None])\n", (24889, 24949), True, 'import tensorflow as tf\n'), ((24997, 25073), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""RepeatedWordIntensity"""', 'shape': '[None, None]'}), "(tf.float32, name='RepeatedWordIntensity', shape=[None, None])\n", (25011, 25073), True, 'import tensorflow as tf\n'), ((25114, 25182), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""SentenceOffsets"""', 'shape': '[None, None]'}), "(tf.int32, name='SentenceOffsets', shape=[None, None])\n", (25128, 25182), True, 'import tensorflow as tf\n'), ((25222, 25283), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""SentenceLabels"""', 'shape': '[None]'}), "(tf.int32, name='SentenceLabels', shape=[None])\n", (25236, 25283), True, 'import tensorflow as tf\n'), ((25325, 25387), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""WordStartLabels"""', 'shape': '[None]'}), "(tf.int32, name='WordStartLabels', shape=[None])\n", (25339, 25387), True, 'import tensorflow as tf\n'), ((25427, 25487), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""WordEndLabels"""', 'shape': '[None]'}), "(tf.int32, name='WordEndLabels', shape=[None])\n", (25441, 25487), True, 'import tensorflow as tf\n'), ((25529, 25596), 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', (['model.embedding_dropout_prob'], {'shape': '[]'}), '(model.embedding_dropout_prob, shape=[])\n', (25556, 25596), True, 'import tensorflow as tf\n'), ((25635, 25699), 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', (['model.hidden_dropout_prob'], {'shape': '[]'}), '(model.hidden_dropout_prob, shape=[])\n', (25662, 25699), True, 'import tensorflow as tf\n'), ((25732, 25801), 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', (['(True)'], {'shape': '[]', 'name': '"""TrainingIndicator"""'}), "(True, shape=[], name='TrainingIndicator')\n", (25759, 25801), True, 'import tensorflow as tf\n'), ((25837, 25892), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""ExactMatch"""', 'shape': '[]'}), "(tf.float32, name='ExactMatch', shape=[])\n", (25851, 25892), True, 'import tensorflow as tf\n'), ((25919, 25966), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""F1"""', 'shape': '[]'}), "(tf.float32, name='F1', shape=[])\n", (25933, 25966), True, 'import tensorflow as tf\n'), ((25990, 26026), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""GloveEmbeddings"""'], {}), "('GloveEmbeddings')\n", (26007, 26026), True, 'import tensorflow as tf\n'), ((26252, 26313), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[model.vocab_size, EMBEDDING_DIM]'], {}), '(tf.float32, [model.vocab_size, EMBEDDING_DIM])\n', (26266, 26313), True, 'import tensorflow as tf\n'), ((26403, 26438), 'tensorflow.name_scope', 'tf.name_scope', (['"""QuestionEmbeddings"""'], {}), "('QuestionEmbeddings')\n", (26416, 26438), True, 'import tensorflow as tf\n'), ((26587, 26622), 'tensorflow.name_scope', 'tf.name_scope', (['"""DocumentEmbeddings"""'], {}), "('DocumentEmbeddings')\n", (26600, 26622), True, 'import tensorflow as tf\n'), ((26941, 26970), 'tensorflow.name_scope', 'tf.name_scope', (['"""PickSentence"""'], {}), "('PickSentence')\n", (26954, 26970), True, 'import tensorflow as tf\n'), ((27473, 27503), 'tensorflow.name_scope', 'tf.name_scope', (['"""PickStartWord"""'], {}), "('PickStartWord')\n", (27486, 27503), True, 'import tensorflow as tf\n'), ((27826, 27886), 'ops.prune_beam', 'ops.prune_beam', (['beam_scores', 'sentence_picks', 'model.beam_size'], {}), '(beam_scores, sentence_picks, model.beam_size)\n', (27840, 27886), False, 'import ops\n'), ((28135, 28163), 'tensorflow.name_scope', 'tf.name_scope', (['"""PickEndWord"""'], {}), "('PickEndWord')\n", (28148, 28163), True, 'import tensorflow as tf\n'), ((28547, 28622), 'ops.prune_beam', 'ops.prune_beam', (['beam_scores', '[kept_sentences, start_words]', 'model.beam_size'], {}), '(beam_scores, [kept_sentences, start_words], model.beam_size)\n', (28561, 28622), False, 'import ops\n'), ((29269, 29290), 'tensorflow.name_scope', 'tf.name_scope', (['"""Loss"""'], {}), "('Loss')\n", (29282, 29290), True, 'import tensorflow as tf\n'), ((29736, 29762), 'tensorflow.name_scope', 'tf.name_scope', (['"""TrainStep"""'], {}), "('TrainStep')\n", (29749, 29762), True, 'import tensorflow as tf\n'), ((29808, 29843), 'ops.default_train_step', 'ops.default_train_step', (['model', 'loss'], {}), '(model, loss)\n', (29830, 29843), False, 'import ops\n'), ((29867, 29896), 'tensorflow.name_scope', 'tf.name_scope', (['"""TrainSummary"""'], {}), "('TrainSummary')\n", (29880, 29896), True, 'import tensorflow as tf\n'), ((29922, 30117), 'ops.scalar_summaries', 'ops.scalar_summaries', (["{'Train-Loss': loss, 'Gradient-Norm': gradnorm, 'Sentence-Correct':\n sentence_correct, 'Start-Word-Correct': start_word_correct,\n 'End-Word-Correct': end_word_correct}"], {}), "({'Train-Loss': loss, 'Gradient-Norm': gradnorm,\n 'Sentence-Correct': sentence_correct, 'Start-Word-Correct':\n start_word_correct, 'End-Word-Correct': end_word_correct})\n", (29942, 30117), False, 'import ops\n'), ((30181, 30210), 'tensorflow.name_scope', 'tf.name_scope', (['"""ValidSummary"""'], {}), "('ValidSummary')\n", (30194, 30210), True, 'import tensorflow as tf\n'), ((30236, 30409), 'ops.scalar_summaries', 'ops.scalar_summaries', (["{'Validation-Loss': loss, 'Sentence-Correct': sentence_correct,\n 'Start-Word-Correct': start_word_correct, 'End-Word-Correct':\n end_word_correct}"], {}), "({'Validation-Loss': loss, 'Sentence-Correct':\n sentence_correct, 'Start-Word-Correct': start_word_correct,\n 'End-Word-Correct': end_word_correct})\n", (30256, 30409), False, 'import ops\n'), ((30461, 30490), 'tensorflow.name_scope', 'tf.name_scope', (['"""SquadSummary"""'], {}), "('SquadSummary')\n", (30474, 30490), True, 'import tensorflow as tf\n'), ((30516, 30576), 'ops.scalar_summaries', 'ops.scalar_summaries', (["{'Exact-Match': exact_match, 'F1': f1}"], {}), "({'Exact-Match': exact_match, 'F1': f1})\n", (30536, 30576), False, 'import ops\n'), ((1946, 1995), 'featurize.random_sample', 'featurize.random_sample', (['augmented_samples', '(10000)'], {}), '(augmented_samples, 10000)\n', (1969, 1995), False, 'import featurize\n'), ((4443, 4484), 'ops.lists_to_array', 'ops.lists_to_array', (['questions'], {'padding': '(-1)'}), '(questions, padding=-1)\n', (4461, 4484), False, 'import ops\n'), ((4508, 4548), 'ops.lists_to_array', 'ops.lists_to_array', (['contexts'], {'padding': '(-1)'}), '(contexts, padding=-1)\n', (4526, 4548), False, 'import ops\n'), ((4580, 4614), 'ops.lists_to_array', 'ops.lists_to_array', (['saq'], {'padding': '(0)'}), '(saq, padding=0)\n', (4598, 4614), False, 'import ops\n'), ((4644, 4677), 'ops.lists_to_array', 'ops.lists_to_array', (['rw'], {'padding': '(0)'}), '(rw, padding=0)\n', (4662, 4677), False, 'import ops\n'), ((4716, 4750), 'ops.lists_to_array', 'ops.lists_to_array', (['rwi'], {'padding': '(0)'}), '(rwi, padding=0)\n', (4734, 4750), False, 'import ops\n'), ((4775, 4810), 'ops.lists_to_array', 'ops.lists_to_array', (['lens'], {'padding': '(0)'}), '(lens, padding=0)\n', (4793, 4810), False, 'import ops\n'), ((5760, 5787), 'os.path.join', 'os.path.join', (['path', '"""train"""'], {}), "(path, 'train')\n", (5772, 5787), False, 'import os\n'), ((8212, 8229), 'tensorflow.shape', 'tf.shape', (['final_h'], {}), '(final_h)\n', (8220, 8229), True, 'import tensorflow as tf\n'), ((9175, 9213), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""MLP0"""'], {'reuse': 'reuse'}), "('MLP0', reuse=reuse)\n", (9192, 9213), True, 'import tensorflow as tf\n'), ((9231, 9334), 'tensorflow.contrib.layers.fully_connected', 'tf.contrib.layers.fully_connected', ([], {'inputs': 'x', 'num_outputs': 'hidden_dimension', 'activation_fn': 'tf.nn.relu'}), '(inputs=x, num_outputs=hidden_dimension,\n activation_fn=tf.nn.relu)\n', (9264, 9334), True, 'import tensorflow as tf\n'), ((9393, 9431), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""MLP1"""'], {'reuse': 'reuse'}), "('MLP1', reuse=reuse)\n", (9410, 9431), True, 'import tensorflow as tf\n'), ((9449, 9546), 'tensorflow.contrib.layers.fully_connected', 'tf.contrib.layers.fully_connected', ([], {'inputs': 'h', 'num_outputs': 'hidden_dimension', 'activation_fn': 'None'}), '(inputs=h, num_outputs=hidden_dimension,\n activation_fn=None)\n', (9482, 9546), True, 'import tensorflow as tf\n'), ((13439, 13459), 'tensorflow.range', 'tf.range', (['batch_size'], {}), '(batch_size)\n', (13447, 13459), True, 'import tensorflow as tf\n'), ((16963, 16978), 'tensorflow.range', 'tf.range', (['beams'], {}), '(beams)\n', (16971, 16978), True, 'import tensorflow as tf\n'), ((21745, 21761), 'tensorflow.shape', 'tf.shape', (['scores'], {}), '(scores)\n', (21753, 21761), True, 'import tensorflow as tf\n'), ((21780, 21796), 'tensorflow.shape', 'tf.shape', (['scores'], {}), '(scores)\n', (21788, 21796), True, 'import tensorflow as tf\n'), ((21827, 21849), 'tensorflow.ones', 'tf.ones', (['(batch, beam)'], {}), '((batch, beam))\n', (21834, 21849), True, 'import tensorflow as tf\n'), ((22212, 22247), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['correct_mask'], {'axis': '(1)'}), '(correct_mask, axis=1)\n', (22225, 22247), True, 'import tensorflow as tf\n'), ((22486, 22517), 'tensorflow.argmax', 'tf.argmax', (['correct_mask'], {'axis': '(1)'}), '(correct_mask, axis=1)\n', (22495, 22517), True, 'import tensorflow as tf\n'), ((22543, 22620), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'targets', 'logits': 'scores'}), '(labels=targets, logits=scores)\n', (22589, 22620), True, 'import tensorflow as tf\n'), ((23611, 23649), 'tensorflow.reshape', 'tf.reshape', (['scores', '[batch * beam, -1]'], {}), '(scores, [batch * beam, -1])\n', (23621, 23649), True, 'import tensorflow as tf\n'), ((23675, 23752), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'targets', 'logits': 'scores'}), '(labels=targets, logits=scores)\n', (23721, 23752), True, 'import tensorflow as tf\n'), ((23796, 23833), 'tensorflow.reshape', 'tf.reshape', (['stage_loss', '[batch, beam]'], {}), '(stage_loss, [batch, beam])\n', (23806, 23833), True, 'import tensorflow as tf\n'), ((24040, 24073), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['stage_loss'], {'axis': '(1)'}), '(stage_loss, axis=1)\n', (24053, 24073), True, 'import tensorflow as tf\n'), ((24293, 24325), 'tensorflow.cast', 'tf.cast', (['any_correct', 'tf.float32'], {}), '(any_correct, tf.float32)\n', (24300, 24325), True, 'import tensorflow as tf\n'), ((27663, 27693), 'tensorflow.expand_dims', 'tf.expand_dims', (['beam_scores', '(2)'], {}), '(beam_scores, 2)\n', (27677, 27693), True, 'import tensorflow as tf\n'), ((28355, 28385), 'tensorflow.expand_dims', 'tf.expand_dims', (['beam_scores', '(2)'], {}), '(beam_scores, 2)\n', (28369, 28385), True, 'import tensorflow as tf\n'), ((29610, 29658), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['model.l2_scale'], {}), '(model.l2_scale)\n', (29642, 29658), True, 'import tensorflow as tf\n'), ((29672, 29696), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (29694, 29696), True, 'import tensorflow as tf\n'), ((2346, 2423), 'ops.lists_to_array', 'ops.lists_to_array', (['[sample.question for sample in current_batch]'], {'padding': '(-1)'}), '([sample.question for sample in current_batch], padding=-1)\n', (2364, 2423), False, 'import ops\n'), ((2473, 2549), 'ops.lists_to_array', 'ops.lists_to_array', (['[sample.context for sample in current_batch]'], {'padding': '(-1)'}), '([sample.context for sample in current_batch], padding=-1)\n', (2491, 2549), False, 'import ops\n'), ((2648, 2741), 'ops.lists_to_array', 'ops.lists_to_array', (['[sample.same_as_question_word for sample in current_batch]'], {'padding': '(0)'}), '([sample.same_as_question_word for sample in\n current_batch], padding=0)\n', (2666, 2741), False, 'import ops\n'), ((2813, 2899), 'ops.lists_to_array', 'ops.lists_to_array', (['[sample.repeated_words for sample in current_batch]'], {'padding': '(0)'}), '([sample.repeated_words for sample in current_batch],\n padding=0)\n', (2831, 2899), False, 'import ops\n'), ((2980, 3075), 'ops.lists_to_array', 'ops.lists_to_array', (['[sample.repeated_word_intensity for sample in current_batch]'], {'padding': '(0)'}), '([sample.repeated_word_intensity for sample in\n current_batch], padding=0)\n', (2998, 3075), False, 'import ops\n'), ((3145, 3233), 'ops.lists_to_array', 'ops.lists_to_array', (['[sample.sentence_lengths for sample in current_batch]'], {'padding': '(0)'}), '([sample.sentence_lengths for sample in current_batch],\n padding=0)\n', (3163, 3233), False, 'import ops\n'), ((3307, 3369), 'numpy.array', 'np.array', (['[sample.answer_sentence for sample in current_batch]'], {}), '([sample.answer_sentence for sample in current_batch])\n', (3315, 3369), True, 'import numpy as np\n'), ((3424, 3483), 'numpy.array', 'np.array', (['[sample.answer_start for sample in current_batch]'], {}), '([sample.answer_start for sample in current_batch])\n', (3432, 3483), True, 'import numpy as np\n'), ((3536, 3593), 'numpy.array', 'np.array', (['[sample.answer_end for sample in current_batch]'], {}), '([sample.answer_end for sample in current_batch])\n', (3544, 3593), True, 'import numpy as np\n'), ((8681, 8729), 'tensorflow.contrib.layers.variance_scaling_initializer', 'tf.contrib.layers.variance_scaling_initializer', ([], {}), '()\n', (8727, 8729), True, 'import tensorflow as tf\n'), ((11325, 11344), 'tensorflow.shape', 'tf.shape', (['documents'], {}), '(documents)\n', (11333, 11344), True, 'import tensorflow as tf\n'), ((14587, 14633), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['sentence_states', 'hidden_dropout'], {}), '(sentence_states, hidden_dropout)\n', (14600, 14633), True, 'import tensorflow as tf\n'), ((16725, 16752), 'tensorflow.shape', 'tf.shape', (['sentence_features'], {}), '(sentence_features)\n', (16733, 16752), True, 'import tensorflow as tf\n'), ((18259, 18309), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['sentence_embeddings', 'hidden_dropout'], {}), '(sentence_embeddings, hidden_dropout)\n', (18272, 18309), True, 'import tensorflow as tf\n'), ((20741, 20779), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['hiddens', 'hidden_dropout'], {}), '(hiddens, hidden_dropout)\n', (20754, 20779), True, 'import tensorflow as tf\n'), ((22772, 22797), 'tensorflow.zeros_like', 'tf.zeros_like', (['stage_loss'], {}), '(stage_loss)\n', (22785, 22797), True, 'import tensorflow as tf\n'), ((23911, 23941), 'tensorflow.cast', 'tf.cast', (['correct_mask', 'tf.bool'], {}), '(correct_mask, tf.bool)\n', (23918, 23941), True, 'import tensorflow as tf\n'), ((23987, 24012), 'tensorflow.zeros_like', 'tf.zeros_like', (['stage_loss'], {}), '(stage_loss)\n', (24000, 24012), True, 'import tensorflow as tf\n'), ((26143, 26165), 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), '()\n', (26163, 26165), True, 'import tensorflow as tf\n'), ((27122, 27156), 'tensorflow.expand_dims', 'tf.expand_dims', (['sentence_scores', '(1)'], {}), '(sentence_scores, 1)\n', (27136, 27156), True, 'import tensorflow as tf\n'), ((27401, 27448), 'tensorflow.equal', 'tf.equal', (['sentence_labels', 'sentence_picks[:, 0]'], {}), '(sentence_labels, sentence_picks[:, 0])\n', (27409, 27448), True, 'import tensorflow as tf\n'), ((29196, 29243), 'tensorflow.equal', 'tf.equal', (['sentence_labels', 'kept_sentences[:, 0]'], {}), '(sentence_labels, kept_sentences[:, 0])\n', (29204, 29243), True, 'import tensorflow as tf\n'), ((21992, 22016), 'tensorflow.expand_dims', 'tf.expand_dims', (['label', '(1)'], {}), '(label, 1)\n', (22006, 22016), True, 'import tensorflow as tf\n'), ((23243, 23269), 'tensorflow.expand_dims', 'tf.expand_dims', (['targets', '(1)'], {}), '(targets, 1)\n', (23257, 23269), True, 'import tensorflow as tf\n'), ((27998, 28044), 'tensorflow.equal', 'tf.equal', (['word_start_labels', 'start_words[:, 0]'], {}), '(word_start_labels, start_words[:, 0])\n', (28006, 28044), True, 'import tensorflow as tf\n'), ((28062, 28109), 'tensorflow.equal', 'tf.equal', (['sentence_labels', 'kept_sentences[:, 0]'], {}), '(sentence_labels, kept_sentences[:, 0])\n', (28070, 28109), True, 'import tensorflow as tf\n'), ((29065, 29112), 'tensorflow.equal', 'tf.equal', (['word_end_labels', 'end_word_picks[:, 0]'], {}), '(word_end_labels, end_word_picks[:, 0])\n', (29073, 29112), True, 'import tensorflow as tf\n'), ((29130, 29181), 'tensorflow.equal', 'tf.equal', (['word_start_labels', 'kept_start_words[:, 0]'], {}), '(word_start_labels, kept_start_words[:, 0])\n', (29138, 29181), True, 'import tensorflow as tf\n'), ((23564, 23580), 'tensorflow.shape', 'tf.shape', (['scores'], {}), '(scores)\n', (23572, 23580), True, 'import tensorflow as tf\n'), ((27281, 27306), 'tensorflow.shape', 'tf.shape', (['sentence_scores'], {}), '(sentence_scores)\n', (27289, 27306), True, 'import tensorflow as tf\n')]
import os import astropy.time import matplotlib.pyplot as plt import matplotlib import numpy as np import pickle import re import pandas as pd import radvel from astroquery.simbad import Simbad import wget, zipfile, shutil from . import config norm_mean = lambda x: x/np.nanmean(x) def pickle_dump(filename,obj): """ write obj to to filename and save INPUT: filename - name to save pickle file (str) obj - object to write to file OUTPUT: obj saved as pickle file EXAMPLE: pickle_dump() """ savefile = open(filename,"w") pickle.dump(obj, savefile) savefile.close() print("Saved to {}".format(filename)) def pickle_load(filename,python3=True): """ load obj from filename INPUT: filename - name of saved pickle file (str) obj - object to write to file OUTPUT: load obj from pickle file EXAMPLE: pickle_load() """ if python3: openfile = open(filename,"rb") return pickle.load(openfile,encoding='latin1') def jd2datetime(times): """ convert jd to iso utc date/time INPUT: times in jd (array) OUTPUT: date/time in utc (array) EXAMPLE: """ return np.array([astropy.time.Time(time,format="jd",scale="utc").datetime for time in times]) def iso2jd(times): """ convert iso utc to jd date/time INPUT: date/time in iso uts (array) OUTPUT: date/time in jd (array) EXAMPLE: """ return np.array([astropy.time.Time(time,format="iso",scale="utc").jd for time in times]) def make_dir(dirname,verbose=True): """ create new directory INPUT: dirname - name of sirectory (str) verbose - include print statements (bool) OUTPUT: creates folder named dirname EXAMPLE: make_dir("folder") """ try: os.makedirs(dirname) if verbose==True: print("Created folder:",dirname) except OSError: if verbose==True: print(dirname,"already exists.") def vac2air(wavelength,P,T,input_in_angstroms=True): """ Convert vacuum wavelengths to air wavelengths INPUT: wavelength - in A if input_in_angstroms is True, else nm P - in Torr T - in Celsius OUTPUT: Wavelength in air in A if input_in_angstroms is True, else nm """ if input_in_angstroms: nn = n_air(P,T,wavelength/10.) else: nn = n_air(P,T,wavelength) return wavelength/(nn+1.) def n_air(P,T,wavelength): """ The edlen equation for index of refraction of air with pressure INPUT: P - pressure in Torr T - Temperature in Celsius wavelength - wavelength in nm OUTPUT: (n-1)_tp - see equation 1, and 2 in REF below. REF: http://iopscience.iop.org/article/10.1088/0026-1394/30/3/004/pdf EXAMPLE: nn = n_air(763.,20.,500.)-n_air(760.,20.,500.) (nn/(nn + 1.))*3.e8 """ wavenum = 1000./wavelength # in 1/micron # refractivity is (n-1)_s for a standard air mixture refractivity = ( 8342.13 + 2406030./(130.-wavenum**2.) + 15997./(38.9-wavenum**2.))*1e-8 return ((P*refractivity)/720.775) * ( (1.+P*(0.817-0.0133*T)*1e-6) / (1. + 0.0036610*T) ) def get_cmap_colors(cmap='jet',p=None,N=10): """ get colormap instance INPUT: cmap - colormap instance p - N - OUTPUT: EXAMPLE: get_cmap_colors() """ cm = plt.get_cmap(cmap) if p is None: return [cm(i) for i in np.linspace(0,1,N)] else: normalize = matplotlib.colors.Normalize(vmin=min(p), vmax=max(p)) colors = [cm(normalize(value)) for value in p] return colors def ax_apply_settings(ax,ticksize=None): """ Apply axis settings that I keep applying """ ax.minorticks_on() if ticksize is None: ticksize=12 ax.tick_params(pad=3,labelsize=ticksize) ax.grid(lw=0.3,alpha=0.3) def ax_add_colorbar(ax,p,cmap='jet',tick_width=1,tick_length=3,direction='out',pad=0.02,minorticks=False,*kw_args): """ Add a colorbar to a plot (e.g., of lines) INPUT: ax - axis to put the colorbar p - parameter that will be used for the scaling (min and max) cmap - 'jet', 'viridis' OUTPUT: cax - the colorbar object NOTES: also see here: import matplotlib.pyplot as plt sm = plt.cm.ScalarMappable(cmap=my_cmap, norm=plt.Normalize(vmin=0, vmax=1)) # fake up the array of the scalar mappable. Urgh... sm._A = [] plt.colorbar(sm) EXAMPLE: cmap = 'jet' colors = get_cmap_colors(N=len(bjds),cmap=cmap) fig, ax = plt.subplots(dpi=200) for i in range(len(bjds)): ax.plot(vin[i],ccf_sub[i],color=colors[i],lw=1) ax_apply_settings(ax,ticksize=14) ax.set_xlabel('Velocity [km/s]',fontsize=20) ax.set_ylabel('Relative Flux ',fontsize=20) cx = ax_add_colorbar(ax,obs_phases,cmap=cmap,pad=0.02) ax_apply_settings(cx) cx.axes.set_ylabel('Phase',fontsize=20,labelpad=0) cbar.set_clim(1.4,4.1) cbar.set_ticks([1.5,2.0,2.5,3.0,3.5,4.0]) """ cax, _ = matplotlib.colorbar.make_axes(ax,pad=pad,*kw_args) normalize = matplotlib.colors.Normalize(vmin=np.nanmin(p), vmax=np.nanmax(p)) cm = plt.get_cmap(cmap) cbar = matplotlib.colorbar.ColorbarBase(cax, cmap=cm, norm=normalize) if minorticks: cax.minorticks_on() cax.axes.tick_params(width=tick_width,length=tick_length,direction=direction) return cax, cbar def get_indices_of_items(arr,items): return np.where(pd.DataFrame(arr).isin(items))[0] def remove_items_from_list(l,bad_items): ibad = np.where(pd.DataFrame(l).isin(bad_items))[0] return np.delete(l,ibad) def savefigure(fig,savename,s1='{}',p1='',s2='{}',p2='',dpi=200): """ Handy function to save figures and append suffixes to filenames EXAMPLE: savefigure(fig,'MASTER_FLATS/COMPARE_PLOTS/testing.png',s1='_o{}',p1=5,s2='_spi{}',p2=14) """ fp = FilePath(savename) make_dir(fp.directory) fp.add_suffix(s1.format(p1)) fp.add_suffix(s2.format(p2)) fig.tight_layout() fig.savefig(fp._fullpath,dpi=dpi) print('Saved figure to: {}'.format(fp._fullpath)) def grep_date(string,intype="isot",outtype='iso'): """ A function to extract date from string. INPUT: string: string intype: "isot" - 20181012T001823 "iso" - 20181012 outtype: "iso" - iso "datetime" - datetime OUTPUT: string with the date """ if intype == "isot": date = re.findall(r'\d{8}T\d{6}',string)[0] elif intype == "iso": date = re.findall(r'\d{8}',string)[0] else: print("intype has to be 'isot' or 'iso'") if outtype == 'iso': return date elif outtype == 'datetime': return pd.to_datetime(date).to_pydatetime() else: print('outtype has to be "iso" or "datetime"') def grep_dates(strings,intype="isot",outtype='iso'): """ A function to extract date from strings INPUT: string: string intype: "isot" - 20181012T001823 "iso" - 20181012 outtype: "iso" - iso "datetime" - datetime OUTPUT: string with the date EXAMPLE: df = grep_dates(files,intype="isot",outtype='series') df['2018-06-26':].values """ if outtype=='series': dates = [grep_date(i,intype=intype,outtype='datetime') for i in strings] return pd.Series(index=dates,data=strings) else: return [grep_date(i,intype,outtype) for i in strings] def replace_dir(files,old,new): for i,f in enumerate(files): files[i] = files[i].replace(old,new) return files def get_header_df(fitsfiles,keywords=["OBJECT","DATE-OBS"],verbose=True): """ A function to read headers and returns a pandas dataframe INPUT: fitsfiles - a list of fitsfiles keywords - a list of header keywords to read OUTPUT: df - pandas dataframe with column names as the passed keywords """ headers = [] for i,name in enumerate(fitsfiles): if verbose: print(i,name) head = astropy.io.fits.getheader(name) values = [name] for key in keywords: values.append(head[key]) headers.append(values) df_header = pd.DataFrame(headers,columns=["filename"]+keywords) return df_header def plot_rv_model(bjd,RV,e_RV,P,T0,K,e,w,nbjd=None,nRV=None,ne_RV=None,title="",fig=None,ax=None,bx=None): """ Plot RVs and the rv model on top. Also plot residuals """ bjd_model = np.linspace(bjd[0]-2,bjd[-1]+2,10000) rv_model = get_rv_curve(bjd_model,P,T0,e=e,omega=w,K=K,plot=False) rv_obs = get_rv_curve(bjd,P,T0,e,w,K,plot=False) if nbjd is not None: rv_obs_bin = get_rv_curve(nbjd,P,T0,e,w,K,plot=False) # Plotting if fig is None and ax is None and bx is None: fig, (ax, bx) = plt.subplots(dpi=200,nrows=2,gridspec_kw={"height_ratios":[5,2]},figsize=(6,4),sharex=True) ax.errorbar(bjd,RV,e_RV,elinewidth=1,mew=0.5,capsize=5,marker="o",lw=0,markersize=6,alpha=0.5, label="Unbin, median errorbar={:0.1f}m/s".format(np.median(e_RV))) ax.plot(bjd_model,rv_model,label="Expected Orbit",lw=1,color="crimson") res = RV - rv_obs bx.errorbar(bjd,res,e_RV,elinewidth=1,mew=0.5,capsize=5,marker="o",lw=0,markersize=6,alpha=0.5,label='Residual: $\sigma$={:0.2f}m/s'.format(np.std(res))) if nbjd is not None: ax.errorbar(nbjd,nRV,ne_RV,elinewidth=1,mew=0.5,capsize=5,marker="h",lw=0,color="crimson", markersize=8,label="Bin, median errorbar={:0.1f}m/s".format(np.median(ne_RV))) bx.errorbar(nbjd,nRV-rv_obs_bin,ne_RV,elinewidth=1,mew=0.5,capsize=5,marker="h",lw=0,markersize=8,alpha=0.5,color="crimson") ax.legend(fontsize=8,loc="upper right") bx.legend(fontsize=8,loc="upper right") for xx in [ax,bx]: ax_apply_settings(xx,ticksize=12) xx.set_ylabel("RV [m/s]",fontsize=16) bx.set_xlabel("Date [UT]",labelpad=0,fontsize=16) ax.set_title(title) fig.tight_layout() fig.subplots_adjust(hspace=0.05) def plot_rv_model_phased(bjd,RV,e_RV,P,T0,K,e,w,nbjd=None,nRV=None,ne_RV=None,title="",fig=None,ax=None,bx=None): """ Plot RVs and the rv model on top. Also plot residuals """ bjd_model = np.linspace(bjd[0]-2,bjd[-1]+2,10000) rv_model = get_rv_curve(bjd_model,P,T0,e=e,omega=w,K=K,plot=False) rv_obs = get_rv_curve(bjd,P,T0,e,w,K,plot=False) # Phases: df_phase = get_phases_sorted(bjd,P,T0).sort_values("time") df_phase_model = get_phases_sorted(bjd_model,P,T0,rvs=rv_model).sort_values("time") if nbjd is not None: rv_obs_bin = get_rv_curve(nbjd,P,T0,e,w,K,plot=False) df_phase_bin = get_phases_sorted(nbjd,P,T0).sort_values("time") # Plotting if fig is None and ax is None and bx is None: fig, (ax, bx) = plt.subplots(dpi=200,nrows=2,gridspec_kw={"height_ratios":[5,2]},figsize=(6,4),sharex=True) ax.errorbar(df_phase.phases,RV,e_RV,elinewidth=1,mew=0.5,capsize=5,marker="o",lw=0,markersize=6,alpha=0.5, label="Unbin, median errorbar={:0.1f}m/s".format(np.median(e_RV))) ax.plot(df_phase_model.phases,rv_model,label="Expected Orbit",lw=0,marker="o",markersize=2,color="crimson") res = RV - rv_obs bx.errorbar(df_phase.phases,res,e_RV,elinewidth=1,mew=0.5,capsize=5,marker="o",lw=0,markersize=6,alpha=0.5,label='Residual: $\sigma$={:0.2f}m/s'.format(np.std(res))) if nbjd is not None: ax.errorbar(df_phase_bin.phases,nRV,ne_RV,elinewidth=1,mew=0.5,capsize=5,marker="h",lw=0,color="crimson", markersize=8,label="Bin, median errorbar={:0.1f}m/s".format(np.median(ne_RV)),alpha=0.9) bx.errorbar(df_phase_bin.phases,nRV-rv_obs_bin,ne_RV,elinewidth=1,mew=0.5,capsize=5,marker="h",lw=0,markersize=8,alpha=0.9,color="crimson") ax.legend(fontsize=8,loc="upper right") bx.legend(fontsize=8,loc="upper right") for xx in [ax,bx]: ax_apply_settings(xx,ticksize=12) xx.set_ylabel("RV [m/s]",fontsize=16) bx.set_xlabel("Orbital phase",labelpad=0,fontsize=16) ax.set_title(title) fig.tight_layout() fig.subplots_adjust(hspace=0.05) def get_phases_sorted(t, P, t0,rvs=None,rvs_err=None,sort=True,centered_on_0=True,tdur=None): """ Get a sorted pandas dataframe of phases, times (and Rvs if supplied) INPUT: t - times in jd P - period in days t0 - time of periastron usually OUTPUT: df - pandas dataframe with columns: -- phases (sorted) -- time - time -- rvs - if provided NOTES: Useful for RVs. """ phases = np.mod(t - t0,P) phases /= P df = pd.DataFrame(zip(phases,t),columns=['phases','time']) if rvs is not None: df['rvs'] = rvs if rvs_err is not None: df['rvs_err'] = rvs_err if centered_on_0: _p = df.phases.values m = df.phases.values > 0.5 _p[m] = _p[m] - 1. df['phases'] = _p if tdur is not None: df["intransit"] = np.abs(df.phases) < tdur/(2.*P) print("Found {} in transit".format(len(df[df['intransit']]))) if sort: df = df.sort_values('phases').reset_index(drop=True) return df def get_rv_curve(times_jd,P,tc,e,omega,K,plot=True,ax=None,verbose=True,plot_tnow=True): """ A function to plot an RV curve as a function of time (not phased) INPUT: times_jd: times in jd P: orbital period in days tc: transit center in jd e: eccentricity omega: periastron in degrees K: RV semi-amplitude in m/s OUTPUT: rv: array of RVs at times times_jd """ t_peri = radvel.orbit.timetrans_to_timeperi(tc=tc, per=P, ecc=e, omega=np.deg2rad(omega)) rvs = radvel.kepler.rv_drive(times_jd,[P, t_peri, e, np.deg2rad(omega), K]) if verbose: print("Assuming:") print("P {}d".format(P)) print("tc {}".format(tc)) print("e {}".format(e)) print("omega {}deg".format(omega)) print("K {}m/s".format(K)) if plot: if ax is None: fig, ax = plt.subplots(figsize=(12,8)) times = jd2datetime(times_jd) ax.plot(times,rvs) ax.set_xlabel("Time") ax.set_ylabel("RV [m/s]") ax.grid(lw=0.5,alpha=0.3) ax.minorticks_on() if plot_tnow: t_now = Time(datetime.datetime.utcnow()) ax.axvline(t_now.datetime,color="red",label="Time now") xlim = ax.get_xlim() ax.hlines(0,xlim[0],xlim[1],alpha=0.5,color="k",lw=1) for label in (ax.get_xticklabels()): label.set_fontsize(10) return rvs def filter_simbadnames(l): """ Filter SIMBAD names """ _n = find_str_in_list(l,'DR2') if _n=='': _n = find_str_in_list(l,'DR1') if _n=='': _n = find_str_in_list(l,'HD') if _n=='': _n = find_str_in_list(l,'GJ') return _n def get_simbad_object_names(name,as_str=False): """ Get all Simbad names for an object """ result_table = Simbad.query_objectids(name).to_pandas() names = result_table.ID.values.astype(str) if as_str: names = [i.replace(' ','_') for i in names] return '|'.join(names) else: return names def find_str_in_list(l,string): """ Return first element that matches a string in a list """ for element in l: if string in element: return element return '' def get_library(overwrite=False): """ Download stellar library if it does not already exist INPUT: overwrite - if True, try redownloading and overwriting current library OUTPUT: saves downloaded zip file to outputdir folder EXAMPLE: hpfspecmatch.utils.get_library() """ if ((os.path.isdir(config.PATH_LIBRARY) is False) and (overwrite is False)) or (overwrite is True): make_dir(config.PATH_LIBRARY) print('Downloading library from: {}'.format(config.URL_LIBRARY)) wget.download(config.URL_LIBRARY, config.PATH_LIBRARY_ZIPNAME) print('Extracting zip file') with zipfile.ZipFile(config.PATH_LIBRARY_ZIPNAME, 'r') as zip_ref: zip_ref.extractall(config.PATH_LIBRARY) print('Extracting zip file complete') print('Deleting zip file') os.remove(config.PATH_LIBRARY_ZIPNAME) #shutil.rmtree('../library/__MACOSX') print('Download complete') else: print('Library already exists. Skipping download') print('Library path is: {}'.format(config.PATH_LIBRARY))
[ "wget.download", "zipfile.ZipFile", "matplotlib.colorbar.ColorbarBase", "numpy.nanmean", "numpy.nanmin", "matplotlib.colorbar.make_axes", "numpy.mod", "pandas.to_datetime", "os.remove", "numpy.delete", "numpy.linspace", "os.path.isdir", "numpy.nanmax", "pandas.DataFrame", "numpy.abs", ...
[((613, 639), 'pickle.dump', 'pickle.dump', (['obj', 'savefile'], {}), '(obj, savefile)\n', (624, 639), False, 'import pickle\n'), ((1053, 1093), 'pickle.load', 'pickle.load', (['openfile'], {'encoding': '"""latin1"""'}), "(openfile, encoding='latin1')\n", (1064, 1093), False, 'import pickle\n'), ((3657, 3675), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['cmap'], {}), '(cmap)\n', (3669, 3675), True, 'import matplotlib.pyplot as plt\n'), ((5436, 5488), 'matplotlib.colorbar.make_axes', 'matplotlib.colorbar.make_axes', (['ax', '*kw_args'], {'pad': 'pad'}), '(ax, *kw_args, pad=pad)\n', (5465, 5488), False, 'import matplotlib\n'), ((5578, 5596), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['cmap'], {}), '(cmap)\n', (5590, 5596), True, 'import matplotlib.pyplot as plt\n'), ((5608, 5670), 'matplotlib.colorbar.ColorbarBase', 'matplotlib.colorbar.ColorbarBase', (['cax'], {'cmap': 'cm', 'norm': 'normalize'}), '(cax, cmap=cm, norm=normalize)\n', (5640, 5670), False, 'import matplotlib\n'), ((6023, 6041), 'numpy.delete', 'np.delete', (['l', 'ibad'], {}), '(l, ibad)\n', (6032, 6041), True, 'import numpy as np\n'), ((8685, 8739), 'pandas.DataFrame', 'pd.DataFrame', (['headers'], {'columns': "(['filename'] + keywords)"}), "(headers, columns=['filename'] + keywords)\n", (8697, 8739), True, 'import pandas as pd\n'), ((8956, 8999), 'numpy.linspace', 'np.linspace', (['(bjd[0] - 2)', '(bjd[-1] + 2)', '(10000)'], {}), '(bjd[0] - 2, bjd[-1] + 2, 10000)\n', (8967, 8999), True, 'import numpy as np\n'), ((10732, 10775), 'numpy.linspace', 'np.linspace', (['(bjd[0] - 2)', '(bjd[-1] + 2)', '(10000)'], {}), '(bjd[0] - 2, bjd[-1] + 2, 10000)\n', (10743, 10775), True, 'import numpy as np\n'), ((13103, 13120), 'numpy.mod', 'np.mod', (['(t - t0)', 'P'], {}), '(t - t0, P)\n', (13109, 13120), True, 'import numpy as np\n'), ((272, 285), 'numpy.nanmean', 'np.nanmean', (['x'], {}), '(x)\n', (282, 285), True, 'import numpy as np\n'), ((2007, 2027), 'os.makedirs', 'os.makedirs', (['dirname'], {}), '(dirname)\n', (2018, 2027), False, 'import os\n'), ((7844, 7880), 'pandas.Series', 'pd.Series', ([], {'index': 'dates', 'data': 'strings'}), '(index=dates, data=strings)\n', (7853, 7880), True, 'import pandas as pd\n'), ((9300, 9402), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'dpi': '(200)', 'nrows': '(2)', 'gridspec_kw': "{'height_ratios': [5, 2]}", 'figsize': '(6, 4)', 'sharex': '(True)'}), "(dpi=200, nrows=2, gridspec_kw={'height_ratios': [5, 2]},\n figsize=(6, 4), sharex=True)\n", (9312, 9402), True, 'import matplotlib.pyplot as plt\n'), ((11314, 11416), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'dpi': '(200)', 'nrows': '(2)', 'gridspec_kw': "{'height_ratios': [5, 2]}", 'figsize': '(6, 4)', 'sharex': '(True)'}), "(dpi=200, nrows=2, gridspec_kw={'height_ratios': [5, 2]},\n figsize=(6, 4), sharex=True)\n", (11326, 11416), True, 'import matplotlib.pyplot as plt\n'), ((16838, 16900), 'wget.download', 'wget.download', (['config.URL_LIBRARY', 'config.PATH_LIBRARY_ZIPNAME'], {}), '(config.URL_LIBRARY, config.PATH_LIBRARY_ZIPNAME)\n', (16851, 16900), False, 'import wget, zipfile, shutil\n'), ((17165, 17203), 'os.remove', 'os.remove', (['config.PATH_LIBRARY_ZIPNAME'], {}), '(config.PATH_LIBRARY_ZIPNAME)\n', (17174, 17203), False, 'import os\n'), ((5536, 5548), 'numpy.nanmin', 'np.nanmin', (['p'], {}), '(p)\n', (5545, 5548), True, 'import numpy as np\n'), ((5555, 5567), 'numpy.nanmax', 'np.nanmax', (['p'], {}), '(p)\n', (5564, 5567), True, 'import numpy as np\n'), ((6916, 6951), 're.findall', 're.findall', (['"""\\\\d{8}T\\\\d{6}"""', 'string'], {}), "('\\\\d{8}T\\\\d{6}', string)\n", (6926, 6951), False, 'import re\n'), ((13498, 13515), 'numpy.abs', 'np.abs', (['df.phases'], {}), '(df.phases)\n', (13504, 13515), True, 'import numpy as np\n'), ((14353, 14370), 'numpy.deg2rad', 'np.deg2rad', (['omega'], {}), '(omega)\n', (14363, 14370), True, 'import numpy as np\n'), ((14561, 14578), 'numpy.deg2rad', 'np.deg2rad', (['omega'], {}), '(omega)\n', (14571, 14578), True, 'import numpy as np\n'), ((14906, 14935), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 8)'}), '(figsize=(12, 8))\n', (14918, 14935), True, 'import matplotlib.pyplot as plt\n'), ((15855, 15883), 'astroquery.simbad.Simbad.query_objectids', 'Simbad.query_objectids', (['name'], {}), '(name)\n', (15877, 15883), False, 'from astroquery.simbad import Simbad\n'), ((16960, 17009), 'zipfile.ZipFile', 'zipfile.ZipFile', (['config.PATH_LIBRARY_ZIPNAME', '"""r"""'], {}), "(config.PATH_LIBRARY_ZIPNAME, 'r')\n", (16975, 17009), False, 'import wget, zipfile, shutil\n'), ((3725, 3745), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'N'], {}), '(0, 1, N)\n', (3736, 3745), True, 'import numpy as np\n'), ((6994, 7022), 're.findall', 're.findall', (['"""\\\\d{8}"""', 'string'], {}), "('\\\\d{8}', string)\n", (7004, 7022), False, 'import re\n'), ((9557, 9572), 'numpy.median', 'np.median', (['e_RV'], {}), '(e_RV)\n', (9566, 9572), True, 'import numpy as np\n'), ((9817, 9828), 'numpy.std', 'np.std', (['res'], {}), '(res)\n', (9823, 9828), True, 'import numpy as np\n'), ((11583, 11598), 'numpy.median', 'np.median', (['e_RV'], {}), '(e_RV)\n', (11592, 11598), True, 'import numpy as np\n'), ((11891, 11902), 'numpy.std', 'np.std', (['res'], {}), '(res)\n', (11897, 11902), True, 'import numpy as np\n'), ((16615, 16649), 'os.path.isdir', 'os.path.isdir', (['config.PATH_LIBRARY'], {}), '(config.PATH_LIBRARY)\n', (16628, 16649), False, 'import os\n'), ((5879, 5896), 'pandas.DataFrame', 'pd.DataFrame', (['arr'], {}), '(arr)\n', (5891, 5896), True, 'import pandas as pd\n'), ((5976, 5991), 'pandas.DataFrame', 'pd.DataFrame', (['l'], {}), '(l)\n', (5988, 5991), True, 'import pandas as pd\n'), ((7177, 7197), 'pandas.to_datetime', 'pd.to_datetime', (['date'], {}), '(date)\n', (7191, 7197), True, 'import pandas as pd\n'), ((10032, 10048), 'numpy.median', 'np.median', (['ne_RV'], {}), '(ne_RV)\n', (10041, 10048), True, 'import numpy as np\n'), ((12121, 12137), 'numpy.median', 'np.median', (['ne_RV'], {}), '(ne_RV)\n', (12130, 12137), True, 'import numpy as np\n')]
""" This script generates anchor boxes for a custom dataset. It will generate: + an anchor text file (depending on number of anchors, default = 5) Example usage: ------------- python anchor_boxes.py --path /path/to/dataset.hdf5 --output_dir ./ --num_anchors 5 """ import os import csv import numpy as np import cv2, io import h5py from PIL import Image from cfg import * from box import box_iou, Box from argparse import ArgumentParser parser = ArgumentParser(description="Generate custom anchor boxes") parser.add_argument('-i', '--input_hdf5', help="Path to input hdf5 file", type=str, default=None) parser.add_argument('-o', '--output_dir', help="Path to output directory", type=str, default='./') parser.add_argument('-n', '--number_anchors', help="Number of anchors [default = 5]", type=int, default=5) def hdf5_read_image_boxes(data_images, data_boxes, idx): image = data_images[idx] boxes = data_boxes[idx] boxes = boxes.reshape((-1, 5)) image = Image.open(io.BytesIO(image)) image_data = np.array(image, dtype=np.float) return np.array(image), np.array(boxes) def main(): args = parser.parse_args() input_hdf5 = args.input_hdf5 output_dir = args.output_dir number_anchors = args.number_anchors h5_data = h5py.File(input_hdf5, 'r') # ################################# # Generate Anchors and Categories # # ################################# train_boxes = np.array(h5_data['train/boxes']) train_images = np.array(h5_data['train/images']) gt_boxes = [] n_small = 0 average_iou = [] print("Calculating Anchors using K-mean Clustering....") if number_anchors in range(2, 16): for i in range(train_images.shape[0]): img, boxes = hdf5_read_image_boxes(train_images, train_boxes, i) img_height, img_width = img.shape[:2] orig_size = np.array([img_width, img_height], dtype=np.float) orig_size = np.expand_dims(orig_size, axis=0) boxes_xy = 0.5 * (boxes[:, 3:5] + boxes[:, 1:3]) boxes_wh = boxes[:, 3:5] - boxes[:, 1:3] # boxes_xy = boxes_xy / orig_size # boxes_wh = boxes_wh / orig_size boxes = np.concatenate((boxes_xy, boxes_wh), axis=1) for box in boxes: xc, yc, w, h = box[0], box[1], box[2], box[3] aspect_ratio = [IMAGE_W / float(img_width), IMAGE_H / float(img_height)] feature_width = float(w) * aspect_ratio[0] / 32 feature_height = float(h) * aspect_ratio[1] / 32 if feature_width < 1 and feature_height < 1: n_small += 1 box = Box(0, 0, feature_width, feature_height) gt_boxes.append(box) print('Total boxes: ' + str(len(gt_boxes))) print('Total small: ' + str(n_small)) anchors, avg_iou = k_mean_cluster(number_anchors, gt_boxes) print("Number of anchors: {:2} | Average IoU:{:-4f}\n\n ".format(number_anchors, avg_iou)) anchors_file = os.path.join(output_dir, str(number_anchors) + '_' + str(round(avg_iou, 2)) + '_anchors.txt') average_iou.append(avg_iou) if not os.path.isdir(output_dir): os.mkdir(output_dir) with open(anchors_file, 'w') as f: for anchor in anchors: f.write("({:5f}, {:5f})\n".format(anchor.w, anchor.h)) print('average_iou:', average_iou); def k_mean_cluster(n_anchors, gt_boxes, loss_convergence=1e-6): """ Cluster anchors. """ # initialize random centroids centroid_indices = np.random.choice(len(gt_boxes), n_anchors) centroids = [] for centroid_index in centroid_indices: centroids.append(gt_boxes[centroid_index]) # iterate k-means anchors, avg_iou, loss = run_k_mean(n_anchors, gt_boxes, centroids) while True: anchors, avg_iou, curr_loss = run_k_mean(n_anchors, gt_boxes, anchors) if abs(loss - curr_loss) < loss_convergence: break loss = curr_loss return anchors, avg_iou def run_k_mean(n_anchors, boxes, centroids): ''' Perform K-mean clustering on training ground truth to generate anchors. In the paper, authors argues that generating anchors through anchors would improve Recall of the network NOTE: Euclidean distance produces larger errors for larger boxes. Therefore, YOLOv2 did not use Euclidean distance to measure calculate loss. Instead, it uses the following formula: d(box, centroid)= 1 - IoU (box, centroid) :param n_anchors: :param boxes: :param centroids: :return: new_centroids: set of new anchors groups: wth? loss: compared to current bboxes ''' loss = 0 groups = [] new_centroids = [] for i in range(n_anchors): groups.append([]) new_centroids.append(Box(0, 0, 0, 0)) for box in boxes: min_distance = 1 group_index = 0 for i, centroid in enumerate(centroids): distance = 1 - box_iou(box, centroid) # Used in YOLO9000 if distance < min_distance: min_distance = distance group_index = i groups[group_index].append(box) loss += min_distance new_centroids[group_index].w += box.w new_centroids[group_index].h += box.h for i in range(n_anchors): if len(groups[i]) == 0: continue new_centroids[i].w /= len(groups[i]) new_centroids[i].h /= len(groups[i]) iou = 0 counter = 0 for i, anchor in enumerate(new_centroids): for gt_box in groups[i]: iou += box_iou(gt_box, anchor) counter += 1 avg_iou = iou / counter return new_centroids, avg_iou, loss if __name__ == '__main__': main()
[ "argparse.ArgumentParser", "io.BytesIO", "h5py.File", "box.Box", "numpy.array", "os.path.isdir", "os.mkdir", "numpy.expand_dims", "numpy.concatenate", "box.box_iou" ]
[((460, 518), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Generate custom anchor boxes"""'}), "(description='Generate custom anchor boxes')\n", (474, 518), False, 'from argparse import ArgumentParser\n'), ((1102, 1133), 'numpy.array', 'np.array', (['image'], {'dtype': 'np.float'}), '(image, dtype=np.float)\n', (1110, 1133), True, 'import numpy as np\n'), ((1354, 1380), 'h5py.File', 'h5py.File', (['input_hdf5', '"""r"""'], {}), "(input_hdf5, 'r')\n", (1363, 1380), False, 'import h5py\n'), ((1520, 1552), 'numpy.array', 'np.array', (["h5_data['train/boxes']"], {}), "(h5_data['train/boxes'])\n", (1528, 1552), True, 'import numpy as np\n'), ((1572, 1605), 'numpy.array', 'np.array', (["h5_data['train/images']"], {}), "(h5_data['train/images'])\n", (1580, 1605), True, 'import numpy as np\n'), ((1066, 1083), 'io.BytesIO', 'io.BytesIO', (['image'], {}), '(image)\n', (1076, 1083), False, 'import cv2, io\n'), ((1156, 1171), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (1164, 1171), True, 'import numpy as np\n'), ((1173, 1188), 'numpy.array', 'np.array', (['boxes'], {}), '(boxes)\n', (1181, 1188), True, 'import numpy as np\n'), ((1960, 2009), 'numpy.array', 'np.array', (['[img_width, img_height]'], {'dtype': 'np.float'}), '([img_width, img_height], dtype=np.float)\n', (1968, 2009), True, 'import numpy as np\n'), ((2034, 2067), 'numpy.expand_dims', 'np.expand_dims', (['orig_size'], {'axis': '(0)'}), '(orig_size, axis=0)\n', (2048, 2067), True, 'import numpy as np\n'), ((2294, 2338), 'numpy.concatenate', 'np.concatenate', (['(boxes_xy, boxes_wh)'], {'axis': '(1)'}), '((boxes_xy, boxes_wh), axis=1)\n', (2308, 2338), True, 'import numpy as np\n'), ((3277, 3302), 'os.path.isdir', 'os.path.isdir', (['output_dir'], {}), '(output_dir)\n', (3290, 3302), False, 'import os\n'), ((3316, 3336), 'os.mkdir', 'os.mkdir', (['output_dir'], {}), '(output_dir)\n', (3324, 3336), False, 'import os\n'), ((4989, 5004), 'box.Box', 'Box', (['(0)', '(0)', '(0)', '(0)'], {}), '(0, 0, 0, 0)\n', (4992, 5004), False, 'from box import box_iou, Box\n'), ((5775, 5798), 'box.box_iou', 'box_iou', (['gt_box', 'anchor'], {}), '(gt_box, anchor)\n', (5782, 5798), False, 'from box import box_iou, Box\n'), ((2765, 2805), 'box.Box', 'Box', (['(0)', '(0)', 'feature_width', 'feature_height'], {}), '(0, 0, feature_width, feature_height)\n', (2768, 2805), False, 'from box import box_iou, Box\n'), ((5155, 5177), 'box.box_iou', 'box_iou', (['box', 'centroid'], {}), '(box, centroid)\n', (5162, 5177), False, 'from box import box_iou, Box\n')]
# -*- coding: utf-8 -*- """ @author: "<NAME> and <NAME>" @license: "MIT" @version: "1.0" @email: "<EMAIL> or <EMAIL> " @created: "26 October 2020" Description: greedy heuristic algorithm that optimizes data lake jobs """ import zmq import time import numpy as np import random as rand import string from multiprocessing import Process from ..common.read_data import FileData from .dl_job import Dl_Job from .u_demand import Demand from .dl_client import Dl_Client class Dl_Server: def __init__(self, file, port="5556"): self.PORT = port self.file_path = file self.running = True context = zmq.Context() self.socket = context.socket(zmq.REP) self.socket.bind("tcp://*:%s" % self.PORT) print("server initialized!") self.jobs = self.init_jobs() self.a_matrix = np.ones(len(self.jobs), dtype=float) self.available = np.ones(len(self.jobs), dtype=bool) print(str(len(self.jobs)) + " jobs created.") def init_jobs(self): jobs = [] cst_idx = -1 fd = FileData(self.file_path) for k, v in fd.title: # print(str(k) + ' ' + str(v.decode())) if v.decode() == 'cost': cst_idx = k if cst_idx > 0: # print(fd.data) for i in range(len(fd.data)): obj = fd.data[i] name = 'jb' + str(i) jb = Dl_Job(i, name, int(obj[cst_idx]), self.PORT) jobs.append(jb) return jobs def choose_job(self): idx = -1 y = 0 x = float(rand.randint(1, 10) / 10) # print("random: " + str(x)) # for i in range(len(self.available)): for jb in self.jobs: if jb.status: # self.available[i]: # idx = i idx = jb.index a = self.a_matrix[idx] cost = 1 / jb.cost y = y + (cost * (a / np.sum(self.a_matrix))) if y >= x: # return self.jobs[idx] return idx return idx def update_ab(self, job, end_time): elapsed = end_time - job.last_time job.last_time = elapsed self.a_matrix[job.index] += 1 print(self.a_matrix) def start(self): print("server is running ...") while self.running: # Wait for next request from client temp = self.socket.recv() message = temp.decode() time.sleep(1) # for jb_o in self.jobs: # print(jb_o.status) if 'jb' in message: # acknowledge job complete and update matrix # self.update_ab(jb1, d1) end = time.time() idx = int(message.strip(string.ascii_letters)) jb = self.jobs[idx] self.update_ab(jb, end) jb.status = True # add to available jobs print(str(message) + " (server) updated!") self.socket.send_string("ACK") else: # new user demand print("Received demand: " + str(message)) delay = int(message) d1 = Demand(delay) print("checking new demands - allocate to jobs") jb_idx = self.choose_job() # jb1 = self.jobs[0] if jb_idx == -1: self.socket.send_string("All jobs are busy") else: # Now we can connect a client to all the demands # Process(target=self.work, args=([jb_idx, d1],)).start() print("chosen job index: " + str(jb_idx)) jb = self.jobs[jb_idx] jb.status = False # remove from available jobs jb.last_time = time.time() Process(target=jb.work, args=(d1,)).start() self.socket.send_string("Demand allocated to job " + jb.name)
[ "multiprocessing.Process", "time.sleep", "numpy.sum", "time.time", "zmq.Context", "random.randint" ]
[((631, 644), 'zmq.Context', 'zmq.Context', ([], {}), '()\n', (642, 644), False, 'import zmq\n'), ((2509, 2522), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (2519, 2522), False, 'import time\n'), ((1602, 1621), 'random.randint', 'rand.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (1614, 1621), True, 'import random as rand\n'), ((2753, 2764), 'time.time', 'time.time', ([], {}), '()\n', (2762, 2764), False, 'import time\n'), ((3856, 3867), 'time.time', 'time.time', ([], {}), '()\n', (3865, 3867), False, 'import time\n'), ((1957, 1978), 'numpy.sum', 'np.sum', (['self.a_matrix'], {}), '(self.a_matrix)\n', (1963, 1978), True, 'import numpy as np\n'), ((3888, 3923), 'multiprocessing.Process', 'Process', ([], {'target': 'jb.work', 'args': '(d1,)'}), '(target=jb.work, args=(d1,))\n', (3895, 3923), False, 'from multiprocessing import Process\n')]
import numpy as np #import scipy as sp import pylab as p import matplotlib import matplotlib.cm as cm import matplotlib.pyplot as plt import pandas as pd import hydropy as hp from matplotlib.colors import Normalize from matplotlib.transforms import offset_copy from matplotlib.ticker import MaxNLocator from pylab import * from model_evaluation_mc import ObjectiveFunctions from matplotlib.ticker import MaxNLocator, LinearLocator, NullLocator from mpl_toolkits.axes_grid import make_axes_locatable p.rc('mathtext', default='regular') def translate_cmap(yourchoice): """ Convert readable colormap to a matplotlib cmap entity """ cmap_transposer = {'red_yellow_green': 'RdYlGn_r', 'yellow_orange_brown' : 'YlOrBr', 'blue_green' : 'winter'} return cmap_transposer[yourchoice] def _define_thresholdrange(measured, modelled, objective_function='SSE'): temp = ObjectiveFunctions(measured, modelled) objective= np.vstack((temp.SSE(), temp.RMSE(), temp.RRMSE(), temp.NSE())) if objective_function == "SSE": selected_of = objective[0] print("Objective_function = SSE") elif objective_function == "RMSE": selected_of = objective[1] print("Objective_function = RMSE") elif objective_function == "RRMSE": selected_of = objective[2] print("Objective_function = RRMSE") else: selected_of = objective[3] print("Objective_function = NSE") return selected_of def create_scatterhist(all_parameters, parameter1, parameter2, measured, modelled, pars_names, objective_function='SSE', colormaps = "red_yellow_green", threshold=0.005, *args, **kwargs): ''' Function to create the interactive scatterplot. Behavioural is always taken as lower as the given threshold. Parameters ---------- all_parameters : Nxp np.array A number of parameter (p) value combinations used as model input. Length N corresponds to the number of simulations parameter1, parameter 2: {parametername : value} Parametername of the parameters that the user wants to use for model evaluation modelled: Nxk np.array simulation outputs for all parameterscombinations (N). Length k is the length of the timeserie measured: 1xk np.array observations. Length k is the length of the timeserie parsnames: {parametername : value} dict with all parameters (p) used the model objective_function : Nx1 np.array The user is allowed to choose between different objective functions (SSE, RMSE, RRMSE) colormaps : Colormap of the scatterplot treshold : Value between 0 and 1. Parametersets for which the scaled value of the objective function < threshold are retained (these parametersets are behavioral). *args, **kwargs: args arguments given to the scatter plot example: s=15, marker='o', edgecolors= 'k', facecolor = 'white' ... ''' # Extract values from pd dataframes all_parameters=all_parameters.values measured=measured.values modelled=modelled.values selected_of = _define_thresholdrange(measured, modelled, objective_function) #Translate color into a colormap colormaps = translate_cmap(colormaps) #Selected parameters & objective function parameters = np.vstack((all_parameters[:,parameter1], all_parameters[:,parameter2])).T scaled_of = np.array((selected_of-selected_of.min())/(selected_of.max()-selected_of.min())) #calculation of the real threshold value from the relative one real_threshold = threshold*(selected_of.max() - selected_of.min())+selected_of.min() print("Current threshold = " + str(real_threshold)) #check if selected parameter are not the same if parameter1 == parameter2: raise Exception('Select two different parameters') #check if parameter and of are really arrays if not isinstance(parameters, np.ndarray): raise Exception('parameters need to be numpy ndarray') if not isinstance(scaled_of, np.ndarray): raise Exception('objective function need to be numpy ndarray') # check if objective function is of size 1xN scaled_of = np.atleast_2d(scaled_of).T if (len(scaled_of.shape) != 2 ): raise Exception("Objective function need to be of size (1, N) got %s instead" %(scaled_of.shape)) # check that SSE row length is equal to parameters if not parameters.shape[0] == scaled_of.shape[0]: raise Exception("None corresponding size of parameters and OF!") # Check if threshold is in range of SSE values if threshold < 0 or threshold > 1: raise Exception("Threshold outside objective function ranges") # Select behavioural parameter sets with of lower as threshold search=np.where(scaled_of < threshold) behav_par = parameters[search[0]] behav_obj = selected_of[search[0]].T print("Number of behavioural parametersets = " + str(behav_obj.shape[0]) + " out of " + str(parameters.shape[0])) if not behav_par.size > 0: raise Exception('Threshold to severe, no behavioural sets.') fig, ax_scatter = plt.subplots(figsize=(8,6)) divider = make_axes_locatable(ax_scatter) ax_scatter.set_autoscale_on(True) # create a new axes with above the axScatter ax_histx = divider.new_vertical(1.5, pad=0.0001, sharex=ax_scatter) # create a new axes on the right side of the axScatter ax_histy = divider.new_horizontal(1.5, pad=0.0001, sharey=ax_scatter) fig.add_axes(ax_histx) fig.add_axes(ax_histy) # now determine nice limits by hand: xmin = np.min(all_parameters[:,parameter1]) xmax = np.max(all_parameters[:,parameter1]) ymin = np.min(all_parameters[:,parameter2]) ymax = np.max(all_parameters[:,parameter2]) ax_histx.set_xlim( (xmin, xmax) ) ax_histy.set_ylim( (ymin, ymax) ) #determine binwidth (pylab examples:scatter_hist.py ) binwidth = 0.05 xymax = np.max( [np.max(behav_par[:,0]), np.max(behav_par[:,1])] ) lim = (int(xymax/binwidth) + 1) * binwidth bins = np.arange(-lim, lim + binwidth, binwidth) # create scatter & histogram sc1 = ax_scatter.scatter(behav_par[:,0], behav_par[:,1], c=behav_obj, edgecolors= 'none', cmap=colormaps, *args, **kwargs) ax_histx.hist(behav_par[:,0], color='0.6', edgecolor='None', bins = bins) ax_histy.hist(behav_par[:,1], orientation='horizontal', edgecolor='None', color='0.6', bins=bins) #determine number of bins scatter majloc1 = MaxNLocator(nbins=5, prune='lower') ax_scatter.yaxis.set_major_locator(majloc1) majloc2 = MaxNLocator(nbins=5) ax_scatter.xaxis.set_major_locator(majloc2) ax_scatter.grid(linestyle = 'dashed', color = '0.75',linewidth = 1.) ax_scatter.set_axisbelow(True) #ax_histx.set_axisbelow(True) plt.setp(ax_histx.get_xticklabels() + ax_histy.get_yticklabels(), visible=False) plt.setp(ax_histx.get_yticklabels() + ax_histy.get_xticklabels(), visible=False) ax_histy.set_xticks([]) ax_histx.set_yticks([]) ax_histx.xaxis.set_ticks_position('bottom') ax_histy.yaxis.set_ticks_position('left') ax_histy.spines['right'].set_color('none') ax_histy.spines['top'].set_color('none') ax_histy.spines['bottom'].set_color('none') ax_histy.spines['left'].set_color('none') ax_histx.spines['top'].set_color('none') ax_histx.spines['right'].set_color('none') ax_histx.spines['left'].set_color('none') ax_histx.spines['bottom'].set_color('none') ax_scatter.spines['top'].set_color('none') ax_scatter.spines['right'].set_color('none') # x and y label of parameter names ax_scatter.set_xlabel(pars_names[parameter1], horizontalalignment ='center', verticalalignment ='center') ax_scatter.set_ylabel(pars_names[parameter2], horizontalalignment ='center', verticalalignment ='center') # Colorbar cbar = fig.colorbar(sc1, ax=ax_scatter, cmap=colormaps, orientation='vertical') cbar.ax.set_ylabel('Value objective function') behav_outputs=modelled[search[0]] return fig, ax_scatter, ax_histx, ax_histy, sc1, cbar, behav_outputs
[ "mpl_toolkits.axes_grid.make_axes_locatable", "numpy.atleast_2d", "pylab.rc", "numpy.where", "numpy.max", "matplotlib.ticker.MaxNLocator", "numpy.vstack", "numpy.min", "matplotlib.pyplot.subplots", "numpy.arange", "model_evaluation_mc.ObjectiveFunctions" ]
[((520, 555), 'pylab.rc', 'p.rc', (['"""mathtext"""'], {'default': '"""regular"""'}), "('mathtext', default='regular')\n", (524, 555), True, 'import pylab as p\n'), ((995, 1033), 'model_evaluation_mc.ObjectiveFunctions', 'ObjectiveFunctions', (['measured', 'modelled'], {}), '(measured, modelled)\n', (1013, 1033), False, 'from model_evaluation_mc import ObjectiveFunctions\n'), ((5376, 5407), 'numpy.where', 'np.where', (['(scaled_of < threshold)'], {}), '(scaled_of < threshold)\n', (5384, 5407), True, 'import numpy as np\n'), ((5747, 5775), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (5759, 5775), True, 'import matplotlib.pyplot as plt\n'), ((5790, 5821), 'mpl_toolkits.axes_grid.make_axes_locatable', 'make_axes_locatable', (['ax_scatter'], {}), '(ax_scatter)\n', (5809, 5821), False, 'from mpl_toolkits.axes_grid import make_axes_locatable\n'), ((6248, 6285), 'numpy.min', 'np.min', (['all_parameters[:, parameter1]'], {}), '(all_parameters[:, parameter1])\n', (6254, 6285), True, 'import numpy as np\n'), ((6297, 6334), 'numpy.max', 'np.max', (['all_parameters[:, parameter1]'], {}), '(all_parameters[:, parameter1])\n', (6303, 6334), True, 'import numpy as np\n'), ((6346, 6383), 'numpy.min', 'np.min', (['all_parameters[:, parameter2]'], {}), '(all_parameters[:, parameter2])\n', (6352, 6383), True, 'import numpy as np\n'), ((6395, 6432), 'numpy.max', 'np.max', (['all_parameters[:, parameter2]'], {}), '(all_parameters[:, parameter2])\n', (6401, 6432), True, 'import numpy as np\n'), ((6732, 6773), 'numpy.arange', 'np.arange', (['(-lim)', '(lim + binwidth)', 'binwidth'], {}), '(-lim, lim + binwidth, binwidth)\n', (6741, 6773), True, 'import numpy as np\n'), ((7268, 7303), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'nbins': '(5)', 'prune': '"""lower"""'}), "(nbins=5, prune='lower')\n", (7279, 7303), False, 'from matplotlib.ticker import MaxNLocator, LinearLocator, NullLocator\n'), ((7368, 7388), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'nbins': '(5)'}), '(nbins=5)\n', (7379, 7388), False, 'from matplotlib.ticker import MaxNLocator, LinearLocator, NullLocator\n'), ((3851, 3924), 'numpy.vstack', 'np.vstack', (['(all_parameters[:, parameter1], all_parameters[:, parameter2])'], {}), '((all_parameters[:, parameter1], all_parameters[:, parameter2]))\n', (3860, 3924), True, 'import numpy as np\n'), ((4767, 4791), 'numpy.atleast_2d', 'np.atleast_2d', (['scaled_of'], {}), '(scaled_of)\n', (4780, 4791), True, 'import numpy as np\n'), ((6620, 6643), 'numpy.max', 'np.max', (['behav_par[:, 0]'], {}), '(behav_par[:, 0])\n', (6626, 6643), True, 'import numpy as np\n'), ((6644, 6667), 'numpy.max', 'np.max', (['behav_par[:, 1]'], {}), '(behav_par[:, 1])\n', (6650, 6667), True, 'import numpy as np\n')]
import os import numpy as np import pylab as pl dat = np.loadtxt(os.environ['DESIMODEL'] + '/focalplane/platescale.txt') wdat = dat[:,0] ## Assume MPS == SPS pscale = dat[:,6] ## Find radius where DESI ratio to centre is 10%. index = np.where(np.abs(pscale / pscale[0] - 1.1).min() == np.abs(pscale / pscale[0] - 1.1)) ## Normalise to platescale to 90.9 at origin. pscale *= 90.9 / pscale[0] wdat *= 224. / wdat[index] print(pscale[index] / pscale[0]) ## Assume radial and azimuthal platescale are the same. output = np.c_[wdat[wdat <= 225.], pscale[wdat <= 225.], pscale[wdat <= 225.]] np.savetxt(os.environ['AUX'] + '/platescale-pfs.txt', output, header='# Radius [mm], Radial platescale [um/arcsec], Azimuthal platescale [um/arcsec]', fmt='%.6lf') pl.plot(wdat[wdat <= 225.], pscale[wdat <= 225.]) pl.xlabel(r'$Radius \ [mm]$') pl.ylabel(r'Plate scale $[\mu \rm{m/arcsec}]$') pl.savefig(os.environ['AUX'] + '/plots/platescale.pdf')
[ "numpy.abs", "pylab.plot", "pylab.savefig", "pylab.xlabel", "numpy.savetxt", "numpy.loadtxt", "pylab.ylabel" ]
[((61, 127), 'numpy.loadtxt', 'np.loadtxt', (["(os.environ['DESIMODEL'] + '/focalplane/platescale.txt')"], {}), "(os.environ['DESIMODEL'] + '/focalplane/platescale.txt')\n", (71, 127), True, 'import numpy as np\n'), ((613, 786), 'numpy.savetxt', 'np.savetxt', (["(os.environ['AUX'] + '/platescale-pfs.txt')", 'output'], {'header': '"""# Radius [mm], Radial platescale [um/arcsec], Azimuthal platescale [um/arcsec]"""', 'fmt': '"""%.6lf"""'}), "(os.environ['AUX'] + '/platescale-pfs.txt', output, header=\n '# Radius [mm], Radial platescale [um/arcsec], Azimuthal platescale [um/arcsec]'\n , fmt='%.6lf')\n", (623, 786), True, 'import numpy as np\n'), ((778, 829), 'pylab.plot', 'pl.plot', (['wdat[wdat <= 225.0]', 'pscale[wdat <= 225.0]'], {}), '(wdat[wdat <= 225.0], pscale[wdat <= 225.0])\n', (785, 829), True, 'import pylab as pl\n'), ((828, 857), 'pylab.xlabel', 'pl.xlabel', (['"""$Radius \\\\ [mm]$"""'], {}), "('$Radius \\\\ [mm]$')\n", (837, 857), True, 'import pylab as pl\n'), ((858, 906), 'pylab.ylabel', 'pl.ylabel', (['"""Plate scale $[\\\\mu \\\\rm{m/arcsec}]$"""'], {}), "('Plate scale $[\\\\mu \\\\rm{m/arcsec}]$')\n", (867, 906), True, 'import pylab as pl\n'), ((906, 961), 'pylab.savefig', 'pl.savefig', (["(os.environ['AUX'] + '/plots/platescale.pdf')"], {}), "(os.environ['AUX'] + '/plots/platescale.pdf')\n", (916, 961), True, 'import pylab as pl\n'), ((302, 334), 'numpy.abs', 'np.abs', (['(pscale / pscale[0] - 1.1)'], {}), '(pscale / pscale[0] - 1.1)\n', (308, 334), True, 'import numpy as np\n'), ((260, 292), 'numpy.abs', 'np.abs', (['(pscale / pscale[0] - 1.1)'], {}), '(pscale / pscale[0] - 1.1)\n', (266, 292), True, 'import numpy as np\n')]
import pygame from pygame.locals import * import time import random import numpy as np import player import food class Agaria: def __init__(self, rendering = True): self.agents: [player.Player] = [] self.foods: [food.Food] = [] self.player_lastID = 0 self.rendering = rendering self.start_time = time.time() self.screen_size = (800,600) self.background_color = (255,255,200) self.is_running = True self.RAM = np.zeros(128, dtype=np.uint32) if self.rendering: pygame.init() self.screen = pygame.display.set_mode(self.screen_size, pygame.DOUBLEBUF | pygame.RESIZABLE) pygame.display.set_caption("Agar.IA") self.setup() def setup(self): agent = self.newPlayer() agent.updateRAM() pass # def loop(self): # while self.is_running: # self.update() # self.updateRAM() # if self.rendering: # self.render() # pass def update(self): for a in self.agents: a.updateRAM() def updateRAM(self): pass def render(self): for e in pygame.event.get(): if e.type == pygame.VIDEORESIZE: self.screen_size = self.screen.get_size() if e.type == pygame.QUIT: self.quit() if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE: self.quit() if self.is_running: self.screen.fill(self.background_color) # game logic for a in self.agents: pygame.draw.circle(self.screen, a.getColor(), a.getPosition(), a.getSize()) for f in self.foods: pygame.draw.circle(self.screen, f.color, f.position, f.size) pygame.display.flip() else: raise RuntimeError("Render was called while self.is_running == False") def quit(self): self.is_running = False print("Game ended after %s seconds." % int(time.time() - self.start_time)) pygame.quit() quit(0) def getRAM(self) -> np.ndarray: return self.RAM def newPlayer(self): p = player.Player(self) self.agents.append(p) return p def newFood(self): f = food.Food(position=(50,50)) self.foods.append(f) return f def getPlayerRAM(self, p): # update the ram ? probably not return p.getRAM() # ---- IA SPECIFIC BELOW ---- def observation(self, player): pass def reward(self, player): pass def done(self, player): pass def info(self, player): pass def new_player(self): pass
[ "pygame.draw.circle", "pygame.quit", "food.Food", "player.Player", "pygame.event.get", "pygame.init", "pygame.display.set_mode", "pygame.display.flip", "numpy.zeros", "pygame.display.set_caption", "time.time" ]
[((342, 353), 'time.time', 'time.time', ([], {}), '()\n', (351, 353), False, 'import time\n'), ((487, 517), 'numpy.zeros', 'np.zeros', (['(128)'], {'dtype': 'np.uint32'}), '(128, dtype=np.uint32)\n', (495, 517), True, 'import numpy as np\n'), ((1193, 1211), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (1209, 1211), False, 'import pygame\n'), ((2097, 2110), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (2108, 2110), False, 'import pygame\n'), ((2226, 2245), 'player.Player', 'player.Player', (['self'], {}), '(self)\n', (2239, 2245), False, 'import player\n'), ((2329, 2357), 'food.Food', 'food.Food', ([], {'position': '(50, 50)'}), '(position=(50, 50))\n', (2338, 2357), False, 'import food\n'), ((558, 571), 'pygame.init', 'pygame.init', ([], {}), '()\n', (569, 571), False, 'import pygame\n'), ((598, 676), 'pygame.display.set_mode', 'pygame.display.set_mode', (['self.screen_size', '(pygame.DOUBLEBUF | pygame.RESIZABLE)'], {}), '(self.screen_size, pygame.DOUBLEBUF | pygame.RESIZABLE)\n', (621, 676), False, 'import pygame\n'), ((689, 726), 'pygame.display.set_caption', 'pygame.display.set_caption', (['"""Agar.IA"""'], {}), "('Agar.IA')\n", (715, 726), False, 'import pygame\n'), ((1834, 1855), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (1853, 1855), False, 'import pygame\n'), ((1761, 1821), 'pygame.draw.circle', 'pygame.draw.circle', (['self.screen', 'f.color', 'f.position', 'f.size'], {}), '(self.screen, f.color, f.position, f.size)\n', (1779, 1821), False, 'import pygame\n'), ((2057, 2068), 'time.time', 'time.time', ([], {}), '()\n', (2066, 2068), False, 'import time\n')]
import cv2 import numpy as np from matplotlib.pyplot import plt from .colors import label_color from .visualization import draw_box, draw_caption, draw_boxes, draw_detections, draw_annotations from keras_retinanet import models from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image from keras_retinanet.utils.visualization import draw_box, draw_caption from keras_retinanet.utils.colors import label_color from keras_retinanet.bin import evaluate THRES_SCORE = 0.9 def predict(image, model): image = preprocess_image(image.copy()) image, scale = resize_image(image) boxes, scores, labels = model.predict_on_batch( np.expand_dims(image, axis=0) ) boxes /= scale return boxes, scores, labels def draw_detections(image, boxes, scores, labels, labels_to_names): for box, score, label in zip(boxes[0], scores[0], labels[0]): if score < THRES_SCORE: break color = label_color(label) b = box.astype(int) draw_box(image, b, color=color) caption = "{} {:.3f}".format(labels_to_names[label], score) draw_caption(image, b, caption) def show_detected_objects(img_path, model, labels_to_names): # img_path = '/content/drive/My Drive/person_detection/WiderPerson/bus_showcase.jpg' image = read_image_bgr(img_path) boxes, scores, labels = predict(image, model) for i, score in enumerate(scores[0]): if score > THRES_SCORE: print('row ', img_path, 'score ', scores[0, i]) if all(i < THRES_SCORE for i in scores[0]): print('no detections') return draw = image.copy() draw = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB) draw_detections(draw, boxes, scores, labels, labels_to_names) plt.axis('off') plt.imshow(draw) plt.show()
[ "keras_retinanet.utils.image.resize_image", "keras_retinanet.utils.image.read_image_bgr", "keras_retinanet.utils.visualization.draw_caption", "keras_retinanet.utils.colors.label_color", "cv2.cvtColor", "matplotlib.pyplot.plt.imshow", "numpy.expand_dims", "matplotlib.pyplot.plt.show", "matplotlib.pyp...
[((588, 607), 'keras_retinanet.utils.image.resize_image', 'resize_image', (['image'], {}), '(image)\n', (600, 607), False, 'from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image\n'), ((1310, 1334), 'keras_retinanet.utils.image.read_image_bgr', 'read_image_bgr', (['img_path'], {}), '(img_path)\n', (1324, 1334), False, 'from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image\n'), ((1655, 1692), 'cv2.cvtColor', 'cv2.cvtColor', (['draw', 'cv2.COLOR_BGR2RGB'], {}), '(draw, cv2.COLOR_BGR2RGB)\n', (1667, 1692), False, 'import cv2\n'), ((1769, 1784), 'matplotlib.pyplot.plt.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1777, 1784), False, 'from matplotlib.pyplot import plt\n'), ((1789, 1805), 'matplotlib.pyplot.plt.imshow', 'plt.imshow', (['draw'], {}), '(draw)\n', (1799, 1805), False, 'from matplotlib.pyplot import plt\n'), ((1810, 1820), 'matplotlib.pyplot.plt.show', 'plt.show', ([], {}), '()\n', (1818, 1820), False, 'from matplotlib.pyplot import plt\n'), ((663, 692), 'numpy.expand_dims', 'np.expand_dims', (['image'], {'axis': '(0)'}), '(image, axis=0)\n', (677, 692), True, 'import numpy as np\n'), ((950, 968), 'keras_retinanet.utils.colors.label_color', 'label_color', (['label'], {}), '(label)\n', (961, 968), False, 'from keras_retinanet.utils.colors import label_color\n'), ((1006, 1037), 'keras_retinanet.utils.visualization.draw_box', 'draw_box', (['image', 'b'], {'color': 'color'}), '(image, b, color=color)\n', (1014, 1037), False, 'from keras_retinanet.utils.visualization import draw_box, draw_caption\n'), ((1115, 1146), 'keras_retinanet.utils.visualization.draw_caption', 'draw_caption', (['image', 'b', 'caption'], {}), '(image, b, caption)\n', (1127, 1146), False, 'from keras_retinanet.utils.visualization import draw_box, draw_caption\n')]
from robot.trajectory import quintic_trajectory_planning from tools.visualize import plot_joint_trajectory import numpy as np if __name__ == "__main__": q0 = np.array([-2, -1, 0, 1, 2, 3]) qd0 = np.array([0, 0, 0, 0, 0, 0]) qdd0 = np.array([0, 0, 0, 0, 0, 0]) qf = np.array([4, -3, -2, 0, 4, -2]) qdf = np.array([0, 0, 0, 0, 0, 0]) qddf = np.array([0, 0, 0, 0, 0, 0]) q, qd, qdd = quintic_trajectory_planning(q0, qf, qd0, qdf, qdd0, qddf) plot_joint_trajectory(q, qd, qdd)
[ "numpy.array", "tools.visualize.plot_joint_trajectory", "robot.trajectory.quintic_trajectory_planning" ]
[((163, 193), 'numpy.array', 'np.array', (['[-2, -1, 0, 1, 2, 3]'], {}), '([-2, -1, 0, 1, 2, 3])\n', (171, 193), True, 'import numpy as np\n'), ((204, 232), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 0]'], {}), '([0, 0, 0, 0, 0, 0])\n', (212, 232), True, 'import numpy as np\n'), ((244, 272), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 0]'], {}), '([0, 0, 0, 0, 0, 0])\n', (252, 272), True, 'import numpy as np\n'), ((282, 313), 'numpy.array', 'np.array', (['[4, -3, -2, 0, 4, -2]'], {}), '([4, -3, -2, 0, 4, -2])\n', (290, 313), True, 'import numpy as np\n'), ((324, 352), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 0]'], {}), '([0, 0, 0, 0, 0, 0])\n', (332, 352), True, 'import numpy as np\n'), ((364, 392), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 0]'], {}), '([0, 0, 0, 0, 0, 0])\n', (372, 392), True, 'import numpy as np\n'), ((411, 468), 'robot.trajectory.quintic_trajectory_planning', 'quintic_trajectory_planning', (['q0', 'qf', 'qd0', 'qdf', 'qdd0', 'qddf'], {}), '(q0, qf, qd0, qdf, qdd0, qddf)\n', (438, 468), False, 'from robot.trajectory import quintic_trajectory_planning\n'), ((473, 506), 'tools.visualize.plot_joint_trajectory', 'plot_joint_trajectory', (['q', 'qd', 'qdd'], {}), '(q, qd, qdd)\n', (494, 506), False, 'from tools.visualize import plot_joint_trajectory\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ psyclab/muscle/brown.py <NAME> 2019 """ import numpy as np class BrownMuscleModel: """ Muscle model based off the work of Cheng, Brown et al. [1] <NAME>., <NAME>., & <NAME>. (2000). Virtual muscle: a computational approach to understanding the effects of muscle properties on motor control. Journal of Neuroscience Methods. [2] """ def __init__(self, muscle_length=1.0, pcsa=1.0, limits=(0.6, 1.1)): """ :param muscle_length: :param pcsa: Phsyiological cross section area :param limits: """ self.resting_length = muscle_length self.length = 1.0 self.limits = tuple(limits) self.velocity = 0.0 self.activation = 0.0 self.limits = limits self.pcsa = pcsa def step(self, new_length=None, neural_input=0.0, time_step=0.001): """ Step the dynamical simulation of the muscle model forward :param new_length: :param neural_input: :param time_step: :return: """ if new_length is not None: self.step_length(new_length, time_step=time_step) self.step_activation(neural_input, time_step=time_step) def step_length(self, muscle_length, time_step=0.001): """ Update the length of the muscle and the velocity of its change :param muscle_length: :param time_step: :return: """ length = np.min((np.max((muscle_length / self.resting_length, self.limits[0])), self.limits[1])) velocity = ((length * self.resting_length) - self.length) / time_step self.length, self.velocity = length, velocity def step_activation(self, neural_input, time_step=0.001, tau_activation=50, tau_deactivation=66): """ Step forward the dynamical simulation of the neural input to the muscle :param neural_input: :param time_step: :param tau_activation: :param tau_deactivation: :return: """ if neural_input > self.activation: tau = tau_deactivation + neural_input * (tau_activation - tau_deactivation) else: tau = tau_deactivation self.activation += ((neural_input - self.activation) / (tau / 1000.0)) * time_step @property def T(self): """ Muscle tension """ return 31.8 * self.pcsa * self.tension(self.A, self.l, self.v) @property def l(self): """ Normalized muscle length """ return self.length @property def v(self): return self.velocity @property def a(self): """ Descending neural activation level """ return self.activation @property def A(self): """ Activity level at neuro-muscular junction """ return self.activity(self.a, self.l) @staticmethod def tension(activity, length, velocity): return (activity * (BrownMuscleModel.force_length(length) * BrownMuscleModel.force_velocity(length, velocity)) + BrownMuscleModel.force_passive(length)) @staticmethod def activity(activation, length): """ Activity level as a function of muscle length and activation """ nf = 2.11 + 4.16 * (1.0 / length - 1.0) return 1.0 - np.exp(-np.power(activation / (0.56 * nf), nf)) @staticmethod def force_length(length): """ Force - length scaling factor """ return np.exp(-np.power(np.abs((np.power(length, 1.93) - 1) / 1.03), 1.87)) @staticmethod def force_velocity(length, velocity): """ Force - velocity scaling factor """ if velocity <= 0.0: return (-5.72 - velocity) / (-5.72 + (1.38 + 2.09 * length) * velocity) return (0.62 - (-3.12 + 4.21 * length - 2.67 * (length ** 2)) * velocity) / (0.62 + velocity) @staticmethod def force_passive(length): """ Passive force generated by muscle fibers and tendons """ return -0.02 * (np.exp(13.8 - 18.7 * length) - 1)
[ "numpy.exp", "numpy.power", "numpy.max" ]
[((1520, 1581), 'numpy.max', 'np.max', (['(muscle_length / self.resting_length, self.limits[0])'], {}), '((muscle_length / self.resting_length, self.limits[0]))\n', (1526, 1581), True, 'import numpy as np\n'), ((4033, 4061), 'numpy.exp', 'np.exp', (['(13.8 - 18.7 * length)'], {}), '(13.8 - 18.7 * length)\n', (4039, 4061), True, 'import numpy as np\n'), ((3346, 3384), 'numpy.power', 'np.power', (['(activation / (0.56 * nf))', 'nf'], {}), '(activation / (0.56 * nf), nf)\n', (3354, 3384), True, 'import numpy as np\n'), ((3521, 3543), 'numpy.power', 'np.power', (['length', '(1.93)'], {}), '(length, 1.93)\n', (3529, 3543), True, 'import numpy as np\n')]
import numpy as np import os from matplotlib import ticker, gridspec, style from matplotlib import pyplot as plt import pandas import xlsxwriter from scipy.interpolate import CubicSpline from scipy.signal import butter, freqz, savgol_filter import time import pytta from tmm import _h5utils as h5utils from tmm.database.path import path as database_path outputs = os.getcwd() + os.sep style.use("seaborn-colorblind") class MaterialModel: """ Models for different surfaces in the GRAS database published in the supplemental data of "A framework for auralization of boundary element method simulations including source and receiver directivity" by <NAME>, <NAME>, and <NAME>. GRAS database: https://depositonce.tu-berlin.de//handle/11303/7506 Supplemental data: https://asa.scitation.org/doi/suppl/10.1121/1.5096171 Available materials: ------------------- - Floor - Ceiling - Door - Concrete - Plaster - MDF - Windows """ def __init__(self, fmin=20, fmax=5000, df=0.5, rho0=1.21, c0=343, project_folder=None): self.fmin = fmin self.fmax = fmax self.df = df # Frequency resolution self.freq = np.linspace(self.fmin, self.fmax, int( (self.fmax - self.fmin) / self.df) + 1) # Frequency vector self.rho0 = rho0 # Air density [kg/m³] self.c0 = c0 # Speed of sound [m/s] self.z = np.zeros_like(self.freq, dtype="complex") # Complex impedance self.s = None # Scattering coefficient (if available) self.database = database_path() # Folder path containing the GRAS db self.project_folder = project_folder @property def z0(self): return 1 # return self.rho0 * self.c0 @property def alpha(self): R, alpha = self.reflection_and_absorption_coefficient(self.z) return alpha.reshape((len(alpha),)) @property def y(self): return 1 / self.z def reflection_and_absorption_coefficient(self, zs): """ Calculate reflection coefficient and absorption coefficient for a given surface impedance. Parameters ---------- zs : array Surface impedance. Returns ------- R : array Reflection coefficient. alpha : array Absorption coefficient. """ R = (zs - self.z0) / (zs + self.z0) alpha = 1 - np.abs(R) ** 2 return R, alpha def floor(self) -> None: """ This is a model of the floor material defined in Scene 9 of the GRAS database. It is a purely real (resistive) admittance found from the measured absorption coefficient data using a spline fit. """ __csv_db_str = self.__format_csv_str("mat_scene09_floor") self._load_GRAS_csv(__csv_db_str) return None def ceiling(self) -> None: """ This is a model of the ceiling material defined in Scene 9 of the GRAS database. It is a purely real (resistive) admittance found from the measured absorption coefficient data using a spline fit. """ __csv_db_str = self.__format_csv_str("mat_scene09_ceiling") self._load_GRAS_csv(__csv_db_str) return None def concrete(self) -> None: """ This is a model of the concrete material defined in Scene 9 of the GRAS database. It is a purely real (resistive) admittance found from the measured absorption coefficient data using a spline fit. """ __csv_db_str = self.__format_csv_str("mat_scene09_concrete") self._load_GRAS_csv(__csv_db_str) return None def plaster(self) -> None: """ This is a model of the plaster material defined in Scene 9 of the GRAS database. It is a purely real (resistive) admittance found from the measured absorption coefficient data using a spline fit. """ __csv_db_str = self.__format_csv_str("mat_scene09_plaster") self._load_GRAS_csv(__csv_db_str) return None def mdf(self) -> None: """ This is a model of the MDF material defined in Scene 9 of the GRAS database. It is a purely real (resistive) admittance found from the measured absorption coefficient data using a spline fit. """ __csv_db_str = self.__format_csv_str("mat_MDF25mmA_plane_00deg") self._load_GRAS_csv(__csv_db_str) return None def __format_csv_str(self, csv_str: str) -> str: """ Common function for string formatation. """ return self.database + "_csv" + os.sep + csv_str + ".csv" def _load_GRAS_csv(self, __csv_db_str: str) -> None: """ Common function for loading CSV data from GRAS database """ # Load the random incidence absorption coefficient data included in the GRAS database: csvData = pandas.read_csv(__csv_db_str, header=None).T fMeas = csvData[0] # Third-octave band center frequencies aMeas = csvData[1] # Third-octave band center absorption coefficients sMeas = csvData[2] # Third-octave band center scattering coefficients # Convert to purely real admittance assuming material follows '55 degree rule': YsMeas = np.cos(np.deg2rad(55)) * \ (1 - np.sqrt(1 - aMeas)) / (1 + np.sqrt(1 - aMeas)) # Interpolate to specific frequency list using a spline fit: Yf = CubicSpline(fMeas, YsMeas, bc_type="natural") Sf = CubicSpline(fMeas, sMeas, bc_type="natural") YsInterp = Yf(self.freq) SsInterp = Sf(self.freq) self.z = 1 / YsInterp self.s = SsInterp return None def door(self, SampleRate=44100, CrossoverFrequency=250, rho_m=375, d=0.043, A=2.2*0.97, fRes=95, smooth=False): """ This is a model of the door material defined in Scene 9 of the GRAS database. It is entirely fabricated from other datasets, since no data was given for this component in the GRAS database. It attempts to define realistic boundary conditions in a case where insufficient data exists, and is included in this work to illustrate the sort of compromises that are often necessary, rather than to propose a specific model for these materials. The reader is asked to consider it with these caveats in mind. It comprises two approaches: 1) A purely resistive fit to octave-band summed absorption and transmission coefficient data. Both absorption and transmission coefficients were used since the former did not rise at low frequencies, indicating that the data in the dataset use was most likely measured for doors on the floor of a reverberation room, hence transmission would be zero. From the perspective of this application, tranmission is another mechanism by which energy is lost and should be included in absorption, hence the coefficients are summed. 2) A reactive Mass-Spring-Damper model of the assumed fundamental resonance of the door panel. This was included since such effects are well known to be reactive, and this affects room modal frequencies. The Mass value was chosen to be consistent with the assumed material. Stiffness and Damping values were tuned to the desired absorption peak frequency and bandwidth. This did not however produce sufficient absorption to join with the trend in 1, so an additional amount of purely resistive absorption was also added. These are combined using the non-linear crossover of Aretz el al. Parameters ---------- SampleRate : int, optional Sampling rate [Hz] CrossoverFrequency : int, optional Crossover frequency between the models [Hz] rho_m : int or float, optional Assumed bulk density [kg/m^3] d : float, optional Assumed thickness [m] A : float, optional Area [m^2] fRes : int, optional Assumed fundamental panel resonance frequency [Hz] smooth : bool, optional Boolean to choose whether apply smoothing to the curve or not. Returns ------- Nothing. """ # Model 1: purely resistive fit to octave-band absorption data: # Measured data: # Octave band centre frequencies (Hz) fMeas = [125, 250, 500, 1000, 2000, 4000, ] aMeas = np.asarray([0.14, 0.10, 0.06, 0.08, 0.1, 0.1, ]) + \ np.asarray([0.07, 0.01, 0.02, 0.03, 0.01, 0.01, ] ) # Absortion and Transmission coefficients # Convert to purely real admittance assuming material follows '55 degree rule': YsMeas = np.cos(np.deg2rad(55)) * \ (1 - np.sqrt(1 - aMeas)) / (1 + np.sqrt(1 - aMeas)) # Interpolate to specific frequency list using a spline fit: Yf = CubicSpline(fMeas, YsMeas, bc_type="natural") Ys1 = Yf(self.freq) # Model 2: reactive Mass-Spring-Damper fit to assumed fundamental panel resonance: M = rho_m * d * A # Mass term # Stiffness term - adjusted to match assumed fRes K = M * (2 * np.pi * fRes) ** 2 R = 12000 # Resistance term - adjusted to match measured coefficients zS = (-1j * 2 * np.pi * self.freq) * M + R + K / \ (-1j * 2 * np.pi * self.freq) # Surface impedance Ys2 = self.rho0 * self.c0 / zS # Specific admittance # Additional resistive component: aExtra = np.mean(aMeas[2::]) YsExtra = np.cos(np.deg2rad(55)) * \ (1 - np.sqrt(1 - aExtra)) / (1 + np.sqrt(1 - aExtra)) Ys2 = Ys2 + YsExtra # Define Butterworth filters. # Note these are applied twice to make Linkwitz-Riley: B_HP, A_HP = butter(8, CrossoverFrequency * 2 / SampleRate, "high") B_LP, A_LP = butter(8, CrossoverFrequency * 2 / SampleRate, "low") # Non-linear crossover method of Aretz et al: Ys = np.abs(Ys2 * np.conj(freqz(B_LP, A_LP, self.freq, fs=SampleRate)[1]) ** 2) + \ np.abs(Ys1 * np.conj(freqz(B_HP, A_HP, self.freq, fs=SampleRate)[1]) ** 2) # Add the magnitudes only # Multiply the phase from MSD model back in Ys = Ys * np.exp(1j * np.angle(Ys2)) if smooth: Ys_real = savgol_filter(np.real(Ys), 31, 3) Ys_imag = savgol_filter(np.imag(Ys), 31, 3) Ys = Ys_real + 1j * Ys_imag self.z = 1 / Ys def window(self, SampleRate=44100, CrossoverFrequency=200, rho_m=2500, d=0.0067, A=5.33, fRes=6.66, smooth=False): """ This is a model of the windows material defined in Scene 9 of the GRAS database. It combines two approaches: 1) A purely resistive fit to teh third-octave band absorption coefficient data provided with the GRAS dataset. 2) A reactive Mass-Spring-Damper model of the assumed fundamental resonance of the window panels. This was included since such effects are well known be reactive, and this affects room modal frequencies. It was also deemed neceessary since the fundamental resonance of the panels appeared to be lower than the bandwidth the measured dataset extended to (absorption rose quite sharply at the lowest frequencies). The Mass value was chosen to be consistent with the assumed material. Stiffness and Damping values were tuned to the desired absorption peak frequency and bandwidth. This did not however produce sufficient absorption to join with the trend in 1, so an additional amount of purely resistive absorption was also added. These are combined using the non-linear crossover of Aretz el al. Note that this script attempts to define realistic boundary conditions in a case where insufficient data exists, and is included in this work to illustrate the sort of compromises that are often necessary, rather than to propose a specific model for these materials. The reader is asked to consider it with these caveats in mind. Input data: - SampleRate = 44100 # Sample rate [Hz] - rho_m = 2500 # Assumed bulk density [kg/m^3] - d = 0.0067 # Assumed glazing thickness [m] - A = 5.33 # Area of each of the three panels [m^2] - fRes = 6.66 # Assumed fundamental panel resonance frequency [Hz] """ # Model 1: purely resistive fit to provided third-octave-band absorption data: # Load the random incidence absorption coefficient data included in the GRAS database: csvData = pandas.read_csv( self.database + "_csv" + os.sep + "mat_scene09_windows.csv", header=None).T fMeas = csvData[0] # Third-octave band center frequencies aMeas = csvData[1] # Third-octave band center absorption coefficients sMeas = csvData[2] # Third-octave band center scattering coefficients # Convert to purely real admittance assuming material follows '55 degree rule': YsMeas = np.cos(np.deg2rad(55)) * \ (1 - np.sqrt(1 - aMeas)) / (1 + np.sqrt(1 - aMeas)) # Interpolate to specific frequency list using a spline fit: Yf = CubicSpline(fMeas, YsMeas, bc_type="natural") Sf = CubicSpline(fMeas, sMeas, bc_type="natural") Ys1 = Yf(self.freq) SsInterp = Sf(self.freq) self.s = SsInterp # Model 2: reactive Mass-Spring-Damper fit to assumed fundamental panel resonance: M = rho_m * d * A # Mass term # Stiffness term - adjusted to match assumed fRes K = M * (2 * np.pi * fRes) ** 2 R = 6000 # Resistance term - adjusted to match measured coefficients zS = (-1j * 2 * np.pi * self.freq) * M + R + K / \ (-1j * 2 * np.pi * self.freq) # Surface impedance Ys2 = self.rho0 * self.c0 / zS # Specific admittance # Additional resistive component: aExtra = aMeas[8] YsExtra = np.cos(np.deg2rad(55)) * \ (1 - np.sqrt(1 - aExtra)) / (1 + np.sqrt(1 - aExtra)) Ys2 = Ys2 + YsExtra # Define Butterworth filters. # Note these are applied twice to make Linkwitz-Riley: B_HP, A_HP = butter(8, CrossoverFrequency * 2 / SampleRate, "high") B_LP, A_LP = butter(8, CrossoverFrequency * 2 / SampleRate, "low") # Non-linear crossover method of Aretz et al: Ys = np.abs(Ys2 * np.conj(freqz(B_LP, A_LP, self.freq, fs=SampleRate)[1]) ** 2) + \ np.abs(Ys1 * np.conj(freqz(B_HP, A_HP, self.freq, fs=SampleRate)[1]) ** 2) # Add the magnitudes only # Multiply the phase from MSD model back in Ys = Ys * np.exp(1j * np.angle(Ys2)) if smooth: Ys_real = savgol_filter(np.real(Ys), 31, 3) Ys_imag = savgol_filter(np.imag(Ys), 31, 3) Ys = Ys_real + 1j * Ys_imag self.z = 1 / Ys def filter_alpha(self, nthOct=1, plot=True, returnValues=False, show=False, figsize=(15, 5)): """ Filters the absorption coefficient into nthOct bands. Parameters ---------- nthOct : int, optional Fractional octave bands that the absorption will be filtered to. plot : bool, optional Boolean to display plot with filtered absorption. returnValues : bool, optional Boolean to return the bands and filetered values. show : bool, optional Boolean to display the filtered values in a table. figsize : tuple, optional Tuple containing the width and height of the figure. Returns ------- bands : ndarray An array containing the center frequencies of the available bands. result : ndarray An array containing the filtered absorption coefficient in the available bands. """ bands, result = pytta.utils.filter_values( self.freq, self.alpha, nthOct=nthOct) # Plot if plot: fig, ax1 = plt.subplots(figsize=figsize) ax1.semilogx(self.freq, self.alpha, label="Narrowband") ax2 = ax1.twiny() ax2.set_xscale("log") ax1.semilogx(bands, result, "o-", label=f"1/{nthOct} octave band") ax2.set_xticks([freq for freq in bands.tolist()]) ax2.set_xticklabels([f"{freq:0.1f}" for freq in bands.tolist()]) ax2.set_xlim(ax1.get_xlim()) ax1.set_ylabel("Absorption Coefficient [-]") ax1.set_xlabel("Narrowband Frequency [Hz]") ax2.set_xlabel(f"1/{nthOct} Octave Bands [Hz]") ax1.set_ylim([-0.1, 1.1]) ax1.legend(loc="best") # Remove scientific notation from xaxis ax1.get_xaxis().set_major_formatter(ticker.ScalarFormatter()) # Remove scientific notation from xaxis ax1.get_xaxis().set_minor_formatter(ticker.ScalarFormatter()) ax1.tick_params(which="minor", length=5, rotation=-90, axis="x") # Set major and minor ticks to same length ax1.tick_params(which="major", length=5, rotation=-90, axis="x") # Set major and minor ticks to same length ax2.tick_params(which="major", length=5, rotation=-90, axis="x") # Set major and minor ticks to same length ax1.minorticks_on() # Set major and minor ticks to same length ax2.minorticks_off() ax1.grid("minor") plt.show() if show: pandas.set_option("display.precision", 2) freq_bands = [] absorption = [] absorption_percentual = [] # for key, value in available_data.items(): for i in range(len(bands)): freq_bands.append(float(f"{bands[i]:0.2f}")) absorption.append(float(f"{result[i]:0.2f}")) absorption_percentual.append(float(f"{result[i] * 100:0.0f}")) data = {"Bands [Hz]": freq_bands, "Absorption [-]": absorption, "Absorption [%]": absorption_percentual} df = pandas.DataFrame(data=data).set_index("Bands [Hz]").T df = df.style.set_caption(f"1/{nthOct} Octave Absorption Data") try: from IPython.display import display display(df) except: print("IPython.diplay unavailable.") if returnValues: return bands, result def save2sheet(self, filename="MaterialModel", timestamp=True, ext=".xlsx", chart_styles=[35, 36], nthOct=3): timestr = time.strftime("%Y%m%d-%H%M_") if self.project_folder is None: full_path = outputs + filename + ext if timestamp is True: full_path = outputs + timestr + filename + ext else: folderCheck = os.path.exists( self.project_folder + os.sep + "Treatments") if folderCheck is False: os.mkdir(self.project_folder + os.sep + "Treatments") full_path = self.project_folder + os.sep + \ "Treatments" + os.sep + filename + ext if timestamp is True: full_path = self.project_folder + os.sep + \ "Treatments" + os.sep + timestr + filename + ext if ext == ".xlsx": workbook = xlsxwriter.Workbook(full_path) worksheet = workbook.add_worksheet() # Setting formats bold = workbook.add_format( {"bold": True, "font_color": "black", "align": "center", "border": 2}) regular = workbook.add_format( {"bold": False, "font_color": "black", "align": "center", "border": 1}) # Adding frequency related data worksheet.write(0, 0, "Frequency", bold) worksheet.write(0, 1, "Real Z", bold) worksheet.write(0, 2, "Img Z", bold) worksheet.write(0, 3, "Absorption", bold) for i in range(len(self.freq)): worksheet.write(1 + i, 0, self.freq[i], regular) worksheet.write(1 + i, 1, np.real(self.z[i]), regular) worksheet.write(1 + i, 2, np.imag(self.z[i]), regular) worksheet.write(1 + i, 3, self.alpha[i], regular) # Absorption coefficient plot chart_abs = workbook.add_chart({"type": "line"}) chart_abs.add_series({"name": ["Sheet1", 0, 3], "categories": ["Sheet1", 1, 0, len(self.freq) + 1, 0], "values": ["Sheet1", 1, 3, len(self.freq) + 1, 3], }) chart_abs.set_title({"name": "Absorption Coefficient"}) chart_abs.set_x_axis({"name": "Frequency [Hz]"}) chart_abs.set_y_axis({"name": "Alpha [-]"}) chart_abs.set_style(chart_styles[0]) worksheet.insert_chart("G17", chart_abs, {"x_offset": 0, "y_offset": 0, "x_scale": 1.334, "y_scale": 1.11}) # Impedance plot chart_z = workbook.add_chart({"type": "line"}) chart_z.add_series({"name": ["Sheet1", 0, 1], "categories": ["Sheet1", 1, 0, len(self.freq) + 1, 0], "values": ["Sheet1", 1, 1, len(self.freq) + 1, 1], }) chart_z.add_series({"name": ["Sheet1", 0, 2], "categories": ["Sheet1", 1, 0, len(self.freq) + 1, 0], "values": ["Sheet1", 1, 2, len(self.freq) + 1, 2], }) chart_z.set_title({"name": "Normalized Surface Impedance"}) chart_z.set_x_axis({"name": "Frequency [Hz]"}) chart_z.set_y_axis({"name": "Z [Pa*s/m]"}) chart_z.set_style(chart_styles[1]) worksheet.insert_chart("G17", chart_z, {"x_offset": 0, "y_offset": 0, "x_scale": 1.334, "y_scale": 1.11}) # Adding nthOct band absorption coeffiecients line = 0 idx = 4 __nthOct_str = f"1/{nthOct} octave band absorption coefficients" worksheet.merge_range( line, idx, line, idx + 1, __nthOct_str, bold) line += 1 worksheet.write(line, idx, "Frequency Band [Hz]", bold) worksheet.write(line, idx + 1, "Absorption Coeffiecient [-]", bold) line += 1 xOct, yOct = self.filter_alpha( nthOct=nthOct, plot=False, returnValues=True) for x, y in zip(xOct, yOct): worksheet.write(line, idx, x, regular) worksheet.write(line, idx + 1, y, regular) line += 1 # Setting column widths worksheet.set_column("A:D", 12) worksheet.set_column("E:F", 28) workbook.close() elif ext == ".csv": df1 = pandas.DataFrame() df1["Frequency"] = self.freq df1["Real Z"] = np.real(self.z) df1["Imag Z"] = np.imag(self.z) df1["Absorption"] = self.alpha df2 = pandas.DataFrame() __nthOct_str = f"1/{nthOct} octave band absorption coefficients" df2["Bands"], df2[__nthOct_str] = self.filter_alpha(nthOct=nthOct, returnValues=True, plot=False) df3 = pandas.concat([df1, df2], axis=1) df3.to_csv(full_path, index=False, float_format="%.3f", sep=";") else: raise NameError( "Unidentified extension. Available extensions: ['.xlsx', '.csv']") print("Sheet saved to ", full_path) def save(self, filename="mm"): """ Saves TMM into HDF5 file. Parameters ---------- filename : string Output filename. Returns ------- Nothing. """ if self.project_folder: h5utils.save_class_to_hdf5( self, filename=filename, folder=self.project_folder) print("HDF5 file saved at " + self.project_folder + filename + ".h5") else: h5utils.save_class_to_hdf5(self, filename=filename, folder=outputs) print("HDF5 file saved at " + filename + ".h5") def load(self, filename): """ Loads TMM data from HDF5 file. Parameters ---------- filename : string Input filename. Returns ------- Nothing. """ if self.project_folder: h5utils.load_class_from_hdf5( self, filename, folder=self.project_folder) print(self.project_folder + filename + ".h5 loaded successfully.") else: h5utils.load_class_from_hdf5(self, filename) print(filename + ".h5 loaded successfully.") def plot(self, figsize=(15, 5), plots=["z", "y", "alpha"], saveFig=False, filename="TMM", timestamp=True, ext=".png"): # sourcery no-metrics """ Plots impedance, admittance and absorption curves. Parameters ---------- figsize : tuple, optional Tuple containing the width and height of the figure. plots : list of strings, optional Desired curves to be plotted. 'z' for impedance, 'y' for admittance and 'alpha' for absorption. saveFig : bool, optional Option to save the plot as an image. filename : strint, optional Name to be added in the filename: timestamp : bool, optional Boolean to add timestamping to the filename. ext : string, optional Desired file extension. max_mode : None, int or string Variable to set a maximum limit to peak detection in the absorption coefficient. 'all' for no limit, None for no detection or int for maximum detection frequency. Returns ------- Nothing. """ fig = plt.figure(figsize=figsize) gs = gridspec.GridSpec(1, len(plots)) i = 0 if "z" in plots or "Z" in plots: ax_z = plt.subplot(gs[0, i]) ax_z.set_title(r"Impedance ($Z$)") ax_z.set_xlabel("Frequency [Hz]") ax_z.set_ylabel("Normalized Surface Impedance [Z/Z0]") ax_z.semilogx(self.freq, np.real(self.z), linewidth=2, label="Real") ax_z.semilogx(self.freq, np.imag(self.z), linewidth=2, label="Real") ax_z.set_xlim([(np.min(self.freq)), (np.max(self.freq))]) ax_z.axhline(y=0, color="k", linewidth=0.5) ax_z.axhline(y=1, linestyle="--", color="gray") ax_z.legend(loc="best") # Remove scientific notation from xaxis ax_z.get_xaxis().set_major_formatter(ticker.ScalarFormatter()) # Remove scientific notation from xaxis ax_z.get_xaxis().set_minor_formatter(ticker.ScalarFormatter()) ax_z.tick_params(which="minor", length=5, rotation=-90, axis="x") # Set major and minor ticks to same length ax_z.tick_params(which="major", length=5, rotation=-90, axis="x") # Set major and minor ticks to same length ax_z.minorticks_on() # Set major and minor ticks to same length ax_z.grid("minor") i += 1 if "y" in plots or "Y" in plots: ax_y = plt.subplot(gs[0, i]) ax_y.set_title(r"Admittance ($Y$)") ax_y.set_xlabel("Frequency [Hz]") ax_y.set_ylabel("Normalized Surface Admittance [Z0/Z]") ax_y.semilogx(self.freq, np.real(self.y), linewidth=2, label="Real") ax_y.semilogx(self.freq, np.imag(self.y), linewidth=2, label="Imag") ax_y.set_xlim([(np.min(self.freq)), (np.max(self.freq))]) ax_y.legend(loc="best") # Remove scientific notation from xaxis ax_y.get_xaxis().set_major_formatter(ticker.ScalarFormatter()) # Remove scientific notation from xaxis ax_y.get_xaxis().set_minor_formatter(ticker.ScalarFormatter()) ax_y.tick_params(which="minor", length=5, rotation=-90, axis="x") # Set major and minor ticks to same length ax_y.tick_params(which="major", length=5, rotation=-90, axis="x") # Set major and minor ticks to same length ax_y.minorticks_on() # Set major and minor ticks to same length ax_y.grid("minor") i += 1 if "alpha" in plots or "abs" in plots or "scattering" in plots or "scat" in plots or "s" in plots: ax_a = plt.subplot(gs[0, i]) ax_a.set_xlabel("Frequency [Hz]") ax_a.set_ylabel("Coefficient [-]") alpha = False scat = False if "alpha" in plots or "abs" in plots: ax_a.semilogx(self.freq, self.alpha, linewidth=2, label="Absorption") alpha = True if self.s is not None: if "scattering" in plots or "scat" in plots or "s" in plots: ax_a.semilogx(self.freq, self.s, linewidth=2, label="Scattering") scat = True if alpha: ax_a.set_title(r"Absorption Coefficient ($\alpha$)") if scat: ax_a.set_title(r"Scattering Coefficient") if alpha and scat: ax_a.set_title( r"Absorption Coefficient & Scattering Coefficients") ax_a.set_xlim([(np.min(self.freq)), (np.max(self.freq))]) ax_a.set_ylim([-0.1, 1.1]) ax_a.legend(loc="best") ax_a.axhline(y=0, color="k", linewidth=0.5) ax_a.axhline(y=1, linestyle="--", color="gray") # Remove scientific notation from xaxis ax_a.get_xaxis().set_major_formatter(ticker.ScalarFormatter()) # Remove scientific notation from xaxis ax_a.get_xaxis().set_minor_formatter(ticker.ScalarFormatter()) ax_a.tick_params(which="minor", length=5, rotation=-90, axis="x") # Set major and minor ticks to same length ax_a.tick_params(which="major", length=5, rotation=-90, axis="x") # Set major and minor ticks to same length ax_a.minorticks_on() # Set major and minor ticks to same length ax_a.grid("minor") i += 1 gs.tight_layout(fig, pad=4, w_pad=1, h_pad=1) if saveFig: timestr = time.strftime("%Y%m%d-%H%M_") if self.project_folder is None: full_path = outputs + filename + ext if timestamp is True: full_path = outputs + timestr + filename + ext else: folderCheck = os.path.exists( self.project_folder + os.sep + "Treatments") if folderCheck is False: os.mkdir(self.project_folder + os.sep + "Treatments") full_path = self.project_folder + os.sep + \ "Treatments" + os.sep + filename + ext if timestamp is True: full_path = self.project_folder + os.sep + \ "Treatments" + os.sep + timestr + filename + ext plt.savefig(full_path, dpi=100) print("Image saved to ", full_path) plt.show()
[ "IPython.display.display", "numpy.sqrt", "pandas.read_csv", "matplotlib.style.use", "matplotlib.ticker.ScalarFormatter", "numpy.imag", "tmm._h5utils.save_class_to_hdf5", "numpy.mean", "os.path.exists", "scipy.interpolate.CubicSpline", "numpy.asarray", "tmm._h5utils.load_class_from_hdf5", "pa...
[((386, 417), 'matplotlib.style.use', 'style.use', (['"""seaborn-colorblind"""'], {}), "('seaborn-colorblind')\n", (395, 417), False, 'from matplotlib import ticker, gridspec, style\n'), ((365, 376), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (374, 376), False, 'import os\n'), ((1448, 1489), 'numpy.zeros_like', 'np.zeros_like', (['self.freq'], {'dtype': '"""complex"""'}), "(self.freq, dtype='complex')\n", (1461, 1489), True, 'import numpy as np\n'), ((1598, 1613), 'tmm.database.path.path', 'database_path', ([], {}), '()\n', (1611, 1613), True, 'from tmm.database.path import path as database_path\n'), ((5544, 5589), 'scipy.interpolate.CubicSpline', 'CubicSpline', (['fMeas', 'YsMeas'], {'bc_type': '"""natural"""'}), "(fMeas, YsMeas, bc_type='natural')\n", (5555, 5589), False, 'from scipy.interpolate import CubicSpline\n'), ((5603, 5647), 'scipy.interpolate.CubicSpline', 'CubicSpline', (['fMeas', 'sMeas'], {'bc_type': '"""natural"""'}), "(fMeas, sMeas, bc_type='natural')\n", (5614, 5647), False, 'from scipy.interpolate import CubicSpline\n'), ((9112, 9157), 'scipy.interpolate.CubicSpline', 'CubicSpline', (['fMeas', 'YsMeas'], {'bc_type': '"""natural"""'}), "(fMeas, YsMeas, bc_type='natural')\n", (9123, 9157), False, 'from scipy.interpolate import CubicSpline\n'), ((9740, 9758), 'numpy.mean', 'np.mean', (['aMeas[2:]'], {}), '(aMeas[2:])\n', (9747, 9758), True, 'import numpy as np\n'), ((10022, 10076), 'scipy.signal.butter', 'butter', (['(8)', '(CrossoverFrequency * 2 / SampleRate)', '"""high"""'], {}), "(8, CrossoverFrequency * 2 / SampleRate, 'high')\n", (10028, 10076), False, 'from scipy.signal import butter, freqz, savgol_filter\n'), ((10098, 10151), 'scipy.signal.butter', 'butter', (['(8)', '(CrossoverFrequency * 2 / SampleRate)', '"""low"""'], {}), "(8, CrossoverFrequency * 2 / SampleRate, 'low')\n", (10104, 10151), False, 'from scipy.signal import butter, freqz, savgol_filter\n'), ((13535, 13580), 'scipy.interpolate.CubicSpline', 'CubicSpline', (['fMeas', 'YsMeas'], {'bc_type': '"""natural"""'}), "(fMeas, YsMeas, bc_type='natural')\n", (13546, 13580), False, 'from scipy.interpolate import CubicSpline\n'), ((13594, 13638), 'scipy.interpolate.CubicSpline', 'CubicSpline', (['fMeas', 'sMeas'], {'bc_type': '"""natural"""'}), "(fMeas, sMeas, bc_type='natural')\n", (13605, 13638), False, 'from scipy.interpolate import CubicSpline\n'), ((14551, 14605), 'scipy.signal.butter', 'butter', (['(8)', '(CrossoverFrequency * 2 / SampleRate)', '"""high"""'], {}), "(8, CrossoverFrequency * 2 / SampleRate, 'high')\n", (14557, 14605), False, 'from scipy.signal import butter, freqz, savgol_filter\n'), ((14627, 14680), 'scipy.signal.butter', 'butter', (['(8)', '(CrossoverFrequency * 2 / SampleRate)', '"""low"""'], {}), "(8, CrossoverFrequency * 2 / SampleRate, 'low')\n", (14633, 14680), False, 'from scipy.signal import butter, freqz, savgol_filter\n'), ((16270, 16333), 'pytta.utils.filter_values', 'pytta.utils.filter_values', (['self.freq', 'self.alpha'], {'nthOct': 'nthOct'}), '(self.freq, self.alpha, nthOct=nthOct)\n', (16295, 16333), False, 'import pytta\n'), ((19075, 19104), 'time.strftime', 'time.strftime', (['"""%Y%m%d-%H%M_"""'], {}), "('%Y%m%d-%H%M_')\n", (19088, 19104), False, 'import time\n'), ((26823, 26850), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (26833, 26850), True, 'from matplotlib import pyplot as plt\n'), ((32431, 32441), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (32439, 32441), True, 'from matplotlib import pyplot as plt\n'), ((4994, 5036), 'pandas.read_csv', 'pandas.read_csv', (['__csv_db_str'], {'header': 'None'}), '(__csv_db_str, header=None)\n', (5009, 5036), False, 'import pandas\n'), ((8649, 8694), 'numpy.asarray', 'np.asarray', (['[0.14, 0.1, 0.06, 0.08, 0.1, 0.1]'], {}), '([0.14, 0.1, 0.06, 0.08, 0.1, 0.1])\n', (8659, 8694), True, 'import numpy as np\n'), ((8714, 8762), 'numpy.asarray', 'np.asarray', (['[0.07, 0.01, 0.02, 0.03, 0.01, 0.01]'], {}), '([0.07, 0.01, 0.02, 0.03, 0.01, 0.01])\n', (8724, 8762), True, 'import numpy as np\n'), ((12925, 13018), 'pandas.read_csv', 'pandas.read_csv', (["(self.database + '_csv' + os.sep + 'mat_scene09_windows.csv')"], {'header': 'None'}), "(self.database + '_csv' + os.sep + 'mat_scene09_windows.csv',\n header=None)\n", (12940, 13018), False, 'import pandas\n'), ((16403, 16432), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (16415, 16432), True, 'from matplotlib import pyplot as plt\n'), ((17920, 17930), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (17928, 17930), True, 'from matplotlib import pyplot as plt\n'), ((17961, 18002), 'pandas.set_option', 'pandas.set_option', (['"""display.precision"""', '(2)'], {}), "('display.precision', 2)\n", (17978, 18002), False, 'import pandas\n'), ((19331, 19390), 'os.path.exists', 'os.path.exists', (["(self.project_folder + os.sep + 'Treatments')"], {}), "(self.project_folder + os.sep + 'Treatments')\n", (19345, 19390), False, 'import os\n'), ((19842, 19872), 'xlsxwriter.Workbook', 'xlsxwriter.Workbook', (['full_path'], {}), '(full_path)\n', (19861, 19872), False, 'import xlsxwriter\n'), ((24743, 24822), 'tmm._h5utils.save_class_to_hdf5', 'h5utils.save_class_to_hdf5', (['self'], {'filename': 'filename', 'folder': 'self.project_folder'}), '(self, filename=filename, folder=self.project_folder)\n', (24769, 24822), True, 'from tmm import _h5utils as h5utils\n'), ((24948, 25015), 'tmm._h5utils.save_class_to_hdf5', 'h5utils.save_class_to_hdf5', (['self'], {'filename': 'filename', 'folder': 'outputs'}), '(self, filename=filename, folder=outputs)\n', (24974, 25015), True, 'from tmm import _h5utils as h5utils\n'), ((25357, 25429), 'tmm._h5utils.load_class_from_hdf5', 'h5utils.load_class_from_hdf5', (['self', 'filename'], {'folder': 'self.project_folder'}), '(self, filename, folder=self.project_folder)\n', (25385, 25429), True, 'from tmm import _h5utils as h5utils\n'), ((25552, 25596), 'tmm._h5utils.load_class_from_hdf5', 'h5utils.load_class_from_hdf5', (['self', 'filename'], {}), '(self, filename)\n', (25580, 25596), True, 'from tmm import _h5utils as h5utils\n'), ((26972, 26993), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[0, i]'], {}), '(gs[0, i])\n', (26983, 26993), True, 'from matplotlib import pyplot as plt\n'), ((28334, 28355), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[0, i]'], {}), '(gs[0, i])\n', (28345, 28355), True, 'from matplotlib import pyplot as plt\n'), ((29648, 29669), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[0, i]'], {}), '(gs[0, i])\n', (29659, 29669), True, 'from matplotlib import pyplot as plt\n'), ((31558, 31587), 'time.strftime', 'time.strftime', (['"""%Y%m%d-%H%M_"""'], {}), "('%Y%m%d-%H%M_')\n", (31571, 31587), False, 'import time\n'), ((32343, 32374), 'matplotlib.pyplot.savefig', 'plt.savefig', (['full_path'], {'dpi': '(100)'}), '(full_path, dpi=100)\n', (32354, 32374), True, 'from matplotlib import pyplot as plt\n'), ((2478, 2487), 'numpy.abs', 'np.abs', (['R'], {}), '(R)\n', (2484, 2487), True, 'import numpy as np\n'), ((5441, 5459), 'numpy.sqrt', 'np.sqrt', (['(1 - aMeas)'], {}), '(1 - aMeas)\n', (5448, 5459), True, 'import numpy as np\n'), ((9009, 9027), 'numpy.sqrt', 'np.sqrt', (['(1 - aMeas)'], {}), '(1 - aMeas)\n', (9016, 9027), True, 'import numpy as np\n'), ((9850, 9869), 'numpy.sqrt', 'np.sqrt', (['(1 - aExtra)'], {}), '(1 - aExtra)\n', (9857, 9869), True, 'import numpy as np\n'), ((10586, 10597), 'numpy.real', 'np.real', (['Ys'], {}), '(Ys)\n', (10593, 10597), True, 'import numpy as np\n'), ((10642, 10653), 'numpy.imag', 'np.imag', (['Ys'], {}), '(Ys)\n', (10649, 10653), True, 'import numpy as np\n'), ((13432, 13450), 'numpy.sqrt', 'np.sqrt', (['(1 - aMeas)'], {}), '(1 - aMeas)\n', (13439, 13450), True, 'import numpy as np\n'), ((14379, 14398), 'numpy.sqrt', 'np.sqrt', (['(1 - aExtra)'], {}), '(1 - aExtra)\n', (14386, 14398), True, 'import numpy as np\n'), ((15115, 15126), 'numpy.real', 'np.real', (['Ys'], {}), '(Ys)\n', (15122, 15126), True, 'import numpy as np\n'), ((15171, 15182), 'numpy.imag', 'np.imag', (['Ys'], {}), '(Ys)\n', (15178, 15182), True, 'import numpy as np\n'), ((17170, 17194), 'matplotlib.ticker.ScalarFormatter', 'ticker.ScalarFormatter', ([], {}), '()\n', (17192, 17194), False, 'from matplotlib import ticker, gridspec, style\n'), ((17296, 17320), 'matplotlib.ticker.ScalarFormatter', 'ticker.ScalarFormatter', ([], {}), '()\n', (17318, 17320), False, 'from matplotlib import ticker, gridspec, style\n'), ((18778, 18789), 'IPython.display.display', 'display', (['df'], {}), '(df)\n', (18785, 18789), False, 'from IPython.display import display\n'), ((19461, 19514), 'os.mkdir', 'os.mkdir', (["(self.project_folder + os.sep + 'Treatments')"], {}), "(self.project_folder + os.sep + 'Treatments')\n", (19469, 19514), False, 'import os\n'), ((23617, 23635), 'pandas.DataFrame', 'pandas.DataFrame', ([], {}), '()\n', (23633, 23635), False, 'import pandas\n'), ((23705, 23720), 'numpy.real', 'np.real', (['self.z'], {}), '(self.z)\n', (23712, 23720), True, 'import numpy as np\n'), ((23749, 23764), 'numpy.imag', 'np.imag', (['self.z'], {}), '(self.z)\n', (23756, 23764), True, 'import numpy as np\n'), ((23826, 23844), 'pandas.DataFrame', 'pandas.DataFrame', ([], {}), '()\n', (23842, 23844), False, 'import pandas\n'), ((24178, 24211), 'pandas.concat', 'pandas.concat', (['[df1, df2]'], {'axis': '(1)'}), '([df1, df2], axis=1)\n', (24191, 24211), False, 'import pandas\n'), ((27191, 27206), 'numpy.real', 'np.real', (['self.z'], {}), '(self.z)\n', (27198, 27206), True, 'import numpy as np\n'), ((27298, 27313), 'numpy.imag', 'np.imag', (['self.z'], {}), '(self.z)\n', (27305, 27313), True, 'import numpy as np\n'), ((27691, 27715), 'matplotlib.ticker.ScalarFormatter', 'ticker.ScalarFormatter', ([], {}), '()\n', (27713, 27715), False, 'from matplotlib import ticker, gridspec, style\n'), ((27818, 27842), 'matplotlib.ticker.ScalarFormatter', 'ticker.ScalarFormatter', ([], {}), '()\n', (27840, 27842), False, 'from matplotlib import ticker, gridspec, style\n'), ((28555, 28570), 'numpy.real', 'np.real', (['self.y'], {}), '(self.y)\n', (28562, 28570), True, 'import numpy as np\n'), ((28662, 28677), 'numpy.imag', 'np.imag', (['self.y'], {}), '(self.y)\n', (28669, 28677), True, 'import numpy as np\n'), ((28939, 28963), 'matplotlib.ticker.ScalarFormatter', 'ticker.ScalarFormatter', ([], {}), '()\n', (28961, 28963), False, 'from matplotlib import ticker, gridspec, style\n'), ((29066, 29090), 'matplotlib.ticker.ScalarFormatter', 'ticker.ScalarFormatter', ([], {}), '()\n', (29088, 29090), False, 'from matplotlib import ticker, gridspec, style\n'), ((30878, 30902), 'matplotlib.ticker.ScalarFormatter', 'ticker.ScalarFormatter', ([], {}), '()\n', (30900, 30902), False, 'from matplotlib import ticker, gridspec, style\n'), ((31005, 31029), 'matplotlib.ticker.ScalarFormatter', 'ticker.ScalarFormatter', ([], {}), '()\n', (31027, 31029), False, 'from matplotlib import ticker, gridspec, style\n'), ((31838, 31897), 'os.path.exists', 'os.path.exists', (["(self.project_folder + os.sep + 'Treatments')"], {}), "(self.project_folder + os.sep + 'Treatments')\n", (31852, 31897), False, 'import os\n'), ((5377, 5391), 'numpy.deg2rad', 'np.deg2rad', (['(55)'], {}), '(55)\n', (5387, 5391), True, 'import numpy as np\n'), ((5414, 5432), 'numpy.sqrt', 'np.sqrt', (['(1 - aMeas)'], {}), '(1 - aMeas)\n', (5421, 5432), True, 'import numpy as np\n'), ((8945, 8959), 'numpy.deg2rad', 'np.deg2rad', (['(55)'], {}), '(55)\n', (8955, 8959), True, 'import numpy as np\n'), ((8982, 9000), 'numpy.sqrt', 'np.sqrt', (['(1 - aMeas)'], {}), '(1 - aMeas)\n', (8989, 9000), True, 'import numpy as np\n'), ((9785, 9799), 'numpy.deg2rad', 'np.deg2rad', (['(55)'], {}), '(55)\n', (9795, 9799), True, 'import numpy as np\n'), ((9822, 9841), 'numpy.sqrt', 'np.sqrt', (['(1 - aExtra)'], {}), '(1 - aExtra)\n', (9829, 9841), True, 'import numpy as np\n'), ((10515, 10528), 'numpy.angle', 'np.angle', (['Ys2'], {}), '(Ys2)\n', (10523, 10528), True, 'import numpy as np\n'), ((13368, 13382), 'numpy.deg2rad', 'np.deg2rad', (['(55)'], {}), '(55)\n', (13378, 13382), True, 'import numpy as np\n'), ((13405, 13423), 'numpy.sqrt', 'np.sqrt', (['(1 - aMeas)'], {}), '(1 - aMeas)\n', (13412, 13423), True, 'import numpy as np\n'), ((14314, 14328), 'numpy.deg2rad', 'np.deg2rad', (['(55)'], {}), '(55)\n', (14324, 14328), True, 'import numpy as np\n'), ((14351, 14370), 'numpy.sqrt', 'np.sqrt', (['(1 - aExtra)'], {}), '(1 - aExtra)\n', (14358, 14370), True, 'import numpy as np\n'), ((15044, 15057), 'numpy.angle', 'np.angle', (['Ys2'], {}), '(Ys2)\n', (15052, 15057), True, 'import numpy as np\n'), ((20613, 20631), 'numpy.real', 'np.real', (['self.z[i]'], {}), '(self.z[i])\n', (20620, 20631), True, 'import numpy as np\n'), ((20684, 20702), 'numpy.imag', 'np.imag', (['self.z[i]'], {}), '(self.z[i])\n', (20691, 20702), True, 'import numpy as np\n'), ((27396, 27413), 'numpy.min', 'np.min', (['self.freq'], {}), '(self.freq)\n', (27402, 27413), True, 'import numpy as np\n'), ((27417, 27434), 'numpy.max', 'np.max', (['self.freq'], {}), '(self.freq)\n', (27423, 27434), True, 'import numpy as np\n'), ((28760, 28777), 'numpy.min', 'np.min', (['self.freq'], {}), '(self.freq)\n', (28766, 28777), True, 'import numpy as np\n'), ((28781, 28798), 'numpy.max', 'np.max', (['self.freq'], {}), '(self.freq)\n', (28787, 28798), True, 'import numpy as np\n'), ((30544, 30561), 'numpy.min', 'np.min', (['self.freq'], {}), '(self.freq)\n', (30550, 30561), True, 'import numpy as np\n'), ((30565, 30582), 'numpy.max', 'np.max', (['self.freq'], {}), '(self.freq)\n', (30571, 30582), True, 'import numpy as np\n'), ((31980, 32033), 'os.mkdir', 'os.mkdir', (["(self.project_folder + os.sep + 'Treatments')"], {}), "(self.project_folder + os.sep + 'Treatments')\n", (31988, 32033), False, 'import os\n'), ((18562, 18589), 'pandas.DataFrame', 'pandas.DataFrame', ([], {'data': 'data'}), '(data=data)\n', (18578, 18589), False, 'import pandas\n'), ((10241, 10284), 'scipy.signal.freqz', 'freqz', (['B_LP', 'A_LP', 'self.freq'], {'fs': 'SampleRate'}), '(B_LP, A_LP, self.freq, fs=SampleRate)\n', (10246, 10284), False, 'from scipy.signal import butter, freqz, savgol_filter\n'), ((10332, 10375), 'scipy.signal.freqz', 'freqz', (['B_HP', 'A_HP', 'self.freq'], {'fs': 'SampleRate'}), '(B_HP, A_HP, self.freq, fs=SampleRate)\n', (10337, 10375), False, 'from scipy.signal import butter, freqz, savgol_filter\n'), ((14770, 14813), 'scipy.signal.freqz', 'freqz', (['B_LP', 'A_LP', 'self.freq'], {'fs': 'SampleRate'}), '(B_LP, A_LP, self.freq, fs=SampleRate)\n', (14775, 14813), False, 'from scipy.signal import butter, freqz, savgol_filter\n'), ((14861, 14904), 'scipy.signal.freqz', 'freqz', (['B_HP', 'A_HP', 'self.freq'], {'fs': 'SampleRate'}), '(B_HP, A_HP, self.freq, fs=SampleRate)\n', (14866, 14904), False, 'from scipy.signal import butter, freqz, savgol_filter\n')]
# -*- coding: utf-8 -*- import torch from torch import nn import numpy as np import torch.nn.functional as F class TextRNNAttentionConfig: sequence_length = 100 vocab_size = 5000 # 词表大小 embedding_dim = 300 # 词向量维度 hidden_size = 128 hidden_size2 = 64 num_layers = 2 dropout = 0.5 num_classes = 10 batch_size = 32 # batch的大小 lr = 1e-3 # 学习率 num_epochs = 10 # 数据训练轮数 load_word2vec = False word2vec_path = '' require_improvement = 1000 model_save_path = './ckpts/rt_model.pth' class TextRNNAttention(nn.Module): def __init__(self, config): super(TextRNNAttention, self).__init__() if config.load_word2vec: embedding = np.load(config.word2vec_path) embedding = torch.tensor(embedding, dtype=torch.float32) self.embedding = nn.Embedding.from_pretrained(embedding, freeze=False) else: self.embedding = nn.Embedding(config.vocab_size, config.embedding_dim) self.lstm = nn.LSTM(config.embedding_dim, config.hidden_size, config.num_layers, bidirectional=True, batch_first=True, dropout=config.dropout) self.tanh1 = nn.Tanh() self.w = nn.Parameter(torch.zeros(config.hidden_size * 2)) # self.tanh2 = nn.Tanh() self.fc1 = nn.Linear(config.hidden_size * 2, config.hidden_size2) self.fc2 = nn.Linear(config.hidden_size2, config.num_classes) def forward(self, x): emb = self.embedding(x) lstmout, _ = self.lstm(emb) # attention # https://www.cnblogs.com/DjangoBlog/p/9504771.html M = self.tanh1(lstmout) alpha = F.softmax(torch.matmul(M, self.w), dim=1).unsqueeze(-1) out = lstmout * alpha out = torch.sum(out, axis=1) out = F.relu(out) out = self.fc1(out) out = self.fc2(out) return out
[ "torch.nn.Tanh", "torch.nn.LSTM", "torch.tensor", "torch.sum", "torch.matmul", "torch.nn.functional.relu", "torch.nn.Linear", "numpy.load", "torch.zeros", "torch.nn.Embedding", "torch.nn.Embedding.from_pretrained" ]
[((1071, 1205), 'torch.nn.LSTM', 'nn.LSTM', (['config.embedding_dim', 'config.hidden_size', 'config.num_layers'], {'bidirectional': '(True)', 'batch_first': '(True)', 'dropout': 'config.dropout'}), '(config.embedding_dim, config.hidden_size, config.num_layers,\n bidirectional=True, batch_first=True, dropout=config.dropout)\n', (1078, 1205), False, 'from torch import nn\n'), ((1251, 1260), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (1258, 1260), False, 'from torch import nn\n'), ((1380, 1434), 'torch.nn.Linear', 'nn.Linear', (['(config.hidden_size * 2)', 'config.hidden_size2'], {}), '(config.hidden_size * 2, config.hidden_size2)\n', (1389, 1434), False, 'from torch import nn\n'), ((1454, 1504), 'torch.nn.Linear', 'nn.Linear', (['config.hidden_size2', 'config.num_classes'], {}), '(config.hidden_size2, config.num_classes)\n', (1463, 1504), False, 'from torch import nn\n'), ((1821, 1843), 'torch.sum', 'torch.sum', (['out'], {'axis': '(1)'}), '(out, axis=1)\n', (1830, 1843), False, 'import torch\n'), ((1859, 1870), 'torch.nn.functional.relu', 'F.relu', (['out'], {}), '(out)\n', (1865, 1870), True, 'import torch.nn.functional as F\n'), ((772, 801), 'numpy.load', 'np.load', (['config.word2vec_path'], {}), '(config.word2vec_path)\n', (779, 801), True, 'import numpy as np\n'), ((826, 870), 'torch.tensor', 'torch.tensor', (['embedding'], {'dtype': 'torch.float32'}), '(embedding, dtype=torch.float32)\n', (838, 870), False, 'import torch\n'), ((900, 953), 'torch.nn.Embedding.from_pretrained', 'nn.Embedding.from_pretrained', (['embedding'], {'freeze': '(False)'}), '(embedding, freeze=False)\n', (928, 953), False, 'from torch import nn\n'), ((997, 1050), 'torch.nn.Embedding', 'nn.Embedding', (['config.vocab_size', 'config.embedding_dim'], {}), '(config.vocab_size, config.embedding_dim)\n', (1009, 1050), False, 'from torch import nn\n'), ((1291, 1326), 'torch.zeros', 'torch.zeros', (['(config.hidden_size * 2)'], {}), '(config.hidden_size * 2)\n', (1302, 1326), False, 'import torch\n'), ((1731, 1754), 'torch.matmul', 'torch.matmul', (['M', 'self.w'], {}), '(M, self.w)\n', (1743, 1754), False, 'import torch\n')]
import numpy as np def getOffAxisCorr(confFile,fldr): #print confFile c=np.loadtxt(confFile) ruler = np.sqrt(c[:,0]**2+c[:,1]**2) # print ruler, fldr, (ruler >= fldr).argmax(), (ruler >= fldr).argmin() step=ruler[1]-ruler[0] p2=(ruler >= fldr) # print "FINE",p2, p2.shape if (np.count_nonzero(p2) == 0): #fldr is too large to be in range p2=c.shape()[0] p1=p2 w1=1 w2=0 elif (p2[0]): #fldr is too small to be in range p2 = 0 #this is going to be used as index p1=0 #this is going to be used as index w1=1 w2=0 else: p1=p2.argmax() - 1; p2 = p2.argmax() w1=(ruler[p2]-fldr)/step w2=(fldr-ruler[p1])/step # print c[p1,2:], c[p2,2:], w1,p1, w2, p2 corr_coeff=np.dot(w1,c[p1,2:]) + np.dot(w2,c[p2,2:]) return corr_coeff
[ "numpy.count_nonzero", "numpy.dot", "numpy.loadtxt", "numpy.sqrt" ]
[((81, 101), 'numpy.loadtxt', 'np.loadtxt', (['confFile'], {}), '(confFile)\n', (91, 101), True, 'import numpy as np\n'), ((115, 151), 'numpy.sqrt', 'np.sqrt', (['(c[:, 0] ** 2 + c[:, 1] ** 2)'], {}), '(c[:, 0] ** 2 + c[:, 1] ** 2)\n', (122, 151), True, 'import numpy as np\n'), ((309, 329), 'numpy.count_nonzero', 'np.count_nonzero', (['p2'], {}), '(p2)\n', (325, 329), True, 'import numpy as np\n'), ((805, 826), 'numpy.dot', 'np.dot', (['w1', 'c[p1, 2:]'], {}), '(w1, c[p1, 2:])\n', (811, 826), True, 'import numpy as np\n'), ((827, 848), 'numpy.dot', 'np.dot', (['w2', 'c[p2, 2:]'], {}), '(w2, c[p2, 2:])\n', (833, 848), True, 'import numpy as np\n')]
import os import pickle import h5py import numpy as np import tensorflow as tf from scipy.io import loadmat from lymph.vgg19 import net def gen_labels(parent_folder: str): # 生成文件路径 path_1 = os.path.join(parent_folder, "allLabels1.mat") path_2 = os.path.join(parent_folder, "allLabels2.mat") out_path = os.path.join(parent_folder, "labels.pydump") # 从文件中加载matlab文件并拼接 all_labels_1 = loadmat(path_1)['allLabels'] all_labels_2 = loadmat(path_2)["allLabels"] all_labels = np.concatenate([all_labels_1, all_labels_2], axis=0) print("[DEBUG] all_labels_1: dtype={}, shape={}".format(all_labels_1.dtype, all_labels_1.shape)) print("[DEBUG] all_labels_2: dtype={}, shape={}".format(all_labels_2.dtype, all_labels_2.shape)) print("[DEBUG] all_labels: dtype={}, shape={}".format(all_labels.dtype, all_labels.shape)) del all_labels_1, all_labels_2 # 对标签进行处理 for i in range(all_labels.shape[0]): temp_list = [0, 0, 0, 0, 0, 0] if (all_labels[i][:5] == 0).all(): # 如果前面都是0,那么就是背景 temp_list[5] = 1 else: temp_list[np.argmax(all_labels[i][:5])] = 1 # 如果前面不都是0,那么就是相应的种类(只有一种) all_labels[i] = temp_list # 分析各种类别数量 _class_map = {k: "({:})".format(v) for k, v in {0: "肝", 1: "左肾", 2: "右肾", 3: "膀胱", 4: "淋巴瘤", 5: "背景"}.items()} total_num = all_labels.shape[0] all_labels_argmax = np.argmax(all_labels, axis=1) for _class in range(all_labels.shape[1]): _class_sum = (all_labels_argmax == _class).sum() print("[DEBUG] class{:1} {:4}\t\t: {:3}/{} - {:.3}%".format(_class, _class_map[_class], _class_sum, total_num, (_class_sum / total_num) * 100)) # 转换为uint8, 存盘 all_labels = all_labels.astype(np.uint8) print("[DEBUG] all_labels: dtype={}, shape={}".format(all_labels.dtype, all_labels.shape)) pickle.dump(all_labels, open(out_path, 'wb')) def gen_images(parent_folder: str): # 生成文件路径 path_1 = os.path.join(parent_folder, "allParts1.mat") path_2 = os.path.join(parent_folder, "allParts2.mat") out_path = os.path.join(parent_folder, "images.pydump") # 从文件中加载matlab文件并拼接 with h5py.File(path_1) as f: all_parts_1 = np.array(f['allParts'], dtype=np.uint8) with h5py.File(path_2) as f: all_parts_2 = np.array(f['allParts'], dtype=np.uint8) all_parts = np.concatenate([all_parts_1, all_parts_2], axis=0) all_parts = all_parts.transpose([0, 2, 1]) print("[DEBUG] all_parts_1: shape={}, dtype={}".format(all_parts_1.shape, all_parts_1.dtype)) print("[DEBUG] all_parts_2: shape={}, dtype={}".format(all_parts_2.shape, all_parts_2.dtype)) print("[DEBUG] all_parts: shape={}, dtype={}".format(all_parts.shape, all_parts.dtype)) del all_parts_1, all_parts_2 # 下一步骤就是放到vgg19-f里,生成权值 images = all_parts print("[DEBUG] images: shape={}, dtype={}".format(images.shape, images.dtype)) # 生成特征值 feature_list = [] batch_size = 20 with tf.Session() as sess: for i in range(0, images.shape[0], batch_size): batch_xs = images[i: i + batch_size] batch_xs = np.stack([batch_xs, batch_xs, batch_xs], axis=3) - mean_pixel if i % 1000 == 0: print("[DEBUG] processing {}-{}...".format(i, i + batch_xs.shape[0])) result = sess.run(nets['fc1'], feed_dict={input_images: batch_xs}) result = result.reshape(batch_xs.shape[0], 4096) feature_list.append(result) # 存盘 arr = np.concatenate(feature_list, axis=0) print("[DEBUG] arr: shape={}, dtype={}".format(arr.shape, arr.dtype)) pickle.dump(arr, open(out_path, 'wb')) if __name__ == '__main__': # 加载vgg19-f网络 net_path = r"C:\VGG_19\imagenet-vgg-verydeep-19.mat" input_images = tf.placeholder(dtype=tf.float32, shape=[None, 224, 224, 3], name="input") nets, mean_pixel, _ = net(net_path, input_images) # 主程序开始 print("-" * 30, "PT06535", '-' * 30) gen_labels(parent_folder=r"C:\LYMPH_data\mat224dataUintPT06535") gen_images(parent_folder=r"C:\LYMPH_data\mat224dataUintPT06535") print("-" * 30, "PT06548", '-' * 30) gen_labels(parent_folder=r"C:\LYMPH_data\mat224dataUintPT06548") gen_images(parent_folder=r"C:\LYMPH_data\mat224dataUintPT06548") print("-" * 30, "PT06586", '-' * 30) gen_labels(parent_folder=r"C:\LYMPH_data\mat224dataUintPT06586") gen_images(parent_folder=r"C:\LYMPH_data\mat224dataUintPT06586") print("-" * 30, "PT38875", '-' * 30) gen_labels(parent_folder=r"C:\LYMPH_data\mat224dataUintPT38875") gen_images(parent_folder=r"C:\LYMPH_data\mat224dataUintPT38875") print("-" * 30, "PT38904", '-' * 30) gen_labels(parent_folder=r"C:\LYMPH_data\mat224dataUintPT38904") gen_images(parent_folder=r"C:\LYMPH_data\mat224dataUintPT38904")
[ "tensorflow.placeholder", "scipy.io.loadmat", "os.path.join", "numpy.argmax", "tensorflow.Session", "h5py.File", "numpy.array", "numpy.stack", "lymph.vgg19.net", "numpy.concatenate" ]
[((202, 247), 'os.path.join', 'os.path.join', (['parent_folder', '"""allLabels1.mat"""'], {}), "(parent_folder, 'allLabels1.mat')\n", (214, 247), False, 'import os\n'), ((261, 306), 'os.path.join', 'os.path.join', (['parent_folder', '"""allLabels2.mat"""'], {}), "(parent_folder, 'allLabels2.mat')\n", (273, 306), False, 'import os\n'), ((322, 366), 'os.path.join', 'os.path.join', (['parent_folder', '"""labels.pydump"""'], {}), "(parent_folder, 'labels.pydump')\n", (334, 366), False, 'import os\n'), ((504, 556), 'numpy.concatenate', 'np.concatenate', (['[all_labels_1, all_labels_2]'], {'axis': '(0)'}), '([all_labels_1, all_labels_2], axis=0)\n', (518, 556), True, 'import numpy as np\n'), ((1397, 1426), 'numpy.argmax', 'np.argmax', (['all_labels'], {'axis': '(1)'}), '(all_labels, axis=1)\n', (1406, 1426), True, 'import numpy as np\n'), ((2025, 2069), 'os.path.join', 'os.path.join', (['parent_folder', '"""allParts1.mat"""'], {}), "(parent_folder, 'allParts1.mat')\n", (2037, 2069), False, 'import os\n'), ((2083, 2127), 'os.path.join', 'os.path.join', (['parent_folder', '"""allParts2.mat"""'], {}), "(parent_folder, 'allParts2.mat')\n", (2095, 2127), False, 'import os\n'), ((2143, 2187), 'os.path.join', 'os.path.join', (['parent_folder', '"""images.pydump"""'], {}), "(parent_folder, 'images.pydump')\n", (2155, 2187), False, 'import os\n'), ((2418, 2468), 'numpy.concatenate', 'np.concatenate', (['[all_parts_1, all_parts_2]'], {'axis': '(0)'}), '([all_parts_1, all_parts_2], axis=0)\n', (2432, 2468), True, 'import numpy as np\n'), ((3568, 3604), 'numpy.concatenate', 'np.concatenate', (['feature_list'], {'axis': '(0)'}), '(feature_list, axis=0)\n', (3582, 3604), True, 'import numpy as np\n'), ((3845, 3918), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None, 224, 224, 3]', 'name': '"""input"""'}), "(dtype=tf.float32, shape=[None, 224, 224, 3], name='input')\n", (3859, 3918), True, 'import tensorflow as tf\n'), ((3945, 3972), 'lymph.vgg19.net', 'net', (['net_path', 'input_images'], {}), '(net_path, input_images)\n', (3948, 3972), False, 'from lymph.vgg19 import net\n'), ((410, 425), 'scipy.io.loadmat', 'loadmat', (['path_1'], {}), '(path_1)\n', (417, 425), False, 'from scipy.io import loadmat\n'), ((458, 473), 'scipy.io.loadmat', 'loadmat', (['path_2'], {}), '(path_2)\n', (465, 473), False, 'from scipy.io import loadmat\n'), ((2221, 2238), 'h5py.File', 'h5py.File', (['path_1'], {}), '(path_1)\n', (2230, 2238), False, 'import h5py\n'), ((2267, 2306), 'numpy.array', 'np.array', (["f['allParts']"], {'dtype': 'np.uint8'}), "(f['allParts'], dtype=np.uint8)\n", (2275, 2306), True, 'import numpy as np\n'), ((2316, 2333), 'h5py.File', 'h5py.File', (['path_2'], {}), '(path_2)\n', (2325, 2333), False, 'import h5py\n'), ((2362, 2401), 'numpy.array', 'np.array', (["f['allParts']"], {'dtype': 'np.uint8'}), "(f['allParts'], dtype=np.uint8)\n", (2370, 2401), True, 'import numpy as np\n'), ((3041, 3053), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (3051, 3053), True, 'import tensorflow as tf\n'), ((1111, 1139), 'numpy.argmax', 'np.argmax', (['all_labels[i][:5]'], {}), '(all_labels[i][:5])\n', (1120, 1139), True, 'import numpy as np\n'), ((3191, 3239), 'numpy.stack', 'np.stack', (['[batch_xs, batch_xs, batch_xs]'], {'axis': '(3)'}), '([batch_xs, batch_xs, batch_xs], axis=3)\n', (3199, 3239), True, 'import numpy as np\n')]
#Linear Regression and plotting using libraries from __future__ import division import pandas as pd import numpy as np import matplotlib.pyplot as plt import math df= pd.read_csv('ex1data1.txt', header=None, names=['x','y']) print(df) x = np.array(df.x) y = np.array(df.y) theta = np.zeros((2,1)) def scatterplot(x,y, yp=None, savePng=False): plt.xlabel('Population of City in 10,000s') plt.ylabel('Profit generated') plt.scatter(x,y, marker='x') plt.show() (m,b) = np.polyfit(x,y,1) print('Slope is '+str(m)) print('Y intercept is '+ str(b)) yp= np.polyval([m,b],x) scatterplot(x,y,yp)
[ "pandas.read_csv", "numpy.polyfit", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.array", "numpy.zeros", "numpy.polyval", "matplotlib.pyplot.scatter", "matplotlib.pyplot.show" ]
[((169, 227), 'pandas.read_csv', 'pd.read_csv', (['"""ex1data1.txt"""'], {'header': 'None', 'names': "['x', 'y']"}), "('ex1data1.txt', header=None, names=['x', 'y'])\n", (180, 227), True, 'import pandas as pd\n'), ((241, 255), 'numpy.array', 'np.array', (['df.x'], {}), '(df.x)\n', (249, 255), True, 'import numpy as np\n'), ((260, 274), 'numpy.array', 'np.array', (['df.y'], {}), '(df.y)\n', (268, 274), True, 'import numpy as np\n'), ((283, 299), 'numpy.zeros', 'np.zeros', (['(2, 1)'], {}), '((2, 1))\n', (291, 299), True, 'import numpy as np\n'), ((486, 505), 'numpy.polyfit', 'np.polyfit', (['x', 'y', '(1)'], {}), '(x, y, 1)\n', (496, 505), True, 'import numpy as np\n'), ((567, 588), 'numpy.polyval', 'np.polyval', (['[m, b]', 'x'], {}), '([m, b], x)\n', (577, 588), True, 'import numpy as np\n'), ((350, 393), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Population of City in 10,000s"""'], {}), "('Population of City in 10,000s')\n", (360, 393), True, 'import matplotlib.pyplot as plt\n'), ((398, 428), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Profit generated"""'], {}), "('Profit generated')\n", (408, 428), True, 'import matplotlib.pyplot as plt\n'), ((433, 462), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'marker': '"""x"""'}), "(x, y, marker='x')\n", (444, 462), True, 'import matplotlib.pyplot as plt\n'), ((466, 476), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (474, 476), True, 'import matplotlib.pyplot as plt\n')]
import os, sys import argparse import numpy as np from ipfml import utils from keras.models import load_model from sklearn.metrics import roc_auc_score, accuracy_score ''' Display progress information as progress bar ''' def write_progress(progress): barWidth = 180 output_str = "[" pos = barWidth * progress for i in range(barWidth): if i < pos: output_str = output_str + "=" elif i == pos: output_str = output_str + ">" else: output_str = output_str + " " output_str = output_str + "] " + str(int(progress * 100.0)) + " %\r" print(output_str) sys.stdout.write("\033[F") def predict_ensemble(models, data, cluster_id, weight): """Predict label from list of models (return probability of label) Args: models ([Sequential]): models list data ([float]): input data for model cluster_id (int): cluster id of current zone (in order to target specific model) weight (int): weight of targeted cluster model """ prob_sum = 0. clusters_weight = len(models) - 1 + weight for i in range(len(models)): prob = models[i].predict(data, batch_size=1)[0][0] # if cluster id model is targeted if i == cluster_id: prob = prob * weight #print('[clusterId: {0}] Model {1} predicts => {2}'.format(cluster_id, i, prob)) prob_sum += prob return prob_sum / clusters_weight def main(): parser = argparse.ArgumentParser(description="Compute KPI from ensemble model") # 1. From generated cluster data: # Compute dataset and keep from file the cluster ID # Separate Train and Test dataset using learned zones csv file # - data folder # - nclusters # - human thresholds parser.add_argument('--data', type=str, help='folder path with all clusters data', required=True) parser.add_argument('--nclusters', type=int, help='number of clusters', required=True) parser.add_argument('--sequence', type=int, help='sequence length expected', required=True) # 2. Prepare input dataset # - selected_zones file # - sequence size # - seqnorm or not parser.add_argument('--selected_zones', type=str, help='file which contains selected zones indices for training part', required=True) parser.add_argument('--seq_norm', type=int, help='normalization sequence by features', choices=[0, 1]) # 3. Load ensemble models # - models folder # - weight for identified cluster model parser.add_argument('--models', type=str, help='folder with all models', required=True) parser.add_argument('--weight', type=float, help='associated weight to cluster model of zone', default=2.5) # 4. Compute each KPI from labels # - output results file parser.add_argument('--output', type=str, help='output prediction file', required=True) args = parser.parse_args() # 1. Generate dataset input from precomputer data p_data = args.data p_nclusters = args.nclusters p_sequence = args.sequence # 2. Dataset preparation p_selected_zones = args.selected_zones p_seq_norm = bool(args.seq_norm) # 3. Models param p_models = args.models p_weight = args.weight # 4. Output KPI of models p_output = args.output # PART 1. Load generated data print('# PART 1: load generated data') """ cluster_data = [ (cluster_id, scene_name, zone_id, label, data) ] """ clusters_data = [] for c_id in range(p_nclusters): cluster_filepath = os.path.join(p_data, 'cluster_data_{0}.csv'.format(c_id)) with open(cluster_filepath, 'r') as f: lines = f.readlines() for line in lines: data = line.split(';') # only if scene is used for training part scene_name = data[0] zones_index = int(data[1]) threshold = int(data[3]) image_indices = data[4].split(',') values_list = data[5].split(',') # compute sequence data here sequence_data = [] for i, index in enumerate(image_indices): values = values_list[i].split(' ') # append new sequence sequence_data.append(values) if i + 1 >= p_sequence: label = int(threshold > int(index)) if len(sequence_data) != p_sequence: print("error found => ", len(sequence_data)) # Add new data line into cluster data clusters_data.append((c_id, scene_name, zones_index, label, sequence_data.copy())) del sequence_data[0] # PART 2. Prepare input data print('# PART 2: preparation of input data') # extract learned zones from file zones_learned = {} if len(p_selected_zones) > 0: with open(p_selected_zones, 'r') as f: lines = f.readlines() for line in lines: data = line.replace(';\n', '').split(';') scene_name = data[0] zones_learned[scene_name] = [ int(z) for z in data[1:] ] """ XXXX_dataset = [ (cluster_id, label, data) ] """ train_dataset = [] test_dataset = [] n_samples = len(clusters_data) for index_line, line in enumerate(clusters_data): data = np.array(line[-1], 'float32') if data.ndim == 1: data = data.reshape(len(data[-1]), 1) else: # check if sequence normalization is used if p_seq_norm: s, f = data.shape for i in range(f): #final_arr[index][] data[:, i] = utils.normalize_arr_with_range(data[:, i]) data = np.expand_dims(data, axis=0) if p_seq_norm: data_line = (line[0], line[3], data) else: data_line = (line[0], line[3], data) # use of stored zone index of scene zone_id = line[2] scene_name = line[1] if zone_id in zones_learned[scene_name]: train_dataset.append(data_line) else: test_dataset.append(data_line) write_progress((index_line + 1) / n_samples) print() print('=> Training set is of {:2f} of total samples'.format(len(train_dataset) / n_samples)) print('=> Testing set is of {:2f} of total samples'.format(len(test_dataset) / n_samples)) # PART 3. Load ensemble models print('# PART 3: load ensemble models and do predictions') # Load each classification model models_path = sorted([ os.path.join(p_models, m) for m in os.listdir(p_models)]) models_list = [] for model_p in models_path: model = load_model(model_p) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) models_list.append(model) # do predictions counter_sample = 0 y_train_predicted = [] y_test_predicted = [] for line in train_dataset: cluster_id = line[0] data = line[-1] prob = predict_ensemble(models_list, data, cluster_id, p_weight) #print(index, ':', image_indices[img_i], '=>', prob) if prob < 0.5: y_train_predicted.append(0) else: y_train_predicted.append(1) counter_sample += 1 write_progress((counter_sample + 1) / n_samples) for line in test_dataset: cluster_id = line[0] data = line[-1] prob = predict_ensemble(models_list, data, cluster_id, p_weight) #print(index, ':', image_indices[img_i], '=>', prob) if prob < 0.5: y_test_predicted.append(0) else: y_test_predicted.append(1) counter_sample += 1 write_progress((counter_sample + 1) / n_samples) # PART 4. Get KPI using labels comparisons y_train = [ line[1] for line in train_dataset ] y_test = [ line[1] for line in test_dataset ] auc_train = roc_auc_score(y_train, y_train_predicted) auc_test = roc_auc_score(y_test, y_test_predicted) acc_train = accuracy_score(y_train, y_train_predicted) acc_test = accuracy_score(y_test, y_test_predicted) print('Train ACC:', acc_train) print('Train AUC', auc_train) print('Test ACC:', acc_test) print('Test AUC:', auc_test) if not os.path.exists(p_output): with open(p_output, 'w') as f: f.write('name;acc_train;auc_train;acc_test;auc_test\n') with open(p_output, 'a') as f: f.write('{0};{1};{2};{3};{4}\n'.format(p_models, acc_train, auc_train, acc_test, auc_test)) if __name__ == "__main__": main()
[ "os.path.exists", "os.listdir", "keras.models.load_model", "argparse.ArgumentParser", "os.path.join", "sklearn.metrics.roc_auc_score", "numpy.array", "numpy.expand_dims", "ipfml.utils.normalize_arr_with_range", "sklearn.metrics.accuracy_score", "sys.stdout.write" ]
[((637, 663), 'sys.stdout.write', 'sys.stdout.write', (['"""\x1b[F"""'], {}), "('\\x1b[F')\n", (653, 663), False, 'import os, sys\n'), ((1500, 1570), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Compute KPI from ensemble model"""'}), "(description='Compute KPI from ensemble model')\n", (1523, 1570), False, 'import argparse\n'), ((8319, 8360), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_train', 'y_train_predicted'], {}), '(y_train, y_train_predicted)\n', (8332, 8360), False, 'from sklearn.metrics import roc_auc_score, accuracy_score\n'), ((8376, 8415), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_test', 'y_test_predicted'], {}), '(y_test, y_test_predicted)\n', (8389, 8415), False, 'from sklearn.metrics import roc_auc_score, accuracy_score\n'), ((8433, 8475), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_train', 'y_train_predicted'], {}), '(y_train, y_train_predicted)\n', (8447, 8475), False, 'from sklearn.metrics import roc_auc_score, accuracy_score\n'), ((8491, 8531), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'y_test_predicted'], {}), '(y_test, y_test_predicted)\n', (8505, 8531), False, 'from sklearn.metrics import roc_auc_score, accuracy_score\n'), ((5584, 5613), 'numpy.array', 'np.array', (['line[-1]', '"""float32"""'], {}), "(line[-1], 'float32')\n", (5592, 5613), True, 'import numpy as np\n'), ((6053, 6081), 'numpy.expand_dims', 'np.expand_dims', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (6067, 6081), True, 'import numpy as np\n'), ((7021, 7040), 'keras.models.load_model', 'load_model', (['model_p'], {}), '(model_p)\n', (7031, 7040), False, 'from keras.models import load_model\n'), ((8688, 8712), 'os.path.exists', 'os.path.exists', (['p_output'], {}), '(p_output)\n', (8702, 8712), False, 'import os, sys\n'), ((6891, 6916), 'os.path.join', 'os.path.join', (['p_models', 'm'], {}), '(p_models, m)\n', (6903, 6916), False, 'import os, sys\n'), ((6926, 6946), 'os.listdir', 'os.listdir', (['p_models'], {}), '(p_models)\n', (6936, 6946), False, 'import os, sys\n'), ((5970, 6012), 'ipfml.utils.normalize_arr_with_range', 'utils.normalize_arr_with_range', (['data[:, i]'], {}), '(data[:, i])\n', (6000, 6012), False, 'from ipfml import utils\n')]
__author__ = 'roehrig' import numpy as np import pandas as pd from osgeo import ogr # from warsa.gis.features.feature import Layers # from warsa.gis.features.interpolation.idw import idw def idw_time_series_interpolation(point_lrs_in, field_name_in, df_ts_in, point_lrs_out, field_name_out): # Extract point coordinates and corresponding ids of input and output layers try: point_lrs_in = Layers(point_lrs_in) except TypeError: pass try: point_lrs_out = Layers(point_lrs_out) except TypeError: pass feat_in = sorted([list(ogr.CreateGeometryFromWkb(f[0]).GetPoints()[0]) + [str(f[1])] for f in point_lrs_in.get_geometries_and_field_values([field_name_in])], key=lambda v: v[2]) feat_out = sorted([list(ogr.CreateGeometryFromWkb(f[0]).GetPoints()[0]) + [str(f[1])] for f in point_lrs_out.get_geometries_and_field_values([field_name_out])], key=lambda v: v[2]) # Read time series df_ts_in.columns = [str(c) for c in df_ts_in.columns] # Harmonize the features and time series # Remove columns from time series not contained in the input features list df_ts_in = df_ts_in[list(zip(*feat_in)[2])] # Remove input features list not contained in the time series feat_in = [f for f in feat_in if f[2] in df_ts_in.columns] # Set gaps label for each row gap_labels = 'GAPLABELS' while gap_labels in df_ts_in.columns: gap_labels += '0' df_ts_in.is_copy = False # TODO: deal with the warning df_ts_in[gap_labels] = df_ts_in.apply(lambda row: ''.join(['0' if np.isnan(v) else '1' for ir, v in enumerate(row)]), axis=1) # Get all patterns of weights =[number of out_points, number of valid input points] combination_weights = {} xy_out = zip(*zip(*feat_out)[0:2]) for combination in set(df_ts_in[gap_labels].tolist()): if combination not in combination_weights: fin = [f for i, f in enumerate(feat_in) if combination[i] == '1'] if fin: combination_weights[combination] = idw(zip(*zip(*fin)[0:2]), np.diag([1]*len(fin)).tolist(), xy_out) else: combination_weights[combination] = None df_ts_out = pd.DataFrame(index=df_ts_in.index) for col_idx, col_out in enumerate(zip(*feat_out)[2]): def weighted_sum(row): comb = combination_weights[row[-1]] if comb is not None: weights = comb[col_idx] gap_indices = [ig for ig, gc in enumerate(row[-1]) if gc == '0'] for gi in gap_indices: weights = np.insert(weights, gi, 0.0) return np.sum(row[:-1] * weights) else: return np.NaN df_ts_out[col_out] = df_ts_in.apply(weighted_sum, axis=1) del df_ts_in[gap_labels] return df_ts_out
[ "numpy.insert", "osgeo.ogr.CreateGeometryFromWkb", "numpy.sum", "numpy.isnan", "pandas.DataFrame" ]
[((2202, 2236), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'df_ts_in.index'}), '(index=df_ts_in.index)\n', (2214, 2236), True, 'import pandas as pd\n'), ((2648, 2674), 'numpy.sum', 'np.sum', (['(row[:-1] * weights)'], {}), '(row[:-1] * weights)\n', (2654, 2674), True, 'import numpy as np\n'), ((2597, 2624), 'numpy.insert', 'np.insert', (['weights', 'gi', '(0.0)'], {}), '(weights, gi, 0.0)\n', (2606, 2624), True, 'import numpy as np\n'), ((1568, 1579), 'numpy.isnan', 'np.isnan', (['v'], {}), '(v)\n', (1576, 1579), True, 'import numpy as np\n'), ((582, 613), 'osgeo.ogr.CreateGeometryFromWkb', 'ogr.CreateGeometryFromWkb', (['f[0]'], {}), '(f[0])\n', (607, 613), False, 'from osgeo import ogr\n'), ((765, 796), 'osgeo.ogr.CreateGeometryFromWkb', 'ogr.CreateGeometryFromWkb', (['f[0]'], {}), '(f[0])\n', (790, 796), False, 'from osgeo import ogr\n')]
import numpy as np from pyesg.configuration.validation_configuration import ValidationAnalysis from pyesg.constants.outputs import DISCOUNT_FACTOR, BOND_INDEX from pyesg.constants.validation_analyses import DISCOUNTEd_BOND_INDEX from pyesg.constants.validation_result_types import MARTINGALE from pyesg.simulation.utils import extract_yield_curve_from_parameters from pyesg.validation.utils import get_confidence_level, do_sample_mean_and_confidence_interval_calculations from pyesg.validation.validators.base_validator import BaseValidator from pyesg.yield_curve.yield_curve import YieldCurve class DiscountedBondIndexValidator(BaseValidator): """ Performs discounted bond index validation analysis. The expected value of the discounted bond index is its initial value (which is 1). """ analysis_id = DISCOUNTEd_BOND_INDEX result_type = MARTINGALE def _validate(self, analysis_settings: ValidationAnalysis): confidence_level = get_confidence_level(analysis_settings) terms = getattr(analysis_settings.parameters, "terms", []) return [self._validate_single_term(confidence_level, term) for term in terms] def _validate_single_term(self, confidence_level: float, term: float): discount_factor_sims = self._data_extractor.get_output_simulations( asset_class=self._asset_class, output_type=DISCOUNT_FACTOR, ) bond_index_sims = self._data_extractor.get_output_simulations( asset_class=self._asset_class, output_type=BOND_INDEX, term=term ) discounted_bond_index_sims = discount_factor_sims * bond_index_sims # Get sample mean and upper and lower confidence intervals results = do_sample_mean_and_confidence_interval_calculations( array=discounted_bond_index_sims, confidence_level=confidence_level, annualisation_factor=self._data_extractor.reader.annualisation_factor ) # Expected value is just 1. expected_values = np.full(self._data_extractor.reader.number_of_time_steps, 1.0) results["expected_value"] = expected_values results["term"] = term return results
[ "numpy.full", "pyesg.validation.utils.get_confidence_level", "pyesg.validation.utils.do_sample_mean_and_confidence_interval_calculations" ]
[((969, 1008), 'pyesg.validation.utils.get_confidence_level', 'get_confidence_level', (['analysis_settings'], {}), '(analysis_settings)\n', (989, 1008), False, 'from pyesg.validation.utils import get_confidence_level, do_sample_mean_and_confidence_interval_calculations\n'), ((1753, 1953), 'pyesg.validation.utils.do_sample_mean_and_confidence_interval_calculations', 'do_sample_mean_and_confidence_interval_calculations', ([], {'array': 'discounted_bond_index_sims', 'confidence_level': 'confidence_level', 'annualisation_factor': 'self._data_extractor.reader.annualisation_factor'}), '(array=\n discounted_bond_index_sims, confidence_level=confidence_level,\n annualisation_factor=self._data_extractor.reader.annualisation_factor)\n', (1804, 1953), False, 'from pyesg.validation.utils import get_confidence_level, do_sample_mean_and_confidence_interval_calculations\n'), ((2054, 2116), 'numpy.full', 'np.full', (['self._data_extractor.reader.number_of_time_steps', '(1.0)'], {}), '(self._data_extractor.reader.number_of_time_steps, 1.0)\n', (2061, 2116), True, 'import numpy as np\n')]
from __future__ import division import os import sys import cv2 import argparse import glob import math import numpy as np import matplotlib.pyplot as plt from skimage import draw, transform from scipy.optimize import minimize from PIL import Image import objs import utils #fp is in cam-ceil normal, height is in cam-floor normal def data2scene(fp_points, height): # cam-ceiling / cam-floor scale = (height - 1.6) / 1.6 #layout_fp, fp_points = fit_layout(fp, scale=None, max_cor=12) size = 512 ratio = 20/size fp_points = fp_points.astype(float) fp_points[0] -= size/2 fp_points[1] -= size/2 fp_points *= scale fp_points[0] += size/2 fp_points[1] += size/2 fp_points = fp_points.astype(int) scene = objs.Scene() scene.cameraHeight = 1.6 scene.layoutHeight = float(height) scene.layoutPoints = [] for i in range(fp_points.shape[1]): fp_xy = (fp_points[:,i] - size/2) * ratio xyz = (fp_xy[1], 0, fp_xy[0]) scene.layoutPoints.append(objs.GeoPoint(scene, None, xyz)) scene.genLayoutWallsByPoints(scene.layoutPoints) scene.updateLayoutGeometry() return scene def f1_score(pred, gt): TP = np.zeros(gt.shape); FP = np.zeros(gt.shape) FN = np.zeros(gt.shape); TN = np.zeros(gt.shape) TP[(pred==gt) & (pred == 1)] = 1 FP[(pred!=gt) & (pred == 1)] = 1 FN[(pred!=gt) & (gt == 1)] = 1 TN[(pred==gt) & (pred == 0)] = 1 TP = np.sum(TP); FP = np.sum(FP) FN = np.sum(FN); TN = np.sum(TN) precision = TP / (TP + FP) recall = TP / (TP + FN) accuracy = (TP + TN) / (gt.shape[0]*gt.shape[1]) f1_score = 2 / ((1 / precision) + (1 / recall)) return f1_score def fit_layout(data, max_cor=12): ret, data_thresh = cv2.threshold(data, 0.5, 1,0) data_thresh = np.uint8(data_thresh) #data_img, data_cnt, data_heri = cv2.findContours(data_thresh, 1, 2) data_cnt, data_heri = cv2.findContours(data_thresh, 1, 2) data_cnt.sort(key=lambda x: cv2.contourArea(x), reverse=True) sub_x, sub_y, w, h = cv2.boundingRect(data_cnt[0]) data_sub = data_thresh[sub_y:sub_y+h,sub_x:sub_x+w] #data_img, data_cnt, data_heri = cv2.findContours(data_sub, 1, 2) data_cnt, data_heri = cv2.findContours(data_sub, 1, 2) data_cnt.sort(key=lambda x: cv2.contourArea(x), reverse=True) data_cnt = data_cnt[0] epsilon = 0.005*cv2.arcLength(data_cnt,True) approx = cv2.approxPolyDP(data_cnt, epsilon,True) x_lst = [0,] y_lst = [0,] for i in range(len(approx)): p1 = approx[i][0] p2 = approx[(i+1)%len(approx)][0] if (p2[0]-p1[0]) == 0: slope = 10 else: slope = abs((p2[1]-p1[1]) / (p2[0]-p1[0])) if slope <= 1: s = int((p1[1] + p2[1])/2) y_lst.append(s) elif slope > 1: s = int((p1[0] + p2[0])/2) x_lst.append(s) x_lst.append(data_sub.shape[1]) y_lst.append(data_sub.shape[0]) x_lst.sort() y_lst.sort() diag = math.sqrt(math.pow(data_sub.shape[1],2) + math.pow(data_sub.shape[0],2)) def merge_near(lst): group = [[0,]] for i in range(1, len(lst)): if lst[i] - np.mean(group[-1]) < diag * 0.05: group[-1].append(lst[i]) else: group.append([lst[i],]) group = [int(np.mean(x)) for x in group] return group x_lst = merge_near(x_lst) y_lst = merge_near(y_lst) #print(x_lst) #print(y_lst) img = np.zeros((data_sub.shape[0],data_sub.shape[1],3)) for x in x_lst: cv2.line(img,(x,0), (x,data_sub.shape[0]),(0,255,0),1) for y in y_lst: cv2.line(img,(0,y), (data_sub.shape[1],y),(255,0,0),1) ans = np.zeros((data_sub.shape[0],data_sub.shape[1])) for i in range(len(x_lst)-1): for j in range(len(y_lst)-1): sample = data_sub[y_lst[j]:y_lst[j+1] , x_lst[i]:x_lst[i+1]] score = sample.mean() if score >= 0.5: ans[y_lst[j]:y_lst[j+1] , x_lst[i]:x_lst[i+1]] = 1 pred = np.uint8(ans) #pred_img, pred_cnt, pred_heri = cv2.findContours(pred, 1, 3) pred_cnt, pred_heri = cv2.findContours(pred, 1, 3) polygon = [(p[0][1], p[0][0]) for p in pred_cnt[0][::-1]] Y = np.array([p[0]+sub_y for p in polygon]) X = np.array([p[1]+sub_x for p in polygon]) fp_points = np.concatenate( (Y[np.newaxis,:],X[np.newaxis,:]), axis=0) layout_fp = np.zeros(data.shape) rr, cc = draw.polygon(fp_points[0], fp_points[1]) rr = np.clip(rr, 0, data.shape[0]-1) cc = np.clip(cc, 0, data.shape[1]-1) layout_fp[rr,cc] = 1 if False: img = np.zeros((data_sub.shape[0],data_sub.shape[1],3)) for i in range(len(approx)): p1 = approx[i][0] p2 = approx[(i+1)%len(approx)][0] slope = abs((p2[1]-p1[1]) / (p2[0]-p1[0])) if slope <= 1: cv2.line(img,(p1[0], p1[1]), (p2[0], p2[1]),(255,0,0),1) elif slope > 1: cv2.line(img,(p1[0], p1[1]), (p2[0], p2[1]),(0,255,0),1) #cv2.drawContours(img, [approx], 0, (,255,0), 1) fig = plt.figure() plt.axis('off') plt.imshow(img) #plt.show() fig.savefig('D:/CVPR/figure/post/002/contour2', bbox_inches='tight',transparent=True, pad_inches=0) if False: fig = plt.figure() plt.axis('off') plt.imshow(layout_fp) fig.savefig('D:/CVPR/figure/post/002/layout_fp', bbox_inches='tight',transparent=True, pad_inches=0) #plt.show() if False: fig = plt.figure() plt.axis('off') ax1 = fig.add_subplot(2,3,1) ax1.imshow(data) ax2 = fig.add_subplot(2,3,2) ax2.imshow(data_thresh) ax3 = fig.add_subplot(2,3,3) ax3.imshow(data_sub) ax4 = fig.add_subplot(2,3,4) #data_sub = data_sub[:,:,np.newaxis] #ax4.imshow(img + np.concatenate( (data_sub,data_sub,data_sub),axis=2) * 0.25) ax4.imshow(img) ax5 = fig.add_subplot(2,3,5) ax5.imshow(ans) ax6 = fig.add_subplot(2,3,6) ax6.imshow(layout_fp) plt.show() return layout_fp, fp_points ''' def fit_layout_old(data, max_cor=12): #find max connective component ret, data_thresh = cv2.threshold(data, 0.5, 1,0) data_thresh = np.uint8(data_thresh) data_img, data_cnt, data_heri = cv2.findContours(data_thresh, 1, 2) data_cnt.sort(key=lambda x: cv2.contourArea(x), reverse=True) # crop data sub as f1 true sub_x, sub_y, w, h = cv2.boundingRect(data_cnt[0]) data_sub = data_thresh[sub_y:sub_y+h,sub_x:sub_x+w] pred = np.ones(data_sub.shape) min_score = 0.05 def optim(corid): def loss(x): h_, w_ = int(x[0]),int(x[1]) box = [[0,0,h_,w_], [0,w_,h_,w], [h_,w_,h,w], [h_,0,h,w_]] sample = pred.copy() sample[box[corid][0]:box[corid][2], box[corid][1]:box[corid][3]] = 0 return -f1_score(sample, data_sub) res_lst = [] for st in [0.1, 0.25]: stp = [[h*st, w*st],[h*st, w*(1-st)],[h*(1-st), w*(1-st)],[h*(1-st), w*st]] res = minimize(loss, np.array(stp[corid]), method='nelder-mead', options={'xtol': 1e-8, 'disp': False}) res_lst.append(res) res_lst.sort(key=lambda x: x.fun, reverse=False) return res_lst[0] ###### res = optim(0) ul = res.x.astype(int) res = optim(1) ur = res.x.astype(int) res = optim(2) dr = res.x.astype(int) res = optim(3) dl = res.x.astype(int) print([ul, ur, dr, dl]) s_ul = ul[0]*ul[1] / (w*h) s_ur = ur[0]*(w-ur[1]) / (w*h) s_dr = (h-dr[0])*(w-dr[1]) / (w*h) s_dl = (h-dl[0])*dl[1] / (w*h) print([s_ul, s_ur, s_dr, s_dl]) sort_idx = list(np.argsort([s_ul, s_ur, s_dr, s_dl])[::-1]) assert max_cor in [4, 6, 8, 10, 12] max_idx = (max_cor-4)/2 if s_ul > min_score and (sort_idx.index(0) < max_idx): pred[0:int(ul[0]), 0:int(ul[1])] = 0 if s_ur > min_score and (sort_idx.index(1) < max_idx): pred[0:int(ur[0]), int(ur[1]):w] = 0 if s_dr > min_score and (sort_idx.index(2) < max_idx): pred[int(dr[0]):h, int(dr[1]):w] = 0 if s_dl > min_score and (sort_idx.index(3) < max_idx): pred[int(dl[0]):h, 0:int(dl[1])] = 0 pred = np.uint8(pred) pred_img, pred_cnt, pred_heri = cv2.findContours(pred, 1, 3) polygon = [(p[0][1], p[0][0]) for p in pred_cnt[0][::-1]] Y = np.array([p[0]+sub_y for p in polygon]) X = np.array([p[1]+sub_x for p in polygon]) fp_points = np.concatenate( (Y[np.newaxis,:],X[np.newaxis,:]), axis=0) layout_fp = np.zeros(data.shape) rr, cc = draw.polygon(fp_points[0], fp_points[1]) rr = np.clip(rr, 0, data.shape[0]-1) cc = np.clip(cc, 0, data.shape[1]-1) layout_fp[rr,cc] = 1 if False: fig = plt.figure() ax1 = fig.add_subplot(1,2,1) ax1.imshow(data_sub) ax2 = fig.add_subplot(1,2,2) ax2.imshow(pred) plt.show() return layout_fp, fp_points ''' if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--i', required=True) args = parser.parse_args() data_path = args.i #for filepath in glob.iglob(data_path + '/*.npy'): #for i in range(404): #for i in [91, 104, 145, 159, 167, 194, 215, 223, 253, 256, 261, 266, 300, 304, 357, 358]: for i in [261]: filepath = os.path.join(data_path, '{0}.npy'.format(i)) print(filepath) data = np.load(filepath, encoding = 'bytes')[()] #color = data['color'] #fp_floor = data['fp_floor'] fp_pred = data['pred_fp_merge'] layout_fp, fp_points = fit_layout(fp_pred) #fit_layout(fp_pred) #print(fp_points)
[ "numpy.uint8", "numpy.clip", "numpy.array", "cv2.approxPolyDP", "matplotlib.pyplot.imshow", "numpy.mean", "argparse.ArgumentParser", "cv2.threshold", "cv2.arcLength", "cv2.line", "cv2.contourArea", "numpy.concatenate", "matplotlib.pyplot.axis", "matplotlib.pyplot.show", "skimage.draw.pol...
[((792, 804), 'objs.Scene', 'objs.Scene', ([], {}), '()\n', (802, 804), False, 'import objs\n'), ((1258, 1276), 'numpy.zeros', 'np.zeros', (['gt.shape'], {}), '(gt.shape)\n', (1266, 1276), True, 'import numpy as np\n'), ((1283, 1301), 'numpy.zeros', 'np.zeros', (['gt.shape'], {}), '(gt.shape)\n', (1291, 1301), True, 'import numpy as np\n'), ((1312, 1330), 'numpy.zeros', 'np.zeros', (['gt.shape'], {}), '(gt.shape)\n', (1320, 1330), True, 'import numpy as np\n'), ((1337, 1355), 'numpy.zeros', 'np.zeros', (['gt.shape'], {}), '(gt.shape)\n', (1345, 1355), True, 'import numpy as np\n'), ((1520, 1530), 'numpy.sum', 'np.sum', (['TP'], {}), '(TP)\n', (1526, 1530), True, 'import numpy as np\n'), ((1537, 1547), 'numpy.sum', 'np.sum', (['FP'], {}), '(FP)\n', (1543, 1547), True, 'import numpy as np\n'), ((1558, 1568), 'numpy.sum', 'np.sum', (['FN'], {}), '(FN)\n', (1564, 1568), True, 'import numpy as np\n'), ((1575, 1585), 'numpy.sum', 'np.sum', (['TN'], {}), '(TN)\n', (1581, 1585), True, 'import numpy as np\n'), ((1846, 1876), 'cv2.threshold', 'cv2.threshold', (['data', '(0.5)', '(1)', '(0)'], {}), '(data, 0.5, 1, 0)\n', (1859, 1876), False, 'import cv2\n'), ((1895, 1916), 'numpy.uint8', 'np.uint8', (['data_thresh'], {}), '(data_thresh)\n', (1903, 1916), True, 'import numpy as np\n'), ((2018, 2053), 'cv2.findContours', 'cv2.findContours', (['data_thresh', '(1)', '(2)'], {}), '(data_thresh, 1, 2)\n', (2034, 2053), False, 'import cv2\n'), ((2149, 2178), 'cv2.boundingRect', 'cv2.boundingRect', (['data_cnt[0]'], {}), '(data_cnt[0])\n', (2165, 2178), False, 'import cv2\n'), ((2338, 2370), 'cv2.findContours', 'cv2.findContours', (['data_sub', '(1)', '(2)'], {}), '(data_sub, 1, 2)\n', (2354, 2370), False, 'import cv2\n'), ((2530, 2571), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['data_cnt', 'epsilon', '(True)'], {}), '(data_cnt, epsilon, True)\n', (2546, 2571), False, 'import cv2\n'), ((3705, 3756), 'numpy.zeros', 'np.zeros', (['(data_sub.shape[0], data_sub.shape[1], 3)'], {}), '((data_sub.shape[0], data_sub.shape[1], 3))\n', (3713, 3756), True, 'import numpy as np\n'), ((3946, 3994), 'numpy.zeros', 'np.zeros', (['(data_sub.shape[0], data_sub.shape[1])'], {}), '((data_sub.shape[0], data_sub.shape[1]))\n', (3954, 3994), True, 'import numpy as np\n'), ((4305, 4318), 'numpy.uint8', 'np.uint8', (['ans'], {}), '(ans)\n', (4313, 4318), True, 'import numpy as np\n'), ((4413, 4441), 'cv2.findContours', 'cv2.findContours', (['pred', '(1)', '(3)'], {}), '(pred, 1, 3)\n', (4429, 4441), False, 'import cv2\n'), ((4518, 4561), 'numpy.array', 'np.array', (['[(p[0] + sub_y) for p in polygon]'], {}), '([(p[0] + sub_y) for p in polygon])\n', (4526, 4561), True, 'import numpy as np\n'), ((4567, 4610), 'numpy.array', 'np.array', (['[(p[1] + sub_x) for p in polygon]'], {}), '([(p[1] + sub_x) for p in polygon])\n', (4575, 4610), True, 'import numpy as np\n'), ((4624, 4684), 'numpy.concatenate', 'np.concatenate', (['(Y[np.newaxis, :], X[np.newaxis, :])'], {'axis': '(0)'}), '((Y[np.newaxis, :], X[np.newaxis, :]), axis=0)\n', (4638, 4684), True, 'import numpy as np\n'), ((4702, 4722), 'numpy.zeros', 'np.zeros', (['data.shape'], {}), '(data.shape)\n', (4710, 4722), True, 'import numpy as np\n'), ((4737, 4777), 'skimage.draw.polygon', 'draw.polygon', (['fp_points[0]', 'fp_points[1]'], {}), '(fp_points[0], fp_points[1])\n', (4749, 4777), False, 'from skimage import draw, transform\n'), ((4788, 4821), 'numpy.clip', 'np.clip', (['rr', '(0)', '(data.shape[0] - 1)'], {}), '(rr, 0, data.shape[0] - 1)\n', (4795, 4821), True, 'import numpy as np\n'), ((4830, 4863), 'numpy.clip', 'np.clip', (['cc', '(0)', '(data.shape[1] - 1)'], {}), '(cc, 0, data.shape[1] - 1)\n', (4837, 4863), True, 'import numpy as np\n'), ((9662, 9687), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (9685, 9687), False, 'import argparse\n'), ((2487, 2516), 'cv2.arcLength', 'cv2.arcLength', (['data_cnt', '(True)'], {}), '(data_cnt, True)\n', (2500, 2516), False, 'import cv2\n'), ((3785, 3846), 'cv2.line', 'cv2.line', (['img', '(x, 0)', '(x, data_sub.shape[0])', '(0, 255, 0)', '(1)'], {}), '(img, (x, 0), (x, data_sub.shape[0]), (0, 255, 0), 1)\n', (3793, 3846), False, 'import cv2\n'), ((3870, 3931), 'cv2.line', 'cv2.line', (['img', '(0, y)', '(data_sub.shape[1], y)', '(255, 0, 0)', '(1)'], {}), '(img, (0, y), (data_sub.shape[1], y), (255, 0, 0), 1)\n', (3878, 3931), False, 'import cv2\n'), ((4920, 4971), 'numpy.zeros', 'np.zeros', (['(data_sub.shape[0], data_sub.shape[1], 3)'], {}), '((data_sub.shape[0], data_sub.shape[1], 3))\n', (4928, 4971), True, 'import numpy as np\n'), ((5445, 5457), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5455, 5457), True, 'import matplotlib.pyplot as plt\n'), ((5467, 5482), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (5475, 5482), True, 'import matplotlib.pyplot as plt\n'), ((5492, 5507), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (5502, 5507), True, 'import matplotlib.pyplot as plt\n'), ((5670, 5682), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5680, 5682), True, 'import matplotlib.pyplot as plt\n'), ((5692, 5707), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (5700, 5707), True, 'import matplotlib.pyplot as plt\n'), ((5717, 5738), 'matplotlib.pyplot.imshow', 'plt.imshow', (['layout_fp'], {}), '(layout_fp)\n', (5727, 5738), True, 'import matplotlib.pyplot as plt\n'), ((5904, 5916), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5914, 5916), True, 'import matplotlib.pyplot as plt\n'), ((5926, 5941), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (5934, 5941), True, 'import matplotlib.pyplot as plt\n'), ((6493, 6503), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6501, 6503), True, 'import matplotlib.pyplot as plt\n'), ((1072, 1103), 'objs.GeoPoint', 'objs.GeoPoint', (['scene', 'None', 'xyz'], {}), '(scene, None, xyz)\n', (1085, 1103), False, 'import objs\n'), ((3201, 3231), 'math.pow', 'math.pow', (['data_sub.shape[1]', '(2)'], {}), '(data_sub.shape[1], 2)\n', (3209, 3231), False, 'import math\n'), ((3234, 3264), 'math.pow', 'math.pow', (['data_sub.shape[0]', '(2)'], {}), '(data_sub.shape[0], 2)\n', (3242, 3264), False, 'import math\n'), ((10109, 10144), 'numpy.load', 'np.load', (['filepath'], {'encoding': '"""bytes"""'}), "(filepath, encoding='bytes')\n", (10116, 10144), True, 'import numpy as np\n'), ((2087, 2105), 'cv2.contourArea', 'cv2.contourArea', (['x'], {}), '(x)\n', (2102, 2105), False, 'import cv2\n'), ((2404, 2422), 'cv2.contourArea', 'cv2.contourArea', (['x'], {}), '(x)\n', (2419, 2422), False, 'import cv2\n'), ((3538, 3548), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (3545, 3548), True, 'import numpy as np\n'), ((5207, 5268), 'cv2.line', 'cv2.line', (['img', '(p1[0], p1[1])', '(p2[0], p2[1])', '(255, 0, 0)', '(1)'], {}), '(img, (p1[0], p1[1]), (p2[0], p2[1]), (255, 0, 0), 1)\n', (5215, 5268), False, 'import cv2\n'), ((3380, 3398), 'numpy.mean', 'np.mean', (['group[-1]'], {}), '(group[-1])\n', (3387, 3398), True, 'import numpy as np\n'), ((5313, 5374), 'cv2.line', 'cv2.line', (['img', '(p1[0], p1[1])', '(p2[0], p2[1])', '(0, 255, 0)', '(1)'], {}), '(img, (p1[0], p1[1]), (p2[0], p2[1]), (0, 255, 0), 1)\n', (5321, 5374), False, 'import cv2\n')]
import numpy as np from multilayernetwork import MultiLayerNetWork from util import load_csv_np from config import * def one_shot_prediction(file_name) -> np.ndarray: """ this load network and given a one shot predict to data :param file_name: read from file name :return one shot encoded in numpy array """ np.set_printoptions(threshold=np.inf) data = load_csv_np(path=file_name) model = MultiLayerNetWork.load_net_work(91) predicts = model.one_hot_predict(data) return predicts if __name__ == "__main__": print(one_shot_prediction(TEST_DATASET))
[ "multilayernetwork.MultiLayerNetWork.load_net_work", "util.load_csv_np", "numpy.set_printoptions" ]
[((335, 372), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.inf'}), '(threshold=np.inf)\n', (354, 372), True, 'import numpy as np\n'), ((384, 411), 'util.load_csv_np', 'load_csv_np', ([], {'path': 'file_name'}), '(path=file_name)\n', (395, 411), False, 'from util import load_csv_np\n'), ((424, 459), 'multilayernetwork.MultiLayerNetWork.load_net_work', 'MultiLayerNetWork.load_net_work', (['(91)'], {}), '(91)\n', (455, 459), False, 'from multilayernetwork import MultiLayerNetWork\n')]
#!/usr/bin/env python3 ''' This script either runs inference and visualizes results. Or runs evaluations on the test set. The following will just run inference and show GT (Green) and predictions (Red). ./infer.py infer Running the following will visualize results: infer.py --debug test Visualization legend: Blue - GT True Positives Yellow - Pred True Positives Green - GT False Negatives Red - Pred False Positives ''' import sys import os import torch import numpy as np from torch.utils.data import Dataset, DataLoader from model import ResNetUNet import torch.nn.functional as F import cv2 from copy import deepcopy from icecream import ic # Custom helpers import helper # My custom dataset from bee_dataloader import BeePointDataset import pickle import time import argparse np.set_printoptions(linewidth=240) # For inference timing of different components ENABLE_TIMING = False def setup_model_dataloader(args, batch_size): num_class = 1 model = ResNetUNet(num_class) device = torch.device("cuda") model_file = os.path.join(args.model_dir, 'best_model.pth') model.load_state_dict(torch.load(model_file, map_location="cuda:0")) model.to(device) # Set model to the evaluation mode model.eval() # Setup dataset # Need to be careful here. This isn't perfect. # I'm assuming that the dataset isn't changing between training and inference time bee_ds = BeePointDataset(root_dir=args.data_dir) if 1: dbfile = open(os.path.join(args.model_dir, 'test_ds.pkl'), 'rb') test_ds = pickle.load(dbfile) #test_loader = DataLoader(test_ds, batch_size=1, shuffle=False, num_workers=1) test_loader = DataLoader(test_ds, batch_size=batch_size, shuffle=True, num_workers=1, collate_fn=helper.bee_collate_fn) else: # Just use the defaults in the bee_ds test_loader = DataLoader(bee_ds, batch_size=batch_size, shuffle=True, num_workers=1, collate_fn=helper.bee_collate_fn) return model, test_loader, device def inference(args): model, dataloder, device = setup_model_dataloader(args, batch_size=1) for _ in range(len(dataloder)): # Because we have variable length points coming from Dataloader, there's some extra overhead # in managing the input and GT data. See collate_fn(). inputs, mask, points = next(iter(dataloder)) inputs = torch.unsqueeze(inputs[0], 0) points = points[0] pred = helper.model_forward(model, inputs, device, ENABLE_TIMING) # For visualization, convert to viewable image input_img = inputs.cpu().numpy().squeeze().transpose(1,2,0) input_img = cv2.cvtColor(input_img, cv2.COLOR_RGB2BGR) input_img = helper.normalize_uint8(input_img) #helper.show_image("input_img", input_img) # Normalize for viewing pred_norm = helper.normalize_uint8(pred) #pred_norm = pred * 255 #helper.show_image("pred", pred_norm) cv2.imshow("pred", pred_norm) #print(np.max(pred_norm)) start_time = time.time() centroids = helper.get_centroids(pred) if ENABLE_TIMING: print("get_centroids time: %s s" % (time.time() - start_time)) # get_centroids time: 0.009763717651367188 s # Convert pred to color pred_norm_color = cv2.cvtColor(pred_norm, cv2.COLOR_GRAY2BGR) color_mask = deepcopy(pred_norm_color) # Color it by zeroing specific channels color_mask[:,:,[0,2]] = 0 # green #color_mask[:,:,[0,1]] = 0 # red # Create a colored overlay overlay = cv2.addWeighted(input_img, 0.5, color_mask, 0.5, 0.0, dtype=cv2.CV_8UC3) #helper.show_image("Heatmap Overlay", overlay) cv2.imshow("Heatmap Overlay", overlay) #stacked = np.hstack((pred_norm_color, overlay)) #helper.show_image("pred", stacked) draw = True if draw and len(centroids) > 0: if 1: # Draw GT for point in points: cv2.circle(input_img, tuple((point[1],point[0])), 5, (0,255,0), cv2.FILLED) for centroid in centroids: cv2.circle(input_img, tuple((centroid[1],centroid[0])), 5, (0,0,255), cv2.FILLED) helper.show_image("Predictions", input_img) def test(args): model, dataloder, device = setup_model_dataloader(args, batch_size=1) num_tp = 0 num_fp = 0 num_fn = 0 for i in range(len(dataloder)): inputs, mask, gt_points = next(iter(dataloder)) inputs = torch.unsqueeze(inputs[0], 0) gt_points = gt_points[0] # Forward pass pred = helper.model_forward(model, inputs, device, ENABLE_TIMING) # Get centroids from resulting heatmap pred_pts = helper.get_centroids(pred) # Compare pred pts to GT pairs = helper.calculate_pairs(pred_pts, gt_points, args.threshold) if len(pairs) > 0: # Calculate stats on the predictions sample_tp, sample_fp, sample_fn = helper.calculate_stats(pred_pts, gt_points, pairs) num_tp += sample_tp num_fp += sample_fp num_fn += sample_fn if args.debug: ic("TP: ", sample_tp) ic("FP: ", sample_fp) ic("FN: ", sample_fn) elif args.debug: print("No matches found") if args.debug: # For visualization, convert to viewable image input_img = inputs.cpu().numpy().squeeze().transpose(1,2,0) input_img = cv2.cvtColor(input_img, cv2.COLOR_RGB2BGR) input_img = helper.normalize_uint8(input_img) #helper.show_image("input_img", input_img) # Draw GT in green for gt_pt in gt_points: cv2.circle(input_img, tuple((gt_pt[1],gt_pt[0])), 5, (0,255,0), cv2.FILLED) # Draw all preds in red for pred_pt in pred_pts: cv2.circle(input_img, tuple((pred_pt[1],pred_pt[0])), 5, (0,0,255), cv2.FILLED) # Draw matched preds in yellow, and matched GTs in blue. # This will overwrite the red spots for good matches. # Note that pairs looks like: [(0, 2), (2, 1), (3, 3), (4, 4), (5, 0)] # Where each entry is (gt_idx, pred_idx) for pair in pairs: gt_pt = gt_points[pair[0]] pred_pt = pred_pts[pair[1]] cv2.circle(input_img, tuple((gt_pt[1],gt_pt[0])), 5, (255,0,0), cv2.FILLED) cv2.circle(input_img, tuple((pred_pt[1],pred_pt[0])), 5, (0,255,255), cv2.FILLED) cv2.namedWindow("input_img") helper.show_image("input_img", input_img) print() ic("Confusion matrix:") conf_mat_id = np.array([["TP", "FP"],["FN", "TN"]]) ic(conf_mat_id) conf_mat = np.array([[num_tp, num_fp],[num_fn,0]]) ic(conf_mat) precision = num_tp / (num_tp + num_fp) recall = num_tp / (num_tp + num_fn) f1 = 2* precision * recall / (precision + recall) ic("Precision: ", precision) ic("Recall: ", recall) ic("F1 Score: ", f1) model_dir = os.path.abspath(args.model_dir) result_file = os.path.join(model_dir, "results.txt") with open(result_file, "w") as f: f.write("Confusion matrix:\n") f.writelines(str(conf_mat_id) + '\n') f.writelines(str(conf_mat) + '\n') f.writelines("Precision: %f\n" % precision) f.writelines("Recall: %f\n" % recall) f.writelines("F1 Score: %f\n" % f1) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--data_dir', default='/data/datasets/bees/ak_bees/images', type=str, help='Dataset dir') parser.add_argument('--model_dir', default='./results/latest', type=str, help='results/<datetime> dir') parser.add_argument('--debug', action='store_true', default=False, help='Enable debugging prints and vis') parser.add_argument('-t', '--threshold', type=int, default=15, help='Pixel distance threshold for matching') subparsers = parser.add_subparsers() parser_infer = subparsers.add_parser('infer') parser_infer.set_defaults(func=inference) parser_test = subparsers.add_parser('test') parser_test.set_defaults(func=test) args = parser.parse_args() args.func(args)
[ "icecream.ic", "cv2.imshow", "numpy.array", "copy.deepcopy", "helper.get_centroids", "bee_dataloader.BeePointDataset", "helper.calculate_stats", "argparse.ArgumentParser", "torch.unsqueeze", "cv2.addWeighted", "helper.normalize_uint8", "model.ResNetUNet", "pickle.load", "cv2.cvtColor", "...
[((789, 823), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'linewidth': '(240)'}), '(linewidth=240)\n', (808, 823), True, 'import numpy as np\n'), ((966, 987), 'model.ResNetUNet', 'ResNetUNet', (['num_class'], {}), '(num_class)\n', (976, 987), False, 'from model import ResNetUNet\n'), ((998, 1018), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (1010, 1018), False, 'import torch\n'), ((1033, 1079), 'os.path.join', 'os.path.join', (['args.model_dir', '"""best_model.pth"""'], {}), "(args.model_dir, 'best_model.pth')\n", (1045, 1079), False, 'import os\n'), ((1379, 1418), 'bee_dataloader.BeePointDataset', 'BeePointDataset', ([], {'root_dir': 'args.data_dir'}), '(root_dir=args.data_dir)\n', (1394, 1418), False, 'from bee_dataloader import BeePointDataset\n'), ((5968, 5991), 'icecream.ic', 'ic', (['"""Confusion matrix:"""'], {}), "('Confusion matrix:')\n", (5970, 5991), False, 'from icecream import ic\n'), ((6007, 6045), 'numpy.array', 'np.array', (["[['TP', 'FP'], ['FN', 'TN']]"], {}), "([['TP', 'FP'], ['FN', 'TN']])\n", (6015, 6045), True, 'import numpy as np\n'), ((6046, 6061), 'icecream.ic', 'ic', (['conf_mat_id'], {}), '(conf_mat_id)\n', (6048, 6061), False, 'from icecream import ic\n'), ((6074, 6115), 'numpy.array', 'np.array', (['[[num_tp, num_fp], [num_fn, 0]]'], {}), '([[num_tp, num_fp], [num_fn, 0]])\n', (6082, 6115), True, 'import numpy as np\n'), ((6115, 6127), 'icecream.ic', 'ic', (['conf_mat'], {}), '(conf_mat)\n', (6117, 6127), False, 'from icecream import ic\n'), ((6257, 6285), 'icecream.ic', 'ic', (['"""Precision: """', 'precision'], {}), "('Precision: ', precision)\n", (6259, 6285), False, 'from icecream import ic\n'), ((6287, 6309), 'icecream.ic', 'ic', (['"""Recall: """', 'recall'], {}), "('Recall: ', recall)\n", (6289, 6309), False, 'from icecream import ic\n'), ((6311, 6331), 'icecream.ic', 'ic', (['"""F1 Score: """', 'f1'], {}), "('F1 Score: ', f1)\n", (6313, 6331), False, 'from icecream import ic\n'), ((6347, 6378), 'os.path.abspath', 'os.path.abspath', (['args.model_dir'], {}), '(args.model_dir)\n', (6362, 6378), False, 'import os\n'), ((6394, 6432), 'os.path.join', 'os.path.join', (['model_dir', '"""results.txt"""'], {}), "(model_dir, 'results.txt')\n", (6406, 6432), False, 'import os\n'), ((6745, 6770), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6768, 6770), False, 'import argparse\n'), ((1103, 1148), 'torch.load', 'torch.load', (['model_file'], {'map_location': '"""cuda:0"""'}), "(model_file, map_location='cuda:0')\n", (1113, 1148), False, 'import torch\n'), ((1505, 1524), 'pickle.load', 'pickle.load', (['dbfile'], {}), '(dbfile)\n', (1516, 1524), False, 'import pickle\n'), ((1622, 1731), 'torch.utils.data.DataLoader', 'DataLoader', (['test_ds'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(1)', 'collate_fn': 'helper.bee_collate_fn'}), '(test_ds, batch_size=batch_size, shuffle=True, num_workers=1,\n collate_fn=helper.bee_collate_fn)\n', (1632, 1731), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((1791, 1899), 'torch.utils.data.DataLoader', 'DataLoader', (['bee_ds'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(1)', 'collate_fn': 'helper.bee_collate_fn'}), '(bee_ds, batch_size=batch_size, shuffle=True, num_workers=1,\n collate_fn=helper.bee_collate_fn)\n', (1801, 1899), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((2274, 2303), 'torch.unsqueeze', 'torch.unsqueeze', (['inputs[0]', '(0)'], {}), '(inputs[0], 0)\n', (2289, 2303), False, 'import torch\n'), ((2334, 2392), 'helper.model_forward', 'helper.model_forward', (['model', 'inputs', 'device', 'ENABLE_TIMING'], {}), '(model, inputs, device, ENABLE_TIMING)\n', (2354, 2392), False, 'import helper\n'), ((2519, 2561), 'cv2.cvtColor', 'cv2.cvtColor', (['input_img', 'cv2.COLOR_RGB2BGR'], {}), '(input_img, cv2.COLOR_RGB2BGR)\n', (2531, 2561), False, 'import cv2\n'), ((2576, 2609), 'helper.normalize_uint8', 'helper.normalize_uint8', (['input_img'], {}), '(input_img)\n', (2598, 2609), False, 'import helper\n'), ((2696, 2724), 'helper.normalize_uint8', 'helper.normalize_uint8', (['pred'], {}), '(pred)\n', (2718, 2724), False, 'import helper\n'), ((2793, 2822), 'cv2.imshow', 'cv2.imshow', (['"""pred"""', 'pred_norm'], {}), "('pred', pred_norm)\n", (2803, 2822), False, 'import cv2\n'), ((2867, 2878), 'time.time', 'time.time', ([], {}), '()\n', (2876, 2878), False, 'import time\n'), ((2893, 2919), 'helper.get_centroids', 'helper.get_centroids', (['pred'], {}), '(pred)\n', (2913, 2919), False, 'import helper\n'), ((3101, 3144), 'cv2.cvtColor', 'cv2.cvtColor', (['pred_norm', 'cv2.COLOR_GRAY2BGR'], {}), '(pred_norm, cv2.COLOR_GRAY2BGR)\n', (3113, 3144), False, 'import cv2\n'), ((3160, 3185), 'copy.deepcopy', 'deepcopy', (['pred_norm_color'], {}), '(pred_norm_color)\n', (3168, 3185), False, 'from copy import deepcopy\n'), ((3341, 3413), 'cv2.addWeighted', 'cv2.addWeighted', (['input_img', '(0.5)', 'color_mask', '(0.5)', '(0.0)'], {'dtype': 'cv2.CV_8UC3'}), '(input_img, 0.5, color_mask, 0.5, 0.0, dtype=cv2.CV_8UC3)\n', (3356, 3413), False, 'import cv2\n'), ((3465, 3503), 'cv2.imshow', 'cv2.imshow', (['"""Heatmap Overlay"""', 'overlay'], {}), "('Heatmap Overlay', overlay)\n", (3475, 3503), False, 'import cv2\n'), ((4152, 4181), 'torch.unsqueeze', 'torch.unsqueeze', (['inputs[0]', '(0)'], {}), '(inputs[0], 0)\n', (4167, 4181), False, 'import torch\n'), ((4235, 4293), 'helper.model_forward', 'helper.model_forward', (['model', 'inputs', 'device', 'ENABLE_TIMING'], {}), '(model, inputs, device, ENABLE_TIMING)\n', (4255, 4293), False, 'import helper\n'), ((4348, 4374), 'helper.get_centroids', 'helper.get_centroids', (['pred'], {}), '(pred)\n', (4368, 4374), False, 'import helper\n'), ((4413, 4472), 'helper.calculate_pairs', 'helper.calculate_pairs', (['pred_pts', 'gt_points', 'args.threshold'], {}), '(pred_pts, gt_points, args.threshold)\n', (4435, 4472), False, 'import helper\n'), ((1442, 1485), 'os.path.join', 'os.path.join', (['args.model_dir', '"""test_ds.pkl"""'], {}), "(args.model_dir, 'test_ds.pkl')\n", (1454, 1485), False, 'import os\n'), ((3887, 3930), 'helper.show_image', 'helper.show_image', (['"""Predictions"""', 'input_img'], {}), "('Predictions', input_img)\n", (3904, 3930), False, 'import helper\n'), ((4572, 4622), 'helper.calculate_stats', 'helper.calculate_stats', (['pred_pts', 'gt_points', 'pairs'], {}), '(pred_pts, gt_points, pairs)\n', (4594, 4622), False, 'import helper\n'), ((4982, 5024), 'cv2.cvtColor', 'cv2.cvtColor', (['input_img', 'cv2.COLOR_RGB2BGR'], {}), '(input_img, cv2.COLOR_RGB2BGR)\n', (4994, 5024), False, 'import cv2\n'), ((5040, 5073), 'helper.normalize_uint8', 'helper.normalize_uint8', (['input_img'], {}), '(input_img)\n', (5062, 5073), False, 'import helper\n'), ((5879, 5907), 'cv2.namedWindow', 'cv2.namedWindow', (['"""input_img"""'], {}), "('input_img')\n", (5894, 5907), False, 'import cv2\n'), ((5911, 5952), 'helper.show_image', 'helper.show_image', (['"""input_img"""', 'input_img'], {}), "('input_img', input_img)\n", (5928, 5952), False, 'import helper\n'), ((4714, 4735), 'icecream.ic', 'ic', (['"""TP: """', 'sample_tp'], {}), "('TP: ', sample_tp)\n", (4716, 4735), False, 'from icecream import ic\n'), ((4740, 4761), 'icecream.ic', 'ic', (['"""FP: """', 'sample_fp'], {}), "('FP: ', sample_fp)\n", (4742, 4761), False, 'from icecream import ic\n'), ((4766, 4787), 'icecream.ic', 'ic', (['"""FN: """', 'sample_fn'], {}), "('FN: ', sample_fn)\n", (4768, 4787), False, 'from icecream import ic\n'), ((2979, 2990), 'time.time', 'time.time', ([], {}), '()\n', (2988, 2990), False, 'import time\n')]
import os import json import pickle import numpy as np import torch from sklearn.metrics import average_precision_score import random def save_pkl(pkl_data, save_path): with open(save_path, 'wb') as f: pickle.dump(pkl_data, f) def load_pkl(load_path): with open(load_path, 'rb') as f: pkl_data = pickle.load(f) return pkl_data def save_json(json_data, save_path): with open(save_path, 'w') as f: json.dump(json_data, f) def load_json(load_path): with open(load_path, 'r') as f: json_data = json.load(f) return json_data def save_state_dict(state_dict, save_path): torch.save(state_dict, save_path) def creat_folder(path): if not os.path.exists(path): os.makedirs(path) def set_random_seed(seed_number): torch.manual_seed(seed_number) np.random.seed(seed_number) random.seed(seed_number) torch.cuda.seed(seed_number) def write_info(filename, info): with open(filename, 'w') as f: f.write(info) def compute_weighted_AP(target, predict_prob, class_weight_list): per_class_AP = [] for i in range(target.shape[1] - 1): class_weight = target[:, i]*class_weight_list[i] \ + (1-target[:, i])*np.ones(class_weight_list[i].shape) per_class_AP.append(average_precision_score(target[:, i], predict_prob[:, i], sample_weight=class_weight)) return per_class_AP def compute_mAP(per_class_AP, subclass_idx): return np.mean([per_class_AP[idx] for idx in subclass_idx]) def compute_class_weight(target): domain_label = target[:, -1] per_class_weight = [] for i in range(target.shape[1]-1): class_label = target[:, i] cp = class_label.sum() # class is positive cn = target.shape[0] - cp # class is negative cn_dn = ((class_label + domain_label)==0).sum() # class is negative, domain is negative cn_dp = ((class_label - domain_label)==-1).sum() cp_dn = ((class_label - domain_label)==1).sum() cp_dp = ((class_label + domain_label)==2).sum() per_class_weight.append( (class_label*cp + (1-class_label)*cn) / (2*( (1-class_label)*(1-domain_label)*cn_dn + (1-class_label)*domain_label*cn_dp + class_label*(1-domain_label)*cp_dn + class_label*domain_label*cp_dp ) ) ) return per_class_weight
[ "torch.manual_seed", "numpy.mean", "os.path.exists", "torch.cuda.seed", "pickle.dump", "os.makedirs", "numpy.ones", "sklearn.metrics.average_precision_score", "pickle.load", "random.seed", "numpy.random.seed", "torch.save", "json.load", "json.dump" ]
[((629, 662), 'torch.save', 'torch.save', (['state_dict', 'save_path'], {}), '(state_dict, save_path)\n', (639, 662), False, 'import torch\n'), ((786, 816), 'torch.manual_seed', 'torch.manual_seed', (['seed_number'], {}), '(seed_number)\n', (803, 816), False, 'import torch\n'), ((821, 848), 'numpy.random.seed', 'np.random.seed', (['seed_number'], {}), '(seed_number)\n', (835, 848), True, 'import numpy as np\n'), ((853, 877), 'random.seed', 'random.seed', (['seed_number'], {}), '(seed_number)\n', (864, 877), False, 'import random\n'), ((882, 910), 'torch.cuda.seed', 'torch.cuda.seed', (['seed_number'], {}), '(seed_number)\n', (897, 910), False, 'import torch\n'), ((1518, 1570), 'numpy.mean', 'np.mean', (['[per_class_AP[idx] for idx in subclass_idx]'], {}), '([per_class_AP[idx] for idx in subclass_idx])\n', (1525, 1570), True, 'import numpy as np\n'), ((215, 239), 'pickle.dump', 'pickle.dump', (['pkl_data', 'f'], {}), '(pkl_data, f)\n', (226, 239), False, 'import pickle\n'), ((322, 336), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (333, 336), False, 'import pickle\n'), ((439, 462), 'json.dump', 'json.dump', (['json_data', 'f'], {}), '(json_data, f)\n', (448, 462), False, 'import json\n'), ((546, 558), 'json.load', 'json.load', (['f'], {}), '(f)\n', (555, 558), False, 'import json\n'), ((699, 719), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (713, 719), False, 'import os\n'), ((729, 746), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (740, 746), False, 'import os\n'), ((1308, 1398), 'sklearn.metrics.average_precision_score', 'average_precision_score', (['target[:, i]', 'predict_prob[:, i]'], {'sample_weight': 'class_weight'}), '(target[:, i], predict_prob[:, i], sample_weight=\n class_weight)\n', (1331, 1398), False, 'from sklearn.metrics import average_precision_score\n'), ((1244, 1279), 'numpy.ones', 'np.ones', (['class_weight_list[i].shape'], {}), '(class_weight_list[i].shape)\n', (1251, 1279), True, 'import numpy as np\n')]
import networkx as nx import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer, CountVectorizer from sklearn.metrics.pairwise import cosine_similarity from sumy.utils import get_stop_words import re import math import warnings warnings.simplefilter("ignore", UserWarning) class SentenceFeature(): def __init__(self, parser) -> None: self.sents = parser.sents self.sents_i = list(range(len(self.sents))) # list contains index of each sentence # self.chunked_sentences = parser.chunked_sentences() # self.entities_name = self.ner(self.chunked_sentences) self.vectorizer = CountVectorizer(stop_words=get_stop_words("english")) self.X = self.vectorizer.fit_transform(self.sents) self.processed_words = parser.processed_words self.unprocessed_words = parser.unprocessed_words def _get_name_entity(self, sent_i): return len(self.entities_name[sent_i]) def _get_position(self, sent_i): count = self.sents_i[-1] position = 1 if count != 0: position = sent_i / count return position def sentence_position(self, sent_i): """ :param sent_i: int Index of a sentence :return: float """ return len(self.sents) - sent_i / len(self.sents) def get_noun_adj(self, sent_i): words_num = len(self.unprocessed_words[sent_i]) if words_num != 0: return len(self.processed_words[sent_i]) / words_num return len(self.processed_words[sent_i]) def numerical_data(self, sent_i): """ :param sent_i: int Index of a sentence :return: float """ word_len = len(self.unprocessed_words[sent_i]) if word_len != 0: return len(re.findall(r'\d+(.\d+)?', self.sents[sent_i])) / word_len return 0 def sentence_length(self, sent_i): return len(self.unprocessed_words[sent_i]) / np.max(len(self.unprocessed_words)) def max_leng_sent(self): return np.max(len(self.unprocessed_words)) def _get_doc_first(self, sent_i): """ :param sent_i: int Index of a sentence :return: int 1, input sentence is the first sentence of a document. 0, input sentence is not the first sentence of a document. """ # return int(sent_i == 0) doc_first = int(sent_i == 0) if doc_first == 0: doc_first = 0 return doc_first def _get_length(self, sent_i): """ :param sent_i: int Index of a sentence :return: int The number of words in a sentence """ return len(self.unprocessed_words[sent_i]) def get_surface_features(self, sents_i=None): """ Surface features are based on structure of documents or sentences. :param sents_i: list or int, optional list contains multiple sentence indices int indicate a single sentence index :return: list 1-dimensional list consists of position, doc_first, para_first, length and quote features for int sents_i parameter 2-dimensional list consists of position, doc_first, para_first, length and quote features for list sents_i parameter """ # solely get surface features for unlabeled data if sents_i is None: sents_i = self.sents_i def get_features(sent_i): position = self._get_position(sent_i) # get 1/sentence no doc_first = self._get_doc_first(sent_i) length = self._get_length(sent_i) return [position, doc_first, length] surface_features = [] if type(sents_i) is list: # get surface features for multiple samples for labeled data for sent_i in sents_i: surface_feature = get_features(sent_i) surface_features.append(surface_feature) # self.features_name = ["position", "doc_first", "para_first", "length", "quote"] else: # get surface features for single sample for labeled data surface_features = get_features(sents_i) surface_features = np.asarray(surface_features) return surface_features def _get_stopwords_ratio(self, sent_i): """ :param sent_i: int Index of a sentence :return: float, in between [0, 1] Stop words ratio of s """ words_num = len(self.unprocessed_words[sent_i]) if words_num != 0: non_stopwords_num = len(self.processed_words[sent_i]) stopwords_ratio = (words_num - non_stopwords_num) / words_num else: stopwords_ratio = 1 return stopwords_ratio def _get_tf_idf(self, sent_i): a = self._get_avg_doc_freq(sent_i) if a <= 0: return 0 return self._get_avg_term_freq(sent_i) * math.log(a) def _get_all_tf_idf(self): score = [] for idx, val in enumerate(self.sents): a = self._get_avg_doc_freq(idx) if a <= 0: b = 0 else: b = (self._get_avg_term_freq(idx) * math.log(a)) score.append(b) return score def _get_centroid_similarity(self, sent_i): tfidfScore = self._get_all_tf_idf() centroidIndex = tfidfScore.index(max(tfidfScore)) return self._cal_cosine_similarity([self.sents[sent_i], self.sents[centroidIndex]]) def _get_avg_term_freq(self, sent_i): """ :param sent_i: int Index of a sentence :param vectorizer: sklearn.feature_extraction.text.CountVectorizer :param X: array, [n_samples, n_features] Document-term matrix. :return: float Average Term Frequency """ GTF = np.ravel(self.X.sum(axis=0)) # sum each columns to get total counts for each word unprocessed_words = self.unprocessed_words[sent_i] total_TF = 0 count = 0 for w in unprocessed_words: w_i_in_array = self.vectorizer.vocabulary_.get(w) # map from word to column index if w_i_in_array: total_TF += GTF[w_i_in_array] count += 1 if count != 0: avg_TF = total_TF / count else: avg_TF = 0 return avg_TF def _get_avg_doc_freq(self, sent_i): """ :param sent_i: int Index of a sentence :param vectorizer: sklearn.feature_extraction.text.CountVectorizer :param X: array, [n_samples, n_features] Document-term matrix. :return: float Average Document Frequency """ unprocessed_words = self.unprocessed_words[sent_i] total_DF = 0 count = 0 for w in unprocessed_words: w_i_in_array = self.vectorizer.vocabulary_.get(w) # map from word to column index if w_i_in_array: total_DF += len(self.X[:, w_i_in_array].nonzero()[0]) count += 1 if count != 0: avg_DF = total_DF / count else: avg_DF = 0 return avg_DF def get_content_features(self, sents_i): # solely get content features for unlabeled data if sents_i is None: sents_i = self.sents_i def get_features(sent_i): stop = self._get_stopwords_ratio(sent_i) TF = self._get_avg_term_freq(sent_i) DF = self._get_avg_doc_freq(sent_i) # Emb = self._get_emb(sent_i, word_vectors) # core_rank_score = self._get_avg_core_rank_score(sent_i) return [stop, TF, DF] content_features = [] if type(sents_i) is list: # get surface features for multiple samples for labeled data for sent_i in sents_i: content_feature = get_features(sent_i) content_features.append(content_feature) # self.features_name = ["stop", "TF", "DF", "core_rank_score"] else: # get surface features for single sample for labeled data content_features = get_features(sents_i) content_features = np.asarray(content_features) return content_features def _cal_cosine_similarity(self, documents): """ :param documents: list :return: float, in between [0, 1] """ tfidf_vectorizer = TfidfVectorizer() try: tfidf_matrix = tfidf_vectorizer.fit_transform(documents) similarity = cosine_similarity(tfidf_matrix[0, :], tfidf_matrix[1, :])[0][0] except ValueError: if documents[0] == documents[1]: similarity = 1.0 else: similarity = 0.0 return similarity def _get_first_rel_doc(self, sent_i): """ :param sent_i: int Index of a sentence :return: float Similarity with the first sentence in the document """ first_sent_doc = self.sents[0] sent = self.sents[sent_i] relevance = self._cal_cosine_similarity([first_sent_doc, sent]) return relevance def page_rank_rel(self, thres=0.1): """ PageRank value of the sentence based on the sentence map :param thres: int Every two sentences are regarded relevant if their similarity is above a threshold. :return: dict Dictionary of index nodes with PageRank as value. """ G = nx.Graph() # Build a sentence map. # Every two sentences are regarded relevant if their similarity is above a threshold. # Every two relevant sentences are connected with a unidirectional link. for i in self.sents_i[:-2]: for j in self.sents_i[i + 1:]: sim = self._cal_cosine_similarity([self.sents[i], self.sents[j]]) if sim > thres: G.add_edge(i, j) pr = nx.pagerank(G) return pr def get_relevance_features(self, sents_i): """ Relevance features are incorporated to exploit inter-sentence relationships. :param sents_i: list or int, optional list contains multiple sentence indices int indicate a single sentence index :return: list 1-dimensional list consists of first_rel_doc, first_rel_para and page_rank_rel features for int sents_i parameter 2-dimensional list consists of first_rel_doc, first_rel_para and page_rank_rel features for list sents_i parameter """ # solely get relevance features for unlabeled data if sents_i is None: sents_i = self.sents_i try: self.pr except AttributeError: self.pr = self.page_rank_rel() # global_avg_word_emb = self._get_global_avg_word_emb(word_vectors) def get_features(sent_i): first_rel_doc = self._get_first_rel_doc(sent_i) page_rank_rel = self.pr.get(sent_i, 0) # Emb_cos = self._get_emb_cos(sent_i, word_vectors, global_avg_word_emb) return [first_rel_doc, page_rank_rel] relevance_features = [] if type(sents_i) is list: # get surface features for multiple samples for labeled data for sent_i in sents_i: relevance_feature = get_features(sent_i) relevance_features.append(relevance_feature) # self.features_name = ["first_rel_doc", "first_rel_para", "page_rank_rel"] else: # get surface features for single sample for labeled data relevance_features = get_features(sents_i) relevance_features = np.asarray(relevance_features) return relevance_features def get_all_features(self, sent_i=None): """ Concatenate sub-features together. :param vectorizer: sklearn.feature_extraction.text.CountVectorizer :param X: Document-term matrix :param word_vectors: optional :param sent_i: index of sent :return: numpy array """ surface_features = self.get_surface_features(sent_i) content_features = self.get_content_features(sent_i) relevance_features = self.get_relevance_features(sent_i) all_feature = np.concatenate((surface_features, content_features, relevance_features), axis=0) # self.features_name = ["position", "doc_first", "para_first", "length", "quote", "stop", "TF", "DF", # "core_rank_score", "first_rel_doc", "first_rel_para", "page_rank_rel"] return all_feature def get_all_features_of_sent(self, vectorizer, X, word_vectors=None, sents_i=None): """ Concatenate sub-features together. :param vectorizer: sklearn.feature_extraction.text.CountVectorizer :param X: Document-term matrix :param word_vectors: optional :param sents_i: list :return: numpy array """ # get all feature for unlabeled data if sents_i is None: sents_i = self.sents_i all_features = [] for sent_i in sents_i: surface_features = self.get_surface_features(sent_i) content_features = self.get_content_features(sent_i, vectorizer, X, word_vectors) relevance_features = self.get_relevance_features(sent_i) all_feature = np.concatenate((surface_features, content_features, relevance_features), axis=0) all_features.append(all_feature) # self.features_name = ["position", "doc_first", "para_first", "length", "quote", "stop", "TF", "DF", # "core_rank_score", "first_rel_doc", "first_rel_para", "page_rank_rel"] return all_features @staticmethod def get_global_term_freq(parsers): """ :param parsers: newssum.parser.StoryParser :return: tuple, (vectorizer, X) vectorizer, sklearn.feature_extraction.text.CountVectorizer. X, Document-term matrix. """ vectorizer = CountVectorizer(stop_words=get_stop_words("english")) if type(parsers) is list: corpus = [parser.body for parser in parsers] else: corpus = [parsers.body] X = vectorizer.fit_transform(corpus) return vectorizer, X def extract_entity_names(self, t): entity_names = [] if hasattr(t, 'label') and t.label: if t.label() == 'NE': entity_names.append(' '.join([child[0] for child in t])) else: for child in t: entity_names.extend(self.extract_entity_names(child)) return entity_names def ner(self, chunked_sentences): entity_names = [] for tree in chunked_sentences: # print(self.extract_entity_names(tree)) entity_names.append(self.extract_entity_names(tree)) return entity_names
[ "sklearn.metrics.pairwise.cosine_similarity", "numpy.asarray", "networkx.Graph", "math.log", "sklearn.feature_extraction.text.TfidfVectorizer", "numpy.concatenate", "sumy.utils.get_stop_words", "warnings.simplefilter", "re.findall", "networkx.pagerank" ]
[((268, 312), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'UserWarning'], {}), "('ignore', UserWarning)\n", (289, 312), False, 'import warnings\n'), ((4282, 4310), 'numpy.asarray', 'np.asarray', (['surface_features'], {}), '(surface_features)\n', (4292, 4310), True, 'import numpy as np\n'), ((8343, 8371), 'numpy.asarray', 'np.asarray', (['content_features'], {}), '(content_features)\n', (8353, 8371), True, 'import numpy as np\n'), ((8579, 8596), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {}), '()\n', (8594, 8596), False, 'from sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer, CountVectorizer\n'), ((9684, 9694), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (9692, 9694), True, 'import networkx as nx\n'), ((10147, 10161), 'networkx.pagerank', 'nx.pagerank', (['G'], {}), '(G)\n', (10158, 10161), True, 'import networkx as nx\n'), ((11898, 11928), 'numpy.asarray', 'np.asarray', (['relevance_features'], {}), '(relevance_features)\n', (11908, 11928), True, 'import numpy as np\n'), ((12505, 12590), 'numpy.concatenate', 'np.concatenate', (['(surface_features, content_features, relevance_features)'], {'axis': '(0)'}), '((surface_features, content_features, relevance_features), axis=0\n )\n', (12519, 12590), True, 'import numpy as np\n'), ((5016, 5027), 'math.log', 'math.log', (['a'], {}), '(a)\n', (5024, 5027), False, 'import math\n'), ((13614, 13699), 'numpy.concatenate', 'np.concatenate', (['(surface_features, content_features, relevance_features)'], {'axis': '(0)'}), '((surface_features, content_features, relevance_features), axis=0\n )\n', (13628, 13699), True, 'import numpy as np\n'), ((685, 710), 'sumy.utils.get_stop_words', 'get_stop_words', (['"""english"""'], {}), "('english')\n", (699, 710), False, 'from sumy.utils import get_stop_words\n'), ((14313, 14338), 'sumy.utils.get_stop_words', 'get_stop_words', (['"""english"""'], {}), "('english')\n", (14327, 14338), False, 'from sumy.utils import get_stop_words\n'), ((1837, 1883), 're.findall', 're.findall', (['"""\\\\d+(.\\\\d+)?"""', 'self.sents[sent_i]'], {}), "('\\\\d+(.\\\\d+)?', self.sents[sent_i])\n", (1847, 1883), False, 'import re\n'), ((5285, 5296), 'math.log', 'math.log', (['a'], {}), '(a)\n', (5293, 5296), False, 'import math\n'), ((8704, 8761), 'sklearn.metrics.pairwise.cosine_similarity', 'cosine_similarity', (['tfidf_matrix[0, :]', 'tfidf_matrix[1, :]'], {}), '(tfidf_matrix[0, :], tfidf_matrix[1, :])\n', (8721, 8761), False, 'from sklearn.metrics.pairwise import cosine_similarity\n')]
"""Handles input args for training models.""" import numpy from gewittergefahr.gg_utils import error_checking from generalexam.ge_io import processed_narr_io TIME_FORMAT = '%Y%m%d%H' INPUT_MODEL_FILE_ARG_NAME = 'input_model_file_name' PREDICTOR_NAMES_ARG_NAME = 'narr_predictor_names' PRESSURE_LEVEL_ARG_NAME = 'pressure_level_mb' DILATION_DISTANCE_ARG_NAME = 'dilation_distance_metres' LEAD_TIME_ARG_NAME = 'num_lead_time_steps' PREDICTOR_TIMES_ARG_NAME = 'predictor_time_step_offsets' NUM_EX_PER_TIME_ARG_NAME = 'num_examples_per_time' WEIGHT_LOSS_ARG_NAME = 'weight_loss_function' DOWNSAMPLING_FRACTIONS_ARG_NAME = 'downsampling_fractions' NARR_DIR_ARG_NAME = 'input_narr_dir_name' FRONT_DIR_ARG_NAME = 'input_frontal_grid_dir_name' NARR_MASK_FILE_ARG_NAME = 'input_narr_mask_file_name' TRAINING_DIR_ARG_NAME = 'input_training_dir_name' VALIDATION_DIR_ARG_NAME = 'input_validation_dir_name' FIRST_TRAINING_TIME_ARG_NAME = 'first_training_time_string' LAST_TRAINING_TIME_ARG_NAME = 'last_training_time_string' FIRST_VALIDATION_TIME_ARG_NAME = 'first_validation_time_string' LAST_VALIDATION_TIME_ARG_NAME = 'last_validation_time_string' NUM_EX_PER_BATCH_ARG_NAME = 'num_examples_per_batch' NUM_EPOCHS_ARG_NAME = 'num_epochs' NUM_TRAINING_BATCHES_ARG_NAME = 'num_training_batches_per_epoch' NUM_VALIDATION_BATCHES_ARG_NAME = 'num_validation_batches_per_epoch' OUTPUT_FILE_ARG_NAME = 'output_file_name' INPUT_MODEL_FILE_HELP_STRING = ( 'Path to input file (containing either trained or untrained CNN). Will be ' 'read by `traditional_cnn.read_keras_model`. The architecture of this CNN ' 'will be copied.') PREDICTOR_NAMES_HELP_STRING = ( 'List of predictor variables (channels). Each must be accepted by ' '`processed_narr_io.check_field_name`.') PRESSURE_LEVEL_HELP_STRING = ( 'Pressure level (millibars) for predictors in list `{0:s}`.' ).format(PREDICTOR_NAMES_ARG_NAME) DILATION_DISTANCE_HELP_STRING = ( 'Dilation distance for target variable (front label). Each warm-frontal or' ' cold-frontal grid cell will be dilated by this amount.') LEAD_TIME_HELP_STRING = ( 'Number of time steps (1 time step = 3 hours) between target time and last ' 'possible predictor time. If you want target time = predictor time ' '(recommended), leave this alone.') PREDICTOR_TIMES_HELP_STRING = ( 'List of time offsets (each between one predictor time and the last ' 'possible predictor time). For example, if `{0:s}` = 2 and ' '`{1:s}` = [2 4 6 8], predictor times will be 4, 6, 8, and 10 time steps ' '-- or 12, 18, 24, and 30 hours -- before target time.' ).format(LEAD_TIME_ARG_NAME, PREDICTOR_TIMES_ARG_NAME) NUM_EX_PER_TIME_HELP_STRING = ( 'Average number of training examples for each target time. This constraint' ' is applied to each batch separately.') WEIGHT_LOSS_HELP_STRING = ( 'Boolean flag. If 1, each class in the loss function will be weighted by ' 'the inverse of its frequency in training data. If 0, no such weighting ' 'will be done.') DOWNSAMPLING_FRACTIONS_HELP_STRING = ( 'List of downsampling fractions. The [k]th value is the fraction for the ' '[k]th class. Fractions must add up to 1.0. If you do not want ' 'downsampling, make this a one-item list.') NARR_DIR_HELP_STRING = ( 'Name of top-level directory with NARR data (predictors). Files therein ' 'will be found by `processed_narr_io.find_file_for_one_time` and read by ' '`processed_narr_io.read_fields_from_file`.') FRONT_DIR_HELP_STRING = ( 'Name of top-level directory with gridded front labels (targets). Files ' 'therein will be found by `fronts_io.find_file_for_one_time` and read by ' '`fronts_io.read_narr_grids_from_file`.') NARR_MASK_FILE_HELP_STRING = ( 'Path to file with NARR mask (will be read by ' '`machine_learning_utils.read_narr_mask`). Masked grid cells cannot be ' 'used as the center of a training example. If you do not want masking, ' 'make this empty ("").') TRAINING_DIR_HELP_STRING = ( 'Name of top-level directory with training data. Files therein (containing' ' downsized 3-D examples, with 2 spatial dimensions) will be found by ' '`training_validation_io.find_downsized_3d_example_file` (with shuffled = ' 'True) and read by `training_validation_io.read_downsized_3d_examples`.') VALIDATION_DIR_HELP_STRING = ( 'Same as `{0:s}` but for on-the-fly validation.' ).format(TRAINING_DIR_ARG_NAME) TRAINING_TIME_HELP_STRING = ( 'Time (format "yyyymmddHH"). Only examples from the period ' '`{0:s}`...`{1:s}` will be used for training.' ).format(FIRST_TRAINING_TIME_ARG_NAME, LAST_TRAINING_TIME_ARG_NAME) VALIDATION_TIME_HELP_STRING = ( 'Time (format "yyyymmddHH"). Only examples from the period ' '`{0:s}`...`{1:s}` will be used for validation.' ).format(FIRST_VALIDATION_TIME_ARG_NAME, LAST_VALIDATION_TIME_ARG_NAME) NUM_EX_PER_BATCH_HELP_STRING = ( 'Number of examples in each training or validation batch.') NUM_EPOCHS_HELP_STRING = 'Number of training epochs.' NUM_TRAINING_BATCHES_HELP_STRING = 'Number of training batches in each epoch.' NUM_VALIDATION_BATCHES_HELP_STRING = ( 'Number of validation batches in each epoch.') OUTPUT_FILE_HELP_STRING = ( 'Path to output file (HDF5 format). The trained CNN model will be saved ' 'here.') DEFAULT_NARR_PREDICTOR_NAMES = [ processed_narr_io.TEMPERATURE_NAME, processed_narr_io.SPECIFIC_HUMIDITY_NAME, processed_narr_io.U_WIND_GRID_RELATIVE_NAME, processed_narr_io.V_WIND_GRID_RELATIVE_NAME ] DEFAULT_PRESSURE_LEVEL_MB = 1000 DEFAULT_DILATION_DISTANCE_METRES = 50000 DEFAULT_NUM_EXAMPLES_PER_TIME = 8 DEFAULT_WEIGHT_LOSS_FLAG = 0 DEFAULT_DOWNSAMPLING_FRACTIONS = numpy.array([0.5, 0.25, 0.25]) DEFAULT_TOP_NARR_DIR_NAME = '/condo/swatwork/ralager/narr_data/processed' DEFAULT_TOP_FRONT_DIR_NAME = ( '/condo/swatwork/ralager/fronts/narr_grids/no_dilation' ) DEFAULT_NARR_MASK_FILE_NAME = ( '/condo/swatwork/ralager/fronts/narr_grids/narr_mask.p' ) DEFAULT_TOP_TRAINING_DIR_NAME = ( '/condo/swatwork/ralager/narr_data/downsized_3d_examples/z_normalized/' 'shuffled/training' ) DEFAULT_TOP_VALIDATION_DIR_NAME = ( '/condo/swatwork/ralager/narr_data/downsized_3d_examples/z_normalized/' 'shuffled/validation' ) DEFAULT_FIRST_TRAINING_TIME_STRING = '2008110515' DEFAULT_LAST_TRAINING_TIME_STRING = '2014122421' DEFAULT_FIRST_VALIDN_TIME_STRING = '2015010100' DEFAULT_LAST_VALIDN_TIME_STRING = '2015122421' DEFAULT_NUM_EXAMPLES_PER_BATCH = 1024 DEFAULT_NUM_EPOCHS = 100 DEFAULT_NUM_TRAINING_BATCHES_PER_EPOCH = 32 DEFAULT_NUM_VALIDATION_BATCHES_PER_EPOCH = 16 def add_input_args(argument_parser, use_downsized_files): """Adds input args to ArgumentParser object. :param argument_parser: Instance of `argparse.ArgumentParser` (may already contain some input args). :param use_downsized_files: Boolean flag. If True, the net will be trained with pre-processed files that contain downsized examples, readable by `training_validation_io.read_downsized_3d_examples`. If False, the net will be trained with examples created on the fly from raw NARR data and gridded front labels. :return: argument_parser: Same as input but with new args added. """ error_checking.assert_is_boolean(use_downsized_files) argument_parser.add_argument( '--' + INPUT_MODEL_FILE_ARG_NAME, type=str, required=True, help=INPUT_MODEL_FILE_HELP_STRING) argument_parser.add_argument( '--' + PREDICTOR_NAMES_ARG_NAME, type=str, nargs='+', required=False, default=DEFAULT_NARR_PREDICTOR_NAMES, help=PREDICTOR_NAMES_HELP_STRING) if use_downsized_files: argument_parser.add_argument( '--' + TRAINING_DIR_ARG_NAME, type=str, required=False, default=DEFAULT_TOP_TRAINING_DIR_NAME, help=TRAINING_DIR_HELP_STRING) argument_parser.add_argument( '--' + VALIDATION_DIR_ARG_NAME, type=str, required=False, default=DEFAULT_TOP_VALIDATION_DIR_NAME, help=VALIDATION_DIR_HELP_STRING) else: argument_parser.add_argument( '--' + PRESSURE_LEVEL_ARG_NAME, type=int, required=False, default=DEFAULT_PRESSURE_LEVEL_MB, help=PRESSURE_LEVEL_HELP_STRING) argument_parser.add_argument( '--' + DILATION_DISTANCE_ARG_NAME, type=int, required=False, default=DEFAULT_DILATION_DISTANCE_METRES, help=DILATION_DISTANCE_HELP_STRING) argument_parser.add_argument( '--' + LEAD_TIME_ARG_NAME, type=int, required=False, default=-1, help=LEAD_TIME_HELP_STRING) argument_parser.add_argument( '--' + PREDICTOR_TIMES_ARG_NAME, type=int, nargs='+', required=False, default=[-1], help=PREDICTOR_TIMES_HELP_STRING) argument_parser.add_argument( '--' + NUM_EX_PER_TIME_ARG_NAME, type=int, required=False, default=DEFAULT_NUM_EXAMPLES_PER_TIME, help=NUM_EX_PER_TIME_HELP_STRING) argument_parser.add_argument( '--' + WEIGHT_LOSS_ARG_NAME, type=int, required=False, default=DEFAULT_WEIGHT_LOSS_FLAG, help=WEIGHT_LOSS_HELP_STRING) argument_parser.add_argument( '--' + DOWNSAMPLING_FRACTIONS_ARG_NAME, type=float, nargs='+', required=False, default=DEFAULT_DOWNSAMPLING_FRACTIONS, help=DOWNSAMPLING_FRACTIONS_HELP_STRING) argument_parser.add_argument( '--' + NARR_DIR_ARG_NAME, type=str, required=False, default=DEFAULT_TOP_NARR_DIR_NAME, help=NARR_DIR_HELP_STRING) argument_parser.add_argument( '--' + FRONT_DIR_ARG_NAME, type=str, required=False, default=DEFAULT_TOP_FRONT_DIR_NAME, help=FRONT_DIR_HELP_STRING) argument_parser.add_argument( '--' + NARR_MASK_FILE_ARG_NAME, type=str, required=False, default=DEFAULT_NARR_MASK_FILE_NAME, help=NARR_MASK_FILE_HELP_STRING) argument_parser.add_argument( '--' + FIRST_TRAINING_TIME_ARG_NAME, type=str, required=False, default=DEFAULT_FIRST_TRAINING_TIME_STRING, help=TRAINING_TIME_HELP_STRING) argument_parser.add_argument( '--' + LAST_TRAINING_TIME_ARG_NAME, type=str, required=False, default=DEFAULT_LAST_TRAINING_TIME_STRING, help=TRAINING_TIME_HELP_STRING) argument_parser.add_argument( '--' + FIRST_VALIDATION_TIME_ARG_NAME, type=str, required=False, default=DEFAULT_FIRST_VALIDN_TIME_STRING, help=VALIDATION_TIME_HELP_STRING) argument_parser.add_argument( '--' + LAST_VALIDATION_TIME_ARG_NAME, type=str, required=False, default=DEFAULT_LAST_VALIDN_TIME_STRING, help=VALIDATION_TIME_HELP_STRING) argument_parser.add_argument( '--' + NUM_EX_PER_BATCH_ARG_NAME, type=int, required=False, default=DEFAULT_NUM_EXAMPLES_PER_BATCH, help=NUM_EX_PER_BATCH_HELP_STRING) argument_parser.add_argument( '--' + NUM_EPOCHS_ARG_NAME, type=int, required=False, default=DEFAULT_NUM_EPOCHS, help=NUM_EPOCHS_HELP_STRING) argument_parser.add_argument( '--' + NUM_TRAINING_BATCHES_ARG_NAME, type=int, required=False, default=DEFAULT_NUM_TRAINING_BATCHES_PER_EPOCH, help=NUM_TRAINING_BATCHES_HELP_STRING) argument_parser.add_argument( '--' + NUM_VALIDATION_BATCHES_ARG_NAME, type=int, required=False, default=DEFAULT_NUM_VALIDATION_BATCHES_PER_EPOCH, help=NUM_VALIDATION_BATCHES_HELP_STRING) argument_parser.add_argument( '--' + OUTPUT_FILE_ARG_NAME, type=str, required=True, help=OUTPUT_FILE_HELP_STRING) return argument_parser
[ "gewittergefahr.gg_utils.error_checking.assert_is_boolean", "numpy.array" ]
[((5756, 5786), 'numpy.array', 'numpy.array', (['[0.5, 0.25, 0.25]'], {}), '([0.5, 0.25, 0.25])\n', (5767, 5786), False, 'import numpy\n'), ((7327, 7380), 'gewittergefahr.gg_utils.error_checking.assert_is_boolean', 'error_checking.assert_is_boolean', (['use_downsized_files'], {}), '(use_downsized_files)\n', (7359, 7380), False, 'from gewittergefahr.gg_utils import error_checking\n')]
import librosa #for audio processing import IPython.display as ipd import matplotlib.pyplot as plt import numpy as np from scipy.io import wavfile #for audio processing import warnings warnings.filterwarnings("ignore") import math, random import torch import torchaudio from torchaudio import transforms from IPython.display import Audio import librosa.display import logging from pydub import AudioSegment import os import wave,array from numpy.lib.stride_tricks import as_strided from mpl_toolkits.axes_grid1 import make_axes_locatable import soundfile as sf import sklearn logging.basicConfig(filename='../logs/audio.log', filemode='w', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO) audio_path='../data/alldata/' def caclulate_duration(audio_file): print(" ============ Calculating duration of audio file =================") logging.info(" ============ Calculating duration of audio file ================= ") #pick audio file and let librosa calculate the sample_rate and samples which we shall use to calculate the duration samples, sample_rate = librosa.load(audio_file) duration=float(len(samples)/sample_rate) return duration def plot_wav(audio_file,sample_rate): logging.info(" ============ Plotting audio wav file ================= ") audio, rate= librosa.load(audio_file) plt.figure(figsize=(20, 5)) librosa.display.waveplot(audio, sr=sample_rate) def sample_audio_play(audio_file,sample_rate): logging.info(" ============ Accessnig audio sample ================= ") audio_sample, rate= librosa.load(audio_file) plt.figure(figsize=(20, 5)) librosa.display.waveplot(audio_sample, sr=sample_rate) audios,rate= librosa.load(audio_file,sr=sample_rate) ipd.Audio(audio_sample,rate=sample_rate) def open(audio_file): #loading audio file and return signal sig, sr = torchaudio.load(audio_file) return (sig, sr) def mono_conversion(audio_file,new_channel): logging.info(" ============ Conerting audio sample from mono to stereo ================= ") print("======= Mono to stereo audio conversion") sig,sir=librosa.load(audio_file) #if signal shape is equal to two (stereo) no need for conversion if (sig.shape[0]==new_channel): return audio_file #if channel shape is equal to 1 we need to convert it to stereo if (new_channel == 1): resig =sig[:1,:] # converting mono to stereo else: resig=torch.cat([sig,sig]) def standard_sample(audio_file,resample): sig,sr=librosa.load(audio_file) if (sr == resample): return audio_file num_channels=sig.shape[0] resig=torchaudio.transforms.Resample(sig,resample)(sig[:1,:]) if (num_channels > 1): sampletwo=torchaudio.transforms.Resample(sr,resample)(sig[1:,:]) resig=torch.cat([resig,sampletwo]) return ((resig,resample)) def time_shift(audio,shift_limit): #this function shifts the signal to the left or right based on time sig,sr =audio _,audio_length =sig.shape shift_amount=int(random.random()* shift_limit * audio_length) return (sig.roll(shift_amount),sr) def spectro_gram(aud, n_mels=64, n_fft=1024, hop_len=None): sig,sr = aud top_db = 80 # spec has shape [channel, n_mels, time], where channel is mono, stereo etc spec = transforms.MelSpectrogram(sr, n_fft=n_fft, hop_length=hop_len, n_mels=n_mels)(sig) # Convert to decibels spec = transforms.AmplitudeToDB(top_db=top_db)(spec) return (spec) def convertor(audio_path): sound=AudioSegment.from_wav(audio_path) sound=sound.set_channels(2) newpath=audio_path.split(".")[0] newpath=newpath+'stereo.wav' subfolder = os.path.join('stereo',audio_path) sound.export(newpath,format='wav') def make_stereo(audio_path): #this function converts mono audio channels into stereo channels logging.info(" ============ Conerting audio sample from mono to stereo ================= ") print("======= Mono to stereo audio conversion") ifile = wave.open(audio_path) #log the info on adio files logging.info(ifile.getparams()) print (ifile.getparams()) # (1, 2, 44100, 2013900, 'NONE', 'not compressed') (nchannels, sampwidth, framerate, nframes, comptype, compname) = ifile.getparams() assert (comptype == 'NONE') # Compressed not supported yet array_type = {1:'B', 2: 'h', 4: 'l'}[sampwidth] print(" ======= Calculting left channel type =====") left_channel = array.array(array_type, ifile.readframes(nframes))[::nchannels] ifile.close() #convert the number of channels to 2 print("====== converting channels ======= ") stereo = 2 * left_channel stereo[0::2] = stereo[1::2] = left_channel #overwrite the wav file making it a stereo file print("====== overwriting wav file ======= ") ofile = wave.open(audio_path, 'w') ofile.setparams((2, sampwidth, framerate, nframes, comptype, compname)) ofile.writeframes(stereo.tobytes()) ofile.close() def create_spectogram(audio_file,fft_length=256,sample_rate=2,hop_length=1): samples,sample_rate = librosa.load(audio_file) assert not np.iscomplexobj(samples), "Must not pass in complex numbers" window = np.hanning(fft_length)[:, None] window_norm = np.sum(window**2) # The scaling below follows the convention of # matplotlib.mlab.specgram which is the same as # matlabs specgram. scale = window_norm * sample_rate trunc = (len(samples) - fft_length) % hop_length x = samples[:len(samples) - trunc] # "stride trick" reshape to include overlap nshape = (fft_length, (len(x) - fft_length) // hop_length + 1) nstrides = (x.strides[0], x.strides[0] * hop_length) x = as_strided(x, shape=nshape, strides=nstrides) # window stride sanity check assert np.all(x[:, 1] == samples[hop_length:(hop_length + fft_length)]) # broadcast window, compute fft over columns and square mod x = np.fft.rfft(x * window, axis=0) x = np.absolute(x)**2 # scale, 2.0 for everything except dc and fft_length/2 x[1:-1, :] *= (2.0 / scale) x[(0, -1), :] /= scale freqs = float(sample_rate) / fft_length * np.arange(x.shape[0]) return x, freqs def plot_spectogram(audio_file): x,freqs = create_spectogram(audio_file,fft_length=256,sample_rate=2,hop_length=1) fig = plt.figure(figsize=(12,5)) ax = fig.add_subplot(111) im = ax.imshow(x, cmap=plt.cm.jet, aspect='auto') plt.title('Spectrogram') plt.ylabel('Time') plt.xlabel('Frequency') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) plt.show() def plot_frequency(audio_file): x,freqs = create_spectogram(audio_file,fft_length=256,sample_rate=2,hop_length=1) X=librosa.stft(x) Xdb=librosa.amplitude_to_db(abs(X)) plt.figure(figsize=(10,9)) librosa.display.specshow(Xdb,sr=freqs,x_axis='time',y_axis='hz') plt.colorbar def resample_data(audio_file,resample_rate): #this function takes in the audio file and resample it a defined sampling rate print(" ============ Resampling data and overwriting audio =================") samples,sample_rate=librosa.load(audio_file) samples=librosa.resample(samples,sample_rate,resample_rate) print(" ========= writing new audio file to location =========== ") sf.write(audio_file,samples,sample_rate) return samples def pad(audio_file): print(" ============ checking duration of audio file to add padding =================") logging.info(" ============ if duration is below 6 we add silence ================= ") #pick audio file and let librosa calculate the sample_rate and samples which we shall use to calculate the duration samples, sample_rate = librosa.load(audio_file) duration=float(len(samples)/sample_rate) print('the duration is ', duration) if duration < 6 : print(" ============ duration is below 6 =================") pad_ms = duration audio = AudioSegment.from_wav(audio_file) silence = AudioSegment.silent(duration=pad_ms) padded = audio + silence samples, sample_rate = librosa.load(padded) newduration=float(len(samples)/sample_rate) sf.write(audio_file, samples, sample_rate) else : print(" ============ duration is above 6 =================") pass def shift (file_path): logging.info(" ============ iAugmenting audio by shifting ================= ") samples, sample_rate = librosa.load(file_path) wav_roll = np.roll(samples,int(sample_rate/10)) #plot_spec(data=wav_roll,sr=sample_rate,title=f'Shfiting the wave by Times {sample_rate/10}',fpath=wav) ipd.Audio(wav_roll,rate=sample_rate) sf.write(file_path, wav_roll, sample_rate) def mfcc(wav): logging.info(" ============ feature extraction mfcc ================= ") samples, sample_rate = librosa.load(wav) mfcc = librosa.feature.mfcc(samples, sr=sample_rate) # Center MFCC coefficient dimensions to the mean and unit variance mfcc = sklearn.preprocessing.scale(mfcc, axis=1) librosa.display.specshow(mfcc, sr=sample_rate, x_axis='time') sf.write(wav, samples, sample_rate) return mfcc if (__name__== '__main__'): # open(audio_path+'SWH-05-20101106_16k-emission_swahili_05h30_-_06h00_tu_20101106_part2.wav') # plot_wav() make_stereo('..\\data\\alldata\\SWH-05-20101106_16k-emission_swahili_05h30_-_06h00_tu_20101106_part100.wav','newtrack.wav')
[ "numpy.hanning", "matplotlib.pyplot.ylabel", "torchaudio.load", "librosa.feature.mfcc", "librosa.resample", "soundfile.write", "librosa.display.waveplot", "logging.info", "numpy.arange", "librosa.load", "wave.open", "matplotlib.pyplot.xlabel", "numpy.fft.rfft", "IPython.display.Audio", "...
[((187, 220), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (210, 220), False, 'import warnings\n'), ((581, 732), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""../logs/audio.log"""', 'filemode': '"""w"""', 'format': '"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""', 'level': 'logging.INFO'}), "(filename='../logs/audio.log', filemode='w', format=\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)\n", (600, 732), False, 'import logging\n'), ((881, 969), 'logging.info', 'logging.info', (['""" ============ Calculating duration of audio file ================= """'], {}), "(\n ' ============ Calculating duration of audio file ================= ')\n", (893, 969), False, 'import logging\n'), ((1117, 1141), 'librosa.load', 'librosa.load', (['audio_file'], {}), '(audio_file)\n', (1129, 1141), False, 'import librosa\n'), ((1261, 1333), 'logging.info', 'logging.info', (['""" ============ Plotting audio wav file ================= """'], {}), "(' ============ Plotting audio wav file ================= ')\n", (1273, 1333), False, 'import logging\n'), ((1351, 1375), 'librosa.load', 'librosa.load', (['audio_file'], {}), '(audio_file)\n', (1363, 1375), False, 'import librosa\n'), ((1380, 1407), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 5)'}), '(figsize=(20, 5))\n', (1390, 1407), True, 'import matplotlib.pyplot as plt\n'), ((1412, 1459), 'librosa.display.waveplot', 'librosa.display.waveplot', (['audio'], {'sr': 'sample_rate'}), '(audio, sr=sample_rate)\n', (1436, 1459), False, 'import librosa\n'), ((1513, 1584), 'logging.info', 'logging.info', (['""" ============ Accessnig audio sample ================= """'], {}), "(' ============ Accessnig audio sample ================= ')\n", (1525, 1584), False, 'import logging\n'), ((1609, 1633), 'librosa.load', 'librosa.load', (['audio_file'], {}), '(audio_file)\n', (1621, 1633), False, 'import librosa\n'), ((1638, 1665), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 5)'}), '(figsize=(20, 5))\n', (1648, 1665), True, 'import matplotlib.pyplot as plt\n'), ((1670, 1724), 'librosa.display.waveplot', 'librosa.display.waveplot', (['audio_sample'], {'sr': 'sample_rate'}), '(audio_sample, sr=sample_rate)\n', (1694, 1724), False, 'import librosa\n'), ((1742, 1782), 'librosa.load', 'librosa.load', (['audio_file'], {'sr': 'sample_rate'}), '(audio_file, sr=sample_rate)\n', (1754, 1782), False, 'import librosa\n'), ((1786, 1827), 'IPython.display.Audio', 'ipd.Audio', (['audio_sample'], {'rate': 'sample_rate'}), '(audio_sample, rate=sample_rate)\n', (1795, 1827), True, 'import IPython.display as ipd\n'), ((1911, 1938), 'torchaudio.load', 'torchaudio.load', (['audio_file'], {}), '(audio_file)\n', (1926, 1938), False, 'import torchaudio\n'), ((2013, 2114), 'logging.info', 'logging.info', (['""" ============ Conerting audio sample from mono to stereo ================= """'], {}), "(\n ' ============ Conerting audio sample from mono to stereo ================= '\n )\n", (2025, 2114), False, 'import logging\n'), ((2175, 2199), 'librosa.load', 'librosa.load', (['audio_file'], {}), '(audio_file)\n', (2187, 2199), False, 'import librosa\n'), ((2591, 2615), 'librosa.load', 'librosa.load', (['audio_file'], {}), '(audio_file)\n', (2603, 2615), False, 'import librosa\n'), ((3634, 3667), 'pydub.AudioSegment.from_wav', 'AudioSegment.from_wav', (['audio_path'], {}), '(audio_path)\n', (3655, 3667), False, 'from pydub import AudioSegment\n'), ((3786, 3820), 'os.path.join', 'os.path.join', (['"""stereo"""', 'audio_path'], {}), "('stereo', audio_path)\n", (3798, 3820), False, 'import os\n'), ((3963, 4064), 'logging.info', 'logging.info', (['""" ============ Conerting audio sample from mono to stereo ================= """'], {}), "(\n ' ============ Conerting audio sample from mono to stereo ================= '\n )\n", (3975, 4064), False, 'import logging\n'), ((4120, 4141), 'wave.open', 'wave.open', (['audio_path'], {}), '(audio_path)\n', (4129, 4141), False, 'import wave, array\n'), ((4938, 4964), 'wave.open', 'wave.open', (['audio_path', '"""w"""'], {}), "(audio_path, 'w')\n", (4947, 4964), False, 'import wave, array\n'), ((5203, 5227), 'librosa.load', 'librosa.load', (['audio_file'], {}), '(audio_file)\n', (5215, 5227), False, 'import librosa\n'), ((5368, 5387), 'numpy.sum', 'np.sum', (['(window ** 2)'], {}), '(window ** 2)\n', (5374, 5387), True, 'import numpy as np\n'), ((5825, 5870), 'numpy.lib.stride_tricks.as_strided', 'as_strided', (['x'], {'shape': 'nshape', 'strides': 'nstrides'}), '(x, shape=nshape, strides=nstrides)\n', (5835, 5870), False, 'from numpy.lib.stride_tricks import as_strided\n'), ((5916, 5978), 'numpy.all', 'np.all', (['(x[:, 1] == samples[hop_length:hop_length + fft_length])'], {}), '(x[:, 1] == samples[hop_length:hop_length + fft_length])\n', (5922, 5978), True, 'import numpy as np\n'), ((6054, 6085), 'numpy.fft.rfft', 'np.fft.rfft', (['(x * window)'], {'axis': '(0)'}), '(x * window, axis=0)\n', (6065, 6085), True, 'import numpy as np\n'), ((6451, 6478), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 5)'}), '(figsize=(12, 5))\n', (6461, 6478), True, 'import matplotlib.pyplot as plt\n'), ((6566, 6590), 'matplotlib.pyplot.title', 'plt.title', (['"""Spectrogram"""'], {}), "('Spectrogram')\n", (6575, 6590), True, 'import matplotlib.pyplot as plt\n'), ((6595, 6613), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Time"""'], {}), "('Time')\n", (6605, 6613), True, 'import matplotlib.pyplot as plt\n'), ((6618, 6641), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frequency"""'], {}), "('Frequency')\n", (6628, 6641), True, 'import matplotlib.pyplot as plt\n'), ((6656, 6679), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (6675, 6679), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((6744, 6769), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'cax': 'cax'}), '(im, cax=cax)\n', (6756, 6769), True, 'import matplotlib.pyplot as plt\n'), ((6774, 6784), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6782, 6784), True, 'import matplotlib.pyplot as plt\n'), ((6910, 6925), 'librosa.stft', 'librosa.stft', (['x'], {}), '(x)\n', (6922, 6925), False, 'import librosa\n'), ((6970, 6997), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 9)'}), '(figsize=(10, 9))\n', (6980, 6997), True, 'import matplotlib.pyplot as plt\n'), ((7001, 7068), 'librosa.display.specshow', 'librosa.display.specshow', (['Xdb'], {'sr': 'freqs', 'x_axis': '"""time"""', 'y_axis': '"""hz"""'}), "(Xdb, sr=freqs, x_axis='time', y_axis='hz')\n", (7025, 7068), False, 'import librosa\n'), ((7323, 7347), 'librosa.load', 'librosa.load', (['audio_file'], {}), '(audio_file)\n', (7335, 7347), False, 'import librosa\n'), ((7360, 7413), 'librosa.resample', 'librosa.resample', (['samples', 'sample_rate', 'resample_rate'], {}), '(samples, sample_rate, resample_rate)\n', (7376, 7413), False, 'import librosa\n'), ((7488, 7530), 'soundfile.write', 'sf.write', (['audio_file', 'samples', 'sample_rate'], {}), '(audio_file, samples, sample_rate)\n', (7496, 7530), True, 'import soundfile as sf\n'), ((7671, 7763), 'logging.info', 'logging.info', (['""" ============ if duration is below 6 we add silence ================= """'], {}), "(\n ' ============ if duration is below 6 we add silence ================= ')\n", (7683, 7763), False, 'import logging\n'), ((7915, 7939), 'librosa.load', 'librosa.load', (['audio_file'], {}), '(audio_file)\n', (7927, 7939), False, 'import librosa\n'), ((8571, 8649), 'logging.info', 'logging.info', (['""" ============ iAugmenting audio by shifting ================= """'], {}), "(' ============ iAugmenting audio by shifting ================= ')\n", (8583, 8649), False, 'import logging\n'), ((8677, 8700), 'librosa.load', 'librosa.load', (['file_path'], {}), '(file_path)\n', (8689, 8700), False, 'import librosa\n'), ((8865, 8902), 'IPython.display.Audio', 'ipd.Audio', (['wav_roll'], {'rate': 'sample_rate'}), '(wav_roll, rate=sample_rate)\n', (8874, 8902), True, 'import IPython.display as ipd\n'), ((8906, 8948), 'soundfile.write', 'sf.write', (['file_path', 'wav_roll', 'sample_rate'], {}), '(file_path, wav_roll, sample_rate)\n', (8914, 8948), True, 'import soundfile as sf\n'), ((8969, 9042), 'logging.info', 'logging.info', (['""" ============ feature extraction mfcc ================= """'], {}), "(' ============ feature extraction mfcc ================= ')\n", (8981, 9042), False, 'import logging\n'), ((9070, 9087), 'librosa.load', 'librosa.load', (['wav'], {}), '(wav)\n', (9082, 9087), False, 'import librosa\n'), ((9099, 9144), 'librosa.feature.mfcc', 'librosa.feature.mfcc', (['samples'], {'sr': 'sample_rate'}), '(samples, sr=sample_rate)\n', (9119, 9144), False, 'import librosa\n'), ((9227, 9268), 'sklearn.preprocessing.scale', 'sklearn.preprocessing.scale', (['mfcc'], {'axis': '(1)'}), '(mfcc, axis=1)\n', (9254, 9268), False, 'import sklearn\n'), ((9273, 9334), 'librosa.display.specshow', 'librosa.display.specshow', (['mfcc'], {'sr': 'sample_rate', 'x_axis': '"""time"""'}), "(mfcc, sr=sample_rate, x_axis='time')\n", (9297, 9334), False, 'import librosa\n'), ((9343, 9378), 'soundfile.write', 'sf.write', (['wav', 'samples', 'sample_rate'], {}), '(wav, samples, sample_rate)\n', (9351, 9378), True, 'import soundfile as sf\n'), ((2515, 2536), 'torch.cat', 'torch.cat', (['[sig, sig]'], {}), '([sig, sig])\n', (2524, 2536), False, 'import torch\n'), ((2711, 2756), 'torchaudio.transforms.Resample', 'torchaudio.transforms.Resample', (['sig', 'resample'], {}), '(sig, resample)\n', (2741, 2756), False, 'import torchaudio\n'), ((2883, 2912), 'torch.cat', 'torch.cat', (['[resig, sampletwo]'], {}), '([resig, sampletwo])\n', (2892, 2912), False, 'import torch\n'), ((3411, 3488), 'torchaudio.transforms.MelSpectrogram', 'transforms.MelSpectrogram', (['sr'], {'n_fft': 'n_fft', 'hop_length': 'hop_len', 'n_mels': 'n_mels'}), '(sr, n_fft=n_fft, hop_length=hop_len, n_mels=n_mels)\n', (3436, 3488), False, 'from torchaudio import transforms\n'), ((3532, 3571), 'torchaudio.transforms.AmplitudeToDB', 'transforms.AmplitudeToDB', ([], {'top_db': 'top_db'}), '(top_db=top_db)\n', (3556, 3571), False, 'from torchaudio import transforms\n'), ((5243, 5267), 'numpy.iscomplexobj', 'np.iscomplexobj', (['samples'], {}), '(samples)\n', (5258, 5267), True, 'import numpy as np\n'), ((5318, 5340), 'numpy.hanning', 'np.hanning', (['fft_length'], {}), '(fft_length)\n', (5328, 5340), True, 'import numpy as np\n'), ((6094, 6108), 'numpy.absolute', 'np.absolute', (['x'], {}), '(x)\n', (6105, 6108), True, 'import numpy as np\n'), ((6278, 6299), 'numpy.arange', 'np.arange', (['x.shape[0]'], {}), '(x.shape[0])\n', (6287, 6299), True, 'import numpy as np\n'), ((8162, 8195), 'pydub.AudioSegment.from_wav', 'AudioSegment.from_wav', (['audio_file'], {}), '(audio_file)\n', (8183, 8195), False, 'from pydub import AudioSegment\n'), ((8214, 8250), 'pydub.AudioSegment.silent', 'AudioSegment.silent', ([], {'duration': 'pad_ms'}), '(duration=pad_ms)\n', (8233, 8250), False, 'from pydub import AudioSegment\n'), ((8315, 8335), 'librosa.load', 'librosa.load', (['padded'], {}), '(padded)\n', (8327, 8335), False, 'import librosa\n'), ((8396, 8438), 'soundfile.write', 'sf.write', (['audio_file', 'samples', 'sample_rate'], {}), '(audio_file, samples, sample_rate)\n', (8404, 8438), True, 'import soundfile as sf\n'), ((2814, 2858), 'torchaudio.transforms.Resample', 'torchaudio.transforms.Resample', (['sr', 'resample'], {}), '(sr, resample)\n', (2844, 2858), False, 'import torchaudio\n'), ((3133, 3148), 'random.random', 'random.random', ([], {}), '()\n', (3146, 3148), False, 'import math, random\n')]
#!/usr/bin/env python2.7 # Author : <NAME> (<EMAIL>) # # Description : Filter data # # Acknowledgement : TomRoelandts.com # # Last updated # 2018.12.15 : version 0.10; import numpy as np import h5py import pywt import matplotlib.pyplot as plt import stats as st def nextpow2(i): n = 1 while n < i: n *= 2 return n class FirFilter(object): def __init__(self, name, fs, fL, fH, b=0.08): self.name = name self.fs = fs self.fL = fL self.fH = fH self.b = b N = int(np.ceil((4 / b))) if not N % 2: N += 1 self.N = N self.filt_coef = np.ones(N) if name == 'FIR_pass' and fL == 0: self.filt_coef = self.fir_lowpass(float(fH/fs), N) elif name == 'FIR_pass' and fH == 0: self.filt_coef = self.fir_lowpass(float(fL/fs), N) elif name == 'FIR_block': self.filt_coef = self.fir_bandblock(fL/fs, fH/fs, N) def apply(self, x): xlp = np.convolve(x, self.filt_coef) if self.name == 'FIR_pass' and self.fH == 0: # high pass filter x = x - xlp[int(self.N/2):int(self.N/2 + len(x))] # delay correction else: x = xlp[int(self.N/2):int(self.N/2 + len(x))] # delay correction return x def fir_lowpass(self, fc, N): n = np.arange(N) # Compute sinc filter. h = np.sinc(2 * fc * (n - (N - 1) / 2.)) # Compute Blackman window. w = np.blackman(N) # Multiply sinc filter with window. h = h * w # Normalize to get unity gain. h = h / np.sum(h) return h def fir_bandblock(self, fL, fH, N): n = np.arange(N) # Compute a low-pass filter with cutoff frequency fL. hlpf = np.sinc(2 * fL * (n - (N - 1) / 2.)) hlpf *= np.blackman(N) hlpf /= np.sum(hlpf) # Compute a high-pass filter with cutoff frequency fH. hhpf = np.sinc(2 * fH * (n - (N - 1) / 2.)) hhpf *= np.blackman(N) hhpf /= np.sum(hhpf) hhpf = -hhpf hhpf[int((N - 1) / 2)] += 1 # Add both filters. h = hlpf + hhpf return h class FftFilter(object): def __init__(self, name, fs, fL, fH): self.name = name self.fs = fs self.fL = fL self.fH = fH def apply(self, x): nfft = len(x) dt = 1.0/self.fs # frequency axis ax = np.fft.fftfreq(nfft, d=dt) # fft X = np.fft.fft(x, n=nfft) # apply filter (brick) if self.name == 'FFT_pass': self.filt_coef = (self.fL <= np.abs(ax)) & (np.abs(ax) <= self.fH) elif self.name == 'FFT_block': self.filt_coef = ~((self.fL <= np.abs(ax)) & (np.abs(ax) <= self.fH)) X = X * self.filt_coef # ifft x = np.fft.ifft(X, n=nfft) return x class SvdFilter(object): def __init__(self, cutoff=0.9): self.cutoff = cutoff def apply(self, data, good_channels, verbose=0): if np.sum(good_channels) == 0: good_channels = self.check_data(data) cnum, tnum = data.shape X = np.zeros((tnum, int(np.sum(good_channels)))) xm = np.zeros(int(np.sum(good_channels))) cnt = 0 for c in range(cnum): if good_channels[c] == 1: X[:,cnt] = data[c,:]/np.sqrt(tnum) xm[cnt] = np.mean(X[:,cnt]) X[:,cnt] = X[:,cnt] - xm[cnt] cnt += 1 # Do SVD U, s, Vt = np.linalg.svd(X, full_matrices=False) # energy of mode and the entropy sv = s**2 E = np.sum(sv) pi = sv / E nsent = st.ns_entropy(pi) print('The normalized Shannon entropy of sv is {:g}'.format(nsent)) if verbose == 1: ax1 = plt.subplot(211) ax1.plot(pi) ax2 = plt.subplot(212) ax2.plot(np.cumsum(sv)/np.sum(sv)) ax2.axhline(y=self.cutoff, color='r') ax1.set_ylabel('SV power') ax2.set_ylabel('Cumulated sum') ax2.set_xlabel('Mode number') plt.show() # filtering s[np.cumsum(sv)/np.sum(sv) >= self.cutoff] = 0 # reconstruct S = np.diag(s) reX = np.dot(U, np.dot(S, Vt)) # print('reconstructed {:0}'.format(np.allclose(X, reX))) cnt = 0 for c in range(cnum): if good_channels[c] == 1: data[c,:] = (reX[:,cnt] + xm[cnt])*np.sqrt(tnum) cnt += 1 return data def check_data(self, data): cnum, tnum = data.shape good_channels = np.ones(cnum) for c in range(cnum): if np.std(data[c,:]) == 0 or ~np.isfinite(np.sum(data[c,:])): # saturated or bad number good_channels[c] = 0 return good_channels class Wave2dFilter(object): def __init__(self, wavename='coif3', alpha=1.0, lim=5): self.wavename = wavename self.alpha = alpha self.lim = lim def apply(self, data, verbose=0): wavename = self.wavename alpha = self.alpha lim = self.lim dim = min(data.shape) if np.abs(dim - nextpow2(dim)) < np.abs(dim - (nextpow2(dim)/2)): level = int(np.log2(nextpow2(dim))) else: level = int(np.log2(nextpow2(dim)/2)) # wavelet transform coeffs = pywt.wavedec2(data, wavename, level=level) # set an intial threshold (noise level) coef1d = coeffs[0].reshape((coeffs[0].size,)) for i in range(1,len(coeffs)): for j in range(len(coeffs[i])): coef1d = np.hstack((coef1d, coeffs[i][j].reshape((coeffs[i][j].size,)))) # ~ size x size tlev = np.sum(coef1d**2) e = alpha*np.sqrt(np.var(coef1d)*np.log(coef1d.size)) # find the noise level via iteration old_e = 0.1*e new_e = e while np.abs(new_e - old_e)/old_e*100 > lim: old_e = new_e idx = np.abs(coef1d) < old_e coef1d = coef1d[idx] new_e = alpha*np.sqrt(np.var(coef1d)*np.log(coef1d.size)) e = old_e # get norms of the coherent and incoherent part ilev = np.sum(coef1d**2) clev = tlev - ilev clev = np.sqrt(clev) ilev = np.sqrt(ilev) # obtain the coherent part idx = np.abs(coeffs[0]) < e coeffs[0][idx] = 0 for i in range(1,len(coeffs)): for j in range(len(coeffs[i])): idx = np.abs(coeffs[i][j]) < e coeffs[i][j][idx] = 0 coh_data = pywt.waverec2(coeffs, wavename) return coh_data, clev, ilev
[ "numpy.convolve", "numpy.sqrt", "numpy.blackman", "numpy.log", "pywt.waverec2", "numpy.arange", "numpy.mean", "pywt.wavedec2", "numpy.fft.fft", "numpy.dot", "stats.ns_entropy", "numpy.abs", "numpy.ceil", "numpy.ones", "numpy.std", "numpy.linalg.svd", "numpy.fft.ifft", "matplotlib.p...
[((660, 670), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (667, 670), True, 'import numpy as np\n'), ((1032, 1062), 'numpy.convolve', 'np.convolve', (['x', 'self.filt_coef'], {}), '(x, self.filt_coef)\n', (1043, 1062), True, 'import numpy as np\n'), ((1381, 1393), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (1390, 1393), True, 'import numpy as np\n'), ((1441, 1478), 'numpy.sinc', 'np.sinc', (['(2 * fc * (n - (N - 1) / 2.0))'], {}), '(2 * fc * (n - (N - 1) / 2.0))\n', (1448, 1478), True, 'import numpy as np\n'), ((1527, 1541), 'numpy.blackman', 'np.blackman', (['N'], {}), '(N)\n', (1538, 1541), True, 'import numpy as np\n'), ((1749, 1761), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (1758, 1761), True, 'import numpy as np\n'), ((1843, 1880), 'numpy.sinc', 'np.sinc', (['(2 * fL * (n - (N - 1) / 2.0))'], {}), '(2 * fL * (n - (N - 1) / 2.0))\n', (1850, 1880), True, 'import numpy as np\n'), ((1897, 1911), 'numpy.blackman', 'np.blackman', (['N'], {}), '(N)\n', (1908, 1911), True, 'import numpy as np\n'), ((1929, 1941), 'numpy.sum', 'np.sum', (['hlpf'], {}), '(hlpf)\n', (1935, 1941), True, 'import numpy as np\n'), ((2022, 2059), 'numpy.sinc', 'np.sinc', (['(2 * fH * (n - (N - 1) / 2.0))'], {}), '(2 * fH * (n - (N - 1) / 2.0))\n', (2029, 2059), True, 'import numpy as np\n'), ((2076, 2090), 'numpy.blackman', 'np.blackman', (['N'], {}), '(N)\n', (2087, 2090), True, 'import numpy as np\n'), ((2108, 2120), 'numpy.sum', 'np.sum', (['hhpf'], {}), '(hhpf)\n', (2114, 2120), True, 'import numpy as np\n'), ((2545, 2571), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['nfft'], {'d': 'dt'}), '(nfft, d=dt)\n', (2559, 2571), True, 'import numpy as np\n'), ((2602, 2623), 'numpy.fft.fft', 'np.fft.fft', (['x'], {'n': 'nfft'}), '(x, n=nfft)\n', (2612, 2623), True, 'import numpy as np\n'), ((2961, 2983), 'numpy.fft.ifft', 'np.fft.ifft', (['X'], {'n': 'nfft'}), '(X, n=nfft)\n', (2972, 2983), True, 'import numpy as np\n'), ((3707, 3744), 'numpy.linalg.svd', 'np.linalg.svd', (['X'], {'full_matrices': '(False)'}), '(X, full_matrices=False)\n', (3720, 3744), True, 'import numpy as np\n'), ((3821, 3831), 'numpy.sum', 'np.sum', (['sv'], {}), '(sv)\n', (3827, 3831), True, 'import numpy as np\n'), ((3870, 3887), 'stats.ns_entropy', 'st.ns_entropy', (['pi'], {}), '(pi)\n', (3883, 3887), True, 'import stats as st\n'), ((4459, 4469), 'numpy.diag', 'np.diag', (['s'], {}), '(s)\n', (4466, 4469), True, 'import numpy as np\n'), ((4874, 4887), 'numpy.ones', 'np.ones', (['cnum'], {}), '(cnum)\n', (4881, 4887), True, 'import numpy as np\n'), ((5673, 5715), 'pywt.wavedec2', 'pywt.wavedec2', (['data', 'wavename'], {'level': 'level'}), '(data, wavename, level=level)\n', (5686, 5715), False, 'import pywt\n'), ((6030, 6049), 'numpy.sum', 'np.sum', (['(coef1d ** 2)'], {}), '(coef1d ** 2)\n', (6036, 6049), True, 'import numpy as np\n'), ((6525, 6544), 'numpy.sum', 'np.sum', (['(coef1d ** 2)'], {}), '(coef1d ** 2)\n', (6531, 6544), True, 'import numpy as np\n'), ((6587, 6600), 'numpy.sqrt', 'np.sqrt', (['clev'], {}), '(clev)\n', (6594, 6600), True, 'import numpy as np\n'), ((6618, 6631), 'numpy.sqrt', 'np.sqrt', (['ilev'], {}), '(ilev)\n', (6625, 6631), True, 'import numpy as np\n'), ((6932, 6963), 'pywt.waverec2', 'pywt.waverec2', (['coeffs', 'wavename'], {}), '(coeffs, wavename)\n', (6945, 6963), False, 'import pywt\n'), ((564, 578), 'numpy.ceil', 'np.ceil', (['(4 / b)'], {}), '(4 / b)\n', (571, 578), True, 'import numpy as np\n'), ((1663, 1672), 'numpy.sum', 'np.sum', (['h'], {}), '(h)\n', (1669, 1672), True, 'import numpy as np\n'), ((3177, 3198), 'numpy.sum', 'np.sum', (['good_channels'], {}), '(good_channels)\n', (3183, 3198), True, 'import numpy as np\n'), ((4012, 4028), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (4023, 4028), True, 'import matplotlib.pyplot as plt\n'), ((4074, 4090), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(212)'], {}), '(212)\n', (4085, 4090), True, 'import matplotlib.pyplot as plt\n'), ((4331, 4341), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4339, 4341), True, 'import matplotlib.pyplot as plt\n'), ((4495, 4508), 'numpy.dot', 'np.dot', (['S', 'Vt'], {}), '(S, Vt)\n', (4501, 4508), True, 'import numpy as np\n'), ((6690, 6707), 'numpy.abs', 'np.abs', (['coeffs[0]'], {}), '(coeffs[0])\n', (6696, 6707), True, 'import numpy as np\n'), ((3384, 3405), 'numpy.sum', 'np.sum', (['good_channels'], {}), '(good_channels)\n', (3390, 3405), True, 'import numpy as np\n'), ((3576, 3594), 'numpy.mean', 'np.mean', (['X[:, cnt]'], {}), '(X[:, cnt])\n', (3583, 3594), True, 'import numpy as np\n'), ((6302, 6316), 'numpy.abs', 'np.abs', (['coef1d'], {}), '(coef1d)\n', (6308, 6316), True, 'import numpy as np\n'), ((2737, 2747), 'numpy.abs', 'np.abs', (['ax'], {}), '(ax)\n', (2743, 2747), True, 'import numpy as np\n'), ((2752, 2762), 'numpy.abs', 'np.abs', (['ax'], {}), '(ax)\n', (2758, 2762), True, 'import numpy as np\n'), ((3332, 3353), 'numpy.sum', 'np.sum', (['good_channels'], {}), '(good_channels)\n', (3338, 3353), True, 'import numpy as np\n'), ((3535, 3548), 'numpy.sqrt', 'np.sqrt', (['tnum'], {}), '(tnum)\n', (3542, 3548), True, 'import numpy as np\n'), ((4113, 4126), 'numpy.cumsum', 'np.cumsum', (['sv'], {}), '(sv)\n', (4122, 4126), True, 'import numpy as np\n'), ((4127, 4137), 'numpy.sum', 'np.sum', (['sv'], {}), '(sv)\n', (4133, 4137), True, 'import numpy as np\n'), ((4376, 4389), 'numpy.cumsum', 'np.cumsum', (['sv'], {}), '(sv)\n', (4385, 4389), True, 'import numpy as np\n'), ((4390, 4400), 'numpy.sum', 'np.sum', (['sv'], {}), '(sv)\n', (4396, 4400), True, 'import numpy as np\n'), ((4718, 4731), 'numpy.sqrt', 'np.sqrt', (['tnum'], {}), '(tnum)\n', (4725, 4731), True, 'import numpy as np\n'), ((4937, 4955), 'numpy.std', 'np.std', (['data[c, :]'], {}), '(data[c, :])\n', (4943, 4955), True, 'import numpy as np\n'), ((6076, 6090), 'numpy.var', 'np.var', (['coef1d'], {}), '(coef1d)\n', (6082, 6090), True, 'import numpy as np\n'), ((6091, 6110), 'numpy.log', 'np.log', (['coef1d.size'], {}), '(coef1d.size)\n', (6097, 6110), True, 'import numpy as np\n'), ((6217, 6238), 'numpy.abs', 'np.abs', (['(new_e - old_e)'], {}), '(new_e - old_e)\n', (6223, 6238), True, 'import numpy as np\n'), ((6848, 6868), 'numpy.abs', 'np.abs', (['coeffs[i][j]'], {}), '(coeffs[i][j])\n', (6854, 6868), True, 'import numpy as np\n'), ((4976, 4994), 'numpy.sum', 'np.sum', (['data[c, :]'], {}), '(data[c, :])\n', (4982, 4994), True, 'import numpy as np\n'), ((6394, 6408), 'numpy.var', 'np.var', (['coef1d'], {}), '(coef1d)\n', (6400, 6408), True, 'import numpy as np\n'), ((6409, 6428), 'numpy.log', 'np.log', (['coef1d.size'], {}), '(coef1d.size)\n', (6415, 6428), True, 'import numpy as np\n'), ((2859, 2869), 'numpy.abs', 'np.abs', (['ax'], {}), '(ax)\n', (2865, 2869), True, 'import numpy as np\n'), ((2874, 2884), 'numpy.abs', 'np.abs', (['ax'], {}), '(ax)\n', (2880, 2884), True, 'import numpy as np\n')]
#!/usr/bin/env python """ Speed-Gauge for matplotlib See http://nbviewer.ipython.org/gist/nicolasfauchereau/794df533eca594565ab3 Adapted to be more typical ratio display. """ from matplotlib import cm from matplotlib import pyplot as plt import numpy as np from matplotlib.patches import Circle, Wedge, Rectangle def degree_range(n): start = np.linspace(0, 180, n+1, endpoint=True)[0:-1] end = np.linspace(0, 180, n+1, endpoint=True)[1::] mid_points = start + ((end-start)/2.) return np.c_[start, end], mid_points def rot_text(ang): rotation = np.degrees(np.radians(ang) * np.pi / np.pi - np.radians(90)) return rotation def gauge(colors='hot', title='', value=0.5, labs=['0%', -1, '100%']): """ Gauge display of a single value against a range. Parameters ---------- hot : string matplotlib colour map specification title : string To put at the base of the gauge. If falsy, no label area. value : float Fractional value to plot, 0 for no colour, 1 for whole bar labs : 3-element list of tuple Label the start, arrow and end of the gauge with these. If the middle one is -1, replace with percentage of value. """ N = 100 # number of elements # if colors is a colormap cmap = cm.get_cmap(colors, N) cmap = cmap(np.arange(N)) colors = cmap[::-1, :].tolist() fig, ax = plt.subplots() ang_range, mid_points = degree_range(N) pos = mid_points[int(N*(1-value))] patches = [] for ang, c in zip(ang_range, colors): # sectors # patches.append(Wedge((0., 0.), .4, *ang, facecolor='w', lw=2)) # arcs if sum(ang) < pos*2: c = 'w' patches.append(Wedge((0., 0.), .4, *ang, width=0.10, facecolor=c, lw=2, alpha=0.5, edgecolor='None')) for mid, lab in zip([180, pos, 0], labs): if lab == -1: lab = "{:.1%}".format(value) if lab: ax.text(0.41 * np.cos(np.radians(mid)), 0.41 * np.sin(np.radians(mid)), lab, ha='center', va='center', fontsize=14, fontweight='bold', rotation=rot_text(mid)) [ax.add_patch(p) for p in patches] if title: r = Rectangle((-0.4, -0.1), 0.8, 0.1, facecolor='w', lw=2) ax.add_patch(r) ax.text(0, -0.05, title, horizontalalignment='center', verticalalignment='center', fontsize=22, fontweight='bold') ax.arrow(0, 0, 0.225 * np.cos(np.radians(pos)), 0.225 * np.sin(np.radians(pos)), width=0.04, head_width=0.09, head_length=0.1, fc='k', ec='k') ax.add_patch(Circle((0, 0), radius=0.02, facecolor='k')) ax.add_patch(Circle((0, 0), radius=0.01, facecolor='w', zorder=11)) ax.set_frame_on(False) ax.axes.set_xticks([]) ax.axes.set_yticks([]) ax.axis('equal') plt.tight_layout()
[ "numpy.radians", "matplotlib.cm.get_cmap", "matplotlib.patches.Rectangle", "matplotlib.patches.Wedge", "numpy.linspace", "matplotlib.pyplot.tight_layout", "matplotlib.patches.Circle", "matplotlib.pyplot.subplots", "numpy.arange" ]
[((1254, 1276), 'matplotlib.cm.get_cmap', 'cm.get_cmap', (['colors', 'N'], {}), '(colors, N)\n', (1265, 1276), False, 'from matplotlib import cm\n'), ((1358, 1372), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1370, 1372), True, 'from matplotlib import pyplot as plt\n'), ((2847, 2865), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2863, 2865), True, 'from matplotlib import pyplot as plt\n'), ((350, 391), 'numpy.linspace', 'np.linspace', (['(0)', '(180)', '(n + 1)'], {'endpoint': '(True)'}), '(0, 180, n + 1, endpoint=True)\n', (361, 391), True, 'import numpy as np\n'), ((406, 447), 'numpy.linspace', 'np.linspace', (['(0)', '(180)', '(n + 1)'], {'endpoint': '(True)'}), '(0, 180, n + 1, endpoint=True)\n', (417, 447), True, 'import numpy as np\n'), ((1293, 1305), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (1302, 1305), True, 'import numpy as np\n'), ((2214, 2268), 'matplotlib.patches.Rectangle', 'Rectangle', (['(-0.4, -0.1)', '(0.8)', '(0.1)'], {'facecolor': '"""w"""', 'lw': '(2)'}), "((-0.4, -0.1), 0.8, 0.1, facecolor='w', lw=2)\n", (2223, 2268), False, 'from matplotlib.patches import Circle, Wedge, Rectangle\n'), ((2624, 2666), 'matplotlib.patches.Circle', 'Circle', (['(0, 0)'], {'radius': '(0.02)', 'facecolor': '"""k"""'}), "((0, 0), radius=0.02, facecolor='k')\n", (2630, 2666), False, 'from matplotlib.patches import Circle, Wedge, Rectangle\n'), ((2685, 2738), 'matplotlib.patches.Circle', 'Circle', (['(0, 0)'], {'radius': '(0.01)', 'facecolor': '"""w"""', 'zorder': '(11)'}), "((0, 0), radius=0.01, facecolor='w', zorder=11)\n", (2691, 2738), False, 'from matplotlib.patches import Circle, Wedge, Rectangle\n'), ((615, 629), 'numpy.radians', 'np.radians', (['(90)'], {}), '(90)\n', (625, 629), True, 'import numpy as np\n'), ((1694, 1785), 'matplotlib.patches.Wedge', 'Wedge', (['(0.0, 0.0)', '(0.4)', '*ang'], {'width': '(0.1)', 'facecolor': 'c', 'lw': '(2)', 'alpha': '(0.5)', 'edgecolor': '"""None"""'}), "((0.0, 0.0), 0.4, *ang, width=0.1, facecolor=c, lw=2, alpha=0.5,\n edgecolor='None')\n", (1699, 1785), False, 'from matplotlib.patches import Circle, Wedge, Rectangle\n'), ((2467, 2482), 'numpy.radians', 'np.radians', (['pos'], {}), '(pos)\n', (2477, 2482), True, 'import numpy as np\n'), ((2513, 2528), 'numpy.radians', 'np.radians', (['pos'], {}), '(pos)\n', (2523, 2528), True, 'import numpy as np\n'), ((581, 596), 'numpy.radians', 'np.radians', (['ang'], {}), '(ang)\n', (591, 596), True, 'import numpy as np\n'), ((1970, 1985), 'numpy.radians', 'np.radians', (['mid'], {}), '(mid)\n', (1980, 1985), True, 'import numpy as np\n'), ((2002, 2017), 'numpy.radians', 'np.radians', (['mid'], {}), '(mid)\n', (2012, 2017), True, 'import numpy as np\n')]
#-*- coding:utf-8 -*- import datetime import cv2 import numpy as np import h5py import sys import shutil cmd_line = sys.argv[1].split(",") video_dir = cmd_line[0] #実行時の引数をビデオファイルの引数とする。 print(video_dir) print(cmd_line) todaydetail = datetime.datetime.today() todaydetail = str(todaydetail.year) + str(todaydetail.month) + str(todaydetail.day) + str(todaydetail.hour) + str(todaydetail.minute) + str(todaydetail.second) for j in range(1,int(cmd_line[1])+1): output_file = "out" + todaydetail +"split"+str(j) + ".h5" #output_file = video_file + ".h5" print(output_file) h5file = h5py.File(output_file,'w') print(video_dir + "\msCam" + str(j) + ".avi") cap = cv2.VideoCapture(video_dir + "\msCam" + str(j) + ".avi") video_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT) i = 0 while(cap.isOpened()):# 動画終了まで繰り返し try: ret, frame = cap.read() gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)#グレースケールに変換 gray_frame = np.reshape(gray_frame, (1, *gray_frame.shape))#(1,px,px)に変換 #print(gray_frame.shape) except: break try: if (i == 0): data = np.array(gray_frame) else: #data = np.dstack((data,frame)) data = np.concatenate([data,gray_frame],axis = 0) #フレームをaxis = 0 方向に重ねていく except: break # qキーが押されたら途中終了 if cv2.waitKey(1) & 0xFF == ord('q'): break i = i + 1 print(j,"of" ,cmd_line[1],"frame",i,"/",video_frame) if(j == 1): data_temp = np.array(data) print(data_temp.shape) else: data_temp = np.concatenate([data_temp,data],axis = 0) print(data_temp.shape) try: h5file.create_dataset('object',data= data) h5file.flush() except: _ = 0 h5file.flush() h5file.close() cap.release() cv2.destroyAllWindows() print("completed") print("out" + todaydetail +"split"+str(j) + ".h5") shutil.move(output_file, 'h5data') output_file2 = "out" + todaydetail +"_" +str(j)+"file_merged" + ".h5" h5file2 = h5py.File(output_file2,'w') try: h5file2.create_dataset('object',data= data_temp) h5file2.flush() except: _ = 0 h5file2.flush() h5file2.close() print("merge completed") print("out" + todaydetail +"_" +str(j)+"file_merged" + ".h5") shutil.move(output_file2, 'h5data')
[ "numpy.reshape", "shutil.move", "h5py.File", "numpy.array", "cv2.destroyAllWindows", "numpy.concatenate", "cv2.cvtColor", "datetime.datetime.today", "cv2.waitKey" ]
[((235, 260), 'datetime.datetime.today', 'datetime.datetime.today', ([], {}), '()\n', (258, 260), False, 'import datetime\n'), ((2207, 2235), 'h5py.File', 'h5py.File', (['output_file2', '"""w"""'], {}), "(output_file2, 'w')\n", (2216, 2235), False, 'import h5py\n'), ((2457, 2492), 'shutil.move', 'shutil.move', (['output_file2', '"""h5data"""'], {}), "(output_file2, 'h5data')\n", (2468, 2492), False, 'import shutil\n'), ((597, 624), 'h5py.File', 'h5py.File', (['output_file', '"""w"""'], {}), "(output_file, 'w')\n", (606, 624), False, 'import h5py\n'), ((1984, 2007), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2005, 2007), False, 'import cv2\n'), ((2090, 2124), 'shutil.move', 'shutil.move', (['output_file', '"""h5data"""'], {}), "(output_file, 'h5data')\n", (2101, 2124), False, 'import shutil\n'), ((1656, 1670), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (1664, 1670), True, 'import numpy as np\n'), ((1732, 1773), 'numpy.concatenate', 'np.concatenate', (['[data_temp, data]'], {'axis': '(0)'}), '([data_temp, data], axis=0)\n', (1746, 1773), True, 'import numpy as np\n'), ((920, 959), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (932, 959), False, 'import cv2\n'), ((996, 1042), 'numpy.reshape', 'np.reshape', (['gray_frame', '(1, *gray_frame.shape)'], {}), '(gray_frame, (1, *gray_frame.shape))\n', (1006, 1042), True, 'import numpy as np\n'), ((1199, 1219), 'numpy.array', 'np.array', (['gray_frame'], {}), '(gray_frame)\n', (1207, 1219), True, 'import numpy as np\n'), ((1326, 1368), 'numpy.concatenate', 'np.concatenate', (['[data, gray_frame]'], {'axis': '(0)'}), '([data, gray_frame], axis=0)\n', (1340, 1368), True, 'import numpy as np\n'), ((1485, 1499), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (1496, 1499), False, 'import cv2\n')]
import numpy as np import pickle import datetime import matplotlib.pyplot as plt with open("../data/factor_out_2020.pickle",'rb') as f: factor_out = pickle.load(f) with open("../data/factor_in_2020.pickle",'rb') as f: factor_in = pickle.load(f) with open("../data/dicOfMatrix.pickle",'rb') as f: matrices = pickle.load(f) coef = 9.3*10000 # 迁徙规模修正系数 def Lout(i,t): """ 城市i在第t天的人口流出 :param i: :param t: :return: [Lo_0,Lo_1,...] 第j位表示流出至城市j的数量 """ begin = datetime.date(2020, 1, 1) day = begin + datetime.timedelta(days=t) matrix = matrices[day] outRate = matrix[i,:] factor = factor_out[i,t]*coef out = outRate*factor*0.01 return out def Lin(i,t): """ 第t天流入城市i的人口 :param i: :param t: :return:number """ begin = datetime.date(2020, 1, 1) day = begin + datetime.timedelta(days=t) # matrix = matrices[day] IN = factor_in[i,t]*coef return IN def dSpread(Lo,vector,i): """ 第i个城市处于vector状态[S,E,I1,I2,R]时,向外流动的人口 :param Lo: :param vector: :param i: :return:[dLSin,dLEin,...,dLRin] 其中dLSin,dLEin,...都是向量 """ S,E,I1,I2,R = vector N = np.sum(vector) dLSin = Lo * S/N dLEin = Lo * E/N dLI1in = Lo * I1/N dLI2in = Lo * I2/N dLRin = Lo * R/N return np.array([dLSin,dLEin,dLI1in,dLI2in,dLRin])
[ "pickle.load", "numpy.sum", "numpy.array", "datetime.date", "datetime.timedelta" ]
[((158, 172), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (169, 172), False, 'import pickle\n'), ((245, 259), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (256, 259), False, 'import pickle\n'), ((328, 342), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (339, 342), False, 'import pickle\n'), ((512, 537), 'datetime.date', 'datetime.date', (['(2020)', '(1)', '(1)'], {}), '(2020, 1, 1)\n', (525, 537), False, 'import datetime\n'), ((836, 861), 'datetime.date', 'datetime.date', (['(2020)', '(1)', '(1)'], {}), '(2020, 1, 1)\n', (849, 861), False, 'import datetime\n'), ((1223, 1237), 'numpy.sum', 'np.sum', (['vector'], {}), '(vector)\n', (1229, 1237), True, 'import numpy as np\n'), ((1364, 1411), 'numpy.array', 'np.array', (['[dLSin, dLEin, dLI1in, dLI2in, dLRin]'], {}), '([dLSin, dLEin, dLI1in, dLI2in, dLRin])\n', (1372, 1411), True, 'import numpy as np\n'), ((557, 583), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 't'}), '(days=t)\n', (575, 583), False, 'import datetime\n'), ((881, 907), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 't'}), '(days=t)\n', (899, 907), False, 'import datetime\n')]
import numpy as np import tensorflow as tf from util import xavier_init class SparseAutoencoder(object): def __init__(self, num_input, num_hidden, transfer_function=tf.nn.softplus, optimizer=tf.train.AdamOptimizer(), scale=0.1): self.num_input = num_input self.num_hidden = num_hidden self.transfer = transfer_function self.scale = tf.placeholder(tf.float32) self.training_scale = scale network_weights = self._initialize_weights() self.weights = network_weights self.sparsity_level = np.repeat([0.05], self.num_hidden).astype(np.float32) self.sparse_reg = 0.0 # model self.x = tf.placeholder(tf.float32, [None, self.num_input]) self.hidden_layer = self.transfer(tf.add(tf.matmul(self.x + scale * tf.random_normal((num_input,)), self.weights['w1']), self.weights['b1'])) self.reconstruction = tf.add(tf.matmul(self.hidden_layer, self.weights['w2']), self.weights['b2']) # cost self.cost = 0.5 * tf.reduce_sum(tf.pow(tf.subtract(self.reconstruction, self.x), 2.0)) + self.sparse_reg \ * self.kl_divergence( self.sparsity_level, self.hidden_layer) self.optimizer = optimizer.minimize(self.cost) init = tf.global_variables_initializer() self.session = tf.Session() self.session.run(init) def _initialize_weights(self): all_weights = dict() all_weights['w1'] = tf.Variable(xavier_init(self.num_input, self.num_hidden)) all_weights['b1'] = tf.Variable(tf.zeros([self.num_hidden], dtype = tf.float32)) all_weights['w2'] = tf.Variable(tf.zeros([self.num_hidden, self.num_input], dtype = tf.float32)) all_weights['b2'] = tf.Variable(tf.zeros([self.num_input], dtype = tf.float32)) return all_weights def partial_fit(self, X): cost, opt = self.session.run((self.cost, self.optimizer), feed_dict = {self.x: X, self.scale: self.training_scale }) return cost def kl_divergence_old(self, p, p_hat): return tf.reduce_mean(p * tf.log(p) - p * tf.log(p_hat) + (1 - p) * tf.log(1 - p) - (1 - p) * tf.log(1 - p_hat)) def kl_divergence(self, p, p_hat): return tf.reduce_mean(p*(tf.log(p)/tf.log(p_hat)) + (1-p)*(tf.log(1-p)/tf.log(1-p_hat))) def calculate_total_cost(self, X): return self.session.run(self.cost, feed_dict = {self.x: X, self.scale: self.training_scale }) def transform(self, X): return self.session.run(self.hidden_layer, feed_dict = {self.x: X, self.scale: self.training_scale }) def generate(self, hidden = None): if hidden is None: hidden = np.random.normal(size = self.weights["b1"]) return self.session.run(self.reconstruction, feed_dict = {self.hidden_layer: hidden}) def reconstruct(self, X): return self.session.run(self.reconstruction, feed_dict = {self.x: X, self.scale: self.training_scale }) def get_weights(self): return self.session.run(self.weights['w1']) def get_biases(self): return self.session.run(self.weights['b1'])
[ "numpy.random.normal", "numpy.repeat", "tensorflow.random_normal", "util.xavier_init", "tensorflow.placeholder", "tensorflow.Session", "tensorflow.global_variables_initializer", "tensorflow.matmul", "tensorflow.subtract", "tensorflow.train.AdamOptimizer", "tensorflow.log", "tensorflow.zeros" ]
[((196, 220), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {}), '()\n', (218, 220), True, 'import tensorflow as tf\n'), ((386, 412), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (400, 412), True, 'import tensorflow as tf\n'), ((689, 739), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, self.num_input]'], {}), '(tf.float32, [None, self.num_input])\n', (703, 739), True, 'import tensorflow as tf\n'), ((1479, 1512), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1510, 1512), True, 'import tensorflow as tf\n'), ((1536, 1548), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1546, 1548), True, 'import tensorflow as tf\n'), ((1035, 1083), 'tensorflow.matmul', 'tf.matmul', (['self.hidden_layer', "self.weights['w2']"], {}), "(self.hidden_layer, self.weights['w2'])\n", (1044, 1083), True, 'import tensorflow as tf\n'), ((1685, 1729), 'util.xavier_init', 'xavier_init', (['self.num_input', 'self.num_hidden'], {}), '(self.num_input, self.num_hidden)\n', (1696, 1729), False, 'from util import xavier_init\n'), ((1771, 1816), 'tensorflow.zeros', 'tf.zeros', (['[self.num_hidden]'], {'dtype': 'tf.float32'}), '([self.num_hidden], dtype=tf.float32)\n', (1779, 1816), True, 'import tensorflow as tf\n'), ((1860, 1921), 'tensorflow.zeros', 'tf.zeros', (['[self.num_hidden, self.num_input]'], {'dtype': 'tf.float32'}), '([self.num_hidden, self.num_input], dtype=tf.float32)\n', (1868, 1921), True, 'import tensorflow as tf\n'), ((1965, 2009), 'tensorflow.zeros', 'tf.zeros', (['[self.num_input]'], {'dtype': 'tf.float32'}), '([self.num_input], dtype=tf.float32)\n', (1973, 2009), True, 'import tensorflow as tf\n'), ((3285, 3326), 'numpy.random.normal', 'np.random.normal', ([], {'size': "self.weights['b1']"}), "(size=self.weights['b1'])\n", (3301, 3326), True, 'import numpy as np\n'), ((571, 605), 'numpy.repeat', 'np.repeat', (['[0.05]', 'self.num_hidden'], {}), '([0.05], self.num_hidden)\n', (580, 605), True, 'import numpy as np\n'), ((2520, 2537), 'tensorflow.log', 'tf.log', (['(1 - p_hat)'], {}), '(1 - p_hat)\n', (2526, 2537), True, 'import tensorflow as tf\n'), ((1168, 1208), 'tensorflow.subtract', 'tf.subtract', (['self.reconstruction', 'self.x'], {}), '(self.reconstruction, self.x)\n', (1179, 1208), True, 'import tensorflow as tf\n'), ((2494, 2507), 'tensorflow.log', 'tf.log', (['(1 - p)'], {}), '(1 - p)\n', (2500, 2507), True, 'import tensorflow as tf\n'), ((2612, 2621), 'tensorflow.log', 'tf.log', (['p'], {}), '(p)\n', (2618, 2621), True, 'import tensorflow as tf\n'), ((2622, 2635), 'tensorflow.log', 'tf.log', (['p_hat'], {}), '(p_hat)\n', (2628, 2635), True, 'import tensorflow as tf\n'), ((2646, 2659), 'tensorflow.log', 'tf.log', (['(1 - p)'], {}), '(1 - p)\n', (2652, 2659), True, 'import tensorflow as tf\n'), ((2658, 2675), 'tensorflow.log', 'tf.log', (['(1 - p_hat)'], {}), '(1 - p_hat)\n', (2664, 2675), True, 'import tensorflow as tf\n'), ((816, 846), 'tensorflow.random_normal', 'tf.random_normal', (['(num_input,)'], {}), '((num_input,))\n', (832, 846), True, 'import tensorflow as tf\n'), ((2452, 2461), 'tensorflow.log', 'tf.log', (['p'], {}), '(p)\n', (2458, 2461), True, 'import tensorflow as tf\n'), ((2468, 2481), 'tensorflow.log', 'tf.log', (['p_hat'], {}), '(p_hat)\n', (2474, 2481), True, 'import tensorflow as tf\n')]
# encoding='utf-8' ''' /** * This is the solution of No.43 problem in the LeetCode, * the website of the problem is as follow: * https://leetcode-cn.com/problems/multiply-strings * <p> * The description of problem is as follow: * ========================================================================================================== * 给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。 * * 示例 1: * * 输入: num1 = "2", num2 = "3" * 输出: "6" * 示例 2: * * 输入: num1 = "123", num2 = "456" * 输出: "56088" * 说明: * * num1 和 num2 的长度小于110。 * num1 和 num2 只包含数字 0-9。 * num1 和 num2 均不以零开头,除非是数字 0 本身。 * 不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/multiply-strings * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * ========================================================================================================== * * @author zhangyu (<EMAIL>) */ ''' import numpy as np class Solution: def multiply1(self, num1: str, num2: str) -> str: ''' 对二进制字符串进行相乘 Args: num1: 字符串数字1 num2: 字符串数字2 Returns: 字符串数 ''' return str(int(num1) * int(num2)) def multiply2(self, num1: str, num2: str) -> str: ''' 对二进制字符串相加减 Args: num1: 字符串数1 num2: 字符串数2 Returns: 两个字符串相乘结果 ''' if not num1 or len(num1) < 1: return "0" if not num2 or len(num2) < 1: return "0" if 0 == num2 or 0 == num1: return "0" len1 = len(num1) len2 = len(num2) if len1 == 0 or len2 == 0: return "0" sb = [] result = np.zeros(len2 + len1) carry = 0 pointer = len(result) - 1 i = len(num1) while i >= 0: n1 = ord(num1.index(i)) - ord("0") start = pointer carry = 0 j = len(num2) - 1 while j >= 0: n2 = ord(num2.index(j)) - ord("0") res = n1 * n2 + result[start] + carry carry = res // 10 res %= 10 result[start] = res start -= 1 if carry > 0: result[start] = carry pointer -= 1 if carry > 0: sb.append(carry) return "".join(sb) if __name__ == '__main__': a = "11" b = "10" solution = Solution() num = solution.multiply1(a, b) print(num)
[ "numpy.zeros" ]
[((1745, 1766), 'numpy.zeros', 'np.zeros', (['(len2 + len1)'], {}), '(len2 + len1)\n', (1753, 1766), True, 'import numpy as np\n')]
from os.path import join, isdir import glob from subprocess import call import numpy as np from rastervision.common.utils import _makedirs from rastervision.common.settings import VALIDATION from rastervision.semseg.tasks.utils import ( make_prediction_img, plot_prediction, predict_x) from rastervision.semseg.models.factory import SemsegModelFactory MAKE_VIDEOS = 'make_videos' def make_videos(run_path, options, generator): model_factory = SemsegModelFactory() videos_path = join(run_path, 'videos') _makedirs(videos_path) checkpoints_path = join(run_path, 'delta_model_checkpoints') if not isdir(checkpoints_path): print('Cannot make videos without delta_model_checkpoints.') return model_paths = glob.glob(join(checkpoints_path, '*.h5')) model_paths.sort() models = [] for model_path in model_paths: model = model_factory.make_model(options, generator) model.load_weights(model_path, by_name=True) models.append(model) split_gen = generator.make_split_generator( VALIDATION, target_size=options.eval_target_size, batch_size=1, shuffle=False, augment_methods=None, normalize=True, only_xy=False) for video_ind, batch in \ enumerate(split_gen): x = np.squeeze(batch.x, axis=0) y = np.squeeze(batch.y, axis=0) display_y = generator.dataset.one_hot_to_rgb_batch(y) all_x = np.squeeze(batch.all_x, axis=0) make_video( x, display_y, all_x, models, videos_path, video_ind, options, generator) if video_ind == options.nb_videos - 1: break def make_video(x, y, all_x, models, videos_path, video_ind, options, generator): video_path = join(videos_path, str(video_ind)) _makedirs(video_path) for frame_ind, model in enumerate(models): y_pred = make_prediction_img( x, options.target_size[0], lambda x: generator.dataset.one_hot_to_rgb_batch( predict_x(x, model))) print(video_ind) print(frame_ind) frame_path = join( video_path, 'frame_{:0>4}.png'.format(frame_ind)) plot_prediction(generator, all_x, y, y_pred, frame_path) frames_path = join(video_path, 'frame_%04d.png') video_path = join(videos_path, '{}.mp4'.format(video_ind)) call(['avconv', '-r', '2', '-i', frames_path, '-vf', 'scale=trunc(in_w/2)*2:trunc(in_h/2)*2', video_path])
[ "rastervision.semseg.tasks.utils.predict_x", "os.path.join", "rastervision.common.utils._makedirs", "numpy.squeeze", "os.path.isdir", "subprocess.call", "rastervision.semseg.models.factory.SemsegModelFactory", "rastervision.semseg.tasks.utils.plot_prediction" ]
[((457, 477), 'rastervision.semseg.models.factory.SemsegModelFactory', 'SemsegModelFactory', ([], {}), '()\n', (475, 477), False, 'from rastervision.semseg.models.factory import SemsegModelFactory\n'), ((496, 520), 'os.path.join', 'join', (['run_path', '"""videos"""'], {}), "(run_path, 'videos')\n", (500, 520), False, 'from os.path import join, isdir\n'), ((525, 547), 'rastervision.common.utils._makedirs', '_makedirs', (['videos_path'], {}), '(videos_path)\n', (534, 547), False, 'from rastervision.common.utils import _makedirs\n'), ((572, 613), 'os.path.join', 'join', (['run_path', '"""delta_model_checkpoints"""'], {}), "(run_path, 'delta_model_checkpoints')\n", (576, 613), False, 'from os.path import join, isdir\n'), ((1809, 1830), 'rastervision.common.utils._makedirs', '_makedirs', (['video_path'], {}), '(video_path)\n', (1818, 1830), False, 'from rastervision.common.utils import _makedirs\n'), ((2279, 2313), 'os.path.join', 'join', (['video_path', '"""frame_%04d.png"""'], {}), "(video_path, 'frame_%04d.png')\n", (2283, 2313), False, 'from os.path import join, isdir\n'), ((2381, 2491), 'subprocess.call', 'call', (["['avconv', '-r', '2', '-i', frames_path, '-vf',\n 'scale=trunc(in_w/2)*2:trunc(in_h/2)*2', video_path]"], {}), "(['avconv', '-r', '2', '-i', frames_path, '-vf',\n 'scale=trunc(in_w/2)*2:trunc(in_h/2)*2', video_path])\n", (2385, 2491), False, 'from subprocess import call\n'), ((625, 648), 'os.path.isdir', 'isdir', (['checkpoints_path'], {}), '(checkpoints_path)\n', (630, 648), False, 'from os.path import join, isdir\n'), ((763, 793), 'os.path.join', 'join', (['checkpoints_path', '"""*.h5"""'], {}), "(checkpoints_path, '*.h5')\n", (767, 793), False, 'from os.path import join, isdir\n'), ((1294, 1321), 'numpy.squeeze', 'np.squeeze', (['batch.x'], {'axis': '(0)'}), '(batch.x, axis=0)\n', (1304, 1321), True, 'import numpy as np\n'), ((1334, 1361), 'numpy.squeeze', 'np.squeeze', (['batch.y'], {'axis': '(0)'}), '(batch.y, axis=0)\n', (1344, 1361), True, 'import numpy as np\n'), ((1440, 1471), 'numpy.squeeze', 'np.squeeze', (['batch.all_x'], {'axis': '(0)'}), '(batch.all_x, axis=0)\n', (1450, 1471), True, 'import numpy as np\n'), ((2203, 2259), 'rastervision.semseg.tasks.utils.plot_prediction', 'plot_prediction', (['generator', 'all_x', 'y', 'y_pred', 'frame_path'], {}), '(generator, all_x, y, y_pred, frame_path)\n', (2218, 2259), False, 'from rastervision.semseg.tasks.utils import make_prediction_img, plot_prediction, predict_x\n'), ((2034, 2053), 'rastervision.semseg.tasks.utils.predict_x', 'predict_x', (['x', 'model'], {}), '(x, model)\n', (2043, 2053), False, 'from rastervision.semseg.tasks.utils import make_prediction_img, plot_prediction, predict_x\n')]
import numpy as np import cv2 as cv import argparse from PIL import Image, ImageEnhance, ImageDraw import matplotlib.pyplot as plt import os def ROI(frame): #enhancer = ImageEnhance.Contrast(frame) #img = enhancer.enhance(0.7) face_classifier = cv.CascadeClassifier('haarcascade_frontalface_default.xml') gray = cv.cvtColor(np.array(frame), cv.COLOR_BGR2GRAY) faces = face_classifier.detectMultiScale(gray, 1.1, 5) try: x, y, w, h = faces[0] #print(faces) except: x,y,w,h = (0,0,0,0) return x,y,w,h def using_cam(): cap = cv.VideoCapture(0) while True: ret, frame = cap.read() x,y,w,h = ROI(frame) cv.rectangle(frame, (x,y), (x+w, y+h), (127, 0, 255), 2) cv.imshow('ROI', frame) if(cv.waitKey(2) == 13 & 0xFF): break cap.release() cv.destroyAllWindows() def KDEF_data(): base_dir = 'data/' dirs = ['train', 'test', 'validation'] data_dir = 'cropped/' if not os.path.exists(data_dir): os.mkdir(data_dir) count = 1 for sub in dirs: curr_dir = base_dir + sub for i, j, k in os.walk(curr_dir): for name in k: img = Image.open(i+"/"+name) x,y,w,h = ROI(img) img_2 = np.array(img) croped = img_2[y:y+h, x:x+w] #resize = cv.resize(Image.fromarray(croped), (500, 500), interpolation=cv.INTER_CUBIC) #resize = Image.fromarray(resize) #croped = Image.fromarray(croped) #croped.save(data_dir+str(count)+'.jpeg','JPEG') if croped.shape[0]>0: croped = Image.fromarray(croped) croped.save(data_dir+str(count)+'.jpeg','JPEG') count+=1 if __name__ == '__main__': #using_cam() KDEF_data()
[ "cv2.rectangle", "os.path.exists", "PIL.Image.fromarray", "PIL.Image.open", "cv2.imshow", "numpy.array", "cv2.destroyAllWindows", "cv2.VideoCapture", "os.mkdir", "cv2.CascadeClassifier", "cv2.waitKey", "os.walk" ]
[((259, 318), 'cv2.CascadeClassifier', 'cv.CascadeClassifier', (['"""haarcascade_frontalface_default.xml"""'], {}), "('haarcascade_frontalface_default.xml')\n", (279, 318), True, 'import cv2 as cv\n'), ((585, 603), 'cv2.VideoCapture', 'cv.VideoCapture', (['(0)'], {}), '(0)\n', (600, 603), True, 'import cv2 as cv\n'), ((860, 882), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (880, 882), True, 'import cv2 as cv\n'), ((342, 357), 'numpy.array', 'np.array', (['frame'], {}), '(frame)\n', (350, 357), True, 'import numpy as np\n'), ((690, 751), 'cv2.rectangle', 'cv.rectangle', (['frame', '(x, y)', '(x + w, y + h)', '(127, 0, 255)', '(2)'], {}), '(frame, (x, y), (x + w, y + h), (127, 0, 255), 2)\n', (702, 751), True, 'import cv2 as cv\n'), ((755, 778), 'cv2.imshow', 'cv.imshow', (['"""ROI"""', 'frame'], {}), "('ROI', frame)\n", (764, 778), True, 'import cv2 as cv\n'), ((1006, 1030), 'os.path.exists', 'os.path.exists', (['data_dir'], {}), '(data_dir)\n', (1020, 1030), False, 'import os\n'), ((1040, 1058), 'os.mkdir', 'os.mkdir', (['data_dir'], {}), '(data_dir)\n', (1048, 1058), False, 'import os\n'), ((1157, 1174), 'os.walk', 'os.walk', (['curr_dir'], {}), '(curr_dir)\n', (1164, 1174), False, 'import os\n'), ((790, 803), 'cv2.waitKey', 'cv.waitKey', (['(2)'], {}), '(2)\n', (800, 803), True, 'import cv2 as cv\n'), ((1238, 1264), 'PIL.Image.open', 'Image.open', (["(i + '/' + name)"], {}), "(i + '/' + name)\n", (1248, 1264), False, 'from PIL import Image, ImageEnhance, ImageDraw\n'), ((1320, 1333), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (1328, 1333), True, 'import numpy as np\n'), ((1714, 1737), 'PIL.Image.fromarray', 'Image.fromarray', (['croped'], {}), '(croped)\n', (1729, 1737), False, 'from PIL import Image, ImageEnhance, ImageDraw\n')]
""" implement the qmix algorithm with tensorflow, also thanks to the pymarl repo. """ from functools import partial from time import time import numpy as np import tensorflow as tf from absl import logging from smac.env import MultiAgentEnv, StarCraft2Env from xt.algorithm.qmix.episode_buffer_np import EpisodeBatchNP from xt.algorithm.qmix.qmix_alg import DecayThenFlatSchedule, EpsilonGreedyActionSelector class QMixAlgorithm(object): """Target network is for calculating the maximum estimated Q-value in given action a. """ def __init__(self, scheme, args, avail_action_num, seq_limit, dtype): # avail_actions vary with env.map self.n_agents = args.n_agents self.args = args self.dtype = dtype self.obs_shape = self._get_input_shape(scheme) logging.debug("obs_shape: {}".format(self.obs_shape)) self.previous_state = None self.ph_hidden_states_in = None self.hidden_states_out = None self.params = None self.inputs = None self.out_actions = None self.avail_action_num = avail_action_num # 2s_vs_1sc , use the episode limit as fix shape. self.fix_seq_length = seq_limit self.schedule = DecayThenFlatSchedule( args.epsilon_start, args.epsilon_finish, args.epsilon_anneal_time, decay="linear", ) self.epsilon = self.schedule.eval(0) # select action self.selector = EpsilonGreedyActionSelector(self.args) # mix self.state_dim = int(np.prod(args.state_shape)) self.embed_dim = args.mixing_embed_dim # self.global_state_dims = (1, 120) # fixme: 2s3z self.graph = tf.Graph() config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config, graph=self.graph) self.sess = sess self.gru_cell = None self.hi_out_val = None self.hi_out_val_default = None # self.hi_target_out_val = None self.grad_update = None # train op self._explore_paras = None # need update after each train process self.last_target_update_episode = 0 self.ph_obs, self.agent_outs, self.hidden_outs = None, None, None self.ph_avail_action, self.ph_actions, self.ph_train_obs = None, None, None self.ph_train_obs_len, self.agent_explore_replace_op = None, None self.agent_train_replace_op, self.ph_train_states = None, None self.ph_train_target_states, self.q_tot, self.target_q_tot = None, None, None self.mix_train_replace_op = None self.ph_rewards, self.ph_terminated = None, None self.loss, self.ph_mask = None, None def _get_input_shape(self, scheme): """assemble input shape""" input_shape = scheme["obs"]["vshape"] if self.args.obs_last_action: input_shape += scheme["actions_onehot"]["vshape"][0] if self.args.obs_agent_id: input_shape += self.n_agents return input_shape def _get_motivate_actions(self, agents_dim, avail_actions, t_env, test_mode=False): self.epsilon = self.schedule.eval(t_env) if test_mode: # Greedy action selection only self.epsilon = 0.0 # random_numbers = th.rand_like(agent_inputs[:, :, 0]) random_numbers = np.random.rand(agents_dim) # pick_random = (random_numbers < self.epsilon).long() pick_random = np.array(random_numbers < self.epsilon).astype(np.long) # random_actions = Categorical(avail_actions.float()).sample().long() avail_action_len = avail_actions.shape[-1] avail_norm_to_np = np.array(avail_actions / avail_actions.sum(-1)).astype(np.float) random_actions = np.random.multinomial(avail_action_len, avail_norm_to_np).astype(np.long) return pick_random, random_actions def build_agent_net( self, inputs_obs, seq_max, obs_lengths, hidden_state_in=None, ): """default init_state for rnn. """ fc1 = tf.layers.dense( inputs=inputs_obs, units=self.args.rnn_hidden_dim, activation=tf.nn.relu, ) fc1 = tf.transpose(fc1, perm=[0, 2, 1, 3]) print("\n fc1 before reshape: ", fc1) fc1 = tf.reshape(fc1, [-1, seq_max, self.args.rnn_hidden_dim]) print("fc1 after reshape: ", fc1) gru_cell = tf.nn.rnn_cell.GRUCell( num_units=self.args.rnn_hidden_dim, # dtype=self.dtype ) # only record the gru cell once time, to init the hidden value. if not self.gru_cell: self.gru_cell = gru_cell # self.hidden_in_zero = self.gru_cell.zero_state(1, dtype=tf.float32) # https://blog.csdn.net/u010223750/article/details/71079036 # tf.nn.dynamic_rnn rnn_output, hidden_state_out = tf.nn.dynamic_rnn( gru_cell, fc1, dtype=self.dtype, initial_state=hidden_state_in, sequence_length=obs_lengths, # sequence_length=[1, ] ) print("rnn raw out: {} ".format(rnn_output)) rnn_output = tf.reshape(rnn_output, [-1, self.n_agents, seq_max, self.args.rnn_hidden_dim]) rnn_output = tf.transpose(rnn_output, perm=[0, 2, 1, 3]) rnn_output = tf.reshape(rnn_output, [-1, self.args.rnn_hidden_dim]) fc2_outputs = tf.layers.dense( inputs=rnn_output, units=self.args.n_actions, activation=None, # activation=tf.nn.relu, ) out_actions = tf.reshape(fc2_outputs, (-1, self.n_agents, self.avail_action_num)) print("out action: {} \n".format(out_actions)) return out_actions, hidden_state_out def _build_mix_net2(self, agent_qs, states): """build mixer architecture with two hyper embed""" hypernet_embed = self.args.hypernet_embed def hyper_w1(hyper_w1_input): """input shape (none, state_dim)""" with tf.variable_scope("hyper_w1"): hw0 = tf.layers.dense(inputs=hyper_w1_input, units=hypernet_embed, activation=tf.nn.relu) hw1 = tf.layers.dense(inputs=hw0, units=self.embed_dim * self.n_agents, activation=None) return hw1 def hyper_w_final(hyper_w_final_input): """input shape (none, state_dim)""" with tf.variable_scope("hyper_w_final"): hw_f0 = tf.layers.dense( inputs=hyper_w_final_input, units=hypernet_embed, activation=tf.nn.relu, ) hw_f1 = tf.layers.dense(inputs=hw_f0, units=self.embed_dim, activation=None) return hw_f1 def hyper_b1(state_input): """State dependent bias for hidden layer""" with tf.variable_scope("hyper_b1"): return tf.layers.dense(inputs=state_input, units=self.embed_dim, activation=None) def val(state_input): """V(s) instead of a bias for the last layers""" with tf.variable_scope("val_for_bias"): val0 = tf.layers.dense(inputs=state_input, units=self.embed_dim, activation=tf.nn.relu) val2 = tf.layers.dense(inputs=val0, units=1, activation=None) return val2 bs = agent_qs.get_shape().as_list()[0] states_reshaped = tf.reshape(states, (-1, self.state_dim)) agent_qs_reshaped = tf.reshape(agent_qs, (-1, 1, self.n_agents)) # firstly layer w1 = tf.math.abs(hyper_w1(states_reshaped)) b1 = hyper_b1(states_reshaped) w1_reshaped = tf.reshape(w1, (-1, self.n_agents, self.embed_dim)) b1_reshaped = tf.reshape(b1, (-1, 1, self.embed_dim)) to_hidden_val = tf.math.add(tf.matmul(agent_qs_reshaped, w1_reshaped), b1_reshaped) hidden = tf.nn.elu(to_hidden_val) # second layer w_final = tf.math.abs(hyper_w_final(states_reshaped)) w_final_reshaped = tf.reshape(w_final, (-1, self.embed_dim, 1)) # state-dependent bias v = tf.reshape(val(states_reshaped), (-1, 1, 1)) # compute final output y = tf.math.add(tf.matmul(hidden, w_final_reshaped), v) # reshape and return q_tot = tf.reshape(y, (bs, -1, 1)) return q_tot def _build_action_selector(self, agent_inputs, avail_actions, ph_pick_random, ph_random_actions): """firstly, calculate the explore action with numpy out of the graph! """ masked_q_values = tf.identity(agent_inputs) negation_inf_val = tf.ones_like(masked_q_values) * -1e10 masked_q_values = tf.where(avail_actions < 1e-5, negation_inf_val, masked_q_values) picked_actions = ph_pick_random * ph_random_actions + (1 - ph_pick_random) * tf.reduce_max( masked_q_values, reduction_indices=[2]) return picked_actions def build_inputs(self, batch, t): """ # Assumes homogenous agents with flat observations. # Other MACs might want to e.g. delegate building inputs to each agent 1. inference stage, use batch = 1, 2. train stage, use batch = episode.limit Also, use numpy for combine the inputs data """ bs = batch.batch_size inputs = list() inputs.append(batch["obs"][:, t]) # b1av # print("forward input.obs shape, ", np.shape(inputs[0])) # torch.Size([1, 5, 80]) if self.args.obs_last_action: if t == 0: # tmp = batch["actions_onehot"][:, t] # print(tmp, np.shape(tmp), np.shape(batch["actions_onehot"])) inputs.append(np.zeros_like(batch["actions_onehot"][:, t])) # print(inputs) else: inputs.append(batch["actions_onehot"][:, t - 1]) # print("forward input.onehot shape, ", # np.shape(inputs[-1]), np.shape(batch["actions_onehot"])) if self.args.obs_agent_id: _ag_id = np.expand_dims(np.eye(self.n_agents), axis=0) # add axis 0 inputs.append(np.tile(_ag_id, (bs, 1, 1))) # broadcast_to # print("inputs shape: ", [np.shape(i) for i in inputs]) # inputs = np.concatenate( # [x.reshape(bs * self.n_agents, -1) for x in inputs], axis=1 # ) # [batch_size, 1, agents, obs_size] inputs = np.expand_dims(np.concatenate(inputs, axis=-1), axis=1) # fixme: make to [batch_size, agent_num, seq_len, obs_size] # print("forward input shape, ", np.shape(inputs)) # torch.Size([5, 96]) # print("inputs shape: ", inputs.shape) return inputs def build_actor_graph(self): """actor graph used by the explorer""" with self.graph.as_default(): self.ph_obs = tf.placeholder(tf.float32, shape=(1, 1, self.n_agents, self.obs_shape), name="obs") # self.ph_obs_len = tf.placeholder(tf.float32, shape=(None,), name="obs_len") self.ph_hidden_states_in = tf.placeholder(tf.float32, shape=(None, self.args.rnn_hidden_dim), name="hidden_in") with tf.variable_scope("explore_agent"): self.agent_outs, self.hidden_outs = self.build_agent_net( inputs_obs=self.ph_obs, seq_max=1, # --------------------- 1, importance obs_lengths=[1 for _ in range(self.n_agents)], hidden_state_in=self.ph_hidden_states_in, ) self._explore_paras = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="explore_agent") def reset_hidden_state(self): """reset hidden before start each episode""" self.hi_out_val = self.hi_out_val_default def get_explore_actions(self, ep_batch, t_ep, t_env, test_mode): """get explore action with numpy""" avail_actions = ep_batch["avail_actions"][:, t_ep] agent_inputs = self.build_inputs(ep_batch, t_ep) # agent_inputs = out_val = self.infer_actions(agent_inputs) select_actions = self.selector.select_action(out_val, avail_actions, t_env, test_mode=test_mode) # print("out_val: {}, select action: {}, avail_actions, {}, t_env:{}".format( # out_val, select_actions, avail_actions, t_env)) return select_actions def infer_actions(self, agent_inputs): """inference with tf.sess.run""" out_val, self.hi_out_val = self.sess.run( [self.agent_outs, self.hidden_outs], feed_dict={ self.ph_obs: agent_inputs, # self.ph_obs_len: list(obs_len), self.ph_hidden_states_in: self.hi_out_val, }, ) return out_val @staticmethod def _gather4d_on_dim3(inputs, indices): """ gather 4dim tensor into 3dim, same to the pytorch.gather + sequeeze(3) function. :param inputs: :param indices: :return: """ print("inputs: ", inputs) len_0d, len_1d, len_2d, len_3d = inputs.get_shape().as_list() print("len_0d, len_1d, len_2d, len_3d", len_0d, len_1d, len_2d, len_3d) inputs = tf.reshape(inputs, (-1, len_3d)) calc_0d = inputs.get_shape()[0] flag_0d, flag_1d, flag_2d, flag_3d = indices.get_shape() indices = tf.reshape(indices, [-1, flag_3d]) idx_matrix = tf.tile(tf.expand_dims(tf.range(0, len_3d, dtype=indices.dtype), 0), [calc_0d, 1]) indices_t = tf.transpose(indices) idx_mask = tf.equal(idx_matrix, tf.transpose(indices_t)) inputs = tf.reshape(tf.boolean_mask(inputs, idx_mask), [flag_0d, flag_1d, flag_2d]) return inputs @staticmethod def _print_trainable_var_name(**kwargs): """print trainable variable name """ for k, v in kwargs.items(): print("{}: \n {}".format(k, list([t.name for t in v]))) def build_train_graph(self): """train graph cannot connect-up to actor.graph, because of the different seq_max(1 vs limit) """ with self.graph.as_default(): self.ph_avail_action = tf.placeholder( tf.float32, shape=[ self.args.batch_size, self.fix_seq_length + 1, self.n_agents, self.avail_action_num, ], name="avail_action", ) self.ph_actions = tf.placeholder( tf.float32, shape=[self.args.batch_size, self.fix_seq_length, self.n_agents, 1], name="actions", ) # agent_num = self.n_agents # seq_max = 300 # -------eval rnn agent ------------------ self.ph_train_obs = tf.placeholder( tf.float32, shape=( self.args.batch_size, self.fix_seq_length + 1, self.n_agents, self.obs_shape, ), name="train_obs", ) self.ph_train_obs_len = tf.placeholder(tf.float32, shape=(None, ), name="train_obs_len") with tf.variable_scope("eval_agent"): trajectory_agent_outs, _ = self.build_agent_net( inputs_obs=self.ph_train_obs, seq_max=self.fix_seq_length + 1, # --------------------- importance obs_lengths=self.ph_train_obs_len, hidden_state_in=None, # with total trajectory, needn't hold hidden ) with tf.variable_scope("target_agent"): tar_agent_outs_tmp, _ = self.build_agent_net( inputs_obs=self.ph_train_obs, # fix value, different between explore and train seq_max=self.fix_seq_length + 1, obs_lengths=self.ph_train_obs_len, hidden_state_in=None, ) target_trajectory_agent_outs = tf.stop_gradient(tar_agent_outs_tmp) _eval_agent_paras = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="eval_agent") _target_agent_paras = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="target_agent") with tf.variable_scope("soft_replacement"): self.agent_train_replace_op = [tf.assign(t, e) for t, e in zip(_target_agent_paras, _eval_agent_paras)] self.agent_explore_replace_op = [ tf.assign(t, e) for t, e in zip(self._explore_paras, _eval_agent_paras) ] self._print_trainable_var_name( _eval_agent_paras=_eval_agent_paras, _target_agent_paras=_target_agent_paras, _explore_paras=self._explore_paras, ) # agent out to max q values # Calculate estimated Q-Values ---------------- mac_out = tf.reshape( trajectory_agent_outs, [self.args.batch_size, self.fix_seq_length + 1, self.n_agents, -1], ) print("mac_out: ", mac_out) chosen_action_qvals = self._gather4d_on_dim3(mac_out[:, :-1], self.ph_actions) # ----- # Calculate the Q-Values necessary for the target ----------- target_mac_out = tf.reshape( target_trajectory_agent_outs, [self.args.batch_size, self.fix_seq_length + 1, self.n_agents, -1], ) target_mac_out = target_mac_out[:, 1:] # Mask out unavailable actions # target_mac_out[avail_actions[:, 1:] == 0] = -9999999 indices = tf.equal(self.ph_avail_action[:, 1:], 0) # TypeError: Input 'e' of 'Select' Op has type float32 that # does not match type int32 of argument 't'. mask_val = tf.tile( [[[[-999999.0]]]], [ self.args.batch_size, self.fix_seq_length, self.n_agents, self.avail_action_num, ], ) print("indices: ", indices) print("mask_val: ", mask_val) print("target_mac_out: ", target_mac_out) target_mac_out = tf.where(indices, mask_val, target_mac_out) if self.args.double_q: # Get actions that maximise live Q (for double q-learning) mac_out_detach = tf.stop_gradient(tf.identity(mac_out[:, 1:])) mac_out_detach = tf.where(indices, mask_val, mac_out_detach) cur_max_actions = tf.expand_dims(tf.argmax(mac_out_detach, axis=-1), -1) target_max_qvals = self._gather4d_on_dim3(target_mac_out, cur_max_actions) else: target_max_qvals = tf.reduce_max(target_mac_out, axis=[-1]) # eval mixer --------------- self.ph_train_states = tf.placeholder( tf.float32, shape=(self.args.batch_size, self.fix_seq_length, self.state_dim), name="train_stats", ) # target mixer ------------------- self.ph_train_target_states = tf.placeholder( tf.float32, shape=(self.args.batch_size, self.fix_seq_length, self.state_dim), name="train_target_stats", ) with tf.variable_scope("eval_mixer"): self.q_tot = self._build_mix_net2(chosen_action_qvals, self.ph_train_states) with tf.variable_scope("target_mixer"): q_tot_tmp = self._build_mix_net2(target_max_qvals, self.ph_train_target_states) self.target_q_tot = tf.stop_gradient(q_tot_tmp) _eval_mix_paras = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="eval_mixer") _target_mix_paras = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="target_mixer") with tf.variable_scope("soft_replacement"): self.mix_train_replace_op = [tf.assign(t, e) for t, e in zip(_target_mix_paras, _eval_mix_paras)] self._print_trainable_var_name(_eval_mix_paras=_eval_mix_paras, _target_mix_paras=_target_mix_paras) # -------- self.ph_rewards = tf.placeholder( tf.float32, shape=(self.args.batch_size, self.fix_seq_length, 1), name="rewards", ) self.ph_terminated = tf.placeholder( tf.float32, shape=(self.args.batch_size, self.fix_seq_length, 1), name="terminated", ) self.ph_mask = tf.placeholder( tf.float32, shape=(self.args.batch_size, self.fix_seq_length, 1), name="mask", ) print("self.ph_rewards: ", self.ph_rewards) print("self.args.gamma: ", self.args.gamma) print("self.ph_terminated: ", self.ph_terminated) print("self.target_q_tot: ", self.target_q_tot) # Calculate 1-step Q-Learning targets targets = (self.ph_rewards + self.args.gamma * (1.0 - self.ph_terminated) * self.target_q_tot) # Td-error td_error = self.q_tot - tf.stop_gradient(targets) # mask = mask.expand_as(td_error) #fixme: default as same shape! # 0-out the targets that came from padded data masked_td_error = tf.multiply(td_error, self.ph_mask) self.loss = tf.reduce_sum(masked_td_error**2) / tf.reduce_sum(self.ph_mask) # # Optimise optimizer = tf.train.RMSPropOptimizer(self.args.lr, decay=0.95, epsilon=1.5e-7, centered=True) grads_and_vars = optimizer.compute_gradients(self.loss) capped_gvs = [( grad if grad is None else tf.clip_by_norm(grad, clip_norm=self.args.grad_norm_clip), var, ) for grad, var in grads_and_vars] self.grad_update = optimizer.apply_gradients(capped_gvs) def _update_targets(self, episode_num): """ update weights periodically. 1. from eval agent to target agent 2. from target mixer to eval mixer :return: """ if (episode_num - self.last_target_update_episode) / self.args.target_update_interval >= 1.0: _a, _m = self.sess.run([self.agent_train_replace_op, self.mix_train_replace_op]) print('episode ' + str(episode_num) + ', target Q network params replaced!') self.last_target_update_episode = episode_num def _update_explore_agent(self): """ update explore agent after each train process :return: """ _ = self.sess.run(self.agent_explore_replace_op) def save_explore_agent_weights(self, save_path): """save explore agent weight for explorer""" explore_saver = tf.train.Saver({t.name: t for t in self._explore_paras}) explore_saver.save(self.sess, save_path=save_path, write_meta_graph=False) # tf.train.list_variables(tf.train.latest_checkpoint(wp)) def train_whole_graph(self, batch: EpisodeBatchNP, t_env: int, episode_num: int): # Truncate batch to only filled timesteps max_ep_t = batch.max_t_filled() logging.debug("episode sample with max_ep_t: {}".format(max_ep_t)) # batch = batch[:, :max_ep_t] # Get the relevant quantities rewards = batch["reward"][:, :-1] actions = batch["actions"][:, :-1] terminated = batch["terminated"][:, :-1].astype(np.float32) mask = batch["filled"][:, :-1].astype(np.float32) mask[:, 1:] = mask[:, 1:] * (1 - terminated[:, :-1]) avail_actions = batch["avail_actions"] # # # Calculate estimated Q-Values # [bs, seq_len, n_agents, obs_size] [32, 1, 2, 26] --> [32, 301, 2, 26] _inputs = [self.build_inputs(batch, t) for t in range(batch.max_seq_length)] batch_trajectories = np.concatenate(_inputs, axis=1) logging.debug("batch_trajectories.shape: {}".format(batch_trajectories.shape)) logging.debug("rewards.shape: {}".format(rewards.shape)) logging.debug("actions.shape: {}".format(actions.shape)) logging.debug("terminated.shape: {}".format(terminated.shape)) logging.debug("mask.shape: {}".format(mask.shape)) logging.debug("avail_actions.shape: {}".format(avail_actions.shape)) logging.debug("batch.max_seq_length: {}".format(batch.max_seq_length)) logging.debug("batch.batch_size: {}".format(batch.batch_size)) # to get action --> [32, 300, 2, 7] # [32*301*2, 26] --> [32*301*2, 7] --> [32, 301, 2, 7] --> [32, 300, 2, 7] # batch4train = batch_trajectories.reshape([-1, batch_trajectories.shape[-1]]) # writer = tf.summary.FileWriter(logdir="logdir", graph=self.graph) # writer.flush() _, loss_val = self.sess.run( [self.grad_update, self.loss], feed_dict={ self.ph_train_obs: batch_trajectories, # Note: split trajectory with each agent. self.ph_train_obs_len: list( [max_ep_t for _ in range(batch.batch_size * self.n_agents)]), self.ph_avail_action: avail_actions, self.ph_actions: actions, self.ph_train_states: batch["state"][:, :-1], self.ph_train_target_states: batch["state"][:, 1:], self.ph_rewards: rewards, self.ph_terminated: terminated, self.ph_mask: mask, }, ) logging.info("episode-{}, t_env-{}, train_loss: {}".format(episode_num, t_env, loss_val)) # from tests.qmix.test_assign import print_mix_tensor_val, print_agent_tensor_val # print_agent_tensor_val(self.graph, self.sess, "before update explore agent") self._update_explore_agent() self.save_explore_agent_weights(save_path="./save_models/actor{}".format(episode_num)) # print_agent_tensor_val(self.graph, self.sess, "after update explore agent") # print_mix_tensor_val(self.graph, self.sess, "before update target") self._update_targets(episode_num=episode_num) # print_mix_tensor_val(self.graph, self.sess, "after update target") return {"train_loss": loss_val} class QMixAgent(object): """agent for 2s_vs_1sc""" def __init__(self, scheme, args): self.args = args self.scheme = scheme def env_fn(env, **kwargs) -> MultiAgentEnv: return env(**kwargs) sc2_env_func = partial(env_fn, env=StarCraft2Env) self.env = sc2_env_func(**self.args.env_args) self.episode_limit = self.env.episode_limit print("limit seq: ", self.episode_limit) env_info = self.env.get_env_info() print("env_info: ", env_info) self.avail_action_num = env_info["n_actions"] self.t = 0 self.t_env = 0 self.n_episode = 0 self.alg = QMixAlgorithm(self.scheme, self.args, self.avail_action_num, self.episode_limit, tf.float32) self.replay_buffer = None self.batch = None # self.bm_writer = BenchmarkBoard("logdir", "qmix_{}".format( # strftime("%Y-%m-%d %H-%M-%S", localtime()))) def setup(self, scheme, groups, preprocess): self.new_batch = partial( EpisodeBatchNP, scheme, groups, 1, # Note: batch size must be 1 in a episode self.episode_limit + 1, preprocess=preprocess, ) self.alg.build_actor_graph() # 1 only use for explore ! self.alg.build_train_graph() # note: init with only once are importance! with self.alg.graph.as_default(): self.alg.sess.run(tf.global_variables_initializer()) self.alg.hi_out_val_default = self.alg.sess.run( self.alg.gru_cell.zero_state(self.args.n_agents, dtype=tf.float32)) writer = tf.summary.FileWriter(logdir="logdir", graph=self.alg.graph) writer.flush() def reset(self): self.alg.reset_hidden_state() self.batch = self.new_batch() self.env.reset() self.t = 0 def run_one_episode(self, test_mode=False): # time_info = [0, 0, 0] # reset, interaction _t = time() self.reset() _reset_t = time() - _t terminated = False episode_return = 0 env_step_list = [] infer_time_list = [] interaction_cycle, cycle_start = [], None def show_time(text, time_list): print("{} mean: {}, Hz-~{}, steps-{}, last-7 as: \n {}".format( text, np.mean(time_list[5:]), int(1.0 / np.mean(time_list)), len(time_list), time_list[-7:], )) return np.mean(time_list[5:]) _start_explore = time() while not terminated: pre_transition_data = { "state": [self.env.get_state()], "avail_actions": [self.env.get_avail_actions()], "obs": [self.env.get_obs()], } self.batch.update(pre_transition_data, ts=self.t) # Pass the entire batch of experiences up till now to the agents # Receive the actions for each agent at this time step in a batch of size 1 before_infer = time() actions = self.alg.get_explore_actions(self.batch, t_ep=self.t, t_env=self.t_env, test_mode=test_mode) infer_time_list.append(time() - before_infer) before_env_step = time() reward, terminated, env_info = self.env.step(actions[0]) env_step_list.append(time() - before_env_step) episode_return += reward post_transition_data = { "actions": actions, "reward": [(reward, )], "terminated": [(terminated != env_info.get("episode_limit", False), )], } self.batch.update(post_transition_data, ts=self.t) self.t += 1 if not cycle_start: cycle_start = time() else: interaction_cycle.append(time() - cycle_start) cycle_start = time() last_data = { "state": [self.env.get_state()], "avail_actions": [self.env.get_avail_actions()], "obs": [self.env.get_obs()], } self.batch.update(last_data, ts=self.t) # Select actions in the last stored state actions = self.alg.get_explore_actions(self.batch, t_ep=self.t, t_env=self.t_env, test_mode=test_mode) self.batch.update({"actions": actions}, ts=self.t) if not test_mode: self.t_env += self.t self.n_episode += 1 # # for time analysis # env_avg = show_time("env_step", env_step_list) # infer_avg = show_time("infer time", infer_time_list) # cycle_avg = show_time("--> cycle", interaction_cycle) # print( # "env step proportion: {}, infer proportion:{}.".format( # env_avg / cycle_avg, infer_avg / cycle_avg # ) # ) logging.debug("t_env: {}, explore reward: {}".format(self.t_env, episode_return)) # print("env_info: ", env_info) if env_info.get("battle_won"): print("\n", "*" * 50, "won once in {} mode! \n".format("TEST" if test_mode else "EXPLORE")) # self.bm_writer.insert_records( record_info_list = [("reset_time", _reset_t, self.n_episode), ("interaction_time", time() - _start_explore, self.n_episode), ("env_step_mean", np.mean(env_step_list), self.n_episode), ("infer_mean", np.mean(infer_time_list), self.n_episode), ("cycle_mean", np.mean(interaction_cycle), self.n_episode), ("explore_reward", episode_return, self.t_env), ("step_per_episode", self.t, self.n_episode)] return self.batch, record_info_list, env_info def train(self, batch_data, t_env, episode_num): info = self.alg.train_whole_graph(batch_data, t_env, episode_num) record_info = [("train_loss", info["train_loss"], self.t_env)] return record_info # self.bm_writer.insert_records([("train_loss", info["train_loss"], self.t_env)])
[ "numpy.prod", "tensorflow.tile", "tensorflow.equal", "numpy.random.rand", "tensorflow.transpose", "tensorflow.boolean_mask", "tensorflow.nn.elu", "tensorflow.reduce_sum", "tensorflow.multiply", "numpy.array", "tensorflow.ones_like", "tensorflow.Graph", "numpy.mean", "xt.algorithm.qmix.qmix...
[((1239, 1348), 'xt.algorithm.qmix.qmix_alg.DecayThenFlatSchedule', 'DecayThenFlatSchedule', (['args.epsilon_start', 'args.epsilon_finish', 'args.epsilon_anneal_time'], {'decay': '"""linear"""'}), "(args.epsilon_start, args.epsilon_finish, args.\n epsilon_anneal_time, decay='linear')\n", (1260, 1348), False, 'from xt.algorithm.qmix.qmix_alg import DecayThenFlatSchedule, EpsilonGreedyActionSelector\n'), ((1497, 1535), 'xt.algorithm.qmix.qmix_alg.EpsilonGreedyActionSelector', 'EpsilonGreedyActionSelector', (['self.args'], {}), '(self.args)\n', (1524, 1535), False, 'from xt.algorithm.qmix.qmix_alg import DecayThenFlatSchedule, EpsilonGreedyActionSelector\n'), ((1735, 1745), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1743, 1745), True, 'import tensorflow as tf\n'), ((1764, 1780), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (1778, 1780), True, 'import tensorflow as tf\n'), ((1843, 1886), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config', 'graph': 'self.graph'}), '(config=config, graph=self.graph)\n', (1853, 1886), True, 'import tensorflow as tf\n'), ((3401, 3427), 'numpy.random.rand', 'np.random.rand', (['agents_dim'], {}), '(agents_dim)\n', (3415, 3427), True, 'import numpy as np\n'), ((4153, 4246), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'inputs_obs', 'units': 'self.args.rnn_hidden_dim', 'activation': 'tf.nn.relu'}), '(inputs=inputs_obs, units=self.args.rnn_hidden_dim,\n activation=tf.nn.relu)\n', (4168, 4246), True, 'import tensorflow as tf\n'), ((4305, 4341), 'tensorflow.transpose', 'tf.transpose', (['fc1'], {'perm': '[0, 2, 1, 3]'}), '(fc1, perm=[0, 2, 1, 3])\n', (4317, 4341), True, 'import tensorflow as tf\n'), ((4402, 4458), 'tensorflow.reshape', 'tf.reshape', (['fc1', '[-1, seq_max, self.args.rnn_hidden_dim]'], {}), '(fc1, [-1, seq_max, self.args.rnn_hidden_dim])\n', (4412, 4458), True, 'import tensorflow as tf\n'), ((4521, 4579), 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', ([], {'num_units': 'self.args.rnn_hidden_dim'}), '(num_units=self.args.rnn_hidden_dim)\n', (4543, 4579), True, 'import tensorflow as tf\n'), ((4977, 5092), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['gru_cell', 'fc1'], {'dtype': 'self.dtype', 'initial_state': 'hidden_state_in', 'sequence_length': 'obs_lengths'}), '(gru_cell, fc1, dtype=self.dtype, initial_state=\n hidden_state_in, sequence_length=obs_lengths)\n', (4994, 5092), True, 'import tensorflow as tf\n'), ((5269, 5347), 'tensorflow.reshape', 'tf.reshape', (['rnn_output', '[-1, self.n_agents, seq_max, self.args.rnn_hidden_dim]'], {}), '(rnn_output, [-1, self.n_agents, seq_max, self.args.rnn_hidden_dim])\n', (5279, 5347), True, 'import tensorflow as tf\n'), ((5369, 5412), 'tensorflow.transpose', 'tf.transpose', (['rnn_output'], {'perm': '[0, 2, 1, 3]'}), '(rnn_output, perm=[0, 2, 1, 3])\n', (5381, 5412), True, 'import tensorflow as tf\n'), ((5435, 5489), 'tensorflow.reshape', 'tf.reshape', (['rnn_output', '[-1, self.args.rnn_hidden_dim]'], {}), '(rnn_output, [-1, self.args.rnn_hidden_dim])\n', (5445, 5489), True, 'import tensorflow as tf\n'), ((5513, 5591), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'rnn_output', 'units': 'self.args.n_actions', 'activation': 'None'}), '(inputs=rnn_output, units=self.args.n_actions, activation=None)\n', (5528, 5591), True, 'import tensorflow as tf\n'), ((5699, 5766), 'tensorflow.reshape', 'tf.reshape', (['fc2_outputs', '(-1, self.n_agents, self.avail_action_num)'], {}), '(fc2_outputs, (-1, self.n_agents, self.avail_action_num))\n', (5709, 5766), True, 'import tensorflow as tf\n'), ((7530, 7570), 'tensorflow.reshape', 'tf.reshape', (['states', '(-1, self.state_dim)'], {}), '(states, (-1, self.state_dim))\n', (7540, 7570), True, 'import tensorflow as tf\n'), ((7599, 7643), 'tensorflow.reshape', 'tf.reshape', (['agent_qs', '(-1, 1, self.n_agents)'], {}), '(agent_qs, (-1, 1, self.n_agents))\n', (7609, 7643), True, 'import tensorflow as tf\n'), ((7783, 7834), 'tensorflow.reshape', 'tf.reshape', (['w1', '(-1, self.n_agents, self.embed_dim)'], {}), '(w1, (-1, self.n_agents, self.embed_dim))\n', (7793, 7834), True, 'import tensorflow as tf\n'), ((7857, 7896), 'tensorflow.reshape', 'tf.reshape', (['b1', '(-1, 1, self.embed_dim)'], {}), '(b1, (-1, 1, self.embed_dim))\n', (7867, 7896), True, 'import tensorflow as tf\n'), ((8007, 8031), 'tensorflow.nn.elu', 'tf.nn.elu', (['to_hidden_val'], {}), '(to_hidden_val)\n', (8016, 8031), True, 'import tensorflow as tf\n'), ((8145, 8189), 'tensorflow.reshape', 'tf.reshape', (['w_final', '(-1, self.embed_dim, 1)'], {}), '(w_final, (-1, self.embed_dim, 1))\n', (8155, 8189), True, 'import tensorflow as tf\n'), ((8421, 8447), 'tensorflow.reshape', 'tf.reshape', (['y', '(bs, -1, 1)'], {}), '(y, (bs, -1, 1))\n', (8431, 8447), True, 'import tensorflow as tf\n'), ((8689, 8714), 'tensorflow.identity', 'tf.identity', (['agent_inputs'], {}), '(agent_inputs)\n', (8700, 8714), True, 'import tensorflow as tf\n'), ((8806, 8872), 'tensorflow.where', 'tf.where', (['(avail_actions < 1e-05)', 'negation_inf_val', 'masked_q_values'], {}), '(avail_actions < 1e-05, negation_inf_val, masked_q_values)\n', (8814, 8872), True, 'import tensorflow as tf\n'), ((13453, 13485), 'tensorflow.reshape', 'tf.reshape', (['inputs', '(-1, len_3d)'], {}), '(inputs, (-1, len_3d))\n', (13463, 13485), True, 'import tensorflow as tf\n'), ((13610, 13644), 'tensorflow.reshape', 'tf.reshape', (['indices', '[-1, flag_3d]'], {}), '(indices, [-1, flag_3d])\n', (13620, 13644), True, 'import tensorflow as tf\n'), ((13770, 13791), 'tensorflow.transpose', 'tf.transpose', (['indices'], {}), '(indices)\n', (13782, 13791), True, 'import tensorflow as tf\n'), ((23288, 23344), 'tensorflow.train.Saver', 'tf.train.Saver', (['{t.name: t for t in self._explore_paras}'], {}), '({t.name: t for t in self._explore_paras})\n', (23302, 23344), True, 'import tensorflow as tf\n'), ((24382, 24413), 'numpy.concatenate', 'np.concatenate', (['_inputs'], {'axis': '(1)'}), '(_inputs, axis=1)\n', (24396, 24413), True, 'import numpy as np\n'), ((27031, 27065), 'functools.partial', 'partial', (['env_fn'], {'env': 'StarCraft2Env'}), '(env_fn, env=StarCraft2Env)\n', (27038, 27065), False, 'from functools import partial\n'), ((27804, 27897), 'functools.partial', 'partial', (['EpisodeBatchNP', 'scheme', 'groups', '(1)', '(self.episode_limit + 1)'], {'preprocess': 'preprocess'}), '(EpisodeBatchNP, scheme, groups, 1, self.episode_limit + 1,\n preprocess=preprocess)\n', (27811, 27897), False, 'from functools import partial\n'), ((28447, 28507), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', ([], {'logdir': '"""logdir"""', 'graph': 'self.alg.graph'}), "(logdir='logdir', graph=self.alg.graph)\n", (28468, 28507), True, 'import tensorflow as tf\n'), ((28789, 28795), 'time.time', 'time', ([], {}), '()\n', (28793, 28795), False, 'from time import time\n'), ((29384, 29390), 'time.time', 'time', ([], {}), '()\n', (29388, 29390), False, 'from time import time\n'), ((1580, 1605), 'numpy.prod', 'np.prod', (['args.state_shape'], {}), '(args.state_shape)\n', (1587, 1605), True, 'import numpy as np\n'), ((7934, 7975), 'tensorflow.matmul', 'tf.matmul', (['agent_qs_reshaped', 'w1_reshaped'], {}), '(agent_qs_reshaped, w1_reshaped)\n', (7943, 7975), True, 'import tensorflow as tf\n'), ((8335, 8370), 'tensorflow.matmul', 'tf.matmul', (['hidden', 'w_final_reshaped'], {}), '(hidden, w_final_reshaped)\n', (8344, 8370), True, 'import tensorflow as tf\n'), ((8742, 8771), 'tensorflow.ones_like', 'tf.ones_like', (['masked_q_values'], {}), '(masked_q_values)\n', (8754, 8771), True, 'import tensorflow as tf\n'), ((10563, 10594), 'numpy.concatenate', 'np.concatenate', (['inputs'], {'axis': '(-1)'}), '(inputs, axis=-1)\n', (10577, 10594), True, 'import numpy as np\n'), ((10969, 11056), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(1, 1, self.n_agents, self.obs_shape)', 'name': '"""obs"""'}), "(tf.float32, shape=(1, 1, self.n_agents, self.obs_shape),\n name='obs')\n", (10983, 11056), True, 'import tensorflow as tf\n'), ((11183, 11272), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, self.args.rnn_hidden_dim)', 'name': '"""hidden_in"""'}), "(tf.float32, shape=(None, self.args.rnn_hidden_dim), name=\n 'hidden_in')\n", (11197, 11272), True, 'import tensorflow as tf\n'), ((11800, 11874), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {'scope': '"""explore_agent"""'}), "(tf.GraphKeys.TRAINABLE_VARIABLES, scope='explore_agent')\n", (11817, 11874), True, 'import tensorflow as tf\n'), ((13832, 13855), 'tensorflow.transpose', 'tf.transpose', (['indices_t'], {}), '(indices_t)\n', (13844, 13855), True, 'import tensorflow as tf\n'), ((13886, 13919), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['inputs', 'idx_mask'], {}), '(inputs, idx_mask)\n', (13901, 13919), True, 'import tensorflow as tf\n'), ((14414, 14558), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[self.args.batch_size, self.fix_seq_length + 1, self.n_agents, self.\n avail_action_num]', 'name': '"""avail_action"""'}), "(tf.float32, shape=[self.args.batch_size, self.fix_seq_length +\n 1, self.n_agents, self.avail_action_num], name='avail_action')\n", (14428, 14558), True, 'import tensorflow as tf\n'), ((14748, 14863), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[self.args.batch_size, self.fix_seq_length, self.n_agents, 1]', 'name': '"""actions"""'}), "(tf.float32, shape=[self.args.batch_size, self.fix_seq_length,\n self.n_agents, 1], name='actions')\n", (14762, 14863), True, 'import tensorflow as tf\n'), ((15079, 15213), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(self.args.batch_size, self.fix_seq_length + 1, self.n_agents, self.obs_shape)', 'name': '"""train_obs"""'}), "(tf.float32, shape=(self.args.batch_size, self.fix_seq_length +\n 1, self.n_agents, self.obs_shape), name='train_obs')\n", (15093, 15213), True, 'import tensorflow as tf\n'), ((15408, 15471), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None,)', 'name': '"""train_obs_len"""'}), "(tf.float32, shape=(None,), name='train_obs_len')\n", (15422, 15471), True, 'import tensorflow as tf\n'), ((16408, 16479), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {'scope': '"""eval_agent"""'}), "(tf.GraphKeys.TRAINABLE_VARIABLES, scope='eval_agent')\n", (16425, 16479), True, 'import tensorflow as tf\n'), ((16514, 16587), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {'scope': '"""target_agent"""'}), "(tf.GraphKeys.TRAINABLE_VARIABLES, scope='target_agent')\n", (16531, 16587), True, 'import tensorflow as tf\n'), ((17270, 17376), 'tensorflow.reshape', 'tf.reshape', (['trajectory_agent_outs', '[self.args.batch_size, self.fix_seq_length + 1, self.n_agents, -1]'], {}), '(trajectory_agent_outs, [self.args.batch_size, self.\n fix_seq_length + 1, self.n_agents, -1])\n', (17280, 17376), True, 'import tensorflow as tf\n'), ((17664, 17777), 'tensorflow.reshape', 'tf.reshape', (['target_trajectory_agent_outs', '[self.args.batch_size, self.fix_seq_length + 1, self.n_agents, -1]'], {}), '(target_trajectory_agent_outs, [self.args.batch_size, self.\n fix_seq_length + 1, self.n_agents, -1])\n', (17674, 17777), True, 'import tensorflow as tf\n'), ((18004, 18044), 'tensorflow.equal', 'tf.equal', (['self.ph_avail_action[:, 1:]', '(0)'], {}), '(self.ph_avail_action[:, 1:], 0)\n', (18012, 18044), True, 'import tensorflow as tf\n'), ((18197, 18311), 'tensorflow.tile', 'tf.tile', (['[[[[-999999.0]]]]', '[self.args.batch_size, self.fix_seq_length, self.n_agents, self.\n avail_action_num]'], {}), '([[[[-999999.0]]]], [self.args.batch_size, self.fix_seq_length, self\n .n_agents, self.avail_action_num])\n', (18204, 18311), True, 'import tensorflow as tf\n'), ((18619, 18662), 'tensorflow.where', 'tf.where', (['indices', 'mask_val', 'target_mac_out'], {}), '(indices, mask_val, target_mac_out)\n', (18627, 18662), True, 'import tensorflow as tf\n'), ((19281, 19398), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(self.args.batch_size, self.fix_seq_length, self.state_dim)', 'name': '"""train_stats"""'}), "(tf.float32, shape=(self.args.batch_size, self.fix_seq_length,\n self.state_dim), name='train_stats')\n", (19295, 19398), True, 'import tensorflow as tf\n'), ((19547, 19671), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(self.args.batch_size, self.fix_seq_length, self.state_dim)', 'name': '"""train_target_stats"""'}), "(tf.float32, shape=(self.args.batch_size, self.fix_seq_length,\n self.state_dim), name='train_target_stats')\n", (19561, 19671), True, 'import tensorflow as tf\n'), ((20119, 20190), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {'scope': '"""eval_mixer"""'}), "(tf.GraphKeys.TRAINABLE_VARIABLES, scope='eval_mixer')\n", (20136, 20190), True, 'import tensorflow as tf\n'), ((20223, 20296), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {'scope': '"""target_mixer"""'}), "(tf.GraphKeys.TRAINABLE_VARIABLES, scope='target_mixer')\n", (20240, 20296), True, 'import tensorflow as tf\n'), ((20636, 20736), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(self.args.batch_size, self.fix_seq_length, 1)', 'name': '"""rewards"""'}), "(tf.float32, shape=(self.args.batch_size, self.fix_seq_length,\n 1), name='rewards')\n", (20650, 20736), True, 'import tensorflow as tf\n'), ((20829, 20932), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(self.args.batch_size, self.fix_seq_length, 1)', 'name': '"""terminated"""'}), "(tf.float32, shape=(self.args.batch_size, self.fix_seq_length,\n 1), name='terminated')\n", (20843, 20932), True, 'import tensorflow as tf\n'), ((21019, 21116), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(self.args.batch_size, self.fix_seq_length, 1)', 'name': '"""mask"""'}), "(tf.float32, shape=(self.args.batch_size, self.fix_seq_length,\n 1), name='mask')\n", (21033, 21116), True, 'import tensorflow as tf\n'), ((21824, 21859), 'tensorflow.multiply', 'tf.multiply', (['td_error', 'self.ph_mask'], {}), '(td_error, self.ph_mask)\n', (21835, 21859), True, 'import tensorflow as tf\n'), ((21999, 22086), 'tensorflow.train.RMSPropOptimizer', 'tf.train.RMSPropOptimizer', (['self.args.lr'], {'decay': '(0.95)', 'epsilon': '(1.5e-07)', 'centered': '(True)'}), '(self.args.lr, decay=0.95, epsilon=1.5e-07,\n centered=True)\n', (22024, 22086), True, 'import tensorflow as tf\n'), ((28836, 28842), 'time.time', 'time', ([], {}), '()\n', (28840, 28842), False, 'from time import time\n'), ((29335, 29357), 'numpy.mean', 'np.mean', (['time_list[5:]'], {}), '(time_list[5:])\n', (29342, 29357), True, 'import numpy as np\n'), ((29886, 29892), 'time.time', 'time', ([], {}), '()\n', (29890, 29892), False, 'from time import time\n'), ((30097, 30103), 'time.time', 'time', ([], {}), '()\n', (30101, 30103), False, 'from time import time\n'), ((3513, 3552), 'numpy.array', 'np.array', (['(random_numbers < self.epsilon)'], {}), '(random_numbers < self.epsilon)\n', (3521, 3552), True, 'import numpy as np\n'), ((3816, 3873), 'numpy.random.multinomial', 'np.random.multinomial', (['avail_action_len', 'avail_norm_to_np'], {}), '(avail_action_len, avail_norm_to_np)\n', (3837, 3873), True, 'import numpy as np\n'), ((6131, 6160), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""hyper_w1"""'], {}), "('hyper_w1')\n", (6148, 6160), True, 'import tensorflow as tf\n'), ((6184, 6272), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'hyper_w1_input', 'units': 'hypernet_embed', 'activation': 'tf.nn.relu'}), '(inputs=hyper_w1_input, units=hypernet_embed, activation=tf.\n nn.relu)\n', (6199, 6272), True, 'import tensorflow as tf\n'), ((6290, 6376), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'hw0', 'units': '(self.embed_dim * self.n_agents)', 'activation': 'None'}), '(inputs=hw0, units=self.embed_dim * self.n_agents,\n activation=None)\n', (6305, 6376), True, 'import tensorflow as tf\n'), ((6514, 6548), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""hyper_w_final"""'], {}), "('hyper_w_final')\n", (6531, 6548), True, 'import tensorflow as tf\n'), ((6574, 6666), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'hyper_w_final_input', 'units': 'hypernet_embed', 'activation': 'tf.nn.relu'}), '(inputs=hyper_w_final_input, units=hypernet_embed,\n activation=tf.nn.relu)\n', (6589, 6666), True, 'import tensorflow as tf\n'), ((6766, 6834), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'hw_f0', 'units': 'self.embed_dim', 'activation': 'None'}), '(inputs=hw_f0, units=self.embed_dim, activation=None)\n', (6781, 6834), True, 'import tensorflow as tf\n'), ((6973, 7002), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""hyper_b1"""'], {}), "('hyper_b1')\n", (6990, 7002), True, 'import tensorflow as tf\n'), ((7027, 7101), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'state_input', 'units': 'self.embed_dim', 'activation': 'None'}), '(inputs=state_input, units=self.embed_dim, activation=None)\n', (7042, 7101), True, 'import tensorflow as tf\n'), ((7211, 7244), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""val_for_bias"""'], {}), "('val_for_bias')\n", (7228, 7244), True, 'import tensorflow as tf\n'), ((7269, 7354), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'state_input', 'units': 'self.embed_dim', 'activation': 'tf.nn.relu'}), '(inputs=state_input, units=self.embed_dim, activation=tf.nn.relu\n )\n', (7284, 7354), True, 'import tensorflow as tf\n'), ((7373, 7427), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'val0', 'units': '(1)', 'activation': 'None'}), '(inputs=val0, units=1, activation=None)\n', (7388, 7427), True, 'import tensorflow as tf\n'), ((8958, 9011), 'tensorflow.reduce_max', 'tf.reduce_max', (['masked_q_values'], {'reduction_indices': '[2]'}), '(masked_q_values, reduction_indices=[2])\n', (8971, 9011), True, 'import tensorflow as tf\n'), ((10184, 10205), 'numpy.eye', 'np.eye', (['self.n_agents'], {}), '(self.n_agents)\n', (10190, 10205), True, 'import numpy as np\n'), ((10255, 10282), 'numpy.tile', 'np.tile', (['_ag_id', '(bs, 1, 1)'], {}), '(_ag_id, (bs, 1, 1))\n', (10262, 10282), True, 'import numpy as np\n'), ((11394, 11428), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""explore_agent"""'], {}), "('explore_agent')\n", (11411, 11428), True, 'import tensorflow as tf\n'), ((13690, 13730), 'tensorflow.range', 'tf.range', (['(0)', 'len_3d'], {'dtype': 'indices.dtype'}), '(0, len_3d, dtype=indices.dtype)\n', (13698, 13730), True, 'import tensorflow as tf\n'), ((15491, 15522), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""eval_agent"""'], {}), "('eval_agent')\n", (15508, 15522), True, 'import tensorflow as tf\n'), ((15907, 15940), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""target_agent"""'], {}), "('target_agent')\n", (15924, 15940), True, 'import tensorflow as tf\n'), ((16338, 16374), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['tar_agent_outs_tmp'], {}), '(tar_agent_outs_tmp)\n', (16354, 16374), True, 'import tensorflow as tf\n'), ((16606, 16643), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""soft_replacement"""'], {}), "('soft_replacement')\n", (16623, 16643), True, 'import tensorflow as tf\n'), ((18885, 18928), 'tensorflow.where', 'tf.where', (['indices', 'mask_val', 'mac_out_detach'], {}), '(indices, mask_val, mac_out_detach)\n', (18893, 18928), True, 'import tensorflow as tf\n'), ((19163, 19203), 'tensorflow.reduce_max', 'tf.reduce_max', (['target_mac_out'], {'axis': '[-1]'}), '(target_mac_out, axis=[-1])\n', (19176, 19203), True, 'import tensorflow as tf\n'), ((19749, 19780), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""eval_mixer"""'], {}), "('eval_mixer')\n", (19766, 19780), True, 'import tensorflow as tf\n'), ((19893, 19926), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""target_mixer"""'], {}), "('target_mixer')\n", (19910, 19926), True, 'import tensorflow as tf\n'), ((20060, 20087), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['q_tot_tmp'], {}), '(q_tot_tmp)\n', (20076, 20087), True, 'import tensorflow as tf\n'), ((20315, 20352), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""soft_replacement"""'], {}), "('soft_replacement')\n", (20332, 20352), True, 'import tensorflow as tf\n'), ((21629, 21654), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['targets'], {}), '(targets)\n', (21645, 21654), True, 'import tensorflow as tf\n'), ((21885, 21920), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(masked_td_error ** 2)'], {}), '(masked_td_error ** 2)\n', (21898, 21920), True, 'import tensorflow as tf\n'), ((21921, 21948), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['self.ph_mask'], {}), '(self.ph_mask)\n', (21934, 21948), True, 'import tensorflow as tf\n'), ((28248, 28281), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (28279, 28281), True, 'import tensorflow as tf\n'), ((30637, 30643), 'time.time', 'time', ([], {}), '()\n', (30641, 30643), False, 'from time import time\n'), ((30755, 30761), 'time.time', 'time', ([], {}), '()\n', (30759, 30761), False, 'from time import time\n'), ((32221, 32243), 'numpy.mean', 'np.mean', (['env_step_list'], {}), '(env_step_list)\n', (32228, 32243), True, 'import numpy as np\n'), ((32305, 32329), 'numpy.mean', 'np.mean', (['infer_time_list'], {}), '(infer_time_list)\n', (32312, 32329), True, 'import numpy as np\n'), ((32391, 32417), 'numpy.mean', 'np.mean', (['interaction_cycle'], {}), '(interaction_cycle)\n', (32398, 32417), True, 'import numpy as np\n'), ((9823, 9867), 'numpy.zeros_like', 'np.zeros_like', (["batch['actions_onehot'][:, t]"], {}), "(batch['actions_onehot'][:, t])\n", (9836, 9867), True, 'import numpy as np\n'), ((16692, 16707), 'tensorflow.assign', 'tf.assign', (['t', 'e'], {}), '(t, e)\n', (16701, 16707), True, 'import tensorflow as tf\n'), ((16836, 16851), 'tensorflow.assign', 'tf.assign', (['t', 'e'], {}), '(t, e)\n', (16845, 16851), True, 'import tensorflow as tf\n'), ((18823, 18850), 'tensorflow.identity', 'tf.identity', (['mac_out[:, 1:]'], {}), '(mac_out[:, 1:])\n', (18834, 18850), True, 'import tensorflow as tf\n'), ((18978, 19012), 'tensorflow.argmax', 'tf.argmax', (['mac_out_detach'], {'axis': '(-1)'}), '(mac_out_detach, axis=-1)\n', (18987, 19012), True, 'import tensorflow as tf\n'), ((20399, 20414), 'tensorflow.assign', 'tf.assign', (['t', 'e'], {}), '(t, e)\n', (20408, 20414), True, 'import tensorflow as tf\n'), ((29166, 29188), 'numpy.mean', 'np.mean', (['time_list[5:]'], {}), '(time_list[5:])\n', (29173, 29188), True, 'import numpy as np\n'), ((30043, 30049), 'time.time', 'time', ([], {}), '()\n', (30047, 30049), False, 'from time import time\n'), ((30206, 30212), 'time.time', 'time', ([], {}), '()\n', (30210, 30212), False, 'from time import time\n'), ((32133, 32139), 'time.time', 'time', ([], {}), '()\n', (32137, 32139), False, 'from time import time\n'), ((22220, 22277), 'tensorflow.clip_by_norm', 'tf.clip_by_norm', (['grad'], {'clip_norm': 'self.args.grad_norm_clip'}), '(grad, clip_norm=self.args.grad_norm_clip)\n', (22235, 22277), True, 'import tensorflow as tf\n'), ((30703, 30709), 'time.time', 'time', ([], {}), '()\n', (30707, 30709), False, 'from time import time\n'), ((29216, 29234), 'numpy.mean', 'np.mean', (['time_list'], {}), '(time_list)\n', (29223, 29234), True, 'import numpy as np\n')]
# Copyright 2016, FBPIC contributors # Authors: <NAME>, <NAME> # License: 3-Clause-BSD-LBNL """ This file is part of the Fourier-Bessel Particle-In-Cell code (FB-PIC) It contains a helper function that parses the data file atomic_data.txt """ import re, os import numpy as np from scipy.constants import e cached_ionization_energies = {} def get_ionization_energies( element ): """ Return an array of ionization energies (in Joules), with one array element per ionization state. If the same element was requested previously, the ionization energy is obtained from a cached dictionary (`cached_ionization_energies`) otherwise the energies are read from a data file. Parameters ---------- element: string The atomic symbol of the considered ionizable species (e.g. 'He', 'N' ; do not use 'Helium' or 'Nitrogen') Returns ------- An array with one array element per ionization state, containing the ionization energy in Joules, or None if the element was not found in the file. """ # Lookup in the cached dictionary if element in cached_ionization_energies.keys(): return( cached_ionization_energies[element] ) else: energies = read_ionization_energies(element) # Record energies in the cached dictionary cached_ionization_energies[element] = energies return( energies ) def read_ionization_energies( element ): """ Read the ionization energies from a data file Parameters ---------- element: string The atomic symbol of the considered ionizable species (e.g. 'He', 'N' ; do not use 'Helium' or 'Nitrogen') Returns ------- An array with one array element per ionization state, containing the ionization energy in Joules. """ # Open and read the file atomic_data.txt filename = os.path.join( os.path.dirname(__file__), 'atomic_data.txt' ) with open(filename) as f: text_data = f.read() # Parse the data using regular expressions (a.k.a. regex) # (see https://docs.python.org/2/library/re.html) # The regex command below parses lines of the type # '\n 10 | Ne IV | +3 | [97.1900]' # and only considers those for which the element (Ne in the above example) # matches the element which is passed as argument of this function # For each line that satisfies this requirement, it extracts a tuple with # - the atomic number (represented as (\d+)) # - the ionization level (represented as the second (\d+)) # - the ionization energy (represented as (\d+\.*\d*)) regex_command = \ '\n\s+(\d+)\s+\|\s+%s\s+\w+\s+\|\s+\+*(\d+)\s+\|\s+\(*\[*(\d+\.*\d*)' \ %element list_of_tuples = re.findall( regex_command, text_data ) # Return None if the requested element was not found if list_of_tuples == []: return(None) # Go through the list of tuples and fill the array of ionization energies. atomic_number = int( list_of_tuples[0][0] ) assert atomic_number > 0 energies = np.zeros( atomic_number ) for ion_level in range( atomic_number ): # Check that, when reading the file, # we obtained the correct ionization level assert ion_level == int( list_of_tuples[ion_level][1] ) # Get the ionization energy and convert in Joules using e energies[ ion_level ] = e * float( list_of_tuples[ion_level][2] ) return( energies )
[ "os.path.dirname", "re.findall", "numpy.zeros" ]
[((2774, 2810), 're.findall', 're.findall', (['regex_command', 'text_data'], {}), '(regex_command, text_data)\n', (2784, 2810), False, 'import re, os\n'), ((3091, 3114), 'numpy.zeros', 'np.zeros', (['atomic_number'], {}), '(atomic_number)\n', (3099, 3114), True, 'import numpy as np\n'), ((1889, 1914), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1904, 1914), False, 'import re, os\n')]
import numpy as np from sklearn import cluster from sklearn import metrics from sklearn.naive_bayes import GaussianNB from .Common import DWConfig, DWutils class DWImageClustering: def __init__(self, bands, bands_keys, invalid_mask, config: DWConfig): self.config = config self.data_as_columns = None self.clusters_labels = None self.clusters_params = None self.cluster_matrix = None self.water_cluster = None self.water_mask = None self.best_k = None self._product_name = None self.bands, self.bands_keys, self.invalid_mask = self.check_necessary_bands(bands, bands_keys, invalid_mask) def check_necessary_bands(self, bands, bands_keys, invalid_mask): """ Check if the bands_keys combination for the clustering algorithm are available in bands and if they all have the same shape :param invalid_mask: array mask with the invalid pixels :param bands: image bands available :param bands_keys: bands combination :return: bands and bands_keys """ if type(bands) is not dict: raise OSError('Bands not in dictionary format') # if len(bands) != len(bands_keys): # raise OSError('Bands and bands_keys have different sizes') # get the first band as reference of size ref_band = list(bands.keys())[0] ref_shape = bands[ref_band].shape # check the invalid_mask if invalid_mask is not None and invalid_mask.shape != ref_shape: raise OSError('Invalid mask and {} with different shape in clustering core'.format(ref_band)) elif invalid_mask is None: invalid_mask = np.zeros(ref_shape, dtype=bool) # check if the MNDWI index is necessary and if it exists if (('mndwi' in DWutils.listify(bands_keys)) or (self.config.clustering_method == 'maxmndwi')) and \ ('mndwi' not in bands.keys()): mndwi, mndwi_mask = DWutils.calc_normalized_difference(bands['Green'], bands['Mir2'], invalid_mask) invalid_mask |= mndwi_mask bands.update({'mndwi': mndwi}) # check if the NDWI index exist if 'ndwi' not in bands.keys(): ndwi, ndwi_mask = DWutils.calc_normalized_difference(bands['Green'], bands['Nir'], invalid_mask) invalid_mask |= ndwi_mask bands.update({'ndwi': ndwi}) # todo: check the band for Principal Component Analysis # check if the list contains the required bands for band in DWutils.listify(bands_keys): if band == 'otsu' or band == 'canny': continue if band not in bands.keys(): raise OSError('Band {}, not available in the dictionary'.format(band)) if type(bands[band]) is not np.ndarray: raise OSError('Band {} is not a numpy array'.format(band)) if ref_shape != bands[band].shape: raise OSError('Bands {} and {} with different size in clustering core'.format(band, ref_band)) return bands, bands_keys, invalid_mask def bands_to_columns(self): """ Convert self.bands to a column type matrix where each band is a column It follows the order of the keys ordered :return: column type matrix """ # load all the bands in the dictionary as numpy arrays columns # the bands will appear in sorted order # valid_data_list = [] data = None for key in sorted(self.bands.keys()): band_array = self.bands[key] band_as_column = band_array[~self.invalid_mask].reshape(-1, 1) if (key == 'Mir') or (key == 'Mir2') or (key == 'Nir') or (key == 'Nir2') or (key == 'Green'): band_as_column = band_as_column * 4 band_as_column[band_as_column > 4] = 4 data = band_as_column if data is None else np.concatenate([data, band_as_column], axis=1) # valid_data_list.append(band_array[~self.invalid_mask]) # prepare the multidimensional data array (bands as columns) # data = np.c_[valid_data_list].transpose() return data ############################################################################ # Clustering related functions # -------------------------------------------------------------------------# def apply_cluster(self, data): """ Apply the cluster algorithm to the data. Number of cluster is in self.best_k :param data: data to be clustered :return: Vector with the labels """ # before calling the clustering function, normalize the data using min_max_scaler # scaled_data = preprocessing.minmax_scale(data) if self.config.clustering_method == 'kmeans': cluster_model = cluster.KMeans(n_clusters=self.best_k, init='k-means++') else: cluster_model = cluster.AgglomerativeClustering(n_clusters=self.best_k, linkage=self.config.linkage) cluster_model.fit(data) return cluster_model.labels_ def find_best_k(self, data): """ Find the best number of clusters according to an metrics. :param data: data to be tested :return: number of clusters """ # # split data for a smaller set (for performance purposes) # train_data, test_data = getTrainTestDataset(data, train_size, min_train_size=1000) min_k = self.config.min_clusters max_k = self.config.max_clusters if min_k == max_k: print('Same number for minimum and maximum clusters: k = {}'.format(min_k)) self.best_k = min_k return self.best_k if self.config.score_index == 'silhouette': print('Selection of best number of clusters using Silhouete Index:') else: print('Selection of best number of clusters using Calinski-Harabasz Index:') computed_metrics = [] for num_k in range(min_k, max_k + 1): # cluster_model = cluster.KMeans(n_clusters=num_k, init='k-means++') cluster_model = cluster.AgglomerativeClustering(n_clusters=num_k, linkage=self.config.linkage) labels = cluster_model.fit_predict(data) if self.config.score_index == 'silhouette': computed_metrics.append(metrics.silhouette_score(data, labels)) print('k={} :Silhouete index={}'.format(num_k, computed_metrics[num_k - min_k])) else: computed_metrics.append(metrics.calinski_harabasz_score(data, labels)) print('k={} :Calinski_harabaz index={}'.format(num_k, computed_metrics[num_k - min_k])) # the best solution is the one with higher index self.best_k = computed_metrics.index(max(computed_metrics)) + min_k return self.best_k def calc_clusters_params(self, data, clusters_labels): """ Calculate parameters for each encountered cluster. Mean, Variance, Std-dev :param data: Clustered data :param clusters_labels: Labels for the data :return: List with cluster statistics """ clusters_params = [] for label_i in range(self.best_k): # first slice the values in the indexed cluster cluster_i = data[clusters_labels == label_i, :] cluster_param = {'clusterid': label_i} cluster_param.update({'mean': np.mean(cluster_i, 0)}) cluster_param.update({'variance': np.var(cluster_i, 0)}) cluster_param.update({'stdev': np.std(cluster_i, 0)}) cluster_param.update({'diffb2b1': cluster_param['mean'][1] - cluster_param['mean'][0]}) cluster_param.update({'pixels': cluster_i.shape[0]}) clusters_params.append(cluster_param) return clusters_params def identify_water_cluster(self): """ Finds the water cluster within all the clusters. It can be done using MNDWI, MBWI or Mir2 bands :return: water cluster object """ if self.config.detect_water_cluster == 'maxmndwi': if 'mndwi' not in self.bands.keys(): raise OSError('MNDWI band necessary for detecting water with maxmndwi option') water_cluster = self.detect_cluster('value', 'max', 'mndwi') elif self.config.detect_water_cluster == 'maxmbwi': if 'mbwi' not in self.bands.keys(): raise OSError('MBWI band necessary for detecting water with maxmbwi option') water_cluster = self.detect_cluster('value', 'max', 'mbwi') elif self.config.detect_water_cluster == 'minmir2': if 'mndwi' not in self.bands.keys(): raise OSError('Mir2 band necessary for detecting water with minmir2 option') water_cluster = self.detect_cluster('value', 'min', 'Mir2') elif self.config.detect_water_cluster == 'maxndwi': if 'ndwi' not in self.bands.keys(): raise OSError('NDWI band necessary for detecting water with minmir2 option') water_cluster = self.detect_cluster('value', 'max', 'ndwi') else: raise OSError('Method {} for detecting water cluster does not exist'. format(self.config.detect_water_cluster)) return water_cluster def detect_cluster(self, param, logic, band1, band2=None): """ Detects a cluster according to a specific metrics :param param: Which parameter to search (mean, std-dev, variance, ...) :param logic: Max or Min :param band1: The band related to the parameter :param band2: :return: Cluster object that satisfies the logic """ # get the bands available in the columns available_bands = sorted(self.bands.keys()) param_list = [] if band1: idx_band1 = available_bands.index(band1) if band2: idx_band2 = available_bands.index(band2) # todo: fix the fixed values for clt in self.clusters_params: if param == 'diff': if not idx_band2: raise OSError('Two bands needed for diff method') param_list.append(clt['mean'][idx_band1] - clt['mean'][idx_band2]) elif param == 'value': if clt['pixels'] > 5: # and (clt['mean'][available_bands.index('Mir2')] < 0.25*4): param_list.append(clt['mean'][idx_band1]) else: param_list.append(-1) if logic == 'max': idx_detected = param_list.index(max(param_list)) else: idx_detected = param_list.index(min(param_list)) return self.clusters_params[idx_detected] ############################################################################ # Classification functions # -------------------------------------------------------------------------# def supervised_classification(self, data, train_data, clusters_labels): """ Applies a machine learning supervised classification :param data: new data to be classified :param train_data: reference data :param clusters_labels: labels for the reference data :return: labels for the new data """ return self.apply_naive_bayes(data, clusters_labels, train_data) @staticmethod def apply_naive_bayes(data, clusters_labels, clusters_data): """ Apply Naive Bayes classifier to classify data :param data: new data to be classified :param clusters_labels: labels for the reference data :param clusters_data: reference data :return: labels for the new data """ # train a NB classifier with the data and labels provided model = GaussianNB() print('Applying clusters based naive bayes classifier') # print('Cross_val_score:{}'.format(cross_val_score(model, clusters_data, clusters_labels))) model.fit(clusters_data, clusters_labels) # return the new predicted labels for the whole dataset return model.predict(data) def get_cluster_param(self, clusters_params, k, param, band): index = sorted(self.bands.keys()).index(band) value = clusters_params[k][param][index] return value def create_matrice_cluster(self, indices_array): """ Recreates the matrix with the original shape with the cluster labels for each pixel :param indices_array: position of the clustered pixels in the matrix :return: clustered image (0-no data, 1-water, 2, 3, ... - other) """ # todo: treat no_data value of -9999 # create an empty matrix matrice_cluster = np.zeros_like(list(self.bands.values())[0]) # apply water pixels to value 1 matrice_cluster[indices_array[0][self.clusters_labels == self.water_cluster['clusterid']], indices_array[1][self.clusters_labels == self.water_cluster['clusterid']]] = 1 print('Assgnin 1 to cluster_id {}'.format(self.water_cluster['clusterid'])) # loop through the remaining labels and apply value >= 3 new_label = 2 for label_i in range(self.best_k): if label_i != self.water_cluster['clusterid']: # if self.verify_cluster(self.clusters_params, label_i) == 'water': # matrice_cluster[indices_array[0][self.clusters_labels == label_i], # indices_array[1][self.clusters_labels == label_i]] = 1 # print('Cluster {} = water'.format(label_i)) # else: # matrice_cluster[indices_array[0][self.clusters_labels == label_i], # indices_array[1][self.clusters_labels == label_i]] = new_label # print('Cluster {} receiving label {}'.format(label_i, new_label)) # matrice_cluster[indices_array[0][self.clusters_labels == label_i], indices_array[1][self.clusters_labels == label_i]] = new_label new_label += 1 else: print('Skipping cluster_id {}'.format(label_i)) return matrice_cluster ############################################################################ # Other utility functions # -------------------------------------------------------------------------# def split_data_by_bands(self, data, selected_keys): """ Gets data in column format (each band is a column) and returns only the desired bands :param data: data in column format :param selected_keys: bands keys to be extracted :return: data in column format only with the selected bands """ bands_index = [] bands_keys = list(sorted(self.bands.keys())) for key in selected_keys: bands_index.append(bands_keys.index(key)) return data[:, bands_index] def apply_canny_treshold(self): from skimage import feature, morphology from skimage.filters import threshold_otsu canny_band = self.bands_keys[1] condition = True correction = 0 while condition: edges = feature.canny(self.bands[canny_band], sigma=2, use_quantiles=True, low_threshold=0.98 - correction, high_threshold=(0.999 - correction), mask=~self.invalid_mask) # mask= (im != 0)) condition = (np.count_nonzero(edges) < 10000) print('Correction: ', correction) print("Canny edges pixels: ", np.count_nonzero(edges)) correction = correction + 0.004 if correction > 1: raise Exception dilated_edges = morphology.binary_dilation(edges, selem=morphology.square(5)) img = self.bands[canny_band] threshold = threshold_otsu(img[dilated_edges & (img != -9999)]) print('Canny threshold on {} band = {}'.format(canny_band, threshold)) # create an empty matrix matrice_cluster = np.zeros_like(list(self.bands.values())[0]) matrice_cluster[self.bands[canny_band] >= threshold] = 1 return matrice_cluster def apply_otsu_treshold(self): from skimage.filters import threshold_otsu self.data_as_columns = self.bands_to_columns() # train_data_as_columns = self.separate_high_low_mndwi() otsu_band = self.bands_keys[1] otsu_band_index = self.index_of_key(otsu_band) # otsu_data = train_data_as_columns[:, otsu_band_index] otsu_data = self.data_as_columns[:, otsu_band_index] threshold = threshold_otsu(otsu_data) print('OTSU threshold on {} band = {}'.format(otsu_band, threshold)) # create an empty matrix matrice_cluster = np.zeros_like(list(self.bands.values())[0]) matrice_cluster[self.bands[otsu_band] >= threshold] = 1 return matrice_cluster ############################################################################ # MAIN run_detect_water function # -------------------------------------------------------------------------# def run_detect_water(self, config=None): """ Runs the detect_water function :param config: Options dictionary for the processing :return: clustered matrix where 1= water """ # if passed options, override the existing options self.config = config if type(config) == DWConfig else self.config if self.bands_keys[0] == 'otsu': self.cluster_matrix = self.apply_otsu_treshold() elif self.bands_keys[0] == 'canny': self.cluster_matrix = self.apply_canny_treshold() elif self.config.average_results: self.cluster_matrix = None # loop through the bands combinations for band_combination in self.config.clustering_bands: self.bands_keys = band_combination if self.cluster_matrix is None: self.cluster_matrix = np.where(self.apply_clustering() == 1, 1, 0) else: new_cluster_result = np.where(self.apply_clustering() == 1, 1, 0) self.cluster_matrix += new_cluster_result self.cluster_matrix = np.where(self.cluster_matrix >= self.config.min_positive_pixels, 1, 0) else: self.cluster_matrix = self.apply_clustering() # self.water_mask = self.cluster_matrix == 1 self.water_mask = np.where(self.cluster_matrix == 1, 1, np.where(self.invalid_mask == 1, 255, 0)) return self.cluster_matrix def index_of_key(self, key): keys = sorted(self.bands.keys()) return keys.index(key) def apply_clustering(self): # Transform the rasters in a matrix where each band is a column self.data_as_columns = self.bands_to_columns() # two line vectors indicating the indexes (line, column) of valid pixels ind_data = np.where(~self.invalid_mask) # if algorithm is not kmeans, split data for a smaller set (for performance purposes) if self.config.clustering_method == 'kmeans': train_data_as_columns = self.data_as_columns else: # original train data keeps all the bands # train_data_as_columns = self.separate_high_low_mndwi() train_data_as_columns, _ = DWutils.get_train_test_data(self.data_as_columns, self.config.train_size, self.config.min_train_size, self.config.max_train_size) # create data bunch only with the bands used for clustering split_train_data_as_columns = self.split_data_by_bands(train_data_as_columns, self.bands_keys) split_data_as_columns = self.split_data_by_bands(self.data_as_columns, self.bands_keys) # find the best clustering solution (k = number of clusters) self.best_k = self.find_best_k(split_train_data_as_columns) # apply the clusterization algorithm and return labels and train dataset train_clusters_labels = self.apply_cluster(split_train_data_as_columns) # calc statistics for each cluster self.clusters_params = self.calc_clusters_params(train_data_as_columns, train_clusters_labels) # detect the water cluster self.water_cluster = self.identify_water_cluster() # if we are dealing with aglomerative cluster or other diff from kmeans, we have only a sample of labels # we need to recreate labels for all the points using supervised classification if self.config.clustering_method != 'kmeans': self.clusters_labels = self.supervised_classification(split_data_as_columns, split_train_data_as_columns, train_clusters_labels) else: self.clusters_labels = train_clusters_labels # after obtaining the final labels, clip bands with superior limit for band, value in zip(self.config.clip_band, self.config.clip_sup_value): if value is not None: self.clusters_labels[(self.clusters_labels == self.water_cluster['clusterid']) & (self.bands[band][~self.invalid_mask] > value)] = -1 # after obtaining the final labels, clip bands with inferior limit for band, value in zip(self.config.clip_band, self.config.clip_inf_value): if value is not None: self.clusters_labels[(self.clusters_labels == self.water_cluster['clusterid']) & (self.bands[band][~self.invalid_mask] < value)] = -1 # create an cluster array based on the cluster result (water will be value 1) return self.create_matrice_cluster(ind_data)
[ "sklearn.cluster.KMeans", "sklearn.metrics.calinski_harabasz_score", "sklearn.cluster.AgglomerativeClustering", "numpy.mean", "skimage.filters.threshold_otsu", "numpy.where", "skimage.morphology.square", "numpy.count_nonzero", "numpy.zeros", "skimage.feature.canny", "numpy.concatenate", "numpy...
[((11939, 11951), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (11949, 11951), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((16089, 16140), 'skimage.filters.threshold_otsu', 'threshold_otsu', (['img[dilated_edges & (img != -9999)]'], {}), '(img[dilated_edges & (img != -9999)])\n', (16103, 16140), False, 'from skimage.filters import threshold_otsu\n'), ((16874, 16899), 'skimage.filters.threshold_otsu', 'threshold_otsu', (['otsu_data'], {}), '(otsu_data)\n', (16888, 16899), False, 'from skimage.filters import threshold_otsu\n'), ((19239, 19267), 'numpy.where', 'np.where', (['(~self.invalid_mask)'], {}), '(~self.invalid_mask)\n', (19247, 19267), True, 'import numpy as np\n'), ((4894, 4950), 'sklearn.cluster.KMeans', 'cluster.KMeans', ([], {'n_clusters': 'self.best_k', 'init': '"""k-means++"""'}), "(n_clusters=self.best_k, init='k-means++')\n", (4908, 4950), False, 'from sklearn import cluster\n'), ((4993, 5082), 'sklearn.cluster.AgglomerativeClustering', 'cluster.AgglomerativeClustering', ([], {'n_clusters': 'self.best_k', 'linkage': 'self.config.linkage'}), '(n_clusters=self.best_k, linkage=self.config\n .linkage)\n', (5024, 5082), False, 'from sklearn import cluster\n'), ((6194, 6272), 'sklearn.cluster.AgglomerativeClustering', 'cluster.AgglomerativeClustering', ([], {'n_clusters': 'num_k', 'linkage': 'self.config.linkage'}), '(n_clusters=num_k, linkage=self.config.linkage)\n', (6225, 6272), False, 'from sklearn import cluster\n'), ((15439, 15606), 'skimage.feature.canny', 'feature.canny', (['self.bands[canny_band]'], {'sigma': '(2)', 'use_quantiles': '(True)', 'low_threshold': '(0.98 - correction)', 'high_threshold': '(0.999 - correction)', 'mask': '(~self.invalid_mask)'}), '(self.bands[canny_band], sigma=2, use_quantiles=True,\n low_threshold=0.98 - correction, high_threshold=0.999 - correction,\n mask=~self.invalid_mask)\n', (15452, 15606), False, 'from skimage import feature, morphology\n'), ((18794, 18834), 'numpy.where', 'np.where', (['(self.invalid_mask == 1)', '(255)', '(0)'], {}), '(self.invalid_mask == 1, 255, 0)\n', (18802, 18834), True, 'import numpy as np\n'), ((1727, 1758), 'numpy.zeros', 'np.zeros', (['ref_shape'], {'dtype': 'bool'}), '(ref_shape, dtype=bool)\n', (1735, 1758), True, 'import numpy as np\n'), ((3980, 4026), 'numpy.concatenate', 'np.concatenate', (['[data, band_as_column]'], {'axis': '(1)'}), '([data, band_as_column], axis=1)\n', (3994, 4026), True, 'import numpy as np\n'), ((15691, 15714), 'numpy.count_nonzero', 'np.count_nonzero', (['edges'], {}), '(edges)\n', (15707, 15714), True, 'import numpy as np\n'), ((15812, 15835), 'numpy.count_nonzero', 'np.count_nonzero', (['edges'], {}), '(edges)\n', (15828, 15835), True, 'import numpy as np\n'), ((16009, 16029), 'skimage.morphology.square', 'morphology.square', (['(5)'], {}), '(5)\n', (16026, 16029), False, 'from skimage import feature, morphology\n'), ((6424, 6462), 'sklearn.metrics.silhouette_score', 'metrics.silhouette_score', (['data', 'labels'], {}), '(data, labels)\n', (6448, 6462), False, 'from sklearn import metrics\n'), ((6620, 6665), 'sklearn.metrics.calinski_harabasz_score', 'metrics.calinski_harabasz_score', (['data', 'labels'], {}), '(data, labels)\n', (6651, 6665), False, 'from sklearn import metrics\n'), ((7528, 7549), 'numpy.mean', 'np.mean', (['cluster_i', '(0)'], {}), '(cluster_i, 0)\n', (7535, 7549), True, 'import numpy as np\n'), ((7598, 7618), 'numpy.var', 'np.var', (['cluster_i', '(0)'], {}), '(cluster_i, 0)\n', (7604, 7618), True, 'import numpy as np\n'), ((7664, 7684), 'numpy.std', 'np.std', (['cluster_i', '(0)'], {}), '(cluster_i, 0)\n', (7670, 7684), True, 'import numpy as np\n'), ((18532, 18602), 'numpy.where', 'np.where', (['(self.cluster_matrix >= self.config.min_positive_pixels)', '(1)', '(0)'], {}), '(self.cluster_matrix >= self.config.min_positive_pixels, 1, 0)\n', (18540, 18602), True, 'import numpy as np\n')]
"""@file audio_feat_processor.py contains the AudioFeatProcessor class""" import os import subprocess import StringIO import scipy.io.wavfile as wav import numpy as np import processor import gzip from nabu.processing.feature_computers import feature_computer_factory class AudioFeatProcessor(processor.Processor): """a processor for audio files, this will compute features""" def __init__(self, conf, segment_lengths): """AudioFeatProcessor constructor Args: conf: AudioFeatProcessor configuration as a dict of strings segment_lengths: A list containing the desired lengths of segments. Possibly multiple segment lengths""" # create the feature computer self.comp = feature_computer_factory.factory(conf['feature'])(conf) # set the length of the segments. Possibly multiple segment lengths self.segment_lengths = segment_lengths # initialize the metadata self.dim = self.comp.get_dim() self.max_length = np.zeros(len(self.segment_lengths)) # self.sequence_length_histogram = np.zeros(0, dtype=np.int32) self.nontime_dims = [self.dim] # set the type of mean and variance normalisation self.mvn_type = conf['mvn_type'] if conf['mvn_type'] == 'global': self.obs_cnt = 0 self.glob_mean = np.zeros([1, self.dim]) self.glob_std = np.zeros([1, self.dim]) elif conf['mvn_type'] in ['local', 'none', 'None', 'from_files']: pass else: raise Exception('Unknown way to apply mvn: %s' % conf['mvn_type']) super(AudioFeatProcessor, self).__init__(conf) def __call__(self, dataline): """process the data in dataline Args: dataline: either a path to a wav file or a command to read and pipe an audio file Returns: segmented_data: The segmented features as a list of numpy arrays per segment length utt_info: some info on the utterance""" utt_info = dict() # read the wav file rate, utt = _read_wav(dataline) # compute the features features = self.comp(utt, rate) # mean and variance normalize the features if self.mvn_type == 'global': features = (features-self.glob_mean)/(self.glob_std+1e-12) elif self.mvn_type == 'local': features = (features-np.mean(features, 0))/(np.std(features, 0)+1e-12) # split the data for all desired segment lengths segmented_data = self.segment_data(features) # update the metadata for i, seg_length in enumerate(self.segment_lengths): self.max_length[i] = max(self.max_length[i], np.shape(segmented_data[seg_length][0])[0]) # seq_length = np.shape(segmented_data[seg_length][0])[0] # if seq_length >= np.shape(self.sequence_length_histogram[i])[0]: # self.sequence_length_histogram[i] = np.concatenate( # [self.sequence_length_histogram[i], np.zeros( # seq_length-np.shape(self.sequence_length_histogram[i])[0]+1, # dtype=np.int32)] # ) # self.sequence_length_histogram[i][seq_length] += len(segmented_data[seg_length]) return segmented_data, utt_info def pre_loop(self, dataconf): """before looping over all the data to process and store it, calculate the global mean and variance to normalize the features later on Args: dataconf: config file on the part of the database being processed""" if self.mvn_type == 'global': loop_types = ['mean', 'std'] # calculate the mean and variance for loop_type in loop_types: # if the directory of mean and variance are pointing to the store directory, # this means that the mean and variance should be calculated here. if dataconf['meanandvar_dir'] == dataconf['store_dir']: for datafile in dataconf['datafiles'].split(' '): if datafile[-3:] == '.gz': open_fn = gzip.open else: open_fn = open # loop over the lines in the datafile for line in open_fn(datafile): # split the name and the data line splitline = line.strip().split(' ') utt_name = splitline[0] dataline = ' '.join(splitline[1:]) # process the dataline if loop_type == 'mean': self.acc_mean(dataline) elif loop_type == 'std': self.acc_std(dataline) if loop_type == 'mean': self.glob_mean = self.glob_mean/float(self.obs_cnt) with open(os.path.join(dataconf['meanandvar_dir'], 'glob_mean.npy'), 'w') as fid: np.save(fid, self.glob_mean) elif loop_type == 'std': self.glob_std = np.sqrt(self.glob_std/float(self.obs_cnt)) with open(os.path.join(dataconf['meanandvar_dir'], 'glob_std.npy'), 'w') as fid: np.save(fid, self.glob_std) else: # get mean and variance calculated on training set if loop_type == 'mean': with open(os.path.join(dataconf['meanandvar_dir'], 'glob_mean.npy')) as fid: self.glob_mean = np.load(fid) elif loop_type == 'std': with open(os.path.join(dataconf['meanandvar_dir'], 'glob_std.npy')) as fid: self.glob_std = np.load(fid) def acc_mean(self, dataline): """accumulate the features to get the mean Args: dataline: either a path to a wav file or a command to read and pipe an audio file""" # read the wav file rate, utt = _read_wav(dataline) # compute the features features = self.comp(utt, rate) # accumulate the features acc_feat = np.sum(features, 0) # update the mean and observation count self.glob_mean += acc_feat self.obs_cnt += features.shape[0] def acc_std(self, dataline): """accumulate the features to get the standard deviation Args: dataline: either a path to a wav file or a command to read and pipe an audio file""" # read the wav file rate, utt = _read_wav(dataline) # compute the features features = self.comp(utt, rate) # accumulate the features acc_feat = np.sum(np.square(features-self.glob_mean), 0) # update the standard deviation self.glob_std += acc_feat def write_metadata(self, datadir): """write the processor metadata to disk Args: datadir: the directory where the metadata should be written""" if self.mvn_type == 'global': with open(os.path.join(datadir, 'glob_mean.npy'), 'w') as fid: np.save(fid, self.glob_mean) with open(os.path.join(datadir, 'glob_std.npy'), 'w') as fid: np.save(fid, self.glob_std) for i, seg_length in enumerate(self.segment_lengths): seg_dir = os.path.join(datadir, seg_length) # with open(os.path.join(seg_dir, 'sequence_length_histogram.npy'), 'w') as fid: # np.save(fid, self.sequence_length_histogram[i]) with open(os.path.join(seg_dir, 'max_length'), 'w') as fid: fid.write(str(self.max_length[i])) with open(os.path.join(seg_dir, 'dim'), 'w') as fid: fid.write(str(self.dim)) with open(os.path.join(seg_dir, 'nontime_dims'), 'w') as fid: fid.write(str(self.nontime_dims)[1:-1]) def _read_wav(wavfile): """ read a wav file Args: wavfile: either a path to a wav file or a command to read and pipe an audio file Returns: - the sampling rate - the utterance as a numpy array """ if os.path.exists(wavfile): # its a file (rate, utterance) = wav.read(wavfile) elif wavfile[-1] == '|': # its a command # read the audio file pid = subprocess.Popen(wavfile + ' tee', shell=True, stdout=subprocess.PIPE) output, _ = pid.communicate() output_buffer = StringIO.StringIO(output) (rate, utterance) = wav.read(output_buffer) else: # its a segment of an utterance split = wavfile.split(' ') begin = float(split[-2]) end = float(split[-1]) unsegmented = ' '.join(split[:-2]) rate, full_utterance = _read_wav(unsegmented) utterance = full_utterance[int(begin*rate):int(end*rate)] return rate, utterance
[ "StringIO.StringIO", "os.path.exists", "numpy.mean", "nabu.processing.feature_computers.feature_computer_factory.factory", "subprocess.Popen", "os.path.join", "numpy.square", "numpy.sum", "numpy.zeros", "scipy.io.wavfile.read", "numpy.std", "numpy.shape", "numpy.load", "numpy.save" ]
[((6983, 7006), 'os.path.exists', 'os.path.exists', (['wavfile'], {}), '(wavfile)\n', (6997, 7006), False, 'import os\n'), ((5240, 5259), 'numpy.sum', 'np.sum', (['features', '(0)'], {}), '(features, 0)\n', (5246, 5259), True, 'import numpy as np\n'), ((7045, 7062), 'scipy.io.wavfile.read', 'wav.read', (['wavfile'], {}), '(wavfile)\n', (7053, 7062), True, 'import scipy.io.wavfile as wav\n'), ((694, 743), 'nabu.processing.feature_computers.feature_computer_factory.factory', 'feature_computer_factory.factory', (["conf['feature']"], {}), "(conf['feature'])\n", (726, 743), False, 'from nabu.processing.feature_computers import feature_computer_factory\n'), ((1246, 1269), 'numpy.zeros', 'np.zeros', (['[1, self.dim]'], {}), '([1, self.dim])\n', (1254, 1269), True, 'import numpy as np\n'), ((1289, 1312), 'numpy.zeros', 'np.zeros', (['[1, self.dim]'], {}), '([1, self.dim])\n', (1297, 1312), True, 'import numpy as np\n'), ((5733, 5769), 'numpy.square', 'np.square', (['(features - self.glob_mean)'], {}), '(features - self.glob_mean)\n', (5742, 5769), True, 'import numpy as np\n'), ((6296, 6329), 'os.path.join', 'os.path.join', (['datadir', 'seg_length'], {}), '(datadir, seg_length)\n', (6308, 6329), False, 'import os\n'), ((7140, 7210), 'subprocess.Popen', 'subprocess.Popen', (["(wavfile + ' tee')"], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), "(wavfile + ' tee', shell=True, stdout=subprocess.PIPE)\n", (7156, 7210), False, 'import subprocess\n'), ((7261, 7286), 'StringIO.StringIO', 'StringIO.StringIO', (['output'], {}), '(output)\n', (7278, 7286), False, 'import StringIO\n'), ((7309, 7332), 'scipy.io.wavfile.read', 'wav.read', (['output_buffer'], {}), '(output_buffer)\n', (7317, 7332), True, 'import scipy.io.wavfile as wav\n'), ((6098, 6126), 'numpy.save', 'np.save', (['fid', 'self.glob_mean'], {}), '(fid, self.glob_mean)\n', (6105, 6126), True, 'import numpy as np\n'), ((6196, 6223), 'numpy.save', 'np.save', (['fid', 'self.glob_std'], {}), '(fid, self.glob_std)\n', (6203, 6223), True, 'import numpy as np\n'), ((2441, 2480), 'numpy.shape', 'np.shape', (['segmented_data[seg_length][0]'], {}), '(segmented_data[seg_length][0])\n', (2449, 2480), True, 'import numpy as np\n'), ((6041, 6079), 'os.path.join', 'os.path.join', (['datadir', '"""glob_mean.npy"""'], {}), "(datadir, 'glob_mean.npy')\n", (6053, 6079), False, 'import os\n'), ((6140, 6177), 'os.path.join', 'os.path.join', (['datadir', '"""glob_std.npy"""'], {}), "(datadir, 'glob_std.npy')\n", (6152, 6177), False, 'import os\n'), ((6480, 6515), 'os.path.join', 'os.path.join', (['seg_dir', '"""max_length"""'], {}), "(seg_dir, 'max_length')\n", (6492, 6515), False, 'import os\n'), ((6582, 6610), 'os.path.join', 'os.path.join', (['seg_dir', '"""dim"""'], {}), "(seg_dir, 'dim')\n", (6594, 6610), False, 'import os\n'), ((6667, 6704), 'os.path.join', 'os.path.join', (['seg_dir', '"""nontime_dims"""'], {}), "(seg_dir, 'nontime_dims')\n", (6679, 6704), False, 'import os\n'), ((2160, 2180), 'numpy.mean', 'np.mean', (['features', '(0)'], {}), '(features, 0)\n', (2167, 2180), True, 'import numpy as np\n'), ((2183, 2202), 'numpy.std', 'np.std', (['features', '(0)'], {}), '(features, 0)\n', (2189, 2202), True, 'import numpy as np\n'), ((4289, 4317), 'numpy.save', 'np.save', (['fid', 'self.glob_mean'], {}), '(fid, self.glob_mean)\n', (4296, 4317), True, 'import numpy as np\n'), ((4737, 4749), 'numpy.load', 'np.load', (['fid'], {}), '(fid)\n', (4744, 4749), True, 'import numpy as np\n'), ((4210, 4267), 'os.path.join', 'os.path.join', (["dataconf['meanandvar_dir']", '"""glob_mean.npy"""'], {}), "(dataconf['meanandvar_dir'], 'glob_mean.npy')\n", (4222, 4267), False, 'import os\n'), ((4507, 4534), 'numpy.save', 'np.save', (['fid', 'self.glob_std'], {}), '(fid, self.glob_std)\n', (4514, 4534), True, 'import numpy as np\n'), ((4646, 4703), 'os.path.join', 'os.path.join', (["dataconf['meanandvar_dir']", '"""glob_mean.npy"""'], {}), "(dataconf['meanandvar_dir'], 'glob_mean.npy')\n", (4658, 4703), False, 'import os\n'), ((4885, 4897), 'numpy.load', 'np.load', (['fid'], {}), '(fid)\n', (4892, 4897), True, 'import numpy as np\n'), ((4429, 4485), 'os.path.join', 'os.path.join', (["dataconf['meanandvar_dir']", '"""glob_std.npy"""'], {}), "(dataconf['meanandvar_dir'], 'glob_std.npy')\n", (4441, 4485), False, 'import os\n'), ((4796, 4852), 'os.path.join', 'os.path.join', (["dataconf['meanandvar_dir']", '"""glob_std.npy"""'], {}), "(dataconf['meanandvar_dir'], 'glob_std.npy')\n", (4808, 4852), False, 'import os\n')]
#importing libraries import numpy import skimage import skimage.io import skimage.color from matplotlib import pyplot, pyplot as plt from pathlib import Path import numpy as np #declaring global array index_0_255_array = np.array([x for x in range(256)]) #generic function to plot histograms of any number of images given #parameter to call should be : name<string> = image <ndarray> pairs def plot_images(**kwargs): #generic number of arguments list_of_names = [x for x in kwargs.keys()] #now we have keys number_of_images = len(kwargs) fig = plt.figure(figsize=(25, 25)) # create instance of figure #figsize to make plots smaller or larger, it is large hor = 2 #2 rows, first has horizontal stack of images, second has horizontal stack of histograms ver = number_of_images #columns as number of images passed to function #first row has plots of images for x in range( number_of_images): fig.add_subplot(hor, ver, (x+1)) #indexing of subplots starts at 1 pyplot.imshow(kwargs[list_of_names[x]], cmap='gray', vmin=0, vmax=255, aspect="auto") pyplot.title(list_of_names[x] , fontsize = 20) for x in range(number_of_images): fig.add_subplot(hor, ver, (x + 1 + number_of_images )) pyplot.plot(index_0_255_array, histogram(kwargs[list_of_names[x]]) ) pyplot.xlabel('intensities') plt.show() #same as above function, just saving plots to file instead of displying #could have implemented signle function via a flag, but its called much frequently, so writing sepearte is good def save_plot_images(path, **kwargs): # generic number of arguments list_of_names = [x for x in kwargs.keys()] # now we have keys number_of_images = len(kwargs) fig = plt.figure(figsize=(25, 25)) # create instance of figure # figsize to make plots smaller or larger, it is large hor = 2 # 2 rows, first has horizontal stack of images, second has horizontal stack of histograms ver = number_of_images # columns as number of images passed to function # first row has plots of images for x in range(number_of_images): fig.add_subplot(hor, ver, (x + 1)) # indexing of subplots starts at 1 pyplot.imshow(kwargs[list_of_names[x]], cmap='gray', vmin=0, vmax=255, aspect="auto") pyplot.title(list_of_names[x] , fontsize = 20) for x in range(number_of_images): fig.add_subplot(hor, ver, (x + 1 + number_of_images)) pyplot.plot(index_0_255_array, histogram(kwargs[list_of_names[x]])) pyplot.xlabel('intensities') plt.savefig(str(path),bbox_inches='tight' ) # bbox_inches='tight' to remove extra whitespace #for plotting single histogram def histogram_plotting(image): bin_center_array = creating_intensity_index_array() #creating intensity array bin_intensity = histogram(image) # print("histogram") # print(bin_intensity) # plt.bar(bin_center_array, bin_intensity) plt.plot(bin_center_array, bin_intensity) plt.show() #plotting histogram and showing images for 2 images #function to create histogram of an image def histogram(image, bins=256) -> numpy.ndarray: intensity_array = np.zeros((256,), dtype=int) row_count, col_count = image.shape image_temp = image.astype(np.uint8) #ensuring only greyscale images as input :sanity check for row in range(row_count): for col in range(col_count): index = image[row,col] intensity_array[index] = intensity_array[index] + 1 return intensity_array #imp its not 0-1 to 0-255 but float in 0-255 to int 0-255 def array_float_to_0_255(intensity_array): intensity_array_temp = intensity_array.astype(int) #if float to int # making intensities saturate to 0 and 255 intensity_array_temp[intensity_array_temp < 0] = 0 # saturate to 0 intensity_array_temp[intensity_array_temp > 255] = 255 # saturate to 255 intensity_array_output = intensity_array_temp.astype(np.uint8) #appropiate data type return intensity_array_output def array_0_1_to_0_255(intensity_array): intensity_array = intensity_array * 255 intensity_array = array_float_to_0_255(intensity_array) return intensity_array #creating an array storing 0 to 255 def creating_intensity_index_array(): intensity_index_array = np.zeros((256,), dtype=int) # stores 0-255 # creating intensity values array sum = 0 for x in range(256): intensity_index_array[x] = sum sum += 1 return intensity_index_array #changing image as per remapped intensity values def remap_image_intensities(intensity_mapping , image): intensity_index_array = creating_intensity_index_array() # array from 0-255 values image = intensity_mapping[image] #JUST ONE LINE!!!! <- #it changes the intensity values in "image" as per the inensity mapping return image
[ "matplotlib.pyplot.imshow", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.figure", "numpy.zeros", "matplotlib.pyplot.title", "matplotlib.pyplot.show" ]
[((578, 606), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(25, 25)'}), '(figsize=(25, 25))\n', (588, 606), True, 'from matplotlib import pyplot, pyplot as plt\n'), ((1449, 1459), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1457, 1459), True, 'from matplotlib import pyplot, pyplot as plt\n'), ((1838, 1866), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(25, 25)'}), '(figsize=(25, 25))\n', (1848, 1866), True, 'from matplotlib import pyplot, pyplot as plt\n'), ((3051, 3092), 'matplotlib.pyplot.plot', 'plt.plot', (['bin_center_array', 'bin_intensity'], {}), '(bin_center_array, bin_intensity)\n', (3059, 3092), True, 'from matplotlib import pyplot, pyplot as plt\n'), ((3097, 3107), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3105, 3107), True, 'from matplotlib import pyplot, pyplot as plt\n'), ((3278, 3305), 'numpy.zeros', 'np.zeros', (['(256,)'], {'dtype': 'int'}), '((256,), dtype=int)\n', (3286, 3305), True, 'import numpy as np\n'), ((4442, 4469), 'numpy.zeros', 'np.zeros', (['(256,)'], {'dtype': 'int'}), '((256,), dtype=int)\n', (4450, 4469), True, 'import numpy as np\n'), ((1080, 1169), 'matplotlib.pyplot.imshow', 'pyplot.imshow', (['kwargs[list_of_names[x]]'], {'cmap': '"""gray"""', 'vmin': '(0)', 'vmax': '(255)', 'aspect': '"""auto"""'}), "(kwargs[list_of_names[x]], cmap='gray', vmin=0, vmax=255,\n aspect='auto')\n", (1093, 1169), False, 'from matplotlib import pyplot, pyplot as plt\n'), ((1174, 1217), 'matplotlib.pyplot.title', 'pyplot.title', (['list_of_names[x]'], {'fontsize': '(20)'}), '(list_of_names[x], fontsize=20)\n', (1186, 1217), False, 'from matplotlib import pyplot, pyplot as plt\n'), ((1416, 1444), 'matplotlib.pyplot.xlabel', 'pyplot.xlabel', (['"""intensities"""'], {}), "('intensities')\n", (1429, 1444), False, 'from matplotlib import pyplot, pyplot as plt\n'), ((2297, 2386), 'matplotlib.pyplot.imshow', 'pyplot.imshow', (['kwargs[list_of_names[x]]'], {'cmap': '"""gray"""', 'vmin': '(0)', 'vmax': '(255)', 'aspect': '"""auto"""'}), "(kwargs[list_of_names[x]], cmap='gray', vmin=0, vmax=255,\n aspect='auto')\n", (2310, 2386), False, 'from matplotlib import pyplot, pyplot as plt\n'), ((2391, 2434), 'matplotlib.pyplot.title', 'pyplot.title', (['list_of_names[x]'], {'fontsize': '(20)'}), '(list_of_names[x], fontsize=20)\n', (2403, 2434), False, 'from matplotlib import pyplot, pyplot as plt\n'), ((2623, 2651), 'matplotlib.pyplot.xlabel', 'pyplot.xlabel', (['"""intensities"""'], {}), "('intensities')\n", (2636, 2651), False, 'from matplotlib import pyplot, pyplot as plt\n')]
# # # Copyright (c) 2013, Georgia Tech Research Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Georgia Tech Research Corporation 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 GEORGIA TECH RESEARCH CORPORATION ''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 GEORGIA TECH 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. # # \authors: <NAME> (Healthcare Robotics Lab, Georgia Tech.) # \adviser: <NAME> (Healthcare Robotics Lab, Georgia Tech.) import subprocess import roslib roslib.load_manifest('hrl_dynamic_mpc') import sys import time import hrl_lib.util as ut import numpy as np import os from hrl_dynamic_mpc.srv import LogData import threading import rospy import signal import darci_client as dc class BatchRunner(): def __init__(self, num_trials, f_threshes, delta_t_s, goal_reset=None): self.num_trials = num_trials self.lock = threading.RLock() self.first_reach = True goal_reset[2] = goal_reset[2] - 0.15 self.goal_reset = goal_reset rospy.init_node('batch_trials_reaching') rospy.wait_for_service('rosbag_data') rospy.wait_for_service('log_skin_data') rospy.wait_for_service('log_data') self.rosbag_srv = rospy.ServiceProxy('rosbag_data', LogData) self.ft_and_humanoid_record_srv = rospy.ServiceProxy('log_data', LogData) self.skin_record_srv = rospy.ServiceProxy('log_skin_data', LogData) self.robot_state = dc.DarciClient() self.f_threshes = f_threshes self.delta_t_s = delta_t_s self.reaching_left_results = [] self.reaching_right_results = [] def run_trial(self, i, side, f_thresh, t_impulse, goal): self.rosbag_srv('first_impact_'+str(i).zfill(3)+'_'+side+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') self.skin_record_srv('first_impact_'+str(i).zfill(3)+'_'+side+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') self.ft_and_humanoid_record_srv('first_impact_'+str(i).zfill(3)+'_'+side+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') goal_ls = goal[0].A1.tolist() goal_str_buf = [str(goal_ls[0])+', '+str(goal_ls[1])+', '+str(goal_ls[2])] goal_str = ''.join(goal_str_buf) controller = subprocess.call(['python', 'run_controller_debug.py', '--darci', '--t_impulse='+str(t_impulse), '--f_thresh='+str(f_thresh), "--goal="+goal_str]) time.sleep(1.0) self.rosbag_srv('') self.skin_record_srv('') self.ft_and_humanoid_record_srv('') data = ut.load_pickle('./result.pkl') if side == 'left': self.reaching_left_results.append(data['result']) else: self.reaching_right_results.append(data['result']) return data['result'] def run_slip_trial(self, i, f_thresh, t_impulse, goal): self.rosbag_srv('slip_impact_'+str(i).zfill(3)+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') self.skin_record_srv('slip_impact_'+str(i).zfill(3)+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') self.ft_and_humanoid_record_srv('slip_impact_'+str(i).zfill(3)+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') goal_ls = goal[0].A1.tolist() goal_str_buf = [str(goal_ls[0])+', '+str(goal_ls[1])+', '+str(goal_ls[2])] goal_str = ''.join(goal_str_buf) controller = subprocess.call(['python', 'run_controller_debug.py', '--darci', '--t_impulse='+str(t_impulse), '--f_thresh='+str(f_thresh), "--goal="+goal_str]) time.sleep(1.0) self.rosbag_srv('') self.skin_record_srv('') self.ft_and_humanoid_record_srv('') data = ut.load_pickle('./result.pkl') self.reaching_right_results.append(data['result']) return data['result'] def run_slip_trial(self, i, f_thresh, t_impulse, goal): self.rosbag_srv('slip_impact_'+str(i).zfill(3)+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') self.skin_record_srv('slip_impact_'+str(i).zfill(3)+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') self.ft_and_humanoid_record_srv('slip_impact_'+str(i).zfill(3)+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') goal_ls = goal[0].A1.tolist() goal_str_buf = [str(goal_ls[0])+', '+str(goal_ls[1])+', '+str(goal_ls[2])] goal_str = ''.join(goal_str_buf) controller = subprocess.call(['python', 'run_controller_debug.py', '--darci', '--t_impulse='+str(t_impulse), '--f_thresh='+str(f_thresh), "--goal="+goal_str]) time.sleep(1.0) self.rosbag_srv('') self.skin_record_srv('') self.ft_and_humanoid_record_srv('') data = ut.load_pickle('./result.pkl') self.reaching_right_results.append(data['result']) return data['result'] def run_canonical_trial(self, i, f_thresh, t_impulse, goal, num_can): self.rosbag_srv('canonical_'+str(num_can).zfill(2)+'_trial_'+str(i).zfill(3)+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)) self.skin_record_srv('canonical_'+str(num_can).zfill(2)+'_trial_'+str(i).zfill(3)+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') self.ft_and_humanoid_record_srv('canonical_'+str(num_can).zfill(2)+'_trial_'+str(i).zfill(3)+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') goal_ls = goal[0].A1.tolist() goal_str_buf = [str(goal_ls[0])+', '+str(goal_ls[1])+', '+str(goal_ls[2])] goal_str = ''.join(goal_str_buf) controller = subprocess.call(['python', 'run_controller_debug.py', '--darci', '--t_impulse='+str(t_impulse), '--f_thresh='+str(f_thresh), "--goal="+goal_str]) time.sleep(1.0) self.rosbag_srv('') self.skin_record_srv('') self.ft_and_humanoid_record_srv('') data = ut.load_pickle('./result.pkl') self.reaching_right_results.append(data['result']) return data['result'] def run_canonical(self, goals, q_configs, num_canonical): for cmd in q_configs['start']: self.robot_state.setDesiredJointAngles(list(cmd)) self.robot_state.updateSendCmd() time.sleep(2.) for f_thresh in self.f_threshes: for t_impulse in self.delta_t_s: for i in xrange(self.num_trials): self.robot_state.setDesiredJointAngles(list(q_configs['right_start'][0])) self.robot_state.updateSendCmd() time.sleep(1.) result = self.run_canonical_trial(i, f_thresh, t_impulse, goals, num_canonical) for cmd in q_configs['restart']: self.robot_state.setDesiredJointAngles(list(cmd)) self.robot_state.updateSendCmd() time.sleep(2.) self.robot_state.setDesiredJointAngles(list(q_configs['right_start'][0])) self.robot_state.updateSendCmd() time.sleep(1.) data2 = {} data2['reaching_straight'] = self.reaching_right_results ut.save_pickle(data, './combined_results_for_canonical'+str(num_canonical)+'.pkl') def run_foliage_trial(self, i, f_thresh, t_impulse, goal, num_reach, record = True): if record == True: self.rosbag_srv('foliage_goal_'+str(num_reach).zfill(3)+'_trial_'+str(i).zfill(3)+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') self.skin_record_srv('foliage_goal_'+str(num_reach).zfill(3)+'_trial_'+str(i).zfill(3)+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') self.ft_and_humanoid_record_srv('foliage_goal_'+str(num_reach).zfill(3)+'_trial_'+str(i).zfill(3)+'_f_thresh_'+str(f_thresh).zfill(2)+'_delta_t_impulse_'+str(t_impulse).zfill(3)+'_') goal_ls = goal goal_str_buf = [str(goal_ls[0])+', '+str(goal_ls[1])+', '+str(goal_ls[2])] goal_str = ''.join(goal_str_buf) controller = subprocess.call(['python', 'run_controller_debug.py', '--darci', '--t_impulse='+str(t_impulse), '--f_thresh='+str(f_thresh), "--goal="+goal_str]) time.sleep(1.0) if record == True: self.rosbag_srv('') self.skin_record_srv('') self.ft_and_humanoid_record_srv('') data = ut.load_pickle('./result.pkl') return data['result'] def run_foliage_reach(self, goals, q_configs, num_reach): if self.first_reach == True: self.first_reach = False for cmd in q_configs['start']: self.robot_state.setDesiredJointAngles(list(cmd)) self.robot_state.updateSendCmd() time.sleep(2.) for f_thresh in self.f_threshes: for t_impulse in self.delta_t_s: for i in xrange(self.num_trials): self.robot_state.setDesiredJointAngles(list(q_configs['trial_start'][0])) self.robot_state.updateSendCmd() time.sleep(1.) result = self.run_foliage_trial(i, f_thresh, t_impulse, goals, num_reach) offset = 0.20 - goals[2] goals[2] = goals[2]+offset counter = (str(i)+'_up').zfill(6) reset_result = self.run_foliage_trial(counter, f_thresh, t_impulse, goals, num_reach) reset_result = self.run_foliage_trial(i, f_thresh, t_impulse, self.goal_reset, num_reach, record = False) if result != 'success': raw_input('Help me a bit please ..') for cmd in q_configs['restart']: self.robot_state.setDesiredJointAngles(list(cmd)) self.robot_state.updateSendCmd() time.sleep(2.) self.robot_state.setDesiredJointAngles(list(q_configs['trial_start'][0])) self.robot_state.updateSendCmd() time.sleep(1.) data2 = {} data2['reaching_straight'] = self.reaching_right_results ut.save_pickle(data, './combined_results_for_foliage.pkl') def run_first_impact(self, goals, q_configs): for cmd in q_configs['start']: self.robot_state.setDesiredJointAngles(list(cmd)) self.robot_state.updateSendCmd() time.sleep(2.) for f_thresh in self.f_threshes: for t_impulse in self.delta_t_s: for i in xrange(self.num_trials): self.robot_state.setDesiredJointAngles(list(q_configs['left_start'][0])) self.robot_state.updateSendCmd() time.sleep(1.) side = 'left' result = self.run_trial(i, side, f_thresh, t_impulse, goals[side]) if result == 'success': self.robot_state.setDesiredJointAngles(list(q_configs['right_start'][0])) self.robot_state.updateSendCmd() time.sleep(2.) else: for cmd in q_configs['left_to_right_restart']: self.robot_state.setDesiredJointAngles(list(cmd)) self.robot_state.updateSendCmd() time.sleep(2.) self.robot_state.setDesiredJointAngles(list(q_configs['right_start'][0])) self.robot_state.updateSendCmd() time.sleep(1.) side = 'right' result = self.run_trial(i, side, f_thresh, t_impulse, goals[side]) if result == 'success': self.robot_state.setDesiredJointAngles(list(q_configs['left_start'][0])) self.robot_state.updateSendCmd() time.sleep(2.) else: for cmd in q_configs['right_to_left_restart']: self.robot_state.setDesiredJointAngles(list(cmd)) self.robot_state.updateSendCmd() time.sleep(2.) self.robot_state.setDesiredJointAngles(list(q_configs['left_start'][0])) self.robot_state.updateSendCmd() time.sleep(1.) data2 = {} data2['reaching_left'] = self.reaching_left_results data2['reaching_right'] = self.reaching_right_results ut.save_pickle(data, './combined_results_for_first_impact.pkl') def in_hull(self, p, hull): """ Test if points in `p` are in `hull` `p` should be a `NxK` coordinates of `N` points in `K` dimension `hull` is either a scipy.spatial.Delaunay object or the `MxK` array of the coordinates of `M` points in `K`dimension for which a Delaunay triangulation will be computed """ from scipy.spatial import Delaunay if not isinstance(hull,Delaunay): hull = Delaunay(hull) return hull.find_simplex(p)>=0 if __name__ == '__main__': num_trials = 1 #f_threshes = [10.] #, 15.] f_threshes = [5.] #delta_t_s = [2., 4., 16., 48.] delta_t_s = [8.] #delta_t_s = [16., 48.] data = ut.load_pickle('./joint_and_ee_data.pkl') goal = data['ee_positions']['restart'] goal_reset = goal[0].A1.tolist() runner = BatchRunner(num_trials, f_threshes, delta_t_s, goal_reset) # goals = {'left':data['ee_positions']['right_start'], # 'right':data['ee_positions']['left_start']} # runner.run_first_impact(goals, data['q_configs']) # data = ut.load_pickle('./starting_configs.pkl') # goals = data['ee_positions']['goal'] # #runner.run_slip_impact(goals, data['q_configs']) # runner.run_canonical(data['ee_positions']['goal'], data['q_configs'], 5) range_pos = np.array(data['ee_positions']['range']).reshape(7,3) z_max = -0.05 z_min = -0.25 x_max = np.max(range_pos[:,0]) x_min = np.min(range_pos[:,0]) y_max = np.max(range_pos[:,1]) y_min = np.min(range_pos[:,1]) goals = [] for i in xrange(120): flag = False while flag == False: x_rand, y_rand, z_rand = np.random.rand(3) x = x_rand*(x_max-x_min)+x_min y = y_rand*(y_max-y_min)+y_min z = z_rand*(z_max-z_min)+z_min flag = runner.in_hull(np.array([x, y]), range_pos[:, 0:2].reshape(7,2)) if np.sqrt(x**2+(y-0.185)**2) < 0.30: flag = False goal_ls = [x, y, z] goals.append(goal_ls) ut.save_pickle(goals, './goal_positions.pkl') runner.run_foliage_reach(goal_ls, data['q_configs'], i)
[ "hrl_lib.util.save_pickle", "numpy.sqrt", "numpy.random.rand", "hrl_lib.util.load_pickle", "rospy.init_node", "rospy.ServiceProxy", "threading.RLock", "time.sleep", "numpy.max", "roslib.load_manifest", "numpy.array", "scipy.spatial.Delaunay", "numpy.min", "darci_client.DarciClient", "ros...
[((1738, 1777), 'roslib.load_manifest', 'roslib.load_manifest', (['"""hrl_dynamic_mpc"""'], {}), "('hrl_dynamic_mpc')\n", (1758, 1777), False, 'import roslib\n'), ((15983, 16024), 'hrl_lib.util.load_pickle', 'ut.load_pickle', (['"""./joint_and_ee_data.pkl"""'], {}), "('./joint_and_ee_data.pkl')\n", (15997, 16024), True, 'import hrl_lib.util as ut\n'), ((16716, 16739), 'numpy.max', 'np.max', (['range_pos[:, 0]'], {}), '(range_pos[:, 0])\n', (16722, 16739), True, 'import numpy as np\n'), ((16751, 16774), 'numpy.min', 'np.min', (['range_pos[:, 0]'], {}), '(range_pos[:, 0])\n', (16757, 16774), True, 'import numpy as np\n'), ((16786, 16809), 'numpy.max', 'np.max', (['range_pos[:, 1]'], {}), '(range_pos[:, 1])\n', (16792, 16809), True, 'import numpy as np\n'), ((16821, 16844), 'numpy.min', 'np.min', (['range_pos[:, 1]'], {}), '(range_pos[:, 1])\n', (16827, 16844), True, 'import numpy as np\n'), ((2122, 2139), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (2137, 2139), False, 'import threading\n'), ((2262, 2302), 'rospy.init_node', 'rospy.init_node', (['"""batch_trials_reaching"""'], {}), "('batch_trials_reaching')\n", (2277, 2302), False, 'import rospy\n'), ((2312, 2349), 'rospy.wait_for_service', 'rospy.wait_for_service', (['"""rosbag_data"""'], {}), "('rosbag_data')\n", (2334, 2349), False, 'import rospy\n'), ((2358, 2397), 'rospy.wait_for_service', 'rospy.wait_for_service', (['"""log_skin_data"""'], {}), "('log_skin_data')\n", (2380, 2397), False, 'import rospy\n'), ((2406, 2440), 'rospy.wait_for_service', 'rospy.wait_for_service', (['"""log_data"""'], {}), "('log_data')\n", (2428, 2440), False, 'import rospy\n'), ((2468, 2510), 'rospy.ServiceProxy', 'rospy.ServiceProxy', (['"""rosbag_data"""', 'LogData'], {}), "('rosbag_data', LogData)\n", (2486, 2510), False, 'import rospy\n'), ((2553, 2592), 'rospy.ServiceProxy', 'rospy.ServiceProxy', (['"""log_data"""', 'LogData'], {}), "('log_data', LogData)\n", (2571, 2592), False, 'import rospy\n'), ((2624, 2668), 'rospy.ServiceProxy', 'rospy.ServiceProxy', (['"""log_skin_data"""', 'LogData'], {}), "('log_skin_data', LogData)\n", (2642, 2668), False, 'import rospy\n'), ((2696, 2712), 'darci_client.DarciClient', 'dc.DarciClient', ([], {}), '()\n', (2710, 2712), True, 'import darci_client as dc\n'), ((3932, 3947), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (3942, 3947), False, 'import time\n'), ((4078, 4108), 'hrl_lib.util.load_pickle', 'ut.load_pickle', (['"""./result.pkl"""'], {}), "('./result.pkl')\n", (4092, 4108), True, 'import hrl_lib.util as ut\n'), ((5339, 5354), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (5349, 5354), False, 'import time\n'), ((5485, 5515), 'hrl_lib.util.load_pickle', 'ut.load_pickle', (['"""./result.pkl"""'], {}), "('./result.pkl')\n", (5499, 5515), True, 'import hrl_lib.util as ut\n'), ((6643, 6658), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (6653, 6658), False, 'import time\n'), ((6789, 6819), 'hrl_lib.util.load_pickle', 'ut.load_pickle', (['"""./result.pkl"""'], {}), "('./result.pkl')\n", (6803, 6819), True, 'import hrl_lib.util as ut\n'), ((8042, 8057), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (8052, 8057), False, 'import time\n'), ((8188, 8218), 'hrl_lib.util.load_pickle', 'ut.load_pickle', (['"""./result.pkl"""'], {}), "('./result.pkl')\n", (8202, 8218), True, 'import hrl_lib.util as ut\n'), ((10759, 10774), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (10769, 10774), False, 'import time\n'), ((10944, 10974), 'hrl_lib.util.load_pickle', 'ut.load_pickle', (['"""./result.pkl"""'], {}), "('./result.pkl')\n", (10958, 10974), True, 'import hrl_lib.util as ut\n'), ((12770, 12828), 'hrl_lib.util.save_pickle', 'ut.save_pickle', (['data', '"""./combined_results_for_foliage.pkl"""'], {}), "(data, './combined_results_for_foliage.pkl')\n", (12784, 12828), True, 'import hrl_lib.util as ut\n'), ((15192, 15255), 'hrl_lib.util.save_pickle', 'ut.save_pickle', (['data', '"""./combined_results_for_first_impact.pkl"""'], {}), "(data, './combined_results_for_first_impact.pkl')\n", (15206, 15255), True, 'import hrl_lib.util as ut\n'), ((17364, 17409), 'hrl_lib.util.save_pickle', 'ut.save_pickle', (['goals', '"""./goal_positions.pkl"""'], {}), "(goals, './goal_positions.pkl')\n", (17378, 17409), True, 'import hrl_lib.util as ut\n'), ((8530, 8545), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (8540, 8545), False, 'import time\n'), ((13041, 13056), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (13051, 13056), False, 'import time\n'), ((15729, 15743), 'scipy.spatial.Delaunay', 'Delaunay', (['hull'], {}), '(hull)\n', (15737, 15743), False, 'from scipy.spatial import Delaunay\n'), ((16610, 16649), 'numpy.array', 'np.array', (["data['ee_positions']['range']"], {}), "(data['ee_positions']['range'])\n", (16618, 16649), True, 'import numpy as np\n'), ((16984, 17001), 'numpy.random.rand', 'np.random.rand', (['(3)'], {}), '(3)\n', (16998, 17001), True, 'import numpy as np\n'), ((11318, 11333), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (11328, 11333), False, 'import time\n'), ((17166, 17182), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (17174, 17182), True, 'import numpy as np\n'), ((17232, 17266), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + (y - 0.185) ** 2)'], {}), '(x ** 2 + (y - 0.185) ** 2)\n', (17239, 17266), True, 'import numpy as np\n'), ((8849, 8864), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (8859, 8864), False, 'import time\n'), ((9376, 9391), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (9386, 9391), False, 'import time\n'), ((11637, 11652), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (11647, 11652), False, 'import time\n'), ((12662, 12677), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (12672, 12677), False, 'import time\n'), ((13359, 13374), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (13369, 13374), False, 'import time\n'), ((9194, 9209), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (9204, 9209), False, 'import time\n'), ((12480, 12495), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (12490, 12495), False, 'import time\n'), ((13720, 13735), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (13730, 13735), False, 'import time\n'), ((14193, 14208), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (14203, 14208), False, 'import time\n'), ((14554, 14569), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (14564, 14569), False, 'import time\n'), ((15026, 15041), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (15036, 15041), False, 'import time\n'), ((13999, 14014), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (14009, 14014), False, 'import time\n'), ((14833, 14848), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (14843, 14848), False, 'import time\n')]
import numpy as np def softmax_func(x): """ Numerically stable softmax function. For more details about numerically calculations please refer: http://www.deeplearningbook.org/slides/04_numerical.pdf :param x: :return: """ stable_values = x - np.max(x, axis=1, keepdims=True) return np.exp(stable_values) / np.sum(np.exp(stable_values), axis=1, keepdims=True) def log_sum_exp(x): """ log_sum_exp is a very useful function in machine learning. It can be seen in many places including cross-entropy error. However, the naive implementation is numerically unstable. Therefore, we use the following implementation. For more details please refer: http://www.deeplearningbook.org/slides/04_numerical.pdf :param x: :return: """ mx = np.max(x, axis=1, keepdims=True) safe = x - mx return mx + np.log(np.sum(np.exp(safe), axis=1, keepdims=True)) # Following two methods were used in the initial version of the convolution operations. # Later we introduced fast Cython versions of `im2col` and `col2im` implementations. # Hence, these two methods are obsolete. def im2col(image, filter_size=(3, 3), padding=(0, 0), stride=(1, 1)): M, C, h, w, = image.shape filter_height = filter_size[0] filter_width = filter_size[1] padding_height = padding[0] padding_width = padding[1] stride_height = stride[0] stride_width = stride[1] x_padded = np.pad(image, ((0, 0), (0, 0), (padding_height, padding_height), (padding_width, padding_width)), mode='constant') h_new = int((h - filter_height + 2 * padding_height) / stride_height + 1) w_new = int((w - filter_width + 2 * padding_width) / stride_width + 1) out = np.zeros((filter_width * filter_height * C, M * h_new * w_new), dtype=image.dtype) itr = 0 for i in range(h_new): for j in range(w_new): for m in range(M): start_i = stride_height * i end_i = stride_height * i + filter_width start_j = stride_width * j end_j = stride_width * j + filter_height out[:, itr] = x_padded[m, :, start_i:end_i, start_j:end_j].ravel() itr += 1 return out def col2im(cols, x_shape, filter_size=(3, 3), padding=(0, 0), stride=(1, 1)): N, C, H, W = x_shape filter_height = filter_size[0] filter_width = filter_size[1] padding_height = padding[0] padding_width = padding[1] stride_height = stride[0] stride_width = stride[1] H_padded, W_padded = H + 2 * padding_height, W + 2 * padding_width x_padded = np.zeros((N, C, H_padded, W_padded), dtype=cols.dtype) idx = 0 for i in range(0, H_padded - filter_height + 1, stride_height): for j in range(0, W_padded - filter_width + 1, stride_width): for m in range(N): col = cols[:, idx] col = col.reshape((C, filter_height, filter_width)) x_padded[m, :, i:i + filter_height, j:j + filter_width] += col idx += 1 if padding[0] or padding[1] > 0: return x_padded[:, :, padding_height:-padding_height, padding_width:-padding_width] else: return x_padded
[ "numpy.exp", "numpy.pad", "numpy.zeros", "numpy.max" ]
[((805, 837), 'numpy.max', 'np.max', (['x'], {'axis': '(1)', 'keepdims': '(True)'}), '(x, axis=1, keepdims=True)\n', (811, 837), True, 'import numpy as np\n'), ((1446, 1565), 'numpy.pad', 'np.pad', (['image', '((0, 0), (0, 0), (padding_height, padding_height), (padding_width,\n padding_width))'], {'mode': '"""constant"""'}), "(image, ((0, 0), (0, 0), (padding_height, padding_height), (\n padding_width, padding_width)), mode='constant')\n", (1452, 1565), True, 'import numpy as np\n'), ((1837, 1924), 'numpy.zeros', 'np.zeros', (['(filter_width * filter_height * C, M * h_new * w_new)'], {'dtype': 'image.dtype'}), '((filter_width * filter_height * C, M * h_new * w_new), dtype=image\n .dtype)\n', (1845, 1924), True, 'import numpy as np\n'), ((2729, 2783), 'numpy.zeros', 'np.zeros', (['(N, C, H_padded, W_padded)'], {'dtype': 'cols.dtype'}), '((N, C, H_padded, W_padded), dtype=cols.dtype)\n', (2737, 2783), True, 'import numpy as np\n'), ((276, 308), 'numpy.max', 'np.max', (['x'], {'axis': '(1)', 'keepdims': '(True)'}), '(x, axis=1, keepdims=True)\n', (282, 308), True, 'import numpy as np\n'), ((320, 341), 'numpy.exp', 'np.exp', (['stable_values'], {}), '(stable_values)\n', (326, 341), True, 'import numpy as np\n'), ((351, 372), 'numpy.exp', 'np.exp', (['stable_values'], {}), '(stable_values)\n', (357, 372), True, 'import numpy as np\n'), ((886, 898), 'numpy.exp', 'np.exp', (['safe'], {}), '(safe)\n', (892, 898), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt from os import path from src.sampler import BTCsampler from src.emulator import Market def main(): """ This function computes the wavelet transform over non-overlapping time windows across the bitcoin dataset to identify coefficients that can be shrinked and removed from the state space """ # Database: set options and create Sampler = BTCsampler db_type = 'BTCsampler'; db = 'db_bitcoin.pickle' fld = path.join('..', 'data', db_type, db) wavChan = 4 window_state= 32 sampler = Sampler(True, fld=fld, variables=['Close'], wavelet_channels=wavChan, window_training_episode=window_state, window_testing_episode=window_state) # Wavelet transform # --- With time difference envTD = Market(sampler, window_state, 0, time_difference=True, wavelet_channels=wavChan) stateTD = [] # --- Without time difference envRAW = Market(sampler, window_state, 0, time_difference=False, wavelet_channels=wavChan) stateRAW = [] # --- Loop and compute for il in range(400): stTD,_ = envTD.reset() stRW,_ = envRAW.reset() stateTD += [stTD] stateRAW+= [stRW] # Compute descriptive stats stateTD = np.array(stateTD) stateRAW = np.array(stateRAW) # --- Mean F = plt.figure() Ax1 = F.add_subplot(121) Ax1.plot( np.mean(stateRAW, axis=0) ) Ax1.set_xlabel('Wavelet coefficient ID') Ax1.set_ylabel('Average magnitude') Ax1.set_title('WT on RAW signal') Ax2 = F.add_subplot(122) Ax2.plot(np.mean(stateTD, axis=0)) Ax2.set_xlabel('Wavelet coefficient ID') Ax2.set_ylabel('Average magnitude') Ax2.set_title('WT on T-D signal') # --- STD F = plt.figure() Ax1 = F.add_subplot(121) Ax1.plot(np.std(stateRAW, axis=0)) Ax1.set_xlabel('Wavelet coefficient ID') Ax1.set_ylabel('Standard deviation') Ax1.set_title('WT on RAW signal') Ax2 = F.add_subplot(122) Ax2.plot(np.std(stateTD, axis=0)) Ax2.set_xlabel('Wavelet coefficient ID') Ax2.set_ylabel('Standard deviation') Ax2.set_title('WT on T-D signal') if __name__ == '__main__': main()
[ "numpy.mean", "os.path.join", "src.emulator.Market", "numpy.array", "matplotlib.pyplot.figure", "numpy.std" ]
[((527, 563), 'os.path.join', 'path.join', (['""".."""', '"""data"""', 'db_type', 'db'], {}), "('..', 'data', db_type, db)\n", (536, 563), False, 'from os import path\n'), ((878, 963), 'src.emulator.Market', 'Market', (['sampler', 'window_state', '(0)'], {'time_difference': '(True)', 'wavelet_channels': 'wavChan'}), '(sampler, window_state, 0, time_difference=True, wavelet_channels=wavChan\n )\n', (884, 963), False, 'from src.emulator import Market\n'), ((1036, 1122), 'src.emulator.Market', 'Market', (['sampler', 'window_state', '(0)'], {'time_difference': '(False)', 'wavelet_channels': 'wavChan'}), '(sampler, window_state, 0, time_difference=False, wavelet_channels=\n wavChan)\n', (1042, 1122), False, 'from src.emulator import Market\n'), ((1370, 1387), 'numpy.array', 'np.array', (['stateTD'], {}), '(stateTD)\n', (1378, 1387), True, 'import numpy as np\n'), ((1408, 1426), 'numpy.array', 'np.array', (['stateRAW'], {}), '(stateRAW)\n', (1416, 1426), True, 'import numpy as np\n'), ((1455, 1467), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1465, 1467), True, 'import matplotlib.pyplot as plt\n'), ((1878, 1890), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1888, 1890), True, 'import matplotlib.pyplot as plt\n'), ((1513, 1538), 'numpy.mean', 'np.mean', (['stateRAW'], {'axis': '(0)'}), '(stateRAW, axis=0)\n', (1520, 1538), True, 'import numpy as np\n'), ((1706, 1730), 'numpy.mean', 'np.mean', (['stateTD'], {'axis': '(0)'}), '(stateTD, axis=0)\n', (1713, 1730), True, 'import numpy as np\n'), ((1933, 1957), 'numpy.std', 'np.std', (['stateRAW'], {'axis': '(0)'}), '(stateRAW, axis=0)\n', (1939, 1957), True, 'import numpy as np\n'), ((2125, 2148), 'numpy.std', 'np.std', (['stateTD'], {'axis': '(0)'}), '(stateTD, axis=0)\n', (2131, 2148), True, 'import numpy as np\n')]