text:
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 11 20:18:45 2020

@author: Moritz
"""

"""Fig 5A

This script reproduces the plots seen in Fig 5A of "The biophysical basis underlying
the maintenance of early phase long-term potentiation".

This script requires that `numpy`,`scipy.integrate`,`matplotlib` and `seaborn` are installed within
the Python environment you are running this script in.
"""

import sys
sys.path.append('../')

import numpy as np
import matplotlib.pyplot as plt
from ampartrafficking import rate_model as rm
import seaborn as sns
sns.set_style("ticks")
plt.rcParams['svg.fonttype'] = 'none'
from matplotlib.font_manager import FontProperties
fontLgd = FontProperties()
fontLgd.set_size('small')

#%%

SaveFig=0

Cooperativity=1

Init=[10,20,13]
Vspine=0.08
Aspine=4*np.pi*(3*Vspine/(4*np.pi))**(2/3)

P=70
kin=0.2
kout=0.018
kexo0=0.0018
kendo=rm.kendo_(Init,kexo0,kin,kout,Aspine) #0.002058
kBU=0.1
kUB0=rm.kUB0_(Init,kBU,P,Aspine,Cooperativity) #0.0005048
kin_RE=0.1
kout_RE=0.000615

Vspine_List=np.linspace(0.0001,0.2501,81, endpoint=True)

BFP_Coop=[]
UFP_List=[]
SexoFP_List=[]
for i,Vspine in enumerate(Vspine_List):

    Aspine=4*np.pi*(3*Vspine/(4*np.pi))**(2/3)

    SexoFP=rm.SexoFP_(kin_RE,kout_RE,Vspine)
    UFP=rm.UFP_(kexo0,SexoFP,kendo,kin,kout,Aspine)

    BFP=rm.BFP_(UFP,kUB0,kBU,P,Aspine,Cooperativity)

    BFP_Coop.append(BFP)
    UFP_List.append(UFP)
    SexoFP_List.append(SexoFP)

#%%

Cooperativity=0

Init=[10,20,13]
Vspine=0.08
Aspine=4*np.pi*(3*Vspine/(4*np.pi))**(2/3)

P=70
kin=0.2
kout=0.018
kexo0=0.0018
kendo=rm.kendo_(Init,kexo0,kin,kout,Aspine) #0.002058
kBU=0.1
kUB0=rm.kUB0_(Init,kBU,P,Aspine,Cooperativity) #0.00359
kin_RE=0.1
kout_RE=0.000615

Vspine_List=np.linspace(0.0001,0.2501,81, endpoint=True)

BFP_Basic=[]
for i,Vspine in enumerate(Vspine_List):

    Aspine=4*np.pi*(3*Vspine/(4*np.pi))**(2/3)

    SexoFP=rm.SexoFP_(kin_RE,kout_RE,Vspine)
    UFP=rm.UFP_(kexo0,SexoFP,kendo,kin,kout,Aspine)

    BFP=rm.BFP_(UFP,kUB0,kBU,P,Aspine,Cooperativity)

    BFP_Basic.append(BFP)

#%%

col0=sns.light_palette(sns.color_palette("colorblind", 10)[0],3)[1]
col1=sns.dark_palette(sns.color_palette("colorblind", 10)[0],4)[2]
col2=sns.dark_palette(sns.color_palette("colorblind", 10)[0],4)[1]
col=[col0,col1,col2,col0,col1,col2,'k','k']

fig,axes=plt.subplots(figsize=(3.5,2.35), dpi=150)
ax2 = axes.twiny()
axes.plot(SexoFP_List,BFP_Coop, Linewidth=2, label='Coop. Model', color=col[0])
axes.plot(SexoFP_List,BFP_Basic, Linewidth=2, label='Basic Model', color='k')
ax2.plot(Vspine_List,BFP_Coop, Linewidth=2, label='Coop. Model', color=col[0])
ax2.plot(Vspine_List,BFP_Basic, Linewidth=2, label='Basic Model', color='k')
lgd = plt.legend(bbox_to_anchor=(0.02,0.80,0,0), loc="lower left", mode="normal", borderaxespad=0, ncol=6, prop=fontLgd)
plt.axhline(0, c='k', Linewidth=0.5)
ax2.axvline(0.08, c='k', Linewidth=0.5)
ax2.axvline(0.16, c='k', Linewidth=0.5)
# plt.xlabel('$k_{out}$')
ax2.set_xlabel('Spine volume $V_{spine}$ ($\mu m^3$)')
axes.set_xlabel('Exocytosis event size $S_{exo}$ (#)')
axes.set_ylabel('Bound AMPARs $B^*$ (#)')
ax2.set_xlim(0,0.25)
axes.set_xlim(0,40)
plt.ylim(10,40)
sns.despine(top=False)
fig.tight_layout()
if SaveFig==1:
    fig.savefig('Figures\\Fig5A.png', bbox_inches="tight", dpi=400)
    fig.savefig('Figures\\Fig5A.svg', bbox_inches="tight", dpi=400)

ext: py

reason: import numpy


text:
#!/usr/bin/env python3

# this is a throwaway prototype
# so the code is highly experimental

import time
import struct
import usb
import code
import sys
import subprocess

dev=usb.core.find(idVendor=0x1209, idProduct=0xDECA)

debug=False
if debug: print(dev)

scale = 8*8

def fix2float(fix):
    return fix/2**scale

def float2fix(f):
    return int(f*2**scale)

def send_command(bytewidth, view, debug=False):
    command_bytes = struct.pack("HHI", view.width-1, view.height-1, view.max_iterations)
    command_bytes += view.corner_x.to_bytes(bytewidth, byteorder='little', signed=True)
    command_bytes += view.corner_y.to_bytes(bytewidth, byteorder='little', signed=True)
    command_bytes += view.step    .to_bytes(bytewidth, byteorder='little', signed=True)
    command_bytes += bytes([0xa5])
    if debug: print(f"command: {[hex(b) for b in command_bytes]}")

    dev.write(0x01, command_bytes)

    time.sleep(0.05)

    result = []
    try:
        while True:
            if debug: print("read")
            r = dev.read(0x81, 256, timeout=10)
            if debug: print("Got: "+ str(len(r)))
            if debug: print(str(r))
            result += r
    except usb.USBError:
        print(f"Got {len(result)} bytes from USB")

    if len(result) > 0:
        first_separator_index = result.index(0xa5)
        if first_separator_index != 7:
            print(f"Warning: Chop until index {first_separator_index}")
            result = result[first_separator_index+1:]
        pixels = [struct.unpack("HHBBBx", bytes(p)) for p in [result[i:i+8] for i in range(0, len(result), 8)] if len(p) == 8]
        for pixel in pixels:
            if debug: print(f"x: {pixel[0]} y: {pixel[1]} R: {pixel[2]} G: {pixel[3]} B: {pixel[4]}")

        print(f"Total number of pixels: {len(pixels)}")

        return pixels

def openImage(path):
    imageViewerFromCommandLine = {'linux':'xdg-open',
                                  'win32':'explorer',
                                  'darwin':'open'}[sys.platform]
    subprocess.run([imageViewerFromCommandLine, path])

class FractalView():
    def __init__(self, *, center_x, center_y, radius, width=1920, height=1080, max_iterations=256) -> None:
        radius_pixels = min(width, height) / 2
        step = radius / radius_pixels / 2

        self.step = float2fix(step)
        self.corner_x = corner_x = float2fix(center_x - (width/2)  * step)
        self.corner_y = corner_y = float2fix(center_y - (height/2) * step)
        self.width  = width
        self.height = height
        self.max_iterations = max_iterations
        if debug:
            print(f"left_corner_x: {corner_x/2**scale} corner_y: {corner_y/2**scale}, step: {self.step/2**scale}")
            print(f"right_corner_x: {(corner_x + width*self.step)/2**scale} upper_corner_y: {(corner_y + height*self.step)/2**scale}")

default_view = FractalView(center_x=-0.75,    center_y=0,             radius=2.5,         max_iterations=170)
swirl        = FractalView(center_x=-0.74791, center_y=0.0888909763, radius=6.9921e-5,   max_iterations=4096)

view = default_view

from sys import argv
if __name__ == "__main__":
    if len(argv) > 1:
        if argv[1] == "plot":
            p = send_command(9, view, debug=False)
            r = [e for e in p if e[3] & 0x1 > 0]
            x = [fix2float(view.corner_x) + fix2float(view.step) * e[0] for e in r]
            y = [fix2float(view.corner_y) + fix2float(view.step) * e[1] for e in r]

            coords = list(zip(x, y))
            print(coords)

            import matplotlib.pyplot as plt
            plt.scatter(x, y, c ="black")

            # To show the plot
            plt.show()

        if argv[1] == "debug":
            send_command(9, view, debug=True)
            code.interact(local=locals())
    else:
        tstart = time.perf_counter()
        pixels = send_command(9, view, debug=False)
        tusb = time.perf_counter()
        print(f"USB transfer took: {tusb - tstart:0.4f} seconds")

        import numpy as np
        from matplotlib.image import imsave

        p = np.zeros((view.height, view.width, 3))

        for pixel in pixels:
            x     = pixel[0]
            y     = pixel[1]
            red   = pixel[2] / 255.0
            green = pixel[3] / 255.0
            blue  = pixel[4] / 255.0

            if x >= view.width:
                print(f"rogue pixel: {str(pixel)}")
                continue
            if y >= view.height:
                print(f"rogue pixel: {str(pixel)}")
                continue

            p[y][x][0] = red
            p[y][x][1] = green
            p[y][x][2] = blue

        pixels = []

        pix_conv = time.perf_counter()
        print(f"converting pixels took: {pix_conv - tusb:0.4f} seconds")

        outfilename = 'mandelbrot.png'
        imsave(outfilename, p)
        img_save = time.perf_counter()
        print(f"saving image took: {img_save - pix_conv:0.4f} seconds")
        openImage(outfilename)

max_stars_repo_name: curliph/deca-mandelbrot

max_issues_repo_name: curliph/deca-mandelbrot

max_forks_repo_name: curliph/deca-mandelbrot


text:
## filter out v1 data from masks
import os, json, time, pickle
import nibabel as nib
import numpy as np
from sklearn import linear_model
import itertools as it

# initialize parameters
### work_dir = '/Users/chloe/Documents/'
### all_subjects = ['sub-02', 'sub-04']
work_dir = '/mindhive/saxelab3/anzellotti/forrest/derivatives/fmriprep/'
mask_dir = '/mindhive/saxelab3/anzellotti/forrest/rV1_mask_funcSize_bin.nii.gz'
all_subjects = ['sub-01', 'sub-02', 'sub-03', 'sub-04', 'sub-05', 'sub-09', 'sub-10', 'sub-14', 'sub-15', 'sub-16', 'sub-17', 'sub-18', 'sub-19', 'sub-20']
mask = 'rV1'
total_run = 8

# cd to work directory
os.chdir(work_dir)
mask_data = nib.load(mask_dir).get_data()

# preprocess data: filter movie data with rois for all subjects
for s in range(0, len(all_subjects)):
	# data initialize
	sub = all_subjects[s]
	sub_dir = work_dir + sub + '_complete/'
	sub_data_dir = sub_dir + 'ses-movie/func/'
	pre_out_dir = sub_dir + sub + '_pre/'
	# make output dir if not exist
	if not os.path.exists(pre_out_dir):
		os.makedirs(pre_out_dir)

	# iterate through all runs of this subject and filter by roi masks
	for run in range(1, total_run + 1):
		run_dir = sub_data_dir + sub + '_ses-movie_task-movie_run-' + str(run) + '_bold_space-MNI152NLin2009cAsym_preproc.nii.gz'
		run_data = nib.load(run_dir).get_data()
		roi_out_dir = pre_out_dir + sub + '_' + mask + '_run_' + str(run) + '.npy'
		roi_data = np.zeros((run_data.shape[3], int(np.sum(mask_data))))

		# iterate through all voxels to find roi voxels
		roi_index = 0
		for t in range(0, run_data.shape[3]):
			for x in range(0, run_data.shape[0]):
				for y in range(0, run_data.shape[1]):
					for z in range(0, run_data.shape[2]):
						if mask_data[x, y, z] == 1:
							roi_data[t, int(roi_index)] = run_data[x, y, z, t]
							roi_index += 1
			roi_index = 0 # to next row, reset column indices

		# save roi data
		np.save(roi_out_dir, roi_data)


text:
import json

import torch
import os
import os.path
import numpy as np
import pandas
import random
from collections import OrderedDict

from lib.train.data import jpeg4py_loader
from .base_video_dataset import BaseVideoDataset
from lib.train.admin import env_settings

class AntiUAV(BaseVideoDataset):
    """ AntiUAV dataset.
    """

    def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, split='train'):
        """
        args:
            root        - The path to the TrackingNet folder, containing the training sets.
            image_loader (jpeg4py_loader) -  The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)
                                            is used by default.
            set_ids (None) - List containing the ids of the TrackingNet sets to be used for training. If None, all the
                            sets (0 - 11) will be used.
            data_fraction - Fraction of dataset to be used. The complete dataset is used by default
        """
        # print(root, env_settings().antiuav_dir)
        if split == 'test':
            self.split_dir = 'test-challenge'
        else:
            self.split_dir = 'trainval'
        root = env_settings().antiuav_dir if root is None else root
        super().__init__('AntiUAV', root, image_loader)

        # Keep a list of all videos. Sequence list is a list of tuples (set_id, video_name) containing the set_id and
        # video_name for each sequence

        self.sequence_list = json.load(open(os.path.join(root, 'split.bk.json')))[split]
        self.sequence_list = [s.split('/')[1] for s in self.sequence_list]
        # self.sequence_list = os.listdir(os.path.join(root, self.split_dir))

        if data_fraction is not None:
            self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list) * data_fraction))

        self.seq_to_class_map, self.seq_per_class = self._load_class_info()

        # we do not have the class_lists for the tracking net
        self.class_list = list(self.seq_per_class.keys())
        self.class_list.sort()

    def _load_class_info(self):
        seq_per_class = {}
        seq_per_class['uav'] = self.sequence_list
        seq_to_class_map = {}
        for i, seq in enumerate(self.sequence_list):
            seq_to_class_map[seq] = 'uav'

        return seq_to_class_map, seq_per_class

    def get_name(self):
        return 'AntiUAV'

    def has_class_info(self):
        return True

    def get_sequences_in_class(self, class_name):
        return self.seq_per_class[class_name]

    def _read_bb_anno(self, seq_id):
        vid_name = self.sequence_list[seq_id]
        bb_anno_file = os.path.join(self.root, self.split_dir, vid_name, "IR_label.json")
        # gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False,
        #                      low_memory=False).values
        gt = json.load(open(bb_anno_file, "r"))['gt_rect']
        for i in range(len(gt)):
            if len(gt[i]) == 0:
                gt[i] = [0, 0, 0, 0]
        return torch.tensor(gt)

    def get_sequence_info(self, seq_id):
        bbox = self._read_bb_anno(seq_id)

        valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)
        visible = valid.clone().byte()
        return {'bbox': bbox, 'valid': valid, 'visible': visible}

    def _get_frame(self, seq_id, frame_id):
        vid_name = self.sequence_list[seq_id]
        frame_path = os.path.join(self.root, 'frames', self.split_dir, vid_name, 'IR',
                                  "{:0>6d}".format(frame_id) + ".jpg")
        return self.image_loader(frame_path)

    def _get_class(self, seq_id):
        seq_name = self.sequence_list[seq_id]
        return self.seq_to_class_map[seq_name]

    def get_class_name(self, seq_id):
        obj_class = self._get_class(seq_id)

        return obj_class

    def get_frames(self, seq_id, frame_ids, anno=None):
        frame_list = [self._get_frame(seq_id, f) for f in frame_ids]

        if anno is None:
            anno = self.get_sequence_info(seq_id)

        anno_frames = {}
        for key, value in anno.items():
            anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]

        obj_class = self._get_class(seq_id)

        object_meta = OrderedDict({'object_class_name': obj_class,
                                   'motion_class': None,
                                   'major_class': None,
                                   'root_class': None,
                                   'motion_adverb': None})

        return frame_list, anno_frames, object_meta


text:
#!/usr/bin/env python3
import numpy as np
import tensorflow as tf
import subprocess
import argparse
import traceback
import json

#
# This script compares the execution result of TFLite interpreter and
# partitioned model(s) from a circle model
#
# Basic usage for example:
#   part_eval_one.py \
#       --driver build/compiler/circle-part-driver/circle-part-driver \
#       --name test_file
#
parser = argparse.ArgumentParser()
parser.add_argument('--driver', type=str, required=True)
parser.add_argument('--name', type=str, required=True)
args = parser.parse_args()

driver = args.driver
tflite_model = args.name + ".tflite"
circle_model = args.name + ".circle"
partition_conn_ini = args.name + ".conn.ini"
partition_conn_json = args.name + ".conn.json"
expected_count = args.name + ".excnt"

# Check expected count of models from partitioning
try:
    with open(expected_count, "r") as expected_count_file:
        expected_count_line = expected_count_file.readline()

    expected_count_line = int(expected_count_line)
    if expected_count_line:
        with open(partition_conn_json) as json_file:
            json_data = json.load(json_file)
            parts_value = json_data["parts"]
            if len(parts_value) != expected_count_line:
                print("Partitioned model count differs from expected:",
                      expected_count_line)
                quit(255)

            print("Partitioned model count expected: ", expected_count_line)
    else:
        print("Skip expected partitioned model count check: 0")

except:
    print("Skip expected partitioned model count check: error")

# Build TFLite interpreter.
interpreter = tf.lite.Interpreter(tflite_model)
interpreter.allocate_tensors()

# Read SignatureDef and get output tensor id orders for remapping
full_signatures = interpreter._get_full_signature_list()
full_signatures_outputs_remap = None
if full_signatures != None:
    signature_serving_default = full_signatures.get('serving_default', None)
    if signature_serving_default != None:
        signature_outputs = signature_serving_default['outputs']

        full_signatures_outputs_remap = []
        for index, (key, value) in enumerate(signature_outputs.items()):
            full_signatures_outputs_remap.append(value)

# Generate random input data.
num_inputs = len(interpreter.get_input_details())
for i in range(num_inputs):
    input_details = interpreter.get_input_details()[i]
    input_details_dtype = input_details["dtype"]
    input_details_shape = input_details["shape"]
    if input_details_dtype == np.float32:
        input_data = np.array(
            np.random.random_sample(input_details_shape), input_details_dtype)
    elif input_details_dtype == np.uint8:
        input_data = np.array(
            np.random.randint(0, 256, size=input_details_shape), input_details_dtype)
    elif input_details_dtype == np.bool_:
        input_data = np.array(
            np.random.choice(a=[True, False], size=input_details_shape),
            input_details_dtype)
    else:
        raise SystemExit("Unsupported input dtype")

    interpreter.set_tensor(input_details["index"], input_data)
    input_data.tofile(circle_model + ".input" + str(i))

# Do inference
interpreter.invoke()

# Execute circle-part-driver.
partition_command = [
    driver, partition_conn_ini,
    str(num_inputs), circle_model + ".input", circle_model + ".output"
]
print("Run: ")
for arg in partition_command:
    print("    ", arg, "\\")
print("", flush=True)

subprocess.run(partition_command, check=True)

# Compare the results.
inpt_output_details = interpreter.get_output_details()
for idx in range(len(inpt_output_details)):
    output_details = inpt_output_details[idx]
    output_dtype = output_details["dtype"]
    output_data = np.fromfile(circle_model + ".output" + str(idx), output_dtype)
    shape_file = open(circle_model + ".output" + str(idx) + ".shape", 'r')
    output_shape = [int(i) for i in shape_file.read().split(',')]
    luci_output_data = np.reshape(output_data, output_shape)
    output_tensor = output_details["index"]
    if full_signatures_outputs_remap != None:
        output_tensor = full_signatures_outputs_remap[idx]
    intp_output_data = interpreter.get_tensor(output_tensor)
    try:
        if output_dtype == np.uint8:
            if np.allclose(luci_output_data, intp_output_data, rtol=0, atol=0) == False:
                raise SystemExit("Execution result of " + tflite_model +
                                 " does not match with " + circle_model)
        elif output_dtype == np.float32:
            if np.allclose(
                    luci_output_data, intp_output_data, rtol=1.e-5, atol=1.e-5) == False:
                raise SystemExit("Execution result of " + tflite_model +
                                 " does not match with " + circle_model)
        elif output_dtype == np.int64:
            if np.allclose(luci_output_data, intp_output_data, rtol=0, atol=0) == False:
                raise SystemExit("Execution result of " + tflite_model +
                                 " does not match with " + circle_model)
        elif output_dtype == np.int32:
            if np.allclose(luci_output_data, intp_output_data, rtol=0, atol=0) == False:
                raise SystemExit("Execution result of " + tflite_model +
                                 " does not match with " + circle_model)
        else:
            raise SystemExit("Unsupported data type: ", output_dtype)
    except:
        print(traceback.format_exc())
        quit(255)

quit(0)


text:
#!/usr/bin/env python
'''
Reporte búsqueda de alquileres de Inmuebles
---------------------------
Autor: Inove Coding School
Version: 1.0

Descripcion:
Este script realiza reportes de los datos adquiridos de alquileres de inmuebles
Reporte Nº
0: Visualizar todos los reportes juntos de estudio por ambientes y m2
1: Cantidad de alquileres por ambiente
2: Precio por ambiente
3: Cantidad de alquileres por m2
4: Precio por m2
5: Calcular y visualizar le prediccion de costos por m2

Requisitos de instalacion:

- Python 3.x
- Libreriras (incluye los comandos de instalacion)
    pip install numpy
    pip install pandas
    pip install matplotlib
    pip install seaborn
    pip install sklearn
'''

__author__ = "Inove Coding School"
__email__ = "INFO@INOVE.COM.AR"
__version__ = "1.0"

import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.axes
import seaborn as sns
from sklearn import linear_model

def generar_reporte(reporte, silent_mode=False):

    df = pd.read_csv("propiedades.csv")

    # Sacamos todas las filas de la tabla las cuales el campo "m2" o "ambientes" se encuentre vacio
    propiedades = df[df['m2'].notna()]
    propiedades = propiedades[propiedades['ambientes'].notna()]

    # Nos quedamos solamente con aquellas filas que el precio haya sido informado en pesos Argentinos
    propiedades = propiedades.loc[propiedades['moneda'] == 'ARS']

    # Como alternativa se puede pasar los precios en dolares a pesos, pero en general estos datos se escapan de la media
    #dolar_pesos = 67
    #propiedades['precio'] = propiedades.apply(lambda x: x['precio']*dolar_pesos if x['moneda']  == 'USD' else x['precio'], axis = 1)

    # Obtener cuantos alquileres por ambientes hay
    ambientes = propiedades.groupby('ambientes')['ambientes'].count()
    ambientes_df = ambientes.reset_index(name='cantidad')

    # Obtener el precio promedio por cantidad de ambientes
    precio_por_ambiente = propiedades.groupby('ambientes')['precio'].mean()/1000
    precio_por_ambiente_df = precio_por_ambiente.reset_index(name='precio')

    fig = plt.figure(figsize=(16,9))
    axs = np.empty(4, dtype=type(matplotlib.axes))

    # En funcion del reporte a mostrar defino el estilo del gráfico
    if reporte < 5:
        sns.set_style("white")
    else:
        sns.set_style("whitegrid", {'grid.linestyle': '--'})

    if reporte == 0:
        # En el caso de desear visualizar todos los gráficos genero subplots para mostarlos juntos
        axs[0] = fig.add_subplot(221)
        axs[1] = fig.add_subplot(222)
        axs[2] = fig.add_subplot(223)
        axs[3] = fig.add_subplot(224)
    elif reporte <= 4:
        # Creo unicamente el gráifico que voy a mostrar
        axs[reporte-1] = fig.add_subplot(111)
    elif reporte == 5:
        ax1 = fig.add_subplot(111)
    elif reporte == 6:
        axs[0] = fig.add_subplot(121)
        axs[1] = fig.add_subplot(122)
    elif reporte == 7:
        axs[2] = fig.add_subplot(121)
        axs[3] = fig.add_subplot(122)

    if reporte == 0 or reporte == 1 or reporte == 6:
        # Graficar "Cantidad de alquileres por ambiente"
        ax = sns.barplot(x=ambientes_df['ambientes'], y=ambientes_df['cantidad'], ax=axs[0])
        ax.set_alpha(0.8)
        ax.set_title("Cantidad de alquileres por ambiente", fontsize=15)
        ax.set_ylabel("Cantidad", fontsize=12)
        ax.set_xlabel("Ambientes", fontsize=12)

    if reporte == 0 or reporte == 2 or reporte == 6:
        # Graficar "Precio por ambiente"
        ax = sns.barplot(x=precio_por_ambiente_df['ambientes'], y=precio_por_ambiente_df['precio'], palette="pastel", ax=axs[1])
        ax.set_alpha(0.8)
        ax.set_title("Precio por ambiente", fontsize=15)
        ax.set_ylabel("Precio[miles de pesos]", fontsize=12)

    if reporte == 0 or reporte == 3 or reporte == 7:
        # Graficar "Cantidad de alquileres por m2"
        ax = sns.distplot(propiedades['m2'], bins=40, kde=True, kde_kws={"color": "blue", "alpha":0.3, "linewidth": 1, "shade":True }, ax=axs[2])
        ax.set_title("Cantidad de alquileres por m2", fontsize=15, y=0.7, x = 0.5)
        ax.set_ylabel("Cantidad", fontsize=12)
        ax.set_xlabel('m2')

    if reporte == 0 or reporte == 4 or reporte == 7:
        # Graficar "Precio por m2"
        ax = sns.scatterplot(propiedades['m2'],propiedades['precio']/1000, color='blue', ax=axs[3])
        ax.set_title("Precio por m2", fontsize=15, y=-0.01)
        ax.set_ylabel("Precio[miles de pesos]", fontsize=12)
        ax.set_xlabel('m2')

    if reporte == 5:
        # Calcular y visualizar le prediccion de costos por m2
        regr = linear_model.LinearRegression()
        x = np.asanyarray(propiedades[['ambientes','m2']])
        y = np.asanyarray(propiedades['precio'])
        regr.fit(x, y)
        y_hat= regr.predict(propiedades[['ambientes','m2']])

        # Graficar "Precio por m2"
        sns.set_style("whitegrid", {'grid.linestyle': '--'})
        ax = sns.scatterplot(propiedades['m2'],propiedades['precio']/1000, color='blue', ax=ax1)
        ax = sns.lineplot(propiedades['m2'],y_hat/1000, color='red', ax=ax1)
        ax.set_title("Precio por m2", fontsize=15)
        ax.set_ylabel("Precio[miles de pesos]", fontsize=12)
        ax.set_xlabel('m2')
        plt.legend(('predicción', 'precio publicado '), prop={'size': 15})

    if silent_mode == False:
        plt.show(block=True)

    return fig

if __name__ == '__main__':
    try:
        reporte = int(sys.argv[1]) # Tomo el número de reporte de la líne ade comando
    except:
        reporte = 0 # Sino especificamos el reporte a visualizar se mostrarán todos

    if(reporte < 0 or reporte > 7):
        print("Error: El reporte especificado debe estar entre los valores 0 y 7")

    generar_reporte(reporte=reporte)


text:
import os
import random
import pickle
import numpy as np
import pandas as pd

random.seed(1234)

DIR = '../../dataset/log_preprocess/20181128/'
CACHE_DIR = '../../algo_recommend_server/script/cache_ph/'

def load_train_muid_and_content_id(muids_map_file, content_ids_map_file):
    index_muid_map = {}
    muid_index_map = {}
    with open(muids_map_file, 'r') as fin:
        lines = fin.readlines()
        for line in lines:
            params = line.strip().split('\t')
            index_muid_map[int(params[1])] = params[0]
            muid_index_map[params[0]] = int(params[1])
    index_content_id_map = {}
    content_id_index_map = {}
    with open(content_ids_map_file, 'r') as fin:
        lines = fin.readlines()
        for line in lines:
            params = line.strip().split('\t')
            index_content_id_map[int(params[1])] = params[0]
            content_id_index_map[params[0]] = int(params[1])
    return index_muid_map, muid_index_map, index_content_id_map, content_id_index_map

def get_tags(item_portraits):
    tags = {}
    train_tags_list = [[] for _ in range(len(item_portraits))]
    for content_id, item_portrait in item_portraits.items():
        # print('content_id:', content_id)
        # print('item_portrait:', item_portrait)
        try:
            tag_portrait = item_portrait['tag_portrait']
        except:
            continue
        content_tags = []
        for tag, tscore in tag_portrait.items():
            content_tags.append(str(tag))
            if tag not in tags:
                tags[tag] = len(tags)
        train_tags_list.append(content_tags)
    print('tags:', len(tags))
    print('train_tags_list:', len(train_tags_list))
    return tags, train_tags_list

def _parse(data):
    for line in data:
        if not line:
            continue
        uid, iid, rating, timestamp = [int(x) for x in line.split('\t')]
        yield uid, iid, rating, timestamp

def _build_pd(rows, cols, data):
    uids = []
    iids = []
    ratings = []
    timestamps = []
    for uid, iid, rating, timestamp in data:
        uids.append(uid)
        iids.append(iid)
        ratings.append(rating)
        timestamps.append(timestamp)
    mat = pd.DataFrame({'reviewerID': uids, 'asin': iids, 'rating': ratings, 'unixReviewTime': timestamps})
    return mat

def prepare_data(dir, cache_dir):
    with open(dir + 'train_ph.txt', 'r') as fin:
        # muid content_id rating timestamp
        train_raw = fin.readlines()
    with open(dir + 'test_ph.txt', 'r') as fin:
        # muid content_id rating timestamp
        test_raw = fin.readlines()

    index_muid_map, muid_index_map, index_content_id_map, content_id_index_map = load_train_muid_and_content_id(
        dir + 'train_muids_map.txt', dir + 'train_content_ids_map.txt')

    num_users, num_items = len(index_muid_map), len(index_content_id_map)

    # Load train interactions
    train = _build_pd(num_users, num_items, _parse(train_raw))
    # Load test interactions
    test = _build_pd(num_users, num_items, _parse(test_raw))

    cache_path = cache_dir + 'item_portraits.pik'
    print('cache_path:', cache_path, 'file_exists:', os.path.exists(cache_path))
    if os.path.exists(cache_path):
        with open(cache_path, 'rb') as data_f:
            item_portraits = pickle.load(data_f)
    else:
        print('ERROR!', 'cache_path:', cache_path)
        exit(-1)
    print('item_portraits:', len(item_portraits))

    tags, train_tags_list = get_tags(item_portraits)

    item_features = np.zeros(shape=(num_items,), dtype=int)
    for content_id_index, content_id in index_content_id_map.items():
        if content_id in item_portraits:
            item_portrait = item_portraits[content_id]
            tag_portrait = item_portrait['tag_portrait']
            item_features[content_id_index] = tags[list(tag_portrait.keys())[0]]
            # item_features[content_id_index] = []
            # for tag, tscore in tag_portrait.items():
            #     item_features[content_id_index].append(str(tags[tag]) + ':' + str(tscore))
        else:
            item_features[content_id_index] = tags['']
    item_features = item_features.tolist()

    data = {'train': train,
            'test': test,
            'item_features': item_features,
            'tags': tags,
            'user_count': num_users,
            'item_count': num_items,
            'cate_count': len(tags),
            'example_count': train.shape[0]+test.shape[0]}

    return data

if __name__ == '__main__':
    data = prepare_data(DIR, CACHE_DIR)
    # print('data:', data)

    # reviews_df = pd.concat([data['train'], data['test']], axis=0)
    train_reviews_df = data['train']
    test_reviews_df = data['test']
    cate_list = data['item_features']
    user_count = data['user_count']
    item_count = data['item_count']
    cate_count = data['cate_count']
    example_count = data['example_count']

    with open('../raw_data/funny_remap.pkl', 'wb') as f:
        # pickle.dump(reviews_df, f, pickle.HIGHEST_PROTOCOL) # uid, iid
        pickle.dump(train_reviews_df, f, pickle.HIGHEST_PROTOCOL) # uid, iid
        pickle.dump(test_reviews_df, f, pickle.HIGHEST_PROTOCOL) # uid, iid
        pickle.dump(cate_list, f, pickle.HIGHEST_PROTOCOL) # cid of iid line
        pickle.dump((user_count, item_count, cate_count, example_count), f, pickle.HIGHEST_PROTOCOL)
        # pickle.dump((asin_key, cate_key, revi_key), f, pickle.HIGHEST_PROTOCOL)


text:
import numpy as np
from scipy.integrate import odeint
from tclab import labtime
import matplotlib.pyplot as plt

if_log = False

class gravtank():

    def __init__(self, name='', A=1, Cv=1, hlimit=500):
        self.name = name
        self.A = A
        self.Cv = Cv
        self.hlimit = hlimit
        self._log = []
        self.qin = 0

    def qout(self,h):
        return self.Cv*np.sqrt(float(h))

    def deriv(self,h,t):
        if h < 0:
          raise ValueError('h is negative')
        dh = (self.qin - self.qout(h))/self.A
        if h >= self.hlimit and dh > 0:
          return 0
        return dh

    def plot(self):
        if not self._log:
          return
        t,qout,h = np.asarray(self._log).transpose()
        plt.plot(t,qout,label=self.name + ' qout')
        plt.plot(t,h,label=self.name + ' h')
        plt.legend(loc='best')

    def generator(self,dt,IC = 0):
        h = IC
        while True:
            t,dt,self.qin = yield self.qout(h),float(h)
            h = odeint(self.deriv,h,[t,t+dt])[-1]
            if if_log:
              self._log.append([t,self.qout(h),float(h)])
            #t += dt

class CGravtank():

    def __init__(self, name='', tank1={}, tank2={},h1=0,h2=0):

        if not tank1 or not tank2:
          raise ValueError('tank1 and tank2 must be defined')

        if h1 < 0 or h2 < 0:
          raise ValueError('h1 and h2 must be positive')

        self.name = name
        self.ifOneTank = False

        if tank1['A'] <= 0 or tank1['Cv'] <= 0 or tank1['hlimit'] <= 0:
          raise ValueError('tank1 A, C1 and hlimit must be great than 0')
        if tank2['A'] <= 0 or tank2['Cv'] <= 0 or tank2['hlimit'] <= 0:
          print("only one tank is simulated!")
          self.ifOneTank = True

        self.tank1_obj = gravtank('tank1',\
                        tank1['A'],tank1['Cv'],tank1['hlimit'])
        if not self.ifOneTank:
          self.tank2_obj = gravtank('tank2',\
                        tank2['A'],tank2['Cv'],tank2['hlimit'])

        #initialize the generators
        self.tank1 = self.tank1_obj.generator(dt=0.1,IC=h1)
        self.tank1.send(None)
        if not self.ifOneTank:
          self.tank2 = self.tank2_obj.generator(dt=0.1,IC=h2)
          self.tank2.send(None)

        labtime.start()
        self._log = []
        #self.tlast = labtime.time()
        self.tlast = 0
        self.qin1 = 0
        self.maxstep = 0.1

    def plot(self):
      if not if_log:
        return
      self.tank1_obj.plot()
      self.tank2_obj.plot()
    def Qin(self,qin):
        if qin < 0:
          raise ValueError('qin is negative')
        self.update()
        self.qin1 = qin

    def H1(self):
        self.update()
        return self.h1
    def H2(self):
        self.update()
        return self.h2

    def update(self):
        if(self.tlast == 0):
          self.tlast = labtime.time()
          return

        now = labtime.time()
        t = now - self.tlast

        teuler = self.tlast
        while True:
          dt = min(self.maxstep, now - teuler)
          if dt <= 0:
            break
          qout1,self.h1 = self.tank1.send((teuler,dt,self.qin1))

          if not self.ifOneTank:
            qout2,self.h2 = self.tank2.send((teuler,dt,qout1))
          teuler += dt
          if teuler == t:
            break
        self.tlast = now

def test():
  import tclab
  import time
  labtime.set_rate(10)

  t = CGravtank(name='test',tank1={'A':4,'Cv':15,'hlimit':12},\
              tank2={'A':6,'Cv':10,'hlimit':20},h1=0,h2=0)
  labtime_start = labtime.time()
  time_start = time.time()
  print("start simulation:")
  for i in tclab.clock(400,step =1,adaptive=False):
    t_real = time.time() - time_start
    t_lab = labtime.time() - labtime_start
    #print("real time = {0:4.1f}    lab time = {1:4.1f}    m.time = {1:4.1f}".format(t_real, t_lab,m.time))
    #print("real time = {0:4.1f}    lab time = {1:4.1f}    ".format(t_real, t_lab))
    print("tclab clock is {}".format(i))
    t.Qin(20)
    labtime.stop()
    if if_log:
      plt.clf()
      t.plot()
      plt.pause(0.02)
    labtime.start()
  if if_log:
    plt.show()
  print("plot")
  input("Press Enter to continue...")

def create_tank(name,A1,Cv1,hlimit1,\
                A2,Cv2,hlimit2,h1,h2):
  tank1 = {
    'A':A1,
    'Cv':Cv1,
    'hlimit':hlimit1
  }
  tank2 = {
    'A':A2,
    'Cv':Cv2,
    'hlimit':hlimit2
  }
  return CGravtank(name=name,tank1=tank1,
                   tank2=tank2,h1=h1,h2=h2)

if __name__ == '__main__':
    test()

max_stars_repo_name: hrg-hgzy/TCLab

max_issues_repo_name: hrg-hgzy/TCLab

max_forks_repo_name: hrg-hgzy/TCLab

reason: import numpy,from scipy


text:
import numpy as np

from utils import check_if_board_is_full, get_winner, negamax_alpha_beta_pruned

human_player = int(input('Do you want to play as the first [1] or as the second [-1] player?\n'))
computer_player = 1 if human_player == -1 else -1

size = 3

board = np.zeros(shape=(size, size))

print(f'\nInitial state of the board:\n{board}\n')

if human_player == 1:
    while True:
        move = input('Play a move. (type e.g. "0, 0" for a move in the left upper corner)\n')

        try:
            move = [int(m) for m in move.split(',')]
        except ValueError:
            print('\nMove coordinates in improper format. Try again.\n')
            continue
        if board[move[0], move[1]] != 0:
            print('\nThis field is taken.\n')
            continue
        board[move[0], move[1]] = human_player

        print(f'\nState of the board:\n{board}\n')

        if get_winner(board) == human_player:
            print('You won!')
            break

        if check_if_board_is_full(board, size):
            print('Draw!')
            break

        break

while True:
    computer_move = negamax_alpha_beta_pruned(board, computer_player, -np.inf, np.inf)['move']
    row = computer_move[0]
    col = computer_move[1]
    board[row, col] = computer_player
    print(f'Computer plays: [{row}, {col}]')

    print(f'\nState of the board:\n{board}\n')

    if get_winner(board) == computer_player:
        print('You lost!')
        break

    if check_if_board_is_full(board, size):
        print('Draw!')
        break

    move = input('Play a move. (type e.g. "0, 0" for a move in the left upper corner)\n')

    try:
        move = [int(m) for m in move.split(',')]
    except ValueError:
        print('\nMove coordinates in improper format. Try again.\n')
        continue
    if board[move[0], move[1]] != 0:
        print('\nThis field is taken.\n')
        continue
    board[move[0], move[1]] = human_player

    print(f'\nState of the board:\n{board}\n')

    if get_winner(board) == human_player:
        print('You won!')
        break

    if check_if_board_is_full(board, size):
        print('Draw!')
        break

max_stars_repo_name: adrzystek/TicTacToeAI

max_issues_repo_name: adrzystek/TicTacToeAI

max_forks_repo_name: adrzystek/TicTacToeAI


text:
# -*- coding: utf-8 -*-
"""
==========================================
 Elekta phantom data with dipole fit
==========================================
"""
# authors: Amit & Alex & Eric

from __future__ import print_function

import numpy as np
import mne

from phantom_helpers import (get_data, plot_errors, maxfilter_options,
                             dipole_amplitudes, dipole_indices, actual_pos)

errors = np.empty(
    (len(maxfilter_options), len(dipole_amplitudes), len(dipole_indices)))

for ui, mf in enumerate(maxfilter_options):
    for ai, dipole_amplitude in enumerate(dipole_amplitudes):
        print(('Processing : %4d nAm : SSS=%s'
               % (dipole_amplitude, mf)).ljust(40), end='')
        for di, dipole_idx in enumerate(dipole_indices):
            epochs, evoked, cov, sphere = get_data(
                dipole_idx, dipole_amplitude, mf)
            # Do the dipole fit
            t_peak = 66e-3  # only fit the largest peak
            evoked.crop(t_peak, t_peak)
            pos = mne.fit_dipole(evoked, cov, sphere)[0].pos[0]
            errors[ui, ai, di] = 1e3 * np.linalg.norm(
                pos - actual_pos[dipole_idx - 1])
        print(np.round(errors[ui, ai], 1))

plot_errors(errors, 'dipfit')

max_stars_repo_name: RTHMaK/RPGOne

max_issues_repo_name: RTHMaK/RPGOne

max_forks_repo_name: RTHMaK/RPGOne


text:
import theano
from theano import Op, Apply
import theano.tensor as T
from theano.gof import local_optimizer
from theano.sandbox.cuda import cuda_available

if cuda_available:
    from theano.sandbox.cuda import CudaNdarrayType
    from theano.sandbox.cuda.basic_ops import host_from_gpu, gpu_from_host
    from theano.sandbox.cuda.opt import register_opt as register_gpu_opt

class BadOldCode(Exception):
    """
    We create a specific Exception to be sure it does not get caught by
    mistake.
    """
    pass

class Images2Neibs(Op):
    def __init__(self, mode='valid'):
        """
        Modes:
            valid : Reshapes the input as a a 2D tensor where each row is a pooling example.
                Requires an input that is a multiple of the pooling factor (in each direction)
            ignore_borders : Same as valid, but will ignore the borders if the shape(s) of the input
                is not a multiple of the pooling factor(s)
            wrap_centered : ?? TODO comment
        """
        if mode not in ['valid', 'wrap_centered', 'ignore_borders']:
            raise NotImplementedError("Only the mode valid, ignore_borders"
                                      " and wrap_centered have been"
                                      " implemented for the op Images2Neibs")
        self.mode = mode

    def __eq__(self, other):
        return type(self) == type(other) and self.mode == other.mode

    def __hash__(self):
        return hash(type(self)) ^ hash(self.mode)

    def __str__(self):
        return self.__class__.__name__ + "{%s}" % self.mode

    def __setstate__(self, d):
        self.__dict__.update(d)
        if not hasattr(self, "mode"):
            self.mode = 'valid'

    def make_node(self, ten4, neib_shape, neib_step=None):
        """
        :param neib_step: (dx,dy) where dx is the number of rows to
                          skip between patch and dy is the number of
                          columns. When None, this is the same as
                          neib_shape(patch are disjoint)
        """
        ten4 = T.as_tensor_variable(ten4)
        neib_shape = T.as_tensor_variable(neib_shape)
        if neib_step is None:
            neib_step = neib_shape
        else:
            neib_step = T.as_tensor_variable(neib_step)

        assert ten4.ndim == 4
        assert neib_shape.ndim == 1
        assert neib_step.ndim == 1

        return Apply(self, [ten4, neib_shape, neib_step],
                     [T.matrix(dtype=ten4.type.dtype)])

    def grad(self, inp, grads):
        x, neib_shape, neib_step = inp
        gz, = grads
        if self.mode in ['valid', 'ignore_borders']:
            raise BadOldCode("The Images2Neibs grad is not implemented."
                            " It was in the past, but returned the wrong"
                            " answer!")
            # This is the reverse of the op, not the grad!
            return [neibs2images(gz, neib_shape, x.shape, mode=self.mode),
                    None, None]
        else:
            raise NotImplementedError()

    def c_code_cache_version(self):
        return (5,)

    def c_code(self, node, name, inp, out, sub):
        ten4, neib_shape, neib_step = inp
        z, = out

        fail = sub['fail']
        mode = self.mode
        return """
        int grid_c = -1; //number of patch in height
        int grid_d = -1; //number of patch in width
        {
        if (%(ten4)s->nd != 4)
        {
            PyErr_Format(PyExc_TypeError, "ten4 wrong rank");
            %(fail)s;
        }
        if (%(neib_shape)s->nd != 1)
        {
            PyErr_Format(PyExc_TypeError, "neib_shape wrong rank");
            %(fail)s;
        }
        if ( (%(neib_shape)s->dimensions)[0] != 2)
        {
            PyErr_Format(PyExc_TypeError, "neib_shape wrong shape ; has to"
                                          " contain 2 elements");
            %(fail)s;
        }
        if (%(neib_step)s->nd != 1)
        {
            PyErr_Format(PyExc_TypeError, "neib_step wrong rank");
            %(fail)s;
        }
        if ( (%(neib_step)s->dimensions)[0] != 2)
        {
            PyErr_Format(PyExc_TypeError,
                         "neib_step wrong step ; has to contain 2 elements");
            %(fail)s;
        }

        // (c,d) = neib_shape
        const npy_intp c = (npy_intp) *(dtype_%(neib_shape)s*) PyArray_GETPTR1(%(neib_shape)s, 0);
        const npy_intp d = (npy_intp) *(dtype_%(neib_shape)s*) PyArray_GETPTR1(%(neib_shape)s, 1);
        // (step_x,step_y) = neib_step
        const npy_intp step_x = (npy_intp) *(dtype_%(neib_step)s*) PyArray_GETPTR1(%(neib_step)s, 0);
        const npy_intp step_y = (npy_intp) *(dtype_%(neib_step)s*) PyArray_GETPTR1(%(neib_step)s, 1);

        if ( "%(mode)s" == "wrap_centered") {
            if (c%%2!=1 || d%%2!=1){
                PyErr_Format(PyExc_TypeError, "Images2Neibs: in mode wrap_centered need patch with odd shapes");
                %(fail)s;
            }
            if ( (%(ten4)s->dimensions)[2] < c || (%(ten4)s->dimensions)[3] < d)
            {
                PyErr_Format(PyExc_TypeError, "Images2Neibs: in wrap_centered mode, don't support image shapes smaller then the patch shapes: neib_shape=(%%ld,%%ld), ten4[2:]=[%%ld,%%ld]",
                             (long int)c, (long int)d, (long int)(%(ten4)s->dimensions[2]), (long int)(%(ten4)s->dimensions[3]));
                %(fail)s;
            }
            //grid_c = CEIL_INTDIV(((%(ten4)s->dimensions)[2]),step_x)
            //grid_d = CEIL_INTDIV(((%(ten4)s->dimensions)[3]),step_y)
            grid_c = ((%(ten4)s->dimensions)[2])/step_x + ((((%(ten4)s->dimensions)[2])%%step_x)? 1:0);
            grid_d = ((%(ten4)s->dimensions)[3])/step_y + ((((%(ten4)s->dimensions)[3])%%step_y)? 1:0);
        }else if ( "%(mode)s" == "valid") {
            if ( ((%(ten4)s->dimensions)[2] < c) ||( (((%(ten4)s->dimensions)[2]-c) %% step_x)!=0))
            {
                PyErr_Format(PyExc_TypeError, "neib_shape[0]=%%ld, neib_step[0]=%%ld and ten4.shape[2]=%%ld not consistent",
                             (long int)c, (long int)step_x, (long int)(%(ten4)s->dimensions[2]));
                %(fail)s;
            }
            if ( ((%(ten4)s->dimensions)[3] < d) ||( (((%(ten4)s->dimensions)[3]-d) %% step_y)!=0))
            {
                PyErr_Format(PyExc_TypeError, "neib_shape[1]=%%ld, neib_step[1]=%%ld and ten4.shape[3]=%%ld not consistent",
                             (long int)d, (long int)step_y, (long int)(%(ten4)s->dimensions[3]));
                %(fail)s;
            }
            grid_c = 1+(((%(ten4)s->dimensions)[2]-c)/step_x); //number of patch in height
            grid_d = 1+(((%(ten4)s->dimensions)[3]-d)/step_y); //number of patch in width
        }else if ( "%(mode)s" == "ignore_borders") {
            grid_c = 1+(((%(ten4)s->dimensions)[2]-c)/step_x); //number of patch in height
            grid_d = 1+(((%(ten4)s->dimensions)[3]-d)/step_y); //number of patch in width
        }else{
            PyErr_Format(PyExc_TypeError, "Images2Neibs: unknow mode '%(mode)s'");
            %(fail)s;
        }

        // new dimensions for z
        const npy_intp z_dim1 = c * d;
        const npy_intp z_dim0 =  grid_c
                            * grid_d
                            * (%(ten4)s->dimensions)[1]
                            * (%(ten4)s->dimensions)[0];

        if ((NULL == %(z)s)
            || ((%(z)s->dimensions)[0] != z_dim0 )
            || ((%(z)s->dimensions)[1] != z_dim1 )
        )
        {
            Py_XDECREF(%(z)s);
            npy_intp dims[2];
            dims[0] = z_dim0;
            dims[1] = z_dim1;

            %(z)s = (PyArrayObject*) PyArray_EMPTY(2,
                dims,
                type_num_%(ten4)s,
                0);

            if (!%(z)s)
            {
                PyErr_SetString(PyExc_MemoryError, "failed to alloc z output");
                %(fail)s;
            }
        }
        }

        { // NESTED SCOPE

        const int nb_batch = (%(ten4)s->dimensions)[0];
        const int nb_stack = (%(ten4)s->dimensions)[1];
        const int height = (%(ten4)s->dimensions)[2];
        const int width = (%(ten4)s->dimensions)[3];

        // (c,d) = neib_shape
        const npy_intp c = (npy_intp) *(dtype_%(neib_shape)s*) PyArray_GETPTR1(%(neib_shape)s, 0);
        const npy_intp d = (npy_intp) *(dtype_%(neib_shape)s*) PyArray_GETPTR1(%(neib_shape)s, 1);
        // (step_x,step_y) = neib_step
        const npy_intp step_x = (npy_intp) *(dtype_%(neib_step)s*) PyArray_GETPTR1(%(neib_step)s, 0);
        const npy_intp step_y = (npy_intp) *(dtype_%(neib_step)s*) PyArray_GETPTR1(%(neib_step)s, 1);

        const int wrap_centered_idx_shift_x = c/2;
        const int wrap_centered_idx_shift_y = d/2;
        // Oh this is messed up...
        for (int n = 0; n < nb_batch; n++)              // loop over batches
            for (int s = 0; s < nb_stack; s++)          // loop over stacks
                for (int a = 0; a < grid_c; a++)        // loop over the number of patch in height
                    for (int b = 0; b < grid_d; b++)    // loop over the number of patch in width
                    {
                        int z_row = b + grid_d*(a + grid_c*(s + nb_stack*n));
                        for (int i = 0; i < c; i++)     // loop over c
                        {
                            int ten4_2 = i + a * step_x;
                            if ( "%(mode)s" == "wrap_centered" ){
                                ten4_2 -= wrap_centered_idx_shift_x;
                                if ( ten4_2 < 0 ) ten4_2 += height;
                                else if (ten4_2 >= height) ten4_2 -= height;
                            }
                            for (int j = 0; j < d; j++)  // loop over d
                            {

                                int ten4_3 = j + b * step_y;
                                if ( "%(mode)s" == "wrap_centered" ){
                                    ten4_3 -= wrap_centered_idx_shift_y;
                                    if ( ten4_3 < 0 ) ten4_3 += width;
                                    else if (ten4_3 >= width) ten4_3 -= width;
                                }
                                int z_col = j + d * i;

                                dtype_%(z)s* curr_z = (dtype_%(z)s*) PyArray_GETPTR2(%(z)s, z_row, z_col);
                                *curr_z = *( (dtype_%(ten4)s*) PyArray_GETPTR4(%(ten4)s, n, s, ten4_2, ten4_3));

                                //printf("\\n(%%i,%%i,%%i,%%i) --> (%%i,%%i)",n,s, ten4_2, ten4_3, z_row, z_col);
                                //printf("%%f ", *curr_z);
                            }
                        }
                    }
        } // END NESTED SCOPE
        """ % locals()

def images2neibs(ten4, neib_shape, neib_step=None, mode='valid'):
    return Images2Neibs(mode)(ten4, neib_shape, neib_step)

def neibs2images(neibs, neib_shape, original_shape, mode='valid'):
    """
    Inverse of images2neib.

    neibs : matrix like the one obtained by images2neib
    neib_shape : neib_shape that was used in images2neib
    original_shape : original shape of the 4d tensor given to images2neib

    Return a 4d tensor of shape `original_shape`.
    """
    neibs = T.as_tensor_variable(neibs)
    neib_shape = T.as_tensor_variable(neib_shape)
    original_shape = T.as_tensor_variable(original_shape)

    new_neib_shape = T.stack(original_shape[-1] // neib_shape[1],
                             neib_shape[1])
    output_2d = images2neibs(neibs.dimshuffle('x', 'x', 0, 1),
                             new_neib_shape, mode=mode)

    if mode == 'ignore_borders':
        valid_shape = list(original_shape)
        valid_shape[2] = (valid_shape[2] // neib_shape[0]) * neib_shape[0]
        valid_shape[3] = (valid_shape[3] // neib_shape[1]) * neib_shape[1]
        output_4d = output_2d.reshape(valid_shape)
        #padding the borders with zeros
        for d in [2, 3]:
            pad_shape = list(output_4d.shape)
            pad_shape[d] = original_shape[d] - valid_shape[d]
            output_4d = T.concatenate([output_4d, T.zeros(pad_shape)], axis=d)
    else:
        output_4d = output_2d.reshape(original_shape)

    return output_4d

# This is work in progress
class GpuImages2Neibs(Images2Neibs):
    def __init__(self, mode='valid'):
        if mode not in ['valid', 'wrap_centered']:
            raise NotImplementedError("Only the mode valid and wrap_centered"
                                      " have been implemented for the op"
                                      " GpuImages2Neibs")
        self.mode = mode

    def make_node(self, ten4, neib_shape, neib_step):
        assert ten4.dtype == 'float32'
        if not isinstance(ten4.type, CudaNdarrayType):
            raise TypeError('ten4 must be cudandarray', ten4)

        assert ten4.ndim == 4
        assert neib_shape.ndim == 1
        assert neib_step.ndim == 1

        return Apply(self, [ten4, neib_shape, neib_step],
                     [CudaNdarrayType(broadcastable=(False, False),
                                      dtype=ten4.type.dtype)()])

    def c_code_cache_version(self):
        return (7,)

    def c_support_code_apply(self, node, nodename):
        mode = self.mode
        return """
//a version that use less register but don't work in all case.
        static __global__ void k_multi_warp_less_%(nodename)s(
            const int nb_batch,
            const int nb_stack,
            const int height,
            const int width,
            const int c,
            const int d,
            const int step_x,
            const int step_y,
            const int grid_c,
            const int grid_d,
            const int stride0, const int stride1, const int stride2, const int stride3,
            float * global_ten4,
            float * global_out
        )
        {
            const int wrap_centered_idx_shift_x = c/2;
            const int wrap_centered_idx_shift_y = d/2;

            for(int tblock = blockIdx.x*blockDim.z+threadIdx.z;tblock<nb_batch*nb_stack*grid_c*grid_d;tblock+=gridDim.x*blockDim.z){
                const int b = tblock%%grid_d;
                int left = tblock/grid_d;
                const int a = left%%grid_c;
                left = left/grid_c;
                const int s = left%%nb_stack;
                left = left/nb_stack;
                const int n = left;

                if(n>nb_batch)continue;
                if(s>nb_stack)continue;
                if(a>grid_c)continue;
                if(b>grid_d)continue;
                            int z_row = b + grid_d*(a + grid_c*(s + nb_stack*n));
                            int i = threadIdx.y;     // loop over c
                            {
                                int ten4_2 = i + a * step_x;
                                if("%(mode)s"=="wrap_centered"){
                                    ten4_2 -= wrap_centered_idx_shift_x;
                                    if ( ten4_2 < 0 ) ten4_2 += height;
                                    else if (ten4_2 >= height) ten4_2 -= height;
                                }
                                int j = threadIdx.x;  // loop over d
                                {
                                    int ten4_3 = j + b * step_y;
                                    if("%(mode)s"=="wrap_centered"){
                                        ten4_3 -= wrap_centered_idx_shift_y;
                                        if ( ten4_3 < 0 ) ten4_3 += width;
                                        else if (ten4_3 >= width) ten4_3 -= width;
                                    }

                                    //int ten4_idx = ten4_3 + width*(ten4_2 + height*(s +nb_stack*n));
                                    //int ten4_idx = stride3*ten4_3 + stride2*(ten4_2 + stride1*(s + stride0*n));
                                    int ten4_idx = stride3*ten4_3 + stride2*ten4_2 + stride1*s + stride0*n;

                                    int z_col = j + d * i;
                                    int z_idx = z_col + c*d*z_row;
                                    global_out[z_idx] = global_ten4[ten4_idx];
                                }
                            }
            }
        }

        static __global__ void k_multi_warp_%(nodename)s(
            const int nb_batch,
            const int nb_stack,
            const int height,
            const int width,
            const int c,
            const int d,
            const int step_x,
            const int step_y,
            const int grid_c,
            const int grid_d,
            const int stride0, const int stride1, const int stride2, const int stride3,
            float * global_ten4,
            float * global_out
        )
        {
            const int wrap_centered_idx_shift_x = c/2;
            const int wrap_centered_idx_shift_y = d/2;

            for(int tblock = blockIdx.x*blockDim.z+threadIdx.z;tblock<nb_batch*nb_stack*grid_c*grid_d;tblock+=gridDim.x*blockDim.z){
                const int b = tblock%%grid_d;
                int left = tblock/grid_d;
                const int a = left%%grid_c;
                left = left/grid_c;
                const int s = left%%nb_stack;
                left = left/nb_stack;
                const int n = left;

                if(n>nb_batch)continue;
                if(s>nb_stack)continue;
                if(a>grid_c)continue;
                if(b>grid_d)continue;
                            int z_row = b + grid_d*(a + grid_c*(s + nb_stack*n));
                            for (int i = threadIdx.y; i < c; i+=blockDim.y)     // loop over c
                            {
                                int ten4_2 = i + a * step_x;
                                if("%(mode)s"=="wrap_centered"){
                                    ten4_2 -= wrap_centered_idx_shift_x;
                                    if ( ten4_2 < 0 ) ten4_2 += height;
                                    else if (ten4_2 >= height) ten4_2 -= height;
                                }
                                for (int j = threadIdx.x; j < d; j+=blockDim.x)  // loop over d
                                {
                                    int ten4_3 = j + b * step_y;
                                    if("%(mode)s"=="wrap_centered"){
                                        ten4_3 -= wrap_centered_idx_shift_y;
                                        if ( ten4_3 < 0 ) ten4_3 += width;
                                        else if (ten4_3 >= width) ten4_3 -= width;
                                    }

                                    //int ten4_idx = ten4_3 + width*(ten4_2 + height*(s +nb_stack*n));
                                    //int ten4_idx = stride3*ten4_3 + stride2*(ten4_2 + stride1*(s + stride0*n));
                                    int ten4_idx = stride3*ten4_3 + stride2*ten4_2 + stride1*s + stride0*n;

                                    int z_col = j + d * i;
                                    int z_idx = z_col + c*d*z_row;
                                    global_out[z_idx] = global_ten4[ten4_idx];
                                }
                            }
            }
        }

        """ % locals()

    def c_code(self, node, name, inp, out, sub):
        ten4, neib_shape, neib_step = inp
        z, = out
        fail = sub['fail']
        mode = self.mode
        return """
        int grid_c = -1;
        int grid_d = -1;

        {
            if (%(ten4)s->nd != 4)
            {
                PyErr_Format(PyExc_TypeError, "pvals wrong rank");
                %(fail)s;
            }
            if (%(neib_shape)s->nd != 1)
            {
                PyErr_Format(PyExc_TypeError, "unis wrong rank");
                %(fail)s;
            }

            if (%(neib_shape)s->dimensions[0] != 2)
            {
                PyErr_Format(PyExc_ValueError, "neib_shape has to contain two elements");
                %(fail)s;
            }

            const int c = *(dtype_%(neib_shape)s*) PyArray_GETPTR1(%(neib_shape)s, 0);
            const int d = *(dtype_%(neib_shape)s*) PyArray_GETPTR1(%(neib_shape)s, 1);
            const npy_intp step_x = (npy_intp) *(dtype_%(neib_step)s*) PyArray_GETPTR1(%(neib_step)s, 0);
            const npy_intp step_y = (npy_intp) *(dtype_%(neib_step)s*) PyArray_GETPTR1(%(neib_step)s, 1);

            if ( "%(mode)s" == "wrap_centered") {
                if (c%%2!=1 || d%%2!=1){
                    PyErr_Format(PyExc_TypeError, "Images2Neibs: in mode wrap_centered need patch with odd shapes");
                    %(fail)s;
                }
                if ( CudaNdarray_HOST_DIMS(%(ten4)s)[2] < c || CudaNdarray_HOST_DIMS(%(ten4)s)[3] < d)
                {
                    PyErr_Format(PyExc_TypeError, "Images2Neibs: in wrap_centered mode, don't support image shapes smaller then the patch shapes: neib_shape=(%%d,%%d), ten4[2:]=[%%d,%%d]",
                                 c, d, CudaNdarray_HOST_DIMS(%(ten4)s)[2], CudaNdarray_HOST_DIMS(%(ten4)s)[3]);
                    %(fail)s;
                }
                //grid_c = CEIL_INTDIV(((CudaNdarray_HOST_DIMS(%(ten4)s))[2]),step_x)
                //grid_d = CEIL_INTDIV(((CudaNdarray_HOST_DIMS(%(ten4)s))[3]),step_y)
                grid_c = ((CudaNdarray_HOST_DIMS(%(ten4)s))[2])/step_x + ((((CudaNdarray_HOST_DIMS(%(ten4)s))[2])%%step_x)? 1:0);
                grid_d = ((CudaNdarray_HOST_DIMS(%(ten4)s))[3])/step_y + ((((CudaNdarray_HOST_DIMS(%(ten4)s))[3])%%step_y)? 1:0);
            }else if ( "%(mode)s" == "valid") {
                if ( ((CudaNdarray_HOST_DIMS(%(ten4)s))[2] < c) ||( (((CudaNdarray_HOST_DIMS(%(ten4)s))[2]-c) %% step_x)!=0))
                {
                    PyErr_Format(PyExc_TypeError, "neib_shape[0]=%%d, neib_step[0]=%%d and ten4.shape[2]=%%d not consistent",
                                 c, step_x, CudaNdarray_HOST_DIMS(%(ten4)s)[2]);
                    %(fail)s;
                }
                if ( ((CudaNdarray_HOST_DIMS(%(ten4)s))[3] < d) ||( (((CudaNdarray_HOST_DIMS(%(ten4)s))[3]-d) %% step_y)!=0))
                {
                    PyErr_Format(PyExc_TypeError, "neib_shape[1]=%%d, neib_step[1]=%%d and ten4.shape[3]=%%d not consistent",
                                 d, step_y, CudaNdarray_HOST_DIMS(%(ten4)s)[3]);
                    %(fail)s;
                }
                grid_c = 1+(((CudaNdarray_HOST_DIMS(%(ten4)s))[2]-c)/step_x); //number of patch in height
                grid_d = 1+(((CudaNdarray_HOST_DIMS(%(ten4)s))[3]-d)/step_y); //number of patch in width
            }else{
                PyErr_Format(PyExc_TypeError, "Images2Neibs: unknow mode '%(mode)s'");
                 %(fail)s;
            }

            // new dimensions for z
            const int z_dim1 = c * d;
            const int z_dim0 =  grid_c
                                * grid_d
                                * CudaNdarray_HOST_DIMS(%(ten4)s)[1]
                                * CudaNdarray_HOST_DIMS(%(ten4)s)[0];

            if ((NULL == %(z)s)
                || (CudaNdarray_HOST_DIMS(%(z)s)[0] != z_dim0)
                || (CudaNdarray_HOST_DIMS(%(z)s)[1] != z_dim1))
            {
                Py_XDECREF(%(z)s);
                npy_intp dims[2];
                dims[0] = z_dim0;
                dims[1] = z_dim1;
                %(z)s = (CudaNdarray*)CudaNdarray_NewDims(2, dims);
                if (!%(z)s)
                {
                    PyErr_SetString(PyExc_MemoryError,
                                    "failed to alloc z output");
                    %(fail)s;
                }
            }

        }

        { // NESTED SCOPE

            const int nb_batch = CudaNdarray_HOST_DIMS(%(ten4)s)[0];
            const int nb_stack = CudaNdarray_HOST_DIMS(%(ten4)s)[1];
            const int height = CudaNdarray_HOST_DIMS(%(ten4)s)[2];
            const int width = CudaNdarray_HOST_DIMS(%(ten4)s)[3];

            const int c = *(dtype_%(neib_shape)s*) PyArray_GETPTR1(%(neib_shape)s, 0);
            const int d = *(dtype_%(neib_shape)s*) PyArray_GETPTR1(%(neib_shape)s, 1);
            const npy_intp step_x = (npy_intp) *(dtype_%(neib_step)s*) PyArray_GETPTR1(%(neib_step)s, 0);
            const npy_intp step_y = (npy_intp) *(dtype_%(neib_step)s*) PyArray_GETPTR1(%(neib_step)s, 1);

            dim3 n_threads(d,c,1);
            //Their is a max of 512 threads per blocks
            while(n_threads.x*n_threads.y>512 && n_threads.y>1)n_threads.y--;
            while(n_threads.x*n_threads.y>512 && n_threads.x>1)n_threads.x--;

            //Make bigger block to have better memory access pattern and a higher core utilisation.
            //for smaller patch size
            while(c*d*(n_threads.z+1) < 128 && n_threads.z<64 && n_threads.z<CudaNdarray_HOST_DIMS(%(z)s)[0]){
                n_threads.z++;
            }
            int nb_block;
            if (CudaNdarray_HOST_DIMS(%(z)s)[0] %% n_threads.z == 0)
                nb_block = CudaNdarray_HOST_DIMS(%(z)s)[0] / n_threads.z;
            else
                nb_block = (CudaNdarray_HOST_DIMS(%(z)s)[0] / n_threads.z) + 1;
            dim3 n_blocks(std::min(32*1024,nb_block));
            int n_shared = 0;

            void (*f)(int, int, int ,int,
                      int, int, int ,int,
                      int, int,
                      int, int, int, int,
                      float*, float*);
            if(n_threads.x==d && n_threads.y==c){
                f = k_multi_warp_less_%(name)s;
            }else{
                f = k_multi_warp_%(name)s;
            }

            f<<<n_blocks, n_threads, n_shared>>>(
                nb_batch,
                nb_stack,
                height, width,
                c, d, step_x, step_y,
                grid_c, grid_d,
                CudaNdarray_HOST_STRIDES(%(ten4)s)[0],
                CudaNdarray_HOST_STRIDES(%(ten4)s)[1],
                CudaNdarray_HOST_STRIDES(%(ten4)s)[2],
                CudaNdarray_HOST_STRIDES(%(ten4)s)[3],
                CudaNdarray_DEV_DATA(%(ten4)s),
                CudaNdarray_DEV_DATA(%(z)s)
            );
            CNDA_THREAD_SYNC;
            cudaError_t sts = cudaGetLastError();
            if (cudaSuccess != sts)
            {
                PyErr_Format(PyExc_RuntimeError,
                             "Cuda error: %%s: %%s. (grid: %%i x %%i;"
                             " block: %%i x %%i x %%i; shared: %%i)\\n",
                    "k_multi_warp_%(name)s",
                    cudaGetErrorString(sts),
                    n_blocks.x,
                    n_blocks.y,
                    n_threads.x,
                    n_threads.y,
                    n_threads.z,
                    n_shared);
                %(fail)s;
            }

        } // END NESTED SCOPE
        """ % locals()

def gpu_images2neibs(ten4, neib_shape, neib_step=None, mode='valid'):
    return GpuImages2Neibs(mode)(ten4, neib_shape, neib_step)

@local_optimizer()
def use_gpu_images2neibs(node):
    if type(node.op) is Images2Neibs:
        return [host_from_gpu(gpu_images2neibs(gpu_from_host(node.inputs[0]),
                                               node.inputs[1], node.inputs[2],
                                               mode=node.op.mode))]

if cuda_available:
    register_gpu_opt()(use_gpu_images2neibs)

max_stars_repo_name: arnaudsj/Theano

max_issues_repo_name: arnaudsj/Theano

max_forks_repo_name: arnaudsj/Theano

reason: import theano,from theano


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import cv2
import torch
import json
import numpy as np

from pysot.core.config import cfg
from pysot.models.model_builder import ModelBuilder
from pysot.tracker.tracker_builder import build_tracker

class SOTTracker:

    def __init__(self, config_file, model_file):
        self.config_file = config_file
        self.model_file = model_file

        # load config
        cfg.merge_from_file(self.config_file)
        cfg.CUDA = torch.cuda.is_available()
        self.device = torch.device('cuda' if cfg.CUDA else 'cpu')

        # load model
        self.model = ModelBuilder()
        self.model.load_state_dict(
            torch.load(
                model_file,
                map_location=lambda storage,
                loc: storage.cpu()))
        self.model.eval().to(self.device)

        # build tracker
        self.tracker = build_tracker(self.model)

    def tracking(self, init_img, init_bbox, imglist_to_track):
        # init tracker
        init_frame = cv2.imread(init_img)
        height, width, channels = init_frame.shape
        # convert bbox from relative coordinates to actual values
        init_bbox_coord = [int(init_bbox[0] * width),
                           int(init_bbox[1] * height),
                           int(init_bbox[2] * width),
                           int(init_bbox[3] * height)]
        self.tracker.init(init_frame, init_bbox_coord)

        # do tracking
        results = {_: {'polygon': None, 'mask': None, 'bbox': None}
                   for _ in imglist_to_track}
        for img in imglist_to_track:
            frame = cv2.imread(img)
            outputs = self.tracker.track(frame)
            if 'polygon' in outputs:
                polygon = np.array(outputs['polygon']).astype(np.int32)
                results[img]['polygon'] = [polygon.reshape((-1, 1, 2))]
                results[img]['mask'] = outputs['mask']

            if 'bbox' in outputs:
                bbox = list(map(float, outputs['bbox']))
                results[img]['bbox'] = [bbox[0] / width, bbox[1] / height,
                                        bbox[2] / width, bbox[3] / height]
        return results

    def tracking_json_query(self, query_json):
        query = json.loads(query_json)
        try:
            init_img = query['init_img']
            init_bbox = [int(_) for _ in query['init_bbox']]
            imglist_to_track = query['imglist_to_track']
            assert len(imglist_to_track) > 0
            return self.tracking(init_img, init_bbox, imglist_to_track)
        except KeyError:
            print('invalid query json')
            return None

    @staticmethod
    def result2json(results):
        json_string = json.dumps(results)
        return json_string

    @staticmethod
    def vis_tracking_result(img_file, result):
        vis_frame = cv2.imread(img_file)
        height, width, channels = vis_frame.shape
        if result['polygon'] is not None:
            cv2.polylines(vis_frame, result['polygon'], True, (0, 255, 0), 3)
            mask = ((result['mask'] > cfg.TRACK.MASK_THERSHOLD) * 255)
            mask = mask.astype(np.uint8)
            mask = np.stack([mask, mask * 255, mask]).transpose(1, 2, 0)
            vis_frame = cv2.addWeighted(vis_frame, 0.77, mask, 0.23, -1)
        elif result['bbox'] is not None:
            bbox = result['bbox']
            cv2.rectangle(vis_frame,
                          (int(bbox[0] * width),
                           int(bbox[1] * height)),
                          (int((bbox[0] + bbox[2]) * width),
                              int((bbox[1] + bbox[3]) * height)),
                          (0,
                              255,
                              0),
                          3)
        return vis_frame

max_stars_repo_name: futurewei-cloud/unno

max_issues_repo_name: futurewei-cloud/unno

max_forks_repo_name: futurewei-cloud/unno


text:
import argparse
import json
import os
import time

import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt

import seaborn as sns

from plotting import plot_single_trajectory
import multiprocessing
multiprocessing.set_start_method("spawn", True)

# Arguments
parser = argparse.ArgumentParser(description='Adaptive Concrete')

# Settings
parser.add_argument('--weights', type=str, default="ConcretePlot1-20200524-112930", help='weight name')
args = parser.parse_args()

if __name__ == "__main__":
    pred_dir = args.weights + '/pred6'

    all_logits = np.load(pred_dir + '/logits.npy')
    all_labels = np.load(pred_dir + '/labels.npy')
    all_selections = np.load(pred_dir + '/selections.npy')

    unique_labels = np.unique(all_labels)

    feature_counts = np.zeros((all_selections.shape[-1], unique_labels.shape[0]))
    num_labels = np.zeros((unique_labels.shape[0]))
    for i in range(all_selections.shape[0]):
        current_selection = all_selections[i, :, :]
        current_truth = all_labels[i, :]
        for label in unique_labels:
            feature_counts[:, label] += np.sum(current_selection[current_truth == label, :], axis=0)
            num_labels[label] += np.sum(current_truth == label)

    sns.set(rc={'figure.figsize':(16,4)})
    # feature_counts = feature_counts / (all_selections.shape[0] * all_selections.shape[1])
    feature_indices = np.array(range(all_selections.shape[-1]))
    feature_counts = feature_counts / num_labels
    feature_totals = np.sum(feature_counts, axis=1) / unique_labels.shape[0]

    feature_counts = feature_counts[feature_totals > 0.05, :]
    feature_indices = feature_indices[feature_totals > 0.05]

    label_name = ["No Label", "Open Door 1","Open Door 2","Close Door 1","Close Door 2","Open Fridge","Close Fridge",
        "Open Dishwasher","Close Dishwasher","Open Drawer 1","Close Drawer 1","Open Drawer 2",
        "Close Drawer 2","Open Drawer 3","Close Drawer 3","Clean Table","Drink from Cup","Toggle Switch",]

    sns_plot = sns.heatmap(np.transpose(feature_counts), xticklabels=feature_indices, yticklabels=label_name)
    plt.xlabel('Feature Number')
    plt.ylabel('Activity')
    sns_plot = sns_plot.get_figure()
    sns_plot.savefig("feature_heatmap.pdf", bbox_inches='tight')
    sns_plot.savefig("feature_heatmap.png", bbox_inches='tight')

max_stars_repo_name: ardywibowo/vfds

max_issues_repo_name: ardywibowo/vfds

max_forks_repo_name: ardywibowo/vfds


text:
# coding: utf-8
#
# Copyright 2018 Moriyoshi Koizumi
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import six
import numpy

class DataType(object):
    _numpy_dtype = numpy.dtype(object)

    def __repr__(self):
        return '{0}()'.format(self.__class__.__name__)

class AtomicType(DataType):
    pass

class NumericType(AtomicType):
    pass

class FractionalType(NumericType):
    pass

class IntegralType(NumericType):
    pass

class DoubleType(FractionalType):
    _numpy_dtype = numpy.dtype(numpy.float64)

class LongType(IntegralType):
    _numpy_dtype = numpy.dtype(numpy.int64)

class BooleanType(AtomicType):
    pass

class StringType(AtomicType):
    _numpy_dtype = numpy.dtype(str)

class StructType(DataType):
    def __init__(self, fields=None):
        self.fields = fields

    @property
    def _numpy_dtype(self):
        return numpy.dtype([
            (field.name, as_numpy_dtype(field.dataType))
            for field in fields
        ])

    def __repr__(self):
        return '{0}({1!r})'.format(self.__class__.__name__, self.fields)

class StructField(DataType):
    def __init__(self, name, dataType, nullable=True, metadata=None):
        self.name = name
        self.dataType = dataType
        self.nullable = nullable
        self.metadata = metadata

    def __repr__(self):
        return '{0}(name={1.name!r}, dataType={1.dataType!r}, nullable={1.nullable!r}, metadata={1.metadata!r})'.format(self.__class__.__name__, self)

def infer_data_type_from_numpy_dtype(dtype):
    if dtype.name == 'int64':
        return LongType()
    elif dtype.name == 'float64':
        return DoubleType()
    elif dtype.name == 'S' or dtype.name == '<U':
        return StringType()
    else:
        raise ValueError()

def infer_data_type_from_python_value(value):
    if isinstance(value, (int, long)):
        return LongType()
    elif isinstance(value, float):
        return DoubleType()
    elif isinstance(value, six.text_types):
        return StringType()
    else:
        raise ValueError()

def as_numpy_dtype(data_type):
    return data_type._numpy_dtype

max_stars_repo_name: moriyoshi/dummydf

max_issues_repo_name: moriyoshi/dummydf

max_forks_repo_name: moriyoshi/dummydf