text:
import numpy as np
import math

class id:
    def __init__(self, uuid, major, minor):
        self.id = (uuid, major, minor)

class beacon:
    def __init__(self, id, x, y, txPower, N):
        self.id = id
        self.x = x
        self.y = y
        self.txPower = txPower
        self.N = N

    def sqrDistToOrg(self, b):
        return (self.x - b.x) ** 2 + (self.y - b.y) ** 2

class user:
    def __init__(self, arr):
        self.A = arr

    def distanceToBeacon(self, RSSI, beaC):
        return pow(10, (beaC.txPower - RSSI) / (10*beaC.N))

    def sqrDistToBeacon(self, RSSI, beaC):
        return pow(self.distanceToBeacon(RSSI, beaC), 2)

class linearSystem:
    def __init__(self, bList, user):
        self.bList = bList
        self.user = user
    def createMat(self):
        row = []
        org = self.bList[0]
        A =[]
        for i in range(1,len(self.bList)):
            row.append(2*(self.bList[i].x - org.x))
            row.append(2*(self.bList[i].y - org.y))
            A.append(row)
            row = []
        return A

    def matAns(self):
        org = self.bList[0]
        b = []
        for i in range(1, len(self.bList)):
            b.append(self.user.sqrDistToBeacon(self.user.A[0], org) - self.user.sqrDistToBeacon(self.user.A[i],self.bList[i]) + self.bList[i].sqrDistToOrg(org))
        return b

    def ans(self):
        A = np.array(self.createMat())
        b = np.array(self.matAns())
        return np.linalg.inv(A.transpose().dot(A)).dot(A.transpose()).dot(b) - [self.bList[0].x, self.bList[0].y]

class extendedMinMax:
    def __init__(self, bList, user):
        self.bList = bList
        self.d = []
        for i in range(len(bList)):
            self.d.append(user.distanceToBeacon(user.A[i], bList[i]))
    def rectangleVertices(self):
        p = []
        xMax = []
        xMin = []
        yMax = []
        yMin = []
        for i in range(len(self.bList)):
            xMax.append(self.bList[i].x - self.d[i])
            xMin.append(self.bList[i].x + self.d[i])
            yMax.append(self.bList[i].y - self.d[i])
            yMin.append(self.bList[i].y + self.d[i])
        p.append([np.amax(xMax), np.amax(yMax)])
        p.append([np.amax(xMax), np.amin(yMin)])
        p.append([np.amin(xMin), np.amin(yMin)])
        p.append([np.amin(xMin), np.amax(yMax)])
        return p

    def ans(self):
        w = []
        p = self.rectangleVertices()
        for i in p:
            w.append(self.weight1(i))
        x = (w[0]*p[0][0] + w[1]*p[1][0] + w[2]*p[2][0] + w[3]*p[3][0])/sum(w)
        y = (w[0]*p[0][1] + w[1]*p[1][1] + w[2]*p[2][1] + w[3]*p[3][1])/sum(w)
        return [x,y]

    def weight1(self, p):
        arr = []
        for i in range(len(self.bList)):
            arr.append(abs(self.euclidean(p, self.bList[i]) - self.d[i]))
        return 1/sum(arr)

    # def weight2(self, p):
    #     arr = []
    #     for i in range(len(self.bList)):
    #         arr.append(pow((self.euclidean(p, self.bList[i]) - self.d[i]), 2))
    #     return 1/sum(arr)

    # def weight4(self, p):
    #     arr = []
    #     for i in range(len(self.bList)):
    #         arr.append(abs(pow(self.euclidean(p, self.bList[i]),2) - pow(self.d[i], 2)))
    #     return 1/sum(arr)

    def euclidean(self, p, beaC):
        return math.sqrt(pow(beaC.x - p[0], 2) + pow(beaC.y - p[1], 2))

# if __name__ == '__main__':
#     beaconList = []
#     beaconList.append(beacon(1,0,0,-60,1))
#     beaconList.append(beacon(1,0, 1, -60, 1))
#     beaconList.append(beacon(1,1, 1, -60, 1))
#     beaconList.append(beacon(1,1, 0, -60, 1))
#     u = user([-30, -60, -61.5, -60])
#     linearModel = linearSystem(beaconList,u)
#     x = linearModel.ans()
#     print(x)
#     # emm = extendedMinMax(beaconList, u)
#     # print(emm.ans())

max_stars_repo_name: ptdzung/beacons

max_issues_repo_name: ptdzung/beacons

max_forks_repo_name: ptdzung/beacons


text:
"""Various implementations of radial distribution function calculations."""

import os
import pdb

import numpy as np

from pyrdf.mdio import read_frame_lammpstrj, distance_pbc

def rdf(file_name, pairs=None, r_range=np.array([0.0, 8.0], dtype=np.float32),
        n_bins=np.uint32(100), max_frames=1, acceleration=True, local_size= None,
        verbose=False):
    """Calculate radial distribution functions.

    Args:
        file_name (str): name of trajectory file.
        pairs (None or list): pairs of atomtypes to consider.
        r_range (np.ndarray): min and max radii.
        n_bins (np.uint32): number of bins.
        max_frames (int): maximum number of frames to read.
    Returns:
        r (np.ndarray): radii values corresponding to bins.
        g_r (np.ndarray): values at r.
    """
    n_bins = np.uint32(n_bins)
    r_range = np.array(r_range)
    r_range = r_range.astype(np.float32)
    g_r, edges = np.histogram([0], bins=n_bins, range=r_range)
    g_r[0] = 0
    g_r = g_r.astype(np.uint32)
    temp_g_r = np.zeros_like(g_r)
    n_frames = 0
    rho = 0

    if acceleration == 'opencl':
        import pyopencl as cl
        ctx = cl.create_some_context()
        queue = cl.CommandQueue(ctx)
        mf = cl.mem_flags

        kernel_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                   'rdf.cl')
        with open(kernel_path, 'r') as f:
            source = "".join(f.readlines())
        program = cl.Program(ctx, source).build()

    elif acceleration == 'cython':
        import pyximport
        pyximport.install(setup_args={'include_dirs':[np.get_include()]})
        from _rdf import cy_rdf

    with open(file_name, 'r') as trj:
        while n_frames < max_frames:
            try:
                xyz, types, _, box = read_frame_lammpstrj(trj)
            except ValueError:
                if verbose:
                    print("Reached end of '{0}' or "
                        "file contains unexpected line.".format(file_name))
                break
            if verbose:
                print "Read " + str(n_frames)
            n_frames += 1
            n_atoms = np.int64(xyz.shape[0])
            box_lengths = [dim_max - dim_min for dim_min, dim_max in box]
            box_lengths = np.array(box_lengths)
            box_volume = np.prod(box_lengths)

            if acceleration == 'opencl':
                if not pairs:
                    pass
                elif pairs[0] == pairs[1]:
                    xyz = xyz[types == pairs[0]]
                    n_atoms = np.int64(xyz.shape[0])
                else:
                    raise Exception("Not yet implemented!")
                i = n_atoms - 1
                global_size = (n_atoms,)

                xyz_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR,
                        hostbuf=xyz)
                box_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR,
                        hostbuf=box_lengths)
                result_buf = cl.Buffer(ctx, mf.WRITE_ONLY, temp_g_r.nbytes)

                kernel = program.rdf(queue, global_size, local_size,
                        n_atoms, n_bins, r_range[0], r_range[1],
                        xyz_buf, box_buf, result_buf)

                cl.enqueue_read_buffer(queue, result_buf, temp_g_r).wait()
                g_r += temp_g_r

            elif acceleration == 'cython':
                if not pairs:
                    g_r = cy_rdf(n_atoms, n_bins, r_range[0], r_range[1],
                            xyz, box_lengths, g_r)
                else:
                    raise Exception("Not yet implemented!")
                i = n_atoms - 1

            else:
                # all-all
                if not pairs:
                    for i, xyz_i in enumerate(xyz):
                        xyz_j = np.vstack([xyz[:i], xyz[i+1:]])
                        d = distance_pbc(xyz_i, xyz_j, box_lengths)
                        temp_g_r, _ = np.histogram(d, n_bins, r_range)
                        g_r += temp_g_r

                # type_i-type_i
                elif pairs[0] == pairs[1]:
                    xyz_0 = xyz[types == pairs[0]]
                    for i, xyz_i in enumerate(xyz_0):
                        xyz_j = np.vstack([xyz_0[:i], xyz_0[i+1:]])
                        d = distance_pbc(xyz_i, xyz_j, box_lengths)
                        temp_g_r, _ = np.histogram(d, n_bins, r_range)
                        g_r += temp_g_r

                # type_i-type_j
                else:
                    for i, xyz_i in enumerate(xyz[types == [pairs[0]]]):
                        xyz_j = xyz[types == pairs[1]]
                        d = distance_pbc(xyz_i, xyz_j, box_lengths)
                        temp_g_r, _ = np.histogram(d, n_bins, r_range)
                        g_r += temp_g_r

            rho += (i + 1) / box_volume

    # normalization
    r = 0.5 * (edges[1:] + edges[:-1])
    V = 4./3. * np.pi * (np.power(edges[1:], 3) - np.power(edges[:-1], 3))
    norm = rho * i
    g_r = g_r.astype(np.float32)  # from uint32
    g_r /= norm * V

    return r, g_r

ext: py

reason: import numpy


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

# File Name : preprocess.py
# Purpose :
# Creation Date : 10-12-2018
# Last Modified : Thu 18 Jan 2018 05:34:42 PM CST
# Created By : Jeasine Ma [jeasinema[at]gmail[dot]com]
# BSD 3-Clause License
#
# Copyright (c) 2019, FPAI
# Copyright (c) 2019, SeriouslyHAO
# Copyright (c) 2019, xcj2019
# Copyright (c) 2019, Leonfirst
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import multiprocessing
import numpy as np
#import pcl

from config import cfg

data_dir = 'velodyne'

def process_pointcloud(point_cloud, cls=cfg.DETECT_OBJ):
    # Input:
    #   (N, 4)
    # Output:
    #   voxel_dict
    # print('process_pointcloud')

    if cls == 'Car':
        scene_size = np.array([4, 80, 70.4], dtype=np.float32)
        voxel_size = np.array([0.4, 0.2, 0.2], dtype=np.float32)
        grid_size = np.array([10, 400, 352], dtype=np.int64)
        lidar_coord = np.array([0, 40, 3], dtype=np.float32)

    # point_cloud = point_cloud[:, :3]
    # p = pcl.PointCloud(point_cloud)
    # fil = p.make_ApproximateVoxelGrid()
    # s = cfg.VOXEL_FILTER_SIZE
    # fil.set_leaf_size(s, s, s)
    # point_cloud = np.array(fil.filter())

    shifted_coord = point_cloud[:, :3] + lidar_coord
    # reverse the point cloud coordinate (X, Y, Z) -> (Z, Y, X)
    voxel_index = np.floor(
        shifted_coord[:, ::-1] / voxel_size).astype(np.int)

    # print("voxel_index.shape ", voxel_index.shape)

    bound_x = np.logical_and(
        voxel_index[:, 2] >= 0, voxel_index[:, 2] < grid_size[2])
    bound_y = np.logical_and(
        voxel_index[:, 1] >= 0, voxel_index[:, 1] < grid_size[1])
    bound_z = np.logical_and(
        voxel_index[:, 0] >= 0, voxel_index[:, 0] < grid_size[0])

    bound_box = np.logical_and(np.logical_and(bound_x, bound_y), bound_z)

    point_cloud = point_cloud[bound_box]
    voxel_index = voxel_index[bound_box]

    # [K, 3] coordinate buffer as described in the paper
    coordinate_buffer = np.unique(voxel_index, axis=0)

    # print("coordinate_buffer.shape ", coordinate_buffer.shape)

    # K = None
    K = len(coordinate_buffer)

    # print("K ", K)

    T = cfg.VOXEL_POINT_COUNT

    # [K, 1] store number of points in each voxel grid
    # number_buffer = np.array(K)
    number_buffer = np.zeros(shape=(K), dtype=np.int64)

    # [K, T, cfg.VOXEL_POINT_DIM] feature buffer as described in the paper
    # feature_buffer = np.array(K, T, cfg.VOXEL_POINT_DIM)
    feature_buffer = np.zeros(shape=(K, T, cfg.VOXEL_POINT_DIM), dtype=np.float32)

    # build a reverse index for coordinate buffer
    index_buffer = {}
    for i in range(K):
        index_buffer[tuple(coordinate_buffer[i])] = i

    # print("point_cloud.shape ", point_cloud.shape)
    # print("point_cloud[0] ", point_cloud[0])
    # print("point_cloud[1] ", point_cloud[1])
    # print("point_cloud[2] ", point_cloud[2])
    # print("point_cloud[3] ", point_cloud[3])
    # print("point_cloud.shape2 ", point_cloud.shape)
    # print("type(point_cloud)", type(point_cloud))
    # print("point_cloud.shape3 ", point_cloud.shape)
    # print(point_cloud[0])
    # print(point_cloud[1])
    # print(point_cloud[2])
    # print(point_cloud[3])
    # print(point_cloud[4])
    # print(point_cloud[5])

    KK=0
    for voxel, point in zip(voxel_index, point_cloud):
        KK=KK+1
        index = index_buffer[tuple(voxel)]
        number = number_buffer[index]
        if number < T:
        # if True:
            feature_buffer[index, number, :cfg.VOXEL_POINT_RAW_DIM] = point
            number_buffer[index] += 1

    # print("KK ",KK)

    # print(feature_buffer[0][0])
    # print(feature_buffer[0][1])
    # print(feature_buffer[0][2])
    # print(feature_buffer[0][3])
    # print(feature_buffer[0][4])
    # print(feature_buffer[0][5])
    # print(feature_buffer[1][0])
    # print(feature_buffer[1][1])
    # print(feature_buffer[1][2])
    # print(feature_buffer[1][3])
    # print(feature_buffer[1][4])
    # print(feature_buffer[1][5])
    # print("feature_buffer[:, :, :3].shape ", feature_buffer[:, :, :3].shape)

    feature_buffer[:, :, -3:] = feature_buffer[:, :, :3] - \
        feature_buffer[:, :, :3].sum(axis=1, keepdims=True)/number_buffer.reshape(K, 1, 1)

    # print(feature_buffer[0][0])
    # print(feature_buffer[0][1])
    # print(feature_buffer[0][2])
    # print(feature_buffer[0][3])
    # print(feature_buffer[0][4])
    # print(feature_buffer[0][5])
    # print(feature_buffer[1][0])
    # print(feature_buffer[1][1])
    # print(feature_buffer[1][2])
    # print(feature_buffer[1][3])
    # print(feature_buffer[1][4])
    # print(feature_buffer[1][5])

    # print("feature_buffer.shape ",feature_buffer.shape)

    voxel_dict = {'feature_buffer': feature_buffer,
                  'coordinate_buffer': coordinate_buffer,
                  'number_buffer': number_buffer}
    return voxel_dict

max_stars_repo_name: Hqss/DINK

max_issues_repo_name: jtpils/DINK

max_forks_repo_name: jtpils/DINK


text:
import networkx
import math
import random
import time

from util import *
from cache import *
from packet import *
from observer import *
from distribution import *
from attack import *

class Node(object):
    def __init__(self, name, caching=True):
        self.name = name
        self.next_hops = {}
        self.neighbors = []

        self.caching = caching
        if caching:
            self.cache = Cache()

    def reset(self):
        if self.caching:
            self.cache.flush()

    def add_link(self, node):
        if node not in self.neighbors:
            self.neighbors.append(node)

    def has_route(self, prefix):
        return prefix in self.next_hops

    def add_route(self, name, node):
        if name not in self.next_hops:
            self.next_hops[name] = [node]
        elif node not in self.next_hops[name]:
            self.next_hops[name].append(node)

    def get_next_hop(self, name, source = None):
        if name in self.next_hops:
            if source == None:
                return self.next_hops[name]
            else:
                neighbors = self.next_hops[name]
                if source in neighbors:
                    neighbors.remove(source)
                return neighbors
        raise Exception("Neighbor not found")

    def get_neighbors(self, to_remove = []):
        copy = self.neighbors[:]
        for other in to_remove:
            if other in copy:
                copy.remove(other)
        return copy

    def process_packet(self, packet, path = []):
        if self.caching:
            # indexing the cache does not include the routable prefix
            identity = self.cache.lookup(packet.identity)
            if identity != None: # and packet.prefix == response.prefix:
                response_packet = Packet(packet.prefix, identity)
                response_packet.hop_count = packet.hop_count
                return response_packet

        prefix = packet.prefix
        if prefix in self.next_hops:
            next_hops = self.next_hops[prefix]
            random.shuffle(next_hops)
            for neighbor in next_hops: # try each face *in random order*
                if neighbor not in path:

                    copy = path[:]
                    copy.append(neighbor)
                    response = neighbor.process_packet(packet.forward(), copy)

                    if response != None:
                        if self.caching:
                            self.cache.add(response.identity, response.identity)
                        return response
            raise Exception("This cannot happen. A content object must be returned: %s %s %s" % (self.name, packet.name, str(path)))
        else:
            raise Exception("We have no route to get this item: %s %s %s %s" % (self.name, packet.name, str(path), str(self.next_hops)))

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.name == other.name
        else:
            return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def __str__(self):
        next_hops = []
        for prefix in self.next_hops:
            hops = []
            for node in self.next_hops[prefix]:
                hops.append(node.name)
            next_hops.append("%s -> [%s]" % (prefix, ",".join(hops)))
        return "%s %s" % (self.name, next_hops)

    def __repr__(self):
        return str(self)

class ObserverNode(Node):
    def __init__(self, name):
        Node.__init__(self, name)
        self.observer = Observer()

    def reset(self):
        self.observer.reset()

    def process_packet(self, packet, path = []):
        self.observer.add(packet.identity, packet.nonce)
        return Node.process_packet(self, packet, path)

    def get_observer(self):
        return self.observer

class ConsumerNode(Node):
    def __init__(self, name):
        Node.__init__(self, name, False)

    def process_packet(self, packet, path = []):
        result = Node.process_packet(self, packet, path)
        if result == None:
            raise Exception("Consumer failed to fetch content -- routing and forwarding error.")
        return result

class ObservingConsumerNode(Node):
    def __init__(self, name, universe):
        Node.__init__(self, name, False)
        self.universe = universe
        self.hits = {item: 0 for item in universe}

    def process_packet(self, packet, path = []):
        result = Node.process_packet(self, packet, path)
        if result == None:
            raise Exception("Consumer failed to fetch content -- routing and forwarding error.")
        if result.cache_hit:
            self.hits[result.identity] += 1
        return result

    def create_observer(self):
        observer = Observer()
        observer.counts = self.hits
        observer.min_count = min(self.hits.itervalues())
        observer.max_count = max(self.hits.itervalues())
        return observer

class ProducerNode(Node):
    def __init__(self, name, prefix, cache):
        Node.__init__(self, name)
        self.cache = cache
        self.prefix = prefix

    def get_prefix(self):
        return self.prefix

    def process_packet(self, packet, path = []):
        response = self.cache.lookup(packet.identity)
        if response != None: # the prefix may not match
            return Packet(packet.prefix, packet.identity, packet.hop_count)
        return Node.process_packet(self, packet, path)

class Network(object):
    def __init__(self, name):
        self.name = name
        self.nodes = {}
        self.consumers = {}
        self.estimators = {}
        self.producers = {}
        self.observers = {}
        self.id_root = 0

    def num_nodes(self):
        return len(self.nodes)

    # route distribution -- spanning tree style
    def propogate_route(self, source, prefix, visited = []):
        if visited == []:
           visited.append(source)

        for neighbor in source.get_neighbors(visited):
            if neighbor not in visited and not neighbor.has_route(prefix):
                neighbor.add_route(prefix, source)
                copy = visited[:]
                copy.append(neighbor)
                self.propogate_route(neighbor, prefix, copy)

    def __next_node_id(self):
        self.id_root += 1
        return str(self.id_root)

    def reset(self):
        for node in self.nodes:
            if node not in self.producers: # don't delete producer caches!
                self.nodes[node].reset()

    def create_node(self, caching=True):
        identity = self.__next_node_id()
        node = Node(identity, caching)
        self.nodes[identity] = node
        return node

    def create_observer(self):
        identity = self.__next_node_id()
        node = ObserverNode(identity)
        self.nodes[identity] = node
        self.observers[identity] = node
        return node

    def create_consumer(self):
        identity = self.__next_node_id()
        consumer = ConsumerNode(identity)
        self.nodes[identity] = consumer
        self.consumers[consumer.name] = consumer
        return consumer

    def create_estimator(self, universe):
        identity = self.__next_node_id()
        consumer = ObservingConsumerNode(identity, universe)
        self.nodes[identity] = consumer
        self.estimators[consumer.name] = consumer
        return consumer

    def create_producer(self, prefix, cache):
        identity = self.__next_node_id()
        node = ProducerNode(identity, prefix, cache)
        self.nodes[identity] = node
        self.producers[identity] = node
        return node

    def get_consumers(self):
        return self.consumers.values()

    def get_estimators(self):
        return self.estimators.values()

    def get_producers(self):
        return self.producers.values()

    def merge_observers(self):
        obs = []
        for o in self.observers:
            obs.append(self.observers[o].observer)
        return combine_observers(obs)

    def merge_estimators(self):
        est = []
        for e in self.estimators:
            est.append(self.estimators[e].create_observer())
        return combine_observers(est)

    def link(self, idA, idB):
        idA = idA.name
        idB = idB.name
        if idA in self.nodes and idB in self.nodes:
            nodeA = self.nodes[idA]
            nodeB = self.nodes[idB]
            nodeA.add_link(nodeB)
            nodeB.add_link(nodeA)
        else:
            raise Exception("%s or %s does not exist in this network" % (idA, idB))

    def add_route(self, idA, idB, prefix):
        idA = str(idA)
        idB = str(idB)
        if idA in self.nodes and idB in self.nodes:
            nodeA = self.nodes[idA]
            nodeB = self.nodes[idB]
            nodeA.add_route(prefix, nodeB)
        else:
            raise Exception("%s or %s does not exist in this network" % (idA, idB))

    def to_dot(self, path):
        lines = []

        G = networkx.Graph()
        seen = []
        queue = [(self.nodes.values()[0], None)]
        while len(queue) > 0:
            curr, prev = queue.pop()
            if curr not in seen:
                seen.append(curr)
                neighbors = curr.get_neighbors([prev])
                for n in neighbors:
                    G.add_edge(curr.name, n.name)
                    queue.append((n, curr))

        dot = networkx.drawing.nx_pydot.write_dot(G, path)

    def __getitem__(self, key):
        return self.nodes[str(key)]

def create_path(items, adv_fraction, cache_fraction, est_fraction, num_consumers, N = 3):
    net = Network("Path-%d-%f-%f" % (N, adv_fraction, cache_fraction))
    curr = net.create_consumer()

    for i in range(N - 2):
        cache = random_flag(cache_fraction)
        adv = random_flag(adv_fraction)
        if adv:
            next_node = net.create_observer()
        else:
            next_node = net.create_node(cache)

        net.link(curr, next_node)
        curr = next_node

    prod = net.create_producer(items[0].prefix, items[0])
    net.link(curr, prod)
    return net

def create_tree(items, levels, k, adv_fraction, cache_fraction):
    net = Network("Tree-%d-%d-%f-%f" % (levels, k, adv_fraction, cache_fraction))

    root = net.create_producer(items)
    prev_level = [root] # first level

    for level in range(levels - 1):
        curr_level = []
        for node in prev_level:
            for i in range(k):
                if random_flag(adv_fraction):
                    next_node = net.create_observer()
                elif level == levels - 1:
                    next_node = net.create_consumer()
                else:
                    next_node = net.create_node(random_flag(cache_fraction))
                net.link(node, next_node)
                curr_level.append(next_node)
        prev_level = curr_level

    return net

def create_lattice_network(cache_list, adv_fraction, cache_fraction, est_fraction, num_consumers):
    net = Network("Lattice-%d-%d-%f-%f" % (len(cache_list), num_consumers, adv_fraction, cache_fraction))

    producers = []
    consumers = []
    routers = []

    # Create the producers
    for cache in cache_list:
        producer = net.create_producer(cache.prefix, cache)
        producers.append(producer)

    # Create the middle routers
    for cache in cache_list:
        if random_flag(adv_fraction):
            router = net.create_observer()
        else:
            router = net.create_node(random_flag(cache_fraction))
        routers.append(router)

    # Connect the upper router
    for i in range(len(cache_list)):
        for j in range(len(cache_list)):
            net.link(producers[i], routers[j])

    universe = set()
    for cache in cache_list:
        for i in range(cache.size()):
            universe.add(cache.index(i))

    # Create the consumers
    consumer_limit = int(math.ceil(float(num_consumers) / len(routers)))
    router = 0
    index = 0
    for i in range(num_consumers):
        consumer = None
        if random_flag(est_fraction):
            consumer = net.create_estimator(universe)
        else:
            consumer = net.create_consumer()

        net.link(consumer, routers[index])
        router += 1
        if router == consumer_limit:
            index += 1
            router = 0

    return net

def create_att_network(cache_list, adv_fraction, cache_fraction, est_fraction, group_size = 10):
    net = Network("ATT-%d-%f-%f" % (group_size, adv_fraction, cache_fraction))

    number_routers = 42
    routers = []

    # Create the routers
    for i in range(number_routers):
        if random_flag(adv_fraction):
            router = net.create_observer()
        else:
            router = net.create_node(random_flag(cache_fraction))
        routers.append(router)

    # Connect the consumers to edge routers
    edge_routers = [0, 36, 37, 9, 38, 13, 16, 20, 18, 28, 21, 24, 26, 35, 34, 33]
    for r in edge_routers:
        for i in range(group_size):
            consumer = net.create_consumer()
            router = routers[r]
            net.link(consumer, router)

    # Create the producer and connect to R0
    router_index = 0
    for cache in cache_list:
        producer = net.create_producer(cache)
        root = routers[router_index]
        net.link(producer, root)
        router_index = (router_index + 1) % len(routers)

    # Connect the internal routers
    internal_edges = [
        (0, 1),
        (1, 2),
        (1, 17),
        (2, 3),
        (2, 4),
        (2, 6),
        (2, 36),
        (2, 8),
        (2, 17),
        (2, 19),
        (3, 5),
        (4, 16),
        (5, 8),
        (6, 7),
        (6, 37),
        (7, 10),
        (8, 9),
        (8, 11),
        (8, 17),
        (10, 11),
        (11, 16),
        (11, 38),
        (11, 12),
        (11, 13),
        (11, 23),
        (12, 13),
        (13, 23),
        (14, 16),
        (14, 15),
        (15, 39),
        (15, 17),
        (16, 17),
        (16, 19),
        (17, 18),
        (17, 19),
        (17, 29),
        (17, 32),
        (17, 31),
        (17, 39),
        (19, 20),
        (19, 27),
        (21, 22),
        (22, 40),
        (22, 23),
        (22, 25),
        (23, 24),
        (25, 27),
        (26, 27),
        (27, 40),
        (27, 30),
        (27, 31),
        (28, 29),
        (29, 30),
        (30, 31),
        (30, 41),
        (30, 35),
        (31, 41),
        (31, 32),
        (31, 34),
        (32, 33)
    ]

    for (u, v) in internal_edges:
        net.link(routers[u], routers[v])

    return net

def create_edge_dfn_network(cache_list, adv_fraction, cache_fraction, est_fraction, group_size = 1):
    net = Network("DFN-%d-%f-%f" % (group_size, adv_fraction, cache_fraction))

    outRouterIndices = [0, 1, 2, 3, 5, 6, 8, 10, 11, 12, 17, 18, 20, 24, 26, 28, 29]
    num_out_routers = len(outRouterIndices)
    inRouterIndices = [4, 7, 9, 13, 14, 15, 16, 19, 21, 22, 23, 25, 27]

    routers = []
    num_routers = 30
    for i in range(num_routers):
        is_adv = random_flag(adv_fraction)
        if i in outRouterIndices and is_adv:
            router = net.create_observer()
        else:
            router = net.create_node(random_flag(cache_fraction))
        routers.append(router)

    # Connecting consumers to edge routers
    for r in outRouterIndices:
        for i in range(group_size):
            consumer = net.create_consumer()
            router = routers[r]
            net.link(consumer, router)

    # Create the producer and connect to R0
    router_index = 0
    for cache in cache_list:
        producer = net.create_producer(cache.prefix, cache)
        root = routers[outRouterIndices[router_index]]
        net.link(root, producer)
        router_index = (router_index + 1) % num_out_routers

    # Connect the inner routers
    net.link(routers[0], routers[9])
    net.link(routers[1], routers[15])
    net.link(routers[2], routers[9])
    net.link(routers[3], routers[4])
    net.link(routers[4], routers[7])
    net.link(routers[4], routers[14])
    net.link(routers[4], routers[9])
    net.link(routers[4], routers[16])
    net.link(routers[4], routers[25])
    net.link(routers[5], routers[13])
    net.link(routers[6], routers[7])
    net.link(routers[7], routers[9])
    net.link(routers[7], routers[14])
    net.link(routers[7], routers[22])
    net.link(routers[7], routers[23])
    net.link(routers[8], routers[9])
    net.link(routers[9], routers[13])
    net.link(routers[9], routers[14])
    net.link(routers[9], routers[22])
    net.link(routers[9], routers[25])
    net.link(routers[9], routers[27])
    net.link(routers[10], routers[14])
    net.link(routers[11], routers[13])
    net.link(routers[12], routers[13])
    net.link(routers[13], routers[14])
    net.link(routers[13], routers[22])
    net.link(routers[13], routers[25])
    net.link(routers[13], routers[27])
    net.link(routers[14], routers[15])
    net.link(routers[14], routers[18])
    net.link(routers[14], routers[19])
    net.link(routers[15], routers[16])
    net.link(routers[15], routers[19])
    net.link(routers[15], routers[21])
    net.link(routers[15], routers[22])
    net.link(routers[15], routers[23])
    net.link(routers[15], routers[25])
    net.link(routers[15], routers[27])
    net.link(routers[16], routers[23])
    net.link(routers[16], routers[27])
    net.link(routers[17], routers[23])
    net.link(routers[19], routers[22])
    net.link(routers[20], routers[25])
    net.link(routers[21], routers[22])
    net.link(routers[21], routers[27])
    net.link(routers[22], routers[23])
    net.link(routers[22], routers[28])
    net.link(routers[22], routers[29])
    net.link(routers[23], routers[24])
    net.link(routers[23], routers[25])
    net.link(routers[23], routers[27])
    net.link(routers[26], routers[27])

    return net

def create_dfn_network(cache_list, adv_fraction, cache_fraction, est_fraction, group_size = 1):
    net = Network("DFN-%d-%f-%f" % (group_size, adv_fraction, cache_fraction))

    outRouterIndices = [0, 1, 2, 3, 5, 6, 8, 10, 11, 12, 17, 18, 20, 24, 26, 28, 29]
    num_out_routers = len(outRouterIndices)
    inRouterIndices = [4, 7, 9, 13, 14, 15, 16, 19, 21, 22, 23, 25, 27]

    routers = []
    num_routers = 30
    for i in range(num_routers):
        if random_flag(adv_fraction):
            router = net.create_observer()
        else:
            router = net.create_node(random_flag(cache_fraction))
        routers.append(router)

    # Connecting consumers to edge routers
    for r in outRouterIndices:
        for i in range(group_size):
            consumer = net.create_consumer()
            router = routers[r]
            net.link(consumer, router)

    # Create the producer and connect to R0
    router_index = 0
    for cache in cache_list:
        producer = net.create_producer(cache.prefix, cache)
        root = routers[outRouterIndices[router_index]]
        net.link(producer, root)
        router_index = (router_index + 1) % num_out_routers

    # Connect the inner routers
    net.link(routers[0], routers[9])
    net.link(routers[1], routers[15])
    net.link(routers[2], routers[9])
    net.link(routers[3], routers[4])
    net.link(routers[4], routers[7])
    net.link(routers[4], routers[14])
    net.link(routers[4], routers[9])
    net.link(routers[4], routers[16])
    net.link(routers[4], routers[25])
    net.link(routers[5], routers[13])
    net.link(routers[6], routers[7])
    net.link(routers[7], routers[9])
    net.link(routers[7], routers[14])
    net.link(routers[7], routers[22])
    net.link(routers[7], routers[23])
    net.link(routers[8], routers[9])
    net.link(routers[9], routers[13])
    net.link(routers[9], routers[14])
    net.link(routers[9], routers[22])
    net.link(routers[9], routers[25])
    net.link(routers[9], routers[27])
    net.link(routers[10], routers[14])
    net.link(routers[11], routers[13])
    net.link(routers[12], routers[13])
    net.link(routers[13], routers[14])
    net.link(routers[13], routers[22])
    net.link(routers[13], routers[25])
    net.link(routers[13], routers[27])
    net.link(routers[14], routers[15])
    net.link(routers[14], routers[18])
    net.link(routers[14], routers[19])
    net.link(routers[15], routers[16])
    net.link(routers[15], routers[19])
    net.link(routers[15], routers[21])
    net.link(routers[15], routers[22])
    net.link(routers[15], routers[23])
    net.link(routers[15], routers[25])
    net.link(routers[15], routers[27])
    net.link(routers[16], routers[23])
    net.link(routers[16], routers[27])
    net.link(routers[17], routers[23])
    net.link(routers[19], routers[22])
    net.link(routers[20], routers[25])
    net.link(routers[21], routers[22])
    net.link(routers[21], routers[27])
    net.link(routers[22], routers[23])
    net.link(routers[22], routers[28])
    net.link(routers[22], routers[29])
    net.link(routers[23], routers[24])
    net.link(routers[23], routers[25])
    net.link(routers[23], routers[27])
    net.link(routers[26], routers[27])

    return net

def create_random_network(items, n, p, adv_fraction, cache_fraction):
    # https://networkx.github.io/documentation/development/reference/generators.html
    G = networkx.fast_gnp_random_graph(n, p)
    net = Network()

    # Pull off the root
    root = net.create_producer()

    seen = set()
    queue = [(0, root)]
    while len(queue) > 0:
        identity, curr = queue.pop()
        if identity not in seen:
            seen.add(identity)
            neighbors = G.neighbors(identity)
            for n in neighbors:
                if random_flag(adv_fraction):
                    next_node = net.create_observer()
                else:
                    next_node = net.create_node(random_flag(cache_fraction))
                net.link(curr, next_node)
                queue.append((n, next_node))

    return net

def create_simple_graph():
    net = Network()
    nA = net.create_consumer()
    nB = net.create_node(False)
    nC = net.create_observer()
    nD = net.create_producer(items)

    net.link(1, 2)
    net.link(2, 3)
    net.link(3, 4)

    return net

max_stars_repo_name: chris-wood/ccn-eavesdropper-simulator

max_issues_repo_name: chris-wood/ccn-eavesdropper-simulator

max_forks_repo_name: chris-wood/ccn-eavesdropper-simulator

reason: import networkx


text:
import numpy as np
# import imutils
import os, sys
import argparse
import copy
# This try-catch is a workaround for Python3 when used with ROS;
# it is not needed for most platforms
try:
    sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
except:
    pass

# Import OpenCV library
import cv2 as cv

# Use Argument Parser to get the video
ap = argparse.ArgumentParser()
ap.add_argument("--vid", required=True, help="Path to video file")
ap.add_argument("--func", required=True, help="1 (for detection) / 2 (for lena superimpose) / 3 (for tracking)")

args = vars(ap.parse_args())

vid = cv.VideoCapture(args["vid"])

func = args["func"]

frame_width = int(vid.get(3))
frame_height = int(vid.get(4))
print("Do you want a video:")
val = input("Give 1 for Yes, 0 for No: ")

if val == "1":
	out = cv.VideoWriter('output.avi', cv.VideoWriter_fourcc('M','J','P','G'), 30, (frame_width, frame_height))
	print("Video recording will start accordingly.")

# Camera configurations from yaml file.
# given as lower triangular matrix.
KT = np.array([[1406.08415449821, 0 , 0],
               [2.20679787308599, 1417.99930662800,0],
               [1014.13643417416, 566.347754321696,1]])

# Intrinsic camera matrix is given by K
K = KT.T

def read_lena():
	img = cv.imread('Lena.png', cv.IMREAD_COLOR)
	return img

def read_marker():
	img = cv.imread('ref_marker.png', cv.IMREAD_COLOR)
	return img

def homography_estimation(src, tgt):
	A = np.array([
					[-src[0][0], -src[0][1], -1, 0, 0, 0, src[0][0] * tgt[0][0], src[0][1] * tgt[0][0], tgt[0][0]],
					[0, 0, 0, -src[0][0], -src[0][1], -1, src[0][0] * tgt[0][1], src[0][1] * tgt[0][1], tgt[0][1]],
					[-src[1][0], -src[1][1], -1, 0, 0, 0, src[1][0] * tgt[1][0], src[1][1] * tgt[1][0], tgt[1][0]],
					[0, 0, 0, -src[1][0], -src[1][1], -1, src[1][0] * tgt[1][1], src[1][1] * tgt[1][1], tgt[1][1]],
					[-src[2][0], -src[2][1], -1, 0, 0, 0, src[2][0] * tgt[2][0], src[2][1] * tgt[2][0], tgt[2][0]],
					[0, 0, 0, -src[2][0], -src[2][1], -1, src[2][0] * tgt[2][1], src[2][1] * tgt[2][1], tgt[2][1]],
					[-src[3][0], -src[3][1], -1, 0, 0, 0, src[3][0] * tgt[3][0], src[3][1] * tgt[3][0], tgt[3][0]],
					[0, 0, 0, -src[3][0], -src[3][1], -1, src[3][0] * tgt[3][1], src[3][1] * tgt[3][1], tgt[3][1]],
				])
	U,S,V = np.linalg.svd(A)
	X = V[:][8]/V[8][8]
	Hinv = np.reshape(X,(3,3))
	H = np.linalg.inv(Hinv)
	H = H/H[2][2]
	return H

def homography_estimation_cube(src, tgt):
	A = np.array([
					[-src[0][0], -src[0][1], -1, 0, 0, 0, src[0][0] * tgt[0][0], src[0][1] * tgt[0][0], tgt[0][0]],
					[0, 0, 0, -src[0][0], -src[0][1], -1, src[0][0] * tgt[0][1], src[0][1] * tgt[0][1], tgt[0][1]],
					[-src[1][0], -src[1][1], -1, 0, 0, 0, src[1][0] * tgt[1][0], src[1][1] * tgt[1][0], tgt[1][0]],
					[0, 0, 0, -src[1][0], -src[1][1], -1, src[1][0] * tgt[1][1], src[1][1] * tgt[1][1], tgt[1][1]],
					[-src[2][0], -src[2][1], -1, 0, 0, 0, src[2][0] * tgt[2][0], src[2][1] * tgt[2][0], tgt[2][0]],
					[0, 0, 0, -src[2][0], -src[2][1], -1, src[2][0] * tgt[2][1], src[2][1] * tgt[2][1], tgt[2][1]],
					[-src[3][0], -src[3][1], -1, 0, 0, 0, src[3][0] * tgt[3][0], src[3][1] * tgt[3][0], tgt[3][0]],
					[0, 0, 0, -src[3][0], -src[3][1], -1, src[3][0] * tgt[3][1], src[3][1] * tgt[3][1], tgt[3][1]],
				])
	U,S,V = np.linalg.svd(A, full_matrices=True)
	V = (copy.deepcopy(V))/(copy.deepcopy(V[8][8]))
	H = V[8,:].reshape(3, 3)
	return H

def calculate_projection_matrix(h_matrix,k_matrix):
    h1 = h_matrix[:,0]
    h2 = h_matrix[:,1]
    h3 = h_matrix[:,2]
    lamda = 2 / (np.linalg.norm(np.matmul(np.linalg.inv(k_matrix),h1)) + np.linalg.norm(np.matmul(np.linalg.inv(k_matrix),h2)))
    btilda = lamda * np.matmul(np.linalg.inv(k_matrix),h_matrix)

    d = np.linalg.det(btilda)
    if d > 0:
        b = btilda
    else:
        b = -1 * btilda
    row1 = b[:, 0]
    row2 = b[:, 1]
    row3 = np.cross(row1, row2)
    l = b[:, 2]
    R = np.column_stack((row1, row2, row3, l))
    P_matrix = np.matmul(k_matrix,R)
    return P_matrix

def tag_orientation(tag):
	orientation = None
	if(tag[2][2] == 0 and tag[5][2] == 0 and tag[5][5] == 1 and tag[2][5] == 0):
		orientation = 0
	elif(tag[2][2] == 0 and tag[5][2] == 1 and tag[5][5] == 0 and tag[2][5] == 0):
		orientation = 90
	elif(tag[2][2] == 1 and tag[5][2] == 0 and tag[5][5] == 0 and tag[2][5] == 0):
		orientation = 180
	elif(tag[2][2] == 0 and tag[5][2] == 0 and tag[5][5] == 0 and tag[2][5] == 1):
		orientation = -90
	# print(orientation)
	return orientation

def get_all_contours():
	ret, frame = vid.read()
	tagCnt = None
	if frame is not None and len(frame) != 0:
		gblur = cv.GaussianBlur(frame, (7,7), 0)
		gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
		ret2, threshold = cv.threshold(gray, 180, 255, cv.THRESH_BINARY)
		contours, hierarchy = cv.findContours(threshold, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
		# contours = sorted(contours, key = cv.contourArea, reverse = True)[1:]
		tagCnt = []
		for h, cnt in zip(hierarchy[0], contours):
			perimeter = cv.arcLength(cnt, True)
			cnt = cv.approxPolyDP(cnt, 0.04*perimeter, True)
			if cv.isContourConvex(cnt) and len(cnt) == 4 and cv.contourArea(cnt) > 1000 and cv.contourArea(cnt) < 10500:
				cnt = cnt.reshape(-1, 2)
				if h[0] == -1 and h[1] == -1 and h[3] != -1:
					tagCnt.append(cnt)
		return tagCnt, frame

def find_tag_id(frame):
	new_ref = []
	frame_h, frame_w, l = frame.shape
	segment_h = int(frame_h/8)
	segment_w = int(frame_w/8)
	black_count = 0
	white_count = 0
	gray_frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
	count = 0
	for itemx in range(0, frame_h, segment_h):
		for itemy in range(0, frame_w, segment_w):
			black_count = 0
			white_count = 0
			for pixx in range(0, segment_h):
				for pixy in range(0, segment_w):
					if frame[itemx + pixx][itemy + pixy].all() == np.all([255,255,255]):
						white_count += 1
					else:
						black_count += 1
			count += 1

			if(white_count > black_count):
				new_ref.append(1)
			else:
				new_ref.append(0)

	new_arr = np.reshape(new_ref, (8, 8))
	print(new_arr)
	orientation = tag_orientation(new_arr)

	if orientation == 0:
		tag_id = new_arr[3][3] * 0 + new_arr[4][3] * 2 + new_arr[4][4] * 4 + new_arr[3][4] * 8
	elif orientation == 90:
		tag_id = new_arr[3][4] * 0 + new_arr[3][3] * 2 + new_arr[4][3] * 4 + new_arr[4][4] * 8
	elif orientation == 180:
		tag_id = new_arr[4][4] * 0 + new_arr[3][4] * 2 + new_arr[3][3] * 4 + new_arr[4][3] * 8
	elif orientation == -90:
		tag_id = new_arr[4][3] * 0 + new_arr[4][4] * 2 + new_arr[3][4] * 4 + new_arr[3][3] * 8
	else:
		tag_id = None
		orientation = None
	# print(tag_id,orientation)

	return orientation, tag_id

def warp_inv(h_matrix, contour, source, copy):
	coordinates = np.indices((copy.shape[1], copy.shape[0]))
	coordinates = coordinates.reshape(2, -1)
	coordinates = np.vstack((coordinates, np.ones(coordinates.shape[1])))
	temp_x, temp_y = coordinates[0], coordinates[1]

	warp_coordinates = (h_matrix@coordinates)

	x1, y1 ,z = warp_coordinates[0, :]/warp_coordinates[2, :], warp_coordinates[1, :]/warp_coordinates[2, :], warp_coordinates[2, :]/warp_coordinates[2, :]
	temp_x, temp_y = temp_x.astype(int), temp_y.astype(int)
	x1, y1 = x1.astype(int), y1.astype(int)
	if x1.all() >= 0 and x1.all() < 1920 and y1.all() >= 0 and y1.all() < 1080:
		copy[temp_y, temp_x] = source[y1,x1]
	return copy

def warp(h_matrix, contour, source, copy):
	coordinates = np.indices((copy.shape[1], copy.shape[0]))
	coordinates = coordinates.reshape(2, -1)
	coordinates = np.vstack((coordinates, np.ones(coordinates.shape[1])))
	temp_x, temp_y = coordinates[0], coordinates[1]

	warp_coordinates = (h_matrix@coordinates)
	x1, y1 ,z= warp_coordinates[0, :]/warp_coordinates[2, :], warp_coordinates[1, :]/warp_coordinates[2, :], warp_coordinates[2, :]/warp_coordinates[2, :]
	temp_x, temp_y = temp_x.astype(int),temp_y.astype(int)
	x1, y1 = x1.astype(int), y1.astype(int)
	if x1.all() >= 0 and x1.all() < 1920 and y1.all() >= 0 and y1.all() < 1080:
		source[y1,x1] = copy[temp_y, temp_x]
	return source

def tag_detection_1(contours, target, frame):
	dest = target
	source = np.float32([[contours[0][0],contours[0][1]],[contours[1][0],contours[1][1]],
                [contours[2][0],contours[2][1]],[contours[3][0],contours[3][1]]])

	h_matrix = homography_estimation(source, dest)

	frame_copy = np.zeros((200, 200, 3), np.uint8)
	warped_frame_1 = warp_inv(h_matrix, contours, frame, frame_copy)

	_,warped_threshold_1= cv.threshold(warped_frame_1, 200, 255, cv.THRESH_BINARY)
	tag_orientation_1, tag_id_1 = find_tag_id(warped_threshold_1)

	print("Tag Orientation 1: ", tag_orientation_1)
	print("Tag ID 1: ", tag_id_1)
	cv.imshow("Tag 1", warped_frame_1)
	font = cv.FONT_HERSHEY_SIMPLEX
	x = contours[0][0]
	y = contours[0][1] - 100
	str_text = "ID: " + str(tag_id_1) + " Orientation: " + str(tag_orientation_1)
	cv.putText(frame, str_text, (x, y), font, 0.8, (0, 0, 255), 2, cv.LINE_AA)

def tag_detection_2(contours, target, frame):
	dest = target

	source = np.float32([[contours[0][0],contours[0][1]],[contours[1][0],contours[1][1]],
                [contours[2][0],contours[2][1]],[contours[3][0],contours[3][1]]])

	h_matrix = homography_estimation(source, dest)

	frame_copy = np.zeros((200, 200, 3), np.uint8)
	warped_frame_2 = warp_inv(h_matrix, contours, frame, frame_copy)
	_,warped_threshold_2 = cv.threshold(warped_frame_2, 200, 255, cv.THRESH_BINARY)
	tag_orientation_2, tag_id_2 = find_tag_id(warped_threshold_2)

	print("Tag Orientation 2: ", tag_orientation_2)
	print("Tag ID 2: ", tag_id_2)
	cv.imshow("Tag 2", warped_frame_2)
	font = cv.FONT_HERSHEY_SIMPLEX
	x = contours[0][0]
	y = contours[0][1] - 100
	str_text = "ID: " + str(tag_id_2) + " Orientation: " + str(tag_orientation_2)
	cv.putText(frame, str_text, (x, y), font, 0.8, (0, 0, 255), 2, cv.LINE_AA)

def tag_detection_3(contours, target, frame):
	dest = target

	source = np.float32([[contours[0][0],contours[0][1]],[contours[1][0],contours[1][1]],
                [contours[2][0],contours[2][1]],[contours[3][0],contours[3][1]]])

	h_matrix = homography_estimation(source, dest)

	frame_copy = np.zeros((200, 200, 3), np.uint8)
	warped_frame_3 = warp_inv(h_matrix, contours, frame, frame_copy)
	_,warped_threshold_3= cv.threshold(warped_frame_3, 200, 255, cv.THRESH_BINARY)
	tag_orientation_3, tag_id_3 = find_tag_id(warped_threshold_3)

	print("Tag Orientation 3: ", tag_orientation_3)
	print("Tag ID 3: ", tag_id_3)
	cv.imshow("Tag 3",warped_frame_3)
	font = cv.FONT_HERSHEY_SIMPLEX
	x = contours[0][0]
	y = contours[0][1] - 100
	str_text = "ID: " + str(tag_id_3) + " Orientation: " + str(tag_orientation_3)
	cv.putText(frame, str_text, (x, y), font, 0.8, (0, 0, 255), 2, cv.LINE_AA)

def lena_transform_1(var, contours, target, frame):
	po = var
	if frame is not None:
		source = np.float32([[contours[0][0],contours[0][1]],[contours[1][0],contours[1][1]], [contours[2][0],contours[2][1]],[contours[3][0],contours[3][1]]])
		reference_corners = np.float32([[0,0],[200,0],[200,200],[0,200]])

		h_matrix = homography_estimation(source, reference_corners)
		h_matrix_lena = homography_estimation(source, target)
		lena = read_lena()
		frame_copy = np.zeros((200,200,3), np.uint8)

		warped_frame_inv = warp_inv(h_matrix,contours,frame,frame_copy)
		_, warped_threshold = cv.threshold(warped_frame_inv, 180, 255, cv.THRESH_BINARY)

		orientation, tag_id = find_tag_id(warped_threshold)
		if orientation==None:
			if po==0:
				Lena=warp(h_matrix_lena,contours,frame,lena)
			elif po==90:
				Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena, cv.ROTATE_90_CLOCKWISE))
			elif po==180:
				Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena, cv.ROTATE_180))
			elif po==-90:
				Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena,cv.ROTATE_90_COUNTERCLOCKWISE))

		if orientation==0:
			Lena=warp(h_matrix_lena,contours,frame,lena)
		elif orientation==90:
			Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena, cv.ROTATE_90_CLOCKWISE))
		elif orientation==180:
			Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena, cv.ROTATE_180))
		elif orientation==-90:
			Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena,cv.ROTATE_90_COUNTERCLOCKWISE))
		if orientation!=None:
			po=orientation

	return po

def lena_transform_2(var, contours, target, frame):
	po = var
	if frame is not None:
		source = np.float32([[contours[0][0],contours[0][1]],[contours[1][0],contours[1][1]], [contours[2][0],contours[2][1]],[contours[3][0],contours[3][1]]])
		reference_corners = np.float32([[0,0],[200,0],[200,200],[0,200]])

		h_matrix = homography_estimation(source, reference_corners)
		h_matrix_lena = homography_estimation(source, target)
		lena = read_lena()
		frame_copy = np.zeros((200,200,3), np.uint8)

		warped_frame_inv = warp_inv(h_matrix,contours,frame,frame_copy)
		_, warped_threshold = cv.threshold(warped_frame_inv, 180, 255, cv.THRESH_BINARY)

		orientation, tag_id = find_tag_id(warped_threshold)
		if orientation==None:
			if po==0:
				Lena=warp(h_matrix_lena,contours,frame,lena)
			elif po==90:
				Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena, cv.ROTATE_90_CLOCKWISE))
			elif po==180:
				Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena, cv.ROTATE_180))
			elif po==-90:
				Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena,cv.ROTATE_90_COUNTERCLOCKWISE))

		if orientation==0:
			Lena=warp(h_matrix_lena,contours,frame,lena)
		elif orientation==90:
			Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena, cv.ROTATE_90_CLOCKWISE))
		elif orientation==180:
			Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena, cv.ROTATE_180))
		elif orientation==-90:
			Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena,cv.ROTATE_90_COUNTERCLOCKWISE))
		if orientation!=None:
			po=orientation

	return po

def lena_transform_3(var, contours, target, frame):
	po = var
	if frame is not None:
		source = np.float32([[contours[0][0],contours[0][1]],[contours[1][0],contours[1][1]], [contours[2][0],contours[2][1]],[contours[3][0],contours[3][1]]])
		reference_corners = np.float32([[0,0],[200,0],[200,200],[0,200]])

		h_matrix = homography_estimation(source, reference_corners)
		h_matrix_lena = homography_estimation(source, target)
		lena = read_lena()
		frame_copy = np.zeros((200,200,3), np.uint8)

		warped_frame_inv = warp_inv(h_matrix,contours,frame,frame_copy)
		_, warped_threshold = cv.threshold(warped_frame_inv, 180, 255, cv.THRESH_BINARY)

		orientation, tag_id = find_tag_id(warped_threshold)
		if orientation==None:
			if po==0:
				Lena=warp(h_matrix_lena,contours,frame,lena)
			elif po==90:
				Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena, cv.ROTATE_90_CLOCKWISE))
			elif po==180:
				Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena, cv.ROTATE_180))
			elif po==-90:
				Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena,cv.ROTATE_90_COUNTERCLOCKWISE))

		if orientation==0:
			Lena=warp(h_matrix_lena,contours,frame,lena)
		elif orientation==90:
			Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena, cv.ROTATE_90_CLOCKWISE))
		elif orientation==180:
			Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena, cv.ROTATE_180))
		elif orientation==-90:
			Lena=warp(h_matrix_lena,contours,frame,cv.rotate(lena,cv.ROTATE_90_COUNTERCLOCKWISE))
		if orientation!=None:
			po=orientation

	return po

def draw_cube_multi(contours, frame):
    if contours is not None:
        target = np.array([[0,0], [0,79], [79,79], [79,0]])
        print(str([[contours[0][0][0],contours[0][0][1]], [contours[0][1][0],contours[0][1][1]], [contours[0][2][0],contours[0][2][1]], [contours[0][3][0],contours[0][3][1]]]))
        if (len(contours) == 3):
        	contours_1 = np.float32([[contours[0][0][0],contours[0][0][1]], [contours[0][1][0],contours[0][1][1]], [contours[0][2][0],contours[0][2][1]], [contours[0][3][0],contours[0][3][1]]])
        	contours_2 = np.float32([[contours[1][0][0],contours[1][0][1]], [contours[1][1][0],contours[1][1][1]], [contours[1][2][0],contours[1][2][1]], [contours[1][3][0],contours[1][3][1]]])
        	contours_3 = np.float32([[contours[2][0][0],contours[2][0][1]], [contours[2][1][0],contours[2][1][1]], [contours[2][2][0],contours[2][2][1]], [contours[2][3][0],contours[2][3][1]]])

        	h_matrix_1 = homography_estimation_cube(target, contours_1)
          	projection_matrix_1 = calculate_projection_matrix(h_matrix_1, K)
            h_matrix_2 = homography_estimation_cube(target, contours_2)
            projection_matrix_2 = calculate_projection_matrix(h_matrix_2, K)
            h_matrix_3 = homography_estimation_cube(target, contours_3)
            projection_matrix_3 = calculate_projection_matrix(h_matrix_3, K)

        	x01,y01,z01 = np.matmul(projection_matrix_1,[0,0,0,1])
        	x02,y02,z02 = np.matmul(projection_matrix_1,[79,0,0,1])
        	x03,y03,z03 = np.matmul(projection_matrix_1,[79,79,0,1])
        	x04,y04,z04 = np.matmul(projection_matrix_1,[0,79,0,1])
        	x05,y05,z05 = np.matmul(projection_matrix_1,[0,0,-79,1])
        	x06,y06,z06 = np.matmul(projection_matrix_1,[79,0,-79,1])
        	x07,y07,z07 = np.matmul(projection_matrix_1,[79,79,-79,1])
        	x08,y08,z08 = np.matmul(projection_matrix_1,[0,79,-79,1])

        	x11,y11,z11 = np.matmul(projection_matrix_2,[0,0,0,1])
        	x12,y12,z12 = np.matmul(projection_matrix_2,[79,0,0,1])
        	x13,y13,z13 = np.matmul(projection_matrix_2,[79,79,0,1])
        	x14,y14,z14 = np.matmul(projection_matrix_2,[0,79,0,1])
        	x15,y15,z15 = np.matmul(projection_matrix_2,[0,0,-79,1])
        	x16,y16,z16 = np.matmul(projection_matrix_2,[79,0,-79,1])
        	x17,y17,z17 = np.matmul(projection_matrix_2,[79,79,-79,1])
        	x18,y18,z18 = np.matmul(projection_matrix_2,[0,79,-79,1])

        	x21,y21,z21 = np.matmul(projection_matrix_3,[0,0,0,1])
        	x22,y22,z22 = np.matmul(projection_matrix_3,[79,0,0,1])
        	x23,y23,z23 = np.matmul(projection_matrix_3,[79,79,0,1])
        	x24,y24,z24 = np.matmul(projection_matrix_3,[0,79,0,1])
        	x25,y25,z25 = np.matmul(projection_matrix_3,[0,0,-79,1])
        	x26,y26,z26 = np.matmul(projection_matrix_3,[79,0,-79,1])
        	x27,y27,z27 = np.matmul(projection_matrix_3,[79,79,-79,1])
        	x28,y28,z28 = np.matmul(projection_matrix_3,[0,79,-79,1])

        	cv.line(frame,(int(x01/z01), int(y01/z01)), (int(x02/z02), int(y02/z02)), (0, 0, 255), 6)
        	cv.line(frame,(int(x02/z02), int(y02/z02)), (int(x03/z03), int(y03/z03)), (0, 0, 255), 6)
        	cv.line(frame,(int(x03/z03), int(y03/z03)), (int(x04/z04), int(y04/z04)), (0, 0, 255), 6)
        	cv.line(frame,(int(x04/z04), int(y04/z04)), (int(x01/z01), int(y01/z01)), (0, 0, 255), 6)
        	cv.line(frame,(int(x01/z01), int(y01/z01)), (int(x05/z05), int(y05/z05)), (0, 0, 255), 6)
        	cv.line(frame,(int(x02/z02), int(y02/z02)), (int(x06/z06), int(y06/z06)), (0, 0, 255), 6)
        	cv.line(frame,(int(x03/z03), int(y03/z03)), (int(x07/z07), int(y07/z07)), (0, 0, 255), 6)
        	cv.line(frame,(int(x04/z04), int(y04/z04)), (int(x08/z08), int(y08/z08)), (0, 0, 255), 6)
        	cv.line(frame,(int(x05/z05), int(y05/z05)), (int(x06/z06), int(y06/z06)), (0, 0, 255), 6)
        	cv.line(frame,(int(x06/z06), int(y06/z06)), (int(x07/z07), int(y07/z07)), (0, 0, 255), 6)
        	cv.line(frame,(int(x07/z07), int(y07/z07)), (int(x08/z08), int(y08/z08)), (0, 0, 255), 6)
        	cv.line(frame,(int(x08/z08), int(y08/z08)), (int(x05/z05), int(y05/z05)), (0, 0, 255), 6)

        	cv.line(frame,(int(x11/z11), int(y11/z11)), (int(x12/z12), int(y12/z12)), (0, 0, 255), 6)
        	cv.line(frame,(int(x12/z12), int(y12/z12)), (int(x13/z13), int(y13/z13)), (0, 0, 255), 6)
        	cv.line(frame,(int(x13/z13), int(y13/z13)), (int(x14/z14), int(y14/z14)), (0, 0, 255), 6)
        	cv.line(frame,(int(x14/z14), int(y14/z14)), (int(x11/z11), int(y11/z11)), (0, 0, 255), 6)
        	cv.line(frame,(int(x11/z11), int(y11/z11)), (int(x15/z15), int(y15/z15)), (0, 0, 255), 6)
        	cv.line(frame,(int(x12/z12), int(y12/z12)), (int(x16/z16), int(y16/z16)), (0, 0, 255), 6)
        	cv.line(frame,(int(x13/z13), int(y13/z13)), (int(x17/z17), int(y17/z17)), (0, 0, 255), 6)
        	cv.line(frame,(int(x14/z14), int(y14/z14)), (int(x18/z18), int(y18/z18)), (0, 0, 255), 6)
        	cv.line(frame,(int(x15/z15), int(y15/z15)), (int(x16/z16), int(y16/z16)), (0, 0, 255), 6)
        	cv.line(frame,(int(x16/z16), int(y16/z16)), (int(x17/z17), int(y17/z17)), (0, 0, 255), 6)
        	cv.line(frame,(int(x17/z17), int(y17/z17)), (int(x18/z18), int(y18/z18)), (0, 0, 255), 6)
        	cv.line(frame,(int(x18/z18), int(y18/z18)), (int(x15/z15), int(y15/z15)), (0, 0, 255), 6)

        	cv.line(frame,(int(x21/z21), int(y21/z21)), (int(x22/z22), int(y22/z22)), (0, 0, 255), 6)
        	cv.line(frame,(int(x22/z22), int(y22/z22)), (int(x23/z23), int(y23/z23)), (0, 0, 255), 6)
        	cv.line(frame,(int(x23/z23), int(y23/z23)), (int(x24/z24), int(y24/z24)), (0, 0, 255), 6)
        	cv.line(frame,(int(x24/z24), int(y24/z24)), (int(x21/z21), int(y21/z21)), (0, 0, 255), 6)
        	cv.line(frame,(int(x21/z21), int(y21/z21)), (int(x25/z25), int(y25/z25)), (0, 0, 255), 6)
        	cv.line(frame,(int(x22/z22), int(y22/z22)), (int(x26/z26), int(y26/z26)), (0, 0, 255), 6)
        	cv.line(frame,(int(x23/z23), int(y23/z23)), (int(x27/z27), int(y27/z27)), (0, 0, 255), 6)
        	cv.line(frame,(int(x24/z24), int(y24/z24)), (int(x28/z28), int(y28/z28)), (0, 0, 255), 6)
        	cv.line(frame,(int(x25/z25), int(y25/z25)), (int(x26/z26), int(y26/z26)), (0, 0, 255), 6)
        	cv.line(frame,(int(x26/z26), int(y26/z26)), (int(x27/z27), int(y27/z27)), (0, 0, 255), 6)
        	cv.line(frame,(int(x27/z27), int(y27/z27)), (int(x28/z28), int(y28/z28)), (0, 0, 255), 6)
        	cv.line(frame,(int(x28/z28), int(y28/z28)), (int(x25/z25), int(y25/z25)), (0, 0, 255), 6)

        	cv.imshow("cubeline", frame)
        	return frame

def main():
	frame_count = 0
	lena = read_lena()
	lena_shape = lena.shape
	lena_before = np.float32([[0,0],[512,0],[512,512],[0,512]])

	reference = read_marker()
	reference_h, reference_w, l = reference.shape

	reference_corners = np.float32([[0,0],[200,0],[200,200],[0,200]])
	po1 = 0
	po2 = 0
	po3 = 0
	if func == "1":
		print("Detecting AR Tag and finding its ID-")
		while(vid.isOpened()):
			contours, frame=get_all_contours()
			if contours is not None:
				if len(contours) == 3:
					tag_detection_1(contours[0], reference_corners, frame)
					tag_detection_2(contours[1], reference_corners, frame)
					tag_detection_3(contours[2], reference_corners, frame)
			cv.imshow("Video", frame)
			if val == "1":
				out.write(frame)
			key = cv.waitKey(1)
			if key == 27:
				break
	elif func == "2":
		count = 0
		print("Superimposing Lena")
		while(vid.isOpened()):
			contours, frame = get_all_contours()
			if contours is not None:
				if len(contours) == 3:
					po1 = lena_transform_1(po1, contours[0], lena_before, frame)
					po2 = lena_transform_2(po2, contours[1], lena_before, frame)
					po3 = lena_transform_3(po3, contours[2], lena_before, frame)
			cv.imshow("Video", frame)
			if val == "1":
				out.write(frame)
			key = cv.waitKey(1)
			if key == 27:
				break
	elif func == "3":
		print("Tracking AR tag and drawing Virtual Cube")
		while(vid.isOpened()):
			contours, frame = get_all_contours()
			if contours is not None:
				cube_frames = draw_cube_multi(contours, frame)
				if val == "1":
					out.write(cube_frames)
			key = cv.waitKey(1)
			if key == 27:
				break
	else:
		print("Please Try Again with either 1 or 2 or 3")
		main()

	vid.release()
	if val == "1":
		out.release()
	cv.destroyAllWindows()

main()


text:
import numpy as np
import os
ModulePath = os.path.dirname(__file__) + '/'


text:
import random
import numpy as np

class ArrayBuilder(object):
    """
    Array generation tool.
    """

    @staticmethod
    def gen_new_array(from_array):
        """
        Generate a new array when there is a value greater than 1 or less than -1.
        :param from_array: An array containing elements greater than 1 or less than -1.
        :return: Return an array between -1 and 1.
        """
        if isinstance(from_array, list) or isinstance(from_array, np.ndarray):
            total = np.sum(from_array)
            m = 10000
            numbers = np.random.randn(len(from_array))
            max_value = max(np.max(numbers), abs(np.min(numbers)))
            numbers = numbers / (max_value + 0.0001)
            summation = sum(numbers)
            k = m / summation
            new_array = [i * k / (1 / total * m) for i in numbers]
            if abs(np.max(new_array)) >= 1.0 or abs(np.min(new_array)) >= 1.0:
                new_array = ArrayBuilder.gen_new_array([x / -2 for x in new_array])
            return new_array
        else:
            return None

    @staticmethod
    def random_array(size, must_over_zero=False):
        """
        Random an initial array.
        :param size: array size.
        :param must_over_zero: must number over zero.
        :return: Return an array between -1 and 1.
        """
        if isinstance(size, int) and size > 0:
            if must_over_zero:
                return [random.uniform(0.0, 0.999) for _ in range(size)]
            return [random.uniform(-0.999, 0.999) for _ in range(size)]
        return None

max_stars_repo_name: Joe-Laue/bread-tools

max_issues_repo_name: Joe-Laue/bread-tools

max_forks_repo_name: Joe-Laue/bread-tools


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

os.system("g++ caminata.cpp -o archivo")
os.system("./archivo > datos.dat")

datos= np.loadtxt("datos.dat")
x=datos[:,0]
y=datos[:,1]

plt.figure()
plt.grid()
plt.plot(x,y)
plt.savefig("21.png")


text:
import fjaccard
import numpy as np
import pandas as pd

data = pd.DataFrame({
    'user': [1, 1, 1, 1, 2, 2, 2, 0],
    'item': [1, 2, 3, 4, 3, 4, 5, 3]
})
distance_query = fjaccard.FJaccard(data.user.values, data.item.values)
print(distance_query.query(1, 2))
print(distance_query.query(1, 3))
print(distance_query.query_square(np.array([1, 2, 3])))
print(distance_query.query_pairs(np.array([0, 1, 3]), np.array([0, 1, 2, 3, 4, 5])))

max_stars_repo_name: proto-n/fjaccard-py

max_issues_repo_name: proto-n/fjaccard-py

max_forks_repo_name: proto-n/fjaccard-py


text:
import pandas as pd
import pickle
import numpy as np
import torch
from sklearn.model_selection import train_test_split

PATH_TO_DATA = '/scratch/speech/datasets/IEMOCAP.pkl'

ENCODING = {
    'fru': torch.tensor([1]),
}

if __name__=='__main__':
    with open(PATH_TO_DATA, 'rb') as f:
        data = pickle.load(f)
    df = pd.DataFrame(list(zip(data['filename'],data['text'],data['label'])),columns=['files','text','label'])
    df = df[df['label'].isin(ENCODING.keys())]
    file_train, file_val, text_train, text_val, label_train, label_val = train_test_split(df['files'], df['text'], df['label'], test_size=0.2, random_state=1234)
    file_train = [x for x in file_train]
    file_val = [x for x in file_val]
    text_train = [x for x in text_train]
    text_val = [x for x in text_val]
    label_train = [ENCODING[x] for x in label_train]
    label_val = [ENCODING[x] for x in label_val]
    train = {
        'filename': file_train,
        'text': text_train,
        'label': label_train
    }

    with open('/scratch/speech/datasets/IEMOCAP_fru_train.pkl','wb') as f:
        pickle.dump(train,f)

    val = {
        'filename': file_val,
        'text': text_val,
        'label': label_val
    }

    with open('/scratch/speech/datasets/IEMOCAP_fru_val.pkl','wb') as f:
        pickle.dump(val,f)


text:
"""
This script includes all the functions to transform picture or 3d matrices
"""
from .vtk_points_loader import VtkPointLoader
import numpy

TOTAL_NUM_OF_PICS = 65
TOTAL_NUM_OF_PIXELS = 31200000

def add_vtk_points_from_plane_list(pic_set: list, trans_set: list, same_shape=True, scale_factor=(1.0, 1.0)):
    """
    Adds atk points from set of planes and its transformation matrix set
    @param pic_set: <list> plane set
    @param trans_set: <list> transformation matrix set
    @param same_shape: <bool> whether pictures are in same shape
    @param scale_factor: <Tuple> scale factor for scaling the matrix
    @return: <VtkPointLoad> Point load, a vtk object
    """
    vtk_point_loader = VtkPointLoader()
    # get first flatten matrix
    flattened_matrix = get_plane_matrix_flatten(pic_set[0])
    # create scaling matrix
    scale_matrix = _create_scale_matrix(scale_factor)
    # put planes into the vtk object
    print('Creating data...')
    loop, volume_list, colors_list = 0, [], []
    for pic, trans in zip(pic_set, trans_set):
        plane_matrix = flattened_matrix if same_shape is True else get_plane_matrix_flatten(pic)
        colors = pic.reshape([int(pic.size/3), 3]).tolist()
        volume = numpy.dot(plane_matrix, trans.transpose()).dot(scale_matrix) * -1
        volume = numpy.delete(volume, 3, 1).tolist()
        volume_list = volume_list + volume
        colors_list = colors_list + colors
        loop += 1
        _print_progress_bar(loop, len(trans_set))

    # set colors to grayscale
    print('-Done Creating data')
    print('changing colors to grayscale...')
    for i in range(len(colors_list)):
        colors_list[i] = 0.2989 * colors_list[i][0] + 0.5870 * colors_list[i][1] + 0.1140 * colors_list[i][2]
    print('-Done changing colors to grayscale')
    vtk_point_loader.add_points_from_list(volume_list, colors_list)

    vtk_point_loader.summarize()

    return vtk_point_loader

def get_plane_matrix_flatten(plane):
    """
    Gets a matrix in the form of
    | X0 Y0 0 1 X0 Y1 0 1 ... ... ... ... Xi Yi 0 1 |
    @param plane: plane
    @return: <numpy.array> Matrix
    """
    trans_list = []
    for y in range(plane.shape[0]):
        for x in range(plane.shape[1]):
            trans_list.append(numpy.array([x, y, 0, 1]))
    return numpy.array(trans_list)

def plane_pt_to_3d_point(pos, trans_matrix):
    """
    Transform plane point position eg. P(x, y, 0, 1) to 3d point eg. P'(X, Y, Z, 1)
    @param pos: <array_like> position
    @param trans_matrix: <numpy.array> transformation matrix
    @return: <Tuple> 3d position
    """
    orig_matrix = numpy.array(pos, ndmin=2)
    return numpy.dot(orig_matrix, trans_matrix.transpose())

def plane_set_to_3d(pic_set: list, trans_set: list, same_shape=True, scale_factor=(1.0, 1.0)):
    """
    Transform plane set to 3d graph and put it to the space matrix by transformation matrices
    Number of transformation matrices is same with number of planes
    @param pic_set: set of picture planes
    @param trans_set: set of transformation matrices
    @param same_shape: if the planes has same shape
    @param scale_factor: <Tuple> scale factor for scaling the matrix
    @return:
    """
    # get first flatten matrix
    flattened_matrix = get_plane_matrix_flatten(pic_set[0])
    volume_list, colors_list = [], []
    # create scaling matrix
    scale_matrix = _create_scale_matrix(scale_factor)
    # put coordinates and colors into lists
    print('building list...\n')
    for pic, trans in zip(pic_set, trans_set):
        plane_matrix = flattened_matrix if same_shape is True else get_plane_matrix_flatten(pic)
        colors = pic.reshape([int(pic.size/3), 3]).tolist()
        volume = numpy.dot(plane_matrix, trans.transpose()).dot(scale_matrix) * -1
        volume = numpy.delete(volume, 3, 1).tolist()
        volume_list = volume_list + volume
        colors_list = colors_list + colors
    print('-Done building list\n')

    print('building space...\n')
    space, min_x, min_y, min_z = _build_space(volume_list)
    print('-Done building space\n')
    print('inserting colors\n')
    for volume, colors in zip(volume_list, colors_list):
        # normalize coordinates
        x = volume[0] + min_x * -1
        y = volume[1] + min_y * -1
        z = volume[2] + min_z * -1
        # change colors to grayscale
        gray_scale_color = 0.2989 * colors[0] + 0.5870 * colors[1] + 0.1140 * colors[2]
        space[int(y), int(x), int(z)] = gray_scale_color
    print('-Done inserting colors\n')
    return space

def _build_space(coordinate_set):
    """
    Builds an empty space to place planes
    @param coordinate_set: set of planes
    @return: <numpy.array> empty space
    """
    coordinate_set_lists = numpy.array(coordinate_set).transpose().tolist()
    max_x, max_y, max_z = max(coordinate_set_lists[0]), max(coordinate_set_lists[1]), max(coordinate_set_lists[2])
    min_x, min_y, min_z = min(coordinate_set_lists[0]), min(coordinate_set_lists[1]), min(coordinate_set_lists[2])

    y = int(max_y) + 2 if min_y >= 0 else int(max_y) + int(min_y) * -1 + 2
    x = int(max_x) + 2 if min_x >= 0 else int(max_x) + int(min_x) * -1 + 2
    z = int(max_z) + 2 if min_z >= 0 else int(max_z) + int(min_z) * -1 + 2
    space = numpy.zeros((y, x, z, 1), float)
    return space, min_x if min_x < 0 else 0, min_y if min_y < 0 else 0, min_z if min_z < 0 else 0

def _create_scale_matrix(scale_factors):
    """
    Creates scale matrix for scaling
    """
    return numpy.array([[scale_factors[0], 0, 0, 0],
                        [0, scale_factors[1], 0, 0],
                        [0, 0, 1, 0],
                        [0, 0, 0, 1]])

def _print_progress_bar(iteration, total, decimals=1, length=100, fill='█'):
    """
    Print progress bar for CLI
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    length = int(length * iteration // total)
    bar = fill * length
    print('\r|%s| %s%%' % (bar, percent), end='\r')
    if iteration == total:
        print()


text:
import numpy as np
import cv2
import carla

from lane_tracking.lane_track import lane_track_init

def process_img(image):
    i = np.array(image.raw_data)
    i2 = i.reshape((288, 768, 4))
    i3 = i2[:, :, :3]
    # image.save_to_disk('data/image_%s.png' % image.timestamp)
    return i3

def save_img(image, path='data/dgmd/image_%s.png'):
    image.save_to_disk(path % image.timestamp)

def process_seg(image):
    image.convert(carla.ColorConverter.CityScapesPalette)
    return process_img(image)

def fast_track_debug(mask):
    """
    lane color: red
    """
    rgb_mask = mask
    return rgb_mask

def debug_view(*sensors, text=[1.0]):
    """
    param: sensor data

    Steps: Add/Filter/Apply masks
    """
    # TODO: Add masks
    # rgb cam
    rgb_cam = process_img(sensors[0])
    # seg cam
    seg_cam = process_seg(sensors[1])

    debug_image = rgb_cam[:]

    # TODO: Filter masks
    # lane track condition
    if sensors[2].any():
        lane_cnd = sensors[2][:, :] < 0.1
        debug_image[lane_cnd, 2] = 255

    # add text
    debug_image = cv2.putText(np.array(debug_image), 'Road Status: '+str("Junction" if text[0] else "Lane"), (15, 15),
                              cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 255), 1)
    debug_image = cv2.putText(np.array(debug_image), 'Control Type: ' + str(text[1]), (15, 30),
                              cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 255), 1)
    debug_image = cv2.putText(np.array(debug_image), 'GPS Waypoint Distance: ' + str(text[2]), (15, 45),
                              cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 255), 1)
    debug_image = cv2.putText(np.array(debug_image), 'Waypoint ID: ' + str("Inactive" if not text[3] else text[3]), (15, 60),
                              cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 255), 1)
    debug_image = cv2.putText(np.array(debug_image), 'Car Chase: ' + str("Off" if not text[4] else "On"), (15, 75),
                              cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 255), 1)
    debug_image = cv2.putText(np.array(debug_image), 'Auto Pilot: ' + str("Off" if not text[5] else "On"), (15, 90),
                              cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 255), 1)

    #########################################################################
    cv2.imshow("debug view", debug_image)
    cv2.waitKey(1)

max_issues_repo_name: DevGlitch/delamain

max_forks_repo_name: DevGlitch/delamain


text:
#!/usr/bin/env python3
import base64
from cryptography.fernet import Fernet
import numpy as np
np.random.seed(0)

# Prime number
Q = 23

class Person():
    def __init__(self, name):
        self.name = name
        self.privKey = np.random.randint(low=0, high=Q)

    def getPubKey(self):
        return np.power(2, self.privKey) % Q

    def encrypt(self, message, recipientPubKey):
        sharedKeyDecimal = np.power(recipientPubKey, self.privKey) % Q
        sharedKeyBinary = bytes('{:032b}'.format(sharedKeyDecimal), encoding='utf8')
        fernetKey = Fernet(base64.urlsafe_b64encode(sharedKeyBinary))
        return fernetKey.encrypt(message)

    def decrypt(self, encryptedMessage, recipientPubKey):
        sharedKeyDecimal = np.power(recipientPubKey, self.privKey) % Q
        sharedKeyBinary = bytes('{:032b}'.format(sharedKeyDecimal), encoding='utf8')
        fernetKey = Fernet(base64.urlsafe_b64encode(sharedKeyBinary))
        return fernetKey.decrypt(encryptedMessage)

if __name__ == "__main__":
    # Construction.
    alice = Person("Alice")
    bob = Person("Bob")

    # Encryption
    encryptedMessage = alice.encrypt(b"Hi Bob, my credit card number is 1111 1111 1111 1111.", bob.getPubKey())
    print(encryptedMessage)

    # Decryption
    decryptedMessage = bob.decrypt(encryptedMessage, alice.getPubKey())
    print(decryptedMessage)


text:
import configparser
import os
import sys

import netCDF4 as nc
import numpy as np
from numpy import linalg as LA
import nrrd
from scipy.interpolate import RegularGridInterpolator

from readMRIData import get_rotation_matrix
from readMRIData import plot_lin_plane_fitting_with_bbox
from readMRIData import read_intra_op_points
from readMRIData import rotate_point_by_rotation_matrix

def read_nrrd_file(filepath):
    data, header = nrrd.read(filepath)

    return data, header

def save_as_netcdf(data, filename):
    print('Save data to {}.'.format(filename))
    nc_file = nc.Dataset(filename, 'w', format='NETCDF3_CLASSIC')
    nc_file.createDimension('nNodes_0', data.shape[0])
    nc_file.createDimension('nNodes_1', data.shape[1])
    nc_file.createDimension('nNodes_2', data.shape[2])
    nc_file.createDimension('time')
    brain = nc_file.createVariable('region', 'i2', ('time', 'nNodes_2',
                                                    'nNodes_1', 'nNodes_0'))
    brain[0,] = np.swapaxes(data, 0, 2)
    nc_file.close()

    print('Done.')

def data_as_binary_data(data):
    binary_data = np.where(data > 1.0, 1, 0)

    return binary_data

def get_ijk_to_lps(header):
    space_origin = return_string_list_as_float_numpy_array(header['space origin'])
    space_origin = np.append(space_origin, 1)

    row0 = return_string_list_as_float_numpy_array(header['space directions'][0])
    row0 = np.append(row0, 0)
    row1 = return_string_list_as_float_numpy_array(header['space directions'][1])
    row1 = np.append(row1, 0)
    row2 = return_string_list_as_float_numpy_array(header['space directions'][2])
    row2 = np.append(row2, 0)
    ijk_to_lps = np.array([row0, row1, row2, space_origin]).T

    return ijk_to_lps

def ijk_to_lps(ijk, header):
    if len(ijk) == 3:
        ijk = np.append(ijk, 1)

    ijk_to_lps = get_ijk_to_lps(header)

    lps = np.dot(ijk_to_lps, ijk)

    return lps[0:3]

def ijk_to_ras(ijk, header):
    if len(ijk) == 3:
        ijk = np.append(ijk, 1)

    ijk_to_lps = get_ijk_to_lps(header)
    lps_to_ras = np.diag([-1, -1, 1, 1])

    lps = np.dot(ijk_to_lps, ijk)
    ras = np.matmul(lps, lps_to_ras)

    return ras[0:3]

def lps_to_ijk(lps, header):
    if len(lps) == 3:
        lps = np.append(lps, 1)

    ijk_to_lps = get_ijk_to_lps(header)
    lps_to_ijk = LA.inv(ijk_to_lps)

    ijk = np.dot(lps_to_ijk, lps)

    return ijk[0:3]

def ras_to_ijk(ras, header):
    if len(ras) == 3:
        ras = np.append(ras, 1)

    ijk_to_lps = get_ijk_to_lps(header)
    lps_to_ijk = LA.inv(ijk_to_lps)
    ras_to_lps = np.diag([-1, -1, 1, 1])

    lps = np.matmul(ras, ras_to_lps)
    ijk = np.dot(lps_to_ijk, lps)

    return ijk[0:3]

def switch_space(point):
    if len(point) == 3:
        point = np.append(point, 1)

    switch_mat = np.diag([-1, -1, 1, 1])

    switched_point = np.matmul(point, switch_mat)

    return switched_point[0:3]

def get_regular_grid_interpolator(data):
    x = np.linspace(0, data.shape[0]-1, data.shape[0])
    y = np.linspace(0, data.shape[1]-1, data.shape[1])
    z = np.linspace(0, data.shape[2]-1, data.shape[2])

    reg_grid_interpolator = RegularGridInterpolator((x, y, z), data,
                                                    method='linear',
                                                    bounds_error=False,
                                                    fill_value=0)

    return reg_grid_interpolator

def read_default_ini_file(params):

    config = configparser.ConfigParser()
    config.optionxform = str

    if os.path.isfile('Parameters.ini') == True:
        config.read('Parameters.ini')
    else:
        print('Parameters.ini does not exist.')
        print('Aborting.')
        exit()

    COORD_NODE_FIRST = config['Geometry'].get('COORD_NODE_FIRST')
    COORD_NODE_FIRST = list(map(float, COORD_NODE_FIRST.split('x')))
    params['COORD_NODE_FIRST'] = COORD_NODE_FIRST

    COORD_NODE_LAST = config['Geometry'].get('COORD_NODE_LAST')
    COORD_NODE_LAST = list(map(float, COORD_NODE_LAST.split('x')))
    params['COORD_NODE_LAST'] = COORD_NODE_LAST

    N_NODES = config['Geometry'].get('N_NODES')
    params['N_NODES_ENV'] = N_NODES
    N_NODES = list(map(int, N_NODES.split('x')))
    params['N_NODES'] = N_NODES

    return params

def write_ini_file(params):
    case = params['CASE']
    n_nodes = params['N_NODES_ENV']
    filename = case + '_' + n_nodes + '.ini'
    print('Write {}.'.format(filename))

    folderpath = params['FOLDERPATH']
    start = params['START']
    end = params['END']

    start_as_string = str(start[0]/1000) + 'x' + str(start[1]/1000) + 'x' \
                      + str(start[2]/1000)
    end_as_string = str(end[0]/1000) + 'x' + str(end[1]/1000) + 'x' \
                    + str(end[2]/1000)

    config = configparser.ConfigParser()
    config.optionxform = str

    if os.path.isfile('Parameters.ini') == True:
        config.read('Parameters.ini')
    else:
        print('Parameters.ini does not exist.')
        print('Aborting.')
        exit()

    config['MRI']['CASE'] = case
    config['Input']['NAME_REGION_FILE'] = os.path.join(folderpath,
                                                       'region_' + n_nodes)
    config['Input']['NAME_VESSELS_FILE'] = os.path.join(folderpath,
                                                        'vessels_' + n_nodes)
    config['Input']['NAME_INITFILE'] = os.path.join(folderpath,
                                                    'init_' + n_nodes)
    config['Input']['USE_MRI_FILE'] = 'True'
    config['Input']['USE_INITFILE'] = 'True'
    config['Input']['CREATE_INITFILE'] = 'True'
    config['Geometry']['COORD_NODE_FIRST'] = start_as_string
    config['Geometry']['COORD_NODE_LAST'] = end_as_string

    with open(filename, 'w') as configfile:
        config.write(configfile)

    print('Done.')

def return_string_list_as_float_numpy_array(list_to_array):
    numpy_array = np.asarray(list(map(float, list_to_array)))

    return numpy_array

def return_float_numpy_array_as_string_list(array_to_list):
    string_list = list(map(str, array_to_list))

    return string_list

def rotate_tumor_data(params, data, iop, header_rot):
    dim0_length = (params['COORD_NODE_LAST'][0] \
                   - params['COORD_NODE_FIRST'][0])*1000
    dim1_length = (params['COORD_NODE_LAST'][1] \
                   - params['COORD_NODE_FIRST'][1])*1000
    dim2_length = (params['COORD_NODE_LAST'][2] \
                   - params['COORD_NODE_FIRST'][2])*1000

    x_min = np.min(iop[:,0])
    x_max = np.max(iop[:,0])
    y_min = np.min(iop[:,1])
    y_max = np.max(iop[:,1])

    #z = np.polyfit(iop[:,0], iop[:,2], 0)
    z = np.max(iop[:,2])
    #z = np.min(iop[:,2])
    z = np.ceil(z)

    x_size = x_max - x_min
    y_size = y_max - y_min

    missing_x = dim0_length - x_size
    missing_y = dim1_length - y_size

    x_start = x_min - missing_x/2.0
    x_start = np.floor(x_start)
    x_end = dim0_length + x_start

    y_start = y_min - missing_y/2.0
    y_start = np.floor(y_start)
    y_end = y_start + dim1_length

    z_start = float(z) - dim2_length
    z_end = float(z)

    start = [x_start, y_start, z_start]
    end = [x_end, y_end, z_end]

    params['START'] = start

    params['END'] = end

    dim0 = params['N_NODES'][0]
    dim1 = params['N_NODES'][1]
    dim2 = params['N_NODES'][2]

    delta_x = dim0_length/(dim0-1)
    delta_y = dim1_length/(dim1-1)
    delta_z = dim2_length/(dim2-1)

    print('Create LPS coordinates array.')

    coord_lps = np.zeros(dim0*dim1*dim2*3).reshape((dim0, dim1, dim2, 3))

    for elem_x in range(0, coord_lps.shape[0]):
        x = x_start + elem_x * delta_x
        for elem_y in range(0, coord_lps.shape[1]):
            y = y_start + elem_y * delta_y
            for elem_z in range(0, coord_lps.shape[2]):
                z = z_start + elem_z * delta_z
                coord_lps[elem_x, elem_y, elem_z] = np.asarray([x, y, z])

    print('Done.')
    print('Create IJK coordinates array.')

    coord_ijk = np.zeros(dim0*dim1*dim2*3).reshape((dim0, dim1, dim2, 3))

    for elem_x in range(0, coord_ijk.shape[0]):
        for elem_y in range(0, coord_ijk.shape[1]):
            for elem_z in range(0, coord_ijk.shape[2]):
                coord_ijk[elem_x, elem_y, elem_z] = lps_to_ijk(coord_lps[elem_x,
                                                                         elem_y,
                                                                         elem_z],
                                                               header_rot)

    print('Done.')
    print('Interpolate data.')

    reg_grid_inter = get_regular_grid_interpolator(data)

    final_data = np.zeros(dim0*dim1*dim2).reshape((dim0, dim1, dim2))

    for elem_x in range(0, final_data.shape[0]):
        for elem_y in range(0, final_data.shape[1]):
            for elem_z in range(0, final_data.shape[2]):
                tmp = coord_ijk[elem_x, elem_y, elem_z]
                data_pt = reg_grid_inter(tmp)
                final_data[elem_x, elem_y, elem_z] = data_pt

    print('Done.')

    return final_data

def build_rotated_header(header, rmat):
    space_dir_0 = return_string_list_as_float_numpy_array(header['space directions'][0])
    space_dir_1 = return_string_list_as_float_numpy_array(header['space directions'][1])
    space_dir_2 = return_string_list_as_float_numpy_array(header['space directions'][2])
    space_origin = return_string_list_as_float_numpy_array(header['space origin'])

    space_dir_0_rot = rotate_point_by_rotation_matrix(space_dir_0, rmat)
    space_dir_1_rot = rotate_point_by_rotation_matrix(space_dir_1, rmat)
    space_dir_2_rot = rotate_point_by_rotation_matrix(space_dir_2, rmat)
    space_origin_rot = rotate_point_by_rotation_matrix(space_origin, rmat)

    header_rot = {'keyvaluepairs': ''}
    header_rot['space directions'] = [return_float_numpy_array_as_string_list(space_dir_0_rot),
                                      return_float_numpy_array_as_string_list(space_dir_1_rot),
                                      return_float_numpy_array_as_string_list(space_dir_2_rot)]
    header_rot['space origin'] = return_float_numpy_array_as_string_list(space_origin_rot)

    return header_rot

def ijk_bounding_box(start, end):
    bbox = np.asarray([[start[0], start[1], start[2]],
                       [end[0], start[1], start[2]],
                       [end[0], end[1], start[2]],
                       [start[0], end[1], start[2]],
                       [start[0], start[1], end[2]],
                       [end[0], start[1], end[2]],
                       [end[0], end[1], end[2]],
                       [start[0], end[1], end[2]]])

    return bbox

def ijk_bounding_box_to_lps(bbox, header):
    for point in bbox:
        point[...] = ijk_to_lps(point, header)

    return bbox

def main():
    params = {'keyvaluepairs' : ''}
    if len(sys.argv) > 1:
        if os.path.isdir(sys.argv[1]) == True:
            tmp = os.path.join(os.sys.argv[1], '_1.nrrd')
            if os.path.isfile(tmp) != True:
                print(sys.argv[1], 'does not contain _1.nrrd.')
                print('Aborting.')
                exit()
            else:
                folderpath = sys.argv[1]
                filepath = tmp
        else:
            print(sys.argv[1], 'does not exist.')
            print('Aborting.')
            exit()
    else:
        print('No command line argument for folder provided.')
        print('Aborting.')
        exit()

    print('Create region file.')

    case = filepath.split('_')[0]
    params['CASE'] = case
    params['FOLDERPATH'] = folderpath

    data, header = read_nrrd_file(filepath)
    save_as_netcdf(data, os.path.join(folderpath, 'tumor.nc'))
    read_default_ini_file(params)
    n_nodes = params['N_NODES_ENV']

    iop = read_intra_op_points(folderpath)

    for point in iop:
        point[...] = switch_space(point)

    rmat = get_rotation_matrix(iop)

    start_ijk = np.asarray([0, 0, 0])
    end_ijk = np.asarray(header['sizes']) - np.asarray([1.0, 1.0, 1.0])
    bbox_ijk = ijk_bounding_box(start_ijk, end_ijk)
    bbox_lps = ijk_bounding_box_to_lps(bbox_ijk, header)
    plot_lin_plane_fitting_with_bbox(iop, bbox_lps,
                                     os.path.join(folderpath, 'iop_and_bbox'))

    for point in iop:
        point[...] = rotate_point_by_rotation_matrix(point, rmat)

    header_rot = build_rotated_header(header, rmat)

    bbox_ijk = ijk_bounding_box(start_ijk, end_ijk)
    bbox_lps_rot = ijk_bounding_box_to_lps(bbox_ijk, header_rot)
    plot_lin_plane_fitting_with_bbox(iop, bbox_lps_rot,
                                     os.path.join(folderpath, 'iop_and_bbox_rot'))

    final_data = rotate_tumor_data(params, data, iop, header_rot)
    final_data = data_as_binary_data(final_data)
    filename = os.path.join(folderpath, 'region_' + n_nodes + '.nc')
    save_as_netcdf(final_data, filename)
    write_ini_file(params)

    print('Done.')

if __name__ == '__main__':
    main()

reason: import numpy,from numpy,from scipy


text:
import rospy
import tensorflow as tf
import numpy as np

from styx_msgs.msg import TrafficLight

MIN_SCORE_THRESHOLD = 0.5
CLASS_DICT = {1: 'Green', 2: 'Red', 3: 'Yellow'}

class TLClassifier(object):
    def __init__(self, is_site):
        #TODO load classifier
        if is_site:
            PATH_TO_MODEL = r'light_classification/models/site/frozen_inference_graph.pb'
            rospy.loginfo('Running on Site!')
        elif not is_site:
            PATH_TO_MODEL = r'light_classification/models/sim/frozen_inference_graph.pb'
            rospy.loginfo('Running in simulator!')

        self.state = TrafficLight.UNKNOWN
        self.detection_graph = tf.Graph()
        with self.detection_graph.as_default():
            od_graph_def = tf.GraphDef()
            # Works up to here.
            with tf.gfile.GFile(PATH_TO_MODEL, 'rb') as fid:
                serialized_graph = fid.read()
                od_graph_def.ParseFromString(serialized_graph)
                tf.import_graph_def(od_graph_def, name='')
            self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
            self.d_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
            self.d_scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
            self.d_classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
            self.num_d = self.detection_graph.get_tensor_by_name('num_detections:0')
        self.sess = tf.Session(graph=self.detection_graph)

    def get_classification(self, image):
        """Determines the color of the traffic light in the image

        Args:
            image (cv::Mat): image containing the traffic light

        Returns:
            int: ID of traffic light color (specified in styx_msgs/TrafficLight)

        """
        #TODO implement light color prediction
        # Bounding Box Detection.
        with self.detection_graph.as_default():
            # Expand dimension since the model expects image to have shape [1, None, None, 3].
            img_expanded = np.expand_dims(image, axis=0)
            (boxes, scores, classes, num) = self.sess.run(
                [self.d_boxes, self.d_scores, self.d_classes, self.num_d],
                feed_dict={self.image_tensor: img_expanded})

            boxes = np.squeeze(boxes)
            scores = np.squeeze(scores)
            classes = np.squeeze(classes).astype(np.int32)

            if scores[0] > MIN_SCORE_THRESHOLD:
                rospy.loginfo('Detecting %s!! Score: %4f', CLASS_DICT[classes[0]], scores[0])
                if classes[0] == 1:
                    self.state = TrafficLight.GREEN
                elif classes[0] == 2:
                    self.state = TrafficLight.RED
                elif classes[0] == 3:
                    self.state = TrafficLight.YELLOW
            else:
                rospy.loginfo('No Detection!')

        return self.state

max_stars_repo_name: yaanyang/CarND-Capstone

max_issues_repo_name: yaanyang/CarND-Capstone

max_forks_repo_name: yaanyang/CarND-Capstone


text:
import numpy as np
import os
import cv2
import dlib

images1 = []
images2 = []
labels = []
folders_main = ['S1' , 'S2' , 'S3']

detector = dlib.get_frontal_face_detector()

def face_detector(image):
    faces = detector(image)
    face = faces[0]
    x1, y1 = face.left(), face.top()
    x2, y2 = face.right(), face.bottom()
    # cv2.rectangle(img1, (x1_1 - 20, y1_1 - 25), (x2_1 + 10, y2_1 + 10), (0, 0, 255), 2)
    roi = image[y1 - 20:y2 + 10, x1 - 20:x2 + 10]
    return roi

for sub_folder in folders_main:
    path = 'data/'+ sub_folder + '/'
    files = os.listdir(path)
    for i in range(len(files)):
        for j in range(len(files)):
            img1 = cv2.imread(path + files[i])
            img1 = face_detector(img1)
            img1 = cv2.resize(img1 , (128,128))
            img2 = cv2.imread(path + files[j])
            img2 = face_detector(img2)
            img2 = cv2.resize(img2 , (128,128))
            images1.append(img1)
            images2.append(img2)
            labels.append(1)

print(len(images2))

for sub_folder in folders_main:
    folders = ['S1' , 'S2' , 'S3']
    print(sub_folder)
    path = 'data/' + sub_folder + '/'
    folders.remove(sub_folder)
    rem_folder = folders
    print(rem_folder)
    files_similar = os.listdir(path)
    files_dissimilar1 = os.listdir('data/{}/'.format(rem_folder[0]))
    files_dissimilar2 = os.listdir('data/{}/'.format(rem_folder[1]))
    rem_images = files_dissimilar1 + files_dissimilar2
    print(rem_images)
    for i in range(len(files_similar)):
        for j in range(len(rem_images)):
            if j<5:
                img1 = cv2.imread(path+files_similar[i])
                img1 = face_detector(img1)
                img1 = cv2.resize(img1, (128, 128))
                img2 = cv2.imread('data/{}/'.format(rem_folder[0]) + rem_images[j])
                img2 = face_detector(img2)
                img2 = cv2.resize(img2, (128, 128))
                images1.append(img1)
                images2.append(img2)
            else:
                img1 = cv2.imread(path + files_similar[i])
                img1 = face_detector(img1)
                img1 = cv2.resize(img1, (128, 128))
                img2 = cv2.imread('data/{}/'.format(rem_folder[1]) + rem_images[j])
                img2 = face_detector(img2)
                img2 = cv2.resize(img2, (128, 128))
                images1.append(img1)
                images2.append(img2)
            labels.append(0)

print(len(labels))

X1 = np.array(images1)
X2 = np.array(images2)
Y = np.array(labels)

np.save('numpy_files/X1.npy',X1)
np.save('numpy_files/X2.npy',X2)
np.save('numpy_files/Y.npy',Y)

max_stars_repo_name: Sparsh-Bansal/Modern-Attendance-system

max_issues_repo_name: Sparsh-Bansal/Modern-Attendance-system

max_forks_repo_name: Sparsh-Bansal/Modern-Attendance-system


text:
import numpy as np
from collections import deque as Queue
import math

t_window = 10
t_step = 5

class Synapse:
	def __init__(self, n_pre, n_post, tau = 1, w_init = 0.5, type = 'hebbian', **kwargs):
		self.n_pre = n_pre
		self.n_post = n_post
		self.w = w_init
		self.I = 0
		self.tau = tau
		self.sign = kwargs.get('sign', 1)
		self.effective = kwargs.get('effective', True)
		if(type == 'hebbian'):
			self.type = 'hebbian'
			self.gamma = kwargs.get('gamma', 0.5)
		elif(type == 'stdp'):
			self.type = 'stdp'
			self.tau_p = kwargs.get('tau_p', 1)
			self.tau_m = kwargs.get('tau_m', 1)
			self.eta_p = kwargs.get('eta_p', 5)
			self.eta_m = kwargs.get('eta_m', 2)
			self.x_j = 0
			self.y_i = 0

	def update(self, dt):
		dIdt = (-self.I/self.tau) + self.n_pre.currspike
		self.I = self.I + dt*dIdt

	def learn(self, dt):
		if(self.type == 'hebbian'):
			dw = 0
			for _ in range(4):
				dw += 0.25 * self.gamma * (self.n_post.spike_rate *
							(self.n_pre.spike_rate - self.w*self.n_post.spike_rate))
			self.w = self.w + dw

		elif(self.type == 'stdp'):
			if len(self.n_pre.spikes) > 0 and len(self.n_post.spikes) > 0:
				self.x_j = self.x_j + dt*(-self.x_j/self.tau_p) + self.n_pre.currspike
				self.y_i = self.y_i + dt*(-self.y_i/self.tau_m) + self.n_post.currspike
				A_p = (1 - self.w)*self.eta_p
				A_m = self.w*self.eta_m
				dwdt = (A_p*self.n_pre.currspike*self.x_j -
						A_m*self.n_post.currspike*self.y_i)
				self.w = self.w + dt*dwdt

	def sout(self):
		return self.sign * self.w * self.I

class Neuron:
	def __init__(self, v_r = 0, R_m = 1, tau = 1, threshold = 0.2, type = "hebbian", **kwargs):
		self.v = v_r
		self.v_r = v_r
		self.R_m = R_m
		self.tau = tau
		self.threshold = threshold
		self.type = type
		self.syns = []
		self.spikes = Queue()
		self.spikestoadd = []
		self.currspike = 0
		self.spike_rate = 0
		self.isteacher = kwargs.get('isteacher', False)
		self.isinput = kwargs.get('isinput', False)

	def add_syn(self, n_pre, tau = 1, w_init = 0.5, **kwargs):
		syn = Synapse(n_pre, self, tau = tau, w_init = w_init, type = self.type, **kwargs)
		self.syns.append(syn)
		return syn

	def remove_syn(self, n_pre):
		for syn in self.syns:
			if syn.n_pre == n_pre:
				self.syns.remove(syn)

	def get_syn(self, n_pre):
		for syn in self.syns:
			if syn.n_pre == n_pre:
				return syn
		return None

	def I_syn(self):
		# We multiply by effective because we only want the synapses that are "effective"
		# to have their current influence the input current
		I_list = [syn.sout()*syn.effective for syn in self.syns]
		return sum(I_list)

	def add_spike(self, val, dt):
		self.currspike = val
		if self.type == 'hebbian':
			global t_step;
			global t_window;
			if len(self.spikestoadd) < int(t_step/dt):
				self.spikestoadd.append(val)
			else:
				for spike in self.spikestoadd:
					self.spikes.append(spike)
					if(len(self.spikes) > t_window/dt):
						self.spikes.popleft()
				self.spikestoadd = []
			# Need a fudge factor to make the spike rates reasonable
			self.spike_rate = float(sum(self.spikes))/(t_window/(dt*25))
		else:
			self.spikes.append(val)
			if(len(self.spikes) > t_window/dt):
						self.spikes.popleft()

	def update(self, dt, I_inj = 0, learn = False):
		if not self.isteacher:
			for syn in self.syns:
				syn.update(dt)
				# If the presynapitc neuron is a teacher, don't change its weights
				# otherwise do.
				if learn and not syn.n_pre.isteacher:
				  syn.learn(dt)
		# If this neuron is a teacher or input, then we just take in the injected current i.e.
		# no synaptic connections
		if self.isteacher or self.isinput:
			I_total = I_inj
		# Otherwise aggregate all the weighted synaptic inputs
		else:
			I_total = self.I_syn()
		if math.isnan(I_total):
			raise Exception("Current is NaN")
		# Leaky integrate and fire dynamics
		dvdt = (-self.v + self.R_m * I_total)/self.tau
		self.v = self.v + dt*dvdt
		if(self.v >= self.threshold):
			self.v = self.v_r
			self.add_spike(1, dt)
			return self.threshold
		else:
			self.add_spike(0, dt)
			return self.v

class SynapseReader:
	def __init__(self, synapse):
		self.synapse = synapse
		self.Is = []
		self.ws = []

	def read_synapse(self, nclock):
		self.Is.append((nclock.gettime, self.synapse.I))
		self.ws.append((nclock.gettime, self.synapse.w))

	def refresh(self):
		self.Is = []
		self.ws = []

class NeuronReader:
	def __init__(self, neuron, readsyns = False):
		self.neuron = neuron
		self.readsyns = readsyns
		if self.readsyns:
			self.syns = self.neuron.syns
			self.synreaders = [SynapseReader(syn) for syn in self.neuron.syns]
		self.vs = []
		self.spikes = []

	def change_neuron(self):
		self.neuron = neuron
		self.vs = []
		self.spikes = []
		if self.readsyns:
			self.syns = self.neuron.syns
			self.synreaders = [SynapseReader(syn) for syn in self.neuron.syns]

	def update_synapses(self):
		if self.readsyns:
			for syn in self.neuron.syns:
				if syn not in self.syns:
					self.synreaders.append(SynapseReader(syn))

	def refresh(self):
		self.vs = []
		self.spikes = []
		if self.readsyns:
			for synreader in self.synreaders:
				synreader.refresh()

	def read_neuron(self, nclock):
		self.vs.append((nclock.gettime, self.neuron.v))
		self.spikes.append((nclock.gettime, self.neuron.currspike))
		if readsyns:
			for synreader in self.synreaders:
				synreader.read_synapse(nclock)

max_stars_repo_name: SamKG/bic-final

max_issues_repo_name: SamKG/SNN-Edge-Detector

max_forks_repo_name: SamKG/SNN-Edge-Detector