text:
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import multiprocessing
import os
import random
import sys
import time
from enum import Enum

import numpy as np
from PIL import Image

import habitat_sim
import habitat_sim.agent
import habitat_sim.bindings as hsim
import habitat_sim.utils as utils
from settings import default_sim_settings, make_cfg

_barrier = None

class DemoRunnerType(Enum):
    BENCHMARK = 1
    EXAMPLE = 2

class DemoRunner:
    def __init__(self, sim_settings, simulator_demo_type):
        if simulator_demo_type == DemoRunnerType.EXAMPLE:
            self.set_sim_settings(sim_settings)

    def set_sim_settings(self, sim_settings):
        self._sim_settings = sim_settings.copy()

    def save_color_observation(self, obs, total_frames):
        color_obs = obs["color_sensor"]
        color_img = Image.fromarray(color_obs, mode="RGBA")
        color_img.save("test.rgba.%05d.png" % total_frames)

    def save_semantic_observation(self, obs, total_frames):
        semantic_obs = obs["semantic_sensor"]
        semantic_img = Image.new("P", (semantic_obs.shape[1], semantic_obs.shape[0]))
        semantic_img.putpalette(utils.d3_40_colors_rgb.flatten())
        semantic_img.putdata((semantic_obs.flatten() % 40).astype(np.uint8))
        semantic_img.save("test.sem.%05d.png" % total_frames)

    def save_depth_observation(self, obs, total_frames):
        if self._sim_settings["depth_sensor"]:
            depth_obs = obs["depth_sensor"]
            depth_img = Image.fromarray(
                (depth_obs / 10 * 255).astype(np.uint8), mode="L"
            )
            depth_img.save("test.depth.%05d.png" % total_frames)

    def output_semantic_mask_stats(self, obs, total_frames):
        semantic_obs = obs["semantic_sensor"]
        counts = np.bincount(semantic_obs.flatten())
        total_count = np.sum(counts)
        print(f"Pixel statistics for frame {total_frames}")
        for object_i, count in enumerate(counts):
            sem_obj = self._sim.semantic_scene.objects[object_i]
            cat = sem_obj.category.name()
            pixel_ratio = count / total_count
            if pixel_ratio > 0.01:
                print(f"obj_id:{sem_obj.id},category:{cat},pixel_ratio:{pixel_ratio}")

    def init_agent_state(self, agent_id):
        # initialize the agent at a random start state
        agent = self._sim.initialize_agent(agent_id)
        start_state = agent.get_state()

        # force starting position on first floor (try 100 samples)
        num_start_tries = 0
        while start_state.position[1] > 0.5 and num_start_tries < 100:
            start_state.position = self._sim.pathfinder.get_random_navigable_point()
            num_start_tries += 1
        agent.set_state(start_state)

        if not self._sim_settings["silent"]:
            print(
                "start_state.position\t",
                start_state.position,
                "start_state.rotation\t",
                start_state.rotation,
            )

        return start_state

    def compute_shortest_path(self, start_pos, end_pos):
        self._shortest_path.requested_start = start_pos
        self._shortest_path.requested_end = end_pos
        self._sim.pathfinder.find_path(self._shortest_path)
        print("shortest_path.geodesic_distance", self._shortest_path.geodesic_distance)

    def do_time_steps(self):
        total_frames = 0
        start_time = time.time()
        action_names = list(
            self._cfg.agents[self._sim_settings["default_agent"]].action_space.keys()
        )

        while total_frames < self._sim_settings["max_frames"]:
            action = random.choice(action_names)
            if not self._sim_settings["silent"]:
                print("action", action)
            observations = self._sim.step(action)

            if self._sim_settings["save_png"]:
                if self._sim_settings["color_sensor"]:
                    self.save_color_observation(observations, total_frames)
                if self._sim_settings["depth_sensor"]:
                    self.save_depth_observation(observations, total_frames)
                if self._sim_settings["semantic_sensor"]:
                    self.save_semantic_observation(observations, total_frames)

            state = self._sim.last_state()

            if not self._sim_settings["silent"]:
                print("position\t", state.position, "\t", "rotation\t", state.rotation)

            if self._sim_settings["compute_shortest_path"]:
                self.compute_shortest_path(
                    state.position, self._sim_settings["goal_position"]
                )

            if self._sim_settings["compute_action_shortest_path"]:
                self._action_shortest_path.requested_start.position = state.position
                self._action_shortest_path.requested_start.rotation = state.rotation
                self._action_pathfinder.find_path(self._action_shortest_path)
                print(
                    "len(action_shortest_path.actions)",
                    len(self._action_shortest_path.actions),
                )

            if (
                self._sim_settings["semantic_sensor"]
                and self._sim_settings["print_semantic_mask_stats"]
            ):
                self.output_semantic_mask_stats(observations, total_frames)

            total_frames += 1

        end_time = time.time()
        perf = {}
        perf["total_time"] = end_time - start_time
        perf["fps"] = total_frames / perf["total_time"]

        return perf

    def print_semantic_scene(self):
        if self._sim_settings["print_semantic_scene"]:
            scene = self._sim.semantic_scene
            print(f"House center:{scene.aabb.center} dims:{scene.aabb.sizes}")
            for level in scene.levels:
                print(
                    f"Level id:{level.id}, center:{level.aabb.center},"
                    f" dims:{level.aabb.sizes}"
                )
                for region in level.regions:
                    print(
                        f"Region id:{region.id}, category:{region.category.name()},"
                        f" center:{region.aabb.center}, dims:{region.aabb.sizes}"
                    )
                    for obj in region.objects:
                        print(
                            f"Object id:{obj.id}, category:{obj.category.name()},"
                            f" center:{obj.aabb.center}, dims:{obj.aabb.sizes}"
                        )
            input("Press Enter to continue...")

    def init_common(self):
        self._cfg = make_cfg(self._sim_settings)
        scene_file = self._sim_settings["scene"]

        if (
            not os.path.exists(scene_file)
            and scene_file == default_sim_settings["test_scene"]
        ):
            print(
                "Test scenes not downloaded locally, downloading and extracting now..."
            )
            utils.download_and_unzip(default_sim_settings["test_scene_data_url"], ".")
            print("Downloaded and extracted test scenes data.")

        self._sim = habitat_sim.Simulator(self._cfg)

        random.seed(self._sim_settings["seed"])
        self._sim.seed(self._sim_settings["seed"])

        # initialize the agent at a random start state
        start_state = self.init_agent_state(self._sim_settings["default_agent"])

        return start_state

    def _bench_target(self, _idx=0):
        self.init_common()

        best_perf = None
        for _ in range(3):

            if _barrier is not None:
                _barrier.wait()
                if _idx == 0:
                    _barrier.reset()

            perf = self.do_time_steps()
            # The variance introduced between runs is due to the worker threads
            # being interrupted a different number of times by the kernel, not
            # due to difference in the speed of the code itself.  The most
            # accurate representation of the performance would be a run where
            # the kernel never interrupted the workers, but this isn't
            # feasible, so we just take the run with the least number of
            # interrupts (the fastest) instead.
            if best_perf is None or perf["fps"] > best_perf["fps"]:
                best_perf = perf

        self._sim.close()
        del self._sim

        return best_perf

    @staticmethod
    def _pool_init(b):
        global _barrier
        _barrier = b

    def benchmark(self, settings):
        self.set_sim_settings(settings)
        nprocs = settings["num_processes"]

        barrier = multiprocessing.Barrier(nprocs)
        with multiprocessing.Pool(
            nprocs, initializer=self._pool_init, initargs=(barrier,)
        ) as pool:
            perfs = pool.map(self._bench_target, range(nprocs))

        res = {k: [] for k in perfs[0].keys()}
        for p in perfs:
            for k, v in p.items():
                res[k] += [v]

        return dict(fps=sum(res["fps"]), total_time=sum(res["total_time"]) / nprocs)

    def example(self):
        start_state = self.init_common()

        # initialize and compute shortest path to goal
        self._shortest_path = hsim.ShortestPath()
        self.compute_shortest_path(
            start_state.position, self._sim_settings["goal_position"]
        )

        # set the goal headings, and compute action shortest path
        if self._sim_settings["compute_action_shortest_path"]:
            agent_id = self._sim_settings["default_agent"]
            goal_headings = self._sim_settings["goal_headings"]
            self._action_pathfinder = self._sim.make_action_pathfinder(agent_id)

            self._action_shortest_path = hsim.MultiGoalActionSpaceShortestPath()
            self._action_shortest_path.requested_start.position = start_state.position
            self._action_shortest_path.requested_start.rotation = start_state.rotation

            # explicitly reset the start position
            self._shortest_path.requested_start = start_state.position

            # initialize the requested ends when computing the action shortest path
            next_goal_idx = 0
            while next_goal_idx < len(goal_headings):
                sampled_pos = self._sim.pathfinder.get_random_navigable_point()
                self._shortest_path.requested_end = sampled_pos
                if (
                    self._sim.pathfinder.find_path(self._shortest_path)
                    and self._shortest_path.geodesic_distance < 5.0
                    and self._shortest_path.geodesic_distance > 2.5
                ):
                    self._action_shortest_path.requested_ends.append(
                        hsim.ActionSpacePathLocation(
                            sampled_pos, goal_headings[next_goal_idx]
                        )
                    )
                    next_goal_idx += 1

            self._shortest_path.requested_end = self._sim_settings["goal_position"]
            self._sim.pathfinder.find_path(self._shortest_path)

            self._action_pathfinder.find_path(self._action_shortest_path)
            print(
                "len(action_shortest_path.actions)",
                len(self._action_shortest_path.actions),
            )

        # print semantic scene
        self.print_semantic_scene()

        perf = self.do_time_steps()
        self._sim.close()
        del self._sim

        return perf

max_stars_repo_name: hzyjerry/habitat-sim

max_issues_repo_name: hzyjerry/habitat-sim

max_forks_repo_name: hzyjerry/habitat-sim


text:
import numpy as np
import matplotlib.pyplot as plt
from magpylib.source.magnet import Box,Cylinder
from magpylib import Collection, displaySystem, Sensor
from scipy.optimize import fsolve, least_squares
import matplotlib.animation as manimation
import random, math

iterations = 1000000

# define sensor
sensor_pos = [[-22.7,7.7,0],[-14.7,-19.4,0],[14.7,-19.4,0],[22.7,7.7,0]]
# sensor_rot = [[0,[0,0,1]],[0,[0,0,1]],[0,[0,0,1]],[0,[0,0,1]],[0,[0,0,1]],[0,[0,0,1]],[0,[0,0,1]],[0,[0,0,1]]]
sensors = []
i = 0
for pos in sensor_pos:
    # sensors.append(Sensor(pos=pos,angle=sensor_rot[i][0], axis=sensor_rot[i][1]))
    sensors.append(Sensor(pos=pos))

def gen_magnets():
    return [Box(mag=(500,0,0),dim=(10,10,10),pos=(0,12,0)), Box(mag=(0,500,0),dim=(10,10,10),pos=(10.392304845,-6,0),angle=60, axis=(0,0,1)), Box(mag=(0,0,500),dim=(10,10,10),pos=(-10.392304845,-6,0),angle=-60, axis=(0,0,1))]

# calculate B-field on a grid
xs = np.linspace(-40,40,33)
ys = np.linspace(-40,40,44)
zs = np.linspace(-40,40,44)
POS0 = np.array([(x,0,z) for z in zs for x in xs])
POS1 = np.array([(x,y,0) for y in ys for x in xs])

body_part = "test"

record = open("/home/letrend/workspace/roboy3/"+body_part+"_data0.log","w")
record.write("mx0 my0 mz0 mx1 my1 mz1 mx2 my2 mz3 mx3 my3 mz3 roll pitch yaw\n")

first = True

for iter in range(iterations):
    rot = [random.uniform(-50,50),random.uniform(-50,50),random.uniform(-90,90)]

    c = Collection(gen_magnets())
    c.rotate(rot[0],(1,0,0), anchor=(0,0,0))
    c.rotate(rot[1],(0,1,0), anchor=(0,0,0))
    c.rotate(rot[2],(0,0,1), anchor=(0,0,0))

    data = []
    for sens in sensors:
        data.append(sens.getB(c))

    record.write(str(data[0][0])+ " " + str(data[0][1]) + " " + str(data[0][2])+ " " + str(data[1][0])+ " " + str(data[1][1])+ " " + str(data[1][2])+ " " + str(data[2][0])+ " " + str(data[2][1])+ " " + str(data[2][2])  + " " + str(data[3][0])+ " " + str(data[3][1])+ " " + str(data[3][2])+ " " + str(rot[0]/180.0*math.pi) + " " + str(rot[1]/180.0*math.pi) + " " + str(rot[2]/180.0*math.pi) + "\n")

    if first:
        # create figure
        fig = plt.figure(figsize=(18,7))
        ax1 = fig.add_subplot(131, projection='3d')  # 3D-axis
        ax2 = fig.add_subplot(132)                   # 2D-axis
        ax3 = fig.add_subplot(133)                   # 2D-axis
        Bs = c.getB(POS0).reshape(44,33,3)     #<--VECTORIZED
        X,Y = np.meshgrid(xs,ys)
        U,V = Bs[:,:,0], Bs[:,:,2]
        ax2.streamplot(X, Y, U, V, color=np.log(U**2+V**2))

        Bs = c.getB(POS1).reshape(44,33,3)     #<--VECTORIZED
        X,Z = np.meshgrid(xs,zs)
        U,V = Bs[:,:,0], Bs[:,:,2]
        ax3.streamplot(X, Z, U, V, color=np.log(U**2+V**2))
        sensor_visualization = []
        i = 0
        for pos in sensor_pos:
             sensor_visualization.append(Box(mag=(0,0,0.001),dim=(1,1,1),pos=sensor_pos[i]))
             i = i+1
        d = Collection(c,sensor_visualization)
        displaySystem(d, subplotAx=ax1, suppress=True)
        plt.show()
        first = False
    if iter%10==0:
        print("(%d/%d)"%(iter,iterations))
record.close()

ext: py

reason: import numpy,from scipy


text:
# Recurrent Neural Network

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sklearn.metrics as metrics

# Importing the training setx
dataset_train = pd.read_csv('traffic_data.csv')
training_set = dataset_train.iloc[:, 5:6].values

from sklearn.model_selection import train_test_split
X_train_split, X_test_split = train_test_split(training_set, shuffle=False, test_size = 0.2, random_state = 0)
X_train_split = pd.DataFrame(X_train_split)
X_test_split = pd.DataFrame(X_test_split)

# Feature Scaling
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range = (0, 1))
training_set_scaled = sc.fit_transform(X_train_split)

timelag = 24
X_train = []
y_train = []
for i in range(timelag, len(training_set_scaled)):
    X_train.append(training_set_scaled[i - timelag : i, 0])
    y_train.append(training_set_scaled[i, 0])
X_train, y_train = np.array(X_train), np.array(y_train)

# Reshaping
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))

# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout

# Initialising the RNN
regressor = Sequential()

# Adding the first LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1)))
regressor.add(Dropout(0.2))

# Adding a second LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.2))
'''
# Adding a third LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))

# Adding a fourth LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 20), input_shape = (X_train.shape[1], 1))
regressor.add(Dropout(0.2))
'''
# Adding the output layer
regressor.add(Dense(units = 1,activation='relu'))

# Compiling the RNN
regressor.compile(optimizer = 'adam', loss = 'mean_squared_error',metrics=['mae'])

# Fitting the RNN to the Training set
regressor.fit(X_train, y_train, epochs = 100, batch_size = 256)

dataset_test = pd.read_csv('traffic_data_test.csv')
real_volume = dataset_test.iloc[:, 5:6].values

dataset_total = pd.concat((X_train_split , X_test_split), axis = 0)
inputs = dataset_total[len(dataset_total) - len(X_test_split) - timelag:].values
inputs = inputs.reshape(-1,1)

# don't need to use fit as it's fitted already
inputs = sc.transform(inputs)
X_test = []
for i in range(timelag, len(inputs)):
    X_test.append(inputs[i - timelag : i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

predicted_volume = regressor.predict(X_test)
predicted_volume = sc.inverse_transform(predicted_volume)

# Visualising the results
plt.plot(X_test_split, color = 'red', label = 'Real volume in Lane-2')
plt.plot(predicted_volume, color = 'blue', label = 'Predicted volume in Lane-2')
plt.title('Volume in Lane-2 prediction')
plt.xlabel('Time')
plt.ylabel('Volume')
leg = plt.legend()
plt.show()

reason: import numpy


text:
from sklearn import datasets
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import RandomizedPCA
from itertools import cycle
import numpy as np
from sklearn.cross_validation import ShuffleSplit
import string
import matplotlib.pyplot as pl
from mpl_toolkits.mplot3d import Axes3D
import os
import time as tm
from sklearn.cross_validation import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report

docs = datasets.load_files(container_path="../../sklearn_data/problemG")
X, y = docs.data, docs.target

X = TfidfVectorizer(decode_error='ignore', stop_words='english', analyzer='char', ngram_range=(2,4), strip_accents='unicode', sublinear_tf=True, max_df=0.5).fit_transform(X)
n_samples, n_features = X.shape

#print y

pca = RandomizedPCA(n_components=2)
X_pca = pca.fit_transform(X)

#print X_pca.shape

# colors = ['b', 'w', 'r']
# markers = ['+', 'o', '^']
# for i, c, m in zip(np.unique(y), cycle(colors), cycle(markers)):
#     pl.scatter(X_pca[y == i, 0], X_pca[y == i, 1], c=c, marker=m, label=i, alpha=0.5)

# _ = pl.legend(loc='best')

# pl.show()

X_reduced = RandomizedPCA(n_components=3).fit_transform(X)

# fig = pl.figure(1, figsize=(8, 6))
# ax = Axes3D(fig, elev=-150, azim=110)
# ax.scatter(X_reduced[:, 0], X_reduced[:, 1], X_reduced[:, 2], c=y, s=100)
# ax.set_title("A PCA Reduction of High Dimensional Data to 3 Dimensions")
# ax.set_xlabel("1st")
# ax.w_xaxis.set_ticklabels([])
# ax.set_ylabel("2nd")
# ax.w_yaxis.set_ticklabels([])
# ax.set_zlabel("3rd")
# ax.w_zaxis.set_ticklabels([])
# pl.legend(loc='best')

# pl.show()

X_train, X_test, y_train, y_test = train_test_split(X_pca, y, test_size=0.5, random_state=3)

parameters = {
    #'vect__max_df': (0.5, 0.75, 1),
    #'vect__max_features': (None, 100, 5000),
    #'vect__analyzer' : ('char', 'word'),
    #'vect__ngram_range': ((1, 1), (1, 2), (2,2), (2,3), (1,3), (1,4), (3,4), (1,5), (4,5), (3,5)),
    #'vect__ngram_range': ((1, 1), (1, 2), (1,3)),  # unigrams or bigrams or ngrams
    #'tfidf__use_idf': (True, False),
    #'clf__alpha': (1, 0.5, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001),
    #'clf__alpha': (0.001, 0.0001, 0.00001, 0.000001)
}

scores = ['precision', 'recall']

sub_dir = "Results/"
location = "results_pca" + tm.strftime("%Y%m%d-%H%M%S") + ".txt"

mnb = MultinomialNB(alpha=0.001)

with open( os.path.join(sub_dir, location), 'w+') as f:
    for score in scores:
        f.write("%s \n" % score)
        clf = GridSearchCV(estimator=mnb, param_grid=parameters, scoring=score)
        clf.fit(X_train, y_train)
        improvement = (clf.best_score_ - baseline) / baseline

        f.write("Best parameters from a %s stand point:\n" % score)
        f.write("Best score: %0.3f \n" % clf.best_score_)
        f.write("Baseline score: %0.3f \n" % baseline)
        f.write("Improved: %0.3f over baseline \n" % improvement)

        f.write("\n\nGrid scores from a %s stand point:\n" % score)

        for params, mean_score, scores in clf.grid_scores_:
            f.write("%0.3f (+/-%0.03f) for %r \n" % (mean_score, scores.std() / 2, params))
        f.write("\n\n")

    f.write("\n\nDetailed classification report:\n")
    f.write("The model is trained on the full development set.\n")
    f.write("The scores are computed on the full evaluation set.\n")

    y_true, y_pred = y_test, clf.best_estimator_.predict(X_test)

    f.write(classification_report(y_true, y_pred))

max_stars_repo_name: dropofwill/author-attr-experiments

max_issues_repo_name: dropofwill/author-attr-experiments

max_forks_repo_name: dropofwill/author-attr-experiments


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

import sys
import numpy as np

# =============== function =============== #
def split_n(line, length):
	"""
	n 文字毎に分割する関数

	Args:
		line (str): 対象文字列
		length (int): 分割後の個別の文字列の長さ

	Returns:
		list
	"""
	return [line[i:i+length] for i in range(0, len(line), length)]

# =============== Atom class =============== #
class Molecule:
	def __init__(self, pdb_file):
		self._chains = []
		self._coords = None

		self.read_pdb(pdb_file)

	@property
	def atoms(self):
		return [atom for chain in self._chains for residue in chain.residues for atom in residue.atoms]

	@property
	def residues(self):
		return [residue for chain in self._chains for residue in chain.residues]

	@property
	def chains(self):
		return self._chains

	@property
	def coords(self):
		return self._coords

	@property
	def connect_info(self):
		return [atom.connect_info for chain in self._chains for residue in chain.residues for atom in residue.atoms if atom.connect_info is not None]

	def read_pdb(self, pdb_file):
		"""
		PDB ファイルを読み込むメソッド

		Args:
			pdb_file (str): PDB ファイルのパス

		Returns:
			self
		"""
		obj_residue = None
		obj_chain = None
		coords = []
		list_obj_atoms = []
		list_obj_atom_indexes = []
		with open(pdb_file, "r") as obj_input:
			for line_val in obj_input:
				if line_val.startswith("ATOM") or line_val.startswith("HETATM"):
					# ATOM レコードの場合

					# Atom オブジェクトを作成する
					obj_atom = Atom(line_val[12:16], int(line_val[6:11].strip()))
					list_obj_atoms.append(obj_atom)

					if len(line_val) >= 60:
						obj_atom.set_occupancy(float(line_val[54:60].strip()))

					if len(line_val) >= 66:
						obj_atom.set_temp_factor(float(line_val[60:66].strip()))

					if len(line_val) >= 78:
						obj_atom.set_element(line_val[76:78])

					if len(line_val) >= 80:
						obj_atom.set_charge(line_val[78:80])

					if obj_residue is None or obj_residue.unique != "{0}-{1}-{2}".format(line_val[17:20], line_val[21:22], int(line_val[22:26].strip())):
						# 操作中の Residue オブジェクトがない場合か、現在の原子が別の Residue オブジェクトの場合
						# Residue オブジェクトを作成する
						obj_residue = Residue(line_val[17:20], int(line_val[22:26].strip()))
						if obj_chain is None or obj_chain.name != line_val[21:22]:
							# Chain オブジェクトがない場合
							# Chain オブジェクトを作成する
							obj_chain = Chain(line_val[21:22])
							self._chains.append(obj_chain)
						obj_chain.append_residue(obj_residue)
						obj_residue.set_chain(obj_chain)
					obj_residue.append_atom(obj_atom)
					obj_atom.set_residue(obj_residue)
					obj_atom.set_chain(obj_chain)

					# 座標を追加する
					coords.append([
						float(line_val[30:38].strip()),
						float(line_val[38:46].strip()),
						float(line_val[46:54].strip())
					])

				elif line_val.startswith("TER"):
					# TER レコードの場合
					obj_chain = None

				elif line_val.startswith("CONECT"):
					# CONECT レコードの場合
					if len(list_obj_atom_indexes) == 0:
						list_obj_atom_indexes = [atom.number for atom in list_obj_atoms]
					connect_info = [int(v) for v in split_n(line_val[6:].strip(), 5)]
					list_obj_atom_connect = [list_obj_atoms[list_obj_atom_indexes.index(atom_index)] for atom_index in connect_info if atom_index in list_obj_atom_indexes]
					list_obj_atom_connect[0].set_connect(list_obj_atom_connect[1:])

		# 座標を ndarray に変換する
		self._coords = np.array(coords)
		return self

	def translate(self, shift_vector):
		"""
		全体の座標を平行移動するメソッド

		Args:
			shift_vector (ndarray): [x(float), y(float), z(float)]

		Returns:
			self
		"""
		self._coords += shift_vector
		return self

	def rotate(self, phi, theta, psi):
		"""
		全体の座標を回転するメソッド

		Args:
			vector (ndarray): []

		Returns:
			self
		"""
		# r_phi = np.array([
		# 	[1.0, 0.0, 0.0],
		# 	[0.0,  np.cos(phi), np.sin(phi), 0.0],
		# 	[0.0, -np.sin(phi), np.cos(phi), 0.0]
		# ])
		# r_theta = np.array([
		# 	[np.cos(theta), 0.0, -np.sin(theta)],
		# 	[0.0, 1.0, 0.0],
		# 	[np.sin(theta), 0.0,  np.cos(theta)]
		# ])
		# r_psi = np.array([
		# 	[np.cos(psi), -np.sin(psi), 0.0],
		# 	[np.sin(psi),  np.cos(psi), 0.0],
		# 	[0.0, 0.0, 1.0]
		# ])
		# r = r_psi.dot(r_theta)
		# print(1000, r)
		# r = r.dot(r_phi)
		# print(2000, r)
		r = rotM([phi, theta, psi])
		r = r.T
		new_coords = []
		for c in self._coords:
			new_coords.append(np.dot(r, c))
		self._coords = np.array(new_coords)
		return self

	def remove(self, remove_object):
		"""
		所属オブジェクトを削除するメソッド

		Args:
			remove_object (Chain/Residue/Atom object): 削除オブジェクト

		Returns:
			self
		"""
		idx_remove = None
		if isinstance(remove_object, Chain):
			# Chain オブジェクトの場合
			new_chain = []
			for chain in self._chains:
				if chain is remove_object:
					idx_remove = [i for i, atom1 in enumerate(self.atoms) for residue in chain.residues for atom2 in residue.atoms if atom1 is atom2]
				else:
					new_chain.append(chain)

			self._chains = new_chain

		elif isinstance(remove_object, Residue):
			# Residue オブジェクトの場合
			for residue in self.residues:
				if residue is remove_object:
					idx_remove = [i for i, atom1 in enumerate(self.atoms) for atom2 in residue.atoms if atom1 is atom2]
					residue.chain.remove_residue(remove_object)
					break

		elif isinstance(remove_object, Atom):
			# Atom オブジェクトの場合
			for i, atom in enumerate(self.atoms):
				if atom is remove_object:
					atom.residue.remove_atom(remove_object)
					idx_remove = i
					break

		else:
			sys.stderr.write("ERROR: Unknown object.\n")
			sys.exit(1)

		self._coords = np.delete(self._coords, idx_remove, 0)
		return self

	def write_pdb(self, output_file):
		"""
		PDB ファイルとして出力するメソッド

		Args:
			output_file (str): PDB ファイル

		Returns:
			self
		"""
		idx_atom = 0
		with open(output_file, "w") as obj_output:
			for chain in self._chains:
				for residue in chain.residues:
					for atom in residue.atoms:
						obj_output.write("HETATM{0:>5} {1:4} {2:3} {3:>1}{4:>4}    {5[0]:>8.3f}{5[1]:>8.3f}{5[2]:>8.3f}{6}{7}          {8}{9}\n".format(
							atom.number,
							atom.name,
							residue.name,
							chain.name,
							residue.number,
							self._coords[idx_atom],
							atom.occupancy,
							atom.temp_factor,
							atom.element,
							atom.charge
						))
						idx_atom += 1
				obj_output.write("TER\n")
			if len(self.connect_info) != 0:
				for connect in self.connect_info:
					obj_output.write("CONECT" + "".join(["{0:>5}".format(v) for v in connect]) + "\n")
			obj_output.write("END\n")
		return self

class Chain:
	def __init__(self, name):
		self._name = None
		self._residues = []

		self.set_name(name)

	@property
	def name(self):
		return self._name

	@property
	def residues(self):
		return self._residues

	def set_name(self, name):
		"""
		Chain に名前を設定するメソッド

		Args:
			name (str): Chain 名

		Returns:
			self
		"""
		self._name = name
		return self

	def append_residue(self, obj_Residue):
		"""
		残基オブジェクトを追加するメソッド

		Args:
			obj_Residue (obj_Residue): 残基オブジェクト

		Returns:
			self
		"""
		self._residues.append(obj_Residue)
		return self

	def set_residues(self, list_obj_Residues):
		"""
		残基オブジェクトを設定するメソッド

		Args:
			list_obj_Residues (list): [obj_Residue, ...]

		Returns:
			self
		"""
		self._residues = list_obj_Residues
		return self

	def remove_residue(self, remove_Residue):
		"""
		Residue オブジェクトを削除するメソッド

		Args:
			remove_Residue (obj_Residue): Residue オブジェクト

		Returns:
			self
		"""
		self._residues = [residue for residue in self._residues if residue is not remove_Residue]
		return self

class Residue:
	"""
	残基クラス (情報のみ)
	"""
	def __init__(self, name, number):
		self._name = None
		self._number = None
		self._atoms = []
		self._chain = None

		self.set_name(name)
		self.set_number(number)

	@property
	def name(self):
		return self._name

	@property
	def number(self):
		return self._number

	@property
	def unique(self):
		return "{0}-{1}-{2}".format(self._name, self._chain.name, self._number)

	@property
	def atoms(self):
		return self._atoms

	@property
	def chain(self):
		return self._chain

	def set_name(self, name):
		"""
		残基名を設定するメソッド

		Args:
			name (str): 残基名

		Returns:
			self
		"""
		self._name = name
		return self

	def set_number(self, number):
		"""
		残基インデックスを設定するメソッド

		Args:
			number (int): 残基インデックス

		Returns:
			self
		"""
		self._number = number
		return self

	def set_chain(self, obj_Chain):
		"""
		所属する Chain オブジェクトを設定するメソッド

		Args:
			obj_Chain (obj_Chain): 所属する Chain オブジェクト

		Returns:
			self
		"""
		self._chain = obj_Chain
		return self

	def append_atom(self, obj_atom):
		"""
		所属原子を追加するメソッド

		Args:
			obj_atom (obj_Atom): Atom オブジェクト

		Returns:
			self
		"""
		self._atoms.append(obj_atom)
		return self

	def set_atoms(self, list_obj_atoms):
		"""
		所属原子を設定するメソッド

		Args:
			list_obj_atoms (list): [obj_Atom, ...]

		Returns:
			self
		"""
		self._atoms = list_obj_atoms
		return self

	def remove_atom(self, remove_Atom):
		"""
		Atom オブジェクトを削除するメソッド

		Args:
			remove_Atom (obj_Atom): Atom オブジェクト

		Returns:
			self
		"""
		self._atoms = [atom for atom in self._atoms if atom is not remove_Atom]
		return self

class Atom:
	def __init__(self, name, number):
		self._name = None
		self._number = None
		self._chain = None
		self._residue = None
		self._occupancy = None
		self._temp_factor = None
		self._element = None
		self._charge = None
		self._connect = []

		self.set_name(name)
		self.set_number(number)

	@property
	def name(self):
		return self._name

	@property
	def number(self):
		return self._number

	@property
	def chain(self):
		return self._chain

	@property
	def residue(self):
		return self._residue

	@property
	def occupancy(self):
		occupancy = self._occupancy
		if occupancy is None:
			occupancy = 1.0
		return "{0:>6.2f}".format(occupancy)

	@property
	def temp_factor(self):
		temp_factor = self._temp_factor
		if temp_factor is None:
			temp_factor = 0.0
		return "{0:>6.2f}".format(temp_factor)

	@property
	def element(self):
		element = self._element
		if element is None:
			element = ""
		return "{0:>2}".format(element)

	@property
	def charge(self):
		charge = self._charge
		if charge is None:
			charge = ""
		return "{0:>2}".format(charge)

	@property
	def connect(self):
		return self._connect

	@property
	def connect_info(self):
		if len(self._connect) != 0:
			return [self.number] + [v.number for v in self._connect]
		return None

	def set_name(self, name):
		"""
		原子名を設定するメソッド

		Args:
			name (str): 原子名

		Returns:
			self
		"""
		self._name = name
		return self

	def set_number(self, number):
		"""
		原子インデックスを設定するメソッド

		Args:
			number (int): 原子インデックス

		Returns:
			self
		"""
		self._number = number
		return self

	def set_chain(self, obj_Chain):
		"""
		所属する Chain オブジェクトを設定するメソッド

		Args:
			obj_Chain (obj_Chain): 所属する Chain オブジェクト

		Returns:
			self
		"""
		self._chain = obj_Chain
		return self

	def set_residue(self, obj_Residue):
		"""
		所属する Residue オブジェクトを設定するメソッド

		Args:
			obj_Residue (obj_Residue): 所属する Residue オブジェクト

		Returns:
			self
		"""
		self._residue = obj_Residue
		return self

	def set_occupancy(self, occupancy):
		"""
		occupancy を設定するメソッド

		Args:
			occupancy (float): occupancy

		Returns:
			self
		"""
		self._occupancy = occupancy
		return self

	def set_temp_factor(self, temp_factor):
		"""
		temp factor を設定するメソッド

		Args:
			temp_factor (float): temp factor

		Returns:
			self
		"""
		self._temp_factor = temp_factor
		return self

	def set_element(self, element):
		"""
		元素を設定するメソッド

		Args:
			element (str): 元素名

		Returns:
			self
		"""
		self._element = element
		return self

	def set_charge(self, charge):
		"""
		電荷を設定するメソッド

		Args:
			charge (str): 電荷

		Returns:
			self
		"""
		self._charge = charge
		return self

	def set_connect(self, list_connect_obj_Atom):
		"""
		接続情報を設定するメソッド

		Args:
			list_connect_objAtom (list): [obj_Atom, ...]

		Returns:
			self
		"""
		self._connect = list_connect_obj_Atom
		return self

max_stars_repo_name: Tatsuya-Ohyama/grodock

max_issues_repo_name: Tatsuya-Ohyama/grodock

max_forks_repo_name: Tatsuya-Ohyama/grodock


text:
'''
lanhuage: python
Descripttion:
version: beta
Author: xiaoshuyui
Date: 2020-10-26 08:31:13
LastEditors: xiaoshuyui
LastEditTime: 2020-11-20 14:12:40
'''
import os
import xml.etree.ElementTree as ET

import numpy as np
import skimage
from convertmask.utils.methods.logger import logger
from convertmask.utils.xml2yolo.xml2yolo import convert as x2yVert
from convertmask.utils.yolo2xml.yolo2xml import convert as y2xVert

def resize_img(img: np.ndarray, heightFactor=1, widthFactor=1):
    if isinstance(img,str):
        img = skimage.io.imread(img)
    imgShape = img.shape
    resizedImg = skimage.transform.resize(
        img, (int(heightFactor * imgShape[0]), int(widthFactor * imgShape[1])))
    return np.array(resizedImg * 255).astype(np.uint8)

# def resize_xml(xmlpath:str, heightFactor=1, widthFactor=1):
#     pass

def resizeScript(img, xmlpath: str, heightFactor=1, widthFactor=1,flag=True):
    if isinstance(img, str) and os.path.exists(img):
        oriImg = skimage.io.imread(img)
    elif isinstance(img, np.ndarray):
        oriImg = img
    else:
        logger.error('Input error!')
        return

    in_file = open(xmlpath)
    tree = ET.parse(in_file)
    root = tree.getroot()

    parentPath, xmlFilename = os.path.split(xmlpath)
    xf, _ = os.path.splitext(xmlFilename)
    savePath = parentPath + os.sep + xf + '_reshape.xml'

    root.find('filename').text = xf + '_reshape.jpg'
    root.find('path').text = parentPath + os.sep + xf + '_reshape.jpg'

    resizeImg = resize_img(oriImg, heightFactor, widthFactor)
    resizeImgShape = resizeImg.shape
    width = int(resizeImgShape[1])
    height = int(resizeImgShape[0])

    size = root.find('size')
    size.find('width').text = str(width)
    size.find('height').text = str(height)

    for obj in root.iter('object'):
        xmlbox = obj.find('bndbox')
        b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text),
             float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
        # print('===========================')
        # print(b)
        bb = x2yVert((oriImg.shape[1], oriImg.shape[0]), b)

        x, y, w, h = bb[0], bb[1], bb[2], bb[3]
        # print(x, y, w, h)
        # w = w
        # h = h
        bbox = y2xVert((resizeImgShape[1],resizeImgShape[0]), x, y, w, h)
        # print(bbox)
        # print('===========================')
        xmlbox.find('xmin').text = str(int(bbox[0]))
        xmlbox.find('ymin').text = str(int(bbox[2]))
        xmlbox.find('xmax').text = str(int(bbox[1]))
        xmlbox.find('ymax').text = str(int(bbox[3]))

    if flag:  # save file
        tree.write(savePath)
        in_file.close()
        return resizeImg, savePath
    else:
        return tree


text:
#!/usr/bin/env python
#
# mgz2imageslices ds ChRIS plugin app
#
# (c) 2021 Fetal-Neonatal Neuroimaging & Developmental Science Center
#                   Boston Children's Hospital
#
#              http://childrenshospital.org/FNNDSC/
#                        dev@babyMRI.org
#

import logging
logging.disable(logging.CRITICAL)

import os
import sys
import traceback
from pydoc import synopsis

import numpy as np
import nibabel as nib
import imageio
import pandas as pd
import re
sys.path.append(os.path.dirname(__file__))
import  pfmisc
from    pfmisc._colors      import  Colors
from    pfmisc.debug        import  debug

import time
# import the Chris app superclass
from chrisapp.base import ChrisApp
from mgz2imgslices import mgz2imgslices

Gstr_title = """
                      _____ _                                 _ _
                     / __  (_)                               | (_)
 _ __ ___   __ _ ____`' / /'_ _ __ ___   __ _  __ _  ___  ___| |_  ___ ___  ___
| '_ ` _ \ / _` |_  /  / / | | '_ ` _ \ / _` |/ _` |/ _ \/ __| | |/ __/ _ \/ __|
| | | | | | (_| |/ / ./ /__| | | | | | | (_| | (_| |  __/\__ \ | | (_|  __/\__ \
|_| |_| |_|\__, /___|\_____/_|_| |_| |_|\__,_|\__, |\___||___/_|_|\___\___||___/
            __/ |                              __/ |
           |___/                              |___/
"""

class Mgz2imageslices(ChrisApp):
    """
    An app to ...
    """
    PACKAGE                 = __package__
    TITLE                   = 'A ChRIS plugin app'
    CATEGORY                = ''
    TYPE                    = 'ds'
    ICON                    = '' # url of an icon image
    MAX_NUMBER_OF_WORKERS   = 1  # Override with integer value
    MIN_NUMBER_OF_WORKERS   = 1  # Override with integer value
    MAX_CPU_LIMIT           = '' # Override with millicore value as string, e.g. '2000m'
    MIN_CPU_LIMIT           = '' # Override with millicore value as string, e.g. '2000m'
    MAX_MEMORY_LIMIT        = '' # Override with string, e.g. '1Gi', '2000Mi'
    MIN_MEMORY_LIMIT        = '' # Override with string, e.g. '1Gi', '2000Mi'
    MIN_GPU_LIMIT           = 0  # Override with the minimum number of GPUs, as an integer, for your plugin
    MAX_GPU_LIMIT           = 0  # Override with the maximum number of GPUs, as an integer, for your plugin

    # Use this dictionary structure to provide key-value output descriptive information
    # that may be useful for the next downstream plugin. For example:
    #
    # {
    #   "finalOutputFile":  "final/file.out",
    #   "viewer":           "genericTextViewer",
    # }
    #
    # The above dictionary is saved when plugin is called with a ``--saveoutputmeta``
    # flag. Note also that all file paths are relative to the system specified
    # output directory.
    OUTPUT_META_DICT = {}

    def define_parameters(self):
        """
        Define the CLI arguments accepted by this plugin app.
        Use self.add_argument to specify a new app argument.
        """

        self.add_argument('-i', '--inputFile',
                            dest        = 'inputFile',
                            type        = str,
                            optional    = False,
                            help        = 'name of the input file within the inputDir')

        self.add_argument('-o', '--outputFileStem',
                            dest        = 'outputFileStem',
                            type        = str,
                            optional    = True,
                            help        = 'output file',
                            default     = 'sample')

        self.add_argument('-t', '--outputFileType',
                            dest        = 'outputFileType',
                            type        = str,
                            default     = 'png',
                            optional    = True,
                            help        = 'output image file format')

        self.add_argument('--saveImages',
                            dest        = 'saveImages',
                            type        = bool,
                            action      = 'store_true',
                            default     = False,
                            optional    = True,
                            help        = 'store png images for each slice of mgz file')

        self.add_argument('--label',
                            dest        = 'label',
                            type        = str,
                            default     = 'label',
                            optional    = True,
                            help        = 'prefix a label to all the label directories')

        self.add_argument('-n', '--normalize',
                            dest        = 'normalize',
                            type        = bool,
                            action      = 'store_true',
                            default     = False,
                            optional    = True,
                            help        = 'normalize the pixels of output image files')

        self.add_argument('-l', '--lookupTable',
                            dest        = 'lookupTable',
                            type        = str,
                            default     = '__none__',
                            optional    = True,
                            help        = 'reads name for the Label directories')

        self.add_argument('-y', '--synopsis',
                            dest        = 'synopsis',
                            type        = bool,
                            action      = 'store_true',
                            default     = False,
                            optional    = True,
                            help        = 'short synopsis')

        self.add_argument('--skipAllLabels',
                            dest        = 'skipAllLabels',
                            type        = bool,
                            action      = 'store_true',
                            default     = False,
                            optional    = True,
                            help        = 'skip all labels and create only whole Volume images')

        self.add_argument('-s', '--skipLabelValueList',
                            dest        = 'skipLabelValueList',
                            type        = str,
                            default     = '',
                            optional    = True,
                            help        = 'Comma separated list of labels to skip')

        self.add_argument('-f', '--filterLabelValueList',
                            dest        = 'filterLabelValueList',
                            type        = str,
                            default     = '-1',
                            optional    = True,
                            help        = 'Comma separated list of voxel values to include')

        self.add_argument('-w', '--wholeVolume',
                            dest        ='wholeVolume',
                            type        = str,
                            default     = "wholeVolume",
                            optional    = True,
                            help        = 'Converts entire mgz volume to png/jpg instead of individually masked labels')

        self.add_argument('--printElapsedTime',
                            dest        = 'printElapsedTime',
                            type        = bool,
                            action      = 'store_true',
                            default     = False,
                            optional    = True,
                            help        = 'print program run time')

        self.add_argument("--verbose",
                            type        = str,
                            optional    = True,
                            help        = "verbosity level for app",
                            dest        = 'verbose',
                            default     = "1")

    def run(self, options):
        """
        Define the code to be run by this plugin app.
        """
        # The med2image module has slightly different variable
        # names for the same concept... convert from the plugin
        # name to the module name:

        options.inputDir = options.inputdir
        options.outputDir = options.outputdir
        options.verbosity = options.verbose

        imgConverter = mgz2imgslices.object_factoryCreate(options).C_convert

        if options.version:
            print("Version: %s" % options.version)
            sys.exit(1)

        if options.man or options.synopsis:
            if options.man:
                str_help = self.show_man_page(False)
            else:
                str_help = self.show_man_page(True)
            print(str_help)
            sys.exit(1)

        imgConverter.tic()
        imgConverter.run()

        # if b_dicomExt:
        #     break

        if options.printElapsedTime:
            print("Elapsed time = %f seconds" % imgConverter.toc())
            sys.exit(0)

    def show_man_page(self, ab_shortOnly=False):
        scriptName = os.path.basename(sys.argv[0])
        shortSynopsis = '''
        NAME

    	    pl-mgz2imgslices - convert mgz volumes to jpg/png/etc.

        SYNOPSIS
            -i|--inputFile <inputFile>                                  \\
            -d|--outputDir <outputDir>                                  \\
            [-I|--inputDir <inputDir>]                                  \\
            [-o|--outputFileStem]<outputFileStem>]                      \\
            [-t|--outputFileType <outputFileType>]                      \\
            [--saveImages]                                              \\
            [--label <prefixForLabelDirectories>]                       \\
            [-n|--normalize]                                            \\
            [-l|--lookupTable <LUTfile>]                                \\
            [--skipAllLabels]                                           \\
            [-s|--skipLabelValueList <ListOfVoxelValuesToSkip>]         \\
            [-f|--filterLabelValueList <ListOfVoxelValuesToInclude>]    \\
            [-w|--wholeVolume <wholeVolDirName>]                        \\
            [-h|--help]                                                 \\
            [--json]                                                    \\
            [--man]                                                     \\
            [--meta]                                                    \\
            [--savejson <DIR>]                                          \\
            [-v|--verbosity <level>]                                    \\
            [--version]                                                 \\
            [-y|--synopsis]

        '''

        description = '''
        DESCRIPTION

        ``mgz2imgslices`` is a simple Python utility that filters "labels"
        from ``mgz`` volume files and saves each label set as slices of
        (by default) ``png`` files, organized into a series of directories,
        one per label set.

        An ``mgz`` format file simply contains a 3D volume data structure of
        image values. Often these values are interpreted to be image
        intensities. Sometimes, however, they can be interpreted as label
        identifiers. Regardless of the interpretation, the volume image data
        is simply a number value in each voxel of the volume.

        This script will scan across the input ``mgz`` volume, and for each
        voxel value create a new output directory. In that directory will be
        a set of (typically) ``png`` images, one per slice of the original
        volume. These images will only contain the voxels in the original
        dataset that all had that particular voxel value.

        In this manner, ``mgz2imgslices`` can also be thought of as a dynamic
        filter of an ``mgz`` volume file that filters each voxel value into
        its own output directory of ``png`` image files.

        ARGS

            [-i|--inputFile  <inputFile>]
            Input file to convert. Should be an ``mgz`` file.

            [-o|--outputFileStem <outputFileStem>]
            The output file stem to store image conversion. If this is specified
            with an extension, this extension will be used to specify the
            output file type.

            [-t|--outputFileType <outputFileType>]
            The output file type. If different to <outputFileStem> extension,
            will override extension in favour of <outputFileType>.

            Should be a ``png``.

            [--saveImages]
            If specified as True(boolean), will save the slices of the mgz file as
            ".png" image files along with the numpy files.

            [--label <prefixForLabelDirectories>]
            Prefixes the string <prefixForLabelDirectories> to each filtered
            directory name. This is mostly for possible downstream processing,
            allowing a subsequent operation to easily determine which of the output
            directories correspond to labels.

            [-n|--normalize]
            If specified, will normalize the output image pixel values to
            0 and 1, otherwise pixel image values will retain the value in
            the original input volume.

            [-l|--lookupTable <LUTfile>]
            If passed, perform a lookup on the filtered voxel label values
            according to the contents of the <LUTfile>. This <LUTfile> should
            conform to the FreeSurfer lookup table format (documented elsewhere).

            Note that the special <LUTfile> string ``__val__`` can be passed which
            effectively means "no <LUTfile>". In this case, the numerical voxel
            values are used for output directory names. This special string is
            really only useful for scripted cases of running this application when
            modifying the CLI is more complex than simply setting the <LUTfile> to
            ``__val__``.

            [--skipAllLabels]
            Skips all labels and converts only the whole mgz volume to png/jpg images.

            [-s|--skipLabelValueList <ListOfLabelNumbersToSkip>]
            If specified as a comma separated string of label numbers,
            will not create directories of those label numbers.

            [-f|--filterLabelValueList <ListOfVoxelValuesToInclude>]
            The logical inverse of the [skipLabelValueList] flag. If specified,
            only filter the comma separated list of passed voxel values from the
            input volume.

            The default value of "-1" implies all voxel values should be filtered.

            [-w|--wholeVolume <wholeVolDirName>]
            If specified, creates a diretory called <wholeVolDirName> (within the
            outputdir) containing PNG/JPG images files of the entire input.

            This effectively really creates a PNG/JPG conversion of the input
            mgz file.

            Values in the image files will be the same as the original voxel
            values in the ``mgz``, unless the [--normalize] flag is specified
            in which case this creates a single-value mask of the input image.

            [-h|--help]
            If specified, show help message and exit.

            [--json]
            If specified, show json representation of app and exit.

            [--man]
            If specified, print (this) man page and exit.

            [--meta]
            If specified, print plugin meta np_data and exit.

            [--savejson <DIR>]
            If specified, save json representation file to DIR and exit.

            [-v <level>|--verbosity <level>]
            Verbosity level for app. Not used currently.

            [--version]
            If specified, print version number and exit.

            [-y|--synopsis]
            Show short synopsis.

        GITHUB

            o See https://github.com/FNNDSC/mgz2imgslices for more help and source.

                '''

        if ab_shortOnly:
            print(shortSynopsis)
        else:
            print(shortSynopsis + description)


text:
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch as T
import numpy as np
# from .callbacks import state_to_features # probably do this instead or change state_to_features to here
from .StateToFeat import state_to_features

ACTIONS = ['UP', 'RIGHT', 'DOWN', 'LEFT', 'WAIT', 'BOMB']

class DQN(nn.Module):
    gamma = 0.9  # 0.9
    learning_rate = 0.0003

    def __init__(self, dim_in, dim_out):
        super(DQN, self).__init__()
        self.model_sequence = nn.Sequential(
            nn.Linear(dim_in, dim_out)
        )
        self.loss = nn.MSELoss()
        self.optimizer = optim.Adam(self.parameters(), self.learning_rate)
        self.device = T.device('cuda' if T.cuda.is_available() else 'cpu')
        self.to(self.device)

    def forward(self, x):
        x = T.tensor(state_to_features(x)).float()
        return self.model_sequence(x.to(self.device)).to('cpu')

    def train_step(self, old_state, action, new_state, reward):
        if action is not None:
            action_mask = T.zeros(len(ACTIONS), dtype=T.int64)
            action_mask[ACTIONS.index(action)] = 1

            state_action_value = T.masked_select(self.forward(old_state), action_mask.bool())
            next_state_action_value = self.forward(new_state).max().unsqueeze(0)
            expected_state_action_value = (next_state_action_value * self.gamma) + reward

            loss = self.loss(state_action_value.to(self.device), expected_state_action_value.to(self.device))
            with open("loss_log.txt", "a") as loss_log:
                loss_log.write(str(loss.item()) + "\t")
            self.optimizer.zero_grad()
            loss.backward()
            self.optimizer.step()

    def train_step_bad(self, old_state, action, new_state, reward):
        if action is not None:
            reward_tensor = T.zeros(len(ACTIONS), dtype=T.int64)
            reward_tensor[ACTIONS.index(action)] = reward

            state_action_value = self.forward(old_state)
            next_state_action_value = self.forward(new_state)
            expected_state_action_value = (next_state_action_value * self.gamma) + reward

            loss = self.loss(state_action_value.to(self.device), expected_state_action_value.to(self.device))
            with open("loss_log.txt", "a") as loss_log:
                loss_log.write(str(loss.item()) + "\t")
            self.optimizer.zero_grad()
            loss.backward()
            self.optimizer.step()

    def train_step_very_bad(self, old_state, action, new_state, reward):
        if action is not None:
            action_mask = T.zeros(len(ACTIONS), dtype=T.int64)
            choice_range = np.arange(len(ACTIONS), dtype=np.int64)
            choice_mask = T.zeros(len(ACTIONS), dtype=T.int64)
            action_mask[ACTIONS.index(action)] = 1
            next_state_val = self.forward(new_state)
            chosen_index = np.random.choice(choice_range, p=F.softmax(next_state_val, dim=1)[0].detach().numpy())
            choice_mask[chosen_index] = 1
            # np.random.choice(ACTIONS, p=F.softmax(self.model.forward(game_state), dim=1)[0].detach().numpy())
            # p=F.softmax(self.model.forward(game_state), dim=1)[0].detach().numpy()

            state_action_value = T.masked_select(self.forward(old_state), action_mask.bool())
            next_state_action_value = T.masked_select(next_state_val, choice_mask.bool())
            # next_state_action_value = self.forward(new_state).max().unsqueeze(0)
            expected_state_action_value = (next_state_action_value * self.gamma) + reward

            loss = self.loss(state_action_value.to(self.device), expected_state_action_value.to(self.device))
            with open("loss_log.txt", "a") as loss_log:
                loss_log.write(str(loss.item()) + "\t")
            self.optimizer.zero_grad()
            loss.backward()
            self.optimizer.step()

max_stars_repo_name: stefanDeveloper/bomberman

max_issues_repo_name: stefanDeveloper/bomberman

max_forks_repo_name: stefanDeveloper/bomberman


text:
"""

.. module:: data_structures
    :synopsis: Data structure for Isotope and Ratio data.

.. moduleauthor:: Joshua Rehak <jsrehak@berkeley.edu>

"""

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

try:
    from pyevtk.hl import gridToVTK
except ImportError:
    print("Unable to load pvevtk, output to VTK will be disabled")

class IsotopeData(object):
    """ Create an IsotopeData file for an isotope with given name, and data.

    :param isotope_label: Name of the isotope.
    :type isotope_label: string

    :param isotope_data: The data for the given isotope.
    :type isotope_data: 3D `numpy` array
    """

    def __init__(self, isotope_label, isotope_data):
        self._label = isotope_label
        self._data = np.array(isotope_data, dtype=float)
        self._is_deadtime_corrected = False

    def get_label(self):
        return self._label

    def __leq__(self, value):
        return self._data <= value

    def __lt__(self, value):
        return self._data < value

    def __gt__(self, value):
        return self._data > value

    def get_data(self, mask=None):
        """ Return the isotope's data. Optionally include a mask to return a \
        numpy masked array.

        :param mask: mask to apply to the data.
        :type mask: numpy bool array.
        """
        if type(mask) is np.ndarray:
            return ma.array(self._data, mask = mask)
        else:
            return self._data

    def get_mask(self, lower=0, upper=np.Inf):
        """Return a mask that will mask all data outside of the bounds given. \
           note that the numpy mask sets values that *will* be masked to True.

        :param lower: lower bound for mask (default 0), values less than or equal to this \
                      will be masked.
        :type type: float

        :param upper: upper bound for mask (default infinity) , values more \
                      than this will be masked.
        :type upper: float

        """
        return np.logical_or(self._data <= lower, self._data > upper)

    def n_cycles(self):
        return np.shape(self._data)[0]

    def n_pixels(self, mask = None):
        """Returns the total number of pixels in the dataset. Optionally masked \
        to return the number of *non-masked* entries.

        :param mask: mask to apply to the data.
        :type mask: numpy bool array
        """
        if type(mask) == np.ndarray:
            return ma.array(self._data, mask = mask).count()
        else:
            return self._data.size

    def perform_deadtime_correction(self, dwell_time, dead_time):
        r""" Perform deadtime correction on the count data:\

        .. math:: n=\frac{n_0}{1-n_0\tau}

        using dead time, :math:`\tau`, and :math:`n_0` is in counts per second:\

        .. math:: n_0=\frac{n}{T}

        where :math:`n` is the counts, and :math:`T` is the dwell time.

        .. important::  Dwell time and dead time may be in any unit of time as \
           long as they are in the *same* units.

        :param dwell_time: Dwell time.
        :type dwell_time: float

        :param dead_time: Dead time.
        :type dead_time: float
        """
        # Prevent applying deadtime correction twice
        if self._is_deadtime_corrected:
            raise RuntimeError("Error: Isotope " + self._label +
                               " is already deadtime corrected")

        print("Deadtime correction: isotope: " + self._label + ";\tdwell_time: " +
              str(dwell_time) + ";\tdead_time: " + str(dead_time))

        self._dwell_time = dwell_time
        self._dead_time = dead_time

        # Perform deadtime correction
        count_rate = np.divide(self._data, dwell_time)
        self._data = np.divide(count_rate,
                               1 - np.multiply(count_rate, dead_time))
        self._data *= dwell_time
        self._is_deadtime_corrected = True

    def plot(self, mask=None):
        """ Plot the isotope, with desired mask.

        :param mask: Mask to be used.
        :type mask: numpy bool array
        """

        # Get plot data
        if type(mask) is np.ndarray:
            plot_data = ma.masked_array(self._data, mask = mask)
            vmin = ma.min(plot_data)
            vmax = ma.max(plot_data)
        else:
            plot_data = self._data
            vmin = np.min(plot_data)
            vmax = np.max(plot_data)

        x = range(np.shape(plot_data)[1])
        y = range(np.shape(plot_data)[2])
        z_max = np.shape(plot_data)[0]
        X, Y = np.meshgrid(x,y)

        fig = plt.figure()
        ax = fig.add_subplot(111, projection = '3d')

        for z in range(z_max):
            x_y_data = plot_data[z, :, :]
            contour = ax.contourf(X, Y, x_y_data, zdir='z', offset=-z, alpha = 1,
                                  cmap = "CMRmap", vmin=vmin, vmax=vmax)

        cbar = fig.colorbar(contour, ax = ax)

        cbar.ax.set_xlabel("Counts")

        ax.set_zlim((-z_max,0))
        ax.set_zlim((-z_max,0))
        ax.set_xlabel("X (px)")
        ax.set_ylabel("Y (px)")
        ax.set_zlabel("Planes")
        ax.set_aspect('equal')
        ax.invert_xaxis()
        ax.view_init(elev=45, azim=45)

        values = "Min value: " + str(vmin) + " Max value: " + str(vmax);
        fig.text(x=0.2, y=0.02, s=values)

        plt.show()

    def trim_back(self, n):
        """ Removes the last n cycles from the dataset

        :param n: number of cycles to remove.
        :type n: int
        """
        z_max = np.shape(self._data)[0]
        if n > z_max:
            raise RuntimeError("trim amount: " + str(n) +
                               " exceeds number of cycles: " + str(z_max))
        self._data = self._data[:z_max-n]

    def trim_front(self, n):
        """ Removes the first n cycles from the dataset

        :param n: number of cycles to remove.
        :type n: int
        """
        z_max = np.shape(self._data)[0]
        if n > z_max:
            raise RuntimeError("trim amount: " + str(n) +
                               " exceeds number of cycles: " + str(z_max))
        self._data = self._data[n:]

    def roll_data(self, x_roll=0, y_roll=0):
        """ Rolls the data in the dataset: moves a given number of rows of data
            in the specified direction from the end of the dataset to the front,
            or vice-versa. For example, setting x_roll=1 will move one row from
            the end of the dataset in the x-direction to the beginning of the
            x-direction. Rolling again with x_roll=-1 will undo this.

        :param x_roll: amount to roll in the x-direction
        :type x_roll: int

        :param y_roll: amount to roll in the y-direction
        :type y_roll: int
        """
        for i, cycle in enumerate(self._data):
            self._data[i] = np.roll(cycle, [x_roll, y_roll], axis = [0, 1])

    def sum(self, mask=None):
        """ Returns the sum of all the data in the dataset, with optional masking.

        :param mask: numpy mask array.
        :type mask: numpy array, optional)
        """
        masked_array = np.ma.array(self._data, mask=mask)
        return masked_array.sum()

    def to_VTK(self, filename, x_roll=0, y_roll=0, mask=None): #pragma: no cover

        to_output = np.ma.array(self._data, mask=mask, fill_value=-1).filled()

        output_data = np.zeros_like(self._data)

        for i, cycle in enumerate(to_output):
            output_data[i] = np.roll(cycle, [x_roll,y_roll], axis=[0,1])
        output_data = np.swapaxes(output_data, 0, 2)

        (nx, ny, nz) = np.shape(output_data)

        # Coordinates
        X = np.arange(0, nx + 1, 1, dtype='float64')
        Y = np.arange(0, ny + 1, 1, dtype='float64')
        Z = np.arange(0, nz + 1, 1, dtype='float64')

        gridToVTK(filename, X, Y, Z, cellData = {self._label : output_data})

    def __str__(self):
        return_string = "label: " + self._label + "; "
        return_string += "\tData size: " + str(np.shape(self._data))
        return_string += "\n\t Corrections: "
        if self._is_deadtime_corrected:
            return_string += "deadtime"
        return return_string

class RatioData(IsotopeData):
    r""" Create a datafile containing the ratios of two isotope data sets.\

    .. math::
       R =
       \begin{cases}
       \frac{I_n}{I_d} & I_d \neq 0 \\ 0 & I_d = 0
       \end{cases}

    where :math:`I_n` is the numerator isotope, and :math:`I_d` is the \
    denominator isotope.
    """

    def __init__(self, label, numerator_isotope, denominator_isotope):
        self._label = label
        numerator_data = numerator_isotope.get_data()
        denominator_data = denominator_isotope.get_data()
        self._data = np.divide(numerator_data, denominator_data,
                               out=np.zeros_like(denominator_data),
                               where=denominator_data!=0)

    def perform_deadtime_correction(self, dwell_time, dead_time):
        """ Should not be run on RatioData, returns a Runtimeerror, perform\
        deadtime correction prior to calculating the ratio"""
        raise RuntimeError("Deadtime correction cannot be performed on a ratio")


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

def save_fig(fname):
    figdir = os.path.join(os.environ["PYPROBML"], "figures")
    plt.tight_layout()
    fullname = os.path.join(figdir, fname)
    print('saving to {}'.format(fullname))
    plt.savefig(fullname)

np.random.seed(0)
N = 5000
r = 2
xs = np.random.uniform(low=-r, high=r, size=N)
ys = np.random.uniform(low=-r, high=r, size=N)
rs = xs ** 2 + ys ** 2
inside = (rs <= r**2)
samples = 4*(r**2)*inside
Ihat = np.mean(samples)
pi_estimate = Ihat/(r**2)
se = np.sqrt(np.var(samples)/N)
print(('the estimated pi = %f' % pi_estimate))
print(('the standard pi = %f' % np.pi))
print(('stderr = %f' % se))

plt.figure(figsize=(5, 5))
plt.plot(xs[inside], ys[inside], 'bo')
plt.plot(xs[~inside], ys[~inside], 'rD')

save_fig('mcEstimatePi.pdf')
plt.show()


text:
""" Tests for skspec.core.Spectra class.  Much inspiration was taken from the pandas
amazing test suite, so thank you to the pandas team for such diligence.

https://github.com/pydata/pandas/blob/master/pandas/tests/test_frame.py
"""

from copy import deepcopy

import sys
import operator
import nose

from numpy import random, nan
from numpy.random import randn
import numpy as np
import numpy.ma as ma
from numpy.testing import assert_array_equal
import numpy.ma.mrecords as mrecords

max_stars_repo_name: hugadams/scikit-spectra

max_issues_repo_name: hugadams/scikit-spectra

max_forks_repo_name: hugadams/scikit-spectra

reason: import numpy,from numpy


text:
# -*- coding: utf-8 -*-
"""
Created on Thu Jun  3 17:05:31 2021

@author: Luigi
"""

import numpy as np
import sympy as sym
import sympy.utilities.lambdify
import allMethods as fz

x = sym.symbols("x")
fx = sym.atan(x)
dfx = sym.diff(fx, x, 1)

f = sym.lambdify(x, fx, np)
df = sym.lambdify(x, dfx, np)

x0 = [1.2, 1.4]
tolx = 1e-6
tolf = 1e-5

for el in x0:
    xk, it, xks = fz.newton(f, df, el, tolx, tolf, 500)
    print("Con xo = {:f} abbiamo xk = {:e} con {:d} iterazioni".format(el,xk,it))

reason: import numpy,import sympy


text:
import argparse
import sys

import numpy as np

import torch.nn as nn
from torch.autograd import Variable
from torch.optim import SGD
from torch.utils.data import DataLoader

from util.util import enumerateWithEstimate
from .dsets import LunaDataset, getCtSampleSize
from util.logconf import logging
# from .model import LunaModel

log = logging.getLogger(__name__)
# log.setLevel(logging.WARN)
log.setLevel(logging.INFO)
# log.setLevel(logging.DEBUG)

class LunaPrepCacheApp:
    @classmethod
    def __init__(self, sys_argv=None):
        if sys_argv is None:
            sys_argv = sys.argv[1:]

        parser = argparse.ArgumentParser()
        parser.add_argument('--batch-size',
            help='Batch size to use for training',
            default=1024,
            type=int,
        )
        parser.add_argument('--num-workers',
            help='Number of worker processes for background data loading',
            default=8,
            type=int,
        )
        # parser.add_argument('--scaled',
        #     help="Scale the CT chunks to square voxels.",
        #     default=False,
        #     action='store_true',
        # )

        self.cli_args = parser.parse_args(sys_argv)

    def main(self):
        log.info("Starting {}, {}".format(type(self).__name__, self.cli_args))

        self.prep_dl = DataLoader(
            LunaDataset(
                sortby_str='series_uid',
            ),
            batch_size=self.cli_args.batch_size,
            num_workers=self.cli_args.num_workers,
        )

        batch_iter = enumerateWithEstimate(
            self.prep_dl,
            "Stuffing cache",
            start_ndx=self.prep_dl.num_workers,
        )
        for batch_ndx, batch_tup in batch_iter:
            pass

if __name__ == '__main__':
    LunaPrepCacheApp().main()

max_stars_repo_name: Andi-Nov/PyTorch

max_issues_repo_name: Andi-Nov/PyTorch

max_forks_repo_name: Andi-Nov/PyTorch


text:
"""
this is the file to pre-process the raw data to the data pack
the data pack including: images, touch center, touch radius

Keyboard control:
left/right/up/down: control the circle's location
m/p: decrease/increase the circle's radius
f/c: decrease/increase the circle's moving step
"""

import gc
from glob import glob
from os import path as osp
import cv2
import numpy as np
import argparse

import nanogui as ng
from nanogui import Texture
from nanogui import glfw

# define the image size, should be consistent with the raw data size
w, h = 640, 480

parser = argparse.ArgumentParser()
parser.add_argument("-data_path", nargs='?', default='../data/calib_ball/',
                    help="Path to the collected raw tactile data.")
args = parser.parse_args()

class Circle:
  """the circle drawed on the tactile image to get the contact size"""
  color_circle = (0, 128, 0)
  radius = 75
  increments = 4
  opacity = 0.5
  def __init__(self, w, h):
    self.center = [h/2,w/2]

class CalibrateApp(ng.Screen):
  fnames = list()
  read_all = False
  load_img = True
  change = False
  bg_img_fn = None
  bg_id = None
  imgs = []
  touch_centers = []
  touch_radius = []
  names = []

  def __init__(self, data_path):
    super(CalibrateApp, self).__init__((1024, 768), "Gelsight Calibration App")

    window = ng.Window(self, "IO Window")
    window.set_position((15, 15))
    window.set_layout(ng.GroupLayout())

    ng.Label(window, "Folder dialog", "sans-bold")
    tools = ng.Widget(window)
    tools.set_layout(ng.BoxLayout(ng.Orientation.Horizontal,
                              ng.Alignment.Middle, 0, 6))
    b = ng.Button(tools, "Open")

    def cb():
        self.img_data_dir = ng.directory_dialog(data_path)
        print("Selected directory = %s" % self.img_data_dir)

        # check for background Frame
        # obtains fnames(currently accepts jpg/ppm/png)
        self.fnames = glob(osp.join(self.img_data_dir, "*.jpg")) +\
              glob(osp.join(self.img_data_dir, "*.ppm")) +\
              glob(osp.join(self.img_data_dir, "*.png")) +\
              glob(osp.join(self.img_data_dir, "*.jpeg"))
        self.fnames = sorted(self.fnames, key=lambda y: int(y.split("_")[-1].split(".")[0]))

        self.next_img_num = 0
        self.background_check(self.fnames)

    b.set_callback(cb)

    # image view
    self.img_window = ng.Window(self, "Current image")
    self.img_window.set_position((200, 15))
    self.img_window.set_layout(ng.GroupLayout())

    b = ng.Button(self.img_window, "Calibrate")
    # Calibrate button
    def calibrate_cb():
      list_to_name = self.fnames[self.next_img_num].split("/")
      frame = self.orig_img
      touch_center = self.circle.center
      radius = self.circle.radius
      print("the radius for frame {} is {}".format(self.next_img_num,radius))
      self.imgs.append(frame)
      self.touch_centers.append(touch_center)
      self.touch_radius.append(radius)
      self.names.append(list_to_name[-1])
      # Update img index
      self.load_img = True
      self.update_img_idx()

    b.set_callback(calibrate_cb)

    b = ng.Button(self.img_window, "Skip")
    # Calibrate button
    def skip_cb():
      print("Skip a frame")
      # Update img index
      self.load_img = True
      self.update_img_idx()

    b.set_callback(skip_cb)

    b = ng.Button(self.img_window, "Save Params")
    def cb():
      out_fn_path = osp.join(self.img_data_dir, "dataPack.npz")
      print("Saving params to %s"%out_fn_path)
      np.savez(out_fn_path,\
        f0 = self.bg_img,
        imgs = self.imgs,
        touch_center = self.touch_centers,
        touch_radius = self.touch_radius,
        names = self.names,
        img_size = self.bg_img.shape)
      print("Saved!")
    b.set_callback(cb)

    self.img_view = ng.ImageView(self.img_window)

    self.img_tex = ng.Texture(
                      pixel_format=Texture.PixelFormat.RGB,
                      component_format=Texture.ComponentFormat.UInt8,
                      size=[w, h],
                      min_interpolation_mode=Texture.InterpolationMode.Trilinear,
                      mag_interpolation_mode=Texture.InterpolationMode.Nearest,
                      flags=Texture.TextureFlags.ShaderRead | Texture.TextureFlags.RenderTarget
                  )

    self.perform_layout()

  def background_check(self, fnames):
    found = False
    for fnId, fn in enumerate(fnames):
      baseFn = osp.basename(fn)
      if(baseFn == "frame_0.ppm" or \
          baseFn == "frame_0.jpg" or \
          baseFn == "frame_0.png" or \
          baseFn == "ball0.jpeg"):
        self.bg_img_fn = fn
        self.bg_id = fnId

        self.bg_img = cv2.imread(self.bg_img_fn)
        found = True
        break

    if not found:
      print("No background Image Found! Looking for frame_0.ppm/frame0.jpg/frame0.png")
      self.set_visible(False)

  def update_img_idx(self):
    self.next_img_num += 1
    if(self.next_img_num == len(self.fnames)): self.read_all = True

  def overlay_circle(self,orig_img, circle):
    center = circle.center
    radius = circle.radius
    color_circle = circle.color_circle
    opacity = circle.opacity

    overlay = orig_img.copy()
    center_tuple = (int(center[0]), int(center[1]))
    cv2.circle(overlay, center_tuple, radius, color_circle, -1)
    cv2.addWeighted(overlay, opacity, orig_img, 1 - opacity, 0, overlay)
    return overlay

  def draw(self, ctx):
    # self.img_window.set_size((700,700))
    self.img_window.set_size((2000,2600))
    self.img_view.set_size((w, h))

    # load a new image
    if (self.load_img and len(self.fnames) > 0 and not self.read_all):
      if(self.next_img_num == self.bg_id): self.update_img_idx()
      print("Loading %s"%self.fnames[self.next_img_num])

      # Load img
      self.orig_img = cv2.imread(self.fnames[self.next_img_num])
      size = self.orig_img.shape
      self.circle = Circle(size[0], size[1])

    # Add circle and add img to viewer
    if((self.load_img and len(self.fnames) > 0) or self.change):
      self.load_img = False
      self.change = False
      # Add circle
      img = self.overlay_circle(self.orig_img, self.circle)

      if(self.img_tex.channels() > 3):
        height, width = img.shape[:2]
        alpha = 255*np.ones((height, width,1), dtype=img.dtype)
        img = np.concatenate((img, alpha), axis=2)

      # Add to img view
      self.img_tex.upload(img)
      self.img_view.set_image(self.img_tex)

    super(CalibrateApp, self).draw(ctx)

  def keyboard_event(self, key, scancode, action, modifiers):
    if super(CalibrateApp, self).keyboard_event(key, scancode,
                                          action, modifiers):
        return True
    if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
        self.set_visible(False)
        return True
    elif key == glfw.KEY_C:
      self.circle.increments *= 2
    elif key == glfw.KEY_F:
      self.circle.increments /= 2
    else:
      self.change = True
      if(key == glfw.KEY_LEFT):
        self.circle.center[0] -= self.circle.increments
      elif(key == glfw.KEY_RIGHT):
        self.circle.center[0] += self.circle.increments
      elif(key == glfw.KEY_UP):
        self.circle.center[1] -= self.circle.increments
      elif(key == glfw.KEY_DOWN):
        self.circle.center[1] += self.circle.increments
      elif key == glfw.KEY_M:
        self.circle.radius -= 1
      elif key == glfw.KEY_P:
        self.circle.radius += 1

    return False

if __name__ == "__main__":
  ng.init()
  app = CalibrateApp(args.data_path)
  app.draw_all()
  app.set_visible(True)
  ng.mainloop(refresh=1 / 60.0 * 1000)
  del app
  gc.collect()
  ng.shutdown()

max_stars_repo_name: CMURoboTouch/Taxim

max_issues_repo_name: radhen/Taxim

max_forks_repo_name: radhen/Taxim


text:
import os.path
import numpy as np
import matplotlib.pyplot as plt
from argparse import ArgumentParser
from sklearn.metrics import r2_score, mean_absolute_error
from typing import List

from adaptiveleak.utils.file_utils import save_json, iterate_dir, read_json

def get_energy(folder: str) -> float:
    energy_path = os.path.join(folder, 'energy.json')
    energy_dict = read_json(energy_path)
    return float(np.median(energy_dict['energy']))

def plot(num_bytes: np.ndarray, energy: np.ndarray, energy_pred: np.ndarray, output_path: str):
    with plt.style.context('seaborn-ticks'):
        fig, ax = plt.subplots()

        ax.scatter(num_bytes, energy, marker='o', label='True')
        ax.plot(num_bytes, energy_pred, label='Pred')

        ax.set_xlabel('Num Bytes')
        ax.set_ylabel('Energy (mJ)')
        ax.set_title('Energy (mJ) per Operation for Multiple Sizes')

        plt.savefig(output_path)

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('--folder', type=str, required=True)
    args = parser.parse_args()

    base = args.folder

    bytes_list: List[int] = []
    energy_list: List[float] = []

    # Get the energy for each trace folder
    for trace_folder in iterate_dir(base, pattern='.*'):
        name = os.path.split(trace_folder)[-1]

        try:
            num_bytes = int(name)
            energy = get_energy(folder=trace_folder)

            bytes_list.append([[num_bytes, 1]])
            energy_list.append(energy)
        except ValueError:
            continue

    X = np.vstack(bytes_list)  # [N, 2]
    y = np.vstack(energy_list)  # [N]
    reg = 0.01 * np.eye(X.shape[-1])

    weights = np.linalg.solve(X.T.dot(X) + reg, X.T.dot(y))  # [2]

    w = weights[0]
    b = weights[1]

    ypred = X.dot(weights)  # [N]

    plot(num_bytes=X[:, 0],
         energy=y,
         energy_pred=ypred,
         output_path=os.path.join(base, 'fit.pdf'))

    result = {
        'w': float(w),
        'b': float(b)
    }

    save_json(result, os.path.join(base, 'model.json'))

max_stars_repo_name: tejaskannan/adaptive-sensor-security

max_issues_repo_name: tejaskannan/adaptive-sensor-security

max_forks_repo_name: tejaskannan/adaptive-sensor-security