text:
# -*- coding: utf-8 -*-

import os.path
import pickle
import time
import numpy as np
import torch
from tttPlayer import tttPlayer
from tttTable import tttTable
from tttTrainer import tttTrainer

# Hyperparameters:
learning_rate = 0.01
howManyHidden0 = 63
howManyHidden1 = 63
decayFactor = 1
sheepConfidenceFactor = 0.3
lionConfidenceFactor = 0.9
sheepProbPicker = 1
lionProbPicker = 0
numGamesVsRandPerIter = 100
numGamesVsSelfPerIter = 100
numGamesVsLionPerIter = 400
numTrainIters = 1000
numPlayTrainCycles = 30
useGPU = 1

numTestRandGames = 500
numTestOptGames = 500

theDevice = myDevice = torch.device("cuda:0")

# check to see if the network is already in the namespace (maybe unneeded now?)
storedNetworks = 0
if os.path.isfile("sheepNetMaybe.pickle"):
    storedNetworks = 1

# Generate data from randomly played games
randTable = tttTable()
randTrainer = tttTrainer(0,decayFactor,sheepConfidenceFactor)

winPctRandVsRand = 0
for ii in range(1000):
    randTable.playMatch()
    if ii%100 == 0:
        print(ii/100)
    randTrainer.addToDatabase(randTable)

# Figuring stupid tables out
boardArr = np.array(list(randTrainer.boards.values()))
evalArr = np.array(list(randTrainer.evals.values()))
numBoards = boardArr.shape[0]
boardTensFlat = torch.tensor(boardArr.reshape(numBoards,9), dtype = torch.float32)
evalTensFlat = torch.tensor(evalArr.reshape(numBoards,9), dtype = torch.float32)
numBoards = boardArr.shape[0]
if useGPU == 1:
    boardTensFlat = boardTensFlat.cuda()
    evalTensFlat = evalTensFlat.cuda()

if storedNetworks == 0:
    # Create two neural Networks
    sheepNet = torch.nn.Sequential(
        torch.nn.Linear(9, howManyHidden0),
        torch.nn.Sigmoid(),
        torch.nn.Linear(howManyHidden0, howManyHidden1),
        torch.nn.Sigmoid(),
        torch.nn.Linear(howManyHidden1, 9),
        torch.nn.Sigmoid(),
    )
    if useGPU == 1:
        sheepNet = sheepNet.cuda()
    origSheepEval = sheepNet(boardTensFlat)

    lionNet = torch.nn.Sequential(
        torch.nn.Linear(9, howManyHidden0),
        torch.nn.Sigmoid(),
        torch.nn.Linear(howManyHidden0, howManyHidden1),
        torch.nn.Sigmoid(),
        torch.nn.Linear(howManyHidden1, 9),
        torch.nn.Sigmoid(),
    )
    if useGPU == 1:
        lionNet = lionNet.cuda()

    # Do initial training of networks
    loss_fn = torch.nn.MSELoss(reduction='sum')
    sheepTimizer = torch.optim.Adam(sheepNet.parameters(), lr=learning_rate)
    lionIzer = torch.optim.Adam(lionNet.parameters(), lr=learning_rate)
    for t in range(numTrainIters):
        sheepEval = sheepNet(boardTensFlat)
        theSheepLoss = loss_fn(sheepEval, evalTensFlat)
        lionEval = lionNet(boardTensFlat)
        theLionLoss = loss_fn(lionEval, evalTensFlat)

        if t % 100 == 99:
            print(t, theSheepLoss.item(), theLionLoss.item())
        sheepTimizer.zero_grad()
        theSheepLoss.backward()
        sheepTimizer.step()
        lionIzer.zero_grad()
        theLionLoss.backward()
        lionIzer.step()
else:
    with open('sheepNetMaybe.pickle', 'rb') as handle:
        sheepNet = pickle.load(handle)
    with open('lionNetMaybe.pickle', 'rb') as handle:
        lionNet = pickle.load(handle)
    if useGPU == 1:
        sheepNet = sheepNet.cuda()
        lionNet = lionNet.cuda()

sheepPlayer = tttPlayer("network", sheepNet, sheepProbPicker)
lionPlayer = tttPlayer("network", lionNet, lionProbPicker)
loss_fn = torch.nn.MSELoss(reduction='sum')
sheepTimizer = torch.optim.Adam(sheepNet.parameters(), lr=learning_rate)
lionIzer = torch.optim.Adam(lionNet.parameters(), lr=learning_rate)

# Initialize Tables for Sheep and Lion to play and respective Trainers
sheepVsRandTable = tttTable("network","random",sheepPlayer,0)
sheepVsSelfTable = tttTable("network","network",sheepPlayer,sheepPlayer)
sheepVsLionTable = tttTable("network","network",sheepPlayer,lionPlayer)
sheepTrainer = tttTrainer(0, decayFactor, sheepConfidenceFactor)
lionTrainer = tttTrainer(1, decayFactor, lionConfidenceFactor,0.02)

# Play games and train
for jj in range(numPlayTrainCycles):
    print("Play Train Cycle", jj,"\n")
    theStartTime = time.time()
    if useGPU == 1:
        sheepPlayer.net = sheepPlayer.net.cpu()
        cow = 2
        lionPlayer.net = lionPlayer.net.cpu()
    sheepTrainer.clearDatabase()
    lionTrainer.clearDatabase()
    winPctVsRand = 0
    for ii in range(numGamesVsRandPerIter):
        sheepVsRandTable.playMatch()
        sheepTrainer.addToDatabase(sheepVsRandTable)
        if sheepVsRandTable.theBoard.winState == 0:
            winPctVsRand = winPctVsRand + 0.5
        else:
            if ((ii%2 == 0)&(sheepVsRandTable.theBoard.winState == 1))|((ii%2 == 1)&(sheepVsRandTable.theBoard.winState == -1)):
                winPctVsRand = winPctVsRand + 1
        sheepVsRandTable.clearBoard()
        sheepVsRandTable.changeFirstPlayer()
    winPctVsRand /= numGamesVsRandPerIter

    winPctVsSelf = 0
    for ii in range(numGamesVsSelfPerIter):
        sheepVsSelfTable.playMatch()
        sheepTrainer.addToDatabase(sheepVsSelfTable)
        if sheepVsSelfTable.theBoard.winState == 0:
            winPctVsSelf = winPctVsSelf + 0.5
        else:
            if ((ii%2 == 0)&(sheepVsSelfTable.theBoard.winState == 1))|((ii%2 == 1)&(sheepVsSelfTable.theBoard.winState == -1)):
                winPctVsSelf = winPctVsSelf + 1
        sheepVsSelfTable.clearBoard()
        sheepVsSelfTable.changeFirstPlayer()
    winPctVsSelf /= numGamesVsSelfPerIter

    winPctVsLion = 0
    for ii in range(numGamesVsLionPerIter):
        sheepVsLionTable.playMatch()
        sheepTrainer.addToDatabase(sheepVsLionTable)
        lionTrainer.addToDatabase(sheepVsLionTable)
        if sheepVsLionTable.theBoard.winState == 0:
            winPctVsLion = winPctVsLion + 0.5
        else:
            if ((ii%2 == 0)&(sheepVsLionTable.theBoard.winState == 1))|((ii%2 == 1)&(sheepVsLionTable.theBoard.winState == -1)):
                winPctVsLion = winPctVsLion + 1
        sheepVsLionTable.clearBoard()
        sheepVsLionTable.changeFirstPlayer()
    winPctVsLion /= numGamesVsLionPerIter
    if winPctVsLion > 0.5:
        sheepVsLionTable.player1.probPickerOn = 1
    else:
        sheepVsLionTable.player1.probPickerOn = 0

    winPctRandVsRand = 0
    for ii in range(200):
        randTable.playMatch()
        if randTable.theBoard.winState == 0:
            winPctRandVsRand = winPctRandVsRand + 0.5
        else:
            if ((ii%2 == 0)&(randTable.theBoard.winState == 1))|((ii%2 == 1)&(randTable.theBoard.winState == -1)):
                winPctRandVsRand = winPctRandVsRand + 1
        randTable.clearBoard()
        randTable.changeFirstPlayer()
    winPctRandVsRand /= 200

    theEndPlayTime = time.time()
    print([winPctVsRand,winPctVsSelf,winPctVsLion,winPctRandVsRand])
    print("\n")

    sheepBoardArr = np.array(list(sheepTrainer.boards.values()))
    sheepEvalArr = np.array(list(sheepTrainer.evals.values()))
    numSheepBoards = sheepBoardArr.shape[0]
    sheepBoardTensFlat = torch.tensor(sheepBoardArr.reshape(numSheepBoards,9), dtype = torch.float32)
    sheepEvalTensFlat = torch.tensor(sheepEvalArr.reshape(numSheepBoards,9), dtype = torch.float32)
    if useGPU == 1:
        sheepBoardTensFlat = sheepBoardTensFlat.cuda()
        sheepEvalTensFlat = sheepEvalTensFlat.cuda()
        sheepPlayer.net = sheepPlayer.net.cuda()
        sheepTimizer = torch.optim.Adam(sheepNet.parameters(), lr=learning_rate)

    lionBoardArr = np.array(list(lionTrainer.boards.values()))
    lionEvalArr = np.array(list(lionTrainer.evals.values()))
    numLionBoards = lionBoardArr.shape[0]
    lionBoardTensFlat = torch.tensor(lionBoardArr.reshape(numLionBoards,9), dtype = torch.float32)
    lionEvalTensFlat = torch.tensor(lionEvalArr.reshape(numLionBoards,9), dtype = torch.float32)
    if useGPU == 1:
        lionBoardTensFlat = lionBoardTensFlat.cuda()
        lionEvalTensFlat = lionEvalTensFlat.cuda()
        lionPlayer.net = lionPlayer.net.cuda()
        lionIzer = torch.optim.Adam(lionNet.parameters(), lr=learning_rate)

    theStartTrainTime = time.time()
    for t in range(numTrainIters):
        sheepEval = sheepNet(sheepBoardTensFlat)
        theSheepLoss = loss_fn(sheepEval, sheepEvalTensFlat)
        lionEval = lionNet(lionBoardTensFlat)
        theLionLoss = loss_fn(lionEval, lionEvalTensFlat)

        if t % 100 == 99:
            print(t, theSheepLoss.item(), theLionLoss.item())
        sheepTimizer.zero_grad()
        theSheepLoss.backward()
        sheepTimizer.step()
        lionIzer.zero_grad()
        theLionLoss.backward()
        lionIzer.step()
    theEndTime = time.time()
    print('Play Time: ', theEndPlayTime - theStartTime)
    print('Train Time: ', theEndTime - theStartTrainTime)
    print('Total Time: ', theEndTime - theStartTime,'\n')
# This is where playing games and training ends

# Store the trained network and evaluate it
if useGPU == 1:
    sheepPlayer.net = sheepPlayer.net.cpu()
    lionPlayer.net = lionPlayer.net.cpu()

with open('sheepNetMaybe.pickle', 'wb') as handle:
    pickle.dump(sheepNet, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open('lionNetMaybe.pickle', 'wb') as handle:
    pickle.dump(lionNet, handle, protocol=pickle.HIGHEST_PROTOCOL)

winPctVsRand = 0
sheepVsRandTable.player0.probPickerOn = 0
for ii in range(numTestRandGames):
    sheepVsRandTable.playMatch()
    if sheepVsRandTable.theBoard.winState == 0:
        winPctVsRand = winPctVsRand + 0.5
    else:
        if ((ii%2 == 0)&(sheepVsRandTable.theBoard.winState == 1))|((ii%2 == 1)&(sheepVsRandTable.theBoard.winState == -1)):
            winPctVsRand = winPctVsRand + 1
        else:
            print("\nLosing Game: ")
            for jj in range(sheepVsRandTable.numMovesPlayed):
                print(sheepVsRandTable.boardHist[jj,:,:])
                print("\n")
    sheepVsRandTable.clearBoard()
    sheepVsRandTable.changeFirstPlayer()
winPctVsRand /= numTestRandGames
print(winPctVsRand)
sheepVsRandTable.player0.probPickerOn = 1

sheepVsOptTable = tttTable("network","optimal",sheepPlayer)
sheepVsOptTable.player0.probPickerOn = 0
winPctVsOpt = 0
for ii in range(numTestOptGames):
    sheepVsOptTable.playMatch()
    if sheepVsOptTable.theBoard.winState == 0:
        winPctVsOpt += 0.5
    else:
        if ((ii%2 == 0)&(sheepVsOptTable.theBoard.winState == 1))|((ii%2 == 1)&(sheepVsOptTable.theBoard.winState == -1)):
            winPctVsOpt = winPctVsOpt + 1
        else:
            print("\nLosing Game: ")
            for jj in range(sheepVsOptTable.numMovesPlayed):
                print(sheepVsOptTable.boardHist[jj,:,:])
                print("\n")
    sheepVsOptTable.clearBoard()
    sheepVsOptTable.changeFirstPlayer()
winPctVsOpt /= numTestOptGames
print(winPctVsOpt)

sheepVsOptTable.player0.probPickerOn = 1
if useGPU == 1:
    sheepPlayer.net = sheepPlayer.net.cuda()
    sheepTimizer = torch.optim.Adam(sheepNet.parameters(), lr=learning_rate)
    lionPlayer.net = lionPlayer.net.cuda()
    lionIzer = torch.optim.Adam(lionNet.parameters(), lr=learning_rate)

max_stars_repo_name: ianpaulleong/TrainTTTNet

max_issues_repo_name: ianpaulleong/TrainTTTNet

max_forks_repo_name: ianpaulleong/TrainTTTNet


text:
'''
Tools for computing topological features in Riemannian space.

Code taken from https://morphomatics.github.io/,
created by Felix Ambellan and Martin Hanik and Christoph von Tycowicz, 2021.
'''

import numpy as np
import numpy.random as rnd
import numpy.linalg as la

from scipy.linalg import logm, expm_frechet

from pymanopt.manifolds.manifold import Manifold
from pymanopt.tools.multi import multisym

class SPD(Manifold):
    """Returns the product manifold Sym+(d)^k, i.e., a product of k dxd symmetric positive matrices (SPD).

     manifold = SPD(k, d)

     Elements of Sym+(d)^k are represented as arrays of size kxdxd where every dxd slice is an SPD matrix, i.e., a
     symmetric matrix S with positive eigenvalues.

     The Riemannian metric used is the product Log-Euclidean metric that is induced by the standard Euclidean trace
     metric; see
                    Arsigny, V., Fillard, P., Pennec, X., and Ayache., N.
                    Fast and simple computations on tensors with Log-Euclidean metrics.
     """

    def __init__(self, k=1, d=3):
        if d <= 0:
            raise RuntimeError("d must be an integer no less than 1.")

        if k == 1:
            self._name = 'Manifold of symmetric positive definite {d} x {d} matrices'.format(d=d, k=k)
        elif k > 1:
            self._name = 'Manifold of {k} symmetric positive definite {d} x {d} matrices (Sym^+({d}))^{k}'.format(d=d, k=k)
        else:
            raise RuntimeError("k must be an integer no less than 1.")

        self._k = k
        self._d = d

    def __str__(self):
        return self._name

    @property
    def dim(self):
        return int((self._d*(self._d+1)/2) * self._k)

    @property
    def typicaldist(self):
        # typical affine invariant distance
        return np.sqrt(self._k * 6)

    def inner(self, S, X, Y):
        """product metric"""
        return np.sum(np.einsum('...ij,...ij', X, Y))

    def norm(self, S, X):
        """norm from product metric"""
        return np.sqrt(self.inner(S, X, X))

    def proj(self, X, H):
        """orthogonal (with respect to the Euclidean inner product) projection of ambient
        vector ((k,3,3) array) onto the tangent space at X"""
        return dlog(X, multisym(H))

    def egrad2rgrad(self,X,D):
        # should be adj_dexp instead of dexp (however, dexp appears to be self-adjoint for symmetric matrices)
        return dexp(log_mat(X), multisym(D))

    def ehess2rhess(self, X, Hess):
        # TODO
        return

    def exp(self, S, X):
        """Riemannian exponential with base point S evaluated at X"""
        assert S.shape == X.shape

        # (avoid additional exp/log)
        Y = X + log_mat(S)
        vals, vecs = la.eigh(Y)
        return np.einsum('...ij,...j,...kj', vecs, np.exp(vals), vecs)

    retr = exp

    def log(self, S, U):
        """Riemannian logarithm with base point S evaluated at U"""
        assert S.shape == U.shape

        # (avoid additional log/exp)
        return log_mat(U) - log_mat(S)

    def geopoint(self, S, T, t):
        """ Evaluate the geodesic from S to T at time t in [0, 1]"""
        assert S.shape == T.shape and np.isscalar(t)

        return self.exp(S, t * self.log(S, T))

    def rand(self):
        S = np.random.random((self._k, self._d, self._d))
        return np.einsum('...ij,...kj', S, S)

    def randvec(self, X):
        Y = self.rand()
        y = self.log(X, Y)
        return y / self.norm(X, y)

    def zerovec(self, X):
        return np.zeros((self._k, self._d, self._d))

    def transp(self, S, T, X):
        """Parallel transport for Sym+(d)^k.
        :param S: element of Symp+(d)^k
        :param T: element of Symp+(d)^k
        :param X: tangent vector at S
        :return: parallel transport of X to the tangent space at T
        """
        assert S.shape == T.shape == X.shape

        # if X were not in algebra but at tangent space at S
        #return dexp(log_mat(T), dlog(S, X))

        return X

    def eleminner(self, R, X, Y):
        """element-wise inner product"""
        return np.einsum('...ij,...ij', X, Y)

    def elemnorm(self, R, X):
        """element-wise norm"""
        return np.sqrt(self.eleminner(R, X, X))

    def projToGeodesic(self, X, Y, P, max_iter=10):
        '''
        :arg X, Y: elements of Symp+(d)^k defining geodesic X->Y.
        :arg P: element of Symp+(d)^k to be projected to X->Y.
        :returns: projection of P to X->Y
        '''

        assert X.shape == Y.shape
        assert Y.shape == P.shape

        # all tagent vectors in common space i.e. algebra
        v = self.log(X, Y)
        v /= self.norm(X, v)

        w = self.log(X, P)
        d = self.inner(X, v, w)

        return self.exp(X, d * v)

    def pairmean(self, S, T):
        assert S.shape == T.shape

        return self.exp(S, 0.5 * self.log(S, T))

    def dist(self, S, T):
        """Distance function in Sym+(d)^k"""
        return self.norm(S, self.log(S,T))

    def adjJacobi(self, S, T, t, X):
        """Evaluates an adjoint Jacobi field along the geodesic gam from S to T
        :param S: element of the space of differential coordinates
        :param T: element of the space of differential coordinates
        :param t: scalar in [0,1]
        :param X: tangent vector at gam(t)
        :return: tangent vector at X
        """
        assert S.shape == T.shape == X.shape and np.isscalar(t)

        U = self.geopoint(S, T, t)
        return (1 - t) * self.transp(U, S, X)

    def adjDxgeo(self, S, T, t, X):
        """Evaluates the adjoint of the differential of the geodesic gamma from S to T w.r.t the starting point S at X,
        i.e, the adjoint  of d_S gamma(t; ., T) applied to X, which is en element of the tangent space at gamma(t).
        """
        assert S.shape == T.shape == X.shape and np.isscalar(t)

        return self.adjJacobi(S, T, t, X)

    def adjDygeo(self, S, T, t, X):
        """Evaluates the adjoint of the differential of the geodesic gamma from S to T w.r.t the endpoint T at X,
        i.e, the adjoint  of d_T gamma(t; S, .) applied to X, which is en element of the tangent space at gamma(t).
        """
        assert S.shape == T.shape == X.shape and np.isscalar(t)

        return self.adjJacobi(T, S, 1 - t, X)

def log_mat(U):
    """Matrix logarithm, only use for normal matrices U, i.e., U * U^T = U^T * U"""
    vals, vecs = la.eigh(U)
    vals = np.log(np.where(vals > 1e-10, vals, 1))
    return np.real(np.einsum('...ij,...j,...kj', vecs, vals, vecs))

def dexp(X, G):
    """Evaluate the derivative of the matrix exponential at
    X in direction G.
    """
    return np.array([expm_frechet(X[i],G[i])[1] for i in range(X.shape[0])])

def dlog(X, G):
    """Evaluate the derivative of the matrix logarithm at
    X in direction G.
    """
    n = X.shape[1]
    # set up [[X, G], [0, X]]
    W = np.hstack((np.dstack((X, G)), np.dstack((np.zeros_like(X), X))))
    return np.array([logm(W[i])[:n, n:] for i in range(X.shape[0])])

def vectime3d(x, A):
    """
    :param x: vector of length k
    :param A: array of size k x n x m
    :return: k x n x m array such that the j-th n x m slice of A is multiplied with the j-th element of x
    """
    assert np.size(x.shape[0]) == 2 and np.size(A) == 3
    assert x.shape[0] == 1 or x.shape[1] == 1
    assert x.shape[0] == A.shape[0] or x.shape[1] == A.shape[0]

    if x.shape[0] == 1:
        x = x.T
    A = np.einsum('kij->ijk', A)
    return np.einsum('ijk->kij', x * A)

def vectime3dB(x, A):
    """
    :param x: vector of length k
    :param A: array of size k x n x m
    :return: k x n x m array such that the j-th n x m slice of A is multiplied with the j-th element of x

    In case of k=1, x * A is returned.
    """
    if np.isscalar(x) and A.ndim == 2:
        return x * A

    x = np.atleast_2d(x)
    assert x.ndim <= 2 and np.size(A.shape) == 3
    assert x.shape[0] == 1 or x.shape[1] == 1
    assert x.shape[0] == A.shape[0] or x.shape[1] == A.shape[0]

    if x.shape[1] == 1:
        x = x.T
    A = np.einsum('kij->ijk', A)
    return np.einsum('ijk->kij', x * A)

ext: py

max_stars_repo_name: basiralab/RegGNN

max_issues_repo_name: basiralab/RegGNN

max_forks_repo_name: basiralab/RegGNN

reason: import numpy,from scipy


text:
import tvm
import os
import numpy as np
import argparse
from tvm import relay
from tvm.relay import testing
from tvm.relay.testing.init import create_workload
from tvm.relay.testing import layers
from tvm import autotvm
from tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner
import tvm.contrib.graph_runtime as runtime

def get_operator(data_shape, out_channel, kernel_size, strides, padding, dtype="float32"):
    data = relay.var("data", shape=data_shape, dtype=dtype)
    body = layers.conv2d(data=data, channels=out_channel, kernel_size=kernel_size, strides=strides, padding=padding, name="conv2d")
    return relay.Function(relay.ir_pass.free_vars(body), body)

def get_workload(batch_size, image_shape, out_channel, kernel_size=(3, 3), strides=(1, 1), padding=(1, 1), dtype="float32"):
    data_shape = (batch_size, *image_shape)
    op = get_operator(data_shape, out_channel, kernel_size, strides, padding, dtype=dtype)
    sym, params = create_workload(op)
    return sym, params, data_shape

target = tvm.target.cuda()
batch_size = 64
image_shape = (3, 227, 227)
out_channel = 96
kernel_size = (7, 7)
strides = (2, 2)
padding = (0, 0)
dtype = "float32"

def tune_kernels(tasks, measure_option, tuner="gridsearch", early_stopping=None, log_filename="tuning.log"):
    for i, task in enumerate(tasks):
        prefix = "[Task %2d/%2d] " % (i + 1, len(tasks))

        # create tuner
        if tuner == 'xgb' or tuner == 'xgb-rank':
            tuner_obj = XGBTuner(task, loss_type='rank')
        elif tuner == 'ga':
            tuner_obj = GATuner(task, pop_size=100)
        elif tuner == 'random':
            tuner_obj = RandomTuner(task)
        elif tuner == 'gridsearch':
            tuner_obj = GridSearchTuner(task)
        else:
            raise ValueError("Invalid tuner: " + tuner)

        # do tuning
        n_trial = 2000
        length = len(task.config_space)
        print("length=", length)
        tuner_obj.tune(n_trial=min(n_trial, length),
                       early_stopping=early_stopping,
                       measure_option=measure_option,
                       callbacks=[
                           autotvm.callback.progress_bar(n_trial, prefix=prefix),
                           autotvm.callback.log_to_file(log_filename)])

def tune_and_evaluate(tuning_opt, number, tune=True):
    op, params, data_shape = get_workload(batch_size, image_shape, out_channel, kernel_size, strides, padding)
    tasks = autotvm.task.extract_from_program(op, target=target, params=params, ops=(relay.op.nn.conv2d,))
    log_file = tuning_opt["log_filename"]
    if tune:
        print("Tuning...")
        tune_kernels(tasks, **tuning_opt)

    if not os.path.exists(log_file):
        raise RuntimeError("the log file {} doesn't exists".format(log_file))
    with autotvm.apply_history_best(log_file):
        print("Compile...")
        with relay.build_config(opt_level=3):
            graph, lib, params = relay.build_module.build(op, target=target, params=params)

        ctx = tvm.context(str(target), 0)
        data_tvm = tvm.nd.array((np.random.uniform(size=data_shape)).astype(dtype))
        module = runtime.create(graph, lib, ctx)
        module.set_input("data", data_tvm)
        module.set_input(**params)

        # evaluate
        print("Evaluate inference time cost...")
        ftimer = module.module.time_evaluator("run", ctx, number=1, repeat=number)
        prof_res = np.array(ftimer().results) * 1e3
        print("Time cost is: ", np.mean(prof_res))

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-t", "--tune", help="tune mode", action="store_true")
    parser.add_argument("-n", "--number", type=int, default=100)
    parser.add_argument("-f", "--file", type=str, default="tune_log.log")
    parser.add_argument("-c", "--choice", type=str, default="gridsearch")
    args = parser.parse_args()
    tuning_option = {
        "log_filename": args.file,
        "tuner": args.choice,
        "early_stopping": 600,
        "measure_option": autotvm.measure_option(
            builder=autotvm.LocalBuilder(timeout=10),
            runner=autotvm.LocalRunner(number=20, repeat=3, timeout=4, min_repeat_ms=150),
            # runner=autotvm.RPCRunner(
            #     '1080ti',  # change the device key to your key
            #     '0.0.0.0', 9190,
            #     number=20, repeat=3, timeout=4, min_repeat_ms=150)
        ),
    }
    tune_and_evaluate(tuning_option, args.number, args.tune)

max_stars_repo_name: imxian/FlexTensor

max_issues_repo_name: KnowingNothing/FlexTensor-Micro

max_forks_repo_name: KnowingNothing/FlexTensor-Micro

reason: import numpy


text:
import tensorflow as tf
import numpy as np

sentence = "if you want to build a ship, don't drum up people together to " \
           "collect wood and don't assign them tasks and work, but rather " \
           "teach them to long for the endless immensity of the sea."

char_set = list(set(sentence))
char_dic = {w: i for i, w in enumerate(char_set)}
idx2char = {v: k for k, v in char_dic.items()}

data_dim = len(char_set)
hidden_size = len(char_set)
num_classes = len(char_set)

dataX = []
dataY = []

seq_length = 10
batch_size = 170

for i in range(0, len(sentence) - seq_length):
    x_str = sentence[i: i + seq_length]
    y_str = sentence[i+1: i + seq_length + 1]
    print(i, x_str, '->', y_str)

    x = [char_dic[c] for c in x_str]
    y = [char_dic[c] for c in y_str]

    dataX.append(x)
    dataY.append(y)

X = tf.placeholder(tf.int32, [None, seq_length])
Y = tf.placeholder(tf.int32, [None, seq_length])

X_one_hot = tf.one_hot(X, num_classes)

cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_size, state_is_tuple=True)
initial_state = cell.zero_state(batch_size, tf.float32)
outputs, _states = tf.nn.dynamic_rnn(cell, X_one_hot, initial_state=initial_state, dtype=tf.float32)

weights = tf.ones([batch_size, seq_length])
sequence_loss = tf.contrib.seq2seq.sequence_loss(logits=outputs, targets=Y, weights=weights)
loss = tf.reduce_mean(sequence_loss)
train = tf.train.AdamOptimizer(learning_rate=0.1).minimize(loss)

prediction = tf.argmax(outputs, axis=2)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(3000):
        l, _ = sess.run([loss, train], feed_dict={X: dataX, Y: dataY})
        result = sess.run(prediction, feed_dict={X: dataX})
        result_str = [idx2char[c] for c in np.squeeze(np.reshape(result, [1, -1]))]  # np.squeeze() : 1차원 엔트리들을 모두 지운다.
        print(i, 'loss: ', l, 'Prediction: ', ''.join(result_str))


text:
def brute_force_root_finder(f, a, b, n):
    from numpy import linspace
    x = linspace(a, b, n)
    y = f(x)
    roots = []
    for i in range(n-1):
        if y[i]*y[i+1] < 0:
            root = x[i] - (x[i+1] - x[i])/(y[i+1] - y[i])*y[i]
            roots.append(root)
        elif y[i] == 0:
            root = x[i]
            roots.append(root)
    return roots

def demo():
    from numpy import exp, cos
    roots = brute_force_root_finder(
        lambda x: exp(-x**2)*cos(4*x), 0, 4, 1001)
    if roots:
        print(roots)
    else:
        print('Could not find any roots')

if __name__ == '__main__':
    demo()

reason: from numpy


text:
import sys
import numpy
import matplotlib.pyplot

def detect_problems (filename):
    """some of our temperature files haave problems, check for these

    this function reads a file and reports on odd looking maxima and minimia that add to zero
    the function does not return any data
    """
    data=numpy.loadtxt(fname=filename, delimiter=',')

    if numpy.max (data, axis=0)[0] ==0 and numpy.max (data, axis=0)[20] ==20:
        print ('suspicious looking maxima')
    elif numpy.sum(numpy.min(data, axis=0)) ==0:
        print ('minimum adds to zero')
    else:
        print ('data looks ok')

def analyse (filename, outfile=None):
    data=numpy.loadtxt(fname=filename,delimiter=',')

    """ this function analyses a dataset and outputs plots for maax min and ave
    """

    fig=matplotlib.pyplot.figure (figsize=(10.0,3.0))
    subplot1=fig.add_subplot (1,3,1)
    subplot2=fig.add_subplot (1,3,2)
    subplot3=fig.add_subplot (1,3,3)

    subplot1.set_ylabel('average')
    subplot1.plot(numpy.mean(data, axis=0))

    subplot2.set_ylabel('minimum')
    subplot2.plot(numpy.min(data, axis=0))

    subplot3.set_ylabel('maximum')
    subplot3.plot(numpy.max(data, axis=0))

    fig.tight_layout()
    if outfile is None:
    matplotlib.pyplot.show

    else:
        matplotlib.pyplot.savefig(outfile)

print("running",sys.argv[0])

print (sys.argv[1])
analyse (sys.argv[1], outfile=sys.argv[2])
detect_problems (sys.argv[1])

max_stars_repo_name: drwalshaw/sc-python

max_issues_repo_name: drwalshaw/sc-python

max_forks_repo_name: drwalshaw/sc-python


text:
from gensim.models import Word2Vec
import matplotlib.pyplot as plt
import numpy as np
#w2v_model = Word2Vec.load("models/model_pei")
#w2v_model = Word2Vec.load("models/model_acta")
#w2v_model = Word2Vec.load("models/model_acta99_19")
model = Word2Vec.load("models/model_Yin")

#model = gensim.models.Word2Vec.load_word2vec_format(model_path, binary=True)
with open( 'tensorsfp', 'w+') as tensors:
    with open( 'metadatafp', 'w+') as metadata:
         for word in model.wv.index2word:
           encoded=word #word.encode('utf-8')
           #print(encoded)
           metadata.write(encoded + '\n')
           vector_row = '\t'.join(map(str, model[word]))
           tensors.write(vector_row + '\n')


text:
import copy
import math
import os
import pickle
import time

import numpy as np
import torch
import torch.nn as nn

def save_vocabulary(vocab, path):
    with open(path, 'wb') as fw:
        pickle.dump(vocab, fw, protocol=pickle.HIGHEST_PROTOCOL)

def load_vocabulary(path):
    with open(path, 'rb') as f:
        return pickle.load(f)

def save_best_model(model, path, filename="saved_best_model.pt"):
    out_path = os.path.abspath(os.path.join(path, filename))
    torch.save(model, out_path)

def load_best_model(path, filename="saved_best_model.pt"):
    out_path = os.path.abspath(os.path.join(path, filename))
    return torch.load(out_path)

def calculate_accuracy(predictions, ground_truths):
    correct = (torch.max(predictions, 1)[1].view(ground_truths.size()).data == ground_truths.data)
    return float(correct.sum()) / len(correct) * 100

def calculate_topk_accuracy(output, target, topk=(2,)):
    """
    Code copied/pasted from PyTorch Imagenet example: https://github.com/pytorch/examples/blob/master/imagenet/main.py
    Computes the accuracy over the k top predictions for the specified values of k
    """
    with torch.no_grad():
        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, keepdim=True)
            res.append(correct_k.mul_(100.0 / batch_size))
    return res

def as_minutes(s):
    m = math.floor(s / 60)
    s -= m * 60
    return "%dm %ds" % (m, s)

def time_since(since, percent):
    now = time.time()
    s = now - since
    es = s / percent
    rs = es - s
    return "%s (- %s)" % (as_minutes(s), as_minutes(rs))

# Direct c/p from Pytorch/BiLSTM Tutorial
def argmax(vec):
    # return the argmax as a python int
    _, idx = torch.max(vec, 1)
    return idx.item()

def log_sum_exp(vec, dim=-1):
    max_score, _ = torch.max(vec, dim=dim)
    max_score_broadcast = max_score.unsqueeze(dim)
    return max_score + \
           torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))

def scheduled_annealing_strategy(epoch, max_epoch, max=1.0, min=0.01, gain=0.3):
    upper_alpha = max - min
    lower_alpha = (1 + torch.exp(gain * (epoch - (max_epoch // 2))))
    alpha = (upper_alpha / lower_alpha) + max
    return alpha

def clones(module, num_of_clones):
    return nn.ModuleList([copy.deepcopy(module) for _ in range(num_of_clones)])

def subsequent_mask(size):
    # Mask out subsequent positions. It is to prevent positions from attenting to subsequent positions
    # For more detailed information:
    # The Annotated Transformer = https://nlp.seas.hardvard.edu/2018/04/03.attention.html
    sm = np.triu(np.ones((1, size, size)), k=1).astype("uint8")
    return torch.from_numpy(sm) == 0

max_stars_repo_name: yakzan/nlp-experiments-in-pytorch

max_issues_repo_name: yakzan/nlp-experiments-in-pytorch

max_forks_repo_name: yakzan/nlp-experiments-in-pytorch


text:
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
from dcgan import Discriminator, Generator, weights_init
from preprocessing import Dataset
import torch.autograd as autograd

beta1 = 0
beta2 = 0.9
p_coeff = 10
n_critic = 5
lr = 1e-4
epoch_num = 64
batch_size = 8
nz = 100  # length of noise
ngpu = 0
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

def main():
    # load training data
    trainset = Dataset('./data/brilliant_blue')

    trainloader = torch.utils.data.DataLoader(
        trainset, batch_size=batch_size, shuffle=True
    )

    # init netD and netG
    netD = Discriminator().to(device)
    netD.apply(weights_init)

    netG = Generator(nz).to(device)
    netG.apply(weights_init)

    # used for visualizing training process
    fixed_noise = torch.randn(16, nz, 1, device=device)

    # optimizers
    # optimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, beta2))
    # optimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, beta2))
    optimizerD = optim.RMSprop(netD.parameters(), lr=lr)
    optimizerG = optim.RMSprop(netG.parameters(), lr=lr)

    for epoch in range(epoch_num):
        for step, (data, _) in enumerate(trainloader):
            # training netD
            real_cpu = data.to(device)
            b_size = real_cpu.size(0)
            netD.zero_grad()

            noise = torch.randn(b_size, nz, 1, device=device)
            fake = netG(noise)

            # gradient penalty
            eps = torch.Tensor(b_size, 1, 1).uniform_(0, 1)
            x_p = eps * data + (1 - eps) * fake
            grad = autograd.grad(netD(x_p).mean(), x_p, create_graph=True, retain_graph=True)[0].view(b_size, -1)
            grad_norm = torch.norm(grad, 2, 1)
            grad_penalty = p_coeff * torch.pow(grad_norm - 1, 2)

            loss_D = torch.mean(netD(fake) - netD(real_cpu))
            loss_D.backward()
            optimizerD.step()

            for p in netD.parameters():
                p.data.clamp_(-0.01, 0.01)

            if step % n_critic == 0:
                # training netG
                noise = torch.randn(b_size, nz, 1, device=device)

                netG.zero_grad()
                fake = netG(noise)
                loss_G = -torch.mean(netD(fake))

                netD.zero_grad()
                netG.zero_grad()
                loss_G.backward()
                optimizerG.step()

            if step % 5 == 0:
                print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f'
                      % (epoch, epoch_num, step, len(trainloader), loss_D.item(), loss_G.item()))

        # save training process
        with torch.no_grad():
            fake = netG(fixed_noise).detach().cpu()
            f, a = plt.subplots(4, 4, figsize=(8, 8))
            for i in range(4):
                for j in range(4):
                    a[i][j].plot(fake[i * 4 + j].view(-1))
                    a[i][j].set_xticks(())
                    a[i][j].set_yticks(())
            plt.savefig('./img/wgan_gp_epoch_%d.png' % epoch)
            plt.close()
    # save model
    torch.save(netG, './nets/wgan_gp_netG.pkl')
    torch.save(netD, './nets/wgan_gp_netD.pkl')

if __name__ == '__main__':
    main()

max_stars_repo_name: LixiangHan/WGAN-GP-for-Raman-Spectra

max_issues_repo_name: LixiangHan/WGAN-GP-for-Raman-Spectra

max_forks_repo_name: LixiangHan/WGAN-GP-for-Raman-Spectra


text:
import paddle
import paddle.nn as nn
from paddle.vision import models

import numpy as np

from .utils import l2norm

def EncoderImage(model_name, img_dim, embed_size, image_norm=True, cnn_type=None, finetune=False):
    """A wrapper to image encoders. Chooses between an different encoders
    that uses precomputed image features.
    """
    model_name = model_name.lower()
    EncoderMap = {
        'scan': EncoderImagePrecomp,
        'vsepp': EncoderImageFull,
        'sgraf': EncoderImagePrecomp,
        'imram': EncoderImagePrecomp
    }

    if model_name in EncoderMap:
        img_enc = EncoderMap[model_name](img_dim, embed_size, image_norm, cnn_type, finetune)
    else:
        raise ValueError("Unknown model: {}".format(model_name))

    return img_enc

class EncoderImagePrecomp(nn.Layer):

    def __init__(self, img_dim, embed_size, image_norm=True, cnn_type=None, finetune=False):
        super(EncoderImagePrecomp, self).__init__()
        self.embed_size = embed_size
        self.image_norm = image_norm
        self.fc = nn.Linear(img_dim, embed_size)
        self.init_weights()

    def init_weights(self):
        """Xavier initialization for the fully connected layer
        """
        r = np.sqrt(6.) / np.sqrt(self.fc.weight.shape[0] + self.fc.weight.shape[1])
        v = np.random.uniform(-r, r, size=(self.fc.weight.shape[0], self.fc.weight.shape[1])).astype('float32')
        b = np.zeros(self.fc.bias.shape).astype('float32')
        self.fc.weight.set_value(v)
        self.fc.bias.set_value(b)

    def forward(self, images):
        """Extract image feature vectors."""
        # assuming that the precomputed features are already l2-normalized

        features = self.fc(images)

        # normalize in the joint embedding space
        if self.image_norm:
            features = l2norm(features, dim=-1)

        return features

class EncoderImageFull(nn.Layer):

    def __init__(self, img_dim, embed_size, image_norm=True, cnn_type='vgg19', finetune=False):

        """Load pretrained VGG19 and replace top fc layer."""
        super(EncoderImageFull, self).__init__()
        self.embed_size = embed_size
        self.image_norm = image_norm

        # Replace the last fully connected layer of CNN with a new one
        if cnn_type.startswith('vgg'):
            self.cnn = models.vgg19(pretrained=True)
            self.cnn.classifier = nn.Sequential(*list(self.cnn.classifier.children())[:-1])

            for param in self.cnn.parameters():
                param.requires_grad = finetune

            self.fc = nn.Linear(4096, embed_size)

        elif cnn_type.startswith('resnet'):
            self.cnn = models.resnet152(pretrained=True)
            self.cnn = nn.Sequential(*list(self.cnn.children())[:-1])

            for param in self.cnn.parameters():
                param.requires_grad = finetune

            self.fc = nn.Linear(2048, embed_size)

        self.init_weights()

    def init_weights(self):
        """Xavier initialization for the fully connected layer
        """
        r = np.sqrt(6.) / np.sqrt(self.fc.weight.shape[0] + self.fc.weight.shape[1])
        v = np.random.uniform(-r, r, size=(self.fc.weight.shape[0], self.fc.weight.shape[1])).astype('float32')
        b = np.zeros(self.fc.bias.shape).astype('float32')
        self.fc.weight.set_value(v)
        self.fc.bias.set_value(b)

    def forward(self, images):

        """Extract image feature vectors."""
        features = self.cnn(images).squeeze()

        # normalization in the image embedding space
        features = l2norm(features, 1)

        # linear projection to the joint embedding space
        features = self.fc(features)

        # normalization in the joint embedding space
        if self.image_norm:
            features = l2norm(features, 1)

        return features

max_stars_repo_name: njustkmg/PaddleMM

max_issues_repo_name: njustkmg/PaddleMM

max_forks_repo_name: njustkmg/PaddleMM


text:
import numpy as np
import math

def earthCyclotronFrequency():
    magneticField = input("Earth's Magnetic Field(ignore the x10^-4): ")
    magneticField = float(magneticField)
    magneticField = magneticField * pow(10,-4)
    #constants
    q = 1.6 * pow(10,-19)
    piMe = 2 * math.pi * 1.673 * pow(10,-27)
    cylotron = ((magneticField*q)/piMe)
    print(cylotron)
earthCyclotronFrequency()


text:
# OpenAI gym environments
import gym
# Numpy arrays
import numpy as np
# Game weapon specifications
from gym_csgo.specs.weapon import WEAPON_NAMES, WEAPON_TYPES, NUM_WEAPON_SLOTS
# Enumeration observation space
from .enum import Enum

# Constructs a Counter Strike weapon observation space
def make_weapon_obs_space():
    # Observation space base components
    from gym.spaces import Box
    # Return observation space dictionary
    return gym.spaces.Dict({
        # Name of the weapon
        'name': Enum(*WEAPON_NAMES, 'none'),
        # Type of the weapon
        'type': Enum(*WEAPON_TYPES, 'none'),
        # State of weapon
        'state': Enum('active', 'holstered', 'reloading', 'none'),
        # Current amount of ammo in the clip
        'ammo_clip': Box(low=0, high=np.inf, shape=(1,)),
        # Maximum amount of ammo the clip for the weapon can hold
        'ammo_clip_max': Box(low=0, high=np.inf, shape=(1,)),
        # Amount of extra (reserve) ammo available for the weapon
        'ammo_reserve': Box(low=0, high=np.inf, shape=(1,))
    })

# Constructs a Counter Strike weapon observation space
def make_obs_space(pov_shape=(640, 480, 3)):
    # Observation space base components
    from gym.spaces import Box, Discrete
    # Get the weapon observation space
    weapon  = make_weapon_obs_space()
    # Return observation space dictionary
    return gym.spaces.Dict({
        # Observation image
        'pov': Box(low=0, high=255, shape=pov_shape, dtype=np.uint8),
        # Player state
        'health': Box(low=0, high=np.inf, shape=(1,)),
        'armor': Box(low=0, high=np.inf, shape=(1,)),
        'helmet': Discrete(2),
        'flashed': Box(low=0, high=255, shape=(1,), dtype=np.uint8),
        'smoked': Box(low=0, high=255, shape=(1,), dtype=np.uint8),
        'burning': Box(low=0, high=255, shape=(1,), dtype=np.uint8),
        'money': Box(low=0, high=np.inf, shape=(1,)),
        'value': Box(low=0, high=np.inf, shape=(1,)),
        # Player stats
        'kills': Box(low=0, high=np.inf, shape=(1,)),
        'assists': Box(low=0, high=np.inf, shape=(1,)),
        'deaths': Box(low=0, high=np.inf, shape=(1,)),
        'mvps': Box(low=0, high=np.inf, shape=(1,)),
        'score': Box(low=0, high=np.inf, shape=(1,)),
        # The player's team
        'team': Enum('CT', 'T', 'none'),
        # The player's active weapon
        'weapon_active': weapon,
        # All the player's weapons
        **{f'weapon_{i}': weapon for i in range(NUM_WEAPON_SLOTS)},
    })

max_stars_repo_name: iksnagreb/gym-csgo

max_issues_repo_name: iksnagreb/gym-csgo

max_forks_repo_name: iksnagreb/gym-csgo


text:
"""
OVERVIEW:\n
Making a trial program for assigning the red lights of the\n
according to the inputs made by the ML division. \n\n

THEORY:
assign green light to the one which has the greatest time in\n
the array inputted\n
\n
INPUT:\n
a numpy array from ML file that contains the time required to\n
clean the intersections\n
\n
WARNING:\n
Training is turned off. Turn it on by increasing the trainLimit\n
in ml_classes file in ML folder
"""
import numpy as np
from classes import Traffic_Light
from functions import loop_exiter, traffic_light_chooser, all_inactive_converter, time_updater, emergency_detector, get_all_traffic_times
from time import sleep
import threading
from sys import path
from os import getcwd

# this variable sees if the project is on trial on or not
DEBUG = True

#will have to change manually to change default display images
img_dir =  'http://127.0.0.1:8000/1.jpg'
img_dir2 = 'http://127.0.0.1:8000/2.jpg'
img_dir3 = 'http://127.0.0.1:8000/3.jpg'
img_dir4 = 'http://127.0.0.1:8000/4.jpg'

# traffic_time contains all the time values
# taking random values right now for testing

# emergency variable
emergency_loop = False

# variable for exiting the full program
exit_program = False

# defining the traffic lights Here we have to add actual links to the images
light_1 = Traffic_Light( 0, img_dir)
light_2 = Traffic_Light( 1, img_dir2)
light_3 = Traffic_Light( 2, img_dir3)
light_4 = Traffic_Light( 3, img_dir4)

intersection = [ light_1, light_2, light_3, light_4]

# getting the initial times by running the IP part
time_updater( intersection, ip_time= DEBUG)  # IP call

# making a loop that will always execute handling the operation
while( 1):
    while( not emergency_loop):

        # breaking loop if letter q is pressed and held
        if loop_exiter():
            exit_program = True
            break

        if DEBUG:
            print( 'times are: ', get_all_traffic_times( intersection))

        # checking if all are inactive
        print( all_inactive_converter( intersection, DEBUG))

        # choosing the light that has max time remaining and is active
        chosen_id = traffic_light_chooser( intersection)
        chosen_traffic_light = intersection[chosen_id]
        objectsAtStart = chosen_traffic_light.objectsArray
        greenTime = chosen_traffic_light.green_time

        # showing the lights for the chosen traffic light
        light_thread = threading.Thread( target= chosen_traffic_light.show_light, args= [intersection])
        light_thread.start()

        # updating the values and using a thread to do it to leave the emergency
        update_thread = threading.Thread( target= time_updater, args= [ intersection, True, chosen_id]) # IP call
        update_thread.start()

        # checking for emergency vehicles while showing lights
        # for now pressing button on website causes emergency
        if emergency_detector( greenTime, intersection):
            emergency_loop = True
            break

        """
        here we need to change for real values
        """

        # ending the light and preparing for next round of the green lights
        light_thread.join()
        update_thread.join()

        # goes into training only if limit is not passed
        if chosen_traffic_light.isTraining:
            train_thread = threading.Thread( target= chosen_traffic_light.light_trainer, args= [objectsAtStart]) # IP call
            train_thread.start()

        if DEBUG:
            print( 'loop finished')
        print( '\n\n')

    if exit_program:
        print( 'Exiting Program')
        break

#________________________________________________________________________________________
    # in emergency conditions this thing runs
    if DEBUG:
        print( 'emergency condition applied')

    # changing current green traffic light to yellow for 2 seconds
    chosen_traffic_light.change_color( 'yellow', from_emergency= True)
    sleep( 2)

    #changing all colors to red
    print( '\n\nchanging all colors to red')
    for tl in intersection:
        tl.change_color( 'red')

    # extracting the light number
    for indx, tl in enumerate( intersection):
        if tl.emergency:
            emer_id = indx

    print( 'emergency at light {}'.format( emer_id))

    # choosing the light that has emergency
    emer_traffic_light = intersection[emer_id]

    # giving input to the chosen light to stop its process
    chosen_traffic_light.was_emergency = True

    print( 'changing light {} to green-emergency'.format( emer_id))
    emer_traffic_light.change_color( 'green', emergency_loop)

    emer_timer = 0

    # checking for emergency after every second
    while( emergency_loop):
        sleep( 1)
        emer_timer += 1
        emergency_loop = emer_traffic_light.emergency

    ip_thread = threading.Thread( target= time_updater, args=[intersection])
    ip_thread.start()

    print( 'Emergency for {} seconds'.format( emer_timer))
    print( 'changing light {} to yellow for 5 seconds-emergency'.format( emer_id))
    emer_traffic_light.change_color( 'yellow', True)
    sleep( 5)

    print( 'changing light {} to red-emergency'.format( emer_id))
    emer_traffic_light.change_color( 'red', True)

    print( 'resetting the traffic lights...')
    print( all_inactive_converter( intersection, DEBUG, emergency= True))

    emergency_loop = False
    ip_thread.join()

    print( '\n\n')

max_stars_repo_path: Traffic Program/main.py

max_stars_repo_name: TanmayHiremath/Traffic-Man

max_issues_repo_path: Traffic Program/main.py

max_issues_repo_name: TanmayHiremath/Traffic-Man

max_forks_repo_path: Traffic Program/main.py

max_forks_repo_name: TanmayHiremath/Traffic-Man


text:
"""
    Introduction to Artificial Intelligence
    Naive Bayes
    Due: 18.05.2017
"""
import numpy as np
from sklearn import metrics
from sklearn.datasets import load_iris
from sklearn.utils import shuffle

def main():
    data = load_iris()
    shuffled_data, shuffled_target = shuffle(data.data, data.target)
    digitized_shuffled_data = digitize_data(shuffled_data)

    for i in range(0, 5):  # naive bayes calculations
        Xtrain, Xtest, Ytrain, Ytest = split_dataset(digitized_shuffled_data, shuffled_target, i)
        feature_freq, class_freq = train_bayes_model(Xtrain, Ytrain)
        predicts = naive_bayes(Xtest, feature_freq, class_freq)
        score = metrics.accuracy_score(Ytest, predicts)
        print("Naive Bayes accuracy score for part " + str(i) + " is: {}".format(round(score * 100, 2)))

def digitize_data(data):
    result = []
    for i in range(0, len(data)):
        s = data[i]
        bins = np.linspace(s[3], s[0], num=10)
        result.append(np.digitize(s, bins))  # inds
    return result

def split_dataset(data, target, option):
    fold = len(target) / 5  # 150/5 = 30
    Xtrain_list = []  # float values for train set (len:120)
    Xtest = []  # float values for test set (len:30)
    Ytrain_list = []  # targets for train set
    Ytest = []  # targets for test set

    for i in range(0, 5):
        if i == option:
            Xtest = data[fold * i:fold * (i + 1)]
            Ytest = target[fold * i:fold * (i + 1)]
        else:
            Xtrain_list.append(data[fold * i:fold * (i + 1)])
            Ytrain_list.append(target[fold * i:fold * (i + 1)])

    Xtrain = merge_Xset(Xtrain_list)  # convert train data set from 4*30 list to 1*120 list
    Ytrain = merge_Yset(Ytrain_list)  # convert train target set from 4*30 list to 1*120 list

    return Xtrain, Xtest, Ytrain, Ytest

def merge_Xset(Xtrain_list):
    Xtrain = Xtrain_list[0][0]
    for ls in Xtrain_list:
        for item in ls:
            Xtrain = np.vstack([Xtrain, item])
    Xtrain = np.delete(Xtrain, 0, 0)
    return Xtrain

def merge_Yset(Ytrain_list):
    Ytrain = Ytrain_list[0][0]
    for ls in Ytrain_list:
        for item in ls:
            Ytrain = np.hstack([Ytrain, item])
    Ytrain = np.delete(Ytrain, 0)
    return Ytrain

def train_bayes_model(Xtrain, Ytrain):
    feature_freq = {}  # { (class,feature):frequency }
    class_freq = {}  # { class:frequency }

    for i in range(len(Ytrain)):
        class_freq[Ytrain[i]] = class_freq.get(Ytrain[i], 0) + 1
        for j in range(len(Xtrain[i])):
            feature_freq[(Ytrain[i], Xtrain[i][j])] = feature_freq.get((Ytrain[i], Xtrain[i][j]), 0) + 1

    return feature_freq, class_freq

def naive_bayes(Xtest, feature_freq, class_freq):
    predicts = []

    for i in range(len(Xtest)):  # calculate for each array in test set
        temp = Xtest[i]
        probabilities = {}

        # calculate probability for each class 0,1,2 and pick max
        # P(c|x) = P(x1|c).P(x2|c).P(x3|c).P(x4|c).P(c) then argmax
        for i in range(0, 3):
            V = 10
            prob = float(1) / float(3)  # P(c) is the probability of given class (one of 0,1,2)
            # calculate likelihood probabilities for each feature
            for feature in temp:
                # P(x1|c) = x1 count in C + 1 / feature count in C + V      {=Count(X1,C) + 1 / Count(C) + V}
                prob *= float(feature_freq.get((i, feature), 0) + 1) / float((class_freq.get(i, 0) * 4) + V)

            probabilities[i] = prob  # probabilities for 0,1,2

        best = max(probabilities, key=probabilities.get)  # pick max
        predicts.append(best)

    return predicts

if __name__ == "__main__":
    main()

max_stars_repo_name: burakekici/Naive-Bayes-and-KNN

max_issues_repo_name: burakekici/Naive-Bayes-and-KNN

max_forks_repo_name: burakekici/Naive-Bayes-and-KNN


text:
# coding=utf-8
from __future__ import absolute_import, print_function

import numpy as np

from sklearn.cluster import KMeans
# from sklearn.mixture import GaussianMixture

def cluster_(features,  labels, n_clusters):
    centers = []
    center_labels = []
    for label in set(labels):
        X = features[labels == label]
        kmeans = KMeans(n_clusters=n_clusters, random_state=None).fit(X)
        center_ = kmeans.cluster_centers_
        centers.extend(center_)
        center_labels.extend(n_clusters*[label])
    centers = np.conjugate(centers)
    centers = normalize(centers)
    return centers, center_labels

def normalize(X):
    norm_inverse = np.diag(1/np.sqrt(np.sum(np.power(X, 2), 1)))
    X_norm = np.matmul(norm_inverse, X)
    return X_norm


text:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import math
from .torchdiffeq import odeint
from .torchdiffeq import odeint_adjoint
import numpy as np

class Spiral(nn.Module):
  transform_matrix = torch.tensor([[-0.1, 1.0], [-2.0, -0.1]])

  def forward(self, t, y):
    return torch.mm(y, self.transform_matrix)

class SimpleNetODE(nn.Module):
    def __init__(self, net):
        super(ODEFunc, self).__init__()
        self.net = net

    def forward(self, t, y):
        return self.net(y)

class DenseLayers1DimODE(nn.Module):
    def __init__(self, state_shape, layers=[50]):
        super().__init__()
        self.state_shape = state_shape
        self.one_d_length = self.state_shape[1]
        self.in_size = np.prod(state_shape)
        layers = [self.in_size] + layers + [self.in_size]
        layers = [nn.Linear(a, b) for a, b in zip(layers[:-1], layers[1:])]
        self.net = nn.Sequential(*layers)

    def forward(self, t, y):
        yshape = y.size()
        y = y.reshape(yshape[0], -1)
        y = self.net(y)
        y = y.reshape(*yshape)
        return y

class ConvLayers1DimODE(nn.Module):
    def __init__(self, state_shape, kernels=2):
        super().__init__()
        self.state_shape = state_shape
        self.one_d_length = self.state_shape[1]
        self.total_inputs = np.prod(state_shape)
        self.conv = nn.Conv2d(1, kernels, 3, padding=1) # 1 input plane, 2 output planes, 3 size kernel, 1 size padding to keep the output planes same size as input
        testvec = torch.randn(size=state_shape).reshape(1, 1, *state_shape)
        conv_out  = np.prod(self.conv(testvec).size())
        self.net = nn.Sequential(
            nn.Linear(conv_out, 2 * self.total_inputs),
            nn.Linear(2 * self.total_inputs, self.total_inputs),
        )

    def forward(self, t, y):
        yshape = y.size()
        y = y.reshape(*([yshape[0]] + [1] + list(yshape[1:])))
        y = self.conv(y)
        y = y.reshape(yshape[0], -1)
        y = self.net(y)
        y = y.reshape(*yshape)
        return y


text:
from collections import Counter
import matplotlib.pyplot as plt
import numpy as np

import parse

def visualize_days(parsed_data):
    """
    Visualizes parsed_data by day of the week.
    """

    # prepare list that will be used later fow counting.
    # counter = Counter(item["DayOfWeek"] for item in parsed_data)

    counter = {}

    for item in parsed_data:
        try:
            counter[item["DayOfWeek"]] += 1
        except KeyError:
            counter[item["DayOfWeek"]] = 0

    # seperate out the counter
    data_counts = [
        counter["Monday"],
        counter["Tuesday"],
        counter["Wednesday"],
        counter["Thursday"],
        counter["Friday"],
        counter["Saturday"],
        counter["Sunday"]
    ]

    # tuple of shorrt days names to be used for labelling the axis
    day_tuple = tuple(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])

    plt.rcParams['toolbar'] = 'None'
    plt.figure(facecolor='white')

    # plot the data
    plt.plot(data_counts)

    # change the x-ticks
    plt.xticks(range(len(day_tuple)), day_tuple)

    # plt.show()

    # save the figure
    plt.savefig("Days.png")

    # close the figure
    plt.clf()

def visualize_type(parsed_data):

    # classify counters by category
    counter = Counter([item["Category"] for item in parsed_data])

    # set labels for the incidents
    category_labels = tuple(counter.keys())

    # set starting x locations for the bars
    x_locations = np.arange(len(category_labels)) + 0.5

    # set width of each bar
    width = 0.5

    # assign the data to the plot
    plt.bar(x_locations, counter.values(), width=width)

    # put labels on the graph
    plt.xticks(x_locations + width/2.0, category_labels, rotation=90)

    # give more space at the bottom to prevent cutting the labels
    plt.subplots_adjust(bottom=0.4)

    # change figure size
    plt.rcParams['figure.figsize'] = 12, 8

    # plt.show()

    # save and close
    plt.savefig('Type.png')
    plt.clf()

def main():
    parsed_data = parse.parse(parse.DATA_FILE, ",")
    visualize_days(parsed_data)
    visualize_type(parsed_data)

if __name__ == '__main__':
    main()

max_stars_repo_name: abhikpal/new-coder-tutorial

max_issues_repo_name: abhikpal/new-coder-tutorial

max_forks_repo_name: abhikpal/new-coder-tutorial


text:
#
# Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS,
# BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, RIXEN@TUM.DE.
#
# Distributed under 3-Clause BSD license. See LICENSE file for more information.
#

"""
Super class of all mesh converter for I/O module.
"""

from enum import Enum
import numpy as np
import pandas as pd
import vtk
from os.path import splitext
import logging

from amfe.io.mesh.base import MeshConverter

__all__ = [
    'VtkMeshConverter'
    ]

class VtkPreallocation(Enum):
    PREALLOCATED = 1
    NOTPREALLOCATED = 2
    UNKNOWN = 3

class VtkMeshConverter(MeshConverter):
    """
    Super class for all mesh converters.
    """

    amfe2vtk = {'straight_line': vtk.vtkLine,
                'quadratic_line': vtk.vtkQuadraticEdge,
                'Tri3': vtk.vtkTriangle,
                'Tri6': vtk.vtkQuadraticTriangle,
                'Quad4': vtk.vtkQuad,
                'Quad8': vtk.vtkQuadraticQuad,
                'Tet4': vtk.vtkTetra,
                'Tet10': vtk.vtkQuadraticTetra,
                'Hexa8': vtk.vtkHexahedron,
                'Hexa20': vtk.vtkQuadraticHexahedron,
                'Prism6': vtk.vtkWedge }

    def __init__(self, filename):
        super().__init__()
        self._filename = filename
        self._vtknodes = vtk.vtkPoints()
        self._vtkelements = vtk.vtkUnstructuredGrid()
        self._nodes = np.empty((0, 4))
        self._elements = []
        self._nodespreallocation = VtkPreallocation.UNKNOWN
        self._elementspreallocation = VtkPreallocation.UNKNOWN
        self._eleid2cell = dict()
        self._tags = dict()
        self._groups = dict()
        self.logger = logging.getLogger('amfe.io.VtkMeshConverter')
        self._nodes_df = pd.DataFrame(columns=['row', 'x', 'y', 'z'])
        self._el_df = pd.DataFrame(columns=['id', 'type', 'connectivity'])
        self._index = 0
        self._el_idx = 0

    def build_no_of_nodes(self, no):
        """
        Build number of nodes (optional)

        This function usually is optional. It can be used to enhance performance
        of the building process. This function can be used to preallocate arrays
        that contain the node coordinates

        Parameters
        ----------
        no : int
            number of nodes in the mesh

        Returns
        -------
        None
        """
        if self._nodespreallocation is VtkPreallocation.UNKNOWN:
            self._vtknodes.SetNumberOfPoints(no)
            self._nodes = np.zeros((no, 4))
            self._nodespreallocation = VtkPreallocation.PREALLOCATED

    def build_no_of_elements(self, no):
        """
        Build number of elements (optional)

        This function usually is optional. It can be used to enhance performance
        of the building process. This function can be used to preallocate arrays
        that contain the element information

        Parameters
        ----------
        no : int
            number of elements in the mesh

        Returns
        -------
        None
        """
        if self._elementspreallocation is VtkPreallocation.UNKNOWN:
            self._vtkelements.Allocate(no, 1)
            self._el_df = pd.DataFrame(columns=['id', 'type', 'connectivity'], index=np.arange(no))
            self._elementspreallocation = VtkPreallocation.PREALLOCATED

    def build_node(self, node_id, x, y, z):
        """
        Builds a node.

        Parameters
        ----------
        node_id : int
            ID of the node
        x : float
            X coordinate of the node
        y : float
            Y coordinate of the node
        z : float
            Z coordinate of the node

        Returns
        -------
        None
        """
        if self._nodespreallocation is VtkPreallocation.PREALLOCATED:
            self._nodes[self._index, 0] = node_id
            self._nodes[self._index, 1] = x
            self._nodes[self._index, 2] = y
            self._nodes[self._index, 3] = z
            self._index += 1
        else:
            new_node = pd.Series({'row': self._nodes_df['row'].count(), 'x': x, 'y': y, 'z': z}, name=int(node_id))
            self._nodes_df = self._nodes_df.append(new_node)
            self._nodes_df = self._nodes_df.astype(dtype={'row': 'int', 'x': 'float', 'y': 'float', 'z': 'float'})
            self._nodespreallocation = VtkPreallocation.NOTPREALLOCATED

    def build_element(self, ele_id, etype, nodes):
        """
        Builds an  element

        Parameters
        ----------
        ele_id : int
            ID of an element
        etype : str
            valid amfe elementtype (shape) string
        nodes : iterable
            iterable of ints describing the connectivity of the element

        Returns
        -------
        None
        """
        self._el_df.loc[self._el_idx] = pd.Series({'id': ele_id, 'type': etype, 'connectivity': nodes})
        self._el_idx += 1

    def build_group(self, name, nodeids, elementids):
        """
        Builds a group, i.e. a collection of nodes and elements

        Parameters
        ----------
        name: str
            Name identifying the node group.
        nodeids: list
            List with node ids.
        elementids: list
            List with element ids.

        Returns
        -------
        None
        """
        self._groups.update({name: {'elements': elementids, 'nodes': nodeids}})

    def build_material(self, material):
        pass

    def build_partition(self, partition):
        pass

    def build_mesh_dimension(self, dim):
        """
        Builds the dimensino of the mesh (optional)
        If this method has not been called during build process, a mesh dimension
        of 3 is assumed

        Parameters
        ----------
        dim : int {2, 3}
            dimension of the mesh

        Returns
        -------
        None
        """
        pass

    def build_tag(self, tag_dict):
        """
        Builds a tag with following dict given in tag_dict

        Parameters
        ----------
        tag_dict : dict
            dict with following format:
            { tagname1 : { tagvalue1 : [elementids],
                           tagvalue2 : [elementids],
                           ...
                         },
              tagname2 : { tagvalue1 : [elementids],
                           tagvalue2 : [elementids]
                           ...
                         },
              ...
            }

        Returns
        -------
        None
        """
        self._tags.update(tag_dict)

    def return_mesh(self):
        """
        Returns the Mesh or the file pointer

        Returns
        -------
        Object
        """
        if self._nodespreallocation is VtkPreallocation.PREALLOCATED:
            x = self._nodes[:, 1]
            y = self._nodes[:, 2]
            z = self._nodes[:, 3]
            no_of_nodes = self._nodes.shape[0]
            self._nodes_df = pd.DataFrame({'row': np.arange(no_of_nodes, dtype=int), 'x': x, 'y': y, 'z': z},
                                          index=np.array(self._nodes[:, 0], dtype=int))

            self._vtknodes.SetNumberOfPoints(no_of_nodes)

        if not self._el_df.isnull().values.any():
            # Function change connectivity ids to row ids in nodes array:
            def change_connectivity(arr):
                return np.array([self._nodes_df.loc[node, 'row'] for node in arr], ndmin=2, dtype=int)

            def write_vtk_element(idx, etype, nodes):
                cell = self.amfe2vtk[etype]()
                for i, node in enumerate(nodes):
                    cell.GetPointIds().SetId(i, node)
                    self._eleid2cell.update({idx: cell})

                if self._elementspreallocation is VtkPreallocation.UNKNOWN:
                    self._vtkelements.Allocate(1, 1)
                    self._elementspreallocation = VtkPreallocation.NOTPREALLOCATED

                cellid = self._vtkelements.InsertNextCell(cell.GetCellType(), cell.GetPointIds())
                self._eleid2cell.update({idx: cellid})

            self._el_df = self._el_df.astype(dtype={'id': 'int', 'type': 'object', 'connectivity': 'object'})
            self._el_df['connectivity'] = self._el_df['connectivity'].apply(change_connectivity)

            for element in self._el_df.itertuples():
                write_vtk_element(element.Index, element.type, element.connectivity[0])

            for node in self._nodes_df.itertuples():
                self._vtknodes.InsertPoint(node.row, node.x, node.y, node.z)

            self._vtkelements.SetPoints(self._vtknodes)

            for tagname, tag_dict in self._tags.items():
                vtkarray = vtk.vtkIntArray()
                vtkarray.SetNumberOfComponents(1)
                vtkarray.SetNumberOfTuples(self._vtkelements.GetNumberOfCells())
                vtkarray.FillComponent(0, 0)
                vtkarray.SetName(tagname)
                for tagvalue, eleids in tag_dict.items():
                    vtkids = [self._eleid2cell[eleid] for eleid in eleids]
                    for vtkid in vtkids:
                        vtkarray.SetTuple1(vtkid, int(tagvalue))
                self._vtkelements.GetCellData().AddArray(vtkarray)

            for groupname, groupdict in self._groups.items():
                nodeids = groupdict['nodes']
                elementids = groupdict['elements']
                elementidxs = []
                for eleid in elementids:
                    elementidxs += self._el_df.index[self._el_df['id'] == eleid].tolist()
                elementids = [self._eleid2cell[eleidx] for eleidx in elementidxs]

                if len(elementids) > 0:
                    # Allocate vtk elements array
                    vtkelements = vtk.vtkIntArray()
                    vtkelements.SetNumberOfComponents(1)
                    vtkelements.SetNumberOfTuples(self._vtkelements.GetNumberOfCells())
                    vtkelements.SetName(groupname + '_elements')
                    vtkelements.FillComponent(0, 0)
                    for elementid in elementids:
                        vtkelements.SetTuple1(elementid, 1)
                    self._vtkelements.GetCellData().AddArray(vtkelements)

                if len(nodeids) > 0:
                    vtknodes = vtk.vtkIntArray()
                    vtknodes.SetNumberOfComponents(1)
                    vtknodes.SetNumberOfTuples(self._vtknodes.GetNumberOfPoints())
                    vtknodes.SetName(groupname + '_nodes')
                    vtknodes.FillComponent(0, 0)

                    for nodeid in nodeids:
                        nodeidx = int(self._nodes_df.loc[nodeid, 'row'])
                        vtknodes.SetTuple1(nodeidx, 1)
                    self._vtkelements.GetPointData().AddArray(vtknodes)

        filename, file_extension = splitext(self._filename)
        if file_extension == '.vtu':
            vtkwriter = vtk.vtkXMLUnstructuredGridWriter()
        elif file_extension == '.vtk':
            vtkwriter = vtk.vtkUnstructuredGridWriter()
        else:
            self.logger.warning('No file extension given, choose \'vtk\' format')
            self._filename = self._filename + '.vtk'
            vtkwriter = vtk.vtkUnstructuredGridWriter()

        vtkwriter.SetInputData(self._vtkelements)
        vtkwriter.SetFileName(self._filename)
        vtkwriter.Write()
        return 0

max_stars_repo_name: ma-kast/AMfe

max_issues_repo_name: ma-kast/AMfe

max_forks_repo_name: ma-kast/AMfe


text:
import matplotlib.pyplot as plt
import numpy as np
import pickle

from collections import defaultdict

# Init NuScenes. Requires the dataset to be stored on disk.
from nuscenes.nuscenes import NuScenes
from nuscenes.map_expansion.map_api import NuScenesMap

nusc = NuScenes(version='v1.0-trainval', \
                dataroot='../../../../data/', \
                verbose=True)

so_map = NuScenesMap(dataroot='../../../../data/', \
                       map_name='singapore-onenorth')
bs_map = NuScenesMap(dataroot='../../../../data/', \
                       map_name='boston-seaport')
sh_map = NuScenesMap(dataroot='../../../../data/', \
                       map_name='singapore-hollandvillage')
sq_map = NuScenesMap(dataroot='../../../../data/', \
                       map_name='singapore-queenstown')

# dict mapping map name to map file
map_files = {'singapore-onenorth': so_map,
             'boston-seaport': bs_map,
             'singapore-hollandvillage': sh_map,
             'singapore-queenstown': sq_map}

# dict with person token as key and other features as values
pedestrian_details = dict()

# dict with scene number as key and trajectories and map name as values
scene_info = dict()

# initializing a dict for layer names and number of points in each layer
layer_list = so_map.layer_names
layer_list.append("white_area")
layer_dict = dict.fromkeys(layer_list, 0)

# defining the sensor to extract ego_pose from sample_data,
# we need a sensor to get sample_data
sensor = "LIDAR_TOP"

for n_scene in range(850):
    # initialize the scene
    my_scene = nusc.scene[n_scene]
    # getting the map name
    cur_map = nusc.get('log', my_scene["log_token"])["location"]
    # entering the scene number and map name
    scene_info[str(n_scene)] = {"trajectories_x": [], "trajectories_y": [],\
                          "map_name": cur_map}

    # per scene person token database
    seen_person_tokens = []

    # first sample
    first_sample_token = my_scene['first_sample_token']
    sample = nusc.get('sample', first_sample_token)

    while True:
        for ann in sample['anns']:
            group_name = nusc.get('sample_annotation', ann)['category_name']
            if "human.pedestrian" in group_name and \
               nusc.get('sample_annotation', ann)['instance_token'] not in seen_person_tokens:

                cur_person_token = nusc.get('sample_annotation', ann)['instance_token']
                cur_person_instance = nusc.get("instance", cur_person_token)
                nbr_samples = cur_person_instance['nbr_annotations']

                # initializing the dict with the new person token
                pedestrian_details[cur_person_token] = {"translation":[],
                                                        "rotation":[],
                                                        "velocity":[],
                                                        "ego_translation":[],
                                                        "ego_rotation":[],
                                                        "ego_time": []}

                first_token = cur_person_instance['first_annotation_token']
                current_token = first_token

                moving_counter = 0
                for i in range(nbr_samples):
                    current_ann = nusc.get('sample_annotation', current_token)

                    # getting the sample corresponding to this annotation to retrieve ego details
                    annotation_sample = nusc.get('sample', current_ann['sample_token'])

                    if current_ann["attribute_tokens"]:
                        current_attr = nusc.get('attribute', current_ann['attribute_tokens'][0])['name']
                        if current_attr.split(".")[1] != "sitting_lying_down":
                            # updating pedestrian details dict
                            pedestrian_details[cur_person_token]["group"] = group_name.split(".")[-1]
                            pedestrian_details[cur_person_token]["translation"].append(
                                        current_ann["translation"])
                            pedestrian_details[cur_person_token]["rotation"].append(
                                        current_ann["rotation"])
                            pedestrian_details[cur_person_token]["scene_no"] = n_scene
                            pedestrian_details[cur_person_token]["map_name"] = cur_map
                            # only takes velocity at a particular time step
                            pedestrian_details[cur_person_token]["velocity"].append(
                                list(nusc.box_velocity(current_token)))

                            # updating ego details
                            lidar_data = nusc.get('sample_data',
                                                  annotation_sample['data'][sensor])
                            ego_token = lidar_data['ego_pose_token']
                            ego_pose = nusc.get('ego_pose', ego_token)
                            pedestrian_details[cur_person_token]["ego_translation"].append(
                                ego_pose["translation"])
                            pedestrian_details[cur_person_token]["ego_rotation"].append(
                                ego_pose["rotation"])
                            pedestrian_details[cur_person_token]["ego_time"].append(
                                ego_pose["timestamp"])

                    current_token = current_ann["next"]

                seen_person_tokens.append(cur_person_token)

        if sample['next'] != '':
            sample = nusc.get('sample', sample['next'])
        else:
            #last sample of the scene
            break

# saving all the dict files in details folder

with open('details/pedestrian_details.pkl', 'wb') as handle:
    pickle.dump(pedestrian_details, handle, protocol=pickle.HIGHEST_PROTOCOL)

max_stars_repo_name: Kishaan/nuscenes-devkit

max_issues_repo_name: Kishaan/nuscenes-devkit

max_forks_repo_name: Kishaan/nuscenes-devkit


text:
#Advent of code 2021
#Day 12 Part 1
#Passage Pathing

import numpy as np
np.set_printoptions(threshold=np.inf)
import pdb #pdb.set_trace()
import time
import copy

#Start Timer
start_time = time.time()

#Functions
def assign_edge(node1,node2,positive_bool,nodesdict):
	#Takes an edge and popuated the dict of nodes with it
	if positive_bool == False:
		start = node2
		end = node1
	else:
		start = node1
		end = node2

	#Assign edge in positive direction
	if start in nodesdict:
		#Assign to existing dict entry (if not already)
		existing_entry = nodesdict[start]

		#Check if there already, If not add to dict entry
		if not end in existing_entry:
			new_entry = existing_entry.append(end)

	else:
		#Make new dict entry
		nodesdict[start] = [end]

	return nodesdict

def make_dict_of_nodes(edges):
	#Takes a list of edges and makes a map of nodes
	nodesdict = {}

	for edge in edges:
		start = edge[0]
		end = edge[1]

		#Assign edge
		nodesdict = assign_edge(start,end,True,nodesdict)#Positive
		nodesdict = assign_edge(start,end,False,nodesdict)#Negitive

	return nodesdict

def produce_new_paths(path,nodesdict,paths):
	#Produce new paths from path

	new_paths = []

	connected_nodes = nodesdict[path[-1]]

	for node in connected_nodes:
		if node.islower() is True and node in path:
			continue

		new_path = path + [node]

		if new_path in paths:
			continue
		else:
			new_paths.append(new_path)

	return new_paths

def check_all_paths_are_ended(paths):

	end_nodes = []

	for path in paths:
		if path[-1] == 'end':
			end_nodes.append(True)
		else:
			end_nodes.append(False)

	bool = all(end_nodes)

	return bool

def find_all_small_town_x1_paths(nodesdict):

	paths = [['start']]
	len_paths_old = 0

	while check_all_paths_are_ended(paths) is False:
		len_paths_old = len(paths)

		new_paths = []

		for path in paths:
			if path[len(path)-1] == 'end':
				new_paths = new_paths + [path]
				continue

			paths_found = produce_new_paths(path,nodesdict,paths)
			new_paths = new_paths + paths_found

		paths = new_paths

		#pdb.set_trace()

	return paths

#Import and sort File
edges = []

with open("input_12.txt") as edgesf:
	for line in edgesf:
		#Import operations

		line = line.strip("\n")#Remove EOL symbol

		line = line.split("-")#Split start / end of edge

		edges.append(line)

###Main Code
#Make graph of nodes
nodesdict = make_dict_of_nodes(edges)

#Start at start node and progress through graph recording unique paths
paths = find_all_small_town_x1_paths(nodesdict)

#Count paths
no_of_unique_paths = len(paths)

#Result
print(edges)
print(nodesdict)
print(paths)
print(no_of_unique_paths)

#Time Code
timetaken = time.time() - start_time
print("Completed in ", timetaken, " seconds")


text:
import math
from typing import List
from typing import List
import numpy as np
import future as future

def zcount(list: List[float]) ->float:
     return len(list)

def zmean(list: List[float]) ->float:
    return sum(list)/len(list)

def zmode(list: List[float]) -> float : #max occureence
    #using iterable it count the max occureence from org list
    # return max(set(list),key=list.count)
    count_element={}
    for element in list:
        try:
          count_element[element]+=1   # adding actual count of that element to value of dict
        except:
          count_element[element]=0

    #print(count_element)
   # print(list)

    mode=0
    for count in count_element:
        if count >mode:
           mode=count
    return mode

def zmedian(list: List[float]) -> float:
    # asending with middle number
    total = len(list)
    for i in range(total):
        for j in range(i + 1, total):
            if (list[i] > list[j]):
                temp = list[i]
                list[i] = list[j]
                list[j] = temp
    print(f'Asending list :{list}')
    mid = (total // 2)
    if total % 2 != 0:
        print(f'Mid Element at index {mid}')
        print(f'Mid value when list size is odd {list[mid]}')
    else:
        print(mid - 1, mid)
        sum = list[mid - 1] + list[mid]
        avg = sum / 2
        #print(f'Mean of 2 values{avg}')
    return avg

def zvariance(list: List[float]) -> float :

    n = zcount(list) - 1
    mean = zmean(list)
    dev = [abs(mean-xi)**2 for xi in list]  # list comprehensive
    variance = sum(dev)/n
    return variance

def zstddev(list: List[float]) -> float:
    return math.sqrt(zvariance(list))

def zstderr(list: List[float]) -> float:
    return zstddev(list)/math.sqrt(zcount(list))

def zcorr1(listx: List[float], listy: List[float]) -> float:
    sum = 0

    sub_x = [i - zmean(listx) for i in listx]
    sub_y = [i - zmean(listy) for i in listy]
    lengthx = zcount(listx)
    lengthy = zcount(listy)

    num_list = [sub_x[i] * sub_y[i] for i in range(lengthx)] # multiple x*y
    #print(num_list)
    num = 0
    for i in num_list:
        #print(i)
        num = num + i  # sum of multiplid list
    den = lengthx - 1
    cov = num / den

    if lengthx == lengthy:
        return cov / (zstddev(listx) * zstddev(listy))

    else:
        return cov

    def zcorr(listx: List[float], listy: List[float]) -> float:
        # sum(xy) ,sum(x), sum(y)
        x_multiply_y = np.multiply(listx, listy)  # multiplied list
        sum_xy = sum(x_multiply_y)
        print(f'sum of xy {sum_xy}')
        sum_x = sum(listx)
        sum_y = sum(listy)
        lengthx = zcount(listx)
        lengthy = zcount(listy)
        if lengthx == lengthy:
            co_relation = ((lengthx * sum_xy) - sum_x * sum_y) / (zstddev(listx) * zstddev(listy))
        return co_relation

def read_data_file(file_name):
    x,y = [], []
    with open(file_name) as f:
        f_line =f.readline()  # discord header from csv file
        for line in f :
            row=line.split(',')
            x.append(float(row[0]))
            y.append(float(row[1]))
    return(x,y)

def read_data_sets(files):  # more than one file
    data= {}
    for file in files:
        data[file]=read_data_file(file)
    return data

if __name__=='__main__':
    list1=[43,21,25,42,57,59]
    list2=[99,65,79,75,87,81]
    print(zcount(list1))
   # print(zmode(list))
   # print(zmedian(list1))
    #list = [1, 2, 3, 4, 5]
    print(zvariance(list1))
    print(f'list 1 std devi  {zstddev(list1)}')
    print(f'list 2 std devi  {zstddev(list2)}')
    print( zstderr(list1))
    print(zcorr1(list1, list2))
    print(f'Formula for corelation{zcorr(list1, list2)}')

max_stars_repo_name: vandanafs/Py-BasicStats

max_issues_repo_name: vandanafs/Py-BasicStats

max_forks_repo_name: vandanafs/Py-BasicStats


text:
import os
import sys
import cv2
import json
import tqdm
import logging
from collections import defaultdict

import numpy as np
import torch

from task import pose as task
from data.coco import COCODataset
from utils.misc import get_transform, kpt_affine, resize

logger = logging.getLogger()
flipRef = [i - 1 for i in [1, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, 17, 16]]

def refine(det, tag, keypoints):
    """
    Given initial keypoint predictions, we identify missing joints
    """
    if len(tag.shape) == 3:
        tag = tag[:, :, :, None]

    tags = []
    for i in range(keypoints.shape[0]):
        if keypoints[i, 2] == 1:
            y, x = keypoints[i][:2].astype(np.int32)
            x = np.clip(x, 0, tag.shape[1] - 1)
            y = np.clip(y, 0, tag.shape[2] - 1)
            tags.append(tag[i, x, y])

    prev_tag = np.mean(tags, axis=0)
    ans = []

    for i in range(keypoints.shape[0]):
        tmp = det[i, :, :]
        tt = (((tag[i, :, :] - prev_tag[None, None, :]) ** 2).sum(axis=2) ** 0.5)
        tmp2 = tmp - np.round(tt)

        x, y = np.unravel_index(np.argmax(tmp2), tmp.shape)
        xx = x
        yy = y
        val = tmp[x, y]
        x += 0.5
        y += 0.5

        if tmp[xx, min(yy + 1, tmp.shape[1] - 1)] > tmp[xx, max(yy - 1, 0)]:
            y += 0.25
        else:
            y -= 0.25

        if tmp[min(xx + 1, tmp.shape[0] - 1), yy] > tmp[max(0, xx - 1), yy]:
            x += 0.25
        else:
            x -= 0.25

        x, y = np.array([y, x])
        ans.append((x, y, val))
    ans = np.array(ans)

    if ans is not None:
        for i in range(17):
            if ans[i, 2] > 0 and keypoints[i, 2] <= 0:
                keypoints[i, :2] = ans[i, :2]
                keypoints[i, 2] = 1

    return keypoints

def multiperson(img, func, persons):
    """
    1. Resize the image to different scales and pass each scale through the network
    2. Merge the outputs across scales
    3. Find the missing joints of the people with a second pass of the heatmaps
    """

    scales = [2, 1., 0.5]

    height, width = img.shape[0:2]
    center = (width / 2, height / 2)
    dets, tags = None, []
    for idx, i in enumerate(scales):
        scale = max(height, width) / 200
        inp_res = int((i * 512 + 63) // 64 * 64)
        res = (inp_res, inp_res)

        mat_ = get_transform(center, scale, res)[:2]
        inp = cv2.warpAffine(img, mat_, res) / 255

        def array2dict(tmp):
            return {
                'det': tmp[0][:, :, :17],
                'tag': tmp[0][:, -1, 17:34]
            }

        tmp1 = array2dict(func([inp]))
        tmp2 = array2dict(func([inp[:, ::-1]]))

        tmp = {}
        for ii in tmp1:
            tmp[ii] = np.concatenate((tmp1[ii], tmp2[ii]), axis=0)

        # === tag: [2, 4, 17, res, res]
        # === det: [2, 17, res, res]

        det = tmp['det'][0, -1] + tmp['det'][1, -1, :, :, ::-1][flipRef]
        if det.max() > 10:
            continue
        if dets is None:
            dets = det
            mat_fw = mat_
            mat_bw = np.linalg.pinv(np.array(mat_).tolist() + [[0, 0, 1]])[:2]
        else:
            # === dets of different scales are resized to the largest res
            dets = dets + resize(det, dets.shape[1:3])

        if abs(i - 1) < 0.5:
            res = dets.shape[1:3]
            # === only keep tags for scale in (0.5, 1.5)
            tags += [resize(tmp['tag'][0], res), resize(tmp['tag'][1, :, :, ::-1][flipRef], res)]

    assert dets is not None
    assert len(tags) != 0

    # === tags: [17, res, res, 2]
    # === dets: [17, res, res]
    tags = np.concatenate([i[:, :, :, None] for i in tags], axis=3)
    dets = dets / len(scales) / 2

    dets = np.minimum(dets, 1)

    refined_persons = []
    for i in range(persons.shape[0]):
        tmp_person = persons[i].copy()
        if np.sum(tmp_person[:, 2] > 0) == 17:
            refined_persons.append(tmp_person)
            continue
        tmp_person[:, :2] = kpt_affine(tmp_person[:, :2], mat_fw) / 4.0
        refined_person = refine(dets, tags, tmp_person)
        refined_person[:, :2] = kpt_affine(refined_person[:, :2] * 4, mat_bw)
        refined_persons.append(refined_person)

    refined_persons = np.stack(refined_persons, axis=0)

    return refined_persons

def genDtByPred(pred, image_id=0):
    """
    Generate the json-style data for the output
    """
    ans = []
    for i in pred:
        val = pred[i] if type(pred) == dict else i
        if val[:, 2].max() > 0:
            tmp = {'image_id': int(image_id), "category_id": 1, "keypoints": [], "score": float(val[:, 2].mean())}
            p = val[val[:, 2] > 0][:, :2].mean(axis=0)
            for j in val:
                if j[2] > 0.:
                    tmp["keypoints"] += [float(j[0]), float(j[1]), 1]
                else:
                    tmp["keypoints"] += [float(p[0]), float(p[1]), 1]
            ans.append(tmp)
    return ans

def complete_pose(input_json_file, output_json_file, mode):

    def init():
        config = task.__config__

        func = task.make_network(config)

        resume_file = os.path.join("exp", "checkpoint.pth.tar")
        if os.path.isfile(resume_file):
            logger.info("=> loading checkpoint {}".format(resume_file))
            checkpoint = torch.load(resume_file)

            config['inference']['net'].load_state_dict(checkpoint['state_dict'])
            config['train']['optimizer'].load_state_dict(checkpoint['optimizer'])
            config['train']['epoch'] = checkpoint['epoch']
            logger.info("=> loaded checkpoint (epoch {})".format(checkpoint['epoch']))
        else:
            logger.info("=> no checkpoint found: {}".format(resume_file))
            exit(0)

        return func, config

    func, config = init()

    def runner(imgs):
        return func(0, config, 'inference', imgs=torch.Tensor(np.float32(imgs)))['preds']

    def do(img, kps, scores, image_id):
        persons = np.array(kps)
        assert persons.shape[1] == 51, persons.shape
        persons = persons.reshape([-1, 17, 3])
        refined_persons = multiperson(img, runner, persons)
        pred = genDtByPred(refined_persons, image_id=image_id)

        for i, score in zip(pred, scores):
            i['score'] = float(score)
        return pred

    dataset = COCODataset(mode)

    preds = []
    logger.info("Loading result file {}".format(input_json_file))
    with open(input_json_file, "r") as f:
        results = json.load(f)
    image_to_dets = defaultdict(list)
    for det in results:
        image_to_dets[det["image_id"]].append(det)

    for i in tqdm.tqdm(range(len(dataset)), total=len(dataset), ncols=100):
        data = dataset[i]
        img = data["img"]
        img_id = data["img_id"]

        if img_id not in image_to_dets:
            continue

        kps = [det["keypoints"] for det in image_to_dets[img_id]]
        scores = [det["score"] for det in image_to_dets[img_id]]

        pred = do(img, kps, scores, image_id=img_id)
        preds += pred

    logger.info("Save output to {}".format(output_json_file))
    with open(output_json_file, "w") as h:
        json.dump(preds, h, indent=4)

if __name__ == "__main__":
    complete_pose(
        input_json_file=sys.argv[1],
        output_json_file=sys.argv[2],
        mode="valid",
    )

max_stars_repo_name: jiahaoLjh/PoseGrouping

max_issues_repo_name: jiahaoLjh/PoseGrouping

max_forks_repo_name: jiahaoLjh/PoseGrouping


text:
#!/usr/bin/env python
# coding: utf-8

# # Hold out

# In[1]:

# %load imports.py
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
get_ipython().run_line_magic('reload_kedro', '')
get_ipython().run_line_magic('config', 'Completer.use_jedi = False  ## (To fix autocomplete)')

import pandas as pd
pd.options.display.max_rows = 100
from src.models.vmm import ModelSimulator
import matplotlib.pyplot as plt
import matplotlib
#matplotlib.rcParams["figure.figsize"] = (10,10)
plt.style.use('presentation')
from src.visualization.plot import track_plots, plot, captive_plot
import kedro
import numpy as np
import os.path
import anyconfig

from myst_nb import glue
from src.symbols import *
import src.symbols as symbols
from src.system_equations import *

from IPython.display import display, Math, Latex, Markdown
from sympy.physics.vector.printing import vpprint, vlatex

from src.models.regression import MotionRegression

from src.parameters import df_parameters
p = df_parameters["symbol"]

# Read configs:
conf_path = os.path.join("../../conf/base/")
runs_globals_path = os.path.join(
    conf_path,
    "runs_globals.yml",
)

runs_globals = anyconfig.load(runs_globals_path)
model_test_ids = runs_globals["model_test_ids"]

join_globals_path = os.path.join(
    conf_path,
    "join_globals.yml",
)

joins = runs_globals["joins"]
join_runs_dict = anyconfig.load(join_globals_path)

globals_path = os.path.join(
    conf_path,
    "globals.yml",
)
global_variables = anyconfig.load(globals_path)

vmm_names = global_variables["vmms"]
vmm_names.remove('vmm_linear')

only_joined = global_variables[
    "only_joined"
]  # (regress/predict with only models from joined runs)S

vmms = {}
for vmm_name in vmm_names:

    vmms[vmm_name] = catalog.load(vmm_name)

# In[18]:

id = 22774

ship_data = catalog.load("ship_data")
data = catalog.load(f"{ id }.data_ek_smooth")

dataframes = {}
styles = {}
for vmm_name in vmm_names:

    data_resimulate = catalog.load(f"{ vmm_name }.motion_regression.no_circle.{ id }.data_resimulate")

    #index = np.argmax(data_resimulate.isnull().any(axis=1))
    if data_resimulate.notnull().all(axis=1).all():
        dataframes[vmm_name] = data_resimulate.iloc[0:-7500].copy()

    styles[vmm_name] = {'alpha':0.75}

dataframes['model test'] = data.iloc[0:-7500]
styles['model test'] = {'style':'k-', 'alpha':1, 'lw':1}

# In[19]:

fig = track_plots(dataframes, lpp=ship_data['L'], beam=ship_data['B'], plot_boats=True, styles=styles, N=7);
fig.axes.set_xlim(-1,17.5)
fig.axes.set_ylim(5,25)

# In[ ]:

reason: import numpy,from sympy


text:
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 22 14:05:38 2020

@author: Siro Moreno
"""
from sympy import (
    symbols,
    pi,
    cos,
    sin,
    simplify,
    integrate,
    Eq,
    solve,
    dsolve,
    Matrix,
    preorder_traversal,
    Float,
    solve_linear_system,
    eye,
    zeros,
    lambdify,
    sqrt,
)
from sympy.physics.mechanics import dynamicsymbols
from sympy.functions import sign

def integerize(expr):
    expr2 = expr
    for a in preorder_traversal(expr):
        if isinstance(a, Float):
            expr2 = expr2.subs(a, round(a))
    return expr2

def roundize(expr, n=4):
    expr2 = expr
    for a in preorder_traversal(expr):
        if isinstance(a, Float):
            expr2 = expr2.subs(a, round(a, n))
    return expr2

def generic_omnibot_mats(n=4, null_beta=True, equal_r=True):
    t, r, d, s = symbols("t r d s")
    alpha, beta = dynamicsymbols("alpha beta")

    W = Matrix([[r, cos(alpha)], [0, sin(alpha)]])
    T = Matrix([[cos(beta), -sin(beta)], [sin(beta), cos(beta)]])
    A = Matrix([[1, 0, -d], [0, 1, s]])
    WTA = W.inv() @ T.inv() @ A
    WTA.simplify()
    r_n = WTA[0, :]
    s_n = WTA[1, :]

    R_list = []
    S_list = []

    for ii in range(n):
        r_ii = r_n.subs(alpha, symbols("alpha_" + str(ii + 1)))
        r_ii = r_ii.subs(d, symbols("d_" + str(ii + 1)))
        r_ii = r_ii.subs(s, symbols("s_" + str(ii + 1)))
        s_ii = s_n.subs(alpha, symbols("alpha_" + str(ii + 1)))
        s_ii = s_ii.subs(d, symbols("d_" + str(ii + 1)))
        s_ii = s_ii.subs(s, symbols("s_" + str(ii + 1)))
        if not equal_r:
            r_ii = r_ii.subs(r, symbols("r_" + str(ii + 1)))
            s_ii = s_ii.subs(r, symbols("r_" + str(ii + 1)))
        if null_beta:
            r_ii = r_ii.subs(beta, 0)
            s_ii = s_ii.subs(beta, 0)
        else:
            r_ii = r_ii.subs(beta, symbols("beta_" + str(ii + 1)))
            s_ii = s_ii.subs(beta, symbols("beta_" + str(ii + 1)))

        S_list.append(s_ii)
        R_list.append(r_ii)

    R = Matrix(R_list)
    S = Matrix(S_list)
    return R, S

t, r, d, s, m, I_z, I_w, l, L, l_2, L_2 = symbols("t r d s m I_z I_w l L l_2 L_2")
x, y, alpha, beta, sigma, psi, theta = dynamicsymbols("x y alpha beta sigma psi theta")
psi_dot = psi.diff()
psi_dot_dot = psi.diff(t, 2)

q = Matrix([x, y, psi] + [dynamicsymbols(f"phi_{i+1}") for i in range(4)])
q_dot = q.diff(t)
q_dot_dot = q.diff(t, 2)
q_r = Matrix([x, y, psi])
q_r_dot = q_r.diff(t)
q_r_dot_dot = q_r.diff(t, 2)
Gamma = Matrix([dynamicsymbols(f"tau_{i+1}") for i in range(4)])
M_w = eye(4) * I_w
M_r = Matrix([[m, 0, 0], [0, m, 0], [0, 0, I_z]])
R_psi = Matrix([[cos(psi), -sin(psi), 0], [sin(psi), cos(psi), 0], [0, 0, 1]])

def dejabot_mats_body():
    R, S = generic_omnibot_mats()
    for ii in range(4):
        alpha = pi / 4 * (1 - 2 * ((int((ii + 1) / 2)) % 2))
        s = L * (1 - 2 * ((int((ii) / 2)) % 2))
        d = l * (1 - 2 * (ii % 2))
        R[ii, :] = R[ii, :].subs(symbols("alpha_" + str(ii + 1)), alpha)
        R[ii, :] = R[ii, :].subs(symbols("s_" + str(ii + 1)), s)
        R[ii, :] = R[ii, :].subs(symbols("d_" + str(ii + 1)), d)
        S[ii, :] = S[ii, :].subs(symbols("alpha_" + str(ii + 1)), alpha)
        S[ii, :] = S[ii, :].subs(symbols("s_" + str(ii + 1)), s)
        S[ii, :] = S[ii, :].subs(symbols("d_" + str(ii + 1)), d)
    return integerize(R), integerize(S)

def dejabot_mats_2():
    R, S = generic_omnibot_mats(null_beta=False)
    s_list = [l_2, L_2, -L_2, -l_2]
    d_list = [L_2, l_2, -l_2, -L_2]
    for ii in range(4):
        alpha = pi / 4 * (1 - 2 * ((int((ii + 1) / 2)) % 2))
        s = s_list[ii]
        d = d_list[ii]
        R[ii, :] = R[ii, :].subs(symbols("alpha_" + str(ii + 1)), alpha)
        R[ii, :] = R[ii, :].subs(symbols("s_" + str(ii + 1)), s)
        R[ii, :] = R[ii, :].subs(symbols("d_" + str(ii + 1)), d)
        R[ii, :] = R[ii, :].subs(symbols("beta_" + str(ii + 1)), pi / 4)
        S[ii, :] = S[ii, :].subs(symbols("alpha_" + str(ii + 1)), alpha)
        S[ii, :] = S[ii, :].subs(symbols("s_" + str(ii + 1)), s)
        S[ii, :] = S[ii, :].subs(symbols("d_" + str(ii + 1)), d)
        S[ii, :] = S[ii, :].subs(symbols("beta_" + str(ii + 1)), pi / 4)
    return integerize(R), integerize(S)

def calc_matrices(axes="body"):
    if axes == "body":
        R, S = dejabot_mats_body()
    elif str(axes) == "2":
        R, S = dejabot_mats_2()
    else:
        raise NameError("Unrecognized axes name:" + str(axes))

    H = simplify(M_r + R_psi @ R.T @ M_w @ R @ R_psi.T)
    K = simplify(R_psi @ R.T @ M_w @ R @ R_psi.diff().T)
    F_a = R_psi @ R.T @ Gamma
    F_a = Matrix(
        [
            F_a[0].factor(sin(psi), cos(psi)),
            F_a[1].factor(sin(psi), cos(psi)),
            F_a[2].factor(),
        ]
    )
    # A = R_psi@R.T COMPROBAR
    H_inv = simplify(H.inv())
    R_inv = simplify(R.pinv())
    return R, S, H, K, F_a, H_inv, R_inv

def calc_vectors(axes="body"):
    if axes == "body":
        R, S, H, K, F_a, H_inv, R_inv = calc_matrices(axes="body")
        q_w_dot = simplify(R @ R_psi.T @ q_r_dot)
    elif str(axes) == "2":
        R, S, H, K, F_a, H_inv, R_inv = calc_matrices(axes="2")
        w, w_1, w_2, a, a_1, a_2 = symbols("w w_1 w_2 a a_1 a_2")
        q_2_dot = Matrix([w_1, w_2, psi_dot])
        q_2_dot_dot = Matrix([a_1, a_2, psi_dot_dot])
        q_w_dot = simplify(R @ q_2_dot)
    else:
        raise NameError("Unrecognized axes name:" + str(axes))

# -----------  Electric variables and motor models ------------------------

a, b, k_e, k_m, n, r_e, tau_m, mu, v_max = symbols("a b K_e K_m N R_e tau_m mu V_{max}")
phi = dynamicsymbols("phi")
phi_dot = phi.diff(t)

max_stars_repo_name: AunSiro/omnibot

max_issues_repo_name: AunSiro/omnibot

max_forks_repo_name: AunSiro/omnibot

reason: from sympy