text:
import math
import numpy
from numpy.linalg import svd

datavec = list(numpy.loadtxt('PCV1_1genesample.txt')) + list(numpy.loadtxt('PCV1_2genesample.txt')) + list(numpy.loadtxt('PCV1_3genesample.txt')) + list(numpy.loadtxt('PCV1_4genesample.txt'))
#Now we want to concatenate the datavector a bit
gene1 = list(numpy.loadtxt('PCV1_1genesample.txt'))
gene2 = list(numpy.loadtxt('PCV1_2genesample.txt'))
gene3 = list(numpy.loadtxt('PCV1_3genesample.txt'))
gene4 = list(numpy.loadtxt('PCV1_4genesample.txt'))
#Name them here for ease but would later cut out this step

Ngenes = 4
x = len(datavec)

#Beginning of defining cdatavec <---
catdatavec = [None]*(x) #x defined as len(datavec), so defines a list of same length as the datavec (for now filled with None's)

catdatavec[::Ngenes] = gene1
catdatavec[1::Ngenes] = gene2
catdatavec[2::Ngenes] = gene3
catdatavec[3::Ngenes] = gene4
#Can catenate before filling it with 4's since 4's end up being at the

#NOTE: eventually want to structure this in terms of number of gene samples Ngenes used <---

b = math.ceil(math.log( x ) / float(math.log( 2 ))) # this defines b so that 2^b > x, but 2^(b-1) < x, i.e. b is the nearest power of 2 above x (or equal if x is a power of 2)

print "b is ", b, "so the length of the combined and filled data sample is ", (2**b)

filler = list((0*numpy.arange(((2**b) - x)) + 4))

if (2**b) == x:
    fdatavec = catdatavec
elif (2**b) > x:
    fdatavec = catdatavec + filler
else:
    print "Something went wrong. Probably didn't define the data vector as needed. Try again"
#Now fdatavec will be a filled vector of length 2^b

#Need to do W0 first and separately since the way we make W0 from fdatavec is different from how we make W1,...,Wb from the sqrt(Lambda).V's

W0=[None]*2
W0[0] = fdatavec[0:(len(fdatavec)/2)]
W0[1] = fdatavec[(len(fdatavec)/2):(len(fdatavec))]
#Note W0 is constructed differently than subsequent W's

#-------------------------------------Start of SVD of W0-----------------------------------------------------------------------------------------------------------------------
# Matrix Multiplication Algorithm to isolate sqrt(Lambda).V of W = U.Lambda.V :
U=svd(W0)[0]
Lambda=svd(W0)[1]
V=svd(W0)[2]
r=0*numpy.ndarray(shape=(len(U),len(V)))

for i in range(len(Lambda)):
    r[i][i]=math.sqrt(Lambda[i])

L = numpy.ndarray.tolist(numpy.matrix(r)) #This is now the sqrt(Lambda) matrix of proper size (although maybe rows and columns are switched and it's a 3x8, not an 8x3 as it should be)

result=numpy.ndarray.tolist(0*numpy.matrix(r))

for i in range(len(L)):
    # iterate through columns of Y
    for j in range(len(V[0])):
        # iterate through rows of Y
        for k in range(len(V)):
            result[i][j] += L[i][k] * V[k][j]

M = result
#-------------------------------------End of SVD of W0-----------------------------------------------------------------------------------------------------------------------

#NOTE: Choosing to construct W0 as we do the other W'sgives rel good results, using for B in range(int(b),0,-1), i.e. using int(b) rather than int(b)-1 and defining M as M = [fdatavec]
for B in range(int(b)-1,0,-1):   #NOTE: Start at int(b)-1 since we did defined W0 previously, so this one should start by making W1
    NumofRows = int((2**(b-B))) #Number of rows of the thing being catenated
    W =[None]*(2*NumofRows)

    #    for n in range(NumofRows):    #Shifted row-wise stacked Catenation
    #        W[(2*n)] = [M[n][i] for i in range(0, int(2**(B-1)))]
    #        W[((2*n)+1)] = [M[n][i] for i in range(int(2**(B-1)), int((2**B)))]

    for n in range(NumofRows): #Alternating Catenation
        W[(2*n)] = M[n][::2] #Should it be an alternation every 2nd pt or should we do W1[0] = A[0][::Ngenes] ???????
        W[((2*n)+1)] = M[n][1::2]

    # Matrix Multiplication Algorithm to isolate sqrt(Lambda).V of W = U.Lambda.V :
    U=svd(W)[0]
    Lambda=svd(W)[1]
    V=svd(W)[2]
    r=0*numpy.ndarray(shape=(len(U),len(V)))

    for i in range(len(Lambda)):
        r[i][i]=math.sqrt(Lambda[i])

    L = numpy.ndarray.tolist(numpy.matrix(r)) #This is now the sqrt(Lambda) matrix of proper size (although maybe rows and columns are switched and it's a 3x8, not an 8x3 as it should be)

    result=numpy.ndarray.tolist(0*numpy.matrix(r))

    for i in range(len(L)):
       # iterate through columns of Y
       for j in range(len(V[0])):
           # iterate through rows of Y
           for k in range(len(V)):
               result[i][j] += L[i][k] * V[k][j]

    M = result #Need to redefine M so the for loop acts on result each time
    print "For the", int(b-B)+1, "-th SVD there are", len(Lambda), "singular values and they are:" #i.e. for W_(b-B) = U.Lambda_(b-B).V, the non-zero values of Lambda_(b-B)
    print Lambda #The list of singular values #Comment this line out to get it to just tell you the number of singular values and nothing more
    print "_____________________________________________________________________" #Just to separate the results a bit

#print W
#print svd(W)[2] #NOTE! svd(W)[1] gives the 2nd element (the sing values) svd(W)[0] the 1st and svd(W)[2] gives the 3rd!  svd(W)[3] does nothing since there is no 4th matrix!

#print svd(numpy.ndarray.tolist(svd(W)[2]))[1]

#print svd(svd(W)[2])[1]
#print svd( svd( svd(W)[2] )[2] )[1]
#print svd( svd( svd( svd(W)[2] )[2] )[2] )[1]
#print svd( svd( svd( svd( svd(W)[2] )[2] )[2] )[2] )[1]
#print svd( svd( svd( svd( svd( svd(W)[2] )[2] )[2] )[2] )[2] )[1]
#print svd( svd( svd( svd( svd( svd( svd(W)[2] )[2] )[2] )[2] )[2] )[2] )[1]
#print svd( svd( svd( svd( svd( svd( svd( svd(W)[2] )[2] )[2] )[2] )[2] )[2] )[2] )[1]
#print svd( svd( svd( svd( svd( svd( svd( svd( svd(W)[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[1]
#print svd( svd( svd( svd( svd( svd( svd( svd( svd( svd(W)[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[1]
#print svd( svd( svd( svd( svd( svd( svd( svd( svd( svd( svd(W)[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[1]
#print svd( svd( svd( svd( svd( svd( svd( svd( svd( svd( svd( svd(W)[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[1]
#print svd( svd( svd( svd( svd( svd( svd( svd( svd( svd( svd( svd( svd(W)[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[1]
#print svd( svd( svd( svd( svd( svd( svd( svd( svd( svd( svd( svd( svd( svd(W)[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[2] )[1]

#print numpy.ndarray.tolist(svd(W)) #The type error this gives shows you when svd(W) is a tuple, not a list like we want

#while len(W[1]) > 2:
#    U, singularValues, W = numpy.linalg.svd( W ) #defines V as the new W, so keeps
#    print singularValues
#    print W

reason: import numpy,from numpy


text:
#!/usr/bin/env python
"""Serialization testing."""

import numpy as np
import pandas as pd

from bowtie._component import jdumps, pack

NPARRAY = np.array([5, 6])
NPSCALAR = np.int32(5)
DATES = pd.date_range('2017-01-01', periods=2)

def test_json():
    """Tests json encoding numpy and pandas."""
    assert jdumps(NPARRAY) == jdumps([5, 6])
    assert jdumps(NPSCALAR) == jdumps(5)
    assert jdumps(DATES) == jdumps(['2017-01-01T00:00:00', '2017-01-02T00:00:00'])

def test_msgpack():
    """Tests msgpack encoding numpy and pandas."""
    assert pack(NPARRAY) == pack([5, 6])
    assert pack(NPSCALAR) == pack(5)
    assert pack(DATES) == pack(['2017-01-01T00:00:00', '2017-01-02T00:00:00'])

ext: py

reason: import numpy


text:
from Main import Hyperparameters
from Main.MCTS import ParallelMCTS
from Main.AlphaZero import LabelGenerator
from Main.Environments.Connect4 import Utils
import numpy as np

'''
Unlike previous implementations where we let self-play agents go against eachother using the "FullGame" interface.
Two agents simple share a game tree, where they both do search and acts as the current game
'''

class SelfPlayAgent():

    def __init__(self, gameFuncs, simulationsPerMove, playerID=1, dataAugmentationFunc=None, opponent=None,
                 computeTable=None):
        self.dataAugmentationFunc = dataAugmentationFunc
        self.simulationsPerMove = simulationsPerMove
        self.stateRewardsBuffer = []
        self.localStatesBuffer = []
        self.localPolicyBuffer = []
        self.gameFuncs = gameFuncs
        self.playerID = playerID
        self.opponent = opponent
        self.currentRound = 0
        self.invertState = False

        self.mirroredState = None
        self.currentNode = None
        self.currentPath = None
        self.currentRoot = None  # Is shared between the two self players

        self.statesEvaluated = []
        self.computeTable = computeTable
        self.savedEvals = 0
        self.performedEvals = 0

    def startNewSearch(self, currentRound):
        self.currentRound = currentRound
        self.addDirichletNoiseToRoot(self.currentRoot)

    # At the start of every new move we add some noise to the policy prediction
    def addDirichletNoiseToRoot(self, root):
        noise = np.random.dirichlet(Hyperparameters.DIRICHLET_NOISE_PARAM * np.ones(len(root.children)))
        for i in range(len(noise)):
            root.children[i].policyEstimation += noise[i]

    # Performs a MCTS until we can either make a move or have state that we require the oracle to evaluate
    def performSearchIteration(self):
        node, path = None, []
        while (node is None and self.currentRoot.visits < self.simulationsPerMove):
            node, path = ParallelMCTS.simulateMCTS(self.gameFuncs, self.currentRoot, self.currentRoot.visits + 1)

        # We can perform a move
        if (node is None and self.currentRoot.visits >= self.simulationsPerMove):
            return "MakeMove", self.makeMove()

        # We have reached an eval Node
        self.currentNode = node
        self.currentPath = path

        '''
        # Remove mirroring of states
        self.invertState = np.random.random() >= 0.5
        if (self.invertState):
            self.mirroredState = node.state.mirror()

        currentState = self.mirroredState if self.invertState else node.state
        '''

        currentState = node.state
        #numpyState = currentState.toNumpyState()
        # Check the pre-compute table
        if (Hyperparameters.USE_PREDICTION_CACHE):
            self.statesEvaluated.append(node.state)

            # Only queries the dict once:
            res = self.computeTable.get(currentState, None)
            # if (currentState in self.computeTable):
            if (res is not None):
                # print("Found precomputed predict!")
                value, policy = res  # self.computeTable[currentState]
                self.getEvalData(value, policy)
                self.savedEvals += 1
                return self.performSearchIteration()

        self.performedEvals += 1

        return "Eval", currentState.toConvState(node.currentPlayer)#Utils.state2ConvState(numpyState, node.currentPlayer)

    def makeMove(self):
        # Create Training Labels from current Tree
        inState, evalLabel, policyLabel = LabelGenerator.generateQLabels(self.currentRoot)
        self._addToLocalGameBuffer(inState, evalLabel, policyLabel)

        if (self.currentRound >= Hyperparameters.POLICY_THRESHOLD):
            selectedMove = np.argmax(policyLabel)
        else:
            selectedMove = np.random.choice(np.arange(0, len(policyLabel)), p=policyLabel)

        self.setNewCurrentRoot(self.currentRoot, selectedMove)
        return selectedMove

    def getEvalData(self, value, policy):
        if (Hyperparameters.USE_PREDICTION_CACHE):
            keyState = self.mirroredState if self.invertState else self.currentNode.state

            # inserts keyState and (value, policy) if not exists, else just returns old value, which we do not use
            # hopefully, this works
            self.computeTable.setdefault(keyState, (value, policy))

        if (self.invertState):
            policy = policy[::-1]  # Re-invert policy
        ParallelMCTS.simulatePostEvaluate(self.gameFuncs, self.currentNode, self.currentPath, value, policy)

    def _addToLocalGameBuffer(self, state, eval, policy):
        self.localStatesBuffer.append(state)
        self.localPolicyBuffer.append(policy)
        if (Hyperparameters.USE_Q_LABELS):
            self.stateRewardsBuffer.append(eval)

    # Effectively playing the move in the current game as the tree is shared with the opponent
    def setNewCurrentRoot(self, root, move):
        for c in root.children:
            if (c.action == move):
                self.opponent.currentRoot = c

    # When a game is over we get a reward, we can then label all of the labels created from the current game
    def getReward(self, reward):
        augmentedStates, augmentedPolices = self.dataAugmentationFunc(self.localStatesBuffer, self.localPolicyBuffer)

        self.localStatesBuffer.extend(augmentedStates)
        self.localPolicyBuffer.extend(augmentedPolices)

        if (Hyperparameters.USE_Q_LABELS):  # IF we use the Q-Labels, we simply duplicate our current eval labels
            self.stateRewardsBuffer.extend(self.stateRewardsBuffer)

            # TESTING, take the mean of the Q-Value & Z-Value
            self.stateRewardsBuffer = (np.array(self.stateRewardsBuffer) + reward) / 2
        else:
            self.stateRewardsBuffer = [reward] * len(self.localStatesBuffer)

    # This is currently not used as we simply create new agents for every self-play turn.
    # It's possible we could gain a minor speedup by re-using old agents and clearing their buffers...
    def clearLocalBuffers(self):
        global CURRENT_ROOT
        CURRENT_ROOT = None
        del self.localStatesBuffer
        del self.stateRewardsBuffer
        del self.localPolicyBuffer
        self.localStatesBuffer = []
        self.stateRewardsBuffer = []
        self.localPolicyBuffer = []


text:
from oculus import DsstParameters, DsstTracker, KcfParameters, KcfTracker,\
    Line2D, Line2DParameters
import cv2
import os
import numpy as np
from cmt import CMT
from threading import Thread
import time

class Eye:
    def __init__(self, source, sequence=False):
        self.optogram = None
        self.frame = None
        self.source = source

        if sequence:
            self.imageSequence = True
            self.counter = 1
        else:
            self.imageSequence = False

            self.cap = cv2.VideoCapture(source)
            if not self.cap.isOpened():
                raise Exception("Unable to connect to video source '%s'." % source)
            self.width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)
            self.height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)

    def close(self):
        self.cap.release()

    def updateFrame(self):
        if self.frame is not None:
            self.optogram = self.frame.copy()

        if self.imageSequence:
            self.frame = cv2.imread(self.source % self.counter)
            self.counter += 1
        else:
            _, self.frame = self.cap.read()

    def getGrayFrame(self):
        self.updateFrame()
        return cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)

    def getColorFrame(self):
        self.updateFrame()
        return self.frame.copy()

    def getBothFrames(self):
        self.updateFrame()
        return self.frame.copy(), cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)

class KCF:
    def __init__(self, **kwargs):
        params = KcfParameters()

        params.padding = kwargs.get('padding', 1.7)
        params.lambdaValue = kwargs.get('lambdaValue', 0.0001)
        params.outputSigmaFactor = kwargs.get('outputSigmaFactor', 0.05)
        params.votScaleStep = kwargs.get('votScaleStep', 1.05)
        params.votScaleWeight = kwargs.get('votScaleWeight', 0.95)
        params.templateSize = kwargs.get('templateSize', 100)
        params.interpFactor = kwargs.get('interpFactor', 0.012)
        params.kernelSigma = kwargs.get('kernelSigma', 0.6)
        params.cellSize = kwargs.get('cellSize', 4)
        params.pixelPadding = kwargs.get('pixelPadding', 0)

        params.enableTrackingLossDetection = kwargs.get('enableTrackingLossDetection', False)
        params.psrThreshold = kwargs.get('psrThreshold', 13.5)
        params.psrPeakDel = kwargs.get('psrPeakDel', 1)

        params.useVotScaleEstimation = kwargs.get('useVotScaleEstimation', False)
        params.useDsstScaleEstimation = kwargs.get('useDsstScaleEstimation', True)

        params.scaleSigmaFactor = kwargs.get('scaleSigmaFactor', 0.25)
        params.scaleEstimatorStep = kwargs.get('scaleEstimatorStep', 1.02)
        params.scaleLambda = kwargs.get('scaleLambda', 0.01)
        params.scaleCellSize = kwargs.get('caleCellSize', 4)
        params.numberOfScales = kwargs.get('numberOfScales', 33)

        params.resizeType = kwargs.get('resizeType', 1)
        params.useFhogTranspose = kwargs.get('useFhogTranspose', False)
        params.minArea = kwargs.get('minArea', 10)
        params.maxAreaFactor = kwargs.get('maxAreaFactor', 0.8)
        params.nScalesVot = kwargs.get('nScalesVot', 3)
        params.votMinScaleFactor = kwargs.get('votMinScaleFactor', 0.01)
        params.votMaxScaleFactor = kwargs.get('votMaxScaleFactor', 40)
        params.useCcs = kwargs.get('useCcs', True)

        self.params = params
        self.tracker = KcfTracker(self.params)
        self.initialized = False

    def init(self, image, boundingBox):
        success = self.tracker.reinit(image, boundingBox)

        if success:
            self.initialized = True
        else:
            raise Exception('Unable to initialize KCF tracker with given frame.')

    def reinit(self, image, boundingBox):
        self.tracker.reinit(image, boundingBox)

    def update(self, image):
        return self.tracker.update(image)

    def updateAt(self, image, boundingBox):
        return self.tracker.updateAt(image, boundingBox)

    def getBoundingBox(self):
        return self.tracker.getBoundingBox()

    def getCenter(self):
        return self.tracker.getCenter()

class DSST:
    def __init__(self, **kwargs):
        params = DsstParameters()

        params.padding = kwargs.get('padding', 1.6)
        params.outputSigmaFactor = kwargs.get('outputSigmaFactor', 0.05)
        params.lambdaValue = kwargs.get('lambdaValue', 0.01)
        params.learningRate = kwargs.get('learningRate', 0.012)
        params.templateSize = kwargs.get('templateSize', 100)
        params.cellSize = kwargs.get('cellSize', 2)

        params.enableTrackingLossDetection = kwargs.get('enableTrackingLossDetection', False)
        params.psrThreshold = kwargs.get('psrThreshold', 13.5)
        params.psrPeakDel = kwargs.get('psrPeakDel', 1)

        params.enableScaleEstimator = kwargs.get('enableScaleEstimator', True)
        params.scaleSigmaFactor = kwargs.get('scaleSigmaFactor', 0.25)
        params.scaleStep = kwargs.get('scaleStep', 1.02)
        params.scaleCellSize = kwargs.get('scaleCellSize', 4)
        params.numberOfScales = kwargs.get('numberOfScales', 33)

        params.originalVersion = kwargs.get('originalVersion', False)
        params.resizeType = kwargs.get('resizeType', 1)
        params.useFhogTranspose = kwargs.get('useFhogTranspose', False)
        params.minArea = kwargs.get('minArea', 10)
        params.maxAreaFactor = kwargs.get('maxAreaFactor', 0.8)
        params.useCcs = kwargs.get('useCcs', True)

        self.params = params
        self.tracker = DsstTracker(self.params)
        self.initialized = False

    def init(self, image, boundingBox):
        success = self.tracker.reinit(image, boundingBox)

        if success:
            self.initialized = True
        else:
            raise Exception('Unable to initialize DSST tracker with given frame.')

    def reinit(self, image, boundingBox):
        self.tracker.reinit(image, boundingBox)

    def update(self, image):
        return self.tracker.update(image)

    def updateAt(self, image, boundingBox):
        return self.tracker.updateAt(image, boundingBox)

    def getBoundingBox(self):
        return self.tracker.getBoundingBox()

    def getCenter(self):
        return self.tracker.getCenter()

def get_rect(im, title='get_rect'):
    mouse_params = {'tl': None, 'br': None, 'current_pos': None,
        'released_once': False}

    cv2.namedWindow(title)
    cv2.moveWindow(title, 100, 100)

    def onMouse(event, x, y, flags, param):

        param['current_pos'] = (x, y)

        if param['tl'] is not None and not (flags & cv2.EVENT_FLAG_LBUTTON):
            param['released_once'] = True

        if flags & cv2.EVENT_FLAG_LBUTTON:
            if param['tl'] is None:
                param['tl'] = param['current_pos']
            elif param['released_once']:
                param['br'] = param['current_pos']

    cv2.setMouseCallback(title, onMouse, mouse_params)
    cv2.imshow(title, im)

    while mouse_params['br'] is None:
        im_draw = np.copy(im)

        if mouse_params['tl'] is not None:
            cv2.rectangle(im_draw, mouse_params['tl'], mouse_params['current_pos'], (255, 0, 0))

        cv2.imshow(title, im_draw)
        _ = cv2.waitKey(10)

    cv2.destroyWindow(title)

    tl = (min(mouse_params['tl'][0], mouse_params['br'][0]),
        min(mouse_params['tl'][1], mouse_params['br'][1]))
    br = (max(mouse_params['tl'][0], mouse_params['br'][0]),
        max(mouse_params['tl'][1], mouse_params['br'][1]))

    return tl, br

def vot():
    directory = 'C:/Users/bobbyluig/Desktop/vot2015/pedestrian2'
    gt = open(os.path.join(directory, 'groundtruth.txt'), 'r')
    i = 1

    tracker = DSST()

    while True:
        truth = gt.readline().strip().split(',')

        if len(truth) < 8:
            break

        truth = [float(t) for t in truth]

        x = truth[::2]
        y = truth[1::2]

        x0 = int(round(min(x)))
        x1 = int(round(max(x)))
        y0 = int(round(min(y)))
        y1 = int(round(max(y)))

        frame = cv2.imread(os.path.join(directory, '%08d.jpg' % i))

        if i == 1:
            tracker.init(frame, (x0, y0, x1 - x0, y1 - y0))
            frame = cv2.rectangle(frame, (x0, y0), (x1, y1), (0, 0, 255), 3)
        else:
            tracker.update(frame)
            pos = tracker.getBoundingBox()
            frame = cv2.rectangle(frame, (x0, y0), (x1, y1), (0, 255, 0), 3)
            frame = cv2.rectangle(frame, (int(pos[0]), int(pos[1])), (int(pos[0] + pos[2]), int(pos[1] + pos[3])), (0, 0, 255), 3)

        cv2.imshow('preview', frame)
        k = cv2.waitKey(30)

        if k != -1:
            break

        i += 1

def correlation_cmt_test(camera):
    eye = Eye(camera)
    eye.cap.set(cv2.CAP_PROP_POS_FRAMES, 0)

    tracker = DSST(enableTrackingLossDetection=True, psrThreshold=8)
    found = True

    while True:
        frame = eye.getColorFrame()
        cv2.imshow('preview', frame)
        k = cv2.waitKey(1)
        if not k == -1:
            break

    frame, gray = eye.getBothFrames()
    tl, br = get_rect(frame)
    cmt = CMT(gray, tl, br)
    tracker.init(frame, (tl[0], tl[1], br[0]-tl[0], br[1]-tl[1]))

    while True:
        frame = eye.getColorFrame()

        if not found:
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            cmt.process_frame(gray)

            if cmt.has_result:
                bb = np.rint(cmt.bb)
                found = tracker.updateAt(frame, (int(bb[0]), int(bb[1]), int(bb[2]), int(bb[3])))
            else:
                found = tracker.update(frame)
        else:
            found = tracker.update(frame)

        pos = tracker.getBoundingBox()

        if found:
            frame = cv2.rectangle(frame, (int(pos[0]), int(pos[1])), (int(pos[0] + pos[2]), int(pos[1] + pos[3])), (0, 255, 0), 3)
        else:
            frame = cv2.rectangle(frame, (int(pos[0]), int(pos[1])), (int(pos[0] + pos[2]), int(pos[1] + pos[3])), (0, 0, 255), 3)

        cv2.imshow('frame', frame)
        k = cv2.waitKey(1)
        if not k == -1:
            break

def correlation_hom_test(camera):
    eye = Eye(camera)
    eye.cap.set(cv2.CAP_PROP_POS_FRAMES, 0)

    tracker = DSST(enableTrackingLossDetection=True, psrThreshold=10, cellSize=4, padding=2)
    found = True

    failedSuggestions = 0

    detector = cv2.BRISK_create()
    computer = cv2.xfeatures2d.SURF_create()

    FLANN_INDEX_KDTREE = 0
    index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
    search_params = dict(checks = 50)
    matcher = cv2.BFMatcher()
    # matcher = cv2.FlannBasedMatcher(index_params, search_params)

    while True:
        frame = eye.getColorFrame()
        cv2.imshow('preview', frame)
        k = cv2.waitKey(1)
        if not k == -1:
            break

    frame, gray = eye.getBothFrames()
    tl, br = get_rect(frame)

    roi = gray[tl[1]:br[1], tl[0]:br[0]]
    kp1 = detector.detect(roi, None)

    if len(kp1) == 0:
        print('Warning, no keypoints.')

    kp1, des1 = computer.compute(roi, kp1)

    h, w = roi.shape

    bb = (tl[0], tl[1], br[0]-tl[0], br[1]-tl[1])
    pos = bb
    tracker.init(frame, bb)

    count = 0

    while True:
        frame = eye.getColorFrame()

        found = tracker.update(frame)

        if not found:
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            kp2 = detector.detect(gray, None)
            kp2, des2 = computer.compute(gray, kp2)

            matches = matcher.knnMatch(des1, des2, k=2)

            # store all the good matches as per Lowe's ratio test.
            good = []
            for m, n in matches:
                if m.distance < 0.8 * n.distance:
                    good.append(m)

            if len(good) > 10:
                src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1,1,2)
                dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1,1,2)
                M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)

                if M is None:
                    continue

                pts = np.float32([[0,0],[0,h-1],[w-1,h-1],[w-1,0]]).reshape(-1,1,2)
                dst = cv2.perspectiveTransform(pts, M)
                dst = np.int32(dst.ravel())
                x = dst[::2]
                y = dst[1::2]

                x0 = int(min(x))
                x1 = int(max(x))
                y0 = int(min(y))
                y1 = int(max(y))

                bb = (x0, y0, x1 - x0, y1 - y0)

                if any(x < 0 for x in bb):
                    continue
                else:
                    if failedSuggestions > 1:
                        tracker.init(frame, bb)
                        found = True
                    else:
                        found = tracker.updateAt(frame, bb)

                    if not found:
                        failedSuggestions += 1
                    else:
                        failedSuggestions = 0

        pos = tracker.getBoundingBox()

        if found:
            frame = cv2.rectangle(frame, (int(pos[0]), int(pos[1])), (int(pos[0] + pos[2]), int(pos[1] + pos[3])), (0, 255, 0), 3)
        else:
            frame = cv2.rectangle(frame, (int(pos[0]), int(pos[1])), (int(pos[0] + pos[2]), int(pos[1] + pos[3])), (0, 0, 255), 3)

        count += 1

        cv2.imshow('frame', frame)
        k = cv2.waitKey(1)
        if not k == -1:
            break

def correlation_template_test(camera, start=None, bb=None, sequence=False):
    eye = Eye(camera, sequence)

    if start is not None:
        eye.cap.set(cv2.CAP_PROP_POS_FRAMES, start)

    tracker = DSST(enableTrackingLossDetection=True, psrThreshold=10, cellSize=4, padding=2)
    found = True

    p = Line2DParameters()
    line = Line2D(p)

    if bb is None:
        while True:
            frame = eye.getColorFrame()
            cv2.imshow('preview', frame)
            k = cv2.waitKey(1)
            if not k == -1:
                break

        tl, br = get_rect(frame)

        bb = (tl[0], tl[1], br[0]-tl[0], br[1]-tl[1])

        print(bb)

        if not sequence:
            print(eye.cap.get(cv2.CAP_PROP_POS_FRAMES))
        else:
            print(eye.counter)

    frame = eye.getColorFrame()
    w, h = bb[2], bb[3]

    roi = frame[bb[1]:bb[1]+bb[3], bb[0]:bb[0]+bb[2]]
    index = line.addTemplate(roi, 'track')

    tracker.init(frame, bb)

    count = 0
    updateInterval = 10

    maxTemplates = 100
    templates = {index: 100}

    while True:
        frame = eye.getColorFrame()

        found = tracker.update(frame)
        pos = tracker.getBoundingBox()

        if not found:
            matches = line.match(frame, 90)
            if len(matches) > 0:
                bestMatch = list(matches)[0]
                print(bestMatch.similarity)
                found = tracker.updateAt(frame, (bestMatch.x, bestMatch.y, bestMatch.width, bestMatch.height))

                if found:
                    templates[bestMatch.template_id] += 1
        else:
            if count > updateInterval:
                if len(templates) == maxTemplates:
                    # Purge old templates.
                    minTimes = min(templates, key=templates.get)

                    line.removeTemplate('track', minTimes)
                    del[minTimes]

                roi = frame[pos[1]:pos[1]+pos[3], pos[0]:pos[0]+pos[2]]
                index = line.addTemplate(roi, 'track')
                templates[index] = 0

                count = 0

        if found:
            frame = cv2.rectangle(frame, (int(pos[0]), int(pos[1])), (int(pos[0] + pos[2]), int(pos[1] + pos[3])), (0, 255, 0), 3)
        else:
            frame = cv2.rectangle(frame, (int(pos[0]), int(pos[1])), (int(pos[0] + pos[2]), int(pos[1] + pos[3])), (0, 0, 255), 3)

        count += 1

        # Make it larger for POC.
        # frame = cv2.resize(frame, (0, 0), fx=2, fy=2)

        cv2.imshow('frame', frame)
        k = cv2.waitKey(1)
        k = chr(k & 255)

        if k == 'q':
            data = line.exportClass('track')
            file = open('track.yaml', 'w')
            file.write(data)
            file.close()
            break

frameNumber = 0
saveFolder = 'C:/users/bobbyluig/desktop/kenneth'
save = False

def showSave(name, image):
    global frameNumber, save

    cv2.imshow(name, image)

    if save:
        fileName = os.path.join(saveFolder, '%04d.png' % frameNumber)
        cv2.imwrite(fileName, image)

        frameNumber += 1

def kenneth():
    from PIL import Image, ImageFont, ImageDraw, ImageOps

    eye = Eye('C:\\Users\\bobbyluig\\Desktop\\Eclipse Large\\k.mp4')

    tracker = DSST(enableTrackingLossDetection=True, psrThreshold=10, cellSize=4, padding=2)
    found = True

    font = ImageFont.truetype("arialbd.ttf", 14)
    largeFont = ImageFont.truetype("arial.ttf", 50)

    strip = Image.new('RGB', (1280, 80), (0, 0, 0))
    draw = ImageDraw.Draw(strip)

    msg = 'Waiting for Tracker Initialization'
    tW, tH = draw.textsize(msg, font=largeFont)
    draw.text(((1280 - tW) / 2, (80 - tH) / 2), msg, font=largeFont, fill='white')

    while eye.cap.get(cv2.CAP_PROP_POS_FRAMES) < 209:
        frame = eye.getColorFrame()
        strip = np.array(strip)
        frame = np.concatenate((frame, strip), axis=0)

        showSave('frame', frame)

        k = cv2.waitKey(20)
        if not k == -1:
            break

    bb = (529, 102, 159, 249)
    frame = eye.getColorFrame()
    w, h = bb[2], bb[3]

    roi = frame[bb[1]:bb[1]+bb[3], bb[0]:bb[0]+bb[2]]
    roi = cv2.resize(roi, (w // 5, h // 5))
    template = cv2.Canny(roi, 50, 200)

    tracker.init(frame, bb)

    count = 0
    updateInterval = 10

    maxTemplates = 10
    templates = [template] + [None] * (maxTemplates - 1)
    templateUses = [100] + [0] * (maxTemplates - 1)

    while True:
        frame = eye.getColorFrame()

        found = tracker.update(frame)
        pos = tracker.getBoundingBox()

        tmp = cv2.resize(frame, (0,0), fx=0.2, fy=0.2)
        gray = cv2.cvtColor(tmp, cv2.COLOR_BGR2GRAY)
        edged = cv2.Canny(gray, 50, 200)
        values = np.array([])
        locs = []
        for template in templates:
            if template is not None:
                res = cv2.matchTemplate(edged, template, cv2.TM_CCOEFF_NORMED)
                _, maxVal, _, maxLoc = cv2.minMaxLoc(res)
                values = np.append(values, maxVal)
                locs.append(maxLoc)

        index = np.argmax(values)
        maxLoc = locs[index]

        orangeIndex = None
        greenIndex = None

        if not found:
            if values[index] > 0.15:
                found = tracker.updateAt(frame, (maxLoc[0] * 5, maxLoc[1] * 5, pos[2], pos[3]))
                frame = cv2.rectangle(frame, (maxLoc[0] * 5, maxLoc[1] * 5),
                                      (int(maxLoc[0] * 5 + round(pos[2])), int(maxLoc[1] * 5 + round(pos[3]))), (255, 0, 255), 3)
                orangeIndex = index

            if found:
                templateUses[index] += 10
        else:
            if ((maxLoc[0] * 5 - pos[0])**2 + (maxLoc[1] * 5 - pos[1])**2) ** (1/2) < 90:
                templateUses[index] += 1
                greenIndex = index

            if count > updateInterval:
                if templates.count(None) == 0:
                    # Purge old templates.
                    minTimes = min(templateUses)
                    index = templateUses.index(minTimes)

                    templates[index] = None
                    templateUses[index] = 0

                if cv2.Laplacian(frame, cv2.CV_64F).var() > 50:
                    roi = frame[pos[1]:pos[1]+pos[3], pos[0]:pos[0]+pos[2]]
                    roi = cv2.resize(roi, (w // 5, h // 5))
                    template = cv2.Canny(roi, 50, 200)

                    freeIndex = templates.index(None)
                    templates[freeIndex] = template
                    # cv2.imshow('template', template)
                else:
                    print('Blurry frame. Discounted.')

                count = 0

        if found:
            frame = cv2.rectangle(frame, (int(pos[0]), int(pos[1])), (int(pos[0] + pos[2]), int(pos[1] + pos[3])), (0, 255, 0), 3)
        else:
            frame = cv2.rectangle(frame, (int(pos[0]), int(pos[1])), (int(pos[0] + pos[2]), int(pos[1] + pos[3])), (0, 0, 255), 3)

        strip = Image.new('RGB', (1280, 80), (0, 0, 0))
        draw = ImageDraw.Draw(strip)

        offset = 5
        for i in range(20):
            if templates[i] is not None:
                template = Image.fromarray(templates[i])
                template = template.convert('RGB')

                if orangeIndex == i:
                    template = ImageOps.expand(template, border=2, fill=(255, 0, 255))
                    strip.paste(template, (offset - 2, 6 - 2))
                elif greenIndex == i:
                    template = ImageOps.expand(template, border=2, fill=(0, 255, 0))
                    strip.paste(template, (offset - 2, 6 - 2))
                else:
                    strip.paste(template, (offset, 6))

                msg = str(templateUses[i])
                tW, tH = draw.textsize(msg, font=font)
                draw.text((offset + (31 - tW) / 2, 61), msg, font=font, fill='white')

            offset += 31 + 30 + 4

        count += 1

        strip = np.array(strip)
        frame = np.concatenate((frame, strip), axis=0)

        showSave('frame', frame)
        k = cv2.waitKey(1)
        if not k == -1:
            break

    '''
    i = 0
    for template in templates:
        cv2.imwrite('%s.png' % i, template)

        i += 1
    '''

def makeBB(array):
    x = array[::2]
    y = array[1::2]

    x0 = int(min(x))
    x1 = int(max(x))
    y0 = int(min(y))
    y1 = int(max(y))

    return (x0, y0, x1 - x0, y1 - y0)

# correlation_template_test('C:\\Users\\bobbyluig\\Desktop\\Eclipse Large\\k.mp4', 209, (529, 102, 159, 249))
correlation_template_test(0)
# correlation_template_test('C:/users/bobbyluig/desktop/vot2015/tunnel/%08d.jpg', bb=makeBB([328.000,339.000,350.000,339.000,350.000,308.000,328.000,308.000]), sequence=True)
# kenneth()

max_stars_repo_name: bobbyluig/eclipse

max_issues_repo_name: bobbyluig/Eclipse

max_forks_repo_name: bobbyluig/Eclipse


text:
#!/usr/bin/env python

import vtk
import math
import time
import numpy
import sys

objs = []

while True:
  try:
    start = int(sys.stdin.readline())
    xs = map(float, sys.stdin.readline().split())
    ys = map(float, sys.stdin.readline().split())
    zs = map(float, sys.stdin.readline().split())
    objs.append((start,xs,ys,zs))
  except:
    break

def comp((s1,xs1,ys1,zs1),(s2,xs2,ys2,zs2)):
  return s1 - s2

# sort for nice colors
objs.sort(comp)

offset = 0

def trajectory(obj,i):
  (_,xs,yz,zs) = obj
  return (xs[i], ys[i], zs[i])

def ball(obj):
  global offset
  sp = vtk.vtkSphereSource()
  (x,y,z) = trajectory(obj,0)
  sp.SetCenter(x,y,z)
  sp.SetRadius(0.02)
  m=vtk.vtkPolyDataMapper()
  m.SetInput(sp.GetOutput())
  a=vtk.vtkActor()
  a.SetMapper(m)
  def update():
    (x,y,z) = trajectory(obj,offset)
    sp.SetCenter(x,y,z)
  return (update,a)

def trace(obj):

  s = vtk.vtkProgrammableSource()
  def execute():
    global offset
    positions = [trajectory(obj,i) for i in range(offset)]

    #construct a VTK polydata object: a single poly-line 'cell'
    dataset = s.GetPolyDataOutput()
    points = vtk.vtkPoints()
    cells = vtk.vtkCellArray()
    cells.InsertNextCell(len(positions))
    for p in positions:
      id = points.InsertNextPoint(*p)
      cells.InsertCellPoint(id)
    dataset.SetPoints(points)
    dataset.SetLines(cells)
    return dataset
  s.SetExecuteMethod(execute)

  m=vtk.vtkPolyDataMapper()
  m.SetInput(s.GetOutput())
  a=vtk.vtkActor()
  a.SetMapper(m)
  def update():
    s.Modified()
  return (update,a)

#boiler-plate VTK stuff....
balls = [ball(o) for o in objs]
traces = [trace(o) for o in objs]

ren = vtk.vtkRenderer()

for (_,a) in balls:
  ren.AddActor(a)
for (_,a) in traces:
  ren.AddActor(a)

renwin = vtk.vtkRenderWindow()
renwin.AddRenderer(ren)

iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renwin)

def animate(obj, evt):
  global offset
  if offset >= len(objs[0][1]): sys.exit()
  for (u,_) in balls: u()
  for (u,_) in traces: u()
  renwin.Render()
  offset += 10

iren.Initialize()
iren.AddObserver("TimerEvent", animate)
iren.CreateRepeatingTimer(1);
iren.Start()

max_stars_repo_name: janduracz/acumen-dev

max_issues_repo_name: janduracz/acumen-dev

max_forks_repo_name: janduracz/acumen-dev


text:
from __future__ import absolute_import

import os
import numpy as np
import re
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from tqdm import tqdm

from learning.model.rnn import RnnModel
from preprocess.dataset import CodeSearchDataset
from preprocess.lex.token import Tokenizer
from preprocess.lex.word_sim import WordSim

class CodeSearcher:
    def __init__(self, conf):
        self.conf = conf
        self.wkdir = self.conf['data']['wkdir']
        self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
        train_data = CodeSearchDataset(os.path.join(conf['data']['wkdir'], conf['data']['train_db_path']))
        self.model = RnnModel(int(conf['data']['query_max_len']), train_data.core_term_size, int(conf['model']['core_term_embedding_size']), int(conf['model']['lstm_hidden_size']), int(conf['model']['lstm_layers']), float(self.conf['train']['margin'])).to(self.device)
        self.batch_size = int(self.conf['train']['batch_size'])

    def save_model(self, epoch):
        model_dir = os.path.join(self.wkdir, 'models')
        if not os.path.exists(model_dir):
            os.mkdir(model_dir)
        torch.save(self.model.state_dict(), os.path.join(model_dir, 'epoch%d.h5' % epoch))

    def load_model(self, epoch):
        model_path = os.path.join(self.wkdir, 'models/epoch%d.h5' % epoch)
        assert os.path.exists(model_path), 'Weights not found.'
        self.model.load_state_dict(torch.load(model_path))

    def train(self):
        train_data = CodeSearchDataset(os.path.join(self.wkdir, self.conf['data']['train_db_path']))
        valid_data = CodeSearchDataset(os.path.join(self.wkdir, self.conf['data']['valid_db_path']))
        test_data = CodeSearchDataset(os.path.join(self.wkdir, self.conf['data']['test_db_path']))
        train_size = len(train_data)
        if torch.cuda.device_count() > 1:
            print("let's use ", torch.cuda.device_count(), "GPUs")

        save_round = int(self.conf['train']['save_round'])
        nb_epoch = int(self.conf['train']['nb_epoch'])
        batch_size = self.batch_size
        dataloader = DataLoader(train_data, batch_size=batch_size, shuffle=True)
        optimizer = optim.Adam(self.model.parameters(), lr=float(self.conf['train']['lr']))

        for epoch in range(nb_epoch):
            self.model.train()
            epoch_loss = 0
            for _, pos_matrix, pos_core_terms, pos_length, neg_matrix, neg_core_terms, neg_length, neg_ids in tqdm(dataloader):
                pos_length = [self.gVar(x) for x in pos_length]
                neg_length = [self.gVar(x) for x in neg_length]
                loss = self.model.loss(self.gVar(pos_matrix), self.gVar(pos_core_terms), pos_length,
                                  self.gVar(neg_matrix), self.gVar(neg_core_terms), neg_length)
                optimizer.zero_grad()
                loss.backward()
                optimizer.step()
                epoch_loss += loss.item()
            print('epoch', epoch, ': Loss =', epoch_loss / (train_size/batch_size))
            if epoch % save_round == 0:
                self.save_model(epoch)
            print('Validation...')
            self.eval(valid_data)
            print('Test...')
            self.eval(test_data)

    def eval2(self):
        data = Tokenizer().parse(os.path.join(self.wkdir, self.conf['data']['test_nl_path']), os.path.join(self.wkdir, self.conf['data']['test_code_path']))
        fasttext_corpus_path = os.path.join(self.wkdir, re.sub(r'\.db$', '.txt', self.conf['data']['test_db_path']))
        core_term_path = os.path.join(self.wkdir, 'conf/core_terms.txt')
        word_sim = WordSim(core_term_path, pretrain=(self.conf['model']['pretrained_wordvec'] == str(True)), update=False, fasttext_corpus_path=fasttext_corpus_path)
        CodeSearchDataset.eval(self.model, data, word_sim, int(self.conf['data']['query_max_len']), int(self.conf['data']['code_max_len']), self.device)

    def eval(self, test_data):
        self.model.eval()
        batch_size = self.batch_size
        dataloader = DataLoader(test_data, batch_size=batch_size, shuffle=True)

        def top_k_acc(pos_score, neg_score, k):
            ranks = compute_rank(pos_score, neg_score)
            result = [1 for r in ranks if r <= k]
            count = sum(result)
            return count/len(ranks)

        def mrr(pos_score, neg_score):
            ranks = compute_rank(pos_score, neg_score)
            reciprocal = [1/r for r in ranks]
            return sum(reciprocal)/len(ranks)

        def compute_rank(pos_score, neg_score):
            ranks = [len(neg_score[0])+1]*len(pos_score)
            for i, pos_ in enumerate(pos_score):
                sort_neg_score = sorted(neg_score[i], reverse=True)
                for j, neg_ in enumerate(sort_neg_score):
                    if pos_ > neg_:
                        ranks[i] = j + 1
                        break
            return ranks

        top_k = 10
        accs = [[] for _ in range(top_k)]
        mrrs = []
        for q_id, pos_matrix, pos_core_terms, pos_length, neg_matrix, neg_core_terms, neg_length, neg_ids in dataloader:
            pos_length = [self.gVar(x) for x in pos_length]
            neg_length = [self.gVar(x) for x in neg_length]
            pos_score = self.model(self.gVar(pos_matrix), pos_length, self.gVar(pos_core_terms)).data.cpu().numpy()
            neg_score = self.model(self.gVar(neg_matrix), neg_length, self.gVar(neg_core_terms)).data.cpu().numpy()
            neg_score = np.split(neg_score, len(pos_score))
            for i in range(top_k):
                accs[i].append(top_k_acc(pos_score, neg_score, i+1))
            mrrs.append(mrr(pos_score, neg_score))
        for i in range(top_k):
            print('Hit@{}: {}'.format(i+1, np.mean(accs[i])))
        print('MRR: {}'.format(np.mean(mrrs)))

    def gVar(self, tensor):
        return tensor.to(self.device)


text:
'''

Plot Zernike polynomials.  Uses the first 14 modes of OSA/ANSI indexing

3D ploting based on matplotlib example by Armin Moser: surface3d_radial_demo.py

'''

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import numpy as np

# Define functions and corresponding labels.
# Using first 14 modes in OSA/ANSI indexing

Z_polys = ['1',
           '2*R*np.sin(Theta)',
           '2*R*np.cos(Theta)',
           'np.sqrt(6)*R**2*np.sin(2*Theta)',
           'np.sqrt(3)*(2*R**2 - 1)',
           'np.sqrt(6)*R**2*np.cos(2*Theta)',
           'np.sqrt(8)*R**3*np.sin(3*Theta)',
           'np.sqrt(8)*(3*R**3 - 2*R)*np.sin(Theta)',
           'np.sqrt(8)*(3*R**3 - 2*R)*np.cos(Theta)',
           'np.sqrt(8)*R**3*np.cos(3*Theta)',
           'np.sqrt(10)*R**4*np.sin(4*Theta)',
           'np.sqrt(10)*(4*R**4 - 3*R**2)*np.sin(2*Theta)',
           'np.sqrt(5)*(6*R**4 - 6*R**2 + 1)',
           'np.sqrt(10)*(4*R**4 - 3*R**2)*np.cos(2*Theta)',
           'np.sqrt(10)*R**4*np.cos(4*Theta)',
          ]

Z_labels = [r'$Z^0_0 , Z_j = 1$, Piston',
            r'$Z^{-1}_1, Z_j = 2\rho sin(\theta),$  Vertical tilt ',
            r'$Z^{1}_1, Z_j = 2\rho cos(\theta),$  Horizontal tilt ',
            r'$Z^{-2}_2, Z_j = \sqrt{6} \rho^2 \sin{2\theta},$  Oblique Astigmatism ',
            r'$Z^{0}_2, Z_j = \sqrt{3} (2\rho^2 -1),$  Defocus',
            r'$Z^{2}_2, Z_j = \sqrt{6} \rho^2 \cos{2\theta},$  Vertical Astigmatism ',
            r'$Z^{-3}_3, Z_j = \sqrt{8} \rho^3 \sin{3\theta},$  Vertical Trefoil ',
            r'$Z^{-1}_3, Z_j = \sqrt{8} (3\rho^3 - 2\rho) \sin{\theta},$  Vertical coma ',
            r'$Z^{1}_3, Z_j = \sqrt{8} (3\rho^3 - 2\rho) \cos{\theta},$  Horizontal coma ',
            r'$Z^{3}_3, Z_j = \sqrt{8} \rho^3 \cos{3\theta},$  Oblique Trefoil ',
            r'$Z^{-4}_4, Z_j = \sqrt{10} \rho^4 \sin{4\theta},$  Oblique Quadrafoil ',
            r'$Z^{-2}_4, Z_j = \sqrt{10} (4\rho^4 - 3\rho^2) \sin{2\theta},$  Oblique Secondary Astigmatism ',
            r'$Z^{0}_4, Z_j = \sqrt{5} (6\rho^4 - 6\rho^2 + 1),$  Primary Spherical ',
            r'$Z^{2}_4, Z_j = \sqrt{10} (4\rho^4 - 3\rho^2) \cos{2\theta},$  Vertical Secondary Astigmatism ',
            r'$Z^{4}_4, Z_j = \sqrt{10} \rho^4 \cos{4\theta},$  Vertical Quadrafoil ',
            ]

def plot_zernikes(osa_index):
    """ can make plots up to index 14 (OSA/ANSI)
    """

    # Create the mesh in polar coordinates and compute corresponding Z.
    r = np.linspace(0, 1.25, 100)
    theta = np.linspace(0, 2*np.pi, 100)
    R, Theta = np.meshgrid(r, theta)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    Z = eval(Z_polys[osa_index])  #select polynomial

    # Express the mesh in the cartesian system.
    X, Y = R*np.cos(Theta), R*np.sin(Theta)

    plt.title(Z_labels[osa_index])
    ax.plot_surface(X, Y, Z, cmap=plt.cm.jet)
    ax.set_zlim(-2*np.pi, 2*np.pi)

    plt.show()

#plot each one.
for i in np.arange(0,15):
    plot_zernikes(i)

#zernike terms
#Z = 1                                       #Z0,0: Piston
#Z = 2*R*np.sin(Theta)                       #Z-1,1: Y, verical tilt
#Z = 2*R*np.cos(Theta)                       #Z1,1: X, horizontal tilt
#Z = np.sqrt(6)*R**2*np.sin(2*Theta)        #Z-2,2: Oblique Astigmatism
#Z = np.sqrt(3)*(2*R**2 - 1)                #Z0,2: Defocus
#Z = np.sqrt(6)*R**2*np.cos(2*Theta)        #Z2,2: Vertical Astigmatism
#Z = np.sqrt(8)*R**3*np.sin(3*Theta)         #Z-3,3 Vertical trefoil
#Z = np.sqrt(8)*(3*R**3 - 2*R)*np.sin(Theta)  #Z-1,3: Vertical Coma
#Z = np.sqrt(8)*(3*R**3 - 2*R)*np.cos(Theta)  #Z1,3: Horizontal Coma
#Z = np.sqrt(8)*R**3*np.cos(3*Theta)          #Z3,3: Oblique trefoil
#Z = np.sqrt(10)*R**4*np.sin(4*Theta)         #Z-4,4: Oblique quadrafoil
#Z = np.sqrt(10)*(4*R**4 - 3*R**2)*np.sin(2*Theta)  #Z-2,4: Oblique secondary astigmatism
#Z = np.sqrt(5)*(6*R**4 - 6*R**2 + 1)                 #Z0,4: Primary spherical
#Z = np.sqrt(10)*(4*R**4 - 3*R**2)*np.cos(2*Theta)   #Vertical secondary astigmatism
#Z = np.sqrt(10)*R**4*np.cos(4*Theta)                #Vertical quadrafoil

max_stars_repo_name: jfblanchard/optical-tools

max_issues_repo_name: jfblanchard/optical-tools

max_forks_repo_name: jfblanchard/optical-tools


text:
from garage.tf.samplers.on_policy_vectorized_sampler import OnPolicyVectorizedSampler
import pickle

import tensorflow as tf
from garage.sampler.base import BaseSampler
from garage.tf.envs.parallel_vec_env_executor import ParallelVecEnvExecutor
from garage.tf.envs.vec_env_executor import VecEnvExecutor
from garage.misc import tensor_utils
import numpy as np
from garage.sampler.stateful_pool import ProgBarCounter
import garage.misc.logger as logger
import itertools
import pdb
from mylab.simulators.example_av_simulator import ExampleAVSimulator
from mylab.rewards.example_av_reward import ExampleAVReward

class ASTVectorizedSampler(OnPolicyVectorizedSampler):
    def __init__(self, algo, open_loop = True, sim = ExampleAVSimulator(), reward_function = ExampleAVReward()):
        # pdb.set_trace()
        self.open_loop = open_loop
        self.sim = sim
        self.reward_function = reward_function
        super().__init__(algo)

    def obtain_samples(self, itr):
        # pdb.set_trace()
        paths = super().obtain_samples(itr)
        if self.open_loop:
            for path in paths:
                s_0 = path["observations"][0]
                actions = path['env_infos']['info']['actions']
                end_idx, info = self.sim.simulate(actions = actions, s_0 = s_0)
                if end_idx >= 0:
                    # pdb.set_trace()
                    self.slice_dict(path, end_idx)
                rewards = self.reward_function.give_reward(
                    action = actions[end_idx],
                    info = self.sim.get_reward_info()
                )
                # pdb.set_trace()
                path["rewards"][end_idx] = rewards
                info[:,-1] = path["rewards"][:info.shape[0]]
                path['env_infos']['info']['cache'] = info

        return paths

    def slice_dict(self, in_dict, slice_idx):
        for key, value in in_dict.items():
            # pdb.set_trace()
            if type(value) is dict:
                in_dict[key] = self.slice_dict(value, slice_idx)
            else:
                in_dict[key][slice_idx + 1:, ...] = np.zeros_like(value[slice_idx + 1:, ...])

        return in_dict

max_stars_repo_name: mark-koren/AdaptiveStressTestingToolbox

max_issues_repo_name: mark-koren/AdaptiveStressTestingToolbox

max_forks_repo_name: mark-koren/AdaptiveStressTestingToolbox