code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
#!/usr/bin/env python3 import argparse import sys import math from typing import List import random import numpy import soundfile import samplerate as libsamplerate import progressbar def divide_sound_file(data: numpy.ndarray, samples_per_chunk: int): return [ data[i * samples_per_chunk:(i + 1) * samples_per_chunk] for i in range(0, math.ceil(len(data) / samples_per_chunk)) ] def stretch_palette(chunks: List[numpy.ndarray], num_chunks: int): # print([sqrt_hlen - math.fabs(sqrt_hlen - math.sqrt(i)) for i in range(0, len(chunks))]) n = math.floor(math.log2(num_chunks)) excess = len(chunks) - num_chunks if excess > 0: snip = excess // 2 print(snip) chunks = chunks[snip:len(chunks)-snip] hlen = len(chunks) / 2 weights = [math.sqrt(hlen - math.fabs(hlen - i) + 1) for i in range(0, len(chunks))] return random.choices(chunks, weights=weights, k=num_chunks) def main(): parser = argparse.ArgumentParser('Rearrange a sound file to match another') parser.add_argument('target', type=str, help='the sound file to recreate') parser.add_argument('palette', type=str, help='the sound file to recreate it from') parser.add_argument('out', type=str, help='the sound file to output') parser.add_argument('--chunk-length', type=int, help='the length of each chunk the sound files are divided in', default=5) parser.add_argument('--seed', type=int, help='the seed of the random number generator') parser.add_argument('--max-swap-fails', type=int, default=250, help='the maximum number of failed attempts to improve the quality') args = parser.parse_args(sys.argv[1:]) random.seed(args.seed) target_data, target_samplerate = soundfile.read(args.target, always_2d=True, dtype='float32') palette_data, palette_samplerate = soundfile.read(args.palette, always_2d=True, dtype='float32') if palette_samplerate != target_samplerate: print('Resampling palette...') progress_bar = progressbar.ProgressBarThread() progress_bar.start() resampler = libsamplerate.Resampler(libsamplerate.converters.ConverterType.sinc_best, channels=2) palette_data = resampler.process(palette_data, target_samplerate / palette_samplerate) progress_bar.stop() sample_rate = target_samplerate del target_samplerate del palette_samplerate print('Chopping up sound files...') progress_bar = progressbar.ProgressBarThread() progress_bar.start() samples_per_chunk = sample_rate * args.chunk_length // 1000 target_chunks = divide_sound_file(target_data, samples_per_chunk) palette_chunks = divide_sound_file(palette_data, samples_per_chunk) progress_bar.stop() print('Moulding palette...') progress_bar = progressbar.ProgressBarThread() progress_bar.start() # occ = {} result_chunks = stretch_palette(palette_chunks, len(target_chunks)) assert len(result_chunks) == len(target_chunks) progress_bar.stop() print('Normalizing chunks...') progress_bar = progressbar.ProgressBarThread(2 * len(target_chunks)) for i, chunk in enumerate(target_chunks): length, num_channels = chunk.shape if length < samples_per_chunk: target_chunks[i] = numpy.append(chunk, [[0, 0]] * (samples_per_chunk - length), axis=0) assert target_chunks[i].shape == (samples_per_chunk, 2) progress_bar.progress(i) for i, chunk in enumerate(result_chunks): length, num_channels = chunk.shape if length < samples_per_chunk: result_chunks[i] = numpy.append(chunk, [[0, 0]] * (samples_per_chunk - length), axis=0) assert result_chunks[i].shape == (samples_per_chunk, 2) progress_bar.progress(i) progress_bar.stop() print('Maximizing sound quality...') progress_bar = progressbar.ProgressBarThread(args.max_swap_fails) progress_bar.start() num_failed_swaps = 0 num_failed_swaps_hist = [num_failed_swaps] total_swaps = 0 total_iters = 0 while num_failed_swaps < args.max_swap_fails: i, k = random.sample(range(0, len(target_chunks)), k=2) cdiff_i = ((result_chunks[i] - target_chunks[i]) ** 2).mean() cdiff_k = ((result_chunks[k] - target_chunks[k]) ** 2).mean() cdiff = cdiff_i + cdiff_k ndiff_i = ((result_chunks[k] - target_chunks[i]) ** 2).mean() ndiff_k = ((result_chunks[i] - target_chunks[k]) ** 2).mean() ndiff = ndiff_i + ndiff_k if ndiff < cdiff: num_failed_swaps_hist = num_failed_swaps_hist[-args.max_swap_fails:] num_failed_swaps_hist.append(num_failed_swaps) num_failed_swaps = 0 total_swaps += 1 result_chunks[i], result_chunks[k] = result_chunks[k], result_chunks[i] else: num_failed_swaps += 1 progress_bar.progress(numpy.average(num_failed_swaps_hist), 's: {}, t: {}'.format(total_swaps, total_iters)) total_iters += 1 progress_bar.stop() soundfile.write(args.out, numpy.concatenate(result_chunks), sample_rate) if __name__ == '__main__': main()
[ "samplerate.Resampler", "soundfile.read", "numpy.average", "argparse.ArgumentParser", "math.fabs", "random.choices", "numpy.append", "random.seed", "math.log2", "numpy.concatenate", "progressbar.ProgressBarThread" ]
[((892, 945), 'random.choices', 'random.choices', (['chunks'], {'weights': 'weights', 'k': 'num_chunks'}), '(chunks, weights=weights, k=num_chunks)\n', (906, 945), False, 'import random\n'), ((973, 1039), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""Rearrange a sound file to match another"""'], {}), "('Rearrange a sound file to match another')\n", (996, 1039), False, 'import argparse\n'), ((1732, 1754), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (1743, 1754), False, 'import random\n'), ((1793, 1853), 'soundfile.read', 'soundfile.read', (['args.target'], {'always_2d': '(True)', 'dtype': '"""float32"""'}), "(args.target, always_2d=True, dtype='float32')\n", (1807, 1853), False, 'import soundfile\n'), ((1893, 1954), 'soundfile.read', 'soundfile.read', (['args.palette'], {'always_2d': '(True)', 'dtype': '"""float32"""'}), "(args.palette, always_2d=True, dtype='float32')\n", (1907, 1954), False, 'import soundfile\n'), ((2508, 2539), 'progressbar.ProgressBarThread', 'progressbar.ProgressBarThread', ([], {}), '()\n', (2537, 2539), False, 'import progressbar\n'), ((2850, 2881), 'progressbar.ProgressBarThread', 'progressbar.ProgressBarThread', ([], {}), '()\n', (2879, 2881), False, 'import progressbar\n'), ((3927, 3977), 'progressbar.ProgressBarThread', 'progressbar.ProgressBarThread', (['args.max_swap_fails'], {}), '(args.max_swap_fails)\n', (3956, 3977), False, 'import progressbar\n'), ((589, 610), 'math.log2', 'math.log2', (['num_chunks'], {}), '(num_chunks)\n', (598, 610), False, 'import math\n'), ((2066, 2097), 'progressbar.ProgressBarThread', 'progressbar.ProgressBarThread', ([], {}), '()\n', (2095, 2097), False, 'import progressbar\n'), ((2148, 2237), 'samplerate.Resampler', 'libsamplerate.Resampler', (['libsamplerate.converters.ConverterType.sinc_best'], {'channels': '(2)'}), '(libsamplerate.converters.ConverterType.sinc_best,\n channels=2)\n', (2171, 2237), True, 'import samplerate as libsamplerate\n'), ((5136, 5168), 'numpy.concatenate', 'numpy.concatenate', (['result_chunks'], {}), '(result_chunks)\n', (5153, 5168), False, 'import numpy\n'), ((3341, 3409), 'numpy.append', 'numpy.append', (['chunk', '([[0, 0]] * (samples_per_chunk - length))'], {'axis': '(0)'}), '(chunk, [[0, 0]] * (samples_per_chunk - length), axis=0)\n', (3353, 3409), False, 'import numpy\n'), ((3671, 3739), 'numpy.append', 'numpy.append', (['chunk', '([[0, 0]] * (samples_per_chunk - length))'], {'axis': '(0)'}), '(chunk, [[0, 0]] * (samples_per_chunk - length), axis=0)\n', (3683, 3739), False, 'import numpy\n'), ((4968, 5004), 'numpy.average', 'numpy.average', (['num_failed_swaps_hist'], {}), '(num_failed_swaps_hist)\n', (4981, 5004), False, 'import numpy\n'), ((824, 843), 'math.fabs', 'math.fabs', (['(hlen - i)'], {}), '(hlen - i)\n', (833, 843), False, 'import math\n')]
import glob import time import cv2 import math import numpy as np from Modules.foregroundExtraction import readyFrame, frameDifferencing, morphologicalOperations, natural_sort from Modules.ballDetection import findContours, sizeDetection, playerProximityDetection, regionDetection, courtBoundaryDetection startTimeReadingFrames = time.time() datasetName= "Dataset1" # Location of dataset filenames = glob.glob(datasetName+"/*.jpg") # Reading each frame and storing it in a list frameList = [cv2.imread(frame) for frame in natural_sort(filenames)] endTimeReadingFrames = time.time() print("Reading Frames--- %s seconds ---" % (endTimeReadingFrames - startTimeReadingFrames)) # Parsing through the frames ballCandidatesPreviousFrame = list() meas=[] pred = [] mp = np.array((2, 1), np.float32) # measurement tp = np.zeros((2, 1), np.float32) # tracked / prediction kalman = cv2.KalmanFilter(4,2) kalman.measurementMatrix = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], np.float32) kalman.transitionMatrix = np.array([[1,0,1,0],[0,1,0,1],[0,0,1,0],[0,0,0,1]],np.float32) kalman.processNoiseCov = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32) * 0.009 kalman.measurementNoiseCov = np.array([[1,0],[0,1]],np.float32) * 0.00003 i = 0 while i < (len(frameList)-2): # cv2.imshow("Frame {}".format(i),frameList[i]) # Storing three frames previousFrame = frameList[i] currFrame = frameList[i+1] nextFrame = frameList[i + 2] # # # FOREGROUND EXTRACTION # # startTimeForeGroundExtraction = time.time() # Readying the frames previousFrameGray, currFrameGray, nextFrameGray = readyFrame( previousFrame, currFrame, nextFrame) # Performing frame differencing threshFrameDifferencing = frameDifferencing( previousFrameGray, currFrameGray, nextFrameGray) # Performing morphological operations img_erosion = morphologicalOperations(threshFrameDifferencing, 4, 4) startTimeBlurringBinary = time.time() # Blurring the binary image to get smooth shapes of objects final_image = cv2.medianBlur(img_erosion, 7) endTimeBlurringBinary = time.time() print("Final Blur--- %s seconds ---" % (endTimeBlurringBinary - startTimeBlurringBinary)) endTimeForegroundExtraction=time.time() print("Foreground Extraction--- %s seconds ---" % (endTimeForegroundExtraction - startTimeForeGroundExtraction)) # # # BALL DETECTION # # startTimeBallDetection =time.time() # Making a copy of pre-processed image frame final_image_copy = final_image.copy() # Finding contours in the frame contours, hier = findContours(final_image_copy) # Separating candidates based on size ballCandidates, playerCadidates, incompletePlayerCandidates = sizeDetection(contours, currFrame,i) # Removing candidates outside the Court Boundary in Dataset2 if (datasetName == 'Dataset2'): ballCandidates, playerCadidates, incompletePlayerCandidates = courtBoundaryDetection(ballCandidates,playerCadidates,incompletePlayerCandidates,currFrame) # Removing Candidates that are close to the Players ballCandidatesFiltered = playerProximityDetection(ballCandidates, playerCadidates, incompletePlayerCandidates, currFrame) # Removing candidates that are not in their expected region after motion ballCandidatesFilteredProximity, ballCandidatesPreviousFrame =regionDetection(ballCandidatesFiltered,ballCandidatesPreviousFrame,currFrame) endTimeBallDetection = time.time() print("Ball Detection--- %s seconds ---" % (endTimeBallDetection - startTimeBallDetection)) print(kalman.gain) if (i + 1 == 1): x = ballCandidatesFilteredProximity[0][0] y = ballCandidatesFilteredProximity[0][1] mp = np.array([[np.float32(x)], [np.float32(y)]]) initstate = [mp[0], mp[1]] tp[0] = initstate[0] tp[1] = initstate[1] pred.append((int(tp[0]), int(tp[1]))) cv2.circle(currFrame, (tp[0], tp[1]), 10, (0, 0, 255), -1) else: tp = kalman.predict() tp[0] = tp[0] + initstate[0] tp[1] = tp[1] + initstate[1] pred.append((int(tp[0]), int(tp[1]))) print("prediction: ") print(tp) cv2.circle(currFrame,(tp[0],tp[1]), 10, (0,0,255), -1) # cv2.putText(currFrame, str(tp[0]) + "," + str(tp[1]), (tp[0], tp[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) if (len(ballCandidatesFilteredProximity) == 1): for cand in ballCandidatesFilteredProximity: x = cand[0] y = cand[1] x = x - initstate[0] y = y - initstate[1] mp = np.array([[np.float32(x)], [np.float32(y)]]) print("measurement: ") print(mp) meas.append((x, y)) corrected = kalman.correct(mp) corrected[0] = corrected[0] + initstate[0] corrected[1] = corrected[1] + initstate[1] print("correction: ") print(kalman.correct(mp)) cv2.circle(currFrame,(corrected[0],corrected[1]), 10, (0,255,0), -1) # cv2.putText(currFrame, str(corrected[0]) + "," + str(corrected[1]), (corrected[0], corrected[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) distncePredAct = math.sqrt(math.pow((cand[0] - tp[0]), 2) + math.pow((cand[1] - tp[1]), 2)) # if (distncePredAct < 50): # cv2.circle(currFrame, (corrected[0], corrected[1]), 10, (0, 255, 0), -1) # else: # cv2.circle(currFrame,(tp[0],tp[1]), 10, (0,0,255), -1) cv2.line(currFrame, (int(cand[0]), int(cand[1])), (int(tp[0]), int(tp[1])), (255, 0, 0), 2) xmidPoint = (cand[0]+tp[0])*0.5 ymidPoint = (cand[1]+tp[1])*0.5 cv2.putText(currFrame, str(round(distncePredAct,2)), (int(xmidPoint)-50, int( ymidPoint)-50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.drawContours(currFrame, [cand[3]], -1, (255, 0,), 2) cv2.putText(currFrame, str(cand[0]) + "," + str(cand[1]), (cand[0] + 1, cand[1] + 1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) cv2.imshow('Candidate image', currFrame) elif(len(ballCandidatesFilteredProximity) > 1): print(meas) r = 1 minDistObject = 1000 minDistXcoord = 0 minDistYcoord = 0 for cand in ballCandidatesFilteredProximity: r=r+20 distncePredAct = math.sqrt(math.pow((cand[0] - tp[0]), 2) + math.pow((cand[1] - tp[1]), 2)) # if (distncePredAct < 50): # if (distncePredAct < minDistObject): # minDistObject = distncePredAct # minDistXcoord = cand[0] # minDistYcoord = cand[1] # if (minDistObject == 1000): # cv2.circle(currFrame, (tp[0], tp[1]), 10, (0, 0, 255), -1) # else: # x = minDistXcoord # y = minDistYcoord # x = x - initstate[0] # y = y - initstate[1] # mp = np.array([[np.float32(x)], [np.float32(y)]]) # print("measurement: ") # print(mp) # meas.append((x, y)) # corrected = kalman.correct(mp) # corrected[0] = corrected[0] + initstate[0] # corrected[1] = corrected[1] + initstate[1] # print("correction: ") # print(kalman.correct(mp)) # cv2.circle(currFrame, (corrected[0], corrected[1]), 10, (0, 255, 0), -1) cv2.line(currFrame, (int(cand[0]), int(cand[1])), (int(tp[0]), int(tp[1])), (255, 0, 0), 2) xmidPoint = (cand[0]+tp[0])*0.5 ymidPoint = (cand[1]+tp[1])*0.5 cv2.putText(currFrame, str(round(distncePredAct,2)), (int(xmidPoint)+r, int( ymidPoint+r)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.drawContours(currFrame, [cand[3]], -1, (255, 0,), 2) # cv2.putText(currFrame, str(cand[0]) + "," + str(cand[1]), (cand[0] + 1, cand[1] + 1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) cv2.imshow('Candidate image', currFrame) else: print(meas) cv2.circle(currFrame,(tp[0],tp[1]), 10, (0,0,255), -1) cv2.imshow('Candidate image', currFrame) i += 1 # increments the loop # Exits the loop when Esc is pressed, goes to previous frame when space pressed and goes to next frame when any other key is pressed k = cv2.waitKey(0) if k == 27: break elif k == 32: i -= 2 else: continue
[ "cv2.medianBlur", "Modules.foregroundExtraction.morphologicalOperations", "Modules.foregroundExtraction.readyFrame", "Modules.ballDetection.findContours", "Modules.ballDetection.regionDetection", "glob.glob", "cv2.imshow", "Modules.foregroundExtraction.natural_sort", "math.pow", "cv2.drawContours", "Modules.ballDetection.sizeDetection", "cv2.circle", "cv2.waitKey", "Modules.ballDetection.courtBoundaryDetection", "Modules.ballDetection.playerProximityDetection", "cv2.KalmanFilter", "numpy.float32", "Modules.foregroundExtraction.frameDifferencing", "numpy.zeros", "time.time", "cv2.imread", "numpy.array" ]
[((331, 342), 'time.time', 'time.time', ([], {}), '()\n', (340, 342), False, 'import time\n'), ((401, 434), 'glob.glob', 'glob.glob', (["(datasetName + '/*.jpg')"], {}), "(datasetName + '/*.jpg')\n", (410, 434), False, 'import glob\n'), ((572, 583), 'time.time', 'time.time', ([], {}), '()\n', (581, 583), False, 'import time\n'), ((772, 800), 'numpy.array', 'np.array', (['(2, 1)', 'np.float32'], {}), '((2, 1), np.float32)\n', (780, 800), True, 'import numpy as np\n'), ((821, 849), 'numpy.zeros', 'np.zeros', (['(2, 1)', 'np.float32'], {}), '((2, 1), np.float32)\n', (829, 849), True, 'import numpy as np\n'), ((883, 905), 'cv2.KalmanFilter', 'cv2.KalmanFilter', (['(4)', '(2)'], {}), '(4, 2)\n', (899, 905), False, 'import cv2\n'), ((932, 982), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0]]', 'np.float32'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0]], np.float32)\n', (940, 982), True, 'import numpy as np\n'), ((1009, 1087), 'numpy.array', 'np.array', (['[[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]]', 'np.float32'], {}), '([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32)\n', (1017, 1087), True, 'import numpy as np\n'), ((493, 510), 'cv2.imread', 'cv2.imread', (['frame'], {}), '(frame)\n', (503, 510), False, 'import cv2\n'), ((1097, 1175), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]', 'np.float32'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32)\n', (1105, 1175), True, 'import numpy as np\n'), ((1213, 1251), 'numpy.array', 'np.array', (['[[1, 0], [0, 1]]', 'np.float32'], {}), '([[1, 0], [0, 1]], np.float32)\n', (1221, 1251), True, 'import numpy as np\n'), ((1565, 1576), 'time.time', 'time.time', ([], {}), '()\n', (1574, 1576), False, 'import time\n'), ((1658, 1705), 'Modules.foregroundExtraction.readyFrame', 'readyFrame', (['previousFrame', 'currFrame', 'nextFrame'], {}), '(previousFrame, currFrame, nextFrame)\n', (1668, 1705), False, 'from Modules.foregroundExtraction import readyFrame, frameDifferencing, morphologicalOperations, natural_sort\n'), ((1782, 1848), 'Modules.foregroundExtraction.frameDifferencing', 'frameDifferencing', (['previousFrameGray', 'currFrameGray', 'nextFrameGray'], {}), '(previousFrameGray, currFrameGray, nextFrameGray)\n', (1799, 1848), False, 'from Modules.foregroundExtraction import readyFrame, frameDifferencing, morphologicalOperations, natural_sort\n'), ((1919, 1973), 'Modules.foregroundExtraction.morphologicalOperations', 'morphologicalOperations', (['threshFrameDifferencing', '(4)', '(4)'], {}), '(threshFrameDifferencing, 4, 4)\n', (1942, 1973), False, 'from Modules.foregroundExtraction import readyFrame, frameDifferencing, morphologicalOperations, natural_sort\n'), ((2005, 2016), 'time.time', 'time.time', ([], {}), '()\n', (2014, 2016), False, 'import time\n'), ((2099, 2129), 'cv2.medianBlur', 'cv2.medianBlur', (['img_erosion', '(7)'], {}), '(img_erosion, 7)\n', (2113, 2129), False, 'import cv2\n'), ((2158, 2169), 'time.time', 'time.time', ([], {}), '()\n', (2167, 2169), False, 'import time\n'), ((2307, 2318), 'time.time', 'time.time', ([], {}), '()\n', (2316, 2318), False, 'import time\n'), ((2510, 2521), 'time.time', 'time.time', ([], {}), '()\n', (2519, 2521), False, 'import time\n'), ((2672, 2702), 'Modules.ballDetection.findContours', 'findContours', (['final_image_copy'], {}), '(final_image_copy)\n', (2684, 2702), False, 'from Modules.ballDetection import findContours, sizeDetection, playerProximityDetection, regionDetection, courtBoundaryDetection\n'), ((2812, 2849), 'Modules.ballDetection.sizeDetection', 'sizeDetection', (['contours', 'currFrame', 'i'], {}), '(contours, currFrame, i)\n', (2825, 2849), False, 'from Modules.ballDetection import findContours, sizeDetection, playerProximityDetection, regionDetection, courtBoundaryDetection\n'), ((3204, 3304), 'Modules.ballDetection.playerProximityDetection', 'playerProximityDetection', (['ballCandidates', 'playerCadidates', 'incompletePlayerCandidates', 'currFrame'], {}), '(ballCandidates, playerCadidates,\n incompletePlayerCandidates, currFrame)\n', (3228, 3304), False, 'from Modules.ballDetection import findContours, sizeDetection, playerProximityDetection, regionDetection, courtBoundaryDetection\n'), ((3445, 3524), 'Modules.ballDetection.regionDetection', 'regionDetection', (['ballCandidatesFiltered', 'ballCandidatesPreviousFrame', 'currFrame'], {}), '(ballCandidatesFiltered, ballCandidatesPreviousFrame, currFrame)\n', (3460, 3524), False, 'from Modules.ballDetection import findContours, sizeDetection, playerProximityDetection, regionDetection, courtBoundaryDetection\n'), ((3555, 3566), 'time.time', 'time.time', ([], {}), '()\n', (3564, 3566), False, 'import time\n'), ((8842, 8856), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (8853, 8856), False, 'import cv2\n'), ((524, 547), 'Modules.foregroundExtraction.natural_sort', 'natural_sort', (['filenames'], {}), '(filenames)\n', (536, 547), False, 'from Modules.foregroundExtraction import readyFrame, frameDifferencing, morphologicalOperations, natural_sort\n'), ((3022, 3120), 'Modules.ballDetection.courtBoundaryDetection', 'courtBoundaryDetection', (['ballCandidates', 'playerCadidates', 'incompletePlayerCandidates', 'currFrame'], {}), '(ballCandidates, playerCadidates,\n incompletePlayerCandidates, currFrame)\n', (3044, 3120), False, 'from Modules.ballDetection import findContours, sizeDetection, playerProximityDetection, regionDetection, courtBoundaryDetection\n'), ((4014, 4072), 'cv2.circle', 'cv2.circle', (['currFrame', '(tp[0], tp[1])', '(10)', '(0, 0, 255)', '(-1)'], {}), '(currFrame, (tp[0], tp[1]), 10, (0, 0, 255), -1)\n', (4024, 4072), False, 'import cv2\n'), ((4289, 4347), 'cv2.circle', 'cv2.circle', (['currFrame', '(tp[0], tp[1])', '(10)', '(0, 0, 255)', '(-1)'], {}), '(currFrame, (tp[0], tp[1]), 10, (0, 0, 255), -1)\n', (4299, 4347), False, 'import cv2\n'), ((5147, 5219), 'cv2.circle', 'cv2.circle', (['currFrame', '(corrected[0], corrected[1])', '(10)', '(0, 255, 0)', '(-1)'], {}), '(currFrame, (corrected[0], corrected[1]), 10, (0, 255, 0), -1)\n', (5157, 5219), False, 'import cv2\n'), ((6124, 6179), 'cv2.drawContours', 'cv2.drawContours', (['currFrame', '[cand[3]]', '(-1)', '(255, 0)', '(2)'], {}), '(currFrame, [cand[3]], -1, (255, 0), 2)\n', (6140, 6179), False, 'import cv2\n'), ((6350, 6390), 'cv2.imshow', 'cv2.imshow', (['"""Candidate image"""', 'currFrame'], {}), "('Candidate image', currFrame)\n", (6360, 6390), False, 'import cv2\n'), ((8553, 8611), 'cv2.circle', 'cv2.circle', (['currFrame', '(tp[0], tp[1])', '(10)', '(0, 0, 255)', '(-1)'], {}), '(currFrame, (tp[0], tp[1]), 10, (0, 0, 255), -1)\n', (8563, 8611), False, 'import cv2\n'), ((8620, 8660), 'cv2.imshow', 'cv2.imshow', (['"""Candidate image"""', 'currFrame'], {}), "('Candidate image', currFrame)\n", (8630, 8660), False, 'import cv2\n'), ((3833, 3846), 'numpy.float32', 'np.float32', (['x'], {}), '(x)\n', (3843, 3846), True, 'import numpy as np\n'), ((3850, 3863), 'numpy.float32', 'np.float32', (['y'], {}), '(y)\n', (3860, 3863), True, 'import numpy as np\n'), ((8234, 8289), 'cv2.drawContours', 'cv2.drawContours', (['currFrame', '[cand[3]]', '(-1)', '(255, 0)', '(2)'], {}), '(currFrame, [cand[3]], -1, (255, 0), 2)\n', (8250, 8289), False, 'import cv2\n'), ((8462, 8502), 'cv2.imshow', 'cv2.imshow', (['"""Candidate image"""', 'currFrame'], {}), "('Candidate image', currFrame)\n", (8472, 8502), False, 'import cv2\n'), ((5426, 5454), 'math.pow', 'math.pow', (['(cand[0] - tp[0])', '(2)'], {}), '(cand[0] - tp[0], 2)\n', (5434, 5454), False, 'import math\n'), ((5459, 5487), 'math.pow', 'math.pow', (['(cand[1] - tp[1])', '(2)'], {}), '(cand[1] - tp[1], 2)\n', (5467, 5487), False, 'import math\n'), ((4751, 4764), 'numpy.float32', 'np.float32', (['x'], {}), '(x)\n', (4761, 4764), True, 'import numpy as np\n'), ((4768, 4781), 'numpy.float32', 'np.float32', (['y'], {}), '(y)\n', (4778, 4781), True, 'import numpy as np\n'), ((6706, 6734), 'math.pow', 'math.pow', (['(cand[0] - tp[0])', '(2)'], {}), '(cand[0] - tp[0], 2)\n', (6714, 6734), False, 'import math\n'), ((6739, 6767), 'math.pow', 'math.pow', (['(cand[1] - tp[1])', '(2)'], {}), '(cand[1] - tp[1], 2)\n', (6747, 6767), False, 'import math\n')]
from mushroom_rl.core import Serializable import torch import numpy as np from mushroom_rl.utils.parameters import Parameter class TestClass(Serializable): def __init__(self, value): # Create some different types of variables self._primitive_variable = value # Primitive python variable self._numpy_vector = np.array([1, 2, 3]*value) # Numpy array self._dictionary = dict(some='random', keywords=2, fill='the dictionary') # A dictionary # Building a torch object data_array = np.ones(3)*value data_tensor = torch.from_numpy(data_array) self._torch_object = torch.nn.Parameter(data_tensor) # Some variables that implement the Serializable interface self._mushroom_parameter = Parameter(2.0*value) self._list_of_objects = [Parameter(i) for i in range(value)] # This is a list! # A variable that is not important e.g. a buffer self.not_important = np.zeros(10000) # A variable that contains a reference to another variable self._list_reference = [self._dictionary] # Superclass constructor super().__init__() # Here we specify how to save each component self._add_save_attr( _primitive_variable='primitive', _numpy_vector='numpy', _dictionary='pickle', _torch_object='torch', _mushroom_parameter='mushroom', # List of mushroom objects can also be saved with the 'mushroom' mode _list_of_objects='mushroom', # The '!' is to specify that we save the variable only if full_save is True not_important='numpy!', ) def _post_load(self): if self.not_important is None: self.not_important = np.zeros(10000) self._list_reference = [self._dictionary] def print_variables(obj): for label, var in vars(obj).items(): if label != '_save_attributes': if isinstance(var, Parameter): print(f'{label}: Parameter({var()})') elif isinstance(var, list) and isinstance(var[0], Parameter): new_list = [f'Parameter({item()})' for item in var] print(f'{label}: {new_list}') else: print(label, ': ', var) if __name__ == '__main__': # Create test object and print its variables test_object = TestClass(1) print('###########################################################################################################') print('The test object contains the following:') print('-----------------------------------------------------------------------------------------------------------') print_variables(test_object) # Changing the buffer test_object.not_important[0] = 1 # Save the object on disk test_object.save('test.msh') # Create another test object test_object = TestClass(2) print('###########################################################################################################') print('After overwriting the test object:') print('-----------------------------------------------------------------------------------------------------------') print_variables(test_object) # Changing the buffer again test_object.not_important[0] = 1 # Save the other test object, this time remember buffer test_object.save('test_full.msh', full_save=True) # Load first test object and print its variables print('###########################################################################################################') test_object = TestClass.load('test.msh') print('Loading previous test object:') print('-----------------------------------------------------------------------------------------------------------') print_variables(test_object) # Load second test object and print its variables print('###########################################################################################################') test_object = TestClass.load('test_full.msh') print('Loading previous test object:') print('-----------------------------------------------------------------------------------------------------------') print_variables(test_object)
[ "torch.nn.Parameter", "mushroom_rl.utils.parameters.Parameter", "numpy.zeros", "numpy.ones", "numpy.array", "torch.from_numpy" ]
[((341, 368), 'numpy.array', 'np.array', (['([1, 2, 3] * value)'], {}), '([1, 2, 3] * value)\n', (349, 368), True, 'import numpy as np\n'), ((575, 603), 'torch.from_numpy', 'torch.from_numpy', (['data_array'], {}), '(data_array)\n', (591, 603), False, 'import torch\n'), ((633, 664), 'torch.nn.Parameter', 'torch.nn.Parameter', (['data_tensor'], {}), '(data_tensor)\n', (651, 664), False, 'import torch\n'), ((768, 790), 'mushroom_rl.utils.parameters.Parameter', 'Parameter', (['(2.0 * value)'], {}), '(2.0 * value)\n', (777, 790), False, 'from mushroom_rl.utils.parameters import Parameter\n'), ((964, 979), 'numpy.zeros', 'np.zeros', (['(10000)'], {}), '(10000)\n', (972, 979), True, 'import numpy as np\n'), ((536, 546), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (543, 546), True, 'import numpy as np\n'), ((822, 834), 'mushroom_rl.utils.parameters.Parameter', 'Parameter', (['i'], {}), '(i)\n', (831, 834), False, 'from mushroom_rl.utils.parameters import Parameter\n'), ((1791, 1806), 'numpy.zeros', 'np.zeros', (['(10000)'], {}), '(10000)\n', (1799, 1806), True, 'import numpy as np\n')]
from __future__ import division, print_function from unittest import TestCase import numpy as np from scipy.signal import fftconvolve import pyroomacoustics as pra ''' We create a signal, a simple filter and compute their convolution. Then we test STFT block procesing with and without overlap, and with and without filtering. ''' # test parameters tol = 1e-6 np.random.seed(0) D = 4 transform = 'numpy' # 'numpy', 'pyfftw', or 'mkl' # filter to apply h_len = 99 h = np.ones((h_len, D)) h /= np.linalg.norm(h, axis=0) # test signal (noise) x = np.random.randn(100000, D) # convolved signal y = np.zeros((x.shape[0] + h_len - 1, x.shape[1])) for i in range(x.shape[1]): y[:,i] = fftconvolve(x[:,i], h[:,i]) def no_overlap_no_filter(D): if D == 1: x_local = x[:,0] else: x_local = x[:,:D] # parameters block_size = 512 # make sure the FFT size is a power of 2 hop = block_size # no overlap # Create the STFT object stft = pra.realtime.STFT(block_size, hop=hop, channels=D, transform=transform) # collect the processed blocks processed_x = np.zeros(x_local.shape) # process the signals while full blocks are available n = 0 while x_local.shape[0] - n > hop: # go to frequency domain stft.analysis(x_local[n:n+hop,]) # copy processed block in the output buffer processed_x[n:n+hop,] = stft.synthesis() n += hop error = np.max(np.abs(x_local[:n,] - processed_x[:n,])) return error def no_overlap_with_filter(D): if D == 1: x_local = x[:,0] y_local = y[:,0] h_local = h[:,0] else: x_local = x[:,:D] y_local = y[:,:D] h_local = h[:,:D] # parameters block_size = 512 - h_len + 1 # make sure the FFT size is a power of 2 hop = block_size # no overlap # Create the STFT object stft = pra.realtime.STFT(block_size, hop=hop, channels=D, transform=transform) # setup the filter stft.set_filter(h_local, zb=h_len - 1) # collect the processed blocks processed_x = np.zeros(x_local.shape) # process the signals while full blocks are available n = 0 while x_local.shape[0] - n > hop: # go to frequency domain stft.analysis(x_local[n:n+hop,]) stft.process() # apply the filter # copy processed block in the output buffer processed_x[n:n+hop,] = stft.synthesis() n += hop error = np.max(np.abs(y_local[:n,] - processed_x[:n,])) return error def with_half_overlap_no_filter(D): if D == 1: x_local = x[:,0] else: x_local = x[:,:D] # parameters block_size = 512 # make sure the FFT size is a power of 2 hop = block_size // 2 # half overlap window = pra.hann(block_size) # the analysis window # Create the STFT object stft = pra.realtime.STFT(block_size, hop=hop, analysis_window=window, channels=D, transform=transform) # collect the processed blocks processed_x = np.zeros(x_local.shape) # process the signals while full blocks are available n = 0 while x_local.shape[0] - n > hop: # go to frequency domain stft.analysis(x_local[n:n+hop,]) # copy processed block in the output buffer processed_x[n:n+hop,] = stft.synthesis() n += hop error = np.max(np.abs(x_local[:n-hop,] - processed_x[hop:n,])) return error def with_half_overlap_with_filter(D): if D == 1: x_local = x[:,0] y_local = y[:,0] h_local = h[:,0] else: x_local = x[:,:D] y_local = y[:,:D] h_local = h[:,:D] # parameters block_size = 512 - h_len + 1 # make sure the FFT size is a power of 2 hop = block_size // 2 # half overlap window = pra.hann(block_size) # the analysis window # Create the STFT object stft = pra.realtime.STFT(block_size, hop=hop, analysis_window=window, channels=D, transform=transform) # setup the filter stft.set_filter(h_local, zb=h_len - 1) # collect the processed blocks processed_x = np.zeros(x_local.shape) # process the signals while full blocks are available n = 0 while x.shape[0] - n > hop: # go to frequency domain stft.analysis(x_local[n:n+hop,]) stft.process() # filtering # copy processed block in the output buffer processed_x[n:n+hop,] = stft.synthesis() n += hop error = np.max(np.abs(y_local[:n-hop,] - processed_x[hop:n,])) return error class TestSTFT(TestCase): def test_no_overlap_no_filter_mono(self): error = no_overlap_no_filter(1) self.assertTrue(error < tol) def test_no_overlap_no_filter_multichannel(self): error = no_overlap_no_filter(D) self.assertTrue(error < tol) def test_no_overlap_with_filter_mono(self): error = no_overlap_with_filter(1) self.assertTrue(error < tol) def test_no_overlap_with_filter_multichannel(self): error = no_overlap_with_filter(D) self.assertTrue(error < tol) def test_with_half_overlap_no_filter_mono(self): error = with_half_overlap_no_filter(1) self.assertTrue(error < tol) def test_with_half_overlap_no_filter_multichannel(self): error = with_half_overlap_no_filter(D) self.assertTrue(error < tol) def test_with_half_overlap_with_filter_mono(self): error = with_half_overlap_with_filter(1) self.assertTrue(error < tol) def test_with_half_overlap_with_filter_multichannel(self): error = with_half_overlap_with_filter(D) self.assertTrue(error < tol) if __name__ == "__main__": error = no_overlap_no_filter(1) print('no overlap, no filter, mono:', error) error = no_overlap_no_filter(D) print('no overlap, no filter, multichannel:', error) error = no_overlap_with_filter(1) print('no overlap, with filter, mono:', error) error = no_overlap_with_filter(D) print('no overlap, with filter, multichannel:', error) error = with_half_overlap_no_filter(1) print('with half overlap, no filter, mono:', error) error = with_half_overlap_no_filter(D) print('with half overlap, no filter, multichannel:', error) error = with_half_overlap_with_filter(1) print('with half overlap, with filter, mono:', error) error = with_half_overlap_with_filter(D) print('with half overlap, with filter, multichannel:', error)
[ "numpy.random.seed", "pyroomacoustics.realtime.STFT", "numpy.abs", "numpy.random.randn", "numpy.zeros", "numpy.ones", "numpy.linalg.norm", "scipy.signal.fftconvolve", "pyroomacoustics.hann" ]
[((364, 381), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (378, 381), True, 'import numpy as np\n'), ((474, 493), 'numpy.ones', 'np.ones', (['(h_len, D)'], {}), '((h_len, D))\n', (481, 493), True, 'import numpy as np\n'), ((499, 524), 'numpy.linalg.norm', 'np.linalg.norm', (['h'], {'axis': '(0)'}), '(h, axis=0)\n', (513, 524), True, 'import numpy as np\n'), ((552, 578), 'numpy.random.randn', 'np.random.randn', (['(100000)', 'D'], {}), '(100000, D)\n', (567, 578), True, 'import numpy as np\n'), ((603, 649), 'numpy.zeros', 'np.zeros', (['(x.shape[0] + h_len - 1, x.shape[1])'], {}), '((x.shape[0] + h_len - 1, x.shape[1]))\n', (611, 649), True, 'import numpy as np\n'), ((691, 720), 'scipy.signal.fftconvolve', 'fftconvolve', (['x[:, i]', 'h[:, i]'], {}), '(x[:, i], h[:, i])\n', (702, 720), False, 'from scipy.signal import fftconvolve\n'), ((983, 1054), 'pyroomacoustics.realtime.STFT', 'pra.realtime.STFT', (['block_size'], {'hop': 'hop', 'channels': 'D', 'transform': 'transform'}), '(block_size, hop=hop, channels=D, transform=transform)\n', (1000, 1054), True, 'import pyroomacoustics as pra\n'), ((1118, 1141), 'numpy.zeros', 'np.zeros', (['x_local.shape'], {}), '(x_local.shape)\n', (1126, 1141), True, 'import numpy as np\n'), ((1904, 1975), 'pyroomacoustics.realtime.STFT', 'pra.realtime.STFT', (['block_size'], {'hop': 'hop', 'channels': 'D', 'transform': 'transform'}), '(block_size, hop=hop, channels=D, transform=transform)\n', (1921, 1975), True, 'import pyroomacoustics as pra\n'), ((2110, 2133), 'numpy.zeros', 'np.zeros', (['x_local.shape'], {}), '(x_local.shape)\n', (2118, 2133), True, 'import numpy as np\n'), ((2810, 2830), 'pyroomacoustics.hann', 'pra.hann', (['block_size'], {}), '(block_size)\n', (2818, 2830), True, 'import pyroomacoustics as pra\n'), ((2895, 2994), 'pyroomacoustics.realtime.STFT', 'pra.realtime.STFT', (['block_size'], {'hop': 'hop', 'analysis_window': 'window', 'channels': 'D', 'transform': 'transform'}), '(block_size, hop=hop, analysis_window=window, channels=D,\n transform=transform)\n', (2912, 2994), True, 'import pyroomacoustics as pra\n'), ((3054, 3077), 'numpy.zeros', 'np.zeros', (['x_local.shape'], {}), '(x_local.shape)\n', (3062, 3077), True, 'import numpy as np\n'), ((3833, 3853), 'pyroomacoustics.hann', 'pra.hann', (['block_size'], {}), '(block_size)\n', (3841, 3853), True, 'import pyroomacoustics as pra\n'), ((3918, 4017), 'pyroomacoustics.realtime.STFT', 'pra.realtime.STFT', (['block_size'], {'hop': 'hop', 'analysis_window': 'window', 'channels': 'D', 'transform': 'transform'}), '(block_size, hop=hop, analysis_window=window, channels=D,\n transform=transform)\n', (3935, 4017), True, 'import pyroomacoustics as pra\n'), ((4144, 4167), 'numpy.zeros', 'np.zeros', (['x_local.shape'], {}), '(x_local.shape)\n', (4152, 4167), True, 'import numpy as np\n'), ((1465, 1504), 'numpy.abs', 'np.abs', (['(x_local[:n,] - processed_x[:n,])'], {}), '(x_local[:n,] - processed_x[:n,])\n', (1471, 1504), True, 'import numpy as np\n'), ((2501, 2540), 'numpy.abs', 'np.abs', (['(y_local[:n,] - processed_x[:n,])'], {}), '(y_local[:n,] - processed_x[:n,])\n', (2507, 2540), True, 'import numpy as np\n'), ((3401, 3449), 'numpy.abs', 'np.abs', (['(x_local[:n - hop,] - processed_x[hop:n,])'], {}), '(x_local[:n - hop,] - processed_x[hop:n,])\n', (3407, 3449), True, 'import numpy as np\n'), ((4522, 4570), 'numpy.abs', 'np.abs', (['(y_local[:n - hop,] - processed_x[hop:n,])'], {}), '(y_local[:n - hop,] - processed_x[hop:n,])\n', (4528, 4570), True, 'import numpy as np\n')]
import sys from matplotlib import path import numpy as np #======================================================================================================= class RTStructFile: def __init__(self,RTS): self.Status = True self.DCM = RTS self.ROINameList = list() self.ROIIDList = list() for ROI in self.DCM.StructureSetROISequence: self.ROINameList.append(ROI.ROIName) self.ROIIDList.append(ROI.ROINumber) #-------------------------------------------------------------------------------------------------------------------------- def DefineROI(self,thisROIID,X0,DirectionX,Y0,DirectionY,Z0,DirectionZ,PixelSpacing,SliceSpacing): self.Margin = 10 self.i_Start = 'none' self.j_Start = 'none' self.k_Start = 'none' self.Nb_i = 'none' self.Nb_j = 'none' self.Nb_k = 'none' self.GetROIProperties(thisROIID,X0,DirectionX,Y0,DirectionY,Z0,DirectionZ,PixelSpacing,SliceSpacing) self.ROIVoxelsIndexCoords = list() #liste des index de toutes les voxels de la ROI ([i,j,k],[i,j,k], ... ) self.ROIContourDicomCoords = list() #liste des coord dicom du contour de la ROI ([x1,y1,z1],[x2,y2,z2],......) self.GetROIVoxelsIndexCoords(thisROIID,X0,DirectionX,Y0,DirectionY,Z0,DirectionZ,PixelSpacing,SliceSpacing,final=0) #-------------------------------------------------------------------------------------------------------------------------- def DefineFinalROI(self,thisROIID,X0,DirectionX,Y0,DirectionY,Z0,DirectionZ,PixelSpacing,SliceSpacing): self.Margin = 10 self.i_Start = 'none' self.j_Start = 'none' self.k_Start = 'none' self.Nb_i = 'none' self.Nb_j = 'none' self.Nb_k = 'none' self.GetROIProperties(thisROIID,X0,DirectionX,Y0,DirectionY,Z0,DirectionZ,PixelSpacing,SliceSpacing) self.ROIVoxelsIndexCoords = list() #liste des index de toutes les voxels de la ROI ([i,j,k],[i,j,k], ... ) self.ROIContourDicomCoords = list() #liste des coord dicom du contour de la ROI ([x1,y1,z1],[x2,y2,z2],......) self.GetROIVoxelsIndexCoords(thisROIID,X0,DirectionX,Y0,DirectionY,Z0,DirectionZ,PixelSpacing,SliceSpacing,final=1) #----------------------------------------------------------------------------------------------------------------------------------- def GetROIProperties(self,thisROIID,X0,DirectionX,Y0,DirectionY,Z0,DirectionZ,PixelSpacing,SliceSpacing): #the main goal of this function is to determine the limits of the coordinates of the ROIs. self.i_list = list() #Index Coords grille Image dataset self.j_list = list() self.k_list = list() for ROI in self.DCM.ROIContourSequence: if int(ROI.ReferencedROINumber) == int(thisROIID): for contour in ROI.ContourSequence: for p in range(0,contour.NumberofContourPoints): x=contour.ContourData[3*p] #Dicom coordinates y=contour.ContourData[3*p+1] z=contour.ContourData[3*p+2] i = np.int(np.rint(((x-X0)/(DirectionX*PixelSpacing)))) #Index coordinates j = np.int(np.rint(((y-Y0)/(DirectionY*PixelSpacing)))) k = np.int(np.rint(((z-Z0)/(DirectionZ*SliceSpacing)))) self.i_list.append(i) self.j_list.append(j) self.k_list.append(k) imin = np.min(self.i_list) jmin = np.min(self.j_list) kmin = np.min(self.k_list) imax = np.max(self.i_list) jmax = np.max(self.j_list) kmax = np.max(self.k_list) self.k_Start = kmin - self.Margin self.k_Stop = kmax + self.Margin self.Nb_k = (self.k_Stop-self.k_Start)+1 self.j_Start = jmin - self.Margin self.j_Stop = jmax + self.Margin self.Nb_j = (self.j_Stop-self.j_Start)+1 self.i_Start = imin - self.Margin self.i_Stop = imax + self.Margin self.Nb_i = (self.i_Stop-self.i_Start)+1 #--------------------------------------------------------------------------------------------------------------------------------------- def GetROIVoxelsIndexCoords(self,thisROIID,X0,DirectionX,Y0,DirectionY,Z0,DirectionZ,PixelSpacing,SliceSpacing,final): for ROI in self.DCM.ROIContourSequence: if int(ROI.ReferencedROINumber) == int(thisROIID): for contour in ROI.ContourSequence: #Find k indice thisz = contour.ContourData[2] k = np.int(np.rint(((thisz-Z0)/(DirectionZ*SliceSpacing)))) thisPath = list() for p in range(0,contour.NumberofContourPoints): x=contour.ContourData[3*p] y=contour.ContourData[3*p+1] z=contour.ContourData[3*p+2] i = np.int(np.rint(((x-X0)/(DirectionX*PixelSpacing)))) j = np.int(np.rint(((y-Y0)/(DirectionY*PixelSpacing)))) thisPath.append([i,j]) self.ROIContourDicomCoords.append([x,y,z]) if final==1: thisPath = path.Path(thisPath) for j in range(self.j_Start,self.j_Stop): for i in range(self.i_Start,self.i_Stop): if thisPath.contains_point([i,j],radius=0.01)== 1: self.ROIVoxelsIndexCoords.append([i,j,k])
[ "matplotlib.path.Path", "numpy.min", "numpy.max", "numpy.rint" ]
[((3162, 3181), 'numpy.min', 'np.min', (['self.i_list'], {}), '(self.i_list)\n', (3168, 3181), True, 'import numpy as np\n'), ((3191, 3210), 'numpy.min', 'np.min', (['self.j_list'], {}), '(self.j_list)\n', (3197, 3210), True, 'import numpy as np\n'), ((3220, 3239), 'numpy.min', 'np.min', (['self.k_list'], {}), '(self.k_list)\n', (3226, 3239), True, 'import numpy as np\n'), ((3252, 3271), 'numpy.max', 'np.max', (['self.i_list'], {}), '(self.i_list)\n', (3258, 3271), True, 'import numpy as np\n'), ((3281, 3300), 'numpy.max', 'np.max', (['self.j_list'], {}), '(self.j_list)\n', (3287, 3300), True, 'import numpy as np\n'), ((3310, 3329), 'numpy.max', 'np.max', (['self.k_list'], {}), '(self.k_list)\n', (3316, 3329), True, 'import numpy as np\n'), ((4166, 4217), 'numpy.rint', 'np.rint', (['((thisz - Z0) / (DirectionZ * SliceSpacing))'], {}), '((thisz - Z0) / (DirectionZ * SliceSpacing))\n', (4173, 4217), True, 'import numpy as np\n'), ((4658, 4677), 'matplotlib.path.Path', 'path.Path', (['thisPath'], {}), '(thisPath)\n', (4667, 4677), False, 'from matplotlib import path\n'), ((2877, 2924), 'numpy.rint', 'np.rint', (['((x - X0) / (DirectionX * PixelSpacing))'], {}), '((x - X0) / (DirectionX * PixelSpacing))\n', (2884, 2924), True, 'import numpy as np\n'), ((2958, 3005), 'numpy.rint', 'np.rint', (['((y - Y0) / (DirectionY * PixelSpacing))'], {}), '((y - Y0) / (DirectionY * PixelSpacing))\n', (2965, 3005), True, 'import numpy as np\n'), ((3020, 3067), 'numpy.rint', 'np.rint', (['((z - Z0) / (DirectionZ * SliceSpacing))'], {}), '((z - Z0) / (DirectionZ * SliceSpacing))\n', (3027, 3067), True, 'import numpy as np\n'), ((4425, 4472), 'numpy.rint', 'np.rint', (['((x - X0) / (DirectionX * PixelSpacing))'], {}), '((x - X0) / (DirectionX * PixelSpacing))\n', (4432, 4472), True, 'import numpy as np\n'), ((4487, 4534), 'numpy.rint', 'np.rint', (['((y - Y0) / (DirectionY * PixelSpacing))'], {}), '((y - Y0) / (DirectionY * PixelSpacing))\n', (4494, 4534), True, 'import numpy as np\n')]
import wave import pylab as pl import numpy as np import speech_features_kit.Volume.Volume as vp # ============ test the algorithm ============= # read wave file and get parameters. fw = wave.open('../data/english.wav','rb') params = fw.getparams() print(params) nchannels, sampwidth, framerate, nframes = params[:4] strData = fw.readframes(nframes) waveData = np.fromstring(strData, dtype=np.int16) waveData = waveData*1.0/max(abs(waveData)) # normalization fw.close() # calculate volume frameSize = 256 overLap = 128 volume11 = vp.calVolume(waveData,frameSize,overLap) volume12 = vp.calVolumeDB(waveData,frameSize,overLap) # plot the wave time = np.arange(0, nframes)*(1.0/framerate) time2 = np.arange(0, len(volume11))*(frameSize-overLap)*1.0/framerate pl.subplot(311) pl.plot(time, waveData) pl.ylabel("Amplitude") pl.subplot(312) pl.plot(time2, volume11) pl.ylabel("absSum") pl.subplot(313) pl.plot(time2, volume12, c="g") pl.ylabel("Decibel(dB)") pl.xlabel("time (seconds)") pl.show()
[ "wave.open", "speech_features_kit.Volume.Volume.calVolumeDB", "pylab.show", "pylab.ylabel", "speech_features_kit.Volume.Volume.calVolume", "pylab.plot", "pylab.subplot", "numpy.arange", "pylab.xlabel", "numpy.fromstring" ]
[((188, 226), 'wave.open', 'wave.open', (['"""../data/english.wav"""', '"""rb"""'], {}), "('../data/english.wav', 'rb')\n", (197, 226), False, 'import wave\n'), ((362, 400), 'numpy.fromstring', 'np.fromstring', (['strData'], {'dtype': 'np.int16'}), '(strData, dtype=np.int16)\n', (375, 400), True, 'import numpy as np\n'), ((533, 575), 'speech_features_kit.Volume.Volume.calVolume', 'vp.calVolume', (['waveData', 'frameSize', 'overLap'], {}), '(waveData, frameSize, overLap)\n', (545, 575), True, 'import speech_features_kit.Volume.Volume as vp\n'), ((585, 629), 'speech_features_kit.Volume.Volume.calVolumeDB', 'vp.calVolumeDB', (['waveData', 'frameSize', 'overLap'], {}), '(waveData, frameSize, overLap)\n', (599, 629), True, 'import speech_features_kit.Volume.Volume as vp\n'), ((760, 775), 'pylab.subplot', 'pl.subplot', (['(311)'], {}), '(311)\n', (770, 775), True, 'import pylab as pl\n'), ((776, 799), 'pylab.plot', 'pl.plot', (['time', 'waveData'], {}), '(time, waveData)\n', (783, 799), True, 'import pylab as pl\n'), ((800, 822), 'pylab.ylabel', 'pl.ylabel', (['"""Amplitude"""'], {}), "('Amplitude')\n", (809, 822), True, 'import pylab as pl\n'), ((824, 839), 'pylab.subplot', 'pl.subplot', (['(312)'], {}), '(312)\n', (834, 839), True, 'import pylab as pl\n'), ((840, 864), 'pylab.plot', 'pl.plot', (['time2', 'volume11'], {}), '(time2, volume11)\n', (847, 864), True, 'import pylab as pl\n'), ((865, 884), 'pylab.ylabel', 'pl.ylabel', (['"""absSum"""'], {}), "('absSum')\n", (874, 884), True, 'import pylab as pl\n'), ((886, 901), 'pylab.subplot', 'pl.subplot', (['(313)'], {}), '(313)\n', (896, 901), True, 'import pylab as pl\n'), ((902, 933), 'pylab.plot', 'pl.plot', (['time2', 'volume12'], {'c': '"""g"""'}), "(time2, volume12, c='g')\n", (909, 933), True, 'import pylab as pl\n'), ((934, 958), 'pylab.ylabel', 'pl.ylabel', (['"""Decibel(dB)"""'], {}), "('Decibel(dB)')\n", (943, 958), True, 'import pylab as pl\n'), ((959, 986), 'pylab.xlabel', 'pl.xlabel', (['"""time (seconds)"""'], {}), "('time (seconds)')\n", (968, 986), True, 'import pylab as pl\n'), ((987, 996), 'pylab.show', 'pl.show', ([], {}), '()\n', (994, 996), True, 'import pylab as pl\n'), ((652, 673), 'numpy.arange', 'np.arange', (['(0)', 'nframes'], {}), '(0, nframes)\n', (661, 673), True, 'import numpy as np\n')]
import numpy as np import datetime as dt import struct from dateutil.relativedelta import relativedelta from netCDF4 import Dataset from os.path import exists from scipy.interpolate import griddata from scipy.interpolate.interpnd import _ndim_coords_from_arrays from scipy.spatial import cKDTree class Pathfinder(): """ forcing class for the budget lets the forcing load efficiently """ def __init__(self,ppath,grid=False): self.name = 'Pathfinder' self.path = ppath self.vyear_load = 0 self.vels_loaded = False if type(grid) == bool: self.check_grid = False else: self.check_grid = True self.grid = grid def get_dates(self,time_start,time_end): """ returns the all encompassing date list for use with the forcing object """ dates =[] d0 = dt.datetime(1970,1,1) n_yrs = (time_end.year - time_start.year)+1 for y in range(n_yrs): yu = time_start.year + y f_name = 'icemotion_daily_nh_25km_'+str(yu)+'0101_'+str(yu)+'1231_v4.1.nc' if exists(self.path+f_name): f_nc = Dataset(self.path+f_name) [dates.append(d0 + relativedelta(days = d)) for d in f_nc['time'][:]] f_nc.close() self.dates = dates print(self.name+' Found '+str(np.shape(dates)[0])+' dates') # daily points in yearly files # next function will take a list of dates and return an appropriately orientated arrays # give a def get_vels(self,dates_u,verbos=False): d0 = dt.datetime(1970,1,1) # does dates_u cover one year or more if (dates_u[-1].year -dates_u[0].year) == 0: # one year, one file yu = dates_u[0].year if ((self.vyear_load != yu) or (not self.vels_loaded)): print('loading new year of data: '+str(yu)) f_name = 'icemotion_daily_nh_25km_'+str(yu)+'0101_'+str(yu)+'1231_v4.1.nc' f_nc = Dataset(self.path+f_name) # print(p0,p1) self.u = f_nc['u'][:] self.v = f_nc['v'][:] self.u[self.u.mask] = np.nan self.v[self.v.mask] = np.nan f_nc.close() self.vyear_load = yu self.vels_loaded= True p0 = dates_u[ 0].timetuple().tm_yday -1 p1 = dates_u[-1].timetuple().tm_yday datau = self.u[p0:p1,:,:].transpose((0,2,1))/100 datav = self.v[p0:p1,:,:].transpose((0,2,1))/100 if self.check_grid: for n in range(np.shape(datau)[0]): datau[n][self.grid.lats>88] = np.nanmean datav[n][self.grid.lats>88] = np.nanmean return datau,datav class PIOMAS(): """ forcing class for the budget lets the forcing load efficiently """ def __init__(self,ppath,time_smooth = 0): self.name = 'PIOMAS' self.path = ppath self.vyear_load = 0 self.hyear_load = 0 self.ayear_load = 0 self.vels_loaded = False self.hi_loaded = False self.aice_loaded = False self.tsmth = time_smooth def get_dates(self,time_start,time_end): """ returns the all encompassing date list for use with the forcing object PIOMAS is a standardised list so we can just build a list """ dates =[] n_yrs = (time_end.year - time_start.year)-1 if n_yrs>-1: y0 = dt.datetime(time_start.year,1,1) ye = dt.datetime(time_start.year,12,31) data_f = self.path+'uiday.H'+y0.strftime('%Y') if exists(data_f): for d in range(time_start.timetuple().tm_yday-1, ye.timetuple().tm_yday): dates.append(y0 + relativedelta(days = d)) for y in range(n_yrs): y0 += relativedelta(years=1) ye += relativedelta(years=1) data_f = self.path+'uiday.H'+y0.strftime('%Y') if exists(data_f): for d in range(ye.timetuple().tm_yday): dates.append(y0 + relativedelta(days = d)) y0 += relativedelta(years=1) ye = time_end data_f = self.path+'uiday.H'+y0.strftime('%Y') if exists(data_f): for d in range(ye.timetuple().tm_yday): dates.append(y0 + relativedelta(days = d)) else: y0 = dt.datetime(time_start.year,1,1) data_f = self.path+'uiday.H'+y0.strftime('%Y') if exists(data_f): for d in range(time_start.timetuple().tm_yday-1, time_end.timetuple().tm_yday): dates.append(y0 + relativedelta(days = d)) self.dates= dates print(self.name+' Found '+str(np.shape(dates)[0])+' dates') # daily points in yearly files # next function will take a list of dates and return an appropriately orientated arrays # give a def get_vels(self,dates_u,verbos=False): # does dates_u cover one year or more if (dates_u[-1].year -dates_u[0].year) == 0: # one year, one file yu = dates_u[0].year if ((self.vyear_load != yu) or (not self.vels_loaded)): print('loading new year of data: '+str(yu)) data_f = self.path+'uiday.H'+str(yu) with open(data_f, mode='rb') as file: filecontent = file.read() data = struct.unpack("f" * (len(filecontent)// 4), filecontent) self.vels=np.asarray(data).reshape(365,2,120,360) self.vyear_load = yu self.vels_loaded= True p0 = dates_u[ 0].timetuple().tm_yday -1 p1 = dates_u[-1].timetuple().tm_yday # print(p0,p1) if self.tsmth < 1: datau = self.vels[p0:p1,0,:,:].transpose((0,2,1)) datav = self.vels[p0:p1,1,:,:].transpose((0,2,1)) return datau,datav elif np.shape(dates_u)[0]>1: print('time smoothing not compatible with multiple dates') datau = self.vels[p0:p1,0,:,:].transpose((0,2,1)) datav = self.vels[p0:p1,1,:,:].transpose((0,2,1)) return datau,datav else: #### each time slice is the mean of 2*tsmth+1 p0 = np.maximum(p0-self.tsmth,0) datau = self.vels[p0:p1+self.tsmth,0,:,:].transpose((0,2,1)) datav = self.vels[p0:p1+self.tsmth,1,:,:].transpose((0,2,1)) # print(np.shape(datau)) datau2 = np.expand_dims(np.nanmean(datau,axis=0),0) datav2 = np.expand_dims(np.nanmean(datav,axis=0),0) return datau2,datav2 def get_hi(self,dates_u,verbos=False): # does dates_u cover one year or more if (dates_u[-1].year -dates_u[0].year) == 0: # one year, one file yu = dates_u[0].year if ((self.hyear_load != yu) or (not self.hi_loaded)): print('loading new year of data: '+str(yu)) data_f = self.path+'hiday.H'+str(yu) with open(data_f, mode='rb') as file: fileContent = file.read() data = struct.unpack("f" * (len(fileContent)// 4), fileContent) self.hi=np.asarray(data).reshape(365,120,360) self.hyear_load = yu self.hi_loaded = True p0 = dates_u[ 0].timetuple().tm_yday -1 p1 = dates_u[-1].timetuple().tm_yday # print(p0,p1) if self.tsmth < 1: data = self.hi[p0:p1,:,:].transpose((0,2,1)) return data elif np.shape(dates_u)[0]>1: print('Time smoothing not compatible with multiple dates') data = self.hi[p0:p1,:,:].transpose((0,2,1)) return data else: #### each time slice is the mean of 2*tsmth+1 p0 = np.maximum(p0-self.tsmth,0) data = self.hi[p0:p1+self.tsmth,0,:,:].transpose((0,2,1)) data2 = np.expand_dims(np.nanmean(data,axis=0),0) return data2 def get_aice(self,dates_u,verbos=False): # does dates_u cover one year or more if (dates_u[-1].year -dates_u[0].year) == 0: # one year, one file yu = dates_u[0].year if ((self.ayear_load != yu) or (not self.aice_loaded)): print('loading new year of data: '+str(yu)) data_f = self.path+'aiday.H'+str(yu) with open(data_f, mode='rb') as file: fileContent = file.read() data = struct.unpack("f" * (len(fileContent)// 4), fileContent) self.aice=np.asarray(data).reshape(365,120,360) self.ayear_load = yu self.aice_loaded= True p0 = dates_u[ 0].timetuple().tm_yday -1 p1 = dates_u[-1].timetuple().tm_yday # print(p0,p1) if self.tsmth < 1: data = self.aice[p0:p1,:,:].transpose((0,2,1)) return data elif np.shape(dates_u)[0]>1: print('Time smoothing not compatible with multiple dates') data = self.aice[p0:p1,:,:].transpose((0,2,1)) return data else: #### each time slice is the mean of 2*tsmth+1 p0 = np.maximum(p0-self.tsmth,0) data = self.aice[p0:p1+self.tsmth,0,:,:].transpose((0,2,1)) data2 = np.expand_dims(np.nanmean(data,axis=0),0) return data2 class NSIDC_nt(): """ forcing class for the budget lets the forcing load efficiently """ def __init__(self,ppath): self.name = 'NSIDC_n' self.path = ppath # next function will take a list of dates and return an appropriately orientated arrays # give a def get_aice(self,dates_u,verbos=False): # does dates_u cover one year or more #daily files dimY = 304 dimX = 448 d_no = np.shape(dates_u)[0] data = np.empty([d_no, dimX, dimY]) for n,d in enumerate(dates_u): # infile = self.path+d.strftime('/%Y/')+"nt_"+d.strftime('%Y%m%d')+"_f17_v1.1_n.bin" if d.year<2020: # infile = self.path+"/nt_"+d.strftime('%Y%m%d')+"_f17_v1.1_n.bin" infile = self.path+d.strftime('/%Y/')+"nt_"+d.strftime('%Y%m%d')+"_f17_v1.1_n.bin" if d.year>2019: # infile = self.path+"/nt_"+d.strftime('%Y%m%d')+"_f18_nrt_n.bin" infile = self.path+d.strftime('/%Y/')+"nt_"+d.strftime('%Y%m%d')+"_f18_nrt_n.bin" # if d.year<2019: # infile = self.path+"nt_"+d.strftime('%Y%m%d')+"_f17_v1.1_n.bin" # if d.year>2018: # infile = self.path+"nt_"+d.strftime('%Y%m%d')+"_f18_nrt_n.bin" with open(infile, 'rb') as fr: hdr = fr.read(300) ice = np.fromfile(fr, dtype=np.uint8) ice = ice.reshape(dimX,dimY) ice = np.flipud(ice) data[n] = ice / 250. data[data>1.0] = np.nan return data def get_dates(self,time_start,time_end): # does dates_u cover one year or more #daily files dates_u = [] d_no = (time_end-time_start).days +3 # make sure we get the bracket points for dn in range(d_no): d = time_start+ relativedelta(days = dn - 1) if d.year<2020: infile = self.path+d.strftime('/%Y/')+"nt_"+d.strftime('%Y%m%d')+"_f17_v1.1_n.bin" if d.year>2019: infile = self.path+d.strftime('/%Y/')+"nt_"+d.strftime('%Y%m%d')+"_f18_nrt_n.bin" # check infile exists if exists(infile): dates_u.append(d) #if it does append dates_u self.dates= dates_u print(self.name+' Found '+str(np.shape(dates_u)[0])+' dates') class NSIDC_bt(): """ forcing class for the budget lets the forcing load efficiently """ def __init__(self,ppath): self.name = 'NSIDC_b' self.path = ppath # next function will take a list of dates and return an appropriately orientated arrays # give a def get_aice(self,dates_u,verbos=False): # does dates_u cover one year or more #daily files dimY = 304 dimX = 448 d_no = np.shape(dates_u)[0] data = np.empty([d_no, dimX, dimY]) for n,d in enumerate(dates_u): infile = self.path+d.strftime('/%Y/')+"bt_"+d.strftime('%Y%m%d')+"_f17_v3.1_n.bin" # if d.year<2019: # infile = self.path+"nt_"+d.strftime('%Y%m%d')+"_f17_v1.1_n.bin" # if d.year>2018: # infile = self.path+"nt_"+d.strftime('%Y%m%d')+"_f18_nrt_n.bin" with open(infile, 'rb') as fr: hdr = fr.read(0) ice = np.fromfile(fr, dtype="<i2") ice = ice.reshape(dimX,dimY) ice = np.flipud(ice) data[n] = ice / 1000. data[data>1.0] = np.nan return data def get_dates(self,time_start,time_end): # does dates_u cover one year or more #daily files dates_u = [] d_no = (time_end-time_start).days +3 # make sure we get the bracket points for dn in range(d_no): d = time_start+ relativedelta(days = dn - 1) # if d.year<2019: infile = self.path+d.strftime('/%Y/')+"bt_"+d.strftime('%Y%m%d')+"_f17_v3.1_n.bin" # if d.year>2018: # infile = self.path+"nt_"+d.strftime('%Y%m%d')+"_f18_nrt_n.bin" # check infile exists if exists(infile): dates_u.append(d) #if it does append dates_u self.dates= dates_u print(self.name+' Found '+str(np.shape(dates_u)[0])+' dates') class AWI_SMOS_daily(): """ forcing class for the budget lets the forcing load efficiently """ def __init__(self,ppath): self.name = 'AWI_SMOS_daily' self.path = ppath # next function will take a list of dates and return an appropriately orientated arrays # give a def get_hi(self,dates_u,verbos=False): # does dates_u cover one year or more #dmonthly blurb = 'W_XX-ESA,SMOS_CS2,NH_25KM_EASE2_' dn = np.shape(dates_u)[0] d = dates_u[0] if d > dt.datetime(2019,6,1): blurb2 = '_r_v202_02_l4sit.nc' else: blurb2 = '_r_v202_01_l4sit.nc' t0 = (d - relativedelta(days = 3)).strftime('%Y%m%d_') t1 = (d + relativedelta(days = 3)).strftime('%Y%m%d') file = self.path+d.strftime('%Y/%m/')+blurb+t0+t1+blurb2 f_nc = Dataset(file) hi = f_nc['analysis_sea_ice_thickness'][0] hi[hi.mask] = np.nan dx,dy = hi.shape data = np.empty([dn,dx,dy]) data[0] = hi f_nc.close() for n,d in enumerate(dates_u[1:]): if d > dt.datetime(2019,6,1): blurb2 = '_r_v202_02_l4sit.nc' else: blurb2 = '_r_v202_01_l4sit.nc' t0 = (d - relativedelta(days = 3)).strftime('%Y%m%d_') t1 = (d + relativedelta(days = 3)).strftime('%Y%m%d') file = self.path+d.strftime('%Y/%m/')+blurb+t0+t1+blurb2 f_nc = Dataset(file) hi = f_nc['analysis_sea_ice_thickness'][0] hi[hi.mask] = np.nan data[n+1] = hi f_nc.close() #if it does append dates_u return data def get_aice(self,dates_u,verbos=False): # does dates_u cover one year or more #dmonthly blurb = 'W_XX-ESA,SMOS_CS2,NH_25KM_EASE2_' dn = np.shape(dates_u)[0] d = dates_u[0] if d > dt.datetime(2019,6,1): blurb2 = '_r_v202_02_l4sit.nc' else: blurb2 = '_r_v202_01_l4sit.nc' t0 = (d - relativedelta(days = 3)).strftime('%Y%m%d_') t1 = (d + relativedelta(days = 3)).strftime('%Y%m%d') file = self.path+d.strftime('/%Y/%m/')+blurb+t0+t1+blurb2 f_nc = Dataset(file) aice = f_nc['sea_ice_concentration'][0] aice[aice.mask] = np.nan dx,dy = aice.shape data = np.empty([dn,dx,dy]) data[0] = aice/100 f_nc.close() for n,d in enumerate(dates_u[1:]): if d > dt.datetime(2019,6,1): blurb2 = '_r_v202_02_l4sit.nc' else: blurb2 = '_r_v202_01_l4sit.nc' t0 = (d - relativedelta(days = 3)).strftime('%Y%m%d_') t1 = (d + relativedelta(days = 3)).strftime('%Y%m%d') file = self.path+d.strftime('%Y/%m/')+blurb+t0+t1+blurb2 f_nc = Dataset(file) aice = f_nc['sea_ice_concentration'][0] aice[aice.mask] = np.nan data[n+1] = aice/100 #if it does append dates_u f_nc.close() return data # next function will take a list of dates and return an appropriately orientated arrays # give a def get_dates(self,time_start,time_end): # does dates_u cover one year or more #daily files blurb = 'W_XX-ESA,SMOS_CS2,NH_25KM_EASE2_' dates_u = [] dd = (time_end-time_start).days+1 # make sure we get the bracket points for dn in range(dd): d = time_start+ relativedelta(days = dn) if d > dt.datetime(2019,6,1): blurb2 = '_r_v202_02_l4sit.nc' else: blurb2 = '_r_v202_01_l4sit.nc' t0 = (d - relativedelta(days = 3)).strftime('%Y%m%d_') t1 = (d + relativedelta(days = 3)).strftime('%Y%m%d') file = self.path+d.strftime('%Y/%m/')+blurb+t0+t1+blurb2 if exists(file): dates_u.append(d) #if it does append dates_u self.dates= dates_u print(self.name+' Found '+str(np.shape(dates_u)[0])+' dates') class AWI_weekly(): """ forcing class for the budget lets the forcing load efficiently """ def __init__(self,ppath): self.name = 'AWI_weekly' self.path = ppath # next function will take a list of dates and return an appropriately orientated arrays # give a def get_hi(self,dates_u,verbos=False): # does dates_u cover one year or more #dmonthly blurb = 'awi-siral-l3c-sithick-cryosat2-rep-nh_25km_ease2-' blurb2 = '-fv2p2.nc' dn = np.shape(dates_u)[0] d = dates_u[0] t0 = (d - relativedelta(days = 3)).strftime('%Y%m%d_') t1 = (d + relativedelta(days = 3)).strftime('%Y%m%d') file = self.path+d.strftime('%Y/')+blurb+t0+t1+blurb2 f_nc = Dataset(file) hi = f_nc['analysis_sea_ice_thickness'][0] hi[hi.mask] = np.nan dx,dy = hi.shape data = np.empty([dn,dx,dy]) data[0] = hi f_nc.close() for n,d in enumerate(dates_u[1:]): t0 = (d - relativedelta(days = 3)).strftime('%Y%m%d_') t1 = (d + relativedelta(days = 3)).strftime('%Y%m%d') file = self.path+d.strftime('%Y/')+blurb+t0+t1+blurb2 f_nc = Dataset(file) hi = f_nc['analysis_sea_ice_thickness'][0] hi[hi.mask] = np.nan data[n+1] = hi f_nc.close() #if it does append dates_u return data def get_aice(self,dates_u,verbos=False): # does dates_u cover one year or more #dmonthly blurb = 'awi-siral-l3c-sithick-cryosat2-rep-nh_25km_ease2-' blurb2 = '-fv2p2.nc' dn = np.shape(dates_u)[0] d = dates_u[0] t0 = (d - relativedelta(days = 3)).strftime('%Y%m%d_') t1 = (d + relativedelta(days = 3)).strftime('%Y%m%d') file = self.path+d.strftime('/%Y/')+blurb+t0+t1+blurb2 f_nc = Dataset(file) aice = f_nc['sea_ice_concentration'][0] aice[aice.mask] = np.nan dx,dy = aice.shape data = np.empty([dn,dx,dy]) data[0] = aice/100 f_nc.close() for n,d in enumerate(dates_u[1:]): t0 = (d - relativedelta(days = 3)).strftime('%Y%m%d_') t1 = (d + relativedelta(days = 3)).strftime('%Y%m%d') file = self.path+d.strftime('%Y/')+blurb+t0+t1+blurb2 f_nc = Dataset(file) aice = f_nc['sea_ice_concentration'][0] aice[aice.mask] = np.nan data[n+1] = aice/100 #if it does append dates_u f_nc.close() return data # next function will take a list of dates and return an appropriately orientated arrays # give a def get_dates(self,time_start,time_end): # does dates_u cover one year or more # awi weekly - first ever week is 20101101 to 20101107 # midpoint of 20101104 w0 = dt.datetime(2010,11,4) # find first time point before time start w1 = int((time_start-w0).days/7) # find first time point after time end w2 = int((time_end-w0).days/7)+1 print(w1,w2) #daily files blurb = 'awi-siral-l3c-sithick-cryosat2-rep-nh_25km_ease2-' blurb2 = '-fv2p2.nc' dates_u = [] # make sure we get the bracket points for w in range(w1,w2): d = w0+ relativedelta(days = w*7) t0 = (d - relativedelta(days = 3)).strftime('%Y%m%d_') t1 = (d + relativedelta(days = 3)).strftime('%Y%m%d') file = self.path+d.strftime('%Y/')+blurb+t0+t1+blurb2 if exists(file): dates_u.append(d) #if it does append dates_u self.dates= dates_u print(self.name+' Found '+str(np.shape(dates_u)[0])+' dates') class AWI_monthly(): """ forcing class for the budget lets the forcing load efficiently """ def __init__(self,ppath): self.name = 'AWI_monthly' self.path = ppath # next function will take a list of dates and return an appropriately orientated arrays # give a def get_hi(self,dates_u,verbos=False): # does dates_u cover one year or more #dmonthly blurb = 'awi-siral-l3c-sithick-cryosat2-rep-nh_25km_ease2-' dn = np.shape(dates_u)[0] d = dates_u[0] dload = d.replace(day=1) file = self.path+dload.strftime('/%Y/')+blurb+dload.strftime('%Y%m')+'-fv2p2.nc' f_nc = Dataset(file) hi = f_nc['sea_ice_thickness'][0] dx,dy = hi.shape data = np.empty([dn,dx,dy]) data[0] = hi f_nc.close() for n,d in enumerate(dates_u[1:]): dload = d.replace(day=1) file = self.path+dload.strftime('/%Y/')+blurb+dload.strftime('%Y%m')+'-fv2p2.nc' f_nc = Dataset(file) hi = f_nc['sea_ice_thickness'][0] data[n+1] = hi f_nc.close() #if it does append dates_u return data def get_aice(self,dates_u,verbos=False): # does dates_u cover one year or more #dmonthly blurb = 'awi-siral-l3c-sithick-cryosat2-rep-nh_25km_ease2-' dn = np.shape(dates_u)[0] d = dates_u[0] dload = d.replace(day=1) file = self.path+dload.strftime('/%Y/')+blurb+dload.strftime('%Y%m')+'-fv2p2.nc' f_nc = Dataset(file) aice = f_nc['sea_ice_concentration'][0] dx,dy = aice.shape data = np.empty([dn,dx,dy]) data[0] = aice/100 f_nc.close() for n,d in enumerate(dates_u[1:]): dload = d.replace(day=1) file = self.path+dload.strftime('/%Y/')+blurb+dload.strftime('%Y%m')+'-fv2p2.nc' f_nc = Dataset(file) aice = f_nc['sea_ice_concentration'][0] data[n+1] = aice/100 #if it does append dates_u f_nc.close() return data # next function will take a list of dates and return an appropriately orientated arrays def get_dates(self,time_start,time_end,fill_end_months=False): # does dates_u cover one year or more #daily files blurb = 'awi-siral-l3c-sithick-cryosat2-rep-nh_25km_ease2-' dates_u = [] dy = time_end.year-time_start.year dm = time_end.month-time_start.month m_no = dy*12 + dm +2 # make sure we get the bracket points ts_m = dt.datetime(time_start.year,time_start.month,1) for mn in range(m_no): d = ts_m+ relativedelta(months = mn ) file = self.path+d.strftime('/%Y/')+blurb+d.strftime('%Y%m')+'-fv2p2.nc' if exists(file): if d.month==2: mid_day = 13 else: mid_day = 14 dates_u.append(d + relativedelta(days=mid_day)) ### now work over the date and adjust for summer ### remove all months = [5,6,8,7,9] ### also need hole end points to be at month end not mid self.dates= [] month_keep = [1,2,3,4,10,11,12] for d in dates_u: if d.month in month_keep: if fill_end_months and d.month == 4: self.dates.append(d) d_end = d.replace(day=30) self.dates.append(d_end) elif fill_end_months and d.month == 10: d_start = d.replace(day=1) self.dates.append(d_start) self.dates.append(d) else: self.dates.append(d) print(self.name+' Found '+str(np.shape(dates_u)[0])+' dates') class OSISAF(): """ forcing class for the budget lets the forcing load efficiently """ def __init__(self,ppath): self.path = ppath self.name = 'osisaf' # next function will take a list of dates and return an appropriately orientated arrays # give a def get_dates(self,time_start,time_end): # individual drift for each day slice dates_u = [] d_no = (time_end-time_start).days +3 # make sure we get the bracket points for dn in range(d_no): d = time_start+ relativedelta(days = dn - 1) t1 = (d - relativedelta(hours=12)).strftime('%Y%m%d%H00') t2 = (d + relativedelta(hours=36)).strftime('%Y%m%d%H00') # check if were on the last day of the month next_month = d.replace(day=28) + dt.timedelta(days=4) # this will never fail next_month.replace(day = 1) if (next_month - d).days>1: td = d.strftime('%Y/%m/') else: td = (d + relativedelta(months=1)).strftime('%Y/%m/') f_name = td+'ice_drift_nh_polstere-625_multi-oi_'+t1+'-'+t2+'.nc' # print(f_name) if exists(self.path+f_name): dates_u.append(d) self.dates= dates_u print(self.name+' Found '+str(np.shape(dates_u)[0])+' dates') # next function will take a list of dates and return an appropriately orientated arrays # give a def get_vels(self,dates_u,verbos=False): # individual drift for each day slice d_no = np.shape(dates_u)[0] d = dates_u[0] # one year, one file t1 = (d - relativedelta(hours=12)).strftime('%Y%m%d%H00') t2 = (d + relativedelta(hours=36)).strftime('%Y%m%d%H00') # check if were on the last day of the month next_month = d.replace(day=28) + dt.timedelta(days=4) next_month.replace(day = 1) if (next_month - d).days>1: td = d.strftime('%Y/%m/') else: td = (d + relativedelta(months=1)).strftime('%Y/%m/') ## extra date check for v component vmult = -1.0 if d > dt.datetime(2015,9,12): vmult = 1.0 f_name = td+'ice_drift_nh_polstere-625_multi-oi_'+t1+'-'+t2+'.nc' f_nc = Dataset(self.path+f_name) unow = np.fliplr(f_nc['dX'][0].T) vnow = np.fliplr(f_nc['dY'][0].T) unow[unow.mask] = np.nan vnow[vnow.mask] = np.nan dx,dy = np.shape(unow) data_u = np.zeros([d_no,dx,dy]) data_v = np.zeros([d_no,dx,dy]) # convert km/48hrs to m/s data_u[0] = unow*1e3/60/60/48 data_v[0] = vmult*vnow*1e3/60/60/48 f_nc.close() for n,d in enumerate(dates_u[1:]): # one year, one file t1 = (d - relativedelta(hours=12)).strftime('%Y%m%d%H00') t2 = (d + relativedelta(hours=36)).strftime('%Y%m%d%H00') # check if were on the last day of the month next_month = d.replace(day=28) + dt.timedelta(days=4) next_month.replace(day = 1) if (next_month - d).days>1: td = d.strftime('%Y/%m/') else: td = (d + relativedelta(months=1)).strftime('%Y/%m/') f_name = td+'ice_drift_nh_polstere-625_multi-oi_'+t1+'-'+t2+'.nc' f_nc = Dataset(self.path+f_name) unow = np.fliplr(f_nc['dX'][0].T) vnow = np.fliplr(f_nc['dY'][0].T) unow[unow.mask] = np.nan vnow[vnow.mask] = np.nan data_u[n+1] = unow*1e3/60/60/48 data_v[n+1] = vmult*vnow*1e3/60/60/48 f_nc.close() return data_u,data_v class CPOM_hi: """ forcing class for the budget lets the forcing load efficiently """ def __init__(self,ppath,G): self.name = 'CPOM_monthly' self.path = ppath ### we need to regrid as we load ### for efficiency we will buffer two months self.hi1 = 0.0 self.dl1 = None self.hi2 = 0.0 self.dl2 = None self.G = G self.THRESH = np.hypot(np.mean(np.diff(self.G.ypts)), np.mean(np.diff(self.G.xpts)))/2 # self.edges_x = self.G.xpts[:,int(G.n/2)] - self.G.dxRes/2 # self.edges_y = self.G.ypts[int(G.m/2),:] - self.G.dyRes/2 # self.edges_x = np.append(self.edges_x,2*self.G.xpts[-1,int(G.n/2)] - self.G.xpts[-2,int(G.n/2)]) # self.edges_y = np.append(self.edges_y,2*self.G.ypts[int(G.m/2),-1] - self.G.ypts[int(G.m/2),-2]) # next function will take a list of dates and return an appropriately orientated arrays # give a def get_hi(self,dates_u,verbos=False): # does dates_u cover one year or more #dmonthly reload = [False,False] d_no = np.shape(dates_u)[0] if d_no>2: print('Warning CPOM hi not compatible with tw over 1 month') return None ### first check if any of the dates in dates_u ### match the preloaded, ddL ### if the first date matches the second data_u = np.zeros([d_no,self.G.m,self.G.n]) for n,d in enumerate(dates_u): if d == self.dl1: ### return buffered data_u[n] = self.hi1 elif d == self.dl2: ### return buffered data_u[n] = self.hi2 else: ### load and bin ### check dates ### normal month, data on the first dload = d.replace(day=1) file = self.path+d.strftime('%Y%m_')+'Thick.map' if verbos: print(file) f = np.genfromtxt(file) hi = f[:,2] lon = f[:,1] lat = f[:,0] xpts,ypts = self.G.mplot(lon,lat) # print('Binning awkward CPOM data') # # # ret = binned_statistic_2d( xpts, ypts, hi, # statistic='mean', bins=[self.edges_x,self.edges_y]) # data_u[n] = ret.statistic # ret = binned_statistic_2d( xpts, ypts, [], # statistic='count', bins=[self.edges_x,self.edges_y]) # data_u[n][ret.statistic<4] = np.nan print('Regridding awkward CPOM data') xpts,ypts = self.G.mplot(lon,lat) xy = np.vstack([xpts,ypts]).T data_u[n] = griddata(xy, hi, (self.G.xpts, self.G.ypts),method='nearest') # Construct kd-tree, functionality copied from scipy.interpolate ### this finds empty values on the grid tree = cKDTree(xy) xi = _ndim_coords_from_arrays((self.G.xpts, self.G.ypts)) dists, indexes = tree.query(xi) # Copy original result but mask missing values with NaNs data_u[n][dists > self.THRESH] = np.nan reload[n] = True ### update buffered thickness if d_no == 2: self.dl1 = dates_u[0] self.hi1 = data_u[0] self.dl2 = dates_u[1] self.hi2 = data_u[1] else: self.dl2 = dates_u[0] self.hi2 = data_u[0] return data_u # next function will take a list of dates and return an appropriately orientated arrays # give a def get_dates(self,time_start,time_end,fill_end_months=False): # does dates_u cover one year or more #daily files dates_u = [] dy = time_end.year-time_start.year dm = time_end.month-time_start.month m_no = dy*12 + dm +2 # make sure we get the bracket points ts_m = dt.datetime(time_start.year,time_start.month,1) for mn in range(m_no): d = ts_m+ relativedelta(months = mn ) file = self.path+d.strftime('%Y%m_')+'Thick.map' if exists(file): if d.month==2: mid_day = 13 else: mid_day = 14 dates_u.append(d + relativedelta(days=mid_day)) #if it does append dates_u ### now work over the date and adjust for summer ### remove all months = [5,6,8,7,9] ### also need hole end points to be at month end not mid self.dates= [] month_keep = [1,2,3,4,10,11,12] for d in dates_u: if d.month in month_keep: if fill_end_months and d.month == 4: self.dates.append(d) d_end = d.replace(day=30) self.dates.append(d_end) elif fill_end_months and d.month == 10: d_start = d.replace(day=1) self.dates.append(d_start) self.dates.append(d) else: self.dates.append(d) print(self.name+' Found '+str(np.shape(dates_u)[0])+' dates') class Kimura(): """ forcing class for the budget lets the forcing load efficiently """ def __init__(self,ppath): self.name = 'Kimura_drift' self.path = ppath def get_dates(self,time_start,time_end): """ returns the all encompassing date list for use with the forcing object """ dates =[] d_no = (time_end-time_start).days +3 for dn in range(d_no): d = time_start+ relativedelta(days = dn - 1) infile = self.path+d.strftime('%y%m%d')+".amsr36i" if exists(infile): dates.append(d) else: infile = self.path+d.strftime('%y%m%d')+".amsr18i" if exists(infile): dates.append(d) self.dates = dates print(self.name+' Found '+str(np.shape(dates)[0])+' dates') # daily points in yearly files # next function will take a list of dates and return an appropriately orientated arrays # give a def get_vels(self,dates_u,verbos=False): dimY = 145 dimX = 145 d_no = np.shape(dates_u)[0] data_u = np.zeros([d_no,dimX,dimY]) data_v = np.zeros([d_no,dimX,dimY]) for n,d in enumerate(dates_u): infile = self.path+d.strftime('%y%m%d')+".amsr36i" if not exists(infile): infile = self.path+d.strftime('%y%m%d')+".amsr18i" if verbos: print(infile) # print(d.strftime('%y%m%d')) with open(infile, 'rb') as fr: hdr = fr.read(0) ice = np.fromfile(fr, dtype=np.float32) ice = ice/100 ice[ice>9] = np.nan iceG = ice.reshape(dimX,dimY,2) data_u[n] =-iceG[:,:,1] data_v[n] = iceG[:,:,0] return data_u,data_v class CICE_jas: def __init__(self,ppath): self.name = 'CICE_1deg' self.path = ppath self.vyear_load = 0 self.hyear_load = 0 self.ayear_load = 0 self.vels_loaded = False self.hi_loaded = False self.aice_loaded = False def get_dates(self,time_start,time_end): """ returns the all encompassing date list for use with the forcing object """ dates =[] n_yrs = (time_end.year - time_start.year)+1 for y in range(n_yrs): yu = time_start.year + y d0 = dt.datetime(yu,1,1) f_name = 'cice_daily_'+str(yu)+'.nc' if exists(self.path+f_name): f_nc = Dataset(self.path+f_name) [dates.append(d0 + relativedelta(days = d)) for d in range(f_nc['time'].shape[0])] f_nc.close() self.dates = dates print(self.name+' Found '+str(np.shape(dates)[0])+' dates') def get_vels(self,dates_u,verbos=False): d0 = dt.datetime(1970,1,1) # does dates_u cover one year or more if (dates_u[-1].year -dates_u[0].year) == 0: dates = dates_u single_year = True else: ## multiple years dates = [d for d in dates_u if d.year == dates_u[0].year] single_year = False # one year, one file yu = dates_u[0].year if ((self.vyear_load != yu) or (not self.vels_loaded)): print('loading new year of data: '+str(yu)) f_name = 'cice_daily_'+str(yu)+'.nc' f_nc = Dataset(self.path+f_name) # print(p0,p1) self.u = f_nc['uvel_d'][:] self.v = f_nc['vvel_d'][:] self.u[self.u.mask] = np.nan self.v[self.v.mask] = np.nan f_nc.close() self.vyear_load = yu self.vels_loaded= True p0 = dates[ 0].timetuple().tm_yday -1 p1 = dates[-1].timetuple().tm_yday datau = self.u[p0:p1,:,:].transpose((0,2,1)) datav = self.v[p0:p1,:,:].transpose((0,2,1)) if single_year: return datau,datav else: ## multiple years data1 = datau dates = [d for d in dates_u if d.year == dates_u[-1].year] yu = dates[-1].year print('loading new year of data: '+str(yu)) f_name = 'cice_daily_'+str(yu)+'.nc' f_nc = Dataset(self.path+f_name) # print(p0,p1) self.u = f_nc['uvel_d'][:] self.v = f_nc['vvel_d'][:] self.u[self.u.mask] = np.nan self.v[self.v.mask] = np.nan f_nc.close() self.hyear_load = yu self.hi_loaded= True p0 = dates[ 0].timetuple().tm_yday -1 p1 = dates[-1].timetuple().tm_yday datau2= self.u[p0:p1,:,:].transpose((0,2,1)) datav2= self.v[p0:p1,:,:].transpose((0,2,1)) datau = np.vstack([datau,datau2]) datav = np.vstack([datav,datav2]) return datau,datav def get_aice(self,dates_u,verbos=False): d0 = dt.datetime(1970,1,1) # does dates_u cover one year or more if (dates_u[-1].year -dates_u[0].year) == 0: dates = dates_u single_year = True else: ## multiple years dates = [d for d in dates_u if d.year == dates_u[0].year] single_year = False # one year, one file yu = dates_u[0].year if ((self.ayear_load != yu) or (not self.aice_loaded)): print('loading new year of data: '+str(yu)) f_name = 'cice_daily_'+str(yu)+'.nc' f_nc = Dataset(self.path+f_name) # print(p0,p1) self.a = f_nc['aice_d'][:] self.a[self.a.mask] = np.nan f_nc.close() self.ayear_load = yu self.aice_loaded= True p0 = dates[ 0].timetuple().tm_yday -1 p1 = dates[-1].timetuple().tm_yday datau = self.a[p0:p1,:,:].transpose((0,2,1)) if single_year: return datau else: ## multiple years data1 = datau dates = [d for d in dates_u if d.year == dates_u[-1].year] yu = dates[-1].year print('loading new year of data: '+str(yu)) f_name = 'cice_daily_'+str(yu)+'.nc' f_nc = Dataset(self.path+f_name) # print(p0,p1) self.a = f_nc['aice_d'][:] self.a[self.a.mask] = np.nan f_nc.close() self.ayear_load = yu self.aice_loaded= True p0 = dates[ 0].timetuple().tm_yday -1 p1 = dates[-1].timetuple().tm_yday data2 = self.a[p0:p1,:,:].transpose((0,2,1)) datau = np.vstack([data1,data2]) return datau def get_hi(self,dates_u,verbos=False): # does dates_u cover one year or more if (dates_u[-1].year -dates_u[0].year) == 0: dates = dates_u single_year = True else: ## multiple years dates = [d for d in dates_u if d.year == dates_u[0].year] single_year = False # one year, one file yu = dates_u[0].year if ((self.hyear_load != yu) or (not self.hi_loaded)): print('loading new year of data: '+str(yu)) f_name = 'cice_daily_'+str(yu)+'.nc' f_nc = Dataset(self.path+f_name) # print(p0,p1) self.h = f_nc['hi_d'][:] self.h[self.h.mask] = np.nan f_nc.close() self.hyear_load = yu self.hi_loaded= True p0 = dates[ 0].timetuple().tm_yday -1 p1 = dates[-1].timetuple().tm_yday datau = self.h[p0:p1,:,:].transpose((0,2,1)) if single_year: return datau else: ## multiple years data1 = datau dates = [d for d in dates_u if d.year == dates_u[-1].year] yu = dates[-1].year print('loading new year of data: '+str(yu)) f_name = 'cice_daily_'+str(yu)+'.nc' f_nc = Dataset(self.path+f_name) # print(p0,p1) self.h = f_nc['hi_d'][:] self.h[self.h.mask] = np.nan f_nc.close() self.hyear_load = yu self.hi_loaded= True p0 = dates[ 0].timetuple().tm_yday -1 p1 = dates[-1].timetuple().tm_yday data2 = self.h[p0:p1,:,:].transpose((0,2,1)) datau = np.vstack([data1,data2]) return datau class Bristol_thickness: def __init__(self,ppath,var='Sea_Ice_Thickness_incSMOS'): """ var can be any of 'Sea_Ice_Thickness' 'Sea_Ice_Thickness_W99' 'Sea_Ice_Thickness_incSMOS' 'Sea_Ice_Volume' 'Sea_Ice_Volume_W99' 'Sea_Ice_Volume_incSMOS' """ self.name = 'Bristol_hi' self.path = ppath self.hi1 = 0.0 self.dl1 = None self.hi2 = 0.0 self.dl2 = None self.var = var def get_dates(self,time_start,time_end,fill_end_months=False): """ returns the all encompassing date list for use with the forcing object """ blurb ='ubristol_cryosat2_seaicethickness_nh25km_' dy = time_end.year-time_start.year dm = time_end.month-time_start.month m_no = dy*12 + dm +2 # make sure we get the bracket points ts_m = dt.datetime(time_start.year,time_start.month,1) dates_u = [] for mn in range(m_no): d = ts_m+ relativedelta(months = mn ) file = self.path+blurb+d.strftime('%Y_%m_')+'v1.nc' if exists(file): if d.month==2: mid_day = 13 else: mid_day = 14 dates_u.append(d + relativedelta(days=mid_day)) #if it does append dates_u ### now work over the date and adjust for summer ### remove all months = [5,6,8,7,9] ### also need hole end points to be at month end not mid self.dates= [] month_keep = [1,2,3,4,10,11,12] for d in dates_u: if d.month in month_keep: if fill_end_months and d.month == 4: self.dates.append(d) d_end = d.replace(day=30) self.dates.append(d_end) elif fill_end_months and d.month == 10: d_start = d.replace(day=1) self.dates.append(d_start) self.dates.append(d) else: self.dates.append(d) print(self.name+' Found '+str(np.shape(dates_u)[0])+' dates') def get_hi(self,dates_u,verbos=False): # does dates_u cover one year or more ### check dates ### normal month, data on the first blurb ='ubristol_cryosat2_seaicethickness_nh25km_' d = dates_u[0] dn = np.shape(dates_u)[0] file = self.path+blurb+d.strftime('%Y_%m_')+'v1.nc' f_nc = Dataset(file) hi = f_nc[self.var][:] dx,dy = hi.shape data = np.empty([dn,dx,dy]) data[0] = hi f_nc.close() for n,d in enumerate(dates_u[1:]): dload = d.replace(day=1) file = self.path+blurb+d.strftime('%Y_%m_')+'v1.nc' f_nc = Dataset(file) hi = f_nc[self.var][:] data[n+1] = hi f_nc.close() #if it does append dates_u return data
[ "numpy.maximum", "numpy.empty", "numpy.shape", "scipy.spatial.cKDTree", "numpy.nanmean", "netCDF4.Dataset", "os.path.exists", "dateutil.relativedelta.relativedelta", "numpy.genfromtxt", "datetime.timedelta", "scipy.interpolate.griddata", "numpy.asarray", "numpy.flipud", "datetime.datetime", "numpy.fliplr", "numpy.vstack", "numpy.fromfile", "numpy.zeros", "scipy.interpolate.interpnd._ndim_coords_from_arrays", "numpy.diff" ]
[((897, 920), 'datetime.datetime', 'dt.datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (908, 920), True, 'import datetime as dt\n'), ((1649, 1672), 'datetime.datetime', 'dt.datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (1660, 1672), True, 'import datetime as dt\n'), ((10474, 10502), 'numpy.empty', 'np.empty', (['[d_no, dimX, dimY]'], {}), '([d_no, dimX, dimY])\n', (10482, 10502), True, 'import numpy as np\n'), ((12883, 12911), 'numpy.empty', 'np.empty', (['[d_no, dimX, dimY]'], {}), '([d_no, dimX, dimY])\n', (12891, 12911), True, 'import numpy as np\n'), ((15212, 15225), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (15219, 15225), False, 'from netCDF4 import Dataset\n'), ((15347, 15369), 'numpy.empty', 'np.empty', (['[dn, dx, dy]'], {}), '([dn, dx, dy])\n', (15355, 15369), True, 'import numpy as np\n'), ((16604, 16617), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (16611, 16617), False, 'from netCDF4 import Dataset\n'), ((16742, 16764), 'numpy.empty', 'np.empty', (['[dn, dx, dy]'], {}), '([dn, dx, dy])\n', (16750, 16764), True, 'import numpy as np\n'), ((19230, 19243), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (19237, 19243), False, 'from netCDF4 import Dataset\n'), ((19365, 19387), 'numpy.empty', 'np.empty', (['[dn, dx, dy]'], {}), '([dn, dx, dy])\n', (19373, 19387), True, 'import numpy as np\n'), ((20370, 20383), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (20377, 20383), False, 'from netCDF4 import Dataset\n'), ((20508, 20530), 'numpy.empty', 'np.empty', (['[dn, dx, dy]'], {}), '([dn, dx, dy])\n', (20516, 20530), True, 'import numpy as np\n'), ((21364, 21388), 'datetime.datetime', 'dt.datetime', (['(2010)', '(11)', '(4)'], {}), '(2010, 11, 4)\n', (21375, 21388), True, 'import datetime as dt\n'), ((22921, 22934), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (22928, 22934), False, 'from netCDF4 import Dataset\n'), ((23018, 23040), 'numpy.empty', 'np.empty', (['[dn, dx, dy]'], {}), '([dn, dx, dy])\n', (23026, 23040), True, 'import numpy as np\n'), ((23817, 23830), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (23824, 23830), False, 'from netCDF4 import Dataset\n'), ((23922, 23944), 'numpy.empty', 'np.empty', (['[dn, dx, dy]'], {}), '([dn, dx, dy])\n', (23930, 23944), True, 'import numpy as np\n'), ((24861, 24910), 'datetime.datetime', 'dt.datetime', (['time_start.year', 'time_start.month', '(1)'], {}), '(time_start.year, time_start.month, 1)\n', (24872, 24910), True, 'import datetime as dt\n'), ((28384, 28411), 'netCDF4.Dataset', 'Dataset', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (28391, 28411), False, 'from netCDF4 import Dataset\n'), ((28425, 28451), 'numpy.fliplr', 'np.fliplr', (["f_nc['dX'][0].T"], {}), "(f_nc['dX'][0].T)\n", (28434, 28451), True, 'import numpy as np\n'), ((28467, 28493), 'numpy.fliplr', 'np.fliplr', (["f_nc['dY'][0].T"], {}), "(f_nc['dY'][0].T)\n", (28476, 28493), True, 'import numpy as np\n'), ((28576, 28590), 'numpy.shape', 'np.shape', (['unow'], {}), '(unow)\n', (28584, 28590), True, 'import numpy as np\n'), ((28608, 28632), 'numpy.zeros', 'np.zeros', (['[d_no, dx, dy]'], {}), '([d_no, dx, dy])\n', (28616, 28632), True, 'import numpy as np\n'), ((28648, 28672), 'numpy.zeros', 'np.zeros', (['[d_no, dx, dy]'], {}), '([d_no, dx, dy])\n', (28656, 28672), True, 'import numpy as np\n'), ((31229, 31265), 'numpy.zeros', 'np.zeros', (['[d_no, self.G.m, self.G.n]'], {}), '([d_no, self.G.m, self.G.n])\n', (31237, 31265), True, 'import numpy as np\n'), ((33844, 33893), 'datetime.datetime', 'dt.datetime', (['time_start.year', 'time_start.month', '(1)'], {}), '(time_start.year, time_start.month, 1)\n', (33855, 33893), True, 'import datetime as dt\n'), ((36254, 36282), 'numpy.zeros', 'np.zeros', (['[d_no, dimX, dimY]'], {}), '([d_no, dimX, dimY])\n', (36262, 36282), True, 'import numpy as np\n'), ((36298, 36326), 'numpy.zeros', 'np.zeros', (['[d_no, dimX, dimY]'], {}), '([d_no, dimX, dimY])\n', (36306, 36326), True, 'import numpy as np\n'), ((38004, 38027), 'datetime.datetime', 'dt.datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (38015, 38027), True, 'import datetime as dt\n'), ((40108, 40131), 'datetime.datetime', 'dt.datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (40119, 40131), True, 'import datetime as dt\n'), ((44478, 44527), 'datetime.datetime', 'dt.datetime', (['time_start.year', 'time_start.month', '(1)'], {}), '(time_start.year, time_start.month, 1)\n', (44489, 44527), True, 'import datetime as dt\n'), ((46096, 46109), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (46103, 46109), False, 'from netCDF4 import Dataset\n'), ((46182, 46204), 'numpy.empty', 'np.empty', (['[dn, dx, dy]'], {}), '([dn, dx, dy])\n', (46190, 46204), True, 'import numpy as np\n'), ((1141, 1167), 'os.path.exists', 'exists', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (1147, 1167), False, 'from os.path import exists\n'), ((3636, 3670), 'datetime.datetime', 'dt.datetime', (['time_start.year', '(1)', '(1)'], {}), '(time_start.year, 1, 1)\n', (3647, 3670), True, 'import datetime as dt\n'), ((3686, 3722), 'datetime.datetime', 'dt.datetime', (['time_start.year', '(12)', '(31)'], {}), '(time_start.year, 12, 31)\n', (3697, 3722), True, 'import datetime as dt\n'), ((3795, 3809), 'os.path.exists', 'exists', (['data_f'], {}), '(data_f)\n', (3801, 3809), False, 'from os.path import exists\n'), ((4365, 4387), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'years': '(1)'}), '(years=1)\n', (4378, 4387), False, 'from dateutil.relativedelta import relativedelta\n'), ((4489, 4503), 'os.path.exists', 'exists', (['data_f'], {}), '(data_f)\n', (4495, 4503), False, 'from os.path import exists\n'), ((4656, 4690), 'datetime.datetime', 'dt.datetime', (['time_start.year', '(1)', '(1)'], {}), '(time_start.year, 1, 1)\n', (4667, 4690), True, 'import datetime as dt\n'), ((4763, 4777), 'os.path.exists', 'exists', (['data_f'], {}), '(data_f)\n', (4769, 4777), False, 'from os.path import exists\n'), ((10437, 10454), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (10445, 10454), True, 'import numpy as np\n'), ((11472, 11486), 'numpy.flipud', 'np.flipud', (['ice'], {}), '(ice)\n', (11481, 11486), True, 'import numpy as np\n'), ((12189, 12203), 'os.path.exists', 'exists', (['infile'], {}), '(infile)\n', (12195, 12203), False, 'from os.path import exists\n'), ((12846, 12863), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (12854, 12863), True, 'import numpy as np\n'), ((13456, 13470), 'numpy.flipud', 'np.flipud', (['ice'], {}), '(ice)\n', (13465, 13470), True, 'import numpy as np\n'), ((14157, 14171), 'os.path.exists', 'exists', (['infile'], {}), '(infile)\n', (14163, 14171), False, 'from os.path import exists\n'), ((14825, 14842), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (14833, 14842), True, 'import numpy as np\n'), ((14884, 14907), 'datetime.datetime', 'dt.datetime', (['(2019)', '(6)', '(1)'], {}), '(2019, 6, 1)\n', (14895, 14907), True, 'import datetime as dt\n'), ((15828, 15841), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (15835, 15841), False, 'from netCDF4 import Dataset\n'), ((16216, 16233), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (16224, 16233), True, 'import numpy as np\n'), ((16275, 16298), 'datetime.datetime', 'dt.datetime', (['(2019)', '(6)', '(1)'], {}), '(2019, 6, 1)\n', (16286, 16298), True, 'import datetime as dt\n'), ((17229, 17242), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (17236, 17242), False, 'from netCDF4 import Dataset\n'), ((18282, 18294), 'os.path.exists', 'exists', (['file'], {}), '(file)\n', (18288, 18294), False, 'from os.path import exists\n'), ((18984, 19001), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (18992, 19001), True, 'import numpy as np\n'), ((19689, 19702), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (19696, 19702), False, 'from netCDF4 import Dataset\n'), ((20123, 20140), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (20131, 20140), True, 'import numpy as np\n'), ((20838, 20851), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (20845, 20851), False, 'from netCDF4 import Dataset\n'), ((22063, 22075), 'os.path.exists', 'exists', (['file'], {}), '(file)\n', (22069, 22075), False, 'from os.path import exists\n'), ((22740, 22757), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (22748, 22757), True, 'import numpy as np\n'), ((23273, 23286), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (23280, 23286), False, 'from netCDF4 import Dataset\n'), ((23636, 23653), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (23644, 23653), True, 'import numpy as np\n'), ((24183, 24196), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (24190, 24196), False, 'from netCDF4 import Dataset\n'), ((25090, 25102), 'os.path.exists', 'exists', (['file'], {}), '(file)\n', (25096, 25102), False, 'from os.path import exists\n'), ((27291, 27317), 'os.path.exists', 'exists', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (27297, 27317), False, 'from os.path import exists\n'), ((27664, 27681), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (27672, 27681), True, 'import numpy as np\n'), ((27967, 27987), 'datetime.timedelta', 'dt.timedelta', ([], {'days': '(4)'}), '(days=4)\n', (27979, 27987), True, 'import datetime as dt\n'), ((28259, 28283), 'datetime.datetime', 'dt.datetime', (['(2015)', '(9)', '(12)'], {}), '(2015, 9, 12)\n', (28270, 28283), True, 'import datetime as dt\n'), ((29456, 29483), 'netCDF4.Dataset', 'Dataset', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (29463, 29483), False, 'from netCDF4 import Dataset\n'), ((29501, 29527), 'numpy.fliplr', 'np.fliplr', (["f_nc['dX'][0].T"], {}), "(f_nc['dX'][0].T)\n", (29510, 29527), True, 'import numpy as np\n'), ((29547, 29573), 'numpy.fliplr', 'np.fliplr', (["f_nc['dY'][0].T"], {}), "(f_nc['dY'][0].T)\n", (29556, 29573), True, 'import numpy as np\n'), ((30933, 30950), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (30941, 30950), True, 'import numpy as np\n'), ((34049, 34061), 'os.path.exists', 'exists', (['file'], {}), '(file)\n', (34055, 34061), False, 'from os.path import exists\n'), ((35676, 35690), 'os.path.exists', 'exists', (['infile'], {}), '(infile)\n', (35682, 35690), False, 'from os.path import exists\n'), ((36216, 36233), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (36224, 36233), True, 'import numpy as np\n'), ((37541, 37562), 'datetime.datetime', 'dt.datetime', (['yu', '(1)', '(1)'], {}), '(yu, 1, 1)\n', (37552, 37562), True, 'import datetime as dt\n'), ((37625, 37651), 'os.path.exists', 'exists', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (37631, 37651), False, 'from os.path import exists\n'), ((38568, 38595), 'netCDF4.Dataset', 'Dataset', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (38575, 38595), False, 'from netCDF4 import Dataset\n'), ((39410, 39437), 'netCDF4.Dataset', 'Dataset', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (39417, 39437), False, 'from netCDF4 import Dataset\n'), ((39946, 39972), 'numpy.vstack', 'np.vstack', (['[datau, datau2]'], {}), '([datau, datau2])\n', (39955, 39972), True, 'import numpy as np\n'), ((39992, 40018), 'numpy.vstack', 'np.vstack', (['[datav, datav2]'], {}), '([datav, datav2])\n', (40001, 40018), True, 'import numpy as np\n'), ((40672, 40699), 'netCDF4.Dataset', 'Dataset', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (40679, 40699), False, 'from netCDF4 import Dataset\n'), ((41375, 41402), 'netCDF4.Dataset', 'Dataset', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (41382, 41402), False, 'from netCDF4 import Dataset\n'), ((41776, 41801), 'numpy.vstack', 'np.vstack', (['[data1, data2]'], {}), '([data1, data2])\n', (41785, 41801), True, 'import numpy as np\n'), ((42410, 42437), 'netCDF4.Dataset', 'Dataset', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (42417, 42437), False, 'from netCDF4 import Dataset\n'), ((43109, 43136), 'netCDF4.Dataset', 'Dataset', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (43116, 43136), False, 'from netCDF4 import Dataset\n'), ((43506, 43531), 'numpy.vstack', 'np.vstack', (['[data1, data2]'], {}), '([data1, data2])\n', (43515, 43531), True, 'import numpy as np\n'), ((44707, 44719), 'os.path.exists', 'exists', (['file'], {}), '(file)\n', (44713, 44719), False, 'from os.path import exists\n'), ((46000, 46017), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (46008, 46017), True, 'import numpy as np\n'), ((46408, 46421), 'netCDF4.Dataset', 'Dataset', (['file'], {}), '(file)\n', (46415, 46421), False, 'from netCDF4 import Dataset\n'), ((1190, 1217), 'netCDF4.Dataset', 'Dataset', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (1197, 1217), False, 'from netCDF4 import Dataset\n'), ((2078, 2105), 'netCDF4.Dataset', 'Dataset', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (2085, 2105), False, 'from netCDF4 import Dataset\n'), ((4053, 4075), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'years': '(1)'}), '(years=1)\n', (4066, 4075), False, 'from dateutil.relativedelta import relativedelta\n'), ((4098, 4120), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'years': '(1)'}), '(years=1)\n', (4111, 4120), False, 'from dateutil.relativedelta import relativedelta\n'), ((4203, 4217), 'os.path.exists', 'exists', (['data_f'], {}), '(data_f)\n', (4209, 4217), False, 'from os.path import exists\n'), ((11380, 11411), 'numpy.fromfile', 'np.fromfile', (['fr'], {'dtype': 'np.uint8'}), '(fr, dtype=np.uint8)\n', (11391, 11411), True, 'import numpy as np\n'), ((11857, 11883), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(dn - 1)'}), '(days=dn - 1)\n', (11870, 11883), False, 'from dateutil.relativedelta import relativedelta\n'), ((13367, 13395), 'numpy.fromfile', 'np.fromfile', (['fr'], {'dtype': '"""<i2"""'}), "(fr, dtype='<i2')\n", (13378, 13395), True, 'import numpy as np\n'), ((13842, 13868), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(dn - 1)'}), '(days=dn - 1)\n', (13855, 13868), False, 'from dateutil.relativedelta import relativedelta\n'), ((15472, 15495), 'datetime.datetime', 'dt.datetime', (['(2019)', '(6)', '(1)'], {}), '(2019, 6, 1)\n', (15483, 15495), True, 'import datetime as dt\n'), ((16873, 16896), 'datetime.datetime', 'dt.datetime', (['(2019)', '(6)', '(1)'], {}), '(2019, 6, 1)\n', (16884, 16896), True, 'import datetime as dt\n'), ((17886, 17908), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': 'dn'}), '(days=dn)\n', (17899, 17908), False, 'from dateutil.relativedelta import relativedelta\n'), ((17930, 17953), 'datetime.datetime', 'dt.datetime', (['(2019)', '(6)', '(1)'], {}), '(2019, 6, 1)\n', (17941, 17953), True, 'import datetime as dt\n'), ((21823, 21848), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(w * 7)'}), '(days=w * 7)\n', (21836, 21848), False, 'from dateutil.relativedelta import relativedelta\n'), ((24962, 24986), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'months': 'mn'}), '(months=mn)\n', (24975, 24986), False, 'from dateutil.relativedelta import relativedelta\n'), ((26644, 26670), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(dn - 1)'}), '(days=dn - 1)\n', (26657, 26670), False, 'from dateutil.relativedelta import relativedelta\n'), ((26915, 26935), 'datetime.timedelta', 'dt.timedelta', ([], {'days': '(4)'}), '(days=4)\n', (26927, 26935), True, 'import datetime as dt\n'), ((29127, 29147), 'datetime.timedelta', 'dt.timedelta', ([], {'days': '(4)'}), '(days=4)\n', (29139, 29147), True, 'import datetime as dt\n'), ((33945, 33969), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'months': 'mn'}), '(months=mn)\n', (33958, 33969), False, 'from dateutil.relativedelta import relativedelta\n'), ((35569, 35595), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(dn - 1)'}), '(days=dn - 1)\n', (35582, 35595), False, 'from dateutil.relativedelta import relativedelta\n'), ((35828, 35842), 'os.path.exists', 'exists', (['infile'], {}), '(infile)\n', (35834, 35842), False, 'from os.path import exists\n'), ((36446, 36460), 'os.path.exists', 'exists', (['infile'], {}), '(infile)\n', (36452, 36460), False, 'from os.path import exists\n'), ((36706, 36739), 'numpy.fromfile', 'np.fromfile', (['fr'], {'dtype': 'np.float32'}), '(fr, dtype=np.float32)\n', (36717, 36739), True, 'import numpy as np\n'), ((37674, 37701), 'netCDF4.Dataset', 'Dataset', (['(self.path + f_name)'], {}), '(self.path + f_name)\n', (37681, 37701), False, 'from netCDF4 import Dataset\n'), ((44600, 44624), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'months': 'mn'}), '(months=mn)\n', (44613, 44624), False, 'from dateutil.relativedelta import relativedelta\n'), ((6639, 6669), 'numpy.maximum', 'np.maximum', (['(p0 - self.tsmth)', '(0)'], {}), '(p0 - self.tsmth, 0)\n', (6649, 6669), True, 'import numpy as np\n'), ((8303, 8333), 'numpy.maximum', 'np.maximum', (['(p0 - self.tsmth)', '(0)'], {}), '(p0 - self.tsmth, 0)\n', (8313, 8333), True, 'import numpy as np\n'), ((9778, 9808), 'numpy.maximum', 'np.maximum', (['(p0 - self.tsmth)', '(0)'], {}), '(p0 - self.tsmth, 0)\n', (9788, 9808), True, 'import numpy as np\n'), ((15025, 15046), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (15038, 15046), False, 'from dateutil.relativedelta import relativedelta\n'), ((15088, 15109), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (15101, 15109), False, 'from dateutil.relativedelta import relativedelta\n'), ((16416, 16437), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (16429, 16437), False, 'from dateutil.relativedelta import relativedelta\n'), ((16479, 16500), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (16492, 16500), False, 'from dateutil.relativedelta import relativedelta\n'), ((19046, 19067), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (19059, 19067), False, 'from dateutil.relativedelta import relativedelta\n'), ((19109, 19130), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (19122, 19130), False, 'from dateutil.relativedelta import relativedelta\n'), ((20185, 20206), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (20198, 20206), False, 'from dateutil.relativedelta import relativedelta\n'), ((20248, 20269), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (20261, 20269), False, 'from dateutil.relativedelta import relativedelta\n'), ((27755, 27778), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'hours': '(12)'}), '(hours=12)\n', (27768, 27778), False, 'from dateutil.relativedelta import relativedelta\n'), ((27821, 27844), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'hours': '(36)'}), '(hours=36)\n', (27834, 27844), False, 'from dateutil.relativedelta import relativedelta\n'), ((30245, 30265), 'numpy.diff', 'np.diff', (['self.G.ypts'], {}), '(self.G.ypts)\n', (30252, 30265), True, 'import numpy as np\n'), ((30307, 30327), 'numpy.diff', 'np.diff', (['self.G.xpts'], {}), '(self.G.xpts)\n', (30314, 30327), True, 'import numpy as np\n'), ((31811, 31830), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {}), '(file)\n', (31824, 31830), True, 'import numpy as np\n'), ((32588, 32650), 'scipy.interpolate.griddata', 'griddata', (['xy', 'hi', '(self.G.xpts, self.G.ypts)'], {'method': '"""nearest"""'}), "(xy, hi, (self.G.xpts, self.G.ypts), method='nearest')\n", (32596, 32650), False, 'from scipy.interpolate import griddata\n'), ((32811, 32822), 'scipy.spatial.cKDTree', 'cKDTree', (['xy'], {}), '(xy)\n', (32818, 32822), False, 'from scipy.spatial import cKDTree\n'), ((32844, 32896), 'scipy.interpolate.interpnd._ndim_coords_from_arrays', '_ndim_coords_from_arrays', (['(self.G.xpts, self.G.ypts)'], {}), '((self.G.xpts, self.G.ypts))\n', (32868, 32896), False, 'from scipy.interpolate.interpnd import _ndim_coords_from_arrays\n'), ((2693, 2708), 'numpy.shape', 'np.shape', (['datau'], {}), '(datau)\n', (2701, 2708), True, 'import numpy as np\n'), ((5811, 5827), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (5821, 5827), True, 'import numpy as np\n'), ((6272, 6289), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (6280, 6289), True, 'import numpy as np\n'), ((6902, 6927), 'numpy.nanmean', 'np.nanmean', (['datau'], {'axis': '(0)'}), '(datau, axis=0)\n', (6912, 6927), True, 'import numpy as np\n'), ((6970, 6995), 'numpy.nanmean', 'np.nanmean', (['datav'], {'axis': '(0)'}), '(datav, axis=0)\n', (6980, 6995), True, 'import numpy as np\n'), ((7633, 7649), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (7643, 7649), True, 'import numpy as np\n'), ((8014, 8031), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (8022, 8031), True, 'import numpy as np\n'), ((8444, 8468), 'numpy.nanmean', 'np.nanmean', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (8454, 8468), True, 'import numpy as np\n'), ((9104, 9120), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (9114, 9120), True, 'import numpy as np\n'), ((9487, 9504), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (9495, 9504), True, 'import numpy as np\n'), ((9921, 9945), 'numpy.nanmean', 'np.nanmean', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (9931, 9945), True, 'import numpy as np\n'), ((15629, 15650), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (15642, 15650), False, 'from dateutil.relativedelta import relativedelta\n'), ((15696, 15717), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (15709, 15717), False, 'from dateutil.relativedelta import relativedelta\n'), ((17030, 17051), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (17043, 17051), False, 'from dateutil.relativedelta import relativedelta\n'), ((17097, 17118), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (17110, 17118), False, 'from dateutil.relativedelta import relativedelta\n'), ((18087, 18108), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (18100, 18108), False, 'from dateutil.relativedelta import relativedelta\n'), ((18154, 18175), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (18167, 18175), False, 'from dateutil.relativedelta import relativedelta\n'), ((19493, 19514), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (19506, 19514), False, 'from dateutil.relativedelta import relativedelta\n'), ((19560, 19581), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (19573, 19581), False, 'from dateutil.relativedelta import relativedelta\n'), ((20642, 20663), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (20655, 20663), False, 'from dateutil.relativedelta import relativedelta\n'), ((20709, 20730), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (20722, 20730), False, 'from dateutil.relativedelta import relativedelta\n'), ((21871, 21892), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (21884, 21892), False, 'from dateutil.relativedelta import relativedelta\n'), ((21938, 21959), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': '(3)'}), '(days=3)\n', (21951, 21959), False, 'from dateutil.relativedelta import relativedelta\n'), ((25258, 25285), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': 'mid_day'}), '(days=mid_day)\n', (25271, 25285), False, 'from dateutil.relativedelta import relativedelta\n'), ((26695, 26718), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'hours': '(12)'}), '(hours=12)\n', (26708, 26718), False, 'from dateutil.relativedelta import relativedelta\n'), ((26765, 26788), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'hours': '(36)'}), '(hours=36)\n', (26778, 26788), False, 'from dateutil.relativedelta import relativedelta\n'), ((28135, 28158), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'months': '(1)'}), '(months=1)\n', (28148, 28158), False, 'from dateutil.relativedelta import relativedelta\n'), ((28907, 28930), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'hours': '(12)'}), '(hours=12)\n', (28920, 28930), False, 'from dateutil.relativedelta import relativedelta\n'), ((28977, 29000), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'hours': '(36)'}), '(hours=36)\n', (28990, 29000), False, 'from dateutil.relativedelta import relativedelta\n'), ((32535, 32558), 'numpy.vstack', 'np.vstack', (['[xpts, ypts]'], {}), '([xpts, ypts])\n', (32544, 32558), True, 'import numpy as np\n'), ((34217, 34244), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': 'mid_day'}), '(days=mid_day)\n', (34230, 34244), False, 'from dateutil.relativedelta import relativedelta\n'), ((44875, 44902), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': 'mid_day'}), '(days=mid_day)\n', (44888, 44902), False, 'from dateutil.relativedelta import relativedelta\n'), ((1251, 1272), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': 'd'}), '(days=d)\n', (1264, 1272), False, 'from dateutil.relativedelta import relativedelta\n'), ((1418, 1433), 'numpy.shape', 'np.shape', (['dates'], {}), '(dates)\n', (1426, 1433), True, 'import numpy as np\n'), ((3971, 3992), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': 'd'}), '(days=d)\n', (3984, 3992), False, 'from dateutil.relativedelta import relativedelta\n'), ((4600, 4621), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': 'd'}), '(days=d)\n', (4613, 4621), False, 'from dateutil.relativedelta import relativedelta\n'), ((4945, 4966), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': 'd'}), '(days=d)\n', (4958, 4966), False, 'from dateutil.relativedelta import relativedelta\n'), ((5035, 5050), 'numpy.shape', 'np.shape', (['dates'], {}), '(dates)\n', (5043, 5050), True, 'import numpy as np\n'), ((12344, 12361), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (12352, 12361), True, 'import numpy as np\n'), ((14312, 14329), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (14320, 14329), True, 'import numpy as np\n'), ((18435, 18452), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (18443, 18452), True, 'import numpy as np\n'), ((22216, 22233), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (22224, 22233), True, 'import numpy as np\n'), ((26057, 26074), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (26065, 26074), True, 'import numpy as np\n'), ((27126, 27149), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'months': '(1)'}), '(months=1)\n', (27139, 27149), False, 'from dateutil.relativedelta import relativedelta\n'), ((27417, 27434), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (27425, 27434), True, 'import numpy as np\n'), ((29315, 29338), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'months': '(1)'}), '(months=1)\n', (29328, 29338), False, 'from dateutil.relativedelta import relativedelta\n'), ((35055, 35072), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (35063, 35072), True, 'import numpy as np\n'), ((35945, 35960), 'numpy.shape', 'np.shape', (['dates'], {}), '(dates)\n', (35953, 35960), True, 'import numpy as np\n'), ((37735, 37756), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': 'd'}), '(days=d)\n', (37748, 37756), False, 'from dateutil.relativedelta import relativedelta\n'), ((37915, 37930), 'numpy.shape', 'np.shape', (['dates'], {}), '(dates)\n', (37923, 37930), True, 'import numpy as np\n'), ((45713, 45730), 'numpy.shape', 'np.shape', (['dates_u'], {}), '(dates_u)\n', (45721, 45730), True, 'import numpy as np\n'), ((4322, 4343), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'days': 'd'}), '(days=d)\n', (4335, 4343), False, 'from dateutil.relativedelta import relativedelta\n')]
import numpy as np from anomaly import adm naive_filter = adm.NaiveFilter() def _test_fit(filter): ts = np.random.random(100) ts_predicted = np.random.random(100) anomalies = np.random.random(100) > 0.9 anomalies_predicted = anomalies & (np.random.random(100) > 0.9) filter.fit(ts, ts_predicted, anomalies, anomalies_predicted) def _test_filter(filter): ts = np.random.random(50) ts_predicted = np.random.random(50) anomalies_predicted = np.random.random(50) > 0.9 anomalies_filtered = filter.filter(ts, ts_predicted, anomalies_predicted) assert anomalies_filtered.shape == ts.shape def test_fit_naive(): _test_fit(naive_filter) def test_predict_naive(): _test_filter(naive_filter)
[ "anomaly.adm.NaiveFilter", "numpy.random.random" ]
[((59, 76), 'anomaly.adm.NaiveFilter', 'adm.NaiveFilter', ([], {}), '()\n', (74, 76), False, 'from anomaly import adm\n'), ((111, 132), 'numpy.random.random', 'np.random.random', (['(100)'], {}), '(100)\n', (127, 132), True, 'import numpy as np\n'), ((152, 173), 'numpy.random.random', 'np.random.random', (['(100)'], {}), '(100)\n', (168, 173), True, 'import numpy as np\n'), ((388, 408), 'numpy.random.random', 'np.random.random', (['(50)'], {}), '(50)\n', (404, 408), True, 'import numpy as np\n'), ((428, 448), 'numpy.random.random', 'np.random.random', (['(50)'], {}), '(50)\n', (444, 448), True, 'import numpy as np\n'), ((190, 211), 'numpy.random.random', 'np.random.random', (['(100)'], {}), '(100)\n', (206, 211), True, 'import numpy as np\n'), ((475, 495), 'numpy.random.random', 'np.random.random', (['(50)'], {}), '(50)\n', (491, 495), True, 'import numpy as np\n'), ((257, 278), 'numpy.random.random', 'np.random.random', (['(100)'], {}), '(100)\n', (273, 278), True, 'import numpy as np\n')]
import torch from torch import tensor import numpy as np from torch.utils.data import TensorDataset, DataLoader, ConcatDataset import os def mnist(): path = '/Users/davidipsen/Documents/DTU/3. Semester (MSc)/MLOps/dtu_mlops/data/corruptmnist/' # exchange with the corrupted mnist dataset #train = torch.randn(50000, 784) #test = torch.randn(10000, 784) # df0 = np.load(path + 'corruptmnist/train_0.npz') # Already normalized to [0, 1] # df1 = np.load(path + 'corruptmnist/train_1.npz') # df2 = np.load(path + 'corruptmnist/train_2.npz') # df3 = np.load(path + 'corruptmnist/train_3.npz') # df4 = np.load(path + 'corruptmnist/train_4.npz') # dftest = np.load(path + 'corruptmnist/test.npz') # test data # trainset0 = TensorDataset(tensor(df0['images']).reshape(-1,1,28,28).double(), tensor(df0['labels']).double()) # (X, y) of df0 # trainset1 = TensorDataset(tensor(df1['images']).reshape(-1,1,28,28).double(), tensor(df1['labels']).double()) # (X, y) of df0 # trainset2 = TensorDataset(tensor(df2['images']).reshape(-1,1,28,28).double(), tensor(df2['labels']).double()) # (X, y) of df0 # trainset3 = TensorDataset(tensor(df3['images']).reshape(-1,1,28,28).double(), tensor(df3['labels']).double()) # (X, y) of df0 # trainset4 = TensorDataset(tensor(df4['images']).reshape(-1,1,28,28).double(), tensor(df4['labels']).double()) # (X, y) of df0 # testset = TensorDataset(tensor(dftest['images']).reshape(-1,1,28,28).double(), tensor(dftest['labels']).double()) # (X, y) of df0 # trainset = ConcatDataset([trainset0, trainset1, trainset2, trainset3, trainset4]) traincontent = [] traindata = [] for i in range(5): traincontent.append(np.load(f"{path}train_{i}.npz", allow_pickle=True)) traindata = torch.tensor(np.concatenate([c["images"] for c in traincontent])).reshape( -1, 1, 28, 28 ) traintargets = torch.tensor(np.concatenate([c["labels"] for c in traincontent])) testcontent = np.load(f"{path}test.npz", allow_pickle=True) testdata = torch.tensor(testcontent["images"]).reshape(-1, 1, 28, 28) testtargets = torch.tensor(testcontent["labels"]) trainloader = DataLoader( (traindata, traintargets), batch_size=64, shuffle=True) testloader = DataLoader( (testdata, traintargets), batch_size=64, shuffle=True) return trainloader, testloader if __name__ == '__main__': mnist() print('Maiiiin')
[ "torch.utils.data.DataLoader", "numpy.load", "numpy.concatenate", "torch.tensor" ]
[((2006, 2051), 'numpy.load', 'np.load', (['f"""{path}test.npz"""'], {'allow_pickle': '(True)'}), "(f'{path}test.npz', allow_pickle=True)\n", (2013, 2051), True, 'import numpy as np\n'), ((2144, 2179), 'torch.tensor', 'torch.tensor', (["testcontent['labels']"], {}), "(testcontent['labels'])\n", (2156, 2179), False, 'import torch\n'), ((2200, 2266), 'torch.utils.data.DataLoader', 'DataLoader', (['(traindata, traintargets)'], {'batch_size': '(64)', 'shuffle': '(True)'}), '((traindata, traintargets), batch_size=64, shuffle=True)\n', (2210, 2266), False, 'from torch.utils.data import TensorDataset, DataLoader, ConcatDataset\n'), ((2285, 2350), 'torch.utils.data.DataLoader', 'DataLoader', (['(testdata, traintargets)'], {'batch_size': '(64)', 'shuffle': '(True)'}), '((testdata, traintargets), batch_size=64, shuffle=True)\n', (2295, 2350), False, 'from torch.utils.data import TensorDataset, DataLoader, ConcatDataset\n'), ((1934, 1985), 'numpy.concatenate', 'np.concatenate', (["[c['labels'] for c in traincontent]"], {}), "([c['labels'] for c in traincontent])\n", (1948, 1985), True, 'import numpy as np\n'), ((1731, 1781), 'numpy.load', 'np.load', (['f"""{path}train_{i}.npz"""'], {'allow_pickle': '(True)'}), "(f'{path}train_{i}.npz', allow_pickle=True)\n", (1738, 1781), True, 'import numpy as np\n'), ((2067, 2102), 'torch.tensor', 'torch.tensor', (["testcontent['images']"], {}), "(testcontent['images'])\n", (2079, 2102), False, 'import torch\n'), ((1812, 1863), 'numpy.concatenate', 'np.concatenate', (["[c['images'] for c in traincontent]"], {}), "([c['images'] for c in traincontent])\n", (1826, 1863), True, 'import numpy as np\n')]
################################################################################################################################ # General setup ################################################################################################################################ # Import libraries import sys import numpy as np from scipy.interpolate import interp1d, interp2d from scipy.integrate import romb, simpson, dblquad # Numerical parameters array_factor_est = 8 tol_residual_rho = 1e-88 dblquad_epsabs = 1e-3 dblquad_epsrel = 1e-3 num_interp_quad_specialized_ignore_yield = int(1e2) minimum_exponent = np.log(sys.float_info.min)/np.log(10) ################################################################################################################################ # Deformation application class ################################################################################################################################ class deform_network: ############################################################################################################################ # Initialization ############################################################################################################################ def __init__(self, F, deformation_type, total_time_in_seconds, single_chain_model, relaxation_function = None, J_sw = 1, \ max_F_dot = None, max_RAM_usage_in_bytes = None, nondimensional_timestep_suggestion = 1e-2, num_grid_suggestion = 129, \ interp_kind_2D = 'quintic', use_spatial_grid = True, enumerate_full_arrays = True, \ ignore_yield = False, ignore_reforming = False): # Initialize and retain certain variables self.csv_initialized = False self.ignore_yield = ignore_yield self.ignore_reforming = ignore_reforming self.use_spatial_grid = use_spatial_grid self.enumerate_full_arrays = enumerate_full_arrays self.initialized_single_chain_model = single_chain_model ######################################################################################################################## # Deformation ######################################################################################################################## # Retain certain variables self.F = F self.J_sw = J_sw self.deformation_type = deformation_type self.total_time_in_seconds = total_time_in_seconds # Estimate the maximum rate of deformation if not given if max_F_dot is None: t_temp = np.linspace(0, total_time_in_seconds, int(1e5)) self.max_F_dot = np.max(np.abs(np.diff(F(t_temp))/np.diff(t_temp))) else: self.max_F_dot = max_F_dot # If gamma_c specified, best method to use may change if single_chain_model.gamma_c is None: self.use_specialized = False else: self.use_specialized = True ######################################################################################################################## # Spatial discretization or quadrature ######################################################################################################################## # Spatial integration using a grid if use_spatial_grid is True: # Retain the 2D interpolation kind self.interp_kind_2D = interp_kind_2D # Create the symmetry-conscious spatial grid self.num_grid = self.adjust_for_romb(num_grid_suggestion) self.z = np.linspace(0, single_chain_model.gamma_TS, self.num_grid) self.r = self.z self.dz = self.z[1] - self.z[0] self.dr = self.dz self.Z, self.R = np.meshgrid(self.z, self.r) ELL = np.sqrt(self.Z*self.Z + self.R*self.R) # Integration element specialized for stress calculation self.ELEMENT_stress = self.element_stress(self.Z, self.R, single_chain_model) # Adjust normalization of P_A_eq on the grid P_A_eq_ELL_non_normalized = np.nan_to_num(single_chain_model.P_A_eq(ELL), nan = 0) self.P_A_eq_normalization = self.integral_grid_d_3_xi(P_A_eq_ELL_non_normalized)/single_chain_model.P_A_tot_eq # Total reverse reaction rate coefficient on the grid P_A_eq_ELL = np.nan_to_num(single_chain_model.P_A_eq(ELL, normalization = self.P_A_eq_normalization), nan = 0) self.k_ELL = np.nan_to_num(single_chain_model.k(ELL), nan = 0) if single_chain_model.gamma_c is None: self.K_hat = self.integral_grid_d_3_xi(self.k_ELL*P_A_eq_ELL)/single_chain_model.P_B_tot_eq else: self.K_hat = single_chain_model.K_hat # Maximum reverse reaction rate coefficient on the grid if single_chain_model.gamma_c is None: self.max_k_rev = np.max(self.k_ELL*P_A_eq_ELL/single_chain_model.P_B_tot_eq) else: self.max_k_rev = single_chain_model.max_k_rev # Spatial integration using quadrature else: # Inherit from single_chain_model since will use the same integration scheme self.P_A_eq_normalization = 1 self.k_0 = single_chain_model.k_0 self.K_hat = single_chain_model.K_hat self.max_k_rev = single_chain_model.max_k_rev ######################################################################################################################## # Relaxation function related setup ######################################################################################################################## if relaxation_function is None: self.g_timescale = np.inf self.g = lambda t, tau: 1 + 0*t + 0*tau self.d_g_d_tau = lambda t, tau: 0*t + 0*tau self.g_K_hat = np.exp(minimum_exponent) else: self.g_timescale = relaxation_function.timescale self.g = relaxation_function.g self.d_g_d_tau = relaxation_function.d_g_d_tau try: self.g_K_hat = single_chain_model.P_A_tot_eq/single_chain_model.P_B_tot_eq/self.g_timescale except AttributeError: self.g_K_hat = np.exp(minimum_exponent) ######################################################################################################################## # Time discretization ######################################################################################################################## # Estimate timestep based on the smallest timescales timescales = np.array([1/self.max_F_dot, 1/self.K_hat, 1/self.max_k_rev, self.g_timescale, 1/self.g_K_hat]) estimated_timestep = float(nondimensional_timestep_suggestion*np.min(timescales)) # Enumerating full arrays requires large memory, so have to do it in chunks rather than over the full history if use_spatial_grid is True: # Memory considerations if max_RAM_usage_in_bytes is None: import psutil max_RAM_usage_in_bytes = psutil.virtual_memory().available max_array_numel = max_RAM_usage_in_bytes/8/array_factor_est if enumerate_full_arrays is True: max_num_time_chunk = np.floor(np.sqrt(max_array_numel/self.num_grid**2)).astype(int) else: max_num_time_chunk = np.floor(max_array_numel/self.num_grid**2).astype(int) # Chunk history and decrease timestep in order to satisfy memory requirements and Romberg integration self.num_chunks = 0 self.num_time = 2*max_num_time_chunk while self.num_time > max_num_time_chunk: self.num_chunks += 1 self.num_time = self.adjust_for_romb(total_time_in_seconds/estimated_timestep/self.num_chunks) self.timestep = total_time_in_seconds/self.num_chunks/(self.num_time - 1) # Enumerate time limits for each chunk t_lims_all = total_time_in_seconds/self.num_chunks*np.arange(0, self.num_chunks + 1, 1) self.t_lims = np.zeros((self.num_chunks, 2)) for index_chunk in range(self.num_chunks): self.t_lims[index_chunk,:] = [t_lims_all[index_chunk], t_lims_all[index_chunk + 1]] # No memory considerations and corresponding history chunking since will not enumerate full arrays else: self.num_time = self.adjust_for_romb(total_time_in_seconds/estimated_timestep) self.timestep = total_time_in_seconds/(self.num_time - 1) ############################################################################################################################ # Function to solve for results over the applied deformation history ############################################################################################################################ def solve(self, display_progress = True, csv_directory = None, checkpoint_directory = None): # Methods using a grid for spatial integrals if self.use_spatial_grid is True: # Enumerate full arrays to mimimize computation time, chunking time history to satisfy memory requirements if self.enumerate_full_arrays is True: # Function to remove an initial point from results def remove_initial_point(results): results_out = list(results) for index in range(len(results)): results_out[index] = results[index][1:] return tuple(results_out) # Allocate results t = [] F = [] P_A_tot = [] total_rate_break = [] total_rate_reform = [] beta_sigma_over_n = [] # Loop over all chunks in the history for index_chunk in range(self.num_chunks): # Display progress if opted if display_progress is True: print(' On chunk', index_chunk + 1, 'of', self.num_chunks, end = '\r') # Equilibrium initial distribution for first chunk, or initial distribution from end of previous chunk if index_chunk == 0: results_chunk, P_A_end = self.compute_results_grid_chunky(self.t_lims[index_chunk,:]) else: results_chunk, P_A_end = self.compute_results_grid_chunky(self.t_lims[index_chunk,:], P_A_0 = P_A_end) # Remove repeated points in time among chunks if index_chunk > 0 or self.J_sw != 1 or self.initialized_single_chain_model.gamma_c is not None: results_chunk = remove_initial_point(results_chunk) # Collect results t = np.append(t, results_chunk[0]) F = np.append(F, results_chunk[1]) P_A_tot = np.append(P_A_tot, results_chunk[2]) total_rate_break = np.append(total_rate_break, results_chunk[3]) total_rate_reform = np.append(total_rate_reform, results_chunk[4]) beta_sigma_over_n = np.append(beta_sigma_over_n, results_chunk[5]) results = t, F, P_A_tot, total_rate_break, total_rate_reform, beta_sigma_over_n # Create a checkpoint .csv if opted after each chunk if checkpoint_directory is not None: checkpoint(checkpoint_directory).create(t[-1], P_A_end) # Refrain from enumerating full arrays but requires no history chunking, takes longer else: results, P_A_end = self.compute_results_grid([0, self.total_time_in_seconds]) # Methods using quadrature for spatial integrals else: # Efficient method in the special case for when k is constant and the single-chain model is infinitely-extensible if self.use_specialized is True and self.ignore_yield is True: results, P_A_end = self.compute_results_quad_specialized_ignore_yield([0, self.total_time_in_seconds]) # Method for the general case else: results, P_A_end = self.compute_results_quad([0, self.total_time_in_seconds]) # Append results to the .csv if opted if csv_directory is not None: if self.csv_initialized is False: results_csv_initialized = results_csv(csv_directory) self.csv_initialized = True results_csv_initialized.append(0, results) # Create a checkpoint .csv if opted if checkpoint_directory is not None: checkpoint(checkpoint_directory).create(t[-1], P_A_end) # Return the results return results ############################################################################################################################ # Function for computing results using spatial quadrature ############################################################################################################################ def compute_results_quad(self, t_span, P_A_0 = None): # Enumerate the time and relative deformation components t, F_zz_rel, F_rr_rel = self.enumerate_t_and_F_rel(t_span) total_time = t_span[-1] - t_span[0] num_time = len(t) # Function for the relatively-deformed coordinates def ell_rel(z, r, index_t, index_tau): return np.sqrt(z*z*F_zz_rel[index_t, index_tau]**2 + r*r*F_rr_rel[index_t, index_tau]**2) ######################################################################################################################## # Time-dependent quantities for spatial integrals ######################################################################################################################## # Function for the relatively-deformed initial distribution if P_A_0 is None: def P_A_0_rel_t(z, r, index_t): return self.initialized_single_chain_model.P_A_eq(ell_rel(z, r, index_t, 0)/self.J_sw**(1/3), \ normalization = self.P_A_eq_normalization*self.J_sw) else: sys.exit('Error: Beginning from a nonequilibrium initial distribution not yet implemented.') # Function for the relatively-deformed equilibrium distribution def P_A_eq_rel(z, r, index_t, index_tau): return self.initialized_single_chain_model.P_A_eq(ell_rel(z, r, index_t, index_tau), \ normalization = self.P_A_eq_normalization) # Function for the relatively-deformed reaction rate coefficient function def k_rel(z, r, index_t, index_tau): return self.initialized_single_chain_model.k(ell_rel(z, r, index_t, index_tau)) # Function for the reaction propagator def Xi(z, r, index_t, index_tau): if index_t == index_tau: return 1 + 0*(z + r) else: integrand = np.zeros((index_t + 1 - index_tau))*(z + r) for index_s in range(index_t + 1 - index_tau): integrand[:,:,index_s] = k_rel(z, r, index_t, index_s) return np.exp(-self.integral_ds(integrand)) # Function for the homogeneous solution for P_A def P_A_h(z, r, index_t): return np.nan_to_num(P_A_0_rel_t(z, r, index_t)*Xi(z, r, index_t, 0)*self.g(t[index_t], 0), nan = 0) # Function for the integrand of K def integrand_K(z, r, index_t, index_tau): return np.nan_to_num(P_A_eq_rel(z, r, index_t, index_tau)*Xi(z, r, index_t, index_tau)*( \ k_rel(z, r, index_t, index_tau)*self.g(t[index_t], t[index_tau]) \ + self.d_g_d_tau(t[index_t], t[index_tau])), nan = 0) ######################################################################################################################## # Solve the integral equation ######################################################################################################################## # Amount of initially-intact chains that have been broken P_B_tot_h = np.zeros(num_time) for index_t in range(num_time): P_B_tot_h[index_t] = 1 - self.integral_quad_d_3_xi(lambda z,r: P_A_h(z, r, index_t)) # Integral equation only defined when P_B_tot_eq is nonzero if self.initialized_single_chain_model.P_B_tot_eq > 0 and self.ignore_reforming is False: # Kernel K(t,tau) and right-hand side b(t) b = self.initialized_single_chain_model.P_B_tot_eq*P_B_tot_h K = np.zeros((num_time, num_time)) for index_t in range(num_time): for index_tau in range(index_t + 1): K[index_t, index_tau] = self.integral_quad_d_3_xi( \ lambda z,r: integrand_K(z, r, index_t, index_tau))/self.initialized_single_chain_model.P_B_tot_eq # Successive approximations to retrieve rho(t) rho = self.solve_Volterra(K, b, total_time) # Total probability of broken chains P_B_tot = self.initialized_single_chain_model.P_B_tot_eq*rho # Integral equation undefined when P_B_tot_eq = 0; also for rate-independent irreversible breaking else: P_B_tot = P_B_tot_h ######################################################################################################################## # Compute and return the results ######################################################################################################################## # Total probability of intact chains P_A_tot = 1 - P_B_tot # Distribution at the end of the partition P_A_end = np.nan # Total breaking and reforming rates total_rate_reform = self.K_hat*(1 - P_A_tot) total_rate_break = np.gradient(P_A_tot)/np.gradient(t) - total_rate_reform # Nondimensional stress corresponding to applied the deformation beta_sigma_h_over_n = np.zeros(num_time) beta_sigma_p_over_n = np.zeros(num_time) for index_t in range(num_time): beta_sigma_h_over_n[index_t] = self.integral_quad_d_3_xi(lambda z,r: P_A_h(z, r, index_t), element = 'stress') if self.initialized_single_chain_model.P_B_tot_eq > 0 and self.ignore_reforming is False: integrand_beta_sigma_p_over_n = np.zeros(num_time) for index_tau in range(index_t + 1): integrand_beta_sigma_p_over_n[index_tau] = rho[index_tau]*self.integral_quad_d_3_xi( \ lambda z,r: integrand_K(z, r, index_t, index_tau), element = 'stress') beta_sigma_p_over_n[index_t] = self.integral_d_tau(integrand_beta_sigma_p_over_n) beta_sigma_over_n = beta_sigma_h_over_n + beta_sigma_p_over_n # Return results results = t, self.F(t), P_A_tot, total_rate_break, total_rate_reform, beta_sigma_over_n return results, P_A_end ############################################################################################################################ # Function for computing results on a spatial grid ############################################################################################################################ def compute_results_grid(self, t_span, P_A_0 = None): # Enumerate the time and relative deformation components t, F_zz_rel, F_rr_rel = self.enumerate_t_and_F_rel(t_span) total_time = t_span[-1] - t_span[0] num_time = len(t) # Function for the relatively-deformed coordinates def ell_rel(index_t, index_tau): return np.sqrt(self.Z*self.Z*F_zz_rel[index_t, index_tau]**2 + self.R*self.R*F_rr_rel[index_t, index_tau]**2) ######################################################################################################################## # Time-dependent quantities for spatial integrals ######################################################################################################################## # Function for the relatively-deformed initial distribution if P_A_0 is None: def P_A_0_rel_t(index_t): return self.initialized_single_chain_model.P_A_eq(ell_rel(index_t, 0)/self.J_sw**(1/3), \ normalization = self.P_A_eq_normalization*self.J_sw) else: sys.exit('Error: Beginning from a nonequilibrium initial distribution not yet implemented.') # Function for the relatively-deformed equilibrium distribution def P_A_eq_rel(index_t, index_tau): return self.initialized_single_chain_model.P_A_eq(ell_rel(index_t, index_tau), \ normalization = self.P_A_eq_normalization) # Function for the relatively-deformed reaction rate coefficient function def k_rel(index_t, index_tau): return self.initialized_single_chain_model.k(ell_rel(index_t, index_tau)) # Function for the reaction propagator def Xi(index_t, index_tau): if index_t == index_tau: return np.ones((self.num_grid, self.num_grid)) else: integrand = np.zeros((self.num_grid, self.num_grid, index_t + 1 - index_tau)) for index_s in range(index_t + 1 - index_tau): integrand[:,:,index_s] = k_rel(index_t, index_s) return np.exp(-self.integral_ds(integrand)) # Function for the homogeneous solution for P_A def P_A_h(index_t): out = P_A_0_rel_t(index_t)*Xi(index_t, 0)*self.g(t[index_t], 0) out[np.isnan(out) + np.isinf(out)] = 0 return out # Function for the integrand of K def integrand_K(index_t, index_tau): out = P_A_eq_rel(index_t, index_tau)*Xi(index_t, index_tau)*( \ k_rel(index_t, index_tau)*self.g(t[index_t], t[index_tau]) + self.d_g_d_tau(t[index_t], t[index_tau])) out[np.isnan(out) + np.isinf(out)] = 0 return out ######################################################################################################################## # Solve the integral equation ######################################################################################################################## # Amount of initially-intact chains that have been broken P_B_tot_h = np.zeros(num_time) for index_t in range(num_time): P_B_tot_h[index_t] = 1 - self.integral_grid_d_3_xi(P_A_h(index_t)) # Integral equation only defined when P_B_tot_eq is nonzero if self.initialized_single_chain_model.P_B_tot_eq > 0 and self.ignore_reforming is False: # Kernel K(t,tau) and right-hand side b(t) b = self.initialized_single_chain_model.P_B_tot_eq*P_B_tot_h K = np.zeros((num_time, num_time)) for index_t in range(num_time): for index_tau in range(index_t + 1): K[index_t, index_tau] = \ self.integral_grid_d_3_xi(integrand_K(index_t,index_tau))/self.initialized_single_chain_model.P_B_tot_eq # Successive approximations to retrieve rho(t) rho = self.solve_Volterra(K, b, total_time) # Total probability of broken chains P_B_tot = self.initialized_single_chain_model.P_B_tot_eq*rho # Integral equation undefined when P_B_tot_eq = 0; also for rate-independent irreversible breaking else: P_B_tot = P_B_tot_h ######################################################################################################################## # Compute and return the results ######################################################################################################################## # Total probability of intact chains P_A_tot = 1 - P_B_tot # Distribution at the end of the partition P_A_end = np.nan # Total breaking and reforming rates total_rate_reform = self.K_hat*(1 - P_A_tot) total_rate_break = np.gradient(P_A_tot)/np.gradient(t) - total_rate_reform # Nondimensional stress corresponding to applied the deformation beta_sigma_h_over_n = np.zeros(num_time) beta_sigma_p_over_n = np.zeros(num_time) for index_t in range(num_time): beta_sigma_h_over_n[index_t] = self.integral_grid_d_3_xi(P_A_h(index_t), element = 'stress') if self.initialized_single_chain_model.P_B_tot_eq > 0 and self.ignore_reforming is False: integrand_beta_sigma_p_over_n = np.zeros(num_time) for index_tau in range(index_t + 1): integrand_beta_sigma_p_over_n[index_tau] = \ rho[index_tau]*self.integral_grid_d_3_xi(integrand_K(index_t, index_tau), element = 'stress') beta_sigma_p_over_n[index_t] = self.integral_d_tau(integrand_beta_sigma_p_over_n) beta_sigma_over_n = beta_sigma_h_over_n + beta_sigma_p_over_n # Return results results = t, self.F(t), P_A_tot, total_rate_break, total_rate_reform, beta_sigma_over_n return results, P_A_end ############################################################################################################################ # Function for computing results on a spatial grid; enumerates full arrays and uses vectorized operations ############################################################################################################################ def compute_results_grid_chunky(self, t_span, P_A_0 = None): # Enumerate the time and relative deformation components t, F_zz_rel, F_rr_rel = self.enumerate_t_and_F_rel(t_span) total_time = t_span[-1] - t_span[0] num_time = len(t) Delta_t = t - t[0] # Enumerate the relatively-deformed coordinates Z_rel = np.tensordot(self.Z, F_zz_rel, axes = 0) R_rel = np.tensordot(self.R, F_rr_rel, axes = 0) ELL_rel = np.sqrt(Z_rel*Z_rel + R_rel*R_rel) z_rel_t = np.tensordot(self.z, F_zz_rel[:,0], axes = 0) r_rel_t = np.tensordot(self.r, F_rr_rel[:,0], axes = 0) # Cleanup del F_zz_rel, F_rr_rel, Z_rel, R_rel ######################################################################################################################## # Time-dependent quantities for spatial integrals ######################################################################################################################## # Enumerate the relatively-deformed equilibrium distribution P_A_eq_rel = self.initialized_single_chain_model.P_A_eq(ELL_rel, normalization = self.P_A_eq_normalization) # Enumerate the relatively-deformed initial distribution if P_A_0 is None: P_A_0_rel_t = self.initialized_single_chain_model.P_A_eq(ELL_rel[:,:,:,0]/self.J_sw**(1/3), \ normalization = self.P_A_eq_normalization*self.J_sw) else: P_A_0_rel_t = np.zeros((self.num_grid, self.num_grid, num_time)) for index_t in range(num_time): P_A_0_rel_t[:,:,index_t] = self.interp_fun_2D(z_rel_t[:,index_t], r_rel_t[:,index_t], P_A_0) # Cleanup del z_rel_t, r_rel_t # Enumerate the relatively-deformed reaction rate coefficient function k_rel = self.initialized_single_chain_model.k(ELL_rel) # Cleanup del ELL_rel # Enumerate the reaction propagator Xi = np.zeros((self.num_grid, self.num_grid, num_time, num_time)) for index_t in range(num_time): for index_tau in range(index_t + 1): Xi[:,:,index_t,index_tau] = \ np.exp(-self.integral_ds(k_rel[:,:,index_t,index_tau:index_t + 1])) # Enumerate the relaxation function and its derivative g = np.zeros((num_time, num_time)) d_g_d_tau = np.zeros((num_time, num_time)) for index_t in range(num_time): for index_tau in range(index_t + 1): g[index_t, index_tau] = self.g(Delta_t[index_t], Delta_t[index_tau]) d_g_d_tau[index_t, index_tau] = self.d_g_d_tau(Delta_t[index_t], Delta_t[index_tau]) # Homogeneous solution for P_A P_A_h = Xi[:,:,:,0]*P_A_0_rel_t # Cleanup del P_A_0_rel_t # Integrand of K if self.initialized_single_chain_model.gamma_c is not None: k_rel[np.isinf(k_rel)] = 0 integrand_K = P_A_eq_rel*Xi*(k_rel*g[None,None,:,:] + d_g_d_tau[None,None,:,:]) # Cleanup del Xi, k_rel, P_A_eq_rel # P_A_h[np.isnan(P_A_h) + np.isinf(P_A_h)] = 0 integrand_K[np.isnan(integrand_K) + np.isinf(integrand_K)] = 0 ######################################################################################################################## # Solve the integral equation ######################################################################################################################## # Amount of initially-intact chains that have been broken P_B_tot_h = 1 - self.integral_grid_d_3_xi(P_A_h) # Integral equation only defined when P_B_tot_eq is nonzero if self.initialized_single_chain_model.P_B_tot_eq > 0 and self.ignore_reforming is False: # Kernel K(t,tau) and right-hand side b(t) K = self.integral_grid_d_3_xi(integrand_K)/self.initialized_single_chain_model.P_B_tot_eq b = P_B_tot_h/self.initialized_single_chain_model.P_B_tot_eq # Successive approximations to retrieve rho(t) rho = self.solve_Volterra(K, b, total_time) # Total probability of broken chains P_B_tot = self.initialized_single_chain_model.P_B_tot_eq*rho # Integral equation undefined when P_B_tot_eq = 0; also for rate-independent irreversible breaking else: P_B_tot = P_B_tot_h rho = np.zeros(num_time) # Integrand of particular solution for P_A integrand_P_A_p = rho*integrand_K # Cleanup del integrand_K ######################################################################################################################## # Compute and return the results ######################################################################################################################## # Total probability of intact chains P_A_tot = 1 - P_B_tot # Distribution of intact chains P_A = P_A_h + self.integral_d_tau(integrand_P_A_p) # Cleanup del P_A_h, integrand_P_A_p # Distribution at the end of the partition P_A_end = P_A[:,:,-1] # Total breaking and reforming rates total_rate_break = -self.integral_grid_d_3_xi(P_A*self.k_ELL[:,:,None]) total_rate_reform = self.K_hat*(1 - P_A_tot) # Nondimensional stress corresponding to the applied deformation beta_sigma_over_n = self.integral_grid_d_3_xi(P_A, element = 'stress') # Return results results = t, self.F(t), P_A_tot, total_rate_break, total_rate_reform, beta_sigma_over_n return results, P_A_end ############################################################################################################################ # Function for (one with k0 AND ignores yield) ############################################################################################################################ def compute_results_quad_specialized_ignore_yield(self, t_span): # Enumerate the time and relative deformation components t, F_zz_rel, F_rr_rel = self.enumerate_t_and_F_rel(t_span) # Function for the relatively-deformed coordinates def ell_rel(z, r, index_t, index_tau): return np.sqrt(z*z*F_zz_rel[index_t, index_tau]**2 + r*r*F_rr_rel[index_t, index_tau]**2) ######################################################################################################################## # Time-dependent quantities for spatial integrals ######################################################################################################################## # Function for the relatively-deformed equilibrium distribution def P_A_eq_rel(z, r, index_t, index_tau): return np.nan_to_num(self.initialized_single_chain_model.P_A_eq(ell_rel(z, r, index_t, index_tau)/self.J_sw**(1/3),\ normalization = self.P_A_eq_normalization*self.J_sw), nan = 0) # Function for the reaction propagator def Xi(t, tau): return np.exp(-self.k_0*(t - tau)) # Function for relative time derivative of the reaction propagator def d_Xi_d_tau(t, tau): return Xi(t, tau)*self.k_0 ######################################################################################################################## # Compute stress only at unique deformations to interpolate from ######################################################################################################################## # Choose deformation for stress response based on deformation mode if self.deformation_type == 'uniaxial': F_use = F_zz_rel # Store a limited number of unique deformations over the history F_unique = np.unique(F_use) indices = np.unique(np.round(np.linspace(0, len(F_unique) - 1, num_interp_quad_specialized_ignore_yield)).astype(int)) F_store = F_unique[indices] # Compute the stress at these deformations to interpolate from beta_sigma_h0_over_n = np.zeros(len(F_store)) for index in range(len(F_store)): index_t, index_tau = np.argwhere(F_store[index] == F_use)[0] beta_sigma_h0_over_n[index] = \ self.integral_quad_d_3_xi(lambda z,r: P_A_eq_rel(z, r, index_t, index_tau), element = 'stress') ######################################################################################################################## # Compute and return the results ######################################################################################################################## # Function to interpolate from computed stress response interp_sigma_fun = interp1d(F_store, beta_sigma_h0_over_n, kind = 'cubic', bounds_error = True) # Homogeneous solution for the nondimensional stress beta_sigma_h_over_n = self.g(t, 0)*Xi(t, 0)*interp_sigma_fun(F_zz_rel[:,0]) # Particular solution for the nondimensional stress beta_sigma_p_over_n = np.zeros(self.num_time) for index_t in range(self.num_time): integrand = interp_sigma_fun(F_zz_rel[index_t,:index_t + 1])*( \ Xi(t[index_t], t[:index_t + 1])*self.d_g_d_tau(t[index_t], t[:index_t + 1]) \ + d_Xi_d_tau(t[index_t], t[:index_t + 1])*self.g(t[index_t], t[:index_t + 1])) beta_sigma_p_over_n[index_t] = self.integral_d_tau(np.append(integrand, np.zeros(self.num_time - 1 - index_t))) # Return results beta_sigma_over_n = beta_sigma_h_over_n + beta_sigma_p_over_n P_A_tot = self.initialized_single_chain_model.P_A_tot_eq*np.ones(self.num_time) total_rate_reform = self.K_hat*(1 - P_A_tot) total_rate_break = -total_rate_reform results = t, self.F(t), P_A_tot, beta_sigma_h_over_n, beta_sigma_p_over_n, beta_sigma_over_n return results, np.nan ############################################################################################################################ # Function to adjust discretization for Romberg integration ############################################################################################################################ def adjust_for_romb(self, num_discretization, decrease = False): if ((np.log(num_discretization - 1)/np.log(2)).is_integer()): return int(round(num_discretization)) else: n = 0 dos_check = 3 while dos_check >= 2: n += 1 dos_check = (num_discretization - 1)**(1/n) if decrease is True and dos_check < 2: return int(1 + 2**(n - 1)) else: return int(1 + 2**n) ############################################################################################################################ # Function for integration over the spatial grid ############################################################################################################################ def integral_grid_d_3_xi(self, FUN, element = None): if element is None: element = self.R elif element == 'stress': element = self.ELEMENT_stress if FUN.ndim == 2: return 4*np.pi*romb(romb(FUN*element, dx = self.dr, axis = 0), dx = self.dz, axis = 0) elif FUN.ndim == 3: return 4*np.pi*romb(romb(FUN*element[:,:,None], dx = self.dr, axis = 0), dx = self.dz, axis = 0) elif FUN.ndim == 4: return 4*np.pi*romb(romb(FUN*element[:,:,None,None], dx = self.dr, axis = 0), dx = self.dz, axis = 0) ############################################################################################################################ # Function for integration over continuous space ############################################################################################################################ def integral_quad_d_3_xi(self, fun, element = None): if element is None: def integrand(z, r): return fun(z, r)*r elif element == 'stress': def integrand(z, r): return fun(z, r)*self.element_stress(z, r, self.initialized_single_chain_model) if self.initialized_single_chain_model.gamma_c is None: lim = self.initialized_single_chain_model.gamma_TS else: lim = self.initialized_single_chain_model.gamma_c return 4*np.pi*dblquad(integrand, 0, lim, lambda r: 0, lambda r: np.sqrt(lim**2 - r**2), \ epsabs = dblquad_epsabs, epsrel = dblquad_epsrel)[0] ############################################################################################################################ # Function for integration element specialized for stress calculation ############################################################################################################################ def element_stress(self, z, r, single_chain_model): ell = np.sqrt(z*z + r*r) eta = np.nan_to_num(single_chain_model.eta(ell), nan = 0) if isinstance(z, np.ndarray): eta_over_ell = np.zeros(z.shape) eta_over_ell[ell != 0] = eta[ell != 0]/ell[ell != 0] else: if ell == 0: eta_over_ell = 0 else: eta_over_ell = eta/ell C = (single_chain_model.N_b + single_chain_model.varsigma*single_chain_model.N_b_H)/self.J_sw if self.deformation_type == 'uniaxial': return C*eta_over_ell*r*(z*z - r*r/2) elif self.deformation_type == 'equibiaxial' or deformation_type == 'simple_shear': return C*eta_over_ell*r*(r*r/2 - z*z) ############################################################################################################################ # Function to interpolate from a stored 2D function on the spatial grid ############################################################################################################################ def interp_fun_2D(self, z_query, r_query, FUN): return interp2d(self.z, self.r, FUN, kind = self.interp_kind_2D)(z_query, r_query) ############################################################################################################################ # Functions for integration in time ############################################################################################################################ def integral_ds(self, FUN): return simpson(FUN, dx = self.timestep, axis = -1, even = 'last') def integral_d_tau(self, FUN): return romb(FUN, dx = self.timestep, axis = -1) ############################################################################################################################ # Function to enumerate the time and relative deformation ############################################################################################################################ def enumerate_t_and_F_rel(self, t_span): # Enumerate the time t = np.linspace(t_span[0], t_span[-1], self.num_time) # Relative deformation gradient components if self.deformation_type == 'uniaxial': F_zz_rel = np.tensordot(1/self.F(t), self.F(t), axes = 0) F_rr_rel = np.tensordot(np.sqrt(self.F(t)), 1/np.sqrt(self.F(t)), axes = 0) elif self.deformation_type == 'equibiaxial': F_zz_rel = np.tensordot(self.F(t), 1/self.F(t), axes = 0) F_rr_rel = np.tensordot(1/self.F(t), self.F(t), axes = 0) elif self.deformation_type == 'simple_shear': pass return t, F_zz_rel, F_rr_rel ############################################################################################################################ # Function to solve the Volterra integral equation ############################################################################################################################ def solve_Volterra(self, K, b, total_time): M = 0 rho = b residual_bound_rho = 1 while residual_bound_rho > tol_residual_rho: M += 1 rho = b - self.integral_d_tau(K*rho) residual_bound_rho = \ (self.K_hat*total_time)**(M + 1)/self.initialized_single_chain_model.P_B_tot_eq/np.math.factorial(M + 1) return rho ################################################################################################################################ # Checkpoint creation class ################################################################################################################################ class checkpoint: # Initialization also clears any previous checkpoint def __init__(self, checkpoint_directory): self.checkpoint_directory_and_file = checkpoint_directory + 'checkpoint.csv' open(self.checkpoint_directory_and_file, 'w').close() # Function to create checkpoints def create(self, t_end, P_A_end): f = open(self.checkpoint_directory_and_file, 'a') f.write("%.8e" % t_end) for i in range(len(P_A_end[:,0])): f.write("\n") for j in range(len(P_A_end[0,:])): f.write("%.8e\t" % P_A_end[i,j]) f.close() # Function to read checkpoints def read(self, existing_checkpoint_directory_and_file): pass ################################################################################################################################ # Results writing class ################################################################################################################################ class results_csv: # Initialization also clears any previous results def __init__(self, csv_directory): self.csv_directory_and_file = csv_directory + 'results.csv' open(self.csv_directory_and_file, "w").close() # Function to append results def append(self, index_chunk, results): f = open(self.csv_directory_and_file, "a") for index_t in range(len(results[0])): for index_results in range(len(results)): f.write("%.8e\t" % results[index_results][index_t]) f.write("\n") f.close()
[ "psutil.virtual_memory", "numpy.floor", "numpy.ones", "numpy.isnan", "numpy.arange", "numpy.exp", "scipy.interpolate.interp1d", "numpy.unique", "numpy.meshgrid", "scipy.integrate.romb", "numpy.append", "numpy.max", "numpy.linspace", "numpy.tensordot", "numpy.isinf", "scipy.interpolate.interp2d", "numpy.min", "numpy.argwhere", "scipy.integrate.simpson", "sys.exit", "numpy.log", "numpy.zeros", "numpy.diff", "numpy.array", "numpy.math.factorial", "numpy.gradient", "numpy.sqrt" ]
[((625, 651), 'numpy.log', 'np.log', (['sys.float_info.min'], {}), '(sys.float_info.min)\n', (631, 651), True, 'import numpy as np\n'), ((652, 662), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (658, 662), True, 'import numpy as np\n'), ((6187, 6294), 'numpy.array', 'np.array', (['[1 / self.max_F_dot, 1 / self.K_hat, 1 / self.max_k_rev, self.g_timescale, \n 1 / self.g_K_hat]'], {}), '([1 / self.max_F_dot, 1 / self.K_hat, 1 / self.max_k_rev, self.\n g_timescale, 1 / self.g_K_hat])\n', (6195, 6294), True, 'import numpy as np\n'), ((14706, 14724), 'numpy.zeros', 'np.zeros', (['num_time'], {}), '(num_time)\n', (14714, 14724), True, 'import numpy as np\n'), ((16432, 16450), 'numpy.zeros', 'np.zeros', (['num_time'], {}), '(num_time)\n', (16440, 16450), True, 'import numpy as np\n'), ((16476, 16494), 'numpy.zeros', 'np.zeros', (['num_time'], {}), '(num_time)\n', (16484, 16494), True, 'import numpy as np\n'), ((20449, 20467), 'numpy.zeros', 'np.zeros', (['num_time'], {}), '(num_time)\n', (20457, 20467), True, 'import numpy as np\n'), ((22137, 22155), 'numpy.zeros', 'np.zeros', (['num_time'], {}), '(num_time)\n', (22145, 22155), True, 'import numpy as np\n'), ((22181, 22199), 'numpy.zeros', 'np.zeros', (['num_time'], {}), '(num_time)\n', (22189, 22199), True, 'import numpy as np\n'), ((23667, 23705), 'numpy.tensordot', 'np.tensordot', (['self.Z', 'F_zz_rel'], {'axes': '(0)'}), '(self.Z, F_zz_rel, axes=0)\n', (23679, 23705), True, 'import numpy as np\n'), ((23719, 23757), 'numpy.tensordot', 'np.tensordot', (['self.R', 'F_rr_rel'], {'axes': '(0)'}), '(self.R, F_rr_rel, axes=0)\n', (23731, 23757), True, 'import numpy as np\n'), ((23773, 23811), 'numpy.sqrt', 'np.sqrt', (['(Z_rel * Z_rel + R_rel * R_rel)'], {}), '(Z_rel * Z_rel + R_rel * R_rel)\n', (23780, 23811), True, 'import numpy as np\n'), ((23821, 23865), 'numpy.tensordot', 'np.tensordot', (['self.z', 'F_zz_rel[:, 0]'], {'axes': '(0)'}), '(self.z, F_zz_rel[:, 0], axes=0)\n', (23833, 23865), True, 'import numpy as np\n'), ((23880, 23924), 'numpy.tensordot', 'np.tensordot', (['self.r', 'F_rr_rel[:, 0]'], {'axes': '(0)'}), '(self.r, F_rr_rel[:, 0], axes=0)\n', (23892, 23924), True, 'import numpy as np\n'), ((25166, 25226), 'numpy.zeros', 'np.zeros', (['(self.num_grid, self.num_grid, num_time, num_time)'], {}), '((self.num_grid, self.num_grid, num_time, num_time))\n', (25174, 25226), True, 'import numpy as np\n'), ((25479, 25509), 'numpy.zeros', 'np.zeros', (['(num_time, num_time)'], {}), '((num_time, num_time))\n', (25487, 25509), True, 'import numpy as np\n'), ((25525, 25555), 'numpy.zeros', 'np.zeros', (['(num_time, num_time)'], {}), '((num_time, num_time))\n', (25533, 25555), True, 'import numpy as np\n'), ((30600, 30616), 'numpy.unique', 'np.unique', (['F_use'], {}), '(F_use)\n', (30609, 30616), True, 'import numpy as np\n'), ((31495, 31567), 'scipy.interpolate.interp1d', 'interp1d', (['F_store', 'beta_sigma_h0_over_n'], {'kind': '"""cubic"""', 'bounds_error': '(True)'}), "(F_store, beta_sigma_h0_over_n, kind='cubic', bounds_error=True)\n", (31503, 31567), False, 'from scipy.interpolate import interp1d, interp2d\n'), ((31791, 31814), 'numpy.zeros', 'np.zeros', (['self.num_time'], {}), '(self.num_time)\n', (31799, 31814), True, 'import numpy as np\n'), ((35452, 35474), 'numpy.sqrt', 'np.sqrt', (['(z * z + r * r)'], {}), '(z * z + r * r)\n', (35459, 35474), True, 'import numpy as np\n'), ((36861, 36913), 'scipy.integrate.simpson', 'simpson', (['FUN'], {'dx': 'self.timestep', 'axis': '(-1)', 'even': '"""last"""'}), "(FUN, dx=self.timestep, axis=-1, even='last')\n", (36868, 36913), False, 'from scipy.integrate import romb, simpson, dblquad\n'), ((36965, 37001), 'scipy.integrate.romb', 'romb', (['FUN'], {'dx': 'self.timestep', 'axis': '(-1)'}), '(FUN, dx=self.timestep, axis=-1)\n', (36969, 37001), False, 'from scipy.integrate import romb, simpson, dblquad\n'), ((37400, 37449), 'numpy.linspace', 'np.linspace', (['t_span[0]', 't_span[-1]', 'self.num_time'], {}), '(t_span[0], t_span[-1], self.num_time)\n', (37411, 37449), True, 'import numpy as np\n'), ((3403, 3461), 'numpy.linspace', 'np.linspace', (['(0)', 'single_chain_model.gamma_TS', 'self.num_grid'], {}), '(0, single_chain_model.gamma_TS, self.num_grid)\n', (3414, 3461), True, 'import numpy as np\n'), ((3561, 3588), 'numpy.meshgrid', 'np.meshgrid', (['self.z', 'self.r'], {}), '(self.z, self.r)\n', (3572, 3588), True, 'import numpy as np\n'), ((3599, 3641), 'numpy.sqrt', 'np.sqrt', (['(self.Z * self.Z + self.R * self.R)'], {}), '(self.Z * self.Z + self.R * self.R)\n', (3606, 3641), True, 'import numpy as np\n'), ((5486, 5510), 'numpy.exp', 'np.exp', (['minimum_exponent'], {}), '(minimum_exponent)\n', (5492, 5510), True, 'import numpy as np\n'), ((7527, 7557), 'numpy.zeros', 'np.zeros', (['(self.num_chunks, 2)'], {}), '((self.num_chunks, 2))\n', (7535, 7557), True, 'import numpy as np\n'), ((12247, 12346), 'numpy.sqrt', 'np.sqrt', (['(z * z * F_zz_rel[index_t, index_tau] ** 2 + r * r * F_rr_rel[index_t,\n index_tau] ** 2)'], {}), '(z * z * F_zz_rel[index_t, index_tau] ** 2 + r * r * F_rr_rel[\n index_t, index_tau] ** 2)\n', (12254, 12346), True, 'import numpy as np\n'), ((12928, 13030), 'sys.exit', 'sys.exit', (['"""Error: Beginning from a nonequilibrium initial distribution not yet implemented."""'], {}), "(\n 'Error: Beginning from a nonequilibrium initial distribution not yet implemented.'\n )\n", (12936, 13030), False, 'import sys\n'), ((15129, 15159), 'numpy.zeros', 'np.zeros', (['(num_time, num_time)'], {}), '((num_time, num_time))\n', (15137, 15159), True, 'import numpy as np\n'), ((17954, 18073), 'numpy.sqrt', 'np.sqrt', (['(self.Z * self.Z * F_zz_rel[index_t, index_tau] ** 2 + self.R * self.R * \n F_rr_rel[index_t, index_tau] ** 2)'], {}), '(self.Z * self.Z * F_zz_rel[index_t, index_tau] ** 2 + self.R * self\n .R * F_rr_rel[index_t, index_tau] ** 2)\n', (17961, 18073), True, 'import numpy as np\n'), ((18643, 18745), 'sys.exit', 'sys.exit', (['"""Error: Beginning from a nonequilibrium initial distribution not yet implemented."""'], {}), "(\n 'Error: Beginning from a nonequilibrium initial distribution not yet implemented.'\n )\n", (18651, 18745), False, 'import sys\n'), ((20854, 20884), 'numpy.zeros', 'np.zeros', (['(num_time, num_time)'], {}), '((num_time, num_time))\n', (20862, 20884), True, 'import numpy as np\n'), ((24729, 24779), 'numpy.zeros', 'np.zeros', (['(self.num_grid, self.num_grid, num_time)'], {}), '((self.num_grid, self.num_grid, num_time))\n', (24737, 24779), True, 'import numpy as np\n'), ((27385, 27403), 'numpy.zeros', 'np.zeros', (['num_time'], {}), '(num_time)\n', (27393, 27403), True, 'import numpy as np\n'), ((29141, 29240), 'numpy.sqrt', 'np.sqrt', (['(z * z * F_zz_rel[index_t, index_tau] ** 2 + r * r * F_rr_rel[index_t,\n index_tau] ** 2)'], {}), '(z * z * F_zz_rel[index_t, index_tau] ** 2 + r * r * F_rr_rel[\n index_t, index_tau] ** 2)\n', (29148, 29240), True, 'import numpy as np\n'), ((29904, 29933), 'numpy.exp', 'np.exp', (['(-self.k_0 * (t - tau))'], {}), '(-self.k_0 * (t - tau))\n', (29910, 29933), True, 'import numpy as np\n'), ((32354, 32376), 'numpy.ones', 'np.ones', (['self.num_time'], {}), '(self.num_time)\n', (32361, 32376), True, 'import numpy as np\n'), ((35584, 35601), 'numpy.zeros', 'np.zeros', (['z.shape'], {}), '(z.shape)\n', (35592, 35601), True, 'import numpy as np\n'), ((36448, 36503), 'scipy.interpolate.interp2d', 'interp2d', (['self.z', 'self.r', 'FUN'], {'kind': 'self.interp_kind_2D'}), '(self.z, self.r, FUN, kind=self.interp_kind_2D)\n', (36456, 36503), False, 'from scipy.interpolate import interp1d, interp2d\n'), ((4598, 4661), 'numpy.max', 'np.max', (['(self.k_ELL * P_A_eq_ELL / single_chain_model.P_B_tot_eq)'], {}), '(self.k_ELL * P_A_eq_ELL / single_chain_model.P_B_tot_eq)\n', (4604, 4661), True, 'import numpy as np\n'), ((6347, 6365), 'numpy.min', 'np.min', (['timescales'], {}), '(timescales)\n', (6353, 6365), True, 'import numpy as np\n'), ((7472, 7508), 'numpy.arange', 'np.arange', (['(0)', '(self.num_chunks + 1)', '(1)'], {}), '(0, self.num_chunks + 1, 1)\n', (7481, 7508), True, 'import numpy as np\n'), ((16281, 16301), 'numpy.gradient', 'np.gradient', (['P_A_tot'], {}), '(P_A_tot)\n', (16292, 16301), True, 'import numpy as np\n'), ((16302, 16316), 'numpy.gradient', 'np.gradient', (['t'], {}), '(t)\n', (16313, 16316), True, 'import numpy as np\n'), ((16776, 16794), 'numpy.zeros', 'np.zeros', (['num_time'], {}), '(num_time)\n', (16784, 16794), True, 'import numpy as np\n'), ((19284, 19323), 'numpy.ones', 'np.ones', (['(self.num_grid, self.num_grid)'], {}), '((self.num_grid, self.num_grid))\n', (19291, 19323), True, 'import numpy as np\n'), ((19351, 19416), 'numpy.zeros', 'np.zeros', (['(self.num_grid, self.num_grid, index_t + 1 - index_tau)'], {}), '((self.num_grid, self.num_grid, index_t + 1 - index_tau))\n', (19359, 19416), True, 'import numpy as np\n'), ((21986, 22006), 'numpy.gradient', 'np.gradient', (['P_A_tot'], {}), '(P_A_tot)\n', (21997, 22006), True, 'import numpy as np\n'), ((22007, 22021), 'numpy.gradient', 'np.gradient', (['t'], {}), '(t)\n', (22018, 22021), True, 'import numpy as np\n'), ((22463, 22481), 'numpy.zeros', 'np.zeros', (['num_time'], {}), '(num_time)\n', (22471, 22481), True, 'import numpy as np\n'), ((25996, 26011), 'numpy.isinf', 'np.isinf', (['k_rel'], {}), '(k_rel)\n', (26004, 26011), True, 'import numpy as np\n'), ((26160, 26175), 'numpy.isnan', 'np.isnan', (['P_A_h'], {}), '(P_A_h)\n', (26168, 26175), True, 'import numpy as np\n'), ((26178, 26193), 'numpy.isinf', 'np.isinf', (['P_A_h'], {}), '(P_A_h)\n', (26186, 26193), True, 'import numpy as np\n'), ((26214, 26235), 'numpy.isnan', 'np.isnan', (['integrand_K'], {}), '(integrand_K)\n', (26222, 26235), True, 'import numpy as np\n'), ((26238, 26259), 'numpy.isinf', 'np.isinf', (['integrand_K'], {}), '(integrand_K)\n', (26246, 26259), True, 'import numpy as np\n'), ((30949, 30985), 'numpy.argwhere', 'np.argwhere', (['(F_store[index] == F_use)'], {}), '(F_store[index] == F_use)\n', (30960, 30985), True, 'import numpy as np\n'), ((38562, 38586), 'numpy.math.factorial', 'np.math.factorial', (['(M + 1)'], {}), '(M + 1)\n', (38579, 38586), True, 'import numpy as np\n'), ((5813, 5837), 'numpy.exp', 'np.exp', (['minimum_exponent'], {}), '(minimum_exponent)\n', (5819, 5837), True, 'import numpy as np\n'), ((6632, 6655), 'psutil.virtual_memory', 'psutil.virtual_memory', ([], {}), '()\n', (6653, 6655), False, 'import psutil\n'), ((9873, 9903), 'numpy.append', 'np.append', (['t', 'results_chunk[0]'], {}), '(t, results_chunk[0])\n', (9882, 9903), True, 'import numpy as np\n'), ((9914, 9944), 'numpy.append', 'np.append', (['F', 'results_chunk[1]'], {}), '(F, results_chunk[1])\n', (9923, 9944), True, 'import numpy as np\n'), ((9961, 9997), 'numpy.append', 'np.append', (['P_A_tot', 'results_chunk[2]'], {}), '(P_A_tot, results_chunk[2])\n', (9970, 9997), True, 'import numpy as np\n'), ((10023, 10068), 'numpy.append', 'np.append', (['total_rate_break', 'results_chunk[3]'], {}), '(total_rate_break, results_chunk[3])\n', (10032, 10068), True, 'import numpy as np\n'), ((10095, 10141), 'numpy.append', 'np.append', (['total_rate_reform', 'results_chunk[4]'], {}), '(total_rate_reform, results_chunk[4])\n', (10104, 10141), True, 'import numpy as np\n'), ((10168, 10214), 'numpy.append', 'np.append', (['beta_sigma_over_n', 'results_chunk[5]'], {}), '(beta_sigma_over_n, results_chunk[5])\n', (10177, 10214), True, 'import numpy as np\n'), ((13640, 13673), 'numpy.zeros', 'np.zeros', (['(index_t + 1 - index_tau)'], {}), '(index_t + 1 - index_tau)\n', (13648, 13673), True, 'import numpy as np\n'), ((19725, 19738), 'numpy.isnan', 'np.isnan', (['out'], {}), '(out)\n', (19733, 19738), True, 'import numpy as np\n'), ((19741, 19754), 'numpy.isinf', 'np.isinf', (['out'], {}), '(out)\n', (19749, 19754), True, 'import numpy as np\n'), ((20038, 20051), 'numpy.isnan', 'np.isnan', (['out'], {}), '(out)\n', (20046, 20051), True, 'import numpy as np\n'), ((20054, 20067), 'numpy.isinf', 'np.isinf', (['out'], {}), '(out)\n', (20062, 20067), True, 'import numpy as np\n'), ((32167, 32204), 'numpy.zeros', 'np.zeros', (['(self.num_time - 1 - index_t)'], {}), '(self.num_time - 1 - index_t)\n', (32175, 32204), True, 'import numpy as np\n'), ((32984, 33014), 'numpy.log', 'np.log', (['(num_discretization - 1)'], {}), '(num_discretization - 1)\n', (32990, 33014), True, 'import numpy as np\n'), ((33015, 33024), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (33021, 33024), True, 'import numpy as np\n'), ((33835, 33874), 'scipy.integrate.romb', 'romb', (['(FUN * element)'], {'dx': 'self.dr', 'axis': '(0)'}), '(FUN * element, dx=self.dr, axis=0)\n', (33839, 33874), False, 'from scipy.integrate import romb, simpson, dblquad\n'), ((2598, 2613), 'numpy.diff', 'np.diff', (['t_temp'], {}), '(t_temp)\n', (2605, 2613), True, 'import numpy as np\n'), ((6894, 6940), 'numpy.floor', 'np.floor', (['(max_array_numel / self.num_grid ** 2)'], {}), '(max_array_numel / self.num_grid ** 2)\n', (6902, 6940), True, 'import numpy as np\n'), ((33949, 34000), 'scipy.integrate.romb', 'romb', (['(FUN * element[:, :, None])'], {'dx': 'self.dr', 'axis': '(0)'}), '(FUN * element[:, :, None], dx=self.dr, axis=0)\n', (33953, 34000), False, 'from scipy.integrate import romb, simpson, dblquad\n'), ((34976, 35002), 'numpy.sqrt', 'np.sqrt', (['(lim ** 2 - r ** 2)'], {}), '(lim ** 2 - r ** 2)\n', (34983, 35002), True, 'import numpy as np\n'), ((6803, 6848), 'numpy.sqrt', 'np.sqrt', (['(max_array_numel / self.num_grid ** 2)'], {}), '(max_array_numel / self.num_grid ** 2)\n', (6810, 6848), True, 'import numpy as np\n'), ((34073, 34130), 'scipy.integrate.romb', 'romb', (['(FUN * element[:, :, None, None])'], {'dx': 'self.dr', 'axis': '(0)'}), '(FUN * element[:, :, None, None], dx=self.dr, axis=0)\n', (34077, 34130), False, 'from scipy.integrate import romb, simpson, dblquad\n')]
# coding: utf-8 import numpy as np import re import copy import sys import networkx as nx #import matplotlib.pyplot as plt #import operator #from collections import defaultdict #from collections import Counter #from collections import deque import time #from itertools import combinations # number of combinations for nb_adapters 1-separated adapters def get_nb_comb(nb_adapters, DBG = True): if nb_adapters==1: return 1 if nb_adapters==2: return 1 if nb_adapters==3: return 2 if nb_adapters==4: return 4 if nb_adapters==5: return 7 print("***",nb_adapters) return -1 def boom(input_val, DBG = True): # find chunks of 1-separated adapters, bounded on the left and right by separation of 3 # for each chunk compute number of possibilities # multiply all that numbers = np.asarray(input_val, dtype=np.int) numbers = np.sort(numbers) numbers = np.append(numbers,max(numbers)+3) numbers = np.insert(numbers,0,0) if DBG:print(numbers) ln = len(numbers) nb_comb = 1 left_idx = 0 right_idx = 1 while right_idx<ln: while (numbers[right_idx]-numbers[right_idx-1]==1): right_idx = right_idx + 1 if DBG:print(numbers[left_idx:right_idx+1],left_idx,right_idx) nb_adapters = right_idx-left_idx if DBG:print(nb_adapters) nbc = get_nb_comb(nb_adapters,DBG) if DBG:print("nbc",nbc) nb_comb = nb_comb * nbc left_idx = right_idx right_idx = left_idx + 1 if DBG:print(numbers[left_idx:right_idx+1],left_idx,right_idx) nb_adapters = right_idx-left_idx if DBG:print(nb_adapters) nbc = get_nb_comb(nb_adapters,DBG) if DBG:print("nbc",nbc) nb_comb = nb_comb * nbc return (nb_comb) def test(cc=None, expected=None, DBG = False): start_millis = int(round(time.time() * 1000)) result = boom(cc,DBG) stop_millis = int(round(time.time() * 1000)) result = str(result) expected = str(expected) flag = (result == expected) if(expected=="None"): print("*** "+str(cc) + " *** -> Result = "+str(result)) else: print("*** "+str(cc) + " *** -> Result = "+str(result)+ " -> success = "+ str(flag) + " -> expected " + expected) print((stop_millis-start_millis),"ms",int((stop_millis-start_millis)/1000),"s",int((stop_millis-start_millis)/1000/60),"min") return flag t1="""16 10 15 5 1 11 7 19 6 12 4""" tt1 = t1.splitlines() test(tt1,8,True) #sys.exit() t1="""28 33 18 42 31 14 46 20 48 47 24 23 49 45 19 38 39 11 1 32 25 35 8 17 7 9 4 2 34 10 3""" tt1 = t1.splitlines() test(tt1,19208,False) #sys.exit() INPUT_FILE="input-d10.txt" f = open(INPUT_FILE, "r") contents = f.read() puzzle_input = contents.splitlines() f.close() ret = boom(puzzle_input, False) print(ret) # part 2 = 3022415986688
[ "numpy.sort", "numpy.asarray", "time.time", "numpy.insert" ]
[((816, 851), 'numpy.asarray', 'np.asarray', (['input_val'], {'dtype': 'np.int'}), '(input_val, dtype=np.int)\n', (826, 851), True, 'import numpy as np\n'), ((866, 882), 'numpy.sort', 'np.sort', (['numbers'], {}), '(numbers)\n', (873, 882), True, 'import numpy as np\n'), ((950, 974), 'numpy.insert', 'np.insert', (['numbers', '(0)', '(0)'], {}), '(numbers, 0, 0)\n', (959, 974), True, 'import numpy as np\n'), ((1853, 1864), 'time.time', 'time.time', ([], {}), '()\n', (1862, 1864), False, 'import time\n'), ((1928, 1939), 'time.time', 'time.time', ([], {}), '()\n', (1937, 1939), False, 'import time\n')]
import os import glob import scipy import numpy as np import nibabel as nib import tensorflow as tf from tqdm import tqdm from scipy.ndimage import zoom from args import TestArgParser from util import DiceCoefficient from model import Model class Interpolator(object): def __init__(self, modalities, order=3, mode='reflect'): self.modalities = modalities self.order = order self.mode = mode def __call__(self, path): """Extracts Numpy image and normalizes it to 1 mm^3.""" # Extract raw images from each. image = [] pixdim = [] affine = [] for name in self.modalities: file_card = glob.glob(os.path.join(path, '*' + name + '*' + '.nii' + '*'))[0] img = nib.load(file_card) image.append(np.array(img.dataobj).astype(np.float32)) pixdim.append(img.header['pixdim'][:4]) affine.append(np.stack([img.header['srow_x'], img.header['srow_y'], img.header['srow_z'], np.array([0., 0., 0., 1.])], axis=0)) # Prepare image. image = np.stack(image, axis=-1) self.pixdim = np.mean(pixdim, axis=0, dtype=np.float32) self.affine = np.mean(affine, axis=0, dtype=np.float32) # Rescale and interpolate voxels spatially. if np.any(self.pixdim[:-1] != 1.0): image = zoom(image, self.pixdim[:-1] + [1.0], order=self.order, mode=self.mode) # Rescale and interpolate voxels depthwise (along time). if self.pixdim[-1] != 1.0: image = zoom(image, [1.0, 1.0, self.pixdim[-1], 1.0], order=self.order, mode=self.mode) # Mask out background voxels. mask = np.max(image, axis=-1, keepdims=True) mask = (mask > 0).astype(np.float32) return image, mask def reverse(self, output, path): """Reverses the interpolation performed in __call__.""" # Scale back spatial voxel interpolation. if np.any(self.pixdim[:-1] != 1.0): output = zoom(output, 1.0 / self.pixdim[:-1], order=self.order, mode=self.mode) # Scale back depthwise voxel interpolation. if self.pixdim[-1] != 1.0: output = zoom(output, [1.0, 1.0, 1.0 / self.pixdim[-1]], order=self.order, mode=self.mode) # Save file. nib.save(nib.Nifti1Image(output, self.affine), os.path.join(path, 'mask.nii')) return output class TestTimeAugmentor(object): """Handles full inference on input with test-time augmentation.""" def __init__(self, mean, std, model, model_data_format, spatial_tta=True, channel_tta=0, threshold=0.5): self.mean = mean self.std = std self.model = model self.model_data_format = model_data_format self.channel_tta = channel_tta self.threshold = threshold self.channel_axis = -1 if self.model_data_format == 'channels_last' else 1 self.spatial_axes = [1, 2, 3] if self.model_data_format == 'channels_last' else [2, 3, 4] if spatial_tta: self.augment_axes = [self.spatial_axes, []] for axis in self.spatial_axes: pairs = self.spatial_axes.copy() pairs.remove(axis) self.augment_axes.append([axis]) self.augment_axes.append(pairs) else: self.augment_axes = [[]] def __call__(self, x, bmask): # Normalize and prepare input (assumes input data format of 'channels_last'). x = (x - self.mean) / self.std # Transpose to channels_first data format if required by model. if self.model_data_format == 'channels_first': x = tf.transpose(x, (3, 0, 1, 2)) bmask = tf.transpose(bmask, (3, 0, 1, 2)) x = tf.expand_dims(x, axis=0) bmask = tf.expand_dims(bmask, axis=0) # Initialize list of inputs to feed model. y = [] # Create shape for intensity shifting. shape = [1, 1, 1] shape.insert(self.channel_axis, x.shape[self.channel_axis]) if self.channel_tta: _, var = tf.nn.moments(x, axes=self.spatial_axes, keepdims=True) std = tf.sqrt(var) # Apply spatial augmentation. for flip in self.augment_axes: # Run inference on spatially augmented input. aug = tf.reverse(x, axis=flip) aug, *_ = self.model(aug, training=False, inference=True) y.append(tf.reverse(aug, axis=flip)) for _ in range(self.channel_tta): shift = tf.random.uniform(shape, -0.1, 0.1) scale = tf.random.uniform(shape, 0.9, 1.1) # Run inference on channel augmented input. aug = (aug + shift * std) * scale aug = self.model(aug, training=False, inference=True) aug = tf.reverse(aug, axis=flip) y.append(aug) # Aggregate outputs. y = tf.concat(y, axis=0) y = tf.reduce_mean(y, axis=0, keepdims=True) # Mask out zero-valued voxels. y *= bmask # Take the argmax to determine label. # y = tf.argmax(y, axis=self.channel_axis, output_type=tf.int32) # Transpose back to channels_last data format. y = tf.squeeze(y, axis=0) if self.model_data_format == 'channels_first': y = tf.transpose(y, (1, 2, 3, 0)) return y def pad_to_spatial_res(res, x, mask): # Assumes that x and mask are channels_last data format. res = tf.convert_to_tensor([res]) shape = tf.convert_to_tensor(x.shape[:-1], dtype=tf.int32) shape = res - (shape % res) pad = [[0, shape[0]], [0, shape[1]], [0, shape[2]], [0, 0]] orig_shape = list(x.shape[:-1]) x = tf.pad(x, pad, mode='CONSTANT', constant_values=0.0) mask = tf.pad(mask, pad, mode='CONSTANT', constant_values=0.0) return x, mask, orig_shape def main(args): in_ch = len(args.modalities) # Initialize model(s) and load weights / preprocessing stats. tumor_model = Model(**args.tumor_model_args) tumor_crop_size = args.tumor_model_args['crop_size'] _ = tumor_model(tf.zeros(shape=[1] + tumor_crop_size + [in_ch] if args.tumor_model_args['data_format'] == 'channels_last' \ else [1, in_ch] + tumor_crop_size, dtype=tf.float32)) tumor_model.load_weights(os.path.join(args.tumor_model, 'chkpt.hdf5')) tumor_mean = tf.convert_to_tensor(args.tumor_prepro['norm']['mean'], dtype=tf.float32) tumor_std = tf.convert_to_tensor(args.tumor_prepro['norm']['std'], dtype=tf.float32) if args.skull_strip: skull_model = Model(**args.skull_model_args) skull_crop_size = args.skull_model_args['crop_size'] _ = model(tf.zeros(shape=[1] + skull_crop_size + [in_ch] if args.skull_model_args['data_format'] == 'channels_last' \ else [1, in_ch] + skull_crop_size, dtype=tf.float32)) skull_model.load_weights(os.path.join(args.skull_model, 'chkpt.hdf5')) skull_mean = tf.convert_to_tensor(args.skull_prepro['norm']['mean'], dtype=tf.float32) skull_std = tf.convert_to_tensor(args.skull_prepro['norm']['std'], dtype=tf.float32) # Initialize helper classes for inference and evaluation (optional). dice_fn = DiceCoefficient(data_format='channels_last') interpolator = Interpolator(args.modalities, order=args.order, mode=args.mode) tumor_ttaugmentor = TestTimeAugmentor( tumor_mean, tumor_std, tumor_model, args.tumor_model_args['data_format'], spatial_tta=args.spatial_tta, channel_tta=args.channel_tta, threshold=args.threshold) if args.skull_strip: skull_ttaugmentor = TestTimeAugmentor( skull_mean, skull_std, skull_model, args.skull_model_args['data_format'], spatial_tta=args.spatial_tta, channel_tta=args.channel_tta, threshold=args.threshold) for loc in args.in_locs: for path in tqdm(glob.glob(os.path.join(loc, '*'))): with tf.device(args.device): # If data is labeled, extract label. try: file_card = glob.glob(os.path.join(path, '*' + args.truth + '*' + '.nii' + '*'))[0] y = np.array(nib.load(file_card).dataobj).astype(np.float32) y = tf.expand_dims(y, axis=-1) except: y = None # Rescale and interpolate input image. x, mask = interpolator(path) # Strip MRI brain of skull and eye sockets. if args.skull_strip: x, pad_mask, pad = pad_to_spatial_res( # Pad to spatial resolution args.skull_spatial_res, x, mask) skull_mask = skull_ttaugmentor(x, pad_mask) # Inference with test time augmentation. skull_mask = 1.0 - skull_mask # Convert skull positives into negatives. x *= skull_mask # Mask out skull voxels. x = tf.slice(x, # Remove padding. [0, 0, 0, 0], pad + [-1]) # Label brain tumor categories per voxel. x, pad_mask, pad = pad_to_spatial_res( # Pad to spatial resolution. args.tumor_spatial_res, x, mask) tumor_mask = tumor_ttaugmentor(x, pad_mask) # Inference with test time augmentation. tumor_mask = tf.slice(tumor_mask, # Remove padding. [0, 0, 0, 0], pad + [-1]) tumor_mask += 1 # Convert [0,1,2] to [1,2,3] for label consistency. tumor_mask = tumor_mask.numpy() np.place(tumor_mask, tumor_mask >= 3, [4]) # Replace label `3` with `4` for label consistency. # Reverse interpolation and save as .nii. y_pred = interpolator.reverse(tumor_mask, path) # If label is available, score the prediction. if y is not None: macro, micro = dice_fn(y, y_pred) print('{}. Macro: {ma: 1.4f}. Micro: {mi: 1.4f}' .format(path.split('/')[-1], ma=macro, mi=micro), flush=True) if __name__ == '__main__': parser = TestArgParser() args = parser.parse_args() print('Test args: {}'.format(args)) main(args)
[ "numpy.mean", "tensorflow.sqrt", "os.path.join", "args.TestArgParser", "tensorflow.random.uniform", "tensorflow.nn.moments", "tensorflow.pad", "tensorflow.concat", "scipy.ndimage.zoom", "numpy.place", "numpy.max", "tensorflow.squeeze", "numpy.stack", "nibabel.Nifti1Image", "tensorflow.reverse", "tensorflow.reduce_mean", "tensorflow.transpose", "tensorflow.expand_dims", "nibabel.load", "tensorflow.convert_to_tensor", "model.Model", "tensorflow.device", "numpy.any", "tensorflow.zeros", "numpy.array", "tensorflow.slice", "util.DiceCoefficient" ]
[((5779, 5806), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['[res]'], {}), '([res])\n', (5799, 5806), True, 'import tensorflow as tf\n'), ((5819, 5869), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['x.shape[:-1]'], {'dtype': 'tf.int32'}), '(x.shape[:-1], dtype=tf.int32)\n', (5839, 5869), True, 'import tensorflow as tf\n'), ((6044, 6096), 'tensorflow.pad', 'tf.pad', (['x', 'pad'], {'mode': '"""CONSTANT"""', 'constant_values': '(0.0)'}), "(x, pad, mode='CONSTANT', constant_values=0.0)\n", (6050, 6096), True, 'import tensorflow as tf\n'), ((6108, 6163), 'tensorflow.pad', 'tf.pad', (['mask', 'pad'], {'mode': '"""CONSTANT"""', 'constant_values': '(0.0)'}), "(mask, pad, mode='CONSTANT', constant_values=0.0)\n", (6114, 6163), True, 'import tensorflow as tf\n'), ((6336, 6366), 'model.Model', 'Model', ([], {}), '(**args.tumor_model_args)\n', (6341, 6366), False, 'from model import Model\n'), ((6734, 6807), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (["args.tumor_prepro['norm']['mean']"], {'dtype': 'tf.float32'}), "(args.tumor_prepro['norm']['mean'], dtype=tf.float32)\n", (6754, 6807), True, 'import tensorflow as tf\n'), ((6824, 6896), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (["args.tumor_prepro['norm']['std']"], {'dtype': 'tf.float32'}), "(args.tumor_prepro['norm']['std'], dtype=tf.float32)\n", (6844, 6896), True, 'import tensorflow as tf\n'), ((7608, 7652), 'util.DiceCoefficient', 'DiceCoefficient', ([], {'data_format': '"""channels_last"""'}), "(data_format='channels_last')\n", (7623, 7652), False, 'from util import DiceCoefficient\n'), ((11466, 11481), 'args.TestArgParser', 'TestArgParser', ([], {}), '()\n', (11479, 11481), False, 'from args import TestArgParser\n'), ((1200, 1224), 'numpy.stack', 'np.stack', (['image'], {'axis': '(-1)'}), '(image, axis=-1)\n', (1208, 1224), True, 'import numpy as np\n'), ((1247, 1288), 'numpy.mean', 'np.mean', (['pixdim'], {'axis': '(0)', 'dtype': 'np.float32'}), '(pixdim, axis=0, dtype=np.float32)\n', (1254, 1288), True, 'import numpy as np\n'), ((1311, 1352), 'numpy.mean', 'np.mean', (['affine'], {'axis': '(0)', 'dtype': 'np.float32'}), '(affine, axis=0, dtype=np.float32)\n', (1318, 1352), True, 'import numpy as np\n'), ((1417, 1448), 'numpy.any', 'np.any', (['(self.pixdim[:-1] != 1.0)'], {}), '(self.pixdim[:-1] != 1.0)\n', (1423, 1448), True, 'import numpy as np\n'), ((1805, 1842), 'numpy.max', 'np.max', (['image'], {'axis': '(-1)', 'keepdims': '(True)'}), '(image, axis=-1, keepdims=True)\n', (1811, 1842), True, 'import numpy as np\n'), ((2079, 2110), 'numpy.any', 'np.any', (['(self.pixdim[:-1] != 1.0)'], {}), '(self.pixdim[:-1] != 1.0)\n', (2085, 2110), True, 'import numpy as np\n'), ((4019, 4044), 'tensorflow.expand_dims', 'tf.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (4033, 4044), True, 'import tensorflow as tf\n'), ((4061, 4090), 'tensorflow.expand_dims', 'tf.expand_dims', (['bmask'], {'axis': '(0)'}), '(bmask, axis=0)\n', (4075, 4090), True, 'import tensorflow as tf\n'), ((5206, 5226), 'tensorflow.concat', 'tf.concat', (['y'], {'axis': '(0)'}), '(y, axis=0)\n', (5215, 5226), True, 'import tensorflow as tf\n'), ((5239, 5279), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['y'], {'axis': '(0)', 'keepdims': '(True)'}), '(y, axis=0, keepdims=True)\n', (5253, 5279), True, 'import tensorflow as tf\n'), ((5527, 5548), 'tensorflow.squeeze', 'tf.squeeze', (['y'], {'axis': '(0)'}), '(y, axis=0)\n', (5537, 5548), True, 'import tensorflow as tf\n'), ((6444, 6611), 'tensorflow.zeros', 'tf.zeros', ([], {'shape': "([1] + tumor_crop_size + [in_ch] if args.tumor_model_args['data_format'] ==\n 'channels_last' else [1, in_ch] + tumor_crop_size)", 'dtype': 'tf.float32'}), "(shape=[1] + tumor_crop_size + [in_ch] if args.tumor_model_args[\n 'data_format'] == 'channels_last' else [1, in_ch] + tumor_crop_size,\n dtype=tf.float32)\n", (6452, 6611), True, 'import tensorflow as tf\n'), ((6671, 6715), 'os.path.join', 'os.path.join', (['args.tumor_model', '"""chkpt.hdf5"""'], {}), "(args.tumor_model, 'chkpt.hdf5')\n", (6683, 6715), False, 'import os\n'), ((6945, 6975), 'model.Model', 'Model', ([], {}), '(**args.skull_model_args)\n', (6950, 6975), False, 'from model import Model\n'), ((7353, 7426), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (["args.skull_prepro['norm']['mean']"], {'dtype': 'tf.float32'}), "(args.skull_prepro['norm']['mean'], dtype=tf.float32)\n", (7373, 7426), True, 'import tensorflow as tf\n'), ((7447, 7519), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (["args.skull_prepro['norm']['std']"], {'dtype': 'tf.float32'}), "(args.skull_prepro['norm']['std'], dtype=tf.float32)\n", (7467, 7519), True, 'import tensorflow as tf\n'), ((770, 789), 'nibabel.load', 'nib.load', (['file_card'], {}), '(file_card)\n', (778, 789), True, 'import nibabel as nib\n'), ((1470, 1541), 'scipy.ndimage.zoom', 'zoom', (['image', '(self.pixdim[:-1] + [1.0])'], {'order': 'self.order', 'mode': 'self.mode'}), '(image, self.pixdim[:-1] + [1.0], order=self.order, mode=self.mode)\n', (1474, 1541), False, 'from scipy.ndimage import zoom\n'), ((1671, 1750), 'scipy.ndimage.zoom', 'zoom', (['image', '[1.0, 1.0, self.pixdim[-1], 1.0]'], {'order': 'self.order', 'mode': 'self.mode'}), '(image, [1.0, 1.0, self.pixdim[-1], 1.0], order=self.order, mode=self.mode)\n', (1675, 1750), False, 'from scipy.ndimage import zoom\n'), ((2133, 2203), 'scipy.ndimage.zoom', 'zoom', (['output', '(1.0 / self.pixdim[:-1])'], {'order': 'self.order', 'mode': 'self.mode'}), '(output, 1.0 / self.pixdim[:-1], order=self.order, mode=self.mode)\n', (2137, 2203), False, 'from scipy.ndimage import zoom\n'), ((2313, 2399), 'scipy.ndimage.zoom', 'zoom', (['output', '[1.0, 1.0, 1.0 / self.pixdim[-1]]'], {'order': 'self.order', 'mode': 'self.mode'}), '(output, [1.0, 1.0, 1.0 / self.pixdim[-1]], order=self.order, mode=self\n .mode)\n', (2317, 2399), False, 'from scipy.ndimage import zoom\n'), ((2434, 2470), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['output', 'self.affine'], {}), '(output, self.affine)\n', (2449, 2470), True, 'import nibabel as nib\n'), ((2492, 2522), 'os.path.join', 'os.path.join', (['path', '"""mask.nii"""'], {}), "(path, 'mask.nii')\n", (2504, 2522), False, 'import os\n'), ((3923, 3952), 'tensorflow.transpose', 'tf.transpose', (['x', '(3, 0, 1, 2)'], {}), '(x, (3, 0, 1, 2))\n', (3935, 3952), True, 'import tensorflow as tf\n'), ((3973, 4006), 'tensorflow.transpose', 'tf.transpose', (['bmask', '(3, 0, 1, 2)'], {}), '(bmask, (3, 0, 1, 2))\n', (3985, 4006), True, 'import tensorflow as tf\n'), ((4351, 4406), 'tensorflow.nn.moments', 'tf.nn.moments', (['x'], {'axes': 'self.spatial_axes', 'keepdims': '(True)'}), '(x, axes=self.spatial_axes, keepdims=True)\n', (4364, 4406), True, 'import tensorflow as tf\n'), ((4425, 4437), 'tensorflow.sqrt', 'tf.sqrt', (['var'], {}), '(var)\n', (4432, 4437), True, 'import tensorflow as tf\n'), ((4593, 4617), 'tensorflow.reverse', 'tf.reverse', (['x'], {'axis': 'flip'}), '(x, axis=flip)\n', (4603, 4617), True, 'import tensorflow as tf\n'), ((5620, 5649), 'tensorflow.transpose', 'tf.transpose', (['y', '(1, 2, 3, 0)'], {}), '(y, (1, 2, 3, 0))\n', (5632, 5649), True, 'import tensorflow as tf\n'), ((7055, 7222), 'tensorflow.zeros', 'tf.zeros', ([], {'shape': "([1] + skull_crop_size + [in_ch] if args.skull_model_args['data_format'] ==\n 'channels_last' else [1, in_ch] + skull_crop_size)", 'dtype': 'tf.float32'}), "(shape=[1] + skull_crop_size + [in_ch] if args.skull_model_args[\n 'data_format'] == 'channels_last' else [1, in_ch] + skull_crop_size,\n dtype=tf.float32)\n", (7063, 7222), True, 'import tensorflow as tf\n'), ((7286, 7330), 'os.path.join', 'os.path.join', (['args.skull_model', '"""chkpt.hdf5"""'], {}), "(args.skull_model, 'chkpt.hdf5')\n", (7298, 7330), False, 'import os\n'), ((4710, 4736), 'tensorflow.reverse', 'tf.reverse', (['aug'], {'axis': 'flip'}), '(aug, axis=flip)\n', (4720, 4736), True, 'import tensorflow as tf\n'), ((4809, 4844), 'tensorflow.random.uniform', 'tf.random.uniform', (['shape', '(-0.1)', '(0.1)'], {}), '(shape, -0.1, 0.1)\n', (4826, 4844), True, 'import tensorflow as tf\n'), ((4869, 4903), 'tensorflow.random.uniform', 'tf.random.uniform', (['shape', '(0.9)', '(1.1)'], {}), '(shape, 0.9, 1.1)\n', (4886, 4903), True, 'import tensorflow as tf\n'), ((5107, 5133), 'tensorflow.reverse', 'tf.reverse', (['aug'], {'axis': 'flip'}), '(aug, axis=flip)\n', (5117, 5133), True, 'import tensorflow as tf\n'), ((8712, 8734), 'os.path.join', 'os.path.join', (['loc', '"""*"""'], {}), "(loc, '*')\n", (8724, 8734), False, 'import os\n'), ((8755, 8777), 'tensorflow.device', 'tf.device', (['args.device'], {}), '(args.device)\n', (8764, 8777), True, 'import tensorflow as tf\n'), ((10527, 10573), 'tensorflow.slice', 'tf.slice', (['tumor_mask', '[0, 0, 0, 0]', '(pad + [-1])'], {}), '(tumor_mask, [0, 0, 0, 0], pad + [-1])\n', (10535, 10573), True, 'import tensorflow as tf\n'), ((10870, 10912), 'numpy.place', 'np.place', (['tumor_mask', '(tumor_mask >= 3)', '[4]'], {}), '(tumor_mask, tumor_mask >= 3, [4])\n', (10878, 10912), True, 'import numpy as np\n'), ((696, 747), 'os.path.join', 'os.path.join', (['path', "('*' + name + '*' + '.nii' + '*')"], {}), "(path, '*' + name + '*' + '.nii' + '*')\n", (708, 747), False, 'import os\n'), ((9062, 9088), 'tensorflow.expand_dims', 'tf.expand_dims', (['y'], {'axis': '(-1)'}), '(y, axis=-1)\n', (9076, 9088), True, 'import tensorflow as tf\n'), ((9926, 9963), 'tensorflow.slice', 'tf.slice', (['x', '[0, 0, 0, 0]', '(pad + [-1])'], {}), '(x, [0, 0, 0, 0], pad + [-1])\n', (9934, 9963), True, 'import tensorflow as tf\n'), ((816, 837), 'numpy.array', 'np.array', (['img.dataobj'], {}), '(img.dataobj)\n', (824, 837), True, 'import numpy as np\n'), ((1120, 1150), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 0.0, 1.0])\n', (1128, 1150), True, 'import numpy as np\n'), ((8895, 8952), 'os.path.join', 'os.path.join', (['path', "('*' + args.truth + '*' + '.nii' + '*')"], {}), "(path, '*' + args.truth + '*' + '.nii' + '*')\n", (8907, 8952), False, 'import os\n'), ((8990, 9009), 'nibabel.load', 'nib.load', (['file_card'], {}), '(file_card)\n', (8998, 9009), True, 'import nibabel as nib\n')]
""" Created on Apr 14, 2017 @author: sgoldsmith Copyright (c) <NAME> All rights reserved. """ import os, cv2, numpy, detectbase class motiondet(detectbase.detectbase): """Motion detection image processor. Uses moving average to determine change percent. """ def __init__(self, appConfig, image, logger): """Init object""" self.appConfig = appConfig # Read ignore mask image if set if appConfig.motion['ignoreMask'] != "": self.maskImg = cv2.imread(os.path.expanduser(appConfig.motion['ignoreMask']), 0) logger.info("Using ignore mask: %s" % appConfig.motion['ignoreMask']) else: self.maskImg = None self.movingAvgImg = None # Set frame information self.frameInfo(image, appConfig) logger.info("Image resized to: %dx%d" % (self.frameResizeWidth, self.frameResizeHeight)) self.motionDetected = False self.logger = logger def contours(self, image): """Return contours""" # The background (bright) dilates around the black regions of frame image = cv2.dilate(image, None, iterations=self.appConfig.motion['dilateAmount']) # The bright areas of the image (the background, apparently), get thinner, whereas the dark zones bigger image = cv2.erode(image, None, iterations=self.appConfig.motion['erodeAmount']); # Find contours contours, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:] # Add objects with motion movementLocations = [] for contour in contours: rect = cv2.boundingRect(contour) movementLocations.append(rect) return movementLocations def detect(self, image, timestamp): """Detect motion""" # Resize image if not the same size as the original if self.frameResizeWidth != self.frameWidth: resizeImg = cv2.resize(image, (self.frameResizeWidth, self.frameResizeHeight), interpolation=cv2.INTER_NEAREST) else: resizeImg = image movementLocationsFiltered = [] # Generate work image by blurring workImg = cv2.blur(resizeImg, self.appConfig.motion['kSize']) # Generate moving average image if needed if self.movingAvgImg is None: self.movingAvgImg = numpy.float32(workImg) # Generate moving average image cv2.accumulateWeighted(workImg, self.movingAvgImg, self.appConfig.motion['alpha']) diffImg = cv2.absdiff(workImg, cv2.convertScaleAbs(self.movingAvgImg)) # Convert to grayscale grayImg = cv2.cvtColor(diffImg, cv2.COLOR_BGR2GRAY) # Convert to BW ret, bwImg = cv2.threshold(grayImg, self.appConfig.motion['blackThreshold'], 255, cv2.THRESH_BINARY) # Apply ignore mask if self.maskImg is None: motionImg = bwImg else: motionImg = numpy.bitwise_and(bwImg, self.maskImg) # Total number of changed motion pixels height, width, channels = resizeImg.shape motionPercent = 100.0 * cv2.countNonZero(motionImg) / (width * height) # Detect if camera is adjusting and reset reference if more than threshold if motionPercent > self.appConfig.motion['maxChange']: self.movingAvgImg = numpy.float32(workImg) self.logger.info("%4.2f%% motion greater than maximum of %4.2f%%, image reset" % (motionPercent, self.appConfig.motion['maxChange'])) # Analyze entire image even if ignore mask used, otherwise the ROI could be partially truncated movementLocations = self.contours(bwImg) # Filter out inside rectangles for ri, r in enumerate(movementLocations): for qi, q in enumerate(movementLocations): if ri != qi and self.inside(r, q): break else: rx, ry, rw, rh = r regPercent = ((rw * rh) / (width * height)) * 100.0 # Toss rectangles >= maxChange percent of total frame if regPercent < self.appConfig.motion['maxChange'] : movementLocationsFiltered.append(r) if self.appConfig.camera['mark']: # Draw rectangle around found objects self.markRectSize(image, movementLocationsFiltered, (0, 255, 0), 2) # Motion start stop events if self.motionDetected: if motionPercent <= self.appConfig.motion['stopThreshold']: self.motionDetected = False # Let listening objects know motion has stopped self.notifyObservers(event=self.appConfig.motionStop, motionPercent=motionPercent, timestamp=timestamp) # Threshold to trigger motionStart elif motionPercent > self.appConfig.motion['startThreshold'] and motionPercent < self.appConfig.motion['maxChange']: self.motionDetected = True # Let listening objects know motion has started self.notifyObservers(event=self.appConfig.motionStart, motionPercent=motionPercent, timestamp=timestamp) return resizeImg, grayImg, bwImg, motionPercent, movementLocationsFiltered
[ "cv2.resize", "cv2.dilate", "cv2.cvtColor", "cv2.accumulateWeighted", "cv2.threshold", "numpy.float32", "cv2.countNonZero", "cv2.blur", "cv2.convertScaleAbs", "numpy.bitwise_and", "cv2.erode", "cv2.boundingRect", "os.path.expanduser", "cv2.findContours" ]
[((1149, 1222), 'cv2.dilate', 'cv2.dilate', (['image', 'None'], {'iterations': "self.appConfig.motion['dilateAmount']"}), "(image, None, iterations=self.appConfig.motion['dilateAmount'])\n", (1159, 1222), False, 'import os, cv2, numpy, detectbase\n'), ((1352, 1423), 'cv2.erode', 'cv2.erode', (['image', 'None'], {'iterations': "self.appConfig.motion['erodeAmount']"}), "(image, None, iterations=self.appConfig.motion['erodeAmount'])\n", (1361, 1423), False, 'import os, cv2, numpy, detectbase\n'), ((2213, 2264), 'cv2.blur', 'cv2.blur', (['resizeImg', "self.appConfig.motion['kSize']"], {}), "(resizeImg, self.appConfig.motion['kSize'])\n", (2221, 2264), False, 'import os, cv2, numpy, detectbase\n'), ((2456, 2543), 'cv2.accumulateWeighted', 'cv2.accumulateWeighted', (['workImg', 'self.movingAvgImg', "self.appConfig.motion['alpha']"], {}), "(workImg, self.movingAvgImg, self.appConfig.motion[\n 'alpha'])\n", (2478, 2543), False, 'import os, cv2, numpy, detectbase\n'), ((2667, 2708), 'cv2.cvtColor', 'cv2.cvtColor', (['diffImg', 'cv2.COLOR_BGR2GRAY'], {}), '(diffImg, cv2.COLOR_BGR2GRAY)\n', (2679, 2708), False, 'import os, cv2, numpy, detectbase\n'), ((2754, 2846), 'cv2.threshold', 'cv2.threshold', (['grayImg', "self.appConfig.motion['blackThreshold']", '(255)', 'cv2.THRESH_BINARY'], {}), "(grayImg, self.appConfig.motion['blackThreshold'], 255, cv2.\n THRESH_BINARY)\n", (2767, 2846), False, 'import os, cv2, numpy, detectbase\n'), ((1472, 1535), 'cv2.findContours', 'cv2.findContours', (['image', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (1488, 1535), False, 'import os, cv2, numpy, detectbase\n'), ((1658, 1683), 'cv2.boundingRect', 'cv2.boundingRect', (['contour'], {}), '(contour)\n', (1674, 1683), False, 'import os, cv2, numpy, detectbase\n'), ((1970, 2073), 'cv2.resize', 'cv2.resize', (['image', '(self.frameResizeWidth, self.frameResizeHeight)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(image, (self.frameResizeWidth, self.frameResizeHeight),\n interpolation=cv2.INTER_NEAREST)\n', (1980, 2073), False, 'import os, cv2, numpy, detectbase\n'), ((2385, 2407), 'numpy.float32', 'numpy.float32', (['workImg'], {}), '(workImg)\n', (2398, 2407), False, 'import os, cv2, numpy, detectbase\n'), ((2578, 2616), 'cv2.convertScaleAbs', 'cv2.convertScaleAbs', (['self.movingAvgImg'], {}), '(self.movingAvgImg)\n', (2597, 2616), False, 'import os, cv2, numpy, detectbase\n'), ((2971, 3009), 'numpy.bitwise_and', 'numpy.bitwise_and', (['bwImg', 'self.maskImg'], {}), '(bwImg, self.maskImg)\n', (2988, 3009), False, 'import os, cv2, numpy, detectbase\n'), ((3370, 3392), 'numpy.float32', 'numpy.float32', (['workImg'], {}), '(workImg)\n', (3383, 3392), False, 'import os, cv2, numpy, detectbase\n'), ((529, 579), 'os.path.expanduser', 'os.path.expanduser', (["appConfig.motion['ignoreMask']"], {}), "(appConfig.motion['ignoreMask'])\n", (547, 579), False, 'import os, cv2, numpy, detectbase\n'), ((3145, 3172), 'cv2.countNonZero', 'cv2.countNonZero', (['motionImg'], {}), '(motionImg)\n', (3161, 3172), False, 'import os, cv2, numpy, detectbase\n')]
import numpy as np from sklearn.cluster import KMeans from tqdm import tqdm import matplotlib.pyplot as plt from preliminaries.embedding import aggregateApiSequences from utils.file import loadJson, dumpIterable, dumpJson from utils.manager import PathManager from baselines.alignment import apiCluster from utils.timer import StepTimer from utils.magic import sample, magicSeed, nRandom from utils.stat import calBeliefeInterval k = 10 n = 10 qk = 5 N = 20 def findOptK(dict_path, k_range=(2,50)): mat = np.load(dict_path) wss = [] for k_ in tqdm(range(k_range[0],k_range[1]+1)): kmeans = KMeans(n_clusters=k_).fit(mat) wss.append(kmeans.inertia_) kaxis = np.arange(k_range[0],k_range[1]+1) plt.plot(kaxis, wss) plt.show() ##################################################### # 将原json文件中的序列根据聚类结果替换为类簇序列,同时使用一个 # 最大长度截断,并保存为npy文件 ##################################################### def makeClusteredData(json_path, cluster_path, word_map_path, dump_path, max_len=1000): word_map = loadJson(word_map_path) cluster_map = loadJson(cluster_path) seqs = aggregateApiSequences(json_path, is_class_dir=True) mat = [] for seq in seqs: seq = seq[:max_len] s = [] for idx in seq: s.append(cluster_map[str(word_map[idx])]) while len(s) < max_len: s.append(-1) mat.append(s) np.save(dump_path, np.array(mat)) ##################################################### # 给定一个类别中的所有序列,生成该类别的转换矩阵 ##################################################### def makeTranMatrix(seqs, n_cluster, maxlen=1000): matrix = np.zeros((n_cluster,n_cluster)) for seq in seqs: for i in range(0,len(seq)-1): if seq[i+1] == -1: break x = seq[i] y = seq[i+1] matrix[x][y] += 1 row_sum = matrix.sum(0) mask = row_sum==0 np.putmask(row_sum,mask,1) # 将行和为0的位置置为1,防止除0错误 normalized_matrix = (matrix.T / row_sum).T return normalized_matrix ################################################## # 根据生成的转换矩阵组,根据最大转换值将序列转换为组内类别的 # 序列 ################################################## def traverse(seq, matrices, maxlen=1000): res_seq = [] for i in range(0, maxlen-1): if seq[i] == -1: res_seq.append(-1) continue prob = matrices[:,seq[i],seq[i+1]] res_seq.append(np.argmax(prob)) # 将所有类中该i->i+1状态转移最大的类下标加入 return res_seq ############################################# # 根据输入序列,在多个类的转换矩阵中进行累计加分, # 返回该序列在所有类的类转换矩阵中的总得分 ############################################# def scoreSeqOnTranMats(seq, tran_mats): score = np.zeros((len(tran_mats))) for i in range(len(seq)-1): score += tran_mats[:,seq[i],seq[i+1]] return score def scoreMarkovEpisode(clustered_data_path, epoch=300, n_cluster=10, maxlen=1000, verbose=True): acc_hist = [] matrix = np.load(clustered_data_path) class_pool = list(range(len(matrix) // N)) item_pool = set(range(N)) tm = StepTimer(epoch) tm.begin() for i in range(epoch): if verbose: print("Epoch", i) supports = [] queries = [] task_seed = magicSeed() sampling_seed = magicSeed() class_seeds = nRandom(n, sampling_seed) label_space = sample(class_pool, n, task_seed) for cls,cseed in zip(label_space, class_seeds): support_idxes = sample(item_pool, k, cseed, return_set=True) query_idxes = sample(item_pool.difference(support_idxes), qk, cseed, return_set=True) support_idxes = np.array(list(support_idxes)) + N*cls query_idxes = np.array(list(query_idxes)) + N*cls supports += [matrix[i] for i in support_idxes] queries += [matrix[i] for i in query_idxes] supports = np.array(supports).reshape(n,k,-1) queries = np.array(queries).reshape(n,qk,-1) # 利用原数据的类簇转换序列,生成每个类的类簇转换矩阵 cluster_tran_mats = [] for cls in range(n): cluster_tran_mats.append(makeTranMatrix(supports[cls], n_cluster=n_cluster,maxlen=maxlen)) cluster_tran_mats = np.stack(cluster_tran_mats, axis=0) # 利用每个类的类簇转换矩阵,根据其中状态转移的最大值,转换为类别之间的转换序列 class_tran_seqs = [] for cls in range(n): for support in supports[cls]: class_tran_seqs.append(traverse(support, cluster_tran_mats, maxlen)) class_tran_seqs = np.stack(class_tran_seqs, axis=0).reshape(n,k,-1) # 根据类别之间的转换序列,生成每个类的类别转换矩阵 class_tran_mats = [] for cls in range(n): # 由于是类别之间的转换序列,因此类簇数量等于类别数量 class_tran_mats.append(makeTranMatrix(class_tran_seqs[cls], n_cluster=n, maxlen=maxlen)) class_tran_mats = np.stack(class_tran_mats, axis=0).reshape(n,n,n) query_class_tran_seqs = [] for cls in range(n): for query in queries[cls]: query_class_tran_seqs.append(traverse(query, cluster_tran_mats, maxlen)) acc_count = 0 for qi,query in enumerate(query_class_tran_seqs): # 返回的总分数最大的一个即为预测结果的类别 predict = np.argmax(scoreSeqOnTranMats(query, class_tran_mats)) acc_count += (predict == (qi//qk)) epoch_acc = acc_count / (qk*n) if verbose: print("Acc:", epoch_acc) tm.step(prt=verbose) acc_hist.append(epoch_acc) if verbose: print("\n") print("*"*50) print("Avg acc:", sum(acc_hist)/epoch) print("95%% belief interval:", calBeliefeInterval(acc_hist)) print("Total consuming time:", tm.step(prt=False,end=True)) return sum(acc_hist)/epoch def gridSearch(c_values, k_values, per_epoch=200): # 网格搜索聚类类簇数量和截断长度 re = {} for ci,c_num in enumerate(c_values): re[c_num] = {} for ki,k_num in enumerate(k_values): print(ci*len(k_values)+ki+1, "/", len(c_values)*len(k_values)) mng = PathManager("virushare-20-original") # findOptK(mng.WordEmbedMatrix(), k_range=(2,100)) apiCluster(mng.WordEmbedMatrix(), mng.DataRoot() + "MarkovClusterMapping.json", cluster_num=c_num) makeClusteredData(json_path=mng.Folder(), cluster_path=mng.DataRoot() + "MarkovClusterMapping.json", word_map_path=mng.WordIndexMap(), dump_path=mng.DataRoot() + "MarkovClusteredData.npy", max_len=k_num) a = scoreMarkovEpisode(clustered_data_path=mng.DataRoot() + "MarkovClusteredData.npy", epoch=per_epoch, n_cluster=c_num, maxlen=k_num, verbose=False) re[c_num][k_num] = a return re def extractBestParam(re): best_c = None best_k = None best_acc = -1 for ck, cv in re.items(): for kk, kv in cv.items(): if kv > best_acc: best_acc = kv best_c = ck best_k = kk return best_c, best_k if __name__ == "__main__": epoch = 5000 seq_len = 50 n_cluster = 30 n_range = (15,30) mng = PathManager("HKS-api") # # # findOptK(mng.WordEmbedMatrix(), k_range=(2,100)) # apiCluster(mng.WordEmbedMatrix(), mng.DataRoot()+"MarkovClusterMapping.json", cluster_num=n_cluster) # makeClusteredData(json_path=mng.Folder(), # cluster_path=mng.DataRoot()+"MarkovClusterMapping.json", # word_map_path=mng.WordIndexMap(), # dump_path=mng.DataRozot()+"MarkovClusteredData.npy", # max_len=seq_len) # scoreMarkovEpisode(clustered_data_path=mng.DataRoot()+"MarkovClusteredData.npy", # epoch=2000, # n_cluster=n_cluster, # maxlen=seq_len) # re = gridSearch(c_values=list(range(*n_range)), # k_values=[i*50 for i in range(1,11)], # per_epoch=1000) # dumpJson(re, mng.DataRoot()+"GSs/GridSearchResult-%dshot-%dway-virushare20.json"%(k,n)) # re = loadJson(mng.DataRoot()+"GSs/GridSearchResult-%dshot-%dway-virushare20.json"%(k,n)) # n_cluster, seq_len = extractBestParam(re) # n_cluster = int(n_cluster) # seq_len = int(seq_len) apiCluster(mng.WordEmbedMatrix(), mng.DataRoot()+"MarkovClusterMapping.json", cluster_num=n_cluster) makeClusteredData(json_path=mng.Folder(), cluster_path=mng.DataRoot()+"MarkovClusterMapping.json", word_map_path=mng.WordIndexMap(), dump_path=mng.DataRoot()+"MarkovClusteredData.npy", max_len=seq_len) scoreMarkovEpisode(clustered_data_path=mng.DataRoot()+"MarkovClusteredData.npy", epoch=epoch, n_cluster=n_cluster, maxlen=seq_len)
[ "numpy.stack", "numpy.load", "utils.stat.calBeliefeInterval", "matplotlib.pyplot.show", "utils.timer.StepTimer", "matplotlib.pyplot.plot", "utils.manager.PathManager", "utils.magic.nRandom", "numpy.argmax", "sklearn.cluster.KMeans", "numpy.zeros", "utils.magic.magicSeed", "numpy.arange", "preliminaries.embedding.aggregateApiSequences", "numpy.array", "numpy.putmask", "utils.magic.sample", "utils.file.loadJson" ]
[((513, 531), 'numpy.load', 'np.load', (['dict_path'], {}), '(dict_path)\n', (520, 531), True, 'import numpy as np\n'), ((695, 732), 'numpy.arange', 'np.arange', (['k_range[0]', '(k_range[1] + 1)'], {}), '(k_range[0], k_range[1] + 1)\n', (704, 732), True, 'import numpy as np\n'), ((735, 755), 'matplotlib.pyplot.plot', 'plt.plot', (['kaxis', 'wss'], {}), '(kaxis, wss)\n', (743, 755), True, 'import matplotlib.pyplot as plt\n'), ((760, 770), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (768, 770), True, 'import matplotlib.pyplot as plt\n'), ((1037, 1060), 'utils.file.loadJson', 'loadJson', (['word_map_path'], {}), '(word_map_path)\n', (1045, 1060), False, 'from utils.file import loadJson, dumpIterable, dumpJson\n'), ((1079, 1101), 'utils.file.loadJson', 'loadJson', (['cluster_path'], {}), '(cluster_path)\n', (1087, 1101), False, 'from utils.file import loadJson, dumpIterable, dumpJson\n'), ((1113, 1164), 'preliminaries.embedding.aggregateApiSequences', 'aggregateApiSequences', (['json_path'], {'is_class_dir': '(True)'}), '(json_path, is_class_dir=True)\n', (1134, 1164), False, 'from preliminaries.embedding import aggregateApiSequences\n'), ((1639, 1671), 'numpy.zeros', 'np.zeros', (['(n_cluster, n_cluster)'], {}), '((n_cluster, n_cluster))\n', (1647, 1671), True, 'import numpy as np\n'), ((1917, 1945), 'numpy.putmask', 'np.putmask', (['row_sum', 'mask', '(1)'], {}), '(row_sum, mask, 1)\n', (1927, 1945), True, 'import numpy as np\n'), ((2947, 2975), 'numpy.load', 'np.load', (['clustered_data_path'], {}), '(clustered_data_path)\n', (2954, 2975), True, 'import numpy as np\n'), ((3062, 3078), 'utils.timer.StepTimer', 'StepTimer', (['epoch'], {}), '(epoch)\n', (3071, 3078), False, 'from utils.timer import StepTimer\n'), ((7312, 7334), 'utils.manager.PathManager', 'PathManager', (['"""HKS-api"""'], {}), "('HKS-api')\n", (7323, 7334), False, 'from utils.manager import PathManager\n'), ((1425, 1438), 'numpy.array', 'np.array', (['mat'], {}), '(mat)\n', (1433, 1438), True, 'import numpy as np\n'), ((3236, 3247), 'utils.magic.magicSeed', 'magicSeed', ([], {}), '()\n', (3245, 3247), False, 'from utils.magic import sample, magicSeed, nRandom\n'), ((3272, 3283), 'utils.magic.magicSeed', 'magicSeed', ([], {}), '()\n', (3281, 3283), False, 'from utils.magic import sample, magicSeed, nRandom\n'), ((3306, 3331), 'utils.magic.nRandom', 'nRandom', (['n', 'sampling_seed'], {}), '(n, sampling_seed)\n', (3313, 3331), False, 'from utils.magic import sample, magicSeed, nRandom\n'), ((3355, 3387), 'utils.magic.sample', 'sample', (['class_pool', 'n', 'task_seed'], {}), '(class_pool, n, task_seed)\n', (3361, 3387), False, 'from utils.magic import sample, magicSeed, nRandom\n'), ((4197, 4232), 'numpy.stack', 'np.stack', (['cluster_tran_mats'], {'axis': '(0)'}), '(cluster_tran_mats, axis=0)\n', (4205, 4232), True, 'import numpy as np\n'), ((2424, 2439), 'numpy.argmax', 'np.argmax', (['prob'], {}), '(prob)\n', (2433, 2439), True, 'import numpy as np\n'), ((3473, 3517), 'utils.magic.sample', 'sample', (['item_pool', 'k', 'cseed'], {'return_set': '(True)'}), '(item_pool, k, cseed, return_set=True)\n', (3479, 3517), False, 'from utils.magic import sample, magicSeed, nRandom\n'), ((5592, 5620), 'utils.stat.calBeliefeInterval', 'calBeliefeInterval', (['acc_hist'], {}), '(acc_hist)\n', (5610, 5620), False, 'from utils.stat import calBeliefeInterval\n'), ((6011, 6047), 'utils.manager.PathManager', 'PathManager', (['"""virushare-20-original"""'], {}), "('virushare-20-original')\n", (6022, 6047), False, 'from utils.manager import PathManager\n'), ((615, 636), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'k_'}), '(n_clusters=k_)\n', (621, 636), False, 'from sklearn.cluster import KMeans\n'), ((3881, 3899), 'numpy.array', 'np.array', (['supports'], {}), '(supports)\n', (3889, 3899), True, 'import numpy as np\n'), ((3934, 3951), 'numpy.array', 'np.array', (['queries'], {}), '(queries)\n', (3942, 3951), True, 'import numpy as np\n'), ((4494, 4527), 'numpy.stack', 'np.stack', (['class_tran_seqs'], {'axis': '(0)'}), '(class_tran_seqs, axis=0)\n', (4502, 4527), True, 'import numpy as np\n'), ((4805, 4838), 'numpy.stack', 'np.stack', (['class_tran_mats'], {'axis': '(0)'}), '(class_tran_mats, axis=0)\n', (4813, 4838), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ This script works for foam phantom. """ import numpy as np import glob import dxchange import matplotlib.pyplot as plt import scipy.interpolate import tomopy from scipy.interpolate import Rbf from mpl_toolkits.mplot3d.axes3d import Axes3D from matplotlib import cm import matplotlib from project import * from simulator import * from sinogram import * from instrument import * from sample import * np.set_printoptions(threshold='infinite') if __name__ == '__main__': pad_length = 1024 sino_width = 2048 half_sino_width = int(sino_width / 2) # scanned_sino_width = 2048 + 1024 trunc_ratio_ls = np.arange(0.1, 1.1, 0.1) gamma_ps = 0.85 gamma_os = 0.85 fprime_ls = (sino_width * trunc_ratio_ls).astype(int) mean_count_tomosaic_ls = [] mean_count_local_ls = [] dose_integral_tomosaic_ls = [] dose_integral_local_ls = [] # create reference recon if os.path.exists(os.path.join('data', 'ref_recon.tiff')): ref_recon = dxchange.read_tiff(os.path.join('data', 'ref_recon.tiff')) else: sino = dxchange.read_tiff(os.path.join('data', 'foam_sino_pad.tiff')) sino = -np.log(sino) sino = sino[:, np.newaxis, :] theta = tomopy.angles(sino.shape[0]) ref_recon = tomopy.recon(sino, theta, center=pad_length+half_sino_width, algorithm='gridrec') dxchange.write_tiff(ref_recon, 'data/ref_recon', overwrite=True) ref_recon = np.squeeze(ref_recon) try: # raise Exception mean_count_tomosaic_ls = np.load(os.path.join('data', 'foam_eff_ratio', 'mean_count_tomosaic_ls.npy')) mean_count_local_ls = np.load(os.path.join('data', 'foam_eff_ratio', 'mean_count_local_ls.npy')) dose_integral_tomosaic_ls = np.load(os.path.join('data', 'foam_eff_ratio', 'dose_integral_tomosaic_ls.npy')) dose_integral_local_ls = np.load(os.path.join('data', 'foam_eff_ratio', 'dose_integral_local_ls.npy')) except: # do things for PS for i, fprime in enumerate(fprime_ls): dirname = 'foam_trunc_{:d}'.format(int(100 * trunc_ratio_ls[i])) f = int(float(fprime) / gamma_ps) f2 = int(f / 2) n_scan = get_nscan_ps(f, gamma_ps, sino_width) if n_scan == 1: stage_list = [pad_length + half_sino_width] else: stage_begin = pad_length + f2 stage_list = np.arange(stage_begin, stage_begin + fprime * (n_scan - 1) + 1, fprime, dtype=int) inst = Instrument(f) inst.add_stage_positions(stage_list) prj_tomosaic = Project() prj_tomosaic.add_simuators(os.path.join('data', 'foam_sino_pad.tiff'), inst, center=pad_length + half_sino_width, pixel_size=1) prj_tomosaic.process_all_tomosaic(save_path=os.path.join('data', 'foam_eff_ratio', dirname), recon=False) mean_count = np.mean(prj_tomosaic.simulators[0].sample_counter_tomosaic) mean_count_tomosaic_ls.append(mean_count) dose_integral_tomosaic_ls.append(prj_tomosaic.simulators[0].sample_sum_tomosaic) dxchange.write_tiff(prj_tomosaic.simulators[0].sample_counter_tomosaic, os.path.join('data', 'foam_eff_ratio', dirname, 'sampling_ps'), dtype='float32', overwrite=True) print('f\' = {}, f = {}, t = {}, n_f = {}, mean_count = {}, dose = {}'.format(fprime, f, trunc_ratio_ls[i], n_scan, mean_count, prj_tomosaic.simulators[0].sample_sum_tomosaic)) print('=====================================') # do things for OS for i, fprime in enumerate(fprime_ls): dirname = 'foam_trunc_{:d}'.format(int(100 * trunc_ratio_ls[i])) f = int(float(fprime) / gamma_os) f2 = int(f / 2) n_scan = get_nscan_os(f, fprime, sino_width) if n_scan == 1: center_list = [(pad_length + half_sino_width, pad_length + half_sino_width)] else: stage_begin = pad_length + fprime / np.sqrt(8) stage_list = np.arange(stage_begin, stage_begin + fprime / np.sqrt(2) * (n_scan - 1) + 1, fprime / np.sqrt(2), dtype=int) center_list = [(y, x) for y in stage_list for x in stage_list] center_list_excl = [] for y, x in center_list: if np.linalg.norm(np.array([y, x]) - np.array([pad_length + half_sino_width, pad_length + half_sino_width])) > half_sino_width + fprime / 2: # print('({}, {}) skipped because it is too far.'.format(y, x)) pass else: center_list_excl.append((y, x)) inst = Instrument(f) print(center_list_excl) inst.add_center_positions(center_list_excl) prj_local = Project() prj_local.add_simuators(os.path.join('data', 'foam_sino_pad.tiff'), inst, center=pad_length + half_sino_width, pixel_size=1) prj_local.process_all_local(mask_ratio=gamma_os, save_path=os.path.join('data', 'foam_eff_ratio', dirname), ref_fname=os.path.join('data', 'ref_recon.tiff'), allow_read=False, offset_intensity=True, recon=False) mean_count = np.mean(prj_local.simulators[0].sample_counter_local) mean_count_local_ls.append(mean_count) dose_integral_local_ls.append(prj_local.simulators[0].sample_sum_local) dxchange.write_tiff(prj_local.simulators[0].sample_counter_local, os.path.join('data', 'foam_eff_ratio', dirname, 'sampling_os'), dtype='float32', overwrite=True) print('f\' = {}, f = {}, t = {}, n_f = {}, mean_count = {}, dose = {}'.format(fprime, f, trunc_ratio_ls[i], n_scan, mean_count, prj_local.simulators[0].sample_sum_local)) mean_count_tomosaic_ls = np.array(mean_count_tomosaic_ls) mean_count_local_ls = np.array(mean_count_local_ls) dose_integral_tomosaic_ls = np.array(dose_integral_tomosaic_ls) dose_integral_local_ls = np.array(dose_integral_local_ls) # save np.save(os.path.join('data', 'foam_eff_ratio', 'mean_count_tomosaic_ls'), mean_count_tomosaic_ls) np.save(os.path.join('data', 'foam_eff_ratio', 'mean_count_local_ls'), mean_count_local_ls) np.save(os.path.join('data', 'foam_eff_ratio', 'dose_integral_tomosaic_ls'), dose_integral_tomosaic_ls) np.save(os.path.join('data', 'foam_eff_ratio', 'dose_integral_local_ls'), dose_integral_local_ls) print(mean_count_tomosaic_ls) print(mean_count_local_ls) print(dose_integral_tomosaic_ls) print(dose_integral_local_ls) # x for tomosaic; y for local comb_pts = np.array([(x, y) for x in trunc_ratio_ls for y in trunc_ratio_ls]) area_ratio = np.array([float(x) / y for x in mean_count_tomosaic_ls for y in mean_count_local_ls]) dose_ratio = np.array([float(x) / y for x in dose_integral_tomosaic_ls for y in dose_integral_local_ls]) x = comb_pts[:, 0] y = comb_pts[:, 1] # print eff_ratio.reshape([len(trunc_ratio_tomosaic_ls), len(trunc_ratio_local_ls)]) t = np.linspace(0.1, 1.0, 50) xx, yy = np.meshgrid(t, t) matplotlib.rcParams['pdf.fonttype'] = 'truetype' fontProperties = {'family': 'serif', 'serif': ['Times New Roman'], 'weight': 'normal', 'size': 9} plt.rc('font', **fontProperties) fig = plt.figure(figsize=(8, 7)) zz = scipy.interpolate.griddata(comb_pts, dose_ratio, (xx, yy), method='linear') # zz = dose_ratio.reshape(xx.shape) ax = fig.add_subplot(1, 1, 1, projection='3d') surf = ax.plot_surface(xx, yy, zz, cmap=cm.jet, linewidth=1, antialiased=True) ax.view_init(10, -135) ax.set_xlabel('Truncation ratio of PS') ax.set_ylabel('Truncation ratio of OS') ax.set_zlabel('Dose ratio (PS/OS)') plt.savefig(os.path.join('data', 'dose_ratio_excl_corners.pdf'), format='pdf') fig = plt.figure(figsize=(8, 7)) zz = scipy.interpolate.griddata(comb_pts, area_ratio, (xx, yy), method='linear') # zz = area_ratio.reshape(xx.shape) print(zz) ax = fig.add_subplot(1, 1, 1, projection='3d') surf = ax.plot_surface(xx, yy, zz, cmap=cm.jet, linewidth=1, antialiased=True) ax.view_init(10, -135) ax.set_xlabel('Truncation ratio of PS') ax.set_ylabel('Truncation ratio of OS') ax.set_zlabel('Area ratio (PS/OS)') plt.savefig(os.path.join('data', 'area_ratio_excl_corners.pdf'), format='pdf') plt.show()
[ "numpy.set_printoptions", "numpy.meshgrid", "matplotlib.pyplot.show", "tomopy.recon", "numpy.log", "dxchange.write_tiff", "tomopy.angles", "matplotlib.pyplot.figure", "numpy.mean", "numpy.arange", "numpy.array", "numpy.linspace", "matplotlib.pyplot.rc", "numpy.squeeze", "numpy.sqrt" ]
[((429, 470), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': '"""infinite"""'}), "(threshold='infinite')\n", (448, 470), True, 'import numpy as np\n'), ((648, 672), 'numpy.arange', 'np.arange', (['(0.1)', '(1.1)', '(0.1)'], {}), '(0.1, 1.1, 0.1)\n', (657, 672), True, 'import numpy as np\n'), ((1463, 1484), 'numpy.squeeze', 'np.squeeze', (['ref_recon'], {}), '(ref_recon)\n', (1473, 1484), True, 'import numpy as np\n'), ((7144, 7210), 'numpy.array', 'np.array', (['[(x, y) for x in trunc_ratio_ls for y in trunc_ratio_ls]'], {}), '([(x, y) for x in trunc_ratio_ls for y in trunc_ratio_ls])\n', (7152, 7210), True, 'import numpy as np\n'), ((7568, 7593), 'numpy.linspace', 'np.linspace', (['(0.1)', '(1.0)', '(50)'], {}), '(0.1, 1.0, 50)\n', (7579, 7593), True, 'import numpy as np\n'), ((7607, 7624), 'numpy.meshgrid', 'np.meshgrid', (['t', 't'], {}), '(t, t)\n', (7618, 7624), True, 'import numpy as np\n'), ((7784, 7816), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {}), "('font', **fontProperties)\n", (7790, 7816), True, 'import matplotlib.pyplot as plt\n'), ((7828, 7854), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 7)'}), '(figsize=(8, 7))\n', (7838, 7854), True, 'import matplotlib.pyplot as plt\n'), ((8386, 8412), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 7)'}), '(figsize=(8, 7))\n', (8396, 8412), True, 'import matplotlib.pyplot as plt\n'), ((8956, 8966), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8964, 8966), True, 'import matplotlib.pyplot as plt\n'), ((1243, 1271), 'tomopy.angles', 'tomopy.angles', (['sino.shape[0]'], {}), '(sino.shape[0])\n', (1256, 1271), False, 'import tomopy\n'), ((1292, 1380), 'tomopy.recon', 'tomopy.recon', (['sino', 'theta'], {'center': '(pad_length + half_sino_width)', 'algorithm': '"""gridrec"""'}), "(sino, theta, center=pad_length + half_sino_width, algorithm=\n 'gridrec')\n", (1304, 1380), False, 'import tomopy\n'), ((1382, 1446), 'dxchange.write_tiff', 'dxchange.write_tiff', (['ref_recon', '"""data/ref_recon"""'], {'overwrite': '(True)'}), "(ref_recon, 'data/ref_recon', overwrite=True)\n", (1401, 1446), False, 'import dxchange\n'), ((1176, 1188), 'numpy.log', 'np.log', (['sino'], {}), '(sino)\n', (1182, 1188), True, 'import numpy as np\n'), ((6286, 6318), 'numpy.array', 'np.array', (['mean_count_tomosaic_ls'], {}), '(mean_count_tomosaic_ls)\n', (6294, 6318), True, 'import numpy as np\n'), ((6349, 6378), 'numpy.array', 'np.array', (['mean_count_local_ls'], {}), '(mean_count_local_ls)\n', (6357, 6378), True, 'import numpy as np\n'), ((6415, 6450), 'numpy.array', 'np.array', (['dose_integral_tomosaic_ls'], {}), '(dose_integral_tomosaic_ls)\n', (6423, 6450), True, 'import numpy as np\n'), ((6484, 6516), 'numpy.array', 'np.array', (['dose_integral_local_ls'], {}), '(dose_integral_local_ls)\n', (6492, 6516), True, 'import numpy as np\n'), ((3096, 3155), 'numpy.mean', 'np.mean', (['prj_tomosaic.simulators[0].sample_counter_tomosaic'], {}), '(prj_tomosaic.simulators[0].sample_counter_tomosaic)\n', (3103, 3155), True, 'import numpy as np\n'), ((5703, 5756), 'numpy.mean', 'np.mean', (['prj_local.simulators[0].sample_counter_local'], {}), '(prj_local.simulators[0].sample_counter_local)\n', (5710, 5756), True, 'import numpy as np\n'), ((2444, 2530), 'numpy.arange', 'np.arange', (['stage_begin', '(stage_begin + fprime * (n_scan - 1) + 1)', 'fprime'], {'dtype': 'int'}), '(stage_begin, stage_begin + fprime * (n_scan - 1) + 1, fprime,\n dtype=int)\n', (2453, 2530), True, 'import numpy as np\n'), ((4206, 4216), 'numpy.sqrt', 'np.sqrt', (['(8)'], {}), '(8)\n', (4213, 4216), True, 'import numpy as np\n'), ((4332, 4342), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (4339, 4342), True, 'import numpy as np\n'), ((4540, 4556), 'numpy.array', 'np.array', (['[y, x]'], {}), '([y, x])\n', (4548, 4556), True, 'import numpy as np\n'), ((4559, 4629), 'numpy.array', 'np.array', (['[pad_length + half_sino_width, pad_length + half_sino_width]'], {}), '([pad_length + half_sino_width, pad_length + half_sino_width])\n', (4567, 4629), True, 'import numpy as np\n'), ((4292, 4302), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (4299, 4302), True, 'import numpy as np\n')]
# (c) <NAME> 2021 # see embedded licence file # imelt V1.1 import numpy as np import torch, time import h5py import torch.nn.functional as F from sklearn.metrics import mean_squared_error class data_loader(): """custom data loader for batch training """ def __init__(self,path_viscosity,path_raman,path_density, path_ri, device, scaling = False): """ Inputs ------ path_viscosity : string path for the viscosity HDF5 dataset path_raman : string path for the Raman spectra HDF5 dataset path_density : string path for the density HDF5 dataset path_ri : String path for the refractive index HDF5 dataset device : CUDA scaling : False or True Scales the input chemical composition. WARNING : Does not work currently as this is a relic of testing this effect, but we chose not to scale inputs and Cp are calculated with unscaled values in the network.""" f = h5py.File(path_viscosity, 'r') # List all groups self.X_columns = f['X_columns'][()] # Entropy dataset X_entropy_train = f["X_entropy_train"][()] y_entropy_train = f["y_entropy_train"][()] X_entropy_valid = f["X_entropy_valid"][()] y_entropy_valid = f["y_entropy_valid"][()] X_entropy_test = f["X_entropy_test"][()] y_entropy_test = f["y_entropy_test"][()] # Viscosity dataset X_train = f["X_train"][()] y_train = f["y_train"][()] X_valid = f["X_valid"][()] y_valid = f["y_valid"][()] X_test = f["X_test"][()] y_test = f["y_test"][()] # Tg dataset X_tg_train = f["X_tg_train"][()] X_tg_valid= f["X_tg_valid"][()] X_tg_test = f["X_tg_test"][()] y_tg_train = f["y_tg_train"][()] y_tg_valid = f["y_tg_valid"][()] y_tg_test = f["y_tg_test"][()] f.close() # Raman dataset f = h5py.File(path_raman, 'r') X_raman_train = f["X_raman_train"][()] y_raman_train = f["y_raman_train"][()] X_raman_valid = f["X_raman_test"][()] y_raman_valid = f["y_raman_test"][()] f.close() # Density dataset f = h5py.File(path_density, 'r') X_density_train = f["X_density_train"][()] X_density_valid = f["X_density_valid"][()] X_density_test = f["X_density_test"][()] y_density_train = f["y_density_train"][()] y_density_valid = f["y_density_valid"][()] y_density_test = f["y_density_test"][()] f.close() # Refractive Index (ri) dataset f = h5py.File(path_ri, 'r') X_ri_train = f["X_ri_train"][()] X_ri_valid = f["X_ri_valid"][()] X_ri_test = f["X_ri_test"][()] lbd_ri_train = f["lbd_ri_train"][()] lbd_ri_valid = f["lbd_ri_valid"][()] lbd_ri_test = f["lbd_ri_test"][()] y_ri_train = f["y_ri_train"][()] y_ri_valid = f["y_ri_valid"][()] y_ri_test = f["y_ri_test"][()] f.close() # grabbing number of Raman channels self.nb_channels_raman = y_raman_valid.shape[1] # preparing data for pytorch # Scaler # Warning : this was done for tests and currently will not work, # as Cp are calculated from unscaled mole fractions... if scaling == True: X_scaler_mean = np.mean(X_train[:,0:4], axis=0) X_scaler_std = np.std(X_train[:,0:4], axis=0) else: X_scaler_mean = 0.0 X_scaler_std = 1.0 # The following lines perform scaling (not needed, not active), # put the data in torch tensors and send them to device (GPU or CPU, as requested) # viscosity self.x_visco_train = torch.FloatTensor(self.scaling(X_train[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.T_visco_train = torch.FloatTensor(X_train[:,4].reshape(-1,1)).to(device) self.y_visco_train = torch.FloatTensor(y_train[:,0].reshape(-1,1)).to(device) self.x_visco_valid = torch.FloatTensor(self.scaling(X_valid[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.T_visco_valid = torch.FloatTensor(X_valid[:,4].reshape(-1,1)).to(device) self.y_visco_valid = torch.FloatTensor(y_valid[:,0].reshape(-1,1)).to(device) self.x_visco_test = torch.FloatTensor(self.scaling(X_test[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.T_visco_test = torch.FloatTensor(X_test[:,4].reshape(-1,1)).to(device) self.y_visco_test = torch.FloatTensor(y_test[:,0].reshape(-1,1)).to(device) # entropy self.x_entro_train = torch.FloatTensor(self.scaling(X_entropy_train[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.y_entro_train = torch.FloatTensor(y_entropy_train[:,0].reshape(-1,1)).to(device) self.x_entro_valid = torch.FloatTensor(self.scaling(X_entropy_valid[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.y_entro_valid = torch.FloatTensor(y_entropy_valid[:,0].reshape(-1,1)).to(device) self.x_entro_test = torch.FloatTensor(self.scaling(X_entropy_test[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.y_entro_test = torch.FloatTensor(y_entropy_test[:,0].reshape(-1,1)).to(device) # tg self.x_tg_train = torch.FloatTensor(self.scaling(X_tg_train[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.y_tg_train = torch.FloatTensor(y_tg_train.reshape(-1,1)).to(device) self.x_tg_valid = torch.FloatTensor(self.scaling(X_tg_valid[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.y_tg_valid = torch.FloatTensor(y_tg_valid.reshape(-1,1)).to(device) self.x_tg_test = torch.FloatTensor(self.scaling(X_tg_test[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.y_tg_test = torch.FloatTensor(y_tg_test.reshape(-1,1)).to(device) # Density self.x_density_train = torch.FloatTensor(self.scaling(X_density_train[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.y_density_train = torch.FloatTensor(y_density_train.reshape(-1,1)).to(device) self.x_density_valid = torch.FloatTensor(self.scaling(X_density_valid[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.y_density_valid = torch.FloatTensor(y_density_valid.reshape(-1,1)).to(device) self.x_density_test = torch.FloatTensor(self.scaling(X_density_test[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.y_density_test = torch.FloatTensor(y_density_test.reshape(-1,1)).to(device) # Optical self.x_ri_train = torch.FloatTensor(self.scaling(X_ri_train[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.lbd_ri_train = torch.FloatTensor(lbd_ri_train.reshape(-1,1)).to(device) self.y_ri_train = torch.FloatTensor(y_ri_train.reshape(-1,1)).to(device) self.x_ri_valid = torch.FloatTensor(self.scaling(X_ri_valid[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.lbd_ri_valid = torch.FloatTensor(lbd_ri_valid.reshape(-1,1)).to(device) self.y_ri_valid = torch.FloatTensor(y_ri_valid.reshape(-1,1)).to(device) self.x_ri_test = torch.FloatTensor(self.scaling(X_ri_test[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.lbd_ri_test = torch.FloatTensor(lbd_ri_test.reshape(-1,1)).to(device) self.y_ri_test = torch.FloatTensor(y_ri_test.reshape(-1,1)).to(device) # Raman self.x_raman_train = torch.FloatTensor(self.scaling(X_raman_train[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.y_raman_train = torch.FloatTensor(y_raman_train).to(device) self.x_raman_valid = torch.FloatTensor(self.scaling(X_raman_valid[:,0:4],X_scaler_mean,X_scaler_std)).to(device) self.y_raman_valid = torch.FloatTensor(y_raman_valid).to(device) def scaling(self,X,mu,s): """perform standard scaling""" return(X-mu)/s def print_data(self): """print the specifications of the datasets""" print("################################") print("#### Dataset specifications ####") print("################################") # print splitting size_train = self.x_visco_train.unique(dim=0).shape[0] size_valid = self.x_visco_valid.unique(dim=0).shape[0] size_test = self.x_visco_test.unique(dim=0).shape[0] size_total = size_train+size_valid+size_test print("") print("Number of unique compositions (viscosity): {}".format(size_total)) print("Number of unique compositions in training (viscosity): {}".format(size_train)) print("Dataset separations are {:.2f} in train, {:.2f} in valid, {:.2f} in test".format(size_train/size_total, size_valid/size_total, size_test/size_total)) # print splitting size_train = self.x_entro_train.unique(dim=0).shape[0] size_valid = self.x_entro_valid.unique(dim=0).shape[0] size_test = self.x_entro_test.unique(dim=0).shape[0] size_total = size_train+size_valid+size_test print("") print("Number of unique compositions (entropy): {}".format(size_total)) print("Number of unique compositions in training (entropy): {}".format(size_train)) print("Dataset separations are {:.2f} in train, {:.2f} in valid, {:.2f} in test".format(size_train/size_total, size_valid/size_total, size_test/size_total)) size_train = self.x_ri_train.unique(dim=0).shape[0] size_valid = self.x_ri_valid.unique(dim=0).shape[0] size_test = self.x_ri_test.unique(dim=0).shape[0] size_total = size_train+size_valid+size_test print("") print("Number of unique compositions (refractive index): {}".format(size_total)) print("Number of unique compositions in training (refractive index): {}".format(size_train)) print("Dataset separations are {:.2f} in train, {:.2f} in valid, {:.2f} in test".format(size_train/size_total, size_valid/size_total, size_test/size_total)) size_train = self.x_density_train.unique(dim=0).shape[0] size_valid = self.x_density_valid.unique(dim=0).shape[0] size_test = self.x_density_test.unique(dim=0).shape[0] size_total = size_train+size_valid+size_test print("") print("Number of unique compositions (density): {}".format(size_total)) print("Number of unique compositions in training (density): {}".format(size_train)) print("Dataset separations are {:.2f} in train, {:.2f} in valid, {:.2f} in test".format(size_train/size_total, size_valid/size_total, size_test/size_total)) size_train = self.x_raman_train.unique(dim=0).shape[0] size_valid = self.x_raman_valid.unique(dim=0).shape[0] size_total = size_train+size_valid print("") print("Number of unique compositions (Raman): {}".format(size_total)) print("Number of unique compositions in training (Raman): {}".format(size_train)) print("Dataset separations are {:.2f} in train, {:.2f} in valid".format(size_train/size_total, size_valid/size_total)) # training shapes print("") print("This is for checking the consistency of the dataset...") print("Visco train shape") print(self.x_visco_train.shape) print(self.T_visco_train.shape) print(self.y_visco_train.shape) print("Entropy train shape") print(self.x_entro_train.shape) print(self.y_entro_train.shape) print("Tg train shape") print(self.x_tg_train.shape) print(self.y_tg_train.shape) print("Density train shape") print(self.x_density_train.shape) print(self.y_density_train.shape) print("Refactive Index train shape") print(self.x_ri_train.shape) print(self.lbd_ri_train.shape) print(self.y_ri_train.shape) print("Raman train shape") print(self.x_raman_train.shape) print(self.y_raman_train.shape) # testing device print("") print("Where are the datasets? CPU or GPU?") print("Visco device") print(self.x_visco_train.device) print(self.T_visco_train.device) print(self.y_visco_train.device) print("Entropy device") print(self.x_entro_train.device) print(self.y_entro_train.device) print("Tg device") print(self.x_tg_train.device) print(self.y_tg_train.device) print("Density device") print(self.x_density_train.device) print(self.y_density_train.device) print("Refactive Index device") print(self.x_ri_test.device) print(self.lbd_ri_test.device) print(self.y_ri_test.device) print("Raman device") print(self.x_raman_train.device) print(self.y_raman_train.device) class model(torch.nn.Module): """i-MELT model """ def __init__(self, input_size, hidden_size, num_layers, nb_channels_raman,p_drop=0.5, activation_function = torch.nn.ReLU()): """Initialization of i-MELT model Parameters ---------- input_size : int number of input parameters hidden_size : int number of hidden units per hidden layer num_layers : int number of hidden layers nb_channels_raman : int number of Raman spectra channels, typically provided by the dataset p_drop : float (optinal) dropout probability, default = 0.5 activation_function : torch.nn activation function activation function for the hidden units, default = torch.nn.ReLU() choose here : https://pytorch.org/docs/stable/nn.html#non-linear-activations-weighted-sum-nonlinearity """ super(model, self).__init__() # init parameters self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.nb_channels_raman = nb_channels_raman # network related torch stuffs self.activation_function = activation_function self.dropout = torch.nn.Dropout(p=p_drop) self.linears = torch.nn.ModuleList([torch.nn.Linear(input_size, self.hidden_size)]) self.linears.extend([torch.nn.Linear(self.hidden_size, self.hidden_size) for i in range(1, self.num_layers)]) self.out_thermo = torch.nn.Linear(self.hidden_size, 17) # Linear output self.out_raman = torch.nn.Linear(self.hidden_size, self.nb_channels_raman) # Linear output def output_bias_init(self): """bias initialisation for self.out_thermo positions are Tg, Sconf(Tg), Ae, A_am, density, fragility (MYEGA one) """ self.out_thermo.bias = torch.nn.Parameter(data=torch.tensor([np.log(1000.),np.log(10.), # Tg, ScTg -1.5,-1.5,-1.5, -4.5, # A_AG, A_AM, A_CG, A_TVF np.log(500.), np.log(100.), np.log(400.), # To_CG, C_CG, C_TVF np.log(2.3),np.log(25.0), # density, fragility .90,.20,.98,0.6,0.2,1., # Sellmeier coeffs B1, B2, B3, C1, C2, C3 ])) def forward(self, x): """foward pass in core neural network""" for layer in self.linears: # Feedforward x = self.dropout(self.activation_function(layer(x))) return x def at_gfu(self,x): """calculate atom per gram formula unit assumes rows are sio2 al2o3 na2o k2o """ out = 3.0*x[:,0] + 5.0*x[:,1] + 3.0*x[:,2] + 3.0*x[:,3] return torch.reshape(out, (out.shape[0], 1)) def aCpl(self,x): """calculate term a in equation Cpl = aCpl + bCpl*T """ out = 81.37*x[:,0] + 27.21*x[:,1] + 100.6*x[:,2] + 50.13*x[:,3] + x[:,0]*(x[:,3]*x[:,3])*151.7 return torch.reshape(out, (out.shape[0], 1)) def b_calc(self,x): """calculate term b in equation Cpl = aCpl + b*T """ out = 0.09428*x[:,1] + 0.01578*x[:,3] return torch.reshape(out, (out.shape[0], 1)) def ap_calc(self,x): """calculate term ap in equation dS = ap ln(T/Tg) + b(T-Tg) """ out = self.aCpl(x) - 3.0*8.314462*self.at_gfu(x) return torch.reshape(out, (out.shape[0], 1)) def dCp(self,x,T): out = self.ap_calc(x)*(torch.log(T)-torch.log(self.tg(x))) + self.b_calc(x)*(T-self.tg(x)) return torch.reshape(out, (out.shape[0], 1)) def raman_pred(self,x): """Raman predicted spectra""" return self.out_raman(self.forward(x)) def tg(self,x): """glass transition temperature Tg""" out = torch.exp(self.out_thermo(self.forward(x))[:,0]) return torch.reshape(out, (out.shape[0], 1)) def sctg(self,x): """configurational entropy at Tg""" out = torch.exp(self.out_thermo(self.forward(x))[:,1]) return torch.reshape(out, (out.shape[0], 1)) def ae(self,x): """Ae parameter in Adam and Gibbs and MYEGA""" out = self.out_thermo(self.forward(x))[:,2] return torch.reshape(out, (out.shape[0], 1)) def a_am(self,x): """A parameter for Avramov-Mitchell""" out = self.out_thermo(self.forward(x))[:,3] return torch.reshape(out, (out.shape[0], 1)) def a_cg(self,x): """A parameter for Free Volume (CG)""" out = self.out_thermo(self.forward(x))[:,4] return torch.reshape(out, (out.shape[0], 1)) def a_tvf(self,x): """A parameter for Free Volume (CG)""" out = self.out_thermo(self.forward(x))[:,5] return torch.reshape(out, (out.shape[0], 1)) def to_cg(self,x): """A parameter for Free Volume (CG)""" out = torch.exp(self.out_thermo(self.forward(x))[:,6]) return torch.reshape(out, (out.shape[0], 1)) def c_cg(self,x): """C parameter for Free Volume (CG)""" out = torch.exp(self.out_thermo(self.forward(x))[:,7]) return torch.reshape(out, (out.shape[0], 1)) def c_tvf(self,x): """C parameter for Free Volume (CG)""" out = torch.exp(self.out_thermo(self.forward(x))[:,8]) return torch.reshape(out, (out.shape[0], 1)) def density(self,x): """glass density""" out = torch.exp(self.out_thermo(self.forward(x))[:,9]) return torch.reshape(out, (out.shape[0], 1)) def fragility(self,x): """melt fragility""" out = torch.exp(self.out_thermo(self.forward(x))[:,10]) return torch.reshape(out, (out.shape[0], 1)) def S_B1(self,x): """Sellmeir B1""" out = self.out_thermo(self.forward(x))[:,11] return torch.reshape(out, (out.shape[0], 1)) def S_B2(self,x): """Sellmeir B1""" out = self.out_thermo(self.forward(x))[:,12] return torch.reshape(out, (out.shape[0], 1)) def S_B3(self,x): """Sellmeir B1""" out = self.out_thermo(self.forward(x))[:,13] return torch.reshape(out, (out.shape[0], 1)) def S_C1(self,x): """Sellmeir C1, with proper scaling""" out = 0.01*self.out_thermo(self.forward(x))[:,14] return torch.reshape(out, (out.shape[0], 1)) def S_C2(self,x): """Sellmeir C2, with proper scaling""" out = 0.1*self.out_thermo(self.forward(x))[:,15] return torch.reshape(out, (out.shape[0], 1)) def S_C3(self,x): """Sellmeir C3, with proper scaling""" out = 100*self.out_thermo(self.forward(x))[:,16] return torch.reshape(out, (out.shape[0], 1)) def b_cg(self, x): """B in free volume (CG) equation""" return 0.5*(12.0 - self.a_cg(x)) * (self.tg(x) - self.to_cg(x) + torch.sqrt( (self.tg(x) - self.to_cg(x))**2 + self.c_cg(x)*self.tg(x))) def b_tvf(self,x): return (12.0-self.a_tvf(x))*(self.tg(x)-self.c_tvf(x)) def be(self,x): """Be term in Adam-Gibbs eq given Ae, Tg and Scong(Tg)""" return (12.0-self.ae(x))*(self.tg(x)*self.sctg(x)) def ag(self,x,T): """viscosity from the Adam-Gibbs equation, given chemistry X and temperature T """ return self.ae(x) + self.be(x) / (T* (self.sctg(x) + self.dCp(x, T))) def myega(self,x, T): """viscosity from the MYEGA equation, given entries X and temperature T """ return self.ae(x) + (12.0 - self.ae(x))*(self.tg(x)/T)*torch.exp((self.fragility(x)/(12.0-self.ae(x))-1.0)*(self.tg(x)/T-1.0)) def am(self,x, T): """viscosity from the Avramov-Mitchell equation, given entries X and temperature T """ return self.a_am(x) + (12.0 - self.a_am(x))*(self.tg(x)/T)**(self.fragility(x)/(12.0 - self.a_am(x))) def cg(self,x, T): """free volume theory viscosity equation, given entries X and temperature T """ return self.a_cg(x) + 2.0*self.b_cg(x)/(T - self.to_cg(x) + torch.sqrt( (T-self.to_cg(x))**2 + self.c_cg(x)*T)) def tvf(self,x, T): """Tamman-Vogel-Fulscher empirical viscosity, given entries X and temperature T """ return self.a_tvf(x) + self.b_tvf(x)/(T - self.c_tvf(x)) def sellmeier(self, x, lbd): """Sellmeier equation for refractive index calculation, with lbd in microns """ return torch.sqrt( 1.0 + self.S_B1(x)*lbd**2/(lbd**2-self.S_C1(x)) + self.S_B2(x)*lbd**2/(lbd**2-self.S_C2(x)) + self.S_B3(x)*lbd**2/(lbd**2-self.S_C3(x))) class loss_scales(): """loss scales for everything""" def __init__(self): # scaling coefficients for loss function # viscosity is always one self.entro = 1. self.raman = 20. self.density = 1000. self.ri = 10000. self.tg = 0.001 def training(neuralmodel,ds,criterion,optimizer,save_switch=True,save_name="./temp",train_patience = 50,min_delta=0.1,verbose=True, mode="main", max_epochs = 5000): """train neuralmodel given a dataset, criterion and optimizer Parameters ---------- neuralmodel : model a neuravi model ds : dataset dataset from data_loader() criterion : pytorch criterion the criterion for goodness of fit optimizer : pytorch optimizer the optimizer to use save_name : string the path to save the model during training Options ------- train_patience : int, default = 50 the number of iterations min_delta : float, default = 0.1 Minimum decrease in the loss to qualify as an improvement, a decrease of less than or equal to `min_delta` will count as no improvement. verbose : bool, default = True Do you want details during training? mode : string, default = "main" "main" or "pretrain" max_epochs : int maximum number of epochs to perform. Useful in case of prototyping, etc. Returns ------- neuralmodel : model trained model record_train_loss : list training loss (global) record_valid_loss : list validation loss (global) """ if verbose == True: time1 = time.time() if mode == "pretrain": print("! Pretrain mode...\n") else: print("Full training.\n") # scaling coefficients for loss function # viscosity is always one # scaling coefficients for loss function # viscosity is always one ls = loss_scales() entro_scale = ls.entro raman_scale = ls.raman density_scale = ls.density ri_scale = ls.ri tg_scale = ls.tg neuralmodel.train() # for early stopping epoch = 0 best_epoch = 0 val_ex = 0 # for recording losses record_train_loss = [] record_valid_loss = [] while val_ex <= train_patience: optimizer.zero_grad() # Forward pass on training set y_ag_pred_train = neuralmodel.ag(ds.x_visco_train,ds.T_visco_train) y_myega_pred_train = neuralmodel.myega(ds.x_visco_train,ds.T_visco_train) y_am_pred_train = neuralmodel.am(ds.x_visco_train,ds.T_visco_train) y_cg_pred_train = neuralmodel.cg(ds.x_visco_train,ds.T_visco_train) y_tvf_pred_train = neuralmodel.tvf(ds.x_visco_train,ds.T_visco_train) y_raman_pred_train = neuralmodel.raman_pred(ds.x_raman_train) y_density_pred_train = neuralmodel.density(ds.x_density_train) y_entro_pred_train = neuralmodel.sctg(ds.x_entro_train) y_tg_pred_train = neuralmodel.tg(ds.x_tg_train) y_ri_pred_train = neuralmodel.sellmeier(ds.x_ri_train, ds.lbd_ri_train) # on validation set y_ag_pred_valid = neuralmodel.ag(ds.x_visco_valid,ds.T_visco_valid) y_myega_pred_valid = neuralmodel.myega(ds.x_visco_valid,ds.T_visco_valid) y_am_pred_valid = neuralmodel.am(ds.x_visco_valid,ds.T_visco_valid) y_cg_pred_valid = neuralmodel.cg(ds.x_visco_valid,ds.T_visco_valid) y_tvf_pred_valid = neuralmodel.tvf(ds.x_visco_valid,ds.T_visco_valid) y_raman_pred_valid = neuralmodel.raman_pred(ds.x_raman_valid) y_density_pred_valid = neuralmodel.density(ds.x_density_valid) y_entro_pred_valid = neuralmodel.sctg(ds.x_entro_valid) y_tg_pred_valid = neuralmodel.tg(ds.x_tg_valid) y_ri_pred_valid = neuralmodel.sellmeier(ds.x_ri_valid, ds.lbd_ri_valid) # Compute Loss # train loss_ag = criterion(y_ag_pred_train, ds.y_visco_train) loss_myega = criterion(y_myega_pred_train, ds.y_visco_train) loss_am = criterion(y_am_pred_train, ds.y_visco_train) loss_cg = criterion(y_cg_pred_train, ds.y_visco_train) loss_tvf = criterion(y_tvf_pred_train, ds.y_visco_train) loss_raman = raman_scale*criterion(y_raman_pred_train,ds.y_raman_train) loss_tg = tg_scale*criterion(y_tg_pred_train,ds.y_tg_train) loss_density = density_scale*criterion(y_density_pred_train,ds.y_density_train) loss_entro = entro_scale*criterion(y_entro_pred_train,ds.y_entro_train) loss_ri = ri_scale*criterion(y_ri_pred_train,ds.y_ri_train) if mode == "pretrain": loss = loss_tg + loss_raman + loss_density + loss_entro + loss_ri else: loss = loss_ag + loss_myega + loss_am + loss_cg + loss_tvf + loss_raman + loss_density + loss_entro + loss_ri record_train_loss.append(loss.item()) # record global loss # validation with torch.set_grad_enabled(False): loss_ag_v = criterion(y_ag_pred_valid, ds.y_visco_valid) loss_myega_v = criterion(y_myega_pred_valid, ds.y_visco_valid) loss_am_v = criterion(y_am_pred_valid, ds.y_visco_valid) loss_cg_v = criterion(y_cg_pred_valid, ds.y_visco_valid) loss_tvf_v = criterion(y_tvf_pred_valid, ds.y_visco_valid) loss_raman_v = raman_scale*criterion(y_raman_pred_valid,ds.y_raman_valid) loss_tg_v = tg_scale*criterion(y_tg_pred_valid,ds.y_tg_valid) loss_density_v = density_scale*criterion(y_density_pred_valid,ds.y_density_valid) loss_entro_v = entro_scale*criterion(y_entro_pred_valid,ds.y_entro_valid) loss_ri_v = ri_scale*criterion(y_ri_pred_valid,ds.y_ri_valid) if mode == "pretrain": loss_v = loss_tg_v + loss_raman_v + loss_density_v + loss_entro_v + loss_ri_v else: loss_v = loss_ag_v + loss_myega_v + loss_am_v + loss_cg_v + loss_tvf_v + loss_raman_v + loss_density_v + loss_entro_v + loss_ri record_valid_loss.append(loss_v.item()) if verbose == True: if (epoch % 200 == 0): print('Epoch {} => train loss: {}; valid loss: {}'.format(epoch, loss.item(), loss_v.item())) ### # calculating ES criterion ### if epoch == 0: val_ex = 0 best_loss_v = loss_v.item() elif loss_v.item() <= best_loss_v - min_delta: # if improvement is significant, this saves the model val_ex = 0 best_epoch = epoch best_loss_v = loss_v.item() if save_switch == True: # save best model torch.save(neuralmodel.state_dict(), save_name) else: val_ex += 1 # Backward pass loss.backward() optimizer.step() epoch += 1 # we test is we are still under a reasonable number of epochs, if not break if epoch > max_epochs: break if verbose == True: time2 = time.time() print("Running time in seconds:", time2-time1) print('Scaled valid loss values are {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f} for Tg, Raman, density, entropy, ri, viscosity (AG)'.format( loss_tg_v, loss_raman_v, loss_density_v, loss_entro_v, loss_ri_v, loss_ag_v )) return neuralmodel, record_train_loss, record_valid_loss def training2(neuralmodel,ds,criterion,optimizer, save_switch=True,save_name="./temp", nb_folds=10,train_patience=50,min_delta=0.1, verbose=True, mode="main",device='cuda'): """train neuralmodel given a dataset, criterion and optimizer Parameters ---------- neuralmodel : model a neuravi model ds : dataset dataset from data_loader() criterion : pytorch criterion the criterion for goodness of fit optimizer : pytorch optimizer the optimizer to use save_name : string the path to save the model during training Options ------- nb_folds : int, default = 10 the number of folds for the K-fold training train_patience : int, default = 50 the number of iterations min_delta : float, default = 0.1 Minimum decrease in the loss to qualify as an improvement, a decrease of less than or equal to `min_delta` will count as no improvement. verbose : bool, default = True Do you want details during training? mode : string, default = "main" "main" or "pretrain" device : string, default = "cuda" the device where the calculations are made during training Returns ------- neuralmodel : model trained model record_train_loss : list training loss (global) record_valid_loss : list validation loss (global) """ if verbose == True: time1 = time.time() if mode == "pretrain": print("! Pretrain mode...\n") else: print("Full training.\n") # scaling coefficients for loss function # viscosity is always one ls = loss_scales() entro_scale = ls.entro raman_scale = ls.raman density_scale = ls.density ri_scale = ls.ri tg_scale = ls.tg neuralmodel.train() # for early stopping epoch = 0 best_epoch = 0 val_ex = 0 # for recording losses record_train_loss = [] record_valid_loss = [] # new vectors for the K-fold training (each vector contains slices of data separated) slices_x_visco_train = [ds.x_visco_train[i::nb_folds] for i in range(nb_folds)] slices_y_visco_train = [ds.y_visco_train[i::nb_folds] for i in range(nb_folds)] slices_T_visco_train = [ds.T_visco_train[i::nb_folds] for i in range(nb_folds)] slices_x_raman_train = [ds.x_raman_train[i::nb_folds] for i in range(nb_folds)] slices_y_raman_train = [ds.y_raman_train[i::nb_folds] for i in range(nb_folds)] slices_x_density_train = [ds.x_density_train[i::nb_folds] for i in range(nb_folds)] slices_y_density_train = [ds.y_density_train[i::nb_folds] for i in range(nb_folds)] slices_x_entro_train = [ds.x_entro_train[i::nb_folds] for i in range(nb_folds)] slices_y_entro_train = [ds.y_entro_train[i::nb_folds] for i in range(nb_folds)] slices_x_tg_train = [ds.x_tg_train[i::nb_folds] for i in range(nb_folds)] slices_y_tg_train = [ds.y_tg_train[i::nb_folds] for i in range(nb_folds)] slices_x_ri_train = [ds.x_ri_train[i::nb_folds] for i in range(nb_folds)] slices_y_ri_train = [ds.y_ri_train[i::nb_folds] for i in range(nb_folds)] slices_lbd_ri_train = [ds.lbd_ri_train[i::nb_folds] for i in range(nb_folds)] while val_ex <= train_patience: # # TRAINING # loss = 0 # initialize the sum of losses of each fold for i in range(nb_folds): # loop for K-Fold training to reduce memory footprint # vectors are sent to device # training dataset is not on device yet and needs to be sent there x_visco_train = slices_x_visco_train[i]#.to(device) y_visco_train = slices_y_visco_train[i]#.to(device) T_visco_train = slices_T_visco_train[i]#.to(device) x_raman_train = slices_x_raman_train[i]#.to(device) y_raman_train = slices_y_raman_train[i]#.to(device) x_density_train = slices_x_density_train[i]#.to(device) y_density_train = slices_y_density_train[i]#.to(device) x_entro_train = slices_x_entro_train[i]#.to(device) y_entro_train = slices_y_entro_train[i]#.to(device) x_tg_train = slices_x_tg_train[i]#.to(device) y_tg_train = slices_y_tg_train[i]#.to(device) x_ri_train = slices_x_ri_train[i]#.to(device) y_ri_train = slices_y_ri_train[i]#.to(device) lbd_ri_train = slices_lbd_ri_train[i]#.to(device) # Forward pass on training set y_ag_pred_train = neuralmodel.ag(x_visco_train,T_visco_train) y_myega_pred_train = neuralmodel.myega(x_visco_train,T_visco_train) y_am_pred_train = neuralmodel.am(x_visco_train,T_visco_train) y_cg_pred_train = neuralmodel.cg(x_visco_train,T_visco_train) y_tvf_pred_train = neuralmodel.tvf(x_visco_train,T_visco_train) y_raman_pred_train = neuralmodel.raman_pred(x_raman_train) y_density_pred_train = neuralmodel.density(x_density_train) y_entro_pred_train = neuralmodel.sctg(x_entro_train) y_tg_pred_train = neuralmodel.tg(x_tg_train) y_ri_pred_train = neuralmodel.sellmeier(x_ri_train,lbd_ri_train) # Precisions precision_visco = 1.0#1/(2*torch.exp(-neuralmodel.log_vars[0])) precision_raman = raman_scale #1/(2*torch.exp(-neuralmodel.log_vars[1])) precision_density = density_scale #1/(2*torch.exp(-neuralmodel.log_vars[2])) precision_entro = entro_scale#1/(2*torch.exp(-neuralmodel.log_vars[3])) precision_tg = tg_scale#1/(2*torch.exp(-neuralmodel.log_vars[4])) precision_ri = ri_scale#1/(2*torch.exp(-neuralmodel.log_vars[5])) # Compute Loss loss_ag = precision_visco * criterion(y_ag_pred_train, y_visco_train) #+ neuralmodel.log_vars[0] loss_myega = precision_visco * criterion(y_myega_pred_train, y_visco_train) #+ neuralmodel.log_vars[0] loss_am = precision_visco * criterion(y_am_pred_train, y_visco_train) #+ neuralmodel.log_vars[0] loss_cg = precision_visco * criterion(y_cg_pred_train, y_visco_train) #+ neuralmodel.log_vars[0] loss_tvf = precision_visco * criterion(y_tvf_pred_train, y_visco_train) #+ neuralmodel.log_vars[0] loss_raman = precision_raman * criterion(y_raman_pred_train,y_raman_train) #+ neuralmodel.log_vars[1] loss_density = precision_density * criterion(y_density_pred_train,y_density_train) #+ neuralmodel.log_vars[2] loss_entro = precision_entro * criterion(y_entro_pred_train,y_entro_train) #+ neuralmodel.log_vars[3] loss_tg = precision_tg * criterion(y_tg_pred_train,y_tg_train) #+ neuralmodel.log_vars[4] loss_ri = precision_ri * criterion(y_ri_pred_train,y_ri_train) #+ neuralmodel.log_vars[5] if mode == "pretrain": loss_fold = loss_tg + loss_raman + loss_density + loss_entro + loss_ri else: loss_fold = (loss_ag + loss_myega + loss_am + loss_cg + loss_tvf + loss_raman + loss_density + loss_entro + loss_ri) optimizer.zero_grad() # initialise gradient loss_fold.backward() # backward gradient determination optimizer.step() # optimiser call and step loss += loss_fold.item() # add the new fold loss to the sum # record global loss (mean of the losses of the training folds) record_train_loss.append(loss/nb_folds) # # MONITORING VALIDATION SUBSET # with torch.set_grad_enabled(False): # Precisions precision_visco = 1.0#1/(2*torch.exp(-neuralmodel.log_vars[0])) precision_raman = raman_scale #1/(2*torch.exp(-neuralmodel.log_vars[1])) precision_density = density_scale #1/(2*torch.exp(-neuralmodel.log_vars[2])) precision_entro = entro_scale#1/(2*torch.exp(-neuralmodel.log_vars[3])) precision_tg = tg_scale#1/(2*torch.exp(-neuralmodel.log_vars[4])) precision_ri = ri_scale#1/(2*torch.exp(-neuralmodel.log_vars[5])) # on validation set y_ag_pred_valid = neuralmodel.ag(ds.x_visco_valid.to(device),ds.T_visco_valid.to(device)) y_myega_pred_valid = neuralmodel.myega(ds.x_visco_valid.to(device),ds.T_visco_valid.to(device)) y_am_pred_valid = neuralmodel.am(ds.x_visco_valid.to(device),ds.T_visco_valid.to(device)) y_cg_pred_valid = neuralmodel.cg(ds.x_visco_valid.to(device),ds.T_visco_valid.to(device)) y_tvf_pred_valid = neuralmodel.tvf(ds.x_visco_valid.to(device),ds.T_visco_valid.to(device)) y_raman_pred_valid = neuralmodel.raman_pred(ds.x_raman_valid.to(device)) y_density_pred_valid = neuralmodel.density(ds.x_density_valid.to(device)) y_entro_pred_valid = neuralmodel.sctg(ds.x_entro_valid.to(device)) y_tg_pred_valid = neuralmodel.tg(ds.x_tg_valid.to(device)) y_cp_pred_valid = neuralmodel.dCp(ds.x_entro_valid.to(device),neuralmodel.tg(ds.x_entro_valid.to(device))) y_ri_pred_valid = neuralmodel.sellmeier(ds.x_ri_valid.to(device), ds.lbd_ri_valid.to(device)) # validation loss loss_ag_v = precision_visco * criterion(y_ag_pred_valid, ds.y_visco_valid.to(device)) #+ neuralmodel.log_vars[0] loss_myega_v = precision_visco * criterion(y_myega_pred_valid, ds.y_visco_valid.to(device)) #+ neuralmodel.log_vars[0] loss_am_v = precision_visco * criterion(y_am_pred_valid, ds.y_visco_valid.to(device)) #+ neuralmodel.log_vars[0] loss_cg_v = precision_visco * criterion(y_cg_pred_valid, ds.y_visco_valid.to(device)) #+ neuralmodel.log_vars[0] loss_tvf_v = precision_visco * criterion(y_tvf_pred_valid, ds.y_visco_valid.to(device)) #+ neuralmodel.log_vars[0] loss_raman_v = precision_raman * criterion(y_raman_pred_valid,ds.y_raman_valid.to(device)) #+ neuralmodel.log_vars[1] loss_density_v = precision_density * criterion(y_density_pred_valid,ds.y_density_valid.to(device)) #+ neuralmodel.log_vars[2] loss_entro_v = precision_entro * criterion(y_entro_pred_valid,ds.y_entro_valid.to(device)) #+ neuralmodel.log_vars[3] loss_tg_v = precision_tg * criterion(y_tg_pred_valid,ds.y_tg_valid.to(device)) #+ neuralmodel.log_vars[4] loss_ri_v = precision_ri * criterion(y_ri_pred_valid,ds.y_ri_valid.to(device)) #+ neuralmodel.log_vars[5] if mode == "pretrain": loss_v = loss_tg_v + loss_raman_v + loss_density_v + loss_entro_v + loss_ri_v else: loss_v = loss_ag_v + loss_myega_v + loss_am_v + loss_cg_v + loss_tvf_v + loss_raman_v + loss_density_v + loss_entro_v + loss_ri record_valid_loss.append(loss_v.item()) # # Print info on screen # if verbose == True: if (epoch % 5 == 0): print('Epoch {} => train loss: {}; valid loss: {}'.format(epoch, loss/nb_folds, loss_v.item())) # # calculating ES criterion # if epoch == 0: val_ex = 0 best_loss_v = loss_v.item() elif loss_v.item() <= best_loss_v - min_delta: # if improvement is significant, this saves the model val_ex = 0 best_epoch = epoch best_loss_v = loss_v.item() if save_switch == True: # save best model torch.save(neuralmodel.state_dict(), save_name) else: val_ex += 1 epoch += 1 if verbose == True: time2 = time.time() print("Running time in seconds:", time2-time1) print('Scaled valid loss values are {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f} for Tg, Raman, density, entropy, ri, viscosity (AG)'.format( loss_tg_v, loss_raman_v, loss_density_v, loss_entro_v, loss_ri_v, loss_ag_v )) return neuralmodel, record_train_loss, record_valid_loss def R_Raman(x,y, lb = 670, hb = 870): """calculates the R_Raman parameter of a Raman signal y sampled at x. y can be an NxM array with N samples and M Raman shifts. """ A_LW = np.trapz(y[:,x<lb],x[x<lb],axis=1) A_HW = np.trapz(y[:,x>hb],x[x>hb],axis=1) return A_LW/A_HW class bagging_models: """custom class for bagging models and making predictions Parameters ---------- path : str path of models name_models : list of str names of models device : str cpu or gpu Methods ------- predict : function make predictions """ def __init__(self, path, name_models, ds, device): self.device = device self.n_models = len(name_models) self.models = [None for _ in range(self.n_models)] for i in range(self.n_models): name = name_models[i] # Extract arch nb_layers = int(name[name.find("l")+1:name.find("_n")]) nb_neurons = int(name[name.find("n")+1:name.rfind("_p")]) p_drop = float(name[name.find("p")+1:name.rfind("_m")]) #p_drop = float(name[name.find("p")+1:name.rfind(".pth")]) self.models[i] = model(4,nb_neurons,nb_layers,ds.nb_channels_raman,p_drop=p_drop) self.models[i].load_state_dict(torch.load(path+name,map_location='cpu')) self.models[i].eval() def predict(self,method,X, T=[1000.0], lbd= [500.0], sampling=False, n_sample = 10): """returns predictions from the n models Parameters ---------- method : str the property to predict. See imelt code for possibilities. Basically it is a string handle that will be converted to an imelt function. For instance, for tg, enter 'tg'. X : pandas dataframe chemical composition for prediction T : list temperatures for predictions sampling and n_sample are not used at the moment, in dev feature. """ X = torch.Tensor(X).to(self.device) T = torch.Tensor(T).to(self.device) lbd = torch.Tensor(lbd).to(self.device) if sampling == True: for i in range(self.n_models): self.models[i].train() # we let the dropout active for error sampling if method == "raman_pred": out = np.zeros((len(X),850,self.n_models)) # problem is defined with a X raman shift of 850 values for i in range(self.n_models): out[:,:,i] = getattr(self.models[i],method)(X).cpu().detach().numpy() return out else: out = np.zeros((len(X),self.n_models)) if method in frozenset(('ag', 'myega', 'am', 'cg', 'tvf')): for i in range(self.n_models): out[:,i] = getattr(self.models[i],method)(X,T).cpu().detach().numpy().reshape(-1) elif method == "sellmeier": for i in range(self.n_models): out[:,i] = getattr(self.models[i],method)(X,lbd).cpu().detach().numpy().reshape(-1) else: for i in range(self.n_models): out[:,i] = getattr(self.models[i],method)(X).cpu().detach().numpy().reshape(-1) return out def RMSE_viscosity_bydomain(bagged_model, ds, method="ag", boundary=7.0): """return the RMSE between predicted and measured viscosities Parameters ---------- bagged_model : bagged model object generated using the bagging_models class ds : ds dataset contains all the training, validation and test viscosity datasets method : str method to provide to the bagged model boundary : float boundary between the high and low viscosity domains (log Pa s value) Returns ------- total_RMSE : list RMSE between predictions and observations, three values (train-valid-test) high_RMSE : list RMSE between predictions and observations, above the boundary, three values (train-valid-test) low_RMSE : list RMSE between predictions and observations, below the boundary, three values (train-valid-test) """ y_pred_train = bagged_model.predict(method,ds.x_visco_train,ds.T_visco_train).mean(axis=1).reshape(-1,1) y_pred_valid = bagged_model.predict(method,ds.x_visco_valid,ds.T_visco_valid).mean(axis=1).reshape(-1,1) y_pred_test = bagged_model.predict(method,ds.x_visco_test,ds.T_visco_test).mean(axis=1).reshape(-1,1) y_train = ds.y_visco_train y_valid = ds.y_visco_valid y_test = ds.y_visco_test total_RMSE_train = mean_squared_error(y_pred_train,y_train,squared=False) total_RMSE_valid = mean_squared_error(y_pred_valid,y_valid,squared=False) total_RMSE_test = mean_squared_error(y_pred_test,y_test,squared=False) high_RMSE_train = mean_squared_error(y_pred_train[y_train>boundary],y_train[y_train>boundary],squared=False) high_RMSE_valid = mean_squared_error(y_pred_valid[y_valid>boundary],y_valid[y_valid>boundary],squared=False) high_RMSE_test = mean_squared_error(y_pred_test[y_test>boundary],y_test[y_test>boundary],squared=False) low_RMSE_train = mean_squared_error(y_pred_train[y_train<boundary],y_train[y_train<boundary],squared=False) low_RMSE_valid = mean_squared_error(y_pred_valid[y_valid<boundary],y_valid[y_valid<boundary],squared=False) low_RMSE_test = mean_squared_error(y_pred_test[y_test<boundary],y_test[y_test<boundary],squared=False) out1 = [total_RMSE_train, total_RMSE_valid, total_RMSE_test] out2 = [high_RMSE_train, high_RMSE_valid, high_RMSE_test] out3 = [low_RMSE_train, low_RMSE_valid, low_RMSE_test] if method =="ag": name_method = "Adam-Gibbs" elif method == "cg": name_method = "Free Volume" elif method == "tvf": name_method = "<NAME>" elif method == "myega": name_method = "MYEGA" elif method == "am": name_method = "<NAME>" print("Using the equation from {}:".format(name_method)) print(" RMSE on the full range (0-15 log Pa s): train {0:.1f}, valid {1:.1f}, test {2:.1f}".format(total_RMSE_train, total_RMSE_valid, total_RMSE_test)) print(" RMSE on the -inf - {:.1f} log Pa s range: train {:.1f}, valid {:.1f}, test {:.1f}".format(boundary, low_RMSE_train, low_RMSE_valid, low_RMSE_test)) print(" RMSE on the {:.1f} - +inf log Pa s range: train {:.1f}, valid {:.1f}, test {:.1f}".format(boundary, high_RMSE_train, high_RMSE_valid, high_RMSE_test)) print("") return out1, out2, out3 ### ### Functions for chemical calculations ### def chimie_control(data): """check that all needed oxides are there and setup correctly the Pandas datalist. Parameters ---------- data : Pandas dataframe the user input list. Returns ------- out : Pandas dataframe the output list with all required oxides. """ list_oxides = ["sio2","al2o3","na2o","k2o","mgo","cao"] datalist = data.copy() # safety network for i in list_oxides: try: oxd = datalist[i] except: datalist[i] = 0. sum_oxides = datalist["sio2"]+datalist["al2o3"]+datalist["na2o"]+datalist["k2o"] datalist["sio2"] = datalist["sio2"]/sum_oxides datalist["al2o3"] = datalist["al2o3"]/sum_oxides datalist["na2o"] = datalist["na2o"]/sum_oxides datalist["k2o"] = datalist["k2o"]/sum_oxides sum_oxides = datalist["sio2"]+datalist["al2o3"]+datalist["na2o"]+datalist["k2o"] datalist["sum"] = sum_oxides return datalist def molarweights(): """returns a partial table of molecular weights for elements and oxides that can be used in other functions Returns ======= w : dictionary containing the molar weights of elements and oxides: - si, ti, al, fe, li, na, k, mg, ca, ba, o (no upper case, symbol calling) - sio2, tio2, al2o3, fe2o3, feo, li2o, na2o, k2o, mgo, cao, sro, bao (no upper case, symbol calling) """ w = {"si": 28.085} # From IUPAC Periodic Table 2016, in g/mol w["ti"] = 47.867 w["al"] = 26.982 w["fe"] = 55.845 w["h"] = 1.00794 w["li"] = 6.94 w["na"] = 22.990 w["k"] = 39.098 w["mg"] = 24.305 w["ca"] = 40.078 w["ba"] = 137.327 w["sr"] = 87.62 w["o"] = 15.9994 w["ni"] = 58.6934 w["mn"] = 54.938045 w["p"] = 30.973762 # oxides w["sio2"] = w["si"] + 2* w["o"] w["tio2"] = w["ti"] + 2* w["o"] w["al2o3"] = 2*w["al"] + 3* w["o"] w["fe2o3"] = 2*w["fe"] + 3* w["o"] w["feo"] = w["fe"] + w["o"] w["h2o"] = 2*w["h"] + w["o"] w["li2o"] = 2*w["li"] +w["o"] w["na2o"] = 2*w["na"] + w["o"] w["k2o"] = 2*w["k"] + w["o"] w["mgo"] = w["mg"] + w["o"] w["cao"] = w["ca"] + w["o"] w["sro"] = w["sr"] + w["o"] w["bao"] = w["ba"] + w["o"] w["nio"] = w["ni"] + w["o"] w["mno"] = w["mn"] + w["o"] w["p2o5"] = w["p"]*2 + w["o"]*5 return w # explicit return def wt_mol(data): """to convert weights in mol fraction Parameters ========== data: Pandas DataFrame containing the fields sio2,tio2,al2o3,fe2o3,li2o,na2o,k2o,mgo,cao,feo Returns ======= chemtable: Pandas DataFrame contains the fields sio2,tio2,al2o3,fe2o3,li2o,na2o,k2o,mgo,cao,feo in mol% """ chemtable = data.copy() w = molarweights() # conversion to mol in 100 grammes sio2 = chemtable["sio2"]/w["sio2"] al2o3 = chemtable["al2o3"]/w["al2o3"] na2o = chemtable["na2o"]/w["na2o"] k2o = chemtable["k2o"]/w["k2o"] # renormalisation tot = sio2+al2o3+na2o+k2o chemtable["sio2"]=sio2/tot chemtable["al2o3"]=al2o3/tot chemtable["na2o"]=na2o/tot chemtable["k2o"]=k2o/tot return chemtable ### ### Functions for ternary plots (not really needed with mpltern) ### def polycorners(ncorners=3): ''' Return 2D cartesian coordinates of a regular convex polygon of a specified number of corners. Args: ncorners (int, optional) number of corners for the polygon (default 3). Returns: (ncorners, 2) np.ndarray of cartesian coordinates of the polygon. ''' center = np.array([0.5, 0.5]) points = [] for i in range(ncorners): angle = (float(i) / ncorners) * (np.pi * 2) + (np.pi / 2) x = center[0] + np.cos(angle) * 0.5 y = center[1] + np.sin(angle) * 0.5 points.append(np.array([x, y])) return np.array(points) def bary2cart(bary, corners): ''' Convert barycentric coordinates to cartesian coordinates given the cartesian coordinates of the corners. Args: bary (np.ndarray): barycentric coordinates to convert. If this matrix has multiple rows, each row is interpreted as an individual coordinate to convert. corners (np.ndarray): cartesian coordinates of the corners. Returns: 2-column np.ndarray of cartesian coordinates for each barycentric coordinate provided. ''' cart = None if len(bary.shape) > 1 and bary.shape[1] > 1: cart = np.array([np.sum(b / np.sum(b) * corners.T, axis=1) for b in bary]) else: cart = np.sum(bary / np.sum(bary) * corners.T, axis=1) return cart def CLR(input_array): """Transform chemical composition in colors Inputs ------ input_array: n*4 array 4 chemical inputs with sio2, al2o3, k2o and na2o in 4 columns, n samples in rows Returns ------- out: n*3 array RGB colors """ XXX = input_array.copy() XXX[:,2] = XXX[:,2]+XXX[:,3] # adding alkalis out = np.delete(XXX,3,1) # remove 4th row # min max scaling to have colors in the full RGB scale out[:,0] = (out[:,0]-out[:,0].min())/(out[:,0].max()-out[:,0].min()) out[:,1] = (out[:,1]-out[:,1].min())/(out[:,1].max()-out[:,1].min()) out[:,2] = (out[:,2]-out[:,2].min())/(out[:,2].max()-out[:,2].min()) return out def make_ternary(ax,t,l,r, z, labelt,labell,labelr, levels, levels_l, c_m, norm, boundaries_SiO2, annotation = "(a)"): ax.plot([1.0,0.5],[0.,0.5],[0.,0.5],"--",color="black") ax.tricontourf(t,l,r,z, levels=levels, cmap=c_m, norm=norm) tc = ax.tricontour(t,l,r,z, levels=levels_l,colors='k', norm=norm) ax.clabel(tc, inline=1, fontsize=7, fmt="%1.1f") ax.set_tlabel(labelt) #ax.set_llabel(labell) #ax.set_rlabel(labelr) ax.taxis.set_label_rotation_mode('horizontal') #ax.laxis.set_tick_rotation_mode('horizontal') #ax.raxis.set_label_rotation_mode('horizontal') make_arrow(ax, labell, labelr) ax.raxis.set_ticks([]) # Using ``ternary_lim``, you can limit the range of ternary axes. # Be sure about the consistency; the limit values must satisfy: # tmax + lmin + rmin = tmin + lmax + rmin = tmin + lmin + rmax = ternary_scale ax.set_ternary_lim( boundaries_SiO2[0], boundaries_SiO2[1], # tmin, tmax 0.0, boundaries_SiO2[0], # lmin, lmax 0.0, boundaries_SiO2[0], # rmin, rmax ) ax.annotate(annotation, xy=(-0.1,1.0), xycoords="axes fraction", fontsize=12) ax.spines['tside'].set_visible(False) #ax.annotate(labell, xy=(-0.1,-0.07), xycoords="axes fraction", ha="center") #ax.annotate(labelr, xy=(1.1,-0.07), xycoords="axes fraction", ha="center") ax.tick_params(labelrotation='horizontal') def make_arrow(ax, labell, labelr, sx1 = -0.1, sx2 = 1.02, fontsize = 9, linewidth = 2): ax.annotate('', xy=(sx1, 0.03), xycoords='axes fraction', xytext=(sx1+0.08, 0.18), arrowprops=dict(arrowstyle="->", color='k',linewidth=linewidth)) ax.annotate(labell, xy=(sx1+0.03 ,0.08), xycoords="axes fraction", ha="center",rotation=60,fontsize = fontsize) ax.annotate('', xy=(sx2, 0.18), xycoords='axes fraction', xytext=(sx2+0.08, 0.03), arrowprops=dict(arrowstyle="<-", color='k',linewidth=linewidth)) ax.annotate(labelr, xy=(sx2+0.05,0.08), xycoords="axes fraction", ha="center",rotation=-60, fontsize = fontsize)
[ "torch.nn.Dropout", "numpy.sum", "numpy.mean", "numpy.sin", "numpy.std", "torch.load", "torch.FloatTensor", "torch.Tensor", "torch.nn.Linear", "torch.log", "sklearn.metrics.mean_squared_error", "numpy.trapz", "h5py.File", "numpy.cos", "torch.set_grad_enabled", "torch.reshape", "numpy.delete", "torch.nn.ReLU", "numpy.log", "time.time", "numpy.array" ]
[((43013, 43054), 'numpy.trapz', 'np.trapz', (['y[:, x < lb]', 'x[x < lb]'], {'axis': '(1)'}), '(y[:, x < lb], x[x < lb], axis=1)\n', (43021, 43054), True, 'import numpy as np\n'), ((43060, 43101), 'numpy.trapz', 'np.trapz', (['y[:, x > hb]', 'x[x > hb]'], {'axis': '(1)'}), '(y[:, x > hb], x[x > hb], axis=1)\n', (43068, 43101), True, 'import numpy as np\n'), ((47454, 47510), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_pred_train', 'y_train'], {'squared': '(False)'}), '(y_pred_train, y_train, squared=False)\n', (47472, 47510), False, 'from sklearn.metrics import mean_squared_error\n'), ((47532, 47588), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_pred_valid', 'y_valid'], {'squared': '(False)'}), '(y_pred_valid, y_valid, squared=False)\n', (47550, 47588), False, 'from sklearn.metrics import mean_squared_error\n'), ((47609, 47663), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_pred_test', 'y_test'], {'squared': '(False)'}), '(y_pred_test, y_test, squared=False)\n', (47627, 47663), False, 'from sklearn.metrics import mean_squared_error\n'), ((47689, 47789), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_pred_train[y_train > boundary]', 'y_train[y_train > boundary]'], {'squared': '(False)'}), '(y_pred_train[y_train > boundary], y_train[y_train >\n boundary], squared=False)\n', (47707, 47789), False, 'from sklearn.metrics import mean_squared_error\n'), ((47802, 47902), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_pred_valid[y_valid > boundary]', 'y_valid[y_valid > boundary]'], {'squared': '(False)'}), '(y_pred_valid[y_valid > boundary], y_valid[y_valid >\n boundary], squared=False)\n', (47820, 47902), False, 'from sklearn.metrics import mean_squared_error\n'), ((47914, 48011), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_pred_test[y_test > boundary]', 'y_test[y_test > boundary]'], {'squared': '(False)'}), '(y_pred_test[y_test > boundary], y_test[y_test > boundary\n ], squared=False)\n', (47932, 48011), False, 'from sklearn.metrics import mean_squared_error\n'), ((48027, 48127), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_pred_train[y_train < boundary]', 'y_train[y_train < boundary]'], {'squared': '(False)'}), '(y_pred_train[y_train < boundary], y_train[y_train <\n boundary], squared=False)\n', (48045, 48127), False, 'from sklearn.metrics import mean_squared_error\n'), ((48139, 48239), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_pred_valid[y_valid < boundary]', 'y_valid[y_valid < boundary]'], {'squared': '(False)'}), '(y_pred_valid[y_valid < boundary], y_valid[y_valid <\n boundary], squared=False)\n', (48157, 48239), False, 'from sklearn.metrics import mean_squared_error\n'), ((48250, 48347), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_pred_test[y_test < boundary]', 'y_test[y_test < boundary]'], {'squared': '(False)'}), '(y_pred_test[y_test < boundary], y_test[y_test < boundary\n ], squared=False)\n', (48268, 48347), False, 'from sklearn.metrics import mean_squared_error\n'), ((53597, 53617), 'numpy.array', 'np.array', (['[0.5, 0.5]'], {}), '([0.5, 0.5])\n', (53605, 53617), True, 'import numpy as np\n'), ((53871, 53887), 'numpy.array', 'np.array', (['points'], {}), '(points)\n', (53879, 53887), True, 'import numpy as np\n'), ((55038, 55058), 'numpy.delete', 'np.delete', (['XXX', '(3)', '(1)'], {}), '(XXX, 3, 1)\n', (55047, 55058), True, 'import numpy as np\n'), ((1057, 1087), 'h5py.File', 'h5py.File', (['path_viscosity', '"""r"""'], {}), "(path_viscosity, 'r')\n", (1066, 1087), False, 'import h5py\n'), ((2047, 2073), 'h5py.File', 'h5py.File', (['path_raman', '"""r"""'], {}), "(path_raman, 'r')\n", (2056, 2073), False, 'import h5py\n'), ((2317, 2345), 'h5py.File', 'h5py.File', (['path_density', '"""r"""'], {}), "(path_density, 'r')\n", (2326, 2345), False, 'import h5py\n'), ((2720, 2743), 'h5py.File', 'h5py.File', (['path_ri', '"""r"""'], {}), "(path_ri, 'r')\n", (2729, 2743), False, 'import h5py\n'), ((13943, 13958), 'torch.nn.ReLU', 'torch.nn.ReLU', ([], {}), '()\n', (13956, 13958), False, 'import torch, time\n'), ((15129, 15155), 'torch.nn.Dropout', 'torch.nn.Dropout', ([], {'p': 'p_drop'}), '(p=p_drop)\n', (15145, 15155), False, 'import torch, time\n'), ((15394, 15431), 'torch.nn.Linear', 'torch.nn.Linear', (['self.hidden_size', '(17)'], {}), '(self.hidden_size, 17)\n', (15409, 15431), False, 'import torch, time\n'), ((15474, 15531), 'torch.nn.Linear', 'torch.nn.Linear', (['self.hidden_size', 'self.nb_channels_raman'], {}), '(self.hidden_size, self.nb_channels_raman)\n', (15489, 15531), False, 'import torch, time\n'), ((16820, 16857), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (16833, 16857), False, 'import torch, time\n'), ((17072, 17109), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (17085, 17109), False, 'import torch, time\n'), ((17265, 17302), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (17278, 17302), False, 'import torch, time\n'), ((17481, 17518), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (17494, 17518), False, 'import torch, time\n'), ((17657, 17694), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (17670, 17694), False, 'import torch, time\n'), ((17958, 17995), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (17971, 17995), False, 'import torch, time\n'), ((18141, 18178), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (18154, 18178), False, 'import torch, time\n'), ((18322, 18359), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (18335, 18359), False, 'import torch, time\n'), ((18497, 18534), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (18510, 18534), False, 'import torch, time\n'), ((18672, 18709), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (18685, 18709), False, 'import torch, time\n'), ((18848, 18885), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (18861, 18885), False, 'import torch, time\n'), ((19035, 19072), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (19048, 19072), False, 'import torch, time\n'), ((19221, 19258), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (19234, 19258), False, 'import torch, time\n'), ((19408, 19445), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (19421, 19445), False, 'import torch, time\n'), ((19578, 19615), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (19591, 19615), False, 'import torch, time\n'), ((19752, 19789), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (19765, 19789), False, 'import torch, time\n'), ((19907, 19944), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (19920, 19944), False, 'import torch, time\n'), ((20062, 20099), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (20075, 20099), False, 'import torch, time\n'), ((20217, 20254), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (20230, 20254), False, 'import torch, time\n'), ((20398, 20435), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (20411, 20435), False, 'import torch, time\n'), ((20579, 20616), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (20592, 20616), False, 'import torch, time\n'), ((20759, 20796), 'torch.reshape', 'torch.reshape', (['out', '(out.shape[0], 1)'], {}), '(out, (out.shape[0], 1))\n', (20772, 20796), False, 'import torch, time\n'), ((24499, 24510), 'time.time', 'time.time', ([], {}), '()\n', (24508, 24510), False, 'import torch, time\n'), ((29955, 29966), 'time.time', 'time.time', ([], {}), '()\n', (29964, 29966), False, 'import torch, time\n'), ((31825, 31836), 'time.time', 'time.time', ([], {}), '()\n', (31834, 31836), False, 'import torch, time\n'), ((42436, 42447), 'time.time', 'time.time', ([], {}), '()\n', (42445, 42447), False, 'import torch, time\n'), ((3490, 3522), 'numpy.mean', 'np.mean', (['X_train[:, 0:4]'], {'axis': '(0)'}), '(X_train[:, 0:4], axis=0)\n', (3497, 3522), True, 'import numpy as np\n'), ((3549, 3580), 'numpy.std', 'np.std', (['X_train[:, 0:4]'], {'axis': '(0)'}), '(X_train[:, 0:4], axis=0)\n', (3555, 3580), True, 'import numpy as np\n'), ((27834, 27863), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (27856, 27863), False, 'import torch, time\n'), ((38272, 38301), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (38294, 38301), False, 'import torch, time\n'), ((53841, 53857), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (53849, 53857), True, 'import numpy as np\n'), ((7678, 7710), 'torch.FloatTensor', 'torch.FloatTensor', (['y_raman_train'], {}), '(y_raman_train)\n', (7695, 7710), False, 'import torch, time\n'), ((7873, 7905), 'torch.FloatTensor', 'torch.FloatTensor', (['y_raman_valid'], {}), '(y_raman_valid)\n', (7890, 7905), False, 'import torch, time\n'), ((15201, 15246), 'torch.nn.Linear', 'torch.nn.Linear', (['input_size', 'self.hidden_size'], {}), '(input_size, self.hidden_size)\n', (15216, 15246), False, 'import torch, time\n'), ((15278, 15329), 'torch.nn.Linear', 'torch.nn.Linear', (['self.hidden_size', 'self.hidden_size'], {}), '(self.hidden_size, self.hidden_size)\n', (15293, 15329), False, 'import torch, time\n'), ((44151, 44194), 'torch.load', 'torch.load', (['(path + name)'], {'map_location': '"""cpu"""'}), "(path + name, map_location='cpu')\n", (44161, 44194), False, 'import torch, time\n'), ((44856, 44871), 'torch.Tensor', 'torch.Tensor', (['X'], {}), '(X)\n', (44868, 44871), False, 'import torch, time\n'), ((44900, 44915), 'torch.Tensor', 'torch.Tensor', (['T'], {}), '(T)\n', (44912, 44915), False, 'import torch, time\n'), ((44946, 44963), 'torch.Tensor', 'torch.Tensor', (['lbd'], {}), '(lbd)\n', (44958, 44963), False, 'import torch, time\n'), ((53755, 53768), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (53761, 53768), True, 'import numpy as np\n'), ((53799, 53812), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (53805, 53812), True, 'import numpy as np\n'), ((17574, 17586), 'torch.log', 'torch.log', (['T'], {}), '(T)\n', (17583, 17586), False, 'import torch, time\n'), ((54617, 54629), 'numpy.sum', 'np.sum', (['bary'], {}), '(bary)\n', (54623, 54629), True, 'import numpy as np\n'), ((15792, 15806), 'numpy.log', 'np.log', (['(1000.0)'], {}), '(1000.0)\n', (15798, 15806), True, 'import numpy as np\n'), ((15806, 15818), 'numpy.log', 'np.log', (['(10.0)'], {}), '(10.0)\n', (15812, 15818), True, 'import numpy as np\n'), ((16016, 16029), 'numpy.log', 'np.log', (['(500.0)'], {}), '(500.0)\n', (16022, 16029), True, 'import numpy as np\n'), ((16030, 16043), 'numpy.log', 'np.log', (['(100.0)'], {}), '(100.0)\n', (16036, 16043), True, 'import numpy as np\n'), ((16044, 16057), 'numpy.log', 'np.log', (['(400.0)'], {}), '(400.0)\n', (16050, 16057), True, 'import numpy as np\n'), ((16148, 16159), 'numpy.log', 'np.log', (['(2.3)'], {}), '(2.3)\n', (16154, 16159), True, 'import numpy as np\n'), ((16160, 16172), 'numpy.log', 'np.log', (['(25.0)'], {}), '(25.0)\n', (16166, 16172), True, 'import numpy as np\n'), ((54531, 54540), 'numpy.sum', 'np.sum', (['b'], {}), '(b)\n', (54537, 54540), True, 'import numpy as np\n')]
#!/usr/bin/env python """ This file uses Theano dense layers for estimating Q values, but uses pre-trained Keras features before the dense layers. """ # -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function from vizdoom import * import itertools as it from random import sample, randint, random from time import time, sleep import numpy as np import skimage.color, skimage.transform from tqdm import trange import pickle from keras.layers import Input, Dense, Convolution2D, Activation, Flatten from keras.models import Model from keras.optimizers import SGD import theano.tensor as T import theano import layers from lasagne.objectives import squared_error from lasagne.updates import rmsprop # Q-learning settings learning_rate = 0.00025 # learning_rate = 0.0001 discount_factor = 0.99 epochs = 20 learning_steps_per_epoch = 2000 replay_memory_size = 10000 # NN learning settings batch_size = 64 # Training regime test_episodes_per_epoch = 100 # Other parameters frame_repeat = 12 resolution = (224, 224) episodes_to_watch = 10 model_savefile = "./weights.dump" # Configuration file path config_file_path = "../../scenarios/simpler_basic.cfg" # config_file_path = "../../scenarios/rocket_basic.cfg" # config_file_path = "../../scenarios/basic.cfg" # Converts and downsamples the input image def preprocess(img): img = skimage.transform.resize(img, resolution) img = img.astype(np.float32) return img class ReplayMemory: def __init__(self, capacity): state_shape = (capacity, 4096) self.s1 = np.zeros(state_shape, dtype=np.float32) self.s2 = np.zeros(state_shape, dtype=np.float32) self.a = np.zeros(capacity, dtype=np.int32) self.r = np.zeros(capacity, dtype=np.float32) self.isterminal = np.zeros(capacity, dtype=np.bool_) self.capacity = capacity self.size = 0 self.pos = 0 def add_transition(self, s1, action, s2, isterminal, reward): self.s1[self.pos, :] = s1 self.a[self.pos] = action if not isterminal: self.s2[self.pos, :] = s2 self.isterminal[self.pos] = isterminal self.r[self.pos] = reward self.pos = (self.pos + 1) % self.capacity self.size = min(self.size + 1, self.capacity) def get_sample(self, sample_size): i = sample(range(0, self.size), sample_size) return self.s1[i], self.a[i], self.s2[i], self.isterminal[i], self.r[i] def create_network(available_actions_count): s1 = T.matrix("State") a = T.vector("Action", dtype="int32") q2 = T.vector("Q2") r = T.vector("Reward") isterminal = T.vector("IsTerminal", dtype="int8") input_state = s1 #Input(shape=(4096,)) # Add a single fully-connected layer. dense_1 = layers.FCLayer(input=input_state, fan_in=4096, num_hidden=128) # Add the output layer. (no nonlinearity as it is for approximating an arbitrary real function) dense_2 = layers.FCLayer(input=dense_1.out, fan_in=128, num_hidden=available_actions_count, activation=None) q = dense_2.out # target_Q(s,a) = r + gamma * max Q(s2,_) if isterminal else r target_q = T.set_subtensor(q[T.arange(q.shape[0]), a], r + discount_factor * (1 - isterminal) * q2) loss = squared_error(q, target_q).mean() # Update the parameters according to the computed gradient using RMSProp. params = dense_1.params + dense_2.params updates = rmsprop(loss, params, learning_rate) # Compile the theano functions print("Compiling the network ...") function_learn = theano.function([s1, q2, a, r, isterminal], loss, updates=updates, name="learn_fn", allow_input_downcast=True) function_get_q_values = theano.function([s1], q, name="eval_fn", allow_input_downcast=True) function_get_best_action = theano.function([s1], T.argmax(q), name="test_fn", allow_input_downcast=True) print("Network compiled.") def simple_get_best_action(state): return function_get_best_action(state) # Returns Theano objects for the net and functions. return params, function_learn, function_get_q_values, simple_get_best_action def learn_from_memory(): """ Learns from a single transition (making use of replay memory). s2 is ignored if s2_isterminal """ # Get a random minibatch from the replay memory and learns from it. if memory.size > batch_size: s1, a, s2, isterminal, r = memory.get_sample(batch_size) q2 = get_q_values(s2) maxq2 = np.max(q2, axis=1) # the value of q2 is ignored in learn if s2 is terminal learn(s1, maxq2, a, r, isterminal) def get_pre_trained_features(im): im = 255 * np.stack([im, im, im], axis=0) im[0,:,:] -= 103.939 #TODO: Check if the format is RGB or BGR im[1,:,:] -= 116.779 im[2,:,:] -= 123.68 im = np.expand_dims(im, axis=0) features = get_penaltimate_features([im, 0])[0] s1new = np.zeros(shape=(1, 4096)) s1new[0, :] = features return s1new from keras import backend as K from vggModel import * CNN_model = vggModel('/home/monaj/Documents/myKeras/LRCN/vgg16_weights.h5') get_penaltimate_features = K.function([CNN_model.layers[0].input, K.learning_phase()], [CNN_model.layers[-2].output]) def perform_learning_step(epoch): """ Makes an action according to eps-greedy policy, observes the result (next state, reward) and learns from the transition""" def exploration_rate(epoch): """# Define exploration rate change over time""" start_eps = 1.0 end_eps = 0.1 const_eps_epochs = 0.1 * epochs # 10% of learning time eps_decay_epochs = 0.6 * epochs # 60% of learning time if epoch < const_eps_epochs: return start_eps elif epoch < eps_decay_epochs: # Linear decay return start_eps - (epoch - const_eps_epochs) / \ (eps_decay_epochs - const_eps_epochs) * (start_eps - end_eps) else: return end_eps s1 = preprocess(game.get_state().screen_buffer) s1 = get_pre_trained_features(s1) # With probability eps make a random action. eps = exploration_rate(epoch) if random() <= eps: a = randint(0, len(actions) - 1) else: # Choose the best action according to the network. a = get_best_action(s1) reward = game.make_action(actions[a], frame_repeat) isterminal = game.is_episode_finished() s2 = get_pre_trained_features(preprocess(game.get_state().screen_buffer)) if not isterminal else None # Remember the transition that was just experienced. memory.add_transition(s1, a, s2, isterminal, reward) learn_from_memory() # Creates and initializes ViZDoom environment. def initialize_vizdoom(config_file_path): print("Initializing doom...") game = DoomGame() game.load_config(config_file_path) game.set_window_visible(False) game.set_mode(Mode.PLAYER) game.set_screen_format(ScreenFormat.GRAY8) game.set_screen_resolution(ScreenResolution.RES_640X480) game.init() print("Doom initialized.") return game def set_all_param_values_special(params, values, **tags): if len(params) != len(values): raise ValueError("mismatch: got %d values to set %d parameters" % (len(values), len(params))) for p, v in zip(params, values): if p.get_value().shape != v.shape: raise ValueError("mismatch: parameter has shape %r but value to " "set has shape %r" % (p.get_value().shape, v.shape)) else: p.set_value(v) # Create Doom instance game = initialize_vizdoom(config_file_path) # Action = which buttons are pressed n = game.get_available_buttons_size() actions = [list(a) for a in it.product([0, 1], repeat=n)] # Create replay memory which will store the transitions memory = ReplayMemory(capacity=replay_memory_size) params, learn, get_q_values, get_best_action = create_network(len(actions)) print("Starting the training!") time_start = time() for epoch in range(epochs): print("\nEpoch %d\n-------" % (epoch + 1)) train_episodes_finished = 0 train_scores = [] print("Training...") game.new_episode() for learning_step in trange(learning_steps_per_epoch): perform_learning_step(epoch) if game.is_episode_finished(): score = game.get_total_reward() train_scores.append(score) game.new_episode() train_episodes_finished += 1 print("%d training episodes played." % train_episodes_finished) train_scores = np.array(train_scores) print("Results: mean: %.1f±%.1f," % (train_scores.mean(), train_scores.std()), \ "min: %.1f," % train_scores.min(), "max: %.1f," % train_scores.max()) print("\nTesting...") test_episode = [] test_scores = [] for test_episode in trange(test_episodes_per_epoch): game.new_episode() while not game.is_episode_finished(): state = preprocess(game.get_state().screen_buffer) state = get_pre_trained_features(state) best_action_index = get_best_action(state) game.make_action(actions[best_action_index], frame_repeat) r = game.get_total_reward() test_scores.append(r) test_scores = np.array(test_scores) print("Results: mean: %.1f±%.1f," % ( test_scores.mean(), test_scores.std()), "min: %.1f" % test_scores.min(), "max: %.1f" % test_scores.max()) print("Saving the network weigths to:", model_savefile) pickle.dump([p.get_value() for p in params], open(model_savefile, "wb")) print("Total elapsed time: %.2f minutes" % ((time() - time_start) / 60.0)) game.close() print("======================================") print("Loading the network weigths from:", model_savefile) print("Training finished. It's time to watch!") # Load the network's parameters from a file params_values = pickle.load(open(model_savefile, "rb")) set_all_param_values_special(params, params_values) # Reinitialize the game with window visible game.set_window_visible(True) game.set_mode(Mode.ASYNC_PLAYER) game.init() for _ in range(episodes_to_watch): game.new_episode() while not game.is_episode_finished(): state = preprocess(game.get_state().screen_buffer) state = get_pre_trained_features(state) best_action_index = get_best_action(state) # Instead of make_action(a, frame_repeat) in order to make the animation smooth game.set_action(actions[best_action_index]) for _ in range(frame_repeat): game.advance_action() # Sleep between episodes sleep(1.0) score = game.get_total_reward() print("Total score: ", score)
[ "layers.FCLayer", "lasagne.objectives.squared_error", "numpy.max", "itertools.product", "theano.tensor.arange", "numpy.stack", "keras.backend.learning_phase", "tqdm.trange", "time.sleep", "random.random", "theano.tensor.matrix", "lasagne.updates.rmsprop", "theano.tensor.vector", "theano.function", "numpy.zeros", "numpy.expand_dims", "time.time", "numpy.array", "theano.tensor.argmax" ]
[((8092, 8098), 'time.time', 'time', ([], {}), '()\n', (8096, 8098), False, 'from time import time, sleep\n'), ((2530, 2547), 'theano.tensor.matrix', 'T.matrix', (['"""State"""'], {}), "('State')\n", (2538, 2547), True, 'import theano.tensor as T\n'), ((2556, 2589), 'theano.tensor.vector', 'T.vector', (['"""Action"""'], {'dtype': '"""int32"""'}), "('Action', dtype='int32')\n", (2564, 2589), True, 'import theano.tensor as T\n'), ((2599, 2613), 'theano.tensor.vector', 'T.vector', (['"""Q2"""'], {}), "('Q2')\n", (2607, 2613), True, 'import theano.tensor as T\n'), ((2622, 2640), 'theano.tensor.vector', 'T.vector', (['"""Reward"""'], {}), "('Reward')\n", (2630, 2640), True, 'import theano.tensor as T\n'), ((2658, 2694), 'theano.tensor.vector', 'T.vector', (['"""IsTerminal"""'], {'dtype': '"""int8"""'}), "('IsTerminal', dtype='int8')\n", (2666, 2694), True, 'import theano.tensor as T\n'), ((2797, 2859), 'layers.FCLayer', 'layers.FCLayer', ([], {'input': 'input_state', 'fan_in': '(4096)', 'num_hidden': '(128)'}), '(input=input_state, fan_in=4096, num_hidden=128)\n', (2811, 2859), False, 'import layers\n'), ((2974, 3077), 'layers.FCLayer', 'layers.FCLayer', ([], {'input': 'dense_1.out', 'fan_in': '(128)', 'num_hidden': 'available_actions_count', 'activation': 'None'}), '(input=dense_1.out, fan_in=128, num_hidden=\n available_actions_count, activation=None)\n', (2988, 3077), False, 'import layers\n'), ((3448, 3484), 'lasagne.updates.rmsprop', 'rmsprop', (['loss', 'params', 'learning_rate'], {}), '(loss, params, learning_rate)\n', (3455, 3484), False, 'from lasagne.updates import rmsprop\n'), ((3581, 3696), 'theano.function', 'theano.function', (['[s1, q2, a, r, isterminal]', 'loss'], {'updates': 'updates', 'name': '"""learn_fn"""', 'allow_input_downcast': '(True)'}), "([s1, q2, a, r, isterminal], loss, updates=updates, name=\n 'learn_fn', allow_input_downcast=True)\n", (3596, 3696), False, 'import theano\n'), ((3720, 3787), 'theano.function', 'theano.function', (['[s1]', 'q'], {'name': '"""eval_fn"""', 'allow_input_downcast': '(True)'}), "([s1], q, name='eval_fn', allow_input_downcast=True)\n", (3735, 3787), False, 'import theano\n'), ((4840, 4866), 'numpy.expand_dims', 'np.expand_dims', (['im'], {'axis': '(0)'}), '(im, axis=0)\n', (4854, 4866), True, 'import numpy as np\n'), ((4931, 4956), 'numpy.zeros', 'np.zeros', ([], {'shape': '(1, 4096)'}), '(shape=(1, 4096))\n', (4939, 4956), True, 'import numpy as np\n'), ((8302, 8334), 'tqdm.trange', 'trange', (['learning_steps_per_epoch'], {}), '(learning_steps_per_epoch)\n', (8308, 8334), False, 'from tqdm import trange\n'), ((8656, 8678), 'numpy.array', 'np.array', (['train_scores'], {}), '(train_scores)\n', (8664, 8678), True, 'import numpy as np\n'), ((8939, 8970), 'tqdm.trange', 'trange', (['test_episodes_per_epoch'], {}), '(test_episodes_per_epoch)\n', (8945, 8970), False, 'from tqdm import trange\n'), ((9372, 9393), 'numpy.array', 'np.array', (['test_scores'], {}), '(test_scores)\n', (9380, 9393), True, 'import numpy as np\n'), ((10718, 10728), 'time.sleep', 'sleep', (['(1.0)'], {}), '(1.0)\n', (10723, 10728), False, 'from time import time, sleep\n'), ((1573, 1612), 'numpy.zeros', 'np.zeros', (['state_shape'], {'dtype': 'np.float32'}), '(state_shape, dtype=np.float32)\n', (1581, 1612), True, 'import numpy as np\n'), ((1631, 1670), 'numpy.zeros', 'np.zeros', (['state_shape'], {'dtype': 'np.float32'}), '(state_shape, dtype=np.float32)\n', (1639, 1670), True, 'import numpy as np\n'), ((1688, 1722), 'numpy.zeros', 'np.zeros', (['capacity'], {'dtype': 'np.int32'}), '(capacity, dtype=np.int32)\n', (1696, 1722), True, 'import numpy as np\n'), ((1740, 1776), 'numpy.zeros', 'np.zeros', (['capacity'], {'dtype': 'np.float32'}), '(capacity, dtype=np.float32)\n', (1748, 1776), True, 'import numpy as np\n'), ((1803, 1837), 'numpy.zeros', 'np.zeros', (['capacity'], {'dtype': 'np.bool_'}), '(capacity, dtype=np.bool_)\n', (1811, 1837), True, 'import numpy as np\n'), ((3841, 3852), 'theano.tensor.argmax', 'T.argmax', (['q'], {}), '(q)\n', (3849, 3852), True, 'import theano.tensor as T\n'), ((4507, 4525), 'numpy.max', 'np.max', (['q2'], {'axis': '(1)'}), '(q2, axis=1)\n', (4513, 4525), True, 'import numpy as np\n'), ((4684, 4714), 'numpy.stack', 'np.stack', (['[im, im, im]'], {'axis': '(0)'}), '([im, im, im], axis=0)\n', (4692, 4714), True, 'import numpy as np\n'), ((5198, 5216), 'keras.backend.learning_phase', 'K.learning_phase', ([], {}), '()\n', (5214, 5216), True, 'from keras import backend as K\n'), ((6197, 6205), 'random.random', 'random', ([], {}), '()\n', (6203, 6205), False, 'from random import sample, randint, random\n'), ((7831, 7859), 'itertools.product', 'it.product', (['[0, 1]'], {'repeat': 'n'}), '([0, 1], repeat=n)\n', (7841, 7859), True, 'import itertools as it\n'), ((3276, 3302), 'lasagne.objectives.squared_error', 'squared_error', (['q', 'target_q'], {}), '(q, target_q)\n', (3289, 3302), False, 'from lasagne.objectives import squared_error\n'), ((3194, 3214), 'theano.tensor.arange', 'T.arange', (['q.shape[0]'], {}), '(q.shape[0])\n', (3202, 3214), True, 'import theano.tensor as T\n'), ((9738, 9744), 'time.time', 'time', ([], {}), '()\n', (9742, 9744), False, 'from time import time, sleep\n')]
"""GUI for rejecting epochs""" # Author: <NAME> <<EMAIL>> # Document: represents data # ChangeAction: modifies Document # Model: creates ChangeActions and applies them to the History # Frame: # - visualizaes Document # - listens to Document changes # - issues commands to Model from logging import getLogger import math import os import re import time import numpy as np from scipy.spatial.distance import cdist import wx from .. import _meeg as meeg from .. import _text from .. import load, save, plot, fmtxt from .._data_obj import Dataset, Factor, Var, Datalist, asndvar, combine from .._info import BAD_CHANNELS from .._names import INTERPOLATE_CHANNELS from .._ndvar import neighbor_correlation from .._utils.parse import FLOAT_PATTERN, POS_FLOAT_PATTERN, INT_PATTERN from .._utils.numpy_utils import FULL_SLICE, INT_TYPES from ..mne_fixes import MNE_EPOCHS from ..plot._base import AxisData, LayerData, PlotType, AxisScale, find_fig_vlims, find_fig_cmaps from ..plot._nuts import _plt_bin_nuts from ..plot._topo import _ax_topomap from ..plot._utsnd import _ax_bfly_epoch from .app import get_app from .frame import EelbrainDialog from .mpl_canvas import FigureCanvasPanel from .history import Action, FileDocument, FileModel, FileFrame from .text import HTMLFrame from .utils import Icon, REValidator from . import ID # IDs MEAN_PLOT = -1 TOPO_PLOT = -2 OUT_OF_RANGE = -3 # For unit-tests TEST_MODE = False def _epoch_list_to_ranges(elist): out = [] i = 0 i_last = len(elist) - 1 start = None while i <= i_last: cur = elist[i] if i < i_last and elist[i + 1] - cur == 1: if start is None: start = cur elif start is None: out.append(fmtxt.Link(cur, 'epoch:%i' % cur)) else: out.append(fmtxt.Link(start, 'epoch:%i' % start) + '-' + fmtxt.Link(cur, 'epoch:%i' % cur)) start = None i += 1 return out def format_epoch_list(l, head="Epochs by channel:"): d = meeg.channel_listlist_to_dict(l) if not d: return "None." out = fmtxt.List(head) for ch in sorted(d, key=lambda x: -len(d[x])): item = fmtxt.FMText("%s (%i): " % (ch, len(d[ch]))) item += fmtxt.delim_list(_epoch_list_to_ranges(d[ch])) out.add_item(item) return out class ChangeAction(Action): """Action objects are kept in the history and can do and undo themselves Parameters ---------- desc : str Description of the action list of (i, name, old, new) tuples """ def __init__(self, desc, index=None, old_accept=None, new_accept=None, old_tag=None, new_tag=None, old_path=None, new_path=None, old_bad_chs=None, new_bad_chs=None, old_interpolate=None, new_interpolate=None): self.desc = desc self.index = index self.old_path = old_path self.old_accept = old_accept self.old_tag = old_tag self.new_path = new_path self.new_accept = new_accept self.new_tag = new_tag self.old_bad_chs = old_bad_chs self.new_bad_chs = new_bad_chs self.old_interpolate = old_interpolate self.new_interpolate = new_interpolate def do(self, doc): if self.index is not None: doc.set_case(self.index, self.new_accept, self.new_tag, self.new_interpolate) if self.new_path is not None: doc.set_path(self.new_path) if self.new_bad_chs is not None: doc.set_bad_channels(self.new_bad_chs) def undo(self, doc): if self.index is not None: doc.set_case(self.index, self.old_accept, self.old_tag, self.old_interpolate) if self.new_path is not None and self.old_path is not None: doc.set_path(self.old_path) if self.new_bad_chs is not None: doc.set_bad_channels(self.old_bad_chs) class Document(FileDocument): """Represent the current state of the Document Data can be accesses through attributes, but should only be changed through the set_...() methods. Parameters ---------- path : None | str Default location of the epoch selection file (used for save command). If the file exists, it is loaded as initial state. Attributes ---------- n_epochs : int The number of epochs. epochs : NDVar The raw epochs. accept : Var of bool Case status. tag : Factor Case tag. trigger : Var of int Case trigger value. blink : Datalist | None Case eye tracker artifact data. """ def __init__(self, ds, data='meg', accept='accept', blink='blink', tag='rej_tag', trigger='trigger', path=None, bad_chs=None, allow_interpolation=True): FileDocument.__init__(self, path) if isinstance(ds, MNE_EPOCHS): epochs = ds ds = Dataset() epochs.load_data() ds[data] = epochs ds['trigger'] = Var(epochs.events[:, 2]) data = asndvar(data, ds=ds) self.n_epochs = n = len(data) if not isinstance(accept, str): raise TypeError("accept needs to be a string") if accept not in ds: x = np.ones(n, dtype=bool) ds[accept] = Var(x) accept = ds[accept] if not isinstance(tag, str): raise TypeError("tag needs to be a string") if tag in ds: tag = ds[tag] else: tag = Factor([''], repeat=n, name=tag) ds.add(tag) if not isinstance(trigger, str): raise TypeError("trigger needs to be a string") if trigger in ds: trigger = ds[trigger] else: raise KeyError(f"ds does not contain a variable named {trigger!r}. The trigger parameters needs to point to a variable in ds containing trigger values.") if INTERPOLATE_CHANNELS in ds: interpolate = ds[INTERPOLATE_CHANNELS] if not allow_interpolation and any(interpolate): raise ValueError("Dataset contains channel interpolation information but interpolation is turned off") else: interpolate = Datalist([[]] * ds.n_cases, INTERPOLATE_CHANNELS, 'strlist') if isinstance(blink, str): if ds is not None: blink = ds.get(blink, None) elif blink is True: if 'edf' in ds.info: tmin = data.time.tmin tmax = data.time.tmax _, blink = load.eyelink.artifact_epochs(ds, tmin, tmax, esacc=False) else: wx.MessageBox("No eye tracker data was found in ds.info['edf']. Use load.eyelink.add_edf(ds) to add an eye tracker file to a Dataset ds.", "Eye Tracker Data Not Found") blink = None elif blink is not None: raise TypeError("blink needs to be a string or None") if blink is not None: raise NotImplementedError("Frame.SetPage() needs to be updated to use blink information") # options self.allow_interpolation = allow_interpolation # data self.epochs = data self.accept = accept self.tag = tag self.interpolate = interpolate self.trigger = trigger self.blink = blink self.bad_channels = [] # list of int self.good_channels = None # cache self._good_sensor_indices = {} # publisher self.callbacks.register_key('case_change') self.callbacks.register_key('bad_chs_change') # finalize if bad_chs is not None: self.set_bad_channels_by_name(bad_chs) if path and os.path.exists(path): accept, tag, interpolate, bad_chs = self.read_rej_file(path) self.accept[:] = accept self.tag[:] = tag self.interpolate[:] = interpolate self.set_bad_channels(bad_chs) self.saved = True @property def bad_channel_names(self): return [self.epochs.sensor.names[i] for i in self.bad_channels] def iter_good_epochs(self): "All cases, only good channels" if self.bad_channels: epochs = self.epochs.sub(sensor=self.good_channels) else: epochs = self.epochs bad_set = set(self.bad_channel_names) interpolate = [set(chs) - bad_set for chs in self.interpolate] if any(interpolate): for epoch, chs in zip(epochs, interpolate): if chs: yield epoch.sub(sensor=epoch.sensor.index(exclude=chs)) else: yield epoch else: for epoch in epochs: yield epoch def good_sensor_index(self, case): "Index of non-interpolated sensor relative to good sensors" if self.interpolate[case]: key = frozenset(self.interpolate[case]) if key in self._good_sensor_indices: return self._good_sensor_indices[key] else: out = np.ones(len(self.epochs.sensor), bool) out[self.epochs.sensor._array_index(self.interpolate[case])] = False if self.good_channels is not None: out = out[self.good_channels] self._good_sensor_indices[key] = out return out def get_epoch(self, case, name): if self.bad_channels: return self.epochs.sub(case=case, sensor=self.good_channels, name=name) else: return self.epochs.sub(case=case, name=name) def get_grand_average(self): "Grand average of all accepted epochs" return self.epochs.sub(case=self.accept.x, sensor=self.good_channels, name="Grand Average").mean('case') def set_bad_channels(self, indexes): """Set the channels to treat as bad (i.e., exclude) Parameters ---------- bad_chs : collection of int Indices of channels to treat as bad. """ indexes = sorted(indexes) if indexes == self.bad_channels: return self.bad_channels = indexes if indexes: self.good_channels = np.setdiff1d(np.arange(len(self.epochs.sensor)), indexes, True) else: self.good_channels = None self._good_sensor_indices.clear() self.callbacks.callback('bad_chs_change') def set_bad_channels_by_name(self, names): self.set_bad_channels(self.epochs.sensor._array_index(names)) def set_case(self, index, state, tag, interpolate): if state is not None: self.accept[index] = state if tag is not None: self.tag[index] = tag if interpolate is not None: self.interpolate[index] = interpolate self.callbacks.callback('case_change', index) def set_path(self, path): """Set the path Parameters ---------- path : str Path under which to save. The extension determines the way file (*.pickled -> pickled Dataset; *.txt -> tsv) """ root, ext = os.path.splitext(path) if ext == '': path = root + '.txt' FileDocument.set_path(self, path) def read_rej_file(self, path): "Read a file making sure it is compatible" _, ext = os.path.splitext(path) if ext.startswith('.pickle'): ds = load.unpickle(path) elif ext == '.txt': ds = load.tsv(path, delimiter='\t') else: raise ValueError(f"Unknown file extension for rejections: {path}") # check file if ds.n_cases > self.n_epochs: app = get_app() cmd = app.message_box(f"The File contains more events than the data (file: {ds.n_cases}, data: {self.n_epochs}). Truncate the file?", "Truncate the file?", wx.OK | wx.CANCEL | wx.CANCEL_DEFAULT | wx.ICON_WARNING) if cmd == wx.ID_OK: ds = ds[:self.n_epochs] else: raise RuntimeError("Unequal number of cases") elif ds.n_cases < self.n_epochs: app = get_app() cmd = app.message_box(f"The rejection file contains fewer epochs than the data (file: {ds.n_cases}, data: {self.n_epochs}). Load anyways (epochs missing from the file will be accepted)?", "Load partial file?", wx.OK | wx.CANCEL | wx.CANCEL_DEFAULT | wx.ICON_WARNING) if cmd == wx.ID_OK: n_missing = self.n_epochs - ds.n_cases tail = Dataset(info=ds.info) tail['trigger'] = Var(self.trigger[-n_missing:]) tail['accept'] = Var([True], repeat=n_missing) tail['tag'] = Factor(['missing'], repeat=n_missing) ds = combine((ds, tail)) else: raise RuntimeError("Unequal number of cases") if not np.all(ds[self.trigger.name] == self.trigger): app = get_app() cmd = app.message_box("The file contains different triggers from the data. Ignore mismatch and proceed?", "Ignore trigger mismatch?", wx.OK | wx.CANCEL | wx.CANCEL_DEFAULT) if cmd == wx.ID_OK: ds[self.trigger.name] = self.trigger else: raise RuntimeError("Trigger mismatch") accept = ds['accept'] if 'rej_tag' in ds: tag = ds['rej_tag'] else: tag = Factor([''], repeat=self.n_epochs, name='rej_tag') if INTERPOLATE_CHANNELS in ds: interpolate = ds[INTERPOLATE_CHANNELS] if not self.allow_interpolation and any(interpolate): app = get_app() cmd = app.message_box("The file contains channel interpolation instructions, but interpolation is disabled is the current session. Drop interpolation instructions?", "Clear Channel Interpolation Instructions?", wx.OK | wx.CANCEL | wx.CANCEL_DEFAULT) if cmd == wx.ID_OK: for l in interpolate: del l[:] else: raise RuntimeError("File with interpolation when Interpolation is disabled") else: interpolate = Datalist([[]] * self.n_epochs, INTERPOLATE_CHANNELS, 'strlist') if BAD_CHANNELS in ds.info: bad_channels = self.epochs.sensor._array_index(ds.info[BAD_CHANNELS]) else: bad_channels = [] return accept, tag, interpolate, bad_channels def save(self): # find dest path _, ext = os.path.splitext(self.path) # create Dataset to save info = {BAD_CHANNELS: self.bad_channel_names} ds = Dataset((self.trigger, self.accept, self.tag, self.interpolate), info=info) if ext == '.pickled': save.pickle(ds, self.path) elif ext == '.txt': ds.save_txt(self.path) else: raise ValueError("Unsupported extension: %r" % ext) class Model(FileModel): """Manages a document as well as its history""" def clear(self): desc = "Clear" index = np.logical_not(self.doc.accept.x) old_tag = self.doc.tag[index] action = ChangeAction(desc, index, False, True, old_tag, 'clear') logger = getLogger(__name__) logger.info("Clearing %i rejections" % index.sum()) self.history.do(action) def load(self, path): new_accept, new_tag, new_interpolate, new_bad_chs = self.doc.read_rej_file(path) # create load action action = ChangeAction("Load File", FULL_SLICE, self.doc.accept, new_accept, self.doc.tag, new_tag, self.doc.path, path, self.doc.bad_channels, new_bad_chs, self.doc.interpolate, new_interpolate) self.history.do(action) self.history.register_save() def set_bad_channels(self, bad_channels, desc="Set bad channels"): "Set bad channels with a list of int" action = ChangeAction(desc, old_bad_chs=self.doc.bad_channels, new_bad_chs=bad_channels) self.history.do(action) def set_case(self, i, state, tag=None, desc="Manual Change"): old_accept = self.doc.accept[i] if tag is None: old_tag = None else: old_tag = self.doc.tag[i] action = ChangeAction(desc, i, old_accept, state, old_tag, tag) self.history.do(action) def set_interpolation(self, case, ch_names): action = ChangeAction("Epoch %s interpolate %r" % (case, ', '.join(ch_names)), case, old_interpolate=self.doc.interpolate[case], new_interpolate=ch_names) self.history.do(action) def set_range(self, start, stop, new_accept): if start < 0: start += len(self.doc.accept) if stop <= 0: stop += len(self.doc.accept) if stop <= start: return old_accept = self.doc.accept[start: stop].copy() action = ChangeAction("Set Range", slice(start, stop), old_accept, new_accept) self.history.do(action) def threshold(self, threshold=2e-12, method='abs'): """Find epochs based on a threshold criterion Parameters ---------- threshold : scalar The threshold value. Examples: 1.25e-11 to detect saturated channels; 2e-12: for conservative MEG rejection. method : 'abs' | 'p2p' How to apply the threshold. With "abs", the threshold is applied to absolute values. With 'p2p' the threshold is applied to peak-to-peak values. Returns ------- sub_threshold : array of bool True for all epochs in which the criterion is not reached (i.e., epochs that should be accepted). """ args = ', '.join(map(str, (threshold, method))) logger = getLogger(__name__) logger.info("Auto-reject trials: %s" % args) if method == 'abs': x = [x.abs().max(('time', 'sensor')) for x in self.doc.iter_good_epochs()] elif method == 'p2p': x = [(x.max('time') - x.min('time')).max('sensor') for x in self.doc.iter_good_epochs()] else: raise ValueError("Invalid method: %r" % method) return np.array(x) < threshold def toggle_interpolation(self, case, ch_name): old_interpolate = self.doc.interpolate[case] new_interpolate = old_interpolate[:] if ch_name in new_interpolate: new_interpolate.remove(ch_name) desc = "Don't interpolate %s for %i" % (ch_name, case) else: new_interpolate.append(ch_name) desc = "Interpolate %s for %i" % (ch_name, case) action = ChangeAction(desc, case, old_interpolate=old_interpolate, new_interpolate=new_interpolate) self.history.do(action) def update_bad_chs(self, bad_chs, interp, desc): if interp is None: index = old_interp = new_interp = None else: new_interp = self.doc.interpolate[:] new_interp._update_listlist(interp) index = np.flatnonzero(new_interp != self.doc.interpolate) if len(index): old_interp = self.doc.interpolate[index] new_interp = new_interp[index] else: index = old_interp = new_interp = None # find changed bad channels old_bad_chs = self.doc.bad_channel_names if bad_chs and any(ch not in old_bad_chs for ch in bad_chs): new_bad_chs = sorted(set(old_bad_chs).union(bad_chs)) else: new_bad_chs = old_bad_chs = None action = ChangeAction(desc, index, old_bad_chs=old_bad_chs, new_bad_chs=new_bad_chs, old_interpolate=old_interp, new_interpolate=new_interp) self.history.do(action) def update_rejection(self, new_accept, mark_good, mark_bad, desc, new_tag): # find changes if not mark_good: index = np.invert(new_accept) elif not mark_bad: index = new_accept else: index = None if index is None: index = new_accept != self.doc.accept.x else: np.logical_and(index, new_accept != self.doc.accept.x, index) index = np.flatnonzero(index) # construct action old_accept = self.doc.accept[index] new_accept = new_accept[index] old_tag = self.doc.tag[index] action = ChangeAction(desc, index, old_accept, new_accept, old_tag, new_tag) self.history.do(action) class Frame(FileFrame): """Epoch rejection GUI Exclude bad epochs and interpolate or remove bad channels. * Use the `Bad Channels` button in the toolbar to exclude channels from analysis (use the `GA` button to plot the grand average and look for channels that are consistently bad). * Click the `Threshold` button to automatically reject epochs in which the signal exceeds a certain threshold. * Click on an epoch plot to toggle rejection of that epoch. * Click on a channel in the topo-map to mark that channel in the epoch plots. * Press ``i`` on the keyboard to toggle channel interpolation for the channel that is closest to the cursor along the y-axis. * Press ``shift-i`` on the keyboard to edit a list of interpolated channels for the epoch under the cursor. *Keyboard shortcuts* in addition to the ones in the menu: =========== ============================================================ Key Effect =========== ============================================================ right-arrow go to the next page left-arrow go to the previous page b butterfly plot of the epoch under the pointer c pairwise sensor correlation plot or the current epoch t topomap plot of the epoch/time point under the pointer i interpolate the channel nearest to the pointer on the y-axis shift-i open dialog to enter channels for interpolation =========== ============================================================ """ _doc_name = 'epoch selection' _title = "Select Epochs" def __init__(self, parent, model, nplots, topo, mean, vlim, color, lw, mark, mcolor, mlw, antialiased, pos, size, allow_interpolation): """View object of the epoch selection GUI Parameters ---------- parent : wx.Frame Parent window. others : See TerminalInterface constructor. """ super(Frame, self).__init__(parent, pos, size, model) self.allow_interpolation = allow_interpolation # bind events self.doc.callbacks.subscribe('case_change', self.CaseChanged) self.doc.callbacks.subscribe('bad_chs_change', self.ShowPage) # setup figure canvas self.canvas = FigureCanvasPanel(self) self.figure = self.canvas.figure self.figure.set_facecolor('white') self.figure.subplots_adjust(left=.01, right=.99, bottom=.025, top=.975, wspace=.1, hspace=.25) # Toolbar tb = self.InitToolbar() tb.AddSeparator() # --> select page txt = wx.StaticText(tb, -1, "Page:") tb.AddControl(txt) self.page_choice = wx.Choice(tb, -1) tb.AddControl(self.page_choice) tb.Bind(wx.EVT_CHOICE, self.OnPageChoice) # --> forward / backward self.back_button = tb.AddTool(wx.ID_BACKWARD, "Back", Icon("tango/actions/go-previous")) self.Bind(wx.EVT_TOOL, self.OnBackward, id=wx.ID_BACKWARD) self.next_button = tb.AddTool(wx.ID_FORWARD, "Next", Icon("tango/actions/go-next")) self.Bind(wx.EVT_TOOL, self.OnForward, id=wx.ID_FORWARD) tb.AddSeparator() # --> Bad Channels button = wx.Button(tb, ID.SET_BAD_CHANNELS, "Bad Channels") button.Bind(wx.EVT_BUTTON, self.OnSetBadChannels) tb.AddControl(button) # --> Thresholding button = wx.Button(tb, ID.THRESHOLD, "Threshold") button.Bind(wx.EVT_BUTTON, self.OnThreshold) tb.AddControl(button) # right-most part tb.AddStretchableSpace() # Grand-average plot button = wx.Button(tb, ID.GRAND_AVERAGE, "GA") button.SetHelpText("Plot the grand average of all accepted epochs") button.Bind(wx.EVT_BUTTON, self.OnPlotGrandAverage) tb.AddControl(button) # Info tb.AddTool(wx.ID_INFO, 'Info', Icon("actions/info")) self.Bind(wx.EVT_TOOL, self.OnInfo, id=wx.ID_INFO) # --> Help self.InitToolbarTail(tb) tb.Realize() self.CreateStatusBar() # check plot parameters if mark: mark, invalid = self.doc.epochs.sensor._normalize_sensor_names(mark, missing='return') if invalid: msg = ("Some channels specified to mark do not exist in the " "data and will be ignored: " + ', '.join(invalid)) wx.CallLater(1, wx.MessageBox, msg, "Invalid Channels in Mark", wx.OK | wx.ICON_WARNING) # setup plot parameters plot_list = ((self.doc.epochs,),) cmaps = find_fig_cmaps(plot_list) self._vlims = find_fig_vlims(plot_list, vlim, None, cmaps) self._mark = mark self._bfly_kwargs = {'color': color, 'lw': lw, 'mlw': mlw, 'antialiased': antialiased, 'vlims': self._vlims, 'mcolor': mcolor} self._topo_kwargs = {'vlims': self._vlims, 'mcolor': 'red', 'mmarker': 'x'} self._SetLayout(nplots, topo, mean) # Bind Events --- self.canvas.mpl_connect('button_press_event', self.OnCanvasClick) self.canvas.mpl_connect('key_release_event', self.OnCanvasKey) self.canvas.mpl_connect('motion_notify_event', self.OnPointerMotion) # plot objects self._current_page_i = None self._epoch_idxs = None self._case_plots = None self._case_axes = None self._case_segs = None self._axes_by_idx = None self._topo_ax = None self._topo_plot_info_str = None self._topo_plot = None self._mean_plot = None # Finalize self.ShowPage(0) self.UpdateTitle() def CanBackward(self): return self._current_page_i > 0 def CanForward(self): return self._current_page_i < self._n_pages - 1 def CaseChanged(self, index): "Update the states of the segments on the current page" if isinstance(index, INT_TYPES): index = [index] elif isinstance(index, slice): start = index.start or 0 stop = index.stop or self.doc.n_epochs index = range(start, stop) elif index.dtype.kind == 'b': index = np.nonzero(index)[0] # update epoch plots axes = [] for idx in index: if idx in self._axes_by_idx: ax = self._axes_by_idx[idx] ax_idx = ax.ax_idx h = self._case_plots[ax_idx] h.set_state(self.doc.accept[idx]) # interpolated channels ch_index = h.epoch.sensor.channel_idx h.set_marked(INTERPOLATE_CHANNELS, [ch_index[ch] for ch in self.doc.interpolate[idx] if ch in ch_index]) axes.append(ax) # update mean plot if self._plot_mean: self._mean_plot.set_data(self._get_page_mean_seg()) axes.append(self._mean_ax) self.canvas.redraw(axes=axes) def GoToEpoch(self, i): for page, epochs in enumerate(self._segs_by_page): if i in epochs: break else: raise ValueError("Epoch not found: %r" % i) if page != self._current_page_i: self.SetPage(page) def MakeToolsMenu(self, menu): app = wx.GetApp() item = menu.Append(wx.ID_ANY, "Set Bad Channels", "Specify bad channels for the whole file") app.Bind(wx.EVT_MENU, self.OnSetBadChannels, item) item = menu.Append(wx.ID_ANY, "Set Rejection for Range", "Set the rejection status for a range of epochs") app.Bind(wx.EVT_MENU, self.OnRejectRange, item) item = menu.Append(wx.ID_ANY, "Find Epochs by Threshold", "Find epochs based in a specific threshold") app.Bind(wx.EVT_MENU, self.OnThreshold, item) item = menu.Append(wx.ID_ANY, "Find Bad Channels", "Find bad channels using different criteria") app.Bind(wx.EVT_MENU, self.OnFindNoisyChannels, item) menu.AppendSeparator() item = menu.Append(wx.ID_ANY, "Plot Grand Average", "Plot the grand average of all accepted epochs " "(does not perform single-epoch channel " "interpolation)") app.Bind(wx.EVT_MENU, self.OnPlotGrandAverage, item) item = menu.Append(wx.ID_ANY, "Info") app.Bind(wx.EVT_MENU, self.OnInfo, item) def OnBackward(self, event): "Turn the page backward" self.SetPage(self._current_page_i - 1) def OnCanvasClick(self, event): "Called by mouse clicks" ax = event.inaxes logger = getLogger(__name__) if ax: logger.debug("Canvas click at ax.ax_idx=%i", ax.ax_idx) if ax.ax_idx >= 0: idx = ax.epoch_idx state = not self.doc.accept[idx] tag = "manual" desc = "Epoch %i %s" % (idx, state) self.model.set_case(idx, state, tag, desc) elif ax.ax_idx == TOPO_PLOT: ch_locs = self._topo_plot.sensors.locs sensor_i = np.argmin(cdist(ch_locs, [[event.xdata, event.ydata]])) sensor = self._topo_plot.sensors.sensors.names[sensor_i] if sensor in self._mark: self._mark.remove(sensor) else: self._mark.append(sensor) self.SetPlotStyle(mark=self._mark) else: logger.debug("Canvas click outside axes") def OnCanvasKey(self, event): # GUI Control events if event.key == 'right': if self.CanForward(): self.OnForward(None) return elif event.key == 'left': if self.CanBackward(): self.OnBackward(None) return elif event.key == 'u': if self.CanUndo(): self.OnUndo(None) return elif event.key == 'U': if self.CanRedo(): self.OnRedo(None) return # plotting ax = event.inaxes if ax is None or ax.ax_idx == TOPO_PLOT: return elif ax.ax_idx > 0 and ax.epoch_idx == OUT_OF_RANGE: return elif event.key == 't': self.PlotTopomap(ax.ax_idx, event.xdata) elif event.key == 'b': self.PlotButterfly(ax.ax_idx) elif event.key == 'c': self.PlotCorrelation(ax.ax_idx) elif ax.ax_idx == MEAN_PLOT: return elif event.key == 'i': self.ToggleChannelInterpolation(ax, event) elif event.key == 'I': self.OnSetInterpolation(ax.epoch_idx) def OnFindNoisyChannels(self, event): dlg = FindNoisyChannelsDialog(self) if dlg.ShowModal() == wx.ID_OK: # Find bad channels flat, flat_average, mincorr = dlg.GetValues() if flat: flats = meeg.find_flat_epochs(self.doc.epochs, flat) else: flats = None if flat_average: flats_av = meeg.find_flat_evoked(self.doc.epochs, flat_average) else: flats_av = None if mincorr: noisies = meeg.find_noisy_channels(self.doc.epochs, mincorr) else: noisies = None # Apply if dlg.do_apply.GetValue(): has_flats = flats and any(flats) has_noisies = noisies and any(noisies) if has_flats and has_noisies: interp = flats[:] interp._update_listlist(noisies) elif has_flats: interp = flats elif has_noisies: interp = noisies else: interp = None self.model.update_bad_chs(flats_av, interp, "Find noisy channels") # Show Report if dlg.do_report.GetValue(): doc = fmtxt.Section("Noisy Channels") doc.append("Total of %i epochs." % len(self.doc.epochs)) if flat_average: sec = doc.add_section("Flat in the average (<%s)" % flat_average) if flats_av: sec.add_paragraph(', '.join(flats_av)) else: sec.add_paragraph("None.") if flat: sec = doc.add_section("Flat Channels (<%s)" % flat) sec.add_paragraph(format_epoch_list(flats)) if mincorr: sec = doc.add_section("Neighbor correlation < %s" % mincorr) sec.add_paragraph(format_epoch_list(noisies)) InfoFrame(self, "Noisy Channels", doc.get_html()) dlg.StoreConfig() dlg.Destroy() def OnForward(self, event): "Turn the page forward" self.SetPage(self._current_page_i + 1) def OnInfo(self, event): doc = fmtxt.Section("%i Epochs" % len(self.doc.epochs)) # rejected epochs rejected = np.invert(self.doc.accept.x) sec = doc.add_section(_text.n_of(rejected.sum(), 'epoch') + ' rejected') if np.any(rejected): para = fmtxt.delim_list((fmtxt.Link(epoch, "epoch:%i" % epoch) for epoch in np.flatnonzero(rejected))) sec.add_paragraph(para) # bad channels heading = _text.n_of(len(self.doc.bad_channels), "bad channel", True) sec = doc.add_section(heading.capitalize()) if self.doc.bad_channels: sec.add_paragraph(', '.join(self.doc.bad_channel_names)) # interpolation by epochs if any(self.doc.interpolate): sec = doc.add_section("Interpolate channels") sec.add_paragraph(format_epoch_list(self.doc.interpolate, "Interpolation by epoch:")) else: doc.add_section("No channels interpolated in individual epochs") InfoFrame(self, "Rejection Info", doc.get_html()) def OnPageChoice(self, event): "Called by the page Choice control" page = event.GetSelection() self.SetPage(page) def OnPlotGrandAverage(self, event): self.PlotGrandAverage() def OnPointerMotion(self, event): "Update view on mouse pointer movement" ax = event.inaxes if not ax: return self.SetStatusText("") elif ax.ax_idx == TOPO_PLOT: return self.SetStatusText(self._topo_plot_info_str) elif ax.ax_idx != MEAN_PLOT and ax.epoch_idx == OUT_OF_RANGE: return self.SetStatusText("") # compose status text x = ax.xaxis.get_major_formatter().format_data(event.xdata) y = ax.yaxis.get_major_formatter().format_data(event.ydata) desc = "Page average" if ax.ax_idx == MEAN_PLOT else "Epoch %i" % ax.epoch_idx status = "%s, x = %s ms, y = %s" % (desc, x, y) if ax.ax_idx >= 0: # single trial plot interp = self.doc.interpolate[ax.epoch_idx] if interp: status += ", interpolate %s" % ', '.join(interp) self.SetStatusText(status) # update topomap if self._plot_topo: tseg = self._get_ax_data(ax.ax_idx, event.xdata) self._topo_plot.set_data([tseg]) self.canvas.redraw(axes=[self._topo_ax]) self._topo_plot_info_str = ("Topomap: %s, t = %s ms, marked: %s" % (desc, x, ', '.join(self._mark))) def OnRejectRange(self, event): dlg = RejectRangeDialog(self) if dlg.ShowModal() == wx.ID_OK: start = int(dlg.first.GetValue()) stop = int(dlg.last.GetValue()) + 1 state = bool(dlg.action.GetSelection()) self.model.set_range(start, stop, state) dlg.StoreConfig() dlg.Destroy() def OnSetBadChannels(self, event): dlg = wx.TextEntryDialog(self, "Please enter bad channel names separated by " "comma (e.g., \"MEG 003, MEG 010\"):", "Set Bad " "Channels", ', '.join(self.doc.bad_channel_names)) while True: if dlg.ShowModal() == wx.ID_OK: try: names_in = filter(None, (s.strip() for s in dlg.GetValue().split(','))) names = self.doc.epochs.sensor._normalize_sensor_names(names_in) break except ValueError as exception: msg = wx.MessageDialog(self, str(exception), "Invalid Entry", wx.OK | wx.ICON_ERROR) msg.ShowModal() msg.Destroy() else: dlg.Destroy() return dlg.Destroy() bad_channels = self.doc.epochs.sensor._array_index(names) self.model.set_bad_channels(bad_channels) def OnSetInterpolation(self, epoch): "Show Dialog for channel interpolation for this epoch (index)" old = self.doc.interpolate[epoch] dlg = wx.TextEntryDialog(self, "Please enter channel names separated by " "comma (e.g., \"MEG 003, MEG 010\"):", "Set " "Channels for Interpolation", ', '.join(old)) while True: if dlg.ShowModal() == wx.ID_OK: try: names = filter(None, (s.strip() for s in dlg.GetValue().split(','))) new = self.doc.epochs.sensor._normalize_sensor_names(names) break except ValueError as exception: msg = wx.MessageDialog(self, str(exception), "Invalid Entry", wx.OK | wx.ICON_ERROR) msg.ShowModal() msg.Destroy() else: dlg.Destroy() return dlg.Destroy() if new != old: self.model.set_interpolation(epoch, new) def OnSetLayout(self, event): dlg = LayoutDialog(self, self._rows, self._columns, self._plot_topo, self._plot_mean) if dlg.ShowModal() == wx.ID_OK: self.SetLayout(dlg.layout, dlg.topo, dlg.mean) def OnSetMarkedChannels(self, event): "Mark is represented in sensor names" dlg = wx.TextEntryDialog(self, "Please enter channel names separated by " "comma (e.g., \"MEG 003, MEG 010\"):", "Set Marked" "Channels", ', '.join(self._mark)) while True: if dlg.ShowModal() == wx.ID_OK: try: names_in = filter(None, (s.strip() for s in dlg.GetValue().split(','))) names = self.doc.epochs.sensor._normalize_sensor_names(names_in) break except ValueError as exception: msg = wx.MessageDialog(self, str(exception), "Invalid Entry", wx.OK | wx.ICON_ERROR) msg.ShowModal() msg.Destroy() else: dlg.Destroy() return dlg.Destroy() self.SetPlotStyle(mark=names) def OnSetVLim(self, event): default = str(tuple(self._vlims.values())[0][1]) dlg = wx.TextEntryDialog(self, "New Y-axis limit:", "Set Y-Axis Limit", default) if dlg.ShowModal() == wx.ID_OK: value = dlg.GetValue() try: vlim = abs(float(value)) except Exception as exception: msg = wx.MessageDialog(self, str(exception), "Invalid Entry", wx.OK | wx.ICON_ERROR) msg.ShowModal() msg.Destroy() raise self.SetVLim(vlim) dlg.Destroy() def OnThreshold(self, event): dlg = ThresholdDialog(self) if dlg.ShowModal() == wx.ID_OK: threshold = dlg.GetThreshold() method = dlg.GetMethod() sub_threshold = self.model.threshold(threshold, method) mark_below = dlg.GetMarkBelow() mark_above = dlg.GetMarkAbove() if mark_below or mark_above: self.model.update_rejection(sub_threshold, mark_below, mark_above, "Threshold-%s" % method, "%s_%s" % (method, threshold)) if dlg.do_report.GetValue(): rejected = np.invert(sub_threshold) doc = fmtxt.Section("Threshold") doc.append("%s at %s: reject %i of %i epochs:" % (method, threshold, rejected.sum(), len(rejected))) if np.any(rejected): para = fmtxt.delim_list((fmtxt.Link(epoch, "epoch:%i" % epoch) for epoch in np.flatnonzero(rejected))) doc.add_paragraph(para) InfoFrame(self, "Rejection Info", doc.get_html()) dlg.StoreConfig() dlg.Destroy() def OnUpdateUIBackward(self, event): event.Enable(self.CanBackward()) def OnUpdateUIForward(self, event): event.Enable(self.CanForward()) def OnUpdateUISetLayout(self, event): event.Enable(True) def OnUpdateUISetMarkedChannels(self, event): event.Enable(True) def OnUpdateUISetVLim(self, event): event.Enable(True) def PlotCorrelation(self, ax_index): if ax_index == MEAN_PLOT: seg = self._mean_seg name = 'Page Mean Neighbor Correlation' else: epoch_idx = self._epoch_idxs[ax_index] seg = self._case_segs[ax_index] name = 'Epoch %i Neighbor Correlation' % epoch_idx plot.Topomap(neighbor_correlation(seg, name=name), sensorlabels='name') def PlotButterfly(self, ax_index): epoch = self._get_ax_data(ax_index) plot.TopoButterfly(epoch, vmax=self._vlims) def PlotGrandAverage(self): epoch = self.doc.get_grand_average() plot.TopoButterfly(epoch) def PlotTopomap(self, ax_index, time): tseg = self._get_ax_data(ax_index, time) plot.Topomap(tseg, vmax=self._vlims, sensorlabels='name', w=8, title=tseg.name) def SetLayout(self, nplots=(6, 6), topo=True, mean=True): """Determine the layout of the Epochs canvas Parameters ---------- nplots : int | tuple of 2 int Number of epoch plots per page. Can be an ``int`` to produce a square layout with that many epochs, or an ``(n_rows, n_columns)`` tuple. topo : bool Show a topomap plot of the time point under the mouse cursor. mean : bool Show a plot of the page mean at the bottom right of the page. """ self._SetLayout(nplots, topo, mean) self.ShowPage(0) def _SetLayout(self, nplots, topo, mean): if topo is None: topo = self.config.ReadBool('Layout/show_topo', True) else: topo = bool(topo) self.config.WriteBool('Layout/show_topo', topo) if mean is None: mean = self.config.ReadBool('Layout/show_mean', True) else: mean = bool(mean) self.config.WriteBool('Layout/show_mean', mean) if nplots is None: nrow = self.config.ReadInt('Layout/n_rows', 6) ncol = self.config.ReadInt('Layout/n_cols', 6) nax = ncol * nrow n_per_page = nax - bool(topo) - bool(mean) else: if isinstance(nplots, int): if nplots == 1: mean = False elif nplots < 1: raise ValueError("nplots needs to be >= 1; got %r" % nplots) nax = nplots + bool(mean) + bool(topo) nrow = math.ceil(math.sqrt(nax)) ncol = int(math.ceil(nax / nrow)) nrow = int(nrow) n_per_page = nplots else: nrow, ncol = nplots nax = ncol * nrow if nax == 1: mean = False topo = False elif nax == 2: mean = False elif nax < 1: err = ("nplots=%s: Need at least one plot." % str(nplots)) raise ValueError(err) n_per_page = nax - bool(topo) - bool(mean) self.config.WriteInt('Layout/n_rows', nrow) self.config.WriteInt('Layout/n_cols', ncol) self.config.Flush() self._plot_mean = mean self._plot_topo = topo # prepare segments n = self.doc.n_epochs self._rows = nrow self._columns = ncol self._n_per_page = n_per_page self._n_pages = n_pages = int(math.ceil(n / n_per_page)) # get a list of IDS for each page self._segs_by_page = [] for i in range(n_pages): start = i * n_per_page stop = min((i + 1) * n_per_page, n) self._segs_by_page.append(np.arange(start, stop)) # update page selector pages = [] for i in range(n_pages): istart = self._segs_by_page[i][0] if i == n_pages - 1: pages.append('%i: %i..%i' % (i, istart, self.doc.n_epochs)) else: pages.append('%i: %i...' % (i, istart)) self.page_choice.SetItems(pages) def SetPlotStyle(self, **kwargs): """Select channels to mark in the butterfly plots. Parameters ---------- color : None | matplotlib color Color for primary data (default is black). lw : scalar Linewidth for normal sensor plots. mark : None | str | list of str Sensors to plot as individual traces with a separate color. mcolor : matplotlib color Color for marked traces. mlw : scalar Line width for marked sensor plots. antialiased : bool Perform Antialiasing on epoch plots (associated with a minor speed cost). """ self._SetPlotStyle(**kwargs) self.ShowPage() def _SetPlotStyle(self, **kwargs): "See .SetPlotStyle()" for key, value in kwargs.items(): if key == 'vlims': err = ("%r is an invalid keyword argument for this function" % key) raise TypeError(err) elif key == 'mark': self._mark = value elif key in self._bf_kwargs: self._bfly_kwargs[key] = value else: raise KeyError(repr(key)) def SetVLim(self, vlim): """Set the value limits (butterfly plot y axes and topomap colormaps) Parameters ---------- vlim : scalar | (scalar, scalar) For symmetric limits the positive vmax, for asymmetric limits a (vmin, vmax) tuple. """ for p in self._case_plots: p.set_ylim(vlim) if self._mean_plot: self._mean_plot.set_ylim(vlim) if self._topo_plot: self._topo_plot.set_vlim(vlim) if np.isscalar(vlim): vlim = (-vlim, vlim) for key in self._vlims: self._vlims[key] = vlim self.canvas.draw() def _page_change(self, page): "Perform operations common to page change events" self._current_page_i = page self.page_choice.Select(page) self._epoch_idxs = self._segs_by_page[page] def SetPage(self, page): "Change the page that is displayed without redrawing" self._page_change(page) self._case_segs = [] self._axes_by_idx = {} for i, epoch_idx in enumerate(self._epoch_idxs): ax = self._case_axes[i] h = self._case_plots[i] case = self.doc.get_epoch(epoch_idx, 'Epoch %i' % epoch_idx) h.set_data(case, epoch_idx) h.set_state(self.doc.accept[epoch_idx]) chs = [case.sensor.channel_idx[ch] for ch in self.doc.interpolate[epoch_idx] if ch in case.sensor.channel_idx] h.set_marked(INTERPOLATE_CHANNELS, chs) h.set_visible() # store objects ax.epoch_idx = epoch_idx self._case_segs.append(case) self._axes_by_idx[epoch_idx] = ax # hide lines axes without data if len(self._epoch_idxs) < len(self._case_axes): for i in range(len(self._epoch_idxs), len(self._case_plots)): self._case_plots[i].set_visible(False) self._case_axes[i].epoch_idx = OUT_OF_RANGE # update mean plot if self._plot_mean: self._mean_plot.set_data(self._get_page_mean_seg()) self.canvas.draw() def ShowPage(self, page=None): "Dislay a specific page (start counting with 0)" wx.BeginBusyCursor() logger = getLogger(__name__) t0 = time.time() if page is not None: self._page_change(page) self.figure.clf() nrow = self._rows ncol = self._columns # formatters t_formatter, t_locator, t_label = self.doc.epochs.time._axis_format(True, True) y_scale = AxisScale(self.doc.epochs, True) # segment plots self._case_plots = [] self._case_axes = [] self._case_segs = [] self._axes_by_idx = {} mark = None for i, epoch_idx in enumerate(self._epoch_idxs): case = self.doc.get_epoch(epoch_idx, 'Epoch %i' % epoch_idx) if mark is None: mark = [case.sensor.channel_idx[ch] for ch in self._mark if ch in case.sensor.channel_idx] state = self.doc.accept[epoch_idx] ax = self.figure.add_subplot(nrow, ncol, i + 1, xticks=[0], yticks=[]) h = _ax_bfly_epoch(ax, case, mark, state, epoch_idx, **self._bfly_kwargs) # mark interpolated channels if self.doc.interpolate[epoch_idx]: chs = [case.sensor.channel_idx[ch] for ch in self.doc.interpolate[epoch_idx] if ch in case.sensor.channel_idx] h.set_marked(INTERPOLATE_CHANNELS, chs) # mark eye tracker artifacts if self.doc.blink is not None: _plt_bin_nuts(ax, self.doc.blink[epoch_idx], color=(0.99, 0.76, 0.21)) # formatters if t_locator is not None: ax.xaxis.set_major_locator(t_locator) ax.xaxis.set_major_formatter(t_formatter) ax.yaxis.set_major_formatter(y_scale.formatter) # store objects ax.ax_idx = i ax.epoch_idx = epoch_idx self._case_plots.append(h) self._case_axes.append(ax) self._case_segs.append(case) self._axes_by_idx[epoch_idx] = ax # mean plot if self._plot_mean: plot_i = nrow * ncol self._mean_ax = ax = self.figure.add_subplot(nrow, ncol, plot_i) ax.ax_idx = MEAN_PLOT self._mean_seg = self._get_page_mean_seg() self._mean_plot = _ax_bfly_epoch(ax, self._mean_seg, mark, 'Page Mean', **self._bfly_kwargs) # formatters ax.xaxis.set_major_formatter(t_formatter) ax.yaxis.set_major_formatter(y_scale.formatter) # topomap if self._plot_topo: plot_i = nrow * ncol - self._plot_mean self._topo_ax = self.figure.add_subplot(nrow, ncol, plot_i) self._topo_ax.ax_idx = TOPO_PLOT self._topo_ax.set_axis_off() tseg = self._get_ax_data(0, True) if self._mark: mark = [ch for ch in self._mark if ch not in self.doc.bad_channel_names] else: mark = None layers = AxisData([LayerData(tseg, PlotType.IMAGE)]) self._topo_plot = _ax_topomap(self._topo_ax, layers, mark=mark, **self._topo_kwargs) self._topo_plot_info_str = "" self.canvas.draw() self.canvas.store_canvas() dt = time.time() - t0 logger.debug('Page draw took %.1f seconds.', dt) wx.EndBusyCursor() def ToggleChannelInterpolation(self, ax, event): if not self.allow_interpolation: wx.MessageBox("Interpolation is disabled for this session", "Interpolation disabled", wx.OK) return plt = self._case_plots[ax.ax_idx] locs = plt.epoch.sub(time=event.xdata).x sensor = np.argmin(np.abs(locs - event.ydata)) sensor_name = plt.epoch.sensor.names[sensor] self.model.toggle_interpolation(ax.epoch_idx, sensor_name) def _get_page_mean_seg(self): page_segments = self._segs_by_page[self._current_page_i] page_index = np.zeros(self.doc.n_epochs, dtype=bool) page_index[page_segments] = True index = np.logical_and(page_index, self.doc.accept.x) mseg = self.doc.get_epoch(index, "Page Average").mean('case') return mseg def _get_ax_data(self, ax_index, time=None): if ax_index == MEAN_PLOT: seg = self._mean_seg epoch_name = 'Page Average' sensor_idx = None elif ax_index >= 0: epoch_idx = self._epoch_idxs[ax_index] epoch_name = 'Epoch %i' % epoch_idx seg = self._case_segs[ax_index] sensor_idx = self.doc.good_sensor_index(epoch_idx) else: raise ValueError("Invalid ax_index: %s" % ax_index) if time is not None: if time is True: time = min(max(0.1, seg.time.tmin), seg.time.tmax) name = '%s, %i ms' % (epoch_name, 1e3 * time) return seg.sub(time=time, sensor=sensor_idx, name=name) elif sensor_idx is None: return seg else: return seg.sub(sensor=sensor_idx) class FindNoisyChannelsDialog(EelbrainDialog): def __init__(self, parent, *args, **kwargs): EelbrainDialog.__init__(self, parent, wx.ID_ANY, "Find Noisy Channels", *args, **kwargs) # load config config = parent.config flat = config.ReadFloat("FindNoisyChannels/flat", 1e-13) flat_average = config.ReadFloat("FindNoisyChannels/flat_average", 1e-14) corr = config.ReadFloat("FindNoisyChannels/mincorr", 0.35) do_apply = config.ReadBool("FindNoisyChannels/do_apply", True) do_report = config.ReadBool("FindNoisyChannels/do_report", True) # construct layout sizer = wx.BoxSizer(wx.VERTICAL) # flat channels sizer.Add(wx.StaticText(self, label="Threshold for flat channels:")) msg = ("Invalid entry for flat channel threshold: {value}. Please " "specify a number > 0.") validator = REValidator(POS_FLOAT_PATTERN, msg, False) ctrl = wx.TextCtrl(self, value=str(flat), validator=validator) ctrl.SetHelpText("A channel that does not deviate from 0 by more than " "this value is considered flat.") ctrl.SelectAll() sizer.Add(ctrl) self.flat_ctrl = ctrl # flat channels in average sizer.Add(wx.StaticText(self, label="Threshold for flat channels in average:")) msg = ("Invalid entry for average flat channel threshold: {value}. Please " "specify a number > 0.") validator = REValidator(POS_FLOAT_PATTERN, msg, False) ctrl = wx.TextCtrl(self, value=str(flat_average), validator=validator) ctrl.SetHelpText("A channel that does not deviate from 0 by more than " "this value in the average of all epochs is " "considered flat.") sizer.Add(ctrl) self.flat_average_ctrl = ctrl # Correlation sizer.Add(wx.StaticText(self, label="Threshold for channel to neighbor correlation:")) msg = ("Invalid entry for channel neighbor correlation: {value}. Please " "specify a number > 0.") validator = REValidator(POS_FLOAT_PATTERN, msg, False) ctrl = wx.TextCtrl(self, value=str(corr), validator=validator) ctrl.SetHelpText("A channel is considered noisy if the average of the " "correlation with its neighbors is smaller than this " "value.") sizer.Add(ctrl) self.mincorr_ctrl = ctrl # output sizer.AddSpacer(4) sizer.Add(wx.StaticText(self, label="Output")) self.do_report = wx.CheckBox(self, wx.ID_ANY, "Show Report") self.do_report.SetValue(do_report) sizer.Add(self.do_report) self.do_apply = wx.CheckBox(self, wx.ID_ANY, "Apply") self.do_apply.SetValue(do_apply) sizer.Add(self.do_apply) # default button sizer.AddSpacer(4) btn = wx.Button(self, wx.ID_DEFAULT, "Default Settings") sizer.Add(btn, border=2) btn.Bind(wx.EVT_BUTTON, self.OnSetDefault) # buttons button_sizer = wx.StdDialogButtonSizer() # ok btn = wx.Button(self, wx.ID_OK) btn.SetDefault() btn.Bind(wx.EVT_BUTTON, self.OnOK) button_sizer.AddButton(btn) # cancel btn = wx.Button(self, wx.ID_CANCEL) button_sizer.AddButton(btn) # finalize button_sizer.Realize() sizer.Add(button_sizer) self.SetSizer(sizer) sizer.Fit(self) def GetValues(self): return (float(self.flat_ctrl.GetValue()), float(self.flat_average_ctrl.GetValue()), float(self.mincorr_ctrl.GetValue())) def OnOK(self, event): if self.do_report.GetValue() or self.do_apply.GetValue(): event.Skip() else: wx.MessageBox("Specify at least one action (report or apply)", "No Command Selected", wx.ICON_EXCLAMATION) def OnSetDefault(self, event): self.flat_ctrl.SetValue('1e-13') self.flat_average_ctrl.SetValue('1e-14') self.mincorr_ctrl.SetValue('0.35') def StoreConfig(self): config = self.Parent.config config.WriteFloat("FindNoisyChannels/flat", float(self.flat_ctrl.GetValue())) config.WriteFloat("FindNoisyChannels/flat_average", float(self.flat_average_ctrl.GetValue())) config.WriteFloat("FindNoisyChannels/mincorr", float(self.mincorr_ctrl.GetValue())) config.WriteBool("FindNoisyChannels/do_report", self.do_report.GetValue()) config.WriteBool("FindNoisyChannels/do_apply", self.do_apply.GetValue()) config.Flush() class LayoutDialog(EelbrainDialog): def __init__(self, parent, rows, columns, topo, mean): EelbrainDialog.__init__(self, parent, wx.ID_ANY, "Select-Epochs Layout") # result attributes self.topo = None self.mean = None self.layout = None sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(wx.StaticText(self, wx.ID_ANY, "Layout: number of rows and " "columns (e.g., '5 7')\n" "or number of epochs (e.g., '35'):")) self.text = wx.TextCtrl(self, wx.ID_ANY, "%i %i" % (rows, columns)) self.text.SelectAll() sizer.Add(self.text) self.topo_ctrl = wx.CheckBox(self, wx.ID_ANY, "Topographic map") self.topo_ctrl.SetValue(topo) sizer.Add(self.topo_ctrl) self.mean_ctrl = wx.CheckBox(self, wx.ID_ANY, "Page mean plot") self.mean_ctrl.SetValue(mean) sizer.Add(self.mean_ctrl) # buttons button_sizer = wx.StdDialogButtonSizer() # ok btn = wx.Button(self, wx.ID_OK) btn.SetDefault() button_sizer.AddButton(btn) # cancel button_sizer.AddButton(wx.Button(self, wx.ID_CANCEL)) # finalize button_sizer.Realize() sizer.Add(button_sizer) self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK) self.SetSizer(sizer) sizer.Fit(self) def OnOk(self, event): self.topo = self.topo_ctrl.GetValue() self.mean = self.mean_ctrl.GetValue() value = self.text.GetValue() m = re.match(r"(\d+)\s*(\d*)", value) if m: rows_str, columns_str = m.groups() rows = int(rows_str) if columns_str: columns = int(columns_str) n_plots = rows * columns self.layout = (rows, columns) else: self.layout = n_plots = rows if n_plots >= self.topo + self.mean + 1: event.Skip() return else: wx.MessageBox("Layout does not have enough plots", "Invalid Layout", wx.OK | wx.ICON_ERROR, self) else: wx.MessageBox("Invalid layout string: %s" % value, "Invalid Layout", wx.OK | wx.ICON_ERROR, self) self.text.SetFocus() self.text.SelectAll() class RejectRangeDialog(EelbrainDialog): def __init__(self, parent): EelbrainDialog.__init__(self, parent, wx.ID_ANY, "Reject Epoch Range") # load config config = parent.config first = config.ReadInt("RejectRange/first", 0) last = config.ReadInt("RejectRange/last", 0) action = config.ReadInt("Threshold/action", 0) sizer = wx.BoxSizer(wx.VERTICAL) # Range hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(wx.StaticText(self, wx.ID_ANY, "First:")) validator = REValidator(INT_PATTERN, "Invalid entry for First: {value}. Need an integer.") self.first = wx.TextCtrl(self, wx.ID_ANY, str(first), validator=validator) hsizer.Add(self.first) hsizer.Add(wx.StaticText(self, wx.ID_ANY, "Last:")) validator = REValidator(INT_PATTERN, "Invalid entry for Last: {value}. Need an integer.") self.last = wx.TextCtrl(self, wx.ID_ANY, str(last), validator=validator) hsizer.Add(self.last) sizer.Add(hsizer) # Action self.action = wx.RadioBox(self, wx.ID_ANY, "Action", choices=('Reject', 'Accept'), style=wx.RA_SPECIFY_ROWS) self.action.SetSelection(action) sizer.Add(self.action) # buttons button_sizer = wx.StdDialogButtonSizer() # ok btn = wx.Button(self, wx.ID_OK) btn.SetDefault() button_sizer.AddButton(btn) # cancel button_sizer.AddButton(wx.Button(self, wx.ID_CANCEL)) # finalize button_sizer.Realize() sizer.Add(button_sizer) self.SetSizer(sizer) sizer.Fit(self) def StoreConfig(self): config = self.Parent.config config.WriteInt("RejectRange/first", int(self.first.GetValue())) config.WriteInt("RejectRange/last", int(self.last.GetValue())) config.WriteInt("RejectRange/action", self.action.GetSelection()) config.Flush() class ThresholdDialog(EelbrainDialog): _methods = (('absolute', 'abs'), ('peak-to-peak', 'p2p')) def __init__(self, parent): title = "Threshold Criterion Rejection" wx.Dialog.__init__(self, parent, wx.ID_ANY, title) choices = tuple(m[0] for m in self._methods) method_tags = tuple(m[1] for m in self._methods) # load config config = parent.config method = config.Read("Threshold/method", "p2p") if method not in method_tags: method = "p2p" mark_above = config.ReadBool("Threshold/mark_above", True) mark_below = config.ReadBool("Threshold/mark_below", False) threshold = config.ReadFloat("Threshold/threshold", 2e-12) do_report = config.ReadBool("Threshold/do_report", True) # construct layout sizer = wx.BoxSizer(wx.VERTICAL) txt = "Mark epochs based on a threshold criterion" ctrl = wx.StaticText(self, wx.ID_ANY, txt) sizer.Add(ctrl) ctrl = wx.RadioBox(self, wx.ID_ANY, "Method", choices=choices) ctrl.SetSelection(method_tags.index(method)) sizer.Add(ctrl) self.method_ctrl = ctrl msg = ("Invalid entry for threshold: {value}. Need a floating\n" "point number.") validator = REValidator(FLOAT_PATTERN, msg, False) ctrl = wx.TextCtrl(self, wx.ID_ANY, str(threshold), validator=validator) ctrl.SetHelpText("Threshold value (positive scalar)") ctrl.SelectAll() sizer.Add(ctrl) self.threshold_ctrl = ctrl # output sizer.AddSpacer(4) sizer.Add(wx.StaticText(self, label="Output")) # mark above self.mark_above = wx.CheckBox(self, wx.ID_ANY, "Reject epochs exceeding the threshold") self.mark_above.SetValue(mark_above) sizer.Add(self.mark_above) # mark below self.mark_below = wx.CheckBox(self, wx.ID_ANY, "Accept epochs below the threshold") self.mark_below.SetValue(mark_below) sizer.Add(self.mark_below) # report self.do_report = wx.CheckBox(self, wx.ID_ANY, "Show Report") self.do_report.SetValue(do_report) sizer.Add(self.do_report) # buttons button_sizer = wx.StdDialogButtonSizer() # ok btn = wx.Button(self, wx.ID_OK) btn.SetDefault() btn.Bind(wx.EVT_BUTTON, self.OnOK) button_sizer.AddButton(btn) # cancel btn = wx.Button(self, wx.ID_CANCEL) button_sizer.AddButton(btn) # finalize button_sizer.Realize() sizer.Add(button_sizer) self.SetSizer(sizer) sizer.Fit(self) def GetMarkAbove(self): return self.mark_above.IsChecked() def GetMarkBelow(self): return self.mark_below.IsChecked() def GetMethod(self): index = self.method_ctrl.GetSelection() value = self._methods[index][1] return value def GetThreshold(self): text = self.threshold_ctrl.GetValue() value = float(text) return value def OnOK(self, event): if not (self.mark_above.GetValue() or self.mark_below.GetValue() or self.do_report.GetValue()): wx.MessageBox("Specify at least one action (create report or " "reject or accept epochs)", "No Command Selected", wx.ICON_EXCLAMATION) else: event.Skip() def StoreConfig(self): config = self.Parent.config config.Write("Threshold/method", self.GetMethod()) config.WriteBool("Threshold/mark_above", self.GetMarkAbove()) config.WriteBool("Threshold/mark_below", self.GetMarkBelow()) config.WriteFloat("Threshold/threshold", self.GetThreshold()) config.WriteBool("Threshold/do_report", self.do_report.GetValue()) config.Flush() class InfoFrame(HTMLFrame): def OpenURL(self, url): m = re.match(r'^(\w+):(\w+)$', url) if m: kind, address = m.groups() if kind == 'epoch': self.Parent.GoToEpoch(int(address)) else: raise NotImplementedError("%s URL" % kind) else: raise ValueError("Invalid link URL: %r" % url)
[ "wx.Dialog.__init__", "numpy.abs", "numpy.invert", "wx.CheckBox", "numpy.ones", "numpy.arange", "wx.RadioBox", "wx.Choice", "numpy.logical_not", "os.path.exists", "wx.TextCtrl", "wx.GetApp", "scipy.spatial.distance.cdist", "wx.TextEntryDialog", "wx.BoxSizer", "math.sqrt", "math.ceil", "wx.StdDialogButtonSizer", "re.match", "wx.StaticText", "wx.MessageBox", "numpy.all", "numpy.logical_and", "numpy.isscalar", "numpy.flatnonzero", "numpy.zeros", "time.time", "numpy.any", "wx.CallLater", "wx.Button", "wx.BeginBusyCursor", "numpy.array", "os.path.splitext", "numpy.nonzero", "wx.EndBusyCursor", "logging.getLogger" ]
[((11436, 11458), 'os.path.splitext', 'os.path.splitext', (['path'], {}), '(path)\n', (11452, 11458), False, 'import os\n'), ((11660, 11682), 'os.path.splitext', 'os.path.splitext', (['path'], {}), '(path)\n', (11676, 11682), False, 'import os\n'), ((14903, 14930), 'os.path.splitext', 'os.path.splitext', (['self.path'], {}), '(self.path)\n', (14919, 14930), False, 'import os\n'), ((15458, 15491), 'numpy.logical_not', 'np.logical_not', (['self.doc.accept.x'], {}), '(self.doc.accept.x)\n', (15472, 15491), True, 'import numpy as np\n'), ((15621, 15640), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (15630, 15640), False, 'from logging import getLogger\n'), ((18369, 18388), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (18378, 18388), False, 'from logging import getLogger\n'), ((20887, 20908), 'numpy.flatnonzero', 'np.flatnonzero', (['index'], {}), '(index)\n', (20901, 20908), True, 'import numpy as np\n'), ((23928, 23958), 'wx.StaticText', 'wx.StaticText', (['tb', '(-1)', '"""Page:"""'], {}), "(tb, -1, 'Page:')\n", (23941, 23958), False, 'import wx\n'), ((24013, 24030), 'wx.Choice', 'wx.Choice', (['tb', '(-1)'], {}), '(tb, -1)\n', (24022, 24030), False, 'import wx\n'), ((24633, 24683), 'wx.Button', 'wx.Button', (['tb', 'ID.SET_BAD_CHANNELS', '"""Bad Channels"""'], {}), "(tb, ID.SET_BAD_CHANNELS, 'Bad Channels')\n", (24642, 24683), False, 'import wx\n'), ((24817, 24857), 'wx.Button', 'wx.Button', (['tb', 'ID.THRESHOLD', '"""Threshold"""'], {}), "(tb, ID.THRESHOLD, 'Threshold')\n", (24826, 24857), False, 'import wx\n'), ((25048, 25085), 'wx.Button', 'wx.Button', (['tb', 'ID.GRAND_AVERAGE', '"""GA"""'], {}), "(tb, ID.GRAND_AVERAGE, 'GA')\n", (25057, 25085), False, 'import wx\n'), ((28888, 28899), 'wx.GetApp', 'wx.GetApp', ([], {}), '()\n', (28897, 28899), False, 'import wx\n'), ((30335, 30354), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (30344, 30354), False, 'from logging import getLogger\n'), ((34851, 34879), 'numpy.invert', 'np.invert', (['self.doc.accept.x'], {}), '(self.doc.accept.x)\n', (34860, 34879), True, 'import numpy as np\n'), ((34972, 34988), 'numpy.any', 'np.any', (['rejected'], {}), '(rejected)\n', (34978, 34988), True, 'import numpy as np\n'), ((41199, 41273), 'wx.TextEntryDialog', 'wx.TextEntryDialog', (['self', '"""New Y-axis limit:"""', '"""Set Y-Axis Limit"""', 'default'], {}), "(self, 'New Y-axis limit:', 'Set Y-Axis Limit', default)\n", (41217, 41273), False, 'import wx\n'), ((49295, 49312), 'numpy.isscalar', 'np.isscalar', (['vlim'], {}), '(vlim)\n', (49306, 49312), True, 'import numpy as np\n'), ((51070, 51090), 'wx.BeginBusyCursor', 'wx.BeginBusyCursor', ([], {}), '()\n', (51088, 51090), False, 'import wx\n'), ((51108, 51127), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (51117, 51127), False, 'from logging import getLogger\n'), ((51141, 51152), 'time.time', 'time.time', ([], {}), '()\n', (51150, 51152), False, 'import time\n'), ((54503, 54521), 'wx.EndBusyCursor', 'wx.EndBusyCursor', ([], {}), '()\n', (54519, 54521), False, 'import wx\n'), ((55154, 55193), 'numpy.zeros', 'np.zeros', (['self.doc.n_epochs'], {'dtype': 'bool'}), '(self.doc.n_epochs, dtype=bool)\n', (55162, 55193), True, 'import numpy as np\n'), ((55251, 55296), 'numpy.logical_and', 'np.logical_and', (['page_index', 'self.doc.accept.x'], {}), '(page_index, self.doc.accept.x)\n', (55265, 55296), True, 'import numpy as np\n'), ((56935, 56959), 'wx.BoxSizer', 'wx.BoxSizer', (['wx.VERTICAL'], {}), '(wx.VERTICAL)\n', (56946, 56959), False, 'import wx\n'), ((58929, 58972), 'wx.CheckBox', 'wx.CheckBox', (['self', 'wx.ID_ANY', '"""Show Report"""'], {}), "(self, wx.ID_ANY, 'Show Report')\n", (58940, 58972), False, 'import wx\n'), ((59074, 59111), 'wx.CheckBox', 'wx.CheckBox', (['self', 'wx.ID_ANY', '"""Apply"""'], {}), "(self, wx.ID_ANY, 'Apply')\n", (59085, 59111), False, 'import wx\n'), ((59253, 59303), 'wx.Button', 'wx.Button', (['self', 'wx.ID_DEFAULT', '"""Default Settings"""'], {}), "(self, wx.ID_DEFAULT, 'Default Settings')\n", (59262, 59303), False, 'import wx\n'), ((59430, 59455), 'wx.StdDialogButtonSizer', 'wx.StdDialogButtonSizer', ([], {}), '()\n', (59453, 59455), False, 'import wx\n'), ((59483, 59508), 'wx.Button', 'wx.Button', (['self', 'wx.ID_OK'], {}), '(self, wx.ID_OK)\n', (59492, 59508), False, 'import wx\n'), ((59644, 59673), 'wx.Button', 'wx.Button', (['self', 'wx.ID_CANCEL'], {}), '(self, wx.ID_CANCEL)\n', (59653, 59673), False, 'import wx\n'), ((61440, 61464), 'wx.BoxSizer', 'wx.BoxSizer', (['wx.VERTICAL'], {}), '(wx.VERTICAL)\n', (61451, 61464), False, 'import wx\n'), ((61693, 61748), 'wx.TextCtrl', 'wx.TextCtrl', (['self', 'wx.ID_ANY', "('%i %i' % (rows, columns))"], {}), "(self, wx.ID_ANY, '%i %i' % (rows, columns))\n", (61704, 61748), False, 'import wx\n'), ((61834, 61881), 'wx.CheckBox', 'wx.CheckBox', (['self', 'wx.ID_ANY', '"""Topographic map"""'], {}), "(self, wx.ID_ANY, 'Topographic map')\n", (61845, 61881), False, 'import wx\n'), ((61980, 62026), 'wx.CheckBox', 'wx.CheckBox', (['self', 'wx.ID_ANY', '"""Page mean plot"""'], {}), "(self, wx.ID_ANY, 'Page mean plot')\n", (61991, 62026), False, 'import wx\n'), ((62141, 62166), 'wx.StdDialogButtonSizer', 'wx.StdDialogButtonSizer', ([], {}), '()\n', (62164, 62166), False, 'import wx\n'), ((62194, 62219), 'wx.Button', 'wx.Button', (['self', 'wx.ID_OK'], {}), '(self, wx.ID_OK)\n', (62203, 62219), False, 'import wx\n'), ((62722, 62757), 're.match', 're.match', (['"""(\\\\d+)\\\\s*(\\\\d*)"""', 'value'], {}), "('(\\\\d+)\\\\s*(\\\\d*)', value)\n", (62730, 62757), False, 'import re\n'), ((63937, 63961), 'wx.BoxSizer', 'wx.BoxSizer', (['wx.VERTICAL'], {}), '(wx.VERTICAL)\n', (63948, 63961), False, 'import wx\n'), ((63996, 64022), 'wx.BoxSizer', 'wx.BoxSizer', (['wx.HORIZONTAL'], {}), '(wx.HORIZONTAL)\n', (64007, 64022), False, 'import wx\n'), ((64632, 64731), 'wx.RadioBox', 'wx.RadioBox', (['self', 'wx.ID_ANY', '"""Action"""'], {'choices': "('Reject', 'Accept')", 'style': 'wx.RA_SPECIFY_ROWS'}), "(self, wx.ID_ANY, 'Action', choices=('Reject', 'Accept'), style=\n wx.RA_SPECIFY_ROWS)\n", (64643, 64731), False, 'import wx\n'), ((64909, 64934), 'wx.StdDialogButtonSizer', 'wx.StdDialogButtonSizer', ([], {}), '()\n', (64932, 64934), False, 'import wx\n'), ((64962, 64987), 'wx.Button', 'wx.Button', (['self', 'wx.ID_OK'], {}), '(self, wx.ID_OK)\n', (64971, 64987), False, 'import wx\n'), ((65778, 65828), 'wx.Dialog.__init__', 'wx.Dialog.__init__', (['self', 'parent', 'wx.ID_ANY', 'title'], {}), '(self, parent, wx.ID_ANY, title)\n', (65796, 65828), False, 'import wx\n'), ((66425, 66449), 'wx.BoxSizer', 'wx.BoxSizer', (['wx.VERTICAL'], {}), '(wx.VERTICAL)\n', (66436, 66449), False, 'import wx\n'), ((66525, 66560), 'wx.StaticText', 'wx.StaticText', (['self', 'wx.ID_ANY', 'txt'], {}), '(self, wx.ID_ANY, txt)\n', (66538, 66560), False, 'import wx\n'), ((66601, 66656), 'wx.RadioBox', 'wx.RadioBox', (['self', 'wx.ID_ANY', '"""Method"""'], {'choices': 'choices'}), "(self, wx.ID_ANY, 'Method', choices=choices)\n", (66612, 66656), False, 'import wx\n'), ((67332, 67401), 'wx.CheckBox', 'wx.CheckBox', (['self', 'wx.ID_ANY', '"""Reject epochs exceeding the threshold"""'], {}), "(self, wx.ID_ANY, 'Reject epochs exceeding the threshold')\n", (67343, 67401), False, 'import wx\n'), ((67567, 67632), 'wx.CheckBox', 'wx.CheckBox', (['self', 'wx.ID_ANY', '"""Accept epochs below the threshold"""'], {}), "(self, wx.ID_ANY, 'Accept epochs below the threshold')\n", (67578, 67632), False, 'import wx\n'), ((67793, 67836), 'wx.CheckBox', 'wx.CheckBox', (['self', 'wx.ID_ANY', '"""Show Report"""'], {}), "(self, wx.ID_ANY, 'Show Report')\n", (67804, 67836), False, 'import wx\n'), ((67956, 67981), 'wx.StdDialogButtonSizer', 'wx.StdDialogButtonSizer', ([], {}), '()\n', (67979, 67981), False, 'import wx\n'), ((68009, 68034), 'wx.Button', 'wx.Button', (['self', 'wx.ID_OK'], {}), '(self, wx.ID_OK)\n', (68018, 68034), False, 'import wx\n'), ((68170, 68199), 'wx.Button', 'wx.Button', (['self', 'wx.ID_CANCEL'], {}), '(self, wx.ID_CANCEL)\n', (68179, 68199), False, 'import wx\n'), ((69663, 69695), 're.match', 're.match', (['"""^(\\\\w+):(\\\\w+)$"""', 'url'], {}), "('^(\\\\w+):(\\\\w+)$', url)\n", (69671, 69695), False, 'import re\n'), ((5366, 5388), 'numpy.ones', 'np.ones', (['n'], {'dtype': 'bool'}), '(n, dtype=bool)\n', (5373, 5388), True, 'import numpy as np\n'), ((7898, 7918), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (7912, 7918), False, 'import os\n'), ((13206, 13251), 'numpy.all', 'np.all', (['(ds[self.trigger.name] == self.trigger)'], {}), '(ds[self.trigger.name] == self.trigger)\n', (13212, 13251), True, 'import numpy as np\n'), ((18812, 18823), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (18820, 18823), True, 'import numpy as np\n'), ((19688, 19738), 'numpy.flatnonzero', 'np.flatnonzero', (['(new_interp != self.doc.interpolate)'], {}), '(new_interp != self.doc.interpolate)\n', (19702, 19738), True, 'import numpy as np\n'), ((20585, 20606), 'numpy.invert', 'np.invert', (['new_accept'], {}), '(new_accept)\n', (20594, 20606), True, 'import numpy as np\n'), ((20809, 20870), 'numpy.logical_and', 'np.logical_and', (['index', '(new_accept != self.doc.accept.x)', 'index'], {}), '(index, new_accept != self.doc.accept.x, index)\n', (20823, 20870), True, 'import numpy as np\n'), ((46884, 46909), 'math.ceil', 'math.ceil', (['(n / n_per_page)'], {}), '(n / n_per_page)\n', (46893, 46909), False, 'import math\n'), ((54421, 54432), 'time.time', 'time.time', ([], {}), '()\n', (54430, 54432), False, 'import time\n'), ((54629, 54725), 'wx.MessageBox', 'wx.MessageBox', (['"""Interpolation is disabled for this session"""', '"""Interpolation disabled"""', 'wx.OK'], {}), "('Interpolation is disabled for this session',\n 'Interpolation disabled', wx.OK)\n", (54642, 54725), False, 'import wx\n'), ((54885, 54911), 'numpy.abs', 'np.abs', (['(locs - event.ydata)'], {}), '(locs - event.ydata)\n', (54891, 54911), True, 'import numpy as np\n'), ((57003, 57060), 'wx.StaticText', 'wx.StaticText', (['self'], {'label': '"""Threshold for flat channels:"""'}), "(self, label='Threshold for flat channels:')\n", (57016, 57060), False, 'import wx\n'), ((57584, 57652), 'wx.StaticText', 'wx.StaticText', (['self'], {'label': '"""Threshold for flat channels in average:"""'}), "(self, label='Threshold for flat channels in average:')\n", (57597, 57652), False, 'import wx\n'), ((58219, 58294), 'wx.StaticText', 'wx.StaticText', (['self'], {'label': '"""Threshold for channel to neighbor correlation:"""'}), "(self, label='Threshold for channel to neighbor correlation:')\n", (58232, 58294), False, 'import wx\n'), ((58867, 58902), 'wx.StaticText', 'wx.StaticText', (['self'], {'label': '"""Output"""'}), "(self, label='Output')\n", (58880, 58902), False, 'import wx\n'), ((60178, 60288), 'wx.MessageBox', 'wx.MessageBox', (['"""Specify at least one action (report or apply)"""', '"""No Command Selected"""', 'wx.ICON_EXCLAMATION'], {}), "('Specify at least one action (report or apply)',\n 'No Command Selected', wx.ICON_EXCLAMATION)\n", (60191, 60288), False, 'import wx\n'), ((61484, 61613), 'wx.StaticText', 'wx.StaticText', (['self', 'wx.ID_ANY', '"""Layout: number of rows and columns (e.g., \'5 7\')\nor number of epochs (e.g., \'35\'):"""'], {}), '(self, wx.ID_ANY,\n """Layout: number of rows and columns (e.g., \'5 7\')\nor number of epochs (e.g., \'35\'):"""\n )\n', (61497, 61613), False, 'import wx\n'), ((62329, 62358), 'wx.Button', 'wx.Button', (['self', 'wx.ID_CANCEL'], {}), '(self, wx.ID_CANCEL)\n', (62338, 62358), False, 'import wx\n'), ((63365, 63466), 'wx.MessageBox', 'wx.MessageBox', (["('Invalid layout string: %s' % value)", '"""Invalid Layout"""', '(wx.OK | wx.ICON_ERROR)', 'self'], {}), "('Invalid layout string: %s' % value, 'Invalid Layout', wx.OK |\n wx.ICON_ERROR, self)\n", (63378, 63466), False, 'import wx\n'), ((64042, 64082), 'wx.StaticText', 'wx.StaticText', (['self', 'wx.ID_ANY', '"""First:"""'], {}), "(self, wx.ID_ANY, 'First:')\n", (64055, 64082), False, 'import wx\n'), ((64316, 64355), 'wx.StaticText', 'wx.StaticText', (['self', 'wx.ID_ANY', '"""Last:"""'], {}), "(self, wx.ID_ANY, 'Last:')\n", (64329, 64355), False, 'import wx\n'), ((65097, 65126), 'wx.Button', 'wx.Button', (['self', 'wx.ID_CANCEL'], {}), '(self, wx.ID_CANCEL)\n', (65106, 65126), False, 'import wx\n'), ((67248, 67283), 'wx.StaticText', 'wx.StaticText', (['self'], {'label': '"""Output"""'}), "(self, label='Output')\n", (67261, 67283), False, 'import wx\n'), ((68935, 69075), 'wx.MessageBox', 'wx.MessageBox', (['"""Specify at least one action (create report or reject or accept epochs)"""', '"""No Command Selected"""', 'wx.ICON_EXCLAMATION'], {}), "(\n 'Specify at least one action (create report or reject or accept epochs)',\n 'No Command Selected', wx.ICON_EXCLAMATION)\n", (68948, 69075), False, 'import wx\n'), ((25835, 25928), 'wx.CallLater', 'wx.CallLater', (['(1)', 'wx.MessageBox', 'msg', '"""Invalid Channels in Mark"""', '(wx.OK | wx.ICON_WARNING)'], {}), "(1, wx.MessageBox, msg, 'Invalid Channels in Mark', wx.OK | wx.\n ICON_WARNING)\n", (25847, 25928), False, 'import wx\n'), ((42445, 42469), 'numpy.invert', 'np.invert', (['sub_threshold'], {}), '(sub_threshold)\n', (42454, 42469), True, 'import numpy as np\n'), ((42684, 42700), 'numpy.any', 'np.any', (['rejected'], {}), '(rejected)\n', (42690, 42700), True, 'import numpy as np\n'), ((47140, 47162), 'numpy.arange', 'np.arange', (['start', 'stop'], {}), '(start, stop)\n', (47149, 47162), True, 'import numpy as np\n'), ((63211, 63312), 'wx.MessageBox', 'wx.MessageBox', (['"""Layout does not have enough plots"""', '"""Invalid Layout"""', '(wx.OK | wx.ICON_ERROR)', 'self'], {}), "('Layout does not have enough plots', 'Invalid Layout', wx.OK |\n wx.ICON_ERROR, self)\n", (63224, 63312), False, 'import wx\n'), ((6817, 6995), 'wx.MessageBox', 'wx.MessageBox', (['"""No eye tracker data was found in ds.info[\'edf\']. Use load.eyelink.add_edf(ds) to add an eye tracker file to a Dataset ds."""', '"""Eye Tracker Data Not Found"""'], {}), '(\n "No eye tracker data was found in ds.info[\'edf\']. Use load.eyelink.add_edf(ds) to add an eye tracker file to a Dataset ds."\n , \'Eye Tracker Data Not Found\')\n', (6830, 6995), False, 'import wx\n'), ((45900, 45914), 'math.sqrt', 'math.sqrt', (['nax'], {}), '(nax)\n', (45909, 45914), False, 'import math\n'), ((45943, 45964), 'math.ceil', 'math.ceil', (['(nax / nrow)'], {}), '(nax / nrow)\n', (45952, 45964), False, 'import math\n'), ((27698, 27715), 'numpy.nonzero', 'np.nonzero', (['index'], {}), '(index)\n', (27708, 27715), True, 'import numpy as np\n'), ((30828, 30872), 'scipy.spatial.distance.cdist', 'cdist', (['ch_locs', '[[event.xdata, event.ydata]]'], {}), '(ch_locs, [[event.xdata, event.ydata]])\n', (30833, 30872), False, 'from scipy.spatial.distance import cdist\n'), ((35115, 35139), 'numpy.flatnonzero', 'np.flatnonzero', (['rejected'], {}), '(rejected)\n', (35129, 35139), True, 'import numpy as np\n'), ((42843, 42867), 'numpy.flatnonzero', 'np.flatnonzero', (['rejected'], {}), '(rejected)\n', (42857, 42867), True, 'import numpy as np\n')]
import numpy as np import argparse import os from PIL import Image class BackofficeIconConverter: """ Icon creator to convert an input file into the correct format needed by the SAP Commerce Backoffice framework to be used as icon in the explorer-tree. """ #: Side length of a single image (height = width) SINGLE_IMAGE_SIDE_LENGTH = 16 #: The backoffice icon file must be 16x80 as RGBA BACKOFFICE_ICON_SIZE = (80, 16, 4) def __init__(self, inputFilename: str) -> None: """ Initialises a new BackofficeIconCreator that can be used to convert a single icon. :param inputFilename: Input file used as source for the conversation. """ self.sourceFilename = inputFilename def getDefaultTargetPath(self) -> str: """ Create the default output path from the input name. """ head, tail = os.path.split(self.sourceFilename) outFilename = f"backoffice-{tail}" return os.path.join(head, outFilename) def convertToDefault(self) -> None: """Convert the current file and place it under the default output location. If the target file already exists, it will be overridden. """ self.convertTo(self.getDefaultTargetPath()) def convertTo(self, targetPath: str) -> None: """Convert the current file and place it under the targetPath. If there is already a file in the given location, it will be overridden. :param targetPath: The path including filename. """ sourceImage = Image.open(self.sourceFilename).convert('RGBA') width, height = sourceImage.size if (width != self.SINGLE_IMAGE_SIDE_LENGTH or height != self.SINGLE_IMAGE_SIDE_LENGTH): raise ValueError("input image must be {}x{} but {} was actually \ {}x{}!".format( self.SINGLE_IMAGE_SIDE_LENGTH, self.SINGLE_IMAGE_SIDE_LENGTH, self.sourceFilename, width, height )) sourceImg = sourceImage.load() outImg = np.zeros(self.BACKOFFICE_ICON_SIZE, dtype=np.uint8) self.__fillImageWithColor(outImg, sourceImg, 0, (127, 144, 165, 255)) self.__fillImageWithColor(outImg, sourceImg, 1, (85, 102, 122, 255)) self.__fillImageWithColor(outImg, sourceImg, 2, (4, 134, 224, 255)) self.__fillImageWithColor(outImg, sourceImg, 3, (4, 134, 224, 255)) self.__fillImageWithColor(outImg, sourceImg, 4, (190, 196, 209, 255)) outImage = Image.fromarray(outImg) outImage.save(targetPath) def __fillImageWithColor( self, outImg: np.ndarray, sourceImg, heightDisplace: int, color: tuple ) -> None: heightDisplaceInPixel = heightDisplace * self.SINGLE_IMAGE_SIDE_LENGTH for y in range(self.SINGLE_IMAGE_SIDE_LENGTH): for x in range(self.SINGLE_IMAGE_SIDE_LENGTH): sourcePx = sourceImg[x, y] # take alpha value from source, the color from the target color color = (color[0], color[1], color[2], sourcePx[3]) outImg[heightDisplaceInPixel + y, x] = color def main(): parser = argparse.ArgumentParser( description="Convert simple icons to the SAP Commerce Backoffice \ explorer tree icon format. The icon must be a sprite consist of 5 \ different color shades of the icon itself." ) parser.add_argument("inputIcons", nargs="+", help="files to convert") parser.add_argument("-o", "--output", dest="output") args = parser.parse_args() for file in args.inputIcons: print(f"Process icon {file}...") iconConverter = BackofficeIconConverter(file) if args.output: # combine the current filename with the out folder name head, tail = os.path.split(file) targetPath = os.path.join(args.output, tail) iconConverter.convertTo(targetPath) print(f"{file} => {targetPath}") pass else: iconConverter.convertToDefault() print(f"{file} => {iconConverter.getDefaultTargetPath()}") if __name__ == "__main__": main()
[ "argparse.ArgumentParser", "numpy.zeros", "PIL.Image.open", "PIL.Image.fromarray", "os.path.split", "os.path.join" ]
[((3290, 3517), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert simple icons to the SAP Commerce Backoffice explorer tree icon format. The icon must be a sprite consist of 5 different color shades of the icon itself."""'}), "(description=\n 'Convert simple icons to the SAP Commerce Backoffice explorer tree icon format. The icon must be a sprite consist of 5 different color shades of the icon itself.'\n )\n", (3313, 3517), False, 'import argparse\n'), ((894, 928), 'os.path.split', 'os.path.split', (['self.sourceFilename'], {}), '(self.sourceFilename)\n', (907, 928), False, 'import os\n'), ((987, 1018), 'os.path.join', 'os.path.join', (['head', 'outFilename'], {}), '(head, outFilename)\n', (999, 1018), False, 'import os\n'), ((2146, 2197), 'numpy.zeros', 'np.zeros', (['self.BACKOFFICE_ICON_SIZE'], {'dtype': 'np.uint8'}), '(self.BACKOFFICE_ICON_SIZE, dtype=np.uint8)\n', (2154, 2197), True, 'import numpy as np\n'), ((2603, 2626), 'PIL.Image.fromarray', 'Image.fromarray', (['outImg'], {}), '(outImg)\n', (2618, 2626), False, 'from PIL import Image\n'), ((3934, 3953), 'os.path.split', 'os.path.split', (['file'], {}), '(file)\n', (3947, 3953), False, 'import os\n'), ((3979, 4010), 'os.path.join', 'os.path.join', (['args.output', 'tail'], {}), '(args.output, tail)\n', (3991, 4010), False, 'import os\n'), ((1583, 1614), 'PIL.Image.open', 'Image.open', (['self.sourceFilename'], {}), '(self.sourceFilename)\n', (1593, 1614), False, 'from PIL import Image\n')]
# These are control plot used in the NN pipeline import h5py import matplotlib as mpl import numpy as np import pandas as pd from modules.BAR_BC_method import calc_BAR_BC, calc_composition, filter_data_mask from modules.collect_data import resave_Tomas_OL_OPX_mixtures import matplotlib.pyplot as plt import matplotlib.patches as patches import seaborn as sns from sklearn.metrics import confusion_matrix from keras.models import Functional from mpl_toolkits.axes_grid1 import make_axes_locatable from modules.NN_losses_metrics_activations import my_rmse, my_r2, my_sam, my_quantile from modules.NN_data import * from modules.NN_config import * from modules.CD_parameters import path_relab, path_taxonomy from modules.NN_config_taxonomy import classes, classes2 mpl.use('TkAgg') TEXT_SIZE = 12 SMALL_SIZE = 16 MEDIUM_SIZE = 20 BIGGER_SIZE = 24 LW = 1 plt.rc('font', size=TEXT_SIZE) # controls default text sizes plt.rc('axes', titlesize=BIGGER_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title # plt.rcParams['text.usetex'] = True plt.rc('text', usetex=True) plt.rcParams['text.latex.preamble'] = r"\usepackage{amsmath}" plt.rc('font', **{'family': 'sans-serif', 'sans-serif': ['Arial']}) # plt.rc('font', **{'family': 'serif', 'serif': ['Palatino']}) outdir = "".join((project_dir, '/figures/')) check_dir(outdir) fig_format = 'pdf' def plot_scatter_plots(y_true: np.ndarray, y_pred: np.ndarray, suf: str = '') -> None: print('Scatter plots') y_true = y_true[:] * 100 y_pred = y_pred[:] * 100 # limit = 0.25 shift = 3 # Control ranges of axes (from 0 - shift to 100 + shift) s = 30 # scaling parameter (marker size) vmin = 0 # minimum for colormap in scatter of chemical cmap = 'viridis_r' # cmap of points titles_all = [['Fa', 'Fo'], ['Fs', 'En', 'Wo'], ['Fs', 'En', 'Wo'], ['An', 'Ab', 'Or']] if not chem_without_modal: titles_all = [titles_all[k] for k in range(len(use_minerals)) if use_minerals_all[k]] titles_all = [[titles_all[k][j] for j in range(len(subtypes_all_used[k])) if subtypes_all_used[k][j]] for k in range(len(subtypes))] # define the lines x_line = np.arange(-150, 151) y_line = x_line y1p_line, y1m_line = y_line + 10, y_line - 10 y2p_line, y2m_line = y_line + 20, y_line - 20 l10, l20 = 'm-', 'c-' lab_line0, lab_line10, lab_line20 = '0 pp error', '10 pp error', '20 pp error' RMSE = my_rmse(num_minerals)(y_true, y_pred).numpy() / 100 # is multiplied with 100 in the code R2 = my_r2(num_minerals)(y_true, y_pred).numpy() SAM = my_sam(num_minerals)(y_true, y_pred).numpy() * 180 / np.pi # modal first start, stop = 0, num_minerals if num_minerals > 1: x_tmp, y_tmp = y_true[:, start:stop], y_pred[:, start:stop] fig, ax = plt.subplots(1, num_minerals, figsize=(4.5 * num_minerals, 6)) for i in range(num_minerals): # lines lns1 = ax[i].plot(x_line, y_line, 'k', label=lab_line0, linewidth=LW) lns2 = ax[i].plot(x_line, y1p_line, l10, label=lab_line10, linewidth=LW) ax[i].plot(x_line, y1m_line, l10, linewidth=LW) lns3 = ax[i].plot(x_line, y2p_line, l20, label=lab_line20, linewidth=LW) ax[i].plot(x_line, y2m_line, l20, linewidth=LW) # data ax[i].scatter(x_tmp[:, i], y_tmp[:, i], c='black', s=s, zorder=100) ax[i].set_xlabel('Actual') ax[i].tick_params(axis='both') ax[i].axis('square') ax[i].set_ylim(bottom=-shift, top=100 + shift) ax[i].set_xlim(left=-shift, right=100 + shift) ax[i].set_title(minerals[i]) ax[i].set_xticks(np.arange(0, 100.1, 25)) ax[i].set_yticks(np.arange(0, 100.1, 25)) ax[i].text(0.8, 0.15, r'\[' # every line is a separate raw string... r'\begin{split}' # ...but they are all concatenated by the interpreter :-) r'\mathsf{RMSE} &= ' + '{:4.1f}'.format(RMSE[i]) + r'\\' r'\mathsf{R}^2 &= ' + '{:4.2f}'.format( R2[i]) + r'\\' r'\mathsf{SAM} &= ' + '{:4.1f}'.format(SAM[i]) + r'\text{ [deg]}' r'\end{split}' r'\]', horizontalalignment='center', verticalalignment='center', transform=ax[i].transAxes) if i > 0: ax[i].set_yticklabels([]) lns = lns1 + lns2 + lns3 labs = [l.get_label() for l in lns] ax[i].legend(lns, labs, loc='upper left', frameon=False) ax[0].set_ylabel('Predicted') plt.draw() plt.tight_layout() fig_name = "".join(('scatter_plot_modal', suf, '.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) # each mineral on separate plot for i in range(len(subtypes)): start, stop = stop, stop + subtypes[i] titles = titles_all[i] # fig size tuned such that the plots are approximately of the same size fig, ax = plt.subplots(1, subtypes[i], figsize=(4.4 * subtypes[i] + 1.5, 6)) if num_minerals > 1: # non-zero modal mask = y_true[:, i] > 0 x_tmp, y_tmp = y_true[mask, start:stop], y_pred[mask, start:stop] c = y_true[mask, i] else: x_tmp, y_tmp = y_true[:, start:stop], y_pred[:, start:stop] c = 'black' for j in range(subtypes[i]): # lines lns1 = ax[j].plot(x_line, y_line, 'k', label=lab_line0, linewidth=LW) lns2 = ax[j].plot(x_line, y1p_line, l10, label=lab_line10, linewidth=LW) ax[j].plot(x_line, y1m_line, l10, linewidth=LW) lns3 = ax[j].plot(x_line, y2p_line, l20, label=lab_line20, linewidth=LW) ax[j].plot(x_line, y2m_line, l20, linewidth=LW) # data sc = ax[j].scatter(x_tmp[:, j], y_tmp[:, j], c=c, cmap=cmap, vmin=vmin, vmax=100, s=s, zorder=100) divider = make_axes_locatable(ax[j]) cax = divider.append_axes("right", size="5%", pad=0.1) cbar = plt.colorbar(sc, ax=ax[j], cax=cax) if j == subtypes[i] - 1: cbar.ax.set_ylabel('Modal abundance [vol\%]') else: cbar.remove() ax[j].set_xlabel('Actual') ax[j].tick_params(axis='both') ax[j].axis('square') ax[j].set_ylim(bottom=-shift, top=100 + shift) ax[j].set_xlim(left=-shift, right=100 + shift) ax[j].set_title(titles[j]) ax[j].set_xticks(np.arange(0, 100.1, 25)) ax[j].set_yticks(np.arange(0, 100.1, 25)) ax[j].text(0.8, 0.15, r'\[' # every line is a separate raw string... r'\begin{split}' # ...but they are all concatenated by the interpreter :-) r'\mathsf{RMSE} &= ' + '{:4.1f}'.format(RMSE[start + j]) + r'\\' r'\mathsf{R}^2 &= ' + '{:4.2f}'.format( R2[start + j]) + r'\\' r'\mathsf{SAM} &= ' + '{:4.1f}'.format(SAM[start + j]) + r'\text{ [deg]}' r'\end{split}' r'\]', horizontalalignment='center', verticalalignment='center', transform=ax[j].transAxes) if j > 0: ax[j].set_yticklabels([]) lns = lns1 + lns2 + lns3 labs = [l.get_label() for l in lns] ax[j].legend(lns, labs, loc='upper left', frameon=False) ax[0].set_ylabel('Predicted') plt.draw() plt.tight_layout() fig_name = "".join(('scatter_plot_', minerals_used[i], suf, '.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_error_evaluation(y_true: np.ndarray, y_pred: np.ndarray) -> None: print('Print quantiles') # define the lines x_line = np.arange(-150, 151) y_line_10 = np.ones(np.shape(x_line)) * 10 y_line_20 = np.ones(np.shape(x_line)) * 20 l10, l20 = 'k--', 'k--' percentile = np.arange(0, 101, 5) quantile = my_quantile(num_minerals, percentile)(y_true, y_pred).numpy() titles_all = [['OL', 'OPX', 'CPX', 'PLG'], ['Fa', 'Fo'], ['Fs (OPX)', 'En (OPX)', 'Wo (OPX)'], ['Fs (CPX)', 'En (CPX)', 'Wo (CPX)'], ['An', 'Ab', 'Or']] titles_all = np.array(flatten_list(titles_all))[used_indices] # modification of used indices (if there are two labels, their absolute errors are the same; one is enough) use_inds = deepcopy([list(use_minerals_all)] + [*subtypes_all]) for i in range(len(use_inds)): if np.sum(use_inds[i]) == 2: use_inds[i][np.where(use_inds[i])[0][-1]] = False use_inds = flatten_list(use_inds) * used_indices # from quantile delete indices, where used_indices are not use_indices keep_inds = np.array([i for i in range(len(np.where(used_indices)[0])) if np.where(used_indices)[0][i] in np.where(use_inds)[0]]) titles_all = titles_all[keep_inds] quantile = quantile[:, keep_inds] shift = 3 # Control ranges of axes (from 0 - shift to 100 + shift) fig, ax = plt.subplots(1, 1, figsize=(8, 6)) if np.shape(quantile)[1] > 10: ax.plot(percentile, quantile[:, :10], linewidth=2) ax.plot(percentile, quantile[:, 10:], '--', linewidth=2) ncol = 2 else: ax.plot(percentile, quantile, linewidth=2) ncol = 1 # constant error lines ax.plot(x_line, y_line_10, l10) ax.plot(x_line, y_line_20, l20) ax.set_xlabel('Percentile') ax.set_ylabel('Absolute error') ax.set_ylim(bottom=-shift, top=100 + shift) ax.set_xlim(left=-shift, right=100 + shift) ax.set_xticks(np.arange(0, 100.1, 10)) ax.set_yticks(np.arange(0, 100.1, 10)) ax.legend(titles_all, loc='upper left', ncol=ncol) plt.draw() plt.tight_layout() fig_name = "".join(('quantile_error_plot', '.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_ast_PC1_PC2(y_pred: np.ndarray) -> None: print('Plot PC1 vs PC2 for asteroids') filename = project_dir + '/Datasets/taxonomy/asteroid_spectra-denoised-norm-meta.dat' data = pd.read_csv(filename, sep='\t', header=None).to_numpy() # to read the file types = data[:, 1].astype(np.str) inds_S = np.array(['S' in ast_type for ast_type in types]) inds_Q = np.array(['Q' in ast_type for ast_type in types]) inds_A = np.array(['A' in ast_type for ast_type in types]) inds_V = np.array(['V' in ast_type for ast_type in types]) inds = inds_S + inds_Q + inds_V + inds_A # ignore Sq: since its spectrum is very weird inds[types == 'Sq:'] = False unique, counts = np.unique(types[inds], return_counts=True) PCA = data[inds, 3:5].astype(np.float64) predictions = y_pred[inds] * 100 cmap = 'viridis_r' # cmap of points s = 30 # scaling parameter (marker size) vmin = 0 # minimum for colormap in scatter of chemical labels = np.core.defchararray.add('$', types[inds]) labels = np.core.defchararray.add(labels, '$') fig, ax = plt.subplots(1, 1, figsize=(8, 6)) # Why I cannot set marker=labels and do it all as for vectors?? for i in range(len(PCA)): if len(labels[i]) == 3: fact = 1 if len(labels[i]) == 4: fact = 2.5 if len(labels[i]) == 5: fact = 5.5 c = predictions[i, 0] sp = ax.scatter(PCA[i, 1], PCA[i, 0], c=c, cmap=cmap, vmin=vmin, vmax=100, s=s * fact, marker=labels[i]) ax.set_xlabel("PC2'") ax.set_ylabel("PC1'") x0, x1 = np.array([0.5, -0.5]), np.array(([0.0, 0.8])) plt.annotate("", xy=x1, xytext=x0, zorder=-1, arrowprops=dict(arrowstyle="->", color='r', facecolor='black', lw=3)) plt.text(x=0.1, y=-0.2, s="Space weathering", rotation=-51, c='r', fontsize=SMALL_SIZE) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) cbar = plt.colorbar(sp, ax=ax, cax=cax) cbar.ax.set_ylabel('Olivine abundance [vol\%]') fig.tight_layout() # otherwise the right y-label is slightly clipped plt.draw() fig_name = "".join(('PCA_plot.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_Fa_vs_Fs_ast_only() -> None: print('Plot Fa vs Fs') limx1, limx2 = 15, 35 limy1, limy2 = 10, 30 shift = 1 # Control ranges of axes s = 50 # scaling parameter fig, ax = plt.subplots(1, 1, figsize=(5, 5)) # definition of boxes from (for some reasons should be used just once) # https://www.researchgate.net/figure/Mineral-compositional-data-for-the-Morokweng-meteoriteDiagram-shows-ferrosilite-Fs_fig3_7093505 H_rect = patches.Rectangle((16.2, 14.5), 3.8, 3.5, linewidth=1.5, edgecolor='r', facecolor='none') L_rect = patches.Rectangle((22.0, 19.0), 4.0, 3.0, linewidth=1.5, edgecolor='g', facecolor='none') LL_rect = patches.Rectangle((26.0, 22.0), 6.0, 4.2, linewidth=1.5, edgecolor='b', facecolor='none') ax.set_xlabel('Fa') ax.set_ylabel('Fs') ax.tick_params(axis='both') ax.axis('square') ax.set_xticks(np.arange(limx1, limx2 + 0.1, 5)) ax.set_yticks(np.arange(limy1, limy2 + 0.1, 5)) ax.set_ylim(bottom=limy1 - shift, top=limy2 + shift) ax.set_xlim(left=limx1 - shift, right=limx2 + shift) # add the patches ax.add_patch(H_rect) ax.add_patch(L_rect) ax.add_patch(LL_rect) # artificial data to get labels for legend ax.plot(120, 120, 'rs', label='H', markerfacecolor='none') ax.plot(120, 120, 'gs', label='L', markerfacecolor='none') ax.plot(120, 120, 'bs', label='LL', markerfacecolor='none') ax.legend(loc='upper left') Fa_S, Fs_S, sigma_fas, sigma_fss = [20.7], [18.3], 4.5, 4.9 Fa_Sq, Fs_Sq, sigma_fasq, sigma_fssq = [23.2], [21.0], 4.6, 4.1 Fa_Sr, Fs_Sr, sigma_fasr, sigma_fssr, = [18.3], [19.2], 5.7, 5.4 Fa_Sw, Fs_Sw, sigma_fasw, sigma_fssw = [21.3], [14.7], 4.1, 4.2 Fa_Q, Fs_Q, sigma_faq, sigma_fsq = [26.2], [23.8], 5.4, 5.1 ax.scatter(Fa_S, Fs_S, marker='$S$', c='k', s=s * 2.5, zorder=100) ax.errorbar(Fa_S, Fs_S, xerr=sigma_fas, yerr=sigma_fss, c='c', ls='None') ax.scatter(Fa_Sq, Fs_Sq, marker='$Sq$', c='k', s=s * 5, zorder=100) ax.errorbar(Fa_Sq, Fs_Sq, xerr=sigma_fasq, yerr=sigma_fssq, c='c', ls='None') ax.scatter(Fa_Sr, Fs_Sr, marker='$Sr$', c='k', s=s * 5, zorder=100) ax.errorbar(Fa_Sr, Fs_Sr, xerr=sigma_fasr, yerr=sigma_fssr, c='c', ls='None') ax.scatter(Fa_Sw, Fs_Sw, marker='$Sw$', c='k', s=s * 6, zorder=100) ax.errorbar(Fa_Sw, Fs_Sw, xerr=sigma_fasw, yerr=sigma_fssw, c='c', ls='None') ax.scatter(Fa_Q, Fs_Q, marker='$Q$', c='k', s=s * 2.5, zorder=100) ax.errorbar(Fa_Q, Fs_Q, xerr=sigma_faq, yerr=sigma_fsq, c='c', ls='None') plt.draw() plt.tight_layout() fig_name = "".join(('Fa_vs_Fs.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_scatter_NN_BC(): from modules.NN_evaluate import evaluate_test_data wvl = np.arange(450, 2451, 5) filename_train_data = 'combined-denoised-norm.dat' x_train, y_train = load_data(filename_train_data, clean_dataset=True) x_train, y_train, x_val, y_val, x_test, y_true = split_data_proportional(x_train, y_train) model_names = ['20220330113805_CNN.h5'] # [14.4, 5.7, 5.7, 10.7] y_pred, accuracy = evaluate_test_data(model_names, x_test, y_true) # to get the test types filename = project_dir + '/Datasets/combined-denoised-norm-clean-meta.dat' data = pd.read_csv(filename, sep='\t', header=None).to_numpy() # to read the file types = data[:, 7] types = np.reshape(types, (len(types), 1)) filename_train_data = 'combined-denoised-norm-clean.dat' x_tmp, y_tmp = load_data(filename_train_data) _, _, _, _, meta, _ = split_data_proportional( np.concatenate((x_tmp, types), axis=1), y_tmp) types = meta[:, -1].astype(np.str) # jenom ty, co obrasuhuji OL a OPX (jen mixtures 12 a 14) binary = (y_true[:, :num_minerals] > 0).astype(int) base = np.array([8, 4, 2, 1])[use_minerals] mixtures = np.sum(binary * base, axis=1) mask1 = np.logical_or(mixtures == 12, mixtures == 14) # only those with CPX < 10 mask2 = y_true[:, 2] < 0.1 mask = np.logical_and(mask1, mask2) x_true = x_test[mask] y_true = y_true[mask] y_pred = y_pred[mask] types = types[mask] inds_HED = np.array(['HED' in type for type in types]) types[inds_HED] = 'V' types[~inds_HED] = 'S' BAR, BIC, BIIC = calc_BAR_BC(wvl, x_true) # remove nans mask = np.logical_and(np.logical_and(BAR > 0, BIC > 0), BIIC > 0) BAR, BIC, BIIC = BAR[mask], BIC[mask], BIIC[mask] OL_true = y_true[mask, 0] * 100 OL_pred = y_pred[mask, 0] * 100 Fs_true = y_true[mask, 5] * 100 Fs_pred = y_pred[mask, 5] * 100 types = types[mask] OL_fraction, Fs, Wo = calc_composition(BAR, BIC, BIIC, types, method=0) _, Fs_v2, _ = calc_composition(BAR, BIC, BIIC, types, method=1) # filter the data mask = filter_data_mask(OL_fraction, Fs, Wo) OL_fraction = OL_fraction[mask] Fs, Wo = Fs[mask], Wo[mask] OL_true = OL_true[mask] OL_pred = OL_pred[mask] Fs_true = Fs_true[mask] Fs_pred = Fs_pred[mask] Fs_v2 = Fs_v2[mask] LW = 1 s = 30 # scaling parameter (marker size) x_line = np.arange(-150, 151) y_line = x_line y1p_line, y1m_line = y_line + 10, y_line - 10 y2p_line, y2m_line = y_line + 20, y_line - 20 l10, l20 = 'm-', 'c-' lab_line0, lab_line10, lab_line20 = '0 pp error', '10 pp error', '20 pp error' shift = 3 # Control ranges of axes (from 0 - shift to 100 + shift) outdir = "".join((project_dir, '/figures/')) check_dir(outdir) fig, ax = plt.subplots(1, 2, figsize=(4.4 * 2 + 1.5, 6)) ax[0].scatter(OL_true, OL_pred, s=s, label='NN pred.', zorder=100) ax[0].scatter(OL_true, OL_fraction, s=s, label='BAR', zorder=99) ax[1].scatter(Fs_true, Fs_pred, s=s, label='NN pred.', zorder=100) ax[1].scatter(Fs_true, Fs_v2, s=s, label='BIC', zorder=99) ax[1].scatter(Fs_true, Fs, s=s, label='BIIC', zorder=98) ax[0].set_title('olivine') ax[1].set_title('Fs') ax[0].set_ylabel('Modelled') for i in range(2): ax[i].plot(x_line, y_line, 'k', label=lab_line0, linewidth=LW) ax[i].plot(x_line, y1p_line, l10, label=lab_line10, linewidth=LW) ax[i].plot(x_line, y1m_line, l10, linewidth=LW) ax[i].plot(x_line, y2p_line, l20, label=lab_line20, linewidth=LW) ax[i].plot(x_line, y2m_line, l20, linewidth=LW) ax[i].set_xlabel('Actual') ax[i].tick_params(axis='both') ax[i].axis('square') ax[i].set_ylim(bottom=-shift, top=100 + shift) ax[i].set_xlim(left=-shift, right=100 + shift) ax[i].set_xticks(np.arange(0, 100.1, 25)) ax[i].set_yticks(np.arange(0, 100.1, 25)) if i > 0: ax[i].set_yticklabels([]) ax[i].legend(loc='upper left', frameon=False) plt.draw() plt.tight_layout() fig_name = "".join(('scatter_plot_NN_BAR_BC_met_mix.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_PCA_BAR(): from modules.NN_evaluate import evaluate model_names = ['20220330113805_CNN.h5'] # [14.4, 5.7, 5.7, 10.7] wvl = np.arange(450, 2451, 5) filename_data = 'asteroid_spectra-denoised-norm-nolabel.dat' data_file = "".join((project_dir, '/Datasets/', filename_data)) data = np.loadtxt(data_file, delimiter='\t') y__pred = evaluate(model_names, filename_data) filename = project_dir + '/Datasets/taxonomy/asteroid_spectra-denoised-norm-meta.dat' meta = pd.read_csv(filename, sep='\t', header=None).to_numpy() # to read the file types = meta[:, 1].astype(np.str) inds_S = np.array(['S' in ast_type for ast_type in types]) inds_Q = np.array(['Q' in ast_type for ast_type in types]) inds_A = np.array(['A' in ast_type for ast_type in types]) inds_V = np.array(['V' in ast_type for ast_type in types]) inds = inds_S + inds_Q + inds_V + inds_A # ignore Sq: since its spectrum is very weird inds[types == 'Sq:'] = False types = types[inds] x_data = data[inds] y_pred = y__pred[inds] PCA = meta[inds, 3:5].astype(np.float64) labels = np.core.defchararray.add('$', types) labels = np.core.defchararray.add(labels, '$') BAR, BIC, BIIC = calc_BAR_BC(wvl, x_data) # remove nans mask = np.logical_and(np.logical_and(BAR > 0, BIC > 0), BIIC > 0) BAR, BIC, BIIC = BAR[mask], BIC[mask], BIIC[mask] OL_pred = y_pred[mask, 0] * 100 Fs_pred = y_pred[mask, 5] * 100 labels = labels[mask] types = types[mask] PCA = PCA[mask] OL_fraction, Fs, Wo = calc_composition(BAR, BIC, BIIC, types, method=0) _, Fs_v2, _ = calc_composition(BAR, BIC, BIIC, types, method=1) # filter the data mask = filter_data_mask(OL_fraction, Fs, Wo) OL_fraction = OL_fraction[mask] Fs, Wo = Fs[mask], Wo[mask] OL_pred = OL_pred[mask] Fs_pred = Fs_pred[mask] labels = labels[mask] types = types[mask] PCA = PCA[mask] unique, counts = np.unique(types, return_counts=True) cmap = 'viridis_r' # cmap of points s = 30 # scaling parameter (marker size) vmin = 0 # minimum for colormap in scatter of chemical fig, ax = plt.subplots(1, 1, figsize=(8, 6)) # Why I cannot set marker=labels and do it all as for vectors?? for i in range(len(PCA)): if len(labels[i]) == 3: fact = 1 if len(labels[i]) == 4: fact = 2.5 if len(labels[i]) == 5: fact = 5.5 c = OL_fraction[i] sp = ax.scatter(PCA[i, 1], PCA[i, 0], c=c, cmap=cmap, vmin=vmin, vmax=100, s=s * fact, marker=labels[i]) ax.set_xlabel("PC2'") ax.set_ylabel("PC1'") x0, x1 = np.array([0.5, -0.5]), np.array(([0.0, 0.8])) plt.annotate("", xy=x1, xytext=x0, zorder=-1, arrowprops=dict(arrowstyle="->", color='r', facecolor='black', lw=3)) plt.text(x=0.16, y=-0.2, s="Space weathering", rotation=-59.5, c='r', fontsize=16) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) cbar = plt.colorbar(sp, ax=ax, cax=cax) cbar.ax.set_ylabel('Olivine abundance [vol\%]') fig.tight_layout() # otherwise the right y-label is slightly clipped plt.draw() fig_name = "".join(('PCA_plot_BAR_BC.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_spectra(x_data, y_data) -> None: x = np.arange(450, 2451, 5) / 1000 # um titles = ['olivine', 'orthopyroxene', 'clinopyroxene', 'laboratory mixtures', 'meteorites', 'asteroids'] m, n = best_blk(len(titles)) # asteroid data filename = project_dir + '/Datasets/taxonomy/asteroid_spectra-denoised-norm-meta.dat' data = pd.read_csv(filename, sep='\t', header=None).to_numpy() # to read the file types = data[:, 1].astype(np.str) inds_S = np.array(['S' in ast_type for ast_type in types]) inds_Q = np.array(['Q' in ast_type for ast_type in types]) inds_A = np.array(['A' in ast_type for ast_type in types]) inds_V = np.array(['V' in ast_type for ast_type in types]) inds = inds_S + inds_Q + inds_V + inds_A # ignore Sq: since its spectrum is very weird inds[types == 'Sq:'] = False filename_data = 'asteroid_spectra-denoised-norm-nolabel.dat' data_file = "".join((project_dir, '/Datasets/', filename_data)) ast_data = np.loadtxt(data_file, delimiter='\t')[inds] fig, ax = plt.subplots(m, n, figsize=(4.7 * n, 4.7 * m)) ax = np.reshape(ax, (m, n)) inds = np.where(np.sum(y_data[:, :3] > 0, axis=1) > 1)[0] # urceno z konkretnich dat (90, 63) inds_met, inds_mix = inds[:63], inds[63:] for j in range(len(titles)): if j <= 2: data = x_data[y_data[:, j] == 1] if j == 3: data = x_data[inds_mix] # data = x_data[109:180] if j == 4: data = x_data[inds_met] # data = x_data[:109] if j == 5: data = ast_data i, k = np.unravel_index(j, (m, n)) ax[i, k].plot(x, np.transpose(data)) ax[i, k].tick_params(axis='both') ax[i, k].set_ylim(bottom=0, top=5) ax[i, k].set_xlim(left=0.4, right=2.500) ax[i, k].set_title(titles[j]) ax[i, k].set_xticks(np.arange(0.5, 2.501, 0.5)) if k > 0: ax[i, k].set_yticklabels([]) else: ax[i, k].set_ylabel('Reflectance [normalised]') if i == 0: ax[i, k].set_xticklabels([]) else: ax[i, k].set_xlabel('$\lambda$ [$\mu$m]') plt.draw() plt.tight_layout() fig_name = "".join(('spectra_all.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close() def plot_model_history(model: Functional) -> None: print('Model history') history = model.history.history kernel_width = 5 # Width of the convolution kernel conv_kernel = np.ones((kernel_width,)) conv_kernel /= np.sum(conv_kernel) fig = plt.figure("Loss and accuracy", figsize=(8, 6)) ax1 = fig.add_subplot(111) color1, color2 = 'tab:red', 'tab:blue' # Normalisation of the edges norm = np.convolve(np.ones((len(history['loss']),)), conv_kernel, 'same') plot1 = np.convolve(history['loss'], conv_kernel, 'same') / norm if model.metrics_names[1] == 'mse': # MSE to RMSE plot3 = np.convolve(np.sqrt(history[model.metrics_names[1]]), conv_kernel, 'same') / norm labely = 'rmse' else: plot3 = np.convolve(history[model.metrics_names[1]], conv_kernel, 'same') / norm labely = model.metrics_names[1] labely = str(np.char.replace(labely, '_', ' ')) lns1 = ax1.plot(plot1, color=color1, linestyle='-', label='loss - training') ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis lns3 = ax2.plot(plot3, color=color2, linestyle='-', label=labely + ' - training') if val_portion > 0: plot2 = np.convolve(history['val_loss'], conv_kernel, 'same') / norm if model.metrics_names[1] == 'mse': # MSE to RMSE plot4 = np.convolve(np.sqrt(history['val_' + model.metrics_names[1]]), conv_kernel, 'same') / norm else: plot4 = np.convolve(history['val_' + model.metrics_names[1]], conv_kernel, 'same') / norm lns2 = ax1.plot(plot2, color=color1, linestyle=':', label='loss - validation') lns4 = ax2.plot(plot4, color=color2, linestyle=':', label=labely + ' - validation') lns = lns1 + lns2 + lns3 + lns4 else: lns = lns1 + lns3 ax1.set_xlabel('epoch') ax1.tick_params(axis='x') ax1.set_ylabel('loss', color=color1) ax1.tick_params(axis='y', labelcolor=color1) ax1.set_ylim(bottom=0) ax1.set_xlim(left=0, right=model.history.params['epochs']) ax1.grid(False) ax2.set_ylabel(labely, color=color2) # we already handled the x-label with ax1 ax2.tick_params(axis='y', labelcolor=color2) ax2.set_ylim(bottom=0) ax2.grid(False) labs = [l.get_label() for l in lns] if plot3[0] > plot3[-1]: # the metric decreases if quality increases loc = 'upper right' else: loc = 'center right' ax1.legend(lns, labs, loc=loc) fig.tight_layout() # otherwise the right y-label is slightly clipped # plt.title('Model history') plt.draw() ''' from datetime import datetime now = datetime.now() dt_string = now.strftime("%Y%m%d%H%M%S") fig_name = "".join((dt_string, '_', 'model_history.', fig_format)) ''' fig_name = "".join(('model_history.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_Fa_vs_Fs(y_true: np.ndarray, y_pred: np.ndarray) -> None: print('Plot Fa vs Fs') # Indices in which Fa and Fs are ind_Fa, ind_Fs = num_minerals, num_minerals + subtypes[0] filename = project_dir + '/Datasets/combined-denoised-norm-clean-meta.dat' data = pd.read_csv(filename, sep='\t', header=None).to_numpy() # to read the file types = data[:, 7] types = np.reshape(types, (len(types), 1)) # to get the test types filename_train_data = 'combined-denoised-norm-clean.dat' x_train, y_train = load_data(filename_train_data) x_train, y_train, x_val, y_val, x_test, y_test = split_data_proportional( np.concatenate((x_train, types), axis=1), y_train) types = x_test[:, -1].astype(np.str) Fa_true, Fs_true = y_true[:, ind_Fa] * 100, y_true[:, ind_Fs] * 100 Fa_pred, Fs_pred = y_pred[:, ind_Fa] * 100, y_pred[:, ind_Fs] * 100 inds_H = np.array([('H' in OC_type) and ('HH' not in OC_type) if len(OC_type) == 2 else False for OC_type in types]) inds_L = np.array([('L' in OC_type) and ('LL' not in OC_type) if len(OC_type) == 2 else False for OC_type in types]) inds_LL = np.array(['LL' in OC_type if len(OC_type) == 3 else False for OC_type in types]) limx1, limx2 = 15, 35 limy1, limy2 = 10, 30 shift = 3 # Control ranges of axes s = 40 # scaling parameter fig, ax = plt.subplots(1, 2, figsize=(4.5 * 2, 6)) error_Fa, error_Fs = 5.7, 5.7 for i in range(2): # definition of boxes from (for some reasons should be used just once) # https://www.researchgate.net/figure/Mineral-compositional-data-for-the-Morokweng-meteoriteDiagram-shows-ferrosilite-Fs_fig3_7093505 H_rect = patches.Rectangle((16.2, 14.5), 3.8, 3.5, linewidth=1.5, edgecolor='r', facecolor='none') L_rect = patches.Rectangle((22.0, 19.0), 4.0, 3.0, linewidth=1.5, edgecolor='g', facecolor='none') LL_rect = patches.Rectangle((26.0, 22.0), 6.0, 4.2, linewidth=1.5, edgecolor='b', facecolor='none') if i == 0: ax[i].scatter(Fa_true[inds_H], Fs_true[inds_H], c='r', s=s, label='H') ax[i].scatter(Fa_true[inds_L], Fs_true[inds_L], c='g', s=s, label='L') ax[i].scatter(Fa_true[inds_LL], Fs_true[inds_LL], c='b', s=s, label='LL') else: ax[i].scatter(Fa_pred[inds_H], Fs_pred[inds_H], c='r', s=s, label='H') ax[i].scatter(Fa_pred[inds_L], Fs_pred[inds_L], c='g', s=s, label='L') ax[i].scatter(Fa_pred[inds_LL], Fs_pred[inds_LL], c='b', s=s, label='LL') ax[i].errorbar(Fa_pred[inds_H], Fs_pred[inds_H], xerr=error_Fa, yerr=error_Fs, c='r', fmt='o') ax[i].errorbar(Fa_pred[inds_L], Fs_pred[inds_L], xerr=error_Fa, yerr=error_Fs, c='g', fmt='o') ax[i].errorbar(Fa_pred[inds_LL], Fs_pred[inds_LL], xerr=error_Fa, yerr=error_Fs, c='b', fmt='o') ax[i].set_xlabel('Fa') if i == 0: ax[i].set_ylabel('Fs') ax[i].set_title('ordinary chondrites') else: ax[i].set_title('predictions') ax[i].set_yticklabels([]) ax[i].tick_params(axis='both') ax[i].axis('square') ax[i].set_xticks(np.arange(limx1, limx2 + 0.1, 5)) ax[i].set_yticks(np.arange(limy1, limy2 + 0.1, 5)) ax[i].set_ylim(bottom=limy1 - shift, top=limy2 + shift) ax[i].set_xlim(left=limx1 - shift, right=limx2 + shift) # add the patches ax[i].add_patch(H_rect) ax[i].add_patch(L_rect) ax[i].add_patch(LL_rect) ax[i].legend() Fa_S, Fs_S = [20.7], [18.3] Fa_Sq, Fs_Sq = [23.2], [21.0] Fa_Sr, Fs_Sr = [18.3], [19.2] Fa_Sw, Fs_Sw = [21.3], [14.7] Fa_Q, Fs_Q = [26.2], [23.8] ax[1].scatter(Fa_S, Fs_S, marker='$S$', c='k', s=s * 2.5) ax[1].scatter(Fa_Sq, Fs_Sq, marker='$Sq$', c='k', s=s * 5) ax[1].scatter(Fa_Sr, Fs_Sr, marker='$Sr$', c='k', s=s * 5) ax[1].scatter(Fa_Sw, Fs_Sw, marker='$Sw$', c='k', s=s * 6) ax[1].scatter(Fa_Q, Fs_Q, marker='$Q$', c='k', s=s * 2.5) plt.draw() plt.tight_layout() fig_name = "".join(('Fa_vs_Fs.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_surface_spectra(y_pred: np.ndarray, filename: str, what_type: str) -> None: # Set is already processed at ray_casting_mean if 'Itokawa' in filename: indices_file = "".join((project_dir, '/Datasets/taxonomy/polysum.h5')) background_image = 'new_itokawa_mosaic.jpg' name = 'Itokawa' elif 'Eros' in filename: indices_file = "".join((project_dir, '/Datasets/taxonomy/polysumeros1000.h5')) background_image = 'eros_cyl_near.jpg' name = 'Eros' else: raise ValueError('"filename" must contain either "Itokawa" or "Eros"') with h5py.File(indices_file, 'r') as f: # Choosing only the spectra, first two indexes contain coordinates # Keeping only the coordinates indices = np.array(f['d'][:, :2]) n, _ = y_pred.shape sum_of_predictions = np.sum(y_pred, axis=0) / n * 100 if what_type == 'taxonomy': n_probable_classes = 3 most_probable_classes = np.argsort(sum_of_predictions)[-n_probable_classes:][::-1] print('\nMost probable classes:') for cls in most_probable_classes: print('{:4s} {:5.2f}%'.format(classes2[cls], round(sum_of_predictions[cls], 2))) titles = ["".join((name, ' spectral ', classes2[most_probable_classes[i]], '-class predictions with confidence')) for i in range(n_probable_classes)] labels = [classes2[most_probable_classes[i]] for i in range(n_probable_classes)] elif what_type == 'mineralogy': most_probable_classes = np.array([0, 3, 5, 9]) # olivine, Fa, Fs_opx, Wo_cpx (possible source of errors...) labels = ['olivine', 'Fa', 'Fs (OPX)', 'Wo (CPX)'] n_probable_classes = len(most_probable_classes) print('\nSelected mineralogy:') for i, cls in enumerate(most_probable_classes): print('{:14s} {:5.2f}%'.format(labels[i], round(sum_of_predictions[cls], 2))) titles = ["".join((name, ' ', labels[i], ' predictions with confidence')) for i in range(n_probable_classes)] else: raise ValueError('"what_type" must be either "taxonomy" or "mineralogy"') # Color code dominant classes / labels probability_values = np.transpose(np.array([y_pred[:, most_probable_classes[i]] for i in range(n_probable_classes)])) for i in range(n_probable_classes): # Plot the coverage map using latitude and longitude from HB img = plt.imread("".join((project_dir, '/Asteroid_images/', background_image))) # Background image fig, ax = plt.subplots(figsize=(30, 25)) ax.imshow(img, cmap="gray", extent=[0, 360, -90, 90], alpha=1) # Draw the predictions map im = ax.scatter(indices[:, 0], indices[:, 1], s=10, c=probability_values[:, i] * 100, marker=',', cmap="viridis_r", vmin=0, vmax=100, alpha=0.4) plt.xlim([0, 360]) plt.ylim([-90, 90]) ax.set_xticks(np.arange(0, 361, 10)) plt.xticks(rotation=90) ax.set_yticks(np.arange(-90, 91, 10)) plt.grid() plt.xlabel('longitude [deg]') # \N{DEGREE SIGN} plt.ylabel('latitude [deg]') plt.title(titles[i]) divider = make_axes_locatable(ax) # cax = divider.append_axes("right", size="5%", pad=0.1) # cbar = plt.colorbar(im, cax=cax) cax = divider.append_axes("bottom", size="10%", pad=1) cbar = plt.colorbar(im, cax=cax, orientation="horizontal") cbar.set_ticks(np.arange(0, 101, 10)) cbar.set_ticklabels(np.arange(0, 101, 10)) plt.draw() fig_name = "".join((name, '_', labels[i].replace(' ', '_'), '.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close('all') def plot_confusion_matrix(y_true: np.ndarray, y_pred: np.ndarray, suf: str = '') -> None: print('Confusion matrix') # upravit podle https://www.frontiersin.org/files/Articles/816268/fspas-09-816268-HTML-r1/image_m/fspas-09-816268-g002.jpg array = confusion_matrix(y_true.argmax(axis=1), y_pred.argmax(axis=1)) ''' sum_cols = np.sum(array, axis=0, keepdims=True) # bude dole array = np.concatenate((array, sum_cols), axis=0) sum_rows = np.sum(array, axis=1, keepdims=True) # bude nahore array = np.concatenate((array, sum_rows), axis=1) ''' sum_rows = np.sum(array, axis=1, keepdims=True) # bude nahore # tady nejak upravit dim dim = np.unique(y_true.argmax(axis=1)) # true values in the confusion matrix # list(range(y_true.shape[1])) df_cm = pd.DataFrame(array / sum_rows, dim, dim) labels = np.array(list(classes.keys()))[dim] # labels = np.concatenate((labels, np.array(['\Sigma']))) fig = plt.figure("Confusion Matrix", figsize=(18, 15)) sns.set(font_scale=1.4) # label size ax = sns.heatmap(df_cm, annot=array, fmt="d", annot_kws={"size": 14}, cmap="Blues", cbar=False) ax.xaxis.tick_top() # x axis on top ax.xaxis.set_label_position('top') ax.tick_params(length=0) ax.tick_params(axis='both') # Plot diagonal line ax.plot([0, np.max(dim) + 1], [0, np.max(dim) + 1], 'k--') ax.set_xticklabels(labels) ax.set_yticklabels(labels) plt.xlabel("Predicted taxonomy") plt.ylabel("Actual taxonomy") """ nx, ny = np.shape(array) for ix in range(nx): for iy in range(ny): ax.text(iy + 0.5, ix + 0.5, int(array[ix, iy]), ha="center", va="center", color="r") """ plt.draw() fig_name = "".join(('confusion_matrix', suf, '.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_corr_matrix(labels: np.ndarray, hp_values: np.ndarray, suf: str) -> None: # pandas corr is NaN tolerant whereas numpy corr is not hp_values = pd.DataFrame(np.transpose(hp_values)) corr_matrix = hp_values.corr().to_numpy() fig, ax = plt.subplots(figsize=(15, 15)) im = ax.matshow(corr_matrix, vmin=-1, vmax=1) plt.xticks(np.arange(0, len(labels), 1.0), rotation=90) plt.yticks(np.arange(0, len(labels), 1.0)) if plt.rcParams['text.usetex']: labels = np.char.replace(labels, '_', '\_') ax.set_xticklabels(labels) ax.set_yticklabels(labels) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) plt.colorbar(im, cax=cax) for ix in range(len(labels)): for iy in range(len(labels)): ax.text(iy, ix, "".join('{:.2f}'.format(corr_matrix[ix, iy])), ha="center", va="center", color="r") plt.draw() plt.tight_layout() fig_name = "".join(('correlation_matrix', suf, '.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_range_histogram(start: np.ndarray, stop: np.ndarray, step: np.ndarray) -> None: print('Range histograms') x_lambda = np.arange(0, 3001, 1) y_lambda = np.zeros(len(x_lambda)) for i in range(len(start)): tmp = np.zeros(y_lambda.shape) tmp[np.where((x_lambda >= start[i]) & (x_lambda <= stop[i]))] = 1 y_lambda += tmp fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 8)) ax1.plot(x_lambda, y_lambda) ax2.hist(step, bins='auto') ax1.set_xlabel('Wavelength [nm]') ax1.set_ylabel('Counts') ax1.tick_params(axis='both') ax1.set_ylim(bottom=0) ax1.set_xlim(left=np.min(x_lambda), right=np.max(x_lambda)) ax1.set_title('Histogram of ranges') ax2.set_xlabel('Wavelength [nm]') ax2.set_xlabel('Wavelength [nm]') ax2.set_ylabel('Counts') ax2.tick_params(axis='both') ax2.set_ylim(bottom=0) ax2.set_xlim(left=0, right=20) ax2.set_title('Histogram of resolution') plt.draw() fig_name = 'hist_range.png' fig.savefig("".join((outdir, '/', fig_name)), format='png', bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_numbers_histogram(fa: np.ndarray, fs: np.ndarray, wo: np.ndarray) -> None: print('Numbers histograms') bins = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(18, 5)) ax1.hist(fa, bins=bins) ax2.hist(fs, bins=bins) ax3.hist(wo, bins=bins) ax1.set_xlabel('Fa') ax2.set_xlabel('Fs') ax3.set_xlabel('Wo') ax1.set_ylabel('Counts') ax1.tick_params(axis='both') ax2.tick_params(axis='both') ax3.tick_params(axis='both') ax1.set_xlim(left=0, right=1) ax2.set_xlim(left=0, right=1) ax3.set_xlim(left=0, right=1) ax1.set_title('Histogram of Fa') ax2.set_title('Histogram of Fs') ax3.set_title('Histogram of Wo') plt.draw() fig_name = 'hist_numbers.png' fig.savefig("".join((outdir, '/', fig_name)), format='png', bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_ast_type_hist(y_pred: np.ndarray) -> None: print('Plot histograms of asteroids compositions') fig_format = 'png' nbins = 10 shift = 3 # Control ylim predictions = y_pred * 100 filename = project_dir + '/Datasets/asteroid_spectra-denoised-norm.dat' data = pd.read_csv(filename, sep='\t', header=None).to_numpy() # to read the file types = data[:, 0] inds_S = np.array(['S' in ast_type for ast_type in types]) inds_Q = np.array(['Q' in ast_type for ast_type in types]) inds_A = np.array(['A' in ast_type for ast_type in types]) inds_V = np.array(['V' in ast_type for ast_type in types]) inds = np.array([inds_S, inds_Q, inds_A, inds_V]) PCA = pd.read_csv(path_taxonomy + 'asteroid_pca-spectra-combined.dat', sep='\t', header=None).to_numpy() color = ['blue', 'magenta', 'brown', 'black'] labels = ['S type', 'Q type', 'A type', 'V type'] # modal first (expect all four minerals are in the model) n_min = 3 fig, ax = plt.subplots(1, n_min, figsize=(6 * (n_min), 5)) # !!!!! labelx = ['Olivine fraction [vol\%]', 'Orthopyroxene fraction [vol\%]', 'Clinopyroxene fraction [vol\%]', 'Plagioclase fraction [vol\%]'] limy = 0 for j in range(n_min): # if j > 1: # !!!!! # continue for i in range(len(inds)): # for i in [0, 1, 3]: # !!!!! for i in range(len(inds)): # if j == 0 and i == 3: # !!!!! # continue # if j == 1 and i == 1: # !!!!! # continue hist, bins = np.histogram(predictions[inds[i, :], j], bins=nbins, range=(0, 100)) ax[j].bar(bins[:-1] + (bins[1] - bins[0]) / 2, hist.astype(np.float32) / hist.sum() * 100, width=(bins[1] - bins[0]), fill=False, edgecolor=color[i], label=labels[i], linewidth=2) if np.max(hist.astype(np.float32) / hist.sum() * 100) > limy: limy = np.max(hist.astype(np.float32) / hist.sum() * 100) if j > 0: ax[j].set_yticklabels([]) else: ax[j].set_ylabel('Normalised counts [\%]') ax[j].set_xlabel(labelx[j]) ax[j].legend(loc='upper left') # must be done after the first loop to get limy limy = np.min((100, np.round(limy))) + shift for j in range(n_min): # if j > 1: # !!!!! # continue ax[j].set_ylim(bottom=0, top=limy) fig.tight_layout() # otherwise the right y-label is slightly clipped plt.draw() fig_name = "".join(('ast_type_hist_modal.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) # OL n_ol = 2 fig, ax = plt.subplots(1, n_ol, figsize=(6 * n_ol, 5)) labelx = ['Fa', 'Fo'] limy = 0 for j in range(n_ol): for i in range(len(inds)): hist, bins = np.histogram(predictions[inds[i, :], n_min + j], bins=nbins, range=(0, 100)) ax[j].bar(bins[:-1] + (bins[1] - bins[0]) / 2, hist.astype(np.float32) / hist.sum() * 100, width=(bins[1] - bins[0]), fill=False, edgecolor=color[i], label=labels[i], linewidth=2) if np.max(hist.astype(np.float32) / hist.sum() * 100) > limy: limy = np.max(hist.astype(np.float32) / hist.sum() * 100) if j > 0: ax[j].set_yticklabels([]) else: ax[j].set_ylabel('Normalised counts [\%]') ax[j].set_xlabel(labelx[j]) ax[j].legend(loc='upper left') # must be done after the first loop to get limy limy = np.min((100, np.round(limy))) + shift for j in range(n_ol): ax[j].set_ylim(bottom=0, top=limy) fig.tight_layout() # otherwise the right y-label is slightly clipped plt.draw() fig_name = "".join(('ast_type_hist_ol.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) # OPX n_opx = 2 fig, ax = plt.subplots(1, n_opx, figsize=(6 * n_opx, 5)) labelx = ['Fs', 'En'] limy = 0 for j in range(n_opx): for i in range(len(inds)): hist, bins = np.histogram(predictions[inds[i, :], n_min + n_ol + j], bins=nbins, range=(0, 100)) ax[j].bar(bins[:-1] + (bins[1] - bins[0]) / 2, hist.astype(np.float32) / hist.sum() * 100, width=(bins[1] - bins[0]), fill=False, edgecolor=color[i], label=labels[i], linewidth=2) if np.max(hist.astype(np.float32) / hist.sum() * 100) > limy: limy = np.max(hist.astype(np.float32) / hist.sum() * 100) if j > 0: ax[j].set_yticklabels([]) else: ax[j].set_ylabel('Normalised counts [\%]') ax[j].set_xlabel(labelx[j]) ax[j].legend(loc='upper left') # must be done after the first loop to get limy limy = np.min((100, np.round(limy))) + shift for j in range(n_opx): ax[j].set_ylim(bottom=0, top=limy) fig.tight_layout() # otherwise the right y-label is slightly clipped plt.draw() fig_name = "".join(('ast_type_hist_opx.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) # CPX n_cpx = 3 fig, ax = plt.subplots(1, n_cpx, figsize=(6 * n_cpx, 5)) labelx = ['Fs', 'En', 'Wo'] limy = 0 for j in range(n_cpx): for i in range(len(inds)): hist, bins = np.histogram(predictions[inds[i, :], n_min + n_ol + n_opx + j], bins=nbins, range=(0, 100)) ax[j].bar(bins[:-1] + (bins[1] - bins[0]) / 2, hist.astype(np.float32) / hist.sum() * 100, width=(bins[1] - bins[0]), fill=False, edgecolor=color[i], label=labels[i], linewidth=2) if np.max(hist.astype(np.float32) / hist.sum() * 100) > limy: limy = np.max(hist.astype(np.float32) / hist.sum() * 100) if j > 0: ax[j].set_yticklabels([]) else: ax[j].set_ylabel('Normalised counts [\%]') ax[j].set_xlabel(labelx[j]) ax[j].legend(loc='upper left') # must be done after the first loop to get limy limy = np.min((100, np.round(limy))) + shift for j in range(n_cpx): ax[j].set_ylim(bottom=0, top=limy) fig.tight_layout() # otherwise the right y-label is slightly clipped plt.draw() fig_name = "".join(('ast_type_hist_cpx.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig) def plot_Tomas_mixtures() -> None: x, spectra_msm, spectra_syn, C = resave_Tomas_OL_OPX_mixtures() colours = ['k', 'r', 'b', 'g', 'c', 'm', 'y', 'k', 'r', 'b', 'g', 'c', 'm', 'y'] fig, ax = plt.subplots(1, 1, figsize=(6, 3.5)) for i in range(len(C)): ax.plot(x, spectra_msm[:, i], colours[i], label=C[i]) ax.plot(x, spectra_syn[:, i], colours[i] + '--') ax.set_ylabel('Reflectance') ax.set_xlabel('$\lambda$ [nm]') ax.set_ylim(bottom=0.2, top=0.8) ax.tick_params(axis='both') ax.set_xlim(left=400, right=2500) # ax.legend(loc='upper right') plt.draw() plt.tight_layout() fig_name = 'spectra_mixtures_Tomas.png' fig.savefig("".join((outdir, '/', fig_name)), format='png', bbox_inches='tight', pad_inches=0.05) plt.close() def plot_OC_distance(y_pred: np.ndarray): print('plot distance of OC predictions from the corresponding box') fig_format = 'png' # Indices in which Fa and Fs are ind_Fa, ind_Fs = num_minerals, num_minerals + subtypes[0] filename = project_dir + '/Datasets/combined-denoised-norm-clean-meta.dat' data = pd.read_csv(filename, sep='\t', header=None).to_numpy() # to read the file types = data[:, 7] types = np.reshape(types, (len(types), 1)) # to get the test types filename_train_data = 'combined-denoised-norm-clean.dat' x_train, y_train = load_data(filename_train_data) x_train, y_train, x_val, y_val, x_test, y_test = split_data_proportional( np.concatenate((x_train, types), axis=1), y_train) types = x_test[:, -1].astype(np.str) Fa_pred, Fs_pred = y_pred[:, ind_Fa] * 100, y_pred[:, ind_Fs] * 100 inds_H = np.array([('H' in OC_type) and ('HH' not in OC_type) if len(OC_type) == 2 else False for OC_type in types]) inds_L = np.array([('L' in OC_type) and ('LL' not in OC_type) if len(OC_type) == 2 else False for OC_type in types]) inds_LL = np.array(['LL' in OC_type if len(OC_type) == 3 else False for OC_type in types]) # https://www.researchgate.net/figure/Mineral-compositional-data-for-the-Morokweng-meteoriteDiagram-shows-ferrosilite-Fs_fig3_7093505 rect_H = np.array([[16.2, 16.2 + 3.8], [14.5, 14.5 + 3.5]]) rect_L = np.array([[22, 22 + 4], [19, 19 + 3]]) rect_LL = np.array([[26, 26 + 6], [22, 22 + 4.2]]) p_H = np.array([Fa_pred[inds_H], Fs_pred[inds_H]]) p_L = np.array([Fa_pred[inds_L], Fs_pred[inds_L]]) p_LL = np.array([Fa_pred[inds_LL], Fs_pred[inds_LL]]) distance_H = np.array([distance(rect_H, p_H), distance(rect_L, p_H), distance(rect_LL, p_H)]) distance_L = np.array([distance(rect_H, p_L), distance(rect_L, p_L), distance(rect_LL, p_L)]) distance_LL = np.array([distance(rect_H, p_LL), distance(rect_L, p_LL), distance(rect_LL, p_LL)]) s = 30 # scaling parameter (marker size) fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111) ax.scatter(distance_H, np.tile(np.array([[0, 1, 2]]).transpose(), (1, np.shape(distance_H)[1])), color='r', label='H', s=s) ax.scatter(distance_L, np.tile(np.array([[0, 1, 2]]).transpose(), (1, np.shape(distance_L)[1])), color='g', label='L', s=s) ax.scatter(distance_LL, np.tile(np.array([[0, 1, 2]]).transpose(), (1, np.shape(distance_LL)[1])), color='b', label='LL', s=s) ax.set_xlabel('Distance') ax.set_ylabel('Type') ax.set_yticks([0, 1, 2]) ax.set_yticklabels(['H', 'L', 'LL']) ax.legend(loc='center right') fig.tight_layout() # otherwise the right y-label is slightly clipped plt.draw() fig_name = "".join(('OC_box_dist.', fig_format)) fig.savefig("".join((outdir, '/', fig_name)), format=fig_format, bbox_inches='tight', pad_inches=0.05) plt.close(fig)
[ "matplotlib.pyplot.title", "numpy.sum", "seaborn.heatmap", "modules.NN_losses_metrics_activations.my_rmse", "pandas.read_csv", "modules.NN_losses_metrics_activations.my_quantile", "modules.NN_losses_metrics_activations.my_sam", "numpy.ones", "numpy.shape", "numpy.argsort", "matplotlib.pyplot.figure", "numpy.histogram", "numpy.arange", "numpy.convolve", "matplotlib.pyplot.tight_layout", "numpy.round", "numpy.unique", "pandas.DataFrame", "modules.BAR_BC_method.filter_data_mask", "matplotlib.patches.Rectangle", "matplotlib.pyplot.close", "numpy.transpose", "modules.BAR_BC_method.calc_composition", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.draw", "numpy.max", "matplotlib.pyplot.rc", "numpy.loadtxt", "numpy.reshape", "matplotlib.pyplot.xticks", "matplotlib.pyplot.subplots", "seaborn.set", "numpy.core.defchararray.add", "h5py.File", "matplotlib.pyplot.ylim", "matplotlib.pyplot.text", "numpy.char.replace", "matplotlib.use", "numpy.min", "matplotlib.pyplot.ylabel", "modules.collect_data.resave_Tomas_OL_OPX_mixtures", "matplotlib.pyplot.grid", "numpy.concatenate", "mpl_toolkits.axes_grid1.make_axes_locatable", "modules.BAR_BC_method.calc_BAR_BC", "matplotlib.pyplot.xlim", "numpy.logical_and", "modules.NN_config_taxonomy.classes.keys", "modules.NN_losses_metrics_activations.my_r2", "modules.NN_evaluate.evaluate_test_data", "numpy.zeros", "numpy.unravel_index", "modules.NN_evaluate.evaluate", "numpy.where", "numpy.array", "numpy.logical_or", "matplotlib.pyplot.xlabel", "numpy.sqrt" ]
[((766, 782), 'matplotlib.use', 'mpl.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (773, 782), True, 'import matplotlib as mpl\n'), ((858, 888), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': 'TEXT_SIZE'}), "('font', size=TEXT_SIZE)\n", (864, 888), True, 'import matplotlib.pyplot as plt\n'), ((920, 957), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'titlesize': 'BIGGER_SIZE'}), "('axes', titlesize=BIGGER_SIZE)\n", (926, 957), True, 'import matplotlib.pyplot as plt\n'), ((988, 1025), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'labelsize': 'MEDIUM_SIZE'}), "('axes', labelsize=MEDIUM_SIZE)\n", (994, 1025), True, 'import matplotlib.pyplot as plt\n'), ((1060, 1097), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'labelsize': 'SMALL_SIZE'}), "('xtick', labelsize=SMALL_SIZE)\n", (1066, 1097), True, 'import matplotlib.pyplot as plt\n'), ((1129, 1166), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'labelsize': 'SMALL_SIZE'}), "('ytick', labelsize=SMALL_SIZE)\n", (1135, 1166), True, 'import matplotlib.pyplot as plt\n'), ((1198, 1235), 'matplotlib.pyplot.rc', 'plt.rc', (['"""legend"""'], {'fontsize': 'SMALL_SIZE'}), "('legend', fontsize=SMALL_SIZE)\n", (1204, 1235), True, 'import matplotlib.pyplot as plt\n'), ((1255, 1294), 'matplotlib.pyplot.rc', 'plt.rc', (['"""figure"""'], {'titlesize': 'BIGGER_SIZE'}), "('figure', titlesize=BIGGER_SIZE)\n", (1261, 1294), True, 'import matplotlib.pyplot as plt\n'), ((1365, 1392), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (1371, 1392), True, 'import matplotlib.pyplot as plt\n'), ((1457, 1524), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {}), "('font', **{'family': 'sans-serif', 'sans-serif': ['Arial']})\n", (1463, 1524), True, 'import matplotlib.pyplot as plt\n'), ((2497, 2517), 'numpy.arange', 'np.arange', (['(-150)', '(151)'], {}), '(-150, 151)\n', (2506, 2517), True, 'import numpy as np\n'), ((8944, 8964), 'numpy.arange', 'np.arange', (['(-150)', '(151)'], {}), '(-150, 151)\n', (8953, 8964), True, 'import numpy as np\n'), ((9105, 9125), 'numpy.arange', 'np.arange', (['(0)', '(101)', '(5)'], {}), '(0, 101, 5)\n', (9114, 9125), True, 'import numpy as np\n'), ((10216, 10250), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(8, 6)'}), '(1, 1, figsize=(8, 6))\n', (10228, 10250), True, 'import matplotlib.pyplot as plt\n'), ((10918, 10928), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (10926, 10928), True, 'import matplotlib.pyplot as plt\n'), ((10933, 10951), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (10949, 10951), True, 'import matplotlib.pyplot as plt\n'), ((11129, 11143), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (11138, 11143), True, 'import matplotlib.pyplot as plt\n'), ((11469, 11520), 'numpy.array', 'np.array', (["[('S' in ast_type) for ast_type in types]"], {}), "([('S' in ast_type) for ast_type in types])\n", (11477, 11520), True, 'import numpy as np\n'), ((11532, 11583), 'numpy.array', 'np.array', (["[('Q' in ast_type) for ast_type in types]"], {}), "([('Q' in ast_type) for ast_type in types])\n", (11540, 11583), True, 'import numpy as np\n'), ((11595, 11646), 'numpy.array', 'np.array', (["[('A' in ast_type) for ast_type in types]"], {}), "([('A' in ast_type) for ast_type in types])\n", (11603, 11646), True, 'import numpy as np\n'), ((11658, 11709), 'numpy.array', 'np.array', (["[('V' in ast_type) for ast_type in types]"], {}), "([('V' in ast_type) for ast_type in types])\n", (11666, 11709), True, 'import numpy as np\n'), ((11860, 11902), 'numpy.unique', 'np.unique', (['types[inds]'], {'return_counts': '(True)'}), '(types[inds], return_counts=True)\n', (11869, 11902), True, 'import numpy as np\n'), ((12148, 12190), 'numpy.core.defchararray.add', 'np.core.defchararray.add', (['"""$"""', 'types[inds]'], {}), "('$', types[inds])\n", (12172, 12190), True, 'import numpy as np\n'), ((12204, 12241), 'numpy.core.defchararray.add', 'np.core.defchararray.add', (['labels', '"""$"""'], {}), "(labels, '$')\n", (12228, 12241), True, 'import numpy as np\n'), ((12257, 12291), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(8, 6)'}), '(1, 1, figsize=(8, 6))\n', (12269, 12291), True, 'import matplotlib.pyplot as plt\n'), ((12954, 13046), 'matplotlib.pyplot.text', 'plt.text', ([], {'x': '(0.1)', 'y': '(-0.2)', 's': '"""Space weathering"""', 'rotation': '(-51)', 'c': '"""r"""', 'fontsize': 'SMALL_SIZE'}), "(x=0.1, y=-0.2, s='Space weathering', rotation=-51, c='r', fontsize\n =SMALL_SIZE)\n", (12962, 13046), True, 'import matplotlib.pyplot as plt\n'), ((13057, 13080), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (13076, 13080), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((13151, 13183), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['sp'], {'ax': 'ax', 'cax': 'cax'}), '(sp, ax=ax, cax=cax)\n', (13163, 13183), True, 'import matplotlib.pyplot as plt\n'), ((13314, 13324), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (13322, 13324), True, 'import matplotlib.pyplot as plt\n'), ((13487, 13501), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (13496, 13501), True, 'import matplotlib.pyplot as plt\n'), ((13709, 13743), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(5, 5)'}), '(1, 1, figsize=(5, 5))\n', (13721, 13743), True, 'import matplotlib.pyplot as plt\n'), ((13971, 14064), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(16.2, 14.5)', '(3.8)', '(3.5)'], {'linewidth': '(1.5)', 'edgecolor': '"""r"""', 'facecolor': '"""none"""'}), "((16.2, 14.5), 3.8, 3.5, linewidth=1.5, edgecolor='r',\n facecolor='none')\n", (13988, 14064), True, 'import matplotlib.patches as patches\n'), ((14074, 14167), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(22.0, 19.0)', '(4.0)', '(3.0)'], {'linewidth': '(1.5)', 'edgecolor': '"""g"""', 'facecolor': '"""none"""'}), "((22.0, 19.0), 4.0, 3.0, linewidth=1.5, edgecolor='g',\n facecolor='none')\n", (14091, 14167), True, 'import matplotlib.patches as patches\n'), ((14178, 14271), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(26.0, 22.0)', '(6.0)', '(4.2)'], {'linewidth': '(1.5)', 'edgecolor': '"""b"""', 'facecolor': '"""none"""'}), "((26.0, 22.0), 6.0, 4.2, linewidth=1.5, edgecolor='b',\n facecolor='none')\n", (14195, 14271), True, 'import matplotlib.patches as patches\n'), ((16062, 16072), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (16070, 16072), True, 'import matplotlib.pyplot as plt\n'), ((16077, 16095), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (16093, 16095), True, 'import matplotlib.pyplot as plt\n'), ((16258, 16272), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (16267, 16272), True, 'import matplotlib.pyplot as plt\n'), ((16366, 16389), 'numpy.arange', 'np.arange', (['(450)', '(2451)', '(5)'], {}), '(450, 2451, 5)\n', (16375, 16389), True, 'import numpy as np\n'), ((16708, 16755), 'modules.NN_evaluate.evaluate_test_data', 'evaluate_test_data', (['model_names', 'x_test', 'y_true'], {}), '(model_names, x_test, y_true)\n', (16726, 16755), False, 'from modules.NN_evaluate import evaluate_test_data\n'), ((17460, 17489), 'numpy.sum', 'np.sum', (['(binary * base)'], {'axis': '(1)'}), '(binary * base, axis=1)\n', (17466, 17489), True, 'import numpy as np\n'), ((17503, 17548), 'numpy.logical_or', 'np.logical_or', (['(mixtures == 12)', '(mixtures == 14)'], {}), '(mixtures == 12, mixtures == 14)\n', (17516, 17548), True, 'import numpy as np\n'), ((17623, 17651), 'numpy.logical_and', 'np.logical_and', (['mask1', 'mask2'], {}), '(mask1, mask2)\n', (17637, 17651), True, 'import numpy as np\n'), ((17771, 17816), 'numpy.array', 'np.array', (["[('HED' in type) for type in types]"], {}), "([('HED' in type) for type in types])\n", (17779, 17816), True, 'import numpy as np\n'), ((17890, 17914), 'modules.BAR_BC_method.calc_BAR_BC', 'calc_BAR_BC', (['wvl', 'x_true'], {}), '(wvl, x_true)\n', (17901, 17914), False, 'from modules.BAR_BC_method import calc_BAR_BC, calc_composition, filter_data_mask\n'), ((18253, 18302), 'modules.BAR_BC_method.calc_composition', 'calc_composition', (['BAR', 'BIC', 'BIIC', 'types'], {'method': '(0)'}), '(BAR, BIC, BIIC, types, method=0)\n', (18269, 18302), False, 'from modules.BAR_BC_method import calc_BAR_BC, calc_composition, filter_data_mask\n'), ((18321, 18370), 'modules.BAR_BC_method.calc_composition', 'calc_composition', (['BAR', 'BIC', 'BIIC', 'types'], {'method': '(1)'}), '(BAR, BIC, BIIC, types, method=1)\n', (18337, 18370), False, 'from modules.BAR_BC_method import calc_BAR_BC, calc_composition, filter_data_mask\n'), ((18405, 18442), 'modules.BAR_BC_method.filter_data_mask', 'filter_data_mask', (['OL_fraction', 'Fs', 'Wo'], {}), '(OL_fraction, Fs, Wo)\n', (18421, 18442), False, 'from modules.BAR_BC_method import calc_BAR_BC, calc_composition, filter_data_mask\n'), ((18718, 18738), 'numpy.arange', 'np.arange', (['(-150)', '(151)'], {}), '(-150, 151)\n', (18727, 18738), True, 'import numpy as np\n'), ((19127, 19173), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(4.4 * 2 + 1.5, 6)'}), '(1, 2, figsize=(4.4 * 2 + 1.5, 6))\n', (19139, 19173), True, 'import matplotlib.pyplot as plt\n'), ((20389, 20399), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (20397, 20399), True, 'import matplotlib.pyplot as plt\n'), ((20404, 20422), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (20420, 20422), True, 'import matplotlib.pyplot as plt\n'), ((20607, 20621), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (20616, 20621), True, 'import matplotlib.pyplot as plt\n'), ((20770, 20793), 'numpy.arange', 'np.arange', (['(450)', '(2451)', '(5)'], {}), '(450, 2451, 5)\n', (20779, 20793), True, 'import numpy as np\n'), ((20939, 20976), 'numpy.loadtxt', 'np.loadtxt', (['data_file'], {'delimiter': '"""\t"""'}), "(data_file, delimiter='\\t')\n", (20949, 20976), True, 'import numpy as np\n'), ((20992, 21028), 'modules.NN_evaluate.evaluate', 'evaluate', (['model_names', 'filename_data'], {}), '(model_names, filename_data)\n', (21000, 21028), False, 'from modules.NN_evaluate import evaluate\n'), ((21259, 21310), 'numpy.array', 'np.array', (["[('S' in ast_type) for ast_type in types]"], {}), "([('S' in ast_type) for ast_type in types])\n", (21267, 21310), True, 'import numpy as np\n'), ((21322, 21373), 'numpy.array', 'np.array', (["[('Q' in ast_type) for ast_type in types]"], {}), "([('Q' in ast_type) for ast_type in types])\n", (21330, 21373), True, 'import numpy as np\n'), ((21385, 21436), 'numpy.array', 'np.array', (["[('A' in ast_type) for ast_type in types]"], {}), "([('A' in ast_type) for ast_type in types])\n", (21393, 21436), True, 'import numpy as np\n'), ((21448, 21499), 'numpy.array', 'np.array', (["[('V' in ast_type) for ast_type in types]"], {}), "([('V' in ast_type) for ast_type in types])\n", (21456, 21499), True, 'import numpy as np\n'), ((21764, 21800), 'numpy.core.defchararray.add', 'np.core.defchararray.add', (['"""$"""', 'types'], {}), "('$', types)\n", (21788, 21800), True, 'import numpy as np\n'), ((21814, 21851), 'numpy.core.defchararray.add', 'np.core.defchararray.add', (['labels', '"""$"""'], {}), "(labels, '$')\n", (21838, 21851), True, 'import numpy as np\n'), ((21874, 21898), 'modules.BAR_BC_method.calc_BAR_BC', 'calc_BAR_BC', (['wvl', 'x_data'], {}), '(wvl, x_data)\n', (21885, 21898), False, 'from modules.BAR_BC_method import calc_BAR_BC, calc_composition, filter_data_mask\n'), ((22211, 22260), 'modules.BAR_BC_method.calc_composition', 'calc_composition', (['BAR', 'BIC', 'BIIC', 'types'], {'method': '(0)'}), '(BAR, BIC, BIIC, types, method=0)\n', (22227, 22260), False, 'from modules.BAR_BC_method import calc_BAR_BC, calc_composition, filter_data_mask\n'), ((22279, 22328), 'modules.BAR_BC_method.calc_composition', 'calc_composition', (['BAR', 'BIC', 'BIIC', 'types'], {'method': '(1)'}), '(BAR, BIC, BIIC, types, method=1)\n', (22295, 22328), False, 'from modules.BAR_BC_method import calc_BAR_BC, calc_composition, filter_data_mask\n'), ((22363, 22400), 'modules.BAR_BC_method.filter_data_mask', 'filter_data_mask', (['OL_fraction', 'Fs', 'Wo'], {}), '(OL_fraction, Fs, Wo)\n', (22379, 22400), False, 'from modules.BAR_BC_method import calc_BAR_BC, calc_composition, filter_data_mask\n'), ((22617, 22653), 'numpy.unique', 'np.unique', (['types'], {'return_counts': '(True)'}), '(types, return_counts=True)\n', (22626, 22653), True, 'import numpy as np\n'), ((22817, 22851), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(8, 6)'}), '(1, 1, figsize=(8, 6))\n', (22829, 22851), True, 'import matplotlib.pyplot as plt\n'), ((23511, 23597), 'matplotlib.pyplot.text', 'plt.text', ([], {'x': '(0.16)', 'y': '(-0.2)', 's': '"""Space weathering"""', 'rotation': '(-59.5)', 'c': '"""r"""', 'fontsize': '(16)'}), "(x=0.16, y=-0.2, s='Space weathering', rotation=-59.5, c='r',\n fontsize=16)\n", (23519, 23597), True, 'import matplotlib.pyplot as plt\n'), ((23609, 23632), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (23628, 23632), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((23703, 23735), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['sp'], {'ax': 'ax', 'cax': 'cax'}), '(sp, ax=ax, cax=cax)\n', (23715, 23735), True, 'import matplotlib.pyplot as plt\n'), ((23866, 23876), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (23874, 23876), True, 'import matplotlib.pyplot as plt\n'), ((24046, 24060), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (24055, 24060), True, 'import matplotlib.pyplot as plt\n'), ((24543, 24594), 'numpy.array', 'np.array', (["[('S' in ast_type) for ast_type in types]"], {}), "([('S' in ast_type) for ast_type in types])\n", (24551, 24594), True, 'import numpy as np\n'), ((24606, 24657), 'numpy.array', 'np.array', (["[('Q' in ast_type) for ast_type in types]"], {}), "([('Q' in ast_type) for ast_type in types])\n", (24614, 24657), True, 'import numpy as np\n'), ((24669, 24720), 'numpy.array', 'np.array', (["[('A' in ast_type) for ast_type in types]"], {}), "([('A' in ast_type) for ast_type in types])\n", (24677, 24720), True, 'import numpy as np\n'), ((24732, 24783), 'numpy.array', 'np.array', (["[('V' in ast_type) for ast_type in types]"], {}), "([('V' in ast_type) for ast_type in types])\n", (24740, 24783), True, 'import numpy as np\n'), ((25120, 25166), 'matplotlib.pyplot.subplots', 'plt.subplots', (['m', 'n'], {'figsize': '(4.7 * n, 4.7 * m)'}), '(m, n, figsize=(4.7 * n, 4.7 * m))\n', (25132, 25166), True, 'import matplotlib.pyplot as plt\n'), ((25177, 25199), 'numpy.reshape', 'np.reshape', (['ax', '(m, n)'], {}), '(ax, (m, n))\n', (25187, 25199), True, 'import numpy as np\n'), ((26262, 26272), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (26270, 26272), True, 'import matplotlib.pyplot as plt\n'), ((26277, 26295), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (26293, 26295), True, 'import matplotlib.pyplot as plt\n'), ((26461, 26472), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (26470, 26472), True, 'import matplotlib.pyplot as plt\n'), ((26665, 26689), 'numpy.ones', 'np.ones', (['(kernel_width,)'], {}), '((kernel_width,))\n', (26672, 26689), True, 'import numpy as np\n'), ((26709, 26728), 'numpy.sum', 'np.sum', (['conv_kernel'], {}), '(conv_kernel)\n', (26715, 26728), True, 'import numpy as np\n'), ((26740, 26787), 'matplotlib.pyplot.figure', 'plt.figure', (['"""Loss and accuracy"""'], {'figsize': '(8, 6)'}), "('Loss and accuracy', figsize=(8, 6))\n", (26750, 26787), True, 'import matplotlib.pyplot as plt\n'), ((29077, 29087), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (29085, 29087), True, 'import matplotlib.pyplot as plt\n'), ((29446, 29460), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (29455, 29460), True, 'import matplotlib.pyplot as plt\n'), ((30840, 30880), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(4.5 * 2, 6)'}), '(1, 2, figsize=(4.5 * 2, 6))\n', (30852, 30880), True, 'import matplotlib.pyplot as plt\n'), ((33528, 33538), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (33536, 33538), True, 'import matplotlib.pyplot as plt\n'), ((33543, 33561), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (33559, 33561), True, 'import matplotlib.pyplot as plt\n'), ((33724, 33738), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (33733, 33738), True, 'import matplotlib.pyplot as plt\n'), ((37583, 37599), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (37592, 37599), True, 'import matplotlib.pyplot as plt\n'), ((38198, 38234), 'numpy.sum', 'np.sum', (['array'], {'axis': '(1)', 'keepdims': '(True)'}), '(array, axis=1, keepdims=True)\n', (38204, 38234), True, 'import numpy as np\n'), ((38406, 38446), 'pandas.DataFrame', 'pd.DataFrame', (['(array / sum_rows)', 'dim', 'dim'], {}), '(array / sum_rows, dim, dim)\n', (38418, 38446), True, 'import pandas as pd\n'), ((38571, 38619), 'matplotlib.pyplot.figure', 'plt.figure', (['"""Confusion Matrix"""'], {'figsize': '(18, 15)'}), "('Confusion Matrix', figsize=(18, 15))\n", (38581, 38619), True, 'import matplotlib.pyplot as plt\n'), ((38624, 38647), 'seaborn.set', 'sns.set', ([], {'font_scale': '(1.4)'}), '(font_scale=1.4)\n', (38631, 38647), True, 'import seaborn as sns\n'), ((38671, 38766), 'seaborn.heatmap', 'sns.heatmap', (['df_cm'], {'annot': 'array', 'fmt': '"""d"""', 'annot_kws': "{'size': 14}", 'cmap': '"""Blues"""', 'cbar': '(False)'}), "(df_cm, annot=array, fmt='d', annot_kws={'size': 14}, cmap=\n 'Blues', cbar=False)\n", (38682, 38766), True, 'import seaborn as sns\n'), ((39061, 39093), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Predicted taxonomy"""'], {}), "('Predicted taxonomy')\n", (39071, 39093), True, 'import matplotlib.pyplot as plt\n'), ((39098, 39127), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Actual taxonomy"""'], {}), "('Actual taxonomy')\n", (39108, 39127), True, 'import matplotlib.pyplot as plt\n'), ((39330, 39340), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (39338, 39340), True, 'import matplotlib.pyplot as plt\n'), ((39520, 39534), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (39529, 39534), True, 'import matplotlib.pyplot as plt\n'), ((39795, 39825), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(15, 15)'}), '(figsize=(15, 15))\n', (39807, 39825), True, 'import matplotlib.pyplot as plt\n'), ((40150, 40173), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (40169, 40173), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((40237, 40262), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'cax': 'cax'}), '(im, cax=cax)\n', (40249, 40262), True, 'import matplotlib.pyplot as plt\n'), ((40453, 40463), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (40461, 40463), True, 'import matplotlib.pyplot as plt\n'), ((40468, 40486), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (40484, 40486), True, 'import matplotlib.pyplot as plt\n'), ((40668, 40682), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (40677, 40682), True, 'import matplotlib.pyplot as plt\n'), ((40819, 40840), 'numpy.arange', 'np.arange', (['(0)', '(3001)', '(1)'], {}), '(0, 3001, 1)\n', (40828, 40840), True, 'import numpy as np\n'), ((41073, 41108), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(20, 8)'}), '(1, 2, figsize=(20, 8))\n', (41085, 41108), True, 'import matplotlib.pyplot as plt\n'), ((41659, 41669), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (41667, 41669), True, 'import matplotlib.pyplot as plt\n'), ((41809, 41823), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (41818, 41823), True, 'import matplotlib.pyplot as plt\n'), ((42037, 42072), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '(18, 5)'}), '(1, 3, figsize=(18, 5))\n', (42049, 42072), True, 'import matplotlib.pyplot as plt\n'), ((42583, 42593), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (42591, 42593), True, 'import matplotlib.pyplot as plt\n'), ((42735, 42749), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (42744, 42749), True, 'import matplotlib.pyplot as plt\n'), ((43162, 43213), 'numpy.array', 'np.array', (["[('S' in ast_type) for ast_type in types]"], {}), "([('S' in ast_type) for ast_type in types])\n", (43170, 43213), True, 'import numpy as np\n'), ((43225, 43276), 'numpy.array', 'np.array', (["[('Q' in ast_type) for ast_type in types]"], {}), "([('Q' in ast_type) for ast_type in types])\n", (43233, 43276), True, 'import numpy as np\n'), ((43288, 43339), 'numpy.array', 'np.array', (["[('A' in ast_type) for ast_type in types]"], {}), "([('A' in ast_type) for ast_type in types])\n", (43296, 43339), True, 'import numpy as np\n'), ((43351, 43402), 'numpy.array', 'np.array', (["[('V' in ast_type) for ast_type in types]"], {}), "([('V' in ast_type) for ast_type in types])\n", (43359, 43402), True, 'import numpy as np\n'), ((43412, 43454), 'numpy.array', 'np.array', (['[inds_S, inds_Q, inds_A, inds_V]'], {}), '([inds_S, inds_Q, inds_A, inds_V])\n', (43420, 43454), True, 'import numpy as np\n'), ((43761, 43807), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', 'n_min'], {'figsize': '(6 * n_min, 5)'}), '(1, n_min, figsize=(6 * n_min, 5))\n', (43773, 43807), True, 'import matplotlib.pyplot as plt\n'), ((45292, 45302), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (45300, 45302), True, 'import matplotlib.pyplot as plt\n'), ((45476, 45490), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (45485, 45490), True, 'import matplotlib.pyplot as plt\n'), ((45528, 45572), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', 'n_ol'], {'figsize': '(6 * n_ol, 5)'}), '(1, n_ol, figsize=(6 * n_ol, 5))\n', (45540, 45572), True, 'import matplotlib.pyplot as plt\n'), ((46594, 46604), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (46602, 46604), True, 'import matplotlib.pyplot as plt\n'), ((46775, 46789), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (46784, 46789), True, 'import matplotlib.pyplot as plt\n'), ((46829, 46875), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', 'n_opx'], {'figsize': '(6 * n_opx, 5)'}), '(1, n_opx, figsize=(6 * n_opx, 5))\n', (46841, 46875), True, 'import matplotlib.pyplot as plt\n'), ((47906, 47916), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (47914, 47916), True, 'import matplotlib.pyplot as plt\n'), ((48088, 48102), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (48097, 48102), True, 'import matplotlib.pyplot as plt\n'), ((48142, 48188), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', 'n_cpx'], {'figsize': '(6 * n_cpx, 5)'}), '(1, n_cpx, figsize=(6 * n_cpx, 5))\n', (48154, 48188), True, 'import matplotlib.pyplot as plt\n'), ((49233, 49243), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (49241, 49243), True, 'import matplotlib.pyplot as plt\n'), ((49415, 49429), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (49424, 49429), True, 'import matplotlib.pyplot as plt\n'), ((49504, 49534), 'modules.collect_data.resave_Tomas_OL_OPX_mixtures', 'resave_Tomas_OL_OPX_mixtures', ([], {}), '()\n', (49532, 49534), False, 'from modules.collect_data import resave_Tomas_OL_OPX_mixtures\n'), ((49635, 49671), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(6, 3.5)'}), '(1, 1, figsize=(6, 3.5))\n', (49647, 49671), True, 'import matplotlib.pyplot as plt\n'), ((50036, 50046), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (50044, 50046), True, 'import matplotlib.pyplot as plt\n'), ((50051, 50069), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (50067, 50069), True, 'import matplotlib.pyplot as plt\n'), ((50221, 50232), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (50230, 50232), True, 'import matplotlib.pyplot as plt\n'), ((51596, 51646), 'numpy.array', 'np.array', (['[[16.2, 16.2 + 3.8], [14.5, 14.5 + 3.5]]'], {}), '([[16.2, 16.2 + 3.8], [14.5, 14.5 + 3.5]])\n', (51604, 51646), True, 'import numpy as np\n'), ((51660, 51698), 'numpy.array', 'np.array', (['[[22, 22 + 4], [19, 19 + 3]]'], {}), '([[22, 22 + 4], [19, 19 + 3]])\n', (51668, 51698), True, 'import numpy as np\n'), ((51713, 51753), 'numpy.array', 'np.array', (['[[26, 26 + 6], [22, 22 + 4.2]]'], {}), '([[26, 26 + 6], [22, 22 + 4.2]])\n', (51721, 51753), True, 'import numpy as np\n'), ((51765, 51809), 'numpy.array', 'np.array', (['[Fa_pred[inds_H], Fs_pred[inds_H]]'], {}), '([Fa_pred[inds_H], Fs_pred[inds_H]])\n', (51773, 51809), True, 'import numpy as np\n'), ((51820, 51864), 'numpy.array', 'np.array', (['[Fa_pred[inds_L], Fs_pred[inds_L]]'], {}), '([Fa_pred[inds_L], Fs_pred[inds_L]])\n', (51828, 51864), True, 'import numpy as np\n'), ((51876, 51922), 'numpy.array', 'np.array', (['[Fa_pred[inds_LL], Fs_pred[inds_LL]]'], {}), '([Fa_pred[inds_LL], Fs_pred[inds_LL]])\n', (51884, 51922), True, 'import numpy as np\n'), ((52280, 52306), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (52290, 52306), True, 'import matplotlib.pyplot as plt\n'), ((53012, 53022), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (53020, 53022), True, 'import matplotlib.pyplot as plt\n'), ((53188, 53202), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (53197, 53202), True, 'import matplotlib.pyplot as plt\n'), ((3137, 3199), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', 'num_minerals'], {'figsize': '(4.5 * num_minerals, 6)'}), '(1, num_minerals, figsize=(4.5 * num_minerals, 6))\n', (3149, 3199), True, 'import matplotlib.pyplot as plt\n'), ((5223, 5233), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (5231, 5233), True, 'import matplotlib.pyplot as plt\n'), ((5242, 5260), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5258, 5260), True, 'import matplotlib.pyplot as plt\n'), ((5454, 5468), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (5463, 5468), True, 'import matplotlib.pyplot as plt\n'), ((5718, 5784), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', 'subtypes[i]'], {'figsize': '(4.4 * subtypes[i] + 1.5, 6)'}), '(1, subtypes[i], figsize=(4.4 * subtypes[i] + 1.5, 6))\n', (5730, 5784), True, 'import matplotlib.pyplot as plt\n'), ((8542, 8552), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (8550, 8552), True, 'import matplotlib.pyplot as plt\n'), ((8561, 8579), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (8577, 8579), True, 'import matplotlib.pyplot as plt\n'), ((8786, 8800), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (8795, 8800), True, 'import matplotlib.pyplot as plt\n'), ((10789, 10812), 'numpy.arange', 'np.arange', (['(0)', '(100.1)', '(10)'], {}), '(0, 100.1, 10)\n', (10798, 10812), True, 'import numpy as np\n'), ((10832, 10855), 'numpy.arange', 'np.arange', (['(0)', '(100.1)', '(10)'], {}), '(0, 100.1, 10)\n', (10841, 10855), True, 'import numpy as np\n'), ((12765, 12786), 'numpy.array', 'np.array', (['[0.5, -0.5]'], {}), '([0.5, -0.5])\n', (12773, 12786), True, 'import numpy as np\n'), ((12788, 12808), 'numpy.array', 'np.array', (['[0.0, 0.8]'], {}), '([0.0, 0.8])\n', (12796, 12808), True, 'import numpy as np\n'), ((14389, 14421), 'numpy.arange', 'np.arange', (['limx1', '(limx2 + 0.1)', '(5)'], {}), '(limx1, limx2 + 0.1, 5)\n', (14398, 14421), True, 'import numpy as np\n'), ((14441, 14473), 'numpy.arange', 'np.arange', (['limy1', '(limy2 + 0.1)', '(5)'], {}), '(limy1, limy2 + 0.1, 5)\n', (14450, 14473), True, 'import numpy as np\n'), ((17191, 17229), 'numpy.concatenate', 'np.concatenate', (['(x_tmp, types)'], {'axis': '(1)'}), '((x_tmp, types), axis=1)\n', (17205, 17229), True, 'import numpy as np\n'), ((17408, 17430), 'numpy.array', 'np.array', (['[8, 4, 2, 1]'], {}), '([8, 4, 2, 1])\n', (17416, 17430), True, 'import numpy as np\n'), ((17960, 17992), 'numpy.logical_and', 'np.logical_and', (['(BAR > 0)', '(BIC > 0)'], {}), '(BAR > 0, BIC > 0)\n', (17974, 17992), True, 'import numpy as np\n'), ((21944, 21976), 'numpy.logical_and', 'np.logical_and', (['(BAR > 0)', '(BIC > 0)'], {}), '(BAR > 0, BIC > 0)\n', (21958, 21976), True, 'import numpy as np\n'), ((23322, 23343), 'numpy.array', 'np.array', (['[0.5, -0.5]'], {}), '([0.5, -0.5])\n', (23330, 23343), True, 'import numpy as np\n'), ((23345, 23365), 'numpy.array', 'np.array', (['[0.0, 0.8]'], {}), '([0.0, 0.8])\n', (23353, 23365), True, 'import numpy as np\n'), ((24113, 24136), 'numpy.arange', 'np.arange', (['(450)', '(2451)', '(5)'], {}), '(450, 2451, 5)\n', (24122, 24136), True, 'import numpy as np\n'), ((25061, 25098), 'numpy.loadtxt', 'np.loadtxt', (['data_file'], {'delimiter': '"""\t"""'}), "(data_file, delimiter='\\t')\n", (25071, 25098), True, 'import numpy as np\n'), ((25691, 25718), 'numpy.unravel_index', 'np.unravel_index', (['j', '(m, n)'], {}), '(j, (m, n))\n', (25707, 25718), True, 'import numpy as np\n'), ((26988, 27037), 'numpy.convolve', 'np.convolve', (["history['loss']", 'conv_kernel', '"""same"""'], {}), "(history['loss'], conv_kernel, 'same')\n", (26999, 27037), True, 'import numpy as np\n'), ((27380, 27413), 'numpy.char.replace', 'np.char.replace', (['labely', '"""_"""', '""" """'], {}), "(labely, '_', ' ')\n", (27395, 27413), True, 'import numpy as np\n'), ((30124, 30164), 'numpy.concatenate', 'np.concatenate', (['(x_train, types)'], {'axis': '(1)'}), '((x_train, types), axis=1)\n', (30138, 30164), True, 'import numpy as np\n'), ((31178, 31271), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(16.2, 14.5)', '(3.8)', '(3.5)'], {'linewidth': '(1.5)', 'edgecolor': '"""r"""', 'facecolor': '"""none"""'}), "((16.2, 14.5), 3.8, 3.5, linewidth=1.5, edgecolor='r',\n facecolor='none')\n", (31195, 31271), True, 'import matplotlib.patches as patches\n'), ((31285, 31378), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(22.0, 19.0)', '(4.0)', '(3.0)'], {'linewidth': '(1.5)', 'edgecolor': '"""g"""', 'facecolor': '"""none"""'}), "((22.0, 19.0), 4.0, 3.0, linewidth=1.5, edgecolor='g',\n facecolor='none')\n", (31302, 31378), True, 'import matplotlib.patches as patches\n'), ((31393, 31486), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(26.0, 22.0)', '(6.0)', '(4.2)'], {'linewidth': '(1.5)', 'edgecolor': '"""b"""', 'facecolor': '"""none"""'}), "((26.0, 22.0), 6.0, 4.2, linewidth=1.5, edgecolor='b',\n facecolor='none')\n", (31410, 31486), True, 'import matplotlib.patches as patches\n'), ((34348, 34376), 'h5py.File', 'h5py.File', (['indices_file', '"""r"""'], {}), "(indices_file, 'r')\n", (34357, 34376), False, 'import h5py\n'), ((34515, 34538), 'numpy.array', 'np.array', (["f['d'][:, :2]"], {}), "(f['d'][:, :2])\n", (34523, 34538), True, 'import numpy as np\n'), ((36347, 36377), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(30, 25)'}), '(figsize=(30, 25))\n', (36359, 36377), True, 'import matplotlib.pyplot as plt\n'), ((36671, 36689), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, 360]'], {}), '([0, 360])\n', (36679, 36689), True, 'import matplotlib.pyplot as plt\n'), ((36698, 36717), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-90, 90]'], {}), '([-90, 90])\n', (36706, 36717), True, 'import matplotlib.pyplot as plt\n'), ((36771, 36794), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (36781, 36794), True, 'import matplotlib.pyplot as plt\n'), ((36849, 36859), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (36857, 36859), True, 'import matplotlib.pyplot as plt\n'), ((36868, 36897), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""longitude [deg]"""'], {}), "('longitude [deg]')\n", (36878, 36897), True, 'import matplotlib.pyplot as plt\n'), ((36925, 36953), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""latitude [deg]"""'], {}), "('latitude [deg]')\n", (36935, 36953), True, 'import matplotlib.pyplot as plt\n'), ((36962, 36982), 'matplotlib.pyplot.title', 'plt.title', (['titles[i]'], {}), '(titles[i])\n', (36971, 36982), True, 'import matplotlib.pyplot as plt\n'), ((37002, 37025), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (37021, 37025), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((37212, 37263), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'cax': 'cax', 'orientation': '"""horizontal"""'}), "(im, cax=cax, orientation='horizontal')\n", (37224, 37263), True, 'import matplotlib.pyplot as plt\n'), ((37370, 37380), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (37378, 37380), True, 'import matplotlib.pyplot as plt\n'), ((39709, 39732), 'numpy.transpose', 'np.transpose', (['hp_values'], {}), '(hp_values)\n', (39721, 39732), True, 'import numpy as np\n'), ((40038, 40073), 'numpy.char.replace', 'np.char.replace', (['labels', '"""_"""', '"""\\\\_"""'], {}), "(labels, '_', '\\\\_')\n", (40053, 40073), True, 'import numpy as np\n'), ((40927, 40951), 'numpy.zeros', 'np.zeros', (['y_lambda.shape'], {}), '(y_lambda.shape)\n', (40935, 40951), True, 'import numpy as np\n'), ((50940, 50980), 'numpy.concatenate', 'np.concatenate', (['(x_train, types)'], {'axis': '(1)'}), '((x_train, types), axis=1)\n', (50954, 50980), True, 'import numpy as np\n'), ((6683, 6709), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax[j]'], {}), '(ax[j])\n', (6702, 6709), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((6796, 6831), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['sc'], {'ax': 'ax[j]', 'cax': 'cax'}), '(sc, ax=ax[j], cax=cax)\n', (6808, 6831), True, 'import matplotlib.pyplot as plt\n'), ((8989, 9005), 'numpy.shape', 'np.shape', (['x_line'], {}), '(x_line)\n', (8997, 9005), True, 'import numpy as np\n'), ((9036, 9052), 'numpy.shape', 'np.shape', (['x_line'], {}), '(x_line)\n', (9044, 9052), True, 'import numpy as np\n'), ((9673, 9692), 'numpy.sum', 'np.sum', (['use_inds[i]'], {}), '(use_inds[i])\n', (9679, 9692), True, 'import numpy as np\n'), ((10259, 10277), 'numpy.shape', 'np.shape', (['quantile'], {}), '(quantile)\n', (10267, 10277), True, 'import numpy as np\n'), ((11341, 11385), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'sep': '"""\t"""', 'header': 'None'}), "(filename, sep='\\t', header=None)\n", (11352, 11385), True, 'import pandas as pd\n'), ((16875, 16919), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'sep': '"""\t"""', 'header': 'None'}), "(filename, sep='\\t', header=None)\n", (16886, 16919), True, 'import pandas as pd\n'), ((20197, 20220), 'numpy.arange', 'np.arange', (['(0)', '(100.1)', '(25)'], {}), '(0, 100.1, 25)\n', (20206, 20220), True, 'import numpy as np\n'), ((20247, 20270), 'numpy.arange', 'np.arange', (['(0)', '(100.1)', '(25)'], {}), '(0, 100.1, 25)\n', (20256, 20270), True, 'import numpy as np\n'), ((21131, 21175), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'sep': '"""\t"""', 'header': 'None'}), "(filename, sep='\\t', header=None)\n", (21142, 21175), True, 'import pandas as pd\n'), ((24415, 24459), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'sep': '"""\t"""', 'header': 'None'}), "(filename, sep='\\t', header=None)\n", (24426, 24459), True, 'import pandas as pd\n'), ((25745, 25763), 'numpy.transpose', 'np.transpose', (['data'], {}), '(data)\n', (25757, 25763), True, 'import numpy as np\n'), ((25966, 25992), 'numpy.arange', 'np.arange', (['(0.5)', '(2.501)', '(0.5)'], {}), '(0.5, 2.501, 0.5)\n', (25975, 25992), True, 'import numpy as np\n'), ((27249, 27314), 'numpy.convolve', 'np.convolve', (['history[model.metrics_names[1]]', 'conv_kernel', '"""same"""'], {}), "(history[model.metrics_names[1]], conv_kernel, 'same')\n", (27260, 27314), True, 'import numpy as np\n'), ((27703, 27756), 'numpy.convolve', 'np.convolve', (["history['val_loss']", 'conv_kernel', '"""same"""'], {}), "(history['val_loss'], conv_kernel, 'same')\n", (27714, 27756), True, 'import numpy as np\n'), ((29748, 29792), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'sep': '"""\t"""', 'header': 'None'}), "(filename, sep='\\t', header=None)\n", (29759, 29792), True, 'import pandas as pd\n'), ((32670, 32702), 'numpy.arange', 'np.arange', (['limx1', '(limx2 + 0.1)', '(5)'], {}), '(limx1, limx2 + 0.1, 5)\n', (32679, 32702), True, 'import numpy as np\n'), ((32729, 32761), 'numpy.arange', 'np.arange', (['limy1', '(limy2 + 0.1)', '(5)'], {}), '(limy1, limy2 + 0.1, 5)\n', (32738, 32761), True, 'import numpy as np\n'), ((34589, 34611), 'numpy.sum', 'np.sum', (['y_pred'], {'axis': '(0)'}), '(y_pred, axis=0)\n', (34595, 34611), True, 'import numpy as np\n'), ((35299, 35321), 'numpy.array', 'np.array', (['[0, 3, 5, 9]'], {}), '([0, 3, 5, 9])\n', (35307, 35321), True, 'import numpy as np\n'), ((36740, 36761), 'numpy.arange', 'np.arange', (['(0)', '(361)', '(10)'], {}), '(0, 361, 10)\n', (36749, 36761), True, 'import numpy as np\n'), ((36817, 36839), 'numpy.arange', 'np.arange', (['(-90)', '(91)', '(10)'], {}), '(-90, 91, 10)\n', (36826, 36839), True, 'import numpy as np\n'), ((37287, 37308), 'numpy.arange', 'np.arange', (['(0)', '(101)', '(10)'], {}), '(0, 101, 10)\n', (37296, 37308), True, 'import numpy as np\n'), ((37338, 37359), 'numpy.arange', 'np.arange', (['(0)', '(101)', '(10)'], {}), '(0, 101, 10)\n', (37347, 37359), True, 'import numpy as np\n'), ((40964, 41020), 'numpy.where', 'np.where', (['((x_lambda >= start[i]) & (x_lambda <= stop[i]))'], {}), '((x_lambda >= start[i]) & (x_lambda <= stop[i]))\n', (40972, 41020), True, 'import numpy as np\n'), ((41325, 41341), 'numpy.min', 'np.min', (['x_lambda'], {}), '(x_lambda)\n', (41331, 41341), True, 'import numpy as np\n'), ((41349, 41365), 'numpy.max', 'np.max', (['x_lambda'], {}), '(x_lambda)\n', (41355, 41365), True, 'import numpy as np\n'), ((43049, 43093), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'sep': '"""\t"""', 'header': 'None'}), "(filename, sep='\\t', header=None)\n", (43060, 43093), True, 'import pandas as pd\n'), ((43466, 43557), 'pandas.read_csv', 'pd.read_csv', (["(path_taxonomy + 'asteroid_pca-spectra-combined.dat')"], {'sep': '"""\t"""', 'header': 'None'}), "(path_taxonomy + 'asteroid_pca-spectra-combined.dat', sep='\\t',\n header=None)\n", (43477, 43557), True, 'import pandas as pd\n'), ((44355, 44423), 'numpy.histogram', 'np.histogram', (['predictions[inds[i, :], j]'], {'bins': 'nbins', 'range': '(0, 100)'}), '(predictions[inds[i, :], j], bins=nbins, range=(0, 100))\n', (44367, 44423), True, 'import numpy as np\n'), ((45701, 45777), 'numpy.histogram', 'np.histogram', (['predictions[inds[i, :], n_min + j]'], {'bins': 'nbins', 'range': '(0, 100)'}), '(predictions[inds[i, :], n_min + j], bins=nbins, range=(0, 100))\n', (45713, 45777), True, 'import numpy as np\n'), ((47005, 47093), 'numpy.histogram', 'np.histogram', (['predictions[inds[i, :], n_min + n_ol + j]'], {'bins': 'nbins', 'range': '(0, 100)'}), '(predictions[inds[i, :], n_min + n_ol + j], bins=nbins, range=(\n 0, 100))\n', (47017, 47093), True, 'import numpy as np\n'), ((48324, 48419), 'numpy.histogram', 'np.histogram', (['predictions[inds[i, :], n_min + n_ol + n_opx + j]'], {'bins': 'nbins', 'range': '(0, 100)'}), '(predictions[inds[i, :], n_min + n_ol + n_opx + j], bins=nbins,\n range=(0, 100))\n', (48336, 48419), True, 'import numpy as np\n'), ((50564, 50608), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'sep': '"""\t"""', 'header': 'None'}), "(filename, sep='\\t', header=None)\n", (50575, 50608), True, 'import pandas as pd\n'), ((2859, 2878), 'modules.NN_losses_metrics_activations.my_r2', 'my_r2', (['num_minerals'], {}), '(num_minerals)\n', (2864, 2878), False, 'from modules.NN_losses_metrics_activations import my_rmse, my_r2, my_sam, my_quantile\n'), ((4033, 4056), 'numpy.arange', 'np.arange', (['(0)', '(100.1)', '(25)'], {}), '(0, 100.1, 25)\n', (4042, 4056), True, 'import numpy as np\n'), ((4087, 4110), 'numpy.arange', 'np.arange', (['(0)', '(100.1)', '(25)'], {}), '(0, 100.1, 25)\n', (4096, 4110), True, 'import numpy as np\n'), ((7281, 7304), 'numpy.arange', 'np.arange', (['(0)', '(100.1)', '(25)'], {}), '(0, 100.1, 25)\n', (7290, 7304), True, 'import numpy as np\n'), ((7335, 7358), 'numpy.arange', 'np.arange', (['(0)', '(100.1)', '(25)'], {}), '(0, 100.1, 25)\n', (7344, 7358), True, 'import numpy as np\n'), ((9141, 9178), 'modules.NN_losses_metrics_activations.my_quantile', 'my_quantile', (['num_minerals', 'percentile'], {}), '(num_minerals, percentile)\n', (9152, 9178), False, 'from modules.NN_losses_metrics_activations import my_rmse, my_r2, my_sam, my_quantile\n'), ((25221, 25254), 'numpy.sum', 'np.sum', (['(y_data[:, :3] > 0)'], {'axis': '(1)'}), '(y_data[:, :3] > 0, axis=1)\n', (25227, 25254), True, 'import numpy as np\n'), ((27129, 27169), 'numpy.sqrt', 'np.sqrt', (['history[model.metrics_names[1]]'], {}), '(history[model.metrics_names[1]])\n', (27136, 27169), True, 'import numpy as np\n'), ((27968, 28042), 'numpy.convolve', 'np.convolve', (["history['val_' + model.metrics_names[1]]", 'conv_kernel', '"""same"""'], {}), "(history['val_' + model.metrics_names[1]], conv_kernel, 'same')\n", (27979, 28042), True, 'import numpy as np\n'), ((34718, 34748), 'numpy.argsort', 'np.argsort', (['sum_of_predictions'], {}), '(sum_of_predictions)\n', (34728, 34748), True, 'import numpy as np\n'), ((38475, 38489), 'modules.NN_config_taxonomy.classes.keys', 'classes.keys', ([], {}), '()\n', (38487, 38489), False, 'from modules.NN_config_taxonomy import classes, classes2\n'), ((38946, 38957), 'numpy.max', 'np.max', (['dim'], {}), '(dim)\n', (38952, 38957), True, 'import numpy as np\n'), ((38968, 38979), 'numpy.max', 'np.max', (['dim'], {}), '(dim)\n', (38974, 38979), True, 'import numpy as np\n'), ((45066, 45080), 'numpy.round', 'np.round', (['limy'], {}), '(limy)\n', (45074, 45080), True, 'import numpy as np\n'), ((46420, 46434), 'numpy.round', 'np.round', (['limy'], {}), '(limy)\n', (46428, 46434), True, 'import numpy as np\n'), ((47731, 47745), 'numpy.round', 'np.round', (['limy'], {}), '(limy)\n', (47739, 47745), True, 'import numpy as np\n'), ((49058, 49072), 'numpy.round', 'np.round', (['limy'], {}), '(limy)\n', (49066, 49072), True, 'import numpy as np\n'), ((2760, 2781), 'modules.NN_losses_metrics_activations.my_rmse', 'my_rmse', (['num_minerals'], {}), '(num_minerals)\n', (2767, 2781), False, 'from modules.NN_losses_metrics_activations import my_rmse, my_r2, my_sam, my_quantile\n'), ((27855, 27904), 'numpy.sqrt', 'np.sqrt', (["history['val_' + model.metrics_names[1]]"], {}), "(history['val_' + model.metrics_names[1]])\n", (27862, 27904), True, 'import numpy as np\n'), ((52373, 52394), 'numpy.array', 'np.array', (['[[0, 1, 2]]'], {}), '([[0, 1, 2]])\n', (52381, 52394), True, 'import numpy as np\n'), ((52412, 52432), 'numpy.shape', 'np.shape', (['distance_H'], {}), '(distance_H)\n', (52420, 52432), True, 'import numpy as np\n'), ((52516, 52537), 'numpy.array', 'np.array', (['[[0, 1, 2]]'], {}), '([[0, 1, 2]])\n', (52524, 52537), True, 'import numpy as np\n'), ((52555, 52575), 'numpy.shape', 'np.shape', (['distance_L'], {}), '(distance_L)\n', (52563, 52575), True, 'import numpy as np\n'), ((52660, 52681), 'numpy.array', 'np.array', (['[[0, 1, 2]]'], {}), '([[0, 1, 2]])\n', (52668, 52681), True, 'import numpy as np\n'), ((52699, 52720), 'numpy.shape', 'np.shape', (['distance_LL'], {}), '(distance_LL)\n', (52707, 52720), True, 'import numpy as np\n'), ((2913, 2933), 'modules.NN_losses_metrics_activations.my_sam', 'my_sam', (['num_minerals'], {}), '(num_minerals)\n', (2919, 2933), False, 'from modules.NN_losses_metrics_activations import my_rmse, my_r2, my_sam, my_quantile\n'), ((9723, 9744), 'numpy.where', 'np.where', (['use_inds[i]'], {}), '(use_inds[i])\n', (9731, 9744), True, 'import numpy as np\n'), ((10026, 10044), 'numpy.where', 'np.where', (['use_inds'], {}), '(use_inds)\n', (10034, 10044), True, 'import numpy as np\n'), ((9937, 9959), 'numpy.where', 'np.where', (['used_indices'], {}), '(used_indices)\n', (9945, 9959), True, 'import numpy as np\n'), ((9994, 10016), 'numpy.where', 'np.where', (['used_indices'], {}), '(used_indices)\n', (10002, 10016), True, 'import numpy as np\n')]
import numpy as np import tensorflow as tf tf.reset_default_graph() sess = tf.InteractiveSession() def exp(): s_len = 3 N, T = 2, 2 l = np.arange(1, N*T*s_len+1).reshape((N, T, s_len) ) x = tf.convert_to_tensor(l, dtype=tf.float32) print("x= {}".format(x.eval() ) ) # l = np.arange(1, N*T+1).reshape((N, T) ) # o = tf.convert_to_tensor(l, dtype=tf.int32) # print("o= {}".format(o.eval() ) ) # l = np.array([1] * N*T).reshape((N, T) ) # l = np.array([1] * N*T).reshape((N, T) ) l = np.random.randint(s_len, size=(N, T) ) a = tf.convert_to_tensor(l, dtype=tf.int32) print("a= {}".format(a.eval() ) ) print("a[1:]= {}".format(a[1:].eval() ) ) print("shape(x)= {}".format(tf.shape(x).eval() ) ) indices = tf.range(0, tf.shape(x)[0]*tf.shape(x)[1] ) * tf.shape(x)[2] + tf.reshape(a, [-1] ) print("indices= {}".format(indices.eval() ) ) ro = tf.reshape(tf.gather(tf.reshape(x, [-1] ), indices), (N, T) ) print("ro= {}".format(ro.eval() ) ) def exp2(): x = tf.constant([[[1.], [1.]], [[2.], [2.]]]) print("x.shape= {}, x= \n{}".format(x.shape, x.eval() ) ) y = tf.reduce_mean(x, axis=0) print("y.shape= {}, y= \n{}".format(y.shape, y.eval() ) ) z = tf.reduce_mean(y, axis=0) print("z.shape= {}, z= \n{}".format(z.shape, z.eval() ) ) if __name__ == "__main__": # exp() exp2()
[ "tensorflow.reset_default_graph", "tensorflow.convert_to_tensor", "tensorflow.reshape", "tensorflow.reduce_mean", "tensorflow.constant", "tensorflow.shape", "numpy.random.randint", "numpy.arange", "tensorflow.InteractiveSession" ]
[((44, 68), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (66, 68), True, 'import tensorflow as tf\n'), ((76, 99), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (97, 99), True, 'import tensorflow as tf\n'), ((200, 241), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['l'], {'dtype': 'tf.float32'}), '(l, dtype=tf.float32)\n', (220, 241), True, 'import tensorflow as tf\n'), ((511, 548), 'numpy.random.randint', 'np.random.randint', (['s_len'], {'size': '(N, T)'}), '(s_len, size=(N, T))\n', (528, 548), True, 'import numpy as np\n'), ((556, 595), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['l'], {'dtype': 'tf.int32'}), '(l, dtype=tf.int32)\n', (576, 595), True, 'import tensorflow as tf\n'), ((1002, 1047), 'tensorflow.constant', 'tf.constant', (['[[[1.0], [1.0]], [[2.0], [2.0]]]'], {}), '([[[1.0], [1.0]], [[2.0], [2.0]]])\n', (1013, 1047), True, 'import tensorflow as tf\n'), ((1113, 1138), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (1127, 1138), True, 'import tensorflow as tf\n'), ((1208, 1233), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['y'], {'axis': '(0)'}), '(y, axis=0)\n', (1222, 1233), True, 'import tensorflow as tf\n'), ((807, 826), 'tensorflow.reshape', 'tf.reshape', (['a', '[-1]'], {}), '(a, [-1])\n', (817, 826), True, 'import tensorflow as tf\n'), ((144, 175), 'numpy.arange', 'np.arange', (['(1)', '(N * T * s_len + 1)'], {}), '(1, N * T * s_len + 1)\n', (153, 175), True, 'import numpy as np\n'), ((904, 923), 'tensorflow.reshape', 'tf.reshape', (['x', '[-1]'], {}), '(x, [-1])\n', (914, 923), True, 'import tensorflow as tf\n'), ((790, 801), 'tensorflow.shape', 'tf.shape', (['x'], {}), '(x)\n', (798, 801), True, 'import tensorflow as tf\n'), ((709, 720), 'tensorflow.shape', 'tf.shape', (['x'], {}), '(x)\n', (717, 720), True, 'import tensorflow as tf\n'), ((756, 767), 'tensorflow.shape', 'tf.shape', (['x'], {}), '(x)\n', (764, 767), True, 'import tensorflow as tf\n'), ((771, 782), 'tensorflow.shape', 'tf.shape', (['x'], {}), '(x)\n', (779, 782), True, 'import tensorflow as tf\n')]
# Copyright 2017 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests of the block operators.""" import numpy as np import tensorflow as tf import block_base import blocks_operator class AddOneBlock(block_base.BlockBase): def __init__(self, name=None): super(AddOneBlock, self).__init__(name) def _Apply(self, x): return x + 1.0 class SquareBlock(block_base.BlockBase): def __init__(self, name=None): super(SquareBlock, self).__init__(name) def _Apply(self, x): return x * x class BlocksOperatorTest(tf.test.TestCase): def testComposition(self): x_value = np.array([[1.0, 2.0, 3.0], [-1.0, -2.0, -3.0]]) y_expected_value = np.array([[4.0, 9.0, 16.0], [0.0, 1.0, 4.0]]) x = tf.placeholder(dtype=tf.float32, shape=[2, 3]) complex_block = blocks_operator.CompositionOperator( [AddOneBlock(), SquareBlock()]) y = complex_block(x) with self.test_session(): y_value = y.eval(feed_dict={x: x_value}) self.assertAllClose(y_expected_value, y_value) if __name__ == '__main__': tf.test.main()
[ "tensorflow.test.main", "tensorflow.placeholder", "numpy.array" ]
[((1812, 1826), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (1824, 1826), True, 'import tensorflow as tf\n'), ((1272, 1319), 'numpy.array', 'np.array', (['[[1.0, 2.0, 3.0], [-1.0, -2.0, -3.0]]'], {}), '([[1.0, 2.0, 3.0], [-1.0, -2.0, -3.0]])\n', (1280, 1319), True, 'import numpy as np\n'), ((1369, 1414), 'numpy.array', 'np.array', (['[[4.0, 9.0, 16.0], [0.0, 1.0, 4.0]]'], {}), '([[4.0, 9.0, 16.0], [0.0, 1.0, 4.0]])\n', (1377, 1414), True, 'import numpy as np\n'), ((1460, 1506), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[2, 3]'}), '(dtype=tf.float32, shape=[2, 3])\n', (1474, 1506), True, 'import tensorflow as tf\n')]
import numpy as np from matplotlib import pyplot as plt from matplotlib import animation, rc, patches import matplotlib.collections as clt import environment import scenarios import trajectory_gen # Set jshtml default mode for notebook use rc('animation', html='jshtml') def plot_one_step(env, x_ref, x_bar, x_opt, x_next=None, nominals=None): ''' Plots a single step of trajectory optimization in environment ''' fig, ax = environment.plot_environment(env, figsize=(16, 10)) ax.plot(x_ref[0, :], x_ref[1, :], '-o', alpha=0.8, color='blue', markersize=3, label='reference trajectory') if nominals is not None: for nom in nominals: ax.plot(nom[0, :], nom[1, :], 'r-', label='nominal trajectories') else: ax.plot(x_bar[0, :], x_bar[1, :], 'r-', label='nominal trajectory') ax.plot(x_opt[0, :], x_opt[1, :], '-o', color='lightseagreen', label='optimal trajectory') if x_next is not None: ax.plot(x_next[0], x_next[1], 'o', color='blueviolet', label='next x0') handles, labels = plt.gca().get_legend_handles_labels() labels, ids = np.unique(labels, return_index=True) handles = [handles[i] for i in ids] ax.legend(handles, labels, loc='best') return fig, ax def plot_all_steps(env, x_ref_full, history): ''' Plots optimization paths in environment at each step over time course of the full MPC run ''' fig, ax = environment.plot_environment(env, figsize=(16, 10)) ax.plot(x_ref_full[0, :], x_ref_full[1, :], '-o', color='blue', label='reference trajectory', markersize=3) for i in range(len(history.keys())): xi = history[i]['x_opt'] ax.plot(xi[0, :], xi[1, :], color='lightseagreen', linewidth=1, label='N-step optimal traj') x0x = [history[i]['x0'][0] for i in history.keys()] x0y = [history[i]['x0'][1] for i in history.keys()] ax.plot(x0x, x0y, '-o', color='blueviolet', label='actual trajectory') xf_bar = history[len(history.keys())-1]['x_bar'] # ax.plot(xf_bar[0, :], xf_bar[1, :], 'r', label='xf_bar') ax.axis('equal') handles, labels = plt.gca().get_legend_handles_labels() labels, ids = np.unique(labels, return_index=True) handles = [handles[i] for i in ids] ax.legend(handles, labels, loc='best') return fig, ax def animate(env, ctrl_pts, bc_headings, v, dt, x_ref, history, rect=False): fig, ax = environment.plot_environment(env, figsize=(16, 10)) xs = x_ref[0, :] ys = x_ref[1, :] x0s = [history[i]['x0'][0] for i in history.keys()] y0s = [history[i]['x0'][1] for i in history.keys()] # plot reference trajectory ax.plot(xs, ys, '-o', alpha=0.8, markersize=3, color='blue', label='reference trajectory') # optimized trajectory opt_line, = ax.plot([], [], '-o', lw=3, color='lightseagreen', label='N-step optimal traj') nom_line, = ax.plot([], [], color='red', label='nominal trajectory') act_line, = ax.plot([], [], '-o', lw=3, markersize=6, color='blueviolet', label='actual trajectory') if rect: ld, wd = 0.5, 0.2 a2 = np.arctan2(wd, ld) diag = np.sqrt(ld**2 + wd**2) heading = np.rad2deg(np.arctan2((y0s[1]-y0s[0]), (x0s[1]-x0s[0]))) car = patches.Rectangle( (x0s[0]-ld, y0s[0]-wd), 2*ld, 2*wd, angle=-heading, fc='none', lw=1, ec='k') def init(): opt_line.set_data([], []) act_line.set_data([], []) nom_line.set_data([], []) if rect: ax.add_patch(car) return opt_line, def step(i): x = history[i]['x_opt'][0] y = history[i]['x_opt'][1] xbar = history[i]['x_bar'][0] ybar = history[i]['x_bar'][1] opt_line.set_data(x, y) act_line.set_data(x0s[:i], y0s[:i]) nom_line.set_data(xbar, ybar) if rect: if (len(x) == 1): heading = bc_headings[1] else: heading = np.arctan2((y[1]-y[0]), (x[1]-x[0])) xoff = diag*np.cos(heading + a2) yoff = diag*np.sin(heading + a2) car.set_xy((x[0] - xoff, y[0] - yoff)) car.angle = np.rad2deg(heading) return opt_line, anim = animation.FuncAnimation(fig, step, init_func=init, frames=len(history.keys()), interval=1000*dt*2, blit=True) ax.axis('equal') ax.legend() plt.close() return anim if __name__ == "__main__": # TEST ANIMATION FUNCTION scene = scenarios.five_obstacle ctrl_pts = scene['control_pts'] bch = scene['bc_headings'] env = environment.Environment(scene['obs_list'], scene['start'], scene['goal']) env.add_control_points(ctrl_pts) v = 4 dt = 0.1 xs, ys, psi = trajectory_gen.sample_trajectory(ctrl_pts, bch, v, dt) nf = len(xs) x_ref = np.vstack((xs.reshape((1, nf)), ys.reshape((1, nf)), psi.reshape((1, nf)), v*np.ones((1, nf)), np.zeros((1, nf)))) anim = animate(env, ctrl_pts, bch, v, dt, x_ref, None) plt.show()
[ "matplotlib.rc", "matplotlib.pyplot.show", "numpy.arctan2", "matplotlib.patches.Rectangle", "matplotlib.pyplot.close", "trajectory_gen.sample_trajectory", "numpy.zeros", "numpy.ones", "numpy.rad2deg", "numpy.sin", "environment.plot_environment", "environment.Environment", "numpy.cos", "matplotlib.pyplot.gca", "numpy.unique", "numpy.sqrt" ]
[((242, 272), 'matplotlib.rc', 'rc', (['"""animation"""'], {'html': '"""jshtml"""'}), "('animation', html='jshtml')\n", (244, 272), False, 'from matplotlib import animation, rc, patches\n'), ((436, 487), 'environment.plot_environment', 'environment.plot_environment', (['env'], {'figsize': '(16, 10)'}), '(env, figsize=(16, 10))\n', (464, 487), False, 'import environment\n'), ((1128, 1164), 'numpy.unique', 'np.unique', (['labels'], {'return_index': '(True)'}), '(labels, return_index=True)\n', (1137, 1164), True, 'import numpy as np\n'), ((1443, 1494), 'environment.plot_environment', 'environment.plot_environment', (['env'], {'figsize': '(16, 10)'}), '(env, figsize=(16, 10))\n', (1471, 1494), False, 'import environment\n'), ((2212, 2248), 'numpy.unique', 'np.unique', (['labels'], {'return_index': '(True)'}), '(labels, return_index=True)\n', (2221, 2248), True, 'import numpy as np\n'), ((2444, 2495), 'environment.plot_environment', 'environment.plot_environment', (['env'], {'figsize': '(16, 10)'}), '(env, figsize=(16, 10))\n', (2472, 2495), False, 'import environment\n'), ((4494, 4505), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4503, 4505), True, 'from matplotlib import pyplot as plt\n'), ((4696, 4769), 'environment.Environment', 'environment.Environment', (["scene['obs_list']", "scene['start']", "scene['goal']"], {}), "(scene['obs_list'], scene['start'], scene['goal'])\n", (4719, 4769), False, 'import environment\n'), ((4882, 4936), 'trajectory_gen.sample_trajectory', 'trajectory_gen.sample_trajectory', (['ctrl_pts', 'bch', 'v', 'dt'], {}), '(ctrl_pts, bch, v, dt)\n', (4914, 4936), False, 'import trajectory_gen\n'), ((5237, 5247), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5245, 5247), True, 'from matplotlib import pyplot as plt\n'), ((3192, 3210), 'numpy.arctan2', 'np.arctan2', (['wd', 'ld'], {}), '(wd, ld)\n', (3202, 3210), True, 'import numpy as np\n'), ((3226, 3252), 'numpy.sqrt', 'np.sqrt', (['(ld ** 2 + wd ** 2)'], {}), '(ld ** 2 + wd ** 2)\n', (3233, 3252), True, 'import numpy as np\n'), ((3338, 3445), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(x0s[0] - ld, y0s[0] - wd)', '(2 * ld)', '(2 * wd)'], {'angle': '(-heading)', 'fc': '"""none"""', 'lw': '(1)', 'ec': '"""k"""'}), "((x0s[0] - ld, y0s[0] - wd), 2 * ld, 2 * wd, angle=-\n heading, fc='none', lw=1, ec='k')\n", (3355, 3445), False, 'from matplotlib import animation, rc, patches\n'), ((1072, 1081), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1079, 1081), True, 'from matplotlib import pyplot as plt\n'), ((2156, 2165), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2163, 2165), True, 'from matplotlib import pyplot as plt\n'), ((3278, 3322), 'numpy.arctan2', 'np.arctan2', (['(y0s[1] - y0s[0])', '(x0s[1] - x0s[0])'], {}), '(y0s[1] - y0s[0], x0s[1] - x0s[0])\n', (3288, 3322), True, 'import numpy as np\n'), ((4249, 4268), 'numpy.rad2deg', 'np.rad2deg', (['heading'], {}), '(heading)\n', (4259, 4268), True, 'import numpy as np\n'), ((5153, 5170), 'numpy.zeros', 'np.zeros', (['(1, nf)'], {}), '((1, nf))\n', (5161, 5170), True, 'import numpy as np\n'), ((4047, 4083), 'numpy.arctan2', 'np.arctan2', (['(y[1] - y[0])', '(x[1] - x[0])'], {}), '(y[1] - y[0], x[1] - x[0])\n', (4057, 4083), True, 'import numpy as np\n'), ((4108, 4128), 'numpy.cos', 'np.cos', (['(heading + a2)'], {}), '(heading + a2)\n', (4114, 4128), True, 'import numpy as np\n'), ((4153, 4173), 'numpy.sin', 'np.sin', (['(heading + a2)'], {}), '(heading + a2)\n', (4159, 4173), True, 'import numpy as np\n'), ((5112, 5128), 'numpy.ones', 'np.ones', (['(1, nf)'], {}), '((1, nf))\n', (5119, 5128), True, 'import numpy as np\n')]
# /* Copyright (C) 2016 Ion Torrent Systems, Inc. All Rights Reserved */ import pandas as pd import datetime import dateutil import matplotlib.dates as dates from matplotlib import pyplot as plt import numpy as np from time import strptime import os # put the date on the same line with the cpu data os.system("awk 'NR%2{printf \"%s \",$0;next;}1' cpu_util.log > cpu_data.log") df = pd.read_csv( "cpu_data.log", names=[ "dow", "mon", "day", "time", "tz", "year", "lcpu", "us", "lus", "sy", "lsy", "ni", "lni", "id", "lid", "wa", "lwa", "hi", "lhi", "si", "lsi", "st", "lst", ], delim_whitespace=True, header=None, ) data = list(df.T.to_dict().values()) # export the data frame to a python dictionary x_axis = np.zeros(len(data), dtype="datetime64[s]") y_axis_idle = np.zeros(len(data)) y_axis_idle_smoothed = np.zeros(len(data)) y_axis_usr = np.zeros(len(data)) y_axis_usr_smoothed = np.zeros(len(data)) y_axis_nice = np.zeros(len(data)) y_axis_nice_smoothed = np.zeros(len(data)) y_axis_sys = np.zeros(len(data)) y_axis_sys_smoothed = np.zeros(len(data)) span = 5 span_gpu = 10 for key in range(0, len(data)): month = str(strptime(data[key]["mon"], "%b").tm_mon).zfill(2) datekey = ( str(data[key]["year"]) + "-" + month + "-" + str(data[key]["day"]) + "T" + data[key]["time"] ) x_axis[key] = np.datetime64(datekey) y_axis_idle[key] = int(data[key]["id"]) y_axis_usr[key] = int(data[key]["us"]) y_axis_nice[key] = int(data[key]["ni"]) y_axis_sys[key] = int(data[key]["sy"]) # now, read in the gpu data df = pd.read_csv( "gpu_util.log", names=["systemtime", "percent"], sep=",", parse_dates=[0] ) # or:, infer_datetime_format=True) data2 = list(df.T.to_dict().values()) # export the data frame to a python dictionary x_axis_gpu = np.zeros(len(data2), dtype="datetime64[s]") y_axis_gpu = np.zeros(len(data)) y_axis_gpu_smoothed = np.zeros(len(data)) for key in range(0, len(data)): x_axis_gpu[key] = np.datetime64((data2[key]["systemtime"])) if key < len(data2): y_axis_gpu[key] = int((data2[key]["percent"].replace(" ", "").replace("%", ""))) else: y_axis_gpu[key] = 0 # print x_axis[0] # print x_axis_gpu[0] # print x_axis[len(x_axis)-1] # print x_axis_gpu[len(x_axis_gpu)-1] # smooth the data if len(data) > span: for key in range(span, len(data) - span): sum_gpu = 0 for key2 in range(key - span, key + span): sum_gpu += y_axis_gpu[key2] y_axis_gpu_smoothed[key] = sum_gpu / (2 * span) for key in range(span, len(data) - span): sum_idle = sum_usr = sum_nice = sum_sys = 0 for key2 in range(key - span, key + span): sum_idle += y_axis_idle[key2] sum_usr += y_axis_usr[key2] sum_nice += y_axis_nice[key2] sum_sys += y_axis_sys[key2] y_axis_idle_smoothed[key] = sum_idle / (2 * span) y_axis_usr_smoothed[key] = sum_usr / (2 * span) y_axis_nice_smoothed[key] = sum_nice / (2 * span) y_axis_sys_smoothed[key] = sum_sys / (2 * span) s = data wl = 0.6 fsz = 8 fig = plt.figure(figsize=(15, 5)) ax = plt.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.85, box.height]) for item in ax.get_xticklabels() + ax.get_yticklabels(): item.set_fontsize(fsz) # xstart, xend = ax.get_xlim() # xtickvals = # ax.xaxis.set_ticks(xtickvals) plt.plot(x_axis, y_axis_usr, "#be4b48", linewidth=wl, label="% usr") plt.plot(x_axis, y_axis_nice, "#98b954", linewidth=wl, label="% nice") plt.plot(x_axis, y_axis_sys, "#7d60a0", linewidth=wl, label="% sys") plt.plot(x_axis, y_axis_idle, "#46aac5", linewidth=wl, label="% idle") plt.plot(x_axis, y_axis_gpu, "#000000", linewidth=wl, label="% gpu") plt.legend(loc="right", bbox_to_anchor=(1.25, 0.5), fontsize=fsz) plt.savefig("oiaTimingRaw.png") plt.clf() wl = 1.0 ax = plt.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.85, box.height]) for item in ax.get_xticklabels() + ax.get_yticklabels(): item.set_fontsize(fsz) plt.plot(x_axis, y_axis_usr_smoothed, "#be4b48", linewidth=wl, label="% usr") plt.plot(x_axis, y_axis_nice_smoothed, "#98b954", linewidth=wl, label="% nice") plt.plot(x_axis, y_axis_sys_smoothed, "#7d60a0", linewidth=wl, label="% sys") plt.plot(x_axis, y_axis_idle_smoothed, "#46aac5", linewidth=wl, label="% idle") plt.plot(x_axis, y_axis_gpu_smoothed, "#000000", linewidth=0.4, label="% gpu") plt.legend(loc="right", bbox_to_anchor=(1.25, 0.5), fontsize=fsz) plt.savefig("oiaTiming.png") os.remove("cpu_data.log")
[ "matplotlib.pyplot.subplot", "os.remove", "matplotlib.pyplot.plot", "matplotlib.pyplot.clf", "pandas.read_csv", "numpy.datetime64", "matplotlib.pyplot.legend", "os.system", "matplotlib.pyplot.figure", "time.strptime", "matplotlib.pyplot.savefig" ]
[((301, 378), 'os.system', 'os.system', (['"""awk \'NR%2{printf "%s ",$0;next;}1\' cpu_util.log > cpu_data.log"""'], {}), '(\'awk \\\'NR%2{printf "%s ",$0;next;}1\\\' cpu_util.log > cpu_data.log\')\n', (310, 378), False, 'import os\n'), ((385, 624), 'pandas.read_csv', 'pd.read_csv', (['"""cpu_data.log"""'], {'names': "['dow', 'mon', 'day', 'time', 'tz', 'year', 'lcpu', 'us', 'lus', 'sy',\n 'lsy', 'ni', 'lni', 'id', 'lid', 'wa', 'lwa', 'hi', 'lhi', 'si', 'lsi',\n 'st', 'lst']", 'delim_whitespace': '(True)', 'header': 'None'}), "('cpu_data.log', names=['dow', 'mon', 'day', 'time', 'tz',\n 'year', 'lcpu', 'us', 'lus', 'sy', 'lsy', 'ni', 'lni', 'id', 'lid',\n 'wa', 'lwa', 'hi', 'lhi', 'si', 'lsi', 'st', 'lst'], delim_whitespace=\n True, header=None)\n", (396, 624), True, 'import pandas as pd\n'), ((1806, 1896), 'pandas.read_csv', 'pd.read_csv', (['"""gpu_util.log"""'], {'names': "['systemtime', 'percent']", 'sep': '""","""', 'parse_dates': '[0]'}), "('gpu_util.log', names=['systemtime', 'percent'], sep=',',\n parse_dates=[0])\n", (1817, 1896), True, 'import pandas as pd\n'), ((3339, 3366), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 5)'}), '(figsize=(15, 5))\n', (3349, 3366), True, 'from matplotlib import pyplot as plt\n'), ((3372, 3388), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (3383, 3388), True, 'from matplotlib import pyplot as plt\n'), ((3640, 3708), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'y_axis_usr', '"""#be4b48"""'], {'linewidth': 'wl', 'label': '"""% usr"""'}), "(x_axis, y_axis_usr, '#be4b48', linewidth=wl, label='% usr')\n", (3648, 3708), True, 'from matplotlib import pyplot as plt\n'), ((3709, 3779), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'y_axis_nice', '"""#98b954"""'], {'linewidth': 'wl', 'label': '"""% nice"""'}), "(x_axis, y_axis_nice, '#98b954', linewidth=wl, label='% nice')\n", (3717, 3779), True, 'from matplotlib import pyplot as plt\n'), ((3780, 3848), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'y_axis_sys', '"""#7d60a0"""'], {'linewidth': 'wl', 'label': '"""% sys"""'}), "(x_axis, y_axis_sys, '#7d60a0', linewidth=wl, label='% sys')\n", (3788, 3848), True, 'from matplotlib import pyplot as plt\n'), ((3849, 3919), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'y_axis_idle', '"""#46aac5"""'], {'linewidth': 'wl', 'label': '"""% idle"""'}), "(x_axis, y_axis_idle, '#46aac5', linewidth=wl, label='% idle')\n", (3857, 3919), True, 'from matplotlib import pyplot as plt\n'), ((3920, 3988), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'y_axis_gpu', '"""#000000"""'], {'linewidth': 'wl', 'label': '"""% gpu"""'}), "(x_axis, y_axis_gpu, '#000000', linewidth=wl, label='% gpu')\n", (3928, 3988), True, 'from matplotlib import pyplot as plt\n'), ((3989, 4054), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""right"""', 'bbox_to_anchor': '(1.25, 0.5)', 'fontsize': 'fsz'}), "(loc='right', bbox_to_anchor=(1.25, 0.5), fontsize=fsz)\n", (3999, 4054), True, 'from matplotlib import pyplot as plt\n'), ((4055, 4086), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""oiaTimingRaw.png"""'], {}), "('oiaTimingRaw.png')\n", (4066, 4086), True, 'from matplotlib import pyplot as plt\n'), ((4087, 4096), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (4094, 4096), True, 'from matplotlib import pyplot as plt\n'), ((4111, 4127), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (4122, 4127), True, 'from matplotlib import pyplot as plt\n'), ((4301, 4378), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'y_axis_usr_smoothed', '"""#be4b48"""'], {'linewidth': 'wl', 'label': '"""% usr"""'}), "(x_axis, y_axis_usr_smoothed, '#be4b48', linewidth=wl, label='% usr')\n", (4309, 4378), True, 'from matplotlib import pyplot as plt\n'), ((4379, 4458), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'y_axis_nice_smoothed', '"""#98b954"""'], {'linewidth': 'wl', 'label': '"""% nice"""'}), "(x_axis, y_axis_nice_smoothed, '#98b954', linewidth=wl, label='% nice')\n", (4387, 4458), True, 'from matplotlib import pyplot as plt\n'), ((4459, 4536), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'y_axis_sys_smoothed', '"""#7d60a0"""'], {'linewidth': 'wl', 'label': '"""% sys"""'}), "(x_axis, y_axis_sys_smoothed, '#7d60a0', linewidth=wl, label='% sys')\n", (4467, 4536), True, 'from matplotlib import pyplot as plt\n'), ((4537, 4616), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'y_axis_idle_smoothed', '"""#46aac5"""'], {'linewidth': 'wl', 'label': '"""% idle"""'}), "(x_axis, y_axis_idle_smoothed, '#46aac5', linewidth=wl, label='% idle')\n", (4545, 4616), True, 'from matplotlib import pyplot as plt\n'), ((4617, 4695), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'y_axis_gpu_smoothed', '"""#000000"""'], {'linewidth': '(0.4)', 'label': '"""% gpu"""'}), "(x_axis, y_axis_gpu_smoothed, '#000000', linewidth=0.4, label='% gpu')\n", (4625, 4695), True, 'from matplotlib import pyplot as plt\n'), ((4696, 4761), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""right"""', 'bbox_to_anchor': '(1.25, 0.5)', 'fontsize': 'fsz'}), "(loc='right', bbox_to_anchor=(1.25, 0.5), fontsize=fsz)\n", (4706, 4761), True, 'from matplotlib import pyplot as plt\n'), ((4762, 4790), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""oiaTiming.png"""'], {}), "('oiaTiming.png')\n", (4773, 4790), True, 'from matplotlib import pyplot as plt\n'), ((4792, 4817), 'os.remove', 'os.remove', (['"""cpu_data.log"""'], {}), "('cpu_data.log')\n", (4801, 4817), False, 'import os\n'), ((1575, 1597), 'numpy.datetime64', 'np.datetime64', (['datekey'], {}), '(datekey)\n', (1588, 1597), True, 'import numpy as np\n'), ((2208, 2247), 'numpy.datetime64', 'np.datetime64', (["data2[key]['systemtime']"], {}), "(data2[key]['systemtime'])\n", (2221, 2247), True, 'import numpy as np\n'), ((1336, 1368), 'time.strptime', 'strptime', (["data[key]['mon']", '"""%b"""'], {}), "(data[key]['mon'], '%b')\n", (1344, 1368), False, 'from time import strptime\n')]
import os import h5py import numpy as np import pickle as pkl import tensorflow as tf from tqdm import tqdm from gcn.train import train_model from gcn.utils import load_data_pkl, load_data_h5 # Set random seed seed = 123 np.random.seed(seed) tf.set_random_seed(seed) # Settings flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_bool('use_h5', True, 'use h5 feature or not') flags.DEFINE_string('data_dir', './data', 'Data root dir') flags.DEFINE_string('save_dir', './genrated_textvqa_gcn_sg', 'dir to save generated scene graph') flags.DEFINE_integer('epochs', 300, 'Number of epochs to train.') flags.DEFINE_integer('hidden1', 600, 'Number of units in hidden layer, equal to the dim of output scene graph') flags.DEFINE_string('tiers', 'train_val_test', 'what tier of textvqa sg to use: train, val, or test') flags.DEFINE_integer('start_index', 0, 'image start index') flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.') flags.DEFINE_float('dropout', 0.2, 'Dropout rate (1 - keep probability).') flags.DEFINE_float('weight_decay', 5e-4, 'Weight for L2 loss on embedding matrix.') flags.DEFINE_bool('use_dummy', False, 'use dummy data for test') if not os.path.exists(FLAGS.save_dir): os.mkdir(FLAGS.save_dir) tiers = FLAGS.tiers.split('_') for tier in tiers: data_root = os.path.join(FLAGS.data_dir, 'textvqa_{}'.format(tier)) if FLAGS.use_h5: node_feature_h5 = h5py.File(os.path.join(data_root, 'node_features.h5'), "r") adj_matrix_h5 = h5py.File(os.path.join(data_root, 'adjacent_matrix.h5'), "r") target_h5 = h5py.File(os.path.join(data_root, 'targets.h5'), "r") mask_h5 = h5py.File(os.path.join(data_root, 'mask.h5'), "r") n_images = mask_h5['masks'].shape[0] save_h5 = h5py.File(os.path.join(FLAGS.save_dir, '{}_sg.h5'.format(tier)), "w") save_h5.create_dataset("gcn_scene_graphs", (n_images, node_feature_h5['object_name_embeddings'].shape[1] + node_feature_h5['ocr_token_embeddings'].shape[1], FLAGS.hidden1), dtype='float32') for image_index in tqdm(range(FLAGS.start_index, n_images), unit='image', desc='Generating gcn sg for {}'.format(tier)): data = load_data_h5(image_index, node_feature_h5, adj_matrix_h5, target_h5, mask_h5) hidden_state = train_model(data) save_h5['gcn_scene_graphs'][image_index] = hidden_state node_feature_h5.close() adj_matrix_h5.close() target_h5.close() mask_h5.close() save_h5.close() else: target_dir = os.path.join(data_root, 'targets') n_images = len(os.listdir(target_dir)) for image_index in tqdm(range(FLAGS.start_index, n_images), unit='image', desc='Generating gcn sg for {}'.format(tier)): data = load_data_pkl(data_root, image_index, FLAGS.use_dummy) hidden_state = train_model(data) # save 2nd layer hidden state save_dir = os.path.join(FLAGS.save_dir, '{}_sg'.format(tier)) if not os.path.exists(save_dir): os.mkdir(save_dir) with open(os.path.join(save_dir, '{}.p'.format(image_index)), 'wb') as f: pkl.dump(hidden_state, f)
[ "os.mkdir", "pickle.dump", "numpy.random.seed", "gcn.utils.load_data_h5", "gcn.train.train_model", "gcn.utils.load_data_pkl", "os.path.exists", "tensorflow.set_random_seed", "os.path.join", "os.listdir" ]
[((223, 243), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (237, 243), True, 'import numpy as np\n'), ((244, 268), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['seed'], {}), '(seed)\n', (262, 268), True, 'import tensorflow as tf\n'), ((1179, 1209), 'os.path.exists', 'os.path.exists', (['FLAGS.save_dir'], {}), '(FLAGS.save_dir)\n', (1193, 1209), False, 'import os\n'), ((1215, 1239), 'os.mkdir', 'os.mkdir', (['FLAGS.save_dir'], {}), '(FLAGS.save_dir)\n', (1223, 1239), False, 'import os\n'), ((2764, 2798), 'os.path.join', 'os.path.join', (['data_root', '"""targets"""'], {}), "(data_root, 'targets')\n", (2776, 2798), False, 'import os\n'), ((1422, 1465), 'os.path.join', 'os.path.join', (['data_root', '"""node_features.h5"""'], {}), "(data_root, 'node_features.h5')\n", (1434, 1465), False, 'import os\n'), ((1506, 1551), 'os.path.join', 'os.path.join', (['data_root', '"""adjacent_matrix.h5"""'], {}), "(data_root, 'adjacent_matrix.h5')\n", (1518, 1551), False, 'import os\n'), ((1588, 1625), 'os.path.join', 'os.path.join', (['data_root', '"""targets.h5"""'], {}), "(data_root, 'targets.h5')\n", (1600, 1625), False, 'import os\n'), ((1660, 1694), 'os.path.join', 'os.path.join', (['data_root', '"""mask.h5"""'], {}), "(data_root, 'mask.h5')\n", (1672, 1694), False, 'import os\n'), ((2405, 2482), 'gcn.utils.load_data_h5', 'load_data_h5', (['image_index', 'node_feature_h5', 'adj_matrix_h5', 'target_h5', 'mask_h5'], {}), '(image_index, node_feature_h5, adj_matrix_h5, target_h5, mask_h5)\n', (2417, 2482), False, 'from gcn.utils import load_data_pkl, load_data_h5\n'), ((2510, 2527), 'gcn.train.train_model', 'train_model', (['data'], {}), '(data)\n', (2521, 2527), False, 'from gcn.train import train_model\n'), ((2822, 2844), 'os.listdir', 'os.listdir', (['target_dir'], {}), '(target_dir)\n', (2832, 2844), False, 'import os\n'), ((3058, 3112), 'gcn.utils.load_data_pkl', 'load_data_pkl', (['data_root', 'image_index', 'FLAGS.use_dummy'], {}), '(data_root, image_index, FLAGS.use_dummy)\n', (3071, 3112), False, 'from gcn.utils import load_data_pkl, load_data_h5\n'), ((3140, 3157), 'gcn.train.train_model', 'train_model', (['data'], {}), '(data)\n', (3151, 3157), False, 'from gcn.train import train_model\n'), ((3294, 3318), 'os.path.exists', 'os.path.exists', (['save_dir'], {}), '(save_dir)\n', (3308, 3318), False, 'import os\n'), ((3336, 3354), 'os.mkdir', 'os.mkdir', (['save_dir'], {}), '(save_dir)\n', (3344, 3354), False, 'import os\n'), ((3457, 3482), 'pickle.dump', 'pkl.dump', (['hidden_state', 'f'], {}), '(hidden_state, f)\n', (3465, 3482), True, 'import pickle as pkl\n')]
##################################################### # # Train and test a restricted Boltzmann machine # # Copyright (c) 2018 christianb93 # Permission is hereby granted, free of charge, to # any person obtaining a copy of this software and # associated documentation files (the "Software"), # to deal in the Software without restriction, # including without limitation the rights to use, # copy, modify, merge, publish, distribute, # sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice # shall be included in all copies or substantial # portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY # OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT # LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # If you want to run this on a machine without X-server, # do a # export MPLBACKEND="AGG" ##################################################### from __future__ import print_function import RBM.CD import RBM.PCD import pickle import socket import numpy as np import matplotlib.pyplot as plt import tempfile import argparse import time import datetime from sklearn.datasets import fetch_mldata import urllib.request from sklearn.datasets.base import get_data_home import os # # Utility class to generate a pattern from the bars-and-stripes # pattern set (MacKay, Information Theory, Inference and learning # algorithms, section 43) # class BAS: def __init__ (self, N = 4): self.N = N def createMatrix(self, orientation = 0, number = 0): # # Create a 4x4 matrix out of the bars-and-stripes # collection # values = np.zeros((self.N,1)) for i in range(self.N): values[i] = (number >> i) % 2 if (orientation == 0): return np.matmul(values, np.ones((1,self.N))) else: return np.transpose(np.matmul(values, np.ones((1,self.N)))) def createVector(self, orientation = 0, number = 0): M = self.createMatrix(orientation = orientation, number = number) return M.reshape((self.N*self.N,1)) # # Return a matrix with a given number of # samples. The result will be stored in a # matrix with shape (size, N*N) # def getSample(self, size = 30): if size > 2*(2**self.N) - 2: raise ValueError("Cannot generate that many samples") if 0 != (size % 2): raise ValueError("Number of samples must be even") images = [] for n in range(int(size / 2)): a = self.createVector(1,n+1) images.append(a) b = self.createVector(0,n+1) images.append(b) V = np.concatenate(images, axis=1) return np.transpose(V) # # A utility class to manage training data sets # that consist of quadratic images # class TrainingData: def __init__(self, N = 6, ds_size = 80, ds = "BAS"): self.ds = ds if ds == "BAS": self.BAS = BAS(args.N) self.ds_size = ds_size self.S = self.BAS.getSample(size = ds_size) elif ds == "MNIST": if (N != 28): raise ValueError("Please use N = 28 for the MNIST data set") try: mnist = fetch_mldata('MNIST originalss') except: print("Could not download MNIST data from mldata.org, trying alternative...") mnist_alternative_url = "https://github.com/amplab/datascience-sp14/raw/master/lab7/mldata/mnist-original.mat" data_home = get_data_home(data_home=None) data_home = os.path.join(data_home, 'mldata') if not os.path.exists(data_home): os.makedirs(data_home) mnist_save_path = os.path.join(data_home, "mnist-original.mat") if not os.path.exists(mnist_save_path): print("Downloading from ", mnist_alternative_url) urllib.request.urlretrieve(mnist_alternative_url, mnist_save_path) print("Now calling fetch_mldata once more") mnist = fetch_mldata('MNIST original') label = mnist['target'] mnist = mnist.data mnist = ((mnist / 255.0) + 0.5).astype(int) images = [] for i in range(ds_size): digit = i % 10 u = np.where(label == digit)[0] images.append(mnist[u[i // 10], None,:]) self.S = np.concatenate(images, axis=0) self.ds_size = ds_size else: raise ValueError("Unknown data set name") def get_batch(self, batch_size = 10): images = [] for i in range(batch_size): u = np.random.randint(low = 0, high = self.ds_size) images.append(self.S[u,None,:]) return np.concatenate(images, axis=0) #################################################### # Parse arguments #################################################### def get_args(): parser = argparse.ArgumentParser() parser.add_argument("--N", type=int, default=6, help="Size of image") parser.add_argument("--patterns", type=int, default=20, help="Number of patterns that we store") parser.add_argument("--hidden", type=int, default=16, help="Number of hidden units") parser.add_argument("--beta", type=float, default=2.0, help="Inverse temperature") parser.add_argument("--step", type=float, default=0.05, help="Step size of gradient descent") parser.add_argument("--iterations", type=int, default=1, help="Number of iterations per batch during training") parser.add_argument("--epochs", type=int, default=30000, help="Number of epochs (batches) during training") parser.add_argument("--sample", type=int, default=100, help="Number of iterations during sampling") parser.add_argument("--errors", type=int, default=3, help="Number of points in the sample pattern that we flip") parser.add_argument("--save", type=int, default=0, help="Save results") parser.add_argument("--run_samples", type=int, default=0, help="Run test samples from full model") parser.add_argument("--run_reconstructions", type=int, default=0, help="Run reconstruction tests") parser.add_argument("--show_weights", type=int, default=0, help="Display weights after training") parser.add_argument("--show_metrics", type=int, default=0, help="Display a few metrics after training") parser.add_argument("--algorithm", choices=["CD", "PCD", "PCDTF"], default="CD", help="Algorithm: contrastive divergence (CD), PCD or PCD on TensorFlow (PCDTF)") parser.add_argument("--batch_size", type=int, default=10, help="Batch size") parser.add_argument("--weight_decay", type=float, default=0.0001, help="Weight decay") parser.add_argument("--data", choices=["BAS", "MNIST"], default="BAS", help="Data set") parser.add_argument("--load", default=None) parser.add_argument("--precision", type=int, choices=[32,64], default=32, help="Floating point precision") parser.add_argument("--sample_size", type=str, default="5,5", help="X,Y: X- and Y-dimension of sampled set of images") parser.add_argument("--tmpdir", type=str, default="/tmp", help="Directory to use for storing results") args=parser.parse_args() return args # # Utility function to display an array # as an N x N binary image # def show_pattern(ax, v): ax.set_yticks([],[]) ax.set_xticks([],[]) ax.imshow(v.reshape(args.N,args.N), "binary") #################################################### # # Main # #################################################### # # Only import tensorflow if really needed # args=get_args() if args.algorithm == "PCDTF": import RBM.PCDTF print("Parameter: ", args) # # Create sample set # TrainingData = TrainingData(N = args.N, ds_size = args.patterns, ds = args.data) # # Init RBM and train # dw = [] error = [] if args.algorithm == "CD": RBM = RBM.CD.CDRBM(visible=args.N*args.N, hidden=args.hidden, beta = args.beta) elif args.algorithm == "PCD": RBM = RBM.PCD.PCDRBM(visible=args.N*args.N, hidden=args.hidden, beta = args.beta, particles=args.batch_size) elif args.algorithm == "PCDTF": RBM = RBM.PCDTF.PCDRBM(visible=args.N*args.N, hidden=args.hidden, beta = args.beta, particles=args.batch_size) else: raise ValueError("Unknown algorithm") start_time = time.time() print("Start time: ", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # # If the load parameter has not been specified, train # if None == args.load: for e in range(args.epochs): V = TrainingData.get_batch(batch_size = args.batch_size) _dw, _error = RBM.train(V, iterations=args.iterations, epochs = args.epochs, step = args.step, weight_decay=args.weight_decay) dw.append(_dw) if len(_error) > 0: error.append(_error) # # Allow the model to finalize the training # RBM.postTraining() else: print("Loading parameters from ", args.load) f= open(args.load, "rb") params = pickle.load(f) f.close() RBM.setParameters(params) end_time = time.time() run_time = end_time - start_time # # Get file name and save model # if args.save == 1: tmp = tempfile.mktemp(dir=args.tmpdir) params = RBM.getParameters() params['args'] = args outfile = tmp + "_RBM.param" f= open(outfile, "wb") pickle.dump(params, f) f.close() print("Saved parameters in ", outfile) # # Now test reconstructions # if args.run_reconstructions: tests = 8 cols = 4 fig = plt.figure(figsize=(5,cols*tests/5)) # # Determine a sample set that we use for testing # I = TrainingData.get_batch(batch_size = tests) # # Now plot the original patterns # for t in range(tests): show_pattern(fig.add_subplot(tests,cols,cols*t+1), I[t,:]) # # Flip some bits at random in each # of the rows # sample = np.copy(I) for t in range(tests): for i in range(args.errors): field = np.random.randint(0,args.N*args.N) sample[t,field] = (1 if I[t,field] == 0 else 0) # # Sample # print("Sampling reconstructions") R0 = RBM.sampleFrom(initial = sample, iterations = int(args.sample / 2), size=tests) R = RBM.sampleFrom(initial = R0, iterations = int(args.sample / 2), size=tests) # # Display results # for t in range(tests): # Display distorted image show_pattern(fig.add_subplot(tests,cols,cols*t+2), sample[t,:]) # Display reconstructions show_pattern(fig.add_subplot(tests,cols,cols*t+3), R0[t,:]) show_pattern(fig.add_subplot(tests,cols,cols*t+4), R[t,:]) if args.save == 1: outfile = tmp + "_RBMPartI.png" print("Saving simulation results part I to ",outfile) fig.savefig(outfile) # # Display metrics # if args.show_metrics == 1: fig = plt.figure(figsize=(10,5)) ax = fig.add_subplot(1,2,1) ax.set_xlabel("Iteration") ax.set_ylabel("Change of weights") ax.plot(dw) ax = fig.add_subplot(1,2,2) ax.plot(error,"y") ax.set_xlabel("Iteration") ax.set_ylabel("Reconstruction error") if args.save == 1: outfile = tmp + "_RBMPartII.png" print("Saving simulation results part II to ",outfile) fig.savefig(outfile) # # Now sample a few images and display them # if args.run_samples == 1: cols = int(args.sample_size.split(',')[1]) rows = int(args.sample_size.split(',')[0]) sampling_start_time = time.time() print("Sampling ", rows*cols, "images") print("Start time: ", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) V = RBM.sample(iterations = args.sample, size=rows*cols) fig = plt.figure(figsize=(8,8)) for i in range(rows*cols): show_pattern(fig.add_subplot(rows,cols,i+1), V[i,:]) end_time = time.time() run_time_sampling = end_time - sampling_start_time if args.save == 1: outfile = tmp + "_RBMPartIII.png" print("Saving simulation results part III to ",outfile) fig.savefig(outfile) # # Display weights # if args.show_weights == 1: fig = plt.figure(figsize=(10,10)) RBM.showWeights(fig, 4, 4, args.N, args.N) if args.save == 1: outfile = tmp + "_RBMPartIV.png" print("Saving simulation results part IV to ",outfile) fig.savefig(outfile) if args.save == 1: outfile = tmp + "_RBMDesc.txt" f= open(outfile, "w") print(args, file=f) print("Run time: ", str(datetime.timedelta(seconds=int(run_time))), file = f) if args.run_samples == 1: print("Run time sampling: ", str(datetime.timedelta(seconds=int(run_time_sampling))), file=f) name = socket.gethostname() print("Host: ", name, file=f) f.close() print("Saved simulation description and results in ",outfile) print("Run time: ", str(datetime.timedelta(seconds=int(run_time)))) if args.run_samples == 1: print("Run time sampling: ", str(datetime.timedelta(seconds=int(run_time_sampling)))) plt.show()
[ "pickle.dump", "argparse.ArgumentParser", "numpy.ones", "matplotlib.pyplot.figure", "pickle.load", "numpy.random.randint", "os.path.join", "numpy.copy", "numpy.transpose", "os.path.exists", "socket.gethostname", "tempfile.mktemp", "time.localtime", "matplotlib.pyplot.show", "numpy.concatenate", "os.makedirs", "numpy.zeros", "sklearn.datasets.base.get_data_home", "time.time", "numpy.where", "sklearn.datasets.fetch_mldata" ]
[((10345, 10356), 'time.time', 'time.time', ([], {}), '()\n', (10354, 10356), False, 'import time\n'), ((11189, 11200), 'time.time', 'time.time', ([], {}), '()\n', (11198, 11200), False, 'import time\n'), ((15172, 15182), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15180, 15182), True, 'import matplotlib.pyplot as plt\n'), ((5554, 5579), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5577, 5579), False, 'import argparse\n'), ((11118, 11132), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (11129, 11132), False, 'import pickle\n'), ((11299, 11331), 'tempfile.mktemp', 'tempfile.mktemp', ([], {'dir': 'args.tmpdir'}), '(dir=args.tmpdir)\n', (11314, 11331), False, 'import tempfile\n'), ((11455, 11477), 'pickle.dump', 'pickle.dump', (['params', 'f'], {}), '(params, f)\n', (11466, 11477), False, 'import pickle\n'), ((11633, 11674), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, cols * tests / 5)'}), '(figsize=(5, cols * tests / 5))\n', (11643, 11674), True, 'import matplotlib.pyplot as plt\n'), ((12015, 12025), 'numpy.copy', 'np.copy', (['I'], {}), '(I)\n', (12022, 12025), True, 'import numpy as np\n'), ((13013, 13040), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (13023, 13040), True, 'import matplotlib.pyplot as plt\n'), ((13647, 13658), 'time.time', 'time.time', ([], {}), '()\n', (13656, 13658), False, 'import time\n'), ((13854, 13880), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (13864, 13880), True, 'import matplotlib.pyplot as plt\n'), ((13987, 13998), 'time.time', 'time.time', ([], {}), '()\n', (13996, 13998), False, 'import time\n'), ((14279, 14307), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (14289, 14307), True, 'import matplotlib.pyplot as plt\n'), ((14844, 14864), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (14862, 14864), False, 'import socket\n'), ((2115, 2136), 'numpy.zeros', 'np.zeros', (['(self.N, 1)'], {}), '((self.N, 1))\n', (2123, 2136), True, 'import numpy as np\n'), ((3163, 3193), 'numpy.concatenate', 'np.concatenate', (['images'], {'axis': '(1)'}), '(images, axis=1)\n', (3177, 3193), True, 'import numpy as np\n'), ((3209, 3224), 'numpy.transpose', 'np.transpose', (['V'], {}), '(V)\n', (3221, 3224), True, 'import numpy as np\n'), ((5359, 5389), 'numpy.concatenate', 'np.concatenate', (['images'], {'axis': '(0)'}), '(images, axis=0)\n', (5373, 5389), True, 'import numpy as np\n'), ((10414, 10430), 'time.localtime', 'time.localtime', ([], {}), '()\n', (10428, 10430), False, 'import time\n'), ((5252, 5295), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': 'self.ds_size'}), '(low=0, high=self.ds_size)\n', (5269, 5295), True, 'import numpy as np\n'), ((12110, 12147), 'numpy.random.randint', 'np.random.randint', (['(0)', '(args.N * args.N)'], {}), '(0, args.N * args.N)\n', (12127, 12147), True, 'import numpy as np\n'), ((13764, 13780), 'time.localtime', 'time.localtime', ([], {}), '()\n', (13778, 13780), False, 'import time\n'), ((2278, 2298), 'numpy.ones', 'np.ones', (['(1, self.N)'], {}), '((1, self.N))\n', (2285, 2298), True, 'import numpy as np\n'), ((4983, 5013), 'numpy.concatenate', 'np.concatenate', (['images'], {'axis': '(0)'}), '(images, axis=0)\n', (4997, 5013), True, 'import numpy as np\n'), ((2363, 2383), 'numpy.ones', 'np.ones', (['(1, self.N)'], {}), '((1, self.N))\n', (2370, 2383), True, 'import numpy as np\n'), ((3747, 3779), 'sklearn.datasets.fetch_mldata', 'fetch_mldata', (['"""MNIST originalss"""'], {}), "('MNIST originalss')\n", (3759, 3779), False, 'from sklearn.datasets import fetch_mldata\n'), ((4049, 4078), 'sklearn.datasets.base.get_data_home', 'get_data_home', ([], {'data_home': 'None'}), '(data_home=None)\n', (4062, 4078), False, 'from sklearn.datasets.base import get_data_home\n'), ((4107, 4140), 'os.path.join', 'os.path.join', (['data_home', '"""mldata"""'], {}), "(data_home, 'mldata')\n", (4119, 4140), False, 'import os\n'), ((4268, 4313), 'os.path.join', 'os.path.join', (['data_home', '"""mnist-original.mat"""'], {}), "(data_home, 'mnist-original.mat')\n", (4280, 4313), False, 'import os\n'), ((4611, 4641), 'sklearn.datasets.fetch_mldata', 'fetch_mldata', (['"""MNIST original"""'], {}), "('MNIST original')\n", (4623, 4641), False, 'from sklearn.datasets import fetch_mldata\n'), ((4877, 4901), 'numpy.where', 'np.where', (['(label == digit)'], {}), '(label == digit)\n', (4885, 4901), True, 'import numpy as np\n'), ((4164, 4189), 'os.path.exists', 'os.path.exists', (['data_home'], {}), '(data_home)\n', (4178, 4189), False, 'import os\n'), ((4211, 4233), 'os.makedirs', 'os.makedirs', (['data_home'], {}), '(data_home)\n', (4222, 4233), False, 'import os\n'), ((4337, 4368), 'os.path.exists', 'os.path.exists', (['mnist_save_path'], {}), '(mnist_save_path)\n', (4351, 4368), False, 'import os\n')]
# -*- coding: UTF-8 -*- """ Created on Sat Jan 20 10:20:33 2018 @author: <NAME> """ import os, re, csv, time, warnings, threading from pymongo import MongoClient import pandas as pd import numpy as np from scipy.sparse import csr_matrix from bson.objectid import ObjectId import Text_Analysis.text_processing as tp from gensim import corpora, utils from sklearn import svm from sklearn.ensemble import RandomForestClassifier from sklearn.externals import joblib from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report import sklearn.exceptions from sklearn.preprocessing import OneHotEncoder warnings.filterwarnings("ignore", category=sklearn.exceptions.UndefinedMetricWarning) warnings.filterwarnings("ignore", category=Warning, module='sklearn') warnings.filterwarnings("ignore", category=UserWarning, module='gensim') warnings.filterwarnings("ignore", category=RuntimeWarning, module='gensim') class TextMining(object): '''Text analysis and prediction functions class. # Arguments: IP: IP address of mongodb database. PORT: Port number corresponding to IP. ''' def __init__(self,**kwarg): self.IP = kwarg['IP'] self.PORT = kwarg['PORT'] self.ConnDB() self.tp = tp.TextProcessing(os.getcwd() + '\\' + 'Chinese_Stop_Words.txt', \ os.getcwd() + '\\' + 'finance_dict.txt') if not os.path.exists(os.getcwd() + '\\' + 'stock_dict_file'): os.makedirs(os.getcwd() + '\\' + 'stock_dict_file') self.DictPath = os.getcwd() + '\\' + 'stock_dict_file' def ConnDB(self): '''Connect to the mongodb. ''' self._Conn = MongoClient(self.IP, self.PORT) def extractData(self,dbName,colName,tag_list): '''Extract data from specific collection of specific database. # Arguments: dbName: Name of database. colName: Name of collection. tag_list: List of tags that need to be extracted. ''' db = self._Conn[dbName] collection = db.get_collection(colName) data = [] Dict = {} for tag in tag_list: exec(tag + " = collection.distinct('" + tag + "')") exec("data.append(" + tag + ")") exec("Dict.update({'" + tag + "' : np.array(" + tag + ")})") dataFrame = pd.DataFrame(Dict,columns=tag_list) return dataFrame def extractStockCodeFromArticle(self,dbName,colName): '''Extract the stocks mentioned by each news(articles/documents). # Arguments: dbName: Name of database. colName: Name of collection. ''' db = self._Conn[dbName] collection = db.get_collection(colName) idLst = self.extractData(dbName,colName,['_id'])._id data = self.extractData("Stock","Basic_Info",['name','code']) articles = [] for _id in idLst: if dbName == 'NBD_Stock': title = collection.find_one({'_id':ObjectId(_id)})['title'] else: title = collection.find_one({'_id':ObjectId(_id)})['Title'] article = collection.find_one({'_id':ObjectId(_id)})['Article'] articles.append(title + ' ' + article) token, _, _ = self.tp.genDictionary(articles,saveDict=False, returnValue=True) j = 0 for tk in token: relevantStockName = [] relevantStockCode = [] for k in range(len(tk)): if len(tk[k]) >= 3 and tk[k] in list(data.name): relevantStockName.append(tk[k]) relevantStockCode.append(list(data[(data.name == tk[k])].code)[0]) if len(relevantStockCode) != 0: relevantStockCodeDuplicateRemoval = list(set(relevantStockCode)) collection.update({"_id":idLst[j]},{"$set":{"relevantStock":\ ' '.join(relevantStockCodeDuplicateRemoval)}}) # print(' [*] finished ' + str(j+1) + ' ... ') j += 1 def extractStockCodeFromRealtimeNews(self,documents): '''Extract stocks mentioined by real-time crawled news(articles/documents), and return the list of corresponding codes. # Arguments: documents: Real-time crawled news(articles/documents). ''' stock_basic_info = self.extractData("Stock","Basic_Info",['name','code']) token_list = self.tp.jieba_tokenize(documents) relevant_stock_list = [] for tokens in token_list: relevantStockCode = [] for tk in tokens: if len(tk) >= 3 and tk in list(stock_basic_info.name): relevantStockCode.append(list(stock_basic_info[(stock_basic_info.name == tk)].code)[0]) relevant_stock_list.append(list(set(relevantStockCode))) return relevant_stock_list def judgeGoodOrBadNews(self,stockCode,date,judgeTerm): '''Label the historical news(articles/documents) with 'Bad', 'Good' or 'Neutral'. # Arguments: stockCode: Code of specific stock. date: Date at which released the specific news. judgeTerm: Interval after which compare the close price with that at the released date. ''' db = self._Conn['Stock'] collection = db.get_collection(stockCode) dateLst = self.extractData("Stock",stockCode,['date']).date days = 0 CloseLst = [] for dt in dateLst: if dt >= date: CloseLst.append(float(collection.find_one({'date':dt})['close'])) if days >= judgeTerm: break days += 1 if CloseLst[-1] > CloseLst[0]: character = '利好' elif CloseLst[-1] < CloseLst[0]: character = '利空' else: character = '中立' return character def getNewsOfSpecificStock(self,dbColLst,stockCode,**kwarg): '''Get news related to specific stock from historical database. # Arguments: dbColLst: List of databases and collections, eg: [(db_1,col_1),(db_2,col_2),...,(db_N,col_N)]. stockCode: Code of specific stock. export: List parameters deciding the ways of exporting('csv' or 'database') and file path of saving, eg: export=['csv','.\\file']. ''' if kwarg['export'][0] == 'csv': with open(kwarg['export'][1] + '\\' + stockCode + '.csv', 'a+', newline='',encoding='utf-8') as file: fieldnames = ['date','address','title','article'] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() for dbName,colName in dbColLst: db = self._Conn[dbName] collection = db.get_collection(colName) idLst = self.extractData(dbName,colName,['_id'])._id if dbName == 'Sina_Stock': for _id in idLst: keys = ' '.join([k for k in collection.find_one({'_id':ObjectId(_id)}).keys()]) if keys.find('RelevantStock') != -1: if collection.find_one({'_id':ObjectId(_id)})['RelevantStock'].find(stockCode) != -1: print(' ' + collection.find_one({'_id':ObjectId(_id)})['Title']) writer.writerow({'date':collection.find_one({'_id':ObjectId(_id)})['Date'], \ 'address':collection.find_one({'_id':ObjectId(_id)})['Address'], \ 'title':collection.find_one({'_id':ObjectId(_id)})['Title'], \ 'article':collection.find_one({'_id':ObjectId(_id)})['Article']}) elif dbName == 'NBD': for _id in idLst: keys = ' '.join([k for k in collection.find_one({'_id':ObjectId(_id)}).keys()]) if keys.find('relevantStock') != -1: if collection.find_one({'_id':ObjectId(_id)})['relevantStock'].find(stockCode) != -1: print(' ' + collection.find_one({'_id':ObjectId(_id)})['title']) writer.writerow({'date':collection.find_one({'_id':ObjectId(_id)})['date'], \ 'address':collection.find_one({'_id':ObjectId(_id)})['address'], \ 'title':collection.find_one({'_id':ObjectId(_id)})['title'], \ 'article':collection.find_one({'_id':ObjectId(_id)})['Article']}) print(' [*] extracting ' + stockCode + ' news from ' + dbName + ' database to CSV file successfully ... ') elif kwarg['export'][0] == 'database': #new database for dbName,colName in dbColLst: db = self._Conn[dbName] collection = db.get_collection(colName) idLst = self.extractData(dbName,colName,['_id'])._id if dbName == 'NBD_Stock': newdb = self._Conn[kwarg['export'][1]] newcollection = newdb.get_collection(kwarg['export'][2]) for _id in idLst: keys = ' '.join([k for k in collection.find_one({'_id':ObjectId(_id)}).keys()]) if keys.find('relevantStock') != -1: if collection.find_one({'_id':ObjectId(_id)})['relevantStock'].find(stockCode) != -1: character = self.judgeGoodOrBadNews(stockCode,\ collection.find_one({'_id':ObjectId(_id)})['date'].split(' ')[0].replace('-',''),kwarg['judgeTerm']) # print(' ' + collection.find_one({'_id':ObjectId(_id)})['title'] + '(' + character + ')') data = {'Date' : collection.find_one({'_id':ObjectId(_id)})['date'], 'Address' : collection.find_one({'_id':ObjectId(_id)})['address'], 'Title' : collection.find_one({'_id':ObjectId(_id)})['title'], 'Article' : collection.find_one({'_id':ObjectId(_id)})['Article'], 'Character' : character} newcollection.insert_one(data) elif dbName == 'Sina_Stock': newdb = self._Conn[kwarg['export'][1]] newcollection = newdb.get_collection(kwarg['export'][2]) for _id in idLst: keys = ' '.join([k for k in collection.find_one({'_id':ObjectId(_id)}).keys()]) if keys.find('RelevantStock') != -1: if collection.find_one({'_id':ObjectId(_id)})['RelevantStock'].find(stockCode) != -1: character = self.judgeGoodOrBadNews(stockCode,\ collection.find_one({'_id':ObjectId(_id)})['Date'].split(' ')[0].replace('-',''),kwarg['judgeTerm']) # print(' ' + collection.find_one({'_id':ObjectId(_id)})['Title'] + '(' + character + ')') data = {'Date' : collection.find_one({'_id':ObjectId(_id)})['Date'], 'Address' : collection.find_one({'_id':ObjectId(_id)})['Address'], 'Title' : collection.find_one({'_id':ObjectId(_id)})['Title'], 'Article' : collection.find_one({'_id':ObjectId(_id)})['Article'], 'Character' : character} newcollection.insert_one(data) else: newdb = self._Conn[kwarg['export'][1]] newcollection = newdb.get_collection(kwarg['export'][2]) for _id in idLst: keys = ' '.join([k for k in collection.find_one({'_id':ObjectId(_id)}).keys()]) if keys.find('relevantStock') != -1: if collection.find_one({'_id':ObjectId(_id)})['relevantStock'].find(stockCode) != -1: character = self.judgeGoodOrBadNews(stockCode,\ collection.find_one({'_id':ObjectId(_id)})['Date'].split(' ')[0].replace('-',''),kwarg['judgeTerm']) # print(' ' + collection.find_one({'_id':ObjectId(_id)})['Title'] + '(' + character + ')') data = {'Date' : collection.find_one({'_id':ObjectId(_id)})['Date'], 'Address' : collection.find_one({'_id':ObjectId(_id)})['Address'], 'Title' : collection.find_one({'_id':ObjectId(_id)})['Title'], 'Article' : collection.find_one({'_id':ObjectId(_id)})['Article'], 'Character' : character} newcollection.insert_one(data) print(' [' + stockCode + '] ' + dbName + ' has been extracted successfully ... ') def classifyHistoryStockNews(self,dbName,stockCode,**kwarg): '''Build classifier from historical news(articles/documents) of specific stock. # Arguments: dbName: Name of database. stockCode: Code of specific stock. renewDict: Renew the dictionary created by historical news(articles/documents) of specific stock or not(bool type). modelType: Transformation model type, including 'lsi', 'lda' and 'None', 'None' means TF-IDF mmodel. tfDim: The number of topics that will be extracted from each news(articles/documents). renewModel: Re-train the transformation models or not(bool type). Classifier: The name of classifier, including 'SVM' and 'RandomForest' so far. Params: The parameters of classifier, detail refer to the setting of classifier parameters of scikit-learn module. ''' if kwarg['renewDict']: if not os.path.exists(self.DictPath+'\\'+stockCode): os.makedirs(self.DictPath+'\\'+stockCode) db = self._Conn[dbName] collection = db.get_collection(stockCode) idLst = self.extractData(dbName,stockCode,['_id'])._id articles = [] characters = [] for _id in idLst: articles.append(collection.find_one({'_id':ObjectId(_id)})['Article']) if collection.find_one({'_id':ObjectId(_id)})['Character'] == "利好": characters.append(1) elif collection.find_one({'_id':ObjectId(_id)})['Character'] == "利空": characters.append(-1) else: characters.append(0) self.tp.genDictionary(articles,saveDict=True,saveDictPath=self.DictPath+'\\'+stockCode+'\\'+stockCode+'_dict.dict',\ saveBowvec=True,saveBowvecPath=self.DictPath+'\\'+stockCode+'\\'+stockCode+'_bowvec.mm',returnValue=False) print(' [*] renew the dictionary and bow-vector successfully ... ') elif not os.path.exists(self.DictPath+'\\'+stockCode+'\\'+stockCode+'_dict.dict') \ or not os.path.exists(self.DictPath+'\\'+stockCode+'\\'+stockCode+'_bowvec.mm'): if not os.path.exists(self.DictPath+'\\'+stockCode): os.makedirs(self.DictPath+'\\'+stockCode) db = self._Conn[dbName] collection = db.get_collection(stockCode) idLst = self.extractData(dbName,stockCode,['_id'])._id articles = [] characters = [] for _id in idLst: articles.append(collection.find_one({'_id':ObjectId(_id)})['Article']) if collection.find_one({'_id':ObjectId(_id)})['Character'] == "利好": characters.append(1) elif collection.find_one({'_id':ObjectId(_id)})['Character'] == "利空": characters.append(-1) else: characters.append(0) self.tp.genDictionary(articles,saveDict=True,saveDictPath=self.DictPath+'\\'+stockCode+'\\'+stockCode+'_dict.dict',\ saveBowvec=True,saveBowvecPath=self.DictPath+'\\'+stockCode+'\\'+stockCode+'_bowvec.mm',returnValue=False) print(' [*] generate and save the dictionary and bow-vector successfully ... ') else: db = self._Conn[dbName] collection = db.get_collection(stockCode) idLst = self.extractData(dbName,stockCode,['_id'])._id characters = [] for _id in idLst: if collection.find_one({'_id':ObjectId(_id)})['Character'] == "利好": characters.append(1) elif collection.find_one({'_id':ObjectId(_id)})['Character'] == "利空": characters.append(-1) else: characters.append(0) dictionary = corpora.Dictionary.load(self.DictPath+'\\'+stockCode+'\\'+stockCode+'_dict.dict') bowvec = corpora.MmCorpus(self.DictPath+'\\'+stockCode+'\\'+stockCode+'_bowvec.mm') print(' [*] load dictionary and bow-vector successfully ... ') _, modelVec = self.tp.CallTransformationModel(dictionary,bowvec,modelType=kwarg['modelType'],\ tfDim=kwarg['tfDim'],renewModel=kwarg['renewModel'],modelPath=self.DictPath+'\\'+stockCode+'\\') CSRMatrix = self.ConvertToCSRMatrix(modelVec) train_X, train_Y, test_X, test_Y = self.genTrainingSet(CSRMatrix,characters) if kwarg['Classifier'] == 'SVM': self.SVMClassifier(train_X,train_Y,test_X,test_Y,kwarg['Params'],['precision'],stockCode) if kwarg['Classifier'] == 'RandomForest': self.RdForestClassifier(train_X,train_Y,test_X,test_Y,kwarg['Params'],['precision'],stockCode) return self._precise def classifyRealtimeStockNews(self,doc_list): '''Classify real-time news(articles/documents) of specific stock. #Arguments: doc_list: List of real-time news(articles/documents) crawled from specific websites. ''' print(' * extract relevant stock codes from latest crawled news ... ') relevant_stock_list = self.extractStockCodeFromRealtimeNews(doc_list) if len(relevant_stock_list) != 0: tfDim = 200 for i, code_list in enumerate(relevant_stock_list): for code in code_list: print(' * load SVM parameters (gamma & C) ... ') Params_svm = {'kernel': ['rbf'], 'gamma': [10, 20, 50, 100, 150, 200], \ 'C': [10, 15, 20, 30, 50, 100]} print(' * use historical news to build SVM model of ' + code + ' ... ') self.classifyHistoryStockNews("Stock_News",code,modelType='lda',tfDim=tfDim,renewDict=False,\ renewModel=False,Classifier='SVM',Params=Params_svm) #code="600740" print(' * load historical dictionary of ' + code + ' ...') dictionary = corpora.Dictionary.load(os.getcwd() + '\\' + 'stock_dict_file\\' + code + '\\' + code + '_dict.dict') print(' * tokenize latest crawled news ... ') token = self.tp.jieba_tokenize(doc_list) print(' * create bow-vector of latest news of ' + code + ' ... ') bowvec_doc = [dictionary.doc2bow(text) for text in token] print(' * load bow-vector of historical news of ' + code + ' ... ') bowvec_all = list(corpora.MmCorpus(os.getcwd() + '\\' + 'stock_dict_file\\' + code + '\\' + code + '_bowvec.mm')) print(' * extend latest bow-vector to historical bow-vector of ' + code + ' ... ') bowvec_all.extend(bowvec_doc) print(' * create new lda model of ' + code + ' ... ') _, NewmodelVec = self.tp.CallTransformationModel(dictionary,bowvec_all,modelType='lda',\ tfDim=200,renewModel=False,modelPath=os.getcwd() + '\\' + 'stock_dict_file\\' + code + '\\') print(' * convert latest lda vector to CSR matrix of ' + code + ' ... ') NewCSRMatrix = self.ConvertToCSRMatrix(NewmodelVec) print(' * load SVM model of ' + code + ' ... ') clf = joblib.load(os.getcwd() + '\\' + 'stock_dict_file\\' + code + '\\' + code + '_svm.pkl') print(' * predicting ... ') if clf.predict(NewCSRMatrix[i-2,:])[0] == 1: print(' 《' + doc_list[i].split(' ')[0] + "》" + '对' + code + '是利好消息 ...') elif clf.predict(NewCSRMatrix[i-2,:])[0] == -1: print(' 《' + doc_list[i].split(' ')[0] + "》" + '对' + code + '是利空消息 ...') else: print(' 《' + doc_list[i].split(' ')[0] + "》" + '对' + code + '是中立消息 ...') else: print(' * not any relevant stock ... ') def SVMClassifier(self,train_X,train_Y,test_X,test_Y,tuned_parameters,scores,stockCode): '''SVM Classifier. # Arguments: train_X: Features train data. train_Y: Labels train data. test_X: Features train data. test_Y: Labels train data. tuned_parameters: The parameters of classifier, refer to the setting of classifier parameters of scikit-learn module. scores: Targets of optimization, detail refer to optimal targets setting of scikit-learn module. stockCode: Code of specific stock. ''' for score in scores: if not os.path.exists(self.DictPath+'\\'+stockCode+'\\'+stockCode+'_svm.pkl'): clf = GridSearchCV(svm.SVC(), tuned_parameters, cv=5, scoring='%s_weighted' % score) # 构造这个GridSearch的分类器,5-fold clf.fit(train_X, train_Y) # 只在训练集上面做k-fold,然后返回最优的模型参数 joblib.dump(clf, self.DictPath+'\\'+stockCode+'\\'+stockCode+'_svm.pkl') print(clf.best_params_) # 输出最优的模型参数 else: clf = joblib.load(self.DictPath+'\\'+stockCode+'\\'+stockCode+'_svm.pkl') # for params, mean_score, scores in clf.grid_scores_: # print("%0.3f (+/-%0.03f) for %r" % (mean_score, scores.std() * 2, params)) train_pred = clf.predict(train_X) test_pred = clf.predict(test_X) # 在测试集上测试最优的模型的泛化能力. print(classification_report(test_Y, test_pred)) precise_train = 0 for k in range(len(train_pred)): if train_pred[k] == train_Y[k]: precise_train += 1 precise_test = 0 for k in range(len(test_pred)): if test_pred[k] == test_Y[k]: precise_test += 1 print(' [*] train_pred:', precise_train/len(train_Y), ', test_pred:', precise_test/len(test_pred)) print(' ' + '-' * 50) self._precise = precise_test/len(test_pred) def RdForestClassifier(self,train_X,train_Y,test_X,test_Y,tuned_parameters,scores,stockCode): '''Random Forest Classifier. # Arguments: train_X: Features train data. train_Y: Labels train data. test_X: Features train data. test_Y: Labels train data. tuned_parameters: The parameters of classifier, refer to the setting of classifier parameters of scikit-learn module. scores: Targets of optimization, detail refer to optimal targets setting of scikit-learn module. stockCode: Code of specific stock. ''' for score in scores: if not os.path.exists(self.DictPath+'\\'+stockCode+'\\'+stockCode+'_rdf.pkl'): clf = GridSearchCV(RandomForestClassifier(random_state=14), tuned_parameters, cv=5, scoring='%s_weighted' % score) # 构造这个GridSearch的分类器,5-fold clf.fit(train_X, train_Y) # 只在训练集上面做k-fold,然后返回最优的模型参数 joblib.dump(clf, self.DictPath+'\\'+stockCode+'\\'+stockCode+'_rdf.pkl') print(clf.best_params_) # 输出最优的模型参数 else: clf = joblib.load(self.DictPath+'\\'+stockCode+'\\'+stockCode+'_rdf.pkl') # for params, mean_score, scores in clf.grid_scores_: # print("%0.3f (+/-%0.03f) for %r" % (mean_score, scores.std() * 2, params)) train_pred = clf.predict(train_X) test_pred = clf.predict(test_X) # 在测试集上测试最优的模型的泛化能力. print(classification_report(test_Y, test_pred)) precise_train = 0 for k in range(len(train_pred)): if train_pred[k] == train_Y[k]: precise_train += 1 precise_test = 0 for k in range(len(test_pred)): if test_pred[k] == test_Y[k]: precise_test += 1 print(' [*] train_pred:', precise_train/len(train_Y), ', test_pred:', precise_test/len(test_pred)) print(' ' + '-' * 50) self._precise = precise_test/len(test_pred) def ConvertToCSRMatrix(self,modelVec): '''Convert LDA(LSI) model vector to CSR sparse matrix, that could be accepted by Scipy and Numpy. # Arguments: modelVec: Transformation model vector, such as LDA model vector, tfidf model vector or lsi model vector. ''' data = [] rows = [] cols = [] self._line_count = 0 for line in modelVec: for elem in line: rows.append(self._line_count) cols.append(elem[0]) data.append(elem[1]) self._line_count += 1 sparse_matrix = csr_matrix((data,(rows,cols))) matrix = sparse_matrix.toarray() return matrix def genTrainingSet(self,X,Y): '''Generate training data set. # Arguments: X: Feature set. Y: Label set. ''' rarray=np.random.random(size=self._line_count) train_X = [] train_Y = [] test_X = [] test_Y = [] for i in range(self._line_count): if rarray[i]<0.8: train_X.append(X[i,:]) train_Y.append(Y[i]) else: test_X.append(X[i,:]) test_Y.append(Y[i]) return train_X,train_Y,test_X,test_Y
[ "pymongo.MongoClient", "pandas.DataFrame", "sklearn.externals.joblib.dump", "sklearn.ensemble.RandomForestClassifier", "os.makedirs", "bson.objectid.ObjectId", "warnings.filterwarnings", "os.getcwd", "sklearn.svm.SVC", "os.path.exists", "sklearn.metrics.classification_report", "sklearn.externals.joblib.load", "scipy.sparse.csr_matrix", "numpy.random.random", "gensim.corpora.MmCorpus", "gensim.corpora.Dictionary.load", "csv.DictWriter" ]
[((665, 755), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'sklearn.exceptions.UndefinedMetricWarning'}), "('ignore', category=sklearn.exceptions.\n UndefinedMetricWarning)\n", (688, 755), False, 'import os, re, csv, time, warnings, threading\n'), ((752, 821), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'Warning', 'module': '"""sklearn"""'}), "('ignore', category=Warning, module='sklearn')\n", (775, 821), False, 'import os, re, csv, time, warnings, threading\n'), ((823, 895), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'UserWarning', 'module': '"""gensim"""'}), "('ignore', category=UserWarning, module='gensim')\n", (846, 895), False, 'import os, re, csv, time, warnings, threading\n'), ((897, 972), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'RuntimeWarning', 'module': '"""gensim"""'}), "('ignore', category=RuntimeWarning, module='gensim')\n", (920, 972), False, 'import os, re, csv, time, warnings, threading\n'), ((1641, 1672), 'pymongo.MongoClient', 'MongoClient', (['self.IP', 'self.PORT'], {}), '(self.IP, self.PORT)\n', (1652, 1672), False, 'from pymongo import MongoClient\n'), ((2226, 2262), 'pandas.DataFrame', 'pd.DataFrame', (['Dict'], {'columns': 'tag_list'}), '(Dict, columns=tag_list)\n', (2238, 2262), True, 'import pandas as pd\n'), ((14377, 14472), 'gensim.corpora.Dictionary.load', 'corpora.Dictionary.load', (["(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_dict.dict')"], {}), "(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode +\n '_dict.dict')\n", (14400, 14472), False, 'from gensim import corpora, utils\n'), ((14471, 14559), 'gensim.corpora.MmCorpus', 'corpora.MmCorpus', (["(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_bowvec.mm')"], {}), "(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode +\n '_bowvec.mm')\n", (14487, 14559), False, 'from gensim import corpora, utils\n'), ((21985, 22017), 'scipy.sparse.csr_matrix', 'csr_matrix', (['(data, (rows, cols))'], {}), '((data, (rows, cols)))\n', (21995, 22017), False, 'from scipy.sparse import csr_matrix\n'), ((22212, 22251), 'numpy.random.random', 'np.random.random', ([], {'size': 'self._line_count'}), '(size=self._line_count)\n', (22228, 22251), True, 'import numpy as np\n'), ((1527, 1538), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1536, 1538), False, 'import os, re, csv, time, warnings, threading\n'), ((5897, 5940), 'csv.DictWriter', 'csv.DictWriter', (['file'], {'fieldnames': 'fieldnames'}), '(file, fieldnames=fieldnames)\n', (5911, 5940), False, 'import os, re, csv, time, warnings, threading\n'), ((11926, 11974), 'os.path.exists', 'os.path.exists', (["(self.DictPath + '\\\\' + stockCode)"], {}), "(self.DictPath + '\\\\' + stockCode)\n", (11940, 11974), False, 'import os, re, csv, time, warnings, threading\n'), ((11977, 12022), 'os.makedirs', 'os.makedirs', (["(self.DictPath + '\\\\' + stockCode)"], {}), "(self.DictPath + '\\\\' + stockCode)\n", (11988, 12022), False, 'import os, re, csv, time, warnings, threading\n'), ((18546, 18631), 'os.path.exists', 'os.path.exists', (["(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_svm.pkl')"], {}), "(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_svm.pkl'\n )\n", (18560, 18631), False, 'import os, re, csv, time, warnings, threading\n'), ((18801, 18887), 'sklearn.externals.joblib.dump', 'joblib.dump', (['clf', "(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_svm.pkl')"], {}), "(clf, self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode +\n '_svm.pkl')\n", (18812, 18887), False, 'from sklearn.externals import joblib\n'), ((18936, 19013), 'sklearn.externals.joblib.load', 'joblib.load', (["(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_svm.pkl')"], {}), "(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_svm.pkl')\n", (18947, 19013), False, 'from sklearn.externals import joblib\n'), ((19251, 19291), 'sklearn.metrics.classification_report', 'classification_report', (['test_Y', 'test_pred'], {}), '(test_Y, test_pred)\n', (19272, 19291), False, 'from sklearn.metrics import classification_report\n'), ((20281, 20366), 'os.path.exists', 'os.path.exists', (["(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_rdf.pkl')"], {}), "(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_rdf.pkl'\n )\n", (20295, 20366), False, 'import os, re, csv, time, warnings, threading\n'), ((20566, 20652), 'sklearn.externals.joblib.dump', 'joblib.dump', (['clf', "(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_rdf.pkl')"], {}), "(clf, self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode +\n '_rdf.pkl')\n", (20577, 20652), False, 'from sklearn.externals import joblib\n'), ((20701, 20778), 'sklearn.externals.joblib.load', 'joblib.load', (["(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_rdf.pkl')"], {}), "(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_rdf.pkl')\n", (20712, 20778), False, 'from sklearn.externals import joblib\n'), ((21016, 21056), 'sklearn.metrics.classification_report', 'classification_report', (['test_Y', 'test_pred'], {}), '(test_Y, test_pred)\n', (21037, 21056), False, 'from sklearn.metrics import classification_report\n'), ((1292, 1303), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1301, 1303), False, 'import os, re, csv, time, warnings, threading\n'), ((1345, 1356), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1354, 1356), False, 'import os, re, csv, time, warnings, threading\n'), ((12846, 12932), 'os.path.exists', 'os.path.exists', (["(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_dict.dict')"], {}), "(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode +\n '_dict.dict')\n", (12860, 12932), False, 'import os, re, csv, time, warnings, threading\n'), ((12931, 13017), 'os.path.exists', 'os.path.exists', (["(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode + '_bowvec.mm')"], {}), "(self.DictPath + '\\\\' + stockCode + '\\\\' + stockCode +\n '_bowvec.mm')\n", (12945, 13017), False, 'import os, re, csv, time, warnings, threading\n'), ((13016, 13064), 'os.path.exists', 'os.path.exists', (["(self.DictPath + '\\\\' + stockCode)"], {}), "(self.DictPath + '\\\\' + stockCode)\n", (13030, 13064), False, 'import os, re, csv, time, warnings, threading\n'), ((13067, 13112), 'os.makedirs', 'os.makedirs', (["(self.DictPath + '\\\\' + stockCode)"], {}), "(self.DictPath + '\\\\' + stockCode)\n", (13078, 13112), False, 'import os, re, csv, time, warnings, threading\n'), ((18642, 18651), 'sklearn.svm.SVC', 'svm.SVC', ([], {}), '()\n', (18649, 18651), False, 'from sklearn import svm\n'), ((20377, 20416), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'random_state': '(14)'}), '(random_state=14)\n', (20399, 20416), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((1411, 1422), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1420, 1422), False, 'import os, re, csv, time, warnings, threading\n'), ((1468, 1479), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1477, 1479), False, 'import os, re, csv, time, warnings, threading\n'), ((2937, 2950), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (2945, 2950), False, 'from bson.objectid import ObjectId\n'), ((2796, 2809), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (2804, 2809), False, 'from bson.objectid import ObjectId\n'), ((2871, 2884), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (2879, 2884), False, 'from bson.objectid import ObjectId\n'), ((12260, 12273), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (12268, 12273), False, 'from bson.objectid import ObjectId\n'), ((12323, 12336), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (12331, 12336), False, 'from bson.objectid import ObjectId\n'), ((12425, 12438), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (12433, 12438), False, 'from bson.objectid import ObjectId\n'), ((13350, 13363), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (13358, 13363), False, 'from bson.objectid import ObjectId\n'), ((13413, 13426), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (13421, 13426), False, 'from bson.objectid import ObjectId\n'), ((14155, 14168), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (14163, 14168), False, 'from bson.objectid import ObjectId\n'), ((13515, 13528), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (13523, 13528), False, 'from bson.objectid import ObjectId\n'), ((14257, 14270), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (14265, 14270), False, 'from bson.objectid import ObjectId\n'), ((17159, 17170), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (17168, 17170), False, 'import os, re, csv, time, warnings, threading\n'), ((16295, 16306), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (16304, 16306), False, 'import os, re, csv, time, warnings, threading\n'), ((17444, 17455), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (17453, 17455), False, 'import os, re, csv, time, warnings, threading\n'), ((8552, 8565), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (8560, 8565), False, 'from bson.objectid import ObjectId\n'), ((8627, 8640), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (8635, 8640), False, 'from bson.objectid import ObjectId\n'), ((8703, 8716), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (8711, 8716), False, 'from bson.objectid import ObjectId\n'), ((8779, 8792), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (8787, 8792), False, 'from bson.objectid import ObjectId\n'), ((16739, 16750), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (16748, 16750), False, 'import os, re, csv, time, warnings, threading\n'), ((6260, 6273), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (6268, 6273), False, 'from bson.objectid import ObjectId\n'), ((6369, 6382), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (6377, 6382), False, 'from bson.objectid import ObjectId\n'), ((6478, 6491), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (6486, 6491), False, 'from bson.objectid import ObjectId\n'), ((6565, 6578), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (6573, 6578), False, 'from bson.objectid import ObjectId\n'), ((6640, 6653), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (6648, 6653), False, 'from bson.objectid import ObjectId\n'), ((6716, 6729), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (6724, 6729), False, 'from bson.objectid import ObjectId\n'), ((6792, 6805), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (6800, 6805), False, 'from bson.objectid import ObjectId\n'), ((8060, 8073), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (8068, 8073), False, 'from bson.objectid import ObjectId\n'), ((8167, 8180), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (8175, 8180), False, 'from bson.objectid import ObjectId\n'), ((9604, 9617), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (9612, 9617), False, 'from bson.objectid import ObjectId\n'), ((9679, 9692), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (9687, 9692), False, 'from bson.objectid import ObjectId\n'), ((9755, 9768), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (9763, 9768), False, 'from bson.objectid import ObjectId\n'), ((9831, 9844), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (9839, 9844), False, 'from bson.objectid import ObjectId\n'), ((10632, 10645), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (10640, 10645), False, 'from bson.objectid import ObjectId\n'), ((10707, 10720), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (10715, 10720), False, 'from bson.objectid import ObjectId\n'), ((10783, 10796), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (10791, 10796), False, 'from bson.objectid import ObjectId\n'), ((10859, 10872), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (10867, 10872), False, 'from bson.objectid import ObjectId\n'), ((6937, 6950), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (6945, 6950), False, 'from bson.objectid import ObjectId\n'), ((7046, 7059), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (7054, 7059), False, 'from bson.objectid import ObjectId\n'), ((7155, 7168), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (7163, 7168), False, 'from bson.objectid import ObjectId\n'), ((7242, 7255), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (7250, 7255), False, 'from bson.objectid import ObjectId\n'), ((7317, 7330), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (7325, 7330), False, 'from bson.objectid import ObjectId\n'), ((7393, 7406), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (7401, 7406), False, 'from bson.objectid import ObjectId\n'), ((7469, 7482), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (7477, 7482), False, 'from bson.objectid import ObjectId\n'), ((9112, 9125), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (9120, 9125), False, 'from bson.objectid import ObjectId\n'), ((9219, 9232), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (9227, 9232), False, 'from bson.objectid import ObjectId\n'), ((10140, 10153), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (10148, 10153), False, 'from bson.objectid import ObjectId\n'), ((10247, 10260), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (10255, 10260), False, 'from bson.objectid import ObjectId\n'), ((8317, 8330), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (8325, 8330), False, 'from bson.objectid import ObjectId\n'), ((9369, 9382), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (9377, 9382), False, 'from bson.objectid import ObjectId\n'), ((10397, 10410), 'bson.objectid.ObjectId', 'ObjectId', (['_id'], {}), '(_id)\n', (10405, 10410), False, 'from bson.objectid import ObjectId\n')]
from dash import dcc, html, Input, Output, callback, dash_table import dash_bootstrap_components as dbc import plotly.express as px import pandas as pd import numpy as np from pages.sas_key import get_df_description from pages.style import PADDING_STYLE TEXT_STYLE = { 'textAlign':'center', 'width': '70%', 'margin': '0 auto', 'background-color': 'AliceBlue', 'color': 'Blue' } layout =html.Div([ html.H1('Subreddit Information',style={'textAlign':'center'}), html.Div([ html.H3(id="factssubredditprinter", className="display-6 text-center"), html.P('Here, you can check out more in formation about the subreddit. A snapshot of posts and their comments can be previewed along with the popularity and size of the subreddit selected. We have collected data on about 1,000 most recent posts and about 10,000 comments categorized as "hot" by Reddit for each subreddit (this might vary accordingly as posts/commets that were removed or deleted are not included in our analysis). Comment threads can be as long as a 100 comments per post due to API limitations.', className = 'fs-4 text-center'), html.Hr(), ]), dbc.Card(style=PADDING_STYLE, children=[ html.H5("Subreddit Description"), html.Div(className='row', children=[ dcc.Loading(children=[ ### Description html.Div(className="six columns", children=[ html.P(id='subredditdescription', style=TEXT_STYLE), ]), ### Fact Table html.Div(className="six columns", children=[ dash_table.DataTable(id="subredditfacts", style_header={'font-weight': 'bold'}, style_cell={'font-family':'sans-serif', 'font-size': '14px', 'text-align': 'center'}, style_data={'whiteSpace': 'normal', 'height': 'auto'}) ]) ]), ]) ]), ### Posts Table dbc.Card([ html.H5("Post Data Preview", className="card-title"), dcc.Loading(children=[ # html.H5("Post Data Preview", style=TEXT_STYLE), dash_table.DataTable(id="subreddittable", page_size=5, # fixed_rows={'headers': True}, style_header={'font-weight': 'bold'}, style_data={'whiteSpace': 'normal'}, columns=[{'name': 'Post ID', 'id': 'Post ID'}, {'name': 'Post Title', 'id': 'Post Title'}, {'name': 'Post Body', 'id': 'Post Body'}], style_cell={ 'font-family':'sans-serif', 'textAlign': 'left', 'font-size': '14px', 'padding-top': '3px', 'padding-bottom': '8px', 'padding-left': '8px', 'padding-right': '8px', }, css=[{ 'selector': '.dash-spreadsheet td div', 'rule': ''' line-height: 15px; max-height: 75px; min-height: 33px; display: block; overflow-y: auto; ''' }] ), ]), # ], style=PADDING_STYLE), ### End of table ### Comments Table # dbc.Card([ html.H5("Comments Data Preview", className="card-title"), dcc.Loading(children=[ # html.H5("Comments Data Preview", style=TEXT_STYLE), # html.P("Click a post in the above Post Table to view comments for that post", style=TEXT_STYLE), html.P("Click a post in the above Post Table to view comments for that post", style=TEXT_STYLE), dash_table.DataTable(id="subredditcommenttable", page_size=5, # fixed_rows={'headers': True}, style_header={'font-weight': 'bold'}, style_data={'whiteSpace': 'normal'}, style_cell={ 'font-family':'sans-serif', 'textAlign': 'left', 'font-size': '14px', 'padding-top': '3px', 'padding-bottom': '8px', 'padding-left': '8px', 'padding-right': '8px', }, css=[{ 'selector': '.dash-spreadsheet td div', 'rule': ''' line-height: 15px; max-height: 75px; min-height: 33px; display: block; overflow-y: auto; ''' }] ) ]) ], style=PADDING_STYLE), ### End of table ### Score Frequency Plots dbc.Card([ html.H5("Popularity", className="card-title"), html.P('Score indicates the net total upvotes versus downvotes for a submission (post/comment), hence showing us Popularity.', className = 'card-subtitle'), html.Div(className='row', children=[ dcc.Loading(children=[ html.Div([ ### Post Score Plot html.Div(className="six columns", children=[ dcc.Graph(id='facts1'), # dcc.RangeSlider(0, 20, 1, value=[5, 15], id='my-range-slider'), ]), ### Comment Score Plot html.Div(className="six columns", children=[ dcc.Graph(id="facts2"), ]) ]), ]), ]), ], style=PADDING_STYLE), ### End of plot ### Word Count Frequency Plots dcc.Loading(children=[ html.Div(id='facts3'), ]) # dbc.Card([ # html.H5("Size", className="card-title"), # html.P('Word-count per submission shows us Size.', className = 'fs-4'), # html.Div(className='row', children=[ # dcc.Loading(children=[ # html.Div([ # ### Post Word Count Plot # html.Div(className="six columns", children=[ # dcc.Graph(id='facts3'), # ]), # ### Comment Word Count Plot # html.Div(className="six columns", children=[ # dcc.Graph(id="facts4"), # ]) # ]), # ]), # ]), # ], style=PADDING_STYLE), ### End of plot ]) @callback( Output('factssubredditprinter', 'children'), Output('subredditdescription', 'children'), Output('subredditfacts', 'data'), Output('subreddittable', 'data'), Output('facts1', 'figure'), Output('facts2', 'figure'), Output('facts3', 'children'), Input('session', 'data'), Input('session2', 'data'), ) def update_df(data, value): try: # Load the data df = pd.DataFrame(data) subreddit = df.at[0, 'subreddit'] subreddit_df = get_df_description(value) # Obtain description of the subreddit description = subreddit_df.at[0, 'description'] # Posts Table post_df = df[['post_id', 'post_title', 'post_body', 'post_score']].groupby('post_id', as_index=False, sort=False).first() post_df['id'] = post_df.post_id # post_df.rename(columns={'post_id': 'Post Id', 'post_title': 'Post Title', 'post_body': 'Post Body'}, inplace=True) # Quick Facts Table number_of_posts = len(post_df) number_of_comments = len(df) facts = [{ "Number of hot posts scraped": number_of_posts, "Number of hot comments scraped": number_of_comments, "Number of subscribers": subreddit_df.at[0, 'subscribers'] }] # Post Score Plot def reject_outliers(data, n=2.): # data = data[~np.isnan(data)] d = np.abs(data - np.median(data)) mdev = np.median(d) s = d/mdev if mdev else 0. return data[s<n].flatten() post_scores = post_df['post_score'].to_numpy() post_scores = reject_outliers(post_scores) posts_score_hist = px.histogram(post_scores, title='Frequency Distribution of Post Score', labels={'value':'Score', 'count':'Number of Posts', 'variable':'Score'}, opacity=0.8, color_discrete_sequence=['indianred'], text_auto=True).update_layout( xaxis_title="Score", yaxis_title="Number of Posts", showlegend=False) # Comment Score Plot comment_scores = df['comment_score'].dropna().to_numpy() comment_scores = reject_outliers(comment_scores) comms_score_hist = px.histogram(comment_scores, labels={'value':'Score', 'variable':'Score'}, log_y=True, title='Frequency Distribution of Comment Score', opacity=0.8).update_layout(yaxis_title="Number of Comments (log scale)", showlegend=False) post_df.dropna(inplace=True, subset=['post_title', 'post_body']) df.dropna(inplace=True, subset=['comment']) try: post_df['word_counts'] = post_df.post_title.str.cat(post_df.post_body, sep=" ").str.split().apply(len) df['word_counts'] = df.comment.astype(str).str.split().apply(len) # Post Word Count Distribution post_word = post_df['word_counts'].dropna().to_numpy() post_word = reject_outliers(post_word) post_word_count = px.histogram(post_word, title='Word-Count Distribution for Posts', labels={'value':'Word Count', 'count':'Number of Posts', 'variable':'Word Count'}, opacity=0.8, color_discrete_sequence=['indianred'], text_auto=True).update_layout( yaxis_title="Number of Posts", showlegend=False) # Comment Word Count Distribution comment_word = df['word_counts'].dropna().to_numpy() comment_word = reject_outliers(comment_word) comms_word_count = px.histogram(comment_word, labels={'value':'Word Count', 'count':'Number of Comments', 'variable':'Word Count'}, log_y=True, title='Word-Count Distribution for Comments', opacity=0.8).update_layout( xaxis_title="Word Count", yaxis_title="Number of Comments (log scale)", showlegend=False) if len(comment_word) == 0 or len(post_word) == 0: card = "" else: card = dbc.Card([ html.H5("Size", className="card-title"), html.P('Word-count per submission shows us Size.', className = 'fs-4'), html.Div(className='row', children=[ dcc.Loading(children=[ html.Div([ ### Post Word Count Plot html.Div(className="six columns", children=[ dcc.Graph(figure=post_word_count), ]), ### Comment Word Count Plot html.Div(className="six columns", children=[ dcc.Graph(figure=comms_word_count), ]) ]), ]), ]), ], style=PADDING_STYLE), except Exception as e: print(e) post_df.rename(columns={'post_id': 'Post ID', 'post_title': 'Post Title', 'post_body': 'Post Body'}, inplace=True) return f"What is r/{subreddit}?", description, facts, post_df.to_dict('records'), posts_score_hist, comms_score_hist, card except KeyError as e: print(e) return 'No data loaded! Go to Home Page first!', "", [], [], {}, {}, "" @callback( Output('subredditcommenttable', 'data'), Input('session', 'data'), Input('subreddittable', 'active_cell') ) def update_comment_table(data, active_cell): try: # Load DataFrame df = pd.DataFrame(data) # Comments Table comment_df = df[['post_id', 'comment']].copy() comment_df.rename(columns={'post_id': 'Post Id', 'comment': 'Comment'}, inplace=True) if active_cell is not None: comment_df = comment_df[comment_df['Post Id'] == active_cell['row_id']] return comment_df.to_dict('records') except KeyError as e: print(e) return []
[ "pandas.DataFrame", "dash.Output", "numpy.median", "dash.html.Div", "dash.dash_table.DataTable", "dash.dcc.Graph", "dash.html.P", "dash.html.H1", "pages.sas_key.get_df_description", "dash.Input", "plotly.express.histogram", "dash.html.Hr", "dash.html.H5", "dash.html.H3" ]
[((8370, 8413), 'dash.Output', 'Output', (['"""factssubredditprinter"""', '"""children"""'], {}), "('factssubredditprinter', 'children')\n", (8376, 8413), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((8419, 8461), 'dash.Output', 'Output', (['"""subredditdescription"""', '"""children"""'], {}), "('subredditdescription', 'children')\n", (8425, 8461), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((8467, 8499), 'dash.Output', 'Output', (['"""subredditfacts"""', '"""data"""'], {}), "('subredditfacts', 'data')\n", (8473, 8499), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((8505, 8537), 'dash.Output', 'Output', (['"""subreddittable"""', '"""data"""'], {}), "('subreddittable', 'data')\n", (8511, 8537), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((8543, 8569), 'dash.Output', 'Output', (['"""facts1"""', '"""figure"""'], {}), "('facts1', 'figure')\n", (8549, 8569), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((8575, 8601), 'dash.Output', 'Output', (['"""facts2"""', '"""figure"""'], {}), "('facts2', 'figure')\n", (8581, 8601), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((8607, 8635), 'dash.Output', 'Output', (['"""facts3"""', '"""children"""'], {}), "('facts3', 'children')\n", (8613, 8635), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((8641, 8665), 'dash.Input', 'Input', (['"""session"""', '"""data"""'], {}), "('session', 'data')\n", (8646, 8665), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((8671, 8696), 'dash.Input', 'Input', (['"""session2"""', '"""data"""'], {}), "('session2', 'data')\n", (8676, 8696), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((14482, 14521), 'dash.Output', 'Output', (['"""subredditcommenttable"""', '"""data"""'], {}), "('subredditcommenttable', 'data')\n", (14488, 14521), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((14527, 14551), 'dash.Input', 'Input', (['"""session"""', '"""data"""'], {}), "('session', 'data')\n", (14532, 14551), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((14557, 14595), 'dash.Input', 'Input', (['"""subreddittable"""', '"""active_cell"""'], {}), "('subreddittable', 'active_cell')\n", (14562, 14595), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((431, 494), 'dash.html.H1', 'html.H1', (['"""Subreddit Information"""'], {'style': "{'textAlign': 'center'}"}), "('Subreddit Information', style={'textAlign': 'center'})\n", (438, 494), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((8774, 8792), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (8786, 8792), True, 'import pandas as pd\n'), ((8858, 8883), 'pages.sas_key.get_df_description', 'get_df_description', (['value'], {}), '(value)\n', (8876, 8883), False, 'from pages.sas_key import get_df_description\n'), ((14690, 14708), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (14702, 14708), True, 'import pandas as pd\n'), ((9814, 9826), 'numpy.median', 'np.median', (['d'], {}), '(d)\n', (9823, 9826), True, 'import numpy as np\n'), ((533, 603), 'dash.html.H3', 'html.H3', ([], {'id': '"""factssubredditprinter"""', 'className': '"""display-6 text-center"""'}), "(id='factssubredditprinter', className='display-6 text-center')\n", (540, 603), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((621, 1175), 'dash.html.P', 'html.P', (['"""Here, you can check out more in formation about the subreddit. A snapshot of posts and their comments can be previewed along with the popularity and size of the subreddit selected. We have collected data on about 1,000 most recent posts and about 10,000 comments categorized as "hot" by Reddit for each subreddit (this might vary accordingly as posts/commets that were removed or deleted are not included in our analysis). Comment threads can be as long as a 100 comments per post due to API limitations."""'], {'className': '"""fs-4 text-center"""'}), '(\n \'Here, you can check out more in formation about the subreddit. A snapshot of posts and their comments can be previewed along with the popularity and size of the subreddit selected. We have collected data on about 1,000 most recent posts and about 10,000 comments categorized as "hot" by Reddit for each subreddit (this might vary accordingly as posts/commets that were removed or deleted are not included in our analysis). Comment threads can be as long as a 100 comments per post due to API limitations.\'\n , className=\'fs-4 text-center\')\n', (627, 1175), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((1185, 1194), 'dash.html.Hr', 'html.Hr', ([], {}), '()\n', (1192, 1194), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((2288, 2340), 'dash.html.H5', 'html.H5', (['"""Post Data Preview"""'], {'className': '"""card-title"""'}), "('Post Data Preview', className='card-title')\n", (2295, 2340), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((4254, 4310), 'dash.html.H5', 'html.H5', (['"""Comments Data Preview"""'], {'className': '"""card-title"""'}), "('Comments Data Preview', className='card-title')\n", (4261, 4310), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((6302, 6347), 'dash.html.H5', 'html.H5', (['"""Popularity"""'], {'className': '"""card-title"""'}), "('Popularity', className='card-title')\n", (6309, 6347), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((6365, 6528), 'dash.html.P', 'html.P', (['"""Score indicates the net total upvotes versus downvotes for a submission (post/comment), hence showing us Popularity."""'], {'className': '"""card-subtitle"""'}), "(\n 'Score indicates the net total upvotes versus downvotes for a submission (post/comment), hence showing us Popularity.'\n , className='card-subtitle')\n", (6371, 6528), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((10047, 10275), 'plotly.express.histogram', 'px.histogram', (['post_scores'], {'title': '"""Frequency Distribution of Post Score"""', 'labels': "{'value': 'Score', 'count': 'Number of Posts', 'variable': 'Score'}", 'opacity': '(0.8)', 'color_discrete_sequence': "['indianred']", 'text_auto': '(True)'}), "(post_scores, title='Frequency Distribution of Post Score',\n labels={'value': 'Score', 'count': 'Number of Posts', 'variable':\n 'Score'}, opacity=0.8, color_discrete_sequence=['indianred'], text_auto\n =True)\n", (10059, 10275), True, 'import plotly.express as px\n'), ((10765, 10919), 'plotly.express.histogram', 'px.histogram', (['comment_scores'], {'labels': "{'value': 'Score', 'variable': 'Score'}", 'log_y': '(True)', 'title': '"""Frequency Distribution of Comment Score"""', 'opacity': '(0.8)'}), "(comment_scores, labels={'value': 'Score', 'variable': 'Score'},\n log_y=True, title='Frequency Distribution of Comment Score', opacity=0.8)\n", (10777, 10919), True, 'import plotly.express as px\n'), ((1282, 1314), 'dash.html.H5', 'html.H5', (['"""Subreddit Description"""'], {}), "('Subreddit Description')\n", (1289, 1314), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((7403, 7424), 'dash.html.Div', 'html.Div', ([], {'id': '"""facts3"""'}), "(id='facts3')\n", (7411, 7424), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((9778, 9793), 'numpy.median', 'np.median', (['data'], {}), '(data)\n', (9787, 9793), True, 'import numpy as np\n'), ((11676, 11909), 'plotly.express.histogram', 'px.histogram', (['post_word'], {'title': '"""Word-Count Distribution for Posts"""', 'labels': "{'value': 'Word Count', 'count': 'Number of Posts', 'variable': 'Word Count'}", 'opacity': '(0.8)', 'color_discrete_sequence': "['indianred']", 'text_auto': '(True)'}), "(post_word, title='Word-Count Distribution for Posts', labels={\n 'value': 'Word Count', 'count': 'Number of Posts', 'variable':\n 'Word Count'}, opacity=0.8, color_discrete_sequence=['indianred'],\n text_auto=True)\n", (11688, 11909), True, 'import plotly.express as px\n'), ((12393, 12588), 'plotly.express.histogram', 'px.histogram', (['comment_word'], {'labels': "{'value': 'Word Count', 'count': 'Number of Comments', 'variable': 'Word Count'\n }", 'log_y': '(True)', 'title': '"""Word-Count Distribution for Comments"""', 'opacity': '(0.8)'}), "(comment_word, labels={'value': 'Word Count', 'count':\n 'Number of Comments', 'variable': 'Word Count'}, log_y=True, title=\n 'Word-Count Distribution for Comments', opacity=0.8)\n", (12405, 12588), True, 'import plotly.express as px\n'), ((2467, 3343), 'dash.dash_table.DataTable', 'dash_table.DataTable', ([], {'id': '"""subreddittable"""', 'page_size': '(5)', 'style_header': "{'font-weight': 'bold'}", 'style_data': "{'whiteSpace': 'normal'}", 'columns': "[{'name': 'Post ID', 'id': 'Post ID'}, {'name': 'Post Title', 'id':\n 'Post Title'}, {'name': 'Post Body', 'id': 'Post Body'}]", 'style_cell': "{'font-family': 'sans-serif', 'textAlign': 'left', 'font-size': '14px',\n 'padding-top': '3px', 'padding-bottom': '8px', 'padding-left': '8px',\n 'padding-right': '8px'}", 'css': '[{\'selector\': \'.dash-spreadsheet td div\', \'rule\':\n """\n line-height: 15px;\n max-height: 75px; min-height: 33px;\n display: block;\n overflow-y: auto;\n """\n }]'}), '(id=\'subreddittable\', page_size=5, style_header={\n \'font-weight\': \'bold\'}, style_data={\'whiteSpace\': \'normal\'}, columns=[{\n \'name\': \'Post ID\', \'id\': \'Post ID\'}, {\'name\': \'Post Title\', \'id\':\n \'Post Title\'}, {\'name\': \'Post Body\', \'id\': \'Post Body\'}], style_cell={\n \'font-family\': \'sans-serif\', \'textAlign\': \'left\', \'font-size\': \'14px\',\n \'padding-top\': \'3px\', \'padding-bottom\': \'8px\', \'padding-left\': \'8px\',\n \'padding-right\': \'8px\'}, css=[{\'selector\': \'.dash-spreadsheet td div\',\n \'rule\':\n """\n line-height: 15px;\n max-height: 75px; min-height: 33px;\n display: block;\n overflow-y: auto;\n """\n }])\n', (2487, 3343), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((4564, 4663), 'dash.html.P', 'html.P', (['"""Click a post in the above Post Table to view comments for that post"""'], {'style': 'TEXT_STYLE'}), "('Click a post in the above Post Table to view comments for that post',\n style=TEXT_STYLE)\n", (4570, 4663), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((4681, 5420), 'dash.dash_table.DataTable', 'dash_table.DataTable', ([], {'id': '"""subredditcommenttable"""', 'page_size': '(5)', 'style_header': "{'font-weight': 'bold'}", 'style_data': "{'whiteSpace': 'normal'}", 'style_cell': "{'font-family': 'sans-serif', 'textAlign': 'left', 'font-size': '14px',\n 'padding-top': '3px', 'padding-bottom': '8px', 'padding-left': '8px',\n 'padding-right': '8px'}", 'css': '[{\'selector\': \'.dash-spreadsheet td div\', \'rule\':\n """\n line-height: 15px;\n max-height: 75px; min-height: 33px;\n display: block;\n overflow-y: auto;\n """\n }]'}), '(id=\'subredditcommenttable\', page_size=5, style_header=\n {\'font-weight\': \'bold\'}, style_data={\'whiteSpace\': \'normal\'},\n style_cell={\'font-family\': \'sans-serif\', \'textAlign\': \'left\',\n \'font-size\': \'14px\', \'padding-top\': \'3px\', \'padding-bottom\': \'8px\',\n \'padding-left\': \'8px\', \'padding-right\': \'8px\'}, css=[{\'selector\':\n \'.dash-spreadsheet td div\', \'rule\':\n """\n line-height: 15px;\n max-height: 75px; min-height: 33px;\n display: block;\n overflow-y: auto;\n """\n }])\n', (4701, 5420), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((13021, 13060), 'dash.html.H5', 'html.H5', (['"""Size"""'], {'className': '"""card-title"""'}), "('Size', className='card-title')\n", (13028, 13060), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((13090, 13158), 'dash.html.P', 'html.P', (['"""Word-count per submission shows us Size."""'], {'className': '"""fs-4"""'}), "('Word-count per submission shows us Size.', className='fs-4')\n", (13096, 13158), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((1549, 1600), 'dash.html.P', 'html.P', ([], {'id': '"""subredditdescription"""', 'style': 'TEXT_STYLE'}), "(id='subredditdescription', style=TEXT_STYLE)\n", (1555, 1600), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((1766, 1999), 'dash.dash_table.DataTable', 'dash_table.DataTable', ([], {'id': '"""subredditfacts"""', 'style_header': "{'font-weight': 'bold'}", 'style_cell': "{'font-family': 'sans-serif', 'font-size': '14px', 'text-align': 'center'}", 'style_data': "{'whiteSpace': 'normal', 'height': 'auto'}"}), "(id='subredditfacts', style_header={'font-weight':\n 'bold'}, style_cell={'font-family': 'sans-serif', 'font-size': '14px',\n 'text-align': 'center'}, style_data={'whiteSpace': 'normal', 'height':\n 'auto'})\n", (1786, 1999), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((6806, 6828), 'dash.dcc.Graph', 'dcc.Graph', ([], {'id': '"""facts1"""'}), "(id='facts1')\n", (6815, 6828), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((7116, 7138), 'dash.dcc.Graph', 'dcc.Graph', ([], {'id': '"""facts2"""'}), "(id='facts2')\n", (7125, 7138), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((13523, 13556), 'dash.dcc.Graph', 'dcc.Graph', ([], {'figure': 'post_word_count'}), '(figure=post_word_count)\n', (13532, 13556), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((13799, 13833), 'dash.dcc.Graph', 'dcc.Graph', ([], {'figure': 'comms_word_count'}), '(figure=comms_word_count)\n', (13808, 13833), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n')]
import numpy as np f8 = np.float64() i8 = np.int64() u8 = np.uint64() f4 = np.float32() i4 = np.int32() u4 = np.uint32() td = np.timedelta64(0, "D") b_ = np.bool_() b = bool() f = float() i = int() AR = np.array([1], dtype=np.bool_) AR.setflags(write=False) AR2 = np.array([1], dtype=np.timedelta64) AR2.setflags(write=False) # Time structures reveal_type(td % td) # E: numpy.timedelta64 reveal_type(AR2 % td) # E: Any reveal_type(td % AR2) # E: Any reveal_type(divmod(td, td)) # E: Tuple[{int64}, numpy.timedelta64] reveal_type(divmod(AR2, td)) # E: Tuple[Any, Any] reveal_type(divmod(td, AR2)) # E: Tuple[Any, Any] # Bool reveal_type(b_ % b) # E: {int8} reveal_type(b_ % i) # E: {int_} reveal_type(b_ % f) # E: {float64} reveal_type(b_ % b_) # E: {int8} reveal_type(b_ % i8) # E: {int64} reveal_type(b_ % u8) # E: {uint64} reveal_type(b_ % f8) # E: {float64} reveal_type(b_ % AR) # E: Any reveal_type(divmod(b_, b)) # E: Tuple[{int8}, {int8}] reveal_type(divmod(b_, i)) # E: Tuple[{int_}, {int_}] reveal_type(divmod(b_, f)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(b_, b_)) # E: Tuple[{int8}, {int8}] reveal_type(divmod(b_, i8)) # E: Tuple[{int64}, {int64}] reveal_type(divmod(b_, u8)) # E: Tuple[{uint64}, {uint64}] reveal_type(divmod(b_, f8)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(b_, AR)) # E: Tuple[Any, Any] reveal_type(b % b_) # E: {int8} reveal_type(i % b_) # E: {int_} reveal_type(f % b_) # E: {float64} reveal_type(b_ % b_) # E: {int8} reveal_type(i8 % b_) # E: {int64} reveal_type(u8 % b_) # E: {uint64} reveal_type(f8 % b_) # E: {float64} reveal_type(AR % b_) # E: Any reveal_type(divmod(b, b_)) # E: Tuple[{int8}, {int8}] reveal_type(divmod(i, b_)) # E: Tuple[{int_}, {int_}] reveal_type(divmod(f, b_)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(b_, b_)) # E: Tuple[{int8}, {int8}] reveal_type(divmod(i8, b_)) # E: Tuple[{int64}, {int64}] reveal_type(divmod(u8, b_)) # E: Tuple[{uint64}, {uint64}] reveal_type(divmod(f8, b_)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(AR, b_)) # E: Tuple[Any, Any] # int reveal_type(i8 % b) # E: {int64} reveal_type(i8 % i) # E: {int64} reveal_type(i8 % f) # E: {float64} reveal_type(i8 % i8) # E: {int64} reveal_type(i8 % f8) # E: {float64} reveal_type(i4 % i8) # E: {int64} reveal_type(i4 % f8) # E: {float64} reveal_type(i4 % i4) # E: {int32} reveal_type(i4 % f4) # E: {float32} reveal_type(i8 % AR) # E: Any reveal_type(divmod(i8, b)) # E: Tuple[{int64}, {int64}] reveal_type(divmod(i8, i)) # E: Tuple[{int64}, {int64}] reveal_type(divmod(i8, f)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(i8, i8)) # E: Tuple[{int64}, {int64}] reveal_type(divmod(i8, f8)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(i8, i4)) # E: Tuple[{int64}, {int64}] reveal_type(divmod(i8, f4)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(i4, i4)) # E: Tuple[{int32}, {int32}] reveal_type(divmod(i4, f4)) # E: Tuple[{float32}, {float32}] reveal_type(divmod(i8, AR)) # E: Tuple[Any, Any] reveal_type(b % i8) # E: {int64} reveal_type(i % i8) # E: {int64} reveal_type(f % i8) # E: {float64} reveal_type(i8 % i8) # E: {int64} reveal_type(f8 % i8) # E: {float64} reveal_type(i8 % i4) # E: {int64} reveal_type(f8 % i4) # E: {float64} reveal_type(i4 % i4) # E: {int32} reveal_type(f4 % i4) # E: {float32} reveal_type(AR % i8) # E: Any reveal_type(divmod(b, i8)) # E: Tuple[{int64}, {int64}] reveal_type(divmod(i, i8)) # E: Tuple[{int64}, {int64}] reveal_type(divmod(f, i8)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(i8, i8)) # E: Tuple[{int64}, {int64}] reveal_type(divmod(f8, i8)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(i4, i8)) # E: Tuple[{int64}, {int64}] reveal_type(divmod(f4, i8)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(i4, i4)) # E: Tuple[{int32}, {int32}] reveal_type(divmod(f4, i4)) # E: Tuple[{float32}, {float32}] reveal_type(divmod(AR, i8)) # E: Tuple[Any, Any] # float reveal_type(f8 % b) # E: {float64} reveal_type(f8 % i) # E: {float64} reveal_type(f8 % f) # E: {float64} reveal_type(i8 % f4) # E: {float64} reveal_type(f4 % f4) # E: {float32} reveal_type(f8 % AR) # E: Any reveal_type(divmod(f8, b)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(f8, i)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(f8, f)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(f8, f8)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(f8, f4)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(f4, f4)) # E: Tuple[{float32}, {float32}] reveal_type(divmod(f8, AR)) # E: Tuple[Any, Any] reveal_type(b % f8) # E: {float64} reveal_type(i % f8) # E: {float64} reveal_type(f % f8) # E: {float64} reveal_type(f8 % f8) # E: {float64} reveal_type(f8 % f8) # E: {float64} reveal_type(f4 % f4) # E: {float32} reveal_type(AR % f8) # E: Any reveal_type(divmod(b, f8)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(i, f8)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(f, f8)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(f8, f8)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(f4, f8)) # E: Tuple[{float64}, {float64}] reveal_type(divmod(f4, f4)) # E: Tuple[{float32}, {float32}] reveal_type(divmod(AR, f8)) # E: Tuple[Any, Any]
[ "numpy.uint32", "numpy.bool_", "numpy.uint64", "numpy.float32", "numpy.timedelta64", "numpy.array", "numpy.int32", "numpy.int64", "numpy.float64" ]
[((25, 37), 'numpy.float64', 'np.float64', ([], {}), '()\n', (35, 37), True, 'import numpy as np\n'), ((43, 53), 'numpy.int64', 'np.int64', ([], {}), '()\n', (51, 53), True, 'import numpy as np\n'), ((59, 70), 'numpy.uint64', 'np.uint64', ([], {}), '()\n', (68, 70), True, 'import numpy as np\n'), ((77, 89), 'numpy.float32', 'np.float32', ([], {}), '()\n', (87, 89), True, 'import numpy as np\n'), ((95, 105), 'numpy.int32', 'np.int32', ([], {}), '()\n', (103, 105), True, 'import numpy as np\n'), ((111, 122), 'numpy.uint32', 'np.uint32', ([], {}), '()\n', (120, 122), True, 'import numpy as np\n'), ((129, 151), 'numpy.timedelta64', 'np.timedelta64', (['(0)', '"""D"""'], {}), "(0, 'D')\n", (143, 151), True, 'import numpy as np\n'), ((157, 167), 'numpy.bool_', 'np.bool_', ([], {}), '()\n', (165, 167), True, 'import numpy as np\n'), ((208, 237), 'numpy.array', 'np.array', (['[1]'], {'dtype': 'np.bool_'}), '([1], dtype=np.bool_)\n', (216, 237), True, 'import numpy as np\n'), ((270, 305), 'numpy.array', 'np.array', (['[1]'], {'dtype': 'np.timedelta64'}), '([1], dtype=np.timedelta64)\n', (278, 305), True, 'import numpy as np\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt from keras.preprocessing import text, sequence from keras.preprocessing.text import Tokenizer from keras.utils import to_categorical from keras.models import * from keras.layers import * from keras.optimizers import * from sklearn.model_selection import train_test_split from keras.metrics import categorical_accuracy from keras import backend as K import tensorflow as tf from keras.callbacks import TensorBoard, LearningRateScheduler, ModelCheckpoint, ReduceLROnPlateau from datetime import datetime import os, pickle from utils import * maxlen_seq = 768 center_augmented_data = False ## center augmented data training_idx = np.arange(5600) test_idx = np.arange(5605,5877) validation_idx = np.arange(5877,6133) cb6133filename = '../data/cb6133.npy' kfold=10 ## cross validation for fold_id in range(0, 10): train_df_all, train_augment_data_all = load_augmented_data(cb6133filename, maxlen_seq, centered=center_augmented_data) train_df = train_df_all.iloc[training_idx] val_df = train_df_all.iloc[validation_idx] # save preprocessed val and test data test_df = train_df_all.iloc[test_idx] train_augment_data = train_augment_data_all[training_idx] test_augment_data = train_augment_data_all[test_idx] index = np.arange(0,len(train_df)) # np.random.seed(0) # np.random.shuffle(index) chunk_all = [int(len(train_df)/kfold)*i for i in range(1,kfold)] val_chunks = np.split(index, chunk_all) chunk = val_chunks[fold_id] val_df = train_df.iloc[chunk] train_train_df = train_df.iloc[list(set(index)-set(chunk))] # Loading and converting the inputs to ngrams train_input_seqs, train_target_seqs = train_df[['input', 'expected']].values.T train_input_grams = seq2ngrams(train_input_seqs, n=1) # Initializing and defining the tokenizer encoders and decoders based on the train set tokenizer_encoder = Tokenizer() tokenizer_encoder.fit_on_texts(train_input_grams) tokenizer_decoder = Tokenizer(char_level = True) tokenizer_decoder.fit_on_texts(train_target_seqs) # Using the tokenizer to encode and decode the sequences for use in training # Inputs train_input_data = tokenizer_encoder.texts_to_sequences(train_input_grams) train_input_data = sequence.pad_sequences(train_input_data, maxlen = maxlen_seq, padding = 'post', truncating='post') # Targets train_target_data = tokenizer_decoder.texts_to_sequences(train_target_seqs) train_target_data = sequence.pad_sequences(train_target_data, maxlen = maxlen_seq, padding = 'post', truncating='post') train_target_data = to_categorical(train_target_data) # Computing the number of words and number of tags to be passed as parameters to the keras model n_words = len(tokenizer_encoder.word_index) + 1 n_tags = len(tokenizer_decoder.word_index) + 1 ############################################ # Splitting the data for train and validation sets X_val = train_input_data[chunk] X_train = train_input_data[list(set(index)-set(chunk))] y_val = train_target_data[chunk] y_train = train_target_data[list(set(index)-set(chunk))] X_train_augment = train_augment_data[list(set(index)-set(chunk))] X_val_augment = train_augment_data[chunk] ############################################ # save preprocessed val and test data and tokenizer script_name = os.path.basename(__file__).split(".")[0] model_name = datetime.now().strftime("%Y%m%d-%H%M%S") + "-" + script_name log_dir = '../logs/{}'.format(model_name) + str(fold_id) os.mkdir(log_dir) val_df.to_csv(os.path.join(log_dir, 'val_data.csv')) np.save(os.path.join(log_dir, 'val_augment_data.npy'), X_val_augment) test_df.to_csv(os.path.join(log_dir, 'test_data.csv')) np.save(os.path.join(log_dir, 'test_augment_data.npy'), test_augment_data) with open(os.path.join(log_dir, 'tokenizer_encoder.pickle'), 'wb') as handle: pickle.dump(tokenizer_encoder, handle) with open(os.path.join(log_dir, 'tokenizer_decoder.pickle'), 'wb') as handle: pickle.dump(tokenizer_decoder, handle) ############################################ # Dropout to prevent overfitting. droprate = 0.25 def conv_block(x, n_channels, droprate): x = BatchNormalization()(x) x = ReLU()(x) x = Conv1D(n_channels, 3, padding = 'same', kernel_initializer = 'he_normal')(x) x = Dropout(droprate)(x) x = BatchNormalization()(x) x = ReLU()(x) x = Conv1D(n_channels, 3, padding = 'same', kernel_initializer = 'he_normal')(x) return x def up_block(x, n_channels): x = BatchNormalization()(x) x = ReLU()(x) x = UpSampling1D(size = 2)(x) x = Conv1D(n_channels, 2, padding = 'same', kernel_initializer = 'he_normal')(x) return x input = Input(shape = (None, )) augment_input = Input(shape = (None, 22)) # Defining an embedding layer mapping from the words (n_words) to a vector of len 128 embed_input = Embedding(input_dim = n_words, output_dim = 128, input_length = None)(input) merged_input = concatenate([embed_input, augment_input], axis = 2) merged_input = Conv1D(128, 3, padding = 'same', kernel_initializer = 'he_normal')(merged_input) conv1 = conv_block(merged_input, 128, droprate) pool1 = MaxPooling1D(pool_size=2)(conv1) conv2 = conv_block(pool1, 192, droprate) pool2 = MaxPooling1D(pool_size=2)(conv2) conv3 = conv_block(pool2, 384, droprate) pool3 = MaxPooling1D(pool_size=2)(conv3) conv4 = conv_block(pool3, 768, droprate) pool4 = MaxPooling1D(pool_size=2)(conv4) conv5 = conv_block(pool4, 1536, droprate) up4 = up_block(conv5, 768) up4 = concatenate([conv4,up4], axis = 2) up4 = conv_block(up4, 768, droprate) up3 = up_block(up4, 384) up3 = concatenate([conv3,up3], axis = 2) up3 = conv_block(up3, 384, droprate) up2 = up_block(up3, 192) up2 = concatenate([conv2,up2], axis = 2) up2 = conv_block(up2, 192, droprate) up1 = up_block(up2, 128) up1 = concatenate([conv1,up1], axis = 2) up1 = conv_block(up1, 128, droprate) up1 = BatchNormalization()(up1) up1 = ReLU()(up1) # the following it equivalent to Conv1D with kernel size 1 # A dense layer to output from the LSTM's64 units to the appropriate number of tags to be fed into the decoder y = TimeDistributed(Dense(n_tags, activation = "softmax"))(up1) # Defining the model as a whole and printing the summary model = Model([input, augment_input], y) model.summary() optim = RMSprop(lr=0.002) def scheduler(i, lr): if i in [60]: return lr * 0.5 return lr reduce_lr = LearningRateScheduler(schedule=scheduler, verbose=1) # reduce_lr = ReduceLROnPlateau(monitor='val_accuracy', factor=0.5, # patience=8, min_lr=0.0005, verbose=1) # Setting up the model with categorical x-entropy loss and the custom accuracy function as accuracy model.compile(optimizer = optim, loss = "categorical_crossentropy", metrics = ["accuracy", accuracy]) tensorboard = TensorBoard(log_dir=log_dir) checkpoint = ModelCheckpoint(os.path.join(log_dir, "best_val_acc.h5"), monitor='val_accuracy', verbose=1, save_best_only=True, mode='max') # Training the model on the training data and validating using the validation set model.fit([X_train, X_train_augment], y_train, batch_size = 128, validation_data = ([X_val, X_val_augment], y_val), verbose = 1, callbacks=[tensorboard, reduce_lr, checkpoint], epochs = 90) K.clear_session() model = load_model(os.path.join(log_dir, "best_val_acc.h5")) val_pred_df = predict_all(model, val_df, tokenizer_encoder, tokenizer_decoder, n_gram=1, max_len=maxlen_seq, augmented_input=X_val_augment, filepath = os.path.join(log_dir, "val_pred_{}.csv".format(model_name))) val_score, val_score_df = edit_score(val_df, val_pred_df, filepath = os.path.join(log_dir, "val_score_{}.csv".format(model_name)), plot=False) plt.close() K.clear_session()
[ "os.mkdir", "pickle.dump", "os.path.basename", "keras.preprocessing.sequence.pad_sequences", "matplotlib.pyplot.close", "datetime.datetime.now", "numpy.split", "keras.preprocessing.text.Tokenizer", "numpy.arange", "keras.callbacks.TensorBoard", "keras.callbacks.LearningRateScheduler", "os.path.join", "keras.backend.clear_session", "keras.utils.to_categorical" ]
[((702, 717), 'numpy.arange', 'np.arange', (['(5600)'], {}), '(5600)\n', (711, 717), True, 'import numpy as np\n'), ((729, 750), 'numpy.arange', 'np.arange', (['(5605)', '(5877)'], {}), '(5605, 5877)\n', (738, 750), True, 'import numpy as np\n'), ((767, 788), 'numpy.arange', 'np.arange', (['(5877)', '(6133)'], {}), '(5877, 6133)\n', (776, 788), True, 'import numpy as np\n'), ((1500, 1526), 'numpy.split', 'np.split', (['index', 'chunk_all'], {}), '(index, chunk_all)\n', (1508, 1526), True, 'import numpy as np\n'), ((1967, 1978), 'keras.preprocessing.text.Tokenizer', 'Tokenizer', ([], {}), '()\n', (1976, 1978), False, 'from keras.preprocessing.text import Tokenizer\n'), ((2057, 2083), 'keras.preprocessing.text.Tokenizer', 'Tokenizer', ([], {'char_level': '(True)'}), '(char_level=True)\n', (2066, 2083), False, 'from keras.preprocessing.text import Tokenizer\n'), ((2337, 2435), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['train_input_data'], {'maxlen': 'maxlen_seq', 'padding': '"""post"""', 'truncating': '"""post"""'}), "(train_input_data, maxlen=maxlen_seq, padding='post',\n truncating='post')\n", (2359, 2435), False, 'from keras.preprocessing import text, sequence\n'), ((2555, 2654), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['train_target_data'], {'maxlen': 'maxlen_seq', 'padding': '"""post"""', 'truncating': '"""post"""'}), "(train_target_data, maxlen=maxlen_seq, padding='post',\n truncating='post')\n", (2577, 2654), False, 'from keras.preprocessing import text, sequence\n'), ((2679, 2712), 'keras.utils.to_categorical', 'to_categorical', (['train_target_data'], {}), '(train_target_data)\n', (2693, 2712), False, 'from keras.utils import to_categorical\n'), ((3645, 3662), 'os.mkdir', 'os.mkdir', (['log_dir'], {}), '(log_dir)\n', (3653, 3662), False, 'import os, pickle\n'), ((6834, 6886), 'keras.callbacks.LearningRateScheduler', 'LearningRateScheduler', ([], {'schedule': 'scheduler', 'verbose': '(1)'}), '(schedule=scheduler, verbose=1)\n', (6855, 6886), False, 'from keras.callbacks import TensorBoard, LearningRateScheduler, ModelCheckpoint, ReduceLROnPlateau\n'), ((7261, 7289), 'keras.callbacks.TensorBoard', 'TensorBoard', ([], {'log_dir': 'log_dir'}), '(log_dir=log_dir)\n', (7272, 7289), False, 'from keras.callbacks import TensorBoard, LearningRateScheduler, ModelCheckpoint, ReduceLROnPlateau\n'), ((7898, 7915), 'keras.backend.clear_session', 'K.clear_session', ([], {}), '()\n', (7913, 7915), True, 'from keras import backend as K\n'), ((8456, 8467), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (8465, 8467), True, 'import matplotlib.pyplot as plt\n'), ((8472, 8489), 'keras.backend.clear_session', 'K.clear_session', ([], {}), '()\n', (8487, 8489), True, 'from keras import backend as K\n'), ((3682, 3719), 'os.path.join', 'os.path.join', (['log_dir', '"""val_data.csv"""'], {}), "(log_dir, 'val_data.csv')\n", (3694, 3719), False, 'import os, pickle\n'), ((3733, 3778), 'os.path.join', 'os.path.join', (['log_dir', '"""val_augment_data.npy"""'], {}), "(log_dir, 'val_augment_data.npy')\n", (3745, 3778), False, 'import os, pickle\n'), ((3814, 3852), 'os.path.join', 'os.path.join', (['log_dir', '"""test_data.csv"""'], {}), "(log_dir, 'test_data.csv')\n", (3826, 3852), False, 'import os, pickle\n'), ((3866, 3912), 'os.path.join', 'os.path.join', (['log_dir', '"""test_augment_data.npy"""'], {}), "(log_dir, 'test_augment_data.npy')\n", (3878, 3912), False, 'import os, pickle\n'), ((4024, 4062), 'pickle.dump', 'pickle.dump', (['tokenizer_encoder', 'handle'], {}), '(tokenizer_encoder, handle)\n', (4035, 4062), False, 'import os, pickle\n'), ((4154, 4192), 'pickle.dump', 'pickle.dump', (['tokenizer_decoder', 'handle'], {}), '(tokenizer_decoder, handle)\n', (4165, 4192), False, 'import os, pickle\n'), ((7324, 7364), 'os.path.join', 'os.path.join', (['log_dir', '"""best_val_acc.h5"""'], {}), "(log_dir, 'best_val_acc.h5')\n", (7336, 7364), False, 'import os, pickle\n'), ((7940, 7980), 'os.path.join', 'os.path.join', (['log_dir', '"""best_val_acc.h5"""'], {}), "(log_dir, 'best_val_acc.h5')\n", (7952, 7980), False, 'import os, pickle\n'), ((3948, 3997), 'os.path.join', 'os.path.join', (['log_dir', '"""tokenizer_encoder.pickle"""'], {}), "(log_dir, 'tokenizer_encoder.pickle')\n", (3960, 3997), False, 'import os, pickle\n'), ((4078, 4127), 'os.path.join', 'os.path.join', (['log_dir', '"""tokenizer_decoder.pickle"""'], {}), "(log_dir, 'tokenizer_decoder.pickle')\n", (4090, 4127), False, 'import os, pickle\n'), ((3460, 3486), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (3476, 3486), False, 'import os, pickle\n'), ((3519, 3533), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3531, 3533), False, 'from datetime import datetime\n')]
from io import StringIO import unittest import os import numpy as np from gimmemotifs.motif import Motif, read_motifs from gimmemotifs.shutils import which class TestMotif(unittest.TestCase): """ A test class for Motif """ def setUp(self): self.data_dir = "test/data/motif" self.pwm = os.path.join(self.data_dir, "test.pwm") self.pwm2 = "test/data/pwms/motifs.pwm" self.jaspar = "test/data/pwms/test.jaspar" self.pfm = [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 1], [2, 0, 2, 0], [3, 0, 0, 3], [0, 1, 0, 1], ] def test1_motif_instance(self): """ Creation of Motif instance """ m = Motif() self.assertTrue(type(m)) def test2_motif_instance_pfm(self): """ Creation of Motif instance from pfm""" m = Motif(self.pfm) self.assertTrue(m) def test3_motif_length(self): """ Motif length """ m = Motif(self.pfm) self.assertEqual(10, len(m)) def test4_motif_consensus(self): """ Motif length """ m = Motif(self.pfm) self.assertEqual("ACGTmskrwy", m.to_consensus()) def test5_motif_to_img(self): """ Motif to img """ seqlogo = which("seqlogo") if seqlogo: m = Motif(self.pfm) m.to_img("test/test.png", fmt="png", seqlogo=seqlogo) self.assertTrue(os.path.exists("test/test.png")) os.unlink("test/test.png") else: print("seqlogo not found, skipping.") def test6_pcc(self): pfm1 = [[5, 0, 0, 0], [0, 5, 0, 0], [0, 5, 0, 0], [0, 0, 0, 5]] pfm2 = [[5, 0, 0, 0], [0, 5, 0, 0], [0, 5, 0, 0], [0, 0, 0, 5]] m1 = Motif(pfm1) m2 = Motif(pfm2) self.assertEqual(4, m1.max_pcc(m2)[0]) def test7__read_motifs_pwm(self): with open(self.pwm2) as f: motifs = read_motifs(f, fmt="pwm") motif_ids = [m.id for m in motifs] self.assertEqual(5, len(motif_ids)) self.assertEqual( ["M1500_1.01", "M5659_1.01", "M5669_1.01", "M5715_1.01", "M5717_1.01"], motif_ids, ) def test7__read_motifs_jaspar(self): with open(self.jaspar) as f: motifs = read_motifs(f, fmt="jaspar") my_motifs = ["MA0002.2", "MA0003.3", "MA0004.1", "MA0006.1"] my_lens = [6, 6, 11, 11] motif_ids = [m.id for m in motifs] self.assertEqual(4, len(motif_ids)) self.assertEqual(my_motifs, motif_ids) self.assertEqual(my_lens, sorted([len(m) for m in motifs])) def test8_pwm_to_str(self): pwm = [[0.01, 0.01, 0.01, 0.97], [0.123, 0.456, 0.222, 0.199]] m = Motif(pwm) s2 = "0.01\t0.01\t0.01\t0.97\n0.12\t0.46\t0.22\t0.20" s3 = "0.010\t0.010\t0.010\t0.970\n0.123\t0.456\t0.222\t0.199" self.assertEqual(s2, m._pwm_to_str(precision=2)) self.assertEqual(s3, m._pwm_to_str(precision=3)) def test8_pwm_to_str_hash(self): pwm = [[0.01, 0.01, 0.01, 0.97], [0.123, 0.456, 0.222, 0.199]] m = Motif(pwm) h = "1f260320cac8c26a" self.assertEqual(h, m.hash()) pwm = [ [0.010000, 0.010000, 0.010000, 0.970000], [0.12300, 0.45600, 0.22200, 0.19900], ] m = Motif(pwm) self.assertEqual(h, m.hash()) def test9_logodds_matrix(self): pwm = [[0.5, 0.4, 0.1, 0.0], [0.25, 0.25, 0.25, 0.25]] logodds = np.array( [ [0.69813, 0.47623, -0.89160, -4.60517], [0.00995, 0.00995, 0.00995, 0.00995], ] ) m = Motif(pwm) np.testing.assert_almost_equal(logodds, np.array(m.logodds), decimal=5) def test10_read_motifs(self): # Read motifs from file motifs = read_motifs(self.pwm2, fmt="pwm") self.assertEqual(5, len(motifs)) # Read motifs from file as dictionary motifs = read_motifs(self.pwm2, fmt="pwm", as_dict=True) self.assertEqual(5, len(motifs)) self.assertEqual(type({}), type(motifs)) def test11_slice_motif(self): pfm = [ [120, 0, 0, 0], [120, 0, 0, 0], [0, 60, 60, 0], [0, 0, 0, 120], [0, 0, 0, 120], ] m = Motif(pfm) m.to_consensus() # take slice m2 = m[1:-1] self.assertEqual("AST", m2.consensus.upper()) self.assertEqual(pfm[1:-1], m2.pfm) def test_motif_export_import(self): pfm = [ [120, 0, 0, 0], [120, 0, 0, 0], [0, 60, 60, 0], [0, 0, 0, 120], [0, 0, 0, 120], ] motif = Motif(pfm) motif.id = "test_motif" f = StringIO(motif.to_transfac()) motif_from_file = read_motifs(f, fmt="transfac")[0] self.assertEqual("AASTT", motif_from_file.to_consensus().upper()) self.assertEqual("test_motif", motif_from_file.id) f = StringIO(motif.to_meme()) motif_from_file = read_motifs(f, fmt="meme")[0] self.assertEqual("AASTT", motif_from_file.to_consensus().upper()) self.assertEqual("test_motif", motif_from_file.id) f = StringIO(motif.to_motevo()) motif_from_file = read_motifs(f, fmt="transfac")[0] self.assertEqual("AASTT", motif_from_file.to_consensus().upper()) self.assertEqual("test_motif", motif_from_file.id) def test_motif_from_alignment(self): align = "AACTT\n" "AAGTA\n" "AACTC\n" "AAGTG\n" f = StringIO(align) motif = read_motifs(f, fmt="align")[0] self.assertEqual("AASTN", motif.to_consensus().upper()) def test_read_motifs_xxmotifs(self): fname = "test/data/motifprogram/xxmotif.pwm" motifs = read_motifs(fname, fmt="xxmotif") self.assertEqual(4, len(motifs)) self.assertEqual(9, len(motifs[-1])) self.assertEqual("RGGCAWGYC", motifs[-1].to_consensus().upper()) def tearDown(self): pass if __name__ == "__main__": unittest.main()
[ "unittest.main", "gimmemotifs.motif.Motif", "io.StringIO", "os.unlink", "os.path.exists", "numpy.array", "gimmemotifs.motif.read_motifs", "gimmemotifs.shutils.which", "os.path.join" ]
[((6224, 6239), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6237, 6239), False, 'import unittest\n'), ((312, 351), 'os.path.join', 'os.path.join', (['self.data_dir', '"""test.pwm"""'], {}), "(self.data_dir, 'test.pwm')\n", (324, 351), False, 'import os\n'), ((834, 841), 'gimmemotifs.motif.Motif', 'Motif', ([], {}), '()\n', (839, 841), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((980, 995), 'gimmemotifs.motif.Motif', 'Motif', (['self.pfm'], {}), '(self.pfm)\n', (985, 995), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((1099, 1114), 'gimmemotifs.motif.Motif', 'Motif', (['self.pfm'], {}), '(self.pfm)\n', (1104, 1114), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((1231, 1246), 'gimmemotifs.motif.Motif', 'Motif', (['self.pfm'], {}), '(self.pfm)\n', (1236, 1246), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((1386, 1402), 'gimmemotifs.shutils.which', 'which', (['"""seqlogo"""'], {}), "('seqlogo')\n", (1391, 1402), False, 'from gimmemotifs.shutils import which\n'), ((1869, 1880), 'gimmemotifs.motif.Motif', 'Motif', (['pfm1'], {}), '(pfm1)\n', (1874, 1880), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((1894, 1905), 'gimmemotifs.motif.Motif', 'Motif', (['pfm2'], {}), '(pfm2)\n', (1899, 1905), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((2859, 2869), 'gimmemotifs.motif.Motif', 'Motif', (['pwm'], {}), '(pwm)\n', (2864, 2869), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((3239, 3249), 'gimmemotifs.motif.Motif', 'Motif', (['pwm'], {}), '(pwm)\n', (3244, 3249), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((3462, 3472), 'gimmemotifs.motif.Motif', 'Motif', (['pwm'], {}), '(pwm)\n', (3467, 3472), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((3630, 3721), 'numpy.array', 'np.array', (['[[0.69813, 0.47623, -0.8916, -4.60517], [0.00995, 0.00995, 0.00995, 0.00995]]'], {}), '([[0.69813, 0.47623, -0.8916, -4.60517], [0.00995, 0.00995, 0.00995,\n 0.00995]])\n', (3638, 3721), True, 'import numpy as np\n'), ((3800, 3810), 'gimmemotifs.motif.Motif', 'Motif', (['pwm'], {}), '(pwm)\n', (3805, 3810), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((3976, 4009), 'gimmemotifs.motif.read_motifs', 'read_motifs', (['self.pwm2'], {'fmt': '"""pwm"""'}), "(self.pwm2, fmt='pwm')\n", (3987, 4009), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((4115, 4162), 'gimmemotifs.motif.read_motifs', 'read_motifs', (['self.pwm2'], {'fmt': '"""pwm"""', 'as_dict': '(True)'}), "(self.pwm2, fmt='pwm', as_dict=True)\n", (4126, 4162), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((4467, 4477), 'gimmemotifs.motif.Motif', 'Motif', (['pfm'], {}), '(pfm)\n', (4472, 4477), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((4868, 4878), 'gimmemotifs.motif.Motif', 'Motif', (['pfm'], {}), '(pfm)\n', (4873, 4878), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((5719, 5734), 'io.StringIO', 'StringIO', (['align'], {}), '(align)\n', (5727, 5734), False, 'from io import StringIO\n'), ((5959, 5992), 'gimmemotifs.motif.read_motifs', 'read_motifs', (['fname'], {'fmt': '"""xxmotif"""'}), "(fname, fmt='xxmotif')\n", (5970, 5992), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((1439, 1454), 'gimmemotifs.motif.Motif', 'Motif', (['self.pfm'], {}), '(self.pfm)\n', (1444, 1454), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((1594, 1620), 'os.unlink', 'os.unlink', (['"""test/test.png"""'], {}), "('test/test.png')\n", (1603, 1620), False, 'import os\n'), ((2049, 2074), 'gimmemotifs.motif.read_motifs', 'read_motifs', (['f'], {'fmt': '"""pwm"""'}), "(f, fmt='pwm')\n", (2060, 2074), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((2406, 2434), 'gimmemotifs.motif.read_motifs', 'read_motifs', (['f'], {'fmt': '"""jaspar"""'}), "(f, fmt='jaspar')\n", (2417, 2434), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((3859, 3878), 'numpy.array', 'np.array', (['m.logodds'], {}), '(m.logodds)\n', (3867, 3878), True, 'import numpy as np\n'), ((4980, 5010), 'gimmemotifs.motif.read_motifs', 'read_motifs', (['f'], {'fmt': '"""transfac"""'}), "(f, fmt='transfac')\n", (4991, 5010), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((5212, 5238), 'gimmemotifs.motif.read_motifs', 'read_motifs', (['f'], {'fmt': '"""meme"""'}), "(f, fmt='meme')\n", (5223, 5238), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((5442, 5472), 'gimmemotifs.motif.read_motifs', 'read_motifs', (['f'], {'fmt': '"""transfac"""'}), "(f, fmt='transfac')\n", (5453, 5472), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((5751, 5778), 'gimmemotifs.motif.read_motifs', 'read_motifs', (['f'], {'fmt': '"""align"""'}), "(f, fmt='align')\n", (5762, 5778), False, 'from gimmemotifs.motif import Motif, read_motifs\n'), ((1549, 1580), 'os.path.exists', 'os.path.exists', (['"""test/test.png"""'], {}), "('test/test.png')\n", (1563, 1580), False, 'import os\n')]
'Test the arnet module.' import sys sys.path.insert(0, './') sys.path.insert(0, './tests') import numpy as np import torch import beer from basetest import BaseTest class TestUtils(BaseTest): def test_create_mask(self): ordering = [2, 0, 1] max_connections = [1, 0, 1, 1] device = torch.device('cpu') mask1 = beer.nnet.arnet.create_mask(ordering, max_connections).numpy() mask2 = np.array([ [0, 1, 1], [0, 1, 0], [0, 1, 1], [0, 1, 1] ]) self.assertArraysAlmostEqual(mask1, mask2) def test_create_final_mask(self): ordering = [2, 0, 1] max_connections = [0, 1, 1, 0] device = torch.device('cpu') mask1 = beer.nnet.arnet.create_final_mask(ordering, max_connections).numpy() mask2 = np.array([ [1, 1, 1, 1], [0, 0, 0, 0], [1, 0, 0, 1] ]) self.assertArraysAlmostEqual(mask1, mask2) class TestMaskedLinearTransform(BaseTest): def setUp(self): self.dim = int(10 + torch.randint(100, (1, 1)).item()) self.dim_out = int(10 + torch.randint(100, (1, 1)).item()) self.npoints = int(1 + torch.randint(100, (1, 1)).item()) self.data = torch.randn(self.npoints, self.dim).type(self.type) self.ltrans = torch.nn.Linear(self.dim, self.dim_out) self.mask = torch.ones(self.dim_out, self.dim) self.masked_ltrans = beer.nnet.arnet.MaskedLinear(self.mask, self.ltrans).type(self.type) def test_ltrans(self): # Don't test the output values, just make sure that everything # run. out = self.masked_ltrans(self.data) self.assertEqual(out.shape[0], self.npoints) self.assertEqual(out.shape[1], self.dim_out) def test_type_casting(self): # Don't test the output values, just make sure that everything # run. self.masked_ltrans.float() self.masked_ltrans.double() device = torch.device('cpu') self.masked_ltrans.to(device) class TestARNetwork(BaseTest): def setUp(self): self.conf_nocontext = { 'data_dim': int(10 + torch.randint(100, (1, 1)).item()), 'depth': int(1 + torch.randint(100, (1, 1)).item()), 'width': int(1 + torch.randint(100, (1, 1)).item()), 'activation': 'Tanh', 'context_dim': 0, } self.conf_context = { 'data_dim': int(10 + torch.randint(100, (1, 1)).item()), 'depth': int(1 + torch.randint(100, (1, 1)).item()), 'width': int(1 + torch.randint(100, (1, 1)).item()), 'activation': 'Tanh', 'context_dim': int(1 + torch.randint(100, (1, 1)).item()), } def test_create(self): arnet = beer.nnet.arnet.create_arnetwork(self.conf_nocontext) self.assertEqual(len(arnet), 2 * self.conf_nocontext['depth'] + 1) arnet = beer.nnet.arnet.create_arnetwork(self.conf_context) self.assertEqual(len(arnet), 2 * self.conf_context['depth'] + 1) __all__ = [ 'TestUtils', 'TestMaskedLinearTransform', 'TestARNetwork' ]
[ "torch.ones", "torch.randint", "sys.path.insert", "beer.nnet.arnet.create_final_mask", "torch.randn", "beer.nnet.arnet.MaskedLinear", "beer.nnet.arnet.create_mask", "numpy.array", "beer.nnet.arnet.create_arnetwork", "torch.nn.Linear", "torch.device" ]
[((37, 61), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""./"""'], {}), "(0, './')\n", (52, 61), False, 'import sys\n'), ((62, 91), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""./tests"""'], {}), "(0, './tests')\n", (77, 91), False, 'import sys\n'), ((314, 333), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (326, 333), False, 'import torch\n'), ((429, 483), 'numpy.array', 'np.array', (['[[0, 1, 1], [0, 1, 0], [0, 1, 1], [0, 1, 1]]'], {}), '([[0, 1, 1], [0, 1, 0], [0, 1, 1], [0, 1, 1]])\n', (437, 483), True, 'import numpy as np\n'), ((717, 736), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (729, 736), False, 'import torch\n'), ((838, 890), 'numpy.array', 'np.array', (['[[1, 1, 1, 1], [0, 0, 0, 0], [1, 0, 0, 1]]'], {}), '([[1, 1, 1, 1], [0, 0, 0, 0], [1, 0, 0, 1]])\n', (846, 890), True, 'import numpy as np\n'), ((1345, 1384), 'torch.nn.Linear', 'torch.nn.Linear', (['self.dim', 'self.dim_out'], {}), '(self.dim, self.dim_out)\n', (1360, 1384), False, 'import torch\n'), ((1405, 1439), 'torch.ones', 'torch.ones', (['self.dim_out', 'self.dim'], {}), '(self.dim_out, self.dim)\n', (1415, 1439), False, 'import torch\n'), ((2022, 2041), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2034, 2041), False, 'import torch\n'), ((2828, 2881), 'beer.nnet.arnet.create_arnetwork', 'beer.nnet.arnet.create_arnetwork', (['self.conf_nocontext'], {}), '(self.conf_nocontext)\n', (2860, 2881), False, 'import beer\n'), ((2974, 3025), 'beer.nnet.arnet.create_arnetwork', 'beer.nnet.arnet.create_arnetwork', (['self.conf_context'], {}), '(self.conf_context)\n', (3006, 3025), False, 'import beer\n'), ((350, 404), 'beer.nnet.arnet.create_mask', 'beer.nnet.arnet.create_mask', (['ordering', 'max_connections'], {}), '(ordering, max_connections)\n', (377, 404), False, 'import beer\n'), ((753, 813), 'beer.nnet.arnet.create_final_mask', 'beer.nnet.arnet.create_final_mask', (['ordering', 'max_connections'], {}), '(ordering, max_connections)\n', (786, 813), False, 'import beer\n'), ((1271, 1306), 'torch.randn', 'torch.randn', (['self.npoints', 'self.dim'], {}), '(self.npoints, self.dim)\n', (1282, 1306), False, 'import torch\n'), ((1469, 1521), 'beer.nnet.arnet.MaskedLinear', 'beer.nnet.arnet.MaskedLinear', (['self.mask', 'self.ltrans'], {}), '(self.mask, self.ltrans)\n', (1497, 1521), False, 'import beer\n'), ((1083, 1109), 'torch.randint', 'torch.randint', (['(100)', '(1, 1)'], {}), '(100, (1, 1))\n', (1096, 1109), False, 'import torch\n'), ((1150, 1176), 'torch.randint', 'torch.randint', (['(100)', '(1, 1)'], {}), '(100, (1, 1))\n', (1163, 1176), False, 'import torch\n'), ((1216, 1242), 'torch.randint', 'torch.randint', (['(100)', '(1, 1)'], {}), '(100, (1, 1))\n', (1229, 1242), False, 'import torch\n'), ((2200, 2226), 'torch.randint', 'torch.randint', (['(100)', '(1, 1)'], {}), '(100, (1, 1))\n', (2213, 2226), False, 'import torch\n'), ((2265, 2291), 'torch.randint', 'torch.randint', (['(100)', '(1, 1)'], {}), '(100, (1, 1))\n', (2278, 2291), False, 'import torch\n'), ((2330, 2356), 'torch.randint', 'torch.randint', (['(100)', '(1, 1)'], {}), '(100, (1, 1))\n', (2343, 2356), False, 'import torch\n'), ((2503, 2529), 'torch.randint', 'torch.randint', (['(100)', '(1, 1)'], {}), '(100, (1, 1))\n', (2516, 2529), False, 'import torch\n'), ((2568, 2594), 'torch.randint', 'torch.randint', (['(100)', '(1, 1)'], {}), '(100, (1, 1))\n', (2581, 2594), False, 'import torch\n'), ((2633, 2659), 'torch.randint', 'torch.randint', (['(100)', '(1, 1)'], {}), '(100, (1, 1))\n', (2646, 2659), False, 'import torch\n'), ((2738, 2764), 'torch.randint', 'torch.randint', (['(100)', '(1, 1)'], {}), '(100, (1, 1))\n', (2751, 2764), False, 'import torch\n')]
""" Testing for AUC ROC metric. """ from . import helpers import itertools import numpy as np import pyltr import sklearn.metrics class TestAUCROC(helpers.TestMetric): def get_metric(self): return pyltr.metrics.AUCROC() def get_queries_with_values(self): for i in range(0, 7): for tup in itertools.product(*([(0, 1)] * i)): if any(e != tup[0] for e in tup): yield (np.array(tup), sklearn.metrics.roc_auc_score(tup, range(i, 0, -1))) else: yield np.array(tup), 0.0 def get_queries(self): for i in range(0, 7): for tup in itertools.product(*([(0, 1)] * i)): yield np.array(tup)
[ "pyltr.metrics.AUCROC", "numpy.array", "itertools.product" ]
[((214, 236), 'pyltr.metrics.AUCROC', 'pyltr.metrics.AUCROC', ([], {}), '()\n', (234, 236), False, 'import pyltr\n'), ((330, 364), 'itertools.product', 'itertools.product', (['*([(0, 1)] * i)'], {}), '(*([(0, 1)] * i))\n', (347, 364), False, 'import itertools\n'), ((686, 720), 'itertools.product', 'itertools.product', (['*([(0, 1)] * i)'], {}), '(*([(0, 1)] * i))\n', (703, 720), False, 'import itertools\n'), ((744, 757), 'numpy.array', 'np.array', (['tup'], {}), '(tup)\n', (752, 757), True, 'import numpy as np\n'), ((443, 456), 'numpy.array', 'np.array', (['tup'], {}), '(tup)\n', (451, 456), True, 'import numpy as np\n'), ((586, 599), 'numpy.array', 'np.array', (['tup'], {}), '(tup)\n', (594, 599), True, 'import numpy as np\n')]
# external libraries import unittest import numpy as np # class to be tested from rss.src.RSSvectors import Mom4 class Mom4TestCase(unittest.TestCase): def test_boosted_to_rest_frame_of(self): """ Test that the boosting function works as advertised """ p4 = Mom4(10,0,0,9.9) # Alon z-axis print(p4[-1]) p4_in_rest_frame = p4.boosted_to_rest_frame_of( p4 ) self.assertAlmostEqual(p4_in_rest_frame.E, np.sqrt(10**2 - 9.9**2)) self.assertAlmostEqual(p4_in_rest_frame.px,0) self.assertAlmostEqual(p4_in_rest_frame.py,0) self.assertAlmostEqual(p4_in_rest_frame.pz,0) p4 = Mom4(10,3,3,3) # Along arbitrary axis p4_in_rest_frame = p4.boosted_to_rest_frame_of( p4 ) self.assertAlmostEqual(p4_in_rest_frame.E, np.sqrt(10**2 - 3 * 3**2)) self.assertAlmostEqual(p4_in_rest_frame.px,0) self.assertAlmostEqual(p4_in_rest_frame.py,0) self.assertAlmostEqual(p4_in_rest_frame.pz,0) p4 = Mom4(10,0,0,6) k4 = Mom4(10,0,1,6) # Boosting a different momentum k4_in_rest_frame = k4.boosted_to_rest_frame_of( p4 ) self.assertAlmostEqual(k4_in_rest_frame.E, np.sqrt(10**2 - 6**2)) self.assertAlmostEqual(k4_in_rest_frame.px,0) self.assertAlmostEqual(k4_in_rest_frame.py,1) self.assertAlmostEqual(k4_in_rest_frame.pz,0) def test_boosted_away_with_momentum(self): """ Test that the boosting function works as advertised """ rest_mom = Mom4(1,0,0,0) p4 = Mom4(10,0,0,6) # Along z-axis rest_mom_boosted_away = rest_mom.boosted_away_with_momentum( p4 ) self.assertAlmostEqual(rest_mom_boosted_away.E, 10/np.sqrt(10**2-6**2) ) self.assertAlmostEqual(rest_mom_boosted_away.px,0) self.assertAlmostEqual(rest_mom_boosted_away.py,0) self.assertAlmostEqual(rest_mom_boosted_away.pz,10*(6/10)/np.sqrt(10**2-6**2)) moving = Mom4(10,0,-7,0) push = Mom4(10,0,+7,0) # Along arbitrary axis moving_pushed_opposite = moving.boosted_away_with_momentum( push ) self.assertAlmostEqual(moving_pushed_opposite.E, np.sqrt(10**2 - 7**2)) self.assertAlmostEqual(moving_pushed_opposite.px,0) self.assertAlmostEqual(moving_pushed_opposite.py,0) self.assertAlmostEqual(moving_pushed_opposite.pz,0)
[ "rss.src.RSSvectors.Mom4", "numpy.sqrt" ]
[((300, 319), 'rss.src.RSSvectors.Mom4', 'Mom4', (['(10)', '(0)', '(0)', '(9.9)'], {}), '(10, 0, 0, 9.9)\n', (304, 319), False, 'from rss.src.RSSvectors import Mom4\n'), ((667, 684), 'rss.src.RSSvectors.Mom4', 'Mom4', (['(10)', '(3)', '(3)', '(3)'], {}), '(10, 3, 3, 3)\n', (671, 684), False, 'from rss.src.RSSvectors import Mom4\n'), ((1021, 1038), 'rss.src.RSSvectors.Mom4', 'Mom4', (['(10)', '(0)', '(0)', '(6)'], {}), '(10, 0, 0, 6)\n', (1025, 1038), False, 'from rss.src.RSSvectors import Mom4\n'), ((1049, 1066), 'rss.src.RSSvectors.Mom4', 'Mom4', (['(10)', '(0)', '(1)', '(6)'], {}), '(10, 0, 1, 6)\n', (1053, 1066), False, 'from rss.src.RSSvectors import Mom4\n'), ((1545, 1561), 'rss.src.RSSvectors.Mom4', 'Mom4', (['(1)', '(0)', '(0)', '(0)'], {}), '(1, 0, 0, 0)\n', (1549, 1561), False, 'from rss.src.RSSvectors import Mom4\n'), ((1572, 1589), 'rss.src.RSSvectors.Mom4', 'Mom4', (['(10)', '(0)', '(0)', '(6)'], {}), '(10, 0, 0, 6)\n', (1576, 1589), False, 'from rss.src.RSSvectors import Mom4\n'), ((1981, 1999), 'rss.src.RSSvectors.Mom4', 'Mom4', (['(10)', '(0)', '(-7)', '(0)'], {}), '(10, 0, -7, 0)\n', (1985, 1999), False, 'from rss.src.RSSvectors import Mom4\n'), ((2012, 2030), 'rss.src.RSSvectors.Mom4', 'Mom4', (['(10)', '(0)', '(+7)', '(0)'], {}), '(10, 0, +7, 0)\n', (2016, 2030), False, 'from rss.src.RSSvectors import Mom4\n'), ((466, 493), 'numpy.sqrt', 'np.sqrt', (['(10 ** 2 - 9.9 ** 2)'], {}), '(10 ** 2 - 9.9 ** 2)\n', (473, 493), True, 'import numpy as np\n'), ((818, 847), 'numpy.sqrt', 'np.sqrt', (['(10 ** 2 - 3 * 3 ** 2)'], {}), '(10 ** 2 - 3 * 3 ** 2)\n', (825, 847), True, 'import numpy as np\n'), ((1209, 1234), 'numpy.sqrt', 'np.sqrt', (['(10 ** 2 - 6 ** 2)'], {}), '(10 ** 2 - 6 ** 2)\n', (1216, 1234), True, 'import numpy as np\n'), ((2184, 2209), 'numpy.sqrt', 'np.sqrt', (['(10 ** 2 - 7 ** 2)'], {}), '(10 ** 2 - 7 ** 2)\n', (2191, 2209), True, 'import numpy as np\n'), ((1736, 1761), 'numpy.sqrt', 'np.sqrt', (['(10 ** 2 - 6 ** 2)'], {}), '(10 ** 2 - 6 ** 2)\n', (1743, 1761), True, 'import numpy as np\n'), ((1942, 1967), 'numpy.sqrt', 'np.sqrt', (['(10 ** 2 - 6 ** 2)'], {}), '(10 ** 2 - 6 ** 2)\n', (1949, 1967), True, 'import numpy as np\n')]
import numpy as np from keras import backend as K from keras.applications.imagenet_utils import preprocess_input from keras.preprocessing import image from heatmap import synset_to_dfs_ids from heatmap import to_heatmap def helper_test(model): img_path = "../examples/dog.jpg" new_model = to_heatmap(model) # Loading the image img = image.load_img(img_path, target_size=(800, 800)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) out = new_model.predict(x) s = "n02084071" # Imagenet code for "dog" ids = synset_to_dfs_ids(s) heatmap = out[0] if K.image_data_format() == 'channels_first': heatmap = heatmap[ids] heatmap = np.sum(heatmap, axis=0) else: heatmap = heatmap[:, :, ids] heatmap = np.sum(heatmap, axis=2) print(heatmap.shape) assert heatmap.shape[0] == heatmap.shape[1] K.clear_session()
[ "heatmap.synset_to_dfs_ids", "numpy.sum", "keras.backend.image_data_format", "heatmap.to_heatmap", "numpy.expand_dims", "keras.preprocessing.image.img_to_array", "keras.preprocessing.image.load_img", "keras.applications.imagenet_utils.preprocess_input", "keras.backend.clear_session" ]
[((300, 317), 'heatmap.to_heatmap', 'to_heatmap', (['model'], {}), '(model)\n', (310, 317), False, 'from heatmap import to_heatmap\n'), ((353, 401), 'keras.preprocessing.image.load_img', 'image.load_img', (['img_path'], {'target_size': '(800, 800)'}), '(img_path, target_size=(800, 800))\n', (367, 401), False, 'from keras.preprocessing import image\n'), ((410, 433), 'keras.preprocessing.image.img_to_array', 'image.img_to_array', (['img'], {}), '(img)\n', (428, 433), False, 'from keras.preprocessing import image\n'), ((442, 467), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (456, 467), True, 'import numpy as np\n'), ((476, 495), 'keras.applications.imagenet_utils.preprocess_input', 'preprocess_input', (['x'], {}), '(x)\n', (492, 495), False, 'from keras.applications.imagenet_utils import preprocess_input\n'), ((586, 606), 'heatmap.synset_to_dfs_ids', 'synset_to_dfs_ids', (['s'], {}), '(s)\n', (603, 606), False, 'from heatmap import synset_to_dfs_ids\n'), ((917, 934), 'keras.backend.clear_session', 'K.clear_session', ([], {}), '()\n', (932, 934), True, 'from keras import backend as K\n'), ((635, 656), 'keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (654, 656), True, 'from keras import backend as K\n'), ((727, 750), 'numpy.sum', 'np.sum', (['heatmap'], {'axis': '(0)'}), '(heatmap, axis=0)\n', (733, 750), True, 'import numpy as np\n'), ((816, 839), 'numpy.sum', 'np.sum', (['heatmap'], {'axis': '(2)'}), '(heatmap, axis=2)\n', (822, 839), True, 'import numpy as np\n')]
from __future__ import print_function, division import sys from datetime import datetime from collections import OrderedDict import numpy as np import h5py from .data import Dataset, SyncRecording, PatchClampRecording, TSeries from .test_pulse import PatchClampTestPulse from . import stimuli class MiesNwb(Dataset): """Class for accessing data from a MIES-generated NWB file. """ def __init__(self, filename): Dataset.__init__(self) self.filename = filename self._hdf = None self._sweeps = None self._timeseries = None self._groups = None self._notebook = None self.open() @property def hdf(self): if self._hdf is None: self.open() return self._hdf def notebook(self): """Return compiled data from the lab notebook. The format is a dict like ``{sweep_number: [ch1, ch2, ...]}`` that contains one key:value pair per sweep. Each value is a list containing one metadata dict for each channel in the sweep. For example:: nwb.notebook()[sweep_id][channel_id][metadata_key] """ if self._notebook is None: # collect all lab notebook entries sweep_entries = OrderedDict() tp_entries = [] device = list(self.hdf['general/devices'].keys())[0].split('_',1)[-1] nb_keys = self.hdf['general']['labnotebook'][device]['numericalKeys'][0] nb_fields = OrderedDict([(k, i) for i,k in enumerate(nb_keys)]) # convert notebook to array here, otherwise we incur the decompression cost for the entire # dataset every time we try to access part of it. nb = np.array(self.hdf['general']['labnotebook'][device]['numericalValues']) # EntrySourceType field is needed to distinguish between records created by TP vs sweep entry_source_type_index = nb_fields.get('EntrySourceType', None) nb_iter = iter(range(nb.shape[0])) # so we can skip multiple rows from within the loop for i in nb_iter: rec = nb[i] sweep_num = rec[0,0] is_tp_record = False is_sweep_record = False # ignore records that were generated by test pulse # (note: entrySourceType is nan if an older pxp is re-exported to nwb using newer MIES) if entry_source_type_index is not None and not np.isnan(rec[entry_source_type_index][0]): if rec[entry_source_type_index][0] == 0: is_sweep_record = True else: is_tp_record = True elif i < nb.shape[0] - 1: # Older files may be missing EntrySourceType. In this case, we can identify TP blocks # as two records containing a "TP Peak Resistance" value in the first record followed # by a "TP Pulse Duration" value in the second record. tp_peak = rec[nb_fields['TP Peak Resistance']] if any(np.isfinite(tp_peak)): tp_dur = nb[i+1][nb_fields['TP Pulse Duration']] if any(np.isfinite(tp_dur)): next(nb_iter) is_tp_record = True if not is_tp_record: is_sweep_record = np.isfinite(sweep_num) if is_tp_record: rec = np.array(rec) next(nb_iter) rec2 = np.array(nb[i+1]) mask = ~np.isnan(rec2) rec[mask] = rec2[mask] tp_entries.append(rec) elif is_sweep_record: sweep_num = int(sweep_num) # each sweep gets multiple nb records; for each field we use the last non-nan value in any record if sweep_num not in sweep_entries: sweep_entries[sweep_num] = np.array(rec) else: mask = ~np.isnan(rec) sweep_entries[sweep_num][mask] = rec[mask] for swid, entry in sweep_entries.items(): # last column is "global"; applies to all channels mask = ~np.isnan(entry[:,8]) entry[mask] = entry[:,8:9][mask] # first 4 fields of first column apply to all channels entry[:4] = entry[:4, 0:1] # async AD fields (notably used to record temperature) appear # only in column 0, but might move to column 8 later? Since these # are not channel-specific, we'll copy them to all channels for i,k in enumerate(nb_keys): if not k.startswith('Async AD '): continue entry[i] = entry[i, 0] # convert to list-o-dicts meta = [] for i in range(entry.shape[1]): tm = entry[:, i] meta.append(OrderedDict([(nb_keys[j], (None if np.isnan(tm[j]) else tm[j])) for j in range(len(nb_keys))])) sweep_entries[swid] = meta # Load textual keys in a similar way text_nb_keys = self.hdf['general']['labnotebook'][device]['textualKeys'][0] text_nb_fields = OrderedDict([(k, i) for i,k in enumerate(text_nb_keys)]) text_nb = np.array(self.hdf['general']['labnotebook'][device]['textualValues']) entry_source_type_index = text_nb_fields.get('EntrySourceType', None) for rec in text_nb: if entry_source_type_index is None: # older nwb files lack EntrySourceType; fake it for now source_type = 0 else: try: source_type = int(rec[entry_source_type_index, 0]) except ValueError: # No entry source type recorded here; skip for now. continue if source_type != 0: # Select only sweep records for now. continue try: sweep_id = int(rec[0,0]) except ValueError: # Not sure how to handle records with no sweep ID; skip for now. continue sweep_entry = sweep_entries[sweep_id] for k,i in text_nb_fields.items(): for j, val in enumerate(rec[i, :-1]): if k in sweep_entry[j]: # already have a value here; don't overwrite. continue if val == '': # take value from last column if this one is empty val == rec[i, -1] if val == '': # no value here; skip. continue sweep_entry[j][k] = val self._notebook = sweep_entries self._tp_notebook = tp_entries self._notebook_keys = nb_fields self._tp_entries = None return self._notebook @property def contents(self): """A list of all sweeps in this file. """ if self._sweeps is None: # sort all timeseries groups into sweeps / channels self._timeseries = {} for ts_name, ts in self.hdf['acquisition/timeseries'].items(): src = dict([field.split('=') for field in ts.attrs['source'].split(';')]) sweep = int(src['Sweep']) ad_chan = int(src['AD']) src['hdf_group_name'] = 'acquisition/timeseries/' + ts_name self._timeseries.setdefault(sweep, {})[ad_chan] = src sweep_ids = sorted(list(self._timeseries.keys())) self._sweeps = [] for sweep_id in sweep_ids: try: srec = self.create_sync_recording(int(sweep_id)) except Exception: print("Skipping sweep %s:" % sweep_id) sys.excepthook(*sys.exc_info()) continue self._sweeps.append(srec) return self._sweeps def create_sync_recording(self, sweep_id): return MiesSyncRecording(self, sweep_id) def close(self): self.hdf.close() self._hdf = None def open(self): if self._hdf is not None: return try: self._hdf = h5py.File(self.filename, 'r') except Exception: print("Error opening: %s" % self.filename) raise def __enter__(self): self.open() return self def __exit__(self, *args): self.close() @staticmethod def pack_sweep_data(sweeps): """Return a single array containing all data from a list of sweeps. The array shape is (sweeps, channels, samples, 2), where the final axis contains recorded data at index 0 and the stimulus at index 1. All sweeps must have the same length and number of channels. """ sweeps = [s.data() for s in sweeps] data = np.empty((len(sweeps),) + sweeps[0].shape, dtype=sweeps[0].dtype) for i in range(len(sweeps)): data[i] = sweeps[i] return data @staticmethod def igorpro_date(timestamp): """Convert an IgorPro timestamp (seconds since 1904-01-01) to a datetime object. """ dt = datetime(1970,1,1) - datetime(1904,1,1) return datetime.utcfromtimestamp(timestamp) - dt @property def children(self): return self.contents def __repr__(self): return "<%s %s>" % (self.__class__.__name__, self.filename) def __getstate__(self): state = self.__dict__.copy() # don't try to pickle hdf objects state['_hdf'] = None return state def test_pulse_entries(self): if self._tp_entries is None: self._tp_entries = [] fields = ['TP Baseline Vm', 'TP Baseline pA', 'TP Peak Resistance', 'TP Steady State Resistance'] stim_fields = ['TP Baseline Fraction', 'TP Amplitude VC', 'TP Amplitude IC', 'TP Pulse Duration'] for rec in self._tp_notebook: entry = {'timestamp': MiesNwb.igorpro_date(rec[1, 0])} for f in fields: i = self._notebook_keys[f] entry[f] = rec[i, :8] entry['stim'] = {f:rec[self._notebook_keys[f], 8] for f in stim_fields} self._tp_entries.append(entry) return self._tp_entries class MiesTSeries(TSeries): def __init__(self, recording, chan): start = recording._meta['start_time'] # Note: this is also available in meta()['Minimum Sampling interval'], # but that key is missing in some older NWB files. dt = recording.primary_hdf.attrs['IGORWaveScaling'][1,0] / 1000. TSeries.__init__(self, recording=recording, channel_id=chan, dt=dt, start_time=start) @property def data(self): if self._data is None: rec = self.recording chan = self.channel_id if chan == 'primary': scale = 1e-12 if rec.clamp_mode == 'vc' else 1e-3 self._data = np.array(rec.primary_hdf) * scale elif chan == 'command': scale = 1e-3 if rec.clamp_mode == 'vc' else 1e-12 # command values are stored _without_ holding, so we add # that back in here. offset = rec.holding_potential if rec.clamp_mode == 'vc' else rec.holding_current if offset is None: exc = Exception("Holding value unknown for this recording; cannot generate command data.") # Mark this exception so it can be ignored in specific places exc._ignorable_bug_flag = True raise exc self._data = (np.array(rec.command_hdf) * scale) + offset return self._data @property def shape(self): # allow accessing shape without reading all data if self._data is None: rec = self.recording chan = self.channel_id if chan == 'primary': return rec.primary_hdf.shape elif chan == 'command': return rec.command_hdf.shape else: return self._data.shape class MiesRecording(PatchClampRecording): """A single stimulus / recording made on a single channel. """ def __init__(self, sweep, sweep_id, ad_chan): self._sweep = sweep self._nwb = sweep._nwb self._trace_id = (sweep_id, ad_chan) self._inserted_test_pulse = None self._nearest_test_pulse = None self._hdf_group_name = sweep._channel_keys[ad_chan]['hdf_group_name'] self._hdf_group = None self._da_chan = None headstage_id = int(self.hdf_group['electrode_name'][()][0].split('_')[1]) PatchClampRecording.__init__(self, device_type='MultiClamp 700', device_id=headstage_id, sync_recording=sweep) # update metadata nb = self._nwb.notebook()[int(self._trace_id[0])][headstage_id] self.meta['holding_potential'] = ( None if nb['V-Clamp Holding Level'] is None else nb['V-Clamp Holding Level'] * 1e-3 ) self.meta['holding_current'] = ( None if nb['I-Clamp Holding Level'] is None else nb['I-Clamp Holding Level'] * 1e-12 ) self._meta['notebook'] = nb if nb['Clamp Mode'] == 0: self._meta['clamp_mode'] = 'vc' else: self._meta['clamp_mode'] = 'ic' self._meta['bridge_balance'] = ( 0.0 if nb['Bridge Bal Enable'] == 0.0 or nb['Bridge Bal Value'] is None else nb['Bridge Bal Value'] * 1e6 ) self._meta['lpf_cutoff'] = nb['LPF Cutoff'] offset = nb['Pipette Offset'] # sometimes the pipette offset recording can fail?? self._meta['pipette_offset'] = None if offset is None else offset * 1e-3 datetime = MiesNwb.igorpro_date(nb['TimeStamp']) self.meta['start_time'] = datetime self._channels['primary'] = MiesTSeries(self, 'primary') self._channels['command'] = MiesTSeries(self, 'command') @property def stimulus(self): stim = self._meta.get('stimulus', None) if stim is None: stim = MiesStimulus(self) self._meta['stimulus'] = stim return stim def _stim_wave_note(self): """Return version and epochs from stim wave note """ notebook = self._meta['notebook'] sweep_count = int(notebook['Set Sweep Count']) wave_note = notebook['Stim Wave Note'] lines = wave_note.split('\n') version = [line for line in lines if line.startswith('Version =')] if len(version) == 0: version = 0 else: version = float(version[0].rstrip(';').split(' = ')[1]) epochs = [] for line in lines: if not line.startswith('Sweep = %d;' % sweep_count): continue epoch = dict([part.split(' = ') for part in line.split(';') if '=' in part]) epochs.append(epoch) return version, epochs @property def hdf_group(self): if self._hdf_group is None: self._hdf_group = self._nwb.hdf[self._hdf_group_name] return self._hdf_group @property def clamp_mode(self): return 'vc' if self.meta['notebook']['Clamp Mode'] == 0 else 'ic' @property def primary_hdf(self): """The raw HDF5 data containing the primary channel recording """ return self.hdf_group['data'] @property def command_hdf(self): """The raw HDF5 data containing the stimulus command """ return self._nwb.hdf['stimulus/presentation/data_%05d_DA%d/data' % (self._trace_id[0], self.da_chan())] @property def nearest_test_pulse(self): """The test pulse that was acquired nearest to this recording. """ if self.has_inserted_test_pulse: return self.inserted_test_pulse else: if self._nearest_test_pulse is None: self._find_nearest_test_pulse() return self._nearest_test_pulse def _find_nearest_test_pulse(self): start = self.start_time min_dt = None nearest = None for entry in self._nwb.test_pulse_entries(): dt = abs((entry['timestamp'] - start).total_seconds()) if min_dt is None or dt < min_dt: min_dt = dt nearest = entry if nearest is None: return None self._nearest_test_pulse = MiesTestPulse(nearest, self) @property def has_inserted_test_pulse(self): return self.meta['notebook']['TP Insert Checkbox'] == 1.0 @property def inserted_test_pulse(self): """Return the test pulse inserted at the beginning of the recording, or None if no pulse was inserted. """ if self._inserted_test_pulse is None: if not self.has_inserted_test_pulse: return None # get start/stop indices of the test pulse region pulse_dur = self.meta['notebook']['TP Pulse Duration'] / 1000. total_dur = pulse_dur / (1.0 - 2. * self.meta['notebook']['TP Baseline Fraction']) start = 0 stop = start + int(total_dur / self['primary'].dt) tp = PatchClampTestPulse(self, indices=(start, stop)) # Record amplitude as specified by MIES if self.clamp_mode == 'vc': amp = self.meta['notebook']['TP Amplitude VC'] * 1e-3 else: amp = self.meta['notebook']['TP Amplitude IC'] * 1e-12 self._inserted_test_pulse = tp return self._inserted_test_pulse @property def baseline_regions(self): """A list of (start, stop) time pairs that cover regions of the recording the cell is expected to be in a steady state. """ pri = self['primary'] regions = [] start = self.meta['notebook']['Delay onset auto'] / 1000. # duration of test pulse dur = self.meta['notebook']['Delay onset user'] / 1000. # duration of baseline if dur > 0: regions.append((start, start+dur)) dur = self.meta['notebook']['Delay termination'] / 1000. if dur > 0: regions.append((pri.t_end-dur, pri.t_end)) return regions def da_chan(self): """Return the DA channel ID for this recording. """ if self._da_chan is None: hdf = self._nwb.hdf['stimulus/presentation'] stims = [k for k in hdf.keys() if k.startswith('data_%05d_'%self._trace_id[0])] for s in stims: elec = hdf[s]['electrode_name'][()][0] if elec == 'electrode_%d' % self.device_id: self._da_chan = int(s.split('_')[-1][2:]) if self._da_chan is None: raise Exception("Cannot find DA channel for headstage %d" % self.device_id) return self._da_chan def _descr(self): stim = self.stimulus stim_name = '' if stim is None else stim.description return "%s %s.%s stim=%s" % (PatchClampRecording._descr(self), self._trace_id[0], self.device_id, stim_name) def __getstate__(self): state = self.__dict__.copy() state['_hdf_group'] = None return state class MiesTestPulse(PatchClampTestPulse): def __init__(self, entry, rec): chan = rec.device_id self._nb_entry = {} for k,v in entry.items(): if isinstance(v, np.ndarray): self._nb_entry[k] = v[chan] else: self._nb_entry[k] = v clamp_mode = 'vc' if np.isnan(self._nb_entry['TP Baseline Vm']) else 'ic' PatchClampRecording.__init__(self, device_type=rec.device_type, device_id=rec.device_id, start_time=entry['timestamp'], channels={}, clamp_mode=clamp_mode ) @property def indices(self): return None @property def access_resistance(self): """The access resistance measured from this test pulse. Includes the bridge balance resistance if the recording was made in current clamp mode. """ if self.clamp_mode == 'vc': return self._nb_entry['TP Peak Resistance'] * 1e6 else: return None @property def input_resistance(self): """The input resistance measured from this test pulse. """ return self._nb_entry['TP Steady State Resistance'] * 1e6 @property def capacitance(self): """The capacitance of the cell measured from this test pulse. """ return None @property def time_constant(self): """The membrane time constant measured from this test pulse. """ return None @property def baseline_potential(self): """The potential of the cell membrane measured (or clamped) before the onset of the test pulse. """ if self.clamp_mode == 'ic': return self._nb_entry['TP Baseline Vm'] * 1e-3 else: return None # how do we get the holding potential?? @property def baseline_current(self): """The pipette current measured (or clamped) before the onset of the test pulse. """ if self.clamp_mode == 'vc': return self._nb_entry['TP Baseline pA'] * 1e-12 else: return None # how do we get the holding current?? class MiesSyncRecording(SyncRecording): """Represents one recorded sweep with multiple channels. """ def __init__(self, nwb, sweep_id): sweep_id = int(sweep_id) self._nwb = nwb self._sweep_id = sweep_id self._chan_meta = None self._traces = None self._notebook_entry = None # get list of all A/D channels in this sweep self._channel_keys = self._nwb._timeseries.get(sweep_id, {}) self._ad_channels = sorted(list(self._channel_keys.keys())) devs = OrderedDict() for ch in self._ad_channels: # there is a very rare/specific acquisition bug that we want to be able to ignore here: try: hdf_group_name = self._channel_keys[ch]['hdf_group_name'] rec = self.create_recording(sweep_id, ch) except Exception as exc: if hasattr(exc, '_ignorable_bug_flag'): print("Warning: ignoring channel %s in %s; could not determine holding value." % (ch, self)) continue else: raise devs[rec.device_id] = rec SyncRecording.__init__(self, devs, parent=nwb) self._meta['sweep_id'] = sweep_id def create_recording(self, sweep_id, ch): return MiesRecording(self, sweep_id, ch) @property def key(self): return self._sweep_id def __repr__(self): return "<%s sweep=%d>" % (self.__class__.__name__, self._sweep_id) @property def parent(self): return self._nwb class MiesStimulus(stimuli.Stimulus): """Stimulus that generates its children by parsing a MIES wavenote """ def __init__(self, recording): self._recording = recording stim_name = recording.hdf_group['stimulus_description'][()][0] stimuli.Stimulus.__init__(self, description=stim_name) self._items = None @property def items(self): if self._items is None: self._items = [] self._parse_wavenote() return tuple(self._items) def _parse_wavenote(self): rec = self._recording # Add holding offset if rec.clamp_mode == 'ic': units = 'A' self.append_item(stimuli.Offset( start_time=0, amplitude=rec.holding_current, description="holding current", units=units, )) elif rec.clamp_mode == 'vc': units = 'V' self.append_item(stimuli.Offset( start_time=0, amplitude=rec.holding_potential, description="holding potential", units=units, )) else: units = None # inserted test pulse? if rec.has_inserted_test_pulse: self.append_item(rec.inserted_test_pulse.stimulus) notebook = rec._meta['notebook'] if 'Stim Wave Note' in notebook: # Stim Wave Note format is explained here: # https://alleninstitute.github.io/MIES/file/_m_i_e_s___wave_builder_8ipf.html#_CPPv319WB_GetWaveNoteEntry4wave8variable6string8variable8variable # read stimulus structure from notebook version, epochs = rec._stim_wave_note() assert len(epochs) > 0 scale = (1e-3 if rec.clamp_mode == 'vc' else 1e-12) * notebook['Stim Scale Factor'] t = (notebook['Delay onset oodDAQ'] + notebook['Delay onset user'] + notebook['Delay onset auto']) * 1e-3 # if dDAQ is active, add delay from previous channels if notebook['Distributed DAQ'] == 1.0: ddaq_delay = notebook['Delay distributed DAQ'] * 1e-3 for dev in rec.parent.devices: rec = rec.parent[dev] if rec is self._recording: break _, epochs = rec._stim_wave_note() for ep in epochs: dt = float(ep.get('Duration', 0)) * 1e-3 t += dt t += ddaq_delay for epoch_n,epoch in enumerate(epochs): try: if epoch['Epoch'] == 'nan': # Sweep-specific entry; not sure if we need to do anything with this. continue stim_type = epoch.get('Type') duration = float(epoch.get('Duration', 0)) * 1e-3 name = "Epoch %d" % int(epoch['Epoch']) if stim_type == 'Square pulse': item = stimuli.SquarePulse( start_time=t, amplitude=float(epoch['Amplitude']) * scale, duration=duration, description=name, units=units, ) elif stim_type == 'Pulse Train': assert epoch['Poisson distribution'] == 'False', "Poisson distributed pulse train not supported" assert epoch['Mixed frequency'] == 'False', "Mixed frequency pulse train not supported" assert epoch['Pulse Type'] == 'Square', "Pulse train with %s pulse type not supported" item = stimuli.SquarePulseTrain( start_time=t, n_pulses=int(epoch['Number of pulses']), pulse_duration=float(epoch['Pulse duration']) * 1e-3, amplitude=float(epoch['Amplitude']) * scale, interval=float(epoch['Pulse To Pulse Length']) * 1e-3, description=name, units=units, ) elif stim_type == 'Sin Wave': # bug in stim wave note version 2: log chirp field is inverted is_chirp = epoch['Log chirp'] == ('False' if version <= 2 else 'True') if is_chirp: assert epoch['FunctionType'] == 'Sin', "Chirp wave function type %s not supported" % epoch['Function type'] item = stimuli.Chirp( start_time=t, start_frequency=float(epoch['Frequency']), end_frequency=float(epoch['End frequency']), duration=duration, amplitude=float(epoch['Amplitude']) * scale, phase=0, offset=float(epoch['Offset']) * scale, description=name, units=units, ) else: if epoch['FunctionType'] == 'Sin': phase = 0 elif epoch['FunctionType'] == 'Cos': phase = np.pi / 2.0 else: raise ValueError("Unsupported sine wave function type: %r" % epoch['FunctionType']) item = stimuli.Sine( start_time=t, frequency=float(epoch['Frequency']), duration=duration, amplitude=float(epoch['Amplitude']) * scale, phase=phase, offset=float(epoch['Offset']) * scale, description=name, units=units, ) else: print(epoch) print("Warning: unknown stimulus type %s in %s sweep %s" % (stim_type, rec._nwb, rec._trace_id)) item = None except Exception as exc: print("Warning: error reading stimulus epoch %d in %s sweep %s: %s" % (epoch_n, rec._nwb, rec._trace_id, str(exc))) t += duration if item is not None: self.append_item(item)
[ "h5py.File", "numpy.isfinite", "numpy.isnan", "datetime.datetime", "datetime.datetime.utcfromtimestamp", "numpy.array", "sys.exc_info", "collections.OrderedDict" ]
[((23002, 23015), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (23013, 23015), False, 'from collections import OrderedDict\n'), ((1266, 1279), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1277, 1279), False, 'from collections import OrderedDict\n'), ((1735, 1806), 'numpy.array', 'np.array', (["self.hdf['general']['labnotebook'][device]['numericalValues']"], {}), "(self.hdf['general']['labnotebook'][device]['numericalValues'])\n", (1743, 1806), True, 'import numpy as np\n'), ((5561, 5630), 'numpy.array', 'np.array', (["self.hdf['general']['labnotebook'][device]['textualValues']"], {}), "(self.hdf['general']['labnotebook'][device]['textualValues'])\n", (5569, 5630), True, 'import numpy as np\n'), ((8807, 8836), 'h5py.File', 'h5py.File', (['self.filename', '"""r"""'], {}), "(self.filename, 'r')\n", (8816, 8836), False, 'import h5py\n'), ((9817, 9837), 'datetime.datetime', 'datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (9825, 9837), False, 'from datetime import datetime\n'), ((9838, 9858), 'datetime.datetime', 'datetime', (['(1904)', '(1)', '(1)'], {}), '(1904, 1, 1)\n', (9846, 9858), False, 'from datetime import datetime\n'), ((9872, 9908), 'datetime.datetime.utcfromtimestamp', 'datetime.utcfromtimestamp', (['timestamp'], {}), '(timestamp)\n', (9897, 9908), False, 'from datetime import datetime\n'), ((20546, 20588), 'numpy.isnan', 'np.isnan', (["self._nb_entry['TP Baseline Vm']"], {}), "(self._nb_entry['TP Baseline Vm'])\n", (20554, 20588), True, 'import numpy as np\n'), ((3555, 3568), 'numpy.array', 'np.array', (['rec'], {}), '(rec)\n', (3563, 3568), True, 'import numpy as np\n'), ((3630, 3649), 'numpy.array', 'np.array', (['nb[i + 1]'], {}), '(nb[i + 1])\n', (3638, 3649), True, 'import numpy as np\n'), ((4386, 4407), 'numpy.isnan', 'np.isnan', (['entry[:, 8]'], {}), '(entry[:, 8])\n', (4394, 4407), True, 'import numpy as np\n'), ((11663, 11688), 'numpy.array', 'np.array', (['rec.primary_hdf'], {}), '(rec.primary_hdf)\n', (11671, 11688), True, 'import numpy as np\n'), ((2506, 2547), 'numpy.isnan', 'np.isnan', (['rec[entry_source_type_index][0]'], {}), '(rec[entry_source_type_index][0])\n', (2514, 2547), True, 'import numpy as np\n'), ((3676, 3690), 'numpy.isnan', 'np.isnan', (['rec2'], {}), '(rec2)\n', (3684, 3690), True, 'import numpy as np\n'), ((3150, 3170), 'numpy.isfinite', 'np.isfinite', (['tp_peak'], {}), '(tp_peak)\n', (3161, 3170), True, 'import numpy as np\n'), ((3472, 3494), 'numpy.isfinite', 'np.isfinite', (['sweep_num'], {}), '(sweep_num)\n', (3483, 3494), True, 'import numpy as np\n'), ((4087, 4100), 'numpy.array', 'np.array', (['rec'], {}), '(rec)\n', (4095, 4100), True, 'import numpy as np\n'), ((12346, 12371), 'numpy.array', 'np.array', (['rec.command_hdf'], {}), '(rec.command_hdf)\n', (12354, 12371), True, 'import numpy as np\n'), ((3277, 3296), 'numpy.isfinite', 'np.isfinite', (['tp_dur'], {}), '(tp_dur)\n', (3288, 3296), True, 'import numpy as np\n'), ((4159, 4172), 'numpy.isnan', 'np.isnan', (['rec'], {}), '(rec)\n', (4167, 4172), True, 'import numpy as np\n'), ((8408, 8422), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (8420, 8422), False, 'import sys\n'), ((5210, 5225), 'numpy.isnan', 'np.isnan', (['tm[j]'], {}), '(tm[j])\n', (5218, 5225), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # Copyright 2019 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License """ Module handles computing and formatting basic statistics about a dataset like false negatives and false positives """ import numpy as np counts_str = ''' === Counts === False Positives: {false_pos} True Negatives: {true_neg} False Negatives: {false_neg} True Positives: {true_pos} '''.strip() summary_str = ''' === Summary === {num_correct} out of {total} {accuracy_ratio:.2%} {false_pos_ratio:.2%} false positives {false_neg_ratio:.2%} false negatives ''' class Stats: """Represents a set of statistics from a model run on a dataset""" def __init__(self, outputs, targets, filenames): self.outputs = np.array(outputs) self.targets = np.array(targets) self.filenames = filenames self.num_positives = int((self.targets > 0.5).sum()) self.num_negatives = int((self.targets < 0.5).sum()) # Methods self.false_positives = lambda threshold=0.5: self.calc_metric(False, True, threshold) / max(1, self.num_negatives) self.false_negatives = lambda threshold=0.5: self.calc_metric(False, False, threshold) / max(1, self.num_positives) self.num_correct = lambda threshold=0.5: ( (self.outputs >= threshold) == self.targets.astype(bool) ).sum() self.num_incorrect = lambda threshold=0.5: len(self) - self.num_correct(threshold) self.accuracy = lambda threshold=0.5: self.num_correct(threshold) / max(1, len(self)) def __len__(self): return len(self.outputs) def to_np_dict(self): import numpy as np return { 'outputs': self.outputs, 'targets': self.targets, 'filenames': np.array(self.filenames) } @staticmethod def from_np_dict(data) -> 'Stats': return Stats(data['outputs'], data['targets'], data['filenames']) def to_dict(self, threshold=0.5): return { 'true_pos': self.calc_metric(True, True, threshold), 'true_neg': self.calc_metric(True, False, threshold), 'false_pos': self.calc_metric(False, True, threshold), 'false_neg': self.calc_metric(False, False, threshold), } def counts_str(self, threshold=0.5): return counts_str.format(**self.to_dict(threshold)) def summary_str(self, threshold=0.5): return summary_str.format( num_correct=self.num_correct(threshold), total=len(self), accuracy_ratio=self.accuracy(threshold), false_pos_ratio=self.false_positives(threshold), false_neg_ratio=self.false_negatives(threshold) ) def calc_filenames(self, is_correct: bool, actual_output: bool, threshold=0.5) -> list: """Find a list of files with the given classification""" return [ filename for output, target, filename in zip(self.outputs, self.targets, self.filenames) if ((output > threshold) == bool(target)) == is_correct and actual_output == bool(output > threshold) ] def calc_metric(self, is_correct: bool, actual_output: bool, threshold=0.5) -> int: """For example, calc_metric(False, True) calculates false positives""" return int( ((((self.outputs > threshold) == self.targets.astype(bool)) == is_correct) & ((self.outputs > threshold) == actual_output)).sum() ) @staticmethod def matches_sample(output, target, threshold, is_correct, actual_output): """ Check if a sample with the given network output, target output, and threshold is the classification (is_correct, actual_output) like true positive or false negative """ return (bool(output > threshold) == bool(target)) == is_correct and actual_output == bool(output > threshold)
[ "numpy.array" ]
[((1227, 1244), 'numpy.array', 'np.array', (['outputs'], {}), '(outputs)\n', (1235, 1244), True, 'import numpy as np\n'), ((1268, 1285), 'numpy.array', 'np.array', (['targets'], {}), '(targets)\n', (1276, 1285), True, 'import numpy as np\n'), ((2462, 2486), 'numpy.array', 'np.array', (['self.filenames'], {}), '(self.filenames)\n', (2470, 2486), True, 'import numpy as np\n')]
#!/usr/bin/env python import os import time import numpy as np from astropy.io import fits from aoide import voronoi import argparse def main(): print("\n======================= Aoide | Step 3 ====================\n") print("AoideVoronoi.py: Voronoi Tesselation based on Stellar Continuum Signal\n") args = parse_args() input_cube = os.path.abspath(args.input_cube) name = args.name continuum_signal_band = args.band_continuum target_sn = args.sn max_area = args.max_area working_directory = os.path.dirname(os.path.abspath(input_cube)) voronoi_directory = working_directory + "/voronoi/" if not os.path.exists(voronoi_directory): os.makedirs(voronoi_directory) print("Voronoi Products Directory {} not found. Creating it.".format( voronoi_directory)) else: print("Voronoi products will be saved to {}".format(voronoi_directory)) # Change to Voronoi directory os.chdir(voronoi_directory) print("Working directory set to {}".format(voronoi_directory)) # Work on input cube hdu = fits.open(input_cube) data = hdu[0].data select = np.isnan(data) data[select] = 0 error = np.sqrt(hdu[1].data) error[select] = 1e9 hdr = hdu[0].header wave = np.arange(hdr['NAXIS3']) * 1.25 + hdr['CRVAL3'] hdu.close() select_wave = (wave > continuum_signal_band[0]) & ( wave < continuum_signal_band[1]) mean_img = np.mean(data[select_wave, :, :], 0) err_img = np.std(data[select_wave, :, :], 0) # Create CONTINUUM SIGNAL and NOISE samples on which to iterate hdu = fits.PrimaryHDU(mean_img) hdu.writeto('signal_cont.fits', overwrite=True) hdu = fits.PrimaryHDU(err_img) hdu.writeto('noise_cont.fits', overwrite=True) voronoi.binning_fits('signal_cont.fits', voronoi_directory + 'noise_cont.fits', target_sn, name, max_area=max_area, gersho=True, plot=False) bin_cube('{}.voronoi.pixel.dat'.format(name), input_cube, '{}.voronoi_rss.fits'.format(name)) return voronoi_directory def bin_cube(voronoi_pixel, input_cube, output_rss): hdu = fits.open(input_cube) data = hdu[0].data select = np.isnan(data) data[select] = 0 error = np.sqrt(hdu[1].data) error[select] = 1e9 hdr = hdu[0].header wave = np.arange(hdr['NAXIS3']) * 1.25 + hdr['CRVAL3'] hdu.close() ascii_in = open(voronoi_pixel, 'r') lines = ascii_in.readlines() x = np.arange(len(lines) - 1, dtype=np.int16) y = np.arange(len(lines) - 1, dtype=np.int16) binNr = np.arange(len(lines) - 1, dtype=np.int16) for i in range(1, len(lines)): line = lines[i].split() x[i - 1] = int(line[0]) y[i - 1] = int(line[1]) binNr[i - 1] = int(line[2]) rss_data = np.zeros((max(binNr), len(wave)), dtype=np.float32) rss_error = np.zeros((max(binNr), len(wave)), dtype=np.float32) for l in range(max(binNr)): select_bin = binNr == (l + 1) x_bin = x[select_bin] - 1 y_bin = y[select_bin] - 1 for j in range(len(x_bin)): rss_data[l, :] += data[:, y_bin[j], x_bin[j]] rss_error[l, :] += error[:, y_bin[j], x_bin[j]]**2 rss_error[l, :] = np.sqrt(rss_error[l, :]) rss_error[np.isnan(rss_error)] = 1e9 rss_out = fits.HDUList([fits.PrimaryHDU(rss_data), fits.ImageHDU( rss_error, name='ERROR'), fits.ImageHDU(np.zeros(rss_data.shape, dtype=np.uint16), name='MASK')]) rss_out[0].header = hdr rss_out[0].header['CDELT1'] = 1.25 rss_out[0].header['CRVAL1'] = hdr['CRVAL3'] rss_out[0].header['CRPIX1'] = 1 rss_out.writeto(output_rss, overwrite=True, output_verify='fix') def parse_args(): parser = argparse.ArgumentParser( description="Voronoi bin a clean MUSE datacube based on S/N in the stellar continuum.") parser.add_argument('input_cube', metavar='CUBE_IN', type=str, nargs='?', help='Input FITS MUSE cube to bin.') parser.add_argument('-n', '--name', metavar='GALAXY_NAME', default='NAME_OF_GALAXY', type=str, nargs='?', help='Name of your galaxy.') parser.add_argument('-b', '--band_continuum', nargs='?', default=(6427, 6632), help='Wavelength range, in Angstroms, of a line-free region of stellar continuum signal. Express as a tuple, e.g. (6427, 6632).') parser.add_argument('-s', '--sn', type=int, nargs='?', default=50, help='Signal-to-noise ratio used for Voronoi threshold. Default is 50.') parser.add_argument('-m', '--max_area', type=int, nargs='?', default=1000, help='Maximum area, in pixels, for any given Voronoi bin. ') args = parser.parse_args() return args if __name__ == '__main__': start_time = time.time() voronoi_directory = main() runtime = round((time.time() - start_time), 3) print("\n================= Aoide | Step 3 Finished ================\n") print("Finished in {} minutes.".format(round(runtime / 60, 3))) print("Use the Voronoi-binned cube as part of your Paradise STELLAR fitting.") print("You'll find these products in {}.".format(voronoi_directory))
[ "astropy.io.fits.ImageHDU", "os.path.abspath", "argparse.ArgumentParser", "os.makedirs", "numpy.std", "astropy.io.fits.PrimaryHDU", "aoide.voronoi.binning_fits", "os.path.exists", "numpy.isnan", "time.time", "numpy.zeros", "numpy.mean", "numpy.arange", "astropy.io.fits.open", "os.chdir", "numpy.sqrt" ]
[((362, 394), 'os.path.abspath', 'os.path.abspath', (['args.input_cube'], {}), '(args.input_cube)\n', (377, 394), False, 'import os\n'), ((968, 995), 'os.chdir', 'os.chdir', (['voronoi_directory'], {}), '(voronoi_directory)\n', (976, 995), False, 'import os\n'), ((1099, 1120), 'astropy.io.fits.open', 'fits.open', (['input_cube'], {}), '(input_cube)\n', (1108, 1120), False, 'from astropy.io import fits\n'), ((1157, 1171), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (1165, 1171), True, 'import numpy as np\n'), ((1205, 1225), 'numpy.sqrt', 'np.sqrt', (['hdu[1].data'], {}), '(hdu[1].data)\n', (1212, 1225), True, 'import numpy as np\n'), ((1461, 1496), 'numpy.mean', 'np.mean', (['data[select_wave, :, :]', '(0)'], {}), '(data[select_wave, :, :], 0)\n', (1468, 1496), True, 'import numpy as np\n'), ((1511, 1545), 'numpy.std', 'np.std', (['data[select_wave, :, :]', '(0)'], {}), '(data[select_wave, :, :], 0)\n', (1517, 1545), True, 'import numpy as np\n'), ((1625, 1650), 'astropy.io.fits.PrimaryHDU', 'fits.PrimaryHDU', (['mean_img'], {}), '(mean_img)\n', (1640, 1650), False, 'from astropy.io import fits\n'), ((1714, 1738), 'astropy.io.fits.PrimaryHDU', 'fits.PrimaryHDU', (['err_img'], {}), '(err_img)\n', (1729, 1738), False, 'from astropy.io import fits\n'), ((1795, 1943), 'aoide.voronoi.binning_fits', 'voronoi.binning_fits', (['"""signal_cont.fits"""', "(voronoi_directory + 'noise_cont.fits')", 'target_sn', 'name'], {'max_area': 'max_area', 'gersho': '(True)', 'plot': '(False)'}), "('signal_cont.fits', voronoi_directory +\n 'noise_cont.fits', target_sn, name, max_area=max_area, gersho=True,\n plot=False)\n", (1815, 1943), False, 'from aoide import voronoi\n'), ((2168, 2189), 'astropy.io.fits.open', 'fits.open', (['input_cube'], {}), '(input_cube)\n', (2177, 2189), False, 'from astropy.io import fits\n'), ((2226, 2240), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (2234, 2240), True, 'import numpy as np\n'), ((2274, 2294), 'numpy.sqrt', 'np.sqrt', (['hdu[1].data'], {}), '(hdu[1].data)\n', (2281, 2294), True, 'import numpy as np\n'), ((3767, 3883), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Voronoi bin a clean MUSE datacube based on S/N in the stellar continuum."""'}), "(description=\n 'Voronoi bin a clean MUSE datacube based on S/N in the stellar continuum.')\n", (3790, 3883), False, 'import argparse\n'), ((4860, 4871), 'time.time', 'time.time', ([], {}), '()\n', (4869, 4871), False, 'import time\n'), ((558, 585), 'os.path.abspath', 'os.path.abspath', (['input_cube'], {}), '(input_cube)\n', (573, 585), False, 'import os\n'), ((655, 688), 'os.path.exists', 'os.path.exists', (['voronoi_directory'], {}), '(voronoi_directory)\n', (669, 688), False, 'import os\n'), ((698, 728), 'os.makedirs', 'os.makedirs', (['voronoi_directory'], {}), '(voronoi_directory)\n', (709, 728), False, 'import os\n'), ((3271, 3295), 'numpy.sqrt', 'np.sqrt', (['rss_error[l, :]'], {}), '(rss_error[l, :])\n', (3278, 3295), True, 'import numpy as np\n'), ((3310, 3329), 'numpy.isnan', 'np.isnan', (['rss_error'], {}), '(rss_error)\n', (3318, 3329), True, 'import numpy as np\n'), ((1285, 1309), 'numpy.arange', 'np.arange', (["hdr['NAXIS3']"], {}), "(hdr['NAXIS3'])\n", (1294, 1309), True, 'import numpy as np\n'), ((2354, 2378), 'numpy.arange', 'np.arange', (["hdr['NAXIS3']"], {}), "(hdr['NAXIS3'])\n", (2363, 2378), True, 'import numpy as np\n'), ((3365, 3390), 'astropy.io.fits.PrimaryHDU', 'fits.PrimaryHDU', (['rss_data'], {}), '(rss_data)\n', (3380, 3390), False, 'from astropy.io import fits\n'), ((3392, 3430), 'astropy.io.fits.ImageHDU', 'fits.ImageHDU', (['rss_error'], {'name': '"""ERROR"""'}), "(rss_error, name='ERROR')\n", (3405, 3430), False, 'from astropy.io import fits\n'), ((4924, 4935), 'time.time', 'time.time', ([], {}), '()\n', (4933, 4935), False, 'import time\n'), ((3455, 3496), 'numpy.zeros', 'np.zeros', (['rss_data.shape'], {'dtype': 'np.uint16'}), '(rss_data.shape, dtype=np.uint16)\n', (3463, 3496), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import gensim import numpy as np from numpy import linalg as LA import logging logger = logging.getLogger(__name__) def embedding_matrix(nb_tokens, embedding_size, token_to_index, glove_path=None, unit_norm=True, rs=None, dtype=None): rs = rs if rs else np.random.RandomState(0) embedding_matrix_np = rs.uniform(low=0.0, high=1.0, size=(nb_tokens, embedding_size)) if glove_path is not None: word_to_vector = load_glove(path=glove_path, words={token for token in token_to_index}) for word, vector in word_to_vector.items(): word_id = token_to_index[word] vector_np = np.array(vector) embedding_matrix_np[word_id, :] = vector_np if unit_norm: norms = LA.norm(embedding_matrix_np, axis=1, keepdims=True) embedding_matrix_np /= norms if dtype is not None: embedding_matrix_np = embedding_matrix_np.astype(dtype) return embedding_matrix_np def load_glove(path, words=None): word_to_embedding = {} with open(path, 'r') as stream: for n, line in enumerate(stream): if not isinstance(line, str): line = line.decode('utf-8') split_line = line.split(' ') word = split_line[0] if words is None or word in words: try: word_to_embedding[word] = [float(f) for f in split_line[1:]] except ValueError: logger.error('{}\t{}\t{}'.format(n, word, str(split_line))) return word_to_embedding def load_word2vec(path, words=None, binary=True): word_to_embedding = {} model = gensim.models.KeyedVectors.load_word2vec_format(path, binary=binary) for word in words: if word in model: word_to_embedding[word] = model[word].tolist() return word_to_embedding
[ "numpy.random.RandomState", "numpy.array", "numpy.linalg.norm", "gensim.models.KeyedVectors.load_word2vec_format", "logging.getLogger" ]
[((116, 143), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (133, 143), False, 'import logging\n'), ((1772, 1840), 'gensim.models.KeyedVectors.load_word2vec_format', 'gensim.models.KeyedVectors.load_word2vec_format', (['path'], {'binary': 'binary'}), '(path, binary=binary)\n', (1819, 1840), False, 'import gensim\n'), ((372, 396), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (393, 396), True, 'import numpy as np\n'), ((877, 928), 'numpy.linalg.norm', 'LA.norm', (['embedding_matrix_np'], {'axis': '(1)', 'keepdims': '(True)'}), '(embedding_matrix_np, axis=1, keepdims=True)\n', (884, 928), True, 'from numpy import linalg as LA\n'), ((770, 786), 'numpy.array', 'np.array', (['vector'], {}), '(vector)\n', (778, 786), True, 'import numpy as np\n')]
"""Debiasing using reweighing""" """ This data recipe performs reweighing debiasing using the AIF360 package. https://github.com/Trusted-AI/AIF360 <NAME>., <NAME>. Data preprocessing techniques for classification without discrimination. Knowl Inf Syst 33, 1–33 (2012). https://doi.org/10.1007/s10115-011-0463-8 The transformer splits the original data as specified and returns training, validation, and test sets with weights added. 1. Update the folder_path and data_file variables to indicate the location of the dataset(s). 2. validation_test_files lists additional validation or test files that need to be updated with weights. 3. validation_split indicates the percentiles at which the original data should be split to create a validation and test set. If it's empty, no validation or test set is created. [0.7] would create a 70/30 training/validation split. [0.7, 0.9] would create a 70/20/10 training, validation, and test split. 4. target is the name of the target column. 5. favorable_label and unfavorable_label are the socially positive and negative target value respectively. 6. protected_group_info list of lists, where each sublist contains the name of a protected column, the unprivledged level, and the privleged level. Each of the protected columns must be binary. 7. From the Datasets section of driverless, click on ADD DATASET and then UPLOAD DATA RECIPE to upload this file. Be sure to use the specified validation set to be used for validation when a model is trained. The weights can cause leakage if the validation or test data is used for determining the weights. """ import datatable as dt import numpy as np import os from h2oaicore.data import CustomData from h2oaicore.systemutils import config class MyReweightingData(CustomData): _modules_needed_by_name = ['datetime', 'fairlearn', 'aif360', 'sklearn'] @staticmethod def create_data(): import pandas as pd from h2oaicore.models_utils import import_tensorflow tf = import_tensorflow() # above is because aif360 requires tensorflow from aif360.datasets import BinaryLabelDataset from aif360.algorithms.preprocessing.reweighing import Reweighing """ Update the below as needed """ ######### ######### ######### # Path to the data folder_path = 'tmp/' # Data file data_file = 'housing_train_proc.csv' full_data_file = folder_path + data_file if not os.path.isfile(full_data_file): # for testing, just return something if config.hard_asserts: return dt.Frame(np.array([[1, 2, 3], [4, 5, 6]])) else: return [] train = pd.read_csv(full_data_file) validation_test_files = ['housing_test_proc.csv'] validation_split = [0.6, 0.8] # Target column target = 'high_priced' favorable_label = 0 unfavorable_label = 1 # Privleged_group_info = [[Protetected group name 1, prevleged level, unprivleged level], [Protetected group name 2, prevleged level, unprivleged level]] # The protected group columns need to be binary protected_group_info = [['hispanic', 0, 1], ['black', 0, 1]] ######### ######### ######### # Set up protected group info protected_groups = [group_info[0] for group_info in protected_group_info] dataset_orig = BinaryLabelDataset(df=train, label_names=[target], favorable_label=favorable_label, unfavorable_label=unfavorable_label, protected_attribute_names=protected_groups) privileged_groups = [] unprivileged_groups = [] for protected_group in protected_group_info: privileged_groups_dict = {} unprivileged_groups_dict = {} privileged_groups_dict[protected_group[0]] = protected_group[1] unprivileged_groups_dict[protected_group[0]] = protected_group[2] privileged_groups.append(privileged_groups_dict) unprivileged_groups.append(unprivileged_groups_dict) # Fit weights on the full dataset to be used on the external test set, if given RW_full = Reweighing(unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups) RW_full.fit(dataset_orig) # Split the original data into train, validation, and test if applicable if len(validation_split) == 1: dataset_orig_train, dataset_orig_valid = dataset_orig.split(validation_split, shuffle=True) elif len(validation_split) == 2: dataset_orig_train_valid, dataset_orig_test = dataset_orig.split([validation_split[1]], shuffle=True) # Fit the weights on both the validation and test set for the test set split RW_train_valid = Reweighing(unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups) RW_train_valid.fit(dataset_orig_train_valid) dataset_orig_train, dataset_orig_valid = dataset_orig_train_valid.split( [validation_split[0] / (validation_split[1])], shuffle=True) else: dataset_orig_train = dataset_orig # Fit weights on the training set only RW = Reweighing(unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups) RW.fit(dataset_orig_train) dataset_transf_train = RW.transform(dataset_orig_train) # Add the weigts to the training set train_df = pd.DataFrame(dataset_transf_train.features, columns=dataset_transf_train.feature_names) train_df[target] = dataset_transf_train.labels.ravel() train_df['weights'] = dataset_transf_train.instance_weights.ravel() # Create datasets with minimum features calculated the given number of days ahead dataset_dict = {} dataset_dict[data_file.split('.')[0] + "_rw_train.csv"] = train_df # Add weights to the validation split (if a validation split was specified) if len(validation_split) >= 1: dataset_transf_valid = RW.transform(dataset_orig_valid) valid_df = pd.DataFrame(dataset_transf_valid.features, columns=dataset_transf_valid.feature_names) valid_df[target] = dataset_transf_valid.labels.ravel() valid_df['weights'] = dataset_transf_valid.instance_weights.ravel() dataset_dict[data_file.split('.')[0] + "_rw_validation.csv"] = valid_df # Add weights to the test split (if a test split was specified) if len(validation_split) >= 2: dataset_transf_test = RW_train_valid.transform(dataset_orig_test) test_df = pd.DataFrame(dataset_transf_test.features, columns=dataset_transf_test.feature_names) test_df[target] = dataset_transf_test.labels.ravel() test_df['weights'] = dataset_transf_test.instance_weights.ravel() dataset_dict[data_file.split('.')[0] + "_rw_test.csv"] = test_df # Add weights to the test files (If provided) for valid_file in validation_test_files: valid = pd.read_csv(folder_path + valid_file) dataset_valid_orig = BinaryLabelDataset(df=valid, label_names=[target], favorable_label=favorable_label, unfavorable_label=unfavorable_label, protected_attribute_names=protected_groups) dataset_transf_valid = RW_full.transform(dataset_valid_orig) valid_df = pd.DataFrame(dataset_transf_valid.features, columns=dataset_transf_valid.feature_names) valid_df[target] = dataset_transf_valid.labels.ravel() valid_df['weights'] = dataset_transf_valid.instance_weights.ravel() dataset_dict[valid_file.split('.')[0] + "_rw_transformed.csv"] = valid_df return dataset_dict
[ "pandas.DataFrame", "aif360.datasets.BinaryLabelDataset", "pandas.read_csv", "h2oaicore.models_utils.import_tensorflow", "aif360.algorithms.preprocessing.reweighing.Reweighing", "os.path.isfile", "numpy.array" ]
[((2001, 2020), 'h2oaicore.models_utils.import_tensorflow', 'import_tensorflow', ([], {}), '()\n', (2018, 2020), False, 'from h2oaicore.models_utils import import_tensorflow\n'), ((2748, 2775), 'pandas.read_csv', 'pd.read_csv', (['full_data_file'], {}), '(full_data_file)\n', (2759, 2775), True, 'import pandas as pd\n'), ((3476, 3649), 'aif360.datasets.BinaryLabelDataset', 'BinaryLabelDataset', ([], {'df': 'train', 'label_names': '[target]', 'favorable_label': 'favorable_label', 'unfavorable_label': 'unfavorable_label', 'protected_attribute_names': 'protected_groups'}), '(df=train, label_names=[target], favorable_label=\n favorable_label, unfavorable_label=unfavorable_label,\n protected_attribute_names=protected_groups)\n', (3494, 3649), False, 'from aif360.datasets import BinaryLabelDataset\n'), ((4312, 4405), 'aif360.algorithms.preprocessing.reweighing.Reweighing', 'Reweighing', ([], {'unprivileged_groups': 'unprivileged_groups', 'privileged_groups': 'privileged_groups'}), '(unprivileged_groups=unprivileged_groups, privileged_groups=\n privileged_groups)\n', (4322, 4405), False, 'from aif360.algorithms.preprocessing.reweighing import Reweighing\n'), ((5366, 5459), 'aif360.algorithms.preprocessing.reweighing.Reweighing', 'Reweighing', ([], {'unprivileged_groups': 'unprivileged_groups', 'privileged_groups': 'privileged_groups'}), '(unprivileged_groups=unprivileged_groups, privileged_groups=\n privileged_groups)\n', (5376, 5459), False, 'from aif360.algorithms.preprocessing.reweighing import Reweighing\n'), ((5619, 5711), 'pandas.DataFrame', 'pd.DataFrame', (['dataset_transf_train.features'], {'columns': 'dataset_transf_train.feature_names'}), '(dataset_transf_train.features, columns=dataset_transf_train.\n feature_names)\n', (5631, 5711), True, 'import pandas as pd\n'), ((2504, 2534), 'os.path.isfile', 'os.path.isfile', (['full_data_file'], {}), '(full_data_file)\n', (2518, 2534), False, 'import os\n'), ((6253, 6345), 'pandas.DataFrame', 'pd.DataFrame', (['dataset_transf_valid.features'], {'columns': 'dataset_transf_valid.feature_names'}), '(dataset_transf_valid.features, columns=dataset_transf_valid.\n feature_names)\n', (6265, 6345), True, 'import pandas as pd\n'), ((6784, 6874), 'pandas.DataFrame', 'pd.DataFrame', (['dataset_transf_test.features'], {'columns': 'dataset_transf_test.feature_names'}), '(dataset_transf_test.features, columns=dataset_transf_test.\n feature_names)\n', (6796, 6874), True, 'import pandas as pd\n'), ((7221, 7258), 'pandas.read_csv', 'pd.read_csv', (['(folder_path + valid_file)'], {}), '(folder_path + valid_file)\n', (7232, 7258), True, 'import pandas as pd\n'), ((7292, 7465), 'aif360.datasets.BinaryLabelDataset', 'BinaryLabelDataset', ([], {'df': 'valid', 'label_names': '[target]', 'favorable_label': 'favorable_label', 'unfavorable_label': 'unfavorable_label', 'protected_attribute_names': 'protected_groups'}), '(df=valid, label_names=[target], favorable_label=\n favorable_label, unfavorable_label=unfavorable_label,\n protected_attribute_names=protected_groups)\n', (7310, 7465), False, 'from aif360.datasets import BinaryLabelDataset\n'), ((7658, 7750), 'pandas.DataFrame', 'pd.DataFrame', (['dataset_transf_valid.features'], {'columns': 'dataset_transf_valid.feature_names'}), '(dataset_transf_valid.features, columns=dataset_transf_valid.\n feature_names)\n', (7670, 7750), True, 'import pandas as pd\n'), ((4933, 5026), 'aif360.algorithms.preprocessing.reweighing.Reweighing', 'Reweighing', ([], {'unprivileged_groups': 'unprivileged_groups', 'privileged_groups': 'privileged_groups'}), '(unprivileged_groups=unprivileged_groups, privileged_groups=\n privileged_groups)\n', (4943, 5026), False, 'from aif360.algorithms.preprocessing.reweighing import Reweighing\n'), ((2653, 2685), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6]]'], {}), '([[1, 2, 3], [4, 5, 6]])\n', (2661, 2685), True, 'import numpy as np\n')]
import numpy as np import pytest import rlberry.seeding as seeding from rlberry.envs import gym_make from copy import deepcopy gym_envs = [ 'Acrobot-v1', 'CartPole-v1', 'MountainCar-v0', ] def get_env_trajectory(env, horizon): states = [] ss = env.reset() for ii in range(horizon): states.append(ss) ss, _, done, _ = env.step(env.action_space.sample()) if done: ss = env.reset() return states def compare_trajectories(traj1, traj2): for ss1, ss2 in zip(traj1, traj2): if not np.array_equal(ss1, ss2): return False return True @pytest.mark.parametrize("env_name", gym_envs) def test_env_seeding(env_name): seeding.set_global_seed(123) env1 = gym_make(env_name) seeding.set_global_seed(456) env2 = gym_make(env_name) seeding.set_global_seed(123) env3 = gym_make(env_name) if deepcopy(env1).is_online(): traj1 = get_env_trajectory(env1, 500) traj2 = get_env_trajectory(env2, 500) traj3 = get_env_trajectory(env3, 500) assert not compare_trajectories(traj1, traj2) assert compare_trajectories(traj1, traj3) @pytest.mark.parametrize("env_name", gym_envs) def test_copy_reseeding(env_name): seeding.set_global_seed(123) env = gym_make(env_name) c_env = deepcopy(env) c_env.reseed() if deepcopy(env).is_online(): traj1 = get_env_trajectory(env, 500) traj2 = get_env_trajectory(c_env, 500) assert not compare_trajectories(traj1, traj2)
[ "copy.deepcopy", "numpy.array_equal", "pytest.mark.parametrize", "rlberry.seeding.set_global_seed", "rlberry.envs.gym_make" ]
[((629, 674), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""env_name"""', 'gym_envs'], {}), "('env_name', gym_envs)\n", (652, 674), False, 'import pytest\n'), ((1181, 1226), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""env_name"""', 'gym_envs'], {}), "('env_name', gym_envs)\n", (1204, 1226), False, 'import pytest\n'), ((712, 740), 'rlberry.seeding.set_global_seed', 'seeding.set_global_seed', (['(123)'], {}), '(123)\n', (735, 740), True, 'import rlberry.seeding as seeding\n'), ((752, 770), 'rlberry.envs.gym_make', 'gym_make', (['env_name'], {}), '(env_name)\n', (760, 770), False, 'from rlberry.envs import gym_make\n'), ((776, 804), 'rlberry.seeding.set_global_seed', 'seeding.set_global_seed', (['(456)'], {}), '(456)\n', (799, 804), True, 'import rlberry.seeding as seeding\n'), ((816, 834), 'rlberry.envs.gym_make', 'gym_make', (['env_name'], {}), '(env_name)\n', (824, 834), False, 'from rlberry.envs import gym_make\n'), ((840, 868), 'rlberry.seeding.set_global_seed', 'seeding.set_global_seed', (['(123)'], {}), '(123)\n', (863, 868), True, 'import rlberry.seeding as seeding\n'), ((880, 898), 'rlberry.envs.gym_make', 'gym_make', (['env_name'], {}), '(env_name)\n', (888, 898), False, 'from rlberry.envs import gym_make\n'), ((1267, 1295), 'rlberry.seeding.set_global_seed', 'seeding.set_global_seed', (['(123)'], {}), '(123)\n', (1290, 1295), True, 'import rlberry.seeding as seeding\n'), ((1306, 1324), 'rlberry.envs.gym_make', 'gym_make', (['env_name'], {}), '(env_name)\n', (1314, 1324), False, 'from rlberry.envs import gym_make\n'), ((1338, 1351), 'copy.deepcopy', 'deepcopy', (['env'], {}), '(env)\n', (1346, 1351), False, 'from copy import deepcopy\n'), ((559, 583), 'numpy.array_equal', 'np.array_equal', (['ss1', 'ss2'], {}), '(ss1, ss2)\n', (573, 583), True, 'import numpy as np\n'), ((907, 921), 'copy.deepcopy', 'deepcopy', (['env1'], {}), '(env1)\n', (915, 921), False, 'from copy import deepcopy\n'), ((1379, 1392), 'copy.deepcopy', 'deepcopy', (['env'], {}), '(env)\n', (1387, 1392), False, 'from copy import deepcopy\n')]
import glob import numpy as np import xlrd import csv def parse_xlsx_file(file_path): """Parse contents of xlsx file into numpy array. Author: <NAME> (<EMAIL>) Args: file_path (str): path for the xlsx file. Returns: numpy.ndarray: parsed contents of the xlsx file. """ # Open worksheet. worksheet = xlrd.open_workbook(file_path).sheet_by_index(0) # Parse data from worksheet. data = np.empty((worksheet.nrows-1, worksheet.ncols), dtype=object) for row in np.arange(1, worksheet.nrows): for col in np.arange(worksheet.ncols): data[row-1, col] = worksheet.cell_value(row, col) return data def parse_csv_file(file_path): """Parse contents of csv file into numpy array. Author: <NAME> (<EMAIL>) Args: file_path (str): path for the csv file. Returns: numpy.ndarray: parsed contents of the csv file. """ # Parse contents into array and return it. reader = csv.reader(open(file_path, "r"), delimiter=",") raw_data = list(reader) raw_data = [[x for x in el if x != ''] for el in raw_data] raw_data = [el for el in raw_data if len(el) == 4] data = np.array(raw_data).astype(np.float) return data def parse_acc_data(data_folder_path, dataset_num): """Parse contents of data files into one numpy array. Author: <NAME> (<EMAIL>) Args: data_folder_path (str): path of folder containing the dataset. Yields: (tuple): parsed contents of next raw data file (examples and target values). """ if dataset_num == 1: # Go over xlsx files in data folder. for f in glob.glob(data_folder_path + '*.xlsx'): data_raw = parse_xlsx_file(f) data = data_raw[:, 2:-1] target = data_raw[:, -1] unlabeled_msk = target == '' target_final = target[~unlabeled_msk].astype(np.int) data_final = data[~unlabeled_msk, :].astype(np.float) yield data_final, target_final elif dataset_num == 2 or dataset_num == 3: # Go over .xlsx files in data folder. for f in glob.glob(data_folder_path + '*.csv'): data_raw = parse_csv_file(f) data = data_raw[:, :-1] target = data_raw[:, -1] yield data.astype(np.int), target.astype(np.int) def concatenate_data(data_folder_path, dataset_num): """Concatenate data from different files of same dataset into one numpy array. Author: <NAME> (<EMAIL>) Args: data_folder_path (str): path of folder containing the dataset. dataset_num (int): index of dataset to parse. Returns: (tuple): parsed contents of dataset files (examples and target values). """ data_master = None target_master = None first = True # Parse accelerometer data and concatenate into data matrix. for data, target in parse_acc_data(data_folder_path, dataset_num): if first: data_master = data target_master = target first = False else: data_master = np.vstack((data_master, data)) target_master = np.hstack((target_master, target)) return data_master, target_master def get_data1(data_folder_path): """Get numpy arrays representing the contents of specified datset. Author: <NAME> (<EMAIL>) Args: file_path (str): path for the xlsx file. Returns: (tuple): parsed contents of dataset files (examples and target values). Raises: ValueError """ dataset_num = 1 return concatenate_data(data_folder_path, dataset_num) def get_data2(data_folder_path): """Get numpy arrays representing the contents of specified datset. Author: <NAME> (<EMAIL>) Args: file_path (str): path for the xlsx file. Returns: (tuple): parsed contents of dataset files (examples and target values). Raises: ValueError """ dataset_num = 2 return concatenate_data(data_folder_path, dataset_num) def get_data3(data_folder_path): """Get numpy arrays representing the contents of specified datset. Author: <NAME> (<EMAIL>) Args: file_path (str): path for the xlsx file. Returns: (tuple): parsed contents of dataset files (examples and target values). Raises: ValueError """ dataset_num = 3 return concatenate_data(data_folder_path, dataset_num)
[ "numpy.empty", "xlrd.open_workbook", "numpy.hstack", "numpy.array", "numpy.arange", "glob.glob", "numpy.vstack" ]
[((443, 505), 'numpy.empty', 'np.empty', (['(worksheet.nrows - 1, worksheet.ncols)'], {'dtype': 'object'}), '((worksheet.nrows - 1, worksheet.ncols), dtype=object)\n', (451, 505), True, 'import numpy as np\n'), ((519, 548), 'numpy.arange', 'np.arange', (['(1)', 'worksheet.nrows'], {}), '(1, worksheet.nrows)\n', (528, 548), True, 'import numpy as np\n'), ((569, 595), 'numpy.arange', 'np.arange', (['worksheet.ncols'], {}), '(worksheet.ncols)\n', (578, 595), True, 'import numpy as np\n'), ((1664, 1702), 'glob.glob', 'glob.glob', (["(data_folder_path + '*.xlsx')"], {}), "(data_folder_path + '*.xlsx')\n", (1673, 1702), False, 'import glob\n'), ((350, 379), 'xlrd.open_workbook', 'xlrd.open_workbook', (['file_path'], {}), '(file_path)\n', (368, 379), False, 'import xlrd\n'), ((1194, 1212), 'numpy.array', 'np.array', (['raw_data'], {}), '(raw_data)\n', (1202, 1212), True, 'import numpy as np\n'), ((2145, 2182), 'glob.glob', 'glob.glob', (["(data_folder_path + '*.csv')"], {}), "(data_folder_path + '*.csv')\n", (2154, 2182), False, 'import glob\n'), ((3123, 3153), 'numpy.vstack', 'np.vstack', (['(data_master, data)'], {}), '((data_master, data))\n', (3132, 3153), True, 'import numpy as np\n'), ((3182, 3216), 'numpy.hstack', 'np.hstack', (['(target_master, target)'], {}), '((target_master, target))\n', (3191, 3216), True, 'import numpy as np\n')]
import random import numpy as np import matplotlib.pyplot as plt import logging from qlazy import QState from qlazy.tools.Register import CreateRegister, InitRegister EPS = 1.e-8 QS_Y = QState(qubit_num=1).h(0).s(0) def init_qs_list(N, prob): return [QState(qubit_num=1).h(0).s(0).z(0) if random.uniform(0, 1) <= prob else QState(qubit_num=1).h(0).s(0) for i in range(N)] def measure_X_stab(mval_list): p0 = (mval_list[3-1] + mval_list[4-1] + mval_list[5-1] + mval_list[6-1]) % 2 p1 = (mval_list[2-1] + mval_list[5-1] + mval_list[6-1] + mval_list[7-1]) % 2 p2 = (mval_list[1-1] + mval_list[4-1] + mval_list[6-1] + mval_list[7-1]) % 2 if p0 == 0 and p1 == 0 and p2 == 0: return True else: return False def measure_logical_X(mval_list): if sum(mval_list) % 2 == 0: return True else: return False def distillation_Y(qs_list): data = CreateRegister(1) # data qubit code = CreateRegister(7) # logical qubit for Steane code anci = CreateRegister(1) # ancilla qubit for S gate qubit_num = InitRegister(data, code, anci) qs = QState(qubit_num=qubit_num-len(anci)) # bell state qs.h(data[0]).cx(data[0], code[6]) # steane code qs.h(code[0]).h(code[1]).h(code[2]) qs.cx(code[6], code[3]).cx(code[6], code[4]) qs.cx(code[2], code[3]).cx(code[2], code[4]).cx(code[2], code[5]) qs.cx(code[1], code[4]).cx(code[1], code[5]).cx(code[1], code[6]) qs.cx(code[0], code[3]).cx(code[0], code[5]).cx(code[0], code[6]) # S gates and measurements mval_list = [] for i in range(7): qs_total = qs.tenspro(qs_list[i]) qs_total.cx(code[i], anci[0]).h(anci[0]).cx(code[i], anci[0]).h(anci[0]) mval = int(qs_total.mx(qid=[code[i]]).last) mval_list.append(mval) qs = qs_total.partial(qid=data+code) if measure_X_stab(mval_list) == False: return None qs_pat = qs_total.partial(qid=data) if measure_logical_X(mval_list) == True: qs_pat.z(0) return qs_pat def prob_simulation(prob, trial): fail = 0 for _ in range(trial): while True: qs_list = init_qs_list(7, prob) qs = distillation_Y(qs_list) if qs is not None: break if abs(qs.fidelity(QS_Y) - 1.0) > EPS: fail += 1 return fail / trial def prob_theoretical(p): u, v = 2 * p - 1, 1 - 2 * p return (1 + 7 * u**3 + 7 * u**4 + u**7) / (2 * (1 + 7 * v**4)) if __name__ == '__main__': # logging logger = logging.getLogger('ErrorSimulation') logger.setLevel(20) sh = logging.StreamHandler() fh = logging.FileHandler('error_simulation_Y.log', mode='w') logger.addHandler(sh) logger.addHandler(fh) # error probability (theoretical) prob_in = np.linspace(0.0, 0.4, 50) prob_out_linear = np.array([p for p in prob_in]) prob_out_theoretical = np.array([prob_theoretical(p) for p in prob_in]) # error probability (simulation) trial = 500 prob_in_simulation = np.linspace(0.0, 0.4, 9) logger.info("{0:}, {1:}, {2:}".format("in", "out(simulation)", "out(theoretical)")) prob_out_simulation = [] for p_in in prob_in_simulation: p_out = prob_simulation(p_in, trial) logger.info("{0:.6f}, {1:.6f} {2:.6f}".format(p_in, p_out, prob_theoretical(p_in))) prob_out_simulation.append(p_out) # plot fig, ax = plt.subplots() ax.set_xlabel("error probability (in)") ax.set_ylabel("error probability (out)") ax.set_title("magic state distillation: |Y>") ax.grid() ax.plot(prob_in, prob_out_theoretical, color='orange', label='theoretical') ax.plot(prob_in, prob_out_linear, color='gray', linestyle='dashed') ax.plot(prob_in_simulation, prob_out_simulation, color='green', label='simultion', marker='s') ax.legend(loc=0) fig.tight_layout() plt.savefig('error_simulation_Y.png') plt.show()
[ "qlazy.tools.Register.CreateRegister", "matplotlib.pyplot.savefig", "matplotlib.pyplot.show", "logging.FileHandler", "random.uniform", "logging.StreamHandler", "qlazy.QState", "qlazy.tools.Register.InitRegister", "numpy.array", "numpy.linspace", "matplotlib.pyplot.subplots", "logging.getLogger" ]
[((875, 892), 'qlazy.tools.Register.CreateRegister', 'CreateRegister', (['(1)'], {}), '(1)\n', (889, 892), False, 'from qlazy.tools.Register import CreateRegister, InitRegister\n'), ((918, 935), 'qlazy.tools.Register.CreateRegister', 'CreateRegister', (['(7)'], {}), '(7)\n', (932, 935), False, 'from qlazy.tools.Register import CreateRegister, InitRegister\n'), ((980, 997), 'qlazy.tools.Register.CreateRegister', 'CreateRegister', (['(1)'], {}), '(1)\n', (994, 997), False, 'from qlazy.tools.Register import CreateRegister, InitRegister\n'), ((1042, 1072), 'qlazy.tools.Register.InitRegister', 'InitRegister', (['data', 'code', 'anci'], {}), '(data, code, anci)\n', (1054, 1072), False, 'from qlazy.tools.Register import CreateRegister, InitRegister\n'), ((2486, 2522), 'logging.getLogger', 'logging.getLogger', (['"""ErrorSimulation"""'], {}), "('ErrorSimulation')\n", (2503, 2522), False, 'import logging\n'), ((2556, 2579), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (2577, 2579), False, 'import logging\n'), ((2589, 2644), 'logging.FileHandler', 'logging.FileHandler', (['"""error_simulation_Y.log"""'], {'mode': '"""w"""'}), "('error_simulation_Y.log', mode='w')\n", (2608, 2644), False, 'import logging\n'), ((2754, 2779), 'numpy.linspace', 'np.linspace', (['(0.0)', '(0.4)', '(50)'], {}), '(0.0, 0.4, 50)\n', (2765, 2779), True, 'import numpy as np\n'), ((2802, 2832), 'numpy.array', 'np.array', (['[p for p in prob_in]'], {}), '([p for p in prob_in])\n', (2810, 2832), True, 'import numpy as np\n'), ((2988, 3012), 'numpy.linspace', 'np.linspace', (['(0.0)', '(0.4)', '(9)'], {}), '(0.0, 0.4, 9)\n', (2999, 3012), True, 'import numpy as np\n'), ((3371, 3385), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3383, 3385), True, 'import matplotlib.pyplot as plt\n'), ((3838, 3875), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""error_simulation_Y.png"""'], {}), "('error_simulation_Y.png')\n", (3849, 3875), True, 'import matplotlib.pyplot as plt\n'), ((3880, 3890), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3888, 3890), True, 'import matplotlib.pyplot as plt\n'), ((187, 206), 'qlazy.QState', 'QState', ([], {'qubit_num': '(1)'}), '(qubit_num=1)\n', (193, 206), False, 'from qlazy import QState\n'), ((296, 316), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (310, 316), False, 'import random\n'), ((330, 349), 'qlazy.QState', 'QState', ([], {'qubit_num': '(1)'}), '(qubit_num=1)\n', (336, 349), False, 'from qlazy import QState\n'), ((258, 277), 'qlazy.QState', 'QState', ([], {'qubit_num': '(1)'}), '(qubit_num=1)\n', (264, 277), False, 'from qlazy import QState\n')]
# Copyright 2018 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for simulator.py""" from typing import List, Dict import numpy as np import pytest import cirq from cirq.testing.mock import mock @mock.patch.multiple(cirq.SimulatesSamples, _run=mock.Mock()) def test_run_simulator_run(): simulator = cirq.SimulatesSamples() expected_measurements = {'a': np.array([[1]])} simulator._run.return_value = expected_measurements circuit = mock.Mock(cirq.Circuit) param_resolver = mock.Mock(cirq.ParamResolver) expected_result = cirq.TrialResult(repetitions=10, measurements=expected_measurements, params=param_resolver) assert expected_result == simulator.run(program=circuit, repetitions=10, param_resolver=param_resolver) simulator._run.assert_called_once_with(circuit=circuit, repetitions=10, param_resolver=param_resolver) @mock.patch.multiple(cirq.SimulatesSamples, _run=mock.Mock()) def test_run_simulator_sweeps(): simulator = cirq.SimulatesSamples() expected_measurements = {'a': np.array([[1]])} simulator._run.return_value = expected_measurements circuit = mock.Mock(cirq.Circuit) param_resolvers = [mock.Mock(cirq.ParamResolver), mock.Mock(cirq.ParamResolver)] expected_results = [cirq.TrialResult(repetitions=10, measurements=expected_measurements, params=param_resolvers[0]), cirq.TrialResult(repetitions=10, measurements=expected_measurements, params=param_resolvers[1])] assert expected_results == simulator.run_sweep(program=circuit, repetitions=10, params=param_resolvers) simulator._run.assert_called_with(circuit=circuit, repetitions=10, param_resolver=mock.ANY) assert simulator._run.call_count == 2 @mock.patch.multiple(cirq.SimulatesIntermediateWaveFunction, _simulator_iterator=mock.Mock()) def test_wave_simulator(): simulator = cirq.SimulatesIntermediateWaveFunction() final_state = np.array([1, 0, 0, 0]) def steps(*args, **kwargs): result = mock.Mock() result.measurements = {'a': [True, True]} yield result result = mock.Mock() result.measurements = {'b': [True, False]} result.state.return_value = final_state yield result simulator._simulator_iterator.side_effect = steps circuit = mock.Mock(cirq.Circuit) param_resolver = mock.Mock(cirq.ParamResolver) qubit_order = mock.Mock(cirq.QubitOrder) result = simulator.simulate(program=circuit, param_resolver=param_resolver, qubit_order=qubit_order, initial_state=2) np.testing.assert_equal(result.measurements['a'], [True, True]) np.testing.assert_equal(result.measurements['b'], [True, False]) assert set(result.measurements.keys()) == {'a', 'b'} assert result.params == param_resolver np.testing.assert_equal(result.final_state, final_state) @mock.patch.multiple(cirq.SimulatesIntermediateWaveFunction, _simulator_iterator=mock.Mock()) def test_wave_simulator_no_steps(): simulator = cirq.SimulatesIntermediateWaveFunction() initial_state = np.array([1, 0, 0, 0], dtype=np.complex64) simulator._simulator_iterator.return_value = iter([]) circuit = cirq.testing.random_circuit(2, 20, 0.99) param_resolver = mock.Mock(cirq.ParamResolver) qubit_order = circuit.all_qubits() result = simulator.simulate(program=circuit, param_resolver=param_resolver, qubit_order=list(qubit_order), initial_state=initial_state) assert len(result.measurements) == 0 assert result.params == param_resolver np.testing.assert_equal(result.final_state, initial_state) @mock.patch.multiple(cirq.SimulatesIntermediateWaveFunction, _simulator_iterator=mock.Mock()) def test_wave_simulator_sweeps(): simulator = cirq.SimulatesIntermediateWaveFunction() final_state = np.array([1, 0, 0, 0]) def steps(*args, **kwargs): result = mock.Mock() result.measurements = {'a': np.array([True, True])} result.state.return_value = final_state yield result simulator._simulator_iterator.side_effect = steps circuit = mock.Mock(cirq.Circuit) param_resolvers = [mock.Mock(cirq.ParamResolver), mock.Mock(cirq.ParamResolver)] qubit_order = mock.Mock(cirq.QubitOrder) results = simulator.simulate_sweep(program=circuit, params=param_resolvers, qubit_order=qubit_order, initial_state=2) expected_results = [ cirq.SimulationTrialResult( measurements={'a': np.array([True, True])}, params=param_resolvers[0], final_state=final_state), cirq.SimulationTrialResult( measurements={'a': np.array([True, True])}, params=param_resolvers[1], final_state=final_state) ] assert results == expected_results # Python 2 gives a different repr due to unicode strings being prefixed with u. @cirq.testing.only_test_in_python3 def test_simulator_simulate_trial_result_repr(): v = cirq.SimulationTrialResult( params=cirq.ParamResolver({'a': 2}), measurements={'m': np.array([1, 2])}, final_state=np.array([0, 1, 0, 0])) assert repr(v) == ("SimulationTrialResult(" "params=cirq.ParamResolver({'a': 2}), " "measurements={'m': array([1, 2])}, " "final_state=array([0, 1, 0, 0]))") def test_simulator_trial_result_equality(): eq = cirq.testing.EqualsTester() eq.add_equality_group( cirq.SimulationTrialResult( params=cirq.ParamResolver({'a': 2}), measurements={'m': np.array([1, 0])}, final_state=np.array([0, 1, 0, 0]))) eq.add_equality_group( cirq.SimulationTrialResult( params=cirq.ParamResolver({'a': 2}), measurements={'m': np.array([1, 0])}, final_state=np.array([0, 0, 1, 0]))) eq.add_equality_group( cirq.SimulationTrialResult( params=cirq.ParamResolver({'a': 3}), measurements={'m': np.array([1, 0])}, final_state=np.array([0, 0, 1, 0]))) eq.add_equality_group( cirq.SimulationTrialResult( params=cirq.ParamResolver({'a': 3}), measurements={'m': np.array([0, 1])}, final_state=np.array([0, 0, 1, 0]))) def test_simulator_trial_pretty_state(): result = cirq.SimulationTrialResult( params=cirq.ParamResolver({'a': 2}), measurements={'m': np.array([1, 2])}, final_state=np.array([0, 1, 0, 0])) assert result.dirac_notation() == '|01⟩' def test_simulator_trial_density_matrix(): result = cirq.SimulationTrialResult( params=cirq.ParamResolver({'a': 2}), measurements={'m': np.array([1, 2])}, final_state=np.array([0, 1, 0, 0])) rho = np.array([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) np.testing.assert_array_almost_equal(rho, result.density_matrix()) def test_simulator_trial_bloch_vector(): result = cirq.SimulationTrialResult( params=cirq.ParamResolver({'a': 2}), measurements={'m': np.array([1, 2])}, final_state=np.array([0, 1, 0, 0])) bloch = np.array([0,0,-1]) np.testing.assert_array_almost_equal(bloch, result.bloch_vector(1)) class BasicStepResult(cirq.StepResult): def __init__(self, qubit_map: Dict, measurements: Dict[str, List[bool]]) -> None: super().__init__(qubit_map, measurements) def state(self) -> np.ndarray: return np.array([0, 1, 0, 0]) def test_step_result_pretty_state(): step_result = BasicStepResult({}, {}) assert step_result.dirac_notation() == '|01⟩' def test_step_result_density_matrix(): q0, q1 = cirq.LineQubit.range(2) step_result = BasicStepResult({q0: 0, q1: 1}, {}) rho = np.array([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) np.testing.assert_array_almost_equal(rho, step_result.density_matrix([q0, q1])) np.testing.assert_array_almost_equal(rho, step_result.density_matrix()) rho_ind_rev = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]]) np.testing.assert_array_almost_equal(rho_ind_rev, step_result.density_matrix([q1, q0])) single_rho = np.array([[0, 0], [0, 1]]) np.testing.assert_array_almost_equal(single_rho, step_result.density_matrix([q1])) def test_step_result_density_matrix_invalid(): q0, q1 = cirq.LineQubit.range(2) step_result = BasicStepResult({q0: 0}, {}) with pytest.raises(KeyError): step_result.density_matrix([q1]) with pytest.raises(KeyError): step_result.density_matrix('junk') with pytest.raises(TypeError): step_result.density_matrix(0) def test_step_result_bloch_vector(): q0, q1 = cirq.LineQubit.range(2) step_result = BasicStepResult({q0: 0, q1: 1}, {}) bloch1 = np.array([0,0,-1]) bloch0 = np.array([0,0,1]) np.testing.assert_array_almost_equal(bloch1, step_result.bloch_vector(q1)) np.testing.assert_array_almost_equal(bloch0, step_result.bloch_vector(q0)) def test_bloch_vector_invalid(): q0, q1 = cirq.LineQubit.range(2) step_result = BasicStepResult({q0: 0}, {}) with pytest.raises(KeyError): step_result.bloch_vector(q1) with pytest.raises(KeyError): step_result.bloch_vector('junk') with pytest.raises(KeyError): step_result.bloch_vector(0) class FakeStepResult(cirq.StepResult): def __init__(self, ones_qubits): self._ones_qubits = set(ones_qubits) def state(self): pass def __setstate__(self, state): pass def sample(self, qubits, repetitions): return [[qubit in self._ones_qubits for qubit in qubits]] * repetitions def test_step_sample_measurement_ops(): q0, q1, q2 = cirq.LineQubit.range(3) measurement_ops = [cirq.measure(q0, q1), cirq.measure(q2)] step_result = FakeStepResult([q1]) measurements = step_result.sample_measurement_ops(measurement_ops) np.testing.assert_equal(measurements, {'0,1': [[False, True]], '2': [[False]]}) def test_step_sample_measurement_ops_repetitions(): q0, q1, q2 = cirq.LineQubit.range(3) measurement_ops = [cirq.measure(q0, q1), cirq.measure(q2)] step_result = FakeStepResult([q1]) measurements = step_result.sample_measurement_ops(measurement_ops, repetitions=3) np.testing.assert_equal(measurements, {'0,1': [[False, True]] * 3, '2': [[False]] * 3}) def test_step_sample_measurement_ops_no_measurements(): step_result = FakeStepResult([]) measurements = step_result.sample_measurement_ops([]) assert measurements == {} def test_step_sample_measurement_ops_not_measurement(): q0 = cirq.LineQubit(0) step_result = FakeStepResult([q0]) with pytest.raises(ValueError, match='MeasurementGate'): step_result.sample_measurement_ops([cirq.X(q0)]) def test_step_sample_measurement_ops_repeated_qubit(): q0, q1, q2 = cirq.LineQubit.range(3) step_result = FakeStepResult([q0]) with pytest.raises(ValueError, match='MeasurementGate'): step_result.sample_measurement_ops( [cirq.measure(q0), cirq.measure(q1, q2), cirq.measure(q0)]) class MultiHTestGate(cirq.Gate): def _decompose_(self, qubits): return cirq.H.on_each(qubits) def test_simulates_composite(): c = cirq.Circuit.from_ops(MultiHTestGate().on(*cirq.LineQubit.range(2))) expected = np.array([0.5] * 4) np.testing.assert_allclose(c.apply_unitary_effect_to_state(), expected) np.testing.assert_allclose(cirq.Simulator().simulate(c).final_state, expected) def test_simulate_measurement_inversions(): q = cirq.NamedQubit('q') c = cirq.Circuit.from_ops(cirq.MeasurementGate(key='q', invert_mask=(True,)).on(q)) assert cirq.Simulator().simulate(c).measurements == {'q': np.array([True])} c = cirq.Circuit.from_ops(cirq.MeasurementGate(key='q', invert_mask=(False,)).on(q)) assert cirq.Simulator().simulate(c).measurements == {'q': np.array([False])}
[ "cirq.SimulatesSamples", "cirq.testing.EqualsTester", "cirq.X", "cirq.LineQubit", "cirq.NamedQubit", "cirq.MeasurementGate", "cirq.H.on_each", "cirq.Simulator", "cirq.ParamResolver", "pytest.raises", "numpy.array", "cirq.testing.random_circuit", "cirq.SimulatesIntermediateWaveFunction", "numpy.testing.assert_equal", "cirq.LineQubit.range", "cirq.testing.mock.mock.Mock", "cirq.TrialResult", "cirq.measure" ]
[((836, 859), 'cirq.SimulatesSamples', 'cirq.SimulatesSamples', ([], {}), '()\n', (857, 859), False, 'import cirq\n'), ((981, 1004), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.Circuit'], {}), '(cirq.Circuit)\n', (990, 1004), False, 'from cirq.testing.mock import mock\n'), ((1026, 1055), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.ParamResolver'], {}), '(cirq.ParamResolver)\n', (1035, 1055), False, 'from cirq.testing.mock import mock\n'), ((1078, 1174), 'cirq.TrialResult', 'cirq.TrialResult', ([], {'repetitions': '(10)', 'measurements': 'expected_measurements', 'params': 'param_resolver'}), '(repetitions=10, measurements=expected_measurements, params\n =param_resolver)\n', (1094, 1174), False, 'import cirq\n'), ((1750, 1773), 'cirq.SimulatesSamples', 'cirq.SimulatesSamples', ([], {}), '()\n', (1771, 1773), False, 'import cirq\n'), ((1895, 1918), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.Circuit'], {}), '(cirq.Circuit)\n', (1904, 1918), False, 'from cirq.testing.mock import mock\n'), ((3017, 3057), 'cirq.SimulatesIntermediateWaveFunction', 'cirq.SimulatesIntermediateWaveFunction', ([], {}), '()\n', (3055, 3057), False, 'import cirq\n'), ((3077, 3099), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (3085, 3099), True, 'import numpy as np\n'), ((3450, 3473), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.Circuit'], {}), '(cirq.Circuit)\n', (3459, 3473), False, 'from cirq.testing.mock import mock\n'), ((3495, 3524), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.ParamResolver'], {}), '(cirq.ParamResolver)\n', (3504, 3524), False, 'from cirq.testing.mock import mock\n'), ((3543, 3569), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.QubitOrder'], {}), '(cirq.QubitOrder)\n', (3552, 3569), False, 'from cirq.testing.mock import mock\n'), ((3792, 3855), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (["result.measurements['a']", '[True, True]'], {}), "(result.measurements['a'], [True, True])\n", (3815, 3855), True, 'import numpy as np\n'), ((3860, 3924), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (["result.measurements['b']", '[True, False]'], {}), "(result.measurements['b'], [True, False])\n", (3883, 3924), True, 'import numpy as np\n'), ((4029, 4085), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['result.final_state', 'final_state'], {}), '(result.final_state, final_state)\n', (4052, 4085), True, 'import numpy as np\n'), ((4255, 4295), 'cirq.SimulatesIntermediateWaveFunction', 'cirq.SimulatesIntermediateWaveFunction', ([], {}), '()\n', (4293, 4295), False, 'import cirq\n'), ((4317, 4359), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {'dtype': 'np.complex64'}), '([1, 0, 0, 0], dtype=np.complex64)\n', (4325, 4359), True, 'import numpy as np\n'), ((4433, 4473), 'cirq.testing.random_circuit', 'cirq.testing.random_circuit', (['(2)', '(20)', '(0.99)'], {}), '(2, 20, 0.99)\n', (4460, 4473), False, 'import cirq\n'), ((4495, 4524), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.ParamResolver'], {}), '(cirq.ParamResolver)\n', (4504, 4524), False, 'from cirq.testing.mock import mock\n'), ((4888, 4946), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['result.final_state', 'initial_state'], {}), '(result.final_state, initial_state)\n', (4911, 4946), True, 'import numpy as np\n'), ((5114, 5154), 'cirq.SimulatesIntermediateWaveFunction', 'cirq.SimulatesIntermediateWaveFunction', ([], {}), '()\n', (5152, 5154), False, 'import cirq\n'), ((5174, 5196), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (5182, 5196), True, 'import numpy as np\n'), ((5456, 5479), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.Circuit'], {}), '(cirq.Circuit)\n', (5465, 5479), False, 'from cirq.testing.mock import mock\n'), ((5606, 5632), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.QubitOrder'], {}), '(cirq.QubitOrder)\n', (5615, 5632), False, 'from cirq.testing.mock import mock\n'), ((6903, 6930), 'cirq.testing.EqualsTester', 'cirq.testing.EqualsTester', ([], {}), '()\n', (6928, 6930), False, 'import cirq\n'), ((8270, 8336), 'numpy.array', 'np.array', (['[[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]'], {}), '([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])\n', (8278, 8336), True, 'import numpy as np\n'), ((8707, 8727), 'numpy.array', 'np.array', (['[0, 0, -1]'], {}), '([0, 0, -1])\n', (8715, 8727), True, 'import numpy as np\n'), ((9256, 9279), 'cirq.LineQubit.range', 'cirq.LineQubit.range', (['(2)'], {}), '(2)\n', (9276, 9279), False, 'import cirq\n'), ((9345, 9411), 'numpy.array', 'np.array', (['[[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]'], {}), '([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])\n', (9353, 9411), True, 'import numpy as np\n'), ((9668, 9734), 'numpy.array', 'np.array', (['[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]]'], {}), '([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]])\n', (9676, 9734), True, 'import numpy as np\n'), ((9937, 9963), 'numpy.array', 'np.array', (['[[0, 0], [0, 1]]'], {}), '([[0, 0], [0, 1]])\n', (9945, 9963), True, 'import numpy as np\n'), ((10148, 10171), 'cirq.LineQubit.range', 'cirq.LineQubit.range', (['(2)'], {}), '(2)\n', (10168, 10171), False, 'import cirq\n'), ((10498, 10521), 'cirq.LineQubit.range', 'cirq.LineQubit.range', (['(2)'], {}), '(2)\n', (10518, 10521), False, 'import cirq\n'), ((10589, 10609), 'numpy.array', 'np.array', (['[0, 0, -1]'], {}), '([0, 0, -1])\n', (10597, 10609), True, 'import numpy as np\n'), ((10621, 10640), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (10629, 10640), True, 'import numpy as np\n'), ((10861, 10884), 'cirq.LineQubit.range', 'cirq.LineQubit.range', (['(2)'], {}), '(2)\n', (10881, 10884), False, 'import cirq\n'), ((11540, 11563), 'cirq.LineQubit.range', 'cirq.LineQubit.range', (['(3)'], {}), '(3)\n', (11560, 11563), False, 'import cirq\n'), ((11742, 11821), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['measurements', "{'0,1': [[False, True]], '2': [[False]]}"], {}), "(measurements, {'0,1': [[False, True]], '2': [[False]]})\n", (11765, 11821), True, 'import numpy as np\n'), ((11921, 11944), 'cirq.LineQubit.range', 'cirq.LineQubit.range', (['(3)'], {}), '(3)\n', (11941, 11944), False, 'import cirq\n'), ((12192, 12284), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['measurements', "{'0,1': [[False, True]] * 3, '2': [[False]] * 3}"], {}), "(measurements, {'0,1': [[False, True]] * 3, '2': [[\n False]] * 3})\n", (12215, 12284), True, 'import numpy as np\n'), ((12559, 12576), 'cirq.LineQubit', 'cirq.LineQubit', (['(0)'], {}), '(0)\n', (12573, 12576), False, 'import cirq\n'), ((12808, 12831), 'cirq.LineQubit.range', 'cirq.LineQubit.range', (['(3)'], {}), '(3)\n', (12828, 12831), False, 'import cirq\n'), ((13286, 13305), 'numpy.array', 'np.array', (['([0.5] * 4)'], {}), '([0.5] * 4)\n', (13294, 13305), True, 'import numpy as np\n'), ((13581, 13601), 'cirq.NamedQubit', 'cirq.NamedQubit', (['"""q"""'], {}), "('q')\n", (13596, 13601), False, 'import cirq\n'), ((894, 909), 'numpy.array', 'np.array', (['[[1]]'], {}), '([[1]])\n', (902, 909), True, 'import numpy as np\n'), ((777, 788), 'cirq.testing.mock.mock.Mock', 'mock.Mock', ([], {}), '()\n', (786, 788), False, 'from cirq.testing.mock import mock\n'), ((1808, 1823), 'numpy.array', 'np.array', (['[[1]]'], {}), '([[1]])\n', (1816, 1823), True, 'import numpy as np\n'), ((1942, 1971), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.ParamResolver'], {}), '(cirq.ParamResolver)\n', (1951, 1971), False, 'from cirq.testing.mock import mock\n'), ((1996, 2025), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.ParamResolver'], {}), '(cirq.ParamResolver)\n', (2005, 2025), False, 'from cirq.testing.mock import mock\n'), ((2051, 2151), 'cirq.TrialResult', 'cirq.TrialResult', ([], {'repetitions': '(10)', 'measurements': 'expected_measurements', 'params': 'param_resolvers[0]'}), '(repetitions=10, measurements=expected_measurements, params\n =param_resolvers[0])\n', (2067, 2151), False, 'import cirq\n'), ((2254, 2354), 'cirq.TrialResult', 'cirq.TrialResult', ([], {'repetitions': '(10)', 'measurements': 'expected_measurements', 'params': 'param_resolvers[1]'}), '(repetitions=10, measurements=expected_measurements, params\n =param_resolvers[1])\n', (2270, 2354), False, 'import cirq\n'), ((1688, 1699), 'cirq.testing.mock.mock.Mock', 'mock.Mock', ([], {}), '()\n', (1697, 1699), False, 'from cirq.testing.mock import mock\n'), ((3149, 3160), 'cirq.testing.mock.mock.Mock', 'mock.Mock', ([], {}), '()\n', (3158, 3160), False, 'from cirq.testing.mock import mock\n'), ((3249, 3260), 'cirq.testing.mock.mock.Mock', 'mock.Mock', ([], {}), '()\n', (3258, 3260), False, 'from cirq.testing.mock import mock\n'), ((2961, 2972), 'cirq.testing.mock.mock.Mock', 'mock.Mock', ([], {}), '()\n', (2970, 2972), False, 'from cirq.testing.mock import mock\n'), ((4190, 4201), 'cirq.testing.mock.mock.Mock', 'mock.Mock', ([], {}), '()\n', (4199, 4201), False, 'from cirq.testing.mock import mock\n'), ((5246, 5257), 'cirq.testing.mock.mock.Mock', 'mock.Mock', ([], {}), '()\n', (5255, 5257), False, 'from cirq.testing.mock import mock\n'), ((5503, 5532), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.ParamResolver'], {}), '(cirq.ParamResolver)\n', (5512, 5532), False, 'from cirq.testing.mock import mock\n'), ((5557, 5586), 'cirq.testing.mock.mock.Mock', 'mock.Mock', (['cirq.ParamResolver'], {}), '(cirq.ParamResolver)\n', (5566, 5586), False, 'from cirq.testing.mock import mock\n'), ((5051, 5062), 'cirq.testing.mock.mock.Mock', 'mock.Mock', ([], {}), '()\n', (5060, 5062), False, 'from cirq.testing.mock import mock\n'), ((9048, 9070), 'numpy.array', 'np.array', (['[0, 1, 0, 0]'], {}), '([0, 1, 0, 0])\n', (9056, 9070), True, 'import numpy as np\n'), ((10230, 10253), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (10243, 10253), False, 'import pytest\n'), ((10305, 10328), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (10318, 10328), False, 'import pytest\n'), ((10382, 10406), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (10395, 10406), False, 'import pytest\n'), ((10942, 10965), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (10955, 10965), False, 'import pytest\n'), ((11013, 11036), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (11026, 11036), False, 'import pytest\n'), ((11088, 11111), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (11101, 11111), False, 'import pytest\n'), ((11587, 11607), 'cirq.measure', 'cirq.measure', (['q0', 'q1'], {}), '(q0, q1)\n', (11599, 11607), False, 'import cirq\n'), ((11609, 11625), 'cirq.measure', 'cirq.measure', (['q2'], {}), '(q2)\n', (11621, 11625), False, 'import cirq\n'), ((11968, 11988), 'cirq.measure', 'cirq.measure', (['q0', 'q1'], {}), '(q0, q1)\n', (11980, 11988), False, 'import cirq\n'), ((11990, 12006), 'cirq.measure', 'cirq.measure', (['q2'], {}), '(q2)\n', (12002, 12006), False, 'import cirq\n'), ((12625, 12675), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""MeasurementGate"""'}), "(ValueError, match='MeasurementGate')\n", (12638, 12675), False, 'import pytest\n'), ((12880, 12930), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""MeasurementGate"""'}), "(ValueError, match='MeasurementGate')\n", (12893, 12930), False, 'import pytest\n'), ((13137, 13159), 'cirq.H.on_each', 'cirq.H.on_each', (['qubits'], {}), '(qubits)\n', (13151, 13159), False, 'import cirq\n'), ((5294, 5316), 'numpy.array', 'np.array', (['[True, True]'], {}), '([True, True])\n', (5302, 5316), True, 'import numpy as np\n'), ((6496, 6524), 'cirq.ParamResolver', 'cirq.ParamResolver', (["{'a': 2}"], {}), "({'a': 2})\n", (6514, 6524), False, 'import cirq\n'), ((6592, 6614), 'numpy.array', 'np.array', (['[0, 1, 0, 0]'], {}), '([0, 1, 0, 0])\n', (6600, 6614), True, 'import numpy as np\n'), ((7874, 7902), 'cirq.ParamResolver', 'cirq.ParamResolver', (["{'a': 2}"], {}), "({'a': 2})\n", (7892, 7902), False, 'import cirq\n'), ((7970, 7992), 'numpy.array', 'np.array', (['[0, 1, 0, 0]'], {}), '([0, 1, 0, 0])\n', (7978, 7992), True, 'import numpy as np\n'), ((8140, 8168), 'cirq.ParamResolver', 'cirq.ParamResolver', (["{'a': 2}"], {}), "({'a': 2})\n", (8158, 8168), False, 'import cirq\n'), ((8236, 8258), 'numpy.array', 'np.array', (['[0, 1, 0, 0]'], {}), '([0, 1, 0, 0])\n', (8244, 8258), True, 'import numpy as np\n'), ((8575, 8603), 'cirq.ParamResolver', 'cirq.ParamResolver', (["{'a': 2}"], {}), "({'a': 2})\n", (8593, 8603), False, 'import cirq\n'), ((8671, 8693), 'numpy.array', 'np.array', (['[0, 1, 0, 0]'], {}), '([0, 1, 0, 0])\n', (8679, 8693), True, 'import numpy as np\n'), ((13804, 13820), 'numpy.array', 'np.array', (['[True]'], {}), '([True])\n', (13812, 13820), True, 'import numpy as np\n'), ((14025, 14042), 'numpy.array', 'np.array', (['[False]'], {}), '([False])\n', (14033, 14042), True, 'import numpy as np\n'), ((6553, 6569), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (6561, 6569), True, 'import numpy as np\n'), ((7013, 7041), 'cirq.ParamResolver', 'cirq.ParamResolver', (["{'a': 2}"], {}), "({'a': 2})\n", (7031, 7041), False, 'import cirq\n'), ((7117, 7139), 'numpy.array', 'np.array', (['[0, 1, 0, 0]'], {}), '([0, 1, 0, 0])\n', (7125, 7139), True, 'import numpy as np\n'), ((7224, 7252), 'cirq.ParamResolver', 'cirq.ParamResolver', (["{'a': 2}"], {}), "({'a': 2})\n", (7242, 7252), False, 'import cirq\n'), ((7328, 7350), 'numpy.array', 'np.array', (['[0, 0, 1, 0]'], {}), '([0, 0, 1, 0])\n', (7336, 7350), True, 'import numpy as np\n'), ((7435, 7463), 'cirq.ParamResolver', 'cirq.ParamResolver', (["{'a': 3}"], {}), "({'a': 3})\n", (7453, 7463), False, 'import cirq\n'), ((7539, 7561), 'numpy.array', 'np.array', (['[0, 0, 1, 0]'], {}), '([0, 0, 1, 0])\n', (7547, 7561), True, 'import numpy as np\n'), ((7646, 7674), 'cirq.ParamResolver', 'cirq.ParamResolver', (["{'a': 3}"], {}), "({'a': 3})\n", (7664, 7674), False, 'import cirq\n'), ((7750, 7772), 'numpy.array', 'np.array', (['[0, 0, 1, 0]'], {}), '([0, 0, 1, 0])\n', (7758, 7772), True, 'import numpy as np\n'), ((7931, 7947), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (7939, 7947), True, 'import numpy as np\n'), ((8197, 8213), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (8205, 8213), True, 'import numpy as np\n'), ((8632, 8648), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (8640, 8648), True, 'import numpy as np\n'), ((12721, 12731), 'cirq.X', 'cirq.X', (['q0'], {}), '(q0)\n', (12727, 12731), False, 'import cirq\n'), ((12993, 13009), 'cirq.measure', 'cirq.measure', (['q0'], {}), '(q0)\n', (13005, 13009), False, 'import cirq\n'), ((13011, 13031), 'cirq.measure', 'cirq.measure', (['q1', 'q2'], {}), '(q1, q2)\n', (13023, 13031), False, 'import cirq\n'), ((13033, 13049), 'cirq.measure', 'cirq.measure', (['q0'], {}), '(q0)\n', (13045, 13049), False, 'import cirq\n'), ((13245, 13268), 'cirq.LineQubit.range', 'cirq.LineQubit.range', (['(2)'], {}), '(2)\n', (13265, 13268), False, 'import cirq\n'), ((13633, 13683), 'cirq.MeasurementGate', 'cirq.MeasurementGate', ([], {'key': '"""q"""', 'invert_mask': '(True,)'}), "(key='q', invert_mask=(True,))\n", (13653, 13683), False, 'import cirq\n'), ((13853, 13904), 'cirq.MeasurementGate', 'cirq.MeasurementGate', ([], {'key': '"""q"""', 'invert_mask': '(False,)'}), "(key='q', invert_mask=(False,))\n", (13873, 13904), False, 'import cirq\n'), ((5964, 5986), 'numpy.array', 'np.array', (['[True, True]'], {}), '([True, True])\n', (5972, 5986), True, 'import numpy as np\n'), ((6133, 6155), 'numpy.array', 'np.array', (['[True, True]'], {}), '([True, True])\n', (6141, 6155), True, 'import numpy as np\n'), ((7074, 7090), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (7082, 7090), True, 'import numpy as np\n'), ((7285, 7301), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (7293, 7301), True, 'import numpy as np\n'), ((7496, 7512), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (7504, 7512), True, 'import numpy as np\n'), ((7707, 7723), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (7715, 7723), True, 'import numpy as np\n'), ((13444, 13460), 'cirq.Simulator', 'cirq.Simulator', ([], {}), '()\n', (13458, 13460), False, 'import cirq\n'), ((13753, 13769), 'cirq.Simulator', 'cirq.Simulator', ([], {}), '()\n', (13767, 13769), False, 'import cirq\n'), ((13974, 13990), 'cirq.Simulator', 'cirq.Simulator', ([], {}), '()\n', (13988, 13990), False, 'import cirq\n')]
# Copyright (c) Facebook, Inc. and its affiliates. import copy import itertools import logging import numpy as np import pickle import random import torch import torch.utils.data as data from torch.utils.data.sampler import Sampler from detectron2.utils.serialize import PicklableWrapper __all__ = ["MapDataset", "DatasetFromList", "AspectRatioGroupedDataset", "ToIterableDataset"] class MapDataset(data.Dataset): """ Map a function over the elements in a dataset. Args: dataset: a dataset where map function is applied. map_func: a callable which maps the element in dataset. map_func is responsible for error handling, when error happens, it needs to return None so the MapDataset will randomly use other elements from the dataset. """ def __init__(self, dataset, map_func, task_dropout=False, train_controller=False, subperclass_indices=None): # 这个task_dropout需要在ratio>0时才为true self._dataset = dataset self.train_controller = train_controller self.superclass_indices = subperclass_indices self._dataset.train_controller = train_controller self._map_func = PicklableWrapper(map_func) # wrap so that a lambda will work self._rng = random.Random(42) if self.train_controller: self._fallback_candidates = [set(range(len(dset))) for dset in dataset._lst] else: self._fallback_candidates = set(range(len(dataset))) self.task_dropout = task_dropout self._dataset.task_dropout = task_dropout self.superclass_id = 0 def set_superclass_id(self, superclass_index: int): self.superclass_id = superclass_index self._dataset.set_superclass_id(superclass_index) def __len__(self): if not self.train_controller: return len(self._dataset) else: return len(self.superclass_indices[self.superclass_id]) def __getitem__(self, idx): retry_count = 0 cur_idx = int(idx) while True: if self.task_dropout: if self.train_controller: dataset_dict, super_targets_idxs, super_targets = self._dataset[self.superclass_indices[self.superclass_id][cur_idx]] else: dataset_dict, super_targets_masks, super_targets_inverse_masks, super_targets_idxs, super_targets = self._dataset[cur_idx] else: dataset_dict = self._dataset[cur_idx] data, m = self._map_func(dataset_dict) # 返回的m是non empty后的图片object nonempty_obj = [] for i, j in enumerate(m): if j: nonempty_obj.append(i) if data is not None: if self.train_controller: self._fallback_candidates[self.superclass_id].add(cur_idx) else: self._fallback_candidates.add(cur_idx) if self.task_dropout: if self.train_controller: return (data, super_targets_idxs[nonempty_obj], super_targets[nonempty_obj]) else: return (data, super_targets_masks[nonempty_obj], super_targets_inverse_masks[nonempty_obj], super_targets_idxs[nonempty_obj], super_targets[nonempty_obj]) return data # _map_func fails for this idx, use a random new index from the pool retry_count += 1 if self.train_controller: self._fallback_candidates[self.superclass_id].discard(cur_idx) cur_idx = self._rng.sample(self._fallback_candidates[self.superclass_id], k=1)[0] else: self._fallback_candidates.discard(cur_idx) cur_idx = self._rng.sample(self._fallback_candidates, k=1)[0] if retry_count >= 3: logger = logging.getLogger(__name__) logger.warning( "Failed to apply `_map_func` for idx: {}, retry count: {}".format( idx, retry_count ) ) class DatasetFromList(data.Dataset): """ Wrap a list to a torch Dataset. It produces elements of the list as data. """ def __init__(self, lst, class_ranges=None, meta=None, in_hier=None, task_dropout: bool = False, \ copy: bool = True, serialize: bool = True, train_controller: bool = False, whole_dataset=None): """ Args: lst (list): a list which contains elements to produce. copy (bool): whether to deepcopy the element when producing it, so that the result can be modified in place without affecting the source in the list. serialize (bool): whether to hold memory using serialized objects, when enabled, data loader workers can use shared RAM from master process instead of making a copy. """ logger = logging.getLogger(__name__) # 当train controller的时候,_lst就是一个list,object类型的np.array,要先根据superclass id拿出指定超类的数据,再去做下面一些必要的代码 self._lst = lst self.whole_dataset = whole_dataset # list,包含整个数据集,里面必须是每个superclass放在一起才行 self.class_ranges = class_ranges self.meta = meta self.in_hier = in_hier self.task_dropout = task_dropout # 这个task_dropout需要在ratio>0时才为true self._copy = copy self._serialize = serialize self.train_controller = train_controller # 当train controller时,dataset设为eval模态 if self.train_controller: assert self.task_dropout self._serialize = False # train controller的时候必须为false,不搞这个了 logger.info("Now data is related to controller, no need to serialize data") self.superclass_id = 0 if self.task_dropout: # 下面的数据都是针对每一个物体的,按照图片的顺序,然后每张图片按照其中物体的顺序,与分类任务还是不一样的 # create a dict contain the start and end anno of each image's objects if not self.train_controller: self.targets = [] self.images_part = [] # 保存每张图片对应的obj是list中的哪一段,原本是定义为dict,但是因为torch的dataset处理getitem的时候是在触发到indexerror时自动停止,结果我这里先遇到了一个keyerror,所以它就报错,改为list,就会在idx超出范围时报错indexerror,就会停止读取数据集了 end = 0 # 每张图片中包含的obj在list中的end index,最后的数值大小是所有物体的数量 for i, s in enumerate(self._lst): start = end # after a image is done, the end of the last one becomes the start of next one for j, obj in enumerate(s['annotations']): id_for_only_class_in_superclass_exists = obj["category_id"] self.targets.append(id_for_only_class_in_superclass_exists) end += 1 self.images_part.append([start, end]) assert end-start==len(s['annotations']), "img objs indexs wrong." self.targets = np.array(self.targets) self.images_part = np.array(self.images_part) else: # train controller的时候,需要把target和image part都搞成每个superclass单独存的 self.whole_targets = [] self.whole_images_part = [] # 保存每张图片对应的obj是list中的哪一段,原本是定义为dict,但是因为torch的dataset处理getitem的时候是在触发到indexerror时自动停止,结果我这里先遇到了一个keyerror,所以它就报错,改为list,就会在idx超出范围时报错indexerror,就会停止读取数据集了 end = 0 # 每张图片中包含的obj在list中的end index,最后的数值大小是所有物体的数量 for i, s in enumerate(self.whole_dataset): start = end # after a image is done, the end of the last one becomes the start of next one for j, obj in enumerate(s['annotations']): id_for_only_class_in_superclass_exists = obj["category_id"] self.whole_targets.append(id_for_only_class_in_superclass_exists) end += 1 self.whole_images_part.append([start, end]) self.whole_targets = np.array(self.whole_targets) self.whole_images_part = np.array(self.whole_images_part) self.targets_per_superclass = [] # 它的长度和当前superclass里的object数量一样 self.images_part_per_superclass = [] # 它的长度和当前superclass里的图片数量一样 for i, superclass_lst in enumerate(self._lst): targets = [] images_part = [] # 保存每张图片对应的obj是list中的哪一段,原本是定义为dict,但是因为torch的dataset处理getitem的时候是在触发到indexerror时自动停止,结果我这里先遇到了一个keyerror,所以它就报错,改为list,就会在idx超出范围时报错indexerror,就会停止读取数据集了 end = 0 # 每张图片中包含的obj在list中的end index,最后的数值大小是所有物体的数量 for i, s in enumerate(superclass_lst): start = end # after a image is done, the end of the last one becomes the start of next one for j, obj in enumerate(s['annotations']): id_in_80 = obj["category_id"] targets.append(id_in_80) end += 1 images_part.append([start, end]) self.targets_per_superclass.append(targets) self.images_part_per_superclass.append(images_part) self.targets_per_superclass = np.array(self.targets_per_superclass, dtype=object) self.images_part_per_superclass = np.array(self.images_part_per_superclass, dtype=object) # 这里获取的targets已经是0-80的label了,不需要映射了 # self.category_ids = self.targets self.class_to_superclass = np.ones(len(self.in_hier.in_wnids_child)) * -1 # 应该是一个长度为80的array for ran in class_ranges: # ranges里保存的是连续的id,是属于0-80范围的 for classnum in ran: classname = self.in_hier.num_to_name_child[classnum] classwnid = self.in_hier.name_to_wnid_child[classname] parentwnid = self.in_hier.tree_child[classwnid].parent_wnid parentnum = self.in_hier.wnid_to_num_parent[parentwnid] self.class_to_superclass[classnum] = parentnum # 验证一下一致性,之前有定义一个连续id到超类id的字典 for num, super_idx in self.meta.class_to_superclass_idx.items(): assert self.class_to_superclass[num] == super_idx, 'inconsistency between num and superclass idx projection' # self.super_targets里不应该有-1 if not self.train_controller: self.super_targets = self.class_to_superclass[self.targets] else: self.whole_super_targets = self.class_to_superclass[self.whole_targets] self.super_targets_per_superclass = [] # inference需要这个量 for i in self.targets_per_superclass: self.super_targets_per_superclass.append(self.class_to_superclass[i]) self.super_targets_per_superclass = np.array(self.super_targets_per_superclass, dtype=object) self.n_superclass = len(class_ranges) if self.train_controller: # 训controller的时候需要对dataset特殊处理, TODO: train controller的时候val数据指定了数量,每个superclass要load一样的数据量 self.superclass_masks = [] self.superclass_data = [] self.superclass_samples_indices = [] self.superclass_targets = self.targets_per_superclass self.superclass_images_part = self.images_part_per_superclass self.super_targets_idxes_per_superclass = [] for i in range(self.n_superclass): super_targets_idxes = [] for idx in range(self.images_part_per_superclass[i][-1][1]): # 获取每个superclass的end super_targets_idxes.append((self.super_targets_per_superclass[i][idx] == self.class_to_superclass).nonzero()[0]) super_targets_idxes = np.stack(super_targets_idxes, axis=0).astype("int64") # 不知道是不是所有类的图片数量都一样,这里可能有问题 self.super_targets_idxes_per_superclass.append(super_targets_idxes) # inference 需要它 obj_idx = (self.whole_super_targets == i).nonzero()[0] # 保存属于当前superclass的所有obj的target index # 如何从obj_idx得到图片的idx,for循环肯定特别慢啊 img_idx = [] for obj_position in obj_idx: # 每一个object在整个数据集的位置 for img_position, (obj_s, obj_e) in enumerate(self.whole_images_part): if obj_s <= obj_position < obj_e and img_position not in img_idx: img_idx.append(img_position) break self.superclass_data.append(np.array(self.whole_dataset)[img_idx].tolist()) self.superclass_samples_indices.append(np.array(img_idx).tolist()) superclass_mask = (self.class_to_superclass == i).astype("int32") self.superclass_masks.append(superclass_mask) self.superclass_masks = np.vstack(self.superclass_masks) self.superclass_masks = np.array(self.superclass_masks) self.superclass_samples_indices = np.array(self.superclass_samples_indices, dtype=object) self.super_targets_idxes_per_superclass = np.array(self.super_targets_idxes_per_superclass, dtype=object) else: self.super_targets_masks = (self.super_targets.reshape(-1, 1) == self.class_to_superclass).astype("single") self.super_targets_inverse_masks = (self.super_targets.reshape(-1, 1) != self.class_to_superclass).astype( "single") self.super_targets_idxes = [] assert end==len(self.super_targets_masks), "end={} wrong, total {} objects".format(end, len(self.super_targets_masks)) for idx in range(end): self.super_targets_idxes.append((self.super_targets[idx] == self.class_to_superclass).nonzero()[0]) self.super_targets_idxes = np.stack(self.super_targets_idxes, axis=0).astype( "int64") # 不知道是不是所有类的图片数量都一样,这里可能有问题 self.superclass_masks = [] self.superclass_samples_indices = [] for i in range(self.n_superclass): idx = (self.super_targets == i).nonzero()[0] self.superclass_samples_indices.append(idx.tolist()) superclass_mask = (self.class_to_superclass == i).astype("single") self.superclass_masks.append(superclass_mask) self.super_targets_idxes = np.array(self.super_targets_idxes) self.superclass_masks = np.array(self.superclass_masks) self.superclass_samples_indices = np.array(self.superclass_samples_indices, dtype=object) def _serialize(data): buffer = pickle.dumps(data, protocol=-1) return np.frombuffer(buffer, dtype=np.uint8) """ 这样处理之后,如果addr一次性指定获取多段,它只能得到第一个元素,比如_lst[:x]是第一张,_lst[x:y]是第二张,这都没问题 但如果指定_lst[:y]还是只能得到第一张,而mask那些就是需要一次性得到多段,所以要用循环来搞 """ if self._serialize and not self.train_controller: logger.info( "Serializing {} _lst elements to byte tensors and concatenating them all ...".format( len(self._lst) ) ) self._lst = [_serialize(x) for x in self._lst] # 把每张图片给平铺成vector了 self._addr = np.asarray([len(x) for x in self._lst], dtype=np.int64) self._addr = np.cumsum(self._addr) self._lst = np.concatenate(self._lst) # 把所有的图片拼成整一条vector了,_addr里记录每张的起始/终止位置 logger.info("Serialized dataset takes {:.2f} MiB".format(len(self._lst) / 1024 ** 2)) if self.task_dropout: logger.info("Serializing {} super_targets_masks elements to byte tensors and concatenating them all ...".format(len(self.super_targets_masks))) self.super_targets_masks = [_serialize(x) for x in self.super_targets_masks] self.super_targets_masks_addr = np.asarray([len(x) for x in self.super_targets_masks], dtype=np.int64) self.super_targets_masks_addr = np.cumsum(self.super_targets_masks_addr) self.super_targets_masks = np.concatenate(self.super_targets_masks) logger.info("Serialized super_targets_masks takes {:.2f} MiB".format(len(self.super_targets_masks) / 1024 ** 2)) logger.info("Serializing {} super_targets_inverse_masks elements to byte tensors and concatenating them all ...".format(len(self.super_targets_inverse_masks))) self.super_targets_inverse_masks = [_serialize(x) for x in self.super_targets_inverse_masks] self.super_targets_inverse_masks_addr = np.asarray([len(x) for x in self.super_targets_inverse_masks], dtype=np.int64) self.super_targets_inverse_masks_addr = np.cumsum(self.super_targets_inverse_masks_addr) self.super_targets_inverse_masks = np.concatenate(self.super_targets_inverse_masks) logger.info("Serialized super_targets_inverse_masks takes {:.2f} MiB".format(len(self.super_targets_inverse_masks) / 1024 ** 2)) logger.info("Serializing {} super_targets_idxes elements to byte tensors and concatenating them all ...".format(len(self.super_targets_idxes))) self.super_targets_idxes = [_serialize(x) for x in self.super_targets_idxes] self.super_targets_idxes_addr = np.asarray([len(x) for x in self.super_targets_idxes], dtype=np.int64) self.super_targets_idxes_addr = np.cumsum(self.super_targets_idxes_addr) self.super_targets_idxes = np.concatenate(self.super_targets_idxes) logger.info("Serialized super_targets_idxes takes {:.2f} MiB".format(len(self.super_targets_idxes) / 1024 ** 2)) logger.info("Serializing {} super_targets elements to byte tensors and concatenating them all ...".format(len(self.super_targets))) self.super_targets = [_serialize(x) for x in self.super_targets] self.super_targets_addr = np.asarray([len(x) for x in self.super_targets], dtype=np.int64) self.super_targets_addr = np.cumsum(self.super_targets_addr) self.super_targets = np.concatenate(self.super_targets) logger.info("Serialized super_targets takes {:.2f} MiB".format(len(self.super_targets) / 1024 ** 2)) def __len__(self): if self.train_controller: return len(self.superclass_data[self.superclass_id]) else: if self._serialize: return len(self._addr) else: return len(self._lst) def set_superclass_id(self, superclass_index: int): self.superclass_id = superclass_index def __getitem__(self, idx): if self.task_dropout: if self.train_controller: start, end = self.superclass_images_part[self.superclass_id][idx] # 获取的是对应总数据集里的image part,所以下面还是从self.super_targets里拿 else: start, end = self.images_part[idx] if self._serialize and not self.train_controller: start_addr = 0 if idx == 0 else self._addr[idx - 1].item() end_addr = self._addr[idx].item() bytes = memoryview(self._lst[start_addr:end_addr]) return_lst = pickle.loads(bytes) assert len(return_lst['annotations'])==end-start, "obj indexs num {} != obj num {} in image".format(end-start, len(return_lst['annotations'])) if self.task_dropout: # _serialize的话,需要先根据image_part对应的start和end,找到对应的下面这些值的addr的开始与结束 """ 下面这些,需要一次得到多个,所以必须用for训练来一个个object的得到 """ super_targets_masks_bytes_for_return = [] super_targets_inverse_masks_bytes_for_return = [] super_targets_idxes_bytes_for_return = [] super_targets_bytes_for_return = [] for obj_idx in range(start, end): # 如果start为0,那么obj_idx就是从-1开始,所以下面的判断需要改为== -1 super_targets_masks_start_addr = 0 if obj_idx == 0 else self.super_targets_masks_addr[obj_idx - 1].item() super_targets_masks_end_addr = self.super_targets_masks_addr[obj_idx].item() super_targets_masks_bytes = memoryview(self.super_targets_masks[super_targets_masks_start_addr:super_targets_masks_end_addr]) super_targets_masks_bytes_for_return.append(pickle.loads(super_targets_masks_bytes)) super_targets_inverse_masks_start_addr = 0 if obj_idx == 0 else self.super_targets_inverse_masks_addr[obj_idx - 1].item() super_targets_inverse_masks_end_addr = self.super_targets_inverse_masks_addr[obj_idx].item() super_targets_inverse_masks_bytes = memoryview(self.super_targets_inverse_masks[super_targets_inverse_masks_start_addr:super_targets_inverse_masks_end_addr]) super_targets_inverse_masks_bytes_for_return.append(pickle.loads(super_targets_inverse_masks_bytes)) super_targets_idxes_start_addr = 0 if obj_idx == 0 else self.super_targets_idxes_addr[obj_idx - 1].item() super_targets_idxes_end_addr = self.super_targets_idxes_addr[obj_idx].item() super_targets_idxes_bytes = memoryview(self.super_targets_idxes[super_targets_idxes_start_addr:super_targets_idxes_end_addr]) super_targets_idxes_bytes_for_return.append(pickle.loads(super_targets_idxes_bytes)) super_targets_start_addr = 0 if obj_idx == 0 else self.super_targets_addr[obj_idx - 1].item() super_targets_end_addr = self.super_targets_addr[obj_idx].item() super_targets_bytes = memoryview(self.super_targets[super_targets_start_addr:super_targets_end_addr]) super_targets_bytes_for_return.append(pickle.loads(super_targets_bytes)) # 仔细想想其实这些量的_serialize有没有必要,这样搞还要加个for训练来获取值,很多次的pickle.loads,会不会更慢了 assert len(super_targets_masks_bytes_for_return)==len(return_lst['annotations']), "return value length num {} != obj num {} in image".format(len(super_targets_masks_bytes_for_return), len(return_lst['annotations'])) return_super_targets_masks = np.stack(super_targets_masks_bytes_for_return, axis=0) return_super_targets_inverse_masks = np.stack(super_targets_inverse_masks_bytes_for_return, axis=0) return_super_targets_idxes = np.stack(super_targets_idxes_bytes_for_return, axis=0) return_super_targets = np.array(super_targets_bytes_for_return) return return_lst, return_super_targets_masks, return_super_targets_inverse_masks, return_super_targets_idxes, return_super_targets return pickle.loads(bytes) elif self._copy: if self.train_controller: return copy.deepcopy(self.superclass_data[self.superclass_id][idx]), copy.deepcopy(self.super_targets_idxes_per_superclass[self.superclass_id][start:end]), copy.deepcopy(self.super_targets_per_superclass[self.superclass_id][start:end]) if self.task_dropout: return copy.deepcopy(self._lst[idx]), copy.deepcopy(self.super_targets_masks[start:end]), copy.deepcopy(self.super_targets_inverse_masks[start:end]),\ copy.deepcopy(self.super_targets_idxes[start:end]), copy.deepcopy(self.super_targets[start:end]) return copy.deepcopy(self._lst[idx]) else: if self.train_controller: return self.superclass_data[self.superclass_id][idx], self.super_targets_idxes_per_superclass[self.superclass_id][start:end], self.super_targets_per_superclass[self.superclass_id][start:end] if self.task_dropout: return self._lst[idx], self.super_targets_masks[start:end], self.super_targets_inverse_masks[start:end],\ self.super_targets_idxes[start:end], self.super_targets[start:end] return self._lst[idx] class ToIterableDataset(data.IterableDataset): """ Convert an old indices-based (also called map-style) dataset to an iterable-style dataset. """ def __init__(self, dataset, sampler): """ Args: dataset (torch.utils.data.Dataset): an old-style dataset with ``__getitem__`` sampler (torch.utils.data.sampler.Sampler): a cheap iterable that produces indices to be applied on ``dataset``. """ assert not isinstance(dataset, data.IterableDataset), dataset assert isinstance(sampler, Sampler), sampler self.dataset = dataset self.sampler = sampler def __iter__(self): worker_info = data.get_worker_info() if worker_info is None or worker_info.num_workers == 1: for idx in self.sampler: yield self.dataset[idx] else: # With map-style dataset, `DataLoader(dataset, sampler)` runs the # sampler in main process only. But `DataLoader(ToIterableDataset(dataset, sampler))` # will run sampler in every of the N worker and only keep 1/N of the ids on each # worker. The assumption is that sampler is cheap to iterate and it's fine to discard # ids in workers. for idx in itertools.islice( self.sampler, worker_info.id, None, worker_info.num_workers ): yield self.dataset[idx] class AspectRatioGroupedDataset(data.IterableDataset): """ Batch data that have similar aspect ratio together. In this implementation, images whose aspect ratio < (or >) 1 will be batched together. This improves training speed because the images then need less padding to form a batch. It assumes the underlying dataset produces dicts with "width" and "height" keys. It will then produce a list of original dicts with length = batch_size, all with similar aspect ratios. """ def __init__(self, dataset, batch_size, task_dropout=False): # 这个task_dropout需要在ratio>0时才为true """ Args: dataset: an iterable. Each element must be a dict with keys "width" and "height", which will be used to batch data. batch_size (int): """ self.dataset = dataset self.batch_size = batch_size self.task_dropout = task_dropout self._buckets = [[] for _ in range(2)] # Hard-coded two aspect ratio groups: w > h and w < h. # Can add support for more aspect ratio groups, but doesn't seem useful def __iter__(self): for d in self.dataset: if self.task_dropout: w, h = d[0]["width"], d[0]["height"] else: w, h = d["width"], d["height"] bucket_id = 0 if w > h else 1 bucket = self._buckets[bucket_id] bucket.append(d) if len(bucket) == self.batch_size: yield bucket[:] del bucket[:] def __len__(self): return len(self.dataset)
[ "pickle.loads", "numpy.stack", "torch.utils.data.get_worker_info", "copy.deepcopy", "numpy.concatenate", "random.Random", "numpy.frombuffer", "numpy.cumsum", "numpy.array", "itertools.islice", "numpy.vstack", "detectron2.utils.serialize.PicklableWrapper", "logging.getLogger", "pickle.dumps" ]
[((1177, 1203), 'detectron2.utils.serialize.PicklableWrapper', 'PicklableWrapper', (['map_func'], {}), '(map_func)\n', (1193, 1203), False, 'from detectron2.utils.serialize import PicklableWrapper\n'), ((1260, 1277), 'random.Random', 'random.Random', (['(42)'], {}), '(42)\n', (1273, 1277), False, 'import random\n'), ((4999, 5026), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (5016, 5026), False, 'import logging\n'), ((24849, 24871), 'torch.utils.data.get_worker_info', 'data.get_worker_info', ([], {}), '()\n', (24869, 24871), True, 'import torch.utils.data as data\n'), ((14826, 14857), 'pickle.dumps', 'pickle.dumps', (['data'], {'protocol': '(-1)'}), '(data, protocol=-1)\n', (14838, 14857), False, 'import pickle\n'), ((14877, 14914), 'numpy.frombuffer', 'np.frombuffer', (['buffer'], {'dtype': 'np.uint8'}), '(buffer, dtype=np.uint8)\n', (14890, 14914), True, 'import numpy as np\n'), ((15511, 15532), 'numpy.cumsum', 'np.cumsum', (['self._addr'], {}), '(self._addr)\n', (15520, 15532), True, 'import numpy as np\n'), ((15557, 15582), 'numpy.concatenate', 'np.concatenate', (['self._lst'], {}), '(self._lst)\n', (15571, 15582), True, 'import numpy as np\n'), ((19414, 19433), 'pickle.loads', 'pickle.loads', (['bytes'], {}), '(bytes)\n', (19426, 19433), False, 'import pickle\n'), ((22911, 22930), 'pickle.loads', 'pickle.loads', (['bytes'], {}), '(bytes)\n', (22923, 22930), False, 'import pickle\n'), ((25447, 25524), 'itertools.islice', 'itertools.islice', (['self.sampler', 'worker_info.id', 'None', 'worker_info.num_workers'], {}), '(self.sampler, worker_info.id, None, worker_info.num_workers)\n', (25463, 25524), False, 'import itertools\n'), ((3905, 3932), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (3922, 3932), False, 'import logging\n'), ((6944, 6966), 'numpy.array', 'np.array', (['self.targets'], {}), '(self.targets)\n', (6952, 6966), True, 'import numpy as np\n'), ((7002, 7028), 'numpy.array', 'np.array', (['self.images_part'], {}), '(self.images_part)\n', (7010, 7028), True, 'import numpy as np\n'), ((7962, 7990), 'numpy.array', 'np.array', (['self.whole_targets'], {}), '(self.whole_targets)\n', (7970, 7990), True, 'import numpy as np\n'), ((8032, 8064), 'numpy.array', 'np.array', (['self.whole_images_part'], {}), '(self.whole_images_part)\n', (8040, 8064), True, 'import numpy as np\n'), ((9221, 9272), 'numpy.array', 'np.array', (['self.targets_per_superclass'], {'dtype': 'object'}), '(self.targets_per_superclass, dtype=object)\n', (9229, 9272), True, 'import numpy as np\n'), ((9323, 9378), 'numpy.array', 'np.array', (['self.images_part_per_superclass'], {'dtype': 'object'}), '(self.images_part_per_superclass, dtype=object)\n', (9331, 9378), True, 'import numpy as np\n'), ((10836, 10893), 'numpy.array', 'np.array', (['self.super_targets_per_superclass'], {'dtype': 'object'}), '(self.super_targets_per_superclass, dtype=object)\n', (10844, 10893), True, 'import numpy as np\n'), ((12956, 12988), 'numpy.vstack', 'np.vstack', (['self.superclass_masks'], {}), '(self.superclass_masks)\n', (12965, 12988), True, 'import numpy as np\n'), ((13030, 13061), 'numpy.array', 'np.array', (['self.superclass_masks'], {}), '(self.superclass_masks)\n', (13038, 13061), True, 'import numpy as np\n'), ((13112, 13167), 'numpy.array', 'np.array', (['self.superclass_samples_indices'], {'dtype': 'object'}), '(self.superclass_samples_indices, dtype=object)\n', (13120, 13167), True, 'import numpy as np\n'), ((13226, 13289), 'numpy.array', 'np.array', (['self.super_targets_idxes_per_superclass'], {'dtype': 'object'}), '(self.super_targets_idxes_per_superclass, dtype=object)\n', (13234, 13289), True, 'import numpy as np\n'), ((14561, 14595), 'numpy.array', 'np.array', (['self.super_targets_idxes'], {}), '(self.super_targets_idxes)\n', (14569, 14595), True, 'import numpy as np\n'), ((14636, 14667), 'numpy.array', 'np.array', (['self.superclass_masks'], {}), '(self.superclass_masks)\n', (14644, 14667), True, 'import numpy as np\n'), ((14718, 14773), 'numpy.array', 'np.array', (['self.superclass_samples_indices'], {'dtype': 'object'}), '(self.superclass_samples_indices, dtype=object)\n', (14726, 14773), True, 'import numpy as np\n'), ((16176, 16216), 'numpy.cumsum', 'np.cumsum', (['self.super_targets_masks_addr'], {}), '(self.super_targets_masks_addr)\n', (16185, 16216), True, 'import numpy as np\n'), ((16260, 16300), 'numpy.concatenate', 'np.concatenate', (['self.super_targets_masks'], {}), '(self.super_targets_masks)\n', (16274, 16300), True, 'import numpy as np\n'), ((16907, 16955), 'numpy.cumsum', 'np.cumsum', (['self.super_targets_inverse_masks_addr'], {}), '(self.super_targets_inverse_masks_addr)\n', (16916, 16955), True, 'import numpy as np\n'), ((17007, 17055), 'numpy.concatenate', 'np.concatenate', (['self.super_targets_inverse_masks'], {}), '(self.super_targets_inverse_masks)\n', (17021, 17055), True, 'import numpy as np\n'), ((17622, 17662), 'numpy.cumsum', 'np.cumsum', (['self.super_targets_idxes_addr'], {}), '(self.super_targets_idxes_addr)\n', (17631, 17662), True, 'import numpy as np\n'), ((17706, 17746), 'numpy.concatenate', 'np.concatenate', (['self.super_targets_idxes'], {}), '(self.super_targets_idxes)\n', (17720, 17746), True, 'import numpy as np\n'), ((18255, 18289), 'numpy.cumsum', 'np.cumsum', (['self.super_targets_addr'], {}), '(self.super_targets_addr)\n', (18264, 18289), True, 'import numpy as np\n'), ((18327, 18361), 'numpy.concatenate', 'np.concatenate', (['self.super_targets'], {}), '(self.super_targets)\n', (18341, 18361), True, 'import numpy as np\n'), ((22393, 22447), 'numpy.stack', 'np.stack', (['super_targets_masks_bytes_for_return'], {'axis': '(0)'}), '(super_targets_masks_bytes_for_return, axis=0)\n', (22401, 22447), True, 'import numpy as np\n'), ((22501, 22563), 'numpy.stack', 'np.stack', (['super_targets_inverse_masks_bytes_for_return'], {'axis': '(0)'}), '(super_targets_inverse_masks_bytes_for_return, axis=0)\n', (22509, 22563), True, 'import numpy as np\n'), ((22609, 22663), 'numpy.stack', 'np.stack', (['super_targets_idxes_bytes_for_return'], {'axis': '(0)'}), '(super_targets_idxes_bytes_for_return, axis=0)\n', (22617, 22663), True, 'import numpy as np\n'), ((22703, 22743), 'numpy.array', 'np.array', (['super_targets_bytes_for_return'], {}), '(super_targets_bytes_for_return)\n', (22711, 22743), True, 'import numpy as np\n'), ((23579, 23608), 'copy.deepcopy', 'copy.deepcopy', (['self._lst[idx]'], {}), '(self._lst[idx])\n', (23592, 23608), False, 'import copy\n'), ((13969, 14011), 'numpy.stack', 'np.stack', (['self.super_targets_idxes'], {'axis': '(0)'}), '(self.super_targets_idxes, axis=0)\n', (13977, 14011), True, 'import numpy as np\n'), ((20545, 20584), 'pickle.loads', 'pickle.loads', (['super_targets_masks_bytes'], {}), '(super_targets_masks_bytes)\n', (20557, 20584), False, 'import pickle\n'), ((21092, 21139), 'pickle.loads', 'pickle.loads', (['super_targets_inverse_masks_bytes'], {}), '(super_targets_inverse_masks_bytes)\n', (21104, 21139), False, 'import pickle\n'), ((21575, 21614), 'pickle.loads', 'pickle.loads', (['super_targets_idxes_bytes'], {}), '(super_targets_idxes_bytes)\n', (21587, 21614), False, 'import pickle\n'), ((21996, 22029), 'pickle.loads', 'pickle.loads', (['super_targets_bytes'], {}), '(super_targets_bytes)\n', (22008, 22029), False, 'import pickle\n'), ((23017, 23077), 'copy.deepcopy', 'copy.deepcopy', (['self.superclass_data[self.superclass_id][idx]'], {}), '(self.superclass_data[self.superclass_id][idx])\n', (23030, 23077), False, 'import copy\n'), ((23079, 23169), 'copy.deepcopy', 'copy.deepcopy', (['self.super_targets_idxes_per_superclass[self.superclass_id][start:end]'], {}), '(self.super_targets_idxes_per_superclass[self.superclass_id][\n start:end])\n', (23092, 23169), False, 'import copy\n'), ((23166, 23245), 'copy.deepcopy', 'copy.deepcopy', (['self.super_targets_per_superclass[self.superclass_id][start:end]'], {}), '(self.super_targets_per_superclass[self.superclass_id][start:end])\n', (23179, 23245), False, 'import copy\n'), ((23303, 23332), 'copy.deepcopy', 'copy.deepcopy', (['self._lst[idx]'], {}), '(self._lst[idx])\n', (23316, 23332), False, 'import copy\n'), ((23334, 23384), 'copy.deepcopy', 'copy.deepcopy', (['self.super_targets_masks[start:end]'], {}), '(self.super_targets_masks[start:end])\n', (23347, 23384), False, 'import copy\n'), ((23386, 23444), 'copy.deepcopy', 'copy.deepcopy', (['self.super_targets_inverse_masks[start:end]'], {}), '(self.super_targets_inverse_masks[start:end])\n', (23399, 23444), False, 'import copy\n'), ((23463, 23513), 'copy.deepcopy', 'copy.deepcopy', (['self.super_targets_idxes[start:end]'], {}), '(self.super_targets_idxes[start:end])\n', (23476, 23513), False, 'import copy\n'), ((23515, 23559), 'copy.deepcopy', 'copy.deepcopy', (['self.super_targets[start:end]'], {}), '(self.super_targets[start:end])\n', (23528, 23559), False, 'import copy\n'), ((11834, 11871), 'numpy.stack', 'np.stack', (['super_targets_idxes'], {'axis': '(0)'}), '(super_targets_idxes, axis=0)\n', (11842, 11871), True, 'import numpy as np\n'), ((12735, 12752), 'numpy.array', 'np.array', (['img_idx'], {}), '(img_idx)\n', (12743, 12752), True, 'import numpy as np\n'), ((12628, 12656), 'numpy.array', 'np.array', (['self.whole_dataset'], {}), '(self.whole_dataset)\n', (12636, 12656), True, 'import numpy as np\n')]
""" Copyright (c) 2018-2021 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import numpy as np import cv2 from .format_converter import DirectoryBasedAnnotationConverter, ConverterReturn from ..utils import UnsupportedPackage from ..representation import CharacterRecognitionAnnotation from ..config import BoolField try: import lmdb except ImportError as import_error: lmdb = UnsupportedPackage("lmdb", import_error.msg) class LMDBConverter(DirectoryBasedAnnotationConverter): __provider__ = 'lmdb_text_recognition_database' annotation_types = (CharacterRecognitionAnnotation, ) supported_symbols = '0123456789abcdefghijklmnopqrstuvwxyz' @classmethod def parameters(cls): configuration_parameters = super().parameters() configuration_parameters.update({ 'lower_case': BoolField(description='Convert GT text to lowercase.', optional=True) }) return configuration_parameters def configure(self): super().configure() self.lower_case = self.get_value_from_config('lower_case') def convert(self, check_content=False, progress_callback=None, progress_interval=100, **kwargs): """Reads data from disk and returns dataset in converted for AC format Args: check_content (bool, optional): Check if content is valid. Defaults to False. progress_callback (bool, optional): Display progress. Defaults to None. progress_interval (int, optional): Units to display progress. Defaults to 100 (percent). Returns: [type]: Converted dataset """ annotations = [] content_errors = None if not check_content else [] lmdb_env = lmdb.open(bytes(self.data_dir), readonly=True) with lmdb_env.begin(write=False) as txn: num_iterations = int(txn.get('num-samples'.encode())) for index in range(1, num_iterations + 1): label_key = f'label-{index:09d}'.encode() text = txn.get(label_key).decode('utf-8') if self.lower_case: text = text.lower() if progress_callback is not None and index % progress_interval == 0: progress_callback(index / num_iterations * 100) if check_content: img_key = f'label-{index:09d}'.encode() image_bytes = txn.get(img_key) image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_ANYCOLOR) if image is None: content_errors.append(f'label-{index:09d}: does not exist') annotations.append(CharacterRecognitionAnnotation(index, text)) label_map = {ind: str(key) for ind, key in enumerate(self.supported_symbols)} meta = {'label_map': label_map, 'blank_label': len(label_map)} return ConverterReturn(annotations, meta, content_errors)
[ "numpy.frombuffer" ]
[((2963, 2999), 'numpy.frombuffer', 'np.frombuffer', (['image_bytes', 'np.uint8'], {}), '(image_bytes, np.uint8)\n', (2976, 2999), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # Copyright (c) the JPEG XL Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """JPEG XL conformance test runner. Tool to perform a conformance test for a decoder. """ import argparse import json import numpy import os import subprocess import sys import tempfile class ConformanceTestError(Exception): """General conformance test error.""" def CompareNPY(ref_npy, ref_icc, dec_npy, dec_icc, threshold=0.): """Compare a decoded numpy against the reference one.""" ref = numpy.load(ref_npy) dec = numpy.load(dec_npy) if ref.shape != dec.shape: raise ConformanceTestError('Expected shape %s but found %s' % (ref.shape, dec.shape)) # TODO(deymo): Implement this comparison. def CompareBinaries(ref_bin, dec_bin): """Compare a decoded binary file against the reference for exact contents.""" with open(ref_bin, 'rb') as reff: ref_data = reff.read() with open(dec_bin, 'rb') as decf: dec_data = decf.read() if ref_data != dec_data: raise ConformanceTestError('Binary files mismatch: %s %s' % (ref_bin, dec_bin)) def ConformanceTestRunner(args): # We can pass either the .txt file or the directory which defaults to the # full corpus. This is useful to run a subset of the corpus in other .txt # files. if os.path.isdir(args.corpus): corpus_dir = args.corpus corpus_txt = os.path.join(args.corpus, 'corpus.txt') else: corpus_dir = os.path.dirname(args.corpus) corpus_txt = args.corpus with open(corpus_txt, 'r') as f: for test_id in f: test_id = test_id.rstrip('\n') print('Testing %s' % test_id) test_dir = os.path.join(corpus_dir, test_id) with open(os.path.join(test_dir, 'test.json'), 'r') as f: descriptor = json.load(f) exact_tests = [] with tempfile.TemporaryDirectory(prefix=test_id) as work_dir: cmd = [args.decoder, os.path.join(test_dir, descriptor['jxl'])] # Select the parameters to run. pixel_prefix = os.path.join(work_dir, 'dec') cmd.extend(['-p', pixel_prefix]) # TODO(deymo): Add preview. if 'preview main' in descriptor: cmd.append('-w') if 'jpeg' in descriptor: jpeg_filename = os.path.join(work_dir, 'decoded.jpg') cmd.extend(['-j', jpeg_filename]) exact_tests.append(('jpeg', jpeg_filename)) if 'original_icc' in descriptor: decoded_original_icc = os.path.join(work_dir, 'decoded_org.icc') cmd.extend(['-i', decoded_original_icc]) exact_tests.append(('original_icc', decoded_original_icc)) if subprocess.call(cmd) != 0: raise ConformanceTestError( 'Running the decoder (%s) returned error' % ' '.join(cmd)) # Run validation of exact files. for key, decoded_filename in exact_tests: reference_filename = os.path.join(test_dir, descriptor[key]) CompareBinaries(reference_filename, decoded_filename) # Pixel data. decoded_icc = pixel_prefix + '.icc' reference_icc = os.path.join(test_dir, descriptor['reference_icc']) if 'reference' in descriptor: reference_npy = os.path.join(test_dir, descriptor['reference']) decoded_npy = os.path.join(work_dir, 'dec.npy') if not os.path.exists(decoded_npy): raise ConformanceTestError('File not decoded: dec.npy') CompareNPY(reference_npy, reference_icc, decoded_npy, decoded_icc) # TODO(deymo): Add preview return True def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--decoder', metavar='DECODER', required=True, help='path to the decoder binary under test.') parser.add_argument('--corpus', metavar='CORPUS', required=True, help=('path to the corpus directory or corpus descriptor' ' text file.')) args = parser.parse_args() if not ConformanceTestRunner(args): sys.exit(1) if __name__ == '__main__': main()
[ "numpy.load", "json.load", "tempfile.TemporaryDirectory", "argparse.ArgumentParser", "os.path.isdir", "os.path.dirname", "os.path.exists", "subprocess.call", "os.path.join", "sys.exit" ]
[((1010, 1029), 'numpy.load', 'numpy.load', (['ref_npy'], {}), '(ref_npy)\n', (1020, 1029), False, 'import numpy\n'), ((1038, 1057), 'numpy.load', 'numpy.load', (['dec_npy'], {}), '(dec_npy)\n', (1048, 1057), False, 'import numpy\n'), ((1846, 1872), 'os.path.isdir', 'os.path.isdir', (['args.corpus'], {}), '(args.corpus)\n', (1859, 1872), False, 'import os\n'), ((4116, 4160), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (4139, 4160), False, 'import argparse\n'), ((1920, 1959), 'os.path.join', 'os.path.join', (['args.corpus', '"""corpus.txt"""'], {}), "(args.corpus, 'corpus.txt')\n", (1932, 1959), False, 'import os\n'), ((1985, 2013), 'os.path.dirname', 'os.path.dirname', (['args.corpus'], {}), '(args.corpus)\n', (2000, 2013), False, 'import os\n'), ((4561, 4572), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4569, 4572), False, 'import sys\n'), ((2191, 2224), 'os.path.join', 'os.path.join', (['corpus_dir', 'test_id'], {}), '(corpus_dir, test_id)\n', (2203, 2224), False, 'import os\n'), ((2311, 2323), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2320, 2323), False, 'import json\n'), ((2360, 2403), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {'prefix': 'test_id'}), '(prefix=test_id)\n', (2387, 2403), False, 'import tempfile\n'), ((2552, 2581), 'os.path.join', 'os.path.join', (['work_dir', '"""dec"""'], {}), "(work_dir, 'dec')\n", (2564, 2581), False, 'import os\n'), ((3626, 3677), 'os.path.join', 'os.path.join', (['test_dir', "descriptor['reference_icc']"], {}), "(test_dir, descriptor['reference_icc'])\n", (3638, 3677), False, 'import os\n'), ((2242, 2277), 'os.path.join', 'os.path.join', (['test_dir', '"""test.json"""'], {}), "(test_dir, 'test.json')\n", (2254, 2277), False, 'import os\n'), ((2446, 2487), 'os.path.join', 'os.path.join', (['test_dir', "descriptor['jxl']"], {}), "(test_dir, descriptor['jxl'])\n", (2458, 2487), False, 'import os\n'), ((2786, 2823), 'os.path.join', 'os.path.join', (['work_dir', '"""decoded.jpg"""'], {}), "(work_dir, 'decoded.jpg')\n", (2798, 2823), False, 'import os\n'), ((2996, 3037), 'os.path.join', 'os.path.join', (['work_dir', '"""decoded_org.icc"""'], {}), "(work_dir, 'decoded_org.icc')\n", (3008, 3037), False, 'import os\n'), ((3170, 3190), 'subprocess.call', 'subprocess.call', (['cmd'], {}), '(cmd)\n', (3185, 3190), False, 'import subprocess\n'), ((3431, 3470), 'os.path.join', 'os.path.join', (['test_dir', 'descriptor[key]'], {}), '(test_dir, descriptor[key])\n', (3443, 3470), False, 'import os\n'), ((3743, 3790), 'os.path.join', 'os.path.join', (['test_dir', "descriptor['reference']"], {}), "(test_dir, descriptor['reference'])\n", (3755, 3790), False, 'import os\n'), ((3815, 3848), 'os.path.join', 'os.path.join', (['work_dir', '"""dec.npy"""'], {}), "(work_dir, 'dec.npy')\n", (3827, 3848), False, 'import os\n'), ((3866, 3893), 'os.path.exists', 'os.path.exists', (['decoded_npy'], {}), '(decoded_npy)\n', (3880, 3893), False, 'import os\n')]
import json import logging from itertools import cycle import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import MeanShift, estimate_bandwidth from sklearn.datasets.samples_generator import make_blobs log = logging.getLogger(__name__) def analyze(data): # Convert this to python data for us to be able to run ML algorithms json_to_python = json.loads(data) per_size = dict() # IP-Response size hostlist = dict() # Data pre-processing here: for y in json_to_python: hostlist[y['HOST']] = 1 if y['HOST'] in per_size: per_size[y['HOST']].append(int(y['SIZE'])) else: per_size[y['HOST']] = [int(y['SIZE'])] ##Data pre-processing ends here log.debug( "*** Printing Input to analysis - 4 (1): K-means on IP and average response size ****" ) #####*****SIZE******#### #### Analysis #4 (1): IP address - Size of response received feature X = np.array([[0.00, 0.00]]) for x in hostlist: avg_size = mean(per_size[x]) log.debug(x + ": " + str(avg_size)) y = x.split(".") ip = "" for z in range(4): l = len(y[z]) l = 3 - l if (l > 0): zero = "" for t in range(3 - len(y[z])): zero = zero + "0" y[z] = zero + y[z] ip = ip + y[z] # log.debug( str(float(float(ip)/1000)) + ": " + str(avg_size)) le = [float(float(ip) / 1000), avg_size] X = np.vstack([X, le]) log.info( "******** Printing Analysis #4: IP-Address and Response Size received: MEAN SHIFT algorithm ********" ) log.info("Please check the graph at test-mean-shift.png for more info!") # print kmeans.labels_ ## Analysis 4 (6): MEAN SHIFT algorithm: (IP-response size) ######### # ############################################################################# # Generate sample data X1 = X centers = X1 X, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6) # ############################################################################# # Compute clustering with MeanShift # The following bandwidth can be automatically detected using bandwidth = estimate_bandwidth(X, quantile=0.2, n_samples=500) ms = MeanShift(bandwidth=bandwidth, bin_seeding=True) ms.fit(X) labels = ms.labels_ cluster_centers = ms.cluster_centers_ labels_unique = np.unique(labels) n_clusters_ = len(labels_unique) log.info("number of estimated clusters : %d" % n_clusters_) # ############################################################################# # Plot result plt.figure(1) plt.clf() colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk') for k, col in zip(range(n_clusters_), colors): my_members = labels == k cluster_center = cluster_centers[k] plt.plot(X[my_members, 0], X[my_members, 1], col + '.') plt.plot( cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=14) plt.title('Estimated number of clusters: %d' % n_clusters_) ##plt.show() plt.savefig('test-mean-shift.png') def mean(numbers): return float(sum(numbers)) / max(len(numbers), 1)
[ "matplotlib.pyplot.title", "matplotlib.pyplot.savefig", "json.loads", "matplotlib.pyplot.plot", "matplotlib.pyplot.clf", "sklearn.cluster.MeanShift", "numpy.unique", "sklearn.cluster.estimate_bandwidth", "matplotlib.pyplot.figure", "numpy.vstack", "numpy.array", "sklearn.datasets.samples_generator.make_blobs", "itertools.cycle", "logging.getLogger" ]
[((230, 257), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (247, 257), False, 'import logging\n'), ((373, 389), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (383, 389), False, 'import json\n'), ((973, 995), 'numpy.array', 'np.array', (['[[0.0, 0.0]]'], {}), '([[0.0, 0.0]])\n', (981, 995), True, 'import numpy as np\n'), ((2039, 2100), 'sklearn.datasets.samples_generator.make_blobs', 'make_blobs', ([], {'n_samples': '(10000)', 'centers': 'centers', 'cluster_std': '(0.6)'}), '(n_samples=10000, centers=centers, cluster_std=0.6)\n', (2049, 2100), False, 'from sklearn.datasets.samples_generator import make_blobs\n'), ((2309, 2359), 'sklearn.cluster.estimate_bandwidth', 'estimate_bandwidth', (['X'], {'quantile': '(0.2)', 'n_samples': '(500)'}), '(X, quantile=0.2, n_samples=500)\n', (2327, 2359), False, 'from sklearn.cluster import MeanShift, estimate_bandwidth\n'), ((2370, 2418), 'sklearn.cluster.MeanShift', 'MeanShift', ([], {'bandwidth': 'bandwidth', 'bin_seeding': '(True)'}), '(bandwidth=bandwidth, bin_seeding=True)\n', (2379, 2418), False, 'from sklearn.cluster import MeanShift, estimate_bandwidth\n'), ((2520, 2537), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (2529, 2537), True, 'import numpy as np\n'), ((2747, 2760), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (2757, 2760), True, 'import matplotlib.pyplot as plt\n'), ((2765, 2774), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2772, 2774), True, 'import matplotlib.pyplot as plt\n'), ((2789, 2826), 'itertools.cycle', 'cycle', (['"""bgrcmykbgrcmykbgrcmykbgrcmyk"""'], {}), "('bgrcmykbgrcmykbgrcmykbgrcmyk')\n", (2794, 2826), False, 'from itertools import cycle\n'), ((3213, 3272), 'matplotlib.pyplot.title', 'plt.title', (["('Estimated number of clusters: %d' % n_clusters_)"], {}), "('Estimated number of clusters: %d' % n_clusters_)\n", (3222, 3272), True, 'import matplotlib.pyplot as plt\n'), ((3294, 3328), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""test-mean-shift.png"""'], {}), "('test-mean-shift.png')\n", (3305, 3328), True, 'import matplotlib.pyplot as plt\n'), ((1553, 1571), 'numpy.vstack', 'np.vstack', (['[X, le]'], {}), '([X, le])\n', (1562, 1571), True, 'import numpy as np\n'), ((2963, 3018), 'matplotlib.pyplot.plot', 'plt.plot', (['X[my_members, 0]', 'X[my_members, 1]', "(col + '.')"], {}), "(X[my_members, 0], X[my_members, 1], col + '.')\n", (2971, 3018), True, 'import matplotlib.pyplot as plt\n'), ((3027, 3139), 'matplotlib.pyplot.plot', 'plt.plot', (['cluster_center[0]', 'cluster_center[1]', '"""o"""'], {'markerfacecolor': 'col', 'markeredgecolor': '"""k"""', 'markersize': '(14)'}), "(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,\n markeredgecolor='k', markersize=14)\n", (3035, 3139), True, 'import matplotlib.pyplot as plt\n')]
from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import inspect import sys import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import math from itertools import product as product import cv2 from trident.backend.opencv_backend import image2array from trident.data.dataset import BboxDataset from trident.backend.common import * from trident.backend.tensorspec import * from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList from trident.backend.pytorch_ops import * from trident.backend.pillow_backend import image2array, array2image from trident.data.bbox_common import xywh2xyxy, xyxy2xywh, bbox_giou, bbox_giou_numpy from trident.data.image_common import * from trident.data.utils import download_model_from_google_drive from trident.layers.pytorch_activations import get_activation, Identity, Relu, softmax from trident.layers.pytorch_blocks import * from trident.layers.pytorch_layers import * from trident.layers.pytorch_normalizations import get_normalization from trident.layers.pytorch_pooling import * from trident.optims.pytorch_trainer import * from trident.optims.pytorch_losses import * from trident.data.transform import * from trident.data.vision_transforms import Resize, Normalize from trident.misc.visualization_utils import generate_palette, plot_bbox image_size = [640, 480] cfg = {'min_sizes': [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]], 'steps': [8, 16, 32, 64], 'variance': [0.1, 0.2], 'clip': False, } __all__ = ['Ssd', 'encode', 'decode', 'SsdBboxDataset', 'SsdBboxDatasetV2', 'SsdDetectionModel', 'MultiBoxLoss', 'MultiBoxLossV2', 'IoULoss'] def intersect(box_a, box_b): """ We Resize both tensors to [A,B,2] without new malloc: [A,2] -> [A,1,2] -> [A,B,2] [B,2] -> [1,B,2] -> [A,B,2] Then we compute the area of intersect between box_a and box_b. Args: box_a: (tensor) bounding boxes, Shape: [A,4]. box_b: (tensor) bounding boxes, Shape: [B,4]. Return: (tensor) intersection area, Shape: [A,B]. """ A = box_a.size(0) B = box_b.size(0) max_xy = torch.min(box_a[:, 2:4].unsqueeze(1).expand(A, B, 2), box_b[:, 2:4].unsqueeze(0).expand(A, B, 2)) min_xy = torch.max(box_a[:, 0:2].unsqueeze(1).expand(A, B, 2), box_b[:, 0:2].unsqueeze(0).expand(A, B, 2)) inter = torch.clamp((max_xy - min_xy), min=0) return inter[:, :, 0] * inter[:, :, 1] def jaccard(box_a, box_b): """Compute the jaccard overlap of two sets of boxes. The jaccard overlap is simply the intersection over union of two boxes. Here we operate on ground truth boxes and default boxes. E.g.: A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B) Args: box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4] box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4] Return: jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)] """ inter = intersect(box_a, box_b) area_a = ((box_a[:, 2] - box_a[:, 0]) * (box_a[:, 3] - box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B] area_b = ((box_b[:, 2] - box_b[:, 0]) * (box_b[:, 3] - box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B] union = area_a + area_b - inter return inter / union # [A,B] def match(truths, priors, variances, labels, threshold=0.3): """Match each prior box with the ground truth box of the highest jaccard overlap, encode the bounding boxes, then return the matched indices corresponding to both confidence and location preds. Args: truths: (tensor) Ground truth boxes, Shape: [num_obj, num_priors]. priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4]. variances: (tensor) Variances corresponding to each prior coord, Shape: [num_priors, 4]. labels: (tensor) All the class labels for the image, Shape: [num_obj]. loc_t: (tensor) Tensor to be filled w/ endcoded location targets. conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds. idx: (int) current batch index threshold: (float) The overlap threshold used when mathing boxes. Return: The matched indices corresponding to 1)location and 2)confidence preds. """ # jaccard index priors2 = priors.clone() num_priors = len(priors) overlaps = jaccard(truths, xywh2xyxy(priors.clone())) # (Bipartite Matching) # [1,num_objects] best prior for each ground truth best_prior_overlap, best_prior_idx = overlaps.max(1, keepdim=True) # ignore hard gt valid_gt_idx = best_prior_overlap[:, 0] >= 0.2 best_prior_idx_filter = best_prior_idx[valid_gt_idx, :] if best_prior_idx_filter.shape[0] <= 0: return np.zeros((num_priors, 4)).astype(np.float32), np.zeros(num_priors).astype(np.int64) # [1,num_priors] best ground truth for each prior best_truth_overlap, best_truth_idx = overlaps.max(0, keepdim=True) best_truth_idx.squeeze_(0) best_truth_overlap.squeeze_(0) best_prior_idx.squeeze_(1) best_prior_idx_filter.squeeze_(1) best_prior_overlap.squeeze_(1) best_truth_overlap.index_fill_(0, best_prior_idx_filter, 2) # ensure best prior # TODO refactor: index best_prior_idx with long tensor # ensure every gt matches with its prior of max overlap for j in range(best_prior_idx.size(0)): best_truth_idx[best_prior_idx[j]] = j matches = truths[best_truth_idx] # Shape: [num_priors,14] conf = labels[best_truth_idx] # Shape: [num_priors] conf[best_truth_overlap < threshold] = 0 # label as background loc = encode(matches, priors2, variances) return loc, conf def encode(matched, priors, variances): """ Args: matched (tensor): Coords of ground truth for each prior in xyxy Shape: [num_priors, 4]. priors (tensor): Prior boxes in center-offset form Shape: [num_priors,4]. variances (list[float]): Variances of priorboxes Returns: encoded boxes and landmarks (tensor), Shape: [num_priors, 14] """ # dist b/t match center and prior's center priors = priors.clone() g_cxcy = (matched[:, 0:2] + matched[:, 2:4]) / 2 - priors[:, 0:2] # encode variance g_cxcy /= (variances[0] * priors[:, 2:4]) # match wh / prior wh g_wh = (matched[:, 2:4] - matched[:, 0:2]) / priors[:, 2:4] g_wh = torch.log(g_wh) / variances[1] # # landmarks # g_xy1 = (matched[:, 4:6] - priors[:, 0:2]) / (variances[0] * priors[:, 2:4]) # g_xy2 = (matched[:, 6:8] - priors[:, 0:2]) / (variances[0] * priors[:, 2:4]) # g_xy3 = (matched[:, 8:10] - priors[:, 0:2]) / (variances[0] * priors[:, 2:4]) # g_xy4 = (matched[:, 10:12] - priors[:, 0:2]) / (variances[0] * priors[:, 2:4]) # g_xy5 = (matched[:, 12:14] - priors[:, 0:2]) / (variances[0] * priors[:, 2:4]) # return target for loss return torch.cat([g_cxcy, g_wh], 1) # [num_priors,14] def decode(loc, priors, variances): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Adapted from https://github.com/Hakuyume/chainer-ssd Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded bounding box predictions """ boxes = torch.cat([priors.unsqueeze(0)[:, :, 0:2] + loc[:, :, 0:2] * variances[0] * priors.unsqueeze(0)[:, :, 2:4], priors.unsqueeze(0)[:, :, 2:4] * torch.exp(loc[:, :, 2:4] * variances[1])], -1) boxes[:, :, 0:2] -= boxes[:, :, 2:4] / 2 boxes[:, :, 2:4] += boxes[:, :, 0:2] return boxes class SsdBboxDataset(BboxDataset): def __init__(self, boxes=None, image_size=None, priors=None, center_variance=0.1, size_variance=0.2, gt_overlap_tolerance=0.5, expect_data_type=ExpectDataType.absolute_bbox, class_names=None, symbol='bbox', name=''): super().__init__(boxes=boxes, image_size=image_size, expect_data_type=expect_data_type, class_names=class_names, symbol=symbol, name=name) self.priors = priors self.label_transform_funcs = [] self.gt_overlap_tolerance = gt_overlap_tolerance self.bbox_post_transform_funcs = [] def binding_class_names(self, class_names=None, language=None): if class_names is not None and hasattr(class_names, '__len__'): if language is None: language = 'en-us' self.class_names[language] = list(class_names) self.__default_language__ = language self._lab2idx = {v: k for k, v in enumerate(self.class_names[language])} self._idx2lab = {k: v for k, v in enumerate(self.class_names[language])} def bbox_transform(self, bbox): num_priors = self.priors.shape[0] if bbox is None or len(bbox) == 0: return np.zeros((num_priors, 4)).astype(np.float32), np.zeros(num_priors).astype(np.int64) elif isinstance(bbox, np.ndarray): height, width = self.image_size gt_label = None gt_box = bbox if bbox.shape[-1] % 2 == 1: gt_box = bbox[:, :-1] gt_label = bbox[:, -1] gt_box[:, 0::2] /= width gt_box[:, 1::2] /= height # match priors (default boxes) and ground truth boxes if gt_box is not None and len(gt_box) > 0: truths = to_tensor(gt_box).float() labels = to_tensor(gt_label).long() loc_t, conf_t = match(truths, self.priors.data, (0.1, 0.2), labels, self.gt_overlap_tolerance) return to_numpy(loc_t).astype(np.float32), to_numpy(conf_t).astype(np.int64) return np.zeros((num_priors, 4)).astype(np.float32), np.zeros(num_priors).astype(np.int64) class SsdBboxDatasetV2(BboxDataset): def __init__(self, boxes=None, image_size=None, priors=None, center_variance=0.1, size_variance=0.2, gt_overlap_tolerance=0.5, expect_data_type=ExpectDataType.absolute_bbox, class_names=None, symbol='bbox', name=''): super().__init__(boxes=boxes, image_size=image_size, expect_data_type=expect_data_type, class_names=class_names, symbol=symbol, name=name) self.priors = priors self.center_variance = center_variance self.size_variance = size_variance self.label_transform_funcs = [] self.gt_overlap_tolerance = gt_overlap_tolerance self.bbox_post_transform_funcs = [] def area_of(self, left_top, right_bottom): """Compute the areas of rectangles given two corners. Args: left_top (N, 2): left top corner. right_bottom (N, 2): right bottom corner. Returns: area (N): return the area. """ hw = np.clip(right_bottom - left_top, 0.0, None) return hw[..., 0] * hw[..., 1] def iou_of(self, boxes0, boxes1, eps=1e-5): """Return intersection-over-union (Jaccard index) of boxes. Args: boxes0 (N, 4): ground truth boxes. boxes1 (N or 1, 4): predicted boxes. eps: a small number to avoid 0 as denominator. Returns: iou (N): IoU values. """ overlap_left_top = np.maximum(boxes0[..., :2], boxes1[..., :2]) overlap_right_bottom = np.minimum(boxes0[..., 2:], boxes1[..., 2:]) overlap_area = self.area_of(overlap_left_top, overlap_right_bottom) area0 = self.area_of(boxes0[..., :2], boxes0[..., 2:]) area1 = self.area_of(boxes1[..., :2], boxes1[..., 2:]) return overlap_area / (area0 + area1 - overlap_area + eps) def convert_boxes_to_locations(self, center_form_boxes, center_form_priors): if len(center_form_priors.shape) + 1 == len(center_form_boxes.shape): center_form_priors = np.expand_dims(center_form_priors, 0) return np.concatenate([(center_form_boxes[..., :2] - center_form_priors[..., :2]) / center_form_priors[..., 2:] / self.center_variance, np.log(np.clip(center_form_boxes[..., 2:] / center_form_priors[..., 2:], 1e-8, np.inf)) / self.size_variance], axis=len(center_form_boxes.shape) - 1) def assign_priors(self, gt_boxes, gt_labels, center_form_priors, iou_threshold): # """Assign ground truth boxes and targets to priors. # # Args: # gt_boxes (num_targets, 4): ground truth boxes. # gt_labels (num_targets): labels of targets. # priors (num_priors, 4): corner form priors # Returns: # boxes (num_priors, 4): real values for priors. # labels (num_priros): labels for priors. # """ # # size: num_priors x num_targets # # if gt_boxes is not None : # # ious = self.iou_of(gt_boxes.unsqueeze(0), corner_form_priors.unsqueeze(1)) # # size: num_priors # best_target_per_prior, best_target_per_prior_index = ious.max(1) # # size: num_targets # best_prior_per_target, best_prior_per_target_index = ious.max(0) # # for target_index, prior_index in enumerate(best_prior_per_target_index): # best_target_per_prior_index[prior_index] = target_index # # 2.0 is used to make sure every target has a prior assigned # best_target_per_prior.index_fill_(0, best_prior_per_target_index, 2) # # size: num_priors # labels = gt_labels[best_target_per_prior_index] # labels[best_target_per_prior < iou_threshold] = 0 # the backgournd id # boxes = gt_boxes[best_target_per_prior_index] # return boxes, labels corner_form_priors = xywh2xyxy(center_form_priors) ious = self.iou_of(np.expand_dims(gt_boxes, 0), np.expand_dims(corner_form_priors, 1)) # size: num_priors best_target_per_prior, best_target_per_prior_index = np.max(ious, axis=1), np.argmax(ious, axis=1) # size: num_targets best_prior_per_target, best_prior_per_target_index = np.max(ious, axis=0), np.argmax(ious, axis=0) for target_index, prior_index in enumerate(best_prior_per_target_index): best_target_per_prior_index[prior_index] = target_index # 2.0 is used to make sure every target has a prior assigned best_prior_per_target_index_list = best_prior_per_target_index.tolist() for i in range(best_target_per_prior.shape[0]): if i in best_prior_per_target_index_list: best_target_per_prior[i] = 2 labels = gt_labels[best_target_per_prior_index] labels[best_target_per_prior < iou_threshold] = 0 # the backgournd id boxes = gt_boxes[best_target_per_prior_index] return boxes, labels def binding_class_names(self, class_names=None, language=None): if class_names is not None and hasattr(class_names, '__len__'): if language is None: language = 'en-us' self.class_names[language] = list(class_names) self.__default_language__ = language self._lab2idx = {v: k for k, v in enumerate(self.class_names[language])} self._idx2lab = {k: v for k, v in enumerate(self.class_names[language])} def bbox_transform(self, bbox): if bbox is None or len(bbox) == 0: return np.zeros((self.priors.shape[0], 4)).astype(np.float32), np.zeros((self.priors.shape[0])).astype( np.int64) elif isinstance(bbox, np.ndarray): height, width = self.image_size bbox[:, 0] = bbox[:, 0] / width bbox[:, 2] = bbox[:, 2] / width bbox[:, 1] = bbox[:, 1] / height bbox[:, 3] = bbox[:, 3] / height if bbox.shape[-1] == 5: gt_box = bbox[:, :4] gt_label = bbox[:, 4] boxes, labels = self.assign_priors(gt_box, gt_label, to_numpy(self.priors), 0.3) boxes = xyxy2xywh(boxes) locations = self.convert_boxes_to_locations(boxes, to_numpy(self.priors)) return boxes.astype(np.float32), labels.astype(np.int64) else: return bbox def hard_negative_mining(loss, labels, neg_pos_ratio): """ It used to suppress the presence of a large number of negative prediction. It works on image level not batch level. For any example/image, it keeps all the positive predictions and cut the number of negative predictions to make sure the ratio between the negative examples and positive examples is no more the given ratio for an image. Args: loss (N, num_priors): the loss for each example. labels (N, num_priors): the labels. neg_pos_ratio: the ratio between the negative examples and positive examples. """ pos_mask = labels > 0 num_pos = pos_mask.long().sum() num_neg = num_pos * neg_pos_ratio loss[pos_mask] = -math.inf _, indexes = loss.sort(descending=True) _, orders = indexes.sort() neg_mask = orders < num_neg return pos_mask | neg_mask class MultiBoxLoss(nn.Module): def __init__(self, priors, neg_pos_ratio, center_variance, size_variance): """Implement SSD Multibox Loss. Basically, Multibox loss combines classification loss and Smooth L1 regression loss. """ super(MultiBoxLoss, self).__init__() self.neg_pos_ratio = neg_pos_ratio self.center_variance = center_variance self.size_variance = size_variance self.priors = to_tensor(priors) def forward(self, confidence, locations, target_confidence, target_locations): """Compute classification loss and smooth l1 loss. Args: confidence (batch_size, num_priors, num_classes): class predictions. locations (batch_size, num_priors, 4): predicted locations. labels (batch_size, num_priors): real labels of all the priors. boxes (batch_size, num_priors, 4): real boxes corresponding all the priors. """ num_classes = confidence.size(2) # derived from cross_entropy=sum(log(p)) with torch.no_grad(): loss = -F.log_softmax(confidence, dim=2)[:, :, 0] mask = hard_negative_mining(loss, target_confidence, self.neg_pos_ratio) weight = to_tensor(np.array([0.05, 1, 5, 20, 10])) classification_loss = F.cross_entropy(confidence[mask, :].reshape(-1, num_classes), target_confidence[mask], weight=weight, reduction='sum') # classification_loss += 0.1*F.cross_entropy(confidence.reshape(-1, num_classes), target_confidence.reshape( # -1), weight=weight, reduction='sum') pos_mask = target_confidence > 0 locations = locations[pos_mask, :].reshape(-1, 4) target_locations = target_locations[pos_mask, :].reshape(-1, 4) smooth_l1_loss = F.mse_loss(locations, target_locations, reduction='sum') # smooth_l1_loss smooth_l1_loss += F.l1_loss(locations[:, 2:4].exp(), target_locations[:, 2:4].exp(), reduction='sum') num_pos = target_locations.size(0) return (smooth_l1_loss + classification_loss) / num_pos class MultiBoxLossV2(nn.Module): def __init__(self, priors, neg_pos_ratio, center_variance, size_variance): """Implement SSD Multibox Loss. Basically, Multibox loss combines classification loss and Smooth L1 regression loss. """ super(MultiBoxLossV2, self).__init__() self.neg_pos_ratio = neg_pos_ratio self.center_variance = center_variance self.size_variance = size_variance self.priors = to_tensor(priors) def forward(self, confidence, locations, target_confidence, target_locations): """Compute classification loss and smooth l1 loss. Args: confidence (batch_size, num_priors, num_classes): class predictions. locations (batch_size, num_priors, 4): predicted locations. target_confidence (batch_size, num_priors): real labels of all the priors. target_locations (batch_size, num_priors, 4): real boxes corresponding all the priors. """ num_classes = confidence.size(2) # derived from cross_entropy=sum(log(p)) with torch.no_grad(): loss = -F.log_softmax(confidence, dim=2)[:, :, 0] mask = hard_negative_mining(loss, target_confidence, self.neg_pos_ratio) classification_loss = CrossEntropyLoss(axis=-1, label_smooth=True, reduction='sum')(confidence[mask, :].reshape(-1, num_classes), target_confidence[mask].reshape(-1)) pos_mask = target_confidence > 0 target_locations = target_locations[pos_mask, :].reshape(-1, 4) num_pos = target_locations.size(0) return classification_loss / num_pos class IouLoss(nn.Module): def __init__(self, priors, center_variance, size_variance): """Implement SSD Multibox Loss. Basically, Multibox loss combines classification loss and Smooth L1 regression loss. """ super(IoULoss, self).__init__() self.center_variance = center_variance self.size_variance = size_variance self.priors = to_tensor(priors) def forward(self, confidence, locations, target_confidence, target_locations): """Compute classification loss and smooth l1 loss. Args: confidence (batch_size, num_priors, num_classes): class predictions. locations (batch_size, num_priors, 4): predicted locations. target_confidence (batch_size, num_priors): real labels of all the priors. target_locations (batch_size, num_priors, 4): real boxes corresponding all the priors. """ num_classes = confidence.size(2) num_batch = confidence.size(0) confidence_logit = softmax(confidence, -1) confidence_logit_probs, confidence_logit_idxs = confidence_logit.max(-1) probs_mask = confidence_logit_probs > 0.5 label_mask = confidence_logit_idxs > 0 pos_target_mask_all = target_confidence > 0 pos_infer_mask_all = (pos_target_mask_all.float() + probs_mask.float() + label_mask.float() == 3) decode_locations_all = decode(locations, self.priors, (self.center_variance, self.size_variance)) decode_target_locations_all = decode(target_locations, self.priors, (self.center_variance, self.size_variance)) giou_np = 0.0 giou = 0.0 overlaps = 0.0 num_boxes = 0 for i in range(num_batch): pos_target_mask = pos_target_mask_all[i] pos_infer_mask = pos_infer_mask_all[i] decode_locations = decode_locations_all[i][pos_infer_mask, :] decode_target_locations = decode_target_locations_all[i][pos_target_mask, :] num_boxes += decode_target_locations.shape[0] if decode_target_locations.shape[0] > 0 and decode_locations.shape[0] > 0: giou = giou + (1 - (bbox_giou(decode_locations, decode_target_locations).sum(0) / decode_target_locations.shape[0])).sum() overlaps = overlaps + (-log(clip(jaccard(decode_locations, decode_target_locations), min=1e-8)).sum(0) / decode_target_locations.shape[0]).sum() elif decode_target_locations.shape[0] == 0 and decode_locations.shape[0] == 0: pass else: giou = giou + 1 overlaps = overlaps - log(to_tensor(1e-8)) giou = giou / num_boxes overlaps = overlaps / num_boxes return giou class Ssd(Layer): def __init__(self, backbond, base_filters=16, num_classes=5, num_regressors=14, variance=(0.1, 0.2), name='tiny_mobile_rfbnet', **kwargs): """ Parameters ---------- layer_defs : object """ super(Ssd, self).__init__(name=name) self.base_filters = base_filters idxes = [] if isinstance(backbond, Sequential): for i in range(len(backbond._modules)): layer = backbond[i] if hasattr(layer, 'strides') or isinstance(layer, Sequential): if isinstance(layer, Sequential): layer = layer[0] if isinstance(layer.strides, int) and layer.strides == 2: idxes.append(i) elif isinstance(layer.strides, tuple) and layer.strides[0] == 2: idxes.append(i) self.backbond1 = Sequential(backbond[:idxes[-2]], name='backbond1') self.backbond2 = Sequential(backbond[idxes[-2]:idxes[-1]], name='backbond2') self.backbond3 = Sequential(backbond[idxes[-1]:], name='backbond3') else: raise ValueError('{0} is not a valid backbond...'.format(backbond.__class__.__name__)) self.variance = variance self.num_classes = num_classes self.num_regressors = num_regressors self.extra = Sequential(Conv2d((1, 1), num_filters=64, strides=1, activation='relu', use_bias=True), DepthwiseConv2d((3, 3), depth_multiplier=1, strides=2, auto_pad=True, activation='relu', use_bias=True), Conv2d((1, 1), num_filters=256, strides=1, activation=None, use_bias=True), Relu()) self.regression_headers = nn.ModuleList([Sequential( DepthwiseConv2d((3, 3), depth_multiplier=1, strides=1, auto_pad=True, activation='relu', use_bias=True), Conv2d((1, 1), num_filters=3 * self.num_regressors, strides=1, activation=None, use_bias=True)), Sequential( DepthwiseConv2d((3, 3), depth_multiplier=1, strides=1, auto_pad=True, activation='relu', use_bias=True), Conv2d((1, 1), num_filters=2 * self.num_regressors, strides=1, activation=None, use_bias=True)), Sequential( DepthwiseConv2d((3, 3), depth_multiplier=1, strides=1, auto_pad=True, activation='relu', use_bias=True), Conv2d((1, 1), num_filters=2 * self.num_regressors, strides=1, activation=None, use_bias=True)), Conv2d((3, 3), num_filters=3 * self.num_regressors, strides=1, auto_pad=True, activation=None), ]) self.classification_headers = nn.ModuleList([Sequential( DepthwiseConv2d((3, 3), depth_multiplier=1, strides=1, auto_pad=True, activation='relu', use_bias=True), Conv2d((1, 1), num_filters=3 * self.num_classes, strides=1, activation=None, use_bias=True)), Sequential( DepthwiseConv2d((3, 3), depth_multiplier=1, strides=1, auto_pad=True, activation='relu', use_bias=True), Conv2d((1, 1), num_filters=2 * self.num_classes, strides=1, activation=None, use_bias=True)), Sequential( DepthwiseConv2d((3, 3), depth_multiplier=1, strides=1, auto_pad=True, activation='relu', use_bias=True), Conv2d((1, 1), num_filters=2 * self.num_classes, strides=1, activation=None, use_bias=True)), Conv2d((3, 3), num_filters=3 * self.num_classes, strides=1, auto_pad=True, activation=None, use_bias=True), ]) self.priors = [] # generate priors self.define_img_size(640) def generate_priors(self, feature_map_list, shrinkage_list, image_size, min_boxes, clamp=True) -> torch.Tensor: priors = [] for index in range(0, len(feature_map_list[0])): scale_w = image_size[0] / shrinkage_list[0][index] scale_h = image_size[1] / shrinkage_list[1][index] for j in range(0, feature_map_list[1][index]): for i in range(0, feature_map_list[0][index]): x_center = (i + 0.5) / scale_w y_center = (j + 0.5) / scale_h for min_box in min_boxes[index]: w = min_box / image_size[0] h = min_box / image_size[1] priors.append([x_center, y_center, w, h]) print("priors nums:{}".format(len(priors))) priors = to_tensor(priors) # .view(-1, 4) if clamp: torch.clamp(priors, 0.0, 1.0, out=priors) return priors def define_img_size(self, size=640): global image_size, feature_map_w_h_list, priors img_size_dict = {128: [128, 96], 160: [160, 120], 320: [320, 240], 480: [480, 360], 640: [640, 480], 1280: [1280, 960]} min_boxes = [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]] shrinkage_list = [] feature_map_w_h_list_dict = {128: [[16, 8, 4, 2], [12, 6, 3, 2]], 160: [[20, 10, 5, 3], [15, 8, 4, 2]], 320: [[40, 20, 10, 5], [30, 15, 8, 4]], 480: [[60, 30, 15, 8], [45, 23, 12, 6]], 640: [[80, 40, 20, 10], [60, 30, 15, 8]], 1280: [[160, 80, 40, 20], [120, 60, 30, 15]]} feature_map_w_h_list = feature_map_w_h_list_dict[size] for i in range(0, len(image_size)): item_list = [] for k in range(0, len(feature_map_w_h_list[i])): item_list.append(image_size[i] / feature_map_w_h_list[i][k]) shrinkage_list.append(item_list) self.priors = self.generate_priors(feature_map_w_h_list_dict[size], shrinkage_list, img_size_dict[size], min_boxes) def init_from_pretrained_ssd(self, model): def _xavier_init_(m: Layer): if isinstance(m, (Conv2d, DepthwiseConv2d)): nn.init.xavier_uniform_(m.weight) state_dict = torch.load(model, map_location=lambda storage, loc: storage) state_dict = state_dict['state_dict'] state_dict = {k: v for k, v in state_dict.items() if not (k.startswith("classification_headers") or k.startswith("regression_headers"))} model_dict = self.state_dict() model_dict.update(state_dict) self.load_state_dict(model_dict, strict=False) self.classification_headers.apply(_xavier_init_) self.regression_headers.apply(_xavier_init_) def compute_header(self, i, x): confidence = self.classification_headers[i](x) confidence = confidence.permute(0, 2, 3, 1).contiguous() confidence = confidence.view(confidence.size(0), -1, self.num_classes) location = self.regression_headers[i](x) location = location.permute(0, 2, 3, 1).contiguous() location = location.view(location.size(0), -1, 4) return confidence, location def forward(self, *x): x = enforce_singleton(x) confidences = [] locations = [] x = self.backbond1(x) confidence0, location0 = self.compute_header(0, x) confidences.append(confidence0) locations.append(location0) x = self.backbond2(x) confidence1, location1 = self.compute_header(1, x) confidences.append(confidence1) locations.append(location1) x = self.backbond3(x) confidence2, location2 = self.compute_header(2, x) confidences.append(confidence2) locations.append(location2) x = self.extra(x) confidence3, location3 = self.compute_header(3, x) confidences.append(confidence3) locations.append(location3) confidences = torch.cat(confidences, 1) locations = torch.cat(locations, 1) if self.training: return confidences, locations else: confidences = softmax(confidences, -1) locations = decode(locations, self.priors, self.variance) return confidences, locations class SsdDetectionModel(ImageDetectionModel): def __init__(self, inputs=None, input_shape=None, output=None): super(SsdDetectionModel, self).__init__(inputs, input_shape, output) self.preprocess_flow = [] self.palette = OrderedDict() with open('coco_classes.txt', 'r', encoding='utf-8-sig') as f: self.class_names = [l.rstrip() for l in f] object.__setattr__(self, 'detection_threshold', 0.2) object.__setattr__(self, 'nms_threshold', 0.1) def area_of(self, left_top, right_bottom): """Compute the areas of rectangles given two corners. Args: left_top (N, 2): left top corner. right_bottom (N, 2): right bottom corner. Returns: area (N): return the area. """ hw = clip(right_bottom - left_top, 0.0, None) return hw[..., 0] * hw[..., 1] def iou_of(self, boxes0, boxes1, eps=1e-5): """Return intersection-over-union (Jaccard index) of boxes. Args: boxes0 (N, 4): ground truth boxes. boxes1 (N or 1, 4): predicted boxes. eps: a small number to avoid 0 as denominator. Returns: iou (N): IoU values. """ overlap_left_top = maximum(boxes0[..., :2], boxes1[..., :2]) overlap_right_bottom = minimum(boxes0[..., 2:], boxes1[..., 2:]) overlap_area = self.area_of(overlap_left_top, overlap_right_bottom) area0 = self.area_of(boxes0[..., :2], boxes0[..., 2:]) area1 = self.area_of(boxes1[..., :2], boxes1[..., 2:]) return overlap_area / (area0 + area1 - overlap_area + eps) def hard_nms(self, box_scores, nms_threshold, top_k=-1, candidate_size=200): """ Args: box_scores (N, 5): boxes in corner-form and probabilities. nms_threshold: intersection over union threshold. top_k: keep top_k results. If k <= 0, keep all the results. candidate_size: only consider the candidates with the highest scores. Returns: picked: a list of indexes of the kept boxes """ if box_scores is None or len(box_scores) == 0: return None, None scores = box_scores[:, -1] boxes = box_scores[:, :4] picked = [] # _, indexes = scores.sort(descending=True) indexes = argsort(scores) # indexes = indexes[:candidate_size] indexes = indexes[-candidate_size:] while len(indexes) > 0: # current = indexes[0] current = indexes[-1] picked.append(current) if 0 < top_k == len(picked) or len(indexes) == 1: break current_box = boxes[current, :] # indexes = indexes[1:] indexes = indexes[:-1] rest_boxes = boxes[indexes, :] iou = self.iou_of(rest_boxes, expand_dims(current_box, axis=0), ) indexes = indexes[iou <= nms_threshold] return box_scores[picked, :], picked def nms(self, boxes, nms_threshold=0.3): # if there are no boxes, return an empty list if len(boxes) == 0: return [] # initialize the list of picked indexes pick = [] # grab the coordinates of the bounding boxes x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] # compute the area of the bounding boxes and sort the bounding # boxes by the bottom-right y-coordinate of the bounding box area = (x2 - x1 + 1) * (y2 - y1 + 1) idxs = np.argsort(y2) # keep looping while some indexes still remain in the indexes # list while len(idxs) > 0: # grab the last index in the indexes list, add the index # value to the list of picked indexes, then initialize # the suppression list (i.e. indexes that will be deleted) # using the last index last = len(idxs) - 1 i = idxs[last] pick.append(i) suppress = [last] # loop over all indexes in the indexes list for pos in range(0, last): # grab the current index j = idxs[pos] # find the largest (x, y) coordinates for the start of # the bounding box and the smallest (x, y) coordinates # for the end of the bounding box xx1 = max(x1[i], x1[j]) yy1 = max(y1[i], y1[j]) xx2 = min(x2[i], x2[j]) yy2 = min(y2[i], y2[j]) # compute the width and height of the bounding box w = max(0, xx2 - xx1 + 1) h = max(0, yy2 - yy1 + 1) # compute the ratio of overlap between the computed # bounding box and the bounding box in the area list overlap = float(w * h) / area[j] # if there is sufficient overlap, suppress the # current bounding box if overlap > nms_threshold: suppress.append(pos) # delete all indexes from the index list that are in the # suppression list idxs = np.delete(idxs, suppress) # return only the bounding boxes that were picked return boxes[pick], pick def infer_single_image(self, img, scale=1): if self._model.built: try: self._model.to(self.device) self._model.eval() if self._model.input_spec.object_type is None: self._model.input_spec.object_type = ObjectType.rgb img = image2array(img) if img.shape[-1] == 4: img = img[:, :, :3] img_orig = img.copy() rescale_scale = 1 for func in self.preprocess_flow: if (inspect.isfunction(func) or isinstance(func, Transform)) and func is not image_backend_adaption: img = func(img, spec=self._model.input_spec) if (inspect.isfunction(func) and func.__qualname__ == 'resize.<locals>.img_op') or (isinstance(func, Transform) and func.name == 'resize'): rescale_scale = func.scale else: print(func) img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) img = image_backend_adaption(img) inp = to_tensor(np.expand_dims(img, 0)).to( torch.device("cuda" if self._model.weights[0].data.is_cuda else "cpu")).to( self._model.weights[0].data.dtype) confidence, boxes = self._model(inp) boxes = boxes[0] confidence = confidence[0] if len(self.palette) == 0: self.palette = generate_palette(confidence.shape[-1]) probs = 1 - confidence[:, 0] label = argmax(confidence[:, 1:], -1) + 1 # mask = label > 0 # probs = probs[mask] # label = label[mask] # boxes = boxes[mask, :] print(probs.max()) mask = probs > self.detection_threshold probs = probs[mask] label = label[mask] boxes = boxes[mask, :] if boxes is not None and len(boxes) > 0: box_probs = concate([boxes.float(), label.reshape(-1, 1).float(), probs.reshape(-1, 1).float()], axis=1) if len(boxes) > 1: box_probs, keep = self.hard_nms(box_probs, nms_threshold=self.nms_threshold, top_k=-1, ) boxes = box_probs[:, :4] boxes[:, 0::2] *= self._model.input_spec.shape.dims[-1] boxes[:, 1::2] *= self._model.input_spec.shape.dims[-2] boxes[:, :4] /= rescale_scale # boxes = boxes * (1 / scale[0]) return img_orig, to_numpy(boxes), to_numpy(box_probs[:, 4]).astype(np.int32), to_numpy(box_probs[:, 5]) else: return img_orig, None, None, None except: PrintException() else: raise ValueError('the model is not built yet.') def infer_then_draw_single_image(self, img, scale=1): start_time = time.time() rgb_image, boxes, labels, probs = self.infer_single_image(img, scale) if boxes is not None and len(boxes) > 0: boxes = np.round(boxes).astype(np.int32) if boxes.ndim == 1: boxes = np.expand_dims(boxes, 0) if labels.ndim == 0: labels = np.expand_dims(labels, 0) print(img, time.time() - start_time) pillow_img = array2image(rgb_image.copy()) for m in range(len(boxes)): this_box = boxes[m] this_label = labels[m] thiscolor = tuple([int(c) for c in self.palette[int(this_label) - 1][:3]]) print(img, self.class_names[int(this_label) - 1], this_box, probs[m]) pillow_img = plot_bbox(this_box, pillow_img, thiscolor, self.class_names[int(this_label) - 1], line_thickness=2) rgb_image = np.array(pillow_img.copy()) return rgb_image, boxes, labels, probs
[ "trident.data.bbox_common.bbox_giou", "numpy.maximum", "trident.layers.pytorch_activations.softmax", "numpy.argmax", "trident.misc.visualization_utils.generate_palette", "torch.cat", "numpy.clip", "numpy.argsort", "torch.device", "torch.no_grad", "trident.data.bbox_common.xyxy2xywh", "numpy.round", "cv2.cvtColor", "torch.load", "trident.data.bbox_common.xywh2xyxy", "trident.backend.pytorch_backend.Sequential", "torch.exp", "numpy.max", "torch.nn.functional.log_softmax", "inspect.isfunction", "torch.log", "numpy.minimum", "torch.nn.init.xavier_uniform_", "torch.nn.functional.mse_loss", "torch.clamp", "trident.layers.pytorch_activations.Relu", "numpy.delete", "trident.backend.pytorch_backend.to_numpy", "numpy.zeros", "numpy.expand_dims", "trident.backend.pytorch_backend.to_tensor", "time.time", "trident.backend.pillow_backend.image2array", "numpy.array" ]
[((2429, 2464), 'torch.clamp', 'torch.clamp', (['(max_xy - min_xy)'], {'min': '(0)'}), '(max_xy - min_xy, min=0)\n', (2440, 2464), False, 'import torch\n'), ((7013, 7041), 'torch.cat', 'torch.cat', (['[g_cxcy, g_wh]', '(1)'], {}), '([g_cxcy, g_wh], 1)\n', (7022, 7041), False, 'import torch\n'), ((6502, 6517), 'torch.log', 'torch.log', (['g_wh'], {}), '(g_wh)\n', (6511, 6517), False, 'import torch\n'), ((11170, 11213), 'numpy.clip', 'np.clip', (['(right_bottom - left_top)', '(0.0)', 'None'], {}), '(right_bottom - left_top, 0.0, None)\n', (11177, 11213), True, 'import numpy as np\n'), ((11629, 11673), 'numpy.maximum', 'np.maximum', (['boxes0[..., :2]', 'boxes1[..., :2]'], {}), '(boxes0[..., :2], boxes1[..., :2])\n', (11639, 11673), True, 'import numpy as np\n'), ((11705, 11749), 'numpy.minimum', 'np.minimum', (['boxes0[..., 2:]', 'boxes1[..., 2:]'], {}), '(boxes0[..., 2:], boxes1[..., 2:])\n', (11715, 11749), True, 'import numpy as np\n'), ((14178, 14207), 'trident.data.bbox_common.xywh2xyxy', 'xywh2xyxy', (['center_form_priors'], {}), '(center_form_priors)\n', (14187, 14207), False, 'from trident.data.bbox_common import xywh2xyxy, xyxy2xywh, bbox_giou, bbox_giou_numpy\n'), ((18048, 18065), 'trident.backend.pytorch_backend.to_tensor', 'to_tensor', (['priors'], {}), '(priors)\n', (18057, 18065), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((19436, 19492), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['locations', 'target_locations'], {'reduction': '"""sum"""'}), "(locations, target_locations, reduction='sum')\n", (19446, 19492), True, 'import torch.nn.functional as F\n'), ((20199, 20216), 'trident.backend.pytorch_backend.to_tensor', 'to_tensor', (['priors'], {}), '(priors)\n', (20208, 20216), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((21771, 21788), 'trident.backend.pytorch_backend.to_tensor', 'to_tensor', (['priors'], {}), '(priors)\n', (21780, 21788), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((22406, 22429), 'trident.layers.pytorch_activations.softmax', 'softmax', (['confidence', '(-1)'], {}), '(confidence, -1)\n', (22413, 22429), False, 'from trident.layers.pytorch_activations import get_activation, Identity, Relu, softmax\n'), ((28729, 28746), 'trident.backend.pytorch_backend.to_tensor', 'to_tensor', (['priors'], {}), '(priors)\n', (28738, 28746), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((30299, 30359), 'torch.load', 'torch.load', (['model'], {'map_location': '(lambda storage, loc: storage)'}), '(model, map_location=lambda storage, loc: storage)\n', (30309, 30359), False, 'import torch\n'), ((32049, 32074), 'torch.cat', 'torch.cat', (['confidences', '(1)'], {}), '(confidences, 1)\n', (32058, 32074), False, 'import torch\n'), ((32095, 32118), 'torch.cat', 'torch.cat', (['locations', '(1)'], {}), '(locations, 1)\n', (32104, 32118), False, 'import torch\n'), ((35996, 36010), 'numpy.argsort', 'np.argsort', (['y2'], {}), '(y2)\n', (36006, 36010), True, 'import numpy as np\n'), ((40861, 40872), 'time.time', 'time.time', ([], {}), '()\n', (40870, 40872), False, 'import time\n'), ((12213, 12250), 'numpy.expand_dims', 'np.expand_dims', (['center_form_priors', '(0)'], {}), '(center_form_priors, 0)\n', (12227, 12250), True, 'import numpy as np\n'), ((14235, 14262), 'numpy.expand_dims', 'np.expand_dims', (['gt_boxes', '(0)'], {}), '(gt_boxes, 0)\n', (14249, 14262), True, 'import numpy as np\n'), ((14264, 14301), 'numpy.expand_dims', 'np.expand_dims', (['corner_form_priors', '(1)'], {}), '(corner_form_priors, 1)\n', (14278, 14301), True, 'import numpy as np\n'), ((14391, 14411), 'numpy.max', 'np.max', (['ious'], {'axis': '(1)'}), '(ious, axis=1)\n', (14397, 14411), True, 'import numpy as np\n'), ((14413, 14436), 'numpy.argmax', 'np.argmax', (['ious'], {'axis': '(1)'}), '(ious, axis=1)\n', (14422, 14436), True, 'import numpy as np\n'), ((14526, 14546), 'numpy.max', 'np.max', (['ious'], {'axis': '(0)'}), '(ious, axis=0)\n', (14532, 14546), True, 'import numpy as np\n'), ((14548, 14571), 'numpy.argmax', 'np.argmax', (['ious'], {'axis': '(0)'}), '(ious, axis=0)\n', (14557, 14571), True, 'import numpy as np\n'), ((18657, 18672), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (18670, 18672), False, 'import torch\n'), ((18848, 18878), 'numpy.array', 'np.array', (['[0.05, 1, 5, 20, 10]'], {}), '([0.05, 1, 5, 20, 10])\n', (18856, 18878), True, 'import numpy as np\n'), ((20829, 20844), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (20842, 20844), False, 'import torch\n'), ((25081, 25131), 'trident.backend.pytorch_backend.Sequential', 'Sequential', (['backbond[:idxes[-2]]'], {'name': '"""backbond1"""'}), "(backbond[:idxes[-2]], name='backbond1')\n", (25091, 25131), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((25161, 25220), 'trident.backend.pytorch_backend.Sequential', 'Sequential', (['backbond[idxes[-2]:idxes[-1]]'], {'name': '"""backbond2"""'}), "(backbond[idxes[-2]:idxes[-1]], name='backbond2')\n", (25171, 25220), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((25250, 25300), 'trident.backend.pytorch_backend.Sequential', 'Sequential', (['backbond[idxes[-1]:]'], {'name': '"""backbond3"""'}), "(backbond[idxes[-1]:], name='backbond3')\n", (25260, 25300), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((25936, 25942), 'trident.layers.pytorch_activations.Relu', 'Relu', ([], {}), '()\n', (25940, 25942), False, 'from trident.layers.pytorch_activations import get_activation, Identity, Relu, softmax\n'), ((28793, 28834), 'torch.clamp', 'torch.clamp', (['priors', '(0.0)', '(1.0)'], {'out': 'priors'}), '(priors, 0.0, 1.0, out=priors)\n', (28804, 28834), False, 'import torch\n'), ((32228, 32252), 'trident.layers.pytorch_activations.softmax', 'softmax', (['confidences', '(-1)'], {}), '(confidences, -1)\n', (32235, 32252), False, 'from trident.layers.pytorch_activations import get_activation, Identity, Relu, softmax\n'), ((37652, 37677), 'numpy.delete', 'np.delete', (['idxs', 'suppress'], {}), '(idxs, suppress)\n', (37661, 37677), True, 'import numpy as np\n'), ((7774, 7814), 'torch.exp', 'torch.exp', (['(loc[:, :, 2:4] * variances[1])'], {}), '(loc[:, :, 2:4] * variances[1])\n', (7783, 7814), False, 'import torch\n'), ((30243, 30276), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['m.weight'], {}), '(m.weight)\n', (30266, 30276), True, 'import torch.nn as nn\n'), ((38102, 38118), 'trident.backend.pillow_backend.image2array', 'image2array', (['img'], {}), '(img)\n', (38113, 38118), False, 'from trident.backend.pillow_backend import image2array, array2image\n'), ((38813, 38849), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2BGR'], {}), '(img, cv2.COLOR_RGB2BGR)\n', (38825, 38849), False, 'import cv2\n'), ((41109, 41133), 'numpy.expand_dims', 'np.expand_dims', (['boxes', '(0)'], {}), '(boxes, 0)\n', (41123, 41133), True, 'import numpy as np\n'), ((41192, 41217), 'numpy.expand_dims', 'np.expand_dims', (['labels', '(0)'], {}), '(labels, 0)\n', (41206, 41217), True, 'import numpy as np\n'), ((4865, 4890), 'numpy.zeros', 'np.zeros', (['(num_priors, 4)'], {}), '((num_priors, 4))\n', (4873, 4890), True, 'import numpy as np\n'), ((4911, 4931), 'numpy.zeros', 'np.zeros', (['num_priors'], {}), '(num_priors)\n', (4919, 4931), True, 'import numpy as np\n'), ((16449, 16465), 'trident.data.bbox_common.xyxy2xywh', 'xyxy2xywh', (['boxes'], {}), '(boxes)\n', (16458, 16465), False, 'from trident.data.bbox_common import xywh2xyxy, xyxy2xywh, bbox_giou, bbox_giou_numpy\n'), ((18694, 18726), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['confidence'], {'dim': '(2)'}), '(confidence, dim=2)\n', (18707, 18726), True, 'import torch.nn.functional as F\n'), ((20866, 20898), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['confidence'], {'dim': '(2)'}), '(confidence, dim=2)\n', (20879, 20898), True, 'import torch.nn.functional as F\n'), ((39319, 39357), 'trident.misc.visualization_utils.generate_palette', 'generate_palette', (['confidence.shape[-1]'], {}), '(confidence.shape[-1])\n', (39335, 39357), False, 'from trident.misc.visualization_utils import generate_palette, plot_bbox\n'), ((41020, 41035), 'numpy.round', 'np.round', (['boxes'], {}), '(boxes)\n', (41028, 41035), True, 'import numpy as np\n'), ((41241, 41252), 'time.time', 'time.time', ([], {}), '()\n', (41250, 41252), False, 'import time\n'), ((9186, 9211), 'numpy.zeros', 'np.zeros', (['(num_priors, 4)'], {}), '((num_priors, 4))\n', (9194, 9211), True, 'import numpy as np\n'), ((9232, 9252), 'numpy.zeros', 'np.zeros', (['num_priors'], {}), '(num_priors)\n', (9240, 9252), True, 'import numpy as np\n'), ((12525, 12610), 'numpy.clip', 'np.clip', (['(center_form_boxes[..., 2:] / center_form_priors[..., 2:])', '(1e-08)', 'np.inf'], {}), '(center_form_boxes[..., 2:] / center_form_priors[..., 2:], 1e-08, np.inf\n )\n', (12532, 12610), True, 'import numpy as np\n'), ((15829, 15864), 'numpy.zeros', 'np.zeros', (['(self.priors.shape[0], 4)'], {}), '((self.priors.shape[0], 4))\n', (15837, 15864), True, 'import numpy as np\n'), ((15885, 15915), 'numpy.zeros', 'np.zeros', (['self.priors.shape[0]'], {}), '(self.priors.shape[0])\n', (15893, 15915), True, 'import numpy as np\n'), ((16397, 16418), 'trident.backend.pytorch_backend.to_numpy', 'to_numpy', (['self.priors'], {}), '(self.priors)\n', (16405, 16418), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((16533, 16554), 'trident.backend.pytorch_backend.to_numpy', 'to_numpy', (['self.priors'], {}), '(self.priors)\n', (16541, 16554), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((40491, 40506), 'trident.backend.pytorch_backend.to_numpy', 'to_numpy', (['boxes'], {}), '(boxes)\n', (40499, 40506), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((40552, 40577), 'trident.backend.pytorch_backend.to_numpy', 'to_numpy', (['box_probs[:, 5]'], {}), '(box_probs[:, 5])\n', (40560, 40577), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((9751, 9768), 'trident.backend.pytorch_backend.to_tensor', 'to_tensor', (['gt_box'], {}), '(gt_box)\n', (9760, 9768), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((9802, 9821), 'trident.backend.pytorch_backend.to_tensor', 'to_tensor', (['gt_label'], {}), '(gt_label)\n', (9811, 9821), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((10053, 10078), 'numpy.zeros', 'np.zeros', (['(num_priors, 4)'], {}), '((num_priors, 4))\n', (10061, 10078), True, 'import numpy as np\n'), ((10099, 10119), 'numpy.zeros', 'np.zeros', (['num_priors'], {}), '(num_priors)\n', (10107, 10119), True, 'import numpy as np\n'), ((24031, 24047), 'trident.backend.pytorch_backend.to_tensor', 'to_tensor', (['(1e-08)'], {}), '(1e-08)\n', (24040, 24047), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((38344, 38368), 'inspect.isfunction', 'inspect.isfunction', (['func'], {}), '(func)\n', (38362, 38368), False, 'import inspect\n'), ((38980, 39050), 'torch.device', 'torch.device', (["('cuda' if self._model.weights[0].data.is_cuda else 'cpu')"], {}), "('cuda' if self._model.weights[0].data.is_cuda else 'cpu')\n", (38992, 39050), False, 'import torch\n'), ((9964, 9979), 'trident.backend.pytorch_backend.to_numpy', 'to_numpy', (['loc_t'], {}), '(loc_t)\n', (9972, 9979), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((10000, 10016), 'trident.backend.pytorch_backend.to_numpy', 'to_numpy', (['conf_t'], {}), '(conf_t)\n', (10008, 10016), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((38538, 38562), 'inspect.isfunction', 'inspect.isfunction', (['func'], {}), '(func)\n', (38556, 38562), False, 'import inspect\n'), ((40508, 40533), 'trident.backend.pytorch_backend.to_numpy', 'to_numpy', (['box_probs[:, 4]'], {}), '(box_probs[:, 4])\n', (40516, 40533), False, 'from trident.backend.pytorch_backend import to_numpy, to_tensor, Layer, Sequential, ModuleList\n'), ((38932, 38954), 'numpy.expand_dims', 'np.expand_dims', (['img', '(0)'], {}), '(img, 0)\n', (38946, 38954), True, 'import numpy as np\n'), ((23563, 23615), 'trident.data.bbox_common.bbox_giou', 'bbox_giou', (['decode_locations', 'decode_target_locations'], {}), '(decode_locations, decode_target_locations)\n', (23572, 23615), False, 'from trident.data.bbox_common import xywh2xyxy, xyxy2xywh, bbox_giou, bbox_giou_numpy\n')]
import unittest import numpy as np import tensorflow as tf import dlf.core from dlf.evaluators.coco_object_detection import CocoObjectDectectionEvaluator class TestCocoObjectDetectionEvaluator(unittest.TestCase): image_shape = (1024, 1024, 3) def setUp(self): self.evaluator = CocoObjectDectectionEvaluator(per_class=True) def test_evaluation(self): bboxes = np.array( [ [[0.1, 0.1, 0.3, 0.3]], [[0.25, 0.25, 0.3, 0.3]], [[0.75, 0.75, 0.8, 0.8]] ] ) labels = np.array([[1], [1], [2]]) scores = np.array([[1.0], [1.0], [1.0]]) ids = np.array([[0], [1], [2]]) self.evaluator.add_batch(self.image_shape, bboxes, labels, scores, bboxes, labels, ids, None) result = self.evaluator.evaluate() self.assertEqual(result['MSCOCO_Precision/mAP'], 1.0) self.assertEqual(result['MSCOCO_Recall/AR@1'], 1.0)
[ "numpy.array", "dlf.evaluators.coco_object_detection.CocoObjectDectectionEvaluator" ]
[((296, 341), 'dlf.evaluators.coco_object_detection.CocoObjectDectectionEvaluator', 'CocoObjectDectectionEvaluator', ([], {'per_class': '(True)'}), '(per_class=True)\n', (325, 341), False, 'from dlf.evaluators.coco_object_detection import CocoObjectDectectionEvaluator\n'), ((391, 482), 'numpy.array', 'np.array', (['[[[0.1, 0.1, 0.3, 0.3]], [[0.25, 0.25, 0.3, 0.3]], [[0.75, 0.75, 0.8, 0.8]]]'], {}), '([[[0.1, 0.1, 0.3, 0.3]], [[0.25, 0.25, 0.3, 0.3]], [[0.75, 0.75, \n 0.8, 0.8]]])\n', (399, 482), True, 'import numpy as np\n'), ((579, 604), 'numpy.array', 'np.array', (['[[1], [1], [2]]'], {}), '([[1], [1], [2]])\n', (587, 604), True, 'import numpy as np\n'), ((622, 653), 'numpy.array', 'np.array', (['[[1.0], [1.0], [1.0]]'], {}), '([[1.0], [1.0], [1.0]])\n', (630, 653), True, 'import numpy as np\n'), ((668, 693), 'numpy.array', 'np.array', (['[[0], [1], [2]]'], {}), '([[0], [1], [2]])\n', (676, 693), True, 'import numpy as np\n')]
import numpy as np def create_results_values(proxy_evaluation, drift_labels_known, drift_decisions, acc_vector, drift_labels): """ Parameters ---------- proxy_evaluation: Boolean whether proxy evaluation was used drift_labels_known: Boolean whether change detection evaluation is used drift_decisions: Array with booleans for decisions about drift acc_vector: Array with booleans for (in)correct classification of data instance drift_labels: Array with booleans of drift labels Returns the results data, the headers for results and the format of the results ------- """ # Save values for: drift_decisions, acc_vector, drift_labels if proxy_evaluation and drift_labels_known: result_data = np.transpose([drift_decisions, acc_vector, drift_labels]) result_header = "driftDecisions, accVector, driftLabels" result_format = ('%i', '%i', '%i') elif proxy_evaluation: result_data = np.transpose([drift_decisions, acc_vector]) result_header = "driftDecisions, accVector" result_format = ('%i', '%i') elif drift_labels_known: result_data = np.transpose([drift_decisions, drift_labels]) result_header = "driftDecisions, driftLabels" result_format = ('%i', '%i') else: result_data = np.transpose([drift_decisions]) result_header = "driftDecisions" result_format = '%i' return result_data, result_header, result_format
[ "numpy.transpose" ]
[((755, 812), 'numpy.transpose', 'np.transpose', (['[drift_decisions, acc_vector, drift_labels]'], {}), '([drift_decisions, acc_vector, drift_labels])\n', (767, 812), True, 'import numpy as np\n'), ((970, 1013), 'numpy.transpose', 'np.transpose', (['[drift_decisions, acc_vector]'], {}), '([drift_decisions, acc_vector])\n', (982, 1013), True, 'import numpy as np\n'), ((1154, 1199), 'numpy.transpose', 'np.transpose', (['[drift_decisions, drift_labels]'], {}), '([drift_decisions, drift_labels])\n', (1166, 1199), True, 'import numpy as np\n'), ((1323, 1354), 'numpy.transpose', 'np.transpose', (['[drift_decisions]'], {}), '([drift_decisions])\n', (1335, 1354), True, 'import numpy as np\n')]
import operator import numpy as np import pytest import pytz from pandas._libs.tslibs import IncompatibleFrequency import pandas as pd from pandas import Series, date_range import pandas._testing as tm def _permute(obj): return obj.take(np.random.permutation(len(obj))) class TestSeriesFlexArithmetic: @pytest.mark.parametrize( "ts", [ (lambda x: x, lambda x: x * 2, False), (lambda x: x, lambda x: x[::2], False), (lambda x: x, lambda x: 5, True), (lambda x: tm.makeFloatSeries(), lambda x: tm.makeFloatSeries(), True), ], ) @pytest.mark.parametrize( "opname", ["add", "sub", "mul", "floordiv", "truediv", "pow"] ) def test_flex_method_equivalence(self, opname, ts): # check that Series.{opname} behaves like Series.__{opname}__, tser = tm.makeTimeSeries().rename("ts") series = ts[0](tser) other = ts[1](tser) check_reverse = ts[2] op = getattr(Series, opname) alt = getattr(operator, opname) result = op(series, other) expected = alt(series, other) tm.assert_almost_equal(result, expected) if check_reverse: rop = getattr(Series, "r" + opname) result = rop(series, other) expected = alt(other, series) tm.assert_almost_equal(result, expected) def test_flex_method_subclass_metadata_preservation(self, all_arithmetic_operators): # GH 13208 class MySeries(Series): _metadata = ["x"] @property def _constructor(self): return MySeries opname = all_arithmetic_operators op = getattr(Series, opname) m = MySeries([1, 2, 3], name="test") m.x = 42 result = op(m, 1) assert result.x == 42 class TestSeriesArithmetic: # Some of these may end up in tests/arithmetic, but are not yet sorted def test_add_series_with_period_index(self): rng = pd.period_range("1/1/2000", "1/1/2010", freq="A") ts = Series(np.random.randn(len(rng)), index=rng) result = ts + ts[::2] expected = ts + ts expected[1::2] = np.nan tm.assert_series_equal(result, expected) result = ts + _permute(ts[::2]) tm.assert_series_equal(result, expected) msg = "Input has different freq=D from PeriodIndex\\(freq=A-DEC\\)" with pytest.raises(IncompatibleFrequency, match=msg): ts + ts.asfreq("D", how="end") @pytest.mark.parametrize( "target_add,input_value,expected_value", [ ("!", ["hello", "world"], ["hello!", "world!"]), ("m", ["hello", "world"], ["hellom", "worldm"]), ], ) def test_string_addition(self, target_add, input_value, expected_value): # GH28658 - ensure adding 'm' does not raise an error a = Series(input_value) result = a + target_add expected = Series(expected_value) tm.assert_series_equal(result, expected) # ------------------------------------------------------------------ # Comparisons class TestSeriesFlexComparison: def test_comparison_flex_basic(self): left = pd.Series(np.random.randn(10)) right = pd.Series(np.random.randn(10)) tm.assert_series_equal(left.eq(right), left == right) tm.assert_series_equal(left.ne(right), left != right) tm.assert_series_equal(left.le(right), left < right) tm.assert_series_equal(left.lt(right), left <= right) tm.assert_series_equal(left.gt(right), left > right) tm.assert_series_equal(left.ge(right), left >= right) # axis for axis in [0, None, "index"]: tm.assert_series_equal(left.eq(right, axis=axis), left == right) tm.assert_series_equal(left.ne(right, axis=axis), left != right) tm.assert_series_equal(left.le(right, axis=axis), left < right) tm.assert_series_equal(left.lt(right, axis=axis), left <= right) tm.assert_series_equal(left.gt(right, axis=axis), left > right) tm.assert_series_equal(left.ge(right, axis=axis), left >= right) # msg = "No axis named 1 for object type" for op in ["eq", "ne", "le", "le", "gt", "ge"]: with pytest.raises(ValueError, match=msg): getattr(left, op)(right, axis=1) class TestSeriesComparison: def test_comparison_different_length(self): a = Series(["a", "b", "c"]) b = Series(["b", "a"]) with pytest.raises(ValueError): a < b a = Series([1, 2]) b = Series([2, 3, 4]) with pytest.raises(ValueError): a == b @pytest.mark.parametrize("opname", ["eq", "ne", "gt", "lt", "ge", "le"]) def test_ser_flex_cmp_return_dtypes(self, opname): # GH#15115 ser = Series([1, 3, 2], index=range(3)) const = 2 result = getattr(ser, opname)(const).dtypes expected = np.dtype("bool") assert result == expected @pytest.mark.parametrize("opname", ["eq", "ne", "gt", "lt", "ge", "le"]) def test_ser_flex_cmp_return_dtypes_empty(self, opname): # GH#15115 empty Series case ser = Series([1, 3, 2], index=range(3)) empty = ser.iloc[:0] const = 2 result = getattr(empty, opname)(const).dtypes expected = np.dtype("bool") assert result == expected @pytest.mark.parametrize( "op", [operator.eq, operator.ne, operator.le, operator.lt, operator.ge, operator.gt], ) @pytest.mark.parametrize( "names", [(None, None, None), ("foo", "bar", None), ("baz", "baz", "baz")] ) def test_ser_cmp_result_names(self, names, op): # datetime64 dtype dti = pd.date_range("1949-06-07 03:00:00", freq="H", periods=5, name=names[0]) ser = Series(dti).rename(names[1]) result = op(ser, dti) assert result.name == names[2] # datetime64tz dtype dti = dti.tz_localize("US/Central") ser = Series(dti).rename(names[1]) result = op(ser, dti) assert result.name == names[2] # timedelta64 dtype tdi = dti - dti.shift(1) ser = Series(tdi).rename(names[1]) result = op(ser, tdi) assert result.name == names[2] # interval dtype if op in [operator.eq, operator.ne]: # interval dtype comparisons not yet implemented ii = pd.interval_range(start=0, periods=5, name=names[0]) ser = Series(ii).rename(names[1]) result = op(ser, ii) assert result.name == names[2] # categorical if op in [operator.eq, operator.ne]: # categorical dtype comparisons raise for inequalities cidx = tdi.astype("category") ser = Series(cidx).rename(names[1]) result = op(ser, cidx) assert result.name == names[2] # ------------------------------------------------------------------ # Unsorted # These arithmetic tests were previously in other files, eventually # should be parametrized and put into tests.arithmetic class TestTimeSeriesArithmetic: # TODO: De-duplicate with test below def test_series_add_tz_mismatch_converts_to_utc_duplicate(self): rng = date_range("1/1/2011", periods=10, freq="H", tz="US/Eastern") ser = Series(np.random.randn(len(rng)), index=rng) ts_moscow = ser.tz_convert("Europe/Moscow") result = ser + ts_moscow assert result.index.tz is pytz.utc result = ts_moscow + ser assert result.index.tz is pytz.utc def test_series_add_tz_mismatch_converts_to_utc(self): rng = date_range("1/1/2011", periods=100, freq="H", tz="utc") perm = np.random.permutation(100)[:90] ser1 = Series( np.random.randn(90), index=rng.take(perm).tz_convert("US/Eastern") ) perm = np.random.permutation(100)[:90] ser2 = Series( np.random.randn(90), index=rng.take(perm).tz_convert("Europe/Berlin") ) result = ser1 + ser2 uts1 = ser1.tz_convert("utc") uts2 = ser2.tz_convert("utc") expected = uts1 + uts2 assert result.index.tz == pytz.UTC tm.assert_series_equal(result, expected) def test_series_add_aware_naive_raises(self): rng = date_range("1/1/2011", periods=10, freq="H") ser = Series(np.random.randn(len(rng)), index=rng) ser_utc = ser.tz_localize("utc") with pytest.raises(Exception): ser + ser_utc with pytest.raises(Exception): ser_utc + ser def test_datetime_understood(self): # Ensures it doesn't fail to create the right series # reported in issue#16726 series = pd.Series(pd.date_range("2012-01-01", periods=3)) offset = pd.offsets.DateOffset(days=6) result = series - offset expected = pd.Series(pd.to_datetime(["2011-12-26", "2011-12-27", "2011-12-28"])) tm.assert_series_equal(result, expected)
[ "pandas.offsets.DateOffset", "pandas.period_range", "pandas.interval_range", "pandas._testing.assert_almost_equal", "pandas.date_range", "numpy.random.randn", "numpy.dtype", "pandas._testing.assert_series_equal", "pytest.raises", "pandas.to_datetime", "pandas.Series", "pandas._testing.makeFloatSeries", "pandas._testing.makeTimeSeries", "numpy.random.permutation", "pytest.mark.parametrize" ]
[((622, 712), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""opname"""', "['add', 'sub', 'mul', 'floordiv', 'truediv', 'pow']"], {}), "('opname', ['add', 'sub', 'mul', 'floordiv',\n 'truediv', 'pow'])\n", (645, 712), False, 'import pytest\n'), ((2550, 2724), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""target_add,input_value,expected_value"""', "[('!', ['hello', 'world'], ['hello!', 'world!']), ('m', ['hello', 'world'],\n ['hellom', 'worldm'])]"], {}), "('target_add,input_value,expected_value', [('!', [\n 'hello', 'world'], ['hello!', 'world!']), ('m', ['hello', 'world'], [\n 'hellom', 'worldm'])])\n", (2573, 2724), False, 'import pytest\n'), ((4754, 4825), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""opname"""', "['eq', 'ne', 'gt', 'lt', 'ge', 'le']"], {}), "('opname', ['eq', 'ne', 'gt', 'lt', 'ge', 'le'])\n", (4777, 4825), False, 'import pytest\n'), ((5094, 5165), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""opname"""', "['eq', 'ne', 'gt', 'lt', 'ge', 'le']"], {}), "('opname', ['eq', 'ne', 'gt', 'lt', 'ge', 'le'])\n", (5117, 5165), False, 'import pytest\n'), ((5489, 5602), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""op"""', '[operator.eq, operator.ne, operator.le, operator.lt, operator.ge, operator.gt]'], {}), "('op', [operator.eq, operator.ne, operator.le,\n operator.lt, operator.ge, operator.gt])\n", (5512, 5602), False, 'import pytest\n'), ((5627, 5730), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""names"""', "[(None, None, None), ('foo', 'bar', None), ('baz', 'baz', 'baz')]"], {}), "('names', [(None, None, None), ('foo', 'bar', None),\n ('baz', 'baz', 'baz')])\n", (5650, 5730), False, 'import pytest\n'), ((1146, 1186), 'pandas._testing.assert_almost_equal', 'tm.assert_almost_equal', (['result', 'expected'], {}), '(result, expected)\n', (1168, 1186), True, 'import pandas._testing as tm\n'), ((2025, 2074), 'pandas.period_range', 'pd.period_range', (['"""1/1/2000"""', '"""1/1/2010"""'], {'freq': '"""A"""'}), "('1/1/2000', '1/1/2010', freq='A')\n", (2040, 2074), True, 'import pandas as pd\n'), ((2231, 2271), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (2253, 2271), True, 'import pandas._testing as tm\n'), ((2321, 2361), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (2343, 2361), True, 'import pandas._testing as tm\n'), ((2924, 2943), 'pandas.Series', 'Series', (['input_value'], {}), '(input_value)\n', (2930, 2943), False, 'from pandas import Series, date_range\n'), ((2996, 3018), 'pandas.Series', 'Series', (['expected_value'], {}), '(expected_value)\n', (3002, 3018), False, 'from pandas import Series, date_range\n'), ((3027, 3067), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (3049, 3067), True, 'import pandas._testing as tm\n'), ((4518, 4541), 'pandas.Series', 'Series', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (4524, 4541), False, 'from pandas import Series, date_range\n'), ((4554, 4572), 'pandas.Series', 'Series', (["['b', 'a']"], {}), "(['b', 'a'])\n", (4560, 4572), False, 'from pandas import Series, date_range\n'), ((4644, 4658), 'pandas.Series', 'Series', (['[1, 2]'], {}), '([1, 2])\n', (4650, 4658), False, 'from pandas import Series, date_range\n'), ((4671, 4688), 'pandas.Series', 'Series', (['[2, 3, 4]'], {}), '([2, 3, 4])\n', (4677, 4688), False, 'from pandas import Series, date_range\n'), ((5037, 5053), 'numpy.dtype', 'np.dtype', (['"""bool"""'], {}), "('bool')\n", (5045, 5053), True, 'import numpy as np\n'), ((5432, 5448), 'numpy.dtype', 'np.dtype', (['"""bool"""'], {}), "('bool')\n", (5440, 5448), True, 'import numpy as np\n'), ((5834, 5906), 'pandas.date_range', 'pd.date_range', (['"""1949-06-07 03:00:00"""'], {'freq': '"""H"""', 'periods': '(5)', 'name': 'names[0]'}), "('1949-06-07 03:00:00', freq='H', periods=5, name=names[0])\n", (5847, 5906), True, 'import pandas as pd\n'), ((7371, 7432), 'pandas.date_range', 'date_range', (['"""1/1/2011"""'], {'periods': '(10)', 'freq': '"""H"""', 'tz': '"""US/Eastern"""'}), "('1/1/2011', periods=10, freq='H', tz='US/Eastern')\n", (7381, 7432), False, 'from pandas import Series, date_range\n'), ((7773, 7828), 'pandas.date_range', 'date_range', (['"""1/1/2011"""'], {'periods': '(100)', 'freq': '"""H"""', 'tz': '"""utc"""'}), "('1/1/2011', periods=100, freq='H', tz='utc')\n", (7783, 7828), False, 'from pandas import Series, date_range\n'), ((8342, 8382), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (8364, 8382), True, 'import pandas._testing as tm\n'), ((8448, 8492), 'pandas.date_range', 'date_range', (['"""1/1/2011"""'], {'periods': '(10)', 'freq': '"""H"""'}), "('1/1/2011', periods=10, freq='H')\n", (8458, 8492), False, 'from pandas import Series, date_range\n'), ((8946, 8975), 'pandas.offsets.DateOffset', 'pd.offsets.DateOffset', ([], {'days': '(6)'}), '(days=6)\n', (8967, 8975), True, 'import pandas as pd\n'), ((9106, 9146), 'pandas._testing.assert_series_equal', 'tm.assert_series_equal', (['result', 'expected'], {}), '(result, expected)\n', (9128, 9146), True, 'import pandas._testing as tm\n'), ((1355, 1395), 'pandas._testing.assert_almost_equal', 'tm.assert_almost_equal', (['result', 'expected'], {}), '(result, expected)\n', (1377, 1395), True, 'import pandas._testing as tm\n'), ((2452, 2499), 'pytest.raises', 'pytest.raises', (['IncompatibleFrequency'], {'match': 'msg'}), '(IncompatibleFrequency, match=msg)\n', (2465, 2499), False, 'import pytest\n'), ((3254, 3273), 'numpy.random.randn', 'np.random.randn', (['(10)'], {}), '(10)\n', (3269, 3273), True, 'import numpy as np\n'), ((3301, 3320), 'numpy.random.randn', 'np.random.randn', (['(10)'], {}), '(10)\n', (3316, 3320), True, 'import numpy as np\n'), ((4586, 4611), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4599, 4611), False, 'import pytest\n'), ((4702, 4727), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4715, 4727), False, 'import pytest\n'), ((6528, 6580), 'pandas.interval_range', 'pd.interval_range', ([], {'start': '(0)', 'periods': '(5)', 'name': 'names[0]'}), '(start=0, periods=5, name=names[0])\n', (6545, 6580), True, 'import pandas as pd\n'), ((7845, 7871), 'numpy.random.permutation', 'np.random.permutation', (['(100)'], {}), '(100)\n', (7866, 7871), True, 'import numpy as np\n'), ((7912, 7931), 'numpy.random.randn', 'np.random.randn', (['(90)'], {}), '(90)\n', (7927, 7931), True, 'import numpy as np\n'), ((8005, 8031), 'numpy.random.permutation', 'np.random.permutation', (['(100)'], {}), '(100)\n', (8026, 8031), True, 'import numpy as np\n'), ((8072, 8091), 'numpy.random.randn', 'np.random.randn', (['(90)'], {}), '(90)\n', (8087, 8091), True, 'import numpy as np\n'), ((8608, 8632), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (8621, 8632), False, 'import pytest\n'), ((8674, 8698), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (8687, 8698), False, 'import pytest\n'), ((8889, 8927), 'pandas.date_range', 'pd.date_range', (['"""2012-01-01"""'], {'periods': '(3)'}), "('2012-01-01', periods=3)\n", (8902, 8927), True, 'import pandas as pd\n'), ((9038, 9096), 'pandas.to_datetime', 'pd.to_datetime', (["['2011-12-26', '2011-12-27', '2011-12-28']"], {}), "(['2011-12-26', '2011-12-27', '2011-12-28'])\n", (9052, 9096), True, 'import pandas as pd\n'), ((865, 884), 'pandas._testing.makeTimeSeries', 'tm.makeTimeSeries', ([], {}), '()\n', (882, 884), True, 'import pandas._testing as tm\n'), ((4341, 4377), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'msg'}), '(ValueError, match=msg)\n', (4354, 4377), False, 'import pytest\n'), ((5921, 5932), 'pandas.Series', 'Series', (['dti'], {}), '(dti)\n', (5927, 5932), False, 'from pandas import Series, date_range\n'), ((6107, 6118), 'pandas.Series', 'Series', (['dti'], {}), '(dti)\n', (6113, 6118), False, 'from pandas import Series, date_range\n'), ((6281, 6292), 'pandas.Series', 'Series', (['tdi'], {}), '(tdi)\n', (6287, 6292), False, 'from pandas import Series, date_range\n'), ((539, 559), 'pandas._testing.makeFloatSeries', 'tm.makeFloatSeries', ([], {}), '()\n', (557, 559), True, 'import pandas._testing as tm\n'), ((571, 591), 'pandas._testing.makeFloatSeries', 'tm.makeFloatSeries', ([], {}), '()\n', (589, 591), True, 'import pandas._testing as tm\n'), ((6599, 6609), 'pandas.Series', 'Series', (['ii'], {}), '(ii)\n', (6605, 6609), False, 'from pandas import Series, date_range\n'), ((6898, 6910), 'pandas.Series', 'Series', (['cidx'], {}), '(cidx)\n', (6904, 6910), False, 'from pandas import Series, date_range\n')]
import numpy as np import pandas as pd import gzip from PCA import IPCA #DEVICE = "cpu" CHUNK_SIZE = 5 BATCH_SIZE = 5 NUM_COMPONENTS = 2 files = ["tweet_tokens/embeddings/training_embeddings.csv.gz", "tweet_tokens/embeddings/training_embeddings_2.csv.gz"] #PATH = "tweet_tokens/embeddings/day_1/embeddings_day_1_clean_unique_COMPLETE.csv" OUTPUT_PATH = "tweet_tokens/embeddings/test_embeddings_PCA_" + str(NUM_COMPONENTS) + ".csv.gz" ''' def read_text_embeddings(emb_file): if i == 0: f = open(path, 'r') text_embeddings = np.genfromtxt(emb_file, delimiter=",", skip_header=1, usecols=range(1,768), max_rows=100000) return text_embeddings ''' def write_header(): output_file = gzip.open(OUTPUT_PATH, "wt") output_file.write("tweet_features_tweet_id") for i in range(0, NUM_COMPONENTS): output_file.write(',embedding_' + str(i)) output_file.write('\n') output_file.close() def write_to_csv(df, embeddings): output_file = gzip.open(OUTPUT_PATH, "at") for i, row in enumerate(df.itertuples(index=False)): output_file.write(str(row[0])) # get the tweet id for j in range(0, NUM_COMPONENTS): output_file.write(',' + str(embeddings[i][j])) output_file.write('\n') output_file.close() if __name__ == "__main__": inc_pca = IPCA(num_components=NUM_COMPONENTS) # incremental training phase print('\nTRAINING\n') i = 0 for f in files: #print(f) for chunk in pd.read_csv(f, usecols=range(1,769), chunksize=CHUNK_SIZE, compression='gzip', nrows=10): #print(chunk) print("Chunk :", i) text_embeddings = np.array(chunk.values, dtype=np.float32) print("Training set :", text_embeddings.shape) #del chunk i += 1 transformed_embeddings = inc_pca.fit(text_embeddings, batch_size=BATCH_SIZE) #transformed_embeddings, reconstructed_embeddings, loss = inc_pca.fit_transform(text_embeddings, batch_size=BATCH_SIZE, with_loss=True) #print("Transformed embeddings : ", transformed_embeddings.shape) #print("Reconstructed embeddings : ", reconstructed_embeddings.shape) #print("\nPCA projection loss :", loss, "\n") # produce embeddings with reduced dimensionality print('\nPRODUCING REDUCED EMBEDDINGS\n') write_header() # column names i = 0 for f in files: for chunk in pd.read_csv(f, chunksize=CHUNK_SIZE, compression='gzip', nrows=10): #print(chunk) print("Chunk :", i) text_embeddings = np.array(chunk.iloc[:,1:769].values, dtype=np.float32) i += 1 transformed_embeddings = inc_pca.transform(text_embeddings) #print("Transformed embeddings : ", transformed_embeddings.shape) write_to_csv(chunk, transformed_embeddings) #emb_file.close()
[ "pandas.read_csv", "PCA.IPCA", "gzip.open", "numpy.array" ]
[((724, 752), 'gzip.open', 'gzip.open', (['OUTPUT_PATH', '"""wt"""'], {}), "(OUTPUT_PATH, 'wt')\n", (733, 752), False, 'import gzip\n'), ((1005, 1033), 'gzip.open', 'gzip.open', (['OUTPUT_PATH', '"""at"""'], {}), "(OUTPUT_PATH, 'at')\n", (1014, 1033), False, 'import gzip\n'), ((1351, 1386), 'PCA.IPCA', 'IPCA', ([], {'num_components': 'NUM_COMPONENTS'}), '(num_components=NUM_COMPONENTS)\n', (1355, 1386), False, 'from PCA import IPCA\n'), ((2497, 2563), 'pandas.read_csv', 'pd.read_csv', (['f'], {'chunksize': 'CHUNK_SIZE', 'compression': '"""gzip"""', 'nrows': '(10)'}), "(f, chunksize=CHUNK_SIZE, compression='gzip', nrows=10)\n", (2508, 2563), True, 'import pandas as pd\n'), ((1698, 1738), 'numpy.array', 'np.array', (['chunk.values'], {'dtype': 'np.float32'}), '(chunk.values, dtype=np.float32)\n', (1706, 1738), True, 'import numpy as np\n'), ((2653, 2708), 'numpy.array', 'np.array', (['chunk.iloc[:, 1:769].values'], {'dtype': 'np.float32'}), '(chunk.iloc[:, 1:769].values, dtype=np.float32)\n', (2661, 2708), True, 'import numpy as np\n')]
from typing import List, Tuple, NoReturn, Optional, Union import numpy as np from auto_editor.utils.log import Log from auto_editor.utils.types import split_num_str def combine_audio_motion( audio_list: np.ndarray, motion_list: np.ndarray, based: str, log: Log ) -> Optional[np.ndarray]: no_place_where = "There was no place where {} exceeded the threshold." if (based == 'audio' or based == 'not_audio') and max(audio_list) == 0: log.error(no_place_where.format('audio')) if (based == 'motion' or based == 'not_motion') and max(motion_list) == 0: log.error(no_place_where.format('motion')) if audio_list is not None and max(audio_list) == 0: log.warning(no_place_where.format('audio')) if motion_list is not None and max(motion_list) == 0: log.warning(no_place_where.format('motion')) if based == 'audio': return audio_list if based == 'motion': return motion_list if based == 'not_audio': return np.invert(audio_list) if based == 'not_motion': return np.invert(motion_list) if based == 'audio_and_motion': return audio_list & motion_list if based == 'audio_or_motion': return audio_list | motion_list if based == 'audio_xor_motion': return np.bitwise_xor(audio_list, motion_list) if based == 'audio_and_not_motion': return audio_list & np.invert(motion_list) if based == 'not_audio_and_motion': return np.invert(audio_list) & motion_list if based == 'not_audio_and_not_motion': return np.invert(audio_list) & np.invert(motion_list) return None def remove_small(has_loud: np.ndarray, lim: int, replace: int, with_: int) -> np.ndarray: startP = 0 active = False for j, item in enumerate(has_loud): if item == replace: if not active: startP = j active = True # Special case for end. if j == len(has_loud) - 1: if j - startP < lim: has_loud[startP:j+1] = with_ else: if active: if j - startP < lim: has_loud[startP:j] = with_ active = False return has_loud def str_is_number(val: str) -> bool: return val.replace('.', '', 1).replace('-', '', 1).isdigit() def str_starts_with_number(val: str) -> bool: if val.startswith('-'): val = val[1:] val = val.replace('.', '', 1) return val[0].isdigit() def set_range( has_loud: np.ndarray, range_syntax: list, fps: float, with_: int, log: Log ) -> np.ndarray: def replace_variables_to_values(val: str, fps: float, log: Log) -> Union[int, NoReturn]: if str_is_number(val): return int(val) if str_starts_with_number(val): try: value, unit = split_num_str(val) except TypeError as e: log.error(str(e)) if unit in ('', 'f', 'frame', 'frames'): if isinstance(value, float): log.error('float type cannot be used with frame unit') return int(value) if unit in ('s', 'sec', 'secs', 'second', 'seconds'): return round(value * fps) log.error(f'Unknown unit: {unit}') if val == 'start': return 0 if val == 'end': return len(has_loud) return log.error(f"variable '{val}' not available.") def var_val_to_frames(val: str, fps: float, log: Log) -> int: num = replace_variables_to_values(val, fps, log) if num < 0: num += len(has_loud) return num for item in range_syntax: pair = [] for val in item: pair.append(var_val_to_frames(val, fps, log)) has_loud[pair[0]:pair[1]] = with_ return has_loud def seconds_to_frames(value: Union[int, str], fps: float) -> int: if isinstance(value, str): return int(float(value) * fps) return value def cook(has_loud: np.ndarray, min_clip: int, min_cut: int) -> np.ndarray: has_loud = remove_small(has_loud, min_clip, replace=1, with_=0) has_loud = remove_small(has_loud, min_cut, replace=0, with_=1) return has_loud # Turn long silent/loud array to formatted chunk list. # Example: [1, 1, 1, 2, 2] => [(0, 3, 1), (3, 5, 2)] def chunkify(arr: np.ndarray, arr_length: int = None) -> List[Tuple[int, int, float]]: if arr_length is None: arr_length = len(arr) chunks = [] start = 0 for j in range(1, arr_length): if arr[j] != arr[j - 1]: chunks.append((start, j, arr[j - 1])) start = j chunks.append((start, arr_length, arr[j])) return chunks def apply_margin( has_loud: np.ndarray, has_loud_length: int, start_m: int, end_m: int ) -> np.ndarray: # Find start and end indexes. start_index = [] end_index = [] for j in range(1, has_loud_length): if has_loud[j] != has_loud[j - 1]: if has_loud[j]: start_index.append(j) else: end_index.append(j) # Apply margin if start_m > 0: for i in start_index: has_loud[max(i-start_m, 0):i] = True if start_m < 0: for i in start_index: has_loud[i:min(i-start_m, has_loud_length)] = False if end_m > 0: for i in end_index: has_loud[i:min(i+end_m, has_loud_length)] = True if end_m < 0: for i in end_index: has_loud[max(i+end_m, 0):i] = False return has_loud def apply_mark_as( has_loud: np.ndarray, has_loud_length: int, fps: float, args, log: Log ) -> np.ndarray: if args.mark_as_loud != []: has_loud = set_range(has_loud, args.mark_as_loud, fps, args.video_speed, log) if args.mark_as_silent != []: has_loud = set_range(has_loud, args.mark_as_silent, fps, args.silent_speed, log) return has_loud def to_speed_list( has_loud: np.ndarray, video_speed: float, silent_speed: float ) -> np.ndarray: speed_list = has_loud.astype(float) # This code will break is speed is allowed to be 0 speed_list[speed_list == 1] = video_speed speed_list[speed_list == 0] = silent_speed return speed_list def merge(start_list: np.ndarray, end_list: np.ndarray) -> np.ndarray: merge = np.zeros((len(start_list)), dtype=np.bool_) startP = 0 for item in start_list: if item == True: where_list = np.where(end_list[startP:])[0] if len(where_list) > 0: merge[startP:where_list[0]] = True startP += 1 return merge
[ "numpy.bitwise_xor", "numpy.where", "auto_editor.utils.types.split_num_str", "numpy.invert" ]
[((1005, 1026), 'numpy.invert', 'np.invert', (['audio_list'], {}), '(audio_list)\n', (1014, 1026), True, 'import numpy as np\n'), ((1073, 1095), 'numpy.invert', 'np.invert', (['motion_list'], {}), '(motion_list)\n', (1082, 1095), True, 'import numpy as np\n'), ((1301, 1340), 'numpy.bitwise_xor', 'np.bitwise_xor', (['audio_list', 'motion_list'], {}), '(audio_list, motion_list)\n', (1315, 1340), True, 'import numpy as np\n'), ((1410, 1432), 'numpy.invert', 'np.invert', (['motion_list'], {}), '(motion_list)\n', (1419, 1432), True, 'import numpy as np\n'), ((1489, 1510), 'numpy.invert', 'np.invert', (['audio_list'], {}), '(audio_list)\n', (1498, 1510), True, 'import numpy as np\n'), ((1585, 1606), 'numpy.invert', 'np.invert', (['audio_list'], {}), '(audio_list)\n', (1594, 1606), True, 'import numpy as np\n'), ((1609, 1631), 'numpy.invert', 'np.invert', (['motion_list'], {}), '(motion_list)\n', (1618, 1631), True, 'import numpy as np\n'), ((2880, 2898), 'auto_editor.utils.types.split_num_str', 'split_num_str', (['val'], {}), '(val)\n', (2893, 2898), False, 'from auto_editor.utils.types import split_num_str\n'), ((6537, 6564), 'numpy.where', 'np.where', (['end_list[startP:]'], {}), '(end_list[startP:])\n', (6545, 6564), True, 'import numpy as np\n')]
"""End to end testing on simple linear models""" # pylint: disable=C0103 # pylint: disable=C0325 # pylint: disable=E1101 import numpy as np from scipy.stats import zscore from sklearn.linear_model import LogisticRegression as sk_LogisticRegression from sklearn.linear_model import LinearRegression as sk_LinearRegression from model_wrangler.model_wrangler import ModelWrangler from model_wrangler.dataset_managers import DatasetManager from model_wrangler.model.corral.linear_regression import LinearRegressionModel from model_wrangler.model.corral.logistic_regression import LogisticRegressionModel from model_wrangler.model.tester import ModelTester LINEAR_PARAMS = { 'name': 'test_lin', 'path': './tests/test_lin', 'graph': { 'in_sizes': [12], 'out_sizes': [1], } } LOGISTIC_PARAMS = { 'name': 'test_log', 'path': './tests/test_log', 'graph': { 'in_sizes': [12], 'out_sizes': [1], } } def make_linear_reg_testdata(in_dim=2, n_samp=1000): """Make sample data for linear regression""" signal = zscore(np.random.randn(n_samp, 1), axis=0) X = zscore(np.random.randn(n_samp, in_dim), axis=0) X += 0.2 * signal X = zscore(X, axis=0) y = signal + 100 return X, y def make_linear_cls_testdata(in_dim=2, n_samp=1000): """Make sample data for logistic regression""" signal = zscore(np.random.randn(n_samp, 1), axis=0) X = zscore(np.random.randn(n_samp, in_dim), axis=0) X += 0.2 * signal X = zscore(X, axis=0) y = (signal > 0).astype(int) return X, y def compare_scikt_and_tf(sk_model, tf_model, X, y, sk_params={}): sk_model = sk_model.fit(X, y.ravel()) print('Scikit values:') print('\t coef: {}'.format(sk_model.coef_.ravel())) print('\t int: {}'.format(sk_model.intercept_.ravel())) dm1 = DatasetManager([X], [y]) dm2 = DatasetManager([X], [y]) tf_model.add_data(dm1, dm2) print('TF training:') print('\tpre-score: {}'.format(tf_model.score([X], [y]))) tf_model.train() print('\tpost-score: {}'.format(tf_model.score([X], [y]))) print('TF values:') data_dict = tf_model.make_data_dict([X], [y], is_training=False) tf_coef = tf_model.get_from_model('params/coeff_0', data_dict) tf_int = tf_model.get_from_model('params/intercept_0', data_dict) print('\t coef: {}'.format(tf_coef.ravel())) print('\t int: {}'.format(tf_int.ravel())) try: corr = np.mean( zscore(tf_model.predict([X])[0].ravel()) * zscore(sk_model.predict_proba(X)[:, 1].ravel()) ) except AttributeError: corr = np.mean( zscore(tf_model.predict([X])[0].ravel()) * zscore(sk_model.predict(X).ravel()) ) print('Model Correlation') print('\tr = {:.2f}'.format(corr)) def test_linear_regr(): """Compare tf linear regression to scikit learn""" X, y = make_linear_reg_testdata(in_dim=LINEAR_PARAMS['graph']['in_sizes'][0]) compare_scikt_and_tf( sk_LinearRegression(), ModelWrangler(LinearRegressionModel, LINEAR_PARAMS), X, y) def test_logistic_regr(): """Compare tf logistic regression to scikit learn""" X, y = make_linear_cls_testdata(in_dim=LOGISTIC_PARAMS['graph']['in_sizes'][0]) compare_scikt_and_tf( sk_LogisticRegression(**{'penalty':'l2', 'C':100.0}), ModelWrangler(LogisticRegressionModel, LOGISTIC_PARAMS), X, y) if __name__ == "__main__": print("\n\nunit testing linear regression") ModelTester( ModelWrangler(LinearRegressionModel, LINEAR_PARAMS) ) print("\n\ne2e testing linear regression") test_linear_regr() print("\n\nunit testing logistic regression") ModelTester( ModelWrangler(LogisticRegressionModel, LOGISTIC_PARAMS) ) print("\n\ne2e testing logistic regression") test_logistic_regr()
[ "scipy.stats.zscore", "numpy.random.randn", "model_wrangler.dataset_managers.DatasetManager", "sklearn.linear_model.LinearRegression", "sklearn.linear_model.LogisticRegression", "model_wrangler.model_wrangler.ModelWrangler" ]
[((1212, 1229), 'scipy.stats.zscore', 'zscore', (['X'], {'axis': '(0)'}), '(X, axis=0)\n', (1218, 1229), False, 'from scipy.stats import zscore\n'), ((1515, 1532), 'scipy.stats.zscore', 'zscore', (['X'], {'axis': '(0)'}), '(X, axis=0)\n', (1521, 1532), False, 'from scipy.stats import zscore\n'), ((1848, 1872), 'model_wrangler.dataset_managers.DatasetManager', 'DatasetManager', (['[X]', '[y]'], {}), '([X], [y])\n', (1862, 1872), False, 'from model_wrangler.dataset_managers import DatasetManager\n'), ((1883, 1907), 'model_wrangler.dataset_managers.DatasetManager', 'DatasetManager', (['[X]', '[y]'], {}), '([X], [y])\n', (1897, 1907), False, 'from model_wrangler.dataset_managers import DatasetManager\n'), ((1089, 1115), 'numpy.random.randn', 'np.random.randn', (['n_samp', '(1)'], {}), '(n_samp, 1)\n', (1104, 1115), True, 'import numpy as np\n'), ((1141, 1172), 'numpy.random.randn', 'np.random.randn', (['n_samp', 'in_dim'], {}), '(n_samp, in_dim)\n', (1156, 1172), True, 'import numpy as np\n'), ((1393, 1419), 'numpy.random.randn', 'np.random.randn', (['n_samp', '(1)'], {}), '(n_samp, 1)\n', (1408, 1419), True, 'import numpy as np\n'), ((1444, 1475), 'numpy.random.randn', 'np.random.randn', (['n_samp', 'in_dim'], {}), '(n_samp, in_dim)\n', (1459, 1475), True, 'import numpy as np\n'), ((3034, 3055), 'sklearn.linear_model.LinearRegression', 'sk_LinearRegression', ([], {}), '()\n', (3053, 3055), True, 'from sklearn.linear_model import LinearRegression as sk_LinearRegression\n'), ((3065, 3116), 'model_wrangler.model_wrangler.ModelWrangler', 'ModelWrangler', (['LinearRegressionModel', 'LINEAR_PARAMS'], {}), '(LinearRegressionModel, LINEAR_PARAMS)\n', (3078, 3116), False, 'from model_wrangler.model_wrangler import ModelWrangler\n'), ((3336, 3390), 'sklearn.linear_model.LogisticRegression', 'sk_LogisticRegression', ([], {}), "(**{'penalty': 'l2', 'C': 100.0})\n", (3357, 3390), True, 'from sklearn.linear_model import LogisticRegression as sk_LogisticRegression\n'), ((3398, 3453), 'model_wrangler.model_wrangler.ModelWrangler', 'ModelWrangler', (['LogisticRegressionModel', 'LOGISTIC_PARAMS'], {}), '(LogisticRegressionModel, LOGISTIC_PARAMS)\n', (3411, 3453), False, 'from model_wrangler.model_wrangler import ModelWrangler\n'), ((3571, 3622), 'model_wrangler.model_wrangler.ModelWrangler', 'ModelWrangler', (['LinearRegressionModel', 'LINEAR_PARAMS'], {}), '(LinearRegressionModel, LINEAR_PARAMS)\n', (3584, 3622), False, 'from model_wrangler.model_wrangler import ModelWrangler\n'), ((3776, 3831), 'model_wrangler.model_wrangler.ModelWrangler', 'ModelWrangler', (['LogisticRegressionModel', 'LOGISTIC_PARAMS'], {}), '(LogisticRegressionModel, LOGISTIC_PARAMS)\n', (3789, 3831), False, 'from model_wrangler.model_wrangler import ModelWrangler\n')]
from functools import wraps from random import random, seed, sample import numpy as np import pandas as pd import datetime import time import Code.method_collector as mc import Code.create_collector as cc import cv2 def to_categorical_unit(target, nb_class): categorical = np.zeros([1, int(nb_class)]) categorical[1, int(target)] = 1 return categorical def from_categorical(target): NotImplemented return target def to_categorical(target, nb_class): categorical = np.zeros([len(target), nb_class]) for idx in range(len(target)): categorical[idx, int(target[idx])] = 1 return categorical def chosen_method(param, comb, datasets): if param.datatype == "disease": return method_collect(param, comb, datasets) elif param.datatype == "type": return method_collect(param, comb, datasets) def feature_add(param, datasets): data1, data2, data3 = datasets plabel = data1[:, -2] tlabel = data1[:, -1] # dataset index data1 = data1[:, :-2] data2 = data2[:, :-2] data3 = data3[:, :-2] nb_class = int(max(tlabel)) + 1 nb_people = int(max(plabel)) + 1 unit_step = cc.get_unit_step(data1) cc.get_index_sampling(param, data1, step_index=unit_step) def method_collect(param, comb, datasets): if param.method == "Sn": """ sampling data : [train_list, trainp, trainc, test_list, testp, testc] """ return mc.method_sn(param, comb, datasets) elif param.method == "base": return mc.method_base(param, comb, datasets) elif param.method == "LeaveOne": return mc.method_leaveone(param, comb, datasets) elif param.method == "SelectLeaveOne": return mc.method_sleaveone(param, comb, datasets) elif param.method == "Feature_Added_LeaveOne": return mc.method_fa_leaveone(param, comb, datasets) elif param.method == "mdpi": return mc.method_mdpi(param, comb, datasets) elif param.method == "dhalf": return mc.method_dhalf(param, comb, datasets) elif param.method == "half": return mc.method_half(param, comb, datasets) elif param.method == "MCCV": return mc.method_MCCV(param, comb, datasets) elif param.method == "7CV" or param.method == "MCCV": return mc.method_CV(param, comb, datasets) # sort people number def sort_by_people(datasets): output_list = list() for data in datasets: row = data.shape[0] nb_people = int(max(data[:, -2])) + 1 output = np.array([]) for pn in range(nb_people): temp = np.array([]) state = False if not max(data[:, -2] == pn): # if max(data[:, -2] == pn) == False: continue for r in range(row): if int(data[r, -2]) == pn and state is False: temp = data[r, :] state = True continue elif int(data[r, -2]) == pn and state is True: temp = np.vstack([temp, data[r, :]]) if pn == 0: output = temp else: output = np.vstack([output, temp]) output_list.append(output) return output_list # Delete Dataset for Binary Classification def del_subject(param, datasets, target): fired = list() for dataset in datasets: drow, dcol = dataset.shape dataset = dataset[dataset[:, -1] != param.collect["category"][target]] fired.append(dataset) return fired def normalize_all_of_length(param, datasets): print("normalize") min_length = 0 data_column = param.collect["csv_columns_names"]["datasets"] pressure_column = param.collect["csv_columns_names"]["pressure"] acc_column = param.collect["csv_columns_names"]["acc"] gyro_column = param.collect["csv_columns_names"]["gyro"] for key, data_paths in datasets.items(): for path in data_paths: data = pd.read_csv(filepath_or_buffer=path, names=data_column, header=None, skiprows=1, encoding='utf7') row, col = data.to_numpy().shape if min_length == 0: min_length = row elif min_length > row and row > 10000: min_length = row init_state = True for key, data_paths in datasets.items(): for i, path in enumerate(data_paths): peo_num = np.full([min_length, 1], int(path.split('/')[-1].split('_')[0])) type_num = np.full([min_length, 1], int(key)) data = pd.read_csv(filepath_or_buffer=path, names=data_column, header=None, skiprows=1, encoding='utf7') target = np.array(data[pressure_column].to_numpy(), dtype='float32') pressure = cv2.resize(src=target, dsize=(target.shape[1], min_length), interpolation=cv2.INTER_CUBIC) target = np.array(data[acc_column].to_numpy(), dtype='float32') acc = cv2.resize(src=target, dsize=(target.shape[1], min_length), interpolation=cv2.INTER_CUBIC) target = np.array(data[gyro_column].to_numpy(), dtype='float32') gyro = cv2.resize(src=target, dsize=(target.shape[1], min_length), interpolation=cv2.INTER_CUBIC) if init_state is True: pressure_collect = pressure acc_collect = acc gyro_collect = gyro peo_collect = peo_num type_collect = type_num init_state = False else: pressure_collect = np.vstack([pressure_collect, pressure]) acc_collect = np.vstack([acc_collect, acc]) gyro_collect = np.vstack([gyro_collect, gyro]) peo_collect = np.vstack([peo_collect, peo_num]) type_collect = np.vstack([type_collect, type_num]) return [np.hstack([pressure_collect, peo_collect, type_collect]), np.hstack([acc_collect, peo_collect, type_collect]), np.hstack([gyro_collect, peo_collect, type_collect])]
[ "Code.method_collector.method_fa_leaveone", "Code.method_collector.method_sleaveone", "pandas.read_csv", "Code.method_collector.method_mdpi", "Code.method_collector.method_dhalf", "Code.method_collector.method_half", "Code.method_collector.method_CV", "Code.create_collector.get_unit_step", "numpy.hstack", "Code.method_collector.method_sn", "Code.method_collector.method_MCCV", "numpy.array", "Code.create_collector.get_index_sampling", "Code.method_collector.method_leaveone", "numpy.vstack", "Code.method_collector.method_base", "cv2.resize" ]
[((1168, 1191), 'Code.create_collector.get_unit_step', 'cc.get_unit_step', (['data1'], {}), '(data1)\n', (1184, 1191), True, 'import Code.create_collector as cc\n'), ((1196, 1253), 'Code.create_collector.get_index_sampling', 'cc.get_index_sampling', (['param', 'data1'], {'step_index': 'unit_step'}), '(param, data1, step_index=unit_step)\n', (1217, 1253), True, 'import Code.create_collector as cc\n'), ((1449, 1484), 'Code.method_collector.method_sn', 'mc.method_sn', (['param', 'comb', 'datasets'], {}), '(param, comb, datasets)\n', (1461, 1484), True, 'import Code.method_collector as mc\n'), ((2527, 2539), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2535, 2539), True, 'import numpy as np\n'), ((5852, 5908), 'numpy.hstack', 'np.hstack', (['[pressure_collect, peo_collect, type_collect]'], {}), '([pressure_collect, peo_collect, type_collect])\n', (5861, 5908), True, 'import numpy as np\n'), ((5922, 5973), 'numpy.hstack', 'np.hstack', (['[acc_collect, peo_collect, type_collect]'], {}), '([acc_collect, peo_collect, type_collect])\n', (5931, 5973), True, 'import numpy as np\n'), ((5975, 6027), 'numpy.hstack', 'np.hstack', (['[gyro_collect, peo_collect, type_collect]'], {}), '([gyro_collect, peo_collect, type_collect])\n', (5984, 6027), True, 'import numpy as np\n'), ((1533, 1570), 'Code.method_collector.method_base', 'mc.method_base', (['param', 'comb', 'datasets'], {}), '(param, comb, datasets)\n', (1547, 1570), True, 'import Code.method_collector as mc\n'), ((2595, 2607), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2603, 2607), True, 'import numpy as np\n'), ((3991, 4092), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': 'path', 'names': 'data_column', 'header': 'None', 'skiprows': '(1)', 'encoding': '"""utf7"""'}), "(filepath_or_buffer=path, names=data_column, header=None,\n skiprows=1, encoding='utf7')\n", (4002, 4092), True, 'import pandas as pd\n'), ((4562, 4663), 'pandas.read_csv', 'pd.read_csv', ([], {'filepath_or_buffer': 'path', 'names': 'data_column', 'header': 'None', 'skiprows': '(1)', 'encoding': '"""utf7"""'}), "(filepath_or_buffer=path, names=data_column, header=None,\n skiprows=1, encoding='utf7')\n", (4573, 4663), True, 'import pandas as pd\n'), ((4764, 4859), 'cv2.resize', 'cv2.resize', ([], {'src': 'target', 'dsize': '(target.shape[1], min_length)', 'interpolation': 'cv2.INTER_CUBIC'}), '(src=target, dsize=(target.shape[1], min_length), interpolation=\n cv2.INTER_CUBIC)\n', (4774, 4859), False, 'import cv2\n'), ((4950, 5045), 'cv2.resize', 'cv2.resize', ([], {'src': 'target', 'dsize': '(target.shape[1], min_length)', 'interpolation': 'cv2.INTER_CUBIC'}), '(src=target, dsize=(target.shape[1], min_length), interpolation=\n cv2.INTER_CUBIC)\n', (4960, 5045), False, 'import cv2\n'), ((5138, 5233), 'cv2.resize', 'cv2.resize', ([], {'src': 'target', 'dsize': '(target.shape[1], min_length)', 'interpolation': 'cv2.INTER_CUBIC'}), '(src=target, dsize=(target.shape[1], min_length), interpolation=\n cv2.INTER_CUBIC)\n', (5148, 5233), False, 'import cv2\n'), ((1623, 1664), 'Code.method_collector.method_leaveone', 'mc.method_leaveone', (['param', 'comb', 'datasets'], {}), '(param, comb, datasets)\n', (1641, 1664), True, 'import Code.method_collector as mc\n'), ((3168, 3193), 'numpy.vstack', 'np.vstack', (['[output, temp]'], {}), '([output, temp])\n', (3177, 3193), True, 'import numpy as np\n'), ((5545, 5584), 'numpy.vstack', 'np.vstack', (['[pressure_collect, pressure]'], {}), '([pressure_collect, pressure])\n', (5554, 5584), True, 'import numpy as np\n'), ((5615, 5644), 'numpy.vstack', 'np.vstack', (['[acc_collect, acc]'], {}), '([acc_collect, acc])\n', (5624, 5644), True, 'import numpy as np\n'), ((5676, 5707), 'numpy.vstack', 'np.vstack', (['[gyro_collect, gyro]'], {}), '([gyro_collect, gyro])\n', (5685, 5707), True, 'import numpy as np\n'), ((5738, 5771), 'numpy.vstack', 'np.vstack', (['[peo_collect, peo_num]'], {}), '([peo_collect, peo_num])\n', (5747, 5771), True, 'import numpy as np\n'), ((5803, 5838), 'numpy.vstack', 'np.vstack', (['[type_collect, type_num]'], {}), '([type_collect, type_num])\n', (5812, 5838), True, 'import numpy as np\n'), ((1723, 1765), 'Code.method_collector.method_sleaveone', 'mc.method_sleaveone', (['param', 'comb', 'datasets'], {}), '(param, comb, datasets)\n', (1742, 1765), True, 'import Code.method_collector as mc\n'), ((1832, 1876), 'Code.method_collector.method_fa_leaveone', 'mc.method_fa_leaveone', (['param', 'comb', 'datasets'], {}), '(param, comb, datasets)\n', (1853, 1876), True, 'import Code.method_collector as mc\n'), ((3041, 3070), 'numpy.vstack', 'np.vstack', (['[temp, data[r, :]]'], {}), '([temp, data[r, :]])\n', (3050, 3070), True, 'import numpy as np\n'), ((1925, 1962), 'Code.method_collector.method_mdpi', 'mc.method_mdpi', (['param', 'comb', 'datasets'], {}), '(param, comb, datasets)\n', (1939, 1962), True, 'import Code.method_collector as mc\n'), ((2012, 2050), 'Code.method_collector.method_dhalf', 'mc.method_dhalf', (['param', 'comb', 'datasets'], {}), '(param, comb, datasets)\n', (2027, 2050), True, 'import Code.method_collector as mc\n'), ((2099, 2136), 'Code.method_collector.method_half', 'mc.method_half', (['param', 'comb', 'datasets'], {}), '(param, comb, datasets)\n', (2113, 2136), True, 'import Code.method_collector as mc\n'), ((2185, 2222), 'Code.method_collector.method_MCCV', 'mc.method_MCCV', (['param', 'comb', 'datasets'], {}), '(param, comb, datasets)\n', (2199, 2222), True, 'import Code.method_collector as mc\n'), ((2296, 2331), 'Code.method_collector.method_CV', 'mc.method_CV', (['param', 'comb', 'datasets'], {}), '(param, comb, datasets)\n', (2308, 2331), True, 'import Code.method_collector as mc\n')]
""" Test benches for the computational efficiency of toolbox routines. """ import time import unittest import numpy as np import pyinduct as pi from pyinduct.tests.test_core import CalculateScalarProductMatrixTestCase def simulation_benchmark(spat_domain, settings): """ This benchmark covers a typical simulation. Args: spat_domain (:py:class:`.Domain`): spatial domain for the simulation settings (dict): settings to use for simulation run Returns: timings """ sys_name = 'transport system' v = 10 temp_domain = pi.Domain(bounds=(0, 5), num=100) init_x = pi.Function(lambda z: 0) _a = time.clock() nodes = pi.Domain(settings["bounds"], settings["num"]) cls = settings.get("shapefunction_class") base = cls.cure_interval(nodes, **settings) _b = time.clock() func_label = 'base' pi.register_base(func_label, base) u = pi.SimulationInputSum([ pi.SignalGenerator('square', temp_domain.points, frequency=0.3, scale=2, offset=4, phase_shift=1), ]) _c = time.clock() weak_form = pi.WeakFormulation([ pi.IntegralTerm(pi.Product( pi.FieldVariable(func_label, order=(1, 0)), pi.TestFunction(func_label)), spat_domain.bounds), pi.IntegralTerm(pi.Product( pi.FieldVariable(func_label), pi.TestFunction(func_label, order=1)), spat_domain.bounds, scale=-v), pi.ScalarTerm(pi.Product( pi.FieldVariable(func_label, location=spat_domain.bounds[-1]), pi.TestFunction(func_label, location=spat_domain.bounds[-1])), scale=v), pi.ScalarTerm(pi.Product( pi.Input(u), pi.TestFunction(func_label, location=0)), scale=-v), ], name=sys_name) _d = time.clock() initial_states = np.atleast_1d(init_x) _e = time.clock() can_eq = pi.parse_weak_formulation(weak_form) _f = time.clock() state_space_form = pi.create_state_space(can_eq) _g = time.clock() q0 = np.array([pi.project_on_base(initial_state, pi.get_base(can_eq.dominant_lbl)) for initial_state in initial_states]).flatten() _h = time.clock() sim_domain, q = pi.simulate_state_space(state_space_form, q0, temp_domain) temporal_order = min(initial_states.size - 1, 0) _i = time.clock() eval_data = pi.get_sim_result(can_eq.dominant_lbl, q, sim_domain, spat_domain, temporal_order, 0, name=can_eq.dominant_form.name) _j = time.clock() pi.deregister_base("base") return _b - _a, _d - _c, _f - _e, _h - _g, _j - _i def product_benchmark(base): def projection_func(z): return np.sin(2 * z) + np.exp(z) _t = time.clock() res = pi.calculate_scalar_product_matrix(base, base) _t_mat = time.clock() - _t _t = time.clock() res = pi.project_on_base(pi.Function(projection_func), base) _t_proj = time.clock() - _t return _t_mat, _t_proj class ShapeFunctionTestBench(unittest.TestCase): """ Compare LagrangeNthOrder with LagrangeSecondOrder (have a look at terminal output). When it succeeds to get positive values (at least a few) under the "Difference" headline by the transport system example, too, you can delete: - this test case - LagrangeFirstOrder - LagrangeSecondOrder """ def setUp(self): self.node_cnt = 51 self.domain = pi.Domain(bounds=(0, 1), num=1000) # first one is used as reference if True: self.candidates = [ dict(shapefunction_class=pi.LagrangeFirstOrder, bounds=self.domain.bounds, num=self.node_cnt), dict(shapefunction_class=pi.LagrangeNthOrder, bounds=self.domain.bounds, num=self.node_cnt, order=1), ] else: self.candidates = [ dict(shapefunction_class=pi.LagrangeSecondOrder, bounds=self.domain.bounds, num=self.node_cnt), dict(shapefunction_class=pi.LagrangeNthOrder, bounds=self.domain.bounds, num=self.node_cnt, order=2), ] print("comparing {} (1) against {} (2)".format( *[candidate["shapefunction_class"] for candidate in self.candidates])) @unittest.skip def test_simulation(self): print(">>> transport system example speed test: \n") timings = [] n_iteration = 3 for i in range(n_iteration): print("running round {} of {}".format(i, n_iteration)) results = [] for candidate in self.candidates: results.append(simulation_benchmark(self.domain, candidate)) timings.append(results) res = np.array(timings) mean = np.mean(res, axis=0) for idx in range(len(self.candidates)): self.print_time( "means of {} rounds for {} in [s]:".format( n_iteration, self.candidates[idx]["shapefunction_class"]), mean[idx]) # process results diff = np.subtract(mean[1], mean[0]) try: frac = 100 * diff / mean[0] self.print_time("relative difference (2-1)/1 in [%]", frac) except FloatingPointError as e: print("relative difference not available") finally: self.print_time("absolute difference (2-1) in [s]", diff) @unittest.skip def test_evaluation(self): print(">>> evaluation speed test:") timings = [] n_iteration = 3 for i in range(n_iteration): print("running round {} of {}".format(i, n_iteration)) results = [] for candidate in self.candidates: nodes = pi.Domain(candidate["bounds"], candidate["num"]) cls = candidate.get("shapefunction_class") base = cls.cure_interval(nodes, **candidate) results.append(product_benchmark(base)) timings.append(results) # process results res = np.array(timings) mean = np.mean(res, axis=0) diff = np.subtract(mean[1], mean[0]) try: frac = 100 * diff / mean[0] print("relative difference (2-1)/1 in [%]:\n\t {}".format(frac)) except FloatingPointError as e: print("relative difference not available") finally: print("absolute difference (2-1) in [s]:\n\t {}".format(diff)) def print_time(self, headline, times): print(headline + "\n" + "\t cure interval: {}\n" "\t create weak form: {}\n" "\t parse weak form: {}\n" "\t initial weights: {}\n" "\t process data: {}\n" "".format(*times)) class ScalarProductMatrixTextBench(unittest.TestCase): @unittest.skip def test_optimization(self): c = CalculateScalarProductMatrixTestCase() c.setUp(dim1=100, dim2=200) c.compare_timings()
[ "pyinduct.create_state_space", "pyinduct.get_sim_result", "pyinduct.FieldVariable", "numpy.mean", "numpy.sin", "numpy.exp", "time.clock", "pyinduct.calculate_scalar_product_matrix", "pyinduct.Input", "pyinduct.simulate_state_space", "pyinduct.get_base", "pyinduct.parse_weak_formulation", "pyinduct.SignalGenerator", "pyinduct.tests.test_core.CalculateScalarProductMatrixTestCase", "pyinduct.deregister_base", "pyinduct.Function", "pyinduct.Domain", "numpy.subtract", "pyinduct.register_base", "numpy.array", "numpy.atleast_1d", "pyinduct.TestFunction" ]
[((577, 610), 'pyinduct.Domain', 'pi.Domain', ([], {'bounds': '(0, 5)', 'num': '(100)'}), '(bounds=(0, 5), num=100)\n', (586, 610), True, 'import pyinduct as pi\n'), ((625, 649), 'pyinduct.Function', 'pi.Function', (['(lambda z: 0)'], {}), '(lambda z: 0)\n', (636, 649), True, 'import pyinduct as pi\n'), ((660, 672), 'time.clock', 'time.clock', ([], {}), '()\n', (670, 672), False, 'import time\n'), ((685, 731), 'pyinduct.Domain', 'pi.Domain', (["settings['bounds']", "settings['num']"], {}), "(settings['bounds'], settings['num'])\n", (694, 731), True, 'import pyinduct as pi\n'), ((835, 847), 'time.clock', 'time.clock', ([], {}), '()\n', (845, 847), False, 'import time\n'), ((877, 911), 'pyinduct.register_base', 'pi.register_base', (['func_label', 'base'], {}), '(func_label, base)\n', (893, 911), True, 'import pyinduct as pi\n'), ((1096, 1108), 'time.clock', 'time.clock', ([], {}), '()\n', (1106, 1108), False, 'import time\n'), ((1854, 1866), 'time.clock', 'time.clock', ([], {}), '()\n', (1864, 1866), False, 'import time\n'), ((1889, 1910), 'numpy.atleast_1d', 'np.atleast_1d', (['init_x'], {}), '(init_x)\n', (1902, 1910), True, 'import numpy as np\n'), ((1921, 1933), 'time.clock', 'time.clock', ([], {}), '()\n', (1931, 1933), False, 'import time\n'), ((1947, 1983), 'pyinduct.parse_weak_formulation', 'pi.parse_weak_formulation', (['weak_form'], {}), '(weak_form)\n', (1972, 1983), True, 'import pyinduct as pi\n'), ((1993, 2005), 'time.clock', 'time.clock', ([], {}), '()\n', (2003, 2005), False, 'import time\n'), ((2030, 2059), 'pyinduct.create_state_space', 'pi.create_state_space', (['can_eq'], {}), '(can_eq)\n', (2051, 2059), True, 'import pyinduct as pi\n'), ((2070, 2082), 'time.clock', 'time.clock', ([], {}), '()\n', (2080, 2082), False, 'import time\n'), ((2246, 2258), 'time.clock', 'time.clock', ([], {}), '()\n', (2256, 2258), False, 'import time\n'), ((2280, 2338), 'pyinduct.simulate_state_space', 'pi.simulate_state_space', (['state_space_form', 'q0', 'temp_domain'], {}), '(state_space_form, q0, temp_domain)\n', (2303, 2338), True, 'import pyinduct as pi\n'), ((2402, 2414), 'time.clock', 'time.clock', ([], {}), '()\n', (2412, 2414), False, 'import time\n'), ((2431, 2552), 'pyinduct.get_sim_result', 'pi.get_sim_result', (['can_eq.dominant_lbl', 'q', 'sim_domain', 'spat_domain', 'temporal_order', '(0)'], {'name': 'can_eq.dominant_form.name'}), '(can_eq.dominant_lbl, q, sim_domain, spat_domain,\n temporal_order, 0, name=can_eq.dominant_form.name)\n', (2448, 2552), True, 'import pyinduct as pi\n'), ((2592, 2604), 'time.clock', 'time.clock', ([], {}), '()\n', (2602, 2604), False, 'import time\n'), ((2610, 2636), 'pyinduct.deregister_base', 'pi.deregister_base', (['"""base"""'], {}), "('base')\n", (2628, 2636), True, 'import pyinduct as pi\n'), ((2803, 2815), 'time.clock', 'time.clock', ([], {}), '()\n', (2813, 2815), False, 'import time\n'), ((2826, 2872), 'pyinduct.calculate_scalar_product_matrix', 'pi.calculate_scalar_product_matrix', (['base', 'base'], {}), '(base, base)\n', (2860, 2872), True, 'import pyinduct as pi\n'), ((2914, 2926), 'time.clock', 'time.clock', ([], {}), '()\n', (2924, 2926), False, 'import time\n'), ((2886, 2898), 'time.clock', 'time.clock', ([], {}), '()\n', (2896, 2898), False, 'import time\n'), ((2956, 2984), 'pyinduct.Function', 'pi.Function', (['projection_func'], {}), '(projection_func)\n', (2967, 2984), True, 'import pyinduct as pi\n'), ((3006, 3018), 'time.clock', 'time.clock', ([], {}), '()\n', (3016, 3018), False, 'import time\n'), ((3506, 3540), 'pyinduct.Domain', 'pi.Domain', ([], {'bounds': '(0, 1)', 'num': '(1000)'}), '(bounds=(0, 1), num=1000)\n', (3515, 3540), True, 'import pyinduct as pi\n'), ((4978, 4995), 'numpy.array', 'np.array', (['timings'], {}), '(timings)\n', (4986, 4995), True, 'import numpy as np\n'), ((5011, 5031), 'numpy.mean', 'np.mean', (['res'], {'axis': '(0)'}), '(res, axis=0)\n', (5018, 5031), True, 'import numpy as np\n'), ((5337, 5366), 'numpy.subtract', 'np.subtract', (['mean[1]', 'mean[0]'], {}), '(mean[1], mean[0])\n', (5348, 5366), True, 'import numpy as np\n'), ((6319, 6336), 'numpy.array', 'np.array', (['timings'], {}), '(timings)\n', (6327, 6336), True, 'import numpy as np\n'), ((6352, 6372), 'numpy.mean', 'np.mean', (['res'], {'axis': '(0)'}), '(res, axis=0)\n', (6359, 6372), True, 'import numpy as np\n'), ((6388, 6417), 'numpy.subtract', 'np.subtract', (['mean[1]', 'mean[0]'], {}), '(mean[1], mean[0])\n', (6399, 6417), True, 'import numpy as np\n'), ((7252, 7290), 'pyinduct.tests.test_core.CalculateScalarProductMatrixTestCase', 'CalculateScalarProductMatrixTestCase', ([], {}), '()\n', (7288, 7290), False, 'from pyinduct.tests.test_core import CalculateScalarProductMatrixTestCase\n'), ((953, 1054), 'pyinduct.SignalGenerator', 'pi.SignalGenerator', (['"""square"""', 'temp_domain.points'], {'frequency': '(0.3)', 'scale': '(2)', 'offset': '(4)', 'phase_shift': '(1)'}), "('square', temp_domain.points, frequency=0.3, scale=2,\n offset=4, phase_shift=1)\n", (971, 1054), True, 'import pyinduct as pi\n'), ((2767, 2780), 'numpy.sin', 'np.sin', (['(2 * z)'], {}), '(2 * z)\n', (2773, 2780), True, 'import numpy as np\n'), ((2783, 2792), 'numpy.exp', 'np.exp', (['z'], {}), '(z)\n', (2789, 2792), True, 'import numpy as np\n'), ((6016, 6064), 'pyinduct.Domain', 'pi.Domain', (["candidate['bounds']", "candidate['num']"], {}), "(candidate['bounds'], candidate['num'])\n", (6025, 6064), True, 'import pyinduct as pi\n'), ((1194, 1236), 'pyinduct.FieldVariable', 'pi.FieldVariable', (['func_label'], {'order': '(1, 0)'}), '(func_label, order=(1, 0))\n', (1210, 1236), True, 'import pyinduct as pi\n'), ((1250, 1277), 'pyinduct.TestFunction', 'pi.TestFunction', (['func_label'], {}), '(func_label)\n', (1265, 1277), True, 'import pyinduct as pi\n'), ((1361, 1389), 'pyinduct.FieldVariable', 'pi.FieldVariable', (['func_label'], {}), '(func_label)\n', (1377, 1389), True, 'import pyinduct as pi\n'), ((1403, 1439), 'pyinduct.TestFunction', 'pi.TestFunction', (['func_label'], {'order': '(1)'}), '(func_label, order=1)\n', (1418, 1439), True, 'import pyinduct as pi\n'), ((1531, 1592), 'pyinduct.FieldVariable', 'pi.FieldVariable', (['func_label'], {'location': 'spat_domain.bounds[-1]'}), '(func_label, location=spat_domain.bounds[-1])\n', (1547, 1592), True, 'import pyinduct as pi\n'), ((1606, 1666), 'pyinduct.TestFunction', 'pi.TestFunction', (['func_label'], {'location': 'spat_domain.bounds[-1]'}), '(func_label, location=spat_domain.bounds[-1])\n', (1621, 1666), True, 'import pyinduct as pi\n'), ((1737, 1748), 'pyinduct.Input', 'pi.Input', (['u'], {}), '(u)\n', (1745, 1748), True, 'import pyinduct as pi\n'), ((1762, 1801), 'pyinduct.TestFunction', 'pi.TestFunction', (['func_label'], {'location': '(0)'}), '(func_label, location=0)\n', (1777, 1801), True, 'import pyinduct as pi\n'), ((2136, 2168), 'pyinduct.get_base', 'pi.get_base', (['can_eq.dominant_lbl'], {}), '(can_eq.dominant_lbl)\n', (2147, 2168), True, 'import pyinduct as pi\n')]
from geometry.TwoDimension import SE2Pose from factors.Factors import SE2RelativeGaussianLikelihoodFactor, \ R2RelativeGaussianLikelihoodFactor, R2RangeGaussianLikelihoodFactor, \ LikelihoodFactor, SE2R2RangeGaussianLikelihoodFactor import numpy as np import TransportMaps.Distributions as dist from slam.Variables import VariableType, Variable, R2Variable, \ SE2Variable import matplotlib.pyplot as plt from typing import Tuple, Iterable, Dict, List, ClassVar from factors.Factors import Factor, UnaryR2GaussianPriorFactor, UnarySE2ApproximateGaussianPriorFactor from enum import Enum class SensorType(Enum): relative = 0 range_only_gaussian = 1 def read_variable_and_truth_from_line(line: str) -> Tuple[Variable, np.ndarray]: """ Read and create a Variable object from a list of strings The string is formatted as: [variable_type, class_name, var_name] + true_pose Return the ground truth location/pose of the variable """ var = Variable.construct_from_text(line) line = line.strip().split() val = np.array([float(line[i]) for i in range(4, 4 + var.dim)]) return var, val def write_variable_and_truth_to_line( var: Variable, truth: np.ndarray = None) -> str: """ Write a variable and its ground truth location/pose to a string """ line = str(var) if truth is not None: line += " " + " ".join([str(v) for v in truth]) return line def factor_graph_to_string(variables: Iterable[Variable], factors: Iterable[Factor], var_truth: Dict[Variable, np.ndarray] = None) -> str: res = [None] * (len(variables) + len(factors)) for i, var in enumerate(variables): truth = var_truth[var] if var in var_truth else None res[i] = write_variable_and_truth_to_line(var, truth) for i, factor in enumerate(factors): res[len(variables) + i] = str(factor) return "\n".join(res) def read_factor_graph_from_file(file_name: str) -> Tuple[List[Variable], Dict[Variable, np.ndarray], List[Factor]]: with open(file_name) as file: variables = [] var_poses = {} line = file.readline() factors = [] while line: texts = line.strip().split() if texts[0] == "Variable": var, val = read_variable_and_truth_from_line(line) variables.append(var) var_poses[var] = val elif texts[0] == "Factor": factors.append(Factor.construct_from_text(line, variables)) line = file.readline() return variables, var_poses, factors def \ generate_measurements_for_factor_graph( input_file_name: str, odometry_class: ClassVar, landmark_measurement_class: ClassVar, landmark_measurement_range: float, output_file_name: str = None, max_measurements_allowed: int = 1, **kwargs) -> Tuple[List[Variable], Dict[Variable, np.ndarray], List[Factor]]: def _create_r2_relative_gaussian_factor( var1: R2Variable, var2: R2Variable, covariance: np.ndarray, obs: np.ndarray = None ) -> R2RelativeGaussianLikelihoodFactor: if obs is None: obs = np.zeros(R2RelativeGaussianLikelihoodFactor.measurement_dim) elif len(obs.shape) != 1 or obs.shape[0] \ != R2RelativeGaussianLikelihoodFactor.measurement_dim: raise ValueError("Dimensionality of obs is incorrect") return R2RelativeGaussianLikelihoodFactor(var1=var1, var2=var2, observation=obs, covariance=covariance) def _create_se2_relative_gaussian_factor( var1: R2Variable, var2: R2Variable, covariance: np.ndarray, obs: np.ndarray = None ) -> SE2RelativeGaussianLikelihoodFactor: if obs is None: obs = np.zeros(SE2RelativeGaussianLikelihoodFactor.measurement_dim) elif len(obs.shape) != 1 or obs.shape[0] \ != SE2RelativeGaussianLikelihoodFactor.measurement_dim: raise ValueError("Dimensionality of obs is incorrect") return SE2RelativeGaussianLikelihoodFactor(var1=var1, var2=var2, observation=SE2Pose.by_array(obs), covariance=covariance) def _create_se2_r2_range_gaussian_factor( var1: SE2Variable, var2: R2Variable, sigma: float, obs: np.ndarray = None ) -> SE2R2RangeGaussianLikelihoodFactor: if obs is None: obs = np.zeros(SE2R2RangeGaussianLikelihoodFactor.measurement_dim) elif len(obs.shape) != 1 or obs.shape[0] \ != SE2R2RangeGaussianLikelihoodFactor.measurement_dim: raise ValueError("Dimensionality of obs is incorrect") return SE2R2RangeGaussianLikelihoodFactor(var1=var1, var2=var2, observation=obs, sigma=sigma) def _create_r2_range_gaussian_factor( var1: R2Variable, var2: R2Variable, sigma: float, obs: np.ndarray = None ) -> R2RangeGaussianLikelihoodFactor: if obs is None: obs = np.zeros(R2RangeGaussianLikelihoodFactor.measurement_dim) elif len(obs.shape) != 1 or obs.shape[0] \ != R2RangeGaussianLikelihoodFactor.measurement_dim: raise ValueError("Dimensionality of obs is incorrect") return R2RangeGaussianLikelihoodFactor(var1=var1, var2=var2, observation=obs, sigma=sigma) def _create_se2_r2_range_gaussian_factor_with_ambiguous_association( var1: SE2Variable, var2: R2Variable, sigma: float, obs: np.ndarray = None ) -> SE2R2RangeGaussianLikelihoodFactor: if obs is None: obs = np.zeros(SE2R2RangeGaussianLikelihoodFactor.measurement_dim) elif len(obs.shape) != 1 or obs.shape[0] \ != SE2R2RangeGaussianLikelihoodFactor.measurement_dim: raise ValueError("Dimensionality of obs is incorrect") return SE2R2RangeGaussianLikelihoodFactor(var1=var1, var2=var2, observation=obs, sigma=sigma) def _create_odometry_factor(var1: Variable, var2: Variable, obs: np.ndarray = None) -> LikelihoodFactor: if odometry_class == R2RelativeGaussianLikelihoodFactor: covariance = kwargs["odometry_covariance"] \ if "odometry_covariance" in kwargs else \ np.identity(2) * kwargs["odometry_sigma"] ** 2 return _create_r2_relative_gaussian_factor(var1=var1, var2=var2, covariance=covariance, obs=obs) elif odometry_class == SE2RelativeGaussianLikelihoodFactor: if "odometry_covariance" in kwargs: covariance = kwargs["odometry_covariance"] else: covariance = np.identity(3) * kwargs["odometry_sigma"] ** 2 covariance[2, 2] = kwargs["orientation_sigma"] ** 2 return _create_se2_relative_gaussian_factor(var1=var1, var2=var2, covariance=covariance, obs=obs) else: raise ValueError("The odometry factor is not supported yet") def _create_landmark_measurement_factor( pose_var: Variable, landmark_var: Variable, obs: np.ndarray = None ) -> LikelihoodFactor: if landmark_measurement_class == R2RelativeGaussianLikelihoodFactor: covariance = kwargs["landmark_covariance"] \ if "landmark_covariance" in kwargs else \ np.identity(2) * kwargs["landmark_sigma"] ** 2 return _create_r2_relative_gaussian_factor(var1=pose_var, var2=landmark_var, covariance=covariance, obs=obs) elif landmark_measurement_class == R2RangeGaussianLikelihoodFactor: return _create_r2_range_gaussian_factor(var1=pose_var, var2=landmark_var, sigma=kwargs[ "landmark_sigma"], obs=obs) elif landmark_measurement_class == SE2R2RangeGaussianLikelihoodFactor: return _create_se2_r2_range_gaussian_factor(var1=pose_var, var2=landmark_var, sigma=kwargs[ "landmark_sigma"], obs=obs) # Read all nodes, true positions, and pre-defined factors variables, truth, factors = read_factor_graph_from_file(input_file_name) # Generate odometry measurements poses = [var for var in variables if var.type == VariableType.Pose] landmarks = [var for var in variables if var.type == VariableType.Landmark] for i in range(len(poses) - 1): var_from, var_to = poses[i: i + 2] tmp_factor = _create_odometry_factor( var1=var_from, var2=var_to) obs = tmp_factor.sample(var1=truth[var_from].reshape( (1, var_from.dim)), var2=truth[var_to].reshape((1, var_to.dim)) ).reshape(tmp_factor.measurement_dim) factor = _create_odometry_factor(var1=var_from, var2=var_to, obs=obs) factors.append(factor) # Generate landmark measurements for var in poses: translational_dim = var.translational_dim pose_location = truth[var][:translational_dim] landmark_distances = {l: np.sqrt(np.sum((pose_location - truth[l][:translational_dim]) ** 2) ) for l in landmarks} detected_landmarks = [l for l in landmarks if landmark_distances[l] <= landmark_measurement_range] if not detected_landmarks: continue else: num_factors = min(max_measurements_allowed, len(detected_landmarks)) landmarks_to_add = sorted(detected_landmarks, key=lambda x: landmark_distances[x])[ :num_factors] for landmark in landmarks_to_add: tmp_factor = _create_landmark_measurement_factor( pose_var=var, landmark_var=landmark) obs = tmp_factor.sample(var1=truth[var].reshape( (1, var.dim)), var2=truth[landmark].reshape((1, landmark.dim)) ).reshape(tmp_factor.measurement_dim) factor = _create_landmark_measurement_factor( pose_var=var, landmark_var=landmark, obs=obs) factors.append(factor) # Write into output file text_file = open(output_file_name, "w") text_file.write(factor_graph_to_string(variables, factors, truth)) text_file.close() return variables, truth, factors def separate_incremental_nodes_and_factors(variables: Iterable[Variable], truth: Dict[Variable, np.ndarray], factors: Iterable[Factor] ) -> Tuple[List[List[Variable]]]: pass class G2oToroPoseGraphReader(object): file_type_list = ["g2o", "graph"] node_header_list = ["VERTEX_SE2", "VERTEX2"] factor_header_list = ["EDGE_SE2", "EDGE2"] info_mat_format_list = [[(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)], [(0, 0), (0, 1), (1, 1), (2, 2), (0, 2), (1, 2)]] def __init__(self, file_path: str, correlated_R_t: bool = True, ignore_orientation: bool = False, synthetic_observation: bool = False, covariance: float = None): """ formats of pose graph files refer to https://www.dropbox.com/s/uwwt3ni7uzdv1j7/g2oVStoro.pdf?dl=0 convert a pose graph file to our NFiSAM object :param file_path: a string of file directory :param correlated_R_t: true if using wrapped Gaussian on manifold; false if using von Mises :param ignore_orientation: when false, SE2 poses are used; when true, R2 poses are used :param synthetic_observation: when false, we use the data from g2o file; when true, we generate synthetic observations :param covariance: the sigma of likelihood factors """ self._correlated_R_t = correlated_R_t self._file_path = file_path self._file_type, self._node_head, self._factor_head, \ self._info_mat_format = self.getFileType() self._node_list = [] self._factor_list = [] self._true_location_mapping = {} dim = 2 if ignore_orientation else 3 with open(file_path) as fp: line = fp.readline() cnt = 1 while line: line_list = line.strip().split() if line_list[0] == self._node_head: # reading lines for init solution to find new nodes var = R2Variable(line_list[1]) if ignore_orientation else SE2Variable(line_list[1]) self._node_list.append(var) self._true_location_mapping[var] = \ np.array([float(line_list[2]), float(line_list[3])]) if ignore_orientation else \ np.array([float(line_list[2]), float(line_list[3]), float(line_list[4])]) elif line_list[0] == self._factor_head: if not synthetic_observation: info_mat = np.zeros((dim, dim)) for i in range(6, 12): info_mat[self._info_mat_format[i - 6]] = float( line_list[i]) info_mat[ self._info_mat_format[i - 6][::-1]] = float( line_list[i]) cov_mat = np.linalg.inv(info_mat) var1 = R2Variable(line_list[1]) if ignore_orientation else SE2Variable(line_list[1]) var2 = R2Variable(line_list[2]) if ignore_orientation else SE2Variable(line_list[2]) tmp = R2RelativeGaussianLikelihoodFactor( var1=var1, var2=var2, observation=np.ndarray([line_list[3], line_list[4]] ), covariance=cov_mat[:2, :2]) \ if ignore_orientation else \ SE2RelativeGaussianLikelihoodFactor( var1=var1, var2=var2, observation=SE2Pose(x=float(line_list[3]), y=float(line_list[4]), theta=float(line_list[5])), covariance=cov_mat, correlated_R_t=correlated_R_t) self._factor_list.append(tmp) else: if ignore_orientation: var1 = R2Variable(line_list[1]) var2 = R2Variable(line_list[2]) obs = self._true_location_mapping[var2] - \ self._true_location_mapping[var1] if covariance is None: cov = np.identity(dim) else: cov = covariance obs += dist.GaussianDistribution( mu=np.zeros(dim), sigma=cov).rvs( 1).reshape(dim) tmp = R2RelativeGaussianLikelihoodFactor( var1=var1, var2=var2, observation=obs, covariance=cov) self._factor_list.append(tmp) line = fp.readline() cnt += 1 plt.plot([self._true_location_mapping[node][0] for node in self._node_list], [self._true_location_mapping[node][1] for node in self._node_list], c='k') plt.savefig(file_path+'.png', dpi=300) plt.show() def dataForSolver(self, prior_cov_scale=.1): var0 = self._node_list[0] if var0.dim == 2: prior_factor = UnaryR2GaussianPriorFactor(var=var0, mu=self._true_location_mapping[var0], covariance=prior_cov_scale * np.identity(var0.dim)) elif var0.dim == 3: prior_factor = UnarySE2ApproximateGaussianPriorFactor(var=var0, prior_pose=SE2Pose.by_array(self._true_location_mapping[var0]), covariance=prior_cov_scale * np.identity(var0.dim)) factors = [prior_factor] + self._factor_list return self._node_list, factors, self._true_location_mapping def getFileType(self): i = 0 for type in G2oToroPoseGraphReader.file_type_list: if self._file_path.endswith(type): return type, G2oToroPoseGraphReader.node_header_list[i], \ G2oToroPoseGraphReader.factor_header_list[i], \ G2oToroPoseGraphReader.info_mat_format_list[i] i += 1 raise ValueError("Can not recognize the suffix of input file") @property def file_type(self): return self._file_type @property def node_head(self): return self._node_head @property def factor_head(self): return self._factor_head @property def info_mat_format(self): return self._info_mat_format @property def file_path(self): return self._file_path @property def node_list(self): return self._node_list @property def factor_list(self): return self._factor_list
[ "factors.Factors.R2RangeGaussianLikelihoodFactor", "matplotlib.pyplot.show", "slam.Variables.Variable.construct_from_text", "matplotlib.pyplot.plot", "factors.Factors.SE2R2RangeGaussianLikelihoodFactor", "numpy.sum", "slam.Variables.SE2Variable", "numpy.zeros", "numpy.identity", "slam.Variables.R2Variable", "geometry.TwoDimension.SE2Pose.by_array", "numpy.linalg.inv", "factors.Factors.R2RelativeGaussianLikelihoodFactor", "factors.Factors.Factor.construct_from_text", "numpy.ndarray", "matplotlib.pyplot.savefig" ]
[((1017, 1051), 'slam.Variables.Variable.construct_from_text', 'Variable.construct_from_text', (['line'], {}), '(line)\n', (1045, 1051), False, 'from slam.Variables import VariableType, Variable, R2Variable, SE2Variable\n'), ((3828, 3928), 'factors.Factors.R2RelativeGaussianLikelihoodFactor', 'R2RelativeGaussianLikelihoodFactor', ([], {'var1': 'var1', 'var2': 'var2', 'observation': 'obs', 'covariance': 'covariance'}), '(var1=var1, var2=var2, observation=obs,\n covariance=covariance)\n', (3862, 3928), False, 'from factors.Factors import SE2RelativeGaussianLikelihoodFactor, R2RelativeGaussianLikelihoodFactor, R2RangeGaussianLikelihoodFactor, LikelihoodFactor, SE2R2RangeGaussianLikelihoodFactor\n'), ((5256, 5346), 'factors.Factors.SE2R2RangeGaussianLikelihoodFactor', 'SE2R2RangeGaussianLikelihoodFactor', ([], {'var1': 'var1', 'var2': 'var2', 'observation': 'obs', 'sigma': 'sigma'}), '(var1=var1, var2=var2, observation=obs,\n sigma=sigma)\n', (5290, 5346), False, 'from factors.Factors import SE2RelativeGaussianLikelihoodFactor, R2RelativeGaussianLikelihoodFactor, R2RangeGaussianLikelihoodFactor, LikelihoodFactor, SE2R2RangeGaussianLikelihoodFactor\n'), ((5837, 5924), 'factors.Factors.R2RangeGaussianLikelihoodFactor', 'R2RangeGaussianLikelihoodFactor', ([], {'var1': 'var1', 'var2': 'var2', 'observation': 'obs', 'sigma': 'sigma'}), '(var1=var1, var2=var2, observation=obs,\n sigma=sigma)\n', (5868, 5924), False, 'from factors.Factors import SE2RelativeGaussianLikelihoodFactor, R2RelativeGaussianLikelihoodFactor, R2RangeGaussianLikelihoodFactor, LikelihoodFactor, SE2R2RangeGaussianLikelihoodFactor\n'), ((6535, 6625), 'factors.Factors.SE2R2RangeGaussianLikelihoodFactor', 'SE2R2RangeGaussianLikelihoodFactor', ([], {'var1': 'var1', 'var2': 'var2', 'observation': 'obs', 'sigma': 'sigma'}), '(var1=var1, var2=var2, observation=obs,\n sigma=sigma)\n', (6569, 6625), False, 'from factors.Factors import SE2RelativeGaussianLikelihoodFactor, R2RelativeGaussianLikelihoodFactor, R2RangeGaussianLikelihoodFactor, LikelihoodFactor, SE2R2RangeGaussianLikelihoodFactor\n'), ((17368, 17523), 'matplotlib.pyplot.plot', 'plt.plot', (['[self._true_location_mapping[node][0] for node in self._node_list]', '[self._true_location_mapping[node][1] for node in self._node_list]'], {'c': '"""k"""'}), "([self._true_location_mapping[node][0] for node in self._node_list],\n [self._true_location_mapping[node][1] for node in self._node_list], c='k')\n", (17376, 17523), True, 'import matplotlib.pyplot as plt\n'), ((17624, 17664), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(file_path + '.png')"], {'dpi': '(300)'}), "(file_path + '.png', dpi=300)\n", (17635, 17664), True, 'import matplotlib.pyplot as plt\n'), ((17672, 17682), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (17680, 17682), True, 'import matplotlib.pyplot as plt\n'), ((3559, 3619), 'numpy.zeros', 'np.zeros', (['R2RelativeGaussianLikelihoodFactor.measurement_dim'], {}), '(R2RelativeGaussianLikelihoodFactor.measurement_dim)\n', (3567, 3619), True, 'import numpy as np\n'), ((4276, 4337), 'numpy.zeros', 'np.zeros', (['SE2RelativeGaussianLikelihoodFactor.measurement_dim'], {}), '(SE2RelativeGaussianLikelihoodFactor.measurement_dim)\n', (4284, 4337), True, 'import numpy as np\n'), ((4987, 5047), 'numpy.zeros', 'np.zeros', (['SE2R2RangeGaussianLikelihoodFactor.measurement_dim'], {}), '(SE2R2RangeGaussianLikelihoodFactor.measurement_dim)\n', (4995, 5047), True, 'import numpy as np\n'), ((5574, 5631), 'numpy.zeros', 'np.zeros', (['R2RangeGaussianLikelihoodFactor.measurement_dim'], {}), '(R2RangeGaussianLikelihoodFactor.measurement_dim)\n', (5582, 5631), True, 'import numpy as np\n'), ((6266, 6326), 'numpy.zeros', 'np.zeros', (['SE2R2RangeGaussianLikelihoodFactor.measurement_dim'], {}), '(SE2R2RangeGaussianLikelihoodFactor.measurement_dim)\n', (6274, 6326), True, 'import numpy as np\n'), ((4668, 4689), 'geometry.TwoDimension.SE2Pose.by_array', 'SE2Pose.by_array', (['obs'], {}), '(obs)\n', (4684, 4689), False, 'from geometry.TwoDimension import SE2Pose\n'), ((10463, 10522), 'numpy.sum', 'np.sum', (['((pose_location - truth[l][:translational_dim]) ** 2)'], {}), '((pose_location - truth[l][:translational_dim]) ** 2)\n', (10469, 10522), True, 'import numpy as np\n'), ((6967, 6981), 'numpy.identity', 'np.identity', (['(2)'], {}), '(2)\n', (6978, 6981), True, 'import numpy as np\n'), ((8259, 8273), 'numpy.identity', 'np.identity', (['(2)'], {}), '(2)\n', (8270, 8273), True, 'import numpy as np\n'), ((2776, 2819), 'factors.Factors.Factor.construct_from_text', 'Factor.construct_from_text', (['line', 'variables'], {}), '(line, variables)\n', (2802, 2819), False, 'from factors.Factors import Factor, UnaryR2GaussianPriorFactor, UnarySE2ApproximateGaussianPriorFactor\n'), ((7463, 7477), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (7474, 7477), True, 'import numpy as np\n'), ((14156, 14180), 'slam.Variables.R2Variable', 'R2Variable', (['line_list[1]'], {}), '(line_list[1])\n', (14166, 14180), False, 'from slam.Variables import VariableType, Variable, R2Variable, SE2Variable\n'), ((14208, 14233), 'slam.Variables.SE2Variable', 'SE2Variable', (['line_list[1]'], {}), '(line_list[1])\n', (14219, 14233), False, 'from slam.Variables import VariableType, Variable, R2Variable, SE2Variable\n'), ((18039, 18060), 'numpy.identity', 'np.identity', (['var0.dim'], {}), '(var0.dim)\n', (18050, 18060), True, 'import numpy as np\n'), ((18246, 18297), 'geometry.TwoDimension.SE2Pose.by_array', 'SE2Pose.by_array', (['self._true_location_mapping[var0]'], {}), '(self._true_location_mapping[var0])\n', (18262, 18297), False, 'from geometry.TwoDimension import SE2Pose\n'), ((14691, 14711), 'numpy.zeros', 'np.zeros', (['(dim, dim)'], {}), '((dim, dim))\n', (14699, 14711), True, 'import numpy as np\n'), ((15083, 15106), 'numpy.linalg.inv', 'np.linalg.inv', (['info_mat'], {}), '(info_mat)\n', (15096, 15106), True, 'import numpy as np\n'), ((18395, 18416), 'numpy.identity', 'np.identity', (['var0.dim'], {}), '(var0.dim)\n', (18406, 18416), True, 'import numpy as np\n'), ((15139, 15163), 'slam.Variables.R2Variable', 'R2Variable', (['line_list[1]'], {}), '(line_list[1])\n', (15149, 15163), False, 'from slam.Variables import VariableType, Variable, R2Variable, SE2Variable\n'), ((15191, 15216), 'slam.Variables.SE2Variable', 'SE2Variable', (['line_list[1]'], {}), '(line_list[1])\n', (15202, 15216), False, 'from slam.Variables import VariableType, Variable, R2Variable, SE2Variable\n'), ((15249, 15273), 'slam.Variables.R2Variable', 'R2Variable', (['line_list[2]'], {}), '(line_list[2])\n', (15259, 15273), False, 'from slam.Variables import VariableType, Variable, R2Variable, SE2Variable\n'), ((15301, 15326), 'slam.Variables.SE2Variable', 'SE2Variable', (['line_list[2]'], {}), '(line_list[2])\n', (15312, 15326), False, 'from slam.Variables import VariableType, Variable, R2Variable, SE2Variable\n'), ((16397, 16421), 'slam.Variables.R2Variable', 'R2Variable', (['line_list[1]'], {}), '(line_list[1])\n', (16407, 16421), False, 'from slam.Variables import VariableType, Variable, R2Variable, SE2Variable\n'), ((16458, 16482), 'slam.Variables.R2Variable', 'R2Variable', (['line_list[2]'], {}), '(line_list[2])\n', (16468, 16482), False, 'from slam.Variables import VariableType, Variable, R2Variable, SE2Variable\n'), ((17044, 17137), 'factors.Factors.R2RelativeGaussianLikelihoodFactor', 'R2RelativeGaussianLikelihoodFactor', ([], {'var1': 'var1', 'var2': 'var2', 'observation': 'obs', 'covariance': 'cov'}), '(var1=var1, var2=var2, observation=obs,\n covariance=cov)\n', (17078, 17137), False, 'from factors.Factors import SE2RelativeGaussianLikelihoodFactor, R2RelativeGaussianLikelihoodFactor, R2RangeGaussianLikelihoodFactor, LikelihoodFactor, SE2R2RangeGaussianLikelihoodFactor\n'), ((16716, 16732), 'numpy.identity', 'np.identity', (['dim'], {}), '(dim)\n', (16727, 16732), True, 'import numpy as np\n'), ((15515, 15555), 'numpy.ndarray', 'np.ndarray', (['[line_list[3], line_list[4]]'], {}), '([line_list[3], line_list[4]])\n', (15525, 15555), True, 'import numpy as np\n'), ((16925, 16938), 'numpy.zeros', 'np.zeros', (['dim'], {}), '(dim)\n', (16933, 16938), True, 'import numpy as np\n')]
#!/usr/local/bin/python3 # SimSRE, a tool to investigate how different work structures for SRE # might affect outcomes for an SRE team or teams. # The basic idea is that we model an SRE team as a state machine (via # discrete event simulation) which has work assigned, processes work, # and different types of work have different effects. # There are a large number of improvements to be made: # 1. Should fully utilise the actual event-oriented approach of simpy, # rather than the half-way house I do here # 2. Should fully simulate multiple teams; the approach here makes # that tricky to do. (Particularly important to do for cross-team work.) # 3. In the future "policy" such as whether onboardings add one operational # work or two or whatever, should be easily swappable out objects, so we # we can test the effects of changing more easily. # You'll need to do the equivalent of pip3 install mplot3d matplotlib # to get this to work. from mpl_toolkits.mplot3d import Axes3D import collections import numpy import matplotlib.pyplot as plt import pprint import random import simpy # Enums, via stack overflow. def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) reverse = dict((value, key) for key, value in enums.items()) enums['reverse_mapping'] = reverse return type('Enum', (), enums) # Constants # The Treynor "hard cap" on operational work, not more than 50%. HARD_CAP_OPEX = 0.5 # How many "clock ticks" the simulation goes for. SIM_DURATION = 100 # How much operational growth happens, per clock tick, which is used # as an analogue for much our existing units of operatational work should # be multiplied by. QUARTERLY_GROWTH = 1.15 # The different work types that an SRE team can have. # Operational: e.g. cell moves, cluster turnups, totally operational and necessary, # but not relevant outside of the team (and it goes up as a function of the systems # that a team has onboarded.) # In team project: a siloized project, basically just some work that again makes # something within the team easier, that's it. # Cross team project: right now, for simplifying reasons, this overloads _two_ things: # the team itself working on cross-team work, and also receiving the benefits of someone # else's cross-team projects. # Onboarding: an onboarding adds some additional work to the stack, and also changes # the base level of operational level. SRE_WORK_TYPES = enum(OPERATIONAL=1, IN_TEAM_PROJECT=2, CROSS_TEAM_PROJECT=3, ONBOARDING=4) # The number of work units an SRE team can process in a clock-tick. SRE_TEAM_CAPACITY = 10 # The maximum number of onboardings an SRE team can do. SRE_TEAM_ONBOARDINGS_LIMIT = 10 # The baseline operational work; again a simplifying constant for the multiplications re: # onboardings. SRE_BASELINE_OPERATIONAL = 1 # The cap on operational work available to be assigned. SRE_TEAM_MAX_OPERATIONAL = 20 # The default distribution of work, for a team starting from scratch. SRE_WORK_DISTRIBUTION = [SRE_WORK_TYPES.OPERATIONAL, SRE_WORK_TYPES.OPERATIONAL, SRE_WORK_TYPES.OPERATIONAL, SRE_WORK_TYPES.OPERATIONAL, SRE_WORK_TYPES.IN_TEAM_PROJECT, SRE_WORK_TYPES.IN_TEAM_PROJECT, SRE_WORK_TYPES.IN_TEAM_PROJECT, SRE_WORK_TYPES.IN_TEAM_PROJECT, SRE_WORK_TYPES.CROSS_TEAM_PROJECT, SRE_WORK_TYPES.CROSS_TEAM_PROJECT] class SRE_work_item(object): """A very thin wrapper around enums to represent work types.""" def __init__(self, work_type=None): if work_type is None: self.work_type = work_type class SRE_team(object): """Class simulating an SRE team. env: simpy environment object.""" def __init__(self, env): self.env = env # Our internal way of tracking the work assigned for us to potentially do. # Double-ended because I want to pop from one end and push onto the other. self.work_items = collections.deque() # Instantiate me as a process. self.action = env.process(self.run(env)) # A guard to prevent simultaneous onboardings. self.onboarding_in_progress = False # Number of total onboardings we've done. self.onboardings = 0 # Multiplication hack. self.operational_work = SRE_BASELINE_OPERATIONAL # How long the sim has gone on for (I believe you can get this from # the simpy env object, but I was on a plane and couldn't look it up) self.ticks = 0 # The history of what assignments were made (i.e. put into the work queue). self.assigned_history_dict = collections.defaultdict(list) # The history of what work was performed self.performed_history_dict = collections.defaultdict(list) # Per-cycle tracking self.tracking = collections.defaultdict(int) def run(self, env): """Run the simulation with this SRE team object.""" print("considering work") while True: self.ticks += 1 # If I have no work items, assign a default distribution... if len(self.work_items) == 0: print("assigning work; default distribution") self.work_items = collections.deque(SRE_WORK_DISTRIBUTION[:]) else: # Otherwise take a census of what work was done (during # which some useful housekeeping is tracked), and assign/process work. self.census(self.env) self.assign_work() self.process_work() # Return back to simulation. yield env.timeout(1) def add_work(self, work_type): """Add work of specifed type at the right end.""" self.work_items.append(work_type) def assign_work(self): """Assign work to the SRE team. This should be in a policy object, but it's hard-coded for now.""" # 10% chance of having a cross team project. if random.randint(1,10) > 9: print ("assigning cross team") self.add_work(SRE_WORK_TYPES.CROSS_TEAM_PROJECT) # This is a hacky representation of a cross-team project # solving other problems... need to find a better way. # If we have a cross team, remove two operationals and an # in-team. Other possibilities exist. self.clear_first_of_type(SRE_WORK_TYPES.OPERATIONAL) self.clear_first_of_type(SRE_WORK_TYPES.OPERATIONAL) self.clear_first_of_type(SRE_WORK_TYPES.IN_TEAM_PROJECT) # 20% chance of an onboarding per tick, but only do it if we're # not already doing one and are below our max. if (random.randint(1,10) > 8 and self.onboarding_in_progress is False and self.onboardings < SRE_TEAM_ONBOARDINGS_LIMIT): print ("assigning onboarding") self.onboarding_in_progress = True self.onboardings += 1 self.add_work(SRE_WORK_TYPES.ONBOARDING) # Unconditionally: scale up our operational work as a proportion of # onboarded systems and "quarterly" growth. self.add_scaled_operational() print ("post assigned work: len", len(self.work_items)) print ("onboardings: ", self.onboardings) def process_work(self): """Process the work we have in our local queue.""" # State variables to allow us to implement things like a limit on # operational work. op_counter = 0 capacity = 0 self.tracking.clear() # Process what work we have up to our allowed limit, potentially # avoiding doing some kinds. while capacity < SRE_TEAM_CAPACITY: # Pop work items from the left, push onto the right try: work_item = self.work_items.popleft() if work_item is SRE_WORK_TYPES.IN_TEAM_PROJECT: print ("found in team project") self.work_items.append(work_item) self.tracking[SRE_WORK_TYPES.IN_TEAM_PROJECT] += 1 capacity += 1 elif (work_item is SRE_WORK_TYPES.OPERATIONAL) and (op_counter < 0.5 * SRE_TEAM_CAPACITY): print ("found operational") op_counter += 1 capacity += 1 self.tracking[SRE_WORK_TYPES.OPERATIONAL] += 1 elif (work_item is SRE_WORK_TYPES.OPERATIONAL) and (op_counter >= 0.5 * SRE_TEAM_CAPACITY): print ("passing on operational work because over threshold") pass elif work_item is SRE_WORK_TYPES.CROSS_TEAM_PROJECT: print ("found cross team project") # "policy": 50% chance that cross team work will give you more cross team work, # e.g. that there's project run-over if random.randint(1,10) > 5: self.add_work(SRE_WORK_TYPES.CROSS_TEAM_PROJECT) capacity += 1 self.tracking[SRE_WORK_TYPES.CROSS_TEAM_PROJECT] += 1 elif work_item is SRE_WORK_TYPES.ONBOARDING: # "policy" -- an onboarding gives you a siloed project and # an operational work. self.add_work(SRE_WORK_TYPES.IN_TEAM_PROJECT) self.add_work(SRE_WORK_TYPES.OPERATIONAL) self.onboarding_in_progress = False capacity += 2 self.tracking[SRE_WORK_TYPES.CROSS_TEAM_PROJECT] += 1 except IndexError: print ("Hmm, work_items is empty.") break print ("post process work: assignable") print (collections.Counter(self.work_items).most_common()) print ("post process work: performed") print (collections.Counter(self.tracking).most_common()) def add_default_operational(self): """Default method I think no longer use.""" for x in range(4): self.add_work(SRE_WORK_TYPES.OPERATIONAL) def add_scaled_operational(self): """Scale the operational work in our queue by some function of growth.""" new_operational_work = int(round(self.operational_work * QUARTERLY_GROWTH) + self.onboardings) delta = new_operational_work - self.operational_work if self.operational_work < SRE_TEAM_MAX_OPERATIONAL: for x in range(delta): self.add_work(SRE_WORK_TYPES.OPERATIONAL) def census(self, env, printing=False): """Display the work that's been done, and record the history of it.""" print ("census -- %s work items" % len(self.work_items)) unused_work_types = [1, 2, 3, 4] if printing: print ("assignable work") print (collections.Counter(self.work_items).most_common()) if printing: print ("performed work") print (self.tracking) for k, v in collections.Counter(self.work_items).most_common(): self.assigned_history_dict[k].append(v) if k in unused_work_types: unused_work_types.remove(k) # We end up with a complete history of what work types were assigned, # including ones that were 0. for work_type in unused_work_types: self.assigned_history_dict[work_type].append(0) # Now do again for performed work unused_work_types = [1, 2, 3, 4] for k, v in collections.Counter(self.tracking).most_common(): self.performed_history_dict[k].append(v) if k in unused_work_types: unused_work_types.remove(k) # We end up with a complete history of what work types were assigned, # including ones that were 0. for work_type in unused_work_types: self.performed_history_dict[work_type].append(0) def clear_first_of_type(self, supplied_type): """Look through work queue and remove the first of the specified type.""" try: self.work_items.remove(supplied_type) except ValueError: return 0 def sum_total_work(self): """Sum the total work done (unused right now).""" sums = [] for x in range(1, self.ticks): sums.append(self.assigned_history_dict[1][x] + self.assigned_history_dict[2][x] + self.assigned_history_dict[3][x] + self.assigned_history_dict[4][x]) return sums def twod_graphing_setup(title, op, in_team, cross_team, onboarding): # The x locations for the groups ind = numpy.arange(sre_team.ticks) # the width of the bars: can also be len(x) sequence width = 0.35 # Plot colours p1 = plt.bar(ind, op, width, color='green') p2 = plt.bar(ind, in_team, width, bottom=op, color='blue') p3 = plt.bar(ind, cross_team, width, bottom=in_team, color='red') p4 = plt.bar(ind, onboarding, width, bottom=cross_team, color='yellow') # Legend, etc plt.ylabel('Work graphing, SRE') plt.title(title) plt.legend( (p1[0], p2[0], p3[0], p4[0]), ('Operational', 'In-team', 'Cross-team', 'Onboarding') ) # Display plt.show() env = simpy.Environment() sre_team = SRE_team(env) env.run(until=SIM_DURATION) sre_team.census(env, printing=True) twod_graphing_setup("Work available for doing", sre_team.assigned_history_dict[SRE_WORK_TYPES.OPERATIONAL], sre_team.assigned_history_dict[SRE_WORK_TYPES.IN_TEAM_PROJECT], sre_team.assigned_history_dict[SRE_WORK_TYPES.CROSS_TEAM_PROJECT], sre_team.assigned_history_dict[SRE_WORK_TYPES.ONBOARDING]) twod_graphing_setup("Work actually performed", sre_team.performed_history_dict[SRE_WORK_TYPES.OPERATIONAL], sre_team.performed_history_dict[SRE_WORK_TYPES.IN_TEAM_PROJECT], sre_team.performed_history_dict[SRE_WORK_TYPES.CROSS_TEAM_PROJECT], sre_team.performed_history_dict[SRE_WORK_TYPES.ONBOARDING])
[ "matplotlib.pyplot.title", "matplotlib.pyplot.show", "random.randint", "matplotlib.pyplot.bar", "matplotlib.pyplot.legend", "collections.Counter", "collections.defaultdict", "numpy.arange", "simpy.Environment", "matplotlib.pyplot.ylabel", "collections.deque" ]
[((12429, 12448), 'simpy.Environment', 'simpy.Environment', ([], {}), '()\n', (12446, 12448), False, 'import simpy\n'), ((11861, 11889), 'numpy.arange', 'numpy.arange', (['sre_team.ticks'], {}), '(sre_team.ticks)\n', (11873, 11889), False, 'import numpy\n'), ((11984, 12022), 'matplotlib.pyplot.bar', 'plt.bar', (['ind', 'op', 'width'], {'color': '"""green"""'}), "(ind, op, width, color='green')\n", (11991, 12022), True, 'import matplotlib.pyplot as plt\n'), ((12030, 12083), 'matplotlib.pyplot.bar', 'plt.bar', (['ind', 'in_team', 'width'], {'bottom': 'op', 'color': '"""blue"""'}), "(ind, in_team, width, bottom=op, color='blue')\n", (12037, 12083), True, 'import matplotlib.pyplot as plt\n'), ((12091, 12151), 'matplotlib.pyplot.bar', 'plt.bar', (['ind', 'cross_team', 'width'], {'bottom': 'in_team', 'color': '"""red"""'}), "(ind, cross_team, width, bottom=in_team, color='red')\n", (12098, 12151), True, 'import matplotlib.pyplot as plt\n'), ((12159, 12225), 'matplotlib.pyplot.bar', 'plt.bar', (['ind', 'onboarding', 'width'], {'bottom': 'cross_team', 'color': '"""yellow"""'}), "(ind, onboarding, width, bottom=cross_team, color='yellow')\n", (12166, 12225), True, 'import matplotlib.pyplot as plt\n'), ((12244, 12276), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Work graphing, SRE"""'], {}), "('Work graphing, SRE')\n", (12254, 12276), True, 'import matplotlib.pyplot as plt\n'), ((12279, 12295), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (12288, 12295), True, 'import matplotlib.pyplot as plt\n'), ((12298, 12398), 'matplotlib.pyplot.legend', 'plt.legend', (['(p1[0], p2[0], p3[0], p4[0])', "('Operational', 'In-team', 'Cross-team', 'Onboarding')"], {}), "((p1[0], p2[0], p3[0], p4[0]), ('Operational', 'In-team',\n 'Cross-team', 'Onboarding'))\n", (12308, 12398), True, 'import matplotlib.pyplot as plt\n'), ((12411, 12421), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12419, 12421), True, 'import matplotlib.pyplot as plt\n'), ((4061, 4080), 'collections.deque', 'collections.deque', ([], {}), '()\n', (4078, 4080), False, 'import collections\n'), ((4681, 4710), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (4704, 4710), False, 'import collections\n'), ((4790, 4819), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (4813, 4819), False, 'import collections\n'), ((4865, 4893), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (4888, 4893), False, 'import collections\n'), ((5885, 5906), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (5899, 5906), False, 'import random\n'), ((5223, 5266), 'collections.deque', 'collections.deque', (['SRE_WORK_DISTRIBUTION[:]'], {}), '(SRE_WORK_DISTRIBUTION[:])\n', (5240, 5266), False, 'import collections\n'), ((6543, 6564), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (6557, 6564), False, 'import random\n'), ((10341, 10377), 'collections.Counter', 'collections.Counter', (['self.work_items'], {}), '(self.work_items)\n', (10360, 10377), False, 'import collections\n'), ((10801, 10835), 'collections.Counter', 'collections.Counter', (['self.tracking'], {}), '(self.tracking)\n', (10820, 10835), False, 'import collections\n'), ((9200, 9236), 'collections.Counter', 'collections.Counter', (['self.work_items'], {}), '(self.work_items)\n', (9219, 9236), False, 'import collections\n'), ((9306, 9340), 'collections.Counter', 'collections.Counter', (['self.tracking'], {}), '(self.tracking)\n', (9325, 9340), False, 'import collections\n'), ((10197, 10233), 'collections.Counter', 'collections.Counter', (['self.work_items'], {}), '(self.work_items)\n', (10216, 10233), False, 'import collections\n'), ((8490, 8511), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (8504, 8511), False, 'import random\n')]
from jesse.helpers import get_candle_source, slice_candles, np_shift, same_length import numpy as np from numba import njit,jit import talib from typing import Union from jesse.helpers import get_config from collections import namedtuple import tulipy as ti import math """ https://www.tradingview.com/script/umIHbltg/#chart-view-comment-form """ #jesse backtest '2021-01-03' '2021-03-02' def reverseema(candles: np.ndarray,source_type: str = "close", sequential: bool = False) -> Union[float, np.ndarray]: candles = slice_candles(candles, sequential) source = get_candle_source(candles, source_type=source_type) rema = fast_reverseema(source,candles) if sequential: return rema else: return rema[-1] @njit def fast_reverseema(source,candles): aa = 0.1 cc = 1 - aa ma = np.full_like(source,0) r1 = np.full_like(source,0) r2 = np.full_like(source,0) r3 = np.full_like(source,0) r4 = np.full_like(source,0) r5 = np.full_like(source,0) r6 = np.full_like(source,0) r7 = np.full_like(source,0) r8 = np.full_like(source,0) wa = np.full_like(source,0) for i in range(source.shape[0]): ma[i] = aa * source[i] + cc*ma[i-1] r1[i] = cc * ma[i] + ma[i-1] r2[i] = np.power(cc,2)*r1[i] + r1[i-1] r3[i] = np.power(cc,4)*r2[i] + r2[i-1] r4[i] = np.power(cc,8)*r3[i] + r3[i-1] r5[i] = np.power(cc,16)*r4[i] + r4[i-1] r6[i] = np.power(cc,32)*r5[i] + r5[i-1] r7[i] = np.power(cc,64)*r6[i] + r6[i-1] r8[i] = np.power(cc,128)*r7[i] + r7[i-1] wa[i] = ma[i] - aa * r8[i] return wa
[ "jesse.helpers.slice_candles", "numpy.power", "numpy.full_like", "jesse.helpers.get_candle_source" ]
[((526, 560), 'jesse.helpers.slice_candles', 'slice_candles', (['candles', 'sequential'], {}), '(candles, sequential)\n', (539, 560), False, 'from jesse.helpers import get_candle_source, slice_candles, np_shift, same_length\n'), ((575, 626), 'jesse.helpers.get_candle_source', 'get_candle_source', (['candles'], {'source_type': 'source_type'}), '(candles, source_type=source_type)\n', (592, 626), False, 'from jesse.helpers import get_candle_source, slice_candles, np_shift, same_length\n'), ((831, 854), 'numpy.full_like', 'np.full_like', (['source', '(0)'], {}), '(source, 0)\n', (843, 854), True, 'import numpy as np\n'), ((863, 886), 'numpy.full_like', 'np.full_like', (['source', '(0)'], {}), '(source, 0)\n', (875, 886), True, 'import numpy as np\n'), ((895, 918), 'numpy.full_like', 'np.full_like', (['source', '(0)'], {}), '(source, 0)\n', (907, 918), True, 'import numpy as np\n'), ((927, 950), 'numpy.full_like', 'np.full_like', (['source', '(0)'], {}), '(source, 0)\n', (939, 950), True, 'import numpy as np\n'), ((959, 982), 'numpy.full_like', 'np.full_like', (['source', '(0)'], {}), '(source, 0)\n', (971, 982), True, 'import numpy as np\n'), ((991, 1014), 'numpy.full_like', 'np.full_like', (['source', '(0)'], {}), '(source, 0)\n', (1003, 1014), True, 'import numpy as np\n'), ((1023, 1046), 'numpy.full_like', 'np.full_like', (['source', '(0)'], {}), '(source, 0)\n', (1035, 1046), True, 'import numpy as np\n'), ((1055, 1078), 'numpy.full_like', 'np.full_like', (['source', '(0)'], {}), '(source, 0)\n', (1067, 1078), True, 'import numpy as np\n'), ((1087, 1110), 'numpy.full_like', 'np.full_like', (['source', '(0)'], {}), '(source, 0)\n', (1099, 1110), True, 'import numpy as np\n'), ((1119, 1142), 'numpy.full_like', 'np.full_like', (['source', '(0)'], {}), '(source, 0)\n', (1131, 1142), True, 'import numpy as np\n'), ((1276, 1291), 'numpy.power', 'np.power', (['cc', '(2)'], {}), '(cc, 2)\n', (1284, 1291), True, 'import numpy as np\n'), ((1324, 1339), 'numpy.power', 'np.power', (['cc', '(4)'], {}), '(cc, 4)\n', (1332, 1339), True, 'import numpy as np\n'), ((1371, 1386), 'numpy.power', 'np.power', (['cc', '(8)'], {}), '(cc, 8)\n', (1379, 1386), True, 'import numpy as np\n'), ((1419, 1435), 'numpy.power', 'np.power', (['cc', '(16)'], {}), '(cc, 16)\n', (1427, 1435), True, 'import numpy as np\n'), ((1467, 1483), 'numpy.power', 'np.power', (['cc', '(32)'], {}), '(cc, 32)\n', (1475, 1483), True, 'import numpy as np\n'), ((1516, 1532), 'numpy.power', 'np.power', (['cc', '(64)'], {}), '(cc, 64)\n', (1524, 1532), True, 'import numpy as np\n'), ((1564, 1581), 'numpy.power', 'np.power', (['cc', '(128)'], {}), '(cc, 128)\n', (1572, 1581), True, 'import numpy as np\n')]
#! -*- coding: utf-8 -*- import json import os import numpy as np import tensorflow as tf import random as rn np.random.seed(42) rn.seed(12345) tf.set_random_seed(1234) os.environ['PYTHONHASHSEED'] = '0' from keras_bert import load_trained_model_from_checkpoint, Tokenizer import codecs from keras.layers import * from keras.models import Model import keras.backend as K import time from keras.optimizers import Adam from keras.callbacks import Callback from tqdm import tqdm import jieba import editdistance import re import numpy as np import sys from dbengine import DBEngine from calc_acc import * from check_input_feature import * from post_treat import * # from mark_acc_ensure import * from new_mark_acc_ensure import * from question_prepro import * from exceptdata import * import argparse parser = argparse.ArgumentParser() parser.add_argument('--mode', type=str, default='', help='execute mode, eg: train/test/evaluate') args = parser.parse_args() if args.mode not in set(['train', 'test', 'evaluate']): raise ValueError('Please input correct execute mode') mode = args.mode maxlen = 160 num_agg = 7 # agg_sql_dict = {0:"", 1:"AVG", 2:"MAX", 3:"MIN", 4:"COUNT", 5:"SUM", 6:"不被select"} num_op = 5 # {0:">", 1:"<", 2:"==", 3:"!=", 4:"不被select"} num_cond_conn_op = 3 # conn_sql_dict = {0:"", 1:"and", 2:"or"} csel_num = 20 # col cnt 最大为20 # learning_rate = 5e-5 learning_rate = 1e-5 # from 15 to 8 min_learning_rate = 1e-5 PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 toy = False toy_data_cnt = 200 except_cnt = 0 config_path = os.path.join(model_bert_wwm_path, 'chinese-bert_chinese_wwm_L-12_H-768_A-12/bert_config.json') checkpoint_path = os.path.join(model_bert_wwm_path, 'chinese-bert_chinese_wwm_L-12_H-768_A-12/bert_model.ckpt') dict_path = os.path.join(model_bert_wwm_path, 'chinese-bert_chinese_wwm_L-12_H-768_A-12/vocab.txt') weight_save_path = os.path.join(model_path, 'weights/nl2sql_finetune_add_div2.weights') # weight_save_path = os.path.join(model_path, 'weights/nl2sql_finetune_add_div_goodest_0.804.weights') def read_data(data_file, table_file): data, tables = [], {} with open(data_file) as f: for l in f: data.append(json.loads(l)) with open(table_file) as f: for l in f: l = json.loads(l) d = {} d['headers'] = l['header'] d['header2id'] = {j: i for i, j in enumerate(d['headers'])} d['content'] = {} d['keywords'] = {} d['all_values'] = set() d['types'] = l['types'] d['title'] = l['title'] rows = np.array(l['rows']) for i, h in enumerate(d['headers']): d['content'][h] = set(rows[:, i]) if d['types'][i] == 'text': d['keywords'][i] = '' # get_key_words(d['content'][h]) else: d['keywords'][i] = '' d['all_values'].update(d['content'][h]) # print(d['keywords']) d['all_values'] = set([i for i in d['all_values'] if hasattr(i, '__len__')]) tables[l['id']] = d if toy: data = data[:toy_data_cnt] return data, tables if mode != 'test': train_data, train_tables = read_data( os.path.join(train_data_path, 'train.json'), os.path.join(train_data_path, 'train.tables.json') ) # 41522 5013 valid_data, valid_tables = read_data( os.path.join(valid_data_path, 'val.json'), os.path.join(valid_data_path, 'val.tables.json') ) # 4396 1197 test_data, test_tables = read_data( os.path.join(test_file_path, 'final_test.json'), os.path.join(test_file_path, 'final_test.tables.json') ) token_dict = {} with codecs.open(dict_path, 'r', 'utf8') as reader: for line in reader: token = line.strip() token_dict[token] = len(token_dict) class OurTokenizer(Tokenizer): def _tokenize(self, text): R = [] for c in text: if c in self._token_dict: R.append(c) elif self._is_space(c): R.append('[unused1]') else: R.append('[UNK]') return R tokenizer = OurTokenizer(token_dict) def seq_padding(X, padding=0, maxlen=None): if maxlen is None: L = [len(x) for x in X] ML = max(L) else: ML = maxlen return np.array([ np.concatenate([x[:ML], [padding] * (ML - len(x))]) if len(x[:ML]) < ML else x for x in X ]) class data_generator: def __init__(self, data, tables, batch_size=32): # 32 to 256 for cpu , 32 for gpu self.data = data self.tables = tables self.batch_size = batch_size self.steps = len(self.data) // self.batch_size if len(self.data) % self.batch_size != 0: self.steps += 1 def __len__(self): return self.steps def __iter__(self): while True: if PY2: idxs = range(len(self.data)) elif PY3: idxs = [x for x in range(len(self.data))] np.random.shuffle(idxs) X1, X2, XM, H, HM, SEL, CONN, CSEL0, COP = [], [], [], [], [], [], [], [], [] CSEL1, CSEL2 = [], [] CDIV = [] for i in idxs: d = self.data[i] ori_q = d['question'] d['question'] = trans_question_acc(d['question']) t = self.tables[d['table_id']]['headers'] dtypes = self.tables[d['table_id']]['types'] x1, x2 = tokenizer.encode(d['question']) ''' 这里的xm的左侧和右侧的mask值为0, len(d['question']) 这个长度被标记为1, mask其实就是像一个盖子一样,把有用的东西盖起来,或者说标记出来对后续有用的东西。 为什么xm的左侧这个[cls]被标记为0了?因为这个位置铁打不动,长度固定就是1 同理xm右侧这个[seq]被标记为0了,因为这个[sep]没啥用这里. ''' xm = [0] + [1] * len(d['question']) + [0] h = [] for j in t: _x1, _x2 = tokenizer.encode(j) h.append(len(x1)) x1.extend(_x1) x2.extend(_x2) ''' batch中的每一个hm其实就是告诉你,前len(h)这个长度是有效的,后面都是为了凑 header_max_cnt 而pandding出来的0. padding出来的东西对loss无任何意义. ''' hm = [1] * len(h) sel = [] for j in range(len(h)): if j in d['sql']['sel']: j = d['sql']['sel'].index(j) sel.append(d['sql']['agg'][j]) else: sel.append(num_agg - 1) conn = [d['sql']['cond_conn_op']] csel0 = np.zeros(len(d['question']) + 2, dtype='int32') # 这里的0既表示padding,表示当前位置不对应任何表中的列 csel1 = np.zeros(len(d['question']) + 2, dtype='int32') csel2 = np.zeros(len(d['question']) + 2, dtype='int32') cop = np.zeros(len(d['question']) + 2, dtype='int32') + num_op - 1 cdiv = np.zeros(len(d['question']) + 2, dtype='int32') is_wrong_q = False for cond in d['sql']['conds']: # 重新在这里面弄 if d['question'] in correct_q_set: # print(d['question']) if dtypes[cond[0]] == 'real': _, start_pos, end_pos = check_num_exactly_match(cond[2], d['question']) # print(start_pos, end_pos, d['question'][start_pos: end_pos + 1]) csel0[start_pos + 1: end_pos + 1 + 1] = cond[0] + 1 cop[start_pos + 1: end_pos + 1 + 1] = cond[1] else: start_pos = d['question'].index(cond[2]) if cond[2] in d['question'] else \ d['question'].index(most_similar_2(cond[2], d['question'])) # print(start_pos, start_pos + len(cond[2]), d['question'][start_pos: start_pos + len(cond[2])]) csel0[start_pos + 1: start_pos + 1 + len(cond[2])] = cond[0] + 1 cop[start_pos + 1: start_pos + 1 + len(cond[2])] = cond[1] elif d['question'] in no_num_similar_set: # print('cond val is{}'.format(cond[2])) # print('cond val is {}, q is {} and sim is {}'.format(cond[2], most_similar_2(cond[2], d['question']))) sim = cond[2] if cond[2] in d['question'] else most_similar_2(cond[2], d['question']) start_pos = d['question'].index(sim) # print(d['question']) # print(start_pos, start_pos + len(sim), d['question'][start_pos: start_pos + len(sim)]) csel0[start_pos + 1: start_pos + len(sim) + 1] = cond[0] + 1 cop[start_pos + 1: start_pos + len(sim) + 1] = cond[1] elif d['question'] in q_one_vs_more_col_set: # print(d['question']) if check_num_exactly_match(cond[2], d['question'])[0] == 1: _, start_pos, end_pos = check_num_exactly_match(cond[2], d['question']) elif check_num_exactly_match_zero_case(cond[2], d['question'])[0] == 1: _, start_pos, end_pos = check_num_exactly_match_zero_case(cond[2], d['question']) else: raise ValueError('value error') if max(csel0[start_pos + 1: end_pos + 1 + 1]) != 0: if max(csel1[start_pos + 1: end_pos + 1 + 1]) != 0: csel2[start_pos + 1: end_pos + 1 + 1] = cond[0] + 1 else: csel1[start_pos + 1: end_pos + 1 + 1] = cond[0] + 1 else: csel0[start_pos + 1: end_pos + 1 + 1] = cond[0] + 1 cop[start_pos + 1: end_pos + 1 + 1] = cond[1] # print(start_pos, end_pos, d['question'][start_pos: end_pos + 1]) elif d['question'] in q_need_exactly_match_set: _, start_pos, end_pos = check_num_exactly_match(cond[2], d['question']) # print(d['question']) # print(start_pos, end_pos, d['question'][start_pos: end_pos + 1]) csel0[start_pos + 1: end_pos + 1 + 1] = cond[0] + 1 cop[start_pos + 1: end_pos + 1 + 1] = cond[1] elif d['question'] in q_need_exactly_match_more_strinct_set: _, start_pos, end_pos = check_num_exactly_match_zero_case(cond[2], d['question']) # print(d['question']) # print(start_pos, end_pos, d['question'][start_pos: end_pos + 1]) csel0[start_pos + 1: end_pos + 1 + 1] = cond[0] + 1 cop[start_pos + 1: end_pos + 1 + 1] = cond[1] elif d['question'] in q_text_contain_similar_set: if dtypes[cond[0]] == 'real': # 如果是数字的话,通过另外的方法判断 # print(d['question']) find_cnt, start_pos, end_pos = check_num_exactly_match_zero_case(cond[2], d['question']) if find_cnt == 1: # print(start_pos, end_pos, d['question'][start_pos: end_pos + 1]) csel0[start_pos + 1: end_pos + 1 + 1] = cond[0] + 1 cop[start_pos + 1: end_pos + 1 + 1] = cond[1] elif find_cnt == 0: val = most_similar_2(cond[2], d['question']) start_pos = d['question'].index(val) # print(start_pos, start_pos + len(sim), d['question'][start_pos: start_pos + len(sim)]) csel0[start_pos + 1: start_pos + len(val) + 1] = cond[0] + 1 cop[start_pos + 1: start_pos + len(val) + 1] = cond[1] else: # 文本 val = most_similar_2(cond[2], d['question']) start_pos = d['question'].index(val) # print(start_pos, start_pos + len(sim), d['question'][start_pos: start_pos + len(sim)]) csel0[start_pos + 1: start_pos + len(val) + 1] = cond[0] + 1 cop[start_pos + 1: start_pos + len(val) + 1] = cond[1] elif d['question'] in q_need_col_similar_set: header_name = t[cond[0]] start_pos, end_pos, match_val = alap_an_cn_mark(d['question'], header_name, cond[2]) csel0[start_pos + 1: end_pos + 1] = cond[0] + 1 cop[start_pos + 1: end_pos + 1] = cond[1] # print(d['question']) # print(start_pos, end_pos, d['question'][start_pos: end_pos]) else: is_wrong_q = True ab = True if ab: for idx in range(1, len(csel0) - 1): if csel0[idx] != csel0[idx - 1] and csel0[idx - 1] != 0 and csel0[idx] != 0: # print(d['question']) cdiv[idx] = 1 # print(cdiv) if len(x1) > maxlen or is_wrong_q : continue X1.append(x1) # bert的输入 X2.append(x2) # bert的输入 XM.append(xm) # 输入序列的mask H.append(h) # 列名所在位置 HM.append(hm) # 列名mask SEL.append(sel) # 被select的列 CONN.append(conn) # 连接类型 CSEL0.append(csel0) # 条件中的列 CSEL1.append(csel1) # 条件中的列 CSEL2.append(csel2) # 条件中的列 COP.append(cop) # 条件中的运算符(同时也是值的标记) CDIV.append(cdiv) # if len(X1) == self.batch_size: X1 = seq_padding(X1) X2 = seq_padding(X2) XM = seq_padding(XM, maxlen=X1.shape[1]) H = seq_padding(H) HM = seq_padding(HM) SEL = seq_padding(SEL) CONN = seq_padding(CONN) CSEL0 = seq_padding(CSEL0, maxlen=X1.shape[1]) CSEL1 = seq_padding(CSEL1, maxlen=X1.shape[1]) CSEL2 = seq_padding(CSEL2, maxlen=X1.shape[1]) CDIV = seq_padding(CDIV, maxlen=X1.shape[1]) COP = seq_padding(COP, maxlen=X1.shape[1]) yield [X1, X2, XM, H, HM, SEL, CONN, CSEL0, CSEL1, CSEL2, COP, CDIV], None X1, X2, XM, H, HM, SEL, CONN, CSEL0, COP = [], [], [], [], [], [], [], [], [] CSEL1, CSEL2 = [], [] CDIV = [] else: pass def seq_gather(x): """seq是[None, seq_len, s_size]的格式, idxs是[None, n]的格式,在seq的第i个序列中选出第idxs[i]个向量, 最终输出[None, n, s_size]的向量。 seq_gather[x, h] """ seq, idxs = x idxs = K.cast(idxs, 'int32') # must int 32 return K.tf.batch_gather(seq, idxs) train_D = data_generator(train_data, train_tables) #get Train data #valid_D = data_generator(valid_data, valid_tables) #get Train data bert_model = load_trained_model_from_checkpoint(config_path, checkpoint_path, seq_len=None) for l in bert_model.layers: l.trainable = True x1_in = Input(shape=(None,), dtype='int32') x2_in = Input(shape=(None,)) xm_in = Input(shape=(None,)) h_in = Input(shape=(None,), dtype='int32') hm_in = Input(shape=(None,)) sel_in = Input(shape=(None,), dtype='int32') conn_in = Input(shape=(1,), dtype='int32') csel0_in = Input(shape=(None,), dtype='int32') csel1_in = Input(shape=(None,), dtype='int32') csel2_in = Input(shape=(None,), dtype='int32') cop_in = Input(shape=(None,), dtype='int32') cdiv_in = Input(shape=(None,), dtype='int32') x1, x2, xm, h, hm, sel, conn, csel0, csel1, csel2, cop, cdiv = ( x1_in, x2_in, xm_in, h_in, hm_in, sel_in, conn_in, csel0_in, csel1_in, csel2_in, cop_in, cdiv_in ) hm = Lambda(lambda x: K.expand_dims(x, 1))(hm) # header的mask.shape=(None, 1, h_len) x = bert_model([x1_in, x2_in]) # shape x [?, ?, 768] [batch_size, n_step(n_input_step), hidden_size] x4conn = Lambda(lambda x: x[:, 0])(x) #x[:, 0]是获取每个训练样本的输入的第0个step,也就是用来判断条件之间关联运算符 [None, hidden_size] pconn = Dense(num_cond_conn_op, activation='softmax')(x4conn) # [None, num_cond_conn_op] # h记录各个header[cls]所在的位置, 这个seq_gather的作用就是把input_x中的header[cls]搞出来。 x4h = Lambda(seq_gather)([x, h]) # header [cls] is selected [batch_size, header_step, hidden_size] psel = Dense(num_agg, activation='softmax')(x4h) # [bs, header_step, num_agg] pcop = Dense(num_op, activation='softmax')(x) # [bs, q_step, num_op] x_ori = x x = Lambda(lambda x: K.expand_dims(x, 2))(x) # shape [batch_size, n_step, 1, hidden_size] x4h_ori = x4h x4h = Lambda(lambda x: K.expand_dims(x, 1))(x4h) # header cls selected in x4h [None, 1, header_n_step, hidden_size ] pcsel_1 = Dense(1)(x) # [None, q_n_step, 1 ,1] pcsel_2 = Dense(1)(x4h) # [None, 1, h_n_step, 1 ] pcsel_att = Lambda(lambda x: x[0] * x[1])([pcsel_1, pcsel_2]) # [None, q_n_step, h_n_step,1] pcsel_att = Lambda(lambda x: x[..., 0])(pcsel_att) # [None,q_n_step,h_n_step] #x4h_ori [None, h_n_step,hidden_size】 pcsel_h_part = Lambda(lambda x: K.batch_dot(x[0], x[1]))([pcsel_att, x4h_ori]) # [None, q_n_step, hidden_siz] #pcsel = Lambda(lambda x: K.batch_dot(x[0], x[1]))([att_val, x4h_ori]) # [None, q_n_step, hidden_size] #pcsel = Lambda(lambda x: x[0] + x[1])([x_ori, pcsel_h_part]) # [None, q_n_step, hidden] pcsel = concatenate([x_ori, pcsel_h_part], axis=-1) # pcsel = Dropout(0.2)(pcsel) # 支持 cdiv # new add pcsel = Dense(1200, activation='relu')(pcsel) #[None, q_n_step, 1200] 看看这个对于缓解 loss 作用大不大 梯度爆炸 pcdiv = Dense(2, activation='softmax')(pcsel) # # ## add Drop out layer # # pcsel = Dense(1200, activation='relu')(pcsel) #[None, q_n_step, 1200] # pcsel = Lambda(lambda x: x, output_shape=lambda s:s)(pcsel) # pcsel = Reshape((-1, 3, 400))(pcsel) # #pcsel = Lambda(lambda x: K.reshape(x, (-1, 3, 400)))(pcsel) # header的mask.shape=(None, 1, h_len) # pcsel = concatenate([x_ori, pcsel_h_part], axis=-1) pcsel0 = Dense(csel_num, activation='softmax')(pcsel) # [bs, q_step, 3, num_op] pcsel1 = Dense(csel_num, activation='softmax')(pcsel) # [bs, q_step, 3, num_op] pcsel2 = Dense(csel_num, activation='softmax')(pcsel) # [bs, q_step, 3, num_op] # Model的参数 def __init__(self, inputs, outputs, name=None): model = Model( [x1_in, x2_in, h_in, hm_in], # inputs [psel, pconn, pcop, pcsel0, pcsel1, pcsel2, pcdiv] # outputs ) # shuai 这里看看是不是要加载一个已经训练出来的模型?? train_model = Model( [x1_in, x2_in, xm_in, h_in, hm_in, sel_in, conn_in, csel0_in, csel1_in, csel2_in, cop_in, cdiv_in], [psel, pconn, pcop, pcsel0, pcsel1, pcsel2, pcdiv] ) ''' mask存在的意义是什么? 为什么被mask的位置要用1,而padding要用0??? (1) mask的位置说明这个位置的数据是有效的,我们后续会专门把为1的部分拿出来,比如计算损失等 (2) 在训练过程中,数据会以batch的形式进行组织,例如batch_size=16, 在这16组训练数据中,以question长度为例,这16组数据的question长度是不同的,那么一般会这样做: 获取这16个question中的长度最大值,然后question中的有效部分会通过mask 1值来记录,而question中未达到max_len的部分会通过padding 0标记. 所以其实这个mask并没有很神奇,只不过是为了标记一下哪些位置是"有用的",而且后续计算损失等会"保留"的. ''' xm = xm # question的mask.shape=(None, x_len) hm = hm[:, 0] # header的mask.shape=(None, h_len) # 这个操作就是去掉1,torch中有squeeze压紧方法做这个事情 # condition mask, [1, 0, 1, 1,1 ] 如果元素为1,说明当前位置的op不是空操作 cm = K.cast(K.not_equal(cop, num_op - 1), 'float32') # conds的mask.shape=(None, x_len) # 注意hm & xm 用在啥地方了 ''' 例子1: 以psel_loss = K.sum(psel_loss * hm) / K.sum(hm) 为例介绍这里的hm的用处. 首先 hm作为header mask, 里面存储的都是header[cls]的位置 hm的shape为[bs, header_cnt], header_cnt这个维度里面的值有一些padding的0 psel_loss 的shape为 [bs, header_cnt] ? psel_loss * hm 的shape为 [bs, header_cnt] 相乘之后即只关注有效header的损失,那些padding出来的不要加入损失计算 k.sum(psel_loss * hm) keras.backend中的sum和普通的sum不同,他会将矩阵中的所有值相加,最后结果为一个值 几乎所有参数都是带有batch_size维度的,因为计算损失是在整个batch上计算的 ''' print(pcsel.get_shape()[2]) print(type(pcsel)) #pcsel0 = pcsel[32, int(pcsel.get_shape()[2]), 1, 20] #print(pcsel0.get_shape()) psel_loss = K.sparse_categorical_crossentropy(sel_in, psel) psel_loss = K.sum(psel_loss * hm) / K.sum(hm) # case: test10 padding位置的header不纳入损失计算 pconn_loss = K.sparse_categorical_crossentropy(conn_in, pconn) pconn_loss = K.mean(pconn_loss) # 取均值,是为了算在整个batch中的损失 pcop_loss = K.sparse_categorical_crossentropy(cop_in, pcop) pcop_loss = K.sum(pcop_loss * xm) / K.sum(xm) pcsel0_loss = K.sparse_categorical_crossentropy(csel0_in, pcsel0) pcsel0_loss = K.sum(pcsel0_loss * xm * cm) / K.sum(xm * cm) pcsel1_loss = K.sparse_categorical_crossentropy(csel1_in, pcsel1) pcsel1_loss = K.sum(pcsel1_loss * xm * cm) / K.sum(xm * cm) pcsel2_loss = K.sparse_categorical_crossentropy(csel2_in, pcsel2) pcsel2_loss = K.sum(pcsel2_loss * xm * cm) / K.sum(xm * cm) pcdiv_loss = K.sparse_categorical_crossentropy(cdiv_in, pcdiv) pcdiv_loss = K.sum(pcdiv_loss * xm * cm) / K.sum(xm * cm) loss = psel_loss + pconn_loss + pcop_loss + pcsel0_loss + pcsel1_loss + pcsel2_loss + pcdiv_loss train_model.add_loss(loss) train_model.compile(optimizer=Adam(learning_rate)) # train_model.summary() model.load_weights(weight_save_path) # except_tr_cnt = 0 log_file = open('./asser_log.log', 'w') assert_wrong_log_file = open('./asser_wrong_log.log', 'w') def nl2sql(question, table): """输入question和headers,转SQL """ try: question = trans_question_acc(question) question = trans_question_short_year(question) # shuai question = question.replace('负数', '小于0') question = question.replace('负值', '小于0') question = question.replace('为负', '小于0') question = question.replace('正数', '大于0') question = question.replace('正值', '大于0') question = question.replace('为正', '大于0') question = question.replace('没什么要求', '不限') question = question.replace('没要求', '不限') except: pass #raise ValueError x1, x2 = tokenizer.encode(question) if question in set([ '总收入高于500万或者座位数大于5000个的场馆有多少个啊', '有多少个场馆的座位超过了5000个或者收入超过了500万' ]): print(question) print(question) h = [] for i in table['headers']: _x1, _x2 = tokenizer.encode(i) # h这里记录了每个header的[cls]所在位置 h.append(len(x1)) x1.extend(_x1) x2.extend(_x2) hm = [1] * len(h) # hm为header在[cls]位置的mask, hm的长度,正好是header的个数,当然header的个数和[cls]的个数是一致的 psel, pconn, pcop, pcsel0, pcsel1, pcsel2, pcdiv = model.predict([ np.array([x1]), np.array([x2]), np.array([h]), np.array([hm]) ]) if max(pcsel2[0][1:len(question) + 1].argmax(1)) > 0: pass # print('pcsel is > 0 with q \n {}\nand pcsel is :{}\n'.format(question, pcsel2[0][1:len(question) + 1].argmax(1))) pcsel_ori = pcsel # pcsel0 = np.squeeze(pcsel[:,:,:1,:], axis=(2,)) # numpy 不能是tensor哈 ,返回是numpy格式数据 # test if max(pcdiv[0][0:len(question) + 1].argmax(1)) > 0: pass # print(question) # print(pcdiv[0][0:len(question) + 1].argmax(1)) # print(pcop[0][0:len(question) + 1].argmax(1)) # print(pcsel0[0][0:len(question) + 1].argmax(1)) # print('\ncop and csel is ---------\n') # pcsel1 = np.squeeze(pcsel[:,:,1:2,:], axis=(2,)) ''' if max(pcsel1[0][1:len(question) + 1].argmax(1)) > 0: print('\nmul col ---------\n') print(question) print(pcop[0][0:len(question) + 1].argmax(1)) print(pcsel0[0][0:len(question) + 1].argmax(1)) print(pcsel1[0][0:len(question) + 1].argmax(1)) else: print('\single op and col ---------\n') print(question) print(pcop[0][0:len(question) + 1].argmax(1)) print(pcsel0[0][0:len(question) + 1].argmax(1)) print('\pcdiv is ---------\n') print(pcdiv[0][0:len(question) + 1].argmax(1)) print('\pconn is ---------\n') print(pconn[0, 1:].argmax()) ''' R = {'agg': [], 'sel': []} # psel是对header的[CLS]位置做处理的出来的,各个header的聚合或者是否被select的概率。 # psel shape [1, 9, 7] => [None, header_col_cnt, op] for i, j in enumerate(psel[0].argmax(1)): if j != num_agg - 1: # num_agg-1类是不被select的意思 # 7中状态拆分成下面两种,1种是是否被选择,另外一种是agg operation R['sel'].append(i) R['agg'].append(j) conds = [] v_op = -1 # pcop: shape [bs, seq_len(n_step), num_op] 下面截取了:len(question) + 1 # 截取之后shape: [bs, question_len] # 在这里的bs=1, 貌似是对每一个样例做的处理. # pcop (1, 103, 5) => [None, question+header_len, op_len] # 这里的pcop的第二个维度为105 # 105 = 32(question len) + 2(question cls&sep)+ 53(all header col len) +18(header cls+sep,total 9 column in table) # 下面取的时候只取了 [0:33] unit_first_list = [] unit_second_list = [] for i, j in enumerate(pcop[0, :len(question) + 1].argmax(1)): #[,,op_cnt] # 这里结合标注和分类来预测条件 if i == 0: continue # start 0 is of no use if j != num_op - 1: # num_op: {0:">", 1:"<", 2:"==", 3:"!=", 4:"不被select"} if v_op != j: if v_op != -1: v_end = v_start + len(v_str) v_start_idx, v_end_idx, smooth_val = smooth_numeric(v_start - 1, v_end - 1, question) unit_first, unit_second = get_append_unit(v_start - 1, v_end - 1, question) # unit_firt: 亿 unit_second: 元 # 添加div中的信息 # print(max(pcdiv[0][v_start: v_end].argmax(1))) if max(pcdiv[0][v_start: v_end].argmax(1)) > 0:# 0 # print(smooth_val) if 1 in pcdiv[0][v_start: v_end].argmax(1): entity_start_pos_list = [v_start + 1 + idx for idx, mark in enumerate(pcdiv[0][v_start + 1: v_end].argmax(1)) if mark == 1] if entity_start_pos_list[0] != v_start: entity_start_pos_list.insert(0, v_start) if entity_start_pos_list[-1] != v_end: entity_start_pos_list.append(v_end) for idx in range(len(entity_start_pos_list) - 1): new_s = entity_start_pos_list[idx] new_e = entity_start_pos_list[idx + 1] # print(question[new_s - 1: new_e - 1]) csel = pcsel0[0][new_s: new_e].mean(0).argmax() - 1 v_str1 = question[new_s - 1: new_e - 1] if v_str1 is not None and csel >= 0: unit_first_list.append(unit_first) unit_second_list.append(unit_second) conds.append((csel, v_op, v_str1)) # print(conds) else: csel = pcsel0[0][v_start: v_end].mean(0).argmax() - 1 if v_str is not None: v_str = smooth_val unit_first_list.append(unit_first) unit_second_list.append(unit_second) conds.append((csel, v_op, v_str)) # print('here--') # print(pcsel1[0][v_start: v_end].argmax(1)) if pcsel1[0][v_start: v_end].mean(0).argmax() - 1 >= 0: # add csel = pcsel1[0][v_start: v_end].mean(0).argmax() - 1 if csel >= 0: ''' print('warnings_ok ---- ') print(question) print((csel, v_op, v_str)) ''' if v_str is not None: v_str = smooth_val unit_first_list.append(unit_first) unit_second_list.append(unit_second) conds.append((csel, v_op, v_str)) if pcsel2[0][v_start: v_end].mean(0).argmax() - 1 > 0: # add csel = pcsel2[0][v_start: v_end].mean(0).argmax() - 1 ''' print('warnings_ok ---- ') print(question) print((csel, v_op, v_str)) ''' if v_str is not None: v_str = smooth_val unit_first_list.append(unit_first) unit_second_list.append(unit_second) conds.append((csel, v_op, v_str)) v_start = i v_op = j # v_op在这里第一次赋值 v_str = question[i - 1] # v_str在这里第一次赋值 else: # 在 这里 j == num_op-1,说明当前运算符在question上延续着 v_str += question[i - 1] if i == len(question): v_end = v_start + len(v_str) v_start_idx, v_end_idx, smooth_val = smooth_numeric(v_start - 1, v_end - 1, question) unit_first, unit_second = get_append_unit(v_start - 1, v_end - 1, question) # unit_firt: 亿 unit_second: 元 # 添加div中的信息 # print(max(pcdiv[0][v_start: v_end].argmax(1))) if max(pcdiv[0][v_start: v_end].argmax(1)) > 0:# 0 # print(smooth_val) if 1 in pcdiv[0][v_start: v_end].argmax(1): entity_start_pos_list = [v_start + 1 + idx for idx, mark in enumerate(pcdiv[0][v_start + 1: v_end].argmax(1)) if mark == 1] if entity_start_pos_list[0] != v_start: entity_start_pos_list.insert(0, v_start) if entity_start_pos_list[-1] != v_end: entity_start_pos_list.append(v_end) for idx in range(len(entity_start_pos_list) - 1): new_s = entity_start_pos_list[idx] new_e = entity_start_pos_list[idx + 1] # print(question[new_s - 1: new_e - 1]) csel = pcsel0[0][new_s: new_e].mean(0).argmax() - 1 v_str1 = question[new_s - 1: new_e - 1] if v_str1 is not None and csel >= 0: unit_first_list.append(unit_first) unit_second_list.append(unit_second) conds.append((csel, v_op, v_str1)) # print(conds) else: # print('here_break--') # print(pcsel1[0][v_start: v_end].argmax(1)) if pcsel1[0][v_start: v_end].mean(0).argmax() - 1 >= 0: # add csel = pcsel1[0][v_start: v_end].mean(0).argmax() - 1 if csel >= 0: ''' print('warnings_ok ---- ') print(question) print((csel, v_op, v_str)) ''' if v_str is not None: v_str = smooth_val unit_first_list.append(unit_first) unit_second_list.append(unit_second) conds.append((csel, v_op, v_str)) if pcsel2[0][v_start: v_end].mean(0).argmax() - 1 >= 0: # add csel = pcsel2[0][v_start: v_end].mean(0).argmax() - 1 ''' print('warnings_ok ---- ') print(question) print((csel, v_op, v_str)) if v_str is not None: v_str = smooth_val unit_first_list.append(unit_first) unit_second_list.append(unit_second) conds.append((csel, v_op, v_str)) ''' csel = pcsel0[0][v_start: v_end].mean(0).argmax() - 1 if v_str is not None: v_str = smooth_val unit_first_list.append(unit_first) unit_second_list.append(unit_second) conds.append((csel, v_op, v_str)) # print(conds) break elif v_op != -1: # 遇到了"not selected" 了 v_end = v_start + len(v_str) # pcsel (1, 105, 9) => (None, q_len+h_len, col_cnt ) # 第二个维度为105, 105 = 32(question len)+2(question cls&sep)+ 53(all header col len) +18(header cls+sep,total 9 column in table # pcsel的作用是定位question中的每个字段对应header中的哪个列,所以最后一维为9,当前测试样例的表有9列 v_start_idx, v_end_idx, smooth_val = smooth_numeric(v_start - 1, v_end - 1, question) unit_first, unit_second = get_append_unit(v_start - 1, v_end - 1, question) # unit_firt: 亿 unit_second: 元 # 添加div中的信息 # print(max(pcdiv[0][v_start: v_end].argmax(1))) if max(pcdiv[0][v_start: v_end].argmax(1)) > 0: ''' print(question) print(smooth_val) print(v_start) print(v_end) print(pcdiv[0][v_start: v_end].argmax(1)) ''' if 1 in pcdiv[0][v_start: v_end].argmax(1) and pcdiv[0][v_start].argmax() != 1 : entity_start_pos_list = [v_start + 1 + idx for idx, mark in enumerate(pcdiv[0][v_start + 1: v_end].argmax(1)) if mark == 1] # print(entity_start_pos_list) if entity_start_pos_list[0] != v_start: entity_start_pos_list.insert(0, v_start) if entity_start_pos_list[-1] != v_end: entity_start_pos_list.append(v_end) for idx in range(len(entity_start_pos_list) - 1): new_s = entity_start_pos_list[idx] new_e = entity_start_pos_list[idx + 1] # print(question[new_s - 1: new_e - 1]) csel = pcsel0[0][new_s: new_e].mean(0).argmax() - 1 v_str1 = question[new_s - 1: new_e - 1] if v_str1 is not None and csel >= 0: unit_first_list.append(unit_first) unit_second_list.append(unit_second) conds.append((csel, v_op, v_str1)) # print(conds) else: csel = pcsel0[0][v_start: v_end].mean(0).argmax() - 1 # 做一些处理 v_e = v_end - 1 untreat_unit = '' if v_e < len(question) and len(re.findall(regex_tail, question[v_e])) > 0: untreat_unit = re.findall(regex_tail, question[v_e])[0] # print('unit is{}, first{}'.format(untreat_unit)) if v_e + 1 < len(question) and len(re.findall(regex_tail, question[v_e + 1])) > 0: untreat_unit += re.findall(regex_tail, question[v_e + 1])[0] if untreat_unit != '': pass # print('untreat_unit is not null and is{} and q is {}\n and v_str is {} \n '.format(untreat_unit, question, v_str)) if v_str is not None: v_str = smooth_val unit_first_list.append(unit_first) unit_second_list.append(unit_second) conds.append((csel, v_op, v_str)) # print('here--') # print(pcsel1[0][v_start: v_end].argmax(1)) if pcsel1[0][v_start: v_end].mean(0).argmax() - 1 >= 0: # add csel = pcsel1[0][v_start: v_end].mean(0).argmax() - 1 if csel >= 0: # print('warnings_ok ---- ') # print(question) # print((csel, v_op, v_str)) if v_str is not None: v_str = smooth_val unit_first_list.append(unit_first) unit_second_list.append(unit_second) conds.append((csel, v_op, v_str)) if pcsel2[0][v_start: v_end].mean(0).argmax() - 1 >= 0: # add csel = pcsel2[0][v_start: v_end].mean(0).argmax() - 1 # print('warnings_ok ---- ') # print(question) # print((csel, v_op, v_str)) if v_str is not None: v_str = smooth_val unit_first_list.append(unit_first) unit_second_list.append(unit_second) conds.append((csel, v_op, v_str)) v_op = -1 R['conds'] = set() # 集合自己去重 idx = 0 for i, j, k in conds: if re.findall('[^\d\-\.\%]', k): # 找到非数字 j = 2 # 非数字只能用等号,, # and len(re.findall('[\d\-\.\%]', k)) != len(k) # re.findall('[^\d\-\.\%]', k) # 如果目标列的所有值里面没有除数字之外的东西,那么就不要模糊匹配了 # try: # col_table_vals = table['content'][table['headers'][i]] # except: col_table_vals = {'--------'} # no_other_text = True # print(col_table_vals) # for val in col_table_vals: # print('val is {}'.format(val)) # if re.findall('[^\d\-\.\%]', str(val)): no_other_text = False if j == 2 : # 这里判定出条件运算符是等号哦 等号也有可能是数字的 ori_k = k before_treat = 'before of i,j, k is({},{},{})\n'.format(i, j, k) before_ikj = (i, j, k) # sqlite3 text where col1='2' 与 col2='2.0'执行结果不一致 if k not in table['all_values']: k_sim = most_similar_new(k, list(table['all_values'])) if k_sim is not None: k = k_sim idx_except = False try: h = table['headers'][i] except: global except_cnt except_cnt += 1 idx_except = True h = table['headers'][0] # 然后检查值对应的列是否正确,如果不正确,直接修正列名 if k not in table['content'][h]: # 发现标记出来的值不在预测出来所属的列不一致。 for r, v in table['content'].items(): if k in v: i = table['header2id'][r] break # if not re.findall('[^\d\-\.\%]', ori_k): # # 字符串还是要精准匹配的,比如 2015跟2015.0 # after_ijk = (i, j, k) # if before_ikj != after_ijk: # print(before_treat) # print(types[i]) # print('after of i,j, k is({},{},{})\n'.format(i, j, k)) unit_first = None if unit_first_list[idx] == '' else unit_first_list[idx] unit_second = None if unit_second_list[idx] == '' else unit_second_list[idx] idx += 1 if not re.findall('[^\d]', str(k)) and i <= len(table['headers']) - 1: ## 需要改 不要用 isnumeric() 并要处理百分号 # 添加一个预处理,预测的数字左右缺失的话 ori_k = k try: right_str = "\n{},'{}','{}',format_of_number={}, format_desc={}\n".format(k, table['headers'][i], table['title'], unit_first, unit_second) assert_str = "assert number_trans({},'{}','{}',format_of_number='{}', format_desc='{}') ==".format(k, table['headers'][i], table['title'], unit_first, unit_second) k = number_trans(int(k), table['headers'][i], table['title'], format_of_number=unit_first, format_desc=unit_second) # print('number_trans right {} \n right param is \n{}\n'.format(question, right_str)) max_col_val = None have_text_in_col = False for col_val in table['content'][table['headers'][i]]: if not re.findall('[^\d\.]', str(col_val)): if max_col_val is None: max_col_val = float(col_val) else: max_col_val = max(max_col_val, float(col_val)) else: have_text_in_col = True break if '万平' in question: if max_col_val is not None and not re.findall('[^\d\.]', str(k)) and float(k) > max_col_val * 10: k = ori_k print('--- warining -- \n use ori {}'.format(k)) print(question) print(table['content'][table['headers'][i]]) print('max is {}'.format(max_col_val)) assert_str = assert_str + '{}'.format(k) print(assert_str) # log_file.write(assert_str) except: # print('number_trans error {} \n'.format(question)) # print("\n{},'{}','{}',format_of_number={}, format_desc={}\n".format(k, table['headers'][i], table['title'], unit_first, unit_second)) # raise assert_str = assert_str + '{}\n'.format(k) # assert_wrong_log_file.write(assert_str) #这里如果k是 数字的话,包含百分数,那么去掉后面的百分号 if not re.findall('[^\d\-\.\%]', str(k)) and '%' in str(k): # print('\n get percent val {} '.format(k)) k = str(k)[:-1] # print('percent after treate {}\n'.format(k)) R['conds'].add((i, j, k)) if max(pcsel2[0][1:len(question) + 1].argmax(1)) > 0: pass # print('pcsel cond is \n {}\n'.format(R['conds'])) R['conds'] = list(R['conds']) if len(R['conds']) <= 1: # 条件数少于等于1时,条件连接符直接为0 R['cond_conn_op'] = 0 else: # pconn (1,3) => (None, con_conn_cnt) R['cond_conn_op'] = 1 + pconn[0, 1:].argmax() # 不能是0 return R def evaluate(data, tables): pbar = tqdm() F = open('../data/logs/evaluate_pred.json', 'w') pred_sql_list = [] gd_sql_list = [] tables_list = [] for i, d in enumerate(data): question = d['question'] table = tables[d['table_id']] R = nl2sql(question, table) # # print("predicted is {}\n".format(R)) gd_sql_list.append(d['sql']) pred_sql_list.append(R) tables_list.append(d['table_id']) pbar.update(1) d['sql_pred'] = R if PY2: s = json.dumps(d, ensure_ascii=False) # add str F.write(s.encode('utf-8') + '\n') elif PY3: s = json.dumps(eval(str(R)), ensure_ascii=False) F.write(s + '\n') # F.close() acc = check_part_acc(pred_sql_list, gd_sql_list, tables_list, data) print(' Acc in evaluate data set is {}'.format(1 - acc[-1])) # data here is valid data pbar.close() return 1 - acc[-1] if mode == 'evaluate': evaluate(valid_data, valid_tables) import sys sys.exit(0) def test(data, tables, submit_path): pbar = tqdm() F = open(submit_path, 'w') for i, d in enumerate(data): question = d['question'] table = tables[d['table_id']] R = nl2sql(question, table) pbar.update(1) if PY2: s = json.dumps(R, ensure_ascii=False) F.write(s.encode('utf-8') + '\n') elif PY3: sql_pred = eval(str(R)) F.writelines(json.dumps(sql_pred, ensure_ascii=False) + '\n') F.close() pbar.close() if mode == 'test': print("Start create test result ....") # submit_path = '../submit/submit-{}.json'.format(time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime(time.time()))) test(test_data, test_tables, test_submit_path) # add by shuai should used !!!!! print('Finish create test result and saved in {}'.format(test_submit_path)) import sys sys.exit(0) class Evaluate(Callback): def __init__(self): self.accs = [] self.best = 0 self.passed = 0 self.stage = 0 def on_batch_begin(self, batch, logs=None): """ 第一个epoch用来warmup,第二个epoch把学习率降到最低 """ if self.passed < self.params['steps']: lr = (self.passed + 1.) / self.params['steps'] * learning_rate K.set_value(self.model.optimizer.lr, lr) self.passed += 1 elif self.params['steps'] <= self.passed < self.params['steps'] * 2: lr = (2 - (self.passed + 1.) / self.params['steps']) * (learning_rate - min_learning_rate) lr += min_learning_rate K.set_value(self.model.optimizer.lr, lr) self.passed += 1 def on_epoch_end(self, epoch, logs=None): acc = self.evaluate() self.accs.append(acc) if acc >= self.best: self.best = acc train_model.save_weights(weight_save_path) print('acc: %.5f, best acc: %.5f\n' % (acc, self.best)) def evaluate(self): return evaluate(valid_data, valid_tables) evaluator = Evaluate() if __name__ == '__main__': train_model.fit_generator( train_D.__iter__(), steps_per_epoch=len(train_D), epochs=40, callbacks=[evaluator] ) else: train_model.load_weights(weight_save_path)
[ "numpy.random.seed", "argparse.ArgumentParser", "keras.backend.set_value", "keras.backend.sparse_categorical_crossentropy", "keras.models.Model", "keras.backend.batch_dot", "json.dumps", "os.path.join", "keras.backend.cast", "keras_bert.load_trained_model_from_checkpoint", "codecs.open", "json.loads", "tensorflow.set_random_seed", "re.findall", "random.seed", "numpy.random.shuffle", "tqdm.tqdm", "keras.backend.expand_dims", "keras.optimizers.Adam", "keras.backend.tf.batch_gather", "sys.exit", "keras.backend.sum", "keras.backend.mean", "numpy.array", "keras.backend.not_equal" ]
[((112, 130), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (126, 130), True, 'import numpy as np\n'), ((131, 145), 'random.seed', 'rn.seed', (['(12345)'], {}), '(12345)\n', (138, 145), True, 'import random as rn\n'), ((146, 170), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1234)'], {}), '(1234)\n', (164, 170), True, 'import tensorflow as tf\n'), ((823, 848), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (846, 848), False, 'import argparse\n'), ((1588, 1686), 'os.path.join', 'os.path.join', (['model_bert_wwm_path', '"""chinese-bert_chinese_wwm_L-12_H-768_A-12/bert_config.json"""'], {}), "(model_bert_wwm_path,\n 'chinese-bert_chinese_wwm_L-12_H-768_A-12/bert_config.json')\n", (1600, 1686), False, 'import os\n'), ((1701, 1798), 'os.path.join', 'os.path.join', (['model_bert_wwm_path', '"""chinese-bert_chinese_wwm_L-12_H-768_A-12/bert_model.ckpt"""'], {}), "(model_bert_wwm_path,\n 'chinese-bert_chinese_wwm_L-12_H-768_A-12/bert_model.ckpt')\n", (1713, 1798), False, 'import os\n'), ((1807, 1898), 'os.path.join', 'os.path.join', (['model_bert_wwm_path', '"""chinese-bert_chinese_wwm_L-12_H-768_A-12/vocab.txt"""'], {}), "(model_bert_wwm_path,\n 'chinese-bert_chinese_wwm_L-12_H-768_A-12/vocab.txt')\n", (1819, 1898), False, 'import os\n'), ((1914, 1982), 'os.path.join', 'os.path.join', (['model_path', '"""weights/nl2sql_finetune_add_div2.weights"""'], {}), "(model_path, 'weights/nl2sql_finetune_add_div2.weights')\n", (1926, 1982), False, 'import os\n'), ((16024, 16102), 'keras_bert.load_trained_model_from_checkpoint', 'load_trained_model_from_checkpoint', (['config_path', 'checkpoint_path'], {'seq_len': 'None'}), '(config_path, checkpoint_path, seq_len=None)\n', (16058, 16102), False, 'from keras_bert import load_trained_model_from_checkpoint, Tokenizer\n'), ((19311, 19401), 'keras.models.Model', 'Model', (['[x1_in, x2_in, h_in, hm_in]', '[psel, pconn, pcop, pcsel0, pcsel1, pcsel2, pcdiv]'], {}), '([x1_in, x2_in, h_in, hm_in], [psel, pconn, pcop, pcsel0, pcsel1,\n pcsel2, pcdiv])\n', (19316, 19401), False, 'from keras.models import Model\n'), ((19478, 19643), 'keras.models.Model', 'Model', (['[x1_in, x2_in, xm_in, h_in, hm_in, sel_in, conn_in, csel0_in, csel1_in,\n csel2_in, cop_in, cdiv_in]', '[psel, pconn, pcop, pcsel0, pcsel1, pcsel2, pcdiv]'], {}), '([x1_in, x2_in, xm_in, h_in, hm_in, sel_in, conn_in, csel0_in,\n csel1_in, csel2_in, cop_in, cdiv_in], [psel, pconn, pcop, pcsel0,\n pcsel1, pcsel2, pcdiv])\n', (19483, 19643), False, 'from keras.models import Model\n'), ((20874, 20921), 'keras.backend.sparse_categorical_crossentropy', 'K.sparse_categorical_crossentropy', (['sel_in', 'psel'], {}), '(sel_in, psel)\n', (20907, 20921), True, 'import keras.backend as K\n'), ((21021, 21070), 'keras.backend.sparse_categorical_crossentropy', 'K.sparse_categorical_crossentropy', (['conn_in', 'pconn'], {}), '(conn_in, pconn)\n', (21054, 21070), True, 'import keras.backend as K\n'), ((21084, 21102), 'keras.backend.mean', 'K.mean', (['pconn_loss'], {}), '(pconn_loss)\n', (21090, 21102), True, 'import keras.backend as K\n'), ((21138, 21185), 'keras.backend.sparse_categorical_crossentropy', 'K.sparse_categorical_crossentropy', (['cop_in', 'pcop'], {}), '(cop_in, pcop)\n', (21171, 21185), True, 'import keras.backend as K\n'), ((21251, 21302), 'keras.backend.sparse_categorical_crossentropy', 'K.sparse_categorical_crossentropy', (['csel0_in', 'pcsel0'], {}), '(csel0_in, pcsel0)\n', (21284, 21302), True, 'import keras.backend as K\n'), ((21378, 21429), 'keras.backend.sparse_categorical_crossentropy', 'K.sparse_categorical_crossentropy', (['csel1_in', 'pcsel1'], {}), '(csel1_in, pcsel1)\n', (21411, 21429), True, 'import keras.backend as K\n'), ((21506, 21557), 'keras.backend.sparse_categorical_crossentropy', 'K.sparse_categorical_crossentropy', (['csel2_in', 'pcsel2'], {}), '(csel2_in, pcsel2)\n', (21539, 21557), True, 'import keras.backend as K\n'), ((21632, 21681), 'keras.backend.sparse_categorical_crossentropy', 'K.sparse_categorical_crossentropy', (['cdiv_in', 'pcdiv'], {}), '(cdiv_in, pcdiv)\n', (21665, 21681), True, 'import keras.backend as K\n'), ((3572, 3613), 'os.path.join', 'os.path.join', (['valid_data_path', '"""val.json"""'], {}), "(valid_data_path, 'val.json')\n", (3584, 3613), False, 'import os\n'), ((3639, 3687), 'os.path.join', 'os.path.join', (['valid_data_path', '"""val.tables.json"""'], {}), "(valid_data_path, 'val.tables.json')\n", (3651, 3687), False, 'import os\n'), ((3755, 3802), 'os.path.join', 'os.path.join', (['test_file_path', '"""final_test.json"""'], {}), "(test_file_path, 'final_test.json')\n", (3767, 3802), False, 'import os\n'), ((3821, 3875), 'os.path.join', 'os.path.join', (['test_file_path', '"""final_test.tables.json"""'], {}), "(test_file_path, 'final_test.tables.json')\n", (3833, 3875), False, 'import os\n'), ((3902, 3937), 'codecs.open', 'codecs.open', (['dict_path', '"""r"""', '"""utf8"""'], {}), "(dict_path, 'r', 'utf8')\n", (3913, 3937), False, 'import codecs\n'), ((15790, 15811), 'keras.backend.cast', 'K.cast', (['idxs', '"""int32"""'], {}), "(idxs, 'int32')\n", (15796, 15811), True, 'import keras.backend as K\n'), ((15838, 15866), 'keras.backend.tf.batch_gather', 'K.tf.batch_gather', (['seq', 'idxs'], {}), '(seq, idxs)\n', (15855, 15866), True, 'import keras.backend as K\n'), ((20201, 20229), 'keras.backend.not_equal', 'K.not_equal', (['cop', '(num_op - 1)'], {}), '(cop, num_op - 1)\n', (20212, 20229), True, 'import keras.backend as K\n'), ((20934, 20955), 'keras.backend.sum', 'K.sum', (['(psel_loss * hm)'], {}), '(psel_loss * hm)\n', (20939, 20955), True, 'import keras.backend as K\n'), ((20958, 20967), 'keras.backend.sum', 'K.sum', (['hm'], {}), '(hm)\n', (20963, 20967), True, 'import keras.backend as K\n'), ((21199, 21220), 'keras.backend.sum', 'K.sum', (['(pcop_loss * xm)'], {}), '(pcop_loss * xm)\n', (21204, 21220), True, 'import keras.backend as K\n'), ((21223, 21232), 'keras.backend.sum', 'K.sum', (['xm'], {}), '(xm)\n', (21228, 21232), True, 'import keras.backend as K\n'), ((21317, 21345), 'keras.backend.sum', 'K.sum', (['(pcsel0_loss * xm * cm)'], {}), '(pcsel0_loss * xm * cm)\n', (21322, 21345), True, 'import keras.backend as K\n'), ((21348, 21362), 'keras.backend.sum', 'K.sum', (['(xm * cm)'], {}), '(xm * cm)\n', (21353, 21362), True, 'import keras.backend as K\n'), ((21444, 21472), 'keras.backend.sum', 'K.sum', (['(pcsel1_loss * xm * cm)'], {}), '(pcsel1_loss * xm * cm)\n', (21449, 21472), True, 'import keras.backend as K\n'), ((21475, 21489), 'keras.backend.sum', 'K.sum', (['(xm * cm)'], {}), '(xm * cm)\n', (21480, 21489), True, 'import keras.backend as K\n'), ((21572, 21600), 'keras.backend.sum', 'K.sum', (['(pcsel2_loss * xm * cm)'], {}), '(pcsel2_loss * xm * cm)\n', (21577, 21600), True, 'import keras.backend as K\n'), ((21603, 21617), 'keras.backend.sum', 'K.sum', (['(xm * cm)'], {}), '(xm * cm)\n', (21608, 21617), True, 'import keras.backend as K\n'), ((21695, 21722), 'keras.backend.sum', 'K.sum', (['(pcdiv_loss * xm * cm)'], {}), '(pcdiv_loss * xm * cm)\n', (21700, 21722), True, 'import keras.backend as K\n'), ((21725, 21739), 'keras.backend.sum', 'K.sum', (['(xm * cm)'], {}), '(xm * cm)\n', (21730, 21739), True, 'import keras.backend as K\n'), ((43797, 43803), 'tqdm.tqdm', 'tqdm', ([], {}), '()\n', (43801, 43803), False, 'from tqdm import tqdm\n'), ((44819, 44830), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (44827, 44830), False, 'import sys\n'), ((44882, 44888), 'tqdm.tqdm', 'tqdm', ([], {}), '()\n', (44886, 44888), False, 'from tqdm import tqdm\n'), ((45726, 45737), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (45734, 45737), False, 'import sys\n'), ((3340, 3383), 'os.path.join', 'os.path.join', (['train_data_path', '"""train.json"""'], {}), "(train_data_path, 'train.json')\n", (3352, 3383), False, 'import os\n'), ((3413, 3463), 'os.path.join', 'os.path.join', (['train_data_path', '"""train.tables.json"""'], {}), "(train_data_path, 'train.tables.json')\n", (3425, 3463), False, 'import os\n'), ((21897, 21916), 'keras.optimizers.Adam', 'Adam', (['learning_rate'], {}), '(learning_rate)\n', (21901, 21916), False, 'from keras.optimizers import Adam\n'), ((38646, 38678), 're.findall', 're.findall', (['"""[^\\\\d\\\\-\\\\.\\\\%]"""', 'k'], {}), "('[^\\\\d\\\\-\\\\.\\\\%]', k)\n", (38656, 38678), False, 'import re\n'), ((2312, 2325), 'json.loads', 'json.loads', (['l'], {}), '(l)\n', (2322, 2325), False, 'import json\n'), ((2644, 2663), 'numpy.array', 'np.array', (["l['rows']"], {}), "(l['rows'])\n", (2652, 2663), True, 'import numpy as np\n'), ((5272, 5295), 'numpy.random.shuffle', 'np.random.shuffle', (['idxs'], {}), '(idxs)\n', (5289, 5295), True, 'import numpy as np\n'), ((16844, 16863), 'keras.backend.expand_dims', 'K.expand_dims', (['x', '(1)'], {}), '(x, 1)\n', (16857, 16863), True, 'import keras.backend as K\n'), ((17553, 17572), 'keras.backend.expand_dims', 'K.expand_dims', (['x', '(2)'], {}), '(x, 2)\n', (17566, 17572), True, 'import keras.backend as K\n'), ((17660, 17679), 'keras.backend.expand_dims', 'K.expand_dims', (['x', '(1)'], {}), '(x, 1)\n', (17673, 17679), True, 'import keras.backend as K\n'), ((18098, 18121), 'keras.backend.batch_dot', 'K.batch_dot', (['x[0]', 'x[1]'], {}), '(x[0], x[1])\n', (18109, 18121), True, 'import keras.backend as K\n'), ((23379, 23393), 'numpy.array', 'np.array', (['[x1]'], {}), '([x1])\n', (23387, 23393), True, 'import numpy as np\n'), ((23403, 23417), 'numpy.array', 'np.array', (['[x2]'], {}), '([x2])\n', (23411, 23417), True, 'import numpy as np\n'), ((23427, 23440), 'numpy.array', 'np.array', (['[h]'], {}), '([h])\n', (23435, 23440), True, 'import numpy as np\n'), ((23450, 23464), 'numpy.array', 'np.array', (['[hm]'], {}), '([hm])\n', (23458, 23464), True, 'import numpy as np\n'), ((44316, 44349), 'json.dumps', 'json.dumps', (['d'], {'ensure_ascii': '(False)'}), '(d, ensure_ascii=False)\n', (44326, 44349), False, 'import json\n'), ((45117, 45150), 'json.dumps', 'json.dumps', (['R'], {'ensure_ascii': '(False)'}), '(R, ensure_ascii=False)\n', (45127, 45150), False, 'import json\n'), ((46135, 46175), 'keras.backend.set_value', 'K.set_value', (['self.model.optimizer.lr', 'lr'], {}), '(self.model.optimizer.lr, lr)\n', (46146, 46175), True, 'import keras.backend as K\n'), ((2229, 2242), 'json.loads', 'json.loads', (['l'], {}), '(l)\n', (2239, 2242), False, 'import json\n'), ((46433, 46473), 'keras.backend.set_value', 'K.set_value', (['self.model.optimizer.lr', 'lr'], {}), '(self.model.optimizer.lr, lr)\n', (46444, 46473), True, 'import keras.backend as K\n'), ((45276, 45316), 'json.dumps', 'json.dumps', (['sql_pred'], {'ensure_ascii': '(False)'}), '(sql_pred, ensure_ascii=False)\n', (45286, 45316), False, 'import json\n'), ((36439, 36476), 're.findall', 're.findall', (['regex_tail', 'question[v_e]'], {}), '(regex_tail, question[v_e])\n', (36449, 36476), False, 'import re\n'), ((36360, 36397), 're.findall', 're.findall', (['regex_tail', 'question[v_e]'], {}), '(regex_tail, question[v_e])\n', (36370, 36397), False, 'import re\n'), ((36694, 36735), 're.findall', 're.findall', (['regex_tail', 'question[v_e + 1]'], {}), '(regex_tail, question[v_e + 1])\n', (36704, 36735), False, 'import re\n'), ((36606, 36647), 're.findall', 're.findall', (['regex_tail', 'question[v_e + 1]'], {}), '(regex_tail, question[v_e + 1])\n', (36616, 36647), False, 'import re\n')]
from src.envs.color_generation import sample_color, infer_color from src.envs.env_params import get_env_params import numpy as np import pybullet as p import os import pickle ENV_PARAMS = get_env_params() # path = "./src/envs/shapenet_objects/" # If the relative path doesn't work, we can use the absolute (complete) path. from constants import root_folder path = root_folder+"src/envs/shapenet_objects/" # If the relative path doesn't work, we can use the absolute (complete) path. objects = [o for o in os.listdir(path) if 'urdf' in o and '_prototype' not in o] with open(path + 'sizes.pkl', 'rb') as f: object_sizes = pickle.load(f) class Thing: def __init__(self, env_params, bullet_client, object_type, color, object_id, objects, size=None): assert color in env_params['colors_attributes'] self.env_params = env_params self.id = object_id self.bullet_client = bullet_client self.type = object_type self.get_type_encoding(object_type) self.color = color self.render_mode = False # render_mode self.attributes = [] if 'categories' in self.env_params['admissible_attributes']: self.attributes += ['thing', object_type, self.color] self.categories = [] self.features = [] self.position = None self.orientation = None self.size_encoding = None self.rgb_encoding = None self.objects = None self.touched = False self.grasped = False if size != None: self.size_encoding = size else: self.sample_size() self.sample_color() self.initial_rgb_encoding = self.rgb_encoding.copy() self.p_id = self.generate_object() self.sample_position(objects) self.bullet_client.changeVisualShape(self.p_id, -1, rgbaColor=self.rgb_encoding) def give_ref_to_obj_list(self, objects): self.objects = objects def sample_color(self): self.rgb_encoding = np.array(list(sample_color(color=self.color)) + [1]) def update_attributes(self): if 'absolute_location' in self.env_params['admissible_attributes']: self.update_absolute_location_attributes(self.position) if 'color' in self.env_params['admissible_attributes']: self.update_color_attributes() def update_all_attributes(self): self.update_attributes() def update_color_attributes(self, old_color=None): if self.color not in self.attributes: self.attributes.append(self.color) if old_color is not None: self.attributes.remove(old_color) def update_position(self, new_position=None): if new_position is None: new_position, new_orientation = self.bullet_client.getBasePositionAndOrientation(self.p_id) self.orientation = np.array(new_orientation).copy() new_position = np.array(new_position) if 'absolute_location' in self.env_params['admissible_attributes']: self.update_absolute_location_attributes(new_position) # update relative attributes self.position = new_position.copy() def get_type_encoding(self, object_type): self.type_encoding = np.zeros([self.env_params['nb_types']]) self.type_encoding[self.env_params['types'].index(object_type)] = 1 def get_features(self): self.features = dict(pos=self.position, orn=self.orientation, type=self.type_encoding, # vel=self.velocity, color=self.rgb_encoding[:3], size=self.get_all_sizes() ) return self.features.copy() def get_all_sizes(self): sizes = np.array(self.bullet_client.getAABB(self.p_id)[1]) - np.array(self.bullet_client.getAABB(self.p_id)[0]) return sizes def compute_radius(self): return np.sqrt((self.sizes[0]/2)**2 + (self.sizes[1]/2)**2) def sample_position(self, objects): ok = False while not ok: is_left = np.random.rand() < 0.5 low, high = np.array(self.env_params['table_ranges'])[:, 0], np.array(self.env_params['table_ranges'])[:, 1] if is_left: high[0] = -0.2 else: low[0] = 0.2 candidate_position = np.random.uniform(low=low, high=high) candidate_position = np.array(list(candidate_position) + [-0.025 + self.sizes[2] + 0.0005]) ok = True for obj in objects: if np.linalg.norm(obj.position - candidate_position) < (self.compute_radius() + obj.compute_radius())*1.2: ok = False if ok: # set object in correct position orientation = np.random.uniform(-180, 180) self.bullet_client.resetBasePositionAndOrientation(self.p_id, candidate_position, self.bullet_client.getQuaternionFromEuler(np.deg2rad([0, 0, orientation]))) #[0.0, 0.0, 0.7071, 0.7071]) # update position encoding self.update_position() def sample_size(self): self.size_encoding = np.random.uniform(self.env_params['min_max_sizes'][0], self.env_params['min_max_sizes'][1]) def update_color(self, new_color=None, new_rgb=None): old_color = self.color if new_color is None: self.color = infer_color(new_rgb[:3]) else: self.color = new_color self.rgb_encoding = new_rgb self.update_color_attributes(old_color) self.bullet_client.changeVisualShape(self.p_id, -1, rgbaColor=self.rgb_encoding) def __repr__(self): return 'Object # {}: {} {}'.format(self.id, self.color, self.type) # SHAPENET objects class ShapeNet(Thing): def __init__(self, env_params, bullet_client, object_type, color, object_id, objects, size=None): super().__init__(env_params, bullet_client, object_type, color, object_id, objects, size=size) def scan_objects_and_save_their_sizes(self): objects = sorted([o for o in os.listdir(path) if 'urdf' in o and '_prototype' not in o]) if os.path.exists(path + 'sizes.pkl'): with open(path + 'sizes.pkl', 'rb') as f: max_sizes = pickle.load(f) else: max_sizes = dict() for o in objects: print(o) object_urdf = path + o boxStartOr = p.getQuaternionFromEuler(np.deg2rad([0, 0, 0])) boxId = p.loadURDF(object_urdf, [0, 0, 0], boxStartOr) sizes = np.array(p.getAABB(boxId)[1]) - np.array(p.getAABB(boxId)[0]) p.removeBody(boxId) max_sizes[o] = sizes with open(path + 'sizes.pkl', 'wb') as f: pickle.dump(max_sizes, f) def generate_object(self): # Uncomment this once # self.scan_objects_and_save_their_sizes() # code for now, until we load the urdf models and save their sizes in the sizes.pkl file for all objects listed in env_params # objects = sorted([o for o in os.listdir(path) if 'urdf' in o and '_prototype' not in o]) # o = np.random.choice(objects) # after o = self.type + '.urdf' object_urdf = path + o original_sizes = object_sizes[o] # get original size ratio = self.size_encoding / np.sqrt(np.sum(np.array(original_sizes)**2)) # compute scaling ratio boxStartOr = self.bullet_client.getQuaternionFromEuler(np.deg2rad([0, 0, 0])) boxId = self.bullet_client.loadURDF(object_urdf, [0, 0, 0], boxStartOr, globalScaling=ratio) self.sizes = original_sizes.copy() * ratio # self.sizes = np.array(p.getAABB(boxId)[1]) - np.array(p.getAABB(boxId)[0]) self.bullet_client.changeDynamics(boxId, -1, linearDamping=0, angularDamping=0, rollingFriction=0.001, spinningFriction=0.001) self.bullet_client.changeVisualShape(boxId, -1, rgbaColor=self.rgb_encoding + [1]) return boxId # CATEGORIES class Solid(Thing): def __init__(self, env_params, bullet_client, object_type, color, object_id, objects, size=None): super().__init__(env_params, bullet_client, object_type, color, object_id, objects, size=size) if 'category' in env_params['admissible_attributes']: self.attributes += ['solid'] class Animal(ShapeNet): def __init__(self, env_params, bullet_client, object_type, color, object_id, objects, size=None): super().__init__(env_params, bullet_client, object_type, color, object_id, objects, size=size) if 'category' in env_params['admissible_attributes']: self.attributes += ['animal'] class Food(ShapeNet): def __init__(self, env_params, bullet_client, object_type, color, object_id, objects, size=None): super().__init__(env_params, bullet_client, object_type, color, object_id, objects, size=size) if 'category' in env_params['admissible_attributes']: self.attributes += ['food'] class Kitchenware(ShapeNet): def __init__(self, env_params, bullet_client, object_type, color, object_id, objects, size=None): super().__init__(env_params, bullet_client, object_type, color, object_id, objects, size=size) if 'category' in env_params['admissible_attributes']: self.attributes += ['kitchenware'] class Vehicle(ShapeNet): def __init__(self, env_params, bullet_client, object_type, color, object_id, objects, size=None): super().__init__(env_params, bullet_client, object_type, color, object_id, objects, size=size) if 'category' in env_params['admissible_attributes']: self.attributes += ['vehicle'] # OBJECTS class Cube(Solid): def __init__(self, env_params, bullet_client, object_type, color, object_id, objects, size=None): super().__init__(env_params, bullet_client, object_type, color, object_id, objects, size=size) def generate_object(self): sizes = [self.size_encoding / (np.sqrt(3) * 2) * 0.75] * 3 self.sizes = sizes.copy() colcubeId = self.bullet_client.createCollisionShape(self.bullet_client.GEOM_BOX, halfExtents=sizes) visplaneId = self.bullet_client.createVisualShape(self.bullet_client.GEOM_BOX, halfExtents=sizes, rgbaColor=list(self.rgb_encoding)) legoUID = self.bullet_client.createMultiBody(0.3, colcubeId, visplaneId, self.position) self.bullet_client.changeDynamics(legoUID, -1, lateralFriction=1.5) return legoUID class Block(Solid): def __init__(self, env_params, bullet_client, object_type, color, object_id, objects, size=None): super().__init__(env_params, bullet_client, object_type, color, object_id, objects, size=size) def generate_object(self): sizes = [self.size_encoding / np.sqrt(6)] + [self.size_encoding / (np.sqrt(6) * 2)] * 2 self.sizes = sizes.copy() self.sizes = sizes.copy() colcubeId = self.bullet_client.createCollisionShape(self.bullet_client.GEOM_BOX, halfExtents=sizes) visplaneId = self.bullet_client.createVisualShape(self.bullet_client.GEOM_BOX, halfExtents=sizes, rgbaColor=list(self.rgb_encoding)) legoUID = self.bullet_client.createMultiBody(0.3, colcubeId, visplaneId, self.position) self.bullet_client.changeDynamics(legoUID, -1, lateralFriction=1.5) return legoUID class Cylinder(Solid): def __init__(self, env_params, bullet_client, object_type, color, object_id, objects, size=None): super().__init__(env_params, bullet_client, object_type, color, object_id, objects, size=size) def generate_object(self): sizes = [self.size_encoding / np.sqrt(6)] + [self.size_encoding / (np.sqrt(6) * 2)] * 2 self.sizes = sizes.copy() colcubeId = self.bullet_client.createCollisionShape(self.bullet_client.GEOM_CYLINDER, radius=self.size_encoding / (np.sqrt(6) * 2), height=2*self.size_encoding / np.sqrt(6)) visplaneId = self.bullet_client.createVisualShape(self.bullet_client.GEOM_CYLINDER, radius=self.size_encoding / (np.sqrt(6) * 2), length=2*self.size_encoding / np.sqrt(6), rgbaColor=list(self.rgb_encoding)) legoUID = self.bullet_client.createMultiBody(0.3, colcubeId, visplaneId, self.position) self.bullet_client.changeDynamics(legoUID, -1, lateralFriction=1.5) return legoUID # build a dict of the classes things_classes = dict(cube=Cube, block=Block, cylinder=Cylinder) shapenet_categories = list(ENV_PARAMS['attributes']['categories']) shapenet_categories.remove('solid') shapenet_obj = [] cat_dict = dict(kitchenware=Kitchenware, vehicle=Vehicle, food=Food, animal=Animal) for c in shapenet_categories: things_classes.update(dict(zip(ENV_PARAMS['categories'][c], [cat_dict[c]] * len(ENV_PARAMS['categories'][c])))) def build_object(env_params, bullet_client, object_type, color, object_id, objects, size=None): assert object_type in env_params['types'] obj_class = things_classes[object_type](env_params, bullet_client, object_type, color, object_id, objects, size) assert obj_class.type == object_type, '{}, {}'.format(obj_class.type, object_type) return obj_class stop = 1
[ "numpy.random.uniform", "pybullet.loadURDF", "pickle.dump", "numpy.deg2rad", "numpy.random.rand", "numpy.zeros", "os.path.exists", "pybullet.removeBody", "src.envs.color_generation.sample_color", "pickle.load", "numpy.array", "numpy.linalg.norm", "src.envs.env_params.get_env_params", "src.envs.color_generation.infer_color", "pybullet.getAABB", "os.listdir", "numpy.sqrt" ]
[((189, 205), 'src.envs.env_params.get_env_params', 'get_env_params', ([], {}), '()\n', (203, 205), False, 'from src.envs.env_params import get_env_params\n'), ((634, 648), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (645, 648), False, 'import pickle\n'), ((514, 530), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (524, 530), False, 'import os\n'), ((3275, 3314), 'numpy.zeros', 'np.zeros', (["[self.env_params['nb_types']]"], {}), "([self.env_params['nb_types']])\n", (3283, 3314), True, 'import numpy as np\n'), ((4021, 4081), 'numpy.sqrt', 'np.sqrt', (['((self.sizes[0] / 2) ** 2 + (self.sizes[1] / 2) ** 2)'], {}), '((self.sizes[0] / 2) ** 2 + (self.sizes[1] / 2) ** 2)\n', (4028, 4081), True, 'import numpy as np\n'), ((5292, 5388), 'numpy.random.uniform', 'np.random.uniform', (["self.env_params['min_max_sizes'][0]", "self.env_params['min_max_sizes'][1]"], {}), "(self.env_params['min_max_sizes'][0], self.env_params[\n 'min_max_sizes'][1])\n", (5309, 5388), True, 'import numpy as np\n'), ((6287, 6321), 'os.path.exists', 'os.path.exists', (["(path + 'sizes.pkl')"], {}), "(path + 'sizes.pkl')\n", (6301, 6321), False, 'import os\n'), ((2950, 2972), 'numpy.array', 'np.array', (['new_position'], {}), '(new_position)\n', (2958, 2972), True, 'import numpy as np\n'), ((4457, 4494), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': 'low', 'high': 'high'}), '(low=low, high=high)\n', (4474, 4494), True, 'import numpy as np\n'), ((5529, 5553), 'src.envs.color_generation.infer_color', 'infer_color', (['new_rgb[:3]'], {}), '(new_rgb[:3])\n', (5540, 5553), False, 'from src.envs.color_generation import sample_color, infer_color\n'), ((6640, 6686), 'pybullet.loadURDF', 'p.loadURDF', (['object_urdf', '[0, 0, 0]', 'boxStartOr'], {}), '(object_urdf, [0, 0, 0], boxStartOr)\n', (6650, 6686), True, 'import pybullet as p\n'), ((6781, 6800), 'pybullet.removeBody', 'p.removeBody', (['boxId'], {}), '(boxId)\n', (6793, 6800), True, 'import pybullet as p\n'), ((6896, 6921), 'pickle.dump', 'pickle.dump', (['max_sizes', 'f'], {}), '(max_sizes, f)\n', (6907, 6921), False, 'import pickle\n'), ((7621, 7642), 'numpy.deg2rad', 'np.deg2rad', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (7631, 7642), True, 'import numpy as np\n'), ((4178, 4194), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (4192, 4194), True, 'import numpy as np\n'), ((4905, 4933), 'numpy.random.uniform', 'np.random.uniform', (['(-180)', '(180)'], {}), '(-180, 180)\n', (4922, 4933), True, 'import numpy as np\n'), ((6405, 6419), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (6416, 6419), False, 'import pickle\n'), ((6597, 6618), 'numpy.deg2rad', 'np.deg2rad', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (6607, 6618), True, 'import numpy as np\n'), ((2038, 2068), 'src.envs.color_generation.sample_color', 'sample_color', ([], {'color': 'self.color'}), '(color=self.color)\n', (2050, 2068), False, 'from src.envs.color_generation import sample_color, infer_color\n'), ((2890, 2915), 'numpy.array', 'np.array', (['new_orientation'], {}), '(new_orientation)\n', (2898, 2915), True, 'import numpy as np\n'), ((4225, 4266), 'numpy.array', 'np.array', (["self.env_params['table_ranges']"], {}), "(self.env_params['table_ranges'])\n", (4233, 4266), True, 'import numpy as np\n'), ((4274, 4315), 'numpy.array', 'np.array', (["self.env_params['table_ranges']"], {}), "(self.env_params['table_ranges'])\n", (4282, 4315), True, 'import numpy as np\n'), ((4672, 4721), 'numpy.linalg.norm', 'np.linalg.norm', (['(obj.position - candidate_position)'], {}), '(obj.position - candidate_position)\n', (4686, 4721), True, 'import numpy as np\n'), ((6215, 6231), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (6225, 6231), False, 'import os\n'), ((10929, 10939), 'numpy.sqrt', 'np.sqrt', (['(6)'], {}), '(6)\n', (10936, 10939), True, 'import numpy as np\n'), ((11800, 11810), 'numpy.sqrt', 'np.sqrt', (['(6)'], {}), '(6)\n', (11807, 11810), True, 'import numpy as np\n'), ((12063, 12073), 'numpy.sqrt', 'np.sqrt', (['(6)'], {}), '(6)\n', (12070, 12073), True, 'import numpy as np\n'), ((12243, 12253), 'numpy.sqrt', 'np.sqrt', (['(6)'], {}), '(6)\n', (12250, 12253), True, 'import numpy as np\n'), ((5074, 5105), 'numpy.deg2rad', 'np.deg2rad', (['[0, 0, orientation]'], {}), '([0, 0, orientation])\n', (5084, 5105), True, 'import numpy as np\n'), ((6716, 6732), 'pybullet.getAABB', 'p.getAABB', (['boxId'], {}), '(boxId)\n', (6725, 6732), True, 'import pybullet as p\n'), ((6748, 6764), 'pybullet.getAABB', 'p.getAABB', (['boxId'], {}), '(boxId)\n', (6757, 6764), True, 'import pybullet as p\n'), ((7504, 7528), 'numpy.array', 'np.array', (['original_sizes'], {}), '(original_sizes)\n', (7512, 7528), True, 'import numpy as np\n'), ((12016, 12026), 'numpy.sqrt', 'np.sqrt', (['(6)'], {}), '(6)\n', (12023, 12026), True, 'import numpy as np\n'), ((12196, 12206), 'numpy.sqrt', 'np.sqrt', (['(6)'], {}), '(6)\n', (12203, 12206), True, 'import numpy as np\n'), ((10125, 10135), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (10132, 10135), True, 'import numpy as np\n'), ((10966, 10976), 'numpy.sqrt', 'np.sqrt', (['(6)'], {}), '(6)\n', (10973, 10976), True, 'import numpy as np\n'), ((11837, 11847), 'numpy.sqrt', 'np.sqrt', (['(6)'], {}), '(6)\n', (11844, 11847), True, 'import numpy as np\n')]
#!/usr/bin/env python # wujian@2018 import argparse from distutils.util import strtobool import numpy as np from libs.data_handler import NumpyReader, NumpyWriter, parse_scps from libs.utils import get_logger logger = get_logger(__name__) def run(args): numpy_reader = NumpyReader(args.npy_scp) spk2utt = parse_scps(args.spk2utt, num_tokens=-1) if args.spk2utt else None with NumpyWriter(args.dump_dir, args.scp) as writer: if spk2utt is None: for key, mat in numpy_reader: if mat.ndim != 2: raise RuntimeError( "--spk2utt is None, so input ndarray must be 2D, got {:d}" .format(mat.ndim)) if args.normalize: mat = mat / np.linalg.norm( mat, ord=2, axis=1, keepdims=True) writer.write(key, np.mean(mat, axis=0)) logger.info("Processed {:d} speakers".format(len(numpy_reader))) else: for spkid, uttlist in spk2utt.items(): spkset = [] for uttid in uttlist: vec = numpy_reader[uttid] if vec.ndim != 1: raise RuntimeError( "--spk2utt is not None, expect input as vector, got {:d}" .format(vec.ndim)) if args.normalize: vec = vec / np.linalg.norm(vec) spkset.append(vec) spk_mat = np.stack(spkset) writer.write(spkid, np.mean(spk_mat, axis=0)) logger.info("Processed {:d} speakers".format(len(spk2utt))) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Command to compute means of numpy vectors/matrix", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("npy_scp", type=str, help="Input numpy rspecifier") parser.add_argument("--dump-dir", type=str, default="mean", help="Directory to dump computed results") parser.add_argument("--spk2utt", type=str, default="", help="Rspecifier for speaker to utterance-list map") parser.add_argument("--scp", type=str, default="", help="If assigned, generate corresponding scripts") parser.add_argument("--normalize", type=strtobool, default=False, help="If true, normalize vectors before compute means") args = parser.parse_args() run(args)
[ "numpy.stack", "libs.utils.get_logger", "argparse.ArgumentParser", "libs.data_handler.NumpyReader", "libs.data_handler.NumpyWriter", "numpy.mean", "numpy.linalg.norm", "libs.data_handler.parse_scps" ]
[((222, 242), 'libs.utils.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (232, 242), False, 'from libs.utils import get_logger\n'), ((279, 304), 'libs.data_handler.NumpyReader', 'NumpyReader', (['args.npy_scp'], {}), '(args.npy_scp)\n', (290, 304), False, 'from libs.data_handler import NumpyReader, NumpyWriter, parse_scps\n'), ((1734, 1887), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Command to compute means of numpy vectors/matrix"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description=\n 'Command to compute means of numpy vectors/matrix', formatter_class=\n argparse.ArgumentDefaultsHelpFormatter)\n", (1757, 1887), False, 'import argparse\n'), ((320, 359), 'libs.data_handler.parse_scps', 'parse_scps', (['args.spk2utt'], {'num_tokens': '(-1)'}), '(args.spk2utt, num_tokens=-1)\n', (330, 359), False, 'from libs.data_handler import NumpyReader, NumpyWriter, parse_scps\n'), ((396, 432), 'libs.data_handler.NumpyWriter', 'NumpyWriter', (['args.dump_dir', 'args.scp'], {}), '(args.dump_dir, args.scp)\n', (407, 432), False, 'from libs.data_handler import NumpyReader, NumpyWriter, parse_scps\n'), ((1541, 1557), 'numpy.stack', 'np.stack', (['spkset'], {}), '(spkset)\n', (1549, 1557), True, 'import numpy as np\n'), ((890, 910), 'numpy.mean', 'np.mean', (['mat'], {'axis': '(0)'}), '(mat, axis=0)\n', (897, 910), True, 'import numpy as np\n'), ((1594, 1618), 'numpy.mean', 'np.mean', (['spk_mat'], {'axis': '(0)'}), '(spk_mat, axis=0)\n', (1601, 1618), True, 'import numpy as np\n'), ((781, 830), 'numpy.linalg.norm', 'np.linalg.norm', (['mat'], {'ord': '(2)', 'axis': '(1)', 'keepdims': '(True)'}), '(mat, ord=2, axis=1, keepdims=True)\n', (795, 830), True, 'import numpy as np\n'), ((1456, 1475), 'numpy.linalg.norm', 'np.linalg.norm', (['vec'], {}), '(vec)\n', (1470, 1475), True, 'import numpy as np\n')]
# the version without filter # !/usr/bin/python3 import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from scipy import signal import time import webcam2rgb import cv2 class RealtimePlotWindow: def __init__(self, channel: str): # create a plot window self.fig, (self.ax, self.ax_iir) = plt.subplots(2) self.ax.set_title('Original data') self.ax_iir.set_title('After filtering') #ax.plt.title("Oiginal") # that's our plotbuffer self.plotbuffer = np.zeros(50) self.plotbuffer_iir = np.zeros(50) # create an empty line self.line, = self.ax.plot(self.plotbuffer) self.line_iir, = self.ax_iir.plot(self.plotbuffer_iir) # axis # That's our ringbuffer which accumluates the samples # It's emptied every time when the plot window below # does a repaint self.ringbuffer = [] self.ringbuffer_iir = [] # add any initialisation code here (filters etc) # start the animation self.ani = animation.FuncAnimation(self.fig, self.update, interval=100) # adjust the space between two subplots plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.5, hspace=0.5) # updates the plot def update(self, data): # add new data to the buffer self.plotbuffer = np.append(self.plotbuffer, self.ringbuffer) self.plotbuffer_iir = np.append(self.plotbuffer_iir, self.ringbuffer_iir) # only keep the 50 newest ones and discard the old ones self.plotbuffer = self.plotbuffer[-50:] self.plotbuffer_iir = self.plotbuffer_iir[-50:] self.ringbuffer = [] self.ringbuffer_iir = [] # set the new 50 points of channel 9 self.line.set_ydata(self.plotbuffer) self.line_iir.set_ydata(self.plotbuffer_iir) # set the y axis limit self.ax.set_ylim(-255, 255) self.ax_iir.set_ylim(-255, 255) return self.line, self.line_iir # appends data to the ringbuffer def addData(self, v): self.ringbuffer.append(v) def addData_iir(self, v): self.ringbuffer_iir.append(v) def addTitle(self, sampling_rate): self.ax.set_title('Original data\n'+"Real time sampling rate: "+str(sampling_rate)+" FPS") def addTitle_iir(self, result_iir): self.ax_iir.set_title('After filtering\n'+"fan speed after filtering : " + str(result_iir)) class IIR2_filter: def __init__(self, s): self.b0 = s[0] self.b1 = s[1] self.b2 = s[2] self.a1 = s[4] self.a2 = s[5] self.buffer1 = 0 self.buffer2 = 0 def filter(self, value): inputt = value inputt = inputt - (self.a1 * self.buffer1) inputt = inputt - (self.a2 * self.buffer2) output = inputt * self.b0 output = output + (self.b1 * self.buffer1) output = output + (self.b2 * self.buffer2) self.buffer2 = self.buffer1 self.buffer1 = inputt return output class IIR_filter: def __init__(self, sos): self.cascade = [] for s in sos: self.cascade.append(IIR2_filter(s)) def dofilter(self, value): for f in self.cascade: value = f.filter(value) return value # calculate the speeed of the fan last_status = 0 last_peak_time = 0 def calFanSpeed(data): global last_status, last_peak_time fan_speed = 0 peak_rate = 0 # if the data surpass the threshold value, count as a peak if data > 10: peak = 1 else: peak = 0 # Detect falling edge of a peak cur_status = peak if cur_status == 0 and last_status == 1: # Calculating the time interval between the two peaks to obtain the peak_rate cur_peak_time = time.time() if last_peak_time != 0: peak_rate = 60 / (cur_peak_time - last_peak_time) last_peak_time = cur_peak_time last_status = cur_status # Because there are six blades, the speed of the fan should be 1/6 of the peak rate fan_speed = peak_rate / 6 return fan_speed # create callback method reading camera and plotting in windows i = 0 list_result=[] list_time=[] def hasData(retval, data): result = 0 global i,list_result,list_time r = data[2] # plot the original figure realtimePlotWindowRed.addData(r) # plot the figure after filtering r_iir = iir_filter.dofilter(r) realtimePlotWindowRed.addData_iir(r_iir) result_iir = calFanSpeed(r_iir) if result_iir: list_result.append(result_iir) # check the sampling rate by obtaining the time gap of every callback time_cur = time.time() list_time.append(time_cur) time_last = time_cur # The results of fan speed and sampling rate are averaged to obtain a more stable output i += 1 if i > 30 and list_result: avg=np.mean(list_result) print("\nfan speed after IIR: ", int(avg), "rpm") realtimePlotWindowRed.addTitle_iir(int(avg)) sampling_rate=1/((list_time[-1]-list_time[0])/(len(list_time)-1)) # Output sampling rate with two decimal places print("check sampling rate", format(sampling_rate, '.2f')) realtimePlotWindowRed.addTitle(format(sampling_rate, '.2f')) i = 0 list_result=[] list_time=[] realtimePlotWindowRed = RealtimePlotWindow("red") # create instances of camera camera = webcam2rgb.Webcam2rgb() # Add a horizontal line as the reference line for the threshold plt.axhline(y=10, ls=":", c="red") # start the thread and stop it when we close the plot windows camera.start(callback=hasData, cameraNumber=0) # create instances for iir filter wc1 = 2 * 0.5 / camera.cameraFs() wc2 = 2 * 5 / camera.cameraFs() sos = signal.butter(3, [wc1, wc2], 'bandpass', output='sos') iir_filter = IIR_filter(sos) print("camera samplerate: ", camera.cameraFs(), "Hz") plt.show() camera.stop() # shutdown the camera camera.cam.release() cv2.destroyAllWindows() print('finished')
[ "matplotlib.pyplot.axhline", "matplotlib.pyplot.show", "numpy.zeros", "time.time", "matplotlib.animation.FuncAnimation", "numpy.append", "numpy.mean", "webcam2rgb.Webcam2rgb", "matplotlib.pyplot.subplots_adjust", "cv2.destroyAllWindows", "matplotlib.pyplot.subplots", "scipy.signal.butter" ]
[((5529, 5552), 'webcam2rgb.Webcam2rgb', 'webcam2rgb.Webcam2rgb', ([], {}), '()\n', (5550, 5552), False, 'import webcam2rgb\n'), ((5617, 5651), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'y': '(10)', 'ls': '""":"""', 'c': '"""red"""'}), "(y=10, ls=':', c='red')\n", (5628, 5651), True, 'import matplotlib.pyplot as plt\n'), ((5867, 5921), 'scipy.signal.butter', 'signal.butter', (['(3)', '[wc1, wc2]', '"""bandpass"""'], {'output': '"""sos"""'}), "(3, [wc1, wc2], 'bandpass', output='sos')\n", (5880, 5921), False, 'from scipy import signal\n'), ((6005, 6015), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6013, 6015), True, 'import matplotlib.pyplot as plt\n'), ((6073, 6096), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (6094, 6096), False, 'import cv2\n'), ((4747, 4758), 'time.time', 'time.time', ([], {}), '()\n', (4756, 4758), False, 'import time\n'), ((350, 365), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {}), '(2)\n', (362, 365), True, 'import matplotlib.pyplot as plt\n'), ((549, 561), 'numpy.zeros', 'np.zeros', (['(50)'], {}), '(50)\n', (557, 561), True, 'import numpy as np\n'), ((592, 604), 'numpy.zeros', 'np.zeros', (['(50)'], {}), '(50)\n', (600, 604), True, 'import numpy as np\n'), ((1081, 1141), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['self.fig', 'self.update'], {'interval': '(100)'}), '(self.fig, self.update, interval=100)\n', (1104, 1141), True, 'import matplotlib.animation as animation\n'), ((1198, 1292), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': 'None', 'bottom': 'None', 'right': 'None', 'top': 'None', 'wspace': '(0.5)', 'hspace': '(0.5)'}), '(left=None, bottom=None, right=None, top=None, wspace=\n 0.5, hspace=0.5)\n', (1217, 1292), True, 'import matplotlib.pyplot as plt\n'), ((1403, 1446), 'numpy.append', 'np.append', (['self.plotbuffer', 'self.ringbuffer'], {}), '(self.plotbuffer, self.ringbuffer)\n', (1412, 1446), True, 'import numpy as np\n'), ((1477, 1528), 'numpy.append', 'np.append', (['self.plotbuffer_iir', 'self.ringbuffer_iir'], {}), '(self.plotbuffer_iir, self.ringbuffer_iir)\n', (1486, 1528), True, 'import numpy as np\n'), ((3867, 3878), 'time.time', 'time.time', ([], {}), '()\n', (3876, 3878), False, 'import time\n'), ((4967, 4987), 'numpy.mean', 'np.mean', (['list_result'], {}), '(list_result)\n', (4974, 4987), True, 'import numpy as np\n')]
import numpy as np import random import matplotlib.pyplot as plt hours = np.arange(0, 100) + 1 def r_exp(n): return 100 * (((1 + 0.01) * 0.9) + ((1 + 0.06) * 0.1)) ** n def r(x): if random.random() < 0.9: return 0.01 else: return 0.06 def f(x): return (1 + r(x))*x x_cache = {} def x(n): if n in x_cache: return x_cache[n] if n == 0: result = 100 elif n > 0: result = f(x(n-1)) x_cache[n] = result return result #def dev() iterations = 20 population = [] sums_pop = [0 for n in hours] running_dev_sum = [0 for n in hours] dangerous_level = 0 for n in range(0, iterations): x_cache = {} population = [x(i) for i in hours] running_dev_sum = list(map(lambda x, y, z: x + (y - r_exp(z)) ** 2, running_dev_sum, population, hours)) plt.scatter(hours, population, s=1.0) sums_pop = list(map(lambda x, y: x + y, sums_pop, population)) if population[-1] > 500: dangerous_level += 1 # X bar sample_mean_pop = [(i/iterations) for i in sums_pop] plt.scatter(hours, sample_mean_pop, c='Orange', s=10.0, alpha=0.5) # E(x) expected = [r_exp(n) for n in hours] plt.scatter(hours, expected, c='Blue', s=10.0, alpha=0.5) # Standard Deviation deviation = [round(np.sqrt(i/iterations), 3) for i in running_dev_sum] print(deviation) # Dangerous Level Probability dangerous_prob = dangerous_level / iterations print(dangerous_prob) plt.xlabel("Hours") plt.ylabel("Population") plt.title(f"{iterations} Iterations w Sample Mean Population (Orange) & Expected (Blue)") plt.show()
[ "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.scatter", "random.random", "numpy.arange", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.sqrt" ]
[((1058, 1124), 'matplotlib.pyplot.scatter', 'plt.scatter', (['hours', 'sample_mean_pop'], {'c': '"""Orange"""', 's': '(10.0)', 'alpha': '(0.5)'}), "(hours, sample_mean_pop, c='Orange', s=10.0, alpha=0.5)\n", (1069, 1124), True, 'import matplotlib.pyplot as plt\n'), ((1170, 1227), 'matplotlib.pyplot.scatter', 'plt.scatter', (['hours', 'expected'], {'c': '"""Blue"""', 's': '(10.0)', 'alpha': '(0.5)'}), "(hours, expected, c='Blue', s=10.0, alpha=0.5)\n", (1181, 1227), True, 'import matplotlib.pyplot as plt\n'), ((1439, 1458), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Hours"""'], {}), "('Hours')\n", (1449, 1458), True, 'import matplotlib.pyplot as plt\n'), ((1459, 1483), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Population"""'], {}), "('Population')\n", (1469, 1483), True, 'import matplotlib.pyplot as plt\n'), ((1484, 1583), 'matplotlib.pyplot.title', 'plt.title', (['f"""{iterations} Iterations w Sample Mean Population (Orange) & Expected (Blue)"""'], {}), "(\n f'{iterations} Iterations w Sample Mean Population (Orange) & Expected (Blue)'\n )\n", (1493, 1583), True, 'import matplotlib.pyplot as plt\n'), ((1574, 1584), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1582, 1584), True, 'import matplotlib.pyplot as plt\n'), ((74, 91), 'numpy.arange', 'np.arange', (['(0)', '(100)'], {}), '(0, 100)\n', (83, 91), True, 'import numpy as np\n'), ((832, 869), 'matplotlib.pyplot.scatter', 'plt.scatter', (['hours', 'population'], {'s': '(1.0)'}), '(hours, population, s=1.0)\n', (843, 869), True, 'import matplotlib.pyplot as plt\n'), ((193, 208), 'random.random', 'random.random', ([], {}), '()\n', (206, 208), False, 'import random\n'), ((1269, 1292), 'numpy.sqrt', 'np.sqrt', (['(i / iterations)'], {}), '(i / iterations)\n', (1276, 1292), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ This framework is based on SSD_tensorlow(https://github.com/balancap/SSD-Tensorflow) Add descriptions """ import math from collections import namedtuple import copy import numpy as np import tensorflow as tf import tf_extended as tfe from nets import custom_layers from nets import textbox_common import tensorflow.contrib.slim as slim # =========================================================================== # # Text class definition. # =========================================================================== # TextboxParams = namedtuple('TextboxParameters', ['img_shape', 'num_classes', 'feat_layers', 'feat_shapes', 'scale_range', 'anchor_ratios', 'anchor_sizes', 'anchor_steps', 'normalizations', 'prior_scaling', 'step', 'scales' ]) class TextboxNet(object): """ Implementation of the Textbox 300 network. The default features layers with 300x300 image input are: conv4_3 ==> 38 x 38 fc7 ==> 19 x 19 conv6_2 ==> 10 x 10 conv7_2 ==> 5 x 5 conv8_2 ==> 3 x 3 pool6 ==> 1 x 1 The default image size used to train this network is 300x300. """ default_params = TextboxParams( img_shape=(768, 768), num_classes=2, feat_layers=['conv4', 'conv7', 'conv8', 'conv9', 'conv10', 'conv11'], feat_shapes=[(96, 96), (48, 48), (24, 24), (12, 12), (10, 10), (8, 8)], scale_range=[0.20, 0.90], # anchor_ratios=[1.0, 2.0, 3.0,4.0, 5.0,1.0, 0.50, 1./3 , 1./4, 1./5], anchor_ratios=[ [2.0, 1. / 2, 3.0, 1. / 3, 5.0, 1. / 5, 7.0, 1. / 7, 9.0, 1. / 9, 15.0, 1. /15], [2.0, 1. / 2, 3.0, 1. / 3, 5.0, 1. / 5, 7.0, 1. / 7, 9.0, 1. / 9, 15.0, 1. / 15], [2.0, 1. / 2, 3.0, 1. / 3, 5.0, 1. / 5, 7.0, 1. / 7, 9.0, 1. / 9, 15.0, 1. / 15], [2.0, 1. / 2, 3.0, 1. / 3, 4.0, 1. / 4, 5.0, 1. / 5, 7., 1. / 7, 9., 1. / 9], [2.0, 1. / 2, 3.0, 1. / 3, 4.0, 1. / 4, 5.0, 1. / 5, 7., 1. / 7, 9., 1. / 9], [2.0, 1. / 2, 3.0, 1. / 3, 4.0, 1. / 4, 5.0, 1. / 5], ], anchor_sizes=[ (30.,60.), (30.,90.), (90.,150.), (150., 210.), (210., 270.), (270., 330.) ], anchor_steps=[8, 16, 32, 64, 100, 300], normalizations=[20, -1, -1, -1, -1, -1], prior_scaling=[0.1, 0.1, 0.2, 0.2], step=0.14, scales=[0.2, 0.34, 0.48, 0.62, 0.76, 0.90] )#step 8 16 32 64 96 192 def __init__(self, params=None): """ Init the Textbox net with some parameters. Use the default ones if none provided. """ if isinstance(params, TextboxParams): self.params = params else: self.params = self.default_params # self.params.step = (scale_range[1] - scale_range[0])/ 5 # self.params.scales = [scale_range[0] + i* self.params.step for i in range(6)] # ======================================================================= # def net(self, inputs, is_training=True, dropout_keep_prob=0.5, reuse=None, scope='text_box_384'): """ Text network definition. """ r = text_net(inputs, feat_layers=self.params.feat_layers, anchor_sizes=self.params.anchor_sizes, anchor_ratios = self.params.anchor_ratios, normalizations=self.params.normalizations, is_training=is_training, dropout_keep_prob=dropout_keep_prob, reuse=reuse, scope=scope) # Update feature shapes (try at least!) def arg_scope(self, weight_decay=0.0005, data_format='NHWC'): """Network arg_scope. """ return ssd_arg_scope(weight_decay, data_format=data_format) def arg_scope_caffe(self, caffe_scope): """Caffe arg_scope used for weights importing. """ return ssd_arg_scope_caffe(caffe_scope) # ======================================================================= # ''' def update_feature_shapes(self, predictions): """Update feature shapes from predictions collection (Tensor or Numpy array). """ shapes = ssd_feat_shapes_from_net(predictions, self.params.feat_shapes) self.params = self.params._replace(feat_shapes=shapes) ''' def anchors(self, img_shape, dtype=np.float32): """Compute the default anchor boxes, given an image shape. """ return textbox_achor_all_layers(img_shape, self.params.feat_shapes, self.params.anchor_ratios, self.params.anchor_sizes, self.params.anchor_steps, self.params.scales, 0.5, dtype) def bboxes_encode(self,glabels, bboxes, anchors, gxs, gys, scope='text_bboxes_encode'): """Encode labels and bounding boxes. """ return textbox_common.tf_text_bboxes_encode( glabels, bboxes, anchors, gxs, gys, matching_threshold=0.5, prior_scaling=self.params.prior_scaling, scope=scope) def losses(self, logits, localisations, glabels, glocalisations, gscores, match_threshold=0.5, negative_ratio=3., alpha=0.2, label_smoothing=0., batch_size=16, scope='txt_losses'): """Define the SSD network losses. """ return ssd_losses(logits, localisations, glabels, glocalisations, gscores, match_threshold=match_threshold, negative_ratio=negative_ratio, alpha=alpha, label_smoothing=label_smoothing, batch_size = batch_size, scope=scope) def text_multibox_layer(layer, inputs, anchor_size, anchor_ratio, normalization=-1): """ Construct a multibox layer, return a class and localization predictions. The most different between textbox and ssd is the prediction shape where textbox has prediction score shape (48,48,2,6) and location has shape (48,48,2,6,12) besise,the kernel for every layer same """ net = inputs if normalization > 0: net = custom_layers.l2_normalization(net, scaling=True) # Number of anchors. num_anchors = len(anchor_ratio) + len(anchor_size) num_classes = 2 # Location. # location 4+8 num_prior_per_location = 2 * num_anchors num_loc_pred = num_prior_per_location* 12 # num_loc_pred = num_prior_per_location * 4 #240/12 = 20 = num_prior_per_location # if(layer == 'conv11'): # loc_pred = slim.conv2d(net, num_loc_pred, [1, 1], activation_fn=None, padding = 'VALID', # scope='conv_loc') # else: loc_pred = slim.conv2d(net, num_loc_pred, [3, 5], activation_fn=None, padding='SAME', scope='conv_loc') # loc_pred = custom_layers.channel_to_last(loc_pred) loc_pred = slim.flatten(loc_pred) l_shape = loc_pred.shape batch_size = l_shape[0] loc_pred = tf.reshape(loc_pred, [batch_size, -1, 12]) # loc_pred = tf.reshape(loc_pred, [1, -1, 2]) # loc_pred = tf.reshape(loc_pred, loc_pred.get_shape().as_list()[:-1] + [2, num_anchors, 12]) # loc_pred = tf.reshape(loc_pred, loc_pred.get_shape().as_list()[:-1] + [2, num_anchors, 4]) # Class prediction. scores_pred = num_prior_per_location * num_classes # scores_pred = num_classes # scores_pred = 40 # if(layer == 'conv11'): # sco_pred = slim.conv2d(net, scores_pred, [1, 1], activation_fn=None, padding = 'VALID', # scope='conv_cls') # else: sco_pred = slim.conv2d(net, scores_pred, [3, 5], activation_fn=None, padding='SAME',scope='conv_cls') # cls_pred = custom_layers.channel_to_last(cls_pred) # sco_pred = tf.reshape(sco_pred, sco_pred.get_shape().as_list()[:-1] + [2, num_anchors, num_classes]) sco_pred = slim.flatten(sco_pred) sco_pred = tf.reshape(sco_pred, [batch_size, -1 ,2]) return sco_pred, loc_pred def text_net(inputs, feat_layers=TextboxNet.default_params.feat_layers, anchor_sizes=TextboxNet.default_params.anchor_sizes, anchor_ratios = TextboxNet.default_params.anchor_ratios, normalizations=TextboxNet.default_params.normalizations, is_training=True, dropout_keep_prob=0.5, reuse=None, scope='text_box_384'): end_points = {} with tf.variable_scope(scope, 'text_box_300', [inputs], reuse=reuse): # 300*300 384*383 # Original VGG-16 blocks. net = slim.repeat(inputs, 2, slim.conv2d, 64, [3, 3], scope='conv1') # 300 384 end_points['conv1'] = net net = slim.max_pool2d(net, [2, 2], scope='pool1') # 150 # Block 2. net = slim.repeat(net, 2, slim.conv2d, 128, [3, 3], scope='conv2') # 150 192 end_points['conv2'] = net net = slim.max_pool2d(net, [2, 2], scope='pool2') # 75 # Block 3. net = slim.repeat(net, 3, slim.conv2d, 256, [3, 3], scope='conv3') # 75 81 end_points['conv3'] = net net = slim.max_pool2d(net, [2, 2], scope='pool3') # 38 # Block 4. net = slim.repeat(net, 3, slim.conv2d, 512, [3, 3], scope='conv4') # 38 40 end_point = 'conv4' end_points[end_point] = net net = slim.max_pool2d(net, [2, 2], scope='pool4') # 19 # Block 5. net = slim.repeat(net, 3, slim.conv2d, 512, [3, 3], scope='conv5') # 19 end_points['conv5'] = net net = slim.max_pool2d(net, [3, 3], stride=1, scope='pool5') # 19 # Additional SSD blocks. # Block 6: let's dilate the hell out of it! net = slim.conv2d(net, 1024, [3, 3], rate=6, scope='conv6') # 19 end_points['conv6'] = net # Block 7: 1x1 conv. Because the fuck. net = slim.conv2d(net, 1024, [1, 1], scope='conv7') # 19 end_point = 'conv7' end_points[end_point] = net # Block 8/9/10/11: 1x1 and 3x3 convolutions stride 2 end_point = 'conv8' with tf.variable_scope(end_point): net = slim.conv2d(net, 256, [1, 1], scope='conv1x1') net = custom_layers.pad2d(net, pad=(1, 1)) net = slim.conv2d(net, 512, [3, 3], stride=2, scope='conv3x3', padding='VALID') end_points[end_point] = net # 10 end_point = 'conv9' with tf.variable_scope(end_point): net = slim.conv2d(net, 128, [1, 1], scope='conv1x1') net = custom_layers.pad2d(net, pad=(1, 1)) net = slim.conv2d(net, 256, [3, 3], stride=2, scope='conv3x3', padding='VALID') end_points[end_point] = net # 5 end_point = 'conv10' with tf.variable_scope(end_point): net = slim.conv2d(net, 128, [1, 1], scope='conv1x1', padding= 'VALID') net = slim.conv2d(net, 256, [3, 3], scope='conv3x3', padding='VALID') end_points[end_point] = net # 3 end_point = 'conv11' with tf.variable_scope(end_point): net = slim.conv2d(net, 128, [1, 1], scope='conv1x1') net = slim.conv2d(net, 256, [3, 3], scope='conv3x3', padding='VALID') end_points[end_point] = net # end_point = feat_layers[0] with tf.variable_scope(end_point): net_dilation1 = slim.conv2d(end_points[end_point], 128, [3, 3], stride=1, scope='dilation1') # net_dilation2 = custom_layers.pad2d(net, pad=(0, 4)) net_dilation2 = slim.conv2d(end_points[end_point], 128, [1, 9], padding='SAME', stride=1, scope='dilation2') net_dilation3 = slim.conv2d(end_points[end_point], 128, [9, 1], stride=1, padding='SAME', scope='dilation3') # net_dilation3 = custom_layers.pad2d(net_dilation3, pad=(4, 0)) net_inception = tf.concat(values=[net_dilation1, net_dilation2, net_dilation3], axis=3) end_points[end_point] = net_inception end_point= feat_layers[1] with tf.variable_scope(end_point): net_dilation1 = slim.conv2d(end_points[end_point], 1024, [1, 1], stride=1, scope='dilation1') net_dilation2 = slim.conv2d(end_points[end_point], 1024, [1, 7], stride=1, scope='dilation2') # net_dilation2 = custom_layers.pad2d(net_dilation2, pad=(0, 3)) net_dilation3 = slim.conv2d(end_points[end_point], 1024, [7, 1], stride=1, scope='dilation3') # net_dilation3 = custom_layers.pad2d(net_dilation3, pad=(3, 0)) net_inception = tf.concat([net_dilation1, net_dilation2, net_dilation3], axis=3) end_points[end_point] = net_inception end_point = 'conv8' with tf.variable_scope(end_point): net_dilation1 = slim.conv2d(end_points[end_point], 128, [1, 1], stride=1,scope='dilation1') net_dilation2 = slim.conv2d(end_points[end_point], 128, [1, 7], stride=1, scope='dilation2') # net_dilation2 = custom_layers.pad2d(net_dilation2, pad=(0, 3)) net_dilation3 = slim.conv2d(end_points[end_point], 128, [7, 1], stride=1, scope='dilation3') # net_dilation3 = custom_layers.pad2d(net_dilation3, pad=(3, 0)) net_inception = tf.concat([net_dilation1, net_dilation2, net_dilation3], axis=3) end_points[end_point] = net_inception end_point = feat_layers[3] with tf.variable_scope(end_point): net_dilation1 = slim.conv2d(end_points[end_point], 128, [1, 1], stride=1,scope='dilation1') net_dilation2 = slim.conv2d(end_points[end_point], 128, [1, 7], stride=1, scope='dilation2') # net_dilation2 = custom_layers.pad2d(net_dilation2, pad=(0, 3)) net_dilation3 = slim.conv2d(end_points[end_point], 128, [7, 1], stride=1, scope='dilation3') # net_dilation3 = custom_layers.pad2d(net_dilation3, pad=(3, 0)) net_inception = tf.concat([net_dilation1, net_dilation2, net_dilation3], axis=3) end_points[end_point] = net_inception # 5 end_point = 'conv10' with tf.variable_scope(end_point): net_dilation1 = slim.conv2d(end_points[end_point], 128, [1, 1], stride=1, scope='dilation1') net_dilation2 = slim.conv2d(end_points[end_point], 128, [1, 7], stride=1, scope='dilation2') # net_dilation2 = custom_layers.pad2d(net_dilation2, pad=(0, 3)) net_dilation3 = slim.conv2d(end_points[end_point], 128, [7, 1], stride=1, scope='dilation3') # net_dilation3 = custom_layers.pad2d(net_dilation3, pad=(3, 0)) net_inception = tf.concat([net_dilation1, net_dilation2, net_dilation3], axis=3) end_points[end_point] = net_inception # 3 end_point = 'conv11' with tf.variable_scope(end_point): net_dilation1 = slim.conv2d(end_points[end_point], 128, [1, 1], stride=1,scope='dilation1') net_dilation2 = slim.conv2d(end_points[end_point], 128, [1, 5], stride=1, scope='dilation2') # net_dilation2 = custom_layers.pad2d(net_dilation2, pad=(0, 2)) net_dilation3 = slim.conv2d(end_points[end_point], 128, [5, 1], stride=1, scope='dilation3') # net_dilation3 = custom_layers.pad2d(net_dilation3, pad=(2, 0)) net_inception = tf.concat([net_dilation1, net_dilation2, net_dilation3], axis=3) end_points[end_point] = net_inception # 1 # Prediction and localisations layers. predictions = [] logits = [] localisations = [] for i, layer in enumerate(feat_layers): with tf.variable_scope(layer + '_box'): p, loc = text_multibox_layer(layer, end_points[layer], anchor_sizes[i], anchor_ratios[i], normalizations[i]) prediction_fn = slim.softmax predictions.append(prediction_fn(p)) logits.append(p) localisations.append(loc) return predictions, localisations, logits, end_points ## produce anchor for one layer # each feature point has 12 default textboxes(6 boxes + 6 offsets boxes) # aspect ratios = (1,2,3,5,1/2,1/3, 1/5) # feat_size : # conv4_3 ==> 38 x 38 # fc7 ==> 19 x 19 # conv6_2 ==> 10 x 10 # conv7_2 ==> 5 x 5 # conv8_2 ==> 3 x 3 # pool6 ==> 1 x 1 """Computer TextBoxes++ default anchor boxes for one feature layer. Determine the relative position grid of the centers, and the relative width and height. Arguments: feat_shape: Feature shape, used for computing relative position grids; ratios: Ratios to use on these features; img_shape: Image shape, used for computing height, width relatively to the former; offset: Grid offset. Return: y, x, h, w: Relative x and y grids, and height and width. """ def textbox_anchor_one_layer(img_shape, feat_size, ratios, size, step, scale, offset=0.5, dtype=np.float32): # Follow the papers scheme # 12 ahchor boxes with out sk' = sqrt(sk * sk+1) # size_h = img_shape[0] / 384 # size_w = img_shape[1] / 384 # # feat_size_h = feat_size[0] * size_h # feat_size_w = feat_size[1] * size_w y, x = np.mgrid[0:feat_size[0], 0:feat_size[1]] + 0.5 y_offset = (y.astype(dtype) + 0.5) * step / img_shape[0] y = y.astype(dtype) * step / img_shape[0] x = x.astype(dtype) * step / img_shape[1] x_offset = x #38,38,2 origin and offset x_out = np.stack((x, x_offset), -1) y_out = np.stack((y, y_offset), -1) # add dims y_out = np.expand_dims(y_out, axis=-1) x_out = np.expand_dims(x_out, axis=-1) # num_anchors = len(ratios) + len(size) h = np.zeros((num_anchors,), dtype=dtype) w = np.zeros((num_anchors,), dtype=dtype) # first prior h[0] = size[0] / img_shape[0] w[0] = size[0] / img_shape[1] di = 1 if len(size) > 1: h[1] = math.sqrt(size[0] * size[1]) / img_shape[0] w[1] = math.sqrt(size[0] * size[1]) / img_shape[1] di += 1 for i, r in enumerate(ratios): h[i+di] = size[0] / img_shape[0] /math.sqrt(r) w[i+di] = size[0] / img_shape[1] * math.sqrt(r) # h[i] = scale / math.sqrt(r) / feat_size[0] # w[i] = scale * math.sqrt(r) / feat_size[1] xmin = x_out - w/2 ymin = y_out - h/2 xmax = x_out + w/2 ymax = y_out + h/2 xmin = xmin.reshape([xmin.shape[0], xmin.shape[1], -1], order='F').reshape(-1) ymin = ymin.reshape([ymin.shape[0], ymin.shape[1], -1], order='F').reshape(-1) xmax = xmax.reshape([xmax.shape[0], xmax.shape[1], -1], order='F').reshape(-1) ymax = ymax.reshape([ymax.shape[0], ymax.shape[1], -1], order='F').reshape(-1) return xmin, ymin, xmax, ymax ## produce anchor for all layers def ssd_arg_scope(weight_decay=0.0005, data_format='NHWC'): """Defines the VGG arg scope. Args: weight_decay: The l2 regularization coefficient. Returns: An arg_scope. """ with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn=tf.nn.relu, weights_regularizer=slim.l2_regularizer(weight_decay), weights_initializer=tf.contrib.layers.xavier_initializer(), biases_initializer=tf.zeros_initializer()): with slim.arg_scope([slim.conv2d, slim.max_pool2d], padding='SAME', data_format=data_format): with slim.arg_scope([custom_layers.pad2d, custom_layers.l2_normalization, custom_layers.channel_to_last], data_format=data_format) as sc: return sc def textbox_achor_all_layers(img_shape, layers_shape, anchor_ratios, anchor_sizes, anchor_steps, scales, offset=0.5, dtype=np.float32): """ Compute anchor boxes for all feature layers. """ layers_anchors = [] for i, s in enumerate(layers_shape): anchor_bboxes = textbox_anchor_one_layer(img_shape, s, anchor_ratios[i], anchor_sizes[i], anchor_steps[i], scales[i], offset=offset, dtype=dtype) layers_anchors.append(anchor_bboxes) return layers_anchors # =========================================================================== # # Caffe scope: importing weights at initialization. # =========================================================================== # def ssd_arg_scope_caffe(caffe_scope): """Caffe scope definition. Args: caffe_scope: Caffe scope object with loaded weights. Returns: An arg_scope. """ # Default network arg scope. with slim.arg_scope([slim.conv2d], activation_fn=tf.nn.relu, weights_initializer=caffe_scope.conv_weights_init(), biases_initializer=caffe_scope.conv_biases_init()): with slim.arg_scope([slim.fully_connected], activation_fn=tf.nn.relu): with slim.arg_scope([custom_layers.l2_normalization], scale_initializer=caffe_scope.l2_norm_scale_init()): with slim.arg_scope([slim.conv2d, slim.max_pool2d], padding='SAME') as sc: return sc # =========================================================================== # # Text loss function. # =========================================================================== # def ssd_losses(logits, localisations,glabels, glocalisations, gscores, match_threshold=0.5, negative_ratio=3., alpha=0.2, label_smoothing=0., batch_size=16, scope=None): '''Loss functions for training the text box network. Arguments: logits: (list of) predictions logits Tensors; x localisations: (list of) localisations Tensors; l glocalisations: (list of) groundtruth localisations Tensors; g gscores: (list of) groundtruth score Tensors; c ''' # from ssd loss with tf.name_scope(scope, 'txt_losses'): lshape = tfe.get_shape(logits[0], 5) num_classes = lshape[-1] batch_size = batch_size l_cross_pos = [] l_cross_neg = [] l_loc = [] # Flatten out all vectors! flogits = logits fgscores = gscores flocalisations = localisations fglocalisations = glocalisations fglabels = glabels # for i in range(len(logits)): # flogits.append(tf.reshape(logits[i], [-1, num_classes])) # fgscores.append(tf.reshape(gscores[i], [-1])) # fglabels.append(tf.reshape(glabels[i], [-1])) # flocalisations.append(tf.reshape(localisations[i], [-1, 12])) # fglocalisations.append(tf.reshape(glocalisations[i], [-1, 12])) # And concat the crap! glabels = tf.concat(fglabels, axis=1) logits = tf.concat(flogits, axis=1) # x gscores = tf.concat(fgscores, axis=1) # c localisations = tf.concat(flocalisations, axis=1) # l glocalisations = tf.concat(fglocalisations, axis=1) # g dtype = logits.dtype # Compute positive matching mask... pmask = gscores > match_threshold # positive mask # pmask = tf.concat(axis=0, values=[pmask[:tf.argmax(gscores, axis=0)], [True], pmask[tf.argmax(gscores, axis=0) + 1:]]) ipmask = tf.cast(pmask, tf.int32) # int positive mask fpmask = tf.cast(pmask, dtype) # float positive mask n_positives = tf.reduce_sum(fpmask) # calculate all number # Hard negative mining... # conf loss ?? no_classes = tf.cast(pmask, tf.int32) predictions = slim.softmax(logits) # nmask = tf.logical_and(tf.logical_not(pmask), gscores > -0.5) # fnmask = tf.cast(nmask, dtype) nvalues = tf.where(nmask, predictions[:, :, 0], 1. - fnmask) nvalues_flat = tf.reshape(nvalues, [-1]) # Number of negative entries to select. max_neg_entries = tf.cast(tf.reduce_sum(fnmask), tf.int32) n_neg = tf.cast(negative_ratio * n_positives, tf.int32) + batch_size n_neg = tf.minimum(n_neg, max_neg_entries) val, idxes = tf.nn.top_k(-nvalues_flat, k=n_neg) max_hard_pred = -val[-1] # Final negative mask. nmask = tf.logical_and(nmask, nvalues < max_hard_pred) fnmask = tf.cast(nmask, dtype) inmask = tf.cast(nmask, tf.int32) # Add cross-entropy loss. # logits [batch_size, num_classes] labels [batch_size] ~ 0,num_class with tf.name_scope('cross_entropy_pos'): loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=glabels) loss = tf.div(tf.reduce_sum(loss * fpmask), batch_size, name='value') tf.losses.add_loss(loss) l_cross_pos.append(loss) with tf.name_scope('cross_entropy_neg'): loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=no_classes) loss = tf.div(tf.reduce_sum(loss * fnmask), batch_size, name='value') tf.losses.add_loss(loss) l_cross_neg.append(loss) # Add localization loss: smooth L1, L2, ... with tf.name_scope('localization'): # Weights Tensor: positive mask + random negative. weights = tf.expand_dims(alpha * fpmask, axis=-1) # localisations = tf.Print(localisations, [localisations, tf.shape(localisations)], "pre is: ", summarize=20) # glocalisations = tf.Print(glocalisations, [glocalisations, tf.shape(glocalisations)], "gt is : ",summarize=20) loss = custom_layers.abs_smooth(localisations - glocalisations) loss = tf.div(tf.reduce_sum(loss * weights), batch_size, name='value') tf.losses.add_loss(loss) l_loc.append(loss) with tf.name_scope('total'): total_cross_pos = tf.add_n(l_cross_pos, 'cross_entropy_pos') total_cross_neg = tf.add_n(l_cross_neg, 'cross_entropy_neg') total_cross = tf.add(total_cross_pos, total_cross_neg, 'cross_entropy') total_loc = tf.add_n(l_loc, 'localization') # Add to EXTRA LOSSES TF.collection tf.add_to_collection('EXTRA_LOSSES', total_cross_pos) tf.add_to_collection('EXTRA_LOSSES', total_cross_neg) tf.add_to_collection('EXTRA_LOSSES', total_cross) tf.add_to_collection('EXTRA_LOSSES', total_loc) # with tf.name_scope(scope, 'txt_losses'): # l_cross_pos = [] # l_cross_neg = [] # l_loc = [] # tf.logging.info('logits len:',len(logits), logits) # for i in range(len(logits)): # dtype = logits[i].dtype # with tf.name_scope('block_%i' % i): # # # Determine weights Tensor. # pmask = gscores[i] > match_threshold # ipmask = tf.cast(pmask, tf.int32) # fpmask = tf.cast(pmask, dtype) # n_positives = tf.reduce_sum(fpmask) # # # Negative mask # # Number of negative entries to select. # n_neg = tf.cast(negative_ratio * n_positives, tf.int32) # # nvalues = tf.where(tf.cast(1-ipmask,tf.bool), gscores[i], np.zeros(gscores[i].shape)) # nvalues_flat = tf.reshape(nvalues, [-1]) # val, idxes = tf.nn.top_k(nvalues_flat, k=n_neg) # minval = val[-1] # # Final negative mask. # nmask = nvalues > minval # fnmask = tf.cast(nmask, dtype) # inmask = tf.cast(nmask, tf.int32) # # Add cross-entropy loss. # with tf.name_scope('cross_entropy_pos'): # loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits[i], # labels=ipmask) # loss = tf.losses.compute_weighted_loss(loss, fpmask) # l_cross_pos.append(loss) # # with tf.name_scope('cross_entropy_neg'): # loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits[i], # labels=inmask) # loss = tf.losses.compute_weighted_loss(loss, fnmask) # l_cross_neg.append(loss) # # # Add localization loss: smooth L1, L2, ... # with tf.name_scope('localization'): # # Weights Tensor: positive mask + random negative. # weights = tf.expand_dims(alpha * fpmask, axis=-1) # loss = custom_layers.abs_smooth(localisations[i] - glocalisations[i]) # loss = tf.losses.compute_weighted_loss(loss, weights) # l_loc.append(loss) # # # Additional total losses... # with tf.name_scope('total'): # total_cross_pos = tf.add_n(l_cross_pos, 'cross_entropy_pos') # total_cross_neg = tf.add_n(l_cross_neg, 'cross_entropy_neg') # total_cross = tf.add(total_cross_pos, total_cross_neg, 'cross_entropy') # total_loc = tf.add_n(l_loc, 'localization') # # # Add to EXTRA LOSSES TF.collection # tf.add_to_collection('EXTRA_LOSSES', total_cross_pos) # tf.add_to_collection('EXTRA_LOSSES', total_cross_neg) # tf.add_to_collection('EXTRA_LOSSES', total_cross) # tf.add_to_collection('EXTRA_LOSSES', total_loc) # with tf.name_scope(scope, 'txt_losses'): # l_cross_pos = [] # l_cross_neg = [] # l_loc = [] # for i in range(len(logits)): # dtype = logits[i].dtype # with tf.name_scope('block_%i' % i): # # Sizing weight... # # wsize = tfe.get_shape(logits[i], rank=5) # wsize = wsize[1] * wsize[2] * wsize[3] # # # Positive mask. # pmask = gscores[i] > match_threshold # fpmask = tf.cast(pmask, dtype) # ipmask = tf.cast(fpmask, 'int32') # n_positives = tf.reduce_sum(fpmask) # # # Negative mask. # no_classes = tf.cast(pmask, tf.int32) # predictions = slim.softmax(logits[i]) # nmask = tf.logical_and(tf.logical_not(pmask), # gscores[i] > -0.5) # fnmask = tf.cast(nmask, dtype) # print('nmask',nmask) # print('preditions', predictions) # predictions_low = predictions[:, :, :, :, :, 0] # print('fnmask', 1.-fnmask) # nvalues = tf.where(nmask, # predictions_low, # 1. - fnmask) # nvalues_flat = tf.reshape(nvalues, [-1]) # # Number of negative entries to select. # n_neg = tf.cast(negative_ratio * n_positives, tf.int32) # n_neg = tf.maximum(n_neg, tf.size(nvalues_flat) // 8) # n_neg = tf.maximum(n_neg, tf.shape(nvalues)[0] * 4) # max_neg_entries = 1 + tf.cast(tf.reduce_sum(fnmask), tf.int32) # n_neg = tf.minimum(n_neg, max_neg_entries) # # val, idxes = tf.nn.top_k(-nvalues_flat, k=n_neg) # max_hard_pred = -val[-1] # # Final negative mask. # nmask = tf.logical_and(nmask, nvalues < max_hard_pred) # fnmask = tf.cast(nmask, dtype) # # # Add cross-entropy loss. # with tf.name_scope('cross_entropy_pos'): # fpmask = wsize * fpmask # loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits[i], # labels=ipmask) # loss = tf.losses.compute_weighted_loss(loss, fpmask) # l_cross_pos.append(loss) # # with tf.name_scope('cross_entropy_neg'): # fnmask = wsize * fnmask # loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits[i], # labels=no_classes) # loss = tf.losses.compute_weighted_loss(loss, fnmask) # l_cross_neg.append(loss) # # # Add localization loss: smooth L1, L2, ... # with tf.name_scope('localization'): # # Weights Tensor: positive mask + random negative. # weights = tf.expand_dims(alpha * fpmask, axis=-1) # loss = custom_layers.abs_smooth(localisations[i] - glocalisations[i]) # loss = tf.losses.compute_weighted_loss(loss, weights) # l_loc.append(loss) # # # Additional total losses... # with tf.name_scope('total'): # total_cross_pos = tf.add_n(l_cross_pos, 'cross_entropy_pos') # total_cross_neg = tf.add_n(l_cross_neg, 'cross_entropy_neg') # total_cross = tf.add(total_cross_pos, total_cross_neg, 'cross_entropy') # total_loc = tf.add_n(l_loc, 'localization') # # # Add to EXTRA LOSSES TF.collection # tf.add_to_collection('EXTRA_LOSSES', total_cross_pos) # tf.add_to_collection('EXTRA_LOSSES', total_cross_neg) # tf.add_to_collection('EXTRA_LOSSES', total_cross) # tf.add_to_collection('EXTRA_LOSSES', total_loc)
[ "tensorflow.contrib.layers.xavier_initializer", "tensorflow.reduce_sum", "nets.custom_layers.abs_smooth", "tensorflow.reshape", "tensorflow.contrib.slim.softmax", "tensorflow.contrib.slim.l2_regularizer", "tensorflow.contrib.slim.conv2d", "tensorflow.add_n", "tensorflow.losses.add_loss", "tensorflow.logical_and", "tensorflow.nn.top_k", "tensorflow.variable_scope", "tensorflow.concat", "tensorflow.minimum", "nets.textbox_common.tf_text_bboxes_encode", "tf_extended.get_shape", "tensorflow.cast", "tensorflow.name_scope", "numpy.stack", "nets.custom_layers.l2_normalization", "tensorflow.contrib.slim.arg_scope", "math.sqrt", "tensorflow.add", "tensorflow.contrib.slim.repeat", "tensorflow.where", "tensorflow.contrib.slim.max_pool2d", "nets.custom_layers.pad2d", "tensorflow.zeros_initializer", "tensorflow.contrib.slim.flatten", "tensorflow.expand_dims", "numpy.zeros", "numpy.expand_dims", "tensorflow.add_to_collection", "tensorflow.logical_not", "collections.namedtuple", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits" ]
[((590, 806), 'collections.namedtuple', 'namedtuple', (['"""TextboxParameters"""', "['img_shape', 'num_classes', 'feat_layers', 'feat_shapes', 'scale_range',\n 'anchor_ratios', 'anchor_sizes', 'anchor_steps', 'normalizations',\n 'prior_scaling', 'step', 'scales']"], {}), "('TextboxParameters', ['img_shape', 'num_classes', 'feat_layers',\n 'feat_shapes', 'scale_range', 'anchor_ratios', 'anchor_sizes',\n 'anchor_steps', 'normalizations', 'prior_scaling', 'step', 'scales'])\n", (600, 806), False, 'from collections import namedtuple\n'), ((7157, 7253), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', 'num_loc_pred', '[3, 5]'], {'activation_fn': 'None', 'padding': '"""SAME"""', 'scope': '"""conv_loc"""'}), "(net, num_loc_pred, [3, 5], activation_fn=None, padding='SAME',\n scope='conv_loc')\n", (7168, 7253), True, 'import tensorflow.contrib.slim as slim\n'), ((7318, 7340), 'tensorflow.contrib.slim.flatten', 'slim.flatten', (['loc_pred'], {}), '(loc_pred)\n', (7330, 7340), True, 'import tensorflow.contrib.slim as slim\n'), ((7407, 7449), 'tensorflow.reshape', 'tf.reshape', (['loc_pred', '[batch_size, -1, 12]'], {}), '(loc_pred, [batch_size, -1, 12])\n', (7417, 7449), True, 'import tensorflow as tf\n'), ((8009, 8104), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', 'scores_pred', '[3, 5]'], {'activation_fn': 'None', 'padding': '"""SAME"""', 'scope': '"""conv_cls"""'}), "(net, scores_pred, [3, 5], activation_fn=None, padding='SAME',\n scope='conv_cls')\n", (8020, 8104), True, 'import tensorflow.contrib.slim as slim\n'), ((8273, 8295), 'tensorflow.contrib.slim.flatten', 'slim.flatten', (['sco_pred'], {}), '(sco_pred)\n', (8285, 8295), True, 'import tensorflow.contrib.slim as slim\n'), ((8309, 8350), 'tensorflow.reshape', 'tf.reshape', (['sco_pred', '[batch_size, -1, 2]'], {}), '(sco_pred, [batch_size, -1, 2])\n', (8319, 8350), True, 'import tensorflow as tf\n'), ((17412, 17439), 'numpy.stack', 'np.stack', (['(x, x_offset)', '(-1)'], {}), '((x, x_offset), -1)\n', (17420, 17439), True, 'import numpy as np\n'), ((17450, 17477), 'numpy.stack', 'np.stack', (['(y, y_offset)', '(-1)'], {}), '((y, y_offset), -1)\n', (17458, 17477), True, 'import numpy as np\n'), ((17501, 17531), 'numpy.expand_dims', 'np.expand_dims', (['y_out'], {'axis': '(-1)'}), '(y_out, axis=-1)\n', (17515, 17531), True, 'import numpy as np\n'), ((17542, 17572), 'numpy.expand_dims', 'np.expand_dims', (['x_out'], {'axis': '(-1)'}), '(x_out, axis=-1)\n', (17556, 17572), True, 'import numpy as np\n'), ((17625, 17662), 'numpy.zeros', 'np.zeros', (['(num_anchors,)'], {'dtype': 'dtype'}), '((num_anchors,), dtype=dtype)\n', (17633, 17662), True, 'import numpy as np\n'), ((17669, 17706), 'numpy.zeros', 'np.zeros', (['(num_anchors,)'], {'dtype': 'dtype'}), '((num_anchors,), dtype=dtype)\n', (17677, 17706), True, 'import numpy as np\n'), ((5186, 5345), 'nets.textbox_common.tf_text_bboxes_encode', 'textbox_common.tf_text_bboxes_encode', (['glabels', 'bboxes', 'anchors', 'gxs', 'gys'], {'matching_threshold': '(0.5)', 'prior_scaling': 'self.params.prior_scaling', 'scope': 'scope'}), '(glabels, bboxes, anchors, gxs, gys,\n matching_threshold=0.5, prior_scaling=self.params.prior_scaling, scope=\n scope)\n', (5222, 5345), False, 'from nets import textbox_common\n'), ((6612, 6661), 'nets.custom_layers.l2_normalization', 'custom_layers.l2_normalization', (['net'], {'scaling': '(True)'}), '(net, scaling=True)\n', (6642, 6661), False, 'from nets import custom_layers\n'), ((8836, 8899), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope', '"""text_box_300"""', '[inputs]'], {'reuse': 'reuse'}), "(scope, 'text_box_300', [inputs], reuse=reuse)\n", (8853, 8899), True, 'import tensorflow as tf\n'), ((8958, 9020), 'tensorflow.contrib.slim.repeat', 'slim.repeat', (['inputs', '(2)', 'slim.conv2d', '(64)', '[3, 3]'], {'scope': '"""conv1"""'}), "(inputs, 2, slim.conv2d, 64, [3, 3], scope='conv1')\n", (8969, 9020), True, 'import tensorflow.contrib.slim as slim\n'), ((9070, 9113), 'tensorflow.contrib.slim.max_pool2d', 'slim.max_pool2d', (['net', '[2, 2]'], {'scope': '"""pool1"""'}), "(net, [2, 2], scope='pool1')\n", (9085, 9113), True, 'import tensorflow.contrib.slim as slim\n'), ((9144, 9204), 'tensorflow.contrib.slim.repeat', 'slim.repeat', (['net', '(2)', 'slim.conv2d', '(128)', '[3, 3]'], {'scope': '"""conv2"""'}), "(net, 2, slim.conv2d, 128, [3, 3], scope='conv2')\n", (9155, 9204), True, 'import tensorflow.contrib.slim as slim\n'), ((9254, 9297), 'tensorflow.contrib.slim.max_pool2d', 'slim.max_pool2d', (['net', '[2, 2]'], {'scope': '"""pool2"""'}), "(net, [2, 2], scope='pool2')\n", (9269, 9297), True, 'import tensorflow.contrib.slim as slim\n'), ((9327, 9387), 'tensorflow.contrib.slim.repeat', 'slim.repeat', (['net', '(3)', 'slim.conv2d', '(256)', '[3, 3]'], {'scope': '"""conv3"""'}), "(net, 3, slim.conv2d, 256, [3, 3], scope='conv3')\n", (9338, 9387), True, 'import tensorflow.contrib.slim as slim\n'), ((9435, 9478), 'tensorflow.contrib.slim.max_pool2d', 'slim.max_pool2d', (['net', '[2, 2]'], {'scope': '"""pool3"""'}), "(net, [2, 2], scope='pool3')\n", (9450, 9478), True, 'import tensorflow.contrib.slim as slim\n'), ((9508, 9568), 'tensorflow.contrib.slim.repeat', 'slim.repeat', (['net', '(3)', 'slim.conv2d', '(512)', '[3, 3]'], {'scope': '"""conv4"""'}), "(net, 3, slim.conv2d, 512, [3, 3], scope='conv4')\n", (9519, 9568), True, 'import tensorflow.contrib.slim as slim\n'), ((9643, 9686), 'tensorflow.contrib.slim.max_pool2d', 'slim.max_pool2d', (['net', '[2, 2]'], {'scope': '"""pool4"""'}), "(net, [2, 2], scope='pool4')\n", (9658, 9686), True, 'import tensorflow.contrib.slim as slim\n'), ((9716, 9776), 'tensorflow.contrib.slim.repeat', 'slim.repeat', (['net', '(3)', 'slim.conv2d', '(512)', '[3, 3]'], {'scope': '"""conv5"""'}), "(net, 3, slim.conv2d, 512, [3, 3], scope='conv5')\n", (9727, 9776), True, 'import tensorflow.contrib.slim as slim\n'), ((9821, 9874), 'tensorflow.contrib.slim.max_pool2d', 'slim.max_pool2d', (['net', '[3, 3]'], {'stride': '(1)', 'scope': '"""pool5"""'}), "(net, [3, 3], stride=1, scope='pool5')\n", (9836, 9874), True, 'import tensorflow.contrib.slim as slim\n'), ((9967, 10020), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(1024)', '[3, 3]'], {'rate': '(6)', 'scope': '"""conv6"""'}), "(net, 1024, [3, 3], rate=6, scope='conv6')\n", (9978, 10020), True, 'import tensorflow.contrib.slim as slim\n'), ((10107, 10152), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(1024)', '[1, 1]'], {'scope': '"""conv7"""'}), "(net, 1024, [1, 1], scope='conv7')\n", (10118, 10152), True, 'import tensorflow.contrib.slim as slim\n'), ((22300, 22334), 'tensorflow.name_scope', 'tf.name_scope', (['scope', '"""txt_losses"""'], {}), "(scope, 'txt_losses')\n", (22313, 22334), True, 'import tensorflow as tf\n'), ((22348, 22375), 'tf_extended.get_shape', 'tfe.get_shape', (['logits[0]', '(5)'], {}), '(logits[0], 5)\n', (22361, 22375), True, 'import tf_extended as tfe\n'), ((23031, 23058), 'tensorflow.concat', 'tf.concat', (['fglabels'], {'axis': '(1)'}), '(fglabels, axis=1)\n', (23040, 23058), True, 'import tensorflow as tf\n'), ((23071, 23097), 'tensorflow.concat', 'tf.concat', (['flogits'], {'axis': '(1)'}), '(flogits, axis=1)\n', (23080, 23097), True, 'import tensorflow as tf\n'), ((23116, 23143), 'tensorflow.concat', 'tf.concat', (['fgscores'], {'axis': '(1)'}), '(fgscores, axis=1)\n', (23125, 23143), True, 'import tensorflow as tf\n'), ((23168, 23201), 'tensorflow.concat', 'tf.concat', (['flocalisations'], {'axis': '(1)'}), '(flocalisations, axis=1)\n', (23177, 23201), True, 'import tensorflow as tf\n'), ((23227, 23261), 'tensorflow.concat', 'tf.concat', (['fglocalisations'], {'axis': '(1)'}), '(fglocalisations, axis=1)\n', (23236, 23261), True, 'import tensorflow as tf\n'), ((23524, 23548), 'tensorflow.cast', 'tf.cast', (['pmask', 'tf.int32'], {}), '(pmask, tf.int32)\n', (23531, 23548), True, 'import tensorflow as tf\n'), ((23582, 23603), 'tensorflow.cast', 'tf.cast', (['pmask', 'dtype'], {}), '(pmask, dtype)\n', (23589, 23603), True, 'import tensorflow as tf\n'), ((23644, 23665), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['fpmask'], {}), '(fpmask)\n', (23657, 23665), True, 'import tensorflow as tf\n'), ((23755, 23779), 'tensorflow.cast', 'tf.cast', (['pmask', 'tf.int32'], {}), '(pmask, tf.int32)\n', (23762, 23779), True, 'import tensorflow as tf\n'), ((23797, 23817), 'tensorflow.contrib.slim.softmax', 'slim.softmax', (['logits'], {}), '(logits)\n', (23809, 23817), True, 'import tensorflow.contrib.slim as slim\n'), ((23927, 23948), 'tensorflow.cast', 'tf.cast', (['nmask', 'dtype'], {}), '(nmask, dtype)\n', (23934, 23948), True, 'import tensorflow as tf\n'), ((23962, 24013), 'tensorflow.where', 'tf.where', (['nmask', 'predictions[:, :, 0]', '(1.0 - fnmask)'], {}), '(nmask, predictions[:, :, 0], 1.0 - fnmask)\n', (23970, 24013), True, 'import tensorflow as tf\n'), ((24075, 24100), 'tensorflow.reshape', 'tf.reshape', (['nvalues', '[-1]'], {}), '(nvalues, [-1])\n', (24085, 24100), True, 'import tensorflow as tf\n'), ((24289, 24323), 'tensorflow.minimum', 'tf.minimum', (['n_neg', 'max_neg_entries'], {}), '(n_neg, max_neg_entries)\n', (24299, 24323), True, 'import tensorflow as tf\n'), ((24342, 24377), 'tensorflow.nn.top_k', 'tf.nn.top_k', (['(-nvalues_flat)'], {'k': 'n_neg'}), '(-nvalues_flat, k=n_neg)\n', (24353, 24377), True, 'import tensorflow as tf\n'), ((24443, 24489), 'tensorflow.logical_and', 'tf.logical_and', (['nmask', '(nvalues < max_hard_pred)'], {}), '(nmask, nvalues < max_hard_pred)\n', (24457, 24489), True, 'import tensorflow as tf\n'), ((24502, 24523), 'tensorflow.cast', 'tf.cast', (['nmask', 'dtype'], {}), '(nmask, dtype)\n', (24509, 24523), True, 'import tensorflow as tf\n'), ((24536, 24560), 'tensorflow.cast', 'tf.cast', (['nmask', 'tf.int32'], {}), '(nmask, tf.int32)\n', (24543, 24560), True, 'import tensorflow as tf\n'), ((10304, 10332), 'tensorflow.variable_scope', 'tf.variable_scope', (['end_point'], {}), '(end_point)\n', (10321, 10332), True, 'import tensorflow as tf\n'), ((10344, 10390), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(256)', '[1, 1]'], {'scope': '"""conv1x1"""'}), "(net, 256, [1, 1], scope='conv1x1')\n", (10355, 10390), True, 'import tensorflow.contrib.slim as slim\n'), ((10401, 10437), 'nets.custom_layers.pad2d', 'custom_layers.pad2d', (['net'], {'pad': '(1, 1)'}), '(net, pad=(1, 1))\n', (10420, 10437), False, 'from nets import custom_layers\n'), ((10448, 10521), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(512)', '[3, 3]'], {'stride': '(2)', 'scope': '"""conv3x3"""', 'padding': '"""VALID"""'}), "(net, 512, [3, 3], stride=2, scope='conv3x3', padding='VALID')\n", (10459, 10521), True, 'import tensorflow.contrib.slim as slim\n'), ((10592, 10620), 'tensorflow.variable_scope', 'tf.variable_scope', (['end_point'], {}), '(end_point)\n', (10609, 10620), True, 'import tensorflow as tf\n'), ((10632, 10678), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(128)', '[1, 1]'], {'scope': '"""conv1x1"""'}), "(net, 128, [1, 1], scope='conv1x1')\n", (10643, 10678), True, 'import tensorflow.contrib.slim as slim\n'), ((10689, 10725), 'nets.custom_layers.pad2d', 'custom_layers.pad2d', (['net'], {'pad': '(1, 1)'}), '(net, pad=(1, 1))\n', (10708, 10725), False, 'from nets import custom_layers\n'), ((10736, 10809), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(256)', '[3, 3]'], {'stride': '(2)', 'scope': '"""conv3x3"""', 'padding': '"""VALID"""'}), "(net, 256, [3, 3], stride=2, scope='conv3x3', padding='VALID')\n", (10747, 10809), True, 'import tensorflow.contrib.slim as slim\n'), ((10879, 10907), 'tensorflow.variable_scope', 'tf.variable_scope', (['end_point'], {}), '(end_point)\n', (10896, 10907), True, 'import tensorflow as tf\n'), ((10919, 10982), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(128)', '[1, 1]'], {'scope': '"""conv1x1"""', 'padding': '"""VALID"""'}), "(net, 128, [1, 1], scope='conv1x1', padding='VALID')\n", (10930, 10982), True, 'import tensorflow.contrib.slim as slim\n'), ((10994, 11057), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(256)', '[3, 3]'], {'scope': '"""conv3x3"""', 'padding': '"""VALID"""'}), "(net, 256, [3, 3], scope='conv3x3', padding='VALID')\n", (11005, 11057), True, 'import tensorflow.contrib.slim as slim\n'), ((11128, 11156), 'tensorflow.variable_scope', 'tf.variable_scope', (['end_point'], {}), '(end_point)\n', (11145, 11156), True, 'import tensorflow as tf\n'), ((11168, 11214), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(128)', '[1, 1]'], {'scope': '"""conv1x1"""'}), "(net, 128, [1, 1], scope='conv1x1')\n", (11179, 11214), True, 'import tensorflow.contrib.slim as slim\n'), ((11225, 11288), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['net', '(256)', '[3, 3]'], {'scope': '"""conv3x3"""', 'padding': '"""VALID"""'}), "(net, 256, [3, 3], scope='conv3x3', padding='VALID')\n", (11236, 11288), True, 'import tensorflow.contrib.slim as slim\n'), ((11369, 11397), 'tensorflow.variable_scope', 'tf.variable_scope', (['end_point'], {}), '(end_point)\n', (11386, 11397), True, 'import tensorflow as tf\n'), ((11419, 11495), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[3, 3]'], {'stride': '(1)', 'scope': '"""dilation1"""'}), "(end_points[end_point], 128, [3, 3], stride=1, scope='dilation1')\n", (11430, 11495), True, 'import tensorflow.contrib.slim as slim\n'), ((11579, 11675), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[1, 9]'], {'padding': '"""SAME"""', 'stride': '(1)', 'scope': '"""dilation2"""'}), "(end_points[end_point], 128, [1, 9], padding='SAME', stride=1,\n scope='dilation2')\n", (11590, 11675), True, 'import tensorflow.contrib.slim as slim\n'), ((11694, 11790), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[9, 1]'], {'stride': '(1)', 'padding': '"""SAME"""', 'scope': '"""dilation3"""'}), "(end_points[end_point], 128, [9, 1], stride=1, padding='SAME',\n scope='dilation3')\n", (11705, 11790), True, 'import tensorflow.contrib.slim as slim\n'), ((11876, 11947), 'tensorflow.concat', 'tf.concat', ([], {'values': '[net_dilation1, net_dilation2, net_dilation3]', 'axis': '(3)'}), '(values=[net_dilation1, net_dilation2, net_dilation3], axis=3)\n', (11885, 11947), True, 'import tensorflow as tf\n'), ((12030, 12058), 'tensorflow.variable_scope', 'tf.variable_scope', (['end_point'], {}), '(end_point)\n', (12047, 12058), True, 'import tensorflow as tf\n'), ((12080, 12157), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(1024)', '[1, 1]'], {'stride': '(1)', 'scope': '"""dilation1"""'}), "(end_points[end_point], 1024, [1, 1], stride=1, scope='dilation1')\n", (12091, 12157), True, 'import tensorflow.contrib.slim as slim\n'), ((12180, 12257), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(1024)', '[1, 7]'], {'stride': '(1)', 'scope': '"""dilation2"""'}), "(end_points[end_point], 1024, [1, 7], stride=1, scope='dilation2')\n", (12191, 12257), True, 'import tensorflow.contrib.slim as slim\n'), ((12349, 12426), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(1024)', '[7, 1]'], {'stride': '(1)', 'scope': '"""dilation3"""'}), "(end_points[end_point], 1024, [7, 1], stride=1, scope='dilation3')\n", (12360, 12426), True, 'import tensorflow.contrib.slim as slim\n'), ((12518, 12582), 'tensorflow.concat', 'tf.concat', (['[net_dilation1, net_dilation2, net_dilation3]'], {'axis': '(3)'}), '([net_dilation1, net_dilation2, net_dilation3], axis=3)\n', (12527, 12582), True, 'import tensorflow as tf\n'), ((12661, 12689), 'tensorflow.variable_scope', 'tf.variable_scope', (['end_point'], {}), '(end_point)\n', (12678, 12689), True, 'import tensorflow as tf\n'), ((12713, 12789), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[1, 1]'], {'stride': '(1)', 'scope': '"""dilation1"""'}), "(end_points[end_point], 128, [1, 1], stride=1, scope='dilation1')\n", (12724, 12789), True, 'import tensorflow.contrib.slim as slim\n'), ((12811, 12887), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[1, 7]'], {'stride': '(1)', 'scope': '"""dilation2"""'}), "(end_points[end_point], 128, [1, 7], stride=1, scope='dilation2')\n", (12822, 12887), True, 'import tensorflow.contrib.slim as slim\n'), ((12979, 13055), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[7, 1]'], {'stride': '(1)', 'scope': '"""dilation3"""'}), "(end_points[end_point], 128, [7, 1], stride=1, scope='dilation3')\n", (12990, 13055), True, 'import tensorflow.contrib.slim as slim\n'), ((13147, 13211), 'tensorflow.concat', 'tf.concat', (['[net_dilation1, net_dilation2, net_dilation3]'], {'axis': '(3)'}), '([net_dilation1, net_dilation2, net_dilation3], axis=3)\n', (13156, 13211), True, 'import tensorflow as tf\n'), ((13297, 13325), 'tensorflow.variable_scope', 'tf.variable_scope', (['end_point'], {}), '(end_point)\n', (13314, 13325), True, 'import tensorflow as tf\n'), ((13347, 13423), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[1, 1]'], {'stride': '(1)', 'scope': '"""dilation1"""'}), "(end_points[end_point], 128, [1, 1], stride=1, scope='dilation1')\n", (13358, 13423), True, 'import tensorflow.contrib.slim as slim\n'), ((13445, 13521), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[1, 7]'], {'stride': '(1)', 'scope': '"""dilation2"""'}), "(end_points[end_point], 128, [1, 7], stride=1, scope='dilation2')\n", (13456, 13521), True, 'import tensorflow.contrib.slim as slim\n'), ((13613, 13689), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[7, 1]'], {'stride': '(1)', 'scope': '"""dilation3"""'}), "(end_points[end_point], 128, [7, 1], stride=1, scope='dilation3')\n", (13624, 13689), True, 'import tensorflow.contrib.slim as slim\n'), ((13779, 13843), 'tensorflow.concat', 'tf.concat', (['[net_dilation1, net_dilation2, net_dilation3]'], {'axis': '(3)'}), '([net_dilation1, net_dilation2, net_dilation3], axis=3)\n', (13788, 13843), True, 'import tensorflow as tf\n'), ((13925, 13953), 'tensorflow.variable_scope', 'tf.variable_scope', (['end_point'], {}), '(end_point)\n', (13942, 13953), True, 'import tensorflow as tf\n'), ((13977, 14053), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[1, 1]'], {'stride': '(1)', 'scope': '"""dilation1"""'}), "(end_points[end_point], 128, [1, 1], stride=1, scope='dilation1')\n", (13988, 14053), True, 'import tensorflow.contrib.slim as slim\n'), ((14076, 14152), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[1, 7]'], {'stride': '(1)', 'scope': '"""dilation2"""'}), "(end_points[end_point], 128, [1, 7], stride=1, scope='dilation2')\n", (14087, 14152), True, 'import tensorflow.contrib.slim as slim\n'), ((14244, 14320), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[7, 1]'], {'stride': '(1)', 'scope': '"""dilation3"""'}), "(end_points[end_point], 128, [7, 1], stride=1, scope='dilation3')\n", (14255, 14320), True, 'import tensorflow.contrib.slim as slim\n'), ((14410, 14474), 'tensorflow.concat', 'tf.concat', (['[net_dilation1, net_dilation2, net_dilation3]'], {'axis': '(3)'}), '([net_dilation1, net_dilation2, net_dilation3], axis=3)\n', (14419, 14474), True, 'import tensorflow as tf\n'), ((14559, 14587), 'tensorflow.variable_scope', 'tf.variable_scope', (['end_point'], {}), '(end_point)\n', (14576, 14587), True, 'import tensorflow as tf\n'), ((14611, 14687), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[1, 1]'], {'stride': '(1)', 'scope': '"""dilation1"""'}), "(end_points[end_point], 128, [1, 1], stride=1, scope='dilation1')\n", (14622, 14687), True, 'import tensorflow.contrib.slim as slim\n'), ((14709, 14785), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[1, 5]'], {'stride': '(1)', 'scope': '"""dilation2"""'}), "(end_points[end_point], 128, [1, 5], stride=1, scope='dilation2')\n", (14720, 14785), True, 'import tensorflow.contrib.slim as slim\n'), ((14877, 14953), 'tensorflow.contrib.slim.conv2d', 'slim.conv2d', (['end_points[end_point]', '(128)', '[5, 1]'], {'stride': '(1)', 'scope': '"""dilation3"""'}), "(end_points[end_point], 128, [5, 1], stride=1, scope='dilation3')\n", (14888, 14953), True, 'import tensorflow.contrib.slim as slim\n'), ((15043, 15107), 'tensorflow.concat', 'tf.concat', (['[net_dilation1, net_dilation2, net_dilation3]'], {'axis': '(3)'}), '([net_dilation1, net_dilation2, net_dilation3], axis=3)\n', (15052, 15107), True, 'import tensorflow as tf\n'), ((17826, 17854), 'math.sqrt', 'math.sqrt', (['(size[0] * size[1])'], {}), '(size[0] * size[1])\n', (17835, 17854), False, 'import math\n'), ((17880, 17908), 'math.sqrt', 'math.sqrt', (['(size[0] * size[1])'], {}), '(size[0] * size[1])\n', (17889, 17908), False, 'import math\n'), ((18007, 18019), 'math.sqrt', 'math.sqrt', (['r'], {}), '(r)\n', (18016, 18019), False, 'import math\n'), ((18058, 18070), 'math.sqrt', 'math.sqrt', (['r'], {}), '(r)\n', (18067, 18070), False, 'import math\n'), ((19182, 19274), 'tensorflow.contrib.slim.arg_scope', 'slim.arg_scope', (['[slim.conv2d, slim.max_pool2d]'], {'padding': '"""SAME"""', 'data_format': 'data_format'}), "([slim.conv2d, slim.max_pool2d], padding='SAME', data_format=\n data_format)\n", (19196, 19274), True, 'import tensorflow.contrib.slim as slim\n'), ((21116, 21180), 'tensorflow.contrib.slim.arg_scope', 'slim.arg_scope', (['[slim.fully_connected]'], {'activation_fn': 'tf.nn.relu'}), '([slim.fully_connected], activation_fn=tf.nn.relu)\n', (21130, 21180), True, 'import tensorflow.contrib.slim as slim\n'), ((23847, 23868), 'tensorflow.logical_not', 'tf.logical_not', (['pmask'], {}), '(pmask)\n', (23861, 23868), True, 'import tensorflow as tf\n'), ((24173, 24194), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['fnmask'], {}), '(fnmask)\n', (24186, 24194), True, 'import tensorflow as tf\n'), ((24217, 24264), 'tensorflow.cast', 'tf.cast', (['(negative_ratio * n_positives)', 'tf.int32'], {}), '(negative_ratio * n_positives, tf.int32)\n', (24224, 24264), True, 'import tensorflow as tf\n'), ((24670, 24704), 'tensorflow.name_scope', 'tf.name_scope', (['"""cross_entropy_pos"""'], {}), "('cross_entropy_pos')\n", (24683, 24704), True, 'import tensorflow as tf\n'), ((24717, 24794), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'logits', 'labels': 'glabels'}), '(logits=logits, labels=glabels)\n', (24763, 24794), True, 'import tensorflow as tf\n'), ((24873, 24897), 'tensorflow.losses.add_loss', 'tf.losses.add_loss', (['loss'], {}), '(loss)\n', (24891, 24897), True, 'import tensorflow as tf\n'), ((24937, 24971), 'tensorflow.name_scope', 'tf.name_scope', (['"""cross_entropy_neg"""'], {}), "('cross_entropy_neg')\n", (24950, 24971), True, 'import tensorflow as tf\n'), ((24984, 25069), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'logits', 'labels': 'no_classes'}), '(logits=logits, labels=no_classes\n )\n', (25030, 25069), True, 'import tensorflow as tf\n'), ((25201, 25225), 'tensorflow.losses.add_loss', 'tf.losses.add_loss', (['loss'], {}), '(loss)\n', (25219, 25225), True, 'import tensorflow as tf\n'), ((25312, 25341), 'tensorflow.name_scope', 'tf.name_scope', (['"""localization"""'], {}), "('localization')\n", (25325, 25341), True, 'import tensorflow as tf\n'), ((25412, 25451), 'tensorflow.expand_dims', 'tf.expand_dims', (['(alpha * fpmask)'], {'axis': '(-1)'}), '(alpha * fpmask, axis=-1)\n', (25426, 25451), True, 'import tensorflow as tf\n'), ((25711, 25767), 'nets.custom_layers.abs_smooth', 'custom_layers.abs_smooth', (['(localisations - glocalisations)'], {}), '(localisations - glocalisations)\n', (25735, 25767), False, 'from nets import custom_layers\n'), ((25847, 25871), 'tensorflow.losses.add_loss', 'tf.losses.add_loss', (['loss'], {}), '(loss)\n', (25865, 25871), True, 'import tensorflow as tf\n'), ((25905, 25927), 'tensorflow.name_scope', 'tf.name_scope', (['"""total"""'], {}), "('total')\n", (25918, 25927), True, 'import tensorflow as tf\n'), ((25951, 25993), 'tensorflow.add_n', 'tf.add_n', (['l_cross_pos', '"""cross_entropy_pos"""'], {}), "(l_cross_pos, 'cross_entropy_pos')\n", (25959, 25993), True, 'import tensorflow as tf\n'), ((26016, 26058), 'tensorflow.add_n', 'tf.add_n', (['l_cross_neg', '"""cross_entropy_neg"""'], {}), "(l_cross_neg, 'cross_entropy_neg')\n", (26024, 26058), True, 'import tensorflow as tf\n'), ((26077, 26134), 'tensorflow.add', 'tf.add', (['total_cross_pos', 'total_cross_neg', '"""cross_entropy"""'], {}), "(total_cross_pos, total_cross_neg, 'cross_entropy')\n", (26083, 26134), True, 'import tensorflow as tf\n'), ((26151, 26182), 'tensorflow.add_n', 'tf.add_n', (['l_loc', '"""localization"""'], {}), "(l_loc, 'localization')\n", (26159, 26182), True, 'import tensorflow as tf\n'), ((26229, 26282), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""EXTRA_LOSSES"""', 'total_cross_pos'], {}), "('EXTRA_LOSSES', total_cross_pos)\n", (26249, 26282), True, 'import tensorflow as tf\n'), ((26287, 26340), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""EXTRA_LOSSES"""', 'total_cross_neg'], {}), "('EXTRA_LOSSES', total_cross_neg)\n", (26307, 26340), True, 'import tensorflow as tf\n'), ((26345, 26394), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""EXTRA_LOSSES"""', 'total_cross'], {}), "('EXTRA_LOSSES', total_cross)\n", (26365, 26394), True, 'import tensorflow as tf\n'), ((26399, 26446), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""EXTRA_LOSSES"""', 'total_loc'], {}), "('EXTRA_LOSSES', total_loc)\n", (26419, 26446), True, 'import tensorflow as tf\n'), ((15309, 15342), 'tensorflow.variable_scope', 'tf.variable_scope', (["(layer + '_box')"], {}), "(layer + '_box')\n", (15326, 15342), True, 'import tensorflow as tf\n'), ((18991, 19024), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['weight_decay'], {}), '(weight_decay)\n', (19010, 19024), True, 'import tensorflow.contrib.slim as slim\n'), ((19068, 19106), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (19104, 19106), True, 'import tensorflow as tf\n'), ((19149, 19171), 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), '()\n', (19169, 19171), True, 'import tensorflow as tf\n'), ((19326, 19455), 'tensorflow.contrib.slim.arg_scope', 'slim.arg_scope', (['[custom_layers.pad2d, custom_layers.l2_normalization, custom_layers.\n channel_to_last]'], {'data_format': 'data_format'}), '([custom_layers.pad2d, custom_layers.l2_normalization,\n custom_layers.channel_to_last], data_format=data_format)\n', (19340, 19455), True, 'import tensorflow.contrib.slim as slim\n'), ((24813, 24841), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(loss * fpmask)'], {}), '(loss * fpmask)\n', (24826, 24841), True, 'import tensorflow as tf\n'), ((25141, 25169), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(loss * fnmask)'], {}), '(loss * fnmask)\n', (25154, 25169), True, 'import tensorflow as tf\n'), ((25786, 25815), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(loss * weights)'], {}), '(loss * weights)\n', (25799, 25815), True, 'import tensorflow as tf\n'), ((21350, 21412), 'tensorflow.contrib.slim.arg_scope', 'slim.arg_scope', (['[slim.conv2d, slim.max_pool2d]'], {'padding': '"""SAME"""'}), "([slim.conv2d, slim.max_pool2d], padding='SAME')\n", (21364, 21412), True, 'import tensorflow.contrib.slim as slim\n')]
# -*- coding:utf-8 -*- """Strassen算法求矩阵乘法 """ import numpy as np def strassen(A, B): """Strassen算法求矩阵乘法 Args: A(np.array): 矩阵1 B(np.array): 矩阵2 Return: C(np.array): 矩阵乘法结果 """ n, _ = A.shape if n == 1: C = np.array(A[0, 0] * B[0, 0]) return C else: A11 = A[0:n//2, 0:n//2] A12 = A[0:n//2, n//2:] A21 = A[n//2:, 0:n//2] A22 = A[n//2:, n//2:] B11 = B[0:n//2, 0:n//2] B12 = B[0:n//2, n//2:] B21 = B[n//2:, 0:n//2] B22 = B[n//2:, n//2:] S1 = B12 - B22 S2 = A11 + A12 S3 = A21 + A22 S4 = B21 - B11 S5 = A11 + A22 S6 = B11 + B22 S7 = A12 - A22 S8 = B21 + B22 S9 = A11 - A21 S10 = B11 + B12 P1 = strassen(A11, S1) P2 = strassen(S2, B22) P3 = strassen(S3, B11) P4 = strassen(A22, S4) P5 = strassen(S5, S6) P6 = strassen(S7, S8) P7 = strassen(S9, S10) C11 = P5 + P4 - P2 + P6 C12 = P1 + P2 C21 = P3 + P4 C22 = P5 + P1 - P3 - P7 C = np.vstack((np.hstack((C11, C12)), np.hstack((C21, C22)))) return C if __name__ == '__main__': A = np.array([ [1, 2, 3, 4], [4, 3, 2, 1], [1, 3, 5, 7], [7, 5, 3, 1], ]) B = np.array([ [2, 4, 6, 8], [8, 6, 4, 2], [1, 2, 3, 4], [4, 3, 2, 1], ]) print(strassen(A, B))
[ "numpy.array", "numpy.hstack" ]
[((1254, 1320), 'numpy.array', 'np.array', (['[[1, 2, 3, 4], [4, 3, 2, 1], [1, 3, 5, 7], [7, 5, 3, 1]]'], {}), '([[1, 2, 3, 4], [4, 3, 2, 1], [1, 3, 5, 7], [7, 5, 3, 1]])\n', (1262, 1320), True, 'import numpy as np\n'), ((1368, 1434), 'numpy.array', 'np.array', (['[[2, 4, 6, 8], [8, 6, 4, 2], [1, 2, 3, 4], [4, 3, 2, 1]]'], {}), '([[2, 4, 6, 8], [8, 6, 4, 2], [1, 2, 3, 4], [4, 3, 2, 1]])\n', (1376, 1434), True, 'import numpy as np\n'), ((269, 296), 'numpy.array', 'np.array', (['(A[0, 0] * B[0, 0])'], {}), '(A[0, 0] * B[0, 0])\n', (277, 296), True, 'import numpy as np\n'), ((1153, 1174), 'numpy.hstack', 'np.hstack', (['(C11, C12)'], {}), '((C11, C12))\n', (1162, 1174), True, 'import numpy as np\n'), ((1176, 1197), 'numpy.hstack', 'np.hstack', (['(C21, C22)'], {}), '((C21, C22))\n', (1185, 1197), True, 'import numpy as np\n')]
# Copyright 2018 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Testing the TFP Hypothesis strategies. (As opposed to using them to test other things). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from absl.testing import parameterized import hypothesis as hp from hypothesis import strategies as hps import numpy as np from tensorflow_probability.python.internal import hypothesis_testlib as tfp_hps from tensorflow_probability.python.internal import test_util @test_util.test_all_tf_execution_regimes class HypothesisTestlibTest(test_util.TestCase): @parameterized.parameters((support,) for support in tfp_hps.ALL_SUPPORTS) @hp.given(hps.data()) @tfp_hps.tfp_hp_settings() def testTensorsInSupportsAlwaysFinite(self, support, data): try: result_ = data.draw(tfp_hps.tensors_in_support(support)) except NotImplementedError: # Constraint class doesn't have a constrainer function at all, so this # test is moot. return result = self.evaluate(result_) self.assertTrue(np.all(np.isfinite(result))) class HypothesisTestlibTimeoutTest(test_util.TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls._num_test_timeout_runs = 0 @hp.given(hps.data()) @tfp_hps.tfp_hp_settings(max_examples=1000, timeout=10) def testTimeout(self, data): # Trivial Hypothesis test. x = data.draw(hps.floats(allow_nan=False, allow_infinity=False)) self.assertGreaterEqual(x * x, 0) # Sleep for two seconds, so only ~5 test runs fit in the 10s timeout. time.sleep(2) # Check that Hypothesis timeout prevented the test from running more than # six times (the expected five times plus a buffer of one). self._num_test_timeout_runs += 1 self.assertLessEqual(self._num_test_timeout_runs, 6) if __name__ == '__main__': test_util.main()
[ "hypothesis.strategies.data", "tensorflow_probability.python.internal.test_util.main", "absl.testing.parameterized.parameters", "time.sleep", "tensorflow_probability.python.internal.hypothesis_testlib.tensors_in_support", "numpy.isfinite", "tensorflow_probability.python.internal.hypothesis_testlib.tfp_hp_settings", "hypothesis.strategies.floats" ]
[((1260, 1332), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (['((support,) for support in tfp_hps.ALL_SUPPORTS)'], {}), '((support,) for support in tfp_hps.ALL_SUPPORTS)\n', (1284, 1332), False, 'from absl.testing import parameterized\n'), ((1360, 1385), 'tensorflow_probability.python.internal.hypothesis_testlib.tfp_hp_settings', 'tfp_hps.tfp_hp_settings', ([], {}), '()\n', (1383, 1385), True, 'from tensorflow_probability.python.internal import hypothesis_testlib as tfp_hps\n'), ((1934, 1988), 'tensorflow_probability.python.internal.hypothesis_testlib.tfp_hp_settings', 'tfp_hps.tfp_hp_settings', ([], {'max_examples': '(1000)', 'timeout': '(10)'}), '(max_examples=1000, timeout=10)\n', (1957, 1988), True, 'from tensorflow_probability.python.internal import hypothesis_testlib as tfp_hps\n'), ((2518, 2534), 'tensorflow_probability.python.internal.test_util.main', 'test_util.main', ([], {}), '()\n', (2532, 2534), False, 'from tensorflow_probability.python.internal import test_util\n'), ((1345, 1355), 'hypothesis.strategies.data', 'hps.data', ([], {}), '()\n', (1353, 1355), True, 'from hypothesis import strategies as hps\n'), ((2237, 2250), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (2247, 2250), False, 'import time\n'), ((1919, 1929), 'hypothesis.strategies.data', 'hps.data', ([], {}), '()\n', (1927, 1929), True, 'from hypothesis import strategies as hps\n'), ((2069, 2118), 'hypothesis.strategies.floats', 'hps.floats', ([], {'allow_nan': '(False)', 'allow_infinity': '(False)'}), '(allow_nan=False, allow_infinity=False)\n', (2079, 2118), True, 'from hypothesis import strategies as hps\n'), ((1483, 1518), 'tensorflow_probability.python.internal.hypothesis_testlib.tensors_in_support', 'tfp_hps.tensors_in_support', (['support'], {}), '(support)\n', (1509, 1518), True, 'from tensorflow_probability.python.internal import hypothesis_testlib as tfp_hps\n'), ((1727, 1746), 'numpy.isfinite', 'np.isfinite', (['result'], {}), '(result)\n', (1738, 1746), True, 'import numpy as np\n')]
import pandas as pd import numpy as np def append(target_df, df): """Append df to the end of target_df. Intended to be used in a loop where you are appending multiple dataframes together. Parameters ---------- target_df : GeoDataFrame or DataFrame May be none for the first append operation. If so, the df will be returned. df : GeoDataFrame or DataFrame dataframe to append Returns ------- GeoDataFrame or DataFrame """ if target_df is None: return df if len(df) > 0: return target_df.append(df, ignore_index=True, sort=False) return target_df def flatten_series(series): """Convert a series, which may have iterables, into a flattened series, repeating index values as necessary. NOTE: this can also be done using .explode() on the pandas Series or DataFrame. Parameters ---------- series : Series Returns ------- Series index will have duplicate values for each entry in the original iterable for that index """ return pd.Series( np.concatenate(series.values), index=np.repeat(series.index, series.apply(len)) ) def ndarray_append_strings(*args): if len(args) < 2: raise ValueError("Must have at least 2 values to append per element") def get_str(value): if ( isinstance(value, np.ndarray) or isinstance(value, pd.Series) ) and not value.dtype == "O": return value.astype("str") return str(value) result = get_str(args[0]) + get_str(args[1]) for i in range(2, len(args)): result = result + get_str(args[i]) return result
[ "numpy.concatenate" ]
[((1103, 1132), 'numpy.concatenate', 'np.concatenate', (['series.values'], {}), '(series.values)\n', (1117, 1132), True, 'import numpy as np\n')]
import numpy as np import tensorflow as tf from collections import deque import random from . import env np.random.seed(1) tf.set_random_seed(1) def weight_variable(shape, name): initial = tf.truncated_normal(shape, stddev=0.01) return tf.Variable(initial, name=name) def bias_variable(shape, name): initial = tf.constant(0.01, shape=shape) return tf.Variable(initial, name=name) def conv2d(x, W, stride): return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding="SAME") def max_pool_2x2(x, name): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME", name=name) class DeepQNetwork: def __init__( self, n_actions, learning_rate=0.9, reward_decay=0.9, e_greedy=0.9, memory_size=500, batch_size=32, e_greedy_increment=None, e_greedy_init=0.0, output_graph=False, ): self.n_actions = n_actions self.lr = learning_rate self.gamma = reward_decay self.epsilon_max = e_greedy self.memory_size = memory_size self.batch_size = batch_size self.epsilon_increment = e_greedy_increment self.epsilon = e_greedy_init # Memory arrangement: (s, s_, r, a) self.memory = deque() self._build_net() self.sess = tf.Session() if output_graph: tf.summary.FileWriter("logs/", self.sess.graph) self.sess.run(tf.global_variables_initializer()) self.cost_his = [] self.saver = tf.train.Saver() def _build_net(self): # ---------inputs------------- self.s = tf.placeholder(tf.float32, [None, env.max_x, env.max_y, 4], name='s') self.r = tf.placeholder(tf.float32, [None], name='r') self.a = tf.placeholder(tf.float32, [None, self.n_actions], name='a') # ------------------ build evaluate_net ------------------ with tf.variable_scope('eval_net'): W_conv1 = weight_variable([7, 7, 4, 32], "W_conv1") b_conv1 = bias_variable([32], "b_conv1") h_conv1 = tf.nn.relu(conv2d(self.s, W_conv1, 4) + b_conv1, name="conv1") h_pool1 = max_pool_2x2(h_conv1, "pool1") W_conv2 = weight_variable([5, 5, 32, 64], "W_conv2") b_conv2 = bias_variable([64], "b_conv2") h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2, 2) + b_conv2, name="conv2") h_pool2 = max_pool_2x2(h_conv2, "pool2") W_conv3 = weight_variable([3, 3, 64, 128], "W_conv3") b_conv3 = bias_variable([128], "b_conv3") h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3, 2) + b_conv3, name="conv3") # h_pool3 = max_pool_2x2(h_conv3, "pool3") h_flat3 = tf.reshape(h_conv3, [-1, 5120]) W_fc1 = weight_variable([5120, 512], "W_fc1") b_fc1 = bias_variable([512], "b_fc1") h_fc1 = tf.nn.relu(tf.matmul(h_flat3, W_fc1) + b_fc1, name="fc1") W_fc2 = weight_variable([512, self.n_actions], "W_fc2") b_fc2 = bias_variable([self.n_actions], "b_fc2") self.q_eval = tf.matmul(h_fc1, W_fc2) + b_fc2 with tf.variable_scope('loss'): self.q0 = tf.reduce_sum(tf.multiply(self.q_eval, self.a), reduction_indices=1) self.loss = tf.losses.mean_squared_error(self.q0, self.r) with tf.variable_scope('train'): self.train0 = tf.train.AdamOptimizer(self.lr).minimize(self.loss) def store_transition(self, state, state_, reward, action): self.memory.append((state, state_, reward, action)) if len(self.memory) > self.memory_size: self.memory.popleft() def choose_action(self, st): # print(st) val = self.sess.run(self.q_eval, feed_dict={self.s: np.reshape(st, newshape=(1, env.max_x, env.max_y, 4))}) # print(val) if np.random.uniform() < self.epsilon: action = np.argmax(val) else: action = np.random.randint(0, self.n_actions) return action def greedy(self, st): # print(st) val = self.sess.run(self.q_eval, feed_dict={self.s: np.reshape(st, newshape=(1, env.max_x, env.max_y, 4))}) action = np.argmax(val) # print(val) return action def learn(self): # Experience Replay batch_memory = random.sample(self.memory, self.batch_size) batch_s = [d[0] for d in batch_memory] batch_s_ = [d[1] for d in batch_memory] batch_r = [d[2] for d in batch_memory] batch_a = [d[3] for d in batch_memory] batch_target = [] batch_action = [] s_eval = self.sess.run(self.q_eval, feed_dict={self.s: batch_s_}) # Compute q-target for i in range(0, len(batch_memory)): batch_target.append(batch_r[i] + self.gamma * np.max(s_eval[i])) a_ = np.zeros(self.n_actions) a_[batch_a[i]] = 1 batch_action.append(a_) _, cost = self.sess.run( [self.train0, self.loss], feed_dict={ self.s: batch_s, self.r: batch_target, self.a: batch_action, }) # ---------------------------------------------------- self.cost_his.append(cost) self.epsilon = self.epsilon + self.epsilon_increment if self.epsilon < self.epsilon_max else self.epsilon_max def save(self, path): try: save_path = self.saver.save(self.sess, path) print("Model saved in path: %s" % save_path) except IOError: print("IOError: Model is not saved.") def load(self, path): self.saver.restore(self.sess, path) print("Successfully loaded.") def plot_cost(self): import matplotlib.pyplot as plt plt.plot(np.arange(len(self.cost_his)), self.cost_his) plt.ylabel('Cost') plt.xlabel('training steps') plt.show()
[ "numpy.random.seed", "numpy.argmax", "random.sample", "tensorflow.reshape", "tensorflow.train.AdamOptimizer", "tensorflow.matmul", "tensorflow.multiply", "tensorflow.Variable", "numpy.random.randint", "tensorflow.nn.conv2d", "tensorflow.truncated_normal", "collections.deque", "tensorflow.variable_scope", "tensorflow.set_random_seed", "tensorflow.placeholder", "numpy.max", "tensorflow.summary.FileWriter", "numpy.reshape", "matplotlib.pyplot.show", "tensorflow.train.Saver", "tensorflow.losses.mean_squared_error", "tensorflow.global_variables_initializer", "tensorflow.Session", "tensorflow.constant", "tensorflow.nn.max_pool", "matplotlib.pyplot.ylabel", "numpy.random.uniform", "numpy.zeros", "matplotlib.pyplot.xlabel" ]
[((106, 123), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (120, 123), True, 'import numpy as np\n'), ((124, 145), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1)'], {}), '(1)\n', (142, 145), True, 'import tensorflow as tf\n'), ((196, 235), 'tensorflow.truncated_normal', 'tf.truncated_normal', (['shape'], {'stddev': '(0.01)'}), '(shape, stddev=0.01)\n', (215, 235), True, 'import tensorflow as tf\n'), ((247, 278), 'tensorflow.Variable', 'tf.Variable', (['initial'], {'name': 'name'}), '(initial, name=name)\n', (258, 278), True, 'import tensorflow as tf\n'), ((327, 357), 'tensorflow.constant', 'tf.constant', (['(0.01)'], {'shape': 'shape'}), '(0.01, shape=shape)\n', (338, 357), True, 'import tensorflow as tf\n'), ((369, 400), 'tensorflow.Variable', 'tf.Variable', (['initial'], {'name': 'name'}), '(initial, name=name)\n', (380, 400), True, 'import tensorflow as tf\n'), ((440, 506), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['x', 'W'], {'strides': '[1, stride, stride, 1]', 'padding': '"""SAME"""'}), "(x, W, strides=[1, stride, stride, 1], padding='SAME')\n", (452, 506), True, 'import tensorflow as tf\n'), ((547, 637), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['x'], {'ksize': '[1, 2, 2, 1]', 'strides': '[1, 2, 2, 1]', 'padding': '"""SAME"""', 'name': 'name'}), "(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME',\n name=name)\n", (561, 637), True, 'import tensorflow as tf\n'), ((1294, 1301), 'collections.deque', 'deque', ([], {}), '()\n', (1299, 1301), False, 'from collections import deque\n'), ((1350, 1362), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1360, 1362), True, 'import tensorflow as tf\n'), ((1554, 1570), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1568, 1570), True, 'import tensorflow as tf\n'), ((1654, 1723), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, env.max_x, env.max_y, 4]'], {'name': '"""s"""'}), "(tf.float32, [None, env.max_x, env.max_y, 4], name='s')\n", (1668, 1723), True, 'import tensorflow as tf\n'), ((1741, 1785), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None]'], {'name': '"""r"""'}), "(tf.float32, [None], name='r')\n", (1755, 1785), True, 'import tensorflow as tf\n'), ((1803, 1863), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, self.n_actions]'], {'name': '"""a"""'}), "(tf.float32, [None, self.n_actions], name='a')\n", (1817, 1863), True, 'import tensorflow as tf\n'), ((4255, 4269), 'numpy.argmax', 'np.argmax', (['val'], {}), '(val)\n', (4264, 4269), True, 'import numpy as np\n'), ((4386, 4429), 'random.sample', 'random.sample', (['self.memory', 'self.batch_size'], {}), '(self.memory, self.batch_size)\n', (4399, 4429), False, 'import random\n'), ((5946, 5964), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cost"""'], {}), "('Cost')\n", (5956, 5964), True, 'import matplotlib.pyplot as plt\n'), ((5973, 6001), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""training steps"""'], {}), "('training steps')\n", (5983, 6001), True, 'import matplotlib.pyplot as plt\n'), ((6010, 6020), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6018, 6020), True, 'import matplotlib.pyplot as plt\n'), ((1400, 1447), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['"""logs/"""', 'self.sess.graph'], {}), "('logs/', self.sess.graph)\n", (1421, 1447), True, 'import tensorflow as tf\n'), ((1471, 1504), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1502, 1504), True, 'import tensorflow as tf\n'), ((1945, 1974), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""eval_net"""'], {}), "('eval_net')\n", (1962, 1974), True, 'import tensorflow as tf\n'), ((2773, 2804), 'tensorflow.reshape', 'tf.reshape', (['h_conv3', '[-1, 5120]'], {}), '(h_conv3, [-1, 5120])\n', (2783, 2804), True, 'import tensorflow as tf\n'), ((3194, 3219), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""loss"""'], {}), "('loss')\n", (3211, 3219), True, 'import tensorflow as tf\n'), ((3336, 3381), 'tensorflow.losses.mean_squared_error', 'tf.losses.mean_squared_error', (['self.q0', 'self.r'], {}), '(self.q0, self.r)\n', (3364, 3381), True, 'import tensorflow as tf\n'), ((3395, 3421), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""train"""'], {}), "('train')\n", (3412, 3421), True, 'import tensorflow as tf\n'), ((3909, 3928), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (3926, 3928), True, 'import numpy as np\n'), ((3966, 3980), 'numpy.argmax', 'np.argmax', (['val'], {}), '(val)\n', (3975, 3980), True, 'import numpy as np\n'), ((4016, 4052), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.n_actions'], {}), '(0, self.n_actions)\n', (4033, 4052), True, 'import numpy as np\n'), ((4944, 4968), 'numpy.zeros', 'np.zeros', (['self.n_actions'], {}), '(self.n_actions)\n', (4952, 4968), True, 'import numpy as np\n'), ((3148, 3171), 'tensorflow.matmul', 'tf.matmul', (['h_fc1', 'W_fc2'], {}), '(h_fc1, W_fc2)\n', (3157, 3171), True, 'import tensorflow as tf\n'), ((3257, 3289), 'tensorflow.multiply', 'tf.multiply', (['self.q_eval', 'self.a'], {}), '(self.q_eval, self.a)\n', (3268, 3289), True, 'import tensorflow as tf\n'), ((2945, 2970), 'tensorflow.matmul', 'tf.matmul', (['h_flat3', 'W_fc1'], {}), '(h_flat3, W_fc1)\n', (2954, 2970), True, 'import tensorflow as tf\n'), ((3449, 3480), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['self.lr'], {}), '(self.lr)\n', (3471, 3480), True, 'import tensorflow as tf\n'), ((3821, 3874), 'numpy.reshape', 'np.reshape', (['st'], {'newshape': '(1, env.max_x, env.max_y, 4)'}), '(st, newshape=(1, env.max_x, env.max_y, 4))\n', (3831, 3874), True, 'import numpy as np\n'), ((4182, 4235), 'numpy.reshape', 'np.reshape', (['st'], {'newshape': '(1, env.max_x, env.max_y, 4)'}), '(st, newshape=(1, env.max_x, env.max_y, 4))\n', (4192, 4235), True, 'import numpy as np\n'), ((4908, 4925), 'numpy.max', 'np.max', (['s_eval[i]'], {}), '(s_eval[i])\n', (4914, 4925), True, 'import numpy as np\n')]
import pandas as pd import numpy as np import glob import os import warnings from joblib import wrap_non_picklable_objects from ..util import get_unique_str_markers def proc_fop(fop): # If provided as just % number, divide by 100 if not isinstance(fop, tuple): fop /= 100 return (fop, 1-fop) elif fop[0] is None: return tuple([None, 1-(fop[1] / 100)]) elif fop[1] is None: return tuple([fop[0] / 100, None]) return tuple([fop[0]/100, 1-(fop[1] / 100)]) def auto_determine_subjects(file_paths, existing_index): # Check if is integer index is_int = False if hasattr(existing_index, 'dtype'): is_int = 'int' in existing_index.dtype.name # Set as list from index existing_index = list(existing_index) if len(existing_index) > 1: # If int, need to handle special case if is_int: existing_index = [str(i) for i in existing_index] # Figure out from existing index # how it would have been loaded by auto ei_as_auto_subjs = auto_determine_subjects(existing_index, []) # Use this information to generate templates templates = [ei.replace(ei_subj, 'SUBJ-MARKER') for ei, ei_subj in zip(existing_index, ei_as_auto_subjs)] # In the case where some templates are messed up # e.g., the common path may repeat, e.g., # ['subjs_grp1-0001', 'subjs_grp1-0002', 'subjs_grp1-0003'] # we want to get the most common template unique, cnts = np.unique(templates, return_counts=True) template = unique[np.argmax(cnts)] # Otherwise no template is used else: template = None # Get top common sub strings, then remove # from all pieces subjects = get_unique_str_markers(file_paths, template=template, template_marker='SUBJ-MARKER') if is_int: subjects = [int(s) for s in subjects] return subjects def proc_file_input(files, file_to_subject, existing_index=None): if existing_index is None: existing_index = [] if not isinstance(files, dict): raise ValueError('files must be passed as a python dict') if file_to_subject is None: raise RuntimeError('file_to_subject must be specified!') # If not passed as dict, convert to dict if not isinstance(file_to_subject, dict): file_to_subject = {key: file_to_subject for key in files} # Check for key in files: if key not in file_to_subject: raise ValueError('If passing file_to_subject as a dict ' 'then a value must be passed for all ' 'keys in files. ' + repr(key) + 'was ' 'not passed in this case.') # Compute pd series files_series = dict() for key in files: file_paths = files[key] # If passed file path as str, assume globbing if isinstance(file_paths, str): file_paths = glob.glob(file_paths) # Auto case if file_to_subject[key] == 'auto': subjects = auto_determine_subjects(file_paths, existing_index=existing_index) # Otherwise normal function else: subjects = [file_to_subject[key](fp) for fp in file_paths] # If more subjects than unique subjects # assume DataFile is made of multiple paths if len(subjects) != len(np.unique(subjects)): # Convert to dict of subjects to list of paths subjects_dict = {subject: [] for subject in set(subjects)} for subject, path in zip(subjects, file_paths): subjects_dict[subject].append(path) # Then convert to two lists lists subjects, file_paths = list(subjects_dict.keys()), list(subjects_dict.values()) # Put together in series files_series[key] = pd.Series(file_paths, index=subjects, dtype='object') return files_series def base_load_subjects(subjects): loaded_subjects = set() if isinstance(subjects, str): with open(subjects, 'r') as f: lines = f.readlines() for line in lines: subject = line.rstrip() try: subject = eval(subject) except NameError: subject = subject loaded_subjects.add(subject) else: loaded_subjects = set([s for s in subjects]) return loaded_subjects def save_subjects(loc, subjects): with open(loc, 'w') as f: for subject in subjects: f.write(repr(subject) + '\n') def add_new_categories(existing, new_values): # This is only relevant for type category if existing.dtype.name != 'category': return existing # Only add new categories new_cats = set(pd.unique(new_values)) existing_cats = set(existing.dtype.categories) to_add = new_cats - existing_cats # Add categories return existing.cat.add_categories(list(to_add)) def remove_unused_categories(existing): # This is only relevant for type category if existing.dtype.name != 'category': return existing to_remove = set(existing.dtype.categories) - set(pd.unique(existing)) to_remove = to_remove - set([np.nan]) return existing.cat.remove_categories(list(to_remove)) def get_str_round(val, places=3): if isinstance(val, int): return val return str(np.round(float(val), places)) def verbose_print(self, *args, **kwargs): '''Overriding the print function to allow for customizable verbosity. According to passed level: Warnings are level 0, Information on sizes / how many dropped are level 1. Set to level -1 to mute warnings too. Parameters ---------- args Anything that would be passed to default python print ''' if 'level' in kwargs: level = kwargs.pop('level') else: level = 1 if self.verbose >= level: # Use warnings for level = 0 if level == 0: # Conv print to str - then warn sep = ' ' if 'sep' in kwargs: sep = kwargs.pop('sep') as_str = sep.join(str(arg) for arg in args) warnings.warn(as_str) # Use base print for rest else: print(flush=True, *args, **kwargs) def mp_consol_save(data_files, index, cast_to, save_dr): # Load the subjects data subj_data = [df.load() for df in data_files] # Stack the subj data with extra columns at last axis subj_data = np.stack(subj_data, axis=-1) # Optional cast to dtype if cast_to is not None: subj_data = subj_data.astype(cast_to) # Save as name of index in save loc save_loc = os.path.join(save_dr, str(index) + '.npy') np.save(save_loc, subj_data) return save_loc def wrap_load_func(load_func, _print): if load_func.__module__ == '__main__': wrapped_load_func = wrap_non_picklable_objects(load_func) _print('Warning: Passed load_func was defined within the', '__main__ namespace and therefore has been ' 'cloud wrapped.', 'The function will still work, but it is ' 'reccomended to', 'define this function in a separate file, ' 'and then import', 'it , otherwise loader caching will be limited', 'in utility!', level=0) else: wrapped_load_func = load_func return wrapped_load_func
[ "numpy.stack", "numpy.save", "numpy.argmax", "joblib.wrap_non_picklable_objects", "pandas.unique", "pandas.Series", "glob.glob", "warnings.warn", "numpy.unique" ]
[((6788, 6816), 'numpy.stack', 'np.stack', (['subj_data'], {'axis': '(-1)'}), '(subj_data, axis=-1)\n', (6796, 6816), True, 'import numpy as np\n'), ((7024, 7052), 'numpy.save', 'np.save', (['save_loc', 'subj_data'], {}), '(save_loc, subj_data)\n', (7031, 7052), True, 'import numpy as np\n'), ((1555, 1595), 'numpy.unique', 'np.unique', (['templates'], {'return_counts': '(True)'}), '(templates, return_counts=True)\n', (1564, 1595), True, 'import numpy as np\n'), ((4036, 4089), 'pandas.Series', 'pd.Series', (['file_paths'], {'index': 'subjects', 'dtype': '"""object"""'}), "(file_paths, index=subjects, dtype='object')\n", (4045, 4089), True, 'import pandas as pd\n'), ((5027, 5048), 'pandas.unique', 'pd.unique', (['new_values'], {}), '(new_values)\n', (5036, 5048), True, 'import pandas as pd\n'), ((7187, 7224), 'joblib.wrap_non_picklable_objects', 'wrap_non_picklable_objects', (['load_func'], {}), '(load_func)\n', (7213, 7224), False, 'from joblib import wrap_non_picklable_objects\n'), ((1622, 1637), 'numpy.argmax', 'np.argmax', (['cnts'], {}), '(cnts)\n', (1631, 1637), True, 'import numpy as np\n'), ((3092, 3113), 'glob.glob', 'glob.glob', (['file_paths'], {}), '(file_paths)\n', (3101, 3113), False, 'import glob\n'), ((5423, 5442), 'pandas.unique', 'pd.unique', (['existing'], {}), '(existing)\n', (5432, 5442), True, 'import pandas as pd\n'), ((6457, 6478), 'warnings.warn', 'warnings.warn', (['as_str'], {}), '(as_str)\n', (6470, 6478), False, 'import warnings\n'), ((3570, 3589), 'numpy.unique', 'np.unique', (['subjects'], {}), '(subjects)\n', (3579, 3589), True, 'import numpy as np\n')]
''' AUTHOR : <NAME>. CAPSTONE 2: BUILDING A SMART QUEUE SYSTEM. INTEL(R) EDGE AI FOR IOT DEVELOPERS NANODEGREE. QUEUE SYSTEM AND INFERENCE MODULE. ''' import numpy as np import time from openvino.inference_engine import IECore import os import cv2 import argparse import sys, traceback class Queue: ''' Class for dealing with queues ''' def __init__(self): self.queues=[] def add_queue(self, points): self.queues.append(points) def get_queues(self, image): for q in self.queues: x_min, y_min, x_max, y_max=q frame=image[y_min:y_max, x_min:x_max] yield frame def check_coords(self, coords): d={k+1:0 for k in range(len(self.queues))} for coord in coords: for i, q in enumerate(self.queues): if coord[0]>q[0] and coord[2]<q[2]: d[i+1]+=1 return d class PersonDetect: def __init__(self, model_name, device, threshold=0.60): self.model_weights=model_name+'.bin' self.model_structure=model_name+'.xml' self.device=device self.threshold=threshold self.ie = IECore() try: self.model=self.ie.read_network(self.model_structure, self.model_weights) except Exception as e: raise ValueError("Could not Initialise the network. Have you enterred the correct model path?") self.input_name=next(iter(self.model.inputs)) self.input_shape=self.model.inputs[self.input_name].shape self.output_name=next(iter(self.model.outputs)) self.output_shape=self.model.outputs[self.output_name].shape def load_model(self): self.net_plugin = self.ie.load_network(network=self.model, device_name=self.device) def predict(self, image): prepro_img = self.preprocess_input(image) self.request_handler = self.net_plugin.start_async(request_id=0, inputs={self.input_name:prepro_img}) if self.wait(0) == 0: output = self.net_plugin.requests[0].outputs[self.output_name] coords, image = self.draw_outputs(output, image) return coords, image def draw_outputs(self, coords, image): coords_new = [] for obj in coords[0][0]: if obj[2] > self.threshold: xmin = int(obj[3] * initial_w) ymin = int(obj[4] * initial_h) xmax = int(obj[5] * initial_w) ymax = int(obj[6] * initial_h) color = (210, 0, 100) cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 4) coords_new.append((xmin, ymin, xmax, ymax)) # coords_new.append((int(obj[3]), int(obj[4]), int(obj[5]), int(obj[6]))) return coords_new, image def preprocess_outputs(self, output): raise NotImplementedError def preprocess_input(self, image): n,c,h,w = self.input_shape image = np.copy(image) inf_image = cv2.resize(image, (w, h)) inf_image = inf_image.transpose((2,0,1)) inf_image = inf_image.reshape((n,c,h,w)) return inf_image def wait(self, request_id): ### Implementing the Infinite Wait for Asynchronous Request to deal with the [REQUEST_BUSY] Error wait_for_complete_interface = self.net_plugin.requests[request_id].wait(-1) return wait_for_complete_interface def main(args): model=args.model device=args.device video_file=args.video max_people=args.max_people threshold=args.threshold output_path=args.output_path global initial_h, initial_w start_model_load_time=time.time() pd= PersonDetect(model, device, threshold) pd.load_model() total_model_load_time = time.time() - start_model_load_time queue=Queue() try: queue_param=np.load(args.queue_param) for q in queue_param: queue.add_queue(q) except: print("error loading queue param file") try: cap=cv2.VideoCapture(video_file) except FileNotFoundError: print("Cannot locate video file: "+ video_file) except Exception as e: print("Something else went wrong with the video file: ", e) initial_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) initial_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) video_len = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) out_video = cv2.VideoWriter(os.path.join(output_path, 'output_video.mp4'), cv2.VideoWriter_fourcc(*'avc1'), fps, (initial_w, initial_h), True) counter=0 start_inference_time=time.time() try: while cap.isOpened(): ret, frame=cap.read() if not ret: break counter+=1 coords, image= pd.predict(frame) num_people= queue.check_coords(coords) print(f"Total People in frame = {len(coords)}") print(f"Number of people in queue = {num_people}") out_text="" y_pixel=25 for k, v in num_people.items(): out_text += f"No. of People in Queue {k} is {v} " if v >= int(max_people): out_text += f" Queue full; Please move to next Queue " cv2.putText(image, out_text, (15, y_pixel), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2) out_text="" y_pixel+=40 out_video.write(image) total_time=time.time()-start_inference_time total_inference_time=round(total_time, 1) fps=counter/total_inference_time with open(os.path.join(output_path, 'stats.txt'), 'w') as f: f.write(str(total_inference_time)+'\n') f.write(str(fps)+'\n') f.write(str(total_model_load_time)+'\n') cap.release() cv2.destroyAllWindows() except Exception as e: print("Could not run Inference: ", e) exc_type, exc_value, exc_traceback = sys.exc_info() print( "*** print_tb:") traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print ("*** print_exception:") traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) if __name__=='__main__': parser=argparse.ArgumentParser() parser.add_argument('--model', required=True) parser.add_argument('--device', default='CPU') parser.add_argument('--video', default=None) parser.add_argument('--queue_param', default=None) parser.add_argument('--output_path', default='/results') parser.add_argument('--max_people', default=2) parser.add_argument('--threshold', default=0.60) args=parser.parse_args() main(args)
[ "numpy.load", "cv2.putText", "argparse.ArgumentParser", "numpy.copy", "openvino.inference_engine.IECore", "cv2.VideoWriter_fourcc", "traceback.print_tb", "time.time", "cv2.VideoCapture", "cv2.rectangle", "sys.exc_info", "traceback.print_exception", "cv2.destroyAllWindows", "os.path.join", "cv2.resize" ]
[((3695, 3706), 'time.time', 'time.time', ([], {}), '()\n', (3704, 3706), False, 'import time\n'), ((4673, 4684), 'time.time', 'time.time', ([], {}), '()\n', (4682, 4684), False, 'import time\n'), ((6406, 6431), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6429, 6431), False, 'import argparse\n'), ((1166, 1174), 'openvino.inference_engine.IECore', 'IECore', ([], {}), '()\n', (1172, 1174), False, 'from openvino.inference_engine import IECore\n'), ((3002, 3016), 'numpy.copy', 'np.copy', (['image'], {}), '(image)\n', (3009, 3016), True, 'import numpy as np\n'), ((3037, 3062), 'cv2.resize', 'cv2.resize', (['image', '(w, h)'], {}), '(image, (w, h))\n', (3047, 3062), False, 'import cv2\n'), ((3802, 3813), 'time.time', 'time.time', ([], {}), '()\n', (3811, 3813), False, 'import time\n'), ((3891, 3916), 'numpy.load', 'np.load', (['args.queue_param'], {}), '(args.queue_param)\n', (3898, 3916), True, 'import numpy as np\n'), ((4060, 4088), 'cv2.VideoCapture', 'cv2.VideoCapture', (['video_file'], {}), '(video_file)\n', (4076, 4088), False, 'import cv2\n'), ((4514, 4559), 'os.path.join', 'os.path.join', (['output_path', '"""output_video.mp4"""'], {}), "(output_path, 'output_video.mp4')\n", (4526, 4559), False, 'import os\n'), ((4561, 4592), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'avc1'"], {}), "(*'avc1')\n", (4583, 4592), False, 'import cv2\n'), ((5939, 5962), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (5960, 5962), False, 'import cv2\n'), ((5574, 5585), 'time.time', 'time.time', ([], {}), '()\n', (5583, 5585), False, 'import time\n'), ((6081, 6095), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (6093, 6095), False, 'import sys, traceback\n'), ((6136, 6195), 'traceback.print_tb', 'traceback.print_tb', (['exc_traceback'], {'limit': '(1)', 'file': 'sys.stdout'}), '(exc_traceback, limit=1, file=sys.stdout)\n', (6154, 6195), False, 'import sys, traceback\n'), ((6243, 6335), 'traceback.print_exception', 'traceback.print_exception', (['exc_type', 'exc_value', 'exc_traceback'], {'limit': '(2)', 'file': 'sys.stdout'}), '(exc_type, exc_value, exc_traceback, limit=2, file\n =sys.stdout)\n', (6268, 6335), False, 'import sys, traceback\n'), ((2568, 2626), 'cv2.rectangle', 'cv2.rectangle', (['image', '(xmin, ymin)', '(xmax, ymax)', 'color', '(4)'], {}), '(image, (xmin, ymin), (xmax, ymax), color, 4)\n', (2581, 2626), False, 'import cv2\n'), ((5362, 5454), 'cv2.putText', 'cv2.putText', (['image', 'out_text', '(15, y_pixel)', 'cv2.FONT_HERSHEY_COMPLEX', '(1)', '(0, 255, 0)', '(2)'], {}), '(image, out_text, (15, y_pixel), cv2.FONT_HERSHEY_COMPLEX, 1, (0,\n 255, 0), 2)\n', (5373, 5454), False, 'import cv2\n'), ((5717, 5755), 'os.path.join', 'os.path.join', (['output_path', '"""stats.txt"""'], {}), "(output_path, 'stats.txt')\n", (5729, 5755), False, 'import os\n')]
from typing import List from functools import lru_cache import numpy as np import matplotlib.pyplot as plt from metaflow import Flow, Run def _tokenize_full_text(texts, tokenizer): """Tokenize texts without truncation.""" return tokenizer(texts, padding=True, truncation=False, return_tensors="np") def token_count(texts, tokenizer): """Get number of tokens in original text after tokenization.""" tokenized = _tokenize_full_text(texts, tokenizer) return np.array(tokenized["attention_mask"].sum(axis=1)) def tokenized_length_histogram(lengths, tokenizer): """Plots a cumulative histogram of tokenized text lengths with vertical line indicating `model_max_length`. Args: lengths: List of lengths (number of tokens) of tokenized texts tokenizer: A `transformers` tokenizer Returns: fig: Cumulative normalised histogram of document lengths with a vertical line indicating the max tokens of the model associated with `tokenizer`. """ max_tokens = np.max(lengths) model_max_length = tokenizer.model_max_length fig, ax = plt.subplots() ax.hist( lengths, cumulative=True, histtype="step", density="normed", bins=max_tokens, ) ax.axvline(model_max_length, color="gray", linestyle="--") ax.set_xlabel("N Tokens") ax.set_xlim(0, max_tokens) ax.set_ylabel("Cumulative Frequency (norm)") return fig def random_sample_idx(x, n_samples, seed=100): """Get a random sample of elements from a list-like without replacement.""" n_total = len(x) rn_gen = np.random.RandomState(seed) sample_idx = rn_gen.choice(n_total, size=n_samples, replace=False) return sample_idx def get_nearest_neighbour(index, embedding): """Gets the single nearest neighbours to a series of embeddings from a faiss index.""" embedding = np.array([embedding]) dists, nn_ids = index.search(embedding, 2) dist = dists[0, 1] # nearest neighbours that aren't self nn_id = nn_ids[0, 1] return nn_id, dist @lru_cache def get_latest_runs_by_model() -> List[Run]: """Gets the last successful production run for each encoder. Returns: latest_runs: A list of the last successful production run for each embedding model used. """ runs = Flow("GlassEmbed").runs("project_branch:prod") _model_names = [] latest_runs = [] for run in filter(lambda run: run.successful, runs): try: model_name = run.data.model_name except KeyError: continue if model_name not in _model_names: latest_runs.append(run) _model_names.append(model_name) return latest_runs
[ "metaflow.Flow", "numpy.random.RandomState", "numpy.max", "numpy.array", "matplotlib.pyplot.subplots" ]
[((1044, 1059), 'numpy.max', 'np.max', (['lengths'], {}), '(lengths)\n', (1050, 1059), True, 'import numpy as np\n'), ((1125, 1139), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1137, 1139), True, 'import matplotlib.pyplot as plt\n'), ((1629, 1656), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (1650, 1656), True, 'import numpy as np\n'), ((1908, 1929), 'numpy.array', 'np.array', (['[embedding]'], {}), '([embedding])\n', (1916, 1929), True, 'import numpy as np\n'), ((2352, 2370), 'metaflow.Flow', 'Flow', (['"""GlassEmbed"""'], {}), "('GlassEmbed')\n", (2356, 2370), False, 'from metaflow import Flow, Run\n')]
import numpy as np import pylab as pl import matplotlib as mpl mpl.rcParams['text.usetex'] = True # Optionally, you can import packages mpl.rcParams['text.latex.preamble'] = r'\usepackage{{amsmath}}\usepackage{{amsfonts}}' mainpath = '/data/pt_02015/human_test_data_deconvolution_08088.b3/tp0/mrtrix/' prob_int_tc = np.load(mainpath+'tc_step_0p5_theta_90_th_0p20_npv_50_seed_int.npy') graphcone_p = np.load(mainpath+'graph_mat_cone60_com2com_prob.npy') N = prob_int_tc.shape[0] graphcone_p_row_norm = graphcone_p / ((graphcone_p - np.eye(N)).sum(axis=1))[:, None] log10_prob_graph_row_norm = np.log10(graphcone_p_row_norm) log_tc_plus_1 = np.log10(prob_int_tc+1) # pl.figure() # pl.imshow(log10_prob_graph_row_norm) # pl.xticks([]) # pl.yticks([]) # pl.title(r'$\log_{{10}}{{(\mathbb{{P}}_{{path}})}}$', fontsize=18) # # pl.show() pl.figure() pl.imshow(np.log10(graphcone_p), 'viridis') pl.xticks([]) pl.yticks([]) pl.title(r'$\log_{{10}}{{(\mathbb{{P}}_{{path}})}}$', fontsize=18) pl.colorbar() # pl.show() pl.savefig('/data/hu_paquette/work/tractoGRAPHy/ismrm2022/images/'+'matrix_log_p.png', dpi=300, pad_inches=0.25, transparent=True, bbox_inches='tight') pl.close() pl.figure() pl.imshow(log_tc_plus_1, 'viridis') pl.xticks([]) pl.yticks([]) pl.title(r'$\log_{{10}}{{(\text{{Streamline}}_{{\text{{count}}}} + 1)}}$', fontsize=18) pl.colorbar() # pl.show() pl.savefig('/data/hu_paquette/work/tractoGRAPHy/ismrm2022/images/'+'matrix_log_tc.png', dpi=300, pad_inches=0.25, transparent=True, bbox_inches='tight') pl.close()
[ "pylab.close", "numpy.load", "pylab.title", "pylab.imshow", "pylab.xticks", "pylab.savefig", "pylab.yticks", "pylab.colorbar", "pylab.figure", "numpy.eye", "numpy.log10" ]
[((326, 396), 'numpy.load', 'np.load', (["(mainpath + 'tc_step_0p5_theta_90_th_0p20_npv_50_seed_int.npy')"], {}), "(mainpath + 'tc_step_0p5_theta_90_th_0p20_npv_50_seed_int.npy')\n", (333, 396), True, 'import numpy as np\n'), ((409, 464), 'numpy.load', 'np.load', (["(mainpath + 'graph_mat_cone60_com2com_prob.npy')"], {}), "(mainpath + 'graph_mat_cone60_com2com_prob.npy')\n", (416, 464), True, 'import numpy as np\n'), ((607, 637), 'numpy.log10', 'np.log10', (['graphcone_p_row_norm'], {}), '(graphcone_p_row_norm)\n', (615, 637), True, 'import numpy as np\n'), ((655, 680), 'numpy.log10', 'np.log10', (['(prob_int_tc + 1)'], {}), '(prob_int_tc + 1)\n', (663, 680), True, 'import numpy as np\n'), ((852, 863), 'pylab.figure', 'pl.figure', ([], {}), '()\n', (861, 863), True, 'import pylab as pl\n'), ((908, 921), 'pylab.xticks', 'pl.xticks', (['[]'], {}), '([])\n', (917, 921), True, 'import pylab as pl\n'), ((922, 935), 'pylab.yticks', 'pl.yticks', (['[]'], {}), '([])\n', (931, 935), True, 'import pylab as pl\n'), ((936, 1003), 'pylab.title', 'pl.title', (['"""$\\\\log_{{10}}{{(\\\\mathbb{{P}}_{{path}})}}$"""'], {'fontsize': '(18)'}), "('$\\\\log_{{10}}{{(\\\\mathbb{{P}}_{{path}})}}$', fontsize=18)\n", (944, 1003), True, 'import pylab as pl\n'), ((1003, 1016), 'pylab.colorbar', 'pl.colorbar', ([], {}), '()\n', (1014, 1016), True, 'import pylab as pl\n'), ((1030, 1191), 'pylab.savefig', 'pl.savefig', (["('/data/hu_paquette/work/tractoGRAPHy/ismrm2022/images/' + 'matrix_log_p.png')"], {'dpi': '(300)', 'pad_inches': '(0.25)', 'transparent': '(True)', 'bbox_inches': '"""tight"""'}), "('/data/hu_paquette/work/tractoGRAPHy/ismrm2022/images/' +\n 'matrix_log_p.png', dpi=300, pad_inches=0.25, transparent=True,\n bbox_inches='tight')\n", (1040, 1191), True, 'import pylab as pl\n'), ((1195, 1205), 'pylab.close', 'pl.close', ([], {}), '()\n', (1203, 1205), True, 'import pylab as pl\n'), ((1208, 1219), 'pylab.figure', 'pl.figure', ([], {}), '()\n', (1217, 1219), True, 'import pylab as pl\n'), ((1220, 1255), 'pylab.imshow', 'pl.imshow', (['log_tc_plus_1', '"""viridis"""'], {}), "(log_tc_plus_1, 'viridis')\n", (1229, 1255), True, 'import pylab as pl\n'), ((1256, 1269), 'pylab.xticks', 'pl.xticks', (['[]'], {}), '([])\n', (1265, 1269), True, 'import pylab as pl\n'), ((1270, 1283), 'pylab.yticks', 'pl.yticks', (['[]'], {}), '([])\n', (1279, 1283), True, 'import pylab as pl\n'), ((1284, 1377), 'pylab.title', 'pl.title', (['"""$\\\\log_{{10}}{{(\\\\text{{Streamline}}_{{\\\\text{{count}}}} + 1)}}$"""'], {'fontsize': '(18)'}), "('$\\\\log_{{10}}{{(\\\\text{{Streamline}}_{{\\\\text{{count}}}} + 1)}}$',\n fontsize=18)\n", (1292, 1377), True, 'import pylab as pl\n'), ((1372, 1385), 'pylab.colorbar', 'pl.colorbar', ([], {}), '()\n', (1383, 1385), True, 'import pylab as pl\n'), ((1399, 1561), 'pylab.savefig', 'pl.savefig', (["('/data/hu_paquette/work/tractoGRAPHy/ismrm2022/images/' + 'matrix_log_tc.png')"], {'dpi': '(300)', 'pad_inches': '(0.25)', 'transparent': '(True)', 'bbox_inches': '"""tight"""'}), "('/data/hu_paquette/work/tractoGRAPHy/ismrm2022/images/' +\n 'matrix_log_tc.png', dpi=300, pad_inches=0.25, transparent=True,\n bbox_inches='tight')\n", (1409, 1561), True, 'import pylab as pl\n'), ((1565, 1575), 'pylab.close', 'pl.close', ([], {}), '()\n', (1573, 1575), True, 'import pylab as pl\n'), ((874, 895), 'numpy.log10', 'np.log10', (['graphcone_p'], {}), '(graphcone_p)\n', (882, 895), True, 'import numpy as np\n'), ((546, 555), 'numpy.eye', 'np.eye', (['N'], {}), '(N)\n', (552, 555), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- __author__ = "Yuchen" __aim__ = 'rank top sentences in one topic' __testCase__ = "../test/test_sentenceRanking.py" import argparse import numpy as np # from Processing import process,synonyms import Processing from sentSimilarity import Rouge import operator from tfidf_contentWords import loadData ## for annotation sentences, there have many similar sentences; I hate monday/ I hate monday either. Although diff people select diff sentences, but the meaning is exactly same. # So the question is how to measure the the similar sentence at annotation stage def load_data(i_corpus): """ input data format: txt. sentence --(rank:1) sentence --(rank:0).. :return: """ docs = np.zeros((1 , len(i_corpus)+1), dtype=np.int16) # for ifl in i_corpus: # print (ifl) for ifl in enumerate(i_corpus): print (ifl) if ifl[0] == 0: with open(ifl[1]) as fi: for ln in enumerate(fi): row = np.array([ln[0],ln[1].split(" --(")[0],ln[1].split(" --(")[1].split(")")[0]]) docs = np.row_stack((docs,row)) else: with open(ifl[1]) as fi: list = [0] for ln in enumerate(fi): # print (ln[1]) list.append(ln[1].split(" --(")[1].split(")")[0]) column = np.array(list) docs = np.column_stack((docs, column)) return docs def main(): parser = argparse.ArgumentParser() parser.add_argument('--allData', default='', action='store', nargs='+', help="add train test validation dataset together") args = parser.parse_args() data = load_data(args.allData) ##processing list = [0] for sent in data[:,1][1:]: list.append(Processing.process(sent)) column = np.array(list) data = np.column_stack((data, column)) #find synonyms synonyms_column = [0] for sent in data[:, -1][1:]: synonyms_sent = [] for word in sent.split(): weight = 1/len(sent.split()) # print (weight) word_list = Processing.synonyms(word) synonyms_sent = synonyms_sent + word_list uniqSynon = set(synonyms_sent) synonyms_column.append(uniqSynon) data = np.column_stack((data, synonyms_column)) #calculate similarity dic = {} simiSentences = [] for i in range(1,len(data)): for j in range(i+1,len(data)): enstance = Rouge(' '.join(data[:,-1][i]), ' '.join(data[:,-1][j])) score = enstance.get_rouge_1() dic[i-1, j-1] = score['f'] sorted_x = sorted(dic.items(), key=operator.itemgetter(1),reverse=True) # print (sorted_x) for sents,simiScore in sorted_x: if simiScore > 0.6: simiSentences.append(sents) # print (simiSentences) ## sentence groups allSents = () for item in simiSentences: allSents = allSents + item # print(allSents) senGroup = [] for item in [sent for sent in allSents if sent not in senGroup]: if item not in senGroup: senGroup.append('mark') senGroup.append(item) for index in senGroup: for i, j in simiSentences: if i == index and j not in senGroup: senGroup.append(j) elif j == index and i not in senGroup: senGroup.append(i) # print (senGroup) ## each sentence groups group = {} num = 0 list = [] for i in senGroup: # print (i) if i != 'mark': list.append(i) # print(list) else: group[num] = list num = num + 1 list = [] # print (list) group[num] = list print(group) #delete first row data = np.delete(data, 0, 0) ##annotate similar sentence for row in data: # pass print (row[:,2:-2]) if __name__ == '__main__': """ --allData enlistment_pos1.txt enlistment_pos2.txt """ main()
[ "Processing.synonyms", "argparse.ArgumentParser", "numpy.array", "Processing.process", "numpy.row_stack", "numpy.column_stack", "operator.itemgetter", "numpy.delete" ]
[((1526, 1551), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1549, 1551), False, 'import argparse\n'), ((1893, 1907), 'numpy.array', 'np.array', (['list'], {}), '(list)\n', (1901, 1907), True, 'import numpy as np\n'), ((1919, 1950), 'numpy.column_stack', 'np.column_stack', (['(data, column)'], {}), '((data, column))\n', (1934, 1950), True, 'import numpy as np\n'), ((2360, 2400), 'numpy.column_stack', 'np.column_stack', (['(data, synonyms_column)'], {}), '((data, synonyms_column))\n', (2375, 2400), True, 'import numpy as np\n'), ((3921, 3942), 'numpy.delete', 'np.delete', (['data', '(0)', '(0)'], {}), '(data, 0, 0)\n', (3930, 3942), True, 'import numpy as np\n'), ((1854, 1878), 'Processing.process', 'Processing.process', (['sent'], {}), '(sent)\n', (1872, 1878), False, 'import Processing\n'), ((2186, 2211), 'Processing.synonyms', 'Processing.synonyms', (['word'], {}), '(word)\n', (2205, 2211), False, 'import Processing\n'), ((2740, 2762), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (2759, 2762), False, 'import operator\n'), ((1411, 1425), 'numpy.array', 'np.array', (['list'], {}), '(list)\n', (1419, 1425), True, 'import numpy as np\n'), ((1449, 1480), 'numpy.column_stack', 'np.column_stack', (['(docs, column)'], {}), '((docs, column))\n', (1464, 1480), True, 'import numpy as np\n'), ((1136, 1161), 'numpy.row_stack', 'np.row_stack', (['(docs, row)'], {}), '((docs, row))\n', (1148, 1161), True, 'import numpy as np\n')]
import os import shutil import pickle from torch import nn import torch import pandas as pd import random import numpy as np from torch.utils.data import Dataset from torch.utils.data import DataLoader from torch.cuda.amp import autocast,GradScaler from sklearn.model_selection import KFold from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from torchvision import transforms from utils import dfs_remove_weight from feature_selection import select_feature_linesvc ACTIVATION = { 'relu':nn.ReLU(inplace=True), 'elu':nn.ELU(inplace=True), 'leakyrelu':nn.LeakyReLU(inplace=True), 'prelu':nn.PReLU(), 'gelu':nn.GELU(), 'tanh':nn.Tanh() } class RandomMask1d(object): def __init__(self,factor=0.1,p=0.5): self.factor = factor self.p = p def __call__(self,seq): """ seq: vector of 1d """ if np.random.rand() > self.p: mask = (np.random.random_sample(seq.shape) > self.factor).astype(np.float32) seq = seq * mask return seq class RandomScale1d(object): def __init__(self,factor=0.2,p=0.5): self.factor = factor self.p = p def __call__(self,seq): """ seq: vector of 1d """ if np.random.rand() > self.p: mask = (np.random.random_sample(seq.shape)*self.factor + (1.0-self.factor/2)).astype(np.float32) seq = seq * mask return seq class MyDataset(Dataset): def __init__(self, X, Y=None,transform=None): self.X = X self.Y = Y self.transform = transform def __len__(self): return len(self.X) def __getitem__(self,index): data = self.X[index] if self.transform is not None: data = self.transform(data) if self.Y is not None: target = self.Y[index] sample = {'data':torch.from_numpy(data), 'target':int(target)} else: sample = {'data':torch.from_numpy(data)} return sample class MLP_CLASSIFIER(nn.Module): def __init__(self, input_size, output_size=245, depth=3, depth_list=[256,128,64], drop_prob=0.5, use_norm=True,activation=None): super(MLP_CLASSIFIER, self).__init__() assert len(depth_list) == depth self.linear_list = [] for i in range(depth): if i == 0: self.linear_list.append(nn.Linear(input_size,depth_list[i])) else: self.linear_list.append(nn.Linear(depth_list[i-1],depth_list[i])) if use_norm: self.linear_list.append(nn.BatchNorm1d(depth_list[i])) self.linear_list.append(nn.Dropout(0.2)) if activation is None: self.linear_list.append(nn.ReLU(inplace=True)) else: self.linear_list.append(activation) # self.linear_list.append(nn.Tanh()) # self.linear_list.append(nn.Dropout(0.5)) #pro self.linear = nn.Sequential(*self.linear_list) self.drop = nn.Dropout(drop_prob) if drop_prob > 0.0 else None self.cls_head = nn.Linear(depth_list[-1],output_size) def forward(self, x): x = self.linear(x) #N*C if self.drop: x = self.drop(x) x = self.cls_head(x) return x class AverageMeter(object): ''' Computes and stores the average and current value ''' def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): ''' Computes the precision@k for the specified values of k ''' maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(1/batch_size)) return res def train_epoch(epoch,net,criterion,optim,train_loader,scaler,use_fp16=True): net.train() train_loss = AverageMeter() train_acc = AverageMeter() for step, sample in enumerate(train_loader): data = sample['data'] target = sample['target'] # print(data.size()) data = data.cuda() target = target.cuda() with autocast(use_fp16): output = net(data) loss = criterion(output, target) optim.zero_grad() if use_fp16: scaler.scale(loss).backward() scaler.step(optim) scaler.update() else: loss.backward() optim.step() output = output.float() loss = loss.float() # measure accuracy and record loss acc = accuracy(output.data, target)[0] train_loss.update(loss.item(), data.size(0)) train_acc.update(acc.item(), data.size(0)) torch.cuda.empty_cache() # if step % 10 == 0: # print('epoch:{},step:{},train_loss:{:.5f},train_acc:{:.5f},lr:{}' # .format(epoch, step, loss.item(), acc.item(), optim.param_groups[0]['lr'])) return train_acc.avg,train_loss.avg def val_epoch(epoch,net,criterion,val_loader,use_fp16=True): net.eval() val_loss = AverageMeter() val_acc = AverageMeter() with torch.no_grad(): for step, sample in enumerate(val_loader): data = sample['data'] target = sample['target'] data = data.cuda() target = target.cuda() with autocast(use_fp16): output = net(data) loss = criterion(output, target) output = output.float() loss = loss.float() # measure accuracy and record loss acc = accuracy(output.data, target)[0] val_loss.update(loss.item(), data.size(0)) val_acc.update(acc.item(), data.size(0)) torch.cuda.empty_cache() # print('epoch:{},step:{},val_loss:{:.5f},val_acc:{:.5f}' # .format(epoch, step, loss.item(), acc.item())) return val_acc.avg,val_loss.avg def evaluation(test_data,net,weight_path,use_fp16=True): ckpt = torch.load(weight_path) net.load_state_dict(ckpt['state_dict']) net.eval() test_data = torch.from_numpy(test_data) #N*fea_len with torch.no_grad(): data = test_data.cuda() with autocast(use_fp16): output = net(data) output = output.float() prob_output = torch.softmax(output,dim=1) # N*C output = torch.argmax(prob_output,dim=1) #N torch.cuda.empty_cache() return output.cpu().numpy().tolist(),prob_output.cpu().numpy() def evaluation_tta(test_data,net,weight_path,use_fp16=True,tta=5): ckpt = torch.load(weight_path) net.load_state_dict(ckpt['state_dict']) net.eval() transform = transforms.Compose([RandomScale1d()]) vote_out = [] prob_out = [] for _ in range(tta): input_data = transform(test_data) input_data = torch.from_numpy(input_data) #N*fea_len with torch.no_grad(): data = input_data.cuda() with autocast(use_fp16): output = net(data) output = output.float() prob_output = torch.softmax(output,dim=1) #N*C output = torch.argmax(prob_output,dim=1) #N vote_out.append(output.cpu().numpy().tolist()) prob_out.append(prob_output.cpu().numpy()) # tta*N*C torch.cuda.empty_cache() vote_array = np.asarray(vote_out).astype(np.uint8) # tta*N vote_out = [max(list(vote_array[:,i]),key=list(vote_array[:,i]).count) for i in range(vote_array.shape[1])] return vote_out, np.mean(prob_out, axis=0) def manual_select(total_list,exclude_list=None): fea_list = [] nouse_list = [] if exclude_list is not None: for exclude_label in exclude_list: if 'sum' not in exclude_label and 'avg' not in exclude_label: nouse_list += [f'{exclude_label}_{str(i)}' for i in range(400)] else: nouse_list += [f'{exclude_label}_{str(i)}' for i in range(40)] for col in total_list: if col not in nouse_list: fea_list.append(col) return fea_list else: return total_list def run(train_path,test_path,output_dir,net_depth=3,exclude_list=None,scale_flag=True,select_flag=False,dim_reduction=False,aug_flag=False,tta=False,**aux_config): torch.manual_seed(0) if not os.path.exists(output_dir): os.makedirs(output_dir) else: shutil.rmtree(output_dir) os.makedirs(output_dir) # load training and testing data train_df = pd.read_csv(train_path) test_df = pd.read_csv(test_path) # data preprocessing del train_df['seq'] del test_df['seq'] test_id = test_df['id'] # print(list(test_id)) del train_df['id'] del test_df['id'] # manual select fea_list = manual_select(train_df.columns,exclude_list) fea_list = [f for f in fea_list if f not in ['label']] le = LabelEncoder() label_list = set(train_df['label']) print(random.sample(label_list,1)) train_df['label'] = le.fit_transform(train_df['label']) # convert to numpy array Y = np.asarray(train_df['label']).astype(np.uint8) X = np.asarray(train_df[fea_list]).astype(np.float32) test = np.asarray(test_df[fea_list]).astype(np.float32) # feature selection if select_flag: select_model_path = './select_model.pkl' if os.path.exists(select_model_path): with open(select_model_path, 'rb') as f: select_model = pickle.load(f) else: select_model = select_feature_linesvc(X, Y, select_model_path) X = select_model.transform(X) test = select_model.transform(test) # data scale if scale_flag: X_len = X.shape[0] data_scaler = StandardScaler() cat_data = np.concatenate([X,test],axis=0) cat_data= data_scaler.fit_transform(cat_data) X = cat_data[:X_len] test = cat_data[X_len:] # dim reduction if dim_reduction: X_len = X.shape[0] cat_data = np.concatenate([X,test],axis=0) # fastica = FastICA(n_components=int(X.shape[1]*0.5),random_state=0) # cat_data= fastica.fit_transform(cat_data) pca = PCA(n_components=int(X.shape[1]*0.5)) cat_data= pca.fit_transform(cat_data) X = cat_data[:X_len] test = cat_data[X_len:] # print(Y) print(X.shape,test.shape) num_classes = len(set(train_df['label'])) #245 fea_len = X.shape[1] total_result = [] total_prob_result = [] kfold = KFold(n_splits=5,shuffle=True,random_state=21) for fold_num,(train_index,val_index) in enumerate(kfold.split(X)): print(f'***********fold {fold_num+1} start!!***********') fold_dir = os.path.join(output_dir,f'fold{fold_num+1}') if not os.path.exists(fold_dir): os.makedirs(fold_dir) # initialization epoch_num = 100 acc_threshold = 0.0 depth = net_depth # depth_list = [int(fea_len*(2**(1-i))) for i in range(depth)] depth_list = [fea_len - i*(fea_len-num_classes)// depth for i in range(1,depth)] print('depth list:',depth_list) net = MLP_CLASSIFIER(fea_len,num_classes,len(depth_list),depth_list,**aux_config) criterion = nn.CrossEntropyLoss() optim = torch.optim.Adam(net.parameters(), lr=0.001, weight_decay=0.0001) lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(optim, [25,60,80], gamma=0.1) scaler = GradScaler() net = net.cuda() criterion = criterion.cuda() # data loader x_train, x_val = X[train_index], X[val_index] y_train, y_val = Y[train_index], Y[val_index] print('Train Data Size:',x_train.shape) print('Val Data Size:',x_val.shape) if aug_flag: transform = transforms.Compose([RandomScale1d()]) else: transform = None train_dataset = MyDataset(X=x_train,Y=y_train,transform=transform) val_dataset = MyDataset(X=x_val,Y=y_val,transform=transform) train_loader = DataLoader( train_dataset, batch_size=256, shuffle=True, num_workers=2) val_loader = DataLoader( val_dataset, batch_size=256, shuffle=False, num_workers=2) # main processing for epoch in range(epoch_num): train_acc, train_loss = train_epoch(epoch,net,criterion,optim,train_loader,scaler) val_acc,val_loss = val_epoch(epoch,net,criterion,val_loader) torch.cuda.empty_cache() if epoch % 10 == 0: print('Train epoch:{},train_loss:{:.5f},train_acc:{:.5f}' .format(epoch, train_loss, train_acc)) print('Val epoch:{},val_loss:{:.5f},val_acc:{:.5f}' .format(epoch, val_loss, val_acc)) if lr_scheduler is not None: lr_scheduler.step() if val_acc > acc_threshold: acc_threshold = val_acc saver = { 'state_dict': net.state_dict() } file_name = 'epoch:{}-val_acc:{:.5f}-val_loss:{:.5f}-mlp.pth'.format(epoch,val_acc,val_loss) save_path = os.path.join(fold_dir, file_name) print('Save as: %s'%file_name) torch.save(saver, save_path) # save top3 model dfs_remove_weight(fold_dir,retain=1) # generating test result using the best model if tta: fold_result,fold_prob_result = evaluation_tta(test,net,save_path,tta=9) #N,N*C else: fold_result,fold_prob_result = evaluation(test,net,save_path) #N,N*C total_result.append(fold_result) total_prob_result.append(fold_prob_result) fold_prob_result = np.argmax(fold_prob_result,axis=1).astype(np.uint8).tolist() fold_result = le.inverse_transform(fold_result) fold_prob_result = le.inverse_transform(fold_prob_result) # csv save fold_vote_csv = {} fold_vote_csv = pd.DataFrame(fold_vote_csv) fold_vote_csv['sample_id'] = list(test_id) + ['d2ciob_'] fold_vote_csv['category_id'] = list(fold_result) + random.sample(label_list,1) fold_vote_csv.to_csv(os.path.join(output_dir, f'fold{fold_num}-vote.csv'),index=False) fold_prob_csv = {} fold_prob_csv = pd.DataFrame(fold_prob_csv) fold_prob_csv['sample_id'] = list(test_id) + ['d2ciob_'] fold_prob_csv['category_id'] = list(fold_prob_result) + random.sample(label_list,1) fold_vote_csv.to_csv(os.path.join(output_dir, f'fold{fold_num}-prob.csv'),index=False) # result fusion by voting final_vote_result = [] vote_array = np.asarray(total_result).astype(np.uint8) #fold*N final_vote_result.extend([max(list(vote_array[:,i]),key=list(vote_array[:,i]).count) for i in range(vote_array.shape[1])]) final_vote_result = le.inverse_transform(final_vote_result) # result fusion by avg prob final_prob_result = [] prob_array = np.asarray(total_prob_result) # fold*N*C prob_array = np.mean(prob_array,axis=0) #N*C final_prob_result = np.argmax(prob_array,axis=1).astype(np.uint8).tolist() final_prob_result = le.inverse_transform(final_prob_result) # csv save total_vote_csv = {} total_vote_csv = pd.DataFrame(total_vote_csv) total_vote_csv['sample_id'] = list(test_id) + ['d2ciob_'] total_vote_csv['category_id'] = list(final_vote_result) + random.sample(label_list,1) total_vote_csv.to_csv(os.path.join(output_dir, f'fusion-vote.csv'),index=False) total_prob_csv = {} total_prob_csv = pd.DataFrame(total_prob_csv) total_prob_csv['sample_id'] = list(test_id) + ['d2ciob_'] total_prob_csv['category_id'] = list(final_prob_result) + random.sample(label_list,1) total_prob_csv.to_csv(os.path.join(output_dir, f'fusion-prob.csv'),index=False) if __name__ == '__main__': os.environ['CUDA_VISIBLE_DEVICES'] = '0' pssm_key = ['pssm_sum', 'pssm_avg','acc_1','acc_2','acc_3','acc_4','acc_5','acc_6','sxg_0','sxg_1','sxg_2','sxg_3','sxg_4','sxg_5'] hmm_key = ['hmm_sum', 'hmm_avg','acc_hmm_1','acc_hmm_2','acc_hmm_3','acc_hmm_4','acc_hmm_5','acc_hmm_6','sxg_hmm_0','sxg_hmm_1','sxg_hmm_2','sxg_hmm_3','sxg_hmm_4','sxg_hmm_5'] total_key = pssm_key[:2] + hmm_key[:2] + pssm_key[2:] + hmm_key[2:] # train_path = '../dataset/pssm_train.csv' # test_path = '../dataset/pssm_test.csv' train_path = '../dataset/hmm_train.csv' test_path = '../dataset/hmm_test.csv' fea_key = hmm_key #HALF output_dir = './result/hmm_half_scale_pro/' for i in range(11,12): # for i,act in enumerate(ACTIVATION): save_path = os.path.join(output_dir,f'trial_{str(i+1)}') # total # exclude_list = None # half exclude_list = random.sample(fea_key[2:],6) # qtr # exclude_list = random.sample(fea_key[2:],9) # uncia # exclude_list = random.sample(fea_key[2:],11) print('exclude list:',exclude_list) run(train_path,test_path,save_path,net_depth=3,exclude_list=exclude_list,scale_flag=True,select_flag=False,dim_reduction=False,aug_flag=False,tta=False) # QTR output_dir = './result/hmm_qtr_scale_pro/' for i in range(10): # for i,act in enumerate(ACTIVATION): save_path = os.path.join(output_dir,f'trial_{str(i+1)}') # total # exclude_list = None # half # exclude_list = random.sample(fea_key[2:],6) # qtr exclude_list = random.sample(fea_key[2:],9) # uncia # exclude_list = random.sample(fea_key[2:],11) print('exclude list:',exclude_list) run(train_path,test_path,save_path,net_depth=3,exclude_list=exclude_list,scale_flag=True,select_flag=False,dim_reduction=False,aug_flag=False,tta=False)
[ "torch.nn.Dropout", "sklearn.preprocessing.StandardScaler", "numpy.random.random_sample", "numpy.argmax", "pandas.read_csv", "torch.argmax", "random.sample", "numpy.mean", "pickle.load", "shutil.rmtree", "torch.no_grad", "os.path.join", "pandas.DataFrame", "torch.cuda.amp.autocast", "torch.utils.data.DataLoader", "torch.load", "os.path.exists", "sklearn.preprocessing.LabelEncoder", "torch.softmax", "torch.nn.Linear", "feature_selection.select_feature_linesvc", "torch.nn.Tanh", "torch.manual_seed", "numpy.asarray", "torch.nn.BatchNorm1d", "utils.dfs_remove_weight", "torch.nn.GELU", "torch.nn.ELU", "torch.cuda.amp.GradScaler", "torch.nn.LeakyReLU", "numpy.concatenate", "torch.from_numpy", "torch.nn.PReLU", "torch.nn.ReLU", "os.makedirs", "torch.nn.Sequential", "torch.nn.CrossEntropyLoss", "sklearn.model_selection.KFold", "torch.save", "torch.cuda.empty_cache", "numpy.random.rand", "torch.optim.lr_scheduler.MultiStepLR" ]
[((580, 601), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (587, 601), False, 'from torch import nn\n'), ((613, 633), 'torch.nn.ELU', 'nn.ELU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (619, 633), False, 'from torch import nn\n'), ((651, 677), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (663, 677), False, 'from torch import nn\n'), ((691, 701), 'torch.nn.PReLU', 'nn.PReLU', ([], {}), '()\n', (699, 701), False, 'from torch import nn\n'), ((714, 723), 'torch.nn.GELU', 'nn.GELU', ([], {}), '()\n', (721, 723), False, 'from torch import nn\n'), ((736, 745), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (743, 745), False, 'from torch import nn\n'), ((6543, 6566), 'torch.load', 'torch.load', (['weight_path'], {}), '(weight_path)\n', (6553, 6566), False, 'import torch\n'), ((6642, 6669), 'torch.from_numpy', 'torch.from_numpy', (['test_data'], {}), '(test_data)\n', (6658, 6669), False, 'import torch\n'), ((7124, 7147), 'torch.load', 'torch.load', (['weight_path'], {}), '(weight_path)\n', (7134, 7147), False, 'import torch\n'), ((8860, 8880), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (8877, 8880), False, 'import torch\n'), ((9086, 9109), 'pandas.read_csv', 'pd.read_csv', (['train_path'], {}), '(train_path)\n', (9097, 9109), True, 'import pandas as pd\n'), ((9124, 9146), 'pandas.read_csv', 'pd.read_csv', (['test_path'], {}), '(test_path)\n', (9135, 9146), True, 'import pandas as pd\n'), ((9472, 9486), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (9484, 9486), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((11123, 11171), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(5)', 'shuffle': '(True)', 'random_state': '(21)'}), '(n_splits=5, shuffle=True, random_state=21)\n', (11128, 11171), False, 'from sklearn.model_selection import KFold\n'), ((15789, 15818), 'numpy.asarray', 'np.asarray', (['total_prob_result'], {}), '(total_prob_result)\n', (15799, 15818), True, 'import numpy as np\n'), ((15847, 15874), 'numpy.mean', 'np.mean', (['prob_array'], {'axis': '(0)'}), '(prob_array, axis=0)\n', (15854, 15874), True, 'import numpy as np\n'), ((16083, 16111), 'pandas.DataFrame', 'pd.DataFrame', (['total_vote_csv'], {}), '(total_vote_csv)\n', (16095, 16111), True, 'import pandas as pd\n'), ((16394, 16422), 'pandas.DataFrame', 'pd.DataFrame', (['total_prob_csv'], {}), '(total_prob_csv)\n', (16406, 16422), True, 'import pandas as pd\n'), ((3092, 3124), 'torch.nn.Sequential', 'nn.Sequential', (['*self.linear_list'], {}), '(*self.linear_list)\n', (3105, 3124), False, 'from torch import nn\n'), ((3220, 3258), 'torch.nn.Linear', 'nn.Linear', (['depth_list[-1]', 'output_size'], {}), '(depth_list[-1], output_size)\n', (3229, 3258), False, 'from torch import nn\n'), ((5231, 5255), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (5253, 5255), False, 'import torch\n'), ((5658, 5673), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5671, 5673), False, 'import torch\n'), ((6690, 6705), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6703, 6705), False, 'import torch\n'), ((6857, 6885), 'torch.softmax', 'torch.softmax', (['output'], {'dim': '(1)'}), '(output, dim=1)\n', (6870, 6885), False, 'import torch\n'), ((6908, 6940), 'torch.argmax', 'torch.argmax', (['prob_output'], {'dim': '(1)'}), '(prob_output, dim=1)\n', (6920, 6940), False, 'import torch\n'), ((6951, 6975), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (6973, 6975), False, 'import torch\n'), ((7387, 7415), 'torch.from_numpy', 'torch.from_numpy', (['input_data'], {}), '(input_data)\n', (7403, 7415), False, 'import torch\n'), ((8074, 8099), 'numpy.mean', 'np.mean', (['prob_out'], {'axis': '(0)'}), '(prob_out, axis=0)\n', (8081, 8099), True, 'import numpy as np\n'), ((8893, 8919), 'os.path.exists', 'os.path.exists', (['output_dir'], {}), '(output_dir)\n', (8907, 8919), False, 'import os\n'), ((8929, 8952), 'os.makedirs', 'os.makedirs', (['output_dir'], {}), '(output_dir)\n', (8940, 8952), False, 'import os\n'), ((8971, 8996), 'shutil.rmtree', 'shutil.rmtree', (['output_dir'], {}), '(output_dir)\n', (8984, 8996), False, 'import shutil\n'), ((9005, 9028), 'os.makedirs', 'os.makedirs', (['output_dir'], {}), '(output_dir)\n', (9016, 9028), False, 'import os\n'), ((9537, 9565), 'random.sample', 'random.sample', (['label_list', '(1)'], {}), '(label_list, 1)\n', (9550, 9565), False, 'import random\n'), ((9938, 9971), 'os.path.exists', 'os.path.exists', (['select_model_path'], {}), '(select_model_path)\n', (9952, 9971), False, 'import os\n'), ((10330, 10346), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (10344, 10346), False, 'from sklearn.preprocessing import StandardScaler\n'), ((10366, 10399), 'numpy.concatenate', 'np.concatenate', (['[X, test]'], {'axis': '(0)'}), '([X, test], axis=0)\n', (10380, 10399), True, 'import numpy as np\n'), ((10608, 10641), 'numpy.concatenate', 'np.concatenate', (['[X, test]'], {'axis': '(0)'}), '([X, test], axis=0)\n', (10622, 10641), True, 'import numpy as np\n'), ((11326, 11373), 'os.path.join', 'os.path.join', (['output_dir', 'f"""fold{fold_num + 1}"""'], {}), "(output_dir, f'fold{fold_num + 1}')\n", (11338, 11373), False, 'import os\n'), ((11862, 11883), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (11881, 11883), False, 'from torch import nn\n'), ((11989, 12057), 'torch.optim.lr_scheduler.MultiStepLR', 'torch.optim.lr_scheduler.MultiStepLR', (['optim', '[25, 60, 80]'], {'gamma': '(0.1)'}), '(optim, [25, 60, 80], gamma=0.1)\n', (12025, 12057), False, 'import torch\n'), ((12073, 12085), 'torch.cuda.amp.GradScaler', 'GradScaler', ([], {}), '()\n', (12083, 12085), False, 'from torch.cuda.amp import autocast, GradScaler\n'), ((12677, 12747), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset'], {'batch_size': '(256)', 'shuffle': '(True)', 'num_workers': '(2)'}), '(train_dataset, batch_size=256, shuffle=True, num_workers=2)\n', (12687, 12747), False, 'from torch.utils.data import DataLoader\n'), ((12843, 12912), 'torch.utils.data.DataLoader', 'DataLoader', (['val_dataset'], {'batch_size': '(256)', 'shuffle': '(False)', 'num_workers': '(2)'}), '(val_dataset, batch_size=256, shuffle=False, num_workers=2)\n', (12853, 12912), False, 'from torch.utils.data import DataLoader\n'), ((14113, 14150), 'utils.dfs_remove_weight', 'dfs_remove_weight', (['fold_dir'], {'retain': '(1)'}), '(fold_dir, retain=1)\n', (14130, 14150), False, 'from utils import dfs_remove_weight\n'), ((14789, 14816), 'pandas.DataFrame', 'pd.DataFrame', (['fold_vote_csv'], {}), '(fold_vote_csv)\n', (14801, 14816), True, 'import pandas as pd\n'), ((15116, 15143), 'pandas.DataFrame', 'pd.DataFrame', (['fold_prob_csv'], {}), '(fold_prob_csv)\n', (15128, 15143), True, 'import pandas as pd\n'), ((16236, 16264), 'random.sample', 'random.sample', (['label_list', '(1)'], {}), '(label_list, 1)\n', (16249, 16264), False, 'import random\n'), ((16290, 16334), 'os.path.join', 'os.path.join', (['output_dir', 'f"""fusion-vote.csv"""'], {}), "(output_dir, f'fusion-vote.csv')\n", (16302, 16334), False, 'import os\n'), ((16547, 16575), 'random.sample', 'random.sample', (['label_list', '(1)'], {}), '(label_list, 1)\n', (16560, 16575), False, 'import random\n'), ((16601, 16645), 'os.path.join', 'os.path.join', (['output_dir', 'f"""fusion-prob.csv"""'], {}), "(output_dir, f'fusion-prob.csv')\n", (16613, 16645), False, 'import os\n'), ((17610, 17639), 'random.sample', 'random.sample', (['fea_key[2:]', '(6)'], {}), '(fea_key[2:], 6)\n', (17623, 17639), False, 'import random\n'), ((18337, 18366), 'random.sample', 'random.sample', (['fea_key[2:]', '(9)'], {}), '(fea_key[2:], 9)\n', (18350, 18366), False, 'import random\n'), ((961, 977), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (975, 977), True, 'import numpy as np\n'), ((1340, 1356), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (1354, 1356), True, 'import numpy as np\n'), ((3145, 3166), 'torch.nn.Dropout', 'nn.Dropout', (['drop_prob'], {}), '(drop_prob)\n', (3155, 3166), False, 'from torch import nn\n'), ((4646, 4664), 'torch.cuda.amp.autocast', 'autocast', (['use_fp16'], {}), '(use_fp16)\n', (4654, 4664), False, 'from torch.cuda.amp import autocast, GradScaler\n'), ((6275, 6299), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (6297, 6299), False, 'import torch\n'), ((6752, 6770), 'torch.cuda.amp.autocast', 'autocast', (['use_fp16'], {}), '(use_fp16)\n', (6760, 6770), False, 'from torch.cuda.amp import autocast, GradScaler\n'), ((7440, 7455), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7453, 7455), False, 'import torch\n'), ((7628, 7656), 'torch.softmax', 'torch.softmax', (['output'], {'dim': '(1)'}), '(output, dim=1)\n', (7641, 7656), False, 'import torch\n'), ((7682, 7714), 'torch.argmax', 'torch.argmax', (['prob_output'], {'dim': '(1)'}), '(prob_output, dim=1)\n', (7694, 7714), False, 'import torch\n'), ((7853, 7877), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (7875, 7877), False, 'import torch\n'), ((7895, 7915), 'numpy.asarray', 'np.asarray', (['vote_out'], {}), '(vote_out)\n', (7905, 7915), True, 'import numpy as np\n'), ((9664, 9693), 'numpy.asarray', 'np.asarray', (["train_df['label']"], {}), "(train_df['label'])\n", (9674, 9693), True, 'import numpy as np\n'), ((9719, 9749), 'numpy.asarray', 'np.asarray', (['train_df[fea_list]'], {}), '(train_df[fea_list])\n', (9729, 9749), True, 'import numpy as np\n'), ((9780, 9809), 'numpy.asarray', 'np.asarray', (['test_df[fea_list]'], {}), '(test_df[fea_list])\n', (9790, 9809), True, 'import numpy as np\n'), ((10113, 10160), 'feature_selection.select_feature_linesvc', 'select_feature_linesvc', (['X', 'Y', 'select_model_path'], {}), '(X, Y, select_model_path)\n', (10135, 10160), False, 'from feature_selection import select_feature_linesvc\n'), ((11386, 11410), 'os.path.exists', 'os.path.exists', (['fold_dir'], {}), '(fold_dir)\n', (11400, 11410), False, 'import os\n'), ((11424, 11445), 'os.makedirs', 'os.makedirs', (['fold_dir'], {}), '(fold_dir)\n', (11435, 11445), False, 'import os\n'), ((13224, 13248), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (13246, 13248), False, 'import torch\n'), ((14941, 14969), 'random.sample', 'random.sample', (['label_list', '(1)'], {}), '(label_list, 1)\n', (14954, 14969), False, 'import random\n'), ((14998, 15050), 'os.path.join', 'os.path.join', (['output_dir', 'f"""fold{fold_num}-vote.csv"""'], {}), "(output_dir, f'fold{fold_num}-vote.csv')\n", (15010, 15050), False, 'import os\n'), ((15273, 15301), 'random.sample', 'random.sample', (['label_list', '(1)'], {}), '(label_list, 1)\n', (15286, 15301), False, 'import random\n'), ((15330, 15382), 'os.path.join', 'os.path.join', (['output_dir', 'f"""fold{fold_num}-prob.csv"""'], {}), "(output_dir, f'fold{fold_num}-prob.csv')\n", (15342, 15382), False, 'import os\n'), ((15471, 15495), 'numpy.asarray', 'np.asarray', (['total_result'], {}), '(total_result)\n', (15481, 15495), True, 'import numpy as np\n'), ((1965, 1987), 'torch.from_numpy', 'torch.from_numpy', (['data'], {}), '(data)\n', (1981, 1987), False, 'import torch\n'), ((2054, 2076), 'torch.from_numpy', 'torch.from_numpy', (['data'], {}), '(data)\n', (2070, 2076), False, 'import torch\n'), ((5882, 5900), 'torch.cuda.amp.autocast', 'autocast', (['use_fp16'], {}), '(use_fp16)\n', (5890, 5900), False, 'from torch.cuda.amp import autocast, GradScaler\n'), ((7511, 7529), 'torch.cuda.amp.autocast', 'autocast', (['use_fp16'], {}), '(use_fp16)\n', (7519, 7529), False, 'from torch.cuda.amp import autocast, GradScaler\n'), ((10057, 10071), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (10068, 10071), False, 'import pickle\n'), ((13944, 13977), 'os.path.join', 'os.path.join', (['fold_dir', 'file_name'], {}), '(fold_dir, file_name)\n', (13956, 13977), False, 'import os\n'), ((14041, 14069), 'torch.save', 'torch.save', (['saver', 'save_path'], {}), '(saver, save_path)\n', (14051, 14069), False, 'import torch\n'), ((2489, 2525), 'torch.nn.Linear', 'nn.Linear', (['input_size', 'depth_list[i]'], {}), '(input_size, depth_list[i])\n', (2498, 2525), False, 'from torch import nn\n'), ((2584, 2627), 'torch.nn.Linear', 'nn.Linear', (['depth_list[i - 1]', 'depth_list[i]'], {}), '(depth_list[i - 1], depth_list[i])\n', (2593, 2627), False, 'from torch import nn\n'), ((2691, 2720), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['depth_list[i]'], {}), '(depth_list[i])\n', (2705, 2720), False, 'from torch import nn\n'), ((2762, 2777), 'torch.nn.Dropout', 'nn.Dropout', (['(0.2)'], {}), '(0.2)\n', (2772, 2777), False, 'from torch import nn\n'), ((2854, 2875), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (2861, 2875), False, 'from torch import nn\n'), ((15903, 15932), 'numpy.argmax', 'np.argmax', (['prob_array'], {'axis': '(1)'}), '(prob_array, axis=1)\n', (15912, 15932), True, 'import numpy as np\n'), ((1008, 1042), 'numpy.random.random_sample', 'np.random.random_sample', (['seq.shape'], {}), '(seq.shape)\n', (1031, 1042), True, 'import numpy as np\n'), ((14535, 14570), 'numpy.argmax', 'np.argmax', (['fold_prob_result'], {'axis': '(1)'}), '(fold_prob_result, axis=1)\n', (14544, 14570), True, 'import numpy as np\n'), ((1387, 1421), 'numpy.random.random_sample', 'np.random.random_sample', (['seq.shape'], {}), '(seq.shape)\n', (1410, 1421), True, 'import numpy as np\n')]
import numpy as np import capytaine as cpt vert = np.array([0.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 1.0, -1.0, 0.0, 1.0, -1.0, 1.0, 0.0, -1.0, 2.0, 0.0, -1.0, 2.0, 1.0, -1.0, 1.0, 1.0, -1.0]).reshape((8, 3)) faces = np.arange(0, 8).reshape(2, 4) mesh = cpt.Mesh(vert, faces) S, K = cpt.Delhommeau().evaluate(mesh, mesh, sea_bottom=-np.infty, wavenumber=1.0) print(S) print(K)
[ "capytaine.Mesh", "capytaine.Delhommeau", "numpy.array", "numpy.arange" ]
[((370, 391), 'capytaine.Mesh', 'cpt.Mesh', (['vert', 'faces'], {}), '(vert, faces)\n', (378, 391), True, 'import capytaine as cpt\n'), ((51, 194), 'numpy.array', 'np.array', (['[0.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 1.0, -1.0, 0.0, 1.0, -1.0, 1.0, 0.0, \n -1.0, 2.0, 0.0, -1.0, 2.0, 1.0, -1.0, 1.0, 1.0, -1.0]'], {}), '([0.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 1.0, -1.0, 0.0, 1.0, -1.0, \n 1.0, 0.0, -1.0, 2.0, 0.0, -1.0, 2.0, 1.0, -1.0, 1.0, 1.0, -1.0])\n', (59, 194), True, 'import numpy as np\n'), ((333, 348), 'numpy.arange', 'np.arange', (['(0)', '(8)'], {}), '(0, 8)\n', (342, 348), True, 'import numpy as np\n'), ((399, 415), 'capytaine.Delhommeau', 'cpt.Delhommeau', ([], {}), '()\n', (413, 415), True, 'import capytaine as cpt\n')]
# SPDX-License-Identifier: BSD-3-Clause # Copyright (c) 2022 Scipp contributors (https://github.com/scipp) # @author <NAME> import numpy as np import scipp as sc def make_variables(): data = np.arange(1, 4, dtype=float) a = sc.Variable(dims=['x'], values=data) b = sc.Variable(dims=['x'], values=data) a_slice = a['x', :] b_slice = b['x', :] return a, b, a_slice, b_slice, data # This check is important: It can happen that an implementation of, # e.g., __iadd__ does an in-place modification, updating `b`, but then the # return value is assigned to `a`, which could break the connection unless # the correct Python object is returned. def test_iadd_returns_original_object(): a = sc.scalar(1.2) b = a a += 1.0 assert sc.identical(a, b) def test_isub_returns_original_object(): a = sc.scalar(1.2) b = a a -= 1.0 assert sc.identical(a, b) def test_imul_returns_original_object(): a = sc.scalar(1.2) b = a a *= 1.0 assert sc.identical(a, b) def test_itruediv_returns_original_object(): a = sc.scalar(1.2) b = a a /= 1.0 assert sc.identical(a, b) def test_add_variable(): a, b, a_slice, b_slice, data = make_variables() c = a + b assert np.array_equal(c.values, data + data) c = a + 2.0 assert np.array_equal(c.values, data + 2.0) c = a + b_slice assert np.array_equal(c.values, data + data) c += b assert np.array_equal(c.values, data + data + data) c += b_slice assert np.array_equal(c.values, data + data + data + data) c = 3.5 + c assert np.array_equal(c.values, data + data + data + data + 3.5) def test_sub_variable(): a, b, a_slice, b_slice, data = make_variables() c = a - b assert np.array_equal(c.values, data - data) c = a - 2.0 assert np.array_equal(c.values, data - 2.0) c = a - b_slice assert np.array_equal(c.values, data - data) c -= b assert np.array_equal(c.values, data - data - data) c -= b_slice assert np.array_equal(c.values, data - data - data - data) c = 3.5 - c assert np.array_equal(c.values, 3.5 - data + data + data + data) def test_mul_variable(): a, b, a_slice, b_slice, data = make_variables() c = a * b assert np.array_equal(c.values, data * data) c = a * 2.0 assert np.array_equal(c.values, data * 2.0) c = a * b_slice assert np.array_equal(c.values, data * data) c *= b assert np.array_equal(c.values, data * data * data) c *= b_slice assert np.array_equal(c.values, data * data * data * data) c = 3.5 * c assert np.array_equal(c.values, data * data * data * data * 3.5) def test_truediv_variable(): a, b, a_slice, b_slice, data = make_variables() c = a / b assert np.array_equal(c.values, data / data) c = a / 2.0 assert np.array_equal(c.values, data / 2.0) c = a / b_slice assert np.array_equal(c.values, data / data) c /= b assert np.array_equal(c.values, data / data / data) c /= b_slice assert np.array_equal(c.values, data / data / data / data) c = 2.0 / a assert np.array_equal(c.values, 2.0 / data) def test_pow_variable(): a, b, a_slice, b_slice, data = make_variables() c = a**b assert np.array_equal(c.values, data**data) c **= b assert np.array_equal(c.values, (data**data)**data) c = a**3 assert np.array_equal(c.values, data**3) c **= 3 assert np.array_equal(c.values, (data**3)**3) c = a**3.0 assert np.array_equal(c.values, data**3.0) c **= 3.0 assert np.array_equal(c.values, (data**3.0)**3.0) c = a**b_slice assert np.array_equal(c.values, data**data) c **= b_slice assert np.array_equal(c.values, (data**data)**data) c = 2**b assert np.array_equal(c.values, 2**data) c = 2.0**b assert np.array_equal(c.values, 2.0**data) def test_iadd_variable_with_scalar(): v = sc.Variable(dims=['x'], values=[10.0]) expected = sc.Variable(dims=['x'], values=[12.0]) v += 2 assert sc.identical(v, expected) def test_isub_variable_with_scalar(): v = sc.Variable(dims=['x'], values=[10.0]) expected = sc.Variable(dims=['x'], values=[9.0]) v -= 1 assert sc.identical(v, expected) def test_imul_variable_with_scalar(): v = sc.Variable(dims=['x'], values=[10.0]) expected = sc.Variable(dims=['x'], values=[30.0]) v *= 3 assert sc.identical(v, expected) def test_itruediv_variable_with_scalar(): v = sc.Variable(dims=['x'], values=[10.0]) expected = sc.Variable(dims=['x'], values=[5.0]) v /= 2 assert sc.identical(v, expected) def test_add_dataarray_with_dataarray(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) expected = sc.zeros_like(da) expected.data = sc.arange('x', 2.0, 20.0, 2.0) assert sc.identical(da + da, expected) def test_sub_dataarray_with_dataarray(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) expected = sc.zeros_like(da) assert sc.identical(da - da, expected) def test_mul_dataarray_with_dataarray(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) expected = sc.zeros_like(da) expected.data = sc.arange('x', 1.0, 10.0)**2 assert sc.identical(da * da, expected) def test_truediv_dataarray_with_dataarray(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) expected = sc.ones_like(da) assert sc.identical(da / da, expected) def test_add_dataarray_with_variable(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) expected = sc.zeros_like(da) expected.data = sc.arange('x', 2.0, 20.0, 2.0) assert sc.identical(da + da.data, expected) assert sc.identical(da.data + da, expected) def test_sub_dataarray_with_variable(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) expected = sc.zeros_like(da) assert sc.identical(da - da.data, expected) assert sc.identical(da.data - da, expected) def test_mul_dataarray_with_variable(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) expected = sc.zeros_like(da) expected.data = sc.arange('x', 1.0, 10.0)**2 assert sc.identical(da * da.data, expected) assert sc.identical(da.data * da, expected) def test_truediv_dataarray_with_variable(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) expected = sc.ones_like(da) assert sc.identical(da / da.data, expected) assert sc.identical(da.data / da, expected) def test_add_dataarray_with_scalar(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) expected = sc.zeros_like(da) expected.data = sc.arange('x', 3.0, 12.0) assert sc.identical(da + 2.0, expected) assert sc.identical(2.0 + da, expected) def test_sub_dataarray_with_scalar(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) expected = sc.zeros_like(da) expected.data = sc.arange('x', 1.0, 10.0) - 2.0 assert sc.identical(da - 2.0, expected) expected.data = 2.0 - sc.arange('x', 1.0, 10.0) assert sc.identical(2.0 - da, expected) def test_mul_dataarray_with_scalar(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) expected = sc.zeros_like(da) expected.data = sc.arange('x', 2.0, 20.0, 2.0) assert sc.identical(da * 2.0, expected) assert sc.identical(2.0 * da, expected) def test_truediv_dataarray_with_scalar(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) expected = sc.zeros_like(da) expected.data = sc.arange('x', 1.0, 10.0) / 2.0 assert sc.identical(da / 2.0, expected) expected.data = 2.0 / sc.arange('x', 1.0, 10.0) assert sc.identical(2.0 / da, expected) def test_iadd_dataset_with_dataarray(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) ds = sc.Dataset({'data': da.copy()}) expected = sc.Dataset({'data': da + da}) ds += da assert sc.identical(ds, expected) def test_isub_dataset_with_dataarray(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) ds = sc.Dataset({'data': da.copy()}) expected = sc.Dataset({'data': da - da}) ds -= da assert sc.identical(ds, expected) def test_imul_dataset_with_dataarray(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) ds = sc.Dataset({'data': da.copy()}) expected = sc.Dataset({'data': da * da}) ds *= da assert sc.identical(ds, expected) def test_itruediv_dataset_with_dataarray(): da = sc.DataArray(sc.arange('x', 1.0, 10.0), coords={'x': sc.arange('x', 10.0, 20.0)}) ds = sc.Dataset({'data': da.copy()}) expected = sc.Dataset({'data': da / da}) ds /= da assert sc.identical(ds, expected) def test_iadd_dataset_with_scalar(): ds = sc.Dataset(data={'data': sc.arange('x', 10.0)}, coords={'x': sc.arange('x', 10.0, 20.0)}) expected = ds.copy() expected['data'] = ds['data'] + 2.0 ds += 2.0 assert sc.identical(ds, expected) def test_isub_dataset_with_scalar(): ds = sc.Dataset(data={'data': sc.arange('x', 10.0)}, coords={'x': sc.arange('x', 10.0, 20.0)}) expected = ds.copy() expected['data'] = ds['data'] - 3.0 ds -= 3.0 assert sc.identical(ds, expected) def test_imul_dataset_with_scalar(): ds = sc.Dataset(data={'data': sc.arange('x', 10.0)}, coords={'x': sc.arange('x', 10.0, 20.0)}) expected = ds.copy() expected['data'] = ds['data'] * 1.5 ds *= 1.5 assert sc.identical(ds, expected) def test_itruediv_dataset_with_scalar(): ds = sc.Dataset(data={'data': sc.arange('x', 10.0)}, coords={'x': sc.arange('x', 10.0, 20.0)}) expected = ds.copy() expected['data'] = ds['data'] / 0.5 ds /= 0.5 assert sc.identical(ds, expected) def test_isub_dataset_with_dataset_broadcast(): ds = sc.Dataset(data={'data': sc.arange('x', 10.0)}, coords={'x': sc.arange('x', 10.0, 20.0)}) expected = ds - ds['x', 0] ds -= ds['x', 0] assert sc.identical(ds, expected) def test_add_function(): assert sc.identical(sc.add(sc.scalar(3), sc.scalar(2)), sc.scalar(5)) def test_divide_function(): assert sc.identical(sc.divide(sc.scalar(6), sc.scalar(2)), sc.scalar(3.0)) def test_floor_divide_function(): assert sc.identical(sc.floor_divide(sc.scalar(6), sc.scalar(2.5)), sc.scalar(2.0)) def test_mod_function(): assert sc.identical(sc.mod(sc.scalar(3), sc.scalar(2)), sc.scalar(1)) def test_multipy_function(): assert sc.identical(sc.multiply(sc.scalar(3), sc.scalar(2)), sc.scalar(6)) def test_subtract_function(): assert sc.identical(sc.subtract(sc.scalar(3), sc.scalar(2)), sc.scalar(1)) def test_negative_function(): assert sc.identical(sc.negative(sc.scalar(3)), sc.scalar(-3))
[ "scipp.Dataset", "scipp.ones_like", "scipp.scalar", "scipp.Variable", "scipp.identical", "scipp.zeros_like", "numpy.arange", "numpy.array_equal", "scipp.arange" ]
[((198, 226), 'numpy.arange', 'np.arange', (['(1)', '(4)'], {'dtype': 'float'}), '(1, 4, dtype=float)\n', (207, 226), True, 'import numpy as np\n'), ((235, 271), 'scipp.Variable', 'sc.Variable', ([], {'dims': "['x']", 'values': 'data'}), "(dims=['x'], values=data)\n", (246, 271), True, 'import scipp as sc\n'), ((280, 316), 'scipp.Variable', 'sc.Variable', ([], {'dims': "['x']", 'values': 'data'}), "(dims=['x'], values=data)\n", (291, 316), True, 'import scipp as sc\n'), ((715, 729), 'scipp.scalar', 'sc.scalar', (['(1.2)'], {}), '(1.2)\n', (724, 729), True, 'import scipp as sc\n'), ((764, 782), 'scipp.identical', 'sc.identical', (['a', 'b'], {}), '(a, b)\n', (776, 782), True, 'import scipp as sc\n'), ((834, 848), 'scipp.scalar', 'sc.scalar', (['(1.2)'], {}), '(1.2)\n', (843, 848), True, 'import scipp as sc\n'), ((883, 901), 'scipp.identical', 'sc.identical', (['a', 'b'], {}), '(a, b)\n', (895, 901), True, 'import scipp as sc\n'), ((953, 967), 'scipp.scalar', 'sc.scalar', (['(1.2)'], {}), '(1.2)\n', (962, 967), True, 'import scipp as sc\n'), ((1002, 1020), 'scipp.identical', 'sc.identical', (['a', 'b'], {}), '(a, b)\n', (1014, 1020), True, 'import scipp as sc\n'), ((1076, 1090), 'scipp.scalar', 'sc.scalar', (['(1.2)'], {}), '(1.2)\n', (1085, 1090), True, 'import scipp as sc\n'), ((1125, 1143), 'scipp.identical', 'sc.identical', (['a', 'b'], {}), '(a, b)\n', (1137, 1143), True, 'import scipp as sc\n'), ((1248, 1285), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data + data)'], {}), '(c.values, data + data)\n', (1262, 1285), True, 'import numpy as np\n'), ((1313, 1349), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data + 2.0)'], {}), '(c.values, data + 2.0)\n', (1327, 1349), True, 'import numpy as np\n'), ((1381, 1418), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data + data)'], {}), '(c.values, data + data)\n', (1395, 1418), True, 'import numpy as np\n'), ((1441, 1485), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data + data + data)'], {}), '(c.values, data + data + data)\n', (1455, 1485), True, 'import numpy as np\n'), ((1514, 1565), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data + data + data + data)'], {}), '(c.values, data + data + data + data)\n', (1528, 1565), True, 'import numpy as np\n'), ((1593, 1650), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data + data + data + data + 3.5)'], {}), '(c.values, data + data + data + data + 3.5)\n', (1607, 1650), True, 'import numpy as np\n'), ((1755, 1792), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data - data)'], {}), '(c.values, data - data)\n', (1769, 1792), True, 'import numpy as np\n'), ((1820, 1856), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data - 2.0)'], {}), '(c.values, data - 2.0)\n', (1834, 1856), True, 'import numpy as np\n'), ((1888, 1925), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data - data)'], {}), '(c.values, data - data)\n', (1902, 1925), True, 'import numpy as np\n'), ((1948, 1992), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data - data - data)'], {}), '(c.values, data - data - data)\n', (1962, 1992), True, 'import numpy as np\n'), ((2021, 2072), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data - data - data - data)'], {}), '(c.values, data - data - data - data)\n', (2035, 2072), True, 'import numpy as np\n'), ((2100, 2157), 'numpy.array_equal', 'np.array_equal', (['c.values', '(3.5 - data + data + data + data)'], {}), '(c.values, 3.5 - data + data + data + data)\n', (2114, 2157), True, 'import numpy as np\n'), ((2262, 2299), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data * data)'], {}), '(c.values, data * data)\n', (2276, 2299), True, 'import numpy as np\n'), ((2327, 2363), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data * 2.0)'], {}), '(c.values, data * 2.0)\n', (2341, 2363), True, 'import numpy as np\n'), ((2395, 2432), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data * data)'], {}), '(c.values, data * data)\n', (2409, 2432), True, 'import numpy as np\n'), ((2455, 2499), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data * data * data)'], {}), '(c.values, data * data * data)\n', (2469, 2499), True, 'import numpy as np\n'), ((2528, 2579), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data * data * data * data)'], {}), '(c.values, data * data * data * data)\n', (2542, 2579), True, 'import numpy as np\n'), ((2607, 2664), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data * data * data * data * 3.5)'], {}), '(c.values, data * data * data * data * 3.5)\n', (2621, 2664), True, 'import numpy as np\n'), ((2773, 2810), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data / data)'], {}), '(c.values, data / data)\n', (2787, 2810), True, 'import numpy as np\n'), ((2838, 2874), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data / 2.0)'], {}), '(c.values, data / 2.0)\n', (2852, 2874), True, 'import numpy as np\n'), ((2906, 2943), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data / data)'], {}), '(c.values, data / data)\n', (2920, 2943), True, 'import numpy as np\n'), ((2966, 3010), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data / data / data)'], {}), '(c.values, data / data / data)\n', (2980, 3010), True, 'import numpy as np\n'), ((3039, 3090), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data / data / data / data)'], {}), '(c.values, data / data / data / data)\n', (3053, 3090), True, 'import numpy as np\n'), ((3118, 3154), 'numpy.array_equal', 'np.array_equal', (['c.values', '(2.0 / data)'], {}), '(c.values, 2.0 / data)\n', (3132, 3154), True, 'import numpy as np\n'), ((3258, 3296), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data ** data)'], {}), '(c.values, data ** data)\n', (3272, 3296), True, 'import numpy as np\n'), ((3318, 3366), 'numpy.array_equal', 'np.array_equal', (['c.values', '((data ** data) ** data)'], {}), '(c.values, (data ** data) ** data)\n', (3332, 3366), True, 'import numpy as np\n'), ((3387, 3422), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data ** 3)'], {}), '(c.values, data ** 3)\n', (3401, 3422), True, 'import numpy as np\n'), ((3444, 3486), 'numpy.array_equal', 'np.array_equal', (['c.values', '((data ** 3) ** 3)'], {}), '(c.values, (data ** 3) ** 3)\n', (3458, 3486), True, 'import numpy as np\n'), ((3509, 3546), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data ** 3.0)'], {}), '(c.values, data ** 3.0)\n', (3523, 3546), True, 'import numpy as np\n'), ((3570, 3616), 'numpy.array_equal', 'np.array_equal', (['c.values', '((data ** 3.0) ** 3.0)'], {}), '(c.values, (data ** 3.0) ** 3.0)\n', (3584, 3616), True, 'import numpy as np\n'), ((3643, 3681), 'numpy.array_equal', 'np.array_equal', (['c.values', '(data ** data)'], {}), '(c.values, data ** data)\n', (3657, 3681), True, 'import numpy as np\n'), ((3709, 3757), 'numpy.array_equal', 'np.array_equal', (['c.values', '((data ** data) ** data)'], {}), '(c.values, (data ** data) ** data)\n', (3723, 3757), True, 'import numpy as np\n'), ((3778, 3813), 'numpy.array_equal', 'np.array_equal', (['c.values', '(2 ** data)'], {}), '(c.values, 2 ** data)\n', (3792, 3813), True, 'import numpy as np\n'), ((3838, 3875), 'numpy.array_equal', 'np.array_equal', (['c.values', '(2.0 ** data)'], {}), '(c.values, 2.0 ** data)\n', (3852, 3875), True, 'import numpy as np\n'), ((3922, 3960), 'scipp.Variable', 'sc.Variable', ([], {'dims': "['x']", 'values': '[10.0]'}), "(dims=['x'], values=[10.0])\n", (3933, 3960), True, 'import scipp as sc\n'), ((3976, 4014), 'scipp.Variable', 'sc.Variable', ([], {'dims': "['x']", 'values': '[12.0]'}), "(dims=['x'], values=[12.0])\n", (3987, 4014), True, 'import scipp as sc\n'), ((4037, 4062), 'scipp.identical', 'sc.identical', (['v', 'expected'], {}), '(v, expected)\n', (4049, 4062), True, 'import scipp as sc\n'), ((4111, 4149), 'scipp.Variable', 'sc.Variable', ([], {'dims': "['x']", 'values': '[10.0]'}), "(dims=['x'], values=[10.0])\n", (4122, 4149), True, 'import scipp as sc\n'), ((4165, 4202), 'scipp.Variable', 'sc.Variable', ([], {'dims': "['x']", 'values': '[9.0]'}), "(dims=['x'], values=[9.0])\n", (4176, 4202), True, 'import scipp as sc\n'), ((4225, 4250), 'scipp.identical', 'sc.identical', (['v', 'expected'], {}), '(v, expected)\n', (4237, 4250), True, 'import scipp as sc\n'), ((4299, 4337), 'scipp.Variable', 'sc.Variable', ([], {'dims': "['x']", 'values': '[10.0]'}), "(dims=['x'], values=[10.0])\n", (4310, 4337), True, 'import scipp as sc\n'), ((4353, 4391), 'scipp.Variable', 'sc.Variable', ([], {'dims': "['x']", 'values': '[30.0]'}), "(dims=['x'], values=[30.0])\n", (4364, 4391), True, 'import scipp as sc\n'), ((4414, 4439), 'scipp.identical', 'sc.identical', (['v', 'expected'], {}), '(v, expected)\n', (4426, 4439), True, 'import scipp as sc\n'), ((4492, 4530), 'scipp.Variable', 'sc.Variable', ([], {'dims': "['x']", 'values': '[10.0]'}), "(dims=['x'], values=[10.0])\n", (4503, 4530), True, 'import scipp as sc\n'), ((4546, 4583), 'scipp.Variable', 'sc.Variable', ([], {'dims': "['x']", 'values': '[5.0]'}), "(dims=['x'], values=[5.0])\n", (4557, 4583), True, 'import scipp as sc\n'), ((4606, 4631), 'scipp.identical', 'sc.identical', (['v', 'expected'], {}), '(v, expected)\n', (4618, 4631), True, 'import scipp as sc\n'), ((4803, 4820), 'scipp.zeros_like', 'sc.zeros_like', (['da'], {}), '(da)\n', (4816, 4820), True, 'import scipp as sc\n'), ((4841, 4871), 'scipp.arange', 'sc.arange', (['"""x"""', '(2.0)', '(20.0)', '(2.0)'], {}), "('x', 2.0, 20.0, 2.0)\n", (4850, 4871), True, 'import scipp as sc\n'), ((4883, 4914), 'scipp.identical', 'sc.identical', (['(da + da)', 'expected'], {}), '(da + da, expected)\n', (4895, 4914), True, 'import scipp as sc\n'), ((5086, 5103), 'scipp.zeros_like', 'sc.zeros_like', (['da'], {}), '(da)\n', (5099, 5103), True, 'import scipp as sc\n'), ((5115, 5146), 'scipp.identical', 'sc.identical', (['(da - da)', 'expected'], {}), '(da - da, expected)\n', (5127, 5146), True, 'import scipp as sc\n'), ((5318, 5335), 'scipp.zeros_like', 'sc.zeros_like', (['da'], {}), '(da)\n', (5331, 5335), True, 'import scipp as sc\n'), ((5396, 5427), 'scipp.identical', 'sc.identical', (['(da * da)', 'expected'], {}), '(da * da, expected)\n', (5408, 5427), True, 'import scipp as sc\n'), ((5603, 5619), 'scipp.ones_like', 'sc.ones_like', (['da'], {}), '(da)\n', (5615, 5619), True, 'import scipp as sc\n'), ((5631, 5662), 'scipp.identical', 'sc.identical', (['(da / da)', 'expected'], {}), '(da / da, expected)\n', (5643, 5662), True, 'import scipp as sc\n'), ((5833, 5850), 'scipp.zeros_like', 'sc.zeros_like', (['da'], {}), '(da)\n', (5846, 5850), True, 'import scipp as sc\n'), ((5871, 5901), 'scipp.arange', 'sc.arange', (['"""x"""', '(2.0)', '(20.0)', '(2.0)'], {}), "('x', 2.0, 20.0, 2.0)\n", (5880, 5901), True, 'import scipp as sc\n'), ((5913, 5949), 'scipp.identical', 'sc.identical', (['(da + da.data)', 'expected'], {}), '(da + da.data, expected)\n', (5925, 5949), True, 'import scipp as sc\n'), ((5961, 5997), 'scipp.identical', 'sc.identical', (['(da.data + da)', 'expected'], {}), '(da.data + da, expected)\n', (5973, 5997), True, 'import scipp as sc\n'), ((6168, 6185), 'scipp.zeros_like', 'sc.zeros_like', (['da'], {}), '(da)\n', (6181, 6185), True, 'import scipp as sc\n'), ((6197, 6233), 'scipp.identical', 'sc.identical', (['(da - da.data)', 'expected'], {}), '(da - da.data, expected)\n', (6209, 6233), True, 'import scipp as sc\n'), ((6245, 6281), 'scipp.identical', 'sc.identical', (['(da.data - da)', 'expected'], {}), '(da.data - da, expected)\n', (6257, 6281), True, 'import scipp as sc\n'), ((6452, 6469), 'scipp.zeros_like', 'sc.zeros_like', (['da'], {}), '(da)\n', (6465, 6469), True, 'import scipp as sc\n'), ((6530, 6566), 'scipp.identical', 'sc.identical', (['(da * da.data)', 'expected'], {}), '(da * da.data, expected)\n', (6542, 6566), True, 'import scipp as sc\n'), ((6578, 6614), 'scipp.identical', 'sc.identical', (['(da.data * da)', 'expected'], {}), '(da.data * da, expected)\n', (6590, 6614), True, 'import scipp as sc\n'), ((6789, 6805), 'scipp.ones_like', 'sc.ones_like', (['da'], {}), '(da)\n', (6801, 6805), True, 'import scipp as sc\n'), ((6817, 6853), 'scipp.identical', 'sc.identical', (['(da / da.data)', 'expected'], {}), '(da / da.data, expected)\n', (6829, 6853), True, 'import scipp as sc\n'), ((6865, 6901), 'scipp.identical', 'sc.identical', (['(da.data / da)', 'expected'], {}), '(da.data / da, expected)\n', (6877, 6901), True, 'import scipp as sc\n'), ((7070, 7087), 'scipp.zeros_like', 'sc.zeros_like', (['da'], {}), '(da)\n', (7083, 7087), True, 'import scipp as sc\n'), ((7108, 7133), 'scipp.arange', 'sc.arange', (['"""x"""', '(3.0)', '(12.0)'], {}), "('x', 3.0, 12.0)\n", (7117, 7133), True, 'import scipp as sc\n'), ((7145, 7177), 'scipp.identical', 'sc.identical', (['(da + 2.0)', 'expected'], {}), '(da + 2.0, expected)\n', (7157, 7177), True, 'import scipp as sc\n'), ((7189, 7221), 'scipp.identical', 'sc.identical', (['(2.0 + da)', 'expected'], {}), '(2.0 + da, expected)\n', (7201, 7221), True, 'import scipp as sc\n'), ((7390, 7407), 'scipp.zeros_like', 'sc.zeros_like', (['da'], {}), '(da)\n', (7403, 7407), True, 'import scipp as sc\n'), ((7471, 7503), 'scipp.identical', 'sc.identical', (['(da - 2.0)', 'expected'], {}), '(da - 2.0, expected)\n', (7483, 7503), True, 'import scipp as sc\n'), ((7567, 7599), 'scipp.identical', 'sc.identical', (['(2.0 - da)', 'expected'], {}), '(2.0 - da, expected)\n', (7579, 7599), True, 'import scipp as sc\n'), ((7768, 7785), 'scipp.zeros_like', 'sc.zeros_like', (['da'], {}), '(da)\n', (7781, 7785), True, 'import scipp as sc\n'), ((7806, 7836), 'scipp.arange', 'sc.arange', (['"""x"""', '(2.0)', '(20.0)', '(2.0)'], {}), "('x', 2.0, 20.0, 2.0)\n", (7815, 7836), True, 'import scipp as sc\n'), ((7848, 7880), 'scipp.identical', 'sc.identical', (['(da * 2.0)', 'expected'], {}), '(da * 2.0, expected)\n', (7860, 7880), True, 'import scipp as sc\n'), ((7892, 7924), 'scipp.identical', 'sc.identical', (['(2.0 * da)', 'expected'], {}), '(2.0 * da, expected)\n', (7904, 7924), True, 'import scipp as sc\n'), ((8097, 8114), 'scipp.zeros_like', 'sc.zeros_like', (['da'], {}), '(da)\n', (8110, 8114), True, 'import scipp as sc\n'), ((8178, 8210), 'scipp.identical', 'sc.identical', (['(da / 2.0)', 'expected'], {}), '(da / 2.0, expected)\n', (8190, 8210), True, 'import scipp as sc\n'), ((8274, 8306), 'scipp.identical', 'sc.identical', (['(2.0 / da)', 'expected'], {}), '(2.0 / da, expected)\n', (8286, 8306), True, 'import scipp as sc\n'), ((8518, 8547), 'scipp.Dataset', 'sc.Dataset', (["{'data': da + da}"], {}), "({'data': da + da})\n", (8528, 8547), True, 'import scipp as sc\n'), ((8572, 8598), 'scipp.identical', 'sc.identical', (['ds', 'expected'], {}), '(ds, expected)\n', (8584, 8598), True, 'import scipp as sc\n'), ((8810, 8839), 'scipp.Dataset', 'sc.Dataset', (["{'data': da - da}"], {}), "({'data': da - da})\n", (8820, 8839), True, 'import scipp as sc\n'), ((8864, 8890), 'scipp.identical', 'sc.identical', (['ds', 'expected'], {}), '(ds, expected)\n', (8876, 8890), True, 'import scipp as sc\n'), ((9102, 9131), 'scipp.Dataset', 'sc.Dataset', (["{'data': da * da}"], {}), "({'data': da * da})\n", (9112, 9131), True, 'import scipp as sc\n'), ((9156, 9182), 'scipp.identical', 'sc.identical', (['ds', 'expected'], {}), '(ds, expected)\n', (9168, 9182), True, 'import scipp as sc\n'), ((9398, 9427), 'scipp.Dataset', 'sc.Dataset', (["{'data': da / da}"], {}), "({'data': da / da})\n", (9408, 9427), True, 'import scipp as sc\n'), ((9452, 9478), 'scipp.identical', 'sc.identical', (['ds', 'expected'], {}), '(ds, expected)\n', (9464, 9478), True, 'import scipp as sc\n'), ((9728, 9754), 'scipp.identical', 'sc.identical', (['ds', 'expected'], {}), '(ds, expected)\n', (9740, 9754), True, 'import scipp as sc\n'), ((10004, 10030), 'scipp.identical', 'sc.identical', (['ds', 'expected'], {}), '(ds, expected)\n', (10016, 10030), True, 'import scipp as sc\n'), ((10280, 10306), 'scipp.identical', 'sc.identical', (['ds', 'expected'], {}), '(ds, expected)\n', (10292, 10306), True, 'import scipp as sc\n'), ((10560, 10586), 'scipp.identical', 'sc.identical', (['ds', 'expected'], {}), '(ds, expected)\n', (10572, 10586), True, 'import scipp as sc\n'), ((10819, 10845), 'scipp.identical', 'sc.identical', (['ds', 'expected'], {}), '(ds, expected)\n', (10831, 10845), True, 'import scipp as sc\n'), ((4697, 4722), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (4706, 4722), True, 'import scipp as sc\n'), ((4980, 5005), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (4989, 5005), True, 'import scipp as sc\n'), ((5212, 5237), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (5221, 5237), True, 'import scipp as sc\n'), ((5356, 5381), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (5365, 5381), True, 'import scipp as sc\n'), ((5497, 5522), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (5506, 5522), True, 'import scipp as sc\n'), ((5727, 5752), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (5736, 5752), True, 'import scipp as sc\n'), ((6062, 6087), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (6071, 6087), True, 'import scipp as sc\n'), ((6346, 6371), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (6355, 6371), True, 'import scipp as sc\n'), ((6490, 6515), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (6499, 6515), True, 'import scipp as sc\n'), ((6683, 6708), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (6692, 6708), True, 'import scipp as sc\n'), ((6964, 6989), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (6973, 6989), True, 'import scipp as sc\n'), ((7284, 7309), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (7293, 7309), True, 'import scipp as sc\n'), ((7428, 7453), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (7437, 7453), True, 'import scipp as sc\n'), ((7530, 7555), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (7539, 7555), True, 'import scipp as sc\n'), ((7662, 7687), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (7671, 7687), True, 'import scipp as sc\n'), ((7991, 8016), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (8000, 8016), True, 'import scipp as sc\n'), ((8135, 8160), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (8144, 8160), True, 'import scipp as sc\n'), ((8237, 8262), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (8246, 8262), True, 'import scipp as sc\n'), ((8371, 8396), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (8380, 8396), True, 'import scipp as sc\n'), ((8663, 8688), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (8672, 8688), True, 'import scipp as sc\n'), ((8955, 8980), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (8964, 8980), True, 'import scipp as sc\n'), ((9251, 9276), 'scipp.arange', 'sc.arange', (['"""x"""', '(1.0)', '(10.0)'], {}), "('x', 1.0, 10.0)\n", (9260, 9276), True, 'import scipp as sc\n'), ((10933, 10945), 'scipp.scalar', 'sc.scalar', (['(5)'], {}), '(5)\n', (10942, 10945), True, 'import scipp as sc\n'), ((11040, 11054), 'scipp.scalar', 'sc.scalar', (['(3.0)'], {}), '(3.0)\n', (11049, 11054), True, 'import scipp as sc\n'), ((11163, 11177), 'scipp.scalar', 'sc.scalar', (['(2.0)'], {}), '(2.0)\n', (11172, 11177), True, 'import scipp as sc\n'), ((11266, 11278), 'scipp.scalar', 'sc.scalar', (['(1)'], {}), '(1)\n', (11275, 11278), True, 'import scipp as sc\n'), ((11376, 11388), 'scipp.scalar', 'sc.scalar', (['(6)'], {}), '(6)\n', (11385, 11388), True, 'import scipp as sc\n'), ((11487, 11499), 'scipp.scalar', 'sc.scalar', (['(1)'], {}), '(1)\n', (11496, 11499), True, 'import scipp as sc\n'), ((11584, 11597), 'scipp.scalar', 'sc.scalar', (['(-3)'], {}), '(-3)\n', (11593, 11597), True, 'import scipp as sc\n'), ((10904, 10916), 'scipp.scalar', 'sc.scalar', (['(3)'], {}), '(3)\n', (10913, 10916), True, 'import scipp as sc\n'), ((10918, 10930), 'scipp.scalar', 'sc.scalar', (['(2)'], {}), '(2)\n', (10927, 10930), True, 'import scipp as sc\n'), ((11011, 11023), 'scipp.scalar', 'sc.scalar', (['(6)'], {}), '(6)\n', (11020, 11023), True, 'import scipp as sc\n'), ((11025, 11037), 'scipp.scalar', 'sc.scalar', (['(2)'], {}), '(2)\n', (11034, 11037), True, 'import scipp as sc\n'), ((11132, 11144), 'scipp.scalar', 'sc.scalar', (['(6)'], {}), '(6)\n', (11141, 11144), True, 'import scipp as sc\n'), ((11146, 11160), 'scipp.scalar', 'sc.scalar', (['(2.5)'], {}), '(2.5)\n', (11155, 11160), True, 'import scipp as sc\n'), ((11237, 11249), 'scipp.scalar', 'sc.scalar', (['(3)'], {}), '(3)\n', (11246, 11249), True, 'import scipp as sc\n'), ((11251, 11263), 'scipp.scalar', 'sc.scalar', (['(2)'], {}), '(2)\n', (11260, 11263), True, 'import scipp as sc\n'), ((11347, 11359), 'scipp.scalar', 'sc.scalar', (['(3)'], {}), '(3)\n', (11356, 11359), True, 'import scipp as sc\n'), ((11361, 11373), 'scipp.scalar', 'sc.scalar', (['(2)'], {}), '(2)\n', (11370, 11373), True, 'import scipp as sc\n'), ((11458, 11470), 'scipp.scalar', 'sc.scalar', (['(3)'], {}), '(3)\n', (11467, 11470), True, 'import scipp as sc\n'), ((11472, 11484), 'scipp.scalar', 'sc.scalar', (['(2)'], {}), '(2)\n', (11481, 11484), True, 'import scipp as sc\n'), ((11569, 11581), 'scipp.scalar', 'sc.scalar', (['(3)'], {}), '(3)\n', (11578, 11581), True, 'import scipp as sc\n'), ((4759, 4785), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (4768, 4785), True, 'import scipp as sc\n'), ((5042, 5068), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (5051, 5068), True, 'import scipp as sc\n'), ((5274, 5300), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (5283, 5300), True, 'import scipp as sc\n'), ((5559, 5585), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (5568, 5585), True, 'import scipp as sc\n'), ((5789, 5815), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (5798, 5815), True, 'import scipp as sc\n'), ((6124, 6150), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (6133, 6150), True, 'import scipp as sc\n'), ((6408, 6434), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (6417, 6434), True, 'import scipp as sc\n'), ((6745, 6771), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (6754, 6771), True, 'import scipp as sc\n'), ((7026, 7052), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (7035, 7052), True, 'import scipp as sc\n'), ((7346, 7372), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (7355, 7372), True, 'import scipp as sc\n'), ((7724, 7750), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (7733, 7750), True, 'import scipp as sc\n'), ((8053, 8079), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (8062, 8079), True, 'import scipp as sc\n'), ((8433, 8459), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (8442, 8459), True, 'import scipp as sc\n'), ((8725, 8751), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (8734, 8751), True, 'import scipp as sc\n'), ((9017, 9043), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (9026, 9043), True, 'import scipp as sc\n'), ((9313, 9339), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (9322, 9339), True, 'import scipp as sc\n'), ((9552, 9572), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)'], {}), "('x', 10.0)\n", (9561, 9572), True, 'import scipp as sc\n'), ((9608, 9634), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (9617, 9634), True, 'import scipp as sc\n'), ((9828, 9848), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)'], {}), "('x', 10.0)\n", (9837, 9848), True, 'import scipp as sc\n'), ((9884, 9910), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (9893, 9910), True, 'import scipp as sc\n'), ((10104, 10124), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)'], {}), "('x', 10.0)\n", (10113, 10124), True, 'import scipp as sc\n'), ((10160, 10186), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (10169, 10186), True, 'import scipp as sc\n'), ((10384, 10404), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)'], {}), "('x', 10.0)\n", (10393, 10404), True, 'import scipp as sc\n'), ((10440, 10466), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (10449, 10466), True, 'import scipp as sc\n'), ((10671, 10691), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)'], {}), "('x', 10.0)\n", (10680, 10691), True, 'import scipp as sc\n'), ((10727, 10753), 'scipp.arange', 'sc.arange', (['"""x"""', '(10.0)', '(20.0)'], {}), "('x', 10.0, 20.0)\n", (10736, 10753), True, 'import scipp as sc\n')]
from numpy import zeros, swapaxes, sign from ....Methods.Machine.Winding import WindingError from swat_em import datamodel def comp_connection_mat(self, Zs=None, p=None): """Compute the Winding Matrix for Parameters ---------- self : Winding A: Winding object Zs : int Number of Slot (Integer >0) p : int Number of pole pairs (Integer >0) Returns ------- wind_mat: numpy.ndarray Winding Matrix (1, 1, Zs, qs) Raises ------ WindingT2DefNtError Zs/qs/2 must be an integer """ if Zs is None: if not hasattr(self.parent, "slot") and not hasattr(self.parent, "slot_list"): raise WindingError("The Winding object must be in a Lamination object.") Zs = self.parent.get_Zs() if p is None: if self.parent is None: raise WindingError("The Winding object must be in a Lamination object.") p = self.parent.get_pole_pair_number() assert Zs > 0, "Zs must be >0" assert Zs % 1 == 0, "Zs must be an integer" assert p > 0, "p must be >0" assert p % 1 == 0, "p must be an integer" qs = self.qs # Phase Number Ntcoil = self.Ntcoil # number of turns per coils Nlayer = self.Nlayer # number of layers # Coil pitch (or coil span) if self.coil_pitch in [0, None]: # Number of slots per pole and per phase spp = Zs / (2 * p * qs) if spp > 0.5: # distributed winding self.coil_pitch = int(qs * spp) else: # tooth concentrated winding self.coil_pitch = 1 # generate a datamodel for the winding wdg = datamodel() # generate winding from inputs wdg.genwdg(Q=Zs, P=2 * p, m=qs, layers=Nlayer, turns=Ntcoil, w=self.coil_pitch) # init connexion matrix wind_mat = zeros((Nlayer, 1, Zs, qs)) # get connexion matrix from swat-em wind_mat_swat = wdg.get_phases() # perform checks assert p == wdg.get_num_polepairs(), ( "number of pole pairs is not as requested (returned " + str(wdg.get_num_polepairs()) + " expected " + str(p) + ")" ) assert qs == wdg.get_num_phases(), ( "number of phases is not as requested (returned " + str(wdg.get_num_phases()) + " expected " + str(qs) + ")" ) # convert swat-em connexion matrix to pyleecan connexion matrix for qq, phase in enumerate(wind_mat_swat): for ll, layer in enumerate(phase): if len(layer) > 0: for cond in layer: wind_mat[Nlayer - ll - 1, 0, abs(cond) - 1, qq] = ( sign(cond) * Ntcoil ) # permute radial and tangential layers if coil span is 1 if wdg.get_coilspan() == 1: wind_mat = swapaxes(wind_mat, 0, 1) # check that requested number of parallel connections is feasible Npcp_list = wdg.get_parallel_connections() if self.Npcp is None: self.Npcp = Npcp_list[0] elif self.Npcp > 2 * p: # self.Npcp = 2 * p self.get_logger().warning( "Number of parallel circuits per phase should be < 2*p, current value is: " + str(self.Npcp) ) # if self.Npcp not in Npcp_list: # if self.Npcp is not None: # self.get_logger().warning( # "Requested number of parallel circuits per phase is not feasible, assign it to: " # + str(Npcp_list[0]) # ) # self.Npcp = Npcp_list[0] # enforce the number of layers if it is not as requested Nlayer_actual = wdg.get_num_layers() if self.Nlayer != Nlayer_actual: self.Nlayer = Nlayer_actual self.get_logger().info( "Requested number of layers is not feasible, assign it to: " + str(Nlayer_actual) ) # get periodicities # self.per_a = wdg.get_periodicity_t() # self.is_aper_a = wdg.get_is_symmetric() # To check periodicities swat-em / pyleecan definitions self.per_a, self.is_aper_a = self.comp_periodicity(wind_mat=wind_mat) # if is_aper_a: # Different def for Anti per # per_a = per_a / 2 # if self.per_a != per_a or self.is_aper_a != is_aper_a: # self.get_logger().warning( # "(Anti-)periodicity calculated by pyleecan and SWAT_EM differs" # ) # Set default values if self.is_reverse_wind is None: self.is_reverse_wind = False if self.Nslot_shift_wind is None: self.Nslot_shift_wind = 0 return wind_mat
[ "numpy.zeros", "numpy.swapaxes", "swat_em.datamodel", "numpy.sign" ]
[((1676, 1687), 'swat_em.datamodel', 'datamodel', ([], {}), '()\n', (1685, 1687), False, 'from swat_em import datamodel\n'), ((1852, 1878), 'numpy.zeros', 'zeros', (['(Nlayer, 1, Zs, qs)'], {}), '((Nlayer, 1, Zs, qs))\n', (1857, 1878), False, 'from numpy import zeros, swapaxes, sign\n'), ((2855, 2879), 'numpy.swapaxes', 'swapaxes', (['wind_mat', '(0)', '(1)'], {}), '(wind_mat, 0, 1)\n', (2863, 2879), False, 'from numpy import zeros, swapaxes, sign\n'), ((2700, 2710), 'numpy.sign', 'sign', (['cond'], {}), '(cond)\n', (2704, 2710), False, 'from numpy import zeros, swapaxes, sign\n')]
""" Kernel orthogonal matching pursuit for changepoint detection. Fast but approximate. """ from itertools import product import numpy as np from ruptures.utils import pairwise class OmpK: """Contient l'algorithme de parcours des partitions.""" def __init__(self, min_size=2, jump=5): """One line description Detailled description Args: min_size (int, optional): minimum segment length jump (int, optional): subsample (one every "jump" points) Returns: self """ self.min_size = min_size # not used self.jump = jump # not used self.n_samples = None self.gram = None def _seg(self, n_bkps=None, pen=None, epsilon=None): """Computes the binary segmentation. The stopping rule depends on the parameter passed to the function. Args: n_bkps (int): number of breakpoints to find before stopping. penalty (float): penalty value (>0) epsilon (float): reconstruction budget Returns: list: list of breakpoint indexes """ stop = False bkps = [self.n_samples] inds = np.arange(1, self.n_samples + 1) csum = self.gram.cumsum(axis=0).cumsum(axis=1) residual = csum[-1, -1] while not stop: # greedy search correlation = np.diag(csum) * self.n_samples * self.n_samples correlation += inds ** 2 * csum[-1, -1] correlation -= 2 * self.n_samples * inds * csum[-1] correlation /= inds * inds[::-1] bkp = np.argmax(correlation) + 1 # orthogonal projection (matrix form) # adj = np.zeros(self.gram.shape) # adjacency matrix # for start, end in pairwise(sorted([0, bkp] + bkps)): # duree = end - start # adj[start:end, start:end] = np.ones(duree, duree) / duree # gram_new = self.gram + adj @ self.gram @ adj - adj @ self.gram - self.gram @ adj # csum = gram_new.cumsum(axis=0).cumsum(axis=1) # orthogonal projection (vectorized form) gram_new = self.gram.copy() # cross product cross_g = np.zeros(self.gram.shape) for start, end in pairwise(sorted([0, bkp] + bkps)): val = self.gram[:, start:end].mean(axis=1).reshape(-1, 1) cross_g[:, start:end] = val gram_new -= cross_g + cross_g.T # products of segment means for p, q in product(pairwise(sorted([0, bkp] + bkps)), repeat=2): start1, end1 = p start2, end2 = q gram_new[start1:end1, start2:end2] += self.gram[ start1:end1, start2:end2 ].mean() csum = gram_new.cumsum(axis=0).cumsum(axis=1) # stopping criterion stop = True if n_bkps is not None: if len(bkps) - 1 < n_bkps: stop = False elif pen is not None: if residual - csum[-1, -1] > pen: stop = False elif epsilon is not None: if csum[-1, -1] > epsilon: stop = False # update if not stop: residual = csum[-1, -1] bkps.append(bkp) bkps.sort() return bkps def fit(self, gram): """Compute params to segment signal. Args: gram (array): Gram matrix of signal to segment. Shape (n_samples, n_samples). Returns: self """ assert gram.shape[0] == gram.shape[1], "Not a square matrix." # update some params self.gram = gram self.n_samples, _ = self.gram.shape return self def predict(self, n_bkps=None, pen=None, epsilon=None): """Return the optimal breakpoints. Must be called after the fit method. The breakpoints are associated with the signal passed to fit(). The stopping rule depends on the parameter passed to the function. Args: n_bkps (int): number of breakpoints to find before stopping. penalty (float): penalty value (>0) penalty (float): penalty value Returns: list: sorted list of breakpoints """ msg = "Give a parameter." assert any(param is not None for param in (n_bkps, pen, epsilon)), msg bkps = self._seg(n_bkps=n_bkps, pen=pen, epsilon=epsilon) return bkps def fit_predict(self, gram, n_bkps=None, pen=None, epsilon=None): """Helper method to call fit and predict once.""" self.fit(gram) return self.predict(n_bkps=n_bkps, pen=pen, epsilon=epsilon)
[ "numpy.zeros", "numpy.diag", "numpy.arange", "numpy.argmax" ]
[((1204, 1236), 'numpy.arange', 'np.arange', (['(1)', '(self.n_samples + 1)'], {}), '(1, self.n_samples + 1)\n', (1213, 1236), True, 'import numpy as np\n'), ((2255, 2280), 'numpy.zeros', 'np.zeros', (['self.gram.shape'], {}), '(self.gram.shape)\n', (2263, 2280), True, 'import numpy as np\n'), ((1630, 1652), 'numpy.argmax', 'np.argmax', (['correlation'], {}), '(correlation)\n', (1639, 1652), True, 'import numpy as np\n'), ((1403, 1416), 'numpy.diag', 'np.diag', (['csum'], {}), '(csum)\n', (1410, 1416), True, 'import numpy as np\n')]
import numpy as np # --------------------------- line-search --------------------------- def wolfe(func, grad, xk, alpha, pk): c1 = 1e-4 return func(xk + alpha * pk) <= func(xk) + c1 * alpha * np.dot(grad(xk), pk) def strong_wolfe(func, grad, xk, alpha, pk, c2): return wolfe(func, grad, xk, alpha, pk) and abs( np.dot(grad(xk + alpha * pk), pk)) <= c2 * abs(np.dot(grad(xk), pk)) def step_length(func, grad, xk, pk, alpha=1., c2=0.9, max_iters=20): f_alpha = lambda alpha: func(xk + alpha * pk) g_alpha = lambda alpha: np.dot(grad(xk + alpha * pk), pk) l = 0.0 h = 1.0 for i in range(max_iters): if strong_wolfe(func, grad, xk, alpha, pk, c2): return alpha half = (l + h) / 2 alpha = - g_alpha(l) * (h ** 2) / (2 * (f_alpha(h) - f_alpha(l) - g_alpha(l) * h)) if alpha < l or alpha > h: alpha = half if g_alpha(alpha) > 0: h = alpha elif g_alpha(alpha) <= 0: l = alpha return alpha # --------------------------- termination criterion --------------------------- def termination_criterion(termination_version, grad, xk, xk1, tol): if termination_version == 0: return np.linalg.norm(grad(xk1)) < tol elif termination_version == 1: return np.linalg.norm(grad(xk1)) / np.linalg.norm(grad(xk)) < tol TERMINATION_VERSION = 0 # TODO: Don't change this argument if not necessary! # --------------------------- gradient descent --------------------------- def gradient_descent(func, grad, x0, tol=1e-5, max_iters=1000): k = 0 xk = x0 gk = grad(xk) logs = [[*xk, func(xk), np.linalg.norm(gk)]] while True: tau = step_length(func, grad, xk, -gk, alpha=1.0, c2=0.9) sk = -tau * gk xk1 = xk + sk if termination_criterion(TERMINATION_VERSION, grad, xk, xk1, tol): logs.append([*xk1, func(xk1), np.linalg.norm(grad(xk1))]) break if k >= max_iters: break xk = xk1 gk = grad(xk) k += 1 logs.append([*xk, func(xk), np.linalg.norm(gk)]) return xk, np.array(logs) # --------------------------- newton --------------------------- def newton(func, grad, hess, x0, tol=1e-5, max_iters=1000): k = 0 xk = x0 gk = grad(xk) logs = [[*xk, func(xk), np.linalg.norm(gk)]] while True: hk = np.linalg.inv(hess(xk)) tau = step_length(func, grad, xk, -hk@gk, alpha=1.0, c2=0.9) sk = -tau * hk@gk xk1 = xk + sk gk1 = grad(xk1) if termination_criterion(TERMINATION_VERSION, grad, xk, xk1, tol): logs.append([*xk1, func(xk1), np.linalg.norm(gk1)]) break if k >= max_iters: break xk = xk1 gk = gk1 k += 1 logs.append([*xk, func(xk), np.linalg.norm(gk)]) return xk, np.array(logs) # --------------------------- bfgs --------------------------- def bfgs(func, grad, x0, tol=1e-5, max_iters=1000): k = 0 xk = x0 gk = grad(xk) hk = e = np.eye(xk.__len__()) logs = [[*xk, func(xk), np.linalg.norm(gk)]] while True: pk = -hk @ gk tau = step_length(func, grad, xk, alpha=1.0, pk=pk, c2=0.9) sk = tau * pk xk1 = xk + sk gk1 = grad(xk1) yk = gk1 - gk if termination_criterion(TERMINATION_VERSION, grad, xk, xk1, tol): logs.append([*xk1, func(xk1), np.linalg.norm(gk1)]) break if np.linalg.norm(yk) == 0: logs = logs[:-1] break if k >= max_iters: break xk = xk1 gk = gk1 temp = e - np.outer(sk, yk) / np.inner(sk, yk) hk = temp @ hk @ temp.T + np.outer(sk, sk) / np.inner(sk, yk) k += 1 logs.append([*xk, func(xk), np.linalg.norm(gk)]) return xk, np.array(logs) # --------------------------- l-bfgs --------------------------- def two_loop_recursion(sks, yks, H0, q): m_t = len(sks) a = np.zeros(m_t) b = np.zeros(m_t) # print('global_var = ', q) for i in reversed(range(m_t)): s = sks[i] y = yks[i] rho_i = float(1.0 / y.T.dot(s)) a[i] = rho_i * s.dot(q) q = q - a[i] * y r = H0.dot(q) for i in range(m_t): s = sks[i] y = yks[i] rho_i = float(1.0 / y.T.dot(s)) b[i] = rho_i * y.dot(r) r = r + s * (a[i] - b[i]) return -r def l_bfgs(func, grad, m, x0, tol=1e-5, max_iters=1000): k = 0 xk = x0 gk = grad(xk) I = np.identity(xk.size) sks = [] yks = [] logs = [[*xk, func(xk), np.linalg.norm(gk)]] while True: # compute search direction pk = two_loop_recursion(sks, yks, I, gk) # obtain step length by line search tau = step_length(func, grad, xk, alpha=1.0, pk=pk, c2=0.9) # update x xk1 = xk + tau * pk gk1 = grad(xk1) # define sk and yk for convenience sk = xk1 - xk yk = gk1 - gk if termination_criterion(TERMINATION_VERSION, grad, xk, xk1, tol): logs.append([*xk1, func(xk1), np.linalg.norm(gk1)]) break if np.linalg.norm(yk) == 0: logs = logs[:-1] break if k >= max_iters: break xk = xk1 gk = gk1 sks.append(sk) yks.append(yk) if len(sks) > m: sks = sks[1:] yks = yks[1:] k += 1 logs.append([*xk, func(xk), np.linalg.norm(gk)]) return xk, np.array(logs) # --------------------------- fast-bfgs --------------------------- def update_lk(m, yk, sks, lk, secant=False): """ lk <- tk @ lk @ tk.T + [[0, 0], [0, 1]]. # ----------------------- note 1 ----------------------- tk = \begin{bmatrix} t_1 & 1 & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ t_{m-1} & 0 & \cdots & 1 \\ t_m - y_k^T s_{k-m} & -y_k^T s_{k+1-m} & \cdots & -y_k^T s_{k-1} \begin{bmatrix} # ----------------------- note 2 ----------------------- \begin{bmatrix} t_1 \\ \vdots \\ t_m \end{bmatrix} = \mathop{\arg\min}_t \| \tilde{S}_{k+1} t - \tilde{\boldsymbol{s}}_{k-m} \|_2 subject to \tilde{\boldsymbol{y}}_k^T \tilde{S}_{k+1} t = \tilde{\boldsymbol{y}}_k^T \tilde{\boldsymbol{s}}_{k-m} """ k = sks.__len__() - 1 n = yk.__len__() if k < m: ys = np.array([[-np.inner(yk, sk) for sk in sks[:-1]]]) tk = np.vstack((np.eye(k), ys)) else: tk = np.zeros(shape=(m, m)) tk[:-1, 1:] = np.eye(m - 1) tk[-1] = np.array([-np.inner(yk, sk) for sk in sks[:-1]]) if m >= n: mat = np.array(sks[-n:]).T rhs = sks[0] try: c = np.linalg.solve(mat, rhs) except np.linalg.LinAlgError: # TODO: `1e-6` is set based on experimental results. c = np.linalg.solve(mat + 1e-6 * np.eye(rhs.__len__()), rhs) tk[-n:, 0] += c else: if secant: mat = np.zeros(shape=(m+1, m+1)) mat[:-1, :-1] = 2 * np.array(sks[1:]) @ np.array(sks[1:]).T mat[:-1, -1] = np.array(sks[1:]) @ yk mat[-1, :-1] = np.array(sks[1:]) @ yk rhs = np.zeros(shape=(m+1, )) rhs[:-1] = 2 * np.array(sks[1:]) @ sks[0] rhs[-1] = np.inner(yk, sks[0]) try: c = np.linalg.solve(mat, rhs) except np.linalg.LinAlgError: c = np.linalg.solve(mat + 1e-6 * np.eye(rhs.__len__()), rhs) tk[:, 0] += c[:-1] else: mat = np.array(sks[1:]) @ np.array(sks[1:]).T rhs = np.array(sks[1:]) @ sks[0] try: c = np.linalg.solve(mat, rhs) except np.linalg.LinAlgError: c = np.linalg.solve(mat + 1e-6 * np.eye(rhs.__len__()), rhs) tk[:, 0] += c lk = tk @ lk @ tk.T lk[-1, -1] += 1 return lk def estimate_vk(grad, xk, gk, pk, w1=0.5, w2=0.5): v1 = gk # TODO: `1e-6` is set based on experimental results. eps = 1e-6 / np.linalg.norm(gk) bg = (grad(xk + eps * gk) - gk) / eps if np.linalg.norm(pk) > 0: eps = 1e-6 / np.linalg.norm(pk) bp = (grad(xk + eps * pk) - gk) / eps eps = 1e-6 / np.linalg.norm(bp) b2p = (grad(xk + eps * bp) - gk) / eps else: b2p = 0 v2 = bg - b2p orth_v1 = v1 - np.inner(v1, v2) / np.inner(v2, v2) * v2 orth_v2 = v2 - np.inner(v1, v2) / np.inner(v1, v1) * v1 if np.linalg.norm(orth_v1) > 0 and np.linalg.norm(orth_v2) > 0: vk = w1 / np.linalg.norm(orth_v1) * orth_v1 + w2 / np.linalg.norm(orth_v2) * orth_v2 elif np.inner(v1, v2) > 0: vk = w1 * v1 + w2 * v2 else: raise ValueError return vk / np.linalg.norm(vk) def estimate_alpha(grad, xk, gk, pk, vk): if np.linalg.norm(vk) == 0: return 0 # TODO: `1e-6` is set based on experimental results. eps = 1e-6 / np.linalg.norm(vk) bv = (grad(xk + eps * vk) - gk) / eps if np.linalg.norm(pk) > 0: eps = 1e-6 / np.linalg.norm(pk) bp = (grad(xk + eps * pk) - gk) / eps else: bp = 0 return np.inner(gk - bp, bv) / np.inner(bv, bv) def fix_pk(grad, xk, gk, pk, version="A"): if version == "A": try: vk = estimate_vk(grad, xk, gk, pk) alpha = estimate_alpha(grad, xk, gk, pk, vk=vk) except ValueError: vk = np.zeros_like(xk) alpha = 0. elif version == "B": vk = gk alpha = estimate_alpha(grad, xk, gk, pk, vk=gk) else: raise ValueError("Invalid argument `version`.") return pk - alpha * vk def fast_bfgs(func, grad, x0, m=8, secant=False, version="A", tol=1e-5, max_iters=1000): xk = x0 gk = grad(xk) logs = [[*xk, func(xk), np.linalg.norm(gk)]] # compute x1, s0, y0 pk = -gk tau = step_length(func, grad, xk, alpha=1.0, pk=pk, c2=0.9) sk = tau * pk xk1 = xk + sk gk1 = grad(xk1) yk = gk1 - gk # update xk, gk, sks, ak, k xk = xk1 gk = gk1 sks = [sk / np.sqrt(np.abs(np.inner(sk, yk)))] lk = np.array([[1]]) k = 0 logs.append([*xk, func(xk), np.linalg.norm(gk)]) while True: # compute pk pk = -np.array(sks).T @ (lk @ (np.array(sks) @ gk)) if m < x0.__len__() or sks.__len__() <= x0.__len__(): # fix pk pk = fix_pk(grad, xk, gk, pk, version=version) # compute xk1, sk, yk tau = step_length(func, grad, xk, alpha=1.0, pk=pk, c2=0.9) sk = tau * pk xk1 = xk + sk gk1 = grad(xk1) yk = gk1 - gk if termination_criterion(TERMINATION_VERSION, grad, xk, xk1, tol): logs.append([*xk1, func(xk1), np.linalg.norm(gk1)]) break if np.linalg.norm(yk) == 0: logs = logs[:-1] break if k >= max_iters: break # update xk, gk, sks, yk, ak, k xk = xk1 gk = gk1 sks.append(sk / np.sqrt(np.abs(np.inner(sk, yk)))) yk = yk / np.sqrt(np.abs(np.inner(sk, yk))) lk = update_lk(m, yk, sks, lk, secant=secant) if len(sks) > m: sks = sks[1:] k += 1 logs.append([*xk, func(xk), np.linalg.norm(gk)]) return xk, np.array(logs) def unit_test(): print('\n' + '#' * 32 + "\tLIGHTWEIGHT TEST\t" + '#' * 32) # Rosenbrock's function class Rosenbrock: @classmethod def function(cls, x): return 100 * (x[1] - x[0] ** 2) ** 2 + (1 - x[0]) ** 2 @classmethod def gradients(cls, x): return np.array([200 * (x[1] - x[0] ** 2) * (-2 * x[0]) + 2 * (x[0] - 1), 200 * (x[1] - x[0] ** 2)]) # Styblinski & Tang's function(1990) class Styblinski: @classmethod def function(cls, x): return np.mean(x ** 4 - 16 * x ** 2 + 5 * x) @classmethod def gradients(cls, x): return (4 * x ** 3 - 32 * x + 5) / x.__len__() m = 8 # Solving Rosenbrock's function. print('-' * 32 + "\tSolving {}-dim Rosenbrock's function\t".format(2) + '-' * 32) func = Rosenbrock.function grad = Rosenbrock.gradients x0 = 1.1 * np.ones(shape=(2, )) xk, log = gradient_descent(func, grad, x0) fk, gk, k = log[-1, -2], log[-1, -1], log.__len__() print("gradient descent: fk = {:.2e}, ||gk|| = {:.2e}, iters = {}".format(fk, gk, k)) xk, log = bfgs(func, grad, x0) fk, gk, k = log[-1, -2], log[-1, -1], log.__len__() print("bfgs: fk = {:.2e}, ||gk|| = {:.2e}, iters = {}".format(fk, gk, k)) xk, log = l_bfgs(func, grad, m, x0) fk, gk, k = log[-1, -2], log[-1, -1], log.__len__() print("l-bfgs(m={}): fk = {:.2e}, ||gk|| = {:.2e}, iters = {}".format(m, fk, gk, k)) for secant in [False, True]: for version in ["A", "B"]: xk, log = fast_bfgs(func, grad, x0, m=m, version=version) fk, gk, k = log[-1, -2], log[-1, -1], log.__len__() print("fast-bfgs(secant={}, version={}, m={}): fk = {:.2e}, ||gk|| = {:.2e}, iters = {}".format( secant, version, m, fk, gk, k)) # Solving Styblinski & Tang's function. for n in [128, 256, 512, 1024]: print('-' * 32 + "\tSolving {}-dim Styblinski & Tang's function\t".format(n) + '-' * 32) func = Styblinski.function grad = Styblinski.gradients x0 = -2.5 * np.ones(shape=(n, )) + 0.1 * np.random.rand(n) xk, log = gradient_descent(func, grad, x0) fk, gk, k = log[-1, -2], log[-1, -1], log.__len__() print("gradient descent: fk = {:.2e}, ||gk|| = {:.2e}, iters = {}".format(fk, gk, k)) xk, log = bfgs(func, grad, x0) fk, gk, k = log[-1, -2], log[-1, -1], log.__len__() print("bfgs: fk = {:.2e}, ||gk|| = {:.2e}, iters = {}".format(fk, gk, k)) xk, log = l_bfgs(func, grad, m, x0) fk, gk, k = log[-1, -2], log[-1, -1], log.__len__() print("l-bfgs(m={}): fk = {:.2e}, ||gk|| = {:.2e}, iters = {}".format(m, fk, gk, k)) for secant in [False, True]: for version in ["A", "B"]: xk, log = fast_bfgs(func, grad, x0, m=m, version=version) fk, gk, k = log[-1, -2], log[-1, -1], log.__len__() print("fast-bfgs(secant={}, version={}, m={}):fk = {:.2e}, ||gk|| = {:.2e}, iters = {}".format( secant, version, m, fk, gk, k)) # unit_test()
[ "numpy.outer", "numpy.zeros_like", "numpy.zeros", "numpy.identity", "numpy.ones", "numpy.mean", "numpy.array", "numpy.linalg.norm", "numpy.inner", "numpy.random.rand", "numpy.eye", "numpy.linalg.solve" ]
[((4042, 4055), 'numpy.zeros', 'np.zeros', (['m_t'], {}), '(m_t)\n', (4050, 4055), True, 'import numpy as np\n'), ((4064, 4077), 'numpy.zeros', 'np.zeros', (['m_t'], {}), '(m_t)\n', (4072, 4077), True, 'import numpy as np\n'), ((4591, 4611), 'numpy.identity', 'np.identity', (['xk.size'], {}), '(xk.size)\n', (4602, 4611), True, 'import numpy as np\n'), ((10486, 10501), 'numpy.array', 'np.array', (['[[1]]'], {}), '([[1]])\n', (10494, 10501), True, 'import numpy as np\n'), ((2149, 2163), 'numpy.array', 'np.array', (['logs'], {}), '(logs)\n', (2157, 2163), True, 'import numpy as np\n'), ((2903, 2917), 'numpy.array', 'np.array', (['logs'], {}), '(logs)\n', (2911, 2917), True, 'import numpy as np\n'), ((3891, 3905), 'numpy.array', 'np.array', (['logs'], {}), '(logs)\n', (3899, 3905), True, 'import numpy as np\n'), ((5594, 5608), 'numpy.array', 'np.array', (['logs'], {}), '(logs)\n', (5602, 5608), True, 'import numpy as np\n'), ((6703, 6725), 'numpy.zeros', 'np.zeros', ([], {'shape': '(m, m)'}), '(shape=(m, m))\n', (6711, 6725), True, 'import numpy as np\n'), ((6748, 6761), 'numpy.eye', 'np.eye', (['(m - 1)'], {}), '(m - 1)\n', (6754, 6761), True, 'import numpy as np\n'), ((8404, 8422), 'numpy.linalg.norm', 'np.linalg.norm', (['gk'], {}), '(gk)\n', (8418, 8422), True, 'import numpy as np\n'), ((8473, 8491), 'numpy.linalg.norm', 'np.linalg.norm', (['pk'], {}), '(pk)\n', (8487, 8491), True, 'import numpy as np\n'), ((9112, 9130), 'numpy.linalg.norm', 'np.linalg.norm', (['vk'], {}), '(vk)\n', (9126, 9130), True, 'import numpy as np\n'), ((9182, 9200), 'numpy.linalg.norm', 'np.linalg.norm', (['vk'], {}), '(vk)\n', (9196, 9200), True, 'import numpy as np\n'), ((9299, 9317), 'numpy.linalg.norm', 'np.linalg.norm', (['vk'], {}), '(vk)\n', (9313, 9317), True, 'import numpy as np\n'), ((9368, 9386), 'numpy.linalg.norm', 'np.linalg.norm', (['pk'], {}), '(pk)\n', (9382, 9386), True, 'import numpy as np\n'), ((9515, 9536), 'numpy.inner', 'np.inner', (['(gk - bp)', 'bv'], {}), '(gk - bp, bv)\n', (9523, 9536), True, 'import numpy as np\n'), ((9539, 9555), 'numpy.inner', 'np.inner', (['bv', 'bv'], {}), '(bv, bv)\n', (9547, 9555), True, 'import numpy as np\n'), ((11661, 11675), 'numpy.array', 'np.array', (['logs'], {}), '(logs)\n', (11669, 11675), True, 'import numpy as np\n'), ((12590, 12609), 'numpy.ones', 'np.ones', ([], {'shape': '(2,)'}), '(shape=(2,))\n', (12597, 12609), True, 'import numpy as np\n'), ((1663, 1681), 'numpy.linalg.norm', 'np.linalg.norm', (['gk'], {}), '(gk)\n', (1677, 1681), True, 'import numpy as np\n'), ((2361, 2379), 'numpy.linalg.norm', 'np.linalg.norm', (['gk'], {}), '(gk)\n', (2375, 2379), True, 'import numpy as np\n'), ((3139, 3157), 'numpy.linalg.norm', 'np.linalg.norm', (['gk'], {}), '(gk)\n', (3153, 3157), True, 'import numpy as np\n'), ((3526, 3544), 'numpy.linalg.norm', 'np.linalg.norm', (['yk'], {}), '(yk)\n', (3540, 3544), True, 'import numpy as np\n'), ((4668, 4686), 'numpy.linalg.norm', 'np.linalg.norm', (['gk'], {}), '(gk)\n', (4682, 4686), True, 'import numpy as np\n'), ((5231, 5249), 'numpy.linalg.norm', 'np.linalg.norm', (['yk'], {}), '(yk)\n', (5245, 5249), True, 'import numpy as np\n'), ((8518, 8536), 'numpy.linalg.norm', 'np.linalg.norm', (['pk'], {}), '(pk)\n', (8532, 8536), True, 'import numpy as np\n'), ((8604, 8622), 'numpy.linalg.norm', 'np.linalg.norm', (['bp'], {}), '(bp)\n', (8618, 8622), True, 'import numpy as np\n'), ((8844, 8867), 'numpy.linalg.norm', 'np.linalg.norm', (['orth_v1'], {}), '(orth_v1)\n', (8858, 8867), True, 'import numpy as np\n'), ((8876, 8899), 'numpy.linalg.norm', 'np.linalg.norm', (['orth_v2'], {}), '(orth_v2)\n', (8890, 8899), True, 'import numpy as np\n'), ((9007, 9023), 'numpy.inner', 'np.inner', (['v1', 'v2'], {}), '(v1, v2)\n', (9015, 9023), True, 'import numpy as np\n'), ((9413, 9431), 'numpy.linalg.norm', 'np.linalg.norm', (['pk'], {}), '(pk)\n', (9427, 9431), True, 'import numpy as np\n'), ((10169, 10187), 'numpy.linalg.norm', 'np.linalg.norm', (['gk'], {}), '(gk)\n', (10183, 10187), True, 'import numpy as np\n'), ((10544, 10562), 'numpy.linalg.norm', 'np.linalg.norm', (['gk'], {}), '(gk)\n', (10558, 10562), True, 'import numpy as np\n'), ((11164, 11182), 'numpy.linalg.norm', 'np.linalg.norm', (['yk'], {}), '(yk)\n', (11178, 11182), True, 'import numpy as np\n'), ((11999, 12097), 'numpy.array', 'np.array', (['[200 * (x[1] - x[0] ** 2) * (-2 * x[0]) + 2 * (x[0] - 1), 200 * (x[1] - x[0\n ] ** 2)]'], {}), '([200 * (x[1] - x[0] ** 2) * (-2 * x[0]) + 2 * (x[0] - 1), 200 * (x\n [1] - x[0] ** 2)])\n', (12007, 12097), True, 'import numpy as np\n'), ((12227, 12264), 'numpy.mean', 'np.mean', (['(x ** 4 - 16 * x ** 2 + 5 * x)'], {}), '(x ** 4 - 16 * x ** 2 + 5 * x)\n', (12234, 12264), True, 'import numpy as np\n'), ((2112, 2130), 'numpy.linalg.norm', 'np.linalg.norm', (['gk'], {}), '(gk)\n', (2126, 2130), True, 'import numpy as np\n'), ((2866, 2884), 'numpy.linalg.norm', 'np.linalg.norm', (['gk'], {}), '(gk)\n', (2880, 2884), True, 'import numpy as np\n'), ((3697, 3713), 'numpy.outer', 'np.outer', (['sk', 'yk'], {}), '(sk, yk)\n', (3705, 3713), True, 'import numpy as np\n'), ((3716, 3732), 'numpy.inner', 'np.inner', (['sk', 'yk'], {}), '(sk, yk)\n', (3724, 3732), True, 'import numpy as np\n'), ((3767, 3783), 'numpy.outer', 'np.outer', (['sk', 'sk'], {}), '(sk, sk)\n', (3775, 3783), True, 'import numpy as np\n'), ((3786, 3802), 'numpy.inner', 'np.inner', (['sk', 'yk'], {}), '(sk, yk)\n', (3794, 3802), True, 'import numpy as np\n'), ((3854, 3872), 'numpy.linalg.norm', 'np.linalg.norm', (['gk'], {}), '(gk)\n', (3868, 3872), True, 'import numpy as np\n'), ((5557, 5575), 'numpy.linalg.norm', 'np.linalg.norm', (['gk'], {}), '(gk)\n', (5571, 5575), True, 'import numpy as np\n'), ((6664, 6673), 'numpy.eye', 'np.eye', (['k'], {}), '(k)\n', (6670, 6673), True, 'import numpy as np\n'), ((6866, 6884), 'numpy.array', 'np.array', (['sks[-n:]'], {}), '(sks[-n:])\n', (6874, 6884), True, 'import numpy as np\n'), ((6950, 6975), 'numpy.linalg.solve', 'np.linalg.solve', (['mat', 'rhs'], {}), '(mat, rhs)\n', (6965, 6975), True, 'import numpy as np\n'), ((7251, 7281), 'numpy.zeros', 'np.zeros', ([], {'shape': '(m + 1, m + 1)'}), '(shape=(m + 1, m + 1))\n', (7259, 7281), True, 'import numpy as np\n'), ((7484, 7508), 'numpy.zeros', 'np.zeros', ([], {'shape': '(m + 1,)'}), '(shape=(m + 1,))\n', (7492, 7508), True, 'import numpy as np\n'), ((7592, 7612), 'numpy.inner', 'np.inner', (['yk', 'sks[0]'], {}), '(yk, sks[0])\n', (7600, 7612), True, 'import numpy as np\n'), ((8735, 8751), 'numpy.inner', 'np.inner', (['v1', 'v2'], {}), '(v1, v2)\n', (8743, 8751), True, 'import numpy as np\n'), ((8754, 8770), 'numpy.inner', 'np.inner', (['v2', 'v2'], {}), '(v2, v2)\n', (8762, 8770), True, 'import numpy as np\n'), ((8795, 8811), 'numpy.inner', 'np.inner', (['v1', 'v2'], {}), '(v1, v2)\n', (8803, 8811), True, 'import numpy as np\n'), ((8814, 8830), 'numpy.inner', 'np.inner', (['v1', 'v1'], {}), '(v1, v1)\n', (8822, 8830), True, 'import numpy as np\n'), ((9788, 9805), 'numpy.zeros_like', 'np.zeros_like', (['xk'], {}), '(xk)\n', (9801, 9805), True, 'import numpy as np\n'), ((11624, 11642), 'numpy.linalg.norm', 'np.linalg.norm', (['gk'], {}), '(gk)\n', (11638, 11642), True, 'import numpy as np\n'), ((13790, 13809), 'numpy.ones', 'np.ones', ([], {'shape': '(n,)'}), '(shape=(n,))\n', (13797, 13809), True, 'import numpy as np\n'), ((13819, 13836), 'numpy.random.rand', 'np.random.rand', (['n'], {}), '(n)\n', (13833, 13836), True, 'import numpy as np\n'), ((2694, 2713), 'numpy.linalg.norm', 'np.linalg.norm', (['gk1'], {}), '(gk1)\n', (2708, 2713), True, 'import numpy as np\n'), ((3475, 3494), 'numpy.linalg.norm', 'np.linalg.norm', (['gk1'], {}), '(gk1)\n', (3489, 3494), True, 'import numpy as np\n'), ((5180, 5199), 'numpy.linalg.norm', 'np.linalg.norm', (['gk1'], {}), '(gk1)\n', (5194, 5199), True, 'import numpy as np\n'), ((6790, 6806), 'numpy.inner', 'np.inner', (['yk', 'sk'], {}), '(yk, sk)\n', (6798, 6806), True, 'import numpy as np\n'), ((7385, 7402), 'numpy.array', 'np.array', (['sks[1:]'], {}), '(sks[1:])\n', (7393, 7402), True, 'import numpy as np\n'), ((7439, 7456), 'numpy.array', 'np.array', (['sks[1:]'], {}), '(sks[1:])\n', (7447, 7456), True, 'import numpy as np\n'), ((7659, 7684), 'numpy.linalg.solve', 'np.linalg.solve', (['mat', 'rhs'], {}), '(mat, rhs)\n', (7674, 7684), True, 'import numpy as np\n'), ((7887, 7904), 'numpy.array', 'np.array', (['sks[1:]'], {}), '(sks[1:])\n', (7895, 7904), True, 'import numpy as np\n'), ((7949, 7966), 'numpy.array', 'np.array', (['sks[1:]'], {}), '(sks[1:])\n', (7957, 7966), True, 'import numpy as np\n'), ((8022, 8047), 'numpy.linalg.solve', 'np.linalg.solve', (['mat', 'rhs'], {}), '(mat, rhs)\n', (8037, 8047), True, 'import numpy as np\n'), ((8923, 8946), 'numpy.linalg.norm', 'np.linalg.norm', (['orth_v1'], {}), '(orth_v1)\n', (8937, 8946), True, 'import numpy as np\n'), ((8964, 8987), 'numpy.linalg.norm', 'np.linalg.norm', (['orth_v2'], {}), '(orth_v2)\n', (8978, 8987), True, 'import numpy as np\n'), ((10457, 10473), 'numpy.inner', 'np.inner', (['sk', 'yk'], {}), '(sk, yk)\n', (10465, 10473), True, 'import numpy as np\n'), ((10617, 10630), 'numpy.array', 'np.array', (['sks'], {}), '(sks)\n', (10625, 10630), True, 'import numpy as np\n'), ((10642, 10655), 'numpy.array', 'np.array', (['sks'], {}), '(sks)\n', (10650, 10655), True, 'import numpy as np\n'), ((11113, 11132), 'numpy.linalg.norm', 'np.linalg.norm', (['gk1'], {}), '(gk1)\n', (11127, 11132), True, 'import numpy as np\n'), ((11448, 11464), 'numpy.inner', 'np.inner', (['sk', 'yk'], {}), '(sk, yk)\n', (11456, 11464), True, 'import numpy as np\n'), ((6601, 6617), 'numpy.inner', 'np.inner', (['yk', 'sk'], {}), '(yk, sk)\n', (6609, 6617), True, 'import numpy as np\n'), ((7314, 7331), 'numpy.array', 'np.array', (['sks[1:]'], {}), '(sks[1:])\n', (7322, 7331), True, 'import numpy as np\n'), ((7334, 7351), 'numpy.array', 'np.array', (['sks[1:]'], {}), '(sks[1:])\n', (7342, 7351), True, 'import numpy as np\n'), ((7539, 7556), 'numpy.array', 'np.array', (['sks[1:]'], {}), '(sks[1:])\n', (7547, 7556), True, 'import numpy as np\n'), ((7907, 7924), 'numpy.array', 'np.array', (['sks[1:]'], {}), '(sks[1:])\n', (7915, 7924), True, 'import numpy as np\n'), ((11395, 11411), 'numpy.inner', 'np.inner', (['sk', 'yk'], {}), '(sk, yk)\n', (11403, 11411), True, 'import numpy as np\n')]
import os import pickle import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from scipy.io import loadmat from torch import optim from torch.autograd import Variable from torch.optim.lr_scheduler import StepLR from torchvision import models from datasets import LOG_PARA, load_datasets # Seed for reproducibility SEED = 3035 if SEED is not None: np.random.seed(SEED) torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) # Nombre de archivo para guardar resultados SAVE_FILENAME = 'CANNet_Prueba.pickle' MODEL_FILENAME = 'CANNet_Prueba.pth' # Para comprobar si tenemos GPUs disponibles para usar o no: use_cuda = torch.cuda.is_available() device = torch.device("cuda" if use_cuda else "cpu") train_loader, val_loader, test_loader, restore_transform = load_datasets() #RED class ContextualModule(nn.Module): def __init__(self, features, out_features=512, sizes=(1, 2, 3, 6)): super(ContextualModule, self).__init__() self.scales = [] self.scales = nn.ModuleList([self._make_scale(features, size) for size in sizes]) self.bottleneck = nn.Conv2d(features * 2, out_features, kernel_size=1) self.relu = nn.ReLU() self.weight_net = nn.Conv2d(features,features,kernel_size=1) def __make_weight(self,feature,scale_feature): weight_feature = feature - scale_feature return F.sigmoid(self.weight_net(weight_feature)) def _make_scale(self, features, size): prior = nn.AdaptiveAvgPool2d(output_size=(size, size)) conv = nn.Conv2d(features, features, kernel_size=1, bias=False) return nn.Sequential(prior, conv) def forward(self, feats): h, w = feats.size(2), feats.size(3) multi_scales = [F.upsample(input=stage(feats), size=(h, w), mode='bilinear') for stage in self.scales] weights = [self.__make_weight(feats,scale_feature) for scale_feature in multi_scales] overall_features = [(multi_scales[0]*weights[0]+multi_scales[1]*weights[1]+multi_scales[2]*weights[2]+multi_scales[3]*weights[3])/(weights[0]+weights[1]+weights[2]+weights[3])]+ [feats] bottle = self.bottleneck(torch.cat(overall_features, 1)) return self.relu(bottle) class CANNet(nn.Module): def __init__(self, load_weights=False): super(CANNet, self).__init__() self.seen = 0 self.context = ContextualModule(512, 512) self.frontend_feat = [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512] self.backend_feat = [512, 512, 512,256,128,64] self.frontend = make_layers(self.frontend_feat) self.backend = make_layers(self.backend_feat,in_channels = 512,batch_norm=True, dilation = True) self.output_layer = nn.Conv2d(64, 1, kernel_size=1) if not load_weights: mod = models.vgg16(pretrained = True) self._initialize_weights() self.frontend.load_state_dict(mod.features[0:23].state_dict()) # for i in range(len(self.frontend.state_dict().items())): # self.frontend.state_dict().items()[i][1].data[:] = mod.state_dict().items()[i][1].data[:] def forward(self,x): x = self.frontend(x) x = self.context(x) x = self.backend(x) x = self.output_layer(x) x = F.upsample(x, scale_factor=8) return x def _initialize_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.normal_(m.weight, std=0.01) if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def make_layers(cfg, in_channels = 3,batch_norm=False,dilation = False): if dilation: d_rate = 2 else: d_rate = 1 layers = [] for v in cfg: if v == 'M': layers += [nn.MaxPool2d(kernel_size=2, stride=2)] else: conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=d_rate,dilation = d_rate) if batch_norm: layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] else: layers += [conv2d, nn.ReLU(inplace=True)] in_channels = v return nn.Sequential(*layers) modelo = CANNet() modelo = modelo.to(device) #pytorch_total_params = sum(p.numel() for p in modelo.parameters()) #print(pytorch_total_params) # Definimos el criterion de pérdida: criterion = nn.MSELoss().to(device) # criterion = nn.L1Loss(reduction='mean') # convertimos train_loader en un iterador # dataiter = iter(train_loader) # y recuperamos el i-esimo elemento, un par de valores (imagenes, etiquetas) # x, y = dataiter.next() # x e y son tensores # Para predecir y, la normalizaremos. Siempre por el mismo valor: #Y_NORM = 200 # UPDATE: Ahora se normaliza en dataset.py con LOG_PARA losses = {'train': list(), 'validacion': list(), 'val_mae': list(), 'val_mse': list()} # PRUEBAS: # print(x.size()) # print(y['map'].size()) # print(torch.max(x)) # print(x) # Parámetros (de la configuracion original) LR = 1e-5 LR_DECAY = 0.99 NUM_EPOCH_LR_DECAY = 1 LR_DECAY_START = -1 # ENTRENAMIENTO 1 n_epochs = 200 optimizador = optim.Adam(modelo.parameters(), lr=LR, weight_decay=1e-4) scheduler = StepLR(optimizador, step_size=NUM_EPOCH_LR_DECAY, gamma=LR_DECAY) train_record = {'best_mae': float('Inf'), 'best_mse': float('Inf')} # Para early stopping: guarda el modelo si mejora en acumulados, para si se sobrepasa MAX_ACCUM MAX_ACCUM = 100 accum = 0 for epoch in range(n_epochs): print("Entrenando... \n") # Esta será la parte de entrenamiento training_loss = 0.0 # el loss en cada epoch de entrenamiento total_iter = 0 modelo.train() # Para preparar el modelo para el training for x, y in train_loader: x = x.to(device) y = y.to(device) total_iter += 1 # como estamos usando el total, auemntamos 1 y.shape[0] # ponemos a cero todos los gradientes en todas las neuronas: optimizador.zero_grad() pred_map = modelo(x) # forward loss = criterion(pred_map.squeeze(), y.squeeze()) # evaluación del loss loss.backward() # backward pass optimizador.step() # optimización training_loss += loss.data.cpu().item() # acumulamos el loss de este batch training_loss /= total_iter lr_computed = optimizador.param_groups[0]['lr']*10000 orig_count = y[0].sum().data/LOG_PARA pred_count = pred_map[0].sum().data/LOG_PARA print( f'[ep {epoch}][loss {training_loss:.4f}][lr {lr_computed:.4f}][cnt: den: {orig_count:.1f} pred: {pred_count:.1f}]') losses['train'].append(training_loss) # .item()) # Para iniciar el scheduler (siempre tras optimizer.step()) if epoch > LR_DECAY_START: scheduler.step() val_loss = 0.0 mae_accum = 0.0 mse_accum = 0.0 total_iter = 0 total = 0 modelo.eval() # Preparar el modelo para validación y/o test print("Validando... \n") for x, y in val_loader: x = x.to(device) y = y.to(device) total_iter += 1 with torch.no_grad(): # y = y/Y_NORM # normalizamoss pred_map = modelo(x) #output = output.flatten() loss = criterion(pred_map.squeeze(), y.squeeze()) val_loss += loss.cpu().item() for i_img in range(pred_map.shape[0]): pred_num = pred_map[i_img].sum().data/LOG_PARA y_num = y[i_img].sum().data/LOG_PARA mae_accum += abs(y_num-pred_num) mse_accum += (pred_num-y_num)*(pred_num-y_num) total += 1 val_loss /= total mae_accum /= total_iter mse_accum = torch.sqrt(mse_accum/total_iter) losses['validacion'].append(val_loss) # .item()) losses['val_mae'].append(mae_accum) # .item()) losses['val_mse'].append(mse_accum) # .item()) print( f'[e {epoch}] \t Train: {training_loss:.4f} \t Val_loss: {val_loss:.4f}, MAE: {mae_accum:.2f}, MSE: {mse_accum:.2f}') # EARLY STOPPING if (mae_accum <= train_record['best_mae']) or (mse_accum <= train_record['best_mse']): print(f'Saving model...') torch.save(modelo, MODEL_FILENAME) accum = 0 if mae_accum <= train_record['best_mae']: print(f'MAE: ({mae_accum:.2f}<{train_record["best_mae"]:.2f})') train_record['best_mae'] = mae_accum if mse_accum <= train_record['best_mse']: print(f'MSE: ({mse_accum:.2f}<{train_record["best_mse"]:.2f})') train_record['best_mse'] = mse_accum else: accum += 1 if accum>MAX_ACCUM: break with open(SAVE_FILENAME, 'wb') as handle: pickle.dump(losses, handle, protocol=pickle.HIGHEST_PROTOCOL) ''' # ENTRENAMIENTO 2 n_epochs = 130 optimizador = optim.SGD(modelo.parameters(), lr=0.0001) for epoch in range(n_epochs): print("Entrenando... \n") # Esta será la parte de entrenamiento training_loss = 0.0 # el loss en cada epoch de entrenamiento total = 0 modelo.train() # Para preparar el modelo para el training for x, y in train_loader: # ponemos a cero todos los gradientes en todas las neuronas: optimizador.zero_grad() # y=y/Y_NORM #normalizamos x = x.to(device) y = y.to(device) total += y.shape[0] output = modelo(x) # forward loss = criterion(output, y) # evaluación del loss loss.backward() # backward pass optimizador.step() # optimización training_loss += loss.cpu().item() # acumulamos el loss de este batch training_loss /= total losses['train'].append(training_loss) # .item()) val_loss = 0.0 total = 0 modelo.eval() # Preparar el modelo para validación y/o test print("Validando... \n") for x, y in val_loader: # y = y/Y_NORM # normalizamos x = x.to(device) y = y.to(device) total += y.shape[0] output = modelo(x) #output = output.flatten() loss = criterion(output, y) val_loss += loss.cpu().item() val_loss /= total losses['validacion'].append(val_loss) # .item()) print( f'Epoch {epoch} \t\t Training Loss: {training_loss} \t\t Validation Loss: {val_loss}') with open(SAVE_FILENAME, 'wb') as handle: pickle.dump(losses, handle, protocol=pickle.HIGHEST_PROTOCOL) ''' # TEST modelo.eval() # Preparar el modelo para validación y/o test print("Testing... \n") # definimos la pérdida total_iter = 0 total = 0 mse = nn.MSELoss() test_loss = 0.0 test_loss_mse = 0.0 test_loss_mae = 0.0 yreal = list() ypredicha = list() with torch.no_grad(): for x, y in test_loader: # y=y/Y_NORM #normalizamos x = x.to(device) y = y.to(device) total_iter += 1 pred_map = modelo(x) #output = output.flatten() loss = mse(pred_map.squeeze(), y.squeeze()) test_loss += loss.cpu().item() for i_img in range(pred_map.shape[0]): pred_num = pred_map[i_img].sum().data/LOG_PARA y_num = y[i_img].sum().data/LOG_PARA test_loss_mae += abs(y_num-pred_num) test_loss_mse += (pred_num-y_num)*(pred_num-y_num) total += 1 output_num = pred_map.data.cpu().sum()/LOG_PARA y_num = y.sum()/LOG_PARA test_loss_mae += abs(output_num - y_num) test_loss_mse += (output_num-y_num)**2 # para guardar las etqieutas. yreal.append(y.data.cpu().numpy()) ypredicha.append(pred_map.data.cpu().numpy()) test_loss /= total test_loss_mae /= total_iter test_loss_mse = torch.sqrt(test_loss_mse/total_iter) # yreal = np.array(yreal).flatten() # ypredicha = np.array(ypredicha).flatten() # comprobar si funciona. losses['yreal'] = yreal losses['ypredicha'] = ypredicha print(f'Test Loss (MSE): {test_loss_mse}') losses['test_mse'] = test_loss_mse # .item()) print(f'Test Loss (MAE): {test_loss_mae}') losses['test_mae'] = test_loss_mae # .item()) with open(SAVE_FILENAME, 'wb') as handle: pickle.dump(losses, handle, protocol=pickle.HIGHEST_PROTOCOL) #%% VISUALIZATION # fig, ax = plt.subplots(2, 1, figsize=(30,10)) # img_orig = x.data.cpu().numpy().squeeze().transpose((1,2,0)) # img_orig = (img_orig-img_orig.min())/(img_orig.max()-img_orig.min()) # ax[0].imshow(img_orig) # ax[1].imshow(y.data.cpu().numpy().squeeze())
[ "pickle.dump", "torch.optim.lr_scheduler.StepLR", "numpy.random.seed", "torch.sqrt", "torch.cat", "torch.nn.init.constant_", "torch.device", "torch.no_grad", "torch.nn.MSELoss", "torchvision.models.vgg16", "torch.manual_seed", "torch.nn.Conv2d", "torch.cuda.manual_seed", "torch.nn.functional.upsample", "torch.nn.BatchNorm2d", "torch.cuda.is_available", "datasets.load_datasets", "torch.nn.MaxPool2d", "torch.nn.AdaptiveAvgPool2d", "torch.nn.ReLU", "torch.nn.Sequential", "torch.save", "torch.nn.init.normal_" ]
[((694, 719), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (717, 719), False, 'import torch\n'), ((729, 772), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (741, 772), False, 'import torch\n'), ((833, 848), 'datasets.load_datasets', 'load_datasets', ([], {}), '()\n', (846, 848), False, 'from datasets import LOG_PARA, load_datasets\n'), ((5403, 5468), 'torch.optim.lr_scheduler.StepLR', 'StepLR', (['optimizador'], {'step_size': 'NUM_EPOCH_LR_DECAY', 'gamma': 'LR_DECAY'}), '(optimizador, step_size=NUM_EPOCH_LR_DECAY, gamma=LR_DECAY)\n', (5409, 5468), False, 'from torch.optim.lr_scheduler import StepLR\n'), ((10743, 10755), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (10753, 10755), True, 'import torch.nn as nn\n'), ((11843, 11881), 'torch.sqrt', 'torch.sqrt', (['(test_loss_mse / total_iter)'], {}), '(test_loss_mse / total_iter)\n', (11853, 11881), False, 'import torch\n'), ((418, 438), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (432, 438), True, 'import numpy as np\n'), ((443, 466), 'torch.manual_seed', 'torch.manual_seed', (['SEED'], {}), '(SEED)\n', (460, 466), False, 'import torch\n'), ((471, 499), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['SEED'], {}), '(SEED)\n', (493, 499), False, 'import torch\n'), ((4360, 4382), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (4373, 4382), True, 'import torch.nn as nn\n'), ((7869, 7903), 'torch.sqrt', 'torch.sqrt', (['(mse_accum / total_iter)'], {}), '(mse_accum / total_iter)\n', (7879, 7903), False, 'import torch\n'), ((10853, 10868), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10866, 10868), False, 'import torch\n'), ((12271, 12332), 'pickle.dump', 'pickle.dump', (['losses', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(losses, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (12282, 12332), False, 'import pickle\n'), ((1153, 1205), 'torch.nn.Conv2d', 'nn.Conv2d', (['(features * 2)', 'out_features'], {'kernel_size': '(1)'}), '(features * 2, out_features, kernel_size=1)\n', (1162, 1205), True, 'import torch.nn as nn\n'), ((1226, 1235), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1233, 1235), True, 'import torch.nn as nn\n'), ((1262, 1306), 'torch.nn.Conv2d', 'nn.Conv2d', (['features', 'features'], {'kernel_size': '(1)'}), '(features, features, kernel_size=1)\n', (1271, 1306), True, 'import torch.nn as nn\n'), ((1524, 1570), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', ([], {'output_size': '(size, size)'}), '(output_size=(size, size))\n', (1544, 1570), True, 'import torch.nn as nn\n'), ((1586, 1642), 'torch.nn.Conv2d', 'nn.Conv2d', (['features', 'features'], {'kernel_size': '(1)', 'bias': '(False)'}), '(features, features, kernel_size=1, bias=False)\n', (1595, 1642), True, 'import torch.nn as nn\n'), ((1658, 1684), 'torch.nn.Sequential', 'nn.Sequential', (['prior', 'conv'], {}), '(prior, conv)\n', (1671, 1684), True, 'import torch.nn as nn\n'), ((2777, 2808), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', '(1)'], {'kernel_size': '(1)'}), '(64, 1, kernel_size=1)\n', (2786, 2808), True, 'import torch.nn as nn\n'), ((3337, 3366), 'torch.nn.functional.upsample', 'F.upsample', (['x'], {'scale_factor': '(8)'}), '(x, scale_factor=8)\n', (3347, 3366), True, 'import torch.nn.functional as F\n'), ((4579, 4591), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (4589, 4591), True, 'import torch.nn as nn\n'), ((8353, 8387), 'torch.save', 'torch.save', (['modelo', 'MODEL_FILENAME'], {}), '(modelo, MODEL_FILENAME)\n', (8363, 8387), False, 'import torch\n'), ((8889, 8950), 'pickle.dump', 'pickle.dump', (['losses', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(losses, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (8900, 8950), False, 'import pickle\n'), ((2192, 2222), 'torch.cat', 'torch.cat', (['overall_features', '(1)'], {}), '(overall_features, 1)\n', (2201, 2222), False, 'import torch\n'), ((2856, 2885), 'torchvision.models.vgg16', 'models.vgg16', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (2868, 2885), False, 'from torchvision import models\n'), ((4066, 4139), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'v'], {'kernel_size': '(3)', 'padding': 'd_rate', 'dilation': 'd_rate'}), '(in_channels, v, kernel_size=3, padding=d_rate, dilation=d_rate)\n', (4075, 4139), True, 'import torch.nn as nn\n'), ((7258, 7273), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7271, 7273), False, 'import torch\n'), ((3510, 3545), 'torch.nn.init.normal_', 'nn.init.normal_', (['m.weight'], {'std': '(0.01)'}), '(m.weight, std=0.01)\n', (3525, 3545), True, 'import torch.nn as nn\n'), ((3992, 4029), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)'}), '(kernel_size=2, stride=2)\n', (4004, 4029), True, 'import torch.nn as nn\n'), ((3605, 3633), 'torch.nn.init.constant_', 'nn.init.constant_', (['m.bias', '(0)'], {}), '(m.bias, 0)\n', (3622, 3633), True, 'import torch.nn as nn\n'), ((3698, 3728), 'torch.nn.init.constant_', 'nn.init.constant_', (['m.weight', '(1)'], {}), '(m.weight, 1)\n', (3715, 3728), True, 'import torch.nn as nn\n'), ((3745, 3773), 'torch.nn.init.constant_', 'nn.init.constant_', (['m.bias', '(0)'], {}), '(m.bias, 0)\n', (3762, 3773), True, 'import torch.nn as nn\n'), ((4203, 4220), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['v'], {}), '(v)\n', (4217, 4220), True, 'import torch.nn as nn\n'), ((4222, 4243), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4229, 4243), True, 'import torch.nn as nn\n'), ((4298, 4319), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4305, 4319), True, 'import torch.nn as nn\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # signals.py - <NAME> (<EMAIL>) - Jan 2017 ''' Contains functions to deal with masking and removing periodic signals in light curves. ''' ############# ## LOGGING ## ############# import logging from astrobase import log_sub, log_fmt, log_date_fmt DEBUG = False if DEBUG: level = logging.DEBUG else: level = logging.INFO LOGGER = logging.getLogger(__name__) logging.basicConfig( level=level, style=log_sub, format=log_fmt, datefmt=log_date_fmt, ) LOGDEBUG = LOGGER.debug LOGINFO = LOGGER.info LOGWARNING = LOGGER.warning LOGERROR = LOGGER.error LOGEXCEPTION = LOGGER.exception ############# ## IMPORTS ## ############# import os.path import os from io import BytesIO as Strio import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt ################### ## LOCAL IMPORTS ## ################### from ..periodbase.zgls import pgen_lsp from ..lcfit.sinusoidal import _fourier_func, fourier_fit_magseries from ..lcmath import sigclip_magseries, phase_magseries ################################################ ## REMOVING SIGNALS FROM MAGNITUDE TIMESERIES ## ################################################ def prewhiten_magseries(times, mags, errs, whitenperiod, whitenparams, sigclip=3.0, magsarefluxes=False, plotfit=None, plotfitphasedlconly=True, rescaletomedian=True): '''Removes a periodic sinusoidal signal generated using whitenparams from the input magnitude time series. Parameters ---------- times,mags,errs : np.array The input mag/flux time-series to prewhiten. whitenperiod : float The period of the sinusoidal signal to remove. whitenparams : list of floats This contains the Fourier amplitude and phase coefficients of the sinusoidal signal to remove:: [ampl_1, ampl_2, ampl_3, ..., ampl_X, pha_1, pha_2, pha_3, ..., pha_X] where `X` is the Fourier order. These are usually the output of a previous Fourier fit to the light curve (from :py:func:`astrobase.lcfit.sinusoidal.fourier_fit_magseries` for example). sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. magsarefluxes : bool If True, will treat the input values of `mags` as fluxes for purposes of plotting the fit and sig-clipping. plotfit : str or False If this is a string, this function will make a plot showing the effect of the pre-whitening on the mag/flux time-series and write the plot to the path specified here. plotfitphasedlconly : bool If True, will plot only the phased LC for showing the effect of pre-whitening, and skip plotting the unphased LC. rescaletomedian : bool If this is True, then we add back the constant median term of the magnitudes to the final pre-whitened mag series. Returns ------- dict Returns a dict of the form:: {'wtimes':times array after pre-whitening, 'wphase':phase array after pre-whitening, 'wmags':mags array after pre-whitening, 'werrs':errs array after pre-whitening, 'whitenparams':the input pre-whitening params used, 'whitenperiod':the input pre-whitening period used, 'fitplotfile':the output plot file if plotfit was set} ''' stimes, smags, serrs = sigclip_magseries(times, mags, errs, sigclip=sigclip, magsarefluxes=magsarefluxes) median_mag = np.median(smags) # phase the mag series using the given period and epoch = min(stimes) mintime = np.min(stimes) # calculate the unsorted phase, then sort it iphase = ( (stimes - mintime)/whitenperiod - np.floor((stimes - mintime)/whitenperiod) ) phasesortind = np.argsort(iphase) # these are the final quantities to use for the Fourier fits phase = iphase[phasesortind] pmags = smags[phasesortind] perrs = serrs[phasesortind] # get the times sorted in phase order (useful to get the fit mag minimum # with respect to phase -- the light curve minimum) ptimes = stimes[phasesortind] # now subtract the harmonic series from the phased LC # these are still in phase order wmags = pmags - _fourier_func(whitenparams, phase, pmags) # resort everything by time order wtimeorder = np.argsort(ptimes) wtimes = ptimes[wtimeorder] wphase = phase[wtimeorder] wmags = wmags[wtimeorder] werrs = perrs[wtimeorder] if rescaletomedian: wmags = wmags + median_mag # prepare the returndict returndict = {'wtimes':wtimes, # these are in the new time order 'wphase':wphase, 'wmags':wmags, 'werrs':werrs, 'whitenparams':whitenparams, 'whitenperiod':whitenperiod} # make the fit plot if required if plotfit and (isinstance(plotfit, str) or isinstance(plotfit, Strio)): if plotfitphasedlconly: plt.figure(figsize=(10,4.8)) else: plt.figure(figsize=(16,9.6)) if plotfitphasedlconly: # phased series before whitening plt.subplot(121) plt.plot(phase,pmags, marker='.', color='k', linestyle='None', markersize=2.0, markeredgewidth=0) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('fluxes') plt.xlabel('phase') plt.title('phased LC before pre-whitening') # phased series after whitening plt.subplot(122) plt.plot(wphase,wmags, marker='.', color='g', linestyle='None', markersize=2.0, markeredgewidth=0) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('fluxes') plt.xlabel('phase') plt.title('phased LC after pre-whitening') else: # time series before whitening plt.subplot(221) plt.plot(stimes,smags, marker='.', color='k', linestyle='None', markersize=2.0, markeredgewidth=0) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('fluxes') plt.xlabel('JD') plt.title('LC before pre-whitening') # time series after whitening plt.subplot(222) plt.plot(wtimes,wmags, marker='.', color='g', linestyle='None', markersize=2.0, markeredgewidth=0) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('fluxes') plt.xlabel('JD') plt.title('LC after pre-whitening with period: %.6f' % whitenperiod) # phased series before whitening plt.subplot(223) plt.plot(phase,pmags, marker='.', color='k', linestyle='None', markersize=2.0, markeredgewidth=0) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('fluxes') plt.xlabel('phase') plt.title('phased LC before pre-whitening') # phased series after whitening plt.subplot(224) plt.plot(wphase,wmags, marker='.', color='g', linestyle='None', markersize=2.0, markeredgewidth=0) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('fluxes') plt.xlabel('phase') plt.title('phased LC after pre-whitening') plt.tight_layout() plt.savefig(plotfit, format='png', pad_inches=0.0) plt.close() if isinstance(plotfit, str) or isinstance(plotfit, Strio): returndict['fitplotfile'] = plotfit return returndict def gls_prewhiten(times, mags, errs, fourierorder=3, # 3rd order series to start with initfparams=None, startp_gls=None, endp_gls=None, stepsize=1.0e-4, autofreq=True, sigclip=30.0, magsarefluxes=False, nbestpeaks=5, nworkers=4, plotfits=None): '''Iterative pre-whitening of a magnitude series using the L-S periodogram. This finds the best period, fits a fourier series with the best period, then whitens the time series with the best period, and repeats until `nbestpeaks` are done. Parameters ---------- times,mags,errs : np.array The input mag/flux time-series to iteratively pre-whiten. fourierorder : int The Fourier order of the sinusoidal signal to fit to the time-series and iteratively remove. initfparams : list or None If this is provided, should be a list of Fourier amplitudes and phases in the following format:: [ampl_1, ampl_2, ampl_3, ..., ampl_X, pha_1, pha_2, pha_3, ..., pha_X] where `X` is the Fourier order. These are usually the output of a previous Fourier fit to the light curve (from :py:func:`astrobase.lcfit.sinusoidal.fourier_fit_magseries` for example). You MUST provide ONE of `fourierorder` and `initfparams`, but not both. If both are provided or both are None, a sinusoidal signal of Fourier order 3 will be used by default. startp_gls, endp_gls : float or None If these are provided, will serve as input to the Generalized Lomb-Scargle function that will attempt to find the best `nbestpeaks` periods in the time-series. These set the minimum and maximum period to search for in the time-series. stepsize : float The step-size in frequency to use when constructing a frequency grid for the period search. autofreq : bool If this is True, the value of `stepsize` will be ignored and the :py:func:`astrobase.periodbase.get_frequency_grid` function will be used to generate a frequency grid based on `startp`, and `endp`. If these are None as well, `startp` will be set to 0.1 and `endp` will be set to `times.max() - times.min()`. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. magsarefluxes : bool If the input measurement values in `mags` and `errs` are in fluxes, set this to True. nbestpeaks : int The number of 'best' peaks to return from the periodogram results, starting from the global maximum of the periodogram peak values. nworkers : int The number of parallel workers to use when calculating the periodogram. plotfits : None or str If this is a str, should indicate the file to which a plot of the successive iterations of pre-whitening will be written to. This will contain a row of plots indicating the before/after states of the light curves for each round of pre-whitening. Returns ------- (bestperiods, plotfile) : tuple This returns a list of the best periods (with the "highest" peak in the periodogram) after each round of pre-whitening is done. If plotfit is a str, will also return the path to the generated plot file. ''' stimes, smags, serrs = sigclip_magseries(times, mags, errs, sigclip=sigclip, magsarefluxes=magsarefluxes) # now start the cycle by doing an GLS on the initial timeseries gls = pgen_lsp(stimes, smags, serrs, magsarefluxes=magsarefluxes, startp=startp_gls, endp=endp_gls, autofreq=autofreq, sigclip=sigclip, stepsize=stepsize, nworkers=nworkers) LOGINFO('round %s: period = %.6f' % (0, gls['bestperiod'])) if plotfits and isinstance(plotfits, str): plt.figure(figsize=(20,6*nbestpeaks)) nplots = nbestpeaks + 1 # periodogram plt.subplot(nplots,3,1) plt.plot(gls['periods'],gls['lspvals']) plt.xlabel('period [days]') plt.ylabel('GLS power') plt.xscale('log') plt.title('round 0, best period = %.6f' % gls['bestperiod']) # unphased LC plt.subplot(nplots,3,2) plt.plot(stimes, smags, linestyle='none', marker='o',ms=1.0,rasterized=True) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('flux') plt.xlabel('JD') plt.title('unphased LC before whitening') # phased LC plt.subplot(nplots,3,3) phased = phase_magseries(stimes, smags, gls['bestperiod'], stimes.min()) plt.plot(phased['phase'], phased['mags'], linestyle='none', marker='o',ms=1.0,rasterized=True) if not magsarefluxes: plt.ylabel('magnitude') plt.gca().invert_yaxis() else: plt.ylabel('flux') plt.xlabel('phase') plt.title('phased LC before whitening: P = %.6f' % gls['bestperiod']) # set up the initial times, mags, errs, period wtimes, wmags, werrs = stimes, smags, serrs wperiod = gls['bestperiod'] # start the best periods list bestperiods = [] # now go through the rest of the cycles for fitind in range(nbestpeaks): wfseries = fourier_fit_magseries(wtimes, wmags, werrs, wperiod, fourierorder=fourierorder, fourierparams=initfparams, magsarefluxes=magsarefluxes, sigclip=sigclip) wffitparams = wfseries['fitinfo']['finalparams'] wseries = prewhiten_magseries(wtimes, wmags, werrs, wperiod, wffitparams, magsarefluxes=magsarefluxes, sigclip=sigclip) LOGINFO('round %s: period = %.6f' % (fitind+1, wperiod)) bestperiods.append(wperiod) # update the mag series with whitened version wtimes, wmags, werrs = ( wseries['wtimes'], wseries['wmags'], wseries['werrs'] ) # redo the periodogram wgls = pgen_lsp(wtimes, wmags, werrs, magsarefluxes=magsarefluxes, startp=startp_gls, endp=endp_gls, autofreq=autofreq, sigclip=sigclip, stepsize=stepsize, nworkers=nworkers) wperiod = wgls['bestperiod'] bestperiods.append(wperiod) # make plots if requested if plotfits and isinstance(plotfits, str): # periodogram plt.subplot(nplots,3,4+fitind*3) plt.plot(wgls['periods'],wgls['lspvals']) plt.xlabel('period [days]') plt.ylabel('LSP power') plt.xscale('log') plt.title('round %s, best period = %.6f' % (fitind+1, wgls['bestperiod'])) # unphased LC plt.subplot(nplots,3,5+fitind*3) plt.plot(wtimes, wmags, linestyle='none', marker='o',ms=1.0,rasterized=True) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('flux') plt.xlabel('JD') plt.title('unphased LC after whitening') # phased LC plt.subplot(nplots,3,6+fitind*3) wphased = phase_magseries(wtimes, wmags, wperiod, stimes.min()) plt.plot(wphased['phase'], wphased['mags'], linestyle='none', marker='o',ms=1.0,rasterized=True) if not magsarefluxes: plt.ylabel('magnitude') plt.gca().invert_yaxis() else: plt.ylabel('flux') plt.xlabel('phase') plt.title('phased LC after whitening: P = %.6f' % wperiod) # in the end, write out the plot if plotfits and isinstance(plotfits, str): plt.subplots_adjust(hspace=0.2,wspace=0.4) plt.savefig(plotfits, bbox_inches='tight') plt.close('all') return bestperiods, os.path.abspath(plotfits) else: return bestperiods def mask_signal(times, mags, errs, signalperiod, signalepoch, magsarefluxes=False, maskphases=(0,0,0.5,1.0), maskphaselength=0.1, plotfit=None, plotfitphasedlconly=True, sigclip=30.0): '''This removes repeating signals in the magnitude time series. Useful for masking planetary transit signals in light curves to search for other variability. A small worked example of using this and `prewhiten_magseries` above: https://github.com/waqasbhatti/astrobase/issues/77#issuecomment-463803558 Parameters ---------- times,mags,errs : np.array The input mag/flux time-series to run the masking on. signalperiod : float The period of the signal to mask. signalepoch : float The epoch of the signal to mask. magsarefluxes : bool Set to True if `mags` is actually an array of fluxes. maskphases : sequence of floats This defines which phase values will be masked. For each item in this sequence, this function will mask a length of phase given by `maskphaselength` centered on each `maskphases` value, and remove all LC points in these regions from the light curve. maskphaselength : float The length in phase to mask for each phase value provided in `maskphases`. plotfit : str or None If provided as a str, indicates the output plot file. plotfitphasedlconly : bool If True, will only plot the effect of masking the signal as requested on the phased LC. If False, will also plot the unphased LC. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. ''' stimes, smags, serrs = sigclip_magseries(times, mags, errs, sigclip=sigclip, magsarefluxes=magsarefluxes) # now phase the light curve using the period and epoch provided phases = ( (stimes - signalepoch)/signalperiod - np.floor((stimes - signalepoch)/signalperiod) ) # mask the requested phases using the mask length (in phase units) # this gets all the masks into one array masks = np.array([(np.abs(phases - x) > maskphaselength) for x in maskphases]) # this flattens the masks to a single array for all combinations masks = np.all(masks,axis=0) # apply the mask to the times, mags, and errs mphases = phases[masks] mtimes = stimes[masks] mmags = smags[masks] merrs = serrs[masks] returndict = {'mphases':mphases, 'mtimes':mtimes, 'mmags':mmags, 'merrs':merrs} # make the fit plot if required if plotfit and isinstance(plotfit, str) or isinstance(plotfit, Strio): if plotfitphasedlconly: plt.figure(figsize=(10,4.8)) else: plt.figure(figsize=(16,9.6)) if plotfitphasedlconly: # phased series before whitening plt.subplot(121) plt.plot(phases,smags, marker='.', color='k', linestyle='None', markersize=2.0, markeredgewidth=0) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('fluxes') plt.xlabel('phase') plt.title('phased LC before signal masking') # phased series after whitening plt.subplot(122) plt.plot(mphases,mmags, marker='.', color='g', linestyle='None', markersize=2.0, markeredgewidth=0) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('fluxes') plt.xlabel('phase') plt.title('phased LC after signal masking') else: # time series before whitening plt.subplot(221) plt.plot(stimes,smags, marker='.', color='k', linestyle='None', markersize=2.0, markeredgewidth=0) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('fluxes') plt.xlabel('JD') plt.title('LC before signal masking') # time series after whitening plt.subplot(222) plt.plot(mtimes,mmags, marker='.', color='g', linestyle='None', markersize=2.0, markeredgewidth=0) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('fluxes') plt.xlabel('JD') plt.title('LC after signal masking') # phased series before whitening plt.subplot(223) plt.plot(phases,smags, marker='.', color='k', linestyle='None', markersize=2.0, markeredgewidth=0) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('fluxes') plt.xlabel('phase') plt.title('phased LC before signal masking') # phased series after whitening plt.subplot(224) plt.plot(mphases,mmags, marker='.', color='g', linestyle='None', markersize=2.0, markeredgewidth=0) if not magsarefluxes: plt.gca().invert_yaxis() plt.ylabel('magnitude') else: plt.ylabel('fluxes') plt.xlabel('phase') plt.title('phased LC after signal masking') plt.tight_layout() plt.savefig(plotfit, format='png', pad_inches=0.0) plt.close() if isinstance(plotfit, str) or isinstance(plotfit, Strio): returndict['fitplotfile'] = plotfit return returndict
[ "matplotlib.pyplot.title", "numpy.abs", "numpy.floor", "logging.getLogger", "numpy.argsort", "matplotlib.pyplot.figure", "matplotlib.pyplot.gca", "matplotlib.pyplot.tight_layout", "os.path.abspath", "matplotlib.pyplot.close", "numpy.median", "numpy.min", "matplotlib.use", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.ylabel", "numpy.all", "matplotlib.pyplot.xscale", "matplotlib.pyplot.subplot", "logging.basicConfig", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig" ]
[((390, 417), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (407, 417), False, 'import logging\n'), ((418, 508), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'level', 'style': 'log_sub', 'format': 'log_fmt', 'datefmt': 'log_date_fmt'}), '(level=level, style=log_sub, format=log_fmt, datefmt=\n log_date_fmt)\n', (437, 508), False, 'import logging\n'), ((795, 816), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (809, 816), False, 'import matplotlib\n'), ((4775, 4791), 'numpy.median', 'np.median', (['smags'], {}), '(smags)\n', (4784, 4791), True, 'import numpy as np\n'), ((4881, 4895), 'numpy.min', 'np.min', (['stimes'], {}), '(stimes)\n', (4887, 4895), True, 'import numpy as np\n'), ((5078, 5096), 'numpy.argsort', 'np.argsort', (['iphase'], {}), '(iphase)\n', (5088, 5096), True, 'import numpy as np\n'), ((5642, 5660), 'numpy.argsort', 'np.argsort', (['ptimes'], {}), '(ptimes)\n', (5652, 5660), True, 'import numpy as np\n'), ((23291, 23312), 'numpy.all', 'np.all', (['masks'], {'axis': '(0)'}), '(masks, axis=0)\n', (23297, 23312), True, 'import numpy as np\n'), ((5011, 5054), 'numpy.floor', 'np.floor', (['((stimes - mintime) / whitenperiod)'], {}), '((stimes - mintime) / whitenperiod)\n', (5019, 5054), True, 'import numpy as np\n'), ((9746, 9764), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (9762, 9764), True, 'import matplotlib.pyplot as plt\n'), ((9773, 9823), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plotfit'], {'format': '"""png"""', 'pad_inches': '(0.0)'}), "(plotfit, format='png', pad_inches=0.0)\n", (9784, 9823), True, 'import matplotlib.pyplot as plt\n'), ((9832, 9843), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (9841, 9843), True, 'import matplotlib.pyplot as plt\n'), ((15148, 15188), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 6 * nbestpeaks)'}), '(figsize=(20, 6 * nbestpeaks))\n', (15158, 15188), True, 'import matplotlib.pyplot as plt\n'), ((15250, 15275), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nplots', '(3)', '(1)'], {}), '(nplots, 3, 1)\n', (15261, 15275), True, 'import matplotlib.pyplot as plt\n'), ((15282, 15322), 'matplotlib.pyplot.plot', 'plt.plot', (["gls['periods']", "gls['lspvals']"], {}), "(gls['periods'], gls['lspvals'])\n", (15290, 15322), True, 'import matplotlib.pyplot as plt\n'), ((15330, 15357), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""period [days]"""'], {}), "('period [days]')\n", (15340, 15357), True, 'import matplotlib.pyplot as plt\n'), ((15366, 15389), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""GLS power"""'], {}), "('GLS power')\n", (15376, 15389), True, 'import matplotlib.pyplot as plt\n'), ((15398, 15415), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (15408, 15415), True, 'import matplotlib.pyplot as plt\n'), ((15424, 15484), 'matplotlib.pyplot.title', 'plt.title', (["('round 0, best period = %.6f' % gls['bestperiod'])"], {}), "('round 0, best period = %.6f' % gls['bestperiod'])\n", (15433, 15484), True, 'import matplotlib.pyplot as plt\n'), ((15516, 15541), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nplots', '(3)', '(2)'], {}), '(nplots, 3, 2)\n', (15527, 15541), True, 'import matplotlib.pyplot as plt\n'), ((15548, 15626), 'matplotlib.pyplot.plot', 'plt.plot', (['stimes', 'smags'], {'linestyle': '"""none"""', 'marker': '"""o"""', 'ms': '(1.0)', 'rasterized': '(True)'}), "(stimes, smags, linestyle='none', marker='o', ms=1.0, rasterized=True)\n", (15556, 15626), True, 'import matplotlib.pyplot as plt\n'), ((15798, 15814), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""JD"""'], {}), "('JD')\n", (15808, 15814), True, 'import matplotlib.pyplot as plt\n'), ((15823, 15864), 'matplotlib.pyplot.title', 'plt.title', (['"""unphased LC before whitening"""'], {}), "('unphased LC before whitening')\n", (15832, 15864), True, 'import matplotlib.pyplot as plt\n'), ((15894, 15919), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nplots', '(3)', '(3)'], {}), '(nplots, 3, 3)\n', (15905, 15919), True, 'import matplotlib.pyplot as plt\n'), ((16041, 16142), 'matplotlib.pyplot.plot', 'plt.plot', (["phased['phase']", "phased['mags']"], {'linestyle': '"""none"""', 'marker': '"""o"""', 'ms': '(1.0)', 'rasterized': '(True)'}), "(phased['phase'], phased['mags'], linestyle='none', marker='o', ms=\n 1.0, rasterized=True)\n", (16049, 16142), True, 'import matplotlib.pyplot as plt\n'), ((16309, 16328), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""phase"""'], {}), "('phase')\n", (16319, 16328), True, 'import matplotlib.pyplot as plt\n'), ((16337, 16406), 'matplotlib.pyplot.title', 'plt.title', (["('phased LC before whitening: P = %.6f' % gls['bestperiod'])"], {}), "('phased LC before whitening: P = %.6f' % gls['bestperiod'])\n", (16346, 16406), True, 'import matplotlib.pyplot as plt\n'), ((19648, 19691), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'hspace': '(0.2)', 'wspace': '(0.4)'}), '(hspace=0.2, wspace=0.4)\n', (19667, 19691), True, 'import matplotlib.pyplot as plt\n'), ((19699, 19741), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plotfits'], {'bbox_inches': '"""tight"""'}), "(plotfits, bbox_inches='tight')\n", (19710, 19741), True, 'import matplotlib.pyplot as plt\n'), ((19750, 19766), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (19759, 19766), True, 'import matplotlib.pyplot as plt\n'), ((22936, 22983), 'numpy.floor', 'np.floor', (['((stimes - signalepoch) / signalperiod)'], {}), '((stimes - signalepoch) / signalperiod)\n', (22944, 22983), True, 'import numpy as np\n'), ((27189, 27207), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (27205, 27207), True, 'import matplotlib.pyplot as plt\n'), ((27216, 27266), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plotfit'], {'format': '"""png"""', 'pad_inches': '(0.0)'}), "(plotfit, format='png', pad_inches=0.0)\n", (27227, 27266), True, 'import matplotlib.pyplot as plt\n'), ((27275, 27286), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (27284, 27286), True, 'import matplotlib.pyplot as plt\n'), ((6298, 6327), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 4.8)'}), '(figsize=(10, 4.8))\n', (6308, 6327), True, 'import matplotlib.pyplot as plt\n'), ((6353, 6382), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 9.6)'}), '(figsize=(16, 9.6))\n', (6363, 6382), True, 'import matplotlib.pyplot as plt\n'), ((6473, 6489), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (6484, 6489), True, 'import matplotlib.pyplot as plt\n'), ((6502, 6605), 'matplotlib.pyplot.plot', 'plt.plot', (['phase', 'pmags'], {'marker': '"""."""', 'color': '"""k"""', 'linestyle': '"""None"""', 'markersize': '(2.0)', 'markeredgewidth': '(0)'}), "(phase, pmags, marker='.', color='k', linestyle='None', markersize=\n 2.0, markeredgewidth=0)\n", (6510, 6605), True, 'import matplotlib.pyplot as plt\n'), ((6889, 6908), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""phase"""'], {}), "('phase')\n", (6899, 6908), True, 'import matplotlib.pyplot as plt\n'), ((6921, 6964), 'matplotlib.pyplot.title', 'plt.title', (['"""phased LC before pre-whitening"""'], {}), "('phased LC before pre-whitening')\n", (6930, 6964), True, 'import matplotlib.pyplot as plt\n'), ((7022, 7038), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (7033, 7038), True, 'import matplotlib.pyplot as plt\n'), ((7051, 7155), 'matplotlib.pyplot.plot', 'plt.plot', (['wphase', 'wmags'], {'marker': '"""."""', 'color': '"""g"""', 'linestyle': '"""None"""', 'markersize': '(2.0)', 'markeredgewidth': '(0)'}), "(wphase, wmags, marker='.', color='g', linestyle='None', markersize\n =2.0, markeredgewidth=0)\n", (7059, 7155), True, 'import matplotlib.pyplot as plt\n'), ((7439, 7458), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""phase"""'], {}), "('phase')\n", (7449, 7458), True, 'import matplotlib.pyplot as plt\n'), ((7471, 7513), 'matplotlib.pyplot.title', 'plt.title', (['"""phased LC after pre-whitening"""'], {}), "('phased LC after pre-whitening')\n", (7480, 7513), True, 'import matplotlib.pyplot as plt\n'), ((7585, 7601), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(221)'], {}), '(221)\n', (7596, 7601), True, 'import matplotlib.pyplot as plt\n'), ((7614, 7718), 'matplotlib.pyplot.plot', 'plt.plot', (['stimes', 'smags'], {'marker': '"""."""', 'color': '"""k"""', 'linestyle': '"""None"""', 'markersize': '(2.0)', 'markeredgewidth': '(0)'}), "(stimes, smags, marker='.', color='k', linestyle='None', markersize\n =2.0, markeredgewidth=0)\n", (7622, 7718), True, 'import matplotlib.pyplot as plt\n'), ((8002, 8018), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""JD"""'], {}), "('JD')\n", (8012, 8018), True, 'import matplotlib.pyplot as plt\n'), ((8031, 8067), 'matplotlib.pyplot.title', 'plt.title', (['"""LC before pre-whitening"""'], {}), "('LC before pre-whitening')\n", (8040, 8067), True, 'import matplotlib.pyplot as plt\n'), ((8123, 8139), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(222)'], {}), '(222)\n', (8134, 8139), True, 'import matplotlib.pyplot as plt\n'), ((8152, 8256), 'matplotlib.pyplot.plot', 'plt.plot', (['wtimes', 'wmags'], {'marker': '"""."""', 'color': '"""g"""', 'linestyle': '"""None"""', 'markersize': '(2.0)', 'markeredgewidth': '(0)'}), "(wtimes, wmags, marker='.', color='g', linestyle='None', markersize\n =2.0, markeredgewidth=0)\n", (8160, 8256), True, 'import matplotlib.pyplot as plt\n'), ((8540, 8556), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""JD"""'], {}), "('JD')\n", (8550, 8556), True, 'import matplotlib.pyplot as plt\n'), ((8569, 8637), 'matplotlib.pyplot.title', 'plt.title', (["('LC after pre-whitening with period: %.6f' % whitenperiod)"], {}), "('LC after pre-whitening with period: %.6f' % whitenperiod)\n", (8578, 8637), True, 'import matplotlib.pyplot as plt\n'), ((8696, 8712), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(223)'], {}), '(223)\n', (8707, 8712), True, 'import matplotlib.pyplot as plt\n'), ((8725, 8828), 'matplotlib.pyplot.plot', 'plt.plot', (['phase', 'pmags'], {'marker': '"""."""', 'color': '"""k"""', 'linestyle': '"""None"""', 'markersize': '(2.0)', 'markeredgewidth': '(0)'}), "(phase, pmags, marker='.', color='k', linestyle='None', markersize=\n 2.0, markeredgewidth=0)\n", (8733, 8828), True, 'import matplotlib.pyplot as plt\n'), ((9112, 9131), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""phase"""'], {}), "('phase')\n", (9122, 9131), True, 'import matplotlib.pyplot as plt\n'), ((9144, 9187), 'matplotlib.pyplot.title', 'plt.title', (['"""phased LC before pre-whitening"""'], {}), "('phased LC before pre-whitening')\n", (9153, 9187), True, 'import matplotlib.pyplot as plt\n'), ((9245, 9261), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(224)'], {}), '(224)\n', (9256, 9261), True, 'import matplotlib.pyplot as plt\n'), ((9274, 9378), 'matplotlib.pyplot.plot', 'plt.plot', (['wphase', 'wmags'], {'marker': '"""."""', 'color': '"""g"""', 'linestyle': '"""None"""', 'markersize': '(2.0)', 'markeredgewidth': '(0)'}), "(wphase, wmags, marker='.', color='g', linestyle='None', markersize\n =2.0, markeredgewidth=0)\n", (9282, 9378), True, 'import matplotlib.pyplot as plt\n'), ((9662, 9681), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""phase"""'], {}), "('phase')\n", (9672, 9681), True, 'import matplotlib.pyplot as plt\n'), ((9694, 9736), 'matplotlib.pyplot.title', 'plt.title', (['"""phased LC after pre-whitening"""'], {}), "('phased LC after pre-whitening')\n", (9703, 9736), True, 'import matplotlib.pyplot as plt\n'), ((15721, 15744), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (15731, 15744), True, 'import matplotlib.pyplot as plt\n'), ((15771, 15789), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""flux"""'], {}), "('flux')\n", (15781, 15789), True, 'import matplotlib.pyplot as plt\n'), ((16195, 16218), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (16205, 16218), True, 'import matplotlib.pyplot as plt\n'), ((16282, 16300), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""flux"""'], {}), "('flux')\n", (16292, 16300), True, 'import matplotlib.pyplot as plt\n'), ((18200, 18238), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nplots', '(3)', '(4 + fitind * 3)'], {}), '(nplots, 3, 4 + fitind * 3)\n', (18211, 18238), True, 'import matplotlib.pyplot as plt\n'), ((18245, 18287), 'matplotlib.pyplot.plot', 'plt.plot', (["wgls['periods']", "wgls['lspvals']"], {}), "(wgls['periods'], wgls['lspvals'])\n", (18253, 18287), True, 'import matplotlib.pyplot as plt\n'), ((18299, 18326), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""period [days]"""'], {}), "('period [days]')\n", (18309, 18326), True, 'import matplotlib.pyplot as plt\n'), ((18339, 18362), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""LSP power"""'], {}), "('LSP power')\n", (18349, 18362), True, 'import matplotlib.pyplot as plt\n'), ((18375, 18392), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (18385, 18392), True, 'import matplotlib.pyplot as plt\n'), ((18405, 18481), 'matplotlib.pyplot.title', 'plt.title', (["('round %s, best period = %.6f' % (fitind + 1, wgls['bestperiod']))"], {}), "('round %s, best period = %.6f' % (fitind + 1, wgls['bestperiod']))\n", (18414, 18481), True, 'import matplotlib.pyplot as plt\n'), ((18575, 18613), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nplots', '(3)', '(5 + fitind * 3)'], {}), '(nplots, 3, 5 + fitind * 3)\n', (18586, 18613), True, 'import matplotlib.pyplot as plt\n'), ((18620, 18698), 'matplotlib.pyplot.plot', 'plt.plot', (['wtimes', 'wmags'], {'linestyle': '"""none"""', 'marker': '"""o"""', 'ms': '(1.0)', 'rasterized': '(True)'}), "(wtimes, wmags, linestyle='none', marker='o', ms=1.0, rasterized=True)\n", (18628, 18698), True, 'import matplotlib.pyplot as plt\n'), ((18898, 18914), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""JD"""'], {}), "('JD')\n", (18908, 18914), True, 'import matplotlib.pyplot as plt\n'), ((18927, 18967), 'matplotlib.pyplot.title', 'plt.title', (['"""unphased LC after whitening"""'], {}), "('unphased LC after whitening')\n", (18936, 18967), True, 'import matplotlib.pyplot as plt\n'), ((19005, 19043), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nplots', '(3)', '(6 + fitind * 3)'], {}), '(nplots, 3, 6 + fitind * 3)\n', (19016, 19043), True, 'import matplotlib.pyplot as plt\n'), ((19165, 19267), 'matplotlib.pyplot.plot', 'plt.plot', (["wphased['phase']", "wphased['mags']"], {'linestyle': '"""none"""', 'marker': '"""o"""', 'ms': '(1.0)', 'rasterized': '(True)'}), "(wphased['phase'], wphased['mags'], linestyle='none', marker='o',\n ms=1.0, rasterized=True)\n", (19173, 19267), True, 'import matplotlib.pyplot as plt\n'), ((19463, 19482), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""phase"""'], {}), "('phase')\n", (19473, 19482), True, 'import matplotlib.pyplot as plt\n'), ((19495, 19553), 'matplotlib.pyplot.title', 'plt.title', (["('phased LC after whitening: P = %.6f' % wperiod)"], {}), "('phased LC after whitening: P = %.6f' % wperiod)\n", (19504, 19553), True, 'import matplotlib.pyplot as plt\n'), ((19795, 19820), 'os.path.abspath', 'os.path.abspath', (['plotfits'], {}), '(plotfits)\n', (19810, 19820), False, 'import os\n'), ((23764, 23793), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 4.8)'}), '(figsize=(10, 4.8))\n', (23774, 23793), True, 'import matplotlib.pyplot as plt\n'), ((23819, 23848), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 9.6)'}), '(figsize=(16, 9.6))\n', (23829, 23848), True, 'import matplotlib.pyplot as plt\n'), ((23939, 23955), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (23950, 23955), True, 'import matplotlib.pyplot as plt\n'), ((23968, 24072), 'matplotlib.pyplot.plot', 'plt.plot', (['phases', 'smags'], {'marker': '"""."""', 'color': '"""k"""', 'linestyle': '"""None"""', 'markersize': '(2.0)', 'markeredgewidth': '(0)'}), "(phases, smags, marker='.', color='k', linestyle='None', markersize\n =2.0, markeredgewidth=0)\n", (23976, 24072), True, 'import matplotlib.pyplot as plt\n'), ((24356, 24375), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""phase"""'], {}), "('phase')\n", (24366, 24375), True, 'import matplotlib.pyplot as plt\n'), ((24388, 24432), 'matplotlib.pyplot.title', 'plt.title', (['"""phased LC before signal masking"""'], {}), "('phased LC before signal masking')\n", (24397, 24432), True, 'import matplotlib.pyplot as plt\n'), ((24490, 24506), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (24501, 24506), True, 'import matplotlib.pyplot as plt\n'), ((24519, 24623), 'matplotlib.pyplot.plot', 'plt.plot', (['mphases', 'mmags'], {'marker': '"""."""', 'color': '"""g"""', 'linestyle': '"""None"""', 'markersize': '(2.0)', 'markeredgewidth': '(0)'}), "(mphases, mmags, marker='.', color='g', linestyle='None',\n markersize=2.0, markeredgewidth=0)\n", (24527, 24623), True, 'import matplotlib.pyplot as plt\n'), ((24908, 24927), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""phase"""'], {}), "('phase')\n", (24918, 24927), True, 'import matplotlib.pyplot as plt\n'), ((24940, 24983), 'matplotlib.pyplot.title', 'plt.title', (['"""phased LC after signal masking"""'], {}), "('phased LC after signal masking')\n", (24949, 24983), True, 'import matplotlib.pyplot as plt\n'), ((25055, 25071), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(221)'], {}), '(221)\n', (25066, 25071), True, 'import matplotlib.pyplot as plt\n'), ((25084, 25188), 'matplotlib.pyplot.plot', 'plt.plot', (['stimes', 'smags'], {'marker': '"""."""', 'color': '"""k"""', 'linestyle': '"""None"""', 'markersize': '(2.0)', 'markeredgewidth': '(0)'}), "(stimes, smags, marker='.', color='k', linestyle='None', markersize\n =2.0, markeredgewidth=0)\n", (25092, 25188), True, 'import matplotlib.pyplot as plt\n'), ((25472, 25488), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""JD"""'], {}), "('JD')\n", (25482, 25488), True, 'import matplotlib.pyplot as plt\n'), ((25501, 25538), 'matplotlib.pyplot.title', 'plt.title', (['"""LC before signal masking"""'], {}), "('LC before signal masking')\n", (25510, 25538), True, 'import matplotlib.pyplot as plt\n'), ((25594, 25610), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(222)'], {}), '(222)\n', (25605, 25610), True, 'import matplotlib.pyplot as plt\n'), ((25623, 25727), 'matplotlib.pyplot.plot', 'plt.plot', (['mtimes', 'mmags'], {'marker': '"""."""', 'color': '"""g"""', 'linestyle': '"""None"""', 'markersize': '(2.0)', 'markeredgewidth': '(0)'}), "(mtimes, mmags, marker='.', color='g', linestyle='None', markersize\n =2.0, markeredgewidth=0)\n", (25631, 25727), True, 'import matplotlib.pyplot as plt\n'), ((26011, 26027), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""JD"""'], {}), "('JD')\n", (26021, 26027), True, 'import matplotlib.pyplot as plt\n'), ((26040, 26076), 'matplotlib.pyplot.title', 'plt.title', (['"""LC after signal masking"""'], {}), "('LC after signal masking')\n", (26049, 26076), True, 'import matplotlib.pyplot as plt\n'), ((26135, 26151), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(223)'], {}), '(223)\n', (26146, 26151), True, 'import matplotlib.pyplot as plt\n'), ((26164, 26268), 'matplotlib.pyplot.plot', 'plt.plot', (['phases', 'smags'], {'marker': '"""."""', 'color': '"""k"""', 'linestyle': '"""None"""', 'markersize': '(2.0)', 'markeredgewidth': '(0)'}), "(phases, smags, marker='.', color='k', linestyle='None', markersize\n =2.0, markeredgewidth=0)\n", (26172, 26268), True, 'import matplotlib.pyplot as plt\n'), ((26552, 26571), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""phase"""'], {}), "('phase')\n", (26562, 26571), True, 'import matplotlib.pyplot as plt\n'), ((26584, 26628), 'matplotlib.pyplot.title', 'plt.title', (['"""phased LC before signal masking"""'], {}), "('phased LC before signal masking')\n", (26593, 26628), True, 'import matplotlib.pyplot as plt\n'), ((26686, 26702), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(224)'], {}), '(224)\n', (26697, 26702), True, 'import matplotlib.pyplot as plt\n'), ((26715, 26819), 'matplotlib.pyplot.plot', 'plt.plot', (['mphases', 'mmags'], {'marker': '"""."""', 'color': '"""g"""', 'linestyle': '"""None"""', 'markersize': '(2.0)', 'markeredgewidth': '(0)'}), "(mphases, mmags, marker='.', color='g', linestyle='None',\n markersize=2.0, markeredgewidth=0)\n", (26723, 26819), True, 'import matplotlib.pyplot as plt\n'), ((27104, 27123), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""phase"""'], {}), "('phase')\n", (27114, 27123), True, 'import matplotlib.pyplot as plt\n'), ((27136, 27179), 'matplotlib.pyplot.title', 'plt.title', (['"""phased LC after signal masking"""'], {}), "('phased LC after signal masking')\n", (27145, 27179), True, 'import matplotlib.pyplot as plt\n'), ((6797, 6820), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (6807, 6820), True, 'import matplotlib.pyplot as plt\n'), ((6855, 6875), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fluxes"""'], {}), "('fluxes')\n", (6865, 6875), True, 'import matplotlib.pyplot as plt\n'), ((7347, 7370), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (7357, 7370), True, 'import matplotlib.pyplot as plt\n'), ((7405, 7425), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fluxes"""'], {}), "('fluxes')\n", (7415, 7425), True, 'import matplotlib.pyplot as plt\n'), ((7910, 7933), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (7920, 7933), True, 'import matplotlib.pyplot as plt\n'), ((7968, 7988), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fluxes"""'], {}), "('fluxes')\n", (7978, 7988), True, 'import matplotlib.pyplot as plt\n'), ((8448, 8471), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (8458, 8471), True, 'import matplotlib.pyplot as plt\n'), ((8506, 8526), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fluxes"""'], {}), "('fluxes')\n", (8516, 8526), True, 'import matplotlib.pyplot as plt\n'), ((9020, 9043), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (9030, 9043), True, 'import matplotlib.pyplot as plt\n'), ((9078, 9098), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fluxes"""'], {}), "('fluxes')\n", (9088, 9098), True, 'import matplotlib.pyplot as plt\n'), ((9570, 9593), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (9580, 9593), True, 'import matplotlib.pyplot as plt\n'), ((9628, 9648), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fluxes"""'], {}), "('fluxes')\n", (9638, 9648), True, 'import matplotlib.pyplot as plt\n'), ((18809, 18832), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (18819, 18832), True, 'import matplotlib.pyplot as plt\n'), ((18867, 18885), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""flux"""'], {}), "('flux')\n", (18877, 18885), True, 'import matplotlib.pyplot as plt\n'), ((19333, 19356), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (19343, 19356), True, 'import matplotlib.pyplot as plt\n'), ((19432, 19450), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""flux"""'], {}), "('flux')\n", (19442, 19450), True, 'import matplotlib.pyplot as plt\n'), ((23128, 23146), 'numpy.abs', 'np.abs', (['(phases - x)'], {}), '(phases - x)\n', (23134, 23146), True, 'import numpy as np\n'), ((24264, 24287), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (24274, 24287), True, 'import matplotlib.pyplot as plt\n'), ((24322, 24342), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fluxes"""'], {}), "('fluxes')\n", (24332, 24342), True, 'import matplotlib.pyplot as plt\n'), ((24816, 24839), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (24826, 24839), True, 'import matplotlib.pyplot as plt\n'), ((24874, 24894), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fluxes"""'], {}), "('fluxes')\n", (24884, 24894), True, 'import matplotlib.pyplot as plt\n'), ((25380, 25403), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (25390, 25403), True, 'import matplotlib.pyplot as plt\n'), ((25438, 25458), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fluxes"""'], {}), "('fluxes')\n", (25448, 25458), True, 'import matplotlib.pyplot as plt\n'), ((25919, 25942), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (25929, 25942), True, 'import matplotlib.pyplot as plt\n'), ((25977, 25997), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fluxes"""'], {}), "('fluxes')\n", (25987, 25997), True, 'import matplotlib.pyplot as plt\n'), ((26460, 26483), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (26470, 26483), True, 'import matplotlib.pyplot as plt\n'), ((26518, 26538), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fluxes"""'], {}), "('fluxes')\n", (26528, 26538), True, 'import matplotlib.pyplot as plt\n'), ((27012, 27035), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""magnitude"""'], {}), "('magnitude')\n", (27022, 27035), True, 'import matplotlib.pyplot as plt\n'), ((27070, 27090), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fluxes"""'], {}), "('fluxes')\n", (27080, 27090), True, 'import matplotlib.pyplot as plt\n'), ((15684, 15693), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (15691, 15693), True, 'import matplotlib.pyplot as plt\n'), ((16231, 16240), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (16238, 16240), True, 'import matplotlib.pyplot as plt\n'), ((6756, 6765), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (6763, 6765), True, 'import matplotlib.pyplot as plt\n'), ((7306, 7315), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (7313, 7315), True, 'import matplotlib.pyplot as plt\n'), ((7869, 7878), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (7876, 7878), True, 'import matplotlib.pyplot as plt\n'), ((8407, 8416), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (8414, 8416), True, 'import matplotlib.pyplot as plt\n'), ((8979, 8988), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (8986, 8988), True, 'import matplotlib.pyplot as plt\n'), ((9529, 9538), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (9536, 9538), True, 'import matplotlib.pyplot as plt\n'), ((18768, 18777), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (18775, 18777), True, 'import matplotlib.pyplot as plt\n'), ((19373, 19382), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (19380, 19382), True, 'import matplotlib.pyplot as plt\n'), ((24223, 24232), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (24230, 24232), True, 'import matplotlib.pyplot as plt\n'), ((24775, 24784), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (24782, 24784), True, 'import matplotlib.pyplot as plt\n'), ((25339, 25348), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (25346, 25348), True, 'import matplotlib.pyplot as plt\n'), ((25878, 25887), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (25885, 25887), True, 'import matplotlib.pyplot as plt\n'), ((26419, 26428), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (26426, 26428), True, 'import matplotlib.pyplot as plt\n'), ((26971, 26980), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (26978, 26980), True, 'import matplotlib.pyplot as plt\n')]
import numpy as np import signal_processing as sp import numpy.ma as ma import datetime as dt """ mel 2018-04-20 Translates RMS results for all files to minimum / mean / maximum and filters out zeros in the minimum. Filters out only weekday results between 6:00 and 18:00 hours. """ # dir_path = "C:\\Users\\mel\\Documents\\Python\\Betacampus_pos1\\" # dir_path = "C:\\Users\\mel\\Documents\\Python\\Betacampus_pos2\\" dir_path = "C:\\Users\\mel\\Documents\\Python\\Huygensgebouw\\" file_list = sp.obtain_files(dir_path) start_date = [] start_time = [] time_length = [] total_time_start = [] total_time_end = [] total = None date = None time_of_day = None for i in range(len(file_list)): file_path = dir_path + file_list[i] # print(file_list[i]) with open(file_path, encoding='latin-1') as f: for cnt, line in enumerate(f): if line.startswith('# StartDate'): year = int(line[12:16]) month = int(line[17:19]) day = int(line[20:22]) date = dt.date(year = year, month = month, day = day) total = dt.datetime(year = year, month = month, day = day) start_date.append(date) elif line.startswith('# StartTime'): hour = int(line[12:14]) minutes = int(line[15:17]) seconds = int(line[18:20]) time_of_day = dt.time(hour = hour, minute = minutes, second = seconds) total = total+ dt.timedelta(hours = hour, minutes = minutes, seconds = seconds) start_time.append(time_of_day) elif line.startswith('# Length'): hour = int(line[9:11]) minutes = int(line[12:14]) seconds = int(line[15:17]) dtime = dt.time(hour = hour, minute= minutes, second = seconds) time_length.append(dtime) total_time_start.append(total) total = total + dt.timedelta(hours = hour, minutes = minutes, seconds = seconds) total_time_end.append(total) break f_band = sp.OneThird_octave(0.625 / 2**(1/3), 80 * 2**(1/3)) filter_weekday = np.ndarray((len(f_band), len(file_list)+1), dtype = 'bool') filter_weekday[..., 0] = True for i in range(len(file_list)): if (start_date[i].weekday() >= 0) and (start_date[i].weekday() <= 4): if (start_time[i].hour >= 6) and (start_time[i].hour <= 18): filter_weekday[..., i + 1] = False else: filter_weekday[..., i + 1] = True else: filter_weekday[..., i + 1] = True # rms_x_array = np.loadtxt("14208_betacampus_pos1_rms_x_400.txt") # rms_y_array = np.loadtxt("14208_betacampus_pos1_rms_y_400.txt") # rms_z_array = np.loadtxt("14208_betacampus_pos1_rms_z_400.txt") # rms_x_array = np.loadtxt("14208_betacampus_pos2_rms_x.txt") # rms_y_array = np.loadtxt("14208_betacampus_pos2_rms_y.txt") # rms_z_array = np.loadtxt("14208_betacampus_pos2_rms_z.txt") rms_x_array = np.loadtxt("14208_Huygensgebouw_rms_x.txt") rms_y_array = np.loadtxt("14208_Huygensgebouw_rms_y.txt") rms_z_array = np.loadtxt("14208_Huygensgebouw_rms_z.txt") rms_x_array = ma.array(rms_x_array, mask = filter_weekday) rms_y_array = ma.array(rms_y_array, mask = filter_weekday) rms_z_array = ma.array(rms_z_array, mask = filter_weekday) rms_x_all = np.zeros((len(f_band), 6)) rms_y_all = np.zeros((len(f_band), 6)) rms_z_all = np.zeros((len(f_band), 6)) rms_x_array_masked = ma.masked_less(rms_x_array, 1e-9) rms_y_array_masked = ma.masked_less(rms_y_array, 1e-9) rms_z_array_masked = ma.masked_less(rms_z_array, 1e-9) rms_x_all[..., 0] = f_band rms_x_all[..., 1] = rms_x_array_masked[..., 1:].min(axis = 1) rms_x_all[..., 2] = rms_x_array[..., 1:].mean(axis = 1) - rms_x_array[..., 1:].std(axis = 1) rms_x_all[..., 3] = rms_x_array[..., 1:].mean(axis = 1) rms_x_all[..., 4] = rms_x_array[..., 1:].mean(axis = 1) + rms_x_array[..., 1:].std(axis = 1) rms_x_all[..., 5] = rms_x_array[..., 1:].max(axis = 1) rms_y_all[..., 0] = f_band rms_y_all[..., 1] = rms_y_array_masked[..., 1:].min(axis = 1) rms_y_all[..., 2] = rms_y_array[..., 1:].mean(axis = 1) - rms_y_array[..., 1:].std(axis = 1) rms_y_all[..., 3] = rms_y_array[..., 1:].mean(axis = 1) rms_y_all[..., 4] = rms_y_array[..., 1:].mean(axis = 1) + rms_y_array[..., 1:].std(axis = 1) rms_y_all[..., 5] = rms_y_array[..., 1:].max(axis = 1) rms_z_all[..., 0] = f_band rms_z_all[..., 1] = rms_z_array_masked[..., 1:].min(axis = 1) rms_z_all[..., 2] = rms_z_array[..., 1:].mean(axis = 1) - rms_z_array[..., 1:].std(axis = 1) rms_z_all[..., 3] = rms_z_array[..., 1:].mean(axis = 1) rms_z_all[..., 4] = rms_z_array[..., 1:].mean(axis = 1) + rms_z_array[..., 1:].std(axis = 1) rms_z_all[..., 5] = rms_z_array[..., 1:].max(axis = 1) # np.savetxt("14208_betacampus_pos1_rms_x_weekday.txt", rms_x_all) # np.savetxt("14208_betacampus_pos1_rms_y_weekday.txt", rms_y_all) # np.savetxt("14208_betacampus_pos1_rms_z_weekday.txt", rms_z_all) # np.savetxt("14208_betacampus_pos2_rms_x_weekday.txt", rms_x_all) # np.savetxt("14208_betacampus_pos2_rms_y_weekday.txt", rms_y_all) # np.savetxt("14208_betacampus_pos2_rms_z_weekday.txt", rms_z_all) np.savetxt("14208_Huygensgebouw_rms_x_weekday.txt", rms_x_all) np.savetxt("14208_Huygensgebouw_rms_y_weekday.txt", rms_y_all) np.savetxt("14208_Huygensgebouw_rms_z_weekday.txt", rms_z_all)
[ "numpy.savetxt", "datetime.date", "datetime.datetime", "numpy.ma.array", "signal_processing.OneThird_octave", "datetime.timedelta", "numpy.loadtxt", "datetime.time", "numpy.ma.masked_less", "signal_processing.obtain_files" ]
[((513, 538), 'signal_processing.obtain_files', 'sp.obtain_files', (['dir_path'], {}), '(dir_path)\n', (528, 538), True, 'import signal_processing as sp\n'), ((2149, 2208), 'signal_processing.OneThird_octave', 'sp.OneThird_octave', (['(0.625 / 2 ** (1 / 3))', '(80 * 2 ** (1 / 3))'], {}), '(0.625 / 2 ** (1 / 3), 80 * 2 ** (1 / 3))\n', (2167, 2208), True, 'import signal_processing as sp\n'), ((3069, 3112), 'numpy.loadtxt', 'np.loadtxt', (['"""14208_Huygensgebouw_rms_x.txt"""'], {}), "('14208_Huygensgebouw_rms_x.txt')\n", (3079, 3112), True, 'import numpy as np\n'), ((3128, 3171), 'numpy.loadtxt', 'np.loadtxt', (['"""14208_Huygensgebouw_rms_y.txt"""'], {}), "('14208_Huygensgebouw_rms_y.txt')\n", (3138, 3171), True, 'import numpy as np\n'), ((3187, 3230), 'numpy.loadtxt', 'np.loadtxt', (['"""14208_Huygensgebouw_rms_z.txt"""'], {}), "('14208_Huygensgebouw_rms_z.txt')\n", (3197, 3230), True, 'import numpy as np\n'), ((3248, 3290), 'numpy.ma.array', 'ma.array', (['rms_x_array'], {'mask': 'filter_weekday'}), '(rms_x_array, mask=filter_weekday)\n', (3256, 3290), True, 'import numpy.ma as ma\n'), ((3308, 3350), 'numpy.ma.array', 'ma.array', (['rms_y_array'], {'mask': 'filter_weekday'}), '(rms_y_array, mask=filter_weekday)\n', (3316, 3350), True, 'import numpy.ma as ma\n'), ((3368, 3410), 'numpy.ma.array', 'ma.array', (['rms_z_array'], {'mask': 'filter_weekday'}), '(rms_z_array, mask=filter_weekday)\n', (3376, 3410), True, 'import numpy.ma as ma\n'), ((3559, 3593), 'numpy.ma.masked_less', 'ma.masked_less', (['rms_x_array', '(1e-09)'], {}), '(rms_x_array, 1e-09)\n', (3573, 3593), True, 'import numpy.ma as ma\n'), ((3615, 3649), 'numpy.ma.masked_less', 'ma.masked_less', (['rms_y_array', '(1e-09)'], {}), '(rms_y_array, 1e-09)\n', (3629, 3649), True, 'import numpy.ma as ma\n'), ((3671, 3705), 'numpy.ma.masked_less', 'ma.masked_less', (['rms_z_array', '(1e-09)'], {}), '(rms_z_array, 1e-09)\n', (3685, 3705), True, 'import numpy.ma as ma\n'), ((5298, 5360), 'numpy.savetxt', 'np.savetxt', (['"""14208_Huygensgebouw_rms_x_weekday.txt"""', 'rms_x_all'], {}), "('14208_Huygensgebouw_rms_x_weekday.txt', rms_x_all)\n", (5308, 5360), True, 'import numpy as np\n'), ((5362, 5424), 'numpy.savetxt', 'np.savetxt', (['"""14208_Huygensgebouw_rms_y_weekday.txt"""', 'rms_y_all'], {}), "('14208_Huygensgebouw_rms_y_weekday.txt', rms_y_all)\n", (5372, 5424), True, 'import numpy as np\n'), ((5426, 5488), 'numpy.savetxt', 'np.savetxt', (['"""14208_Huygensgebouw_rms_z_weekday.txt"""', 'rms_z_all'], {}), "('14208_Huygensgebouw_rms_z_weekday.txt', rms_z_all)\n", (5436, 5488), True, 'import numpy as np\n'), ((1066, 1106), 'datetime.date', 'dt.date', ([], {'year': 'year', 'month': 'month', 'day': 'day'}), '(year=year, month=month, day=day)\n', (1073, 1106), True, 'import datetime as dt\n'), ((1137, 1181), 'datetime.datetime', 'dt.datetime', ([], {'year': 'year', 'month': 'month', 'day': 'day'}), '(year=year, month=month, day=day)\n', (1148, 1181), True, 'import datetime as dt\n'), ((1433, 1483), 'datetime.time', 'dt.time', ([], {'hour': 'hour', 'minute': 'minutes', 'second': 'seconds'}), '(hour=hour, minute=minutes, second=seconds)\n', (1440, 1483), True, 'import datetime as dt\n'), ((1521, 1579), 'datetime.timedelta', 'dt.timedelta', ([], {'hours': 'hour', 'minutes': 'minutes', 'seconds': 'seconds'}), '(hours=hour, minutes=minutes, seconds=seconds)\n', (1533, 1579), True, 'import datetime as dt\n'), ((1828, 1878), 'datetime.time', 'dt.time', ([], {'hour': 'hour', 'minute': 'minutes', 'second': 'seconds'}), '(hour=hour, minute=minutes, second=seconds)\n', (1835, 1878), True, 'import datetime as dt\n'), ((2005, 2063), 'datetime.timedelta', 'dt.timedelta', ([], {'hours': 'hour', 'minutes': 'minutes', 'seconds': 'seconds'}), '(hours=hour, minutes=minutes, seconds=seconds)\n', (2017, 2063), True, 'import datetime as dt\n')]
import torch import numpy as np from torch.autograd import Variable import halp.utils.utils from halp.utils.utils import single_to_half_det, single_to_half_stoc from halp.models.logistic_regression import LogisticRegression from unittest import TestCase class LeNetTest(TestCase): def test_logistic_regression_grad(self): n_sample = 4 n_dim = 3 n_class = 4 X = Variable(torch.DoubleTensor(np.random.normal(size=(n_sample, n_dim) ) ) ) Y = Variable(torch.LongTensor(np.array([0, 1, 3, 2] ) ) ) regressor = LogisticRegression(input_dim=n_dim, n_class=n_class, reg_lambda=100.0, dtype="fp") regressor.double() loss1 = regressor.forward(X, Y) loss_diff = 0.0 move = 1e-9 loss1.backward() for w in regressor.parameters(): loss_diff += torch.sum(w.grad.data * move) for w in regressor.parameters(): w.data += move loss2 = regressor.forward(X, Y) assert np.abs((loss2.item() - loss1.item() ) - loss_diff) < 1e-9 print("logistic regression gradient test done!") if __name__ == "__main__": print(torch.__version__) unittest.main()
[ "halp.models.logistic_regression.LogisticRegression", "torch.sum", "numpy.array", "numpy.random.normal" ]
[((560, 646), 'halp.models.logistic_regression.LogisticRegression', 'LogisticRegression', ([], {'input_dim': 'n_dim', 'n_class': 'n_class', 'reg_lambda': '(100.0)', 'dtype': '"""fp"""'}), "(input_dim=n_dim, n_class=n_class, reg_lambda=100.0,\n dtype='fp')\n", (578, 646), False, 'from halp.models.logistic_regression import LogisticRegression\n'), ((845, 874), 'torch.sum', 'torch.sum', (['(w.grad.data * move)'], {}), '(w.grad.data * move)\n', (854, 874), False, 'import torch\n'), ((428, 468), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(n_sample, n_dim)'}), '(size=(n_sample, n_dim))\n', (444, 468), True, 'import numpy as np\n'), ((512, 534), 'numpy.array', 'np.array', (['[0, 1, 3, 2]'], {}), '([0, 1, 3, 2])\n', (520, 534), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') def plot_images(images, targets, n_plot=30): n_rows = n_plot // 10 + ((n_plot % 10) > 0) fig, axes = plt.subplots(n_rows, 10, figsize=(15, 1.5 * n_rows)) axes = np.atleast_2d(axes) for i, (image, target) in enumerate(zip(images[:n_plot], targets[:n_plot])): row, col = i // 10, i % 10 ax = axes[row, col] ax.set_title('#{} - Label:{}'.format(i, target), {'size': 12}) # plot filter channel in grayscale ax.imshow(image.squeeze(), cmap='gray', vmin=0, vmax=1) for ax in axes.flat: ax.set_xticks([]) ax.set_yticks([]) ax.label_outer() plt.tight_layout() return fig
[ "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.style.use", "matplotlib.pyplot.subplots", "numpy.atleast_2d" ]
[((51, 83), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""fivethirtyeight"""'], {}), "('fivethirtyeight')\n", (64, 83), True, 'import matplotlib.pyplot as plt\n'), ((194, 246), 'matplotlib.pyplot.subplots', 'plt.subplots', (['n_rows', '(10)'], {'figsize': '(15, 1.5 * n_rows)'}), '(n_rows, 10, figsize=(15, 1.5 * n_rows))\n', (206, 246), True, 'import matplotlib.pyplot as plt\n'), ((258, 277), 'numpy.atleast_2d', 'np.atleast_2d', (['axes'], {}), '(axes)\n', (271, 277), True, 'import numpy as np\n'), ((713, 731), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (729, 731), True, 'import matplotlib.pyplot as plt\n')]
import os import sys import h5py import numpy as np import pandas as pd import networkx as nx from convert import make_adjacency, make_sparse_adjacency, save_problem, spadj2edgelist np.random.seed(123) def load_ages(path): ages = pd.read_csv(path, header=None, sep='\t') ages.columns = ('id', 'age') ages = ages[ages.age != 'null'] ages.age = ages.age.astype(int) ages = ages[ages.age > 0] return ages max_degree = 128 inpath = '../data/pokec/' # -- # Load data ages = load_ages(os.path.join(inpath, 'soc-pokec-ages.tsv')) edges = pd.read_csv(os.path.join(inpath, 'soc-pokec-relationships.txt'), header=None, sep='\t') edges.columns = ('src', 'trg') edges = edges[edges.src.isin(ages.id)] edges = edges[edges.trg.isin(ages.id)] ages = ages[ages.id.isin(edges.src) | ages.id.isin(edges.trg)] ages['uid'] = np.arange(ages.shape[0]) edges = pd.merge(edges, ages, left_on='src', right_on='id') edges = edges[['uid', 'trg']] edges.columns = ('src', 'trg') edges = pd.merge(edges, ages, left_on='trg', right_on='id') edges = edges[['src', 'uid']] edges.columns = ('src', 'trg') ages = ages[['uid', 'age']] targets = np.array(ages.age).astype(float).reshape(-1, 1) folds = np.random.choice(['train', 'val'], targets.shape[0], p=[0.5, 0.5]) G = nx.from_edgelist(np.array(edges)) # -- # Dense version adj = make_adjacency(G, max_degree, sel=None) # Adds dummy node aug_targets = np.vstack([targets, np.zeros((targets.shape[1],), dtype='float64')]) aug_folds = np.hstack([folds, ['dummy']]) save_problem({ "task" : 'regression_mae', "n_classes" : None, "feats" : None, "adj" : adj, "train_adj" : adj, "targets" : aug_targets, "folds" : aug_folds, }, '../data/pokec/problem.h5') spadj = make_sparse_adjacency(G, sel=None) aug_targets = np.vstack([np.zeros((targets.shape[1],), dtype='float64'), targets]) aug_folds = np.hstack([['dummy'], folds]) save_problem({ "task" : 'regression_mae', "n_classes" : None, "feats" : None, "sparse" : True, "adj" : spadj2edgelist(spadj), "train_adj" : spadj2edgelist(spadj), "targets" : aug_targets, "folds" : aug_folds, }, '../data/pokec/sparse-problem.h5')
[ "numpy.random.seed", "convert.make_adjacency", "convert.save_problem", "pandas.read_csv", "pandas.merge", "numpy.zeros", "numpy.hstack", "numpy.arange", "numpy.array", "numpy.random.choice", "os.path.join", "convert.spadj2edgelist", "convert.make_sparse_adjacency" ]
[((183, 202), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (197, 202), True, 'import numpy as np\n'), ((848, 872), 'numpy.arange', 'np.arange', (['ages.shape[0]'], {}), '(ages.shape[0])\n', (857, 872), True, 'import numpy as np\n'), ((882, 933), 'pandas.merge', 'pd.merge', (['edges', 'ages'], {'left_on': '"""src"""', 'right_on': '"""id"""'}), "(edges, ages, left_on='src', right_on='id')\n", (890, 933), True, 'import pandas as pd\n'), ((1003, 1054), 'pandas.merge', 'pd.merge', (['edges', 'ages'], {'left_on': '"""trg"""', 'right_on': '"""id"""'}), "(edges, ages, left_on='trg', right_on='id')\n", (1011, 1054), True, 'import pandas as pd\n'), ((1212, 1278), 'numpy.random.choice', 'np.random.choice', (["['train', 'val']", 'targets.shape[0]'], {'p': '[0.5, 0.5]'}), "(['train', 'val'], targets.shape[0], p=[0.5, 0.5])\n", (1228, 1278), True, 'import numpy as np\n'), ((1347, 1386), 'convert.make_adjacency', 'make_adjacency', (['G', 'max_degree'], {'sel': 'None'}), '(G, max_degree, sel=None)\n', (1361, 1386), False, 'from convert import make_adjacency, make_sparse_adjacency, save_problem, spadj2edgelist\n'), ((1503, 1532), 'numpy.hstack', 'np.hstack', (["[folds, ['dummy']]"], {}), "([folds, ['dummy']])\n", (1512, 1532), True, 'import numpy as np\n'), ((1534, 1718), 'convert.save_problem', 'save_problem', (["{'task': 'regression_mae', 'n_classes': None, 'feats': None, 'adj': adj,\n 'train_adj': adj, 'targets': aug_targets, 'folds': aug_folds}", '"""../data/pokec/problem.h5"""'], {}), "({'task': 'regression_mae', 'n_classes': None, 'feats': None,\n 'adj': adj, 'train_adj': adj, 'targets': aug_targets, 'folds':\n aug_folds}, '../data/pokec/problem.h5')\n", (1546, 1718), False, 'from convert import make_adjacency, make_sparse_adjacency, save_problem, spadj2edgelist\n'), ((1790, 1824), 'convert.make_sparse_adjacency', 'make_sparse_adjacency', (['G'], {'sel': 'None'}), '(G, sel=None)\n', (1811, 1824), False, 'from convert import make_adjacency, make_sparse_adjacency, save_problem, spadj2edgelist\n'), ((1922, 1951), 'numpy.hstack', 'np.hstack', (["[['dummy'], folds]"], {}), "([['dummy'], folds])\n", (1931, 1951), True, 'import numpy as np\n'), ((236, 276), 'pandas.read_csv', 'pd.read_csv', (['path'], {'header': 'None', 'sep': '"""\t"""'}), "(path, header=None, sep='\\t')\n", (247, 276), True, 'import pandas as pd\n'), ((519, 561), 'os.path.join', 'os.path.join', (['inpath', '"""soc-pokec-ages.tsv"""'], {}), "(inpath, 'soc-pokec-ages.tsv')\n", (531, 561), False, 'import os\n'), ((583, 634), 'os.path.join', 'os.path.join', (['inpath', '"""soc-pokec-relationships.txt"""'], {}), "(inpath, 'soc-pokec-relationships.txt')\n", (595, 634), False, 'import os\n'), ((1301, 1316), 'numpy.array', 'np.array', (['edges'], {}), '(edges)\n', (1309, 1316), True, 'import numpy as np\n'), ((1440, 1486), 'numpy.zeros', 'np.zeros', (['(targets.shape[1],)'], {'dtype': '"""float64"""'}), "((targets.shape[1],), dtype='float64')\n", (1448, 1486), True, 'import numpy as np\n'), ((1850, 1896), 'numpy.zeros', 'np.zeros', (['(targets.shape[1],)'], {'dtype': '"""float64"""'}), "((targets.shape[1],), dtype='float64')\n", (1858, 1896), True, 'import numpy as np\n'), ((2099, 2120), 'convert.spadj2edgelist', 'spadj2edgelist', (['spadj'], {}), '(spadj)\n', (2113, 2120), False, 'from convert import make_adjacency, make_sparse_adjacency, save_problem, spadj2edgelist\n'), ((2140, 2161), 'convert.spadj2edgelist', 'spadj2edgelist', (['spadj'], {}), '(spadj)\n', (2154, 2161), False, 'from convert import make_adjacency, make_sparse_adjacency, save_problem, spadj2edgelist\n'), ((1156, 1174), 'numpy.array', 'np.array', (['ages.age'], {}), '(ages.age)\n', (1164, 1174), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Sun Jan 19 21:43:37 2020 @author: acer """ import numpy as np import sys import csv import argparse def step1(dec_matrix): sqrtSum=np.sqrt(np.sum(np.square(dec_matrix),axis=0)) dec_matrix=dec_matrix/sqrtSum return (dec_matrix) def step2(dec_matrix,weights): return dec_matrix*weights def step3a(dec_matrix,impact): col=len(dec_matrix[0]) row=len(dec_matrix) minValues=np.min(dec_matrix, axis=0) maxValues=np.max(dec_matrix, axis=0) idealSol=np.zeros((1,col)) for i in range(0,col): if(impact[i]==1): idealSol[0][i]=maxValues[i] else: idealSol[0][i]=minValues[i] return idealSol def step3b(dec_matrix,impact): col=len(dec_matrix[0]) row=len(dec_matrix) minValues=np.min(dec_matrix, axis=0) maxValues=np.max(dec_matrix, axis=0) negIdealSol=np.zeros((1,col)) for i in range(0,col): if(impact[i]==1): negIdealSol[0][i]=minValues[i] else: negIdealSol[0][i]=maxValues[i] return negIdealSol def step4a(idealSol,dec_matrix): return np.sqrt(np.sum(np.square(dec_matrix-idealSol),axis=1)) def step4b(negIdealSol,dec_matrix): return np.sqrt(np.sum(np.square(dec_matrix-negIdealSol),axis=1)) def step5(idealSol,negIdealSol): return (negIdealSol)/(idealSol+negIdealSol) def topsisCalc(dec_matrix,weights,impacts): dec_matrix=step1(dec_matrix) dec_matrix=step2(dec_matrix,weights) idealSol=step3a(dec_matrix,impacts) negIdealSol=step3b(dec_matrix,impacts) eucIdeal=step4a(idealSol,dec_matrix) eucNonIdeal=step4b(negIdealSol,dec_matrix) relClos=step5(eucIdeal,eucNonIdeal) print("BEST DECISION: ",max(relClos),"\n") print("WORST DECISION: ",min(relClos),"\n") def main(args): filename = args['InputDataFile'] try: f = open(filename, 'r') except IOError: print ("There was an error reading", filename) sys.exit() file = csv.reader(f) data = list(file) data=np.array(data) data=np.array(data[1:,1:],dtype=float) x=data n=np.size(x,1) m=np.size(x,0) try: weights = np.array(args['Weights'][0].split(','),dtype=float) except ValueError: print ("Incorrect value(s) in Weight vector") sys.exit() if(len(weights) != n): print("Incorrect input size for Weights vector") sys.exit(0) try: impacts = args['Impacts'][0].split(',') except ValueError: print ("Incorrect value(s) in Impacts vector") sys.exit() if(len(impacts) != n): print("Incorrect input size for Impacts vector") sys.exit(0) topsisCalc(x,weights,impacts) # driver code if __name__ == "__main__": # parse command line arguments parser = argparse.ArgumentParser() parser.add_argument("InputDataFile", help="Enter the name of CSV file with .csv extention",type=str) parser.add_argument("Weights", nargs=1, help="Enter the weight vector comma separated" ,type=str) parser.add_argument("Impacts", nargs=1, help="Enter the impact vector comma separated",type=str) args = parser.parse_args() main(vars(args)) '''m=[[7,9,9,8],[8,7,8,7],[9,6,8,9],[6,7,8,6]] w=[0.1,.4,.3,.2] i=[1,1,1,0] topsisCalc(m,w,i) m=step1(m) print(m) w=[0.1,.4,.3,.2] m=step2(m,w) print(m) i=[1,1,1,0] ideal=step3a(m,i) neg=step3b(m,i) print(ideal) print(neg) anspos=step4a(ideal,m) print(anspos) ansneg=step4b(neg,m) print(ansneg) relClos=step5(anspos,ansneg) print(relClos)'''
[ "numpy.size", "csv.reader", "argparse.ArgumentParser", "numpy.square", "numpy.zeros", "numpy.min", "numpy.max", "numpy.array", "sys.exit" ]
[((439, 465), 'numpy.min', 'np.min', (['dec_matrix'], {'axis': '(0)'}), '(dec_matrix, axis=0)\n', (445, 465), True, 'import numpy as np\n'), ((481, 507), 'numpy.max', 'np.max', (['dec_matrix'], {'axis': '(0)'}), '(dec_matrix, axis=0)\n', (487, 507), True, 'import numpy as np\n'), ((526, 544), 'numpy.zeros', 'np.zeros', (['(1, col)'], {}), '((1, col))\n', (534, 544), True, 'import numpy as np\n'), ((816, 842), 'numpy.min', 'np.min', (['dec_matrix'], {'axis': '(0)'}), '(dec_matrix, axis=0)\n', (822, 842), True, 'import numpy as np\n'), ((858, 884), 'numpy.max', 'np.max', (['dec_matrix'], {'axis': '(0)'}), '(dec_matrix, axis=0)\n', (864, 884), True, 'import numpy as np\n'), ((906, 924), 'numpy.zeros', 'np.zeros', (['(1, col)'], {}), '((1, col))\n', (914, 924), True, 'import numpy as np\n'), ((2025, 2038), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (2035, 2038), False, 'import csv\n'), ((2070, 2084), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (2078, 2084), True, 'import numpy as np\n'), ((2094, 2129), 'numpy.array', 'np.array', (['data[1:, 1:]'], {'dtype': 'float'}), '(data[1:, 1:], dtype=float)\n', (2102, 2129), True, 'import numpy as np\n'), ((2155, 2168), 'numpy.size', 'np.size', (['x', '(1)'], {}), '(x, 1)\n', (2162, 2168), True, 'import numpy as np\n'), ((2174, 2187), 'numpy.size', 'np.size', (['x', '(0)'], {}), '(x, 0)\n', (2181, 2187), True, 'import numpy as np\n'), ((2898, 2923), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2921, 2923), False, 'import argparse\n'), ((2467, 2478), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2475, 2478), False, 'import sys\n'), ((2745, 2756), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2753, 2756), False, 'import sys\n'), ((191, 212), 'numpy.square', 'np.square', (['dec_matrix'], {}), '(dec_matrix)\n', (200, 212), True, 'import numpy as np\n'), ((1165, 1197), 'numpy.square', 'np.square', (['(dec_matrix - idealSol)'], {}), '(dec_matrix - idealSol)\n', (1174, 1197), True, 'import numpy as np\n'), ((1268, 1303), 'numpy.square', 'np.square', (['(dec_matrix - negIdealSol)'], {}), '(dec_matrix - negIdealSol)\n', (1277, 1303), True, 'import numpy as np\n'), ((1999, 2009), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2007, 2009), False, 'import sys\n'), ((2359, 2369), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2367, 2369), False, 'import sys\n'), ((2637, 2647), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2645, 2647), False, 'import sys\n')]
from __future__ import print_function import cv2 import numpy as np import os import tkFileDialog, tkMessageBox def lin_regress(x, y): A = np.vstack([x]).T return np.linalg.lstsq(A, y)[0] def get_track(filename): with open(filename, 'r') as f: lines = f.readlines() print(lines[0]) lines = np.array([ map(float, _.split(' ')[-5:]) for _ in lines[1:]]) return lines def click_and_drag(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: #refPt = [(x, y)] param[3] = x; param[4] = y; elif event == cv2.EVENT_MOUSEMOVE and flags>0: param[0] = int(round((x+param[3])/2.0)) param[1] = int(round((y+param[4])/2.0)) param[2] = np.sqrt((param[3]-x)**2+(param[4]-y)**2)/2 def get_tracker_parameters(footage_file): print("Click and drag on the image to select where the tracked ball is located and then press Enter") try: center_x_y_rad = np.zeros(5) cv2.namedWindow("footage") cv2.setMouseCallback("footage", click_and_drag, param = center_x_y_rad) cap = cv2.VideoCapture(footage_file) k = 0 while (cap.isOpened()): ret, frame = cap.read() if ret == True: frame = frame[:,:] cv2.circle(frame,( int(round(center_x_y_rad[0])), int(round(center_x_y_rad[1]))), int(round(center_x_y_rad[2]) ), color=(255)) cv2.imshow('footage', frame) k = cv2.waitKey(25) & 0xFF if k == ord('q'): break elif k==13: #enter pressed, success cap.release() center_x_y_rad[3:5] = frame.shape cv2.destroyWindow('footage') return center_x_y_rad else: cap.set(cv2.CAP_PROP_POS_FRAMES, 0) except Exception as e: print("Error in footage processing of {}".format(footage_file)) print(e.message) pass def save_tracking_params(ball_cx, ball_cy, ball_r, cxy_rad, cxy_tan, c_z): lines = [] config_filename = '..\\Config\\tracking.cfg' if os.path.exists(config_filename): with open(config_filename, 'r') as f: lines = f.readlines() else: #default values lines = """[camera settings] # if true, CameraSettingsFile will be loaded: LoadCameraSettings=true # file of the camera settings. The camera can be set up with the # Pylon viewer: CameraSettingsFile=Config/camera_settings.pfs # user defined name of the camera to use for ball tracking: TrackingCameraName=ball_cam [tracking settings] # These are the settings to extract optical flow from the frame # the circle bounding the tracked ball in frame coordinates: BallCenterX=112.0 BallCenterY=70.0 BallRadius=116.0 # These are the calibration constants, the factors scaling optical # flow in pixels to the ball rotation. [px/rad] CxyRad=100.31 CxyTan=76.85 Cz=20.63 """.split('\n') lines = map(lambda l: l+'\n', lines) #print(lines) for _ in range(len(lines)): if "BallCenterX" in lines[_]: lines[_] = "BallCenterX={}\n".format(ball_cx) if "BallCenterY" in lines[_]: lines[_] = "BallCenterY={}\n".format(ball_cy) if "BallRadius" in lines[_]: lines[_] = "BallRadius={}\n".format(ball_r) if "CxyRad" in lines[_]: lines[_] = "CxyRad={}\n".format(cxy_rad) if "CxyTan" in lines[_]: lines[_] = "CxyTan={}\n".format(cxy_tan) if "Cz" in lines[_]: lines[_] = "Cz={}\n".format(c_z) if os.path.exists(config_filename): os.remove(config_filename) with open(config_filename, "w+") as f: f.writelines(lines) def run_tracking(input_filename, parameters): tmp_cfg = 'tmp_track.cfg' tmp_track = '.'.join(input_filename.split('.')[:-1])+'.txt' for f in [tmp_cfg, tmp_track]: if os.path.exists(f): os.remove(f) with open(tmp_cfg, "w+") as f: f.write("""[tracking settings] BallCenterX={} BallCenterY={} BallRadius={} CxyRad=1.0 CxyTan=1.0 Cz=1.0 """.format(*parameters[:3])) os.system(r'..\BallFootageTracking.exe "{}" "{}" -c "{}" -q true'.format(input_filename, tmp_track, tmp_cfg)) if os.path.exists(tmp_cfg): os.remove(tmp_cfg) return tmp_track def main(): print("Welcome to the 2-camera calibration procedure") print("Select main (ball tracking) camera footage") tkMessageBox.showinfo("Select calibration footage", "Select the footage from the main tracking camera") main_footage_file = tkFileDialog.askopenfilename(initialfile="D:\\test.avi") main_track_params = get_tracker_parameters(main_footage_file) print('main: ', main_track_params) if main_track_params is not None: main_track_file = run_tracking(main_footage_file, main_track_params) else: print("Could not get tracking parameters") return print("Select secondary camera footage") tkMessageBox.showinfo("Select calibration footage", "Select the footage from the secondary camera") secondary_footage_file = tkFileDialog.askopenfilename(initialdir=main_footage_file) secondary_track_params = get_tracker_parameters(secondary_footage_file) print('secondary: ', secondary_track_params) if secondary_track_params is not None: secondary_track_file = run_tracking(secondary_footage_file, secondary_track_params) else: print("Could not get tracking parameters") return ''' Caluclating the calibration factors ''' main_track = get_track(main_track_file) secondary_track = get_track(secondary_track_file) fit_quality_threshold = np.mean(main_track[:, 0]) filter = np.where((np.abs(main_track[:, 0]) < fit_quality_threshold) & (np.abs(secondary_track[:, 0]) < fit_quality_threshold)) main_track, secondary_track = main_track[filter], secondary_track[filter] main_tracking_cam_resolution_h = main_track_params[3] secondary_tracking_cam_resolution_h = secondary_track_params[3] c_z = float(main_tracking_cam_resolution_h) / np.pi / 2.0 c_z_secondary = float(secondary_tracking_cam_resolution_h)/np.pi/2.0 rad_tan_ratio = lin_regress(main_track[:, 1], main_track[:, 2])[0] c = lin_regress(np.cos(main_track[:, 4]) * main_track[:, 2], secondary_track[:, 3])[0] c_xy_rad = np.abs(c_z_secondary/c) c_xy_tan = np.abs(c_xy_rad * rad_tan_ratio) #print(rad_tan_ratio) print(c_xy_rad, c_xy_tan, c_z) mbox = tkMessageBox.askquestion('Calibration complete. Save parameters?', 'Calibration complete. The factors found are: \nc_xy_rad={}\nc_xy_tan={}\n c_z={}\nSave them for VR application?'.format( c_xy_rad, c_xy_tan, c_z ), icon='info') if mbox == 'yes': save_tracking_params(main_track_params[0], main_track_params[1], main_track_params[2], c_xy_rad, c_xy_tan, c_z ) pass else: print("No :(") #secondary_footage_file = tkFileDialog.askopenfilename(initialdir=main_footage_file) #main_footage_file = 'D:\\test.avi' print(main_footage_file) pass if __name__=="__main__": main() print("Press any key to exit") #while cv2.waitKey(1) == 255: # pass
[ "os.remove", "numpy.abs", "numpy.linalg.lstsq", "cv2.waitKey", "os.path.exists", "numpy.zeros", "tkMessageBox.showinfo", "cv2.VideoCapture", "cv2.namedWindow", "numpy.mean", "cv2.setMouseCallback", "numpy.cos", "cv2.destroyWindow", "cv2.imshow", "tkFileDialog.askopenfilename", "numpy.vstack", "numpy.sqrt" ]
[((2243, 2274), 'os.path.exists', 'os.path.exists', (['config_filename'], {}), '(config_filename)\n', (2257, 2274), False, 'import os\n'), ((3728, 3759), 'os.path.exists', 'os.path.exists', (['config_filename'], {}), '(config_filename)\n', (3742, 3759), False, 'import os\n'), ((4397, 4420), 'os.path.exists', 'os.path.exists', (['tmp_cfg'], {}), '(tmp_cfg)\n', (4411, 4420), False, 'import os\n'), ((4602, 4709), 'tkMessageBox.showinfo', 'tkMessageBox.showinfo', (['"""Select calibration footage"""', '"""Select the footage from the main tracking camera"""'], {}), "('Select calibration footage',\n 'Select the footage from the main tracking camera')\n", (4623, 4709), False, 'import tkFileDialog, tkMessageBox\n'), ((4730, 4786), 'tkFileDialog.askopenfilename', 'tkFileDialog.askopenfilename', ([], {'initialfile': '"""D:\\\\test.avi"""'}), "(initialfile='D:\\\\test.avi')\n", (4758, 4786), False, 'import tkFileDialog, tkMessageBox\n'), ((5132, 5235), 'tkMessageBox.showinfo', 'tkMessageBox.showinfo', (['"""Select calibration footage"""', '"""Select the footage from the secondary camera"""'], {}), "('Select calibration footage',\n 'Select the footage from the secondary camera')\n", (5153, 5235), False, 'import tkFileDialog, tkMessageBox\n'), ((5261, 5319), 'tkFileDialog.askopenfilename', 'tkFileDialog.askopenfilename', ([], {'initialdir': 'main_footage_file'}), '(initialdir=main_footage_file)\n', (5289, 5319), False, 'import tkFileDialog, tkMessageBox\n'), ((5840, 5865), 'numpy.mean', 'np.mean', (['main_track[:, 0]'], {}), '(main_track[:, 0])\n', (5847, 5865), True, 'import numpy as np\n'), ((6518, 6543), 'numpy.abs', 'np.abs', (['(c_z_secondary / c)'], {}), '(c_z_secondary / c)\n', (6524, 6543), True, 'import numpy as np\n'), ((6557, 6589), 'numpy.abs', 'np.abs', (['(c_xy_rad * rad_tan_ratio)'], {}), '(c_xy_rad * rad_tan_ratio)\n', (6563, 6589), True, 'import numpy as np\n'), ((145, 159), 'numpy.vstack', 'np.vstack', (['[x]'], {}), '([x])\n', (154, 159), True, 'import numpy as np\n'), ((173, 194), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['A', 'y'], {}), '(A, y)\n', (188, 194), True, 'import numpy as np\n'), ((967, 978), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (975, 978), True, 'import numpy as np\n'), ((988, 1014), 'cv2.namedWindow', 'cv2.namedWindow', (['"""footage"""'], {}), "('footage')\n", (1003, 1014), False, 'import cv2\n'), ((1023, 1092), 'cv2.setMouseCallback', 'cv2.setMouseCallback', (['"""footage"""', 'click_and_drag'], {'param': 'center_x_y_rad'}), "('footage', click_and_drag, param=center_x_y_rad)\n", (1043, 1092), False, 'import cv2\n'), ((1110, 1140), 'cv2.VideoCapture', 'cv2.VideoCapture', (['footage_file'], {}), '(footage_file)\n', (1126, 1140), False, 'import cv2\n'), ((3769, 3795), 'os.remove', 'os.remove', (['config_filename'], {}), '(config_filename)\n', (3778, 3795), False, 'import os\n'), ((4056, 4073), 'os.path.exists', 'os.path.exists', (['f'], {}), '(f)\n', (4070, 4073), False, 'import os\n'), ((4430, 4448), 'os.remove', 'os.remove', (['tmp_cfg'], {}), '(tmp_cfg)\n', (4439, 4448), False, 'import os\n'), ((4087, 4099), 'os.remove', 'os.remove', (['f'], {}), '(f)\n', (4096, 4099), False, 'import os\n'), ((740, 790), 'numpy.sqrt', 'np.sqrt', (['((param[3] - x) ** 2 + (param[4] - y) ** 2)'], {}), '((param[3] - x) ** 2 + (param[4] - y) ** 2)\n', (747, 790), True, 'import numpy as np\n'), ((1529, 1557), 'cv2.imshow', 'cv2.imshow', (['"""footage"""', 'frame'], {}), "('footage', frame)\n", (1539, 1557), False, 'import cv2\n'), ((5889, 5913), 'numpy.abs', 'np.abs', (['main_track[:, 0]'], {}), '(main_track[:, 0])\n', (5895, 5913), True, 'import numpy as np\n'), ((5942, 5971), 'numpy.abs', 'np.abs', (['secondary_track[:, 0]'], {}), '(secondary_track[:, 0])\n', (5948, 5971), True, 'import numpy as np\n'), ((6431, 6455), 'numpy.cos', 'np.cos', (['main_track[:, 4]'], {}), '(main_track[:, 4])\n', (6437, 6455), True, 'import numpy as np\n'), ((1578, 1593), 'cv2.waitKey', 'cv2.waitKey', (['(25)'], {}), '(25)\n', (1589, 1593), False, 'import cv2\n'), ((1821, 1849), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""footage"""'], {}), "('footage')\n", (1838, 1849), False, 'import cv2\n')]
import os from PIL import Image import numpy as np import tensorflow as tf import matplotlib.pyplot as plt def read_ct_scan(folder_name): """Read the CT scan image files from directory""" images = [] # Construct path for two image file folders filepaths = [os.path.join(folder_name,file) for file in os.listdir(folder_name) if file != '.DS_Store'] # Read image file in each folder and convert them to RGB channel for file in filepaths: images.append(np.array(Image.open(file).convert('RGB'))) return images def get_metric_history(history): """Extract loss and metrics history from model's training history, and return as a list that has training and validation: 1. loss 2. accuracy 3. type I error 4. type II error """ keys = [key for key in history.history.keys()] loss=history.history[keys[0]] val_loss=history.history[keys[6]] acc = history.history[keys[1]] val_acc = history.history[keys[7]] false_pos = np.array(history.history[keys[2]]) true_pos = np.array(history.history[keys[3]]) false_negs = np.array(history.history[keys[4]]) true_negs = np.array(history.history[keys[5]]) val_false_pos = np.array(history.history[keys[8]]) val_true_pos = np.array(history.history[keys[9]]) val_false_negs = np.array(history.history[keys[10]]) val_true_negs = np.array(history.history[keys[11]]) type_1 = np.nan_to_num(false_pos/(false_pos+true_negs), nan=0) val_type_1 = np.nan_to_num(val_false_pos/(val_false_pos+val_true_negs)) type_2 = np.nan_to_num(false_negs/(false_negs+true_pos)) val_type_2 = np.nan_to_num(val_false_negs/(val_false_negs+val_true_pos)) metric_history = [loss, val_loss, acc, val_acc, type_1.tolist(), val_type_1.tolist(), type_2.tolist(), val_type_2.tolist()] return metric_history def plot_metric_history(metric_history): """Plot loss and metrics history""" epochs_range = range(len(metric_history[0])) plt.figure(figsize=(12, 10)) plt.subplot(2, 2, 1) plt.plot(epochs_range, metric_history[0], label='Training Loss') plt.plot(epochs_range, metric_history[1], '-', label='Validation Loss') plt.legend(loc='upper right') plt.title('Loss') plt.subplot(2, 2, 2) plt.plot(epochs_range, metric_history[2], label='Training Accuracy') plt.plot(epochs_range, metric_history[3], '-', label='Validation Accuracy') plt.legend(loc='lower right') plt.title('Accuracy') plt.subplot(2, 2, 3) plt.plot(epochs_range, metric_history[4], label='Training Type I Error') plt.plot(epochs_range, metric_history[5], '-', label='Validation Type I Error') plt.legend(loc='upper right') plt.title('Type I Error') plt.subplot(2, 2, 4) plt.plot(epochs_range, metric_history[6], label='Training Type II Error') plt.plot(epochs_range, metric_history[7], '-', label='Validation Type II Error') plt.legend(loc='upper right') plt.title('Type II Error') plt.show() return def resize_and_shuffle(X, y, img_size=(256,256), batch_size=32, seed=123, buffer_size=500): """Resize image files to equal height and width of IMG_SIZE, Convert data to tensorflow.data.Dataset objects with random shuffle and batches """ results = list(map(lambda img: tf.image.resize(img, img_size), X)) results = tf.data.Dataset.from_tensor_slices((results, y)) ds = results.shuffle(len(y)).batch(batch_size) return ds def label_predictions(predictions): predictions = predictions.reshape(len(predictions)) mask = predictions > 0.5 predictions = np.full(len(predictions), 'NonCOVID') predictions[mask] = 'COVID' return(predictions.tolist())
[ "matplotlib.pyplot.title", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "numpy.nan_to_num", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "tensorflow.data.Dataset.from_tensor_slices", "PIL.Image.open", "matplotlib.pyplot.figure", "numpy.array", "tensorflow.image.resize", "os.path.join", "os.listdir" ]
[((1033, 1067), 'numpy.array', 'np.array', (['history.history[keys[2]]'], {}), '(history.history[keys[2]])\n', (1041, 1067), True, 'import numpy as np\n'), ((1083, 1117), 'numpy.array', 'np.array', (['history.history[keys[3]]'], {}), '(history.history[keys[3]])\n', (1091, 1117), True, 'import numpy as np\n'), ((1135, 1169), 'numpy.array', 'np.array', (['history.history[keys[4]]'], {}), '(history.history[keys[4]])\n', (1143, 1169), True, 'import numpy as np\n'), ((1186, 1220), 'numpy.array', 'np.array', (['history.history[keys[5]]'], {}), '(history.history[keys[5]])\n', (1194, 1220), True, 'import numpy as np\n'), ((1242, 1276), 'numpy.array', 'np.array', (['history.history[keys[8]]'], {}), '(history.history[keys[8]])\n', (1250, 1276), True, 'import numpy as np\n'), ((1296, 1330), 'numpy.array', 'np.array', (['history.history[keys[9]]'], {}), '(history.history[keys[9]])\n', (1304, 1330), True, 'import numpy as np\n'), ((1352, 1387), 'numpy.array', 'np.array', (['history.history[keys[10]]'], {}), '(history.history[keys[10]])\n', (1360, 1387), True, 'import numpy as np\n'), ((1408, 1443), 'numpy.array', 'np.array', (['history.history[keys[11]]'], {}), '(history.history[keys[11]])\n', (1416, 1443), True, 'import numpy as np\n'), ((1458, 1515), 'numpy.nan_to_num', 'np.nan_to_num', (['(false_pos / (false_pos + true_negs))'], {'nan': '(0)'}), '(false_pos / (false_pos + true_negs), nan=0)\n', (1471, 1515), True, 'import numpy as np\n'), ((1529, 1591), 'numpy.nan_to_num', 'np.nan_to_num', (['(val_false_pos / (val_false_pos + val_true_negs))'], {}), '(val_false_pos / (val_false_pos + val_true_negs))\n', (1542, 1591), True, 'import numpy as np\n'), ((1602, 1653), 'numpy.nan_to_num', 'np.nan_to_num', (['(false_negs / (false_negs + true_pos))'], {}), '(false_negs / (false_negs + true_pos))\n', (1615, 1653), True, 'import numpy as np\n'), ((1667, 1730), 'numpy.nan_to_num', 'np.nan_to_num', (['(val_false_negs / (val_false_negs + val_true_pos))'], {}), '(val_false_negs / (val_false_negs + val_true_pos))\n', (1680, 1730), True, 'import numpy as np\n'), ((2046, 2074), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 10)'}), '(figsize=(12, 10))\n', (2056, 2074), True, 'import matplotlib.pyplot as plt\n'), ((2079, 2099), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (2090, 2099), True, 'import matplotlib.pyplot as plt\n'), ((2104, 2168), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs_range', 'metric_history[0]'], {'label': '"""Training Loss"""'}), "(epochs_range, metric_history[0], label='Training Loss')\n", (2112, 2168), True, 'import matplotlib.pyplot as plt\n'), ((2173, 2244), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs_range', 'metric_history[1]', '"""-"""'], {'label': '"""Validation Loss"""'}), "(epochs_range, metric_history[1], '-', label='Validation Loss')\n", (2181, 2244), True, 'import matplotlib.pyplot as plt\n'), ((2249, 2278), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (2259, 2278), True, 'import matplotlib.pyplot as plt\n'), ((2283, 2300), 'matplotlib.pyplot.title', 'plt.title', (['"""Loss"""'], {}), "('Loss')\n", (2292, 2300), True, 'import matplotlib.pyplot as plt\n'), ((2310, 2330), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (2321, 2330), True, 'import matplotlib.pyplot as plt\n'), ((2335, 2403), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs_range', 'metric_history[2]'], {'label': '"""Training Accuracy"""'}), "(epochs_range, metric_history[2], label='Training Accuracy')\n", (2343, 2403), True, 'import matplotlib.pyplot as plt\n'), ((2408, 2483), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs_range', 'metric_history[3]', '"""-"""'], {'label': '"""Validation Accuracy"""'}), "(epochs_range, metric_history[3], '-', label='Validation Accuracy')\n", (2416, 2483), True, 'import matplotlib.pyplot as plt\n'), ((2488, 2517), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (2498, 2517), True, 'import matplotlib.pyplot as plt\n'), ((2522, 2543), 'matplotlib.pyplot.title', 'plt.title', (['"""Accuracy"""'], {}), "('Accuracy')\n", (2531, 2543), True, 'import matplotlib.pyplot as plt\n'), ((2549, 2569), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(3)'], {}), '(2, 2, 3)\n', (2560, 2569), True, 'import matplotlib.pyplot as plt\n'), ((2574, 2646), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs_range', 'metric_history[4]'], {'label': '"""Training Type I Error"""'}), "(epochs_range, metric_history[4], label='Training Type I Error')\n", (2582, 2646), True, 'import matplotlib.pyplot as plt\n'), ((2651, 2730), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs_range', 'metric_history[5]', '"""-"""'], {'label': '"""Validation Type I Error"""'}), "(epochs_range, metric_history[5], '-', label='Validation Type I Error')\n", (2659, 2730), True, 'import matplotlib.pyplot as plt\n'), ((2735, 2764), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (2745, 2764), True, 'import matplotlib.pyplot as plt\n'), ((2769, 2794), 'matplotlib.pyplot.title', 'plt.title', (['"""Type I Error"""'], {}), "('Type I Error')\n", (2778, 2794), True, 'import matplotlib.pyplot as plt\n'), ((2800, 2820), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(4)'], {}), '(2, 2, 4)\n', (2811, 2820), True, 'import matplotlib.pyplot as plt\n'), ((2825, 2898), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs_range', 'metric_history[6]'], {'label': '"""Training Type II Error"""'}), "(epochs_range, metric_history[6], label='Training Type II Error')\n", (2833, 2898), True, 'import matplotlib.pyplot as plt\n'), ((2903, 2988), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs_range', 'metric_history[7]', '"""-"""'], {'label': '"""Validation Type II Error"""'}), "(epochs_range, metric_history[7], '-', label='Validation Type II Error'\n )\n", (2911, 2988), True, 'import matplotlib.pyplot as plt\n'), ((2988, 3017), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (2998, 3017), True, 'import matplotlib.pyplot as plt\n'), ((3022, 3048), 'matplotlib.pyplot.title', 'plt.title', (['"""Type II Error"""'], {}), "('Type II Error')\n", (3031, 3048), True, 'import matplotlib.pyplot as plt\n'), ((3053, 3063), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3061, 3063), True, 'import matplotlib.pyplot as plt\n'), ((3413, 3461), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['(results, y)'], {}), '((results, y))\n', (3447, 3461), True, 'import tensorflow as tf\n'), ((280, 311), 'os.path.join', 'os.path.join', (['folder_name', 'file'], {}), '(folder_name, file)\n', (292, 311), False, 'import os\n'), ((323, 346), 'os.listdir', 'os.listdir', (['folder_name'], {}), '(folder_name)\n', (333, 346), False, 'import os\n'), ((3363, 3393), 'tensorflow.image.resize', 'tf.image.resize', (['img', 'img_size'], {}), '(img, img_size)\n', (3378, 3393), True, 'import tensorflow as tf\n'), ((503, 519), 'PIL.Image.open', 'Image.open', (['file'], {}), '(file)\n', (513, 519), False, 'from PIL import Image\n')]
import numpy as np from torchnlp.datasets import imdb_dataset # run pip install pytorch-nlp if you dont have this from tamnun.bert import BertClassifier, BertVectorizer from sklearn.pipeline import make_pipeline from sklearn.metrics import classification_report # Getting data train_data, test_data = imdb_dataset(train=True, test=True) # Each instance in the dataset is a dict with `text` and `sentiment`, we extract those fields and create two variables train_texts, train_labels = list(zip(*map(lambda d: (d['text'], d['sentiment']), train_data))) test_texts, test_labels = list(zip(*map(lambda d: (d['text'], d['sentiment']), test_data))) # Convert label to boolean train_y = np.array(train_labels) == 'pos' test_y = np.array(test_labels) == 'pos' print('Train size:', len(train_texts)) print('Test size:', len(test_texts)) # Create a pipeline with the vectorizer and the classifier and then fit it on the raw data print('Fine-tuning BERT...') clf = make_pipeline(BertVectorizer(do_truncate=True), BertClassifier(num_of_classes=2, lr=1e-5)).fit(train_texts, train_y) predicted = clf.predict(test_texts) print(classification_report(predicted, test_y))
[ "torchnlp.datasets.imdb_dataset", "tamnun.bert.BertVectorizer", "sklearn.metrics.classification_report", "tamnun.bert.BertClassifier", "numpy.array" ]
[((302, 337), 'torchnlp.datasets.imdb_dataset', 'imdb_dataset', ([], {'train': '(True)', 'test': '(True)'}), '(train=True, test=True)\n', (314, 337), False, 'from torchnlp.datasets import imdb_dataset\n'), ((683, 705), 'numpy.array', 'np.array', (['train_labels'], {}), '(train_labels)\n', (691, 705), True, 'import numpy as np\n'), ((724, 745), 'numpy.array', 'np.array', (['test_labels'], {}), '(test_labels)\n', (732, 745), True, 'import numpy as np\n'), ((1140, 1180), 'sklearn.metrics.classification_report', 'classification_report', (['predicted', 'test_y'], {}), '(predicted, test_y)\n', (1161, 1180), False, 'from sklearn.metrics import classification_report\n'), ((973, 1005), 'tamnun.bert.BertVectorizer', 'BertVectorizer', ([], {'do_truncate': '(True)'}), '(do_truncate=True)\n', (987, 1005), False, 'from tamnun.bert import BertClassifier, BertVectorizer\n'), ((1027, 1069), 'tamnun.bert.BertClassifier', 'BertClassifier', ([], {'num_of_classes': '(2)', 'lr': '(1e-05)'}), '(num_of_classes=2, lr=1e-05)\n', (1041, 1069), False, 'from tamnun.bert import BertClassifier, BertVectorizer\n')]
import numpy as np import time import sys from ServoMotor import * from fns import * # Initialize motor control library & USB Port filename = "/dev/ttyUSB0" motor = ServoMotor(filename) IO = motor.IO_Init() if IO < 0: print('IO exit') sys.exit() # Call corresponding function to convert sim2real/real2sim def convFns(pos, convType): conv = [left_armpit, left_elbow, left_shoulder, right_armpit, right_elbow, right_shoulder, left_armpit, left_elbow, left_shoulder, right_armpit, right_elbow, right_shoulder] targ = np.zeros(12) for i in range(len(pos)): if i==0: targ[i] = conv[i](pos[i], convType, "front") elif i==6: targ[i] = conv[i](pos[i], convType, "back") else: targ[i] = conv[i](pos[i], convType) return targ # Define next action given parameters def act(t, p0, p1, p2, p3, p4, p5, p6, p7, p8): # front shoulder (+p1) f_s = p0 * np.sin(t * p8) # front elbow (+p3) f_e = p2 * np.sin(t * p8) # back shoulder (+p5) b_s = p4 * np.sin(t * p8) # back elbow (+p7) b_e = p6 * np.sin(t * p8) desired_p = np.array([0, f_s+p1, f_e+p3, 0, -f_s+p1, -f_e+p3, 0, -b_s+p5, -b_e+p7, 0, b_s+p5, b_e+p7]) # return desired new position return convFns(desired_p, "sim2real") # Return position to take def get_action(steps): #params = np.array(np.load('params/best_overall_5.npy')) params = np.array([0.15, 0.0, 0.15, 0.0, 0.2, 0.15, 0.2, 0.15, 0.21]) # Smooth Criminal, Jul 31 19:00 return act(steps, *params) # MOVE MOTOR TO GIVEN POSITION def walk(pos): h = 0 real_pos = [] for j in range(1,5): u = 10*j r = range(u, u+3) for i in r: real_pos.append(motor.readPosition(i)) motor.move(i, int(pos[h]), 0) h+=1 time.sleep(0.005) return real_pos # Initialize motors as servos and set offset offsets = [30, 0, 64, 0, 70, 50, 26, 0, 55, 80, 90, 35] h = 0 # Set servo mode to all servos with their offset for j in range(1,5): u = 10*j r = range(u, u+3) for i in r: motor.setServoMode(i) if offsets[h]!=0: motor.setPositionOffset(i,offsets[h]) h+=1 # RESET position and stand down & up before walking pos = [500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500] h = 0 for j in range(1,5): u = 10*j r = range(u, u+3) for i in r: motor.move(i, int(pos[h]), 1500) h+=1 time.sleep(3) pos = [500, 750, 583, 500, 250, 417, 500, 750, 583, 500, 250, 417] #pos = get_action(0) h = 0 for j in range(1,5): u = 10*j r = range(u, u+3) for i in r: if h>5: motor.move(i, int(pos[h]), 1000) else: motor.move(i, int(pos[h]), 1500) h+=1 time.sleep(3) # Determine need to smoothen transition to first position pos_prev = [500, 750, 583, 500, 250, 417, 500, 750, 583, 500, 250, 417] pos = get_action(0) delta_pos = abs(pos-pos_prev) steps = int(max(delta_pos)/15) m = [] for i in range(len(pos)): m.append(np.linspace(pos_prev[i], pos[i], steps)) m_t = np.array(m).T.tolist() for i in range(len(m_t)): for j in range(len(m_t[0])): m_t[i][j] = int(round(m_t[i][j])) # If smoothing is needed, perform actions for i in m_t: real_pos = walk(i) # WALK j = 1 while j < 300: # Get target position pos = get_action(j) # Move robot to target position real_pos = walk(pos) j += 1 # RESET position and stand down & up before walking pos = [500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500] h = 0 for j in range(1,5): u = 10*j r = range(u, u+3) for i in r: motor.move(i, int(pos[h]), 1500) h+=1
[ "numpy.zeros", "time.sleep", "numpy.sin", "numpy.array", "numpy.linspace", "sys.exit" ]
[((2243, 2256), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (2253, 2256), False, 'import time\n'), ((2511, 2524), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (2521, 2524), False, 'import time\n'), ((238, 248), 'sys.exit', 'sys.exit', ([], {}), '()\n', (246, 248), False, 'import sys\n'), ((524, 536), 'numpy.zeros', 'np.zeros', (['(12)'], {}), '(12)\n', (532, 536), True, 'import numpy as np\n'), ((1040, 1151), 'numpy.array', 'np.array', (['[0, f_s + p1, f_e + p3, 0, -f_s + p1, -f_e + p3, 0, -b_s + p5, -b_e + p7, 0,\n b_s + p5, b_e + p7]'], {}), '([0, f_s + p1, f_e + p3, 0, -f_s + p1, -f_e + p3, 0, -b_s + p5, -\n b_e + p7, 0, b_s + p5, b_e + p7])\n', (1048, 1151), True, 'import numpy as np\n'), ((1321, 1381), 'numpy.array', 'np.array', (['[0.15, 0.0, 0.15, 0.0, 0.2, 0.15, 0.2, 0.15, 0.21]'], {}), '([0.15, 0.0, 0.15, 0.0, 0.2, 0.15, 0.2, 0.15, 0.21])\n', (1329, 1381), True, 'import numpy as np\n'), ((866, 880), 'numpy.sin', 'np.sin', (['(t * p8)'], {}), '(t * p8)\n', (872, 880), True, 'import numpy as np\n'), ((914, 928), 'numpy.sin', 'np.sin', (['(t * p8)'], {}), '(t * p8)\n', (920, 928), True, 'import numpy as np\n'), ((964, 978), 'numpy.sin', 'np.sin', (['(t * p8)'], {}), '(t * p8)\n', (970, 978), True, 'import numpy as np\n'), ((1011, 1025), 'numpy.sin', 'np.sin', (['(t * p8)'], {}), '(t * p8)\n', (1017, 1025), True, 'import numpy as np\n'), ((1665, 1682), 'time.sleep', 'time.sleep', (['(0.005)'], {}), '(0.005)\n', (1675, 1682), False, 'import time\n'), ((2780, 2819), 'numpy.linspace', 'np.linspace', (['pos_prev[i]', 'pos[i]', 'steps'], {}), '(pos_prev[i], pos[i], steps)\n', (2791, 2819), True, 'import numpy as np\n'), ((2827, 2838), 'numpy.array', 'np.array', (['m'], {}), '(m)\n', (2835, 2838), True, 'import numpy as np\n')]
import numpy # ############################################################### # # ############################################################### THRESHOLD = 0.00001 AREA_THRESHOLD = 0.01 def fequal(x1, x2, threshold=THRESHOLD): d = x1 - x2 if d < 0.0: d *= -1.0 if threshold >= d: return True else: return False def area_equal(a1, a2, threshold=AREA_THRESHOLD): return fequal(a1, a2, threshold) # ############################################################### # # ############################################################### class Vertex: def __init__(self, x, y): self._vertex = [0.0, 0.0] self._vertex[0] = x self._vertex[1] = y def __str__(self): return '[{}, {}]'.format(self._vertex[0], self._vertex[1]) @property def x(self): return self._vertex[0] @x.setter def x(self, value): self._vertex[0] = value @property def y(self): return self._vertex[1] @y.setter def y(self, value): self._vertex[1] = value def __eq__(self, b): result = True if not fequal(self.x, b.x): result = False if not fequal(self.y, b.y): result = False return result def is_higher_than(self, q): if self.x < q.x and self.y >= q.y: return True else: return False # ############################################################### # # ############################################################### class Points(object): def __init__(self): self._order = [] self._points = [] self._i = 0 def __add_point_from_vertex(self, n): if self._points: h = self._points[0] if n.y > h.y or (n.y == h.y and n.x < h.x): self._points[0] = n n = h self._points.append(n) def length(self): return len(self._points) def add_point(self, *args): if isinstance(args[0], Vertex): self.__add_point_from_vertex(args[0]) elif isinstance(args[0], float) and isinstance(args[1], float): n = Vertex(args[0], args[1]) self.__add_point_from_vertex(n) else: raise ValueError() def get_point(self, i): if self._order: return self._points[self._order[i]] else: return self._points[i] def __getitem__(self, key): return self.get_point(key) def permute(self): p = numpy.random.permutation(len(self._points)) l = list(p) l.remove(0) l.insert(0,0) self._order = l def highest(self): return self.get_point(0) def __iter__(self): self._i = 0 return self def __next__(self): if self._i >= len(self._points): raise StopIteration() i = self._i self._i += 1 return self.get_point(i) # ############################################################### # # ############################################################### class DagNode: def __init__(self): self._children = None def is_leaf(self): if self._children is None: return True else: return False @property def children(self): return self._children def add_child(self, value): if not issubclass(value, DagNode): raise ValueError() if self._children: self._children.append(value) else: self._children = [value] # ############################################################### # # ############################################################### def are_pts_ccw(pts): a = pts[0] b = pts[1] c = pts[2] det = (b.x - a.x) * (c.y - a.y) \ - (c.x - a.x) * (b.y - a.y) if det > 0.0: return True else: return False def is_higher(a, b): if a.y > b.y or (a.y == b.y and a.x < b.x): return True else: return False def order_pt(a, b, c): pts = [] if is_higher(a, b): if is_higher(a, c): pts = [a, b, c] else: pts = [c, a, b] else: if is_higher(b, c): pts = [b, c, a] else: pts = [c, a, b] if are_pts_ccw(pts): return pts else: return [pts[0], pts[2], pts[1]] def area_of_triangle(a,b,c): area = ( a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) )/ 2.0 if area < 0.0: return -area else: return area def adjacent_triangle_edges(t1,t2): adj_edges = None uni_edges = None if t1.a == t2.a and t1.b == t2.b: adj_edges = (t1.a, t1.b, t2.a, t2.b) uni_edges = (t1.c, t2.c) elif t1.a == t2.a and t1.b == t2.c: adj_edges = (t1.a, t1.b, t2.a, t2.c) uni_edges = (t1.c, t2.b) elif t1.a == t2.a and t1.c == t2.b: adj_edges = (t1.a, t1.c, t2.a, t2.b) uni_edges = (t1.b, t2.b) elif t1.a == t2.a and t1.c == t2.c: adj_edges = (t1.a, t1.c, t2.a, t2.c) uni_edges = (t1.b, t2.b) elif t1.a == t2.b and t1.b == t2.a: adj_edges = (t1.a, t1.b, t2.b, t2.a) uni_edges = (t1.c, t2.c) elif t1.a == t2.b and t1.b == t2.c: adj_edges = (t1.a, t1.b, t2.b, t2.c) uni_edges = (t1.c, t2.a) elif t1.a == t2.b and t1.c == t2.a: adj_edges = (t1.a, t1.c, t2.b, t2.a) uni_edges = (t1.b, t2.c) elif t1.a == t2.b and t1.c == t2.c: adj_edges = (t1.a, t1.c, t2.b, t2.c) uni_edges = (t1.b, t2.a) elif t1.a == t2.c and t1.b == t2.a: adj_edges = (t1.a, t1.b, t2.c, t2.a) uni_edges = (t1.c, t2.b) elif t1.a == t2.c and t1.b == t2.b: adj_edges = (t1.a, t1.b, t2.c, t2.b) uni_edges = (t1.c, t2.a) elif t1.a == t2.c and t1.c == t2.a: adj_edges = (t1.a, t1.c, t2.c, t2.a) uni_edges = (t1.b, t2.b) elif t1.a == t2.c and t1.c == t2.b: adj_edges = (t1.a, t1.c, t2.c, t2.b) uni_edges = (t1.b, t2.a) elif t1.b == t2.a and t1.c == t2.b: adj_edges = (t1.b, t1.c, t2.a, t2.b) uni_edges = (t1.a, t2.c) elif t1.b == t2.a and t1.c == t2.c: adj_edges = (t1.b, t1.c, t2.a, t2.c) uni_edges = (t1.a, t2.b) elif t1.b == t2.b and t1.c == t2.a: adj_edges = (t1.b, t1.c, t2.b, t2.a) uni_edges = (t1.a, t2.c) elif t1.b == t2.b and t1.c == t2.c: adj_edges = (t1.b, t1.c, t2.b, t2.c) uni_edges = (t1.a, t2.a) elif t1.b == t2.c and t1.c == t2.a: adj_edges = (t1.b, t1.c, t2.c, t2.a) uni_edges = (t1.a, t2.b) elif t1.b == t2.c and t1.c == t2.b: adj_edges = (t1.b, t1.c, t2.c, t2.b) uni_edges = (t1.a, t2.a) else: adj_edges = None uni_edges = None return (adj_edges, uni_edges) def are_triangles_adjacent(t1,t2): result = False if t1.a == t2.a and t1.b == t2.b: result = True elif t1.a == t2.a and t1.b == t2.c: result = True elif t1.a == t2.a and t1.c == t2.b: result = True elif t1.a == t2.a and t1.c == t2.c: result = True elif t1.a == t2.b and t1.b == t2.a: result = True elif t1.a == t2.b and t1.b == t2.c: result = True elif t1.a == t2.b and t1.c == t2.a: result = True elif t1.a == t2.b and t1.c == t2.c: result = True elif t1.a == t2.c and t1.b == t2.a: result = True elif t1.a == t2.c and t1.b == t2.b: result = True elif t1.a == t2.c and t1.c == t2.a: result = True elif t1.a == t2.c and t1.c == t2.b: result = True elif t1.b == t2.a and t1.c == t2.b: result = True elif t1.b == t2.a and t1.c == t2.c: result = True elif t1.b == t2.b and t1.c == t2.a: result = True elif t1.b == t2.b and t1.c == t2.c: result = True elif t1.b == t2.c and t1.c == t2.a: result = True elif t1.b == t2.c and t1.c == t2.b: result = True else: result = False return result # ############################################################### # # ############################################################### class Triangle(DagNode): def __init__(self, a, b, c): DagNode.__init__(self) self._points = order_pts(a, b, c) @property def a(self): return self._points[0] @property def b(self): return self._points[1] @property def c(self): return self._points[2] def area(self): a = area_of_triangle(self.a, self.b, self.c) if area_equal(a, 0.0): return 0.0 else: return a def is_adjacent(self, b): return are_triangles_adjacent(self, b) # ############################################################### # # ############################################################### def is_triangle_area_zero(a, b, c): a = area_of_triangle(a, b, c) if area_equal(a, 0.0): return True else: return False def is_pt_on_edge(p, t): on_edge = False a1 = area_of_triangle(t.a, t.b, p) if area_equal(a1, 0.0): on_edge = True a2 = area_of_triangle(t.b, t.c, p) if area_equal(a2, 0.0): on_edge = True a3 = area_of_triangle(t.c, t.a, p) if area_equal(a3, 0.0): on_edge = True return on_edge def is_pt_inside_triangle(p, t): if t.b == None and t.c == None: # This is the first triangle that contains all points return True a1 = area_of_triangle(t.a, t.b, p) a2 = area_of_triangle(t.b, t.c, p) a3 = area_of_triangle(t.c, t.a, p) a = area_of_triangle(t.a, t.b, t.c) inside = fequal(a, a1+a2+a3) return inside def is_pt_inside_triangle2(p, t): x = p.x y = p.y x1 = t.a.x y1 = t.a.y x2 = t.b.x y2 = t.b.y x3 = t.c.x y3 = t.c.y denom = (x1 * (y2 - y3) + y1 * (x3 - x2) + x2 * y3 - y2 * x3) t1 = (x * (y3 - y1) + y * (x1 - x3) - x1 * y3 + y1 * x3) / denom t2 = (x * (y2 - y1) + y * (x1 - x2) - x1 * y2 + y1 * x2) / -denom if 0.0 <= t1 <= 1.0 and 0.0 <= t2 <= 1.0 and t1 + t2 <= 1.0: return True else: return False # ############################################################### # # ############################################################### def circle_for_points(a, b, c): x1 = a.x y1 = a.y x2 = b.x y2 = b.y x3 = c.x y3 = c.y X2 = (x2-x1) X3 = (x3-x1) Y2 = (y2-y1) Y3 = (y3-y1) alpha = X3 / X2 bx2 = (x2+x1) * X2 bx3 = (x3+x1) * X3 by2 = (y2+y1) * Y2 by3 = (y3+y1) * Y3 h = 0.0 k = 0.0 r = 0.0 k = bx3 + by3 - alpha * (bx2 + by2) k /= 2 * (Y3 - alpha * Y2) h = bx2 + by2 - 2 * k * Y2 h /= 2 * X2 r = numpy.sqrt( (x1 - h)*(x1 - h) + (y1 - k)*(y1 - k) ) return h, k, r def in_circle(t, pr): x, y, r = circle_for_points(t.points[0], t.points[1], t.points[2]) x_diff = pr.x - x y_diff = pr.y - y dist = numpy.sqrt(x_diff**2 + y_diff**2) if dist <= r: return True else: return False
[ "numpy.sqrt" ]
[((11063, 11116), 'numpy.sqrt', 'numpy.sqrt', (['((x1 - h) * (x1 - h) + (y1 - k) * (y1 - k))'], {}), '((x1 - h) * (x1 - h) + (y1 - k) * (y1 - k))\n', (11073, 11116), False, 'import numpy\n'), ((11289, 11326), 'numpy.sqrt', 'numpy.sqrt', (['(x_diff ** 2 + y_diff ** 2)'], {}), '(x_diff ** 2 + y_diff ** 2)\n', (11299, 11326), False, 'import numpy\n')]
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.3 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Materials # # This test showcases rendering with various materials provided by Lightmetrica. We render the images using ``renderer::pt``. # %load_ext autoreload # %autoreload 2 import lmenv env = lmenv.load('.lmenv') import os import pickle import json import numpy as np import matplotlib.pyplot as plt import lightmetrica as lm # %load_ext lightmetrica_jupyter import lmscene lm.init() lm.log.init('jupyter') lm.progress.init('jupyter') lm.info() lm.comp.load_plugin(os.path.join(env.bin_path, 'accel_embree')) if not lm.Release: lm.parallel.init('openmp', num_threads=1) lm.debug.attach_to_debugger() # + def render(scene, name, **kwargs): w = 854 h = 480 film = lm.load_film('film', 'bitmap', w=w, h=h) renderer = lm.load_renderer('renderer', name, scene=scene, output=film, max_verts=20, scheduler='time', render_time=30, **kwargs) renderer.render() return np.copy(film.buffer()) def display_image(img, fig_size=15, scale=1): f = plt.figure(figsize=(fig_size,fig_size)) ax = f.add_subplot(111) ax.imshow(np.clip(np.power(img*scale,1/2.2),0,1), origin='lower') ax.axis('off') plt.show() # - # ## Scene setup # Create scene accel = lm.load_accel('accel', 'embree') scene = lm.load_scene('scene', 'default', accel=accel) mat = lm.load_material('mat_ut', 'diffuse', Kd=[1,1,1]) lmscene.bunny_with_area_light(scene, env.scene_path, mat_knob=mat) scene.build() # ## Rendering # ### Diffse material # # `material::diffuse` lm.load_material('mat_ut', 'diffuse', Kd=[.8,.2,.2]) img = render(scene, 'pt') display_image(img) # ### Glossy material # # `material::glossy` lm.load_material('mat_ut', 'glossy', Ks=[.8,.2,.2], ax=0.2, ay=0.2) img = render(scene, 'pt') display_image(img) # ### Perfect specular reflection # # `material::mirror` lm.load_material('mat_ut', 'mirror') img = render(scene, 'pt') display_image(img) # ### Fresnel reflection / refraction # # `material::fresnel` lm.load_material('mat_ut', 'glass', Ni=1.5) img = render(scene, 'pt') display_image(img) # ### Mixture material with constant weights using RR # # `material::constant_weight_mixture_rr` mat_diffuse = lm.load_material('mat_diffuse', 'diffuse', Kd=[.1,.8,.1]) mat_glossy = lm.load_material('mat_glossy', 'glossy', Ks=[.8,.1,.1], ax=0.2, ay=0.2) mat_mirror = lm.load_material('mat_mirror', 'mirror') mat = lm.load_material('mat_ut', 'constant_weight_mixture_rr', [ {'material': mat_diffuse.loc(), 'weight': 0.2}, {'material': mat_glossy.loc(), 'weight': 0.4}, {'material': mat_mirror.loc(), 'weight': 0.4} ]) img = render(scene, 'pt') display_image(img) # ### Mixture material with constant weights using marginalization # # `material::constant_weight_mixture_marginalized` mat = lm.load_material('mat_ut', 'constant_weight_mixture_marginalized', [ {'material': mat_diffuse.loc(), 'weight': 0.2}, {'material': mat_glossy.loc(), 'weight': 0.4}, {'material': mat_mirror.loc(), 'weight': 0.4} ]) img = render(scene, 'pt') display_image(img) # ### Mixture material with alpha texture # # `material::mixture_wavefrontobj` # # This material is the default material converted from MTL format of Wavefront OBJ. tex = lm.load_texture('tex', 'bitmap', path=os.path.join(env.scene_path, 'fireplace_room', 'textures', 'leaf.png')) lm.load_material('mat_ut', 'mixture_wavefrontobj', Kd=[.8,.8,.8], mapKd=tex, Ks=[0,0,0], ax=0.2, ay=0.2, no_alpha_mask=False) img = render(scene, 'pt') display_image(img)
[ "lmscene.bunny_with_area_light", "lightmetrica.load_renderer", "matplotlib.pyplot.show", "lightmetrica.load_scene", "lightmetrica.load_film", "lightmetrica.progress.init", "numpy.power", "lightmetrica.init", "lightmetrica.load_accel", "lmenv.load", "lightmetrica.info", "matplotlib.pyplot.figure", "lightmetrica.debug.attach_to_debugger", "lightmetrica.log.init", "lightmetrica.load_material", "os.path.join", "lightmetrica.parallel.init" ]
[((497, 517), 'lmenv.load', 'lmenv.load', (['""".lmenv"""'], {}), "('.lmenv')\n", (507, 517), False, 'import lmenv\n'), ((681, 690), 'lightmetrica.init', 'lm.init', ([], {}), '()\n', (688, 690), True, 'import lightmetrica as lm\n'), ((691, 713), 'lightmetrica.log.init', 'lm.log.init', (['"""jupyter"""'], {}), "('jupyter')\n", (702, 713), True, 'import lightmetrica as lm\n'), ((714, 741), 'lightmetrica.progress.init', 'lm.progress.init', (['"""jupyter"""'], {}), "('jupyter')\n", (730, 741), True, 'import lightmetrica as lm\n'), ((742, 751), 'lightmetrica.info', 'lm.info', ([], {}), '()\n', (749, 751), True, 'import lightmetrica as lm\n'), ((1689, 1721), 'lightmetrica.load_accel', 'lm.load_accel', (['"""accel"""', '"""embree"""'], {}), "('accel', 'embree')\n", (1702, 1721), True, 'import lightmetrica as lm\n'), ((1730, 1776), 'lightmetrica.load_scene', 'lm.load_scene', (['"""scene"""', '"""default"""'], {'accel': 'accel'}), "('scene', 'default', accel=accel)\n", (1743, 1776), True, 'import lightmetrica as lm\n'), ((1783, 1834), 'lightmetrica.load_material', 'lm.load_material', (['"""mat_ut"""', '"""diffuse"""'], {'Kd': '[1, 1, 1]'}), "('mat_ut', 'diffuse', Kd=[1, 1, 1])\n", (1799, 1834), True, 'import lightmetrica as lm\n'), ((1833, 1899), 'lmscene.bunny_with_area_light', 'lmscene.bunny_with_area_light', (['scene', 'env.scene_path'], {'mat_knob': 'mat'}), '(scene, env.scene_path, mat_knob=mat)\n', (1862, 1899), False, 'import lmscene\n'), ((1978, 2035), 'lightmetrica.load_material', 'lm.load_material', (['"""mat_ut"""', '"""diffuse"""'], {'Kd': '[0.8, 0.2, 0.2]'}), "('mat_ut', 'diffuse', Kd=[0.8, 0.2, 0.2])\n", (1994, 2035), True, 'import lightmetrica as lm\n'), ((2123, 2195), 'lightmetrica.load_material', 'lm.load_material', (['"""mat_ut"""', '"""glossy"""'], {'Ks': '[0.8, 0.2, 0.2]', 'ax': '(0.2)', 'ay': '(0.2)'}), "('mat_ut', 'glossy', Ks=[0.8, 0.2, 0.2], ax=0.2, ay=0.2)\n", (2139, 2195), True, 'import lightmetrica as lm\n'), ((2295, 2331), 'lightmetrica.load_material', 'lm.load_material', (['"""mat_ut"""', '"""mirror"""'], {}), "('mat_ut', 'mirror')\n", (2311, 2331), True, 'import lightmetrica as lm\n'), ((2441, 2484), 'lightmetrica.load_material', 'lm.load_material', (['"""mat_ut"""', '"""glass"""'], {'Ni': '(1.5)'}), "('mat_ut', 'glass', Ni=1.5)\n", (2457, 2484), True, 'import lightmetrica as lm\n'), ((2643, 2705), 'lightmetrica.load_material', 'lm.load_material', (['"""mat_diffuse"""', '"""diffuse"""'], {'Kd': '[0.1, 0.8, 0.1]'}), "('mat_diffuse', 'diffuse', Kd=[0.1, 0.8, 0.1])\n", (2659, 2705), True, 'import lightmetrica as lm\n'), ((2714, 2790), 'lightmetrica.load_material', 'lm.load_material', (['"""mat_glossy"""', '"""glossy"""'], {'Ks': '[0.8, 0.1, 0.1]', 'ax': '(0.2)', 'ay': '(0.2)'}), "('mat_glossy', 'glossy', Ks=[0.8, 0.1, 0.1], ax=0.2, ay=0.2)\n", (2730, 2790), True, 'import lightmetrica as lm\n'), ((2799, 2839), 'lightmetrica.load_material', 'lm.load_material', (['"""mat_mirror"""', '"""mirror"""'], {}), "('mat_mirror', 'mirror')\n", (2815, 2839), True, 'import lightmetrica as lm\n'), ((3792, 3928), 'lightmetrica.load_material', 'lm.load_material', (['"""mat_ut"""', '"""mixture_wavefrontobj"""'], {'Kd': '[0.8, 0.8, 0.8]', 'mapKd': 'tex', 'Ks': '[0, 0, 0]', 'ax': '(0.2)', 'ay': '(0.2)', 'no_alpha_mask': '(False)'}), "('mat_ut', 'mixture_wavefrontobj', Kd=[0.8, 0.8, 0.8],\n mapKd=tex, Ks=[0, 0, 0], ax=0.2, ay=0.2, no_alpha_mask=False)\n", (3808, 3928), True, 'import lightmetrica as lm\n'), ((772, 814), 'os.path.join', 'os.path.join', (['env.bin_path', '"""accel_embree"""'], {}), "(env.bin_path, 'accel_embree')\n", (784, 814), False, 'import os\n'), ((839, 880), 'lightmetrica.parallel.init', 'lm.parallel.init', (['"""openmp"""'], {'num_threads': '(1)'}), "('openmp', num_threads=1)\n", (855, 880), True, 'import lightmetrica as lm\n'), ((885, 914), 'lightmetrica.debug.attach_to_debugger', 'lm.debug.attach_to_debugger', ([], {}), '()\n', (912, 914), True, 'import lightmetrica as lm\n'), ((991, 1031), 'lightmetrica.load_film', 'lm.load_film', (['"""film"""', '"""bitmap"""'], {'w': 'w', 'h': 'h'}), "('film', 'bitmap', w=w, h=h)\n", (1003, 1031), True, 'import lightmetrica as lm\n'), ((1047, 1169), 'lightmetrica.load_renderer', 'lm.load_renderer', (['"""renderer"""', 'name'], {'scene': 'scene', 'output': 'film', 'max_verts': '(20)', 'scheduler': '"""time"""', 'render_time': '(30)'}), "('renderer', name, scene=scene, output=film, max_verts=20,\n scheduler='time', render_time=30, **kwargs)\n", (1063, 1169), True, 'import lightmetrica as lm\n'), ((1325, 1365), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(fig_size, fig_size)'}), '(figsize=(fig_size, fig_size))\n', (1335, 1365), True, 'import matplotlib.pyplot as plt\n'), ((1630, 1640), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1638, 1640), True, 'import matplotlib.pyplot as plt\n'), ((3720, 3790), 'os.path.join', 'os.path.join', (['env.scene_path', '"""fireplace_room"""', '"""textures"""', '"""leaf.png"""'], {}), "(env.scene_path, 'fireplace_room', 'textures', 'leaf.png')\n", (3732, 3790), False, 'import os\n'), ((1559, 1589), 'numpy.power', 'np.power', (['(img * scale)', '(1 / 2.2)'], {}), '(img * scale, 1 / 2.2)\n', (1567, 1589), True, 'import numpy as np\n')]
import face_recognition import cv2 import numpy as np from PIL import Image,ImageDraw import pickle all_face_encodings = {} shah_image = face_recognition.load_image_file("alexa.jpg") np.save("shah",shah_image) shah_encoding = face_recognition.face_encodings(shah_image)[0] np.save("shah-en",shah_encoding) all_face_encodings["shahrukhan"] = face_recognition.face_encodings(shah_image)[0] with open('dataset_sali1.dat', 'wb') as f: pickle.dump(all_face_encodings, f) known_face_encodings=[shah_encoding] print(type(known_face_encodings)) known_face_names=["joe"] test_image=face_recognition.load_image_file('stud2.jpeg') face_locations=face_recognition.face_locations(test_image) face_encodings = face_recognition.face_encodings(test_image,face_locations) pil_image=Image.fromarray(test_image) draw=ImageDraw.Draw(pil_image) for (top,right,bottom,left) ,face_encoding in zip(face_locations,face_encodings): matches=face_recognition.compare_faces(known_face_encodings,face_encoding) name="Unknown Person" if True in matches: first_match_index=matches.index(True) name=known_face_names[first_match_index] draw.rectangle(((left+2,top+2),(right+2,bottom+2)),outline=(0,255,255)) text_width,text_height=draw.textsize(name) draw.rectangle(((left,bottom-text_height-10),(right,bottom)),fill=(0,0,0),outline=(0,0,0)) draw.text((left+6,bottom-text_height-5),name,fill=(255,255,255,255)) del draw img = np.array(pil_image) img= cv2.cvtColor(img, cv2.COLOR_BGR2RGB) scale_percent = 60 # percent of original size width = int(img.shape[1] * scale_percent / 100) height = int(img.shape[0] * scale_percent / 100) dim = (width, height) img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) cv2.imshow("test",img) cv2.waitKey(0) cv2.destroyAllWindows()
[ "pickle.dump", "numpy.save", "face_recognition.compare_faces", "cv2.cvtColor", "cv2.waitKey", "face_recognition.face_encodings", "cv2.destroyAllWindows", "cv2.imshow", "PIL.ImageDraw.Draw", "numpy.array", "PIL.Image.fromarray", "face_recognition.face_locations", "face_recognition.load_image_file", "cv2.resize" ]
[((139, 184), 'face_recognition.load_image_file', 'face_recognition.load_image_file', (['"""alexa.jpg"""'], {}), "('alexa.jpg')\n", (171, 184), False, 'import face_recognition\n'), ((185, 212), 'numpy.save', 'np.save', (['"""shah"""', 'shah_image'], {}), "('shah', shah_image)\n", (192, 212), True, 'import numpy as np\n'), ((277, 310), 'numpy.save', 'np.save', (['"""shah-en"""', 'shah_encoding'], {}), "('shah-en', shah_encoding)\n", (284, 310), True, 'import numpy as np\n'), ((587, 633), 'face_recognition.load_image_file', 'face_recognition.load_image_file', (['"""stud2.jpeg"""'], {}), "('stud2.jpeg')\n", (619, 633), False, 'import face_recognition\n'), ((649, 692), 'face_recognition.face_locations', 'face_recognition.face_locations', (['test_image'], {}), '(test_image)\n', (680, 692), False, 'import face_recognition\n'), ((710, 769), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['test_image', 'face_locations'], {}), '(test_image, face_locations)\n', (741, 769), False, 'import face_recognition\n'), ((779, 806), 'PIL.Image.fromarray', 'Image.fromarray', (['test_image'], {}), '(test_image)\n', (794, 806), False, 'from PIL import Image, ImageDraw\n'), ((812, 837), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['pil_image'], {}), '(pil_image)\n', (826, 837), False, 'from PIL import Image, ImageDraw\n'), ((1450, 1469), 'numpy.array', 'np.array', (['pil_image'], {}), '(pil_image)\n', (1458, 1469), True, 'import numpy as np\n'), ((1475, 1511), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (1487, 1511), False, 'import cv2\n'), ((1683, 1733), 'cv2.resize', 'cv2.resize', (['img', 'dim'], {'interpolation': 'cv2.INTER_AREA'}), '(img, dim, interpolation=cv2.INTER_AREA)\n', (1693, 1733), False, 'import cv2\n'), ((1736, 1759), 'cv2.imshow', 'cv2.imshow', (['"""test"""', 'img'], {}), "('test', img)\n", (1746, 1759), False, 'import cv2\n'), ((1759, 1773), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (1770, 1773), False, 'import cv2\n'), ((1774, 1797), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1795, 1797), False, 'import cv2\n'), ((230, 273), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['shah_image'], {}), '(shah_image)\n', (261, 273), False, 'import face_recognition\n'), ((348, 391), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['shah_image'], {}), '(shah_image)\n', (379, 391), False, 'import face_recognition\n'), ((443, 477), 'pickle.dump', 'pickle.dump', (['all_face_encodings', 'f'], {}), '(all_face_encodings, f)\n', (454, 477), False, 'import pickle\n'), ((932, 999), 'face_recognition.compare_faces', 'face_recognition.compare_faces', (['known_face_encodings', 'face_encoding'], {}), '(known_face_encodings, face_encoding)\n', (962, 999), False, 'import face_recognition\n')]
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import torch from torch.utils.data.dataset import Dataset import cv2 import numpy as np from datasets.sensor import Sensor import os import sys import time import math import scipy.io CCM_NUS = {}#每相机的CCM校正矩阵 with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ccm', 'nus', 'canon_eos_1D_mark3.txt'), 'r') as f: CCM_NUS['canon_eos_1D_mark3'] = torch.FloatTensor(np.loadtxt(f)) with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ccm', 'nus', 'canon_eos_600D.txt'), 'r') as f: CCM_NUS['canon_eos_600D'] = torch.FloatTensor(np.loadtxt(f)) with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ccm', 'nus', 'fuji.txt'), 'r') as f: CCM_NUS['fuji'] = torch.FloatTensor(np.loadtxt(f)) with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ccm', 'nus', 'nikonD40.txt'), 'r') as f: CCM_NUS['nikonD40'] = torch.FloatTensor(np.loadtxt(f)) with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ccm', 'nus', 'nikonD5200.txt'), 'r') as f: CCM_NUS['nikonD5200'] = torch.FloatTensor(np.loadtxt(f)) with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ccm', 'nus', 'olympus.txt'), 'r') as f: CCM_NUS['olympus'] = torch.FloatTensor(np.loadtxt(f)) with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ccm', 'nus', 'panasonic.txt'), 'r') as f: CCM_NUS['panasonic'] = torch.FloatTensor(np.loadtxt(f)) with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ccm', 'nus', 'samsung.txt'), 'r') as f: CCM_NUS['samsung'] = torch.FloatTensor(np.loadtxt(f)) with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ccm', 'nus', 'sony.txt'), 'r') as f: CCM_NUS['sony'] = torch.FloatTensor(np.loadtxt(f)) class CanonEos1DMark3Sensor(Sensor): def __init__(self, black_level, saturation): super(CanonEos1DMark3Sensor, self).__init__(black_level, saturation, CCM_NUS['canon_eos_1D_mark3'], 'CanonEos1DMark3') class CanonEos600DSensor(Sensor): def __init__(self, black_level, saturation): super(CanonEos600DSensor, self).__init__(black_level, saturation, CCM_NUS['canon_eos_600D'], 'CanonEos600D') class FujiSensor(Sensor): def __init__(self, black_level, saturation): super(FujiSensor, self).__init__(black_level, saturation, CCM_NUS['fuji'], 'FujifilmXM1') class NikonD40Sensor(Sensor): def __init__(self, black_level, saturation): super(NikonD40Sensor, self).__init__(black_level, saturation, CCM_NUS['nikonD40'], 'NikonD40') class NikonD5200Sensor(Sensor): def __init__(self, black_level, saturation): super(NikonD5200Sensor, self).__init__(black_level, saturation, CCM_NUS['nikonD5200'], 'NikonD5200') class OlympusSensor(Sensor): def __init__(self, black_level, saturation): super(OlympusSensor, self).__init__(black_level, saturation, CCM_NUS['olympus'], 'OlympusEPL6') class PanasonicSensor(Sensor): def __init__(self, black_level, saturation): super(PanasonicSensor, self).__init__(black_level, saturation, CCM_NUS['panasonic'], 'PanasonicGX1') class SamsungSensor(Sensor): def __init__(self, black_level, saturation): super(SamsungSensor, self).__init__(black_level, saturation, CCM_NUS['samsung'], 'SamsungNX2000') class SonySensor(Sensor): def __init__(self, black_level, saturation): super(SonySensor, self).__init__(black_level, saturation, CCM_NUS['sony'], 'SonyA57') CAMERA_CLASS_NUS = {}#类成员 CAMERA_CLASS_NUS['canon_eos_1D_mark3'] = CanonEos1DMark3Sensor CAMERA_CLASS_NUS['canon_eos_600D'] = CanonEos600DSensor CAMERA_CLASS_NUS['fuji'] = FujiSensor CAMERA_CLASS_NUS['nikonD40'] = NikonD40Sensor CAMERA_CLASS_NUS['nikonD5200'] = NikonD5200Sensor CAMERA_CLASS_NUS['olympus'] = OlympusSensor CAMERA_CLASS_NUS['panasonic'] = PanasonicSensor CAMERA_CLASS_NUS['samsung'] = SamsungSensor CAMERA_CLASS_NUS['sony'] = SonySensor # NUS dataset: http://cvil.eecs.yorku.ca/projects/public_html/illuminant/illuminant.html class Nus(Dataset): def __init__(self, subdataset, data_conf, file, cache): self._rgbs = [] self._illuminants = []#按_rgbs顺序对应存储光源gt self._x = {} self._y = {} self._base_path = data_conf['nus_'+subdataset] if type(file) is list: for f in file: self._read_list(os.path.join(data_conf['base'], f)) else: self._read_list(os.path.join(data_conf['base'], file)) gt = scipy.io.loadmat(os.path.join(self._base_path, 'gt', 'gt.mat')) self._darkness_level = int(gt['darkness_level'][0][0]) self._saturation_level = int(gt['saturation_level'][0][0]) self._class_dataset = CAMERA_CLASS_NUS[subdataset] image_names = gt['all_image_names'].tolist() image_names = [e[0][0] for e in image_names] groundtruth_illuminants = gt['groundtruth_illuminants'] CC_coords = gt['CC_coords'] #按对应关系将光源取出 for i in range(len(self._rgbs)): basename_rgb = os.path.basename(self._rgbs[i].replace('.PNG', '')) index = image_names.index(basename_rgb) self._illuminants.append(groundtruth_illuminants[index, :]) self._cache = cache def get_filename(self, index): return self._rgbs[index] def get_illuminants(self): return self._illuminants def get_illuminants_by_sensor(self): dict = {self._class_dataset(None,None).camera_name: self._illuminants} return dict def _read_list(self, file): with open(file, 'r') as f: content = f.readlines() for line in content: filename = line.strip() rgb_path = os.path.join(self._base_path, 'PNG', filename) self._rgbs.append(rgb_path) txt = filename.replace('.PNG','_mask.txt') mask_path = os.path.join(self._base_path, 'mask', txt) with open(mask_path, 'r') as file_txt: coordinates = file_txt.readlines()[0].split(',') x = float(coordinates[0]) width = float(coordinates[2]) y = float(coordinates[1]) height = float(coordinates[3]) self._x[rgb_path] = [x, x+width, x+width, x] self._y[rgb_path] = [y, y, y+height, y+height] def get_rgb_by_path(self, filename): sensor = self._class_dataset(self._darkness_level, self._saturation_level) if self._cache.is_cached(filename): im, mask = self._cache.read(filename) else: im = cv2.imread(filename, -1) if im is None: raise Exception('File not found: ' + filename) im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) # get mask of valid pixels mask = np.ones(im.shape[:2], dtype = np.float32) rc = np.array((self._x[filename], self._y[filename])).T ctr = rc.reshape((-1,1,2)).astype(np.int32) cv2.drawContours(mask, [ctr], 0, 0, -1) # set CCB pixels to zero # TODO: ideally, downsampling should consider the mask # and then, apply the mask as a final step im[mask == 0] = [0, 0, 0] # rotate 90 degrees so that all images have the same resolution if im.shape[0] == 2820: im = cv2.transpose(im) im = cv2.flip(im, flipCode=0) mask = cv2.transpose(mask) mask = cv2.flip(mask, flipCode=0) self._cache.save(filename, (im, mask)) im = im[np.newaxis, ...] mask = mask[np.newaxis, ...] sensor = [sensor] return im, mask, sensor def get_rgb(self, index): path = self._rgbs[index] return self.get_rgb_by_path(path) def __getitem__(self, index): filename = self._rgbs[index] im, mask, sensor = self.get_rgb(index) illuminant = np.array(self._illuminants[index], dtype=np.float32) dict = {'rgb': im, 'sensor': sensor, 'mask': mask, 'illuminant': illuminant, 'path': filename} return dict def __len__(self): return len(self._rgbs) if __name__ == '__main__': import scipy import scipy.io #利用cv_metadata.mat做fold分割 path = 'data/nus/' camera = scipy.io.loadmat(os.path.join(path, 'cv_metadata.mat'))['cv_metadata'][0][0] cameras_list = ['canon_eos_1D_mark3', 'canon_eos_600D', 'fuji', 'nikonD40', 'nikonD5200', 'olympus', 'panasonic', 'samsung', 'sony'] camera_folds = [] for i in range(len(cameras_list)): camera_folds.append([[],[],[]]) for i in range(len(camera)): files = camera[i] for j in range(len(files)): file = files[j] filename = file[0][0][0] scene_idx = file[0][1][0][0] - 1 cv_fold = file[0][2][0][0] - 1 camera_folds[i][cv_fold].append(filename) for i in range(len(camera)): camera_name = cameras_list[i] with open(os.path.join(path, camera_name + '.txt'), 'w') as f: f.write('Nus\n') f.write('data/nus/splits/'+camera_name+'/fold1.txt\n') f.write('data/nus/splits/'+camera_name+'/fold2.txt\n') f.write('data/nus/splits/'+camera_name+'/fold3.txt\n') for fold in range(3): camera_folder = os.path.join(path, 'splits', camera_name) os.makedirs(camera_folder, exist_ok=True) with open(os.path.join(camera_folder, 'fold'+str(fold+1)+'.txt'), 'w') as f: files = camera_folds[i][fold] for file in files: f.write(file+'\n')
[ "os.makedirs", "cv2.cvtColor", "os.path.realpath", "numpy.ones", "cv2.transpose", "cv2.flip", "cv2.imread", "numpy.array", "numpy.loadtxt", "cv2.drawContours", "os.path.join" ]
[((944, 957), 'numpy.loadtxt', 'np.loadtxt', (['f'], {}), '(f)\n', (954, 957), True, 'import numpy as np\n'), ((1126, 1139), 'numpy.loadtxt', 'np.loadtxt', (['f'], {}), '(f)\n', (1136, 1139), True, 'import numpy as np\n'), ((1288, 1301), 'numpy.loadtxt', 'np.loadtxt', (['f'], {}), '(f)\n', (1298, 1301), True, 'import numpy as np\n'), ((1458, 1471), 'numpy.loadtxt', 'np.loadtxt', (['f'], {}), '(f)\n', (1468, 1471), True, 'import numpy as np\n'), ((1632, 1645), 'numpy.loadtxt', 'np.loadtxt', (['f'], {}), '(f)\n', (1642, 1645), True, 'import numpy as np\n'), ((1800, 1813), 'numpy.loadtxt', 'np.loadtxt', (['f'], {}), '(f)\n', (1810, 1813), True, 'import numpy as np\n'), ((1972, 1985), 'numpy.loadtxt', 'np.loadtxt', (['f'], {}), '(f)\n', (1982, 1985), True, 'import numpy as np\n'), ((2140, 2153), 'numpy.loadtxt', 'np.loadtxt', (['f'], {}), '(f)\n', (2150, 2153), True, 'import numpy as np\n'), ((2302, 2315), 'numpy.loadtxt', 'np.loadtxt', (['f'], {}), '(f)\n', (2312, 2315), True, 'import numpy as np\n'), ((8520, 8572), 'numpy.array', 'np.array', (['self._illuminants[index]'], {'dtype': 'np.float32'}), '(self._illuminants[index], dtype=np.float32)\n', (8528, 8572), True, 'import numpy as np\n'), ((5040, 5085), 'os.path.join', 'os.path.join', (['self._base_path', '"""gt"""', '"""gt.mat"""'], {}), "(self._base_path, 'gt', 'gt.mat')\n", (5052, 5085), False, 'import os\n'), ((7154, 7178), 'cv2.imread', 'cv2.imread', (['filename', '(-1)'], {}), '(filename, -1)\n', (7164, 7178), False, 'import cv2\n'), ((7287, 7322), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2RGB'], {}), '(im, cv2.COLOR_BGR2RGB)\n', (7299, 7322), False, 'import cv2\n'), ((7382, 7421), 'numpy.ones', 'np.ones', (['im.shape[:2]'], {'dtype': 'np.float32'}), '(im.shape[:2], dtype=np.float32)\n', (7389, 7421), True, 'import numpy as np\n'), ((7560, 7599), 'cv2.drawContours', 'cv2.drawContours', (['mask', '[ctr]', '(0)', '(0)', '(-1)'], {}), '(mask, [ctr], 0, 0, -1)\n', (7576, 7599), False, 'import cv2\n'), ((9993, 10034), 'os.path.join', 'os.path.join', (['path', '"""splits"""', 'camera_name'], {}), "(path, 'splits', camera_name)\n", (10005, 10034), False, 'import os\n'), ((10047, 10088), 'os.makedirs', 'os.makedirs', (['camera_folder'], {'exist_ok': '(True)'}), '(camera_folder, exist_ok=True)\n', (10058, 10088), False, 'import os\n'), ((809, 835), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (825, 835), False, 'import os\n'), ((999, 1025), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (1015, 1025), False, 'import os\n'), ((1181, 1207), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (1197, 1207), False, 'import os\n'), ((1343, 1369), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (1359, 1369), False, 'import os\n'), ((1513, 1539), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (1529, 1539), False, 'import os\n'), ((1687, 1713), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (1703, 1713), False, 'import os\n'), ((1855, 1881), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (1871, 1881), False, 'import os\n'), ((2027, 2053), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (2043, 2053), False, 'import os\n'), ((2195, 2221), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (2211, 2221), False, 'import os\n'), ((4970, 5007), 'os.path.join', 'os.path.join', (["data_conf['base']", 'file'], {}), "(data_conf['base'], file)\n", (4982, 5007), False, 'import os\n'), ((6257, 6303), 'os.path.join', 'os.path.join', (['self._base_path', '"""PNG"""', 'filename'], {}), "(self._base_path, 'PNG', filename)\n", (6269, 6303), False, 'import os\n'), ((6436, 6478), 'os.path.join', 'os.path.join', (['self._base_path', '"""mask"""', 'txt'], {}), "(self._base_path, 'mask', txt)\n", (6448, 6478), False, 'import os\n'), ((7441, 7489), 'numpy.array', 'np.array', (['(self._x[filename], self._y[filename])'], {}), '((self._x[filename], self._y[filename]))\n', (7449, 7489), True, 'import numpy as np\n'), ((7932, 7949), 'cv2.transpose', 'cv2.transpose', (['im'], {}), '(im)\n', (7945, 7949), False, 'import cv2\n'), ((7971, 7995), 'cv2.flip', 'cv2.flip', (['im'], {'flipCode': '(0)'}), '(im, flipCode=0)\n', (7979, 7995), False, 'import cv2\n'), ((8019, 8038), 'cv2.transpose', 'cv2.transpose', (['mask'], {}), '(mask)\n', (8032, 8038), False, 'import cv2\n'), ((8062, 8088), 'cv2.flip', 'cv2.flip', (['mask'], {'flipCode': '(0)'}), '(mask, flipCode=0)\n', (8070, 8088), False, 'import cv2\n'), ((9651, 9691), 'os.path.join', 'os.path.join', (['path', "(camera_name + '.txt')"], {}), "(path, camera_name + '.txt')\n", (9663, 9691), False, 'import os\n'), ((4892, 4926), 'os.path.join', 'os.path.join', (["data_conf['base']", 'f'], {}), "(data_conf['base'], f)\n", (4904, 4926), False, 'import os\n'), ((8919, 8956), 'os.path.join', 'os.path.join', (['path', '"""cv_metadata.mat"""'], {}), "(path, 'cv_metadata.mat')\n", (8931, 8956), False, 'import os\n')]
import pygame as pg import math import numpy as np _BLACK = (0, 0, 0) _DARK_GRAY = (40, 40, 40) _GRAY = (100, 100, 100) _WHITE = (255, 255, 255) draw_speed = 60 clock = pg.time.Clock() class Cube: def __init__(self, surface, color, position, rotation, scale): self.surface = surface self.color = color self.position = position self.rotation = rotation self.scale = scale # Relative to center-point # Top-left # Top-Right # Bottom-Left # Bottom-Right self.vertices = np.array( [[self.position[0] - self.scale[0] / 2, self.position[1] - self.scale[1] / 2, self.position[2] - self.scale[2] / 2], [self.position[0] + self.scale[0] / 2, self.position[1] - self.scale[1] / 2, self.position[2] - self.scale[2] / 2], [self.position[0] - self.scale[0] / 2, self.position[1] + self.scale[1] / 2, self.position[2] - self.scale[2] / 2], [self.position[0] + self.scale[0] / 2, self.position[1] + self.scale[1] / 2, self.position[2] - self.scale[2] / 2], [self.position[0] - self.scale[0] / 2, self.position[1] - self.scale[1] / 2, self.position[2] / 2 + self.scale[2] / 2], [self.position[0] + self.scale[0] / 2, self.position[1] - self.scale[1] / 2, self.position[2] / 2 + self.scale[2] / 2], [self.position[0] - self.scale[0] / 2, self.position[1] + self.scale[1] / 2, self.position[2] / 2 + self.scale[2] / 2], [self.position[0] + self.scale[0] / 2, self.position[1] + self.scale[1] / 2, self.position[2] / 2 + self.scale[2] / 2]] ) self.rotate_x(90 - self.rotation[0]) self.rotate_y(90 - self.rotation[1]) self.rotate_z(90 - self.rotation[2]) def rotate_z(self, degrees): for ind, _ in enumerate(self.vertices): r_x = self.vertices[ind, 0] - self.position[0] r_y = self.vertices[ind, 1] - self.position[1] r = math.hypot(r_x, r_y) theta = math.atan2(r_y, r_x) + math.radians(degrees) self.vertices[ind, 0] = self.position[0] + r * math.cos(theta) self.vertices[ind, 1] = self.position[1] + r * math.sin(theta) def rotate_y(self, degrees): for ind, _ in enumerate(self.vertices): r_x = self.vertices[ind, 0] - self.position[0] r_z = self.vertices[ind, 2] - self.position[2] r = math.hypot(r_x, r_z) theta = math.atan2(r_x, r_z) + math.radians(degrees) self.vertices[ind, 0] = self.position[0] + r * math.cos(theta) self.vertices[ind, 2] = self.position[2] + r * math.sin(theta) def rotate_x(self, degrees): for ind, _ in enumerate(self.vertices): r_y = self.vertices[ind, 1] - self.position[1] r_z = self.vertices[ind, 2] - self.position[2] r = math.hypot(r_y, r_z) theta = math.atan2(r_y, r_z) - math.radians(degrees) self.vertices[ind, 1] = self.position[1] + r * math.cos(theta) self.vertices[ind, 2] = self.position[2] + r * math.sin(theta) def render_points(self, point_radius): for x, y, z in sorted(self.vertices, key=lambda x:x[2]): pg.draw.circle(self.surface, np.interp([z, z, z], [-10, 10], [0, 255]), (x, y), point_radius) cube_surfaces = np.array( [[0, 1, 3, 2], [4, 5, 7, 6], [0, 4, 6, 2], [1, 5, 7, 3], [0, 4, 5, 1], [2, 6, 7, 3]] ) surfaces = np.array([self.vertices[i] for i in [surface for surface in cube_surfaces]]) for surface in sorted(surfaces, key=lambda x:np.mean(x, axis=0)[2]): mean_z = np.mean(surface, axis=0)[2] pg.draw.polygon(self.surface, np.interp([mean_z, mean_z, mean_z], [-20, 20], [0, 255]), [vertex[:2] for vertex in surface]) def setup(): display_width = 500 display_height = 500 pg.init() dis = pg.display.set_mode((display_width, display_height)) pg.display.set_caption('Pseudo-3D') dis.fill(_BLACK) pg.display.update() loop(dis) def loop(dis): running = True x = 0 y = 0 z = 0 while running: for event in pg.event.get(): if event.type == pg.QUIT: running=False dis.fill(_BLACK) pressed = pg.key.get_pressed() if pressed[pg.K_w]: y += 1 if pressed[pg.K_s]: y -= 1 if pressed[pg.K_d]: x += 1 if pressed[pg.K_a]: x -= 1 if pressed[pg.K_q]: z += 1 if pressed[pg.K_e]: z -= 1 cube = Cube(dis, _WHITE, (100, 100, 0), (x, y, z), (50, 50, 50)) cube.render_points(3) clock.tick(draw_speed) pg.display.flip() pg.quit() if __name__=='__main__': setup()
[ "pygame.quit", "math.hypot", "math.atan2", "pygame.event.get", "pygame.display.set_mode", "math.radians", "pygame.init", "pygame.display.flip", "math.sin", "pygame.display.update", "numpy.mean", "numpy.array", "math.cos", "numpy.interp", "pygame.display.set_caption", "pygame.time.Clock", "pygame.key.get_pressed" ]
[((171, 186), 'pygame.time.Clock', 'pg.time.Clock', ([], {}), '()\n', (184, 186), True, 'import pygame as pg\n'), ((3981, 3990), 'pygame.init', 'pg.init', ([], {}), '()\n', (3988, 3990), True, 'import pygame as pg\n'), ((4001, 4053), 'pygame.display.set_mode', 'pg.display.set_mode', (['(display_width, display_height)'], {}), '((display_width, display_height))\n', (4020, 4053), True, 'import pygame as pg\n'), ((4058, 4093), 'pygame.display.set_caption', 'pg.display.set_caption', (['"""Pseudo-3D"""'], {}), "('Pseudo-3D')\n", (4080, 4093), True, 'import pygame as pg\n'), ((4120, 4139), 'pygame.display.update', 'pg.display.update', ([], {}), '()\n', (4137, 4139), True, 'import pygame as pg\n'), ((4861, 4870), 'pygame.quit', 'pg.quit', ([], {}), '()\n', (4868, 4870), True, 'import pygame as pg\n'), ((565, 1580), 'numpy.array', 'np.array', (['[[self.position[0] - self.scale[0] / 2, self.position[1] - self.scale[1] / \n 2, self.position[2] - self.scale[2] / 2], [self.position[0] + self.\n scale[0] / 2, self.position[1] - self.scale[1] / 2, self.position[2] - \n self.scale[2] / 2], [self.position[0] - self.scale[0] / 2, self.\n position[1] + self.scale[1] / 2, self.position[2] - self.scale[2] / 2],\n [self.position[0] + self.scale[0] / 2, self.position[1] + self.scale[1] /\n 2, self.position[2] - self.scale[2] / 2], [self.position[0] - self.\n scale[0] / 2, self.position[1] - self.scale[1] / 2, self.position[2] / \n 2 + self.scale[2] / 2], [self.position[0] + self.scale[0] / 2, self.\n position[1] - self.scale[1] / 2, self.position[2] / 2 + self.scale[2] /\n 2], [self.position[0] - self.scale[0] / 2, self.position[1] + self.\n scale[1] / 2, self.position[2] / 2 + self.scale[2] / 2], [self.position\n [0] + self.scale[0] / 2, self.position[1] + self.scale[1] / 2, self.\n position[2] / 2 + self.scale[2] / 2]]'], {}), '([[self.position[0] - self.scale[0] / 2, self.position[1] - self.\n scale[1] / 2, self.position[2] - self.scale[2] / 2], [self.position[0] +\n self.scale[0] / 2, self.position[1] - self.scale[1] / 2, self.position[\n 2] - self.scale[2] / 2], [self.position[0] - self.scale[0] / 2, self.\n position[1] + self.scale[1] / 2, self.position[2] - self.scale[2] / 2],\n [self.position[0] + self.scale[0] / 2, self.position[1] + self.scale[1] /\n 2, self.position[2] - self.scale[2] / 2], [self.position[0] - self.\n scale[0] / 2, self.position[1] - self.scale[1] / 2, self.position[2] / \n 2 + self.scale[2] / 2], [self.position[0] + self.scale[0] / 2, self.\n position[1] - self.scale[1] / 2, self.position[2] / 2 + self.scale[2] /\n 2], [self.position[0] - self.scale[0] / 2, self.position[1] + self.\n scale[1] / 2, self.position[2] / 2 + self.scale[2] / 2], [self.position\n [0] + self.scale[0] / 2, self.position[1] + self.scale[1] / 2, self.\n position[2] / 2 + self.scale[2] / 2]])\n', (573, 1580), True, 'import numpy as np\n'), ((3370, 3468), 'numpy.array', 'np.array', (['[[0, 1, 3, 2], [4, 5, 7, 6], [0, 4, 6, 2], [1, 5, 7, 3], [0, 4, 5, 1], [2, \n 6, 7, 3]]'], {}), '([[0, 1, 3, 2], [4, 5, 7, 6], [0, 4, 6, 2], [1, 5, 7, 3], [0, 4, 5,\n 1], [2, 6, 7, 3]])\n', (3378, 3468), True, 'import numpy as np\n'), ((3572, 3648), 'numpy.array', 'np.array', (['[self.vertices[i] for i in [surface for surface in cube_surfaces]]'], {}), '([self.vertices[i] for i in [surface for surface in cube_surfaces]])\n', (3580, 3648), True, 'import numpy as np\n'), ((4262, 4276), 'pygame.event.get', 'pg.event.get', ([], {}), '()\n', (4274, 4276), True, 'import pygame as pg\n'), ((4391, 4411), 'pygame.key.get_pressed', 'pg.key.get_pressed', ([], {}), '()\n', (4409, 4411), True, 'import pygame as pg\n'), ((4839, 4856), 'pygame.display.flip', 'pg.display.flip', ([], {}), '()\n', (4854, 4856), True, 'import pygame as pg\n'), ((1986, 2006), 'math.hypot', 'math.hypot', (['r_x', 'r_y'], {}), '(r_x, r_y)\n', (1996, 2006), False, 'import math\n'), ((2439, 2459), 'math.hypot', 'math.hypot', (['r_x', 'r_z'], {}), '(r_x, r_z)\n', (2449, 2459), False, 'import math\n'), ((2892, 2912), 'math.hypot', 'math.hypot', (['r_y', 'r_z'], {}), '(r_y, r_z)\n', (2902, 2912), False, 'import math\n'), ((2027, 2047), 'math.atan2', 'math.atan2', (['r_y', 'r_x'], {}), '(r_y, r_x)\n', (2037, 2047), False, 'import math\n'), ((2050, 2071), 'math.radians', 'math.radians', (['degrees'], {}), '(degrees)\n', (2062, 2071), False, 'import math\n'), ((2480, 2500), 'math.atan2', 'math.atan2', (['r_x', 'r_z'], {}), '(r_x, r_z)\n', (2490, 2500), False, 'import math\n'), ((2503, 2524), 'math.radians', 'math.radians', (['degrees'], {}), '(degrees)\n', (2515, 2524), False, 'import math\n'), ((2933, 2953), 'math.atan2', 'math.atan2', (['r_y', 'r_z'], {}), '(r_y, r_z)\n', (2943, 2953), False, 'import math\n'), ((2956, 2977), 'math.radians', 'math.radians', (['degrees'], {}), '(degrees)\n', (2968, 2977), False, 'import math\n'), ((3280, 3321), 'numpy.interp', 'np.interp', (['[z, z, z]', '[-10, 10]', '[0, 255]'], {}), '([z, z, z], [-10, 10], [0, 255])\n', (3289, 3321), True, 'import numpy as np\n'), ((3748, 3772), 'numpy.mean', 'np.mean', (['surface'], {'axis': '(0)'}), '(surface, axis=0)\n', (3755, 3772), True, 'import numpy as np\n'), ((3818, 3874), 'numpy.interp', 'np.interp', (['[mean_z, mean_z, mean_z]', '[-20, 20]', '[0, 255]'], {}), '([mean_z, mean_z, mean_z], [-20, 20], [0, 255])\n', (3827, 3874), True, 'import numpy as np\n'), ((2132, 2147), 'math.cos', 'math.cos', (['theta'], {}), '(theta)\n', (2140, 2147), False, 'import math\n'), ((2207, 2222), 'math.sin', 'math.sin', (['theta'], {}), '(theta)\n', (2215, 2222), False, 'import math\n'), ((2585, 2600), 'math.cos', 'math.cos', (['theta'], {}), '(theta)\n', (2593, 2600), False, 'import math\n'), ((2660, 2675), 'math.sin', 'math.sin', (['theta'], {}), '(theta)\n', (2668, 2675), False, 'import math\n'), ((3038, 3053), 'math.cos', 'math.cos', (['theta'], {}), '(theta)\n', (3046, 3053), False, 'import math\n'), ((3113, 3128), 'math.sin', 'math.sin', (['theta'], {}), '(theta)\n', (3121, 3128), False, 'import math\n'), ((3703, 3721), 'numpy.mean', 'np.mean', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (3710, 3721), True, 'import numpy as np\n')]
import torch import torch.autograd from torch.autograd import Variable import torch.optim as optim import torch.nn as nn import numpy as np import scipy as sp import scipy.linalg from qpsolvers import solve_qp from core.DDPG import DDPGagent from core.ConstraintNetwork import ConstraintNetwork class SafeDDPGagent(DDPGagent): def __init__(self, state_dim, act_dim, constraint_dim, num_agents, constraint_networks_dir, col_margin = 0.35 , hidden_size=256, actor_learning_rate=1e-4, critic_learning_rate=1e-3, gamma=0.99, tau=1e-2, max_memory_size=16000, soften = True): # Call DDPGagent's constructor super().__init__(state_dim, act_dim, num_agents ,hidden_size, actor_learning_rate, critic_learning_rate, gamma, tau, max_memory_size) # Extra Params self.col_margin = col_margin self.constraint_dim = constraint_dim self.total_state_dim = self.state_dim * self.num_agents self.total_constraint_dim = self.constraint_dim * self.num_agents self.total_action_dim = self.act_dim * self.num_agents self.constraint_nets = self.total_constraint_dim*[None] # Initialize constraint networks for i in range(self.total_constraint_dim): self.constraint_nets[i] = ConstraintNetwork(self.total_state_dim, self.total_action_dim) self.constraint_nets[i].load_state_dict(torch.load(constraint_networks_dir + "constraint_net_" + str(i) + ".pkl")) # Define Solver Globaly self.solver_interventions = 0 self.solver_infeasible = 0 # Choose Solver if soften: self.correct_actions = self.correct_actions_soften else: self.correct_actions = self.correct_actions_hard def reset_metrics(self): self.solver_interventions = 0 self.solver_infeasible = 0 def get_interventions(self): return self.solver_interventions def get_infeasible(self): return self.solver_infeasible @torch.no_grad() def get_action(self, state, constraint): state = Variable(torch.from_numpy(state).float().unsqueeze(0)) action = self.actor(state) action = action.detach().numpy().flatten() # transform numpy array into list of 3 actions action = self.correct_actions(state, action, constraint) actions = np.split(action, self.num_agents) return actions @torch.no_grad() def correct_actions_hard(self, state, actions, constraint): # (1) Problem Variables # Problem specific constants I = np.eye(self.total_action_dim) ones = np.ones(self.total_action_dim) C = np.concatenate(constraint) # Formulate the constraints using neural networks G = np.zeros([self.total_action_dim, self.total_action_dim]) for i, net in enumerate(self.constraint_nets): G[i, :] = net(state).numpy() # (2) Problem Variables in QP form # Cost Function q = -actions P = np.eye(self.total_action_dim) # Constraints A = np.concatenate([-G, I, -I]) ub = np.concatenate([C - self.col_margin, ones, ones]) lb = None # Solve Optimization Problem try: x = solve_qp(P.astype(np.float64), q.astype(np.float64), A.astype(np.float64), ub.astype(np.float64), None, None, None, None) except: self.solver_infeasible +=1 return actions # Count Solver interventions if np.linalg.norm(actions - x) > 1e-3: self.solver_interventions += 1 return x @torch.no_grad() def correct_actions_soften(self, state, actions, constraint): # (1) Create solver as a globar variable l1_penalty = 1000 # (2) Problem Variables # Problem specific constants I = np.eye(self.total_action_dim) Z = np.zeros([self.total_action_dim, self.total_action_dim]) ones = np.ones(self.total_action_dim) zeros = np.zeros(self.total_action_dim) C = np.concatenate(constraint) - self.col_margin # Formulate the constraints using neural networks G = np.zeros([self.total_action_dim, self.total_action_dim]) for i, net in enumerate(self.constraint_nets): G[i, :] = net(state).numpy() # (2) Problem Variables in QP form # Cost Function P = sp.linalg.block_diag(I, Z + I * 0.001, Z + I * 0.001) q = np.concatenate([-actions, ones, zeros]) # Constraints A = np.vstack((np.concatenate([-G, Z, -I], axis = 1), np.concatenate([Z, Z, -I], axis = 1), np.concatenate([Z, -I, l1_penalty * I], axis = 1), np.concatenate([Z, -I, -l1_penalty * I], axis = 1))) ub = np.concatenate((C, zeros, zeros, zeros)) lb = None # Solve Optimization Problem try: x = solve_qp(P.astype(np.float64), q.astype(np.float64), A.astype(np.float64), ub.astype(np.float64), None, None, None, None) x = x[0:(self.total_action_dim)] except: self.solver_infeasible +=1 return actions # Count Solver interventions if np.linalg.norm(actions - x) > 1e-3: self.solver_interventions += 1 return x
[ "core.ConstraintNetwork.ConstraintNetwork", "scipy.linalg.block_diag", "numpy.zeros", "numpy.ones", "numpy.split", "numpy.linalg.norm", "numpy.eye", "torch.no_grad", "numpy.concatenate", "torch.from_numpy" ]
[((2130, 2145), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2143, 2145), False, 'import torch\n'), ((2551, 2566), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2564, 2566), False, 'import torch\n'), ((3784, 3799), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3797, 3799), False, 'import torch\n'), ((2488, 2521), 'numpy.split', 'np.split', (['action', 'self.num_agents'], {}), '(action, self.num_agents)\n', (2496, 2521), True, 'import numpy as np\n'), ((2716, 2745), 'numpy.eye', 'np.eye', (['self.total_action_dim'], {}), '(self.total_action_dim)\n', (2722, 2745), True, 'import numpy as np\n'), ((2761, 2791), 'numpy.ones', 'np.ones', (['self.total_action_dim'], {}), '(self.total_action_dim)\n', (2768, 2791), True, 'import numpy as np\n'), ((2807, 2833), 'numpy.concatenate', 'np.concatenate', (['constraint'], {}), '(constraint)\n', (2821, 2833), True, 'import numpy as np\n'), ((2908, 2964), 'numpy.zeros', 'np.zeros', (['[self.total_action_dim, self.total_action_dim]'], {}), '([self.total_action_dim, self.total_action_dim])\n', (2916, 2964), True, 'import numpy as np\n'), ((3162, 3191), 'numpy.eye', 'np.eye', (['self.total_action_dim'], {}), '(self.total_action_dim)\n', (3168, 3191), True, 'import numpy as np\n'), ((3227, 3254), 'numpy.concatenate', 'np.concatenate', (['[-G, I, -I]'], {}), '([-G, I, -I])\n', (3241, 3254), True, 'import numpy as np\n'), ((3268, 3317), 'numpy.concatenate', 'np.concatenate', (['[C - self.col_margin, ones, ones]'], {}), '([C - self.col_margin, ones, ones])\n', (3282, 3317), True, 'import numpy as np\n'), ((4028, 4057), 'numpy.eye', 'np.eye', (['self.total_action_dim'], {}), '(self.total_action_dim)\n', (4034, 4057), True, 'import numpy as np\n'), ((4074, 4130), 'numpy.zeros', 'np.zeros', (['[self.total_action_dim, self.total_action_dim]'], {}), '([self.total_action_dim, self.total_action_dim])\n', (4082, 4130), True, 'import numpy as np\n'), ((4147, 4177), 'numpy.ones', 'np.ones', (['self.total_action_dim'], {}), '(self.total_action_dim)\n', (4154, 4177), True, 'import numpy as np\n'), ((4194, 4225), 'numpy.zeros', 'np.zeros', (['self.total_action_dim'], {}), '(self.total_action_dim)\n', (4202, 4225), True, 'import numpy as np\n'), ((4361, 4417), 'numpy.zeros', 'np.zeros', (['[self.total_action_dim, self.total_action_dim]'], {}), '([self.total_action_dim, self.total_action_dim])\n', (4369, 4417), True, 'import numpy as np\n'), ((4594, 4647), 'scipy.linalg.block_diag', 'sp.linalg.block_diag', (['I', '(Z + I * 0.001)', '(Z + I * 0.001)'], {}), '(I, Z + I * 0.001, Z + I * 0.001)\n', (4614, 4647), True, 'import scipy as sp\n'), ((4660, 4699), 'numpy.concatenate', 'np.concatenate', (['[-actions, ones, zeros]'], {}), '([-actions, ones, zeros])\n', (4674, 4699), True, 'import numpy as np\n'), ((5011, 5051), 'numpy.concatenate', 'np.concatenate', (['(C, zeros, zeros, zeros)'], {}), '((C, zeros, zeros, zeros))\n', (5025, 5051), True, 'import numpy as np\n'), ((1340, 1402), 'core.ConstraintNetwork.ConstraintNetwork', 'ConstraintNetwork', (['self.total_state_dim', 'self.total_action_dim'], {}), '(self.total_state_dim, self.total_action_dim)\n', (1357, 1402), False, 'from core.ConstraintNetwork import ConstraintNetwork\n'), ((3681, 3708), 'numpy.linalg.norm', 'np.linalg.norm', (['(actions - x)'], {}), '(actions - x)\n', (3695, 3708), True, 'import numpy as np\n'), ((4242, 4268), 'numpy.concatenate', 'np.concatenate', (['constraint'], {}), '(constraint)\n', (4256, 4268), True, 'import numpy as np\n'), ((5461, 5488), 'numpy.linalg.norm', 'np.linalg.norm', (['(actions - x)'], {}), '(actions - x)\n', (5475, 5488), True, 'import numpy as np\n'), ((4746, 4781), 'numpy.concatenate', 'np.concatenate', (['[-G, Z, -I]'], {'axis': '(1)'}), '([-G, Z, -I], axis=1)\n', (4760, 4781), True, 'import numpy as np\n'), ((4808, 4842), 'numpy.concatenate', 'np.concatenate', (['[Z, Z, -I]'], {'axis': '(1)'}), '([Z, Z, -I], axis=1)\n', (4822, 4842), True, 'import numpy as np\n'), ((4869, 4916), 'numpy.concatenate', 'np.concatenate', (['[Z, -I, l1_penalty * I]'], {'axis': '(1)'}), '([Z, -I, l1_penalty * I], axis=1)\n', (4883, 4916), True, 'import numpy as np\n'), ((4944, 4992), 'numpy.concatenate', 'np.concatenate', (['[Z, -I, -l1_penalty * I]'], {'axis': '(1)'}), '([Z, -I, -l1_penalty * I], axis=1)\n', (4958, 4992), True, 'import numpy as np\n'), ((2216, 2239), 'torch.from_numpy', 'torch.from_numpy', (['state'], {}), '(state)\n', (2232, 2239), False, 'import torch\n')]
import pandas as pd import numpy as np from gamechangerml.src.utilities.text_utils import normalize_answer, normalize_query, get_tokens from gamechangerml.src.utilities.test_utils import * from gamechangerml.configs.config import ValidationConfig, TrainingConfig from gamechangerml.api.utils.logger import logger from gamechangerml.src.utilities.es_search_utils import get_paragraph_results, connect_es from gamechangerml.src.utilities.test_utils import filter_date_range ES_URL = 'https://vpc-gamechanger-iquxkyq2dobz4antllp35g2vby.us-east-1.es.amazonaws.com' class ValidationData(): def __init__(self, validation_dir): self.validation_dir = validation_dir class SQuADData(ValidationData): def __init__( self, validation_dir=ValidationConfig.DATA_ARGS['validation_dir'], squad_path=ValidationConfig.DATA_ARGS['squad']['dev'], sample_limit=None ): super().__init__(validation_dir) logger.info(f"Pulling validation data from {str(os.path.join(validation_dir, squad_path))}") if not os.path.exists(os.path.join(validation_dir, squad_path)): logger.warning("No directory exists for this validation data.") self.dev = open_json(squad_path, validation_dir) self.queries = self.get_squad_sample(sample_limit) def get_squad_sample(self, sample_limit): '''Format SQuAD data into list of dictionaries (length = sample size)''' data_limit = len(self.dev['data']) if sample_limit: data_limit = np.min([data_limit, sample_limit]) par_limit = sample_limit // data_limit else: par_limit = np.max([len(d['paragraphs']) for d in self.dev['data']]) count = 0 queries = [] for p in range(par_limit): for d in range(data_limit): try: base = self.dev['data'][d]['paragraphs'][p] context = base['context'] questions = base['qas'] q_limit = np.min([2, par_limit, len(questions)]) for q in range(q_limit): if count < sample_limit: count += 1 mydict = { "search_context": context, "question": questions[q]['question'], "id": questions[q]['id'], "null_expected": questions[q]['is_impossible'], "expected": questions[q]['answers'] } queries.append(mydict) else: break except: pass logger.info("Generated {} question/answer pairs from SQuAD dataset".format(len(queries))) return queries class QADomainData(ValidationData): def __init__( self, validation_dir=ValidationConfig.DATA_ARGS['validation_dir'], qa_gc_data_path=ValidationConfig.DATA_ARGS['question_gc']['queries'] ): super().__init__(validation_dir) self.all_queries = open_json(qa_gc_data_path, self.validation_dir) self.queries = self.check_queries() def check_queries(self): '''Check that in-domain examples contain expected answers in their context''' checked = [] for test in self.all_queries['test_queries']: alltext = normalize_query(' '.join(test['search_context'])) checked_answers = [i for i in test['expected'] if normalize_answer(i['text']) in alltext] test['expected'] = checked_answers if test['expected'] != []: checked.append(test) else: logger.info("Could not add {} to test queries: answer not in context".format(test['question'])) logger.info("Generated {} question/answer pairs from in-domain data".format(len(checked))) return checked class MSMarcoData(ValidationData): def __init__( self, validation_dir=ValidationConfig.DATA_ARGS['validation_dir'], queries=ValidationConfig.DATA_ARGS['msmarco']['queries'], collection=ValidationConfig.DATA_ARGS['msmarco']['collection'], relations=ValidationConfig.DATA_ARGS['msmarco']['relations'], metadata=ValidationConfig.DATA_ARGS['msmarco']['metadata'] ): super().__init__(validation_dir) self.queries = open_json(queries, self.validation_dir) self.collection = open_json(collection, self.validation_dir) self.relations = open_json(relations, self.validation_dir) self.metadata = open_json(metadata, self.validation_dir) self.corpus = self.get_msmarco_corpus() def get_msmarco_corpus(self): '''Format MSMarco so it can be indexed like the GC corpus''' return [(x, y, '') for x, y in self.collection.items()] class RetrieverGSData(ValidationData): def __init__( self, validation_dir, available_ids, gold_standard): super().__init__(validation_dir) self.samples = pd.read_csv(os.path.join(self.validation_dir, gold_standard), names=['query', 'document']) self.queries, self.collection, self.relations = self.dictify_data(available_ids) def dictify_data(self, available_ids): ''' Filter out any validation queries whose documents areen't in the index. Forrmat gold standard csv examples into MSMarco format. ''' ids = ['.'.join(i.strip('\n').split('.')[:-1]).strip().lstrip() for i in available_ids] self.samples['document'] = self.samples['document'].apply(lambda x: [i.strip().lstrip() for i in x.split(';')]) self.samples = self.samples.explode('document') df = self.samples[self.samples['document'].isin(ids)] # check ids are in the index if df.shape[0] < self.samples.shape[0]: all_ids = self.samples['document'].unique() missing_ids = [i for i in all_ids if i not in ids] logger.info("Validation IDs not in the index (removed from validation set): {}".format(missing_ids)) logger.info("Number of missing IDs: {}".format(str(len(missing_ids)))) logger.info("Number documents in the index to test: {}".format(str(len(all_ids) - len(missing_ids)))) df = df.groupby('query').agg({'document': lambda x: x.tolist()}).reset_index() query_list = df['query'].to_list() doc_list = df['document'].to_list() q_idx = ["query_" + str(i) for i in range(len(query_list))] queries = dict(zip(q_idx, query_list)) collection = dict(zip(all_ids, all_ids)) relations = dict(zip(q_idx, doc_list)) logger.info("Generated {} test queries of gold standard data".format(len(query_list))) return queries, collection, relations class UpdatedGCRetrieverData(RetrieverGSData): def __init__(self, available_ids, level=['gold', 'silver'], data_path=None, validation_dir=ValidationConfig.DATA_ARGS['validation_dir'], gold_standard=ValidationConfig.DATA_ARGS['retriever_gc']['gold_standard'] ): super().__init__(validation_dir, available_ids, gold_standard) try: if data_path: # if there is a path for data, use that self.data_path = os.path.join(data_path, level) else: new_data = get_most_recent_dir(os.path.join(ValidationConfig.DATA_ARGS['validation_dir'], 'sent_transformer')) self.data_path = os.path.join(new_data, level) self.new_queries, self.new_collection, self.new_relations = self.load_new_data() self.combine_in_domain() except: logger.info(f"Error getting data from {new_data}. Could not create UpdatedGCRetrieverData object.") def load_new_data(self): f = open_json('intelligent_search_data.json', self.data_path) intel = json.loads(f) logger.info(f"Added {str(len(intel['correct']))} correct query/sent pairs from updated GC retriever data.") return intel['queries'], intel['collection'], intel['correct'] def combine_in_domain(self): self.queries.update({k:v for (k, v) in self.new_queries.items() if k in self.new_relations.keys()}) self.collection.update(self.new_collection) self.relations.update(self.new_relations) return class NLIData(ValidationData): def __init__( self, sample_limit, validation_dir=ValidationConfig.DATA_ARGS['validation_dir'], matched=ValidationConfig.DATA_ARGS['nli']['matched'], mismatched=ValidationConfig.DATA_ARGS['nli']['matched'] ): super().__init__(validation_dir) self.matched = open_jsonl(matched, self.validation_dir) self.mismatched = open_jsonl(mismatched, self.validation_dir) self.sample_csv = self.get_sample_csv(sample_limit) self.query_lookup = dict(zip(self.sample_csv['promptID'], self.sample_csv['sentence1'])) def get_sample_csv(self, sample_limit): '''Format NLI data into smaller sample for evaluation''' match_df = pd.DataFrame(self.matched) mismatched_df = pd.DataFrame(self.mismatched) match_df['set'] = 'matched' mismatched_df['set'] = 'mismatched' both = pd.concat([match_df, mismatched_df]) # assign int ranks based on gold label gold_labels_map = { 'entailment': 2, 'neutral': 1, 'contradiction': 5 } both['gold_label_int'] = both['gold_label'].map(gold_labels_map) # filter out propmtIDs that don't have a clear 0, 1, 2 rank sum_map = both.groupby('promptID')['gold_label_int'].sum().to_dict() both['rank_sum'] = both['promptID'].map(sum_map) both = both[both['rank_sum']==8] # map ranks rank_map = { 'entailment': 0, 'neutral': 1, 'contradiction': 2 } both['expected_rank'] = both['gold_label'].map(rank_map) cats = both['genre'].nunique() # get smaller sample df with even proportion of genres across matched/mismatched sample = pd.DataFrame() for i in both['genre'].unique(): subset = both[both['genre']==i].sort_values(by='promptID') if sample_limit: split = sample_limit * 3 // cats subset = subset.head(split) sample = pd.concat([sample, subset]) logger.info(("Created {} sample sentence pairs from {} unique queries:".format(sample.shape[0], sample_limit))) return sample[['genre', 'gold_label', 'pairID', 'promptID', 'sentence1', 'sentence2', 'expected_rank']] class MatamoFeedback(): def __init__( self, start_date, end_date, exclude_searches ): self.matamo = concat_matamo() self.start_date = start_date self.end_date = end_date self.exclude_searches=exclude_searches self.intel, self.qa = self.split_matamo() def split_matamo(self): '''Split QA queries from intelligent search queries''' df = self.matamo if self.start_date or self.end_date: df = filter_date_range(df, self.start_date, self.end_date) df.drop_duplicates(subset = ['user_id', 'createdAt', 'value_1', 'value_2'], inplace = True) df['source'] = 'matamo' df['correct'] = df['event_name'].apply(lambda x: ' '.join(x.split('_')[-2:])).map({'thumbs up': True, 'thumbs down': False}) df['type'] = df['event_name'].apply(lambda x: ' '.join(x.split('_')[:-2])) df['value_5'] = df['value_5'].apply(lambda x: x.replace('sentence_results', 'sentence_results:') if type(x)==str else x) intel = df[df['type']=='intelligent search'].copy() intel.dropna(axis=1, how='all', inplace = True) qa = df[df['type']=='qa'].copy() qa.dropna(axis=1, how='all', inplace = True) def process_matamo(df): '''Reformat Matamo feedback''' queries = [] cols = [i for i in df.columns if i[:5]=='value'] def process_row(row, col_name): '''Split the pre-colon text from rows''' if ':' in row: row = row.split(':') key = row[0] vals = ':'.join(row[1:]) return key, vals else: return col_name, row for i in df.index: query = {} query['date'] = df.loc[i, 'createdAt'] query['source'] = 'matamo' query['correct_match'] = df.loc[i, 'correct'] for j in cols: row = df.loc[i, j] if type(row) == str and row[0] != '[': key, val = process_row(row, j) query[key] = val if key in ['question', 'search_text', 'QA answer']: clean_val = normalize_query(val) clean_key = key + '_clean' query[clean_key] = clean_val queries.append(query) return pd.DataFrame(queries) return process_matamo(intel), process_matamo(qa) class SearchHistory(): def __init__( self, start_date, end_date, exclude_searches ): self.history = concat_search_hist() self.start_date = start_date self.end_date = end_date self.exclude_searches=exclude_searches self.intel_matched, self.intel_unmatched = self.split_feedback() def split_feedback(self): df = self.history if self.start_date or self.end_date: df = filter_date_range(df, self.start_date, self.end_date) df.dropna(subset = ['search'], inplace = True) # drop all rows where is no search if self.exclude_searches: logger.info(f"Excluding searches: {str(self.exclude_searches)}") df = df[~df['search'].isin(self.exclude_searches)] # remove searches we don't want to use df.drop_duplicates(subset = ['idvisit', 'document', 'search'], inplace = True) # drop duplicates df['source'] = 'user_history' def clean_quot(string): return string.replace('&quot;', "'").replace("&#039;", "'").lower() def clean_doc(string): return string.strip('.pdf') def is_question(string): '''If we find a good way to use search history for QA validation (not used currently)''' question_words = ['what', 'who', 'where', 'why', 'how', 'when'] if '?' in string: return True else: return bool(set(string.lower().split()).intersection(question_words)) df.rename(columns = {'documenttime': 'date', 'search': 'search_text', 'document': 'title_returned'}, inplace = True) df['search_text'] = df['search_text'].apply(lambda x: clean_quot(x)) df['search_text_clean'] = df['search_text'].apply(lambda x: normalize_query(x)) df = df[df['search_text_clean'] != ''].copy() df.drop(columns = ['idvisit', 'idaction_name', 'search_cat', 'searchtime'], inplace = True) matched = df[~df['title_returned'].isnull()].copy() matched['correct_match'] = True matched['title_returned'] = matched['title_returned'].apply(lambda x: clean_doc(x)) #matched['is_question'] = matched['search'].apply(lambda x: is_question(x)) unmatched = df[df['title_returned'].isnull()].copy() unmatched['correct_match'] = False return matched, unmatched class SearchValidationData(): def __init__( self, start_date, end_date, exclude_searches ): self.start_date = start_date self.end_date = end_date self.exclude_searches=exclude_searches self.matamo_data = MatamoFeedback(self.start_date, self.end_date, self.exclude_searches) self.history_data = SearchHistory(self.start_date, self.end_date, self.exclude_searches) class QASearchData(SearchValidationData): ##TODO: add context relations attr for QASearchData def __init__( self, start_date, end_date, exclude_searches, min_correct_matches, max_results ): super().__init__(start_date, end_date, exclude_searches) self.data = self.matamo_data.qa self.min_correct_matches = min_correct_matches self.max_results = max_results self.queries, self.collection, self.all_relations, self.correct, self.incorrect = self.make_qa() def make_qa(self): qa = self.data # get set of queries + make unique query dict qa_queries = set(qa['question_clean']) qa_search_queries = update_dictionary(old_dict = {}, new_additions = qa_queries, prefix = 'Q') # get set of docs + make unique doc dict qa_answers = set(qa['QA answer_clean']) qa_search_results = update_dictionary(old_dict = {}, new_additions = qa_answers, prefix = 'A') # map IDs back to df qa = map_ids(qa_search_queries, qa, 'question_clean', 'key') qa = map_ids(qa_search_results, qa, 'QA answer_clean', 'value') # create new QA metadata rels qa_metadata = {} # TODO: add option to add existing metadata new_qa_metadata = update_meta_relations(qa_metadata, qa, 'question', 'QA answer') # filtere the metadata to only get relations we want to test against correct, incorrect = filter_rels(new_qa_metadata, min_correct_matches=self.min_correct_matches, max_results=self.max_results) return qa_search_queries, qa_search_results, new_qa_metadata, correct, incorrect class IntelSearchData(SearchValidationData): def __init__( self, start_date, end_date, exclude_searches, min_correct_matches, max_results ): super().__init__(start_date, end_date, exclude_searches) self.exclude_searches = exclude_searches self.data = pd.concat([self.matamo_data.intel, self.history_data.intel_matched]).reset_index() self.min_correct_matches = min_correct_matches self.max_results = max_results self.queries, self.collection, self.all_relations, self.correct, self.incorrect = self.make_intel() def make_intel(self): intel = self.data intel = intel[~intel['search_text'].isin(self.exclude_searches)] int_queries = set(intel['search_text_clean']) intel_search_queries = update_dictionary(old_dict = {}, new_additions = int_queries, prefix ='S') int_docs = set(intel['title_returned']) intel_search_results = update_dictionary(old_dict = {}, new_additions = int_docs, prefix ='R') # map IDS back to dfs intel = map_ids(intel_search_queries, intel, 'search_text_clean', 'key') intel = map_ids(intel_search_results, intel, 'title_returned', 'value') # create new intel search metadata rels intel_metadata = {} # TODO: add option to add existing metadata new_intel_metadata = update_meta_relations(intel_metadata, intel, 'search_text', 'title_returned') # filtere the metadata to only get relations we want to test against logger.info(f"min_correct_matches: {(str(self.min_correct_matches))}") logger.info(f"max_results: {(str(self.max_results))}") correct, incorrect = filter_rels(new_intel_metadata, min_correct_matches=self.min_correct_matches, max_results=self.max_results) return intel_search_queries, intel_search_results, new_intel_metadata, correct, incorrect class QEXPDomainData(ValidationData): def __init__( self, validation_dir=ValidationConfig.DATA_ARGS['validation_dir'], qe_gc_path=ValidationConfig.DATA_ARGS['qe_gc'] ): super().__init__(validation_dir) self.data = open_json(qe_gc_path, self.validation_dir)['queries']
[ "pandas.DataFrame", "gamechangerml.api.utils.logger.logger.info", "gamechangerml.src.utilities.text_utils.normalize_query", "numpy.min", "gamechangerml.src.utilities.test_utils.filter_date_range", "gamechangerml.api.utils.logger.logger.warning", "gamechangerml.src.utilities.text_utils.normalize_answer", "pandas.concat" ]
[((9324, 9350), 'pandas.DataFrame', 'pd.DataFrame', (['self.matched'], {}), '(self.matched)\n', (9336, 9350), True, 'import pandas as pd\n'), ((9375, 9404), 'pandas.DataFrame', 'pd.DataFrame', (['self.mismatched'], {}), '(self.mismatched)\n', (9387, 9404), True, 'import pandas as pd\n'), ((9500, 9536), 'pandas.concat', 'pd.concat', (['[match_df, mismatched_df]'], {}), '([match_df, mismatched_df])\n', (9509, 9536), True, 'import pandas as pd\n'), ((10378, 10392), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (10390, 10392), True, 'import pandas as pd\n'), ((1141, 1204), 'gamechangerml.api.utils.logger.logger.warning', 'logger.warning', (['"""No directory exists for this validation data."""'], {}), "('No directory exists for this validation data.')\n", (1155, 1204), False, 'from gamechangerml.api.utils.logger import logger\n'), ((1548, 1582), 'numpy.min', 'np.min', (['[data_limit, sample_limit]'], {}), '([data_limit, sample_limit])\n', (1554, 1582), True, 'import numpy as np\n'), ((10648, 10675), 'pandas.concat', 'pd.concat', (['[sample, subset]'], {}), '([sample, subset])\n', (10657, 10675), True, 'import pandas as pd\n'), ((11457, 11510), 'gamechangerml.src.utilities.test_utils.filter_date_range', 'filter_date_range', (['df', 'self.start_date', 'self.end_date'], {}), '(df, self.start_date, self.end_date)\n', (11474, 11510), False, 'from gamechangerml.src.utilities.test_utils import filter_date_range\n'), ((13478, 13499), 'pandas.DataFrame', 'pd.DataFrame', (['queries'], {}), '(queries)\n', (13490, 13499), True, 'import pandas as pd\n'), ((14069, 14122), 'gamechangerml.src.utilities.test_utils.filter_date_range', 'filter_date_range', (['df', 'self.start_date', 'self.end_date'], {}), '(df, self.start_date, self.end_date)\n', (14086, 14122), False, 'from gamechangerml.src.utilities.test_utils import filter_date_range\n'), ((7885, 7994), 'gamechangerml.api.utils.logger.logger.info', 'logger.info', (['f"""Error getting data from {new_data}. Could not create UpdatedGCRetrieverData object."""'], {}), "(\n f'Error getting data from {new_data}. Could not create UpdatedGCRetrieverData object.'\n )\n", (7896, 7994), False, 'from gamechangerml.api.utils.logger import logger\n'), ((15415, 15433), 'gamechangerml.src.utilities.text_utils.normalize_query', 'normalize_query', (['x'], {}), '(x)\n', (15430, 15433), False, 'from gamechangerml.src.utilities.text_utils import normalize_answer, normalize_query, get_tokens\n'), ((18609, 18677), 'pandas.concat', 'pd.concat', (['[self.matamo_data.intel, self.history_data.intel_matched]'], {}), '([self.matamo_data.intel, self.history_data.intel_matched])\n', (18618, 18677), True, 'import pandas as pd\n'), ((3636, 3663), 'gamechangerml.src.utilities.text_utils.normalize_answer', 'normalize_answer', (["i['text']"], {}), "(i['text'])\n", (3652, 3663), False, 'from gamechangerml.src.utilities.text_utils import normalize_answer, normalize_query, get_tokens\n'), ((13287, 13307), 'gamechangerml.src.utilities.text_utils.normalize_query', 'normalize_query', (['val'], {}), '(val)\n', (13302, 13307), False, 'from gamechangerml.src.utilities.text_utils import normalize_answer, normalize_query, get_tokens\n')]
from queue import * from Segmentation import CombinedHist import numpy as np #Thia class is a queuse of histograms class HistQueue: size = 0 added_elements = 0 hist_queue = Queue() total_blue_histr = np.zeros((256,1),dtype = np.float32) total_green_histr = np.zeros((256,1),dtype = np.float32) total_red_histr = np.zeros((256,1),dtype = np.float32) # initializer def __init__(self, size): self.size = size self.hist_queue = Queue(size) # this will insert a new histr to qwuee # if the queue is full this will remove the first element and # then insert the new histr def insert_histr(self, combined_histr): self.added_elements +=1 if self.hist_queue.qsize() < self.size: self.hist_queue.put(combined_histr) self.increaseTotalValues(combined_histr) else: removed_hist = self.hist_queue.get() self.decreaseTotalValues(removed_hist) self.hist_queue.put(combined_histr) self.increaseTotalValues(combined_histr) # this will return the size of the queue def getMaximumSize(self): return self.size # this will return the number of elements currently added to the queue def getAddedNoOfHistr(self): return self.added_elements #this will return an average hist from the elements in the queue def getAverageHist(self): if self.added_elements>0: avg_blue_histr = self.total_blue_histr/self.added_elements avg_green_histr = self.total_green_histr / self.added_elements avg_red_histr = self.total_red_histr / self.added_elements return CombinedHist.CombinedHist(avg_blue_histr, avg_green_histr, avg_red_histr) else: return CombinedHist.CombinedHist(np.zeros((256, 1), dtype = np.float32), np.zeros((256, 1), dtype = np.float32), np.zeros((256, 1), dtype = np.float32)) #this will increase the total values for a given hist def increaseTotalValues(self,cmbHist): #cmbHist = CombinedHist.CombinedHist(CombinedHists) self.total_blue_histr += cmbHist.getBlueHistr() self.total_green_histr += cmbHist.getGreenHistr() self.total_red_histr += cmbHist.getRedHistr() # this will increase the total values for a given hist def decreaseTotalValues(self, cmbHist): #cmbHist = CombinedHist.CombinedHist(CombinedHists) self.total_blue_histr -= cmbHist.getBlueHistr() self.total_green_histr -= cmbHist.getGreenHistr() self.total_red_histr -= cmbHist.getRedHistr()
[ "Segmentation.CombinedHist.CombinedHist", "numpy.zeros" ]
[((219, 255), 'numpy.zeros', 'np.zeros', (['(256, 1)'], {'dtype': 'np.float32'}), '((256, 1), dtype=np.float32)\n', (227, 255), True, 'import numpy as np\n'), ((280, 316), 'numpy.zeros', 'np.zeros', (['(256, 1)'], {'dtype': 'np.float32'}), '((256, 1), dtype=np.float32)\n', (288, 316), True, 'import numpy as np\n'), ((339, 375), 'numpy.zeros', 'np.zeros', (['(256, 1)'], {'dtype': 'np.float32'}), '((256, 1), dtype=np.float32)\n', (347, 375), True, 'import numpy as np\n'), ((1686, 1759), 'Segmentation.CombinedHist.CombinedHist', 'CombinedHist.CombinedHist', (['avg_blue_histr', 'avg_green_histr', 'avg_red_histr'], {}), '(avg_blue_histr, avg_green_histr, avg_red_histr)\n', (1711, 1759), False, 'from Segmentation import CombinedHist\n'), ((1819, 1855), 'numpy.zeros', 'np.zeros', (['(256, 1)'], {'dtype': 'np.float32'}), '((256, 1), dtype=np.float32)\n', (1827, 1855), True, 'import numpy as np\n'), ((1859, 1895), 'numpy.zeros', 'np.zeros', (['(256, 1)'], {'dtype': 'np.float32'}), '((256, 1), dtype=np.float32)\n', (1867, 1895), True, 'import numpy as np\n'), ((1899, 1935), 'numpy.zeros', 'np.zeros', (['(256, 1)'], {'dtype': 'np.float32'}), '((256, 1), dtype=np.float32)\n', (1907, 1935), True, 'import numpy as np\n')]