code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import numpy as np
import gym
import sys
import rospy
from quads_msgs.msg import Transition
from std_msgs.msg import Empty
class BaxterHwEnv(gym.Env):
def __init__(self):
# Calling init method of parent class.
super(BaxterHwEnv, self).__init__()
# Setting name of ros node.
self._name = rospy.get_name() + "/Environment"
# Loading parameters for dynamics
if not self.load_parameters(): sys.exit(1)
if not self.register_callbacks(): sys.exit(1)
# Set up observation space and action space.
NUM_PREPROCESSED_STATES = 21
NUM_ACTION_DIMS = 56
self.observation_space = gym.spaces.Box(-np.inf, np.inf, (NUM_PREPROCESSED_STATES,))
self.action_space = gym.spaces.Box(-np.inf, np.inf, (NUM_ACTION_DIMS,))
# Queue of state transitions observed in real system with current policy.
self._transitions = []
self._num_steps = 0
def step(self):
""" Return x, r, u, done. """
while len(self._transitions) == 0 and not rospy.is_shutdown():
rospy.logwarn_throttle(10.0, "%s: Out of transitions." % self._name)
rospy.sleep(0.01)
if rospy.is_shutdown():
return None
transition = self._transitions.pop(0)
x = np.array(transition.x)
a = np.array(transition.a)
r = transition.r
done = False
if self._num_steps > 25:
self._num_steps = 0
done = True
self._num_steps += 1
return self.preprocess_state(x), r, a, done, {}
# def preprocess_state(self, x0):
# # x = x0.copy()
# # x[0] = np.sin(x[3])
# # x[1] = np.sin(x[4])
# # x[2]= np.sin(x[5])
# # x[3] = np.cos(x[3])
# # x[4] = np.cos(x[4])
# # x[5]= np.cos(x[5])
# # # Remove xi.
# # x = np.delete(x, 10)
# # TODO: think about removing p, q, r?
# return x0
def preprocess_state(self, x0):
q = x0[0:7]
dq = x0[7:14]
x = np.hstack([np.sin(q), np.cos(q), dq])
return x
def reset(self):
self._linear_system_reset_pub.publish(Empty())
self.clear()
def render(self):
# TODO!
#aren't we doing this in rviz already?
pass
def seed(self, s):
pass
def load_parameters(self):
if not rospy.has_param("~topics/transition"):
return False
self._transition_topic = rospy.get_param("~topics/transition")
if not rospy.has_param("~topics/linear_system_reset"):
return False
self._linear_system_reset_topic = rospy.get_param("~topics/linear_system_reset")
return True
def register_callbacks(self):
self._transition_sub = rospy.Subscriber(
self._transition_topic, Transition, self.transition_callback)
self._linear_system_reset_pub = rospy.Publisher(self._linear_system_reset_topic, Empty)
return True
def transition_callback(self, msg):
self._transitions.append(msg)
def clear(self):
self._transitions = []
| [
"rospy.Subscriber",
"rospy.Publisher",
"rospy.sleep",
"std_msgs.msg.Empty",
"rospy.get_param",
"rospy.is_shutdown",
"numpy.sin",
"numpy.array",
"gym.spaces.Box",
"numpy.cos",
"rospy.logwarn_throttle",
"rospy.get_name",
"rospy.has_param",
"sys.exit"
] | [((661, 720), 'gym.spaces.Box', 'gym.spaces.Box', (['(-np.inf)', 'np.inf', '(NUM_PREPROCESSED_STATES,)'], {}), '(-np.inf, np.inf, (NUM_PREPROCESSED_STATES,))\n', (675, 720), False, 'import gym\n'), ((749, 800), 'gym.spaces.Box', 'gym.spaces.Box', (['(-np.inf)', 'np.inf', '(NUM_ACTION_DIMS,)'], {}), '(-np.inf, np.inf, (NUM_ACTION_DIMS,))\n', (763, 800), False, 'import gym\n'), ((1196, 1215), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (1213, 1215), False, 'import rospy\n'), ((1312, 1334), 'numpy.array', 'np.array', (['transition.x'], {}), '(transition.x)\n', (1320, 1334), True, 'import numpy as np\n'), ((1347, 1369), 'numpy.array', 'np.array', (['transition.a'], {}), '(transition.a)\n', (1355, 1369), True, 'import numpy as np\n'), ((2500, 2537), 'rospy.get_param', 'rospy.get_param', (['"""~topics/transition"""'], {}), "('~topics/transition')\n", (2515, 2537), False, 'import rospy\n'), ((2669, 2715), 'rospy.get_param', 'rospy.get_param', (['"""~topics/linear_system_reset"""'], {}), "('~topics/linear_system_reset')\n", (2684, 2715), False, 'import rospy\n'), ((2803, 2881), 'rospy.Subscriber', 'rospy.Subscriber', (['self._transition_topic', 'Transition', 'self.transition_callback'], {}), '(self._transition_topic, Transition, self.transition_callback)\n', (2819, 2881), False, 'import rospy\n'), ((2936, 2991), 'rospy.Publisher', 'rospy.Publisher', (['self._linear_system_reset_topic', 'Empty'], {}), '(self._linear_system_reset_topic, Empty)\n', (2951, 2991), False, 'import rospy\n'), ((326, 342), 'rospy.get_name', 'rospy.get_name', ([], {}), '()\n', (340, 342), False, 'import rospy\n'), ((442, 453), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (450, 453), False, 'import sys\n'), ((496, 507), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (504, 507), False, 'import sys\n'), ((1085, 1153), 'rospy.logwarn_throttle', 'rospy.logwarn_throttle', (['(10.0)', "('%s: Out of transitions.' % self._name)"], {}), "(10.0, '%s: Out of transitions.' % self._name)\n", (1107, 1153), False, 'import rospy\n'), ((1166, 1183), 'rospy.sleep', 'rospy.sleep', (['(0.01)'], {}), '(0.01)\n', (1177, 1183), False, 'import rospy\n'), ((2190, 2197), 'std_msgs.msg.Empty', 'Empty', ([], {}), '()\n', (2195, 2197), False, 'from std_msgs.msg import Empty\n'), ((2403, 2440), 'rospy.has_param', 'rospy.has_param', (['"""~topics/transition"""'], {}), "('~topics/transition')\n", (2418, 2440), False, 'import rospy\n'), ((2554, 2600), 'rospy.has_param', 'rospy.has_param', (['"""~topics/linear_system_reset"""'], {}), "('~topics/linear_system_reset')\n", (2569, 2600), False, 'import rospy\n'), ((1052, 1071), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (1069, 1071), False, 'import rospy\n'), ((2078, 2087), 'numpy.sin', 'np.sin', (['q'], {}), '(q)\n', (2084, 2087), True, 'import numpy as np\n'), ((2089, 2098), 'numpy.cos', 'np.cos', (['q'], {}), '(q)\n', (2095, 2098), True, 'import numpy as np\n')] |
"""
This Module being called from .sh script for the problem 2
Runs the pre-trained ACGAN model and saves generates 10 pairs of images entangled via 'smiling feature attribute'
"""
# general
import random
import os
import numpy as np
# dl related
import torch
from torch.autograd import Variable
# custom modules
import parser
from acgan import Generator_ACGAN
# saving the subplot
import torchvision.utils as vutils
def random_generator_input(num_pairs = 10):
"""This function return random generator input """
# will used to represent smiling
ones = np.ones(num_pairs)
# will used to represent non-smiling
zeros = np.zeros(num_pairs)
# concatinate for input pairs
label_tensor = np.hstack((ones,zeros))
label_tensor= torch.from_numpy(label_tensor).view(20,1,1,1).type(torch.FloatTensor)
# random noise
random_tensor = torch.randn(10, 100, 1, 1)
random_tensor = torch.cat((random_tensor,random_tensor))
generator_input = Variable(torch.cat((random_tensor, label_tensor),1))
return generator_input.cuda()
if __name__=='__main__':
num_gpu = 1 if torch.cuda.is_available() else 0
args = parser.arg_parse()
# set up the seed
random.seed(args.random_seed)
torch.manual_seed(args.random_seed)
# set up the model
generator = Generator_ACGAN().cuda()
# load weights
generator.load_state_dict(torch.load(args.resume))
generator.eval()
# encouraged to say 32 since you will generate 32 pics
batch_size = args.batch_size
latent_size = args.nz
fixed_input = random_generator_input(num_pairs = 10)
# generate the random input
img = generator(fixed_input)
generator.train()
vutils.save_image(img.cpu().data, os.path.join(args.out_dir_p1_p2, 'fig2_2.jpg') ,nrow = 10) | [
"torch.manual_seed",
"torch.load",
"acgan.Generator_ACGAN",
"numpy.zeros",
"torch.cat",
"numpy.ones",
"torch.randn",
"numpy.hstack",
"random.seed",
"torch.cuda.is_available",
"parser.arg_parse",
"os.path.join",
"torch.from_numpy"
] | [((572, 590), 'numpy.ones', 'np.ones', (['num_pairs'], {}), '(num_pairs)\n', (579, 590), True, 'import numpy as np\n'), ((644, 663), 'numpy.zeros', 'np.zeros', (['num_pairs'], {}), '(num_pairs)\n', (652, 663), True, 'import numpy as np\n'), ((717, 741), 'numpy.hstack', 'np.hstack', (['(ones, zeros)'], {}), '((ones, zeros))\n', (726, 741), True, 'import numpy as np\n'), ((868, 894), 'torch.randn', 'torch.randn', (['(10)', '(100)', '(1)', '(1)'], {}), '(10, 100, 1, 1)\n', (879, 894), False, 'import torch\n'), ((915, 956), 'torch.cat', 'torch.cat', (['(random_tensor, random_tensor)'], {}), '((random_tensor, random_tensor))\n', (924, 956), False, 'import torch\n'), ((1157, 1175), 'parser.arg_parse', 'parser.arg_parse', ([], {}), '()\n', (1173, 1175), False, 'import parser\n'), ((1202, 1231), 'random.seed', 'random.seed', (['args.random_seed'], {}), '(args.random_seed)\n', (1213, 1231), False, 'import random\n'), ((1236, 1271), 'torch.manual_seed', 'torch.manual_seed', (['args.random_seed'], {}), '(args.random_seed)\n', (1253, 1271), False, 'import torch\n'), ((988, 1031), 'torch.cat', 'torch.cat', (['(random_tensor, label_tensor)', '(1)'], {}), '((random_tensor, label_tensor), 1)\n', (997, 1031), False, 'import torch\n'), ((1112, 1137), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1135, 1137), False, 'import torch\n'), ((1387, 1410), 'torch.load', 'torch.load', (['args.resume'], {}), '(args.resume)\n', (1397, 1410), False, 'import torch\n'), ((1747, 1793), 'os.path.join', 'os.path.join', (['args.out_dir_p1_p2', '"""fig2_2.jpg"""'], {}), "(args.out_dir_p1_p2, 'fig2_2.jpg')\n", (1759, 1793), False, 'import os\n'), ((1312, 1329), 'acgan.Generator_ACGAN', 'Generator_ACGAN', ([], {}), '()\n', (1327, 1329), False, 'from acgan import Generator_ACGAN\n'), ((759, 789), 'torch.from_numpy', 'torch.from_numpy', (['label_tensor'], {}), '(label_tensor)\n', (775, 789), False, 'import torch\n')] |
#!/usr/bin/env python2
from sys import argv, exit
from os import listdir
from math import sqrt
from cv2 import imread
from scipy.misc import imresize
from keras.models import load_model
from numpy import float32, transpose, expand_dims
from PyQt5.QtWidgets import QLabel, QWidget, QApplication, QPushButton
from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen
from PyQt5.QtCore import Qt, QTimer
# Program which allows a user to visually compare and contrast a neural network and a human's steering abilities
# Created by brendon-ai, August 2017
class DataVisualizer(QWidget):
# Degrees to rotate steering wheel, multiplied by the corresponding steering angle
STEERING_WHEEL_COEFFICIENT = 360
# Parameters for the low-pass filter
LOW_PASS_VECTOR = [1.0]
# UI elements and counters
video_display = None
current_frame = 0
num_frames = None
frame_counter = None
# Images and corresponding steering angles
loaded_images = []
actual_angles = []
predicted_angles = []
# Everything required for each of the two steering wheels and graph lines
red_wheel = None
red_wheel_label = None
red_wheel_image = None
red_line_points = []
green_wheel = None
green_wheel_label = None
green_wheel_image = None
green_line_points = []
# Call various initialization functions
def __init__(self):
super(DataVisualizer, self).__init__()
# Load images, set up the UI, and start updating
standard_deviation = self.process_images()
self.init_ui(standard_deviation)
self.update_ui()
# Initialize the user interface, with standard deviation parameter to be displayed on label
def init_ui(self, standard_deviation):
# Font used for the big labels under the steering wheels
large_font = QFont('Source Sans Pro', 24)
large_font.setWeight(30)
# Font used for the steering angle indicators next to the graph
small_font = QFont('Source Sans Pro', 16)
small_font.setWeight(20)
# Initialize a steering wheel and corresponding label at a given Y position
def init_wheel_and_label(y):
# Create a wheel and set its position
wheel = QLabel(self)
wheel.setAlignment(Qt.AlignCenter)
wheel.setFixedSize(290, 288)
wheel.move(1620, y)
# Create a label, configure its text positioning and font, and set its position
label = QLabel(self)
label.setAlignment(Qt.AlignCenter)
label.setFixedSize(290, 72)
label.move(1620, y + 298)
label.setFont(large_font)
return wheel, label
# Create a small graph indicator label with text and position generated from a steering angle
def init_graph_label(steering_angle):
y_point = self.get_line_graph_y_position(steering_angle) - 15
label = QLabel(self)
label.setAlignment(Qt.AlignCenter)
label.setFixedSize(30, 30)
label.move(1580, y_point)
label.setFont(small_font)
label.setText(str(steering_angle))
# Black text on a light gray background
palette = QPalette()
palette.setColor(QPalette.Foreground, Qt.black)
palette.setColor(QPalette.Background, Qt.lightGray)
# Set the size, position, title, and color scheme of the window
self.setFixedSize(1920, 860)
self.move(0, 100)
self.setWindowTitle('Training Data Visualizer')
self.setPalette(palette)
# Generate the buttons that handle skipping forward and backward
skip_button_values = [-1000, -100, 100, 1000]
for i in range(len(skip_button_values)):
skip_value = skip_button_values[i]
# Generate a function to skip forward or backward by frames
def make_skip_function(frames):
# Internal function for return
def skip_frames():
self.current_frame += frames
self.red_line_points = []
self.green_line_points = []
return skip_frames
# Define the attributes of the button
skip_button = QPushButton(self)
skip_button.setFont(small_font)
skip_button.setText("Skip %d" % skip_value)
skip_button.clicked.connect(make_skip_function(skip_value))
skip_button.setFixedSize(190, 40)
# Calculate the X position of the button
x_pos = (200 * i) + 10
if skip_value > 0:
x_pos += 800
skip_button.move(x_pos, 810)
# Initialize the label that shows the frame we are currently on
self.frame_counter = QLabel(self)
self.frame_counter.setAlignment(Qt.AlignCenter)
self.frame_counter.setFont(small_font)
self.frame_counter.setFixedSize(290, 40)
self.frame_counter.move(1620, 810)
# Initialize the label at the bottom that display low pass filter parameters and standard deviation
std_dev_label = QLabel(self)
std_dev_label.setAlignment(Qt.AlignCenter)
std_dev_label.setFixedSize(800, 40)
std_dev_label.move(410, 810)
std_dev_label.setFont(small_font)
std_dev_label.setText('Low pass filter parameters: %s Standard deviation over whole run: %f'
% (self.LOW_PASS_VECTOR, standard_deviation))
# Initialize the image box that holds the video frames
self.video_display = QLabel(self)
self.video_display.setAlignment(Qt.AlignCenter)
self.video_display.setFixedSize(1600, 528)
self.video_display.move(10, 10)
# Load the steering wheel images from the assets folder
self.red_wheel_image = QImage("assets/red_wheel.png")
self.green_wheel_image = QImage("assets/green_wheel.png")
# Initialize the red and green wheels and corresponding labels
self.red_wheel, self.red_wheel_label = init_wheel_and_label(10)
self.green_wheel, self.green_wheel_label = init_wheel_and_label(435)
# Create graph indicator labels for positions -0.1, 0.0, and 0.1
init_graph_label(-0.1)
init_graph_label(0.0)
init_graph_label(0.1)
# Make the window exist
self.show()
# Load all images from disk and calculate their human and network steering angles
# Return standard deviation between human and network angles over whole run
def process_images(self):
# An implementation of a low pass filter, used to dampen the network's steering angle responses
def low_pass_filter(steering_angle, output_memory):
# Add current steering angle to memory of outputs (passed from outer function) and remove the oldest element
output_memory = output_memory[:-1]
output_memory.insert(0, steering_angle)
# Weighted average of the last 5 outputs, using the low pass filter parameters as weights
weighted_sum = sum(i[0] * i[1] for i in zip(output_memory, self.LOW_PASS_VECTOR))
total_of_weights = sum(self.LOW_PASS_VECTOR)
weighted_average = weighted_sum / total_of_weights
return weighted_average, output_memory
# Compute the standard deviation of the difference between two lists
def standard_deviation(actual_output, ground_truth):
total_squared_error = 0
for i in range(len(actual_output)):
error = actual_output[i] - ground_truth[i]
squared_error = error * error
total_squared_error += squared_error
variance = total_squared_error / len(actual_output)
return sqrt(variance)
# If the arguments are invalid, fail to an error message
try:
# Load the Keras model from disk
model = load_model(argv[1])
# Load all image names from the folder, and record how many there are
image_folder = argv[2]
file_names = listdir(image_folder)
image_names = [name for name in file_names if '.jpg' in name or '.png' in name]
image_names.sort()
self.num_frames = len(image_names)
# Initialize a short-term memory of the last 5 raw outputs from the network, used for the low pass filter
last_5_outputs = [0] * 5
# Notify the user the process has begun; this may take a while
print("Loading and processing images...")
index = 0
for image_name in image_names:
# Take the human steering angle from the file name
actual_angle = float(image_name.split("_")[1][:-4])
self.actual_angles.append(actual_angle)
# Load the image itself into a Numpy array
image_path = ("%s/%s" % (image_folder, image_name))
loaded_image = imread(image_path)
self.loaded_images.append(loaded_image)
# Pre-processing required for the network to classify it
image_float = loaded_image.astype(float32)
image_3d = transpose(image_float, (1, 0, 2))
image_final = expand_dims(image_3d, 0)
# Use the loaded model to predict a steering angle for the image, and apply a low pass filter
predicted_angle = model.predict(image_final)
(dampened_angle, last_5_outputs) = low_pass_filter(predicted_angle[0, 0], last_5_outputs)
self.predicted_angles.append(dampened_angle)
# Update the user every 1000 images
index += 1
if index % 1000 == 0:
print("Processed image %d of %d" % (index, self.num_frames))
# Compute and return the standard deviation over the whole run
return standard_deviation(self.predicted_angles, self.actual_angles)
# Display an error message and quit
except IndexError:
print("Usage: ./data_visualizer.py <model> <image folder>")
exit()
# Updates the image box, steering wheels, and labels
def update_ui(self):
# Given a steering angle, rotate the steering wheel image and set the label correspondingly
def set_wheel_angle(steering_angle, wheel_image, wheel, label, title):
wheel_angle = steering_angle * self.STEERING_WHEEL_COEFFICIENT
transform = QTransform().rotate(wheel_angle)
pixmap = QPixmap.fromImage(wheel_image).transformed(transform)
wheel.setPixmap(pixmap)
label.setText("Steering angle\n(%s): %f" % (title, steering_angle))
# Add a new point to the graph and shift all points left 5 pixels
def update_point_list(point_list, steering_angle):
y_point = self.get_line_graph_y_position(steering_angle)
point_list.append([1570, y_point])
for point in point_list:
point[0] -= 5
# Update the index that tells us what frame and steering angle to display
image_index = self.current_frame % self.num_frames
self.current_frame += 1
# Update the label that displays the current frame
self.frame_counter.setText("Frame %d / %d" % (image_index, self.num_frames))
# Upscale a loaded image and display it
frame = imresize(self.loaded_images[image_index], 8.0, interp='nearest')
image = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888).rgbSwapped()
pix = QPixmap.fromImage(image)
self.video_display.setPixmap(pix)
# Get the corresponding network and human steering angles for the current image
red_angle = self.actual_angles[image_index]
green_angle = self.predicted_angles[image_index]
# Update the UI for the current steering angles
set_wheel_angle(red_angle, self.red_wheel_image, self.red_wheel, self.red_wheel_label, "human")
set_wheel_angle(green_angle, self.green_wheel_image, self.green_wheel, self.green_wheel_label, "network")
# Add the current steering angles to the graph
update_point_list(self.red_line_points, red_angle)
update_point_list(self.green_line_points, green_angle)
# Make sure the graph is redrawn every frame
self.repaint()
# Call this function again in 30 milliseconds
QTimer().singleShot(30, self.update_ui)
# Called when it is time to redraw
def paintEvent(self, event):
# Initialize the drawing tool
painter = QPainter(self)
# Draw a jagged line over a list of points
def paint_line(point_list, color):
# Check if there are any points to be drawn
if point_list:
# Configure the line color and width
pen = QPen()
pen.setColor(color)
pen.setWidth(3)
painter.setPen(pen)
# Iterate over the points and draw a line between each consecutive pair
previous_point = point_list[0]
for i in range(1, len(point_list)):
current_point = point_list[i]
line_parameters = current_point + previous_point
painter.drawLine(*line_parameters)
previous_point = current_point
# Calculate the Y points on the graph for steering angles of -0.1, 0.0, and 0.1 respectively
y_0_1 = self.get_line_graph_y_position(-0.1)
y0 = self.get_line_graph_y_position(0.0)
y0_1 = self.get_line_graph_y_position(0.1)
# Draw the three grid lines
paint_line([[0, y_0_1], [1570, y_0_1]], QColor(0, 0, 0))
paint_line([[0, y0], [1570, y0]], QColor(0, 0, 0))
paint_line([[0, y0_1], [1570, y0_1]], QColor(0, 0, 0))
# Draw the steering angle lines on the graph
paint_line(self.red_line_points, QColor(255, 0, 0))
paint_line(self.green_line_points, QColor(0, 255, 0))
# Take an arbitrary steering angle, return the Y position that angle would correspond to on the graph
@staticmethod
def get_line_graph_y_position(steering_angle):
y_point = -int(steering_angle * 800) + 669
return y_point
# If this file is being run directly, instantiate the DataVisualizer class
if __name__ == '__main__':
app = QApplication([])
ic = DataVisualizer()
exit(app.exec_())
| [
"keras.models.load_model",
"PyQt5.QtGui.QColor",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtWidgets.QApplication",
"PyQt5.QtGui.QPainter",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtGui.QPixmap.fromImage",
"numpy.transpose",
"PyQt5.QtCore.QTimer",
"math.sqrt",
"PyQt5.QtGui.QPalette",
"PyQt5.QtGui.QImage"... | [((14543, 14559), 'PyQt5.QtWidgets.QApplication', 'QApplication', (['[]'], {}), '([])\n', (14555, 14559), False, 'from PyQt5.QtWidgets import QLabel, QWidget, QApplication, QPushButton\n'), ((1868, 1896), 'PyQt5.QtGui.QFont', 'QFont', (['"""Source Sans Pro"""', '(24)'], {}), "('Source Sans Pro', 24)\n", (1873, 1896), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((2024, 2052), 'PyQt5.QtGui.QFont', 'QFont', (['"""Source Sans Pro"""', '(16)'], {}), "('Source Sans Pro', 16)\n", (2029, 2052), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((3265, 3275), 'PyQt5.QtGui.QPalette', 'QPalette', ([], {}), '()\n', (3273, 3275), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((4826, 4838), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['self'], {}), '(self)\n', (4832, 4838), False, 'from PyQt5.QtWidgets import QLabel, QWidget, QApplication, QPushButton\n'), ((5167, 5179), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['self'], {}), '(self)\n', (5173, 5179), False, 'from PyQt5.QtWidgets import QLabel, QWidget, QApplication, QPushButton\n'), ((5637, 5649), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['self'], {}), '(self)\n', (5643, 5649), False, 'from PyQt5.QtWidgets import QLabel, QWidget, QApplication, QPushButton\n'), ((5893, 5923), 'PyQt5.QtGui.QImage', 'QImage', (['"""assets/red_wheel.png"""'], {}), "('assets/red_wheel.png')\n", (5899, 5923), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((5957, 5989), 'PyQt5.QtGui.QImage', 'QImage', (['"""assets/green_wheel.png"""'], {}), "('assets/green_wheel.png')\n", (5963, 5989), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((11528, 11592), 'scipy.misc.imresize', 'imresize', (['self.loaded_images[image_index]', '(8.0)'], {'interp': '"""nearest"""'}), "(self.loaded_images[image_index], 8.0, interp='nearest')\n", (11536, 11592), False, 'from scipy.misc import imresize\n'), ((11704, 11728), 'PyQt5.QtGui.QPixmap.fromImage', 'QPixmap.fromImage', (['image'], {}), '(image)\n', (11721, 11728), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((12732, 12746), 'PyQt5.QtGui.QPainter', 'QPainter', (['self'], {}), '(self)\n', (12740, 12746), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((2278, 2290), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['self'], {}), '(self)\n', (2284, 2290), False, 'from PyQt5.QtWidgets import QLabel, QWidget, QApplication, QPushButton\n'), ((2524, 2536), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['self'], {}), '(self)\n', (2530, 2536), False, 'from PyQt5.QtWidgets import QLabel, QWidget, QApplication, QPushButton\n'), ((2976, 2988), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['self'], {}), '(self)\n', (2982, 2988), False, 'from PyQt5.QtWidgets import QLabel, QWidget, QApplication, QPushButton\n'), ((4297, 4314), 'PyQt5.QtWidgets.QPushButton', 'QPushButton', (['self'], {}), '(self)\n', (4308, 4314), False, 'from PyQt5.QtWidgets import QLabel, QWidget, QApplication, QPushButton\n'), ((7844, 7858), 'math.sqrt', 'sqrt', (['variance'], {}), '(variance)\n', (7848, 7858), False, 'from math import sqrt\n'), ((8003, 8022), 'keras.models.load_model', 'load_model', (['argv[1]'], {}), '(argv[1])\n', (8013, 8022), False, 'from keras.models import load_model\n'), ((8166, 8187), 'os.listdir', 'listdir', (['image_folder'], {}), '(image_folder)\n', (8173, 8187), False, 'from os import listdir\n'), ((13864, 13879), 'PyQt5.QtGui.QColor', 'QColor', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (13870, 13879), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((13923, 13938), 'PyQt5.QtGui.QColor', 'QColor', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (13929, 13938), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((13986, 14001), 'PyQt5.QtGui.QColor', 'QColor', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (13992, 14001), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((14098, 14115), 'PyQt5.QtGui.QColor', 'QColor', (['(255)', '(0)', '(0)'], {}), '(255, 0, 0)\n', (14104, 14115), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((14160, 14177), 'PyQt5.QtGui.QColor', 'QColor', (['(0)', '(255)', '(0)'], {}), '(0, 255, 0)\n', (14166, 14177), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((9059, 9077), 'cv2.imread', 'imread', (['image_path'], {}), '(image_path)\n', (9065, 9077), False, 'from cv2 import imread\n'), ((9294, 9327), 'numpy.transpose', 'transpose', (['image_float', '(1, 0, 2)'], {}), '(image_float, (1, 0, 2))\n', (9303, 9327), False, 'from numpy import float32, transpose, expand_dims\n'), ((9358, 9382), 'numpy.expand_dims', 'expand_dims', (['image_3d', '(0)'], {}), '(image_3d, 0)\n', (9369, 9382), False, 'from numpy import float32, transpose, expand_dims\n'), ((10234, 10240), 'sys.exit', 'exit', ([], {}), '()\n', (10238, 10240), False, 'from sys import argv, exit\n'), ((11609, 11676), 'PyQt5.QtGui.QImage', 'QImage', (['frame', 'frame.shape[1]', 'frame.shape[0]', 'QImage.Format_RGB888'], {}), '(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)\n', (11615, 11676), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((12562, 12570), 'PyQt5.QtCore.QTimer', 'QTimer', ([], {}), '()\n', (12568, 12570), False, 'from PyQt5.QtCore import Qt, QTimer\n'), ((13000, 13006), 'PyQt5.QtGui.QPen', 'QPen', ([], {}), '()\n', (13004, 13006), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((10603, 10615), 'PyQt5.QtGui.QTransform', 'QTransform', ([], {}), '()\n', (10613, 10615), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n'), ((10657, 10687), 'PyQt5.QtGui.QPixmap.fromImage', 'QPixmap.fromImage', (['wheel_image'], {}), '(wheel_image)\n', (10674, 10687), False, 'from PyQt5.QtGui import QPixmap, QPalette, QImage, QTransform, QFont, QPainter, QColor, QPen\n')] |
import os, sys, glob
import argparse
import numpy as np
import pandas as pd
from scipy.interpolate import griddata
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt, rc
from matplotlib.pyplot import figure
import figure_size
plt.style.use("../../publication.mplstyle")
def get_args(argv=None):
parser = argparse.ArgumentParser(description="The sky is not the limit.")
parser.add_argument(
"--snapnr",
dest="snapnr",
action="store",
type=int,
default=10,
help="Snapshot number",
)
parser.add_argument(
"--indir",
dest="indir",
action="store",
type=str,
default="/cosma7/data/dp004/dc-beck3/3_Proca/cvg_b3_000001_with_cbf/",
help="Folder in which simulation output is saved.",
)
parser.add_argument(
"--outdir",
dest="outdir",
action="store",
type=str,
default="/cosma7/data/dp004/dc-beck3/3_Proca/cvg_b3_000001_with_cbf/",
help="Folder in which transformed data will be saved.",
)
parser.add_argument(
"--boxsize",
dest="boxsize",
action="store",
type=int,
default=200,
help="Box-size of simulation in Mpc/h.",
)
parser.add_argument(
"--ngrid",
dest="n_grid",
action="store",
type=int,
default=256,
help="Number of particles used.",
)
args = parser.parse_args()
return args
def run(args, snap_nrs, quantities):
"""
"""
for snapnr in snap_nrs:
print("Reading data of snapshot %d" % snapnr)
# load snapshot
infile = args.indir + "grav_%05d.h5" % snapnr
fields = pd.read_hdf(infile, key="df")
# take slice
delta = 1 / args.n_grid * (1 + 0.1)
centre = 0.5
fields = fields.loc[
(fields["z"] > centre - delta / 2) & (fields["z"] < centre + delta / 2)
]
print(len(fields["x"].values))
# Make 2d mesh and map of slice data
# frac_x = 1
# bins = np.linspace(0, frac_x, int(args.n_grid*frac_x))
# bincenter = (bins[1:]+bins[:-1])/2
xxi, yyi = np.mgrid[0.0:1.0:256j, 0.0:1.0:256j] # depending on grid_size
for quant in quantities:
print("Create map of %s" % quant)
if np.min(fields["x"].values) < 0.0:
print("Map lifted by %.3f" % np.abs(fields["x"].values))
values = fields[quant].values + np.abs(fields[quant].values)
else:
values = fields[quant].values
value_map = griddata(
(fields["x"].values, fields["y"].values),
values, # avoid <0 values
(xxi, yyi),
method="linear",
fill_value=np.mean(values),
)
np.save(args.indir + "map_%s_%05d" % (quant, snapnr), value_map.T)
if __name__ == "__main__":
args = get_args()
snap_nrs = [10] # snapshots
# TODO: compare \partial^2\partial_i\chi to \partial^2B_i
quantities = [
"phi",
"sf",
] # , "sf", "lp2_cbf1", "lp2_cbf2", "lp2_cbf3"] # cvg fields
run(args, snap_nrs, quantities)
| [
"numpy.save",
"numpy.abs",
"pandas.read_hdf",
"argparse.ArgumentParser",
"matplotlib.pyplot.style.use",
"numpy.min",
"numpy.mean"
] | [((270, 313), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""../../publication.mplstyle"""'], {}), "('../../publication.mplstyle')\n", (283, 313), True, 'from matplotlib import pyplot as plt, rc\n'), ((354, 418), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""The sky is not the limit."""'}), "(description='The sky is not the limit.')\n", (377, 418), False, 'import argparse\n'), ((1744, 1773), 'pandas.read_hdf', 'pd.read_hdf', (['infile'], {'key': '"""df"""'}), "(infile, key='df')\n", (1755, 1773), True, 'import pandas as pd\n'), ((2893, 2959), 'numpy.save', 'np.save', (["(args.indir + 'map_%s_%05d' % (quant, snapnr))", 'value_map.T'], {}), "(args.indir + 'map_%s_%05d' % (quant, snapnr), value_map.T)\n", (2900, 2959), True, 'import numpy as np\n'), ((2378, 2404), 'numpy.min', 'np.min', (["fields['x'].values"], {}), "(fields['x'].values)\n", (2384, 2404), True, 'import numpy as np\n'), ((2533, 2561), 'numpy.abs', 'np.abs', (['fields[quant].values'], {}), '(fields[quant].values)\n', (2539, 2561), True, 'import numpy as np\n'), ((2850, 2865), 'numpy.mean', 'np.mean', (['values'], {}), '(values)\n', (2857, 2865), True, 'import numpy as np\n'), ((2457, 2483), 'numpy.abs', 'np.abs', (["fields['x'].values"], {}), "(fields['x'].values)\n", (2463, 2483), True, 'import numpy as np\n')] |
__author__ = '<NAME> (<EMAIL>)'
import numpy as np
def update_user_count_eponymous(set_of_contributors, anonymous_coward_comments_counter):
"""
Eponymous user count update.
Input: - set_of_contributors: A python set of user ids.
- anonymous_coward_comments_counter: The number of comments posted by anonymous user(s).
Output: - user_count: The number of eponymous users active in the information cascade.
"""
user_count = len(set_of_contributors)
return user_count
def update_user_count_estimated(set_of_contributors, anonymous_coward_comments_counter):
"""
Total user count estimate update in the presence of anonymous users.
Currently we use a very simplistic model for estimating the full user count.
Inputs: - set_of_contributors: A python set of user ids.
- anonymous_coward_comments_counter: The number of comments posted by anonymous user(s).
Output: estimated_anonymous_contributor_count: The estimated number of users active in the information cascade.
"""
eponymous_user_count = len(set_of_contributors)
if anonymous_coward_comments_counter > 0:
# TODO: Of course, I can use a much more sophisticated model.
estimated_anonymous_user_count = (1 + anonymous_coward_comments_counter)/2
else:
estimated_anonymous_user_count = 0.0
estimated_user_count = eponymous_user_count + estimated_anonymous_user_count
return estimated_user_count
def update_user_hirsch_eponymous(contributor_comment_counts, minimum_hirsch_value, maximum_hirsch_value):
"""
Calculates the Hirsch index for a user-comment occurrence vector.
Inputs: - contributor_comment_counts: A map from user id to comments posted in numpy array format.
- minimum_hirsch_value: This is the previous Hirsch value.
- maximum_hirsch_value: This is the depth of the latest node added to the tree.
Output: - hirsch: The Hirsch index.
"""
sorted_indices = np.argsort(contributor_comment_counts)
# This is the previous hirsch index value
hirsch_index = minimum_hirsch_value
if maximum_hirsch_value > contributor_comment_counts.size:
maximum_hirsch_value = contributor_comment_counts.size
if maximum_hirsch_value > minimum_hirsch_value:
comment_count = contributor_comment_counts[sorted_indices[-maximum_hirsch_value]]
if comment_count >= maximum_hirsch_value:
hirsch_index = maximum_hirsch_value
# # Check from maximum to minimum (not inclusive) possible hirsch values
# for active_contributors in np.arange(maximum_hirsch_value, minimum_hirsch_value, -1):
# comment_count = contributor_comment_counts[sorted_indices[-active_contributors]]
# if comment_count >= active_contributors:
# hirsch = active_contributors
# break
return hirsch_index
def update_graph_outdegree_entropy(contributor_comment_count):
"""
Calculates the entropy of the user-to-comment distribution for eponymous users.
Input: - contributor_comment_count: A map from user id to comments posted in numpy array format.
Output: - comment_entropy: The entropy of the user-to-comment distribution
"""
# TODO: The vector also contains a position for the Anonymous user. However, the value should always remain zero.
number_of_comments = np.sum(contributor_comment_count)
if number_of_comments < 2:
comment_entropy = 0
return comment_entropy
comment_distribution = contributor_comment_count/number_of_comments
comment_distribution = comment_distribution[comment_distribution > 0]
comment_entropy = np.abs(-np.sum(np.multiply(comment_distribution,
np.log(comment_distribution))))
return comment_entropy
def update_graph_indegree_entropy(contributor_replied_to_count):
# TODO: The vector also contains a position for the Anonymous user. However, the value should always remain zero.
number_of_comments = np.sum(contributor_replied_to_count)
if number_of_comments < 2:
replied_to_entropy = 0
return replied_to_entropy
replied_to_distribution = contributor_replied_to_count/number_of_comments
replied_to_distribution = replied_to_distribution[replied_to_distribution > 0]
replied_to_entropy = np.abs(-np.sum(np.multiply(replied_to_distribution,
np.log(replied_to_distribution))))
return replied_to_entropy
def update_normalized_graph_outdegree_entropy(contributor_comment_count,
set_of_users,
within_discussion_anonymous_coward):
"""
Calculates the ratio of the entropy of the user-to-comment distribution to the maximum possible for eponymous users.
Inputs: - contributor_comment_count: A map from user id to comments posted in numpy array format.
- set_of_users: A python set of user ids.
- within_discussion_anonymous_coward: The name of the Anonymous user for this dataset.
Output: - normalized_eponymous_contributor_recurrence: The ratio of the entropy of the user-to-comment distribution
to the maximum possible for eponymous users.
"""
number_of_comments = np.sum(contributor_comment_count)
if number_of_comments < 2:
normalized_eponymous_contributor_recurrence = 1.0
return normalized_eponymous_contributor_recurrence
if within_discussion_anonymous_coward is not None:
number_of_users = len(set_of_users) - 1
else:
number_of_users = len(set_of_users)
# Calculate the user-to-comment distribution entropy.
comment_distribution = contributor_comment_count/number_of_comments
comment_distribution = comment_distribution[comment_distribution > 0]
comment_entropy = np.abs(-np.sum(np.multiply(comment_distribution,
np.log(comment_distribution))))
# Calculate the maximum possible user-to-comment distribution entropy given the number of comments.
uniform_comment_count = np.zeros(number_of_users, dtype=np.float64)
uniform_comment_count += (number_of_comments // number_of_users)
uniform_comment_count[:(number_of_comments % number_of_users)] += 1
uniform_comment_distribution = uniform_comment_count/number_of_comments
uniform_comment_distribution = uniform_comment_distribution[uniform_comment_distribution > 0]
max_comment_entropy = np.abs(-np.sum(np.multiply(uniform_comment_distribution,
np.log(uniform_comment_distribution))))
# Calculate normalized user-to-comment entropy.
if max_comment_entropy == 0.0:
normalized_eponymous_contributor_recurrence = 1.0
else:
normalized_eponymous_contributor_recurrence = np.abs(comment_entropy/max_comment_entropy)
return normalized_eponymous_contributor_recurrence
def update_normalized_graph_indegree_entropy(contributor_replied_to_count,
set_of_users,
within_discussion_anonymous_coward):
number_of_comments = np.sum(contributor_replied_to_count)
if number_of_comments < 2:
normalized_eponymous_contributor_recurrence = 1.0
return normalized_eponymous_contributor_recurrence
if within_discussion_anonymous_coward is not None:
number_of_users = len(set_of_users) - 1
else:
number_of_users = len(set_of_users)
# Calculate the user-to-comment distribution entropy.
replied_to_distribution = contributor_replied_to_count/number_of_comments
replied_to_distribution = replied_to_distribution[replied_to_distribution > 0]
replied_to_entropy = np.abs(-np.sum(np.multiply(replied_to_distribution,
np.log(replied_to_distribution))))
# Calculate the maximum possible user-to-comment distribution entropy given the number of comments.
uniform_replied_to_count = np.zeros(number_of_users, dtype=np.float64)
uniform_replied_to_count += (number_of_comments // number_of_users)
uniform_replied_to_count[:(number_of_comments % number_of_users)] += 1
uniform_replied_to_distribution = uniform_replied_to_count/number_of_comments
uniform_replied_to_distribution = uniform_replied_to_distribution[uniform_replied_to_distribution > 0]
max_replied_to_entropy = np.abs(-np.sum(np.multiply(uniform_replied_to_distribution,
np.log(uniform_replied_to_distribution))))
# Calculate normalized user-to-comment entropy.
if max_replied_to_entropy == 0.0:
normalized_eponymous_contributor_recurrence = 1.0
else:
normalized_eponymous_contributor_recurrence = np.abs(replied_to_entropy/max_replied_to_entropy)
return normalized_eponymous_contributor_recurrence
| [
"numpy.abs",
"numpy.sum",
"numpy.log",
"numpy.zeros",
"numpy.argsort"
] | [((1998, 2036), 'numpy.argsort', 'np.argsort', (['contributor_comment_counts'], {}), '(contributor_comment_counts)\n', (2008, 2036), True, 'import numpy as np\n'), ((3383, 3416), 'numpy.sum', 'np.sum', (['contributor_comment_count'], {}), '(contributor_comment_count)\n', (3389, 3416), True, 'import numpy as np\n'), ((4046, 4082), 'numpy.sum', 'np.sum', (['contributor_replied_to_count'], {}), '(contributor_replied_to_count)\n', (4052, 4082), True, 'import numpy as np\n'), ((5399, 5432), 'numpy.sum', 'np.sum', (['contributor_comment_count'], {}), '(contributor_comment_count)\n', (5405, 5432), True, 'import numpy as np\n'), ((6231, 6274), 'numpy.zeros', 'np.zeros', (['number_of_users'], {'dtype': 'np.float64'}), '(number_of_users, dtype=np.float64)\n', (6239, 6274), True, 'import numpy as np\n'), ((7322, 7358), 'numpy.sum', 'np.sum', (['contributor_replied_to_count'], {}), '(contributor_replied_to_count)\n', (7328, 7358), True, 'import numpy as np\n'), ((8186, 8229), 'numpy.zeros', 'np.zeros', (['number_of_users'], {'dtype': 'np.float64'}), '(number_of_users, dtype=np.float64)\n', (8194, 8229), True, 'import numpy as np\n'), ((6978, 7023), 'numpy.abs', 'np.abs', (['(comment_entropy / max_comment_entropy)'], {}), '(comment_entropy / max_comment_entropy)\n', (6984, 7023), True, 'import numpy as np\n'), ((8969, 9020), 'numpy.abs', 'np.abs', (['(replied_to_entropy / max_replied_to_entropy)'], {}), '(replied_to_entropy / max_replied_to_entropy)\n', (8975, 9020), True, 'import numpy as np\n'), ((3776, 3804), 'numpy.log', 'np.log', (['comment_distribution'], {}), '(comment_distribution)\n', (3782, 3804), True, 'import numpy as np\n'), ((4472, 4503), 'numpy.log', 'np.log', (['replied_to_distribution'], {}), '(replied_to_distribution)\n', (4478, 4503), True, 'import numpy as np\n'), ((6066, 6094), 'numpy.log', 'np.log', (['comment_distribution'], {}), '(comment_distribution)\n', (6072, 6094), True, 'import numpy as np\n'), ((6728, 6764), 'numpy.log', 'np.log', (['uniform_comment_distribution'], {}), '(uniform_comment_distribution)\n', (6734, 6764), True, 'import numpy as np\n'), ((8015, 8046), 'numpy.log', 'np.log', (['replied_to_distribution'], {}), '(replied_to_distribution)\n', (8021, 8046), True, 'import numpy as np\n'), ((8713, 8752), 'numpy.log', 'np.log', (['uniform_replied_to_distribution'], {}), '(uniform_replied_to_distribution)\n', (8719, 8752), True, 'import numpy as np\n')] |
# Copyright 2016-2019 <NAME>. All rights reserved.
# Use of this source code is governed by a MIT
# license that can be found in the LICENSE file.
"""
`Mutual information`_ (MI) is a measure of the amount of mutual dependence
between two random variables. When applied to time series, two time series are
used to construct the empirical distributions and then
:py:func:`~.shannon.mutual_info` can be applied. Locally MI is defined as
.. math::
i_{i}(X,Y) = -\\log_2 \\frac{p(x_i, y_i)}{p(x_i)p(y_i)}.
The mutual information is then just the time average of :math:`i_{i}(X,Y)`.
.. math::
I(X,Y) = -\\sum_{x_i, y_i} p(x_i, y_i) \\log_2 \\frac{p(x_i, y_i)}{p(x_i)p(y_i)}.
See [Cover1991]_ for more details.
.. _Mutual information: https://en.wikipedia.org/wiki/Mutual_information
Examples
--------
.. doctest:: mutual_info
>>> xs = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1]
>>> ys = [0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1]
>>> mutual_info(xs, ys)
0.21417094500762912
>>> mutual_info(xs, ys, local=True)
array([-1. , -1. , 0.22239242, 0.22239242, 0.22239242,
0.22239242, 0.22239242, 0.22239242, 0.22239242, 0.22239242,
0.22239242, 0.22239242, 0.22239242, 0.22239242, 0.22239242,
0.22239242, 1.5849625 , 1.5849625 , 1.5849625 , -1.5849625 ])
"""
import numpy as np
from ctypes import byref, c_int, c_ulong, c_double, POINTER
from pyinform import _inform
from pyinform.error import ErrorCode, error_guard
def mutual_info(xs, ys, local=False):
"""
Compute the (local) mutual information between two time series.
This function explicitly takes the logarithmic base *b* as an argument.
:param xs: a time series
:type xs: a sequence or ``numpy.ndarray``
:param ys: a time series
:type ys: a sequence or ``numpy.ndarray``
:param bool local: compute the local mutual information
:return: the local or average mutual information
:rtype: float or ``numpy.ndarray``
:raises ValueError: if the time series have different shapes
:raises InformError: if an error occurs within the ``inform`` C call
"""
us = np.ascontiguousarray(xs, dtype=np.int32)
vs = np.ascontiguousarray(ys, dtype=np.int32)
if us.shape != vs.shape:
raise ValueError("timeseries lengths do not match")
series = np.ascontiguousarray([us.flatten(), vs.flatten()], dtype=np.int32)
bx = max(2, np.amax(us) + 1)
by = max(2, np.amax(vs) + 1)
bs = np.ascontiguousarray([bx, by], dtype=np.int32)
seriesdata = series.ctypes.data_as(POINTER(c_int))
bsdata = bs.ctypes.data_as(POINTER(c_int))
l, n = series.shape
e = ErrorCode(0)
if local is True:
mi = np.empty(us.shape, dtype=np.float64)
out = mi.ctypes.data_as(POINTER(c_double))
_local_mutual_info(seriesdata, c_ulong(l), c_ulong(n), bsdata, out, byref(e))
else:
mi = _mutual_info(seriesdata, c_ulong(l), c_ulong(n), bsdata, byref(e))
error_guard(e)
return mi
_mutual_info = _inform.inform_mutual_info
_mutual_info.argtypes = [POINTER(c_int), c_ulong, c_ulong, POINTER(c_int), POINTER(c_int)]
_mutual_info.restype = c_double
_local_mutual_info = _inform.inform_local_mutual_info
_local_mutual_info.argtypes = [POINTER(c_int), c_ulong, c_ulong, POINTER(c_int), POINTER(c_double), POINTER(c_int)]
_local_mutual_info.restype = c_double
| [
"pyinform.error.error_guard",
"ctypes.byref",
"numpy.empty",
"ctypes.c_ulong",
"pyinform.error.ErrorCode",
"numpy.amax",
"numpy.ascontiguousarray",
"ctypes.POINTER"
] | [((2160, 2200), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['xs'], {'dtype': 'np.int32'}), '(xs, dtype=np.int32)\n', (2180, 2200), True, 'import numpy as np\n'), ((2210, 2250), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['ys'], {'dtype': 'np.int32'}), '(ys, dtype=np.int32)\n', (2230, 2250), True, 'import numpy as np\n'), ((2498, 2544), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['[bx, by]'], {'dtype': 'np.int32'}), '([bx, by], dtype=np.int32)\n', (2518, 2544), True, 'import numpy as np\n'), ((2681, 2693), 'pyinform.error.ErrorCode', 'ErrorCode', (['(0)'], {}), '(0)\n', (2690, 2693), False, 'from pyinform.error import ErrorCode, error_guard\n'), ((2999, 3013), 'pyinform.error.error_guard', 'error_guard', (['e'], {}), '(e)\n', (3010, 3013), False, 'from pyinform.error import ErrorCode, error_guard\n'), ((3098, 3112), 'ctypes.POINTER', 'POINTER', (['c_int'], {}), '(c_int)\n', (3105, 3112), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((3132, 3146), 'ctypes.POINTER', 'POINTER', (['c_int'], {}), '(c_int)\n', (3139, 3146), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((3148, 3162), 'ctypes.POINTER', 'POINTER', (['c_int'], {}), '(c_int)\n', (3155, 3162), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((3282, 3296), 'ctypes.POINTER', 'POINTER', (['c_int'], {}), '(c_int)\n', (3289, 3296), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((3316, 3330), 'ctypes.POINTER', 'POINTER', (['c_int'], {}), '(c_int)\n', (3323, 3330), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((3332, 3349), 'ctypes.POINTER', 'POINTER', (['c_double'], {}), '(c_double)\n', (3339, 3349), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((3351, 3365), 'ctypes.POINTER', 'POINTER', (['c_int'], {}), '(c_int)\n', (3358, 3365), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((2585, 2599), 'ctypes.POINTER', 'POINTER', (['c_int'], {}), '(c_int)\n', (2592, 2599), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((2632, 2646), 'ctypes.POINTER', 'POINTER', (['c_int'], {}), '(c_int)\n', (2639, 2646), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((2730, 2766), 'numpy.empty', 'np.empty', (['us.shape'], {'dtype': 'np.float64'}), '(us.shape, dtype=np.float64)\n', (2738, 2766), True, 'import numpy as np\n'), ((2438, 2449), 'numpy.amax', 'np.amax', (['us'], {}), '(us)\n', (2445, 2449), True, 'import numpy as np\n'), ((2471, 2482), 'numpy.amax', 'np.amax', (['vs'], {}), '(vs)\n', (2478, 2482), True, 'import numpy as np\n'), ((2799, 2816), 'ctypes.POINTER', 'POINTER', (['c_double'], {}), '(c_double)\n', (2806, 2816), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((2857, 2867), 'ctypes.c_ulong', 'c_ulong', (['l'], {}), '(l)\n', (2864, 2867), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((2869, 2879), 'ctypes.c_ulong', 'c_ulong', (['n'], {}), '(n)\n', (2876, 2879), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((2894, 2902), 'ctypes.byref', 'byref', (['e'], {}), '(e)\n', (2899, 2902), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((2952, 2962), 'ctypes.c_ulong', 'c_ulong', (['l'], {}), '(l)\n', (2959, 2962), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((2964, 2974), 'ctypes.c_ulong', 'c_ulong', (['n'], {}), '(n)\n', (2971, 2974), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n'), ((2984, 2992), 'ctypes.byref', 'byref', (['e'], {}), '(e)\n', (2989, 2992), False, 'from ctypes import byref, c_int, c_ulong, c_double, POINTER\n')] |
#!/usr/bin/env python
"""
Several forms of the logistic function and their first and second derivatives
The current functions are the following. Each function has a second form with
`_p` appended to the name, where parameters are given as an iterable, e.g.
`logistic` and `logistic_p` = `logistic(x, *p)`:
.. list-table::
:widths: 15 50
:header-rows: 1
* - Function
- Description
* - logistic
- Logistic function `L/(1+exp(-k(x-x0)))`
* - dlogistic
- First derivative of logistic function
* - d2logistic
- Second derivative of logistic function
* - logistic_offset
- logistic function with offset `L/(1+exp(-k(x-x0))) + a`
* - dlogistic_offset
- First derivative of logistic function with offset
* - d2logistic_offset
- Second derivative of logistic function with offset
* - logistic2_offset
- Double logistic function with offset
`L1/(1+exp(-k1(x-x01))) - L2/(1+exp(-k2(x-x02))) + a`
* - dlogistic2_offset
- First derivative of double logistic function with offset
* - d2logistic2_offset
- Second derivative of double logistic function with offset
This module was written by <NAME> while at Department of
Computational Hydrosystems, Helmholtz Centre for Environmental
Research - UFZ, Leipzig, Germany, and continued while at Institut
National de Recherche pour l'Agriculture, l'Alimentation et
l'Environnement (INRAE), Nancy, France.
:copyright: Copyright 2015-2022 <NAME>, see AUTHORS.rst for details.
:license: MIT License, see LICENSE for details.
.. moduleauthor:: <NAME>
Functions:
.. autosummary::
logistic
logistic_p
dlogistic
dlogistic_p
d2logistic
d2logistic_p
logistic_offset
logistic_offset_p
dlogistic_offset
dlogistic_offset_p
d2logistic_offset
d2logistic_offset_p
logistic2_offset
logistic2_offset_p
dlogistic2_offset
dlogistic2_offset_p
d2logistic2_offset
d2logistic2_offset_p
History
* Written Mar 2015 by <NAME> (mc (at) macu (dot) de)
* Added functions logistic_p and logistic_offset_p,
Dec 2017, <NAME>
* Changed to Sphinx docstring and numpydoc, Dec 2019, <NAME>
* Distinguish iterable and array_like parameter types,
Jan 2020, <NAME>
* Make systematically function_p versions of all logistic functions and its
derivatives, Feb 2020, <NAME>
* Split logistic and curvature into separate files,
May 2020, <NAME>
* More consistent docstrings, Jan 2022, <NAME>
"""
import numpy as np
import scipy.special as sp
__all__ = ['logistic', 'logistic_p',
'dlogistic', 'dlogistic_p',
'd2logistic', 'd2logistic_p',
'logistic_offset', 'logistic_offset_p',
'dlogistic_offset', 'dlogistic_offset_p',
'd2logistic_offset', 'd2logistic_offset_p',
'logistic2_offset', 'logistic2_offset_p',
'dlogistic2_offset', 'dlogistic2_offset_p',
'd2logistic2_offset', 'd2logistic2_offset_p']
# -----------------------------------------------------------
# a/(1+exp(-b(x-c))) - logistic function
def logistic(x, L, k, x0):
"""
Logistic function
.. math::
L/(1+exp(-k(x-x0)))
Parameters
----------
x : array_like
Independent variable to evalute logistic function
L : float
Maximum of logistic function
k : float
Steepness of logistic function
x0 : float
Inflection point of logistic function
Returns
-------
float or ndarray
Logistic function at *x* with maximum *L*, steepness *k* and inflection
point *x0*
"""
return L * sp.expit(k * (x - x0))
def logistic_p(x, p):
"""
Wrapper function for :func:`logistic`: `logistic(x, *p)`
"""
return logistic(x, *p)
# -----------------------------------------------------------
# 1st derivative of logistic functions
def dlogistic(x, L, k, x0):
"""
First derivative of :func:`logistic` function
.. math::
L/(1+exp(-k(x-x0)))
which is
.. math::
k.L/(2(cosh(k(x-x0))+1))
Parameters
----------
x : array_like
Independent variable to evalute derivative of logistic function
L : float
Maximum of logistic function
k : float
Steepness of logistic function
x0 : float
Inflection point of logistic function
Returns
-------
float or ndarray
First derivative of logistic function at *x* with maximum *L*,
steepness *k* and inflection point *x0*
"""
return k * L / (2. * (np.cosh(k * (x - x0)) + 1.))
def dlogistic_p(x, p):
"""
Wrapper function for :func:`dlogistic`: `dlogistic(x, *p)`
"""
return dlogistic(x, *p)
# -----------------------------------------------------------
# 2nd derivative of logistic functions
def d2logistic(x, L, k, x0):
"""
Second derivative of :func:`logistic` function
.. math::
L/(1+exp(-k(x-x0)))
which is
.. math::
-k^2.L.sinh(k(x-x0))/(2(cosh(k(x-x0))+1)^2)
Parameters
----------
x : array_like
Independent variable to evalute derivative of logistic function
L : float
Maximum of logistic function
k : float
Steepness of logistic function
x0 : float
Inflection point of logistic function
Returns
-------
float or ndarray
Second derivative of logistic function at *x* with maximum *L*,
steepness *k* and inflection point *x0*
"""
return ( -k**2 * L * np.sinh(k * (x - x0)) /
(2. * (np.cosh(k * (x - x0)) + 1.)**2) )
def d2logistic_p(x, p):
"""
Wrapper function for :func:`d2logistic`: `d2logistic(x, *p)`
"""
return d2logistic(x, *p)
# -----------------------------------------------------------
# L/(1+exp(-k(x-x0))) + a - logistic function with offset
def logistic_offset(x, L, k, x0, a):
"""
Logistic function with offset
.. math::
L/(1+exp(-k(x-x0))) + a
Parameters
----------
x : array_like
Independent variable to evalute logistic function
L : float
Maximum of logistic function
k : float
Steepness of logistic function
x0 : float
Inflection point of logistic function
a : float
Offset of logistic function
Returns
-------
float or ndarray
Logistic function at *x* with maximum *L*, steepness *k*, inflection
point *x0* and offset *a*
"""
return L * sp.expit(k * (x - x0)) + a
def logistic_offset_p(x, p):
"""
Wrapper function for :func:`logistic_offset`: `logistic_offset(x, *p)`
"""
return logistic_offset(x, *p)
# -----------------------------------------------------------
# 1st derivative of logistic functions with offset
def dlogistic_offset(x, L, k, x0, a):
"""
First derivative of :func:`logistic_offset` function
.. math::
L/(1+exp(-k(x-x0))) + a
which is
.. math::
k.L/(2(cosh(k(x-x0))+1))
Parameters
----------
x : array_like
Independent variable to evalute derivative of logistic function
L : float
Maximum of logistic function
k : float
Steepness of logistic function
x0 : float
Inflection point of logistic function
a : float
Offset of logistic function
Returns
-------
float or ndarray
First derivative of logistic function with offset at *x* with maximum
*L*, steepness *k*, inflection point *x0*, and offset *a*
"""
return k * L / (2. * (np.cosh(k * (x - x0)) + 1.))
def dlogistic_offset_p(x, p):
"""
Wrapper function for :func:`dlogistic_offset`: `dlogistic_offset(x, *p)`
"""
return dlogistic_offset(x, *p)
# -----------------------------------------------------------
# 2nd derivative of logistic functions with offset
def d2logistic_offset(x, L, k, x0, a):
"""
Second derivative of :func:`logistic_offset` function
.. math::
L/(1+exp(-k(x-x0))) + a
which is
.. math::
-k^2.L.sinh(k(x-x0))/(2(cosh(k(x-x0))+1)^2)
Parameters
----------
x : array_like
Independent variable to evalute derivative of logistic function
L : float
Maximum of logistic function
k : float
Steepness of logistic function
x0 : float
Inflection point of logistic function
a : float
Offset of logistic function
Returns
-------
float or ndarray
Second derivative of logistic function at *x* with maximum *L*,
steepness *k*, inflection point *x0*, and offset *a*
"""
return ( -k**2 * L * np.sinh(k * (x - x0)) /
(2. * (np.cosh(k * (x - x0)) + 1.)**2) )
def d2logistic_offset_p(x, p):
"""
Wrapper function for :func:`d2logistic_offset`: `d2logistic_offset(x, *p)`
"""
return d2logistic_offset(x, *p)
# -----------------------------------------------------------
# L/(1+exp(-k(x-x0))) + a - logistic function with offset
def logistic2_offset(x, L1, k1, x01, L2, k2, x02, a):
"""
Double logistic function with offset
.. math::
L1/(1+exp(-k1(x-x01))) - L2/(1+exp(-k2(x-x02))) + a
Parameters
----------
x : array_like
Independent variable to evalute logistic function
L1 : float
Maximum of first logistic function
k1 : float
Steepness of first logistic function
x01 : float
Inflection point of first logistic function
L2 : float
Maximum of second logistic function
k2 : float
Steepness of second logistic function
x02 : float
Inflection point of second logistic function
a : float
Offset of double logistic function
Returns
-------
float or ndarray
Double Logistic function at *x*
"""
return L1 * sp.expit(k1 * (x - x01)) - L2 * sp.expit(k2 * (x - x02)) + a
def logistic2_offset_p(x, p):
"""
Wrapper function for :func:`logistic2_offset`: `logistic2_offset(x, *p)`
"""
return logistic2_offset(x, *p)
# -----------------------------------------------------------
# 1st derivative of logistic functions with offset
def dlogistic2_offset(x, L1, k1, x01, L2, k2, x02, a):
"""
First derivative of :func:`logistic2_offset` function
.. math::
L1/(1+exp(-k1(x-x01))) - L2/(1+exp(-k2(x-x02))) + a
which is
.. math::
k1.L1/(2(cosh(k1(x-x01))+1)) - k2.L2/(2(cosh(k2(x-x02))+1))
Parameters
----------
x : array_like
Independent variable to evalute logistic function
L1 : float
Maximum of first logistic function
k1 : float
Steepness of first logistic function
x01 : float
Inflection point of first logistic function
L2 : float
Maximum of second logistic function
k2 : float
Steepness of second logistic function
x02 : float
Inflection point of second logistic function
a : float
Offset of double logistic function
Returns
-------
float or ndarray
First derivative of double logistic function with offset at *x*
"""
return ( k1 * L1 / (2. * (np.cosh(k1 * (x - x01)) + 1.)) -
k2 * L2 / (2. * (np.cosh(k2 * (x - x02)) + 1.)) )
def dlogistic2_offset_p(x, p):
"""
Wrapper function for :func:`dlogistic2_offset`: `dlogistic2_offset(x, *p)`
"""
return dlogistic2_offset(x, *p)
# -----------------------------------------------------------
# 2nd derivative of logistic functions with offset
def d2logistic2_offset(x, L1, k1, x01, L2, k2, x02, a):
"""
Second derivative of :func:`logistic_offset` function
.. math::
L1/(1+exp(-k1(x-x01))) - L2/(1+exp(-k2(x-x02))) + a
which is
.. math::
- k1^2.L1.sinh(k1(x-x01)) / (2(cosh(k1(x-x01))+1)^2)
+ k2^2.L2.sinh(k2(x-x02)) / (2(cosh(k2(x-x02))+1)^2)
Parameters
----------
x : array_like
Independent variable to evalute logistic function
L1 : float
Maximum of first logistic function
k1 : float
Steepness of first logistic function
x01 : float
Inflection point of first logistic function
L2 : float
Maximum of second logistic function
k2 : float
Steepness of second logistic function
x02 : float
Inflection point of second logistic function
a : float
Offset of double logistic function
Returns
-------
float or ndarray
Second derivative of double logistic function with offset at *x*
"""
return ( -k1**2 * L1 * np.sinh(k1 * (x - x01)) /
(2. * (np.cosh(k1 * (x - x01)) + 1.)**2) +
k2**2 * L2 * np.sinh(k2 * (x - x02)) /
(2. * (np.cosh(k2 * (x - x02)) + 1.)**2) )
def d2logistic2_offset_p(x, p):
"""
Wrapper function for
:func:`d2logistic2_offset`: `d2logistic2_offset(x, *p)`
"""
return d2logistic2_offset(x, *p)
# -----------------------------------------------------------
if __name__ == '__main__':
import doctest
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
# logistic(1., 1., 0., 2.)
# # 0.5
# logistic(1., 1., 2., 1.)
# # 0.5
# logistic(2., 1., 1., 1.)
# # 1./(1.+np.exp(-1.))
# # 0.7310585786300049
# logistic_p(1., [1., 0., 2.])
# logistic_p(1., [1., 2., 1.])
# logistic_p(2., [1., 1., 1.])
# logistic_offset(1., 1., 0., 2., 1.)
# logistic_offset(1., 1., 2., 1., 1.)
# # 1.5
# logistic_offset(2., 1., 1., 1., 1.)
# # 1./(1.+np.exp(-1.)) + 1.
# # 1.7310585786300049
# logistic_offset_p(1., [1., 0., 2., 1.])
# logistic_offset_p(1., [1., 2., 1., 1.])
# logistic_offset_p(2., [1., 1., 1., 1.])
# logistic2_offset(1., 1., 2., 1., 2., 2., 1., 1.)
# # 0.5
# logistic2_offset_p(1., [1., 2., 1., 2., 2., 1., 1.])
# dlogistic(1., 1., 2., 1.)
# # 0.5
# dlogistic_offset(1., 1., 2., 1., 1.)
# # 0.5
# dlogistic2_offset(1., 1., 2., 1., 2., 2., 1., 1.)
# # -0.5
# print(np.around(d2logistic(1., 1., 2., 2.),4))
# # 0.3199
# print(np.around(d2logistic_offset(1., 1., 2., 2., 1.),4))
# # 0.3199
# print(np.around(d2logistic2_offset(1., 1., 2., 2., 2., 2., 2., 1.),4))
# # -0.3199
| [
"scipy.special.expit",
"numpy.cosh",
"numpy.sinh",
"doctest.testmod"
] | [((13054, 13111), 'doctest.testmod', 'doctest.testmod', ([], {'optionflags': 'doctest.NORMALIZE_WHITESPACE'}), '(optionflags=doctest.NORMALIZE_WHITESPACE)\n', (13069, 13111), False, 'import doctest\n'), ((3626, 3648), 'scipy.special.expit', 'sp.expit', (['(k * (x - x0))'], {}), '(k * (x - x0))\n', (3634, 3648), True, 'import scipy.special as sp\n'), ((5519, 5540), 'numpy.sinh', 'np.sinh', (['(k * (x - x0))'], {}), '(k * (x - x0))\n', (5526, 5540), True, 'import numpy as np\n'), ((6485, 6507), 'scipy.special.expit', 'sp.expit', (['(k * (x - x0))'], {}), '(k * (x - x0))\n', (6493, 6507), True, 'import scipy.special as sp\n'), ((8642, 8663), 'numpy.sinh', 'np.sinh', (['(k * (x - x0))'], {}), '(k * (x - x0))\n', (8649, 8663), True, 'import numpy as np\n'), ((4557, 4578), 'numpy.cosh', 'np.cosh', (['(k * (x - x0))'], {}), '(k * (x - x0))\n', (4564, 4578), True, 'import numpy as np\n'), ((7556, 7577), 'numpy.cosh', 'np.cosh', (['(k * (x - x0))'], {}), '(k * (x - x0))\n', (7563, 7577), True, 'import numpy as np\n'), ((9835, 9859), 'scipy.special.expit', 'sp.expit', (['(k1 * (x - x01))'], {}), '(k1 * (x - x01))\n', (9843, 9859), True, 'import scipy.special as sp\n'), ((9867, 9891), 'scipy.special.expit', 'sp.expit', (['(k2 * (x - x02))'], {}), '(k2 * (x - x02))\n', (9875, 9891), True, 'import scipy.special as sp\n'), ((12576, 12599), 'numpy.sinh', 'np.sinh', (['(k1 * (x - x01))'], {}), '(k1 * (x - x01))\n', (12583, 12599), True, 'import numpy as np\n'), ((12684, 12707), 'numpy.sinh', 'np.sinh', (['(k2 * (x - x02))'], {}), '(k2 * (x - x02))\n', (12691, 12707), True, 'import numpy as np\n'), ((5563, 5584), 'numpy.cosh', 'np.cosh', (['(k * (x - x0))'], {}), '(k * (x - x0))\n', (5570, 5584), True, 'import numpy as np\n'), ((8686, 8707), 'numpy.cosh', 'np.cosh', (['(k * (x - x0))'], {}), '(k * (x - x0))\n', (8693, 8707), True, 'import numpy as np\n'), ((11160, 11183), 'numpy.cosh', 'np.cosh', (['(k1 * (x - x01))'], {}), '(k1 * (x - x01))\n', (11167, 11183), True, 'import numpy as np\n'), ((11223, 11246), 'numpy.cosh', 'np.cosh', (['(k2 * (x - x02))'], {}), '(k2 * (x - x02))\n', (11230, 11246), True, 'import numpy as np\n'), ((12622, 12645), 'numpy.cosh', 'np.cosh', (['(k1 * (x - x01))'], {}), '(k1 * (x - x01))\n', (12629, 12645), True, 'import numpy as np\n'), ((12730, 12753), 'numpy.cosh', 'np.cosh', (['(k2 * (x - x02))'], {}), '(k2 * (x - x02))\n', (12737, 12753), True, 'import numpy as np\n')] |
import numpy as np
from .abstract_seair import AbstractSEAIR
from .ode_model import ODEModel
from ..packages import click
class SEAIR(ODEModel, AbstractSEAIR):
"""
A simple SIR model linearized around the DFE.
"""
def diff(self, x, t):
s, e, a, i, r = x
n = s + e + a + i + r
beta = self.beta
gamma = self.gamma
sigma = self.sigma
rho = self.rho
Qs = self.Qs
infections = beta * s * ((i + rho * a) / n)
return np.array(
[
-infections,
+infections - sigma * e,
+(1 - Qs) * sigma * e - gamma * a,
+Qs * sigma * e - gamma * i,
+gamma * (i + a),
]
)
if __name__ == "__main__":
@click.command()
@click.option("--R0", "-r", default=2.74, help="Reproduction number")
@click.option("--duration", "-t", default=90, type=int, help="Duration")
@click.option("--log", default=False, type=bool, help="Use log-scale?")
def cli(duration, r0, log):
m = SEAIR()
m.R0 = r0
m.run(duration)
m.plot(logy=log, show=True)
cli()
| [
"numpy.array"
] | [((503, 638), 'numpy.array', 'np.array', (['[-infections, +infections - sigma * e, +(1 - Qs) * sigma * e - gamma * a, +\n Qs * sigma * e - gamma * i, +gamma * (i + a)]'], {}), '([-infections, +infections - sigma * e, +(1 - Qs) * sigma * e - \n gamma * a, +Qs * sigma * e - gamma * i, +gamma * (i + a)])\n', (511, 638), True, 'import numpy as np\n')] |
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import neighbors
from sklearn.model_selection import train_test_split
import sklearn.neighbors
from mlxtend.plotting import plot_decision_regions
import numpy as np
from sklearn.metrics import confusion_matrix, classification_report
def split_input_data(data):
x1 = pd.read_csv("A1-inputData.csv")['paramA'].array
x2 = pd.read_csv("A1-inputData.csv")['paramB'].array
x = [[x, y] for x, y in zip(x1, x2)]
y = pd.read_csv("A1-inputData.csv")['Class'].array
X_train, X_test, y_train, y_test = train_test_split(x, y)
return X_train, X_test, y_train, y_test
def display_contours(classifier, number_of_neighbors, x, y):
plot_decision_regions(np.asarray(x), np.asarray(y), clf=classifier, legend=2)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('KNN with K = x')
plt.show()
def knn(nneighbors, X_train, y_train, X_test):
clf = neighbors.KNeighborsRegressor(nneighbors)
clf.fit(X_train, y_train)
predicted_y = clf.predict(X_test)
display_contours(clf, nneighbors, X_train, y_train)
return predicted_y
def evaluateknn(y_predicted, y_test):
df = pd.DataFrame(y_predicted)
products_list = df.values.reshape(-1,).tolist()
products_list = [int(x) for x in products_list]
df = pd.DataFrame(y_test)
products_list2 = df.values.reshape(-1,).tolist()
products_list2 = [int(x) for x in products_list2]
print("Classification report: ")
print(classification_report(products_list2, products_list))
print("Confusion matrix: ")
print(confusion_matrix(products_list2, products_list))
#y_test, y_predicted))
if __name__ == "__main__":
input_data = pd.read_csv("A1-inputData.csv")
X_train, X_test, y_train, y_test = split_input_data(input_data)
predicted_y = knn(3, X_train, y_train, X_test)
evaluateknn(predicted_y, y_test)
| [
"matplotlib.pyplot.title",
"pandas.DataFrame",
"sklearn.metrics.confusion_matrix",
"sklearn.neighbors.KNeighborsRegressor",
"matplotlib.pyplot.show",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"numpy.asarray",
"sklearn.metrics.classification_report",
"matplotlib.pyplot.ylabel",... | [((577, 599), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {}), '(x, y)\n', (593, 599), False, 'from sklearn.model_selection import train_test_split\n'), ((793, 808), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""X"""'], {}), "('X')\n", (803, 808), True, 'import matplotlib.pyplot as plt\n'), ((813, 828), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Y"""'], {}), "('Y')\n", (823, 828), True, 'import matplotlib.pyplot as plt\n'), ((833, 860), 'matplotlib.pyplot.title', 'plt.title', (['"""KNN with K = x"""'], {}), "('KNN with K = x')\n", (842, 860), True, 'import matplotlib.pyplot as plt\n'), ((865, 875), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (873, 875), True, 'import matplotlib.pyplot as plt\n'), ((935, 976), 'sklearn.neighbors.KNeighborsRegressor', 'neighbors.KNeighborsRegressor', (['nneighbors'], {}), '(nneighbors)\n', (964, 976), False, 'from sklearn import neighbors\n'), ((1173, 1198), 'pandas.DataFrame', 'pd.DataFrame', (['y_predicted'], {}), '(y_predicted)\n', (1185, 1198), True, 'import pandas as pd\n'), ((1313, 1333), 'pandas.DataFrame', 'pd.DataFrame', (['y_test'], {}), '(y_test)\n', (1325, 1333), True, 'import pandas as pd\n'), ((1707, 1738), 'pandas.read_csv', 'pd.read_csv', (['"""A1-inputData.csv"""'], {}), "('A1-inputData.csv')\n", (1718, 1738), True, 'import pandas as pd\n'), ((733, 746), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (743, 746), True, 'import numpy as np\n'), ((748, 761), 'numpy.asarray', 'np.asarray', (['y'], {}), '(y)\n', (758, 761), True, 'import numpy as np\n'), ((1489, 1541), 'sklearn.metrics.classification_report', 'classification_report', (['products_list2', 'products_list'], {}), '(products_list2, products_list)\n', (1510, 1541), False, 'from sklearn.metrics import confusion_matrix, classification_report\n'), ((1585, 1632), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['products_list2', 'products_list'], {}), '(products_list2, products_list)\n', (1601, 1632), False, 'from sklearn.metrics import confusion_matrix, classification_report\n'), ((336, 367), 'pandas.read_csv', 'pd.read_csv', (['"""A1-inputData.csv"""'], {}), "('A1-inputData.csv')\n", (347, 367), True, 'import pandas as pd\n'), ((393, 424), 'pandas.read_csv', 'pd.read_csv', (['"""A1-inputData.csv"""'], {}), "('A1-inputData.csv')\n", (404, 424), True, 'import pandas as pd\n'), ((490, 521), 'pandas.read_csv', 'pd.read_csv', (['"""A1-inputData.csv"""'], {}), "('A1-inputData.csv')\n", (501, 521), True, 'import pandas as pd\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 8 17:15:32 2021
@author: rolly
"""
from tensorflow.keras.models import Sequential,load_model
from tensorflow.keras.layers import Dense
from tensorflow.keras.losses import MeanSquaredError
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import device
from tensorflow.python.client.device_lib import list_local_devices
import scipy.io
from skimage.metrics import structural_similarity
import cv2
import math
def getdatatrainfrommat(matfile):
mat = scipy.io.loadmat(matfile)
train_data,label=loadtrainandlabel(mat)
images=np.delete(label,0,1)
return train_data,images
def getdatatestfrommat(matfile):
mat = scipy.io.loadmat(matfile)
train_data,label=loadtestandlabel(mat)
images=np.delete(label,0,1)
return train_data,images
def trainModel(matfile,arch):
mat = scipy.io.loadmat(matfile)
train_data,label=loadtrainandlabel(mat)
for x in range(1,101):#pembentukan model dari pixel 1-100
labelperpx=getlabel(label,x)#mendapatkan label per pixel
path=modelfolderpath(matfile)+str(arch)+'\\'+str(x)#melakukan set path model
createmodel(train_data,labelperpx,path,arch)#membuat dan menyimpan model
def testModel(matfile,arch):
mat = scipy.io.loadmat(matfile)
testdt,testlb=loadtestandlabel(mat)
pixel=1
path=modelfolderpath(matfile)+str(arch)+'\\'+str(pixel)
print(path)
piksel=generatePixel(path,testdt)
for x in range(2,101):
path=modelfolderpath(matfile)+str(arch)+'\\'+str(x)
pikselbr=generatePixel(path,testdt)
piksel=np.concatenate((piksel,pikselbr),axis=1)
pxlb=delfirstCol(testlb)
return pxlb,piksel
def simpanSemuaGambar(pxlb,piksel,matfile):
n=1
for stim,recon in zip(pxlb,piksel):
simpanGambar(stim,recon,getfigpath(matfile,'reconstruct',n))
n=n+1
def simpanScore(label,pred,matfile,arch):
allres=np.zeros(shape=(1,4))
for limagerow,predimagerow in zip(label,pred):
mlabel=rowtoimagematrix(limagerow)
mpred=rowtoimagematrix(predimagerow)
mseresult=msescore(mlabel,mpred)
ssimresult=ssimscore(mlabel,mpred)
psnrresult=psnrscore(mlabel,mpred)
corrresult=corrscore(mlabel,mpred)
therow=np.array([[mseresult,ssimresult,psnrresult,corrresult]])
allres=np.concatenate((allres,therow),axis=0)
fname=msefilename(matfile,arch)
createfolder(getfoldernamefrompath(fname))
allres = np.delete(allres, (0), axis=0)
print(fname)
np.savetxt(fname,allres,delimiter=',', fmt='%f')
return allres
def simpanMSE(label,pred,matfile,arch):#matfile digunakan untuk menamai file
#mse sendiri
mse = ((label - pred)**2).mean(axis=1)
fname=msefilename(matfile,arch)
createfolder(getfoldernamefrompath(fname))
np.savetxt(fname,mse,delimiter=',')
return mse
def simpanScoreMiyawaki():
directory='../imgRecon/result/s1/V1/smlr/'
#matfilename='s1_V1_Ecc1to11_baseByRestPre_smlr_s1071119ROI_resol10_figRecon_linComb-no_opt_1x1_maxProbLabel_dimNorm.mat'
matfilename='s1_V1_Ecc1to11_baseByRestPre_smlr_s1071119ROI_resol10_figRecon_linComb-errFuncImageNonNegCon_1x1_maxProbLabel_dimNorm.mat'
matfile=directory+matfilename
mat = scipy.io.loadmat(matfile)
pred,label=mat['stimFigTestAllPre'],mat['stimFigTestAll']
allres=np.zeros(shape=(1,4))
for limagerow,predimagerow in zip(label,pred):
mlabel=rowtoimagematrix(limagerow)
mpred=rowtoimagematrix(predimagerow)
mseresult=msescore(mlabel,mpred)
ssimresult=ssimscore(mlabel,mpred)
psnrresult=psnrscore(mlabel,mpred)
corrresult=corrscore(mlabel,mpred)
therow=np.array([[mseresult,ssimresult,psnrresult,corrresult]])
allres=np.concatenate((allres,therow),axis=0)
allres = np.delete(allres, (0), axis=0)
np.savetxt('miyawaki.csv',allres,delimiter=',', fmt='%f')
return pred,label,allres
def simpanMSEMiyawaki():
directory='../imgRecon/result/s1/V1/smlr/'
#matfilename='s1_V1_Ecc1to11_baseByRestPre_smlr_s1071119ROI_resol10_figRecon_linComb-no_opt_1x1_maxProbLabel_dimNorm.mat'
matfilename='s1_V1_Ecc1to11_baseByRestPre_smlr_s1071119ROI_resol10_figRecon_linComb-errFuncImageNonNegCon_1x1_maxProbLabel_dimNorm.mat'
matfile=directory+matfilename
mat = scipy.io.loadmat(matfile)
pred,label=mat['stimFigTestAllPre'],mat['stimFigTestAll']
mse = ((pred - label)**2).mean(axis=1)
np.savetxt('miyawaki.csv',mse,delimiter=',')
return pred,label,mse
def testingGPUSupport():
local_device_protos = list_local_devices()
print(local_device_protos)
def runOnGPU(model):
with device('/gpu:0'):
model.fit()
def loaddatanorest(mat):
mdata =mat['D']
mdtype = mdata .dtype
ndata = {n: mdata[n][0, 0] for n in mdtype.names}
label = ndata['label']
data = ndata['data']
nl=[]
nd=[]
for l,d in zip(label,data):
if l[1] < 2:
nl.append(l)
nd.append(d)
return nl,nd
def loadtestandlabel(mat):
nl,nd=loaddatanorest(mat)
label=nl[440:]
data=nd[440:]
return np.asarray(data, dtype=np.float64),np.asarray(label, dtype=np.float64)
def loadtrainandlabel(mat):
nl,nd=loaddatanorest(mat)
alllabel=nl[:440]
rdata=nd[:440]
return np.asarray(rdata, dtype=np.float64),np.asarray(alllabel, dtype=np.float64)
def getlabel(alllabel,x):
px1=[]
for i in alllabel:
px1.append(i[x])
label_data=np.asarray(px1, dtype=np.float64)
return label_data
#https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/
def createmodel(train_data,label_data,filename,arch):
X = train_data#440row
y = label_data
featurelength=len(train_data[0])
print('feature leength : ')#967
print(featurelength)
arcl=arch.split('_')
print(arcl)
# define the keras model
model = Sequential()
firstarch=int(arcl.pop(0))
model.add(Dense(firstarch, input_dim=featurelength, activation='sigmoid'))
for arc in arcl:
model.add(Dense(int(arc),activation='relu'))
if firstarch != 1:
model.add(Dense(1, activation='sigmoid'))
# compile the keras model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
#model.compile(loss=MeanSquaredError(), optimizer='adam', metrics=['accuracy'])
model.summary()
model.fit(X, y, epochs=500, batch_size=40)
# evaluate the keras model
_, accuracy = model.evaluate(X, y)
print('Accuracy: %.2f' % (accuracy*100))
model.save(str(filename))
def generatePixel(pxpath,data):
print(pxpath)
model = load_model(pxpath)
#return model.predict_classes(data)
res = model.predict(data)
#print(res)
return res
def showFig(az):
gbr = az.reshape((10,10)).T
plt.imshow(gbr)
def getfoldernamefrompath(fullpath):
return fullpath.split('\\')[-2]
def getsubfolderfrompath(fullpath):
mf=fullpath.split('\\')[-3]
subf=fullpath.split('\\')[-2]
return './'+mf+'/'+subf
def createfolder(foldername):
import os
if not os.path.exists(foldername):
print('membuat folder baru : '+foldername)
os.makedirs(foldername)
def saveFig(az,fname):
createfolder(getfoldernamefrompath(fname))
data = az.reshape((10,10)).T
new_data = np.zeros(np.array(data.shape) * 10)
for j in range(data.shape[0]):
for k in range(data.shape[1]):
new_data[j * 10: (j+1) * 10, k * 10: (k+1) * 10] = data[j, k]
print('menyimpan gambar : '+fname)
plt.imsave(str(fname),new_data)
def simpanGambar(stim,recon,fname):
createfolder(getfoldernamefrompath(fname))
plt.figure()
sp1 = plt.subplot(131)
sp1.axis('off')
plt.title('Stimulus')
sp2 = plt.subplot(132)
sp2.axis('off')
plt.title('Reconstruction')
sp3 = plt.subplot(133)
sp3.axis('off')
plt.title('Binarized')
sp1.imshow(stim.reshape((10,10)).T, cmap=plt.cm.gray,
interpolation='nearest'),
sp2.imshow(recon.reshape((10,10)).T, cmap=plt.cm.gray,
interpolation='nearest'),
sp3.imshow(np.reshape(recon > .5, (10, 10)).T, cmap=plt.cm.gray,
interpolation='nearest')
plt.savefig(fname)
def rowtoimagematrix(rowimage):
matriximage=rowimage.reshape((10,10)).T
return matriximage
def plotting(label,pred,predm,fname):
cols=['stimulus','rolly','miyawaki']
fig, ax = plt.subplots(nrows=10, ncols=3,figsize=(5, 20))
for axes, col in zip(ax[0], cols):
axes.set_title(col)
for row,fig,p,pm in zip(ax,label,pred,predm):
row[0].axis('off')
row[1].axis('off')
row[2].axis('off')
row[0].imshow(fig.reshape((10,10)).T, cmap=plt.cm.gray,
interpolation='nearest'),
row[1].imshow(p.reshape((10,10)).T, cmap=plt.cm.gray,
interpolation='nearest'),
row[2].imshow(pm.reshape((10, 10)).T, cmap=plt.cm.gray,
interpolation='nearest')
plt.show()
def plotHasil(label,pred,predm,mse,msem,matfile,n,arch):
fname1=getfigpath(matfile,'resultpict'+'\\'+arch,n)
createfolder(getsubfolderfrompath(fname1))
rows=['Stimulus','Rolly','Miyawaki']
idx=list(range(1,len(mse)+1))
fig, ax = plt.subplots(nrows=3, ncols=10,figsize=(15, 5))
for axes, row in zip(ax[:,0], rows):
axes.set_ylabel(row, rotation=90, size='large')
for idn,col,fig in zip(idx,ax[0],label):
col.set_yticklabels([])
col.set_yticks([])
col.set_xticklabels([])
col.set_xticks([])
col.imshow(fig.reshape((10,10)).T, cmap=plt.cm.gray,interpolation='nearest')
col.set_title(idn)
for col,p in zip(ax[1],pred):
col.set_yticklabels([])
col.set_yticks([])
col.set_xticklabels([])
col.set_xticks([])
col.imshow(p.reshape((10,10)).T, cmap=plt.cm.gray,interpolation='nearest')
for col,pm in zip(ax[2],predm):
col.set_yticklabels([])
col.set_yticks([])
col.set_xticklabels([])
col.set_xticks([])
col.imshow(pm.reshape((10,10)).T, cmap=plt.cm.gray,interpolation='nearest')
plt.suptitle(' Hasil Rekonstruksi Multilayer Perceptron : '+arch+', bagian ke-'+str(n), fontsize=16)
# plt.show()
plt.savefig(fname1)
fname2=getfigpath(matfile,'resultmse'+'\\'+arch,n)
createfolder(getsubfolderfrompath(fname2))
fige, axe = plt.subplots(figsize=(15, 5))
axe.plot(idx, mse, color = 'green', label = 'mse rolly')
axe.plot(idx, msem, color = 'red', label = 'mse miyawaki')
axe.legend(loc = 'lower left')
axe.set_xticks(idx)
# plt.show()
plt.suptitle('Perbandingan Mean Suare Error', fontsize=16)
plt.savefig(fname2)
import PIL
fnamegab=getfigpath(matfile,'results'+'\\'+arch,n)
createfolder(getsubfolderfrompath(fnamegab))
list_im = [fname1, fname2]
imgs = [ PIL.Image.open(i) for i in list_im ]
min_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]
imgs_comb = np.hstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )
imgs_comb = np.vstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )
imgs_comb = PIL.Image.fromarray( imgs_comb)
imgs_comb.save(fnamegab)
def plotDGMM(label,pred,predm,mse,msem,matfile,n,arch):
fname1=getfigpath(matfile,'resultpict'+'\\'+arch,n)
createfolder(getsubfolderfrompath(fname1))
rows=['Stimulus','DGMM','Miyawaki']
idx=list(range(1,len(mse)+1))
fig, ax = plt.subplots(nrows=3, ncols=10,figsize=(15, 5))
for axes, row in zip(ax[:,0], rows):
axes.set_ylabel(row, rotation=90, size='large')
for idn,col,fig in zip(idx,ax[0],label):
col.set_yticklabels([])
col.set_yticks([])
col.set_xticklabels([])
col.set_xticks([])
col.imshow(fig.reshape((10,10)).T, cmap=plt.cm.gray,interpolation='nearest')
col.set_title(idn)
for col,p in zip(ax[1],pred):
col.set_yticklabels([])
col.set_yticks([])
col.set_xticklabels([])
col.set_xticks([])
col.imshow(p.reshape((10,10)).T, cmap=plt.cm.gray,interpolation='nearest')
for col,pm in zip(ax[2],predm):
col.set_yticklabels([])
col.set_yticks([])
col.set_xticklabels([])
col.set_xticks([])
col.imshow(pm.reshape((10,10)).T, cmap=plt.cm.gray,interpolation='nearest')
plt.suptitle(' Perbandingan Rekonstruksi '+arch+' dan Miyawaki, bagian ke-'+str(n), fontsize=16)
# plt.show()
plt.savefig(fname1)
fname2=getfigpath(matfile,'resultmse'+'\\'+arch,n)
createfolder(getsubfolderfrompath(fname2))
fige, axe = plt.subplots(figsize=(15, 5))
axe.plot(idx, mse, color = 'green', label = 'mse dgmm')
axe.plot(idx, msem, color = 'red', label = 'mse miyawaki')
axe.legend(loc = 'lower left')
axe.set_xticks(idx)
# plt.show()
plt.suptitle('Perbandingan Mean Square Error', fontsize=16)
plt.savefig(fname2)
import PIL
fnamegab=getfigpath(matfile,'results'+'\\'+arch,n)
createfolder(getsubfolderfrompath(fnamegab))
list_im = [fname1, fname2]
imgs = [ PIL.Image.open(i) for i in list_im ]
min_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]
imgs_comb = np.hstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )
imgs_comb = np.vstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )
imgs_comb = PIL.Image.fromarray( imgs_comb)
imgs_comb.save(fnamegab)
def delfirstCol(testlb):
return np.delete(testlb,0,1)
def modelfolderpath(matfile):
mpath='.\\'+matfile.split('_')[2]+'_'+matfile.split('_')[-2]+'\\'
return mpath
def figfile(matfile,n):
figfolderpath='.\\'+matfile.split('_')[2]+'_'+matfile.split('_')[-2]+'_fig'+'\\'+str(n)+'.png'
return figfolderpath
def figrecfile(matfile,n):
figfolderpath='.\\'+matfile.split('_')[2]+'_'+matfile.split('_')[-2]+'_figrec'+'\\'+str(n)+'.png'
return figfolderpath
def getfigpath(matfile,suffix,n):
import pathlib
scriptDirectory = pathlib.Path().absolute()
figfolderpath=str(scriptDirectory)+'\\'+matfile.split('_')[2]+'_'+matfile.split('_')[-2]+'_'+suffix+'\\'+str(n)+'.png'
print('generate path gambar : '+figfolderpath)
return figfolderpath
def msefilename(matfile,arch):
import pathlib
scriptDirectory = pathlib.Path().absolute()
figfolderpath=str(scriptDirectory)+'\\'+matfile.split('_')[2]+'_'+matfile.split('_')[-2]+'_mse'+'\\'+str(arch)+'.csv'
return figfolderpath
def divide_chunks(l, n):
# looping till length l
for i in range(0, len(l), n):
yield l[i:i + n]
def ubahkelistofchunks(mse,msem,pred,predm,label,n):
mse=mse.tolist()
msem=msem.tolist()
lmse=list(divide_chunks(mse, n))
lmsem=list(divide_chunks(msem, n))
lpred=list(divide_chunks(pred, n))
lpredm=list(divide_chunks(predm, n))
llabel=list(divide_chunks(label, n))
return lmse,lmsem,lpred,lpredm,llabel
def ssimscore(matrixgambar1,matrixgambar2):
# SSIM: 1.0 is similar
(score, diff) = structural_similarity(matrixgambar1, matrixgambar2, full=True)
diff = (diff * 255).astype("uint8")
# 6. You can print only the score if you want
print("SSIM: {}".format(score))
return score
def msescore(matrixgambar1,matrixgambar2):
#mse 0:similar
mse = np.mean( (matrixgambar1 - matrixgambar2) ** 2 )
#mse = ((original - contrast)**2).mean(axis=1)
return mse
def psnrscore(matrixgambar1,matrixgambar2):
#psnr 1:similar
mse = np.mean( (matrixgambar1 - matrixgambar2) ** 2 )
if mse == 0:
psnr = 100
else:
PIXEL_MAX = 255.0
psnr = 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
return psnr/100
def corrscore(matrixgambar1,matrixgambar2):
#1 maka similar
cor = np.corrcoef(matrixgambar1.reshape(-1),matrixgambar2.reshape(-1))[0][1]
return cor | [
"matplotlib.pyplot.title",
"numpy.sum",
"tensorflow.keras.layers.Dense",
"matplotlib.pyplot.suptitle",
"matplotlib.pyplot.figure",
"numpy.mean",
"pathlib.Path",
"tensorflow.keras.models.Sequential",
"matplotlib.pyplot.imshow",
"numpy.savetxt",
"os.path.exists",
"numpy.reshape",
"matplotlib.p... | [((600, 622), 'numpy.delete', 'np.delete', (['label', '(0)', '(1)'], {}), '(label, 0, 1)\n', (609, 622), True, 'import numpy as np\n'), ((774, 796), 'numpy.delete', 'np.delete', (['label', '(0)', '(1)'], {}), '(label, 0, 1)\n', (783, 796), True, 'import numpy as np\n'), ((1942, 1964), 'numpy.zeros', 'np.zeros', ([], {'shape': '(1, 4)'}), '(shape=(1, 4))\n', (1950, 1964), True, 'import numpy as np\n'), ((2495, 2523), 'numpy.delete', 'np.delete', (['allres', '(0)'], {'axis': '(0)'}), '(allres, 0, axis=0)\n', (2504, 2523), True, 'import numpy as np\n'), ((2547, 2597), 'numpy.savetxt', 'np.savetxt', (['fname', 'allres'], {'delimiter': '""","""', 'fmt': '"""%f"""'}), "(fname, allres, delimiter=',', fmt='%f')\n", (2557, 2597), True, 'import numpy as np\n'), ((2839, 2876), 'numpy.savetxt', 'np.savetxt', (['fname', 'mse'], {'delimiter': '""","""'}), "(fname, mse, delimiter=',')\n", (2849, 2876), True, 'import numpy as np\n'), ((3378, 3400), 'numpy.zeros', 'np.zeros', ([], {'shape': '(1, 4)'}), '(shape=(1, 4))\n', (3386, 3400), True, 'import numpy as np\n'), ((3848, 3876), 'numpy.delete', 'np.delete', (['allres', '(0)'], {'axis': '(0)'}), '(allres, 0, axis=0)\n', (3857, 3876), True, 'import numpy as np\n'), ((3883, 3942), 'numpy.savetxt', 'np.savetxt', (['"""miyawaki.csv"""', 'allres'], {'delimiter': '""","""', 'fmt': '"""%f"""'}), "('miyawaki.csv', allres, delimiter=',', fmt='%f')\n", (3893, 3942), True, 'import numpy as np\n'), ((4488, 4534), 'numpy.savetxt', 'np.savetxt', (['"""miyawaki.csv"""', 'mse'], {'delimiter': '""","""'}), "('miyawaki.csv', mse, delimiter=',')\n", (4498, 4534), True, 'import numpy as np\n'), ((4611, 4631), 'tensorflow.python.client.device_lib.list_local_devices', 'list_local_devices', ([], {}), '()\n', (4629, 4631), False, 'from tensorflow.python.client.device_lib import list_local_devices\n'), ((5527, 5560), 'numpy.asarray', 'np.asarray', (['px1'], {'dtype': 'np.float64'}), '(px1, dtype=np.float64)\n', (5537, 5560), True, 'import numpy as np\n'), ((5943, 5955), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (5953, 5955), False, 'from tensorflow.keras.models import Sequential, load_model\n'), ((6692, 6710), 'tensorflow.keras.models.load_model', 'load_model', (['pxpath'], {}), '(pxpath)\n', (6702, 6710), False, 'from tensorflow.keras.models import Sequential, load_model\n'), ((6866, 6881), 'matplotlib.pyplot.imshow', 'plt.imshow', (['gbr'], {}), '(gbr)\n', (6876, 6881), True, 'import matplotlib.pyplot as plt\n'), ((7728, 7740), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (7738, 7740), True, 'import matplotlib.pyplot as plt\n'), ((7751, 7767), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(131)'], {}), '(131)\n', (7762, 7767), True, 'import matplotlib.pyplot as plt\n'), ((7792, 7813), 'matplotlib.pyplot.title', 'plt.title', (['"""Stimulus"""'], {}), "('Stimulus')\n", (7801, 7813), True, 'import matplotlib.pyplot as plt\n'), ((7824, 7840), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(132)'], {}), '(132)\n', (7835, 7840), True, 'import matplotlib.pyplot as plt\n'), ((7865, 7892), 'matplotlib.pyplot.title', 'plt.title', (['"""Reconstruction"""'], {}), "('Reconstruction')\n", (7874, 7892), True, 'import matplotlib.pyplot as plt\n'), ((7903, 7919), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(133)'], {}), '(133)\n', (7914, 7919), True, 'import matplotlib.pyplot as plt\n'), ((7944, 7966), 'matplotlib.pyplot.title', 'plt.title', (['"""Binarized"""'], {}), "('Binarized')\n", (7953, 7966), True, 'import matplotlib.pyplot as plt\n'), ((8279, 8297), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname'], {}), '(fname)\n', (8290, 8297), True, 'import matplotlib.pyplot as plt\n'), ((8492, 8540), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(10)', 'ncols': '(3)', 'figsize': '(5, 20)'}), '(nrows=10, ncols=3, figsize=(5, 20))\n', (8504, 8540), True, 'import matplotlib.pyplot as plt\n'), ((9054, 9064), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9062, 9064), True, 'import matplotlib.pyplot as plt\n'), ((9315, 9363), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(3)', 'ncols': '(10)', 'figsize': '(15, 5)'}), '(nrows=3, ncols=10, figsize=(15, 5))\n', (9327, 9363), True, 'import matplotlib.pyplot as plt\n'), ((10334, 10353), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname1'], {}), '(fname1)\n', (10345, 10353), True, 'import matplotlib.pyplot as plt\n'), ((10477, 10506), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(15, 5)'}), '(figsize=(15, 5))\n', (10489, 10506), True, 'import matplotlib.pyplot as plt\n'), ((10711, 10769), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""Perbandingan Mean Suare Error"""'], {'fontsize': '(16)'}), "('Perbandingan Mean Suare Error', fontsize=16)\n", (10723, 10769), True, 'import matplotlib.pyplot as plt\n'), ((10774, 10793), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname2'], {}), '(fname2)\n', (10785, 10793), True, 'import matplotlib.pyplot as plt\n'), ((11266, 11296), 'PIL.Image.fromarray', 'PIL.Image.fromarray', (['imgs_comb'], {}), '(imgs_comb)\n', (11285, 11296), False, 'import PIL\n'), ((11575, 11623), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(3)', 'ncols': '(10)', 'figsize': '(15, 5)'}), '(nrows=3, ncols=10, figsize=(15, 5))\n', (11587, 11623), True, 'import matplotlib.pyplot as plt\n'), ((12590, 12609), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname1'], {}), '(fname1)\n', (12601, 12609), True, 'import matplotlib.pyplot as plt\n'), ((12733, 12762), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(15, 5)'}), '(figsize=(15, 5))\n', (12745, 12762), True, 'import matplotlib.pyplot as plt\n'), ((12966, 13025), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""Perbandingan Mean Square Error"""'], {'fontsize': '(16)'}), "('Perbandingan Mean Square Error', fontsize=16)\n", (12978, 13025), True, 'import matplotlib.pyplot as plt\n'), ((13030, 13049), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname2'], {}), '(fname2)\n', (13041, 13049), True, 'import matplotlib.pyplot as plt\n'), ((13522, 13552), 'PIL.Image.fromarray', 'PIL.Image.fromarray', (['imgs_comb'], {}), '(imgs_comb)\n', (13541, 13552), False, 'import PIL\n'), ((13625, 13648), 'numpy.delete', 'np.delete', (['testlb', '(0)', '(1)'], {}), '(testlb, 0, 1)\n', (13634, 13648), True, 'import numpy as np\n'), ((15167, 15229), 'skimage.metrics.structural_similarity', 'structural_similarity', (['matrixgambar1', 'matrixgambar2'], {'full': '(True)'}), '(matrixgambar1, matrixgambar2, full=True)\n', (15188, 15229), False, 'from skimage.metrics import structural_similarity\n'), ((15450, 15495), 'numpy.mean', 'np.mean', (['((matrixgambar1 - matrixgambar2) ** 2)'], {}), '((matrixgambar1 - matrixgambar2) ** 2)\n', (15457, 15495), True, 'import numpy as np\n'), ((15639, 15684), 'numpy.mean', 'np.mean', (['((matrixgambar1 - matrixgambar2) ** 2)'], {}), '((matrixgambar1 - matrixgambar2) ** 2)\n', (15646, 15684), True, 'import numpy as np\n'), ((1619, 1661), 'numpy.concatenate', 'np.concatenate', (['(piksel, pikselbr)'], {'axis': '(1)'}), '((piksel, pikselbr), axis=1)\n', (1633, 1661), True, 'import numpy as np\n'), ((2288, 2347), 'numpy.array', 'np.array', (['[[mseresult, ssimresult, psnrresult, corrresult]]'], {}), '([[mseresult, ssimresult, psnrresult, corrresult]])\n', (2296, 2347), True, 'import numpy as np\n'), ((2360, 2400), 'numpy.concatenate', 'np.concatenate', (['(allres, therow)'], {'axis': '(0)'}), '((allres, therow), axis=0)\n', (2374, 2400), True, 'import numpy as np\n'), ((3724, 3783), 'numpy.array', 'np.array', (['[[mseresult, ssimresult, psnrresult, corrresult]]'], {}), '([[mseresult, ssimresult, psnrresult, corrresult]])\n', (3732, 3783), True, 'import numpy as np\n'), ((3796, 3836), 'numpy.concatenate', 'np.concatenate', (['(allres, therow)'], {'axis': '(0)'}), '((allres, therow), axis=0)\n', (3810, 3836), True, 'import numpy as np\n'), ((4694, 4710), 'tensorflow.device', 'device', (['"""/gpu:0"""'], {}), "('/gpu:0')\n", (4700, 4710), False, 'from tensorflow import device\n'), ((5157, 5191), 'numpy.asarray', 'np.asarray', (['data'], {'dtype': 'np.float64'}), '(data, dtype=np.float64)\n', (5167, 5191), True, 'import numpy as np\n'), ((5192, 5227), 'numpy.asarray', 'np.asarray', (['label'], {'dtype': 'np.float64'}), '(label, dtype=np.float64)\n', (5202, 5227), True, 'import numpy as np\n'), ((5343, 5378), 'numpy.asarray', 'np.asarray', (['rdata'], {'dtype': 'np.float64'}), '(rdata, dtype=np.float64)\n', (5353, 5378), True, 'import numpy as np\n'), ((5379, 5417), 'numpy.asarray', 'np.asarray', (['alllabel'], {'dtype': 'np.float64'}), '(alllabel, dtype=np.float64)\n', (5389, 5417), True, 'import numpy as np\n'), ((6001, 6064), 'tensorflow.keras.layers.Dense', 'Dense', (['firstarch'], {'input_dim': 'featurelength', 'activation': '"""sigmoid"""'}), "(firstarch, input_dim=featurelength, activation='sigmoid')\n", (6006, 6064), False, 'from tensorflow.keras.layers import Dense\n'), ((7147, 7173), 'os.path.exists', 'os.path.exists', (['foldername'], {}), '(foldername)\n', (7161, 7173), False, 'import os\n'), ((7234, 7257), 'os.makedirs', 'os.makedirs', (['foldername'], {}), '(foldername)\n', (7245, 7257), False, 'import os\n'), ((10970, 10987), 'PIL.Image.open', 'PIL.Image.open', (['i'], {}), '(i)\n', (10984, 10987), False, 'import PIL\n'), ((13226, 13243), 'PIL.Image.open', 'PIL.Image.open', (['i'], {}), '(i)\n', (13240, 13243), False, 'import PIL\n'), ((6181, 6211), 'tensorflow.keras.layers.Dense', 'Dense', (['(1)'], {'activation': '"""sigmoid"""'}), "(1, activation='sigmoid')\n", (6186, 6211), False, 'from tensorflow.keras.layers import Dense\n'), ((7390, 7410), 'numpy.array', 'np.array', (['data.shape'], {}), '(data.shape)\n', (7398, 7410), True, 'import numpy as np\n'), ((8181, 8214), 'numpy.reshape', 'np.reshape', (['(recon > 0.5)', '(10, 10)'], {}), '(recon > 0.5, (10, 10))\n', (8191, 8214), True, 'import numpy as np\n'), ((14145, 14159), 'pathlib.Path', 'pathlib.Path', ([], {}), '()\n', (14157, 14159), False, 'import pathlib\n'), ((14443, 14457), 'pathlib.Path', 'pathlib.Path', ([], {}), '()\n', (14455, 14457), False, 'import pathlib\n'), ((15802, 15816), 'math.sqrt', 'math.sqrt', (['mse'], {}), '(mse)\n', (15811, 15816), False, 'import math\n'), ((11038, 11052), 'numpy.sum', 'np.sum', (['i.size'], {}), '(i.size)\n', (11044, 11052), True, 'import numpy as np\n'), ((13294, 13308), 'numpy.sum', 'np.sum', (['i.size'], {}), '(i.size)\n', (13300, 13308), True, 'import numpy as np\n')] |
import argparse
import logging
import nengo
from nengo import spa
import nengo_spinnaker
import numpy as np
from six import iteritems
import time
def label_net(network, prefixes=tuple()):
for net in network.networks:
label_net(net, prefixes + (net.label, ))
prefix = ".".join(p or "?" for p in prefixes)
for node in network.nodes:
node.label = "{}.{}".format(prefix, node.label)
def make_model(n_dimensions, seed):
"""Create a model with the given parameters."""
with spa.SPA(seed=seed) as model:
# Create the inputs
model.a = spa.State(dimensions=n_dimensions)
model.b = spa.State(dimensions=n_dimensions)
# Create the output
model.c = spa.State(dimensions=n_dimensions)
# Create the convolution
model.cortical = spa.Cortical(spa.Actions("c = a * b"), synapse=0.01)
# Add some input
model.input = spa.Input(a='A', b='B')
label_net(model)
return model
def run_experiment(model, spinnaker, placer):
"""Run the experiment and return the results in a dictionary."""
# Add probes for the output of the network
with model:
p_c = nengo.Probe(model.c.output, synapse=0.01)
# Create the simulator
if not spinnaker:
sim = nengo.Simulator(model)
else:
# Configure all the Nodes as function of time Nodes
nengo_spinnaker.add_spinnaker_params(model.config)
for n in model.all_nodes:
if n.output is not None:
model.config[n].function_of_time = True
# XXX
import importlib
model.config[nengo_spinnaker.Simulator].placer = \
importlib.import_module("rig.place_and_route.place.{}".format(placer)).place
sim = nengo_spinnaker.Simulator(model, use_spalloc=True, allocation_fudge_factor=2.0)
# Get the current number of dropped packets
dropped = sum(
sim.controller.get_router_diagnostics(x, y).dropped_multicast
for (x, y) in sim.controller.get_machine()
)
# Run the simulation
try:
sim.run(0.5)
# Get the vocabulary
vocab = model.get_output_vocab("c")
AB = vocab.parse("A * B").v
# Prepare the results for later analysis, recording the magnitude of the
# error vector
results = dict()
results["output"] = np.sqrt(np.sum(np.square(AB - sim.data[p_c]), axis=1))
results["times"] = sim.trange()
finally:
# Tidy up SpiNNaker and get the count of dropped packets
if spinnaker:
# Count the number of packets dropped during the simulation
results["dropped_multicast"] = sum(
sim.controller.get_router_diagnostics(x, y).dropped_multicast
for (x, y) in sim.controller.get_machine()
) - dropped
sim.close()
return results
def run_all_experiments(n_dimensions, spinnaker=False, runs_per_scale=30,
runs_per_seed=1, filename=None, placer="sa"):
"""Run a large number of experiments."""
# Initialise the results as empty lists
data = {"n_dimensions": list(),
"seed": list(),
"times": None,
"output": list()}
if spinnaker:
data["dropped_multicast"] = list()
# Repeatedly build and run the experiments
for n_dims in n_dimensions:
for seed in range(runs_per_scale):
for _ in range(runs_per_seed):
model = make_model(n_dims, seed)
try:
results = run_experiment(model, spinnaker, placer)
# Combine the results with the already stored results
data["n_dimensions"].append(n_dims)
data["seed"].append(seed)
for k, v in iteritems(results):
if k == "times":
if data["times"] is None:
data["times"] = v
else:
data[k].append(v)
finally:
pass
#except Exception as e:
# print("FAILED.")
# print(e)
# Store all the data in Numpy arrays and write to file
final_data = dict()
for k in ("n_dimensions", "seed"):
final_data[k] = np.array(data.pop(k), dtype=np.int)
for k, v in iteritems(data):
final_data[k] = np.array(v)
if filename is None:
filename = "cconv_{}_{}_{}_{}_{}_{}.npz".format(
"nengo" if not spinnaker else "spinnaker",
",".join(map(str, n_dimensions)),
placer,
runs_per_scale,
runs_per_seed,
int(time.time())
)
np.savez_compressed(filename, **final_data)
if __name__ == "__main__":
# Get the arguments from the command line
parser = argparse.ArgumentParser()
parser.add_argument("n_dimensions", nargs="+", type=int)
parser.add_argument("--runs", type=int, default=30)
parser.add_argument("--runs-per-seed", type=int, default=1)
parser.add_argument("-s", "--spinnaker", action="store_true")
parser.add_argument("--filename", type=str, default=None)
parser.add_argument("-v", "--verbosity", action="count", default=0)
parser.add_argument("-p", "--placer", type=str, default="sa")
args = parser.parse_args()
if args.verbosity == 1:
logging.basicConfig(level=logging.INFO)
if args.verbosity >= 2:
logging.basicConfig(level=logging.DEBUG)
# Run the experiment
run_all_experiments(args.n_dimensions,
args.spinnaker,
args.runs,
args.runs_per_seed,
args.filename,
args.placer)
| [
"nengo_spinnaker.Simulator",
"argparse.ArgumentParser",
"logging.basicConfig",
"nengo.spa.State",
"nengo_spinnaker.add_spinnaker_params",
"numpy.square",
"nengo.Probe",
"time.time",
"numpy.savez_compressed",
"nengo.spa.Input",
"numpy.array",
"nengo.spa.Actions",
"nengo.Simulator",
"six.ite... | [((4434, 4449), 'six.iteritems', 'iteritems', (['data'], {}), '(data)\n', (4443, 4449), False, 'from six import iteritems\n'), ((4790, 4833), 'numpy.savez_compressed', 'np.savez_compressed', (['filename'], {}), '(filename, **final_data)\n', (4809, 4833), True, 'import numpy as np\n'), ((4922, 4947), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4945, 4947), False, 'import argparse\n'), ((510, 528), 'nengo.spa.SPA', 'spa.SPA', ([], {'seed': 'seed'}), '(seed=seed)\n', (517, 528), False, 'from nengo import spa\n'), ((585, 619), 'nengo.spa.State', 'spa.State', ([], {'dimensions': 'n_dimensions'}), '(dimensions=n_dimensions)\n', (594, 619), False, 'from nengo import spa\n'), ((638, 672), 'nengo.spa.State', 'spa.State', ([], {'dimensions': 'n_dimensions'}), '(dimensions=n_dimensions)\n', (647, 672), False, 'from nengo import spa\n'), ((720, 754), 'nengo.spa.State', 'spa.State', ([], {'dimensions': 'n_dimensions'}), '(dimensions=n_dimensions)\n', (729, 754), False, 'from nengo import spa\n'), ((915, 938), 'nengo.spa.Input', 'spa.Input', ([], {'a': '"""A"""', 'b': '"""B"""'}), "(a='A', b='B')\n", (924, 938), False, 'from nengo import spa\n'), ((1172, 1213), 'nengo.Probe', 'nengo.Probe', (['model.c.output'], {'synapse': '(0.01)'}), '(model.c.output, synapse=0.01)\n', (1183, 1213), False, 'import nengo\n'), ((1278, 1300), 'nengo.Simulator', 'nengo.Simulator', (['model'], {}), '(model)\n', (1293, 1300), False, 'import nengo\n'), ((1379, 1429), 'nengo_spinnaker.add_spinnaker_params', 'nengo_spinnaker.add_spinnaker_params', (['model.config'], {}), '(model.config)\n', (1415, 1429), False, 'import nengo_spinnaker\n'), ((1761, 1840), 'nengo_spinnaker.Simulator', 'nengo_spinnaker.Simulator', (['model'], {'use_spalloc': '(True)', 'allocation_fudge_factor': '(2.0)'}), '(model, use_spalloc=True, allocation_fudge_factor=2.0)\n', (1786, 1840), False, 'import nengo_spinnaker\n'), ((4475, 4486), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (4483, 4486), True, 'import numpy as np\n'), ((5463, 5502), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (5482, 5502), False, 'import logging\n'), ((5539, 5579), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (5558, 5579), False, 'import logging\n'), ((827, 851), 'nengo.spa.Actions', 'spa.Actions', (['"""c = a * b"""'], {}), "('c = a * b')\n", (838, 851), False, 'from nengo import spa\n'), ((2395, 2424), 'numpy.square', 'np.square', (['(AB - sim.data[p_c])'], {}), '(AB - sim.data[p_c])\n', (2404, 2424), True, 'import numpy as np\n'), ((4762, 4773), 'time.time', 'time.time', ([], {}), '()\n', (4771, 4773), False, 'import time\n'), ((3835, 3853), 'six.iteritems', 'iteritems', (['results'], {}), '(results)\n', (3844, 3853), False, 'from six import iteritems\n')] |
import csv
import numpy as np
import math
import logging
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
class Logger(object):
def __init__(self, path, header):
self.log_file = open(path, 'w')
self.logger = csv.writer(self.log_file, delimiter='\t')
self.logger.writerow(header)
self.header = header
def __del(self):
self.log_file.close()
def log(self, values):
write_values = []
for col in self.header:
assert col in values
write_values.append(values[col])
self.logger.writerow(write_values)
self.log_file.flush()
def load_value_file(file_path):
with open(file_path, 'r') as input_file:
value = float(input_file.read().rstrip('\n\r'))
return value
def normalize_map(s_map, sim=False):
# normalize the salience map (as done in MIT code)
norm_s_map = (s_map - np.min(s_map)) / (np.max(s_map) - np.min(s_map))
if sim:
norm_s_map /= np.sum(norm_s_map)
return norm_s_map
def auc_judd_np(s_map, gt):
# Normalize saliency map to have values between [0,1]
s_map = normalize_map(s_map)
gt = normalize_map(gt)
S = s_map.ravel()
F = gt.ravel()
S_fix = S[F > 0] # Saliency map values at fixation locations
n_fix = len(S_fix)
n_pixels = len(S)
# Calculate AUC
thresholds = sorted(S_fix, reverse=True)
tp = np.zeros(len(thresholds) + 2)
fp = np.zeros(len(thresholds) + 2)
tp[0] = 0
tp[-1] = 1
fp[0] = 0
fp[-1] = 1
for k, thresh in enumerate(thresholds):
above_th = np.sum(S >= thresh) # Total number of saliency map values above threshold
tp[k + 1] = (k + 1) / float(n_fix) # Ratio saliency map values at fixation locations above threshold
fp[k + 1] = (above_th - k - 1) / float(n_pixels - n_fix) # Ratio other saliency map values above threshold
return np.trapz(tp, fp)
def auc_shuff(s_map, gt, other_map, n_splits=100, stepsize=0.1):
# If there are no fixations to predict, return NaN
if np.sum(gt) == 0:
print('no gt')
return None
# normalize saliency map
s_map = normalize_map(s_map)
S = s_map.flatten()
F = gt.flatten()
Oth = other_map.flatten()
Sth = S[F > 0] # sal map values at fixation locations
Nfixations = len(Sth)
# for each fixation, sample Nsplits values from the sal map at locations
# specified by other_map
ind = np.where(Oth > 0)[0] # find fixation locations on other images
Nfixations_oth = min(Nfixations, len(ind))
randfix = np.full((Nfixations_oth, n_splits), np.nan)
for i in range(n_splits):
# randomize choice of fixation locations
randind = np.random.permutation(ind.copy())
# sal map values at random fixation locations of other random images
randfix[:, i] = S[randind[:Nfixations_oth]]
# calculate AUC per random split (set of random locations)
auc = np.full(n_splits, np.nan)
for s in range(n_splits):
curfix = randfix[:, s]
allthreshes = np.flip(np.arange(0, max(np.max(Sth), np.max(curfix)), stepsize))
tp = np.zeros(len(allthreshes) + 2)
fp = np.zeros(len(allthreshes) + 2)
tp[-1] = 1
fp[-1] = 1
for i in range(len(allthreshes)):
thresh = allthreshes[i]
tp[i + 1] = np.sum(Sth >= thresh) / Nfixations
fp[i + 1] = np.sum(curfix >= thresh) / Nfixations_oth
auc[s] = np.trapz(np.array(tp), np.array(fp))
return np.mean(auc)
def similarity(s_map, gt):
s_map = normalize_map(s_map, sim=True)
gt = normalize_map(gt, sim=True)
return np.sum(np.minimum(s_map, gt))
def nss(s_map, gt):
s_map_norm = (s_map - np.mean(s_map)) / np.std(s_map)
x, y = np.where(gt == 1)
temp = []
for i in zip(x, y):
temp.append(s_map_norm[i[0], i[1]])
return np.mean(temp)
def cc(s_map, gt):
s_map_norm = (s_map - np.mean(s_map)) / np.std(s_map)
gt_norm = (gt - np.mean(gt)) / np.std(gt)
a = s_map_norm
b = gt_norm
r = (a * b).sum() / math.sqrt((a * a).sum() * (b * b).sum())
return r
def get_logger(filename, name=None):
logger = logging.getLogger(name)
logger.setLevel(level=logging.INFO)
fh = logging.FileHandler(filename)
formatter = logging.Formatter('%(asctime)s - %(filename)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
sh = logging.StreamHandler()
sh.setFormatter(formatter)
logger.addHandler(sh)
return logger
| [
"numpy.full",
"numpy.trapz",
"numpy.minimum",
"numpy.sum",
"logging.FileHandler",
"csv.writer",
"numpy.std",
"logging.StreamHandler",
"logging.Formatter",
"numpy.min",
"numpy.mean",
"numpy.where",
"numpy.max",
"numpy.array",
"logging.getLogger"
] | [((2250, 2266), 'numpy.trapz', 'np.trapz', (['tp', 'fp'], {}), '(tp, fp)\n', (2258, 2266), True, 'import numpy as np\n'), ((2925, 2968), 'numpy.full', 'np.full', (['(Nfixations_oth, n_splits)', 'np.nan'], {}), '((Nfixations_oth, n_splits), np.nan)\n', (2932, 2968), True, 'import numpy as np\n'), ((3304, 3329), 'numpy.full', 'np.full', (['n_splits', 'np.nan'], {}), '(n_splits, np.nan)\n', (3311, 3329), True, 'import numpy as np\n'), ((3878, 3890), 'numpy.mean', 'np.mean', (['auc'], {}), '(auc)\n', (3885, 3890), True, 'import numpy as np\n'), ((4132, 4149), 'numpy.where', 'np.where', (['(gt == 1)'], {}), '(gt == 1)\n', (4140, 4149), True, 'import numpy as np\n'), ((4244, 4257), 'numpy.mean', 'np.mean', (['temp'], {}), '(temp)\n', (4251, 4257), True, 'import numpy as np\n'), ((4548, 4571), 'logging.getLogger', 'logging.getLogger', (['name'], {}), '(name)\n', (4565, 4571), False, 'import logging\n'), ((4621, 4650), 'logging.FileHandler', 'logging.FileHandler', (['filename'], {}), '(filename)\n', (4640, 4650), False, 'import logging\n'), ((4667, 4728), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s - %(filename)s - %(message)s"""'], {}), "('%(asctime)s - %(filename)s - %(message)s')\n", (4684, 4728), False, 'import logging\n'), ((4795, 4818), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (4816, 4818), False, 'import logging\n'), ((575, 616), 'csv.writer', 'csv.writer', (['self.log_file'], {'delimiter': '"""\t"""'}), "(self.log_file, delimiter='\\t')\n", (585, 616), False, 'import csv\n'), ((1330, 1348), 'numpy.sum', 'np.sum', (['norm_s_map'], {}), '(norm_s_map)\n', (1336, 1348), True, 'import numpy as np\n'), ((1937, 1956), 'numpy.sum', 'np.sum', (['(S >= thresh)'], {}), '(S >= thresh)\n', (1943, 1956), True, 'import numpy as np\n'), ((2396, 2406), 'numpy.sum', 'np.sum', (['gt'], {}), '(gt)\n', (2402, 2406), True, 'import numpy as np\n'), ((2799, 2816), 'numpy.where', 'np.where', (['(Oth > 0)'], {}), '(Oth > 0)\n', (2807, 2816), True, 'import numpy as np\n'), ((4018, 4039), 'numpy.minimum', 'np.minimum', (['s_map', 'gt'], {}), '(s_map, gt)\n', (4028, 4039), True, 'import numpy as np\n'), ((4107, 4120), 'numpy.std', 'np.std', (['s_map'], {}), '(s_map)\n', (4113, 4120), True, 'import numpy as np\n'), ((4323, 4336), 'numpy.std', 'np.std', (['s_map'], {}), '(s_map)\n', (4329, 4336), True, 'import numpy as np\n'), ((4372, 4382), 'numpy.std', 'np.std', (['gt'], {}), '(gt)\n', (4378, 4382), True, 'import numpy as np\n'), ((1247, 1260), 'numpy.min', 'np.min', (['s_map'], {}), '(s_map)\n', (1253, 1260), True, 'import numpy as np\n'), ((1265, 1278), 'numpy.max', 'np.max', (['s_map'], {}), '(s_map)\n', (1271, 1278), True, 'import numpy as np\n'), ((1281, 1294), 'numpy.min', 'np.min', (['s_map'], {}), '(s_map)\n', (1287, 1294), True, 'import numpy as np\n'), ((3838, 3850), 'numpy.array', 'np.array', (['tp'], {}), '(tp)\n', (3846, 3850), True, 'import numpy as np\n'), ((3852, 3864), 'numpy.array', 'np.array', (['fp'], {}), '(fp)\n', (3860, 3864), True, 'import numpy as np\n'), ((4089, 4103), 'numpy.mean', 'np.mean', (['s_map'], {}), '(s_map)\n', (4096, 4103), True, 'import numpy as np\n'), ((4305, 4319), 'numpy.mean', 'np.mean', (['s_map'], {}), '(s_map)\n', (4312, 4319), True, 'import numpy as np\n'), ((4357, 4368), 'numpy.mean', 'np.mean', (['gt'], {}), '(gt)\n', (4364, 4368), True, 'import numpy as np\n'), ((3710, 3731), 'numpy.sum', 'np.sum', (['(Sth >= thresh)'], {}), '(Sth >= thresh)\n', (3716, 3731), True, 'import numpy as np\n'), ((3769, 3793), 'numpy.sum', 'np.sum', (['(curfix >= thresh)'], {}), '(curfix >= thresh)\n', (3775, 3793), True, 'import numpy as np\n'), ((3440, 3451), 'numpy.max', 'np.max', (['Sth'], {}), '(Sth)\n', (3446, 3451), True, 'import numpy as np\n'), ((3453, 3467), 'numpy.max', 'np.max', (['curfix'], {}), '(curfix)\n', (3459, 3467), True, 'import numpy as np\n')] |
#!/usr/bin/env python
#===============================================================================
# Copyright 2017 Geoscience Australia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#===============================================================================
'''
Created on 7/7/2019
@author: <NAME>
Spatial functions used for various bits an pieces
'''
from scipy.spatial.ckdtree import cKDTree
import numpy as np
from scipy.interpolate import griddata
from scipy.interpolate import interp1d
import math
from shapely.geometry import Point
def depth_to_thickness(depth):
"""
Function for calculating thickness from depth array
:param depth: an array of depths
:return:
a flat array of thicknesses with the last entry being a null
"""
# Create a new thickness array
thickness = np.nan*np.ones(shape=depth.shape,
dtype=np.float)
# Iterate through the depth array
if len(depth.shape) == 1:
thickness[0:-1] = depth[1:] - depth[:-1]
return thickness
elif len(depth.shape) == 2:
thickness[:, 0:-1] = depth[:, 1:] - depth[:, :-1]
return thickness
elif len(depth.shape) == 3:
thickness[:-1,:,:] = depth[1:,:, :] - depth[:-1,:, :]
return thickness
def thickness_to_depth(thickness):
"""
Function for calculating depth top from a thickness array
:param depth: an array of thicknesses
:return:
a flat array of depth
"""
# Create a new thickness array
depth = np.zeros(shape=thickness.shape,
dtype=np.float)
# Iterate through the depth array
depth[1:] = np.cumsum(thickness[:-1])
return depth
def nearest_neighbours(points, coords, points_required = 1,max_distance = 250.):
"""
An implementation of nearest neaighbour for spatial data that uses kdtrees
:param points: array of points to find the nearest neighbour for
:param coords: coordinates of points
:param points_required: number of points to return
:param max_distance: maximum search radius
:return:
"""
if len(np.array(points).shape) == 1:
points = np.array([points])
# Initialise tree instance
kdtree = cKDTree(data=coords)
# iterate throught the points and find the nearest neighbour
distances, indices = kdtree.query(points, k=points_required,
distance_upper_bound=max_distance)
# Mask out infitnite distances in indices to avoid confusion
mask = np.isfinite(distances)
if not np.all(mask):
distances[~mask] = np.nan
return distances, indices
def layer_centre_to_top(layer_centre_depth):
"""Function for getting layer top depth from layer centre depths. Assumes
that depth starts at zero.
Parameters
----------
layer_centre_depth : array
Description of parameter `layer_centre_depth`.
Returns
-------
array
Layer top depth
"""
layer_top_depth = np.zeros(shape = layer_centre_depth.shape,
dtype = layer_centre_depth.dtype)
layer_top_depth[:,1:] = layer_centre_depth[:,1:] - layer_centre_depth[:, :1]
return layer_top_depth
def line_length(line):
'''
Function to return length of line
@param line: iterable containing two two-ordinate iterables, e.g. 2 x 2 array or 2-tuple of 2-tuples
@return length: Distance between start & end points in native units
'''
return math.sqrt(math.pow(line[1][0] - line[0][0], 2.0) +
math.pow(line[1][1] - line[0][1], 2.0))
def coords2distance(coordinate_array):
'''
From geophys_utils, transect_utils
Function to calculate cumulative distance in metres from native (lon/lat) coordinates
@param coordinate_array: Array of shape (n, 2) or iterable containing coordinate pairs
@return distance_array: Array of shape (n) containing cumulative distances from first coord
'''
coord_count = coordinate_array.shape[0]
distance_array = np.zeros((coord_count,), coordinate_array.dtype)
cumulative_distance = 0.0
distance_array[0] = cumulative_distance
last_point = coordinate_array[0]
for coord_index in range(1, coord_count):
point = coordinate_array[coord_index]
distance = line_length((point, last_point))
cumulative_distance += distance
distance_array[coord_index] = cumulative_distance
last_point = point
return distance_array
def interpolate_1d_vars(vars_1D, var_dict, resampling_method='linear'):
"""
Interpolate the 1D variables onto regular distance axes
"""
# Iterate through the 1D variables, interpolate them onto the distances that were used for
# the 2D variable gridding and add it to the dictionary
for var in vars_1D:
varray = griddata(var_dict['distances'],
var_dict[var], var_dict['grid_distances'],
method=resampling_method)
yield varray
def interpolate_2d_vars(vars_2d, var_dict, xres, yres):
"""
Generator to interpolate 2d variables (i.e conductivity, uncertainty)
:param vars_2d:
:param var_dict:
:param xres:
:param yres:
:return:
"""
ndepth_cells = var_dict['ndepth_cells']
# Find the depth variable
layer_thicknesses = depth_to_thickness(var_dict['layer_top_depth'])
# Give the bottom layer the tickness of the second bottom layer
layer_thicknesses[:,-1] = layer_thicknesses[:,-2]
# Get the vertical limits
elevations = var_dict['elevation']
max_depth = np.max(var_dict['layer_top_depth'])
# elevation limits
vlimits = [np.min(elevations) - max_depth,
np.max(elevations) + 5]
# Get the horizontal limits
distances = var_dict['distances']
hlimits = [np.min(distances), np.max(distances)]
# Get the x and y dimension coordinates
xres = np.float(xres)
yres = np.float(yres)
grid_y, grid_x = np.mgrid[vlimits[1]:vlimits[0]:-yres,
hlimits[0]:hlimits[1]:xres]
grid_distances = grid_x[0]
grid_elevations = grid_y[:, 0]
assert len(grid_elevations) > ndepth_cells
# Add to the variable dictionary
var_dict['grid_elevations'] = grid_elevations
var_dict['grid_distances'] = grid_distances
# Interpolate the elevation
f = interp1d(distances, elevations)
max_elevation = f(grid_distances)
# Interpolate the layer thicknesses ont our grid
grid_thicknesses = np.nan*np.ones(shape = (grid_distances.shape[0],
grid_elevations.shape[0]),
dtype = layer_thicknesses.dtype)
# Iterate through each one of the layers and iterpolate
# Nb if all layers are equally thick then this block does nothing
for j in range(layer_thicknesses.shape[1]):
# Guard against nans
if not np.isnan(layer_thicknesses[:,j]).any():
# Grid in log10 space
layer_thickness = np.log10(layer_thicknesses[:, j])
f = interp1d(distances, layer_thickness)
grid_thicknesses[:,j] = f(grid_distances)
# Tranform back to linear space
grid_thicknesses = 10**grid_thicknesses
# Interpolate the variables
# Iterate through variables and interpolate onto new grid
for var in vars_2d:
interpolated_var = np.nan*np.ones(grid_thicknesses.shape,
dtype = var_dict[var].dtype)
# For conductivity we interpolate in log10 space
point_var = var_dict[var]
new_var = np.ones(shape = (len(grid_distances),
ndepth_cells))
if var == 'conductivity':
point_var = np.log10(point_var)
for j in range(point_var.shape[1]):
f = interp1d(distances, point_var[:,j])
new_var[:, j] = f(grid_distances)
if var.startswith('conductivity'):
new_var = 10**(new_var)
# Now we need to place the 2d variables on the new grid
for i in range(grid_distances.shape[0]):
dtop = 0.
for j in range(ndepth_cells - 1):
# Get the thickness
thick = grid_thicknesses[i,j]
# Find the elevation top and bottom
etop = max_elevation[i] - dtop
ebot = etop - thick
# Get the indices for this elevation range
j_ind = np.where((etop >= grid_elevations) & (ebot <= grid_elevations))
# Populate the section
interpolated_var[i, j_ind] = new_var[i,j]
# Update the depth top
dtop += thick
# Reverse the grid if it is west to east
#if var_dict['reverse_line']:
# interpolated_var = np.flipud(interpolated_var)
# We also want to transpose the grid so the up elevations are up
interpolated_var = interpolated_var.T
# Yield the generator and the dictionary with added variables
yield interpolated_var, var_dict
def interpolate_data(data_variables, var_dict, interpolated_utm,
resampling_method='linear'):
"""
:param data_variables: variables from netCDF4 dataset to interpolate
:param var_dict: dictionary with the arrays for each variable
:param interpolated_utm: utm corrdinates onto which to interpolate the line data
:param resampling_method:
:return:
"""
# Define coordinates
utm_coordinates = var_dict['utm_coordinates']
# Add distance array to dictionary
distances = coords2distance(utm_coordinates)
# Now we want to find the equivalent line distance of the data based on the
# gridded coordinates
interpolated_distances = griddata(utm_coordinates, distances, interpolated_utm,
method=resampling_method)
# Now extract the data variable, interpolate them and add them to the dictionary
for var in data_variables:
# Create an empty array for interpolation
arr = var_dict[var]
interp_arr = np.zeros(shape=(np.shape(interpolated_distances)[0], np.shape(arr)[1]),
dtype=var_dict[var].dtype)
# Interpolate each column separately
for j in range(interp_arr.shape[1]):
vals = np.log10(arr[:, j])
interp_arr[:, j] = 10**griddata(distances, vals, interpolated_distances,
method=resampling_method)
# Add to the dictionary
yield interp_arr
def xy_2_var(xarray, xy, var, max_distance = 100.):
"""
Function for finding a variable for gridded AEM sections
given an input easting and northing
@ param: xarray : for gridded line data
@ param: xy: numpy array with easting and northing
@ param: var: string with variable name
returns
float: distance along line
"""
utm_coords = np.column_stack((xarray.easting.values,
xarray.northing.values))
d, i = nearest_neighbours(xy, utm_coords, max_distance=max_distance)
if np.isnan(d).all():
return None
else:
return xarray[var][i]
def return_valid_points(points, coords, extent):
# Now get points that are within our survey area
mask = [Point(coords[id]).within(extent) for id in points]
u, indices = np.unique(np.array(points)[mask], return_index = True)
return u[indices]
def interp2scatter(surface, line, gridded_data, easting_col = 'X',
northing_col = 'Y', elevation_col = 'ELEVATION',
line_col = 'SURVEY_LINE'):
"""Function for taking .
Parameters
----------
surface : instance of modelling class
From modelling_utils.
line : int
line number.
gridded_data : dictionary
dictionary of section grids.
Returns
-------
grid_dists
Array of grid distances.
elevs
Array of elevations
fids
Array of fiducials
"""
mask = surface.interpreted_points[line_col] == line
utm_coords = np.column_stack((gridded_data[line]['easting'],
gridded_data[line]['northing']))
dist, inds = nearest_neighbours(surface.interpreted_points[mask][[easting_col,northing_col]].values,
utm_coords, max_distance=100.)
grid_dists = gridded_data[line]['grid_distances'][inds]
elevs = surface.interpreted_points[mask][elevation_col].values
fids = surface.interpreted_points[mask].index
return grid_dists, elevs, fids
def sort_variables(var_dict):
"""Function for sorting a dictionary of variables by fiducial then easting.
Assumes 'easting' and fiducial are in dictionary
Parameters
----------
var_dict : dicitonary
Dictionary of variables.
Returns
-------
dictionary
dictionary of sorted array
"""
# First sort on fiducial
sort_mask = np.argsort(var_dict['fiducial'])
# Now sort from east to west if need be
if var_dict['easting'][sort_mask][0] > var_dict['easting'][sort_mask][-1]:
sort_mask = sort_mask[::-1]
# now apply the mask to every variable
for item in var_dict:
var_dict[item] = var_dict[item][sort_mask]
return var_dict
def scale_distance_along_line(xarr1, xarr2):
"""
Function for scaling one xarray onto the -axis of another
Parameters
----------
xr xarray
dataset onto which to scale grid distances
xarr2 xarray
dataset to scale
Returns
-------
"""
# create the interpolator
coords = np.column_stack((xarr1['easting'].values,
xarr1['northing'].values))
# Now interpolate
new_coords = np.column_stack((xarr2['easting'].values,
xarr2['northing'].values))
# Our new coordinates are always sitting between two points
d, i = nearest_neighbours(new_coords, coords, points_required = 2,max_distance = 250.)
weights = 1/d
# Normalise the array so the rows sum to unit
weights /= np.sum(weights, axis=1)[:, None]
# get our grid distances
return np.sum(xarr1['grid_distances'].values[i] * weights, axis=1) | [
"scipy.spatial.ckdtree.cKDTree",
"numpy.sum",
"numpy.ones",
"numpy.isnan",
"numpy.argsort",
"numpy.shape",
"scipy.interpolate.interp1d",
"shapely.geometry.Point",
"math.pow",
"numpy.isfinite",
"numpy.cumsum",
"numpy.max",
"numpy.log10",
"scipy.interpolate.griddata",
"numpy.float",
"num... | [((2054, 2101), 'numpy.zeros', 'np.zeros', ([], {'shape': 'thickness.shape', 'dtype': 'np.float'}), '(shape=thickness.shape, dtype=np.float)\n', (2062, 2101), True, 'import numpy as np\n'), ((2187, 2212), 'numpy.cumsum', 'np.cumsum', (['thickness[:-1]'], {}), '(thickness[:-1])\n', (2196, 2212), True, 'import numpy as np\n'), ((2757, 2777), 'scipy.spatial.ckdtree.cKDTree', 'cKDTree', ([], {'data': 'coords'}), '(data=coords)\n', (2764, 2777), False, 'from scipy.spatial.ckdtree import cKDTree\n'), ((3059, 3081), 'numpy.isfinite', 'np.isfinite', (['distances'], {}), '(distances)\n', (3070, 3081), True, 'import numpy as np\n'), ((3537, 3609), 'numpy.zeros', 'np.zeros', ([], {'shape': 'layer_centre_depth.shape', 'dtype': 'layer_centre_depth.dtype'}), '(shape=layer_centre_depth.shape, dtype=layer_centre_depth.dtype)\n', (3545, 3609), True, 'import numpy as np\n'), ((4570, 4618), 'numpy.zeros', 'np.zeros', (['(coord_count,)', 'coordinate_array.dtype'], {}), '((coord_count,), coordinate_array.dtype)\n', (4578, 4618), True, 'import numpy as np\n'), ((6148, 6183), 'numpy.max', 'np.max', (["var_dict['layer_top_depth']"], {}), "(var_dict['layer_top_depth'])\n", (6154, 6183), True, 'import numpy as np\n'), ((6478, 6492), 'numpy.float', 'np.float', (['xres'], {}), '(xres)\n', (6486, 6492), True, 'import numpy as np\n'), ((6504, 6518), 'numpy.float', 'np.float', (['yres'], {}), '(yres)\n', (6512, 6518), True, 'import numpy as np\n'), ((6924, 6955), 'scipy.interpolate.interp1d', 'interp1d', (['distances', 'elevations'], {}), '(distances, elevations)\n', (6932, 6955), False, 'from scipy.interpolate import interp1d\n'), ((10375, 10460), 'scipy.interpolate.griddata', 'griddata', (['utm_coordinates', 'distances', 'interpolated_utm'], {'method': 'resampling_method'}), '(utm_coordinates, distances, interpolated_utm, method=resampling_method\n )\n', (10383, 10460), False, 'from scipy.interpolate import griddata\n'), ((11563, 11627), 'numpy.column_stack', 'np.column_stack', (['(xarray.easting.values, xarray.northing.values)'], {}), '((xarray.easting.values, xarray.northing.values))\n', (11578, 11627), True, 'import numpy as np\n'), ((12730, 12815), 'numpy.column_stack', 'np.column_stack', (["(gridded_data[line]['easting'], gridded_data[line]['northing'])"], {}), "((gridded_data[line]['easting'], gridded_data[line]['northing'])\n )\n", (12745, 12815), True, 'import numpy as np\n'), ((13630, 13662), 'numpy.argsort', 'np.argsort', (["var_dict['fiducial']"], {}), "(var_dict['fiducial'])\n", (13640, 13662), True, 'import numpy as np\n'), ((14290, 14358), 'numpy.column_stack', 'np.column_stack', (["(xarr1['easting'].values, xarr1['northing'].values)"], {}), "((xarr1['easting'].values, xarr1['northing'].values))\n", (14305, 14358), True, 'import numpy as np\n'), ((14428, 14496), 'numpy.column_stack', 'np.column_stack', (["(xarr2['easting'].values, xarr2['northing'].values)"], {}), "((xarr2['easting'].values, xarr2['northing'].values))\n", (14443, 14496), True, 'import numpy as np\n'), ((14846, 14905), 'numpy.sum', 'np.sum', (["(xarr1['grid_distances'].values[i] * weights)"], {'axis': '(1)'}), "(xarr1['grid_distances'].values[i] * weights, axis=1)\n", (14852, 14905), True, 'import numpy as np\n'), ((1359, 1401), 'numpy.ones', 'np.ones', ([], {'shape': 'depth.shape', 'dtype': 'np.float'}), '(shape=depth.shape, dtype=np.float)\n', (1366, 1401), True, 'import numpy as np\n'), ((2693, 2711), 'numpy.array', 'np.array', (['[points]'], {}), '([points])\n', (2701, 2711), True, 'import numpy as np\n'), ((3094, 3106), 'numpy.all', 'np.all', (['mask'], {}), '(mask)\n', (3100, 3106), True, 'import numpy as np\n'), ((5375, 5479), 'scipy.interpolate.griddata', 'griddata', (["var_dict['distances']", 'var_dict[var]', "var_dict['grid_distances']"], {'method': 'resampling_method'}), "(var_dict['distances'], var_dict[var], var_dict['grid_distances'],\n method=resampling_method)\n", (5383, 5479), False, 'from scipy.interpolate import griddata\n'), ((6382, 6399), 'numpy.min', 'np.min', (['distances'], {}), '(distances)\n', (6388, 6399), True, 'import numpy as np\n'), ((6401, 6418), 'numpy.max', 'np.max', (['distances'], {}), '(distances)\n', (6407, 6418), True, 'import numpy as np\n'), ((7080, 7182), 'numpy.ones', 'np.ones', ([], {'shape': '(grid_distances.shape[0], grid_elevations.shape[0])', 'dtype': 'layer_thicknesses.dtype'}), '(shape=(grid_distances.shape[0], grid_elevations.shape[0]), dtype=\n layer_thicknesses.dtype)\n', (7087, 7182), True, 'import numpy as np\n'), ((14772, 14795), 'numpy.sum', 'np.sum', (['weights'], {'axis': '(1)'}), '(weights, axis=1)\n', (14778, 14795), True, 'import numpy as np\n'), ((4029, 4067), 'math.pow', 'math.pow', (['(line[1][0] - line[0][0])', '(2.0)'], {}), '(line[1][0] - line[0][0], 2.0)\n', (4037, 4067), False, 'import math\n'), ((4091, 4129), 'math.pow', 'math.pow', (['(line[1][1] - line[0][1])', '(2.0)'], {}), '(line[1][1] - line[0][1], 2.0)\n', (4099, 4129), False, 'import math\n'), ((6223, 6241), 'numpy.min', 'np.min', (['elevations'], {}), '(elevations)\n', (6229, 6241), True, 'import numpy as np\n'), ((6270, 6288), 'numpy.max', 'np.max', (['elevations'], {}), '(elevations)\n', (6276, 6288), True, 'import numpy as np\n'), ((7594, 7627), 'numpy.log10', 'np.log10', (['layer_thicknesses[:, j]'], {}), '(layer_thicknesses[:, j])\n', (7602, 7627), True, 'import numpy as np\n'), ((7645, 7681), 'scipy.interpolate.interp1d', 'interp1d', (['distances', 'layer_thickness'], {}), '(distances, layer_thickness)\n', (7653, 7681), False, 'from scipy.interpolate import interp1d\n'), ((7972, 8030), 'numpy.ones', 'np.ones', (['grid_thicknesses.shape'], {'dtype': 'var_dict[var].dtype'}), '(grid_thicknesses.shape, dtype=var_dict[var].dtype)\n', (7979, 8030), True, 'import numpy as np\n'), ((8335, 8354), 'numpy.log10', 'np.log10', (['point_var'], {}), '(point_var)\n', (8343, 8354), True, 'import numpy as np\n'), ((8417, 8453), 'scipy.interpolate.interp1d', 'interp1d', (['distances', 'point_var[:, j]'], {}), '(distances, point_var[:, j])\n', (8425, 8453), False, 'from scipy.interpolate import interp1d\n'), ((10955, 10974), 'numpy.log10', 'np.log10', (['arr[:, j]'], {}), '(arr[:, j])\n', (10963, 10974), True, 'import numpy as np\n'), ((11743, 11754), 'numpy.isnan', 'np.isnan', (['d'], {}), '(d)\n', (11751, 11754), True, 'import numpy as np\n'), ((12016, 12032), 'numpy.array', 'np.array', (['points'], {}), '(points)\n', (12024, 12032), True, 'import numpy as np\n'), ((2646, 2662), 'numpy.array', 'np.array', (['points'], {}), '(points)\n', (2654, 2662), True, 'import numpy as np\n'), ((9062, 9125), 'numpy.where', 'np.where', (['((etop >= grid_elevations) & (ebot <= grid_elevations))'], {}), '((etop >= grid_elevations) & (ebot <= grid_elevations))\n', (9070, 9125), True, 'import numpy as np\n'), ((11011, 11086), 'scipy.interpolate.griddata', 'griddata', (['distances', 'vals', 'interpolated_distances'], {'method': 'resampling_method'}), '(distances, vals, interpolated_distances, method=resampling_method)\n', (11019, 11086), False, 'from scipy.interpolate import griddata\n'), ((11938, 11955), 'shapely.geometry.Point', 'Point', (['coords[id]'], {}), '(coords[id])\n', (11943, 11955), False, 'from shapely.geometry import Point\n'), ((7490, 7523), 'numpy.isnan', 'np.isnan', (['layer_thicknesses[:, j]'], {}), '(layer_thicknesses[:, j])\n', (7498, 7523), True, 'import numpy as np\n'), ((10730, 10762), 'numpy.shape', 'np.shape', (['interpolated_distances'], {}), '(interpolated_distances)\n', (10738, 10762), True, 'import numpy as np\n'), ((10767, 10780), 'numpy.shape', 'np.shape', (['arr'], {}), '(arr)\n', (10775, 10780), True, 'import numpy as np\n')] |
import numpy as np
import torch
import torch.nn as nn
import math
import torch.nn.functional as F
class NASMODE:
microsearch = 0
channelsearch = 1
vanilla = 2
class Arch_State:
def __init__(self, device, input_file = None) -> None:
self.device = device
self.layer_alphas = {}
self.alpha_gumbels = {}
self.channel_alphas = {}
self.channel_masks = {}
self.ind2ch = {}
self.out_range = {}
if input_file is not None:
self.load_arch_state(input_file)
def add_layer_alphas(self, block_name, no_cells):
alphas = torch.randn(no_cells)
self.layer_alphas[block_name] = alphas.to(self.device).requires_grad_(True)
def update_alpha_gumbel(self, tau):
for block_name in self.layer_alphas:
self.alpha_gumbels[block_name] = F.gumbel_softmax(self.layer_alphas[block_name], tau=tau.item(), hard=False, eps=1e-10, dim=-1)
for block_name in self.channel_alphas:
self.alpha_gumbels[block_name] = F.gumbel_softmax(self.channel_alphas[block_name], tau=tau.item(), hard=False, eps=1e-10, dim=-1)
def get_layer_alpha(self, name):
if name in self.layer_alphas:
return self.layer_alphas[name]
return None
def get_alpha_gumbel(self, name):
if name in self.alpha_gumbels:
return self.alpha_gumbels[name]
return None
def get_dmask_vars(self, name):
alpha_gumbel, masks, soft_eff_ch = None, None, None
if name in self.alpha_gumbels:
alpha_gumbel = alpha_gumbel = self.alpha_gumbels[name]
if name in self.ind2ch:
soft_eff_ch = torch.sum(alpha_gumbel * self.ind2ch[name])
if name in self.channel_masks:
masks = self.channel_masks[name]
return alpha_gumbel, soft_eff_ch, masks
def add_channel_alphas(self, block_name, out_range):
step = out_range["step"]
start = int(np.ceil(out_range["start"] / step) * step)
stop = int(np.floor(out_range["stop"] / step) * step)
no_steps = int((stop - start) / step + 1)
mean = np.random.randint(low=0,high=no_steps)
sd = 1
x = np.arange(no_steps)
var = sd**2
alphas = 1*np.exp(-np.power(x-mean,2)/(2*var)) / ((2*math.pi*var)**.5)
alphas = torch.Tensor(alphas)
ch_range = np.linspace(start=start, stop=stop, num=no_steps, dtype=int, endpoint=True)
channel_masks = []
ind2ch = []
for ch in ch_range:
mask = [0 for j in range(out_range["stop"])]
mask[0:ch] = [1 for j in range(ch)]
channel_masks.append(mask)
ind2ch.append(ch)
self.channel_alphas[block_name] = alphas.to(self.device).requires_grad_(True)
self.channel_masks[block_name] = torch.tensor(channel_masks, dtype=torch.float).to(self.device)
self.ind2ch[block_name] = torch.tensor(ind2ch).to(self.device)
self.out_range[block_name] = out_range
def load_arch_state(self, arch_state):
for block_name in arch_state:
if "layer_alphas" in arch_state[block_name]:
self.layer_alphas[block_name] = torch.tensor(arch_state[block_name]["layer_alphas"]).to(self.device).requires_grad_(True)
if "channel_alphas" in arch_state[block_name]:
self.channel_alphas[block_name] = torch.tensor(arch_state[block_name]["channel_alphas"]).to(self.device).requires_grad_(True)
self.out_range[block_name] = out_range = arch_state[block_name]["out_range"]
step = out_range["step"]
start = int(np.ceil(out_range["start"] / step) * step)
stop = int(np.floor(out_range["stop"] / step) * step)
no_steps = int((stop - start) / step + 1)
ch_range = np.linspace(start=start, stop=stop, num=no_steps, dtype=int, endpoint=True)
channel_masks = []
ind2ch = []
for ch in ch_range:
mask = [0 for j in range(stop)]
mask[0:ch] = [1 for j in range(ch)]
channel_masks.append(mask)
ind2ch.append(ch)
self.channel_masks[block_name] = torch.tensor(channel_masks, dtype=torch.float).to(self.device)
self.ind2ch[block_name] = torch.tensor(ind2ch).to(self.device)
def export_arch_state(self):
out = {}
for block_name in self.layer_alphas:
out[block_name] = {"layer_alphas": self.layer_alphas[block_name].tolist()}
for block_name in self.channel_alphas:
out[block_name] = {"channel_alphas": self.channel_alphas[block_name].tolist(),
"out_range": self.out_range[block_name]}
return out
class Dmask(nn.Module):
def __init__(self, layer_name, in_channels, out_channels, out_range, nasmode=NASMODE.vanilla, hw_model=None, device=None):
super().__init__()
self.layer_name = layer_name
self.device = device
self.out_range = out_range
self.nasmode = nasmode
self.in_channels = in_channels
if out_channels is None:
assert out_range is not None, 'both out_channels and out_range cannot be None'
self.out_channels = self.out_range["stop"]
else:
assert out_range is None, 'either out_channels or out_range can be None'
self.out_channels = out_channels
self.soft_eff_channels = None
self.alpha = None
self.hw_model = hw_model
self.bn = None
self.relu = None
def forward(self, x, in_channels, alpha_gumbel=None, soft_eff_channels=None, masks=None):
if self.nasmode == NASMODE.channelsearch:
self.soft_eff_channels = soft_eff_channels
out_channels = soft_eff_channels
masks = torch.sum(torch.multiply(alpha_gumbel, masks.transpose(0, 1)), dim=1).reshape([1, -1] + [1 for i in range(2, len(x.shape))])
x = torch.multiply(masks, self.cell(x))
else:
out_channels = self.out_channels
x = self.cell(x)
if self.bn is not None:
x = self.bn(x)
if self.relu is not None:
x = self.relu(x)
runtime, util = self.hw_model.runtime(self.cell, in_channels, out_channels, x.shape)
return x, out_channels, runtime, util
def get_arch_parameters(self):
return self.alpha
def set_arch_parameters(self, alpha):
self.alpha = alpha
def get_hard_eff_channels(self):
if self.nasmode == NASMODE.channelsearch:
step = self.out_range["step"]
start = int(np.ceil(self.out_range["start"] / step) * step)
stop = int(np.floor(self.out_range["stop"] / step) * step)
no_steps = int((stop - start) / step + 1)
ch_range = np.linspace(start=start, stop=stop, num=no_steps, dtype=int, endpoint=True)
return ch_range[torch.argmax(self.alpha)].item()
else:
return self.out_channels
def get_soft_eff_channels(self):
return self.soft_eff_channels if self.nasmode == NASMODE.channelsearch else self.out_channels
def convert_keras(self):
raise NotImplementedError
def print_layer(self):
s = self.layer_type
s += str(self.kernel_size) if hasattr(self, 'kernel_size') else ""
s += "\t" + str(self.in_channels) + "->" + str(self.get_hard_eff_channels())
return s
if __name__=="__main__":
import matplotlib.pyplot as plt
sd = 1
mean = 10
no_steps = 25
x = np.arange(no_steps)
var = sd**2
norm_pdf = np.exp(-np.power(x-mean,2)/(2*var)) / ((2*math.pi*var)**.5)
plt.plot(norm_pdf)
plt.savefig("results/initialization.png")
| [
"numpy.ceil",
"matplotlib.pyplot.plot",
"numpy.power",
"numpy.floor",
"torch.argmax",
"torch.randn",
"numpy.random.randint",
"numpy.arange",
"torch.Tensor",
"numpy.linspace",
"torch.tensor",
"torch.sum",
"matplotlib.pyplot.savefig"
] | [((7695, 7714), 'numpy.arange', 'np.arange', (['no_steps'], {}), '(no_steps)\n', (7704, 7714), True, 'import numpy as np\n'), ((7815, 7833), 'matplotlib.pyplot.plot', 'plt.plot', (['norm_pdf'], {}), '(norm_pdf)\n', (7823, 7833), True, 'import matplotlib.pyplot as plt\n'), ((7838, 7879), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""results/initialization.png"""'], {}), "('results/initialization.png')\n", (7849, 7879), True, 'import matplotlib.pyplot as plt\n'), ((615, 636), 'torch.randn', 'torch.randn', (['no_cells'], {}), '(no_cells)\n', (626, 636), False, 'import torch\n'), ((2149, 2188), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': 'no_steps'}), '(low=0, high=no_steps)\n', (2166, 2188), True, 'import numpy as np\n'), ((2216, 2235), 'numpy.arange', 'np.arange', (['no_steps'], {}), '(no_steps)\n', (2225, 2235), True, 'import numpy as np\n'), ((2352, 2372), 'torch.Tensor', 'torch.Tensor', (['alphas'], {}), '(alphas)\n', (2364, 2372), False, 'import torch\n'), ((2393, 2468), 'numpy.linspace', 'np.linspace', ([], {'start': 'start', 'stop': 'stop', 'num': 'no_steps', 'dtype': 'int', 'endpoint': '(True)'}), '(start=start, stop=stop, num=no_steps, dtype=int, endpoint=True)\n', (2404, 2468), True, 'import numpy as np\n'), ((1690, 1733), 'torch.sum', 'torch.sum', (['(alpha_gumbel * self.ind2ch[name])'], {}), '(alpha_gumbel * self.ind2ch[name])\n', (1699, 1733), False, 'import torch\n'), ((6951, 7026), 'numpy.linspace', 'np.linspace', ([], {'start': 'start', 'stop': 'stop', 'num': 'no_steps', 'dtype': 'int', 'endpoint': '(True)'}), '(start=start, stop=stop, num=no_steps, dtype=int, endpoint=True)\n', (6962, 7026), True, 'import numpy as np\n'), ((1978, 2012), 'numpy.ceil', 'np.ceil', (["(out_range['start'] / step)"], {}), "(out_range['start'] / step)\n", (1985, 2012), True, 'import numpy as np\n'), ((2040, 2074), 'numpy.floor', 'np.floor', (["(out_range['stop'] / step)"], {}), "(out_range['stop'] / step)\n", (2048, 2074), True, 'import numpy as np\n'), ((2847, 2893), 'torch.tensor', 'torch.tensor', (['channel_masks'], {'dtype': 'torch.float'}), '(channel_masks, dtype=torch.float)\n', (2859, 2893), False, 'import torch\n'), ((2944, 2964), 'torch.tensor', 'torch.tensor', (['ind2ch'], {}), '(ind2ch)\n', (2956, 2964), False, 'import torch\n'), ((3868, 3943), 'numpy.linspace', 'np.linspace', ([], {'start': 'start', 'stop': 'stop', 'num': 'no_steps', 'dtype': 'int', 'endpoint': '(True)'}), '(start=start, stop=stop, num=no_steps, dtype=int, endpoint=True)\n', (3879, 3943), True, 'import numpy as np\n'), ((6754, 6793), 'numpy.ceil', 'np.ceil', (["(self.out_range['start'] / step)"], {}), "(self.out_range['start'] / step)\n", (6761, 6793), True, 'import numpy as np\n'), ((6825, 6864), 'numpy.floor', 'np.floor', (["(self.out_range['stop'] / step)"], {}), "(self.out_range['stop'] / step)\n", (6833, 6864), True, 'import numpy as np\n'), ((7754, 7775), 'numpy.power', 'np.power', (['(x - mean)', '(2)'], {}), '(x - mean, 2)\n', (7762, 7775), True, 'import numpy as np\n'), ((3669, 3703), 'numpy.ceil', 'np.ceil', (["(out_range['start'] / step)"], {}), "(out_range['start'] / step)\n", (3676, 3703), True, 'import numpy as np\n'), ((3739, 3773), 'numpy.floor', 'np.floor', (["(out_range['stop'] / step)"], {}), "(out_range['stop'] / step)\n", (3747, 3773), True, 'import numpy as np\n'), ((4287, 4333), 'torch.tensor', 'torch.tensor', (['channel_masks'], {'dtype': 'torch.float'}), '(channel_masks, dtype=torch.float)\n', (4299, 4333), False, 'import torch\n'), ((4392, 4412), 'torch.tensor', 'torch.tensor', (['ind2ch'], {}), '(ind2ch)\n', (4404, 4412), False, 'import torch\n'), ((7055, 7079), 'torch.argmax', 'torch.argmax', (['self.alpha'], {}), '(self.alpha)\n', (7067, 7079), False, 'import torch\n'), ((2283, 2304), 'numpy.power', 'np.power', (['(x - mean)', '(2)'], {}), '(x - mean, 2)\n', (2291, 2304), True, 'import numpy as np\n'), ((3215, 3267), 'torch.tensor', 'torch.tensor', (["arch_state[block_name]['layer_alphas']"], {}), "(arch_state[block_name]['layer_alphas'])\n", (3227, 3267), False, 'import torch\n'), ((3414, 3468), 'torch.tensor', 'torch.tensor', (["arch_state[block_name]['channel_alphas']"], {}), "(arch_state[block_name]['channel_alphas'])\n", (3426, 3468), False, 'import torch\n')] |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : LongVideoNvN.py
# Author : <NAME>
# Email : <EMAIL>
# Date : 08/02/2021
#
# This file is part of TOQ-Nets-PyTorch.
# Distributed under terms of the MIT license.
import os
import random
from copy import deepcopy
import numpy as np
import torch
from toqnets.config_update import ConfigUpdate, update_config
from toqnets.datasets.utils import sample_from_list
def get_folder(config):
name = config['folder'] % (config['n_players'], config['n_players'])
return os.path.join('data', name)
def get_raw_action(config, action):
folder = get_folder(config)
file_list = os.listdir(folder)
file_list = [x for x in file_list if x.startswith(action) and x.endswith('.npz')]
np_datas = []
for name in file_list:
np_datas.append(np.load(os.path.join(folder, name))['data'])
np_datas = np.concatenate(np_datas, axis=0)
print(action, np_datas.shape[0])
return np_datas
def move_player_to_first(trajectory, playerid, n_left_players, n_right_players):
playerid = int(playerid)
left_indices = [i for i in range(1, n_left_players + 1)]
right_indices = [i for i in range(n_left_players + 1, n_left_players + n_right_players + 1)]
if playerid > n_left_players:
k = playerid - n_left_players - 1
right_indices = right_indices[k:k + 1] + right_indices[:k] + right_indices[k + 1:]
indices = [0] + right_indices + left_indices
else:
k = playerid - 1
left_indices = left_indices[k:k + 1] + left_indices[:k] + left_indices[k + 1:]
indices = [0] + left_indices + right_indices
return trajectory[:, indices]
class LongVideoNvN:
default_config = {
'name': 'LongVideoNvN',
'length': 61,
'n_players': 6,
'temporal': 'exact',
'state_dim': 3,
'folder': 'LongVideo%dv%d',
'actions': [
'trap',
'short_pass',
'long_pass',
'high_pass',
'interfere',
'trip',
'shot',
'deflect',
'sliding'
],
'n_train': None,
'finetune_n_train': 5,
'finetune_scale': 2.0,
'finetune_subsample': 2,
'exact_length': 25,
}
def set_equal_sample(self, mode, val):
self.equal_sample[mode] = val
def set_only_regular(self, mode, val):
pass
def set_gfootball_finetune(self, val):
self.gfootball_finetune = val
@classmethod
def complete_config(cls, config_update, default_config=None):
config = deepcopy(cls.default_config) if default_config is None else default_config
update_config(config, config_update)
config['n_agents'] = config['n_players'] * 2 + 1
return config
def _get_actions_action2index(self):
actions = self.config['actions']
action2index = {a: i for i, a in enumerate(actions)}
return actions, action2index
def __init__(self, config):
"""
:param config: config for dataset, in addition to the default self.config
"""
self.config = config
self.actions, self.action2index = self._get_actions_action2index()
self.library, self.indices = self.fetch()
n_players = self.config['n_players']
n_agents = self.config['n_agents']
self.types = torch.zeros(n_agents, 3)
for k in range(n_agents):
self.types[k, 0 if k == 0 else (1 if k <= n_players else 2)] = 1
self.equal_sample = {'train': False, 'val': False, 'test': False}
self.gfootball_finetune = False
def fetch(self):
n_agents = self.config['n_agents']
length = self.config['length']
state_dim = self.config['state_dim']
library = {'train': [], 'val': [], 'test': []}
indices = {'train': [], 'val': [], 'test': []}
for aid, action in enumerate(self.config['actions']):
raw_data = get_raw_action(self.config, action)
rng = np.random.default_rng(2333)
rng.shuffle(raw_data)
print("Loading action %s" % action)
num = raw_data.shape[0]
if self.config['n_train'] is None:
end_train = num * 8 // 13
end_val = num * 10 // 13
n_rep = 1
n_rep_val = 1
elif self.config['n_train'] >= 1:
end_train = self.config['n_train']
end_val = end_train * 2
n_rep = max(1, int(num * 8 / 13 / end_train))
n_rep_val = max(1, 1024 // end_train)
assert end_val < num
else:
assert 0 < self.config['n_train'] < 1
end_train = int(self.config['n_train'] * num)
end_val = end_train * 2
n_rep = 1
n_rep_val = 1
assert end_train < end_val < num
block_data = {
'train': raw_data[:end_train],
'val': raw_data[end_train: end_val],
'test': raw_data[end_val:]
}
block_data['train'] = np.repeat(block_data['train'], n_rep, axis=0)
block_data['val'] = np.repeat(block_data['val'], n_rep_val, axis=0)
for mode in ['train', 'val', 'test']:
raw = block_data[mode]
tra = np.zeros((raw.shape[0], length, n_agents, state_dim))
pid = np.zeros(raw.shape[0]).astype(np.int)
act = np.zeros(raw.shape[0]).astype(np.int)
for k in range(n_agents):
if k == 0:
tra[:, :, k, :] = raw[:, :, 0:3]
else:
tra[:, :, k, :2] = raw[:, :, (k - 1) * 13 + 3:(k - 1) * 13 + 5]
if k > 0:
pid_k = raw[:, length // 2, -n_agents + k].astype(np.int) * k
# print('raw[:, length, -n_agents + k] = ', raw[:, (length + 1) // 2, -n_agents + k])
# print("pid_k", pid_k)
pid = np.maximum(pid, pid_k)
# pid += pid_k
tra[:, :, :, :2] *= 60
tra[:, :, :, 2:] *= 0.3
act += aid
n_data = raw.shape[0]
library[mode].append((torch.Tensor(tra), torch.LongTensor(pid)))
index = np.zeros((n_data, 2), dtype=np.int)
index[:, 0] = aid
index[:, 1] = np.arange(n_data)
indices[mode].append(index)
print(action, mode, library[mode][-1][0].size(0))
for key in indices:
indices[key] = np.concatenate(indices[key], axis=0)
np.random.seed(233)
np.random.shuffle(indices[key])
return library, indices
def get_action_list(self):
return tuple(self.actions)
def get_item_aid_sid(self, aid, sid, mode, library=None):
if library is None:
library = self.library
trajectories = library[mode][aid][0][sid].clone()
playerid = library[mode][aid][1][sid].clone()
if self.gfootball_finetune:
subsample = self.config['finetune_subsample']
scale = self.config['finetune_scale']
if scale != 1.0:
trajectories *= scale
if subsample != 1:
offset = (trajectories.size(0) % subsample) // 2
trajectories = trajectories[offset:trajectories.size(0):subsample]
length = trajectories.size(0)
if self.config['temporal'] == 'all':
start_time = random.randint(12, 26)
duration = 25
elif self.config['temporal'] == 'left':
start_time = random.randint(12, 19)
duration = 25
elif self.config['temporal'] == 'right':
start_time = random.randint(19, 26)
duration = 25
elif self.config['temporal'] == 'exact':
duration = self.config['exact_length']
start_time = length // 2 - (duration - 1) // 2
else:
raise ValueError()
trajectories = trajectories[start_time:start_time + duration]
middle = self.config['length'] // 2 - start_time
return {
'trajectories': trajectories,
'playerid': playerid,
'actions': aid,
'types': self.types,
'sample_ids': sid,
'middle': middle,
}
def getitem_withmode(self, item, mode):
if self.equal_sample[mode]:
aid = sample_from_list([i for i in range(len(self.actions))])
sid = random.randint(0, self.library[mode][aid][0].shape[0] - 1)
if self.gfootball_finetune:
sid = random.randint(0, self.config['finetune_n_train'])
weight = 1.0
else:
aid = self.indices[mode][item][0]
sid = self.indices[mode][item][1]
total = self.len_withmode(mode)
n_actions = len(self.actions)
fre = self.library[mode][aid][0].shape[0]
weight = total / n_actions / fre
dat = self.get_item_aid_sid(aid, sid, mode)
dat['weight'] = weight
return dat
def len_withmode(self, mode):
return self.indices[mode].shape[0]
class LongVideoNvN_Wrapper_FewShot_Softmax:
default_config = {
'name': 'LongVideoNvN_Wrapper_FewShot_Softmax',
'equal_sample': {'train': False, 'val': False, 'test': False},
'only_regular': {'train': False, 'val': False, 'test': False},
'new_actions': [
'trap', 'sliding'
],
'n_few_shot': 50,
'exact_length': None,
}
@classmethod
def complete_config(cls, config_update, default_config=None):
config = deepcopy(cls.default_config) if default_config is None else default_config
update_config(config, config_update)
return config
def complete_sub_config(self, config):
sub_args = {}
if config['exact_length'] is not None:
sub_args['exact_length'] = config['exact_length']
sub_config = deepcopy(LongVideoNvN.complete_config(ConfigUpdate(sub_args)))
return sub_config
def set_equal_sample(self, mode, val):
self.config['equal_sample'][mode] = val
def set_only_regular(self, mode, val):
self.config['only_regular'][mode] = val
def fetch_from_sub(self, library):
indices = {'train': [], 'val': [], 'test': []}
n_few_shot = self.config['n_few_shot']
new_library = {'train': [], 'val': [], 'test': []}
for aid, action in enumerate(self.get_action_list()):
if action in self.config['new_actions']:
tra = torch.cat((library['train'][aid][0], library['val'][aid][0], library['test'][aid][0]),
dim=0)
pid = torch.cat((library['train'][aid][1], library['val'][aid][1], library['test'][aid][1]),
dim=0)
new_library['train'].append((tra[:n_few_shot], pid[:n_few_shot]))
new_library['val'].append((tra[n_few_shot:n_few_shot * 2], pid[n_few_shot:n_few_shot * 2]))
new_library['test'].append((tra[n_few_shot * 2:], pid[n_few_shot * 2:]))
else:
for split in ('train', 'val', 'test'):
new_library[split].append(library[split][aid])
for split in ('train', 'val', 'test'):
n_data = new_library[split][aid][0].shape[0]
index = np.zeros((n_data, 2), dtype=np.int)
index[:, 0] = aid
index[:, 1] = np.arange(n_data)
indices[split].append(index)
print('%s %s %d' % (action, split, n_data))
for split in ('train', 'val', 'test'):
indices[split] = np.concatenate(indices[split], axis=0)
return new_library, indices
def __init__(self, config):
self.config = config
sub_config = self.complete_sub_config(config)
self.dataset = LongVideoNvN(sub_config)
self.library, self.indices = self.fetch_from_sub(self.dataset.library)
self.reg_indices = {}
actions = self.dataset.config['actions']
self.reg_action_onehot = [False if actions[i] in self.config['new_actions'] else True
for i in range(len(actions))]
self.reg_action_indices = [i for i in range(len(actions)) if self.reg_action_onehot[i]]
self.all_action_indices = [i for i in range(len(actions))]
for mode in ['train', 'val', 'test']:
self.reg_indices[mode] = np.zeros(self.indices[mode].shape, dtype=np.int)
j = 0
for i in range(self.indices[mode].shape[0]):
if self.reg_action_onehot[self.indices[mode][i][0]]:
self.reg_indices[mode][j] = self.indices[mode][i]
j += 1
self.reg_indices[mode] = self.reg_indices[mode][:j]
def get_action_list(self):
return self.dataset.get_action_list()
def get_new_actions(self):
return [x for x in deepcopy(self.config['new_actions'])]
def getitem_withmode(self, item, mode):
aid, sid = None, None
if self.config['equal_sample'][mode]:
if self.config['only_regular'][mode]:
aid = sample_from_list(self.reg_action_indices)
else:
aid = sample_from_list(self.all_action_indices)
sid = random.randint(0, self.library[mode][aid][0].shape[0] - 1)
else:
if self.config['only_regular'][mode]:
aid = self.reg_indices[mode][item][0]
sid = self.reg_indices[mode][item][1]
else:
aid = self.indices[mode][item][0]
sid = self.indices[mode][item][1]
return self.dataset.get_item_aid_sid(aid, sid, mode, self.library)
def len_withmode(self, mode):
if self.config['only_regular'][mode]:
return self.reg_indices[mode].shape[0]
return self.indices[mode].shape[0]
if __name__ == '__main__':
config = LongVideoNvN.complete_config(ConfigUpdate({
'n_players': 8,
'n_train': 0.1,
}))
dataset = LongVideoNvN(config)
| [
"numpy.random.seed",
"numpy.maximum",
"torch.cat",
"numpy.random.default_rng",
"numpy.arange",
"os.path.join",
"toqnets.config_update.update_config",
"random.randint",
"torch.Tensor",
"torch.zeros",
"numpy.random.shuffle",
"numpy.repeat",
"copy.deepcopy",
"toqnets.config_update.ConfigUpdat... | [((532, 558), 'os.path.join', 'os.path.join', (['"""data"""', 'name'], {}), "('data', name)\n", (544, 558), False, 'import os\n'), ((645, 663), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (655, 663), False, 'import os\n'), ((879, 911), 'numpy.concatenate', 'np.concatenate', (['np_datas'], {'axis': '(0)'}), '(np_datas, axis=0)\n', (893, 911), True, 'import numpy as np\n'), ((2677, 2713), 'toqnets.config_update.update_config', 'update_config', (['config', 'config_update'], {}), '(config, config_update)\n', (2690, 2713), False, 'from toqnets.config_update import ConfigUpdate, update_config\n'), ((3376, 3400), 'torch.zeros', 'torch.zeros', (['n_agents', '(3)'], {}), '(n_agents, 3)\n', (3387, 3400), False, 'import torch\n'), ((9922, 9958), 'toqnets.config_update.update_config', 'update_config', (['config', 'config_update'], {}), '(config, config_update)\n', (9935, 9958), False, 'from toqnets.config_update import ConfigUpdate, update_config\n'), ((14254, 14300), 'toqnets.config_update.ConfigUpdate', 'ConfigUpdate', (["{'n_players': 8, 'n_train': 0.1}"], {}), "({'n_players': 8, 'n_train': 0.1})\n", (14266, 14300), False, 'from toqnets.config_update import ConfigUpdate, update_config\n'), ((2594, 2622), 'copy.deepcopy', 'deepcopy', (['cls.default_config'], {}), '(cls.default_config)\n', (2602, 2622), False, 'from copy import deepcopy\n'), ((4026, 4053), 'numpy.random.default_rng', 'np.random.default_rng', (['(2333)'], {}), '(2333)\n', (4047, 4053), True, 'import numpy as np\n'), ((5146, 5191), 'numpy.repeat', 'np.repeat', (["block_data['train']", 'n_rep'], {'axis': '(0)'}), "(block_data['train'], n_rep, axis=0)\n", (5155, 5191), True, 'import numpy as np\n'), ((5224, 5271), 'numpy.repeat', 'np.repeat', (["block_data['val']", 'n_rep_val'], {'axis': '(0)'}), "(block_data['val'], n_rep_val, axis=0)\n", (5233, 5271), True, 'import numpy as np\n'), ((6702, 6738), 'numpy.concatenate', 'np.concatenate', (['indices[key]'], {'axis': '(0)'}), '(indices[key], axis=0)\n', (6716, 6738), True, 'import numpy as np\n'), ((6751, 6770), 'numpy.random.seed', 'np.random.seed', (['(233)'], {}), '(233)\n', (6765, 6770), True, 'import numpy as np\n'), ((6783, 6814), 'numpy.random.shuffle', 'np.random.shuffle', (['indices[key]'], {}), '(indices[key])\n', (6800, 6814), True, 'import numpy as np\n'), ((7651, 7673), 'random.randint', 'random.randint', (['(12)', '(26)'], {}), '(12, 26)\n', (7665, 7673), False, 'import random\n'), ((8674, 8732), 'random.randint', 'random.randint', (['(0)', '(self.library[mode][aid][0].shape[0] - 1)'], {}), '(0, self.library[mode][aid][0].shape[0] - 1)\n', (8688, 8732), False, 'import random\n'), ((9839, 9867), 'copy.deepcopy', 'deepcopy', (['cls.default_config'], {}), '(cls.default_config)\n', (9847, 9867), False, 'from copy import deepcopy\n'), ((11916, 11954), 'numpy.concatenate', 'np.concatenate', (['indices[split]'], {'axis': '(0)'}), '(indices[split], axis=0)\n', (11930, 11954), True, 'import numpy as np\n'), ((12719, 12767), 'numpy.zeros', 'np.zeros', (['self.indices[mode].shape'], {'dtype': 'np.int'}), '(self.indices[mode].shape, dtype=np.int)\n', (12727, 12767), True, 'import numpy as np\n'), ((13584, 13642), 'random.randint', 'random.randint', (['(0)', '(self.library[mode][aid][0].shape[0] - 1)'], {}), '(0, self.library[mode][aid][0].shape[0] - 1)\n', (13598, 13642), False, 'import random\n'), ((5384, 5437), 'numpy.zeros', 'np.zeros', (['(raw.shape[0], length, n_agents, state_dim)'], {}), '((raw.shape[0], length, n_agents, state_dim))\n', (5392, 5437), True, 'import numpy as np\n'), ((6418, 6453), 'numpy.zeros', 'np.zeros', (['(n_data, 2)'], {'dtype': 'np.int'}), '((n_data, 2), dtype=np.int)\n', (6426, 6453), True, 'import numpy as np\n'), ((6518, 6535), 'numpy.arange', 'np.arange', (['n_data'], {}), '(n_data)\n', (6527, 6535), True, 'import numpy as np\n'), ((7773, 7795), 'random.randint', 'random.randint', (['(12)', '(19)'], {}), '(12, 19)\n', (7787, 7795), False, 'import random\n'), ((8795, 8845), 'random.randint', 'random.randint', (['(0)', "self.config['finetune_n_train']"], {}), "(0, self.config['finetune_n_train'])\n", (8809, 8845), False, 'import random\n'), ((10215, 10237), 'toqnets.config_update.ConfigUpdate', 'ConfigUpdate', (['sub_args'], {}), '(sub_args)\n', (10227, 10237), False, 'from toqnets.config_update import ConfigUpdate, update_config\n'), ((10788, 10886), 'torch.cat', 'torch.cat', (["(library['train'][aid][0], library['val'][aid][0], library['test'][aid][0])"], {'dim': '(0)'}), "((library['train'][aid][0], library['val'][aid][0], library['test'\n ][aid][0]), dim=0)\n", (10797, 10886), False, 'import torch\n'), ((10936, 11034), 'torch.cat', 'torch.cat', (["(library['train'][aid][1], library['val'][aid][1], library['test'][aid][1])"], {'dim': '(0)'}), "((library['train'][aid][1], library['val'][aid][1], library['test'\n ][aid][1]), dim=0)\n", (10945, 11034), False, 'import torch\n'), ((11617, 11652), 'numpy.zeros', 'np.zeros', (['(n_data, 2)'], {'dtype': 'np.int'}), '((n_data, 2), dtype=np.int)\n', (11625, 11652), True, 'import numpy as np\n'), ((11717, 11734), 'numpy.arange', 'np.arange', (['n_data'], {}), '(n_data)\n', (11726, 11734), True, 'import numpy as np\n'), ((13211, 13247), 'copy.deepcopy', 'deepcopy', (["self.config['new_actions']"], {}), "(self.config['new_actions'])\n", (13219, 13247), False, 'from copy import deepcopy\n'), ((13442, 13483), 'toqnets.datasets.utils.sample_from_list', 'sample_from_list', (['self.reg_action_indices'], {}), '(self.reg_action_indices)\n', (13458, 13483), False, 'from toqnets.datasets.utils import sample_from_list\n'), ((13524, 13565), 'toqnets.datasets.utils.sample_from_list', 'sample_from_list', (['self.all_action_indices'], {}), '(self.all_action_indices)\n', (13540, 13565), False, 'from toqnets.datasets.utils import sample_from_list\n'), ((827, 853), 'os.path.join', 'os.path.join', (['folder', 'name'], {}), '(folder, name)\n', (839, 853), False, 'import os\n'), ((7896, 7918), 'random.randint', 'random.randint', (['(19)', '(26)'], {}), '(19, 26)\n', (7910, 7918), False, 'import random\n'), ((5460, 5482), 'numpy.zeros', 'np.zeros', (['raw.shape[0]'], {}), '(raw.shape[0])\n', (5468, 5482), True, 'import numpy as np\n'), ((5520, 5542), 'numpy.zeros', 'np.zeros', (['raw.shape[0]'], {}), '(raw.shape[0])\n', (5528, 5542), True, 'import numpy as np\n'), ((6107, 6129), 'numpy.maximum', 'np.maximum', (['pid', 'pid_k'], {}), '(pid, pid_k)\n', (6117, 6129), True, 'import numpy as np\n'), ((6351, 6368), 'torch.Tensor', 'torch.Tensor', (['tra'], {}), '(tra)\n', (6363, 6368), False, 'import torch\n'), ((6370, 6391), 'torch.LongTensor', 'torch.LongTensor', (['pid'], {}), '(pid)\n', (6386, 6391), False, 'import torch\n')] |
# -*- coding: utf-8 -*-
"""Tests for Coastal Blue Carbon Functions."""
import logging
import os
import pprint
import shutil
import tempfile
import unittest
import glob
import numpy
from osgeo import gdal, osr
import pygeoprocessing
from natcap.invest import utils
from natcap.invest.coastal_blue_carbon import coastal_blue_carbon
REGRESSION_DATA = os.path.join(
os.path.dirname(__file__), '..', 'data', 'invest-test-data',
'coastal_blue_carbon')
LOGGER = logging.getLogger(__name__)
class TestPreprocessor(unittest.TestCase):
"""Test Coastal Blue Carbon preprocessor functions."""
def setUp(self):
"""Create a temp directory for the workspace."""
self.workspace_dir = tempfile.mkdtemp()
def tearDown(self):
"""Remove workspace."""
shutil.rmtree(self.workspace_dir)
def test_sample_data(self):
"""CBC Preprocessor: Test on sample data."""
from natcap.invest.coastal_blue_carbon import preprocessor
snapshot_csv_path = os.path.join(
REGRESSION_DATA, 'inputs', 'snapshots.csv')
args = {
'workspace_dir': os.path.join(self.workspace_dir, 'workspace'),
'results_suffix': '150225',
'lulc_lookup_table_path': os.path.join(
REGRESSION_DATA, 'inputs', 'lulc_lookup.csv'),
'landcover_snapshot_csv': snapshot_csv_path,
}
preprocessor.execute(args)
# walk through all files in the workspace and assert that outputs have
# the file suffix.
non_suffixed_files = []
outputs_dir = os.path.join(
args['workspace_dir'], 'outputs_preprocessor')
for root_dir, dirnames, filenames in os.walk(outputs_dir):
for filename in filenames:
if not filename.lower().endswith('.txt'): # ignore logfile
basename, extension = os.path.splitext(filename)
if not basename.endswith('_150225'):
path_rel_to_workspace = os.path.relpath(
os.path.join(root_dir, filename),
args['workspace_dir'])
non_suffixed_files.append(path_rel_to_workspace)
if non_suffixed_files:
self.fail('%s files are missing suffixes: %s' %
(len(non_suffixed_files),
pprint.pformat(non_suffixed_files)))
expected_landcover_codes = set(range(0, 24))
found_landcover_codes = set(utils.build_lookup_from_csv(
os.path.join(outputs_dir,
'carbon_biophysical_table_template_150225.csv'),
'code').keys())
self.assertEqual(expected_landcover_codes, found_landcover_codes)
def test_transition_table(self):
"""CBC Preprocessor: Test creation of transition table."""
from natcap.invest.coastal_blue_carbon import preprocessor
srs = osr.SpatialReference()
srs.ImportFromEPSG(3157)
projection_wkt = srs.ExportToWkt()
origin = (443723.127327877911739, 4956546.905980412848294)
matrix_a = numpy.array([
[0, 1],
[0, 1],
[0, 1]], dtype=numpy.int16)
filename_a = os.path.join(self.workspace_dir, 'raster_a.tif')
pygeoprocessing.numpy_array_to_raster(
matrix_a, -1, (100, -100), origin, projection_wkt, filename_a)
matrix_b = numpy.array([
[0, 1],
[1, 0],
[-1, -1]], dtype=numpy.int16)
filename_b = os.path.join(self.workspace_dir, 'raster_b.tif')
pygeoprocessing.numpy_array_to_raster(
matrix_b, -1, (100, -100), origin, projection_wkt, filename_b)
landcover_table_path = os.path.join(self.workspace_dir,
'lulc_table.csv')
with open(landcover_table_path, 'w') as lulc_csv:
lulc_csv.write('code,lulc-class,is_coastal_blue_carbon_habitat\n')
lulc_csv.write('0,mangrove,True\n')
lulc_csv.write('1,parking lot,False\n')
landcover_table = utils.build_lookup_from_csv(
landcover_table_path, 'code')
target_table_path = os.path.join(self.workspace_dir,
'transition_table.csv')
# Remove landcover code 1 from the table; expect error.
del landcover_table[1]
with self.assertRaises(ValueError) as context:
preprocessor._create_transition_table(
landcover_table, [filename_a, filename_b], target_table_path)
self.assertIn('missing a row with the landuse code 1',
str(context.exception))
# Re-load the landcover table
landcover_table = utils.build_lookup_from_csv(
landcover_table_path, 'code')
preprocessor._create_transition_table(
landcover_table, [filename_a, filename_b], target_table_path)
with open(target_table_path) as transition_table:
self.assertEqual(
transition_table.readline(),
'lulc-class,mangrove,parking lot\n')
self.assertEqual(
transition_table.readline(),
'mangrove,accum,disturb\n')
self.assertEqual(
transition_table.readline(),
'parking lot,accum,NCC\n')
# After the above lines is a blank line, then the legend.
# Deliberately not testing the legend.
self.assertEqual(transition_table.readline(), '\n')
class TestCBC2(unittest.TestCase):
"""Test Coastal Blue Carbon main model functions."""
def setUp(self):
"""Create a temp directory for the workspace."""
self.workspace_dir = tempfile.mkdtemp()
def tearDown(self):
"""Remove workspace after each test function."""
shutil.rmtree(self.workspace_dir)
def test_extract_snapshots(self):
"""CBC: Extract snapshots from a snapshot CSV."""
csv_path = os.path.join(self.workspace_dir, 'snapshots.csv')
transition_years = (2000, 2010, 2020)
transition_rasters = []
with open(csv_path, 'w') as transitions_csv:
# Check that we can interpret varying case.
transitions_csv.write('snapshot_YEAR,raster_PATH\n')
for transition_year in transition_years:
# Write absolute paths.
transition_file_path = os.path.join(
self.workspace_dir, f'{transition_year}.tif)')
transition_rasters.append(transition_file_path)
transitions_csv.write(
f'{transition_year},{transition_file_path}\n')
# Make one path relative to the workspace, where the transitions
# CSV also lives.
# The expected raster path is absolute.
transitions_csv.write('2030,some_path.tif\n')
transition_years += (2030,)
transition_rasters.append(os.path.join(self.workspace_dir,
'some_path.tif'))
extracted_transitions = (
coastal_blue_carbon._extract_snapshots_from_table(csv_path))
self.assertEqual(
extracted_transitions,
dict(zip(transition_years, transition_rasters)))
def test_read_invalid_transition_matrix(self):
"""CBC: Test exceptions in invalid transition structure."""
# The full biophysical table will have much, much more information. To
# keep the test simple, I'm only tracking the columns I know I'll need
# in this function.
biophysical_table = {
1: {'lulc-class': 'a',
'soil-yearly-accumulation': 2,
'biomass-yearly-accumulation': 3,
'soil-high-impact-disturb': 4,
'biomass-high-impact-disturb': 5},
2: {'lulc-class': 'b',
'soil-yearly-accumulation': 6,
'biomass-yearly-accumulation': 7,
'soil-high-impact-disturb': 8,
'biomass-high-impact-disturb': 9},
3: {'lulc-class': 'c',
'soil-yearly-accumulation': 10,
'biomass-yearly-accumulation': 11,
'soil-high-impact-disturb': 12,
'biomass-high-impact-disturb': 13}
}
transition_csv_path = os.path.join(self.workspace_dir,
'transitions.csv')
with open(transition_csv_path, 'w') as transition_csv:
transition_csv.write('lulc-class,a,b,c\n')
transition_csv.write('missing code,NCC,accum,high-impact-disturb\n')
transition_csv.write('b,,NCC,accum\n')
transition_csv.write('c,accum,,NCC\n')
transition_csv.write(',,,\n')
transition_csv.write(',legend,,') # simulate legend
with self.assertRaises(ValueError) as cm:
disturbance_matrices, accumulation_matrices = (
coastal_blue_carbon._read_transition_matrix(
transition_csv_path, biophysical_table))
self.assertIn("'lulc-class' column has a value, 'missing code'",
str(cm.exception))
with open(transition_csv_path, 'w') as transition_csv:
transition_csv.write('lulc-class,missing code,b,c\n')
transition_csv.write('a,NCC,accum,high-impact-disturb\n')
transition_csv.write('b,,NCC,accum\n')
transition_csv.write('c,accum,,NCC\n')
transition_csv.write(',,,\n')
transition_csv.write(',legend,,') # simulate legend
with self.assertRaises(ValueError) as cm:
disturbance_matrices, accumulation_matrices = (
coastal_blue_carbon._read_transition_matrix(
transition_csv_path, biophysical_table))
self.assertIn("The transition table's header row has a column name, "
"'missing code',", str(cm.exception))
def test_read_transition_matrix(self):
"""CBC: Test transition matrix reading."""
# The full biophysical table will have much, much more information. To
# keep the test simple, I'm only tracking the columns I know I'll need
# in this function.
biophysical_table = {
1: {'lulc-class': 'a',
'soil-yearly-accumulation': 2,
'biomass-yearly-accumulation': 3,
'soil-high-impact-disturb': 4,
'biomass-high-impact-disturb': 5},
2: {'lulc-class': 'b',
'soil-yearly-accumulation': 6,
'biomass-yearly-accumulation': 7,
'soil-high-impact-disturb': 8,
'biomass-high-impact-disturb': 9},
3: {'lulc-class': 'c',
'soil-yearly-accumulation': 10,
'biomass-yearly-accumulation': 11,
'soil-high-impact-disturb': 12,
'biomass-high-impact-disturb': 13}
}
transition_csv_path = os.path.join(self.workspace_dir,
'transitions.csv')
with open(transition_csv_path, 'w') as transition_csv:
transition_csv.write('lulc-class,a,b,c\n')
transition_csv.write('a,NCC,accum,high-impact-disturb\n')
transition_csv.write('b,,NCC,accum\n')
transition_csv.write('c,accum,,NCC\n')
transition_csv.write(',,,\n')
transition_csv.write(',legend,,') # simulate legend
disturbance_matrices, accumulation_matrices = (
coastal_blue_carbon._read_transition_matrix(
transition_csv_path, biophysical_table))
expected_biomass_disturbance = numpy.zeros((4, 4), dtype=numpy.float32)
expected_biomass_disturbance[1, 3] = (
biophysical_table[1]['biomass-high-impact-disturb'])
numpy.testing.assert_allclose(
expected_biomass_disturbance,
disturbance_matrices['biomass'].toarray())
expected_soil_disturbance = numpy.zeros((4, 4), dtype=numpy.float32)
expected_soil_disturbance[1, 3] = (
biophysical_table[1]['soil-high-impact-disturb'])
numpy.testing.assert_allclose(
expected_soil_disturbance,
disturbance_matrices['soil'].toarray())
expected_biomass_accumulation = numpy.zeros(
(4, 4), dtype=numpy.float32)
expected_biomass_accumulation[3, 1] = (
biophysical_table[1]['biomass-yearly-accumulation'])
expected_biomass_accumulation[1, 2] = (
biophysical_table[2]['biomass-yearly-accumulation'])
expected_biomass_accumulation[2, 3] = (
biophysical_table[3]['biomass-yearly-accumulation'])
numpy.testing.assert_allclose(
expected_biomass_accumulation,
accumulation_matrices['biomass'].toarray())
expected_soil_accumulation = numpy.zeros((4, 4), dtype=numpy.float32)
expected_soil_accumulation[3, 1] = (
biophysical_table[1]['soil-yearly-accumulation'])
expected_soil_accumulation[1, 2] = (
biophysical_table[2]['soil-yearly-accumulation'])
expected_soil_accumulation[2, 3] = (
biophysical_table[3]['soil-yearly-accumulation'])
numpy.testing.assert_allclose(
expected_soil_accumulation,
accumulation_matrices['soil'].toarray())
def test_emissions(self):
"""CBC: Check emissions calculations."""
volume_disturbed_carbon = numpy.array(
[[5.5, coastal_blue_carbon.NODATA_FLOAT32_MIN]], dtype=numpy.float32)
year_last_disturbed = numpy.array(
[[10, coastal_blue_carbon.NODATA_UINT16_MAX]], dtype=numpy.uint16)
half_life = numpy.array([[7.5, 7.5]], dtype=numpy.float32)
current_year = 15
result_matrix = coastal_blue_carbon._calculate_emissions(
volume_disturbed_carbon, year_last_disturbed, half_life,
current_year)
# Calculated by hand.
expected_array = numpy.array([
[0.3058625, coastal_blue_carbon.NODATA_FLOAT32_MIN]],
dtype=numpy.float32)
numpy.testing.assert_allclose(
result_matrix, expected_array, rtol=1E-6)
def test_add_rasters(self):
"""CBC: Check that we can sum rasters."""
srs = osr.SpatialReference()
srs.ImportFromEPSG(32731) # WGS84 / UTM zone 31 S
wkt = srs.ExportToWkt()
raster_a_path = os.path.join(self.workspace_dir, 'a.tif')
pygeoprocessing.numpy_array_to_raster(
numpy.array([[5, 15, 12, 15]], dtype=numpy.uint8),
15, (2, -2), (2, -2), wkt, raster_a_path)
raster_b_path = os.path.join(self.workspace_dir, 'b.tif')
pygeoprocessing.numpy_array_to_raster(
numpy.array([[3, 4, 5, 5]], dtype=numpy.uint8),
5, (2, -2), (2, -2), wkt, raster_b_path)
target_path = os.path.join(self.workspace_dir, 'output.tif')
coastal_blue_carbon._sum_n_rasters(
[raster_a_path, raster_b_path], target_path)
nodata = coastal_blue_carbon.NODATA_FLOAT32_MIN
try:
raster = gdal.OpenEx(target_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
numpy.array([[8, 4, 12, nodata]], dtype=numpy.float32))
finally:
raster = None
@staticmethod
def _create_model_args(target_dir):
srs = osr.SpatialReference()
srs.ImportFromEPSG(32731) # WGS84 / UTM zone 31 S
wkt = srs.ExportToWkt()
biophysical_table = [
['code', 'lulc-class', 'biomass-initial', 'soil-initial',
'litter-initial', 'biomass-half-life',
'biomass-low-impact-disturb', 'biomass-med-impact-disturb',
'biomass-high-impact-disturb', 'biomass-yearly-accumulation',
'soil-half-life', 'soil-low-impact-disturb',
'soil-med-impact-disturb', 'soil-high-impact-disturb',
'soil-yearly-accumulation', 'litter-yearly-accumulation'],
[1, 'mangrove',
64, 313, 3, # initial
15, 0.5, 0.5, 1, 2, # biomass
7.5, 0.3, 0.5, 0.66, 5.35, # soil
1], # litter accum.
[2, 'parking lot',
0, 0, 0, # initial
0, 0, 0, 0, 0, # biomass
0, 0, 0, 0, 0, # soil
0], # litter accum.
]
biophysical_table_path = os.path.join(
target_dir, 'biophysical.csv')
with open(biophysical_table_path, 'w') as bio_table:
for line_list in biophysical_table:
line = ','.join(str(field) for field in line_list)
bio_table.write(f'{line}\n')
transition_matrix = [
['lulc-class', 'mangrove', 'parking lot'],
['mangrove', 'NCC', 'high-impact-disturb'],
['parking lot', 'accum', 'NCC']
]
transition_matrix_path = os.path.join(
target_dir, 'transitions.csv')
with open(transition_matrix_path, 'w') as transition_table:
for line_list in transition_matrix:
line = ','.join(line_list)
transition_table.write(f'{line}\n')
baseline_landcover_raster_path = os.path.join(
target_dir, 'baseline_lulc.tif')
baseline_matrix = numpy.array([[1, 2]], dtype=numpy.uint8)
pygeoprocessing.numpy_array_to_raster(
baseline_matrix, 255, (2, -2), (2, -2), wkt,
baseline_landcover_raster_path)
snapshot_2010_raster_path = os.path.join(
target_dir, 'snapshot_2010.tif')
snapshot_2010_matrix = numpy.array([[2, 1]], dtype=numpy.uint8)
pygeoprocessing.numpy_array_to_raster(
snapshot_2010_matrix, 255, (2, -2), (2, -2), wkt,
snapshot_2010_raster_path)
snapshot_2020_raster_path = os.path.join(
target_dir, 'snapshot_2020.tif')
snapshot_2020_matrix = numpy.array([[1, 2]], dtype=numpy.uint8)
pygeoprocessing.numpy_array_to_raster(
snapshot_2020_matrix, 255, (2, -2), (2, -2), wkt,
snapshot_2020_raster_path)
snapshot_rasters_csv_path = os.path.join(
target_dir, 'snapshot_rasters.csv')
baseline_year = 2000
with open(snapshot_rasters_csv_path, 'w') as snapshot_rasters_csv:
snapshot_rasters_csv.write('snapshot_year,raster_path\n')
snapshot_rasters_csv.write(
f'{baseline_year},{baseline_landcover_raster_path}\n')
snapshot_rasters_csv.write(
f'2010,{snapshot_2010_raster_path}\n')
snapshot_rasters_csv.write(
f'2020,{snapshot_2020_raster_path}\n')
args = {
'landcover_transitions_table': transition_matrix_path,
'landcover_snapshot_csv': snapshot_rasters_csv_path,
'biophysical_table_path': biophysical_table_path,
'analysis_year': 2030,
'do_economic_analysis': True,
'use_price_table': True,
'price_table_path': os.path.join(target_dir,
'price_table.csv'),
'discount_rate': 4,
}
with open(args['price_table_path'], 'w') as price_table:
price_table.write('year,price\n')
prior_year_price = 1.0
for year in range(baseline_year,
args['analysis_year']+1):
price = prior_year_price * 1.04
price_table.write(f'{year},{price}\n')
return args
def test_duplicate_lulc_classes(self):
"""CBC: Raise an execption if duplicate lulc-classes."""
args = TestCBC2._create_model_args(self.workspace_dir)
args['workspace_dir'] = os.path.join(self.workspace_dir, 'workspace')
with open(args['biophysical_table_path'], 'r') as table:
lines = table.readlines()
with open(args['biophysical_table_path'], 'a') as table:
last_line_contents = lines[-1].strip().split(',')
last_line_contents[0] = '3' # assign a new code
table.write(','.join(last_line_contents))
with self.assertRaises(ValueError) as context:
coastal_blue_carbon.execute(args)
self.assertIn("`lulc-class` column must be unique",
str(context.exception))
def test_model_no_analysis_year_no_price_table(self):
"""CBC: Test the model's execution."""
args = TestCBC2._create_model_args(self.workspace_dir)
args['workspace_dir'] = os.path.join(self.workspace_dir, 'workspace')
del args['analysis_year'] # final year is 2020.
args['use_price_table'] = False
args['inflation_rate'] = 5
args['price'] = 10.0
coastal_blue_carbon.execute(args)
# Sample values calculated by hand. Pixel 0 only accumulates. Pixel 1
# has no accumulation (per the biophysical table) and also has no
# emissions.
expected_sequestration_2000_to_2010 = numpy.array(
[[83.5, 0]], dtype=numpy.float32)
raster_path = os.path.join(
args['workspace_dir'], 'output',
('total-net-carbon-sequestration-between-'
'2000-and-2010.tif'))
try:
raster = gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_sequestration_2000_to_2010)
finally:
raster = None
expected_sequestration_2010_to_2020 = numpy.array(
[[-176.9792, 73.5]], dtype=numpy.float32)
raster_path = os.path.join(
args['workspace_dir'], 'output',
('total-net-carbon-sequestration-between-'
'2010-and-2020.tif'))
try:
raster = gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_sequestration_2010_to_2020, rtol=1e-6)
finally:
raster = None
# Total sequestration is the sum of all the previous sequestration.
expected_total_sequestration = (
expected_sequestration_2000_to_2010 +
expected_sequestration_2010_to_2020)
raster_path = os.path.join(
args['workspace_dir'], 'output',
'total-net-carbon-sequestration.tif')
try:
raster = gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_total_sequestration, rtol=1e-6)
finally:
raster = None
expected_net_present_value_at_2020 = numpy.array(
[[-20506.314, 16123.521]], dtype=numpy.float32)
raster_path = os.path.join(
args['workspace_dir'], 'output', 'net-present-value-at-2020.tif')
try:
raster = gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_net_present_value_at_2020, rtol=1e-6)
finally:
raster = None
def test_model_one_transition_no_analysis_year(self):
"""CBC: Test the model on one transition with no analysis year.
This test came up while looking into an issue reported on the forums:
https://community.naturalcapitalproject.org/t/coastal-blue-carbon-negative-carbon-stocks/780/12
"""
args = TestCBC2._create_model_args(self.workspace_dir)
args['workspace_dir'] = os.path.join(self.workspace_dir, 'workspace')
prior_snapshots = coastal_blue_carbon._extract_snapshots_from_table(
args['landcover_snapshot_csv'])
baseline_year = min(prior_snapshots.keys())
baseline_raster = prior_snapshots[baseline_year]
with open(args['landcover_snapshot_csv'], 'w') as snapshot_csv:
snapshot_csv.write('snapshot_year,raster_path\n')
snapshot_csv.write(f'{baseline_year},{baseline_raster}\n')
snapshot_csv.write(f'2010,{prior_snapshots[2010]}\n')
del args['analysis_year']
# Use valuation parameters rather than price table.
args['use_price_table'] = False
args['inflation_rate'] = 4
args['price'] = 1.0
coastal_blue_carbon.execute(args)
# Check sequestration raster
expected_sequestration_2000_to_2010 = numpy.array(
[[83.5, 0.]], dtype=numpy.float32)
raster_path = os.path.join(
args['workspace_dir'], 'output',
('total-net-carbon-sequestration-between-'
'2000-and-2010.tif'))
try:
raster= gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_sequestration_2000_to_2010)
finally:
raster = None
# Check valuation raster
# Discount rate here matches the inflation rate, so the value of the 10
# years' accumulation is just 1*(10 years of accumulation).
expected_net_present_value_at_2010 = numpy.array(
[[835.0, 0.]], dtype=numpy.float32)
raster_path = os.path.join(
args['workspace_dir'], 'output', 'net-present-value-at-2010.tif')
try:
raster = gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_net_present_value_at_2010, rtol=1e-6)
finally:
raster = None
def test_model(self):
"""CBC: Test the model's execution."""
args = TestCBC2._create_model_args(self.workspace_dir)
args['workspace_dir'] = os.path.join(self.workspace_dir, 'workspace')
coastal_blue_carbon.execute(args)
# Sample values calculated by hand. Pixel 0 only accumulates. Pixel 1
# has no accumulation (per the biophysical table) and also has no
# emissions.
expected_sequestration_2000_to_2010 = numpy.array(
[[83.5, 0]], dtype=numpy.float32)
raster_path = os.path.join(
args['workspace_dir'], 'output',
('total-net-carbon-sequestration-between-'
'2000-and-2010.tif'))
try:
raster = gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_sequestration_2000_to_2010)
finally:
raster = None
expected_sequestration_2010_to_2020 = numpy.array(
[[-176.9792, 73.5]], dtype=numpy.float32)
raster_path = os.path.join(
args['workspace_dir'], 'output',
('total-net-carbon-sequestration-between-'
'2010-and-2020.tif'))
try:
raster = gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_sequestration_2010_to_2020, rtol=1e-6)
finally:
raster = None
expected_sequestration_2020_to_2030 = numpy.array(
[[73.5, -28.698004]], dtype=numpy.float32)
raster_path = os.path.join(
args['workspace_dir'], 'output',
('total-net-carbon-sequestration-between-'
'2020-and-2030.tif'))
try:
raster = gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_sequestration_2020_to_2030, rtol=1e-6)
finally:
raster = None
# Total sequestration is the sum of all the previous sequestration.
expected_total_sequestration = (
expected_sequestration_2000_to_2010 +
expected_sequestration_2010_to_2020 +
expected_sequestration_2020_to_2030)
raster_path = os.path.join(
args['workspace_dir'], 'output',
'total-net-carbon-sequestration.tif')
try:
raster = gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_total_sequestration, rtol=1e-6)
finally:
raster = None
expected_net_present_value_at_2030 = numpy.array(
[[-373.67245, 837.93445]], dtype=numpy.float32)
raster_path = os.path.join(
args['workspace_dir'], 'output', 'net-present-value-at-2030.tif')
try:
raster = gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_net_present_value_at_2030, rtol=1e-6)
finally:
raster = None
# For emissions, make sure that each of the emissions sum rasters in
# the output folder match the sum of all annual emissions from the time
# period.
for emissions_raster_path in glob.glob(
os.path.join(args['workspace_dir'], 'output',
'carbon-emissions-between-*.tif')):
try:
raster = gdal.OpenEx(emissions_raster_path)
band = raster.GetRasterBand(1)
emissions_in_period = band.ReadAsArray()
finally:
band = None
raster = None
basename = os.path.splitext(
os.path.basename(emissions_raster_path))[0]
parts = basename.split('-')
start_year = int(parts[3])
end_year = int(parts[5])
summed_emissions_over_time_period = numpy.array(
[[0.0, 0.0]], dtype=numpy.float32)
for year in range(start_year, end_year):
for pool in ('soil', 'biomass'):
yearly_emissions_raster = os.path.join(
args['workspace_dir'], 'intermediate',
f'emissions-{pool}-{year}.tif')
try:
raster = gdal.OpenEx(yearly_emissions_raster)
band = raster.GetRasterBand(1)
summed_emissions_over_time_period += band.ReadAsArray()
finally:
band = None
raster = None
numpy.testing.assert_allclose(
emissions_in_period,
summed_emissions_over_time_period)
def test_model_no_transitions(self):
"""CBC: Test model without transitions.
When the model executes without transitions, we still evaluate carbon
sequestration (accumulation only) for the whole baseline period.
"""
args = TestCBC2._create_model_args(self.workspace_dir)
args['workspace_dir'] = os.path.join(self.workspace_dir, 'workspace')
prior_snapshots = coastal_blue_carbon._extract_snapshots_from_table(
args['landcover_snapshot_csv'])
baseline_year = min(prior_snapshots.keys())
baseline_raster = prior_snapshots[baseline_year]
with open(args['landcover_snapshot_csv'], 'w') as snapshot_csv:
snapshot_csv.write('snapshot_year,raster_path\n')
snapshot_csv.write(f'{baseline_year},{baseline_raster}\n')
args['analysis_year'] = baseline_year + 10
# Use valuation parameters rather than price table.
args['use_price_table'] = False
args['inflation_rate'] = 4
args['price'] = 1.0
coastal_blue_carbon.execute(args)
# Check sequestration raster
expected_sequestration_2000_to_2010 = numpy.array(
[[83.5, 0.]], dtype=numpy.float32)
raster_path = os.path.join(
args['workspace_dir'], 'output',
('total-net-carbon-sequestration-between-'
'2000-and-2010.tif'))
try:
raster= gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_sequestration_2000_to_2010)
finally:
raster = None
# Check valuation raster
# Discount rate here matches the inflation rate, so the value of the 10
# years' accumulation is just 1*(10 years of accumulation).
expected_net_present_value_at_2010 = numpy.array(
[[835.0, 0.]], dtype=numpy.float32)
raster_path = os.path.join(
args['workspace_dir'], 'output', 'net-present-value-at-2010.tif')
try:
raster = gdal.OpenEx(raster_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_net_present_value_at_2010, rtol=1e-6)
finally:
raster = None
def test_validation(self):
"""CBC: Test custom validation."""
args = TestCBC2._create_model_args(self.workspace_dir)
args['workspace_dir'] = self.workspace_dir
# verify validation passes on basic set of arguments.
validation_warnings = coastal_blue_carbon.validate(args)
self.assertEqual([], validation_warnings)
# Now work through the extra validation warnings.
# Create an invalid transitions table.
invalid_raster_path = os.path.join(self.workspace_dir,
'invalid_raster.tif')
with open(invalid_raster_path, 'w') as raster:
raster.write('not a raster')
# Write over the landcover snapshot CSV
prior_snapshots = coastal_blue_carbon._extract_snapshots_from_table(
args['landcover_snapshot_csv'])
baseline_year = min(prior_snapshots)
with open(args['landcover_snapshot_csv'], 'w') as snapshot_table:
snapshot_table.write('snapshot_year,raster_path\n')
snapshot_table.write(
f'{baseline_year},{prior_snapshots[baseline_year]}\n')
snapshot_table.write(
f"{baseline_year + 10},{invalid_raster_path}")
# analysis year must be >= the last transition year.
args['analysis_year'] = baseline_year
validation_warnings = coastal_blue_carbon.validate(args)
self.assertEqual(len(validation_warnings), 2)
self.assertIn(
f"Raster for snapshot {baseline_year + 10} could not "
"be validated", validation_warnings[0][1])
self.assertIn(
"Analysis year 2000 must be >= the latest snapshot year "
"(2010)",
validation_warnings[1][1])
def test_track_first_disturbance(self):
"""CBC: Track disturbances over time."""
float32_nodata = coastal_blue_carbon.NODATA_FLOAT32_MIN
srs = osr.SpatialReference()
srs.ImportFromEPSG(32731) # WGS84 / UTM zone 31 S
wkt = srs.ExportToWkt()
disturbance_magnitude_path = os.path.join(
self.workspace_dir, 'disturbance_magnitude.tif')
disturbance_magnitude_matrix = numpy.array(
[[0.5, float32_nodata, 0.0]], dtype=numpy.float32)
pygeoprocessing.numpy_array_to_raster(
disturbance_magnitude_matrix, float32_nodata, (2, -2), (2, -2), wkt,
disturbance_magnitude_path)
stocks_path = os.path.join(
self.workspace_dir, 'stocks.tif')
stocks_matrix = numpy.array(
[[10, -1, 10]], dtype=numpy.float32)
pygeoprocessing.numpy_array_to_raster(
stocks_matrix, -1, (2, -2), (2, -2), wkt, stocks_path)
current_year = 2010
target_disturbance_path = os.path.join(
self.workspace_dir, 'disturbance_volume.tif')
target_year_of_disturbance = os.path.join(
self.workspace_dir, 'year_of_disturbance.tif')
coastal_blue_carbon._track_disturbance(
disturbance_magnitude_path, stocks_path,
None, # No prior disturbance volume
None, # No prior disturbance years
current_year, target_disturbance_path, target_year_of_disturbance)
try:
expected_disturbance = numpy.array(
[[5.0, float32_nodata, 0.0]], dtype=numpy.float32)
raster = gdal.OpenEx(target_disturbance_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_disturbance)
finally:
raster = None
try:
uint16_nodata = coastal_blue_carbon.NODATA_UINT16_MAX
expected_year_of_disturbance = numpy.array(
[[2010, uint16_nodata, uint16_nodata]], dtype=numpy.uint16)
raster = gdal.OpenEx(target_year_of_disturbance)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_year_of_disturbance)
finally:
raster = None
def test_track_later_disturbance(self):
"""CBC: Track disturbances over time."""
float32_nodata = coastal_blue_carbon.NODATA_FLOAT32_MIN
uint16_nodata = coastal_blue_carbon.NODATA_UINT16_MAX
srs = osr.SpatialReference()
srs.ImportFromEPSG(32731) # WGS84 / UTM zone 31 S
wkt = srs.ExportToWkt()
disturbance_magnitude_path = os.path.join(
self.workspace_dir, 'disturbance_magnitude.tif')
disturbance_magnitude_matrix = numpy.array(
[[0.5, float32_nodata, 0.0]], dtype=numpy.float32)
pygeoprocessing.numpy_array_to_raster(
disturbance_magnitude_matrix, float32_nodata, (2, -2), (2, -2), wkt,
disturbance_magnitude_path)
stocks_path = os.path.join(
self.workspace_dir, 'stocks.tif')
stocks_matrix = numpy.array(
[[10, -1, 10]], dtype=numpy.float32)
pygeoprocessing.numpy_array_to_raster(
stocks_matrix, -1, (2, -2), (2, -2), wkt, stocks_path)
prior_disturbance_volume_path = os.path.join(
self.workspace_dir, 'prior_disturbance_vol.tif')
prior_disturbance_vol_matrix = numpy.array(
[[700, float32_nodata, 300]], numpy.float32)
pygeoprocessing.numpy_array_to_raster(
prior_disturbance_vol_matrix, float32_nodata, (2, -2), (2, -2),
wkt, prior_disturbance_volume_path)
prior_year_disturbance_path = os.path.join(
self.workspace_dir, 'prior_disturbance_years.tif')
prior_year_disturbance_matrix = numpy.array(
[[2000, uint16_nodata, 1990]], numpy.uint16)
pygeoprocessing.numpy_array_to_raster(
prior_year_disturbance_matrix, uint16_nodata, (2, -2), (2, -2), wkt,
prior_year_disturbance_path)
target_disturbance_path = os.path.join(
self.workspace_dir, 'disturbance_volume.tif')
target_year_of_disturbance = os.path.join(
self.workspace_dir, 'year_of_disturbance.tif')
current_year = 2010
coastal_blue_carbon._track_disturbance(
disturbance_magnitude_path, stocks_path,
prior_disturbance_volume_path,
prior_year_disturbance_path,
current_year, target_disturbance_path, target_year_of_disturbance)
try:
expected_disturbance = numpy.array(
[[5.0, float32_nodata, 300]], dtype=numpy.float32)
raster = gdal.OpenEx(target_disturbance_path)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_disturbance)
finally:
raster = None
try:
expected_year_of_disturbance = numpy.array(
[[2010, uint16_nodata, 1990]], dtype=numpy.uint16)
raster = gdal.OpenEx(target_year_of_disturbance)
numpy.testing.assert_allclose(
raster.ReadAsArray(),
expected_year_of_disturbance)
finally:
raster = None
| [
"pprint.pformat",
"os.walk",
"natcap.invest.coastal_blue_carbon.coastal_blue_carbon._track_disturbance",
"logging.getLogger",
"shutil.rmtree",
"os.path.join",
"natcap.invest.coastal_blue_carbon.coastal_blue_carbon._calculate_emissions",
"os.path.dirname",
"pygeoprocessing.numpy_array_to_raster",
"... | [((467, 494), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (484, 494), False, 'import logging\n'), ((370, 395), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (385, 395), False, 'import os\n'), ((707, 725), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (723, 725), False, 'import tempfile\n'), ((791, 824), 'shutil.rmtree', 'shutil.rmtree', (['self.workspace_dir'], {}), '(self.workspace_dir)\n', (804, 824), False, 'import shutil\n'), ((1007, 1063), 'os.path.join', 'os.path.join', (['REGRESSION_DATA', '"""inputs"""', '"""snapshots.csv"""'], {}), "(REGRESSION_DATA, 'inputs', 'snapshots.csv')\n", (1019, 1063), False, 'import os\n'), ((1401, 1427), 'natcap.invest.coastal_blue_carbon.preprocessor.execute', 'preprocessor.execute', (['args'], {}), '(args)\n', (1421, 1427), False, 'from natcap.invest.coastal_blue_carbon import preprocessor\n'), ((1589, 1648), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""outputs_preprocessor"""'], {}), "(args['workspace_dir'], 'outputs_preprocessor')\n", (1601, 1648), False, 'import os\n'), ((1707, 1727), 'os.walk', 'os.walk', (['outputs_dir'], {}), '(outputs_dir)\n', (1714, 1727), False, 'import os\n'), ((2941, 2963), 'osgeo.osr.SpatialReference', 'osr.SpatialReference', ([], {}), '()\n', (2961, 2963), False, 'from osgeo import gdal, osr\n'), ((3126, 3182), 'numpy.array', 'numpy.array', (['[[0, 1], [0, 1], [0, 1]]'], {'dtype': 'numpy.int16'}), '([[0, 1], [0, 1], [0, 1]], dtype=numpy.int16)\n', (3137, 3182), False, 'import numpy\n'), ((3241, 3289), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""raster_a.tif"""'], {}), "(self.workspace_dir, 'raster_a.tif')\n", (3253, 3289), False, 'import os\n'), ((3298, 3402), 'pygeoprocessing.numpy_array_to_raster', 'pygeoprocessing.numpy_array_to_raster', (['matrix_a', '(-1)', '(100, -100)', 'origin', 'projection_wkt', 'filename_a'], {}), '(matrix_a, -1, (100, -100), origin,\n projection_wkt, filename_a)\n', (3335, 3402), False, 'import pygeoprocessing\n'), ((3432, 3490), 'numpy.array', 'numpy.array', (['[[0, 1], [1, 0], [-1, -1]]'], {'dtype': 'numpy.int16'}), '([[0, 1], [1, 0], [-1, -1]], dtype=numpy.int16)\n', (3443, 3490), False, 'import numpy\n'), ((3549, 3597), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""raster_b.tif"""'], {}), "(self.workspace_dir, 'raster_b.tif')\n", (3561, 3597), False, 'import os\n'), ((3606, 3710), 'pygeoprocessing.numpy_array_to_raster', 'pygeoprocessing.numpy_array_to_raster', (['matrix_b', '(-1)', '(100, -100)', 'origin', 'projection_wkt', 'filename_b'], {}), '(matrix_b, -1, (100, -100), origin,\n projection_wkt, filename_b)\n', (3643, 3710), False, 'import pygeoprocessing\n'), ((3752, 3802), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""lulc_table.csv"""'], {}), "(self.workspace_dir, 'lulc_table.csv')\n", (3764, 3802), False, 'import os\n'), ((4111, 4168), 'natcap.invest.utils.build_lookup_from_csv', 'utils.build_lookup_from_csv', (['landcover_table_path', '"""code"""'], {}), "(landcover_table_path, 'code')\n", (4138, 4168), False, 'from natcap.invest import utils\n'), ((4210, 4266), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""transition_table.csv"""'], {}), "(self.workspace_dir, 'transition_table.csv')\n", (4222, 4266), False, 'import os\n'), ((4763, 4820), 'natcap.invest.utils.build_lookup_from_csv', 'utils.build_lookup_from_csv', (['landcover_table_path', '"""code"""'], {}), "(landcover_table_path, 'code')\n", (4790, 4820), False, 'from natcap.invest import utils\n'), ((4842, 4945), 'natcap.invest.coastal_blue_carbon.preprocessor._create_transition_table', 'preprocessor._create_transition_table', (['landcover_table', '[filename_a, filename_b]', 'target_table_path'], {}), '(landcover_table, [filename_a,\n filename_b], target_table_path)\n', (4879, 4945), False, 'from natcap.invest.coastal_blue_carbon import preprocessor\n'), ((5767, 5785), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (5783, 5785), False, 'import tempfile\n'), ((5876, 5909), 'shutil.rmtree', 'shutil.rmtree', (['self.workspace_dir'], {}), '(self.workspace_dir)\n', (5889, 5909), False, 'import shutil\n'), ((6026, 6075), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""snapshots.csv"""'], {}), "(self.workspace_dir, 'snapshots.csv')\n", (6038, 6075), False, 'import os\n'), ((7157, 7216), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon._extract_snapshots_from_table', 'coastal_blue_carbon._extract_snapshots_from_table', (['csv_path'], {}), '(csv_path)\n', (7206, 7216), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((8412, 8463), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""transitions.csv"""'], {}), "(self.workspace_dir, 'transitions.csv')\n", (8424, 8463), False, 'import os\n'), ((11094, 11145), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""transitions.csv"""'], {}), "(self.workspace_dir, 'transitions.csv')\n", (11106, 11145), False, 'import os\n'), ((11656, 11743), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon._read_transition_matrix', 'coastal_blue_carbon._read_transition_matrix', (['transition_csv_path', 'biophysical_table'], {}), '(transition_csv_path,\n biophysical_table)\n', (11699, 11743), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((11799, 11839), 'numpy.zeros', 'numpy.zeros', (['(4, 4)'], {'dtype': 'numpy.float32'}), '((4, 4), dtype=numpy.float32)\n', (11810, 11839), False, 'import numpy\n'), ((12125, 12165), 'numpy.zeros', 'numpy.zeros', (['(4, 4)'], {'dtype': 'numpy.float32'}), '((4, 4), dtype=numpy.float32)\n', (12136, 12165), False, 'import numpy\n'), ((12443, 12483), 'numpy.zeros', 'numpy.zeros', (['(4, 4)'], {'dtype': 'numpy.float32'}), '((4, 4), dtype=numpy.float32)\n', (12454, 12483), False, 'import numpy\n'), ((13012, 13052), 'numpy.zeros', 'numpy.zeros', (['(4, 4)'], {'dtype': 'numpy.float32'}), '((4, 4), dtype=numpy.float32)\n', (13023, 13052), False, 'import numpy\n'), ((13620, 13706), 'numpy.array', 'numpy.array', (['[[5.5, coastal_blue_carbon.NODATA_FLOAT32_MIN]]'], {'dtype': 'numpy.float32'}), '([[5.5, coastal_blue_carbon.NODATA_FLOAT32_MIN]], dtype=numpy.\n float32)\n', (13631, 13706), False, 'import numpy\n'), ((13745, 13823), 'numpy.array', 'numpy.array', (['[[10, coastal_blue_carbon.NODATA_UINT16_MAX]]'], {'dtype': 'numpy.uint16'}), '([[10, coastal_blue_carbon.NODATA_UINT16_MAX]], dtype=numpy.uint16)\n', (13756, 13823), False, 'import numpy\n'), ((13857, 13903), 'numpy.array', 'numpy.array', (['[[7.5, 7.5]]'], {'dtype': 'numpy.float32'}), '([[7.5, 7.5]], dtype=numpy.float32)\n', (13868, 13903), False, 'import numpy\n'), ((13955, 14070), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon._calculate_emissions', 'coastal_blue_carbon._calculate_emissions', (['volume_disturbed_carbon', 'year_last_disturbed', 'half_life', 'current_year'], {}), '(volume_disturbed_carbon,\n year_last_disturbed, half_life, current_year)\n', (13995, 14070), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((14148, 14240), 'numpy.array', 'numpy.array', (['[[0.3058625, coastal_blue_carbon.NODATA_FLOAT32_MIN]]'], {'dtype': 'numpy.float32'}), '([[0.3058625, coastal_blue_carbon.NODATA_FLOAT32_MIN]], dtype=\n numpy.float32)\n', (14159, 14240), False, 'import numpy\n'), ((14269, 14341), 'numpy.testing.assert_allclose', 'numpy.testing.assert_allclose', (['result_matrix', 'expected_array'], {'rtol': '(1e-06)'}), '(result_matrix, expected_array, rtol=1e-06)\n', (14298, 14341), False, 'import numpy\n'), ((14451, 14473), 'osgeo.osr.SpatialReference', 'osr.SpatialReference', ([], {}), '()\n', (14471, 14473), False, 'from osgeo import gdal, osr\n'), ((14590, 14631), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""a.tif"""'], {}), "(self.workspace_dir, 'a.tif')\n", (14602, 14631), False, 'import os\n'), ((14821, 14862), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""b.tif"""'], {}), "(self.workspace_dir, 'b.tif')\n", (14833, 14862), False, 'import os\n'), ((15046, 15092), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""output.tif"""'], {}), "(self.workspace_dir, 'output.tif')\n", (15058, 15092), False, 'import os\n'), ((15101, 15180), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon._sum_n_rasters', 'coastal_blue_carbon._sum_n_rasters', (['[raster_a_path, raster_b_path]', 'target_path'], {}), '([raster_a_path, raster_b_path], target_path)\n', (15135, 15180), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((15579, 15601), 'osgeo.osr.SpatialReference', 'osr.SpatialReference', ([], {}), '()\n', (15599, 15601), False, 'from osgeo import gdal, osr\n'), ((16640, 16683), 'os.path.join', 'os.path.join', (['target_dir', '"""biophysical.csv"""'], {}), "(target_dir, 'biophysical.csv')\n", (16652, 16683), False, 'import os\n'), ((17147, 17190), 'os.path.join', 'os.path.join', (['target_dir', '"""transitions.csv"""'], {}), "(target_dir, 'transitions.csv')\n", (17159, 17190), False, 'import os\n'), ((17457, 17502), 'os.path.join', 'os.path.join', (['target_dir', '"""baseline_lulc.tif"""'], {}), "(target_dir, 'baseline_lulc.tif')\n", (17469, 17502), False, 'import os\n'), ((17542, 17582), 'numpy.array', 'numpy.array', (['[[1, 2]]'], {'dtype': 'numpy.uint8'}), '([[1, 2]], dtype=numpy.uint8)\n', (17553, 17582), False, 'import numpy\n'), ((17591, 17710), 'pygeoprocessing.numpy_array_to_raster', 'pygeoprocessing.numpy_array_to_raster', (['baseline_matrix', '(255)', '(2, -2)', '(2, -2)', 'wkt', 'baseline_landcover_raster_path'], {}), '(baseline_matrix, 255, (2, -2), (2, -2\n ), wkt, baseline_landcover_raster_path)\n', (17628, 17710), False, 'import pygeoprocessing\n'), ((17768, 17813), 'os.path.join', 'os.path.join', (['target_dir', '"""snapshot_2010.tif"""'], {}), "(target_dir, 'snapshot_2010.tif')\n", (17780, 17813), False, 'import os\n'), ((17858, 17898), 'numpy.array', 'numpy.array', (['[[2, 1]]'], {'dtype': 'numpy.uint8'}), '([[2, 1]], dtype=numpy.uint8)\n', (17869, 17898), False, 'import numpy\n'), ((17907, 18026), 'pygeoprocessing.numpy_array_to_raster', 'pygeoprocessing.numpy_array_to_raster', (['snapshot_2010_matrix', '(255)', '(2, -2)', '(2, -2)', 'wkt', 'snapshot_2010_raster_path'], {}), '(snapshot_2010_matrix, 255, (2, -2), (\n 2, -2), wkt, snapshot_2010_raster_path)\n', (17944, 18026), False, 'import pygeoprocessing\n'), ((18084, 18129), 'os.path.join', 'os.path.join', (['target_dir', '"""snapshot_2020.tif"""'], {}), "(target_dir, 'snapshot_2020.tif')\n", (18096, 18129), False, 'import os\n'), ((18174, 18214), 'numpy.array', 'numpy.array', (['[[1, 2]]'], {'dtype': 'numpy.uint8'}), '([[1, 2]], dtype=numpy.uint8)\n', (18185, 18214), False, 'import numpy\n'), ((18223, 18342), 'pygeoprocessing.numpy_array_to_raster', 'pygeoprocessing.numpy_array_to_raster', (['snapshot_2020_matrix', '(255)', '(2, -2)', '(2, -2)', 'wkt', 'snapshot_2020_raster_path'], {}), '(snapshot_2020_matrix, 255, (2, -2), (\n 2, -2), wkt, snapshot_2020_raster_path)\n', (18260, 18342), False, 'import pygeoprocessing\n'), ((18400, 18448), 'os.path.join', 'os.path.join', (['target_dir', '"""snapshot_rasters.csv"""'], {}), "(target_dir, 'snapshot_rasters.csv')\n", (18412, 18448), False, 'import os\n'), ((20002, 20047), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""workspace"""'], {}), "(self.workspace_dir, 'workspace')\n", (20014, 20047), False, 'import os\n'), ((20804, 20849), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""workspace"""'], {}), "(self.workspace_dir, 'workspace')\n", (20816, 20849), False, 'import os\n'), ((21020, 21053), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon.execute', 'coastal_blue_carbon.execute', (['args'], {}), '(args)\n', (21047, 21053), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((21276, 21321), 'numpy.array', 'numpy.array', (['[[83.5, 0]]'], {'dtype': 'numpy.float32'}), '([[83.5, 0]], dtype=numpy.float32)\n', (21287, 21321), False, 'import numpy\n'), ((21357, 21466), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""total-net-carbon-sequestration-between-2000-and-2010.tif"""'], {}), "(args['workspace_dir'], 'output',\n 'total-net-carbon-sequestration-between-2000-and-2010.tif')\n", (21369, 21466), False, 'import os\n'), ((21792, 21845), 'numpy.array', 'numpy.array', (['[[-176.9792, 73.5]]'], {'dtype': 'numpy.float32'}), '([[-176.9792, 73.5]], dtype=numpy.float32)\n', (21803, 21845), False, 'import numpy\n'), ((21881, 21990), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""total-net-carbon-sequestration-between-2010-and-2020.tif"""'], {}), "(args['workspace_dir'], 'output',\n 'total-net-carbon-sequestration-between-2010-and-2020.tif')\n", (21893, 21990), False, 'import os\n'), ((22519, 22606), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""total-net-carbon-sequestration.tif"""'], {}), "(args['workspace_dir'], 'output',\n 'total-net-carbon-sequestration.tif')\n", (22531, 22606), False, 'import os\n'), ((22914, 22973), 'numpy.array', 'numpy.array', (['[[-20506.314, 16123.521]]'], {'dtype': 'numpy.float32'}), '([[-20506.314, 16123.521]], dtype=numpy.float32)\n', (22925, 22973), False, 'import numpy\n'), ((23010, 23088), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""net-present-value-at-2020.tif"""'], {}), "(args['workspace_dir'], 'output', 'net-present-value-at-2020.tif')\n", (23022, 23088), False, 'import os\n'), ((23769, 23814), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""workspace"""'], {}), "(self.workspace_dir, 'workspace')\n", (23781, 23814), False, 'import os\n'), ((23842, 23928), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon._extract_snapshots_from_table', 'coastal_blue_carbon._extract_snapshots_from_table', (["args['landcover_snapshot_csv']"], {}), "(args[\n 'landcover_snapshot_csv'])\n", (23891, 23928), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((24524, 24557), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon.execute', 'coastal_blue_carbon.execute', (['args'], {}), '(args)\n', (24551, 24557), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((24642, 24689), 'numpy.array', 'numpy.array', (['[[83.5, 0.0]]'], {'dtype': 'numpy.float32'}), '([[83.5, 0.0]], dtype=numpy.float32)\n', (24653, 24689), False, 'import numpy\n'), ((24724, 24833), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""total-net-carbon-sequestration-between-2000-and-2010.tif"""'], {}), "(args['workspace_dir'], 'output',\n 'total-net-carbon-sequestration-between-2000-and-2010.tif')\n", (24736, 24833), False, 'import os\n'), ((25338, 25386), 'numpy.array', 'numpy.array', (['[[835.0, 0.0]]'], {'dtype': 'numpy.float32'}), '([[835.0, 0.0]], dtype=numpy.float32)\n', (25349, 25386), False, 'import numpy\n'), ((25421, 25499), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""net-present-value-at-2010.tif"""'], {}), "(args['workspace_dir'], 'output', 'net-present-value-at-2010.tif')\n", (25433, 25499), False, 'import os\n'), ((25928, 25973), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""workspace"""'], {}), "(self.workspace_dir, 'workspace')\n", (25940, 25973), False, 'import os\n'), ((25983, 26016), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon.execute', 'coastal_blue_carbon.execute', (['args'], {}), '(args)\n', (26010, 26016), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((26239, 26284), 'numpy.array', 'numpy.array', (['[[83.5, 0]]'], {'dtype': 'numpy.float32'}), '([[83.5, 0]], dtype=numpy.float32)\n', (26250, 26284), False, 'import numpy\n'), ((26320, 26429), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""total-net-carbon-sequestration-between-2000-and-2010.tif"""'], {}), "(args['workspace_dir'], 'output',\n 'total-net-carbon-sequestration-between-2000-and-2010.tif')\n", (26332, 26429), False, 'import os\n'), ((26755, 26808), 'numpy.array', 'numpy.array', (['[[-176.9792, 73.5]]'], {'dtype': 'numpy.float32'}), '([[-176.9792, 73.5]], dtype=numpy.float32)\n', (26766, 26808), False, 'import numpy\n'), ((26844, 26953), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""total-net-carbon-sequestration-between-2010-and-2020.tif"""'], {}), "(args['workspace_dir'], 'output',\n 'total-net-carbon-sequestration-between-2010-and-2020.tif')\n", (26856, 26953), False, 'import os\n'), ((27290, 27344), 'numpy.array', 'numpy.array', (['[[73.5, -28.698004]]'], {'dtype': 'numpy.float32'}), '([[73.5, -28.698004]], dtype=numpy.float32)\n', (27301, 27344), False, 'import numpy\n'), ((27380, 27489), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""total-net-carbon-sequestration-between-2020-and-2030.tif"""'], {}), "(args['workspace_dir'], 'output',\n 'total-net-carbon-sequestration-between-2020-and-2030.tif')\n", (27392, 27489), False, 'import os\n'), ((28068, 28155), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""total-net-carbon-sequestration.tif"""'], {}), "(args['workspace_dir'], 'output',\n 'total-net-carbon-sequestration.tif')\n", (28080, 28155), False, 'import os\n'), ((28463, 28522), 'numpy.array', 'numpy.array', (['[[-373.67245, 837.93445]]'], {'dtype': 'numpy.float32'}), '([[-373.67245, 837.93445]], dtype=numpy.float32)\n', (28474, 28522), False, 'import numpy\n'), ((28559, 28637), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""net-present-value-at-2030.tif"""'], {}), "(args['workspace_dir'], 'output', 'net-present-value-at-2030.tif')\n", (28571, 28637), False, 'import os\n'), ((30933, 30978), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""workspace"""'], {}), "(self.workspace_dir, 'workspace')\n", (30945, 30978), False, 'import os\n'), ((31006, 31092), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon._extract_snapshots_from_table', 'coastal_blue_carbon._extract_snapshots_from_table', (["args['landcover_snapshot_csv']"], {}), "(args[\n 'landcover_snapshot_csv'])\n", (31055, 31092), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((31639, 31672), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon.execute', 'coastal_blue_carbon.execute', (['args'], {}), '(args)\n', (31666, 31672), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((31757, 31804), 'numpy.array', 'numpy.array', (['[[83.5, 0.0]]'], {'dtype': 'numpy.float32'}), '([[83.5, 0.0]], dtype=numpy.float32)\n', (31768, 31804), False, 'import numpy\n'), ((31839, 31948), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""total-net-carbon-sequestration-between-2000-and-2010.tif"""'], {}), "(args['workspace_dir'], 'output',\n 'total-net-carbon-sequestration-between-2000-and-2010.tif')\n", (31851, 31948), False, 'import os\n'), ((32453, 32501), 'numpy.array', 'numpy.array', (['[[835.0, 0.0]]'], {'dtype': 'numpy.float32'}), '([[835.0, 0.0]], dtype=numpy.float32)\n', (32464, 32501), False, 'import numpy\n'), ((32536, 32614), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""net-present-value-at-2010.tif"""'], {}), "(args['workspace_dir'], 'output', 'net-present-value-at-2010.tif')\n", (32548, 32614), False, 'import os\n'), ((33156, 33190), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon.validate', 'coastal_blue_carbon.validate', (['args'], {}), '(args)\n', (33184, 33190), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((33377, 33431), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""invalid_raster.tif"""'], {}), "(self.workspace_dir, 'invalid_raster.tif')\n", (33389, 33431), False, 'import os\n'), ((33646, 33732), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon._extract_snapshots_from_table', 'coastal_blue_carbon._extract_snapshots_from_table', (["args['landcover_snapshot_csv']"], {}), "(args[\n 'landcover_snapshot_csv'])\n", (33695, 33732), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((34265, 34299), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon.validate', 'coastal_blue_carbon.validate', (['args'], {}), '(args)\n', (34293, 34299), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((34826, 34848), 'osgeo.osr.SpatialReference', 'osr.SpatialReference', ([], {}), '()\n', (34846, 34848), False, 'from osgeo import gdal, osr\n'), ((34978, 35039), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""disturbance_magnitude.tif"""'], {}), "(self.workspace_dir, 'disturbance_magnitude.tif')\n", (34990, 35039), False, 'import os\n'), ((35092, 35154), 'numpy.array', 'numpy.array', (['[[0.5, float32_nodata, 0.0]]'], {'dtype': 'numpy.float32'}), '([[0.5, float32_nodata, 0.0]], dtype=numpy.float32)\n', (35103, 35154), False, 'import numpy\n'), ((35176, 35314), 'pygeoprocessing.numpy_array_to_raster', 'pygeoprocessing.numpy_array_to_raster', (['disturbance_magnitude_matrix', 'float32_nodata', '(2, -2)', '(2, -2)', 'wkt', 'disturbance_magnitude_path'], {}), '(disturbance_magnitude_matrix,\n float32_nodata, (2, -2), (2, -2), wkt, disturbance_magnitude_path)\n', (35213, 35314), False, 'import pygeoprocessing\n'), ((35359, 35405), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""stocks.tif"""'], {}), "(self.workspace_dir, 'stocks.tif')\n", (35371, 35405), False, 'import os\n'), ((35443, 35491), 'numpy.array', 'numpy.array', (['[[10, -1, 10]]'], {'dtype': 'numpy.float32'}), '([[10, -1, 10]], dtype=numpy.float32)\n', (35454, 35491), False, 'import numpy\n'), ((35513, 35609), 'pygeoprocessing.numpy_array_to_raster', 'pygeoprocessing.numpy_array_to_raster', (['stocks_matrix', '(-1)', '(2, -2)', '(2, -2)', 'wkt', 'stocks_path'], {}), '(stocks_matrix, -1, (2, -2), (2, -2),\n wkt, stocks_path)\n', (35550, 35609), False, 'import pygeoprocessing\n'), ((35683, 35741), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""disturbance_volume.tif"""'], {}), "(self.workspace_dir, 'disturbance_volume.tif')\n", (35695, 35741), False, 'import os\n'), ((35792, 35851), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""year_of_disturbance.tif"""'], {}), "(self.workspace_dir, 'year_of_disturbance.tif')\n", (35804, 35851), False, 'import os\n'), ((35874, 36040), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon._track_disturbance', 'coastal_blue_carbon._track_disturbance', (['disturbance_magnitude_path', 'stocks_path', 'None', 'None', 'current_year', 'target_disturbance_path', 'target_year_of_disturbance'], {}), '(disturbance_magnitude_path,\n stocks_path, None, None, current_year, target_disturbance_path,\n target_year_of_disturbance)\n', (35912, 36040), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((37170, 37192), 'osgeo.osr.SpatialReference', 'osr.SpatialReference', ([], {}), '()\n', (37190, 37192), False, 'from osgeo import gdal, osr\n'), ((37322, 37383), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""disturbance_magnitude.tif"""'], {}), "(self.workspace_dir, 'disturbance_magnitude.tif')\n", (37334, 37383), False, 'import os\n'), ((37436, 37498), 'numpy.array', 'numpy.array', (['[[0.5, float32_nodata, 0.0]]'], {'dtype': 'numpy.float32'}), '([[0.5, float32_nodata, 0.0]], dtype=numpy.float32)\n', (37447, 37498), False, 'import numpy\n'), ((37520, 37658), 'pygeoprocessing.numpy_array_to_raster', 'pygeoprocessing.numpy_array_to_raster', (['disturbance_magnitude_matrix', 'float32_nodata', '(2, -2)', '(2, -2)', 'wkt', 'disturbance_magnitude_path'], {}), '(disturbance_magnitude_matrix,\n float32_nodata, (2, -2), (2, -2), wkt, disturbance_magnitude_path)\n', (37557, 37658), False, 'import pygeoprocessing\n'), ((37703, 37749), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""stocks.tif"""'], {}), "(self.workspace_dir, 'stocks.tif')\n", (37715, 37749), False, 'import os\n'), ((37787, 37835), 'numpy.array', 'numpy.array', (['[[10, -1, 10]]'], {'dtype': 'numpy.float32'}), '([[10, -1, 10]], dtype=numpy.float32)\n', (37798, 37835), False, 'import numpy\n'), ((37857, 37953), 'pygeoprocessing.numpy_array_to_raster', 'pygeoprocessing.numpy_array_to_raster', (['stocks_matrix', '(-1)', '(2, -2)', '(2, -2)', 'wkt', 'stocks_path'], {}), '(stocks_matrix, -1, (2, -2), (2, -2),\n wkt, stocks_path)\n', (37894, 37953), False, 'import pygeoprocessing\n'), ((38004, 38065), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""prior_disturbance_vol.tif"""'], {}), "(self.workspace_dir, 'prior_disturbance_vol.tif')\n", (38016, 38065), False, 'import os\n'), ((38118, 38174), 'numpy.array', 'numpy.array', (['[[700, float32_nodata, 300]]', 'numpy.float32'], {}), '([[700, float32_nodata, 300]], numpy.float32)\n', (38129, 38174), False, 'import numpy\n'), ((38196, 38337), 'pygeoprocessing.numpy_array_to_raster', 'pygeoprocessing.numpy_array_to_raster', (['prior_disturbance_vol_matrix', 'float32_nodata', '(2, -2)', '(2, -2)', 'wkt', 'prior_disturbance_volume_path'], {}), '(prior_disturbance_vol_matrix,\n float32_nodata, (2, -2), (2, -2), wkt, prior_disturbance_volume_path)\n', (38233, 38337), False, 'import pygeoprocessing\n'), ((38398, 38461), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""prior_disturbance_years.tif"""'], {}), "(self.workspace_dir, 'prior_disturbance_years.tif')\n", (38410, 38461), False, 'import os\n'), ((38515, 38571), 'numpy.array', 'numpy.array', (['[[2000, uint16_nodata, 1990]]', 'numpy.uint16'], {}), '([[2000, uint16_nodata, 1990]], numpy.uint16)\n', (38526, 38571), False, 'import numpy\n'), ((38593, 38732), 'pygeoprocessing.numpy_array_to_raster', 'pygeoprocessing.numpy_array_to_raster', (['prior_year_disturbance_matrix', 'uint16_nodata', '(2, -2)', '(2, -2)', 'wkt', 'prior_year_disturbance_path'], {}), '(prior_year_disturbance_matrix,\n uint16_nodata, (2, -2), (2, -2), wkt, prior_year_disturbance_path)\n', (38630, 38732), False, 'import pygeoprocessing\n'), ((38789, 38847), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""disturbance_volume.tif"""'], {}), "(self.workspace_dir, 'disturbance_volume.tif')\n", (38801, 38847), False, 'import os\n'), ((38898, 38957), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""year_of_disturbance.tif"""'], {}), "(self.workspace_dir, 'year_of_disturbance.tif')\n", (38910, 38957), False, 'import os\n'), ((39008, 39222), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon._track_disturbance', 'coastal_blue_carbon._track_disturbance', (['disturbance_magnitude_path', 'stocks_path', 'prior_disturbance_volume_path', 'prior_year_disturbance_path', 'current_year', 'target_disturbance_path', 'target_year_of_disturbance'], {}), '(disturbance_magnitude_path,\n stocks_path, prior_disturbance_volume_path, prior_year_disturbance_path,\n current_year, target_disturbance_path, target_year_of_disturbance)\n', (39046, 39222), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((1124, 1169), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""workspace"""'], {}), "(self.workspace_dir, 'workspace')\n", (1136, 1169), False, 'import os\n'), ((1249, 1307), 'os.path.join', 'os.path.join', (['REGRESSION_DATA', '"""inputs"""', '"""lulc_lookup.csv"""'], {}), "(REGRESSION_DATA, 'inputs', 'lulc_lookup.csv')\n", (1261, 1307), False, 'import os\n'), ((4471, 4574), 'natcap.invest.coastal_blue_carbon.preprocessor._create_transition_table', 'preprocessor._create_transition_table', (['landcover_table', '[filename_a, filename_b]', 'target_table_path'], {}), '(landcover_table, [filename_a,\n filename_b], target_table_path)\n', (4508, 4574), False, 'from natcap.invest.coastal_blue_carbon import preprocessor\n'), ((9043, 9130), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon._read_transition_matrix', 'coastal_blue_carbon._read_transition_matrix', (['transition_csv_path', 'biophysical_table'], {}), '(transition_csv_path,\n biophysical_table)\n', (9086, 9130), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((9802, 9889), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon._read_transition_matrix', 'coastal_blue_carbon._read_transition_matrix', (['transition_csv_path', 'biophysical_table'], {}), '(transition_csv_path,\n biophysical_table)\n', (9845, 9889), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((14691, 14740), 'numpy.array', 'numpy.array', (['[[5, 15, 12, 15]]'], {'dtype': 'numpy.uint8'}), '([[5, 15, 12, 15]], dtype=numpy.uint8)\n', (14702, 14740), False, 'import numpy\n'), ((14922, 14968), 'numpy.array', 'numpy.array', (['[[3, 4, 5, 5]]'], {'dtype': 'numpy.uint8'}), '([[3, 4, 5, 5]], dtype=numpy.uint8)\n', (14933, 14968), False, 'import numpy\n'), ((15285, 15309), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['target_path'], {}), '(target_path)\n', (15296, 15309), False, 'from osgeo import gdal, osr\n'), ((19295, 19338), 'os.path.join', 'os.path.join', (['target_dir', '"""price_table.csv"""'], {}), "(target_dir, 'price_table.csv')\n", (19307, 19338), False, 'import os\n'), ((20462, 20495), 'natcap.invest.coastal_blue_carbon.coastal_blue_carbon.execute', 'coastal_blue_carbon.execute', (['args'], {}), '(args)\n', (20489, 20495), False, 'from natcap.invest.coastal_blue_carbon import coastal_blue_carbon\n'), ((21543, 21567), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (21554, 21567), False, 'from osgeo import gdal, osr\n'), ((22067, 22091), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (22078, 22091), False, 'from osgeo import gdal, osr\n'), ((22662, 22686), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (22673, 22686), False, 'from osgeo import gdal, osr\n'), ((23136, 23160), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (23147, 23160), False, 'from osgeo import gdal, osr\n'), ((24909, 24933), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (24920, 24933), False, 'from osgeo import gdal, osr\n'), ((25547, 25571), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (25558, 25571), False, 'from osgeo import gdal, osr\n'), ((26506, 26530), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (26517, 26530), False, 'from osgeo import gdal, osr\n'), ((27030, 27054), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (27041, 27054), False, 'from osgeo import gdal, osr\n'), ((27566, 27590), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (27577, 27590), False, 'from osgeo import gdal, osr\n'), ((28211, 28235), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (28222, 28235), False, 'from osgeo import gdal, osr\n'), ((28685, 28709), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (28696, 28709), False, 'from osgeo import gdal, osr\n'), ((29137, 29216), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""output"""', '"""carbon-emissions-between-*.tif"""'], {}), "(args['workspace_dir'], 'output', 'carbon-emissions-between-*.tif')\n", (29149, 29216), False, 'import os\n'), ((29775, 29821), 'numpy.array', 'numpy.array', (['[[0.0, 0.0]]'], {'dtype': 'numpy.float32'}), '([[0.0, 0.0]], dtype=numpy.float32)\n', (29786, 29821), False, 'import numpy\n'), ((30465, 30554), 'numpy.testing.assert_allclose', 'numpy.testing.assert_allclose', (['emissions_in_period', 'summed_emissions_over_time_period'], {}), '(emissions_in_period,\n summed_emissions_over_time_period)\n', (30494, 30554), False, 'import numpy\n'), ((32024, 32048), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (32035, 32048), False, 'from osgeo import gdal, osr\n'), ((32662, 32686), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['raster_path'], {}), '(raster_path)\n', (32673, 32686), False, 'from osgeo import gdal, osr\n'), ((36192, 36254), 'numpy.array', 'numpy.array', (['[[5.0, float32_nodata, 0.0]]'], {'dtype': 'numpy.float32'}), '([[5.0, float32_nodata, 0.0]], dtype=numpy.float32)\n', (36203, 36254), False, 'import numpy\n'), ((36293, 36329), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['target_disturbance_path'], {}), '(target_disturbance_path)\n', (36304, 36329), False, 'from osgeo import gdal, osr\n'), ((36615, 36686), 'numpy.array', 'numpy.array', (['[[2010, uint16_nodata, uint16_nodata]]'], {'dtype': 'numpy.uint16'}), '([[2010, uint16_nodata, uint16_nodata]], dtype=numpy.uint16)\n', (36626, 36686), False, 'import numpy\n'), ((36725, 36764), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['target_year_of_disturbance'], {}), '(target_year_of_disturbance)\n', (36736, 36764), False, 'from osgeo import gdal, osr\n'), ((39313, 39375), 'numpy.array', 'numpy.array', (['[[5.0, float32_nodata, 300]]'], {'dtype': 'numpy.float32'}), '([[5.0, float32_nodata, 300]], dtype=numpy.float32)\n', (39324, 39375), False, 'import numpy\n'), ((39414, 39450), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['target_disturbance_path'], {}), '(target_disturbance_path)\n', (39425, 39450), False, 'from osgeo import gdal, osr\n'), ((39670, 39732), 'numpy.array', 'numpy.array', (['[[2010, uint16_nodata, 1990]]'], {'dtype': 'numpy.uint16'}), '([[2010, uint16_nodata, 1990]], dtype=numpy.uint16)\n', (39681, 39732), False, 'import numpy\n'), ((39771, 39810), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['target_year_of_disturbance'], {}), '(target_year_of_disturbance)\n', (39782, 39810), False, 'from osgeo import gdal, osr\n'), ((6461, 6520), 'os.path.join', 'os.path.join', (['self.workspace_dir', 'f"""{transition_year}.tif)"""'], {}), "(self.workspace_dir, f'{transition_year}.tif)')\n", (6473, 6520), False, 'import os\n'), ((7008, 7057), 'os.path.join', 'os.path.join', (['self.workspace_dir', '"""some_path.tif"""'], {}), "(self.workspace_dir, 'some_path.tif')\n", (7020, 7057), False, 'import os\n'), ((15407, 15461), 'numpy.array', 'numpy.array', (['[[8, 4, 12, nodata]]'], {'dtype': 'numpy.float32'}), '([[8, 4, 12, nodata]], dtype=numpy.float32)\n', (15418, 15461), False, 'import numpy\n'), ((29290, 29324), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['emissions_raster_path'], {}), '(emissions_raster_path)\n', (29301, 29324), False, 'from osgeo import gdal, osr\n'), ((1886, 1912), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (1902, 1912), False, 'import os\n'), ((29566, 29605), 'os.path.basename', 'os.path.basename', (['emissions_raster_path'], {}), '(emissions_raster_path)\n', (29582, 29605), False, 'import os\n'), ((29987, 30074), 'os.path.join', 'os.path.join', (["args['workspace_dir']", '"""intermediate"""', 'f"""emissions-{pool}-{year}.tif"""'], {}), "(args['workspace_dir'], 'intermediate',\n f'emissions-{pool}-{year}.tif')\n", (29999, 30074), False, 'import os\n'), ((2384, 2418), 'pprint.pformat', 'pprint.pformat', (['non_suffixed_files'], {}), '(non_suffixed_files)\n', (2398, 2418), False, 'import pprint\n'), ((2552, 2625), 'os.path.join', 'os.path.join', (['outputs_dir', '"""carbon_biophysical_table_template_150225.csv"""'], {}), "(outputs_dir, 'carbon_biophysical_table_template_150225.csv')\n", (2564, 2625), False, 'import os\n'), ((30178, 30214), 'osgeo.gdal.OpenEx', 'gdal.OpenEx', (['yearly_emissions_raster'], {}), '(yearly_emissions_raster)\n', (30189, 30214), False, 'from osgeo import gdal, osr\n'), ((2063, 2095), 'os.path.join', 'os.path.join', (['root_dir', 'filename'], {}), '(root_dir, filename)\n', (2075, 2095), False, 'import os\n')] |
import pandas as pd
import numpy as np
from scipy.stats import hmean, gmean, entropy
from sklearn.decomposition import PCA
# Macros
METRICS = ['precision', 'recall', 'f1-score', 'auc', 'kappa']
PCA_THRESH = 0.95
class StatsMetrics():
def __init__(self):
pass
def _get_prop_pca(self, df: pd.DataFrame) -> dict:
n = df.shape[0]
pca = PCA(n_components=PCA_THRESH)
principal_components = pca.fit_transform(df.select_dtypes(include=np.number))
return {'prop_pca': principal_components.shape[1] / n}
def _get_sparsity(self, df: pd.DataFrame) -> dict:
n = df.shape[0]
uniqueness_ratio = (df.nunique()/n).to_dict()
sparsity = (1 - df.fillna(0).astype(bool).sum(axis=0) / n).to_dict()
uniqueness_ratio = {k + '_uniqueness_ratio': v for k, v in uniqueness_ratio.items()}
sparsity = {k + '_sparsity': v for k, v in sparsity.items()}
return {**uniqueness_ratio, **sparsity}
def _get_nr_outliers_iqr(self, df: pd.DataFrame) -> dict:
Q1 = df.quantile(0.25)
Q3 = df.quantile(0.75)
IQR = Q3 - Q1
nr_out = ((df < (Q1 - 1.5 * IQR)) | (df > (Q3 + 1.5 * IQR))).sum().to_dict()
iqr_dict = IQR.to_dict()
nr_out = {k + '_nr_outliers': v for k, v in nr_out.items()}
iqr_dict = {k + '_iqr': v for k, v in iqr_dict.items()}
return {**nr_out, **iqr_dict}
def _get_kurt_skew(self, df: pd.DataFrame) -> dict:
skew = df.skew(axis=0).to_dict()
kurt = df.kurt(axis=0).to_dict()
return {**skew, **kurt}
def _get_gmean_hmean_entropy(self, df: pd.DataFrame) -> dict:
metrics = {}
for col in df.columns:
metrics[f'{col}_gmean'] = gmean(df[col])
metrics[f'{col}_hmean'] = hmean(df[col])
metrics[f'{col}_entropy'] = entropy(df[col])
metrics[f'{col}_median'] = df[col].median()
return metrics
def _get_statistical_metrics(self, df: pd.DataFrame) -> dict:
metrics = df.describe().reset_index()
metrics = metrics[metrics['index'].isin(['mean', 'max', 'min', 'std'])]
metrics = pd.melt(metrics, id_vars=['index'])
metrics['variable'] = metrics['variable'] + '_' + metrics['index']
metrics = metrics.drop('index', axis=1).set_index('variable').T
return metrics.to_dict(orient='records')[0]
def _get_correlation(self, df: pd.DataFrame) -> dict:
corr = df.corr()
keep = np.logical_not(np.triu(np.ones(corr.shape))).astype('bool').reshape(corr.size)
corr = pd.melt(corr.reset_index(), id_vars=['index'])[keep]
corr['variable'] = 'correlation_' + corr['variable'] + '_' + corr['index']
corr = corr.drop('index', axis=1).set_index('variable').T
return corr.to_dict(orient='records')[0]
def fit(self, *args):
return self
def evaluate(self, df: pd.DataFrame) -> dict:
# Filter numeric variables
df = df.select_dtypes(include=np.number)
stats = self._get_statistical_metrics(df)
corr = self._get_correlation(df)
means = self._get_gmean_hmean_entropy(df)
outliers = self._get_nr_outliers_iqr(df)
sparsity = self._get_sparsity(df)
pca = self._get_prop_pca(df)
return {**stats, **corr, **means, **outliers, **sparsity, **pca} | [
"scipy.stats.gmean",
"scipy.stats.entropy",
"numpy.ones",
"sklearn.decomposition.PCA",
"pandas.melt",
"scipy.stats.hmean"
] | [((368, 396), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'PCA_THRESH'}), '(n_components=PCA_THRESH)\n', (371, 396), False, 'from sklearn.decomposition import PCA\n'), ((2146, 2181), 'pandas.melt', 'pd.melt', (['metrics'], {'id_vars': "['index']"}), "(metrics, id_vars=['index'])\n", (2153, 2181), True, 'import pandas as pd\n'), ((1731, 1745), 'scipy.stats.gmean', 'gmean', (['df[col]'], {}), '(df[col])\n', (1736, 1745), False, 'from scipy.stats import hmean, gmean, entropy\n'), ((1784, 1798), 'scipy.stats.hmean', 'hmean', (['df[col]'], {}), '(df[col])\n', (1789, 1798), False, 'from scipy.stats import hmean, gmean, entropy\n'), ((1839, 1855), 'scipy.stats.entropy', 'entropy', (['df[col]'], {}), '(df[col])\n', (1846, 1855), False, 'from scipy.stats import hmean, gmean, entropy\n'), ((2503, 2522), 'numpy.ones', 'np.ones', (['corr.shape'], {}), '(corr.shape)\n', (2510, 2522), True, 'import numpy as np\n')] |
import os
import numpy as np
import torch
from functools import partial
from torchnet.transform import compose
from torchnet.dataset import ListDataset, TransformDataset
from fewshots.data.base import convert_dict, CudaTransform, EpisodicBatchSampler
from fewshots.data.setup import setup_images
from fewshots.data.cache import Cache
from fewshots.utils import filter_opt
from fewshots.data.SetupEpisode import SetupEpisode
root_dir = ''
def extract_episode(setup_episode, augm_opt, d):
# data: N x C x H x W
n_max_examples = d[0]['data'].size(0)
n_way, n_shot, n_query = setup_episode.get_current_setup()
example_inds = torch.randperm(n_max_examples)[:(n_shot + n_query)]
support_inds = example_inds[:n_shot]
query_inds = example_inds[n_shot:]
xs_list = [d[i]['data'][support_inds] for i in range(augm_opt['n_augment'])]
# concatenate as shots into xs
xs = torch.cat(xs_list, dim=0)
# extract queries from a single cache entry
xq = d[np.random.randint(augm_opt['n_augment'])]['data'][query_inds]
out_dict = {'class': d[0]['class'], 'xs': xs, 'xq': xq, 'n_way': n_way, 'n_shot': n_shot, 'n_query': n_query}
return out_dict
def load_data(opt, splits):
global root_dir
root_dir = opt['data.root_dir']
augm_opt = filter_opt(opt, 'augm')
dataset = opt['data.dataset']
split_dir = os.path.join(opt['data.root_dir'], opt['data.dataset'], 'splits', opt['data.split'])
ret = {}
# cache = {}
cache = Cache()
for split in splits:
if split in ['val1', 'val5', 'test']:
n_way = opt['data.test_way']
else:
n_way = opt['data.way']
if split in ['train', 'trainval']:
# random shots
SE = SetupEpisode(batch_size=opt['data.batch_size'], shot_max=opt['data.shot_max'],
fixed_shot=opt['data.shot'], way_min=opt['data.way_min'], fixed_way=n_way)
elif split == 'val1':
SE = SetupEpisode(batch_size=opt['data.batch_size'], shot_max=opt['data.shot_max'], fixed_shot=1,
way_min=opt['data.way_min'], fixed_way=n_way)
elif split == 'val5':
SE = SetupEpisode(batch_size=opt['data.batch_size'], shot_max=opt['data.shot_max'], fixed_shot=5,
way_min=opt['data.way_min'], fixed_way=n_way)
else:
SE = SetupEpisode(batch_size=opt['data.batch_size'], shot_max=opt['data.shot_max'],
fixed_shot=opt['data.test_shot'], way_min=opt['data.way_min'], fixed_way=n_way)
if split in ['val1', 'val5', 'test']:
n_episodes = opt['data.test_episodes']
else:
n_episodes = opt['data.train_episodes']
transforms = [partial(convert_dict, 'class'),
partial(load_class_images, split, dataset, cache, augm_opt),
partial(extract_episode, SE, augm_opt)]
if opt['data.cuda']:
transforms.append(CudaTransform())
transforms = compose(transforms)
class_names = []
split_file = 'val.txt' if split in ['val1', 'val5'] else "{:s}.txt".format(split)
with open(os.path.join(split_dir, split_file), 'r') as f:
for class_name in f.readlines():
class_names.append(class_name.rstrip('\n'))
ds = TransformDataset(ListDataset(class_names), transforms)
sampler = EpisodicBatchSampler(SE, len(ds), n_episodes)
# use num_workers=0, otherwise may receive duplicate episodes
ret[split] = torch.utils.data.DataLoader(ds, batch_sampler=sampler, num_workers=0)
return ret
def load_class_images(split, dataset, cache, augm_opt, d):
if d['class'] in cache.data.keys():
if len(cache.data[d['class']]) < augm_opt['cache_size']:
init_entry = False
setup_images(split, d, cache, dataset, init_entry, root_dir, augm_opt)
else:
init_entry = True
setup_images(split, d, cache, dataset, init_entry, root_dir, augm_opt)
cache_len = len(cache.data[d['class']])
# if cache does not enough shots yet, repeat
if cache_len < augm_opt['n_augment']:
rand_ids = np.random.choice(cache_len, size=augm_opt['n_augment'], replace=True)
else:
rand_ids = np.random.choice(cache_len, size=augm_opt['n_augment'], replace=False)
out_dicts = [{'class': d['class'], 'data': cache.data[d['class']][rand_ids[i]]} for i in
range(augm_opt['n_augment'])]
return out_dicts
| [
"functools.partial",
"fewshots.data.SetupEpisode.SetupEpisode",
"torchnet.dataset.ListDataset",
"fewshots.data.cache.Cache",
"torchnet.transform.compose",
"torch.utils.data.DataLoader",
"fewshots.data.base.CudaTransform",
"torch.cat",
"numpy.random.randint",
"torch.randperm",
"fewshots.utils.fil... | [((902, 927), 'torch.cat', 'torch.cat', (['xs_list'], {'dim': '(0)'}), '(xs_list, dim=0)\n', (911, 927), False, 'import torch\n'), ((1284, 1307), 'fewshots.utils.filter_opt', 'filter_opt', (['opt', '"""augm"""'], {}), "(opt, 'augm')\n", (1294, 1307), False, 'from fewshots.utils import filter_opt\n'), ((1358, 1447), 'os.path.join', 'os.path.join', (["opt['data.root_dir']", "opt['data.dataset']", '"""splits"""', "opt['data.split']"], {}), "(opt['data.root_dir'], opt['data.dataset'], 'splits', opt[\n 'data.split'])\n", (1370, 1447), False, 'import os\n'), ((1486, 1493), 'fewshots.data.cache.Cache', 'Cache', ([], {}), '()\n', (1491, 1493), False, 'from fewshots.data.cache import Cache\n'), ((643, 673), 'torch.randperm', 'torch.randperm', (['n_max_examples'], {}), '(n_max_examples)\n', (657, 673), False, 'import torch\n'), ((3044, 3063), 'torchnet.transform.compose', 'compose', (['transforms'], {}), '(transforms)\n', (3051, 3063), False, 'from torchnet.transform import compose\n'), ((3576, 3645), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['ds'], {'batch_sampler': 'sampler', 'num_workers': '(0)'}), '(ds, batch_sampler=sampler, num_workers=0)\n', (3603, 3645), False, 'import torch\n'), ((3986, 4056), 'fewshots.data.setup.setup_images', 'setup_images', (['split', 'd', 'cache', 'dataset', 'init_entry', 'root_dir', 'augm_opt'], {}), '(split, d, cache, dataset, init_entry, root_dir, augm_opt)\n', (3998, 4056), False, 'from fewshots.data.setup import setup_images\n'), ((4213, 4282), 'numpy.random.choice', 'np.random.choice', (['cache_len'], {'size': "augm_opt['n_augment']", 'replace': '(True)'}), "(cache_len, size=augm_opt['n_augment'], replace=True)\n", (4229, 4282), True, 'import numpy as np\n'), ((4312, 4382), 'numpy.random.choice', 'np.random.choice', (['cache_len'], {'size': "augm_opt['n_augment']", 'replace': '(False)'}), "(cache_len, size=augm_opt['n_augment'], replace=False)\n", (4328, 4382), True, 'import numpy as np\n'), ((1745, 1908), 'fewshots.data.SetupEpisode.SetupEpisode', 'SetupEpisode', ([], {'batch_size': "opt['data.batch_size']", 'shot_max': "opt['data.shot_max']", 'fixed_shot': "opt['data.shot']", 'way_min': "opt['data.way_min']", 'fixed_way': 'n_way'}), "(batch_size=opt['data.batch_size'], shot_max=opt[\n 'data.shot_max'], fixed_shot=opt['data.shot'], way_min=opt[\n 'data.way_min'], fixed_way=n_way)\n", (1757, 1908), False, 'from fewshots.data.SetupEpisode import SetupEpisode\n'), ((2768, 2798), 'functools.partial', 'partial', (['convert_dict', '"""class"""'], {}), "(convert_dict, 'class')\n", (2775, 2798), False, 'from functools import partial\n'), ((2822, 2881), 'functools.partial', 'partial', (['load_class_images', 'split', 'dataset', 'cache', 'augm_opt'], {}), '(load_class_images, split, dataset, cache, augm_opt)\n', (2829, 2881), False, 'from functools import partial\n'), ((2905, 2943), 'functools.partial', 'partial', (['extract_episode', 'SE', 'augm_opt'], {}), '(extract_episode, SE, augm_opt)\n', (2912, 2943), False, 'from functools import partial\n'), ((3381, 3405), 'torchnet.dataset.ListDataset', 'ListDataset', (['class_names'], {}), '(class_names)\n', (3392, 3405), False, 'from torchnet.dataset import ListDataset, TransformDataset\n'), ((3871, 3941), 'fewshots.data.setup.setup_images', 'setup_images', (['split', 'd', 'cache', 'dataset', 'init_entry', 'root_dir', 'augm_opt'], {}), '(split, d, cache, dataset, init_entry, root_dir, augm_opt)\n', (3883, 3941), False, 'from fewshots.data.setup import setup_images\n'), ((987, 1027), 'numpy.random.randint', 'np.random.randint', (["augm_opt['n_augment']"], {}), "(augm_opt['n_augment'])\n", (1004, 1027), True, 'import numpy as np\n'), ((1976, 2124), 'fewshots.data.SetupEpisode.SetupEpisode', 'SetupEpisode', ([], {'batch_size': "opt['data.batch_size']", 'shot_max': "opt['data.shot_max']", 'fixed_shot': '(1)', 'way_min': "opt['data.way_min']", 'fixed_way': 'n_way'}), "(batch_size=opt['data.batch_size'], shot_max=opt[\n 'data.shot_max'], fixed_shot=1, way_min=opt['data.way_min'], fixed_way=\n n_way)\n", (1988, 2124), False, 'from fewshots.data.SetupEpisode import SetupEpisode\n'), ((3005, 3020), 'fewshots.data.base.CudaTransform', 'CudaTransform', ([], {}), '()\n', (3018, 3020), False, 'from fewshots.data.base import convert_dict, CudaTransform, EpisodicBatchSampler\n'), ((3198, 3233), 'os.path.join', 'os.path.join', (['split_dir', 'split_file'], {}), '(split_dir, split_file)\n', (3210, 3233), False, 'import os\n'), ((2192, 2340), 'fewshots.data.SetupEpisode.SetupEpisode', 'SetupEpisode', ([], {'batch_size': "opt['data.batch_size']", 'shot_max': "opt['data.shot_max']", 'fixed_shot': '(5)', 'way_min': "opt['data.way_min']", 'fixed_way': 'n_way'}), "(batch_size=opt['data.batch_size'], shot_max=opt[\n 'data.shot_max'], fixed_shot=5, way_min=opt['data.way_min'], fixed_way=\n n_way)\n", (2204, 2340), False, 'from fewshots.data.SetupEpisode import SetupEpisode\n'), ((2392, 2560), 'fewshots.data.SetupEpisode.SetupEpisode', 'SetupEpisode', ([], {'batch_size': "opt['data.batch_size']", 'shot_max': "opt['data.shot_max']", 'fixed_shot': "opt['data.test_shot']", 'way_min': "opt['data.way_min']", 'fixed_way': 'n_way'}), "(batch_size=opt['data.batch_size'], shot_max=opt[\n 'data.shot_max'], fixed_shot=opt['data.test_shot'], way_min=opt[\n 'data.way_min'], fixed_way=n_way)\n", (2404, 2560), False, 'from fewshots.data.SetupEpisode import SetupEpisode\n')] |
"""
NCL_polyg_8_lbar.py
===================
This script illustrates the following concepts:
- Drawing a scatter plot on a map
- Changing the marker color and size in a map plot
- Plotting station locations using markers
- Creating a custom color bar
- Adding text to a plot
- Generating dummy data using "random_uniform"
- Binning data
See following URLs to see the reproduced NCL plot & script:
- Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/polyg_8_lbar.ncl
- Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/polyg_8_lbar_lg.png
"""
###############################################################################
# Import packages:
import numpy as np
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
from matplotlib import colors, cm
from geocat.viz import util as gvutil
from geocat.viz import cmaps as gvcmap
###############################################################################
# Generate dummy data
npts = 100
random = np.random.default_rng(seed=1)
# Create random coordinates to position the markers
lat = random.uniform(low=25, high=50, size=npts)
lon = random.uniform(low=-125, high=-70, size=npts)
# Create random data which the color will be based off of
r = random.uniform(low=-1.2, high=35, size=npts)
###############################################################################
# Specify bins and sizes and create custom mappable based on NCV_jet colormap
bins = [0, 5, 10, 15, 20, 23, 26]
cmap = gvcmap.NCV_jet
# Create the boundaries for your data, this may be larger than bins to
# accomodate colors for data outside of the smallest and largest bins
boundaries = [-1.2, 0, 5, 10, 15, 20, 23, 26, 35]
norm = colors.BoundaryNorm(boundaries, cmap.N)
mappable = cm.ScalarMappable(norm=norm, cmap=cmap)
# Retreive the list of colors to use for the markers
marker_colors = mappable.to_rgba(boundaries)
# Increasing sizes for the markers in each bin, by using numpy.geomspace the
# size differences are more noticeable
sizes = np.geomspace(10, 250, len(boundaries))
###############################################################################
# Plot:
plt.figure(figsize=(9, 6))
projection = ccrs.PlateCarree()
ax = plt.axes(projection=projection)
ax.set_extent([-125, -70, 25, 50], crs=projection)
# Draw land
ax.add_feature(cfeature.LAND, color='silver', zorder=0)
ax.add_feature(cfeature.LAKES, color='white', zorder=0)
# Use geocat.viz.util convenience function to set axes tick values
gvutil.set_axes_limits_and_ticks(ax,
xticks=np.linspace(-120, -70, 6),
yticks=np.linspace(25, 50, 6))
# Use geocat.viz.util convenience function to make latitude and longitude tick
# labels
gvutil.add_lat_lon_ticklabels(ax)
# Use geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(ax,
x_minor_per_major=1,
y_minor_per_major=1,
labelsize=12)
# Remove ticks on the top and right sides of the plot
ax.tick_params(axis='both', which='both', top=False, right=False)
# Use geocat.viz.util convenience function to add titles
gvutil.set_titles_and_labels(
ax,
maintitlefontsize=16,
maintitle=
"Dummy station data colored and\nsized according to range of values")
# Plot markers with values less than first bin value
masked_lon = np.where(r < bins[0], lon, np.nan)
masked_lat = np.where(r < bins[0], lat, np.nan)
plt.scatter(masked_lon,
masked_lat,
s=sizes[0],
color=marker_colors[0],
zorder=1)
# Plot all other markers but those in the last bin
for x in range(1, len(bins)):
masked_lon = np.where(bins[x - 1] <= r, lon, np.nan)
masked_lon = np.where(r < bins[x], masked_lon, np.nan)
masked_lat = np.where(bins[x - 1] <= r, lat, np.nan)
masked_lat = np.where(r < bins[x], masked_lat, np.nan)
plt.scatter(masked_lon,
masked_lat,
s=sizes[x],
color=marker_colors[x],
zorder=1)
# Plot markers with values greater than or equal to last bin value
masked_lon = np.where(r >= bins[-1], lon, np.nan)
masked_lat = np.where(r >= bins[-1], lat, np.nan)
plt.scatter(masked_lon,
masked_lat,
s=sizes[-1],
color=marker_colors[-1],
zorder=1)
# Create colorbar
plt.colorbar(mappable=mappable,
ax=ax,
orientation='horizontal',
drawedges=True,
format='%.2f',
ticks=bins)
plt.show()
| [
"matplotlib.pyplot.show",
"geocat.viz.util.set_titles_and_labels",
"matplotlib.pyplot.axes",
"matplotlib.cm.ScalarMappable",
"matplotlib.colors.BoundaryNorm",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.colorbar",
"numpy.random.default_rng",
"matplotlib.pyplot.figure",
"geocat.viz.util.add_lat... | [((1051, 1080), 'numpy.random.default_rng', 'np.random.default_rng', ([], {'seed': '(1)'}), '(seed=1)\n', (1072, 1080), True, 'import numpy as np\n'), ((1757, 1796), 'matplotlib.colors.BoundaryNorm', 'colors.BoundaryNorm', (['boundaries', 'cmap.N'], {}), '(boundaries, cmap.N)\n', (1776, 1796), False, 'from matplotlib import colors, cm\n'), ((1808, 1847), 'matplotlib.cm.ScalarMappable', 'cm.ScalarMappable', ([], {'norm': 'norm', 'cmap': 'cmap'}), '(norm=norm, cmap=cmap)\n', (1825, 1847), False, 'from matplotlib import colors, cm\n'), ((2200, 2226), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 6)'}), '(figsize=(9, 6))\n', (2210, 2226), True, 'import matplotlib.pyplot as plt\n'), ((2240, 2258), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ([], {}), '()\n', (2256, 2258), True, 'import cartopy.crs as ccrs\n'), ((2264, 2295), 'matplotlib.pyplot.axes', 'plt.axes', ([], {'projection': 'projection'}), '(projection=projection)\n', (2272, 2295), True, 'import matplotlib.pyplot as plt\n'), ((2797, 2830), 'geocat.viz.util.add_lat_lon_ticklabels', 'gvutil.add_lat_lon_ticklabels', (['ax'], {}), '(ax)\n', (2826, 2830), True, 'from geocat.viz import util as gvutil\n'), ((2909, 3001), 'geocat.viz.util.add_major_minor_ticks', 'gvutil.add_major_minor_ticks', (['ax'], {'x_minor_per_major': '(1)', 'y_minor_per_major': '(1)', 'labelsize': '(12)'}), '(ax, x_minor_per_major=1, y_minor_per_major=1,\n labelsize=12)\n', (2937, 3001), True, 'from geocat.viz import util as gvutil\n'), ((3264, 3406), 'geocat.viz.util.set_titles_and_labels', 'gvutil.set_titles_and_labels', (['ax'], {'maintitlefontsize': '(16)', 'maintitle': '"""Dummy station data colored and\nsized according to range of values"""'}), '(ax, maintitlefontsize=16, maintitle=\n """Dummy station data colored and\nsized according to range of values""")\n', (3292, 3406), True, 'from geocat.viz import util as gvutil\n'), ((3484, 3518), 'numpy.where', 'np.where', (['(r < bins[0])', 'lon', 'np.nan'], {}), '(r < bins[0], lon, np.nan)\n', (3492, 3518), True, 'import numpy as np\n'), ((3532, 3566), 'numpy.where', 'np.where', (['(r < bins[0])', 'lat', 'np.nan'], {}), '(r < bins[0], lat, np.nan)\n', (3540, 3566), True, 'import numpy as np\n'), ((3567, 3652), 'matplotlib.pyplot.scatter', 'plt.scatter', (['masked_lon', 'masked_lat'], {'s': 'sizes[0]', 'color': 'marker_colors[0]', 'zorder': '(1)'}), '(masked_lon, masked_lat, s=sizes[0], color=marker_colors[0],\n zorder=1)\n', (3578, 3652), True, 'import matplotlib.pyplot as plt\n'), ((4242, 4278), 'numpy.where', 'np.where', (['(r >= bins[-1])', 'lon', 'np.nan'], {}), '(r >= bins[-1], lon, np.nan)\n', (4250, 4278), True, 'import numpy as np\n'), ((4292, 4328), 'numpy.where', 'np.where', (['(r >= bins[-1])', 'lat', 'np.nan'], {}), '(r >= bins[-1], lat, np.nan)\n', (4300, 4328), True, 'import numpy as np\n'), ((4329, 4416), 'matplotlib.pyplot.scatter', 'plt.scatter', (['masked_lon', 'masked_lat'], {'s': 'sizes[-1]', 'color': 'marker_colors[-1]', 'zorder': '(1)'}), '(masked_lon, masked_lat, s=sizes[-1], color=marker_colors[-1],\n zorder=1)\n', (4340, 4416), True, 'import matplotlib.pyplot as plt\n'), ((4480, 4592), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'mappable': 'mappable', 'ax': 'ax', 'orientation': '"""horizontal"""', 'drawedges': '(True)', 'format': '"""%.2f"""', 'ticks': 'bins'}), "(mappable=mappable, ax=ax, orientation='horizontal', drawedges=\n True, format='%.2f', ticks=bins)\n", (4492, 4592), True, 'import matplotlib.pyplot as plt\n'), ((4654, 4664), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4662, 4664), True, 'import matplotlib.pyplot as plt\n'), ((3796, 3835), 'numpy.where', 'np.where', (['(bins[x - 1] <= r)', 'lon', 'np.nan'], {}), '(bins[x - 1] <= r, lon, np.nan)\n', (3804, 3835), True, 'import numpy as np\n'), ((3853, 3894), 'numpy.where', 'np.where', (['(r < bins[x])', 'masked_lon', 'np.nan'], {}), '(r < bins[x], masked_lon, np.nan)\n', (3861, 3894), True, 'import numpy as np\n'), ((3912, 3951), 'numpy.where', 'np.where', (['(bins[x - 1] <= r)', 'lat', 'np.nan'], {}), '(bins[x - 1] <= r, lat, np.nan)\n', (3920, 3951), True, 'import numpy as np\n'), ((3969, 4010), 'numpy.where', 'np.where', (['(r < bins[x])', 'masked_lat', 'np.nan'], {}), '(r < bins[x], masked_lat, np.nan)\n', (3977, 4010), True, 'import numpy as np\n'), ((4015, 4100), 'matplotlib.pyplot.scatter', 'plt.scatter', (['masked_lon', 'masked_lat'], {'s': 'sizes[x]', 'color': 'marker_colors[x]', 'zorder': '(1)'}), '(masked_lon, masked_lat, s=sizes[x], color=marker_colors[x],\n zorder=1)\n', (4026, 4100), True, 'import matplotlib.pyplot as plt\n'), ((2617, 2642), 'numpy.linspace', 'np.linspace', (['(-120)', '(-70)', '(6)'], {}), '(-120, -70, 6)\n', (2628, 2642), True, 'import numpy as np\n'), ((2684, 2706), 'numpy.linspace', 'np.linspace', (['(25)', '(50)', '(6)'], {}), '(25, 50, 6)\n', (2695, 2706), True, 'import numpy as np\n')] |
# coding: utf-8
""" Astropy coordinate class for the Sagittarius coordinate system """
from __future__ import division, print_function
__author__ = "adrn <<EMAIL>>"
# Third-party
import numpy as np
from astropy.coordinates import frame_transform_graph
from astropy.coordinates.angles import rotation_matrix
import astropy.coordinates as coord
import astropy.units as u
__all__ = ["Orphan"]
class Orphan(coord.BaseCoordinateFrame):
"""
A Heliocentric spherical coordinate system defined by the orbit
of the Orphan stream, as described in
Newberg et al. 2010 (see: `<http://arxiv.org/abs/1001.0576>`_).
For more information about this class, see the Astropy documentation
on coordinate frames in :mod:`~astropy.coordinates`.
Parameters
----------
representation : :class:`~astropy.coordinates.BaseRepresentation` or None
A representation object or None to have no data (or use the other keywords)
Lambda : angle_like, optional, must be keyword
The longitude-like angle corresponding to Orphan's orbit.
Beta : angle_like, optional, must be keyword
The latitude-like angle corresponding to Orphan's orbit.
distance : :class:`~astropy.units.Quantity`, optional, must be keyword
The Distance for this object along the line-of-sight.
"""
default_representation = coord.SphericalRepresentation
frame_specific_representation_info = {
'spherical': [coord.RepresentationMapping('lon', 'Lambda'),
coord.RepresentationMapping('lat', 'Beta'),
coord.RepresentationMapping('distance', 'distance')],
'unitspherical': [coord.RepresentationMapping('lon', 'Lambda'),
coord.RepresentationMapping('lat', 'Beta')]
}
# Define the Euler angles
phi = np.radians(128.79)
theta = np.radians(54.39)
psi = np.radians(90.70)
# Generate the rotation matrix using the x-convention (see Goldstein)
D = rotation_matrix(phi, "z", unit=u.radian)
C = rotation_matrix(theta, "x", unit=u.radian)
B = rotation_matrix(psi, "z", unit=u.radian)
R = np.array(B.dot(C).dot(D))
@frame_transform_graph.transform(coord.StaticMatrixTransform, coord.Galactic, Orphan)
def galactic_to_orp():
""" Compute the transformation from Galactic spherical to
heliocentric Orphan coordinates.
"""
return R
# Oph to Galactic coordinates
@frame_transform_graph.transform(coord.StaticMatrixTransform, Orphan, coord.Galactic)
def oph_to_galactic():
""" Compute the transformation from heliocentric Orphan coordinates to
spherical Galactic.
"""
return galactic_to_orp().T
| [
"astropy.coordinates.frame_transform_graph.transform",
"numpy.radians",
"astropy.coordinates.angles.rotation_matrix",
"astropy.coordinates.RepresentationMapping"
] | [((1819, 1837), 'numpy.radians', 'np.radians', (['(128.79)'], {}), '(128.79)\n', (1829, 1837), True, 'import numpy as np\n'), ((1846, 1863), 'numpy.radians', 'np.radians', (['(54.39)'], {}), '(54.39)\n', (1856, 1863), True, 'import numpy as np\n'), ((1870, 1886), 'numpy.radians', 'np.radians', (['(90.7)'], {}), '(90.7)\n', (1880, 1886), True, 'import numpy as np\n'), ((1963, 2003), 'astropy.coordinates.angles.rotation_matrix', 'rotation_matrix', (['phi', '"""z"""'], {'unit': 'u.radian'}), "(phi, 'z', unit=u.radian)\n", (1978, 2003), False, 'from astropy.coordinates.angles import rotation_matrix\n'), ((2008, 2050), 'astropy.coordinates.angles.rotation_matrix', 'rotation_matrix', (['theta', '"""x"""'], {'unit': 'u.radian'}), "(theta, 'x', unit=u.radian)\n", (2023, 2050), False, 'from astropy.coordinates.angles import rotation_matrix\n'), ((2055, 2095), 'astropy.coordinates.angles.rotation_matrix', 'rotation_matrix', (['psi', '"""z"""'], {'unit': 'u.radian'}), "(psi, 'z', unit=u.radian)\n", (2070, 2095), False, 'from astropy.coordinates.angles import rotation_matrix\n'), ((2128, 2216), 'astropy.coordinates.frame_transform_graph.transform', 'frame_transform_graph.transform', (['coord.StaticMatrixTransform', 'coord.Galactic', 'Orphan'], {}), '(coord.StaticMatrixTransform, coord.Galactic,\n Orphan)\n', (2159, 2216), False, 'from astropy.coordinates import frame_transform_graph\n'), ((2392, 2481), 'astropy.coordinates.frame_transform_graph.transform', 'frame_transform_graph.transform', (['coord.StaticMatrixTransform', 'Orphan', 'coord.Galactic'], {}), '(coord.StaticMatrixTransform, Orphan, coord.\n Galactic)\n', (2423, 2481), False, 'from astropy.coordinates import frame_transform_graph\n'), ((1450, 1494), 'astropy.coordinates.RepresentationMapping', 'coord.RepresentationMapping', (['"""lon"""', '"""Lambda"""'], {}), "('lon', 'Lambda')\n", (1477, 1494), True, 'import astropy.coordinates as coord\n'), ((1518, 1560), 'astropy.coordinates.RepresentationMapping', 'coord.RepresentationMapping', (['"""lat"""', '"""Beta"""'], {}), "('lat', 'Beta')\n", (1545, 1560), True, 'import astropy.coordinates as coord\n'), ((1584, 1635), 'astropy.coordinates.RepresentationMapping', 'coord.RepresentationMapping', (['"""distance"""', '"""distance"""'], {}), "('distance', 'distance')\n", (1611, 1635), True, 'import astropy.coordinates as coord\n'), ((1664, 1708), 'astropy.coordinates.RepresentationMapping', 'coord.RepresentationMapping', (['"""lon"""', '"""Lambda"""'], {}), "('lon', 'Lambda')\n", (1691, 1708), True, 'import astropy.coordinates as coord\n'), ((1736, 1778), 'astropy.coordinates.RepresentationMapping', 'coord.RepresentationMapping', (['"""lat"""', '"""Beta"""'], {}), "('lat', 'Beta')\n", (1763, 1778), True, 'import astropy.coordinates as coord\n')] |
import numpy as np
from .base import Representation
from acousticsim.exceptions import AcousticSimError
from acousticsim.analysis.specgram import file_to_powerspec
class Spectrogram(Representation):
def __init__(self, file_path, min_freq, max_freq, win_len, time_step, data=None, attributes=None):
Representation.__init__(self,file_path, data=data, attributes=attributes)
self.min_freq = min_freq
self.max_freq = max_freq
self.win_len = win_len
self.time_step = time_step
if self.time_step is None:
steps = 100
self.time_step = self.duration / steps
self.pspec = {}
self.freqs = []
def powerspec(self):
times = sorted(self.pspec.keys())
ex = next(iter(self.pspec.values()))
try:
frame_len = len(ex)
except ValueError:
frame_len = 1
output = np.zeros((len(times),frame_len))
for i, t in enumerate(times):
output[i, :] = self.pspec[t]
return output
def process(self, algorithm='as', reset=False):
if algorithm not in ['as']:
raise AcousticSimError('Spectrogram algorithm must be one of: as')
if reset:
self.data = {}
if self.data:
raise AcousticSimError('Data already exists for this representation, use reset=True to generate new data.')
self.pspec = file_to_powerspec(self.file_path, self.win_len, self.time_step)
for k in self.pspec.keys():
nfft = (len(self.pspec[k])-1) * 2
self.data[k] = 10 * np.log10(self.pspec[k] + np.spacing(1))
self.freqs = (self.sr / nfft) * np.arange((nfft/2) + 1)
| [
"acousticsim.analysis.specgram.file_to_powerspec",
"numpy.arange",
"acousticsim.exceptions.AcousticSimError",
"numpy.spacing"
] | [((1418, 1481), 'acousticsim.analysis.specgram.file_to_powerspec', 'file_to_powerspec', (['self.file_path', 'self.win_len', 'self.time_step'], {}), '(self.file_path, self.win_len, self.time_step)\n', (1435, 1481), False, 'from acousticsim.analysis.specgram import file_to_powerspec\n'), ((1148, 1208), 'acousticsim.exceptions.AcousticSimError', 'AcousticSimError', (['"""Spectrogram algorithm must be one of: as"""'], {}), "('Spectrogram algorithm must be one of: as')\n", (1164, 1208), False, 'from acousticsim.exceptions import AcousticSimError\n'), ((1294, 1405), 'acousticsim.exceptions.AcousticSimError', 'AcousticSimError', (['"""Data already exists for this representation, use reset=True to generate new data."""'], {}), "(\n 'Data already exists for this representation, use reset=True to generate new data.'\n )\n", (1310, 1405), False, 'from acousticsim.exceptions import AcousticSimError\n'), ((1677, 1700), 'numpy.arange', 'np.arange', (['(nfft / 2 + 1)'], {}), '(nfft / 2 + 1)\n', (1686, 1700), True, 'import numpy as np\n'), ((1621, 1634), 'numpy.spacing', 'np.spacing', (['(1)'], {}), '(1)\n', (1631, 1634), True, 'import numpy as np\n')] |
import argparse
import os
import random
import numpy as np
import torch
from torch.nn.functional import mse_loss
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from pynif3d.common.verification import check_equal
from pynif3d.datasets import Blender
from pynif3d.loss.conversions import mse_to_psnr
from pynif3d.pipeline.nerf import NeRF
model_filename = "model.pt"
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("--data-directory", "-dd", required=True)
parser.add_argument("--save-directory", "-sd", default="./saved_models")
parser.add_argument("--batch-size", "-bs", type=int, default=1)
parser.add_argument("--scene", "-s", default="lego")
parser.add_argument("--lr", "-l", type=float, default=5e-4)
parser.add_argument("--decay-rate", "-dr", type=float, default=0.1)
parser.add_argument("--decay-step", "-ds", type=float, default=250000)
parser.add_argument("--n-iterations", "-i", type=int, default=1000000)
parser.add_argument("--random-seed", "-rs", type=int, default=None)
parser.add_argument("--half-resolution", "-hr", type=bool, default=True)
parser.add_argument("--white-background", "-wb", type=bool, default=True)
parser.add_argument("--resume", action="store_true")
args = parser.parse_args()
return args
def save_checkpoint(
save_directory, model, optimizer, image_size, focal_length, iteration
):
checkpoint_path = os.path.join(save_directory, model_filename)
data = {
"iteration": iteration,
"model_state": model.state_dict(),
"optimizer_state": optimizer.state_dict(),
"focal_length": focal_length,
"image_size": image_size,
}
torch.save(data, checkpoint_path)
print("Saved checkpoint to:", checkpoint_path)
def load_checkpoint(save_directory):
checkpoint_path = os.path.join(save_directory, model_filename)
if not os.path.exists(checkpoint_path):
print("No checkpoint paths found in:", save_directory)
print("Will start training from scratch...")
return
checkpoint_data = torch.load(checkpoint_path)
return checkpoint_data
def train(dataset, model, optimizer, args):
device = None
if torch.cuda.is_available():
device = torch.cuda.current_device()
model.to(device)
model.train()
start_iteration = 0
if args.resume:
checkpoint = load_checkpoint(args.save_directory)
if checkpoint is not None:
check_equal(
dataset.image_size,
checkpoint["image_size"],
"dataset.image_size",
"checkpoint image_size",
)
check_equal(
dataset.focal_length,
checkpoint["focal_length"],
"dataset.focal_length",
"checkpoint focal_length",
)
model.load_state_dict(checkpoint["model_state"])
optimizer.load_state_dict(checkpoint["optimizer_state"])
start_iteration = checkpoint["iteration"]
train_loader = DataLoader(
dataset, shuffle=True, batch_size=args.batch_size, num_workers=4
)
train_iter = iter(train_loader)
checkpoint_interval = 10000
writer = SummaryWriter(args.save_directory)
for iteration in range(start_iteration, args.n_iterations):
# Grab a random batch from the dataset
try:
batch = next(train_iter)
except StopIteration:
train_iter = iter(train_loader)
batch = next(train_iter)
# Preprocess the data
images, camera_poses = batch
images = torch.as_tensor(images, device=device)
# Discard existing alpha channels and convert to [B, C, H, W]
images = images[..., :3].permute(0, 3, 1, 2)
camera_poses = torch.as_tensor(camera_poses, device=device)
camera_poses = camera_poses[:, :3, :]
# Run the inference
prediction = model(camera_poses)
sampled_coordinates = prediction["sample_coordinates"]
predicted_pixels = prediction["rgb_map"]
# Get the ground-truth (target) pixels based on the sampled coordinates
ys = sampled_coordinates[:, :, 0]
xs = sampled_coordinates[:, :, 1]
target_pixels = images[torch.arange(len(images))[:, None], :, ys, xs]
loss = [mse_loss(pred_pix, target_pixels) for pred_pix in predicted_pixels]
loss = torch.sum(torch.stack(loss))
# Update the model weights
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Apply learning rate scheduling
initial_lr = optimizer.defaults["lr"]
decay_rate = args.decay_rate
lr = initial_lr * decay_rate ** (iteration / args.decay_step)
optimizer.param_groups[0]["lr"] = lr
if iteration % 50 == 0:
mse = loss
psnr = mse_to_psnr(loss.detach())
print(
"[Iteration {}/{}]\tMSE: {:.4f}\tPSNR: {:.4f}\tLR: {:.6f}".format(
iteration, args.n_iterations, float(mse), float(psnr), lr
)
)
writer.add_scalar("loss/mse", float(mse), iteration)
writer.add_scalar("loss/psnr", float(psnr), iteration)
# Save the model
if iteration % checkpoint_interval == 0 or iteration == args.n_iterations - 1:
save_checkpoint(
args.save_directory,
model,
optimizer,
dataset.image_size,
dataset.focal_length,
iteration,
)
def main():
args = parse_arguments()
if args.random_seed is not None:
torch.manual_seed(args.random_seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(args.random_seed)
random.seed(args.random_seed)
# Create the dataset object
dataset = Blender(
args.data_directory,
mode="train",
scene=args.scene,
half_resolution=args.half_resolution,
white_background=args.white_background,
)
# Set up the model
background_color = None
if args.white_background:
background_color = torch.as_tensor([1, 1, 1], dtype=torch.float32)
model = NeRF(
dataset.image_size, dataset.focal_length, background_color=background_color
)
# Set up the optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, eps=1e-7)
# Create the directory that stores the saved models
os.makedirs(args.save_directory, exist_ok=True)
# Run the training pipeline
train(dataset, model, optimizer, args)
if __name__ == "__main__":
main()
| [
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.cuda.current_device",
"os.path.join",
"torch.utils.data.DataLoader",
"torch.load",
"os.path.exists",
"random.seed",
"torch.utils.tensorboard.SummaryWriter",
"pynif3d.common.verification.check_equal",
"pynif3d.pipeline.nerf.NeRF",
"torch.ma... | [((449, 474), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (472, 474), False, 'import argparse\n'), ((1482, 1526), 'os.path.join', 'os.path.join', (['save_directory', 'model_filename'], {}), '(save_directory, model_filename)\n', (1494, 1526), False, 'import os\n'), ((1748, 1781), 'torch.save', 'torch.save', (['data', 'checkpoint_path'], {}), '(data, checkpoint_path)\n', (1758, 1781), False, 'import torch\n'), ((1894, 1938), 'os.path.join', 'os.path.join', (['save_directory', 'model_filename'], {}), '(save_directory, model_filename)\n', (1906, 1938), False, 'import os\n'), ((2138, 2165), 'torch.load', 'torch.load', (['checkpoint_path'], {}), '(checkpoint_path)\n', (2148, 2165), False, 'import torch\n'), ((2264, 2289), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2287, 2289), False, 'import torch\n'), ((3119, 3195), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'shuffle': '(True)', 'batch_size': 'args.batch_size', 'num_workers': '(4)'}), '(dataset, shuffle=True, batch_size=args.batch_size, num_workers=4)\n', (3129, 3195), False, 'from torch.utils.data import DataLoader\n'), ((3291, 3325), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', (['args.save_directory'], {}), '(args.save_directory)\n', (3304, 3325), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((6007, 6154), 'pynif3d.datasets.Blender', 'Blender', (['args.data_directory'], {'mode': '"""train"""', 'scene': 'args.scene', 'half_resolution': 'args.half_resolution', 'white_background': 'args.white_background'}), "(args.data_directory, mode='train', scene=args.scene,\n half_resolution=args.half_resolution, white_background=args.\n white_background)\n", (6014, 6154), False, 'from pynif3d.datasets import Blender\n'), ((6363, 6449), 'pynif3d.pipeline.nerf.NeRF', 'NeRF', (['dataset.image_size', 'dataset.focal_length'], {'background_color': 'background_color'}), '(dataset.image_size, dataset.focal_length, background_color=\n background_color)\n', (6367, 6449), False, 'from pynif3d.pipeline.nerf import NeRF\n'), ((6623, 6670), 'os.makedirs', 'os.makedirs', (['args.save_directory'], {'exist_ok': '(True)'}), '(args.save_directory, exist_ok=True)\n', (6634, 6670), False, 'import os\n'), ((1951, 1982), 'os.path.exists', 'os.path.exists', (['checkpoint_path'], {}), '(checkpoint_path)\n', (1965, 1982), False, 'import os\n'), ((2308, 2335), 'torch.cuda.current_device', 'torch.cuda.current_device', ([], {}), '()\n', (2333, 2335), False, 'import torch\n'), ((3684, 3722), 'torch.as_tensor', 'torch.as_tensor', (['images'], {'device': 'device'}), '(images, device=device)\n', (3699, 3722), False, 'import torch\n'), ((3869, 3913), 'torch.as_tensor', 'torch.as_tensor', (['camera_poses'], {'device': 'device'}), '(camera_poses, device=device)\n', (3884, 3913), False, 'import torch\n'), ((5748, 5783), 'torch.manual_seed', 'torch.manual_seed', (['args.random_seed'], {}), '(args.random_seed)\n', (5765, 5783), False, 'import torch\n'), ((5889, 5921), 'numpy.random.seed', 'np.random.seed', (['args.random_seed'], {}), '(args.random_seed)\n', (5903, 5921), True, 'import numpy as np\n'), ((5930, 5959), 'random.seed', 'random.seed', (['args.random_seed'], {}), '(args.random_seed)\n', (5941, 5959), False, 'import random\n'), ((6302, 6349), 'torch.as_tensor', 'torch.as_tensor', (['[1, 1, 1]'], {'dtype': 'torch.float32'}), '([1, 1, 1], dtype=torch.float32)\n', (6317, 6349), False, 'import torch\n'), ((2526, 2634), 'pynif3d.common.verification.check_equal', 'check_equal', (['dataset.image_size', "checkpoint['image_size']", '"""dataset.image_size"""', '"""checkpoint image_size"""'], {}), "(dataset.image_size, checkpoint['image_size'],\n 'dataset.image_size', 'checkpoint image_size')\n", (2537, 2634), False, 'from pynif3d.common.verification import check_equal\n'), ((2722, 2838), 'pynif3d.common.verification.check_equal', 'check_equal', (['dataset.focal_length', "checkpoint['focal_length']", '"""dataset.focal_length"""', '"""checkpoint focal_length"""'], {}), "(dataset.focal_length, checkpoint['focal_length'],\n 'dataset.focal_length', 'checkpoint focal_length')\n", (2733, 2838), False, 'from pynif3d.common.verification import check_equal\n'), ((4402, 4435), 'torch.nn.functional.mse_loss', 'mse_loss', (['pred_pix', 'target_pixels'], {}), '(pred_pix, target_pixels)\n', (4410, 4435), False, 'from torch.nn.functional import mse_loss\n'), ((4495, 4512), 'torch.stack', 'torch.stack', (['loss'], {}), '(loss)\n', (4506, 4512), False, 'import torch\n')] |
import json
import pickle
import warnings
import os
import numpy as np
import pandas as pd
import networkx as nx
from math import ceil
from collections import defaultdict, Counter
from tqdm import tqdm
from matplotlib import pyplot as plt
import pystan
from convokit import Utterance, Corpus, User, Coordination, download
from utils import *
from copy import copy
import spacy
from spacy.tokenizer import Tokenizer
tokenized = spacy.load('en')
class WikiCorpusReader(object):
"""
Reader object for the Controversial TalkPages Corpus.
"""
def __init__(self, directory_path):
super(WikiCorpusReader, self).__init__()
self.directory_path = directory_path
self.topics_path = directory_path + 'ControversialTopics.txt'
self.threads_path = directory_path + 'WikipediaControversial.json'
self.FIELDS = ['topics', 'forum', 'author_name', 'target_name', 'utt_id',
'target_id', 'author_admin', 'target_admin',
'author_registered', 'author_gender', 'text']
self.ROOT = '<<ROOT>>'
self.TOPIC_SEPARATOR = '|||'
with open(self.topics_path, 'r') as f:
lines = f.readlines()
self.forum_to_topic = defaultdict(list)
for line in tqdm(lines):
line = line.strip()
if not line:
continue
# Antisemitism Politics and economics|||History|||People
forum_and_topics = line.split()
forum = forum_and_topics[0].replace('_', ' ')
topics_tmp = forum_and_topics[1].split(self.TOPIC_SEPARATOR)
for t in topics_tmp:
if t[-1] == ',': t = t[:-1]
self.forum_to_topic[forum].append(t.lower())
def json_to_tsv(self, tsv_path, topic_list=None):
print('Loading threads from original json file...')
with open(self.threads_path, 'r') as f:
threads = json.loads('\n'.join(f.readlines()))
print('{} threads loaded.'.format(len(threads)))
print('Process threads.')
utterances = []
for post_dict in tqdm(threads):
forum = post_dict["forum"]
forum_name = forum[5:].split('/Archive')[0]
try:
topics = self.forum_to_topic[forum_name]
except KeyError:
continue
if topic_list:
relevant_topics = set(topic_list) & set(topics)
if not relevant_topics:
continue
else:
relevant_topics = topics
# (speaker_name, is_speaker_admin)
previous_speakers = defaultdict(lambda: [(self.ROOT, -1, False)])
for comment_dict in post_dict["z_comments"]:
comment_id = comment_dict["comment_id"] # int
author_name = comment_dict["user_id"] # string
text = comment_dict["comment"]
author_registered = comment_dict["registered"] # boolean
try:
author_gender = comment_dict["gender"] # string
except KeyError:
author_gender = 'unknown'
try:
is_author_admin = comment_dict["admin_post"] # boolean
except KeyError:
is_author_admin = False
for topic in relevant_topics:
previous_speaker = previous_speakers[topic][comment_dict["parent_id"]]
target_name, target_utt_id, is_target_admin = previous_speaker
utterance = '\t'.join([topic,
forum_name,
author_name, target_name,
str(len(utterances)), str(target_utt_id),
str(is_author_admin), str(is_target_admin),
str(author_registered), author_gender,
text])
previous_speakers[topic].append((author_name, len(utterances), is_author_admin))
utterances.append(utterance)
print('{} valid utterances found.'.format(len(utterances)))
if topic_list:
tsv_filepath = '{}WikiControversial-{}.tsv'.format(tsv_path, ':'.join(topic_list))
else:
tsv_filepath = '{}WikiControversial-all.tsv'.format(tsv_path)
with open(tsv_filepath, 'w') as f:
for utterance in tqdm(utterances):
f.write("{}\n".format(utterance))
print('Utterances written to tab-separated file {}'.format(tsv_filepath))
return tsv_filepath
class WikiCorpus(object):
"""docstring for WikiCorpus"""
def __init__(self, filename):
super(WikiCorpus, self).__init__()
self.FIELDS = ['topics', 'forum', 'author_name', 'target_name', 'utt_id',
'target_id', 'author_admin', 'target_admin',
'author_registered', 'author_gender', 'text']
# self.ROOT = '<<ROOT>>'
if filename[-3:] == 'tsv':
self.posts = pd.read_csv(filename, sep='\t', names=self.FIELDS)
# try:
# os.remove(filename)
# except OSError:
# pass
elif filename[-3:] == 'csv':
self.posts = pd.read_csv(filename, header=0, index_col=0)
else:
raise ValueError('Use a tsv / csv file.')
try:
self.posts.set_index('utt_id', inplace=True)
except:
pass
self.pairs = None
self.users = None
self.network = None
def tokenize_posts(self):
"""
Add a 'tokens' column to the posts dataframe.
"""
if 'tokens' in self.posts:
warnings.warn("Posts are already tokenized. Skipping tokenization.")
return
tokens_lens_types = []
for text in tqdm(self.posts['text'], desc="Tokenizing posts."):
toks = [t.text.lower() for t in tokenized(str(text))]
tokens_lens_types.append((toks, len(toks), len(set(toks))))
tokens, lengths, types = zip(*tokens_lens_types)
self.posts = self.posts.assign(tokens=tokens)
self.posts = self.posts.assign(n_tokens=lengths)
self.posts = self.posts.assign(n_types=types)
n = len(self.posts)
self.posts = self.posts[self.posts.n_tokens > 0]
print("Filtered {} posts with 0-length utterances".format(n - len(self.posts)))
return
def count_marker_categories(self, markers):
""" Add feature columns for marker counts.
Markers is a dictionary where the keys are the marker types and
the values are a list of markers.
"""
if not 'tokens' in self.posts:
raise ValueError("Corpus must be tokenized for marker detection.")
if all(m in self.posts for m in markers):
warnings.warn("All marker columns already exist. Skipping marker detection.")
return
for m in markers:
counts = []
for tokens in tqdm(self.posts['tokens'], desc="Detecting {}.".format(m)):
m_lemmas = markers[m]
m_cnt = 0
for m_lemma in m_lemmas:
m_cnt += count(m_lemma, tokens)
counts.append(m_cnt)
self.posts[m] = counts
def count_marker_categories_efficient(self, markers):
""" Add feature columns for marker counts.
Markers is a dictionary where the keys are the marker types and
the values are a list of markers.
"""
if not 'tokens' in self.posts:
raise ValueError("Corpus must be tokenized for marker detection.")
if all(m in self.posts for m in markers):
warnings.warn("All marker columns already exist. Skipping marker detection.")
return
counts_tmp = {}
m2m = {}
m2cat = {}
for cat, marker_words in markers.items():
for m in marker_words:
if m[-1] == '*':
# counts_tmp[m[:-1]] = 0
m2m[m] = m[-1]
m2cat[m] = cat
counts_tmp[cat] = 0
counts = []
for i in range(len(self.posts['tokens'])):
counts.append(dict(counts_tmp))
# counts.append({k:v for k,v in counts_tmp.items()})
for i, tokens in enumerate(tqdm(self.posts['tokens'], desc="Detecting markers.")):
for token in tokens:
try:
counts[i][m2cat[token]] += 1
except KeyError:
for m, m_ in m2m.items(): # contains *
if token.startswith(m_):
counts[i][m2cat[m]] += 1
for cat in markers.keys():
self.posts[cat] = [count[cat] for count in counts]
def count_marker_tokens(self, marker_words):
""" Add feature columns for marker counts.
Markers is a list of word markers.
"""
if not 'tokens' in self.posts:
raise ValueError("Corpus must be tokenized for marker detection.")
if all(m in self.posts for m in marker_words):
warnings.warn("All marker columns already exist. Skipping marker detection.")
return
for m in marker_words:
counts = []
for tokens in tqdm(self.posts['tokens'], desc="Detecting {}.".format(m)):
counts.append(count(m, tokens))
self.posts[m] = counts
def count_marker_tokens_efficient(self, marker_words):
""" Add feature columns for marker counts.
Markers is a list of markers.
"""
if not 'tokens' in self.posts:
raise ValueError("Corpus must be tokenized for marker detection.")
if all(m in self.posts for m in marker_words):
warnings.warn("All marker columns already exist. Skipping marker detection.")
return
counts_tmp = {}
m2m = {}
for m in marker_words:
if m[-1] == '*':
# counts_tmp[m[:-1]] = 0
m2m[m] = m[-1]
counts_tmp[m] = 0
counts = []
for i in range(len(self.posts['tokens'])):
counts.append({k:v for k,v in counts_tmp.items()})
for i, tokens in enumerate(tqdm(self.posts['tokens'], desc="Detecting markers.")):
for token in tokens:
try:
counts[i][token] += 1
except KeyError:
for m, m_ in m2m.items(): # contains *
if token.startswith(m_):
counts[i][m] += 1
for m in marker_words:
self.posts[m] = [count[m] for count in counts]
def save(self, filename):
self.posts.to_csv(filename)
def reply_pairs(self, suffixes=['_a', '_b'], filter_self_replies=True):
"""
View the posts dataframe as reply pairs
"""
if self.pairs is not None:
return self.pairs
pairs = pd.merge(self.posts, self.posts,
how='inner', left_index=True,
right_on='target_id', left_on='utt_id',
suffixes=suffixes)
if filter_self_replies:
self_replies = (pairs['author_name' + suffixes[0]] != pairs['author_name' + suffixes[1]])
pairs = pairs[self_replies]
self.pairs = pairs
return self.pairs
def social_network(self, prune=False):
if self.network is not None:
return self.network
if self.pairs is None:
print("The list of reply pairs has not been constructed yet.")
print('Build reply pairs.')
self.reply_pairs()
print('Build network.')
self.network = nx.Graph()
for i, pair in tqdm(self.pairs.iterrows(), total=len(self.pairs)):
user_a, user_b = pair['author_name_a'], pair['author_name_b']
# ignore self-talk
if user_a == user_b or '' in (user_a, user_b):
continue
if self.network.has_edge(user_a, user_b):
self.network[user_a][user_b]['weight'] += 1
else:
self.network.add_edge(user_a, user_b, weight=1)
if self.network.has_edge(user_b, user_a):
self.network[user_b][user_a]['weight'] += 1
else:
self.network.add_edge(user_b, user_a, weight=1)
print("The unpruned network has {} nodes (users).".format(len(self.network.nodes())))
if prune:
# pruning the network to it's largest component:
minor_components = list(nx.connected_components(self.network))[1:]
disconnected_users = [user for com in minor_components for user in com]
self.network.remove_nodes_from(disconnected_users)
print("Removed {} users from {} disconnected components.".format(
len(disconnected_users), len(minor_components)))
return self.network
def assign_tie_strength(self):
tie_strengths = []
for _, pair in self.pairs.iterrows():
user_a, user_b = pair['author_name_a'], pair['author_name_b']
tie_strengths.append(self.network[user_a][user_b]['weight'])
tot_exchanges = np.sum(tie_strengths)
tie_strengths = [x / tot_exchanges for x in tie_strengths]
self.pairs['tie_strength'] = tie_strengths
print('Tie strength information has been assigned to all pairs.')
def assign_centrality(self, centrality='eigenvector'):
if centrality == 'eigenvector':
centrality_scores = nx.eigenvector_centrality_numpy(self.network)
elif centrality == 'betweenness':
centrality_scores = nx.eigenvector_centrality_numpy(self.network)
else:
raise ValueError('Choose "eigenvector" or "betweenness" centrality.')
# centrality_scores = pd.DataFrame(list(centrality_scores.items()),
# columns=['author_name', centrality])
# centrality_scores.set_index('author_name', inplace=True)
# self.users[centrality] = centrality_scores
centrality_values = []
for i, pair in self.pairs.iterrows():
try:
centrality_a = centrality_scores[pair['author_name_a']]
centrality_b = centrality_scores[pair['author_name_b']]
except KeyError:
centrality_a, centrality_b = (-1, -1)
centrality_values.append((centrality_a, centrality_b))
a_values, b_values = zip(*centrality_values)
self.pairs[centrality + '_a'] = a_values
self.pairs[centrality + '_b'] = b_values
print('Centrality information has been assigned to all pairs.')
def get_users(self):
if self.users is not None:
return self.users
users = {'author_name': [],
'author_admin': [],
'author_gender': []}
seen = {}
for _, pair in tqdm(self.pairs.iterrows(), total=len(self.pairs)):
for suffix in ['_a', '_b']:
try:
seen[pair['author_name' + suffix]]
except KeyError:
for field, values in users.items():
users[field].append(pair[field + suffix])
self.users = pd.DataFrame(data=users, columns=list(users.keys()))
self.users.set_index('author_name', inplace=True)
return self.users | [
"tqdm.tqdm",
"numpy.sum",
"pandas.read_csv",
"pandas.merge",
"collections.defaultdict",
"spacy.load",
"networkx.connected_components",
"networkx.Graph",
"networkx.eigenvector_centrality_numpy",
"warnings.warn"
] | [((432, 448), 'spacy.load', 'spacy.load', (['"""en"""'], {}), "('en')\n", (442, 448), False, 'import spacy\n'), ((1254, 1271), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1265, 1271), False, 'from collections import defaultdict, Counter\n'), ((1292, 1303), 'tqdm.tqdm', 'tqdm', (['lines'], {}), '(lines)\n', (1296, 1303), False, 'from tqdm import tqdm\n'), ((2181, 2194), 'tqdm.tqdm', 'tqdm', (['threads'], {}), '(threads)\n', (2185, 2194), False, 'from tqdm import tqdm\n'), ((6204, 6254), 'tqdm.tqdm', 'tqdm', (["self.posts['text']"], {'desc': '"""Tokenizing posts."""'}), "(self.posts['text'], desc='Tokenizing posts.')\n", (6208, 6254), False, 'from tqdm import tqdm\n'), ((11541, 11667), 'pandas.merge', 'pd.merge', (['self.posts', 'self.posts'], {'how': '"""inner"""', 'left_index': '(True)', 'right_on': '"""target_id"""', 'left_on': '"""utt_id"""', 'suffixes': 'suffixes'}), "(self.posts, self.posts, how='inner', left_index=True, right_on=\n 'target_id', left_on='utt_id', suffixes=suffixes)\n", (11549, 11667), True, 'import pandas as pd\n'), ((12341, 12351), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (12349, 12351), True, 'import networkx as nx\n'), ((13913, 13934), 'numpy.sum', 'np.sum', (['tie_strengths'], {}), '(tie_strengths)\n', (13919, 13934), True, 'import numpy as np\n'), ((2733, 2779), 'collections.defaultdict', 'defaultdict', (['(lambda : [(self.ROOT, -1, False)])'], {}), '(lambda : [(self.ROOT, -1, False)])\n', (2744, 2779), False, 'from collections import defaultdict, Counter\n'), ((4725, 4741), 'tqdm.tqdm', 'tqdm', (['utterances'], {}), '(utterances)\n', (4729, 4741), False, 'from tqdm import tqdm\n'), ((5367, 5417), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'sep': '"""\t"""', 'names': 'self.FIELDS'}), "(filename, sep='\\t', names=self.FIELDS)\n", (5378, 5417), True, 'import pandas as pd\n'), ((6055, 6123), 'warnings.warn', 'warnings.warn', (['"""Posts are already tokenized. Skipping tokenization."""'], {}), "('Posts are already tokenized. Skipping tokenization.')\n", (6068, 6123), False, 'import warnings\n'), ((7231, 7308), 'warnings.warn', 'warnings.warn', (['"""All marker columns already exist. Skipping marker detection."""'], {}), "('All marker columns already exist. Skipping marker detection.')\n", (7244, 7308), False, 'import warnings\n'), ((8129, 8206), 'warnings.warn', 'warnings.warn', (['"""All marker columns already exist. Skipping marker detection."""'], {}), "('All marker columns already exist. Skipping marker detection.')\n", (8142, 8206), False, 'import warnings\n'), ((8801, 8854), 'tqdm.tqdm', 'tqdm', (["self.posts['tokens']"], {'desc': '"""Detecting markers."""'}), "(self.posts['tokens'], desc='Detecting markers.')\n", (8805, 8854), False, 'from tqdm import tqdm\n'), ((9608, 9685), 'warnings.warn', 'warnings.warn', (['"""All marker columns already exist. Skipping marker detection."""'], {}), "('All marker columns already exist. Skipping marker detection.')\n", (9621, 9685), False, 'import warnings\n'), ((10296, 10373), 'warnings.warn', 'warnings.warn', (['"""All marker columns already exist. Skipping marker detection."""'], {}), "('All marker columns already exist. Skipping marker detection.')\n", (10309, 10373), False, 'import warnings\n'), ((10786, 10839), 'tqdm.tqdm', 'tqdm', (["self.posts['tokens']"], {'desc': '"""Detecting markers."""'}), "(self.posts['tokens'], desc='Detecting markers.')\n", (10790, 10839), False, 'from tqdm import tqdm\n'), ((14262, 14307), 'networkx.eigenvector_centrality_numpy', 'nx.eigenvector_centrality_numpy', (['self.network'], {}), '(self.network)\n', (14293, 14307), True, 'import networkx as nx\n'), ((5591, 5635), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'header': '(0)', 'index_col': '(0)'}), '(filename, header=0, index_col=0)\n', (5602, 5635), True, 'import pandas as pd\n'), ((14382, 14427), 'networkx.eigenvector_centrality_numpy', 'nx.eigenvector_centrality_numpy', (['self.network'], {}), '(self.network)\n', (14413, 14427), True, 'import networkx as nx\n'), ((13267, 13304), 'networkx.connected_components', 'nx.connected_components', (['self.network'], {}), '(self.network)\n', (13290, 13304), True, 'import networkx as nx\n')] |
import csv
import itertools
import operator
import numpy as np
import nltk
import os
import sys
from datetime import datetime
from keras.models import Sequential
from keras.layers import Dense, Activation,TimeDistributed
from keras.layers import LSTM,GRU
from keras.layers.embeddings import Embedding
from keras.optimizers import RMSprop, Adam
from keras.utils.data_utils import get_file
from keras.layers import Dropout
import numpy as np
import random
import sys
from keras.utils.np_utils import to_categorical
from keras.preprocessing import sequence
from keras.models import model_from_json
from keras.callbacks import EarlyStopping, ModelCheckpoint
#from make_smile import ziprocess_organic,process_zinc_data
from make_smile import zinc_data_with_bracket_original,zinc_processed_with_bracket
from keras.layers import Conv1D, MaxPooling1D
#from combine_bond_atom import organic, process_organic,bond_atom
import yaml
import matplotlib as mpl
mpl.use('Agg') ## fix the "Invalid DISPLAY variable" Error
import matplotlib.pyplot as plt
def load_data():
sen_space=[]
#f = open('/Users/yang/smiles.csv', 'rb')
f = open(dataset, 'rb')
reader = csv.reader(f)
for row in reader:
#word_space[row].append(reader[row])
#print word_sapce
sen_space.append(row)
#print sen_space
f.close()
element_table=["Cu","Ti","Zr","Ga","Ge","As","Se","Br","Si","Zn","Cl","Be","Ca","Na","Sr","Ir","Li","Rb","Cs","Fr","Be","Mg",
"Ca","Sr","Ba","Ra","Sc","La","Ac","Ti","Zr","Nb","Ta","Db","Cr","Mo","Sg","Mn","Tc","Re","Bh","Fe","Ru","Os","Hs","Co","Rh",
"Ir","Mt","Ni","Pd","Pt","Ds","Cu","Ag","Au","Rg","Zn","Cd","Hg","Cn","Al","Ga","In","Tl","Nh","Si","Ge","Sn","Pb","Fl",
"As","Sb","Bi","Mc","Se","Te","Po","Lv","Cl","Br","At","Ts","He","Ne","Ar","Kr","Xe","Rn","Og"]
#print sen_space
word1=sen_space[0]
word_space=list(word1[0])
end="\n"
#start="st"
#word_space.insert(0,end)
word_space.append(end)
#print word_space
#print len(sen_space)
all_smile=[]
#print word_space
#for i in range(len(all_smile)):
for i in range(len(sen_space)):
word1=sen_space[i]
word_space=list(word1[0])
word=[]
#word_space.insert(0,end)
j=0
while j<len(word_space):
word_space1=[]
word_space1.append(word_space[j])
if j+1<len(word_space):
word_space1.append(word_space[j+1])
word_space2=''.join(word_space1)
else:
word_space1.insert(0,word_space[j-1])
word_space2=''.join(word_space1)
if word_space2 not in element_table:
word.append(word_space[j])
j=j+1
else:
word.append(word_space2)
j=j+2
word.append(end)
all_smile.append(list(word))
#print all_smile
val=[]
for i in range(len(all_smile)):
for j in range(len(all_smile[i])):
if all_smile[i][j] not in val:
val.append(all_smile[i][j])
#print val
val.remove("\n")
val.insert(0,"\n")
return val, all_smile
def organic_data():
sen_space=[]
#f = open('/Users/yang/smiles.csv', 'rb')
f = open('/Users/yang/LSTM-chemical-project/make_sm.csv', 'rb')
#f = open('/Users/yang/LSTM-chemical-project/smile_trainning.csv', 'rb')
reader = csv.reader(f)
for row in reader:
#word_space[row].append(reader[row])
#print word_sapce
sen_space.append(row)
#print sen_space
f.close()
element_table=["Cu","Ti","Zr","Ga","Ge","As","Se","Br","Si","Zn","Cl","Be","Ca","Na","Sr","Ir","Li","Rb","Cs","Fr","Be","Mg",
"Ca","Sr","Ba","Ra","Sc","La","Ac","Ti","Zr","Nb","Ta","Db","Cr","Mo","Sg","Mn","Tc","Re","Bh","Fe","Ru","Os","Hs","Co","Rh",
"Ir","Mt","Ni","Pd","Pt","Ds","Cu","Ag","Au","Rg","Zn","Cd","Hg","Cn","Al","Ga","In","Tl","Nh","Si","Ge","Sn","Pb","Fl",
"As","Sb","Bi","Mc","Se","Te","Po","Lv","Cl","Br","At","Ts","He","Ne","Ar","Kr","Xe","Rn","Og"]
#print sen_space
word1=sen_space[0]
word_space=list(word1[0])
end="\n"
#start="st"
#word_space.insert(0,end)
word_space.append(end)
#print word_space
#print len(sen_space)
all_smile=[]
#print word_space
#for i in range(len(all_smile)):
for i in range(len(sen_space)):
word1=sen_space[i]
word_space=list(word1[0])
word=[]
#word_space.insert(0,end)
j=0
while j<len(word_space):
word_space1=[]
word_space1.append(word_space[j])
if j+1<len(word_space):
word_space1.append(word_space[j+1])
word_space2=''.join(word_space1)
else:
word_space1.insert(0,word_space[j-1])
word_space2=''.join(word_space1)
if word_space2 not in element_table:
word.append(word_space[j])
j=j+1
else:
word.append(word_space2)
j=j+2
word.append(end)
all_smile.append(list(word))
#print all_smile
val=[]
for i in range(len(all_smile)):
for j in range(len(all_smile[i])):
if all_smile[i][j] not in val:
val.append(all_smile[i][j])
#print val
val.remove("\n")
val.insert(0,"\n")
return val, all_smile
def prepare_data(smiles,all_smile):
all_smile_index=[]
for i in range(len(all_smile)):
smile_index=[]
for j in range(len(all_smile[i])):
smile_index.append(smiles.index(all_smile[i][j]))
all_smile_index.append(smile_index)
X_train=all_smile_index
y_train=[]
for i in range(len(X_train)):
x1=X_train[i]
x2=x1[1:len(x1)]
x2.append(0)
y_train.append(x2)
return X_train,y_train
def generate_smile(model,val):
end="\n"
start_smile_index= [val.index("C")]
new_smile=[]
while not start_smile_index[-1] == val.index(end):
predictions=model.predict(start_smile_index)
##next atom probability
smf=[]
for i in range (len(X)):
sm=[]
for j in range(len(X[i])):
#if np.argmax(predictions[i][j])=!0
sm.append(np.argmax(predictions[i][j]))
smf.append(sm)
#print sm
#print smf
#print len(sm)
new_smile.append(sampled_word)
#sentence_str = [index_to_word[x] for x in new_sentence[1:-1]]
#return new_sentence
def save_model(model):
# serialize model to JSON
model_json = model.to_json()
#with open("model.json", "w") as json_file:
with open(output_json, "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
#model.save_weights("model.h5")
model.save_weights(output_weight)
print("Saved model to disk")
def save_model_ES(model):
model_json = model.to_json()
with open(output_json, "w") as json_file:
json_file.write(model_json)
print("Saved model to disk")
if __name__ == "__main__":
argvs = sys.argv
argc = len(argvs)
if argc == 1:
print("input configuration file")
exit()
f = open(str(argvs[1]), "r+")
conf = yaml.load(f)
f.close()
dataset = conf.get('dataset')
output_json = conf.get('output_json')
output_weight = conf.get('output_weight')
dropout_rate = conf.get('dropout_rate',0.2)
lr_val = conf.get('learning_rate',0.01)
epochs = conf.get('epoch',100)
batch_size = conf.get('batch_size',512)
validation_split = conf.get('validation_split', 0.1)
units = conf.get('units', 256)
rec_dropout_rate = conf.get('rec_dropout_rate', 0.2)
print('========== display configuration ==========')
print('dataset = ',dataset)
print('output_json = ',output_json)
print('output_weight = ',output_weight)
print('dropout_rate = ',dropout_rate)
print('learning_rate = ',lr_val)
print('epoch = ',epochs)
print('batch_size = ',batch_size)
print('validation_split = ',validation_split)
print('units = ', units)
print('rec_dropout_rate = ', rec_dropout_rate)
smile=zinc_data_with_bracket_original(dataset)
valcabulary,all_smile=zinc_processed_with_bracket(smile)
print(valcabulary)
print(len(all_smile))
X_train,y_train=prepare_data(valcabulary,all_smile)
maxlen=82
X= sequence.pad_sequences(X_train, maxlen=82, dtype='int32',
padding='post', truncating='pre', value=0.)
y = sequence.pad_sequences(y_train, maxlen=82, dtype='int32',
padding='post', truncating='pre', value=0.)
y_train_one_hot = np.array([to_categorical(sent_label, num_classes=len(valcabulary)) for sent_label in y])
print(y_train_one_hot.shape)
vocab_size=len(valcabulary)
embed_size=len(valcabulary)
N=X.shape[1]
model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim=len(valcabulary), input_length=N,mask_zero=False))
model.add(GRU(output_dim=units, input_shape=(82,64),activation='tanh', dropout = dropout_rate, recurrent_dropout = rec_dropout_rate,return_sequences=True))
#model.add(LSTM(output_dim=256, input_shape=(82,64),activation='tanh',return_sequences=True))
#model.add(Dropout(dropout_rate))
model.add(GRU(units,activation='tanh',dropout = dropout_rate, recurrent_dropout = rec_dropout_rate,return_sequences=True))
#model.add(LSTM(output_dim=1000, activation='sigmoid',return_sequences=True))
#model.add(Dropout(dropout_rate))
model.add(TimeDistributed(Dense(embed_size, activation='softmax')))
optimizer=Adam(lr_val)
print(model.summary())
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
if epochs == -1:
early_stopping = EarlyStopping(monitor = 'val_loss', patience = 5, verbose = 1)
checkpointer = ModelCheckpoint(filepath = output_weight, verbose = 1, save_weights_only = True, save_best_only = True)
result = model.fit(X,y_train_one_hot,batch_size = batch_size,epochs=100,verbose = 1, callbacks = [early_stopping, checkpointer], validation_split = validation_split, shuffle = True)
save_model_ES(model)
else:
result = model.fit(X,y_train_one_hot,batch_size,epochs,1,None,validation_split, shuffle = True)
save_model(model)
## plot the training acc
#%matplotlib inline
try:
# before keras 2.0.5
plt.plot(range(1, len(result.history['acc'])+1), result.history['acc'], label="training")
plt.plot(range(1, len(result.history['val_acc'])+1), result.history['val_acc'], label="validation")
except KeyError:
# after keras-2.3.1
plt.plot(range(1, len(result.history['accuracy'])+1), result.history['accuracy'], label="training")
plt.plot(range(1, len(result.history['val_accuracy'])+1), result.history['val_accuracy'], label="validation")
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.savefig('learning_curve_GRU'+dataset.split('/')[-1]+'_units'+str(units)+'_dropout'+str(dropout_rate)+'_recDP'+str(rec_dropout_rate)+'_lr'+str(lr_val)+'_batchsize'+str(batch_size)+'.png', dpi = 300, bbox_inches='tight', pad_inches=0)
| [
"yaml.load",
"csv.reader",
"numpy.argmax",
"keras.preprocessing.sequence.pad_sequences",
"keras.callbacks.ModelCheckpoint",
"matplotlib.pyplot.legend",
"keras.layers.GRU",
"keras.optimizers.Adam",
"matplotlib.pyplot.ylabel",
"matplotlib.use",
"keras.callbacks.EarlyStopping",
"keras.layers.Dens... | [((949, 963), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (956, 963), True, 'import matplotlib as mpl\n'), ((1164, 1177), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (1174, 1177), False, 'import csv\n'), ((3440, 3453), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (3450, 3453), False, 'import csv\n'), ((7344, 7356), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (7353, 7356), False, 'import yaml\n'), ((8283, 8323), 'make_smile.zinc_data_with_bracket_original', 'zinc_data_with_bracket_original', (['dataset'], {}), '(dataset)\n', (8314, 8323), False, 'from make_smile import zinc_data_with_bracket_original, zinc_processed_with_bracket\n'), ((8350, 8384), 'make_smile.zinc_processed_with_bracket', 'zinc_processed_with_bracket', (['smile'], {}), '(smile)\n', (8377, 8384), False, 'from make_smile import zinc_data_with_bracket_original, zinc_processed_with_bracket\n'), ((8516, 8622), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['X_train'], {'maxlen': '(82)', 'dtype': '"""int32"""', 'padding': '"""post"""', 'truncating': '"""pre"""', 'value': '(0.0)'}), "(X_train, maxlen=82, dtype='int32', padding='post',\n truncating='pre', value=0.0)\n", (8538, 8622), False, 'from keras.preprocessing import sequence\n'), ((8634, 8740), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['y_train'], {'maxlen': '(82)', 'dtype': '"""int32"""', 'padding': '"""post"""', 'truncating': '"""pre"""', 'value': '(0.0)'}), "(y_train, maxlen=82, dtype='int32', padding='post',\n truncating='pre', value=0.0)\n", (8656, 8740), False, 'from keras.preprocessing import sequence\n'), ((8995, 9007), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (9005, 9007), False, 'from keras.models import Sequential\n'), ((9746, 9758), 'keras.optimizers.Adam', 'Adam', (['lr_val'], {}), '(lr_val)\n', (9750, 9758), False, 'from keras.optimizers import RMSprop, Adam\n'), ((11053, 11073), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (11063, 11073), True, 'import matplotlib.pyplot as plt\n'), ((11078, 11100), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy"""'], {}), "('Accuracy')\n", (11088, 11100), True, 'import matplotlib.pyplot as plt\n'), ((11105, 11117), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (11115, 11117), True, 'import matplotlib.pyplot as plt\n'), ((9131, 9279), 'keras.layers.GRU', 'GRU', ([], {'output_dim': 'units', 'input_shape': '(82, 64)', 'activation': '"""tanh"""', 'dropout': 'dropout_rate', 'recurrent_dropout': 'rec_dropout_rate', 'return_sequences': '(True)'}), "(output_dim=units, input_shape=(82, 64), activation='tanh', dropout=\n dropout_rate, recurrent_dropout=rec_dropout_rate, return_sequences=True)\n", (9134, 9279), False, 'from keras.layers import LSTM, GRU\n'), ((9427, 9542), 'keras.layers.GRU', 'GRU', (['units'], {'activation': '"""tanh"""', 'dropout': 'dropout_rate', 'recurrent_dropout': 'rec_dropout_rate', 'return_sequences': '(True)'}), "(units, activation='tanh', dropout=dropout_rate, recurrent_dropout=\n rec_dropout_rate, return_sequences=True)\n", (9430, 9542), False, 'from keras.layers import LSTM, GRU\n'), ((9927, 9983), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'patience': '(5)', 'verbose': '(1)'}), "(monitor='val_loss', patience=5, verbose=1)\n", (9940, 9983), False, 'from keras.callbacks import EarlyStopping, ModelCheckpoint\n'), ((10013, 10112), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'filepath': 'output_weight', 'verbose': '(1)', 'save_weights_only': '(True)', 'save_best_only': '(True)'}), '(filepath=output_weight, verbose=1, save_weights_only=True,\n save_best_only=True)\n', (10028, 10112), False, 'from keras.callbacks import EarlyStopping, ModelCheckpoint\n'), ((9690, 9729), 'keras.layers.Dense', 'Dense', (['embed_size'], {'activation': '"""softmax"""'}), "(embed_size, activation='softmax')\n", (9695, 9729), False, 'from keras.layers import Dense, Activation, TimeDistributed\n'), ((6370, 6398), 'numpy.argmax', 'np.argmax', (['predictions[i][j]'], {}), '(predictions[i][j])\n', (6379, 6398), True, 'import numpy as np\n')] |
import cv2
import numpy as np
import math
import matplotlib.pyplot as plt
# colour-science を
# PiPi からインストールしておく
from colour.plotting import *
#----------UI-----------------------
#import pyto_ui as ui
#view = ui.View()
#view.background_color = ui.COLOR_SYSTEM_BACKGROUND
#ui.show_view(view, ui.PRESENTATION_MODE_SHEET) # to show the view:
#----------UI-----------------------
#-----------設定-----------------------
# どのような処理を行うかを設定する
#-------------------------------------
# 動画をファイルから読み込むか、カメラから読み込むかを決める
isCamera = True
frameRate = 25 # frame/second
captureDurationInSecond = 20 # 撮影時間(sec.)
# デバイスが撮影するだろう画像サイズ(記入値はiPhone 11 の場合)
assumptionW = 480 # 480 #1920
assumptionH = 360 # 360 #1080
# (計算時間短縮のために)撮影画像の長さを何分の一にするか
resizeRatioInLength = 1 # 10分の1
aW = int( assumptionW / resizeRatioInLength )
aH = int( assumptionH / resizeRatioInLength )
# デバイスが撮影するだろう画像サイズ下で、
# 分光情報が得られるだろうX位置・領域 (これも想定)
# 0-1で指定
spectorPixelStart = 0.6
spectorPixelWidth = 0.3
aSpectorPixelStart = int( aH * spectorPixelStart)
aSpectorPixelWidth = int( aH * spectorPixelWidth)
# ------------撮影時の歪み補正用の行列を生成する------------
# 画像サイズや歪み程度が一定なら、動画読み込みより事前に処理しておく
#m1 = 0.1 # ずれ補正の傾斜調整、1 より小さな値に設定する、0になると補正量は0になる
m2 = int(-40.0 / resizeRatioInLength) # 中央と上下両端での、横方向ズレをピクセルで表したもの
mapY = np.zeros( (aH, aW), dtype=np.float32 )
mapX = np.zeros( (aH, aW), dtype=np.float32 )
for x in range( aW ):
mapX[:, x] = x # X方向は変化させない
for y in range( aH ):
for x in range( aW ):
mapY[y, x] = y + m2 * math.cos( (float(x)-float(aW)/2.0) / (float(aW)/2.0) * math.pi/2.0 )
cv2.imwrite( 'mapY.png', mapY )
# ------------撮影時の歪み補正用の行列を生成する------------
#-----------動画デバイスを開く(撮影ループ)-----------------------
frames = []
if isCamera: # カメラから動画を読み込む場合
cap = cv2.VideoCapture( 0 ) # 0:back, 1: front
#cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'));
#cap.set( cv2.CAP_PROP_FPS, frameRate )
ret = cap.set( cv2.CAP_PROP_FRAME_WIDTH, assumptionW )
ret = cap.set( cv2.CAP_PROP_FRAME_HEIGHT, assumptionH )
# 画像サイズを取得する
w = round( cap.get( cv2.CAP_PROP_FRAME_WIDTH ) )
h = round( cap.get( cv2.CAP_PROP_FRAME_HEIGHT ) )
#print( w )
#print( h )
# カメラ時は「読み込む時間長さ(フレーム数)」を決めておく
frame_n = frameRate * captureDurationInSecond
else: # ファイルから動画を読み込む場合
cap = cv2.VideoCapture( "sample.MOV" )
frame_n = round( cap.get( cv2.CAP_PROP_FRAME_COUNT ) )
if not cap.isOpened(): # 動画ファイルを開くことができなかったら
#print("VideoCapture can't be opened.")
exit()
#---------------------------------------------------------
#-------------------動画読み取りループ-----------------------
n = 0
while( True ):
ret, frame = cap.read() # 動画象読み取り
# 各種終了処理
if not ret: # 画像を読み取れなかった場合
#print("VideoCapture can't be read.")
continue
# Convert from BGR to RGB
# BGRでなくて、RGBになってるので、入れ替える
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
frames.append(frame )
# キャプチャー画像表示
cv2.imshow('frame', frame)
n = n+1
if n >= frame_n:
break
cap.release() # 動画象読み取り終了
#-----------動画取得の終了-----------------------
#-----------動画加工処理-----------------------
undistortFrames = []
for frame in frames:
if resizeRatioInLength != 1:
frame = cv2.resize( frame, (aW, aH) )
# 歪み除去画像を表示
undistortFrame = cv2.remap(frame, mapX, mapY, cv2.INTER_CUBIC)
undistortFrames.append( undistortFrame )
cv2.imshow('frame', undistortFrame)
del frames # メモリ削減のために撮影フレーム削除
#-----------動画加工処理-----------------------
print(undistortFrames[0].shape)
#-----------簡易RGB画像出力-----------------------
# RGB3チャンネル画像格納用行列を作成する
# 単純化したRGB値をどの(x方向)画素から読み込むか
aBOffset = int( aSpectorPixelWidth / 6.0 )
aGOffset = int( 3 * aSpectorPixelWidth / 6.0 )
aROffset = int( 5 * aSpectorPixelWidth / 6.0 )
simpleRGBImg = np.zeros( (frame_n, aW, 3), np.float )
n = 0
for frame in undistortFrames:
simpleRGBImg[ n, :, 2 ] = frame[ aSpectorPixelStart + aBOffset, :, 0 ].astype( np.float )*5 # B
simpleRGBImg[ n, :, 1 ] = frame[ aSpectorPixelStart + aGOffset, :, 1 ].astype( np.float ) # G
simpleRGBImg[ n, :, 0 ] = frame[ aSpectorPixelStart + aROffset, :, 2 ].astype( np.float )*5 # R
n = n+1
#print(simpleRGBImg.shape)
#print(simpleRGBImg[0][0])
#print( np.max( simpleRGBImg ) )
#print( np.min( simpleRGBImg ) )
plt.figure(figsize=(3, 3), dpi=200)
plt.imshow(simpleRGBImg/255.)
plt.show()
| [
"matplotlib.pyplot.show",
"cv2.cvtColor",
"cv2.imwrite",
"matplotlib.pyplot.imshow",
"numpy.zeros",
"cv2.remap",
"cv2.VideoCapture",
"matplotlib.pyplot.figure",
"cv2.imshow",
"cv2.resize"
] | [((1273, 1309), 'numpy.zeros', 'np.zeros', (['(aH, aW)'], {'dtype': 'np.float32'}), '((aH, aW), dtype=np.float32)\n', (1281, 1309), True, 'import numpy as np\n'), ((1320, 1356), 'numpy.zeros', 'np.zeros', (['(aH, aW)'], {'dtype': 'np.float32'}), '((aH, aW), dtype=np.float32)\n', (1328, 1356), True, 'import numpy as np\n'), ((1565, 1594), 'cv2.imwrite', 'cv2.imwrite', (['"""mapY.png"""', 'mapY'], {}), "('mapY.png', mapY)\n", (1576, 1594), False, 'import cv2\n'), ((3781, 3817), 'numpy.zeros', 'np.zeros', (['(frame_n, aW, 3)', 'np.float'], {}), '((frame_n, aW, 3), np.float)\n', (3789, 3817), True, 'import numpy as np\n'), ((4287, 4322), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(3, 3)', 'dpi': '(200)'}), '(figsize=(3, 3), dpi=200)\n', (4297, 4322), True, 'import matplotlib.pyplot as plt\n'), ((4323, 4355), 'matplotlib.pyplot.imshow', 'plt.imshow', (['(simpleRGBImg / 255.0)'], {}), '(simpleRGBImg / 255.0)\n', (4333, 4355), True, 'import matplotlib.pyplot as plt\n'), ((4353, 4363), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4361, 4363), True, 'import matplotlib.pyplot as plt\n'), ((1746, 1765), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (1762, 1765), False, 'import cv2\n'), ((2313, 2343), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""sample.MOV"""'], {}), "('sample.MOV')\n", (2329, 2343), False, 'import cv2\n'), ((2859, 2897), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_RGB2BGR'], {}), '(frame, cv2.COLOR_RGB2BGR)\n', (2871, 2897), False, 'import cv2\n'), ((2946, 2972), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'frame'], {}), "('frame', frame)\n", (2956, 2972), False, 'import cv2\n'), ((3291, 3336), 'cv2.remap', 'cv2.remap', (['frame', 'mapX', 'mapY', 'cv2.INTER_CUBIC'], {}), '(frame, mapX, mapY, cv2.INTER_CUBIC)\n', (3300, 3336), False, 'import cv2\n'), ((3386, 3421), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'undistortFrame'], {}), "('frame', undistortFrame)\n", (3396, 3421), False, 'import cv2\n'), ((3224, 3251), 'cv2.resize', 'cv2.resize', (['frame', '(aW, aH)'], {}), '(frame, (aW, aH))\n', (3234, 3251), False, 'import cv2\n')] |
"""This module computes distances between DNA/protein sequences based on the
sequence feature, named Base-Base Correlation (BBC).
References:
1. Liu, Zhi-Hua, et al. (2007) Bioinformatics and Biomedical Engineering,
ICBBE. The 1st International Conference on. IEEE, 2007.
doi: 10.1109/ICBBE.2007.98
2. <NAME>, <NAME>, <NAME>. (2008) Biochem Biophys Res Commun. 368(2):223-30.
doi: 10.1016/j.bbrc.2008.01.070.
Todo:
* handle sequence symbols not included in molecule's alphabet
"""
import numpy as np
from .utils import distance
def base_base_correlation(seq, k, alphabet=None):
"""Compute the base base correlation (BBC) vector for a sequence.
Args:
seq (str) : sequence
k (int) : parameter of the BBC. Intuitively, it represents
the maximum distance to observe correlation between bases.
alphabet (str/list) : List of possible characters. This can be used to
avoid autodetection of the alphabet in the case where
sequences with missing letters are to be compared.
Returns:
numpy.ndarray: shape (1, 16) for DNA and (1, 400) for protein.
Examples:
>>> print(base_base_correlation('ATGCATGC', 1, 'ATGC'))
[[
-0.12547302 -0.12547302 0.2281059 0.17169665 0.01815213
-0.12547302 -0.12547302 0.04258163 0.04258163 0.17169665
-0.12547302 -0.12547302 -0.12547302 0.2281059 0.17169665
-0.12547302
]]
Note:
A description of the method can be found here:
http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=4272582
This implementation is generalized for any sequence type.
"""
s = seq
if k > len(s) - 2:
raise Exception("Sequence too short to compute BBC with "
"k={}".format(k))
if alphabet is None:
alphabet = set(s)
else:
s = "".join([c for c in s if c in alphabet])
alphabet = sorted(list(alphabet))
alphabet = dict(zip(alphabet, range(len(alphabet))))
L = len(alphabet)
# Compute the base probabilities for every character.
p = np.zeros(L)
for c in s:
p[alphabet[c]] += 1
p /= np.sum(p)
p.shape = (1, L)
bbc = np.zeros((L, L))
for l in range(1, k + 2):
# Compute $p_{ij}(l)$ representing the probability of
# observing the bases i and j separated by l "gaps".
# Compute it for all 16 combinations of alleles.
l_dist_correlations = np.zeros((L, L))
for i in range(len(s) - l):
nuc1 = alphabet[s[i]]
nuc2 = alphabet[s[i + l]]
l_dist_correlations[nuc1][nuc2] += 1
l_dist_correlations /= np.sum(l_dist_correlations)
# Compute the D_{ij}(l) which is the deviation from
# statistical independance.
# $D_{ij}(l) = p_{ij}(l) - p_i p_j$
D = l_dist_correlations - np.dot(p.T, p)
bbc += D + (D ** 2 / 2 * np.dot(p.T ** 2, p ** 2)) + D ** 3
# Flatten the bbc into a 16 feature vector.
bbc.shape = (1, L * L)
return bbc
def create_vectors(seq_records, k=10, alphabet="ATGC"):
"""Create BBC's vectors for multiple sequence records.
Args:
seq_records (obj SeqRecords)
"""
data = np.zeros(shape=(seq_records.count, len(alphabet)**2))
for seqidx, seq in enumerate(seq_records.seq_list):
vector = base_base_correlation(seq, k=k, alphabet=alphabet)
data[seqidx] = vector
return data
class Distance(distance.Distance):
def __init__(self, vector, disttype='euclid_norm'):
super(Distance, self).__init__(vector, disttype)
def main():
from .utils.seqrecords import main
from .utils import distmatrix
seq_records = main()
vector = create_vectors(seq_records, 10, alphabet="ATGC")
dist = Distance(vector)
matrix = distmatrix.create(seq_records.id_list, dist)
matrix.display()
if __name__ == '__main__':
main()
| [
"numpy.dot",
"numpy.zeros",
"numpy.sum"
] | [((2169, 2180), 'numpy.zeros', 'np.zeros', (['L'], {}), '(L)\n', (2177, 2180), True, 'import numpy as np\n'), ((2234, 2243), 'numpy.sum', 'np.sum', (['p'], {}), '(p)\n', (2240, 2243), True, 'import numpy as np\n'), ((2276, 2292), 'numpy.zeros', 'np.zeros', (['(L, L)'], {}), '((L, L))\n', (2284, 2292), True, 'import numpy as np\n'), ((2533, 2549), 'numpy.zeros', 'np.zeros', (['(L, L)'], {}), '((L, L))\n', (2541, 2549), True, 'import numpy as np\n'), ((2738, 2765), 'numpy.sum', 'np.sum', (['l_dist_correlations'], {}), '(l_dist_correlations)\n', (2744, 2765), True, 'import numpy as np\n'), ((2941, 2955), 'numpy.dot', 'np.dot', (['p.T', 'p'], {}), '(p.T, p)\n', (2947, 2955), True, 'import numpy as np\n'), ((2990, 3014), 'numpy.dot', 'np.dot', (['(p.T ** 2)', '(p ** 2)'], {}), '(p.T ** 2, p ** 2)\n', (2996, 3014), True, 'import numpy as np\n')] |
from time import time
import numpy as np
from scipy.stats import multivariate_normal as normal
from experiments.lnpdfs.create_target_lnpfs import build_GPR_iono_lnpdf
from sampler.elliptical_slice.bovy_mcmc.elliptical_slice import elliptical_slice as ess_update
num_dimensions = 34
prior_chol = np.eye(num_dimensions)
prior = normal(np.zeros(34), np.eye(num_dimensions))
target_lnpdf = build_GPR_iono_lnpdf()
def sample(n_samps, path=None):
samples = np.empty((n_samps, num_dimensions))
likelihoods = np.empty((n_samps))
iters = []
nfevals = []
target_lnpdf.counter = 0
timestamps = [time()]
cur_theta = prior.rvs(1)
cur_lnpdf = target_lnpdf(cur_theta, without_prior=True)
for i in range(0, n_samps):
if i % 10000 == 0:
print('iter' + str(i))
iters.append(i)
nfevals.append(target_lnpdf.counter)
timestamps.append(time())
[cur_theta, cur_lnpdf] = ess_update(cur_theta, prior_chol, target_lnpdf, pdf_params=(True,),
cur_lnpdf=cur_lnpdf)
samples[i] = cur_theta
likelihoods[i] = cur_lnpdf # without prior!
iters.append(i)
nfevals.append(target_lnpdf.counter)
timestamps.append(time())
if path is not None:
np.savez(path+"processed_data", iter=iters, samples=np.array(all_samples), fevals=np.array(nfevals), timestamps=np.array(timestamps))
print("done")
if __name__ == '__main__':
sample(1000)
| [
"numpy.empty",
"numpy.zeros",
"time.time",
"numpy.array",
"sampler.elliptical_slice.bovy_mcmc.elliptical_slice.elliptical_slice",
"experiments.lnpdfs.create_target_lnpfs.build_GPR_iono_lnpdf",
"numpy.eye"
] | [((297, 319), 'numpy.eye', 'np.eye', (['num_dimensions'], {}), '(num_dimensions)\n', (303, 319), True, 'import numpy as np\n'), ((389, 411), 'experiments.lnpdfs.create_target_lnpfs.build_GPR_iono_lnpdf', 'build_GPR_iono_lnpdf', ([], {}), '()\n', (409, 411), False, 'from experiments.lnpdfs.create_target_lnpfs import build_GPR_iono_lnpdf\n'), ((335, 347), 'numpy.zeros', 'np.zeros', (['(34)'], {}), '(34)\n', (343, 347), True, 'import numpy as np\n'), ((349, 371), 'numpy.eye', 'np.eye', (['num_dimensions'], {}), '(num_dimensions)\n', (355, 371), True, 'import numpy as np\n'), ((459, 494), 'numpy.empty', 'np.empty', (['(n_samps, num_dimensions)'], {}), '((n_samps, num_dimensions))\n', (467, 494), True, 'import numpy as np\n'), ((513, 530), 'numpy.empty', 'np.empty', (['n_samps'], {}), '(n_samps)\n', (521, 530), True, 'import numpy as np\n'), ((612, 618), 'time.time', 'time', ([], {}), '()\n', (616, 618), False, 'from time import time\n'), ((951, 1043), 'sampler.elliptical_slice.bovy_mcmc.elliptical_slice.elliptical_slice', 'ess_update', (['cur_theta', 'prior_chol', 'target_lnpdf'], {'pdf_params': '(True,)', 'cur_lnpdf': 'cur_lnpdf'}), '(cur_theta, prior_chol, target_lnpdf, pdf_params=(True,),\n cur_lnpdf=cur_lnpdf)\n', (961, 1043), True, 'from sampler.elliptical_slice.bovy_mcmc.elliptical_slice import elliptical_slice as ess_update\n'), ((1254, 1260), 'time.time', 'time', ([], {}), '()\n', (1258, 1260), False, 'from time import time\n'), ((910, 916), 'time.time', 'time', ([], {}), '()\n', (914, 916), False, 'from time import time\n'), ((1347, 1368), 'numpy.array', 'np.array', (['all_samples'], {}), '(all_samples)\n', (1355, 1368), True, 'import numpy as np\n'), ((1377, 1394), 'numpy.array', 'np.array', (['nfevals'], {}), '(nfevals)\n', (1385, 1394), True, 'import numpy as np\n'), ((1407, 1427), 'numpy.array', 'np.array', (['timestamps'], {}), '(timestamps)\n', (1415, 1427), True, 'import numpy as np\n')] |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
# ------------------------------------
import os
import datetime
import re
import shutil
from munch import munchify
from collections import OrderedDict
import numpy as np
import yaml
import torch
# pylint: disable=no-member
def _tidy_args(args):
print("Processing command-line arguments")
print("-", args)
if args.test_epoch > args.epochs:
print("- Setting test_epoch to %d" % args.epochs)
args.test_epoch = args.epochs
if args.plot_epoch > args.epochs:
print("- Setting plot_epoch to %d" % args.epochs)
args.plot_epoch = args.epochs
"""Try to fix the PyTorch and Numpy random seeds to achieve deterministic behaviour.
2020-03-31: looks like it is working."""
seed = args.seed
if seed is not None:
print("- Setting: np.random.seed({})".format(seed))
np.random.seed(seed)
print("- Setting: torch.manual_seed({})".format(seed))
torch.manual_seed(seed)
return args
def locate_yml(folder):
matches = []
for root, _, files in os.walk(folder):
for file in files:
if file.endswith(".yaml"):
matches.append(os.path.join(root, file))
return matches[0]
def _unique_dir_name(name, results_dir="Results"):
now = datetime.datetime.now().replace(microsecond=0).isoformat()
time_code = re.sub("[^A-Za-z0-9]+", "", now) # current date and time concatenated into str for logging
experiment = name + "_" + time_code
return os.path.join(results_dir, experiment)
def apply_defaults_params(config):
defaults = munchify(
{
"solver": "midpoint",
"adjoint_solver": False,
"use_laplace": False,
"n_filters": 10,
"filter_size": 10,
"pool_size": 5,
"lambda_l2": 0.001,
"lambda_l2_hidden": 0.001,
"n_hidden": 50,
"n_hidden_decoder": 50,
"n_batch": 36,
"data_format": "channels_last",
"precision_type": "constant",
"precision_alpha": 1000.0,
"precision_beta": 1.0,
"init_prec": 0.00001,
"init_latent_species": 0.001,
"transfer_func": "tanh",
"n_hidden_decoder_precisions": 20,
"n_growth_layers": 4,
"tb_gradients": False,
"plot_histograms": False,
"learning_boundaries": [250, 500],
"learning_rate": 0.01,
"learning_gamma": 0.2,
}
)
for k in config:
defaults[k] = config[k]
return defaults
def depth(group_values):
return len(set([g for g in group_values if g is not None]))
def proc_data(data_settings):
# Group-level parameter assignments for each device
groups_list = [[k, v] for k, v in data_settings.groups.items()]
data_settings.component_maps = OrderedDict()
for k, group in groups_list:
data_settings.component_maps[k] = OrderedDict(zip(data_settings.devices, group))
# Total number of group-level parameters
data_settings.device_depth = sum([depth(cm.values()) for k, cm in data_settings.component_maps.items()])
# Relevance vectors for decoding multi-hot vector into multiple one-hot vectors
data_settings.relevance_vectors = OrderedDict()
k1 = 0
for k, group in groups_list:
k2 = depth(group) + k1
rv = np.zeros(data_settings.device_depth)
rv[k1:k2] = 1.0
# print("Relevance for %s: "%k + str(rv))
if k in data_settings.default_devices:
rv[k1 + data_settings.default_devices[k]] = 0.0
data_settings.relevance_vectors[k] = rv.astype(np.float32)
k1 = k2
# Manually curated device list: map from device names to 0.0, 1.0, ...
data_settings.device_map = dict(zip(data_settings.devices, (float(v) for v in range(len(data_settings.devices)))))
# Map from device indices (as ints) to device names
data_settings.device_idx_to_device_name = dict(enumerate(data_settings.devices))
# Map from device indices (as floats) to device names
data_settings.device_lookup = {v: k for k, v in data_settings.device_map.items()}
return data_settings
def apply_defaults_data(config):
ndevices = len(config.devices)
defaults = munchify(
{
"groups": {"default": [0] * ndevices},
"default_devices": dict(),
"normalize": None,
"merge": True,
"subtract_background": True,
"separate_conditions": False,
"dtype": "float32",
}
)
for k in config:
defaults[k] = config[k]
defaults.data_dir = get_data_directory()
return proc_data(defaults)
class Config(object):
def __init__(self, args):
args = _tidy_args(args)
if args.yaml is None:
return None
with open(args.yaml, "r") as stream:
config = munchify(yaml.safe_load(stream))
# return Munch.fromYAML(stream)
self.data = apply_defaults_data(config.data)
# self.models = config.models
# self.experiments = {}
# for node, data_settings in config.experiments.items():
# self.experiments[node] = apply_defaults_data(data_settings)
self.params = apply_defaults_params(config.params)
if args.precision_hidden_layers is not None:
self.params.n_hidden_decoder_precisions = args.precision_hidden_layers
self.model = config.model
self.seed = args.seed
if (args.gpu is not None) & torch.cuda.is_available():
print("- GPU mode computation")
self.device = torch.device("cuda:" + str(args.gpu))
if self.data.dtype == "float32":
torch.set_default_tensor_type("torch.cuda.FloatTensor")
elif self.data.dtype == "float64":
torch.set_default_tensor_type("torch.cuda.DoubleTensor")
else:
raise Exception("Unknown dtype %s" % self.data.dtype)
else:
print("- CPU mode computation")
self.device = torch.device("cpu")
if self.data.dtype == "float32":
torch.set_default_tensor_type("torch.FloatTensor")
elif self.data.dtype == "float64":
torch.set_default_tensor_type("torch.DoubleTensor")
else:
raise Exception("Unknown dtype %s" % self.data.dtype)
self.trainer = None # Trainer(args, log_dir=log_dir, add_timestamp=True)
def get_data_directory():
"""Returns directory where observation datasets are stored (default: "data")"""
data_dir = os.getenv("INFERENCE_DATA_DIR")
if data_dir:
return data_dir
else:
return "data"
def get_results_directory():
"""
Returns mount directory of remote machine on local, where inference results are to be stored
(default: "results")
"""
results_dir = os.getenv("INFERENCE_RESULTS_DIR")
if results_dir:
return results_dir
else:
return "results"
class Trainer(object):
"""Collection functions and attributes for training a Model"""
def __init__(self, args, log_dir=None, add_timestamp=False):
self.results_dir = get_results_directory()
self.experiment = args.experiment
self.yaml_file_name = args.yaml
if log_dir is None:
self.create_logging_dirs(add_timestamp)
else:
self.tb_log_dir = log_dir
def _unique_dir_name(self, experiment, add_timestamp):
now = datetime.datetime.now().isoformat()
time_code = re.sub("[^A-Za-z0-9]+", "", now) # current date and time concatenated into str for logging
if add_timestamp is True:
experiment += "_" + time_code
return os.path.join(self.results_dir, experiment)
def create_logging_dirs(self, add_timestamp=False):
self.tb_log_dir = self._unique_dir_name(self.experiment, add_timestamp)
os.makedirs(self.tb_log_dir, exist_ok=True)
shutil.copyfile(
self.yaml_file_name, os.path.join(self.tb_log_dir, os.path.basename(self.yaml_file_name)),
)
| [
"numpy.random.seed",
"os.path.join",
"munch.munchify",
"os.makedirs",
"os.path.basename",
"torch.manual_seed",
"os.walk",
"numpy.zeros",
"torch.set_default_tensor_type",
"datetime.datetime.now",
"torch.cuda.is_available",
"yaml.safe_load",
"torch.device",
"collections.OrderedDict",
"re.s... | [((1152, 1167), 'os.walk', 'os.walk', (['folder'], {}), '(folder)\n', (1159, 1167), False, 'import os\n'), ((1452, 1484), 're.sub', 're.sub', (['"""[^A-Za-z0-9]+"""', '""""""', 'now'], {}), "('[^A-Za-z0-9]+', '', now)\n", (1458, 1484), False, 'import re\n'), ((1595, 1632), 'os.path.join', 'os.path.join', (['results_dir', 'experiment'], {}), '(results_dir, experiment)\n', (1607, 1632), False, 'import os\n'), ((1685, 2326), 'munch.munchify', 'munchify', (["{'solver': 'midpoint', 'adjoint_solver': False, 'use_laplace': False,\n 'n_filters': 10, 'filter_size': 10, 'pool_size': 5, 'lambda_l2': 0.001,\n 'lambda_l2_hidden': 0.001, 'n_hidden': 50, 'n_hidden_decoder': 50,\n 'n_batch': 36, 'data_format': 'channels_last', 'precision_type':\n 'constant', 'precision_alpha': 1000.0, 'precision_beta': 1.0,\n 'init_prec': 1e-05, 'init_latent_species': 0.001, 'transfer_func':\n 'tanh', 'n_hidden_decoder_precisions': 20, 'n_growth_layers': 4,\n 'tb_gradients': False, 'plot_histograms': False, 'learning_boundaries':\n [250, 500], 'learning_rate': 0.01, 'learning_gamma': 0.2}"], {}), "({'solver': 'midpoint', 'adjoint_solver': False, 'use_laplace': \n False, 'n_filters': 10, 'filter_size': 10, 'pool_size': 5, 'lambda_l2':\n 0.001, 'lambda_l2_hidden': 0.001, 'n_hidden': 50, 'n_hidden_decoder': \n 50, 'n_batch': 36, 'data_format': 'channels_last', 'precision_type':\n 'constant', 'precision_alpha': 1000.0, 'precision_beta': 1.0,\n 'init_prec': 1e-05, 'init_latent_species': 0.001, 'transfer_func':\n 'tanh', 'n_hidden_decoder_precisions': 20, 'n_growth_layers': 4,\n 'tb_gradients': False, 'plot_histograms': False, 'learning_boundaries':\n [250, 500], 'learning_rate': 0.01, 'learning_gamma': 0.2})\n", (1693, 2326), False, 'from munch import munchify\n'), ((2975, 2988), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2986, 2988), False, 'from collections import OrderedDict\n'), ((3387, 3400), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3398, 3400), False, 'from collections import OrderedDict\n'), ((6735, 6766), 'os.getenv', 'os.getenv', (['"""INFERENCE_DATA_DIR"""'], {}), "('INFERENCE_DATA_DIR')\n", (6744, 6766), False, 'import os\n'), ((7027, 7061), 'os.getenv', 'os.getenv', (['"""INFERENCE_RESULTS_DIR"""'], {}), "('INFERENCE_RESULTS_DIR')\n", (7036, 7061), False, 'import os\n'), ((950, 970), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (964, 970), True, 'import numpy as np\n'), ((1042, 1065), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (1059, 1065), False, 'import torch\n'), ((3489, 3525), 'numpy.zeros', 'np.zeros', (['data_settings.device_depth'], {}), '(data_settings.device_depth)\n', (3497, 3525), True, 'import numpy as np\n'), ((7697, 7729), 're.sub', 're.sub', (['"""[^A-Za-z0-9]+"""', '""""""', 'now'], {}), "('[^A-Za-z0-9]+', '', now)\n", (7703, 7729), False, 'import re\n'), ((7880, 7922), 'os.path.join', 'os.path.join', (['self.results_dir', 'experiment'], {}), '(self.results_dir, experiment)\n', (7892, 7922), False, 'import os\n'), ((8068, 8111), 'os.makedirs', 'os.makedirs', (['self.tb_log_dir'], {'exist_ok': '(True)'}), '(self.tb_log_dir, exist_ok=True)\n', (8079, 8111), False, 'import os\n'), ((5647, 5672), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5670, 5672), False, 'import torch\n'), ((6191, 6210), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (6203, 6210), False, 'import torch\n'), ((5022, 5044), 'yaml.safe_load', 'yaml.safe_load', (['stream'], {}), '(stream)\n', (5036, 5044), False, 'import yaml\n'), ((5843, 5898), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['"""torch.cuda.FloatTensor"""'], {}), "('torch.cuda.FloatTensor')\n", (5872, 5898), False, 'import torch\n'), ((6272, 6322), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['"""torch.FloatTensor"""'], {}), "('torch.FloatTensor')\n", (6301, 6322), False, 'import torch\n'), ((7641, 7664), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (7662, 7664), False, 'import datetime\n'), ((8200, 8237), 'os.path.basename', 'os.path.basename', (['self.yaml_file_name'], {}), '(self.yaml_file_name)\n', (8216, 8237), False, 'import os\n'), ((1266, 1290), 'os.path.join', 'os.path.join', (['root', 'file'], {}), '(root, file)\n', (1278, 1290), False, 'import os\n'), ((1377, 1400), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1398, 1400), False, 'import datetime\n'), ((5962, 6018), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['"""torch.cuda.DoubleTensor"""'], {}), "('torch.cuda.DoubleTensor')\n", (5991, 6018), False, 'import torch\n'), ((6386, 6437), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['"""torch.DoubleTensor"""'], {}), "('torch.DoubleTensor')\n", (6415, 6437), False, 'import torch\n')] |
import numpy
import pytest
from numpy.testing import assert_allclose, assert_almost_equal
from fgivenx._utils import _check_args, _normalise_weights, \
_equally_weight_samples
def test__check_args():
numpy.random.seed(0)
nfuncs = 3
logZ = numpy.random.rand(nfuncs)
f = [lambda x: x**i for i in range(nfuncs)]
nx = 100
x = numpy.linspace(0, 1, nx)
nsamps = 200
nparams = 5
samples = numpy.random.rand(nfuncs, nsamps, nparams)
weights = numpy.random.rand(nfuncs, nsamps)
# check these valid versions pass
_check_args(logZ, f, x, samples, weights)
_check_args(None, f[0], x, samples[0], weights[0])
with pytest.raises(ValueError):
_check_args(numpy.ones((2, 2)), f, x, samples, weights)
with pytest.raises(ValueError):
_check_args(logZ, f, numpy.ones((2, 2)), samples, weights)
with pytest.raises(ValueError):
_check_args(logZ, f, numpy.ones((2, 2)), samples, weights)
with pytest.raises(ValueError):
_check_args(logZ, f[1:], x, samples, weights)
with pytest.raises(ValueError):
_check_args(logZ, numpy.ones_like(f), x, samples, weights)
with pytest.raises(ValueError):
_check_args(logZ, f, x, samples[1:], weights)
with pytest.raises(ValueError):
_check_args(logZ, f, x, numpy.random.rand(nfuncs, nparams), weights)
with pytest.raises(ValueError):
_check_args(logZ, f, x, samples, weights[1:])
with pytest.raises(ValueError):
_check_args(logZ, f, x, samples, numpy.random.rand(nfuncs))
with pytest.raises(ValueError):
_check_args(logZ, f, x, samples, numpy.random.rand(nfuncs, nsamps+1))
def assert_in_ratio(a, b):
assert_almost_equal(numpy.array(a)*max(b), max(a)*numpy.array(b))
def test__normalise_weights():
numpy.random.seed(0)
nfuncs = 5
nsamps = 5000
ntrim = 500
logZ = numpy.random.rand(nfuncs)
weights = numpy.random.rand(nfuncs, nsamps)
logZ, weights = _normalise_weights(logZ, weights)
assert_almost_equal(numpy.max(weights), 1)
assert_almost_equal(numpy.max(logZ), 0)
assert_in_ratio([sum(w) for w in weights], numpy.exp(logZ))
logZ, weights = _normalise_weights(logZ, weights, ntrim)
assert_in_ratio([sum(w) for w in weights], numpy.exp(logZ))
assert_almost_equal(numpy.sum(weights), ntrim)
def test__equally_weight_samples():
numpy.random.seed(0)
nsamps = 5000
nparams = 5
samples = numpy.random.rand(nsamps, nparams)
weights = numpy.random.rand(nsamps)
with pytest.raises(ValueError):
_equally_weight_samples(samples, weights[1:])
with pytest.raises(ValueError):
_equally_weight_samples(samples, weights+1)
with pytest.raises(ValueError):
_equally_weight_samples(samples, weights-1)
samples_1 = _equally_weight_samples(samples, weights)
rand_1 = numpy.random.rand()
samples_2 = _equally_weight_samples(samples, weights)
rand_2 = numpy.random.rand()
assert_allclose(samples_1, samples_2)
assert(rand_1 != rand_2)
assert_almost_equal(len(samples_1)/sum(weights), 1, 1)
| [
"numpy.random.seed",
"numpy.sum",
"numpy.ones_like",
"fgivenx._utils._equally_weight_samples",
"fgivenx._utils._normalise_weights",
"numpy.ones",
"pytest.raises",
"numpy.max",
"numpy.array",
"numpy.exp",
"numpy.linspace",
"numpy.random.rand",
"numpy.testing.assert_allclose",
"fgivenx._util... | [((233, 253), 'numpy.random.seed', 'numpy.random.seed', (['(0)'], {}), '(0)\n', (250, 253), False, 'import numpy\n'), ((280, 305), 'numpy.random.rand', 'numpy.random.rand', (['nfuncs'], {}), '(nfuncs)\n', (297, 305), False, 'import numpy\n'), ((375, 399), 'numpy.linspace', 'numpy.linspace', (['(0)', '(1)', 'nx'], {}), '(0, 1, nx)\n', (389, 399), False, 'import numpy\n'), ((447, 489), 'numpy.random.rand', 'numpy.random.rand', (['nfuncs', 'nsamps', 'nparams'], {}), '(nfuncs, nsamps, nparams)\n', (464, 489), False, 'import numpy\n'), ((504, 537), 'numpy.random.rand', 'numpy.random.rand', (['nfuncs', 'nsamps'], {}), '(nfuncs, nsamps)\n', (521, 537), False, 'import numpy\n'), ((581, 622), 'fgivenx._utils._check_args', '_check_args', (['logZ', 'f', 'x', 'samples', 'weights'], {}), '(logZ, f, x, samples, weights)\n', (592, 622), False, 'from fgivenx._utils import _check_args, _normalise_weights, _equally_weight_samples\n'), ((627, 677), 'fgivenx._utils._check_args', '_check_args', (['None', 'f[0]', 'x', 'samples[0]', 'weights[0]'], {}), '(None, f[0], x, samples[0], weights[0])\n', (638, 677), False, 'from fgivenx._utils import _check_args, _normalise_weights, _equally_weight_samples\n'), ((1834, 1854), 'numpy.random.seed', 'numpy.random.seed', (['(0)'], {}), '(0)\n', (1851, 1854), False, 'import numpy\n'), ((1915, 1940), 'numpy.random.rand', 'numpy.random.rand', (['nfuncs'], {}), '(nfuncs)\n', (1932, 1940), False, 'import numpy\n'), ((1955, 1988), 'numpy.random.rand', 'numpy.random.rand', (['nfuncs', 'nsamps'], {}), '(nfuncs, nsamps)\n', (1972, 1988), False, 'import numpy\n'), ((2010, 2043), 'fgivenx._utils._normalise_weights', '_normalise_weights', (['logZ', 'weights'], {}), '(logZ, weights)\n', (2028, 2043), False, 'from fgivenx._utils import _check_args, _normalise_weights, _equally_weight_samples\n'), ((2221, 2261), 'fgivenx._utils._normalise_weights', '_normalise_weights', (['logZ', 'weights', 'ntrim'], {}), '(logZ, weights, ntrim)\n', (2239, 2261), False, 'from fgivenx._utils import _check_args, _normalise_weights, _equally_weight_samples\n'), ((2420, 2440), 'numpy.random.seed', 'numpy.random.seed', (['(0)'], {}), '(0)\n', (2437, 2440), False, 'import numpy\n'), ((2489, 2523), 'numpy.random.rand', 'numpy.random.rand', (['nsamps', 'nparams'], {}), '(nsamps, nparams)\n', (2506, 2523), False, 'import numpy\n'), ((2538, 2563), 'numpy.random.rand', 'numpy.random.rand', (['nsamps'], {}), '(nsamps)\n', (2555, 2563), False, 'import numpy\n'), ((2850, 2891), 'fgivenx._utils._equally_weight_samples', '_equally_weight_samples', (['samples', 'weights'], {}), '(samples, weights)\n', (2873, 2891), False, 'from fgivenx._utils import _check_args, _normalise_weights, _equally_weight_samples\n'), ((2905, 2924), 'numpy.random.rand', 'numpy.random.rand', ([], {}), '()\n', (2922, 2924), False, 'import numpy\n'), ((2941, 2982), 'fgivenx._utils._equally_weight_samples', '_equally_weight_samples', (['samples', 'weights'], {}), '(samples, weights)\n', (2964, 2982), False, 'from fgivenx._utils import _check_args, _normalise_weights, _equally_weight_samples\n'), ((2996, 3015), 'numpy.random.rand', 'numpy.random.rand', ([], {}), '()\n', (3013, 3015), False, 'import numpy\n'), ((3021, 3058), 'numpy.testing.assert_allclose', 'assert_allclose', (['samples_1', 'samples_2'], {}), '(samples_1, samples_2)\n', (3036, 3058), False, 'from numpy.testing import assert_allclose, assert_almost_equal\n'), ((688, 713), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (701, 713), False, 'import pytest\n'), ((789, 814), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (802, 814), False, 'import pytest\n'), ((893, 918), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (906, 918), False, 'import pytest\n'), ((997, 1022), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1010, 1022), False, 'import pytest\n'), ((1032, 1077), 'fgivenx._utils._check_args', '_check_args', (['logZ', 'f[1:]', 'x', 'samples', 'weights'], {}), '(logZ, f[1:], x, samples, weights)\n', (1043, 1077), False, 'from fgivenx._utils import _check_args, _normalise_weights, _equally_weight_samples\n'), ((1088, 1113), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1101, 1113), False, 'import pytest\n'), ((1192, 1217), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1205, 1217), False, 'import pytest\n'), ((1227, 1272), 'fgivenx._utils._check_args', '_check_args', (['logZ', 'f', 'x', 'samples[1:]', 'weights'], {}), '(logZ, f, x, samples[1:], weights)\n', (1238, 1272), False, 'from fgivenx._utils import _check_args, _normalise_weights, _equally_weight_samples\n'), ((1283, 1308), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1296, 1308), False, 'import pytest\n'), ((1397, 1422), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1410, 1422), False, 'import pytest\n'), ((1432, 1477), 'fgivenx._utils._check_args', '_check_args', (['logZ', 'f', 'x', 'samples', 'weights[1:]'], {}), '(logZ, f, x, samples, weights[1:])\n', (1443, 1477), False, 'from fgivenx._utils import _check_args, _normalise_weights, _equally_weight_samples\n'), ((1488, 1513), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1501, 1513), False, 'import pytest\n'), ((1593, 1618), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1606, 1618), False, 'import pytest\n'), ((2069, 2087), 'numpy.max', 'numpy.max', (['weights'], {}), '(weights)\n', (2078, 2087), False, 'import numpy\n'), ((2116, 2131), 'numpy.max', 'numpy.max', (['logZ'], {}), '(logZ)\n', (2125, 2131), False, 'import numpy\n'), ((2183, 2198), 'numpy.exp', 'numpy.exp', (['logZ'], {}), '(logZ)\n', (2192, 2198), False, 'import numpy\n'), ((2310, 2325), 'numpy.exp', 'numpy.exp', (['logZ'], {}), '(logZ)\n', (2319, 2325), False, 'import numpy\n'), ((2351, 2369), 'numpy.sum', 'numpy.sum', (['weights'], {}), '(weights)\n', (2360, 2369), False, 'import numpy\n'), ((2574, 2599), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2587, 2599), False, 'import pytest\n'), ((2609, 2654), 'fgivenx._utils._equally_weight_samples', '_equally_weight_samples', (['samples', 'weights[1:]'], {}), '(samples, weights[1:])\n', (2632, 2654), False, 'from fgivenx._utils import _check_args, _normalise_weights, _equally_weight_samples\n'), ((2665, 2690), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2678, 2690), False, 'import pytest\n'), ((2700, 2745), 'fgivenx._utils._equally_weight_samples', '_equally_weight_samples', (['samples', '(weights + 1)'], {}), '(samples, weights + 1)\n', (2723, 2745), False, 'from fgivenx._utils import _check_args, _normalise_weights, _equally_weight_samples\n'), ((2754, 2779), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2767, 2779), False, 'import pytest\n'), ((2789, 2834), 'fgivenx._utils._equally_weight_samples', '_equally_weight_samples', (['samples', '(weights - 1)'], {}), '(samples, weights - 1)\n', (2812, 2834), False, 'from fgivenx._utils import _check_args, _normalise_weights, _equally_weight_samples\n'), ((735, 753), 'numpy.ones', 'numpy.ones', (['(2, 2)'], {}), '((2, 2))\n', (745, 753), False, 'import numpy\n'), ((845, 863), 'numpy.ones', 'numpy.ones', (['(2, 2)'], {}), '((2, 2))\n', (855, 863), False, 'import numpy\n'), ((949, 967), 'numpy.ones', 'numpy.ones', (['(2, 2)'], {}), '((2, 2))\n', (959, 967), False, 'import numpy\n'), ((1141, 1159), 'numpy.ones_like', 'numpy.ones_like', (['f'], {}), '(f)\n', (1156, 1159), False, 'import numpy\n'), ((1342, 1376), 'numpy.random.rand', 'numpy.random.rand', (['nfuncs', 'nparams'], {}), '(nfuncs, nparams)\n', (1359, 1376), False, 'import numpy\n'), ((1556, 1581), 'numpy.random.rand', 'numpy.random.rand', (['nfuncs'], {}), '(nfuncs)\n', (1573, 1581), False, 'import numpy\n'), ((1661, 1698), 'numpy.random.rand', 'numpy.random.rand', (['nfuncs', '(nsamps + 1)'], {}), '(nfuncs, nsamps + 1)\n', (1678, 1698), False, 'import numpy\n'), ((1751, 1765), 'numpy.array', 'numpy.array', (['a'], {}), '(a)\n', (1762, 1765), False, 'import numpy\n'), ((1781, 1795), 'numpy.array', 'numpy.array', (['b'], {}), '(b)\n', (1792, 1795), False, 'import numpy\n')] |
import os
import datetime
from tensorflow import keras
import pandas as pd
import numpy as np
import pickle
import json
class Logic():
def __init__(self):
with open('pickle_model.pkl', 'rb') as file:
pickle_model = pickle.load(file)
json_model = keras.models.load_model('model.json')
self.model = json_model
with open('facilities.json') as json_file:
self.data = json.load(json_file)
def _prepare_data(self, facility, date):
print("DATE:", date)
facility_id, traffic, max_spots = self.data[facility]
date = date.split('-')
yr = date[0]
m = date[1]
d = date[2]
h = date[3]
time = pd.to_datetime(f"{yr}/{m}/{d}T{h}:00:00+00:00")
wd = time.weekday()
weekend = (lambda x: 0 if x < 5 else 1)(wd)
return np.asarray(pd.Series({'weekend': weekend, 'weekday': wd, 'hour': h, 'month': m, 'day': d, 'facility_id': facility_id, 'traffic': traffic, 'max_spots': max_spots})).reshape(1, -1).astype('float32')
def pred(self, facility, date):
X = self._prepare_data(facility, date)
pred = self.model.predict(X)
return int(np.argmax(pred[0]))
def detail(self, facility, date):
# do konca dnia predykcje preds double
facility = facility[0].capitalize() + facility[1:]
preds = []
d = date.split('-')
if len(d[3]) < 2:
date += "0"
date = date[:-2]
for i in range(23):
preds.append(self.pred(facility, date + str(i)))
return json.dumps({"preds":preds})
def home(self):
# facility(str), max_spots(int), taken_pred(int) in json
json_arr = []
for fac in self.data.keys():
_, __, max_spots = self.data[fac]
json_arr.append({"facility": fac,
"max_spots": int(max_spots),
"taken_all": self.pred(fac, datetime.datetime.now().strftime("%Y-%m-%d-%H"))})
return json.dumps(json_arr)
def rafcik(self):
return json.dumps([{
"facility":"1 nazwa",
"max_spots":33,
"taken_all":22
},
{
"facility":"2 nazwa",
"max_spots":44,
"taken_all":33
},
{
"facility":"3 nazwa",
"max_spots":55,
"taken_all":44
},
{
"facility":"4 nazwa",
"max_spots":66,
"taken_all":55
},
{
"facility":"5 nazwa",
"max_spots":77,
"taken_all":66
},
{
"facility":"6 nazwa",
"max_spots":88,
"taken_all":77
},
{
"facility":"7 nazwa",
"max_spots":99,
"taken_all":88
}]
)
| [
"json.load",
"tensorflow.keras.models.load_model",
"numpy.argmax",
"json.dumps",
"pickle.load",
"pandas.to_datetime",
"pandas.Series",
"datetime.datetime.now"
] | [((289, 326), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['"""model.json"""'], {}), "('model.json')\n", (312, 326), False, 'from tensorflow import keras\n'), ((719, 766), 'pandas.to_datetime', 'pd.to_datetime', (['f"""{yr}/{m}/{d}T{h}:00:00+00:00"""'], {}), "(f'{yr}/{m}/{d}T{h}:00:00+00:00')\n", (733, 766), True, 'import pandas as pd\n'), ((1598, 1626), 'json.dumps', 'json.dumps', (["{'preds': preds}"], {}), "({'preds': preds})\n", (1608, 1626), False, 'import json\n'), ((2018, 2038), 'json.dumps', 'json.dumps', (['json_arr'], {}), '(json_arr)\n', (2028, 2038), False, 'import json\n'), ((2077, 2527), 'json.dumps', 'json.dumps', (["[{'facility': '1 nazwa', 'max_spots': 33, 'taken_all': 22}, {'facility':\n '2 nazwa', 'max_spots': 44, 'taken_all': 33}, {'facility': '3 nazwa',\n 'max_spots': 55, 'taken_all': 44}, {'facility': '4 nazwa', 'max_spots':\n 66, 'taken_all': 55}, {'facility': '5 nazwa', 'max_spots': 77,\n 'taken_all': 66}, {'facility': '6 nazwa', 'max_spots': 88, 'taken_all':\n 77}, {'facility': '7 nazwa', 'max_spots': 99, 'taken_all': 88}]"], {}), "([{'facility': '1 nazwa', 'max_spots': 33, 'taken_all': 22}, {\n 'facility': '2 nazwa', 'max_spots': 44, 'taken_all': 33}, {'facility':\n '3 nazwa', 'max_spots': 55, 'taken_all': 44}, {'facility': '4 nazwa',\n 'max_spots': 66, 'taken_all': 55}, {'facility': '5 nazwa', 'max_spots':\n 77, 'taken_all': 66}, {'facility': '6 nazwa', 'max_spots': 88,\n 'taken_all': 77}, {'facility': '7 nazwa', 'max_spots': 99, 'taken_all':\n 88}])\n", (2087, 2527), False, 'import json\n'), ((241, 258), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (252, 258), False, 'import pickle\n'), ((434, 454), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (443, 454), False, 'import json\n'), ((1207, 1225), 'numpy.argmax', 'np.argmax', (['pred[0]'], {}), '(pred[0])\n', (1216, 1225), True, 'import numpy as np\n'), ((873, 1028), 'pandas.Series', 'pd.Series', (["{'weekend': weekend, 'weekday': wd, 'hour': h, 'month': m, 'day': d,\n 'facility_id': facility_id, 'traffic': traffic, 'max_spots': max_spots}"], {}), "({'weekend': weekend, 'weekday': wd, 'hour': h, 'month': m, 'day':\n d, 'facility_id': facility_id, 'traffic': traffic, 'max_spots': max_spots})\n", (882, 1028), True, 'import pandas as pd\n'), ((1952, 1975), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1973, 1975), False, 'import datetime\n')] |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import multiprocessing as mp
import threading
import time
import numpy as np
from libtorchbeast import rpcenv
from torchbeast.env_wrappers import create_env as create_other_env
# yapf: disable
parser = argparse.ArgumentParser(description='Remote Environment Server')
parser.add_argument("--pipes_basename", default="unix:/tmp/polybeast",
help="Basename for the pipes for inter-process communication. "
"Has to be of the type unix:/some/path.")
parser.add_argument('--num_servers', default=4, type=int, metavar='N',
help='Number of environment servers.')
parser.add_argument('--env', type=str, default='PongNoFrameskip-v4',
help='Gym environment.')
# For Coinrun Platforms: setting statics and dynamics to i+num_worlds holds
# out world i from training. E.g. --set-statics=7 --set-dynamics=7 means
# only worlds 0,1,3 will be used for RL+SVAE training.
parser.add_argument('--set_statics', type=int, default=0,
help='Statics for CoinRun world [0-3]')
parser.add_argument('--set_dynamics', type=int, default=0,
help='Dynamics for CoinRun world [0-3]')
parser.add_argument('--num_levels', type=int, default=500,
help='Number of levels per platforms world')
parser.add_argument('--any_custom_game', type=int, default=1,
help='Select any of the 4 custom games.')
parser.add_argument('--is_high_res', type=int, default=0,
help='Whether to render in high resolution.')
parser.add_argument('--default_zoom', type=int, default=5,
help='Default zoom for game visualization.')
# yapf: enable
class Env:
def reset(self):
print("reset called")
return np.ones((4, 84, 84), dtype=np.uint8)
def step(self, action):
frame = np.zeros((4, 84, 84), dtype=np.uint8)
return frame, 0.0, False, {} # First three mandatory.
def create_env(env_name, flags, lock=threading.Lock()):
with lock: # envs might not be threadsafe at construction time.
return create_other_env(env_name, flags)
def serve(env_name, server_address, flags):
init = Env if env_name == "Mock" else lambda: create_env(env_name, flags)
server = rpcenv.Server(init, server_address=server_address)
server.run()
if __name__ == "__main__":
flags = parser.parse_args()
if not flags.pipes_basename.startswith("unix:"):
raise Exception("--pipes_basename has to be of the form unix:/some/path.")
processes = []
for i in range(flags.num_servers):
p = mp.Process(
target=serve, args=(flags.env, f"{flags.pipes_basename}.{i}", flags), daemon=True
)
p.start()
processes.append(p)
try:
# We are only here to listen to the interrupt.
while True:
time.sleep(10)
except KeyboardInterrupt:
pass
| [
"argparse.ArgumentParser",
"torchbeast.env_wrappers.create_env",
"numpy.zeros",
"numpy.ones",
"time.sleep",
"threading.Lock",
"libtorchbeast.rpcenv.Server",
"multiprocessing.Process"
] | [((820, 884), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Remote Environment Server"""'}), "(description='Remote Environment Server')\n", (843, 884), False, 'import argparse\n'), ((2601, 2617), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (2615, 2617), False, 'import threading\n'), ((2875, 2925), 'libtorchbeast.rpcenv.Server', 'rpcenv.Server', (['init'], {'server_address': 'server_address'}), '(init, server_address=server_address)\n', (2888, 2925), False, 'from libtorchbeast import rpcenv\n'), ((2379, 2415), 'numpy.ones', 'np.ones', (['(4, 84, 84)'], {'dtype': 'np.uint8'}), '((4, 84, 84), dtype=np.uint8)\n', (2386, 2415), True, 'import numpy as np\n'), ((2461, 2498), 'numpy.zeros', 'np.zeros', (['(4, 84, 84)'], {'dtype': 'np.uint8'}), '((4, 84, 84), dtype=np.uint8)\n', (2469, 2498), True, 'import numpy as np\n'), ((2704, 2737), 'torchbeast.env_wrappers.create_env', 'create_other_env', (['env_name', 'flags'], {}), '(env_name, flags)\n', (2720, 2737), True, 'from torchbeast.env_wrappers import create_env as create_other_env\n'), ((3212, 3309), 'multiprocessing.Process', 'mp.Process', ([], {'target': 'serve', 'args': "(flags.env, f'{flags.pipes_basename}.{i}', flags)", 'daemon': '(True)'}), "(target=serve, args=(flags.env, f'{flags.pipes_basename}.{i}',\n flags), daemon=True)\n", (3222, 3309), True, 'import multiprocessing as mp\n'), ((3471, 3485), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (3481, 3485), False, 'import time\n')] |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch.nn import functional as F
from maskrcnn_benchmark.layers import smooth_l1_loss
from maskrcnn_benchmark.modeling.matcher import Matcher
from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou
from maskrcnn_benchmark.modeling.utils import cat
import cv2
import numpy as np
import os
def project_masks_on_boxes(segmentation_masks, proposals, discretization_size):
"""
Given segmentation masks and the bounding boxes corresponding
to the location of the masks in the image, this function
crops and resizes the masks in the position defined by the
boxes. This prepares the masks for them to be fed to the
loss computation as the targets.
Arguments:
segmentation_masks: an instance of SegmentationMask
proposals: an instance of BoxList
"""
masks = []
M = discretization_size
device = proposals.bbox.device
proposals = proposals.convert("xyxy")
assert segmentation_masks.size == proposals.size, "{}, {}".format(
segmentation_masks, proposals
)
# FIXME: CPU computation bottleneck, this should be parallelized
proposals = proposals.bbox.to(torch.device("cpu"))
for segmentation_mask, proposal in zip(segmentation_masks, proposals):
# crop the masks, resize them to the desired resolution and
# then convert them to the tensor representation.
# print("mask", segmentation_mask)
# print("proposal", proposal)
cropped_mask = segmentation_mask.crop(proposal)
scaled_mask = cropped_mask.resize((M, M))
mask = scaled_mask.get_mask_tensor()
# print("mask", mask.shape)
masks.append(mask)
if len(masks) == 0:
return torch.empty(0, dtype=torch.float32, device=device)
return torch.stack(masks, dim=0).to(device, dtype=torch.float32)
class MaskRCNNLossComputation(object):
def __init__(self, proposal_matcher, discretization_size, outroot):
"""
Arguments:
proposal_matcher (Matcher)
discretization_size (int)
"""
self.proposal_matcher = proposal_matcher
self.discretization_size = discretization_size
self.outroot = outroot
self.iter_mask_loss = 0
def build_tfboard_writer(self, device):
print(device)
def match_targets_to_proposals(self, proposal, target):
match_quality_matrix = boxlist_iou(target, proposal)
matched_idxs = self.proposal_matcher(match_quality_matrix)
# Mask RCNN needs "labels" and "masks "fields for creating the targets
target = target.copy_with_fields(["labels", "masks"])
# get the targets corresponding GT for each proposal
# NB: need to clamp the indices because we can have a single
# GT in the image, and matched_idxs can be -2, which goes
# out of bounds
matched_targets = target[matched_idxs.clamp(min=0)]
matched_targets.add_field("matched_idxs", matched_idxs)
return matched_targets
def prepare_targets(self, proposals, targets):
labels = []
masks = []
# print(proposals, targets)
for proposals_per_image, targets_per_image in zip(proposals, targets): # each batch?
matched_targets = self.match_targets_to_proposals(
proposals_per_image, targets_per_image
)
matched_idxs = matched_targets.get_field("matched_idxs")
labels_per_image = matched_targets.get_field("labels")
labels_per_image = labels_per_image.to(dtype=torch.int64)
# this can probably be removed, but is left here for clarity
# and completeness
neg_inds = matched_idxs == Matcher.BELOW_LOW_THRESHOLD
labels_per_image[neg_inds] = 0
# mask scores are only computed on positive samples
positive_inds = torch.nonzero(labels_per_image > 0).squeeze(1)
segmentation_masks = matched_targets.get_field("masks")
segmentation_masks = segmentation_masks[positive_inds]
positive_proposals = proposals_per_image[positive_inds]
masks_per_image = project_masks_on_boxes(
segmentation_masks, positive_proposals, self.discretization_size
)
labels.append(labels_per_image)
masks.append(masks_per_image)
return labels, masks
def __call__(self, proposals, mask_logits, targets, target_ignore=None, nega_mask_logits=None, nega_coeff=0):
"""
Arguments:
proposals (list[BoxList])
mask_logits (Tensor)
targets (list[BoxList])
Return:
mask_loss (Tensor): scalar tensor containing the loss
"""
total_seed_growing = True
# print(targets, target_ignore)
labels, mask_targets = self.prepare_targets(proposals, targets)
if not target_ignore is None:
_, mask_targets_ignore = self.prepare_targets(proposals, target_ignore)
# print(len(mask_targets), len(mask_targets_ignore))
# print(mask_targets[0].shape, mask_targets[1].shape, mask_targets_ignore[0].shape, mask_targets_ignore[1].shape)
# for m_target, m_target_ignore in zip(mask_targets, mask_targets_ignore):
# for m_t, m_t_i in zip(m_target, m_target_ignore):
# self.visualize_mask(m_t, m_t_i)
#
# # print(mask_targets, mask_targets_ignore)
labels = cat(labels, dim=0)
mask_targets = cat(mask_targets, dim=0)
is_mismatch = False
if not target_ignore is None:
mask_targets_ignore = cat(mask_targets_ignore, dim=0)
# print( mask_targets.shape, mask_targets_ignore.shape)
if mask_targets.shape != mask_targets_ignore.shape:
print("mismatch")
is_mismatch = True
# print(mask_targets.shape, mask_targets_ignore.shape)
# print(mask_targets, mask_targets_ignore)
# print(labels)
# print(mask_targets)
positive_inds = torch.nonzero(labels > 0).squeeze(1)
labels_pos = labels[positive_inds]
# torch.mean (in binary_cross_entropy_with_logits) doesn't
# accept empty tensors, so handle it separately
if mask_targets.numel() == 0:
return mask_logits.sum() * 0
# print(mask_logits[positive_inds, labels_pos].shape, mask_targets.shape, mask_targets_ignore.shape)
loss_balance = True
if target_ignore is None or is_mismatch:
if loss_balance:
mask_loss_structure = F.binary_cross_entropy_with_logits(
mask_logits[positive_inds, labels_pos], mask_targets, reduction='none'
)
mask_loss = (mask_loss_structure[mask_targets == 1]).mean() + (mask_loss_structure[mask_targets == 0]).mean()
mask_loss /= 2
else:
mask_loss = F.binary_cross_entropy_with_logits(
mask_logits[positive_inds, labels_pos], mask_targets
)
else:
seed_growing = True
if not seed_growing:
mask_logit = mask_logits[positive_inds, labels_pos]
mask_loss_structure = F.binary_cross_entropy_with_logits(
mask_logit, mask_targets, reduction='none'
)
ignore_mask = torch.ones_like(mask_loss_structure)
for m_idx, (m_target, m_target_ignore) in enumerate(zip(mask_targets, mask_targets_ignore)):
if torch.all(torch.eq(m_target, m_target_ignore)): # ignore all
ignore_mask[m_idx, :, :] = 0
else:
ignore_mask[m_idx][(m_target == 0) & (m_target_ignore == 1)] = 0
total_pixels = ignore_mask.sum()
else:
th_growing = 0.9
# print("th_growing", th_growing)
mask_logit = mask_logits[positive_inds, labels_pos] # [5, 28, 28]
fg_select = mask_targets.clone() # minimal foreground, 1: fg
bg_select = (1 - mask_targets_ignore).clone() # minimal background, 1: bg
initial_seed_fg = (fg_select == 1)
initial_seed_bg = (bg_select == 1)
before_grown_fg = fg_select.sum()
before_grown_bg = bg_select.sum()
mask_logit_sigmoid = torch.nn.functional.sigmoid(mask_logit)
fg_select[mask_logit_sigmoid > th_growing] = 1 # original fg, grown fg = 1
bg_select[mask_logit_sigmoid < (1 - th_growing)] = 1 # original bg, grown bg = 1
# fg_select and bg_select may be both 1, if:
# initial seed: foreground, but mask_logit < 1-th_growing
fg_select[initial_seed_bg] = 0
bg_select[initial_seed_fg] = 0
# now, fg_select and bg_select: disjoint
W = torch.ones([1, 1, 3, 3]).to(fg_select.device)
W[:, :, 1, 1] = 0 # consider only neighbors
fg_select_neighbor = torch.nn.functional.conv2d(fg_select.unsqueeze(1), W, stride=1, padding=1)[:, 0]
bg_select_neighbor = torch.nn.functional.conv2d(bg_select.unsqueeze(1), W, stride=1, padding=1)[:, 0]
mask_target_news = torch.zeros_like(mask_targets) - 1
mask_target_news[(fg_select == 1) & (fg_select_neighbor > 0)] = 1
mask_target_news[(bg_select == 1) & (bg_select_neighbor > 0)] = 0
# print(((mask_target_news==1).sum()/before_grown_fg).data.cpu().numpy())
total = float((mask_logit_sigmoid>0).sum())
fg = float((mask_logit_sigmoid>th_growing).sum())
bg = float((mask_logit_sigmoid<1-th_growing).sum())
# print("over", fg/total, bg/total)
ignore_mask = torch.zeros_like(mask_target_news)
ignore_mask[mask_target_news > -1] = 1
# mask_target_news[mask_target_news == -1] = 0
mask_loss_structure = F.binary_cross_entropy_with_logits(
mask_logit, mask_target_news, reduction='none'
)
total_pixels = ignore_mask.sum()
# print(ignore_mask.mean().data.cpu().numpy())
if total_pixels == 0:
mask_loss = (mask_loss_structure * ignore_mask).sum() * 0
else:
if loss_balance:
if seed_growing:
m1 = (mask_loss_structure[(mask_target_news == 1) & (ignore_mask == 1)])
m2 = (mask_loss_structure[(mask_target_news == 0) & (ignore_mask == 1)])
if m1.shape[0] == 0 or m2.shape[0] == 0:
print("nan")
mask_loss = (m1.sum()+m2.sum())*0
else:
mask_loss = m1.mean()+m2.mean()
else:
mask_loss = (mask_loss_structure[(mask_targets == 1) & (ignore_mask == 1)]).mean() \
+ (mask_loss_structure[(mask_targets == 0) & (ignore_mask == 1)]).mean()
mask_loss /= 2
else:
mask_loss = (mask_loss_structure * ignore_mask).sum() / total_pixels
# print(mask_loss)
# original
"""
mask_loss_structure = F.binary_cross_entropy_with_logits(
mask_logits[positive_inds, labels_pos], mask_targets, reduction='none'
)
ignore_mask = torch.ones_like(mask_loss_structure)
for m_idx, (m_target, m_target_ignore) in enumerate(zip(mask_targets, mask_targets_ignore)):
if torch.all(torch.eq(m_target, m_target_ignore)): # ignore all
ignore_mask[m_idx, :, :] = 0
else:
ignore_mask[m_idx][(m_target == 0) & (m_target_ignore == 1)] = 0
total_pixels = ignore_mask.sum()
if total_pixels == 0:
mask_loss = (mask_loss_structure * ignore_mask).sum() * 0
else:
mask_loss = (mask_loss_structure * ignore_mask).sum() / total_pixels
"""
# print("SUM", (mask_loss_structure * ignore_mask).sum(), mask_loss_structure.sum())
# print("MEAN", mask_loss, mask_loss_structure.mean())
# for m_target, m_target_ignore, m_ignore in zip(mask_targets, mask_targets_ignore, ignore_mask):
# self.visualize_mask(m_target, m_target_ignore, m_ignore)
# print(mask_loss.detach().cpu().numpy())
if nega_mask_logits is None:
self.iter_mask_loss += 1
return mask_loss
else:
values, _ = torch.max(nega_mask_logits[:, 1:, :, :], dim=1)
# print(values.shape)
# print(mask_loss)
# print(F.binary_cross_entropy_with_logits(
# values, torch.zeros_like(values)))
nega_loss = nega_coeff * F.binary_cross_entropy_with_logits(
values, torch.zeros_like(values))
mask_loss += nega_loss
self.iter_mask_loss += 1
return mask_loss
def visualize_mask(self, target, target_ignore, ignore_mask):
target, target_ignore, ignore_mask = target.data.cpu().numpy().astype(np.float32), target_ignore.data.cpu().numpy().astype(np.float32), ignore_mask.data.cpu().numpy().astype(np.float32)
cv2.imshow('target', target)
cv2.imshow('target_ignore', target_ignore)
cv2.imshow('ignore_mask', ignore_mask)
diff = target_ignore-target
print(diff.shape, np.sum((diff>=0)))
cv2.imshow('diff', diff)
cv2.waitKey(0)
def make_roi_mask_loss_evaluator(cfg):
matcher = Matcher(
cfg.MODEL.ROI_HEADS.FG_IOU_THRESHOLD,
cfg.MODEL.ROI_HEADS.BG_IOU_THRESHOLD,
allow_low_quality_matches=False,
)
loss_evaluator = MaskRCNNLossComputation(
matcher, cfg.MODEL.ROI_MASK_HEAD.RESOLUTION, outroot=cfg.OUTPUT_DIR
)
return loss_evaluator
| [
"torch.ones_like",
"torch.eq",
"torch.ones",
"numpy.sum",
"torch.stack",
"torch.zeros_like",
"cv2.waitKey",
"maskrcnn_benchmark.structures.boxlist_ops.boxlist_iou",
"torch.empty",
"cv2.imshow",
"torch.nonzero",
"torch.nn.functional.binary_cross_entropy_with_logits",
"torch.max",
"maskrcnn_... | [((13973, 14094), 'maskrcnn_benchmark.modeling.matcher.Matcher', 'Matcher', (['cfg.MODEL.ROI_HEADS.FG_IOU_THRESHOLD', 'cfg.MODEL.ROI_HEADS.BG_IOU_THRESHOLD'], {'allow_low_quality_matches': '(False)'}), '(cfg.MODEL.ROI_HEADS.FG_IOU_THRESHOLD, cfg.MODEL.ROI_HEADS.\n BG_IOU_THRESHOLD, allow_low_quality_matches=False)\n', (13980, 14094), False, 'from maskrcnn_benchmark.modeling.matcher import Matcher\n'), ((1231, 1250), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (1243, 1250), False, 'import torch\n'), ((1787, 1837), 'torch.empty', 'torch.empty', (['(0)'], {'dtype': 'torch.float32', 'device': 'device'}), '(0, dtype=torch.float32, device=device)\n', (1798, 1837), False, 'import torch\n'), ((2466, 2495), 'maskrcnn_benchmark.structures.boxlist_ops.boxlist_iou', 'boxlist_iou', (['target', 'proposal'], {}), '(target, proposal)\n', (2477, 2495), False, 'from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou\n'), ((5543, 5561), 'maskrcnn_benchmark.modeling.utils.cat', 'cat', (['labels'], {'dim': '(0)'}), '(labels, dim=0)\n', (5546, 5561), False, 'from maskrcnn_benchmark.modeling.utils import cat\n'), ((5585, 5609), 'maskrcnn_benchmark.modeling.utils.cat', 'cat', (['mask_targets'], {'dim': '(0)'}), '(mask_targets, dim=0)\n', (5588, 5609), False, 'from maskrcnn_benchmark.modeling.utils import cat\n'), ((13654, 13682), 'cv2.imshow', 'cv2.imshow', (['"""target"""', 'target'], {}), "('target', target)\n", (13664, 13682), False, 'import cv2\n'), ((13691, 13733), 'cv2.imshow', 'cv2.imshow', (['"""target_ignore"""', 'target_ignore'], {}), "('target_ignore', target_ignore)\n", (13701, 13733), False, 'import cv2\n'), ((13742, 13780), 'cv2.imshow', 'cv2.imshow', (['"""ignore_mask"""', 'ignore_mask'], {}), "('ignore_mask', ignore_mask)\n", (13752, 13780), False, 'import cv2\n'), ((13870, 13894), 'cv2.imshow', 'cv2.imshow', (['"""diff"""', 'diff'], {}), "('diff', diff)\n", (13880, 13894), False, 'import cv2\n'), ((13903, 13917), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (13914, 13917), False, 'import cv2\n'), ((1849, 1874), 'torch.stack', 'torch.stack', (['masks'], {'dim': '(0)'}), '(masks, dim=0)\n', (1860, 1874), False, 'import torch\n'), ((5710, 5741), 'maskrcnn_benchmark.modeling.utils.cat', 'cat', (['mask_targets_ignore'], {'dim': '(0)'}), '(mask_targets_ignore, dim=0)\n', (5713, 5741), False, 'from maskrcnn_benchmark.modeling.utils import cat\n'), ((12938, 12985), 'torch.max', 'torch.max', (['nega_mask_logits[:, 1:, :, :]'], {'dim': '(1)'}), '(nega_mask_logits[:, 1:, :, :], dim=1)\n', (12947, 12985), False, 'import torch\n'), ((13843, 13860), 'numpy.sum', 'np.sum', (['(diff >= 0)'], {}), '(diff >= 0)\n', (13849, 13860), True, 'import numpy as np\n'), ((6135, 6160), 'torch.nonzero', 'torch.nonzero', (['(labels > 0)'], {}), '(labels > 0)\n', (6148, 6160), False, 'import torch\n'), ((6672, 6782), 'torch.nn.functional.binary_cross_entropy_with_logits', 'F.binary_cross_entropy_with_logits', (['mask_logits[positive_inds, labels_pos]', 'mask_targets'], {'reduction': '"""none"""'}), "(mask_logits[positive_inds, labels_pos],\n mask_targets, reduction='none')\n", (6706, 6782), True, 'from torch.nn import functional as F\n'), ((7021, 7113), 'torch.nn.functional.binary_cross_entropy_with_logits', 'F.binary_cross_entropy_with_logits', (['mask_logits[positive_inds, labels_pos]', 'mask_targets'], {}), '(mask_logits[positive_inds, labels_pos],\n mask_targets)\n', (7055, 7113), True, 'from torch.nn import functional as F\n'), ((7335, 7413), 'torch.nn.functional.binary_cross_entropy_with_logits', 'F.binary_cross_entropy_with_logits', (['mask_logit', 'mask_targets'], {'reduction': '"""none"""'}), "(mask_logit, mask_targets, reduction='none')\n", (7369, 7413), True, 'from torch.nn import functional as F\n'), ((7482, 7518), 'torch.ones_like', 'torch.ones_like', (['mask_loss_structure'], {}), '(mask_loss_structure)\n', (7497, 7518), False, 'import torch\n'), ((8528, 8567), 'torch.nn.functional.sigmoid', 'torch.nn.functional.sigmoid', (['mask_logit'], {}), '(mask_logit)\n', (8555, 8567), False, 'import torch\n'), ((10012, 10046), 'torch.zeros_like', 'torch.zeros_like', (['mask_target_news'], {}), '(mask_target_news)\n', (10028, 10046), False, 'import torch\n'), ((10204, 10291), 'torch.nn.functional.binary_cross_entropy_with_logits', 'F.binary_cross_entropy_with_logits', (['mask_logit', 'mask_target_news'], {'reduction': '"""none"""'}), "(mask_logit, mask_target_news, reduction=\n 'none')\n", (10238, 10291), True, 'from torch.nn import functional as F\n'), ((3946, 3981), 'torch.nonzero', 'torch.nonzero', (['(labels_per_image > 0)'], {}), '(labels_per_image > 0)\n', (3959, 3981), False, 'import torch\n'), ((9446, 9476), 'torch.zeros_like', 'torch.zeros_like', (['mask_targets'], {}), '(mask_targets)\n', (9462, 9476), False, 'import torch\n'), ((13257, 13281), 'torch.zeros_like', 'torch.zeros_like', (['values'], {}), '(values)\n', (13273, 13281), False, 'import torch\n'), ((7662, 7697), 'torch.eq', 'torch.eq', (['m_target', 'm_target_ignore'], {}), '(m_target, m_target_ignore)\n', (7670, 7697), False, 'import torch\n'), ((9067, 9091), 'torch.ones', 'torch.ones', (['[1, 1, 3, 3]'], {}), '([1, 1, 3, 3])\n', (9077, 9091), False, 'import torch\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import tensorflow as tf
import numpy as np
command2int = {"up": 0, "left": 1, "right": 2}
int2command = {i[1]: i[0] for i in command2int.items()}
def run_test(testClass):
"""
Function to run all the tests from a class of tests.
:param testClass: class for testing
:type testClass: unittest.TesCase
"""
suite = unittest.TestLoader().loadTestsFromTestCase(testClass)
unittest.TextTestRunner(verbosity=2).run(suite)
def reconstruct_from_record(record_path, bound=1000):
"""
Function to transform a tf records into a tuple of
np arrays. The size is controled by the param "bound".
:param record_path: path to tf_record
:type record_path: str
:param bound: number of examples to be read
:type bound: int
:return: images, labels, shape
:rtype: np.array, np.array, tuple
"""
reconstructed_images = []
reconstructed_labels = []
record_iterator = tf.python_io.tf_record_iterator(path=record_path)
for i, string_record in enumerate(record_iterator):
if i <= bound:
example = tf.train.Example()
example.ParseFromString(string_record)
height = int(example.features.feature['height'].int64_list.value[0]) # noqa
width = int(example.features.feature['width'].int64_list.value[0]) # noqa
channels = int(example.features.feature['channels'].int64_list.value[0]) # noqa
img_string = (example.features.feature['image_raw']
.bytes_list
.value[0])
annotation_string = (example.features.feature['labels_raw']
.bytes_list
.value[0])
reconstructed_img = np.fromstring(img_string, dtype=np.uint8)
reconstructed_annotation = np.fromstring(annotation_string,
dtype=np.uint8)
reconstructed_images.append(reconstructed_img)
reconstructed_labels.append(reconstructed_annotation)
else:
break
shape = (height, width, channels)
reconstructed_images = np.array(reconstructed_images)
reconstructed_labels = np.array(reconstructed_labels)
return reconstructed_images, reconstructed_labels, shape
def accuracy_per_category(pred, label, categories):
"""
Function to give the model's accuracy for each category.
:param pred: model's prediction
:type pred: np.array
:param label: true labels
:type label: np.array
:param categories: number of categories
:type categories: int
:return: accuracy's list
:rtype: list of float
"""
pred, label = list(pred), list(label)
results = []
for cat in range(categories):
vfunc = np.vectorize(lambda x: 1 if x == cat else 0)
mapped_pred = vfunc(pred)
mapped_labels = vfunc(label)
right = float(np.dot(mapped_pred, mapped_labels))
total = np.sum(mapped_labels)
if total == 0:
results.append(0.0)
else:
results.append((right / total))
return results
def get_random_architecture_and_activations(network_sizes,
categories=3,
upper_bound=6000):
"""
Creates a random architecture list and activations list
using a list of sizes for different networks.
:param network_sizes: list of network's size
:type network_sizes: list of int
:param categories: number of categories
:type categories: int
:param upper_bound: max number of nodes per layer
:type upper_bound: int
:return: list of hidden layer sizes, list of activation functions
:rtype: list of int, list of function tensorflow
"""
activations_dict = {0: tf.nn.relu,
1: tf.nn.sigmoid,
2: tf.nn.tanh}
hidden_layers = []
activations = []
lower_bound = categories
for size in network_sizes:
hidden_sizes = []
last = upper_bound
for _ in range(size):
if lower_bound < last / 2:
new_size = np.random.randint(lower_bound, last / 2)
else:
new_size = np.random.randint(lower_bound, lower_bound + 1)
hidden_sizes.append(new_size)
last = new_size
hidden_layers.append(hidden_sizes)
for hidden in hidden_layers:
activ = np.random.randint(0, 3, len(hidden))
activ = list(map(lambda x: activations_dict[x], activ))
activations.append(activ)
for hidden in hidden_layers:
hidden.append(categories)
return hidden_layers, activations
def parser_with_normalization(tfrecord):
"""
Parser function, transforming string into
a tuple of tensors.
:param tfrecord: a single binary serialized
:type tfrecord: tf.Tensor(shape=(), dype=tf.string)
:return: image, label
:rtype: tf.Tensor(shape=(1, height*width*channels),
dtype=tf.float32),
tf.Tensor(shape=(1,), dtyṕe=tf.int32)
"""
features = {'height': tf.FixedLenFeature([], tf.int64),
'width': tf.FixedLenFeature([], tf.int64),
'channels': tf.FixedLenFeature([], tf.int64),
'image_raw': tf.FixedLenFeature([], tf.string),
'labels_raw': tf.FixedLenFeature([], tf.string)}
tfrecord_parsed = tf.parse_single_sequence_example(
tfrecord, features)
image = tf.decode_raw(tfrecord_parsed[0]['image_raw'], tf.uint8)
image = tf.cast(image, tf.float32) / 255
label = tf.decode_raw(tfrecord_parsed[0]['labels_raw'], tf.uint8)
label = tf.cast(label, tf.int32)
return image, label
def get_iterator(filename, batch_size, parser):
"""
Function to get an interator.
:param filename: path to tfrecord dataset
:type filename: str
:param batch_size: size of the batch
:type batch_size: int
:param parser: function to parse a string
into a tensor
:type parser: tf.Tensor(shape=(), dype=tf.string)
->
tf.Tensor(shape=(1, height*width*channels),
dtype=tf.float32),
tf.Tensor(shape=(1,), dtyṕe=tf.int32)
:return: data iterator
:rtype: tf.contrib.data.Iterator
"""
dataset = tf.contrib.data.TFRecordDataset(filename)
dataset = dataset.map(parser)
dataset = dataset.repeat()
dataset = dataset.batch(batch_size)
dataset = dataset.shuffle(batch_size * 2)
iterator = dataset.make_initializable_iterator()
return iterator
| [
"numpy.vectorize",
"tensorflow.contrib.data.TFRecordDataset",
"numpy.sum",
"unittest.TextTestRunner",
"tensorflow.parse_single_sequence_example",
"tensorflow.train.Example",
"tensorflow.decode_raw",
"tensorflow.cast",
"numpy.random.randint",
"numpy.array",
"unittest.TestLoader",
"tensorflow.Fi... | [((988, 1037), 'tensorflow.python_io.tf_record_iterator', 'tf.python_io.tf_record_iterator', ([], {'path': 'record_path'}), '(path=record_path)\n', (1019, 1037), True, 'import tensorflow as tf\n'), ((2263, 2293), 'numpy.array', 'np.array', (['reconstructed_images'], {}), '(reconstructed_images)\n', (2271, 2293), True, 'import numpy as np\n'), ((2321, 2351), 'numpy.array', 'np.array', (['reconstructed_labels'], {}), '(reconstructed_labels)\n', (2329, 2351), True, 'import numpy as np\n'), ((5562, 5614), 'tensorflow.parse_single_sequence_example', 'tf.parse_single_sequence_example', (['tfrecord', 'features'], {}), '(tfrecord, features)\n', (5594, 5614), True, 'import tensorflow as tf\n'), ((5637, 5693), 'tensorflow.decode_raw', 'tf.decode_raw', (["tfrecord_parsed[0]['image_raw']", 'tf.uint8'], {}), "(tfrecord_parsed[0]['image_raw'], tf.uint8)\n", (5650, 5693), True, 'import tensorflow as tf\n'), ((5752, 5809), 'tensorflow.decode_raw', 'tf.decode_raw', (["tfrecord_parsed[0]['labels_raw']", 'tf.uint8'], {}), "(tfrecord_parsed[0]['labels_raw'], tf.uint8)\n", (5765, 5809), True, 'import tensorflow as tf\n'), ((5822, 5846), 'tensorflow.cast', 'tf.cast', (['label', 'tf.int32'], {}), '(label, tf.int32)\n', (5829, 5846), True, 'import tensorflow as tf\n'), ((6501, 6542), 'tensorflow.contrib.data.TFRecordDataset', 'tf.contrib.data.TFRecordDataset', (['filename'], {}), '(filename)\n', (6532, 6542), True, 'import tensorflow as tf\n'), ((2896, 2940), 'numpy.vectorize', 'np.vectorize', (['(lambda x: 1 if x == cat else 0)'], {}), '(lambda x: 1 if x == cat else 0)\n', (2908, 2940), True, 'import numpy as np\n'), ((3086, 3107), 'numpy.sum', 'np.sum', (['mapped_labels'], {}), '(mapped_labels)\n', (3092, 3107), True, 'import numpy as np\n'), ((5255, 5287), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (5273, 5287), True, 'import tensorflow as tf\n'), ((5314, 5346), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (5332, 5346), True, 'import tensorflow as tf\n'), ((5376, 5408), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (5394, 5408), True, 'import tensorflow as tf\n'), ((5439, 5472), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.string'], {}), '([], tf.string)\n', (5457, 5472), True, 'import tensorflow as tf\n'), ((5504, 5537), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.string'], {}), '([], tf.string)\n', (5522, 5537), True, 'import tensorflow as tf\n'), ((5706, 5732), 'tensorflow.cast', 'tf.cast', (['image', 'tf.float32'], {}), '(image, tf.float32)\n', (5713, 5732), True, 'import tensorflow as tf\n'), ((401, 422), 'unittest.TestLoader', 'unittest.TestLoader', ([], {}), '()\n', (420, 422), False, 'import unittest\n'), ((460, 496), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (483, 496), False, 'import unittest\n'), ((1140, 1158), 'tensorflow.train.Example', 'tf.train.Example', ([], {}), '()\n', (1156, 1158), True, 'import tensorflow as tf\n'), ((1858, 1899), 'numpy.fromstring', 'np.fromstring', (['img_string'], {'dtype': 'np.uint8'}), '(img_string, dtype=np.uint8)\n', (1871, 1899), True, 'import numpy as np\n'), ((1939, 1987), 'numpy.fromstring', 'np.fromstring', (['annotation_string'], {'dtype': 'np.uint8'}), '(annotation_string, dtype=np.uint8)\n', (1952, 1987), True, 'import numpy as np\n'), ((3034, 3068), 'numpy.dot', 'np.dot', (['mapped_pred', 'mapped_labels'], {}), '(mapped_pred, mapped_labels)\n', (3040, 3068), True, 'import numpy as np\n'), ((4283, 4323), 'numpy.random.randint', 'np.random.randint', (['lower_bound', '(last / 2)'], {}), '(lower_bound, last / 2)\n', (4300, 4323), True, 'import numpy as np\n'), ((4369, 4416), 'numpy.random.randint', 'np.random.randint', (['lower_bound', '(lower_bound + 1)'], {}), '(lower_bound, lower_bound + 1)\n', (4386, 4416), True, 'import numpy as np\n')] |
import os
import shutil
import UQpy as uq
import numpy as np
import sys
class RunCommandLine:
def __init__(self, argparseobj):
os.system('clear')
self.args = argparseobj
################################################################################################################
# Read UQpy parameter file
os.chdir(os.path.join(os.getcwd(), self.args.Model_directory))
from UQpy import ReadInputFile
if not os.path.isfile('UQpy_Params.txt'):
print("Error: UQpy parameters file does not exist")
sys.exit()
else:
from UQpy.ReadInputFile import readfile
data = readfile('UQpy_Params.txt')
################################################################################################################
# Run UQpy
print("\nExecuting UQpy...\n")
################################################################################################################
# Run Selected method
if data['method'] in ['SuS']:
self.run_reliability(data)
elif data['method'] in ['mcs', 'lhs', 'mcmc', 'pss', 'sts']:
self.run_uq(data)
def run_uq(self, data):
# Steps:
# Initialize the sampling method (Check if UQpy_Params.txt contains all the necessary information)
# Actually run the selected sampling method in U(0, 1) and transform to the original space
# Save the samples in a .txt (or .csv) file
# If a solver (black box model) is provided then:
# If parallel processing is selected: Split the samples into chunks
# Run the model
# Save the model evaluations
# Brute-force sampling methods. Set the adaptivity flag False
self.args.Adaptive = False
################################################################################################################
# Initialize the requested UQpy method: Check if all necessary parameters are defined in the UQpyParams.txt file
from UQpy.SampleMethods import init_sm, run_sm
init_sm(data)
################################################################################################################
# Run the requested UQpy method
rvs = run_sm(data)
# Save the samples in a .txt file
np.savetxt('UQpy_Samples.txt', rvs.samples, fmt='%0.5f')
# Save the samples in a .csv file
if 'names of parameters' not in data:
import itertools
data['names of parameters'] = list(itertools.repeat('#name', rvs.samples.shape[1]))
save_csv(data['names of parameters'], rvs.samples)
################################################################################################################
# If a model is provided then run it
if self.args.Solver is not None:
RunModel(self.args.CPUs, self.args.Solver, self.args.Input_Shell_Script, self.args.Output_Shell_Script,
self.args.Adaptive, rvs.dimension)
################################################################################################################
print("\nSuccessful execution of UQpy\n\n")
def run_reliability(self, data):
from UQpy.Reliability import init_rm, run_rm
init_rm(data)
if data['method'] == 'SuS':
from UQpy.Reliability import SubsetSimulation
self.args.CPUs_flag = True
self.args.ParallelProcessing = False
self.args.Adaptive = True
sus = run_rm(self, data)
# Save the samples in a .txt file
np.savetxt('UQpy_Samples.txt', sus.samples, fmt='%0.5f')
# Save the samples in a .csv file
save_csv(data['Names of random variables'], sus.samples)
# Save the probability of failure in a .txt file
print(sus.pf)
with open('PF.txt', 'wb') as f:
np.savetxt(f, [sus.pf], fmt='%0.6f')
np.savetxt(f, [sus.cov], fmt='%0.6f')
################################################################################################################
# Move the data to directory simUQpyOut/ , delete the temp/ directory
# and terminate the program
_files = list()
_files.append('UQpy_Samples.csv')
_files.append('UQpy_Samples.txt')
_files.append('PF.txt')
for file_name in _files:
full_file_name = os.path.join(self.args.WorkingDir, file_name)
shutil.copy(full_file_name, self.args.Output_directory)
shutil.rmtree(self.args.WorkingDir)
shutil.move(self.args.Output_directory, self.args.Model_directory)
################################################################################################################
print("\nSuccessful execution of UQpy\n\n")
def save_csv(headers, param_values):
index = np.array(range(1, param_values.shape[0] + 1)).astype(int)
param_values = np.hstack((index.reshape(index.shape[0], 1), param_values))
expand_header = list()
expand_header.append('Run')
for i in range(len(headers)):
expand_header.append(headers[i])
import csv
with open('UQpy_Samples.csv', "w") as output:
writer = csv.writer(output, lineterminator='\n')
writer.writerow(expand_header)
for val in param_values:
writer.writerow(val)
def save_txt(headers, param_values):
index = np.array(range(1, param_values.shape[0] + 1)).astype(int)
param_values = np.hstack((index.reshape(index.shape[0], 1), param_values))
expand_header = list()
expand_header.append('Run')
for i in range(len(headers)):
expand_header.append(headers[i])
header = ', '.join(expand_header)
np.savetxt('UQpy_Samples.txt', param_values, header=str(header), fmt='%0.5f')
| [
"itertools.repeat",
"csv.writer",
"shutil.rmtree",
"os.getcwd",
"numpy.savetxt",
"UQpy.SampleMethods.init_sm",
"os.system",
"UQpy.Reliability.run_rm",
"shutil.copy",
"os.path.isfile",
"shutil.move",
"UQpy.SampleMethods.run_sm",
"UQpy.ReadInputFile.readfile",
"UQpy.Reliability.init_rm",
"... | [((142, 160), 'os.system', 'os.system', (['"""clear"""'], {}), "('clear')\n", (151, 160), False, 'import os\n'), ((2163, 2176), 'UQpy.SampleMethods.init_sm', 'init_sm', (['data'], {}), '(data)\n', (2170, 2176), False, 'from UQpy.SampleMethods import init_sm, run_sm\n'), ((2353, 2365), 'UQpy.SampleMethods.run_sm', 'run_sm', (['data'], {}), '(data)\n', (2359, 2365), False, 'from UQpy.SampleMethods import init_sm, run_sm\n'), ((2417, 2473), 'numpy.savetxt', 'np.savetxt', (['"""UQpy_Samples.txt"""', 'rvs.samples'], {'fmt': '"""%0.5f"""'}), "('UQpy_Samples.txt', rvs.samples, fmt='%0.5f')\n", (2427, 2473), True, 'import numpy as np\n'), ((3403, 3416), 'UQpy.Reliability.init_rm', 'init_rm', (['data'], {}), '(data)\n', (3410, 3416), False, 'from UQpy.Reliability import init_rm, run_rm\n'), ((4707, 4742), 'shutil.rmtree', 'shutil.rmtree', (['self.args.WorkingDir'], {}), '(self.args.WorkingDir)\n', (4720, 4742), False, 'import shutil\n'), ((4751, 4817), 'shutil.move', 'shutil.move', (['self.args.Output_directory', 'self.args.Model_directory'], {}), '(self.args.Output_directory, self.args.Model_directory)\n', (4762, 4817), False, 'import shutil\n'), ((5400, 5439), 'csv.writer', 'csv.writer', (['output'], {'lineterminator': '"""\n"""'}), "(output, lineterminator='\\n')\n", (5410, 5439), False, 'import csv\n'), ((479, 512), 'os.path.isfile', 'os.path.isfile', (['"""UQpy_Params.txt"""'], {}), "('UQpy_Params.txt')\n", (493, 512), False, 'import os\n'), ((590, 600), 'sys.exit', 'sys.exit', ([], {}), '()\n', (598, 600), False, 'import sys\n'), ((686, 713), 'UQpy.ReadInputFile.readfile', 'readfile', (['"""UQpy_Params.txt"""'], {}), "('UQpy_Params.txt')\n", (694, 713), False, 'from UQpy.ReadInputFile import readfile\n'), ((3655, 3673), 'UQpy.Reliability.run_rm', 'run_rm', (['self', 'data'], {}), '(self, data)\n', (3661, 3673), False, 'from UQpy.Reliability import init_rm, run_rm\n'), ((3733, 3789), 'numpy.savetxt', 'np.savetxt', (['"""UQpy_Samples.txt"""', 'sus.samples'], {'fmt': '"""%0.5f"""'}), "('UQpy_Samples.txt', sus.samples, fmt='%0.5f')\n", (3743, 3789), True, 'import numpy as np\n'), ((4584, 4629), 'os.path.join', 'os.path.join', (['self.args.WorkingDir', 'file_name'], {}), '(self.args.WorkingDir, file_name)\n', (4596, 4629), False, 'import os\n'), ((4642, 4697), 'shutil.copy', 'shutil.copy', (['full_file_name', 'self.args.Output_directory'], {}), '(full_file_name, self.args.Output_directory)\n', (4653, 4697), False, 'import shutil\n'), ((382, 393), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (391, 393), False, 'import os\n'), ((2639, 2686), 'itertools.repeat', 'itertools.repeat', (['"""#name"""', 'rvs.samples.shape[1]'], {}), "('#name', rvs.samples.shape[1])\n", (2655, 2686), False, 'import itertools\n'), ((4054, 4090), 'numpy.savetxt', 'np.savetxt', (['f', '[sus.pf]'], {'fmt': '"""%0.6f"""'}), "(f, [sus.pf], fmt='%0.6f')\n", (4064, 4090), True, 'import numpy as np\n'), ((4107, 4144), 'numpy.savetxt', 'np.savetxt', (['f', '[sus.cov]'], {'fmt': '"""%0.6f"""'}), "(f, [sus.cov], fmt='%0.6f')\n", (4117, 4144), True, 'import numpy as np\n')] |
import numpy as np
import torch
import gc
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
from summarizer import Summarizer
from summarizer.coreference_handler import CoreferenceHandler
from transformers import (BartForConditionalGeneration, BartTokenizerFast,
DistilBertConfig,
DistilBertModel, DistilBertTokenizerFast, BertModel)
from torch import nn
sum_tokenizer = BartTokenizerFast.from_pretrained(
'sshleifer/distilbart-cnn-12-6')
sum_model = BartForConditionalGeneration.from_pretrained(
'sshleifer/distilbart-cnn-12-6')
custom_config = DistilBertConfig.from_pretrained('distilbert-base-uncased')
custom_config.output_hidden_states = True
custom_tokenizer = DistilBertTokenizerFast.from_pretrained(
"distilbert-base-uncased")
custom_model = DistilBertModel.from_pretrained(
"distilbert-base-uncased", config=custom_config)
handler = CoreferenceHandler("en_core_web_sm")
def convert_to_int(rating):
if(rating == 'TRUE' or rating == "true" or rating == True):
return 0
if(rating == 'FALSE' or rating == "false" or rating == False):
return 1
if(rating == "partially false"):
return 2
else:
return 3
def convert_to_rating(int):
if(int == 0):
return "true"
if(int == 1):
return "false"
if(int == 2):
return "partially false"
else:
return "other"
def compute_metrics(pred):
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
precision, recall, f1, _ = precision_recall_fscore_support(
labels, preds, average="macro")
acc = accuracy_score(labels, preds)
return {
'accuracy': acc,
'f1': f1,
'precision': precision,
'recall': recall
}
def get_extractive_summary(extractive_sum_model, text):
sum_text = extractive_sum_model(text, ratio=0.4)
if not sum_text:
return text
else:
return sum_text
def generate_extractive_summaries(dataframe, filename):
extractive_sum_model = Summarizer(
custom_model=custom_model, custom_tokenizer=custom_tokenizer, handler=handler, random_state=43)
dataframe['text_extractive'] = dataframe.apply(
lambda x: get_extractive_summary(extractive_sum_model, x['text']), axis=1)
dataframe = dataframe[["public_id", "title",
"text", "text_extractive", "our rating"]]
dataframe.to_csv(filename, index=False)
def refresh_cuda_memory():
"""
Re-allocate all cuda memory to help alleviate fragmentation
"""
# Run a full garbage collect first so any dangling tensors are released
gc.collect()
# Then move all tensors to the CPU
locations = {}
for obj in gc.get_objects():
if not isinstance(obj, torch.Tensor):
continue
locations[obj] = obj.device
obj.data = obj.data.cpu()
if isinstance(obj, torch.nn.Parameter) and obj.grad is not None:
obj.grad.data = obj.grad.cpu()
# Now empty the cache to flush the allocator
torch.cuda.empty_cache()
# Finally move the tensors back to their associated GPUs
for tensor, device in locations.items():
tensor.data = tensor.to(device)
if isinstance(tensor, torch.nn.Parameter) and tensor.grad is not None:
tensor.grad.data = tensor.grad.to(device)
def get_abstractive_summary(text, sum_tokenizer, sum_model):
summary = ""
oom = False
if(len(text.split()) > 1000):
texts = get_split(text, 1000, 0)
inputs = sum_tokenizer(texts, return_tensors='pt', truncation="only_first", padding="max_length", max_length=1024).input_ids
# Generate Summary
try:
output = sum_model.generate(inputs.cuda(), min_length = 400, max_length = 512, top_k=100, top_p=.95, do_sample=True)
except RuntimeError:
oom = True
print("OOM Error")
if oom:
output = sum_model.cpu().generate(inputs.cpu(), min_length = 400, max_length = 512, top_k=100, top_p=.95, do_sample=True)
print("Iteration ran on cpu instead")
sum_model.cuda()
refresh_cuda_memory()
sum_texts = sum_tokenizer.batch_decode(output, skip_special_tokens=True)
summary = "".join(sum_texts)
else:
inputs = sum_tokenizer(text, return_tensors='pt', truncation=True, padding=True, max_length=1024).input_ids
# Generate Summary
try:
output = sum_model.generate(inputs.cuda(), min_length = int(len(text.split())*0.4), max_length = 512, top_k=100, top_p=.95, do_sample=True)
except RuntimeError:
oom = True
print("OOM Error")
if oom:
output = sum_model.cpu().generate(inputs.cpu(), min_length = int(len(text.split())*0.4), max_length = 512, top_k=100, top_p=.95, do_sample=True)
sum_model.cuda()
refresh_cuda_memory()
sum_texts = sum_tokenizer.batch_decode(output, skip_special_tokens=True)
summary = sum_texts[0]
return summary
def generate_abstractive_summaries(dataframe, filename):
dataframe['text_abstractive'] = dataframe.apply(
lambda x: get_abstractive_summary(x['text'], sum_tokenizer, sum_model), axis=1)
dataframe = dataframe[["public_id", "title", "text",
"text_extractive", "text_abstractive", "our rating"]]
dataframe.to_csv(filename, index=False)
def get_encodings_test(dataframe, tokenizer, summary=0):
encodings = []
for idx in range(len(dataframe)):
if(summary == 2):
sum_text = str(dataframe.iloc[idx]['title']) + \
". " + dataframe.iloc[idx]['text_extractive']
if(summary == 1):
sum_text = str(dataframe.iloc[idx]['title']) + \
". " + dataframe.iloc[idx]['text_abstractive']
else:
sum_text = str(dataframe.iloc[idx]['title']) + \
". " + dataframe.iloc[idx]['text']
# Split longer texts into documents with overlapping parts
if(len(sum_text.split()) > 500):
text_parts = get_split(sum_text, 500, 50)
tensors = tokenizer(
text_parts, padding="max_length", truncation="only_first")
encodings.append(tensors)
else:
encodings.append(
tokenizer(sum_text, padding="max_length", truncation="only_first"))
return encodings
def get_encodings(dataframe, tokenizer, summary=0):
encodings = []
labels = []
for idx in range(len(dataframe)):
if(summary == 2):
sum_text = str(dataframe.iloc[idx]['title']) + \
". " + dataframe.iloc[idx]['text_extractive']
if(summary == 1):
sum_text = str(dataframe.iloc[idx]['title']) + \
". " + dataframe.iloc[idx]['text_abstractive']
elif(summary == 0):
sum_text = str(dataframe.iloc[idx]['title']) + \
". " + dataframe.iloc[idx]['text']
# Split longer texts into documents with overlapping parts
if(len(sum_text.split()) > 500):
text_parts = get_split(sum_text, 500, 50)
tensors = tokenizer(
text_parts, padding="max_length", truncation="only_first")
encodings.append(tensors)
labels.append(dataframe.iloc[idx]['label'])
else:
encodings.append(
tokenizer(sum_text, padding="max_length", truncation="only_first"))
labels.append(dataframe.iloc[idx]['label'])
return encodings, labels
# This class represent one part of the dataset (either training, validation or test via subclass)
class CheckThatLabDataset(torch.utils.data.Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {}
internal_counter = 0
if type(self.encodings[idx]['input_ids'][0]) == list:
for encoding in self.encodings[idx]['input_ids']:
if internal_counter < 4:
if internal_counter != 0:
item['input_ids_' + str(internal_counter)] = encoding
else:
item['input_ids'] = encoding
internal_counter += 1
else:
item['input_ids'] = self.encodings[idx]['input_ids']
internal_counter = 0
if type(self.encodings[idx]['attention_mask'][0]) == list:
for encoding in self.encodings[idx]['attention_mask']:
if internal_counter < 4:
if internal_counter != 0:
item['attention_mask_' + str(internal_counter)] = encoding
else:
item['attention_mask'] = encoding
internal_counter += 1
else:
item['attention_mask'] = self.encodings[idx]['attention_mask']
for i in range(1,4):
if not 'input_ids_' + str(i) in item:
item['input_ids_' + str(i)] = np.zeros(512, dtype=int)
item['attention_mask_' + str(i)] = np.zeros(512, dtype=int)
item['labels'] = torch.tensor(self.labels[idx])
return item
def __len__(self):
return len(self.labels)
class CheckThatLabDatasetTest(torch.utils.data.Dataset):
def __init__(self, encodings):
self.encodings = encodings
def __getitem__(self, idx):
item = {}
internal_counter = 0
if type(self.encodings[idx]['input_ids'][0]) == list:
for encoding in self.encodings[idx]['input_ids']:
if internal_counter < 4:
if internal_counter != 0:
item['input_ids_' + str(internal_counter)] = encoding
else:
item['input_ids'] = encoding
internal_counter += 1
else:
item['input_ids'] = self.encodings[idx]['input_ids']
internal_counter = 0
if type(self.encodings[idx]['attention_mask'][0]) == list:
for encoding in self.encodings[idx]['attention_mask']:
if internal_counter < 4:
if internal_counter != 0:
item['attention_mask_' + str(internal_counter)] = encoding
else:
item['attention_mask'] = encoding
internal_counter += 1
else:
item['attention_mask'] = self.encodings[idx]['attention_mask']
for i in range(1,4):
if not 'input_ids_' + str(i) in item:
item['input_ids_' + str(i)] = np.zeros(512, dtype=int)
item['attention_mask_' + str(i)] = np.zeros(512, dtype=int)
return item
def __len__(self):
return len(self.encodings)
def get_split(text, split_length, stride_length=50):
l_total = []
l_partial = []
text_length = len(text.split())
partial_length = split_length - stride_length
if text_length//partial_length > 0:
n = text_length//partial_length
else:
n = 1
for w in range(n):
if w == 0:
l_partial = text.split()[:split_length]
l_total.append(" ".join(l_partial))
else:
l_partial = text.split()[w*partial_length:w *
partial_length + split_length]
l_total.append(" ".join(l_partial))
return l_total
# Basically a custom implementation of BertForSequenceClassification with the possibility to freeze the layers or the embeddings
class BertClassifier(nn.Module):
# This parameters need to be equal to the used BERT model
def __init__(self, bert_model_path=None, labels_count=4, hidden_dim=4*768, dropout=0.1, freeze_emb=False, freeze_all=False):
super().__init__()
self.config = {
'labels_count': labels_count,
'hidden_dim': hidden_dim,
'dropout': dropout,
}
self.bert = BertModel.from_pretrained("bert-base-uncased")
if(freeze_all):
# Freeze all layers -> BERT baseline without any training (train only classifier)
for param in self.bert.parameters():
param.requires_grad = False
if(freeze_emb):
# Freeze embeddings only
for param in self.bert.embeddings.parameters():
param.requires_grad = False
self.pre_classifier = nn.Linear(hidden_dim, hidden_dim)
self.classifier = nn.Linear(hidden_dim, labels_count)
self.dropout = nn.Dropout(dropout)
def forward(self, attention_mask, input_ids, labels=None, token_type_ids=None, input_ids_1=None, input_ids_2=None, input_ids_3=None, attention_mask_1=None, attention_mask_2=None, attention_mask_3=None):
tensors = []
hidden_state = self.bert(input_ids, attention_mask)[0] # (bs, seq_len, dim)
pooled_output = hidden_state[:, 0] # (bs, dim)
tensors.append(pooled_output)
hidden_state = self.bert(input_ids_1, attention_mask_1)[0] # (bs, seq_len, dim)
pooled_output = hidden_state[:, 0] # (bs, dim)
tensors.append(pooled_output)
hidden_state = self.bert(input_ids_2, attention_mask_2)[0] # (bs, seq_len, dim)
pooled_output = hidden_state[:, 0] # (bs, dim)
tensors.append(pooled_output)
hidden_state = self.bert(input_ids_3, attention_mask_3)[0] # (bs, seq_len, dim)
pooled_output = hidden_state[:, 0] # (bs, dim)
tensors.append(pooled_output)
pooled_output = torch.cat(tensors, dim=1)
pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
pooled_output = nn.ReLU()(pooled_output) # (bs, dim)
pooled_output = self.dropout(pooled_output) # (bs, dim)
logits = self.classifier(pooled_output) # (bs, num_labels)
loss = None
if labels is not None:
loss_fct = nn.CrossEntropyLoss()
loss = loss_fct(
logits.view(-1, self.config['labels_count']), labels.view(-1))
output = {}
if loss is not None:
output['loss'] = loss
output['logits'] = logits
return output
def init_full_text_model():
return BertClassifier()
def init_frozen_model():
return BertClassifier(freeze_all=True)
| [
"torch.nn.Dropout",
"sklearn.metrics.accuracy_score",
"torch.cat",
"gc.collect",
"transformers.BartTokenizerFast.from_pretrained",
"sklearn.metrics.precision_recall_fscore_support",
"transformers.BartForConditionalGeneration.from_pretrained",
"summarizer.Summarizer",
"summarizer.coreference_handler.... | [((450, 516), 'transformers.BartTokenizerFast.from_pretrained', 'BartTokenizerFast.from_pretrained', (['"""sshleifer/distilbart-cnn-12-6"""'], {}), "('sshleifer/distilbart-cnn-12-6')\n", (483, 516), False, 'from transformers import BartForConditionalGeneration, BartTokenizerFast, DistilBertConfig, DistilBertModel, DistilBertTokenizerFast, BertModel\n'), ((534, 611), 'transformers.BartForConditionalGeneration.from_pretrained', 'BartForConditionalGeneration.from_pretrained', (['"""sshleifer/distilbart-cnn-12-6"""'], {}), "('sshleifer/distilbart-cnn-12-6')\n", (578, 611), False, 'from transformers import BartForConditionalGeneration, BartTokenizerFast, DistilBertConfig, DistilBertModel, DistilBertTokenizerFast, BertModel\n'), ((634, 693), 'transformers.DistilBertConfig.from_pretrained', 'DistilBertConfig.from_pretrained', (['"""distilbert-base-uncased"""'], {}), "('distilbert-base-uncased')\n", (666, 693), False, 'from transformers import BartForConditionalGeneration, BartTokenizerFast, DistilBertConfig, DistilBertModel, DistilBertTokenizerFast, BertModel\n'), ((755, 821), 'transformers.DistilBertTokenizerFast.from_pretrained', 'DistilBertTokenizerFast.from_pretrained', (['"""distilbert-base-uncased"""'], {}), "('distilbert-base-uncased')\n", (794, 821), False, 'from transformers import BartForConditionalGeneration, BartTokenizerFast, DistilBertConfig, DistilBertModel, DistilBertTokenizerFast, BertModel\n'), ((842, 927), 'transformers.DistilBertModel.from_pretrained', 'DistilBertModel.from_pretrained', (['"""distilbert-base-uncased"""'], {'config': 'custom_config'}), "('distilbert-base-uncased', config=custom_config\n )\n", (873, 927), False, 'from transformers import BartForConditionalGeneration, BartTokenizerFast, DistilBertConfig, DistilBertModel, DistilBertTokenizerFast, BertModel\n'), ((938, 974), 'summarizer.coreference_handler.CoreferenceHandler', 'CoreferenceHandler', (['"""en_core_web_sm"""'], {}), "('en_core_web_sm')\n", (956, 974), False, 'from summarizer.coreference_handler import CoreferenceHandler\n'), ((1574, 1637), 'sklearn.metrics.precision_recall_fscore_support', 'precision_recall_fscore_support', (['labels', 'preds'], {'average': '"""macro"""'}), "(labels, preds, average='macro')\n", (1605, 1637), False, 'from sklearn.metrics import accuracy_score, precision_recall_fscore_support\n'), ((1657, 1686), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['labels', 'preds'], {}), '(labels, preds)\n', (1671, 1686), False, 'from sklearn.metrics import accuracy_score, precision_recall_fscore_support\n'), ((2077, 2187), 'summarizer.Summarizer', 'Summarizer', ([], {'custom_model': 'custom_model', 'custom_tokenizer': 'custom_tokenizer', 'handler': 'handler', 'random_state': '(43)'}), '(custom_model=custom_model, custom_tokenizer=custom_tokenizer,\n handler=handler, random_state=43)\n', (2087, 2187), False, 'from summarizer import Summarizer\n'), ((2679, 2691), 'gc.collect', 'gc.collect', ([], {}), '()\n', (2689, 2691), False, 'import gc\n'), ((2766, 2782), 'gc.get_objects', 'gc.get_objects', ([], {}), '()\n', (2780, 2782), False, 'import gc\n'), ((3092, 3116), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (3114, 3116), False, 'import torch\n'), ((9270, 9300), 'torch.tensor', 'torch.tensor', (['self.labels[idx]'], {}), '(self.labels[idx])\n', (9282, 9300), False, 'import torch\n'), ((12101, 12147), 'transformers.BertModel.from_pretrained', 'BertModel.from_pretrained', (['"""bert-base-uncased"""'], {}), "('bert-base-uncased')\n", (12126, 12147), False, 'from transformers import BartForConditionalGeneration, BartTokenizerFast, DistilBertConfig, DistilBertModel, DistilBertTokenizerFast, BertModel\n'), ((12556, 12589), 'torch.nn.Linear', 'nn.Linear', (['hidden_dim', 'hidden_dim'], {}), '(hidden_dim, hidden_dim)\n', (12565, 12589), False, 'from torch import nn\n'), ((12616, 12651), 'torch.nn.Linear', 'nn.Linear', (['hidden_dim', 'labels_count'], {}), '(hidden_dim, labels_count)\n', (12625, 12651), False, 'from torch import nn\n'), ((12675, 12694), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (12685, 12694), False, 'from torch import nn\n'), ((13689, 13714), 'torch.cat', 'torch.cat', (['tensors'], {'dim': '(1)'}), '(tensors, dim=1)\n', (13698, 13714), False, 'import torch\n'), ((13812, 13821), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (13819, 13821), False, 'from torch import nn\n'), ((14058, 14079), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (14077, 14079), False, 'from torch import nn\n'), ((9135, 9159), 'numpy.zeros', 'np.zeros', (['(512)'], {'dtype': 'int'}), '(512, dtype=int)\n', (9143, 9159), True, 'import numpy as np\n'), ((9211, 9235), 'numpy.zeros', 'np.zeros', (['(512)'], {'dtype': 'int'}), '(512, dtype=int)\n', (9219, 9235), True, 'import numpy as np\n'), ((10741, 10765), 'numpy.zeros', 'np.zeros', (['(512)'], {'dtype': 'int'}), '(512, dtype=int)\n', (10749, 10765), True, 'import numpy as np\n'), ((10817, 10841), 'numpy.zeros', 'np.zeros', (['(512)'], {'dtype': 'int'}), '(512, dtype=int)\n', (10825, 10841), True, 'import numpy as np\n')] |
import dlib
import cv2
import numpy as np
from dlib import rectangle
import dlib
import FeatureExtraction1 as ft
from sklearn.externals import joblib
predictorPath = "faceModels/shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictorPath)
def extractFacialLandmarks(faceROI, img, imgScale, predictor):
upscaledFaceROI = rectangle(int(faceROI.left() / imgScale), int(faceROI.top() / imgScale),
int(faceROI.right() / imgScale), int(faceROI.bottom() / imgScale))
# predict facial landmark points
facialLandmarks = predictor(img, upscaledFaceROI)
# make an array of the landmark points with 68 (x,y) coordinates
facialLandmarkCoords = np.array([[p.x, p.y] for p in facialLandmarks.parts()])
# transpose the landmark points so that we deal with a 2xn and not an nx2 model, it makes
# calculations easier along the way when its a row for x's and a row for y's
return facialLandmarkCoords.T
def downScaleImg(img, imgScale, maxImgSizeForDetection):
scaledImg = img
if max(img.shape) > maxImgSizeForDetection:
imgScale = maxImgSizeForDetection / float(max(img.shape))
scaledImg = cv2.resize(img, (int(img.shape[1] * imgScale), int(img.shape[0] * imgScale)))
return scaledImg, imgScale
def getFacialLandmarks(textureImage, detector, predictor, maxImgSizeForDetection=640):
imgScale = 1
downScaledImg, imgScale = downScaleImg(textureImage, imgScale, maxImgSizeForDetection)
# detect face on smaller image (much faster)
detectedFacesROI = detector(downScaledImg, 1)
# return nothing if no faces are found
if len(detectedFacesROI) == 0:
return None
# list of facial landmarks for each face in the mapped image
facialLandmarksList = []
for faceROI in detectedFacesROI:
facialLandmarks = extractFacialLandmarks(faceROI, textureImage, imgScale, predictor)
facialLandmarksList.append(facialLandmarks)
# return list of faces
return facialLandmarksList
def reshape_for_polyline(array):
# do not know what the outer dimension is, but make it an 1x2 now
return np.array(array, np.int32).reshape((-1, 1, 2))
def drawImposterLandmarks(frame, landmarks, black_image):
#black_image = np.zeros(frame.shape, np.uint8)
landmarks = landmarks.T
jaw = reshape_for_polyline(landmarks[0:17])
left_eyebrow = reshape_for_polyline(landmarks[22:27])
right_eyebrow = reshape_for_polyline(landmarks[17:22])
nose_bridge = reshape_for_polyline(landmarks[27:31])
lower_nose = reshape_for_polyline(landmarks[30:35])
left_eye = reshape_for_polyline(landmarks[42:48])
right_eye = reshape_for_polyline(landmarks[36:42])
outer_lip = reshape_for_polyline(landmarks[48:60])
inner_lip = reshape_for_polyline(landmarks[60:68])
color = (255, 255, 255)
thickness = 3
cv2.polylines(black_image, [jaw], False, color, thickness)
cv2.polylines(black_image, [left_eyebrow], False, color, thickness)
cv2.polylines(black_image, [right_eyebrow], False, color, thickness)
cv2.polylines(black_image, [nose_bridge], False, color, thickness)
cv2.polylines(black_image, [lower_nose], True, color, thickness)
cv2.polylines(black_image, [left_eye], True, color, thickness)
cv2.polylines(black_image, [right_eye], True, color, thickness)
cv2.polylines(black_image, [outer_lip], True, color, thickness)
cv2.polylines(black_image, [inner_lip], True, color, thickness)
return black_image
def getCenter(feature):
return (np.max(feature[:, 0]) + np.min(feature[:, 0]))//2, (np.max(feature[:, 1]) + np.min(feature[:, 1]))//2
def get_preprocesed_face_image(faceImg, faces):
blank_image = np.zeros(faceImg.shape, np.uint8)
for facialLandmarks2D in faces:
# draw the landmarks of all the faces detected from the source frame
landmark_image = drawImposterLandmarks(faceImg, facialLandmarks2D, blank_image)
left_eye = facialLandmarks2D.T[42:48]
center_of_left_eye = getCenter(left_eye)
right_eye = facialLandmarks2D.T[36:42]
center_of_right_eye = getCenter(right_eye)
outer_lip = facialLandmarks2D.T[48:60]
center_of_mouth = getCenter(outer_lip)
nose_ridge = facialLandmarks2D.T[27:31]
center_of_nose_ridge = getCenter(nose_ridge)
lower_nose = facialLandmarks2D.T[30:35]
center_of_lower_nose = getCenter(lower_nose)
center_of_nose = ((center_of_lower_nose[0] + center_of_nose_ridge[0]) // 2,
(center_of_lower_nose[1] + center_of_nose_ridge[1]) // 2)
face_Outline = cv2.convexHull(facialLandmarks2D.T)
face_mask = np.zeros(faceImg.shape, np.uint8)
cv2.fillConvexPoly(face_mask, face_Outline, (255, 255, 255))
masked_face = cv2.bitwise_and(faceImg, face_mask)
masked_face_feature_highlight = masked_face.copy()
masked_nose_feature_highlight = masked_face.copy()
masked_mouth_feature_highlight = masked_face.copy()
masked_left_eye_feature_highlight = masked_face.copy()
masked_right_eye_feature_highlight = masked_face.copy()
masked_feature_highlights = {'Face': None, 'Nose': None, 'Mouth': None, 'Left Eye': None, 'Right Eye': None}
# ------------------For Face---------------
cv2.circle(masked_face_feature_highlight, center_of_left_eye, 30, (0, 0, 255), -1)
cv2.circle(masked_face_feature_highlight, center_of_right_eye, 30, (0, 0, 255), -1)
cv2.circle(masked_face_feature_highlight, center_of_mouth, 40, (0, 0, 255), -1)
cv2.circle(masked_face_feature_highlight, center_of_nose, 35, (0, 0, 255), -1)
masked_feature_highlights['Face'] = masked_face_feature_highlight
# -----------------For Nose----------------
cv2.circle(masked_nose_feature_highlight, center_of_nose, 35, (0, 0, 255), -1)
masked_feature_highlights['Nose'] = masked_nose_feature_highlight
# -----------------For Mouth---------------
cv2.circle(masked_mouth_feature_highlight, center_of_mouth, 40, (0, 0, 255), -1)
masked_feature_highlights['Mouth'] = masked_mouth_feature_highlight
# -----------------For Left Eye------------
cv2.circle(masked_left_eye_feature_highlight, center_of_left_eye, 30, (0, 0, 255), -1)
masked_feature_highlights['Left Eye'] = masked_left_eye_feature_highlight
# -----------------For Right Eye------------
cv2.circle(masked_right_eye_feature_highlight, center_of_right_eye, 30, (0, 0, 255), -1)
masked_feature_highlights['Right Eye'] = masked_right_eye_feature_highlight
# find just the red part of the image
# start by making a mask
roiMasks = {'Face':None, 'Nose': None, 'Mouth': None, 'Left Eye': None, 'Right Eye': None}
roiFaceMask = cv2.inRange(masked_face_feature_highlight, (0, 0, 255), (0, 0, 255))
roiMasks['Face'] = roiFaceMask
roiMouthMask = cv2.inRange(masked_mouth_feature_highlight, (0, 0, 255), (0, 0, 255))
roiMasks['Mouth'] = roiMouthMask
roiNoseMask = cv2.inRange(masked_nose_feature_highlight, (0, 0, 255), (0, 0, 255))
roiMasks['Nose'] = roiNoseMask
roiLeftEyeMask = cv2.inRange(masked_left_eye_feature_highlight, (0, 0, 255), (0, 0, 255))
roiMasks['Left Eye'] = roiLeftEyeMask
roiRightEyeMask = cv2.inRange(masked_right_eye_feature_highlight, (0, 0, 255), (0, 0, 255))
roiMasks['Right Eye'] = roiRightEyeMask
regions_of_interest = {'Face':None, 'Nose': None, 'Mouth': None, 'Left Eye': None, 'Right Eye': None}
face_region_of_interest = cv2.bitwise_and(masked_face, masked_face, mask=roiFaceMask)
regions_of_interest['Face'] = face_region_of_interest
mouth_region_of_interest = cv2.bitwise_and(masked_face, masked_face, mask=roiMouthMask)
regions_of_interest['Mouth'] = mouth_region_of_interest
nose_region_of_interest = cv2.bitwise_and(masked_face, masked_face, mask=roiNoseMask)
regions_of_interest['Nose'] = nose_region_of_interest
left_region_of_interest = cv2.bitwise_and(masked_face, masked_face, mask=roiLeftEyeMask)
regions_of_interest['Left Eye'] = left_region_of_interest
right_region_of_interest = cv2.bitwise_and(masked_face, masked_face, mask=roiRightEyeMask)
regions_of_interest['Right Eye'] = right_region_of_interest
return faceImg, landmark_image, masked_face, masked_feature_highlights, roiMasks, regions_of_interest
def rectT0BoundingBox(rect):
x = rect.left()
y = rect.top()
w = rect.right() - x
h = rect.bottom() - y
return x, y, w, h
if __name__ == '__main__':
cap = cv2.VideoCapture(0)
lbp = ft.LBP(8, 1)
rf = joblib.load('rf.pkl')
faceEthnicity = ['White', 'Black', 'Asian', 'Indian', 'Other']
while True:
faceImg = cap.read()[1]
faceImg = cv2.flip(faceImg, 1)
faces = getFacialLandmarks(faceImg, detector, predictor, 320)
if faces is not None:
# faceImg, landmark_image, masked_face, masked_feature_highlights, roiMasks, regions_of_interest
faceImg = get_preprocesed_face_image(faceImg, faces)[0]
landmark_image = get_preprocesed_face_image(faceImg, faces)[1]
masked_face = get_preprocesed_face_image(faceImg, faces)[2]
masked_feature_highlights = get_preprocesed_face_image(faceImg, faces)[3]
roiMasks = get_preprocesed_face_image(faceImg, faces)[4]
regions_of_interest = get_preprocesed_face_image(faceImg, faces)[5]
'''
masked_face_feature_highlight = cv2.resize(masked_feature_highlights['Face'], dsize=(100, 100))
cv2.imshow("masked_face_feature_highlight", masked_face_feature_highlight)
masked_mouth_feature_highlight = cv2.resize(masked_feature_highlights['Mouth'], dsize=(100, 100))
cv2.imshow("masked_mouth_feature_highlight", masked_feature_highlights['Mouth'])
masked_nose_feature_highlight = cv2.resize(masked_feature_highlights['Nose'], dsize=(100, 100))
cv2.imshow("masked_nose_feature_highlight", masked_feature_highlights['Nose'])
masked_left_eye_feature_highlight = cv2.resize(masked_feature_highlights['Left Eye'], dsize=(100, 100))
cv2.imshow("masked_left_eye_feature_highlight", masked_feature_highlights['Left Eye'])
masked_right_eye_feature_highlight = cv2.resize(masked_feature_highlights['Right Eye'], dsize=(100, 100))
cv2.imshow("masked_right_eye_feature_highlight", masked_feature_highlights['Right Eye'])
roiFaceMask = cv2.resize(roiMasks['Face'], dsize=(100, 100))
cv2.imshow("roiFaceMask", roiFaceMask)
roiMouthMask = cv2.resize(roiMasks['Mouth'], dsize=(100, 100))
cv2.imshow("roiMouthMask", roiMasks['Mouth'])
roiNoseMask = cv2.resize(roiMasks['Nose'], dsize=(100, 100))
cv2.imshow("roiNoseMask", roiNoseMask)
roiLeftEyeMask = cv2.resize(roiMasks['Left Eye'], dsize=(100, 100))
cv2.imshow("roiLeftEyeMask", roiLeftEyeMask)
roiRightEyeMask = cv2.resize(roiMasks['Right Eye'], dsize=(100, 100))
cv2.imshow("roiRightEyeMask", roiRightEyeMask)
'''
face_region_of_interest = cv2.resize(regions_of_interest['Face'], dsize=(200, 200))
cv2.imshow("face_region_of_interest", face_region_of_interest)
mouth_region_of_interest = cv2.resize(regions_of_interest['Mouth'], dsize=(200, 200))
cv2.imshow("mouth_region_of_interest", mouth_region_of_interest)
nose_region_of_interest = cv2.resize(regions_of_interest['Nose'], dsize=(200, 200))
cv2.imshow("nose_region_of_interest", nose_region_of_interest)
left_eye_region_of_interest = cv2.resize(regions_of_interest['Left Eye'], dsize=(200, 200))
cv2.imshow("left_eye_region_of_interest", left_eye_region_of_interest)
right_eye_region_of_interest = cv2.resize(regions_of_interest['Right Eye'], dsize=(200, 200))
cv2.imshow("right_eye_region_of_interest", right_eye_region_of_interest)
faces = detector(faceImg)
if len(faces) > 0:
for face in faces:
(x, y, w, h) = rectT0BoundingBox(face)
cv2.rectangle(faceImg, (x, y), (x + w, y + h), (0, 255, 0), 1)
faceLbph = ft.getFeatureVector(face_region_of_interest, lbp).reshape(1, -1)
pred_val = rf.predict(faceLbph)[0]
prediction = faceEthnicity[pred_val]
cv2.putText(faceImg, prediction, (x, (y + h) - 10), cv2.FONT_HERSHEY_DUPLEX, .4, (255, 255, 255))
faceImg = cv2.resize(faceImg, dsize=(600, 600))
cv2.imshow("faceImg", faceImg)
landmark_image = cv2.resize(landmark_image, dsize=(300, 300))
cv2.imshow("landmark_image", landmark_image)
masked_face = cv2.resize(masked_face, dsize=(300, 300))
cv2.imshow("masked_face", masked_face)
key = cv2.waitKey(1)
if key == 27:
break
cap.release()
cv2.destroyAllWindows() | [
"cv2.bitwise_and",
"FeatureExtraction1.getFeatureVector",
"cv2.rectangle",
"cv2.imshow",
"cv2.inRange",
"dlib.shape_predictor",
"numpy.max",
"cv2.destroyAllWindows",
"cv2.resize",
"cv2.circle",
"cv2.waitKey",
"numpy.min",
"cv2.convexHull",
"dlib.get_frontal_face_detector",
"sklearn.exter... | [((229, 261), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (259, 261), False, 'import dlib\n'), ((274, 309), 'dlib.shape_predictor', 'dlib.shape_predictor', (['predictorPath'], {}), '(predictorPath)\n', (294, 309), False, 'import dlib\n'), ((2925, 2983), 'cv2.polylines', 'cv2.polylines', (['black_image', '[jaw]', '(False)', 'color', 'thickness'], {}), '(black_image, [jaw], False, color, thickness)\n', (2938, 2983), False, 'import cv2\n'), ((2988, 3055), 'cv2.polylines', 'cv2.polylines', (['black_image', '[left_eyebrow]', '(False)', 'color', 'thickness'], {}), '(black_image, [left_eyebrow], False, color, thickness)\n', (3001, 3055), False, 'import cv2\n'), ((3060, 3128), 'cv2.polylines', 'cv2.polylines', (['black_image', '[right_eyebrow]', '(False)', 'color', 'thickness'], {}), '(black_image, [right_eyebrow], False, color, thickness)\n', (3073, 3128), False, 'import cv2\n'), ((3133, 3199), 'cv2.polylines', 'cv2.polylines', (['black_image', '[nose_bridge]', '(False)', 'color', 'thickness'], {}), '(black_image, [nose_bridge], False, color, thickness)\n', (3146, 3199), False, 'import cv2\n'), ((3204, 3268), 'cv2.polylines', 'cv2.polylines', (['black_image', '[lower_nose]', '(True)', 'color', 'thickness'], {}), '(black_image, [lower_nose], True, color, thickness)\n', (3217, 3268), False, 'import cv2\n'), ((3273, 3335), 'cv2.polylines', 'cv2.polylines', (['black_image', '[left_eye]', '(True)', 'color', 'thickness'], {}), '(black_image, [left_eye], True, color, thickness)\n', (3286, 3335), False, 'import cv2\n'), ((3340, 3403), 'cv2.polylines', 'cv2.polylines', (['black_image', '[right_eye]', '(True)', 'color', 'thickness'], {}), '(black_image, [right_eye], True, color, thickness)\n', (3353, 3403), False, 'import cv2\n'), ((3408, 3471), 'cv2.polylines', 'cv2.polylines', (['black_image', '[outer_lip]', '(True)', 'color', 'thickness'], {}), '(black_image, [outer_lip], True, color, thickness)\n', (3421, 3471), False, 'import cv2\n'), ((3476, 3539), 'cv2.polylines', 'cv2.polylines', (['black_image', '[inner_lip]', '(True)', 'color', 'thickness'], {}), '(black_image, [inner_lip], True, color, thickness)\n', (3489, 3539), False, 'import cv2\n'), ((3772, 3805), 'numpy.zeros', 'np.zeros', (['faceImg.shape', 'np.uint8'], {}), '(faceImg.shape, np.uint8)\n', (3780, 3805), True, 'import numpy as np\n'), ((8784, 8803), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (8800, 8803), False, 'import cv2\n'), ((8814, 8826), 'FeatureExtraction1.LBP', 'ft.LBP', (['(8)', '(1)'], {}), '(8, 1)\n', (8820, 8826), True, 'import FeatureExtraction1 as ft\n'), ((8837, 8858), 'sklearn.externals.joblib.load', 'joblib.load', (['"""rf.pkl"""'], {}), "('rf.pkl')\n", (8848, 8858), False, 'from sklearn.externals import joblib\n'), ((13320, 13343), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (13341, 13343), False, 'import cv2\n'), ((4693, 4728), 'cv2.convexHull', 'cv2.convexHull', (['facialLandmarks2D.T'], {}), '(facialLandmarks2D.T)\n', (4707, 4728), False, 'import cv2\n'), ((4749, 4782), 'numpy.zeros', 'np.zeros', (['faceImg.shape', 'np.uint8'], {}), '(faceImg.shape, np.uint8)\n', (4757, 4782), True, 'import numpy as np\n'), ((4791, 4851), 'cv2.fillConvexPoly', 'cv2.fillConvexPoly', (['face_mask', 'face_Outline', '(255, 255, 255)'], {}), '(face_mask, face_Outline, (255, 255, 255))\n', (4809, 4851), False, 'import cv2\n'), ((4874, 4909), 'cv2.bitwise_and', 'cv2.bitwise_and', (['faceImg', 'face_mask'], {}), '(faceImg, face_mask)\n', (4889, 4909), False, 'import cv2\n'), ((5393, 5480), 'cv2.circle', 'cv2.circle', (['masked_face_feature_highlight', 'center_of_left_eye', '(30)', '(0, 0, 255)', '(-1)'], {}), '(masked_face_feature_highlight, center_of_left_eye, 30, (0, 0, \n 255), -1)\n', (5403, 5480), False, 'import cv2\n'), ((5484, 5572), 'cv2.circle', 'cv2.circle', (['masked_face_feature_highlight', 'center_of_right_eye', '(30)', '(0, 0, 255)', '(-1)'], {}), '(masked_face_feature_highlight, center_of_right_eye, 30, (0, 0, \n 255), -1)\n', (5494, 5572), False, 'import cv2\n'), ((5576, 5655), 'cv2.circle', 'cv2.circle', (['masked_face_feature_highlight', 'center_of_mouth', '(40)', '(0, 0, 255)', '(-1)'], {}), '(masked_face_feature_highlight, center_of_mouth, 40, (0, 0, 255), -1)\n', (5586, 5655), False, 'import cv2\n'), ((5664, 5742), 'cv2.circle', 'cv2.circle', (['masked_face_feature_highlight', 'center_of_nose', '(35)', '(0, 0, 255)', '(-1)'], {}), '(masked_face_feature_highlight, center_of_nose, 35, (0, 0, 255), -1)\n', (5674, 5742), False, 'import cv2\n'), ((5878, 5956), 'cv2.circle', 'cv2.circle', (['masked_nose_feature_highlight', 'center_of_nose', '(35)', '(0, 0, 255)', '(-1)'], {}), '(masked_nose_feature_highlight, center_of_nose, 35, (0, 0, 255), -1)\n', (5888, 5956), False, 'import cv2\n'), ((6092, 6177), 'cv2.circle', 'cv2.circle', (['masked_mouth_feature_highlight', 'center_of_mouth', '(40)', '(0, 0, 255)', '(-1)'], {}), '(masked_mouth_feature_highlight, center_of_mouth, 40, (0, 0, 255), -1\n )\n', (6102, 6177), False, 'import cv2\n'), ((6310, 6400), 'cv2.circle', 'cv2.circle', (['masked_left_eye_feature_highlight', 'center_of_left_eye', '(30)', '(0, 0, 255)', '(-1)'], {}), '(masked_left_eye_feature_highlight, center_of_left_eye, 30, (0, 0,\n 255), -1)\n', (6320, 6400), False, 'import cv2\n'), ((6541, 6633), 'cv2.circle', 'cv2.circle', (['masked_right_eye_feature_highlight', 'center_of_right_eye', '(30)', '(0, 0, 255)', '(-1)'], {}), '(masked_right_eye_feature_highlight, center_of_right_eye, 30, (0,\n 0, 255), -1)\n', (6551, 6633), False, 'import cv2\n'), ((6915, 6983), 'cv2.inRange', 'cv2.inRange', (['masked_face_feature_highlight', '(0, 0, 255)', '(0, 0, 255)'], {}), '(masked_face_feature_highlight, (0, 0, 255), (0, 0, 255))\n', (6926, 6983), False, 'import cv2\n'), ((7046, 7115), 'cv2.inRange', 'cv2.inRange', (['masked_mouth_feature_highlight', '(0, 0, 255)', '(0, 0, 255)'], {}), '(masked_mouth_feature_highlight, (0, 0, 255), (0, 0, 255))\n', (7057, 7115), False, 'import cv2\n'), ((7179, 7247), 'cv2.inRange', 'cv2.inRange', (['masked_nose_feature_highlight', '(0, 0, 255)', '(0, 0, 255)'], {}), '(masked_nose_feature_highlight, (0, 0, 255), (0, 0, 255))\n', (7190, 7247), False, 'import cv2\n'), ((7312, 7384), 'cv2.inRange', 'cv2.inRange', (['masked_left_eye_feature_highlight', '(0, 0, 255)', '(0, 0, 255)'], {}), '(masked_left_eye_feature_highlight, (0, 0, 255), (0, 0, 255))\n', (7323, 7384), False, 'import cv2\n'), ((7457, 7530), 'cv2.inRange', 'cv2.inRange', (['masked_right_eye_feature_highlight', '(0, 0, 255)', '(0, 0, 255)'], {}), '(masked_right_eye_feature_highlight, (0, 0, 255), (0, 0, 255))\n', (7468, 7530), False, 'import cv2\n'), ((7724, 7783), 'cv2.bitwise_and', 'cv2.bitwise_and', (['masked_face', 'masked_face'], {'mask': 'roiFaceMask'}), '(masked_face, masked_face, mask=roiFaceMask)\n', (7739, 7783), False, 'import cv2\n'), ((7881, 7941), 'cv2.bitwise_and', 'cv2.bitwise_and', (['masked_face', 'masked_face'], {'mask': 'roiMouthMask'}), '(masked_face, masked_face, mask=roiMouthMask)\n', (7896, 7941), False, 'import cv2\n'), ((8040, 8099), 'cv2.bitwise_and', 'cv2.bitwise_and', (['masked_face', 'masked_face'], {'mask': 'roiNoseMask'}), '(masked_face, masked_face, mask=roiNoseMask)\n', (8055, 8099), False, 'import cv2\n'), ((8196, 8258), 'cv2.bitwise_and', 'cv2.bitwise_and', (['masked_face', 'masked_face'], {'mask': 'roiLeftEyeMask'}), '(masked_face, masked_face, mask=roiLeftEyeMask)\n', (8211, 8258), False, 'import cv2\n'), ((8360, 8423), 'cv2.bitwise_and', 'cv2.bitwise_and', (['masked_face', 'masked_face'], {'mask': 'roiRightEyeMask'}), '(masked_face, masked_face, mask=roiRightEyeMask)\n', (8375, 8423), False, 'import cv2\n'), ((8992, 9012), 'cv2.flip', 'cv2.flip', (['faceImg', '(1)'], {}), '(faceImg, 1)\n', (9000, 9012), False, 'import cv2\n'), ((13243, 13257), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (13254, 13257), False, 'import cv2\n'), ((2191, 2216), 'numpy.array', 'np.array', (['array', 'np.int32'], {}), '(array, np.int32)\n', (2199, 2216), True, 'import numpy as np\n'), ((11442, 11499), 'cv2.resize', 'cv2.resize', (["regions_of_interest['Face']"], {'dsize': '(200, 200)'}), "(regions_of_interest['Face'], dsize=(200, 200))\n", (11452, 11499), False, 'import cv2\n'), ((11512, 11574), 'cv2.imshow', 'cv2.imshow', (['"""face_region_of_interest"""', 'face_region_of_interest'], {}), "('face_region_of_interest', face_region_of_interest)\n", (11522, 11574), False, 'import cv2\n'), ((11614, 11672), 'cv2.resize', 'cv2.resize', (["regions_of_interest['Mouth']"], {'dsize': '(200, 200)'}), "(regions_of_interest['Mouth'], dsize=(200, 200))\n", (11624, 11672), False, 'import cv2\n'), ((11685, 11749), 'cv2.imshow', 'cv2.imshow', (['"""mouth_region_of_interest"""', 'mouth_region_of_interest'], {}), "('mouth_region_of_interest', mouth_region_of_interest)\n", (11695, 11749), False, 'import cv2\n'), ((11788, 11845), 'cv2.resize', 'cv2.resize', (["regions_of_interest['Nose']"], {'dsize': '(200, 200)'}), "(regions_of_interest['Nose'], dsize=(200, 200))\n", (11798, 11845), False, 'import cv2\n'), ((11858, 11920), 'cv2.imshow', 'cv2.imshow', (['"""nose_region_of_interest"""', 'nose_region_of_interest'], {}), "('nose_region_of_interest', nose_region_of_interest)\n", (11868, 11920), False, 'import cv2\n'), ((11963, 12024), 'cv2.resize', 'cv2.resize', (["regions_of_interest['Left Eye']"], {'dsize': '(200, 200)'}), "(regions_of_interest['Left Eye'], dsize=(200, 200))\n", (11973, 12024), False, 'import cv2\n'), ((12037, 12107), 'cv2.imshow', 'cv2.imshow', (['"""left_eye_region_of_interest"""', 'left_eye_region_of_interest'], {}), "('left_eye_region_of_interest', left_eye_region_of_interest)\n", (12047, 12107), False, 'import cv2\n'), ((12151, 12213), 'cv2.resize', 'cv2.resize', (["regions_of_interest['Right Eye']"], {'dsize': '(200, 200)'}), "(regions_of_interest['Right Eye'], dsize=(200, 200))\n", (12161, 12213), False, 'import cv2\n'), ((12226, 12298), 'cv2.imshow', 'cv2.imshow', (['"""right_eye_region_of_interest"""', 'right_eye_region_of_interest'], {}), "('right_eye_region_of_interest', right_eye_region_of_interest)\n", (12236, 12298), False, 'import cv2\n'), ((12898, 12935), 'cv2.resize', 'cv2.resize', (['faceImg'], {'dsize': '(600, 600)'}), '(faceImg, dsize=(600, 600))\n', (12908, 12935), False, 'import cv2\n'), ((12948, 12978), 'cv2.imshow', 'cv2.imshow', (['"""faceImg"""', 'faceImg'], {}), "('faceImg', faceImg)\n", (12958, 12978), False, 'import cv2\n'), ((13008, 13052), 'cv2.resize', 'cv2.resize', (['landmark_image'], {'dsize': '(300, 300)'}), '(landmark_image, dsize=(300, 300))\n', (13018, 13052), False, 'import cv2\n'), ((13065, 13109), 'cv2.imshow', 'cv2.imshow', (['"""landmark_image"""', 'landmark_image'], {}), "('landmark_image', landmark_image)\n", (13075, 13109), False, 'import cv2\n'), ((13136, 13177), 'cv2.resize', 'cv2.resize', (['masked_face'], {'dsize': '(300, 300)'}), '(masked_face, dsize=(300, 300))\n', (13146, 13177), False, 'import cv2\n'), ((13190, 13228), 'cv2.imshow', 'cv2.imshow', (['"""masked_face"""', 'masked_face'], {}), "('masked_face', masked_face)\n", (13200, 13228), False, 'import cv2\n'), ((3602, 3623), 'numpy.max', 'np.max', (['feature[:, 0]'], {}), '(feature[:, 0])\n', (3608, 3623), True, 'import numpy as np\n'), ((3626, 3647), 'numpy.min', 'np.min', (['feature[:, 0]'], {}), '(feature[:, 0])\n', (3632, 3647), True, 'import numpy as np\n'), ((3654, 3675), 'numpy.max', 'np.max', (['feature[:, 1]'], {}), '(feature[:, 1])\n', (3660, 3675), True, 'import numpy as np\n'), ((3678, 3699), 'numpy.min', 'np.min', (['feature[:, 1]'], {}), '(feature[:, 1])\n', (3684, 3699), True, 'import numpy as np\n'), ((12483, 12545), 'cv2.rectangle', 'cv2.rectangle', (['faceImg', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(1)'], {}), '(faceImg, (x, y), (x + w, y + h), (0, 255, 0), 1)\n', (12496, 12545), False, 'import cv2\n'), ((12777, 12878), 'cv2.putText', 'cv2.putText', (['faceImg', 'prediction', '(x, y + h - 10)', 'cv2.FONT_HERSHEY_DUPLEX', '(0.4)', '(255, 255, 255)'], {}), '(faceImg, prediction, (x, y + h - 10), cv2.FONT_HERSHEY_DUPLEX, \n 0.4, (255, 255, 255))\n', (12788, 12878), False, 'import cv2\n'), ((12578, 12627), 'FeatureExtraction1.getFeatureVector', 'ft.getFeatureVector', (['face_region_of_interest', 'lbp'], {}), '(face_region_of_interest, lbp)\n', (12597, 12627), True, 'import FeatureExtraction1 as ft\n')] |
import numpy as np
import math
from unitreepy.robots.a1.constants import HIP_OFFSETS,MOTOR_DIRECTION
from unitreepy.robots.a1.constants import LEG_LENGTH, BASE_TO_HIPS, COM_TO_HIPS, ANGLE_DIRECTION
#HIP_COEFFICIENT = 0.08505 #original motion imitation
HIP_COEFFICIENT = 0.0838
def leg_kinematics(motor_angles, link_lengths, base_position):
q1, q2, q3 = motor_angles
r0_x, r0_y = base_position
l1, l2, l3 = link_lengths
c1, s1 = np.cos(q1), np.sin(q1)
c2, s2 = np.cos(q2), np.sin(q2)
c23, s23 = np.cos(q2 + q3), np.sin(q2 + q3)
# calculate the position of the foot
position = np.array([-l2*s2 - l3*s23 + r0_x,
-l1*c1 + (l2*c2 + l3*c23)*s1 + r0_y,
-l1*s1 - (l2*c2 + l3*c23)*c1])
# jacobian of the foot position with respect to
jacobian = np.array([[0, -l2*c2 - l3*c23, -l3*c23],
[l1*s1 + (l2*c2 + l3*c23)*c1, -
(l2*s2 + l3*s23)*s1, -l3*s1*s23],
[-l1*c1 + (l2*c2 + l3*c23)*s1, (l2*s2 + l3*s23)*c1, l3*s23*c1]])
rotation_matrix = np.array([[c23, s1*s23, -s23*c1],
[0, c1, s1],
[s23, -s1*c23, c1*c23]])
return position, jacobian, rotation_matrix
def quat_to_euler_matrix(q):
x = q[0]
y = q[1]
z = q[2]
w = q[3]
return 2*np.array([[ 0.5-y**2-z**2, x*y-w*z , x*z+w*y],
[ x*y+w*z , 0.5-x**2-z**2, y*z-w*x],
[ x*z-w*y , y*z+w*x , 0.5-x**2-y**2]])
def euler_from_quat(quat):
x,y,z,w = quat
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + y * y)
roll_x = np.arctan2(t0, t1)
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
pitch_y = np.arcsin(t2)
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 - 2.0 * (y * y + z * z)
yaw_z = np.arctan2(t3, t4)
return [roll_x, pitch_y, yaw_z]
def foot_position_hip_frame(angles, l_hip_sign=1):
theta_ab, theta_hip, theta_knee = angles[0], angles[1], angles[2]
l_up = 0.2
l_low = 0.2
l_hip = HIP_COEFFICIENT * ((-1)**(l_hip_sign + 1))
leg_distance = np.sqrt(l_up**2 + l_low**2 + 2 * l_up * l_low * np.cos(theta_knee))
eff_swing = theta_hip + theta_knee / 2
off_x_hip = -leg_distance * np.sin(eff_swing)
off_z_hip = -leg_distance * np.cos(eff_swing)
off_y_hip = l_hip
theta_ab_cos = np.cos(theta_ab)
theta_ab_sin = np.sin(theta_ab)
off_x = off_x_hip
off_y = theta_ab_cos * off_y_hip - theta_ab_sin * off_z_hip
off_z = theta_ab_sin * off_y_hip + theta_ab_cos * off_z_hip
return [off_x, off_y, off_z]
def foot_pos_hip_frame_to_joint_angle(foot_position, l_hip_sign=1):
l_up = 0.2
l_low = 0.2
l_hip = HIP_COEFFICIENT * ((-1)**(l_hip_sign + 1))
x, y, z = foot_position[0], foot_position[1], foot_position[2]
theta_knee = -math.acos(
(x**2 + y**2 + z**2 - l_hip**2 - l_low**2 - l_up**2) /
(2 * l_low * l_up))
l = math.sqrt(l_up**2 + l_low**2 + 2 * l_up * l_low * np.cos(theta_knee))
theta_hip = math.asin(-x / l) - theta_knee / 2
c1 = l_hip * y - l * math.cos(theta_hip + theta_knee / 2) * z
s1 = l * math.cos(theta_hip + theta_knee / 2) * y + l_hip * z
theta_ab = math.atan2(s1, c1)
return [theta_ab, theta_hip, theta_knee]
def motor_angles_from_foot_local_position(leg_id,
foot_local_position):
joint_position_idxs = list(range(leg_id * 3,leg_id * 3 + 3))
try:
joint_angles = foot_pos_hip_frame_to_joint_angle(
foot_local_position - HIP_OFFSETS[leg_id],
l_hip_sign=leg_id)
except:
joint_angles = [math.nan,math.nan,math.nan]
joint_angles = joint_angles*MOTOR_DIRECTION[joint_position_idxs]
return joint_position_idxs, joint_angles.tolist()
def analytical_leg_jacobian(leg_angles, sign):
"""
Computes the analytical Jacobian.
Args:
` leg_angles: a list of 3 numbers for current abduction, hip and knee angle.
sign: whether it's a left (1) or right(-1) leg.
"""
l_up = 0.2
l_low = 0.2
l_hip = HIP_COEFFICIENT* (-1)**(sign + 1)
t1, t2, t3 = leg_angles[0], leg_angles[1], leg_angles[2]
l_eff = np.sqrt(l_up**2 + l_low**2 + 2 * l_up * l_low * np.cos(t3))
t_eff = t2 + t3 / 2
J = np.zeros((3, 3))
J[0, 0] = 0
J[0, 1] = -l_eff * np.cos(t_eff)
J[0, 2] = l_low * l_up * np.sin(t3) * np.sin(t_eff) / l_eff - l_eff * np.cos(
t_eff) / 2
J[1, 0] = -l_hip * np.sin(t1) + l_eff * np.cos(t1) * np.cos(t_eff)
J[1, 1] = -l_eff * np.sin(t1) * np.sin(t_eff)
J[1, 2] = -l_low * l_up * np.sin(t1) * np.sin(t3) * np.cos(
t_eff) / l_eff - l_eff * np.sin(t1) * np.sin(t_eff) / 2
J[2, 0] = l_hip * np.cos(t1) + l_eff * np.sin(t1) * np.cos(t_eff)
J[2, 1] = l_eff * np.sin(t_eff) * np.cos(t1)
J[2, 2] = l_low * l_up * np.sin(t3) * np.cos(t1) * np.cos(
t_eff) / l_eff + l_eff * np.sin(t_eff) * np.cos(t1) / 2
return J
def compact_analytical_leg_jacobian(leg_angles, sign):
"""
Computes the analytical Jacobian in a single vector
Args:
` leg_angles: a list of 3 numbers for current abduction, hip and knee angle.
sign: whether it's a left (1) or right(-1) leg.
"""
l_up = 0.2
l_low = 0.2
l_hip = HIP_COEFFICIENT * (-1)**(sign + 1)
t1, t2, t3 = leg_angles[0], leg_angles[1], leg_angles[2]
l_eff = np.sqrt(l_up**2 + l_low**2 + 2 * l_up * l_low * np.cos(t3))
t_eff = t2 + t3 / 2
J = np.zeros(9)
J[0] = 0
J[1] = -l_eff * np.cos(t_eff)
J[2] = l_low * l_up * np.sin(t3) * np.sin(t_eff) / l_eff - l_eff * np.cos(
t_eff) / 2
J[3] = -l_hip * np.sin(t1) + l_eff * np.cos(t1) * np.cos(t_eff)
J[4] = -l_eff * np.sin(t1) * np.sin(t_eff)
J[5] = -l_low * l_up * np.sin(t1) * np.sin(t3) * np.cos(
t_eff) / l_eff - l_eff * np.sin(t1) * np.sin(t_eff) / 2
J[6] = l_hip * np.cos(t1) + l_eff * np.sin(t1) * np.cos(t_eff)
J[7] = l_eff * np.sin(t_eff) * np.cos(t1)
J[8] = l_low * l_up * np.sin(t3) * np.cos(t1) * np.cos(
t_eff) / l_eff + l_eff * np.sin(t_eff) * np.cos(t1) / 2
return J
# MAKE THINGS CLEAR
"""
There are the following CSs in robot:
Base Frame is located in the center of the robot with x axis directed forward and z axis directed upward
Hip Frame is located in the hips of the robot
COM Frame is located in Center of mass
All three CSs are different only in TRANSLATION
Angles are in radians with order [hip joint, thigh joint, calf joint]
leg_id are in range(4) for [FR LR RR RL]
"""
def angles_from_position_hip_frame(leg_id, foot_position):
l_up = LEG_LENGTH[1]
l_low = LEG_LENGTH[2]
l_hip = LEG_LENGTH[0] * ((-1)**(leg_id + 1))
x, y, z = foot_position[0], foot_position[1], foot_position[2]
# Check if solution of IK exists
try:
# Here we have two solutions for knee joint and choose the one with negative sign (more natural)
theta_knee = ANGLE_DIRECTION[leg_id,2] * -math.acos(
(x**2 + y**2 + z**2 - l_hip**2 - l_low**2 - l_up**2) /
(2 * l_low * l_up))
l = math.sqrt(l_up**2 + l_low**2 + 2 * l_up * l_low * math.cos(theta_knee))
theta_hip = ANGLE_DIRECTION[leg_id,1] * (math.asin(-x / l) - theta_knee / 2)
c1 = l_hip * y - l * math.cos(theta_hip + theta_knee / 2) * z
s1 = l * math.cos(theta_hip + theta_knee / 2) * y + l_hip * z
theta_ab = ANGLE_DIRECTION[leg_id,0] * math.atan2(s1, c1)
except:
theta_ab = math.nan
theta_hip = math.nan
theta_knee = math.nan
return [theta_ab, theta_hip, theta_knee]
def position_hip_frame_from_angles(leg_id, angles):
theta_ab, theta_hip, theta_knee = ANGLE_DIRECTION[leg_id,0] * angles[0], \
ANGLE_DIRECTION[leg_id,1] * angles[1], \
ANGLE_DIRECTION[leg_id,2] * angles[2]
l_up = LEG_LENGTH[1]
l_low = LEG_LENGTH[2]
l_hip = LEG_LENGTH[0] * ((-1)**(leg_id + 1))
leg_distance = np.sqrt(l_up**2 + l_low**2 + 2 * l_up * l_low * np.cos(theta_knee))
eff_swing = theta_hip + theta_knee / 2
off_x_hip = -leg_distance * np.sin(eff_swing)
off_z_hip = -leg_distance * np.cos(eff_swing)
off_y_hip = l_hip
theta_ab_cos = np.cos(theta_ab)
theta_ab_sin = np.sin(theta_ab)
off_x = off_x_hip
off_y = theta_ab_cos * off_y_hip - theta_ab_sin * off_z_hip
off_z = theta_ab_sin * off_y_hip + theta_ab_cos * off_z_hip
return [off_x, off_y, off_z]
def position_base_frame_from_angles(leg_id, angles):
return position_hip_frame_from_angles(leg_id, angles) + BASE_TO_HIPS[leg_id]
def position_com_frame_from_angles(leg_id, angles):
return position_hip_frame_from_angles(leg_id, angles) + COM_TO_HIPS[leg_id]
def angles_from_position_in_base_frame(leg_id, foot_position):
return angles_from_position_hip_frame(leg_id, foot_position - BASE_TO_HIPS[leg_id])
def angles_from_position_in_com_frame(leg_id, foot_position):
return angles_from_position_hip_frame(leg_id, foot_position - COM_TO_HIPS[leg_id])
def compute_jacobian(leg_id, angles):
"""
Computes the analytical Jacobian in a single vector
Args:
` leg_angles: a list of 3 numbers for current abduction, hip and knee angle.
sign: whether it's a left (1) or right(-1) leg.
"""
l_up = LEG_LENGTH[1]
l_low = LEG_LENGTH[2]
l_hip = LEG_LENGTH[0] * ((-1)**(leg_id + 1))
t1, t2, t3 = ANGLE_DIRECTION[leg_id,0] * angles[0], \
ANGLE_DIRECTION[leg_id,1] * angles[1], \
ANGLE_DIRECTION[leg_id,2] * angles[2]
l_eff = np.sqrt(l_up**2 + l_low**2 + 2 * l_up * l_low * np.cos(t3))
t_eff = t2 + t3 / 2
J = np.zeros(9)
J[0] = 0
J[1] = -l_eff * np.cos(t_eff)
J[2] = l_low * l_up * np.sin(t3) * np.sin(t_eff) / l_eff - l_eff * np.cos(
t_eff) / 2
J[3] = -l_hip * np.sin(t1) + l_eff * np.cos(t1) * np.cos(t_eff)
J[4] = -l_eff * np.sin(t1) * np.sin(t_eff)
J[5] = -l_low * l_up * np.sin(t1) * np.sin(t3) * np.cos(
t_eff) / l_eff - l_eff * np.sin(t1) * np.sin(t_eff) / 2
J[6] = l_hip * np.cos(t1) + l_eff * np.sin(t1) * np.cos(t_eff)
J[7] = l_eff * np.sin(t_eff) * np.cos(t1)
J[8] = l_low * l_up * np.sin(t3) * np.cos(t1) * np.cos(
t_eff) / l_eff + l_eff * np.sin(t_eff) * np.cos(t1) / 2
return J | [
"numpy.arctan2",
"math.asin",
"math.atan2",
"numpy.zeros",
"numpy.arcsin",
"math.acos",
"numpy.sin",
"numpy.array",
"math.cos",
"numpy.cos"
] | [((610, 735), 'numpy.array', 'np.array', (['[-l2 * s2 - l3 * s23 + r0_x, -l1 * c1 + (l2 * c2 + l3 * c23) * s1 + r0_y, -\n l1 * s1 - (l2 * c2 + l3 * c23) * c1]'], {}), '([-l2 * s2 - l3 * s23 + r0_x, -l1 * c1 + (l2 * c2 + l3 * c23) * s1 +\n r0_y, -l1 * s1 - (l2 * c2 + l3 * c23) * c1])\n', (618, 735), True, 'import numpy as np\n'), ((824, 1044), 'numpy.array', 'np.array', (['[[0, -l2 * c2 - l3 * c23, -l3 * c23], [l1 * s1 + (l2 * c2 + l3 * c23) * c1,\n -(l2 * s2 + l3 * s23) * s1, -l3 * s1 * s23], [-l1 * c1 + (l2 * c2 + l3 *\n c23) * s1, (l2 * s2 + l3 * s23) * c1, l3 * s23 * c1]]'], {}), '([[0, -l2 * c2 - l3 * c23, -l3 * c23], [l1 * s1 + (l2 * c2 + l3 *\n c23) * c1, -(l2 * s2 + l3 * s23) * s1, -l3 * s1 * s23], [-l1 * c1 + (l2 *\n c2 + l3 * c23) * s1, (l2 * s2 + l3 * s23) * c1, l3 * s23 * c1]])\n', (832, 1044), True, 'import numpy as np\n'), ((1089, 1168), 'numpy.array', 'np.array', (['[[c23, s1 * s23, -s23 * c1], [0, c1, s1], [s23, -s1 * c23, c1 * c23]]'], {}), '([[c23, s1 * s23, -s23 * c1], [0, c1, s1], [s23, -s1 * c23, c1 * c23]])\n', (1097, 1168), True, 'import numpy as np\n'), ((1685, 1703), 'numpy.arctan2', 'np.arctan2', (['t0', 't1'], {}), '(t0, t1)\n', (1695, 1703), True, 'import numpy as np\n'), ((1842, 1855), 'numpy.arcsin', 'np.arcsin', (['t2'], {}), '(t2)\n', (1851, 1855), True, 'import numpy as np\n'), ((1956, 1974), 'numpy.arctan2', 'np.arctan2', (['t3', 't4'], {}), '(t3, t4)\n', (1966, 1974), True, 'import numpy as np\n'), ((2504, 2520), 'numpy.cos', 'np.cos', (['theta_ab'], {}), '(theta_ab)\n', (2510, 2520), True, 'import numpy as np\n'), ((2540, 2556), 'numpy.sin', 'np.sin', (['theta_ab'], {}), '(theta_ab)\n', (2546, 2556), True, 'import numpy as np\n'), ((3370, 3388), 'math.atan2', 'math.atan2', (['s1', 'c1'], {}), '(s1, c1)\n', (3380, 3388), False, 'import math\n'), ((4534, 4550), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (4542, 4550), True, 'import numpy as np\n'), ((5727, 5738), 'numpy.zeros', 'np.zeros', (['(9)'], {}), '(9)\n', (5735, 5738), True, 'import numpy as np\n'), ((8557, 8573), 'numpy.cos', 'np.cos', (['theta_ab'], {}), '(theta_ab)\n', (8563, 8573), True, 'import numpy as np\n'), ((8593, 8609), 'numpy.sin', 'np.sin', (['theta_ab'], {}), '(theta_ab)\n', (8599, 8609), True, 'import numpy as np\n'), ((10039, 10050), 'numpy.zeros', 'np.zeros', (['(9)'], {}), '(9)\n', (10047, 10050), True, 'import numpy as np\n'), ((446, 456), 'numpy.cos', 'np.cos', (['q1'], {}), '(q1)\n', (452, 456), True, 'import numpy as np\n'), ((458, 468), 'numpy.sin', 'np.sin', (['q1'], {}), '(q1)\n', (464, 468), True, 'import numpy as np\n'), ((482, 492), 'numpy.cos', 'np.cos', (['q2'], {}), '(q2)\n', (488, 492), True, 'import numpy as np\n'), ((494, 504), 'numpy.sin', 'np.sin', (['q2'], {}), '(q2)\n', (500, 504), True, 'import numpy as np\n'), ((520, 535), 'numpy.cos', 'np.cos', (['(q2 + q3)'], {}), '(q2 + q3)\n', (526, 535), True, 'import numpy as np\n'), ((537, 552), 'numpy.sin', 'np.sin', (['(q2 + q3)'], {}), '(q2 + q3)\n', (543, 552), True, 'import numpy as np\n'), ((1364, 1547), 'numpy.array', 'np.array', (['[[0.5 - y ** 2 - z ** 2, x * y - w * z, x * z + w * y], [x * y + w * z, 0.5 -\n x ** 2 - z ** 2, y * z - w * x], [x * z - w * y, y * z + w * x, 0.5 - x **\n 2 - y ** 2]]'], {}), '([[0.5 - y ** 2 - z ** 2, x * y - w * z, x * z + w * y], [x * y + w *\n z, 0.5 - x ** 2 - z ** 2, y * z - w * x], [x * z - w * y, y * z + w * x,\n 0.5 - x ** 2 - y ** 2]])\n', (1372, 1547), True, 'import numpy as np\n'), ((2394, 2411), 'numpy.sin', 'np.sin', (['eff_swing'], {}), '(eff_swing)\n', (2400, 2411), True, 'import numpy as np\n'), ((2444, 2461), 'numpy.cos', 'np.cos', (['eff_swing'], {}), '(eff_swing)\n', (2450, 2461), True, 'import numpy as np\n'), ((2990, 3090), 'math.acos', 'math.acos', (['((x ** 2 + y ** 2 + z ** 2 - l_hip ** 2 - l_low ** 2 - l_up ** 2) / (2 *\n l_low * l_up))'], {}), '((x ** 2 + y ** 2 + z ** 2 - l_hip ** 2 - l_low ** 2 - l_up ** 2) /\n (2 * l_low * l_up))\n', (2999, 3090), False, 'import math\n'), ((3188, 3205), 'math.asin', 'math.asin', (['(-x / l)'], {}), '(-x / l)\n', (3197, 3205), False, 'import math\n'), ((4590, 4603), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (4596, 4603), True, 'import numpy as np\n'), ((4812, 4825), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (4818, 4825), True, 'import numpy as np\n'), ((5062, 5072), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (5068, 5072), True, 'import numpy as np\n'), ((5772, 5785), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (5778, 5785), True, 'import numpy as np\n'), ((5985, 5998), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (5991, 5998), True, 'import numpy as np\n'), ((6226, 6236), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (6232, 6236), True, 'import numpy as np\n'), ((8447, 8464), 'numpy.sin', 'np.sin', (['eff_swing'], {}), '(eff_swing)\n', (8453, 8464), True, 'import numpy as np\n'), ((8497, 8514), 'numpy.cos', 'np.cos', (['eff_swing'], {}), '(eff_swing)\n', (8503, 8514), True, 'import numpy as np\n'), ((10084, 10097), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (10090, 10097), True, 'import numpy as np\n'), ((10297, 10310), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (10303, 10310), True, 'import numpy as np\n'), ((10538, 10548), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (10544, 10548), True, 'import numpy as np\n'), ((4728, 4738), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (4734, 4738), True, 'import numpy as np\n'), ((4762, 4775), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (4768, 4775), True, 'import numpy as np\n'), ((4799, 4809), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (4805, 4809), True, 'import numpy as np\n'), ((4976, 4986), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (4982, 4986), True, 'import numpy as np\n'), ((5010, 5023), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (5016, 5023), True, 'import numpy as np\n'), ((5046, 5059), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (5052, 5059), True, 'import numpy as np\n'), ((5904, 5914), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (5910, 5914), True, 'import numpy as np\n'), ((5938, 5951), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (5944, 5951), True, 'import numpy as np\n'), ((5972, 5982), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (5978, 5982), True, 'import numpy as np\n'), ((6143, 6153), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (6149, 6153), True, 'import numpy as np\n'), ((6177, 6190), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (6183, 6190), True, 'import numpy as np\n'), ((6210, 6223), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (6216, 6223), True, 'import numpy as np\n'), ((7731, 7749), 'math.atan2', 'math.atan2', (['s1', 'c1'], {}), '(s1, c1)\n', (7741, 7749), False, 'import math\n'), ((10216, 10226), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (10222, 10226), True, 'import numpy as np\n'), ((10250, 10263), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (10256, 10263), True, 'import numpy as np\n'), ((10284, 10294), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (10290, 10294), True, 'import numpy as np\n'), ((10455, 10465), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (10461, 10465), True, 'import numpy as np\n'), ((10489, 10502), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (10495, 10502), True, 'import numpy as np\n'), ((10522, 10535), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (10528, 10535), True, 'import numpy as np\n'), ((2298, 2316), 'numpy.cos', 'np.cos', (['theta_knee'], {}), '(theta_knee)\n', (2304, 2316), True, 'import numpy as np\n'), ((3151, 3169), 'numpy.cos', 'np.cos', (['theta_knee'], {}), '(theta_knee)\n', (3157, 3169), True, 'import numpy as np\n'), ((3248, 3284), 'math.cos', 'math.cos', (['(theta_hip + theta_knee / 2)'], {}), '(theta_hip + theta_knee / 2)\n', (3256, 3284), False, 'import math\n'), ((3302, 3338), 'math.cos', 'math.cos', (['(theta_hip + theta_knee / 2)'], {}), '(theta_hip + theta_knee / 2)\n', (3310, 3338), False, 'import math\n'), ((4490, 4500), 'numpy.cos', 'np.cos', (['t3'], {}), '(t3)\n', (4496, 4500), True, 'import numpy as np\n'), ((4646, 4659), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (4652, 4659), True, 'import numpy as np\n'), ((4678, 4691), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (4684, 4691), True, 'import numpy as np\n'), ((4749, 4759), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (4755, 4759), True, 'import numpy as np\n'), ((4882, 4895), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (4888, 4895), True, 'import numpy as np\n'), ((4936, 4949), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (4942, 4949), True, 'import numpy as np\n'), ((4997, 5007), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (5003, 5007), True, 'import numpy as np\n'), ((5128, 5141), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (5134, 5141), True, 'import numpy as np\n'), ((5185, 5195), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (5191, 5195), True, 'import numpy as np\n'), ((5683, 5693), 'numpy.cos', 'np.cos', (['t3'], {}), '(t3)\n', (5689, 5693), True, 'import numpy as np\n'), ((5825, 5838), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (5831, 5838), True, 'import numpy as np\n'), ((5857, 5870), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (5863, 5870), True, 'import numpy as np\n'), ((5925, 5935), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (5931, 5935), True, 'import numpy as np\n'), ((6052, 6065), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (6058, 6065), True, 'import numpy as np\n'), ((6106, 6119), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (6112, 6119), True, 'import numpy as np\n'), ((6164, 6174), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (6170, 6174), True, 'import numpy as np\n'), ((6289, 6302), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (6295, 6302), True, 'import numpy as np\n'), ((6346, 6356), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (6352, 6356), True, 'import numpy as np\n'), ((7263, 7363), 'math.acos', 'math.acos', (['((x ** 2 + y ** 2 + z ** 2 - l_hip ** 2 - l_low ** 2 - l_up ** 2) / (2 *\n l_low * l_up))'], {}), '((x ** 2 + y ** 2 + z ** 2 - l_hip ** 2 - l_low ** 2 - l_up ** 2) /\n (2 * l_low * l_up))\n', (7272, 7363), False, 'import math\n'), ((7508, 7525), 'math.asin', 'math.asin', (['(-x / l)'], {}), '(-x / l)\n', (7517, 7525), False, 'import math\n'), ((8351, 8369), 'numpy.cos', 'np.cos', (['theta_knee'], {}), '(theta_knee)\n', (8357, 8369), True, 'import numpy as np\n'), ((9995, 10005), 'numpy.cos', 'np.cos', (['t3'], {}), '(t3)\n', (10001, 10005), True, 'import numpy as np\n'), ((10137, 10150), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (10143, 10150), True, 'import numpy as np\n'), ((10169, 10182), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (10175, 10182), True, 'import numpy as np\n'), ((10237, 10247), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (10243, 10247), True, 'import numpy as np\n'), ((10364, 10377), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (10370, 10377), True, 'import numpy as np\n'), ((10418, 10431), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (10424, 10431), True, 'import numpy as np\n'), ((10476, 10486), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (10482, 10486), True, 'import numpy as np\n'), ((10601, 10614), 'numpy.cos', 'np.cos', (['t_eff'], {}), '(t_eff)\n', (10607, 10614), True, 'import numpy as np\n'), ((10658, 10668), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (10664, 10668), True, 'import numpy as np\n'), ((4633, 4643), 'numpy.sin', 'np.sin', (['t3'], {}), '(t3)\n', (4639, 4643), True, 'import numpy as np\n'), ((4869, 4879), 'numpy.sin', 'np.sin', (['t3'], {}), '(t3)\n', (4875, 4879), True, 'import numpy as np\n'), ((4923, 4933), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (4929, 4933), True, 'import numpy as np\n'), ((5115, 5125), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (5121, 5125), True, 'import numpy as np\n'), ((5169, 5182), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (5175, 5182), True, 'import numpy as np\n'), ((5812, 5822), 'numpy.sin', 'np.sin', (['t3'], {}), '(t3)\n', (5818, 5822), True, 'import numpy as np\n'), ((6039, 6049), 'numpy.sin', 'np.sin', (['t3'], {}), '(t3)\n', (6045, 6049), True, 'import numpy as np\n'), ((6093, 6103), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (6099, 6103), True, 'import numpy as np\n'), ((6276, 6286), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (6282, 6286), True, 'import numpy as np\n'), ((6330, 6343), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (6336, 6343), True, 'import numpy as np\n'), ((7436, 7456), 'math.cos', 'math.cos', (['theta_knee'], {}), '(theta_knee)\n', (7444, 7456), False, 'import math\n'), ((7573, 7609), 'math.cos', 'math.cos', (['(theta_hip + theta_knee / 2)'], {}), '(theta_hip + theta_knee / 2)\n', (7581, 7609), False, 'import math\n'), ((7631, 7667), 'math.cos', 'math.cos', (['(theta_hip + theta_knee / 2)'], {}), '(theta_hip + theta_knee / 2)\n', (7639, 7667), False, 'import math\n'), ((10124, 10134), 'numpy.sin', 'np.sin', (['t3'], {}), '(t3)\n', (10130, 10134), True, 'import numpy as np\n'), ((10351, 10361), 'numpy.sin', 'np.sin', (['t3'], {}), '(t3)\n', (10357, 10361), True, 'import numpy as np\n'), ((10405, 10415), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (10411, 10415), True, 'import numpy as np\n'), ((10588, 10598), 'numpy.cos', 'np.cos', (['t1'], {}), '(t1)\n', (10594, 10598), True, 'import numpy as np\n'), ((10642, 10655), 'numpy.sin', 'np.sin', (['t_eff'], {}), '(t_eff)\n', (10648, 10655), True, 'import numpy as np\n'), ((4856, 4866), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (4862, 4866), True, 'import numpy as np\n'), ((5102, 5112), 'numpy.sin', 'np.sin', (['t3'], {}), '(t3)\n', (5108, 5112), True, 'import numpy as np\n'), ((6026, 6036), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (6032, 6036), True, 'import numpy as np\n'), ((6263, 6273), 'numpy.sin', 'np.sin', (['t3'], {}), '(t3)\n', (6269, 6273), True, 'import numpy as np\n'), ((10338, 10348), 'numpy.sin', 'np.sin', (['t1'], {}), '(t1)\n', (10344, 10348), True, 'import numpy as np\n'), ((10575, 10585), 'numpy.sin', 'np.sin', (['t3'], {}), '(t3)\n', (10581, 10585), True, 'import numpy as np\n')] |
## Copyright 2020 UT-Battelle, LLC. See LICENSE.txt for more information.
###
# @author <NAME>, <NAME>, <NAME>, <NAME>
# <EMAIL>
#
# Modification:
# Baseline code
# Date: Apr, 2020
# **************************************************************************
###
import numpy as np
import re
import pdb
import pandas as pd
from deffe_thread import *
from deffe_utils import Log, ReshapeCosts
checkpoint_dir = "checkpoints"
class BaseMLModel:
def __init__(self):
None
def Initialize(self, headers, cost_names, valid_costs,
parameters, cost_data, samples, cost_scaling_factor):
Log("Headers: " + str(headers))
orig_cost_data = cost_data
self.headers = headers
self.cost_names = cost_names
self.valid_costs = valid_costs
self.parameters_data = parameters
self.cost_data = cost_data.astype('float') * cost_scaling_factor
self.orig_cost_data = orig_cost_data.astype('float') * cost_scaling_factor
self.sample_actual_indexes = samples
self.cost_models = []
def IsValidCost(self, cost):
if len(self.valid_costs) > 0:
if cost not in self.valid_costs:
return False
return True
def GetModel(self, index):
if index < len(self.cost_models):
return self.cost_models[index]
return None
def Train(self, threading_model=False):
output = []
valid_trains = []
self.SaveTrainValTestData(self.step)
for index, cost in enumerate(self.cost_names):
output.append(None)
if self.IsValidCost(cost):
valid_trains.append((index, cost))
train_threads_list = []
for (index, cost) in valid_trains:
if threading_model:
def TrainThread(self, index, cost):
out = self.TrainCost(index)
output[index] = out
train_th_obj = DeffeThread(TrainThread,
(self, index, cost), True)
train_th_obj.StartThread()
train_threads_list.append(train_th_obj)
else:
output[index] = self.TrainCost(index)
for th in train_threads_list:
th.JoinThread()
return output
def PreLoadData(self, step, train_test_split, validation_split, shuffle=False):
parameters = self.parameters_data
cost_data = self.cost_data
orig_cost_data = self.orig_cost_data
train_count = int(parameters.shape[0] * train_test_split)
test_count = parameters.shape[0] - train_count
print("Init Total count:" + str(parameters.shape[0]))
print("Init Train count:" + str(train_count))
print("Init Test count:" + str(test_count))
self.train_count = train_count
self.val_count = int(train_count * validation_split)
self.test_count = test_count
indices = range(parameters.shape[0])
if shuffle:
indices = np.random.permutation(parameters.shape[0])
training_idx = indices[:train_count]
test_idx = indices[train_count:]
# print("Tr_indices:"+str(training_idx))
# print("test_indices:"+str(test_idx))
# print("Tr_indices count:"+str(training_idx.size))
# print("test_indices count:"+str(test_idx.size))
self.training_idx = training_idx
self.test_idx = test_idx
x_train = parameters[training_idx, :].astype("float")
x_test = parameters[test_idx, :].astype("float")
y_train = np.array([])
z_train = np.array([])
y_test = np.array([])
z_test = np.array([])
if cost_data.size != 0:
y_train = cost_data[training_idx, :]
z_train = orig_cost_data[training_idx, :]
y_test = cost_data[test_idx, :]
z_test = orig_cost_data[test_idx, :]
y_train = ReshapeCosts(y_train)
z_train = ReshapeCosts(z_train)
y_test = ReshapeCosts(y_test)
z_test = ReshapeCosts(z_test)
self.x_train, self.y_train, self.z_train = x_train, y_train, z_train
self.x_test, self.y_test, self.z_test = x_test, y_test, z_test
def SaveTrainValTestData(self, step=-1):
if step == -1:
print("Saving ML model indices: ml-indices.npy")
np.save("ml-indices.npy",
self.sample_actual_indexes)
else:
print("Saving ML indices: "
"step{}-ml-indices.npy".format(step))
np.save("step{}-ml-indices.npy".format(step),
self.sample_actual_indexes)
def LoadTrainValTestData(self, step=-1):
if step == -1:
print("Loading ML indices: ml-indices.npy")
sample_load_indexes = np.load(
"ml-indices.npy")
else:
print("Loading ML indices: "
"step{}-ml-indices.npy".format(step))
sample_load_indexes = np.load(
"step{}-ml-indices.npy".format(step))
parameters = self.parameters_data
cost_data = self.cost_data
orig_cost_data = self.orig_cost_data
train_val_indexes = self.sample_actual_indexes
index_hash = {
target_index: index for index, target_index in enumerate(train_val_indexes)
}
train_val_indexes = sample_load_indexes
training_idx = [index_hash[index] for index in train_val_indexes]
self.x_all = parameters.astype("float")
self.y_all = cost_data.astype("float")
x_train = parameters[training_idx, :].astype("float")
y_train = cost_data[training_idx, :].astype("float")
z_train = orig_cost_data[training_idx, :].astype("float")
# Get all remaining data other than traininga
all_indexes = range(parameters.shape[0])
test_idx = np.delete(all_indexes, training_idx)
x_test = parameters[test_idx, :].astype("float")
y_test = cost_data[test_idx, :].astype("float")
z_test = orig_cost_data[test_idx, :].astype("float")
y_train = ReshapeCosts(y_train)
z_train = ReshapeCosts(z_train)
y_test = ReshapeCosts(y_test)
z_test = ReshapeCosts(z_test)
self.x_train, self.y_train, self.z_train = x_train, y_train, z_train
self.x_test, self.y_test, self.z_test = x_test, y_test, z_test
self.train_count = len(training_idx) * (1 - self.validation_split)
self.val_count = len(training_idx) * self.validation_split
self.test_count = len(test_idx)
def get_last_cp_model(self, all_files):
epoch_re = re.compile(r"step([0-9]+).*weights-improvement-([0-9]+)-")
max_epoch = 0
last_icp = ""
for index, icp_file in enumerate(all_files):
epoch_flag = epoch_re.search(icp_file)
epoch = 0 # loss0.4787-valloss0.4075.hdf5a
step = 0 # loss0.4787-valloss0.4075.hdf5a
if epoch_flag:
step = int(epoch_flag.group(1))
epoch = int(epoch_flag.group(2))
step_epoch = step * 10000000 + epoch
if step_epoch > max_epoch:
max_epoch = step_epoch
last_icp = icp_file
return last_icp
# Evalaute model results
def EvaluateModel(self, all_files, outfile="test-output.csv"):
None
| [
"numpy.load",
"numpy.save",
"deffe_utils.ReshapeCosts",
"numpy.array",
"numpy.random.permutation",
"numpy.delete",
"re.compile"
] | [((3594, 3606), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3602, 3606), True, 'import numpy as np\n'), ((3625, 3637), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3633, 3637), True, 'import numpy as np\n'), ((3655, 3667), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3663, 3667), True, 'import numpy as np\n'), ((3685, 3697), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3693, 3697), True, 'import numpy as np\n'), ((5928, 5964), 'numpy.delete', 'np.delete', (['all_indexes', 'training_idx'], {}), '(all_indexes, training_idx)\n', (5937, 5964), True, 'import numpy as np\n'), ((6157, 6178), 'deffe_utils.ReshapeCosts', 'ReshapeCosts', (['y_train'], {}), '(y_train)\n', (6169, 6178), False, 'from deffe_utils import Log, ReshapeCosts\n'), ((6197, 6218), 'deffe_utils.ReshapeCosts', 'ReshapeCosts', (['z_train'], {}), '(z_train)\n', (6209, 6218), False, 'from deffe_utils import Log, ReshapeCosts\n'), ((6236, 6256), 'deffe_utils.ReshapeCosts', 'ReshapeCosts', (['y_test'], {}), '(y_test)\n', (6248, 6256), False, 'from deffe_utils import Log, ReshapeCosts\n'), ((6274, 6294), 'deffe_utils.ReshapeCosts', 'ReshapeCosts', (['z_test'], {}), '(z_test)\n', (6286, 6294), False, 'from deffe_utils import Log, ReshapeCosts\n'), ((6689, 6746), 're.compile', 're.compile', (['"""step([0-9]+).*weights-improvement-([0-9]+)-"""'], {}), "('step([0-9]+).*weights-improvement-([0-9]+)-')\n", (6699, 6746), False, 'import re\n'), ((3040, 3082), 'numpy.random.permutation', 'np.random.permutation', (['parameters.shape[0]'], {}), '(parameters.shape[0])\n', (3061, 3082), True, 'import numpy as np\n'), ((3948, 3969), 'deffe_utils.ReshapeCosts', 'ReshapeCosts', (['y_train'], {}), '(y_train)\n', (3960, 3969), False, 'from deffe_utils import Log, ReshapeCosts\n'), ((3992, 4013), 'deffe_utils.ReshapeCosts', 'ReshapeCosts', (['z_train'], {}), '(z_train)\n', (4004, 4013), False, 'from deffe_utils import Log, ReshapeCosts\n'), ((4035, 4055), 'deffe_utils.ReshapeCosts', 'ReshapeCosts', (['y_test'], {}), '(y_test)\n', (4047, 4055), False, 'from deffe_utils import Log, ReshapeCosts\n'), ((4077, 4097), 'deffe_utils.ReshapeCosts', 'ReshapeCosts', (['z_test'], {}), '(z_test)\n', (4089, 4097), False, 'from deffe_utils import Log, ReshapeCosts\n'), ((4388, 4441), 'numpy.save', 'np.save', (['"""ml-indices.npy"""', 'self.sample_actual_indexes'], {}), "('ml-indices.npy', self.sample_actual_indexes)\n", (4395, 4441), True, 'import numpy as np\n'), ((4841, 4866), 'numpy.load', 'np.load', (['"""ml-indices.npy"""'], {}), "('ml-indices.npy')\n", (4848, 4866), True, 'import numpy as np\n')] |
import path_utils
import numpy as np
from RNN1L import RNN1L
from FFNN_multilayer import FFNN_multilayer
import gym
import matplotlib.pyplot as plt
import os
# Environment setup
#env_name = "CartPole-v0"
env_name = 'Acrobot-v1'
env = gym.make(env_name)
nactions = env.action_space.n
ninputs = env.reset().size
# Network setup
#net = RNN1L(ninputs, nactions)
net = FFNN_multilayer(ninputs, nactions) # Simple feedforward NN
net.set_random_weights()
def run_episode(ep_net):
# Function for running a single episode, returns score.
ep_net.reset_state()
obs = env.reset()
score = 0
done = False
step = 0
while not done:
#print(f'step {step}')
action = ep_net.get_action(obs)
obs, rew, done, info = env.step(action)
score += rew
step += 1
return score
all_scores = []
best_scores = []
best_score = None
best_weights = None
max_gen = 1000
N_trials = 3
# Gameplay loop
for gen in range(max_gen):
if gen % max(1, max_gen//100) == 0:
print(f'generation {gen}')
# Get new NN
net.set_random_weights()
# Run each agent for several trials, to get a representative mean
score_trials = []
for _ in range(N_trials):
ep_score = run_episode(net)
score_trials.append(ep_score)
# Take mean, append, test to see if best yet.
mean_score = np.mean(score_trials)
all_scores.append(mean_score)
# I use >= here, because it's possible that the N_trials could achieve
# the maximum score but still fail the 100 episode average, so I want it
# to be able to try again with another NN.
if len(best_scores)==0 or mean_score >= best_score:
best_score = mean_score
best_weights = net.weights_matrix
# If it achieved a new best score, test for 100 episode average score.
# If 100 ep mean score is >= 195.0, it's considered solved.
eval_trials = []
for _ in range(100):
score = run_episode(net)
eval_trials.append(score)
eval_mean = np.mean(eval_trials)
if eval_mean >= 195.0:
print(f'Solved! 100 episode mean score = {eval_mean:.2f} in generation {gen}')
break
else:
print(f'Unsolved. 100 episode mean score = {eval_mean:.2f} in generation {gen}')
# Append even if there was no improvement
best_scores.append(best_score)
# Plot results
print(f'Best score achieved: {best_score}')
print(f'Best weight matrix: \n{best_weights}')
plt.plot(best_scores, color='tomato', label='Best FF found')
plt.plot(all_scores, color='dodgerblue', label='All FF')
plt.xlabel('Episode')
plt.ylabel('Fitness Function (FF)')
plt.legend()
plt.title('CartPole-v0 environment')
plt.savefig(os.path.join(path_utils.get_output_dir(), 'NE_cartpole_FF.png'))
plt.show()
#env = gym.wrappers.Monitor(env, 'video', force = True)
# Set to best weights found, run episode and show
net.set_weights(best_weights)
obs = env.reset()
score = 0
done = False
while not done:
env.render()
action = net.get_action(obs)
obs, rew, done, info = env.step(action)
score += rew
print(f'Final score: {score}')
env.close()
#
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"gym.make",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"path_utils.get_output_dir",
"numpy.mean",
"FFNN_multilayer.FFNN_multilayer",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((235, 253), 'gym.make', 'gym.make', (['env_name'], {}), '(env_name)\n', (243, 253), False, 'import gym\n'), ((366, 400), 'FFNN_multilayer.FFNN_multilayer', 'FFNN_multilayer', (['ninputs', 'nactions'], {}), '(ninputs, nactions)\n', (381, 400), False, 'from FFNN_multilayer import FFNN_multilayer\n'), ((2497, 2557), 'matplotlib.pyplot.plot', 'plt.plot', (['best_scores'], {'color': '"""tomato"""', 'label': '"""Best FF found"""'}), "(best_scores, color='tomato', label='Best FF found')\n", (2505, 2557), True, 'import matplotlib.pyplot as plt\n'), ((2558, 2614), 'matplotlib.pyplot.plot', 'plt.plot', (['all_scores'], {'color': '"""dodgerblue"""', 'label': '"""All FF"""'}), "(all_scores, color='dodgerblue', label='All FF')\n", (2566, 2614), True, 'import matplotlib.pyplot as plt\n'), ((2616, 2637), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Episode"""'], {}), "('Episode')\n", (2626, 2637), True, 'import matplotlib.pyplot as plt\n'), ((2638, 2673), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Fitness Function (FF)"""'], {}), "('Fitness Function (FF)')\n", (2648, 2673), True, 'import matplotlib.pyplot as plt\n'), ((2674, 2686), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2684, 2686), True, 'import matplotlib.pyplot as plt\n'), ((2687, 2723), 'matplotlib.pyplot.title', 'plt.title', (['"""CartPole-v0 environment"""'], {}), "('CartPole-v0 environment')\n", (2696, 2723), True, 'import matplotlib.pyplot as plt\n'), ((2801, 2811), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2809, 2811), True, 'import matplotlib.pyplot as plt\n'), ((1357, 1378), 'numpy.mean', 'np.mean', (['score_trials'], {}), '(score_trials)\n', (1364, 1378), True, 'import numpy as np\n'), ((2038, 2058), 'numpy.mean', 'np.mean', (['eval_trials'], {}), '(eval_trials)\n', (2045, 2058), True, 'import numpy as np\n'), ((2749, 2776), 'path_utils.get_output_dir', 'path_utils.get_output_dir', ([], {}), '()\n', (2774, 2776), False, 'import path_utils\n')] |
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from collections import Iterable
from torch.autograd import Variable
import torch
import numpy as np
from torchdiffeq import odeint
from models.bnn import BNN
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class ODE(nn.Module):
def __init__(self, num_channels=3, img_size=(64,64), method='naive language', batch_size=5):
super(ODE, self).__init__()
self.encoder = Encoder(num_channels=num_channels)
self.rnn = RNN_FeatEncoder(batch_size=batch_size)
self.decoder = Decoder(num_channels=num_channels)
self.bnn = BNN(256+16, 256, act='tanh', n_hidden=128, bnn=False)
self.bnn.draw_f()
self.language_encoder = Language_Encoder()
self.img_size = img_size
self.method = method
self.lan_mu_proj = nn.Linear(128, 128)
self.lan_var_proj = nn.Linear(128, 128)
self.vid_feat_proj = nn.Linear(256, 128)
self.batch_size = batch_size
def forward(self, input, pos_language=None, neg_language=None):
"""
input is video trajectory in training, or single image in testing.
language is language feature from VisualCommet
"""
if pos_language is None:
batchsize = input.shape[0]
latent_total= self.encoder(input).view([batchsize, -1])
state = torch.randn(batchsize, 128).to(device)
init_state = latent_total
else:
batchsize = input.shape[0]
if input.shape[1]==1:
# Only given the first image
if self.method == "naive language":
latent_total= self.encoder(input.squeeze(1)).view([batchsize, 1, -1])
language_feature = self.language_encoder(pos_language)
state = torch.randn(batchsize, 128).to(device) * language_feature + language_feature
init_state = latent_total[:,0]
elif self.method == 'nce':
latent_total= self.encoder(input.squeeze(1)).view([batchsize, 1, -1])
language_feature = self.language_encoder(pos_language)
mu = self.lan_mu_proj(language_feature)
logvar = self.lan_var_proj(language_feature)
state = self.decoder.reparametrize(mu, logvar)
init_state = latent_total[:,0]
else:
contrastive_loss = 0
# Training time, given a sequence
latent_total= self.encoder(input.reshape([batchsize*10, 3, 64, 64])).view([batchsize, 10, -1])
h = self.rnn.init_h.to(device)
c = self.rnn.init_c.to(device)
for i in reversed(range(10)):
latent, h, c = self.rnn(latent_total[:, i:i+1, :].permute(1, 0, 2), h, c)
state_dist = self.rnn.linearlay(latent.view([batchsize, 256]))
if self.method == 'naive language':
mu = state_dist[:, :128]
logvar = state_dist[:, 128:]
language_feature = self.language_encoder(pos_language)
video_latent = self.decoder.reparametrize(mu, logvar)
state = video_latent * language_feature + language_feature
init_state = latent_total[:, 0]
elif self.method == 'nce':
video_feature = self.vid_feat_proj(state_dist)
pos_language_feature = self.language_encoder(pos_language)
neg_language_feature = self.language_encoder(neg_language)
pos_sim = torch.sum(video_feature * pos_language_feature, dim=1)
neg_sim = torch.sum(video_feature * neg_language_feature, dim=1)
contrastive_loss = torch.mean(torch.exp(neg_sim) / (torch.exp(pos_sim) + 1e-10))
mu = self.lan_mu_proj(pos_language_feature)
logvar = self.lan_var_proj(neg_language_feature)
state = self.decoder.reparametrize(mu, logvar)
init_state = latent_total[:, 0]
concat_state = torch.cat([state, init_state], 1)
ts1 = torch.tensor(np.linspace(1, 10, 10)).to(device)
output_latent = odeint(self.bnn, concat_state, ts1)
recon = self.decoder(output_latent.reshape([batchsize*10, 256])).reshape([batchsize, 10, 3, 64, 64])
if input.shape[1]==1:
return recon
else:
return recon, mu, logvar, contrastive_loss
class Language_Encoder(nn.Module):
def __init__(self):
super(Language_Encoder, self).__init__()
self.fc1 = nn.Linear(512, 256)
self.fc2 = nn.Linear(256, 128)
self.relu = nn.ReLU(inplace=True)
def forward(self, input):
out = self.relu(self.fc1(input))
out = self.fc2(out)
return out
class Encoder(nn.Module):
def __init__(self, num_channels=3):
super(Encoder, self).__init__()
self.cnn1 = nn.Conv2d(num_channels, 4, kernel_size=4, stride=2, padding=1)
self.cnn2 = nn.Conv2d(4, 8, kernel_size=4, stride=2, padding=1)
self.cnn3 = nn.Conv2d(8, 16, kernel_size=4, stride=2, padding=1)
self.cnn4 = nn.Conv2d(16, 32, kernel_size=4, stride=2, padding=1)
#self.fc1 = nn.Linear(15*20*32, 256)
self.fc1 = nn.Linear(4*4*32, 256)
self.fc2 = nn.Linear(256, 128)
self.bn1 = nn.BatchNorm2d(4)
self.bn2 = nn.BatchNorm2d(8)
self.bn3 = nn.BatchNorm2d(16)
self.bn4 = nn.BatchNorm2d(32)
#self.relu = nn.ReLU(inplace=True)
self.relu1 = nn.ReLU()
self.relu2 = nn.ReLU()
self.relu3 = nn.ReLU()
self.relu4 = nn.ReLU()
self.relu5 = nn.ReLU()
# self.weight_init()
def forward(self, input):
out = self.relu1(self.bn1(self.cnn1(input)))
out = self.relu2(self.bn2(self.cnn2(out)))
out = self.relu3(self.bn3(self.cnn3(out)))
out = self.relu4(self.bn4(self.cnn4(out)))
out = self.relu5(self.fc1(out.reshape([-1, 4*4*32])))
return self.fc2(out)
def weight_init(self):
for block in self._modules:
if isinstance(self._modules[block], Iterable):
for m in self._modules[block]:
if self.args.init_method == 'kaiming':
m.apply(kaiming_init)
elif self.args.init_method == 'xavier':
m.apply(xavier_uniform_init)
else:
m.apply(normal_init)
else:
if self.args.init_method == 'kaiming':
self._modules[block].apply(kaiming_init)
elif self.args.init_method == 'xavier':
self._modules[block].apply(xavier_uniform_init)
else:
self._modules[block].apply(normal_init)
class RNN_FeatEncoder(nn.Module):
def __init__(self, batch_size=5):
super(RNN_FeatEncoder, self).__init__()
latent_size = 256
self.lstm = nn.LSTM(latent_size//2, latent_size, 1)
self.batch = batch_size
self.init_h = torch.zeros([1, self.batch, latent_size], device=device)
self.init_c = torch.zeros([1, self.batch, latent_size], device=device)
self.fc3 = nn.Linear(latent_size, latent_size)
self.fc4 = nn.Linear(latent_size, latent_size)
self.relu = nn.ReLU(inplace=True)
def forward(self, input, h, c):
out, (h, c) = self.lstm(input, (h, c))
return out, h, c
def linearlay(self, input):
temp = self.relu(self.fc3(input))
return self.fc4(temp)
class Decoder(nn.Module):
def __init__(self, num_channels=3):
super(Decoder, self).__init__()
self.cnn2 = nn.ConvTranspose2d(32, 16, kernel_size=4, stride=2, padding=1)
self.cnn3 = nn.ConvTranspose2d(16, 8, kernel_size=4, stride=2, padding=1)
self.cnn4 = nn.ConvTranspose2d(8, 4, kernel_size=4, stride=2, padding=1)
self.cnn5 = nn.ConvTranspose2d(4, num_channels, kernel_size=4, stride=2, padding=1)
self.fc1 = nn.Linear(256, 256)
#self.fc2 = nn.Linear(256, 15*20*32)
self.fc2 = nn.Linear(256, 4*4*32)
self.bn2 = nn.BatchNorm2d(16)
self.bn3 = nn.BatchNorm2d(8)
self.bn4 = nn.BatchNorm2d(4)
self.relu1 = nn.ReLU()
self.relu2 = nn.ReLU()
self.relu3 = nn.ReLU()
self.relu4 = nn.ReLU()
self.relu5 = nn.ReLU()
self.relu6 = nn.ReLU()
def forward(self, z):
out = self.relu1(self.fc1(z))
out = self.relu2(self.fc2(out)).reshape([-1, 32, 4, 4])
out = self.relu3(self.bn2(self.cnn2(out)))
out = self.relu4(self.bn3(self.cnn3(out)))
out = self.relu5(self.bn4(self.cnn4(out)))
out = self.relu6(self.cnn5(out))
return out
def reparametrize(self, mu, logvar):
std = logvar.div(2).exp_()
eps = Variable(std.data.new(std.size()).normal_())
return mu + std * eps
def kaiming_init(m):
if isinstance(m, (nn.Linear, nn.Conv3d, nn.ConvTranspose3d)):
init.kaiming_normal_(m.weight)
if m.bias is not None:
m.bias.data.fill_(0)
elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm3d)):
m.weight.data.fill_(1)
if m.bias is not None:
m.bias.data.fill_(0)
def normal_init(m, mean=0, std=0.1):
if isinstance(m, (nn.Linear, nn.Conv3d)):
m.weight.data.normal_(mean, std)
if m.bias.data is not None:
m.bias.data.zero_()
elif isinstance(m, (nn.BatchNorm3d, nn.BatchNorm1d)):
m.weight.data.fill_(1)
if m.bias.data is not None:
m.bias.data.zero_()
def xavier_uniform_init(m):
if isinstance(m, (nn.Linear, nn.Conv3d, nn.ConvTranspose3d)):
nn.init.xavier_normal_(m.weight)
if m.bias.data is not None:
m.bias.data.fill_(0.01)
elif isinstance(m, (nn.BatchNorm3d, nn.BatchNorm1d)):
m.weight.data.fill_(1)
if m.bias.data is not None:
m.bias.data.zero_()
| [
"torch.nn.ReLU",
"torch.nn.ConvTranspose2d",
"torch.nn.init.kaiming_normal_",
"torch.sum",
"torch.nn.Conv2d",
"torch.nn.init.xavier_normal_",
"torch.cat",
"torch.randn",
"torch.exp",
"torch.nn.BatchNorm2d",
"torchdiffeq.odeint",
"torch.cuda.is_available",
"numpy.linspace",
"torch.nn.Linear... | [((274, 299), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (297, 299), False, 'import torch\n'), ((661, 716), 'models.bnn.BNN', 'BNN', (['(256 + 16)', '(256)'], {'act': '"""tanh"""', 'n_hidden': '(128)', 'bnn': '(False)'}), "(256 + 16, 256, act='tanh', n_hidden=128, bnn=False)\n", (664, 716), False, 'from models.bnn import BNN\n'), ((881, 900), 'torch.nn.Linear', 'nn.Linear', (['(128)', '(128)'], {}), '(128, 128)\n', (890, 900), True, 'import torch.nn as nn\n'), ((929, 948), 'torch.nn.Linear', 'nn.Linear', (['(128)', '(128)'], {}), '(128, 128)\n', (938, 948), True, 'import torch.nn as nn\n'), ((978, 997), 'torch.nn.Linear', 'nn.Linear', (['(256)', '(128)'], {}), '(256, 128)\n', (987, 997), True, 'import torch.nn as nn\n'), ((3918, 3951), 'torch.cat', 'torch.cat', (['[state, init_state]', '(1)'], {}), '([state, init_state], 1)\n', (3927, 3951), False, 'import torch\n'), ((4034, 4069), 'torchdiffeq.odeint', 'odeint', (['self.bnn', 'concat_state', 'ts1'], {}), '(self.bnn, concat_state, ts1)\n', (4040, 4069), False, 'from torchdiffeq import odeint\n'), ((4417, 4436), 'torch.nn.Linear', 'nn.Linear', (['(512)', '(256)'], {}), '(512, 256)\n', (4426, 4436), True, 'import torch.nn as nn\n'), ((4456, 4475), 'torch.nn.Linear', 'nn.Linear', (['(256)', '(128)'], {}), '(256, 128)\n', (4465, 4475), True, 'import torch.nn as nn\n'), ((4496, 4517), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4503, 4517), True, 'import torch.nn as nn\n'), ((4758, 4820), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channels', '(4)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(num_channels, 4, kernel_size=4, stride=2, padding=1)\n', (4767, 4820), True, 'import torch.nn as nn\n'), ((4841, 4892), 'torch.nn.Conv2d', 'nn.Conv2d', (['(4)', '(8)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(4, 8, kernel_size=4, stride=2, padding=1)\n', (4850, 4892), True, 'import torch.nn as nn\n'), ((4913, 4965), 'torch.nn.Conv2d', 'nn.Conv2d', (['(8)', '(16)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(8, 16, kernel_size=4, stride=2, padding=1)\n', (4922, 4965), True, 'import torch.nn as nn\n'), ((4986, 5039), 'torch.nn.Conv2d', 'nn.Conv2d', (['(16)', '(32)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(16, 32, kernel_size=4, stride=2, padding=1)\n', (4995, 5039), True, 'import torch.nn as nn\n'), ((5105, 5131), 'torch.nn.Linear', 'nn.Linear', (['(4 * 4 * 32)', '(256)'], {}), '(4 * 4 * 32, 256)\n', (5114, 5131), True, 'import torch.nn as nn\n'), ((5147, 5166), 'torch.nn.Linear', 'nn.Linear', (['(256)', '(128)'], {}), '(256, 128)\n', (5156, 5166), True, 'import torch.nn as nn\n'), ((5186, 5203), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(4)'], {}), '(4)\n', (5200, 5203), True, 'import torch.nn as nn\n'), ((5223, 5240), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(8)'], {}), '(8)\n', (5237, 5240), True, 'import torch.nn as nn\n'), ((5260, 5278), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(16)'], {}), '(16)\n', (5274, 5278), True, 'import torch.nn as nn\n'), ((5298, 5316), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(32)'], {}), '(32)\n', (5312, 5316), True, 'import torch.nn as nn\n'), ((5382, 5391), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5389, 5391), True, 'import torch.nn as nn\n'), ((5413, 5422), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5420, 5422), True, 'import torch.nn as nn\n'), ((5444, 5453), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5451, 5453), True, 'import torch.nn as nn\n'), ((5475, 5484), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5482, 5484), True, 'import torch.nn as nn\n'), ((5506, 5515), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5513, 5515), True, 'import torch.nn as nn\n'), ((6839, 6880), 'torch.nn.LSTM', 'nn.LSTM', (['(latent_size // 2)', 'latent_size', '(1)'], {}), '(latent_size // 2, latent_size, 1)\n', (6846, 6880), True, 'import torch.nn as nn\n'), ((6933, 6989), 'torch.zeros', 'torch.zeros', (['[1, self.batch, latent_size]'], {'device': 'device'}), '([1, self.batch, latent_size], device=device)\n', (6944, 6989), False, 'import torch\n'), ((7012, 7068), 'torch.zeros', 'torch.zeros', (['[1, self.batch, latent_size]'], {'device': 'device'}), '([1, self.batch, latent_size], device=device)\n', (7023, 7068), False, 'import torch\n'), ((7088, 7123), 'torch.nn.Linear', 'nn.Linear', (['latent_size', 'latent_size'], {}), '(latent_size, latent_size)\n', (7097, 7123), True, 'import torch.nn as nn\n'), ((7143, 7178), 'torch.nn.Linear', 'nn.Linear', (['latent_size', 'latent_size'], {}), '(latent_size, latent_size)\n', (7152, 7178), True, 'import torch.nn as nn\n'), ((7199, 7220), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (7206, 7220), True, 'import torch.nn as nn\n'), ((7563, 7625), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(32)', '(16)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(32, 16, kernel_size=4, stride=2, padding=1)\n', (7581, 7625), True, 'import torch.nn as nn\n'), ((7646, 7707), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(16)', '(8)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(16, 8, kernel_size=4, stride=2, padding=1)\n', (7664, 7707), True, 'import torch.nn as nn\n'), ((7728, 7788), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(8)', '(4)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(8, 4, kernel_size=4, stride=2, padding=1)\n', (7746, 7788), True, 'import torch.nn as nn\n'), ((7809, 7880), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(4)', 'num_channels'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(4, num_channels, kernel_size=4, stride=2, padding=1)\n', (7827, 7880), True, 'import torch.nn as nn\n'), ((7900, 7919), 'torch.nn.Linear', 'nn.Linear', (['(256)', '(256)'], {}), '(256, 256)\n', (7909, 7919), True, 'import torch.nn as nn\n'), ((7984, 8010), 'torch.nn.Linear', 'nn.Linear', (['(256)', '(4 * 4 * 32)'], {}), '(256, 4 * 4 * 32)\n', (7993, 8010), True, 'import torch.nn as nn\n'), ((8026, 8044), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(16)'], {}), '(16)\n', (8040, 8044), True, 'import torch.nn as nn\n'), ((8064, 8081), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(8)'], {}), '(8)\n', (8078, 8081), True, 'import torch.nn as nn\n'), ((8101, 8118), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(4)'], {}), '(4)\n', (8115, 8118), True, 'import torch.nn as nn\n'), ((8140, 8149), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (8147, 8149), True, 'import torch.nn as nn\n'), ((8171, 8180), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (8178, 8180), True, 'import torch.nn as nn\n'), ((8202, 8211), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (8209, 8211), True, 'import torch.nn as nn\n'), ((8233, 8242), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (8240, 8242), True, 'import torch.nn as nn\n'), ((8264, 8273), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (8271, 8273), True, 'import torch.nn as nn\n'), ((8295, 8304), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (8302, 8304), True, 'import torch.nn as nn\n'), ((8910, 8940), 'torch.nn.init.kaiming_normal_', 'init.kaiming_normal_', (['m.weight'], {}), '(m.weight)\n', (8930, 8940), True, 'import torch.nn.init as init\n'), ((9611, 9643), 'torch.nn.init.xavier_normal_', 'nn.init.xavier_normal_', (['m.weight'], {}), '(m.weight)\n', (9633, 9643), True, 'import torch.nn as nn\n'), ((1409, 1436), 'torch.randn', 'torch.randn', (['batchsize', '(128)'], {}), '(batchsize, 128)\n', (1420, 1436), False, 'import torch\n'), ((3977, 3999), 'numpy.linspace', 'np.linspace', (['(1)', '(10)', '(10)'], {}), '(1, 10, 10)\n', (3988, 3999), True, 'import numpy as np\n'), ((3441, 3495), 'torch.sum', 'torch.sum', (['(video_feature * pos_language_feature)'], {'dim': '(1)'}), '(video_feature * pos_language_feature, dim=1)\n', (3450, 3495), False, 'import torch\n'), ((3518, 3572), 'torch.sum', 'torch.sum', (['(video_feature * neg_language_feature)'], {'dim': '(1)'}), '(video_feature * neg_language_feature, dim=1)\n', (3527, 3572), False, 'import torch\n'), ((3615, 3633), 'torch.exp', 'torch.exp', (['neg_sim'], {}), '(neg_sim)\n', (3624, 3633), False, 'import torch\n'), ((1813, 1840), 'torch.randn', 'torch.randn', (['batchsize', '(128)'], {}), '(batchsize, 128)\n', (1824, 1840), False, 'import torch\n'), ((3637, 3655), 'torch.exp', 'torch.exp', (['pos_sim'], {}), '(pos_sim)\n', (3646, 3655), False, 'import torch\n')] |
"""
Written by <NAME>, May 2021, <EMAIL>
Optimizes a force for the study of the time-integrated velocity of a particle on a ring,
with a periodic potential and a constant driving force in the overdamped case.
Uses an Actor-Critic algorithm, with temporal-difference errors calculated using single
time-step segments of trajectory from a discretized diffusive simulation. Updates are done
for each individual transition.
"""
import math
import copy
import time
import numba
import numpy as np
import numpy.random
from matplotlib import pyplot as plt
""" Dynamics parameters. """
magnitude = 2
driving = 1
time_step = 0.001
divisor = 4 * time_step
variance = (2*time_step)**0.5
""" Variable initialization. """
average_reward = 0
average_kl = 0
average_velocity = 0
""" Algorithm parameters. """
reward_learning_rate = 10**(-5)
final_learning_rate = 10**(-6)
training_steps = 10000000
linear_rate_change = (final_learning_rate - reward_learning_rate)/training_steps
force_learning_rate = 10**(-1)
value_learning_rate = 10**(-2)
""" Approximation parameters. """
parameter_number = 5
""" Approximation setup. """
basis_index = np.arange(parameter_number) + 1
force_parameters = np.zeros(parameter_number * 2 + 1)
force_parameters[0] = 1
force_parameters[1] = 2
force_current_update = np.zeros(parameter_number * 2 + 1)
value_parameters = np.zeros(parameter_number * 2 + 1)
value_current_update = np.zeros(parameter_number * 2 + 1)
@numba.njit
def force(position):
"""Calculates the force applied directly to the particle position."""
return magnitude * math.sin(position) + driving
@numba.njit
def fourier_basis(position):
"""Calculates the values of a Fourier basis at a given position."""
trig_arguments = position * basis_index
sin_basis = np.sin(trig_arguments)
cos_basis = np.cos(trig_arguments)
return np.concatenate((np.array([1]), sin_basis, cos_basis))
@numba.njit
def trajectory(position, length):
"""Evolves given position with the original dynamics."""
trajectory = np.zeros(length + 1)
trajectory[0] = position
for i in range(1, length + 1):
noise = variance * numpy.random.randn()
position += time_step * force(position) + noise
position -= 2*math.pi*math.floor(position / (2*math.pi))
trajectory[i] = position
return trajectory
@numba.njit
def regularized_reward(position, position_change, noise, bias):
"""Calculates the reward for the specified transition, using noise.
Assumes the current dynamics was used to generate the transition
with the sampled noise being that given as an input.
"""
reward = noise**2/divisor
reward -= (position_change - time_step * force(position))**2/divisor
kl_reg = reward
reward -= bias * position_change
return reward, kl_reg
@numba.njit
def train(position, steps, save_period, average_reward, force_parameters,
value_parameters, reward_learning_rate, bias, average_kl, average_velocity):
"""Trains the dynamics for the specified number of steps."""
rewards = np.zeros(int(steps / save_period))
kl_divergences = np.zeros(int(steps / save_period))
velocities = np.zeros(int(steps / save_period))
features = fourier_basis(position)
current_value = value_parameters @ features
for step in range(steps):
previous_value = current_value
previous_features = np.copy(features)
unit_noise = numpy.random.randn()
noise = variance * unit_noise
parameterized_force = force_parameters @ features
position_change = time_step * parameterized_force + noise
reward, kl_reg = regularized_reward(position, position_change, noise, bias)
position += position_change
position -= 2*math.pi*math.floor(position / (2*math.pi))
features = fourier_basis(position)
current_value = value_parameters @ features
td_error = current_value + reward - average_reward - previous_value
force_parameters += (force_learning_rate * td_error * unit_noise
* previous_features)
value_parameters += value_learning_rate * td_error * previous_features
average_reward += reward_learning_rate * td_error
average_kl += reward_learning_rate*0.1 * (kl_reg - average_kl)
average_velocity += reward_learning_rate*0.1 * (position_change - average_velocity)
reward_learning_rate += linear_rate_change
if step % save_period == 0:
rewards[int(step/save_period)] = average_reward / time_step
kl_divergences[int(step/save_period)] = average_kl / time_step
velocities[int(step/save_period)] = average_velocity / time_step
return rewards, kl_divergences, velocities, force_parameters, value_parameters, average_reward, average_velocity, average_kl
""" Bias setup. """
bias_number = 20
initial_bias = -0.5
bias_range = 2
bias_step = bias_range/bias_number
biases = [round(initial_bias + bias_step*i, 3) for i in range(bias_number + 1)]
print(biases)
""" Data storage for plotting. """
rews = []
kldivs = []
velocits = []
scgfs = []
kls = []
velos = []
save = False
for bias in biases:
initial_time = time.time()
rewards, kl_divergences, velocities, force_parameters, value_parameters, average_reward, average_velocity, average_kl = train(
0, training_steps, int(training_steps/10000), average_reward,
force_parameters,
value_parameters, reward_learning_rate, bias, average_kl, average_velocity)
rews.append(rewards)
kldivs.append(kl_divergences)
velocits.append(velocities)
scgfs.append(rewards[-1])
kls.append(kl_divergences[-1])
velos.append(velocities[-1])
print(bias)
print(time.time() - initial_time)
if save:
np.save("overdamped_bias%s_fb%s_ts%s_force_parameters"%(
bias, parameter_number,
time_step), force_parameters)
np.save("overdamped_bias%s_fb%s_ts%s_value_parameters"%(
bias, parameter_number,
time_step), value_parameters)
np.save("overdamped_bias%s_fb%s_ts%s_ls%s_scgf_estimate"%(
bias, parameter_number,
time_step, training_steps), rewards)
np.save("overdamped_bias%s_fb%s_ts%s_ls%s_kl_estimate"%(
bias, parameter_number,
time_step, training_steps), kl_divergences)
np.save("overdamped_bias%s_fb%s_ts%s_ls%s_velocity_estimate"%(
bias, parameter_number,
time_step, training_steps), velocities)
plt.figure(figsize = (13, 4))
plt.subplot(231)
for i in range(bias_number + 1):
plt.plot(rews[i])
plt.subplot(232)
for i in range(bias_number + 1):
plt.plot(-kldivs[i])
plt.subplot(233)
for i in range(bias_number + 1):
plt.plot(velocits[i])
plt.subplot(234)
plt.plot(biases, scgfs)
plt.subplot(235)
plt.plot(biases, -np.array(kls))
plt.subplot(236)
plt.plot(biases, velos)
plt.show() | [
"matplotlib.pyplot.subplot",
"numpy.save",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.copy",
"numpy.zeros",
"math.floor",
"math.sin",
"time.time",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.arange",
"numpy.array",
"numpy.cos"
] | [((1182, 1216), 'numpy.zeros', 'np.zeros', (['(parameter_number * 2 + 1)'], {}), '(parameter_number * 2 + 1)\n', (1190, 1216), True, 'import numpy as np\n'), ((1288, 1322), 'numpy.zeros', 'np.zeros', (['(parameter_number * 2 + 1)'], {}), '(parameter_number * 2 + 1)\n', (1296, 1322), True, 'import numpy as np\n'), ((1342, 1376), 'numpy.zeros', 'np.zeros', (['(parameter_number * 2 + 1)'], {}), '(parameter_number * 2 + 1)\n', (1350, 1376), True, 'import numpy as np\n'), ((1400, 1434), 'numpy.zeros', 'np.zeros', (['(parameter_number * 2 + 1)'], {}), '(parameter_number * 2 + 1)\n', (1408, 1434), True, 'import numpy as np\n'), ((6070, 6097), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(13, 4)'}), '(figsize=(13, 4))\n', (6080, 6097), True, 'from matplotlib import pyplot as plt\n'), ((6100, 6116), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(231)'], {}), '(231)\n', (6111, 6116), True, 'from matplotlib import pyplot as plt\n'), ((6169, 6185), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(232)'], {}), '(232)\n', (6180, 6185), True, 'from matplotlib import pyplot as plt\n'), ((6241, 6257), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(233)'], {}), '(233)\n', (6252, 6257), True, 'from matplotlib import pyplot as plt\n'), ((6314, 6330), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(234)'], {}), '(234)\n', (6325, 6330), True, 'from matplotlib import pyplot as plt\n'), ((6331, 6354), 'matplotlib.pyplot.plot', 'plt.plot', (['biases', 'scgfs'], {}), '(biases, scgfs)\n', (6339, 6354), True, 'from matplotlib import pyplot as plt\n'), ((6355, 6371), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(235)'], {}), '(235)\n', (6366, 6371), True, 'from matplotlib import pyplot as plt\n'), ((6405, 6421), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(236)'], {}), '(236)\n', (6416, 6421), True, 'from matplotlib import pyplot as plt\n'), ((6422, 6445), 'matplotlib.pyplot.plot', 'plt.plot', (['biases', 'velos'], {}), '(biases, velos)\n', (6430, 6445), True, 'from matplotlib import pyplot as plt\n'), ((6446, 6456), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6454, 6456), True, 'from matplotlib import pyplot as plt\n'), ((1131, 1158), 'numpy.arange', 'np.arange', (['parameter_number'], {}), '(parameter_number)\n', (1140, 1158), True, 'import numpy as np\n'), ((1756, 1778), 'numpy.sin', 'np.sin', (['trig_arguments'], {}), '(trig_arguments)\n', (1762, 1778), True, 'import numpy as np\n'), ((1792, 1814), 'numpy.cos', 'np.cos', (['trig_arguments'], {}), '(trig_arguments)\n', (1798, 1814), True, 'import numpy as np\n'), ((1996, 2016), 'numpy.zeros', 'np.zeros', (['(length + 1)'], {}), '(length + 1)\n', (2004, 2016), True, 'import numpy as np\n'), ((4901, 4912), 'time.time', 'time.time', ([], {}), '()\n', (4910, 4912), False, 'import time\n'), ((6151, 6168), 'matplotlib.pyplot.plot', 'plt.plot', (['rews[i]'], {}), '(rews[i])\n', (6159, 6168), True, 'from matplotlib import pyplot as plt\n'), ((6220, 6240), 'matplotlib.pyplot.plot', 'plt.plot', (['(-kldivs[i])'], {}), '(-kldivs[i])\n', (6228, 6240), True, 'from matplotlib import pyplot as plt\n'), ((6292, 6313), 'matplotlib.pyplot.plot', 'plt.plot', (['velocits[i]'], {}), '(velocits[i])\n', (6300, 6313), True, 'from matplotlib import pyplot as plt\n'), ((3258, 3275), 'numpy.copy', 'np.copy', (['features'], {}), '(features)\n', (3265, 3275), True, 'import numpy as np\n'), ((5436, 5551), 'numpy.save', 'np.save', (["('overdamped_bias%s_fb%s_ts%s_force_parameters' % (bias, parameter_number,\n time_step))", 'force_parameters'], {}), "('overdamped_bias%s_fb%s_ts%s_force_parameters' % (bias,\n parameter_number, time_step), force_parameters)\n", (5443, 5551), True, 'import numpy as np\n'), ((5555, 5670), 'numpy.save', 'np.save', (["('overdamped_bias%s_fb%s_ts%s_value_parameters' % (bias, parameter_number,\n time_step))", 'value_parameters'], {}), "('overdamped_bias%s_fb%s_ts%s_value_parameters' % (bias,\n parameter_number, time_step), value_parameters)\n", (5562, 5670), True, 'import numpy as np\n'), ((5674, 5798), 'numpy.save', 'np.save', (["('overdamped_bias%s_fb%s_ts%s_ls%s_scgf_estimate' % (bias, parameter_number,\n time_step, training_steps))", 'rewards'], {}), "('overdamped_bias%s_fb%s_ts%s_ls%s_scgf_estimate' % (bias,\n parameter_number, time_step, training_steps), rewards)\n", (5681, 5798), True, 'import numpy as np\n'), ((5802, 5931), 'numpy.save', 'np.save', (["('overdamped_bias%s_fb%s_ts%s_ls%s_kl_estimate' % (bias, parameter_number,\n time_step, training_steps))", 'kl_divergences'], {}), "('overdamped_bias%s_fb%s_ts%s_ls%s_kl_estimate' % (bias,\n parameter_number, time_step, training_steps), kl_divergences)\n", (5809, 5931), True, 'import numpy as np\n'), ((5935, 6066), 'numpy.save', 'np.save', (["('overdamped_bias%s_fb%s_ts%s_ls%s_velocity_estimate' % (bias,\n parameter_number, time_step, training_steps))", 'velocities'], {}), "('overdamped_bias%s_fb%s_ts%s_ls%s_velocity_estimate' % (bias,\n parameter_number, time_step, training_steps), velocities)\n", (5942, 6066), True, 'import numpy as np\n'), ((6390, 6403), 'numpy.array', 'np.array', (['kls'], {}), '(kls)\n', (6398, 6403), True, 'import numpy as np\n'), ((1562, 1580), 'math.sin', 'math.sin', (['position'], {}), '(position)\n', (1570, 1580), False, 'import math\n'), ((1839, 1852), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (1847, 1852), True, 'import numpy as np\n'), ((2191, 2227), 'math.floor', 'math.floor', (['(position / (2 * math.pi))'], {}), '(position / (2 * math.pi))\n', (2201, 2227), False, 'import math\n'), ((3588, 3624), 'math.floor', 'math.floor', (['(position / (2 * math.pi))'], {}), '(position / (2 * math.pi))\n', (3598, 3624), False, 'import math\n'), ((5396, 5407), 'time.time', 'time.time', ([], {}), '()\n', (5405, 5407), False, 'import time\n')] |
import numpy as np
from fenics import *
time_factor = 86400.0*365.24
secpera = 86400.0*365.24
class glenFlow(object):
#Computes harmonic mean of diffusion and dislocation creep based ice rheology
R = 8.314
def __init__(self,grain_size=1e-3,*args,**kwargs):
# Parameters in Glen's Flow Law Rheology (from Cuffey and Paterson)
self.enhancement = 1.0
self.E1 = 60e3 # Activation of ice warmer than -10
self.E2 = 115e3 # Activation energy of ice colder than -10
self.A = 3.5e-25 # Prefactor
self.pre1 = self.enhancement*(np.exp(self.E1/self.R/263.15)*self.A)**(-1.0/3)/(time_factor)**(1./3)
self.pre2 = self.enhancement*(np.exp(self.E2/self.R/263.15)*self.A)**(-1.0/3)/(time_factor)**(1./3)
self.set_grain_size(grain_size)
self.E_diff = 59.4e3
# Additional parameterself.B0 = 697.3/(time_factor)**(1./3)
self.plastic = True
self.yield_strength = 200e3
self.yield_min = 10e3
self.crit_strain = 0.1
self.visc_min = 1e8
self.visc_max = 1e18
self.mu = 0.0
self.num_yielded = 0.0
def set_grain_size(self, grain_size):
self.grain_size = grain_size
self.pre_diff = (1.2e-10/(grain_size**2))**(-1.0)/(time_factor)
def ductile_visc(self,epsII,tempFun,functionSpace=None):
"""
Calculate effective viscosity
Input: u_values: velocity fields (as Fenics array thingy)
scalar : the appropriate FENICS function space we live in
Return: scalar effective viscosity in units of Pa s
"""
# If no function space is provided then these are just raw nparrays
if functionSpace == None:
temp = tempFun
epsII = np.maximum(epsII,0.0)
Bdiff = self.pre_diff*np.exp(self.E_diff/(8.314*temp))
Bdisl = (self.pre1*np.exp(self.E1/(3.0*8.314*temp))*(temp<=263.15) + self.pre2*np.exp(self.E2/(3.0*8.314*temp))*(temp>263.15))
visc = 0.5*(epsII**(2.0/3.0)/Bdisl + 1.0/Bdiff)**(-1.0)
else:
Bdisl = Function(functionSpace)
Bdiff = Function(functionSpace)
temp = interpolate(tempFun,functionSpace).vector().get_local()
Bdiff.vector()[:] = self.pre_diff*np.exp(self.E_diff/(8.314*temp))
Bdisl.vector()[:] = (self.pre1*np.exp(self.E1/(3.0*8.314*temp))*(temp<=263.15) + self.pre2*np.exp(self.E2/(3.0*8.314*temp))*(temp>263.15))
visc = 0.5*(epsII**(2.0/3.0)/Bdisl + 1.0/Bdiff)**(-1.0)
return visc
def cohes(self,strainFun,functionSpace=None):
if functionSpace == None:
strain = strainFun
tau_y = np.maximum(self.yield_strength -(self.yield_strength -self.yield_min)*strain/self.crit_strain,self.yield_min)
assert(np.min(tau_y)>0)
else:
tau_y = Function(functionSpace)
strain = interpolate(strainFun,functionSpace).vector().get_local()
tau_y.vector()[:] = np.maximum(self.yield_strength -(self.yield_strength -self.yield_min)*strain/self.crit_strain,self.yield_min)
assert(np.min(tau_y.vector().get_local())>0)
return tau_y
def plastic_visc(self,epsII,strain,functionSpace=None):
"""
Calculate plastic effective viscosity
Input:
epsII_squared: second invariant squared in UFL form
strain: plastic strain on markers as an interpolation object or expression as a FENICS function
functionSpace: FENICS function space for cohesion
epsII_visc: Viscous part of epsII in UFL form
Return: scalar effective viscosity in units of Pa s in FENICS UFL form
"""
tau_y = self.cohes(strain,functionSpace)
if functionSpace ==None:
visc = 0.5*tau_y/(epsII+(1e-16))
else:
visc = 0.5*tau_y/(epsII+Constant(1e-16))
return visc
def update(self,epsII,temp,strain,dt):
""" Needs to be called at the particle level """
eta_visc = self.ductile_visc(epsII,temp,functionSpace=None)
eta_plas = self.plastic_visc(epsII,strain,functionSpace=None)
strain_new = strain + (eta_visc>eta_plas)*np.maximum(epsII,0.0)*dt
return strain_new
def strain_update(self,epsII,temp,strain,dt):
""" Needs to be called at the particle level """
eta_visc = self.ductile_visc(epsII,temp,functionSpace=None)
eta_plas = self.plastic_visc(epsII,strain,functionSpace=None)
#eta = (1/eta_visc + 1/eta_plas)**(-1)
#eta = self.__call__(epsII,temp,strain,functionSpace=None)
#F = 2*eta*epsII
#epsII_visc = F/eta_visc
epsII_visc = 0.0 # In case we want to subtract viscous strain rate
deps = (eta_visc>eta_plas)*np.maximum(epsII,0.0)*dt
self.num_yielded = sum(eta_visc>eta_plas)/len(epsII)
return deps
def __call__(self,epsII,temp,strain,functionSpace=None):
"""
Calculate effective viscosity
Input: u_values: velocity fields (as Fenics array thingy)
scalar : the appropriate FENICS function space we live in
Return: scalar effective viscosity
"""
visc = self.ductile_visc(epsII,temp,functionSpace)
if self.plastic==True:
tau_y = self.cohes(strain,functionSpace)
visc = Constant(0.5*self.visc_min/time_factor) + (1.0/visc + 2*epsII/tau_y + 2.0/Constant(self.visc_max/time_factor))**(-1.0)
return visc
| [
"numpy.min",
"numpy.maximum",
"numpy.exp"
] | [((1766, 1788), 'numpy.maximum', 'np.maximum', (['epsII', '(0.0)'], {}), '(epsII, 0.0)\n', (1776, 1788), True, 'import numpy as np\n'), ((2695, 2815), 'numpy.maximum', 'np.maximum', (['(self.yield_strength - (self.yield_strength - self.yield_min) * strain /\n self.crit_strain)', 'self.yield_min'], {}), '(self.yield_strength - (self.yield_strength - self.yield_min) *\n strain / self.crit_strain, self.yield_min)\n', (2705, 2815), True, 'import numpy as np\n'), ((3010, 3130), 'numpy.maximum', 'np.maximum', (['(self.yield_strength - (self.yield_strength - self.yield_min) * strain /\n self.crit_strain)', 'self.yield_min'], {}), '(self.yield_strength - (self.yield_strength - self.yield_min) *\n strain / self.crit_strain, self.yield_min)\n', (3020, 3130), True, 'import numpy as np\n'), ((1823, 1859), 'numpy.exp', 'np.exp', (['(self.E_diff / (8.314 * temp))'], {}), '(self.E_diff / (8.314 * temp))\n', (1829, 1859), True, 'import numpy as np\n'), ((2287, 2323), 'numpy.exp', 'np.exp', (['(self.E_diff / (8.314 * temp))'], {}), '(self.E_diff / (8.314 * temp))\n', (2293, 2323), True, 'import numpy as np\n'), ((2824, 2837), 'numpy.min', 'np.min', (['tau_y'], {}), '(tau_y)\n', (2830, 2837), True, 'import numpy as np\n'), ((4802, 4824), 'numpy.maximum', 'np.maximum', (['epsII', '(0.0)'], {}), '(epsII, 0.0)\n', (4812, 4824), True, 'import numpy as np\n'), ((4221, 4243), 'numpy.maximum', 'np.maximum', (['epsII', '(0.0)'], {}), '(epsII, 0.0)\n', (4231, 4243), True, 'import numpy as np\n'), ((582, 615), 'numpy.exp', 'np.exp', (['(self.E1 / self.R / 263.15)'], {}), '(self.E1 / self.R / 263.15)\n', (588, 615), True, 'import numpy as np\n'), ((690, 723), 'numpy.exp', 'np.exp', (['(self.E2 / self.R / 263.15)'], {}), '(self.E2 / self.R / 263.15)\n', (696, 723), True, 'import numpy as np\n'), ((1887, 1925), 'numpy.exp', 'np.exp', (['(self.E1 / (3.0 * 8.314 * temp))'], {}), '(self.E1 / (3.0 * 8.314 * temp))\n', (1893, 1925), True, 'import numpy as np\n'), ((1947, 1985), 'numpy.exp', 'np.exp', (['(self.E2 / (3.0 * 8.314 * temp))'], {}), '(self.E2 / (3.0 * 8.314 * temp))\n', (1953, 1985), True, 'import numpy as np\n'), ((2363, 2401), 'numpy.exp', 'np.exp', (['(self.E1 / (3.0 * 8.314 * temp))'], {}), '(self.E1 / (3.0 * 8.314 * temp))\n', (2369, 2401), True, 'import numpy as np\n'), ((2423, 2461), 'numpy.exp', 'np.exp', (['(self.E2 / (3.0 * 8.314 * temp))'], {}), '(self.E2 / (3.0 * 8.314 * temp))\n', (2429, 2461), True, 'import numpy as np\n')] |
import numpy as np
import torch
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torchvision import transforms
import scipy.ndimage as nd
import cv2
import PIL.Image
import os, random
import os.path as osp
import pickle
from scipy.spatial import distance
from scipy.stats import norm
import init_path
from lib.dataset import imutils
from ipdb import set_trace
class VOC12ClsSalDataset(Dataset):
"""voc2012 multi-label classification dataset with saliency as additional information"""
def __init__(self, voc12_root, cue_file, max_iters=None, new_size=321, mirror=True, mean=(128, 128, 128), std=None,
sal_subdir="sal_sdnet", seed_subdir="base_30_bg", sal_thresh=0.06):
self.voc12_root = voc12_root
self.label_dict = pickle.load(open(cue_file, "rb"))
self.sal_subdir = sal_subdir
self.sal_thresh = sal_thresh
self.seed_subdir = seed_subdir
self.img_name_list = sorted(list(self.label_dict.keys()))
if max_iters:
self.img_name_list = self.img_name_list * int(np.ceil(float(max_iters) / len(self.img_name_list)))
# data pre-processing
self.mirror = mirror
self.new_size = new_size
self.mean = mean # in BGR order
self.std = std
def __len__(self):
return len(self.img_name_list)
def __getitem__(self, idx):
name = self.img_name_list[idx]
im_full_name = osp.join(self.voc12_root, "JPEGImages", name + ".jpg")
sal_full_name = osp.join(self.voc12_root, "sal", self.sal_subdir, name + ".png")
seed_full_name = osp.join(self.voc12_root, "ini_seed", self.seed_subdir, name + ".png")
im = cv2.imread(im_full_name)
sal = cv2.imread(sal_full_name, cv2.IMREAD_GRAYSCALE)
seed = cv2.imread(seed_full_name, cv2.IMREAD_GRAYSCALE)
h, w = im.shape[:2]
# resize
im = nd.zoom(im, (self.new_size / h, self.new_size / w, 1), order=1)
sal = nd.zoom(sal, (self.new_size / h, self.new_size / w), order=1)
seed = nd.zoom(seed, (self.new_size / h, self.new_size / w), order=0)
# subtract mean
im = np.asarray(im, np.float32)
if self.std is not None:
im = im[:, :, ::-1] # change to RGB order
im /= 255.0
im -= self.mean
im /= self.std
else:
im -= self.mean
# for sal from sdnet
# sal = np.asarray(sal, np.float32)
# sal /= 255
# sal_bi = np.ones(sal.shape)
# sal_bi[sal > self.sal_thresh] = 1
# sal_bi[sal <= self.sal_thresh] = 0
# sal_bi = sal_bi.astype(np.uint8)
# HWC->CHW
im = im.transpose((2, 0, 1))
# random flip
if self.mirror:
flip = np.random.choice(2) * 2 - 1
im = im[:, :, ::flip]
sal = sal[:, ::flip]
seed = seed[:, ::flip]
label = np.zeros(shape=(20,), dtype=np.int)
label_ind = self.label_dict[name]
label[label_ind - 1] = 1
# for sal to compute similarity map
feat_size = round(self.new_size / 8 + 0.5)
sal_reduced = nd.zoom(sal, (feat_size / self.new_size, feat_size / self.new_size), order=1).astype(np.float32)
sal_reduced /= 255.0
sal_reduced = sal_reduced > self.sal_thresh
sal_reduced = sal_reduced.astype(np.uint8)
sal_reduced[:1, :] = 0
sal_reduced[:, :1] = 0
sal_reduced[-1:, :] = 0
sal_reduced[:, -1:] = 0
sal_reshape = np.tile(np.reshape(sal_reduced, (feat_size * feat_size, -1)), (1, feat_size * feat_size))
sal_reshape_1 = np.transpose(sal_reshape)
# divide into fg sim and bg sim
fg_sim = sal_reshape * sal_reshape_1
bg_sim = (1 - sal_reshape) * (1 - sal_reshape_1)
fg_sim = fg_sim.astype(np.float32)
bg_sim = bg_sim.astype(np.float32)
bg_sim = bg_sim / (np.sum(bg_sim, axis=-1) + 1e-5)
# preprocess initial seed
seed_reduced = nd.zoom(seed, (feat_size / self.new_size, feat_size / self.new_size), order=0)
zero_ind = np.where(seed_reduced == 0)
seed_reduced[zero_ind] = 21
seed_reduced = seed_reduced - 1
return name, im.copy(), label.copy(), fg_sim.copy(), bg_sim.copy(), seed_reduced.copy(), np.array([h, w])
class VOC12TestSalDataset(Dataset):
"""voc2012 test dataset"""
def __init__(self, voc12_root, cue_file, new_size=321, mean=(128, 128, 128)):
self.voc12_root = voc12_root
self.label_dict = pickle.load(open(cue_file, "rb"))
self.img_name_list = sorted(list(self.label_dict.keys()))
self.new_size = new_size
self.mean = np.asarray(mean, dtype=np.float32).reshape((1, 1, 3)) # in BGR order
def __len__(self):
return len(self.img_name_list)
def __getitem__(self, idx):
name = self.img_name_list[idx]
im_full_name = osp.join(self.voc12_root, "JPEGImages", name + ".jpg")
sal_full_name = osp.join(self.voc12_root, "sal_sdnet", name + ".png")
im = cv2.imread(im_full_name)
sal = cv2.imread(sal_full_name, cv2.IMREAD_GRAYSCALE)
h, w = im.shape[:2]
# resize
im = nd.zoom(im, (self.new_size / h, self.new_size / w, 1), order=1)
sal = nd.zoom(sal, (self.new_size / h, self.new_size / w), order=1)
# subtract mean
im = np.asarray(im, np.float32)
im -= self.mean
# HWC->CHW
im = im.transpose((2, 0, 1))
label = np.zeros(shape=(20,), dtype=np.int)
label_ind = self.label_dict[name]
label[label_ind - 1] = 1
# for sal to compute similarity map
sal = np.asarray(sal, np.float32)
sal /= 255
sal_bi = np.ones(sal.shape) * 21
sal_bi[sal > 0.06] = 1
sal_bi[sal <= 0.06] = 0
sal_bi = sal_bi.astype(np.uint8)
feat_size = round(self.new_size / 4 + 0.5)
sal_reduced = nd.zoom(sal_bi, (feat_size / self.new_size, feat_size / self.new_size), order=0)
sal_reshape = np.tile(np.reshape(sal_reduced, (feat_size * feat_size, -1)), (1, feat_size * feat_size))
sal_reshape_1 = np.transpose(sal_reshape)
# sal_reshape = np.tile(np.reshape(sal_bi, (self.new_size * self.new_size, -1)), (1, self.new_size * self.new_size))
# sal_reshape_1 = np.transpose(sal_reshape)
# divide into fg sim and bg sim
fg_sim = sal_reshape * sal_reshape_1
bg_sim = (1 - sal_reshape) * (1 - sal_reshape_1)
fg_sim = fg_sim.astype(np.float32)
bg_sim = bg_sim.astype(np.float32)
bg_sim = bg_sim / (np.sum(bg_sim, axis=-1) + 1e-5)
return name, im.copy(), label.copy(), fg_sim.copy(), bg_sim.copy(), np.array([h, w])
# class VOC12ClsSeedDataset(Dataset):
# """voc2012 multi-label classification with seed as additional information"""
# def __init__(self, voc12_root, cue_file, seed_subdir=None, max_iters=None, resize=353,
# crop_size=321, mstrain=[], mirror=True, mean=(128, 128, 128), color_jitter=False,
# out_cue=False, ignore_label=21, use_att_mask=False):
# self.voc12_root = voc12_root
# self.seed_subdir = seed_subdir
# self.label_dict = pickle.load(open(cue_file, "rb"))
# self.img_name_list = sorted(list(self.label_dict.keys()))
# if max_iters:
# self.img_name_list = self.img_name_list * int(np.ceil(float(max_iters) / len(self.img_name_list)))
# # data pre-processing
# self.mirror = mirror
# self.crop_size = crop_size
# self.new_size = resize
# self.mstrain = mstrain
# self.color_jitter = color_jitter
# self.mean = np.asarray(mean, dtype=np.float32).reshape((1, 1, 3)) # in BGR order
# self.out_cue = out_cue # produce localization cues format (c * h * w) or segemntation mask format (h * w)
# self.ignore_label = ignore_label
# self.use_att_mask = use_att_mask # whether to output fore-ignore-background mask (1, hw) for balanced self-attention
# def __len__(self):
# return len(self.img_name_list)
# def __getitem__(self, idx):
# name = self.img_name_list[idx]
# im_full_name = osp.join(self.voc12_root, "JPEGImages", name + ".jpg")
# seed_full_name = osp.join(self.voc12_root, self.seed_subdir, name + ".png")
# assert osp.exists(seed_full_name), "{} not exists".format(seed_full_name)
# im = cv2.imread(im_full_name)
# seed = cv2.imread(seed_full_name, cv2.IMREAD_GRAYSCALE)
# h, w = im.shape[:2]
# # resize
# im = nd.zoom(im, (self.new_size / h, self.new_size / w, 1), order=1)
# seed = nd.zoom(seed, (self.new_size / h, self.new_size / w), order=0)
# # color jitter
# if self.color_jitter:
# im = imutils.random_jitter(im)
# # subtract mean
# im = np.asarray(im, np.float32)
# im -= self.mean
# # crop
# im, seed = imutils.random_crop(im, seed, self.crop_size, data_pad_value=(0, 0, 0), label_pad_value=(self.ignore_label,))
# # HWC->CHW
# im = im.transpose((2, 0, 1))
# # random flip
# if self.mirror:
# flip = np.random.choice(2) * 2 - 1
# if flip == -1:
# im = im[:, :, ::-1]
# seed = seed[:, ::-1]
# label = np.zeros(shape=(20,), dtype=np.int)
# label_ind = self.label_dict[name]
# label[label_ind - 1] = 1
# # preprocess initial seed
# feat_size = round(self.crop_size / 8 + 0.5)
# seed_reduced = nd.zoom(seed, (feat_size / seed.shape[0], feat_size / seed.shape[1]), order=0)
# if self.out_cue:
# non_ignore_ind = np.where(seed_reduced != 21)
# cues = np.zeros(shape=(21, feat_size, feat_size), dtype=np.float)
# cues[seed_reduced[non_ignore_ind], non_ignore_ind[0], non_ignore_ind[1]] = 1.0
# if self.use_att_mask:
# att_mask = imutils.generate_att_mask_from_seed(seed_reduced)
# att_mask = np.reshape(att_mask, newshape=(1, -1))
# return name, im.copy(), label.copy(), cues.copy(), np.array([h, w]), att_mask.copy()
# return name, im.copy(), label.copy(), cues.copy(), np.array([h, w])
# else:
# if self.use_att_mask:
# att_mask = imutils.generate_att_mask_from_seed(seed_reduced)
# att_mask = np.reshape(att_mask, newshape=(1, -1))
# return name, im.copy(), label.copy(), seed_reduced.copy(), np.array([h, w]), att_mask.copy()
# return name, im.copy(), label.copy(), seed_reduced.copy(), np.array([h, w])
# class VOC12TestDataset(Dataset):
# """voc2012 multi-label classification dataset"""
# def __init__(self, voc12_root, cue_file, new_size=321, mean=(128, 128, 128)):
# self.voc12_root = voc12_root
# self.label_dict = pickle.load(open(cue_file, "rb"))
# self.img_name_list = sorted(list(self.label_dict.keys()))
# self.new_size = new_size
# self.mean = np.asarray(mean, dtype=np.float32).reshape((1, 1, 3)) # in BGR order
# def __len__(self):
# return len(self.img_name_list)
# def __getitem__(self, idx):
# name = self.img_name_list[idx]
# im_full_name = osp.join(self.voc12_root, "JPEGImages", name + ".jpg")
# im = cv2.imread(im_full_name)
# h, w = im.shape[:2]
# # resize
# im = nd.zoom(im, (self.new_size / h, self.new_size / w, 1), order=1)
# # subtract mean
# im = np.asarray(im, np.float32)
# im -= self.mean
# # HWC->CHW
# im = im.transpose((2, 0, 1))
# label = np.zeros(shape=(20,), dtype=np.int)
# label_ind = self.label_dict[name]
# label[label_ind - 1] = 1
# return name, im.copy(), label.copy(), np.array([h, w])
# def denormalizing(ori_images, mean=(0, 0, 0), std=None):
# """
# denormalizing tensor images with mean and std
# Args:
# images: tensor, N*C*H*W
# mean: tuple
# std: tuple
# """
# images = torch.tensor(ori_images, requires_grad=False)
# if std is not None:
# """pytorch style normalization"""
# mean = torch.tensor(mean).view((1, 3, 1, 1))
# std = torch.tensor(std).view((1, 3, 1, 1))
# images *= std
# images += mean
# images *= 255
# images = torch.flip(images, dims=(1,))
# else:
# """caffe style normalization"""
# mean = torch.tensor(mean).view((1, 3, 1, 1))
# images += mean
# return images
if __name__ == '__main__':
import imutils
import matplotlib.pyplot as plt
plt.switch_backend("agg")
from ipdb import set_trace
# from tools import imutils
voc12_root = "/data1/yaoqi/Dataset/VOCdevkit/VOC2012/"
cue_file = "im_tags.pkl"
batch_size = 2
max_iter = 8000
resize = 353
crop_size = 321
color_jitter = True
save_path = "visualize/viz_dataloader"
if not osp.exists(save_path):
os.mkdir(save_path)
classes = ['background',
'aeroplane',
'bicycle',
'bird',
'boat',
'bottle',
'bus',
'car',
'cat',
'chair',
'cow',
'diningtable',
'dog',
'horse',
'motorbike',
'person',
'pottedplant',
'sheep',
'sofa',
'train',
'tvmonitor']
# test seed dataset
train_dataset = VOC12ClsSeedDataset(voc12_root=voc12_root,
cue_file=cue_file,
max_iters=max_iter * batch_size,
resize=resize,
crop_size=crop_size,
color_jitter=color_jitter,
seed_subdir="ini_seed/ssenet_tb",
mean=(0, 0, 0),
out_cue=False,
use_att_mask=True)
for k, data in enumerate(train_dataset):
name, im, label, seed, size, att_mask = data
im = np.transpose(im, (1, 2, 0)).astype(np.uint8)
f = plt.figure(facecolor="white")
ax = f.add_subplot(1, 3, 1)
ax.imshow(im[:, :, ::-1])
ax.axis("off")
ax = f.add_subplot(1, 3, 2)
ax.matshow(seed)
ax.axis("off")
ax = f.add_subplot(1, 3, 3)
att_mask = np.reshape(att_mask, newshape=seed.shape)
ax.imshow(att_mask, cmap=plt.cm.Greys_r)
ax.axis("off")
plt.tight_layout()
plt.subplots_adjust(wspace=0.01, hspace=0.15)
plt.savefig(os.path.join(save_path, name + ".png"))
plt.close()
if k == 40:
break
# for k, data in enumerate(train_dataset):
# name, im, label, cue, size = data[0], data[1], data[2], data[3], data[4]
# im = np.transpose(im, (1, 2, 0)).astype(np.uint8)
# label_ind = np.where(label == 1)[0]
# cols = len(label_ind)
# f = plt.figure(facecolor="white")
# ax = f.add_subplot(1, cols + 1, 1)
# ax.imshow(im[:, :, ::-1])
# ax.axis("off")
# for m in range(cols):
# ax = f.add_subplot(1, cols + 1, m + 2)
# mask = cue[label_ind[m] + 1, :, :]
# mask = np.array(mask, dtype=np.int)
# ax.matshow(mask)
# ax.axis("off")
# ax.set_title(classes[label_ind[m] + 1])
# # plt.show()
# plt.tight_layout()
# plt.subplots_adjust(wspace=0.01, hspace=0.15)
# plt.savefig(os.path.join(save_path, name + ".png"))
# plt.close()
# if k == 10:
# break | [
"os.mkdir",
"numpy.sum",
"numpy.ones",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.tight_layout",
"os.path.join",
"matplotlib.pyplot.close",
"numpy.transpose",
"os.path.exists",
"scipy.ndimage.zoom",
"numpy.reshape",
"numpy.random.choice",
"numpy.asarray",
"matplotlib.pyplot.subplots_ad... | [((12848, 12873), 'matplotlib.pyplot.switch_backend', 'plt.switch_backend', (['"""agg"""'], {}), "('agg')\n", (12866, 12873), True, 'import matplotlib.pyplot as plt\n'), ((1451, 1505), 'os.path.join', 'osp.join', (['self.voc12_root', '"""JPEGImages"""', "(name + '.jpg')"], {}), "(self.voc12_root, 'JPEGImages', name + '.jpg')\n", (1459, 1505), True, 'import os.path as osp\n'), ((1530, 1594), 'os.path.join', 'osp.join', (['self.voc12_root', '"""sal"""', 'self.sal_subdir', "(name + '.png')"], {}), "(self.voc12_root, 'sal', self.sal_subdir, name + '.png')\n", (1538, 1594), True, 'import os.path as osp\n'), ((1620, 1690), 'os.path.join', 'osp.join', (['self.voc12_root', '"""ini_seed"""', 'self.seed_subdir', "(name + '.png')"], {}), "(self.voc12_root, 'ini_seed', self.seed_subdir, name + '.png')\n", (1628, 1690), True, 'import os.path as osp\n'), ((1704, 1728), 'cv2.imread', 'cv2.imread', (['im_full_name'], {}), '(im_full_name)\n', (1714, 1728), False, 'import cv2\n'), ((1743, 1790), 'cv2.imread', 'cv2.imread', (['sal_full_name', 'cv2.IMREAD_GRAYSCALE'], {}), '(sal_full_name, cv2.IMREAD_GRAYSCALE)\n', (1753, 1790), False, 'import cv2\n'), ((1806, 1854), 'cv2.imread', 'cv2.imread', (['seed_full_name', 'cv2.IMREAD_GRAYSCALE'], {}), '(seed_full_name, cv2.IMREAD_GRAYSCALE)\n', (1816, 1854), False, 'import cv2\n'), ((1914, 1977), 'scipy.ndimage.zoom', 'nd.zoom', (['im', '(self.new_size / h, self.new_size / w, 1)'], {'order': '(1)'}), '(im, (self.new_size / h, self.new_size / w, 1), order=1)\n', (1921, 1977), True, 'import scipy.ndimage as nd\n'), ((1992, 2053), 'scipy.ndimage.zoom', 'nd.zoom', (['sal', '(self.new_size / h, self.new_size / w)'], {'order': '(1)'}), '(sal, (self.new_size / h, self.new_size / w), order=1)\n', (1999, 2053), True, 'import scipy.ndimage as nd\n'), ((2069, 2131), 'scipy.ndimage.zoom', 'nd.zoom', (['seed', '(self.new_size / h, self.new_size / w)'], {'order': '(0)'}), '(seed, (self.new_size / h, self.new_size / w), order=0)\n', (2076, 2131), True, 'import scipy.ndimage as nd\n'), ((2170, 2196), 'numpy.asarray', 'np.asarray', (['im', 'np.float32'], {}), '(im, np.float32)\n', (2180, 2196), True, 'import numpy as np\n'), ((2940, 2975), 'numpy.zeros', 'np.zeros', ([], {'shape': '(20,)', 'dtype': 'np.int'}), '(shape=(20,), dtype=np.int)\n', (2948, 2975), True, 'import numpy as np\n'), ((3662, 3687), 'numpy.transpose', 'np.transpose', (['sal_reshape'], {}), '(sal_reshape)\n', (3674, 3687), True, 'import numpy as np\n'), ((4034, 4112), 'scipy.ndimage.zoom', 'nd.zoom', (['seed', '(feat_size / self.new_size, feat_size / self.new_size)'], {'order': '(0)'}), '(seed, (feat_size / self.new_size, feat_size / self.new_size), order=0)\n', (4041, 4112), True, 'import scipy.ndimage as nd\n'), ((4132, 4159), 'numpy.where', 'np.where', (['(seed_reduced == 0)'], {}), '(seed_reduced == 0)\n', (4140, 4159), True, 'import numpy as np\n'), ((4947, 5001), 'os.path.join', 'osp.join', (['self.voc12_root', '"""JPEGImages"""', "(name + '.jpg')"], {}), "(self.voc12_root, 'JPEGImages', name + '.jpg')\n", (4955, 5001), True, 'import os.path as osp\n'), ((5026, 5079), 'os.path.join', 'osp.join', (['self.voc12_root', '"""sal_sdnet"""', "(name + '.png')"], {}), "(self.voc12_root, 'sal_sdnet', name + '.png')\n", (5034, 5079), True, 'import os.path as osp\n'), ((5093, 5117), 'cv2.imread', 'cv2.imread', (['im_full_name'], {}), '(im_full_name)\n', (5103, 5117), False, 'import cv2\n'), ((5132, 5179), 'cv2.imread', 'cv2.imread', (['sal_full_name', 'cv2.IMREAD_GRAYSCALE'], {}), '(sal_full_name, cv2.IMREAD_GRAYSCALE)\n', (5142, 5179), False, 'import cv2\n'), ((5239, 5302), 'scipy.ndimage.zoom', 'nd.zoom', (['im', '(self.new_size / h, self.new_size / w, 1)'], {'order': '(1)'}), '(im, (self.new_size / h, self.new_size / w, 1), order=1)\n', (5246, 5302), True, 'import scipy.ndimage as nd\n'), ((5317, 5378), 'scipy.ndimage.zoom', 'nd.zoom', (['sal', '(self.new_size / h, self.new_size / w)'], {'order': '(1)'}), '(sal, (self.new_size / h, self.new_size / w), order=1)\n', (5324, 5378), True, 'import scipy.ndimage as nd\n'), ((5417, 5443), 'numpy.asarray', 'np.asarray', (['im', 'np.float32'], {}), '(im, np.float32)\n', (5427, 5443), True, 'import numpy as np\n'), ((5542, 5577), 'numpy.zeros', 'np.zeros', ([], {'shape': '(20,)', 'dtype': 'np.int'}), '(shape=(20,), dtype=np.int)\n', (5550, 5577), True, 'import numpy as np\n'), ((5712, 5739), 'numpy.asarray', 'np.asarray', (['sal', 'np.float32'], {}), '(sal, np.float32)\n', (5722, 5739), True, 'import numpy as np\n'), ((5978, 6063), 'scipy.ndimage.zoom', 'nd.zoom', (['sal_bi', '(feat_size / self.new_size, feat_size / self.new_size)'], {'order': '(0)'}), '(sal_bi, (feat_size / self.new_size, feat_size / self.new_size), order=0\n )\n', (5985, 6063), True, 'import scipy.ndimage as nd\n'), ((6195, 6220), 'numpy.transpose', 'np.transpose', (['sal_reshape'], {}), '(sal_reshape)\n', (6207, 6220), True, 'import numpy as np\n'), ((13180, 13201), 'os.path.exists', 'osp.exists', (['save_path'], {}), '(save_path)\n', (13190, 13201), True, 'import os.path as osp\n'), ((13211, 13230), 'os.mkdir', 'os.mkdir', (['save_path'], {}), '(save_path)\n', (13219, 13230), False, 'import os, random\n'), ((14446, 14475), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'facecolor': '"""white"""'}), "(facecolor='white')\n", (14456, 14475), True, 'import matplotlib.pyplot as plt\n'), ((14710, 14751), 'numpy.reshape', 'np.reshape', (['att_mask'], {'newshape': 'seed.shape'}), '(att_mask, newshape=seed.shape)\n', (14720, 14751), True, 'import numpy as np\n'), ((14833, 14851), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (14849, 14851), True, 'import matplotlib.pyplot as plt\n'), ((14860, 14905), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.01)', 'hspace': '(0.15)'}), '(wspace=0.01, hspace=0.15)\n', (14879, 14905), True, 'import matplotlib.pyplot as plt\n'), ((14974, 14985), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (14983, 14985), True, 'import matplotlib.pyplot as plt\n'), ((3556, 3608), 'numpy.reshape', 'np.reshape', (['sal_reduced', '(feat_size * feat_size, -1)'], {}), '(sal_reduced, (feat_size * feat_size, -1))\n', (3566, 3608), True, 'import numpy as np\n'), ((4334, 4350), 'numpy.array', 'np.array', (['[h, w]'], {}), '([h, w])\n', (4342, 4350), True, 'import numpy as np\n'), ((5776, 5794), 'numpy.ones', 'np.ones', (['sal.shape'], {}), '(sal.shape)\n', (5783, 5794), True, 'import numpy as np\n'), ((6089, 6141), 'numpy.reshape', 'np.reshape', (['sal_reduced', '(feat_size * feat_size, -1)'], {}), '(sal_reduced, (feat_size * feat_size, -1))\n', (6099, 6141), True, 'import numpy as np\n'), ((6764, 6780), 'numpy.array', 'np.array', (['[h, w]'], {}), '([h, w])\n', (6772, 6780), True, 'import numpy as np\n'), ((14926, 14964), 'os.path.join', 'os.path.join', (['save_path', "(name + '.png')"], {}), "(save_path, name + '.png')\n", (14938, 14964), False, 'import os, random\n'), ((3169, 3246), 'scipy.ndimage.zoom', 'nd.zoom', (['sal', '(feat_size / self.new_size, feat_size / self.new_size)'], {'order': '(1)'}), '(sal, (feat_size / self.new_size, feat_size / self.new_size), order=1)\n', (3176, 3246), True, 'import scipy.ndimage as nd\n'), ((3944, 3967), 'numpy.sum', 'np.sum', (['bg_sim'], {'axis': '(-1)'}), '(bg_sim, axis=-1)\n', (3950, 3967), True, 'import numpy as np\n'), ((4719, 4753), 'numpy.asarray', 'np.asarray', (['mean'], {'dtype': 'np.float32'}), '(mean, dtype=np.float32)\n', (4729, 4753), True, 'import numpy as np\n'), ((6655, 6678), 'numpy.sum', 'np.sum', (['bg_sim'], {'axis': '(-1)'}), '(bg_sim, axis=-1)\n', (6661, 6678), True, 'import numpy as np\n'), ((14380, 14407), 'numpy.transpose', 'np.transpose', (['im', '(1, 2, 0)'], {}), '(im, (1, 2, 0))\n', (14392, 14407), True, 'import numpy as np\n'), ((2793, 2812), 'numpy.random.choice', 'np.random.choice', (['(2)'], {}), '(2)\n', (2809, 2812), True, 'import numpy as np\n')] |
''' brief description
detailed description
@Time : 2020/2/26 19:16
@Author : <NAME>
@FileName: split_dataset.py
@Software: PyCharm
'''
import numpy as np
import random
all_path_out = "flow2vec.all.c2v"
train_output = "flow2vec.train.c2v"
val_output = "flow2vec.val.c2v"
test_output = "flow2vec.test.c2v"
max_context = 100
def mix_train():
with open(all_path_out, "r", encoding="utf-8") as f:
all_paths = np.array(f.read().splitlines())
train_paths_idx = np.random.choice(len(all_paths), round(len(all_paths) * 0.8), replace=False)
from_train_paths_idx_idx = np.random.choice(len(train_paths_idx), round(len(train_paths_idx) * 0.1), replace=False)
from_train_paths_idx = train_paths_idx[from_train_paths_idx_idx]
test_paths_idx = np.array(list(set(range(len(all_paths))) - set(train_paths_idx)))
# val_paths_idx = np.array(list(set(range(len(all_paths))) - set(train_paths_idx)))
# val_paths_idx = np.concatenate((val_paths_idx, from_train_paths_idx))
val_paths_idx = np.random.choice(len(all_paths), round(len(all_paths) * 0.2), replace=False)
# train_paths = all_paths[train_paths_idx]
train_paths = all_paths
test_paths = all_paths[test_paths_idx]
val_paths = all_paths[val_paths_idx]
print("train size:{}".format(len(train_paths)))
with open(train_output, "w", encoding="utf-8") as trf:
for path in train_paths:
trf.write(path)
trf.write("\n")
# test_paths = random.sample(all_paths, len(all_paths) // 10)
# val_paths = random.sample(all_paths, len(all_paths) // 10)
print("val size:{}".format(len(val_paths)))
with open(test_output, "w", encoding="utf-8") as tsf:
for path in test_paths:
tsf.write(path)
tsf.write("\n")
with open(val_output, "w", encoding="utf-8") as vf:
for path in val_paths:
vf.write(path)
vf.write("\n")
def split_data():
with open(all_path_out, "r", encoding="utf-8") as f:
all_paths_pre = np.array(f.read().splitlines())
all_paths = list()
for line in all_paths_pre:
lilist = line.strip().split(" ")
if len(lilist) < 50:
continue
path_context = lilist[1:]
path_len = len(path_context)
num_space = 0
# path length > max_context - random sample
if path_len > max_context:
# index = np.random.choice(paths.shape[0], max_context, replace=False)
# paths = paths[index]
path_context = random.sample(path_context, max_context)
# padding with " "
else:
num_space = max_context - path_len
newline = ""
newline += lilist[0]
# write path
for triple in path_context:
newline += " "
newline += triple
# write padding
for ct in range(num_space):
newline += " "
all_paths.append(newline)
all_paths = np.array(all_paths)
train_paths_idx = np.random.choice(len(all_paths), round(len(all_paths) * 0.8), replace=False)
test_paths_idx = np.array(list(set(range(len(all_paths))) - set(train_paths_idx)))
val_paths_idx = np.array(list(set(range(len(all_paths))) - set(train_paths_idx)))
train_paths = all_paths[train_paths_idx]
test_paths = all_paths[test_paths_idx]
val_paths = all_paths[val_paths_idx]
print("train size:{}".format(len(train_paths)))
with open(train_output, "w", encoding="utf-8") as trf:
for path in train_paths:
trf.write(path)
trf.write("\n")
# test_paths = random.sample(all_paths, len(all_paths) // 10)
# val_paths = random.sample(all_paths, len(all_paths) // 10)
print("val size:{}".format(len(val_paths)))
with open(test_output, "w", encoding="utf-8") as tsf:
for path in test_paths:
tsf.write(path)
tsf.write("\n")
with open(val_output, "w", encoding="utf-8") as vf:
for path in val_paths:
vf.write(path)
vf.write("\n")
if __name__ == '__main__':
mix_train()
| [
"random.sample",
"numpy.array"
] | [((3173, 3192), 'numpy.array', 'np.array', (['all_paths'], {}), '(all_paths)\n', (3181, 3192), True, 'import numpy as np\n'), ((2685, 2725), 'random.sample', 'random.sample', (['path_context', 'max_context'], {}), '(path_context, max_context)\n', (2698, 2725), False, 'import random\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 13 11:05:07 2018
@author: Alexandre
"""
###############################################################################
import numpy as np
###############################################################################
from pyro.dynamic import vehicle
from pyro.planning import discretizer
from pyro.analysis import costfunction
from pyro.planning import valueiteration
from pyro.control import controller
###############################################################################
sys = vehicle.KinematicProtoCarModelwithObstacles()
###############################################################################
# Planning
# Set domain
sys.x_ub = np.array([+3.5, +1, +0.3])
sys.x_lb = np.array([-2, -1, -0.3])
sys.u_ub = np.array([+1, +1])
sys.u_lb = np.array([-1, -1])
# Discrete world
grid_sys = discretizer.GridDynamicSystem(sys, (61, 61, 21), (3, 3), 0.025)
# Cost Function
cf = costfunction.QuadraticCostFunction(sys.n,sys.m,sys.p)
cf.xbar = np.array( [3, 0, 0] ) # target
cf.INF = 1E4
cf.EPS = 0.05
cf.R = np.array([[0.01,0],[0,0]])
# VI algo
vi = valueiteration.ValueIteration_ND( grid_sys , cf )
vi.uselookuptable = True
vi.initialize()
#if load_data:
vi.load_data('udes_racecar')
# vi.compute_steps(50, plot=True, maxJ=100)
#if save_data:
# vi.save_data('udes_racecar')
vi.assign_interpol_controller()
vi.plot_cost2go(maxJ=100)
vi.plot_policy(0)
vi.plot_policy(1)
cl_sys = controller.ClosedLoopSystem( sys , vi.ctl )
#
## Simulation and animation
cl_sys.x0 = np.array([0, 0, 0])
tf = 5
cl_sys.compute_trajectory(tf, 10001, 'euler')
cl_sys.plot_trajectory('xu')
cl_sys.animate_simulation() | [
"pyro.planning.valueiteration.ValueIteration_ND",
"pyro.control.controller.ClosedLoopSystem",
"pyro.planning.discretizer.GridDynamicSystem",
"pyro.dynamic.vehicle.KinematicProtoCarModelwithObstacles",
"pyro.analysis.costfunction.QuadraticCostFunction",
"numpy.array"
] | [((545, 590), 'pyro.dynamic.vehicle.KinematicProtoCarModelwithObstacles', 'vehicle.KinematicProtoCarModelwithObstacles', ([], {}), '()\n', (588, 590), False, 'from pyro.dynamic import vehicle\n'), ((709, 735), 'numpy.array', 'np.array', (['[+3.5, +1, +0.3]'], {}), '([+3.5, +1, +0.3])\n', (717, 735), True, 'import numpy as np\n'), ((747, 771), 'numpy.array', 'np.array', (['[-2, -1, -0.3]'], {}), '([-2, -1, -0.3])\n', (755, 771), True, 'import numpy as np\n'), ((784, 802), 'numpy.array', 'np.array', (['[+1, +1]'], {}), '([+1, +1])\n', (792, 802), True, 'import numpy as np\n'), ((814, 832), 'numpy.array', 'np.array', (['[-1, -1]'], {}), '([-1, -1])\n', (822, 832), True, 'import numpy as np\n'), ((862, 925), 'pyro.planning.discretizer.GridDynamicSystem', 'discretizer.GridDynamicSystem', (['sys', '(61, 61, 21)', '(3, 3)', '(0.025)'], {}), '(sys, (61, 61, 21), (3, 3), 0.025)\n', (891, 925), False, 'from pyro.planning import discretizer\n'), ((947, 1002), 'pyro.analysis.costfunction.QuadraticCostFunction', 'costfunction.QuadraticCostFunction', (['sys.n', 'sys.m', 'sys.p'], {}), '(sys.n, sys.m, sys.p)\n', (981, 1002), False, 'from pyro.analysis import costfunction\n'), ((1012, 1031), 'numpy.array', 'np.array', (['[3, 0, 0]'], {}), '([3, 0, 0])\n', (1020, 1031), True, 'import numpy as np\n'), ((1082, 1111), 'numpy.array', 'np.array', (['[[0.01, 0], [0, 0]]'], {}), '([[0.01, 0], [0, 0]])\n', (1090, 1111), True, 'import numpy as np\n'), ((1126, 1172), 'pyro.planning.valueiteration.ValueIteration_ND', 'valueiteration.ValueIteration_ND', (['grid_sys', 'cf'], {}), '(grid_sys, cf)\n', (1158, 1172), False, 'from pyro.planning import valueiteration\n'), ((1459, 1499), 'pyro.control.controller.ClosedLoopSystem', 'controller.ClosedLoopSystem', (['sys', 'vi.ctl'], {}), '(sys, vi.ctl)\n', (1486, 1499), False, 'from pyro.control import controller\n'), ((1547, 1566), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (1555, 1566), True, 'import numpy as np\n')] |
import hashlib
import numpy as np
import tensorflow as tf
import os
import pickle
import time
class Header:
def __init__(self, n: int, prev, w, t, p, timestamp: int):
self.blockNumber = n
self.prevBlockHash = prev
self.weightHash = w
self.testsetHash = t
self.participantHash = p
self.timestamp = timestamp
class Block:
def __init__(self, blockNumber: int, prevBlockHash, weights: list, testset: tuple, participants: list, timestamp: int):
self.header = Header(
blockNumber,
prevBlockHash,
self.calWeightHash(weights),
self.calTestsetHash(testset),
self.calParticipantHash(participants),
timestamp
)
self.weights = weights
self.testset = testset
self.participants = participants
def calBlockHash(self):
header_list = list()
header_list.append(bytes(self.header.blockNumber))
header_list.append(self.header.prevBlockHash.encode('utf-8'))
header_list.append(self.header.weightHash.encode('utf-8'))
header_list.append(self.header.testsetHash.encode('utf-8'))
return self.__getHash(header_list)
def calWeightHash(self, weights: list):
weights_list = list()
for weight in weights:
# print("original:", weight, weight.shape, weight.dtype.name)
# t = weight.dtype.name
# s = weight.shape
b = weight.tobytes()
# f = np.frombuffer(b, dtype=t).reshape(s)
# print("encoded :", f, f.shape, f.dtype.name)
weights_list.append(b)
# if type(weight) == np.ndarray:
# weight = weight.tolist()
# weights_list.append(weight)
return self.__getHash(weights_list)
def calTestsetHash(self, testset: tuple):
testset_list = list()
for i in testset:
# (x, y)
if type(i) != np.ndarray:
i = np.array(i)
b = i.tobytes()
testset_list.append(b)
return self.__getHash(testset_list)
def calParticipantHash(self, participants: list):
participants = np.array(participants)
participants.tobytes()
return self.__getHash(participants)
def __getHash(self, inputs=[]):
SHA3 = hashlib.sha3_256()
for i in inputs:
SHA3.update(i)
return SHA3.hexdigest()
def delegate(method, prop):
def decorate(cls):
setattr(cls, method,
lambda self, *args, **kwargs:
getattr(getattr(self, prop), method)(*args, **kwargs))
return cls
return decorate
@delegate("__len__", "blocks")
class Blockchain:
def __init__(self, genesisBlock):
self.blocks = [genesisBlock]
def append(self, block):
self.blocks.append(block)
def getBlock(self, blockNumber):
return self.blocks[blockNumber]
# def len(self):
# pass
def printBlock(block: Block):
print("{")
print(" \"blockNumber\" :", block.header.blockNumber, end=",\n")
print(" \"prevBlockHash\" :", block.header.prevBlockHash, end=",\n")
print(" \"timestamp\" :", block.header.timestamp, end=",\n")
print(" \"weightHash\" :", block.header.weightHash, end=",\n")
print(" \"testsetHash\" :", block.header.testsetHash, end=",\n")
print(" \"participantHash\":", block.header.participantHash, end=",\n")
print(" \"(+)testsetSize\" :", len(block.testset[0]), end=",\n")
print(" \"(+)participants\":", len(block.participants), end=",\n")
print(" \"(+)blockHash\" :", block.calBlockHash())
print("}")
def writeBlock(PATH, block: Block):
# Create directory
try:
os.mkdir(PATH) # Create target Directory
except FileExistsError:
pass
# Write
with open(PATH + "/block_" + str(block.header.blockNumber) + ".bin", "wb") as f:
pickle.dump(block, f)
def readBlock(PATH, blockNumber: int):
with open(PATH + "/block_" + str(blockNumber) + ".bin", "rb") as f:
return pickle.load(f)
def writeBlockchain(PATH, blockchain: Blockchain):
# Create directory
try:
os.mkdir(PATH) # Create target Directory
except FileExistsError:
pass
# Write
with open(PATH + "/chain.bin", "wb") as f:
pickle.dump(blockchain, f)
def readBlockchain(PATH):
with open(PATH + "/chain.bin", "rb") as f:
return pickle.load(f)
if __name__ == "__main__":
from model import FLModel
import tensorflow as tf
from time import time
# load data
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
testset = (x_test, y_test)
# set FL model
mnist_model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
mnist_model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
flmodel = FLModel(mnist_model)
# set Blockchain
init_weights = flmodel.get_weights()
genesis = Block(
0,
"0" * 64,
init_weights,
testset,
[],
int(time())
)
flchain = Blockchain(genesis) # set blockchain with genesis block
flmodel.fit(x_train, y_train, epochs=1) # training
nextBlockNumber = 1
modified_weight = flmodel.get_weights()
new_block = Block(
nextBlockNumber,
flchain.getBlock(nextBlockNumber - 1).calBlockHash(),
modified_weight,
testset,
[],
int(time())
)
flchain.append(new_block)
flmodel.evaluate(x_test, y_test)
print(flmodel.loss, flmodel.metrics)
# write blockchain
writeBlockchain("../data", flchain)
# read blockchain
flchain = readBlockchain("../data")
print(flchain.blocks[0].calBlockHash())
print(flchain.blocks[1].header.prevBlockHash)
| [
"os.mkdir",
"pickle.dump",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Dense",
"model.FLModel",
"time.time",
"pickle.load",
"numpy.array",
"hashlib.sha3_256",
"tensorflow.keras.layers.Flatten"
] | [((5268, 5288), 'model.FLModel', 'FLModel', (['mnist_model'], {}), '(mnist_model)\n', (5275, 5288), False, 'from model import FLModel\n'), ((2202, 2224), 'numpy.array', 'np.array', (['participants'], {}), '(participants)\n', (2210, 2224), True, 'import numpy as np\n'), ((2352, 2370), 'hashlib.sha3_256', 'hashlib.sha3_256', ([], {}), '()\n', (2368, 2370), False, 'import hashlib\n'), ((3797, 3811), 'os.mkdir', 'os.mkdir', (['PATH'], {}), '(PATH)\n', (3805, 3811), False, 'import os\n'), ((3986, 4007), 'pickle.dump', 'pickle.dump', (['block', 'f'], {}), '(block, f)\n', (3997, 4007), False, 'import pickle\n'), ((4136, 4150), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (4147, 4150), False, 'import pickle\n'), ((4244, 4258), 'os.mkdir', 'os.mkdir', (['PATH'], {}), '(PATH)\n', (4252, 4258), False, 'import os\n'), ((4395, 4421), 'pickle.dump', 'pickle.dump', (['blockchain', 'f'], {}), '(blockchain, f)\n', (4406, 4421), False, 'import pickle\n'), ((4512, 4526), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (4523, 4526), False, 'import pickle\n'), ((4914, 4959), 'tensorflow.keras.layers.Flatten', 'tf.keras.layers.Flatten', ([], {'input_shape': '(28, 28)'}), '(input_shape=(28, 28))\n', (4937, 4959), True, 'import tensorflow as tf\n'), ((4969, 5018), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(512)'], {'activation': 'tf.nn.relu'}), '(512, activation=tf.nn.relu)\n', (4990, 5018), True, 'import tensorflow as tf\n'), ((5028, 5056), 'tensorflow.keras.layers.Dropout', 'tf.keras.layers.Dropout', (['(0.2)'], {}), '(0.2)\n', (5051, 5056), True, 'import tensorflow as tf\n'), ((5066, 5117), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(10)'], {'activation': 'tf.nn.softmax'}), '(10, activation=tf.nn.softmax)\n', (5087, 5117), True, 'import tensorflow as tf\n'), ((5465, 5471), 'time.time', 'time', ([], {}), '()\n', (5469, 5471), False, 'from time import time\n'), ((5852, 5858), 'time.time', 'time', ([], {}), '()\n', (5856, 5858), False, 'from time import time\n'), ((2003, 2014), 'numpy.array', 'np.array', (['i'], {}), '(i)\n', (2011, 2014), True, 'import numpy as np\n')] |
import os
import random
import sys
import time
import numpy as np
import torch
from a2c_ppo_acktr import utils
from collections import deque
def learn(shared_list, done_list, rollout_storages, test_q,
done_training, device, agents,
shared_cpu_actor_critics, please_load_model, args):
"""
Learn grab data from a data storage and update the parameters.
The updated parameters are loaded to
shared_cpu_actor_critics for actors to load.
Args:
shared_list: A shared list that indicates if environment processes are waiting.
done_list: A shared list that indicates if environment processes finish all steps.
rollout_storages : A list of two rollout storage.
test_q: A shared queue to communicate with the evaluation process.
done_training: A shared variable. Set to one when the learn finish its job.
device: CPU/GPU device.
agents: A list of models. Used to update parameters.
shared_cpu_actor_critics: A list of shared models. It contains the updated parameters.
please_load_model: A shared integer. Set to one when the updated mode is ready for loading.
args: Command line arguments.
Returns:
None
"""
if args.cuda_deterministic:
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
torch.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed)
np.random.seed(args.seed)
random.seed(args.seed)
os.environ['PYTHONHASHSEED'] = str(args.seed)
sync_count = 0
target_eval_step = args.eval_freq
start_sync_step = time.time()
for agent_idx in range(args.num_agents):
agents[agent_idx].actor_critic.to(device)
left_agent_idx = [i for i in range(args.num_left_agents)]
right_agent_idx = [i for i in range(args.num_left_agents, args.num_agents)]
update_times = [0]
num_updates = int(
args.num_env_steps) // args.sync_every // args.num_processes
fps_log = deque(maxlen=10)
while True:
if False not in shared_list: # all env process waiting
st_idx = sync_count % 2
agents_to_train = left_agent_idx + right_agent_idx
sync_count += 1
# ask env process to load the updated model, and wait for acknowledgement
please_load_model.value = 1
while True:
if please_load_model.value == 0:
break
total_steps = sync_count * args.num_processes * args.sync_every
fps = int((args.sync_every * args.num_processes) /
(time.time() - start_sync_step))
fps_log.append(fps)
print('---------------------\n'
'SYNC : {}\n'
'Steps : {}\n'
'Sync SPS : {}\n'
'Average SPS : {}\n'
'Sync time : {:.6f}\n'
'Update time : {:.6f}\n'
'---------------------'.format(
sync_count, total_steps, fps, np.mean(fps_log), time.time() - start_sync_step, update_times[-1]))
sys.stdout.flush()
start_sync_step = time.time()
start_update = time.time()
for i in range(len(shared_list)):
shared_list[i] = False
for agent_idx in agents_to_train:
# update model
if args.use_linear_lr_decay:
# decrease learning rate linearly
utils.update_linear_schedule(
agents[agent_idx].optimizer, sync_count, num_updates, args.lr)
one_agent_rollout = rollout_storages[st_idx].get_one_agent_rollout(
agent_idx, is_aug=False)
one_agent_rollout.to(device)
with torch.no_grad():
input_obs = one_agent_rollout.obs[-1]
next_value = agents[agent_idx].actor_critic.get_value(
input_obs, one_agent_rollout.recurrent_hidden_states[-1],
one_agent_rollout.masks[-1]).detach()
one_agent_rollout.compute_returns(next_value, args.use_gae,
args.gamma,
args.gae_lambda,
args.use_proper_time_limits)
value_loss, action_loss, dist_entropy = agents[agent_idx].update(
one_agent_rollout)
shared_cpu_actor_critics[agent_idx].load_state_dict(
agents[agent_idx].actor_critic.state_dict())
update_times.append(time.time() - start_update)
if args.eval_every_step > 0 and total_steps >= target_eval_step:
target_eval_step += args.eval_every_step
if not test_q.empty():
print(
"Wanring: eval slower than training, please decrease eval_freq")
test_q.put(1)
print('INFO: Sent model for evaluation')
sys.stdout.flush()
if False not in done_list:
break
done_training.value = True
print('Done Learning')
| [
"numpy.random.seed",
"torch.manual_seed",
"time.time",
"torch.cuda.manual_seed_all",
"numpy.mean",
"random.seed",
"sys.stdout.flush",
"a2c_ppo_acktr.utils.update_linear_schedule",
"torch.no_grad",
"collections.deque"
] | [((1376, 1404), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (1393, 1404), False, 'import torch\n'), ((1409, 1446), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['args.seed'], {}), '(args.seed)\n', (1435, 1446), False, 'import torch\n'), ((1451, 1476), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (1465, 1476), True, 'import numpy as np\n'), ((1481, 1503), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (1492, 1503), False, 'import random\n'), ((1634, 1645), 'time.time', 'time.time', ([], {}), '()\n', (1643, 1645), False, 'import time\n'), ((2012, 2028), 'collections.deque', 'deque', ([], {'maxlen': '(10)'}), '(maxlen=10)\n', (2017, 2028), False, 'from collections import deque\n'), ((3163, 3181), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (3179, 3181), False, 'import sys\n'), ((3212, 3223), 'time.time', 'time.time', ([], {}), '()\n', (3221, 3223), False, 'import time\n'), ((3251, 3262), 'time.time', 'time.time', ([], {}), '()\n', (3260, 3262), False, 'import time\n'), ((5145, 5163), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (5161, 5163), False, 'import sys\n'), ((3083, 3099), 'numpy.mean', 'np.mean', (['fps_log'], {}), '(fps_log)\n', (3090, 3099), True, 'import numpy as np\n'), ((3546, 3641), 'a2c_ppo_acktr.utils.update_linear_schedule', 'utils.update_linear_schedule', (['agents[agent_idx].optimizer', 'sync_count', 'num_updates', 'args.lr'], {}), '(agents[agent_idx].optimizer, sync_count,\n num_updates, args.lr)\n', (3574, 3641), False, 'from a2c_ppo_acktr import utils\n'), ((3858, 3873), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3871, 3873), False, 'import torch\n'), ((4724, 4735), 'time.time', 'time.time', ([], {}), '()\n', (4733, 4735), False, 'import time\n'), ((2624, 2635), 'time.time', 'time.time', ([], {}), '()\n', (2633, 2635), False, 'import time\n'), ((3101, 3112), 'time.time', 'time.time', ([], {}), '()\n', (3110, 3112), False, 'import time\n')] |
from __future__ import print_function
import os, struct, math
import numpy as np
import torch
from glob import glob
import cv2
import torch.nn.functional as F
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.mplot3d import Axes3D
from scipy.spatial.transform import Rotation as R
from matplotlib import cm
import re
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
def get_latest_file(root_dir):
"""Returns path to latest file in a directory."""
list_of_files = glob.glob(os.path.join(root_dir, '*'))
latest_file = max(list_of_files, key=os.path.getctime)
return latest_file
def parse_num_range(s):
'''Accept either a comma separated list of numbers 'a,b,c' or a range 'a-c' and return as a list of ints.'''
range_re = re.compile(r'^(\d+)-(\d+)$')
m = range_re.match(s)
if m:
return list(range(int(m.group(1)), int(m.group(2))+1))
vals = s.split(',')
return [int(x) for x in vals]
def convert_image(img):
if not isinstance(img, np.ndarray):
img = np.array(img.cpu().detach().numpy())
img = img.squeeze()
img = img.transpose(1,2,0)
img += 1.
img /= 2.
img *= 2**8 - 1
img = img.round().clip(0, 2**8-1)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return img
def write_img(img, path):
cv2.imwrite(path, img.astype(np.uint8))
def in_out_to_param_count(in_out_tuples):
return np.sum([np.prod(in_out) + in_out[-1] for in_out in in_out_tuples])
def lin2img(tensor, color_map=None):
batch_size, num_samples, channels = tensor.shape
sidelen = np.sqrt(num_samples).astype(int)
if color_map is not None:
tensor = tensor.squeeze(2).long()
output_img = torch.cat([color_map[p].unsqueeze(0) for p in tensor], dim=0)
channels = output_img.shape[-1]
else:
output_img = tensor
return output_img.permute(0,2,1).view(batch_size, channels, sidelen, sidelen)
def num_divisible_by_2(number):
i = 0
while not number%2:
number = number // 2
i += 1
return i
def cond_mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def load_pose(filename):
assert os.path.isfile(filename)
lines = open(filename).read().splitlines()
assert len(lines) == 4
lines = [[x[0],x[1],x[2],x[3]] for x in (x.split(" ") for x in lines)]
return torch.from_numpy(np.asarray(lines).astype(np.float32))
def normalize(img):
return (img - img.min()) / (img.max() - img.min())
def write_image(writer, name, img, iter):
writer.add_image(name, normalize(img.permute([0,3,1,2])), iter)
def print_network(net):
model_parameters = filter(lambda p: p.requires_grad, net.parameters())
params = sum([np.prod(p.size()) for p in model_parameters])
print("%d"%params)
def custom_load(model, path, discriminator=None, overwrite_embeddings=False, overwrite_renderer=False, overwrite_cam=True, optimizer=None):
if os.path.isdir(path):
checkpoint_path = sorted(glob(os.path.join(path, "*.pth")))[-1]
else:
checkpoint_path = path
whole_dict = torch.load(checkpoint_path)
if overwrite_embeddings:
del whole_dict['model']['latent_codes.weight']
if overwrite_cam:
if 'cam_pose.weight' in whole_dict['model']:
del whole_dict['model']['cam_pose.weight']
if overwrite_renderer:
keys_to_remove = [key for key in whole_dict['model'].keys() if 'rendering_net' in key]
for key in keys_to_remove:
print(key)
whole_dict['model'].pop(key, None)
state = model.state_dict()
state.update(whole_dict['model'])
model.load_state_dict(state)
if discriminator:
discriminator.load_state_dict(whole_dict['discriminator'])
if optimizer:
optimizer.load_state_dict(whole_dict['optimizer'])
def custom_save(model, path, discriminator=None, optimizer=None):
whole_dict = {'model':model.state_dict()}
if discriminator:
whole_dict.update({'discriminator':discriminator.state_dict()})
if optimizer:
whole_dict.update({'optimizer':optimizer.state_dict()})
torch.save(whole_dict, path)
def show_images(images, titles=None):
"""Display a list of images in a single figure with matplotlib.
Parameters
---------
images: List of np.arrays compatible with plt.imshow.
cols (Default = 1): Number of columns in figure (number of rows is
set to np.ceil(n_images/float(cols))).
titles: List of titles corresponding to each image. Must have
the same length as titles.
"""
assert ((titles is None) or (len(images) == len(titles)))
cols = np.ceil(np.sqrt(len(images))).astype(int)
n_images = len(images)
if titles is None: titles = ['Image (%d)' % i for i in range(1, n_images + 1)]
fig = plt.figure()
for n, (image, title) in enumerate(zip(images, titles)):
a = fig.add_subplot(np.ceil(n_images / float(cols)), cols, n + 1)
im = a.imshow(image)
a.get_xaxis().set_visible(False)
a.get_yaxis().set_visible(False)
if len(images) < 10:
divider = make_axes_locatable(a)
cax = divider.append_axes("right", size="5%", pad=0.05)
fig.colorbar(im, cax=cax, orientation='vertical')
plt.tight_layout()
# fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)
return fig
# def transform_points(self, points, eps: Optional[float] = None):
# """
# Use this transform to transform a set of 3D points. Assumes row major
# ordering of the input points.
# Args:
# points: Tensor of shape (P, 3) or (N, P, 3)
# eps: If eps!=None, the argument is used to clamp the
# last coordinate before peforming the final division.
# The clamping corresponds to:
# last_coord := (last_coord.sign() + (last_coord==0)) *
# torch.clamp(last_coord.abs(), eps),
# i.e. the last coordinates that are exactly 0 will
# be clamped to +eps.
# Returns:
# points_out: points of shape (N, P, 3) or (P, 3) depending
# on the dimensions of the transform
# """
# points_batch = points.clone()
# if points_batch.dim() == 2:
# points_batch = points_batch[None] # (P, 3) -> (1, P, 3)
# if points_batch.dim() != 3:
# msg = "Expected points to have dim = 2 or dim = 3: got shape %r"
# raise ValueError(msg % repr(points.shape))
# N, P, _3 = points_batch.shape
# ones = torch.ones(N, P, 1, dtype=points.dtype, device=points.device)
# points_batch = torch.cat([points_batch, ones], dim=2)
# composed_matrix = self.get_matrix()
# points_out = _broadcast_bmm(points_batch, composed_matrix)
# denom = points_out[..., 3:] # denominator
# if eps is not None:
# denom_sign = denom.sign() + (denom == 0.0).type_as(denom)
# denom = denom_sign * torch.clamp(denom.abs(), eps)
# points_out = points_out[..., :3] / denom
# # When transform is (1, 4, 4) and points is (P, 3) return
# # points_out of shape (P, 3)
# if points_out.shape[0] == 1 and points.dim() == 2:
# points_out = points_out.reshape(points.shape)
# return points_out
def plot_camera_scene(cam_pose):
"""
Plots a set of predicted cameras `cameras` and their corresponding
ground truth locations `cameras_gt`. The plot is named with
a string passed inside the `status` argument.
"""
def _get_camera_wireframe(scale: float = 0.3):
"""
Returns a wireframe of a 3D line-plot of a camera symbol.
"""
a = 0.5 * np.array([-2, 1.5, 4])
b = 0.5 * np.array([2, 1.5, 4])
c = 0.5 * np.array([-2, -1.5, 4])
d = 0.5 * np.array([2, -1.5, 4])
C = np.zeros(3)
F = np.array([0, 0, 3])
camera_points = [a, b, d, c, a, C, b, d, C, c, C, F]
lines = np.stack([x.astype(np.float) for x in camera_points]) * scale
return lines
def _plot_cameras(ax, cam_pose, color: str = "blue"):
"""
Plots a set of `cameras` objects into the maplotlib axis `ax` with
color `color`.
"""
cam_wires_canonical = _get_camera_wireframe().T
cam_wires_canonical = np.expand_dims(cam_wires_canonical, axis=0)
cam_R = cam_pose[:, :3, :3]
cam_T = cam_pose[:, :3, 3:]
cam_wires_trans = cam_R@cam_wires_canonical
cam_wires_trans = cam_wires_trans + cam_T
plot_handles = []
for idx in range(cam_wires_trans.shape[0]):
# the Z and Y axes are flipped intentionally here!
x_, z_, y_ = cam_wires_trans[idx].astype(float)
(h,) = ax.plot(x_, y_, z_, color=color, linewidth=0.3)
plot_handles.append(h)
return plot_handles
fig = plt.figure(figsize=(10, 5))
ax = fig.gca(projection="3d")
ax.clear()
handle_cam = _plot_cameras(ax, cam_pose, color="#FF7D1E")
plot_radius = 5
ax.set_xlim3d([-plot_radius, plot_radius])
ax.set_ylim3d([-plot_radius, plot_radius])
ax.set_zlim3d([0, plot_radius])
ax.set_xlabel("x")
ax.set_ylabel("z")
ax.set_zlabel("y")
# plt.show()
return fig
| [
"mpl_toolkits.axes_grid1.make_axes_locatable",
"os.path.join",
"os.makedirs",
"cv2.cvtColor",
"os.path.isdir",
"torch.load",
"numpy.asarray",
"os.path.exists",
"numpy.zeros",
"numpy.expand_dims",
"torch.save",
"os.path.isfile",
"matplotlib.pyplot.figure",
"numpy.array",
"numpy.sqrt",
"... | [((829, 858), 're.compile', 're.compile', (['"""^(\\\\d+)-(\\\\d+)$"""'], {}), "('^(\\\\d+)-(\\\\d+)$')\n", (839, 858), False, 'import re\n'), ((1283, 1319), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (1295, 1319), False, 'import cv2\n'), ((2235, 2259), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (2249, 2259), False, 'import os, struct, math\n'), ((3002, 3021), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (3015, 3021), False, 'import os, struct, math\n'), ((3154, 3181), 'torch.load', 'torch.load', (['checkpoint_path'], {}), '(checkpoint_path)\n', (3164, 3181), False, 'import torch\n'), ((4191, 4219), 'torch.save', 'torch.save', (['whole_dict', 'path'], {}), '(whole_dict, path)\n', (4201, 4219), False, 'import torch\n'), ((4900, 4912), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4910, 4912), True, 'import matplotlib.pyplot as plt\n'), ((5371, 5389), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5387, 5389), True, 'import matplotlib.pyplot as plt\n'), ((8929, 8956), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (8939, 8956), True, 'import matplotlib.pyplot as plt\n'), ((563, 590), 'os.path.join', 'os.path.join', (['root_dir', '"""*"""'], {}), "(root_dir, '*')\n", (575, 590), False, 'import os, struct, math\n'), ((2149, 2169), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (2163, 2169), False, 'import os, struct, math\n'), ((2179, 2196), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (2190, 2196), False, 'import os, struct, math\n'), ((7889, 7900), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (7897, 7900), True, 'import numpy as np\n'), ((7913, 7932), 'numpy.array', 'np.array', (['[0, 0, 3]'], {}), '([0, 0, 3])\n', (7921, 7932), True, 'import numpy as np\n'), ((8362, 8405), 'numpy.expand_dims', 'np.expand_dims', (['cam_wires_canonical'], {'axis': '(0)'}), '(cam_wires_canonical, axis=0)\n', (8376, 8405), True, 'import numpy as np\n'), ((1632, 1652), 'numpy.sqrt', 'np.sqrt', (['num_samples'], {}), '(num_samples)\n', (1639, 1652), True, 'import numpy as np\n'), ((5212, 5234), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['a'], {}), '(a)\n', (5231, 5234), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((7731, 7753), 'numpy.array', 'np.array', (['[-2, 1.5, 4]'], {}), '([-2, 1.5, 4])\n', (7739, 7753), True, 'import numpy as np\n'), ((7772, 7793), 'numpy.array', 'np.array', (['[2, 1.5, 4]'], {}), '([2, 1.5, 4])\n', (7780, 7793), True, 'import numpy as np\n'), ((7812, 7835), 'numpy.array', 'np.array', (['[-2, -1.5, 4]'], {}), '([-2, -1.5, 4])\n', (7820, 7835), True, 'import numpy as np\n'), ((7854, 7876), 'numpy.array', 'np.array', (['[2, -1.5, 4]'], {}), '([2, -1.5, 4])\n', (7862, 7876), True, 'import numpy as np\n'), ((1468, 1483), 'numpy.prod', 'np.prod', (['in_out'], {}), '(in_out)\n', (1475, 1483), True, 'import numpy as np\n'), ((2437, 2454), 'numpy.asarray', 'np.asarray', (['lines'], {}), '(lines)\n', (2447, 2454), True, 'import numpy as np\n'), ((3061, 3088), 'os.path.join', 'os.path.join', (['path', '"""*.pth"""'], {}), "(path, '*.pth')\n", (3073, 3088), False, 'import os, struct, math\n')] |
import numpy as np
import os
import time
import random
import pdb
import forecast_lib as fl
import forecast_lib.forecast_training as ft
dropout=False
if dropout:
type_exp = '_dropout'
rho_d = -1
else:
type_exp = ''
rho_d = 1
# experiment parameters
directory = './experiments/ensemble'+type_exp+'/'
m = fl.num_meters
max_num_models = 20
m_d_frac = [0.2, 0.33, 0.5, 0.66, 0.8]
n_vec = [5, 3, 2, 3, 5]
total_load = np.sum(fl.load_meters, axis=1)
max_load = max(total_load)
for i in range(len(n_vec)):
print('model = '+str(i))
dir_rep = directory + 'model_'+str(i) +'/'
try:
os.makedirs(dir_rep)
except:
pass
m_d = m_d_frac[i]
n = n_vec[i]
t0 = time.perf_counter()
print('\t n: '+str(n))
for k in range(10, 20):
model_name = 'model_' + str(k)
if m_d <= 0.5:
list_meters = ft.get_partition( m, n )
else:
list_meters = ft.get_sets( m, n )
np.save(dir_rep + 'meters_' + str(k) + '.npy', list_meters)
# define the target for the experiment
for j in range(n):
# get the total load for the meters
ft.y = np.sum(fl.load_meters[:, list_meters[j]], axis=1)/max_load
# extract the data for this set
model_name_j = model_name + '_' + str(j)
data_j = fl.extract_data( [list_meters[j]] )
fl.train_and_save_forecaster(dir_rep, data_j, model_name_j, rho_d)
t_f = time.perf_counter()
print('\t***Train time: ' + str((t_f-t0)/60.0))
| [
"numpy.sum",
"os.makedirs",
"forecast_lib.train_and_save_forecaster",
"time.perf_counter",
"forecast_lib.forecast_training.get_sets",
"forecast_lib.forecast_training.get_partition",
"forecast_lib.extract_data"
] | [((427, 457), 'numpy.sum', 'np.sum', (['fl.load_meters'], {'axis': '(1)'}), '(fl.load_meters, axis=1)\n', (433, 457), True, 'import numpy as np\n'), ((674, 693), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (691, 693), False, 'import time\n'), ((1325, 1344), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (1342, 1344), False, 'import time\n'), ((595, 615), 'os.makedirs', 'os.makedirs', (['dir_rep'], {}), '(dir_rep)\n', (606, 615), False, 'import os\n'), ((812, 834), 'forecast_lib.forecast_training.get_partition', 'ft.get_partition', (['m', 'n'], {}), '(m, n)\n', (828, 834), True, 'import forecast_lib.forecast_training as ft\n'), ((862, 879), 'forecast_lib.forecast_training.get_sets', 'ft.get_sets', (['m', 'n'], {}), '(m, n)\n', (873, 879), True, 'import forecast_lib.forecast_training as ft\n'), ((1209, 1242), 'forecast_lib.extract_data', 'fl.extract_data', (['[list_meters[j]]'], {}), '([list_meters[j]])\n', (1224, 1242), True, 'import forecast_lib as fl\n'), ((1248, 1314), 'forecast_lib.train_and_save_forecaster', 'fl.train_and_save_forecaster', (['dir_rep', 'data_j', 'model_name_j', 'rho_d'], {}), '(dir_rep, data_j, model_name_j, rho_d)\n', (1276, 1314), True, 'import forecast_lib as fl\n'), ((1058, 1107), 'numpy.sum', 'np.sum', (['fl.load_meters[:, list_meters[j]]'], {'axis': '(1)'}), '(fl.load_meters[:, list_meters[j]], axis=1)\n', (1064, 1107), True, 'import numpy as np\n')] |
""" Tests for turning curve stats"""
import numpy as np
import inspect
from opexebo.analysis import tuning_curve_stats as func
print("=== tests_analysis_turning_curve_stats ===")
###############################################################################
################ MAIN TESTS
###############################################################################
def test_random_data():
n = 1000
data = np.random.rand(n) * 2 * np.pi
tuning_curve = np.histogram(data, bins=int(360 / 15))[0]
func(tuning_curve)
print(f"{inspect.stack()[0][3]} passed")
return True
# if __name__ == '__main__':
# test_random_data()
| [
"numpy.random.rand",
"inspect.stack",
"opexebo.analysis.tuning_curve_stats"
] | [((531, 549), 'opexebo.analysis.tuning_curve_stats', 'func', (['tuning_curve'], {}), '(tuning_curve)\n', (535, 549), True, 'from opexebo.analysis import tuning_curve_stats as func\n'), ((436, 453), 'numpy.random.rand', 'np.random.rand', (['n'], {}), '(n)\n', (450, 453), True, 'import numpy as np\n'), ((563, 578), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (576, 578), False, 'import inspect\n')] |
import numpy as np
from scipy.linalg import solve_triangular
from scipy.spatial.distance import cdist
"""
Active Learning Acquisition Functions (2022/02/07, <NAME> (<EMAIL>))
This script contains the following strategies and related functions:
1. Variance Reduction (IMSE)
2. PIMSE
3. Uncertainty Sampling
4. Variance-based QBC
5. Maximin Distance
*. Random Sampling (Passive Learning)
The acquisition functions have similar interfaces.
1. X_cand: candidate set of points that are to be evaluated
2. gp: Gaussian Process model
3. X_ref: reference set of points for some acquisition functions (generally, the entire design space)
4. weights: prior information for imposing importance on canddiate points (default: uniform)
5. global_search: whether to use global search or local search (default: True). For more information,
please refer to the following paper:
Lee, Cheolhei, et al. "Partitioned Active Learning for Heterogeneous Systems.",
arXiv preprint arXiv:2105.08547 (2021).
"""
# Variacne Reduction (IMSE: Integrated Mean Squared Error)
def imse(X_cand, gp, X_ref, p_ref=None):
n = len(X_cand)
m = len(X_ref)
if p_ref is None:
p_ref = np.ones(m) / m
else:
if len(p_ref) != m or not np.isclose(p_ref.sum(), 1.):
raise Exception("Probability function of reference set is invalid!")
else:
pass
imse_vals = np.zeros(n)
k_ref = gp.kernel_(gp.X_train_, X_ref)
L = gp.L_
v = solve_triangular(L, k_ref, lower=True)
for i in range(n):
xi = X_cand[i][np.newaxis, :]
k12 = gp.kernel_(gp.X_train_, xi)
k22 = gp.kernel_(xi) + 1e-10
k_ = gp.kernel_(xi, X_ref)
L_ = chol_update(L, k12, k22)
l12 = L_[-1, :-1]
k_ -= l12.reshape(1, -1) @ v
imse_vals[i] = np.inner(k_ * p_ref.reshape(k_.shape), k_) / m
return imse_vals
# Partitioned IMSE (PIMSE)
def pimse(X_cand, gp, X_ref, global_search=True):
C_cand = gp.region_classifier.predict(X_cand)
C_ref = gp.region_classifier.predict(X_ref)
cand_labels = np.unique(C_cand)
ref_labels = np.unique(C_ref)
sub_var_vals = np.zeros(len(gp.local_gp))
imse_vals = np.full(len(X_cand), -np.inf)
for c in ref_labels:
if c in gp.unknown_classes:
sub_var_vals[c] = np.inf
else:
sub_var_vals[c] = np.square(gp.local_gp[c].predict(X_ref[C_ref == c], return_std=True)[1]).mean()
if global_search:
# choose the most uncertain region`
c_sel = np.argmax(sub_var_vals)
if c_sel not in C_cand:
raise Exception("No candidate is not in the most uncertain region")
elif c_sel in gp.unknown_classes:
return random_sampling(X_cand)
else:
valid_cand_id = np.where(C_cand == c_sel)[0]
X_sel_cand = X_cand[valid_cand_id]
X_sel_ref = X_ref[valid_cand_id]
imse_vals[valid_cand_id] = imse(X_sel_cand, gp.local_gp[c_sel], X_sel_ref)
return imse_vals
else:
for c in cand_labels:
if c in gp.unknown_classes:
imse_vals[C_cand == c] = -np.inf
else:
imse_vals[C_cand == c] = -imse(X_cand[C_cand == c], gp.local_gp[c], X_ref[C_ref == c]) \
+ sub_var_vals.sum()
return imse_vals
# Uncertainty Sampling
def uncertainty_sampling(X_cand, gp, weights=None):
# check weights has the same length of X_cand
if weights is None:
weights = np.ones(len(X_cand))
weights /= np.sum(weights)
else:
assert len(weights) == len(X_cand), "weights must have the same length as X_cand"
return gp.predict(X_cand, return_std=True)[1] * weights
# Variance-based QBC
def var_qbc(X_cand, gp, model_preference=None, weights=None):
# check more than one GPs are given
assert len(gp.estimators_) > 1, "Only one GP is given"
if model_preference is None:
model_preference = np.ones(len(gp.estimators_))
else:
assert len(model_preference) == len(gp.estimators_), "model_preference must have the same length as gp"
if weights is None:
weights = np.ones(len(X_cand))
else:
assert len(weights) == len(X_cand), "weights must have the same length as X_cand"
weights /= np.sum(weights)
pred_group = np.zeros((len(gp.estimators_), len(X_cand)))
for i, gp in enumerate(gp.estimators_):
pred_group[i] = gp.predict(X_cand) * model_preference[i]
return np.var(pred_group, axis=0) * weights
# Maximin Distance
def maximin_dist(X_cand, gp, metric='euclidean', weights=None):
if weights is None:
weights = np.ones(len(X_cand))
else:
assert len(weights) == len(X_cand), "weights must have the same length as X_cand"
weights /= np.sum(weights)
X_ = gp.X_train_
# return averaged distance of each point in X_cand to X_
return cdist(X_cand, X_, metric=metric).min(axis=1) * weights
# Random Sampling (Note: this is not active learning, but passivie learning)
def random_sampling(X_cand):
score = np.zeros(len(X_cand))
score[np.random.choice(len(X_cand), 1, replace=False)] = 1
return score
"""
Below functions are not acquisition functions or may be deprecated
"""
# Rank-one Cholesky update for IMSE criteria
def chol_update(L, a12, a22, lower=True):
# check if L is lower triangular
if lower:
if np.all(np.triu(L, k=1) == 0.):
pass
else:
raise Exception("L is not a lower triangle matrix")
# if L is upper triangular, transpose it
else:
if np.all(np.tril(L, k=1) == 0.):
L = L.T
else:
raise Exception("L is not an upper triangle matrix")
n = len(L)
# check a12 is compatible with L
if len(a12) != n:
raise Exception("a12 length must be n")
elif np.ndim(a12) != 2:
a12 = a12[:, np.newaxis]
else:
pass
l12 = solve_triangular(L, a12, lower=True)
l22 = np.sqrt(a22 - np.square(l12).sum())
L_sol = np.vstack((
np.hstack((L, np.zeros((n, 1)))),
np.hstack((l12.T, l22))
))
return L_sol
# IMSE criterion using Sherman-Morrison-Woodbury formula
# This has the same performance as the IMSE with Rank-one Cholesky update (imse)
def imse_sherman(X_cand, gp, X_ref):
if np.ndim(X_cand) == 1:
X_cand = X_cand[np.newaxis, :]
else:
pass
m = len(X_cand)
n = len(X_ref)
k_ref = np.trace(gp.predict(X_ref, return_cov=True)[1]) / n
K = gp.kernel_(gp.X_train_) + np.eye(len(gp.X_train_)) * gp.alpha
K_inv = np.linalg.inv(K)
k_ = gp.kernel_(X_ref, gp.X_train_)
imse_vals = np.full(m, k_ref)
for i in range(m):
xi = X_cand[i][np.newaxis, :]
k12 = gp.kernel_(xi, gp.X_train_)
k22 = gp.kernel_(xi) + gp.alpha
v = k22 - k12 @ K_inv @ k12.T
g = - (1 / v) * K_inv @ k12.T
K_aug_inv = np.vstack((np.hstack((K_inv + g @ g.T * v, g)), np.hstack((g.T, (1 / v)))))
k_aug = np.hstack((k_, gp.kernel_(X_ref, xi)))
imse_vals[i] = k_ref - np.trace(k_aug @ K_aug_inv @ k_aug.T) / n
return imse_vals | [
"numpy.full",
"scipy.spatial.distance.cdist",
"numpy.trace",
"numpy.sum",
"scipy.linalg.solve_triangular",
"numpy.triu",
"numpy.argmax",
"numpy.tril",
"numpy.square",
"numpy.zeros",
"numpy.ndim",
"numpy.ones",
"numpy.hstack",
"numpy.where",
"numpy.linalg.inv",
"numpy.var",
"numpy.uni... | [((1433, 1444), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1441, 1444), True, 'import numpy as np\n'), ((1513, 1551), 'scipy.linalg.solve_triangular', 'solve_triangular', (['L', 'k_ref'], {'lower': '(True)'}), '(L, k_ref, lower=True)\n', (1529, 1551), False, 'from scipy.linalg import solve_triangular\n'), ((2131, 2148), 'numpy.unique', 'np.unique', (['C_cand'], {}), '(C_cand)\n', (2140, 2148), True, 'import numpy as np\n'), ((2167, 2183), 'numpy.unique', 'np.unique', (['C_ref'], {}), '(C_ref)\n', (2176, 2183), True, 'import numpy as np\n'), ((6188, 6224), 'scipy.linalg.solve_triangular', 'solve_triangular', (['L', 'a12'], {'lower': '(True)'}), '(L, a12, lower=True)\n', (6204, 6224), False, 'from scipy.linalg import solve_triangular\n'), ((6874, 6890), 'numpy.linalg.inv', 'np.linalg.inv', (['K'], {}), '(K)\n', (6887, 6890), True, 'import numpy as np\n'), ((6949, 6966), 'numpy.full', 'np.full', (['m', 'k_ref'], {}), '(m, k_ref)\n', (6956, 6966), True, 'import numpy as np\n'), ((2598, 2621), 'numpy.argmax', 'np.argmax', (['sub_var_vals'], {}), '(sub_var_vals)\n', (2607, 2621), True, 'import numpy as np\n'), ((3682, 3697), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (3688, 3697), True, 'import numpy as np\n'), ((4467, 4482), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (4473, 4482), True, 'import numpy as np\n'), ((4679, 4705), 'numpy.var', 'np.var', (['pred_group'], {'axis': '(0)'}), '(pred_group, axis=0)\n', (4685, 4705), True, 'import numpy as np\n'), ((4992, 5007), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (4998, 5007), True, 'import numpy as np\n'), ((6591, 6606), 'numpy.ndim', 'np.ndim', (['X_cand'], {}), '(X_cand)\n', (6598, 6606), True, 'import numpy as np\n'), ((1209, 1219), 'numpy.ones', 'np.ones', (['m'], {}), '(m)\n', (1216, 1219), True, 'import numpy as np\n'), ((6097, 6109), 'numpy.ndim', 'np.ndim', (['a12'], {}), '(a12)\n', (6104, 6109), True, 'import numpy as np\n'), ((6349, 6372), 'numpy.hstack', 'np.hstack', (['(l12.T, l22)'], {}), '((l12.T, l22))\n', (6358, 6372), True, 'import numpy as np\n'), ((5106, 5138), 'scipy.spatial.distance.cdist', 'cdist', (['X_cand', 'X_'], {'metric': 'metric'}), '(X_cand, X_, metric=metric)\n', (5111, 5138), False, 'from scipy.spatial.distance import cdist\n'), ((5635, 5650), 'numpy.triu', 'np.triu', (['L'], {'k': '(1)'}), '(L, k=1)\n', (5642, 5650), True, 'import numpy as np\n'), ((5833, 5848), 'numpy.tril', 'np.tril', (['L'], {'k': '(1)'}), '(L, k=1)\n', (5840, 5848), True, 'import numpy as np\n'), ((7224, 7259), 'numpy.hstack', 'np.hstack', (['(K_inv + g @ g.T * v, g)'], {}), '((K_inv + g @ g.T * v, g))\n', (7233, 7259), True, 'import numpy as np\n'), ((7261, 7284), 'numpy.hstack', 'np.hstack', (['(g.T, 1 / v)'], {}), '((g.T, 1 / v))\n', (7270, 7284), True, 'import numpy as np\n'), ((7377, 7414), 'numpy.trace', 'np.trace', (['(k_aug @ K_aug_inv @ k_aug.T)'], {}), '(k_aug @ K_aug_inv @ k_aug.T)\n', (7385, 7414), True, 'import numpy as np\n'), ((2869, 2894), 'numpy.where', 'np.where', (['(C_cand == c_sel)'], {}), '(C_cand == c_sel)\n', (2877, 2894), True, 'import numpy as np\n'), ((6250, 6264), 'numpy.square', 'np.square', (['l12'], {}), '(l12)\n', (6259, 6264), True, 'import numpy as np\n'), ((6320, 6336), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (6328, 6336), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
'''
@author: <NAME>
@email: <EMAIL>
@date: Jan. 28th 2021
'''
import numpy as np
def calculate_BIC(preds, targets, non_zero_term):
'''
calculate BIC
modified the second part
'''
points_num = preds.shape[0]
preds, targets = np.array(preds), np.array(targets)
residuals = preds - targets
# print('points_num * np.log(np.var(residuals))', points_num * np.log(np.var(residuals)))
# print('np.exp(non_zero_term) * np.log(points_num)', np.exp(non_zero_term) * np.log(points_num))
criterion = points_num * np.log(np.var(residuals)) \
+ np.exp(non_zero_term) * np.log(points_num)
return criterion
def calculate_BIC_formal(preds, targets, non_zero_term):
'''
calculate BIC formal
'''
points_num = preds.shape[0]
preds, targets = np.array(preds), np.array(targets)
residuals = preds - targets
criterion = points_num * np.log(np.var(residuals)) \
+ non_zero_term * np.log(points_num)
return criterion
if __name__ == "__main__":
preds = [1, 2, 3]
targets = [1, 0, 1]
non_zero_term = 1
criterion = calculate_BIC(preds, targets, non_zero_term)
print(criterion)
| [
"numpy.log",
"numpy.array",
"numpy.exp",
"numpy.var"
] | [((276, 291), 'numpy.array', 'np.array', (['preds'], {}), '(preds)\n', (284, 291), True, 'import numpy as np\n'), ((293, 310), 'numpy.array', 'np.array', (['targets'], {}), '(targets)\n', (301, 310), True, 'import numpy as np\n'), ((827, 842), 'numpy.array', 'np.array', (['preds'], {}), '(preds)\n', (835, 842), True, 'import numpy as np\n'), ((844, 861), 'numpy.array', 'np.array', (['targets'], {}), '(targets)\n', (852, 861), True, 'import numpy as np\n'), ((610, 631), 'numpy.exp', 'np.exp', (['non_zero_term'], {}), '(non_zero_term)\n', (616, 631), True, 'import numpy as np\n'), ((634, 652), 'numpy.log', 'np.log', (['points_num'], {}), '(points_num)\n', (640, 652), True, 'import numpy as np\n'), ((981, 999), 'numpy.log', 'np.log', (['points_num'], {}), '(points_num)\n', (987, 999), True, 'import numpy as np\n'), ((575, 592), 'numpy.var', 'np.var', (['residuals'], {}), '(residuals)\n', (581, 592), True, 'import numpy as np\n'), ((930, 947), 'numpy.var', 'np.var', (['residuals'], {}), '(residuals)\n', (936, 947), True, 'import numpy as np\n')] |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""
Dataloader and preprocessing
"""
import os
import os.path
import random
import math
import numpy as np
from PIL import Image
import mindspore.dataset.vision.py_transforms as py_vision
import mindspore.dataset as ds
from mindspore.communication.management import get_rank, get_group_size
def TrainDataLoader(img_size, data_path, dataset, batch_size, distributed):
""" DataLoader """
train_transform = [
py_vision.ToPIL(),
py_vision.RandomHorizontalFlip(),
py_vision.Resize((img_size + 30, img_size + 30)),
py_vision.RandomCrop(img_size),
py_vision.ToTensor(),
py_vision.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
]
test_transform = [
py_vision.ToPIL(),
py_vision.Resize((img_size, img_size)),
py_vision.ToTensor(),
py_vision.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
]
rank_size = 1
if distributed:
rank_id = get_rank()
rank_size = get_group_size()
train_generator = GetDatasetGenerator(os.path.join(data_path, dataset), 'train')
train_data = ds.GeneratorDataset(train_generator, ["image_A", "image_B"], shuffle=True, num_parallel_workers=12,
num_shards=rank_size, shard_id=rank_id)
test_generator = GetDatasetGenerator(os.path.join(data_path, dataset), 'test')
test_data = ds.GeneratorDataset(test_generator, ["image_A", "image_B"], shuffle=False, num_parallel_workers=12,
num_shards=rank_size, shard_id=rank_id)
else:
train_generator = GetDatasetGenerator(os.path.join(data_path, dataset), 'train')
train_data = ds.GeneratorDataset(train_generator, ["image_A", "image_B"], shuffle=True, num_parallel_workers=12)
test_generator = GetDatasetGenerator(os.path.join(data_path, dataset), 'test')
test_data = ds.GeneratorDataset(test_generator, ["image_A", "image_B"], shuffle=False, num_parallel_workers=12)
train_data = train_data.map(operations=train_transform, input_columns=["image_A"])
train_data = train_data.map(operations=train_transform, input_columns=["image_B"])
train_data = train_data.batch(batch_size=batch_size).repeat(3)
train_num = train_data.get_dataset_size()
test_data = test_data.map(operations=test_transform, input_columns=["image_A"])
test_data = test_data.map(operations=test_transform, input_columns=["image_B"])
test_data = test_data.batch(batch_size=1).repeat()
return train_data, test_data, train_num
def TestDataLoader(img_size, data_path, dataset):
""" DataLoader """
test_transform = [
py_vision.ToPIL(),
py_vision.Resize((img_size, img_size)),
py_vision.ToTensor(),
py_vision.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
]
testA_generator = GetDatasetGenerator(os.path.join(data_path, dataset), 'test')
testA = ds.GeneratorDataset(testA_generator, ["image_A", "image_B"], shuffle=False, num_parallel_workers=12)
testA = testA.map(operations=test_transform, input_columns=["image_A"])
testA = testA.map(operations=test_transform, input_columns=["image_B"])
testA_loader = testA.batch(batch_size=1).repeat(1)
return testA_loader
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
Returns:
bool: True if the filename ends with a known image extension
"""
filename_lower = filename.lower()
return any(filename_lower.endswith(ext) for ext in extensions)
def make_dataset(in_dir, extensions):
images = []
for root, _, fnames in sorted(os.walk(in_dir)):
for fname in sorted(fnames):
if has_file_allowed_extension(fname, extensions):
path = os.path.join(root, fname)
item = (path, 0)
images.append(item)
return images
IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif']
def pil_loader(path):
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with open(path, 'rb') as f:
img = Image.open(f)
return img.convert('RGB')
def default_loader(path):
return pil_loader(path)
class GetDatasetGenerator:
"""Dataset"""
def __init__(self, root, phase, loader=default_loader, extensions=None, transform=None, target_transform=None):
if not extensions:
extensions = IMG_EXTENSIONS
self.root_A = os.path.join(root, phase + 'A')
self.root_B = os.path.join(root, phase + 'B')
samlpe_A = make_dataset(self.root_A, extensions)
samlpe_B = make_dataset(self.root_B, extensions)
if not samlpe_A:
raise (RuntimeError("Found 0 files in subfolders of: " + root + "\n"
"Supported extensions are: " + ",".join(extensions)))
self.phase = phase
self.root = root
self.loader = loader
self.extensions = extensions
self.samlpe_A = samlpe_A
self.samlpe_B = samlpe_B
self.A_size = len(self.samlpe_A)
self.B_size = len(self.samlpe_B)
self.transform = transform
self.target_transform = target_transform
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (sample, target) where target is class_index of the target class.
"""
index_B = index % self.B_size
if self.phase == 'train':
if index % max(self.A_size, self.B_size) == 0:
random.shuffle(self.samlpe_A)
index_B = random.randint(0, self.B_size - 1)
path_A, _ = self.samlpe_A[index % self.A_size]
path_B, _ = self.samlpe_B[index_B]
# sample = self.loader(path)
sample_A = np.array(Image.open(path_A).convert('RGB'))
sample_B = np.array(Image.open(path_B).convert('RGB'))
return sample_A, sample_B
def __len__(self):
return max(self.A_size, self.B_size)
def __repr__(self):
fmt_str = 'Dataset ' + self.__class__.__name__ + '\n'
fmt_str += ' Number of datapoints: {}\n'.format(self.__len__())
fmt_str += ' Root Location: {}\n'.format(self.root)
tmp = ' Transforms (if any): '
fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
tmp = ' Target Transforms (if any): '
fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
return fmt_str
class DistributedSampler:
"""Distributed sampler."""
def __init__(self,
dataset_size,
num_replicas=None,
rank=None,
shuffle=True):
if num_replicas is None:
print(
"***********Setting world_size to 1 since it is not passed in ******************"
)
num_replicas = 1
if rank is None:
print(
"***********Setting rank to 0 since it is not passed in ******************"
)
rank = 0
self.dataset_size = dataset_size
self.num_replicas = num_replicas
self.rank = rank
self.epoch = 0
self.num_samples = int(
math.ceil(dataset_size * 1.0 / self.num_replicas))
self.total_size = self.num_samples * self.num_replicas
self.shuffle = shuffle
def __iter__(self):
# deterministically shuffle based on epoch
if self.shuffle:
indices = np.random.RandomState(seed=self.epoch).permutation(
self.dataset_size)
# np.array type. number from 0 to len(dataset_size)-1, used as index of dataset
indices = indices.tolist()
self.epoch += 1
# change to list type
else:
indices = list(range(self.dataset_size))
# add extra samlpe_A to make it evenly divisible
indices += indices[:(self.total_size - len(indices))]
assert len(indices) == self.total_size
# subsample
indices = indices[self.rank:self.total_size:self.num_replicas]
assert len(indices) == self.num_samples
return iter(indices)
def __len__(self):
return self.num_samples
| [
"mindspore.dataset.vision.py_transforms.Normalize",
"mindspore.dataset.vision.py_transforms.Resize",
"os.path.join",
"random.randint",
"math.ceil",
"random.shuffle",
"os.walk",
"numpy.random.RandomState",
"mindspore.dataset.GeneratorDataset",
"PIL.Image.open",
"mindspore.communication.management... | [((3610, 3714), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['testA_generator', "['image_A', 'image_B']"], {'shuffle': '(False)', 'num_parallel_workers': '(12)'}), "(testA_generator, ['image_A', 'image_B'], shuffle=False,\n num_parallel_workers=12)\n", (3629, 3714), True, 'import mindspore.dataset as ds\n'), ((1092, 1109), 'mindspore.dataset.vision.py_transforms.ToPIL', 'py_vision.ToPIL', ([], {}), '()\n', (1107, 1109), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((1119, 1151), 'mindspore.dataset.vision.py_transforms.RandomHorizontalFlip', 'py_vision.RandomHorizontalFlip', ([], {}), '()\n', (1149, 1151), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((1161, 1209), 'mindspore.dataset.vision.py_transforms.Resize', 'py_vision.Resize', (['(img_size + 30, img_size + 30)'], {}), '((img_size + 30, img_size + 30))\n', (1177, 1209), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((1219, 1249), 'mindspore.dataset.vision.py_transforms.RandomCrop', 'py_vision.RandomCrop', (['img_size'], {}), '(img_size)\n', (1239, 1249), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((1259, 1279), 'mindspore.dataset.vision.py_transforms.ToTensor', 'py_vision.ToTensor', ([], {}), '()\n', (1277, 1279), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((1289, 1351), 'mindspore.dataset.vision.py_transforms.Normalize', 'py_vision.Normalize', ([], {'mean': '[0.5, 0.5, 0.5]', 'std': '[0.5, 0.5, 0.5]'}), '(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n', (1308, 1351), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((1390, 1407), 'mindspore.dataset.vision.py_transforms.ToPIL', 'py_vision.ToPIL', ([], {}), '()\n', (1405, 1407), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((1417, 1455), 'mindspore.dataset.vision.py_transforms.Resize', 'py_vision.Resize', (['(img_size, img_size)'], {}), '((img_size, img_size))\n', (1433, 1455), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((1465, 1485), 'mindspore.dataset.vision.py_transforms.ToTensor', 'py_vision.ToTensor', ([], {}), '()\n', (1483, 1485), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((1495, 1557), 'mindspore.dataset.vision.py_transforms.Normalize', 'py_vision.Normalize', ([], {'mean': '[0.5, 0.5, 0.5]', 'std': '[0.5, 0.5, 0.5]'}), '(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n', (1514, 1557), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((1621, 1631), 'mindspore.communication.management.get_rank', 'get_rank', ([], {}), '()\n', (1629, 1631), False, 'from mindspore.communication.management import get_rank, get_group_size\n'), ((1652, 1668), 'mindspore.communication.management.get_group_size', 'get_group_size', ([], {}), '()\n', (1666, 1668), False, 'from mindspore.communication.management import get_rank, get_group_size\n'), ((1779, 1922), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['train_generator', "['image_A', 'image_B']"], {'shuffle': '(True)', 'num_parallel_workers': '(12)', 'num_shards': 'rank_size', 'shard_id': 'rank_id'}), "(train_generator, ['image_A', 'image_B'], shuffle=True,\n num_parallel_workers=12, num_shards=rank_size, shard_id=rank_id)\n", (1798, 1922), True, 'import mindspore.dataset as ds\n'), ((2068, 2211), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['test_generator', "['image_A', 'image_B']"], {'shuffle': '(False)', 'num_parallel_workers': '(12)', 'num_shards': 'rank_size', 'shard_id': 'rank_id'}), "(test_generator, ['image_A', 'image_B'], shuffle=False,\n num_parallel_workers=12, num_shards=rank_size, shard_id=rank_id)\n", (2087, 2211), True, 'import mindspore.dataset as ds\n'), ((2369, 2472), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['train_generator', "['image_A', 'image_B']"], {'shuffle': '(True)', 'num_parallel_workers': '(12)'}), "(train_generator, ['image_A', 'image_B'], shuffle=True,\n num_parallel_workers=12)\n", (2388, 2472), True, 'import mindspore.dataset as ds\n'), ((2576, 2679), 'mindspore.dataset.GeneratorDataset', 'ds.GeneratorDataset', (['test_generator', "['image_A', 'image_B']"], {'shuffle': '(False)', 'num_parallel_workers': '(12)'}), "(test_generator, ['image_A', 'image_B'], shuffle=False,\n num_parallel_workers=12)\n", (2595, 2679), True, 'import mindspore.dataset as ds\n'), ((3339, 3356), 'mindspore.dataset.vision.py_transforms.ToPIL', 'py_vision.ToPIL', ([], {}), '()\n', (3354, 3356), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((3366, 3404), 'mindspore.dataset.vision.py_transforms.Resize', 'py_vision.Resize', (['(img_size, img_size)'], {}), '((img_size, img_size))\n', (3382, 3404), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((3414, 3434), 'mindspore.dataset.vision.py_transforms.ToTensor', 'py_vision.ToTensor', ([], {}), '()\n', (3432, 3434), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((3444, 3506), 'mindspore.dataset.vision.py_transforms.Normalize', 'py_vision.Normalize', ([], {'mean': '[0.5, 0.5, 0.5]', 'std': '[0.5, 0.5, 0.5]'}), '(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n', (3463, 3506), True, 'import mindspore.dataset.vision.py_transforms as py_vision\n'), ((3556, 3588), 'os.path.join', 'os.path.join', (['data_path', 'dataset'], {}), '(data_path, dataset)\n', (3568, 3588), False, 'import os\n'), ((4387, 4402), 'os.walk', 'os.walk', (['in_dir'], {}), '(in_dir)\n', (4394, 4402), False, 'import os\n'), ((4890, 4903), 'PIL.Image.open', 'Image.open', (['f'], {}), '(f)\n', (4900, 4903), False, 'from PIL import Image\n'), ((5247, 5278), 'os.path.join', 'os.path.join', (['root', "(phase + 'A')"], {}), "(root, phase + 'A')\n", (5259, 5278), False, 'import os\n'), ((5301, 5332), 'os.path.join', 'os.path.join', (['root', "(phase + 'B')"], {}), "(root, phase + 'B')\n", (5313, 5332), False, 'import os\n'), ((1715, 1747), 'os.path.join', 'os.path.join', (['data_path', 'dataset'], {}), '(data_path, dataset)\n', (1727, 1747), False, 'import os\n'), ((2006, 2038), 'os.path.join', 'os.path.join', (['data_path', 'dataset'], {}), '(data_path, dataset)\n', (2018, 2038), False, 'import os\n'), ((2305, 2337), 'os.path.join', 'os.path.join', (['data_path', 'dataset'], {}), '(data_path, dataset)\n', (2317, 2337), False, 'import os\n'), ((2514, 2546), 'os.path.join', 'os.path.join', (['data_path', 'dataset'], {}), '(data_path, dataset)\n', (2526, 2546), False, 'import os\n'), ((8104, 8153), 'math.ceil', 'math.ceil', (['(dataset_size * 1.0 / self.num_replicas)'], {}), '(dataset_size * 1.0 / self.num_replicas)\n', (8113, 8153), False, 'import math\n'), ((4527, 4552), 'os.path.join', 'os.path.join', (['root', 'fname'], {}), '(root, fname)\n', (4539, 4552), False, 'import os\n'), ((6344, 6373), 'random.shuffle', 'random.shuffle', (['self.samlpe_A'], {}), '(self.samlpe_A)\n', (6358, 6373), False, 'import random\n'), ((6400, 6434), 'random.randint', 'random.randint', (['(0)', '(self.B_size - 1)'], {}), '(0, self.B_size - 1)\n', (6414, 6434), False, 'import random\n'), ((6598, 6616), 'PIL.Image.open', 'Image.open', (['path_A'], {}), '(path_A)\n', (6608, 6616), False, 'from PIL import Image\n'), ((6661, 6679), 'PIL.Image.open', 'Image.open', (['path_B'], {}), '(path_B)\n', (6671, 6679), False, 'from PIL import Image\n'), ((8372, 8410), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': 'self.epoch'}), '(seed=self.epoch)\n', (8393, 8410), True, 'import numpy as np\n')] |
import datetime
import json
import os
import random
import time
import cv2
import numpy as np
import torch
from django.conf import settings
from django.http import HttpResponse, JsonResponse, StreamingHttpResponse
from django.shortcuts import render
from scipy import ndimage
from .models import GardenPlan, PlantSpecification, Settings, WateringSchedule
from .modules.solov2 import SOLOV2
from .utils import Table, cfg, config
from .utils.imgutils import imresize
IMG_FILE = os.path.join(settings.BASE_DIR, "img/video.jpg")
# Load model
model = SOLOV2(
cfg,
pretrained=os.path.join(settings.BASE_DIR, "models/solov2_448_r18_epoch_36.pth"),
mode="test",
)
# model = model.cuda()
def show_result_ins(img, result, score_thr=0.3, sort_by_density=False):
h, w, _ = img.shape
cur_result = result[0]
seg_label = cur_result[0]
seg_label = seg_label.cpu().numpy().astype(np.uint8)
cate_label = cur_result[1]
cate_label = cate_label.cpu().numpy()
score = cur_result[2].cpu().numpy()
vis_inds = score > score_thr
seg_label = seg_label[vis_inds]
num_mask = seg_label.shape[0]
cate_label = cate_label[vis_inds]
cate_score = score[vis_inds]
if sort_by_density:
mask_density = []
for idx in range(num_mask):
cur_mask = seg_label[idx, :, :]
cur_mask = imresize(cur_mask, (w, h))
cur_mask = (cur_mask > 0.5).astype(np.int32)
mask_density.append(cur_mask.sum())
orders = np.argsort(mask_density)
seg_label = seg_label[orders]
cate_label = cate_label[orders]
cate_score = cate_score[orders]
np.random.seed(42)
color_masks = [
np.random.randint(0, 256, (1, 3), dtype=np.uint8) for _ in range(num_mask)
]
# img_show = None
for idx in range(num_mask):
idx = -(idx + 1)
cur_mask = seg_label[idx, :, :]
cur_mask = imresize(cur_mask, (w, h))
cur_mask = (cur_mask > 0.5).astype(np.uint8)
if cur_mask.sum() == 0:
continue
color_mask = color_masks[idx]
cur_mask_bool = cur_mask.astype(np.bool)
img[cur_mask_bool] = img[cur_mask_bool] * 0.5 + color_mask * 0.5
# 当前实例的类别
cur_cate = cate_label[idx]
realclass = config.COCO_LABEL[cur_cate]
cur_score = cate_score[idx]
name_idx = config.COCO_LABEL_MAP[realclass]
label_text = config.COCO_CLASSES[name_idx - 1]
label_text += "|{:.02f}".format(cur_score)
center_y, center_x = ndimage.measurements.center_of_mass(cur_mask)
vis_pos = (max(int(center_x) - 10, 0), int(center_y))
cv2.putText(
img, label_text, vis_pos, cv2.FONT_HERSHEY_COMPLEX, 1.0, (255, 255, 255)
) # green
print(f"index: {idx}, name: {label_text}")
return img
### Make prediction on tested image
# Preprocess the input image
img_cam = cv2.imread(IMG_FILE)
img_cam = cv2.copyMakeBorder(
img_cam, 280, 280, 0, 0, cv2.BORDER_CONSTANT, value=[0, 0, 0]
) # zero-padding
img = cv2.cvtColor(img_cam, cv2.COLOR_BGR2RGB)
img = img.transpose(2, 0, 1)
img = img.astype(np.float32)
# Normalization of image
# 1. step
img = img / 255.0
# 2. step
img[0, :, :] = (img[0, :, :] - config.MEAN[0]) / config.STD[0]
img[1, :, :] = (img[1, :, :] - config.MEAN[1]) / config.STD[1]
img[2, :, :] = (img[2, :, :] - config.MEAN[2]) / config.STD[2]
# img = torch.from_numpy(img).cuda().unsqueeze(0)
img = torch.from_numpy(img).unsqueeze(0)
# Predict
with torch.no_grad():
seg_result = model.simple_test(
img=img,
img_meta=[
{
"ori_shape": img_cam.shape,
"img_shape": img_cam.shape,
"scale_factor": 1,
}
],
)
if not None in seg_result:
img_cam = show_result_ins(img_cam, seg_result)
img_cam = img_cam[280:-280, :, :]
### --------------------------
def index(request):
return render(request, "index.html")
def sensors(request):
if "read" in request.GET and request.GET["read"] == "1":
return JsonResponse(
{
"Temp 0": [round(random.random() * 200 - 50), "°C", "[-50, 150]"],
"Temp 1": [round(random.random() * 200 - 50), "°C", "[-50, 150]"],
"Heat index": [round(random.random() * 200 - 50), "°C", "[-50, 150]"],
"Humidity 0": [round(random.random() * 100), "%", "[0, 100]"],
"Pressure 0": [
round(random.random() * 750 + 400),
"hPa",
"[400, 1150]",
],
"Soil moisture 0": [round(random.random() * 100), "%", "[0, 100]"],
"Soil moisture 1": [round(random.random() * 100), "%", "[0, 100]"],
}
)
else:
return render(
request,
"sensors.html",
{
"refreshInterval": Settings.objects.values_list(
"refreshInterval", flat=True
).last()
},
)
def control(request):
if request.method == "POST":
print(request.body)
return render(request, "control.html")
def settings(request):
if request.method == "POST":
data = json.loads(request.body)
print(data)
# delete last settings
if Settings.objects.count() > 0:
Settings.objects.all().delete()
# Create row with actual settings
Settings.objects.create(
selectedMode=data["mode"], refreshInterval=data["refreshInterval"]
)
# Delete selected items
for row_id in data[f"del_{WateringSchedule.__name__}"]:
WateringSchedule.objects.filter(pk=row_id).delete()
# Add new items
for row in data[f"new_{WateringSchedule.__name__}"]:
WateringSchedule.objects.create(
time=datetime.datetime.strptime(row[0], "%H:%M").time()
)
return HttpResponse(status=204)
else:
return render(
request,
"settings.html",
context={
"modes": ["Automatic", "Manual"],
"selectedMode": Settings.objects.values_list(
"selectedMode", flat=True
).last(),
"refreshInterval": Settings.objects.values_list(
"refreshInterval", flat=True
).last(),
"wateringSchedule": Table(WateringSchedule),
},
)
def plants(request):
if request.method == "POST":
data = json.loads(request.body)
print(data)
# Delete selected items
for row_id in data[f"del_{GardenPlan.__name__}"]:
GardenPlan.objects.filter(pk=row_id).delete()
for row_id in data[f"del_{PlantSpecification.__name__}"]:
PlantSpecification.objects.filter(pk=row_id).delete()
# Add new items
for row in data[f"new_{GardenPlan.__name__}"]:
GardenPlan.objects.create(
p_type=row[0],
p_variety=row[1],
p_planting_date=datetime.datetime.strptime(row[2], "%Y-%m-%d").date(),
p_location=row[3],
)
for row in data[f"new_{PlantSpecification.__name__}"]:
PlantSpecification.objects.create(
p_type=row[0],
p_variety=row[1],
p_num_of_seeds_in_1g=row[2],
p_planting_date=row[3],
p_planting_temp=row[4],
p_planting_depth=row[5],
p_germination_time=row[6],
p_harvest_time=row[7],
p_harvest_date=row[8],
p_length_of_root=row[9],
p_diameter=row[10],
p_watering_time=datetime.datetime.strptime(row[11], "%H:%M").time(),
p_class=row[12],
)
return HttpResponse(status=204)
else:
return render(
request,
"plants.html",
context={
"gardenPlan": Table(GardenPlan),
"plantSpecification": Table(PlantSpecification),
},
)
def img_generator():
while True:
ret, jpeg = cv2.imencode(".jpg", img_cam)
time.sleep(0.1) # aby nepretazoval siet
yield (
b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n" + jpeg.tobytes() + b"\r\n\r\n"
)
def video_feed(request):
return StreamingHttpResponse(
img_generator(), content_type="multipart/x-mixed-replace;boundary=frame"
)
| [
"numpy.random.seed",
"cv2.putText",
"json.loads",
"django.http.HttpResponse",
"cv2.cvtColor",
"cv2.copyMakeBorder",
"time.sleep",
"numpy.argsort",
"cv2.imread",
"random.random",
"numpy.random.randint",
"datetime.datetime.strptime",
"scipy.ndimage.measurements.center_of_mass",
"cv2.imencode... | [((479, 527), 'os.path.join', 'os.path.join', (['settings.BASE_DIR', '"""img/video.jpg"""'], {}), "(settings.BASE_DIR, 'img/video.jpg')\n", (491, 527), False, 'import os\n'), ((2910, 2930), 'cv2.imread', 'cv2.imread', (['IMG_FILE'], {}), '(IMG_FILE)\n', (2920, 2930), False, 'import cv2\n'), ((2941, 3027), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['img_cam', '(280)', '(280)', '(0)', '(0)', 'cv2.BORDER_CONSTANT'], {'value': '[0, 0, 0]'}), '(img_cam, 280, 280, 0, 0, cv2.BORDER_CONSTANT, value=[0, \n 0, 0])\n', (2959, 3027), False, 'import cv2\n'), ((3051, 3091), 'cv2.cvtColor', 'cv2.cvtColor', (['img_cam', 'cv2.COLOR_BGR2RGB'], {}), '(img_cam, cv2.COLOR_BGR2RGB)\n', (3063, 3091), False, 'import cv2\n'), ((1647, 1665), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (1661, 1665), True, 'import numpy as np\n'), ((3510, 3525), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3523, 3525), False, 'import torch\n'), ((3943, 3972), 'django.shortcuts.render', 'render', (['request', '"""index.html"""'], {}), "(request, 'index.html')\n", (3949, 3972), False, 'from django.shortcuts import render\n'), ((5150, 5181), 'django.shortcuts.render', 'render', (['request', '"""control.html"""'], {}), "(request, 'control.html')\n", (5156, 5181), False, 'from django.shortcuts import render\n'), ((582, 651), 'os.path.join', 'os.path.join', (['settings.BASE_DIR', '"""models/solov2_448_r18_epoch_36.pth"""'], {}), "(settings.BASE_DIR, 'models/solov2_448_r18_epoch_36.pth')\n", (594, 651), False, 'import os\n'), ((1499, 1523), 'numpy.argsort', 'np.argsort', (['mask_density'], {}), '(mask_density)\n', (1509, 1523), True, 'import numpy as np\n'), ((1694, 1743), 'numpy.random.randint', 'np.random.randint', (['(0)', '(256)', '(1, 3)'], {'dtype': 'np.uint8'}), '(0, 256, (1, 3), dtype=np.uint8)\n', (1711, 1743), True, 'import numpy as np\n'), ((2532, 2577), 'scipy.ndimage.measurements.center_of_mass', 'ndimage.measurements.center_of_mass', (['cur_mask'], {}), '(cur_mask)\n', (2567, 2577), False, 'from scipy import ndimage\n'), ((2648, 2738), 'cv2.putText', 'cv2.putText', (['img', 'label_text', 'vis_pos', 'cv2.FONT_HERSHEY_COMPLEX', '(1.0)', '(255, 255, 255)'], {}), '(img, label_text, vis_pos, cv2.FONT_HERSHEY_COMPLEX, 1.0, (255, \n 255, 255))\n', (2659, 2738), False, 'import cv2\n'), ((3459, 3480), 'torch.from_numpy', 'torch.from_numpy', (['img'], {}), '(img)\n', (3475, 3480), False, 'import torch\n'), ((5255, 5279), 'json.loads', 'json.loads', (['request.body'], {}), '(request.body)\n', (5265, 5279), False, 'import json\n'), ((5976, 6000), 'django.http.HttpResponse', 'HttpResponse', ([], {'status': '(204)'}), '(status=204)\n', (5988, 6000), False, 'from django.http import HttpResponse, JsonResponse, StreamingHttpResponse\n'), ((6587, 6611), 'json.loads', 'json.loads', (['request.body'], {}), '(request.body)\n', (6597, 6611), False, 'import json\n'), ((7920, 7944), 'django.http.HttpResponse', 'HttpResponse', ([], {'status': '(204)'}), '(status=204)\n', (7932, 7944), False, 'from django.http import HttpResponse, JsonResponse, StreamingHttpResponse\n'), ((8246, 8275), 'cv2.imencode', 'cv2.imencode', (['""".jpg"""', 'img_cam'], {}), "('.jpg', img_cam)\n", (8258, 8275), False, 'import cv2\n'), ((8284, 8299), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (8294, 8299), False, 'import time\n'), ((4391, 4406), 'random.random', 'random.random', ([], {}), '()\n', (4404, 4406), False, 'import random\n'), ((4644, 4659), 'random.random', 'random.random', ([], {}), '()\n', (4657, 4659), False, 'import random\n'), ((4728, 4743), 'random.random', 'random.random', ([], {}), '()\n', (4741, 4743), False, 'import random\n'), ((5895, 5938), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['row[0]', '"""%H:%M"""'], {}), "(row[0], '%H:%M')\n", (5921, 5938), False, 'import datetime\n'), ((7129, 7175), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['row[2]', '"""%Y-%m-%d"""'], {}), "(row[2], '%Y-%m-%d')\n", (7155, 7175), False, 'import datetime\n'), ((7804, 7848), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['row[11]', '"""%H:%M"""'], {}), "(row[11], '%H:%M')\n", (7830, 7848), False, 'import datetime\n'), ((4134, 4149), 'random.random', 'random.random', ([], {}), '()\n', (4147, 4149), False, 'import random\n'), ((4217, 4232), 'random.random', 'random.random', ([], {}), '()\n', (4230, 4232), False, 'import random\n'), ((4304, 4319), 'random.random', 'random.random', ([], {}), '()\n', (4317, 4319), False, 'import random\n'), ((4491, 4506), 'random.random', 'random.random', ([], {}), '()\n', (4504, 4506), False, 'import random\n')] |
import numpy as np
import tensorflow as tf
import tt_v2 as tt
from hyperparameter_v2 import *
r_1 = FLAGS.tt_ranks_1
r_2 = FLAGS.tt_ranks_2
input_node=FLAGS.input_node
output_node=FLAGS.output_node
hidden1_node=FLAGS.hidden_node
#TTO_layer1
inp_modes1 = [4,7,7,4]
out_modes1 = [4,4,4,4]
mat_rank1 = [1,r_1,r_1,r_1,1]
#TTO_layer2
inp_modes2 = [4,4,4,4]
out_modes2 = [1,10,1,1]
mat_rank2 = [1,r_2,r_2,r_2,1]
def inference(inputs):
inputs = tt.tto(inputs,
np.array(inp_modes1,dtype=np.int32),
np.array(out_modes1,dtype=np.int32),
np.array(mat_rank1,dtype=np.int32),
scope='tt_scope_1')
inputs = tf.nn.relu(inputs)
inputs = tt.tto(inputs,
np.array(inp_modes2, dtype=np.int32),
np.array(out_modes2, dtype=np.int32),
np.array(mat_rank2, dtype=np.int32),
scope='tt_scope_2')
return inputs
| [
"tensorflow.nn.relu",
"numpy.array"
] | [((692, 710), 'tensorflow.nn.relu', 'tf.nn.relu', (['inputs'], {}), '(inputs)\n', (702, 710), True, 'import tensorflow as tf\n'), ((489, 525), 'numpy.array', 'np.array', (['inp_modes1'], {'dtype': 'np.int32'}), '(inp_modes1, dtype=np.int32)\n', (497, 525), True, 'import numpy as np\n'), ((546, 582), 'numpy.array', 'np.array', (['out_modes1'], {'dtype': 'np.int32'}), '(out_modes1, dtype=np.int32)\n', (554, 582), True, 'import numpy as np\n'), ((603, 638), 'numpy.array', 'np.array', (['mat_rank1'], {'dtype': 'np.int32'}), '(mat_rank1, dtype=np.int32)\n', (611, 638), True, 'import numpy as np\n'), ((759, 795), 'numpy.array', 'np.array', (['inp_modes2'], {'dtype': 'np.int32'}), '(inp_modes2, dtype=np.int32)\n', (767, 795), True, 'import numpy as np\n'), ((817, 853), 'numpy.array', 'np.array', (['out_modes2'], {'dtype': 'np.int32'}), '(out_modes2, dtype=np.int32)\n', (825, 853), True, 'import numpy as np\n'), ((875, 910), 'numpy.array', 'np.array', (['mat_rank2'], {'dtype': 'np.int32'}), '(mat_rank2, dtype=np.int32)\n', (883, 910), True, 'import numpy as np\n')] |
import numpy as np
import json
def _network_to_json(network):
weights = list([list(l) for l in l_weights]
for l_weights in network.weights)
biases = list(list(b) for b in network.biases)
return json.dumps({"weights": weights, "biases": biases})
def _json_to_network(json_input):
python_data = json.loads(json_input)
biases = [np.array(b) for b in python_data['biases']]
weights = [np.array(w) for w in python_data['weights']]
return biases, weights
def json_export(network, path):
output_string = _network_to_json(network)
with open(path, 'w') as file:
file.write(output_string)
def json_import(network, path):
with open(path, 'r') as file:
json_input = file.read()
biases, weights = _json_to_network(json_input)
network.biases = biases
network.weights = weights
| [
"numpy.array",
"json.loads",
"json.dumps"
] | [((228, 278), 'json.dumps', 'json.dumps', (["{'weights': weights, 'biases': biases}"], {}), "({'weights': weights, 'biases': biases})\n", (238, 278), False, 'import json\n'), ((333, 355), 'json.loads', 'json.loads', (['json_input'], {}), '(json_input)\n', (343, 355), False, 'import json\n'), ((370, 381), 'numpy.array', 'np.array', (['b'], {}), '(b)\n', (378, 381), True, 'import numpy as np\n'), ((429, 440), 'numpy.array', 'np.array', (['w'], {}), '(w)\n', (437, 440), True, 'import numpy as np\n')] |
"""Unittests for the deepblink.metrics module."""
# pylint: disable=missing-function-docstring
from hypothesis import given
from hypothesis import strategies as st
from hypothesis.extra.numpy import arrays
import numpy as np
import pytest
import scipy.spatial
from deepblink.metrics import _f1_at_cutoff
from deepblink.metrics import euclidean_dist
from deepblink.metrics import f1_integral
from deepblink.metrics import f1_score
from deepblink.metrics import linear_sum_assignment
from deepblink.metrics import offset_euclidean
from deepblink.metrics import precision_score
from deepblink.metrics import recall_score
@pytest.mark.parametrize(
"x1, y1, x2, y2, expected",
[(2, 2, 2, 2, 0), (2, 2, 2, 3, 1), (3, 3, 4, 4, np.sqrt(2))],
)
def test_euclidean_dist(x1, y1, x2, y2, expected):
assert euclidean_dist(x1, y1, x2, y2) == expected
@pytest.mark.parametrize(
"nfalsepositive, expected_precision", [(2, 0.98), (3, 0.97), (0, 1), (7, 0.93)]
)
def test_precision_score(nfalsepositive, expected_precision):
true = np.ones((10, 10, 3))
pred = np.ones((10, 10, 3))
index1 = np.random.choice(true.shape[0], nfalsepositive, replace=False)
index2 = np.random.choice(true.shape[0], nfalsepositive, replace=False)
true[index1, index2, 0] = 0
assert precision_score(pred, true) == expected_precision
@pytest.mark.parametrize(
"nfalsenegative, expected_recall", [(2, 0.98), (3, 0.97), (0, 1), (7, 0.93)]
)
def test_recall_score(nfalsenegative, expected_recall):
true = np.ones((10, 10, 3))
pred = np.ones((10, 10, 3))
index1 = np.random.choice(true.shape[0], nfalsenegative, replace=False)
index2 = np.random.choice(true.shape[0], nfalsenegative, replace=False)
pred[index1, index2, 0] = 0
assert recall_score(pred, true) == expected_recall
@pytest.mark.parametrize(
"nfalsenegative, expected_recall", [(2, 0.98), (3, 0.97), (0, 1), (7, 0.93)]
)
def test_f1_score(nfalsenegative, expected_recall):
true = np.ones((10, 10, 3))
pred = np.ones((10, 10, 3))
index1 = np.random.choice(true.shape[0], nfalsenegative, replace=False)
index2 = np.random.choice(true.shape[0], nfalsenegative, replace=False)
pred[index1, index2, 0] = 0
output = f1_score(pred, true)
expected = (2 * expected_recall * 1) / (expected_recall + 1)
assert output == pytest.approx(expected)
@given(n=st.integers(min_value=0, max_value=20))
def test_linear_sum_assignment_diagonal(n):
# Basic diagonal matrix with lowest scores along diagonal
matrix = 1 - np.diag(np.ones(n))
output = linear_sum_assignment(matrix, cutoff=0)
expected = (list(range(n)), list(range(n)))
assert output == expected
def test_linear_sum_assignment_non_diagonal():
# Offset diagonal matrix
matrix = 1 - np.diag(np.ones(3))
matrix[:, [0, 1]] = matrix[:, [1, 0]]
output = linear_sum_assignment(matrix, cutoff=0)
expected = (list(range(3)), [1, 0, 2])
assert output == expected
def test_f1_at_cutoff():
true = np.zeros((10, 2))
pred = true + 1
# Without offset
matrix = scipy.spatial.distance.cdist(pred, true, metric="euclidean")
for cutoff, expected in zip([0, 1, 2], [0, 0, 1]):
output = _f1_at_cutoff(matrix, pred, true, cutoff=cutoff, return_raw=False)
assert output == pytest.approx(expected)
# # With empty offset
output = _f1_at_cutoff(matrix, pred, true, cutoff=0, return_raw=True)
assert len(output) == 3
assert output[1] == []
# # With populated offset
output = _f1_at_cutoff(matrix, pred, true, cutoff=2, return_raw=True)
assert len(output) == 3
assert sorted(output[1]) == list(range(10))
assert sorted(output[2]) == list(range(10))
@given(arrays(np.uint8, (10, 2)))
def test_f1_integral_v0(true):
# Equal inputs
output = f1_integral(true, true, mdist=5, n_cutoffs=20, return_raw=False)
assert output == pytest.approx(1)
def test_f1_integral_v1():
# Unequal inputs
true = np.ones((10, 2))
pred = np.zeros((10, 2))
output = f1_integral(pred, true, mdist=2, n_cutoffs=11, return_raw=False)
assert output == pytest.approx(0.25)
# Raw output
output = f1_integral(true, true, mdist=5, n_cutoffs=20, return_raw=True)
assert len(output) == 3
assert len(output[1]) == 20 # 20 cutoffs
assert len(output[1][0]) == 10 # 10 coord inputs -> offsets
assert (output[2] == np.linspace(start=0, stop=5, num=20)).all()
def test_offset_euclidean():
offset = [[0, 0], [1, 1], [-1, 1], [1, 0]]
expected = [0, np.sqrt(2), np.sqrt(2), 1]
assert offset_euclidean(offset) == pytest.approx(expected)
| [
"hypothesis.extra.numpy.arrays",
"deepblink.metrics.euclidean_dist",
"deepblink.metrics.recall_score",
"deepblink.metrics.f1_score",
"deepblink.metrics.offset_euclidean",
"numpy.zeros",
"numpy.ones",
"deepblink.metrics._f1_at_cutoff",
"deepblink.metrics.precision_score",
"deepblink.metrics.linear_... | [((856, 965), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""nfalsepositive, expected_precision"""', '[(2, 0.98), (3, 0.97), (0, 1), (7, 0.93)]'], {}), "('nfalsepositive, expected_precision', [(2, 0.98), (\n 3, 0.97), (0, 1), (7, 0.93)])\n", (879, 965), False, 'import pytest\n'), ((1343, 1449), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""nfalsenegative, expected_recall"""', '[(2, 0.98), (3, 0.97), (0, 1), (7, 0.93)]'], {}), "('nfalsenegative, expected_recall', [(2, 0.98), (3, \n 0.97), (0, 1), (7, 0.93)])\n", (1366, 1449), False, 'import pytest\n'), ((1815, 1921), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""nfalsenegative, expected_recall"""', '[(2, 0.98), (3, 0.97), (0, 1), (7, 0.93)]'], {}), "('nfalsenegative, expected_recall', [(2, 0.98), (3, \n 0.97), (0, 1), (7, 0.93)])\n", (1838, 1921), False, 'import pytest\n'), ((1040, 1060), 'numpy.ones', 'np.ones', (['(10, 10, 3)'], {}), '((10, 10, 3))\n', (1047, 1060), True, 'import numpy as np\n'), ((1072, 1092), 'numpy.ones', 'np.ones', (['(10, 10, 3)'], {}), '((10, 10, 3))\n', (1079, 1092), True, 'import numpy as np\n'), ((1107, 1169), 'numpy.random.choice', 'np.random.choice', (['true.shape[0]', 'nfalsepositive'], {'replace': '(False)'}), '(true.shape[0], nfalsepositive, replace=False)\n', (1123, 1169), True, 'import numpy as np\n'), ((1183, 1245), 'numpy.random.choice', 'np.random.choice', (['true.shape[0]', 'nfalsepositive'], {'replace': '(False)'}), '(true.shape[0], nfalsepositive, replace=False)\n', (1199, 1245), True, 'import numpy as np\n'), ((1518, 1538), 'numpy.ones', 'np.ones', (['(10, 10, 3)'], {}), '((10, 10, 3))\n', (1525, 1538), True, 'import numpy as np\n'), ((1550, 1570), 'numpy.ones', 'np.ones', (['(10, 10, 3)'], {}), '((10, 10, 3))\n', (1557, 1570), True, 'import numpy as np\n'), ((1585, 1647), 'numpy.random.choice', 'np.random.choice', (['true.shape[0]', 'nfalsenegative'], {'replace': '(False)'}), '(true.shape[0], nfalsenegative, replace=False)\n', (1601, 1647), True, 'import numpy as np\n'), ((1661, 1723), 'numpy.random.choice', 'np.random.choice', (['true.shape[0]', 'nfalsenegative'], {'replace': '(False)'}), '(true.shape[0], nfalsenegative, replace=False)\n', (1677, 1723), True, 'import numpy as np\n'), ((1986, 2006), 'numpy.ones', 'np.ones', (['(10, 10, 3)'], {}), '((10, 10, 3))\n', (1993, 2006), True, 'import numpy as np\n'), ((2018, 2038), 'numpy.ones', 'np.ones', (['(10, 10, 3)'], {}), '((10, 10, 3))\n', (2025, 2038), True, 'import numpy as np\n'), ((2053, 2115), 'numpy.random.choice', 'np.random.choice', (['true.shape[0]', 'nfalsenegative'], {'replace': '(False)'}), '(true.shape[0], nfalsenegative, replace=False)\n', (2069, 2115), True, 'import numpy as np\n'), ((2129, 2191), 'numpy.random.choice', 'np.random.choice', (['true.shape[0]', 'nfalsenegative'], {'replace': '(False)'}), '(true.shape[0], nfalsenegative, replace=False)\n', (2145, 2191), True, 'import numpy as np\n'), ((2237, 2257), 'deepblink.metrics.f1_score', 'f1_score', (['pred', 'true'], {}), '(pred, true)\n', (2245, 2257), False, 'from deepblink.metrics import f1_score\n'), ((2575, 2614), 'deepblink.metrics.linear_sum_assignment', 'linear_sum_assignment', (['matrix'], {'cutoff': '(0)'}), '(matrix, cutoff=0)\n', (2596, 2614), False, 'from deepblink.metrics import linear_sum_assignment\n'), ((2863, 2902), 'deepblink.metrics.linear_sum_assignment', 'linear_sum_assignment', (['matrix'], {'cutoff': '(0)'}), '(matrix, cutoff=0)\n', (2884, 2902), False, 'from deepblink.metrics import linear_sum_assignment\n'), ((3014, 3031), 'numpy.zeros', 'np.zeros', (['(10, 2)'], {}), '((10, 2))\n', (3022, 3031), True, 'import numpy as np\n'), ((3377, 3437), 'deepblink.metrics._f1_at_cutoff', '_f1_at_cutoff', (['matrix', 'pred', 'true'], {'cutoff': '(0)', 'return_raw': '(True)'}), '(matrix, pred, true, cutoff=0, return_raw=True)\n', (3390, 3437), False, 'from deepblink.metrics import _f1_at_cutoff\n'), ((3537, 3597), 'deepblink.metrics._f1_at_cutoff', '_f1_at_cutoff', (['matrix', 'pred', 'true'], {'cutoff': '(2)', 'return_raw': '(True)'}), '(matrix, pred, true, cutoff=2, return_raw=True)\n', (3550, 3597), False, 'from deepblink.metrics import _f1_at_cutoff\n'), ((3821, 3885), 'deepblink.metrics.f1_integral', 'f1_integral', (['true', 'true'], {'mdist': '(5)', 'n_cutoffs': '(20)', 'return_raw': '(False)'}), '(true, true, mdist=5, n_cutoffs=20, return_raw=False)\n', (3832, 3885), False, 'from deepblink.metrics import f1_integral\n'), ((3731, 3756), 'hypothesis.extra.numpy.arrays', 'arrays', (['np.uint8', '(10, 2)'], {}), '(np.uint8, (10, 2))\n', (3737, 3756), False, 'from hypothesis.extra.numpy import arrays\n'), ((3985, 4001), 'numpy.ones', 'np.ones', (['(10, 2)'], {}), '((10, 2))\n', (3992, 4001), True, 'import numpy as np\n'), ((4013, 4030), 'numpy.zeros', 'np.zeros', (['(10, 2)'], {}), '((10, 2))\n', (4021, 4030), True, 'import numpy as np\n'), ((4044, 4108), 'deepblink.metrics.f1_integral', 'f1_integral', (['pred', 'true'], {'mdist': '(2)', 'n_cutoffs': '(11)', 'return_raw': '(False)'}), '(pred, true, mdist=2, n_cutoffs=11, return_raw=False)\n', (4055, 4108), False, 'from deepblink.metrics import f1_integral\n'), ((4181, 4244), 'deepblink.metrics.f1_integral', 'f1_integral', (['true', 'true'], {'mdist': '(5)', 'n_cutoffs': '(20)', 'return_raw': '(True)'}), '(true, true, mdist=5, n_cutoffs=20, return_raw=True)\n', (4192, 4244), False, 'from deepblink.metrics import f1_integral\n'), ((810, 840), 'deepblink.metrics.euclidean_dist', 'euclidean_dist', (['x1', 'y1', 'x2', 'y2'], {}), '(x1, y1, x2, y2)\n', (824, 840), False, 'from deepblink.metrics import euclidean_dist\n'), ((1290, 1317), 'deepblink.metrics.precision_score', 'precision_score', (['pred', 'true'], {}), '(pred, true)\n', (1305, 1317), False, 'from deepblink.metrics import precision_score\n'), ((1768, 1792), 'deepblink.metrics.recall_score', 'recall_score', (['pred', 'true'], {}), '(pred, true)\n', (1780, 1792), False, 'from deepblink.metrics import recall_score\n'), ((2344, 2367), 'pytest.approx', 'pytest.approx', (['expected'], {}), '(expected)\n', (2357, 2367), False, 'import pytest\n'), ((2379, 2417), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(0)', 'max_value': '(20)'}), '(min_value=0, max_value=20)\n', (2390, 2417), True, 'from hypothesis import strategies as st\n'), ((3221, 3287), 'deepblink.metrics._f1_at_cutoff', '_f1_at_cutoff', (['matrix', 'pred', 'true'], {'cutoff': 'cutoff', 'return_raw': '(False)'}), '(matrix, pred, true, cutoff=cutoff, return_raw=False)\n', (3234, 3287), False, 'from deepblink.metrics import _f1_at_cutoff\n'), ((3907, 3923), 'pytest.approx', 'pytest.approx', (['(1)'], {}), '(1)\n', (3920, 3923), False, 'import pytest\n'), ((4130, 4149), 'pytest.approx', 'pytest.approx', (['(0.25)'], {}), '(0.25)\n', (4143, 4149), False, 'import pytest\n'), ((4550, 4560), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (4557, 4560), True, 'import numpy as np\n'), ((4562, 4572), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (4569, 4572), True, 'import numpy as np\n'), ((4588, 4612), 'deepblink.metrics.offset_euclidean', 'offset_euclidean', (['offset'], {}), '(offset)\n', (4604, 4612), False, 'from deepblink.metrics import offset_euclidean\n'), ((4616, 4639), 'pytest.approx', 'pytest.approx', (['expected'], {}), '(expected)\n', (4629, 4639), False, 'import pytest\n'), ((732, 742), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (739, 742), True, 'import numpy as np\n'), ((2550, 2560), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (2557, 2560), True, 'import numpy as np\n'), ((2796, 2806), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (2803, 2806), True, 'import numpy as np\n'), ((3313, 3336), 'pytest.approx', 'pytest.approx', (['expected'], {}), '(expected)\n', (3326, 3336), False, 'import pytest\n'), ((4409, 4445), 'numpy.linspace', 'np.linspace', ([], {'start': '(0)', 'stop': '(5)', 'num': '(20)'}), '(start=0, stop=5, num=20)\n', (4420, 4445), True, 'import numpy as np\n')] |
import osgeo
import gdal
import cv2
# import rasterio
import numpy as np
# from rasterio.plot import show
# Set root dir to save results
root = r'TEST-RESULTS/'
save_path = root + 'THRESH_GDAL.jpeg'
def thresh_gdal(img_path = 'defult', start_thresh_value = 65, step = 50, auto = 'off'):
# Fix image_file_path for quick run
if img_path == 'defult':
img_path = root + 'TIR-2.png'
inpuDataset = gdal.Open(img_path)
format = 'JPEG'
driver = gdal.GetDriverByName(format)
# Creat copy of the image to be worked on apart of original input
outputDataset = driver.CreateCopy(save_path, inpuDataset, 0)
# Release values
inpuDataset = None
outputDataset = None
# Load image using GDAL ref and OpenCV library in grayscale
img = cv2.imread(save_path, cv2.IMREAD_LOAD_GDAL & cv2.IMREAD_GRAYSCALE)
thresh_value = start_thresh_value
while thresh_value < 255:
th, processed_image = cv2.threshold(img, thresh_value, 255, cv2.THRESH_BINARY)
cv2.imwrite(save_path, processed_image)
cv2.imshow('thresholded_NDVI', processed_image)
print('THRESH_VALUE: ' + str(thresh_value))
if auto == 'off':
# Wait infinitly for any key press (make sure you on the image window)
cv2.waitKey(0)
else:
cv2.waitKey(500)
cv2.destroyAllWindows()
thresh_value = thresh_value + step
def start():
image_file_path = input('Enter image_file_path or Press Enter for defult: ')
if image_file_path is '':
thresh_gdal()
else:
value = int(input('Enter start_thresh_value: '))
step = int(input('Enter step: '))
auto = input('choose on or off for auto itration mode: ')
thresh_gdal(image_file_path, value, step, auto)
# Load Ref Dictionary
try:
dict = np.load('GDAL_thresh_dictionary.npy',allow_pickle='TRUE').item()
except FileNotFoundError:
# doesn't exist
print('No previous references found, new one will be created!')
dict = {}
else:
# exists
print('Check dict below for previous threshold refernces')
print(dict)
save_to_dictionary = input('Which Threshold Value to be saved for this image?\n give image number and THRESH_VALUE\n (ex: 2,75) \n Enter: ')
a = save_to_dictionary.split(',')
dict[int(a[0])] = int(a[1])
# print(dict)
np.save('GDAL_thresh_dictionary.npy', dict)
| [
"numpy.load",
"numpy.save",
"gdal.GetDriverByName",
"cv2.waitKey",
"cv2.imwrite",
"cv2.threshold",
"cv2.destroyAllWindows",
"gdal.Open",
"cv2.imread",
"cv2.imshow"
] | [((415, 434), 'gdal.Open', 'gdal.Open', (['img_path'], {}), '(img_path)\n', (424, 434), False, 'import gdal\n'), ((468, 496), 'gdal.GetDriverByName', 'gdal.GetDriverByName', (['format'], {}), '(format)\n', (488, 496), False, 'import gdal\n'), ((778, 844), 'cv2.imread', 'cv2.imread', (['save_path', '(cv2.IMREAD_LOAD_GDAL & cv2.IMREAD_GRAYSCALE)'], {}), '(save_path, cv2.IMREAD_LOAD_GDAL & cv2.IMREAD_GRAYSCALE)\n', (788, 844), False, 'import cv2\n'), ((2403, 2446), 'numpy.save', 'np.save', (['"""GDAL_thresh_dictionary.npy"""', 'dict'], {}), "('GDAL_thresh_dictionary.npy', dict)\n", (2410, 2446), True, 'import numpy as np\n'), ((945, 1001), 'cv2.threshold', 'cv2.threshold', (['img', 'thresh_value', '(255)', 'cv2.THRESH_BINARY'], {}), '(img, thresh_value, 255, cv2.THRESH_BINARY)\n', (958, 1001), False, 'import cv2\n'), ((1011, 1050), 'cv2.imwrite', 'cv2.imwrite', (['save_path', 'processed_image'], {}), '(save_path, processed_image)\n', (1022, 1050), False, 'import cv2\n'), ((1059, 1106), 'cv2.imshow', 'cv2.imshow', (['"""thresholded_NDVI"""', 'processed_image'], {}), "('thresholded_NDVI', processed_image)\n", (1069, 1106), False, 'import cv2\n'), ((1346, 1369), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1367, 1369), False, 'import cv2\n'), ((1280, 1294), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (1291, 1294), False, 'import cv2\n'), ((1321, 1337), 'cv2.waitKey', 'cv2.waitKey', (['(500)'], {}), '(500)\n', (1332, 1337), False, 'import cv2\n'), ((1842, 1900), 'numpy.load', 'np.load', (['"""GDAL_thresh_dictionary.npy"""'], {'allow_pickle': '"""TRUE"""'}), "('GDAL_thresh_dictionary.npy', allow_pickle='TRUE')\n", (1849, 1900), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# Copyright (c) 2016, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
# OF SUCH DAMAGE.
import sys
import pylab
import numpy
import Queue
import numpy as np
import rospy
from audio.msg import AudioData
class RealtimePlotter:
def __init__(self):
self.q = Queue.Queue(10)
pylab.ion()
fig = pylab.figure(1)
ax = fig.add_subplot(111)
ax.grid(True)
ax.set_title("Realtime Audio Waveform Plot")
ax.set_xlabel("Time")
ax.set_ylabel("Amplitude")
self.fig =fig
self.ax = ax
self.line1=None
input = rospy.get_param('~input', '/audio/default/raw')
rospy.Subscriber(input, AudioData, RealtimePlotter.callback, self)
def animate(self):
try:
data = self.q.get(True, 0.25)
size = len(data)
xdata=pylab.arange(0,size,1)
ydata=pylab.array(data)
if self.line1 == None:
# Create line plot
self.line1 = self.ax.plot(xdata,ydata,'-')
else:
# Update existing line plot
self.line1[0].set_data(xdata,ydata)
self.ax.axis([xdata.min(),xdata.max(),-1.1,1.1])
self.fig.canvas.draw()
except Queue.Empty:
pass
@staticmethod
def callback(data, self):
if not self.q.full():
# Convert to numpy array and normalize in range [-1,1]
audio = np.array(data.data)
audio = audio / 32767.0
self.q.put(audio)
else:
rospy.logwarn('Audio queue is full!')
if __name__ == '__main__':
try:
rospy.init_node('viewer_audio')
plt = RealtimePlotter()
while not rospy.is_shutdown():
plt.animate()
except rospy.ROSInterruptException: pass
| [
"rospy.logwarn",
"pylab.ion",
"rospy.Subscriber",
"pylab.array",
"Queue.Queue",
"pylab.arange",
"rospy.get_param",
"rospy.is_shutdown",
"pylab.figure",
"rospy.init_node",
"numpy.array"
] | [((1773, 1788), 'Queue.Queue', 'Queue.Queue', (['(10)'], {}), '(10)\n', (1784, 1788), False, 'import Queue\n'), ((1798, 1809), 'pylab.ion', 'pylab.ion', ([], {}), '()\n', (1807, 1809), False, 'import pylab\n'), ((1824, 1839), 'pylab.figure', 'pylab.figure', (['(1)'], {}), '(1)\n', (1836, 1839), False, 'import pylab\n'), ((2115, 2162), 'rospy.get_param', 'rospy.get_param', (['"""~input"""', '"""/audio/default/raw"""'], {}), "('~input', '/audio/default/raw')\n", (2130, 2162), False, 'import rospy\n'), ((2171, 2237), 'rospy.Subscriber', 'rospy.Subscriber', (['input', 'AudioData', 'RealtimePlotter.callback', 'self'], {}), '(input, AudioData, RealtimePlotter.callback, self)\n', (2187, 2237), False, 'import rospy\n'), ((3230, 3261), 'rospy.init_node', 'rospy.init_node', (['"""viewer_audio"""'], {}), "('viewer_audio')\n", (3245, 3261), False, 'import rospy\n'), ((2377, 2401), 'pylab.arange', 'pylab.arange', (['(0)', 'size', '(1)'], {}), '(0, size, 1)\n', (2389, 2401), False, 'import pylab\n'), ((2418, 2435), 'pylab.array', 'pylab.array', (['data'], {}), '(data)\n', (2429, 2435), False, 'import pylab\n'), ((3022, 3041), 'numpy.array', 'np.array', (['data.data'], {}), '(data.data)\n', (3030, 3041), True, 'import numpy as np\n'), ((3134, 3171), 'rospy.logwarn', 'rospy.logwarn', (['"""Audio queue is full!"""'], {}), "('Audio queue is full!')\n", (3147, 3171), False, 'import rospy\n'), ((3321, 3340), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (3338, 3340), False, 'import rospy\n')] |
import numpy as np
npts = 100
seed = 37
norm = np.random.RandomState(seed).randn(npts)
np.savetxt('normal.csv', norm, delimiter=',')
| [
"numpy.savetxt",
"numpy.random.RandomState"
] | [((90, 135), 'numpy.savetxt', 'np.savetxt', (['"""normal.csv"""', 'norm'], {'delimiter': '""","""'}), "('normal.csv', norm, delimiter=',')\n", (100, 135), True, 'import numpy as np\n'), ((49, 76), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (70, 76), True, 'import numpy as np\n')] |
class exponential:
def __init__(self, amplitude=50.0, decay=1.0, shift=1.0,
function="enumerate(('a*exp(-bx)',\
'a*exp(-bx)+c',\
'a*(1-exp(-bx))',\
'a*(1-exp(-bx))+c',\
'a*(1-2*exp(-bx))',\
'a*(1-2*c*exp(-bx))'))",
x=[0.0]):
import numpy as np
self.y = []
x = np.asarray(x)
if function == 'a*exp(-bx)':
self.y = amplitude * np.exp(-x / decay)
elif function == 'a*exp(-bx)+c':
self.y = amplitude * np.exp(-x / decay) + shift
elif function == 'a*(1-exp(-bx))':
self.y = amplitude * (1 - np.exp(-x / decay))
elif function == 'a*(1-exp(-bx))+c':
self.y = amplitude * (1 - np.exp(-x / decay)) + shift
elif function == 'a*(1-2*exp(-bx))':
self.y = amplitude * (1 - 2 * np.exp(-x / decay))
elif function == 'a*(1-2*c*exp(-bx))':
self.y = amplitude * (1 - 2 * shift * np.exp(-x / decay))
def outFonction(self: 'list_float'):
return self.y
###############################################################################
class trigonometric:
def __init__(self, angle=0.0,
function="enumerate(('sin(x)',\
'cos(x)',\
'tan(x)',\
'arcsin(x)',\
'arccos(x)',\
'arctan(x)'))",
x_degree=[0.0]):
import numpy as np
self.y = []
# x = np.asarray(x_degree * np.pi / 180.0)
x = np.radians(x_degree)
angle *= np.pi / 180.0
if function == 'sin(x)':
self.y = np.sin(x + angle)
elif function == 'cos(x)':
self.y = np.cos(x + angle)
elif function == 'tan(x)':
self.y = np.tan(x + angle)
elif function == 'arcsin(x)':
self.y = np.arcsin(x + angle)
elif function == 'arccos(x)':
self.y = np.arccos(x + angle)
elif function == 'arctan(x)':
self.y = np.arctan(x + angle)
def outFonction(self: 'list_float'):
return self.y
###############################################################################
class functions:
def __init__(self, amplitude=10.0, frequency=5.0, sample=500,
functions="enumerate(('ramp',\
'sinus',\
'cosinus',\
'square',\
'triangle'))",
peak_to_peak = True):
from scipy import signal
import numpy as np
if peak_to_peak:
div = 0
else:
div = 1
t = np.linspace(0, 1, sample)
if functions == 'ramp':
self.y = (amplitude / (div + 1)) * (signal.sawtooth(2 * np.pi * frequency * t) + div)
elif functions == 'triangle':
self.y = (amplitude / (div + 1)) * (signal.sawtooth(2 * np.pi * frequency * t, 0.5) + div)
elif functions == 'square':
self.y = (amplitude / (div + 1)) * (signal.square(2 * np.pi * frequency * t) + div)
elif functions == "sinus":
self.y = (amplitude / (div + 1)) * (np.sin(2 * np.pi * frequency * t) + div)
elif functions == "cosinus":
self.y = (amplitude / (div + 1)) * (np.cos(2 * np.pi * frequency * t) + div)
def outRamp(self: 'list_float'):
return self.y
###############################################################################
class PWM:
def __init__(self, sig=[0.0], frequency=30.0):
from scipy import signal
import numpy as np
sig = np.array(sig)
sample = len(sig)
amplitude = max(sig)
t = np.linspace(0, 1, sample, endpoint=False)
self.pwm = amplitude * signal.square(2 * np.pi * frequency * t, duty=((sig / amplitude) + 1)/2)
def out_pwm(self: 'list_float'):
return self.pwm | [
"numpy.radians",
"numpy.asarray",
"scipy.signal.sawtooth",
"numpy.arcsin",
"numpy.sin",
"numpy.array",
"numpy.exp",
"numpy.linspace",
"numpy.cos",
"numpy.tan",
"scipy.signal.square",
"numpy.arccos",
"numpy.arctan"
] | [((512, 525), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (522, 525), True, 'import numpy as np\n'), ((1804, 1824), 'numpy.radians', 'np.radians', (['x_degree'], {}), '(x_degree)\n', (1814, 1824), True, 'import numpy as np\n'), ((3012, 3037), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'sample'], {}), '(0, 1, sample)\n', (3023, 3037), True, 'import numpy as np\n'), ((3987, 4000), 'numpy.array', 'np.array', (['sig'], {}), '(sig)\n', (3995, 4000), True, 'import numpy as np\n'), ((4068, 4109), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'sample'], {'endpoint': '(False)'}), '(0, 1, sample, endpoint=False)\n', (4079, 4109), True, 'import numpy as np\n'), ((1911, 1928), 'numpy.sin', 'np.sin', (['(x + angle)'], {}), '(x + angle)\n', (1917, 1928), True, 'import numpy as np\n'), ((4141, 4213), 'scipy.signal.square', 'signal.square', (['(2 * np.pi * frequency * t)'], {'duty': '((sig / amplitude + 1) / 2)'}), '(2 * np.pi * frequency * t, duty=(sig / amplitude + 1) / 2)\n', (4154, 4213), False, 'from scipy import signal\n'), ((597, 615), 'numpy.exp', 'np.exp', (['(-x / decay)'], {}), '(-x / decay)\n', (603, 615), True, 'import numpy as np\n'), ((1985, 2002), 'numpy.cos', 'np.cos', (['(x + angle)'], {}), '(x + angle)\n', (1991, 2002), True, 'import numpy as np\n'), ((2059, 2076), 'numpy.tan', 'np.tan', (['(x + angle)'], {}), '(x + angle)\n', (2065, 2076), True, 'import numpy as np\n'), ((3118, 3160), 'scipy.signal.sawtooth', 'signal.sawtooth', (['(2 * np.pi * frequency * t)'], {}), '(2 * np.pi * frequency * t)\n', (3133, 3160), False, 'from scipy import signal\n'), ((690, 708), 'numpy.exp', 'np.exp', (['(-x / decay)'], {}), '(-x / decay)\n', (696, 708), True, 'import numpy as np\n'), ((2136, 2156), 'numpy.arcsin', 'np.arcsin', (['(x + angle)'], {}), '(x + angle)\n', (2145, 2156), True, 'import numpy as np\n'), ((3254, 3301), 'scipy.signal.sawtooth', 'signal.sawtooth', (['(2 * np.pi * frequency * t)', '(0.5)'], {}), '(2 * np.pi * frequency * t, 0.5)\n', (3269, 3301), False, 'from scipy import signal\n'), ((798, 816), 'numpy.exp', 'np.exp', (['(-x / decay)'], {}), '(-x / decay)\n', (804, 816), True, 'import numpy as np\n'), ((2216, 2236), 'numpy.arccos', 'np.arccos', (['(x + angle)'], {}), '(x + angle)\n', (2225, 2236), True, 'import numpy as np\n'), ((3393, 3433), 'scipy.signal.square', 'signal.square', (['(2 * np.pi * frequency * t)'], {}), '(2 * np.pi * frequency * t)\n', (3406, 3433), False, 'from scipy import signal\n'), ((2296, 2316), 'numpy.arctan', 'np.arctan', (['(x + angle)'], {}), '(x + angle)\n', (2305, 2316), True, 'import numpy as np\n'), ((3524, 3557), 'numpy.sin', 'np.sin', (['(2 * np.pi * frequency * t)'], {}), '(2 * np.pi * frequency * t)\n', (3530, 3557), True, 'import numpy as np\n'), ((901, 919), 'numpy.exp', 'np.exp', (['(-x / decay)'], {}), '(-x / decay)\n', (907, 919), True, 'import numpy as np\n'), ((3650, 3683), 'numpy.cos', 'np.cos', (['(2 * np.pi * frequency * t)'], {}), '(2 * np.pi * frequency * t)\n', (3656, 3683), True, 'import numpy as np\n'), ((1016, 1034), 'numpy.exp', 'np.exp', (['(-x / decay)'], {}), '(-x / decay)\n', (1022, 1034), True, 'import numpy as np\n'), ((1133, 1151), 'numpy.exp', 'np.exp', (['(-x / decay)'], {}), '(-x / decay)\n', (1139, 1151), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 30 15:13:51 2019
@author: wzhan
"""
"""
Mask R-CNN
Train on the Synthetic Arabidopsis dataset which based on Leaf Challenging Segmentation
https://data.csiro.au/collections/#collection/CIcsiro:34323v004.
Download the dataset and put it under the Mask_RCNN directory
Written by <NAME> and <NAME>
------------------------------------------------------------
"""
# Set matplotlib backend
# This has to be done before other import that might set it
# But only if we're running in script mode.
if __name__ == '__main__':
import matplotlib
# Set 'Agg' as backend which cant display
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# %% importing module
import os
import sys
import datetime
import numpy as np
# To import gen_IDs.py, add the root directory of gen_IDs to a python
# package searching file. You can modify this according to your path
sys.path.append('')
import gen_IDs
from imgaug import augmenters as iaa
from plantcv import plantcv as pcv
# Root directory of the project. You can modify according to your path
ROOT_DIR = '/mnt/efs/data/Mask_RCNN'
# Import Mask RCNN
sys.path.append(ROOT_DIR)
from mrcnn.config import Config
from mrcnn import utils
from mrcnn import model as modellib
from mrcnn import visualize
# %% Preparation of dataset, project directory..
# Path to trained weights file. Put the pre-trained weights file under ROOT_DIR
LEAF_WEIGHTS_PATH = os.path.join(ROOT_DIR, 'mask_rcnn_leaf.h5')
# Direcotry of dataset. Modify it according to your path
dataset_dir ='/mnt/efs/data/synthetic_arabidopsis_LSC'
# Generate the list of image_id for train, validation and test dataset
# The generate_ID function assume the image and mask are stored like
# synthetic_arabidopsis (image file and mask file are under dataset_dir.
# There is no sub folder here)
# If you have different structure of dataset, please modify the generate_IDs
# function in the gen_IDs.py
num_images, Image_IDs_train, Image_IDs_val, Image_IDs_test = gen_IDs.generate_IDs(dataset_dir)
# Direcotry to save logs and model checkpoints, if not provided
# through the command line argument --logs
DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, 'logs')
# Results directory
RESULTS_DIR = os.path.join(ROOT_DIR, 'results/leaves')
# %% Set Hyperparameter for Training
class LeavesConfig(Config):
'''Configuration for training on the Synthetic Arabidopsis dataset.
Derives from the base Config class and overrides values specific to
the leave dataset
'''
# Give the configuration a recognizable name
NAME = 'leaves'
# Number of classes(including background)
NUM_CLASSES = 1 + 1 # background + leaves
# Train on 1 GPU AND 5 images per GPU. We can put multiples images on each
# GPU because the images are samll. Batch size is 5 (GPU * images/GPU)
GPU_COUNT = 1
IMAGES_PER_GPU = 4 # Modify according to your GPU memory. We trained this on AWS P2
Batch_size = GPU_COUNT * IMAGES_PER_GPU
# Number of training and validation steps per epoch
STEPS_PER_EPOCH = (num_images * 0.6)// Batch_size # define dataset_IDS
VALIDATION_STEPS = max(0, (num_images * 0.2) // Batch_size)
# Don't exclude based on confidence. ##??
DETECTION_MIN_CONFIDENCE = 0.8
DETECTION_NMS_THRESHOLD = 0.48
# Backbone network architecture
# Supported values are: resnet50, resnet101
BACKBONE = 'resnet50'
# Input image resizing
# Random crops of size 512x512
IMAGE_RESIZE_MODE = 'crop'
IMAGE_MIN_DIM = 512
IMAGE_MAX_DIM = 512
IMAGE_MIN_SCALE = 2.0
# Length of square anchor side in pixels.
RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128)
# ROIs kept after non-maximum supression (training and inference)
POST_NMS_ROIS_TRAINING = 2000
POST_NMS_ROIS_INFERENCE = 1000
# Non-max suppression threshold to filter RPN proposals.
# You can increase this during training to generate more propsals.
RPN_NMS_THRESHOLD = 0.9
# How many anchors per image to use for RPN training
RPN_TRAIN_ANCHORS_PER_IMAGE = 256
# Image mean (RGB)
MEAN_PIXEL = np.array([123.7, 116.8, 103.9])
# If enabled, resizes instance masks to a smaller size to reduce
# memory load. Recommended when using high-resolution images.
USE_MINI_MASK = True
MINI_MASK_SHAPE = (56, 56) # (height, width) of the mini-mask
# Number of ROIs per image to feed to classifier/mask heads
# The Mask RCNN paper uses 512 but often the RPN doesn't generate
# enough positive proposals to fill this and keep a positive:negative
# ratio of 1:3. You can increase the number of proposals by adjusting
# the RPN NMS threshold.
TRAIN_ROIS_PER_IMAGE = 150
# Maximum number of ground truth instances to use in one image
MAX_GT_INSTANCES = 50 ## ?? you can adjust this to smaller number
# Max number of final detections per image
DETECTION_MAX_INSTANCES = 100 # ?? this number can be much less
# %% Set Hyperparameter for Testing
class LeavesInferenceConfig(LeavesConfig):
# Set batch size to 1 to run and inference one image at a time
GPU_COUNT = 1
IMAGES_PER_GPU =1
# Don't resize image for inferencing
IMAGE_RESIZE_MODE = 'pad64'
# Non-max suppression threhold to filter RPN proposals
# You can increase this during training to generate more proposals
RPN_NMS_THRESHOLD = 0.9
# %% Load Dataset image and mask
class LeavesDataset(utils.Dataset):
"""Load the synthetic arabidopsis dataset.
Different image from dataset has different name. In this load_leaves function, we assume
image name is like format of 'plant00000_rgb.png' and corresponding mask is like
'plant00000_label.png'. The image_id generated by function gen_IDs is like 'plant00000'.
"""
def load_leaves(self, dataset_dir, Image_IDs):
"""Load a subset of the leaf dataset.
dataset_dir: Root direcotry of the dataset
Image_IDs: A list that includes all the images to load
"""
# Add classes. We only have one class to add---leaves
# Naming the dataset 'leaves'
self.add_class('leaves', 1, 'leaves')
# Add images
for image_id in Image_IDs:
self.add_image(
'leaves',
image_id = image_id,
path = os.path.join(dataset_dir, image_id + '_rgb.png')) ##
def load_mask(self, image_id):
'''
Generate masks for each instance of the given image
Input: the image_id, the index number of given image in the Image_IDs_(train, val, test)
Output:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks. Here we only have
one class, leave and class_id = 1.
'''
info = self.image_info[image_id]
mask_id = '{}_label.png'.format(info['id'])
instance_masks = []
# Set debug to 'print' instead of None
pcv.params.debug = 'print'
# Use a pre-v3 function to open a image
# Note that pcv.params.debug is passed to the debug argument
# read the mask file for the given image
masks_img, masks_path, masks_filename = pcv.readimage(os.path.join(dataset_dir, mask_id)) ## path?
# Find the pixel value for each mask
uniq_rgb = np.unique(masks_img.reshape(-1, masks_img.shape[2]), axis=0)
## remove the instance of background, whose pixel value is [0, 0, 0]
uniq_rgb = np.delete(uniq_rgb, 0, 0)
for rgb in uniq_rgb:
# Generate a mask for each instance with positive area = 255
# negative area = 0
mask = np.zeros(np.shape(masks_img)[:2], dtype=np.uint8)
mask[np.all(masks_img == rgb, axis=-1)] = 255
# Transfer the mask to bool mask. Positive area = True
# Negative area = False
mask = mask.astype(np.bool)
instance_masks.append(mask)
instance_masks = np.stack(instance_masks, axis=-1)
return instance_masks, np.ones(uniq_rgb.shape[0], dtype=np.int32)
def image_reference(self, image_id):
"""Return the path of the image."""
info = self.image_info[image_id]
if info['source'] == 'leaves':
return info['id']
else:
super(self.__class__, self).image_reference(image_id)
# %% Training
def train(model, dataset_dir):
""" Train the model. """
# Preparing training and validation dataset
## Generate LeavesDataset class.
dataset_train = LeavesDataset()
dataset_val = LeavesDataset()
## Preparing training dataset.
dataset_train.load_leaves(dataset_dir, Image_IDs_train)
dataset_train.prepare()
## Preparing validation dataset
dataset_val.load_leaves(dataset_dir, Image_IDs_val)
dataset_val.prepare()
# Image augmentation
# http://imgaug.readthedocs.io/en/latest/source/augmenters.html
augmentation = iaa.SomeOf((0, 2), [
iaa.Fliplr(0.5),
iaa.Flipud(0.5),
iaa.OneOf([iaa.Affine(rotate=90),
iaa.Affine(rotate=180),
iaa.Affine(rotate=270)]),
iaa.Multiply((0.8, 1.5)),
iaa.GaussianBlur(sigma=(0.0, 5.0))
])
# *** This training schedule is an example. Update to your needs ***
# If starting from mask_rcnn_leave.h5, train heads only for a bit
# since they have random weights
print("Train network heads")
model.train(dataset_train, dataset_val,
learning_rate=config.LEARNING_RATE,
epochs = 20, # Discuss with Dr Noah
augmentation=augmentation,
layers='heads')
print("Train all layers")
model.train(dataset_train, dataset_val,
learning_rate=config.LEARNING_RATE,
epochs = 60, # Discuss with Dr Noah
augmentation=augmentation,
layers='all')
# %%RLE Encoding
def rle_encode(mask):
"""Encodes a mask in Run Length Encoding (RLE).
Returns a string of space-separated values.
"""
assert mask.ndim == 2, "Mask must be of shape [Height, Width]"
# Flatten it column wise
m = mask.T.flatten()
# Compute gradient. Equals 1 or -1 at transition points
g = np.diff(np.concatenate([[0], m, [0]]), n=1)
# 1-based indicies of transition points (where gradient != 0)
rle = np.where(g != 0)[0].reshape([-1, 2]) + 1
# Convert second index in each pair to lenth
rle[:, 1] = rle[:, 1] - rle[:, 0]
return " ".join(map(str, rle.flatten()))
def rle_decode(rle, shape):
"""Decodes an RLE encoded list of space separated
numbers and returns a binary mask."""
rle = list(map(int, rle.split()))
rle = np.array(rle, dtype=np.int32).reshape([-1, 2])
rle[:, 1] += rle[:, 0]
rle -= 1
mask = np.zeros([shape[0] * shape[1]], np.bool)
for s, e in rle:
assert 0 <= s < mask.shape[0]
assert 1 <= e <= mask.shape[0], "shape: {} s {} e {}".format(shape, s, e)
mask[s:e] = 1
# Reshape and transpose
mask = mask.reshape([shape[1], shape[0]]).T
return mask
def mask_to_rle(image_id, mask, scores):
"Encodes instance masks to submission format."
assert mask.ndim == 3, "Mask must be [H, W, count]"
# If mask is empty, return line with image ID only
if mask.shape[-1] == 0:
return "{},".format(image_id)
# Remove mask overlaps
# Multiply each instance mask by its score order
# then take the maximum across the last dimension
order = np.argsort(scores)[::-1] + 1 # 1-based descending
mask = np.max(mask * np.reshape(order, [1, 1, -1]), -1)
# Loop over instance masks
lines = []
for o in order:
m = np.where(mask == o, 1, 0)
# Skip if empty
if m.sum() == 0.0:
continue
rle = rle_encode(m)
lines.append("{}, {}".format(image_id, rle))
return "\n".join(lines)
# %% Inferencing
def detect(model, dataset_dir):
"""Run detection on images in the given directory."""
print("Running on {}".format(dataset_dir))
# Create directory to store detecting result.
if not os.path.exists(RESULTS_DIR):
os.makedirs(RESULTS_DIR)
submit_dir = "submit_{:%Y%m%dT%H%M%S}".format(datetime.datetime.now())
submit_dir = os.path.join(RESULTS_DIR, submit_dir)
os.makedirs(submit_dir)
# Load test dataset
dataset_test = LeavesDataset()
dataset_test.load_leaves(dataset_dir, Image_IDs_test)
dataset_test.prepare()
# Load over images
submission = []
for image_id in dataset_test.image_ids:
# Load image and run detection
image = dataset_test.load_image(image_id)
# Detect objects
r = model.detect([image], verbose=0)[0]
# Encode image to RLE. Returns a string of multiple lines
source_id = dataset_test.image_info[image_id]["id"]
rle = mask_to_rle(source_id, r["masks"], r["scores"])
submission.append(rle)
# Save image with masks
visualize.display_instances(
image, r['rois'], r['masks'], r['class_ids'],
dataset_test.class_names, r['scores'],
show_bbox=False, show_mask=False,
title="Predictions")
plt.savefig("{}/{}.png".format(submit_dir, dataset_test.image_info[image_id]["id"]))
# Save to csv file
submission = "ImageId,EncodedPixels\n" + "\n".join(submission)
file_path = os.path.join(submit_dir, "submit.csv")
with open(file_path, "w") as f:
f.write(submission)
print("Saved to ", submit_dir)
##%% Running on spyder directory instead command line
#
## Training
### Configurations
#config = LeavesConfig()
##config.display()
### Create model
#print('in mask RCNN +++++++++++++++++++++++++++++++++++++++++++++++')
#model = modellib.MaskRCNN(mode='training', config=config, model_dir= DEFAULT_LOGS_DIR)
### Select weights file to load
#weights_path = LEAF_WEIGHTS_PATH
#model.load_weights(weights_path, by_name=True)
#train(model, dataset_dir)
# %% Running using Command Line parsing
if __name__ == '__main__':
import argparse
# Parse command line arguments
parser = argparse.ArgumentParser(
description='Mask R-CNN for leaf counting and segmentation')
parser.add_argument("command",
metavar="<command>",
help="'train' or 'detect'")
parser.add_argument('--dataset_dir', required=False,
metavar="/path/to/dataset_dir/",
help='Root directory of the dataset_dir')
parser.add_argument('--weights', required=True,
metavar="/path/to/weights.h5",
help="Path to weights .h5 file")
parser.add_argument('--logs', required=False,
default=DEFAULT_LOGS_DIR,
metavar="/path/to/logs/",
help='Logs and checkpoints directory (default=logs/)')
args = parser.parse_args()
# Validate arguments
if args.command == "train":
assert args.dataset_dir, "Argument --dataset_dir is required for training"
elif args.command == "detect":
assert args.dataset_dir, "Provide --dataset_dir to run prediction on"
print("Weights: ", args.weights)
print("Dataset: ", args.dataset_dir)
print("Logs: ", args.logs)
# Configurations
if args.command == "train":
config = LeavesConfig()
else:
config = LeavesInferenceConfig()
config.display()
# Create model
if args.command == "train":
print('in mask RCNN +++++++++++++++++++++++++++++++++++++++++++++++')
model = modellib.MaskRCNN(mode="training", config=config,
model_dir=args.logs)
else:
model = modellib.MaskRCNN(mode="inference", config=config,
model_dir=args.logs)
# Select weights file to load
if args.weights.lower() == "last":
# Find last trained weights
weights_path = model.find_last()[1]
else:
weights_path = args.weights
# Load weights
print("Loading weights ", weights_path)
model.load_weights(weights_path, by_name=True)
# Train or evaluate
if args.command == "train":
train(model, args.dataset_dir)
elif args.command == "detect":
detect(model, args.dataset_dir)
else:
print("'{}' is not recognized. "
"Use 'train' or 'detect'".format(args.command))
| [
"argparse.ArgumentParser",
"numpy.ones",
"numpy.argsort",
"numpy.shape",
"mrcnn.model.MaskRCNN",
"os.path.join",
"imgaug.augmenters.GaussianBlur",
"sys.path.append",
"os.path.exists",
"imgaug.augmenters.Flipud",
"numpy.reshape",
"datetime.datetime.now",
"numpy.stack",
"matplotlib.use",
"... | [((950, 969), 'sys.path.append', 'sys.path.append', (['""""""'], {}), "('')\n", (965, 969), False, 'import sys\n'), ((1191, 1216), 'sys.path.append', 'sys.path.append', (['ROOT_DIR'], {}), '(ROOT_DIR)\n', (1206, 1216), False, 'import sys\n'), ((1494, 1537), 'os.path.join', 'os.path.join', (['ROOT_DIR', '"""mask_rcnn_leaf.h5"""'], {}), "(ROOT_DIR, 'mask_rcnn_leaf.h5')\n", (1506, 1537), False, 'import os\n'), ((2067, 2100), 'gen_IDs.generate_IDs', 'gen_IDs.generate_IDs', (['dataset_dir'], {}), '(dataset_dir)\n', (2087, 2100), False, 'import gen_IDs\n'), ((2230, 2260), 'os.path.join', 'os.path.join', (['ROOT_DIR', '"""logs"""'], {}), "(ROOT_DIR, 'logs')\n", (2242, 2260), False, 'import os\n'), ((2297, 2337), 'os.path.join', 'os.path.join', (['ROOT_DIR', '"""results/leaves"""'], {}), "(ROOT_DIR, 'results/leaves')\n", (2309, 2337), False, 'import os\n'), ((669, 690), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (683, 690), False, 'import matplotlib\n'), ((4227, 4258), 'numpy.array', 'np.array', (['[123.7, 116.8, 103.9]'], {}), '([123.7, 116.8, 103.9])\n', (4235, 4258), True, 'import numpy as np\n'), ((11191, 11231), 'numpy.zeros', 'np.zeros', (['[shape[0] * shape[1]]', 'np.bool'], {}), '([shape[0] * shape[1]], np.bool)\n', (11199, 11231), True, 'import numpy as np\n'), ((12678, 12715), 'os.path.join', 'os.path.join', (['RESULTS_DIR', 'submit_dir'], {}), '(RESULTS_DIR, submit_dir)\n', (12690, 12715), False, 'import os\n'), ((12720, 12743), 'os.makedirs', 'os.makedirs', (['submit_dir'], {}), '(submit_dir)\n', (12731, 12743), False, 'import os\n'), ((13814, 13852), 'os.path.join', 'os.path.join', (['submit_dir', '"""submit.csv"""'], {}), "(submit_dir, 'submit.csv')\n", (13826, 13852), False, 'import os\n'), ((14544, 14633), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Mask R-CNN for leaf counting and segmentation"""'}), "(description=\n 'Mask R-CNN for leaf counting and segmentation')\n", (14567, 14633), False, 'import argparse\n'), ((7772, 7797), 'numpy.delete', 'np.delete', (['uniq_rgb', '(0)', '(0)'], {}), '(uniq_rgb, 0, 0)\n', (7781, 7797), True, 'import numpy as np\n'), ((8271, 8304), 'numpy.stack', 'np.stack', (['instance_masks'], {'axis': '(-1)'}), '(instance_masks, axis=-1)\n', (8279, 8304), True, 'import numpy as np\n'), ((10634, 10663), 'numpy.concatenate', 'np.concatenate', (['[[0], m, [0]]'], {}), '([[0], m, [0]])\n', (10648, 10663), True, 'import numpy as np\n'), ((12095, 12120), 'numpy.where', 'np.where', (['(mask == o)', '(1)', '(0)'], {}), '(mask == o, 1, 0)\n', (12103, 12120), True, 'import numpy as np\n'), ((12524, 12551), 'os.path.exists', 'os.path.exists', (['RESULTS_DIR'], {}), '(RESULTS_DIR)\n', (12538, 12551), False, 'import os\n'), ((12561, 12585), 'os.makedirs', 'os.makedirs', (['RESULTS_DIR'], {}), '(RESULTS_DIR)\n', (12572, 12585), False, 'import os\n'), ((12636, 12659), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (12657, 12659), False, 'import datetime\n'), ((13397, 13572), 'mrcnn.visualize.display_instances', 'visualize.display_instances', (['image', "r['rois']", "r['masks']", "r['class_ids']", 'dataset_test.class_names', "r['scores']"], {'show_bbox': '(False)', 'show_mask': '(False)', 'title': '"""Predictions"""'}), "(image, r['rois'], r['masks'], r['class_ids'],\n dataset_test.class_names, r['scores'], show_bbox=False, show_mask=False,\n title='Predictions')\n", (13424, 13572), False, 'from mrcnn import visualize\n'), ((16042, 16112), 'mrcnn.model.MaskRCNN', 'modellib.MaskRCNN', ([], {'mode': '"""training"""', 'config': 'config', 'model_dir': 'args.logs'}), "(mode='training', config=config, model_dir=args.logs)\n", (16059, 16112), True, 'from mrcnn import model as modellib\n'), ((16173, 16244), 'mrcnn.model.MaskRCNN', 'modellib.MaskRCNN', ([], {'mode': '"""inference"""', 'config': 'config', 'model_dir': 'args.logs'}), "(mode='inference', config=config, model_dir=args.logs)\n", (16190, 16244), True, 'from mrcnn import model as modellib\n'), ((7503, 7537), 'os.path.join', 'os.path.join', (['dataset_dir', 'mask_id'], {}), '(dataset_dir, mask_id)\n', (7515, 7537), False, 'import os\n'), ((8336, 8378), 'numpy.ones', 'np.ones', (['uniq_rgb.shape[0]'], {'dtype': 'np.int32'}), '(uniq_rgb.shape[0], dtype=np.int32)\n', (8343, 8378), True, 'import numpy as np\n'), ((9330, 9345), 'imgaug.augmenters.Fliplr', 'iaa.Fliplr', (['(0.5)'], {}), '(0.5)\n', (9340, 9345), True, 'from imgaug import augmenters as iaa\n'), ((9355, 9370), 'imgaug.augmenters.Flipud', 'iaa.Flipud', (['(0.5)'], {}), '(0.5)\n', (9365, 9370), True, 'from imgaug import augmenters as iaa\n'), ((9510, 9534), 'imgaug.augmenters.Multiply', 'iaa.Multiply', (['(0.8, 1.5)'], {}), '((0.8, 1.5))\n', (9522, 9534), True, 'from imgaug import augmenters as iaa\n'), ((9544, 9578), 'imgaug.augmenters.GaussianBlur', 'iaa.GaussianBlur', ([], {'sigma': '(0.0, 5.0)'}), '(sigma=(0.0, 5.0))\n', (9560, 9578), True, 'from imgaug import augmenters as iaa\n'), ((11093, 11122), 'numpy.array', 'np.array', (['rle'], {'dtype': 'np.int32'}), '(rle, dtype=np.int32)\n', (11101, 11122), True, 'import numpy as np\n'), ((11906, 11924), 'numpy.argsort', 'np.argsort', (['scores'], {}), '(scores)\n', (11916, 11924), True, 'import numpy as np\n'), ((11982, 12011), 'numpy.reshape', 'np.reshape', (['order', '[1, 1, -1]'], {}), '(order, [1, 1, -1])\n', (11992, 12011), True, 'import numpy as np\n'), ((8021, 8054), 'numpy.all', 'np.all', (['(masks_img == rgb)'], {'axis': '(-1)'}), '(masks_img == rgb, axis=-1)\n', (8027, 8054), True, 'import numpy as np\n'), ((6512, 6560), 'os.path.join', 'os.path.join', (['dataset_dir', "(image_id + '_rgb.png')"], {}), "(dataset_dir, image_id + '_rgb.png')\n", (6524, 6560), False, 'import os\n'), ((7963, 7982), 'numpy.shape', 'np.shape', (['masks_img'], {}), '(masks_img)\n', (7971, 7982), True, 'import numpy as np\n'), ((9391, 9412), 'imgaug.augmenters.Affine', 'iaa.Affine', ([], {'rotate': '(90)'}), '(rotate=90)\n', (9401, 9412), True, 'from imgaug import augmenters as iaa\n'), ((9433, 9455), 'imgaug.augmenters.Affine', 'iaa.Affine', ([], {'rotate': '(180)'}), '(rotate=180)\n', (9443, 9455), True, 'from imgaug import augmenters as iaa\n'), ((9476, 9498), 'imgaug.augmenters.Affine', 'iaa.Affine', ([], {'rotate': '(270)'}), '(rotate=270)\n', (9486, 9498), True, 'from imgaug import augmenters as iaa\n'), ((10746, 10762), 'numpy.where', 'np.where', (['(g != 0)'], {}), '(g != 0)\n', (10754, 10762), True, 'import numpy as np\n')] |
import random
import itertools
import collections
import numpy as np
import tensorflow as tf
from bot_code.modelHelpers.actions.action_handler import ActionHandler, ActionMap
class SplitActionHandler(ActionHandler):
"""
For the different actions, (input axes and their possible values)
defines and applies the loss function.
Notes:
- `index` in the context of this class means an index into the `actions` list
"""
actions = []
action_sizes = []
movement_actions = []
tensorflow_combo_actions = []
def __init__(self):
super().__init__()
def reset(self):
super().reset()
self.actions = []
self.action_sizes = []
self.movement_actions = []
self.tensorflow_combo_actions = []
def create_actions(self):
self.reset()
"""
Creates all variations of all of the actions.
controller options = [throttle, steer, pitch, steer, roll, jump, boost, handbrake]
:return: A combination of all actions. This is an array of an array
"""
steer = np.arange(-1, 1.5, .5)
pitch = np.arange(-1, 1.5, .5)
roll = np.arange(-1, 1.5, .5)
throttle = np.arange(-1, 2, 1)
jump = [False, True]
boost = [False, True]
handbrake = [False, True]
action_list = [throttle, jump, boost, handbrake]
self.combo_list = action_list
# 24 + 5 + 5 + 5 = 39
button_combo = list(itertools.product(*action_list))
actions = []
split_actions_sizes = []
actions.append(steer)
actions.append(pitch)
actions.append(roll)
self.movement_actions = tf.constant(np.array(actions), shape=[len(actions), len(steer)])
self.tensorflow_combo_actions = tf.constant(button_combo)
self.action_list_names = ['steer', 'pitch', 'yaw', 'combo']
actions.append(button_combo)
for i in actions:
split_actions_sizes.append(len(i))
self.action_sizes = split_actions_sizes
return actions
def create_action_map(self):
return ActionMap(self.actions[3])
def is_split_mode(self):
return True
def get_number_actions(self):
return len(self.actions)
def get_action_sizes(self):
return self.action_sizes
def get_logit_size(self):
"""
:return: the size of the logits layer in a model
"""
counter = 0
for action in self.actions:
counter += len(action)
return counter
def _create_one_hot_encoding(self, action_indexes):
encoding = np.zeros(39)
encoding[action_indexes[0] + 0] = 1
encoding[action_indexes[1] + 5] = 1
encoding[action_indexes[2] + 10] = 1
encoding[action_indexes[3] + 15] = 1
return encoding
def create_action_index(self, real_action):
steer = real_action[1]
yaw = real_action[3]
if steer != yaw and abs(steer) < abs(yaw):
# only take the larger magnitude number
steer = yaw
steer_index = self._find_closet_real_number(steer)
pitch_index = self._find_closet_real_number(real_action[2])
roll_index = self._find_closet_real_number(real_action[4])
button_combo = self.action_map.get_key([round(real_action[0]), real_action[5], real_action[6], real_action[7]])
return [steer_index, pitch_index, roll_index, button_combo]
def create_controller_from_selection(self, action_selection):
if len(action_selection) != len(self.actions):
print('ACTION SELECTION IS NOT THE SAME LENGTH returning invalid action data')
return [0, 0, 0, 0, 0, False, False, False]
steer = self.actions[0][action_selection[0]]
pitch = self.actions[1][action_selection[1]]
roll = self.actions[2][action_selection[2]]
button_combo = self.actions[3][action_selection[3]]
throttle = button_combo[0]
jump = button_combo[1]
boost = button_combo[2]
handbrake = button_combo[3]
controller_option = [throttle, steer, pitch, steer, roll, jump, boost, handbrake]
# print(controller_option)
return controller_option
def create_tensorflow_controller_from_selection(self, action_selection, batch_size=1, should_stack=True):
movement_actions = self.movement_actions
combo_actions = self.tensorflow_combo_actions
indexer = tf.constant(1, dtype=tf.int32)
action_selection = tf.cast(action_selection, tf.int32)
if batch_size > 1:
movement_actions = tf.expand_dims(movement_actions, 0)
multiplier = tf.constant([int(batch_size), 1, 1])
movement_actions = tf.tile(movement_actions, multiplier)
combo_actions = tf.tile(tf.expand_dims(combo_actions, 0), multiplier)
indexer = tf.constant(np.arange(0, batch_size, 1), dtype=tf.int32)
yaw_actions = tf.squeeze(tf.slice(movement_actions, [0, 0, 0], [-1, 1, -1]))
pitch_actions = tf.squeeze(tf.slice(movement_actions, [0, 1, 0], [-1, 1, -1]))
roll_actions = tf.squeeze(tf.slice(movement_actions, [0, 2, 0], [-1, 1, -1]))
else:
yaw_actions = movement_actions[0]
pitch_actions = movement_actions[1]
roll_actions = movement_actions[2]
# we get the options based on each individual index in the batches. so this returns batch_size options
steer = tf.gather_nd(yaw_actions, tf.stack([indexer, action_selection[0]], axis=1))
pitch = tf.gather_nd(pitch_actions, tf.stack([indexer, action_selection[1]], axis=1))
roll = tf.gather_nd(roll_actions, tf.stack([indexer, action_selection[2]], axis=1))
button_combo = tf.gather_nd(combo_actions, tf.stack([indexer, action_selection[3]], axis=1))
new_shape = [len(self.combo_list), batch_size]
button_combo = tf.reshape(button_combo, new_shape)
throttle = button_combo[0]
jump = button_combo[1]
boost = button_combo[2]
handbrake = button_combo[3]
controller_option = [throttle, steer, pitch, steer, roll, jump, boost, handbrake]
controller_option = [tf.cast(option, tf.float32) for option in controller_option]
# print(controller_option)
if should_stack:
return tf.stack(controller_option, axis=1)
return controller_option
def get_random_option(self):
return [random.randrange(5), random.randrange(5), random.randrange(5), random.randrange(24)]
def run_func_on_split_tensors(self, input_tensors, split_func, return_as_list=False):
"""
Optionally splits the tensor and runs a function on the split tensor
If the tensor should not be split it runs the function on the entire tensor
:param input_tensors: needs to have shape of (?, num_actions)
:param split_func: a function that is called with a tensor or array the same rank as input_tensor.
It should return a tensor with the same rank as input_tensor
:param return_as_list If true then the result will be a list of tensors instead of a single stacked tensor
:return: a stacked tensor (see tf.stack) or the same tensor depending on if it is in split mode or not.
"""
if not isinstance(input_tensors, collections.Sequence):
input_tensors = [input_tensors]
total_input = []
for i in self.action_sizes:
total_input.append([])
for tensor in input_tensors:
total_action_size = 0
for i, val in enumerate(self.action_sizes):
starting_length = len(total_input[i])
if isinstance(tensor, collections.Sequence):
if len(tensor) == self.get_logit_size():
# grabs each slice of tensor
total_input[i].append(tensor[total_action_size:total_action_size + val])
else:
total_input[i].append(tensor[i])
else:
if len(tensor.get_shape()) == 0:
total_input[i].append(tf.identity(tensor, name='copy' + str(i)))
elif tensor.get_shape()[0] == self.get_logit_size():
total_input[i].append(tf.slice(tensor, [total_action_size], [val]))
elif tensor.get_shape()[1] == self.get_logit_size():
total_input[i].append(tf.slice(tensor, [0, total_action_size], [-1, val]))
elif tensor.get_shape()[1] == self.get_number_actions():
total_input[i].append(tf.slice(tensor, [0, i], [-1, 1]))
elif tensor.get_shape()[1] == 1:
total_input[i].append(tf.identity(tensor, name='copy' + str(i)))
total_action_size += val
if starting_length == len(total_input[i]):
print('tensor ignored', tensor)
if len(total_input[0]) != len(input_tensors):
print('mis match in tensor length')
results = []
for i, val in enumerate(self.action_list_names):
with tf.name_scope(val):
try:
functional_input = total_input[i]
results.append(split_func(*functional_input))
except Exception as e:
print('exception in split func ', val)
raise e
if return_as_list:
return results
return tf.stack(results, axis=1)
def optionally_split_numpy_arrays(self, numpy_array, split_func, is_already_split=False):
"""
Optionally splits the tensor and runs a function on the split tensor
If the tensor should not be split it runs the function on the entire tensor
:param numpy_array: needs to have shape of (?, num_actions)
:param split_func: a function that is called with a tensor the same rank as input_tensor.
It should return a tensor with the same rank as input_tensor
:param is_already_split: True if the array is already sliced by action length
:return: a stacked tensor (see tf.stack) or the same tensor depending on if it is in split mode or not.
"""
total_input = []
total_action_size = 0
for i, val in enumerate(self.action_sizes):
if not is_already_split:
total_input.append(numpy_array[:, total_action_size:val])
else:
total_input.append(numpy_array[i])
total_action_size += val
result = []
for element in total_input:
result.append(split_func(element))
return result
def create_action_indexes_graph(self, real_action, batch_size=None):
#slice each index
throttle = tf.slice(real_action, [0, 0], [-1, 1])
steer = tf.slice(real_action, [0, 1], [-1, 1])
pitch = tf.slice(real_action, [0, 2], [-1, 1])
yaw = tf.slice(real_action, [0, 3], [-1, 1])
roll = tf.slice(real_action, [0, 4], [-1, 1])
jump = tf.slice(real_action, [0, 5], [-1, 1])
boost = tf.slice(real_action, [0, 6], [-1, 1])
handbrake = tf.slice(real_action, [0, 7], [-1, 1])
conditional = tf.logical_and(tf.not_equal(steer, yaw), tf.less(tf.abs(steer), tf.abs(yaw)))
use_yaw = tf.cast(conditional, tf.float32)
use_steer = 1.0 - use_yaw
steer = use_yaw * yaw + use_steer * steer
steer_index = self._find_closet_real_number_graph(steer)
pitch_index = self._find_closet_real_number_graph(pitch)
roll_index = self._find_closet_real_number_graph(roll)
rounded_throttle = tf.maximum(-1.0, tf.minimum(1.0, tf.round(throttle * 1.5)))
# throttle, jump, boost, handbrake -> index number
binary_combo_index = tf.squeeze(tf.constant(16.0) * tf.cast(tf.equal(rounded_throttle, 1), tf.float32) +
tf.constant(8.0) * tf.cast(tf.equal(rounded_throttle, 0), tf.float32) +
tf.constant(4.0) * jump +
tf.constant(2.0) * boost +
tf.constant(1.0) * handbrake)
result = tf.stack([steer_index, pitch_index, roll_index, binary_combo_index], axis=1)
return result
| [
"tensorflow.not_equal",
"tensorflow.abs",
"tensorflow.reshape",
"numpy.zeros",
"tensorflow.constant",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.tile",
"tensorflow.round",
"numpy.arange",
"numpy.array",
"random.randrange",
"itertools.product",
"tensorflow.equal",
"tensorflow.slic... | [((1135, 1158), 'numpy.arange', 'np.arange', (['(-1)', '(1.5)', '(0.5)'], {}), '(-1, 1.5, 0.5)\n', (1144, 1158), True, 'import numpy as np\n'), ((1175, 1198), 'numpy.arange', 'np.arange', (['(-1)', '(1.5)', '(0.5)'], {}), '(-1, 1.5, 0.5)\n', (1184, 1198), True, 'import numpy as np\n'), ((1214, 1237), 'numpy.arange', 'np.arange', (['(-1)', '(1.5)', '(0.5)'], {}), '(-1, 1.5, 0.5)\n', (1223, 1237), True, 'import numpy as np\n'), ((1257, 1276), 'numpy.arange', 'np.arange', (['(-1)', '(2)', '(1)'], {}), '(-1, 2, 1)\n', (1266, 1276), True, 'import numpy as np\n'), ((1850, 1875), 'tensorflow.constant', 'tf.constant', (['button_combo'], {}), '(button_combo)\n', (1861, 1875), True, 'import tensorflow as tf\n'), ((2183, 2209), 'bot_code.modelHelpers.actions.action_handler.ActionMap', 'ActionMap', (['self.actions[3]'], {}), '(self.actions[3])\n', (2192, 2209), False, 'from bot_code.modelHelpers.actions.action_handler import ActionHandler, ActionMap\n'), ((2719, 2731), 'numpy.zeros', 'np.zeros', (['(39)'], {}), '(39)\n', (2727, 2731), True, 'import numpy as np\n'), ((4605, 4635), 'tensorflow.constant', 'tf.constant', (['(1)'], {'dtype': 'tf.int32'}), '(1, dtype=tf.int32)\n', (4616, 4635), True, 'import tensorflow as tf\n'), ((4664, 4699), 'tensorflow.cast', 'tf.cast', (['action_selection', 'tf.int32'], {}), '(action_selection, tf.int32)\n', (4671, 4699), True, 'import tensorflow as tf\n'), ((6104, 6139), 'tensorflow.reshape', 'tf.reshape', (['button_combo', 'new_shape'], {}), '(button_combo, new_shape)\n', (6114, 6139), True, 'import tensorflow as tf\n'), ((9817, 9842), 'tensorflow.stack', 'tf.stack', (['results'], {'axis': '(1)'}), '(results, axis=1)\n', (9825, 9842), True, 'import tensorflow as tf\n'), ((11161, 11199), 'tensorflow.slice', 'tf.slice', (['real_action', '[0, 0]', '[-1, 1]'], {}), '(real_action, [0, 0], [-1, 1])\n', (11169, 11199), True, 'import tensorflow as tf\n'), ((11217, 11255), 'tensorflow.slice', 'tf.slice', (['real_action', '[0, 1]', '[-1, 1]'], {}), '(real_action, [0, 1], [-1, 1])\n', (11225, 11255), True, 'import tensorflow as tf\n'), ((11273, 11311), 'tensorflow.slice', 'tf.slice', (['real_action', '[0, 2]', '[-1, 1]'], {}), '(real_action, [0, 2], [-1, 1])\n', (11281, 11311), True, 'import tensorflow as tf\n'), ((11327, 11365), 'tensorflow.slice', 'tf.slice', (['real_action', '[0, 3]', '[-1, 1]'], {}), '(real_action, [0, 3], [-1, 1])\n', (11335, 11365), True, 'import tensorflow as tf\n'), ((11382, 11420), 'tensorflow.slice', 'tf.slice', (['real_action', '[0, 4]', '[-1, 1]'], {}), '(real_action, [0, 4], [-1, 1])\n', (11390, 11420), True, 'import tensorflow as tf\n'), ((11437, 11475), 'tensorflow.slice', 'tf.slice', (['real_action', '[0, 5]', '[-1, 1]'], {}), '(real_action, [0, 5], [-1, 1])\n', (11445, 11475), True, 'import tensorflow as tf\n'), ((11493, 11531), 'tensorflow.slice', 'tf.slice', (['real_action', '[0, 6]', '[-1, 1]'], {}), '(real_action, [0, 6], [-1, 1])\n', (11501, 11531), True, 'import tensorflow as tf\n'), ((11553, 11591), 'tensorflow.slice', 'tf.slice', (['real_action', '[0, 7]', '[-1, 1]'], {}), '(real_action, [0, 7], [-1, 1])\n', (11561, 11591), True, 'import tensorflow as tf\n'), ((11714, 11746), 'tensorflow.cast', 'tf.cast', (['conditional', 'tf.float32'], {}), '(conditional, tf.float32)\n', (11721, 11746), True, 'import tensorflow as tf\n'), ((12636, 12712), 'tensorflow.stack', 'tf.stack', (['[steer_index, pitch_index, roll_index, binary_combo_index]'], {'axis': '(1)'}), '([steer_index, pitch_index, roll_index, binary_combo_index], axis=1)\n', (12644, 12712), True, 'import tensorflow as tf\n'), ((1530, 1561), 'itertools.product', 'itertools.product', (['*action_list'], {}), '(*action_list)\n', (1547, 1561), False, 'import itertools\n'), ((1756, 1773), 'numpy.array', 'np.array', (['actions'], {}), '(actions)\n', (1764, 1773), True, 'import numpy as np\n'), ((4760, 4795), 'tensorflow.expand_dims', 'tf.expand_dims', (['movement_actions', '(0)'], {}), '(movement_actions, 0)\n', (4774, 4795), True, 'import tensorflow as tf\n'), ((4891, 4928), 'tensorflow.tile', 'tf.tile', (['movement_actions', 'multiplier'], {}), '(movement_actions, multiplier)\n', (4898, 4928), True, 'import tensorflow as tf\n'), ((5682, 5730), 'tensorflow.stack', 'tf.stack', (['[indexer, action_selection[0]]'], {'axis': '(1)'}), '([indexer, action_selection[0]], axis=1)\n', (5690, 5730), True, 'import tensorflow as tf\n'), ((5777, 5825), 'tensorflow.stack', 'tf.stack', (['[indexer, action_selection[1]]'], {'axis': '(1)'}), '([indexer, action_selection[1]], axis=1)\n', (5785, 5825), True, 'import tensorflow as tf\n'), ((5870, 5918), 'tensorflow.stack', 'tf.stack', (['[indexer, action_selection[2]]'], {'axis': '(1)'}), '([indexer, action_selection[2]], axis=1)\n', (5878, 5918), True, 'import tensorflow as tf\n'), ((5974, 6022), 'tensorflow.stack', 'tf.stack', (['[indexer, action_selection[3]]'], {'axis': '(1)'}), '([indexer, action_selection[3]], axis=1)\n', (5982, 6022), True, 'import tensorflow as tf\n'), ((6399, 6426), 'tensorflow.cast', 'tf.cast', (['option', 'tf.float32'], {}), '(option, tf.float32)\n', (6406, 6426), True, 'import tensorflow as tf\n'), ((6542, 6577), 'tensorflow.stack', 'tf.stack', (['controller_option'], {'axis': '(1)'}), '(controller_option, axis=1)\n', (6550, 6577), True, 'import tensorflow as tf\n'), ((6665, 6684), 'random.randrange', 'random.randrange', (['(5)'], {}), '(5)\n', (6681, 6684), False, 'import random\n'), ((6686, 6705), 'random.randrange', 'random.randrange', (['(5)'], {}), '(5)\n', (6702, 6705), False, 'import random\n'), ((6707, 6726), 'random.randrange', 'random.randrange', (['(5)'], {}), '(5)\n', (6723, 6726), False, 'import random\n'), ((6728, 6748), 'random.randrange', 'random.randrange', (['(24)'], {}), '(24)\n', (6744, 6748), False, 'import random\n'), ((11632, 11656), 'tensorflow.not_equal', 'tf.not_equal', (['steer', 'yaw'], {}), '(steer, yaw)\n', (11644, 11656), True, 'import tensorflow as tf\n'), ((4966, 4998), 'tensorflow.expand_dims', 'tf.expand_dims', (['combo_actions', '(0)'], {}), '(combo_actions, 0)\n', (4980, 4998), True, 'import tensorflow as tf\n'), ((5047, 5074), 'numpy.arange', 'np.arange', (['(0)', 'batch_size', '(1)'], {}), '(0, batch_size, 1)\n', (5056, 5074), True, 'import numpy as np\n'), ((5130, 5180), 'tensorflow.slice', 'tf.slice', (['movement_actions', '[0, 0, 0]', '[-1, 1, -1]'], {}), '(movement_actions, [0, 0, 0], [-1, 1, -1])\n', (5138, 5180), True, 'import tensorflow as tf\n'), ((5222, 5272), 'tensorflow.slice', 'tf.slice', (['movement_actions', '[0, 1, 0]', '[-1, 1, -1]'], {}), '(movement_actions, [0, 1, 0], [-1, 1, -1])\n', (5230, 5272), True, 'import tensorflow as tf\n'), ((5313, 5363), 'tensorflow.slice', 'tf.slice', (['movement_actions', '[0, 2, 0]', '[-1, 1, -1]'], {}), '(movement_actions, [0, 2, 0], [-1, 1, -1])\n', (5321, 5363), True, 'import tensorflow as tf\n'), ((9448, 9466), 'tensorflow.name_scope', 'tf.name_scope', (['val'], {}), '(val)\n', (9461, 9466), True, 'import tensorflow as tf\n'), ((11666, 11679), 'tensorflow.abs', 'tf.abs', (['steer'], {}), '(steer)\n', (11672, 11679), True, 'import tensorflow as tf\n'), ((11681, 11692), 'tensorflow.abs', 'tf.abs', (['yaw'], {}), '(yaw)\n', (11687, 11692), True, 'import tensorflow as tf\n'), ((12094, 12118), 'tensorflow.round', 'tf.round', (['(throttle * 1.5)'], {}), '(throttle * 1.5)\n', (12102, 12118), True, 'import tensorflow as tf\n'), ((12586, 12602), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {}), '(1.0)\n', (12597, 12602), True, 'import tensorflow as tf\n'), ((12518, 12534), 'tensorflow.constant', 'tf.constant', (['(2.0)'], {}), '(2.0)\n', (12529, 12534), True, 'import tensorflow as tf\n'), ((12451, 12467), 'tensorflow.constant', 'tf.constant', (['(4.0)'], {}), '(4.0)\n', (12462, 12467), True, 'import tensorflow as tf\n'), ((8563, 8607), 'tensorflow.slice', 'tf.slice', (['tensor', '[total_action_size]', '[val]'], {}), '(tensor, [total_action_size], [val])\n', (8571, 8607), True, 'import tensorflow as tf\n'), ((12224, 12241), 'tensorflow.constant', 'tf.constant', (['(16.0)'], {}), '(16.0)\n', (12235, 12241), True, 'import tensorflow as tf\n'), ((12338, 12354), 'tensorflow.constant', 'tf.constant', (['(8.0)'], {}), '(8.0)\n', (12349, 12354), True, 'import tensorflow as tf\n'), ((8730, 8781), 'tensorflow.slice', 'tf.slice', (['tensor', '[0, total_action_size]', '[-1, val]'], {}), '(tensor, [0, total_action_size], [-1, val])\n', (8738, 8781), True, 'import tensorflow as tf\n'), ((12252, 12281), 'tensorflow.equal', 'tf.equal', (['rounded_throttle', '(1)'], {}), '(rounded_throttle, 1)\n', (12260, 12281), True, 'import tensorflow as tf\n'), ((12365, 12394), 'tensorflow.equal', 'tf.equal', (['rounded_throttle', '(0)'], {}), '(rounded_throttle, 0)\n', (12373, 12394), True, 'import tensorflow as tf\n'), ((8908, 8941), 'tensorflow.slice', 'tf.slice', (['tensor', '[0, i]', '[-1, 1]'], {}), '(tensor, [0, i], [-1, 1])\n', (8916, 8941), True, 'import tensorflow as tf\n')] |
import numpy as np
import cv2
import glob
import pickle
import os
from src.utils import check_dir, save_image
import time
import sys
class CameraCalibration:
def __init__(self, chessboardSize, path):
self.path = path
self.showImages = False
self.chessboardSize = chessboardSize
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(8,5,0)
self.objp = np.zeros((chessboardSize[0] * chessboardSize[1], 3), np.float32)
self.objp[:, :2] = np.mgrid[0:chessboardSize[0], 0:chessboardSize[1]].T.reshape(-1, 2)
def calibrateCamera(self):
calibration_results = os.path.join(self.path + "_results", "calibration_results_pickle.p")
if os.path.exists(calibration_results):
print("calibration results file exists, loading from file.")
ret, mtx, dist, rvecs, tvecs = self.calibrateCameraFromFile(calibration_results)
else:
print("calibration results file does not exist, start calibration from scratch.")
ret, mtx, dist, rvecs, tvecs = self.calibrateCameraFromImages(self.path)
# Only to have a copy for the undistorted chessboard images
from src.undistortion import Undistortion
ud = Undistortion(mtx, dist)
ud.undistortChessboardImages(self.path)
return ret, mtx, dist, rvecs, tvecs
def calibrateCameraFromImages(self, path):
print("Calibrating:")
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d points in image plane.
images = glob.glob(path + "/*")
# setup toolbar
toolbar_width = len(images)
sys.stdout.write("[%s]" % (" " * toolbar_width))
sys.stdout.flush()
sys.stdout.write("\b" * (toolbar_width + 1)) # return to start of line, after '['
# Step through the list and search for chessboard corners
for idx, file_name in enumerate(images):
img = cv2.imread(file_name)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chessboard corners
ret, corners = cv2.findChessboardCorners(gray, self.chessboardSize, None)
# If found, add object points, image points
if ret:
objpoints.append(self.objp)
imgpoints.append(corners) # Draw and display the corners
cv2.drawChessboardCorners(img, self.chessboardSize, corners, ret)
# save image
save_image(img, file_name, path, "corners")
if self.showImages:
cv2.imshow('img', img)
cv2.waitKey(500)
# update the bar
sys.stdout.write("-")
sys.stdout.flush()
sys.stdout.write("]\n") # this ends the progress bar
print("Calibration done. Saving calibration results.")
if self.showImages:
cv2.destroyAllWindows()
# Do camera calibration given object points and image points
img_size = (img.shape[1], img.shape[0])
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size, None, None)
# Save the camera calibration result for later use (we won't worry about rvecs / tvecs)
dist_pickle = {"ret": ret, "mtx": mtx, "dist": dist, "rvecs": rvecs, "tvecs": tvecs}
calibration_file = os.path.join(self.path + "_results", "calibration_results_pickle.p")
check_dir(calibration_file)
pickle.dump(dist_pickle, open(calibration_file, "wb"))
return ret, mtx, dist, rvecs, tvecs
def calibrateCameraFromFile(self, calibration_results):
with open(calibration_results, "rb") as f:
dist_pickle = pickle.load(f)
return dist_pickle["ret"], dist_pickle["mtx"], dist_pickle["dist"], dist_pickle["rvecs"], dist_pickle[
"tvecs"]
| [
"sys.stdout.write",
"cv2.findChessboardCorners",
"src.undistortion.Undistortion",
"cv2.cvtColor",
"cv2.waitKey",
"numpy.zeros",
"os.path.exists",
"cv2.imshow",
"cv2.imread",
"src.utils.check_dir",
"pickle.load",
"sys.stdout.flush",
"src.utils.save_image",
"cv2.calibrateCamera",
"glob.glo... | [((406, 470), 'numpy.zeros', 'np.zeros', (['(chessboardSize[0] * chessboardSize[1], 3)', 'np.float32'], {}), '((chessboardSize[0] * chessboardSize[1], 3), np.float32)\n', (414, 470), True, 'import numpy as np\n'), ((628, 696), 'os.path.join', 'os.path.join', (["(self.path + '_results')", '"""calibration_results_pickle.p"""'], {}), "(self.path + '_results', 'calibration_results_pickle.p')\n", (640, 696), False, 'import os\n'), ((708, 743), 'os.path.exists', 'os.path.exists', (['calibration_results'], {}), '(calibration_results)\n', (722, 743), False, 'import os\n'), ((1570, 1592), 'glob.glob', 'glob.glob', (["(path + '/*')"], {}), "(path + '/*')\n", (1579, 1592), False, 'import glob\n'), ((1662, 1710), 'sys.stdout.write', 'sys.stdout.write', (["('[%s]' % (' ' * toolbar_width))"], {}), "('[%s]' % (' ' * toolbar_width))\n", (1678, 1710), False, 'import sys\n'), ((1719, 1737), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (1735, 1737), False, 'import sys\n'), ((1746, 1792), 'sys.stdout.write', 'sys.stdout.write', (["('\\x08' * (toolbar_width + 1))"], {}), "('\\x08' * (toolbar_width + 1))\n", (1762, 1792), False, 'import sys\n'), ((2753, 2776), 'sys.stdout.write', 'sys.stdout.write', (['"""]\n"""'], {}), "(']\\n')\n", (2769, 2776), False, 'import sys\n'), ((3090, 3153), 'cv2.calibrateCamera', 'cv2.calibrateCamera', (['objpoints', 'imgpoints', 'img_size', 'None', 'None'], {}), '(objpoints, imgpoints, img_size, None, None)\n', (3109, 3153), False, 'import cv2\n'), ((3370, 3438), 'os.path.join', 'os.path.join', (["(self.path + '_results')", '"""calibration_results_pickle.p"""'], {}), "(self.path + '_results', 'calibration_results_pickle.p')\n", (3382, 3438), False, 'import os\n'), ((3447, 3474), 'src.utils.check_dir', 'check_dir', (['calibration_file'], {}), '(calibration_file)\n', (3456, 3474), False, 'from src.utils import check_dir, save_image\n'), ((1247, 1270), 'src.undistortion.Undistortion', 'Undistortion', (['mtx', 'dist'], {}), '(mtx, dist)\n', (1259, 1270), False, 'from src.undistortion import Undistortion\n'), ((1962, 1983), 'cv2.imread', 'cv2.imread', (['file_name'], {}), '(file_name)\n', (1972, 1983), False, 'import cv2\n'), ((2003, 2040), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (2015, 2040), False, 'import cv2\n'), ((2110, 2168), 'cv2.findChessboardCorners', 'cv2.findChessboardCorners', (['gray', 'self.chessboardSize', 'None'], {}), '(gray, self.chessboardSize, None)\n', (2135, 2168), False, 'import cv2\n'), ((2692, 2713), 'sys.stdout.write', 'sys.stdout.write', (['"""-"""'], {}), "('-')\n", (2708, 2713), False, 'import sys\n'), ((2726, 2744), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (2742, 2744), False, 'import sys\n'), ((2910, 2933), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2931, 2933), False, 'import cv2\n'), ((3720, 3734), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3731, 3734), False, 'import pickle\n'), ((2380, 2445), 'cv2.drawChessboardCorners', 'cv2.drawChessboardCorners', (['img', 'self.chessboardSize', 'corners', 'ret'], {}), '(img, self.chessboardSize, corners, ret)\n', (2405, 2445), False, 'import cv2\n'), ((2491, 2534), 'src.utils.save_image', 'save_image', (['img', 'file_name', 'path', '"""corners"""'], {}), "(img, file_name, path, 'corners')\n", (2501, 2534), False, 'from src.utils import check_dir, save_image\n'), ((2591, 2613), 'cv2.imshow', 'cv2.imshow', (['"""img"""', 'img'], {}), "('img', img)\n", (2601, 2613), False, 'import cv2\n'), ((2634, 2650), 'cv2.waitKey', 'cv2.waitKey', (['(500)'], {}), '(500)\n', (2645, 2650), False, 'import cv2\n')] |
import random
import math
import glob
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
import importlib
import helper
def group_data(identifier):
path = os.path.dirname(os.path.abspath(__file__))
if identifier == "all":
dataset_path = path + "\\..\\..\\img\\train_pitch\\"
e1 = glob.glob1(dataset_path+"e1\\", "note-*")
f1 = glob.glob1(dataset_path+"f1\\", "note-*")
g1 = glob.glob1(dataset_path+"g1\\", "note-*")
a1 = glob.glob1(dataset_path+"a1\\", "note-*")
b1 = glob.glob1(dataset_path+"h1\\", "note-*")
c2 = glob.glob1(dataset_path+"c2\\", "note-*")
d2 = glob.glob1(dataset_path+"d2\\", "note-*")
e2 = glob.glob1(dataset_path+"e2\\", "note-*")
f2 = glob.glob1(dataset_path+"f2\\", "note-*")
else:
dataset_path = path + "\\..\\..\\img\\"+ identifier +"\\"
e1 = glob.glob1(dataset_path+"e1\\", "note-" + identifier + "*")
f1 = glob.glob1(dataset_path+"f1\\", "note-" + identifier + "*")
g1 = glob.glob1(dataset_path+"g1\\", "note-" + identifier + "*")
a1 = glob.glob1(dataset_path+"a1\\", "note-" + identifier + "*")
b1 = glob.glob1(dataset_path+"h1\\", "note-" + identifier + "*")
c2 = glob.glob1(dataset_path+"c2\\", "note-" + identifier + "*")
d2 = glob.glob1(dataset_path+"d2\\", "note-" + identifier + "*")
e2 = glob.glob1(dataset_path+"e2\\", "note-" + identifier + "*")
f2 = glob.glob1(dataset_path+"f2\\", "note-" + identifier + "*")
train = [e1, f1, g1, a1, b1, c2, d2, e2, f2]
test_e1 = glob.glob1(dataset_path+"e1\\test\\", "note-" + identifier + "*")
test_f1 = glob.glob1(dataset_path+"f1\\test\\", "note-" + identifier + "*")
test_g1 = glob.glob1(dataset_path+"g1\\test\\", "note-" + identifier + "*")
test_a1 = glob.glob1(dataset_path+"a1\\test\\", "note-" + identifier + "*")
test_b1 = glob.glob1(dataset_path+"h1\\test\\", "note-" + identifier + "*")
test_c2 = glob.glob1(dataset_path+"c2\\test\\", "note-" + identifier + "*")
test_d2 = glob.glob1(dataset_path+"d2\\test\\", "note-" + identifier + "*")
test_e2 = glob.glob1(dataset_path+"e2\\test\\", "note-" + identifier + "*")
test_f2 = glob.glob1(dataset_path+"f2\\test\\", "note-" + identifier + "*")
test = [test_e1, test_f1, test_g1, test_a1, test_b1, test_c2, test_d2, test_e2, test_f2]
return train, test, dataset_path
def group_data_beats():
path = os.path.dirname(os.path.abspath(__file__))
dataset_path = path + "\\..\\..\\img\\train_pitch\\"
subdir = next(os.walk(dataset_path))[1]
whole = list()
half = list()
quarter = list()
for i in range(len(subdir)):
whole.extend(glob.glob1(dataset_path+subdir[i]+"\\", "note-whole*"))
half.extend(glob.glob1(dataset_path+subdir[i]+"\\", "note-half*"))
quarter.extend(glob.glob1(dataset_path+subdir[i]+"\\", "note-quarter*"))
beats = [whole, half, quarter]
test_whole = glob.glob1(dataset_path+"whole\\test\\", "note-whole*")
test_half = glob.glob1(dataset_path+"half\\test\\", "note-half*")
test_quarter = glob.glob1(dataset_path+"quarter\\test\\", "note-quarter*")
test_beats = [test_whole, test_half, test_quarter]
return beats, test_beats, dataset_path
def group_data_test_beats():
path = os.path.dirname(os.path.abspath(__file__))
dataset_path = path + "\\..\\..\\img\\test\\"
whole = glob.glob1(dataset_path, "note-whole*")
half = glob.glob1(dataset_path, "note-half*")
quarter = glob.glob1(dataset_path, "note-quarter*")
beats = [whole, half, quarter]
# print(beats)
return beats, dataset_path
def group_data_test_pitch():
path = os.path.dirname(os.path.abspath(__file__))
dataset_path = path + "\\..\\..\\img\\test\\"
e1 = glob.glob1(dataset_path, "note-*-e1*")
f1 = glob.glob1(dataset_path, "note-*-f1*")
g1 = glob.glob1(dataset_path, "note-*-g1*")
a1 = glob.glob1(dataset_path, "note-*-a1*")
c2 = glob.glob1(dataset_path, "note-*-c2*")
d2 = glob.glob1(dataset_path, "note-*-d2*")
b1 = glob.glob1(dataset_path, "note-*-h1*")
e2 = glob.glob1(dataset_path, "note-*-e2*")
f2 = glob.glob1(dataset_path, "note-*-f2*")
pitch = [e1, f1, g1, a1, b1, c2, d2, e2, f2]
# print(pitch)
return pitch, dataset_path
def create_csv(**kwargs):
identifier = kwargs.get('identifier', "quarter")
if identifier == 'beats':
train_group, test_group, dataset_path = group_data_beats()
else:
train_group, test_group, dataset_path = group_data(identifier)
type = kwargs.get('type', 'all')
extraction = kwargs.get('extraction', 'paranada')
hist_axis = kwargs.get('hist_axis', 'row')
thresh_method = kwargs.get('thresh_method', "gaussian")
if thresh_method == 'mean':
thresh_cv = cv2.ADAPTIVE_THRESH_MEAN_C
else:
thresh_cv = cv2.ADAPTIVE_THRESH_GAUSSIAN_C
max_num_class = kwargs.get('max_num_class', 10)
length_area = kwargs.get('length_area', 5)
if type == 'all' or type == 'train':
if extraction == 'pixel':
extract_pixel(train_group, type, identifier, dataset_path, thresh_cv, max_num_class)
elif extraction == 'histogram':
extract_hist(hist_axis, train_group, type, identifier, dataset_path, thresh_cv, max_num_class)
else:
extract_paranada(train_group, type, identifier, dataset_path, thresh_cv, max_num_class, length_area)
# ===============================================================
if type == 'all' or type == 'test':
if extraction == 'pixel':
extract_pixel(test_group, type, identifier, dataset_path, thresh_cv)
elif extraction == 'histogram':
extract_hist(hist_axis, test_group, type, identifier, dataset_path, thresh_cv, max_num_class)
else:
extract_paranada(test_group, type, identifier, dataset_path, thresh_cv, max_num_class, length_area)
def create_csv_test(**kwargs):
identifier = kwargs.get('identifier', "quarter")
thresh_method = kwargs.get('thresh_method', "gaussian")
if thresh_method == 'mean':
thresh_cv = cv2.ADAPTIVE_THRESH_MEAN_C
else:
thresh_cv = cv2.ADAPTIVE_THRESH_GAUSSIAN_C
max_num_class = kwargs.get('max_num_class', 10)
length_area = kwargs.get('length_area', 5)
test_group, dataset_path = group_data_test_beats()
extract_hist('col', test_group, "test", identifier, dataset_path, thresh_cv, max_num_class)
test_group, dataset_path = group_data_test_pitch()
extract_paranada(test_group, "test", identifier, dataset_path, thresh_cv, max_num_class, length_area)
def extract_pixel(group, type, identifier, dataset_path, thresh_method, max_num_class):
if type == "train":
data = open(type + "_" + identifier + ".csv", "w")
info = open(type +"_"+ identifier +"_info.csv", "w")
else:
data = open(type + "_pixel.csv", "w")
info = open(type + "_pixel_info.csv", "w")
class_column = 0
for note in group:
class_counter = 0
for i in note:
info.write(i + "\n")
img = cv2.imread(dataset_path + i, cv2.IMREAD_GRAYSCALE)
thresh = cv2.adaptiveThreshold(img, 255, thresh_method,
cv2.THRESH_BINARY_INV, 11, 2)
for row in thresh:
for column in row:
data.write(str(column) + ", ")
data.write(str(class_column) + "\n")
class_counter += 1
if class_counter == max_num_class:
break
class_column += 1
data.close()
info.close
def extract_paranada(group, type, identifier, dataset_path, thresh_method, max_num_class, length_area):
if type == "train":
data = open(type + "_" + identifier + ".csv", "w")
info = open(type +"_"+ identifier +"_info.csv", "w")
else:
data = open(type + "_paranada.csv", "w")
info = open(type + "_paranada_info.csv", "w")
class_column = 0
for note in group:
class_counter = 0
for i in note:
img = cv2.imread(dataset_path + i, cv2.IMREAD_GRAYSCALE)
thresh = cv2.adaptiveThreshold(img, 255, thresh_method,
cv2.THRESH_BINARY_INV, 11, 2)
# calculating histogram each row of image
hist = np.sum(thresh == 255, axis=1)
# check the index row of the paranada exist
paranada, group_paranada, paranada_index = detect_paranada(hist, i)
# remove paranada
non_paranada = remove_paranada(paranada, hist)
non_paranada = remove_outlier(non_paranada)
# calculate average of hist (head of notes position)
average = np.mean(hist)
index_area = detect_head(non_paranada, length_area)
info.write(i + "\n")
# print(i)
# print(index_area)
# helper.show_non_paranada_plot(i, hist, non_paranada)
# inserting feature to csv file
for paranada in paranada_index:
data.write(str(paranada) + ", ")
# data.write(str(class_column) + ", ")
data.write(str(index_area) + ", ")
data.write(str(class_column) + "\n")
class_counter += 1
if class_counter == max_num_class:
break
class_column += 1
data.close()
info.close()
def extract_hist(hist_axis, group, type, identifier, dataset_path, thresh_method, max_num_class):
if type == "train":
data = open(type + "_" + identifier + ".csv", "w")
info = open(type +"_"+ identifier +"_info.csv", "w")
else:
data = open(type + "_histogram.csv", "w")
info = open(type + "_histogram_info.csv", "w")
class_column = 0
for note in group:
class_counter = 0
for i in note:
info.write(i + "\n")
img = cv2.imread(dataset_path + i, cv2.IMREAD_GRAYSCALE)
thresh = cv2.adaptiveThreshold(img, 255, thresh_method,
cv2.THRESH_BINARY_INV, 11, 2)
if hist_axis == 'col':
index_axis = 0
else:
index_axis = 1
# calculating histogram each col of image
hist = np.sum(thresh == 255, axis=index_axis)
if hist_axis == 'col':
max = np.max(hist)
hist = min_max_normalize(hist, 0, max)
for c in hist:
data.write(str(c) + ", ")
data.write(str(class_column) + "\n")
class_counter += 1
if class_counter == max_num_class:
break
class_column += 1
data.close()
info.close()
def noise_reduction(img):
# convert all to float64
img = np.float64(img)
# create a noise of variance 25
noise = np.random.randn(*img.shape)*10
# Add this noise to images
noisy = img+noise
# Convert back to uint8
noisy = np.uint8(np.clip(img,0,255))
# Denoise 3rd frame considering all the 5 frames
dst = cv2.fastNlMeansDenoising(noisy)
return dst
def detect_paranada(hist, filename):
mean = np.mean(hist)
std = np.std(hist)
stat_z = [(s-mean)/std for s in hist]
paranada = (np.abs(stat_z) > 2)
indices = [i for i, x in enumerate(paranada) if x == True]
if indices == []:
max_hist = max(hist)
paranada = (np.abs(np.abs(hist - max_hist) <= 2))
indices = [i for i, x in enumerate(paranada) if x == True]
log_message = "WARNING: Failed to get outlier of " + filename
helper.write_log('dataset', '4', log_message)
# helper.show_plot(i, hist, "")
group_paranada = list(helper.split_tol(indices,2))
paranada_index = [i[0] for i in group_paranada]
if len(paranada_index) < 5:
log_message = "FATAL ERROR: Paranada index of " + filename + " is not completely detected"
helper.write_log('dataset', '1', log_message)
print("Something error, please check dataset.log!")
return paranada, group_paranada, paranada_index
def remove_paranada(paranada, hist):
non_paranada = list()
j = 0
for x in paranada:
if x == True:
if j > 0 and j < len(paranada)-1:
if paranada[j+1] == True:
mean = (hist[j-1]+hist[j+2])/2
elif paranada[j-1] == True:
mean = (hist[j-2]+hist[j+1])/2
else:
mean = (hist[j-1]+hist[j+1])/2
elif j == 0:
if paranada[j+1] == True:
mean = hist[j+2]
else:
mean = hist[j+1]
elif j == len(paranada)-1:
if paranada[j-1] == True:
mean = hist[j-2]
else:
mean = hist[j-1]
non_paranada.append(mean)
else :
non_paranada.append(hist[j])
j += 1
return non_paranada
def remove_outlier(data):
mean = np.mean(data)
std = np.std(data)
stat_z = [(s-mean)/std for s in data]
outlier = (np.abs(stat_z) > 2)
return remove_paranada(outlier, data)
def detect_head(hist, length_area):
area = 0
index_area = 0
for c in range(len(hist) - (length_area - 1)):
y_vals = hist[c:c + length_area]
this_area = helper.integrate(y_vals, (length_area - 1))
if area < this_area:
index_area = c + (length_area/2)
area = this_area
return index_area
def min_max_normalize(dataset, min=0, max=100):
data = list()
for i in range(len(dataset)):
data.append(round(((dataset[i] - min) / (max - min)),6))
return data | [
"helper.integrate",
"os.path.abspath",
"helper.write_log",
"numpy.abs",
"numpy.sum",
"numpy.random.randn",
"numpy.std",
"os.walk",
"numpy.clip",
"cv2.adaptiveThreshold",
"cv2.fastNlMeansDenoising",
"cv2.imread",
"numpy.max",
"numpy.mean",
"numpy.float64",
"helper.split_tol",
"glob.gl... | [((1614, 1681), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'e1\\\\test\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'e1\\\\test\\\\', 'note-' + identifier + '*')\n", (1624, 1681), False, 'import glob\n'), ((1694, 1761), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'f1\\\\test\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'f1\\\\test\\\\', 'note-' + identifier + '*')\n", (1704, 1761), False, 'import glob\n'), ((1774, 1841), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'g1\\\\test\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'g1\\\\test\\\\', 'note-' + identifier + '*')\n", (1784, 1841), False, 'import glob\n'), ((1854, 1921), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'a1\\\\test\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'a1\\\\test\\\\', 'note-' + identifier + '*')\n", (1864, 1921), False, 'import glob\n'), ((1934, 2001), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'h1\\\\test\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'h1\\\\test\\\\', 'note-' + identifier + '*')\n", (1944, 2001), False, 'import glob\n'), ((2014, 2081), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'c2\\\\test\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'c2\\\\test\\\\', 'note-' + identifier + '*')\n", (2024, 2081), False, 'import glob\n'), ((2094, 2161), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'd2\\\\test\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'd2\\\\test\\\\', 'note-' + identifier + '*')\n", (2104, 2161), False, 'import glob\n'), ((2174, 2241), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'e2\\\\test\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'e2\\\\test\\\\', 'note-' + identifier + '*')\n", (2184, 2241), False, 'import glob\n'), ((2254, 2321), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'f2\\\\test\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'f2\\\\test\\\\', 'note-' + identifier + '*')\n", (2264, 2321), False, 'import glob\n'), ((3017, 3074), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'whole\\\\test\\\\')", '"""note-whole*"""'], {}), "(dataset_path + 'whole\\\\test\\\\', 'note-whole*')\n", (3027, 3074), False, 'import glob\n'), ((3089, 3144), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'half\\\\test\\\\')", '"""note-half*"""'], {}), "(dataset_path + 'half\\\\test\\\\', 'note-half*')\n", (3099, 3144), False, 'import glob\n'), ((3162, 3223), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'quarter\\\\test\\\\')", '"""note-quarter*"""'], {}), "(dataset_path + 'quarter\\\\test\\\\', 'note-quarter*')\n", (3172, 3223), False, 'import glob\n'), ((3470, 3509), 'glob.glob1', 'glob.glob1', (['dataset_path', '"""note-whole*"""'], {}), "(dataset_path, 'note-whole*')\n", (3480, 3509), False, 'import glob\n'), ((3521, 3559), 'glob.glob1', 'glob.glob1', (['dataset_path', '"""note-half*"""'], {}), "(dataset_path, 'note-half*')\n", (3531, 3559), False, 'import glob\n'), ((3574, 3615), 'glob.glob1', 'glob.glob1', (['dataset_path', '"""note-quarter*"""'], {}), "(dataset_path, 'note-quarter*')\n", (3584, 3615), False, 'import glob\n'), ((3848, 3886), 'glob.glob1', 'glob.glob1', (['dataset_path', '"""note-*-e1*"""'], {}), "(dataset_path, 'note-*-e1*')\n", (3858, 3886), False, 'import glob\n'), ((3896, 3934), 'glob.glob1', 'glob.glob1', (['dataset_path', '"""note-*-f1*"""'], {}), "(dataset_path, 'note-*-f1*')\n", (3906, 3934), False, 'import glob\n'), ((3944, 3982), 'glob.glob1', 'glob.glob1', (['dataset_path', '"""note-*-g1*"""'], {}), "(dataset_path, 'note-*-g1*')\n", (3954, 3982), False, 'import glob\n'), ((3992, 4030), 'glob.glob1', 'glob.glob1', (['dataset_path', '"""note-*-a1*"""'], {}), "(dataset_path, 'note-*-a1*')\n", (4002, 4030), False, 'import glob\n'), ((4040, 4078), 'glob.glob1', 'glob.glob1', (['dataset_path', '"""note-*-c2*"""'], {}), "(dataset_path, 'note-*-c2*')\n", (4050, 4078), False, 'import glob\n'), ((4088, 4126), 'glob.glob1', 'glob.glob1', (['dataset_path', '"""note-*-d2*"""'], {}), "(dataset_path, 'note-*-d2*')\n", (4098, 4126), False, 'import glob\n'), ((4136, 4174), 'glob.glob1', 'glob.glob1', (['dataset_path', '"""note-*-h1*"""'], {}), "(dataset_path, 'note-*-h1*')\n", (4146, 4174), False, 'import glob\n'), ((4184, 4222), 'glob.glob1', 'glob.glob1', (['dataset_path', '"""note-*-e2*"""'], {}), "(dataset_path, 'note-*-e2*')\n", (4194, 4222), False, 'import glob\n'), ((4232, 4270), 'glob.glob1', 'glob.glob1', (['dataset_path', '"""note-*-f2*"""'], {}), "(dataset_path, 'note-*-f2*')\n", (4242, 4270), False, 'import glob\n'), ((11076, 11091), 'numpy.float64', 'np.float64', (['img'], {}), '(img)\n', (11086, 11091), True, 'import numpy as np\n'), ((11356, 11387), 'cv2.fastNlMeansDenoising', 'cv2.fastNlMeansDenoising', (['noisy'], {}), '(noisy)\n', (11380, 11387), False, 'import cv2\n'), ((11453, 11466), 'numpy.mean', 'np.mean', (['hist'], {}), '(hist)\n', (11460, 11466), True, 'import numpy as np\n'), ((11477, 11489), 'numpy.std', 'np.std', (['hist'], {}), '(hist)\n', (11483, 11489), True, 'import numpy as np\n'), ((13336, 13349), 'numpy.mean', 'np.mean', (['data'], {}), '(data)\n', (13343, 13349), True, 'import numpy as np\n'), ((13360, 13372), 'numpy.std', 'np.std', (['data'], {}), '(data)\n', (13366, 13372), True, 'import numpy as np\n'), ((202, 227), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (217, 227), False, 'import os\n'), ((333, 376), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'e1\\\\')", '"""note-*"""'], {}), "(dataset_path + 'e1\\\\', 'note-*')\n", (343, 376), False, 'import glob\n'), ((388, 431), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'f1\\\\')", '"""note-*"""'], {}), "(dataset_path + 'f1\\\\', 'note-*')\n", (398, 431), False, 'import glob\n'), ((443, 486), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'g1\\\\')", '"""note-*"""'], {}), "(dataset_path + 'g1\\\\', 'note-*')\n", (453, 486), False, 'import glob\n'), ((498, 541), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'a1\\\\')", '"""note-*"""'], {}), "(dataset_path + 'a1\\\\', 'note-*')\n", (508, 541), False, 'import glob\n'), ((553, 596), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'h1\\\\')", '"""note-*"""'], {}), "(dataset_path + 'h1\\\\', 'note-*')\n", (563, 596), False, 'import glob\n'), ((608, 651), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'c2\\\\')", '"""note-*"""'], {}), "(dataset_path + 'c2\\\\', 'note-*')\n", (618, 651), False, 'import glob\n'), ((663, 706), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'd2\\\\')", '"""note-*"""'], {}), "(dataset_path + 'd2\\\\', 'note-*')\n", (673, 706), False, 'import glob\n'), ((718, 761), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'e2\\\\')", '"""note-*"""'], {}), "(dataset_path + 'e2\\\\', 'note-*')\n", (728, 761), False, 'import glob\n'), ((773, 816), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'f2\\\\')", '"""note-*"""'], {}), "(dataset_path + 'f2\\\\', 'note-*')\n", (783, 816), False, 'import glob\n'), ((905, 966), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'e1\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'e1\\\\', 'note-' + identifier + '*')\n", (915, 966), False, 'import glob\n'), ((978, 1039), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'f1\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'f1\\\\', 'note-' + identifier + '*')\n", (988, 1039), False, 'import glob\n'), ((1051, 1112), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'g1\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'g1\\\\', 'note-' + identifier + '*')\n", (1061, 1112), False, 'import glob\n'), ((1124, 1185), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'a1\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'a1\\\\', 'note-' + identifier + '*')\n", (1134, 1185), False, 'import glob\n'), ((1197, 1258), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'h1\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'h1\\\\', 'note-' + identifier + '*')\n", (1207, 1258), False, 'import glob\n'), ((1270, 1331), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'c2\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'c2\\\\', 'note-' + identifier + '*')\n", (1280, 1331), False, 'import glob\n'), ((1343, 1404), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'd2\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'd2\\\\', 'note-' + identifier + '*')\n", (1353, 1404), False, 'import glob\n'), ((1416, 1477), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'e2\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'e2\\\\', 'note-' + identifier + '*')\n", (1426, 1477), False, 'import glob\n'), ((1489, 1550), 'glob.glob1', 'glob.glob1', (["(dataset_path + 'f2\\\\')", "('note-' + identifier + '*')"], {}), "(dataset_path + 'f2\\\\', 'note-' + identifier + '*')\n", (1499, 1550), False, 'import glob\n'), ((2504, 2529), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (2519, 2529), False, 'import os\n'), ((3379, 3404), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (3394, 3404), False, 'import os\n'), ((3760, 3785), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (3775, 3785), False, 'import os\n'), ((11140, 11167), 'numpy.random.randn', 'np.random.randn', (['*img.shape'], {}), '(*img.shape)\n', (11155, 11167), True, 'import numpy as np\n'), ((11273, 11293), 'numpy.clip', 'np.clip', (['img', '(0)', '(255)'], {}), '(img, 0, 255)\n', (11280, 11293), True, 'import numpy as np\n'), ((11553, 11567), 'numpy.abs', 'np.abs', (['stat_z'], {}), '(stat_z)\n', (11559, 11567), True, 'import numpy as np\n'), ((11897, 11942), 'helper.write_log', 'helper.write_log', (['"""dataset"""', '"""4"""', 'log_message'], {}), "('dataset', '4', log_message)\n", (11913, 11942), False, 'import helper\n'), ((12014, 12042), 'helper.split_tol', 'helper.split_tol', (['indices', '(2)'], {}), '(indices, 2)\n', (12030, 12042), False, 'import helper\n'), ((12235, 12280), 'helper.write_log', 'helper.write_log', (['"""dataset"""', '"""1"""', 'log_message'], {}), "('dataset', '1', log_message)\n", (12251, 12280), False, 'import helper\n'), ((13435, 13449), 'numpy.abs', 'np.abs', (['stat_z'], {}), '(stat_z)\n', (13441, 13449), True, 'import numpy as np\n'), ((13679, 13720), 'helper.integrate', 'helper.integrate', (['y_vals', '(length_area - 1)'], {}), '(y_vals, length_area - 1)\n', (13695, 13720), False, 'import helper\n'), ((2608, 2629), 'os.walk', 'os.walk', (['dataset_path'], {}), '(dataset_path)\n', (2615, 2629), False, 'import os\n'), ((2751, 2809), 'glob.glob1', 'glob.glob1', (["(dataset_path + subdir[i] + '\\\\')", '"""note-whole*"""'], {}), "(dataset_path + subdir[i] + '\\\\', 'note-whole*')\n", (2761, 2809), False, 'import glob\n'), ((2827, 2884), 'glob.glob1', 'glob.glob1', (["(dataset_path + subdir[i] + '\\\\')", '"""note-half*"""'], {}), "(dataset_path + subdir[i] + '\\\\', 'note-half*')\n", (2837, 2884), False, 'import glob\n'), ((2905, 2965), 'glob.glob1', 'glob.glob1', (["(dataset_path + subdir[i] + '\\\\')", '"""note-quarter*"""'], {}), "(dataset_path + subdir[i] + '\\\\', 'note-quarter*')\n", (2915, 2965), False, 'import glob\n'), ((7236, 7286), 'cv2.imread', 'cv2.imread', (['(dataset_path + i)', 'cv2.IMREAD_GRAYSCALE'], {}), '(dataset_path + i, cv2.IMREAD_GRAYSCALE)\n', (7246, 7286), False, 'import cv2\n'), ((7308, 7384), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['img', '(255)', 'thresh_method', 'cv2.THRESH_BINARY_INV', '(11)', '(2)'], {}), '(img, 255, thresh_method, cv2.THRESH_BINARY_INV, 11, 2)\n', (7329, 7384), False, 'import cv2\n'), ((8248, 8298), 'cv2.imread', 'cv2.imread', (['(dataset_path + i)', 'cv2.IMREAD_GRAYSCALE'], {}), '(dataset_path + i, cv2.IMREAD_GRAYSCALE)\n', (8258, 8298), False, 'import cv2\n'), ((8321, 8397), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['img', '(255)', 'thresh_method', 'cv2.THRESH_BINARY_INV', '(11)', '(2)'], {}), '(img, 255, thresh_method, cv2.THRESH_BINARY_INV, 11, 2)\n', (8342, 8397), False, 'import cv2\n'), ((8528, 8557), 'numpy.sum', 'np.sum', (['(thresh == 255)'], {'axis': '(1)'}), '(thresh == 255, axis=1)\n', (8534, 8557), True, 'import numpy as np\n'), ((8941, 8954), 'numpy.mean', 'np.mean', (['hist'], {}), '(hist)\n', (8948, 8954), True, 'import numpy as np\n'), ((10155, 10205), 'cv2.imread', 'cv2.imread', (['(dataset_path + i)', 'cv2.IMREAD_GRAYSCALE'], {}), '(dataset_path + i, cv2.IMREAD_GRAYSCALE)\n', (10165, 10205), False, 'import cv2\n'), ((10228, 10304), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['img', '(255)', 'thresh_method', 'cv2.THRESH_BINARY_INV', '(11)', '(2)'], {}), '(img, 255, thresh_method, cv2.THRESH_BINARY_INV, 11, 2)\n', (10249, 10304), False, 'import cv2\n'), ((10551, 10589), 'numpy.sum', 'np.sum', (['(thresh == 255)'], {'axis': 'index_axis'}), '(thresh == 255, axis=index_axis)\n', (10557, 10589), True, 'import numpy as np\n'), ((10647, 10659), 'numpy.max', 'np.max', (['hist'], {}), '(hist)\n', (10653, 10659), True, 'import numpy as np\n'), ((11720, 11743), 'numpy.abs', 'np.abs', (['(hist - max_hist)'], {}), '(hist - max_hist)\n', (11726, 11743), True, 'import numpy as np\n')] |
import os
import numpy as np
import torch
from PIL import Image
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
import sys
sys.path.append('./reference/detection')
from engine import train_one_epoch, evaluate
import utils
import transforms as T
"""
image: (H, W)
target: dictionary
boxes (FloatTensor[N, 4]): the coordinates of the N bounding boxes in [x0, y0, x1, y1] format, ranging from 0 to W and 0 to H.
labels (Int64Tensor[N]): the label for each bounding box.
image_id (Int64Tensor[1]): an image identifier. It should be unique between all the images in the dataset, and is used during evaluation.
area (Tensor[N]): The area of the bounding box. This is used during evaluation with the COCO metric, to separate the metric scores between small, medium and large boxes.
iscrowd (UInt8Tensor[N]): instances with iscrowd=True will be ignored during evaluation.
(optionally) masks (UInt8Tensor[N, H, W]): The segmentation masks for each one of the objects
(optionally) keypoints (FloatTensor[N, K, 3]): For each one of the N objects,
it contains the K keypoints in [x, y, visibility] format, defining the object.
visibility=0 means that the keypoint is not visible.
Note that for data augmentation, the notion of flipping a keypoint is dependent on the data representation,
and you should probably adapt references/detection/transforms.py for your new keypoint representation
"""
class PennFudanDataset(object):
def __init__(self, root, transforms):
self.root = root
self.transforms = transforms
# load all image files, sorting them to
# ensure that they are aligned
#self.imgs = list(sorted(os.listdir(os.path.join(root, "PNGImages"))))
#self.masks = list(sorted(os.listdir(os.path.join(root, "PedMasks"))))
self.imgs = sorted(os.listdir(os.path.join(root, "PNGImages")))
self.masks = sorted(os.listdir(os.path.join(root, "PedMasks")))
def __getitem__(self, idx):
# load images ad masks
img_path = os.path.join(self.root, "PNGImages", self.imgs[idx])
mask_path = os.path.join(self.root, "PedMasks", self.masks[idx])
img = Image.open(img_path).convert("RGB")
# note that we haven't converted the mask to RGB,
# because each color corresponds to a different instance
# with 0 being background
mask = Image.open(mask_path)
mask = np.array(mask) # 이미지 모든 위치에 대해서 배경:0, 첫번째 사람:1, 두번째 사람:2, ...으로 저장되어있음.
# instances are encoded as different colors
obj_ids = np.unique(mask) # [0, 1, 2]
# first id is the background, so remove it
obj_ids = obj_ids[1:] # [1, 2]
print('obj_ids', obj_ids)
# split the color-encoded mask into a set
# of binary masks
masks = mask == obj_ids[:, None, None] # 이미지 모든 위치에서 각 인스턴스 id와 비교한다.
print('mask.shape', mask.shape) # (428, 721)
print('masks.shape', masks.shape) # (2, 428, 721)
# get bounding box coordinates for each mask
num_objs = len(obj_ids)
boxes = []
for i in range(num_objs):
pos = np.where(masks[i]) # 2차원 행렬에서 값이 True인 indices 추출
xmin = np.min(pos[1]) # 열에서의 최대, 최소
xmax = np.max(pos[1])
ymin = np.min(pos[0]) # 행에서의 최대, 최소
ymax = np.max(pos[0])
boxes.append([xmin, ymin, xmax, ymax])
boxes = torch.as_tensor(boxes, dtype=torch.float32)
# there is only one class
labels = torch.ones((num_objs,), dtype=torch.int64)
masks = torch.as_tensor(masks, dtype=torch.uint8)
image_id = torch.tensor([idx])
area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])
# suppose all instances are not crowd
iscrowd = torch.zeros((num_objs,), dtype=torch.int64)
target = {}
target["boxes"] = boxes
target["labels"] = labels
target["masks"] = masks
target["image_id"] = image_id
target["area"] = area
target["iscrowd"] = iscrowd
if self.transforms is not None:
img, target = self.transforms(img, target)
return img, target
def __len__(self):
return len(self.imgs)
def get_model_instance_segmentation(num_classes):
# load an instance segmentation model pre-trained pre-trained on COCO
model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
# get number of input features for the classifier
in_features = model.roi_heads.box_predictor.cls_score.in_features
# replace the pre-trained head with a new one
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
# now get the number of input features for the mask classifier
in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels
hidden_layer = 256
# and replace the mask predictor with a new one
model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask,
hidden_layer,
num_classes)
return model
def get_transform(train):
transforms = []
transforms.append(T.ToTensor())
if train:
transforms.append(T.RandomHorizontalFlip(0.5))
return T.Compose(transforms)
def testing_forward_methods():
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
dataset = PennFudanDataset('D:/Datasets/PennFudanPed', get_transform(train=True))
data_loader = torch.utils.data.DataLoader(
dataset, batch_size=1, shuffle=True, num_workers=0,
collate_fn=utils.collate_fn)
# For Training
images,targets = next(iter(data_loader))
images = list(image for image in images)
targets = [{k: v for k, v in t.items()} for t in targets]
output = model(images,targets) # Returns losses and detections
# For inference
model.eval()
x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
predictions = model(x) # Returns predictions
def main():
# train on the GPU or on the CPU, if a GPU is not available
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
# our dataset has two classes only - background and person
num_classes = 2
# use our dataset and defined transformations
dataset = PennFudanDataset('D:/Datasets/PennFudanPed', get_transform(train=True))
dataset_test = PennFudanDataset('D:/Datasets/PennFudanPed', get_transform(train=False))
# split the dataset in train and test set
indices = torch.randperm(len(dataset)).tolist()
dataset = torch.utils.data.Subset(dataset, indices[:-50])
dataset_test = torch.utils.data.Subset(dataset_test, indices[-50:])
# define training and validation data loaders
data_loader = torch.utils.data.DataLoader(
dataset, batch_size=2, shuffle=True, num_workers=0,
collate_fn=utils.collate_fn)
data_loader_test = torch.utils.data.DataLoader(
dataset_test, batch_size=1, shuffle=False, num_workers=0,
collate_fn=utils.collate_fn)
# get the model using our helper function
model = get_model_instance_segmentation(num_classes)
# move model to the right device
model.to(device)
# construct an optimizer
params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr=0.005,
momentum=0.9, weight_decay=0.0005)
# and a learning rate scheduler
lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer,
step_size=3,
gamma=0.1)
# let's train it for 10 epochs
num_epochs = 10
for epoch in range(num_epochs):
# train for one epoch, printing every 10 iterations
train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)
# update the learning rate
lr_scheduler.step()
# evaluate on the test dataset
evaluate(model, data_loader_test, device=device)
print("That's it!")
if __name__ == "__main__":
#main()
testing_forward_methods()
| [
"torchvision.models.detection.faster_rcnn.FastRCNNPredictor",
"torch.optim.lr_scheduler.StepLR",
"torch.device",
"os.path.join",
"numpy.unique",
"sys.path.append",
"torch.ones",
"torch.utils.data.DataLoader",
"torchvision.models.detection.maskrcnn_resnet50_fpn",
"numpy.max",
"torchvision.models.... | [((246, 286), 'sys.path.append', 'sys.path.append', (['"""./reference/detection"""'], {}), "('./reference/detection')\n", (261, 286), False, 'import sys\n'), ((4639, 4706), 'torchvision.models.detection.maskrcnn_resnet50_fpn', 'torchvision.models.detection.maskrcnn_resnet50_fpn', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (4689, 4706), False, 'import torchvision\n'), ((4923, 4966), 'torchvision.models.detection.faster_rcnn.FastRCNNPredictor', 'FastRCNNPredictor', (['in_features', 'num_classes'], {}), '(in_features, num_classes)\n', (4940, 4966), False, 'from torchvision.models.detection.faster_rcnn import FastRCNNPredictor\n'), ((5230, 5292), 'torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', 'MaskRCNNPredictor', (['in_features_mask', 'hidden_layer', 'num_classes'], {}), '(in_features_mask, hidden_layer, num_classes)\n', (5247, 5292), False, 'from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor\n'), ((5597, 5618), 'transforms.Compose', 'T.Compose', (['transforms'], {}), '(transforms)\n', (5606, 5618), True, 'import transforms as T\n'), ((5668, 5737), 'torchvision.models.detection.fasterrcnn_resnet50_fpn', 'torchvision.models.detection.fasterrcnn_resnet50_fpn', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (5720, 5737), False, 'import torchvision\n'), ((5844, 5956), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': '(1)', 'shuffle': '(True)', 'num_workers': '(0)', 'collate_fn': 'utils.collate_fn'}), '(dataset, batch_size=1, shuffle=True,\n num_workers=0, collate_fn=utils.collate_fn)\n', (5871, 5956), False, 'import torch\n'), ((6974, 7021), 'torch.utils.data.Subset', 'torch.utils.data.Subset', (['dataset', 'indices[:-50]'], {}), '(dataset, indices[:-50])\n', (6997, 7021), False, 'import torch\n'), ((7042, 7094), 'torch.utils.data.Subset', 'torch.utils.data.Subset', (['dataset_test', 'indices[-50:]'], {}), '(dataset_test, indices[-50:])\n', (7065, 7094), False, 'import torch\n'), ((7167, 7279), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': '(2)', 'shuffle': '(True)', 'num_workers': '(0)', 'collate_fn': 'utils.collate_fn'}), '(dataset, batch_size=2, shuffle=True,\n num_workers=0, collate_fn=utils.collate_fn)\n', (7194, 7279), False, 'import torch\n'), ((7321, 7439), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset_test'], {'batch_size': '(1)', 'shuffle': '(False)', 'num_workers': '(0)', 'collate_fn': 'utils.collate_fn'}), '(dataset_test, batch_size=1, shuffle=False,\n num_workers=0, collate_fn=utils.collate_fn)\n', (7348, 7439), False, 'import torch\n'), ((7738, 7806), 'torch.optim.SGD', 'torch.optim.SGD', (['params'], {'lr': '(0.005)', 'momentum': '(0.9)', 'weight_decay': '(0.0005)'}), '(params, lr=0.005, momentum=0.9, weight_decay=0.0005)\n', (7753, 7806), False, 'import torch\n'), ((7897, 7963), 'torch.optim.lr_scheduler.StepLR', 'torch.optim.lr_scheduler.StepLR', (['optimizer'], {'step_size': '(3)', 'gamma': '(0.1)'}), '(optimizer, step_size=3, gamma=0.1)\n', (7928, 7963), False, 'import torch\n'), ((2239, 2291), 'os.path.join', 'os.path.join', (['self.root', '"""PNGImages"""', 'self.imgs[idx]'], {}), "(self.root, 'PNGImages', self.imgs[idx])\n", (2251, 2291), False, 'import os\n'), ((2313, 2365), 'os.path.join', 'os.path.join', (['self.root', '"""PedMasks"""', 'self.masks[idx]'], {}), "(self.root, 'PedMasks', self.masks[idx])\n", (2325, 2365), False, 'import os\n'), ((2593, 2614), 'PIL.Image.open', 'Image.open', (['mask_path'], {}), '(mask_path)\n', (2603, 2614), False, 'from PIL import Image\n'), ((2633, 2647), 'numpy.array', 'np.array', (['mask'], {}), '(mask)\n', (2641, 2647), True, 'import numpy as np\n'), ((2777, 2792), 'numpy.unique', 'np.unique', (['mask'], {}), '(mask)\n', (2786, 2792), True, 'import numpy as np\n'), ((3656, 3699), 'torch.as_tensor', 'torch.as_tensor', (['boxes'], {'dtype': 'torch.float32'}), '(boxes, dtype=torch.float32)\n', (3671, 3699), False, 'import torch\n'), ((3753, 3795), 'torch.ones', 'torch.ones', (['(num_objs,)'], {'dtype': 'torch.int64'}), '((num_objs,), dtype=torch.int64)\n', (3763, 3795), False, 'import torch\n'), ((3813, 3854), 'torch.as_tensor', 'torch.as_tensor', (['masks'], {'dtype': 'torch.uint8'}), '(masks, dtype=torch.uint8)\n', (3828, 3854), False, 'import torch\n'), ((3877, 3896), 'torch.tensor', 'torch.tensor', (['[idx]'], {}), '([idx])\n', (3889, 3896), False, 'import torch\n'), ((4037, 4080), 'torch.zeros', 'torch.zeros', (['(num_objs,)'], {'dtype': 'torch.int64'}), '((num_objs,), dtype=torch.int64)\n', (4048, 4080), False, 'import torch\n'), ((5500, 5512), 'transforms.ToTensor', 'T.ToTensor', ([], {}), '()\n', (5510, 5512), True, 'import transforms as T\n'), ((6258, 6281), 'torch.rand', 'torch.rand', (['(3)', '(300)', '(400)'], {}), '(3, 300, 400)\n', (6268, 6281), False, 'import torch\n'), ((6283, 6306), 'torch.rand', 'torch.rand', (['(3)', '(500)', '(400)'], {}), '(3, 500, 400)\n', (6293, 6306), False, 'import torch\n'), ((6488, 6513), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (6511, 6513), False, 'import torch\n'), ((6464, 6484), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (6476, 6484), False, 'import torch\n'), ((6519, 6538), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (6531, 6538), False, 'import torch\n'), ((8236, 8312), 'engine.train_one_epoch', 'train_one_epoch', (['model', 'optimizer', 'data_loader', 'device', 'epoch'], {'print_freq': '(10)'}), '(model, optimizer, data_loader, device, epoch, print_freq=10)\n', (8251, 8312), False, 'from engine import train_one_epoch, evaluate\n'), ((8427, 8475), 'engine.evaluate', 'evaluate', (['model', 'data_loader_test'], {'device': 'device'}), '(model, data_loader_test, device=device)\n', (8435, 8475), False, 'from engine import train_one_epoch, evaluate\n'), ((3367, 3385), 'numpy.where', 'np.where', (['masks[i]'], {}), '(masks[i])\n', (3375, 3385), True, 'import numpy as np\n'), ((3437, 3451), 'numpy.min', 'np.min', (['pos[1]'], {}), '(pos[1])\n', (3443, 3451), True, 'import numpy as np\n'), ((3486, 3500), 'numpy.max', 'np.max', (['pos[1]'], {}), '(pos[1])\n', (3492, 3500), True, 'import numpy as np\n'), ((3521, 3535), 'numpy.min', 'np.min', (['pos[0]'], {}), '(pos[0])\n', (3527, 3535), True, 'import numpy as np\n'), ((3570, 3584), 'numpy.max', 'np.max', (['pos[0]'], {}), '(pos[0])\n', (3576, 3584), True, 'import numpy as np\n'), ((5556, 5583), 'transforms.RandomHorizontalFlip', 'T.RandomHorizontalFlip', (['(0.5)'], {}), '(0.5)\n', (5578, 5583), True, 'import transforms as T\n'), ((2045, 2076), 'os.path.join', 'os.path.join', (['root', '"""PNGImages"""'], {}), "(root, 'PNGImages')\n", (2057, 2076), False, 'import os\n'), ((2119, 2149), 'os.path.join', 'os.path.join', (['root', '"""PedMasks"""'], {}), "(root, 'PedMasks')\n", (2131, 2149), False, 'import os\n'), ((2381, 2401), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (2391, 2401), False, 'from PIL import Image\n')] |
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import numpy as np
try:
xrange
except NameError:
xrange = range
class BinarySage(object):
def __init__(self, filename, ignored_fields=None, num_files=1):
"""
Set up instance variables
"""
# The input galaxy structure:
Galdesc_full = [
('SnapNum' , np.int32),
('Type' , np.int32),
('GalaxyIndex' , np.int64),
('CentralGalaxyIndex' , np.int64),
('SAGEHaloIndex' , np.int32),
('SAGETreeIndex' , np.int32),
('SimulationHaloIndex' , np.int64),
('mergeType' , np.int32),
('mergeIntoID' , np.int32),
('mergeIntoSnapNum' , np.int32),
('dT' , np.float32),
('Pos' , (np.float32, 3)),
('Vel' , (np.float32, 3)),
('Spin' , (np.float32, 3)),
('Len' , np.int32),
('Mvir' , np.float32),
('CentralMvir' , np.float32),
('Rvir' , np.float32),
('Vvir' , np.float32),
('Vmax' , np.float32),
('VelDisp' , np.float32),
('ColdGas' , np.float32),
('StellarMass' , np.float32),
('BulgeMass' , np.float32),
('HotGas' , np.float32),
('EjectedMass' , np.float32),
('BlackHoleMass' , np.float32),
('IntraClusterStars' , np.float32),
('MetalsColdGas' , np.float32),
('MetalsStellarMass' , np.float32),
('MetalsBulgeMass' , np.float32),
('MetalsHotGas' , np.float32),
('MetalsEjectedMass' , np.float32),
('MetalsIntraClusterStars' , np.float32),
('SfrDisk' , np.float32),
('SfrBulge' , np.float32),
('SfrDiskZ' , np.float32),
('SfrBulgeZ' , np.float32),
('DiskRadius' , np.float32),
('Cooling' , np.float32),
('Heating' , np.float32),
('QuasarModeBHaccretionMass' , np.float32),
('TimeOfLastMajorMerger' , np.float32),
('TimeOfLastMinorMerger' , np.float32),
('OutflowRate' , np.float32),
('infallMvir' , np.float32),
('infallVvir' , np.float32),
('infallVmax' , np.float32)
]
_names = [g[0] for g in Galdesc_full]
_formats = [g[1] for g in Galdesc_full]
_galdesc = np.dtype({'names':_names, 'formats':_formats}, align=True)
self.filename = filename
self.num_files = num_files
self.dtype = _galdesc
self.totntrees = None
self.totngals = None
self.ngal_per_tree = None
self.bytes_offset_per_tree = None
if not ignored_fields:
ignored_fields = []
self.ignored_fields = ignored_fields
def __enter__(self):
return self
def read_header(self, fp):
"""
Read the initial header from the LHaloTree binary file
"""
import numpy as np
# Read number of trees in file
totntrees = np.fromfile(fp, dtype=np.int32, count=1)[0]
# Read number of gals in file.
totngals = np.fromfile(fp, dtype=np.int32, count=1)[0]
# Read the number of gals in each tree
ngal_per_tree = np.fromfile(fp, dtype=np.int32, count=totntrees)
self.totntrees = totntrees
self.totngals = totngals
self.ngal_per_tree = ngal_per_tree
# First calculate the bytes size of each tree
bytes_offset_per_tree = ngal_per_tree * self.dtype.itemsize
# then compute the cumulative sum across the sizes to
# get an offset to any tree
# However, tmp here will show the offset to the 0'th
# tree as the size of the 0'th tree. What we want is the
# offset to the 1st tree as the size of the 0'th tree
tmp = bytes_offset_per_tree.cumsum()
# Now assign the cumulative sum of sizes for 0:last-1 (inclusive)
# as the offsets to 1:last
bytes_offset_per_tree[1:-1] = tmp[0:-2]
# And set the offset of the 0'th tree as 0
bytes_offset_per_tree[0] = 0
# Now add the initial offset that we need to get to the
# 0'th tree -- i.e., the size of the headers
header_size = 4 + 4 + totntrees*4
bytes_offset_per_tree[:] += header_size
# Now assign to the instance variable
self.bytes_offset_per_tree = bytes_offset_per_tree
def read_tree(self, treenum, fp=None):
"""
Read a single tree specified by the tree number.
If ``trenum`` is ``None``, all trees are read.
"""
close_file = False
if fp is None:
fp = open(self.filename, "rb")
close_file = True
if self.totntrees is None:
self.read_header(fp)
if treenum is not None:
if treenum < 0 or treenum >= self.totntrees:
msg = "The requested tree index = {0} should be within [0, {2})"\
.format(treenum, self.totntrees)
raise ValueError(msg)
if treenum is not None:
ngal = self.ngal_per_tree[treenum]
else:
ngal = self.totngals
if ngal == 0:
return None
# This assumes sequential reads
tree = np.fromfile(fp, dtype=self.dtype, count=ngal)
# If we had to open up the file, close it.
if close_file:
fp.close()
return tree
def update_metadata(self):
"""
The binary galaxies can be split up over multiple files. In this method, we
iterate over the files and collect info that is spread across them.
"""
self.totntrees_all_files = 0
self.totngals_all_files = 0
self.ngal_per_tree_all_files = []
for file_idx in range(self.num_files):
# Cut off the number at the end of the file.
fname_base = self.filename[:-2]
# Then append this file number.
fname = "{0}_{1}".format(fname_base, file_idx)
# Open and read the header.
with open(fname, "rb") as fp:
self.read_header(fp)
# Then update the global parameters.
self.totntrees_all_files += self.totntrees
self.totngals_all_files += self.totngals
self.ngal_per_tree_all_files.extend(self.ngal_per_tree)
def read_gals(self):
# Initialize an empty array.
gals = np.empty(self.totngals_all_files, dtype=self.dtype)
# Then slice all the galaxies in.
offset = 0
for file_idx in range(self.num_files):
fname_base = self.filename[:-2]
fname = "{0}_{1}".format(fname_base, file_idx)
with open(fname, "rb") as fp:
self.read_header(fp)
gals_file = self.read_tree(None, fp)
gals_this_file = len(gals_file)
gals[offset:offset+gals_this_file] = gals_file
offset += gals_this_file
return gals
def compare_catalogs(fname1, num_files_file1, fname2, num_files_file2, mode, ignored_fields, multidim_fields=None,
rtol=1e-9, atol=5e-5):
"""
Compares two SAGE catalogs exactly
"""
import h5py
# For both modes, the first file will be binary. So lets initialize it.
g1 = BinarySage(fname1, ignored_fields, num_files_file1)
# The second file will be either binary or HDF5.
if mode == "binary-binary":
g2 = BinarySage(fname2, ignored_fields, num_files_file2)
compare_binary_catalogs(g1, g2, rtol, atol)
else:
with h5py.File(fname2, "r") as hdf5_file:
compare_binary_hdf5_catalogs(g1, hdf5_file, multidim_fields,
rtol, atol)
def determine_binary_redshift(fname):
# We assume the file name for the binary file is of the form
# /base/path/<ModelPrefix>_zW.XYZ.
# First pull out the model name fully.
model_name = fname.split("/")[-1]
# Then get the redshift in string form.
redshift_string = model_name.split("z")[-1]
# Cast and return.
redshift = float(redshift_string)
return redshift
def compare_binary_hdf5_catalogs(g1, hdf5_file, multidim_fields, rtol=1e-9,
atol=5e-5, verbose=False):
# We need to first determine the snapshot that corresponds to the redshift we're
# checking. This is because the HDF5 file will contain multiple snapshots of data
# whereas we only passed a single redshift binary file.
binary_redshift = determine_binary_redshift(g1.filename)
_, snap_key = determine_snap_from_binary_z(hdf5_file,
binary_redshift,
verbose=verbose)
# SAGE could have been run in parallel in which the HDF5 master file will have
# multiple core datasets.
ncores = hdf5_file["Header"]["Misc"].attrs["num_cores"]
# Load all the galaxies from all trees in the binary file.
binary_gals = g1.read_tree(None)
# Check that number of galaxies is equal.
ngals_binary = g1.totngals
ngals_hdf5 = determine_num_gals_at_snap(hdf5_file, ncores, snap_key)
if ngals_binary != ngals_hdf5:
print("The binary file had {0} galaxies whereas the HDF5 file had {1} galaxies. "
"We determined that the binary file was at redshift {2} and that the "
"corresponding dataset in the HDF5 file was {3}".format(ngals_binary,
ngals_hdf5, binary_redshift, snap_key))
raise ValueError
# We will key via the binary file because the HDF5 file has some multidimensional
# fields split across mutliple datasets.
dim_names = ["x", "y", "z"]
failed_fields = []
for key in g1.dtype.names:
if key in g1.ignored_fields:
continue
offset = 0
# Create an array to hold all the HDF5 data. This may need to be an Nx3 array...
if key in multidim_fields:
hdf5_data = np.zeros((ngals_hdf5, 3))
else:
hdf5_data = np.zeros((ngals_hdf5))
# Iterate through all the core groups and slice the data into the array.
for core_idx in range(ncores):
core_name = "Core_{0}".format(core_idx)
num_gals_this_file = hdf5_file[core_name][snap_key].attrs["num_gals"]
if key in multidim_fields:
# In the HDF5 file, the fields are named <BaseKey><x/y/z>.
for dim_num, dim_name in enumerate(dim_names):
hdf5_name = "{0}{1}".format(key, dim_name)
data_this_file = hdf5_file[core_name][snap_key][hdf5_name][:]
hdf5_data[offset:offset+num_gals_this_file, dim_num] = data_this_file
else:
data_this_file = hdf5_file[core_name][snap_key][key][:]
hdf5_data[offset:offset+num_gals_this_file] = data_this_file
offset += num_gals_this_file
binary_data = binary_gals[key]
# The two arrays should now have the identical shape. Compare them.
if binary_data.shape != hdf5_data.shape:
print("For field {0}, the shape of the binary and HDF5 data were not "
"identical. The binary data had a shape of {1} and the HDF5 had shape "
"of {2}".format(key, binary_data.shape, hdf5_data.shape))
raise ValueError
return_value = compare_field_equality(binary_data, hdf5_data, key, rtol, atol)
if not return_value:
failed_fields.append(key)
if failed_fields:
print("The following fields failed: {0}".format(failed_fields))
raise ValueError
def determine_num_gals_at_snap(hdf5_file, ncores, snap_key):
num_gals = 0
for core_idx in range(ncores):
core_key = "Core_{0}".format(core_idx)
num_gals += hdf5_file[core_key][snap_key].attrs["num_gals"]
return num_gals
def determine_snap_from_binary_z(hdf5_file, redshift, verbose=False):
hdf5_snap_keys = []
hdf5_redshifts = []
# We're handling the HDF5 master file. Hence let's look at the Core_0 group because
# it's guaranteed to always be present.
for key in hdf5_file["Core_0"].keys():
# We need to be careful here. We have a "Header" group that we don't
# want to count when we're trying to work out the correct snapshot.
if 'Snap' not in key:
continue
hdf5_snap_keys.append(key)
hdf5_redshifts.append(hdf5_file["Core_0"][key].attrs["redshift"])
# Find the snapshot that is closest to the redshift.
z_array = np.array(hdf5_redshifts)
idx = (np.abs(z_array - redshift)).argmin()
snap_key = hdf5_snap_keys[idx]
snap_num = snap_key_to_snap_num(snap_key)
if verbose:
print("Determined Snapshot {0} with Key {1} corresponds to the binary "
"file at redshift {2}".format(snap_num, snap_key, redshift))
return snap_num, snap_key
def snap_key_to_snap_num(snap_key):
"""
Given the name of a snapshot key, finds the associated snapshot number.
This is necessary because the 0th snapshot key may not be snapshot 000 and
there could be missing snapshots. This function searches backwards for a
group of digits that identify the snapshot number. If there are numbers
outside of this cluster they will be disregarded and a warning raised.
For example, if the key is "Snap1_030", the function will return 30 and
issue a warning that there were digits ignored.
Parameters
----------
snap_key: String.
The name of the snapshot key.
Returns
----------
snapnum: Integer.
The snapshot number that corresponds to the snapshot key.
Examples
----------
>>> snap_key_to_snapnum('Snap_018')
18
>>> snap_key_to_snapnum('018_Snap')
18
>>> snap_key_to_snapnum('Sn3p_018')
--WARNING--
For Snapshot key 'Sn3p_018' there were numbers that were not \
clustered together at the end of the key.
We assume the snapshot number corresponding to this key is 18; \
please check that this is correct.
18
"""
snapnum = ""
reached_numbers = None
for letter in reversed(snap_key): # Go backwards through the key.
if letter.isdigit():
if reached_numbers is False and len(snapnum):
print("--WARNING--")
print("For Snapshot key '{0}' there were numbers that were not"
" clustered together at the end of the key.\nWe assume "
"the snapshot number corresponding to this key is {1}; "
"please check that this is correct."
.format(snap_key, int(snapnum[::-1])))
break
# When a number is found, we concatenate it with the others and
# flag that we have encountered a cluster of numbers.
snapnum = "{0}{1}".format(snapnum, letter)
reached_numbers = True
else:
# When we reach something that's not a number, turn flag off.
reached_numbers = False
snapnum = snapnum[::-1] # We searched backwards so flip the string around.
return int(snapnum) # Cast as integer before returning.
def compare_binary_catalogs(g1, g2, rtol=1e-9, atol=5e-5):
if not (isinstance(g1, BinarySage) and
isinstance(g2, BinarySage)):
msg = "Both inputs must be objects the class 'BinarySage'"\
"type(Object1) = {0} type(Object2) = {1}\n"\
.format(type(g1), type(g2))
raise ValueError
# If SAGE we run in parallel, the data is split over multiple files. To ensure
# correct comparisons, sum basic info (such as total number of trees/galaxies)
# across all these files.
g1.update_metadata()
g2.update_metadata()
msg = "Total number of trees must be identical\n"
if g1.totntrees_all_files != g2.totntrees_all_files:
msg += "catalog1 has {0} trees while catalog2 has {1} trees\n"\
.format(g1.totntrees_all_files, g2.totntrees_all_files)
raise ValueError(msg)
msg = "Total number of galaxies must be identical\n"
if g1.totngals_all_files != g2.totngals_all_files:
msg += "catalog1 has {0} galaxies while catalog2 has {1} "\
"galaxies\n".format(g1.totngals_all_files, g2.totngals_all_files)
raise ValueError(msg)
for treenum, (n1, n2) in enumerate(zip(g1.ngal_per_tree_all_files,
g2.ngal_per_tree_all_files)):
msg = "Treenumber {0} should have exactly the same number of "\
"galaxies\n".format(treenum)
if n1 != n2:
msg += "catalog1 has {0} galaxies while catalog2 has {1} "\
"galaxies\n".format(n1, n2)
raise ValueError(msg)
ignored_fields = [a for a in g1.ignored_fields if a in g2.ignored_fields]
failed_fields = []
# Load all the galaxies in from all trees.
gals1 = g1.read_gals()
gals2 = g2.read_gals()
for field in g1.dtype.names:
if field in ignored_fields:
continue
field1 = gals1[field]
field2 = gals2[field]
return_value = compare_field_equality(field1, field2, field, rtol, atol)
if not return_value:
failed_fields.append(field)
if failed_fields:
print("The following fields failed: {0}".format(failed_fields))
raise ValueError
def compare_field_equality(field1, field2, field_name, rtol, atol):
if np.array_equal(field1, field2):
return True
print("A `numpy.array_equal` failed. Attempting a `np.allclose` with rtol={0} "
"and atol={1}\n".format(rtol, atol), file=sys.stderr)
if np.allclose(field1, field2, rtol=rtol, atol=atol):
return True
# If control reaches here, then the arrays are not equal
print("Printing values that were different side-by side\n",
file=sys.stderr)
print("#######################################", file=sys.stderr)
print("# index {0}1 {0}2 Diff".format(field_name),
file=sys.stderr)
# `isclose` is True for all elements of `field1` that are close to the corresponding
# element in `field2`.
bool_mask = np.isclose(field1, field2, rtol=rtol, atol=atol)
bad_field1 = field1[bool_mask == False]
bad_field2 = field2[bool_mask == False]
for idx, (field1_val, field2_val) in enumerate(zip(bad_field1, bad_field2)):
print("{0} {1} {2} {3}".format(idx, field1_val, field2_val,
field1_val-field2_val), file=sys.stderr)
# printed out the offending values
print("------ Found {0} mis-matched values out of a total of {1} "
"------".format(len(bad_field1), len(field1)), file=sys.stderr)
print("#######################################\n", file=sys.stderr)
return False
if __name__ == '__main__':
import argparse
description = "Show differences between two SAGE catalogs"
parser = argparse.ArgumentParser(description=description)
parser.add_argument("file1", metavar="FILE",
help="the basename for the first set of files (say, model1_z0.000)")
parser.add_argument("file2", metavar="FILE",
help="the basename for the second set of files (say, model2_z0.000)")
parser.add_argument("mode", metavar="MODE",
help="Either 'binary-binary' or 'binary-hdf5'.")
parser.add_argument("num_files_file1", metavar="NUM_FILES_FILE1", type=int,
help="Number of files the first file was split over.")
parser.add_argument("num_files_file2", metavar="NUM_FILES_FILE2", type=int,
help="Number of files the second file was split over.")
parser.add_argument("verbose", metavar="verbose", type=bool, default=False,
nargs='?', help="print lots of info messages.")
args = parser.parse_args()
if not (args.mode == "binary-binary" or args.mode == "binary-hdf5"):
print("We only accept comparisons between 'binary-binary' files "
"or 'binary-hdf5' files. Please set the 'mode' argument "
"to one of these options.")
raise ValueError
if args.mode == "binary-hdf5" and args.num_files_file2 > 1:
print("You're comparing a binary with a HDF5 file but are saying "
"the HDF5 file is split over multiple files. This shouldn't "
"be the case; simply specify the master file and set "
"'num_files_file2' to 1.")
raise ValueError
ignored_fields = []
# Some multi-dimensional values (e.g., Position) are saved in multiple datasets for
# the HDF5 file.
multidim_fields = ["Pos", "Vel", "Spin"]
# Tolerance levels for the comparisons.
rtol = 1e-07
atol = 1e-11
if args.verbose:
print("Running sagediff on files {0} and {1} in mode {2}. The first "\
"file was split over {3} files and the second file was split "\
"over {4} files.".format(args.file1, args.file2,
args.mode, args.num_files_file1,
args.num_files_file2))
compare_catalogs(args.file1, args.num_files_file1, args.file2, args.num_files_file2,
args.mode, ignored_fields, multidim_fields, rtol, atol)
print("========================")
print("All tests passed for files {0} and {1}. Yay!".format(args.file1, args.file2))
print("========================")
print("")
| [
"h5py.File",
"numpy.abs",
"argparse.ArgumentParser",
"numpy.fromfile",
"numpy.empty",
"numpy.allclose",
"numpy.dtype",
"numpy.zeros",
"numpy.isclose",
"numpy.array",
"numpy.array_equal"
] | [((13674, 13698), 'numpy.array', 'np.array', (['hdf5_redshifts'], {}), '(hdf5_redshifts)\n', (13682, 13698), True, 'import numpy as np\n'), ((18627, 18657), 'numpy.array_equal', 'np.array_equal', (['field1', 'field2'], {}), '(field1, field2)\n', (18641, 18657), True, 'import numpy as np\n'), ((18835, 18884), 'numpy.allclose', 'np.allclose', (['field1', 'field2'], {'rtol': 'rtol', 'atol': 'atol'}), '(field1, field2, rtol=rtol, atol=atol)\n', (18846, 18884), True, 'import numpy as np\n'), ((19369, 19417), 'numpy.isclose', 'np.isclose', (['field1', 'field2'], {'rtol': 'rtol', 'atol': 'atol'}), '(field1, field2, rtol=rtol, atol=atol)\n', (19379, 19417), True, 'import numpy as np\n'), ((20113, 20161), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'description'}), '(description=description)\n', (20136, 20161), False, 'import argparse\n'), ((3327, 3387), 'numpy.dtype', 'np.dtype', (["{'names': _names, 'formats': _formats}"], {'align': '(True)'}), "({'names': _names, 'formats': _formats}, align=True)\n", (3335, 3387), True, 'import numpy as np\n'), ((4201, 4249), 'numpy.fromfile', 'np.fromfile', (['fp'], {'dtype': 'np.int32', 'count': 'totntrees'}), '(fp, dtype=np.int32, count=totntrees)\n', (4212, 4249), True, 'import numpy as np\n'), ((6247, 6292), 'numpy.fromfile', 'np.fromfile', (['fp'], {'dtype': 'self.dtype', 'count': 'ngal'}), '(fp, dtype=self.dtype, count=ngal)\n', (6258, 6292), True, 'import numpy as np\n'), ((7443, 7494), 'numpy.empty', 'np.empty', (['self.totngals_all_files'], {'dtype': 'self.dtype'}), '(self.totngals_all_files, dtype=self.dtype)\n', (7451, 7494), True, 'import numpy as np\n'), ((3982, 4022), 'numpy.fromfile', 'np.fromfile', (['fp'], {'dtype': 'np.int32', 'count': '(1)'}), '(fp, dtype=np.int32, count=1)\n', (3993, 4022), True, 'import numpy as np\n'), ((4085, 4125), 'numpy.fromfile', 'np.fromfile', (['fp'], {'dtype': 'np.int32', 'count': '(1)'}), '(fp, dtype=np.int32, count=1)\n', (4096, 4125), True, 'import numpy as np\n'), ((8614, 8636), 'h5py.File', 'h5py.File', (['fname2', '"""r"""'], {}), "(fname2, 'r')\n", (8623, 8636), False, 'import h5py\n'), ((11046, 11071), 'numpy.zeros', 'np.zeros', (['(ngals_hdf5, 3)'], {}), '((ngals_hdf5, 3))\n', (11054, 11071), True, 'import numpy as np\n'), ((11110, 11130), 'numpy.zeros', 'np.zeros', (['ngals_hdf5'], {}), '(ngals_hdf5)\n', (11118, 11130), True, 'import numpy as np\n'), ((13710, 13736), 'numpy.abs', 'np.abs', (['(z_array - redshift)'], {}), '(z_array - redshift)\n', (13716, 13736), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import sys, os
sys.path = [os.path.dirname(__file__), os.path.dirname(os.path.dirname(__file__))] + sys.path
from bottle import route, run, response, request, hook
import scipy.stats as st
import numpy as np
from stac import nonparametric_tests as npt
from stac import parametric_tests as pt
from utils import clean_missing_values, evaluate_test
import json
import traceback
def headers(func):
def func_wrapper(*args, **kwargs):
response.content_type = "application/json"
try:
if request.method == "OPTIONS":
return {}
else:
return json.dumps(func(*args, **kwargs))
except Exception as e:
response.status = 400
return json.dumps({"error": str(e), "stack": str(traceback.format_exc())})
return func_wrapper
@hook('after_request')
def enable_cors():
"""
You need to add some headers to each request.
Don't use the wildcard '*' for Access-Control-Allow-Origin in production.
"""
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
@route('/assistant', method=["POST", "OPTIONS"])
@headers
def asssistant():
values = request.json
data = {'n': len(values.values()[0]), 'k': len(values.keys())}
# Paired?
values_clean = clean_missing_values(request.json)
data['paired'] = True if data['n'] == len(values_clean.values()[0]) else False
# Normality?
alpha = 0.1
values_clean = clean_missing_values(request.json, delete_row=False)
_, p_values = map(list, zip(*[st.shapiro(v) for v in values_clean.values()]))
data['normality'] = int(reduce(lambda x,y: x and y, [p_value < alpha for p_value in p_values]))
# Homocedasticity?
_, p_value = st.levene(*values_clean.values())
data['homocedasticity'] = int(p_value < alpha)
data.update(evaluate_test(data))
return data
@route('/binomialsign', method=["POST", "OPTIONS"])
@route('/binomialsign/<alpha:float>', method=["POST", "OPTIONS"])
@headers
def binomialsign(alpha=0.05):
values = clean_missing_values(request.json)
statistic, p_value = npt.binomial_sign_test(values.values()[0], values.values()[1])
result = int(p_value<alpha)
return {"result" : result, "statistic" : statistic, "p_value" : p_value}
@route('/wilcoxon', method=["POST", "OPTIONS"])
@route('/wilcoxon/<alpha:float>', method=["POST", "OPTIONS"])
@headers
def wilcoxon(alpha=0.05):
values = clean_missing_values(request.json)
statistic, p_value = st.wilcoxon(values.values()[0], values.values()[1])
result = int(p_value<alpha)
return {"result" : result, "statistic" : statistic, "p_value" : p_value}
@route('/mannwhitneyu', method=["POST", "OPTIONS"])
@route('/mannwhitneyu/<alpha:float>', method=["POST", "OPTIONS"])
@headers
def mannwhitneyu(alpha=0.05):
values = clean_missing_values(request.json, delete_row=False)
statistic, p_value = st.mannwhitneyu(values.values()[0], values.values()[1], use_continuity="false")
result = int(p_value*2<alpha)
return {"result" : result, "statistic" : statistic, "p_value" : p_value*2}
def ranking(func):
def func_wrapper(alpha=0.05, *args, **kwargs):
response.headers['Access-Control-Allow-Origin'] = '*'
response.content_type = "application/json"
statistic, p_value, rankings, names, comparisons, z_values, adj_p_values = func(*args, **kwargs)
return {
"ranking": {
"statistic": statistic,
"p_value": p_value,
"rankings": rankings,
"names": names,
"result": np.asscalar(p_value < alpha)
},
"post_hoc": {
"comparisons": comparisons,
"statistic": z_values,
"p_value": adj_p_values,
"control": names[0],
"result": [int(adj_p_value < alpha) for adj_p_value in adj_p_values]
}
}
return func_wrapper
@route('/friedman', method=["POST", "OPTIONS"])
@route('/friedman/<alpha:float>', method=["POST", "OPTIONS"])
@route('/friedman/<post_hoc>', method=["POST", "OPTIONS"])
@route('/friedman/<post_hoc>/<control>', method=["POST", "OPTIONS"])
@route('/friedman/<post_hoc>/<alpha:float>', method=["POST", "OPTIONS"])
@route('/friedman/<post_hoc>/<control>/<alpha:float>', method=["POST", "OPTIONS"])
@headers
@ranking
def friedman(alpha=0.05, post_hoc="bonferroni_dunn_test", control=None):
values = clean_missing_values(request.json)
statistic, p_value, rankings, ranking_cmp = npt.friedman_test(*values.values())
rankings, names = map(list, zip(*sorted(zip(rankings, values.keys()), key=lambda t: t[0])))
ranks = {key: ranking_cmp[i] for i,key in enumerate(values.keys())}
if post_hoc.split('_')[-1] == "test":
comparisons, z_values, _, adj_p_values = getattr(npt, post_hoc)(ranks, control)
else:
comparisons, z_values, _, adj_p_values = getattr(npt, post_hoc)(ranks)
return statistic, p_value, rankings, names, comparisons, z_values, adj_p_values
@route('/friedman-aligned-ranks', method=["POST", "OPTIONS"])
@route('/friedman-aligned-ranks/<alpha:float>', method=["POST", "OPTIONS"])
@route('/friedman-aligned-ranks/<post_hoc>', method=["POST", "OPTIONS"])
@route('/friedman-aligned-ranks/<post_hoc>/<control>', method=["POST", "OPTIONS"])
@route('/friedman-aligned-ranks/<post_hoc>/<alpha:float>', method=["POST", "OPTIONS"])
@route('/friedman-aligned-ranks/<post_hoc>/<control>/<alpha:float>', method=["POST", "OPTIONS"])
@headers
@ranking
def friedman_aligned_ranks(alpha=0.05, post_hoc="bonferroni_dunn_test", control=None):
values = clean_missing_values(request.json)
statistic, p_value, rankings, ranking_cmp = npt.friedman_aligned_ranks_test(*values.values())
rankings, names = map(list, zip(*sorted(zip(rankings, values.keys()), key=lambda t: t[0])))
ranks = {key: ranking_cmp[i] for i,key in enumerate(values.keys())}
if post_hoc.split('_')[-1] == "test":
comparisons, z_values, _, adj_p_values = getattr(npt, post_hoc)(ranks, control)
else:
comparisons, z_values, _, adj_p_values = getattr(npt, post_hoc)(ranks)
return statistic, p_value, rankings, names, comparisons, z_values, adj_p_values
@route('/quade', method=["POST", "OPTIONS"])
@route('/quade/<alpha:float>', method=["POST", "OPTIONS"])
@route('/quade/<post_hoc>', method=["POST", "OPTIONS"])
@route('/quade/<post_hoc>/<control>', method=["POST", "OPTIONS"])
@route('/quade/<post_hoc>/<alpha:float>', method=["POST", "OPTIONS"])
@route('/quade/<post_hoc>/<control>/<alpha:float>', method=["POST", "OPTIONS"])
@headers
@ranking
def quade(alpha=0.05, post_hoc="bonferroni_dunn_test", control=None):
values = clean_missing_values(request.json)
statistic, p_value, rankings, ranking_cmp = npt.quade_test(*values.values())
rankings, names = map(list, zip(*sorted(zip(rankings, values.keys()), key=lambda t: t[0])))
ranks = {key: ranking_cmp[i] for i,key in enumerate(values.keys())}
if post_hoc.split('_')[-1] == "test":
comparisons, z_values, _, adj_p_values = getattr(npt, post_hoc)(ranks, control)
else:
comparisons, z_values, _, adj_p_values = getattr(npt, post_hoc)(ranks)
return statistic, p_value, rankings, names, comparisons, z_values, adj_p_values
@route('/shapiro', method=["POST", "OPTIONS"])
@route('/shapiro/<alpha:float>', method=["POST", "OPTIONS"])
@headers
def shapiro(alpha=0.05):
values = clean_missing_values(request.json, delete_row=False)
statistics, p_values = map(list, zip(*[st.shapiro(v) for v in values.values()]))
result = [int(p_value < alpha) for p_value in p_values]
return {"statistic": statistics, "p_value": p_values, "result": result}
@route('/kolmogorov', method=["POST", "OPTIONS"])
@route('/kolmogorov/<alpha:float>', method=["POST", "OPTIONS"])
@headers
def kolmogorov(alpha=0.05):
values = clean_missing_values(request.json, delete_row=False)
statistics, p_values = map(list, zip(*[st.kstest(v, 'norm') for v in values.values()]))
result = [int(p_value < alpha) for p_value in p_values]
return {"statistic": statistics, "p_value": p_values, "result": result}
@route('/agostino', method=["POST", "OPTIONS"])
@route('/agostino/<alpha:float>', method=["POST", "OPTIONS"])
@headers
def agostino(alpha=0.05):
values = clean_missing_values(request.json, delete_row=False)
statistics, p_values = map(list, zip(*[st.normaltest(v) for v in values.values()]))
result = [int(p_value < alpha) for p_value in p_values]
return {"statistic": statistics, "p_value": p_values, "result": result}
@route('/levene', method=["POST", "OPTIONS"])
@route('/levene/<alpha:float>', method=["POST", "OPTIONS"])
@headers
def levene(alpha=0.05):
values = clean_missing_values(request.json, delete_row=False)
statistic, p_value = st.levene(*values.values())
result = int(p_value < alpha)
return {"statistic": statistic, "p_value": p_value, "result": result}
@route('/ttest', method=["POST", "OPTIONS"])
@route('/ttest/<alpha:float>', method=["POST", "OPTIONS"])
@headers
def ttest(alpha=0.05):
values = clean_missing_values(request.json)
statistic, p_value = st.ttest_rel(values.values()[0], values.values()[1])
result = int(p_value < alpha)
return {"statistic": statistic.tolist(), "p_value": p_value, "result": result}
@route('/ttest-ind', method=["POST", "OPTIONS"])
@route('/ttest-ind/<alpha:float>', method=["POST", "OPTIONS"])
@headers
def ttest_ind(alpha=0.05):
values = clean_missing_values(request.json)
statistic, p_value = st.ttest_ind(values.values()[0], values.values()[1])
result = int(p_value < alpha)
return {"statistic": statistic.tolist(), "p_value": p_value, "result": result}
@route('/anova', method=["POST", "OPTIONS"])
@route('/anova/<alpha:float>', method=["POST", "OPTIONS"])
@headers
def anova(alpha=0.05):
values = clean_missing_values(request.json)
statistic, p_value, pivots = pt.anova_test(*values.values())
pivots_cmp = {key: pivots[i] for i,key in enumerate(values.keys())}
comparisons, t_values, _, adj_p_values = pt.bonferroni_test(pivots_cmp, len(values.values()[0]))
return {
"anova": {
"statistic": statistic,
"p_value": p_value,
"result": np.asscalar(p_value < alpha)
},
"post_hoc": {
"comparisons": comparisons,
"statistic": t_values,
"p_value": adj_p_values,
"result": [int(adj_p_value < alpha) for adj_p_value in adj_p_values]
}
}
@route('/anova-within', method=["POST", "OPTIONS"])
@route('/anova-within/<alpha:float>', method=["POST", "OPTIONS"])
@headers
def anova(alpha=0.05):
values = clean_missing_values(request.json)
statistic, p_value, pivots = pt.anova_within_test(*values.values())
pivots_cmp = {key: pivots[i] for i,key in enumerate(values.keys())}
comparisons, t_values, _, adj_p_values = pt.bonferroni_test(pivots_cmp, len(values.values()[0]))
return {
"anova": {
"statistic": statistic,
"p_value": p_value,
"result": np.asscalar(p_value < alpha)
},
"post_hoc": {
"comparisons": comparisons,
"statistic": t_values,
"p_value": adj_p_values,
"result": [int(adj_p_value < alpha) for adj_p_value in adj_p_values]
}
}
if __name__ == '__main__':
run(reloader=True, host='localhost', port=8080, quiet=False)
| [
"bottle.hook",
"scipy.stats.kstest",
"utils.evaluate_test",
"scipy.stats.shapiro",
"scipy.stats.normaltest",
"os.path.dirname",
"bottle.run",
"bottle.route",
"utils.clean_missing_values",
"traceback.format_exc",
"numpy.asscalar"
] | [((854, 875), 'bottle.hook', 'hook', (['"""after_request"""'], {}), "('after_request')\n", (858, 875), False, 'from bottle import route, run, response, request, hook\n'), ((1308, 1355), 'bottle.route', 'route', (['"""/assistant"""'], {'method': "['POST', 'OPTIONS']"}), "('/assistant', method=['POST', 'OPTIONS'])\n", (1313, 1355), False, 'from bottle import route, run, response, request, hook\n'), ((2124, 2174), 'bottle.route', 'route', (['"""/binomialsign"""'], {'method': "['POST', 'OPTIONS']"}), "('/binomialsign', method=['POST', 'OPTIONS'])\n", (2129, 2174), False, 'from bottle import route, run, response, request, hook\n'), ((2176, 2240), 'bottle.route', 'route', (['"""/binomialsign/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/binomialsign/<alpha:float>', method=['POST', 'OPTIONS'])\n", (2181, 2240), False, 'from bottle import route, run, response, request, hook\n'), ((2527, 2573), 'bottle.route', 'route', (['"""/wilcoxon"""'], {'method': "['POST', 'OPTIONS']"}), "('/wilcoxon', method=['POST', 'OPTIONS'])\n", (2532, 2573), False, 'from bottle import route, run, response, request, hook\n'), ((2575, 2635), 'bottle.route', 'route', (['"""/wilcoxon/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/wilcoxon/<alpha:float>', method=['POST', 'OPTIONS'])\n", (2580, 2635), False, 'from bottle import route, run, response, request, hook\n'), ((2913, 2963), 'bottle.route', 'route', (['"""/mannwhitneyu"""'], {'method': "['POST', 'OPTIONS']"}), "('/mannwhitneyu', method=['POST', 'OPTIONS'])\n", (2918, 2963), False, 'from bottle import route, run, response, request, hook\n'), ((2965, 3029), 'bottle.route', 'route', (['"""/mannwhitneyu/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/mannwhitneyu/<alpha:float>', method=['POST', 'OPTIONS'])\n", (2970, 3029), False, 'from bottle import route, run, response, request, hook\n'), ((4229, 4275), 'bottle.route', 'route', (['"""/friedman"""'], {'method': "['POST', 'OPTIONS']"}), "('/friedman', method=['POST', 'OPTIONS'])\n", (4234, 4275), False, 'from bottle import route, run, response, request, hook\n'), ((4277, 4337), 'bottle.route', 'route', (['"""/friedman/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/friedman/<alpha:float>', method=['POST', 'OPTIONS'])\n", (4282, 4337), False, 'from bottle import route, run, response, request, hook\n'), ((4339, 4396), 'bottle.route', 'route', (['"""/friedman/<post_hoc>"""'], {'method': "['POST', 'OPTIONS']"}), "('/friedman/<post_hoc>', method=['POST', 'OPTIONS'])\n", (4344, 4396), False, 'from bottle import route, run, response, request, hook\n'), ((4398, 4465), 'bottle.route', 'route', (['"""/friedman/<post_hoc>/<control>"""'], {'method': "['POST', 'OPTIONS']"}), "('/friedman/<post_hoc>/<control>', method=['POST', 'OPTIONS'])\n", (4403, 4465), False, 'from bottle import route, run, response, request, hook\n'), ((4467, 4538), 'bottle.route', 'route', (['"""/friedman/<post_hoc>/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/friedman/<post_hoc>/<alpha:float>', method=['POST', 'OPTIONS'])\n", (4472, 4538), False, 'from bottle import route, run, response, request, hook\n'), ((4540, 4625), 'bottle.route', 'route', (['"""/friedman/<post_hoc>/<control>/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/friedman/<post_hoc>/<control>/<alpha:float>', method=['POST',\n 'OPTIONS'])\n", (4545, 4625), False, 'from bottle import route, run, response, request, hook\n'), ((5323, 5383), 'bottle.route', 'route', (['"""/friedman-aligned-ranks"""'], {'method': "['POST', 'OPTIONS']"}), "('/friedman-aligned-ranks', method=['POST', 'OPTIONS'])\n", (5328, 5383), False, 'from bottle import route, run, response, request, hook\n'), ((5385, 5459), 'bottle.route', 'route', (['"""/friedman-aligned-ranks/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/friedman-aligned-ranks/<alpha:float>', method=['POST', 'OPTIONS'])\n", (5390, 5459), False, 'from bottle import route, run, response, request, hook\n'), ((5461, 5532), 'bottle.route', 'route', (['"""/friedman-aligned-ranks/<post_hoc>"""'], {'method': "['POST', 'OPTIONS']"}), "('/friedman-aligned-ranks/<post_hoc>', method=['POST', 'OPTIONS'])\n", (5466, 5532), False, 'from bottle import route, run, response, request, hook\n'), ((5534, 5619), 'bottle.route', 'route', (['"""/friedman-aligned-ranks/<post_hoc>/<control>"""'], {'method': "['POST', 'OPTIONS']"}), "('/friedman-aligned-ranks/<post_hoc>/<control>', method=['POST',\n 'OPTIONS'])\n", (5539, 5619), False, 'from bottle import route, run, response, request, hook\n'), ((5617, 5706), 'bottle.route', 'route', (['"""/friedman-aligned-ranks/<post_hoc>/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/friedman-aligned-ranks/<post_hoc>/<alpha:float>', method=['POST',\n 'OPTIONS'])\n", (5622, 5706), False, 'from bottle import route, run, response, request, hook\n'), ((5704, 5804), 'bottle.route', 'route', (['"""/friedman-aligned-ranks/<post_hoc>/<control>/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/friedman-aligned-ranks/<post_hoc>/<control>/<alpha:float>', method=\n ['POST', 'OPTIONS'])\n", (5709, 5804), False, 'from bottle import route, run, response, request, hook\n'), ((6528, 6571), 'bottle.route', 'route', (['"""/quade"""'], {'method': "['POST', 'OPTIONS']"}), "('/quade', method=['POST', 'OPTIONS'])\n", (6533, 6571), False, 'from bottle import route, run, response, request, hook\n'), ((6573, 6630), 'bottle.route', 'route', (['"""/quade/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/quade/<alpha:float>', method=['POST', 'OPTIONS'])\n", (6578, 6630), False, 'from bottle import route, run, response, request, hook\n'), ((6632, 6686), 'bottle.route', 'route', (['"""/quade/<post_hoc>"""'], {'method': "['POST', 'OPTIONS']"}), "('/quade/<post_hoc>', method=['POST', 'OPTIONS'])\n", (6637, 6686), False, 'from bottle import route, run, response, request, hook\n'), ((6688, 6752), 'bottle.route', 'route', (['"""/quade/<post_hoc>/<control>"""'], {'method': "['POST', 'OPTIONS']"}), "('/quade/<post_hoc>/<control>', method=['POST', 'OPTIONS'])\n", (6693, 6752), False, 'from bottle import route, run, response, request, hook\n'), ((6754, 6822), 'bottle.route', 'route', (['"""/quade/<post_hoc>/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/quade/<post_hoc>/<alpha:float>', method=['POST', 'OPTIONS'])\n", (6759, 6822), False, 'from bottle import route, run, response, request, hook\n'), ((6824, 6902), 'bottle.route', 'route', (['"""/quade/<post_hoc>/<control>/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/quade/<post_hoc>/<control>/<alpha:float>', method=['POST', 'OPTIONS'])\n", (6829, 6902), False, 'from bottle import route, run, response, request, hook\n'), ((7594, 7639), 'bottle.route', 'route', (['"""/shapiro"""'], {'method': "['POST', 'OPTIONS']"}), "('/shapiro', method=['POST', 'OPTIONS'])\n", (7599, 7639), False, 'from bottle import route, run, response, request, hook\n'), ((7641, 7700), 'bottle.route', 'route', (['"""/shapiro/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/shapiro/<alpha:float>', method=['POST', 'OPTIONS'])\n", (7646, 7700), False, 'from bottle import route, run, response, request, hook\n'), ((8028, 8076), 'bottle.route', 'route', (['"""/kolmogorov"""'], {'method': "['POST', 'OPTIONS']"}), "('/kolmogorov', method=['POST', 'OPTIONS'])\n", (8033, 8076), False, 'from bottle import route, run, response, request, hook\n'), ((8078, 8140), 'bottle.route', 'route', (['"""/kolmogorov/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/kolmogorov/<alpha:float>', method=['POST', 'OPTIONS'])\n", (8083, 8140), False, 'from bottle import route, run, response, request, hook\n'), ((8478, 8524), 'bottle.route', 'route', (['"""/agostino"""'], {'method': "['POST', 'OPTIONS']"}), "('/agostino', method=['POST', 'OPTIONS'])\n", (8483, 8524), False, 'from bottle import route, run, response, request, hook\n'), ((8526, 8586), 'bottle.route', 'route', (['"""/agostino/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/agostino/<alpha:float>', method=['POST', 'OPTIONS'])\n", (8531, 8586), False, 'from bottle import route, run, response, request, hook\n'), ((8914, 8958), 'bottle.route', 'route', (['"""/levene"""'], {'method': "['POST', 'OPTIONS']"}), "('/levene', method=['POST', 'OPTIONS'])\n", (8919, 8958), False, 'from bottle import route, run, response, request, hook\n'), ((8960, 9018), 'bottle.route', 'route', (['"""/levene/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/levene/<alpha:float>', method=['POST', 'OPTIONS'])\n", (8965, 9018), False, 'from bottle import route, run, response, request, hook\n'), ((9282, 9325), 'bottle.route', 'route', (['"""/ttest"""'], {'method': "['POST', 'OPTIONS']"}), "('/ttest', method=['POST', 'OPTIONS'])\n", (9287, 9325), False, 'from bottle import route, run, response, request, hook\n'), ((9327, 9384), 'bottle.route', 'route', (['"""/ttest/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/ttest/<alpha:float>', method=['POST', 'OPTIONS'])\n", (9332, 9384), False, 'from bottle import route, run, response, request, hook\n'), ((9666, 9713), 'bottle.route', 'route', (['"""/ttest-ind"""'], {'method': "['POST', 'OPTIONS']"}), "('/ttest-ind', method=['POST', 'OPTIONS'])\n", (9671, 9713), False, 'from bottle import route, run, response, request, hook\n'), ((9715, 9776), 'bottle.route', 'route', (['"""/ttest-ind/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/ttest-ind/<alpha:float>', method=['POST', 'OPTIONS'])\n", (9720, 9776), False, 'from bottle import route, run, response, request, hook\n'), ((10059, 10102), 'bottle.route', 'route', (['"""/anova"""'], {'method': "['POST', 'OPTIONS']"}), "('/anova', method=['POST', 'OPTIONS'])\n", (10064, 10102), False, 'from bottle import route, run, response, request, hook\n'), ((10104, 10161), 'bottle.route', 'route', (['"""/anova/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/anova/<alpha:float>', method=['POST', 'OPTIONS'])\n", (10109, 10161), False, 'from bottle import route, run, response, request, hook\n'), ((10933, 10983), 'bottle.route', 'route', (['"""/anova-within"""'], {'method': "['POST', 'OPTIONS']"}), "('/anova-within', method=['POST', 'OPTIONS'])\n", (10938, 10983), False, 'from bottle import route, run, response, request, hook\n'), ((10985, 11049), 'bottle.route', 'route', (['"""/anova-within/<alpha:float>"""'], {'method': "['POST', 'OPTIONS']"}), "('/anova-within/<alpha:float>', method=['POST', 'OPTIONS'])\n", (10990, 11049), False, 'from bottle import route, run, response, request, hook\n'), ((1519, 1553), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {}), '(request.json)\n', (1539, 1553), False, 'from utils import clean_missing_values, evaluate_test\n'), ((1694, 1746), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {'delete_row': '(False)'}), '(request.json, delete_row=False)\n', (1714, 1746), False, 'from utils import clean_missing_values, evaluate_test\n'), ((2293, 2327), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {}), '(request.json)\n', (2313, 2327), False, 'from utils import clean_missing_values, evaluate_test\n'), ((2684, 2718), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {}), '(request.json)\n', (2704, 2718), False, 'from utils import clean_missing_values, evaluate_test\n'), ((3082, 3134), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {'delete_row': '(False)'}), '(request.json, delete_row=False)\n', (3102, 3134), False, 'from utils import clean_missing_values, evaluate_test\n'), ((4726, 4760), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {}), '(request.json)\n', (4746, 4760), False, 'from utils import clean_missing_values, evaluate_test\n'), ((5918, 5952), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {}), '(request.json)\n', (5938, 5952), False, 'from utils import clean_missing_values, evaluate_test\n'), ((7004, 7038), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {}), '(request.json)\n', (7024, 7038), False, 'from utils import clean_missing_values, evaluate_test\n'), ((7748, 7800), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {'delete_row': '(False)'}), '(request.json, delete_row=False)\n', (7768, 7800), False, 'from utils import clean_missing_values, evaluate_test\n'), ((8191, 8243), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {'delete_row': '(False)'}), '(request.json, delete_row=False)\n', (8211, 8243), False, 'from utils import clean_missing_values, evaluate_test\n'), ((8635, 8687), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {'delete_row': '(False)'}), '(request.json, delete_row=False)\n', (8655, 8687), False, 'from utils import clean_missing_values, evaluate_test\n'), ((9065, 9117), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {'delete_row': '(False)'}), '(request.json, delete_row=False)\n', (9085, 9117), False, 'from utils import clean_missing_values, evaluate_test\n'), ((9430, 9464), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {}), '(request.json)\n', (9450, 9464), False, 'from utils import clean_missing_values, evaluate_test\n'), ((9826, 9860), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {}), '(request.json)\n', (9846, 9860), False, 'from utils import clean_missing_values, evaluate_test\n'), ((10207, 10241), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {}), '(request.json)\n', (10227, 10241), False, 'from utils import clean_missing_values, evaluate_test\n'), ((11095, 11129), 'utils.clean_missing_values', 'clean_missing_values', (['request.json'], {}), '(request.json)\n', (11115, 11129), False, 'from utils import clean_missing_values, evaluate_test\n'), ((11855, 11915), 'bottle.run', 'run', ([], {'reloader': '(True)', 'host': '"""localhost"""', 'port': '(8080)', 'quiet': '(False)'}), "(reloader=True, host='localhost', port=8080, quiet=False)\n", (11858, 11915), False, 'from bottle import route, run, response, request, hook\n'), ((51, 76), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (66, 76), False, 'import sys, os\n'), ((2080, 2099), 'utils.evaluate_test', 'evaluate_test', (['data'], {}), '(data)\n', (2093, 2099), False, 'from utils import clean_missing_values, evaluate_test\n'), ((94, 119), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (109, 119), False, 'import sys, os\n'), ((10620, 10648), 'numpy.asscalar', 'np.asscalar', (['(p_value < alpha)'], {}), '(p_value < alpha)\n', (10631, 10648), True, 'import numpy as np\n'), ((11515, 11543), 'numpy.asscalar', 'np.asscalar', (['(p_value < alpha)'], {}), '(p_value < alpha)\n', (11526, 11543), True, 'import numpy as np\n'), ((3863, 3891), 'numpy.asscalar', 'np.asscalar', (['(p_value < alpha)'], {}), '(p_value < alpha)\n', (3874, 3891), True, 'import numpy as np\n'), ((1781, 1794), 'scipy.stats.shapiro', 'st.shapiro', (['v'], {}), '(v)\n', (1791, 1794), True, 'import scipy.stats as st\n'), ((7844, 7857), 'scipy.stats.shapiro', 'st.shapiro', (['v'], {}), '(v)\n', (7854, 7857), True, 'import scipy.stats as st\n'), ((8287, 8307), 'scipy.stats.kstest', 'st.kstest', (['v', '"""norm"""'], {}), "(v, 'norm')\n", (8296, 8307), True, 'import scipy.stats as st\n'), ((8731, 8747), 'scipy.stats.normaltest', 'st.normaltest', (['v'], {}), '(v)\n', (8744, 8747), True, 'import scipy.stats as st\n'), ((793, 815), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (813, 815), False, 'import traceback\n')] |
# A Graphical Visualization of Chess Openings
# April 2020
# Provides a colorful multi-level pie chart which shows the popularity of openings after moves
# For more info, go to www.github.com/Destaq/chess_graph
import plotly.graph_objects as go
from collections import Counter
import new_parser
import find_opening
import pandas as pd
import numpy as np
def form_values(gammme, depth, fragmentation_percentage, should_defragment, custom_branching, color, name):
"""Create parent, id, labels, and values """
lst, ratios, kick_depth = new_parser.parse_games(gammme, depth, custom_branching, color, name) #whether or not to implement custom branching
firstx = [
lst[i][:depth+kick_depth] for i in range(len(lst))
] # probably unneeded but for safety's sake...
all_level_moves, exclude_first_moves = [], [] # for parent/labels later
counter = kick_depth
holder = [firstx[i][0] for i in range(len(firstx))]
holder = dict(Counter(holder))
percentage_holder, firstmove = [], []
while counter < depth + kick_depth:
counter += 1
othermove = list(
Counter([tuple(firstx[i][kick_depth:counter]) for i in range(len(lst))]).items()
)
all_level_moves.append(othermove)
exclude_first_moves.append(
othermove
) # obviously excluding first moves (for parent creation)
pz = []
true_ids = [] # the ids, that is
parents = []
labels = []
for i in range(len(all_level_moves)):
if i == 0:
true_ids = [
all_level_moves[0][r][0] for r in range(len(all_level_moves[0]))
] # special ids for original parents
true_ids = [
item for sublist in true_ids for item in sublist
] # functions perfectly
labels += [
all_level_moves[i][f][0][0] for f in range(len(all_level_moves[i]))
] # similar to hackerrank diagonal
firstcount = len(labels)
else:
labels += [
all_level_moves[i][f][0][i] for f in range(len(all_level_moves[i]))
] # similar to hackerrank diagonal
true_ids += [
all_level_moves[i][r][0] for r in range(len(all_level_moves[i]))
]
parents += [
all_level_moves[i][r][0][: len(all_level_moves[i][r][0]) - 1]
for r in range(len(all_level_moves[i]))
]
pz += [z[0][:i] for ply_depth in exclude_first_moves for z in ply_depth]
parents = [""] * firstcount + parents # flattening
ids = true_ids
values = [i[1] for i in firstmove] + [
i[1] for move in exclude_first_moves for i in move
]
game_count = 0
for i in range(len(values)):
if parents[i] == "":
game_count += values[i]
for i in range(len(values)): # e.g e6 has 50, parent e4, with value 100
if parents[i] != "": # each child has parent, this one is e4 so yes
parent_id = parents[i] # parent id = e4
aka = list(parent_id)
if len(aka) >= 2:
aka = tuple(aka)
else:
aka = "".join(aka)
parent_value = ids.index(aka)
parent_value = values[parent_value]
complete_value = round((values[i] / parent_value) * 100, 2)
percentage_holder.append(complete_value)
else:
complete_value = round((values[i] / game_count) * 100, 2)
percentage_holder.append(complete_value)
num_games = 0
for i in range(len(parents)):
if parents[i] == '':
num_games+=values[i]
if should_defragment == True:
del_list = []
for i in range(len(values)):
if values[i]/num_games <= fragmentation_percentage:
del_list.append(i)
percentage_holder = [percentage_holder[i] for i in range(len(percentage_holder)) if i not in del_list]
ids = [ids[i] for i in range(len(ids)) if i not in del_list]
labels = [labels[i] for i in range(len(labels)) if i not in del_list]
parents = [parents[i] for i in range(len(parents)) if i not in del_list]
values = [values[i] for i in range(len(values)) if i not in del_list]
return ids, labels, parents, values, percentage_holder, lst, ratios, kick_depth
# fig = form(ids, labels, parents, values, full_ratios, full_ratios, percentage_everything, hovertip_openings, shade)
def form(ids, labels, parents, values, colors, ratios, percentage_everything, hovertip_openings, shade):
if shade:
fig = go.Figure(
go.Sunburst(
ids=ids,
labels=labels,
parents=parents,
values=values,
marker = dict(
colors = colors,
colorscale = 'Greys_r',
colorbar = dict(
thickness = 20,
title = dict(
text = 'White/Black Winning Percentage',
side = 'right'
)
)
),
leaf = {
'opacity': 1.0
},
branchvalues="total", # if children exceed parent, graph will crash and not show
insidetextorientation="horizontal", # text displays PP
hovertext=[
str(percentage_everything[i])
+ "% of Parent<br>Game Count: "
+ str(values[i])
+ '<br>Opening: '
+ hovertip_openings[i]
+ '<br>W/B Winning Percentage: ' # Note: this is wins+1/2draws/wins+losses+draws
+ str(ratios[i])
for i in range(len(percentage_everything))
],
hovertemplate="%{hovertext}<extra></extra>",
)
)
fig.update_layout(
margin=dict(t=30, l=30, r=30, b=0),
title = {
'text': "The Chess Opening Graph",
'xanchor': 'center',
'y':0.995,
'x':0.4715,
'yanchor': 'top',
'font': {
'size': 25
}
})
else:
fig = go.Figure(
go.Sunburst(
ids=ids,
labels=labels,
parents=parents,
values=values,
leaf = {
'opacity': 1.0
},
branchvalues="total", # if children exceed parent, graph will crash and not show
insidetextorientation="horizontal", # text displays PP
hovertext=[
str(percentage_everything[i])
+ "% of Parent<br>Game Count: "
+ str(values[i])
+ '<br>Opening: '
+ hovertip_openings[i]
+ '<br>W/B Winning Percentage: ' # Note: this is wins+1/2draws/wins+losses+draws
+ str(ratios[i])
for i in range(len(percentage_everything))
],
hovertemplate="%{hovertext}<extra></extra>",
)
)
fig.update_layout(
margin=dict(t=30, l=30, r=30, b=0),
title = {
'text': "The Chess Opening Graph",
'xanchor': 'center',
'y':0.995,
'x':0.50,
'yanchor': 'top',
'font': {
'size': 25
}
})
return fig #nasty thing should be fixed by autopep8
def find_colors(ids, ratios, lst, kick_depth):
holder = []
for i in range(len(ids)):
if type(ids[i]) != str:
holder.append(list(ids[i]))
else:
holder.append(list(ids[i].split(' ')))
lst = [lst[i][kick_depth:] for i in range(len(lst))]
white_list = [0]*len(holder)
black_list = [0]*len(holder)
draw_list = [0]*len(holder)
for i in range(len(holder)):
a = len(holder[i])
for r in range(len(lst)):
if lst[r][:a] == holder[i]:
if ratios[r] == '1-0':
white_list[i] += 1
elif ratios[r] == '0-1':
black_list[i] += 1
else:
draw_list[i] += 1
full_ratios = []
for i in range(len(white_list)):
result = round((white_list[i]+draw_list[i])/(black_list[i]+white_list[i]+draw_list[i]+draw_list[i]), 3)
full_ratios.append(result)
return full_ratios
def best_worst(ids, labels, parents, values, percentage_everything, full_ratios, min_games_best_lines):
df = pd.DataFrame()
df['ids'] = ids
df['labels'] = labels
df['parents'] = parents
df['values'] = values
df['percentage_everything'] = percentage_everything
df['full_ratios'] = full_ratios
def semimove_number(l):
a=len(l.parents)+1
return a
tmp = df.apply(semimove_number, axis=1)
tmp = tmp.to_frame()
tmp.columns = ['semimove']
df['semimove'] = tmp['semimove']
best_worst = pd.DataFrame(columns=['move', 'Best', 'b_score', 'b_games', 'Worst', 'w_score', 'w_games'])
for i in np.unique(df.semimove):
semimove_df = df[(df.semimove == i) & (df['values'] >= min_games_best_lines)]
if (len(semimove_df) > 0):
semimove_df = semimove_df.sort_values('full_ratios', ascending=False)
best = semimove_df.head(1)
worst = semimove_df.tail(1)
move = semimove_df.semimove.values[0]
Best = best['ids'].values[0]
b_score = best['full_ratios'].values[0]
b_games = best['values'].values[0]
Worst = worst['ids'].values[0]
w_score = worst['full_ratios'].values[0]
w_games = worst['values'].values[0]
best_worst.loc[len(best_worst)] = [move, Best, b_score, b_games, Worst, w_score, w_games]
else:
out_warning = 'No lines at move ' + str(i) + ' with at least ' + str(min_games_best_lines) + ' games'
print(out_warning)
print('\n')
best_worst.set_index('move')
print(best_worst)
print('\n')
def graph(database, depth=5, shade = True, fragmentation_percentage=0.0032, should_defragment=False, custom_branching=False, should_download = False, download_format = 'png', download_name = 'fig1', color = 'both', name = '', print_best_lines=False, min_games_best_lines=1): # need file path, depth,
ids, labels, parents, values, percentage_everything, lst, ratios, kick_depth = form_values(database, depth, fragmentation_percentage, should_defragment, custom_branching, color, name) # a good value is about 10x the smallest value
full_ratios = find_colors(ids, ratios, lst, kick_depth)
eco_codes, eco_names, eco_positions = find_opening.create_openings()
hovertip_openings = []
for i in range(len(ids)):
if ids[i] in eco_positions:
analyzed = eco_positions.index(ids[i])
hovertip_openings.append(eco_names[analyzed])
else:
hovertip_openings.append('Non-ECO Opening')
fig = form(ids, labels, parents, values, full_ratios, full_ratios, percentage_everything, hovertip_openings, shade)
fig.show()
def download(format, name = 'fig1'):
fig.write_image(name+'.'+format)
def download_html(name = 'fig1'):
fig.write_html(name+'.html')
static_download_formats = ['png', 'jpeg', 'svg', 'pdf', 'jpg', 'webp']
if should_download == True:
if download_format in static_download_formats:
download(download_format, download_name)
else:
download_html(download_name)
if print_best_lines == True:
best_worst(ids, labels, parents, values, percentage_everything, full_ratios, min_games_best_lines)
| [
"pandas.DataFrame",
"new_parser.parse_games",
"collections.Counter",
"find_opening.create_openings",
"numpy.unique"
] | [((548, 616), 'new_parser.parse_games', 'new_parser.parse_games', (['gammme', 'depth', 'custom_branching', 'color', 'name'], {}), '(gammme, depth, custom_branching, color, name)\n', (570, 616), False, 'import new_parser\n'), ((9006, 9020), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (9018, 9020), True, 'import pandas as pd\n'), ((9457, 9552), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['move', 'Best', 'b_score', 'b_games', 'Worst', 'w_score', 'w_games']"}), "(columns=['move', 'Best', 'b_score', 'b_games', 'Worst',\n 'w_score', 'w_games'])\n", (9469, 9552), True, 'import pandas as pd\n'), ((9563, 9585), 'numpy.unique', 'np.unique', (['df.semimove'], {}), '(df.semimove)\n', (9572, 9585), True, 'import numpy as np\n'), ((11218, 11248), 'find_opening.create_openings', 'find_opening.create_openings', ([], {}), '()\n', (11246, 11248), False, 'import find_opening\n'), ((966, 981), 'collections.Counter', 'Counter', (['holder'], {}), '(holder)\n', (973, 981), False, 'from collections import Counter\n')] |
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
import numpy as np
es = Elasticsearch(['localhost'],port=9200)
label_fields = ["title"]
fields = ["title","cast","country","description"]
weight_fields =["title^2","cast^1","country^1","description^3"]
label_id =[]
Similarity_score=[]
Similarity_id = []
Similarity_title = []
Similarity_name =[]
tmp_precision =0
tmp_recall =0
tmp_f_measure =0
w_tmp_precision =0
w_tmp_recall =0
w_tmp_f_measure =0
Ag_precision = []
Ag_recall = []
Ag_f_measure = []
W_Ag_precision = []
W_Ag_recall = []
W_Ag_f_measure =[]
def label(index,label_query,label_fields):
label_id=[]
s = Search(using=es, index=index)
results = s.query("simple_query_string", query=label_query, fields=label_fields,
auto_generate_synonyms_phrase_query=True).execute()
for hit in results:
label_id.append(hit.meta.id)
# print('This is label_id:', label_id)
return label_id
def Similarity_module(index,query,fields):
Similarity_score=[]
Similarity_id =[]
Similarity_title = []
s = Search(using=es, index=index)
results = s.query("simple_query_string", query=query, fields=fields,
auto_generate_synonyms_phrase_query=True).execute()
for hit in results:
Similarity_score.append(hit.meta.score)
Similarity_id.append(hit.meta.id)
Similarity_title.append(hit.title)
# print('This is Similarity_score:', Similarity_score)
# print('This is Similarity_id:', Similarity_id)
Similarity_score = score_normalized(Similarity_score)
return Similarity_score,Similarity_id,Similarity_title
def Similarity_module_weight(index,query,weight_fields):
Similarity_score=[]
Similarity_id =[]
Similarity_title = []
s = Search(using=es, index=index)
results = s.query("simple_query_string", query=query, fields=weight_fields,
auto_generate_synonyms_phrase_query=True).execute()
for hit in results:
Similarity_score.append(hit.meta.score)
Similarity_id.append(hit.meta.id)
Similarity_title.append(hit.title)
# print('This is Similarity_score:', Similarity_score)
# print('This is Similarity_id:', Similarity_id)
Similarity_score=score_normalized(Similarity_score)
return Similarity_score,Similarity_id,Similarity_title
def cal_rec_pre(label_id,search_id):
tmp = [val for val in label_id if val in search_id]
precision = len(tmp) / len(label_id)
recall = len(tmp) / len(search_id)
print(precision)
print(recall)
f_measure = (2*precision*recall)/(precision+recall)
return precision,recall,f_measure
def score_normalized(Similarity_score):
normalize_score = []
min_score = min(Similarity_score)
max_score = max(Similarity_score)
for i in range(len(Similarity_score)):
normalize_score.append((Similarity_score[i]-min_score)/(max_score-min_score))
return normalize_score
def Kendall_rank_correlation(model1,model2,query,fields):
model1_score,model1_id,_=Similarity_module(model1,query,fields)
model2_score, model2_id,_ = Similarity_module(model2, query, fields)
Same_results = [val for val in model1_id if val in model2_id]
N = len(model1_id)
C = len(Same_results)
D = N - 2 * C
tau = (C - D) / (N * (N+1) / 2)
return tau
def rank_combination(query,index,fields):
score = []
id = []
name = []
rank = []
for i in range(len(index)):
_, Similarity_id, Similarity_name = Similarity_module(index[i], query, fields)
rank += [1,2,3,4,5,6,7,8,9,10]
id += Similarity_id
name += Similarity_name
# print(id)
id_unique = sorted(set(id), key=id.index)
rank_unique = []
name_unique = sorted(set(name), key=name.index)
sum_rank = 0
for j in range (len(id_unique)):
location = [i for i, a in enumerate(id) if a == id_unique[j]]
for k in range(len(location)):
sum_rank = sum_rank + rank[location[k]]
avg_rank = sum_rank/len(location)
rank_unique.append(float(avg_rank))
sum_rank = 0
rank_unique = np.array(rank_unique, dtype=np.float32)
id_unique = np.array(id_unique, dtype=np.int32)
name_unique = np.array(name_unique)
rank_unique = rank_unique[np.argsort(rank_unique)]
id_unique = id_unique[np.argsort(rank_unique)]
name_unique = name_unique[np.argsort(rank_unique)]
rank_id_name = np.array([rank_unique,id_unique,name_unique])
# print(rank_id_name[:, 0:10])
return rank_id_name[:, 0:10]
def socre_combination(query, index, fields):
score = []
id = []
name = []
for i in range(len(index)):
Similarity_score, Similarity_id, Similarity_name = Similarity_module(index[i], query, fields)
score += Similarity_score
id += Similarity_id
name += Similarity_name
id_unique = sorted(set(id), key=id.index)
score_unique = []
name_unique = sorted(set(name),key=name.index)
sum_score = 0
for j in range(len(id_unique)):
location = [i for i, a in enumerate(id) if a == id_unique[j]]
for k in range(len(location)):
sum_score = sum_score + score[location[k]]
avg_score = sum_score / len(location)
score_unique.append(float(avg_score))
sum_score = 0
score_unique = np.array(score_unique, dtype=np.float32)
id_unique = np.array(id_unique,dtype=np.int32)
name_unique = np.array(name_unique)
score_unique = score_unique[np.argsort(-score_unique)]
id_unique=id_unique[np.argsort(-score_unique)]
name_unique =name_unique[np.argsort(-score_unique)]
score_id_name = np.array([score_unique, id_unique, name_unique])
# print(score_id_name)
return score_id_name[:, 0:10]
if __name__ == '__main__':
print("----------------------")
label_query = ['Kr<NAME> and Baltiboy', 'Rings Lord', 'transformers', 'The Matrix', 'Star Trek', 'Vampire',
'spider man', 'Rocky', 'Avengers', 'Indiana Jones']
query = ['which series of Krish Trish Baloy is about India',
'Lord of the Rings about going to Mordor to destroy Rings',
'Transformers beat Megatron',
'The matrix is about protecting Zion',
'Star ship explore new space',
'Boy and his sister meet the vampire every night',
'The spider man collection of parallel universes',
'Rocky fights with former Soviet soldiers',
'Avengers against thanos who has infinite stones',
'Indiana Jones tries to find Ark of Covenant']
index = ['bm25netflix', 'dfinetflix','ibnetflix','dfrnetflix','lmjnetflix','tfidfnetflix','lmdnetflix']
for i in range(len(index)):
for j in range(len(label_query)):
label_id = label(index[i], label_query[j], label_fields)
size = len(label_id)
Similarity_score,Similarity_id,Similarity_title=Similarity_module(index[i],query[j],fields)
w_Similarity_score,w_Similarity_id,w_Similarity_title=Similarity_module_weight(index[i],query[j],weight_fields)
precision, recall,f_measure = cal_rec_pre(label_id,Similarity_id)
w_precision, w_recall,w_f_measure =cal_rec_pre(label_id,w_Similarity_id)
tmp_precision = tmp_precision+precision
tmp_recall = tmp_recall+recall
tmp_f_measure = tmp_f_measure+f_measure
w_tmp_precision = w_tmp_precision + w_precision
w_tmp_recall = w_tmp_recall + w_recall
w_f_measure =w_f_measure+w_f_measure
output_score = np.array(Similarity_score)
output_id = np.array(Similarity_id)
output_query = np.array(query[j])
Output_result=np.array([output_query,output_id,output_score])
np.savetxt("result/%s_query"%index[i]+"%i_result"%j,Output_result,fmt='%s')
w_output_score = np.array(w_Similarity_score)
w_output_id = np.array(w_Similarity_id)
W_Output_result = np.array([output_query, w_output_id, w_output_score])
np.savetxt("result/W_%s_query" % index[i] + "%i_result" % j, W_Output_result, fmt='%s')
Ag_precision.append(tmp_precision/len(label_query))
Ag_recall.append(tmp_recall/len(label_query))
Ag_f_measure.append(tmp_f_measure/len(label_query))
tmp_precision=0
tmp_recall=0
tmp_f_measure =0
W_Ag_precision.append(w_tmp_precision / len(label_query))
W_Ag_recall.append(w_tmp_recall / len(label_query))
W_Ag_f_measure.append(w_f_measure/len(label_query))
w_tmp_precision = 0
w_tmp_recall = 0
w_f_measure = 0
ag_precision=np.array(Ag_precision)
ag_recall=np.array(Ag_recall)
ag_f_measure = np.array(Ag_f_measure)
w_ag_precision = np.array(W_Ag_precision)
w_ag_recall = np.array(W_Ag_recall)
w_ag_f_measure = np.array(W_Ag_f_measure)
np.savetxt("result/Average_precision",ag_precision)
np.savetxt("result/Average_recall",ag_recall)
np.savetxt("result/Average_f_measure", ag_f_measure)
np.savetxt("result/W_Average_precision", w_ag_precision)
np.savetxt("result/W_Average_recall", w_ag_recall)
np.savetxt("result/W_Average_f_measure", w_ag_f_measure)
print("This is Ag_precision:",Ag_precision)
print("This is Ag_recall:",Ag_recall)
print("This is Ag_f_measure:", Ag_f_measure)
print("This is W_Ag_precision:", W_Ag_precision)
print("This is W_Ag_recall:", W_Ag_recall)
print("This is W_Ag_f_measure:", W_Ag_f_measure)
Avg_tau = []
max_p = 0
min_p = 10000
for i in range(7):
for j in range(7):
tmp = 0
tau = 0
for k in range(len(query)):
if i < j:
tau = Kendall_rank_correlation(index[i], index[j],query[k],fields)
# print(tau)
tmp = tmp + tau
p = tmp/len(query)
if max_p < p:
max_p = p
max_indexi = i
max_indexj = j
if p != 0:
Avg_tau.append((index[i], index[j],p))
if min_p > p:
min_p = p
min_indexi = i
min_indexj = j
tmp = 0
tau = 0
# print(index[i],index[j],(tmp/len(query)))
print("This is AVG_tau:",Avg_tau)
print("What combination has the highest tau:",index[max_indexi], index[max_indexj],max_p)
print("What combination has the lowest tau:", index[min_indexi], index[min_indexj],min_p)
| [
"elasticsearch.Elasticsearch",
"numpy.savetxt",
"numpy.argsort",
"elasticsearch_dsl.Search",
"numpy.array"
] | [((106, 145), 'elasticsearch.Elasticsearch', 'Elasticsearch', (["['localhost']"], {'port': '(9200)'}), "(['localhost'], port=9200)\n", (119, 145), False, 'from elasticsearch import Elasticsearch\n'), ((679, 708), 'elasticsearch_dsl.Search', 'Search', ([], {'using': 'es', 'index': 'index'}), '(using=es, index=index)\n', (685, 708), False, 'from elasticsearch_dsl import Search\n'), ((1126, 1155), 'elasticsearch_dsl.Search', 'Search', ([], {'using': 'es', 'index': 'index'}), '(using=es, index=index)\n', (1132, 1155), False, 'from elasticsearch_dsl import Search\n'), ((1843, 1872), 'elasticsearch_dsl.Search', 'Search', ([], {'using': 'es', 'index': 'index'}), '(using=es, index=index)\n', (1849, 1872), False, 'from elasticsearch_dsl import Search\n'), ((4256, 4295), 'numpy.array', 'np.array', (['rank_unique'], {'dtype': 'np.float32'}), '(rank_unique, dtype=np.float32)\n', (4264, 4295), True, 'import numpy as np\n'), ((4313, 4348), 'numpy.array', 'np.array', (['id_unique'], {'dtype': 'np.int32'}), '(id_unique, dtype=np.int32)\n', (4321, 4348), True, 'import numpy as np\n'), ((4368, 4389), 'numpy.array', 'np.array', (['name_unique'], {}), '(name_unique)\n', (4376, 4389), True, 'import numpy as np\n'), ((4574, 4621), 'numpy.array', 'np.array', (['[rank_unique, id_unique, name_unique]'], {}), '([rank_unique, id_unique, name_unique])\n', (4582, 4621), True, 'import numpy as np\n'), ((5501, 5541), 'numpy.array', 'np.array', (['score_unique'], {'dtype': 'np.float32'}), '(score_unique, dtype=np.float32)\n', (5509, 5541), True, 'import numpy as np\n'), ((5559, 5594), 'numpy.array', 'np.array', (['id_unique'], {'dtype': 'np.int32'}), '(id_unique, dtype=np.int32)\n', (5567, 5594), True, 'import numpy as np\n'), ((5613, 5634), 'numpy.array', 'np.array', (['name_unique'], {}), '(name_unique)\n', (5621, 5634), True, 'import numpy as np\n'), ((5825, 5873), 'numpy.array', 'np.array', (['[score_unique, id_unique, name_unique]'], {}), '([score_unique, id_unique, name_unique])\n', (5833, 5873), True, 'import numpy as np\n'), ((8934, 8956), 'numpy.array', 'np.array', (['Ag_precision'], {}), '(Ag_precision)\n', (8942, 8956), True, 'import numpy as np\n'), ((8972, 8991), 'numpy.array', 'np.array', (['Ag_recall'], {}), '(Ag_recall)\n', (8980, 8991), True, 'import numpy as np\n'), ((9012, 9034), 'numpy.array', 'np.array', (['Ag_f_measure'], {}), '(Ag_f_measure)\n', (9020, 9034), True, 'import numpy as np\n'), ((9057, 9081), 'numpy.array', 'np.array', (['W_Ag_precision'], {}), '(W_Ag_precision)\n', (9065, 9081), True, 'import numpy as np\n'), ((9101, 9122), 'numpy.array', 'np.array', (['W_Ag_recall'], {}), '(W_Ag_recall)\n', (9109, 9122), True, 'import numpy as np\n'), ((9145, 9169), 'numpy.array', 'np.array', (['W_Ag_f_measure'], {}), '(W_Ag_f_measure)\n', (9153, 9169), True, 'import numpy as np\n'), ((9175, 9227), 'numpy.savetxt', 'np.savetxt', (['"""result/Average_precision"""', 'ag_precision'], {}), "('result/Average_precision', ag_precision)\n", (9185, 9227), True, 'import numpy as np\n'), ((9232, 9278), 'numpy.savetxt', 'np.savetxt', (['"""result/Average_recall"""', 'ag_recall'], {}), "('result/Average_recall', ag_recall)\n", (9242, 9278), True, 'import numpy as np\n'), ((9283, 9335), 'numpy.savetxt', 'np.savetxt', (['"""result/Average_f_measure"""', 'ag_f_measure'], {}), "('result/Average_f_measure', ag_f_measure)\n", (9293, 9335), True, 'import numpy as np\n'), ((9341, 9397), 'numpy.savetxt', 'np.savetxt', (['"""result/W_Average_precision"""', 'w_ag_precision'], {}), "('result/W_Average_precision', w_ag_precision)\n", (9351, 9397), True, 'import numpy as np\n'), ((9403, 9453), 'numpy.savetxt', 'np.savetxt', (['"""result/W_Average_recall"""', 'w_ag_recall'], {}), "('result/W_Average_recall', w_ag_recall)\n", (9413, 9453), True, 'import numpy as np\n'), ((9459, 9515), 'numpy.savetxt', 'np.savetxt', (['"""result/W_Average_f_measure"""', 'w_ag_f_measure'], {}), "('result/W_Average_f_measure', w_ag_f_measure)\n", (9469, 9515), True, 'import numpy as np\n'), ((4421, 4444), 'numpy.argsort', 'np.argsort', (['rank_unique'], {}), '(rank_unique)\n', (4431, 4444), True, 'import numpy as np\n'), ((4473, 4496), 'numpy.argsort', 'np.argsort', (['rank_unique'], {}), '(rank_unique)\n', (4483, 4496), True, 'import numpy as np\n'), ((4529, 4552), 'numpy.argsort', 'np.argsort', (['rank_unique'], {}), '(rank_unique)\n', (4539, 4552), True, 'import numpy as np\n'), ((5668, 5693), 'numpy.argsort', 'np.argsort', (['(-score_unique)'], {}), '(-score_unique)\n', (5678, 5693), True, 'import numpy as np\n'), ((5720, 5745), 'numpy.argsort', 'np.argsort', (['(-score_unique)'], {}), '(-score_unique)\n', (5730, 5745), True, 'import numpy as np\n'), ((5777, 5802), 'numpy.argsort', 'np.argsort', (['(-score_unique)'], {}), '(-score_unique)\n', (5787, 5802), True, 'import numpy as np\n'), ((7812, 7838), 'numpy.array', 'np.array', (['Similarity_score'], {}), '(Similarity_score)\n', (7820, 7838), True, 'import numpy as np\n'), ((7864, 7887), 'numpy.array', 'np.array', (['Similarity_id'], {}), '(Similarity_id)\n', (7872, 7887), True, 'import numpy as np\n'), ((7916, 7934), 'numpy.array', 'np.array', (['query[j]'], {}), '(query[j])\n', (7924, 7934), True, 'import numpy as np\n'), ((7962, 8011), 'numpy.array', 'np.array', (['[output_query, output_id, output_score]'], {}), '([output_query, output_id, output_score])\n', (7970, 8011), True, 'import numpy as np\n'), ((8023, 8110), 'numpy.savetxt', 'np.savetxt', (["('result/%s_query' % index[i] + '%i_result' % j)", 'Output_result'], {'fmt': '"""%s"""'}), "('result/%s_query' % index[i] + '%i_result' % j, Output_result,\n fmt='%s')\n", (8033, 8110), True, 'import numpy as np\n'), ((8129, 8157), 'numpy.array', 'np.array', (['w_Similarity_score'], {}), '(w_Similarity_score)\n', (8137, 8157), True, 'import numpy as np\n'), ((8185, 8210), 'numpy.array', 'np.array', (['w_Similarity_id'], {}), '(w_Similarity_id)\n', (8193, 8210), True, 'import numpy as np\n'), ((8242, 8295), 'numpy.array', 'np.array', (['[output_query, w_output_id, w_output_score]'], {}), '([output_query, w_output_id, w_output_score])\n', (8250, 8295), True, 'import numpy as np\n'), ((8309, 8400), 'numpy.savetxt', 'np.savetxt', (["('result/W_%s_query' % index[i] + '%i_result' % j)", 'W_Output_result'], {'fmt': '"""%s"""'}), "('result/W_%s_query' % index[i] + '%i_result' % j,\n W_Output_result, fmt='%s')\n", (8319, 8400), True, 'import numpy as np\n')] |
import math
import numpy as np
def quaternion_from_matrix(matrix):
"""Return quaternion from rotation matrix.
>>> R = rotation_matrix(0.123, (1, 2, 3))
>>> q = quaternion_from_matrix(R)
>>> numpy.allclose(q, [0.0164262, 0.0328524, 0.0492786, 0.9981095])
True
"""
q = np.empty((4, ), dtype=np.float64)
M = np.array(matrix, dtype=np.float64, copy=False)[:4, :4]
t = np.trace(M)
if t > M[3, 3]:
q[3] = t
q[2] = M[1, 0] - M[0, 1]
q[1] = M[0, 2] - M[2, 0]
q[0] = M[2, 1] - M[1, 2]
else:
i, j, k = 0, 1, 2
if M[1, 1] > M[0, 0]:
i, j, k = 1, 2, 0
if M[2, 2] > M[i, i]:
i, j, k = 2, 0, 1
t = M[i, i] - (M[j, j] + M[k, k]) + M[3, 3]
q[i] = t
q[j] = M[i, j] + M[j, i]
q[k] = M[k, i] + M[i, k]
q[3] = M[k, j] - M[j, k]
q *= 0.5 / math.sqrt(t * M[3, 3])
return q
def pose_quaternion_from_matrix(matrix):
"""Return translation + quaternion(x,y,z,w)
"""
if matrix.shape == (3, 4):
matrix = np.concatenate((matrix, [[0, 0, 0, 1]]), axis=0)
pose = matrix[:3, 3]
quat = quaternion_from_matrix(matrix)
return np.concatenate((pose, quat), axis=0)
class URKinematics():
def __init__(self, robot_name):
if robot_name == 'ur3':
import ur3_ikfast as ur_ikfast
elif robot_name == 'ur3e':
import ur3e_ikfast as ur_ikfast
elif robot_name == 'ur5':
import ur5_ikfast as ur_ikfast
elif robot_name == 'ur5e':
import ur5e_ikfast as ur_ikfast
elif robot_name == 'ur10':
import ur10_ikfast as ur_ikfast
elif robot_name == 'ur10e':
import ur10e_ikfast as ur_ikfast
else:
raise Exception("Unsupported robot")
self.kinematics = ur_ikfast.PyKinematics()
self.n_joints = self.kinematics.getDOF()
def forward(self, joint_angles, rotation_type='quaternion'):
"""
Compute robot's forward kinematics for the specified robot
joint_angles: list
rotation_type: 'quaternion' or 'matrix'
:return: if 'quaternion' then return a list of [x, y, z, w. qx, qy, qz]
if 'matrix' then a list of 12 values the 3x3 rotation matrix and
the 3 translational values
"""
if isinstance(joint_angles, np.ndarray):
joint_angles = joint_angles.tolist()
ee_pose = self.kinematics.forward(joint_angles)
ee_pose = np.asarray(ee_pose).reshape(3, 4)
if rotation_type == 'matrix':
return ee_pose
elif rotation_type == 'quaternion':
return pose_quaternion_from_matrix(ee_pose)
def inverse(self, ee_pose, all_solutions=False, q_guess=np.zeros(6)):
""" Compute robot's inverse kinematics for the specified robot
ee_pose: list of 7 if quaternion [x, y, z, w, qx, qy, qz]
list of 12 if rotation matrix + translational values
all_solutions: whether to return all the solutions found or just the best one
q_guess: if just one solution is request, this set of joint values will be use
to find the closest solution to this
:return: list of joint angles
list of best joint angles if found
q_guess if no solution is found
"""
pose = None
if len(ee_pose) == 7:
rot = np.roll(ee_pose[3:], 1)
pose = np.concatenate((ee_pose[:3], rot), axis=0)
else:
pose = ee_pose
joint_configs = self.kinematics.inverse(pose.reshape(-1).tolist())
n_solutions = int(len(joint_configs)/self.n_joints)
joint_configs = np.asarray(joint_configs).reshape(n_solutions, self.n_joints)
if all_solutions:
return joint_configs
return best_ik_sol(joint_configs, q_guess)
def best_ik_sol(sols, q_guess, weights=np.ones(6)):
""" Get best IK solution """
valid_sols = []
for sol in sols:
test_sol = np.ones(6) * 9999.
for i in range(6):
for add_ang in [-2. * np.pi, 0, 2. * np.pi]:
test_ang = sol[i] + add_ang
if (abs(test_ang) <= 2. * np.pi
and abs(test_ang - q_guess[i]) <
abs(test_sol[i] - q_guess[i])):
test_sol[i] = test_ang
if np.all(test_sol != 9999.):
valid_sols.append(test_sol)
if not valid_sols:
return None
best_sol_ind = np.argmin(
np.sum((weights * (valid_sols - np.array(q_guess)))**2, 1))
return valid_sols[best_sol_ind]
| [
"numpy.trace",
"math.sqrt",
"numpy.roll",
"numpy.empty",
"numpy.asarray",
"numpy.zeros",
"numpy.ones",
"ur10e_ikfast.PyKinematics",
"numpy.all",
"numpy.array",
"numpy.concatenate"
] | [((296, 328), 'numpy.empty', 'np.empty', (['(4,)'], {'dtype': 'np.float64'}), '((4,), dtype=np.float64)\n', (304, 328), True, 'import numpy as np\n'), ((401, 412), 'numpy.trace', 'np.trace', (['M'], {}), '(M)\n', (409, 412), True, 'import numpy as np\n'), ((1198, 1234), 'numpy.concatenate', 'np.concatenate', (['(pose, quat)'], {'axis': '(0)'}), '((pose, quat), axis=0)\n', (1212, 1234), True, 'import numpy as np\n'), ((4028, 4038), 'numpy.ones', 'np.ones', (['(6)'], {}), '(6)\n', (4035, 4038), True, 'import numpy as np\n'), ((338, 384), 'numpy.array', 'np.array', (['matrix'], {'dtype': 'np.float64', 'copy': '(False)'}), '(matrix, dtype=np.float64, copy=False)\n', (346, 384), True, 'import numpy as np\n'), ((888, 910), 'math.sqrt', 'math.sqrt', (['(t * M[3, 3])'], {}), '(t * M[3, 3])\n', (897, 910), False, 'import math\n'), ((1070, 1118), 'numpy.concatenate', 'np.concatenate', (['(matrix, [[0, 0, 0, 1]])'], {'axis': '(0)'}), '((matrix, [[0, 0, 0, 1]]), axis=0)\n', (1084, 1118), True, 'import numpy as np\n'), ((1855, 1879), 'ur10e_ikfast.PyKinematics', 'ur_ikfast.PyKinematics', ([], {}), '()\n', (1877, 1879), True, 'import ur10e_ikfast as ur_ikfast\n'), ((2826, 2837), 'numpy.zeros', 'np.zeros', (['(6)'], {}), '(6)\n', (2834, 2837), True, 'import numpy as np\n'), ((4496, 4522), 'numpy.all', 'np.all', (['(test_sol != 9999.0)'], {}), '(test_sol != 9999.0)\n', (4502, 4522), True, 'import numpy as np\n'), ((3527, 3550), 'numpy.roll', 'np.roll', (['ee_pose[3:]', '(1)'], {}), '(ee_pose[3:], 1)\n', (3534, 3550), True, 'import numpy as np\n'), ((3570, 3612), 'numpy.concatenate', 'np.concatenate', (['(ee_pose[:3], rot)'], {'axis': '(0)'}), '((ee_pose[:3], rot), axis=0)\n', (3584, 3612), True, 'import numpy as np\n'), ((4134, 4144), 'numpy.ones', 'np.ones', (['(6)'], {}), '(6)\n', (4141, 4144), True, 'import numpy as np\n'), ((2565, 2584), 'numpy.asarray', 'np.asarray', (['ee_pose'], {}), '(ee_pose)\n', (2575, 2584), True, 'import numpy as np\n'), ((3813, 3838), 'numpy.asarray', 'np.asarray', (['joint_configs'], {}), '(joint_configs)\n', (3823, 3838), True, 'import numpy as np\n'), ((4676, 4693), 'numpy.array', 'np.array', (['q_guess'], {}), '(q_guess)\n', (4684, 4693), True, 'import numpy as np\n')] |
""""
The goal of this module is to give a comprehensive solution to Task 6
from the coding homeworks from the Machine Learning course on coursera.com.
The task is broken down into smaller parts.
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
import readers
import algorithms
import plots
DATA_PATH_1 = Path("../data/data1.mat")
DATA_PATH_2 = Path("../data/data2.mat")
DATA_PATH_3 = Path("../data/data3.mat")
DATA_PATH_4 = Path("../data/emailSample1.txt")
DATA_PATH_5 = Path("../data/vocab.txt")
DATA_PATH_6 = Path("../data/spamTrain.mat")
DATA_PATH_7 = Path("../data/spamTest.mat")
def part_1() -> None:
"""
Support Vector Machines:
- Data visualization.
- Implementing SVM with Gaussian Kernels.
Returns:
None
"""
x, y = readers.read_data(DATA_PATH_1)
pos = np.array([x[i] for i in range(x.shape[0]) if y[i] == 1])
neg = np.array([x[i] for i in range(x.shape[0]) if y[i] == 0])
plots.plot_data((pos, neg))
for c_value in (1, 100):
title = f"Decision boundary with C={c_value}"
plots.plot_data((pos, neg), title)
plots.plot_boundary(
(algorithms.train_svm(x, y, C=c_value, kernel="linear"), 0, 4.5)
)
def part_2() -> None:
"""
Support Vector Machines:
- Data visualization.
- Implementing SVM with Gaussian Kernels.
Returns:
None
"""
x, y = readers.read_data(DATA_PATH_2)
pos = np.array([x[i] for i in range(x.shape[0]) if y[i] == 1])
neg = np.array([x[i] for i in range(x.shape[0]) if y[i] == 0])
plots.plot_data((pos, neg), title="scatter plot of training data 2")
c_value = 1
sigma = 0.1
title = f"Decision boundary with C={c_value}"
plots.plot_data((pos, neg), title)
plots.plot_boundary_gaussian(
(
algorithms.train_svm(
x, y, C=c_value, kernel="rbf", gamma=np.power(sigma, -2)
),
0,
1,
0.4,
1,
)
)
def part_3() -> None:
"""
Support Vector Machines:
- Data visualization.
- Implementing SVM with Gaussian Kernels.
Returns:
None
"""
x, y = readers.read_data(DATA_PATH_3)
pos = np.array([x[i] for i in range(x.shape[0]) if y[i] == 1])
neg = np.array([x[i] for i in range(x.shape[0]) if y[i] == 0])
plots.plot_data((pos, neg), title="scatter plot of training data 3")
c_value = 2
sigma = 0.1
title = f"Decision boundary with C={c_value}"
plots.plot_data((pos, neg), title)
plots.plot_boundary_gaussian(
(
algorithms.train_svm(
x, y, C=c_value, kernel="rbf", gamma=np.power(sigma, -2)
),
-0.5,
0.3,
-0.8,
0.6,
)
)
def part_4() -> None:
"""
Spam Classification:
- Preprocessing emails.
- Making a vocabulary list.
- Extracting features from emails.
- Training SVM for spam classification.
Returns:
None
"""
vocabulary = readers.read_vocabulary(DATA_PATH_5)
tokens = readers.read_tokens(DATA_PATH_4, vocabulary)
feature_vector_len = len(vocabulary)
features = algorithms.extract_features(tokens, feature_vector_len)
non_zero_count = np.count_nonzero(features)
print(f"Length of feature vector is {feature_vector_len}")
print(f"Number of non-zero entries is {non_zero_count}")
x, y = readers.read_data(DATA_PATH_6)
svm_function = algorithms.train_svm(
x,
y,
C=0.1,
coef0=0.0,
decision_function_shape="ovr",
degree=3,
gamma="auto",
kernel="linear",
)
predictions = svm_function.predict(x)
print(f"Training accuracy: {np.mean(predictions == y.flatten()) * 100}")
x_test, y_test = readers.read_test_data(DATA_PATH_7)
predictions = svm_function.predict(x_test)
print(f"Test accuracy: {np.mean(predictions == y_test.flatten()) * 100}")
weights = svm_function.coef_[0]
data_frame = pd.DataFrame({"vocabulary": vocabulary, "weights": weights})
print(data_frame.sort_values(by="weights", ascending=False).head())
def main() -> None:
"""
The main functions. Calls the functions that implement different parts of the solution
to the Task 6 from the coding homeworks from the Machine Learning course on coursera.com.
Returns:
None
"""
plt.style.use("seaborn")
part_1()
part_2()
part_3()
part_4()
plt.show()
if __name__ == "__main__":
main()
| [
"pandas.DataFrame",
"algorithms.extract_features",
"readers.read_vocabulary",
"readers.read_tokens",
"numpy.count_nonzero",
"matplotlib.pyplot.show",
"algorithms.train_svm",
"plots.plot_data",
"numpy.power",
"readers.read_test_data",
"pathlib.Path",
"matplotlib.pyplot.style.use",
"readers.re... | [((359, 384), 'pathlib.Path', 'Path', (['"""../data/data1.mat"""'], {}), "('../data/data1.mat')\n", (363, 384), False, 'from pathlib import Path\n'), ((399, 424), 'pathlib.Path', 'Path', (['"""../data/data2.mat"""'], {}), "('../data/data2.mat')\n", (403, 424), False, 'from pathlib import Path\n'), ((439, 464), 'pathlib.Path', 'Path', (['"""../data/data3.mat"""'], {}), "('../data/data3.mat')\n", (443, 464), False, 'from pathlib import Path\n'), ((479, 511), 'pathlib.Path', 'Path', (['"""../data/emailSample1.txt"""'], {}), "('../data/emailSample1.txt')\n", (483, 511), False, 'from pathlib import Path\n'), ((526, 551), 'pathlib.Path', 'Path', (['"""../data/vocab.txt"""'], {}), "('../data/vocab.txt')\n", (530, 551), False, 'from pathlib import Path\n'), ((566, 595), 'pathlib.Path', 'Path', (['"""../data/spamTrain.mat"""'], {}), "('../data/spamTrain.mat')\n", (570, 595), False, 'from pathlib import Path\n'), ((610, 638), 'pathlib.Path', 'Path', (['"""../data/spamTest.mat"""'], {}), "('../data/spamTest.mat')\n", (614, 638), False, 'from pathlib import Path\n'), ((816, 846), 'readers.read_data', 'readers.read_data', (['DATA_PATH_1'], {}), '(DATA_PATH_1)\n', (833, 846), False, 'import readers\n'), ((985, 1012), 'plots.plot_data', 'plots.plot_data', (['(pos, neg)'], {}), '((pos, neg))\n', (1000, 1012), False, 'import plots\n'), ((1433, 1463), 'readers.read_data', 'readers.read_data', (['DATA_PATH_2'], {}), '(DATA_PATH_2)\n', (1450, 1463), False, 'import readers\n'), ((1602, 1670), 'plots.plot_data', 'plots.plot_data', (['(pos, neg)'], {'title': '"""scatter plot of training data 2"""'}), "((pos, neg), title='scatter plot of training data 2')\n", (1617, 1670), False, 'import plots\n'), ((1758, 1792), 'plots.plot_data', 'plots.plot_data', (['(pos, neg)', 'title'], {}), '((pos, neg), title)\n', (1773, 1792), False, 'import plots\n'), ((2214, 2244), 'readers.read_data', 'readers.read_data', (['DATA_PATH_3'], {}), '(DATA_PATH_3)\n', (2231, 2244), False, 'import readers\n'), ((2383, 2451), 'plots.plot_data', 'plots.plot_data', (['(pos, neg)'], {'title': '"""scatter plot of training data 3"""'}), "((pos, neg), title='scatter plot of training data 3')\n", (2398, 2451), False, 'import plots\n'), ((2539, 2573), 'plots.plot_data', 'plots.plot_data', (['(pos, neg)', 'title'], {}), '((pos, neg), title)\n', (2554, 2573), False, 'import plots\n'), ((3076, 3112), 'readers.read_vocabulary', 'readers.read_vocabulary', (['DATA_PATH_5'], {}), '(DATA_PATH_5)\n', (3099, 3112), False, 'import readers\n'), ((3126, 3170), 'readers.read_tokens', 'readers.read_tokens', (['DATA_PATH_4', 'vocabulary'], {}), '(DATA_PATH_4, vocabulary)\n', (3145, 3170), False, 'import readers\n'), ((3227, 3282), 'algorithms.extract_features', 'algorithms.extract_features', (['tokens', 'feature_vector_len'], {}), '(tokens, feature_vector_len)\n', (3254, 3282), False, 'import algorithms\n'), ((3304, 3330), 'numpy.count_nonzero', 'np.count_nonzero', (['features'], {}), '(features)\n', (3320, 3330), True, 'import numpy as np\n'), ((3468, 3498), 'readers.read_data', 'readers.read_data', (['DATA_PATH_6'], {}), '(DATA_PATH_6)\n', (3485, 3498), False, 'import readers\n'), ((3518, 3638), 'algorithms.train_svm', 'algorithms.train_svm', (['x', 'y'], {'C': '(0.1)', 'coef0': '(0.0)', 'decision_function_shape': '"""ovr"""', 'degree': '(3)', 'gamma': '"""auto"""', 'kernel': '"""linear"""'}), "(x, y, C=0.1, coef0=0.0, decision_function_shape='ovr',\n degree=3, gamma='auto', kernel='linear')\n", (3538, 3638), False, 'import algorithms\n'), ((3848, 3883), 'readers.read_test_data', 'readers.read_test_data', (['DATA_PATH_7'], {}), '(DATA_PATH_7)\n', (3870, 3883), False, 'import readers\n'), ((4063, 4123), 'pandas.DataFrame', 'pd.DataFrame', (["{'vocabulary': vocabulary, 'weights': weights}"], {}), "({'vocabulary': vocabulary, 'weights': weights})\n", (4075, 4123), True, 'import pandas as pd\n'), ((4448, 4472), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn"""'], {}), "('seaborn')\n", (4461, 4472), True, 'import matplotlib.pyplot as plt\n'), ((4529, 4539), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4537, 4539), True, 'import matplotlib.pyplot as plt\n'), ((1105, 1139), 'plots.plot_data', 'plots.plot_data', (['(pos, neg)', 'title'], {}), '((pos, neg), title)\n', (1120, 1139), False, 'import plots\n'), ((1182, 1236), 'algorithms.train_svm', 'algorithms.train_svm', (['x', 'y'], {'C': 'c_value', 'kernel': '"""linear"""'}), "(x, y, C=c_value, kernel='linear')\n", (1202, 1236), False, 'import algorithms\n'), ((1924, 1943), 'numpy.power', 'np.power', (['sigma', '(-2)'], {}), '(sigma, -2)\n', (1932, 1943), True, 'import numpy as np\n'), ((2705, 2724), 'numpy.power', 'np.power', (['sigma', '(-2)'], {}), '(sigma, -2)\n', (2713, 2724), True, 'import numpy as np\n')] |
"""
Copyright (c) 2016 <NAME> and <NAME>
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 numpy as np
import math
import pandas as pd
import sys
# Thu Apr 6 13:15:17 CDT 2017
###############################################################################
def getVariables(header, x, y, options):
"""Get all the needed variables into a Dictionary
More added in overallDataType()"""
pname = options['phenotypename']
var = {'NumAttributes' : len(header),
'phenoTypeList' : list(set(y)) }
if(len(var['phenoTypeList']) <= options['discretelimit']):
var['discretePhenotype'] = True
var['phenSD'] = 0
else:
var['discretePhenotype'] = False
var['phenSD'] = np.std(y, ddof=1)
var['discreteLimit'] = options['discretelimit']
var['labelMissingData'] = options['missingdata']
var['phenoTypeName'] = pname
#var['phenoTypeLoc'] = options['classloc']
var['numNeighbors'] = options['neighbors']
var['mdcnt'] = np.isnan(x).sum()
var['datalen'] = len(x)
return var
###############################################################################
def getAttributeInfo(header, x, var, options):
"""Get attribute as tuple into Dictionary"""
attr = dict()
c = d = 0
limit = options['discretelimit']
w = x.transpose()
#for h in header:
for idx in range(len(w)):
h = header[idx]
z = w[idx]
z = z[np.logical_not(np.isnan(z))] # remove missing data before
zulen = len(np.unique(z)) # calculating unique set
if(zulen <= limit):
attr[h] = ('discrete', 0, 0, 0, 0)
d += 1
else:
mx = np.max(z)
mn = np.min(z)
sd = np.std(z)
attr[h] = ('continuous', mx, mn, mx - mn, sd)
c += 1
overallDataType(attr,var,options) # add datatype of data and endpoints
var['dpct'] = (float(d) / (d + c) * 100, d)
var['cpct'] = (float(c) / (d + c) * 100, c)
return attr
###############################################################################
# Is the data entirely discrete, continuous, or mixed?
# Is the class type discrete, continuous or multiclass?
# This will help with future directions. Adding this to the variables
# dictionary. This is called from within getAttributeInfo()
def overallDataType(attr, var, options):
""" adds overall datatype of the data and class to var dictionary """
D = False; C = False # set tmp booleons
for key in attr.keys():
if(key == 'dataType' or key == 'phenoType'): continue
if(attr[key][0] == 'discrete'):
D = True
if(attr[key][0] == 'continuous'):
C = True
if(var['discretePhenotype'] and len(var['phenoTypeList']) > 2):
pheno = 'multiclass'
elif(var['discretePhenotype']):
pheno = 'binary'
else:
pheno = 'continuous'
if(D and C):
dataType = 'mixed'
elif(D and not C):
dataType = 'discrete'
elif(C and not D):
dataType = 'continuous'
var['dataType'] = dataType
var['classType'] = pheno
###############################################################################
def getDistances(x, attr, var, cidx, didx, cheader):
""" This creates the distance array for only discrete or continuous data
with no missing data """
from scipy.spatial.distance import pdist, squareform
#--------------------------------------------------------------------------
def pre_normalize(x):
idx = 0
for i in cheader:
cmin = attr[i][2]
diff = attr[i][3]
x[:,idx] -= cmin
x[:,idx] /= diff
idx += 1
return x
#--------------------------------------------------------------------------
dtype = var['dataType']
numattr = var['NumAttributes']
if(dtype == 'discrete'):
return squareform(pdist(x,metric='hamming'))
if(dtype == 'mixed'):
d_dist = squareform(pdist(x[:,didx],metric='hamming'))
xc = pre_normalize(x[:,cidx])
c_dist = squareform(pdist(xc,metric='cityblock'))
return np.add(d_dist, c_dist) / numattr
else: #(dtype == 'continuous'):
return squareform(pdist(pre_normalize(x),metric='cityblock'))
###############################################################################
# return mask for discrete(0)/continuous(1) attributes and their indices
# return array of max/min diffs of attributes.
# added for cython routines
def dtypeArray(header, attr, var):
import numpy as np
attrtype = []
attrdiff = []
pname = var['phenoTypeName']
for key in header:
#if(key == pname): continue
if(attr[key][0] == 'continuous'):
attrtype.append(1)
else:
attrtype.append(0)
attrdiff.append(attr[key][3]) # build array of max-min diffs
attrtype = np.array(attrtype)
cidx = np.where(attrtype == 1)[0] # grab indices for split_data()
cidx = np.ascontiguousarray(cidx, dtype=np.int32)
didx = np.where(attrtype == 0)[0] # where returns a tuple
didx = np.ascontiguousarray(didx, dtype=np.int32)
attrdiff = np.array(attrdiff)
attrdiff = np.ascontiguousarray(attrdiff, dtype=np.double)
return attrdiff, cidx, didx
###############################################################################
def printf(format, *args):
sys.stdout.write(format % args)
| [
"sys.stdout.write",
"numpy.std",
"numpy.isnan",
"numpy.max",
"numpy.where",
"numpy.array",
"numpy.min",
"scipy.spatial.distance.pdist",
"numpy.add",
"numpy.ascontiguousarray",
"numpy.unique"
] | [((5945, 5963), 'numpy.array', 'np.array', (['attrtype'], {}), '(attrtype)\n', (5953, 5963), True, 'import numpy as np\n'), ((6047, 6089), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['cidx'], {'dtype': 'np.int32'}), '(cidx, dtype=np.int32)\n', (6067, 6089), True, 'import numpy as np\n'), ((6165, 6207), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['didx'], {'dtype': 'np.int32'}), '(didx, dtype=np.int32)\n', (6185, 6207), True, 'import numpy as np\n'), ((6228, 6246), 'numpy.array', 'np.array', (['attrdiff'], {}), '(attrdiff)\n', (6236, 6246), True, 'import numpy as np\n'), ((6262, 6309), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['attrdiff'], {'dtype': 'np.double'}), '(attrdiff, dtype=np.double)\n', (6282, 6309), True, 'import numpy as np\n'), ((6454, 6485), 'sys.stdout.write', 'sys.stdout.write', (['(format % args)'], {}), '(format % args)\n', (6470, 6485), False, 'import sys\n'), ((1711, 1728), 'numpy.std', 'np.std', (['y'], {'ddof': '(1)'}), '(y, ddof=1)\n', (1717, 1728), True, 'import numpy as np\n'), ((5975, 5998), 'numpy.where', 'np.where', (['(attrtype == 1)'], {}), '(attrtype == 1)\n', (5983, 5998), True, 'import numpy as np\n'), ((6101, 6124), 'numpy.where', 'np.where', (['(attrtype == 0)'], {}), '(attrtype == 0)\n', (6109, 6124), True, 'import numpy as np\n'), ((1991, 2002), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (1999, 2002), True, 'import numpy as np\n'), ((2512, 2524), 'numpy.unique', 'np.unique', (['z'], {}), '(z)\n', (2521, 2524), True, 'import numpy as np\n'), ((2686, 2695), 'numpy.max', 'np.max', (['z'], {}), '(z)\n', (2692, 2695), True, 'import numpy as np\n'), ((2713, 2722), 'numpy.min', 'np.min', (['z'], {}), '(z)\n', (2719, 2722), True, 'import numpy as np\n'), ((2740, 2749), 'numpy.std', 'np.std', (['z'], {}), '(z)\n', (2746, 2749), True, 'import numpy as np\n'), ((4957, 4983), 'scipy.spatial.distance.pdist', 'pdist', (['x'], {'metric': '"""hamming"""'}), "(x, metric='hamming')\n", (4962, 4983), False, 'from scipy.spatial.distance import pdist, squareform\n'), ((5039, 5074), 'scipy.spatial.distance.pdist', 'pdist', (['x[:, didx]'], {'metric': '"""hamming"""'}), "(x[:, didx], metric='hamming')\n", (5044, 5074), False, 'from scipy.spatial.distance import pdist, squareform\n'), ((5140, 5169), 'scipy.spatial.distance.pdist', 'pdist', (['xc'], {'metric': '"""cityblock"""'}), "(xc, metric='cityblock')\n", (5145, 5169), False, 'from scipy.spatial.distance import pdist, squareform\n'), ((5185, 5207), 'numpy.add', 'np.add', (['d_dist', 'c_dist'], {}), '(d_dist, c_dist)\n', (5191, 5207), True, 'import numpy as np\n'), ((2448, 2459), 'numpy.isnan', 'np.isnan', (['z'], {}), '(z)\n', (2456, 2459), True, 'import numpy as np\n')] |
# --------------
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import seaborn as sns
import matplotlib.pyplot as plt
# load the data from dataset
df = pd.read_csv(path)
# visualize the first five rows of the dataset
print(df.head())
# split the dataset into features and targets
X = df.drop('Price',axis=1)
y = df['Price']
# split the dataset inot test and train set
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3, random_state=6)
# identify the correlation between different features of the train set
corr = X_train.corr()
print(corr)
# visualize the correlation between features using heatmap
plt.figure(figsize=(12,10))
sns.heatmap(corr,cmap='YlGnBu')
#Code starts here
# --------------
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
# Code starts here
#initialize the LinearRegression
regressor = LinearRegression()
# fit the model to train data
regressor.fit(X_train, y_train)
# predict output using the regressor
y_pred = regressor.predict(X_test)
# identify the r2 score of the model
r2 = r2_score(y_test,y_pred)
print(r2)
# --------------
from sklearn.linear_model import Lasso
# Code starts here
#initialize the lasso model
lasso = Lasso()
# fit the model to train data
lasso.fit(X_train, y_train)
# predict the prices
lasso_pred = lasso.predict(X_test)
# identify the r2 scrore of the predicted value
r2_lasso = r2_score(y_test, lasso_pred)
print(r2_lasso)
# --------------
from sklearn.linear_model import Ridge
# Code starts here
ridge = Ridge()
ridge.fit(X_train, y_train)
ridge_pred = ridge.predict(X_test)
r2_ridge = r2_score(y_test, ridge_pred)
print("value of r2 score for Ridge Regression is: ",r2_ridge)
# Code ends here
# --------------
from sklearn.model_selection import cross_val_score
#Code starts here
#initialize the linear regression model
regressor = LinearRegression()
#Cross validation with linear model
score = cross_val_score(regressor,X_train, y_train, cv=10 )
# identify the mean cross val score
mean_score = np.mean(score)
print(mean_score)
# --------------
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
#Code starts here
#initialize the model using make pipeline
model = make_pipeline(PolynomialFeatures(2),LinearRegression())
# fit the model
model.fit(X_train, y_train)
# predict the test labels
y_pred = model.predict(X_test)
# calculate the r2 score
r2_poly = r2_score(y_test,y_pred)
print('r2 score using polynomial features is:' , r2_poly)
| [
"seaborn.heatmap",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.linear_model.Ridge",
"sklearn.metrics.r2_score",
"sklearn.model_selection.cross_val_score",
"sklearn.linear_model.LinearRegression",
"sklearn.preprocessing.PolynomialFeatures",
"matplotlib.pyplot.figure",
"n... | [((205, 222), 'pandas.read_csv', 'pd.read_csv', (['path'], {}), '(path)\n', (216, 222), True, 'import pandas as pd\n'), ((470, 523), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.3)', 'random_state': '(6)'}), '(X, y, test_size=0.3, random_state=6)\n', (486, 523), False, 'from sklearn.model_selection import train_test_split\n'), ((697, 725), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 10)'}), '(figsize=(12, 10))\n', (707, 725), True, 'import matplotlib.pyplot as plt\n'), ((726, 758), 'seaborn.heatmap', 'sns.heatmap', (['corr'], {'cmap': '"""YlGnBu"""'}), "(corr, cmap='YlGnBu')\n", (737, 758), True, 'import seaborn as sns\n'), ((955, 973), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (971, 973), False, 'from sklearn.linear_model import LinearRegression\n'), ((1162, 1186), 'sklearn.metrics.r2_score', 'r2_score', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (1170, 1186), False, 'from sklearn.metrics import r2_score\n'), ((1317, 1324), 'sklearn.linear_model.Lasso', 'Lasso', ([], {}), '()\n', (1322, 1324), False, 'from sklearn.linear_model import Lasso\n'), ((1510, 1538), 'sklearn.metrics.r2_score', 'r2_score', (['y_test', 'lasso_pred'], {}), '(y_test, lasso_pred)\n', (1518, 1538), False, 'from sklearn.metrics import r2_score\n'), ((1649, 1656), 'sklearn.linear_model.Ridge', 'Ridge', ([], {}), '()\n', (1654, 1656), False, 'from sklearn.linear_model import Ridge\n'), ((1740, 1768), 'sklearn.metrics.r2_score', 'r2_score', (['y_test', 'ridge_pred'], {}), '(y_test, ridge_pred)\n', (1748, 1768), False, 'from sklearn.metrics import r2_score\n'), ((2000, 2018), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (2016, 2018), False, 'from sklearn.linear_model import LinearRegression\n'), ((2067, 2118), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['regressor', 'X_train', 'y_train'], {'cv': '(10)'}), '(regressor, X_train, y_train, cv=10)\n', (2082, 2118), False, 'from sklearn.model_selection import cross_val_score\n'), ((2173, 2187), 'numpy.mean', 'np.mean', (['score'], {}), '(score)\n', (2180, 2187), True, 'import numpy as np\n'), ((2605, 2629), 'sklearn.metrics.r2_score', 'r2_score', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (2613, 2629), False, 'from sklearn.metrics import r2_score\n'), ((2414, 2435), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', (['(2)'], {}), '(2)\n', (2432, 2435), False, 'from sklearn.preprocessing import PolynomialFeatures\n'), ((2436, 2454), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (2452, 2454), False, 'from sklearn.linear_model import LinearRegression\n')] |
import numpy as np
import qosy as qy
def xxz_chain(L, J_xy, J_z, periodic=False):
"""Construct a 1D XXZ Hamiltonian H = 1/4 \sum_<ij> [J_xy (X_i X_j + Y_i Y_j) + J_z Z_i Z_j]
Parameters
----------
L : int
The length of the chain.
J_xy : float
The coefficient in front of the exchange term.
J_z : float
The coefficient in front of the Ising term.
periodic : bool, optional
Specifies whether the model is periodic. Defaults to False.
Returns
-------
qosy.Operator
The Hamiltonian.
Examples
--------
Build a 5-site Heisenberg chain:
>>> H = xxz_chain(5, 1.0, 1.0)
"""
coeffs = []
op_strings = []
for site in range(L):
if site == L-1 and not periodic:
continue
sitep = (site + 1) % L
s1 = np.minimum(site, sitep)
s2 = np.maximum(site, sitep)
for orb in ['X', 'Y', 'Z']:
if orb in ['X', 'Y']:
coeffs.append(0.25 * J_xy)
else:
coeffs.append(0.25 * J_z)
op_strings.append(qy.opstring('{} {} {} {}'.format(orb,s1,orb,s2)))
H = qy.Operator(coeffs, op_strings)
return H
def xxz_square(L, J_xy, J_z, periodic=False):
"""Construct a 2D square-lattice XXZ Hamiltonian H = 1/4 \\sum_<ij> [J_xy (X_i X_j + Y_i Y_j) + J_z Z_i Z_j]
Parameters
----------
L : int
The side-length of the square.
J_xy : float
The coefficient in front of the exchange term.
J_z : float
The coefficient in front of the Ising term.
periodic : bool, optional
Specifies whether the model is periodic. Defaults to False.
Returns
-------
qosy.Operator
The Hamiltonian.
Examples
--------
Build a 5x5 2D Heisenberg model:
>>> H = xxz_square(5, 1.0, 1.0)
"""
Lx = L
Ly = L
N = Lx*Ly
coeffs = []
op_strings = []
for y in range(Ly):
for x in range(Lx):
# Two bonds
for bond in [(1,0), (0,1)]:
site = y*Lx + x
dx = bond[0]
dy = bond[1]
# Bond pointing to the right and up
xp = x + dx
yp = y + dy
if periodic:
xp = xp % Lx
yp = yp % Ly
if xp >= 0 and xp < Lx and yp >= 0 and yp < Ly:
sitep = yp*Lx + xp
s1 = np.minimum(site, sitep)
s2 = np.maximum(site, sitep)
for orb in ['X', 'Y', 'Z']:
if orb in ['X', 'Y']:
coeffs.append(0.25 * J_xy)
else:
coeffs.append(0.25 * J_z)
op_strings.append(qy.opstring('{} {} {} {}'.format(orb,s1,orb,s2)))
H = qy.Operator(coeffs, op_strings)
return H
def xxz_cubic(L, J_xy, J_z, periodic=False):
"""Construct a 3D cubic-lattice XXZ Hamiltonian H = 1/4 \\sum_<ij> [J_xy (X_i X_j + Y_i Y_j) + J_z Z_i Z_j]
Parameters
----------
L : int
The side-length of the cubic lattice.
J_xy : float
The coefficient in front of the exchange term.
J_z : float
The coefficient in front of the Ising term.
periodic : bool, optional
Specifies whether the model is periodic. Defaults to False.
Returns
-------
qosy.Operator
The Hamiltonian.
Examples
--------
Build a 5x5x5 3D Heisenberg model:
>>> H = xxz_cubic(5, 1.0, 1.0)
"""
Lx = L
Ly = L
Lz = L
N = Lx*Ly*Lz
coeffs = []
op_strings = []
for z in range(Lz):
for y in range(Ly):
for x in range(Lx):
# Two bonds
for bond in [(1,0,0), (0,1,0), (0,0,1)]:
site = z*Lx*Ly + y*Lx + x
dx = bond[0]
dy = bond[1]
dz = bond[2]
# Bond pointing to the right, up, and in
xp = x + dx
yp = y + dy
zp = z + dz
if periodic:
xp = xp % Lx
yp = yp % Ly
zp = zp % Lz
if xp >= 0 and xp < Lx and yp >= 0 and yp < Ly and zp >= 0 and zp < Lz:
sitep = zp*Lx*Ly + yp*Lx + xp
s1 = np.minimum(site, sitep)
s2 = np.maximum(site, sitep)
for orb in ['X', 'Y', 'Z']:
if orb in ['X', 'Y']:
coeffs.append(0.25 * J_xy)
else:
coeffs.append(0.25 * J_z)
op_strings.append(qy.opstring('{} {} {} {}'.format(orb,s1,orb,s2)))
H = qy.Operator(coeffs, op_strings)
return H
def bose_hubbard_square(L, periodic=False):
"""Construct a 2D square-lattice hard-core Bose-Hubbard Hamiltonian (without magnetic fields),
which when written in terms of spin operators is an XX-model of the form:
H = -1/2 \\sum_<ij> (X_i X_j + Y_i Y_j)
Parameters
----------
L : int
The side-length of the square.
periodic : bool, optional
Specifies whether the model is periodic. Defaults to False.
Returns
-------
qosy.Operator
The Hamiltonian.
Examples
--------
Build a 5x5 2D hard-core Bose-Hubbard model:
>>> H = xxz_square(5, 1.0, 1.0)
"""
Lx = L
Ly = L
N = Lx*Ly
coeffs = []
op_strings = []
for y in range(Ly):
for x in range(Lx):
# Two bonds
for bond in [(1,0), (0,1)]:
site = y*Lx + x
dx = bond[0]
dy = bond[1]
# Bond pointing to the right and up
xp = x + dx
yp = y + dy
if periodic:
xp = xp % Lx
yp = yp % Ly
if xp >= 0 and xp < Lx and yp >= 0 and yp < Ly:
sitep = yp*Lx + xp
s1 = np.minimum(site, sitep)
s2 = np.maximum(site, sitep)
for orb in ['X', 'Y']:
coeffs.append(-0.5) # J = 1.0
op_strings.append(qy.opstring('{} {} {} {}'.format(orb,s1,orb,s2)))
H = qy.Operator(coeffs, op_strings)
return H
def magnetic_fields(potentials):
"""Construct a magnetic fields operator H = 1/2 \\sum_j h_j Z_j from the specified potentials h_j.
Parameters
----------
potentials : list or ndarray
The potentials h_j.
Returns
-------
qosy.Operator
The Hamiltonian representing the magnetic fields.
Examples
--------
Build a 5-site disordered Heisenberg model:
>>> import numpy as np
>>> W = 6.0 # Disorder strength
>>> H = xxz_square(5, 1.0, 1.0) + W * magnetic_fields(2.0*np.random.rand(5) - 1.0)
"""
N = len(potentials)
coeffs = 0.5 * potentials
op_strings = [qy.opstring('Z {}'.format(site)) for site in range(N)]
H = qy.Operator(coeffs, op_strings)
return H
def number_ops(H, num_orbitals):
"""Construct the number operators that diagonalize the given
quadratic fermionic tight-binding Hamiltonian.
Parameters
----------
H : qosy.Operator
The quadratic tight-binding Hamiltonian.
num_orbitals : int
The number of orbitals (sites) in the model.
Returns
-------
list of qosy.Operator
The number operators that commute with H.
"""
H_tb = qy.convert(H, 'Fermion')
H_tb = H_tb.remove_zeros(tol=1e-15)
(evals, evecs) = qy.diagonalize_quadratic_tightbinding(H_tb, num_orbitals)
N = num_orbitals
# NOTE: Number operator construction assumes
# that the tight-binding Hamiltonian has only real coefficients.
assert(np.allclose(np.imag(evecs), np.zeros_like(evecs)))
evecs = np.real(evecs)
num_ops = []
for ind_ev in range(N):
coeffs = []
op_strings = []
for orb in range(N):
coeffs.append(np.abs(evecs[orb, ind_ev])**2.0)
op_strings.append(qy.opstring('D {}'.format(orb)))
for orb1 in range(N):
for orb2 in range(orb1+1,N):
coeffs.append(-evecs[orb1, ind_ev] * evecs[orb2, ind_ev])
op_strings.append(qy.opstring('1j A {} B {}'.format(orb1, orb2)))
coeffs.append(+evecs[orb1, ind_ev] * evecs[orb2, ind_ev])
op_strings.append(qy.opstring('1j B {} A {}'.format(orb1, orb2)))
num_op = qy.Operator(coeffs, op_strings, 'Majorana')
num_ops.append(num_op)
return (num_ops, evals)
| [
"numpy.minimum",
"numpy.maximum",
"qosy.convert",
"numpy.zeros_like",
"numpy.abs",
"qosy.diagonalize_quadratic_tightbinding",
"numpy.imag",
"numpy.real",
"qosy.Operator"
] | [((1199, 1230), 'qosy.Operator', 'qy.Operator', (['coeffs', 'op_strings'], {}), '(coeffs, op_strings)\n', (1210, 1230), True, 'import qosy as qy\n'), ((2958, 2989), 'qosy.Operator', 'qy.Operator', (['coeffs', 'op_strings'], {}), '(coeffs, op_strings)\n', (2969, 2989), True, 'import qosy as qy\n'), ((5042, 5073), 'qosy.Operator', 'qy.Operator', (['coeffs', 'op_strings'], {}), '(coeffs, op_strings)\n', (5053, 5073), True, 'import qosy as qy\n'), ((6652, 6683), 'qosy.Operator', 'qy.Operator', (['coeffs', 'op_strings'], {}), '(coeffs, op_strings)\n', (6663, 6683), True, 'import qosy as qy\n'), ((7444, 7475), 'qosy.Operator', 'qy.Operator', (['coeffs', 'op_strings'], {}), '(coeffs, op_strings)\n', (7455, 7475), True, 'import qosy as qy\n'), ((7955, 7979), 'qosy.convert', 'qy.convert', (['H', '"""Fermion"""'], {}), "(H, 'Fermion')\n", (7965, 7979), True, 'import qosy as qy\n'), ((8041, 8098), 'qosy.diagonalize_quadratic_tightbinding', 'qy.diagonalize_quadratic_tightbinding', (['H_tb', 'num_orbitals'], {}), '(H_tb, num_orbitals)\n', (8078, 8098), True, 'import qosy as qy\n'), ((8314, 8328), 'numpy.real', 'np.real', (['evecs'], {}), '(evecs)\n', (8321, 8328), True, 'import numpy as np\n'), ((863, 886), 'numpy.minimum', 'np.minimum', (['site', 'sitep'], {}), '(site, sitep)\n', (873, 886), True, 'import numpy as np\n'), ((900, 923), 'numpy.maximum', 'np.maximum', (['site', 'sitep'], {}), '(site, sitep)\n', (910, 923), True, 'import numpy as np\n'), ((8263, 8277), 'numpy.imag', 'np.imag', (['evecs'], {}), '(evecs)\n', (8270, 8277), True, 'import numpy as np\n'), ((8279, 8299), 'numpy.zeros_like', 'np.zeros_like', (['evecs'], {}), '(evecs)\n', (8292, 8299), True, 'import numpy as np\n'), ((8989, 9032), 'qosy.Operator', 'qy.Operator', (['coeffs', 'op_strings', '"""Majorana"""'], {}), "(coeffs, op_strings, 'Majorana')\n", (9000, 9032), True, 'import qosy as qy\n'), ((2550, 2573), 'numpy.minimum', 'np.minimum', (['site', 'sitep'], {}), '(site, sitep)\n', (2560, 2573), True, 'import numpy as np\n'), ((2599, 2622), 'numpy.maximum', 'np.maximum', (['site', 'sitep'], {}), '(site, sitep)\n', (2609, 2622), True, 'import numpy as np\n'), ((6376, 6399), 'numpy.minimum', 'np.minimum', (['site', 'sitep'], {}), '(site, sitep)\n', (6386, 6399), True, 'import numpy as np\n'), ((6425, 6448), 'numpy.maximum', 'np.maximum', (['site', 'sitep'], {}), '(site, sitep)\n', (6435, 6448), True, 'import numpy as np\n'), ((8482, 8508), 'numpy.abs', 'np.abs', (['evecs[orb, ind_ev]'], {}), '(evecs[orb, ind_ev])\n', (8488, 8508), True, 'import numpy as np\n'), ((4606, 4629), 'numpy.minimum', 'np.minimum', (['site', 'sitep'], {}), '(site, sitep)\n', (4616, 4629), True, 'import numpy as np\n'), ((4659, 4682), 'numpy.maximum', 'np.maximum', (['site', 'sitep'], {}), '(site, sitep)\n', (4669, 4682), True, 'import numpy as np\n')] |
import os
import csv
import cv2
import imutils
import random
import numpy as np
from pprint import pprint
from collections import Counter
from PIL import Image as Img
from PIL import ImageTk
from random import randint
from Tkinter import *
import Tkinter,tkFileDialog, tkMessageBox
meta_path = "./Tournament_Logs/Meta_Information.csv"
def Card_Information_GUI(meta_path):
class Generator_Screen:
PLAYER = " "
TOURNAMENT = " "
bad_exit = True
def Exit_Program(self,event='<Button-1>'):
self.master.destroy()
def Start_Program(self,event='<Button-1>'):
Generator_Screen.PLAYER = self.player_var.get()
Generator_Screen.TOURNAMENT = self.tournament_var.get()
Generator_Screen.bad_exit = False
self.master.destroy()
def Retrieve_Information(self,meta_path):
player_array = ["None"]
tournament_array = ["All"]
with open(meta_path, 'rb') as csvfile:
reader = csv.reader(csvfile,delimiter=',',quotechar='|')
for row in reader:
if row[3] not in tournament_array:
tournament_array.append(row[3])
players = row[5:]
for groups in players:
for people in players:
if people.strip() not in player_array and len(people) > 0:
player_array.append(people.strip())
return player_array,tournament_array
def __init__(self,master):
# configure master window
self.master = master
self.master.resizable(0,0)
master.title('Pump It Up Card Generator')
# creates icon in top left corner
if os.name == 'nt':
self.master.iconbitmap("./Graphics/icon.ico")
p_arr,t_arr = self.Retrieve_Information(meta_path)
self.player_var = StringVar(self.master)
self.tournament_var = StringVar(self.master)
self.player_var.set(p_arr[0])
self.tournament_var.set(t_arr[0])
# TODO: Create file options at top for full gui support
# blank bar at top for "file, edit, view, help" setings
self.File_Options = Tkinter.Frame(self.master, height=25)
self.File_Options.grid(row=0,column=0)
# Images for buttons and splash screen
self.Main_Menu = Tkinter.PhotoImage(file="./Graphics/Generator_Logo.gif")
self.Start = Tkinter.PhotoImage(file="./Graphics/Generate_Card.gif")
self.Exit = Tkinter.PhotoImage(file="./Graphics/Exit_Program.gif")
# splash screen image
self.Selected_Song = Tkinter.Label(self.master, image=self.Main_Menu)
self.Selected_Song.grid(row=1,column=0)
# Contains all buttons and widgets
self.Button_Frame = Tkinter.Frame(self.master, height=90)
self.Button_Frame.grid(row=2,column=0)
# important buttons
self.Command_Options = Tkinter.Frame(self.Button_Frame, height=90)
self.Command_Options.config(bg="WHITE")
self.Command_Options.grid(row=0,column=2,pady=(25,25))
player_text = Tkinter.Label(self.Command_Options, text="Player")
tournament_text = Tkinter.Label(self.Command_Options, text="Tournament")
player_text.configure(font=("TkDefaultFont",20))
tournament_text.configure(font=("TkDefaultFont",20))
player_text.grid(row=0,column=0,sticky=W+E+N+S)
tournament_text.grid(row=0,column=1,sticky=W+E+N+S)
player_menu = Tkinter.OptionMenu(self.Command_Options, self.player_var, *p_arr)
player_menu.config(bg='WHITE')
tournament_menu = Tkinter.OptionMenu(self.Command_Options, self.tournament_var, *t_arr)
tournament_menu.config(bg='WHITE')
player_menu.configure(font=("TkDefaultFont",20))
tournament_menu.configure(font=("TkDefaultFont",20))
player_menu.grid(row=1,column=0,sticky=W+E+N+S)
tournament_menu.grid(row=1,column=1,sticky=W+E+N+S)
# exits program
self.Start_Button = Tkinter.Button(self.Command_Options, image=self.Start, command=self.Start_Program)
self.Start_Button.grid(row=2,column=0,sticky=W+E+N+S)
# exits program
self.Exit_Button = Tkinter.Button(self.Command_Options, image=self.Exit, command=self.Exit_Program)
self.Exit_Button.grid(row=2,column=1,sticky=W+E+N+S)
# hotkeys
self.master.bind("<Return>", self.Start_Program)
self.master.bind("<Escape>", self.Exit_Program)
# starts GUI
Generator_Root = Tkinter.Tk()
Generator_Window = Generator_Screen(Generator_Root)
Generator_Root.mainloop()
return Generator_Screen.PLAYER,Generator_Screen.TOURNAMENT,Generator_Screen.bad_exit
def Generate_Player_Card(PLAYER,TOURNAMENT,meta_path):
def return_song_information(song_array,diff_array,mode_array,player_array,tournament_array,player="All",Tournament="All"):
try:
song_counts = Counter()
level_counts = Counter()
songs = []
levels = []
for i in range(len(song_array)):
if (player in [player_array[i][0].strip(),player_array[i][1].strip()] or player == "All") and Tournament in [tournament_array[i],"All"]:
if mode_array[i] == "Singles":
mode = 'S'
elif mode_array[i] == "Doubles":
mode = 'D'
songs.append(song_array[i])
song_counts[song_array[i]] += 1
level = "%s %s%s" % (song_array[i],mode,diff_array[i])
levels.append(level)
level_counts[level] += 1
sorted_song = sorted(songs, key=lambda x: -song_counts[x])
sorted_level = sorted(levels, key=lambda x: -level_counts[x])
printstring = ["Most Played Song:", "%s. (%d plays)" % (sorted_song[0],song_counts[sorted_song[0]]) ,"Most Played Level:", "%s. (%d plays)" % (sorted_level[0],level_counts[sorted_level[0]])]
return printstring
except:
return []
def return_difficulty_information(diff_array,mode_array,player_array,tournament_array,player="All",Tournament="All"):
try:
player_diff_array = []
player_mode_array = []
for i in range(len(diff_array)):
if (player in [player_array[i][0].strip(),player_array[i][1].strip()] or player == "All") and Tournament in [tournament_array[i],"All"]:
if mode_array[i] == "Singles":
mode = 'S'
elif mode_array[i] == "Doubles":
mode = 'D'
player_diff_array.append(diff_array[i])
player_mode_array.append("%s%d" %(mode,diff_array[i]))
avg_value = sum(player_diff_array)/len(player_diff_array)
highest_difficulty = max(player_diff_array)
diff_counts = Counter()
for elements in player_mode_array:
diff_counts[elements] += 1
sorted_list = sorted(player_mode_array, key=lambda x: -diff_counts[x])
most_played = sorted_list[0]
printstring = ["Average difficulty level: %d." % (avg_value), "Highest difficulty level: %d." % (highest_difficulty), "Most played difficulty: %s. (%d plays)" % (most_played,diff_counts[most_played])]
return printstring
except:
return []
def return_win_rate(winner_array,player_array,tournament_array,player="All",Tournament="All"):
try:
win_counts = Counter()
for i in range(len(winner_array)):
if Tournament in [tournament_array[i],"All"] and player in [player_array[i][0].strip(),player_array[i][1].strip()]:
win_counts[winner_array[i].strip()] += 1
player_counts = Counter()
for i in range(len(player_array)):
if Tournament in [tournament_array[i],"All"]:
for players in player_array[i]:
#print players
player_counts[players.strip()] += 1
#print player_counts
games_won = games_played = 0
for indexes in win_counts:
if indexes == player:
games_won = win_counts[indexes]
break
for indexes in player_counts:
if indexes == player:
games_played = player_counts[indexes]
break
win_percent = (float(games_won)/float(games_played))*100.00
printstring = [ "Number of games played: %d." % (games_played),"Number of games won: %d." % (games_won),
"Average win rate: %.2f%%. (%d wins %d losses)" % (win_percent,games_won,games_played-games_won)]
return printstring
except:
return []
song_array = []
mode_array = []
diff_array = []
tournament_array = []
winner_array = []
player_array = []
with open(meta_path, 'rb') as csvfile:
reader = csv.reader(csvfile,delimiter=',',quotechar='|')
for row in reader:
song_array.append(row[0])
mode_array.append(row[1])
diff_array.append(int(row[2]))
tournament_array.append(row[3])
winner_array.append(row[4])
player_array.append([players for players in row[5:] if len(players) > 0])
height = 780
width = 640
filler_string = ''
for characters in PLAYER:
filler_string += "="
filler_string = filler_string [:-2]
song_info = return_song_information(song_array,diff_array,mode_array,player_array,tournament_array,PLAYER,TOURNAMENT)
diff_info = return_difficulty_information(diff_array,mode_array,player_array,tournament_array,PLAYER,TOURNAMENT)
win_info = return_win_rate(winner_array,player_array,tournament_array,PLAYER,TOURNAMENT)
splash_array = ["./Graphics/Top_Generator_1.jpg","./Graphics/Top_Generator_2.jpg"]
splash_path = random.choice(splash_array)
accent_array = [(78,116,16),(32,6,96)]
accent_color = accent_array[splash_array.index(splash_path)]
logo_path = "./Graphics/Prime2_Logo.png"
splash_image = cv2.imread(splash_path)
logo_image = cv2.imread(logo_path)
splash_image = imutils.resize(splash_image,width=width)
logo_image = imutils.resize(logo_image,width=100)
blank_image = np.zeros((height,width,3), np.uint8)
blank_image[0:splash_image.shape[0], 0:splash_image.shape[1]] = splash_image
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 0.75
fontColor = (255,255,255)
lineType = 2
cv2.rectangle(blank_image,(25,25),(25+275,splash_image.shape[0]-25),(0,0,0),-1)
cv2.rectangle(blank_image,(25,25),(25+275,splash_image.shape[0]-25),(255,255,255),3)
for j in range(logo_image.shape[0]):
for i in range(logo_image.shape[1]):
if logo_image[j][i][0] != 0 or logo_image[j][i][1] != 0 or logo_image[j][i][2] != 0:
blank_image[j][i+25][0] = logo_image[j][i][0]
blank_image[j][i+25][1] = logo_image[j][i][1]
blank_image[j][i+25][2] = logo_image[j][i][2]
cv2.putText(blank_image,PLAYER, (50,100),font,2*fontScale,fontColor,lineType*2)
y_offset = 25+splash_image.shape[0]
#cv2.rectangle(blank_image,(0,25+y_offset),(width,65+y_offset),accent_color,-1)
if TOURNAMENT == "All":
tournament_info = "Lifetime Record"
TOURNAMENT = "Lifetime_Record"
else:
tournament_info = "Tournament: %s" % TOURNAMENT
sublist = ''
for elements in TOURNAMENT:
if elements != ' ':
sublist += elements
else:
sublist += '-'
TOURNAMENT = sublist
cv2.rectangle(blank_image,(0,y_offset-25),(width,40+y_offset-25),accent_color,-1)
cv2.putText(blank_image,tournament_info, (10,y_offset),font,fontScale,fontColor,lineType)
y_offset += 40
for elements in win_info:
cv2.putText(blank_image,elements,(10,y_offset),font,fontScale,fontColor,lineType)
y_offset += 40
y_offset += 40
for elements in song_info:
if "Most" in elements:
cv2.rectangle(blank_image,(0,y_offset-25),(width,40+y_offset-25),accent_color,-1)
cv2.putText(blank_image,elements, (10,y_offset),font,fontScale,fontColor,lineType)
y_offset += 40
else:
cv2.putText(blank_image,elements, (10,y_offset),font,fontScale,fontColor,lineType)
y_offset += 80
#y_offset += 40
cv2.rectangle(blank_image,(0,y_offset-25),(width,40+y_offset-25),accent_color,-1)
cv2.putText(blank_image,"Song Difficulties:",(10,y_offset),font,fontScale,fontColor,lineType)
y_offset += 40
for elements in diff_info:
cv2.putText(blank_image,elements,(10,y_offset),font,fontScale,fontColor,lineType)
y_offset += 40
y_offset += 40
cv2.imwrite("./Player_Cards/%s_%s.jpg" % (PLAYER,TOURNAMENT), blank_image)
cv2.imshow("Frame",blank_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
PLAYER, TOURNAMENT,CONTINUE = Card_Information_GUI(meta_path)
if not CONTINUE:
Generate_Player_Card(PLAYER,TOURNAMENT,meta_path) | [
"cv2.putText",
"csv.reader",
"Tkinter.Tk",
"cv2.waitKey",
"cv2.imwrite",
"cv2.destroyAllWindows",
"Tkinter.Frame",
"numpy.zeros",
"random.choice",
"Tkinter.PhotoImage",
"Tkinter.Label",
"Tkinter.OptionMenu",
"cv2.imread",
"cv2.rectangle",
"imutils.resize",
"collections.Counter",
"cv2... | [((4097, 4109), 'Tkinter.Tk', 'Tkinter.Tk', ([], {}), '()\n', (4107, 4109), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((8756, 8783), 'random.choice', 'random.choice', (['splash_array'], {}), '(splash_array)\n', (8769, 8783), False, 'import random\n'), ((8946, 8969), 'cv2.imread', 'cv2.imread', (['splash_path'], {}), '(splash_path)\n', (8956, 8969), False, 'import cv2\n'), ((8984, 9005), 'cv2.imread', 'cv2.imread', (['logo_path'], {}), '(logo_path)\n', (8994, 9005), False, 'import cv2\n'), ((9023, 9064), 'imutils.resize', 'imutils.resize', (['splash_image'], {'width': 'width'}), '(splash_image, width=width)\n', (9037, 9064), False, 'import imutils\n'), ((9078, 9115), 'imutils.resize', 'imutils.resize', (['logo_image'], {'width': '(100)'}), '(logo_image, width=100)\n', (9092, 9115), False, 'import imutils\n'), ((9130, 9168), 'numpy.zeros', 'np.zeros', (['(height, width, 3)', 'np.uint8'], {}), '((height, width, 3), np.uint8)\n', (9138, 9168), True, 'import numpy as np\n'), ((9398, 9493), 'cv2.rectangle', 'cv2.rectangle', (['blank_image', '(25, 25)', '(25 + 275, splash_image.shape[0] - 25)', '(0, 0, 0)', '(-1)'], {}), '(blank_image, (25, 25), (25 + 275, splash_image.shape[0] - 25),\n (0, 0, 0), -1)\n', (9411, 9493), False, 'import cv2\n'), ((9479, 9579), 'cv2.rectangle', 'cv2.rectangle', (['blank_image', '(25, 25)', '(25 + 275, splash_image.shape[0] - 25)', '(255, 255, 255)', '(3)'], {}), '(blank_image, (25, 25), (25 + 275, splash_image.shape[0] - 25),\n (255, 255, 255), 3)\n', (9492, 9579), False, 'import cv2\n'), ((9884, 9977), 'cv2.putText', 'cv2.putText', (['blank_image', 'PLAYER', '(50, 100)', 'font', '(2 * fontScale)', 'fontColor', '(lineType * 2)'], {}), '(blank_image, PLAYER, (50, 100), font, 2 * fontScale, fontColor,\n lineType * 2)\n', (9895, 9977), False, 'import cv2\n'), ((10382, 10479), 'cv2.rectangle', 'cv2.rectangle', (['blank_image', '(0, y_offset - 25)', '(width, 40 + y_offset - 25)', 'accent_color', '(-1)'], {}), '(blank_image, (0, y_offset - 25), (width, 40 + y_offset - 25),\n accent_color, -1)\n', (10395, 10479), False, 'import cv2\n'), ((10465, 10564), 'cv2.putText', 'cv2.putText', (['blank_image', 'tournament_info', '(10, y_offset)', 'font', 'fontScale', 'fontColor', 'lineType'], {}), '(blank_image, tournament_info, (10, y_offset), font, fontScale,\n fontColor, lineType)\n', (10476, 10564), False, 'import cv2\n'), ((11087, 11184), 'cv2.rectangle', 'cv2.rectangle', (['blank_image', '(0, y_offset - 25)', '(width, 40 + y_offset - 25)', 'accent_color', '(-1)'], {}), '(blank_image, (0, y_offset - 25), (width, 40 + y_offset - 25),\n accent_color, -1)\n', (11100, 11184), False, 'import cv2\n'), ((11170, 11274), 'cv2.putText', 'cv2.putText', (['blank_image', '"""Song Difficulties:"""', '(10, y_offset)', 'font', 'fontScale', 'fontColor', 'lineType'], {}), "(blank_image, 'Song Difficulties:', (10, y_offset), font,\n fontScale, fontColor, lineType)\n", (11181, 11274), False, 'import cv2\n'), ((11429, 11504), 'cv2.imwrite', 'cv2.imwrite', (["('./Player_Cards/%s_%s.jpg' % (PLAYER, TOURNAMENT))", 'blank_image'], {}), "('./Player_Cards/%s_%s.jpg' % (PLAYER, TOURNAMENT), blank_image)\n", (11440, 11504), False, 'import cv2\n'), ((11505, 11537), 'cv2.imshow', 'cv2.imshow', (['"""Frame"""', 'blank_image'], {}), "('Frame', blank_image)\n", (11515, 11537), False, 'import cv2\n'), ((11538, 11552), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (11549, 11552), False, 'import cv2\n'), ((11554, 11577), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (11575, 11577), False, 'import cv2\n'), ((7892, 7941), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""', 'quotechar': '"""|"""'}), "(csvfile, delimiter=',', quotechar='|')\n", (7902, 7941), False, 'import csv\n'), ((10600, 10692), 'cv2.putText', 'cv2.putText', (['blank_image', 'elements', '(10, y_offset)', 'font', 'fontScale', 'fontColor', 'lineType'], {}), '(blank_image, elements, (10, y_offset), font, fontScale,\n fontColor, lineType)\n', (10611, 10692), False, 'import cv2\n'), ((11310, 11402), 'cv2.putText', 'cv2.putText', (['blank_image', 'elements', '(10, y_offset)', 'font', 'fontScale', 'fontColor', 'lineType'], {}), '(blank_image, elements, (10, y_offset), font, fontScale,\n fontColor, lineType)\n', (11321, 11402), False, 'import cv2\n'), ((1926, 1963), 'Tkinter.Frame', 'Tkinter.Frame', (['self.master'], {'height': '(25)'}), '(self.master, height=25)\n', (1939, 1963), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((2072, 2128), 'Tkinter.PhotoImage', 'Tkinter.PhotoImage', ([], {'file': '"""./Graphics/Generator_Logo.gif"""'}), "(file='./Graphics/Generator_Logo.gif')\n", (2090, 2128), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((2145, 2200), 'Tkinter.PhotoImage', 'Tkinter.PhotoImage', ([], {'file': '"""./Graphics/Generate_Card.gif"""'}), "(file='./Graphics/Generate_Card.gif')\n", (2163, 2200), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((2216, 2270), 'Tkinter.PhotoImage', 'Tkinter.PhotoImage', ([], {'file': '"""./Graphics/Exit_Program.gif"""'}), "(file='./Graphics/Exit_Program.gif')\n", (2234, 2270), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((2324, 2372), 'Tkinter.Label', 'Tkinter.Label', (['self.master'], {'image': 'self.Main_Menu'}), '(self.master, image=self.Main_Menu)\n', (2337, 2372), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((2478, 2515), 'Tkinter.Frame', 'Tkinter.Frame', (['self.master'], {'height': '(90)'}), '(self.master, height=90)\n', (2491, 2515), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((2611, 2654), 'Tkinter.Frame', 'Tkinter.Frame', (['self.Button_Frame'], {'height': '(90)'}), '(self.Button_Frame, height=90)\n', (2624, 2654), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((2777, 2827), 'Tkinter.Label', 'Tkinter.Label', (['self.Command_Options'], {'text': '"""Player"""'}), "(self.Command_Options, text='Player')\n", (2790, 2827), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((2849, 2903), 'Tkinter.Label', 'Tkinter.Label', (['self.Command_Options'], {'text': '"""Tournament"""'}), "(self.Command_Options, text='Tournament')\n", (2862, 2903), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((3135, 3200), 'Tkinter.OptionMenu', 'Tkinter.OptionMenu', (['self.Command_Options', 'self.player_var', '*p_arr'], {}), '(self.Command_Options, self.player_var, *p_arr)\n', (3153, 3200), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((3256, 3325), 'Tkinter.OptionMenu', 'Tkinter.OptionMenu', (['self.Command_Options', 'self.tournament_var', '*t_arr'], {}), '(self.Command_Options, self.tournament_var, *t_arr)\n', (3274, 3325), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((3624, 3711), 'Tkinter.Button', 'Tkinter.Button', (['self.Command_Options'], {'image': 'self.Start', 'command': 'self.Start_Program'}), '(self.Command_Options, image=self.Start, command=self.\n Start_Program)\n', (3638, 3711), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((3805, 3890), 'Tkinter.Button', 'Tkinter.Button', (['self.Command_Options'], {'image': 'self.Exit', 'command': 'self.Exit_Program'}), '(self.Command_Options, image=self.Exit, command=self.Exit_Program\n )\n', (3819, 3890), False, 'import Tkinter, tkFileDialog, tkMessageBox\n'), ((4480, 4489), 'collections.Counter', 'Counter', ([], {}), '()\n', (4487, 4489), False, 'from collections import Counter\n'), ((4508, 4517), 'collections.Counter', 'Counter', ([], {}), '()\n', (4515, 4517), False, 'from collections import Counter\n'), ((6108, 6117), 'collections.Counter', 'Counter', ([], {}), '()\n', (6115, 6117), False, 'from collections import Counter\n'), ((6671, 6680), 'collections.Counter', 'Counter', ([], {}), '()\n', (6678, 6680), False, 'from collections import Counter\n'), ((6908, 6917), 'collections.Counter', 'Counter', ([], {}), '()\n', (6915, 6917), False, 'from collections import Counter\n'), ((10771, 10868), 'cv2.rectangle', 'cv2.rectangle', (['blank_image', '(0, y_offset - 25)', '(width, 40 + y_offset - 25)', 'accent_color', '(-1)'], {}), '(blank_image, (0, y_offset - 25), (width, 40 + y_offset - 25),\n accent_color, -1)\n', (10784, 10868), False, 'import cv2\n'), ((10856, 10948), 'cv2.putText', 'cv2.putText', (['blank_image', 'elements', '(10, y_offset)', 'font', 'fontScale', 'fontColor', 'lineType'], {}), '(blank_image, elements, (10, y_offset), font, fontScale,\n fontColor, lineType)\n', (10867, 10948), False, 'import cv2\n'), ((10968, 11060), 'cv2.putText', 'cv2.putText', (['blank_image', 'elements', '(10, y_offset)', 'font', 'fontScale', 'fontColor', 'lineType'], {}), '(blank_image, elements, (10, y_offset), font, fontScale,\n fontColor, lineType)\n', (10979, 11060), False, 'import cv2\n'), ((902, 951), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""', 'quotechar': '"""|"""'}), "(csvfile, delimiter=',', quotechar='|')\n", (912, 951), False, 'import csv\n')] |
"""
Global variables for the package
"""
__author__ = 'martinez'
import numpy as np
MAX_FLOAT = np.finfo(np.float).max
NO_CONNECTION = -1
STR_2GT_EL = 'edge_length'
STR_CELL = 'cell_id'
STR_2FIL_LEN = 'fil_len'
STR_2FIL_CT = 'fil_ct'
STR_2FIL_SIN = 'fil_sin'
STR_2FIL_SMO = 'fil_smooth'
STR_2FIL_MC = 'fil_mc'
WRN_RED = '\033[93m'
CSQRT_EXP = 1. / 3. | [
"numpy.finfo"
] | [((105, 123), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (113, 123), True, 'import numpy as np\n')] |
import AlphaBase as AlphaBase
import os
import numpy as np
class LanguageSource(object):
""" A class for training data.
"""
def __init__(self, alpha_set: AlphaBase):
""" Constructor, must be constructed after alpha_set is computed.
:param alpha_set: information about the characters used in the languages.
"""
self.language_file_id = {}
self.language_name_to_index = {}
self.language_index_to_name = {}
self.alpha_set = alpha_set
self.current_language_id = 0
self.num_languages = 0
pass
def begin(self, data_dir):
""" Create data structures for reading data
:param data_dir: the base directory of the data, one file per language
:return:
"""
for ix, file in enumerate(os.listdir(data_dir)):
lang_name = file.split('-')[1].split('.')[0] # get the language's name (string representation)
full_file_name = data_dir + '/' + file
self.language_file_id[lang_name] = open(full_file_name, 'r')
self.language_name_to_index[lang_name] = ix
self.language_index_to_name[ix] = lang_name
self.num_languages = len(self.language_file_id)
@staticmethod
def read_with_restart(fh, read_len):
""" read a string from the data file. If it is at the end of the file then seek back to the beginning.
:param fh:
:param read_len:
:return: a string from the data.
"""
ft1 = fh.tell()
r_data = fh.read(read_len)
ft2 = fh.tell()
if ft1 == ft2:
print('End of file found on:', fh)
fh.seek(0)
r_data = fh.read(read_len)
return r_data
def get_next_batch(self, batch_size: int, seq_len) -> ([str], [str]):
""" Retrun a list of strings from the data set.
:param batch_size: the number of strings to return.
:param seq_len: the length of each string.
:return: a list of strings. Each string is from a language found sequentially.
"""
lang_str_list = []
lang_id_list = []
for bi in range(batch_size):
# get the next language id and update it for the cycle
lang_id = self.current_language_id
self.current_language_id += 1
if self.current_language_id >= self.num_languages:
self.current_language_id = 0
# Get the file handle for the language and read from it.
lang_name = self.language_index_to_name[lang_id]
fd = self.language_file_id[lang_name]
lang_str = self.alpha_set.filter(self.read_with_restart(fd, seq_len))
# Continue reading until a string of the correct length is created
while len(lang_str) < seq_len:
rem = seq_len - len(lang_str)
lang_str += self.alpha_set.filter(self.read_with_restart(fd, rem))
lang_str_list.append(lang_str)
lang_id_list.append(lang_id)
return lang_str_list, lang_id_list
def get_next_batch_one_hot(self, batch_size: int, seq_len):
batch_x, batch_y = self.get_next_batch(batch_size, seq_len)
# one-hot encode the strings, batch_xs = [n_step x batch_size x n_input]
batch_xs = self.get_ml_data_matrix(self.alpha_set.alpha_compressed_size, batch_x)
# one-hot encode the languages ids of each string, batch_ys = [n_step x batch_size x n_classes]
batch_ys = self.get_class_rep(batch_y, self.num_languages)
return batch_xs, batch_ys
def get_ml_data_matrix(self, n_char: int, lang_strings: [str]):
""" Return a numpy matrix representing the list of strings in lang_str.
Each character of the strings in lang_string is represented by a one-hot encoding vector
Each string is then a concatenation of the one-hot vectors.
:param n_char:
:param lang_strings: a list of strings to find representations for
:return: a numpy matrix with a row for each string in lang_string
"""
n = len(lang_strings)
m = len(lang_strings[0]) # each string is the same length
# Create the empty matrix. Each row is a string. Each row has m one-hot vectors, each of length n_char.
rep_mat = np.zeros((m, n, n_char), dtype=np.float32)
for i, str_x in enumerate(lang_strings):
for j, char in enumerate(str_x):
rep = self.alpha_set.get_alpha_index(char) # look up the characters integer representation
rep_mat[j, i, rep] = 1 # set the one-hot bit in the vector for 'char' in string 'str_x'
return rep_mat
@staticmethod
def get_class_rep(class_id_list, n_class):
""" Get the one-hot representation matrix of a list of class indices.
:param class_id_list:
:param n_class: maximum number of classes
:return: a matrix of one-hot vectors. Each row is a one-hot vector.
"""
n_class_id = len(class_id_list)
class_vec = np.zeros((n_class_id, n_class), dtype=np.float32)
for i, class_id in enumerate(class_id_list):
class_vec[i, class_id] = 1
return class_vec
@staticmethod
def self_test():
ab = AlphaBase.AlphaBase.load_object_from_file('alpha_dog.pk')
ls = LanguageSource(ab)
ls.begin('/Users/frank/data/LanguageDetectionModel/exp_data_test')
# x, y = ls.get_next_batch(420, 32)
# for x1, y1 in zip(x, y):
# print(y1, x1, len(x1))
# bs = 64
# for i in range(10000000):
# x, y = ls.get_next_batch(bs, 128)
# if i % 1000 == 0:
# print(i, (i+1)*bs)
print('test complete.')
# LanguageSource.self_test()
| [
"AlphaBase.AlphaBase.load_object_from_file",
"numpy.zeros",
"os.listdir"
] | [((4304, 4346), 'numpy.zeros', 'np.zeros', (['(m, n, n_char)'], {'dtype': 'np.float32'}), '((m, n, n_char), dtype=np.float32)\n', (4312, 4346), True, 'import numpy as np\n'), ((5049, 5098), 'numpy.zeros', 'np.zeros', (['(n_class_id, n_class)'], {'dtype': 'np.float32'}), '((n_class_id, n_class), dtype=np.float32)\n', (5057, 5098), True, 'import numpy as np\n'), ((5269, 5326), 'AlphaBase.AlphaBase.load_object_from_file', 'AlphaBase.AlphaBase.load_object_from_file', (['"""alpha_dog.pk"""'], {}), "('alpha_dog.pk')\n", (5310, 5326), True, 'import AlphaBase as AlphaBase\n'), ((807, 827), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (817, 827), False, 'import os\n')] |
from vocoder.models.fatchord_version import WaveRNN
from vocoder.vocoder_dataset import VocoderDataset, collate_vocoder
from vocoder.distribution import discretized_mix_logistic_loss
from vocoder.display import stream, simple_table
from vocoder.gen_wavernn import gen_testset
from torch.utils.data import DataLoader
from pathlib import Path
from torch import optim
import torch.nn.functional as F
import vocoder.hparams as hp
import numpy as np
import time
from vocoder.model_vc import *
import torch.nn as nn
from vocoder.griffin_lin import *
import scipy
import matplotlib.pyplot as plt
import torch
def _learning_rate_decay(init_lr, global_step):
# Noam scheme from tensor2tensor:
warmup_steps = 4000.0
step = torch.tensor(global_step + 1, dtype=torch.float32)
return init_lr * warmup_steps**0.5 * torch.min(step * warmup_steps**-1.5, step**-0.5)
def train(run_id: str, syn_dir: Path, voc_dir: Path, models_dir: Path, ground_truth: bool,
save_every: int, backup_every: int, force_restart: bool):
# Check to make sure the hop length is correctly factorised
# assert np.cumprod(hp.voc_upsample_factors)[-1] == hp.hop_length
# Instantiate the model
print("Initializing the model...")
# model = WaveRNN(
# rnn_dims=hp.voc_rnn_dims,
# fc_dims=hp.voc_fc_dims,
# bits=hp.bits,
# pad=hp.voc_pad,
# upsample_factors=hp.voc_upsample_factors,
# feat_dims=hp.num_mels,
# compute_dims=hp.voc_compute_dims,
# res_out_dims=hp.voc_res_out_dims,
# res_blocks=hp.voc_res_blocks,
# hop_length=hp.hop_length,
# sample_rate=hp.sample_rate,
# mode=hp.voc_mode
# ).cuda()
model= model_VC(32,256,512,32).cuda()
# Initialize the optimizer
optimizer = optim.Adam(model.parameters())
for p in optimizer.param_groups:
p["lr"] = hp.voc_lr
loss_recon = nn.MSELoss()
loss_content=nn.L1Loss()
# Load the weights
model_dir = models_dir.joinpath(run_id)
model_dir.mkdir(exist_ok=True)
weights_fpath = model_dir.joinpath(run_id + ".pt")
if force_restart or not weights_fpath.exists():
print("\nStarting the training of AutoVC from scratch\n")
model.save(weights_fpath, optimizer)
else:
print("\nLoading weights at %s" % weights_fpath)
model.load(weights_fpath, optimizer)
print("AutoVC weights loaded from step %d" % model.step)
# Initialize the dataset
metadata_fpath = syn_dir.joinpath("train.txt") if ground_truth else \
voc_dir.joinpath("synthesized.txt")
mel_dir = syn_dir.joinpath("mels") if ground_truth else voc_dir.joinpath("mels_gta")
wav_dir = syn_dir.joinpath("audio")
#2019.11.26
embed_dir=syn_dir.joinpath("embeds")
dataset = VocoderDataset(metadata_fpath, mel_dir, wav_dir,embed_dir)
test_loader = DataLoader(dataset,
batch_size=1,
shuffle=True,
pin_memory=True)
# Begin the training
simple_table([('Batch size', hp.voc_batch_size),
('LR', hp.voc_lr),
('Sequence Len', hp.voc_seq_len)])
for epoch in range(1, 350):
model.train()
data_loader = DataLoader(dataset,
collate_fn=collate_vocoder,
batch_size=hp.voc_batch_size,
num_workers=2,
shuffle=True,
pin_memory=True)
start = time.time()
running_loss = 0.
for i, (m, e,_) in enumerate(data_loader, 1):
#print("e:",e.shape)
#print("m:",m.shape)
model.train()
m, e= m.cuda(), e.cuda()
# Forward pass
C,X_C,X_before,X_after,_ = model(m, e,e)
#c_org shape: torch.Size([100, 256, 1])
#x shape: torch.Size([100, 80, 544])
#c_org_expand shape torch.Size([100, 256, 544])
#encoder_outputs shape: torch.Size([100, 544, 320])
#C shape: torch.Size([100, 544, 64])
#X shape: torch.Size([100, 1, 544, 80])
X_after = X_after.squeeze(1).permute(0,2,1)
X_before = X_before.squeeze(1).permute(0,2,1)
#print("C shape:",C.shape)
#if X_C:
# print("X_C shape:",X_C.shape)
#print("X shape:",X.shape)
# Backward pass
loss_rec_before = loss_recon(X_before,m)
loss_rec_after = loss_recon(X_after, m)
loss_c=loss_content(C,X_C)
loss = loss_rec_before + loss_rec_after + loss_c
#print("recon loss:",loss1)
#print("content loss:",loss2)
optimizer.zero_grad()
loss.backward()
optimizer.step()
#print("loss:",loss.item())
running_loss += loss.item()
#print("running loss:",running_loss)
speed = i / (time.time() - start)
avg_loss = running_loss / i
#print("avg_loss:",avg_loss)
step = model.get_step()
if hp.decay_learning_rate==True:
p["lr"]=_learning_rate_decay(p["lr"], step)
k = step // 1000
if step%100==0 and step !=0:
model.eval()
plt.figure(1)
C,X_C,X_before,X_after,_ = model(m, e,e)
X_after = X_after.squeeze(1).permute(0,2,1)
mel_out=torch.tensor(X_after).clone().detach().cpu().numpy()
from synthesizer import audio
from synthesizer.hparams import hparams
wav = audio.inv_mel_spectrogram(mel_out[0,:,:], hparams)
librosa.output.write_wav("out.wav", np.float32(wav),hparams.sample_rate)
mel_out=mel_out[0,:,:].transpose(1,0)
plt.imshow(mel_out.T, interpolation='nearest', aspect='auto')
plt.title("Generate Spectrogram")
save_path=model_dir
p_path=save_path.joinpath("generate.png")
plt.savefig(p_path)
plt.figure(2)
m_out=m.squeeze(1).permute(0,2,1)
m_out=torch.tensor(m).clone().detach().cpu().numpy()
m_out=m_out[0,:,:].transpose(1,0)
plt.imshow(m_out.T, interpolation='nearest', aspect='auto')
plt.title("Orignal Spectrogram")
o_path=save_path.joinpath("orignal.png")
plt.savefig(o_path)
if backup_every != 0 and step % backup_every == 0 :
model.checkpoint(model_dir, optimizer)
if save_every != 0 and step % save_every == 0 :
model.save(weights_fpath, optimizer)
torch.save(model,"model_ttsdb_48_48.pkl")
msg = f"| Epoch: {epoch} ({i}/{len(data_loader)}) | " \
f"Loss: {avg_loss:.4f} | {speed:.1f} " \
f"steps/s | Step: {k}k | "
stream(msg)
# gen_testset(model, test_loader, hp.voc_gen_at_checkpoint, hp.voc_gen_batched,hp.voc_target,model_dir)
print("")
| [
"matplotlib.pyplot.title",
"synthesizer.audio.inv_mel_spectrogram",
"torch.nn.MSELoss",
"vocoder.display.stream",
"matplotlib.pyplot.savefig",
"torch.utils.data.DataLoader",
"torch.nn.L1Loss",
"matplotlib.pyplot.imshow",
"numpy.float32",
"time.time",
"torch.save",
"matplotlib.pyplot.figure",
... | [((749, 799), 'torch.tensor', 'torch.tensor', (['(global_step + 1)'], {'dtype': 'torch.float32'}), '(global_step + 1, dtype=torch.float32)\n', (761, 799), False, 'import torch\n'), ((1953, 1965), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (1963, 1965), True, 'import torch.nn as nn\n'), ((1984, 1995), 'torch.nn.L1Loss', 'nn.L1Loss', ([], {}), '()\n', (1993, 1995), True, 'import torch.nn as nn\n'), ((2867, 2926), 'vocoder.vocoder_dataset.VocoderDataset', 'VocoderDataset', (['metadata_fpath', 'mel_dir', 'wav_dir', 'embed_dir'], {}), '(metadata_fpath, mel_dir, wav_dir, embed_dir)\n', (2881, 2926), False, 'from vocoder.vocoder_dataset import VocoderDataset, collate_vocoder\n'), ((2945, 3009), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': '(1)', 'shuffle': '(True)', 'pin_memory': '(True)'}), '(dataset, batch_size=1, shuffle=True, pin_memory=True)\n', (2955, 3009), False, 'from torch.utils.data import DataLoader\n'), ((3133, 3240), 'vocoder.display.simple_table', 'simple_table', (["[('Batch size', hp.voc_batch_size), ('LR', hp.voc_lr), ('Sequence Len', hp.\n voc_seq_len)]"], {}), "([('Batch size', hp.voc_batch_size), ('LR', hp.voc_lr), (\n 'Sequence Len', hp.voc_seq_len)])\n", (3145, 3240), False, 'from vocoder.display import stream, simple_table\n'), ((842, 894), 'torch.min', 'torch.min', (['(step * warmup_steps ** -1.5)', '(step ** -0.5)'], {}), '(step * warmup_steps ** -1.5, step ** -0.5)\n', (851, 894), False, 'import torch\n'), ((3362, 3490), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'collate_fn': 'collate_vocoder', 'batch_size': 'hp.voc_batch_size', 'num_workers': '(2)', 'shuffle': '(True)', 'pin_memory': '(True)'}), '(dataset, collate_fn=collate_vocoder, batch_size=hp.\n voc_batch_size, num_workers=2, shuffle=True, pin_memory=True)\n', (3372, 3490), False, 'from torch.utils.data import DataLoader\n'), ((3673, 3684), 'time.time', 'time.time', ([], {}), '()\n', (3682, 3684), False, 'import time\n'), ((7304, 7315), 'vocoder.display.stream', 'stream', (['msg'], {}), '(msg)\n', (7310, 7315), False, 'from vocoder.display import stream, simple_table\n'), ((5563, 5576), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (5573, 5576), True, 'import matplotlib.pyplot as plt\n'), ((5903, 5955), 'synthesizer.audio.inv_mel_spectrogram', 'audio.inv_mel_spectrogram', (['mel_out[0, :, :]', 'hparams'], {}), '(mel_out[0, :, :], hparams)\n', (5928, 5955), False, 'from synthesizer import audio\n'), ((6118, 6179), 'matplotlib.pyplot.imshow', 'plt.imshow', (['mel_out.T'], {'interpolation': '"""nearest"""', 'aspect': '"""auto"""'}), "(mel_out.T, interpolation='nearest', aspect='auto')\n", (6128, 6179), True, 'import matplotlib.pyplot as plt\n'), ((6197, 6230), 'matplotlib.pyplot.title', 'plt.title', (['"""Generate Spectrogram"""'], {}), "('Generate Spectrogram')\n", (6206, 6230), True, 'import matplotlib.pyplot as plt\n'), ((6344, 6363), 'matplotlib.pyplot.savefig', 'plt.savefig', (['p_path'], {}), '(p_path)\n', (6355, 6363), True, 'import matplotlib.pyplot as plt\n'), ((6383, 6396), 'matplotlib.pyplot.figure', 'plt.figure', (['(2)'], {}), '(2)\n', (6393, 6396), True, 'import matplotlib.pyplot as plt\n'), ((6586, 6645), 'matplotlib.pyplot.imshow', 'plt.imshow', (['m_out.T'], {'interpolation': '"""nearest"""', 'aspect': '"""auto"""'}), "(m_out.T, interpolation='nearest', aspect='auto')\n", (6596, 6645), True, 'import matplotlib.pyplot as plt\n'), ((6663, 6695), 'matplotlib.pyplot.title', 'plt.title', (['"""Orignal Spectrogram"""'], {}), "('Orignal Spectrogram')\n", (6672, 6695), True, 'import matplotlib.pyplot as plt\n'), ((6771, 6790), 'matplotlib.pyplot.savefig', 'plt.savefig', (['o_path'], {}), '(o_path)\n', (6782, 6790), True, 'import matplotlib.pyplot as plt\n'), ((7076, 7118), 'torch.save', 'torch.save', (['model', '"""model_ttsdb_48_48.pkl"""'], {}), "(model, 'model_ttsdb_48_48.pkl')\n", (7086, 7118), False, 'import torch\n'), ((5182, 5193), 'time.time', 'time.time', ([], {}), '()\n', (5191, 5193), False, 'import time\n'), ((6007, 6022), 'numpy.float32', 'np.float32', (['wav'], {}), '(wav)\n', (6017, 6022), True, 'import numpy as np\n'), ((5721, 5742), 'torch.tensor', 'torch.tensor', (['X_after'], {}), '(X_after)\n', (5733, 5742), False, 'import torch\n'), ((6471, 6486), 'torch.tensor', 'torch.tensor', (['m'], {}), '(m)\n', (6483, 6486), False, 'import torch\n')] |
import timeit
import pandas as pd
import matplotlib.pyplot
from sklearn.linear_model import base
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from line_profiler import LineProfiler
import numpy as np
from utility import ols_lstsq, ols_sklearn
# We learn that
#https://github.com/scikit-learn/scikit-learn/blob/1495f6924/sklearn/linear_model/base.py#L438
# LinearRegression.fit is expensive because
# of calls to check_X_y, _preprocess_data and linalg.lstsq
# https://github.com/scikit-learn/scikit-learn/blob/1495f6924/sklearn/linear_model/base.py#L101
# _preprocess_data
# has 3 expensive lines - check_array, np.asarray, np.average
#https://github.com/scikit-learn/scikit-learn/blob/1495f69242646d239d89a5713982946b8ffcf9d9/sklearn/utils/validation.py#L600
# check_X_y
# checks for array for certain characteristics and lengths
#
df = pd.read_pickle('generated_ols_data.pickle')
print(f"Loaded {df.shape} rows")
est = LinearRegression()
row = df.iloc[0]
X = np.arange(row.shape[0]).reshape(-1, 1).astype(np.float_)
lp = LineProfiler(est.fit)
print("Run on a single row")
lp.run("est.fit(X, row.values)")
lp.print_stats()
print("Run on 5000 rows")
lp.run("df[:5000].apply(ols_sklearn, axis=1)")
lp.print_stats()
lp = LineProfiler(base._preprocess_data)
lp.run("base._preprocess_data(X, row, fit_intercept=True)")
lp.print_stats()
lp = LineProfiler(base.check_X_y)
lp.run("base.check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'], y_numeric=True, multi_output=True)")
lp.print_stats()
#%lprun -f est_diagnosis.fit est_diagnosis.fit(np.arange(rowx.shape[0]).reshape(-1, 1), rowx.values)
#lp.run("est_diagnosis.fit(np.arange(rowx.shape[0]).reshape(-1, 1).astype(np.float_), y.values)")
#lp.run("base._preprocess_data(np.arange(rowx.shape[0]).reshape(-1, 1).astype(np.float_), rowx, fit_intercept=True)")
| [
"pandas.read_pickle",
"numpy.arange",
"line_profiler.LineProfiler",
"sklearn.linear_model.LinearRegression"
] | [((879, 922), 'pandas.read_pickle', 'pd.read_pickle', (['"""generated_ols_data.pickle"""'], {}), "('generated_ols_data.pickle')\n", (893, 922), True, 'import pandas as pd\n'), ((963, 981), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (979, 981), False, 'from sklearn.linear_model import LinearRegression\n'), ((1066, 1087), 'line_profiler.LineProfiler', 'LineProfiler', (['est.fit'], {}), '(est.fit)\n', (1078, 1087), False, 'from line_profiler import LineProfiler\n'), ((1264, 1299), 'line_profiler.LineProfiler', 'LineProfiler', (['base._preprocess_data'], {}), '(base._preprocess_data)\n', (1276, 1299), False, 'from line_profiler import LineProfiler\n'), ((1383, 1411), 'line_profiler.LineProfiler', 'LineProfiler', (['base.check_X_y'], {}), '(base.check_X_y)\n', (1395, 1411), False, 'from line_profiler import LineProfiler\n'), ((1003, 1026), 'numpy.arange', 'np.arange', (['row.shape[0]'], {}), '(row.shape[0])\n', (1012, 1026), True, 'import numpy as np\n')] |
# coding: utf-8
from __future__ import division, print_function
__author__ = "adrn <<EMAIL>>"
# Standard library
import os
import logging
# Third-party
import numpy as np
from astropy import log as logger
import gary.potential as gp
# Project
from ... import project_path
from ..core import align_ensemble, compute_align_matrix
logger.setLevel(logging.DEBUG)
plot_path = "plots/tests/TODO"
if not os.path.exists(plot_path):
os.makedirs(plot_path)
potential = gp.load(os.path.join(project_path,'potentials/triaxial-NFW.yml'))
def test_align_orbit():
# start with an orbit that circulates x
w0 = [1., 0., 30., 0., 0.15, -0.1]
t,w = potential.integrate_orbit(w0, dt=1., nsteps=25000)
w = w[:,0]
# fig = gd.plot_orbits(w, marker=None)
# plt.show()
R = compute_align_matrix(w[-1])
new_x = np.array(R.dot(w[:,:3].T).T)
new_v = np.array(R.dot(w[:,3:].T).T)
new_L = np.cross(new_x[-1], new_v[-1])[0]
a = np.array([0., 0., np.linalg.norm(new_L)])
b = new_L
assert np.allclose(a,b)
a = np.array([np.linalg.norm(new_x[-1]), 0., 0.])
assert np.allclose(a,new_x[-1])
def test_align_many_points():
# start with an orbit that circulates x
w0 = [1., 0., 30., 0., 0.15, -0.1]
t,w = potential.integrate_orbit(w0, dt=1., nsteps=25000)
w = w[:,0]
# fig = gd.plot_orbits(w, marker=None)
# plt.show()
for i in np.random.randint(len(w), size=100):
print(i)
R = compute_align_matrix(w[i])
new_x = R.dot(w[:i+1,:3].T).T
new_v = R.dot(w[:i+1,3:].T).T
new_L = np.cross(new_x[-1], new_v[-1])[0]
a = np.array([0., 0., np.linalg.norm(new_L)])
b = new_L
assert np.allclose(a,b)
a = np.array([np.linalg.norm(new_x[-1]), 0., 0.])
assert np.allclose(a,new_x[-1])
def test_align_ensemble():
# start with an orbit that circulates x
parent_w0 = np.array([1., 0., 30., 0., 0.15, -0.1])
w0 = np.random.normal(parent_w0,
[0.01,0.01,0.01,0.002,0.002,0.002],
size=(250,6))
w0 = np.vstack((parent_w0[None], w0))
t,w = potential.integrate_orbit(w0, dt=1., nsteps=15000)
for i in np.random.randint(len(w), size=100):
print(i)
new_x, new_v = align_ensemble(w[:i])
# fig = gd.plot_orbits(new_x, linestyle='none')
# fig = gd.plot_orbits(new_x[:1], marker='o', color='r',
# linestyle='none', axes=fig.axes)
# plt.show()
# break
new_L = np.cross(new_x[0], new_v[0])[0]
a = np.array([0., 0., np.linalg.norm(new_L)])
b = new_L
assert np.allclose(a,b)
a = np.array([np.linalg.norm(new_x[0]), 0., 0.])
assert np.allclose(a,new_x[0])
| [
"os.makedirs",
"astropy.log.setLevel",
"numpy.allclose",
"os.path.exists",
"numpy.cross",
"numpy.array",
"numpy.linalg.norm",
"numpy.random.normal",
"os.path.join",
"numpy.vstack"
] | [((334, 364), 'astropy.log.setLevel', 'logger.setLevel', (['logging.DEBUG'], {}), '(logging.DEBUG)\n', (349, 364), True, 'from astropy import log as logger\n'), ((404, 429), 'os.path.exists', 'os.path.exists', (['plot_path'], {}), '(plot_path)\n', (418, 429), False, 'import os\n'), ((435, 457), 'os.makedirs', 'os.makedirs', (['plot_path'], {}), '(plot_path)\n', (446, 457), False, 'import os\n'), ((479, 536), 'os.path.join', 'os.path.join', (['project_path', '"""potentials/triaxial-NFW.yml"""'], {}), "(project_path, 'potentials/triaxial-NFW.yml')\n", (491, 536), False, 'import os\n'), ((1023, 1040), 'numpy.allclose', 'np.allclose', (['a', 'b'], {}), '(a, b)\n', (1034, 1040), True, 'import numpy as np\n'), ((1106, 1131), 'numpy.allclose', 'np.allclose', (['a', 'new_x[-1]'], {}), '(a, new_x[-1])\n', (1117, 1131), True, 'import numpy as np\n'), ((1907, 1950), 'numpy.array', 'np.array', (['[1.0, 0.0, 30.0, 0.0, 0.15, -0.1]'], {}), '([1.0, 0.0, 30.0, 0.0, 0.15, -0.1])\n', (1915, 1950), True, 'import numpy as np\n'), ((1956, 2044), 'numpy.random.normal', 'np.random.normal', (['parent_w0', '[0.01, 0.01, 0.01, 0.002, 0.002, 0.002]'], {'size': '(250, 6)'}), '(parent_w0, [0.01, 0.01, 0.01, 0.002, 0.002, 0.002], size=(\n 250, 6))\n', (1972, 2044), True, 'import numpy as np\n'), ((2095, 2127), 'numpy.vstack', 'np.vstack', (['(parent_w0[None], w0)'], {}), '((parent_w0[None], w0))\n', (2104, 2127), True, 'import numpy as np\n'), ((913, 943), 'numpy.cross', 'np.cross', (['new_x[-1]', 'new_v[-1]'], {}), '(new_x[-1], new_v[-1])\n', (921, 943), True, 'import numpy as np\n'), ((1703, 1720), 'numpy.allclose', 'np.allclose', (['a', 'b'], {}), '(a, b)\n', (1714, 1720), True, 'import numpy as np\n'), ((1794, 1819), 'numpy.allclose', 'np.allclose', (['a', 'new_x[-1]'], {}), '(a, new_x[-1])\n', (1805, 1819), True, 'import numpy as np\n'), ((2661, 2678), 'numpy.allclose', 'np.allclose', (['a', 'b'], {}), '(a, b)\n', (2672, 2678), True, 'import numpy as np\n'), ((2751, 2775), 'numpy.allclose', 'np.allclose', (['a', 'new_x[0]'], {}), '(a, new_x[0])\n', (2762, 2775), True, 'import numpy as np\n'), ((974, 995), 'numpy.linalg.norm', 'np.linalg.norm', (['new_L'], {}), '(new_L)\n', (988, 995), True, 'import numpy as np\n'), ((1059, 1084), 'numpy.linalg.norm', 'np.linalg.norm', (['new_x[-1]'], {}), '(new_x[-1])\n', (1073, 1084), True, 'import numpy as np\n'), ((1581, 1611), 'numpy.cross', 'np.cross', (['new_x[-1]', 'new_v[-1]'], {}), '(new_x[-1], new_v[-1])\n', (1589, 1611), True, 'import numpy as np\n'), ((2542, 2570), 'numpy.cross', 'np.cross', (['new_x[0]', 'new_v[0]'], {}), '(new_x[0], new_v[0])\n', (2550, 2570), True, 'import numpy as np\n'), ((1646, 1667), 'numpy.linalg.norm', 'np.linalg.norm', (['new_L'], {}), '(new_L)\n', (1660, 1667), True, 'import numpy as np\n'), ((1743, 1768), 'numpy.linalg.norm', 'np.linalg.norm', (['new_x[-1]'], {}), '(new_x[-1])\n', (1757, 1768), True, 'import numpy as np\n'), ((2604, 2625), 'numpy.linalg.norm', 'np.linalg.norm', (['new_L'], {}), '(new_L)\n', (2618, 2625), True, 'import numpy as np\n'), ((2701, 2725), 'numpy.linalg.norm', 'np.linalg.norm', (['new_x[0]'], {}), '(new_x[0])\n', (2715, 2725), True, 'import numpy as np\n')] |
import os
import numpy as np
import shutil
import random
# todo;构造卷积神经网络
from keras.layers import Dense, Dropout, Convolution2D, MaxPool2D, Flatten
from keras.models import load_model, Sequential
from keras.preprocessing import image
# from data_gen import DataGenerator
from .data_gen import DataGenerator
class CatDog():
def __init__(self, file_path):
self.file_path = file_path
# 构造训练数据
self.BATH_PATH = os.path.abspath(os.path.dirname(__file__)) + os.sep
self.original_data = os.path.join(self.BATH_PATH, "data", "original_data") + os.sep
# print(self.train) #D:\Users\Administrator\Desktop\ml_project\ai_yueqian\catdog\data\train\
# 猫狗数据分离
# 构造目标训练地址
self.target = os.path.join(self.BATH_PATH, "data", "target") + os.sep
# print(self.target) #D:\Users\Administrator\Desktop\ml_project\ai_yueqian\catdog\data\target\
# todo:构造模型保存路径
self.model_path = os.path.join(self.BATH_PATH, "static", "model") + os.sep
self.model_save = os.path.join(self.BATH_PATH, "static", "model", "mymodel.h5")
self.model_save_weights = os.path.join(self.BATH_PATH, "static", "model", "myweights.h5")
def ensure_dir(self, dir_path):
"""
创建文件夹
:param dir_path: 文件夹的路径
:return:
"""
if not os.path.exists(dir_path):
try:
os.makedirs(dir_path)
except OSError:
print("文件夹已经存在,创建文件夹失败")
def del_dir(self, dir_path):
"""
删除文件夹
:param dir_path: 文件夹的路径
:return:
"""
try:
shutil.rmtree(dir_path) # 删除当前文件夹所有目录
except FileNotFoundError:
print(f"{dir_path}路径不存在!")
def init_cat_dog(self, fresh=False):
"""
构造数据集
:param fresh: 是否重新构造数据集
:return:
"""
if fresh:
try:
self.del_dir(self.target)
except Exception:
print(f"删除路径失败:{self.target}")
if not os.path.exists(self.target):
# 创建保存训练数据的路径
self.ensure_dir(os.path.join(self.target, "train", "cat") + os.sep)
self.ensure_dir(os.path.join(self.target, "train", "dog") + os.sep)
self.ensure_dir(os.path.join(self.target, "test", "cat") + os.sep)
self.ensure_dir(os.path.join(self.target, "test", "dog") + os.sep)
# todo:训练集和测试集的分离
train_list = os.listdir(self.original_data) # 路径下的所有文件名称
# print(train_list)
dogs = [self.original_data + i for i in train_list if "dog" in i]
# print(dogs)
cats = [self.original_data + i for i in train_list if "cat" in i]
# 复制到数据到训练路径中
random.shuffle(dogs)
random.shuffle(cats)
cut_size = int(len(dogs) * 0.75) # 75%训练
# todo:构造训练数据
for dog_path in dogs[:cut_size]:
shutil.copyfile(dog_path,
os.path.join(self.target, "train", "dog") + os.sep + os.path.basename(dog_path))
shutil.copyfile(dog_path,
os.path.join(self.target, "test", "dog") + os.sep + os.path.basename(dog_path))
for cat_path in cats[:cut_size]:
shutil.copyfile(cat_path,
os.path.join(self.target, "train", "cat") + os.sep + os.path.basename(cat_path))
shutil.copyfile(cat_path,
os.path.join(self.target, "test", "cat") + os.sep + os.path.basename(cat_path))
else:
print("训练集和数据集已经就绪,不需要重复加载!")
def init_data(self, datatype="train"):
"""
读取数据
:param datatype: 读取数据的文件夹[‘train’,'test']
:return:所有训练数据的路径
"""
datas = []
data_path = self.target + datatype + os.sep
for file in os.listdir(data_path):
# print(file) #["cat","dog"]
file_path = os.path.join(data_path, file)
# print(file_path)
if os.path.isdir(file_path):
for subfile in os.listdir(file_path):
datas.append(os.path.join(file_path, subfile))
return datas
def init_model(self):
"""
构造卷积神经网络模型
:return:
"""
# 统一图像尺寸
img_width = 128
img_height = 128
input_shape = (img_width, img_height, 3)
model = Sequential([
Convolution2D(32, (3, 3), input_shape=input_shape, strides=(1, 1), activation="relu"), # 卷积层
MaxPool2D(pool_size=(2, 2), strides=(2, 2), name="pool1"), # 池化层
Convolution2D(64, (3, 3), activation="relu"), # 卷积层
MaxPool2D(pool_size=(2, 2), strides=(2, 2), name="pool2"), # 池化层
Flatten(), # 扁平化
Dense(64, activation="relu"),
Dropout(0.5), # 随机失活
Dense(2, activation="sigmoid")
])
# 编译模型
# 动量梯度下降算法,交叉熵误差函数,正确率做模型评估指标
model.compile(optimizer="rmsprop", loss="binary_crossentropy", metrics=["accuracy"])
self.model = model
def save_my_model(self):
"""
保存模型
:return:
"""
self.ensure_dir(self.model_path)
# json_string = self.model.to_json()
self.model.save(self.model_save) # 保存模型
self.model.save_weights(self.model_save_weights) # b保存权重
def load_my_model(self):
model = load_model(self.model_save) # 加载模型
model.load_weights(self.model_save_weights) # 加载权重
return model
def model_trian(self, refresh=False):
"""
模型训练
:return:
"""
if refresh:
try:
self.del_dir(self.model_path)
except Exception:
print(f"删除路径失败:{self.model_path}")
if not os.path.exists(self.model_save) or not os.path.exists(self.model_save_weights):
# 1、构造数据
self.init_cat_dog()
train_datas = self.init_data()
train_generator = DataGenerator(train_datas, batch_size=32, shuffle=True)
# 2、构造模型
self.init_model()
# 3、模型训练
self.model.fit_generator(train_generator, epochs=30, max_queue_size=10, workers=1, verbose=1)
# 保存模型
self.save_my_model()
else:
import tensorflow as tf
graph = tf.get_default_graph() # 功能:获取当前默认计算图。
with graph.as_default():
self.model = self.load_my_model()
def pred_cat_dog(self):
img = image.load_img(self.file_path, target_size=(128, 128))
x = image.img_to_array(img)
x /= 255
x = np.expand_dims(x, axis=0)
y = self.model.predict(x)
pred_index = np.argmax(y)
if pred_index == 1:
return "识别结果:-<狗狗>-"
else:
return "识别结果:-<喵喵>-"
#
# c = CatDog('./2.jpg')
# c.model_trian()
# print(c.pred_cat_dog())
| [
"keras.models.load_model",
"numpy.argmax",
"random.shuffle",
"keras.layers.MaxPool2D",
"keras.preprocessing.image.img_to_array",
"shutil.rmtree",
"tensorflow.get_default_graph",
"os.path.join",
"os.path.dirname",
"os.path.exists",
"keras.layers.Flatten",
"keras.preprocessing.image.load_img",
... | [((1032, 1093), 'os.path.join', 'os.path.join', (['self.BATH_PATH', '"""static"""', '"""model"""', '"""mymodel.h5"""'], {}), "(self.BATH_PATH, 'static', 'model', 'mymodel.h5')\n", (1044, 1093), False, 'import os\n'), ((1128, 1191), 'os.path.join', 'os.path.join', (['self.BATH_PATH', '"""static"""', '"""model"""', '"""myweights.h5"""'], {}), "(self.BATH_PATH, 'static', 'model', 'myweights.h5')\n", (1140, 1191), False, 'import os\n'), ((3910, 3931), 'os.listdir', 'os.listdir', (['data_path'], {}), '(data_path)\n', (3920, 3931), False, 'import os\n'), ((5464, 5491), 'keras.models.load_model', 'load_model', (['self.model_save'], {}), '(self.model_save)\n', (5474, 5491), False, 'from keras.models import load_model, Sequential\n'), ((6591, 6645), 'keras.preprocessing.image.load_img', 'image.load_img', (['self.file_path'], {'target_size': '(128, 128)'}), '(self.file_path, target_size=(128, 128))\n', (6605, 6645), False, 'from keras.preprocessing import image\n'), ((6658, 6681), 'keras.preprocessing.image.img_to_array', 'image.img_to_array', (['img'], {}), '(img)\n', (6676, 6681), False, 'from keras.preprocessing import image\n'), ((6711, 6736), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (6725, 6736), True, 'import numpy as np\n'), ((6794, 6806), 'numpy.argmax', 'np.argmax', (['y'], {}), '(y)\n', (6803, 6806), True, 'import numpy as np\n'), ((518, 571), 'os.path.join', 'os.path.join', (['self.BATH_PATH', '"""data"""', '"""original_data"""'], {}), "(self.BATH_PATH, 'data', 'original_data')\n", (530, 571), False, 'import os\n'), ((740, 786), 'os.path.join', 'os.path.join', (['self.BATH_PATH', '"""data"""', '"""target"""'], {}), "(self.BATH_PATH, 'data', 'target')\n", (752, 786), False, 'import os\n'), ((949, 996), 'os.path.join', 'os.path.join', (['self.BATH_PATH', '"""static"""', '"""model"""'], {}), "(self.BATH_PATH, 'static', 'model')\n", (961, 996), False, 'import os\n'), ((1331, 1355), 'os.path.exists', 'os.path.exists', (['dir_path'], {}), '(dir_path)\n', (1345, 1355), False, 'import os\n'), ((1627, 1650), 'shutil.rmtree', 'shutil.rmtree', (['dir_path'], {}), '(dir_path)\n', (1640, 1650), False, 'import shutil\n'), ((2038, 2065), 'os.path.exists', 'os.path.exists', (['self.target'], {}), '(self.target)\n', (2052, 2065), False, 'import os\n'), ((2467, 2497), 'os.listdir', 'os.listdir', (['self.original_data'], {}), '(self.original_data)\n', (2477, 2497), False, 'import os\n'), ((2764, 2784), 'random.shuffle', 'random.shuffle', (['dogs'], {}), '(dogs)\n', (2778, 2784), False, 'import random\n'), ((2797, 2817), 'random.shuffle', 'random.shuffle', (['cats'], {}), '(cats)\n', (2811, 2817), False, 'import random\n'), ((3998, 4027), 'os.path.join', 'os.path.join', (['data_path', 'file'], {}), '(data_path, file)\n', (4010, 4027), False, 'import os\n'), ((4074, 4098), 'os.path.isdir', 'os.path.isdir', (['file_path'], {}), '(file_path)\n', (4087, 4098), False, 'import os\n'), ((6420, 6442), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (6440, 6442), True, 'import tensorflow as tf\n'), ((453, 478), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (468, 478), False, 'import os\n'), ((1390, 1411), 'os.makedirs', 'os.makedirs', (['dir_path'], {}), '(dir_path)\n', (1401, 1411), False, 'import os\n'), ((4131, 4152), 'os.listdir', 'os.listdir', (['file_path'], {}), '(file_path)\n', (4141, 4152), False, 'import os\n'), ((4485, 4574), 'keras.layers.Convolution2D', 'Convolution2D', (['(32)', '(3, 3)'], {'input_shape': 'input_shape', 'strides': '(1, 1)', 'activation': '"""relu"""'}), "(32, (3, 3), input_shape=input_shape, strides=(1, 1),\n activation='relu')\n", (4498, 4574), False, 'from keras.layers import Dense, Dropout, Convolution2D, MaxPool2D, Flatten\n'), ((4591, 4648), 'keras.layers.MaxPool2D', 'MaxPool2D', ([], {'pool_size': '(2, 2)', 'strides': '(2, 2)', 'name': '"""pool1"""'}), "(pool_size=(2, 2), strides=(2, 2), name='pool1')\n", (4600, 4648), False, 'from keras.layers import Dense, Dropout, Convolution2D, MaxPool2D, Flatten\n'), ((4669, 4713), 'keras.layers.Convolution2D', 'Convolution2D', (['(64)', '(3, 3)'], {'activation': '"""relu"""'}), "(64, (3, 3), activation='relu')\n", (4682, 4713), False, 'from keras.layers import Dense, Dropout, Convolution2D, MaxPool2D, Flatten\n'), ((4734, 4791), 'keras.layers.MaxPool2D', 'MaxPool2D', ([], {'pool_size': '(2, 2)', 'strides': '(2, 2)', 'name': '"""pool2"""'}), "(pool_size=(2, 2), strides=(2, 2), name='pool2')\n", (4743, 4791), False, 'from keras.layers import Dense, Dropout, Convolution2D, MaxPool2D, Flatten\n'), ((4812, 4821), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (4819, 4821), False, 'from keras.layers import Dense, Dropout, Convolution2D, MaxPool2D, Flatten\n'), ((4842, 4870), 'keras.layers.Dense', 'Dense', (['(64)'], {'activation': '"""relu"""'}), "(64, activation='relu')\n", (4847, 4870), False, 'from keras.layers import Dense, Dropout, Convolution2D, MaxPool2D, Flatten\n'), ((4884, 4896), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (4891, 4896), False, 'from keras.layers import Dense, Dropout, Convolution2D, MaxPool2D, Flatten\n'), ((4918, 4948), 'keras.layers.Dense', 'Dense', (['(2)'], {'activation': '"""sigmoid"""'}), "(2, activation='sigmoid')\n", (4923, 4948), False, 'from keras.layers import Dense, Dropout, Convolution2D, MaxPool2D, Flatten\n'), ((5857, 5888), 'os.path.exists', 'os.path.exists', (['self.model_save'], {}), '(self.model_save)\n', (5871, 5888), False, 'import os\n'), ((5896, 5935), 'os.path.exists', 'os.path.exists', (['self.model_save_weights'], {}), '(self.model_save_weights)\n', (5910, 5935), False, 'import os\n'), ((2121, 2162), 'os.path.join', 'os.path.join', (['self.target', '"""train"""', '"""cat"""'], {}), "(self.target, 'train', 'cat')\n", (2133, 2162), False, 'import os\n'), ((2201, 2242), 'os.path.join', 'os.path.join', (['self.target', '"""train"""', '"""dog"""'], {}), "(self.target, 'train', 'dog')\n", (2213, 2242), False, 'import os\n'), ((2281, 2321), 'os.path.join', 'os.path.join', (['self.target', '"""test"""', '"""cat"""'], {}), "(self.target, 'test', 'cat')\n", (2293, 2321), False, 'import os\n'), ((2360, 2400), 'os.path.join', 'os.path.join', (['self.target', '"""test"""', '"""dog"""'], {}), "(self.target, 'test', 'dog')\n", (2372, 2400), False, 'import os\n'), ((3070, 3096), 'os.path.basename', 'os.path.basename', (['dog_path'], {}), '(dog_path)\n', (3086, 3096), False, 'import os\n'), ((3224, 3250), 'os.path.basename', 'os.path.basename', (['dog_path'], {}), '(dog_path)\n', (3240, 3250), False, 'import os\n'), ((3424, 3450), 'os.path.basename', 'os.path.basename', (['cat_path'], {}), '(cat_path)\n', (3440, 3450), False, 'import os\n'), ((3578, 3604), 'os.path.basename', 'os.path.basename', (['cat_path'], {}), '(cat_path)\n', (3594, 3604), False, 'import os\n'), ((4187, 4219), 'os.path.join', 'os.path.join', (['file_path', 'subfile'], {}), '(file_path, subfile)\n', (4199, 4219), False, 'import os\n'), ((3017, 3058), 'os.path.join', 'os.path.join', (['self.target', '"""train"""', '"""dog"""'], {}), "(self.target, 'train', 'dog')\n", (3029, 3058), False, 'import os\n'), ((3172, 3212), 'os.path.join', 'os.path.join', (['self.target', '"""test"""', '"""dog"""'], {}), "(self.target, 'test', 'dog')\n", (3184, 3212), False, 'import os\n'), ((3371, 3412), 'os.path.join', 'os.path.join', (['self.target', '"""train"""', '"""cat"""'], {}), "(self.target, 'train', 'cat')\n", (3383, 3412), False, 'import os\n'), ((3526, 3566), 'os.path.join', 'os.path.join', (['self.target', '"""test"""', '"""cat"""'], {}), "(self.target, 'test', 'cat')\n", (3538, 3566), False, 'import os\n')] |
import numpy as np
import pandas as pd
import vtk
from vtk.util import numpy_support as ns
class BaseArray(object):
def __init__(self, array, type_array=None):
'''
:param array: Receives a pandas DataFrame, or numpy array or vtkDataArray
:param type_array: Receives the vtk data type or a numpy array type
'''
self._vtk = None
array = self._convert_list_pandas_to_numpy(array)
vtk_type = None
np_type = None
if isinstance(type_array, int):
vtk_type = type_array
np_type = ns.get_vtk_to_numpy_typemap()[type_array]
elif isinstance(type_array, type):
vtk_type = ns.get_vtk_array_type(type_array)
np_type = type_array
if isinstance(array, np.ndarray):
if not array.flags.contiguous:
array = np.ascontiguousarray(array)
if np_type:
array = array.astype(np_type)
self._numpy = array
self._vtk = ns.numpy_to_vtk(self._numpy, array_type=vtk_type)
self._vtk._np = array
elif isinstance(array, vtk.vtkDataArray):
if type_array is None or array.GetDataType() == vtk_type:
self._vtk = array
self._numpy = ns.vtk_to_numpy(array)
else:
if type_array is None:
np_type = np.double
vtk_type = vtk.VTK_DOUBLE
np_array = ns.vtk_to_numpy(array).astype(np_type)
self._vtk = ns.create_vtk_array(vtk_type)
self._vtk.SetName(array.GetName())
self.numpy_to_vtk(np_array)
else:
raise ValueError('Expected a Numpy array, but received a: {}'.format(type(array)))
self._vtk.AddObserver(vtk.vtkCommand.ModifiedEvent, self._update_numpy)
@property
def numpy(self):
return self._numpy
@numpy.setter
def numpy(self, np_array):
if np_array.flags.contiguous:
np_array = np.ascontiguousarray(np_array)
self._numpy = np_array
self.numpy_to_vtk(self._numpy)
@property
def vtk(self):
return self._vtk
@vtk.setter
def vtk(self, vtk_object):
if not isinstance(vtk_object, vtk.vtkDataArray):
raise TypeError('Expected a vtkDataArray object, got {}'.format(type(vtk_object)))
self._vtk = vtk_object
array = ns.vtk_to_numpy(vtk_object)
self.numpy_to_vtk(array)
self._numpy = array
def __getattr__(self, item):
try:
attr = getattr(self._vtk, item)
if hasattr(attr, "__self__") and attr.__self__ is self._vtk:
def _vtk_method_proxy(*args, **kwargs):
'''
This is black magic, do not do this at home. :)
It is need because the self._vtk.AddObserver(vtk.vtkCommand.ModifiedEvent, update_numpy)
only works if the method Modified() is called, when we add a value or remove it, it will not
be called.
:param args:
:param kwargs:
:return:
'''
result = attr(*args, **kwargs)
self._update_numpy()
return result
return _vtk_method_proxy
else:
return attr
except AttributeError as msg:
raise AttributeError('Object has not attribute {}'.format(msg.message))
def __eq__(self, other):
other = self._convert_list_pandas_to_numpy(other)
if isinstance(other, np.ndarray):
return np.array_equal(self._numpy, other)
condition = True
if isinstance(other, BaseArray):
condition = self._numpy.shape == other.numpy.shape
return self.GetNumberOfComponents() == other.GetNumberOfComponents() \
and self.GetNumberOfTuples() == other.GetNumberOfTuples() \
and condition \
and self.GetName() == other.GetName()
def __ne__(self, other):
return not self.__eq__(other)
def __contains__(self, item):
return item in self._numpy
def __len__(self):
return self._numpy.size
def __getitem__(self, index):
cls = type(self)
if isinstance(index, slice):
return cls(self._numpy[index])
else:
return self._numpy[index]
def __setitem__(self, key, value):
self._numpy[key] = value
def __str__(self):
return '{}: {}'.format(self.GetName(), self._numpy)
def _convert_list_pandas_to_numpy(self, data_array):
result = None
if isinstance(data_array, list):
result = np.array(data_array)
elif isinstance(data_array, pd.DataFrame):
result = data_array.as_matrix()
if not result.flags.contiguous:
result = np.ascontiguousarray(result)
if result.shape[1] == 1:
result = result.reshape(-1)
if not result is None:
return result
return data_array
def __add__(self, other):
return self._do_operation(other, '+')
def __mul__(self, other):
return self._do_operation(other, '*')
def __truediv__(self, other):
return self._do_operation(other, '//')
def __div__(self, other):
return self._do_operation(other, '/')
def __sub__(self, other):
return self._do_operation(other, '-')
def _do_operation(self, other, operation):
'''
Method just to easily manipulate the operations in numpy array
:param other: Receives a number, pandas dataframe, numpy array, list or BaseArray which
will be calculated
:param operation: Receives the symbol which represents the operation which will be executed
:return: Return a BaseArray calculated given the parameters
'''
cls = type(self)
parc = self._convert_list_pandas_to_numpy(other)
result = None
if operation == '+':
result = self._numpy + parc
elif operation == '-':
result = self._numpy - parc
elif operation == '*':
result = self._numpy * parc
elif operation == '/':
result = self._numpy / parc
elif operation == '//':
result = self._numpy // parc
else:
raise ValueError('Expected a valid operation such as: +, -, *, / Received: {}'.format(operation))
result = cls(result)
result.SetName(self.GetName())
return result
def add_row(self, row_val):
'''
Receives a new row which will be add to the vtkDataArray
:param row_val: Receives a numpy array or a list to be add
'''
if self._numpy.size == 0:
self._numpy = row_val
else:
self._numpy = np.vstack((self._numpy, row_val))
self.numpy_to_vtk(self._numpy)
def _update_numpy(self, *args, **kwargs):
'''
This method is called when the any method of the vtk is called
:return:
'''
self._numpy = ns.vtk_to_numpy(self._vtk)
def copy_array(self, array):
'''
Set the data to the vtkDataArray
:param array: receives a pandas DataFrame, numpy array or a list
:return:
'''
self.numpy_to_vtk(array)
def numpy_to_vtk(self, num_array):
"""
Code adapted from official VTK Project.
License and original code can be found here:
https://gitlab.kitware.com/vtk/vtk/blob/master/Wrapping/Python/vtk/util/numpy_support.py
Converts a real numpy Array to a VTK array object.
This function only works for real arrays.
Complex arrays are NOT handled. It also works for multi-component
arrays. However, only 1, and 2 dimensional arrays are supported.
This function is very efficient, so large arrays should not be a
problem.
If the second argument is set to 1, the array is deep-copied from
from numpy. This is not as efficient as the default behavior
(shallow copy) and uses more memory but detaches the two arrays
such that the numpy array can be released.
WARNING: You must maintain a reference to the passed numpy array, if
the numpy data is gc'd and VTK will point to garbage which will in
the best case give you a segfault.
Parameters:
num_array
a 1D or 2D, real numpy array.
"""
if not num_array.flags.contiguous:
num_array = np.ascontiguousarray(num_array)
shape = num_array.shape
assert num_array.flags.contiguous, 'Only contiguous arrays are supported.'
assert len(shape) < 3, \
"Only arrays of dimensionality 2 or lower are allowed!"
assert not np.issubdtype(num_array.dtype, complex), \
"Complex numpy arrays cannot be converted to vtk arrays." \
"Use real() or imag() to get a component of the array before" \
" passing it to vtk."
# Fixup shape in case its empty or scalar.
try:
testVar = shape[0]
except:
shape = (0,)
# Find the shape and set number of components.
if len(shape) == 1:
self._vtk.SetNumberOfComponents(1)
else:
self._vtk.SetNumberOfComponents(shape[1])
self._vtk.SetNumberOfTuples(shape[0])
# Ravel the array appropriately.
array_flat = np.ravel(num_array)
# Point the VTK array to the numpy data. The last argument (1)
# tells the array not to deallocate.
self._vtk.SetVoidArray(array_flat, array_flat.size, 1)
self._vtk._numpy_reference = num_array
| [
"vtk.util.numpy_support.get_vtk_array_type",
"vtk.util.numpy_support.numpy_to_vtk",
"numpy.ravel",
"vtk.util.numpy_support.get_vtk_to_numpy_typemap",
"vtk.util.numpy_support.vtk_to_numpy",
"numpy.issubdtype",
"vtk.util.numpy_support.create_vtk_array",
"numpy.array",
"numpy.array_equal",
"numpy.asc... | [((2440, 2467), 'vtk.util.numpy_support.vtk_to_numpy', 'ns.vtk_to_numpy', (['vtk_object'], {}), '(vtk_object)\n', (2455, 2467), True, 'from vtk.util import numpy_support as ns\n'), ((7239, 7265), 'vtk.util.numpy_support.vtk_to_numpy', 'ns.vtk_to_numpy', (['self._vtk'], {}), '(self._vtk)\n', (7254, 7265), True, 'from vtk.util import numpy_support as ns\n'), ((9652, 9671), 'numpy.ravel', 'np.ravel', (['num_array'], {}), '(num_array)\n', (9660, 9671), True, 'import numpy as np\n'), ((1016, 1065), 'vtk.util.numpy_support.numpy_to_vtk', 'ns.numpy_to_vtk', (['self._numpy'], {'array_type': 'vtk_type'}), '(self._numpy, array_type=vtk_type)\n', (1031, 1065), True, 'from vtk.util import numpy_support as ns\n'), ((2032, 2062), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['np_array'], {}), '(np_array)\n', (2052, 2062), True, 'import numpy as np\n'), ((3701, 3735), 'numpy.array_equal', 'np.array_equal', (['self._numpy', 'other'], {}), '(self._numpy, other)\n', (3715, 3735), True, 'import numpy as np\n'), ((4789, 4809), 'numpy.array', 'np.array', (['data_array'], {}), '(data_array)\n', (4797, 4809), True, 'import numpy as np\n'), ((6980, 7013), 'numpy.vstack', 'np.vstack', (['(self._numpy, row_val)'], {}), '((self._numpy, row_val))\n', (6989, 7013), True, 'import numpy as np\n'), ((8713, 8744), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['num_array'], {}), '(num_array)\n', (8733, 8744), True, 'import numpy as np\n'), ((8981, 9020), 'numpy.issubdtype', 'np.issubdtype', (['num_array.dtype', 'complex'], {}), '(num_array.dtype, complex)\n', (8994, 9020), True, 'import numpy as np\n'), ((577, 606), 'vtk.util.numpy_support.get_vtk_to_numpy_typemap', 'ns.get_vtk_to_numpy_typemap', ([], {}), '()\n', (604, 606), True, 'from vtk.util import numpy_support as ns\n'), ((685, 718), 'vtk.util.numpy_support.get_vtk_array_type', 'ns.get_vtk_array_type', (['type_array'], {}), '(type_array)\n', (706, 718), True, 'from vtk.util import numpy_support as ns\n'), ((862, 889), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['array'], {}), '(array)\n', (882, 889), True, 'import numpy as np\n'), ((1284, 1306), 'vtk.util.numpy_support.vtk_to_numpy', 'ns.vtk_to_numpy', (['array'], {}), '(array)\n', (1299, 1306), True, 'from vtk.util import numpy_support as ns\n'), ((1544, 1573), 'vtk.util.numpy_support.create_vtk_array', 'ns.create_vtk_array', (['vtk_type'], {}), '(vtk_type)\n', (1563, 1573), True, 'from vtk.util import numpy_support as ns\n'), ((4974, 5002), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['result'], {}), '(result)\n', (4994, 5002), True, 'import numpy as np\n'), ((1477, 1499), 'vtk.util.numpy_support.vtk_to_numpy', 'ns.vtk_to_numpy', (['array'], {}), '(array)\n', (1492, 1499), True, 'from vtk.util import numpy_support as ns\n')] |
''' This module contains functions necessary to fit a negative binomial
using the maximum likelihood estimator and some numerical analysis
@author: <NAME>
@website: http://www.peterxeno.com
'''
import math
import numpy as np
from scipy.optimize import newton
from scipy.special import digamma
def r_derv(r_var, vec):
''' Function that represents the derivative of the neg bin likelihood wrt r
@param r: The value of r in the derivative of the likelihood wrt r
@param vec: The data vector used in the likelihood
'''
if not r_var or not vec:
raise ValueError("r parameter and data must be specified")
if r_var <= 0:
raise ValueError("r must be strictly greater than 0")
total_sum = 0
obs_mean = np.mean(vec) # Save the mean of the data
n_pop = float(len(vec)) # Save the length of the vector, n_pop
for obs in vec:
total_sum += digamma(obs + r_var)
total_sum -= n_pop*digamma(r_var)
total_sum += n_pop*math.log(r_var / (r_var + obs_mean))
return total_sum
def p_equa(r_var, vec):
''' Function that represents the equation for p in the neg bin likelihood wrt p
@param r: The value of r in the derivative of the likelihood wrt p
@param vec: Te data vector used in the likelihood
'''
if not r_var or not vec:
raise ValueError("r parameter and data must be specified")
if r_var <= 0:
raise ValueError("r must be strictly greater than 0")
data_sum = np.sum(vec)
n_pop = float(len(vec))
p_var = 1 - (data_sum / (n_pop * r_var + data_sum))
return p_var
def neg_bin_fit(vec, init=0.0001):
''' Function to fit negative binomial to data
@param vec: The data vector used to fit the negative binomial distribution
@param init: Set init to a number close to 0, and you will always converge
'''
if not vec:
raise ValueError("Data must be specified")
est_r = newton(r_derv, init, args=(vec,))
est_p = p_equa(est_r, vec)
return est_r, est_p
| [
"numpy.sum",
"scipy.special.digamma",
"numpy.mean",
"scipy.optimize.newton",
"math.log"
] | [((747, 759), 'numpy.mean', 'np.mean', (['vec'], {}), '(vec)\n', (754, 759), True, 'import numpy as np\n'), ((1477, 1488), 'numpy.sum', 'np.sum', (['vec'], {}), '(vec)\n', (1483, 1488), True, 'import numpy as np\n'), ((1919, 1952), 'scipy.optimize.newton', 'newton', (['r_derv', 'init'], {'args': '(vec,)'}), '(r_derv, init, args=(vec,))\n', (1925, 1952), False, 'from scipy.optimize import newton\n'), ((899, 919), 'scipy.special.digamma', 'digamma', (['(obs + r_var)'], {}), '(obs + r_var)\n', (906, 919), False, 'from scipy.special import digamma\n'), ((944, 958), 'scipy.special.digamma', 'digamma', (['r_var'], {}), '(r_var)\n', (951, 958), False, 'from scipy.special import digamma\n'), ((982, 1018), 'math.log', 'math.log', (['(r_var / (r_var + obs_mean))'], {}), '(r_var / (r_var + obs_mean))\n', (990, 1018), False, 'import math\n')] |
from problem2 import *
import numpy as np
import sys
'''
Unit test 2:
This file includes unit tests for problem2.py.
'''
#-------------------------------------------------------------------------
def test_python_version():
''' ----------- Problem 2 (30 points in total)---------------------'''
assert sys.version_info[0]==3 # require python 3.7 or above
assert sys.version_info[1]>=7
#-------------------------------------------------------------------------
def test_compute_fx():
''' (1 point) compute_fx'''
x = np.array([1.,2.])
w = np.array([0.1,0.2])
b = -0.5
fx = compute_fx(x,w,b)
assert np.allclose(fx,0)
b = -0.4
fx = compute_fx(x,w,b)
assert np.allclose(fx,0.1)
#-------------------------------------------------------------------------
def test_compute_gx():
''' (1 points) compute_gx'''
x = np.array([1.,2.])
w = np.array([0.1,0.2])
b = -0.4
gx = compute_gx(x,w,b)
assert gx==1
b = -0.5
gx = compute_gx(x,w,b)
assert gx==1
b = -0.6
gx = compute_gx(x,w,b)
assert gx==-1
#-------------------------------------------------------------------------
def test_compute_gradient():
''' (5 points) compute_gradient'''
x = np.array([1.,1.])
y = -1.
w = np.array([1.,1.])
b = -1.
dL_dw, dL_db = compute_gradient(x,y,w,b,l=1.)
assert type(dL_dw) == np.ndarray
assert dL_dw.shape == (2,)
assert np.allclose(dL_dw, [2,2], atol = 1e-3)
assert dL_db == 1.
x = np.array([1.,2.])
dL_dw, dL_db = compute_gradient(x,y,w,b,l=1.)
assert np.allclose(dL_dw, [2,3], atol = 1e-3)
assert dL_db == 1.
x = np.array([2.,1.])
dL_dw, dL_db = compute_gradient(x,y,w,b,l=1.)
assert np.allclose(dL_dw, [3,2], atol = 1e-3)
assert dL_db == 1.
x = np.array([1.,1.])
dL_dw, dL_db = compute_gradient(x,y,w,b,l=.5)
assert np.allclose(dL_dw, [1.5,1.5], atol = 1e-3)
assert dL_db == 1.
x = np.array([2.,2.])
y = 1.
dL_dw, dL_db = compute_gradient(x,y,w,b,l=1.)
assert np.allclose(dL_dw, [1.,1.], atol = 1e-3)
assert dL_db == 0.
dL_dw, dL_db = compute_gradient(x,y,w,b,l=.5)
assert np.allclose(dL_dw, [.5,.5], atol = 1e-3)
assert dL_db == 0.
w = np.array([2.,1.])
dL_dw, dL_db = compute_gradient(x,y,w,b,l=.5)
assert np.allclose(dL_dw, np.array([1.,.5]), atol = 1e-3)
assert dL_db == 0.
x = np.array([1.,1.])
w = np.array([1.,1.])
dL_dw, dL_db = compute_gradient(x,y,w,b,l=.5)
assert np.allclose(dL_dw, [.5,.5], atol = 1e-3)
assert dL_db == 0.
#-------------------------------------------------------------------------
def test_update_w():
''' (5 points) update_w'''
w = np.array([1.,1.])
dL_dw = np.array([2.,3.])
w_new = update_w(w,dL_dw,1.)
assert type(w_new) == np.ndarray
assert np.allclose(w_new, [-1,-2])
w_new = update_w(w,dL_dw,.5)
assert np.allclose(w_new,[0,-.5])
w = np.array([4.,6.])
w_new = update_w(w,dL_dw,1.)
assert np.allclose(w_new, [2,3])
#-------------------------------------------------------------------------
def test_update_b():
''' (5 points) update_b'''
b = 1.
dL_db = 2.
b_new = update_b(b,dL_db,1.)
assert np.allclose(b_new, -1)
b_new = update_b(b,dL_db,.5)
assert np.allclose(b_new, 0)
#-------------------------------------------------------------------------
def test_train():
'''(5 point) train'''
# an example feature matrix (2 instances, 2 features)
X = np.array([[0., 0.],
[1., 1.]])
Y = np.array([-1., 1.])
w, b = train(X, Y, 0.01,n_epoch = 1000)
assert np.allclose(w[0]+w[1]+ b, 1.,atol = 0.1) # x2 is a positive support vector
assert np.allclose(b, -1.,atol =0.1) # x1 is a negative support vector
#------------------
# another example
X = np.array([[0., 1.],
[1., 0.],
[2., 0.],
[0., 2.]])
Y = np.array([-1., -1., 1., 1.])
w, b = train(X, Y, 0.01, C= 10000., n_epoch = 1000)
assert np.allclose(w[0]+b, -1, atol = 0.1)
assert np.allclose(w[1]+b, -1, atol = 0.1)
assert np.allclose(w[0]+w[1]+b, 1, atol = 0.1)
w, b = train(X, Y, 0.01, C= 0.01, n_epoch = 1000)
assert np.allclose(w, [0,0], atol = 0.1)
#-------------------------------------------------------------------------
def test_predict():
''' (3 points) predict'''
X = np.array([[0.,1.],
[1.,0.],
[0.,0.],
[1.,1.]])
w = np.array([1.,1.])
b = -.5
y = predict(X,w,b)
assert type(y) == np.ndarray
assert y.shape == (4,)
assert np.allclose(y, [1,1,-1,1], atol = 1e-3)
b = -1.5
y = predict(X,w,b)
assert np.allclose(y, [-1,-1,-1,1], atol = 1e-3)
w = np.array([2.,1.])
b = -1.5
y = predict(X,w,b)
assert np.allclose(y, [-1,1,-1,1], atol = 1e-3)
#-------------------------------------------------------------------------
def test_svm():
'''(5 point) SVM '''
# load a binary classification dataset
n_samples = 200
X=np.loadtxt('X.csv',dtype=float, delimiter=',')
y=np.loadtxt('y.csv',dtype=int, delimiter=',')
# split the dataset into a training set and a test set
Xtrain, Ytrain, Xtest, Ytest = X[::2], y[::2], X[1::2], y[1::2]
# train SVM
w,b = train(Xtrain, Ytrain, .001, C=1000., n_epoch=500)
# training accuracy
Y = predict(Xtrain, w, b)
accuracy = (Y == Ytrain).sum()/(n_samples/2.)
print('Training accuracy:', accuracy)
assert accuracy > 0.9
# test accuracy
Y = predict(Xtest, w, b)
accuracy = (Y == Ytest).sum()/(n_samples/2.)
print('Test accuracy:', accuracy)
assert accuracy > 0.9
| [
"numpy.allclose",
"numpy.array",
"numpy.loadtxt"
] | [((547, 567), 'numpy.array', 'np.array', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (555, 567), True, 'import numpy as np\n'), ((573, 593), 'numpy.array', 'np.array', (['[0.1, 0.2]'], {}), '([0.1, 0.2])\n', (581, 593), True, 'import numpy as np\n'), ((645, 663), 'numpy.allclose', 'np.allclose', (['fx', '(0)'], {}), '(fx, 0)\n', (656, 663), True, 'import numpy as np\n'), ((715, 735), 'numpy.allclose', 'np.allclose', (['fx', '(0.1)'], {}), '(fx, 0.1)\n', (726, 735), True, 'import numpy as np\n'), ((876, 896), 'numpy.array', 'np.array', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (884, 896), True, 'import numpy as np\n'), ((902, 922), 'numpy.array', 'np.array', (['[0.1, 0.2]'], {}), '([0.1, 0.2])\n', (910, 922), True, 'import numpy as np\n'), ((1253, 1273), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (1261, 1273), True, 'import numpy as np\n'), ((1291, 1311), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (1299, 1311), True, 'import numpy as np\n'), ((1450, 1488), 'numpy.allclose', 'np.allclose', (['dL_dw', '[2, 2]'], {'atol': '(0.001)'}), '(dL_dw, [2, 2], atol=0.001)\n', (1461, 1488), True, 'import numpy as np\n'), ((1522, 1542), 'numpy.array', 'np.array', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (1530, 1542), True, 'import numpy as np\n'), ((1601, 1639), 'numpy.allclose', 'np.allclose', (['dL_dw', '[2, 3]'], {'atol': '(0.001)'}), '(dL_dw, [2, 3], atol=0.001)\n', (1612, 1639), True, 'import numpy as np\n'), ((1673, 1693), 'numpy.array', 'np.array', (['[2.0, 1.0]'], {}), '([2.0, 1.0])\n', (1681, 1693), True, 'import numpy as np\n'), ((1752, 1790), 'numpy.allclose', 'np.allclose', (['dL_dw', '[3, 2]'], {'atol': '(0.001)'}), '(dL_dw, [3, 2], atol=0.001)\n', (1763, 1790), True, 'import numpy as np\n'), ((1824, 1844), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (1832, 1844), True, 'import numpy as np\n'), ((1903, 1945), 'numpy.allclose', 'np.allclose', (['dL_dw', '[1.5, 1.5]'], {'atol': '(0.001)'}), '(dL_dw, [1.5, 1.5], atol=0.001)\n', (1914, 1945), True, 'import numpy as np\n'), ((1979, 1999), 'numpy.array', 'np.array', (['[2.0, 2.0]'], {}), '([2.0, 2.0])\n', (1987, 1999), True, 'import numpy as np\n'), ((2069, 2111), 'numpy.allclose', 'np.allclose', (['dL_dw', '[1.0, 1.0]'], {'atol': '(0.001)'}), '(dL_dw, [1.0, 1.0], atol=0.001)\n', (2080, 2111), True, 'import numpy as np\n'), ((2196, 2238), 'numpy.allclose', 'np.allclose', (['dL_dw', '[0.5, 0.5]'], {'atol': '(0.001)'}), '(dL_dw, [0.5, 0.5], atol=0.001)\n', (2207, 2238), True, 'import numpy as np\n'), ((2270, 2290), 'numpy.array', 'np.array', (['[2.0, 1.0]'], {}), '([2.0, 1.0])\n', (2278, 2290), True, 'import numpy as np\n'), ((2433, 2453), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (2441, 2453), True, 'import numpy as np\n'), ((2459, 2479), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (2467, 2479), True, 'import numpy as np\n'), ((2538, 2580), 'numpy.allclose', 'np.allclose', (['dL_dw', '[0.5, 0.5]'], {'atol': '(0.001)'}), '(dL_dw, [0.5, 0.5], atol=0.001)\n', (2549, 2580), True, 'import numpy as np\n'), ((2745, 2765), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (2753, 2765), True, 'import numpy as np\n'), ((2775, 2795), 'numpy.array', 'np.array', (['[2.0, 3.0]'], {}), '([2.0, 3.0])\n', (2783, 2795), True, 'import numpy as np\n'), ((2874, 2902), 'numpy.allclose', 'np.allclose', (['w_new', '[-1, -2]'], {}), '(w_new, [-1, -2])\n', (2885, 2902), True, 'import numpy as np\n'), ((2947, 2976), 'numpy.allclose', 'np.allclose', (['w_new', '[0, -0.5]'], {}), '(w_new, [0, -0.5])\n', (2958, 2976), True, 'import numpy as np\n'), ((2983, 3003), 'numpy.array', 'np.array', (['[4.0, 6.0]'], {}), '([4.0, 6.0])\n', (2991, 3003), True, 'import numpy as np\n'), ((3045, 3071), 'numpy.allclose', 'np.allclose', (['w_new', '[2, 3]'], {}), '(w_new, [2, 3])\n', (3056, 3071), True, 'import numpy as np\n'), ((3272, 3294), 'numpy.allclose', 'np.allclose', (['b_new', '(-1)'], {}), '(b_new, -1)\n', (3283, 3294), True, 'import numpy as np\n'), ((3340, 3361), 'numpy.allclose', 'np.allclose', (['b_new', '(0)'], {}), '(b_new, 0)\n', (3351, 3361), True, 'import numpy as np\n'), ((3551, 3585), 'numpy.array', 'np.array', (['[[0.0, 0.0], [1.0, 1.0]]'], {}), '([[0.0, 0.0], [1.0, 1.0]])\n', (3559, 3585), True, 'import numpy as np\n'), ((3609, 3630), 'numpy.array', 'np.array', (['[-1.0, 1.0]'], {}), '([-1.0, 1.0])\n', (3617, 3630), True, 'import numpy as np\n'), ((3684, 3727), 'numpy.allclose', 'np.allclose', (['(w[0] + w[1] + b)', '(1.0)'], {'atol': '(0.1)'}), '(w[0] + w[1] + b, 1.0, atol=0.1)\n', (3695, 3727), True, 'import numpy as np\n'), ((3772, 3802), 'numpy.allclose', 'np.allclose', (['b', '(-1.0)'], {'atol': '(0.1)'}), '(b, -1.0, atol=0.1)\n', (3783, 3802), True, 'import numpy as np\n'), ((3894, 3952), 'numpy.array', 'np.array', (['[[0.0, 1.0], [1.0, 0.0], [2.0, 0.0], [0.0, 2.0]]'], {}), '([[0.0, 1.0], [1.0, 0.0], [2.0, 0.0], [0.0, 2.0]])\n', (3902, 3952), True, 'import numpy as np\n'), ((4010, 4042), 'numpy.array', 'np.array', (['[-1.0, -1.0, 1.0, 1.0]'], {}), '([-1.0, -1.0, 1.0, 1.0])\n', (4018, 4042), True, 'import numpy as np\n'), ((4106, 4141), 'numpy.allclose', 'np.allclose', (['(w[0] + b)', '(-1)'], {'atol': '(0.1)'}), '(w[0] + b, -1, atol=0.1)\n', (4117, 4141), True, 'import numpy as np\n'), ((4153, 4188), 'numpy.allclose', 'np.allclose', (['(w[1] + b)', '(-1)'], {'atol': '(0.1)'}), '(w[1] + b, -1, atol=0.1)\n', (4164, 4188), True, 'import numpy as np\n'), ((4200, 4241), 'numpy.allclose', 'np.allclose', (['(w[0] + w[1] + b)', '(1)'], {'atol': '(0.1)'}), '(w[0] + w[1] + b, 1, atol=0.1)\n', (4211, 4241), True, 'import numpy as np\n'), ((4307, 4339), 'numpy.allclose', 'np.allclose', (['w', '[0, 0]'], {'atol': '(0.1)'}), '(w, [0, 0], atol=0.1)\n', (4318, 4339), True, 'import numpy as np\n'), ((4476, 4534), 'numpy.array', 'np.array', (['[[0.0, 1.0], [1.0, 0.0], [0.0, 0.0], [1.0, 1.0]]'], {}), '([[0.0, 1.0], [1.0, 0.0], [0.0, 0.0], [1.0, 1.0]])\n', (4484, 4534), True, 'import numpy as np\n'), ((4585, 4605), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (4593, 4605), True, 'import numpy as np\n'), ((4710, 4751), 'numpy.allclose', 'np.allclose', (['y', '[1, 1, -1, 1]'], {'atol': '(0.001)'}), '(y, [1, 1, -1, 1], atol=0.001)\n', (4721, 4751), True, 'import numpy as np\n'), ((4800, 4843), 'numpy.allclose', 'np.allclose', (['y', '[-1, -1, -1, 1]'], {'atol': '(0.001)'}), '(y, [-1, -1, -1, 1], atol=0.001)\n', (4811, 4843), True, 'import numpy as np\n'), ((4852, 4872), 'numpy.array', 'np.array', (['[2.0, 1.0]'], {}), '([2.0, 1.0])\n', (4860, 4872), True, 'import numpy as np\n'), ((4918, 4960), 'numpy.allclose', 'np.allclose', (['y', '[-1, 1, -1, 1]'], {'atol': '(0.001)'}), '(y, [-1, 1, -1, 1], atol=0.001)\n', (4929, 4960), True, 'import numpy as np\n'), ((5147, 5194), 'numpy.loadtxt', 'np.loadtxt', (['"""X.csv"""'], {'dtype': 'float', 'delimiter': '""","""'}), "('X.csv', dtype=float, delimiter=',')\n", (5157, 5194), True, 'import numpy as np\n'), ((5200, 5245), 'numpy.loadtxt', 'np.loadtxt', (['"""y.csv"""'], {'dtype': 'int', 'delimiter': '""","""'}), "('y.csv', dtype=int, delimiter=',')\n", (5210, 5245), True, 'import numpy as np\n'), ((2368, 2388), 'numpy.array', 'np.array', (['[1.0, 0.5]'], {}), '([1.0, 0.5])\n', (2376, 2388), True, 'import numpy as np\n')] |
# Created by <NAME> (<EMAIL>)
from pdb import set_trace
import numpy as np
import numpy.linalg as la
from ConfigSpace import ConfigurationSpace
from ConfigSpace.hyperparameters import UniformIntegerHyperparameter
from .model import Model, ModelFactory
#from ..hyper import IntRangeHyperparam
class ARXFactory(ModelFactory):
R"""
Autoregression with Exogenous Variable (ARX) learns the dynamics as
a linear function of the last :math:`k` observations and controls.
That is
.. math::
x_{t+1} = [x_t, \ldots x_{t-k+1}, u_t, \ldots, u_{t-k+1}] \theta
The model is trained least-squared linear regression.
Hyperparameters:
- *history* (Type: int, Low: 1, High: 10, Default: 4): Size of history window
for ARX model.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.Model = ARX
self.name = "ARX"
def get_configuration_space(self):
cs = ConfigurationSpace()
history = UniformIntegerHyperparameter(name='history',
lower=1, upper=10, default_value=4)
cs.add_hyperparameter(history)
return cs
class ARX(Model):
def __init__(self, system, history):
super().__init__(system)
self.k = history
def _get_feature_vector(self, traj, t=None):
k = self.k
if t is None:
t = len(traj)
feature_elements = [traj[t-1].obs]
for i in range(t-2, t-k-1, -1):
if i >= 0:
feature_elements += [traj[i].obs, traj[i].ctrl]
else:
feature_elements += [traj[0].obs, traj[0].ctrl]
feature_elements += [np.ones(1), traj[t-1].ctrl]
return np.concatenate(feature_elements)
def _get_all_feature_vectors(self, traj):
k = self.k
feature_vectors = np.zeros((len(traj), k*(self.system.obs_dim + self.system.ctrl_dim)+1))
feature_vectors[:,:self.system.obs_dim] = traj.obs
j = self.system.obs_dim
for i in range(1, k, 1):
feature_vectors[:,j:j+self.system.obs_dim] = np.concatenate([traj.obs[:1,:]]*i + [traj.obs[:-i, :]])
j += self.system.obs_dim
feature_vectors[:,j:j+self.system.ctrl_dim] = np.concatenate([traj.ctrls[:1,:]]*i + [traj.ctrls[:-i, :]])
j += self.system.ctrl_dim
feature_vectors[:,-(self.system.ctrl_dim+1)] = 1
feature_vectors[:,-self.system.ctrl_dim:] = traj.ctrls
return feature_vectors
def _get_fvec_size(self):
k = self.k
return 1 + k*self.system.obs_dim + k*self.system.ctrl_dim
def _get_training_matrix_and_targets(self, trajs):
nsamples = sum([len(traj) for traj in trajs])
matrix = np.zeros((nsamples, self._get_fvec_size()))
targets = np.zeros((nsamples, self.system.obs_dim))
i = 0
for traj in trajs:
for t in range(1, len(traj)):
matrix[i, :] = self._get_feature_vector(traj, t)
targets[i, :] = traj[t].obs
i += 1
return matrix, targets
def update_state(self, state, new_ctrl, new_obs):
# Shift the targets
newstate = self.A @ state + self.B @ new_ctrl
newstate[:self.system.obs_dim] = new_obs
return newstate
def traj_to_state(self, traj):
return self._get_feature_vector(traj)[:-self.system.ctrl_dim]
def traj_to_states(self, traj):
return self._get_all_feature_vectors(traj)[:, :-self.system.ctrl_dim]
def state_to_obs(self, state):
return state[0:self.system.obs_dim]
def train(self, trajs, silent=False):
matrix, targets = self._get_training_matrix_and_targets(trajs)
coeffs = np.zeros((self.system.obs_dim, self._get_fvec_size()))
for i in range(targets.shape[1]):
res, _, _, _ = la.lstsq(matrix, targets[:,i], rcond=None)
coeffs[i,:] = res
# First we construct the system matrices
A = np.zeros((self.state_dim, self.state_dim))
B = np.zeros((self.state_dim, self.system.ctrl_dim))
# Constant term
A[-1,-1] = 1.0
# Shift history
n = self.system.obs_dim
l = self.system.ctrl_dim
m = self.system.obs_dim + self.system.ctrl_dim
k = self.k
if k > 1:
A[n : 2*n, 0 : n] = np.eye(n)
for i in range(k-2):
A[(i+1)*m+n : (i+2)*m+n, i*m+n : (i+1)*m+n] = np.eye(m)
# Predict new observation
A[0 : n, :] = coeffs[:, :-l]
# Add new control
B[0 : n, :] = coeffs[:, -l:]
B[2*n : 2*n + l, :] = np.eye(l)
self.A, self.B = A, B
def pred(self, state, ctrl):
statenew = self.A @ state + self.B @ ctrl
return statenew
def pred_batch(self, states, ctrls):
statesnew = self.A @ states.T + self.B @ ctrls.T
return statesnew.T
def pred_diff(self, state, ctrl):
statenew = self.A @ state + self.B @ ctrl
return statenew, self.A, self.B
def to_linear(self):
return self.A, self.B
@property
def state_dim(self):
return self._get_fvec_size() - self.system.ctrl_dim
def get_parameters(self):
return {"coeffs" : np.copy(self.coeffs)}
def set_parameters(self, params):
self.coeffs = np.copy(params["coeffs"])
| [
"ConfigSpace.ConfigurationSpace",
"numpy.linalg.lstsq",
"numpy.copy",
"ConfigSpace.hyperparameters.UniformIntegerHyperparameter",
"numpy.zeros",
"numpy.ones",
"numpy.eye",
"numpy.concatenate"
] | [((961, 981), 'ConfigSpace.ConfigurationSpace', 'ConfigurationSpace', ([], {}), '()\n', (979, 981), False, 'from ConfigSpace import ConfigurationSpace\n'), ((1000, 1085), 'ConfigSpace.hyperparameters.UniformIntegerHyperparameter', 'UniformIntegerHyperparameter', ([], {'name': '"""history"""', 'lower': '(1)', 'upper': '(10)', 'default_value': '(4)'}), "(name='history', lower=1, upper=10, default_value=4\n )\n", (1028, 1085), False, 'from ConfigSpace.hyperparameters import UniformIntegerHyperparameter\n'), ((1715, 1747), 'numpy.concatenate', 'np.concatenate', (['feature_elements'], {}), '(feature_elements)\n', (1729, 1747), True, 'import numpy as np\n'), ((2807, 2848), 'numpy.zeros', 'np.zeros', (['(nsamples, self.system.obs_dim)'], {}), '((nsamples, self.system.obs_dim))\n', (2815, 2848), True, 'import numpy as np\n'), ((4001, 4043), 'numpy.zeros', 'np.zeros', (['(self.state_dim, self.state_dim)'], {}), '((self.state_dim, self.state_dim))\n', (4009, 4043), True, 'import numpy as np\n'), ((4056, 4104), 'numpy.zeros', 'np.zeros', (['(self.state_dim, self.system.ctrl_dim)'], {}), '((self.state_dim, self.system.ctrl_dim))\n', (4064, 4104), True, 'import numpy as np\n'), ((4641, 4650), 'numpy.eye', 'np.eye', (['l'], {}), '(l)\n', (4647, 4650), True, 'import numpy as np\n'), ((5347, 5372), 'numpy.copy', 'np.copy', (["params['coeffs']"], {}), "(params['coeffs'])\n", (5354, 5372), True, 'import numpy as np\n'), ((1672, 1682), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (1679, 1682), True, 'import numpy as np\n'), ((2093, 2151), 'numpy.concatenate', 'np.concatenate', (['([traj.obs[:1, :]] * i + [traj.obs[:-i, :]])'], {}), '([traj.obs[:1, :]] * i + [traj.obs[:-i, :]])\n', (2107, 2151), True, 'import numpy as np\n'), ((2244, 2306), 'numpy.concatenate', 'np.concatenate', (['([traj.ctrls[:1, :]] * i + [traj.ctrls[:-i, :]])'], {}), '([traj.ctrls[:1, :]] * i + [traj.ctrls[:-i, :]])\n', (2258, 2306), True, 'import numpy as np\n'), ((3866, 3909), 'numpy.linalg.lstsq', 'la.lstsq', (['matrix', 'targets[:, i]'], {'rcond': 'None'}), '(matrix, targets[:, i], rcond=None)\n', (3874, 3909), True, 'import numpy.linalg as la\n'), ((4368, 4377), 'numpy.eye', 'np.eye', (['n'], {}), '(n)\n', (4374, 4377), True, 'import numpy as np\n'), ((4465, 4474), 'numpy.eye', 'np.eye', (['m'], {}), '(m)\n', (4471, 4474), True, 'import numpy as np\n'), ((5264, 5284), 'numpy.copy', 'np.copy', (['self.coeffs'], {}), '(self.coeffs)\n', (5271, 5284), True, 'import numpy as np\n')] |
from typing import Optional, Union
import numpy as np
import pandas as pd
from bokeh.io import output_notebook, reset_output
from bokeh.models import Legend, Dropdown, ColumnDataSource, CustomJS
from bokeh.plotting import figure, output_file, show
from bokeh.layouts import column
from bokeh.events import MenuItemClick
from wellcomeml.viz.palettes import (Wellcome33, WellcomeBackground, WellcomeNoData)
def visualize_clusters(clustering, filter_list: Optional[list] = None,
texts: Optional[list] = None,
radius: float = 0.05,
alpha: float = 0.5,
plot_width: int = 1000, plot_height: int = 530,
output_in_notebook: bool = True,
output_file_path: Optional[str] = None,
palette: Union[list, str] = 'Wellcome33'):
"""
This function creates a plot of the clusters
Args:
clustering: wellcomeml.ml.TextClustering instance
filter_list: list
texts: A list of texts to be displayed by the hover function
radius: float, default: 0.05
alpha: float, default: 0.5
plot_width: int, default: 600
plot_height: int, default: 600
output_in_notebook: bool, default: True
output_file_path: str, default: 'cluster_viz.html'
palette: list, default: Wellcome33
Returns:
None (Prints a bokeh figure)
"""
# Dataframe creation
reduced_points = clustering.reduced_points
data = pd.DataFrame(reduced_points)
data = data.rename(columns={0: 'X', 1: 'Y'})
data['cluster_id'] = clustering.cluster_ids
data['cluster_id'] = data['cluster_id'].astype(str)
data['Keywords'] = clustering.cluster_kws
data['category'] = (filter_list if filter_list else ['All']*len(data))
# Palette setting
palette = (Wellcome33 if palette == 'Wellcome33' else palette)
palette = [str(x) for x in palette]
well_background = str(WellcomeBackground)
clusters = list(data['cluster_id'])
clusters = list(map(int, clusters))
clusters_uniq = np.unique(clusters)
data['colors'] = [(palette[x % len(palette)]
if x != -1 else str(WellcomeNoData)) for x in clusters]
tools = ('hover, pan, wheel_zoom, zoom_in, zoom_out, reset, save, tap')
tooltips = [("index", "$index"), ("(x,y)", "($x, $y)"),
("cluster", "@cluster_id"), ("keywords", "@Keywords")]
if texts is not None:
# Only gets the 60 characters of the text
data['text'] = [text[:60] + '...' for text in texts]
tooltips += [("text", "@text")]
# DropDown Button
dropdown_options = list(set([('All', 'All'), None] +
[(cat, cat) for i, cat in enumerate(sorted(
data['category'].unique()), 2)]))
dropdown = Dropdown(label='Category', button_type='default',
menu=dropdown_options, width=190, align="end")
# Defines figure for plotting the clusters
p = figure(title="Cluster visualization", toolbar_location="above",
plot_width=plot_width, plot_height=plot_height,
tools=tools, tooltips=tooltips,
background_fill_color=well_background)
R = []
sources = []
filtered_sources = []
for x in clusters_uniq:
data_cluster_id_unfiltered = data[data['cluster_id'] == str(x)]
sources.append(ColumnDataSource(data_cluster_id_unfiltered))
filtered_sources.append(ColumnDataSource(data_cluster_id_unfiltered))
# Plots the cluster
r = p.circle(x="X", y="Y", radius=radius, fill_alpha=alpha,
color="colors", source=filtered_sources[-1])
R += [r]
# JavaScript callback for the Dropdown Button
callback = CustomJS(
args=dict(sources=sources, filtered_sources=filtered_sources),
code="""
var data = []
var cat = cb_obj.item;
function generateNewDataObject(oldDataObject){
var newDataObject = {}
for (var key of Object.keys(oldDataObject)){
newDataObject[key] = [];
}
return newDataObject
}
function addRowToAccumulator(accumulator, dataObject, index) {
for (var key of Object.keys(dataObject)){
accumulator[key][index] = dataObject[key][index];
}
return accumulator;
}
if (cat === 'All') {
for (var i = 0; i < sources.length; i++) {
data.push(sources[i].data);
}
} else {
for (var i = 0; i < sources.length; i++) {
let new_data = generateNewDataObject(sources[i].data);
for (var j = 0; j <= sources[i].data['category'].length; j++) {
if (sources[i].data['category'][j] == cat) {
new_data = addRowToAccumulator(new_data, sources[i].data,
j);
}
}
data[i] = new_data
}
}
for (var i = 0; i < sources.length; i++) {
filtered_sources[i].data = data[i]
filtered_sources[i].change.emit()
}
"""
)
dropdown.js_on_event(MenuItemClick, callback)
# Plots the legend on two columns
if len(clusters_uniq) > 36:
median = len(R) // 2
legend1 = Legend(items=[(str(s), [r]) for s, r in
zip(clusters_uniq[:median], R[:median])])
legend2 = Legend(items=[(str(s), [r]) for s, r in
zip(clusters_uniq[median:], R[median:])])
p.add_layout(legend1, 'right')
p.add_layout(legend2, 'right')
else:
legend = Legend(items=[(str(s), [r]) for s, r in
zip(clusters_uniq, R)])
p.add_layout(legend, 'right')
# Plots other extra annotations to the plot
p.legend.title = "Cluster ID"
p.legend.label_text_font_size = "11px"
p.legend.background_fill_color = str(WellcomeBackground)
p.legend.click_policy = "hide"
p.min_border_left = 200
# Output in notebook and new page
reset_output()
if output_in_notebook:
output_notebook()
if output_file_path:
output_file(output_file_path)
show(column(dropdown, p))
| [
"pandas.DataFrame",
"bokeh.models.ColumnDataSource",
"bokeh.plotting.figure",
"bokeh.io.output_notebook",
"bokeh.models.Dropdown",
"bokeh.plotting.output_file",
"bokeh.layouts.column",
"bokeh.io.reset_output",
"numpy.unique"
] | [((1541, 1569), 'pandas.DataFrame', 'pd.DataFrame', (['reduced_points'], {}), '(reduced_points)\n', (1553, 1569), True, 'import pandas as pd\n'), ((2120, 2139), 'numpy.unique', 'np.unique', (['clusters'], {}), '(clusters)\n', (2129, 2139), True, 'import numpy as np\n'), ((2895, 2995), 'bokeh.models.Dropdown', 'Dropdown', ([], {'label': '"""Category"""', 'button_type': '"""default"""', 'menu': 'dropdown_options', 'width': '(190)', 'align': '"""end"""'}), "(label='Category', button_type='default', menu=dropdown_options,\n width=190, align='end')\n", (2903, 2995), False, 'from bokeh.models import Legend, Dropdown, ColumnDataSource, CustomJS\n'), ((3072, 3263), 'bokeh.plotting.figure', 'figure', ([], {'title': '"""Cluster visualization"""', 'toolbar_location': '"""above"""', 'plot_width': 'plot_width', 'plot_height': 'plot_height', 'tools': 'tools', 'tooltips': 'tooltips', 'background_fill_color': 'well_background'}), "(title='Cluster visualization', toolbar_location='above', plot_width=\n plot_width, plot_height=plot_height, tools=tools, tooltips=tooltips,\n background_fill_color=well_background)\n", (3078, 3263), False, 'from bokeh.plotting import figure, output_file, show\n'), ((6142, 6156), 'bokeh.io.reset_output', 'reset_output', ([], {}), '()\n', (6154, 6156), False, 'from bokeh.io import output_notebook, reset_output\n'), ((6192, 6209), 'bokeh.io.output_notebook', 'output_notebook', ([], {}), '()\n', (6207, 6209), False, 'from bokeh.io import output_notebook, reset_output\n'), ((6244, 6273), 'bokeh.plotting.output_file', 'output_file', (['output_file_path'], {}), '(output_file_path)\n', (6255, 6273), False, 'from bokeh.plotting import figure, output_file, show\n'), ((6284, 6303), 'bokeh.layouts.column', 'column', (['dropdown', 'p'], {}), '(dropdown, p)\n', (6290, 6303), False, 'from bokeh.layouts import column\n'), ((3479, 3523), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', (['data_cluster_id_unfiltered'], {}), '(data_cluster_id_unfiltered)\n', (3495, 3523), False, 'from bokeh.models import Legend, Dropdown, ColumnDataSource, CustomJS\n'), ((3557, 3601), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', (['data_cluster_id_unfiltered'], {}), '(data_cluster_id_unfiltered)\n', (3573, 3601), False, 'from bokeh.models import Legend, Dropdown, ColumnDataSource, CustomJS\n')] |
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from .planefit import plane_z
def scatter_3d(pcloud, **scatter_kwargs):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = pcloud[:, 0]
y = pcloud[:, 1]
z = pcloud[:, 2]
ax.scatter(x, y, z, **scatter_kwargs)
plt.show()
def arange_fixed_len(a, b, n_steps=100):
step = (b - a) / n_steps
return np.arange(a, b, step)
def plot_plane_3d(plane_coefs, pcloud):
min_vals = pcloud.min(axis=0)
max_vals = pcloud.max(axis=0)
range_x = arange_fixed_len(min_vals[0], max_vals[0])
range_y = arange_fixed_len(min_vals[1], max_vals[1])
xx, yy = np.meshgrid(range_x, range_y)
zz = plane_z(plane_coefs, xx, yy)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = pcloud[:, 0]
y = pcloud[:, 1]
z = pcloud[:, 2]
ax.scatter(x, y, z)
ax.plot_surface(xx, yy, zz, alpha=0.4)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
| [
"matplotlib.pyplot.figure",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"numpy.arange"
] | [((181, 193), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (191, 193), True, 'from matplotlib import pyplot as plt\n'), ((353, 363), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (361, 363), True, 'from matplotlib import pyplot as plt\n'), ((447, 468), 'numpy.arange', 'np.arange', (['a', 'b', 'step'], {}), '(a, b, step)\n', (456, 468), True, 'import numpy as np\n'), ((709, 738), 'numpy.meshgrid', 'np.meshgrid', (['range_x', 'range_y'], {}), '(range_x, range_y)\n', (720, 738), True, 'import numpy as np\n'), ((788, 800), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (798, 800), True, 'from matplotlib import pyplot as plt\n'), ((1055, 1065), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1063, 1065), True, 'from matplotlib import pyplot as plt\n')] |
from os.path import exists
import pandas as pd
import numpy as np
from scripts.progress_bar.progress_bar import printProgressBar
def check_one_file(file_path, index, l):
printProgressBar(index, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
return exists(file_path)
def concatenate(row, other_row):
return str(row) + str(other_row) + '.pdf'
def make_path_check_exist(csv_source, csv_dest, source_folder):
df = pd.read_csv(csv_source)
df_copy = df.copy()
df_copy['path'] = source_folder
func_concat = np.vectorize(concatenate)
values = func_concat(df_copy['path'], df_copy['index'])
df_copy['path'] = values.tolist()
l = len(df_copy.index)
func_check_exist = np.vectorize(check_one_file)
values = func_check_exist(df_copy['path'], df_copy['index'], l)
df_copy['exist'] = values.tolist()
df_copy.to_csv(csv_dest, index=False)
if __name__ == '__main__':
make_path_check_exist('csv_files/url_thesis_8211.csv', 'csv_files/url_thesis_8211_exist.csv', 'thesis_pdf_all/')
| [
"scripts.progress_bar.progress_bar.printProgressBar",
"os.path.exists",
"pandas.read_csv",
"numpy.vectorize"
] | [((175, 251), 'scripts.progress_bar.progress_bar.printProgressBar', 'printProgressBar', (['index', 'l'], {'prefix': '"""Progress:"""', 'suffix': '"""Complete"""', 'length': '(50)'}), "(index, l, prefix='Progress:', suffix='Complete', length=50)\n", (191, 251), False, 'from scripts.progress_bar.progress_bar import printProgressBar\n'), ((269, 286), 'os.path.exists', 'exists', (['file_path'], {}), '(file_path)\n', (275, 286), False, 'from os.path import exists\n'), ((441, 464), 'pandas.read_csv', 'pd.read_csv', (['csv_source'], {}), '(csv_source)\n', (452, 464), True, 'import pandas as pd\n'), ((549, 574), 'numpy.vectorize', 'np.vectorize', (['concatenate'], {}), '(concatenate)\n', (561, 574), True, 'import numpy as np\n'), ((725, 753), 'numpy.vectorize', 'np.vectorize', (['check_one_file'], {}), '(check_one_file)\n', (737, 753), True, 'import numpy as np\n')] |
"""
Implementation of the original DQN Nature paper:
https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf
Some of the complexity is captured via wrappers but the main components such as the DQN model itself,
the training loop, the memory-efficient replay buffer are implemented from scratch.
Some modifications:
* Using Adam instead of RMSProp
"""
import os
import argparse
import time
import copy
import numpy as np
import torch
from torch import nn
import matplotlib.pyplot as plt
from torch.optim import Adam
from torch.utils.tensorboard import SummaryWriter
import utils.utils as utils
from utils.replay_buffer import ReplayBuffer
from utils.constants import *
from models.definitions.DQN import DQN
class ActorLearner:
def __init__(self, config, env, replay_buffer, dqn, target_dqn, last_frame):
self.start_time = time.time()
self.config = config
self.env = env
self.last_frame = last_frame # always keeps the latest frame from the environment
self.replay_buffer = replay_buffer
# DQN Models
self.dqn = dqn
self.target_dqn = target_dqn
# Logging/debugging-related
self.debug = config['debug']
self.log_freq = config['log_freq']
self.episode_log_freq = config['episode_log_freq']
self.grads_log_freq = config['grads_log_freq']
self.checkpoint_freq = config['checkpoint_freq']
self.tensorboard_writer = SummaryWriter()
self.huber_loss = []
self.best_episode_reward = -np.inf
self.best_dqn_model = None # keeps a deep copy of the best DQN model so far (best = highest episode reward)
# MSE/L2 between [-1,1] and L1 otherwise (as stated in the Nature paper) aka "Huber loss"
self.loss = nn.SmoothL1Loss()
self.optimizer = Adam(self.dqn.parameters(), lr=config['learning_rate'])
self.grad_clip_value = config['grad_clipping_value']
self.acting_learning_step_ratio = config['acting_learning_step_ratio']
self.num_warmup_steps = config['num_warmup_steps']
self.batch_size = config['batch_size']
self.gamma = config['gamma'] # discount factor
self.learner_cnt = 0
self.target_dqn_update_interval = config['target_dqn_update_interval']
# should perform a hard or a soft update of target DQN weights
self.tau = config['tau']
def collect_experience(self):
# We're collecting more experience than we're doing weight updates (4x in the Nature paper)
for _ in range(self.acting_learning_step_ratio):
last_index = self.replay_buffer.store_frame(self.last_frame)
state = self.replay_buffer.fetch_last_state() # state = 4 preprocessed last frames for Atari
action = self.sample_action(state)
new_frame, reward, done_flag, _ = self.env.step(action)
self.replay_buffer.store_action_reward_done(last_index, action, reward, done_flag)
if done_flag:
new_frame = self.env.reset()
self.maybe_log_episode()
self.last_frame = new_frame
if self.debug:
self.visualize_state(state)
self.env.render()
self.maybe_log()
def sample_action(self, state):
if self.env.get_total_steps() < self.num_warmup_steps:
action = self.env.action_space.sample() # initial warm up period - no learning, acting randomly
else:
with torch.no_grad():
action = self.dqn.epsilon_greedy(state)
return action
def get_number_of_env_steps(self):
return self.env.get_total_steps()
def learn_from_experience(self):
current_states, actions, rewards, next_states, done_flags = self.replay_buffer.fetch_random_states(self.batch_size)
# Better than detaching: in addition to target dqn not being a part of the computational graph it also
# saves time/memory because we're not storing activations during forward propagation needed for the backprop
with torch.no_grad():
# shape = (B, NA) -> (B, 1), where NA - number of actions
# [0] because max returns (values, indices) tuples
next_state_max_q_values = self.target_dqn(next_states).max(dim=1, keepdim=True)[0]
# shape = (B, 1), TD targets. We need (1 - done) because when we're in a terminal state the next
# state Q value should be 0 and we only use the reward information
target_q_values = rewards + (1 - done_flags) * self.gamma * next_state_max_q_values
# shape = (B, 1), pick those Q values that correspond to the actions we made in those states
current_state_q_values = self.dqn(current_states).gather(dim=1, index=actions)
loss = self.loss(target_q_values, current_state_q_values)
self.huber_loss.append(loss.item())
self.optimizer.zero_grad()
loss.backward() # compute the gradients
if self.grad_clip_value is not None: # potentially clip gradients for stability reasons
nn.utils.clip_grad_norm_(self.dqn.parameters(), self.grad_clip_value)
self.optimizer.step() # update step
self.learner_cnt += 1
# Periodically update the target DQN weights (coupled to the number of DQN weight updates and not # env steps)
if self.learner_cnt % self.target_dqn_update_interval == 0:
if self.tau == 1.:
print('Update target DQN (hard update)')
self.target_dqn.load_state_dict(self.dqn.state_dict())
else: # soft update, the 2 branches can be merged together, leaving it like this for now
raise Exception(f'Soft update is not yet implemented (hard update was used in the original paper)')
@staticmethod
def visualize_state(state):
state = state[0].to('cpu').numpy() # (1/B, C, H, W) -> (C, H, W)
stacked_frames = np.hstack([np.repeat((img * 255).astype(np.uint8)[:, :, np.newaxis], 3, axis=2) for img in state]) # (C, H, W) -> (H, C*W, 3)
plt.imshow(stacked_frames)
plt.show()
def maybe_log_episode(self):
rewards = self.env.get_episode_rewards() # we can do this thanks to the Monitor wrapper
episode_lengths = self.env.get_episode_lengths()
num_episodes = len(rewards)
if self.episode_log_freq is not None and num_episodes % self.episode_log_freq == 0:
self.tensorboard_writer.add_scalar('Rewards per episode', rewards[-1], num_episodes)
self.tensorboard_writer.add_scalar('Steps per episode', episode_lengths[-1], num_episodes)
if rewards[-1] > self.best_episode_reward:
self.best_episode_reward = rewards[-1]
self.config['best_episode_reward'] = self.best_episode_reward # metadata
self.best_dqn_model = copy.deepcopy(self.dqn) # keep track of the model that gave the best reward
def maybe_log(self):
num_steps = self.env.get_total_steps()
if self.log_freq is not None and num_steps > 0 and num_steps % self.log_freq == 0:
self.tensorboard_writer.add_scalar('Epsilon', self.dqn.epsilon_value(), num_steps)
if len(self.huber_loss) > 0:
self.tensorboard_writer.add_scalar('Huber loss', np.mean(self.huber_loss), num_steps)
self.tensorboard_writer.add_scalar('FPS', num_steps / (time.time() - self.start_time), num_steps)
self.huber_loss = [] # clear the loss values and start recollecting them again
# Periodically save DQN models
if self.checkpoint_freq is not None and num_steps > 0 and num_steps % self.checkpoint_freq == 0:
ckpt_model_name = f'dqn_{self.config["env_id"]}_ckpt_steps_{num_steps}.pth'
torch.save(utils.get_training_state(self.config, self.dqn), os.path.join(CHECKPOINTS_PATH, ckpt_model_name))
# Log the gradients
if self.grads_log_freq is not None and self.learner_cnt > 0 and self.learner_cnt % self.grads_log_freq == 0:
total_grad_l2_norm = 0
for cnt, (name, weight_or_bias_parameters) in enumerate(self.dqn.named_parameters()):
grad_l2_norm = weight_or_bias_parameters.grad.data.norm(p=2).item()
self.tensorboard_writer.add_scalar(f'grad_norms/{name}', grad_l2_norm, self.learner_cnt)
total_grad_l2_norm += grad_l2_norm ** 2
# As if we concatenated all of the params into a single vector and took L2
total_grad_l2_norm = total_grad_l2_norm ** (1/2)
self.tensorboard_writer.add_scalar(f'grad_norms/total', total_grad_l2_norm, self.learner_cnt)
def log_to_console(self): # keep it minimal for now, I mostly use tensorboard - feel free to expand functionality
print(f'Number of env steps = {self.get_number_of_env_steps()}')
def train_dqn(config):
env = utils.get_env_wrapper(config['env_id'])
replay_buffer = ReplayBuffer(config['replay_buffer_size'], crash_if_no_mem=config['dont_crash_if_no_mem'])
utils.set_random_seeds(env, config['seed'])
linear_schedule = utils.LinearSchedule(
config['epsilon_start_value'],
config['epsilon_end_value'],
config['epsilon_duration']
)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
dqn = DQN(env, number_of_actions=env.action_space.n, epsilon_schedule=linear_schedule).to(device)
target_dqn = DQN(env, number_of_actions=env.action_space.n).to(device)
# Don't get confused by the actor-learner terminology, DQN is not an actor-critic method, but conceptually
# we can split the learning process into collecting experience/acting in the env and learning from that experience
actor_learner = ActorLearner(config, env, replay_buffer, dqn, target_dqn, env.reset())
while actor_learner.get_number_of_env_steps() < config['num_of_training_steps']:
num_env_steps = actor_learner.get_number_of_env_steps()
if config['console_log_freq'] is not None and num_env_steps % config['console_log_freq'] == 0:
actor_learner.log_to_console()
actor_learner.collect_experience()
if num_env_steps > config['num_warmup_steps']:
actor_learner.learn_from_experience()
torch.save( # save the best DQN model overall (gave the highest reward in an episode)
utils.get_training_state(config, actor_learner.best_dqn_model),
os.path.join(BINARIES_PATH, utils.get_available_binary_name(config['env_id']))
)
def get_training_args():
parser = argparse.ArgumentParser()
# Training related
parser.add_argument("--seed", type=int, help="Very important for reproducibility - set the random seed", default=23)
parser.add_argument("--env_id", type=str, help="Atari game id", default='BreakoutNoFrameskip-v4')
parser.add_argument("--num_of_training_steps", type=int, help="Number of training env steps", default=50000000)
parser.add_argument("--acting_learning_step_ratio", type=int, help="Number of experience collection steps for every learning step", default=4)
parser.add_argument("--learning_rate", type=float, default=1e-4)
parser.add_argument("--grad_clipping_value", type=float, default=5) # 5 is fairly arbitrarily chosen
parser.add_argument("--replay_buffer_size", type=int, help="Number of frames to store in buffer", default=1000000)
parser.add_argument("--dont_crash_if_no_mem", action='store_false', help="Optimization - crash if not enough RAM before the training even starts (default=True)")
parser.add_argument("--num_warmup_steps", type=int, help="Number of steps before learning starts", default=50000)
parser.add_argument("--target_dqn_update_interval", type=int, help="Target DQN update freq per learning update", default=10000)
parser.add_argument("--batch_size", type=int, help="Number of states in a batch (from replay buffer)", default=32)
parser.add_argument("--gamma", type=float, help="Discount factor", default=0.99)
parser.add_argument("--tau", type=float, help='Set to 1 for a hard target DQN update, < 1 for a soft one', default=1.)
# epsilon-greedy annealing params
parser.add_argument("--epsilon_start_value", type=float, default=1.)
parser.add_argument("--epsilon_end_value", type=float, default=0.1)
parser.add_argument("--epsilon_duration", type=int, default=1000000)
# Logging/debugging/checkpoint related (helps a lot with experimentation)
parser.add_argument("--console_log_freq", type=int, help="Log to console after this many env steps (None = no logging)", default=10000)
parser.add_argument("--log_freq", type=int, help="Log metrics to tensorboard after this many env steps (None = no logging)", default=10000)
parser.add_argument("--episode_log_freq", type=int, help="Log metrics to tensorboard after this many episodes (None = no logging)", default=5)
parser.add_argument("--checkpoint_freq", type=int, help="Save checkpoint model after this many env steps (None = no checkpointing)", default=10000)
parser.add_argument("--grads_log_freq", type=int, help="Log grad norms after this many weight update steps (None = no logging)", default=2500)
parser.add_argument("--debug", action='store_true', help='Train in debugging mode')
args = parser.parse_args()
# Wrapping training configuration into a dictionary
training_config = dict()
for arg in vars(args):
training_config[arg] = getattr(args, arg)
return training_config
if __name__ == '__main__':
# Train the DQN model
train_dqn(get_training_args())
| [
"utils.utils.get_env_wrapper",
"utils.utils.LinearSchedule",
"copy.deepcopy",
"models.definitions.DQN.DQN",
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"os.path.join",
"matplotlib.pyplot.imshow",
"time.time",
"utils.utils.set_random_seeds",
"numpy.mean",
"torch.cuda.is_available",
"... | [((8979, 9018), 'utils.utils.get_env_wrapper', 'utils.get_env_wrapper', (["config['env_id']"], {}), "(config['env_id'])\n", (9000, 9018), True, 'import utils.utils as utils\n'), ((9039, 9134), 'utils.replay_buffer.ReplayBuffer', 'ReplayBuffer', (["config['replay_buffer_size']"], {'crash_if_no_mem': "config['dont_crash_if_no_mem']"}), "(config['replay_buffer_size'], crash_if_no_mem=config[\n 'dont_crash_if_no_mem'])\n", (9051, 9134), False, 'from utils.replay_buffer import ReplayBuffer\n'), ((9135, 9178), 'utils.utils.set_random_seeds', 'utils.set_random_seeds', (['env', "config['seed']"], {}), "(env, config['seed'])\n", (9157, 9178), True, 'import utils.utils as utils\n'), ((9202, 9315), 'utils.utils.LinearSchedule', 'utils.LinearSchedule', (["config['epsilon_start_value']", "config['epsilon_end_value']", "config['epsilon_duration']"], {}), "(config['epsilon_start_value'], config[\n 'epsilon_end_value'], config['epsilon_duration'])\n", (9222, 9315), True, 'import utils.utils as utils\n'), ((10659, 10684), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (10682, 10684), False, 'import argparse\n'), ((891, 902), 'time.time', 'time.time', ([], {}), '()\n', (900, 902), False, 'import time\n'), ((1494, 1509), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {}), '()\n', (1507, 1509), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((1818, 1835), 'torch.nn.SmoothL1Loss', 'nn.SmoothL1Loss', ([], {}), '()\n', (1833, 1835), False, 'from torch import nn\n'), ((6148, 6174), 'matplotlib.pyplot.imshow', 'plt.imshow', (['stacked_frames'], {}), '(stacked_frames)\n', (6158, 6174), True, 'import matplotlib.pyplot as plt\n'), ((6183, 6193), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6191, 6193), True, 'import matplotlib.pyplot as plt\n'), ((10462, 10524), 'utils.utils.get_training_state', 'utils.get_training_state', (['config', 'actor_learner.best_dqn_model'], {}), '(config, actor_learner.best_dqn_model)\n', (10486, 10524), True, 'import utils.utils as utils\n'), ((4127, 4142), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4140, 4142), False, 'import torch\n'), ((6934, 6957), 'copy.deepcopy', 'copy.deepcopy', (['self.dqn'], {}), '(self.dqn)\n', (6947, 6957), False, 'import copy\n'), ((9378, 9403), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (9401, 9403), False, 'import torch\n'), ((9426, 9511), 'models.definitions.DQN.DQN', 'DQN', (['env'], {'number_of_actions': 'env.action_space.n', 'epsilon_schedule': 'linear_schedule'}), '(env, number_of_actions=env.action_space.n, epsilon_schedule=linear_schedule\n )\n', (9429, 9511), False, 'from models.definitions.DQN import DQN\n'), ((9535, 9581), 'models.definitions.DQN.DQN', 'DQN', (['env'], {'number_of_actions': 'env.action_space.n'}), '(env, number_of_actions=env.action_space.n)\n', (9538, 9581), False, 'from models.definitions.DQN import DQN\n'), ((10562, 10611), 'utils.utils.get_available_binary_name', 'utils.get_available_binary_name', (["config['env_id']"], {}), "(config['env_id'])\n", (10593, 10611), True, 'import utils.utils as utils\n'), ((3546, 3561), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3559, 3561), False, 'import torch\n'), ((7873, 7920), 'utils.utils.get_training_state', 'utils.get_training_state', (['self.config', 'self.dqn'], {}), '(self.config, self.dqn)\n', (7897, 7920), True, 'import utils.utils as utils\n'), ((7922, 7969), 'os.path.join', 'os.path.join', (['CHECKPOINTS_PATH', 'ckpt_model_name'], {}), '(CHECKPOINTS_PATH, ckpt_model_name)\n', (7934, 7969), False, 'import os\n'), ((7377, 7401), 'numpy.mean', 'np.mean', (['self.huber_loss'], {}), '(self.huber_loss)\n', (7384, 7401), True, 'import numpy as np\n'), ((7481, 7492), 'time.time', 'time.time', ([], {}), '()\n', (7490, 7492), False, 'import time\n')] |
from datetime import datetime
import spacy
import pandas
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import numpy as np
import matplotlib.pyplot as plt
# torch geometric libraries
from torch_geometric.loader import DataLoader
from torch_geometric.data import Data
import torch_geometric.nn as pyg_nn
from torch_geometric.graphgym import optim
import torch_geometric.utils as pyg_utils
import time
import os
# visulise the graph
import networkx as nx
source_dir = 'data/en'
target_dir_net = 'data/net'
target_dir_figures = 'figures'
nlp = spacy.load("en_core_web_lg")
vector_size = 300 # the size of token vector representation s in en_core_web_lg model
def text_to_graph(text, y):
text_to_graph_start = time.time()
node_labels = {}
edge_index = [] # list of all edges in a graph
doc = nlp(text)
root = 0
for token in doc:
node_labels[token.i] = token.text
edge_index.append([token.i, token.i]) # add a self loop
if token.i == token.head.i:
root = token.i
else:
edge_index.append([token.i, token.head.i]) # add a connection from token to its parent
edge_index.append([token.head.i, token.i]) # add a reverse connection
x = torch.tensor(np.array([d.vector for d in doc])) # compute token embedings
edge_index = torch.tensor(edge_index, dtype=torch.long).t().contiguous() # torch geometric expects to get the edges in a matrix with to rows and a column for each connection
data = Data(x=x, edge_index=edge_index, y=torch.tensor([y]), text=text, root_index=root)
text_to_graph_end = time.time()
print(f"Text to graph took: {text_to_graph_end - text_to_graph_start:.2f} s")
return data, node_labels
def text_to_nx(text):
graph, labels = text_to_graph(text, 0)
graph_to_nx_start = time.time()
g = pyg_utils.to_networkx(graph, to_undirected=True)
nx.set_node_attributes(g, labels, 'label')
graph_to_nx_end = time.time()
print(f"Graph to nx took: {graph_to_nx_end - graph_to_nx_start:.2f} s")
return g, labels
def file_to_nx(filename):
f = open(filename, "r")
contents = f.read()
return text_to_nx(contents.replace('\r\n', ' ').replace('\n', ' '))
def process_file(filename):
print(f'Now working on: {filename}')
G, labels = file_to_nx(f'{source_dir}/{filename}.txt')
print('No. nodes: ', G.number_of_nodes())
print('No. edges: ', G.number_of_edges())
nx.write_gexf(G, f'{target_dir_net}/{filename}.gexf')
giant = G.subgraph(max(nx.connected_components(G), key=len))
print('No. nodes in LCSG: ', giant.number_of_nodes())
print('No. edges in LCSG: ', giant.number_of_edges())
nx.write_gexf(giant, f'{target_dir_net}/{filename}_lcsg.gexf')
words = nx.relabel_nodes(G, labels)
print('No. nodes in words: ', words.number_of_nodes())
print('No. edges in words: ', words.number_of_edges())
nx.write_gexf(words, f'{target_dir_net}/{filename}_words.gexf')
giant_words = words.subgraph(max(nx.connected_components(words), key=len))
print('No. nodes in words LCSG: ', giant_words.number_of_nodes())
print('No. edges in words LCSG: ', giant_words.number_of_edges())
nx.write_gexf(giant_words, f'{target_dir_net}/{filename}_words_lcsg.gexf')
# nx_draw_start = time.time()
# f = plt.figure()
# label_dict = nx.get_node_attributes(G, 'label')
# nx.draw(G, labels=label_dict, ax=f.add_subplot(1, 1, 1), with_labels = True)
# f.savefig(f"{target_dir_figures}/{filename}.pdf")
# plt.close(f)
# nx_draw_end = time.time()
# print(f"Full draw took: {nx_draw_end - nx_draw_start:.2f} s")
# nx_draw_start = time.time()
# f = plt.figure()
# label_dict = nx.get_node_attributes(giant, 'label')
# nx.draw(giant, labels=label_dict, ax=f.add_subplot(1, 1, 1), with_labels = True)
# f.savefig(f"{target_dir_figures}/{filename}_lcsg.pdf")
# plt.close(f)
# nx_draw_end = time.time()
# print(f"LCSG draw took: {nx_draw_end - nx_draw_start:.2f} s")
if __name__ == '__main__':
for file in os.listdir(source_dir):
if file.endswith(".txt"):
split = file.split('.')
filename = split[0]
print('=================')
process_file(filename) | [
"networkx.set_node_attributes",
"torch_geometric.utils.to_networkx",
"time.time",
"networkx.relabel_nodes",
"spacy.load",
"networkx.connected_components",
"numpy.array",
"networkx.write_gexf",
"os.listdir",
"torch.tensor"
] | [((615, 643), 'spacy.load', 'spacy.load', (['"""en_core_web_lg"""'], {}), "('en_core_web_lg')\n", (625, 643), False, 'import spacy\n'), ((786, 797), 'time.time', 'time.time', ([], {}), '()\n', (795, 797), False, 'import time\n'), ((1683, 1694), 'time.time', 'time.time', ([], {}), '()\n', (1692, 1694), False, 'import time\n'), ((1897, 1908), 'time.time', 'time.time', ([], {}), '()\n', (1906, 1908), False, 'import time\n'), ((1917, 1965), 'torch_geometric.utils.to_networkx', 'pyg_utils.to_networkx', (['graph'], {'to_undirected': '(True)'}), '(graph, to_undirected=True)\n', (1938, 1965), True, 'import torch_geometric.utils as pyg_utils\n'), ((1970, 2012), 'networkx.set_node_attributes', 'nx.set_node_attributes', (['g', 'labels', '"""label"""'], {}), "(g, labels, 'label')\n", (1992, 2012), True, 'import networkx as nx\n'), ((2035, 2046), 'time.time', 'time.time', ([], {}), '()\n', (2044, 2046), False, 'import time\n'), ((2521, 2574), 'networkx.write_gexf', 'nx.write_gexf', (['G', 'f"""{target_dir_net}/{filename}.gexf"""'], {}), "(G, f'{target_dir_net}/{filename}.gexf')\n", (2534, 2574), True, 'import networkx as nx\n'), ((2761, 2823), 'networkx.write_gexf', 'nx.write_gexf', (['giant', 'f"""{target_dir_net}/{filename}_lcsg.gexf"""'], {}), "(giant, f'{target_dir_net}/{filename}_lcsg.gexf')\n", (2774, 2823), True, 'import networkx as nx\n'), ((2837, 2864), 'networkx.relabel_nodes', 'nx.relabel_nodes', (['G', 'labels'], {}), '(G, labels)\n', (2853, 2864), True, 'import networkx as nx\n'), ((2987, 3050), 'networkx.write_gexf', 'nx.write_gexf', (['words', 'f"""{target_dir_net}/{filename}_words.gexf"""'], {}), "(words, f'{target_dir_net}/{filename}_words.gexf')\n", (3000, 3050), True, 'import networkx as nx\n'), ((3275, 3349), 'networkx.write_gexf', 'nx.write_gexf', (['giant_words', 'f"""{target_dir_net}/{filename}_words_lcsg.gexf"""'], {}), "(giant_words, f'{target_dir_net}/{filename}_words_lcsg.gexf')\n", (3288, 3349), True, 'import networkx as nx\n'), ((4154, 4176), 'os.listdir', 'os.listdir', (['source_dir'], {}), '(source_dir)\n', (4164, 4176), False, 'import os\n'), ((1320, 1353), 'numpy.array', 'np.array', (['[d.vector for d in doc]'], {}), '([d.vector for d in doc])\n', (1328, 1353), True, 'import numpy as np\n'), ((1607, 1624), 'torch.tensor', 'torch.tensor', (['[y]'], {}), '([y])\n', (1619, 1624), False, 'import torch\n'), ((2603, 2629), 'networkx.connected_components', 'nx.connected_components', (['G'], {}), '(G)\n', (2626, 2629), True, 'import networkx as nx\n'), ((3089, 3119), 'networkx.connected_components', 'nx.connected_components', (['words'], {}), '(words)\n', (3112, 3119), True, 'import networkx as nx\n'), ((1399, 1441), 'torch.tensor', 'torch.tensor', (['edge_index'], {'dtype': 'torch.long'}), '(edge_index, dtype=torch.long)\n', (1411, 1441), False, 'import torch\n')] |
# -*- coding: utf-8 -*-
import PyMca5
from PyMca5.PyMcaPhysics.xrf import McaAdvancedFitBatch
from PyMca5.PyMcaPhysics.xrf import FastXRFLinearFit
from PyMca5.PyMcaPhysics.xrf import ClassMcaTheory
from PyMca5.PyMca import EDFStack
from PyMca5.PyMcaIO import ConfigDict
try:
from PyMca5.PyMcaPhysics.xrf.McaAdvancedFitBatch import (
OutputBuffer as OutputBufferBase,
)
except ImportError:
OutputBuffer = None
else:
class OutputBuffer(OutputBufferBase):
@property
def outputDirLegacy(self):
return self.outputDir
import numpy as np
import re
import os
import glob
import collections
import matplotlib.pyplot as plt
import logging
from ..utils import instance
from ..io import edf
from ..io import localfs
from ..io import utils as ioutils
logger = logging.getLogger(__name__)
def AdaptPyMcaConfigFile(filename, *args, **kwargs):
cfg = ConfigDict.ConfigDict(filelist=cfg)
AdaptPyMcaConfig(cfg, *args, **kwargs)
cfg.write(filename)
def AdaptPyMcaConfig_energy(cfg, energy, addhigh):
if energy is None or not np.isfinite(energy):
return
# Extract source lines
ind = instance.asarray(cfg["fit"]["energyflag"]).astype(bool)
norg = len(ind)
nenergies = ind.sum() + bool(addhigh)
def extract(name, default=np.nan):
arr = cfg["fit"][name]
if instance.isarray(arr):
arr = [instance.asnumber(v) for v in arr]
arr = instance.asarray(arr)
# Select based on energyflag
narr = len(arr)
if narr < norg:
arr = np.append(arr, [default] * (norg - narr))
arr = arr[0:norg][ind]
# At least nenergies
narr = len(arr)
if narr < nenergies:
arr = np.append(arr, [default] * (nenergies - narr))
return arr
cfg_energy = extract("energy", default=np.nan)
cfg_energyweight = extract("energyweight", default=np.nan)
cfg_energyflag = extract("energyflag", default=1)
cfg_energyscatter = extract("energyscatter", default=0)
# Modify energy
cfg_energy = cfg_energy / cfg_energy[0] * energy
cfg_energyweight = cfg_energyweight / cfg_energyweight[0]
# Add missing lines
for i in range(nenergies):
if not np.isfinite(cfg_energy[i]):
if i == 0:
cfg_energy[i] = energy
else:
cfg_energy[i] = addhigh * energy
if not np.isfinite(cfg_energyweight[i]):
if i == 0:
cfg_energyweight[i] = 1
else:
cfg_energyweight[i] = 1e-10
# Remove extract line when it was already there
if addhigh:
if (
cfg_energyweight[-2] / cfg_energyweight[0] < 1e-5
and cfg_energy[-2] > energy
):
nenergies -= 1
cfg_energy = cfg_energy[:-1]
cfg_energyweight = cfg_energyweight[:-1]
cfg_energyflag = cfg_energyflag[:-1]
cfg_energyscatter = cfg_energyscatter[:-1]
# List with original size
def reset(arr, default=0):
arr = arr.tolist()
if len(arr) < norg:
arr += [default] * (norg - len(arr))
return arr
cfg["fit"]["energy"] = reset(cfg_energy, default=None)
cfg["fit"]["energyweight"] = reset(cfg_energyweight)
cfg["fit"]["energyflag"] = reset(cfg_energyflag)
cfg["fit"]["energyscatter"] = reset(cfg_energyscatter)
# Dummy matrix (apparently needed for multi-energy)
if cfg["attenuators"]["Matrix"][0] == 0 and nenergies > 1:
cfg["materials"]["Dummy"] = {
"Comment": "Dummy",
"CompoundFraction": [1],
"CompoundList": ["H1"],
"Density": 1.0,
"Thickness": 0.0,
}
cfg["attenuators"]["Matrix"][0] = 1
cfg["attenuators"]["Matrix"][1] = "Dummy"
cfg["attenuators"]["Matrix"][2] = 1.0
cfg["attenuators"]["Matrix"][3] = 0.0 # thickness in cm
def AdaptPyMcaConfig_mlines(cfg, mlines):
# Split M-lines
# /usr/local/lib/python2.7/dist-packages/PyMca5/PyMcaPhysics/xrf/Elements.py
# /users/opid21/.local/lib/python2.7/site-packages/PyMca5/PyMcaPhysics/xrf/Elements.py
#
# You need an adapted pymca version: Elements
# ElementShellTransitions = [KShell.ElementKShellTransitions,
# KShell.ElementKAlphaTransitions,
# KShell.ElementKBetaTransitions,
# LShell.ElementLShellTransitions,
# LShell.ElementL1ShellTransitions,
# LShell.ElementL2ShellTransitions,
# LShell.ElementL3ShellTransitions,
# [s+"*" for s in MShell.ElementMShellTransitions],
# MShell.ElementM1ShellTransitions,
# MShell.ElementM2ShellTransitions,
# MShell.ElementM3ShellTransitions,
# MShell.ElementM4ShellTransitions,
# MShell.ElementM5ShellTransitions]
# ElementShellRates = [KShell.ElementKShellRates,
# KShell.ElementKAlphaRates,
# KShell.ElementKBetaRates,
# LShell.ElementLShellRates,
# LShell.ElementL1ShellRates,
# LShell.ElementL2ShellRates,
# LShell.ElementL3ShellRates,
# MShell.ElementMShellRates,
# MShell.ElementM1ShellRates,
# MShell.ElementM2ShellRates,
# MShell.ElementM3ShellRates,
# MShell.ElementM4ShellRates,
# MShell.ElementM5ShellRates]
# ElementXrays = ['K xrays', 'Ka xrays', 'Kb xrays', 'L xrays','L1 xrays','L2 xrays','L3 xrays','M xrays','M1 xrays','M2 xrays','M3 xrays','M4 xrays','M5 xrays']
if "M5 xrays" not in ClassMcaTheory.Elements.ElementXrays:
msg = "XRF fit: PyMca5.PyMcaPhysics.xrf.Elements is not patched to supported M-line group splitting."
logger.error(msg)
raise ImportError(msg)
for el in mlines:
if el in cfg["peaks"]:
if "M" in cfg["peaks"][el]:
cfg["peaks"][el] = [
group for group in cfg["peaks"][el] if group != "M"
] + mlines[el]
def AdaptPyMcaConfig_quant(cfg, quant):
if "flux" in quant:
cfg["concentrations"]["flux"] = quant["flux"]
if "time" in quant:
cfg["concentrations"]["time"] = quant["time"]
if "area" in quant:
cfg["concentrations"]["area"] = quant["area"]
if "distance" in quant:
cfg["concentrations"]["distance"] = quant["distance"]
if "anglein" in quant:
cfg["attenuators"]["Matrix"][4] = quant["anglein"]
if "angleout" in quant:
cfg["attenuators"]["Matrix"][5] = quant["angleout"]
if "anglein" in quant or "angleout" in quant:
cfg["attenuators"]["Matrix"][7] = (
cfg["attenuators"]["Matrix"][4] + cfg["attenuators"]["Matrix"][5]
)
def AdaptPyMcaConfig_fast(cfg):
if cfg["fit"]["linearfitflag"] == 0:
cfg["fit"]["linearfitflag"] = 1
if "strategyflag" not in cfg["fit"]:
cfg["fit"]["strategyflag"] = 0
elif cfg["fit"]["strategyflag"]:
cfg["fit"]["strategyflag"] = 0
cfg["fit"]["fitweight"] = 0
def AdaptPyMcaConfig_forcebatch(cfg):
# Force no weights (for spectra with low counts):
cfg["fit"]["fitweight"] = 0
def AdaptPyMcaConfig_modinfo(cfg, quant):
ind = instance.asarray(cfg["fit"]["energyflag"]).astype(bool)
_energy = instance.asarray(cfg["fit"]["energy"])[ind]
_weights = instance.asarray(cfg["fit"]["energyweight"])[ind]
_weights = _weights / _weights.sum() * 100
_scatter = instance.asarray(cfg["fit"]["energyscatter"])[ind]
info = "\n ".join(
[
"{} keV (Rate = {:.2f}%, Scatter {})".format(en, w, "ON" if scat else "OFF")
for en, w, scat in zip(_energy, _weights, _scatter)
]
)
if quant:
info += "\n flux = {:e} s^(-1)\n time = {} s\n active area = {} cm^2\n sample-detector distance = {} cm\n angle IN = {} deg\n angle OUT = {} deg".format(
cfg["concentrations"]["flux"],
cfg["concentrations"]["time"],
cfg["concentrations"]["area"],
cfg["concentrations"]["distance"],
cfg["attenuators"]["Matrix"][4],
cfg["attenuators"]["Matrix"][5],
)
if cfg["attenuators"]["Matrix"][0] == 0:
info += "\n Matrix = None"
else:
info += "\n Matrix = {}".format(cfg["attenuators"]["Matrix"][1])
info += "\n Linear = {}".format("YES" if cfg["fit"]["linearfitflag"] else "NO")
info += "\n Error propagation = {}".format(
"Poisson" if cfg["fit"]["fitweight"] else "OFF"
)
info += "\n Matrix adjustment = {}".format(
"ON" if cfg["fit"]["strategyflag"] else "OFF"
)
logger.info("XRF fit configuration adapted:\n {}".format(info))
def AdaptPyMcaConfig(cfg, energy, addhigh=0, mlines=None, quant=None, fast=False):
"""
Args:
cfg(ConfigDict): pymca configuration
energy(float): primary beam energy in keV
addhigh(Optional(num)): add high primary energy with very low weight
mlines(Optional(dict)): elements (keys) which M line group must be replaced by some M subgroups (values)
quant(Optional(dict)):
"""
AdaptPyMcaConfig_energy(cfg, energy, addhigh)
if mlines:
AdaptPyMcaConfig_mlines(cfg, mlines)
if quant and isinstance(quant, dict):
AdaptPyMcaConfig_quant(cfg, quant)
if fast:
AdaptPyMcaConfig_fast(cfg)
AdaptPyMcaConfig_forcebatch(cfg)
AdaptPyMcaConfig_modinfo(cfg, quant)
def PerformRoi(filelist, rois, norm=None):
"""ROI XRF spectra in batch with changing primary beam energy.
Args:
filelist(list(str)|np.array): spectra to fit
rois(dict(2-tuple)): ROIs
norm(Optional(np.array)): normalization array
Returns:
dict: {label:nenergies x nfiles,...}
"""
# Load data
# Each spectrum (each row) in 1 edf file is acquired at a different energy
if isinstance(filelist, list):
dataStack = EDFStack.EDFStack(filelist, dtype=np.float32).data
else:
dataStack = filelist
nfiles, nenergies, nchannels = dataStack.shape
# Normalization
if norm is None:
norm = [1] * nenergies
else:
if hasattr(norm, "__iter__"):
if len(norm) == 1:
norm = [norm[0]] * nenergies
elif len(norm) != nenergies:
raise ValueError(
"Expected {} normalization values ({} given)".format(
nenergies, len(norm)
)
)
else:
norm = [norm] * nenergies
# ROI
ret = {}
for k in rois:
ret[k] = np.zeros((nenergies, nfiles), dtype=type(dataStack))
for i in range(nfiles):
for k, roi in rois.items():
ret[k][:, i] = np.sum(dataStack[i, :, roi[0] : roi[1]], axis=1) / norm
return ret
def PerformFit(
filelist,
cfgfile,
energies,
mlines={},
norm=None,
fast=False,
addhigh=0,
prog=None,
plot=False,
):
"""Fit XRF spectra in batch with changing primary beam energy.
Args:
filelist(list(str)|np.array): spectra to fit
cfgfile(str): configuration file to use
energies(np.array): primary beam energies
mlines(Optional(dict)): elements (keys) which M line group must be replaced by some M subgroups (values)
norm(Optional(np.array)): normalization array
fast(Optional(bool)): fast fitting (linear)
addhigh(Optional(number)): add higher energy
prog(Optional(timing.ProgessLogger)): progress object
plot(Optional(bool))
Returns:
dict: {label:nenergies x nfiles,...}
"""
# Load data
# Each spectrum (each row) in 1 edf file is acquired at a different energy
if isinstance(filelist, list):
dataStack = EDFStack.EDFStack(filelist, dtype=np.float32).data
else:
dataStack = filelist
nfiles, nenergies, nchannels = dataStack.shape
# MCA channels
xmin = 0
xmax = nchannels - 1
x = np.arange(nchannels, dtype=np.float32)
# Energies
if hasattr(energies, "__iter__"):
if len(energies) == 1:
energies = [energies[0]] * nenergies
elif len(energies) != nenergies:
raise ValueError(
"Expected {} energies ({} given)".format(nenergies, len(energies))
)
else:
energies = [energies] * nenergies
# Normalization
if norm is None:
norm = [1] * nenergies
else:
if hasattr(norm, "__iter__"):
if len(norm) == 1:
norm = [norm[0]] * nenergies
elif len(norm) != nenergies:
raise ValueError(
"Expected {} normalization values ({} given)".format(
nenergies, len(norm)
)
)
else:
norm = [norm] * nenergies
# Prepare plot
if plot:
fig, ax = plt.subplots()
# Prepare fit
# ClassMcaTheory.DEBUG = 1
mcafit = ClassMcaTheory.McaTheory()
try:
mcafit.useFisxEscape(True)
except:
pass
if fast:
mcafit.enableOptimizedLinearFit()
else:
mcafit.disableOptimizedLinearFit()
cfg = mcafit.configure(ReadPyMcaConfigFile(cfgfile))
# Fit at each energy
if prog is not None:
prog.setnfine(nenergies * nfiles)
ret = {}
for j in range(nenergies):
# Prepare fit with this energy
AdaptPyMcaConfig(cfg, energies[j], mlines=mlines, fast=fast, addhigh=addhigh)
mcafit.configure(cfg)
# Fit all spectra with this energy
for i in range(nfiles):
# Data to fit
y = dataStack[i, j, :].flatten()
mcafit.setData(x, y, xmin=xmin, xmax=xmax)
# Initial parameter estimates
mcafit.estimate()
# Fit
fitresult = mcafit.startfit(digest=0)
# Extract result
if plot:
mcafitresult = mcafit.digestresult()
ax.cla()
if (
plot == 2
or not any(np.isfinite(np.log(mcafitresult["ydata"])))
or not any(mcafitresult["ydata"] > 0)
):
ax.plot(mcafitresult["energy"], mcafitresult["ydata"])
ax.plot(mcafitresult["energy"], mcafitresult["yfit"], color="red")
else:
ax.semilogy(mcafitresult["energy"], mcafitresult["ydata"])
ax.semilogy(
mcafitresult["energy"], mcafitresult["yfit"], color="red"
)
ax.set_ylim(
ymin=np.nanmin(
mcafitresult["ydata"][np.nonzero(mcafitresult["ydata"])]
)
)
ax.set_title("Primary energy: {} keV".format(energies[j]))
ax.set_xlabel("Energy (keV)")
ax.set_ylabel("Intensity (cts)")
plt.pause(0.0001)
else:
mcafitresult = mcafit.imagingDigestResult()
# Store result
for k in mcafitresult["groups"]:
if k not in ret:
ret[k] = np.zeros(
(nenergies, nfiles), dtype=type(mcafitresult[k]["fitarea"])
)
ret[k][j, i] = mcafitresult[k]["fitarea"] / norm[j]
if "chisq" not in ret:
ret["chisq"] = np.zeros((nenergies, nfiles), dtype=type(mcafit.chisq))
ret["chisq"][j, i] = mcafit.chisq
# Print progress
if prog is not None:
prog.ndonefine(nfiles)
prog.printprogress()
return ret
def PerformBatchFit(*args, **kwargs):
if OutputBuffer is None:
return PerformBatchFitOld(*args, **kwargs)
else:
return PerformBatchFitNew(*args, **kwargs)
def PerformBatchFitHDF5(
filelist,
cfg,
outuri,
energy=None,
mlines=None,
quant=None,
fast=False,
addhigh=0,
**kw
):
"""Fit XRF spectra in batch with one primary beam energy.
Least-square fitting. If you intend a linear fit, modify the configuration:
- Get current energy calibration with "Load From Fit"
- Enable: Perform a Linear Fit
- Disable: Stripping
- Strip iterations = 0
Fast linear least squares:
- Use SNIP instead of STRIP
Args:
filelist(list(str)): spectra to fit
cfg(str or ConfigDict): configuration file to use
outuri(h5fs.Path): directory for results
energy(num): primary beam energy
mlines(Optional(dict)): elements (keys) which M line group must be replaced by some M subgroups (values)
fast(Optional(bool)): fast fitting (linear)
quant(Optional(dict)):
addhigh(Optional(int)):
"""
if instance.isstring(cfg):
cfg = ConfigDict.ConfigDict(filelist=cfg)
AdaptPyMcaConfig(
cfg, energy, mlines=mlines, quant=quant, fast=fast, addhigh=addhigh
)
# outputDir/outputRoot.h5::/fileEntry/fileProcess
kw["h5"] = True
kw["edf"] = False
kw["outputDir"] = outuri.device.parent.path
kw["outputRoot"] = os.path.splitext(outuri.device.name)[0]
kw["fileEntry"] = outuri.parent.path
kw["fileProcess"] = outuri.name
outbuffer = OutputBuffer(**kw)
if fast:
batch = FastXRFLinearFit.FastXRFLinearFit()
stack = FastXRFLinearFit.prepareDataStack(filelist)
kwargs = {
"y": stack,
"configuration": cfg,
"concentrations": bool(quant),
"refit": 1,
"outbuffer": outbuffer,
}
else:
kwargs = {
"filelist": filelist,
"concentrations": bool(quant),
"fitfiles": 0,
"fitconcfile": 0,
"outbuffer": outbuffer,
}
batch = McaAdvancedFitBatch.McaAdvancedFitBatch(cfg, **kwargs)
with outbuffer.saveContext():
if fast:
batch.fitMultipleSpectra(**kwargs)
else:
batch.processList()
def PerformBatchFitNew(
filelist,
outdir,
outname,
cfg,
energy,
mlines=None,
quant=None,
fast=False,
addhigh=0,
):
"""Fit XRF spectra in batch with one primary beam energy.
Least-square fitting. If you intend a linear fit, modify the configuration:
- Get current energy calibration with "Load From Fit"
- Enable: Perform a Linear Fit
- Disable: Stripping
- Strip iterations = 0
Fast linear least squares:
- Use SNIP instead of STRIP
Args:
filelist(list(str)): spectra to fit
outdir(str): directory for results
outname(str): output radix
cfg(str or ConfigDict): configuration file to use
energy(num): primary beam energy
mlines(Optional(dict)): elements (keys) which M line group must be replaced by some M subgroups (values)
fast(Optional(bool)): fast fitting (linear)
quant(Optional(dict)):
addhigh(Optional(int))
Returns:
files(list(str)): files produced by pymca
labels(list(str)): corresponding HDF5 labels
"""
# Adapt cfg in memory
if instance.isstring(cfg):
cfg = ConfigDict.ConfigDict(filelist=cfg)
AdaptPyMcaConfig(
cfg, energy, mlines=mlines, quant=quant, fast=fast, addhigh=addhigh
)
buncertainties = False
bconcentrations = bool(quant)
# Save cfg in temporary file
outdir = localfs.Path(outdir).mkdir()
with outdir.temp(name=outname + ".cfg", force=True) as cfgfile:
cfg.write(cfgfile.path)
kwargs = {
"outputDir": outdir.path,
"fileEntry": outname,
"h5": False,
"edf": True,
"multipage": False,
"saveFOM": True,
}
outbuffer = OutputBuffer(**kwargs)
if fast:
batch = FastXRFLinearFit.FastXRFLinearFit()
stack = FastXRFLinearFit.prepareDataStack(filelist)
kwargs = {
"y": stack,
"configuration": cfg,
"concentrations": bconcentrations,
"refit": 1,
"weight": None, # None -> from cfg file
"outbuffer": outbuffer,
}
else:
kwargs = {
"filelist": filelist,
"concentrations": bconcentrations,
"fitfiles": 0,
"fitconcfile": 0,
"outbuffer": outbuffer,
}
batch = McaAdvancedFitBatch.McaAdvancedFitBatch(cfgfile.path, **kwargs)
with outbuffer.saveContext():
if fast:
batch.fitMultipleSpectra(**kwargs)
else:
batch.processList()
# List of files and labels
files, labels = [], []
groups = ["parameters", "massfractions"]
if buncertainties:
groups.append("uncertainties")
for group in groups:
for label in outbuffer.labels(group, labeltype="filename"):
filename = outbuffer.filename(".edf", suffix="_" + label)
labels.append(label)
files.append(filename)
if "chisq" in outbuffer:
labels.append("calc_chisq")
files.append(outbuffer.filename(".edf", suffix="_chisq"))
return files, labels
def PerformBatchFitOld(
filelist,
outdir,
outname,
cfg,
energy,
mlines=None,
quant=None,
fast=False,
addhigh=0,
):
"""Fit XRF spectra in batch with one primary beam energy.
Least-square fitting. If you intend a linear fit, modify the configuration:
- Get current energy calibration with "Load From Fit"
- Enable: Perform a Linear Fit
- Disable: Stripping
- Strip iterations = 0
Fast linear least squares:
- Use SNIP instead of STRIP
Args:
filelist(list(str)): spectra to fit
outdir(str): directory for results
outname(str): output radix
cfg(str or ConfigDict): configuration file to use
energy(num): primary beam energy
mlines(Optional(dict)): elements (keys) which M line group must be replaced by some M subgroups (values)
fast(Optional(bool)): fast fitting (linear)
quant(Optional(dict)):
addhigh(Optional(int))
Returns:
files(list(str)): files produced by pymca
labels(list(str)): corresponding HDF5 labels
"""
outdir = localfs.Path(outdir).mkdir()
if instance.isstring(cfg):
cfg = ConfigDict.ConfigDict(filelist=cfg)
with outdir.temp(name=outname + ".cfg", force=True) as cfgfile:
AdaptPyMcaConfig(
cfg, energy, mlines=mlines, quant=quant, fast=fast, addhigh=addhigh
)
cfg.write(cfgfile.path)
buncertainties = False
bconcentrations = bool(quant)
if fast:
# Prepare fit
fastFit = FastXRFLinearFit.FastXRFLinearFit()
fastFit.setFitConfiguration(cfg)
dataStack = EDFStack.EDFStack(filelist, dtype=np.float32)
# Fit
result = fastFit.fitMultipleSpectra(
y=dataStack, refit=1, concentrations=bconcentrations
)
# Save result and keep filenames + labels
names = result["names"]
if bconcentrations:
names = names[: -len(result["concentrations"])]
parse = re.compile("^(?P<Z>.+)[_ -](?P<line>.+)$")
def filename(x):
return outdir["{}_{}.edf".format(outname, x)].path
labels = []
files = []
j = 0
for i, name in enumerate(names):
m = parse.match(name)
if not m:
continue
m = m.groupdict()
Z, line = m["Z"], m["line"]
# Peak area
label = "{}_{}".format(Z, line)
f = filename(label)
edf.saveedf(
f, result["parameters"][i], {"Title": label}, overwrite=True
)
labels.append(label)
files.append(f)
# Error on peak area
if buncertainties:
label = "s{}_{}".format(Z, line)
f = filename(label)
edf.saveedf(
f, result["uncertainties"][i], {"Title": label}, overwrite=True
)
labels.append(label)
files.append(f)
# Mass fraction
if bconcentrations and Z.lower() != "scatter":
label = "w{}_{}".format(Z, line)
f = filename(label)
edf.saveedf(
f, result["concentrations"][j], {"Title": label}, overwrite=True
)
labels.append(label)
files.append(f)
j += 1
else:
b = McaAdvancedFitBatch.McaAdvancedFitBatch(
cfgfile.path,
filelist=filelist,
outputdir=outdir.path,
fitfiles=0,
concentrations=bconcentrations,
)
b.processList()
filemask = os.path.join(outdir.path, "IMAGES", "*.dat")
def basename(x):
return os.path.splitext(os.path.basename(x))[0]
nbase = len(basename(glob.glob(filemask)[0])) + 1
filemask = os.path.join(outdir.path, "IMAGES", "*.edf")
labels = []
files = []
for name in sorted(glob.glob(filemask)):
label = basename(name)[nbase:]
if label.endswith("mass_fraction"):
label = "w" + label[:-14]
if label == "chisq":
label = "calc_chisq"
labels.append(label)
files.append(name)
return files, labels
| [
"numpy.sum",
"numpy.arange",
"glob.glob",
"os.path.join",
"PyMca5.PyMcaPhysics.xrf.McaAdvancedFitBatch.McaAdvancedFitBatch",
"PyMca5.PyMcaPhysics.xrf.ClassMcaTheory.McaTheory",
"PyMca5.PyMca.EDFStack.EDFStack",
"numpy.isfinite",
"numpy.append",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.subpl... | [((806, 833), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (823, 833), False, 'import logging\n'), ((899, 934), 'PyMca5.PyMcaIO.ConfigDict.ConfigDict', 'ConfigDict.ConfigDict', ([], {'filelist': 'cfg'}), '(filelist=cfg)\n', (920, 934), False, 'from PyMca5.PyMcaIO import ConfigDict\n'), ((12338, 12376), 'numpy.arange', 'np.arange', (['nchannels'], {'dtype': 'np.float32'}), '(nchannels, dtype=np.float32)\n', (12347, 12376), True, 'import numpy as np\n'), ((13343, 13369), 'PyMca5.PyMcaPhysics.xrf.ClassMcaTheory.McaTheory', 'ClassMcaTheory.McaTheory', ([], {}), '()\n', (13367, 13369), False, 'from PyMca5.PyMcaPhysics.xrf import ClassMcaTheory\n'), ((13265, 13279), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (13277, 13279), True, 'import matplotlib.pyplot as plt\n'), ((17298, 17333), 'PyMca5.PyMcaIO.ConfigDict.ConfigDict', 'ConfigDict.ConfigDict', ([], {'filelist': 'cfg'}), '(filelist=cfg)\n', (17319, 17333), False, 'from PyMca5.PyMcaIO import ConfigDict\n'), ((17606, 17642), 'os.path.splitext', 'os.path.splitext', (['outuri.device.name'], {}), '(outuri.device.name)\n', (17622, 17642), False, 'import os\n'), ((17787, 17822), 'PyMca5.PyMcaPhysics.xrf.FastXRFLinearFit.FastXRFLinearFit', 'FastXRFLinearFit.FastXRFLinearFit', ([], {}), '()\n', (17820, 17822), False, 'from PyMca5.PyMcaPhysics.xrf import FastXRFLinearFit\n'), ((17839, 17882), 'PyMca5.PyMcaPhysics.xrf.FastXRFLinearFit.prepareDataStack', 'FastXRFLinearFit.prepareDataStack', (['filelist'], {}), '(filelist)\n', (17872, 17882), False, 'from PyMca5.PyMcaPhysics.xrf import FastXRFLinearFit\n'), ((18298, 18352), 'PyMca5.PyMcaPhysics.xrf.McaAdvancedFitBatch.McaAdvancedFitBatch', 'McaAdvancedFitBatch.McaAdvancedFitBatch', (['cfg'], {}), '(cfg, **kwargs)\n', (18337, 18352), False, 'from PyMca5.PyMcaPhysics.xrf import McaAdvancedFitBatch\n'), ((19694, 19729), 'PyMca5.PyMcaIO.ConfigDict.ConfigDict', 'ConfigDict.ConfigDict', ([], {'filelist': 'cfg'}), '(filelist=cfg)\n', (19715, 19729), False, 'from PyMca5.PyMcaIO import ConfigDict\n'), ((23001, 23036), 'PyMca5.PyMcaIO.ConfigDict.ConfigDict', 'ConfigDict.ConfigDict', ([], {'filelist': 'cfg'}), '(filelist=cfg)\n', (23022, 23036), False, 'from PyMca5.PyMcaIO import ConfigDict\n'), ((1084, 1103), 'numpy.isfinite', 'np.isfinite', (['energy'], {}), '(energy)\n', (1095, 1103), True, 'import numpy as np\n'), ((1575, 1616), 'numpy.append', 'np.append', (['arr', '([default] * (norg - narr))'], {}), '(arr, [default] * (norg - narr))\n', (1584, 1616), True, 'import numpy as np\n'), ((1749, 1795), 'numpy.append', 'np.append', (['arr', '([default] * (nenergies - narr))'], {}), '(arr, [default] * (nenergies - narr))\n', (1758, 1795), True, 'import numpy as np\n'), ((2251, 2277), 'numpy.isfinite', 'np.isfinite', (['cfg_energy[i]'], {}), '(cfg_energy[i])\n', (2262, 2277), True, 'import numpy as np\n'), ((2423, 2455), 'numpy.isfinite', 'np.isfinite', (['cfg_energyweight[i]'], {}), '(cfg_energyweight[i])\n', (2434, 2455), True, 'import numpy as np\n'), ((10266, 10311), 'PyMca5.PyMca.EDFStack.EDFStack', 'EDFStack.EDFStack', (['filelist'], {'dtype': 'np.float32'}), '(filelist, dtype=np.float32)\n', (10283, 10311), False, 'from PyMca5.PyMca import EDFStack\n'), ((12130, 12175), 'PyMca5.PyMca.EDFStack.EDFStack', 'EDFStack.EDFStack', (['filelist'], {'dtype': 'np.float32'}), '(filelist, dtype=np.float32)\n', (12147, 12175), False, 'from PyMca5.PyMca import EDFStack\n'), ((20363, 20398), 'PyMca5.PyMcaPhysics.xrf.FastXRFLinearFit.FastXRFLinearFit', 'FastXRFLinearFit.FastXRFLinearFit', ([], {}), '()\n', (20396, 20398), False, 'from PyMca5.PyMcaPhysics.xrf import FastXRFLinearFit\n'), ((20419, 20462), 'PyMca5.PyMcaPhysics.xrf.FastXRFLinearFit.prepareDataStack', 'FastXRFLinearFit.prepareDataStack', (['filelist'], {}), '(filelist)\n', (20452, 20462), False, 'from PyMca5.PyMcaPhysics.xrf import FastXRFLinearFit\n'), ((21007, 21070), 'PyMca5.PyMcaPhysics.xrf.McaAdvancedFitBatch.McaAdvancedFitBatch', 'McaAdvancedFitBatch.McaAdvancedFitBatch', (['cfgfile.path'], {}), '(cfgfile.path, **kwargs)\n', (21046, 21070), False, 'from PyMca5.PyMcaPhysics.xrf import McaAdvancedFitBatch\n'), ((23389, 23424), 'PyMca5.PyMcaPhysics.xrf.FastXRFLinearFit.FastXRFLinearFit', 'FastXRFLinearFit.FastXRFLinearFit', ([], {}), '()\n', (23422, 23424), False, 'from PyMca5.PyMcaPhysics.xrf import FastXRFLinearFit\n'), ((23494, 23539), 'PyMca5.PyMca.EDFStack.EDFStack', 'EDFStack.EDFStack', (['filelist'], {'dtype': 'np.float32'}), '(filelist, dtype=np.float32)\n', (23511, 23539), False, 'from PyMca5.PyMca import EDFStack\n'), ((23898, 23940), 're.compile', 're.compile', (['"""^(?P<Z>.+)[_ -](?P<line>.+)$"""'], {}), "('^(?P<Z>.+)[_ -](?P<line>.+)$')\n", (23908, 23940), False, 'import re\n'), ((25483, 25626), 'PyMca5.PyMcaPhysics.xrf.McaAdvancedFitBatch.McaAdvancedFitBatch', 'McaAdvancedFitBatch.McaAdvancedFitBatch', (['cfgfile.path'], {'filelist': 'filelist', 'outputdir': 'outdir.path', 'fitfiles': '(0)', 'concentrations': 'bconcentrations'}), '(cfgfile.path, filelist=filelist,\n outputdir=outdir.path, fitfiles=0, concentrations=bconcentrations)\n', (25522, 25626), False, 'from PyMca5.PyMcaPhysics.xrf import McaAdvancedFitBatch\n'), ((25769, 25813), 'os.path.join', 'os.path.join', (['outdir.path', '"""IMAGES"""', '"""*.dat"""'], {}), "(outdir.path, 'IMAGES', '*.dat')\n", (25781, 25813), False, 'import os\n'), ((25994, 26038), 'os.path.join', 'os.path.join', (['outdir.path', '"""IMAGES"""', '"""*.edf"""'], {}), "(outdir.path, 'IMAGES', '*.edf')\n", (26006, 26038), False, 'import os\n'), ((11095, 11141), 'numpy.sum', 'np.sum', (['dataStack[i, :, roi[0]:roi[1]]'], {'axis': '(1)'}), '(dataStack[i, :, roi[0]:roi[1]], axis=1)\n', (11101, 11141), True, 'import numpy as np\n'), ((15366, 15383), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.0001)'], {}), '(0.0001)\n', (15375, 15383), True, 'import matplotlib.pyplot as plt\n'), ((26117, 26136), 'glob.glob', 'glob.glob', (['filemask'], {}), '(filemask)\n', (26126, 26136), False, 'import glob\n'), ((25884, 25903), 'os.path.basename', 'os.path.basename', (['x'], {}), '(x)\n', (25900, 25903), False, 'import os\n'), ((25942, 25961), 'glob.glob', 'glob.glob', (['filemask'], {}), '(filemask)\n', (25951, 25961), False, 'import glob\n'), ((14465, 14494), 'numpy.log', 'np.log', (["mcafitresult['ydata']"], {}), "(mcafitresult['ydata'])\n", (14471, 14494), True, 'import numpy as np\n'), ((15097, 15130), 'numpy.nonzero', 'np.nonzero', (["mcafitresult['ydata']"], {}), "(mcafitresult['ydata'])\n", (15107, 15130), True, 'import numpy as np\n')] |
from __future__ import absolute_import
from __future__ import print_function
import theano
import theano.tensor as T
import numpy as np
import warnings
import time
from collections import deque
from .utils.generic_utils import Progbar
class CallbackList(object):
def __init__(self, callbacks, queue_length=10):
self.callbacks = callbacks
self.queue_length = queue_length
def append(self, callback):
self.callbacks.append(callback)
def _set_params(self, params):
for callback in self.callbacks:
callback._set_params(params)
def _set_model(self, model):
for callback in self.callbacks:
callback._set_model(model)
def on_epoch_begin(self, epoch, logs={}):
for callback in self.callbacks:
callback.on_epoch_begin(epoch, logs)
self._delta_t_batch = 0.
self._delta_ts_batch_begin = deque([], maxlen=self.queue_length)
self._delta_ts_batch_end = deque([], maxlen=self.queue_length)
def on_epoch_end(self, epoch, logs={}):
for callback in self.callbacks:
callback.on_epoch_end(epoch, logs)
def on_batch_begin(self, batch, logs={}):
t_before_callbacks = time.time()
for callback in self.callbacks:
callback.on_batch_begin(batch, logs)
self._delta_ts_batch_begin.append(time.time() - t_before_callbacks)
delta_t_median = np.median(self._delta_ts_batch_begin)
if self._delta_t_batch > 0. and delta_t_median > 0.95 * self._delta_t_batch \
and delta_t_median > 0.1:
warnings.warn('Method on_batch_begin() is slow compared '
'to the batch update (%f). Check your callbacks.' % delta_t_median)
self._t_enter_batch = time.time()
def on_batch_end(self, batch, logs={}):
self._delta_t_batch = time.time() - self._t_enter_batch
t_before_callbacks = time.time()
for callback in self.callbacks:
callback.on_batch_end(batch, logs)
self._delta_ts_batch_end.append(time.time() - t_before_callbacks)
delta_t_median = np.median(self._delta_ts_batch_end)
if self._delta_t_batch > 0. and delta_t_median > 0.95 * self._delta_t_batch \
and delta_t_median > 0.1:
warnings.warn('Method on_batch_end() is slow compared '
'to the batch update (%f). Check your callbacks.' % delta_t_median)
def on_train_begin(self, logs={}):
for callback in self.callbacks:
callback.on_train_begin(logs)
def on_train_end(self, logs={}):
for callback in self.callbacks:
callback.on_train_end(logs)
class Callback(object):
def __init__(self):
pass
def _set_params(self, params):
self.params = params
def _set_model(self, model):
self.model = model
def on_epoch_begin(self, epoch, logs={}):
pass
def on_epoch_end(self, epoch, logs={}):
pass
def on_batch_begin(self, batch, logs={}):
pass
def on_batch_end(self, batch, logs={}):
pass
def on_train_begin(self, logs={}):
pass
def on_train_end(self, logs={}):
pass
class BaseLogger(Callback):
def on_train_begin(self, logs={}):
self.verbose = self.params['verbose']
def on_epoch_begin(self, epoch, logs={}):
if self.verbose:
print('Epoch %d' % epoch)
self.progbar = Progbar(target=self.params['nb_sample'], \
verbose=self.verbose)
self.current = 0
self.tot_loss = 0.
self.tot_acc = 0.
def on_batch_begin(self, batch, logs={}):
if self.current < self.params['nb_sample']:
self.log_values = []
def on_batch_end(self, batch, logs={}):
batch_size = logs.get('size', 0)
self.current += batch_size
loss = logs.get('loss')
self.log_values.append(('loss', loss))
self.tot_loss += loss * batch_size
if self.params['show_accuracy']:
accuracy = logs.get('accuracy')
self.log_values.append(('acc.', accuracy))
self.tot_acc += accuracy * batch_size
# skip progbar update for the last batch; will be handled by on_epoch_end
if self.verbose and self.current < self.params['nb_sample']:
self.progbar.update(self.current, self.log_values)
def on_epoch_end(self, epoch, logs={}):
self.log_values.append(('loss', self.tot_loss / self.current))
if self.params['show_accuracy']:
self.log_values.append(('acc.', self.tot_acc / self.current))
if self.params['do_validation']:
val_loss = logs.get('val_loss')
self.log_values.append(('val. loss', val_loss))
# added by zhaowuxia begins
min_val_loss = logs.get('min_val_loss')
self.log_values.append(('min val. loss', min_val_loss))
# added by zhaowuxia ends
if self.params['show_accuracy']:
val_acc = logs.get('val_accuracy')
self.log_values.append(('val. acc.', val_acc))
# added by zhaowuxia begins
max_val_acc = logs.get('max_val_accuracy')
self.log_values.append(('max val. loss', max_val_acc))
# added by zhaowuxia ends
self.progbar.update(self.current, self.log_values)
class History(Callback):
def on_train_begin(self, logs={}):
self.epoch = []
self.loss = []
if self.params['show_accuracy']:
self.accuracy = []
if self.params['do_validation']:
self.validation_loss = []
if self.params['show_accuracy']:
self.validation_accuracy = []
def on_epoch_begin(self, epoch, logs={}):
self.seen = 0
self.tot_loss = 0.
self.tot_accuracy = 0.
def on_batch_end(self, batch, logs={}):
batch_size = logs.get('size', 0)
self.seen += batch_size
self.tot_loss += logs.get('loss', 0.) * batch_size
if self.params['show_accuracy']:
self.tot_accuracy += logs.get('accuracy', 0.) * batch_size
def on_epoch_end(self, epoch, logs={}):
val_loss = logs.get('val_loss')
val_acc = logs.get('val_accuracy')
self.epoch.append(epoch)
self.loss.append(self.tot_loss / self.seen)
if self.params['show_accuracy']:
self.accuracy.append(self.tot_accuracy / self.seen)
if self.params['do_validation']:
self.validation_loss.append(val_loss)
if self.params['show_accuracy']:
self.validation_accuracy.append(val_acc)
| [
"numpy.median",
"warnings.warn",
"collections.deque",
"time.time"
] | [((903, 938), 'collections.deque', 'deque', (['[]'], {'maxlen': 'self.queue_length'}), '([], maxlen=self.queue_length)\n', (908, 938), False, 'from collections import deque\n'), ((974, 1009), 'collections.deque', 'deque', (['[]'], {'maxlen': 'self.queue_length'}), '([], maxlen=self.queue_length)\n', (979, 1009), False, 'from collections import deque\n'), ((1218, 1229), 'time.time', 'time.time', ([], {}), '()\n', (1227, 1229), False, 'import time\n'), ((1420, 1457), 'numpy.median', 'np.median', (['self._delta_ts_batch_begin'], {}), '(self._delta_ts_batch_begin)\n', (1429, 1457), True, 'import numpy as np\n'), ((1766, 1777), 'time.time', 'time.time', ([], {}), '()\n', (1775, 1777), False, 'import time\n'), ((1916, 1927), 'time.time', 'time.time', ([], {}), '()\n', (1925, 1927), False, 'import time\n'), ((2114, 2149), 'numpy.median', 'np.median', (['self._delta_ts_batch_end'], {}), '(self._delta_ts_batch_end)\n', (2123, 2149), True, 'import numpy as np\n'), ((1594, 1726), 'warnings.warn', 'warnings.warn', (["('Method on_batch_begin() is slow compared to the batch update (%f). Check your callbacks.'\n % delta_t_median)"], {}), "(\n 'Method on_batch_begin() is slow compared to the batch update (%f). Check your callbacks.'\n % delta_t_median)\n", (1607, 1726), False, 'import warnings\n'), ((1853, 1864), 'time.time', 'time.time', ([], {}), '()\n', (1862, 1864), False, 'import time\n'), ((2286, 2416), 'warnings.warn', 'warnings.warn', (["('Method on_batch_end() is slow compared to the batch update (%f). Check your callbacks.'\n % delta_t_median)"], {}), "(\n 'Method on_batch_end() is slow compared to the batch update (%f). Check your callbacks.'\n % delta_t_median)\n", (2299, 2416), False, 'import warnings\n'), ((1361, 1372), 'time.time', 'time.time', ([], {}), '()\n', (1370, 1372), False, 'import time\n'), ((2055, 2066), 'time.time', 'time.time', ([], {}), '()\n', (2064, 2066), False, 'import time\n')] |
"""
Implement the pipeline to generate data
"""
import subprocess
from multiprocessing import Process, Queue
import argparse
from scripts.ml_scene_gen import scene_gen
from scripts.data_gen_util import toml_dict
import numpy as np
import os
def main(args):
#scene_gen(args.NP, args.sp, args.path)
# generate path
path = args.path
ps = []
# 1 process -> 20 paths
def single_process_gen(NP, sp):
for i in range(NP):
print('generating problem %d' % (i+sp))
while True:
# generate problems until success
scene_gen(1, i+sp, args.path)
prob_path = args.path + "%d/" % (i+sp)
problem_name = "prob%d" % (i+sp)
toml = toml_dict(prob_path, problem_name, path)
# write the toml file
f = open(prob_path + 'clutter_ml.toml', 'w')
for name, val in toml.items():
f.write("%s = \"%s\"\n" % (name, val))
f.close()
# we give 5 trials, and if non succeed, then regenerate problem
subprocess.run(args=["./planet_gen_traj", prob_path+"clutter_ml.toml", '-r', '3'],
)#stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
# check if the solution path is stored, if yes, then success and generate next scene
if os.path.exists(prob_path+'clutter_ml_cont_state.txt'):
break
NP = 1 #20
num_process = int(np.round(args.NP / NP))
for i in range(num_process):
# calculate sp
sp = args.sp + NP * i
p = Process(target=single_process_gen, args=(NP, sp))
ps.append(p)
p.start()
try:
for p in ps:
p.join()
except:
print('terminating child processes...')
for i in range(num_process):
ps[i].terminate()
ps[i].join()
print('finished terminate.')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--path', type=str, default='./')
parser.add_argument('--NP', type=int, default=20)
parser.add_argument('--sp', type=int, default=0)
args = parser.parse_args()
main(args) | [
"subprocess.run",
"scripts.data_gen_util.toml_dict",
"argparse.ArgumentParser",
"os.path.exists",
"scripts.ml_scene_gen.scene_gen",
"multiprocessing.Process",
"numpy.round"
] | [((2038, 2063), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2061, 2063), False, 'import argparse\n'), ((1531, 1553), 'numpy.round', 'np.round', (['(args.NP / NP)'], {}), '(args.NP / NP)\n', (1539, 1553), True, 'import numpy as np\n'), ((1653, 1702), 'multiprocessing.Process', 'Process', ([], {'target': 'single_process_gen', 'args': '(NP, sp)'}), '(target=single_process_gen, args=(NP, sp))\n', (1660, 1702), False, 'from multiprocessing import Process, Queue\n'), ((596, 627), 'scripts.ml_scene_gen.scene_gen', 'scene_gen', (['(1)', '(i + sp)', 'args.path'], {}), '(1, i + sp, args.path)\n', (605, 627), False, 'from scripts.ml_scene_gen import scene_gen\n'), ((754, 794), 'scripts.data_gen_util.toml_dict', 'toml_dict', (['prob_path', 'problem_name', 'path'], {}), '(prob_path, problem_name, path)\n', (763, 794), False, 'from scripts.data_gen_util import toml_dict\n'), ((1122, 1210), 'subprocess.run', 'subprocess.run', ([], {'args': "['./planet_gen_traj', prob_path + 'clutter_ml.toml', '-r', '3']"}), "(args=['./planet_gen_traj', prob_path + 'clutter_ml.toml',\n '-r', '3'])\n", (1136, 1210), False, 'import subprocess\n'), ((1412, 1467), 'os.path.exists', 'os.path.exists', (["(prob_path + 'clutter_ml_cont_state.txt')"], {}), "(prob_path + 'clutter_ml_cont_state.txt')\n", (1426, 1467), False, 'import os\n')] |
"""
Version: 1.0
Last modified on: 17 November, 2014
Developers: <NAME>, <NAME>.
email: eduardo_(DOT)_luis_(AT)_aluno_(DOT)_ufabc_(DOT)_edu_(DOT)_br
: folivetti_(AT)_ufabc_(DOT)_edu_(DOT)_br
Based on source-code by <NAME> and <NAME>
available at http://goanna.cs.rmit.edu.au/~xiaodong/cec15-niching/competition/
"""
import numpy as np
def get_ub(fno):
if (fno == 1):
ub = 30
elif(fno == 2 or fno == 3):
ub = 1
elif(fno == 4):
ub = 6*np.ones([1,2])
elif(fno == 5):
ub = np.array( [1.9, 1.1] )
elif(fno == 6 or fno == 8):
ub = 10*np.ones([1,2])
elif(fno == 7 or fno == 9):
ub = 10*np.ones([1,2])
elif(fno == 10):
ub = np.ones([1,2])
elif(fno == 11 or fno == 12 or fno == 13):
dim = 2
ub = 5*np.ones([1,dim])
elif(fno == 14 or fno == 15):
dim = 3
ub = 5*np.ones([1,dim])
elif(fno == 16 or fno == 17):
dim = 5
ub = 5*np.ones([1,dim])
elif(fno == 18 or fno == 19):
dim = 10
ub = 5*np.ones([1,dim])
elif(fno == 20):
dim = 20
ub = 5*np.ones([1,dim])
else:
ub = []
return ub
| [
"numpy.array",
"numpy.ones"
] | [((502, 517), 'numpy.ones', 'np.ones', (['[1, 2]'], {}), '([1, 2])\n', (509, 517), True, 'import numpy as np\n'), ((552, 572), 'numpy.array', 'np.array', (['[1.9, 1.1]'], {}), '([1.9, 1.1])\n', (560, 572), True, 'import numpy as np\n'), ((625, 640), 'numpy.ones', 'np.ones', (['[1, 2]'], {}), '([1, 2])\n', (632, 640), True, 'import numpy as np\n'), ((690, 705), 'numpy.ones', 'np.ones', (['[1, 2]'], {}), '([1, 2])\n', (697, 705), True, 'import numpy as np\n'), ((741, 756), 'numpy.ones', 'np.ones', (['[1, 2]'], {}), '([1, 2])\n', (748, 756), True, 'import numpy as np\n'), ((838, 855), 'numpy.ones', 'np.ones', (['[1, dim]'], {}), '([1, dim])\n', (845, 855), True, 'import numpy as np\n'), ((923, 940), 'numpy.ones', 'np.ones', (['[1, dim]'], {}), '([1, dim])\n', (930, 940), True, 'import numpy as np\n'), ((1008, 1025), 'numpy.ones', 'np.ones', (['[1, dim]'], {}), '([1, dim])\n', (1015, 1025), True, 'import numpy as np\n'), ((1094, 1111), 'numpy.ones', 'np.ones', (['[1, dim]'], {}), '([1, dim])\n', (1101, 1111), True, 'import numpy as np\n'), ((1167, 1184), 'numpy.ones', 'np.ones', (['[1, dim]'], {}), '([1, dim])\n', (1174, 1184), True, 'import numpy as np\n')] |
"""
Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
and <NAME>
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
__author__ = 'jhuapl, antor'
__version__ = 0.1
import json
from keras.applications import VGG16, VGG19, MobileNet, imagenet_utils, InceptionResNetV2, InceptionV3, Xception, ResNet50
from keras.layers import Dense,Input,Flatten,Dropout,LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, \
MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D
from keras.models import Sequential,Model
from keras.preprocessing.image import random_channel_shift
from keras.utils.np_utils import to_categorical
import numpy as np
from data_ml_functions.dataFunctions import get_batch_inds, flip_axis
from glob import glob
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from functools import partial
from collections import defaultdict
import copy
import random
import cv2
import scipy
import math
#from data_ml_functions.iterm import show_image
import datetime
#from data_ml_functions.keras_squeeze_excite_network.se_inception_resnet_v2 import SEInceptionResNetV2
#from data_ml_functions.DenseNet import densenet
def get_cnn_model(params):
"""
Load base CNN model and add metadata fusion layers if 'use_metadata' is set in params.py
:param params: global parameters, used to find location of the dataset and json file
:return model: CNN model with or without depending on params
"""
if params.views == 0:
input_tensor = Input(shape=(params.target_img_size, params.target_img_size, params.num_channels))
else:
input_tensors = []
for _ in range(params.views):
_i = Input(shape=(params.target_img_size, params.target_img_size, params.num_channels))
input_tensors.append(_i)
classifier = globals()[params.classifier]
if params.classifier == 'densenet':
baseModel = densenet.DenseNetImageNet161(
input_shape=(params.target_img_size, params.target_img_size, params.num_channels), include_top=False)
else:
baseModel = classifier(weights='imagenet' if not params.no_imagenet else None,
include_top=False,
pooling=params.pooling if params.pooling != 'none' else None,
input_shape=(params.target_img_size, params.target_img_size, params.num_channels))
if params.classifier == 'ResNet50' and params.pooling == 'none':
baseModel.layers.pop()
baseModel.outputs = [baseModel.layers[-1].output]
baseModel.output_layers = [baseModel.layers[-1]]
baseModel.layers[-1].outbound_nodes = []
trainable = False
n_trainable = 0
for i, layer in enumerate(baseModel.layers):
if i >= params.freeze:
trainable = True
n_trainable += 1
layer.trainable = trainable
print("Base CNN model has " + str(n_trainable) + "/" + str(len(baseModel.layers)) + " trainable layers")
if params.views == 0:
modelStruct = baseModel(input_tensor)
else:
modelStruct = None
for _input_tensor in input_tensors:
_modelStruct = baseModel(_input_tensor)
if modelStruct == None:
modelStruct = _modelStruct
else:
modelStruct = concatenate([modelStruct, _modelStruct])
#modelStruct = add([modelStruct, _modelStruct])
# new
if params.pooling != 'none':
mview_preffix = 'lstm_'
modelStruct = Reshape((params.views, -1))(modelStruct)
modelStruct = LSTM(1024, return_sequences=True, name=mview_preffix + '0_1024_' + str(params.views))(modelStruct)
modelStruct = LSTM(512, return_sequences=True, name=mview_preffix + '1_512_' + str(params.views))(modelStruct)
if True:
predictions = Activation('softmax')(modelStruct)
else:
modelStruct = Flatten()(modelStruct)
predictions = Dense(params.num_labels, activation='softmax', name='predictions')(modelStruct)
else:
last_shape = modelStruct.shape
assert last_shape[1] == last_shape[2]
conv_features_grid_shape = int(last_shape[1])
conv_features_filters_shape = int(last_shape[3])
new_shape = (params.views, conv_features_grid_shape, conv_features_grid_shape, -1)
modelStruct = Reshape(new_shape)(modelStruct)
if params.view_model == 'lstm2d':
# TODO: make it adaptative rel to grid shape
mview_preffix = 'lstm2d_'
modelStruct = ConvLSTM2D(256, (1,1), activation='relu', return_sequences=True, name=mview_preffix + '0_256_' + str(params.views))(modelStruct)
#modelStruct = ConvLSTM2D(256, (3,3), activation='relu', return_sequences=True, name=lstm_preffix + '1_256_' + str(params.views))(modelStruct)
modelStruct = ConvLSTM2D(256, (3,3), activation='relu', return_sequences=True, name=mview_preffix + '2_256_' + str(params.views))(modelStruct)
modelStruct = ConvLSTM2D(params.num_labels, (3,3), return_sequences=False, name=mview_preffix + 'labels_' + str(params.views))(modelStruct)
modelStruct = Flatten()(modelStruct)
modelStruct = Activation('softmax')(modelStruct)
elif params.view_model == 'conv3d':
mview_preffix = 'conv3d_'
down_convs = max(conv_features_grid_shape, params.views)
kernels_views = np.diff(np.linspace(params.views, 1, down_convs, dtype=np.int32))
# defer kernel view to bottom of convs
kernels_views_holes = 0
for kernel_views in kernels_views:
if kernel_views == 0:
kernels_views_holes += 1
kernels_views = np.roll(kernels_views, kernels_views_holes)
kernels_grids = np.diff(np.linspace(conv_features_grid_shape, 1, down_convs, dtype=np.int32))
#todo change 6 below to 2**(ceil(log2(params.num_labels)
filters = 2** np.int32(np.log2(np.logspace(np.log2(conv_features_filters_shape)-1,6, down_convs, dtype=np.int32, base=2)))
filters[-1] = params.num_labels
for it, (kernel_views, kernel_grid, _filter) in enumerate(zip(kernels_views, kernels_grids, filters[1:])):
last = (it == down_convs - 2)
_kernel_views = -kernel_views + 1
_kernel_grid = -kernel_grid + 1
modelStruct = Conv3D(
_filter,
(_kernel_views,_kernel_grid,_kernel_grid),
activation='relu' if not last else 'softmax',
name=mview_preffix + str(it) + '_k'+ str(_kernel_views) + '_' + str(_kernel_grid) + '_f' + str(_filter) + '_' + str(params.views) + ('_softmax' if last else ''))(modelStruct)
if not last:
modelStruct = BatchNormalization(name=mview_preffix + str(it) + '_batchnorm_' + str(params.views))(modelStruct)
# fixed
#modelStruct = Conv3D(512, (1,1,1), activation='relu', name=mview_preffix + '0_512_' + str(params.views))(modelStruct)
#modelStruct = BatchNormalization()(modelStruct)
#modelStruct = Conv3D(256, (2,3,3), activation='relu', name=mview_preffix + '1_256_' + str(params.views))(modelStruct)
#modelStruct = BatchNormalization()(modelStruct)
#modelStruct = Conv3D(128, (2,3,3), activation='relu', name=mview_preffix + '2_128_' + str(params.views))(modelStruct)
#modelStruct = BatchNormalization()(modelStruct)
#modelStruct = Conv3D(params.num_labels, (1,1,1), activation='softmax', name=mview_preffix + '3_labels_' + str(params.views))(modelStruct)
predictions = Flatten()(modelStruct)
#model.add(Dense(params.num_labels, activation='softmax'))
#modelStruct = Permute((2, 1))(modelStruct)
#modelStruct = LocallyConnected1D(3, 1, activation='relu')(modelStruct)
#modelStruct = LocallyConnected1D(2, 1, activation='relu')(modelStruct)
#modelStruct = LocallyConnected1D(1, 1, activation='relu')(modelStruct)
#modelStruct = Flatten()(modelStruct)
# modelStruct = Conv1D(512, 1, activation='relu')(modelStruct)
# new
if params.use_metadata:
auxiliary_input = Input(shape=(params.metadata_length,), name='aux_input')
modelStruct = concatenate([modelStruct, auxiliary_input])
modelStruct = Dense(params.cnn_last_layer_length, activation='relu', name='fc1')(modelStruct)
modelStruct = Dropout(0.2)(modelStruct)
#modelStruct = Dense(512, activation='relu', name='nfc2')(modelStruct)
#modelStruct = Dropout(0.1)(modelStruct)
#modelStruct = Dense(1024, activation='relu', name='nfc1')(modelStruct)
#modelStruct = Dropout(0.3)(modelStruct)
if params.views == 0:
modelStruct = Dense(512, activation='relu', name='nfc2')(modelStruct)
modelStruct = Dropout(0.5)(modelStruct)
modelStruct = Dense(512, activation='relu', name='nfc3')(modelStruct)
modelStruct = Dropout(0.5)(modelStruct)
predictions = Dense(params.num_labels, activation='softmax', name='predictions')(modelStruct)
if params.views == 0:
inputs = [input_tensor]
else:
inputs = input_tensors
if params.use_metadata:
inputs.append(auxiliary_input)
model = Model(inputs=inputs, outputs=predictions)
return model
def get_multi_model(params, codesStats):
"""
Load LSTM model and add metadata concatenation to input if 'use_metadata' is set in params.py
:param params: global parameters, used to find location of the dataset and json file
:param codesStats: dictionary containing CNN codes statistics, which are used to normalize the inputs
:return model: LSTM model
"""
if params.use_metadata:
layerLength = params.cnn_multi_layer_length + params.metadata_length
else:
layerLength = params.cnn_multi_layer_length
layerShape = params.cnn_multi_layer_shape
print(codesStats['max_temporal'], layerLength)
model = Sequential()
arch = params.classifier
if arch == 'lstm':
model.add(InstanceNormalization(axis=2, input_shape=(codesStats['max_temporal'], layerLength)))
model.add(LSTM(256, return_sequences=True, input_shape=(codesStats['max_temporal'], layerLength), dropout=0.5))
model.add(LSTM(256, return_sequences=True, dropout=0.5))
model.add(Flatten())
model.add(Dense(params.num_labels, activation='softmax'))
elif arch == 'lstm2':
model.add(InstanceNormalization(axis=2, input_shape=(codesStats['max_temporal'], layerLength)))
model.add(LSTM(256, return_sequences=True, input_shape=(codesStats['max_temporal'], layerLength)))
model.add(LSTM(params.num_labels, return_sequences=False, dropout=0.5))
model.add(Activation(activation='softmax'))
# model.add(Dense(params.num_labels, activation='softmax'))
elif arch == 'lstm3':
model.add(InstanceNormalization(axis=2, input_shape=(codesStats['max_temporal'], layershape[0], layershape[1], layershape[2] )))
#model.add(Reshape(target_shape=( codesStats['max_temporal'], 1, 1, layerLength)))
model.add(ConvLSTM2D(128, 3, return_sequences=True, dropout=0.5))
model.add(ConvLSTM2D(params.num_labels, 3, return_sequences=False, dropout=0.5))
model.add(Flatten())
model.add(Activation(activation='softmax'))
#model.add(Dense(params.num_labels, activation='softmax'))
elif arch == 'gru':
model.add(GRU(128, return_sequences=True, input_shape=(codesStats['max_temporal'], layerLength), dropout=0.5))
model.add(GRU(128, return_sequences=True, input_shape=(codesStats['max_temporal'], layerLength), dropout=0.5))
model.add(GRU(params.num_labels, activation='softmax', return_sequences=False))
elif arch == 'pnet':
model.add(Reshape(target_shape=(codesStats['max_temporal'], layerLength, 1), input_shape=(codesStats['max_temporal'], layerLength)))
model.add(Conv2D(filters=1024, kernel_size=(1, 1), activation='relu'))
model.add(Conv2D(filters=2048, kernel_size=(1, 1), activation='relu'))
model.add(Conv2D(filters=4096, kernel_size=(1, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(codesStats['max_temporal'], 1), padding='valid'))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dense(params.num_labels, activation='softmax'))
return model
def img_metadata_generator(params, data, metadataStats, class_aware_sampling = True, augmentation = True):
"""
Custom generator that yields images or (image,metadata) batches and their
category labels (categorical format).
:param params: global parameters, used to find location of the dataset and json file
:param data: list of objects containing the category labels and paths to images and metadata features
:param metadataStats: metadata stats used to normalize metadata features
:yield (imgdata,labels) or (imgdata,metadata,labels): image data, metadata (if params set to use), and labels (categorical form)
"""
N = len(data)
if class_aware_sampling:
if params.views == 0:
data_labels = [datum['category'] for datum in data]
else:
data_labels = [datum[0]['category'] for datum in data]
label_to_idx = defaultdict(list)
for i, label in enumerate(data_labels):
label_to_idx[label].append(i)
running_label_to_idx = copy.deepcopy(label_to_idx)
executor = ThreadPoolExecutor(max_workers=params.num_workers)
while True:
if class_aware_sampling:
# class-aware supersampling
idx = []
num_labels = len(label_to_idx)
assert num_labels == params.num_labels
for _ in range(N):
random_label = np.random.randint(num_labels)
if len(running_label_to_idx[random_label]) == 0:
running_label_to_idx[random_label] = copy.copy(label_to_idx[random_label])
random.shuffle(running_label_to_idx[random_label])
idx.append(running_label_to_idx[random_label].pop())
else:
idx = np.random.permutation(N)
batchInds = get_batch_inds(params.batch_size, idx, N)
for inds in batchInds:
batchData = [data[ind] for ind in inds]
imgdata,metadata,labels = load_cnn_batch(params, batchData, metadataStats, executor, augmentation)
inputs = imgdata
if params.views != 0:
assert len(imgdata) == params.views
assert len(metadata) == params.views
assert len(labels) == params.views
# all labels should be equal
label = labels[0]
for _label in labels:
assert np.argmax(_label) == np.argmax(label)
labels = label
metadata = np.mean(metadata, axis=0)
if params.use_metadata:
if not isinstance(inputs, (list, tuple)):
inputs = [inputs]
inputs.append(metadata)
yield(inputs,labels)
def load_cnn_batch(params, batchData, metadataStats, executor, augmentation):
"""
Load batch of images and metadata and preprocess the data before returning.
:param params: global parameters, used to find location of the dataset and json file
:param batchData: list of objects in the current batch containing the category labels and paths to CNN codes and images
:param metadataStats: metadata stats used to normalize metadata features
:return imgdata,metadata,labels: numpy arrays containing the image data, metadata, and labels (categorical form)
"""
futures = []
if params.views == 0:
imgdata = np.zeros((params.batch_size,params.target_img_size,params.target_img_size,params.num_channels))
metadata = np.zeros((params.batch_size,params.metadata_length))
labels = np.zeros((params.batch_size, params.num_labels))
else:
imgdata = []
metadata = []
labels = []
for _ in range(params.views):
imgdata.append(np.zeros((params.batch_size,params.target_img_size,params.target_img_size,params.num_channels)))
metadata.append(np.zeros((params.batch_size,params.metadata_length)))
labels.append(np.zeros((params.batch_size, params.num_labels)))
inputs = []
results = []
for i in range(0,len(batchData)):
currInput = {}
currInput['data'] = batchData[i]
currInput['metadataStats'] = metadataStats
currInput['target_img_size'] = params.target_img_size
currInput['angle'] = params.angle
currInput['flip_north_south'] = params.flip_north_south
currInput['flip_east_west'] = params.flip_east_west
currInput['mask_metadata'] = params.mask_metadata
currInput['offset'] = params.offset
currInput['zoom'] = params.zoom
currInput['views'] = params.views
currInput['num_labels'] = params.num_labels
currInput['jitter_channel'] = params.jitter_channel
currInput['jitter_metadata'] = params.jitter_metadata
task = partial(_load_batch_helper, currInput, augmentation)
futures.append(executor.submit(task))
results = [future.result() for future in futures]
for i,result in enumerate(results):
if params.views == 0:
imgdata[i, ...] = result['img']
metadata[i,:] = result['metadata']
labels[i] = result['labels']
else:
for view in range(params.views):
imgdata[view][i] = result[view]['img']
metadata[view][i] = result[view]['metadata']
labels[view][i] = result[view]['labels']
return imgdata,metadata,labels
# counter-clockwise rotation
def rotate(a, angle, img_shape):
center = np.array([img_shape[1], img_shape[0]]) / 2.
theta = (angle/180.) * np.pi
rotMatrix = np.array([[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)]])
return np.dot(a - center, rotMatrix) + center
def zoom(a, scale, img_shape):
center = np.array([img_shape[1], img_shape[0]]) / 2.
return (a - center) * scale + center
def transform_metadata(metadata, flip_h, flip_v, angle=0, zoom = 1):
metadata_angles = np.fmod(180. + np.array(metadata[19:27]) * 360., 360.) - 180.
# b/c angles are clockwise we add the clockwise rotation angle
metadata_angles += angle
if flip_h: # > <
metadata_angles = - metadata_angles
if flip_v: # v ^
metadata_angles = 180. - metadata_angles
metadata[19:27] = list(np.fmod(metadata_angles + 2*360., 360.) / 360.)
# zoom > 1 is zoom OUT
# zoom < 1 is zoom IN
metadata[35] *= zoom
metadata[36] *= zoom
metadata[0] *= zoom # zoom > 1 zooms OUT so each pixel measures more
assert all([i <= 1. and i >=0. for i in metadata[19:27]])
return metadata
def mask_metadata(metadata):
'''
features[0] = float(jsonData['gsd'])
x,y = utm_to_xy(jsonData['utm'])
features[1] = x
features[2] = y
features[3] = float(jsonData['cloud_cover']) / 100.0
date = dparser.parse(jsonData['timestamp'])
features[4] = float(date.year)
features[5] = float(date.month) / 12.0
features[6] = float(date.day) / 31.0
features[7] = float(date.hour) + float(date.minute)/60.0
if jsonData['scan_direction'].lower() == 'forward':
features[8] = 0.0
else:
features[8] = 1.0
features[9] = float(jsonData['pan_resolution_dbl'])
features[10] = float(jsonData['pan_resolution_start_dbl'])
features[11] = float(jsonData['pan_resolution_end_dbl'])
features[12] = float(jsonData['pan_resolution_min_dbl'])
features[13] = float(jsonData['pan_resolution_max_dbl'])
features[14] = float(jsonData['multi_resolution_dbl'])
features[15] = float(jsonData['multi_resolution_min_dbl'])
features[16] = float(jsonData['multi_resolution_max_dbl'])
features[17] = float(jsonData['multi_resolution_start_dbl'])
features[18] = float(jsonData['multi_resolution_end_dbl'])
features[19] = float(jsonData['target_azimuth_dbl']) / 360.0
features[20] = float(jsonData['target_azimuth_min_dbl']) / 360.0
features[21] = float(jsonData['target_azimuth_max_dbl']) / 360.0
features[22] = float(jsonData['target_azimuth_start_dbl']) / 360.0
features[23] = float(jsonData['target_azimuth_end_dbl']) / 360.0
features[24] = float(jsonData['sun_azimuth_dbl']) / 360.0
features[25] = float(jsonData['sun_azimuth_min_dbl']) / 360.0
features[26] = float(jsonData['sun_azimuth_max_dbl']) / 360.0
features[27] = float(jsonData['sun_elevation_min_dbl']) / 90.0
features[28] = float(jsonData['sun_elevation_dbl']) / 90.0
features[29] = float(jsonData['sun_elevation_max_dbl']) / 90.0
features[30] = float(jsonData['off_nadir_angle_dbl']) / 90.0
features[31] = float(jsonData['off_nadir_angle_min_dbl']) / 90.0
features[32] = float(jsonData['off_nadir_angle_max_dbl']) / 90.0
features[33] = float(jsonData['off_nadir_angle_start_dbl']) / 90.0
features[34] = float(jsonData['off_nadir_angle_end_dbl']) / 90.0
features[35] = float(bb['box'][2])
features[36] = float(bb['box'][3])
features[37] = float(jsonData['img_width'])
features[38] = float(jsonData['img_height'])
features[39] = float(date.weekday())
features[40] = min([features[35], features[36]]) / max([features[37], features[38]])
features[41] = features[35] / features[37]
features[42] = features[36] / features[38]
features[43] = date.second
if len(jsonData['bounding_boxes']) == 1:
features[44] = 1.0
else:
features[44] = 0.0
'''
masked_attributes = [ \
6, # day
7, # hour/min
35, # bbox loc
36, # bbox loc
37, # img_width
38, # img_height
39, # weekday
43, # second
44, # 1 bbox or more
]
for to_mask in masked_attributes:
metadata[to_mask] = 0.
return metadata
def get_timestamp(metadata):
return (metadata[4]-1970)*525600 + metadata[5]*12*43800 + metadata[6]*31*1440 + metadata[7]*60
def jitter_metadata(metadata, scale, max_values):
year = int(metadata[4])
month = int(metadata[5]*12) # 1..12 / 12 => 1..12
day = int(metadata[6]*31) # 1..31 / 31 => 1..31
hour = int(metadata[7]) # 0..23 + 0..59/60 -> 0..23
minute = int((metadata[7] - hour) * 60) # 0..59
second = int(metadata[43]) # 0..59
scan_direction = metadata[8] # 0 or 1
bounding_boxes = metadata[44] # 0 or 1
_max_values = np.array(max_values)
metadata = np.random.uniform(metadata - _max_values * scale / 2., metadata + _max_values * scale / 2.)
timespan_1year = 365.25 # in days
time_delta = datetime.timedelta(\
days=int(np.random.uniform(-scale * 365/ 2, scale * 365 / 2)))
metadata_time = datetime.datetime(year, month, day, hour, minute) + time_delta
metadata[4] = metadata_time.year
metadata[5] = metadata_time.month/12.
metadata[6] = metadata_time.day/31.
metadata[7] = hour/12. # keep hour b/c lighting conditions
metadata[39] = float(metadata_time.weekday())
metadata[43] = metadata_time.second
metadata[8] = scan_direction # keep scan direction
metadata[44] = bounding_boxes # keep bounding boxes (0 or 1)
return metadata
def _load_batch_helper(inputDict, augmentation):
"""
Helper for load_cnn_batch that actually loads imagery and supports parallel processing
:param inputDict: dict containing the data and metadataStats that will be used to load imagery
:return currOutput: dict with image data, metadata, and the associated label
"""
datas = inputDict['data']
metadataStats = inputDict['metadataStats']
num_labels = inputDict['num_labels']
# for 0-views make it a list so we can iterate later
if not isinstance(datas, (list, tuple)):
datas = [datas]
currOutputs = [ ]
target_img_size = inputDict['target_img_size']
if augmentation:
random_offset = (np.random.random((2,)) - 0.5 ) * (inputDict['offset'] * target_img_size)
random_angle = (np.random.random() - 0.5 ) * inputDict['angle']
random_zoom = np.random.uniform(1. - inputDict['zoom'] / 2., 1 + inputDict['zoom'] / 2.)
flip_v = (np.random.random() < 0.5) and inputDict['flip_east_west']
flip_h = (np.random.random() < 0.5) and inputDict['flip_north_south']
else:
random_offset = np.zeros(2,)
random_zoom = 1.
random_angle = 0.
flip_v = flip_h = False
if inputDict['views'] != 0:
datas = random.sample(datas, inputDict['views'])
timestamps = []
for data in datas:
metadata = json.load(open(data['features_path']))
timestamps.append(get_timestamp(metadata))
img = scipy.misc.imread(data['img_path'])
if inputDict['jitter_channel'] != 0 and augmentation:
img = random_channel_shift(img, inputDict['jitter_channel'] * 255., 2)
if (random_angle != 0. or random_zoom != 1.) and augmentation:
patch_size = img.shape[0]
patch_center = patch_size / 2
sq2 = 1.4142135624
src_points = np.float32([
[ patch_center - target_img_size / 2 , patch_center - target_img_size / 2 ],
[ patch_center + target_img_size / 2 , patch_center - target_img_size / 2 ],
[ patch_center + target_img_size / 2 , patch_center + target_img_size / 2 ]])
# src_points are rotated COUNTER-CLOCKWISE
src_points = rotate(src_points, random_angle, img.shape)
src_points = zoom(src_points, random_zoom, img.shape)
src_points += random_offset
# dst_points are fixed
dst_points = np.float32([
[ 0 , 0 ],
[ target_img_size - 1, 0 ],
[ target_img_size - 1, target_img_size - 1]])
# this is effectively a CLOCKWISE rotation
M = cv2.getAffineTransform(src_points.astype(np.float32), dst_points)
img = cv2.warpAffine(img, M, (target_img_size, target_img_size), borderMode = cv2.BORDER_REFLECT_101).astype(np.float32)
else:
crop_size = target_img_size
x0 = int(img.shape[1]/2 - crop_size/2 + random_offset[0])
x1 = x0 + crop_size
y0 = int(img.shape[0]/2 - crop_size/2 + random_offset[1])
y1 = y0 + crop_size
img = img[y0:y1, x0:x1,...].astype(np.float32)
if flip_h:
img = flip_axis(img, 1) # flips > into <
if flip_v:
img = flip_axis(img, 0) # flips ^ into v
#show_image(img.astype(np.uint8))
#raw_input("Press enter")
if augmentation:
metadata = transform_metadata(metadata, flip_h=flip_h, flip_v=flip_v, angle=random_angle, zoom=random_zoom)
if inputDict['jitter_metadata'] != 0:
metadata = jitter_metadata(metadata, inputDict['jitter_metadata'], metadataStats['metadata_max'])
img = imagenet_utils.preprocess_input(img) / 255.
labels = to_categorical(data['category'], num_labels)
currOutput = {}
currOutput['img'] = copy.deepcopy(img)
metadata = np.divide(json.load(open(data['features_path'])) - np.array(metadataStats['metadata_mean']), metadataStats['metadata_max'])
if inputDict['mask_metadata']:
metadata = mask_metadata(metadata)
currOutput['metadata'] = metadata
currOutput['labels'] = labels
currOutputs.append(currOutput)
if (len(currOutputs) == 1) and (inputDict['views'] == 0):
currOutputs = currOutputs[0]
else:
# sort by timestamp
sortedInds = sorted(range(len(timestamps)), key=lambda k:timestamps[k])
currOutputs = [currOutputs[i] for i in sortedInds]
return currOutputs
def codes_metadata_generator(params, data, metadataStats, codesStats, class_aware_sampling = True, temporal_dropout = True):
"""
Custom generator that yields a vector containign the 4096-d CNN codes output by ResNet50 and metadata features (if params set to use).
:param params: global parameters, used to find location of the dataset and json file
:param data: list of objects containing the category labels and paths to CNN codes and images
:param metadataStats: metadata stats used to normalize metadata features
:yield (codesMetadata,labels): 4096-d CNN codes + metadata features (if set), and labels (categorical form)
"""
N = len(data)
if class_aware_sampling:
data_labels = [datum['category'] for datum in data.values()]
label_to_idx = defaultdict(list)
for i, label in enumerate(data_labels):
label_to_idx[label].append(i)
running_label_to_idx = copy.deepcopy(label_to_idx)
trainKeys = list(data.keys())
executor = ThreadPoolExecutor(max_workers=1)#params.num_workers)
while True:
if class_aware_sampling:
#idx = np.random.permutation(N)
# class-aware supersampling
idx = []
num_labels = len(label_to_idx)
assert num_labels == params.num_labels
for _ in range(N):
random_label = np.random.randint(num_labels)
if len(running_label_to_idx[random_label]) == 0:
running_label_to_idx[random_label] = copy.copy(label_to_idx[random_label])
random.shuffle(running_label_to_idx[random_label])
idx.append(running_label_to_idx[random_label].pop())
else:
idx = np.random.permutation(N)
batchInds = get_batch_inds(params.batch_size, idx, N)
for inds in batchInds:
batchKeys = [trainKeys[ind] for ind in inds]
codesMetadata, labels = load_lstm_batch(params, data, batchKeys, metadataStats, codesStats, executor, temporal_dropout)
yield(codesMetadata,labels)
def load_lstm_batch(params, data, batchKeys, metadataStats, codesStats, executor, temporal_dropout):
"""
Load batch of CNN codes + metadata and preprocess the data before returning.
:param params: global parameters, used to find location of the dataset and json file
:param data: dictionary where the values are the paths to the files containing the CNN codes and metadata for a particular sequence
:param batchKeys: list of keys for the current batch, where each key represents a temporal sequence of CNN codes and metadata
:param metadataStats: metadata stats used to normalize metadata features
:param codesStats: CNN codes stats used to normalize CNN codes and define the maximum number of temporal views
:return codesMetadata,labels: 4096-d CNN codes + metadata (if set) and labels (categorical form)
"""
if params.use_metadata:
codesMetadata = np.zeros((params.batch_size, codesStats['max_temporal'], params.cnn_multi_layer_length + params.metadata_length))
else:
codesMetadata = np.zeros((params.batch_size, codesStats['max_temporal'], params.cnn_multi_layer_shape[0], params.cnn_multi_layer_shape[1], params.cnn_multi_layer_shape[2]))
labels = np.zeros(params.batch_size)
futures = []
for i,key in enumerate(batchKeys):
currInput = {}
currInput['currData'] = data[key]
currInput['lastLayerLength'] = codesMetadata.shape[2]
currInput['lastLayerShape'] = params.cnn_multi_layer_shape
currInput['codesStats'] = codesStats
currInput['use_metadata'] = params.use_metadata
currInput['metadataStats'] = metadataStats
currInput['mask_metadata'] = params.mask_metadata
currInput['temporal_dropout'] = temporal_dropout
labels[i] = data[key]['category']
task = partial(_load_lstm_batch_helper, currInput)
futures.append(executor.submit(task))
results = [future.result() for future in futures]
for i,result in enumerate(results):
codesMetadata[i,:,:] = result['codesMetadata']
labels = to_categorical(labels, params.num_labels)
return codesMetadata,labels
def _load_lstm_batch_helper(inputDict):
currData = inputDict['currData']
codesStats = inputDict['codesStats']
metadataStats = inputDict['metadataStats']
currOutput = {}
codesMetadata = np.zeros((codesStats['max_temporal'], inputDict['lastLayerLength']))
timestamps = []
temporal_dropout = inputDict['temporal_dropout']
n_codes = len(currData['cnn_codes_paths'])
n_codes_indexes = range(n_codes)
if n_codes > 3 and temporal_dropout != 0:
n_codes_to_train = int(math.ceil(n_codes * (1 - np.random.rand() * temporal_dropout)))
n_codes_to_train = max(n_codes_to_train, 3)
n_codes_indexes = random.sample(n_codes_indexes, n_codes_to_train)
if len(n_codes_indexes) > codesStats['max_temporal']:
n_codes_indexes = n_codes_indexes[:codesStats['max_temporal']]
for i, codesIndex in enumerate(n_codes_indexes):
#cnnCodes = json.load(open(currData['cnn_codes_paths'][codesIndex]))
cnnCodes = np.load(jcurrData['cnn_codes_paths'][codesIndex])
metadata = json.load(open(currData['metadata_paths'][codesIndex]))
# compute a timestamp for temporally sorting
timestamp = get_timestamp(metadata)
timestamps.append(timestamp)
cnnCodes = np.divide(cnnCodes - np.array(codesStats['codes_mean']), np.array(codesStats['codes_max']))
metadata = np.divide(metadata - np.array(metadataStats['metadata_mean']), np.array(metadataStats['metadata_max']))
if inputDict['use_metadata']:
if inputDict['mask_metadata']:
metadata = mask_metadata(metadata)
codesMetadata[i,:] = np.concatenate((cnnCodes, metadata), axis=0)
else:
codesMetadata[i,...] = cnnCodes
sortedInds = sorted(range(len(timestamps)), key=lambda k:timestamps[k])
codesMetadata[range(len(sortedInds)),:] = codesMetadata[sortedInds,:]
currOutput['codesMetadata'] = codesMetadata
return currOutput
| [
"numpy.load",
"numpy.argmax",
"random.sample",
"random.shuffle",
"keras.models.Model",
"collections.defaultdict",
"cv2.warpAffine",
"numpy.random.randint",
"numpy.mean",
"numpy.sin",
"keras.layers.Input",
"keras.layers.ConvLSTM2D",
"keras.layers.concatenate",
"keras.preprocessing.image.ran... | [((10477, 10518), 'keras.models.Model', 'Model', ([], {'inputs': 'inputs', 'outputs': 'predictions'}), '(inputs=inputs, outputs=predictions)\n', (10482, 10518), False, 'from keras.models import Sequential, Model\n'), ((11220, 11232), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (11230, 11232), False, 'from keras.models import Sequential, Model\n'), ((14832, 14882), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', ([], {'max_workers': 'params.num_workers'}), '(max_workers=params.num_workers)\n', (14850, 14882), False, 'from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\n'), ((24324, 24344), 'numpy.array', 'np.array', (['max_values'], {}), '(max_values)\n', (24332, 24344), True, 'import numpy as np\n'), ((24361, 24459), 'numpy.random.uniform', 'np.random.uniform', (['(metadata - _max_values * scale / 2.0)', '(metadata + _max_values * scale / 2.0)'], {}), '(metadata - _max_values * scale / 2.0, metadata + \n _max_values * scale / 2.0)\n', (24378, 24459), True, 'import numpy as np\n'), ((30880, 30913), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', ([], {'max_workers': '(1)'}), '(max_workers=1)\n', (30898, 30913), False, 'from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\n'), ((33228, 33255), 'numpy.zeros', 'np.zeros', (['params.batch_size'], {}), '(params.batch_size)\n', (33236, 33255), True, 'import numpy as np\n'), ((34110, 34151), 'keras.utils.np_utils.to_categorical', 'to_categorical', (['labels', 'params.num_labels'], {}), '(labels, params.num_labels)\n', (34124, 34151), False, 'from keras.utils.np_utils import to_categorical\n'), ((34408, 34476), 'numpy.zeros', 'np.zeros', (["(codesStats['max_temporal'], inputDict['lastLayerLength'])"], {}), "((codesStats['max_temporal'], inputDict['lastLayerLength']))\n", (34416, 34476), True, 'import numpy as np\n'), ((2145, 2232), 'keras.layers.Input', 'Input', ([], {'shape': '(params.target_img_size, params.target_img_size, params.num_channels)'}), '(shape=(params.target_img_size, params.target_img_size, params.\n num_channels))\n', (2150, 2232), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((9363, 9419), 'keras.layers.Input', 'Input', ([], {'shape': '(params.metadata_length,)', 'name': '"""aux_input"""'}), "(shape=(params.metadata_length,), name='aux_input')\n", (9368, 9419), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((9445, 9488), 'keras.layers.concatenate', 'concatenate', (['[modelStruct, auxiliary_input]'], {}), '([modelStruct, auxiliary_input])\n', (9456, 9488), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((14644, 14661), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (14655, 14661), False, 'from collections import defaultdict\n'), ((14786, 14813), 'copy.deepcopy', 'copy.deepcopy', (['label_to_idx'], {}), '(label_to_idx)\n', (14799, 14813), False, 'import copy\n'), ((15585, 15626), 'data_ml_functions.dataFunctions.get_batch_inds', 'get_batch_inds', (['params.batch_size', 'idx', 'N'], {}), '(params.batch_size, idx, N)\n', (15599, 15626), False, 'from data_ml_functions.dataFunctions import get_batch_inds, flip_axis\n'), ((17203, 17305), 'numpy.zeros', 'np.zeros', (['(params.batch_size, params.target_img_size, params.target_img_size, params.\n num_channels)'], {}), '((params.batch_size, params.target_img_size, params.target_img_size,\n params.num_channels))\n', (17211, 17305), True, 'import numpy as np\n'), ((17319, 17372), 'numpy.zeros', 'np.zeros', (['(params.batch_size, params.metadata_length)'], {}), '((params.batch_size, params.metadata_length))\n', (17327, 17372), True, 'import numpy as np\n'), ((17390, 17438), 'numpy.zeros', 'np.zeros', (['(params.batch_size, params.num_labels)'], {}), '((params.batch_size, params.num_labels))\n', (17398, 17438), True, 'import numpy as np\n'), ((18650, 18702), 'functools.partial', 'partial', (['_load_batch_helper', 'currInput', 'augmentation'], {}), '(_load_batch_helper, currInput, augmentation)\n', (18657, 18702), False, 'from functools import partial\n'), ((19384, 19422), 'numpy.array', 'np.array', (['[img_shape[1], img_shape[0]]'], {}), '([img_shape[1], img_shape[0]])\n', (19392, 19422), True, 'import numpy as np\n'), ((19596, 19625), 'numpy.dot', 'np.dot', (['(a - center)', 'rotMatrix'], {}), '(a - center, rotMatrix)\n', (19602, 19625), True, 'import numpy as np\n'), ((19683, 19721), 'numpy.array', 'np.array', (['[img_shape[1], img_shape[0]]'], {}), '([img_shape[1], img_shape[0]])\n', (19691, 19721), True, 'import numpy as np\n'), ((24629, 24678), 'datetime.datetime', 'datetime.datetime', (['year', 'month', 'day', 'hour', 'minute'], {}), '(year, month, day, hour, minute)\n', (24646, 24678), False, 'import datetime\n'), ((26022, 26099), 'numpy.random.uniform', 'np.random.uniform', (["(1.0 - inputDict['zoom'] / 2.0)", "(1 + inputDict['zoom'] / 2.0)"], {}), "(1.0 - inputDict['zoom'] / 2.0, 1 + inputDict['zoom'] / 2.0)\n", (26039, 26099), True, 'import numpy as np\n'), ((26289, 26300), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (26297, 26300), True, 'import numpy as np\n'), ((26443, 26483), 'random.sample', 'random.sample', (['datas', "inputDict['views']"], {}), "(datas, inputDict['views'])\n", (26456, 26483), False, 'import random\n'), ((26659, 26694), 'scipy.misc.imread', 'scipy.misc.imread', (["data['img_path']"], {}), "(data['img_path'])\n", (26676, 26694), False, 'import scipy\n'), ((29049, 29093), 'keras.utils.np_utils.to_categorical', 'to_categorical', (["data['category']", 'num_labels'], {}), "(data['category'], num_labels)\n", (29063, 29093), False, 'from keras.utils.np_utils import to_categorical\n'), ((29148, 29166), 'copy.deepcopy', 'copy.deepcopy', (['img'], {}), '(img)\n', (29161, 29166), False, 'import copy\n'), ((30655, 30672), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (30666, 30672), False, 'from collections import defaultdict\n'), ((30797, 30824), 'copy.deepcopy', 'copy.deepcopy', (['label_to_idx'], {}), '(label_to_idx)\n', (30810, 30824), False, 'import copy\n'), ((31675, 31716), 'data_ml_functions.dataFunctions.get_batch_inds', 'get_batch_inds', (['params.batch_size', 'idx', 'N'], {}), '(params.batch_size, idx, N)\n', (31689, 31716), False, 'from data_ml_functions.dataFunctions import get_batch_inds, flip_axis\n'), ((32905, 33023), 'numpy.zeros', 'np.zeros', (["(params.batch_size, codesStats['max_temporal'], params.\n cnn_multi_layer_length + params.metadata_length)"], {}), "((params.batch_size, codesStats['max_temporal'], params.\n cnn_multi_layer_length + params.metadata_length))\n", (32913, 33023), True, 'import numpy as np\n'), ((33055, 33221), 'numpy.zeros', 'np.zeros', (["(params.batch_size, codesStats['max_temporal'], params.\n cnn_multi_layer_shape[0], params.cnn_multi_layer_shape[1], params.\n cnn_multi_layer_shape[2])"], {}), "((params.batch_size, codesStats['max_temporal'], params.\n cnn_multi_layer_shape[0], params.cnn_multi_layer_shape[1], params.\n cnn_multi_layer_shape[2]))\n", (33063, 33221), True, 'import numpy as np\n'), ((33847, 33890), 'functools.partial', 'partial', (['_load_lstm_batch_helper', 'currInput'], {}), '(_load_lstm_batch_helper, currInput)\n', (33854, 33890), False, 'from functools import partial\n'), ((34863, 34911), 'random.sample', 'random.sample', (['n_codes_indexes', 'n_codes_to_train'], {}), '(n_codes_indexes, n_codes_to_train)\n', (34876, 34911), False, 'import random\n'), ((35205, 35254), 'numpy.load', 'np.load', (["jcurrData['cnn_codes_paths'][codesIndex]"], {}), "(jcurrData['cnn_codes_paths'][codesIndex])\n", (35212, 35254), True, 'import numpy as np\n'), ((2324, 2411), 'keras.layers.Input', 'Input', ([], {'shape': '(params.target_img_size, params.target_img_size, params.num_channels)'}), '(shape=(params.target_img_size, params.target_img_size, params.\n num_channels))\n', (2329, 2411), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((9514, 9580), 'keras.layers.Dense', 'Dense', (['params.cnn_last_layer_length'], {'activation': '"""relu"""', 'name': '"""fc1"""'}), "(params.cnn_last_layer_length, activation='relu', name='fc1')\n", (9519, 9580), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((9617, 9629), 'keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (9624, 9629), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((9950, 9992), 'keras.layers.Dense', 'Dense', (['(512)'], {'activation': '"""relu"""', 'name': '"""nfc2"""'}), "(512, activation='relu', name='nfc2')\n", (9955, 9992), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((10029, 10041), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (10036, 10041), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((10078, 10120), 'keras.layers.Dense', 'Dense', (['(512)'], {'activation': '"""relu"""', 'name': '"""nfc3"""'}), "(512, activation='relu', name='nfc3')\n", (10083, 10120), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((10157, 10169), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (10164, 10169), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((10206, 10272), 'keras.layers.Dense', 'Dense', (['params.num_labels'], {'activation': '"""softmax"""', 'name': '"""predictions"""'}), "(params.num_labels, activation='softmax', name='predictions')\n", (10211, 10272), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((11413, 11517), 'keras.layers.LSTM', 'LSTM', (['(256)'], {'return_sequences': '(True)', 'input_shape': "(codesStats['max_temporal'], layerLength)", 'dropout': '(0.5)'}), "(256, return_sequences=True, input_shape=(codesStats['max_temporal'],\n layerLength), dropout=0.5)\n", (11417, 11517), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((11534, 11579), 'keras.layers.LSTM', 'LSTM', (['(256)'], {'return_sequences': '(True)', 'dropout': '(0.5)'}), '(256, return_sequences=True, dropout=0.5)\n', (11538, 11579), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((11600, 11609), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (11607, 11609), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((11630, 11676), 'keras.layers.Dense', 'Dense', (['params.num_labels'], {'activation': '"""softmax"""'}), "(params.num_labels, activation='softmax')\n", (11635, 11676), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((15537, 15561), 'numpy.random.permutation', 'np.random.permutation', (['N'], {}), '(N)\n', (15558, 15561), True, 'import numpy as np\n'), ((20202, 20245), 'numpy.fmod', 'np.fmod', (['(metadata_angles + 2 * 360.0)', '(360.0)'], {}), '(metadata_angles + 2 * 360.0, 360.0)\n', (20209, 20245), True, 'import numpy as np\n'), ((26779, 26844), 'keras.preprocessing.image.random_channel_shift', 'random_channel_shift', (['img', "(inputDict['jitter_channel'] * 255.0)", '(2)'], {}), "(img, inputDict['jitter_channel'] * 255.0, 2)\n", (26799, 26844), False, 'from keras.preprocessing.image import random_channel_shift\n'), ((27061, 27308), 'numpy.float32', 'np.float32', (['[[patch_center - target_img_size / 2, patch_center - target_img_size / 2],\n [patch_center + target_img_size / 2, patch_center - target_img_size / 2\n ], [patch_center + target_img_size / 2, patch_center + target_img_size / 2]\n ]'], {}), '([[patch_center - target_img_size / 2, patch_center - \n target_img_size / 2], [patch_center + target_img_size / 2, patch_center -\n target_img_size / 2], [patch_center + target_img_size / 2, patch_center +\n target_img_size / 2]])\n', (27071, 27308), True, 'import numpy as np\n'), ((27664, 27759), 'numpy.float32', 'np.float32', (['[[0, 0], [target_img_size - 1, 0], [target_img_size - 1, target_img_size - 1]]'], {}), '([[0, 0], [target_img_size - 1, 0], [target_img_size - 1, \n target_img_size - 1]])\n', (27674, 27759), True, 'import numpy as np\n'), ((28460, 28477), 'data_ml_functions.dataFunctions.flip_axis', 'flip_axis', (['img', '(1)'], {}), '(img, 1)\n', (28469, 28477), False, 'from data_ml_functions.dataFunctions import get_batch_inds, flip_axis\n'), ((28537, 28554), 'data_ml_functions.dataFunctions.flip_axis', 'flip_axis', (['img', '(0)'], {}), '(img, 0)\n', (28546, 28554), False, 'from data_ml_functions.dataFunctions import get_batch_inds, flip_axis\n'), ((28985, 29021), 'keras.applications.imagenet_utils.preprocess_input', 'imagenet_utils.preprocess_input', (['img'], {}), '(img)\n', (29016, 29021), False, 'from keras.applications import VGG16, VGG19, MobileNet, imagenet_utils, InceptionResNetV2, InceptionV3, Xception, ResNet50\n'), ((31627, 31651), 'numpy.random.permutation', 'np.random.permutation', (['N'], {}), '(N)\n', (31648, 31651), True, 'import numpy as np\n'), ((35548, 35581), 'numpy.array', 'np.array', (["codesStats['codes_max']"], {}), "(codesStats['codes_max'])\n", (35556, 35581), True, 'import numpy as np\n'), ((35666, 35705), 'numpy.array', 'np.array', (["metadataStats['metadata_max']"], {}), "(metadataStats['metadata_max'])\n", (35674, 35705), True, 'import numpy as np\n'), ((35878, 35922), 'numpy.concatenate', 'np.concatenate', (['(cnnCodes, metadata)'], {'axis': '(0)'}), '((cnnCodes, metadata), axis=0)\n', (35892, 35922), True, 'import numpy as np\n'), ((3987, 4027), 'keras.layers.concatenate', 'concatenate', (['[modelStruct, _modelStruct]'], {}), '([modelStruct, _modelStruct])\n', (3998, 4027), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((4210, 4237), 'keras.layers.Reshape', 'Reshape', (['(params.views, -1)'], {}), '((params.views, -1))\n', (4217, 4237), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((5129, 5147), 'keras.layers.Reshape', 'Reshape', (['new_shape'], {}), '(new_shape)\n', (5136, 5147), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((11829, 11920), 'keras.layers.LSTM', 'LSTM', (['(256)'], {'return_sequences': '(True)', 'input_shape': "(codesStats['max_temporal'], layerLength)"}), "(256, return_sequences=True, input_shape=(codesStats['max_temporal'],\n layerLength))\n", (11833, 11920), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((11937, 11997), 'keras.layers.LSTM', 'LSTM', (['params.num_labels'], {'return_sequences': '(False)', 'dropout': '(0.5)'}), '(params.num_labels, return_sequences=False, dropout=0.5)\n', (11941, 11997), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((12018, 12050), 'keras.layers.Activation', 'Activation', ([], {'activation': '"""softmax"""'}), "(activation='softmax')\n", (12028, 12050), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((15169, 15198), 'numpy.random.randint', 'np.random.randint', (['num_labels'], {}), '(num_labels)\n', (15186, 15198), True, 'import numpy as np\n'), ((16299, 16324), 'numpy.mean', 'np.mean', (['metadata'], {'axis': '(0)'}), '(metadata, axis=0)\n', (16306, 16324), True, 'import numpy as np\n'), ((17586, 17688), 'numpy.zeros', 'np.zeros', (['(params.batch_size, params.target_img_size, params.target_img_size, params.\n num_channels)'], {}), '((params.batch_size, params.target_img_size, params.target_img_size,\n params.num_channels))\n', (17594, 17688), True, 'import numpy as np\n'), ((17712, 17765), 'numpy.zeros', 'np.zeros', (['(params.batch_size, params.metadata_length)'], {}), '((params.batch_size, params.metadata_length))\n', (17720, 17765), True, 'import numpy as np\n'), ((17793, 17841), 'numpy.zeros', 'np.zeros', (['(params.batch_size, params.num_labels)'], {}), '((params.batch_size, params.num_labels))\n', (17801, 17841), True, 'import numpy as np\n'), ((19490, 19503), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (19496, 19503), True, 'import numpy as np\n'), ((19551, 19564), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (19557, 19564), True, 'import numpy as np\n'), ((19567, 19580), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (19573, 19580), True, 'import numpy as np\n'), ((24551, 24603), 'numpy.random.uniform', 'np.random.uniform', (['(-scale * 365 / 2)', '(scale * 365 / 2)'], {}), '(-scale * 365 / 2, scale * 365 / 2)\n', (24568, 24603), True, 'import numpy as np\n'), ((25850, 25872), 'numpy.random.random', 'np.random.random', (['(2,)'], {}), '((2,))\n', (25866, 25872), True, 'import numpy as np\n'), ((25949, 25967), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (25965, 25967), True, 'import numpy as np\n'), ((26116, 26134), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (26132, 26134), True, 'import numpy as np\n'), ((26193, 26211), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (26209, 26211), True, 'import numpy as np\n'), ((29238, 29278), 'numpy.array', 'np.array', (["metadataStats['metadata_mean']"], {}), "(metadataStats['metadata_mean'])\n", (29246, 29278), True, 'import numpy as np\n'), ((31259, 31288), 'numpy.random.randint', 'np.random.randint', (['num_labels'], {}), '(num_labels)\n', (31276, 31288), True, 'import numpy as np\n'), ((35512, 35546), 'numpy.array', 'np.array', (["codesStats['codes_mean']"], {}), "(codesStats['codes_mean'])\n", (35520, 35546), True, 'import numpy as np\n'), ((35624, 35664), 'numpy.array', 'np.array', (["metadataStats['metadata_mean']"], {}), "(metadataStats['metadata_mean'])\n", (35632, 35664), True, 'import numpy as np\n'), ((4556, 4577), 'keras.layers.Activation', 'Activation', (['"""softmax"""'], {}), "('softmax')\n", (4566, 4577), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((4641, 4650), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (4648, 4650), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((4695, 4761), 'keras.layers.Dense', 'Dense', (['params.num_labels'], {'activation': '"""softmax"""', 'name': '"""predictions"""'}), "(params.num_labels, activation='softmax', name='predictions')\n", (4700, 4761), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((5981, 5990), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (5988, 5990), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((6035, 6056), 'keras.layers.Activation', 'Activation', (['"""softmax"""'], {}), "('softmax')\n", (6045, 6056), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((6640, 6683), 'numpy.roll', 'np.roll', (['kernels_views', 'kernels_views_holes'], {}), '(kernels_views, kernels_views_holes)\n', (6647, 6683), True, 'import numpy as np\n'), ((12396, 12450), 'keras.layers.ConvLSTM2D', 'ConvLSTM2D', (['(128)', '(3)'], {'return_sequences': '(True)', 'dropout': '(0.5)'}), '(128, 3, return_sequences=True, dropout=0.5)\n', (12406, 12450), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((12472, 12541), 'keras.layers.ConvLSTM2D', 'ConvLSTM2D', (['params.num_labels', '(3)'], {'return_sequences': '(False)', 'dropout': '(0.5)'}), '(params.num_labels, 3, return_sequences=False, dropout=0.5)\n', (12482, 12541), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((12563, 12572), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (12570, 12572), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((12593, 12625), 'keras.layers.Activation', 'Activation', ([], {'activation': '"""softmax"""'}), "(activation='softmax')\n", (12603, 12625), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((15323, 15360), 'copy.copy', 'copy.copy', (['label_to_idx[random_label]'], {}), '(label_to_idx[random_label])\n', (15332, 15360), False, 'import copy\n'), ((15382, 15432), 'random.shuffle', 'random.shuffle', (['running_label_to_idx[random_label]'], {}), '(running_label_to_idx[random_label])\n', (15396, 15432), False, 'import random\n'), ((19506, 19519), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (19512, 19519), True, 'import numpy as np\n'), ((19879, 19904), 'numpy.array', 'np.array', (['metadata[19:27]'], {}), '(metadata[19:27])\n', (19887, 19904), True, 'import numpy as np\n'), ((27978, 28076), 'cv2.warpAffine', 'cv2.warpAffine', (['img', 'M', '(target_img_size, target_img_size)'], {'borderMode': 'cv2.BORDER_REFLECT_101'}), '(img, M, (target_img_size, target_img_size), borderMode=cv2.\n BORDER_REFLECT_101)\n', (27992, 28076), False, 'import cv2\n'), ((31413, 31450), 'copy.copy', 'copy.copy', (['label_to_idx[random_label]'], {}), '(label_to_idx[random_label])\n', (31422, 31450), False, 'import copy\n'), ((31472, 31522), 'random.shuffle', 'random.shuffle', (['running_label_to_idx[random_label]'], {}), '(running_label_to_idx[random_label])\n', (31486, 31522), False, 'import random\n'), ((6277, 6333), 'numpy.linspace', 'np.linspace', (['params.views', '(1)', 'down_convs'], {'dtype': 'np.int32'}), '(params.views, 1, down_convs, dtype=np.int32)\n', (6288, 6333), True, 'import numpy as np\n'), ((6727, 6795), 'numpy.linspace', 'np.linspace', (['conv_features_grid_shape', '(1)', 'down_convs'], {'dtype': 'np.int32'}), '(conv_features_grid_shape, 1, down_convs, dtype=np.int32)\n', (6738, 6795), True, 'import numpy as np\n'), ((8779, 8788), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (8786, 8788), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((12739, 12842), 'keras.layers.GRU', 'GRU', (['(128)'], {'return_sequences': '(True)', 'input_shape': "(codesStats['max_temporal'], layerLength)", 'dropout': '(0.5)'}), "(128, return_sequences=True, input_shape=(codesStats['max_temporal'],\n layerLength), dropout=0.5)\n", (12742, 12842), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((12859, 12962), 'keras.layers.GRU', 'GRU', (['(128)'], {'return_sequences': '(True)', 'input_shape': "(codesStats['max_temporal'], layerLength)", 'dropout': '(0.5)'}), "(128, return_sequences=True, input_shape=(codesStats['max_temporal'],\n layerLength), dropout=0.5)\n", (12862, 12962), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((12979, 13047), 'keras.layers.GRU', 'GRU', (['params.num_labels'], {'activation': '"""softmax"""', 'return_sequences': '(False)'}), "(params.num_labels, activation='softmax', return_sequences=False)\n", (12982, 13047), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((16201, 16218), 'numpy.argmax', 'np.argmax', (['_label'], {}), '(_label)\n', (16210, 16218), True, 'import numpy as np\n'), ((16222, 16238), 'numpy.argmax', 'np.argmax', (['label'], {}), '(label)\n', (16231, 16238), True, 'import numpy as np\n'), ((13094, 13219), 'keras.layers.Reshape', 'Reshape', ([], {'target_shape': "(codesStats['max_temporal'], layerLength, 1)", 'input_shape': "(codesStats['max_temporal'], layerLength)"}), "(target_shape=(codesStats['max_temporal'], layerLength, 1),\n input_shape=(codesStats['max_temporal'], layerLength))\n", (13101, 13219), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((13236, 13295), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(1024)', 'kernel_size': '(1, 1)', 'activation': '"""relu"""'}), "(filters=1024, kernel_size=(1, 1), activation='relu')\n", (13242, 13295), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((13318, 13377), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(2048)', 'kernel_size': '(1, 1)', 'activation': '"""relu"""'}), "(filters=2048, kernel_size=(1, 1), activation='relu')\n", (13324, 13377), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((13400, 13459), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(4096)', 'kernel_size': '(1, 1)', 'activation': '"""relu"""'}), "(filters=4096, kernel_size=(1, 1), activation='relu')\n", (13406, 13459), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((13482, 13554), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': "(codesStats['max_temporal'], 1)", 'padding': '"""valid"""'}), "(pool_size=(codesStats['max_temporal'], 1), padding='valid')\n", (13494, 13554), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((13575, 13584), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (13582, 13584), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((13605, 13634), 'keras.layers.Dense', 'Dense', (['(512)'], {'activation': '"""relu"""'}), "(512, activation='relu')\n", (13610, 13634), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((13655, 13701), 'keras.layers.Dense', 'Dense', (['params.num_labels'], {'activation': '"""softmax"""'}), "(params.num_labels, activation='softmax')\n", (13660, 13701), False, 'from keras.layers import Dense, Input, Flatten, Dropout, LSTM, GRU, concatenate, add, Reshape, Conv2D, Conv1D, MaxPooling2D, ConvLSTM2D, Activation, BatchNormalization, Permute, LocallyConnected1D, ConvLSTM2D, Conv3D\n'), ((34744, 34760), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (34758, 34760), True, 'import numpy as np\n'), ((6932, 6968), 'numpy.log2', 'np.log2', (['conv_features_filters_shape'], {}), '(conv_features_filters_shape)\n', (6939, 6968), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 2 14:45:30 2018
@author: <NAME>
"""
from scipy import optimize
from scipy import stats
import numpy as np
class SuPP:
def __init__(self,k = 1,options=None):
if options is None:
options = {'un_classes':0,
'nr_classes':0,#comes from the data
'N':0,#comes from the dava
'M':0,#comes from the data
'n':100,
'orth_weight':64,#2*np.log2(3)
'discrete_entropy':False,
'bw_method':'scott',
'optimization':{'minmethod' : 'COBYLA','Temp':1000,'disp':True,'niter':200,}
}
self.k = k#number of latent components
self.opts = options
self.minmethod = self.opts['optimization']['minmethod']
if self.opts['bw_method'] is None:
self.opts['bw_method'] = 'scott'
if self.opts['optimization']['display'] is None:
self.opts['optimization']['display'] = False
if self.opts['optimization']['niter'] is None:
self.opts['optimization']['niter'] = 100
self.g = []
def pursuit(self,X,y,w,X0=None):
k = self.k
bnds = ()
N,M = np.shape(X)
CLASSES = np.shape(np.unique(y))
if self.opts['M'] == 0 and M>0:
self.opts['M'] = M
if self.opts['N'] == 0 and N>0:
self.opts['N'] = N
if self.opts['nr_classes'] == 0 and CLASSES>0:
self.opts['nr_classes'] = CLASSES
for j in range(self.opts['M']):
bnds = (bnds) + ((-1,1),)
kwarg = {'method':self.minmethod,'bounds':bnds}
self.g = np.zeros([k,self.opts['M']])
for j in range(k):
self.opts['j'] = j
if X0 is None:
x0 = np.random.rand(1,self.opts['M'])
else:
x0 = X0[j,:]
x0 = x0/np.linalg.norm(x0)
res = optimize.basinhopping(lambda x: self.objectFun(x,y,X,w,self.opts), x0, T = self.opts['optimization']['Temp'], disp=self.opts['optimization']['display'], minimizer_kwargs = kwarg,niter=self.opts['optimization']['niter'])
if self.opts['optimization']['display'] == True:
print(res)
self.g[j,:] = res.x/np.linalg.norm(res.x)
self.scores = self.getScores(X)
return self.g
def objectFun(self,x,Y,X,w,opts):
k = self.g
n = opts['j']
k[n,:] = x/np.linalg.norm(x)#append the new coordinate
J = 0
O = 0#initializing orthogonality
Xk = self.projectVect(X,k[n,:])
pts = np.linspace(np.nanmin(Xk),np.nanmax(Xk),opts['n'])
Hx = 0
Mix = np.zeros([1,opts['n']])
bw = opts['bw_method']
if self.opts['discrete_entropy'] == True:
for ids in range(opts['nr_classes']):
f,_ = np.histogram(Xk[Y == opts['un_classes'][ids]],bins = opts['n'],range=[pts[0],pts[-1]])
f = f/np.sum(f)
Hx = Hx - w[ids]*np.nansum(f[f>0]*np.log2(f[f>0]))
Mix = Mix + w[ids]*f
Mix,kk = np.histogram(Xk,bins = opts['n'],range=[pts[0],pts[-1]])
Mix = Mix/np.sum(Mix)
Hmix = -np.sum(Mix[Mix>0]*np.log2(Mix[Mix>0]))
else:
for ids in range(opts['nr_classes']):
xk = Xk[Y == opts['un_classes'][ids]]
KernelD = stats.gaussian_kde(xk[~np.isnan(xk)],bw_method = bw)
f = KernelD.evaluate(pts)#
# making discretization of KDS
Mix = Mix + w[ids]*f
Fx = f#(f[0:-1] + 0.5*np.diff(f))
Fx = Fx/np.sum(Fx)#
Hx = Hx - w[ids]*(np.sum(Fx[Fx>0]*np.log2(Fx[Fx>0])))
#
Fmix = Mix#(Mix[0,0:-1] + 0.5*np.diff(Mix))
Fmix = Fmix/np.sum(Fmix)
Hmix = -(np.sum(Fmix[Fmix>0]*np.log2(Fmix[Fmix>0])))
J = Hmix - Hx
if n>0:
D = n+1
u = np.ones([D,D],dtype=bool)
e = np.eye(D,dtype=bool)
O = (2/(D*(D-1)))*np.sum(np.abs(np.dot(k[0:D,:],k[0:D,:].T)[np.triu((u!=e))]))
Cost = (1-J/self.opts['epsilon'])**2 + self.opts['orth_weight']*O**2#
else:
Cost = (1-J/self.opts['epsilon'])**2
return Cost
def projectVect(self,X,g):
N = X.shape[0]
T = np.repeat([g],N,0)
return np.nansum(X*T,1)/np.linalg.norm(g)**2
def getScores(self,X,g = None):
if g is None:
g = self.g
n = X.shape[0]
k = g.shape[0]
Scores = []
for i in range(k):
Scores.append(self.projectVect(X,g[i,:]))
if g is None:
self.scores = np.array(Scores).T
return np.array(Scores).T
def gramSchmidt(self,g, row_vecs=True, norm = True):
if not row_vecs:
g = g.T
y = g[0:1,:].copy()
for i in range(1, g.shape[0]):
proj = np.diag((g[i,:].dot(y.T)/np.linalg.norm(y,axis=1)**2).flat).dot(y)
y = np.vstack((y, g[i,:] - proj.sum(0)))
if norm:
y = np.diag(1/np.linalg.norm(y,axis=1)).dot(y)
if row_vecs:
return y
else:
return y.T
def relativeGroupDist(self,Y,X=None):
if self.scores is None and X is not None:
Scores = self.getScores(X)
elif self.scores is None and X is None:
print("Error! the Scores are not set and the data was not passed.\nPlease Specify the data X or calculate the scores first using getScores(Data) method")
elif X is not None and self.Scores is not None:
print("Warning! Data was passed with the previously calculated attribute Scores!\nRecalculating Scores")
Scores = self.getScores(X)
else:
Scores = self.scores
RelGD = []
for i in range(Scores.shape[1]):
Quant = []
D = 0
for c in range(self.opts['nr_classes']):
Quant.append({'5p':np.nanquantile(Scores[Y == self.opts['un_classes'][c],i],0.05),
'50p':np.nanquantile(Scores[Y == self.opts['un_classes'][c],i],0.5),
'95p':np.nanquantile(Scores[Y == self.opts['un_classes'][c],i],0.95)})
MinEntry = min(Quant,key = lambda x: x['5p'])
MaxEntry = max(Quant,key = lambda x: x['5p'])
for item in Quant:
if item == MinEntry:
D += np.abs(item['95p'] - item['50p'])
elif item == MaxEntry:
D += np.abs(item['50p'] - item['5p'])
else:
D += np.abs(item['95p'] - item['5p'])
RelGD.append((MaxEntry['50p']-MinEntry['50p'])/D)
return RelGD
| [
"numpy.sum",
"numpy.abs",
"numpy.triu",
"numpy.ones",
"numpy.isnan",
"numpy.shape",
"numpy.histogram",
"numpy.linalg.norm",
"numpy.unique",
"numpy.repeat",
"numpy.nansum",
"numpy.log2",
"numpy.dot",
"numpy.nanmax",
"numpy.nanquantile",
"numpy.zeros",
"numpy.nanmin",
"numpy.array",
... | [((1287, 1298), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (1295, 1298), True, 'import numpy as np\n'), ((1760, 1789), 'numpy.zeros', 'np.zeros', (["[k, self.opts['M']]"], {}), "([k, self.opts['M']])\n", (1768, 1789), True, 'import numpy as np\n'), ((2872, 2896), 'numpy.zeros', 'np.zeros', (["[1, opts['n']]"], {}), "([1, opts['n']])\n", (2880, 2896), True, 'import numpy as np\n'), ((4682, 4702), 'numpy.repeat', 'np.repeat', (['[g]', 'N', '(0)'], {}), '([g], N, 0)\n', (4691, 4702), True, 'import numpy as np\n'), ((1326, 1338), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (1335, 1338), True, 'import numpy as np\n'), ((2606, 2623), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {}), '(x)\n', (2620, 2623), True, 'import numpy as np\n'), ((2804, 2817), 'numpy.nanmin', 'np.nanmin', (['Xk'], {}), '(Xk)\n', (2813, 2817), True, 'import numpy as np\n'), ((2818, 2831), 'numpy.nanmax', 'np.nanmax', (['Xk'], {}), '(Xk)\n', (2827, 2831), True, 'import numpy as np\n'), ((3333, 3390), 'numpy.histogram', 'np.histogram', (['Xk'], {'bins': "opts['n']", 'range': '[pts[0], pts[-1]]'}), "(Xk, bins=opts['n'], range=[pts[0], pts[-1]])\n", (3345, 3390), True, 'import numpy as np\n'), ((4283, 4310), 'numpy.ones', 'np.ones', (['[D, D]'], {'dtype': 'bool'}), '([D, D], dtype=bool)\n', (4290, 4310), True, 'import numpy as np\n'), ((4325, 4346), 'numpy.eye', 'np.eye', (['D'], {'dtype': 'bool'}), '(D, dtype=bool)\n', (4331, 4346), True, 'import numpy as np\n'), ((4716, 4735), 'numpy.nansum', 'np.nansum', (['(X * T)', '(1)'], {}), '(X * T, 1)\n', (4725, 4735), True, 'import numpy as np\n'), ((5064, 5080), 'numpy.array', 'np.array', (['Scores'], {}), '(Scores)\n', (5072, 5080), True, 'import numpy as np\n'), ((1895, 1928), 'numpy.random.rand', 'np.random.rand', (['(1)', "self.opts['M']"], {}), "(1, self.opts['M'])\n", (1909, 1928), True, 'import numpy as np\n'), ((1995, 2013), 'numpy.linalg.norm', 'np.linalg.norm', (['x0'], {}), '(x0)\n', (2009, 2013), True, 'import numpy as np\n'), ((2384, 2405), 'numpy.linalg.norm', 'np.linalg.norm', (['res.x'], {}), '(res.x)\n', (2398, 2405), True, 'import numpy as np\n'), ((3061, 3153), 'numpy.histogram', 'np.histogram', (["Xk[Y == opts['un_classes'][ids]]"], {'bins': "opts['n']", 'range': '[pts[0], pts[-1]]'}), "(Xk[Y == opts['un_classes'][ids]], bins=opts['n'], range=[pts[0\n ], pts[-1]])\n", (3073, 3153), True, 'import numpy as np\n'), ((3412, 3423), 'numpy.sum', 'np.sum', (['Mix'], {}), '(Mix)\n', (3418, 3423), True, 'import numpy as np\n'), ((4091, 4103), 'numpy.sum', 'np.sum', (['Fmix'], {}), '(Fmix)\n', (4097, 4103), True, 'import numpy as np\n'), ((4733, 4750), 'numpy.linalg.norm', 'np.linalg.norm', (['g'], {}), '(g)\n', (4747, 4750), True, 'import numpy as np\n'), ((5030, 5046), 'numpy.array', 'np.array', (['Scores'], {}), '(Scores)\n', (5038, 5046), True, 'import numpy as np\n'), ((3170, 3179), 'numpy.sum', 'np.sum', (['f'], {}), '(f)\n', (3176, 3179), True, 'import numpy as np\n'), ((3896, 3906), 'numpy.sum', 'np.sum', (['Fx'], {}), '(Fx)\n', (3902, 3906), True, 'import numpy as np\n'), ((6864, 6897), 'numpy.abs', 'np.abs', (["(item['95p'] - item['50p'])"], {}), "(item['95p'] - item['50p'])\n", (6870, 6897), True, 'import numpy as np\n'), ((3462, 3483), 'numpy.log2', 'np.log2', (['Mix[Mix > 0]'], {}), '(Mix[Mix > 0])\n', (3469, 3483), True, 'import numpy as np\n'), ((4164, 4187), 'numpy.log2', 'np.log2', (['Fmix[Fmix > 0]'], {}), '(Fmix[Fmix > 0])\n', (4171, 4187), True, 'import numpy as np\n'), ((6391, 6455), 'numpy.nanquantile', 'np.nanquantile', (["Scores[Y == self.opts['un_classes'][c], i]", '(0.05)'], {}), "(Scores[Y == self.opts['un_classes'][c], i], 0.05)\n", (6405, 6455), True, 'import numpy as np\n'), ((6491, 6554), 'numpy.nanquantile', 'np.nanquantile', (["Scores[Y == self.opts['un_classes'][c], i]", '(0.5)'], {}), "(Scores[Y == self.opts['un_classes'][c], i], 0.5)\n", (6505, 6554), True, 'import numpy as np\n'), ((6590, 6654), 'numpy.nanquantile', 'np.nanquantile', (["Scores[Y == self.opts['un_classes'][c], i]", '(0.95)'], {}), "(Scores[Y == self.opts['un_classes'][c], i], 0.95)\n", (6604, 6654), True, 'import numpy as np\n'), ((6962, 6994), 'numpy.abs', 'np.abs', (["(item['50p'] - item['5p'])"], {}), "(item['50p'] - item['5p'])\n", (6968, 6994), True, 'import numpy as np\n'), ((7042, 7074), 'numpy.abs', 'np.abs', (["(item['95p'] - item['5p'])"], {}), "(item['95p'] - item['5p'])\n", (7048, 7074), True, 'import numpy as np\n'), ((3666, 3678), 'numpy.isnan', 'np.isnan', (['xk'], {}), '(xk)\n', (3674, 3678), True, 'import numpy as np\n'), ((4402, 4432), 'numpy.dot', 'np.dot', (['k[0:D, :]', 'k[0:D, :].T'], {}), '(k[0:D, :], k[0:D, :].T)\n', (4408, 4432), True, 'import numpy as np\n'), ((4430, 4445), 'numpy.triu', 'np.triu', (['(u != e)'], {}), '(u != e)\n', (4437, 4445), True, 'import numpy as np\n'), ((5434, 5459), 'numpy.linalg.norm', 'np.linalg.norm', (['y'], {'axis': '(1)'}), '(y, axis=1)\n', (5448, 5459), True, 'import numpy as np\n'), ((3246, 3263), 'numpy.log2', 'np.log2', (['f[f > 0]'], {}), '(f[f > 0])\n', (3253, 3263), True, 'import numpy as np\n'), ((3973, 3992), 'numpy.log2', 'np.log2', (['Fx[Fx > 0]'], {}), '(Fx[Fx > 0])\n', (3980, 3992), True, 'import numpy as np\n'), ((5296, 5321), 'numpy.linalg.norm', 'np.linalg.norm', (['y'], {'axis': '(1)'}), '(y, axis=1)\n', (5310, 5321), True, 'import numpy as np\n')] |
from typing import Any, Dict
import numpy as np
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
from module.detector.Detector import Detector
class ArimaDetector(Detector):
def __init__(self, dataset: pd.DataFrame, ground_truth_outliers: np.ndarray,
configuration_name: str, ) -> None:
super().__init__(dataset, ground_truth_outliers, configuration_name)
def detect(self, params: Dict[str, Any]) -> None:
threshold = params["threshold"]
del params["threshold"]
x = self.dataset.iloc[:, 1]
model = ARIMA(x, **params).fit()
err = model.resid ** 2
self.outliers_array = np.array(err > threshold * err.std(), dtype=np.int8)
self.outlier_indexes = np.argwhere(self.outliers_array).squeeze()
| [
"numpy.argwhere",
"statsmodels.tsa.arima.model.ARIMA"
] | [((587, 605), 'statsmodels.tsa.arima.model.ARIMA', 'ARIMA', (['x'], {}), '(x, **params)\n', (592, 605), False, 'from statsmodels.tsa.arima.model import ARIMA\n'), ((757, 789), 'numpy.argwhere', 'np.argwhere', (['self.outliers_array'], {}), '(self.outliers_array)\n', (768, 789), True, 'import numpy as np\n')] |
# This source code is part of the Biotite package and is distributed
# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further
# information.
import numpy as np
import pytest
import biotite.sequence as seq
import biotite.sequence.align as align
K = 3
@pytest.fixture
def kmer_alphabet():
return align.KmerAlphabet(seq.ProteinSequence.alphabet, K)
np.random.seed(0)
N = 10
L = 30
@pytest.mark.parametrize(
"ref_split_kmer_code",
# Test for single instances as input
list(np.random.randint(len(seq.ProteinSequence.alphabet), size=(N, K))) +
# Test for multiple instances as input
list(np.random.randint(len(seq.ProteinSequence.alphabet), size=(N, L, K)))
)
def test_fuse_and_split(kmer_alphabet, ref_split_kmer_code):
"""
Check if :meth:`fuse()` and its reverse counterpart :meth:`split()`
work properly by using them back and forth on random input.
"""
fused = kmer_alphabet.fuse(ref_split_kmer_code)
test_split_kmer_code = kmer_alphabet.split(fused)
assert test_split_kmer_code.tolist() == ref_split_kmer_code.tolist()
np.random.seed(0)
N = 10
@pytest.mark.parametrize(
"split_kmer_code",
np.random.randint(len(seq.ProteinSequence.alphabet), size=(N, K))
)
def test_encode_and_decode(kmer_alphabet, split_kmer_code):
"""
Check if :meth:`encode()` and its reverse counterpart
:meth:`decode()` work properly by using them back and forth on
random input.
"""
alph = seq.ProteinSequence.alphabet
ref_kmer_symbol = alph.decode_multiple(split_kmer_code)
kmer_code = kmer_alphabet.encode(ref_kmer_symbol)
test_kmer_symbol = kmer_alphabet.decode(kmer_code)
assert test_kmer_symbol.tolist() == ref_kmer_symbol.tolist()
def test_create_kmers(kmer_alphabet):
"""
Test :meth:`create_kmers()` against repetitive use of
:meth:`fuse()`, which rely on two different implementations.
The input sequence code is randomly created.
"""
np.random.seed(0)
LENGTH = 100
seq_code = np.random.randint(
len(seq.ProteinSequence.alphabet), size=LENGTH, dtype=np.uint8
)
ref_kmers = [
kmer_alphabet.fuse(seq_code[i : i + kmer_alphabet.k])
for i in range(len(seq_code) - kmer_alphabet.k + 1)
]
test_kmers = kmer_alphabet.create_kmers(seq_code)
assert test_kmers.tolist() == ref_kmers | [
"biotite.sequence.align.KmerAlphabet",
"numpy.random.seed"
] | [((372, 389), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (386, 389), True, 'import numpy as np\n'), ((1099, 1116), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (1113, 1116), True, 'import numpy as np\n'), ((317, 368), 'biotite.sequence.align.KmerAlphabet', 'align.KmerAlphabet', (['seq.ProteinSequence.alphabet', 'K'], {}), '(seq.ProteinSequence.alphabet, K)\n', (335, 368), True, 'import biotite.sequence.align as align\n'), ((1975, 1992), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (1989, 1992), True, 'import numpy as np\n')] |
"""
Join
=====
Some examples of how joining works.
"""
import numpy as np
from matplotlib import pyplot as plt
import WrightTools as wt
a = wt.data.Data(name="a")
b = wt.data.Data(name="b")
a.create_variable("x", np.linspace(0, 10, 51)[:, None])
b.create_variable("x", np.linspace(5, 15, 51)[:, None])
a.create_variable("y", np.linspace(0, 10, 51)[None, :])
b.create_variable("y", np.linspace(0, 10, 51)[None, :])
a.create_channel("z", np.sin(a.x[:]) * np.cos(a.y[:]) + 1)
b.create_channel("z", 5 * np.exp(-((b.x[:] - 10) ** 2)) * np.exp(-((b.y[:] - 5) ** 2)) + 1)
a.transform("x", "y")
b.transform("x", "y")
first = wt.data.join([a, b], name="first")
last = wt.data.join([a, b], method="last", name="last")
min = wt.data.join([a, b], method="min", name="min")
max = wt.data.join([a, b], method="max", name="max")
sum = wt.data.join([a, b], method="sum", name="sum")
mean = wt.data.join([a, b], method="mean", name="mean")
# Plot the splits in columns
fig, gs = wt.artists.create_figure(nrows=4, cols=[1, 1])
for i, da in enumerate([a, b, first, last, min, max, sum, mean]):
ax = plt.subplot(gs[i])
ax.pcolor(da, vmin=0, vmax=6)
wt.artists.corner_text(da.natural_name, ax=ax)
ax.set_xlim(first.axes[0].min(), first.axes[0].max())
ax.set_ylim(first.axes[1].min(), first.axes[1].max())
wt.artists.set_fig_labels(xlabel=a.axes[0].label, ylabel=a.axes[1].label)
| [
"matplotlib.pyplot.subplot",
"WrightTools.artists.corner_text",
"WrightTools.artists.create_figure",
"WrightTools.data.join",
"WrightTools.data.Data",
"numpy.sin",
"numpy.exp",
"numpy.linspace",
"WrightTools.artists.set_fig_labels",
"numpy.cos"
] | [((142, 164), 'WrightTools.data.Data', 'wt.data.Data', ([], {'name': '"""a"""'}), "(name='a')\n", (154, 164), True, 'import WrightTools as wt\n'), ((169, 191), 'WrightTools.data.Data', 'wt.data.Data', ([], {'name': '"""b"""'}), "(name='b')\n", (181, 191), True, 'import WrightTools as wt\n'), ((622, 656), 'WrightTools.data.join', 'wt.data.join', (['[a, b]'], {'name': '"""first"""'}), "([a, b], name='first')\n", (634, 656), True, 'import WrightTools as wt\n'), ((664, 712), 'WrightTools.data.join', 'wt.data.join', (['[a, b]'], {'method': '"""last"""', 'name': '"""last"""'}), "([a, b], method='last', name='last')\n", (676, 712), True, 'import WrightTools as wt\n'), ((719, 765), 'WrightTools.data.join', 'wt.data.join', (['[a, b]'], {'method': '"""min"""', 'name': '"""min"""'}), "([a, b], method='min', name='min')\n", (731, 765), True, 'import WrightTools as wt\n'), ((772, 818), 'WrightTools.data.join', 'wt.data.join', (['[a, b]'], {'method': '"""max"""', 'name': '"""max"""'}), "([a, b], method='max', name='max')\n", (784, 818), True, 'import WrightTools as wt\n'), ((825, 871), 'WrightTools.data.join', 'wt.data.join', (['[a, b]'], {'method': '"""sum"""', 'name': '"""sum"""'}), "([a, b], method='sum', name='sum')\n", (837, 871), True, 'import WrightTools as wt\n'), ((879, 927), 'WrightTools.data.join', 'wt.data.join', (['[a, b]'], {'method': '"""mean"""', 'name': '"""mean"""'}), "([a, b], method='mean', name='mean')\n", (891, 927), True, 'import WrightTools as wt\n'), ((968, 1014), 'WrightTools.artists.create_figure', 'wt.artists.create_figure', ([], {'nrows': '(4)', 'cols': '[1, 1]'}), '(nrows=4, cols=[1, 1])\n', (992, 1014), True, 'import WrightTools as wt\n'), ((1311, 1384), 'WrightTools.artists.set_fig_labels', 'wt.artists.set_fig_labels', ([], {'xlabel': 'a.axes[0].label', 'ylabel': 'a.axes[1].label'}), '(xlabel=a.axes[0].label, ylabel=a.axes[1].label)\n', (1336, 1384), True, 'import WrightTools as wt\n'), ((1090, 1108), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[i]'], {}), '(gs[i])\n', (1101, 1108), True, 'from matplotlib import pyplot as plt\n'), ((1147, 1193), 'WrightTools.artists.corner_text', 'wt.artists.corner_text', (['da.natural_name'], {'ax': 'ax'}), '(da.natural_name, ax=ax)\n', (1169, 1193), True, 'import WrightTools as wt\n'), ((215, 237), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(51)'], {}), '(0, 10, 51)\n', (226, 237), True, 'import numpy as np\n'), ((271, 293), 'numpy.linspace', 'np.linspace', (['(5)', '(15)', '(51)'], {}), '(5, 15, 51)\n', (282, 293), True, 'import numpy as np\n'), ((327, 349), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(51)'], {}), '(0, 10, 51)\n', (338, 349), True, 'import numpy as np\n'), ((383, 405), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(51)'], {}), '(0, 10, 51)\n', (394, 405), True, 'import numpy as np\n'), ((439, 453), 'numpy.sin', 'np.sin', (['a.x[:]'], {}), '(a.x[:])\n', (445, 453), True, 'import numpy as np\n'), ((456, 470), 'numpy.cos', 'np.cos', (['a.y[:]'], {}), '(a.y[:])\n', (462, 470), True, 'import numpy as np\n'), ((534, 560), 'numpy.exp', 'np.exp', (['(-(b.y[:] - 5) ** 2)'], {}), '(-(b.y[:] - 5) ** 2)\n', (540, 560), True, 'import numpy as np\n'), ((502, 529), 'numpy.exp', 'np.exp', (['(-(b.x[:] - 10) ** 2)'], {}), '(-(b.x[:] - 10) ** 2)\n', (508, 529), True, 'import numpy as np\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.