code
stringlengths 31
1.05M
| apis
list | extract_api
stringlengths 97
1.91M
|
---|---|---|
"""
Move object from one visual marker to another
"""
import sys
import cv2
import numpy as np
import obj_loader
from utils import (calculate_dist_corners, get_camera_params,
get_matrix, load_ref_images, render, get_homographies_contour)
if __name__ == "__main__":
OBJ_PATH = sys.argv[1]
OBJ = obj_loader.OBJ(OBJ_PATH, swapyz=True)
REF_IMAGES, REF_DSC = load_ref_images()
VID_FEED = cv2.VideoCapture(-1)
CAM_MAT = get_camera_params()
REACHED_X, REACHED_Y = 0, 0
MATCH_DATA = [None, None]
CORNER_DATA = [None, None]
while True:
RET, FRAME = VID_FEED.read()
if not RET:
print("Unable to capture video")
sys.exit()
MATCH_DATA, CORNER_DATA = get_homographies_contour(FRAME, REF_IMAGES, MATCH_DATA, CORNER_DATA)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
if MATCH_DATA[0] is not None and MATCH_DATA[1] is not None:
HOMOGRAPHY1 = MATCH_DATA[0]
HOMOGRAPHY2 = MATCH_DATA[1]
CORNER1 = CORNER_DATA[0]
CORNER2 = CORNER_DATA[1]
PROJ_MAT1, R, T = get_matrix(CAM_MAT, HOMOGRAPHY1)
DIST = calculate_dist_corners(CORNER1, CORNER2)
DIST_X = DIST[0]
DIST_Y = DIST[1]
STEP_X = DIST_X/40
STEP_Y = DIST_Y/40
if abs(REACHED_X) >= abs(DIST_X) or abs(REACHED_Y) >= abs(DIST_Y):
REACHED_X = 0
REACHED_Y = 0
else:
REACHED_X += STEP_X
REACHED_Y += STEP_Y
TRANS = np.array(
[[1, 0, REACHED_X], [0, 1, REACHED_Y], [0, 0, 1]])
PROJ_MAT1 = np.dot(TRANS, PROJ_MAT1)
FRAME = render(FRAME, OBJ, PROJ_MAT1, REF_IMAGES[0], False)
cv2.imshow("frame", FRAME)
else:
cv2.imshow("frame", FRAME)
VID_FEED.release()
cv2.destroyAllWindows()
|
[
"utils.get_camera_params",
"utils.get_matrix",
"cv2.waitKey",
"obj_loader.OBJ",
"utils.calculate_dist_corners",
"cv2.imshow",
"utils.load_ref_images",
"cv2.VideoCapture",
"utils.render",
"numpy.array",
"numpy.dot",
"utils.get_homographies_contour",
"cv2.destroyAllWindows",
"sys.exit"
] |
[((326, 363), 'obj_loader.OBJ', 'obj_loader.OBJ', (['OBJ_PATH'], {'swapyz': '(True)'}), '(OBJ_PATH, swapyz=True)\n', (340, 363), False, 'import obj_loader\n'), ((390, 407), 'utils.load_ref_images', 'load_ref_images', ([], {}), '()\n', (405, 407), False, 'from utils import calculate_dist_corners, get_camera_params, get_matrix, load_ref_images, render, get_homographies_contour\n'), ((423, 443), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(-1)'], {}), '(-1)\n', (439, 443), False, 'import cv2\n'), ((458, 477), 'utils.get_camera_params', 'get_camera_params', ([], {}), '()\n', (475, 477), False, 'from utils import calculate_dist_corners, get_camera_params, get_matrix, load_ref_images, render, get_homographies_contour\n'), ((1923, 1946), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1944, 1946), False, 'import cv2\n'), ((749, 817), 'utils.get_homographies_contour', 'get_homographies_contour', (['FRAME', 'REF_IMAGES', 'MATCH_DATA', 'CORNER_DATA'], {}), '(FRAME, REF_IMAGES, MATCH_DATA, CORNER_DATA)\n', (773, 817), False, 'from utils import calculate_dist_corners, get_camera_params, get_matrix, load_ref_images, render, get_homographies_contour\n'), ((703, 713), 'sys.exit', 'sys.exit', ([], {}), '()\n', (711, 713), False, 'import sys\n'), ((1139, 1171), 'utils.get_matrix', 'get_matrix', (['CAM_MAT', 'HOMOGRAPHY1'], {}), '(CAM_MAT, HOMOGRAPHY1)\n', (1149, 1171), False, 'from utils import calculate_dist_corners, get_camera_params, get_matrix, load_ref_images, render, get_homographies_contour\n'), ((1192, 1232), 'utils.calculate_dist_corners', 'calculate_dist_corners', (['CORNER1', 'CORNER2'], {}), '(CORNER1, CORNER2)\n', (1214, 1232), False, 'from utils import calculate_dist_corners, get_camera_params, get_matrix, load_ref_images, render, get_homographies_contour\n'), ((1605, 1664), 'numpy.array', 'np.array', (['[[1, 0, REACHED_X], [0, 1, REACHED_Y], [0, 0, 1]]'], {}), '([[1, 0, REACHED_X], [0, 1, REACHED_Y], [0, 0, 1]])\n', (1613, 1664), True, 'import numpy as np\n'), ((1706, 1730), 'numpy.dot', 'np.dot', (['TRANS', 'PROJ_MAT1'], {}), '(TRANS, PROJ_MAT1)\n', (1712, 1730), True, 'import numpy as np\n'), ((1751, 1802), 'utils.render', 'render', (['FRAME', 'OBJ', 'PROJ_MAT1', 'REF_IMAGES[0]', '(False)'], {}), '(FRAME, OBJ, PROJ_MAT1, REF_IMAGES[0], False)\n', (1757, 1802), False, 'from utils import calculate_dist_corners, get_camera_params, get_matrix, load_ref_images, render, get_homographies_contour\n'), ((1815, 1841), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'FRAME'], {}), "('frame', FRAME)\n", (1825, 1841), False, 'import cv2\n'), ((1868, 1894), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'FRAME'], {}), "('frame', FRAME)\n", (1878, 1894), False, 'import cv2\n'), ((830, 844), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (841, 844), False, 'import cv2\n')]
|
# Copyright (c) 2018 <NAME>, <NAME>
# All rights reserved.
#
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
import mSCM
import sys
import numpy as np
from numpy.random import choice
from numpy.random import seed
import random
nbr = int(sys.argv[1])
random.seed(nbr)
np.random.seed(nbr)
# change the following to point to the directory in which you have cloned the code repository
rootdir = "~/vcs/sigmasep"
# change the following to point to the directory in which you want to save the output
outdir = "/dev/shm/jmooij1/sigmasep"
# change the following to point to the directory in which clingo lives
clingodir = "/zfs/ivi/causality/opt/clingo-4.5.4-linux-x86_64/"
for nbr_do in range(6):
mSCM.sample_mSCM_run_all_and_save(
d=5,k=2,p=0.3,m=0,nbr=nbr,add_ind_noise_to_A=False,
add_ind_noise_to_W=True,
include_latent=True,
folderpath=outdir+"/mSCM_data/experiment_"+str(nbr_do)+"/",
AF=[np.tanh],SC=[1],NOI=['normal'],SD=[1],n=10000,
AL =[0.001],MUL=[1000],infty=1000,nbr_do=nbr_do,max_do=1,do_strategy=2,
clingodir=clingodir,
aspdir=rootdir+"/ASP/"
)
|
[
"numpy.random.seed",
"random.seed"
] |
[((305, 321), 'random.seed', 'random.seed', (['nbr'], {}), '(nbr)\n', (316, 321), False, 'import random\n'), ((322, 341), 'numpy.random.seed', 'np.random.seed', (['nbr'], {}), '(nbr)\n', (336, 341), True, 'import numpy as np\n')]
|
# 引入 sqlite 套件
import sqlite3
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
#定義資料庫位置
conn = sqlite3.connect('database.db')
db_connection = conn.cursor()
List_Ecg_Signal = [] ## 空列表
#t查詢數據
rows = db_connection.execute("SELECT serialno,time,length,date,ecg,qrs,beat,feature,measurement,marker,scale,parameter FROM Records;")
for row in rows:
# print ("serialno = ", row[0])
# print ("time = ", row[1])
# print ("length = ", row[2])
# print ("date = ", row[3])
# print ("ecg = ", np.frombuffer(row[4], dtype='<f4'),"\n")
# print ("qrs = ", row[5])
# print ("beat = ", row[6])
# print ("feature = ", row[7].hex())
# print ("measurement = ", row[8].hex())
# print ("marker = ", row[9].hex())
# print ("scale = ", row[10],"\n")
# print ("parameter = ", binascii.hexlify(row[11]))
# print("parameter = ",float.fromhex(row[11].hex()),"\n" )
# print("parameter = ", np.frombuffer(row[11], dtype=np.float32),"\n" )
List_Ecg_Signal.append(np.frombuffer(row[4], dtype='<f4'))
db_connection.close()
|
[
"numpy.frombuffer",
"sqlite3.connect"
] |
[((119, 149), 'sqlite3.connect', 'sqlite3.connect', (['"""database.db"""'], {}), "('database.db')\n", (134, 149), False, 'import sqlite3\n'), ((1028, 1062), 'numpy.frombuffer', 'np.frombuffer', (['row[4]'], {'dtype': '"""<f4"""'}), "(row[4], dtype='<f4')\n", (1041, 1062), True, 'import numpy as np\n')]
|
import copy
import cv2
import glob
import json
import numpy as np
import os
from .box_utils import compute_box_3d, boxes_to_corners_3d, get_size
from .rotation import convert_angle_axis_to_matrix3
from .taxonomy import class_names, ARKitDatasetConfig
def TrajStringToMatrix(traj_str):
""" convert traj_str into translation and rotation matrices
Args:
traj_str: A space-delimited file where each line represents a camera position at a particular timestamp.
The file has seven columns:
* Column 1: timestamp
* Columns 2-4: rotation (axis-angle representation in radians)
* Columns 5-7: translation (usually in meters)
Returns:
ts: translation matrix
Rt: rotation matrix
"""
# line=[float(x) for x in traj_str.split()]
# ts = line[0];
# R = cv2.Rodrigues(np.array(line[1:4]))[0];
# t = np.array(line[4:7]);
# Rt = np.concatenate((np.concatenate((R, t[:,np.newaxis]), axis=1), [[0.0,0.0,0.0,1.0]]), axis=0)
tokens = traj_str.split()
assert len(tokens) == 7
ts = tokens[0]
# Rotation in angle axis
angle_axis = [float(tokens[1]), float(tokens[2]), float(tokens[3])]
r_w_to_p = convert_angle_axis_to_matrix3(np.asarray(angle_axis))
# Translation
t_w_to_p = np.asarray([float(tokens[4]), float(tokens[5]), float(tokens[6])])
extrinsics = np.eye(4, 4)
extrinsics[:3, :3] = r_w_to_p
extrinsics[:3, -1] = t_w_to_p
Rt = np.linalg.inv(extrinsics)
return (ts, Rt)
def st2_camera_intrinsics(filename):
w, h, fx, fy, hw, hh = np.loadtxt(filename)
return np.asarray([[fx, 0, hw], [0, fy, hh], [0, 0, 1]])
def generate_point(
rgb_image,
depth_image,
intrinsic,
subsample=1,
world_coordinate=True,
pose=None,
):
"""Generate 3D point coordinates and related rgb feature
Args:
rgb_image: (h, w, 3) rgb
depth_image: (h, w) depth
intrinsic: (3, 3)
subsample: int
resize stride
world_coordinate: bool
pose: (4, 4) matrix
transfer from camera to world coordindate
Returns:
points: (N, 3) point cloud coordinates
in world-coordinates if world_coordinate==True
else in camera coordinates
rgb_feat: (N, 3) rgb feature of each point
"""
intrinsic_4x4 = np.identity(4)
intrinsic_4x4[:3, :3] = intrinsic
u, v = np.meshgrid(
range(0, depth_image.shape[1], subsample),
range(0, depth_image.shape[0], subsample),
)
d = depth_image[v, u]
d_filter = d != 0
mat = np.vstack(
(
u[d_filter] * d[d_filter],
v[d_filter] * d[d_filter],
d[d_filter],
np.ones_like(u[d_filter]),
)
)
new_points_3d = np.dot(np.linalg.inv(intrinsic_4x4), mat)[:3]
if world_coordinate:
new_points_3d_padding = np.vstack(
(new_points_3d, np.ones((1, new_points_3d.shape[1])))
)
world_coord_padding = np.dot(pose, new_points_3d_padding)
new_points_3d = world_coord_padding[:3]
rgb_feat = rgb_image[v, u][d_filter]
return new_points_3d.T, rgb_feat
def extract_gt(gt_fn):
"""extract original label data
Args:
gt_fn: str (file name of "annotation.json")
after loading, we got a dict with keys
'data', 'stats', 'comment', 'confirm', 'skipped'
['data']: a list of dict for bboxes, each dict has keys:
'uid', 'label', 'modelId', 'children', 'objectId',
'segments', 'hierarchy', 'isInGroup', 'labelType', 'attributes'
'label': str
'segments': dict for boxes
'centroid': list of float (x, y, z)?
'axesLengths': list of float (x, y, z)?
'normalizedAxes': list of float len()=9
'uid'
'comments':
'stats': ...
Returns:
skipped: bool
skipped or not
boxes_corners: (n, 8, 3) box corners
**world-coordinate**
centers: (n, 3)
**world-coordinate**
sizes: (n, 3) full-sizes (no halving!)
labels: list of str
uids: list of str
"""
gt = json.load(open(gt_fn, "r"))
skipped = gt['skipped']
if len(gt) == 0:
boxes_corners = np.zeros((0, 8, 3))
centers = np.zeros((0, 3))
sizes = np.zeros((0, 3))
labels, uids = [], []
return skipped, boxes_corners, centers, sizes, labels, uids
boxes_corners = []
centers = []
sizes = []
labels = []
uids = []
for data in gt['data']:
l = data["label"]
for delimiter in [" ", "-", "/"]:
l = l.replace(delimiter, "_")
if l not in class_names:
print("unknown category: %s" % l)
continue
rotmat = np.array(data["segments"]["obbAligned"]["normalizedAxes"]).reshape(
3, 3
)
center = np.array(data["segments"]["obbAligned"]["centroid"]).reshape(-1, 3)
size = np.array(data["segments"]["obbAligned"]["axesLengths"]).reshape(-1, 3)
box3d = compute_box_3d(size.reshape(3).tolist(), center, rotmat)
'''
Box corner order that we return is of the format below:
6 -------- 7
/| /|
5 -------- 4 .
| | | |
. 2 -------- 3
|/ |/
1 -------- 0
'''
boxes_corners.append(box3d.reshape(1, 8, 3))
size = np.array(get_size(box3d)).reshape(1, 3)
center = np.mean(box3d, axis=0).reshape(1, 3)
# boxes_corners.append(box3d.reshape(1, 8, 3))
centers.append(center)
sizes.append(size)
# labels.append(l)
labels.append(data["label"])
uids.append(data["uid"])
centers = np.concatenate(centers, axis=0)
sizes = np.concatenate(sizes, axis=0)
boxes_corners = np.concatenate(boxes_corners, axis=0)
return skipped, boxes_corners, centers, sizes, labels, uids
class TenFpsDataLoader(object):
def __init__(
self,
dataset_cfg,
class_names,
root_path=None,
gt_path=None,
logger=None,
frame_rate=1,
with_color_image=True,
subsample=2,
world_coordinate=True,
):
"""
Args:
dataset_cfg: EasyDict() with key
POINT_CLOUD_RANGE
POINT_FEATURE_ENCODING
DATA_PROCESSOR
class_names: list of str
root_path: path with all info for a scene_id
color, color_2det, depth, label, vote, ...
gt_path: xxx.json
just to get correct floor height
an2d_root: path to scene_id.json
or None
logger:
frame_rate: int
subsample: int
world_coordinate: bool
"""
self.root_path = root_path
# pipeline does box residual coding here
self.num_class = len(class_names)
self.dc = ARKitDatasetConfig()
depth_folder = os.path.join(self.root_path, "lowres_depth")
if not os.path.exists(depth_folder):
self.frame_ids = []
else:
depth_images = sorted(glob.glob(os.path.join(depth_folder, "*.png")))
self.frame_ids = [os.path.basename(x) for x in depth_images]
self.frame_ids = [x.split(".png")[0].split("_")[1] for x in self.frame_ids]
self.video_id = depth_folder.split('/')[-3]
self.frame_ids = [x for x in self.frame_ids]
self.frame_ids.sort()
self.intrinsics = {}
traj_file = os.path.join(self.root_path, 'lowres_wide.traj')
with open(traj_file) as f:
self.traj = f.readlines()
# convert traj to json dict
poses_from_traj = {}
for line in self.traj:
traj_timestamp = line.split(" ")[0]
poses_from_traj[f"{round(float(traj_timestamp), 3):.3f}"] = TrajStringToMatrix(line)[1].tolist()
if os.path.exists(traj_file):
# self.poses = json.load(open(traj_file))
self.poses = poses_from_traj
else:
self.poses = {}
# get intrinsics
for frame_id in self.frame_ids:
intrinsic_fn = os.path.join(self.root_path, "lowres_wide_intrinsics", f"{self.video_id}_{frame_id}.pincam")
if not os.path.exists(intrinsic_fn):
intrinsic_fn = os.path.join(self.root_path, "lowres_wide_intrinsics",
f"{self.video_id}_{float(frame_id) - 0.001:.3f}.pincam")
if not os.path.exists(intrinsic_fn):
intrinsic_fn = os.path.join(self.root_path, "lowres_wide_intrinsics",
f"{self.video_id}_{float(frame_id) + 0.001:.3f}.pincam")
if not os.path.exists(intrinsic_fn):
print("frame_id", frame_id)
print(intrinsic_fn)
self.intrinsics[frame_id] = st2_camera_intrinsics(intrinsic_fn)
# # intrinsic_fn = os.path.join(self.root_path, "camera.txt")
# intrinsic_fn = os.path.join(self.root_path, "color.pincam")
# if os.path.exists(intrinsic_fn):
# self.intrinsics = st2_camera_intrinsics(intrinsic_fn)
# else:
# self.intrinsics = None
self.frame_rate = frame_rate
self.subsample = subsample
self.with_color_image = with_color_image
self.world_coordinate = world_coordinate
if gt_path is not None and os.path.exists(gt_path):
skipped, gt_corners, gt_centers, gt_sizes, _, _ = extract_gt(gt_path)
self.gt_corners = gt_corners
self.gt_centers = gt_centers
self.gt_sizes = gt_sizes
else:
self.gt_corners = None
self.gt_centers = None
self.gt_sizes = None
def __iter__(self):
return self
def __len__(self):
return len(self.frame_ids)
def __getitem__(self, idx):
"""
Returns:
frame: a dict
{frame_id}: str
{depth}: (h, w)
{image}: (h, w)
{image_path}: str
{intrinsics}: np.array 3x3
{pose}: np.array 4x4
{pcd}: np.array (n, 3)
in world coordinate
{color}: (n, 3)
"""
frame_id = self.frame_ids[idx]
frame = {}
frame["frame_id"] = frame_id
fname = "{}_{}.png".format(self.video_id, frame_id)
# fname = "{}.png".format(frame_id)
depth_image_path = os.path.join(self.root_path, "lowres_depth", fname)
if not os.path.exists(depth_image_path):
print(depth_image_path)
image_path = os.path.join(self.root_path, "lowres_wide", fname)
if not os.path.exists(depth_image_path):
print(depth_image_path, "does not exist")
frame["depth"] = cv2.imread(depth_image_path, -1)
frame["image"] = cv2.imread(image_path)
frame["image_path"] = image_path
depth_height, depth_width = frame["depth"].shape
im_height, im_width, im_channels = frame["image"].shape
frame["intrinsics"] = copy.deepcopy(self.intrinsics[frame_id])
if str(frame_id) in self.poses.keys():
frame_pose = np.array(self.poses[str(frame_id)])
else:
for my_key in list(self.poses.keys()):
if abs(float(frame_id) - float(my_key)) < 0.005:
frame_pose = np.array(self.poses[str(my_key)])
frame["pose"] = copy.deepcopy(frame_pose)
im_height_scale = np.float(depth_height) / im_height
im_width_scale = np.float(depth_width) / im_width
if depth_height != im_height:
frame["image"] = np.zeros([depth_height, depth_width, 3]) # 288, 384, 3
frame["image"][48 : 48 + 192, 64 : 64 + 256, :] = cv2.imread(image_path)
(m, n, _) = frame["image"].shape
depth_image = frame["depth"] / 1000.0
rgb_image = frame["image"] / 255.0
pcd, rgb_feat = generate_point(
rgb_image,
depth_image,
frame["intrinsics"],
self.subsample,
self.world_coordinate,
frame_pose,
)
frame["pcd"] = pcd
frame["color"] = rgb_feat
return frame
|
[
"copy.deepcopy",
"numpy.ones_like",
"os.path.basename",
"numpy.asarray",
"numpy.zeros",
"numpy.identity",
"os.path.exists",
"numpy.float",
"numpy.ones",
"cv2.imread",
"numpy.mean",
"numpy.linalg.inv",
"numpy.loadtxt",
"numpy.array",
"numpy.dot",
"numpy.eye",
"os.path.join",
"numpy.concatenate"
] |
[((1363, 1375), 'numpy.eye', 'np.eye', (['(4)', '(4)'], {}), '(4, 4)\n', (1369, 1375), True, 'import numpy as np\n'), ((1453, 1478), 'numpy.linalg.inv', 'np.linalg.inv', (['extrinsics'], {}), '(extrinsics)\n', (1466, 1478), True, 'import numpy as np\n'), ((1565, 1585), 'numpy.loadtxt', 'np.loadtxt', (['filename'], {}), '(filename)\n', (1575, 1585), True, 'import numpy as np\n'), ((1597, 1646), 'numpy.asarray', 'np.asarray', (['[[fx, 0, hw], [0, fy, hh], [0, 0, 1]]'], {}), '([[fx, 0, hw], [0, fy, hh], [0, 0, 1]])\n', (1607, 1646), True, 'import numpy as np\n'), ((2341, 2355), 'numpy.identity', 'np.identity', (['(4)'], {}), '(4)\n', (2352, 2355), True, 'import numpy as np\n'), ((5908, 5939), 'numpy.concatenate', 'np.concatenate', (['centers'], {'axis': '(0)'}), '(centers, axis=0)\n', (5922, 5939), True, 'import numpy as np\n'), ((5952, 5981), 'numpy.concatenate', 'np.concatenate', (['sizes'], {'axis': '(0)'}), '(sizes, axis=0)\n', (5966, 5981), True, 'import numpy as np\n'), ((6002, 6039), 'numpy.concatenate', 'np.concatenate', (['boxes_corners'], {'axis': '(0)'}), '(boxes_corners, axis=0)\n', (6016, 6039), True, 'import numpy as np\n'), ((1222, 1244), 'numpy.asarray', 'np.asarray', (['angle_axis'], {}), '(angle_axis)\n', (1232, 1244), True, 'import numpy as np\n'), ((3004, 3039), 'numpy.dot', 'np.dot', (['pose', 'new_points_3d_padding'], {}), '(pose, new_points_3d_padding)\n', (3010, 3039), True, 'import numpy as np\n'), ((4359, 4378), 'numpy.zeros', 'np.zeros', (['(0, 8, 3)'], {}), '((0, 8, 3))\n', (4367, 4378), True, 'import numpy as np\n'), ((4397, 4413), 'numpy.zeros', 'np.zeros', (['(0, 3)'], {}), '((0, 3))\n', (4405, 4413), True, 'import numpy as np\n'), ((4430, 4446), 'numpy.zeros', 'np.zeros', (['(0, 3)'], {}), '((0, 3))\n', (4438, 4446), True, 'import numpy as np\n'), ((7180, 7224), 'os.path.join', 'os.path.join', (['self.root_path', '"""lowres_depth"""'], {}), "(self.root_path, 'lowres_depth')\n", (7192, 7224), False, 'import os\n'), ((7760, 7808), 'os.path.join', 'os.path.join', (['self.root_path', '"""lowres_wide.traj"""'], {}), "(self.root_path, 'lowres_wide.traj')\n", (7772, 7808), False, 'import os\n'), ((8147, 8172), 'os.path.exists', 'os.path.exists', (['traj_file'], {}), '(traj_file)\n', (8161, 8172), False, 'import os\n'), ((10782, 10833), 'os.path.join', 'os.path.join', (['self.root_path', '"""lowres_depth"""', 'fname'], {}), "(self.root_path, 'lowres_depth', fname)\n", (10794, 10833), False, 'import os\n'), ((10941, 10991), 'os.path.join', 'os.path.join', (['self.root_path', '"""lowres_wide"""', 'fname'], {}), "(self.root_path, 'lowres_wide', fname)\n", (10953, 10991), False, 'import os\n'), ((11121, 11153), 'cv2.imread', 'cv2.imread', (['depth_image_path', '(-1)'], {}), '(depth_image_path, -1)\n', (11131, 11153), False, 'import cv2\n'), ((11179, 11201), 'cv2.imread', 'cv2.imread', (['image_path'], {}), '(image_path)\n', (11189, 11201), False, 'import cv2\n'), ((11395, 11435), 'copy.deepcopy', 'copy.deepcopy', (['self.intrinsics[frame_id]'], {}), '(self.intrinsics[frame_id])\n', (11408, 11435), False, 'import copy\n'), ((11765, 11790), 'copy.deepcopy', 'copy.deepcopy', (['frame_pose'], {}), '(frame_pose)\n', (11778, 11790), False, 'import copy\n'), ((2721, 2746), 'numpy.ones_like', 'np.ones_like', (['u[d_filter]'], {}), '(u[d_filter])\n', (2733, 2746), True, 'import numpy as np\n'), ((2791, 2819), 'numpy.linalg.inv', 'np.linalg.inv', (['intrinsic_4x4'], {}), '(intrinsic_4x4)\n', (2804, 2819), True, 'import numpy as np\n'), ((7240, 7268), 'os.path.exists', 'os.path.exists', (['depth_folder'], {}), '(depth_folder)\n', (7254, 7268), False, 'import os\n'), ((8404, 8500), 'os.path.join', 'os.path.join', (['self.root_path', '"""lowres_wide_intrinsics"""', 'f"""{self.video_id}_{frame_id}.pincam"""'], {}), "(self.root_path, 'lowres_wide_intrinsics',\n f'{self.video_id}_{frame_id}.pincam')\n", (8416, 8500), False, 'import os\n'), ((9688, 9711), 'os.path.exists', 'os.path.exists', (['gt_path'], {}), '(gt_path)\n', (9702, 9711), False, 'import os\n'), ((10849, 10881), 'os.path.exists', 'os.path.exists', (['depth_image_path'], {}), '(depth_image_path)\n', (10863, 10881), False, 'import os\n'), ((11008, 11040), 'os.path.exists', 'os.path.exists', (['depth_image_path'], {}), '(depth_image_path)\n', (11022, 11040), False, 'import os\n'), ((11818, 11840), 'numpy.float', 'np.float', (['depth_height'], {}), '(depth_height)\n', (11826, 11840), True, 'import numpy as np\n'), ((11878, 11899), 'numpy.float', 'np.float', (['depth_width'], {}), '(depth_width)\n', (11886, 11899), True, 'import numpy as np\n'), ((11979, 12019), 'numpy.zeros', 'np.zeros', (['[depth_height, depth_width, 3]'], {}), '([depth_height, depth_width, 3])\n', (11987, 12019), True, 'import numpy as np\n'), ((12097, 12119), 'cv2.imread', 'cv2.imread', (['image_path'], {}), '(image_path)\n', (12107, 12119), False, 'import cv2\n'), ((2926, 2962), 'numpy.ones', 'np.ones', (['(1, new_points_3d.shape[1])'], {}), '((1, new_points_3d.shape[1]))\n', (2933, 2962), True, 'import numpy as np\n'), ((4887, 4945), 'numpy.array', 'np.array', (["data['segments']['obbAligned']['normalizedAxes']"], {}), "(data['segments']['obbAligned']['normalizedAxes'])\n", (4895, 4945), True, 'import numpy as np\n'), ((4999, 5051), 'numpy.array', 'np.array', (["data['segments']['obbAligned']['centroid']"], {}), "(data['segments']['obbAligned']['centroid'])\n", (5007, 5051), True, 'import numpy as np\n'), ((5082, 5137), 'numpy.array', 'np.array', (["data['segments']['obbAligned']['axesLengths']"], {}), "(data['segments']['obbAligned']['axesLengths'])\n", (5090, 5137), True, 'import numpy as np\n'), ((5646, 5668), 'numpy.mean', 'np.mean', (['box3d'], {'axis': '(0)'}), '(box3d, axis=0)\n', (5653, 5668), True, 'import numpy as np\n'), ((7428, 7447), 'os.path.basename', 'os.path.basename', (['x'], {}), '(x)\n', (7444, 7447), False, 'import os\n'), ((8516, 8544), 'os.path.exists', 'os.path.exists', (['intrinsic_fn'], {}), '(intrinsic_fn)\n', (8530, 8544), False, 'import os\n'), ((8752, 8780), 'os.path.exists', 'os.path.exists', (['intrinsic_fn'], {}), '(intrinsic_fn)\n', (8766, 8780), False, 'import os\n'), ((8988, 9016), 'os.path.exists', 'os.path.exists', (['intrinsic_fn'], {}), '(intrinsic_fn)\n', (9002, 9016), False, 'import os\n'), ((7360, 7395), 'os.path.join', 'os.path.join', (['depth_folder', '"""*.png"""'], {}), "(depth_folder, '*.png')\n", (7372, 7395), False, 'import os\n')]
|
#
# Copyright (c) 2021 Intel Corporation
#
# 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.
#
from grpc import StatusCode
from numpy import array, float64, int32, int8, float128, float32
from ovmsclient.tfs_compat.base.errors import ModelNotFoundError, InvalidInputError
from config import CallCount, PATH_VALID # noqa
from tensorflow.core.framework.tensor_pb2 import TensorProto
from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto
from tensorflow_serving.apis.get_model_status_pb2 import ModelVersionStatus
from tensorflow.core.framework.types_pb2 import DataType
from tensorflow.core.protobuf.error_codes_pb2 import Code as ErrorCode
from tensorflow_serving.apis.get_model_status_pb2 import GetModelStatusRequest
from tensorflow_serving.apis.get_model_metadata_pb2 import GetModelMetadataRequest
from tensorflow_serving.apis.predict_pb2 import PredictRequest
from ovmsclient.tfs_compat.grpc.requests import (GrpcModelMetadataRequest, GrpcModelStatusRequest,
GrpcPredictRequest)
# responses_dict = {
# model_version: { expected_status }
# }
MODEL_STATUS_RESPONSE_VALID = [
{
1: {
"state": ModelVersionStatus.State.AVAILABLE,
"error_code": ErrorCode.OK,
"error_message": "OK"
}
},
{
2: {
"state": ModelVersionStatus.State.END,
"error_code": ErrorCode.OK,
"error_message": "OK"
},
3: {
"state": ModelVersionStatus.State.AVAILABLE,
"error_code": ErrorCode.OK,
"error_message": ""
}
},
{
1: {
"state": ModelVersionStatus.State.START,
"error_code": ErrorCode.OK,
"error_message": ""
},
2: {
"state": ModelVersionStatus.State.LOADING,
"error_code": ErrorCode.UNKNOWN,
"error_message": "Could not load CNN"
},
3: {
"state": ModelVersionStatus.State.UNLOADING,
"error_code": ErrorCode.OK,
"error_message": ""
}
}
]
# response_dict = {
# 'version': model_version,
# 'name': model_name,
# 'inputs': inputs_dict,
# 'outputs': outputs_dict
# }
MODEL_METADATA_RESPONSE_VALID = [
{
'version': 2,
'name': 'resnet',
'inputs': {
'0': {
'shape': [1, 3, 244, 244],
'dtype': DataType.DT_FLOAT
}
},
'outputs': {
'1463': {
'shape': [1, 1000],
'dtype': DataType.DT_FLOAT
}
}
},
{
'version': 1,
'name': 'model_name',
'inputs': {
'0': {
'shape': [1, 3, 244, 244],
'dtype': DataType.DT_FLOAT
},
'1': {
'shape': [0, 1, 3, 244, 244],
'dtype': DataType.DT_INT32
}
},
'outputs': {
'1463': {
'shape': [1, 1000],
'dtype': DataType.DT_FLOAT
},
'second_output': {
'shape': [0, 1, 1000],
'dtype': DataType.DT_INT32
}
}
},
{
'version': 1,
'name': 'model_name',
'inputs': {
'input1': {
'shape': [1, 3, 1080, 1920],
'dtype': DataType.DT_QINT32
},
'input2': {
'shape': [1, 3, 244, 244],
'dtype': DataType.DT_INT32
}
},
'outputs': {
'single_output': {
'shape': [1, 7, 200, 200],
'dtype': DataType.DT_FLOAT
}
}
}
]
# (inputs_dict,
# model_name, model_version, expected_exception, expected_message)
PREDICT_REQUEST_INVALID_INPUTS = [
([],
'model_name', 0, TypeError, "inputs type should be dict, but is list"),
(('input1', [1, 2, 3]),
'model_name', 0, TypeError, "inputs type should be dict, but is tuple"),
({
1: [1, 2, 3],
"input2": [1, 2]
}, 'model_name', 0, TypeError, "inputs keys type should be str, but found int"),
({
"input1": [[1.0, 2.0], [1.0, 2.0, 3.0]]
}, 'model_name', 0, ValueError,
("argument must be a dense tensor: [[1.0, 2.0], [1.0, 2.0, 3.0]] - "
"got shape [2], but wanted [2, 2]")),
({
"input1": [[(1, 2, 3)], [(1, 2)], [(1, 2, 3)]]
}, 'model_name', 0, TypeError, "provided values type is not valid"),
({
"input1": float128(2.5)
}, 'model_name', 0, TypeError, "provided values type is not valid"),
({
"input1": (1, 2, 3)
}, 'model_name', 0, TypeError,
"values type should be (list, np.ndarray, scalar), but is tuple"),
({
"input1": [
[bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00]),
bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])],
[bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00]),
bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])]
]
}, 'model_name', 0, ValueError, "bytes values with dtype DT_STRING must be in shape [N]"),
]
# (inputs_dict,
# expected_proto_dict,
# model_name, model_version)
PREDICT_REQUEST_VALID = [
({
"input1": [1, 2, 3],
"input2": array([1.0, 2.0, 3.0]),
"input3": [[int32(3), int32(1)], [int32(4), int32(16)]],
}, {
"input1": {
"field": "tensor_content",
"shape": TensorShapeProto(dim=[TensorShapeProto.Dim(size=3)]),
"dtype": DataType.DT_INT32,
'value': array([1, 2, 3], dtype=int32).tobytes()
},
"input2": {
"field": "tensor_content",
"shape": TensorShapeProto(dim=[TensorShapeProto.Dim(size=3)]),
"dtype": DataType.DT_DOUBLE,
'value': array([1.0, 2.0, 3.0]).tobytes()
},
"input3": {
"field": "tensor_content",
"shape": TensorShapeProto(dim=[TensorShapeProto.Dim(size=2),
TensorShapeProto.Dim(size=2)]),
"dtype": DataType.DT_INT32,
'value': array([[int32(3), int32(1)], [int32(4), int32(16)]]).tobytes()
},
}, 'model_name', 0),
({
"input1": TensorProto(dtype=DataType.DT_INT8,
tensor_shape=TensorShapeProto(dim=[TensorShapeProto.Dim(size=2),
TensorShapeProto.Dim(size=3)]),
tensor_content=array([1, 2, 3, 4, 5, 6]).tobytes()),
"input2": 5.0,
"input3": bytes([1, 2, 3])
}, {
"input2": {
"field": "float_val",
"shape": TensorShapeProto(dim=[TensorShapeProto.Dim(size=1)]),
"dtype": DataType.DT_FLOAT,
'value': array([5.0], dtype=float32)
},
"input3": {
"field": "string_val",
"shape": TensorShapeProto(dim=[TensorShapeProto.Dim(size=1)]),
"dtype": DataType.DT_STRING,
'value': [bytes([1, 2, 3])]
}
}, 'model_name', 0),
({
}, {
}, 'model_name', 0)
]
# (response_outputs_dict, model_name, model_version, expected_outputs)
PREDICT_RESPONSE_VALID = [
({
"1463": TensorProto(dtype=DataType.DT_INT8,
tensor_shape=TensorShapeProto(dim=[TensorShapeProto.Dim(size=3)]),
tensor_content=array([1, 2, 3], dtype=int8).tobytes()),
}, "model_name", 0, array([1, 2, 3], dtype=int8)
),
({
"1463": TensorProto(dtype=DataType.DT_INT32,
tensor_shape=TensorShapeProto(dim=[TensorShapeProto.Dim(size=2),
TensorShapeProto.Dim(size=3)]),
tensor_content=array([1, 2, 3, 4, 5, 6], dtype=int32).tobytes()),
"2": TensorProto(dtype=DataType.DT_DOUBLE,
tensor_shape=TensorShapeProto(dim=[TensorShapeProto.Dim(size=1)]),
double_val=array([12.0], dtype=float64)),
}, "model_name", 0, {
"1463": array([[1, 2, 3], [4, 5, 6]], dtype=int32),
"2": array([12.0], dtype=float64)
}),
({
"1463": TensorProto(dtype=DataType.DT_STRING,
tensor_shape=TensorShapeProto(dim=[TensorShapeProto.Dim(size=2)]),
string_val=[bytes([1, 2, 3]), bytes([4, 5])]),
"2": TensorProto(dtype=DataType.DT_STRING,
tensor_shape=TensorShapeProto(dim=[TensorShapeProto.Dim(size=1)]),
string_val=[bytes([1, 2, 3])]),
}, "model_name", 0, {
"1463": [bytes([1, 2, 3]), bytes([4, 5])],
"2": [bytes([1, 2, 3])]
}),
]
# (response_outputs_dict, model_name, model_version, expected_exception, expected_message)
PREDICT_RESPONSE_TENSOR_TYPE_INVALID = [
({
"1463": TensorProto(),
}, "model_name", 0, TypeError, "Unsupported tensor type: 0"),
({
"1463": TensorProto(dtype=DataType.DT_INVALID),
}, "model_name", 0, TypeError, "Unsupported tensor type: 0"),
({
"1463": TensorProto(dtype=DataType.DT_RESOURCE),
}, "model_name", 0, TypeError, "Unsupported tensor type: 20"),
]
# ({"model_name": model_name, "model_version": model_version,
# "raw_request_model_name": raw_request_model_name, "raw_request_model_version": raw_request_model_version})# noqa : E501
MODEL_STATUS_REQUEST_VALID = [
({"model_name": "name", "model_version": 0,
"raw_request_model_name": "name", "raw_request_model_version": 0}),
]
# ({"model_name": model_name, "model_version": model_version,
# "raw_request_model_name": raw_request_model_name, "raw_request_model_version": raw_request_model_version},# noqa : E501
# expected_exception, expected_message)
MODEL_STATUS_REQUEST_INVALID_RAW_REQUEST = [
({"model_name": "name", "model_version": 0,
"raw_request_model_name": "other_name", "raw_request_model_version": 0},
ValueError, 'request is not valid GrpcModelStatusRequest'),
({"model_name": "other_name", "model_version": 0,
"raw_request_model_name": "name", "raw_request_model_version": 0},
ValueError, 'request is not valid GrpcModelStatusRequest'),
({"model_name": "name", "model_version": 0,
"raw_request_model_name": "name", "raw_request_model_version": 1},
ValueError, 'request is not valid GrpcModelStatusRequest'),
({"model_name": "name", "model_version": 1,
"raw_request_model_name": "name", "raw_request_model_version": 0},
ValueError, 'request is not valid GrpcModelStatusRequest'),
]
# (request, expeceted_exception, expected_message)
MODEL_STATUS_REQUEST_INVALID_REQUEST_TYPE = [
(None, TypeError,
"request type should be GrpcModelStatusRequest, but is NoneType"),
(GetModelStatusRequest(), TypeError,
"request type should be GrpcModelStatusRequest, but is GetModelStatusRequest"),
(GrpcModelStatusRequest('model_name', 0, 'raw_request'), TypeError,
"request is not valid GrpcModelStatusRequest")
]
# (grpc_error_status_code, grpc_error_details, raised_error_type, raised_error_message)
COMMON_INVALID_GRPC = [
(StatusCode.UNAVAILABLE, "failed to connect to all adresses",
ConnectionError, "Error occurred during handling the request: "
"failed to connect to all adresses"),
(StatusCode.UNAVAILABLE, "Empty update",
ConnectionError, "Error occurred during handling the request: Empty update"),
(StatusCode.DEADLINE_EXCEEDED, "Deadline Exceeded",
TimeoutError, "Error occurred during handling the request: "
"Request handling exceeded timeout"),
(StatusCode.NOT_FOUND, "Model with requested version is not found",
ModelNotFoundError, "Error occurred during handling the request: "
"Model with requested version is not found"),
(StatusCode.NOT_FOUND, "Model with requested name is not found",
ModelNotFoundError, "Error occurred during handling the request: "
"Model with requested name is not found"),
]
# ({"model_name": model_name, "model_version": model_version,
# "raw_request_model_name": raw_request_model_name, "raw_request_model_version": raw_request_model_version,# noqa : E501
# "metadata_field_list": raw_request_metadata_fields})
MODEL_METADATA_REQUEST_VALID = [
({"model_name": "name", "model_version": 0,
"raw_request_model_name": "name", "raw_request_model_version": 0,
"metadata_field_list": ["signature_def"]}),
]
# ({"model_name": model_name, "model_version": model_version,
# "raw_request_model_name": raw_request_model_name, "raw_request_model_version": raw_request_model_version,# noqa : E501
# "metadata_field_list": raw_request_metadata_fields},
# expected_exception, expected_message)
MODEL_METADATA_REQUEST_INVALID_RAW_REQUEST = [
({"model_name": "name", "model_version": 0,
"raw_request_model_name": "other_name", "raw_request_model_version": 0,
"metadata_field_list": ["signature_def"]},
ValueError, 'request is not valid GrpcModelMetadataRequest'),
({"model_name": "other_name", "model_version": 0,
"raw_request_model_name": "name", "raw_request_model_version": 0,
"metadata_field_list": ["signature_def"]},
ValueError, 'request is not valid GrpcModelMetadataRequest'),
({"model_name": "name", "model_version": 0,
"raw_request_model_name": "name", "raw_request_model_version": 1,
"metadata_field_list": ["signature_def"]},
ValueError, 'request is not valid GrpcModelMetadataRequest'),
({"model_name": "name", "model_version": 1,
"raw_request_model_name": "name", "raw_request_model_version": 0,
"metadata_field_list": ["signature_def"]},
ValueError, 'request is not valid GrpcModelMetadataRequest'),
({"model_name": "name", "model_version": 1,
"raw_request_model_name": "name", "raw_request_model_version": 1,
"metadata_field_list": ["invalid"]},
ValueError, 'request is not valid GrpcModelMetadataRequest'),
]
# (request, expected_exception, expected_message)
MODEL_METADATA_REQUEST_INVALID_REQUEST_TYPE = [
(None, TypeError,
"request type should be GrpcModelMetadataRequest, but is NoneType"),
(GetModelMetadataRequest(), TypeError,
"request type should be GrpcModelMetadataRequest, but is GetModelMetadataRequest"),
(GrpcModelMetadataRequest('model_name', 0, 'raw_request'), TypeError,
"request is not valid GrpcModelMetadataRequest")
]
# ({"model_name": model_name, "model_version": model_version,
# "raw_request_model_name": raw_request_model_name, "raw_request_model_version": raw_request_model_version,# noqa : E501
# "inputs_dict": inputs_for_request, "raw_request_inputs_dict": inputs_for_raw_request})
PREDICT_REQUEST_VALID_SPEC = [
({"model_name": "name", "model_version": 0,
"raw_request_model_name": "name", "raw_request_model_version": 0,
"inputs_dict": {
"0": TensorProto(dtype=DataType.DT_INT8,
tensor_shape=TensorShapeProto(dim=[TensorShapeProto.Dim(size=3)]),
tensor_content=array([1, 2, 3]).tobytes())
},
"raw_request_inputs_dict": {
"0": TensorProto(dtype=DataType.DT_INT8,
tensor_shape=TensorShapeProto(dim=[TensorShapeProto.Dim(size=3)]),
tensor_content=array([1, 2, 3]).tobytes())
}}),
]
# ({"model_name": model_name, "model_version": model_version,
# "raw_request_model_name": raw_request_model_name, "raw_request_model_version": raw_request_model_version,# noqa : E501
# "inputs_dict": inputs_for_request, "raw_request_inputs_dict": inputs_for_raw_request},
# expected_exception, expected_message)
PREDICT_REQUEST_INVALID_SPEC_RAW_REQUEST = [
({"model_name": "name", "model_version": 0,
"raw_request_model_name": "other_name", "raw_request_model_version": 0,
"inputs_dict": {
"0": TensorProto()
},
"raw_request_inputs_dict": {
"0": TensorProto()
}}, ValueError, 'request is not valid GrpcPredictRequest'),
({"model_name": "other_name", "model_version": 0,
"raw_request_model_name": "name", "raw_request_model_version": 0,
"inputs_dict": {
"0": TensorProto()
},
"raw_request_inputs_dict": {
"0": TensorProto()
}}, ValueError, 'request is not valid GrpcPredictRequest'),
({"model_name": "name", "model_version": 1,
"raw_request_model_name": "name", "raw_request_model_version": 0,
"inputs_dict": {
"0": TensorProto()
},
"raw_request_inputs_dict": {
"0": TensorProto()
}}, ValueError, 'request is not valid GrpcPredictRequest'),
({"model_name": "name", "model_version": 0,
"raw_request_model_name": "name", "raw_request_model_version": 1,
"inputs_dict": {
"0": TensorProto()
},
"raw_request_inputs_dict": {
"0": TensorProto()
}}, ValueError, 'request is not valid GrpcPredictRequest'),
({"model_name": "name", "model_version": 0,
"raw_request_model_name": "name", "raw_request_model_version": 0,
"inputs_dict": {
"0": TensorProto()
},
"raw_request_inputs_dict": {
"1": TensorProto()
}}, ValueError, 'request is not valid GrpcPredictRequest'),
]
# (predict_request, expected_exception, expected_message)
PREDICT_REQUEST_INVALID_SPEC_TYPE = [
(None, TypeError,
'request type should be GrpcPredictRequest, but is NoneType'),
(PredictRequest(), TypeError,
'request type should be GrpcPredictRequest, but is PredictRequest'),
(GrpcPredictRequest({}, "model_name", 0, "raw_request"),
TypeError, 'request is not valid GrpcPredictRequest'),
]
# (grpc_error_status_code, grpc_error_details, raised_error_type, raised_error_message)
PREDICT_INVALID_GRPC = COMMON_INVALID_GRPC + [
(StatusCode.INVALID_ARGUMENT, "Invalid input precision - Expected: FP32; Actual: I64",
InvalidInputError, "Error occurred during handling the request: "
"Invalid input precision - Expected: FP32; Actual: I64"),
(StatusCode.INVALID_ARGUMENT, "Invalid number of inputs - Expected: 1; Actual: 0",
InvalidInputError, "Error occurred during handling the request: "
"Invalid number of inputs - Expected: 1; Actual: 0"),
(StatusCode.INVALID_ARGUMENT, "Missing input with specific name - Required input: 0",
InvalidInputError, "Error occurred during handling the request: "
"Missing input with specific name - Required input: 0"),
(StatusCode.INVALID_ARGUMENT, "Invalid number of shape dimensions - "
"Expected: (1,3,224,224); Actual: (3)",
InvalidInputError, "Error occurred during handling the request: "
"Invalid number of shape dimensions - Expected: (1,3,224,224); "
"Actual: (3)"),
]
# (config_dict,
# method_call_count_dict= {"method_name": CallCount.NumberOfCalls})
BUILD_VALID = [
(
{
"url": "localhost:9000"
},
{
"_check_url": CallCount.ONE,
"_check_tls_config": CallCount.ZERO,
"_prepare_certs": CallCount.ZERO
}
),
(
{
"url": "172.16.17.32:1"
},
{
"_check_url": CallCount.ONE,
"_check_tls_config": CallCount.ZERO,
"_prepare_certs": CallCount.ZERO
}
),
(
{
"url": f"cluster.cloud.iotg.intel.com:{2**16-1}"
},
{
"_check_url": CallCount.ONE,
"_check_tls_config": CallCount.ZERO,
"_prepare_certs": CallCount.ZERO
}
),
(
{
"url": "localhost:9000",
"tls_config": {
"server_cert_path": "valid_path"
}
},
{
"_check_url": CallCount.ONE,
"_check_tls_config": CallCount.ONE,
"_prepare_certs": CallCount.ONE
}
),
(
{
"url": "localhost:9000",
"tls_config": {
"client_key_path": PATH_VALID,
"client_cert_path": PATH_VALID,
"server_cert_path": PATH_VALID
}
},
{
"_check_url": CallCount.ONE,
"_check_tls_config": CallCount.ONE,
"_prepare_certs": CallCount.ONE
}
)
]
# (config_dict,
# method_call_dict= {"method_name": (CallCount.NumberOfCalls, error_raised)},
# expected_exception, expected_message)
BUILD_INVALID_CONFIG = [
(
{
"url": "localhost"
},
{
"_check_url": (CallCount.ONE, ValueError("url must be a string "
"in format <address>:<port>")),
"_check_tls_config": (CallCount.ZERO, None),
"_prepare_certs": (CallCount.ZERO, None)
},
ValueError, "url must be a string in format <address>:<port>"
),
(
{
"url": 123
},
{
"_check_url": (CallCount.ONE, TypeError("url must be a string "
"in format <address>:<port>")),
"_check_tls_config": (CallCount.ZERO, None),
"_prepare_certs": (CallCount.ZERO, None)
},
TypeError, "url must be a string in format <address>:<port>"
),
(
{
"url": "address:9000",
},
{
"_check_url": (CallCount.ONE, ValueError("address is not valid")),
"_check_tls_config": (CallCount.ZERO, None),
"_prepare_certs": (CallCount.ZERO, None)
},
ValueError, "address is not valid"
),
(
{
"url": "localhost:port"
},
{
"_check_url": (CallCount.ONE, TypeError("port should be of type int")),
"_check_tls_config": (CallCount.ZERO, None),
"_prepare_certs": (CallCount.ZERO, None)
},
TypeError, "port should be of type int"
),
(
{
"url": f"localhost:{2**16}"
},
{
"_check_url": (CallCount.ONE, ValueError(f"port should be in range <0, {2**16-1}>")),
"_check_tls_config": (CallCount.ZERO, None),
"_prepare_certs": (CallCount.ZERO, None)
},
ValueError, f"port should be in range <0, {2**16-1}>"
),
(
{
"url": "localhost:9000",
"tls_config": 123
},
{
"_check_url": (CallCount.ONE, None),
"_check_tls_config": (CallCount.ONE, TypeError("tls_config should be of type dict")),
"_prepare_certs": (CallCount.ZERO, None)
},
TypeError, "tls_config should be of type dict"
),
(
{
"url": "localhost:9000",
"tls_config": {
}
},
{
"_check_url": (CallCount.ONE, None),
"_check_tls_config": (CallCount.ONE, ValueError("server_cert_path is not defined "
"in tls_config")),
"_prepare_certs": (CallCount.ZERO, None)
},
ValueError, "server_cert_path is not defined in tls_config"
),
(
{
"url": "10.20.30.40:1000",
"tls_config": {
"server_cert_path": PATH_VALID,
"client_key_path": PATH_VALID
}
},
{
"_check_url": (CallCount.ONE, None),
"_check_tls_config": (CallCount.ONE, ValueError("none or both client_key_path "
"and client_cert_path are required "
"in tls_config")),
"_prepare_certs": (CallCount.ZERO, None)
},
ValueError, "none or both client_key_path and client_cert_path are required in tls_config"
),
(
{
"url": "localhost:9000",
"tls_config": {
"server_cert_path": PATH_VALID,
"client_key_path": PATH_VALID,
"client_cert_path": PATH_VALID,
"invalid_key_name": PATH_VALID
}
},
{
"_check_url": (CallCount.ONE, None),
"_check_tls_config": (CallCount.ONE, ValueError("invalid_key_name is "
"not valid tls_config key")),
"_prepare_certs": (CallCount.ZERO, None)
},
ValueError, "invalid_key_name is not valid tls_config key"
),
(
{
"url": "localhost:9000",
"tls_config": {
"server_cert_path": PATH_VALID,
"client_key_path": PATH_VALID,
"client_cert_path": 123,
}
},
{
"_check_url": (CallCount.ONE, None),
"_check_tls_config": (CallCount.ONE, TypeError("client_cert_path type should be string "
"but is type int")),
"_prepare_certs": (CallCount.ZERO, None)
},
TypeError, "client_cert_path type should be string but is type int"
),
(
{
"url": "localhost:9000",
"tls_config": {
"server_cert_path": PATH_VALID,
"client_key_path": "invalid_path",
"client_cert_path": PATH_VALID,
}
},
{
"_check_url": (CallCount.ONE, None),
"_check_tls_config": (CallCount.ONE, ValueError("invalid_path is not valid "
"path to file")),
"_prepare_certs": (CallCount.ZERO, None)
},
ValueError, "invalid_path is not valid path to file"
),
]
# (config_dict,
# method_call_dict= {"method_name": (CallCount.NumberOfCalls, error_raised)},
# expected_exception, expected_message)
BUILD_INVALID_CERTS = [
(
{
"url": "localhost:9000",
"tls_config": {
"server_cert_path": PATH_VALID,
"client_key_path": "path_to_invalid_private_key",
"client_cert_path": PATH_VALID,
}
},
{
"_check_url": (CallCount.ONE, None),
"_check_tls_config": (CallCount.ONE, None),
"_prepare_certs": (CallCount.ONE, ValueError("path_to_invalid_private_key file "
"is not valid private key"))
},
ValueError, "path_to_invalid_private_key file is not valid private key"
),
(
{
"url": "localhost:9000",
"tls_config": {
"server_cert_path": "path_to_invalid_server_certificate",
"client_key_path": PATH_VALID,
"client_cert_path": PATH_VALID,
}
},
{
"_check_url": (CallCount.ONE, None),
"_check_tls_config": (CallCount.ONE, None),
"_prepare_certs": (CallCount.ONE, ValueError("path_to_invalid_server_certificate "
"is not valid certificate"))
},
ValueError, "path_to_invalid_server_certificate is not valid certificate"
),
(
{
"url": "localhost:9000",
"tls_config": {
"server_cert_path": PATH_VALID,
"client_key_path": PATH_VALID,
"client_cert_path": "path_to_invalid_client_certificate",
}
},
{
"_check_url": (CallCount.ONE, None),
"_check_tls_config": (CallCount.ONE, None),
"_prepare_certs": (CallCount.ONE, ValueError("path_to_invalid_client_certificate "
"is not valid certificate"))
},
ValueError, "path_to_invalid_client_certificate is not valid certificate"
),
]
|
[
"tensorflow_serving.apis.get_model_metadata_pb2.GetModelMetadataRequest",
"tensorflow_serving.apis.predict_pb2.PredictRequest",
"tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim",
"tensorflow.core.framework.tensor_pb2.TensorProto",
"ovmsclient.tfs_compat.grpc.requests.GrpcModelStatusRequest",
"tensorflow_serving.apis.get_model_status_pb2.GetModelStatusRequest",
"numpy.array",
"numpy.int32",
"numpy.float128",
"ovmsclient.tfs_compat.grpc.requests.GrpcModelMetadataRequest",
"ovmsclient.tfs_compat.grpc.requests.GrpcPredictRequest"
] |
[((8055, 8083), 'numpy.array', 'array', (['[1, 2, 3]'], {'dtype': 'int8'}), '([1, 2, 3], dtype=int8)\n', (8060, 8083), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((11394, 11417), 'tensorflow_serving.apis.get_model_status_pb2.GetModelStatusRequest', 'GetModelStatusRequest', ([], {}), '()\n', (11415, 11417), False, 'from tensorflow_serving.apis.get_model_status_pb2 import GetModelStatusRequest\n'), ((11520, 11574), 'ovmsclient.tfs_compat.grpc.requests.GrpcModelStatusRequest', 'GrpcModelStatusRequest', (['"""model_name"""', '(0)', '"""raw_request"""'], {}), "('model_name', 0, 'raw_request')\n", (11542, 11574), False, 'from ovmsclient.tfs_compat.grpc.requests import GrpcModelMetadataRequest, GrpcModelStatusRequest, GrpcPredictRequest\n'), ((14844, 14869), 'tensorflow_serving.apis.get_model_metadata_pb2.GetModelMetadataRequest', 'GetModelMetadataRequest', ([], {}), '()\n', (14867, 14869), False, 'from tensorflow_serving.apis.get_model_metadata_pb2 import GetModelMetadataRequest\n'), ((14976, 15032), 'ovmsclient.tfs_compat.grpc.requests.GrpcModelMetadataRequest', 'GrpcModelMetadataRequest', (['"""model_name"""', '(0)', '"""raw_request"""'], {}), "('model_name', 0, 'raw_request')\n", (15000, 15032), False, 'from ovmsclient.tfs_compat.grpc.requests import GrpcModelMetadataRequest, GrpcModelStatusRequest, GrpcPredictRequest\n'), ((18158, 18174), 'tensorflow_serving.apis.predict_pb2.PredictRequest', 'PredictRequest', ([], {}), '()\n', (18172, 18174), False, 'from tensorflow_serving.apis.predict_pb2 import PredictRequest\n'), ((18266, 18320), 'ovmsclient.tfs_compat.grpc.requests.GrpcPredictRequest', 'GrpcPredictRequest', (['{}', '"""model_name"""', '(0)', '"""raw_request"""'], {}), "({}, 'model_name', 0, 'raw_request')\n", (18284, 18320), False, 'from ovmsclient.tfs_compat.grpc.requests import GrpcModelMetadataRequest, GrpcModelStatusRequest, GrpcPredictRequest\n'), ((5079, 5092), 'numpy.float128', 'float128', (['(2.5)'], {}), '(2.5)\n', (5087, 5092), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((5824, 5846), 'numpy.array', 'array', (['[1.0, 2.0, 3.0]'], {}), '([1.0, 2.0, 3.0])\n', (5829, 5846), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((8681, 8723), 'numpy.array', 'array', (['[[1, 2, 3], [4, 5, 6]]'], {'dtype': 'int32'}), '([[1, 2, 3], [4, 5, 6]], dtype=int32)\n', (8686, 8723), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((8738, 8766), 'numpy.array', 'array', (['[12.0]'], {'dtype': 'float64'}), '([12.0], dtype=float64)\n', (8743, 8766), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((9482, 9495), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {}), '()\n', (9493, 9495), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((9586, 9624), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {'dtype': 'DataType.DT_INVALID'}), '(dtype=DataType.DT_INVALID)\n', (9597, 9624), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((9715, 9754), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {'dtype': 'DataType.DT_RESOURCE'}), '(dtype=DataType.DT_RESOURCE)\n', (9726, 9754), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((7364, 7391), 'numpy.array', 'array', (['[5.0]'], {'dtype': 'float32'}), '([5.0], dtype=float32)\n', (7369, 7391), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((16561, 16574), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {}), '()\n', (16572, 16574), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((16634, 16647), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {}), '()\n', (16645, 16647), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((16878, 16891), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {}), '()\n', (16889, 16891), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((16951, 16964), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {}), '()\n', (16962, 16964), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((17189, 17202), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {}), '()\n', (17200, 17202), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((17262, 17275), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {}), '()\n', (17273, 17275), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((17500, 17513), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {}), '()\n', (17511, 17513), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((17573, 17586), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {}), '()\n', (17584, 17586), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((17811, 17824), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {}), '()\n', (17822, 17824), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((17884, 17897), 'tensorflow.core.framework.tensor_pb2.TensorProto', 'TensorProto', ([], {}), '()\n', (17895, 17897), False, 'from tensorflow.core.framework.tensor_pb2 import TensorProto\n'), ((5868, 5876), 'numpy.int32', 'int32', (['(3)'], {}), '(3)\n', (5873, 5876), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((5878, 5886), 'numpy.int32', 'int32', (['(1)'], {}), '(1)\n', (5883, 5886), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((5890, 5898), 'numpy.int32', 'int32', (['(4)'], {}), '(4)\n', (5895, 5898), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((5900, 5909), 'numpy.int32', 'int32', (['(16)'], {}), '(16)\n', (5905, 5909), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((8608, 8636), 'numpy.array', 'array', (['[12.0]'], {'dtype': 'float64'}), '([12.0], dtype=float64)\n', (8613, 8636), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((6117, 6146), 'numpy.array', 'array', (['[1, 2, 3]'], {'dtype': 'int32'}), '([1, 2, 3], dtype=int32)\n', (6122, 6146), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((6364, 6386), 'numpy.array', 'array', (['[1.0, 2.0, 3.0]'], {}), '([1.0, 2.0, 3.0])\n', (6369, 6386), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((6024, 6052), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(3)'}), '(size=3)\n', (6044, 6052), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((6270, 6298), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(3)'}), '(size=3)\n', (6290, 6298), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((6510, 6538), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(2)'}), '(size=2)\n', (6530, 6538), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((6583, 6611), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(2)'}), '(size=2)\n', (6603, 6611), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((7069, 7094), 'numpy.array', 'array', (['[1, 2, 3, 4, 5, 6]'], {}), '([1, 2, 3, 4, 5, 6])\n', (7074, 7094), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((7271, 7299), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(1)'}), '(size=1)\n', (7291, 7299), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((7501, 7529), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(1)'}), '(size=1)\n', (7521, 7529), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((7990, 8018), 'numpy.array', 'array', (['[1, 2, 3]'], {'dtype': 'int8'}), '([1, 2, 3], dtype=int8)\n', (7995, 8018), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((8378, 8416), 'numpy.array', 'array', (['[1, 2, 3, 4, 5, 6]'], {'dtype': 'int32'}), '([1, 2, 3, 4, 5, 6], dtype=int32)\n', (8383, 8416), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((15737, 15753), 'numpy.array', 'array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (15742, 15753), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((15996, 16012), 'numpy.array', 'array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (16001, 16012), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((6902, 6930), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(2)'}), '(size=2)\n', (6922, 6930), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((6992, 7020), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(3)'}), '(size=3)\n', (7012, 7020), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((7915, 7943), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(3)'}), '(size=3)\n', (7935, 7943), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((8215, 8243), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(2)'}), '(size=2)\n', (8235, 8243), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((8303, 8331), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(3)'}), '(size=3)\n', (8323, 8331), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((8540, 8568), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(1)'}), '(size=1)\n', (8560, 8568), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((8900, 8928), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(2)'}), '(size=2)\n', (8920, 8928), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((9118, 9146), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(1)'}), '(size=1)\n', (9138, 9146), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((15663, 15691), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(3)'}), '(size=3)\n', (15683, 15691), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((15922, 15950), 'tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': '(3)'}), '(size=3)\n', (15942, 15950), False, 'from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto\n'), ((6684, 6692), 'numpy.int32', 'int32', (['(3)'], {}), '(3)\n', (6689, 6692), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((6694, 6702), 'numpy.int32', 'int32', (['(1)'], {}), '(1)\n', (6699, 6702), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((6706, 6714), 'numpy.int32', 'int32', (['(4)'], {}), '(4)\n', (6711, 6714), False, 'from numpy import array, float64, int32, int8, float128, float32\n'), ((6716, 6725), 'numpy.int32', 'int32', (['(16)'], {}), '(16)\n', (6721, 6725), False, 'from numpy import array, float64, int32, int8, float128, float32\n')]
|
"""
Module containing all general purpose functions shared by other modules.
This module is not intended for the direct use by a User. Therefore, I will
only docstring functions if I see fit to do so.
LOG
---
11/07/18
Changed the way vector path is analysed. Now, the initial analysis is
done with the geometrical formula for line-sphere intersection. Only
the remaining vestors that do not intersect any van der Waals spheres are
then analysed in the old way.
27/07/17
Fixed the cartesian coordinates -> fractional coordinates -> cartesian
coordinates conversion related functions, creation of lattice array
from unit cell parameters (triclinic system: so applicable to any)
and conversion back to unit cell parameters. WORKS! inspiration from:
http://www.ruppweb.org/Xray/tutorial/Coordinate%20system%20transformation.htm
26/07/17
Changed the way bonds are determined. Now, rather then fixed value
a formula and covalent radii are used as explained in the Elemental_Radii
spreadsheet (see tables module).
TO DO LIST
----------
- Fix and validate calculating shape descriptors: asphericity, acylindricity
and the realtive shape anisotropy. (Not working at the moment)
- In the find_windows() function, maybe change the way the EPS value for
the DBSCAN() is estimates. Need to look how the distances change with the
increase in size of the sampling sphere. (validate this with the MongoDB)
"""
import numpy as np
from copy import deepcopy
from multiprocessing import Pool
from scipy.optimize import brute, fmin, minimize
from sklearn.cluster import DBSCAN
from sklearn.metrics.pairwise import euclidean_distances
from sklearn.neighbors import KDTree
from .tables import (
atomic_mass, atomic_vdw_radius, opls_atom_keys, atomic_covalent_radius
)
class _AtomKeyError(Exception):
def __init__(self, message):
self.message = message
class _AtomKeyConflict(Exception):
def __init__(self, message):
self.message = message
class _ForceFieldError(Exception):
def __init__(self, message):
self.message = message
class _FunctionError(Exception):
def __init__(self, message):
self.message = message
def is_number(number):
"""
Return True if an object is a number - can be converted into a float.
Parameters
----------
number : any
Returns
-------
bool
True if input is a float convertable (a number), False otherwise.
"""
try:
float(number)
return True
except ValueError:
return False
def unique(input_list):
"""
Return a list of unique items (similar to set functionality).
Parameters
----------
input_list : list
A list containg some items that can occur more than once.
Returns
-------
list
A list with only unique occurances of an item.
"""
output = []
for item in input_list:
if item not in output:
output.append(item)
return output
def to_list(obj):
""" """
if isinstance(obj, np.ndarray):
return obj.tolist()
raise TypeError('Not serializable')
def distance(a, b):
"""
Return the distance between two vectors (points) a and b.
Parameters
----------
a : numpy.ndarray
First vector.
b : numpy.ndarray
Second vector.
Returns
-------
numpy.float64
A distance between two vectors (points).
"""
return (np.sum((a - b)**2))**0.5
def molecular_weight(elements):
"""
Return molecular weight of a molecule.
Parameters
----------
elements : numpy.ndarray
An array of all elements (type: str) in a molecule.
Returns
-------
numpy.float64
A molecular weight of a molecule.
"""
return (np.array([atomic_mass[i.upper()] for i in elements]).sum())
def center_of_coor(coordinates):
"""
Return the centre of coordinates.
Parameters
----------
coordinates : numpy.ndarray
An array containing molecule's coordinates.
Returns
-------
numpy.ndarray
An 1d array with coordinates of the centre of coordinates excluding
elements' masses.
"""
return (np.sum(coordinates, axis=0) / coordinates.shape[0])
def center_of_mass(elements, coordinates):
"""
Return the centre of mass (COM).
Parameters
----------
elements : numpy.ndarray
An array of all elements (type: str) in a molecule.
coordinates : numpy.ndarray
An array containing molecule's coordinates.
Returns
-------
numpy.ndarray
An 1d array with coordinates of the centre of mass including elements'
masses.
"""
mass = molecular_weight(elements)
mass_array = np.array([[atomic_mass[i.upper()]] * 3 for i in elements])
mass_coordinates = coordinates * mass_array
return (np.sum(mass_coordinates, axis=0) / np.array([mass, mass, mass]))
def compose_atom_list(*args):
"""
Return an `atom list` from elements and/or atom ids and coordinates.
An `atom list` is a special object that some pywindowfunctions uses.
It is a nested list of lists with each individual list containing:
1. [[element, coordinates (x, y, z)], ...]
2. [[element, atom key, coordinates (x, y, z)], ...]
They work better for molecular re-building than two separate arrays for
elements and coordinates do.
Parameters
----------
elements : :class:`numpy.ndarray`
An array of all elements (type: str) in a molecule.
coordinates : :class:`numpy.ndarray`
An array containing molecule's coordinates.
atom_ids : :class:`numpy.ndarray`, optional
An array of all forcfield dependent atom keys (type:str) in a molecule.
Returns
-------
list
Version 1 or version 2 atom list depending on input parameters.
Raises
------
_FunctionError : :class:`Exception`
Raised when wrong number of parameters is passed to the function.
"""
if len(args) == 2:
atom_list = [[
i[0],
round(float(i[1]), 8),
round(float(i[2]), 8),
round(float(i[3]), 8),
] for i in np.concatenate(
(args[0].reshape(-1, 1), args[1]), axis=1)]
elif len(args) == 3:
atom_list = [
[
i[0],
i[1],
round(float(i[2]), 8),
round(float(i[3]), 8),
round(float(i[4]), 8),
]
for i in np.concatenate(
(np.concatenate(
(args[0].reshape(-1, 1), args[1].reshape(-1, 1)
), axis=1), args[2]),
axis=1)
]
else:
raise _FunctionError(
"The compose_atom_list() function accepts only 2 or 3 arguments.")
return atom_list
def decompose_atom_list(atom_list):
"""
Return elements and/or atom ids and coordinates from an `atom list`.
Depending on input type of an atom list (version 1 or 2)
1. [[element, coordinates (x, y, z)], ...]
2. [[element, atom key, coordinates (x, y, z)], ...]
the function reverses what pywindow.utilities.compose_atom_list() do.
Parameters
----------
atom_list : list
A nested list of lists (version 1 or 2)
Returns
-------
touple
A touple of elements and coordinates arrays, or if input contained
atom ideas, also atom ids array.
"""
transpose = list(zip(*atom_list))
if len(transpose) == 4:
elements = np.array(transpose[0])
array_a = np.array(transpose[1]).reshape(-1, 1)
array_b = np.array(transpose[2]).reshape(-1, 1)
array_c = np.array(transpose[3]).reshape(-1, 1)
array_ab = np.concatenate((array_a, array_b), axis=1)
coordinates = np.concatenate((array_ab, array_c), axis=1)
return elements, coordinates
elif len(transpose) == 5:
elements = np.array(transpose[0])
atom_ids = np.array(transpose[1])
array_a = np.array(transpose[2]).reshape(-1, 1)
array_b = np.array(transpose[3]).reshape(-1, 1)
array_c = np.array(transpose[4]).reshape(-1, 1)
array_ab = np.concatenate((array_a, array_b), axis=1)
coordinates = np.concatenate((array_ab, array_c), axis=1)
return elements, atom_ids, coordinates
else:
raise _FunctionError(
"The decompose_atom_list() function accepts only list of lists "
" with only 4 or 5 items per sublist.")
def dlf_notation(atom_key):
"""Return element for atom key using DL_F notation."""
split = list(atom_key)
element = ''
number = False
count = 0
while number is False:
element = "".join((element, split[count]))
count += 1
if is_number(split[count]) is True:
number = True
# In case of for example Material Studio output, integers can also be
# in the beginning of the string. As the dlf_notation decipher function
# is very general in use, we have to make sure these integers are deleted.
# In standard DL_F notation the string will never start with integer so it
# will not affect the functionality towards it.
# EDIT2: also the '?' atoms, you can delete them manually or somewhere else
element = "".join(i for i in element if not is_number(i))
element = "".join(i for i in element if i != '?')
return element
def opls_notation(atom_key):
"""Return element for OPLS forcefield atom key."""
# warning for Ne, He, Na types overlap
conflicts = ['ne', 'he', 'na']
if atom_key in conflicts:
raise _AtomKeyConflict((
"One of the OPLS conflicting "
"atom_keys has occured '{0}'. "
"For how to solve this issue see the manual or "
"MolecularSystem._atom_key_swap() doc string.").format(atom_key))
for element in opls_atom_keys:
if atom_key in opls_atom_keys[element]:
return element
# In case if atom_key was not found in the OPLS keys dictionary
raise _AtomKeyError((
"OPLS atom key {0} was not found in OPLS keys dictionary.").format(
atom_key))
def decipher_atom_key(atom_key, forcefield):
"""
Return element for deciphered atom key.
This functions checks if the forcfield specified by user is supported
and passes the atom key to the appropriate function for deciphering.
Parameters
----------
atom_key : str
The atom key which is to be deciphered.
forcefield : str
The forcefield to which the atom key belongs to.
Returns
-------
str
A string that is the periodic table element equvalent of forcefield
atom key.
"""
load_funcs = {
'DLF': dlf_notation,
'DL_F': dlf_notation,
'OPLS': opls_notation,
'OPLSAA': opls_notation,
'OPLS2005': opls_notation,
'OPLS3': opls_notation,
}
if forcefield.upper() in load_funcs.keys():
return load_funcs[forcefield.upper()](atom_key)
else:
raise _ForceFieldError(
("Unfortunetely, '{0}' forcefield is not supported by pyWINDOW."
" For list of supported forcefields see User's Manual or "
"MolecularSystem._decipher_atom_keys() function doc string."
).format(forcefield))
def shift_com(elements, coordinates, com_adjust=np.zeros(3)):
"""
Return coordinates translated by some vector.
Parameters
----------
elements : numpy.ndarray
An array of all elements (type: str) in a molecule.
coordinates : numpy.ndarray
An array containing molecule's coordinates.
com_adjust : numpy.ndarray (default = [0, 0, 0])
Returns
-------
numpy.ndarray
Translated array of molecule's coordinates.
"""
com = center_of_mass(elements, coordinates)
com = np.array([com - com_adjust] * coordinates.shape[0])
return coordinates - com
def max_dim(elements, coordinates):
"""
Return the maximum diameter of a molecule.
Parameters
----------
elements : numpy.ndarray
An array of all elements (type: str) in a molecule.
coordinates : numpy.ndarray
An array containing molecule's coordinates.
Returns
-------
"""
atom_vdw_vertical = np.matrix(
[[atomic_vdw_radius[i.upper()]] for i in elements])
atom_vdw_horizontal = np.matrix(
[atomic_vdw_radius[i.upper()] for i in elements])
dist_matrix = euclidean_distances(coordinates, coordinates)
vdw_matrix = atom_vdw_vertical + atom_vdw_horizontal
re_dist_matrix = dist_matrix + vdw_matrix
final_matrix = np.triu(re_dist_matrix)
i1, i2 = np.unravel_index(final_matrix.argmax(), final_matrix.shape)
maxdim = final_matrix[i1, i2]
return i1, i2, maxdim
def pore_diameter(elements, coordinates, com=None):
"""Return pore diameter of a molecule."""
if com is None:
com = center_of_mass(elements, coordinates)
atom_vdw = np.array([[atomic_vdw_radius[x.upper()]] for x in elements])
dist_matrix = euclidean_distances(coordinates, com.reshape(1, -1))
re_dist_matrix = dist_matrix - atom_vdw
index = np.argmin(re_dist_matrix)
pored = re_dist_matrix[index][0] * 2
return (pored, index)
def correct_pore_diameter(com, *params):
"""Return negative of a pore diameter. (optimisation function)."""
elements, coordinates = params
return (-pore_diameter(elements, coordinates, com)[0])
def opt_pore_diameter(elements, coordinates, bounds=None, com=None, **kwargs):
"""Return optimised pore diameter and it's COM."""
args = elements, coordinates
if com is not None:
pass
else:
com = center_of_mass(elements, coordinates)
if bounds is None:
pore_r = pore_diameter(elements, coordinates, com=com)[0] / 2
bounds = (
(com[0]-pore_r, com[0]+pore_r),
(com[1]-pore_r, com[1]+pore_r),
(com[2]-pore_r, com[2]+pore_r)
)
minimisation = minimize(
correct_pore_diameter, x0=com, args=args, bounds=bounds)
pored = pore_diameter(elements, coordinates, com=minimisation.x)
return (pored[0], pored[1], minimisation.x)
def sphere_volume(sphere_radius):
"""Return volume of a sphere."""
return (4 / 3 * np.pi * sphere_radius**3)
def asphericity(S):
return (S[0] - (S[1] + S[2]) / 2)
def acylidricity(S):
return (S[1] - S[2])
def relative_shape_anisotropy(S):
return (1 - 3 * (
(S[0] * S[1] + S[0] * S[2] + S[1] * S[2]) / (np.sum(S))**2))
def get_tensor_eigenvalues(T, sort=False):
if sort:
return (sorted(np.linalg.eigvals(T), reverse=True))
else:
return (np.linalg.eigvals(T))
def get_gyration_tensor(elements, coordinates):
"""
Return the gyration tensor of a molecule.
The gyration tensor should be invariant to the molecule's position.
The known formulas for the gyration tensor have the correction for the
centre of mass of the molecule, therefore, the coordinates are first
corrected for the centre of mass and essentially shifted to the origin.
Parameters
----------
elements : numpy.ndarray
The array containing the molecule's elemental data.
coordinates : numpy.ndarray
The array containing the Cartesian coordinates of the molecule.
Returns
-------
numpy.ndarray
The gyration tensor of a molecule invariant to the molecule's position.
"""
# First calculate COM for correction.
com = centre_of_mass(elements, coordinates)
# Correct the coordinates for the COM.
coordinates = coordinates - com
# Calculate diagonal and then other values of the matrix.
diag = np.sum(coordinates**2, axis=0)
xy = np.sum(coordinates[:, 0] * coordinates[:, 1])
xz = np.sum(coordinates[:, 0] * coordinates[:, 2])
yz = np.sum(coordinates[:, 1] * coordinates[:, 2])
S = np.array([[diag[0], xy, xz], [xy, diag[1], yz],
[xz, yz, diag[2]]]) / coordinates.shape[0]
return (S)
def get_inertia_tensor(elements, coordinates):
"""
Return the tensor of inertia a molecule.
Parameters
----------
elements : numpy.ndarray
The array containing the molecule's elemental data.
coordinates : numpy.ndarray
The array containing the Cartesian coordinates of the molecule.
Returns
-------
numpy.ndarray
The tensor of inertia of a molecule.
"""
pow2 = coordinates**2
molecular_weight = np.array(
[[atomic_mass[e.upper()]] for e in elements])
diag_1 = np.sum(molecular_weight * (pow2[:, 1] + pow2[:, 2]))
diag_2 = np.sum(molecular_weight * (pow2[:, 0] + pow2[:, 2]))
diag_3 = np.sum(molecular_weight * (pow2[:, 0] + pow2[:, 1]))
mxy = np.sum(-molecular_weight * coordinates[:, 0] * coordinates[:, 1])
mxz = np.sum(-molecular_weight * coordinates[:, 0] * coordinates[:, 2])
myz = np.sum(-molecular_weight * coordinates[:, 1] * coordinates[:, 2])
inertia_tensor = np.array([[diag_1, mxy, mxz], [mxy, diag_2, myz],
[mxz, myz, diag_3]]) / coordinates.shape[0]
return (inertia_tensor)
def principal_axes(elements, coordinates):
return (np.linalg.eig(get_inertia_tensor(elements, coordinates))[1].T)
def normalize_vector(vector):
"""
Normalize a vector.
A new vector is returned, the original vector is not modified.
Parameters
----------
vector : np.array
The vector to be normalized.
Returns
-------
np.array
The normalized vector.
"""
v = np.divide(vector, np.linalg.norm(vector))
return np.round(v, decimals=4)
def rotation_matrix_arbitrary_axis(angle, axis):
"""
Return a rotation matrix of `angle` radians about `axis`.
Parameters
----------
angle : int or float
The size of the rotation in radians.
axis : numpy.array
A 3 element aray which represents a vector. The vector is the
axis about which the rotation is carried out.
Returns
-------
numpy.array
A 3x3 array representing a rotation matrix.
"""
axis = normalize_vector(axis)
a = np.cos(angle / 2)
b, c, d = axis * np.sin(angle / 2)
e11 = np.square(a) + np.square(b) - np.square(c) - np.square(d)
e12 = 2 * (b * c - a * d)
e13 = 2 * (b * d + a * c)
e21 = 2 * (b * c + a * d)
e22 = np.square(a) + np.square(c) - np.square(b) - np.square(d)
e23 = 2 * (c * d - a * b)
e31 = 2 * (b * d - a * c)
e32 = 2 * (c * d + a * b)
e33 = np.square(a) + np.square(d) - np.square(b) - np.square(c)
return np.array([[e11, e12, e13], [e21, e22, e23], [e31, e32, e33]])
def align_principal_ax(elements, coordinates):
""" """
coor = deepcopy(coordinates)
new_coor = []
rot = []
for i, j in zip([2, 1, 0], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]):
p_axes = principal_axes(elements, coordinates)
r_vec = np.cross(p_axes[i], np.array(j))
sin = np.linalg.norm(r_vec)
cos = np.dot(p_axes[i], np.array(j))
ang = np.arctan2(sin, cos)
R_mat = np.matrix(rotation_matrix_arbitrary_axis(ang, r_vec))
rot.append(R_mat)
for i in coor:
new_coord = R_mat * i.reshape(-1, 1)
new_coor.append(np.array(new_coord.reshape(1, -1))[0])
new_coor = np.array(new_coor)
coor = new_coor
new_coor = []
return (coor, rot)
def calc_asphericity(elements, coordinates):
inertia_tensor = get_inertia_tensor(elements, coordinates)
tensor_eigenvalues = get_tensor_eigenvalues(inertia_tensor, sort=True)
return asphericity(tensor_eigenvalues)
def calc_acylidricity(elements, coordinates):
inertia_tensor = get_inertia_tensor(elements, coordinates)
tensor_eigenvalues = get_tensor_eigenvalues(inertia_tensor, sort=True)
return acylidricity(tensor_eigenvalues)
def calc_relative_shape_anisotropy(elements, coordinates):
inertia_tensor = get_inertia_tensor(elements, coordinates)
tensor_eigenvalues = get_tensor_eigenvalues(inertia_tensor, sort=True)
return relative_shape_anisotropy(tensor_eigenvalues)
def unit_cell_to_lattice_array(cryst):
"""Return parallelpiped unit cell lattice matrix."""
a_, b_, c_, alpha, beta, gamma = cryst
# Convert angles from degrees to radians.
r_alpha = np.deg2rad(alpha)
r_beta = np.deg2rad(beta)
r_gamma = np.deg2rad(gamma)
# Calculate unit cell volume that is neccessary.
volume = a_ * b_ * c_ * (
1 - np.cos(r_alpha)**2 - np.cos(r_beta)**2 - np.cos(r_gamma)**2 + 2 *
np.cos(r_alpha) * np.cos(r_beta) * np.cos(r_gamma))**0.5
# Create the orthogonalisation Matrix (M^-1) - lattice matrix
a_x = a_
a_y = b_ * np.cos(r_gamma)
a_z = c_ * np.cos(r_beta)
b_x = 0
b_y = b_ * np.sin(r_gamma)
b_z = c_ * (
np.cos(r_alpha) - np.cos(r_beta) * np.cos(r_gamma)) / np.sin(r_gamma)
c_x = 0
c_y = 0
c_z = volume / (a_ * b_ * np.sin(r_gamma))
lattice_array = np.array(
[[a_x, a_y, a_z], [b_x, b_y, b_z], [c_x, c_y, c_z]])
return lattice_array
def lattice_array_to_unit_cell(lattice_array):
"""Return crystallographic param. from unit cell lattice matrix."""
cell_lengths = np.sqrt(np.sum(lattice_array**2, axis=0))
gamma_r = np.arccos(lattice_array[0][1] / cell_lengths[1])
beta_r = np.arccos(lattice_array[0][2] / cell_lengths[2])
alpha_r = np.arccos(
lattice_array[1][2] * np.sin(gamma_r) / cell_lengths[2]
+ np.cos(beta_r) * np.cos(gamma_r)
)
cell_angles = [
np.rad2deg(alpha_r), np.rad2deg(beta_r), np.rad2deg(gamma_r)
]
return np.append(cell_lengths, cell_angles)
def volume_from_lattice_array(lattice_array):
"""Return unit cell's volume from lattice matrix."""
return np.linalg.det(lattice_array)
def volume_from_cell_parameters(cryst):
"""Return unit cell's volume from crystallographic parameters."""
return volume_from_lattice_array(unit_cell_to_lattice_array(cryst))
def fractional_from_cartesian(coordinate, lattice_array):
"""Return a fractional coordinate from a cartesian one."""
deorthogonalisation_M = np.matrix(np.linalg.inv(lattice_array))
fractional = deorthogonalisation_M * coordinate.reshape(-1, 1)
return np.array(fractional.reshape(1, -1))
def cartisian_from_fractional(coordinate, lattice_array):
"""Return cartesian coordinate from a fractional one."""
orthogonalisation_M = np.matrix(lattice_array)
orthogonal = orthogonalisation_M * coordinate.reshape(-1, 1)
return np.array(orthogonal.reshape(1, -1))
def cart2frac_all(coordinates, lattice_array):
"""Convert all cartesian coordinates to fractional."""
frac_coordinates = deepcopy(coordinates)
for coord in range(frac_coordinates.shape[0]):
frac_coordinates[coord] = fractional_from_cartesian(
frac_coordinates[coord], lattice_array)
return frac_coordinates
def frac2cart_all(frac_coordinates, lattice_array):
"""Convert all fractional coordinates to cartesian."""
coordinates = deepcopy(frac_coordinates)
for coord in range(coordinates.shape[0]):
coordinates[coord] = cartisian_from_fractional(coordinates[coord],
lattice_array)
return coordinates
def create_supercell(system, supercell=[[-1, 1], [-1, 1], [-1, 1]]):
"""Create a supercell."""
if 'lattice' not in system.keys():
matrix = unit_cell_to_lattice_array(system['unit_cell'])
else:
matrix = system['lattice']
coordinates = deepcopy(system['coordinates'])
multiplication_matrices = []
for a_ in range(supercell[0][0], supercell[0][1] + 1):
for b_ in range(supercell[1][0], supercell[1][1] + 1):
for c_ in range(supercell[2][0], supercell[2][1] + 1):
mult_matrix = np.array([[a_, b_, c_]])
mult_matrix = np.repeat(
mult_matrix, coordinates.shape[0], axis=0)
multiplication_matrices.append(mult_matrix)
frac_coordinates = cart2frac_all(coordinates, matrix)
updated_coordinates = []
for mat in multiplication_matrices:
updated_coor = frac_coordinates + mat
updated_coordinates.append(updated_coor)
supercell_frac_coordinates = np.concatenate(updated_coordinates, axis=0)
supercell_coordinates = frac2cart_all(supercell_frac_coordinates, matrix)
# Now for each new cell in the supercell we need to repeat the
# elements array so that it maches
new_elements = deepcopy(system['elements'])
new_ids = deepcopy(system['atom_ids'])
for i in range(len(updated_coordinates) - 1):
new_elements = np.concatenate((new_elements, system['elements']))
new_ids = np.concatenate((new_ids, system['atom_ids']))
cryst = lattice_array_to_unit_cell(matrix)
supercell_system = {
'elements': new_elements,
'atom_ids': new_ids,
'coordinates': supercell_coordinates,
'unit_cell': cryst,
'lattice': matrix,
}
return supercell_system
def is_inside_polyhedron(point, polyhedron):
if polyhedron.shape == (1, 6):
matrix = unit_cell_to_lattice_array(polyhedron)
if polyhedron.shape == (3, 3):
matrix = polyhedron
frac_coord = pw.utilities.fractional_from_cartesian(point, matrix)[0]
if 0 <= frac_coord[0] <= 1.000 and 0 <= frac_coord[
1] <= 1.000 and 0 <= frac_coord[2] <= 1.000:
return True
else:
return False
def normal_vector(origin, vectors):
"""Return normal vector for two vectors with same origin."""
return np.cross(vectors[0] - origin, vectors[1] - origin)
def discrete_molecules(system, rebuild=None, tol=0.4):
"""
Decompose molecular system into individual discreet molecules.
Note
----
New formula for bonds: (26/07/17)
The two atoms, x and y, are considered bonded if the distance between
them, calculated with distance matrix, is within the ranges:
.. :math:
Rcov(x) + Rcov(y) - t < R(x,y) < Rcov(x) + Rcov(y) + t
where Rcov is the covalent radius and the tolarenace (t) is set to
0.4 Angstrom.
"""
# First we check which operation mode we use.
# 1) Non-periodic MolecularSystem.
# 2) Periodic MolecularSystem without rebuilding.
# 3) Periodic Molecular system with rebuilding (supercell provided).
if rebuild is not None:
mode = 3
else:
if 'unit_cell' in system.keys():
if system['unit_cell'].shape == (6,):
mode = 2
else:
mode = 1
elif 'lattice' in system.keys():
if system['lattice'].shape == (3, 3):
mode = 2
else:
mode = 1
else:
mode = 1
# We create a list containing all atoms, theirs periodic elements and
# coordinates. As this process is quite complicated, we need a list
# which we will gradually be reducing.
try:
elements = system['elements']
coordinates = system['coordinates']
except KeyError:
raise _FunctionError(
"The 'elements' key is missing in the 'system' dictionary "
"attribute of the MolecularSystem object. Which means, you need to"
" decipher the forcefield based atom keys first (see manual)."
)
coordinates = system['coordinates']
args = (elements, coordinates)
adj = 0
# If there are forcefield 'atom ids' as well we will retain them.
if 'atom_ids' in system.keys():
atom_ids = system['atom_ids']
args = (elements, atom_ids, coordinates)
adj = 1
atom_list = compose_atom_list(*args)
atom_coor = decompose_atom_list(atom_list)[1 + adj]
# Scenario 1: We load a non-periodic MolecularSystem.
# We will not have 'unit_cell' nor 'lattice' keywords in the dictionary
# and also we do not do any re-building.
# Scenario 2: We load a periodic MolecularSystem. We want to only Extract
# complete molecules that do not have been affected by the periodic
# boundary.
# Scenario 3: We load a periodic Molecular System. We want it to be rebuild
# therefore, we also provide a supercell.
# Scenarios 2 and 3 require a lattice and also their origin is at origin.
# Scenario 1 should have the origin at the center of mass of the system.
# EDIT 09-04-18: All origins/pseudo_origin had to be skewed towards some
# direction (x + 0.01) so that there would be no ambiguity in periodic
# ang highly symmetric systems where the choice of the closest atom would
# be random from a set of equally far choices - bug found in the testing
# this way rebuild system should always look the same from the same input
# and on different machines.
if mode == 2 or mode == 3:
# Scenarios 2 or 3.
origin = np.array([0.01, 0., 0.])
if 'lattice' not in system.keys():
matrix = unit_cell_to_lattice_array(system['unit_cell'])
else:
matrix = system['lattice']
pseudo_origin_frac = np.array([0.26, 0.25, 0.25])
pseudo_origin = cartisian_from_fractional(pseudo_origin_frac, matrix)
# If a supercell is also provided that encloses the unit cell for the
# reconstruction of the molecules through the periodic boundary.
if rebuild is not None:
selements = rebuild['elements']
sids = rebuild['atom_ids']
scoordinates = rebuild['coordinates']
satom_list = compose_atom_list(selements, sids, scoordinates)
satom_coor = decompose_atom_list(satom_list)[1 + adj]
# There is one more step. We need to sort out for all the
# reconstructed molecules, which are the ones that belong to the
# unit cell. As we did the reconstruction to every chunk in the unit
# cell we have now some molecules that belong to neighbouring cells.
# The screening is simple. If the COM of a molecule translated to
# fractional coordinates (so that it works for parallelpiped) is
# within the unit cell boundaries <0, 1> then it's it. There is
# an exception, for the trajectories, very often the unit cell
# is centered at origin. Therefore we need to use <-0.5, 0.5>
# boundary. We will simply decide which is the case by calculating
# the centre of mass of the whole system.
system_com = center_of_mass(elements, coordinates)
if np.allclose(system_com, origin, atol=1e-00):
boundary = np.array([-0.5, 0.5])
else:
boundary = np.array([0., 1.])
else:
# Scenario 1.
pseudo_origin = center_of_mass(
elements, coordinates) + np.array([0.01, 0., 0.])
# Here the final discrete molecules will be stored.
molecules = []
# Exceptions. Usually end-point atoms that create single bonds or
# just a separate atoms in the system.
exceptions = ['H', 'CL', 'BR', 'F', 'HE', 'AR', 'NE', 'KR', 'XE', 'RN']
# The upper limit for distances analysed for bonds will be assigned for
# a given system (to save time). We take set('elements') and then find
# the largest R(cov) in the system and set the max_dist as a double
# of it plus the 150% tolerance (tol).
set_of_elements = set(system['elements'])
max_r_cov = max([
atomic_covalent_radius[i.upper()] for i in set_of_elements])
max_dist = 2 * max_r_cov + tol
# We continue untill all items in the list have been analysed and popped.
while atom_list:
inside_atoms_heavy = [
i for i in atom_list if i[0].upper() not in exceptions
]
if inside_atoms_heavy:
# Now we create an array of atom coordinates. It does seem
# somehow counter-intuitive as this is what we started with
# and made it into a list. But, in my opinion it's the only
# way to do it. It's hard to control and delete items in two
# separate arrays that we started with and we don't want
# atoms already assigned in our array for distance matrix.
inside_atoms_coord_heavy = decompose_atom_list(inside_atoms_heavy)[
1 + adj]
dist_matrix = euclidean_distances(inside_atoms_coord_heavy,
pseudo_origin.reshape(1, -1))
atom_index_x, _ = np.unravel_index(dist_matrix.argmin(),
dist_matrix.shape)
# Added this so that lone atoms (even if heavy) close to the
# periodic boundary are not analysed, as they surely have matching
# symmetry equivalence that bind to a bigger atom cluster inside
# the unit_cell.
potential_starting_point = inside_atoms_heavy[atom_index_x]
pot_arr = np.array(potential_starting_point[1 + adj:])
dist_matrix = euclidean_distances(
atom_coor, pot_arr.reshape(1, -1)
)
idx = (dist_matrix > 0.1) * (dist_matrix < max_dist)
if len(idx) < 1:
pass
else:
working_list = [potential_starting_point]
else:
# Safety check.
break
final_molecule = []
while working_list:
working_list_temp = []
try:
atom_coor = decompose_atom_list(atom_list)[1 + adj]
except _FunctionError:
atom_coor = None
for i in working_list:
if i[0].upper() not in exceptions:
# It's of GREATEST importance that the i_arr variable
# is assigned here before entering the atom_coor loop.!
# Otherwise it will not be re-asigned when the satom_list
# still iterates, but the atom_list is already empty...
i_arr = np.array(i[1 + adj:])
if atom_coor is not None:
dist_matrix = euclidean_distances(
atom_coor, i_arr.reshape(1, -1)
)
idx = (dist_matrix > 0.1) * (dist_matrix < max_dist)
neighbours_indexes = np.where(idx)[0]
for j in neighbours_indexes:
j_arr = np.array(atom_coor[j])
r_i_j = distance(i_arr, j_arr)
r_cov_i_j = atomic_covalent_radius[
i[0].upper()] + atomic_covalent_radius[
atom_list[j][0].upper()]
if r_cov_i_j - tol < r_i_j < r_cov_i_j + tol:
working_list_temp.append(atom_list[j])
if rebuild is not None:
sdist_matrix = euclidean_distances(
satom_coor, i_arr.reshape(1, -1))
sidx = (sdist_matrix > 0.1) * (sdist_matrix < max_dist)
sneighbours_indexes = np.where(sidx)[0]
for j in sneighbours_indexes:
if satom_list[j] in atom_list:
pass
else:
j_arr = np.array(satom_coor[j])
r_i_j = distance(i_arr, j_arr)
r_cov_i_j = atomic_covalent_radius[
i[0].upper()
] + atomic_covalent_radius[
satom_list[j][0].upper()]
if r_cov_i_j - tol < r_i_j < r_cov_i_j + tol:
working_list_temp.append(satom_list[j])
final_molecule.append(i)
else:
final_molecule.append(i)
for i in working_list:
try:
atom_list.remove(i)
except ValueError:
pass
# We empty the working list as all the items were analysed
# and moved to the final_molecule list.
working_list = []
# We make sure there are no duplicates in the working_list_temp.
working_list_temp = unique(working_list_temp)
# Now we move the entries from the temporary working list
# to the working list for looping analysys.
for i in working_list_temp:
# We make sure that only new and unassigned atoms are
# being transfered.
if i not in final_molecule:
working_list.append(i)
final_molecule_dict = {}
final_molecule_dict['elements'] = np.array(
[x[0] for x in final_molecule], dtype='str')
final_molecule_dict['coordinates'] = np.array(
[[*xyz[1 + adj:]] for xyz in final_molecule])
if adj == 1:
final_molecule_dict['atom_ids'] = np.array(
[x[1] for x in final_molecule], dtype='str')
# In general we always want the molecule so the initial bool_ is True.
bool_ = True
# But, for periodic only if the molecule is in the initial unit cell.
if rebuild is not None:
com = center_of_mass(final_molecule_dict['elements'],
final_molecule_dict['coordinates'])
com_frac = fractional_from_cartesian(com, matrix)[0]
# If we don't round the numerical errors will come up.
com_frac_round = np.around(com_frac, decimals=8)
bool_ = np.all(np.logical_and(com_frac_round >= boundary[0],
com_frac_round < boundary[1]),
axis=0)
if bool(bool_) is True:
molecules.append(final_molecule_dict)
return molecules
def angle_between_vectors(x, y):
"""Calculate the angle between two vectors x and y."""
first_step = abs(x[0] * y[0] + x[1] * y[1] + x[2] * y[2]) / (
np.sqrt(x[0]**2 + x[1]**2 + x[2]**2) *
np.sqrt(y[0]**2 + y[1]**2 + y[2]**2))
second_step = np.arccos(first_step)
return (second_step)
def vector_analysis(vector, coordinates, elements_vdw, increment=1.0):
"""Analyse a sampling vector's path for window analysis purpose."""
# Calculate number of chunks if vector length is divided by increment.
chunks = int(np.linalg.norm(vector) // increment)
# Create a single chunk.
chunk = vector / chunks
# Calculate set of points on vector's path every increment.
vector_pathway = np.array([chunk * i for i in range(chunks + 1)])
analysed_vector = np.array([
np.amin(
euclidean_distances(coordinates, i.reshape(1, -1)) - elements_vdw)
for i in vector_pathway
])
if all(i > 0 for i in analysed_vector):
pos = np.argmin(analysed_vector)
# As first argument we need to give the distance from the origin.
dist = np.linalg.norm(chunk * pos)
return np.array(
[dist, analysed_vector[pos] * 2, *chunk * pos, *vector])
def vector_preanalysis(vector, coordinates, elements_vdw, increment=1.0):
norm_vec = vector/np.linalg.norm(vector)
intersections = []
origin = center_of_coor(coordinates)
L = coordinates - origin
t_ca = np.dot(L, norm_vec)
d = np.sqrt(np.einsum('ij,ij->i', L, L) - t_ca**2)
under_sqrt = elements_vdw**2 - d**2
diag = under_sqrt.diagonal()
positions = np.argwhere(diag > 0)
for pos in positions:
t_hc = np.sqrt(diag[pos[0]])
t_0 = t_ca[pos][0] - t_hc
t_1 = t_ca[pos][0] + t_hc
P_0 = origin + np.dot(t_0, norm_vec)
P_1 = origin + np.dot(t_1, norm_vec)
# print(np.linalg.norm(P_0), np.linalg.norm(P_1))
if np.linalg.norm(P_0) < np.linalg.norm(P_1):
intersections.append(1)
else:
intersections.append(0)
if sum(intersections) == 0:
return vector_analysis(vector, coordinates, elements_vdw, increment)
def optimise_xy(xy, *args):
"""Return negative pore diameter for x and y coordinates optimisation."""
z, elements, coordinates = args
window_com = np.array([xy[0], xy[1], z])
return -pore_diameter(elements, coordinates, com=window_com)[0]
def optimise_z(z, *args):
"""Return pore diameter for coordinates optimisation in z direction."""
x, y, elements, coordinates = args
window_com = np.array([x, y, z])
return pore_diameter(elements, coordinates, com=window_com)[0]
def window_analysis(window,
elements,
coordinates,
elements_vdw,
increment2=0.1,
z_bounds=[None, None],
lb_z=True,
z_second_mini=False,
**kwargs):
"""
Return window diameter and window's centre.
Parameters
----------
widnow: list
elements: numpy.array
coordinates: numpy.array
elements_vdw: numpy.array
step: float
"""
# Copy the coordinates as we will manipulate them.
coordinates = deepcopy(coordinates)
# Find the vector with the largest window sampling diameter from the pool.
vector_ = window[window.argmax(axis=0)[1]][5:8]
vector_analysed = vector_analysis(
vector_, coordinates, elements_vdw, increment=increment2)
# A safety check, if the refined analysis give None we end the function.
if vector_analysed is not None:
pass
else:
return None
vector = vector_analysed[5:8]
# Unit vectors.
vec_a = [1, 0, 0]
vec_b = [0, 1, 0]
vec_c = [0, 0, 1]
# Angles needed for rotation (in radians) to rotate and translate the
# molecule for the vector to become the Z-axis.
angle_1 = angle_between_vectors(np.array([vector[0], vector[1], 0]), vec_a)
angle_2 = angle_between_vectors(vector, vec_c)
# Depending in which cartesian coordinate system area the vector is
# We need a rotation into a different direction and by different value.
if vector[0] >= 0 and vector[1] >= 0 and vector[2] >= 0:
angle_1 = -angle_1
angle_2 = -angle_2
if vector[0] < 0 and vector[1] >= 0 and vector[2] >= 0:
angle_1 = np.pi * 2 + angle_1
angle_2 = angle_2
if vector[0] >= 0 and vector[1] < 0 and vector[2] >= 0:
angle_1 = angle_1
angle_2 = -angle_2
if vector[0] < 0 and vector[1] < 0 and vector[2] >= 0:
angle_1 = np.pi * 2 - angle_1
if vector[0] >= 0 and vector[1] >= 0 and vector[2] < 0:
angle_1 = -angle_1
angle_2 = np.pi + angle_2
if vector[0] < 0 and vector[1] >= 0 and vector[2] < 0:
angle_2 = np.pi - angle_2
if vector[0] >= 0 and vector[1] < 0 and vector[2] < 0:
angle_2 = angle_2 + np.pi
if vector[0] < 0 and vector[1] < 0 and vector[2] < 0:
angle_1 = -angle_1
angle_2 = np.pi - angle_2
# Rotation matrix for rotation around Z-axis with angle_1.
rotation_around_z = np.array([[np.cos(angle_1), -np.sin(angle_1), 0],
[np.sin(angle_1), np.cos(angle_1), 0],
[0, 0, 1]])
# Rotate the whole molecule around with rotation_around_z.
coordinates = np.array([np.dot(rotation_around_z, i) for i in coordinates])
# Rotation matrix for rotation around Y-axis with angle_2
rotation_around_y = np.array([[np.cos(angle_2), 0, np.sin(angle_2)],
[0, 1, 0],
[-np.sin(angle_2), 0, np.cos(angle_2)]])
# Rotate the whole molecule around with rotation_around_y.
coordinates = np.array([np.dot(rotation_around_y, i) for i in coordinates])
# Third step is translation. We are now at [0, 0, -z].
# We shift the molecule so that center of the window is at the origin.
# The `z` is from original vector analysis. It is the point on the vector
# where the largest sampling sphere was (vector_analysed[0]).
new_z = vector_analysed[0]
# Translate the whole molecule to shift window's center to origin.
coordinates = coordinates - np.array([[0, 0, new_z]] *
coordinates.shape[0])
# !!!Here the window center (xy and z) optimisation take place!!!
window_com = np.array([0, 0, 0], dtype=float)
# The lb_z parameter is 'lower bound equal to z' which means,
# that we set the lower bound for the z optimisation to be equal
# to the -new_z as in some cages it's the COM - pore that is the
# limiting diameter. But, no lower than new_z because we don't want to
# move into the other direction.
if lb_z:
z_bounds[0] = -new_z
window_diameter, _ = pore_diameter(elements, coordinates, com=window_com)
# SciPy minimisation on z coordinate.
z_args = (window_com[0], window_com[1], elements, coordinates)
z_optimisation = minimize(
optimise_z, x0=window_com[2], args=z_args, bounds=[z_bounds])
# Substitute the z coordinate for a minimised one.
window_com[2] = z_optimisation.x[0]
# SciPy brute optimisation on x and y coordinates in window plane.
xy_args = (window_com[2], elements, coordinates)
xy_bounds = ((-window_diameter / 2, window_diameter / 2),
(-window_diameter / 2, window_diameter / 2))
xy_optimisation = brute(
optimise_xy, xy_bounds, args=xy_args, full_output=True, finish=fmin)
# Substitute the x and y coordinates for the optimised ones.
window_com[0] = xy_optimisation[0][0]
window_com[1] = xy_optimisation[0][1]
# Additional SciPy minimisation on z coordinate. Added on 18 May 2017.
# We can argue which aproach is best. Whether z opt and then xy opt
# or like now z opt -> xy opt -> additional z opt etc. I have also tested
# a loop of optimisations until some convergence and optimisation of
# xyz coordinates at the same time by optimising these two optimisations.
# In the end. I think this approach is best for cages.
# Update 20 October 2017: I made this optional and turned off by default
# In many cases that worsen the quality of the results and should be used
# with caution.
if z_second_mini is not False:
z_args = (window_com[0], window_com[1], elements, coordinates)
# The z_bounds should be passed in kwargs.
z_optimisation = minimize(
optimise_z, x0=window_com[2], args=z_args, bounds=[z_bounds])
# Substitute the z coordinate for a minimised one.
window_com[2] = z_optimisation.x[0]
# Calculate the new window diameter.
window_diameter, _ = pore_diameter(elements, coordinates, com=window_com)
# To get the window true centre of mass we need to revere the rotation and
# translation operations on the window com.
# Reverse the translation by substracting the new_z.
window_com[2] = window_com[2] + new_z
angle_2_1 = -angle_2
reverse_around_y = np.array([[np.cos(angle_2_1), 0, np.sin(angle_2_1)],
[0, 1, 0],
[-np.sin(angle_2_1), 0, np.cos(angle_2_1)]])
# Reversing the second rotation around Y-axis.
window_com = np.dot(reverse_around_y, window_com)
angle_1_1 = -angle_1
reverse_around_z = np.array([[np.cos(angle_1_1), -np.sin(angle_1_1), 0],
[np.sin(angle_1_1), np.cos(angle_1_1), 0],
[0, 0, 1]])
# Reversing the first rotation around Z-axis.
window_com = np.dot(reverse_around_z, window_com)
return (window_diameter, window_com)
def find_windows(elements,
coordinates,
processes=None,
mol_size=None,
adjust=1,
pore_opt=True,
increment=1.0,
**kwargs):
"""Return windows diameters and center of masses for a molecule."""
# Copy the coordinates as will perform many opertaions on them
coordinates = deepcopy(coordinates)
# Center of our cartesian system is always at origin
origin = np.array([0, 0, 0])
# Initial center of mass to reverse translation at the end
initial_com = center_of_mass(elements, coordinates)
# Shift the cage to the origin using either the standard center of mass
# or if pore_opt flag is True, the optimised pore center as center of mass
if pore_opt is True:
# Normally the pore is calculated from the COM of a molecule.
# So, esentially the molecule's COM is the pore center.
# To shift the molecule so that the center of the optimised pore
# is at the origin of the system and not the center of the not
# optimised one, we need to adjust the shift. We also have to update
# the initial com.
com_adjust = initial_com - opt_pore_diameter(elements, coordinates, **
kwargs)[2]
initial_com = initial_com - com_adjust
coordinates = shift_com(elements, coordinates, com_adjust=com_adjust)
else:
# Otherwise, we just shift the cage to the origin.
coordinates = shift_com(elements, coordinates)
# We create an array of vdw radii of elements.
elements_vdw = np.array([[atomic_vdw_radius[x.upper()]] for x in elements])
# We calculate maximum diameter of a molecule to determine the radius
# of a sampling sphere neccessary to enclose the whole molecule.
shpere_radius = max_dim(elements, coordinates)[2] / 2
sphere_surface_area = 4 * np.pi * shpere_radius**2
# Here we determine the number of sampling points necessary for a fine
# sampling. Smaller molecules require more finner density of sampling
# points on the sampling sphere's surface, whereas largen require less.
# This formula was created so that larger molecule do not take much longer
# to analyse, as number_sampling_points*length_of_sampling_vectors
# results in quadratic increase of sampling time. The 250 factor was
# specificly determined to produce close to 1 sampling point /Angstrom^2
# for a sphere of radius ~ 24 Angstrom. We can adjust how fine is the
# sampling by changing the adjust factor.
number_of_points = int(np.log10(sphere_surface_area) * 250 * adjust)
# Here I use code by <NAME> for spreading points on a sphere:
# http://blog.marmakoide.org/?p=1
golden_angle = np.pi * (3 - np.sqrt(5))
theta = golden_angle * np.arange(number_of_points)
z = np.linspace(1 - 1.0 / number_of_points, 1.0 / number_of_points - 1.0,
number_of_points)
radius = np.sqrt(1 - z * z)
points = np.zeros((number_of_points, 3))
points[:, 0] = radius * np.cos(theta) * shpere_radius
points[:, 1] = radius * np.sin(theta) * shpere_radius
points[:, 2] = z * shpere_radius
# Here we will compute the eps parameter for the sklearn.cluster.DBSCAN
# (3-dimensional spatial clustering algorithm) which is the mean distance
# to the closest point of all points.
values = []
tree = KDTree(points)
for i in points:
dist, ind = tree.query(i.reshape(1, -1), k=10)
values.extend(dist)
mean_distance = np.mean(values)
# The best eps is parametrized when adding the mean distance and it's root.
eps = mean_distance + mean_distance**0.5
# Here we either run the sampling points vectors analysis in serial
# or parallel. The vectors that go through molecular pores return
# as analysed list with the increment at vector's path with largest
# included sphere, coordinates for this narrow channel point. vectors
# that find molecule on theirs path are return as NoneType object.
# Parralel analysis on user's defined number of CPUs.
if processes:
pool = Pool(processes=processes)
parallel = [
pool.apply_async(
vector_preanalysis,
args=(
point,
coordinates,
elements_vdw, ),
kwds={'increment': increment}) for point in points
]
results = [p.get() for p in parallel if p.get() is not None]
pool.terminate()
# Dataset is an array of sampling points coordinates.
dataset = np.array([x[5:8] for x in results])
else:
results = [
vector_preanalysis(
point, coordinates, elements_vdw, increment=increment)
for point in points
]
results = [x for x in results if x is not None]
dataset = np.array([x[5:8] for x in results])
# If not a single vector was returned from the analysis it mean that
# no molecular channels (what we call windows here) connects the
# molecule's interior with the surroungsings (exterior space).
# The number of windows in that case equals zero and zero is returned.
# Otherwise we continue our search for windows.
if len(results) == 0:
return None
else:
# Perfomr DBSCAN to cluster the sampling points vectors.
# the n_jobs will be developed later.
# db = DBSCAN(eps=eps, n_jobs=_ncpus).fit(dataset)
db = DBSCAN(eps=eps).fit(dataset)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = set(db.labels_)
# Assing cluster label to a sampling point.
clusters = [[i, j] for i, j in zip(results, db.labels_)]
clustered_results = {label: [] for label in labels}
# Create a dictionary of clusters with points listed.
[clustered_results[i[1]].append(i[0]) for i in clusters]
# No for the sampling point vector in each cluster that had
# the widest channel's 'neck' is assumed to pass the closest
# to the window's center and therefore will be passed to
# window analysis function.
# We also pass user defined settings for window analysis.
# Again either in serlia or in parallel.
# Noisy points get a cluster label -1, therefore we have to exclude it.
if processes:
pool = Pool(processes=processes)
parallel = [
pool.apply_async(
window_analysis,
args=(np.array(clustered_results[cluster]), elements,
coordinates, elements_vdw),
kwds=kwargs) for cluster in clustered_results
if cluster != -1
]
window_results = [p.get() for p in parallel if p.get() is not None]
pool.terminate()
else:
window_results = [
window_analysis(
np.array(clustered_results[cluster]), elements,
coordinates, elements_vdw, **kwargs)
for cluster in clustered_results if cluster != -1
]
# The function returns two numpy arrays, one with windows diameters
# in Angstrom, second with corresponding windows center's coordinates
windows = np.array([result[0] for result in window_results
if result is not None])
windows_coms = np.array(
[np.add(result[1], initial_com) for result in window_results
if result is not None])
# Safety measures, if one of the windows is None or negative a warning
# should be raised.
for result in window_results:
if result is None:
msg_ = " ".join(
['Warning. One of the analysed windows has',
'returned as None. See manual.']
)
# print(msg_)
elif result[0] < 0:
msg_ = " ".join(
['Warning. One of the analysed windows has a vdW',
'corrected diameter smaller than 0. See manual.']
)
# print(msg_)
return (windows, windows_coms)
def window_shape(window,
elements,
coordinates,
increment2=0.1,
z_bounds=[None, None],
lb_z=True,
z_second_mini=False,
**kwargs):
"""
Return window diameter and window's centre.
Parameters
----------
widnow: list
elements: numpy.array
coordinates: numpy.array
elements_vdw: numpy.array
step: float
"""
# Copy the coordinates as we will manipulate them.
coordinates = deepcopy(coordinates)
# We create an array of vdw radii of elements.
elements_vdw = np.array([[atomic_vdw_radius[x.upper()]] for x in elements])
# Find the vector with the largest window sampling diameter from the pool.
vector_ = window[window.argmax(axis=0)[1]][5:8]
vector_analysed = vector_analysis(
vector_, coordinates, elements_vdw, increment=increment2)
# A safety check, if the refined analysis give None we end the function.
if vector_analysed is not None:
pass
else:
return None
vector = vector_analysed[5:8]
# Unit vectors.
vec_a = [1, 0, 0]
vec_b = [0, 1, 0]
vec_c = [0, 0, 1]
# Angles needed for rotation (in radians) to rotate and translate the
# molecule for the vector to become the Z-axis.
angle_1 = angle_between_vectors(np.array([vector[0], vector[1], 0]), vec_a)
angle_2 = angle_between_vectors(vector, vec_c)
# Depending in which cartesian coordinate system area the vector is
# We need a rotation into a different direction and by different value.
if vector[0] >= 0 and vector[1] >= 0 and vector[2] >= 0:
angle_1 = -angle_1
angle_2 = -angle_2
if vector[0] < 0 and vector[1] >= 0 and vector[2] >= 0:
angle_1 = np.pi * 2 + angle_1
angle_2 = angle_2
if vector[0] >= 0 and vector[1] < 0 and vector[2] >= 0:
angle_1 = angle_1
angle_2 = -angle_2
if vector[0] < 0 and vector[1] < 0 and vector[2] >= 0:
angle_1 = np.pi * 2 - angle_1
if vector[0] >= 0 and vector[1] >= 0 and vector[2] < 0:
angle_1 = -angle_1
angle_2 = np.pi + angle_2
if vector[0] < 0 and vector[1] >= 0 and vector[2] < 0:
angle_2 = np.pi - angle_2
if vector[0] >= 0 and vector[1] < 0 and vector[2] < 0:
angle_2 = angle_2 + np.pi
if vector[0] < 0 and vector[1] < 0 and vector[2] < 0:
angle_1 = -angle_1
angle_2 = np.pi - angle_2
# Rotation matrix for rotation around Z-axis with angle_1.
rotation_around_z = np.array([[np.cos(angle_1), -np.sin(angle_1), 0],
[np.sin(angle_1), np.cos(angle_1), 0],
[0, 0, 1]])
# Rotate the whole molecule around with rotation_around_z.
coordinates = np.array([np.dot(rotation_around_z, i) for i in coordinates])
# Rotation matrix for rotation around Y-axis with angle_2
rotation_around_y = np.array([[np.cos(angle_2), 0, np.sin(angle_2)],
[0, 1, 0],
[-np.sin(angle_2), 0, np.cos(angle_2)]])
# Rotate the whole molecule around with rotation_around_y.
coordinates = np.array([np.dot(rotation_around_y, i) for i in coordinates])
# Third step is translation. We are now at [0, 0, -z].
# We shift the molecule so that center of the window is at the origin.
# The `z` is from original vector analysis. It is the point on the vector
# where the largest sampling sphere was (vector_analysed[0]).
new_z = vector_analysed[0]
# Translate the whole molecule to shift window's center to origin.
coordinates = coordinates - np.array([[0, 0, new_z]] *
coordinates.shape[0])
# !!!Here the window center (xy and z) optimisation take place!!!
window_com = np.array([0, 0, 0], dtype=float)
# The lb_z parameter is 'lower bound equal to z' which means,
# that we set the lower bound for the z optimisation to be equal
# to the -new_z as in some cages it's the COM - pore that is the
# limiting diameter. But, no lower than new_z because we don't want to
# move into the other direction.
if lb_z:
z_bounds[0] = -new_z
window_diameter, _ = pore_diameter(elements, coordinates, com=window_com)
# SciPy minimisation on z coordinate.
z_args = (window_com[0], window_com[1], elements, coordinates)
z_optimisation = minimize(
optimise_z, x0=window_com[2], args=z_args, bounds=[z_bounds])
# Substitute the z coordinate for a minimised one.
window_com[2] = z_optimisation.x[0]
# SciPy brute optimisation on x and y coordinates in window plane.
xy_args = (window_com[2], elements, coordinates)
xy_bounds = ((-window_diameter / 2, window_diameter / 2),
(-window_diameter / 2, window_diameter / 2))
xy_optimisation = brute(
optimise_xy, xy_bounds, args=xy_args, full_output=True, finish=fmin)
# Substitute the x and y coordinates for the optimised ones.
window_com[0] = xy_optimisation[0][0]
window_com[1] = xy_optimisation[0][1]
# Additional SciPy minimisation on z coordinate. Added on 18 May 2017.
# We can argue which aproach is best. Whether z opt and then xy opt
# or like now z opt -> xy opt -> additional z opt etc. I have also tested
# a loop of optimisations until some convergence and optimisation of
# xyz coordinates at the same time by optimising these two optimisations.
# In the end. I think this approach is best for cages.
# Update 20 October 2017: I made this optional and turned off by default
# In many cases that worsen the quality of the results and should be used
# with caution.
if z_second_mini is not False:
z_args = (window_com[0], window_com[1], elements, coordinates)
# The z_bounds should be passed in kwargs.
z_optimisation = minimize(
optimise_z, x0=window_com[2], args=z_args, bounds=[z_bounds])
# Substitute the z coordinate for a minimised one.
window_com[2] = z_optimisation.x[0]
# Getting the 2D plane crosssection of a window in XY plain. (10-04-18)
# First translation around Z axis.
vectors_translated = [
[
np.dot(rotation_around_z, i[5:])[0],
np.dot(rotation_around_z, i[5:])[1],
np.dot(rotation_around_z, i[5:])[2],
] for i in window
]
# Second rotation around Y axis.
vectors_translated = [
[
np.dot(rotation_around_y, i)[0],
np.dot(rotation_around_y, i)[1],
np.dot(rotation_around_y, i)[2]
] for i in vectors_translated
]
ref_distance = (new_z - window_com[2]) / np.linalg.norm(vector)
# Cutting the XY plane.
XY_plane = np.array(
[
[i[0] * ref_distance, i[1] * ref_distance]
for i in vectors_translated
]
)
return XY_plane
def find_windows_new(elements,
coordinates,
processes=None,
mol_size=None,
adjust=1,
pore_opt=True,
increment=1.0,
**kwargs):
"""Return windows diameters and center of masses for a molecule."""
# Copy the coordinates as will perform many opertaions on them
coordinates = deepcopy(coordinates)
# Center of our cartesian system is always at origin
origin = np.array([0, 0, 0])
# Initial center of mass to reverse translation at the end
initial_com = center_of_mass(elements, coordinates)
# Shift the cage to the origin using either the standard center of mass
# or if pore_opt flag is True, the optimised pore center as center of mass
if pore_opt is True:
# Normally the pore is calculated from the COM of a molecule.
# So, esentially the molecule's COM is the pore center.
# To shift the molecule so that the center of the optimised pore
# is at the origin of the system and not the center of the not
# optimised one, we need to adjust the shift. We also have to update
# the initial com.
com_adjust = initial_com - opt_pore_diameter(elements, coordinates, **
kwargs)[2]
initial_com = initial_com - com_adjust
coordinates = shift_com(elements, coordinates, com_adjust=com_adjust)
else:
# Otherwise, we just shift the cage to the origin.
coordinates = shift_com(elements, coordinates)
# We create an array of vdw radii of elements.
elements_vdw = np.array([[atomic_vdw_radius[x.upper()]] for x in elements])
# We calculate maximum diameter of a molecule to determine the radius
# of a sampling sphere neccessary to enclose the whole molecule.
shpere_radius = max_dim(elements, coordinates)[2] / 2
sphere_surface_area = 4 * np.pi * shpere_radius**2
# Here we determine the number of sampling points necessary for a fine
# sampling. Smaller molecules require more finner density of sampling
# points on the sampling sphere's surface, whereas largen require less.
# This formula was created so that larger molecule do not take much longer
# to analyse, as number_sampling_points*length_of_sampling_vectors
# results in quadratic increase of sampling time. The 250 factor was
# specificly determined to produce close to 1 sampling point /Angstrom^2
# for a sphere of radius ~ 24 Angstrom. We can adjust how fine is the
# sampling by changing the adjust factor.
number_of_points = int(np.log10(sphere_surface_area) * 250 * adjust)
# Here I use code by <NAME> for spreading points on a sphere:
# http://blog.marmakoide.org/?p=1
golden_angle = np.pi * (3 - np.sqrt(5))
theta = golden_angle * np.arange(number_of_points)
z = np.linspace(1 - 1.0 / number_of_points, 1.0 / number_of_points - 1.0,
number_of_points)
radius = np.sqrt(1 - z * z)
points = np.zeros((number_of_points, 3))
points[:, 0] = radius * np.cos(theta) * shpere_radius
points[:, 1] = radius * np.sin(theta) * shpere_radius
points[:, 2] = z * shpere_radius
# Here we will compute the eps parameter for the sklearn.cluster.DBSCAN
# (3-dimensional spatial clustering algorithm) which is the mean distance
# to the closest point of all points.
values = []
tree = KDTree(points)
for i in points:
dist, ind = tree.query(i.reshape(1, -1), k=10)
values.extend(dist)
mean_distance = np.mean(values)
# The best eps is parametrized when adding the mean distance and it's root.
eps = mean_distance + mean_distance**0.5
# Here we either run the sampling points vectors analysis in serial
# or parallel. The vectors that go through molecular pores return
# as analysed list with the increment at vector's path with largest
# included sphere, coordinates for this narrow channel point. vectors
# that find molecule on theirs path are return as NoneType object.
# Parralel analysis on user's defined number of CPUs.
if processes:
pool = Pool(processes=processes)
parallel = [
pool.apply_async(
vector_preanalysis,
args=(
point,
coordinates,
elements_vdw, ),
kwds={'increment': increment}) for point in points
]
results = [p.get() for p in parallel if p.get() is not None]
pool.terminate()
# Dataset is an array of sampling points coordinates.
dataset = np.array([x[5:8] for x in results])
else:
results = [
vector_preanalysis(
point, coordinates, elements_vdw, increment=increment)
for point in points
]
results = [x for x in results if x is not None]
dataset = np.array([x[5:8] for x in results])
# If not a single vector was returned from the analysis it mean that
# no molecular channels (what we call windows here) connects the
# molecule's interior with the surroungsings (exterior space).
# The number of windows in that case equals zero and zero is returned.
# Otherwise we continue our search for windows.
if len(results) == 0:
return None
else:
# Perfomr DBSCAN to cluster the sampling points vectors.
# the n_jobs will be developed later.
# db = DBSCAN(eps=eps, n_jobs=_ncpus).fit(dataset)
db = DBSCAN(eps=eps).fit(dataset)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = set(db.labels_)
# Assing cluster label to a sampling point.
clusters = [[i, j] for i, j in zip(results, db.labels_)]
clustered_results = {label: [] for label in labels}
# Create a dictionary of clusters with points listed.
[clustered_results[i[1]].append(i[0]) for i in clusters]
return clustered_results, elements, coordinates, initial_com
def calculate_window_diameter(window, elements, coordinates, **kwargs):
elements_vdw = np.array(
[[atomic_vdw_radius[x.upper()]] for x in elements]
)
window_results = window_analysis(
np.array(window), elements, coordinates, elements_vdw, **kwargs
)
# The function returns two numpy arrays, one with windows diameters
# in Angstrom, second with corresponding windows center's coordinates
if window_results:
return window_results[0]
else:
return None
def get_window_com(window, elements, coordinates, initial_com, **kwargs):
elements_vdw = np.array(
[[atomic_vdw_radius[x.upper()]] for x in elements]
)
window_results = window_analysis(
np.array(window), elements, coordinates, elements_vdw, **kwargs
)
# The function returns two numpy arrays, one with windows diameters
# in Angstrom, second with corresponding windows center's coordinates
if window_results:
# I correct the COM of window for the initial COM of the cage
return np.add(window_results[1], initial_com)
else:
return None
def vector_analysis_reversed(vector, coordinates, elements_vdw):
norm_vec = vector/np.linalg.norm(vector)
intersections = []
origin = center_of_coor(coordinates)
L = coordinates - origin
t_ca = np.dot(L, norm_vec)
d = np.sqrt(np.einsum('ij,ij->i', L, L) - t_ca**2)
under_sqrt = elements_vdw**2 - d**2
diag = under_sqrt.diagonal()
positions = np.argwhere(diag > 0)
for pos in positions:
t_hc = np.sqrt(diag[pos[0]])
t_0 = t_ca[pos][0] - t_hc
t_1 = t_ca[pos][0] + t_hc
P_0 = origin + np.dot(t_0, norm_vec)
P_1 = origin + np.dot(t_1, norm_vec)
if np.linalg.norm(P_0) < np.linalg.norm(P_1):
intersections.append([np.linalg.norm(P_1), P_1])
if intersections:
intersection = sorted(intersections, reverse=True)[0][1]
dist_origin = np.linalg.norm(intersection)
return [dist_origin, intersection]
def find_average_diameter(elements, coordinates, adjust=1, increment=0.1,
processes=None, **kwargs):
"""Return average diameter for a molecule."""
# Copy the coordinates as will perform many opertaions on them
coordinates = deepcopy(coordinates)
# Center of our cartesian system is always at origin
origin = np.array([0, 0, 0])
# Initial center of mass to reverse translation at the end
initial_com = center_of_mass(elements, coordinates)
# We just shift the cage to the origin.
coordinates = shift_com(elements, coordinates)
# We create an array of vdw radii of elements.
elements_vdw = np.array([[atomic_vdw_radius[x.upper()]] for x in elements])
# We calculate maximum diameter of a molecule to determine the radius
# of a sampling sphere neccessary to enclose the whole molecule.
shpere_radius = max_dim(elements, coordinates)[2]
sphere_surface_area = 4 * np.pi * shpere_radius**2
# Here we determine the number of sampling points necessary for a fine
# sampling. Smaller molecules require more finner density of sampling
# points on the sampling sphere's surface, whereas largen require less.
# This formula was created so that larger molecule do not take much longer
# to analyse, as number_sampling_points*length_of_sampling_vectors
# results in quadratic increase of sampling time. The 250 factor was
# specificly determined to produce close to 1 sampling point /Angstrom^2
# for a sphere of radius ~ 24 Angstrom. We can adjust how fine is the
# sampling by changing the adjust factor.
number_of_points = int(np.log10(sphere_surface_area) * 250 * adjust)
# Here I use code by <NAME> for spreading points on a sphere:
# http://blog.marmakoide.org/?p=1
golden_angle = np.pi * (3 - np.sqrt(5))
theta = golden_angle * np.arange(number_of_points)
z = np.linspace(1 - 1.0 / number_of_points, 1.0 / number_of_points - 1.0,
number_of_points)
radius = np.sqrt(1 - z * z)
points = np.zeros((number_of_points, 3))
points[:, 0] = radius * np.cos(theta) * shpere_radius
points[:, 1] = radius * np.sin(theta) * shpere_radius
points[:, 2] = z * shpere_radius
# Here we analyse the vectors and retain the ones that create the molecule
# outline.
if processes:
pool = Pool(processes=processes)
parallel = [
pool.apply_async(
vector_analysis_reversed,
args=(
point, coordinates, elements_vdw)
) for point in points
]
results = [p.get() for p in parallel if p.get() is not None]
pool.terminate()
else:
results = [
vector_analysis_reversed(
point, coordinates, elements_vdw)
for point in points
]
results_cleaned = [x[0] for x in results if x is not None]
return np.mean(results_cleaned)*2
def vector_analysis_pore_shape(vector, coordinates, elements_vdw):
norm_vec = vector/np.linalg.norm(vector)
intersections = []
origin = center_of_coor(coordinates)
L = coordinates - origin
t_ca = np.dot(L, norm_vec)
d = np.sqrt(np.einsum('ij,ij->i', L, L) - t_ca**2)
under_sqrt = elements_vdw**2 - d**2
diag = under_sqrt.diagonal()
positions = np.argwhere(diag > 0)
for pos in positions:
t_hc = np.sqrt(diag[pos[0]])
t_0 = t_ca[pos][0] - t_hc
t_1 = t_ca[pos][0] + t_hc
P_0 = origin + np.dot(t_0, norm_vec)
P_1 = origin + np.dot(t_1, norm_vec)
# print(np.linalg.norm(P_0), np.linalg.norm(P_1))
if np.linalg.norm(P_0) < np.linalg.norm(P_1):
intersections.append([np.linalg.norm(P_0), P_0])
if intersections:
return sorted(intersections)[0][1]
def calculate_pore_shape(elements, coordinates, adjust=1, increment=0.1,
**kwargs):
"""Return average diameter for a molecule."""
# Copy the coordinates as will perform many opertaions on them
coordinates = deepcopy(coordinates)
# Center of our cartesian system is always at origin
origin = np.array([0, 0, 0])
# Initial center of mass to reverse translation at the end
initial_com = center_of_mass(elements, coordinates)
# We just shift the cage to the origin.
coordinates = shift_com(elements, coordinates)
# We create an array of vdw radii of elements.
elements_vdw = np.array([[atomic_vdw_radius[x.upper()]] for x in elements])
# We calculate maximum diameter of a molecule to determine the radius
# of a sampling sphere neccessary to enclose the whole molecule.
shpere_radius = max_dim(elements, coordinates)[2]/2
sphere_surface_area = 4 * np.pi * shpere_radius**2
# Here we determine the number of sampling points necessary for a fine
# sampling. Smaller molecules require more finner density of sampling
# points on the sampling sphere's surface, whereas largen require less.
# This formula was created so that larger molecule do not take much longer
# to analyse, as number_sampling_points*length_of_sampling_vectors
# results in quadratic increase of sampling time. The 250 factor was
# specificly determined to produce close to 1 sampling point /Angstrom^2
# for a sphere of radius ~ 24 Angstrom. We can adjust how fine is the
# sampling by changing the adjust factor.
number_of_points = int(np.log10(sphere_surface_area) * 250 * adjust)
# Here I use code by <NAME> for spreading points on a sphere:
# http://blog.marmakoide.org/?p=1
golden_angle = np.pi * (3 - np.sqrt(5))
theta = golden_angle * np.arange(number_of_points)
z = np.linspace(1 - 1.0 / number_of_points, 1.0 / number_of_points - 1.0,
number_of_points)
radius = np.sqrt(1 - z * z)
points = np.zeros((number_of_points, 3))
points[:, 0] = radius * np.cos(theta) * shpere_radius
points[:, 1] = radius * np.sin(theta) * shpere_radius
points[:, 2] = z * shpere_radius
# Here we will compute the eps parameter for the sklearn.cluster.DBSCAN
# (3-dimensional spatial clustering algorithm) which is the mean distance
# to the closest point of all points.
values = []
tree = KDTree(points)
for i in points:
dist, ind = tree.query(i.reshape(1, -1), k=10)
values.extend(dist)
mean_distance = np.mean(values)
# The best eps is parametrized when adding the mean distance and it's root.
eps = mean_distance + mean_distance**0.5
# Here we either run the sampling points vectors analysis in serial
# or parallel. The vectors that go through molecular voids return
# as analysed list with the increment at vector's path with largest
# included sphere, coordinates for this narrow channel point. vectors
# that find molecule on theirs path are return as NoneType object.
results = [
vector_analysis_pore_shape(point, coordinates, elements_vdw)
for point in points
]
results_cleaned = [x for x in results if x is not None]
ele = np.array(['X'] * len(results_cleaned))
coor = np.array(results_cleaned)
return coor
def circumcircle_window(coordinates, atom_set):
# Calculating circumcircle
A = np.array(coordinates[int(atom_set[0])])
B = np.array(coordinates[int(atom_set[1])])
C = np.array(coordinates[int(atom_set[2])])
a = np.linalg.norm(C - B)
b = np.linalg.norm(C - A)
c = np.linalg.norm(B - A)
s = (a + b + c) / 2
# Holden et al. method is intended to only work with triads of carbons,
# therefore I substract the vdW radii for a carbon.
# These equation calculaties the window's radius.
R = a*b*c / 4 / np.sqrt(s * (s - a) * (s - b) * (s - c)) - 1.70
# This steps are used to calculate the window's COM.
b1 = a*a * (b*b + c*c - a*a)
b2 = b*b * (a*a + c*c - b*b)
b3 = c*c * (a*a + b*b - c*c)
COM = np.column_stack((A, B, C)).dot(np.hstack((b1, b2, b3)))
# The window's COM.
COM /= b1 + b2 + b3
return R, COM
def circumcircle(coordinates, atom_sets):
pld_diameter_list = []
pld_com_list = []
iter_ = 0
while iter_ < len(atom_sets):
R, COM = circumcircle_window(coordinates, atom_sets[iter_])
pld_diameter_list.append(R*2)
pld_com_list.append(COM)
iter_ += 1
return pld_diameter_list, pld_com_list
|
[
"numpy.linalg.eigvals",
"numpy.triu",
"numpy.sum",
"numpy.arctan2",
"numpy.allclose",
"numpy.einsum",
"numpy.argmin",
"numpy.around",
"numpy.mean",
"numpy.linalg.norm",
"numpy.sin",
"numpy.arange",
"numpy.round",
"sklearn.cluster.DBSCAN",
"scipy.optimize.minimize",
"numpy.zeros_like",
"sklearn.metrics.pairwise.euclidean_distances",
"numpy.append",
"numpy.linspace",
"numpy.linalg.det",
"numpy.add",
"numpy.arccos",
"numpy.log10",
"numpy.repeat",
"copy.deepcopy",
"numpy.square",
"numpy.cross",
"numpy.hstack",
"numpy.linalg.inv",
"numpy.cos",
"multiprocessing.Pool",
"numpy.argwhere",
"numpy.dot",
"numpy.concatenate",
"numpy.matrix",
"numpy.logical_and",
"numpy.deg2rad",
"numpy.zeros",
"numpy.rad2deg",
"numpy.where",
"numpy.array",
"scipy.optimize.brute",
"numpy.column_stack",
"sklearn.neighbors.KDTree",
"numpy.sqrt"
] |
[((11504, 11515), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (11512, 11515), True, 'import numpy as np\n'), ((11997, 12048), 'numpy.array', 'np.array', (['([com - com_adjust] * coordinates.shape[0])'], {}), '([com - com_adjust] * coordinates.shape[0])\n', (12005, 12048), True, 'import numpy as np\n'), ((12618, 12663), 'sklearn.metrics.pairwise.euclidean_distances', 'euclidean_distances', (['coordinates', 'coordinates'], {}), '(coordinates, coordinates)\n', (12637, 12663), False, 'from sklearn.metrics.pairwise import euclidean_distances\n'), ((12786, 12809), 'numpy.triu', 'np.triu', (['re_dist_matrix'], {}), '(re_dist_matrix)\n', (12793, 12809), True, 'import numpy as np\n'), ((13318, 13343), 'numpy.argmin', 'np.argmin', (['re_dist_matrix'], {}), '(re_dist_matrix)\n', (13327, 13343), True, 'import numpy as np\n'), ((14159, 14224), 'scipy.optimize.minimize', 'minimize', (['correct_pore_diameter'], {'x0': 'com', 'args': 'args', 'bounds': 'bounds'}), '(correct_pore_diameter, x0=com, args=args, bounds=bounds)\n', (14167, 14224), False, 'from scipy.optimize import brute, fmin, minimize\n'), ((15872, 15904), 'numpy.sum', 'np.sum', (['(coordinates ** 2)'], {'axis': '(0)'}), '(coordinates ** 2, axis=0)\n', (15878, 15904), True, 'import numpy as np\n'), ((15912, 15957), 'numpy.sum', 'np.sum', (['(coordinates[:, 0] * coordinates[:, 1])'], {}), '(coordinates[:, 0] * coordinates[:, 1])\n', (15918, 15957), True, 'import numpy as np\n'), ((15967, 16012), 'numpy.sum', 'np.sum', (['(coordinates[:, 0] * coordinates[:, 2])'], {}), '(coordinates[:, 0] * coordinates[:, 2])\n', (15973, 16012), True, 'import numpy as np\n'), ((16022, 16067), 'numpy.sum', 'np.sum', (['(coordinates[:, 1] * coordinates[:, 2])'], {}), '(coordinates[:, 1] * coordinates[:, 2])\n', (16028, 16067), True, 'import numpy as np\n'), ((16752, 16804), 'numpy.sum', 'np.sum', (['(molecular_weight * (pow2[:, 1] + pow2[:, 2]))'], {}), '(molecular_weight * (pow2[:, 1] + pow2[:, 2]))\n', (16758, 16804), True, 'import numpy as np\n'), ((16818, 16870), 'numpy.sum', 'np.sum', (['(molecular_weight * (pow2[:, 0] + pow2[:, 2]))'], {}), '(molecular_weight * (pow2[:, 0] + pow2[:, 2]))\n', (16824, 16870), True, 'import numpy as np\n'), ((16884, 16936), 'numpy.sum', 'np.sum', (['(molecular_weight * (pow2[:, 0] + pow2[:, 1]))'], {}), '(molecular_weight * (pow2[:, 0] + pow2[:, 1]))\n', (16890, 16936), True, 'import numpy as np\n'), ((16948, 17013), 'numpy.sum', 'np.sum', (['(-molecular_weight * coordinates[:, 0] * coordinates[:, 1])'], {}), '(-molecular_weight * coordinates[:, 0] * coordinates[:, 1])\n', (16954, 17013), True, 'import numpy as np\n'), ((17024, 17089), 'numpy.sum', 'np.sum', (['(-molecular_weight * coordinates[:, 0] * coordinates[:, 2])'], {}), '(-molecular_weight * coordinates[:, 0] * coordinates[:, 2])\n', (17030, 17089), True, 'import numpy as np\n'), ((17100, 17165), 'numpy.sum', 'np.sum', (['(-molecular_weight * coordinates[:, 1] * coordinates[:, 2])'], {}), '(-molecular_weight * coordinates[:, 1] * coordinates[:, 2])\n', (17106, 17165), True, 'import numpy as np\n'), ((17822, 17845), 'numpy.round', 'np.round', (['v'], {'decimals': '(4)'}), '(v, decimals=4)\n', (17830, 17845), True, 'import numpy as np\n'), ((18361, 18378), 'numpy.cos', 'np.cos', (['(angle / 2)'], {}), '(angle / 2)\n', (18367, 18378), True, 'import numpy as np\n'), ((18817, 18878), 'numpy.array', 'np.array', (['[[e11, e12, e13], [e21, e22, e23], [e31, e32, e33]]'], {}), '([[e11, e12, e13], [e21, e22, e23], [e31, e32, e33]])\n', (18825, 18878), True, 'import numpy as np\n'), ((18951, 18972), 'copy.deepcopy', 'deepcopy', (['coordinates'], {}), '(coordinates)\n', (18959, 18972), False, 'from copy import deepcopy\n'), ((20551, 20568), 'numpy.deg2rad', 'np.deg2rad', (['alpha'], {}), '(alpha)\n', (20561, 20568), True, 'import numpy as np\n'), ((20582, 20598), 'numpy.deg2rad', 'np.deg2rad', (['beta'], {}), '(beta)\n', (20592, 20598), True, 'import numpy as np\n'), ((20613, 20630), 'numpy.deg2rad', 'np.deg2rad', (['gamma'], {}), '(gamma)\n', (20623, 20630), True, 'import numpy as np\n'), ((21226, 21287), 'numpy.array', 'np.array', (['[[a_x, a_y, a_z], [b_x, b_y, b_z], [c_x, c_y, c_z]]'], {}), '([[a_x, a_y, a_z], [b_x, b_y, b_z], [c_x, c_y, c_z]])\n', (21234, 21287), True, 'import numpy as np\n'), ((21518, 21566), 'numpy.arccos', 'np.arccos', (['(lattice_array[0][1] / cell_lengths[1])'], {}), '(lattice_array[0][1] / cell_lengths[1])\n', (21527, 21566), True, 'import numpy as np\n'), ((21580, 21628), 'numpy.arccos', 'np.arccos', (['(lattice_array[0][2] / cell_lengths[2])'], {}), '(lattice_array[0][2] / cell_lengths[2])\n', (21589, 21628), True, 'import numpy as np\n'), ((21881, 21917), 'numpy.append', 'np.append', (['cell_lengths', 'cell_angles'], {}), '(cell_lengths, cell_angles)\n', (21890, 21917), True, 'import numpy as np\n'), ((22034, 22062), 'numpy.linalg.det', 'np.linalg.det', (['lattice_array'], {}), '(lattice_array)\n', (22047, 22062), True, 'import numpy as np\n'), ((22699, 22723), 'numpy.matrix', 'np.matrix', (['lattice_array'], {}), '(lattice_array)\n', (22708, 22723), True, 'import numpy as np\n'), ((22967, 22988), 'copy.deepcopy', 'deepcopy', (['coordinates'], {}), '(coordinates)\n', (22975, 22988), False, 'from copy import deepcopy\n'), ((23312, 23338), 'copy.deepcopy', 'deepcopy', (['frac_coordinates'], {}), '(frac_coordinates)\n', (23320, 23338), False, 'from copy import deepcopy\n'), ((23821, 23852), 'copy.deepcopy', 'deepcopy', (["system['coordinates']"], {}), "(system['coordinates'])\n", (23829, 23852), False, 'from copy import deepcopy\n'), ((24549, 24592), 'numpy.concatenate', 'np.concatenate', (['updated_coordinates'], {'axis': '(0)'}), '(updated_coordinates, axis=0)\n', (24563, 24592), True, 'import numpy as np\n'), ((24796, 24824), 'copy.deepcopy', 'deepcopy', (["system['elements']"], {}), "(system['elements'])\n", (24804, 24824), False, 'from copy import deepcopy\n'), ((24839, 24867), 'copy.deepcopy', 'deepcopy', (["system['atom_ids']"], {}), "(system['atom_ids'])\n", (24847, 24867), False, 'from copy import deepcopy\n'), ((25881, 25931), 'numpy.cross', 'np.cross', (['(vectors[0] - origin)', '(vectors[1] - origin)'], {}), '(vectors[0] - origin, vectors[1] - origin)\n', (25889, 25931), True, 'import numpy as np\n'), ((38535, 38556), 'numpy.arccos', 'np.arccos', (['first_step'], {}), '(first_step)\n', (38544, 38556), True, 'import numpy as np\n'), ((39736, 39755), 'numpy.dot', 'np.dot', (['L', 'norm_vec'], {}), '(L, norm_vec)\n', (39742, 39755), True, 'import numpy as np\n'), ((39900, 39921), 'numpy.argwhere', 'np.argwhere', (['(diag > 0)'], {}), '(diag > 0)\n', (39911, 39921), True, 'import numpy as np\n'), ((40612, 40639), 'numpy.array', 'np.array', (['[xy[0], xy[1], z]'], {}), '([xy[0], xy[1], z])\n', (40620, 40639), True, 'import numpy as np\n'), ((40868, 40887), 'numpy.array', 'np.array', (['[x, y, z]'], {}), '([x, y, z])\n', (40876, 40887), True, 'import numpy as np\n'), ((41555, 41576), 'copy.deepcopy', 'deepcopy', (['coordinates'], {}), '(coordinates)\n', (41563, 41576), False, 'from copy import deepcopy\n'), ((44755, 44787), 'numpy.array', 'np.array', (['[0, 0, 0]'], {'dtype': 'float'}), '([0, 0, 0], dtype=float)\n', (44763, 44787), True, 'import numpy as np\n'), ((45354, 45424), 'scipy.optimize.minimize', 'minimize', (['optimise_z'], {'x0': 'window_com[2]', 'args': 'z_args', 'bounds': '[z_bounds]'}), '(optimise_z, x0=window_com[2], args=z_args, bounds=[z_bounds])\n', (45362, 45424), False, 'from scipy.optimize import brute, fmin, minimize\n'), ((45799, 45873), 'scipy.optimize.brute', 'brute', (['optimise_xy', 'xy_bounds'], {'args': 'xy_args', 'full_output': '(True)', 'finish': 'fmin'}), '(optimise_xy, xy_bounds, args=xy_args, full_output=True, finish=fmin)\n', (45804, 45873), False, 'from scipy.optimize import brute, fmin, minimize\n'), ((47647, 47683), 'numpy.dot', 'np.dot', (['reverse_around_y', 'window_com'], {}), '(reverse_around_y, window_com)\n', (47653, 47683), True, 'import numpy as np\n'), ((47974, 48010), 'numpy.dot', 'np.dot', (['reverse_around_z', 'window_com'], {}), '(reverse_around_z, window_com)\n', (47980, 48010), True, 'import numpy as np\n'), ((48452, 48473), 'copy.deepcopy', 'deepcopy', (['coordinates'], {}), '(coordinates)\n', (48460, 48473), False, 'from copy import deepcopy\n'), ((48544, 48563), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (48552, 48563), True, 'import numpy as np\n'), ((50953, 51044), 'numpy.linspace', 'np.linspace', (['(1 - 1.0 / number_of_points)', '(1.0 / number_of_points - 1.0)', 'number_of_points'], {}), '(1 - 1.0 / number_of_points, 1.0 / number_of_points - 1.0,\n number_of_points)\n', (50964, 51044), True, 'import numpy as np\n'), ((51074, 51092), 'numpy.sqrt', 'np.sqrt', (['(1 - z * z)'], {}), '(1 - z * z)\n', (51081, 51092), True, 'import numpy as np\n'), ((51106, 51137), 'numpy.zeros', 'np.zeros', (['(number_of_points, 3)'], {}), '((number_of_points, 3))\n', (51114, 51137), True, 'import numpy as np\n'), ((51514, 51528), 'sklearn.neighbors.KDTree', 'KDTree', (['points'], {}), '(points)\n', (51520, 51528), False, 'from sklearn.neighbors import KDTree\n'), ((51653, 51668), 'numpy.mean', 'np.mean', (['values'], {}), '(values)\n', (51660, 51668), True, 'import numpy as np\n'), ((55503, 55575), 'numpy.array', 'np.array', (['[result[0] for result in window_results if result is not None]'], {}), '([result[0] for result in window_results if result is not None])\n', (55511, 55575), True, 'import numpy as np\n'), ((56879, 56900), 'copy.deepcopy', 'deepcopy', (['coordinates'], {}), '(coordinates)\n', (56887, 56900), False, 'from copy import deepcopy\n'), ((60210, 60242), 'numpy.array', 'np.array', (['[0, 0, 0]'], {'dtype': 'float'}), '([0, 0, 0], dtype=float)\n', (60218, 60242), True, 'import numpy as np\n'), ((60809, 60879), 'scipy.optimize.minimize', 'minimize', (['optimise_z'], {'x0': 'window_com[2]', 'args': 'z_args', 'bounds': '[z_bounds]'}), '(optimise_z, x0=window_com[2], args=z_args, bounds=[z_bounds])\n', (60817, 60879), False, 'from scipy.optimize import brute, fmin, minimize\n'), ((61254, 61328), 'scipy.optimize.brute', 'brute', (['optimise_xy', 'xy_bounds'], {'args': 'xy_args', 'full_output': '(True)', 'finish': 'fmin'}), '(optimise_xy, xy_bounds, args=xy_args, full_output=True, finish=fmin)\n', (61259, 61328), False, 'from scipy.optimize import brute, fmin, minimize\n'), ((63160, 63246), 'numpy.array', 'np.array', (['[[i[0] * ref_distance, i[1] * ref_distance] for i in vectors_translated]'], {}), '([[i[0] * ref_distance, i[1] * ref_distance] for i in\n vectors_translated])\n', (63168, 63246), True, 'import numpy as np\n'), ((63743, 63764), 'copy.deepcopy', 'deepcopy', (['coordinates'], {}), '(coordinates)\n', (63751, 63764), False, 'from copy import deepcopy\n'), ((63835, 63854), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (63843, 63854), True, 'import numpy as np\n'), ((66244, 66335), 'numpy.linspace', 'np.linspace', (['(1 - 1.0 / number_of_points)', '(1.0 / number_of_points - 1.0)', 'number_of_points'], {}), '(1 - 1.0 / number_of_points, 1.0 / number_of_points - 1.0,\n number_of_points)\n', (66255, 66335), True, 'import numpy as np\n'), ((66365, 66383), 'numpy.sqrt', 'np.sqrt', (['(1 - z * z)'], {}), '(1 - z * z)\n', (66372, 66383), True, 'import numpy as np\n'), ((66397, 66428), 'numpy.zeros', 'np.zeros', (['(number_of_points, 3)'], {}), '((number_of_points, 3))\n', (66405, 66428), True, 'import numpy as np\n'), ((66805, 66819), 'sklearn.neighbors.KDTree', 'KDTree', (['points'], {}), '(points)\n', (66811, 66819), False, 'from sklearn.neighbors import KDTree\n'), ((66944, 66959), 'numpy.mean', 'np.mean', (['values'], {}), '(values)\n', (66951, 66959), True, 'import numpy as np\n'), ((70815, 70834), 'numpy.dot', 'np.dot', (['L', 'norm_vec'], {}), '(L, norm_vec)\n', (70821, 70834), True, 'import numpy as np\n'), ((70979, 71000), 'numpy.argwhere', 'np.argwhere', (['(diag > 0)'], {}), '(diag > 0)\n', (70990, 71000), True, 'import numpy as np\n'), ((71784, 71805), 'copy.deepcopy', 'deepcopy', (['coordinates'], {}), '(coordinates)\n', (71792, 71805), False, 'from copy import deepcopy\n'), ((71876, 71895), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (71884, 71895), True, 'import numpy as np\n'), ((73422, 73513), 'numpy.linspace', 'np.linspace', (['(1 - 1.0 / number_of_points)', '(1.0 / number_of_points - 1.0)', 'number_of_points'], {}), '(1 - 1.0 / number_of_points, 1.0 / number_of_points - 1.0,\n number_of_points)\n', (73433, 73513), True, 'import numpy as np\n'), ((73543, 73561), 'numpy.sqrt', 'np.sqrt', (['(1 - z * z)'], {}), '(1 - z * z)\n', (73550, 73561), True, 'import numpy as np\n'), ((73575, 73606), 'numpy.zeros', 'np.zeros', (['(number_of_points, 3)'], {}), '((number_of_points, 3))\n', (73583, 73606), True, 'import numpy as np\n'), ((74704, 74723), 'numpy.dot', 'np.dot', (['L', 'norm_vec'], {}), '(L, norm_vec)\n', (74710, 74723), True, 'import numpy as np\n'), ((74868, 74889), 'numpy.argwhere', 'np.argwhere', (['(diag > 0)'], {}), '(diag > 0)\n', (74879, 74889), True, 'import numpy as np\n'), ((75596, 75617), 'copy.deepcopy', 'deepcopy', (['coordinates'], {}), '(coordinates)\n', (75604, 75617), False, 'from copy import deepcopy\n'), ((75688, 75707), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (75696, 75707), True, 'import numpy as np\n'), ((77236, 77327), 'numpy.linspace', 'np.linspace', (['(1 - 1.0 / number_of_points)', '(1.0 / number_of_points - 1.0)', 'number_of_points'], {}), '(1 - 1.0 / number_of_points, 1.0 / number_of_points - 1.0,\n number_of_points)\n', (77247, 77327), True, 'import numpy as np\n'), ((77357, 77375), 'numpy.sqrt', 'np.sqrt', (['(1 - z * z)'], {}), '(1 - z * z)\n', (77364, 77375), True, 'import numpy as np\n'), ((77389, 77420), 'numpy.zeros', 'np.zeros', (['(number_of_points, 3)'], {}), '((number_of_points, 3))\n', (77397, 77420), True, 'import numpy as np\n'), ((77797, 77811), 'sklearn.neighbors.KDTree', 'KDTree', (['points'], {}), '(points)\n', (77803, 77811), False, 'from sklearn.neighbors import KDTree\n'), ((77936, 77951), 'numpy.mean', 'np.mean', (['values'], {}), '(values)\n', (77943, 77951), True, 'import numpy as np\n'), ((78675, 78700), 'numpy.array', 'np.array', (['results_cleaned'], {}), '(results_cleaned)\n', (78683, 78700), True, 'import numpy as np\n'), ((78950, 78971), 'numpy.linalg.norm', 'np.linalg.norm', (['(C - B)'], {}), '(C - B)\n', (78964, 78971), True, 'import numpy as np\n'), ((78980, 79001), 'numpy.linalg.norm', 'np.linalg.norm', (['(C - A)'], {}), '(C - A)\n', (78994, 79001), True, 'import numpy as np\n'), ((79010, 79031), 'numpy.linalg.norm', 'np.linalg.norm', (['(B - A)'], {}), '(B - A)\n', (79024, 79031), True, 'import numpy as np\n'), ((3485, 3505), 'numpy.sum', 'np.sum', (['((a - b) ** 2)'], {}), '((a - b) ** 2)\n', (3491, 3505), True, 'import numpy as np\n'), ((4243, 4270), 'numpy.sum', 'np.sum', (['coordinates'], {'axis': '(0)'}), '(coordinates, axis=0)\n', (4249, 4270), True, 'import numpy as np\n'), ((4911, 4943), 'numpy.sum', 'np.sum', (['mass_coordinates'], {'axis': '(0)'}), '(mass_coordinates, axis=0)\n', (4917, 4943), True, 'import numpy as np\n'), ((4946, 4974), 'numpy.array', 'np.array', (['[mass, mass, mass]'], {}), '([mass, mass, mass])\n', (4954, 4974), True, 'import numpy as np\n'), ((7629, 7651), 'numpy.array', 'np.array', (['transpose[0]'], {}), '(transpose[0])\n', (7637, 7651), True, 'import numpy as np\n'), ((7839, 7881), 'numpy.concatenate', 'np.concatenate', (['(array_a, array_b)'], {'axis': '(1)'}), '((array_a, array_b), axis=1)\n', (7853, 7881), True, 'import numpy as np\n'), ((7904, 7947), 'numpy.concatenate', 'np.concatenate', (['(array_ab, array_c)'], {'axis': '(1)'}), '((array_ab, array_c), axis=1)\n', (7918, 7947), True, 'import numpy as np\n'), ((14849, 14869), 'numpy.linalg.eigvals', 'np.linalg.eigvals', (['T'], {}), '(T)\n', (14866, 14869), True, 'import numpy as np\n'), ((16076, 16143), 'numpy.array', 'np.array', (['[[diag[0], xy, xz], [xy, diag[1], yz], [xz, yz, diag[2]]]'], {}), '([[diag[0], xy, xz], [xy, diag[1], yz], [xz, yz, diag[2]]])\n', (16084, 16143), True, 'import numpy as np\n'), ((17188, 17258), 'numpy.array', 'np.array', (['[[diag_1, mxy, mxz], [mxy, diag_2, myz], [mxz, myz, diag_3]]'], {}), '([[diag_1, mxy, mxz], [mxy, diag_2, myz], [mxz, myz, diag_3]])\n', (17196, 17258), True, 'import numpy as np\n'), ((17787, 17809), 'numpy.linalg.norm', 'np.linalg.norm', (['vector'], {}), '(vector)\n', (17801, 17809), True, 'import numpy as np\n'), ((18400, 18417), 'numpy.sin', 'np.sin', (['(angle / 2)'], {}), '(angle / 2)\n', (18406, 18417), True, 'import numpy as np\n'), ((18474, 18486), 'numpy.square', 'np.square', (['d'], {}), '(d)\n', (18483, 18486), True, 'import numpy as np\n'), ((18633, 18645), 'numpy.square', 'np.square', (['d'], {}), '(d)\n', (18642, 18645), True, 'import numpy as np\n'), ((18792, 18804), 'numpy.square', 'np.square', (['c'], {}), '(c)\n', (18801, 18804), True, 'import numpy as np\n'), ((19190, 19211), 'numpy.linalg.norm', 'np.linalg.norm', (['r_vec'], {}), '(r_vec)\n', (19204, 19211), True, 'import numpy as np\n'), ((19271, 19291), 'numpy.arctan2', 'np.arctan2', (['sin', 'cos'], {}), '(sin, cos)\n', (19281, 19291), True, 'import numpy as np\n'), ((19548, 19566), 'numpy.array', 'np.array', (['new_coor'], {}), '(new_coor)\n', (19556, 19566), True, 'import numpy as np\n'), ((20951, 20966), 'numpy.cos', 'np.cos', (['r_gamma'], {}), '(r_gamma)\n', (20957, 20966), True, 'import numpy as np\n'), ((20982, 20996), 'numpy.cos', 'np.cos', (['r_beta'], {}), '(r_beta)\n', (20988, 20996), True, 'import numpy as np\n'), ((21024, 21039), 'numpy.sin', 'np.sin', (['r_gamma'], {}), '(r_gamma)\n', (21030, 21039), True, 'import numpy as np\n'), ((21119, 21134), 'numpy.sin', 'np.sin', (['r_gamma'], {}), '(r_gamma)\n', (21125, 21134), True, 'import numpy as np\n'), ((21470, 21504), 'numpy.sum', 'np.sum', (['(lattice_array ** 2)'], {'axis': '(0)'}), '(lattice_array ** 2, axis=0)\n', (21476, 21504), True, 'import numpy as np\n'), ((21799, 21818), 'numpy.rad2deg', 'np.rad2deg', (['alpha_r'], {}), '(alpha_r)\n', (21809, 21818), True, 'import numpy as np\n'), ((21820, 21838), 'numpy.rad2deg', 'np.rad2deg', (['beta_r'], {}), '(beta_r)\n', (21830, 21838), True, 'import numpy as np\n'), ((21840, 21859), 'numpy.rad2deg', 'np.rad2deg', (['gamma_r'], {}), '(gamma_r)\n', (21850, 21859), True, 'import numpy as np\n'), ((22408, 22436), 'numpy.linalg.inv', 'np.linalg.inv', (['lattice_array'], {}), '(lattice_array)\n', (22421, 22436), True, 'import numpy as np\n'), ((24941, 24991), 'numpy.concatenate', 'np.concatenate', (["(new_elements, system['elements'])"], {}), "((new_elements, system['elements']))\n", (24955, 24991), True, 'import numpy as np\n'), ((25010, 25055), 'numpy.concatenate', 'np.concatenate', (["(new_ids, system['atom_ids'])"], {}), "((new_ids, system['atom_ids']))\n", (25024, 25055), True, 'import numpy as np\n'), ((29152, 29178), 'numpy.array', 'np.array', (['[0.01, 0.0, 0.0]'], {}), '([0.01, 0.0, 0.0])\n', (29160, 29178), True, 'import numpy as np\n'), ((29371, 29399), 'numpy.array', 'np.array', (['[0.26, 0.25, 0.25]'], {}), '([0.26, 0.25, 0.25])\n', (29379, 29399), True, 'import numpy as np\n'), ((30782, 30823), 'numpy.allclose', 'np.allclose', (['system_com', 'origin'], {'atol': '(1.0)'}), '(system_com, origin, atol=1.0)\n', (30793, 30823), True, 'import numpy as np\n'), ((37124, 37177), 'numpy.array', 'np.array', (['[x[0] for x in final_molecule]'], {'dtype': '"""str"""'}), "([x[0] for x in final_molecule], dtype='str')\n", (37132, 37177), True, 'import numpy as np\n'), ((37236, 37290), 'numpy.array', 'np.array', (['[[*xyz[1 + adj:]] for xyz in final_molecule]'], {}), '([[*xyz[1 + adj:]] for xyz in final_molecule])\n', (37244, 37290), True, 'import numpy as np\n'), ((39273, 39299), 'numpy.argmin', 'np.argmin', (['analysed_vector'], {}), '(analysed_vector)\n', (39282, 39299), True, 'import numpy as np\n'), ((39389, 39416), 'numpy.linalg.norm', 'np.linalg.norm', (['(chunk * pos)'], {}), '(chunk * pos)\n', (39403, 39416), True, 'import numpy as np\n'), ((39432, 39499), 'numpy.array', 'np.array', (['[dist, analysed_vector[pos] * 2, *(chunk * pos), *vector]'], {}), '([dist, analysed_vector[pos] * 2, *(chunk * pos), *vector])\n', (39440, 39499), True, 'import numpy as np\n'), ((39609, 39631), 'numpy.linalg.norm', 'np.linalg.norm', (['vector'], {}), '(vector)\n', (39623, 39631), True, 'import numpy as np\n'), ((39963, 39984), 'numpy.sqrt', 'np.sqrt', (['diag[pos[0]]'], {}), '(diag[pos[0]])\n', (39970, 39984), True, 'import numpy as np\n'), ((42251, 42286), 'numpy.array', 'np.array', (['[vector[0], vector[1], 0]'], {}), '([vector[0], vector[1], 0])\n', (42259, 42286), True, 'import numpy as np\n'), ((44578, 44626), 'numpy.array', 'np.array', (['([[0, 0, new_z]] * coordinates.shape[0])'], {}), '([[0, 0, new_z]] * coordinates.shape[0])\n', (44586, 44626), True, 'import numpy as np\n'), ((46824, 46894), 'scipy.optimize.minimize', 'minimize', (['optimise_z'], {'x0': 'window_com[2]', 'args': 'z_args', 'bounds': '[z_bounds]'}), '(optimise_z, x0=window_com[2], args=z_args, bounds=[z_bounds])\n', (46832, 46894), False, 'from scipy.optimize import brute, fmin, minimize\n'), ((50917, 50944), 'numpy.arange', 'np.arange', (['number_of_points'], {}), '(number_of_points)\n', (50926, 50944), True, 'import numpy as np\n'), ((52244, 52269), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'processes'}), '(processes=processes)\n', (52248, 52269), False, 'from multiprocessing import Pool\n'), ((52728, 52763), 'numpy.array', 'np.array', (['[x[5:8] for x in results]'], {}), '([x[5:8] for x in results])\n', (52736, 52763), True, 'import numpy as np\n'), ((53013, 53048), 'numpy.array', 'np.array', (['[x[5:8] for x in results]'], {}), '([x[5:8] for x in results])\n', (53021, 53048), True, 'import numpy as np\n'), ((53681, 53718), 'numpy.zeros_like', 'np.zeros_like', (['db.labels_'], {'dtype': 'bool'}), '(db.labels_, dtype=bool)\n', (53694, 53718), True, 'import numpy as np\n'), ((57706, 57741), 'numpy.array', 'np.array', (['[vector[0], vector[1], 0]'], {}), '([vector[0], vector[1], 0])\n', (57714, 57741), True, 'import numpy as np\n'), ((60033, 60081), 'numpy.array', 'np.array', (['([[0, 0, new_z]] * coordinates.shape[0])'], {}), '([[0, 0, new_z]] * coordinates.shape[0])\n', (60041, 60081), True, 'import numpy as np\n'), ((62279, 62349), 'scipy.optimize.minimize', 'minimize', (['optimise_z'], {'x0': 'window_com[2]', 'args': 'z_args', 'bounds': '[z_bounds]'}), '(optimise_z, x0=window_com[2], args=z_args, bounds=[z_bounds])\n', (62287, 62349), False, 'from scipy.optimize import brute, fmin, minimize\n'), ((63094, 63116), 'numpy.linalg.norm', 'np.linalg.norm', (['vector'], {}), '(vector)\n', (63108, 63116), True, 'import numpy as np\n'), ((66208, 66235), 'numpy.arange', 'np.arange', (['number_of_points'], {}), '(number_of_points)\n', (66217, 66235), True, 'import numpy as np\n'), ((67535, 67560), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'processes'}), '(processes=processes)\n', (67539, 67560), False, 'from multiprocessing import Pool\n'), ((68019, 68054), 'numpy.array', 'np.array', (['[x[5:8] for x in results]'], {}), '([x[5:8] for x in results])\n', (68027, 68054), True, 'import numpy as np\n'), ((68304, 68339), 'numpy.array', 'np.array', (['[x[5:8] for x in results]'], {}), '([x[5:8] for x in results])\n', (68312, 68339), True, 'import numpy as np\n'), ((68972, 69009), 'numpy.zeros_like', 'np.zeros_like', (['db.labels_'], {'dtype': 'bool'}), '(db.labels_, dtype=bool)\n', (68985, 69009), True, 'import numpy as np\n'), ((69688, 69704), 'numpy.array', 'np.array', (['window'], {}), '(window)\n', (69696, 69704), True, 'import numpy as np\n'), ((70206, 70222), 'numpy.array', 'np.array', (['window'], {}), '(window)\n', (70214, 70222), True, 'import numpy as np\n'), ((70530, 70568), 'numpy.add', 'np.add', (['window_results[1]', 'initial_com'], {}), '(window_results[1], initial_com)\n', (70536, 70568), True, 'import numpy as np\n'), ((70688, 70710), 'numpy.linalg.norm', 'np.linalg.norm', (['vector'], {}), '(vector)\n', (70702, 70710), True, 'import numpy as np\n'), ((71042, 71063), 'numpy.sqrt', 'np.sqrt', (['diag[pos[0]]'], {}), '(diag[pos[0]])\n', (71049, 71063), True, 'import numpy as np\n'), ((71448, 71476), 'numpy.linalg.norm', 'np.linalg.norm', (['intersection'], {}), '(intersection)\n', (71462, 71476), True, 'import numpy as np\n'), ((73386, 73413), 'numpy.arange', 'np.arange', (['number_of_points'], {}), '(number_of_points)\n', (73395, 73413), True, 'import numpy as np\n'), ((73887, 73912), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'processes'}), '(processes=processes)\n', (73891, 73912), False, 'from multiprocessing import Pool\n'), ((74459, 74483), 'numpy.mean', 'np.mean', (['results_cleaned'], {}), '(results_cleaned)\n', (74466, 74483), True, 'import numpy as np\n'), ((74577, 74599), 'numpy.linalg.norm', 'np.linalg.norm', (['vector'], {}), '(vector)\n', (74591, 74599), True, 'import numpy as np\n'), ((74931, 74952), 'numpy.sqrt', 'np.sqrt', (['diag[pos[0]]'], {}), '(diag[pos[0]])\n', (74938, 74952), True, 'import numpy as np\n'), ((77200, 77227), 'numpy.arange', 'np.arange', (['number_of_points'], {}), '(number_of_points)\n', (77209, 77227), True, 'import numpy as np\n'), ((79507, 79530), 'numpy.hstack', 'np.hstack', (['(b1, b2, b3)'], {}), '((b1, b2, b3))\n', (79516, 79530), True, 'import numpy as np\n'), ((8034, 8056), 'numpy.array', 'np.array', (['transpose[0]'], {}), '(transpose[0])\n', (8042, 8056), True, 'import numpy as np\n'), ((8076, 8098), 'numpy.array', 'np.array', (['transpose[1]'], {}), '(transpose[1])\n', (8084, 8098), True, 'import numpy as np\n'), ((8286, 8328), 'numpy.concatenate', 'np.concatenate', (['(array_a, array_b)'], {'axis': '(1)'}), '((array_a, array_b), axis=1)\n', (8300, 8328), True, 'import numpy as np\n'), ((8351, 8394), 'numpy.concatenate', 'np.concatenate', (['(array_ab, array_c)'], {'axis': '(1)'}), '((array_ab, array_c), axis=1)\n', (8365, 8394), True, 'import numpy as np\n'), ((14786, 14806), 'numpy.linalg.eigvals', 'np.linalg.eigvals', (['T'], {}), '(T)\n', (14803, 14806), True, 'import numpy as np\n'), ((18459, 18471), 'numpy.square', 'np.square', (['c'], {}), '(c)\n', (18468, 18471), True, 'import numpy as np\n'), ((18618, 18630), 'numpy.square', 'np.square', (['b'], {}), '(b)\n', (18627, 18630), True, 'import numpy as np\n'), ((18777, 18789), 'numpy.square', 'np.square', (['b'], {}), '(b)\n', (18786, 18789), True, 'import numpy as np\n'), ((19163, 19174), 'numpy.array', 'np.array', (['j'], {}), '(j)\n', (19171, 19174), True, 'import numpy as np\n'), ((19244, 19255), 'numpy.array', 'np.array', (['j'], {}), '(j)\n', (19252, 19255), True, 'import numpy as np\n'), ((21189, 21204), 'numpy.sin', 'np.sin', (['r_gamma'], {}), '(r_gamma)\n', (21195, 21204), True, 'import numpy as np\n'), ((30850, 30871), 'numpy.array', 'np.array', (['[-0.5, 0.5]'], {}), '([-0.5, 0.5])\n', (30858, 30871), True, 'import numpy as np\n'), ((30909, 30929), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (30917, 30929), True, 'import numpy as np\n'), ((31037, 31063), 'numpy.array', 'np.array', (['[0.01, 0.0, 0.0]'], {}), '([0.01, 0.0, 0.0])\n', (31045, 31063), True, 'import numpy as np\n'), ((33170, 33214), 'numpy.array', 'np.array', (['potential_starting_point[1 + adj:]'], {}), '(potential_starting_point[1 + adj:])\n', (33178, 33214), True, 'import numpy as np\n'), ((37371, 37424), 'numpy.array', 'np.array', (['[x[1] for x in final_molecule]'], {'dtype': '"""str"""'}), "([x[1] for x in final_molecule], dtype='str')\n", (37379, 37424), True, 'import numpy as np\n'), ((37948, 37979), 'numpy.around', 'np.around', (['com_frac'], {'decimals': '(8)'}), '(com_frac, decimals=8)\n', (37957, 37979), True, 'import numpy as np\n'), ((38432, 38474), 'numpy.sqrt', 'np.sqrt', (['(x[0] ** 2 + x[1] ** 2 + x[2] ** 2)'], {}), '(x[0] ** 2 + x[1] ** 2 + x[2] ** 2)\n', (38439, 38474), True, 'import numpy as np\n'), ((38479, 38521), 'numpy.sqrt', 'np.sqrt', (['(y[0] ** 2 + y[1] ** 2 + y[2] ** 2)'], {}), '(y[0] ** 2 + y[1] ** 2 + y[2] ** 2)\n', (38486, 38521), True, 'import numpy as np\n'), ((38819, 38841), 'numpy.linalg.norm', 'np.linalg.norm', (['vector'], {}), '(vector)\n', (38833, 38841), True, 'import numpy as np\n'), ((39772, 39799), 'numpy.einsum', 'np.einsum', (['"""ij,ij->i"""', 'L', 'L'], {}), "('ij,ij->i', L, L)\n", (39781, 39799), True, 'import numpy as np\n'), ((40077, 40098), 'numpy.dot', 'np.dot', (['t_0', 'norm_vec'], {}), '(t_0, norm_vec)\n', (40083, 40098), True, 'import numpy as np\n'), ((40122, 40143), 'numpy.dot', 'np.dot', (['t_1', 'norm_vec'], {}), '(t_1, norm_vec)\n', (40128, 40143), True, 'import numpy as np\n'), ((40213, 40232), 'numpy.linalg.norm', 'np.linalg.norm', (['P_0'], {}), '(P_0)\n', (40227, 40232), True, 'import numpy as np\n'), ((40235, 40254), 'numpy.linalg.norm', 'np.linalg.norm', (['P_1'], {}), '(P_1)\n', (40249, 40254), True, 'import numpy as np\n'), ((43716, 43744), 'numpy.dot', 'np.dot', (['rotation_around_z', 'i'], {}), '(rotation_around_z, i)\n', (43722, 43744), True, 'import numpy as np\n'), ((44114, 44142), 'numpy.dot', 'np.dot', (['rotation_around_y', 'i'], {}), '(rotation_around_y, i)\n', (44120, 44142), True, 'import numpy as np\n'), ((50878, 50888), 'numpy.sqrt', 'np.sqrt', (['(5)'], {}), '(5)\n', (50885, 50888), True, 'import numpy as np\n'), ((51166, 51179), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (51172, 51179), True, 'import numpy as np\n'), ((51224, 51237), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (51230, 51237), True, 'import numpy as np\n'), ((54588, 54613), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'processes'}), '(processes=processes)\n', (54592, 54613), False, 'from multiprocessing import Pool\n'), ((55638, 55668), 'numpy.add', 'np.add', (['result[1]', 'initial_com'], {}), '(result[1], initial_com)\n', (55644, 55668), True, 'import numpy as np\n'), ((59171, 59199), 'numpy.dot', 'np.dot', (['rotation_around_z', 'i'], {}), '(rotation_around_z, i)\n', (59177, 59199), True, 'import numpy as np\n'), ((59569, 59597), 'numpy.dot', 'np.dot', (['rotation_around_y', 'i'], {}), '(rotation_around_y, i)\n', (59575, 59597), True, 'import numpy as np\n'), ((66169, 66179), 'numpy.sqrt', 'np.sqrt', (['(5)'], {}), '(5)\n', (66176, 66179), True, 'import numpy as np\n'), ((66457, 66470), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (66463, 66470), True, 'import numpy as np\n'), ((66515, 66528), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (66521, 66528), True, 'import numpy as np\n'), ((70851, 70878), 'numpy.einsum', 'np.einsum', (['"""ij,ij->i"""', 'L', 'L'], {}), "('ij,ij->i', L, L)\n", (70860, 70878), True, 'import numpy as np\n'), ((71156, 71177), 'numpy.dot', 'np.dot', (['t_0', 'norm_vec'], {}), '(t_0, norm_vec)\n', (71162, 71177), True, 'import numpy as np\n'), ((71201, 71222), 'numpy.dot', 'np.dot', (['t_1', 'norm_vec'], {}), '(t_1, norm_vec)\n', (71207, 71222), True, 'import numpy as np\n'), ((71234, 71253), 'numpy.linalg.norm', 'np.linalg.norm', (['P_0'], {}), '(P_0)\n', (71248, 71253), True, 'import numpy as np\n'), ((71256, 71275), 'numpy.linalg.norm', 'np.linalg.norm', (['P_1'], {}), '(P_1)\n', (71270, 71275), True, 'import numpy as np\n'), ((73347, 73357), 'numpy.sqrt', 'np.sqrt', (['(5)'], {}), '(5)\n', (73354, 73357), True, 'import numpy as np\n'), ((73635, 73648), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (73641, 73648), True, 'import numpy as np\n'), ((73693, 73706), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (73699, 73706), True, 'import numpy as np\n'), ((74740, 74767), 'numpy.einsum', 'np.einsum', (['"""ij,ij->i"""', 'L', 'L'], {}), "('ij,ij->i', L, L)\n", (74749, 74767), True, 'import numpy as np\n'), ((75045, 75066), 'numpy.dot', 'np.dot', (['t_0', 'norm_vec'], {}), '(t_0, norm_vec)\n', (75051, 75066), True, 'import numpy as np\n'), ((75090, 75111), 'numpy.dot', 'np.dot', (['t_1', 'norm_vec'], {}), '(t_1, norm_vec)\n', (75096, 75111), True, 'import numpy as np\n'), ((75181, 75200), 'numpy.linalg.norm', 'np.linalg.norm', (['P_0'], {}), '(P_0)\n', (75195, 75200), True, 'import numpy as np\n'), ((75203, 75222), 'numpy.linalg.norm', 'np.linalg.norm', (['P_1'], {}), '(P_1)\n', (75217, 75222), True, 'import numpy as np\n'), ((77161, 77171), 'numpy.sqrt', 'np.sqrt', (['(5)'], {}), '(5)\n', (77168, 77171), True, 'import numpy as np\n'), ((77449, 77462), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (77455, 77462), True, 'import numpy as np\n'), ((77507, 77520), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (77513, 77520), True, 'import numpy as np\n'), ((79262, 79302), 'numpy.sqrt', 'np.sqrt', (['(s * (s - a) * (s - b) * (s - c))'], {}), '(s * (s - a) * (s - b) * (s - c))\n', (79269, 79302), True, 'import numpy as np\n'), ((79476, 79502), 'numpy.column_stack', 'np.column_stack', (['(A, B, C)'], {}), '((A, B, C))\n', (79491, 79502), True, 'import numpy as np\n'), ((7670, 7692), 'numpy.array', 'np.array', (['transpose[1]'], {}), '(transpose[1])\n', (7678, 7692), True, 'import numpy as np\n'), ((7726, 7748), 'numpy.array', 'np.array', (['transpose[2]'], {}), '(transpose[2])\n', (7734, 7748), True, 'import numpy as np\n'), ((7782, 7804), 'numpy.array', 'np.array', (['transpose[3]'], {}), '(transpose[3])\n', (7790, 7804), True, 'import numpy as np\n'), ((18429, 18441), 'numpy.square', 'np.square', (['a'], {}), '(a)\n', (18438, 18441), True, 'import numpy as np\n'), ((18444, 18456), 'numpy.square', 'np.square', (['b'], {}), '(b)\n', (18453, 18456), True, 'import numpy as np\n'), ((18588, 18600), 'numpy.square', 'np.square', (['a'], {}), '(a)\n', (18597, 18600), True, 'import numpy as np\n'), ((18603, 18615), 'numpy.square', 'np.square', (['c'], {}), '(c)\n', (18612, 18615), True, 'import numpy as np\n'), ((18747, 18759), 'numpy.square', 'np.square', (['a'], {}), '(a)\n', (18756, 18759), True, 'import numpy as np\n'), ((18762, 18774), 'numpy.square', 'np.square', (['d'], {}), '(d)\n', (18771, 18774), True, 'import numpy as np\n'), ((21065, 21080), 'numpy.cos', 'np.cos', (['r_alpha'], {}), '(r_alpha)\n', (21071, 21080), True, 'import numpy as np\n'), ((21728, 21742), 'numpy.cos', 'np.cos', (['beta_r'], {}), '(beta_r)\n', (21734, 21742), True, 'import numpy as np\n'), ((21745, 21760), 'numpy.cos', 'np.cos', (['gamma_r'], {}), '(gamma_r)\n', (21751, 21760), True, 'import numpy as np\n'), ((24105, 24129), 'numpy.array', 'np.array', (['[[a_, b_, c_]]'], {}), '([[a_, b_, c_]])\n', (24113, 24129), True, 'import numpy as np\n'), ((24160, 24212), 'numpy.repeat', 'np.repeat', (['mult_matrix', 'coordinates.shape[0]'], {'axis': '(0)'}), '(mult_matrix, coordinates.shape[0], axis=0)\n', (24169, 24212), True, 'import numpy as np\n'), ((38007, 38082), 'numpy.logical_and', 'np.logical_and', (['(com_frac_round >= boundary[0])', '(com_frac_round < boundary[1])'], {}), '(com_frac_round >= boundary[0], com_frac_round < boundary[1])\n', (38021, 38082), True, 'import numpy as np\n'), ((43467, 43482), 'numpy.cos', 'np.cos', (['angle_1'], {}), '(angle_1)\n', (43473, 43482), True, 'import numpy as np\n'), ((43541, 43556), 'numpy.sin', 'np.sin', (['angle_1'], {}), '(angle_1)\n', (43547, 43556), True, 'import numpy as np\n'), ((43558, 43573), 'numpy.cos', 'np.cos', (['angle_1'], {}), '(angle_1)\n', (43564, 43573), True, 'import numpy as np\n'), ((43865, 43880), 'numpy.cos', 'np.cos', (['angle_2'], {}), '(angle_2)\n', (43871, 43880), True, 'import numpy as np\n'), ((43885, 43900), 'numpy.sin', 'np.sin', (['angle_2'], {}), '(angle_2)\n', (43891, 43900), True, 'import numpy as np\n'), ((44004, 44019), 'numpy.cos', 'np.cos', (['angle_2'], {}), '(angle_2)\n', (44010, 44019), True, 'import numpy as np\n'), ((47415, 47432), 'numpy.cos', 'np.cos', (['angle_2_1'], {}), '(angle_2_1)\n', (47421, 47432), True, 'import numpy as np\n'), ((47437, 47454), 'numpy.sin', 'np.sin', (['angle_2_1'], {}), '(angle_2_1)\n', (47443, 47454), True, 'import numpy as np\n'), ((47558, 47575), 'numpy.cos', 'np.cos', (['angle_2_1'], {}), '(angle_2_1)\n', (47564, 47575), True, 'import numpy as np\n'), ((47743, 47760), 'numpy.cos', 'np.cos', (['angle_1_1'], {}), '(angle_1_1)\n', (47749, 47760), True, 'import numpy as np\n'), ((47820, 47837), 'numpy.sin', 'np.sin', (['angle_1_1'], {}), '(angle_1_1)\n', (47826, 47837), True, 'import numpy as np\n'), ((47839, 47856), 'numpy.cos', 'np.cos', (['angle_1_1'], {}), '(angle_1_1)\n', (47845, 47856), True, 'import numpy as np\n'), ((50696, 50725), 'numpy.log10', 'np.log10', (['sphere_surface_area'], {}), '(sphere_surface_area)\n', (50704, 50725), True, 'import numpy as np\n'), ((53624, 53639), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {'eps': 'eps'}), '(eps=eps)\n', (53630, 53639), False, 'from sklearn.cluster import DBSCAN\n'), ((58922, 58937), 'numpy.cos', 'np.cos', (['angle_1'], {}), '(angle_1)\n', (58928, 58937), True, 'import numpy as np\n'), ((58996, 59011), 'numpy.sin', 'np.sin', (['angle_1'], {}), '(angle_1)\n', (59002, 59011), True, 'import numpy as np\n'), ((59013, 59028), 'numpy.cos', 'np.cos', (['angle_1'], {}), '(angle_1)\n', (59019, 59028), True, 'import numpy as np\n'), ((59320, 59335), 'numpy.cos', 'np.cos', (['angle_2'], {}), '(angle_2)\n', (59326, 59335), True, 'import numpy as np\n'), ((59340, 59355), 'numpy.sin', 'np.sin', (['angle_2'], {}), '(angle_2)\n', (59346, 59355), True, 'import numpy as np\n'), ((59459, 59474), 'numpy.cos', 'np.cos', (['angle_2'], {}), '(angle_2)\n', (59465, 59474), True, 'import numpy as np\n'), ((62630, 62662), 'numpy.dot', 'np.dot', (['rotation_around_z', 'i[5:]'], {}), '(rotation_around_z, i[5:])\n', (62636, 62662), True, 'import numpy as np\n'), ((62679, 62711), 'numpy.dot', 'np.dot', (['rotation_around_z', 'i[5:]'], {}), '(rotation_around_z, i[5:])\n', (62685, 62711), True, 'import numpy as np\n'), ((62728, 62760), 'numpy.dot', 'np.dot', (['rotation_around_z', 'i[5:]'], {}), '(rotation_around_z, i[5:])\n', (62734, 62760), True, 'import numpy as np\n'), ((62883, 62911), 'numpy.dot', 'np.dot', (['rotation_around_y', 'i'], {}), '(rotation_around_y, i)\n', (62889, 62911), True, 'import numpy as np\n'), ((62928, 62956), 'numpy.dot', 'np.dot', (['rotation_around_y', 'i'], {}), '(rotation_around_y, i)\n', (62934, 62956), True, 'import numpy as np\n'), ((62973, 63001), 'numpy.dot', 'np.dot', (['rotation_around_y', 'i'], {}), '(rotation_around_y, i)\n', (62979, 63001), True, 'import numpy as np\n'), ((65987, 66016), 'numpy.log10', 'np.log10', (['sphere_surface_area'], {}), '(sphere_surface_area)\n', (65995, 66016), True, 'import numpy as np\n'), ((68915, 68930), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {'eps': 'eps'}), '(eps=eps)\n', (68921, 68930), False, 'from sklearn.cluster import DBSCAN\n'), ((73165, 73194), 'numpy.log10', 'np.log10', (['sphere_surface_area'], {}), '(sphere_surface_area)\n', (73173, 73194), True, 'import numpy as np\n'), ((76979, 77008), 'numpy.log10', 'np.log10', (['sphere_surface_area'], {}), '(sphere_surface_area)\n', (76987, 77008), True, 'import numpy as np\n'), ((8117, 8139), 'numpy.array', 'np.array', (['transpose[2]'], {}), '(transpose[2])\n', (8125, 8139), True, 'import numpy as np\n'), ((8173, 8195), 'numpy.array', 'np.array', (['transpose[3]'], {}), '(transpose[3])\n', (8181, 8195), True, 'import numpy as np\n'), ((8229, 8251), 'numpy.array', 'np.array', (['transpose[4]'], {}), '(transpose[4])\n', (8237, 8251), True, 'import numpy as np\n'), ((14689, 14698), 'numpy.sum', 'np.sum', (['S'], {}), '(S)\n', (14695, 14698), True, 'import numpy as np\n'), ((20835, 20850), 'numpy.cos', 'np.cos', (['r_gamma'], {}), '(r_gamma)\n', (20841, 20850), True, 'import numpy as np\n'), ((21083, 21097), 'numpy.cos', 'np.cos', (['r_beta'], {}), '(r_beta)\n', (21089, 21097), True, 'import numpy as np\n'), ((21100, 21115), 'numpy.cos', 'np.cos', (['r_gamma'], {}), '(r_gamma)\n', (21106, 21115), True, 'import numpy as np\n'), ((21684, 21699), 'numpy.sin', 'np.sin', (['gamma_r'], {}), '(gamma_r)\n', (21690, 21699), True, 'import numpy as np\n'), ((34243, 34264), 'numpy.array', 'np.array', (['i[1 + adj:]'], {}), '(i[1 + adj:])\n', (34251, 34264), True, 'import numpy as np\n'), ((43485, 43500), 'numpy.sin', 'np.sin', (['angle_1'], {}), '(angle_1)\n', (43491, 43500), True, 'import numpy as np\n'), ((43984, 43999), 'numpy.sin', 'np.sin', (['angle_2'], {}), '(angle_2)\n', (43990, 43999), True, 'import numpy as np\n'), ((47536, 47553), 'numpy.sin', 'np.sin', (['angle_2_1'], {}), '(angle_2_1)\n', (47542, 47553), True, 'import numpy as np\n'), ((47763, 47780), 'numpy.sin', 'np.sin', (['angle_1_1'], {}), '(angle_1_1)\n', (47769, 47780), True, 'import numpy as np\n'), ((55158, 55194), 'numpy.array', 'np.array', (['clustered_results[cluster]'], {}), '(clustered_results[cluster])\n', (55166, 55194), True, 'import numpy as np\n'), ((58940, 58955), 'numpy.sin', 'np.sin', (['angle_1'], {}), '(angle_1)\n', (58946, 58955), True, 'import numpy as np\n'), ((59439, 59454), 'numpy.sin', 'np.sin', (['angle_2'], {}), '(angle_2)\n', (59445, 59454), True, 'import numpy as np\n'), ((71311, 71330), 'numpy.linalg.norm', 'np.linalg.norm', (['P_1'], {}), '(P_1)\n', (71325, 71330), True, 'import numpy as np\n'), ((75258, 75277), 'numpy.linalg.norm', 'np.linalg.norm', (['P_0'], {}), '(P_0)\n', (75272, 75277), True, 'import numpy as np\n'), ((20767, 20782), 'numpy.cos', 'np.cos', (['r_gamma'], {}), '(r_gamma)\n', (20773, 20782), True, 'import numpy as np\n'), ((20818, 20832), 'numpy.cos', 'np.cos', (['r_beta'], {}), '(r_beta)\n', (20824, 20832), True, 'import numpy as np\n'), ((20747, 20761), 'numpy.cos', 'np.cos', (['r_beta'], {}), '(r_beta)\n', (20753, 20761), True, 'import numpy as np\n'), ((20800, 20815), 'numpy.cos', 'np.cos', (['r_alpha'], {}), '(r_alpha)\n', (20806, 20815), True, 'import numpy as np\n'), ((34582, 34595), 'numpy.where', 'np.where', (['idx'], {}), '(idx)\n', (34590, 34595), True, 'import numpy as np\n'), ((34688, 34710), 'numpy.array', 'np.array', (['atom_coor[j]'], {}), '(atom_coor[j])\n', (34696, 34710), True, 'import numpy as np\n'), ((35404, 35418), 'numpy.where', 'np.where', (['sidx'], {}), '(sidx)\n', (35412, 35418), True, 'import numpy as np\n'), ((54736, 54772), 'numpy.array', 'np.array', (['clustered_results[cluster]'], {}), '(clustered_results[cluster])\n', (54744, 54772), True, 'import numpy as np\n'), ((20726, 20741), 'numpy.cos', 'np.cos', (['r_alpha'], {}), '(r_alpha)\n', (20732, 20741), True, 'import numpy as np\n'), ((35646, 35669), 'numpy.array', 'np.array', (['satom_coor[j]'], {}), '(satom_coor[j])\n', (35654, 35669), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
from typing import List
import numpy as np
import copy
import pprint as pp
from scipy.misc import logsumexp
from scipy.stats import beta
from neuralmonkey.vocabulary import Vocabulary
from n_gram_model import NGramModel
from hypothesis import Hypothesis, ExpandFunction
from beam_search import score_hypothesis, compute_feature, \
log_softmax, expand_null, empty_hypothesis
def list_startswith(list1, list2):
return all([token1 == token2 for token1, token2 in zip(list1, list2)])
def update_weights(violation_hyp: Hypothesis, target_hyp: Hypothesis,
weights: dict, states_cnt: int):
LEARNING_RATE = 0.0005
for key in weights.keys():
weights[key] += LEARNING_RATE * (compute_feature(key, target_hyp, states_cnt) -
compute_feature(key, violation_hyp, states_cnt))
def add_expanded_hyp(
ctc_table: np.ndarray,
weights: dict,
row: int,
col: int,
candidate_hyp: Hypothesis,
parent: (int, int)):
current_hyp = ctc_table[row, col]
weights = {
"lm_score" : 0.0,
"null_trailing" : 0.0,
"null_token_ratio" : 0.0
}
if current_hyp:
score_current = score_hypothesis(current_hyp[0], weights, 0)
score_candidate = score_hypothesis(candidate_hyp, weights, 0)
if score_candidate <= score_current:
return
candidate_hyp.recombine_with(current_hyp[0])
ctc_table[row, col] = (candidate_hyp, parent)
def ctc_path(
target: List,
log_prob_table: np.ndarray,
weights: dict,
lm: NGramModel,
vocabulary: Vocabulary) -> List[Hypothesis]:
rows = len(target) + 1
time_steps = len(log_prob_table)
# error in data, target cannot be decoded
if time_steps < len(target):
return None
ctc_table = np.empty(shape=(rows, time_steps), dtype=tuple)
# fill the starting cell with the empty hypothesis
ctc_table[0,0] = (empty_hypothesis(), None)
for time in range(time_steps-1):
null_log_prob = log_prob_table[time, -1]
# fill only the space around the diagonal
min_row = max(0, rows - (time_steps-time))
max_row = min(time + 1, len(target))
for row in range(min_row, max_row):
hyp = ctc_table[row, time][0]
next_token = target[row]
next_token_idx = vocabulary.word_to_index[next_token]
# add eps
expanded = expand_null(hyp, null_log_prob)
add_expanded_hyp(ctc_table, weights, row, time+1,
candidate_hyp=expanded, parent=(row, time))
# add next token
next_token_score = log_prob_table[time, next_token_idx]
expanded = lm.expand_token(hyp, next_token, next_token_score)
add_expanded_hyp(ctc_table, weights, row+1, time+1,
candidate_hyp=expanded, parent=(row, time))
# reconstruct path
path = []
hyp = ctc_table[rows-1, time_steps-1]
# error in data
if hyp is None:
return None
while True:
path.append(hyp[0])
prev_idx = hyp[1]
if prev_idx is None:
break
hyp = ctc_table[prev_idx]
path.reverse()
return path
def train_weights(
logits_table: np.ndarray,
beam_width: int,
vocabulary: Vocabulary,
target: list,
weights: dict,
lm: NGramModel) -> List[str]:
assert beam_width >= 1
log_prob_table = log_softmax(logits_table)
hypotheses = [empty_hypothesis()]
time_steps = log_prob_table.shape[0]
target_hyp_path = ctc_path(target, log_prob_table, weights, lm, vocabulary)
# error in data
if target_hyp_path is None:
return
states_cnt = len(log_prob_table)
for time in range(len(log_prob_table)-1):
log_probs = log_prob_table[time]
null_log_prob = log_probs[-1]
token_log_probs = log_probs[:-1]
new_hypotheses = []
str_to_hyp = {}
for hyp in hypotheses:
expanded = expand_null(hyp, null_log_prob)
str_to_hyp[" ".join(expanded.tokens)] = (
expanded, len(new_hypotheses))
new_hypotheses.append(expanded)
best_tokens = np.argpartition(
-token_log_probs, 2 * beam_width)[:2 * beam_width]
best_scores = token_log_probs[best_tokens]
for hyp_index, hyp in enumerate(hypotheses):
for token_index, score in zip(best_tokens, best_scores):
token = vocabulary.index_to_word[token_index]
expanded = lm.expand_token(hyp, token, score)
score = score_hypothesis(expanded, weights, states_cnt)
hyp_str = " ".join(expanded.tokens)
if hyp_str in str_to_hyp:
orig_hyp, hyp_index = str_to_hyp[hyp_str]
expanded.recombine_with(orig_hyp)
new_hypotheses[hyp_index] = expanded
str_to_hyp[hyp_str] = (expanded, hyp_index)
else:
str_to_hyp[hyp_str] = (expanded, len(new_hypotheses))
new_hypotheses.append(expanded)
target_candidates_indices = [i for i, h in enumerate(new_hypotheses)
if list_startswith(target, h.tokens)]
new_scores = np.array([score_hypothesis(h, weights, states_cnt)
for h in new_hypotheses])
target_candidates = [new_hypotheses[i]
for i in target_candidates_indices]
target_candidates_tokens_cnt = np.array([len(h.tokens)
for h in target_candidates])
best_hyp_indices = np.argsort(-new_scores)
target_hyp_ranks = np.in1d(best_hyp_indices, target_candidates_indices).nonzero()[0]
hypotheses = [new_hypotheses[i] for i in best_hyp_indices[:beam_width]]
# hypotheses are out of the beam or no hypotheses can be finished in time
if (all(target_hyp_ranks >= beam_width) or
all(target_candidates_tokens_cnt + (time_steps - time) < len(target))):
for i in range(beam_width):
violation_hyp = hypotheses[i]
target_hyp = target_hyp_path[time+1]
update_weights(violation_hyp, target_hyp, weights, states_cnt)
return
|
[
"beam_search.empty_hypothesis",
"numpy.empty",
"beam_search.compute_feature",
"beam_search.score_hypothesis",
"numpy.argsort",
"numpy.argpartition",
"beam_search.expand_null",
"beam_search.log_softmax",
"numpy.in1d"
] |
[((1875, 1922), 'numpy.empty', 'np.empty', ([], {'shape': '(rows, time_steps)', 'dtype': 'tuple'}), '(shape=(rows, time_steps), dtype=tuple)\n', (1883, 1922), True, 'import numpy as np\n'), ((3544, 3569), 'beam_search.log_softmax', 'log_softmax', (['logits_table'], {}), '(logits_table)\n', (3555, 3569), False, 'from beam_search import score_hypothesis, compute_feature, log_softmax, expand_null, empty_hypothesis\n'), ((1255, 1299), 'beam_search.score_hypothesis', 'score_hypothesis', (['current_hyp[0]', 'weights', '(0)'], {}), '(current_hyp[0], weights, 0)\n', (1271, 1299), False, 'from beam_search import score_hypothesis, compute_feature, log_softmax, expand_null, empty_hypothesis\n'), ((1326, 1369), 'beam_search.score_hypothesis', 'score_hypothesis', (['candidate_hyp', 'weights', '(0)'], {}), '(candidate_hyp, weights, 0)\n', (1342, 1369), False, 'from beam_search import score_hypothesis, compute_feature, log_softmax, expand_null, empty_hypothesis\n'), ((2001, 2019), 'beam_search.empty_hypothesis', 'empty_hypothesis', ([], {}), '()\n', (2017, 2019), False, 'from beam_search import score_hypothesis, compute_feature, log_softmax, expand_null, empty_hypothesis\n'), ((3588, 3606), 'beam_search.empty_hypothesis', 'empty_hypothesis', ([], {}), '()\n', (3604, 3606), False, 'from beam_search import score_hypothesis, compute_feature, log_softmax, expand_null, empty_hypothesis\n'), ((5799, 5822), 'numpy.argsort', 'np.argsort', (['(-new_scores)'], {}), '(-new_scores)\n', (5809, 5822), True, 'import numpy as np\n'), ((2497, 2528), 'beam_search.expand_null', 'expand_null', (['hyp', 'null_log_prob'], {}), '(hyp, null_log_prob)\n', (2508, 2528), False, 'from beam_search import score_hypothesis, compute_feature, log_softmax, expand_null, empty_hypothesis\n'), ((4111, 4142), 'beam_search.expand_null', 'expand_null', (['hyp', 'null_log_prob'], {}), '(hyp, null_log_prob)\n', (4122, 4142), False, 'from beam_search import score_hypothesis, compute_feature, log_softmax, expand_null, empty_hypothesis\n'), ((4311, 4360), 'numpy.argpartition', 'np.argpartition', (['(-token_log_probs)', '(2 * beam_width)'], {}), '(-token_log_probs, 2 * beam_width)\n', (4326, 4360), True, 'import numpy as np\n'), ((765, 809), 'beam_search.compute_feature', 'compute_feature', (['key', 'target_hyp', 'states_cnt'], {}), '(key, target_hyp, states_cnt)\n', (780, 809), False, 'from beam_search import score_hypothesis, compute_feature, log_softmax, expand_null, empty_hypothesis\n'), ((854, 901), 'beam_search.compute_feature', 'compute_feature', (['key', 'violation_hyp', 'states_cnt'], {}), '(key, violation_hyp, states_cnt)\n', (869, 901), False, 'from beam_search import score_hypothesis, compute_feature, log_softmax, expand_null, empty_hypothesis\n'), ((4714, 4761), 'beam_search.score_hypothesis', 'score_hypothesis', (['expanded', 'weights', 'states_cnt'], {}), '(expanded, weights, states_cnt)\n', (4730, 4761), False, 'from beam_search import score_hypothesis, compute_feature, log_softmax, expand_null, empty_hypothesis\n'), ((5430, 5470), 'beam_search.score_hypothesis', 'score_hypothesis', (['h', 'weights', 'states_cnt'], {}), '(h, weights, states_cnt)\n', (5446, 5470), False, 'from beam_search import score_hypothesis, compute_feature, log_softmax, expand_null, empty_hypothesis\n'), ((5850, 5902), 'numpy.in1d', 'np.in1d', (['best_hyp_indices', 'target_candidates_indices'], {}), '(best_hyp_indices, target_candidates_indices)\n', (5857, 5902), True, 'import numpy as np\n')]
|
# ---
# jupyter:
# jupytext:
# formats: ipynb,py
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.9.1+dev
# kernelspec:
# display_name: Python [conda env:generic_expression] *
# language: python
# name: conda-env-generic_expression-py
# ---
# # Compare generic genes
#
# The goal of this notebook is to compare the generic genes found using the same template experiment run two times and 2 different recount2 template experiments.
# +
# %load_ext autoreload
# %autoreload 2
import os
from scipy import stats
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from ponyo import utils
# +
# Read in config variables
base_dir = os.path.abspath(os.path.join(os.getcwd(), "../"))
config_filename = os.path.abspath(
os.path.join(base_dir, "configs", "config_human_general.tsv")
)
params = utils.read_config(config_filename)
local_dir = params["local_dir"]
project_id1 = "SRP012656"
project_id2 = "SRP061689"
# +
# Get data directory containing gene summary data
data_dir = os.path.join(base_dir, "human_general_analysis")
# Get gene ranking files
gene_ranking_filename1 = os.path.join(
data_dir, f"generic_gene_summary_{project_id1}.tsv"
)
gene_ranking_filename1_run2 = os.path.join(
data_dir, f"generic_gene_summary_{project_id1}_run2.tsv"
)
gene_ranking_filename2 = os.path.join(
data_dir, f"generic_gene_summary_{project_id2}.tsv"
)
# Get template data
template_filename1 = os.path.join(
data_dir, "data", f"processed_recount2_template_{project_id1}.tsv"
)
template_filename2 = os.path.join(
data_dir, "data", f"processed_recount2_template_{project_id2}.tsv"
)
# -
# ## Correlation between rankings between same experiment
#
# Here we compare gene ranking after running SOPHIE 2 times using the same template experiment but different seeds.
# Load gene ranking
gene_ranking_summary1 = pd.read_csv(
gene_ranking_filename1, sep="\t", index_col=0, header=0
)
gene_ranking_summary1_run2 = pd.read_csv(
gene_ranking_filename1_run2, sep="\t", index_col=0, header=0
)
# Get simulated ranking
gene_ranking1 = (
gene_ranking_summary1["Rank (simulated)"].rename("Rank 1").to_frame("Rank 1")
)
gene_ranking1_run2 = (
gene_ranking_summary1_run2["Rank (simulated)"].rename("Rank 2").to_frame("Rank 2")
)
# +
# Scale ranking to percentile (0,100)
scaler = MinMaxScaler(feature_range=(0, 100))
gene_ranking1["Percentile 1"] = scaler.fit_transform(
np.array(gene_ranking1["Rank 1"]).reshape(-1, 1)
)
gene_ranking1_run2["Percentile 2"] = scaler.fit_transform(
np.array(gene_ranking1_run2["Rank 2"]).reshape(-1, 1)
)
gene_ranking1_run2.head()
# -
# Combine ranking
gene_ranking_same_combined = pd.concat(
[gene_ranking1["Percentile 1"], gene_ranking1_run2["Percentile 2"]], axis=1
)
print(gene_ranking_same_combined.shape)
gene_ranking_same_combined.head()
# Check for NAs
gene_ranking_same_combined[pd.isnull(gene_ranking_same_combined).any(axis=1)]
# +
# Plot correlation between ranking
r, p = stats.spearmanr(
gene_ranking_same_combined["Percentile 1"],
gene_ranking_same_combined["Percentile 2"],
)
print(r, p)
fig = sns.jointplot(
data=gene_ranking_same_combined,
x="Percentile 1",
y="Percentile 2",
kind="hex",
marginal_kws={"color": "white", "edgecolor": "white"},
)
fig.set_axis_labels(
f"Percentile in {project_id1}",
f"Percentile in {project_id1} different runs",
fontsize=14,
fontname="Verdana",
)
cbar_ax = fig.fig.add_axes([0.9, 0.25, 0.05, 0.4]) # x, y, width, height
cb = plt.colorbar(cax=cbar_ax)
cb.set_label("Number of genes")
output_figure_filename = "concordance_between_same_recount2_templates.svg"
fig.savefig(
output_figure_filename,
format="svg",
bbox_inches="tight",
transparent=True,
pad_inches=0,
dpi=300,
)
# -
# **Takeaway:**
# * Running SOPHIE twice using the same template experiment will generate 2 different sets of simulated experiments.
# * Since the template experiment is the same, these 2 sets of simulated experiments will have the same experimental design structure/biological context
# * As expected, the concordance is very high especially for high ranked and low ranked genes. The genes in the middle rank are more sensitive to changes so you don't get as clear of a signal compared to the extreme ranked genes.
# ## Correlation between rankings between 2 different experiments
#
# Here we compare gene ranking generated by SOPHIE using 2 different template experiments.
# Load gene ranking
gene_ranking_summary2 = pd.read_csv(
gene_ranking_filename2, sep="\t", index_col=0, header=0
)
# Get simulated ranking
gene_ranking1 = (
gene_ranking_summary1["Rank (simulated)"].rename("Rank 1").to_frame("Rank 1")
)
gene_ranking2 = (
gene_ranking_summary2["Rank (simulated)"].rename("Rank 2").to_frame("Rank 2")
)
# +
# Scale ranking to percentile (0,100)
scaler = MinMaxScaler(feature_range=(0, 100))
gene_ranking1["Percentile 1"] = scaler.fit_transform(
np.array(gene_ranking1["Rank 1"]).reshape(-1, 1)
)
gene_ranking2["Percentile 2"] = scaler.fit_transform(
np.array(gene_ranking2["Rank 2"]).reshape(-1, 1)
)
gene_ranking2.head()
# -
# Combine ranking
gene_ranking_diff_combined = pd.concat(
[gene_ranking1["Percentile 1"], gene_ranking2["Percentile 2"]], axis=1
)
print(gene_ranking_diff_combined.shape)
gene_ranking_diff_combined.head()
# Check for NAs
gene_ranking_diff_combined[pd.isnull(gene_ranking_diff_combined).any(axis=1)]
# +
# Plot correlation between ranking
r, p = stats.spearmanr(
gene_ranking_diff_combined["Percentile 1"],
gene_ranking_diff_combined["Percentile 2"],
)
print(r, p)
fig = sns.jointplot(
data=gene_ranking_diff_combined,
x="Percentile 1",
y="Percentile 2",
kind="hex",
marginal_kws={"color": "white", "edgecolor": "white"},
)
fig.set_axis_labels(
f"Percentile in {project_id1}",
f"Percentile in {project_id2}",
fontsize=14,
fontname="Verdana",
)
cbar_ax = fig.fig.add_axes([0.9, 0.25, 0.05, 0.4]) # x, y, width, height
cb = plt.colorbar(cax=cbar_ax)
cb.set_label("Number of genes")
output_figure_filename = "concordance_between_diff_recount2_templates.svg"
fig.savefig(
output_figure_filename,
format="svg",
bbox_inches="tight",
transparent=True,
pad_inches=0,
dpi=300,
)
# -
# **Takeaway:**
#
# * Looks like there is good concordance between highly ranked genes (i.e. generic genes)
# * By comparison if we run SOPHIE using two different template experiments, there are genes in the off-diagonal regions that might indicate that there are generic within the given context of the specific experiment.
# * In general, the genes in the middle rank are more sensitive to changes so you don't get as clear of a signal compared to the highest rank genes.
# ## Examine gene expression data
# Read expression data
template_1 = pd.read_csv(template_filename1, sep="\t", index_col=0, header=0)
template_2 = pd.read_csv(template_filename2, sep="\t", index_col=0, header=0)
# +
# Get concordance genes
concordant_genes = list(
gene_ranking_diff_combined[
(gene_ranking_diff_combined["Percentile 1"] > 80)
& (gene_ranking_diff_combined["Percentile 2"] > 80)
].index
)
# Get disconcordant genes
discordant_genes = set(gene_ranking_diff_combined.index).difference(concordant_genes)
# +
# Distribution of concordant genes in template experiment 1
template1_mean = template_1.mean()
print(
"Percent concordant genes with 0 expression in template 1:",
len(template1_mean[concordant_genes].loc[template1_mean[concordant_genes] == 0])
/ len(template1_mean[concordant_genes]),
)
print(
"Percent nonzero concordant genes in template 1:",
len(
template1_mean[concordant_genes].loc[
(template1_mean[concordant_genes] > 0)
& (template1_mean[concordant_genes] < 1000)
]
)
/ len(template1_mean[concordant_genes]),
)
f1 = sns.distplot(template_1.mean()[concordant_genes], kde=False)
f1.set_title(f"Expression of concordant genes in {project_id1}")
f1.set_xlabel("log(gene expression)")
f1.set_ylabel("log(count)")
f1.set(xscale="log", yscale="log")
# +
# Distribution of concordant genes in template experiment 2
template2_mean = template_2.mean()
print(
"Percent concordant genes with 0 expression in template 2:",
len(template2_mean[concordant_genes].loc[template2_mean[concordant_genes] == 0])
/ len(template2_mean[concordant_genes]),
)
print(
"Percent nonzero concordant genes in template 2:",
len(
template2_mean[concordant_genes].loc[
(template2_mean[concordant_genes] > 0)
& (template2_mean[concordant_genes] < 1000)
]
)
/ len(template2_mean[concordant_genes]),
)
# There are more 0 expressed genes in this template experiment
f2 = sns.distplot(template_2.mean()[concordant_genes], kde=False)
f2.set_title(f"Expression of concordant genes in {project_id2}")
f2.set_xlabel("log(gene expression)")
f2.set_ylabel("log(count)")
f2.set(xscale="log", yscale="log")
# +
# Distribution of discordant gense in template experiment 1
template1_mean = template_1.mean()
print(
"Percent discordant genes with 0 expression in template 1:",
len(template1_mean[discordant_genes].loc[template1_mean[discordant_genes] == 0])
/ len(template1_mean[discordant_genes]),
)
print(
"Percent nonzero discordant genes in template 1:",
len(
template1_mean[discordant_genes].loc[
(template1_mean[discordant_genes] > 0)
& (template1_mean[discordant_genes] < 1000)
]
)
/ len(template1_mean[discordant_genes]),
)
print(
len(template1_mean[discordant_genes].loc[template1_mean[discordant_genes] > 0])
/ len(template1_mean[discordant_genes])
)
f3 = sns.distplot(template_1.mean()[discordant_genes], kde=False)
f3.set_title(f"Expression of discordant genes in {project_id1}")
f3.set_xlabel("log(gene expression)")
f3.set_ylabel("log(count)")
f3.set(xscale="log", yscale="log")
# +
# Distribution of discordant genes in template experiment 2
template2_mean = template_2.mean()
print(
"Percent discordant genes with 0 expression in template 2:",
len(template2_mean[discordant_genes].loc[template2_mean[discordant_genes] == 0])
/ len(template2_mean[discordant_genes]),
)
print(
"Percent nonzero discordant genes in template 2:",
len(
template2_mean[discordant_genes].loc[
(template2_mean[discordant_genes] > 0)
& (template2_mean[discordant_genes] < 1000)
]
)
/ len(template2_mean[discordant_genes]),
)
f4 = sns.distplot(template_2.mean()[discordant_genes], kde=False)
f4.set_title(f"Expression of discordant genes in {project_id2}")
f4.set_xlabel("log(gene expression)")
f4.set_ylabel("log(count)")
f4.set(xscale="log", yscale="log")
# -
# **Takeaway:**
#
# Doesn't appear to be much of a difference between the distribution of average gene expression values for these two experiments.
#
# Theoretically, I would expect the scenario where a gene is lowly expressed in the context of template experiment 1 and therefore not found to be generic. But this same gene could be found to be generic in the context of template experiment 2 if it is more expressed. Its possible that differences in gene expression distribution can change which genes are found to be generic given that the simulation is producing experiments with a similar context.
#
# In this case, despite having similar gene expression distributions there are still many differences in gene ranking. This suggests to me that level of gene expression activity doesn't matter as much as the overall patterns perhaps.
#
# Overall we observe a slight shift showing that concordant genes are more lowly expressed compared to discordant genes, but most genes are still predominantly lowly gene expression. If most genes have expression levels very close to 0, then small fluctuations in the expression of some genes could lead to large changes in rank without changing the overall expression distribution.
|
[
"pandas.read_csv",
"os.getcwd",
"sklearn.preprocessing.MinMaxScaler",
"scipy.stats.spearmanr",
"ponyo.utils.read_config",
"pandas.isnull",
"matplotlib.pyplot.colorbar",
"numpy.array",
"seaborn.jointplot",
"os.path.join",
"pandas.concat"
] |
[((987, 1021), 'ponyo.utils.read_config', 'utils.read_config', (['config_filename'], {}), '(config_filename)\n', (1004, 1021), False, 'from ponyo import utils\n'), ((1174, 1222), 'os.path.join', 'os.path.join', (['base_dir', '"""human_general_analysis"""'], {}), "(base_dir, 'human_general_analysis')\n", (1186, 1222), False, 'import os\n'), ((1274, 1339), 'os.path.join', 'os.path.join', (['data_dir', 'f"""generic_gene_summary_{project_id1}.tsv"""'], {}), "(data_dir, f'generic_gene_summary_{project_id1}.tsv')\n", (1286, 1339), False, 'import os\n'), ((1376, 1446), 'os.path.join', 'os.path.join', (['data_dir', 'f"""generic_gene_summary_{project_id1}_run2.tsv"""'], {}), "(data_dir, f'generic_gene_summary_{project_id1}_run2.tsv')\n", (1388, 1446), False, 'import os\n'), ((1478, 1543), 'os.path.join', 'os.path.join', (['data_dir', 'f"""generic_gene_summary_{project_id2}.tsv"""'], {}), "(data_dir, f'generic_gene_summary_{project_id2}.tsv')\n", (1490, 1543), False, 'import os\n'), ((1592, 1677), 'os.path.join', 'os.path.join', (['data_dir', '"""data"""', 'f"""processed_recount2_template_{project_id1}.tsv"""'], {}), "(data_dir, 'data', f'processed_recount2_template_{project_id1}.tsv'\n )\n", (1604, 1677), False, 'import os\n'), ((1700, 1785), 'os.path.join', 'os.path.join', (['data_dir', '"""data"""', 'f"""processed_recount2_template_{project_id2}.tsv"""'], {}), "(data_dir, 'data', f'processed_recount2_template_{project_id2}.tsv'\n )\n", (1712, 1785), False, 'import os\n'), ((2013, 2081), 'pandas.read_csv', 'pd.read_csv', (['gene_ranking_filename1'], {'sep': '"""\t"""', 'index_col': '(0)', 'header': '(0)'}), "(gene_ranking_filename1, sep='\\t', index_col=0, header=0)\n", (2024, 2081), True, 'import pandas as pd\n'), ((2117, 2190), 'pandas.read_csv', 'pd.read_csv', (['gene_ranking_filename1_run2'], {'sep': '"""\t"""', 'index_col': '(0)', 'header': '(0)'}), "(gene_ranking_filename1_run2, sep='\\t', index_col=0, header=0)\n", (2128, 2190), True, 'import pandas as pd\n'), ((2488, 2524), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(0, 100)'}), '(feature_range=(0, 100))\n', (2500, 2524), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((2834, 2925), 'pandas.concat', 'pd.concat', (["[gene_ranking1['Percentile 1'], gene_ranking1_run2['Percentile 2']]"], {'axis': '(1)'}), "([gene_ranking1['Percentile 1'], gene_ranking1_run2['Percentile 2'\n ]], axis=1)\n", (2843, 2925), True, 'import pandas as pd\n'), ((3144, 3251), 'scipy.stats.spearmanr', 'stats.spearmanr', (["gene_ranking_same_combined['Percentile 1']", "gene_ranking_same_combined['Percentile 2']"], {}), "(gene_ranking_same_combined['Percentile 1'],\n gene_ranking_same_combined['Percentile 2'])\n", (3159, 3251), False, 'from scipy import stats\n'), ((3278, 3436), 'seaborn.jointplot', 'sns.jointplot', ([], {'data': 'gene_ranking_same_combined', 'x': '"""Percentile 1"""', 'y': '"""Percentile 2"""', 'kind': '"""hex"""', 'marginal_kws': "{'color': 'white', 'edgecolor': 'white'}"}), "(data=gene_ranking_same_combined, x='Percentile 1', y=\n 'Percentile 2', kind='hex', marginal_kws={'color': 'white', 'edgecolor':\n 'white'})\n", (3291, 3436), True, 'import seaborn as sns\n'), ((3682, 3707), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'cax': 'cbar_ax'}), '(cax=cbar_ax)\n', (3694, 3707), True, 'import matplotlib.pyplot as plt\n'), ((4681, 4749), 'pandas.read_csv', 'pd.read_csv', (['gene_ranking_filename2'], {'sep': '"""\t"""', 'index_col': '(0)', 'header': '(0)'}), "(gene_ranking_filename2, sep='\\t', index_col=0, header=0)\n", (4692, 4749), True, 'import pandas as pd\n'), ((5037, 5073), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(0, 100)'}), '(feature_range=(0, 100))\n', (5049, 5073), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((5368, 5453), 'pandas.concat', 'pd.concat', (["[gene_ranking1['Percentile 1'], gene_ranking2['Percentile 2']]"], {'axis': '(1)'}), "([gene_ranking1['Percentile 1'], gene_ranking2['Percentile 2']],\n axis=1)\n", (5377, 5453), True, 'import pandas as pd\n'), ((5673, 5780), 'scipy.stats.spearmanr', 'stats.spearmanr', (["gene_ranking_diff_combined['Percentile 1']", "gene_ranking_diff_combined['Percentile 2']"], {}), "(gene_ranking_diff_combined['Percentile 1'],\n gene_ranking_diff_combined['Percentile 2'])\n", (5688, 5780), False, 'from scipy import stats\n'), ((5807, 5965), 'seaborn.jointplot', 'sns.jointplot', ([], {'data': 'gene_ranking_diff_combined', 'x': '"""Percentile 1"""', 'y': '"""Percentile 2"""', 'kind': '"""hex"""', 'marginal_kws': "{'color': 'white', 'edgecolor': 'white'}"}), "(data=gene_ranking_diff_combined, x='Percentile 1', y=\n 'Percentile 2', kind='hex', marginal_kws={'color': 'white', 'edgecolor':\n 'white'})\n", (5820, 5965), True, 'import seaborn as sns\n'), ((6197, 6222), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'cax': 'cbar_ax'}), '(cax=cbar_ax)\n', (6209, 6222), True, 'import matplotlib.pyplot as plt\n'), ((7021, 7085), 'pandas.read_csv', 'pd.read_csv', (['template_filename1'], {'sep': '"""\t"""', 'index_col': '(0)', 'header': '(0)'}), "(template_filename1, sep='\\t', index_col=0, header=0)\n", (7032, 7085), True, 'import pandas as pd\n'), ((7099, 7163), 'pandas.read_csv', 'pd.read_csv', (['template_filename2'], {'sep': '"""\t"""', 'index_col': '(0)', 'header': '(0)'}), "(template_filename2, sep='\\t', index_col=0, header=0)\n", (7110, 7163), True, 'import pandas as pd\n'), ((913, 974), 'os.path.join', 'os.path.join', (['base_dir', '"""configs"""', '"""config_human_general.tsv"""'], {}), "(base_dir, 'configs', 'config_human_general.tsv')\n", (925, 974), False, 'import os\n'), ((853, 864), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (862, 864), False, 'import os\n'), ((2584, 2617), 'numpy.array', 'np.array', (["gene_ranking1['Rank 1']"], {}), "(gene_ranking1['Rank 1'])\n", (2592, 2617), True, 'import numpy as np\n'), ((2699, 2737), 'numpy.array', 'np.array', (["gene_ranking1_run2['Rank 2']"], {}), "(gene_ranking1_run2['Rank 2'])\n", (2707, 2737), True, 'import numpy as np\n'), ((3046, 3083), 'pandas.isnull', 'pd.isnull', (['gene_ranking_same_combined'], {}), '(gene_ranking_same_combined)\n', (3055, 3083), True, 'import pandas as pd\n'), ((5133, 5166), 'numpy.array', 'np.array', (["gene_ranking1['Rank 1']"], {}), "(gene_ranking1['Rank 1'])\n", (5141, 5166), True, 'import numpy as np\n'), ((5243, 5276), 'numpy.array', 'np.array', (["gene_ranking2['Rank 2']"], {}), "(gene_ranking2['Rank 2'])\n", (5251, 5276), True, 'import numpy as np\n'), ((5575, 5612), 'pandas.isnull', 'pd.isnull', (['gene_ranking_diff_combined'], {}), '(gene_ranking_diff_combined)\n', (5584, 5612), True, 'import pandas as pd\n')]
|
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
import warnings
from matplotlib import colors
matplotlib.rc("font",family='AR PL SungtiL GB')
warnings.filterwarnings('ignore')
def vis_national(national, native, null, x):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.grid()
plt.title('2018-2020年度各区县馆编目数据占比')
years = [
'国图编目数据库',
'本地编目数据库',
'无编目数据库'
]
total_width, n = 0.8, len(years)
width = total_width / n
xx = np.arange(len(x))
xx = xx - (total_width - width) / 2
plt.bar(xx, national, width=width, label=years[0])
plt.bar(xx + width, native, width=width, label=years[1])
plt.bar(xx + 2 * width, null, width=width, label=years[2])
plt.xticks(range(len(x)), x, rotation = 45)
plt.ylabel('百分比(%)')
plt.xlabel('区县图书馆')
plt.legend(loc='best')
plt.axhline(50, color = 'r')
name = 'data'
plt.savefig(name)
return
def book_purchase(p18, p19, p20, x):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.grid()
plt.title('2018-2020年度各区县馆中文图书入藏量')
years = [
'2018',
'2019',
'2020'
]
total_width, n = 0.8, len(years)
width = total_width / n
xx = np.arange(len(x))
xx = xx - (total_width - width) / 2
plt.bar(xx, p18, width=width, label=years[0])
plt.bar(xx + width, p19, width=width, label=years[1])
plt.bar(xx + 2 * width, p20, width=width, label=years[2])
plt.xticks(range(len(x)), x, rotation = 45)
plt.ylabel('中文图书入藏量(册)')
plt.xlabel('区县图书馆')
plt.legend(loc='best')
plt.axhline(20000, color = 'r')
max18 = np.argmax(np.array(p18))
max19 = np.argmax(np.array(p19))
max20 = np.argmax(np.array(p20))
plt.annotate(
x[max18] + str(p18[max18]),
xy = (max18, p18[max18]),
bbox = dict(fc=(1,0.9,0.9))
)
plt.annotate(
x[max19] + str(p19[max19]),
xy = (max19, p19[max19]),
bbox = dict(fc=(1,0.9,0.9))
)
plt.annotate(
x[max20] + str(p20[max20]),
xy = (max20, p20[max20]),
bbox = dict(fc=(1,0.9,0.9))
)
name = 'purchase'
plt.savefig(name)
return
def delay_time(delay, x):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.grid()
plt.title('2018-2020年度各区县馆无编目数据图书平均滞后周期')
plt.xticks(range(len(x)), x, rotation = 45)
plt.ylabel('无编目数据图书平均滞后周期(月)')
plt.xlabel('区县图书馆')
# plt.legend(loc='best')
xx = range(len(x))
plt.plot(xx, delay, marker = 'o', markersize = 2)
plt.axhline(3, color = 'r')
for xxy in zip(xx, delay):
plt.annotate(
str(xxy[1]),
xy = xxy,
bbox = dict(fc=(1,0.9,0.9))
)
name = 'delay'
plt.savefig(name)
return
if __name__ == '__main__':
national = [
5,
70,
85,
20,
80,
50,
85,
40,
40,
40,
30,
100,
]
native = [
94,
10,
14,
79,
0,
50,
14,
50,
40,
40,
40,
0,
]
null = [
1,
20,
1,
1,
20,
1,
1,
10,
20,
20,
30,
0,
]
p18 = [
22299,
76721,
50234,
50369,
682,
275,
16381,
56261,
16934,
0,
41631,
33474,
]
p19 = [
24528,
28174,
21897,
15263,
1500,
2588,
19133,
23960,
26385,
0,
58390,
23005,
]
p20 = [
0,
14875,
12365,
27157,
0,
3186,
43311,
33822,
38390,
44433,
20068,
18744,
]
delay = [
2,
3,
4,
2,
3,
6,
4,
3,
24,
18,
9,
0.5,
]
x = [
'和平馆',
'河西馆',
'河东馆',
'红桥馆',
'河北馆',
'津南馆',
'西青馆',
'北辰馆',
'东丽馆',
'宁河馆',
'宝坻馆',
'蓟州馆',
]
vis_national(national, native, null, x)
book_purchase(p18, p19, p20, x)
delay_time(delay, x)
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.axhline",
"matplotlib.rc",
"matplotlib.pyplot.plot",
"warnings.filterwarnings",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig"
] |
[((126, 174), 'matplotlib.rc', 'matplotlib.rc', (['"""font"""'], {'family': '"""AR PL SungtiL GB"""'}), "('font', family='AR PL SungtiL GB')\n", (139, 174), False, 'import matplotlib\n'), ((175, 208), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (198, 208), False, 'import warnings\n'), ((266, 278), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (276, 278), True, 'import matplotlib.pyplot as plt\n'), ((313, 323), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (321, 323), True, 'import matplotlib.pyplot as plt\n'), ((328, 362), 'matplotlib.pyplot.title', 'plt.title', (['"""2018-2020年度各区县馆编目数据占比"""'], {}), "('2018-2020年度各区县馆编目数据占比')\n", (337, 362), True, 'import matplotlib.pyplot as plt\n'), ((575, 625), 'matplotlib.pyplot.bar', 'plt.bar', (['xx', 'national'], {'width': 'width', 'label': 'years[0]'}), '(xx, national, width=width, label=years[0])\n', (582, 625), True, 'import matplotlib.pyplot as plt\n'), ((630, 686), 'matplotlib.pyplot.bar', 'plt.bar', (['(xx + width)', 'native'], {'width': 'width', 'label': 'years[1]'}), '(xx + width, native, width=width, label=years[1])\n', (637, 686), True, 'import matplotlib.pyplot as plt\n'), ((691, 749), 'matplotlib.pyplot.bar', 'plt.bar', (['(xx + 2 * width)', 'null'], {'width': 'width', 'label': 'years[2]'}), '(xx + 2 * width, null, width=width, label=years[2])\n', (698, 749), True, 'import matplotlib.pyplot as plt\n'), ((803, 823), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""百分比(%)"""'], {}), "('百分比(%)')\n", (813, 823), True, 'import matplotlib.pyplot as plt\n'), ((828, 847), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""区县图书馆"""'], {}), "('区县图书馆')\n", (838, 847), True, 'import matplotlib.pyplot as plt\n'), ((852, 874), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (862, 874), True, 'import matplotlib.pyplot as plt\n'), ((879, 905), 'matplotlib.pyplot.axhline', 'plt.axhline', (['(50)'], {'color': '"""r"""'}), "(50, color='r')\n", (890, 905), True, 'import matplotlib.pyplot as plt\n'), ((930, 947), 'matplotlib.pyplot.savefig', 'plt.savefig', (['name'], {}), '(name)\n', (941, 947), True, 'import matplotlib.pyplot as plt\n'), ((1009, 1021), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1019, 1021), True, 'import matplotlib.pyplot as plt\n'), ((1056, 1066), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (1064, 1066), True, 'import matplotlib.pyplot as plt\n'), ((1071, 1106), 'matplotlib.pyplot.title', 'plt.title', (['"""2018-2020年度各区县馆中文图书入藏量"""'], {}), "('2018-2020年度各区县馆中文图书入藏量')\n", (1080, 1106), True, 'import matplotlib.pyplot as plt\n'), ((1311, 1356), 'matplotlib.pyplot.bar', 'plt.bar', (['xx', 'p18'], {'width': 'width', 'label': 'years[0]'}), '(xx, p18, width=width, label=years[0])\n', (1318, 1356), True, 'import matplotlib.pyplot as plt\n'), ((1361, 1414), 'matplotlib.pyplot.bar', 'plt.bar', (['(xx + width)', 'p19'], {'width': 'width', 'label': 'years[1]'}), '(xx + width, p19, width=width, label=years[1])\n', (1368, 1414), True, 'import matplotlib.pyplot as plt\n'), ((1419, 1476), 'matplotlib.pyplot.bar', 'plt.bar', (['(xx + 2 * width)', 'p20'], {'width': 'width', 'label': 'years[2]'}), '(xx + 2 * width, p20, width=width, label=years[2])\n', (1426, 1476), True, 'import matplotlib.pyplot as plt\n'), ((1530, 1554), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""中文图书入藏量(册)"""'], {}), "('中文图书入藏量(册)')\n", (1540, 1554), True, 'import matplotlib.pyplot as plt\n'), ((1559, 1578), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""区县图书馆"""'], {}), "('区县图书馆')\n", (1569, 1578), True, 'import matplotlib.pyplot as plt\n'), ((1583, 1605), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (1593, 1605), True, 'import matplotlib.pyplot as plt\n'), ((1610, 1639), 'matplotlib.pyplot.axhline', 'plt.axhline', (['(20000)'], {'color': '"""r"""'}), "(20000, color='r')\n", (1621, 1639), True, 'import matplotlib.pyplot as plt\n'), ((2176, 2193), 'matplotlib.pyplot.savefig', 'plt.savefig', (['name'], {}), '(name)\n', (2187, 2193), True, 'import matplotlib.pyplot as plt\n'), ((2244, 2256), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2254, 2256), True, 'import matplotlib.pyplot as plt\n'), ((2291, 2301), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2299, 2301), True, 'import matplotlib.pyplot as plt\n'), ((2306, 2347), 'matplotlib.pyplot.title', 'plt.title', (['"""2018-2020年度各区县馆无编目数据图书平均滞后周期"""'], {}), "('2018-2020年度各区县馆无编目数据图书平均滞后周期')\n", (2315, 2347), True, 'import matplotlib.pyplot as plt\n'), ((2400, 2430), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""无编目数据图书平均滞后周期(月)"""'], {}), "('无编目数据图书平均滞后周期(月)')\n", (2410, 2430), True, 'import matplotlib.pyplot as plt\n'), ((2435, 2454), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""区县图书馆"""'], {}), "('区县图书馆')\n", (2445, 2454), True, 'import matplotlib.pyplot as plt\n'), ((2511, 2556), 'matplotlib.pyplot.plot', 'plt.plot', (['xx', 'delay'], {'marker': '"""o"""', 'markersize': '(2)'}), "(xx, delay, marker='o', markersize=2)\n", (2519, 2556), True, 'import matplotlib.pyplot as plt\n'), ((2565, 2590), 'matplotlib.pyplot.axhline', 'plt.axhline', (['(3)'], {'color': '"""r"""'}), "(3, color='r')\n", (2576, 2590), True, 'import matplotlib.pyplot as plt\n'), ((2766, 2783), 'matplotlib.pyplot.savefig', 'plt.savefig', (['name'], {}), '(name)\n', (2777, 2783), True, 'import matplotlib.pyplot as plt\n'), ((1665, 1678), 'numpy.array', 'np.array', (['p18'], {}), '(p18)\n', (1673, 1678), True, 'import numpy as np\n'), ((1702, 1715), 'numpy.array', 'np.array', (['p19'], {}), '(p19)\n', (1710, 1715), True, 'import numpy as np\n'), ((1739, 1752), 'numpy.array', 'np.array', (['p20'], {}), '(p20)\n', (1747, 1752), True, 'import numpy as np\n')]
|
# Copyright 2019 Graphcore Ltd.
import tensorflow as tf
import os
import time
import argparse
import numpy as np
import random
from tensorflow.python.ipu.scopes import ipu_scope
from tensorflow.python.ipu import ipu_compiler
from seq2seq_edits import AttentionWrapperNoAssert, dynamic_decode, TrainingHelperNoCond, GreedyEmbeddingHelperNoCond
from data_gen.reader import Data, Vocabulary
from tensorflow.python.ipu import utils
import util
try:
import __builtin__
input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
pass
tf.logging.set_verbosity(tf.logging.ERROR)
time_major = True
DTYPE = tf.float16
forget_bias = 1.0
max_gradient_norm = 1
learning_rate = 1
CHECKPOINT_FILE = './weights/'
def print_data(src, src_vocab, tgt, tgt_vocab):
for i, s in enumerate(src.T):
t = tgt.T[i]
src_end_idx = list(s).index(src_vocab.end_id())
try:
tgt_end_idx = list(t).index(tgt_vocab.end_id())
except ValueError:
tgt_end_idx = len(t) - 1
print("{} -> {}".format(
''.join(src_vocab.int_to_string(s[:src_end_idx])),
''.join(tgt_vocab.int_to_string(t[:tgt_end_idx])),
))
class Nmt(object):
def __init__(self, opts):
self.opts = opts
self.src_length = opts.sequence_length
self.tgt_length = 11 # YYYY-MM-DD<eot>
def _build_generator(self, data, vocab):
instance_id = range(len(data.inputs))
priming = True
if priming and self.opts.infer:
priming = False
batch_ids = random.sample(instance_id, self.opts.batch_size)
src = np.array(data.inputs[batch_ids], dtype=np.int32)
yield {self.placeholders['source']: src.T, }
while True:
batch_ids = random.sample(instance_id, self.opts.batch_size)
src = np.array(data.inputs[batch_ids], dtype=np.int32)
if self.opts.infer:
if self.opts.interact:
src = np.array([vocab[0].string_to_int(input("Enter a human date: ").strip())])
yield {
self.placeholders['source']: src.T,
}
else:
tgt = np.roll(np.array(data.targets[batch_ids], dtype=np.int32), 1)
tgt[:, 0] = self.start_id
lbl = np.array(data.targets[batch_ids], dtype=np.int32)
mask = np.zeros(lbl.shape)
for i, label in enumerate(lbl):
end_idx = list(label).index(self.end_id)
mask[i][:end_idx+1] = 1
yield {
self.placeholders['source']: src.T,
self.placeholders['target']: tgt.T,
self.placeholders['label']: lbl.T,
self.placeholders['mask']: mask.T
}
def _build_inputs(self):
input_vocab = Vocabulary('./data/human_vocab.json', padding=self.src_length)
output_vocab = Vocabulary('./data/machine_vocab.json', padding=self.tgt_length)
self.src_vocab_size = input_vocab.size()
self.tgt_vocab_size = output_vocab.size()
self.start_id = output_vocab.start_id()
self.end_id = output_vocab.end_id()
data_file = './data/validation.csv' if self.opts.infer else './data/training.csv'
data = Data(data_file, input_vocab, output_vocab)
data.load()
data.transform()
self.placeholders = {
'source': tf.placeholder(tf.int32, shape=[self.src_length, self.opts.batch_size], name="source"),
'target': tf.placeholder(tf.int32, shape=[self.tgt_length, self.opts.batch_size], name="target"),
'label': tf.placeholder(tf.int32, shape=[self.tgt_length, self.opts.batch_size], name="label"),
'mask': tf.placeholder_with_default(
tf.constant(1, shape=[self.tgt_length, self.opts.batch_size], dtype=tf.float16),
[self.tgt_length, self.opts.batch_size],
name="mask")
}
vocab = (input_vocab, output_vocab)
generator = self._build_generator(data, vocab)
return generator, vocab
def infer(self):
def build_infer():
embedding = Nmt._build_embedding(self.src_vocab_size, self.opts.embedding_size,
name="source_embedding")
input_, encoder_outputs, encoder_state = self._build_encoder(embedding)
embedding = Nmt._build_embedding(self.tgt_vocab_size, self.opts.embedding_size, name="tgt_embedding")
samples, logits = self._build_decoder(encoder_outputs, encoder_state, embedding, train=False)
return samples, logits
with ipu_scope('/device:IPU:0'):
data, vocab = self._build_inputs()
batch = ipu_compiler.compile(build_infer, [])
# Create a restoring object
saver = tf.train.Saver()
ipu_options = util.get_config(report_n=0)
utils.configure_ipu_system(ipu_options)
session = tf.Session()
checkpoint = CHECKPOINT_FILE + 'ckpt'
saver.restore(session, checkpoint)
# Run a dummy value to force the graph compilation
session.run(batch, feed_dict=next(data))
while True:
feed_dict = next(data)
predictions, _ = session.run(batch, feed_dict=feed_dict)
print_data(feed_dict[self.placeholders['source']], vocab[0], predictions, vocab[1])
if not self.opts.interact:
break
def train(self):
def build_train():
embedding = Nmt._build_embedding(self.src_vocab_size, self.opts.embedding_size,
name="source_embedding")
input_, encoder_outputs, encoder_state = self._build_encoder(embedding)
embedding = Nmt._build_embedding(self.tgt_vocab_size, self.opts.embedding_size, name="tgt_embedding")
samples, logits = self._build_decoder(encoder_outputs, encoder_state, embedding, train=True)
loss, update = self._build_optimiser(logits)
return loss, samples, logits, update
with ipu_scope('/device:IPU:0'):
data, _ = self._build_inputs()
batch = ipu_compiler.compile(build_train, [])
# Create a restoring object
saver = tf.train.Saver()
if self.opts.save_graph:
# Dump the graph to a logdir
writer = tf.summary.FileWriter(os.path.join('./logs', 'NMT', time.strftime('%Y%m%d_%H%M%S_%Z')))
writer.add_graph(tf.get_default_graph())
ipu_options = util.get_config(report_n=0)
utils.configure_ipu_system(ipu_options)
session = tf.Session()
checkpoint = CHECKPOINT_FILE + 'ckpt'
if self.opts.ckpt:
saver.restore(session, checkpoint)
else:
utils.move_variable_initialization_to_cpu()
session.run(tf.global_variables_initializer())
print("Init done.")
session.run(batch, feed_dict=next(data)) # Warmup
duration = 0
avg_loss = 0
best_loss = float('Inf')
for e in range(1, 1 + self.opts.steps):
start = time.time()
l, _, _ = session.run(batch, feed_dict=next(data))
duration += time.time() - start
avg_loss += l
if (e <= 1000 and not e % 100) or not e % 1000:
duration /= 100 if e <= 1000 else 1000
avg_loss /= 100 if e <= 1000 else 1000
print("Step: {:>5}. Average Loss {:.3}. Items/sec {:.4}. Tokens/sec {}".format(
e,
avg_loss,
self.opts.batch_size / duration,
self.opts.batch_size * (self.src_length + self.tgt_length) / duration))
if avg_loss < best_loss:
best_loss = avg_loss
saver.save(session, checkpoint)
duration = 0
avg_loss = 0
@staticmethod
def _build_embedding(vocab_size, embedding_size, name="embedding"):
with tf.variable_scope("embedding", dtype=DTYPE, use_resource=True) as scope:
# Random embedding
embedding = tf.get_variable(
name, [vocab_size, embedding_size], scope.dtype,
initializer=tf.initializers.random_uniform(maxval=1.0, dtype=scope.dtype), trainable=False)
return embedding
@staticmethod
def _build_cell(num_units, num_layers):
if num_layers is 1:
return tf.contrib.rnn.BasicLSTMCell(num_units, forget_bias=forget_bias, state_is_tuple=False)
cell_list = []
for i in range(num_layers):
cell_list.append(tf.contrib.rnn.BasicLSTMCell(
num_units,
forget_bias=forget_bias, state_is_tuple=False))
return tf.contrib.rnn.MultiRNNCell(cell_list)
def _build_encoder(self, embedding):
with tf.variable_scope("input", dtype=DTYPE, use_resource=True) as scope:
source = self.placeholders['source']
encoder_emb_inp = tf.nn.embedding_lookup(
embedding, source)
with tf.variable_scope("encoder", dtype=DTYPE, use_resource=True) as scope: # use resource
dtype = scope.dtype
cell = Nmt._build_cell(self.opts.num_units, self.opts.num_layers)
if self.opts.bi:
outputs, states = tf.nn.bidirectional_dynamic_rnn(
cell,
Nmt._build_cell(self.opts.num_units, self.opts.num_layers),
encoder_emb_inp,
dtype=dtype,
time_major=time_major,
swap_memory=False)
encoder_outputs = tf.add_n(outputs)
encoder_state = states[0] + states[1]
else:
encoder_outputs, encoder_state = tf.nn.dynamic_rnn(
cell,
encoder_emb_inp,
dtype=dtype,
time_major=time_major,
swap_memory=False)
return source, encoder_outputs, encoder_state
def _build_attention(self, encoder_outputs, decoder_cell):
with tf.variable_scope("attention", dtype=DTYPE, use_resource=True) as scope:
# Attention is batch major
inputs = tf.transpose(encoder_outputs, [1, 0, 2])
if self.opts.attention == "luong":
attention_mechanism = tf.contrib.seq2seq.LuongAttention(
self.opts.num_units,
inputs,
dtype=scope.dtype,
)
else:
attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(
self.opts.num_units,
inputs,
dtype=scope.dtype,
)
return AttentionWrapperNoAssert(
decoder_cell, attention_mechanism)
def _build_decoder(self, encoder_outputs, encoder_state, embedding, train=False):
with tf.variable_scope("decoder", dtype=DTYPE, use_resource=True) as decoder_scope:
dtype = decoder_scope.dtype
tgt_length = self.src_length * 2
decoder_num_units = self.opts.num_units
atten_num_units = self.opts.num_units
# RNN Cell
cell = Nmt._build_cell(decoder_num_units, self.opts.num_layers)
initial_state = encoder_state
# Attention wrapper
if self.opts.attention:
cell = self._build_attention(encoder_outputs, cell)
initial_state = tf.contrib.seq2seq.AttentionWrapperState(
cell_state=encoder_state,
attention=tf.zeros([self.opts.batch_size, atten_num_units], dtype),
time=tf.constant(0, tf.int32),
alignments=tf.zeros([self.opts.batch_size, self.src_length], dtype),
alignment_history=(),
attention_state=tf.zeros([self.opts.batch_size, self.src_length], dtype)
)
# Projection Layer
projection_layer = tf.layers.Dense(units=self.tgt_vocab_size, use_bias=False, name="projection")
if train:
tgt_length = self.tgt_length
target = self.placeholders['target']
decoder_emb_inp = tf.nn.embedding_lookup(
embedding, target)
helper = TrainingHelperNoCond(
decoder_emb_inp, np.full([self.opts.batch_size], tgt_length, dtype=np.int32), time_major=time_major)
else:
# Inference
tgt_sos_id = self.start_id
tgt_eos_id = self.end_id
start_tokens = np.full([self.opts.batch_size], tgt_sos_id, dtype=np.int32)
end_token = tgt_eos_id
helper = GreedyEmbeddingHelperNoCond(
embedding, start_tokens, end_token)
decoder = tf.contrib.seq2seq.BasicDecoder(
cell,
helper,
initial_state=initial_state,
output_layer=projection_layer if not train else None # applied per timestep
)
# Dynamic decoding
outputs, final_context_state, _ = dynamic_decode( # Contains the XLA check
decoder,
maximum_iterations=tgt_length, # Required for static TensorArrays
output_time_major=time_major,
swap_memory=False,
scope=decoder_scope)
if train:
# Specify dynamic shapes to avoid Assert
logits = outputs.rnn_output
logits.set_shape([tgt_length, self.opts.batch_size, atten_num_units])
logits = projection_layer(logits)
return outputs.sample_id, logits
else:
return outputs.sample_id, outputs.rnn_output
def _build_optimiser(self, logits):
with tf.variable_scope("loss", use_resource=True):
labels = self.placeholders['label']
mask = self.placeholders['mask']
# Logits is dynamic so an Assert is added to check shapes
crossent = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=labels, logits=logits)
train_loss = (tf.reduce_sum(crossent*mask) / self.opts.batch_size)
# Calculate and clip gradients
params = tf.trainable_variables()
gradients = tf.gradients(train_loss, params)
clipped_gradients = [tf.clip_by_norm(grad, max_gradient_norm) for grad in gradients]
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
update_step = optimizer.apply_gradients(
zip(clipped_gradients, params))
return train_loss, update_step
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='NMT model in TensorFlow to run on the IPU')
parser.add_argument('--infer', action="store_true",
help="Inference Only")
parser.add_argument('--bi', action="store_true",
help="Use bidirectional layer in encoder (with outputs summed)")
parser.add_argument('--attention', choices=['luong', 'bahdanau'], default='luong',
help="Add an attention model")
parser.add_argument('--batch-size', type=int, default=1,
help="Set batch-size")
parser.add_argument('--num-units', type=int, default=512,
help="Number of units in each LSTM cell")
parser.add_argument('--num-layers', type=int, default=1,
help="Size of LSTM stack in the encoder and decoder")
parser.add_argument('--embedding-size', type=int, default=32,
help="Size of source and target embedding")
parser.add_argument('--sequence-length', type=int, default=20,
help="Size of input length (by padding or truncating)")
parser.add_argument('--ckpt', action="store_true",
help="load weights from latest checkpoint")
parser.add_argument('--seed', type=int, default=1984,
help="Random seed")
parser.add_argument('--interact', action="store_true",
help="Perform inference on values entered from the command line")
parser.add_argument('--save-graph', action="store_true",
help="Save the graph to './logs' to be viewed by TensorBoard")
parser.add_argument('--steps', type=int, default=50000,
help="Number of steps to complete in training")
args = parser.parse_args()
random.seed(args.seed)
if args.interact:
args.batch_size = 1
args.infer = True
print("NMT {}.\n Batch size: {}. Hidden units: {}. Layers: {}.".format(
"Inference" if args.infer else "Training", args.batch_size, args.num_units, args.num_layers))
n = Nmt(args)
if args.infer:
n.infer()
else:
n.train()
|
[
"tensorflow.contrib.seq2seq.BahdanauAttention",
"util.get_config",
"tensorflow.reduce_sum",
"tensorflow.contrib.seq2seq.LuongAttention",
"argparse.ArgumentParser",
"tensorflow.trainable_variables",
"seq2seq_edits.GreedyEmbeddingHelperNoCond",
"random.sample",
"time.strftime",
"tensorflow.logging.set_verbosity",
"tensorflow.contrib.seq2seq.BasicDecoder",
"tensorflow.get_default_graph",
"data_gen.reader.Data",
"tensorflow.layers.Dense",
"numpy.full",
"tensorflow.add_n",
"tensorflow.variable_scope",
"tensorflow.python.ipu.ipu_compiler.compile",
"tensorflow.placeholder",
"seq2seq_edits.AttentionWrapperNoAssert",
"random.seed",
"tensorflow.gradients",
"tensorflow.clip_by_norm",
"tensorflow.contrib.rnn.MultiRNNCell",
"seq2seq_edits.dynamic_decode",
"tensorflow.python.ipu.utils.configure_ipu_system",
"tensorflow.initializers.random_uniform",
"tensorflow.train.Saver",
"tensorflow.nn.embedding_lookup",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.constant",
"tensorflow.transpose",
"tensorflow.contrib.rnn.BasicLSTMCell",
"data_gen.reader.Vocabulary",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.python.ipu.scopes.ipu_scope",
"tensorflow.nn.dynamic_rnn",
"numpy.zeros",
"time.time",
"tensorflow.zeros",
"numpy.array",
"tensorflow.python.ipu.utils.move_variable_initialization_to_cpu",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits"
] |
[((566, 608), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.ERROR'], {}), '(tf.logging.ERROR)\n', (590, 608), True, 'import tensorflow as tf\n'), ((14999, 15084), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""NMT model in TensorFlow to run on the IPU"""'}), "(description='NMT model in TensorFlow to run on the IPU'\n )\n", (15022, 15084), False, 'import argparse\n'), ((16813, 16835), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (16824, 16835), False, 'import random\n'), ((2917, 2979), 'data_gen.reader.Vocabulary', 'Vocabulary', (['"""./data/human_vocab.json"""'], {'padding': 'self.src_length'}), "('./data/human_vocab.json', padding=self.src_length)\n", (2927, 2979), False, 'from data_gen.reader import Data, Vocabulary\n'), ((3003, 3067), 'data_gen.reader.Vocabulary', 'Vocabulary', (['"""./data/machine_vocab.json"""'], {'padding': 'self.tgt_length'}), "('./data/machine_vocab.json', padding=self.tgt_length)\n", (3013, 3067), False, 'from data_gen.reader import Data, Vocabulary\n'), ((3366, 3408), 'data_gen.reader.Data', 'Data', (['data_file', 'input_vocab', 'output_vocab'], {}), '(data_file, input_vocab, output_vocab)\n', (3370, 3408), False, 'from data_gen.reader import Data, Vocabulary\n'), ((4936, 4952), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (4950, 4952), True, 'import tensorflow as tf\n'), ((4976, 5003), 'util.get_config', 'util.get_config', ([], {'report_n': '(0)'}), '(report_n=0)\n', (4991, 5003), False, 'import util\n'), ((5012, 5051), 'tensorflow.python.ipu.utils.configure_ipu_system', 'utils.configure_ipu_system', (['ipu_options'], {}), '(ipu_options)\n', (5038, 5051), False, 'from tensorflow.python.ipu import utils\n'), ((5070, 5082), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (5080, 5082), True, 'import tensorflow as tf\n'), ((6377, 6393), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (6391, 6393), True, 'import tensorflow as tf\n'), ((6654, 6681), 'util.get_config', 'util.get_config', ([], {'report_n': '(0)'}), '(report_n=0)\n', (6669, 6681), False, 'import util\n'), ((6690, 6729), 'tensorflow.python.ipu.utils.configure_ipu_system', 'utils.configure_ipu_system', (['ipu_options'], {}), '(ipu_options)\n', (6716, 6729), False, 'from tensorflow.python.ipu import utils\n'), ((6748, 6760), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (6758, 6760), True, 'import tensorflow as tf\n'), ((8908, 8946), 'tensorflow.contrib.rnn.MultiRNNCell', 'tf.contrib.rnn.MultiRNNCell', (['cell_list'], {}), '(cell_list)\n', (8935, 8946), True, 'import tensorflow as tf\n'), ((14582, 14606), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (14604, 14606), True, 'import tensorflow as tf\n'), ((14627, 14659), 'tensorflow.gradients', 'tf.gradients', (['train_loss', 'params'], {}), '(train_loss, params)\n', (14639, 14659), True, 'import tensorflow as tf\n'), ((14775, 14823), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['learning_rate'], {}), '(learning_rate)\n', (14808, 14823), True, 'import tensorflow as tf\n'), ((1587, 1635), 'random.sample', 'random.sample', (['instance_id', 'self.opts.batch_size'], {}), '(instance_id, self.opts.batch_size)\n', (1600, 1635), False, 'import random\n'), ((1654, 1702), 'numpy.array', 'np.array', (['data.inputs[batch_ids]'], {'dtype': 'np.int32'}), '(data.inputs[batch_ids], dtype=np.int32)\n', (1662, 1702), True, 'import numpy as np\n'), ((1804, 1852), 'random.sample', 'random.sample', (['instance_id', 'self.opts.batch_size'], {}), '(instance_id, self.opts.batch_size)\n', (1817, 1852), False, 'import random\n'), ((1871, 1919), 'numpy.array', 'np.array', (['data.inputs[batch_ids]'], {'dtype': 'np.int32'}), '(data.inputs[batch_ids], dtype=np.int32)\n', (1879, 1919), True, 'import numpy as np\n'), ((3507, 3597), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[self.src_length, self.opts.batch_size]', 'name': '"""source"""'}), "(tf.int32, shape=[self.src_length, self.opts.batch_size],\n name='source')\n", (3521, 3597), True, 'import tensorflow as tf\n'), ((3617, 3707), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[self.tgt_length, self.opts.batch_size]', 'name': '"""target"""'}), "(tf.int32, shape=[self.tgt_length, self.opts.batch_size],\n name='target')\n", (3631, 3707), True, 'import tensorflow as tf\n'), ((3726, 3815), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[self.tgt_length, self.opts.batch_size]', 'name': '"""label"""'}), "(tf.int32, shape=[self.tgt_length, self.opts.batch_size],\n name='label')\n", (3740, 3815), True, 'import tensorflow as tf\n'), ((4750, 4776), 'tensorflow.python.ipu.scopes.ipu_scope', 'ipu_scope', (['"""/device:IPU:0"""'], {}), "('/device:IPU:0')\n", (4759, 4776), False, 'from tensorflow.python.ipu.scopes import ipu_scope\n'), ((4845, 4882), 'tensorflow.python.ipu.ipu_compiler.compile', 'ipu_compiler.compile', (['build_infer', '[]'], {}), '(build_infer, [])\n', (4865, 4882), False, 'from tensorflow.python.ipu import ipu_compiler\n'), ((6195, 6221), 'tensorflow.python.ipu.scopes.ipu_scope', 'ipu_scope', (['"""/device:IPU:0"""'], {}), "('/device:IPU:0')\n", (6204, 6221), False, 'from tensorflow.python.ipu.scopes import ipu_scope\n'), ((6286, 6323), 'tensorflow.python.ipu.ipu_compiler.compile', 'ipu_compiler.compile', (['build_train', '[]'], {}), '(build_train, [])\n', (6306, 6323), False, 'from tensorflow.python.ipu import ipu_compiler\n'), ((6907, 6950), 'tensorflow.python.ipu.utils.move_variable_initialization_to_cpu', 'utils.move_variable_initialization_to_cpu', ([], {}), '()\n', (6948, 6950), False, 'from tensorflow.python.ipu import utils\n'), ((7241, 7252), 'time.time', 'time.time', ([], {}), '()\n', (7250, 7252), False, 'import time\n'), ((8146, 8208), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""embedding"""'], {'dtype': 'DTYPE', 'use_resource': '(True)'}), "('embedding', dtype=DTYPE, use_resource=True)\n", (8163, 8208), True, 'import tensorflow as tf\n'), ((8599, 8689), 'tensorflow.contrib.rnn.BasicLSTMCell', 'tf.contrib.rnn.BasicLSTMCell', (['num_units'], {'forget_bias': 'forget_bias', 'state_is_tuple': '(False)'}), '(num_units, forget_bias=forget_bias,\n state_is_tuple=False)\n', (8627, 8689), True, 'import tensorflow as tf\n'), ((9002, 9060), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""input"""'], {'dtype': 'DTYPE', 'use_resource': '(True)'}), "('input', dtype=DTYPE, use_resource=True)\n", (9019, 9060), True, 'import tensorflow as tf\n'), ((9150, 9191), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embedding', 'source'], {}), '(embedding, source)\n', (9172, 9191), True, 'import tensorflow as tf\n'), ((9223, 9283), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""encoder"""'], {'dtype': 'DTYPE', 'use_resource': '(True)'}), "('encoder', dtype=DTYPE, use_resource=True)\n", (9240, 9283), True, 'import tensorflow as tf\n'), ((10277, 10339), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""attention"""'], {'dtype': 'DTYPE', 'use_resource': '(True)'}), "('attention', dtype=DTYPE, use_resource=True)\n", (10294, 10339), True, 'import tensorflow as tf\n'), ((10410, 10450), 'tensorflow.transpose', 'tf.transpose', (['encoder_outputs', '[1, 0, 2]'], {}), '(encoder_outputs, [1, 0, 2])\n', (10422, 10450), True, 'import tensorflow as tf\n'), ((10946, 11005), 'seq2seq_edits.AttentionWrapperNoAssert', 'AttentionWrapperNoAssert', (['decoder_cell', 'attention_mechanism'], {}), '(decoder_cell, attention_mechanism)\n', (10970, 11005), False, 'from seq2seq_edits import AttentionWrapperNoAssert, dynamic_decode, TrainingHelperNoCond, GreedyEmbeddingHelperNoCond\n'), ((11123, 11183), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""decoder"""'], {'dtype': 'DTYPE', 'use_resource': '(True)'}), "('decoder', dtype=DTYPE, use_resource=True)\n", (11140, 11183), True, 'import tensorflow as tf\n'), ((12236, 12313), 'tensorflow.layers.Dense', 'tf.layers.Dense', ([], {'units': 'self.tgt_vocab_size', 'use_bias': '(False)', 'name': '"""projection"""'}), "(units=self.tgt_vocab_size, use_bias=False, name='projection')\n", (12251, 12313), True, 'import tensorflow as tf\n'), ((13096, 13228), 'tensorflow.contrib.seq2seq.BasicDecoder', 'tf.contrib.seq2seq.BasicDecoder', (['cell', 'helper'], {'initial_state': 'initial_state', 'output_layer': '(projection_layer if not train else None)'}), '(cell, helper, initial_state=initial_state,\n output_layer=projection_layer if not train else None)\n', (13127, 13228), True, 'import tensorflow as tf\n'), ((13409, 13538), 'seq2seq_edits.dynamic_decode', 'dynamic_decode', (['decoder'], {'maximum_iterations': 'tgt_length', 'output_time_major': 'time_major', 'swap_memory': '(False)', 'scope': 'decoder_scope'}), '(decoder, maximum_iterations=tgt_length, output_time_major=\n time_major, swap_memory=False, scope=decoder_scope)\n', (13423, 13538), False, 'from seq2seq_edits import AttentionWrapperNoAssert, dynamic_decode, TrainingHelperNoCond, GreedyEmbeddingHelperNoCond\n'), ((14119, 14163), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""loss"""'], {'use_resource': '(True)'}), "('loss', use_resource=True)\n", (14136, 14163), True, 'import tensorflow as tf\n'), ((14352, 14428), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'labels', 'logits': 'logits'}), '(labels=labels, logits=logits)\n', (14398, 14428), True, 'import tensorflow as tf\n'), ((14690, 14730), 'tensorflow.clip_by_norm', 'tf.clip_by_norm', (['grad', 'max_gradient_norm'], {}), '(grad, max_gradient_norm)\n', (14705, 14730), True, 'import tensorflow as tf\n'), ((2355, 2404), 'numpy.array', 'np.array', (['data.targets[batch_ids]'], {'dtype': 'np.int32'}), '(data.targets[batch_ids], dtype=np.int32)\n', (2363, 2404), True, 'import numpy as np\n'), ((2428, 2447), 'numpy.zeros', 'np.zeros', (['lbl.shape'], {}), '(lbl.shape)\n', (2436, 2447), True, 'import numpy as np\n'), ((3878, 3957), 'tensorflow.constant', 'tf.constant', (['(1)'], {'shape': '[self.tgt_length, self.opts.batch_size]', 'dtype': 'tf.float16'}), '(1, shape=[self.tgt_length, self.opts.batch_size], dtype=tf.float16)\n', (3889, 3957), True, 'import tensorflow as tf\n'), ((6607, 6629), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (6627, 6629), True, 'import tensorflow as tf\n'), ((6975, 7008), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (7006, 7008), True, 'import tensorflow as tf\n'), ((7340, 7351), 'time.time', 'time.time', ([], {}), '()\n', (7349, 7351), False, 'import time\n'), ((8774, 8864), 'tensorflow.contrib.rnn.BasicLSTMCell', 'tf.contrib.rnn.BasicLSTMCell', (['num_units'], {'forget_bias': 'forget_bias', 'state_is_tuple': '(False)'}), '(num_units, forget_bias=forget_bias,\n state_is_tuple=False)\n', (8802, 8864), True, 'import tensorflow as tf\n'), ((9809, 9826), 'tensorflow.add_n', 'tf.add_n', (['outputs'], {}), '(outputs)\n', (9817, 9826), True, 'import tensorflow as tf\n'), ((9948, 10047), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['cell', 'encoder_emb_inp'], {'dtype': 'dtype', 'time_major': 'time_major', 'swap_memory': '(False)'}), '(cell, encoder_emb_inp, dtype=dtype, time_major=time_major,\n swap_memory=False)\n', (9965, 10047), True, 'import tensorflow as tf\n'), ((10537, 10623), 'tensorflow.contrib.seq2seq.LuongAttention', 'tf.contrib.seq2seq.LuongAttention', (['self.opts.num_units', 'inputs'], {'dtype': 'scope.dtype'}), '(self.opts.num_units, inputs, dtype=scope.\n dtype)\n', (10570, 10623), True, 'import tensorflow as tf\n'), ((10758, 10847), 'tensorflow.contrib.seq2seq.BahdanauAttention', 'tf.contrib.seq2seq.BahdanauAttention', (['self.opts.num_units', 'inputs'], {'dtype': 'scope.dtype'}), '(self.opts.num_units, inputs, dtype=\n scope.dtype)\n', (10794, 10847), True, 'import tensorflow as tf\n'), ((12469, 12510), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embedding', 'target'], {}), '(embedding, target)\n', (12491, 12510), True, 'import tensorflow as tf\n'), ((12863, 12922), 'numpy.full', 'np.full', (['[self.opts.batch_size]', 'tgt_sos_id'], {'dtype': 'np.int32'}), '([self.opts.batch_size], tgt_sos_id, dtype=np.int32)\n', (12870, 12922), True, 'import numpy as np\n'), ((12988, 13051), 'seq2seq_edits.GreedyEmbeddingHelperNoCond', 'GreedyEmbeddingHelperNoCond', (['embedding', 'start_tokens', 'end_token'], {}), '(embedding, start_tokens, end_token)\n', (13015, 13051), False, 'from seq2seq_edits import AttentionWrapperNoAssert, dynamic_decode, TrainingHelperNoCond, GreedyEmbeddingHelperNoCond\n'), ((14472, 14502), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(crossent * mask)'], {}), '(crossent * mask)\n', (14485, 14502), True, 'import tensorflow as tf\n'), ((2237, 2286), 'numpy.array', 'np.array', (['data.targets[batch_ids]'], {'dtype': 'np.int32'}), '(data.targets[batch_ids], dtype=np.int32)\n', (2245, 2286), True, 'import numpy as np\n'), ((6542, 6575), 'time.strftime', 'time.strftime', (['"""%Y%m%d_%H%M%S_%Z"""'], {}), "('%Y%m%d_%H%M%S_%Z')\n", (6555, 6575), False, 'import time\n'), ((8384, 8445), 'tensorflow.initializers.random_uniform', 'tf.initializers.random_uniform', ([], {'maxval': '(1.0)', 'dtype': 'scope.dtype'}), '(maxval=1.0, dtype=scope.dtype)\n', (8414, 8445), True, 'import tensorflow as tf\n'), ((12617, 12676), 'numpy.full', 'np.full', (['[self.opts.batch_size]', 'tgt_length'], {'dtype': 'np.int32'}), '([self.opts.batch_size], tgt_length, dtype=np.int32)\n', (12624, 12676), True, 'import numpy as np\n'), ((11818, 11874), 'tensorflow.zeros', 'tf.zeros', (['[self.opts.batch_size, atten_num_units]', 'dtype'], {}), '([self.opts.batch_size, atten_num_units], dtype)\n', (11826, 11874), True, 'import tensorflow as tf\n'), ((11901, 11925), 'tensorflow.constant', 'tf.constant', (['(0)', 'tf.int32'], {}), '(0, tf.int32)\n', (11912, 11925), True, 'import tensorflow as tf\n'), ((11958, 12014), 'tensorflow.zeros', 'tf.zeros', (['[self.opts.batch_size, self.src_length]', 'dtype'], {}), '([self.opts.batch_size, self.src_length], dtype)\n', (11966, 12014), True, 'import tensorflow as tf\n'), ((12094, 12150), 'tensorflow.zeros', 'tf.zeros', (['[self.opts.batch_size, self.src_length]', 'dtype'], {}), '([self.opts.batch_size, self.src_length], dtype)\n', (12102, 12150), True, 'import tensorflow as tf\n')]
|
import cv2
import numpy as np
from random import randint
from functools import reduce
from os import walk
from scipy.spatial import ConvexHull
DIMENSIONS = (512, 512)
def fragment_overlay(background_img, masked_fragment):
mask = masked_fragment.astype(int).sum(-1) == np.zeros(DIMENSIONS)
background_img = np.where(mask[..., None], background_img, masked_fragment)
return background_img
def transparent_superimposition(background_img, masked_fragment):
mask = masked_fragment.astype(int).sum(-1) == np.zeros(DIMENSIONS)
background_img = np.where(mask[..., None], background_img, cv2.addWeighted(background_img, 0.5, masked_fragment, 0.5, 0))
return background_img
def polygon_area(vertices):
x, y = vertices[:, 0], vertices[:, 1]
correction = x[-1] * y[0] - y[-1] * x[0]
main_area = np.dot(x[:-1], y[1:]) - np.dot(y[:-1], x[1:])
return 0.5 * np.abs(main_area + correction)
def lab_adjust(image, delta_light=0, clip_limit=1.0):
lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(lab)
clahe = cv2.createCLAHE(clipLimit=clip_limit)
cl = clahe.apply(l)
cl = cv2.add(cl, delta_light)
limg = cv2.merge((cl, a, b))
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
return final
def rotate(image, angle=0, scale=1.0):
center = tuple(ti//2 for ti in DIMENSIONS)
M = cv2.getRotationMatrix2D(center, angle, scale)
rotated = cv2.warpAffine(image, M, DIMENSIONS)
return rotated
def darken(image, delta_light=-25):
return lab_adjust(image, delta_light=delta_light)
def lighten(image, delta_light=25):
return lab_adjust(image, delta_light=delta_light)
def increase_contrast(image, clip_limit=2.5):
return lab_adjust(image, clip_limit=clip_limit)
def blur(image):
blurred = cv2.GaussianBlur(image, (3, 3), 0)
return blurred
def do_nothing(image):
return image
def random_image_adjustment():
# change contrast, brightness, rotate?, blur? - functions with respective probabilities of being chosen
chosen_transformations = []
for list_of_functions in all_transformations:
chosen_transformations.append(np.random.choice(list_of_functions, p=[0.6, 0.2, 0.2]))
return compose_functions(*chosen_transformations)
def compose_functions(*func):
def compose(f, g):
return lambda x: f(g(x))
return reduce(compose, func, lambda x: x)
def load(path='images'):
_, _, filenames = next(walk(path))
return np.array(list(map(lambda x: cv2.resize(cv2.imread(path + '/' + x), DIMENSIONS), filenames)), dtype='uint8')
def save(image, identifier=123):
cv2.imwrite(f"results/{identifier}_{randint(0, 1000)}.jpg", image)
def random_point(shift=[255, 255], deviation=256):
x, y = randint(shift[0] - deviation, shift[0] + deviation), randint(shift[1] - deviation, shift[1] + deviation)
return np.array([x, y])
def random_mask():
mask = np.zeros(DIMENSIONS, dtype='uint8')
cv2.fillPoly(mask, pts=[random_polygon(9)], color=255)
return mask
def random_polygon(n):
points = np.random.randint(0, 511, size=(n, 2))
hull = ConvexHull(points)
return points[hull.vertices]
all_transformations = [[do_nothing, do_nothing, increase_contrast],
[do_nothing, darken, lighten],
[do_nothing, do_nothing, blur]]
|
[
"cv2.GaussianBlur",
"numpy.abs",
"os.walk",
"cv2.warpAffine",
"numpy.random.randint",
"cv2.getRotationMatrix2D",
"random.randint",
"cv2.cvtColor",
"cv2.split",
"numpy.random.choice",
"cv2.addWeighted",
"cv2.createCLAHE",
"numpy.dot",
"cv2.merge",
"scipy.spatial.ConvexHull",
"cv2.add",
"numpy.zeros",
"cv2.imread",
"numpy.where",
"numpy.array",
"functools.reduce"
] |
[((329, 387), 'numpy.where', 'np.where', (['mask[..., None]', 'background_img', 'masked_fragment'], {}), '(mask[..., None], background_img, masked_fragment)\n', (337, 387), True, 'import numpy as np\n'), ((1016, 1054), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2LAB'], {}), '(image, cv2.COLOR_BGR2LAB)\n', (1028, 1054), False, 'import cv2\n'), ((1070, 1084), 'cv2.split', 'cv2.split', (['lab'], {}), '(lab)\n', (1079, 1084), False, 'import cv2\n'), ((1098, 1135), 'cv2.createCLAHE', 'cv2.createCLAHE', ([], {'clipLimit': 'clip_limit'}), '(clipLimit=clip_limit)\n', (1113, 1135), False, 'import cv2\n'), ((1171, 1195), 'cv2.add', 'cv2.add', (['cl', 'delta_light'], {}), '(cl, delta_light)\n', (1178, 1195), False, 'import cv2\n'), ((1208, 1229), 'cv2.merge', 'cv2.merge', (['(cl, a, b)'], {}), '((cl, a, b))\n', (1217, 1229), False, 'import cv2\n'), ((1243, 1280), 'cv2.cvtColor', 'cv2.cvtColor', (['limg', 'cv2.COLOR_LAB2BGR'], {}), '(limg, cv2.COLOR_LAB2BGR)\n', (1255, 1280), False, 'import cv2\n'), ((1400, 1445), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['center', 'angle', 'scale'], {}), '(center, angle, scale)\n', (1423, 1445), False, 'import cv2\n'), ((1461, 1497), 'cv2.warpAffine', 'cv2.warpAffine', (['image', 'M', 'DIMENSIONS'], {}), '(image, M, DIMENSIONS)\n', (1475, 1497), False, 'import cv2\n'), ((1851, 1885), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['image', '(3, 3)', '(0)'], {}), '(image, (3, 3), 0)\n', (1867, 1885), False, 'import cv2\n'), ((2440, 2474), 'functools.reduce', 'reduce', (['compose', 'func', '(lambda x: x)'], {}), '(compose, func, lambda x: x)\n', (2446, 2474), False, 'from functools import reduce\n'), ((2960, 2976), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (2968, 2976), True, 'import numpy as np\n'), ((3013, 3048), 'numpy.zeros', 'np.zeros', (['DIMENSIONS'], {'dtype': '"""uint8"""'}), "(DIMENSIONS, dtype='uint8')\n", (3021, 3048), True, 'import numpy as np\n'), ((3168, 3206), 'numpy.random.randint', 'np.random.randint', (['(0)', '(511)'], {'size': '(n, 2)'}), '(0, 511, size=(n, 2))\n', (3185, 3206), True, 'import numpy as np\n'), ((3219, 3237), 'scipy.spatial.ConvexHull', 'ConvexHull', (['points'], {}), '(points)\n', (3229, 3237), False, 'from scipy.spatial import ConvexHull\n'), ((286, 306), 'numpy.zeros', 'np.zeros', (['DIMENSIONS'], {}), '(DIMENSIONS)\n', (294, 306), True, 'import numpy as np\n'), ((537, 557), 'numpy.zeros', 'np.zeros', (['DIMENSIONS'], {}), '(DIMENSIONS)\n', (545, 557), True, 'import numpy as np\n'), ((622, 683), 'cv2.addWeighted', 'cv2.addWeighted', (['background_img', '(0.5)', 'masked_fragment', '(0.5)', '(0)'], {}), '(background_img, 0.5, masked_fragment, 0.5, 0)\n', (637, 683), False, 'import cv2\n'), ((851, 872), 'numpy.dot', 'np.dot', (['x[:-1]', 'y[1:]'], {}), '(x[:-1], y[1:])\n', (857, 872), True, 'import numpy as np\n'), ((875, 896), 'numpy.dot', 'np.dot', (['y[:-1]', 'x[1:]'], {}), '(y[:-1], x[1:])\n', (881, 896), True, 'import numpy as np\n'), ((915, 945), 'numpy.abs', 'np.abs', (['(main_area + correction)'], {}), '(main_area + correction)\n', (921, 945), True, 'import numpy as np\n'), ((2533, 2543), 'os.walk', 'walk', (['path'], {}), '(path)\n', (2537, 2543), False, 'from os import walk\n'), ((2843, 2894), 'random.randint', 'randint', (['(shift[0] - deviation)', '(shift[0] + deviation)'], {}), '(shift[0] - deviation, shift[0] + deviation)\n', (2850, 2894), False, 'from random import randint\n'), ((2896, 2947), 'random.randint', 'randint', (['(shift[1] - deviation)', '(shift[1] + deviation)'], {}), '(shift[1] - deviation, shift[1] + deviation)\n', (2903, 2947), False, 'from random import randint\n'), ((2220, 2274), 'numpy.random.choice', 'np.random.choice', (['list_of_functions'], {'p': '[0.6, 0.2, 0.2]'}), '(list_of_functions, p=[0.6, 0.2, 0.2])\n', (2236, 2274), True, 'import numpy as np\n'), ((2744, 2760), 'random.randint', 'randint', (['(0)', '(1000)'], {}), '(0, 1000)\n', (2751, 2760), False, 'from random import randint\n'), ((2596, 2622), 'cv2.imread', 'cv2.imread', (["(path + '/' + x)"], {}), "(path + '/' + x)\n", (2606, 2622), False, 'import cv2\n')]
|
# View more python tutorials on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
# 12 - contours
"""
Please note, this script is for python3+.
If you are using python2+, please modify it accordingly.
Tutorial reference:
http://www.scipy-lectures.org/intro/matplotlib/matplotlib.html
"""
import matplotlib.pyplot as plt
import numpy as np
def f(x,y):
# the height function
return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X,Y = np.meshgrid(x, y)
# use plt.contourf to filling contours
# X, Y and value for (X,Y) point
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)
# use plt.contour to add contour lines
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
# adding label
plt.clabel(C, inline=True, fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show()
|
[
"matplotlib.pyplot.clabel",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"matplotlib.pyplot.yticks",
"numpy.exp",
"numpy.linspace",
"matplotlib.pyplot.xticks"
] |
[((576, 597), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', 'n'], {}), '(-3, 3, n)\n', (587, 597), True, 'import numpy as np\n'), ((602, 623), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', 'n'], {}), '(-3, 3, n)\n', (613, 623), True, 'import numpy as np\n'), ((630, 647), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (641, 647), True, 'import numpy as np\n'), ((899, 938), 'matplotlib.pyplot.clabel', 'plt.clabel', (['C'], {'inline': '(True)', 'fontsize': '(10)'}), '(C, inline=True, fontsize=10)\n', (909, 938), True, 'import matplotlib.pyplot as plt\n'), ((940, 954), 'matplotlib.pyplot.xticks', 'plt.xticks', (['()'], {}), '(())\n', (950, 954), True, 'import matplotlib.pyplot as plt\n'), ((955, 969), 'matplotlib.pyplot.yticks', 'plt.yticks', (['()'], {}), '(())\n', (965, 969), True, 'import matplotlib.pyplot as plt\n'), ((970, 980), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (978, 980), True, 'import matplotlib.pyplot as plt\n'), ((543, 567), 'numpy.exp', 'np.exp', (['(-x ** 2 - y ** 2)'], {}), '(-x ** 2 - y ** 2)\n', (549, 567), True, 'import numpy as np\n')]
|
import kfp
import kfp.dsl as dsl
from kfp.components import create_component_from_func
import kfp.components as comp
IMAGE = 'salazar99/python-kubeflow:latest'
DATA_URL = 'https://gs-kubeflow-pipelines.nyc3.digitaloceanspaces.com/clean-spam-data.csv'
# Download data
# def download_data(source_path: str, output_csv: comp.OutputPath('CSV')):
# import pandas as pd
# data = pd.read_csv(source_path)
# print(output_csv)
# data.to_csv(output_csv, index=False)
# download_op = create_component_from_func(func=download_data,
# base_image=IMAGE)
web_downloader_op = kfp.components.load_component_from_url(
'https://raw.githubusercontent.com/kubeflow/pipelines/master/components/web/Download/component.yaml')
# Preprocess and store data
def preprocess_data(source_path: comp.InputPath('CSV'),
x_train_output_path: str,
x_test_output_path: str,
y_train_output_path: str,
y_test_output_path: str):
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif
from sklearn.model_selection import train_test_split
from typing import List
import pandas as pd
import numpy as np
# Load and split data
data = pd.read_csv(source_path + '.csv')
x_train, x_test, y_train, y_test = train_test_split(data['text'], data['label'], test_size=0.2)
# Convert to required format
x_train = list(x_train)
y_train = y_train.to_numpy()
x_test = list(x_test)
y_test = y_test.to_numpy()
# Function for preprocessing data
def ngram_vectorize(train_text: List[str], train_labels: np.ndarray, test_text: List[str]):
# Arguments for vectorizor
kwargs = {
'ngram_range': NGRAM_RANGE, # Use 1-grams + 2-grams.
'dtype': 'int32',
'strip_accents': 'unicode',
'decode_error': 'replace',
'analyzer': TOKEN_MODE, # Split text into word tokens.
'min_df': MIN_DOCUMENT_FREQUENCY,
}
vectorizer = TfidfVectorizer(**kwargs)
# Vectorize training text
x_train = vectorizer.fit_transform(train_text)
# Vectorize test text
x_test = vectorizer.transform(test_text)
# Select top k features
selector = SelectKBest(f_classif, k=TOP_K)
selector.fit(x_train, train_labels)
x_train = selector.transform(x_train).astype('float32')
x_test = selector.transform(x_test).astype('float32')
return x_train, x_test
# Preprocess data
x_train, x_test = ngram_vectorize(x_train, y_train, x_test)
# Save data
np.save(x_train, x_train_output_path)
np.save(x_test, x_test_output_path)
np.save(y_train, y_train_output_path)
np.save(y_test, y_test_output_path)
preprocess_op = create_component_from_func(func=preprocess_data,
base_image=IMAGE)
# Train model
# Evaluate model
# Save model
# Build pipeline
@dsl.pipeline(
name="SMS Spam Detection Model Pipeline",
description="Train an MLP to detect spam messages from csv data"
)
def pipeline(url=DATA_URL):
download = web_downloader_op(url=url)
preprocess = preprocess_op(download.outputs['data'],
'x_train.npy',
'x_test.npy',
'y_train.npy',
'y_test.npy').after(download)
if __name__ == '__main__':
kfp.compiler.Compiler().compile(
pipeline_func=pipeline,
package_path='pipeline.yaml'
)
|
[
"numpy.save",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.feature_extraction.text.TfidfVectorizer",
"kfp.components.create_component_from_func",
"kfp.compiler.Compiler",
"kfp.components.InputPath",
"kfp.components.load_component_from_url",
"sklearn.feature_selection.SelectKBest",
"kfp.dsl.pipeline"
] |
[((621, 771), 'kfp.components.load_component_from_url', 'kfp.components.load_component_from_url', (['"""https://raw.githubusercontent.com/kubeflow/pipelines/master/components/web/Download/component.yaml"""'], {}), "(\n 'https://raw.githubusercontent.com/kubeflow/pipelines/master/components/web/Download/component.yaml'\n )\n", (659, 771), False, 'import kfp\n'), ((2955, 3021), 'kfp.components.create_component_from_func', 'create_component_from_func', ([], {'func': 'preprocess_data', 'base_image': 'IMAGE'}), '(func=preprocess_data, base_image=IMAGE)\n', (2981, 3021), False, 'from kfp.components import create_component_from_func\n'), ((3129, 3254), 'kfp.dsl.pipeline', 'dsl.pipeline', ([], {'name': '"""SMS Spam Detection Model Pipeline"""', 'description': '"""Train an MLP to detect spam messages from csv data"""'}), "(name='SMS Spam Detection Model Pipeline', description=\n 'Train an MLP to detect spam messages from csv data')\n", (3141, 3254), True, 'import kfp.dsl as dsl\n'), ((1377, 1410), 'pandas.read_csv', 'pd.read_csv', (["(source_path + '.csv')"], {}), "(source_path + '.csv')\n", (1388, 1410), True, 'import pandas as pd\n'), ((1450, 1510), 'sklearn.model_selection.train_test_split', 'train_test_split', (["data['text']", "data['label']"], {'test_size': '(0.2)'}), "(data['text'], data['label'], test_size=0.2)\n", (1466, 1510), False, 'from sklearn.model_selection import train_test_split\n'), ((2778, 2815), 'numpy.save', 'np.save', (['x_train', 'x_train_output_path'], {}), '(x_train, x_train_output_path)\n', (2785, 2815), True, 'import numpy as np\n'), ((2820, 2855), 'numpy.save', 'np.save', (['x_test', 'x_test_output_path'], {}), '(x_test, x_test_output_path)\n', (2827, 2855), True, 'import numpy as np\n'), ((2860, 2897), 'numpy.save', 'np.save', (['y_train', 'y_train_output_path'], {}), '(y_train, y_train_output_path)\n', (2867, 2897), True, 'import numpy as np\n'), ((2902, 2937), 'numpy.save', 'np.save', (['y_test', 'y_test_output_path'], {}), '(y_test, y_test_output_path)\n', (2909, 2937), True, 'import numpy as np\n'), ((829, 850), 'kfp.components.InputPath', 'comp.InputPath', (['"""CSV"""'], {}), "('CSV')\n", (843, 850), True, 'import kfp.components as comp\n'), ((2177, 2202), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {}), '(**kwargs)\n', (2192, 2202), False, 'from sklearn.feature_extraction.text import TfidfVectorizer\n'), ((2432, 2463), 'sklearn.feature_selection.SelectKBest', 'SelectKBest', (['f_classif'], {'k': 'TOP_K'}), '(f_classif, k=TOP_K)\n', (2443, 2463), False, 'from sklearn.feature_selection import SelectKBest\n'), ((3569, 3592), 'kfp.compiler.Compiler', 'kfp.compiler.Compiler', ([], {}), '()\n', (3590, 3592), False, 'import kfp\n')]
|
# ==============================================================================
# Copyright 2019 - <NAME>
#
# NOTICE: 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.
# ==============================================================================
""" RL (NeurIPS 2019) Dataset Builder
- Base class responsible for generating the protocol buffers to be used by the model
"""
import logging
import numpy as np
from diplomacy import Map
from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField
from diplomacy_research.models.policy.base_policy_builder import BasePolicyBuilder
from diplomacy_research.models.state_space import get_order_based_mask, proto_to_board_state, GO_ID, NB_NODES, \
NB_SUPPLY_CENTERS, POWER_VOCABULARY_KEY_TO_IX, MAX_CANDIDATES, NB_FEATURES, NB_ORDERS_FEATURES, NB_PREV_ORDERS, \
get_board_alignments, get_orderable_locs_for_powers, get_current_season, proto_to_prev_orders_state
# Constants
LOGGER = logging.getLogger(__name__)
class BaseDatasetBuilder(BasePolicyBuilder):
""" This object is responsible for maintaining the data and feeding it into the model """
@staticmethod
def get_proto_fields():
""" Returns the proto fields used by this dataset builder """
# Creating proto fields
proto_fields = {
'request_id': FixedProtoField([], None),
'player_seed': FixedProtoField([], np.int32),
'board_state': FixedProtoField([NB_NODES, NB_FEATURES], np.uint8),
'board_alignments': VarProtoField([NB_NODES * NB_SUPPLY_CENTERS], np.uint8),
'prev_orders_state': FixedProtoField([NB_PREV_ORDERS, NB_NODES, NB_ORDERS_FEATURES], np.uint8),
'decoder_inputs': VarProtoField([1 + NB_SUPPLY_CENTERS], np.int32),
'decoder_lengths': FixedProtoField([], np.int32),
'candidates': VarProtoField([None, MAX_CANDIDATES], np.int32),
'noise': FixedProtoField([], np.float32),
'temperature': FixedProtoField([], np.float32),
'dropout_rate': FixedProtoField([], np.float32),
'current_power': FixedProtoField([], np.int32),
'current_season': FixedProtoField([], np.int32),
'value_targets': FixedProtoField([], np.float32),
'context': VarProtoField([256 * 2 * 8], np.float32),
'messages': VarProtoField([1 + 1000], np.int32),
'message_lengths': FixedProtoField([], np.int32),
'senders': VarProtoField([1000], np.uint8),
'recipients': VarProtoField([1000], np.uint8),
'next_conversant': FixedProtoField([2], np.int32)
}
return proto_fields
@staticmethod
def get_feedable_item(locs, state_proto, power_name, phase_history_proto, possible_orders_proto, **kwargs):
""" Computes and return a feedable item (to be fed into the feedable queue)
:param locs: A list of locations for which we want orders
:param state_proto: A `.proto.game.State` representation of the state of the game.
:param power_name: The power name for which we want the orders and the state values
:param phase_history_proto: A list of `.proto.game.PhaseHistory`. This represents prev phases.
:param possible_orders_proto: A `proto.game.PossibleOrders` object representing possible order for each loc.
:param kwargs: Additional optional kwargs:
- player_seed: The seed to apply to the player to compute a deterministic mask.
- noise: The sigma of the additional noise to apply to the intermediate layers (i.e. sigma * epsilon)
- temperature: The temperature to apply to the logits. (Default to 0. for deterministic/greedy)
- dropout_rate: The amount of dropout to apply to the inputs/outputs of the decoder.
:return: A feedable item, with feature names as key and numpy arrays as values
"""
# pylint: disable=too-many-branches
# Converting to state space
map_object = Map(state_proto.map)
board_state = proto_to_board_state(state_proto, map_object)
# Building the decoder length
# For adjustment phase, we restrict the number of builds/disbands to what is allowed by the game engine
in_adjustment_phase = state_proto.name[-1] == 'A'
nb_builds = state_proto.builds[power_name].count
nb_homes = len(state_proto.builds[power_name].homes)
# If we are in adjustment phase, making sure the locs are the orderable locs (and not the policy locs)
if in_adjustment_phase:
orderable_locs, _ = get_orderable_locs_for_powers(state_proto, [power_name])
if sorted(locs) != sorted(orderable_locs):
if locs:
LOGGER.warning('Adj. phase requires orderable locs. Got %s. Expected %s.', locs, orderable_locs)
locs = orderable_locs
# WxxxA - We can build units
# WxxxA - We can disband units
# Other phase
if in_adjustment_phase and nb_builds >= 0:
decoder_length = min(nb_builds, nb_homes)
elif in_adjustment_phase and nb_builds < 0:
decoder_length = abs(nb_builds)
else:
decoder_length = len(locs)
# Computing the candidates for the policy
if possible_orders_proto:
# Adjustment Phase - Use all possible orders for each location.
if in_adjustment_phase:
# Building a list of all orders for all locations
adj_orders = []
for loc in locs:
adj_orders += possible_orders_proto[loc].value
# Computing the candidates
candidates = [get_order_based_mask(adj_orders)] * decoder_length
# Regular phase - Compute candidates for each location
else:
candidates = []
for loc in locs:
candidates += [get_order_based_mask(possible_orders_proto[loc].value)]
# We don't have possible orders, so we cannot compute candidates
# This might be normal if we are only getting the state value or the next message to send
else:
candidates = []
for _ in range(decoder_length):
candidates.append([])
# Prev orders state
prev_orders_state = []
for phase_proto in reversed(phase_history_proto):
if len(prev_orders_state) == NB_PREV_ORDERS:
break
if phase_proto.name[-1] == 'M':
prev_orders_state = [proto_to_prev_orders_state(phase_proto, map_object)] + prev_orders_state
for _ in range(NB_PREV_ORDERS - len(prev_orders_state)):
prev_orders_state = [np.zeros((NB_NODES, NB_ORDERS_FEATURES), dtype=np.uint8)] + prev_orders_state
prev_orders_state = np.array(prev_orders_state)
# Building (order) decoder inputs [GO_ID]
decoder_inputs = [GO_ID]
# kwargs
player_seed = kwargs.get('player_seed', 0)
noise = kwargs.get('noise', 0.)
temperature = kwargs.get('temperature', 0.)
dropout_rate = kwargs.get('dropout_rate', 0.)
# Building feedable data
item = {
'player_seed': player_seed,
'board_state': board_state,
'board_alignments': get_board_alignments(locs,
in_adjustment_phase=in_adjustment_phase,
tokens_per_loc=1,
decoder_length=decoder_length),
'prev_orders_state': prev_orders_state,
'decoder_inputs': decoder_inputs,
'decoder_lengths': decoder_length,
'candidates': candidates,
'noise': noise,
'temperature': temperature,
'dropout_rate': dropout_rate,
'current_power': POWER_VOCABULARY_KEY_TO_IX[power_name],
'current_season': get_current_season(state_proto)
}
# Return
return item
@property
def proto_generation_callable(self):
""" Returns a callable required for proto files generation.
e.g. return generate_proto(saved_game_bytes, is_validation_set)
Note: Callable args are - saved_game_bytes: A `.proto.game.SavedGame` object from the dataset
- phase_ix: The index of the phase we want to process
- is_validation_set: Boolean that indicates if we are generating the validation set
Note: Used bytes_to_proto from diplomacy_research.utils.proto to convert bytes to proto
The callable must return a list of tf.train.Example to put in the protocol buffer file
"""
raise NotImplementedError()
|
[
"diplomacy_research.models.state_space.get_current_season",
"diplomacy_research.models.datasets.base_builder.VarProtoField",
"diplomacy_research.models.state_space.get_orderable_locs_for_powers",
"diplomacy_research.models.state_space.get_order_based_mask",
"numpy.zeros",
"diplomacy_research.models.state_space.get_board_alignments",
"numpy.array",
"diplomacy.Map",
"diplomacy_research.models.datasets.base_builder.FixedProtoField",
"diplomacy_research.models.state_space.proto_to_prev_orders_state",
"diplomacy_research.models.state_space.proto_to_board_state",
"logging.getLogger"
] |
[((1513, 1540), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1530, 1540), False, 'import logging\n'), ((4610, 4630), 'diplomacy.Map', 'Map', (['state_proto.map'], {}), '(state_proto.map)\n', (4613, 4630), False, 'from diplomacy import Map\n'), ((4653, 4698), 'diplomacy_research.models.state_space.proto_to_board_state', 'proto_to_board_state', (['state_proto', 'map_object'], {}), '(state_proto, map_object)\n', (4673, 4698), False, 'from diplomacy_research.models.state_space import get_order_based_mask, proto_to_board_state, GO_ID, NB_NODES, NB_SUPPLY_CENTERS, POWER_VOCABULARY_KEY_TO_IX, MAX_CANDIDATES, NB_FEATURES, NB_ORDERS_FEATURES, NB_PREV_ORDERS, get_board_alignments, get_orderable_locs_for_powers, get_current_season, proto_to_prev_orders_state\n'), ((7462, 7489), 'numpy.array', 'np.array', (['prev_orders_state'], {}), '(prev_orders_state)\n', (7470, 7489), True, 'import numpy as np\n'), ((1881, 1906), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[]', 'None'], {}), '([], None)\n', (1896, 1906), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((1935, 1964), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[]', 'np.int32'], {}), '([], np.int32)\n', (1950, 1964), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((1993, 2043), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[NB_NODES, NB_FEATURES]', 'np.uint8'], {}), '([NB_NODES, NB_FEATURES], np.uint8)\n', (2008, 2043), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2077, 2132), 'diplomacy_research.models.datasets.base_builder.VarProtoField', 'VarProtoField', (['[NB_NODES * NB_SUPPLY_CENTERS]', 'np.uint8'], {}), '([NB_NODES * NB_SUPPLY_CENTERS], np.uint8)\n', (2090, 2132), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2167, 2240), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[NB_PREV_ORDERS, NB_NODES, NB_ORDERS_FEATURES]', 'np.uint8'], {}), '([NB_PREV_ORDERS, NB_NODES, NB_ORDERS_FEATURES], np.uint8)\n', (2182, 2240), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2272, 2320), 'diplomacy_research.models.datasets.base_builder.VarProtoField', 'VarProtoField', (['[1 + NB_SUPPLY_CENTERS]', 'np.int32'], {}), '([1 + NB_SUPPLY_CENTERS], np.int32)\n', (2285, 2320), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2353, 2382), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[]', 'np.int32'], {}), '([], np.int32)\n', (2368, 2382), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2410, 2457), 'diplomacy_research.models.datasets.base_builder.VarProtoField', 'VarProtoField', (['[None, MAX_CANDIDATES]', 'np.int32'], {}), '([None, MAX_CANDIDATES], np.int32)\n', (2423, 2457), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2480, 2511), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[]', 'np.float32'], {}), '([], np.float32)\n', (2495, 2511), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2540, 2571), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[]', 'np.float32'], {}), '([], np.float32)\n', (2555, 2571), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2601, 2632), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[]', 'np.float32'], {}), '([], np.float32)\n', (2616, 2632), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2663, 2692), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[]', 'np.int32'], {}), '([], np.int32)\n', (2678, 2692), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2724, 2753), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[]', 'np.int32'], {}), '([], np.int32)\n', (2739, 2753), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2784, 2815), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[]', 'np.float32'], {}), '([], np.float32)\n', (2799, 2815), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2840, 2880), 'diplomacy_research.models.datasets.base_builder.VarProtoField', 'VarProtoField', (['[256 * 2 * 8]', 'np.float32'], {}), '([256 * 2 * 8], np.float32)\n', (2853, 2880), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2906, 2941), 'diplomacy_research.models.datasets.base_builder.VarProtoField', 'VarProtoField', (['[1 + 1000]', 'np.int32'], {}), '([1 + 1000], np.int32)\n', (2919, 2941), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((2974, 3003), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[]', 'np.int32'], {}), '([], np.int32)\n', (2989, 3003), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((3028, 3059), 'diplomacy_research.models.datasets.base_builder.VarProtoField', 'VarProtoField', (['[1000]', 'np.uint8'], {}), '([1000], np.uint8)\n', (3041, 3059), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((3087, 3118), 'diplomacy_research.models.datasets.base_builder.VarProtoField', 'VarProtoField', (['[1000]', 'np.uint8'], {}), '([1000], np.uint8)\n', (3100, 3118), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((3151, 3181), 'diplomacy_research.models.datasets.base_builder.FixedProtoField', 'FixedProtoField', (['[2]', 'np.int32'], {}), '([2], np.int32)\n', (3166, 3181), False, 'from diplomacy_research.models.datasets.base_builder import FixedProtoField, VarProtoField\n'), ((5202, 5258), 'diplomacy_research.models.state_space.get_orderable_locs_for_powers', 'get_orderable_locs_for_powers', (['state_proto', '[power_name]'], {}), '(state_proto, [power_name])\n', (5231, 5258), False, 'from diplomacy_research.models.state_space import get_order_based_mask, proto_to_board_state, GO_ID, NB_NODES, NB_SUPPLY_CENTERS, POWER_VOCABULARY_KEY_TO_IX, MAX_CANDIDATES, NB_FEATURES, NB_ORDERS_FEATURES, NB_PREV_ORDERS, get_board_alignments, get_orderable_locs_for_powers, get_current_season, proto_to_prev_orders_state\n'), ((7952, 8072), 'diplomacy_research.models.state_space.get_board_alignments', 'get_board_alignments', (['locs'], {'in_adjustment_phase': 'in_adjustment_phase', 'tokens_per_loc': '(1)', 'decoder_length': 'decoder_length'}), '(locs, in_adjustment_phase=in_adjustment_phase,\n tokens_per_loc=1, decoder_length=decoder_length)\n', (7972, 8072), False, 'from diplomacy_research.models.state_space import get_order_based_mask, proto_to_board_state, GO_ID, NB_NODES, NB_SUPPLY_CENTERS, POWER_VOCABULARY_KEY_TO_IX, MAX_CANDIDATES, NB_FEATURES, NB_ORDERS_FEATURES, NB_PREV_ORDERS, get_board_alignments, get_orderable_locs_for_powers, get_current_season, proto_to_prev_orders_state\n'), ((8621, 8652), 'diplomacy_research.models.state_space.get_current_season', 'get_current_season', (['state_proto'], {}), '(state_proto)\n', (8639, 8652), False, 'from diplomacy_research.models.state_space import get_order_based_mask, proto_to_board_state, GO_ID, NB_NODES, NB_SUPPLY_CENTERS, POWER_VOCABULARY_KEY_TO_IX, MAX_CANDIDATES, NB_FEATURES, NB_ORDERS_FEATURES, NB_PREV_ORDERS, get_board_alignments, get_orderable_locs_for_powers, get_current_season, proto_to_prev_orders_state\n'), ((7356, 7412), 'numpy.zeros', 'np.zeros', (['(NB_NODES, NB_ORDERS_FEATURES)'], {'dtype': 'np.uint8'}), '((NB_NODES, NB_ORDERS_FEATURES), dtype=np.uint8)\n', (7364, 7412), True, 'import numpy as np\n'), ((6318, 6350), 'diplomacy_research.models.state_space.get_order_based_mask', 'get_order_based_mask', (['adj_orders'], {}), '(adj_orders)\n', (6338, 6350), False, 'from diplomacy_research.models.state_space import get_order_based_mask, proto_to_board_state, GO_ID, NB_NODES, NB_SUPPLY_CENTERS, POWER_VOCABULARY_KEY_TO_IX, MAX_CANDIDATES, NB_FEATURES, NB_ORDERS_FEATURES, NB_PREV_ORDERS, get_board_alignments, get_orderable_locs_for_powers, get_current_season, proto_to_prev_orders_state\n'), ((6555, 6609), 'diplomacy_research.models.state_space.get_order_based_mask', 'get_order_based_mask', (['possible_orders_proto[loc].value'], {}), '(possible_orders_proto[loc].value)\n', (6575, 6609), False, 'from diplomacy_research.models.state_space import get_order_based_mask, proto_to_board_state, GO_ID, NB_NODES, NB_SUPPLY_CENTERS, POWER_VOCABULARY_KEY_TO_IX, MAX_CANDIDATES, NB_FEATURES, NB_ORDERS_FEATURES, NB_PREV_ORDERS, get_board_alignments, get_orderable_locs_for_powers, get_current_season, proto_to_prev_orders_state\n'), ((7185, 7236), 'diplomacy_research.models.state_space.proto_to_prev_orders_state', 'proto_to_prev_orders_state', (['phase_proto', 'map_object'], {}), '(phase_proto, map_object)\n', (7211, 7236), False, 'from diplomacy_research.models.state_space import get_order_based_mask, proto_to_board_state, GO_ID, NB_NODES, NB_SUPPLY_CENTERS, POWER_VOCABULARY_KEY_TO_IX, MAX_CANDIDATES, NB_FEATURES, NB_ORDERS_FEATURES, NB_PREV_ORDERS, get_board_alignments, get_orderable_locs_for_powers, get_current_season, proto_to_prev_orders_state\n')]
|
import csv
import numpy as np
import torch
import time
class Timer(object):
"""
docstring for Timer
"""
def __init__(self):
super(Timer, self).__init__()
self.total_time = 0.0
self.calls = 0
self.start_time = 0.0
self.diff = 0.0
self.average_time = 0.0
def tic(self):
self.start_time = time.time()
def toc(self, average = False):
self.diff = time.time() - self.start_time
self.calls += 1
self.total_time += self.diff
self.average_time = self.total_time / self.calls
if average:
return self.average_time
else:
return self.diff
def format(self, time):
m,s = divmod(time, 60)
h,m = divmod(m, 60)
d,h = divmod(h, 24)
return ("{}d:{}h:{}m:{}s".format(int(d), int(h), int(m), int(s)))
def end_time(self, extra_time):
"""
calculate the end time for training, show local time
"""
localtime= time.asctime(time.localtime(time.time() + extra_time))
return localtime
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 calculate_accuracy(outputs, targets):
batch_size = targets.size(0)
_, pred = outputs.topk(1, 1, True)
pred = pred.t()
correct = pred.eq(targets.view(1, -1))
n_correct_elems = correct.float().sum().data[0]
return n_correct_elems / batch_size
class MixUp(object):
def __init__(self, alpha):
self.alpha = alpha
def mixup_data(self, x, y, use_cuda=True):
"""
return mixed inputs. pairs of targets
"""
if self.alpha > 0:
lam = np.random.beta(self.alpha, self.alpha)
else:
lam = 1
batch_size = x.size()[0]
if use_cuda:
index = torch.randperm(batch_size).cuda()
else:
index = torch.randperm(batch_size)
mixed_x = lam * x + (1 - lam) * x[index, :]
y_a, y_b = y, y[index]
return mixed_x, y_a, y_b, lam
def mixup_criterion(self, criterion, pred, y_a, y_b, lam):
return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)
class TrainingHelper(object):
def __init__(self, image):
self.image = image
def congratulation(self):
"""
if finish training success, print congratulation information
"""
for i in range(40):
print('*')*i
print('finish training')
def submission_file(ids, outputs, filename):
""" write list of ids and outputs to filename"""
with open(filename, 'w') as f:
for vid, output in zip(ids, outputs):
scores = ['{:g}'.format(x)
for x in output]
f.write('{} {}\n'.format(vid, ' '.join(scores)))
|
[
"numpy.random.beta",
"torch.randperm",
"csv.writer",
"time.time"
] |
[((307, 318), 'time.time', 'time.time', ([], {}), '()\n', (316, 318), False, 'import time\n'), ((1435, 1476), 'csv.writer', 'csv.writer', (['self.log_file'], {'delimiter': '"""\t"""'}), "(self.log_file, delimiter='\\t')\n", (1445, 1476), False, 'import csv\n'), ((367, 378), 'time.time', 'time.time', ([], {}), '()\n', (376, 378), False, 'import time\n'), ((2503, 2541), 'numpy.random.beta', 'np.random.beta', (['self.alpha', 'self.alpha'], {}), '(self.alpha, self.alpha)\n', (2517, 2541), True, 'import numpy as np\n'), ((2718, 2744), 'torch.randperm', 'torch.randperm', (['batch_size'], {}), '(batch_size)\n', (2732, 2744), False, 'import torch\n'), ((872, 883), 'time.time', 'time.time', ([], {}), '()\n', (881, 883), False, 'import time\n'), ((2650, 2676), 'torch.randperm', 'torch.randperm', (['batch_size'], {}), '(batch_size)\n', (2664, 2676), False, 'import torch\n')]
|
# check utils zdecomp
def izmat_zdecomp():
import numpy as np
from limetr.special_mat import izmat
ok = True
tol = 1e-10
# setup problem
# -------------------------------------------------------------------------
k = 3
n = [5, 2, 4]
z_list = []
tr_u_list = []
tr_s_list = []
for i in range(len(n)):
z_list.append(np.random.randn(n[i], k))
u, s, vt = np.linalg.svd(z_list[-1], full_matrices=False)
tr_u_list.append(u)
tr_s_list.append(s)
z = np.vstack(z_list)
tr_u = np.hstack([u.reshape(u.size, order='F') for u in tr_u_list])
tr_s = np.hstack(tr_s_list)
my_u = np.zeros(tr_u.size)
my_s = np.zeros(tr_s.size)
nz = [z_sub.shape[0] for z_sub in z_list]
nu = [u_sub.size for u_sub in tr_u_list]
ns = [s_sub.size for s_sub in tr_s_list]
izmat.zdecomp(nz, nu, ns, z, my_u, my_s)
if not ok:
print('err in zdecomp')
print('err:', err)
return ok
|
[
"numpy.random.randn",
"limetr.special_mat.izmat.zdecomp",
"numpy.zeros",
"numpy.hstack",
"numpy.linalg.svd",
"numpy.vstack"
] |
[((530, 547), 'numpy.vstack', 'np.vstack', (['z_list'], {}), '(z_list)\n', (539, 547), True, 'import numpy as np\n'), ((631, 651), 'numpy.hstack', 'np.hstack', (['tr_s_list'], {}), '(tr_s_list)\n', (640, 651), True, 'import numpy as np\n'), ((664, 683), 'numpy.zeros', 'np.zeros', (['tr_u.size'], {}), '(tr_u.size)\n', (672, 683), True, 'import numpy as np\n'), ((695, 714), 'numpy.zeros', 'np.zeros', (['tr_s.size'], {}), '(tr_s.size)\n', (703, 714), True, 'import numpy as np\n'), ((857, 897), 'limetr.special_mat.izmat.zdecomp', 'izmat.zdecomp', (['nz', 'nu', 'ns', 'z', 'my_u', 'my_s'], {}), '(nz, nu, ns, z, my_u, my_s)\n', (870, 897), False, 'from limetr.special_mat import izmat\n'), ((418, 464), 'numpy.linalg.svd', 'np.linalg.svd', (['z_list[-1]'], {'full_matrices': '(False)'}), '(z_list[-1], full_matrices=False)\n', (431, 464), True, 'import numpy as np\n'), ((373, 397), 'numpy.random.randn', 'np.random.randn', (['n[i]', 'k'], {}), '(n[i], k)\n', (388, 397), True, 'import numpy as np\n')]
|
'''
Created on 13 Aug 2020
@author: <NAME>
'''
from .ts_util import *
import numpy as np
from typing import List, Tuple
class ts_data(object):
def __init__(self, ts: np.array, prop_train: float =0.75, has_time:bool = True, delta_t:float = 1.0):
'''
Utility object for time series data.
:param ts: PxN time series matrix of P timesteps consisting of N-1 features or PxN snapshot matrix of P timesteps consisting of N features
:param prop_train: proportion of training data
:param has_time: is ts a snapshot matrix
:param delta_t: timestep to be applied if ts is a snapshot matrix
'''
if (has_time):
self.ts = ts
else:
self.ts = add_uni_time(ts, delta_t)
self._create_train_test(prop_train)
self.train_ts_centered = None
self.test_ts_centered = None
self.ts_centered = None
self.train_ts_norm = None
self.test_ts_norm = None
self.ts_norm = None
self.train_mean = None
self.train_std = None
self.train_inv_std = None
self.x = None
self.x_val = None
self.x_all = None
self.x_inp = None
self.train_chunks = None
self.x_val_inp = None
self.x_val2_inp = None
@property
def num_features(self):
return self.ts.shape[1] - 1
@property
def num_obs(self):
return self.ts.shape[0]
@property
def num_train(self):
return self.train_ts.shape[0]
@property
def num_train_filtered(self):
return self.x.shape[0]
@property
def num_test(self):
return self.test_ts.shape[0]
@property
def num_test_filtered(self):
return self.x_val.shape[0]
def _create_train_test(self, prop_train=0.75):
self.train_ts, self.test_ts = train_test_split_ts(self.ts, prop_train)
def standardize(self):
'''
Standardize all training and evaluation set with the mean and the standard deviation matrix of the training set.
'''
self.train_ts_centered, self.train_mean = center_ts(self.train_ts)
self.test_ts_centered = translate_ts(self.test_ts, -self.train_mean)
self.ts_centered = translate_ts(self.ts, -self.train_mean)
self.train_std = std_ts(self.train_ts_centered)
self.train_inv_std = np.linalg.inv(self.train_std)
self.train_ts_norm = scale_ts(self.train_ts_centered, self.train_inv_std)
self.test_ts_norm = scale_ts(self.test_ts_centered, self.train_inv_std)
self.ts_norm = scale_ts(self.ts_centered, self.train_inv_std)
def generate_train_model_inputs(self, num_train_chunks:int =1, rate:float =0):
'''
'Hankelize' the training data and apply adaptive sampling rate to all data sets.
:param num_train_chunks: number of chunks
:param rate: threshold value for sampling
'''
self.x = adapt_sampling_rate(self.train_ts_norm, rate)
self.x_val = adapt_sampling_rate(self.test_ts_norm, rate)
self.x_all = adapt_sampling_rate(self.ts_norm, rate)
self.x_inp, self.train_chunks = prepare_train_model_data(self.x, num_train_chunks)
self.x_val_inp, _ = prepare_train_model_data(self.x_val, 1)
self.x_all[:,-1] = self.x_all[:,-1] - self.x_all[self.train_chunks[-1],-1]
self.x_val2_inp, _ = prepare_train_model_data(self.x_all[self.train_chunks[-1]:], 1)
|
[
"numpy.linalg.inv"
] |
[((2492, 2521), 'numpy.linalg.inv', 'np.linalg.inv', (['self.train_std'], {}), '(self.train_std)\n', (2505, 2521), True, 'import numpy as np\n')]
|
# %% [markdown]
"""
# Target Tracking
This example demonstrates the kernel-based stochastic optimal control algorithm and the
dynamic programming algorithm. By default, it uses a nonholonomic vehicle system
(unicycle dynamics), and seeks to track a v-shaped trajectory.
To run the example, use the following command:
```shell
python examples/control/tracking.py
```
"""
# %%
import gym
import numpy as np
from gym.envs.registration import make
from gym_socks.algorithms.control.kernel_control_fwd import KernelControlFwd
from gym_socks.algorithms.control.kernel_control_bwd import KernelControlBwd
from functools import partial
from sklearn.metrics.pairwise import rbf_kernel
from gym_socks.sampling import sample
from gym_socks.sampling import default_sampler
from gym_socks.sampling import random_sampler
from gym_socks.sampling import grid_sampler
from gym_socks.utils.grid import make_grid_from_ranges
# %% [markdown]
# Configuration variables.
# %%
system_id = "NonholonomicVehicleEnv-v0"
sigma = 3 # Kernel bandwidth parameter.
regularization_param = 1e-7 # Regularization parameter.
time_horizon = 20
# For controlling randomness.
seed = 12345
# %% [markdown]
# ## Generate the Sample
#
# We generate a random sample from the system, and choose random control actions and
# random initial conditions.
# %%
env = make(system_id)
env.sampling_time = 0.1
env.seed(seed)
env.action_space = gym.spaces.Box(
low=np.array([0.1, -10.1], dtype=np.float32),
high=np.array([1.1, 10.1], dtype=np.float32),
shape=(2,),
dtype=np.float32,
seed=seed,
)
sample_size = 1500
sample_space = gym.spaces.Box(
low=np.array([-1.2, -1.2, -2 * np.pi], dtype=np.float32),
high=np.array([1.2, 1.2, 2 * np.pi], dtype=np.float32),
shape=(3,),
dtype=np.float32,
seed=seed,
)
state_sampler = random_sampler(sample_space=sample_space)
action_sampler = random_sampler(sample_space=env.action_space)
S = sample(
sampler=default_sampler(
state_sampler=state_sampler, action_sampler=action_sampler, env=env
),
sample_size=sample_size,
)
A = make_grid_from_ranges([np.linspace(0.1, 1.1, 10), np.linspace(-10.1, 10.1, 21)])
# %% [markdown]
# We define the cost as the norm distance to the target at each time step.
# %%
a = 0.5 # Path amplitude.
p = 2.0 # Path period.
target_trajectory = [
[
(x * 0.1) - 1.0,
4 * a / p * np.abs((((((x * 0.1) - 1.0) - p / 2) % p) + p) % p - p / 2) - a,
]
for x in range(time_horizon)
]
def _tracking_cost(time: int = 0, state: np.ndarray = None) -> float:
"""Tracking cost function.
The goal is to minimize the distance of the x/y position of the vehicle to the
'state' of the target trajectory at each time step.
Args:
time : Time of the simulation. Used for time-dependent cost functions.
state : State of the system.
Returns:
cost : Real-valued cost.
"""
dist = state[:, :2] - np.array([target_trajectory[time]])
result = np.linalg.norm(dist, ord=2, axis=1)
result = np.power(result, 2)
return result
# %% [markdown]
# ## Algorithm
#
# Now, we can compute the policy using the algorithm, and then simulate the system
# forward in time using the computed policy.
#
# In order to change this to the dynamic programming algorithm, use `KernelControlBwd`.
# %%
# Compute the policy.
policy = KernelControlFwd(
time_horizon=time_horizon,
cost_fn=_tracking_cost,
kernel_fn=partial(rbf_kernel, gamma=1 / (2 * (sigma ** 2))),
regularization_param=regularization_param,
verbose=False,
)
policy.train(S=S, A=A)
# Simulate the controlled system.
env.reset()
initial_condition = [-0.8, 0, 0]
env.state = initial_condition
trajectory = [initial_condition]
for t in range(time_horizon):
action = policy(time=t, state=[env.state])
state, *_ = env.step(time=t, action=action)
trajectory.append(list(state))
# %% [markdown]
# ## Results
#
# We then plot the simulated trajectories of the actual system alongside the predicted
# state trajectory using the approximated dynamics.
# %%
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes()
target_trajectory = np.array(target_trajectory, dtype=np.float32)
plt.plot(
target_trajectory[:, 0],
target_trajectory[:, 1],
marker="o",
color="C0",
label="Target Trajectory",
)
trajectory = np.array(trajectory, dtype=np.float32)
plt.plot(
trajectory[:, 0],
trajectory[:, 1],
color="C1",
label="System Trajectory",
)
# Plot the markers as arrows, showing vehicle heading.
paper_airplane = [(0, -0.25), (0.5, -0.5), (0, 1), (-0.5, -0.5), (0, -0.25)]
for x in trajectory:
angle = -np.rad2deg(x[2])
t = matplotlib.markers.MarkerStyle(marker=paper_airplane)
t._transform = t.get_transform().rotate_deg(angle)
plt.plot(x[0], x[1], marker=t, markersize=15, linestyle="None", color="C1")
plt.legend()
plt.show()
|
[
"functools.partial",
"gym_socks.sampling.random_sampler",
"matplotlib.pyplot.show",
"numpy.abs",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axes",
"numpy.power",
"matplotlib.pyplot.legend",
"numpy.rad2deg",
"matplotlib.pyplot.figure",
"numpy.array",
"gym.envs.registration.make",
"numpy.linalg.norm",
"gym_socks.sampling.default_sampler",
"numpy.linspace",
"matplotlib.markers.MarkerStyle"
] |
[((1343, 1358), 'gym.envs.registration.make', 'make', (['system_id'], {}), '(system_id)\n', (1347, 1358), False, 'from gym.envs.registration import make\n'), ((1833, 1874), 'gym_socks.sampling.random_sampler', 'random_sampler', ([], {'sample_space': 'sample_space'}), '(sample_space=sample_space)\n', (1847, 1874), False, 'from gym_socks.sampling import random_sampler\n'), ((1892, 1937), 'gym_socks.sampling.random_sampler', 'random_sampler', ([], {'sample_space': 'env.action_space'}), '(sample_space=env.action_space)\n', (1906, 1937), False, 'from gym_socks.sampling import random_sampler\n'), ((4160, 4172), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4170, 4172), True, 'import matplotlib.pyplot as plt\n'), ((4178, 4188), 'matplotlib.pyplot.axes', 'plt.axes', ([], {}), '()\n', (4186, 4188), True, 'import matplotlib.pyplot as plt\n'), ((4210, 4255), 'numpy.array', 'np.array', (['target_trajectory'], {'dtype': 'np.float32'}), '(target_trajectory, dtype=np.float32)\n', (4218, 4255), True, 'import numpy as np\n'), ((4256, 4369), 'matplotlib.pyplot.plot', 'plt.plot', (['target_trajectory[:, 0]', 'target_trajectory[:, 1]'], {'marker': '"""o"""', 'color': '"""C0"""', 'label': '"""Target Trajectory"""'}), "(target_trajectory[:, 0], target_trajectory[:, 1], marker='o',\n color='C0', label='Target Trajectory')\n", (4264, 4369), True, 'import matplotlib.pyplot as plt\n'), ((4403, 4441), 'numpy.array', 'np.array', (['trajectory'], {'dtype': 'np.float32'}), '(trajectory, dtype=np.float32)\n', (4411, 4441), True, 'import numpy as np\n'), ((4442, 4530), 'matplotlib.pyplot.plot', 'plt.plot', (['trajectory[:, 0]', 'trajectory[:, 1]'], {'color': '"""C1"""', 'label': '"""System Trajectory"""'}), "(trajectory[:, 0], trajectory[:, 1], color='C1', label=\n 'System Trajectory')\n", (4450, 4530), True, 'import matplotlib.pyplot as plt\n'), ((4930, 4942), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4940, 4942), True, 'import matplotlib.pyplot as plt\n'), ((4943, 4953), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4951, 4953), True, 'import matplotlib.pyplot as plt\n'), ((3010, 3045), 'numpy.linalg.norm', 'np.linalg.norm', (['dist'], {'ord': '(2)', 'axis': '(1)'}), '(dist, ord=2, axis=1)\n', (3024, 3045), True, 'import numpy as np\n'), ((3059, 3078), 'numpy.power', 'np.power', (['result', '(2)'], {}), '(result, 2)\n', (3067, 3078), True, 'import numpy as np\n'), ((4739, 4792), 'matplotlib.markers.MarkerStyle', 'matplotlib.markers.MarkerStyle', ([], {'marker': 'paper_airplane'}), '(marker=paper_airplane)\n', (4769, 4792), False, 'import matplotlib\n'), ((4853, 4928), 'matplotlib.pyplot.plot', 'plt.plot', (['x[0]', 'x[1]'], {'marker': 't', 'markersize': '(15)', 'linestyle': '"""None"""', 'color': '"""C1"""'}), "(x[0], x[1], marker=t, markersize=15, linestyle='None', color='C1')\n", (4861, 4928), True, 'import matplotlib.pyplot as plt\n'), ((1441, 1481), 'numpy.array', 'np.array', (['[0.1, -10.1]'], {'dtype': 'np.float32'}), '([0.1, -10.1], dtype=np.float32)\n', (1449, 1481), True, 'import numpy as np\n'), ((1492, 1531), 'numpy.array', 'np.array', (['[1.1, 10.1]'], {'dtype': 'np.float32'}), '([1.1, 10.1], dtype=np.float32)\n', (1500, 1531), True, 'import numpy as np\n'), ((1648, 1700), 'numpy.array', 'np.array', (['[-1.2, -1.2, -2 * np.pi]'], {'dtype': 'np.float32'}), '([-1.2, -1.2, -2 * np.pi], dtype=np.float32)\n', (1656, 1700), True, 'import numpy as np\n'), ((1711, 1760), 'numpy.array', 'np.array', (['[1.2, 1.2, 2 * np.pi]'], {'dtype': 'np.float32'}), '([1.2, 1.2, 2 * np.pi], dtype=np.float32)\n', (1719, 1760), True, 'import numpy as np\n'), ((1963, 2051), 'gym_socks.sampling.default_sampler', 'default_sampler', ([], {'state_sampler': 'state_sampler', 'action_sampler': 'action_sampler', 'env': 'env'}), '(state_sampler=state_sampler, action_sampler=action_sampler,\n env=env)\n', (1978, 2051), False, 'from gym_socks.sampling import default_sampler\n'), ((2122, 2147), 'numpy.linspace', 'np.linspace', (['(0.1)', '(1.1)', '(10)'], {}), '(0.1, 1.1, 10)\n', (2133, 2147), True, 'import numpy as np\n'), ((2149, 2177), 'numpy.linspace', 'np.linspace', (['(-10.1)', '(10.1)', '(21)'], {}), '(-10.1, 10.1, 21)\n', (2160, 2177), True, 'import numpy as np\n'), ((2961, 2996), 'numpy.array', 'np.array', (['[target_trajectory[time]]'], {}), '([target_trajectory[time]])\n', (2969, 2996), True, 'import numpy as np\n'), ((3478, 3525), 'functools.partial', 'partial', (['rbf_kernel'], {'gamma': '(1 / (2 * sigma ** 2))'}), '(rbf_kernel, gamma=1 / (2 * sigma ** 2))\n', (3485, 3525), False, 'from functools import partial\n'), ((4713, 4729), 'numpy.rad2deg', 'np.rad2deg', (['x[2]'], {}), '(x[2])\n', (4723, 4729), True, 'import numpy as np\n'), ((2402, 2455), 'numpy.abs', 'np.abs', (['(((x * 0.1 - 1.0 - p / 2) % p + p) % p - p / 2)'], {}), '(((x * 0.1 - 1.0 - p / 2) % p + p) % p - p / 2)\n', (2408, 2455), True, 'import numpy as np\n')]
|
"""
ckwg +31
Copyright 2016-2020 by Kitware, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither name of Kitware, Inc. nor the names of any 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 AUTHORS 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.
==============================================================================
Tests for vital.types.Rotation class
"""
from __future__ import print_function
import math
import unittest
import nose.tools
import numpy
from kwiver.vital.types import rotation, RotationD, RotationF
def array_normalize(a, dtype=None):
a = numpy.asarray(a, dtype)
return (a / numpy.linalg.norm(a)).tolist()
class TestVitalRotation(unittest.TestCase):
def test_new_default(self):
# That these even construct
rot_d = RotationD()
nose.tools.assert_equal(rot_d.type_name, "d")
rot_f = RotationF()
nose.tools.assert_equal(rot_f.type_name, "f")
def test_eq(self):
# Identities should equal
r1 = RotationD()
r2 = RotationD()
nose.tools.assert_equal(r1, r2)
r3 = RotationD([1, 2, 3, 4])
r4 = RotationD([1, 2, 3, 4])
nose.tools.assert_equal(r3, r4)
nose.tools.assert_false(r1 == r3)
r1 = RotationF()
r2 = RotationF()
nose.tools.assert_equal(r1, r2)
r3 = RotationF([1, 2, 3, 4])
r4 = RotationF([1, 2, 3, 4])
nose.tools.assert_equal(r3, r4)
nose.tools.assert_false(r1 == r3)
r1 = RotationD([1, 2, 3, 4])
r2 = RotationD([-1, -2, -3, -4])
assert r1.angle_from(r2) < 1e-12
def test_not_eq(self):
# Identities should equal
r1 = RotationD()
r2 = RotationD()
nose.tools.assert_false(r1 != r2)
r3 = RotationD([1, 2, 3, 4])
r4 = RotationD([1, 2, 3, 4])
nose.tools.assert_false(r3 != r4)
nose.tools.ok_(r1 != r3)
r1 = RotationF()
r2 = RotationF()
nose.tools.assert_false(r1 != r2)
r3 = RotationF([1, 2, 3, 4])
r4 = RotationF([1, 2, 3, 4])
nose.tools.assert_false(r3 != r4)
nose.tools.ok_(r1 != r3)
def test_to_matrix(self):
# Default value should be identity
rot_d = RotationD()
numpy.testing.assert_array_equal(rot_d.matrix(), numpy.eye(3))
rot_f = RotationF()
numpy.testing.assert_array_equal(rot_f.matrix(), numpy.eye(3))
def test_to_quaternion(self):
rot_d = RotationD()
numpy.testing.assert_array_equal(rot_d.quaternion(), [0, 0, 0, 1])
rot_f = RotationF()
numpy.testing.assert_array_equal(rot_f.quaternion(), [0, 0, 0, 1])
def test_to_axis_angle(self):
# expected identity: [0,0,1] and 0
ident_axis = [0, 0, 1]
ident_angle = 0
rot_d = RotationD()
rot_f = RotationF()
numpy.testing.assert_equal(rot_d.axis(), ident_axis)
nose.tools.assert_equal(rot_d.angle(), ident_angle)
numpy.testing.assert_equal(rot_f.axis(), ident_axis)
nose.tools.assert_equal(rot_f.angle(), ident_angle)
def test_to_rodrigues(self):
# rodrigues identity: [0,0,0]
ident_rod = [0, 0, 0]
rot_d = RotationD()
rot_f = RotationF()
rod = rot_d.rodrigues()
numpy.testing.assert_equal(rod, ident_rod)
rod = rot_f.rodrigues()
numpy.testing.assert_equal(rod, ident_rod)
def test_to_ypr(self):
# ypr identity: (pi/2, 0, pi)
ident_ypr = (math.pi / 2, 0, -math.pi)
rot_d = RotationD()
rot_f = RotationF()
numpy.testing.assert_almost_equal(rot_d.yaw_pitch_roll(), ident_ypr, 15)
numpy.testing.assert_almost_equal(rot_f.yaw_pitch_roll(), ident_ypr)
def test_from_rotation(self):
r = RotationD()
r_cpy = RotationD(r)
nose.tools.ok_(r == r_cpy)
r = RotationD([1, 2, 3, 4])
r_cpy = RotationD(r)
nose.tools.ok_(r == r_cpy)
r = RotationF()
r_cpy = RotationF(r)
nose.tools.ok_(r == r_cpy)
r = RotationF([1, 2, 3, 4])
r_cpy = RotationF(r)
nose.tools.ok_(r == r_cpy)
def test_from_rotation_other_type(self):
r = RotationD()
r_cpy = RotationF(r)
numpy.testing.assert_array_almost_equal(r.quaternion(), r_cpy.quaternion(), 6)
r = RotationD([1, 2, 3, 4])
r_cpy = RotationF(r)
numpy.testing.assert_array_almost_equal(r.quaternion(), r_cpy.quaternion(), 6)
r = RotationF()
r_cpy = RotationD(r)
numpy.testing.assert_array_almost_equal(r.quaternion(), r_cpy.quaternion(), 6)
r = RotationF([1, 2, 3, 4])
r_cpy = RotationD(r)
numpy.testing.assert_array_almost_equal(r.quaternion(), r_cpy.quaternion(), 6)
def test_from_quaternion(self):
q = array_normalize([+2, -1, -3, +0], float)
r = RotationD(q)
numpy.testing.assert_equal(r.quaternion(), q)
def test_from_rodrigues(self):
rod_list_1 = [0, 0, 0]
r1 = RotationD(rod_list_1)
numpy.testing.assert_equal(r1.rodrigues(), rod_list_1)
# This one will get normalized by magnitude in rotation instance
# This vector's is less than 2*pi, so we should expect this vector to be
# returned as is.
rod2 = numpy.array([2, -1, 0.5])
nod2_normed = array_normalize(rod2)
print("r2 2-norm:", numpy.linalg.norm(rod2))
print("r2-normed:", nod2_normed)
r2 = RotationD(rod2)
numpy.testing.assert_array_almost_equal(
r2.rodrigues(), rod2, decimal=14, # 1e-14
)
def test_from_aa(self):
# Axis should come out of rotation normalized
angle = 0.8
axis = [-3, 2, 1]
axis_norm = array_normalize(axis)
r = RotationD(angle, axis)
nose.tools.assert_equal(angle, r.angle())
numpy.testing.assert_equal(axis_norm, r.axis())
def test_from_ypr(self):
y = 1.2
p = 0.3
r = -1.0
# XXX
rot = RotationD(y, p, r)
ry, rp, rr = rot.yaw_pitch_roll()
nose.tools.assert_almost_equal(y, ry, 14)
nose.tools.assert_almost_equal(p, rp, 14)
nose.tools.assert_almost_equal(r, rr, 14)
# 0XX
rot = RotationD(0, p, r)
ry, rp, rr = rot.yaw_pitch_roll()
nose.tools.assert_almost_equal(0, ry, 14)
nose.tools.assert_almost_equal(p, rp, 14)
nose.tools.assert_almost_equal(r, rr, 14)
# X0X
rot = RotationD(y, 0, r)
ry, rp, rr = rot.yaw_pitch_roll()
nose.tools.assert_almost_equal(y, ry, 14)
nose.tools.assert_almost_equal(0, rp, 14)
nose.tools.assert_almost_equal(r, rr, 14)
# XX0
rot = RotationD(y, p, 0)
ry, rp, rr = rot.yaw_pitch_roll()
nose.tools.assert_almost_equal(y, ry, 14)
nose.tools.assert_almost_equal(p, rp, 14)
nose.tools.assert_almost_equal(0, rr, 14)
# 00X
rot = RotationD(0, 0, r)
ry, rp, rr = rot.yaw_pitch_roll()
nose.tools.assert_almost_equal(0, ry, 14)
nose.tools.assert_almost_equal(0, rp, 14)
nose.tools.assert_almost_equal(r, rr, 14)
# 0X0
rot = RotationD(0, p, 0)
ry, rp, rr = rot.yaw_pitch_roll()
nose.tools.assert_almost_equal(0, ry, 14)
nose.tools.assert_almost_equal(p, rp, 14)
nose.tools.assert_almost_equal(0, rr, 14)
# X00
rot = RotationD(y, 0, 0)
ry, rp, rr = rot.yaw_pitch_roll()
nose.tools.assert_almost_equal(y, ry, 14)
nose.tools.assert_almost_equal(0, rp, 14)
nose.tools.assert_almost_equal(0, rr, 14)
# 000
rot = RotationD(0, 0, 0)
ry, rp, rr = rot.yaw_pitch_roll()
nose.tools.assert_almost_equal(0, ry, 14)
nose.tools.assert_almost_equal(0, rp, 14)
nose.tools.assert_almost_equal(0, rr, 14)
def test_from_matrix(self):
# Create a non-identity matrix from a different constructor that we
# assume works
# Create new rotation with that matrix.
# New rotation to_matrix method should produce the same matrix
pre_r = RotationD([+2, -1, -3, +0])
mat = pre_r.matrix()
r = RotationD(mat)
numpy.testing.assert_allclose(mat, r.matrix(), 1e-15)
def test_inverse(self):
# quaternion calc from:
# https://www.wolframalpha.com/input/?i=quaternion:+0%2B2i-j-3k&lk=3
r = RotationD([+2, -1, -3, +0])
r_inv = r.inverse()
e_inv = array_normalize([-1 / 7.0, +1 / 14.0, +3 / 14.0, 0])
numpy.testing.assert_allclose(r_inv.quaternion(), e_inv, 1e-15)
r = RotationF([+2, -1, -3, +0])
r_inv = r.inverse()
numpy.testing.assert_allclose(r_inv.quaternion(), e_inv, 1e-7)
def test_mul(self):
# Normalize quaternaion vector.
expected_quat = array_normalize([+2.0, -1.0, -3.0, +0.0])
r_ident_d = RotationD()
r_ident_f = RotationF()
r_other_d = RotationD(expected_quat)
r_other_f = RotationF(expected_quat)
r_res_d = r_ident_d * r_other_d
nose.tools.assert_is_not(r_other_d, r_res_d)
numpy.testing.assert_equal(r_res_d, r_other_d)
numpy.testing.assert_equal(r_res_d.quaternion(), expected_quat)
r_res_f = r_ident_f * r_other_f
nose.tools.assert_is_not(r_other_f, r_res_f)
numpy.testing.assert_equal(r_res_f, r_other_f)
numpy.testing.assert_allclose(r_res_f.quaternion(), expected_quat, 1e-7)
def test_mul_vector(self):
vec = [1, 0, 0]
vec_expected = [0, 1, 0]
r_axis = [0, 0, 1]
r_angle = math.pi / 2.0
r = RotationD(r_angle, r_axis)
vec_rotated = r * vec
numpy.testing.assert_array_almost_equal(vec_expected, vec_rotated)
def test_interpolation(self):
x_d = RotationD(0, [1, 0, 0])
y_d = RotationD(math.pi / 2, [0, 1, 0])
r_d = RotationD(math.pi / 4, [0, 1, 0])
x_f = RotationF(0, [1, 0, 0])
y_f = RotationF(math.pi / 2, [0, 1, 0])
r_f = RotationF(math.pi / 4, [0, 1, 0])
z_d = rotation.interpolate_rotation(x_d, y_d, 0.5)
z_f = rotation.interpolate_rotation(x_f, y_f, 0.5)
nose.tools.assert_almost_equal((z_d.inverse() * r_d).angle(), 0, 14)
nose.tools.assert_almost_equal((z_f.inverse() * r_f).angle(), 0, 6)
def test_interpolated_rotations(self):
x = RotationD(0, [1, 0, 0])
a = math.pi / 2
y = RotationD(a, [0, 1, 0])
i_list = rotation.interpolated_rotations(x, y, 3)
nose.tools.assert_equal([i.type_name for i in i_list], ["d"] * 3)
i0_e_axis, i0_e_angle = [0, 1, 0], a * 0.25
i1_e_axis, i1_e_angle = [0, 1, 0], a * 0.50
i2_e_axis, i2_e_angle = [0, 1, 0], a * 0.75
numpy.testing.assert_almost_equal(i_list[0].axis(), i0_e_axis, 14)
numpy.testing.assert_almost_equal(i_list[0].angle(), i0_e_angle, 14)
numpy.testing.assert_almost_equal(i_list[1].axis(), i1_e_axis, 14)
numpy.testing.assert_almost_equal(i_list[1].angle(), i1_e_angle, 14)
numpy.testing.assert_almost_equal(i_list[2].axis(), i2_e_axis, 14)
numpy.testing.assert_almost_equal(i_list[2].angle(), i2_e_angle, 14)
|
[
"kwiver.vital.types.rotation.interpolate_rotation",
"numpy.asarray",
"numpy.array",
"kwiver.vital.types.RotationD",
"kwiver.vital.types.RotationF",
"numpy.testing.assert_equal",
"numpy.linalg.norm",
"numpy.eye",
"numpy.testing.assert_array_almost_equal",
"kwiver.vital.types.rotation.interpolated_rotations"
] |
[((1827, 1850), 'numpy.asarray', 'numpy.asarray', (['a', 'dtype'], {}), '(a, dtype)\n', (1840, 1850), False, 'import numpy\n'), ((2028, 2039), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (2037, 2039), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2111, 2122), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (2120, 2122), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2248, 2259), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (2257, 2259), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2273, 2284), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (2282, 2284), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2339, 2362), 'kwiver.vital.types.RotationD', 'RotationD', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (2348, 2362), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2376, 2399), 'kwiver.vital.types.RotationD', 'RotationD', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (2385, 2399), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2496, 2507), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (2505, 2507), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2521, 2532), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (2530, 2532), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2587, 2610), 'kwiver.vital.types.RotationF', 'RotationF', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (2596, 2610), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2624, 2647), 'kwiver.vital.types.RotationF', 'RotationF', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (2633, 2647), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2744, 2767), 'kwiver.vital.types.RotationD', 'RotationD', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (2753, 2767), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2781, 2808), 'kwiver.vital.types.RotationD', 'RotationD', (['[-1, -2, -3, -4]'], {}), '([-1, -2, -3, -4])\n', (2790, 2808), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2925, 2936), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (2934, 2936), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((2950, 2961), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (2959, 2961), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((3018, 3041), 'kwiver.vital.types.RotationD', 'RotationD', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (3027, 3041), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((3055, 3078), 'kwiver.vital.types.RotationD', 'RotationD', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (3064, 3078), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((3168, 3179), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (3177, 3179), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((3193, 3204), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (3202, 3204), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((3261, 3284), 'kwiver.vital.types.RotationF', 'RotationF', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (3270, 3284), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((3298, 3321), 'kwiver.vital.types.RotationF', 'RotationF', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (3307, 3321), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((3487, 3498), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (3496, 3498), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((3587, 3598), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (3596, 3598), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((3721, 3732), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (3730, 3732), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((3825, 3836), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (3834, 3836), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((4062, 4073), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (4071, 4073), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((4090, 4101), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (4099, 4101), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((4465, 4476), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (4474, 4476), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((4493, 4504), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (4502, 4504), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((4546, 4588), 'numpy.testing.assert_equal', 'numpy.testing.assert_equal', (['rod', 'ident_rod'], {}), '(rod, ident_rod)\n', (4572, 4588), False, 'import numpy\n'), ((4630, 4672), 'numpy.testing.assert_equal', 'numpy.testing.assert_equal', (['rod', 'ident_rod'], {}), '(rod, ident_rod)\n', (4656, 4672), False, 'import numpy\n'), ((4803, 4814), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (4812, 4814), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((4831, 4842), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (4840, 4842), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5050, 5061), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (5059, 5061), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5078, 5090), 'kwiver.vital.types.RotationD', 'RotationD', (['r'], {}), '(r)\n', (5087, 5090), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5139, 5162), 'kwiver.vital.types.RotationD', 'RotationD', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (5148, 5162), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5179, 5191), 'kwiver.vital.types.RotationD', 'RotationD', (['r'], {}), '(r)\n', (5188, 5191), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5240, 5251), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (5249, 5251), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5268, 5280), 'kwiver.vital.types.RotationF', 'RotationF', (['r'], {}), '(r)\n', (5277, 5280), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5329, 5352), 'kwiver.vital.types.RotationF', 'RotationF', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (5338, 5352), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5369, 5381), 'kwiver.vital.types.RotationF', 'RotationF', (['r'], {}), '(r)\n', (5378, 5381), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5475, 5486), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (5484, 5486), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5503, 5515), 'kwiver.vital.types.RotationF', 'RotationF', (['r'], {}), '(r)\n', (5512, 5515), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5616, 5639), 'kwiver.vital.types.RotationD', 'RotationD', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (5625, 5639), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5656, 5668), 'kwiver.vital.types.RotationF', 'RotationF', (['r'], {}), '(r)\n', (5665, 5668), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5769, 5780), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (5778, 5780), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5797, 5809), 'kwiver.vital.types.RotationD', 'RotationD', (['r'], {}), '(r)\n', (5806, 5809), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5910, 5933), 'kwiver.vital.types.RotationF', 'RotationF', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (5919, 5933), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((5950, 5962), 'kwiver.vital.types.RotationD', 'RotationD', (['r'], {}), '(r)\n', (5959, 5962), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((6153, 6165), 'kwiver.vital.types.RotationD', 'RotationD', (['q'], {}), '(q)\n', (6162, 6165), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((6301, 6322), 'kwiver.vital.types.RotationD', 'RotationD', (['rod_list_1'], {}), '(rod_list_1)\n', (6310, 6322), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((6584, 6609), 'numpy.array', 'numpy.array', (['[2, -1, 0.5]'], {}), '([2, -1, 0.5])\n', (6595, 6609), False, 'import numpy\n'), ((6762, 6777), 'kwiver.vital.types.RotationD', 'RotationD', (['rod2'], {}), '(rod2)\n', (6771, 6777), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((7076, 7098), 'kwiver.vital.types.RotationD', 'RotationD', (['angle', 'axis'], {}), '(angle, axis)\n', (7085, 7098), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((7313, 7331), 'kwiver.vital.types.RotationD', 'RotationD', (['y', 'p', 'r'], {}), '(y, p, r)\n', (7322, 7331), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((7553, 7571), 'kwiver.vital.types.RotationD', 'RotationD', (['(0)', 'p', 'r'], {}), '(0, p, r)\n', (7562, 7571), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((7793, 7811), 'kwiver.vital.types.RotationD', 'RotationD', (['y', '(0)', 'r'], {}), '(y, 0, r)\n', (7802, 7811), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((8033, 8051), 'kwiver.vital.types.RotationD', 'RotationD', (['y', 'p', '(0)'], {}), '(y, p, 0)\n', (8042, 8051), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((8273, 8291), 'kwiver.vital.types.RotationD', 'RotationD', (['(0)', '(0)', 'r'], {}), '(0, 0, r)\n', (8282, 8291), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((8513, 8531), 'kwiver.vital.types.RotationD', 'RotationD', (['(0)', 'p', '(0)'], {}), '(0, p, 0)\n', (8522, 8531), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((8753, 8771), 'kwiver.vital.types.RotationD', 'RotationD', (['y', '(0)', '(0)'], {}), '(y, 0, 0)\n', (8762, 8771), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((8993, 9011), 'kwiver.vital.types.RotationD', 'RotationD', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (9002, 9011), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((9473, 9500), 'kwiver.vital.types.RotationD', 'RotationD', (['[+2, -1, -3, +0]'], {}), '([+2, -1, -3, +0])\n', (9482, 9500), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((9542, 9556), 'kwiver.vital.types.RotationD', 'RotationD', (['mat'], {}), '(mat)\n', (9551, 9556), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((9771, 9798), 'kwiver.vital.types.RotationD', 'RotationD', (['[+2, -1, -3, +0]'], {}), '([+2, -1, -3, +0])\n', (9780, 9798), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((9981, 10008), 'kwiver.vital.types.RotationF', 'RotationF', (['[+2, -1, -3, +0]'], {}), '([+2, -1, -3, +0])\n', (9990, 10008), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((10260, 10271), 'kwiver.vital.types.RotationD', 'RotationD', ([], {}), '()\n', (10269, 10271), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((10292, 10303), 'kwiver.vital.types.RotationF', 'RotationF', ([], {}), '()\n', (10301, 10303), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((10324, 10348), 'kwiver.vital.types.RotationD', 'RotationD', (['expected_quat'], {}), '(expected_quat)\n', (10333, 10348), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((10369, 10393), 'kwiver.vital.types.RotationF', 'RotationF', (['expected_quat'], {}), '(expected_quat)\n', (10378, 10393), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((10496, 10542), 'numpy.testing.assert_equal', 'numpy.testing.assert_equal', (['r_res_d', 'r_other_d'], {}), '(r_res_d, r_other_d)\n', (10522, 10542), False, 'import numpy\n'), ((10717, 10763), 'numpy.testing.assert_equal', 'numpy.testing.assert_equal', (['r_res_f', 'r_other_f'], {}), '(r_res_f, r_other_f)\n', (10743, 10763), False, 'import numpy\n'), ((11006, 11032), 'kwiver.vital.types.RotationD', 'RotationD', (['r_angle', 'r_axis'], {}), '(r_angle, r_axis)\n', (11015, 11032), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((11072, 11138), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['vec_expected', 'vec_rotated'], {}), '(vec_expected, vec_rotated)\n', (11111, 11138), False, 'import numpy\n'), ((11188, 11211), 'kwiver.vital.types.RotationD', 'RotationD', (['(0)', '[1, 0, 0]'], {}), '(0, [1, 0, 0])\n', (11197, 11211), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((11226, 11259), 'kwiver.vital.types.RotationD', 'RotationD', (['(math.pi / 2)', '[0, 1, 0]'], {}), '(math.pi / 2, [0, 1, 0])\n', (11235, 11259), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((11274, 11307), 'kwiver.vital.types.RotationD', 'RotationD', (['(math.pi / 4)', '[0, 1, 0]'], {}), '(math.pi / 4, [0, 1, 0])\n', (11283, 11307), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((11323, 11346), 'kwiver.vital.types.RotationF', 'RotationF', (['(0)', '[1, 0, 0]'], {}), '(0, [1, 0, 0])\n', (11332, 11346), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((11361, 11394), 'kwiver.vital.types.RotationF', 'RotationF', (['(math.pi / 2)', '[0, 1, 0]'], {}), '(math.pi / 2, [0, 1, 0])\n', (11370, 11394), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((11409, 11442), 'kwiver.vital.types.RotationF', 'RotationF', (['(math.pi / 4)', '[0, 1, 0]'], {}), '(math.pi / 4, [0, 1, 0])\n', (11418, 11442), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((11458, 11502), 'kwiver.vital.types.rotation.interpolate_rotation', 'rotation.interpolate_rotation', (['x_d', 'y_d', '(0.5)'], {}), '(x_d, y_d, 0.5)\n', (11487, 11502), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((11517, 11561), 'kwiver.vital.types.rotation.interpolate_rotation', 'rotation.interpolate_rotation', (['x_f', 'y_f', '(0.5)'], {}), '(x_f, y_f, 0.5)\n', (11546, 11561), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((11771, 11794), 'kwiver.vital.types.RotationD', 'RotationD', (['(0)', '[1, 0, 0]'], {}), '(0, [1, 0, 0])\n', (11780, 11794), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((11831, 11854), 'kwiver.vital.types.RotationD', 'RotationD', (['a', '[0, 1, 0]'], {}), '(a, [0, 1, 0])\n', (11840, 11854), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((11872, 11912), 'kwiver.vital.types.rotation.interpolated_rotations', 'rotation.interpolated_rotations', (['x', 'y', '(3)'], {}), '(x, y, 3)\n', (11903, 11912), False, 'from kwiver.vital.types import rotation, RotationD, RotationF\n'), ((3556, 3568), 'numpy.eye', 'numpy.eye', (['(3)'], {}), '(3)\n', (3565, 3568), False, 'import numpy\n'), ((3656, 3668), 'numpy.eye', 'numpy.eye', (['(3)'], {}), '(3)\n', (3665, 3668), False, 'import numpy\n'), ((6682, 6705), 'numpy.linalg.norm', 'numpy.linalg.norm', (['rod2'], {}), '(rod2)\n', (6699, 6705), False, 'import numpy\n'), ((1867, 1887), 'numpy.linalg.norm', 'numpy.linalg.norm', (['a'], {}), '(a)\n', (1884, 1887), False, 'import numpy\n')]
|
# This file is part of the Astrometry.net suite.
# Licensed under a 3-clause BSD style license - see LICENSE
from __future__ import print_function
from __future__ import absolute_import
import os
from astrometry.util.fits import fits_table
import numpy as np
import logging
import tempfile
import sys
py3 = (sys.version_info[0] >= 3)
if py3:
from urllib.parse import urljoin
else:
from urlparse import urljoin
fitsio = None
try:
import fitsio
except:
try:
import pyfits
except ImportError:
try:
from astropy.io import fits as pyfits
except ImportError:
raise ImportError("Cannot import either pyfits or astropy.io.fits")
from .common import *
from .dr7 import *
from .yanny import *
from astrometry.util.run_command import run_command
class Frame(SdssFile):
def __init__(self, *args, **kwargs):
super(Frame, self).__init__(*args, **kwargs)
self.filetype = 'frame'
self.image = None
self.image_proxy = None
def getImageShape(self):
if self.image_proxy is not None:
# fitsio fits.FITSHDU object
H,W = self.image_proxy.get_info()['dims']
H = int(H)
W = int(W)
else:
H,W = self.image.shape
return H,W
def getImageSlice(self, slice):
if self.image_proxy is not None:
#print 'reading slice from image proxy:', slice
return self.image_proxy[slice]
return self.image[slice]
#def __str__(self):
def getImage(self):
if self.image is None and self.image_proxy is not None:
self.image = self.image_proxy.read()
self.image_proxy = None
return self.image
def getHeader(self):
return self.header
def getAsTrans(self):
return self.astrans
def getCalibVec(self):
return self.calib
def getSkyAt(self, x, y):
skyim = self.sky
(sh,sw) = skyim.shape
if sw != 256:
skyim = skyim.T
(sh,sw) = skyim.shape
xi = np.round(self.skyxi[x]).astype(int)
yi = np.round(self.skyyi[y]).astype(int)
yi = np.minimum(yi,sh-1)
return skyim[yi,xi]
def getSky(self):
skyim = self.sky
(sh,sw) = skyim.shape
if sw != 256:
skyim = skyim.T
(sh,sw) = skyim.shape
xi = np.round(self.skyxi).astype(int)
yi = np.round(self.skyyi).astype(int)
yi = np.minimum(yi,sh-1)
assert(all(xi >= 0) and all(xi < sw))
assert(all(yi >= 0) and all(yi < sh))
XI,YI = np.meshgrid(xi, yi)
# Nearest-neighbour interpolation -- we just need this
# for approximate invvar.
bigsky = skyim[YI,XI]
return bigsky
def getInvvar(self, psfield, bandnum, ignoreSourceFlux=False,
sourceFlux=None, constantSkyAt=None):
'''
If constantSkyAt = (x,y) (INTEGERS!),
returns a scalar (rather than a np.array) of the invvar at that point.
NOTE that this does NOT blank out masked pixels; use, eg,
fpM = sdss.readFpM(run, camcol, field, bandname)
for plane in [ 'INTERP', 'SATUR', 'CR', 'GHOST' ]:
fpM.setMaskedPixels(plane, invvar, 0, roi=roi)
'''
calibvec = self.getCalibVec()
if constantSkyAt:
x,y = constantSkyAt
calibvec = calibvec[x]
sky = self.getSkyAt(x,y)
if ignoreSourceFlux:
dn = sky
elif sourceFlux is None:
image = self.getImage()
dn = (image[y,x] / calibvec) + sky
else:
dn = (sourceFlux / calibvec) + sky
else:
bigsky = self.getSky()
if ignoreSourceFlux:
dn = bigsky
elif sourceFlux is None:
image = self.getImage()
dn = (image / calibvec) + bigsky
else:
dn = (sourceFlux / calibvec) + bigsky
gain = psfield.getGain(bandnum)
# Note, "darkvar" includes dark current *and* read noise.
darkvar = psfield.getDarkVariance(bandnum)
dnvar = (dn / gain) + darkvar
invvar = 1./(dnvar * calibvec**2)
return invvar
class PhotoObj(SdssFile):
def __init__(self, *args, **kwargs):
super(PhotoObj, self).__init__(*args, **kwargs)
self.filetype = 'photoObj'
self.table = None
def getTable(self):
return self.table
class runlist(object):
pass
class DR8(DR7):
_lup_to_mag_b = np.array([1.4e-10, 0.9e-10, 1.2e-10, 1.8e-10, 7.4e-10])
_two_lup_to_mag_b = 2.*_lup_to_mag_b
_ln_lup_to_mag_b = np.log(_lup_to_mag_b)
'''
From
http://data.sdss3.org/datamodel/glossary.html#asinh
m = -(2.5/ln(10))*[asinh(f/2b)+ln(b)].
The parameter b is a softening parameter measured in maggies, and
for the [u, g, r, i, z] bands has the values
[1.4, 0.9, 1.2, 1.8, 7.4] x 1e-10
'''
@staticmethod
def luptitude_to_mag(Lmag, bandnum, badmag=25):
if bandnum is None:
# assume Lmag is broadcastable to a 5-vector
twobi = DR8._two_lup_to_mag_b
lnbi = DR8._ln_lup_to_mag_b
else:
twobi = DR8._two_lup_to_mag_b[bandnum]
lnbi = DR8._ln_lup_to_mag_b[bandnum]
# MAGIC -1.08.... = -2.5/np.log(10.)
f = np.sinh(Lmag/-1.0857362047581294 - lnbi) * twobi
# prevent log10(-flux)
mag = np.zeros_like(f) + badmag
I = (f > 0)
mag[I] = -2.5 * np.log10(f[I])
return mag
@staticmethod
def nmgy_to_mag(nmgy):
return 22.5 - 2.5 * np.log10(nmgy)
def getDRNumber(self):
return 8
def useLocalTree(self, photoObjs=None, resolve=None):
if photoObjs is None:
photoObjs = os.environ['BOSS_PHOTOOBJ']
redux = os.environ['PHOTO_REDUX']
if resolve is None:
resolve = os.environ['PHOTO_RESOLVE']
self.filenames.update(
photoObj = os.path.join(photoObjs, '%(rerun)s', '%(run)i', '%(camcol)i',
'photoObj-%(run)06i-%(camcol)i-%(field)04i.fits'),
frame = os.path.join(photoObjs, 'frames', '%(rerun)s', '%(run)i', '%(camcol)i',
'frame-%(band)s-%(run)06i-%(camcol)i-%(field)04i.fits.bz2'),
photoField = os.path.join(photoObjs, '%(rerun)s', '%(run)i',
'photoField-%(run)06i-%(camcol)i.fits'),
psField = os.path.join(redux, '%(rerun)s', '%(run)i', 'objcs', '%(camcol)i',
'psField-%(run)06i-%(camcol)i-%(field)04i.fit'),
fpM = os.path.join(redux, '%(rerun)s', '%(run)i', 'objcs', '%(camcol)i',
'fpM-%(run)06i-%(band)s%(camcol)i-%(field)04i.fit.gz'),
window_flist = os.path.join(resolve, 'window_flist.fits'),
)
# use fpM files compressed
try:
del self.dassuffix['fpM']
except:
pass
try:
del self.processcmds['fpM']
except:
pass
def saveUnzippedFiles(self, basedir):
self.unzip_dir = basedir
def setFitsioReadBZ2(self, to=True):
'''
Call this if fitsio supports reading .bz2 files directly.
'''
self.readBz2 = to
def __init__(self, **kwargs):
'''
Useful kwargs:
basedir : (string) - local directory where data will be stored.
'''
DR7.__init__(self, **kwargs)
self.unzip_dir = None
self.readBz2 = False
# Local filenames
self.filenames.update({
'frame': 'frame-%(band)s-%(run)06i-%(camcol)i-%(field)04i.fits.bz2',
'idR': 'idR-%(run)06i-%(band)s-%(camcol)i-%(field)04i.fits',
'photoObj': 'photoObj-%(run)06i-%(camcol)i-%(field)04i.fits',
'photoField': 'photoField-%(run)06i-%(camcol)i.fits',
'window_flist': 'window_flist.fits',
})
# URLs on DAS server
self.dasurl = 'http://data.sdss3.org/sas/dr8/groups/boss/'
self.daspaths = {
'idR': 'photo/data/%(run)i/fields/%(camcol)i/idR-%(run)06i-%(band)s%(camcol)i-%(field)04i.fit.Z',
'fpObjc': 'photo/redux/%(rerun)s/%(run)i/objcs/%(camcol)i/fpObjc-%(run)06i-%(camcol)i-%(field)04i.fit',
# DR8 frames are no longer available on DAS.
'frame': '/sas/dr9/boss/photoObj/frames/%(rerun)s/%(run)i/%(camcol)i/frame-%(band)s-%(run)06i-%(camcol)i-%(field)04i.fits.bz2',
#'frame': 'photoObj/frames/%(rerun)s/%(run)i/%(camcol)i/frame-%(band)s-%(run)06i-%(camcol)i-%(field)04i.fits.bz2',
'photoObj': 'photoObj/%(rerun)s/%(run)i/%(camcol)i/photoObj-%(run)06i-%(camcol)i-%(field)04i.fits',
'psField': 'photo/redux/%(rerun)s/%(run)i/objcs/%(camcol)i/psField-%(run)06i-%(camcol)i-%(field)04i.fit',
'photoField': 'photoObj/%(rerun)s/%(run)i/photoField-%(run)06i-%(camcol)i.fits',
'fpM': 'photo/redux/%(rerun)s/%(run)i/objcs/%(camcol)i/fpM-%(run)06i-%(band)s%(camcol)i-%(field)04i.fit.gz',
'fpAtlas': 'photo/redux/%(rerun)s/%(run)i/objcs/%(camcol)i/fpAtlas-%(run)06i-%(camcol)i-%(field)04i.fit',
'window_flist': 'resolve/2010-05-23/window_flist.fits',
}
self.dassuffix = {
#'frame': '.bz2',
'fpM': '.gz',
'idR': '.Z',
}
# called in retrieve()
self.processcmds = {
'fpM': 'gunzip -cd %(input)s > %(output)s',
'idR': 'gunzip -cd %(input)s > %(output)s',
}
self.postprocesscmds = {
'frame': 'TMPFILE=$(mktemp %(output)s.tmp.XXXXXX) && bunzip2 -cd %(input)s > $TMPFILE && mv $TMPFILE %(output)s',
}
y = read_yanny(self._get_runlist_filename())
y = y['RUNDATA']
rl = runlist()
rl.run = np.array(y['run'])
rl.startfield = np.array(y['startfield'])
rl.endfield = np.array(y['endfield'])
rl.rerun = np.array(y['rerun'])
#print 'Rerun type:', type(rl.rerun), rl.rerun.dtype
self.runlist = rl
self.logger = logging.getLogger('astrometry.sdss.DR%i' %
self.getDRNumber())
#self.logger.debug('debug test')
#self.logger.info('info test')
#self.logger.warning('warning test')
def _unzip_frame(self, fn, run, camcol):
if self.readBz2:
return None,True
# No, PJM reported that pyfits failed on SDSS frame*.bz2 files
# if not fitsio:
# # pyfits can read .bz2
# return None,True
tempfn = None
keep = False
filetype = 'frame'
if not(filetype in self.postprocesscmds and fn.endswith('.bz2')):
return None,True
cmd = self.postprocesscmds[filetype]
if self.unzip_dir is not None:
udir = os.path.join(self.unzip_dir, '%i' % run, '%i' % camcol)
if not os.path.exists(udir):
try:
os.makedirs(udir)
except:
pass
tempfn = os.path.join(udir, os.path.basename(fn).replace('.bz2', ''))
#print 'Checking', tempfn
if os.path.exists(tempfn):
print('File exists:', tempfn)
return tempfn,True
else:
print('Saving to', tempfn)
keep = True
else:
fid,tempfn = tempfile.mkstemp()
os.close(fid)
cmd = cmd % dict(input = fn, output = tempfn)
self.logger.debug('cmd: %s' % cmd)
print('command:', cmd)
(rtn,out,err) = run_command(cmd)
if rtn:
print('Command failed: command', cmd)
print('Output:', out)
print('Error:', err)
print('Return val:', rtn)
raise RuntimeError('Command failed (return val %i): %s' % (rtn, cmd))
print(out)
print(err)
return tempfn,keep
def _get_runlist_filename(self):
return self._get_data_file('runList-dr8.par')
# read a data file describing the DR8 data
def _get_data_file(self, fn):
return os.path.join(os.path.dirname(__file__), fn)
def get_rerun(self, run, field=None):
I = (self.runlist.run == run)
if field is not None:
I *= (self.runlist.startfield <= field) * (self.runlist.endfield >= field)
I = np.flatnonzero(I)
reruns = np.unique(self.runlist.rerun[I])
#print 'Run', run, '-> reruns:', reruns
if len(reruns) == 0:
return None
return reruns[-1]
def get_url(self, filetype, run, camcol, field, band=None, rerun=None):
if rerun is None:
rerun = self.get_rerun(run, field)
path = self.daspaths[filetype]
url = urljoin(self.dasurl, path % dict(
run=run, camcol=camcol, field=field, rerun=rerun, band=band))
return url
def retrieve(self, filetype, run, camcol, field=None, band=None, skipExisting=True,
tempsuffix='.tmp', rerun=None):
outfn = self.getPath(filetype, run, camcol, field, band,
rerun=rerun)
print('Checking for file', outfn)
if outfn is None:
return None
if skipExisting and os.path.exists(outfn):
#print('Exists')
return outfn
outdir = os.path.dirname(outfn)
if not os.path.exists(outdir):
try:
os.makedirs(outdir)
except:
pass
url = self.get_url(filetype, run, camcol, field, band=band, rerun=rerun)
#print 'Did not find file:', outfn
print('Retrieving from URL:', url)
if self.curl:
cmd = "curl -o '%(outfn)s' '%(url)s'"
else:
cmd = "wget --continue -nv -O %(outfn)s '%(url)s'"
# suffix to add to the downloaded filename
suff = self.dassuffix.get(filetype, '')
oo = outfn + suff
if tempsuffix is not None:
oo += tempsuffix
cmd = cmd % dict(outfn=oo, url=url)
self.logger.debug('cmd: %s' % cmd)
(rtn,out,err) = run_command(cmd)
if rtn:
print('Command failed: command', cmd)
print('Output:', out)
print('Error:', err)
print('Return val:', rtn)
return None
if tempsuffix is not None:
#
self.logger.debug('Renaming %s to %s' % (oo, outfn+suff))
os.rename(oo, outfn + suff)
if filetype in self.processcmds:
cmd = self.processcmds[filetype]
cmd = cmd % dict(input = outfn + suff, output = outfn)
self.logger.debug('cmd: %s' % cmd)
(rtn,out,err) = run_command(cmd)
if rtn:
print('Command failed: command', cmd)
print('Output:', out)
print('Error:', err)
print('Return val:', rtn)
return None
return outfn
def readPhotoObj(self, run, camcol, field, filename=None):
obj = PhotoObj(run, camcol, field)
if filename is None:
fn = self.getPath('photoObj', run, camcol, field)
else:
fn = filename
obj.table = fits_table(fn)
return obj
def readFrame(self, run, camcol, field, band, filename=None):
'''
http://data.sdss3.org/datamodel/files/BOSS_PHOTOOBJ/frames/RERUN/RUN/CAMCOL/frame.html
'''
f = Frame(run, camcol, field, band)
# ...
if filename is None:
fn = self.getPath('frame', run, camcol, field, band)
else:
fn = filename
# optionally bunzip2 the frame file.
tempfn,keep = self._unzip_frame(fn, run, camcol)
if tempfn is not None:
fn = tempfn
if fitsio:
print('Frame filename', fn)
# eg /clusterfs/riemann/raid006/dr10/boss/photoObj/frames/301/2825/1/frame-u-002825-1-0126.fits.bz2
F = fitsio.FITS(fn, lower=True)
f.header = F[0].read_header()
# Allow later reading of just the pixels of interest.
f.image_proxy = F[0]
f.calib = F[1].read()
sky = F[2].read_columns(['allsky', 'xinterp', 'yinterp'])
#print 'sky', type(sky)
# ... supposed to be a recarray, but it's not...
f.sky, f.skyxi, f.skyyi = sky.tolist()[0]
tab = fits_table(F[3].read())
if not keep and tempfn is not None:
os.remove(tempfn)
else:
p = pyfits.open(fn)
# in nanomaggies
f.image = p[0].data
f.header = p[0].header
# converts counts -> nanomaggies
f.calib = p[1].data
# table with val,x,y -- binned; use bilinear interpolation to expand
sky = p[2].data
# table -- asTrans structure
tab = fits_table(p[3].data)
f.sky = sky.field('allsky')[0]
f.skyxi = sky.field('xinterp')[0]
f.skyyi = sky.field('yinterp')[0]
#print 'sky shape', f.sky.shape
if len(f.sky.shape) != 2:
f.sky = f.sky.reshape((-1, 256))
assert(len(tab) == 1)
tab = tab[0]
# DR7 has NODE, INCL in radians...
f.astrans = AsTrans(run, camcol, field, band,
node=np.deg2rad(tab.node), incl=np.deg2rad(tab.incl),
astrans=tab, cut_to_band=False)
return f
|
[
"os.remove",
"os.close",
"os.path.join",
"numpy.round",
"numpy.unique",
"numpy.meshgrid",
"numpy.zeros_like",
"os.path.dirname",
"os.path.exists",
"numpy.log10",
"numpy.minimum",
"os.path.basename",
"os.rename",
"astropy.io.fits.open",
"astrometry.util.fits.fits_table",
"astrometry.util.run_command.run_command",
"numpy.log",
"tempfile.mkstemp",
"fitsio.FITS",
"os.makedirs",
"numpy.deg2rad",
"numpy.flatnonzero",
"numpy.array",
"numpy.sinh"
] |
[((4601, 4654), 'numpy.array', 'np.array', (['[1.4e-10, 9e-11, 1.2e-10, 1.8e-10, 7.4e-10]'], {}), '([1.4e-10, 9e-11, 1.2e-10, 1.8e-10, 7.4e-10])\n', (4609, 4654), True, 'import numpy as np\n'), ((4721, 4742), 'numpy.log', 'np.log', (['_lup_to_mag_b'], {}), '(_lup_to_mag_b)\n', (4727, 4742), True, 'import numpy as np\n'), ((2169, 2191), 'numpy.minimum', 'np.minimum', (['yi', '(sh - 1)'], {}), '(yi, sh - 1)\n', (2179, 2191), True, 'import numpy as np\n'), ((2484, 2506), 'numpy.minimum', 'np.minimum', (['yi', '(sh - 1)'], {}), '(yi, sh - 1)\n', (2494, 2506), True, 'import numpy as np\n'), ((2612, 2631), 'numpy.meshgrid', 'np.meshgrid', (['xi', 'yi'], {}), '(xi, yi)\n', (2623, 2631), True, 'import numpy as np\n'), ((10059, 10077), 'numpy.array', 'np.array', (["y['run']"], {}), "(y['run'])\n", (10067, 10077), True, 'import numpy as np\n'), ((10102, 10127), 'numpy.array', 'np.array', (["y['startfield']"], {}), "(y['startfield'])\n", (10110, 10127), True, 'import numpy as np\n'), ((10150, 10173), 'numpy.array', 'np.array', (["y['endfield']"], {}), "(y['endfield'])\n", (10158, 10173), True, 'import numpy as np\n'), ((10193, 10213), 'numpy.array', 'np.array', (["y['rerun']"], {}), "(y['rerun'])\n", (10201, 10213), True, 'import numpy as np\n'), ((11875, 11891), 'astrometry.util.run_command.run_command', 'run_command', (['cmd'], {}), '(cmd)\n', (11886, 11891), False, 'from astrometry.util.run_command import run_command\n'), ((12673, 12690), 'numpy.flatnonzero', 'np.flatnonzero', (['I'], {}), '(I)\n', (12687, 12690), True, 'import numpy as np\n'), ((12708, 12740), 'numpy.unique', 'np.unique', (['self.runlist.rerun[I]'], {}), '(self.runlist.rerun[I])\n', (12717, 12740), True, 'import numpy as np\n'), ((13662, 13684), 'os.path.dirname', 'os.path.dirname', (['outfn'], {}), '(outfn)\n', (13677, 13684), False, 'import os\n'), ((14445, 14461), 'astrometry.util.run_command.run_command', 'run_command', (['cmd'], {}), '(cmd)\n', (14456, 14461), False, 'from astrometry.util.run_command import run_command\n'), ((15562, 15576), 'astrometry.util.fits.fits_table', 'fits_table', (['fn'], {}), '(fn)\n', (15572, 15576), False, 'from astrometry.util.fits import fits_table\n'), ((5435, 5477), 'numpy.sinh', 'np.sinh', (['(Lmag / -1.0857362047581294 - lnbi)'], {}), '(Lmag / -1.0857362047581294 - lnbi)\n', (5442, 5477), True, 'import numpy as np\n'), ((5529, 5545), 'numpy.zeros_like', 'np.zeros_like', (['f'], {}), '(f)\n', (5542, 5545), True, 'import numpy as np\n'), ((5599, 5613), 'numpy.log10', 'np.log10', (['f[I]'], {}), '(f[I])\n', (5607, 5613), True, 'import numpy as np\n'), ((11103, 11158), 'os.path.join', 'os.path.join', (['self.unzip_dir', "('%i' % run)", "('%i' % camcol)"], {}), "(self.unzip_dir, '%i' % run, '%i' % camcol)\n", (11115, 11158), False, 'import os\n'), ((11443, 11465), 'os.path.exists', 'os.path.exists', (['tempfn'], {}), '(tempfn)\n', (11457, 11465), False, 'import os\n'), ((11677, 11695), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {}), '()\n', (11693, 11695), False, 'import tempfile\n'), ((11708, 11721), 'os.close', 'os.close', (['fid'], {}), '(fid)\n', (11716, 11721), False, 'import os\n'), ((12432, 12457), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (12447, 12457), False, 'import os\n'), ((13568, 13589), 'os.path.exists', 'os.path.exists', (['outfn'], {}), '(outfn)\n', (13582, 13589), False, 'import os\n'), ((13700, 13722), 'os.path.exists', 'os.path.exists', (['outdir'], {}), '(outdir)\n', (13714, 13722), False, 'import os\n'), ((14789, 14816), 'os.rename', 'os.rename', (['oo', '(outfn + suff)'], {}), '(oo, outfn + suff)\n', (14798, 14816), False, 'import os\n'), ((15046, 15062), 'astrometry.util.run_command.run_command', 'run_command', (['cmd'], {}), '(cmd)\n', (15057, 15062), False, 'from astrometry.util.run_command import run_command\n'), ((16322, 16349), 'fitsio.FITS', 'fitsio.FITS', (['fn'], {'lower': '(True)'}), '(fn, lower=True)\n', (16333, 16349), False, 'import fitsio\n'), ((16901, 16916), 'astropy.io.fits.open', 'pyfits.open', (['fn'], {}), '(fn)\n', (16912, 16916), True, 'from astropy.io import fits as pyfits\n'), ((17258, 17279), 'astrometry.util.fits.fits_table', 'fits_table', (['p[3].data'], {}), '(p[3].data)\n', (17268, 17279), False, 'from astrometry.util.fits import fits_table\n'), ((2071, 2094), 'numpy.round', 'np.round', (['self.skyxi[x]'], {}), '(self.skyxi[x])\n', (2079, 2094), True, 'import numpy as np\n'), ((2120, 2143), 'numpy.round', 'np.round', (['self.skyyi[y]'], {}), '(self.skyyi[y])\n', (2128, 2143), True, 'import numpy as np\n'), ((2392, 2412), 'numpy.round', 'np.round', (['self.skyxi'], {}), '(self.skyxi)\n', (2400, 2412), True, 'import numpy as np\n'), ((2438, 2458), 'numpy.round', 'np.round', (['self.skyyi'], {}), '(self.skyyi)\n', (2446, 2458), True, 'import numpy as np\n'), ((5707, 5721), 'numpy.log10', 'np.log10', (['nmgy'], {}), '(nmgy)\n', (5715, 5721), True, 'import numpy as np\n'), ((6091, 6206), 'os.path.join', 'os.path.join', (['photoObjs', '"""%(rerun)s"""', '"""%(run)i"""', '"""%(camcol)i"""', '"""photoObj-%(run)06i-%(camcol)i-%(field)04i.fits"""'], {}), "(photoObjs, '%(rerun)s', '%(run)i', '%(camcol)i',\n 'photoObj-%(run)06i-%(camcol)i-%(field)04i.fits')\n", (6103, 6206), False, 'import os\n'), ((6260, 6395), 'os.path.join', 'os.path.join', (['photoObjs', '"""frames"""', '"""%(rerun)s"""', '"""%(run)i"""', '"""%(camcol)i"""', '"""frame-%(band)s-%(run)06i-%(camcol)i-%(field)04i.fits.bz2"""'], {}), "(photoObjs, 'frames', '%(rerun)s', '%(run)i', '%(camcol)i',\n 'frame-%(band)s-%(run)06i-%(camcol)i-%(field)04i.fits.bz2')\n", (6272, 6395), False, 'import os\n'), ((6454, 6545), 'os.path.join', 'os.path.join', (['photoObjs', '"""%(rerun)s"""', '"""%(run)i"""', '"""photoField-%(run)06i-%(camcol)i.fits"""'], {}), "(photoObjs, '%(rerun)s', '%(run)i',\n 'photoField-%(run)06i-%(camcol)i.fits')\n", (6466, 6545), False, 'import os\n'), ((6603, 6721), 'os.path.join', 'os.path.join', (['redux', '"""%(rerun)s"""', '"""%(run)i"""', '"""objcs"""', '"""%(camcol)i"""', '"""psField-%(run)06i-%(camcol)i-%(field)04i.fit"""'], {}), "(redux, '%(rerun)s', '%(run)i', 'objcs', '%(camcol)i',\n 'psField-%(run)06i-%(camcol)i-%(field)04i.fit')\n", (6615, 6721), False, 'import os\n'), ((6772, 6897), 'os.path.join', 'os.path.join', (['redux', '"""%(rerun)s"""', '"""%(run)i"""', '"""objcs"""', '"""%(camcol)i"""', '"""fpM-%(run)06i-%(band)s%(camcol)i-%(field)04i.fit.gz"""'], {}), "(redux, '%(rerun)s', '%(run)i', 'objcs', '%(camcol)i',\n 'fpM-%(run)06i-%(band)s%(camcol)i-%(field)04i.fit.gz')\n", (6784, 6897), False, 'import os\n'), ((6953, 6995), 'os.path.join', 'os.path.join', (['resolve', '"""window_flist.fits"""'], {}), "(resolve, 'window_flist.fits')\n", (6965, 6995), False, 'import os\n'), ((11178, 11198), 'os.path.exists', 'os.path.exists', (['udir'], {}), '(udir)\n', (11192, 11198), False, 'import os\n'), ((13757, 13776), 'os.makedirs', 'os.makedirs', (['outdir'], {}), '(outdir)\n', (13768, 13776), False, 'import os\n'), ((16852, 16869), 'os.remove', 'os.remove', (['tempfn'], {}), '(tempfn)\n', (16861, 16869), False, 'import os\n'), ((17717, 17737), 'numpy.deg2rad', 'np.deg2rad', (['tab.node'], {}), '(tab.node)\n', (17727, 17737), True, 'import numpy as np\n'), ((17744, 17764), 'numpy.deg2rad', 'np.deg2rad', (['tab.incl'], {}), '(tab.incl)\n', (17754, 17764), True, 'import numpy as np\n'), ((11241, 11258), 'os.makedirs', 'os.makedirs', (['udir'], {}), '(udir)\n', (11252, 11258), False, 'import os\n'), ((11348, 11368), 'os.path.basename', 'os.path.basename', (['fn'], {}), '(fn)\n', (11364, 11368), False, 'import os\n')]
|
import base64
import json
import sys
import wave
from flask import Flask, jsonify, request
from flask_cors import CORS
import parselmouth
import pandas as pd
from scipy.signal import find_peaks
import numpy as np
import matplotlib.pyplot as plt
app = Flask(__name__)
app_config = {"host": "0.0.0.0", "port": sys.argv[1]}
"""
---------------------- DEVELOPER MODE CONFIG -----------------------
"""
# Developer mode uses app.py
if "app.py" in sys.argv[0]:
# Update app config
app_config["debug"] = True
# CORS settings
cors = CORS(app, resource={
r"/*":{
"origins":"*"
}
})
# CORS headers
app.config["CORS_HEADERS"] = "Content-Type"
"""
--------------------------- REST CALLS -----------------------------
"""
def draw_pitch(pitch):
# Extract selected pitch contour, and
# replace unvoiced samples by NaN to not plot
pitch_values = pitch.selected_array['frequency']
pitch_values[pitch_values==0] = np.nan
plt.plot(pitch.xs(), pitch_values, 'o', markersize=5, color='w')
plt.plot(pitch.xs(), pitch_values, 'o', markersize=2)
plt.grid(False)
plt.ylim(0, pitch.ceiling)
plt.ylabel("fundamental frequency [Hz]")
# Remove and replace with your own
@app.route("/example",methods=['GET','POST'])
def example():
print(request.json)
data=request.get_json()
snd = parselmouth.Sound(data['filepath'])
pitch = snd.to_pitch()
plt.figure()
plt.twinx()
x=pitch.xs()
y=pitch.selected_array['frequency']
dataPoints=[]
for i in range(len(y)):
if(y[i]!=0):
dataPoints.append({"x":x[i],"y":y[i]})
print(dataPoints)
draw_pitch(pitch)
plt.xlim([snd.xmin, snd.xmax])
name="image1.png"
plt.savefig(name)
data=""
with open("image1.png", "rb") as image_file:
data = format(base64.b64encode(image_file.read()))
# See /src/components/App.js for frontend call
return {"dataPoints":dataPoints}
@app.route("/wavepattern",methods=['GET','POST'])
def wavepattern():
data=request.get_json()
snd = parselmouth.Sound(data['filepath'])
pitch = snd.to_pitch()
plt.figure()
plt.twinx()
path = data['filepath']
raw = wave.open(path)
signal = raw.readframes(-1)
signal = np.frombuffer(signal, dtype ="int16")
f_rate = raw.getframerate()
time = np.linspace(
0,
len(signal) / f_rate,
num = len(signal)
)
dataPoints=[]
cnt=0
cur_x=0
cur_y=0
for i in range(len(signal)):
if i%100==0:
dataPoints.append({"x":cur_x/100,"y":cur_y/100})
cur_x=0
cur_y=0
else:
cur_x+=float(time[i])
cur_y+=float(signal[i])
plt.ylabel("fundamental frequency [Hz]")
plt.plot(time, signal,color="red")
# plt.xlim([snd.xmin, snd.xmax])
name="image2.png"
plt.savefig(name)
data=""
with open("image2.png", "rb") as image_file:
data = format(base64.b64encode(image_file.read()))
# See /src/components/App.js for frontend call
# print(dataPoints)
return jsonify({"dataPoints":dataPoints})
def differentitate_pitch(pitch,pitch2,pitch_values1,pitch_values2,s1,s2):
# Extract selected pitch contour, and
# replace unvoiced samples by NaN to not plot
if s1>s2:
pitch_values1=pitch_values1[:s2]
if s1<s2:
pitch_values2=pitch_values2[:s1]
cnt = 0
p = np.empty((pitch_values1.size))
for i in range(0,pitch_values1.size):
p[i]=np.nan
for i in range(0,pitch_values1.size):
if abs(pitch_values1[i]-pitch_values2[i])>50:
#print(pitch_values2[i])
p[i]=pitch_values2[i]
cnt += 1
# print(cnt)
# print(p)
#plt.plot(pitch2.xs(), pitch_values2, 'o', markersize=5, color='w',label='differences')
#plt.plot(pitch2.xs(), pitch_values2, 'o', markersize=2)
if s1>s2:
plt.plot(pitch2.xs(), pitch_values2, 'o', markersize=5, color='w',label='differences')
plt.plot(pitch2.xs(), pitch_values2, 'o', markersize=2)
plt.plot(pitch2.xs(), p, 'o', markersize=5, color='w',label='normal')
plt.plot(pitch2.xs(), p, 'o', markersize=2)
#draw_pitch(pitch)
if s1<s2:
plt.plot(pitch.xs(), pitch_values1, 'o', markersize=5, color='w',label='differences')
plt.plot(pitch.xs(), pitch_values1, 'o', markersize=2)
plt.plot(pitch.xs(), p, 'o', markersize=5, color='w',label='normal')
plt.plot(pitch.xs(), p, 'o', markersize=2)
#draw_pitch(pitch2)
plt.grid(False)
plt.ylim(0, pitch.ceiling)
plt.ylabel("fundamental frequency [Hz]")
@app.route("/speechpattern",methods=['GET','POST'])
def speechpattern():
data=request.get_json()
snd = parselmouth.Sound(data['filepath1'])
pitch = snd.to_pitch()
snd2 = parselmouth.Sound(data['filepath2'])
pitch2 = snd2.to_pitch()
pitch_values1 = pitch.selected_array['frequency']
pitch_values1[pitch_values1==0] = np.nan
pitch_values2 = pitch2.selected_array['frequency']
pitch_values2[pitch_values2==0] = np.nan
s1=pitch_values1.size
s2=pitch_values2.size
if s1>s2:
draw_pitch(pitch)
differentitate_pitch(pitch,pitch2,pitch_values1,pitch_values2,s1,s2)
if s1<s2:
draw_pitch(pitch2)
plt.xlim([snd2.xmin-0.2, snd2.xmax+0.2])
name="image3.png"
plt.savefig(name)
data=""
with open("image3.png", "rb") as image_file:
data = format(base64.b64encode(image_file.read()))
# See /src/components/App.js for frontend call
return jsonify({"imagename":data[2:-1]})
@app.route("/highlight",methods=['GET','POST'])
def highlight():
data=request.get_json()
snd = parselmouth.Sound(data['filepath'])
pitch = snd.to_pitch()
plt.figure()
plt.twinx()
pitch_values = pitch.selected_array['frequency']
x=pitch.xs()
y=pitch.selected_array['frequency']
dataPoints=[]
for i in range(len(y)):
if(y[i]!=0):
dataPoints.append({"x":x[i],"y":y[i]})
s = pitch_values.size
p = np.empty(s)
for i in range(s-15):
flag = 0
for j in range(0,15):
if abs(pitch_values[i]-pitch_values[i+j])>5:
flag=1
if flag == 0:
for j in range(0,15):
p[i+j]=pitch_values[i+j]
pitch_values[pitch_values==0] = np.nan
dataPoints2=[]
x=pitch.xs()
y=p
for i in range(len(y)):
if(y[i]!=0):
dataPoints2.append({"x":x[i],"y":y[i]})
p[p==0] = np.nan
plt.plot(pitch.xs(), pitch_values, 'o', markersize=5, color='w')
plt.plot(pitch.xs(), pitch_values, 'o', markersize=2)
plt.plot(pitch.xs(), p, 'o', markersize=5, color='w')
plt.plot(pitch.xs(), p, 'o', markersize=2)
plt.grid(False)
plt.ylim(0, pitch.ceiling)
plt.ylabel("fundamental frequency [Hz]")
plt.xlim([snd.xmin-0.2, snd.xmax+0.2])
name="image4.png"
plt.savefig(name)
data=""
with open("image4.png", "rb") as image_file:
data = format(base64.b64encode(image_file.read()))
# See /src/components/App.js for frontend call
return jsonify({"normal":dataPoints,"highlight":dataPoints2})
"""
-------------------------- APP SERVICES ----------------------------
"""
# Quits Flask on Electron exit
@app.route("/quit")
def quit():
shutdown = request.environ.get("werkzeug.server.shutdown")
shutdown()
return
if __name__ == "__main__":
app.run(**app_config)
|
[
"matplotlib.pyplot.xlim",
"wave.open",
"parselmouth.Sound",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"flask_cors.CORS",
"matplotlib.pyplot.twinx",
"numpy.frombuffer",
"flask.Flask",
"numpy.empty",
"flask.request.environ.get",
"matplotlib.pyplot.figure",
"flask.jsonify",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.grid",
"flask.request.get_json",
"matplotlib.pyplot.savefig"
] |
[((253, 268), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (258, 268), False, 'from flask import Flask, jsonify, request\n'), ((537, 581), 'flask_cors.CORS', 'CORS', (['app'], {'resource': "{'/*': {'origins': '*'}}"}), "(app, resource={'/*': {'origins': '*'}})\n", (541, 581), False, 'from flask_cors import CORS\n'), ((1086, 1101), 'matplotlib.pyplot.grid', 'plt.grid', (['(False)'], {}), '(False)\n', (1094, 1101), True, 'import matplotlib.pyplot as plt\n'), ((1106, 1132), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', 'pitch.ceiling'], {}), '(0, pitch.ceiling)\n', (1114, 1132), True, 'import matplotlib.pyplot as plt\n'), ((1137, 1177), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fundamental frequency [Hz]"""'], {}), "('fundamental frequency [Hz]')\n", (1147, 1177), True, 'import matplotlib.pyplot as plt\n'), ((1308, 1326), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (1324, 1326), False, 'from flask import Flask, jsonify, request\n'), ((1335, 1370), 'parselmouth.Sound', 'parselmouth.Sound', (["data['filepath']"], {}), "(data['filepath'])\n", (1352, 1370), False, 'import parselmouth\n'), ((1398, 1410), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1408, 1410), True, 'import matplotlib.pyplot as plt\n'), ((1413, 1424), 'matplotlib.pyplot.twinx', 'plt.twinx', ([], {}), '()\n', (1422, 1424), True, 'import matplotlib.pyplot as plt\n'), ((1624, 1654), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[snd.xmin, snd.xmax]'], {}), '([snd.xmin, snd.xmax])\n', (1632, 1654), True, 'import matplotlib.pyplot as plt\n'), ((1678, 1695), 'matplotlib.pyplot.savefig', 'plt.savefig', (['name'], {}), '(name)\n', (1689, 1695), True, 'import matplotlib.pyplot as plt\n'), ((1977, 1995), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (1993, 1995), False, 'from flask import Flask, jsonify, request\n'), ((2004, 2039), 'parselmouth.Sound', 'parselmouth.Sound', (["data['filepath']"], {}), "(data['filepath'])\n", (2021, 2039), False, 'import parselmouth\n'), ((2067, 2079), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2077, 2079), True, 'import matplotlib.pyplot as plt\n'), ((2082, 2093), 'matplotlib.pyplot.twinx', 'plt.twinx', ([], {}), '()\n', (2091, 2093), True, 'import matplotlib.pyplot as plt\n'), ((2129, 2144), 'wave.open', 'wave.open', (['path'], {}), '(path)\n', (2138, 2144), False, 'import wave\n'), ((2189, 2225), 'numpy.frombuffer', 'np.frombuffer', (['signal'], {'dtype': '"""int16"""'}), "(signal, dtype='int16')\n", (2202, 2225), True, 'import numpy as np\n'), ((2597, 2637), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fundamental frequency [Hz]"""'], {}), "('fundamental frequency [Hz]')\n", (2607, 2637), True, 'import matplotlib.pyplot as plt\n'), ((2640, 2675), 'matplotlib.pyplot.plot', 'plt.plot', (['time', 'signal'], {'color': '"""red"""'}), "(time, signal, color='red')\n", (2648, 2675), True, 'import matplotlib.pyplot as plt\n'), ((2737, 2754), 'matplotlib.pyplot.savefig', 'plt.savefig', (['name'], {}), '(name)\n', (2748, 2754), True, 'import matplotlib.pyplot as plt\n'), ((2947, 2982), 'flask.jsonify', 'jsonify', (["{'dataPoints': dataPoints}"], {}), "({'dataPoints': dataPoints})\n", (2954, 2982), False, 'from flask import Flask, jsonify, request\n'), ((3262, 3290), 'numpy.empty', 'np.empty', (['pitch_values1.size'], {}), '(pitch_values1.size)\n', (3270, 3290), True, 'import numpy as np\n'), ((4308, 4323), 'matplotlib.pyplot.grid', 'plt.grid', (['(False)'], {}), '(False)\n', (4316, 4323), True, 'import matplotlib.pyplot as plt\n'), ((4326, 4352), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', 'pitch.ceiling'], {}), '(0, pitch.ceiling)\n', (4334, 4352), True, 'import matplotlib.pyplot as plt\n'), ((4355, 4395), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fundamental frequency [Hz]"""'], {}), "('fundamental frequency [Hz]')\n", (4365, 4395), True, 'import matplotlib.pyplot as plt\n'), ((4478, 4496), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (4494, 4496), False, 'from flask import Flask, jsonify, request\n'), ((4505, 4541), 'parselmouth.Sound', 'parselmouth.Sound', (["data['filepath1']"], {}), "(data['filepath1'])\n", (4522, 4541), False, 'import parselmouth\n'), ((4576, 4612), 'parselmouth.Sound', 'parselmouth.Sound', (["data['filepath2']"], {}), "(data['filepath2'])\n", (4593, 4612), False, 'import parselmouth\n'), ((5022, 5066), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[snd2.xmin - 0.2, snd2.xmax + 0.2]'], {}), '([snd2.xmin - 0.2, snd2.xmax + 0.2])\n', (5030, 5066), True, 'import matplotlib.pyplot as plt\n'), ((5093, 5110), 'matplotlib.pyplot.savefig', 'plt.savefig', (['name'], {}), '(name)\n', (5104, 5110), True, 'import matplotlib.pyplot as plt\n'), ((5284, 5318), 'flask.jsonify', 'jsonify', (["{'imagename': data[2:-1]}"], {}), "({'imagename': data[2:-1]})\n", (5291, 5318), False, 'from flask import Flask, jsonify, request\n'), ((5393, 5411), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (5409, 5411), False, 'from flask import Flask, jsonify, request\n'), ((5420, 5455), 'parselmouth.Sound', 'parselmouth.Sound', (["data['filepath']"], {}), "(data['filepath'])\n", (5437, 5455), False, 'import parselmouth\n'), ((5483, 5495), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5493, 5495), True, 'import matplotlib.pyplot as plt\n'), ((5498, 5509), 'matplotlib.pyplot.twinx', 'plt.twinx', ([], {}), '()\n', (5507, 5509), True, 'import matplotlib.pyplot as plt\n'), ((5754, 5765), 'numpy.empty', 'np.empty', (['s'], {}), '(s)\n', (5762, 5765), True, 'import numpy as np\n'), ((6394, 6409), 'matplotlib.pyplot.grid', 'plt.grid', (['(False)'], {}), '(False)\n', (6402, 6409), True, 'import matplotlib.pyplot as plt\n'), ((6412, 6438), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', 'pitch.ceiling'], {}), '(0, pitch.ceiling)\n', (6420, 6438), True, 'import matplotlib.pyplot as plt\n'), ((6441, 6481), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""fundamental frequency [Hz]"""'], {}), "('fundamental frequency [Hz]')\n", (6451, 6481), True, 'import matplotlib.pyplot as plt\n'), ((6487, 6529), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[snd.xmin - 0.2, snd.xmax + 0.2]'], {}), '([snd.xmin - 0.2, snd.xmax + 0.2])\n', (6495, 6529), True, 'import matplotlib.pyplot as plt\n'), ((6549, 6566), 'matplotlib.pyplot.savefig', 'plt.savefig', (['name'], {}), '(name)\n', (6560, 6566), True, 'import matplotlib.pyplot as plt\n'), ((6740, 6797), 'flask.jsonify', 'jsonify', (["{'normal': dataPoints, 'highlight': dataPoints2}"], {}), "({'normal': dataPoints, 'highlight': dataPoints2})\n", (6747, 6797), False, 'from flask import Flask, jsonify, request\n'), ((6952, 6999), 'flask.request.environ.get', 'request.environ.get', (['"""werkzeug.server.shutdown"""'], {}), "('werkzeug.server.shutdown')\n", (6971, 6999), False, 'from flask import Flask, jsonify, request\n')]
|
# Lint as: python2, python3
# Copyright 2019 The TensorFlow Authors. 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.
# ==============================================================================
r"""Read saved Decoder's outputs and convert to KITTI text format.
First, obtain a KITTI camera calibration file.
To export all detections from a single model:
python export_kitti_detection.py \
--decoder_path=/path/to/decoder_out_000103000 \
--calib_file=/tmp/kitti_test_calibs.npz \
--output_dir=/tmp/my-kitti-export-directory \
--logtostderr
--- OR ---
Export combined detections selected from multiple models:
python export_kitti_detection.py \
--car_decoder_path=/path/to/car_decoder_out \
--ped_decoder_path=/path/to/ped_decoder_out \
--cyc_decoder_path=/path/to/cyc_decoder_out \
--calib_file=/tmp/kitti_test_calibs.npz \
--output_dir=/tmp/my-kitti-export-directory \
--logtostderr
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import flags
from lingvo import compat as tf
from lingvo.core.ops import record_pb2
from lingvo.tasks.car import kitti_metadata
from lingvo.tasks.car.tools import kitti_data
import numpy as np
FLAGS = flags.FLAGS
flags.DEFINE_string(
"decoder_path", None, "Paths to decoder file containing output "
"of decoder for everything. Either supply this argument or individual "
"decoder paths for cars, pedestrians and cyclists.")
flags.DEFINE_string(
"car_decoder_path", None,
"Paths to decoder file containing output of decoder for cars."
"Either supply plus cyclists and pedestrians or supply one "
"decoder for all labels.")
flags.DEFINE_string(
"ped_decoder_path", None,
"Paths to decoder file containing output of decoder for "
"pedestrians. Either supply plus cyclists and cars or "
"supply one decoder for all labels.")
flags.DEFINE_string(
"cyc_decoder_path", None,
"Paths to decoder file containing output of decoder for cyclist. "
"Either supply plus cars and pedestrians or supply one "
"decoder for all labels.")
flags.DEFINE_string(
"calib_file", None,
"Path to a npz file that contains all calibration matrices.")
flags.DEFINE_string("output_dir", None, "Place to write detections.")
flags.DEFINE_float("score_threshold", 0, "Ignore detections with lower score.")
def LoadCalibData(fname):
"""Load and parse calibration data from NPZ file."""
# If this throws an error, make sure the npz file was generated from
# the same version of python as this binary.
npz = np.load(fname)
scene_to_calib = {}
for idx, scene_id in enumerate(npz["scene_id"]):
tf.logging.info("Processing %s", scene_id)
raw_calib = {}
raw_calib["P0"] = npz["P0"][idx]
raw_calib["P1"] = npz["P1"][idx]
raw_calib["P2"] = npz["P2"][idx]
raw_calib["P3"] = npz["P3"][idx]
raw_calib["R0_rect"] = npz["R0_rect"][idx]
raw_calib["Tr_velo_to_cam"] = npz["Tr_velo_to_cam"][idx]
raw_calib["Tr_imu_to_velo"] = npz["Tr_imu_to_velo"][idx]
calib = kitti_data.ParseCalibrationDict(raw_calib)
scene_to_calib[scene_id] = calib
return scene_to_calib
def ExtractNpContent(np_dict, calib):
"""Parse saved np arrays and convert 3D bboxes to camera0 coordinates.
Args:
np_dict: a dict of numpy arrays.
calib: a parsed calibration dictionary.
Returns:
A tuple of 6 ndarrays:
- location_camera: [N, 3]. [x, y, z] in camera0 coordinate.
- dimension_camera: [N, 3]. The [height, width, length] of objects.
- phi_camera: [N]. Rotation around y-axis in camera0 coodinate.
- bboxes_2d: [N, 4]. The corresponding 2D bboxes in the image coordinate.
- scores: [N]. Confidence scores for each box for the assigned class.
- class_ids: [N]. The class id assigned to each box.
"""
bboxes = np_dict["bboxes"]
scores = np_dict["scores"]
class_ids = np_dict["class_ids"]
bboxes_2d = np_dict["bboxes_2d"]
# Transform from velodyne coordinates to camera coordinates.
velo_to_cam_transform = kitti_data.VeloToCameraTransformation(calib)
location_cam = np.zeros((len(bboxes), 3))
dimension_cam = np.zeros((len(bboxes), 3))
rotation_cam = np.zeros((len(bboxes), 1))
for idx, bbox in enumerate(bboxes):
location_cam[idx, :], dimension_cam[idx, :], rotation_cam[idx, :] = (
kitti_data.BBox3DToKITTIObject(bbox, velo_to_cam_transform))
return location_cam, dimension_cam, rotation_cam, bboxes_2d, scores, class_ids
_INCLUDED_KITTI_CLASS_NAMES = ["Car", "Pedestrian", "Cyclist"]
def ExportKITTIDetection(out_dir, source_id, location_cam, dimension_cam,
rotation_cam, bboxes_2d, scores, class_name, is_first):
"""Write detections to a text file in KITTI format."""
tf.logging.info("Exporting %s for %s" % (class_name, source_id))
fname = out_dir + "/" + source_id + ".txt"
with tf.gfile.Open(fname, "a") as fid:
# Ensure we always create a file even when there's no detection.
# TODO(shlens): Test whether this is actually necessary on the KITTI
# eval server.
if is_first:
fid.write("")
for location, dimension, ry, bbox_2d, score in zip(
location_cam, dimension_cam, rotation_cam, bboxes_2d, scores):
if score < FLAGS.score_threshold:
continue
# class_name, truncated(ignore), alpha(ignore), bbox2D x 4
part1 = [class_name, -1, -1, -10] + list(bbox_2d)
# dimesion x 3, location x 3, rotation_y x 1, score x 1
fill = tuple(part1 + list(dimension) + list(location) + [ry] + [score])
kitti_format_string = ("%s %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf "
"%lf %lf %lf %lf")
kitti_line = kitti_format_string % fill
fid.write(kitti_line + "\n")
def main(argv):
if len(argv) > 1:
raise tf.app.UsageError("Too many command-line arguments.")
if FLAGS.decoder_path:
assert not FLAGS.car_decoder_path and not FLAGS.ped_decoder_path \
and not FLAGS.cyc_decoder_path, ("Either provide decoder_path or "
"individual decoders but not both.")
else:
assert FLAGS.car_decoder_path and FLAGS.ped_decoder_path and \
FLAGS.cyc_decoder_path, ("No decoder_path specified. Please supply all "
"individual decoder_paths for labels.")
is_single_decoder_file = FLAGS.decoder_path is not None
if is_single_decoder_file:
list_of_decoder_paths = [FLAGS.decoder_path]
else:
# Note the correspondence between _INCLUDED_KITTI_CLASS_NAMES ordering and
# this list.
list_of_decoder_paths = [
FLAGS.car_decoder_path, FLAGS.ped_decoder_path, FLAGS.cyc_decoder_path
]
# A list of dictionaries mapping img ids to a dictionary of numpy tensors.
table_data = []
img_ids = []
for table_path in list_of_decoder_paths:
img_id_dict = {}
for serialized in tf.io.tf_record_iterator(table_path):
record = record_pb2.Record()
record.ParseFromString(serialized)
img_id = str(tf.make_ndarray(record.fields["img_id"]))
img_ids.append(img_id)
np_dict = {k: tf.make_ndarray(v) for k, v in record.fields.items()}
img_id_dict[img_id] = np_dict
table_data.append(img_id_dict)
img_ids = list(set(img_ids))
if not tf.gfile.Exists(FLAGS.output_dir):
tf.gfile.MkDir(FLAGS.output_dir)
all_kitti_class_names = kitti_metadata.KITTIMetadata().ClassNames()
calib_data = LoadCalibData(tf.gfile.Open(FLAGS.calib_file, "rb"))
count = 0
for img_id in img_ids:
# Ignore padded samples where the img_ids are empty.
if not img_id:
continue
for table_index, img_id_dict in enumerate(table_data):
if img_id in img_id_dict:
np_dict = img_id_dict[img_id]
(location_cam, dimension_cam, rotation_cam, bboxes_2d, scores,
class_ids) = ExtractNpContent(np_dict, calib_data[img_id + ".txt"])
if is_single_decoder_file:
valid_labels = _INCLUDED_KITTI_CLASS_NAMES
else:
valid_labels = [_INCLUDED_KITTI_CLASS_NAMES[table_index]]
is_first = table_index == 0
for class_name in valid_labels:
class_mask = (class_ids == all_kitti_class_names.index(class_name))
ExportKITTIDetection(FLAGS.output_dir, img_id,
location_cam[class_mask],
dimension_cam[class_mask],
rotation_cam[class_mask], bboxes_2d[class_mask],
scores[class_mask], class_name, is_first)
count += 1
tf.logging.info("Total example exported: %d", count)
if __name__ == "__main__":
tf.app.run(main)
|
[
"lingvo.tasks.car.kitti_metadata.KITTIMetadata",
"lingvo.compat.gfile.Open",
"numpy.load",
"lingvo.compat.gfile.MkDir",
"lingvo.tasks.car.tools.kitti_data.VeloToCameraTransformation",
"lingvo.compat.app.run",
"lingvo.compat.gfile.Exists",
"absl.flags.DEFINE_string",
"lingvo.compat.logging.info",
"absl.flags.DEFINE_float",
"lingvo.compat.io.tf_record_iterator",
"lingvo.compat.app.UsageError",
"lingvo.core.ops.record_pb2.Record",
"lingvo.compat.make_ndarray",
"lingvo.tasks.car.tools.kitti_data.ParseCalibrationDict",
"lingvo.tasks.car.tools.kitti_data.BBox3DToKITTIObject"
] |
[((1752, 1964), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""decoder_path"""', 'None', '"""Paths to decoder file containing output of decoder for everything. Either supply this argument or individual decoder paths for cars, pedestrians and cyclists."""'], {}), "('decoder_path', None,\n 'Paths to decoder file containing output of decoder for everything. Either supply this argument or individual decoder paths for cars, pedestrians and cyclists.'\n )\n", (1771, 1964), False, 'from absl import flags\n'), ((1975, 2174), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""car_decoder_path"""', 'None', '"""Paths to decoder file containing output of decoder for cars.Either supply plus cyclists and pedestrians or supply one decoder for all labels."""'], {}), "('car_decoder_path', None,\n 'Paths to decoder file containing output of decoder for cars.Either supply plus cyclists and pedestrians or supply one decoder for all labels.'\n )\n", (1994, 2174), False, 'from absl import flags\n'), ((2189, 2389), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""ped_decoder_path"""', 'None', '"""Paths to decoder file containing output of decoder for pedestrians. Either supply plus cyclists and cars or supply one decoder for all labels."""'], {}), "('ped_decoder_path', None,\n 'Paths to decoder file containing output of decoder for pedestrians. Either supply plus cyclists and cars or supply one decoder for all labels.'\n )\n", (2208, 2389), False, 'from absl import flags\n'), ((2404, 2603), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""cyc_decoder_path"""', 'None', '"""Paths to decoder file containing output of decoder for cyclist. Either supply plus cars and pedestrians or supply one decoder for all labels."""'], {}), "('cyc_decoder_path', None,\n 'Paths to decoder file containing output of decoder for cyclist. Either supply plus cars and pedestrians or supply one decoder for all labels.'\n )\n", (2423, 2603), False, 'from absl import flags\n'), ((2618, 2723), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""calib_file"""', 'None', '"""Path to a npz file that contains all calibration matrices."""'], {}), "('calib_file', None,\n 'Path to a npz file that contains all calibration matrices.')\n", (2637, 2723), False, 'from absl import flags\n'), ((2729, 2798), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""output_dir"""', 'None', '"""Place to write detections."""'], {}), "('output_dir', None, 'Place to write detections.')\n", (2748, 2798), False, 'from absl import flags\n'), ((2799, 2878), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""score_threshold"""', '(0)', '"""Ignore detections with lower score."""'], {}), "('score_threshold', 0, 'Ignore detections with lower score.')\n", (2817, 2878), False, 'from absl import flags\n'), ((3088, 3102), 'numpy.load', 'np.load', (['fname'], {}), '(fname)\n', (3095, 3102), True, 'import numpy as np\n'), ((4556, 4600), 'lingvo.tasks.car.tools.kitti_data.VeloToCameraTransformation', 'kitti_data.VeloToCameraTransformation', (['calib'], {}), '(calib)\n', (4593, 4600), False, 'from lingvo.tasks.car.tools import kitti_data\n'), ((5278, 5342), 'lingvo.compat.logging.info', 'tf.logging.info', (["('Exporting %s for %s' % (class_name, source_id))"], {}), "('Exporting %s for %s' % (class_name, source_id))\n", (5293, 5342), True, 'from lingvo import compat as tf\n'), ((9088, 9140), 'lingvo.compat.logging.info', 'tf.logging.info', (['"""Total example exported: %d"""', 'count'], {}), "('Total example exported: %d', count)\n", (9103, 9140), True, 'from lingvo import compat as tf\n'), ((9172, 9188), 'lingvo.compat.app.run', 'tf.app.run', (['main'], {}), '(main)\n', (9182, 9188), True, 'from lingvo import compat as tf\n'), ((3180, 3222), 'lingvo.compat.logging.info', 'tf.logging.info', (['"""Processing %s"""', 'scene_id'], {}), "('Processing %s', scene_id)\n", (3195, 3222), True, 'from lingvo import compat as tf\n'), ((3572, 3614), 'lingvo.tasks.car.tools.kitti_data.ParseCalibrationDict', 'kitti_data.ParseCalibrationDict', (['raw_calib'], {}), '(raw_calib)\n', (3603, 3614), False, 'from lingvo.tasks.car.tools import kitti_data\n'), ((4854, 4913), 'lingvo.tasks.car.tools.kitti_data.BBox3DToKITTIObject', 'kitti_data.BBox3DToKITTIObject', (['bbox', 'velo_to_cam_transform'], {}), '(bbox, velo_to_cam_transform)\n', (4884, 4913), False, 'from lingvo.tasks.car.tools import kitti_data\n'), ((5395, 5420), 'lingvo.compat.gfile.Open', 'tf.gfile.Open', (['fname', '"""a"""'], {}), "(fname, 'a')\n", (5408, 5420), True, 'from lingvo import compat as tf\n'), ((6328, 6381), 'lingvo.compat.app.UsageError', 'tf.app.UsageError', (['"""Too many command-line arguments."""'], {}), "('Too many command-line arguments.')\n", (6345, 6381), True, 'from lingvo import compat as tf\n'), ((7415, 7451), 'lingvo.compat.io.tf_record_iterator', 'tf.io.tf_record_iterator', (['table_path'], {}), '(table_path)\n', (7439, 7451), True, 'from lingvo import compat as tf\n'), ((7805, 7838), 'lingvo.compat.gfile.Exists', 'tf.gfile.Exists', (['FLAGS.output_dir'], {}), '(FLAGS.output_dir)\n', (7820, 7838), True, 'from lingvo import compat as tf\n'), ((7844, 7876), 'lingvo.compat.gfile.MkDir', 'tf.gfile.MkDir', (['FLAGS.output_dir'], {}), '(FLAGS.output_dir)\n', (7858, 7876), True, 'from lingvo import compat as tf\n'), ((7977, 8014), 'lingvo.compat.gfile.Open', 'tf.gfile.Open', (['FLAGS.calib_file', '"""rb"""'], {}), "(FLAGS.calib_file, 'rb')\n", (7990, 8014), True, 'from lingvo import compat as tf\n'), ((7468, 7487), 'lingvo.core.ops.record_pb2.Record', 'record_pb2.Record', ([], {}), '()\n', (7485, 7487), False, 'from lingvo.core.ops import record_pb2\n'), ((7904, 7934), 'lingvo.tasks.car.kitti_metadata.KITTIMetadata', 'kitti_metadata.KITTIMetadata', ([], {}), '()\n', (7932, 7934), False, 'from lingvo.tasks.car import kitti_metadata\n'), ((7548, 7588), 'lingvo.compat.make_ndarray', 'tf.make_ndarray', (["record.fields['img_id']"], {}), "(record.fields['img_id'])\n", (7563, 7588), True, 'from lingvo import compat as tf\n'), ((7639, 7657), 'lingvo.compat.make_ndarray', 'tf.make_ndarray', (['v'], {}), '(v)\n', (7654, 7657), True, 'from lingvo import compat as tf\n')]
|
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import datetime
import json
import math
import os
import random
import time
import numpy as np
import torch
import torch.optim as optim
import torch.utils.data
import compression
from compression.utils import load_imagenet_data
from optimization.training import train, evaluate
random.seed(7610)
parser = argparse.ArgumentParser(description='PyTorch Discrete Normalizing flows')
parser.add_argument('--imagenet64_data_path', type=str, default='~/data/imagenet-small/train_64x64.npy')
parser.add_argument('--imagenet64_valid_data_path', type=str, default='~/data/imagenet-small/valid_64x64.npy')
parser.add_argument('--imagenet64_model', type=str, default=None)
parser.add_argument('--state_parameters', type=str, default=None)
parser.add_argument('--from_torch', action="store_true")
parser.add_argument('--manual_seed', type=int, help='manual seed, if not given resorts to random seed.')
parser.add_argument('--evaluate_interval_epochs', type=int, default=5,
help='Evaluate per how many epochs')
parser.add_argument('--snap_images', type=int, default=100000,
help='Number of images to process on training before save snapshots')
parser.add_argument('-od', '--out_dir', type=str, default='./', help='output directory for model snapshots etc.')
# optimization settings
parser.add_argument('-e', '--epochs', type=int, default=100, metavar='EPOCHS',
help='number of epochs to train (default: 2000)')
parser.add_argument('-bs', '--batch_size', type=int, default=2, metavar='BATCH_SIZE',
help='input batch size for training (default: 100)')
parser.add_argument('-lr', '--learning_rate', type=float, default=0.00001, metavar='LEARNING_RATE',
help='learning rate')
parser.add_argument('--step_size', default=10000, type=float,
help='Number of batch iteration to update the learning rate')
parser.add_argument('--gamma', default=0.1, type=float,
help='Multiplicative factor of learning rate decay')
args = parser.parse_args()
if args.manual_seed is None:
args.manual_seed = random.randint(1, 100000)
random.seed(args.manual_seed)
torch.manual_seed(args.manual_seed)
np.random.seed(args.manual_seed)
def run(args):
print('\nMODEL SETTINGS: \n', args, '\n')
print("Random Seed: ", args.manual_seed)
# ==================================================================================================================
# SNAPSHOTS
# ==================================================================================================================
args.model_signature = str(datetime.datetime.now())[0:19].replace(' ', '_')
args.model_signature = args.model_signature.replace(':', '_')
os.makedirs(args.out_dir, exist_ok=True)
snap_dir = args.out_dir
with open(os.path.join(snap_dir, 'log.txt'), 'a') as ff:
print('\nMODEL SETTINGS: \n', args, '\n', file=ff)
# SAVING
torch.save(args, snap_dir + '.config')
# Load snapshot parameters
parameters_dict = None
if args.state_parameters is not None:
assert os.path.isfile(args.state_parameters)
parameters_dict = json.load(open(args.state_parameters))
args.learning_rate = parameters_dict['scheduler']['_last_lr'][0]
args.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print('Device:', args.device)
# ==================================================================================================================
# LOAD DATA
# ==================================================================================================================
dataset = load_imagenet_data(os.path.expanduser(args.imagenet64_data_path))
validation_dataset = load_imagenet_data(os.path.expanduser(args.imagenet64_valid_data_path))
train_loader = torch.utils.data.DataLoader(dataset, batch_size=args.batch_size, shuffle=True, drop_last=False)
val_loader = torch.utils.data.DataLoader(validation_dataset, batch_size=args.batch_size, shuffle=True,
drop_last=False)
# test_loader = torch.utils.data.DataLoader(
# dataset,
# batch_size=args.batch_size,
# shuffle=False,
# **kwargs)
args.input_size = [3, 64, 64]
# ==================================================================================================================
# SELECT MODEL
# ==================================================================================================================
# flow parameters and architecture choice are passed on to model through args
print(args.input_size)
from compression.models.load_flowpp_imagenet64 import Imagenet64Model
# Load model
if args.imagenet64_model is None:
model = Imagenet64Model(force_float32_cond=True).eval()
else:
model_ctor = compression.models.load_imagenet64_model
model_filename = os.path.expanduser(args.imagenet64_model)
model = model_ctor(model_filename, force_float32_cond=True, from_torch=args.from_torch)
model.to(device=args.device)
model_sample = model
optimizer = optim.Adam(model.parameters(), lr=args.learning_rate)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=args.step_size, gamma=args.gamma)
# ==================================================================================================================
# TRAINING
# ==================================================================================================================
train_bpd = []
val_bpd = []
# for early stopping
best_val_bpd = np.inf
best_val_loss = np.inf
if args.state_parameters is None:
last_epoch = 1
run_number = 1
else:
last_epoch = parameters_dict['epoch']
run_number = parameters_dict['run_number'] + 1
scheduler.load_state_dict(parameters_dict['scheduler'])
train_times = []
model.double()
for epoch in range(last_epoch, args.epochs + 1):
t_start = time.time()
if parameters_dict is not None:
tr_loss, tr_bpd = train(epoch, train_loader, model, optimizer, args, scheduler,
True, parameters_dict['batch_idx'], run_number)
else:
tr_loss, tr_bpd = train(epoch, train_loader, model, optimizer, args, scheduler, False)
train_bpd.append(tr_bpd)
train_times.append(time.time() - t_start)
print('One training epoch took %.2f seconds' % (time.time() - t_start))
if epoch < 5 or epoch % args.evaluate_interval_epochs == 0:
v_loss, v_bpd = evaluate(
val_loader, model, model_sample, args,
epoch=epoch, file=snap_dir + 'log.txt')
val_bpd.append(v_bpd)
best_val_bpd = min(v_bpd, best_val_bpd)
best_val_loss = min(v_loss, best_val_loss)
print('(BEST: val bpd {:.4f}, val loss {:.4f})\n'.format(best_val_bpd, best_val_loss))
print(f'VALIDATION: loss: {v_loss}, bpd: {v_bpd}')
if math.isnan(v_loss):
raise ValueError('NaN encountered!')
train_bpd = np.hstack(train_bpd)
val_bpd = np.array(val_bpd)
# training time per epoch
train_times = np.array(train_times)
mean_train_time = np.mean(train_times)
std_train_time = np.std(train_times, ddof=1)
print('Average train time per epoch: %.2f +/- %.2f' % (mean_train_time, std_train_time))
# ==================================================================================================================
# EVALUATION
# ==================================================================================================================
final_model = torch.load(snap_dir + 'a.model')
test_loss, test_bpd = evaluate(
train_loader, test_loader, final_model, final_model, args,
epoch=epoch, file=snap_dir + 'test_log.txt')
print('Test loss / bpd: %.2f / %.2f' % (test_loss, test_bpd))
if __name__ == "__main__":
run(args)
|
[
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.optim.lr_scheduler.StepLR",
"os.path.isfile",
"numpy.mean",
"optimization.training.train",
"os.path.join",
"optimization.training.evaluate",
"random.randint",
"torch.utils.data.DataLoader",
"numpy.std",
"torch.load",
"random.seed",
"compression.models.load_flowpp_imagenet64.Imagenet64Model",
"datetime.datetime.now",
"math.isnan",
"torch.manual_seed",
"numpy.hstack",
"torch.cuda.is_available",
"os.makedirs",
"time.time",
"torch.save",
"numpy.array",
"os.path.expanduser"
] |
[((384, 401), 'random.seed', 'random.seed', (['(7610)'], {}), '(7610)\n', (395, 401), False, 'import random\n'), ((412, 485), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PyTorch Discrete Normalizing flows"""'}), "(description='PyTorch Discrete Normalizing flows')\n", (435, 485), False, 'import argparse\n'), ((2250, 2279), 'random.seed', 'random.seed', (['args.manual_seed'], {}), '(args.manual_seed)\n', (2261, 2279), False, 'import random\n'), ((2280, 2315), 'torch.manual_seed', 'torch.manual_seed', (['args.manual_seed'], {}), '(args.manual_seed)\n', (2297, 2315), False, 'import torch\n'), ((2316, 2348), 'numpy.random.seed', 'np.random.seed', (['args.manual_seed'], {}), '(args.manual_seed)\n', (2330, 2348), True, 'import numpy as np\n'), ((2224, 2249), 'random.randint', 'random.randint', (['(1)', '(100000)'], {}), '(1, 100000)\n', (2238, 2249), False, 'import random\n'), ((2867, 2907), 'os.makedirs', 'os.makedirs', (['args.out_dir'], {'exist_ok': '(True)'}), '(args.out_dir, exist_ok=True)\n', (2878, 2907), False, 'import os\n'), ((3075, 3113), 'torch.save', 'torch.save', (['args', "(snap_dir + '.config')"], {}), "(args, snap_dir + '.config')\n", (3085, 3113), False, 'import torch\n'), ((3976, 4076), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(True)', 'drop_last': '(False)'}), '(dataset, batch_size=args.batch_size, shuffle=\n True, drop_last=False)\n', (4003, 4076), False, 'import torch\n'), ((4089, 4199), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['validation_dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(True)', 'drop_last': '(False)'}), '(validation_dataset, batch_size=args.batch_size,\n shuffle=True, drop_last=False)\n', (4116, 4199), False, 'import torch\n'), ((5375, 5460), 'torch.optim.lr_scheduler.StepLR', 'optim.lr_scheduler.StepLR', (['optimizer'], {'step_size': 'args.step_size', 'gamma': 'args.gamma'}), '(optimizer, step_size=args.step_size, gamma=args.gamma\n )\n', (5400, 5460), True, 'import torch.optim as optim\n'), ((7336, 7356), 'numpy.hstack', 'np.hstack', (['train_bpd'], {}), '(train_bpd)\n', (7345, 7356), True, 'import numpy as np\n'), ((7371, 7388), 'numpy.array', 'np.array', (['val_bpd'], {}), '(val_bpd)\n', (7379, 7388), True, 'import numpy as np\n'), ((7438, 7459), 'numpy.array', 'np.array', (['train_times'], {}), '(train_times)\n', (7446, 7459), True, 'import numpy as np\n'), ((7482, 7502), 'numpy.mean', 'np.mean', (['train_times'], {}), '(train_times)\n', (7489, 7502), True, 'import numpy as np\n'), ((7524, 7551), 'numpy.std', 'np.std', (['train_times'], {'ddof': '(1)'}), '(train_times, ddof=1)\n', (7530, 7551), True, 'import numpy as np\n'), ((7923, 7955), 'torch.load', 'torch.load', (["(snap_dir + 'a.model')"], {}), "(snap_dir + 'a.model')\n", (7933, 7955), False, 'import torch\n'), ((7982, 8099), 'optimization.training.evaluate', 'evaluate', (['train_loader', 'test_loader', 'final_model', 'final_model', 'args'], {'epoch': 'epoch', 'file': "(snap_dir + 'test_log.txt')"}), "(train_loader, test_loader, final_model, final_model, args, epoch=\n epoch, file=snap_dir + 'test_log.txt')\n", (7990, 8099), False, 'from optimization.training import train, evaluate\n'), ((3230, 3267), 'os.path.isfile', 'os.path.isfile', (['args.state_parameters'], {}), '(args.state_parameters)\n', (3244, 3267), False, 'import os\n'), ((3812, 3857), 'os.path.expanduser', 'os.path.expanduser', (['args.imagenet64_data_path'], {}), '(args.imagenet64_data_path)\n', (3830, 3857), False, 'import os\n'), ((3903, 3954), 'os.path.expanduser', 'os.path.expanduser', (['args.imagenet64_valid_data_path'], {}), '(args.imagenet64_valid_data_path)\n', (3921, 3954), False, 'import os\n'), ((5090, 5131), 'os.path.expanduser', 'os.path.expanduser', (['args.imagenet64_model'], {}), '(args.imagenet64_model)\n', (5108, 5131), False, 'import os\n'), ((6202, 6213), 'time.time', 'time.time', ([], {}), '()\n', (6211, 6213), False, 'import time\n'), ((2951, 2984), 'os.path.join', 'os.path.join', (['snap_dir', '"""log.txt"""'], {}), "(snap_dir, 'log.txt')\n", (2963, 2984), False, 'import os\n'), ((3448, 3473), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3471, 3473), False, 'import torch\n'), ((6284, 6397), 'optimization.training.train', 'train', (['epoch', 'train_loader', 'model', 'optimizer', 'args', 'scheduler', '(True)', "parameters_dict['batch_idx']", 'run_number'], {}), "(epoch, train_loader, model, optimizer, args, scheduler, True,\n parameters_dict['batch_idx'], run_number)\n", (6289, 6397), False, 'from optimization.training import train, evaluate\n'), ((6474, 6542), 'optimization.training.train', 'train', (['epoch', 'train_loader', 'model', 'optimizer', 'args', 'scheduler', '(False)'], {}), '(epoch, train_loader, model, optimizer, args, scheduler, False)\n', (6479, 6542), False, 'from optimization.training import train, evaluate\n'), ((6803, 6894), 'optimization.training.evaluate', 'evaluate', (['val_loader', 'model', 'model_sample', 'args'], {'epoch': 'epoch', 'file': "(snap_dir + 'log.txt')"}), "(val_loader, model, model_sample, args, epoch=epoch, file=snap_dir +\n 'log.txt')\n", (6811, 6894), False, 'from optimization.training import train, evaluate\n'), ((7246, 7264), 'math.isnan', 'math.isnan', (['v_loss'], {}), '(v_loss)\n', (7256, 7264), False, 'import math\n'), ((4945, 4985), 'compression.models.load_flowpp_imagenet64.Imagenet64Model', 'Imagenet64Model', ([], {'force_float32_cond': '(True)'}), '(force_float32_cond=True)\n', (4960, 4985), False, 'from compression.models.load_flowpp_imagenet64 import Imagenet64Model\n'), ((6603, 6614), 'time.time', 'time.time', ([], {}), '()\n', (6612, 6614), False, 'import time\n'), ((2747, 2770), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2768, 2770), False, 'import datetime\n'), ((6682, 6693), 'time.time', 'time.time', ([], {}), '()\n', (6691, 6693), False, 'import time\n')]
|
#!/usr/bin/env python3
from pymoos import pymoos
import time
import matplotlib.pyplot as plt
import numpy as np
import threading
fig, ax = plt.subplots(subplot_kw=dict(polar=True))
ax.set_theta_direction(-1)
ax.set_theta_zero_location('N')
nav_line, des_line, = ax.plot([], [], 'r', [], [], 'b')
nav_line.set_label('NAV')
des_line.set_label('DESIRED')
ax.legend()
class plotter(pymoos.comms):
"""plotter is a simple app that connects to MOOSDB and plots data."""
def __init__(self, moos_community, moos_port):
"""Initiates MOOSComms, sets the callbacks and runs the loop"""
super(plotter, self).__init__()
self.server = moos_community
self.port = moos_port
self.name = 'plotter'
self.d_heading = 0
self.d_speed = 0
self.n_heading = 0
self.n_speed = 0
# getting a lock to threadsafely draw
self.lock = threading.Lock()
self.set_on_connect_callback(self.__on_connect)
self.set_on_mail_callback(self.__on_new_mail)
self.add_active_queue('nav_queue', self.on_nav)
self.add_message_route_to_active_queue('nav_queue', 'NAV_HEADING')
self.add_message_route_to_active_queue('nav_queue', 'NAV_SPEED')
self.add_active_queue('desired_queue', self.on_desired)
self.add_message_route_to_active_queue('desired_queue', 'DESIRED_HEADING')
self.add_message_route_to_active_queue('desired_queue', 'DESIRED_SPEED')
self.run(self.server, self.port, self.name)
def __on_connect(self):
"""OnConnect callback"""
print("Connected to", self.server, self.port,
"under the name ", self.name)
return (self.register("NAV_SPEED", 0)
and self.register("NAV_HEADING", 0)
and self.register("DESIRED_SPEED", 0)
and self.register("DESIRED_HEADING", 0))
def __on_new_mail(self):
"""OnNewMail callback"""
for msg in self.fetch():
print("Unhandled mail received:", msg.key(), "!")
return True
def on_nav(self, msg):
"""Special callback for NAV_*"""
print("on_nav activated by",
msg.key(), "with value", msg.double())
if msg.key() == 'NAV_HEADING':
self.n_heading = msg.double()
elif msg.key() == 'NAV_SPEED':
self.n_speed = msg.double()
r = np.arange(0, self.n_speed, 0.1)
theta = np.deg2rad(self.n_heading)
self.lock.acquire()
try:
nav_line.set_xdata(theta)
nav_line.set_ydata(r)
ax.set_rmax(5)
plt.draw()
finally:
self.lock.release()
return True
def on_desired(self, msg):
"""Special callback for DESIRED_*"""
print("on_desired activated by",
msg.key(), "with value", msg.double())
if msg.key() == 'DESIRED_HEADING':
self.d_heading = msg.double()
elif msg.key() == 'DESIRED_SPEED':
self.d_speed = msg.double()
r = np.arange(0, self.d_speed, 0.1)
theta = np.deg2rad(self.d_heading)
self.lock.acquire()
try:
des_line.set_xdata(theta)
des_line.set_ydata(r)
ax.set_rmax(5)
plt.draw()
finally:
self.lock.release()
return True
def main():
plottr = plotter('localhost', 9000)
plt.show()
if __name__=="__main__":
main()
|
[
"matplotlib.pyplot.show",
"numpy.deg2rad",
"threading.Lock",
"matplotlib.pyplot.draw",
"numpy.arange"
] |
[((3430, 3440), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3438, 3440), True, 'import matplotlib.pyplot as plt\n'), ((906, 922), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (920, 922), False, 'import threading\n'), ((2401, 2432), 'numpy.arange', 'np.arange', (['(0)', 'self.n_speed', '(0.1)'], {}), '(0, self.n_speed, 0.1)\n', (2410, 2432), True, 'import numpy as np\n'), ((2449, 2475), 'numpy.deg2rad', 'np.deg2rad', (['self.n_heading'], {}), '(self.n_heading)\n', (2459, 2475), True, 'import numpy as np\n'), ((3062, 3093), 'numpy.arange', 'np.arange', (['(0)', 'self.d_speed', '(0.1)'], {}), '(0, self.d_speed, 0.1)\n', (3071, 3093), True, 'import numpy as np\n'), ((3110, 3136), 'numpy.deg2rad', 'np.deg2rad', (['self.d_heading'], {}), '(self.d_heading)\n', (3120, 3136), True, 'import numpy as np\n'), ((2629, 2639), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (2637, 2639), True, 'import matplotlib.pyplot as plt\n'), ((3290, 3300), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (3298, 3300), True, 'import matplotlib.pyplot as plt\n')]
|
import numpy as np
from random import random
import math
class Path:
def __init__(self, r):
self.radius = r
self.path = []
def circleDiscretization(self, qtd_poits = 40):
self.path = []
angle_diff = 2 * math.pi / qtd_poits
for i in range(qtd_poits):
point = (self.radius * math.cos(i * angle_diff) + 85, self.radius * math.sin(i * angle_diff) + 65)
self.path.append(point)
return self.path
def getPath(self):
return self.path[1:] + [self.path[0]]
def pointDistance(self, x1, y1, x2, y2):
return math.sqrt( (x1-x2)**2 + (y1-y2)**2)
def area(self):
return math.pi * self.radius * self.radius
def getSimpleError(self, path, robotPath, N=1):
totalError = 0.0
for i in range(len(path) - 1):
totalError += self.getPointError(path[i], path[i+1], robotPath[i])[2]
totalError += self.getPointError(path[i], path[1], robotPath[i])[2]
return totalError/N
def getPointError(self, startPoint, endPoint, robotPos):
start, end, robot= np.array(startPoint), np.array(endPoint), np.array(robotPos)
middle = (start + end)/ 2.0
errorS = np.sqrt(((start - robot) ** 2).sum(0))
errorE = np.sqrt(((end - robot) ** 2).sum(0))
errorM = np.sqrt(((middle - robot) ** 2).sum(0))
return errorS, errorE, errorM
def tD2I(self, tup):
return (int(tup[0]), int(tup[1]))
def getPerimeterError(self, startPoint, endPoint, robotPath, src=''):
path = [startPoint] + robotPath + [endPoint]
pathNp = np.array(path)
totalError = 0.0
for i in range(len (pathNp) - 1):
totalError += np.sqrt(((pathNp[i] - pathNp[i+1]) ** 2).sum(0))
return totalError
# if __name__ == '__main__':
# height, width = 480, 640
# radius = 150
# angleShift = math.radians(20)
# src = np.zeros(shape=(height, width, 3),dtype=np.uint8)
# center = (width//2, height//2)
# cv2.circle(src, center, radius, (0,0,255),1)
# path = []
# robotPath = []
# for i in np.arange(0, angleShift * 2, angleShift):
# x = (width/2 + math.cos(i) * radius)
# y = (height/2 + math.sin(i) * radius)
# cv2.circle(src, (int(x), int(y)), 1, (255, 0, 0), 1)
# xn = (width/2 + math.cos(i + angleShift/4.0) * radius)
# yn = (height/2 + math.sin(i + angleShift/4.0) * radius)
# xr = xn + (random() - 0.5) * radius/2.5
# yr = yn + (random() - 0.5) * radius/2.5
# robotPath.append((xr, yr))
# cv2.circle(src, (int(xr), int(yr)), 1, (0, 255, 0), 1)
# xn = (width/2 + math.cos(i + angleShift/2.0) * radius)
# yn = (height/2 + math.sin(i + angleShift/2.0) * radius)
# xr = xn + (random() - 0.5) * radius/2.5
# yr = yn + (random() - 0.5) * radius/2.5
# robotPath.append((xr, yr))
# cv2.circle(src, (int(xr), int(yr)), 1, (0, 255, 0), 1)
# path.append((x,y))
# ptError = PathError()
# print (ptError.getPerimeterError(path[0], path[1], robotPath, src))
# cv2.namedWindow("ErrorWin", cv2.WINDOW_NORMAL)
# cv2.imshow("ErrorWin",src)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
|
[
"math.sin",
"numpy.array",
"math.cos",
"math.sqrt"
] |
[((614, 656), 'math.sqrt', 'math.sqrt', (['((x1 - x2) ** 2 + (y1 - y2) ** 2)'], {}), '((x1 - x2) ** 2 + (y1 - y2) ** 2)\n', (623, 656), False, 'import math\n'), ((1655, 1669), 'numpy.array', 'np.array', (['path'], {}), '(path)\n', (1663, 1669), True, 'import numpy as np\n'), ((1132, 1152), 'numpy.array', 'np.array', (['startPoint'], {}), '(startPoint)\n', (1140, 1152), True, 'import numpy as np\n'), ((1154, 1172), 'numpy.array', 'np.array', (['endPoint'], {}), '(endPoint)\n', (1162, 1172), True, 'import numpy as np\n'), ((1174, 1192), 'numpy.array', 'np.array', (['robotPos'], {}), '(robotPos)\n', (1182, 1192), True, 'import numpy as np\n'), ((338, 362), 'math.cos', 'math.cos', (['(i * angle_diff)'], {}), '(i * angle_diff)\n', (346, 362), False, 'import math\n'), ((383, 407), 'math.sin', 'math.sin', (['(i * angle_diff)'], {}), '(i * angle_diff)\n', (391, 407), False, 'import math\n')]
|
#! /usr/bin/env python
import random
import numpy as np
class Environment:
def __init__(self, size=[3,4], start=(0,0), end=(2,3), block=[(1,1)], false_end=(1,3)):
self.size = size
self.state = np.zeros(self.size)
self.action_space = self.generate_action_space()
self.state_space = self.generate_state_space()
self.agent_position = start
def generate_action_space(self):
a_keys = ['<KEY>']
a_values = [(1, 0),(-1, 0),(0, -1),(0, 1)]
return {a_keys[i]:a_values[i] for i in range(len(a_keys))}
def generate_state_space(self):
state = {}
for i in range(self.size[0]):
for j in range(self.size[1]):
state[(i,j)] = list(self.action_space)
return state
def generate_default_probability(self):
p_keys = self.state_space.keys()
p_values = [0.25, 0.25, 0.25, 0.25]
return {p_keys[i]:p_values[i] for i in range(len(p_keys))}
def get_state_action_hash(self, curr_pos):
hash_vals = []
for action in self.state_space[curr_pos]:
str_val = str(str(curr_pos)+'-'+action)
hash_vals.append(str_val)
return hash_vals
if __name__ == "__main__":
env = Environment()
|
[
"numpy.zeros"
] |
[((215, 234), 'numpy.zeros', 'np.zeros', (['self.size'], {}), '(self.size)\n', (223, 234), True, 'import numpy as np\n')]
|
import numpy as np
import matplotlib.pyplot as plt
from lib5c.util.plotting import plotter
@plotter
def plot_pvalue_histogram(data, xlabel='pvalue', **kwargs):
"""
Plots a p-value or q-value distribution.
Parameters
----------
data : np.ndarray
The p-values or q-values to plot.
kwargs : kwargs
Typical plotter kwargs.
Returns
-------
pyplot axis
The axis plotted on.
"""
plt.hist(data, bins=np.linspace(0, 1, 21))
plt.ylabel('number of pixels')
|
[
"matplotlib.pyplot.ylabel",
"numpy.linspace"
] |
[((492, 522), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""number of pixels"""'], {}), "('number of pixels')\n", (502, 522), True, 'import matplotlib.pyplot as plt\n'), ((465, 486), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(21)'], {}), '(0, 1, 21)\n', (476, 486), True, 'import numpy as np\n')]
|
#PHDF_PATH = '/home/brryan/rpm/phoebus/external/parthenon/scripts/python/'
#PHDF_PATH = '/home/brryan/github/phoebus/external/parthenon/scripts/python/'
#DUMP_NAMES = '/home/brryan/builds/phoebus/torus.out1.*.phdf'
DUMP_NAMES = 'torus.out1.*.phdf'
import argparse
import numpy as np
import sys
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import shutil
import os
from subprocess import call, DEVNULL
import glob
#sys.path.append(PHDF_PATH)
#import phdf
from parthenon_tools import phdf
import time
from enum import Enum
#plot = "mks"
plot = "cartesian"
# Outer radius to plot or None
rmax = 40
#rmax = None
parser = argparse.ArgumentParser(description='Plot torus')
parser.add_argument('--nfinal', type=int, default=-1, help='dump to plot')
parser.add_argument('--savefig', type=bool, default=False, help='Whether to save figure')
args = parser.parse_args()
# Whether to plot meshblock boundaries
plot_meshblocks = True
h_ = 0.3
a = 0.9375
rh = 1. + np.sqrt(1. - a*a)
nfinal = args.nfinal
dfnams = np.sort(glob.glob(DUMP_NAMES))
#dfnam = dfnams[nfinal]
dfile = phdf.phdf(dfnams[0])
dfile1 = phdf.phdf(dfnams[nfinal])
nblocks = dfile.NumBlocks
meshblocksize = dfile.MeshBlockSize
nb = nblocks
nx = meshblocksize[0]
ny = meshblocksize[1]
nz = meshblocksize[2]
print("File: ", dfnams[nfinal], end="\n\n")
time = dfile1.Time
print("Time: ", time, end="\n\n")
print("Nblocks: ", nblocks)
print(" nx: %i" % nx + " ny: %i" % ny)
print("")
blockbounds = dfile.BlockBounds
dx = (blockbounds[0][1] - blockbounds[0][0])/nx
dy = (blockbounds[0][3] - blockbounds[0][2])/ny
# Get pcolormesh grid for each block
xblock = np.zeros([nblocks, nx+1, ny+1])
yblock = np.zeros([nblocks, nx+1, ny+1])
for n in range(nblocks):
for i in range(nx+1):
for j in range(ny+1):
dx = (blockbounds[n][1] - blockbounds[n][0])/nx
dy = (blockbounds[n][3] - blockbounds[n][2])/ny
xblock[n,i,j] = blockbounds[n][0] + i*dx
yblock[n,i,j] = blockbounds[n][2] + j*dy
# Convert from FMKS to xy
r = np.exp(xblock)
th = np.pi*yblock + ((1. - h_)/2.)*np.sin(2.*np.pi*yblock)
x = r*np.sin(th)
y = r*np.cos(th)
print("Variables:")
for var in dfile.Variables:
print(" " + var)
print("")
# Numblocks, nz, ny, nx
Pg = dfile1.Get("pressure", flatten=False)
#bfield = dfile.Get("p.bfield", flatten=False)
vcon = dfile.Get("p.velocity", flatten=False)
density = dfile1.Get("p.density", flatten=False)
crho = dfile1.Get("c.density", flatten=False)
ug = dfile1.Get("p.energy", flatten=False)
fd = dfile1.Get("flux_divergence", flatten=False)
st = dfile1.Get("src_terms", flatten=False)
v1 = vcon[:,:,:,:,0]
v2 = vcon[:,:,:,:,1]
v3 = vcon[:,:,:,:,2]
Bcon = dfile1.Get("p.bfield", flatten=False)
flatgcov = dfile1.Get("g.c.gcov", flatten=False)
alpha = dfile1.Get("g.c.alpha", flatten=False)
gcov = np.zeros([nb,nz,ny,nx,4,4])
def flatten(m,n):
ind = [[0,1,3,6],[1,2,4,7],[3,4,5,8],[6,7,8,9]]
return ind[m][n]
for mu in range(4):
gcov[:,:,:,:,mu,0] = flatgcov[:,:,:,:,flatten(mu,0)]
gcov[:,:,:,:,0,mu] = flatgcov[:,:,:,:,flatten(0,mu)]
for mu in range(1,4):
gcov[:,:,:,:,mu,1] = flatgcov[:,:,:,:,flatten(mu,1)]
gcov[:,:,:,:,1,mu] = flatgcov[:,:,:,:,flatten(1,mu)]
for mu in range(2,4):
gcov[:,:,:,:,mu,2] = flatgcov[:,:,:,:,flatten(mu,2)]
gcov[:,:,:,:,2,mu] = flatgcov[:,:,:,:,flatten(2,mu)]
gcov[:,:,:,:,3,3] = flatgcov[:,:,:,:,flatten(3,3)]
Bcov = np.zeros([nb,nz,ny,nx,3])
vcov = np.zeros([nb,nz,ny,nx,3])
for ii in range(3):
for jj in range(3):
Bcov[:,:,:,:,ii] += gcov[:,:,:,:,ii+1,jj+1]*Bcon[:,:,:,:,jj]
vcov[:,:,:,:,ii] += gcov[:,:,:,:,ii+1,jj+1]*vcon[:,:,:,:,jj]
Bsq = np.zeros([nb,nz,ny,nx])
Bdv = np.zeros([nb,nz,ny,nx])
vsq = np.zeros([nb,nz,ny,nx])
Gamma = np.zeros([nb,nz,ny,nx])
for ii in range(3):
Bsq[:,:,:,:] += Bcon[:,:,:,:,ii]*Bcov[:,:,:,:,ii]
Bdv[:,:,:,:] += Bcon[:,:,:,:,ii]*vcov[:,:,:,:,ii]
vsq[:,:,:,:] += vcon[:,:,:,:,ii]*vcov[:,:,:,:,ii]
Gamma[:,:,:,:] = 1./np.sqrt(1 - vsq[:,:,:,:])
b0 = Gamma*Bdv/alpha
bsq = (Bsq + alpha**2*b0**2)/Gamma**2
beta = 2.*Pg/(bsq + 1.e-20)
#b1 = bfield[:,:,:,:,0]
#b2 = bfield[:,:,:,:,1]
#b3 = bfield[:,:,:,:,2]
#b2 = b1*b1 + b2*b2 + b3*b3
#beta = 2*Pg/(b2 + 1.e-100)
#fig = plt.figure()
#ax = plt.gca()
#ax.plot(density[3,0,:,64])
#print(density[3,:,:,64])
#plt.show()
#sys.exit()
var = density
#var = ug
vmin = -5
vmax = 0
#var1 = dfile1.Get("p.density", flatten=False)
#var1 = dfile1.Get("p.energy", flatten=False)
var1 = density
#var = np.fabs(v1)
#vmin=-4
#vmax=0
#var = beta
#vmin = -2
#vmax = 2
mblw = 0.5
def myplot(myvar, n, vmin=vmin, vmax=vmax, uselog=True, cmap='jet',label=None):
from mpl_toolkits.axes_grid1 import make_axes_locatable
ax = axes[n]
#ax = axes
for nb in range(nblocks):
if plot == "mks":
im = ax.pcolormesh(xblock[nb,:,:], yblock[nb,:,:], np.log10(myvar[nb,0].transpose()),
vmin=vmin, vmax=vmax, cmap=cmap)
elif plot == "cartesian":
if uselog:
im = ax.pcolormesh(x[nb,:,:], y[nb,:,:], np.log10(myvar[nb,0].transpose()),
vmin=vmin, vmax=vmax, cmap=cmap)
else:
im = ax.pcolormesh(x[nb,:,:], y[nb,:,:], myvar[nb,0].transpose(),
vmin=vmin, vmax=vmax, cmap=cmap)
if plot_meshblocks:
ax.plot(x[nb,0,:], y[nb,0,:], color='k', linewidth=mblw, linestyle='--')
ax.plot(x[nb,-1,:], y[nb,-1,:], color='k', linewidth=mblw, linestyle='--')
ax.plot(x[nb,:,0], y[nb,:,0], color='k', linewidth=mblw, linestyle='--')
ax.plot(x[nb,:,-1], y[nb,:,-1], color='k', linewidth=mblw, linestyle='--')
if rmax is not None:
ax.set_xlim([0,rmax])
ax.set_ylim([-rmax,rmax])
else:
print("Plotting coordinates \"" + plot + "\" unknown")
sys.exit()
if plot == "cartesian":
ax.set_aspect('equal')
ax.set_xlabel('x')
ax.set_ylabel('y')
# Draw black hole
bh = plt.Circle((0, 0), rh, color='k')
ax.add_patch(bh)
if label is not None:
ax.set_title(label)
if n > 0:
ax.set_yticklabels([])
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im, cax=cax, orientation='vertical')
fig, axes = plt.subplots(1, 2, figsize=(8,8))
myplot(var1,0,label='density')
myplot(beta,1,vmin=-3,vmax=3,uselog=True,cmap='RdBu',label='plasma beta')
if args.savefig:
plt.savefig('frame_%08d.png' % args.nfinal, bbox_inches='tight')
else:
plt.show()
|
[
"mpl_toolkits.axes_grid1.make_axes_locatable",
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"numpy.zeros",
"numpy.sin",
"numpy.exp",
"numpy.cos",
"glob.glob",
"matplotlib.pyplot.Circle",
"sys.exit",
"parthenon_tools.phdf.phdf",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"numpy.sqrt"
] |
[((644, 693), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Plot torus"""'}), "(description='Plot torus')\n", (667, 693), False, 'import argparse\n'), ((1092, 1112), 'parthenon_tools.phdf.phdf', 'phdf.phdf', (['dfnams[0]'], {}), '(dfnams[0])\n', (1101, 1112), False, 'from parthenon_tools import phdf\n'), ((1122, 1147), 'parthenon_tools.phdf.phdf', 'phdf.phdf', (['dfnams[nfinal]'], {}), '(dfnams[nfinal])\n', (1131, 1147), False, 'from parthenon_tools import phdf\n'), ((1645, 1680), 'numpy.zeros', 'np.zeros', (['[nblocks, nx + 1, ny + 1]'], {}), '([nblocks, nx + 1, ny + 1])\n', (1653, 1680), True, 'import numpy as np\n'), ((1686, 1721), 'numpy.zeros', 'np.zeros', (['[nblocks, nx + 1, ny + 1]'], {}), '([nblocks, nx + 1, ny + 1])\n', (1694, 1721), True, 'import numpy as np\n'), ((2026, 2040), 'numpy.exp', 'np.exp', (['xblock'], {}), '(xblock)\n', (2032, 2040), True, 'import numpy as np\n'), ((2817, 2849), 'numpy.zeros', 'np.zeros', (['[nb, nz, ny, nx, 4, 4]'], {}), '([nb, nz, ny, nx, 4, 4])\n', (2825, 2849), True, 'import numpy as np\n'), ((3391, 3420), 'numpy.zeros', 'np.zeros', (['[nb, nz, ny, nx, 3]'], {}), '([nb, nz, ny, nx, 3])\n', (3399, 3420), True, 'import numpy as np\n'), ((3424, 3453), 'numpy.zeros', 'np.zeros', (['[nb, nz, ny, nx, 3]'], {}), '([nb, nz, ny, nx, 3])\n', (3432, 3453), True, 'import numpy as np\n'), ((3629, 3655), 'numpy.zeros', 'np.zeros', (['[nb, nz, ny, nx]'], {}), '([nb, nz, ny, nx])\n', (3637, 3655), True, 'import numpy as np\n'), ((3659, 3685), 'numpy.zeros', 'np.zeros', (['[nb, nz, ny, nx]'], {}), '([nb, nz, ny, nx])\n', (3667, 3685), True, 'import numpy as np\n'), ((3689, 3715), 'numpy.zeros', 'np.zeros', (['[nb, nz, ny, nx]'], {}), '([nb, nz, ny, nx])\n', (3697, 3715), True, 'import numpy as np\n'), ((3721, 3747), 'numpy.zeros', 'np.zeros', (['[nb, nz, ny, nx]'], {}), '([nb, nz, ny, nx])\n', (3729, 3747), True, 'import numpy as np\n'), ((6146, 6180), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(8, 8)'}), '(1, 2, figsize=(8, 8))\n', (6158, 6180), True, 'import matplotlib.pyplot as plt\n'), ((979, 999), 'numpy.sqrt', 'np.sqrt', (['(1.0 - a * a)'], {}), '(1.0 - a * a)\n', (986, 999), True, 'import numpy as np\n'), ((1037, 1058), 'glob.glob', 'glob.glob', (['DUMP_NAMES'], {}), '(DUMP_NAMES)\n', (1046, 1058), False, 'import glob\n'), ((2106, 2116), 'numpy.sin', 'np.sin', (['th'], {}), '(th)\n', (2112, 2116), True, 'import numpy as np\n'), ((2123, 2133), 'numpy.cos', 'np.cos', (['th'], {}), '(th)\n', (2129, 2133), True, 'import numpy as np\n'), ((3941, 3969), 'numpy.sqrt', 'np.sqrt', (['(1 - vsq[:, :, :, :])'], {}), '(1 - vsq[:, :, :, :])\n', (3948, 3969), True, 'import numpy as np\n'), ((5844, 5877), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(0, 0)', 'rh'], {'color': '"""k"""'}), "((0, 0), rh, color='k')\n", (5854, 5877), True, 'import matplotlib.pyplot as plt\n'), ((5999, 6022), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (6018, 6022), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((6305, 6369), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('frame_%08d.png' % args.nfinal)"], {'bbox_inches': '"""tight"""'}), "('frame_%08d.png' % args.nfinal, bbox_inches='tight')\n", (6316, 6369), True, 'import matplotlib.pyplot as plt\n'), ((6378, 6388), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6386, 6388), True, 'import matplotlib.pyplot as plt\n'), ((2076, 2104), 'numpy.sin', 'np.sin', (['(2.0 * np.pi * yblock)'], {}), '(2.0 * np.pi * yblock)\n', (2082, 2104), True, 'import numpy as np\n'), ((5710, 5720), 'sys.exit', 'sys.exit', ([], {}), '()\n', (5718, 5720), False, 'import sys\n')]
|
import numpy as np
# Python3 program to find element
# closet to given target.
# Returns element closest to target in arr[]
def findClosest(arr, n, target):
# Corner cases
if (target <= arr[0][0]):
return 0
if (target >= arr[n - 1][0]):
return n - 1
# Doing binary search
i = 0
j = n
mid = 0
while (i < j):
mid = (i + j) // 2
if (arr[mid][0] == target):
return mid
# If target is less than array
# element, then search in left
if (target < arr[mid][0]):
# If target is greater than previous
# to mid, return closest of two
if (mid > 0 and target > arr[mid - 1][0]):
return getClosest(arr, mid - 1, mid, target)
# Repeat for left half
j = mid
# If target is greater than mid
else:
if (mid < n - 1 and target < arr[mid + 1][0]):
return getClosest(arr, mid, mid + 1, target)
# update i
i = mid + 1
# Only single element left after search
return mid
# Method to compare which one is the more close.
# We find the closest by taking the difference
# between the target and both values. It assumes
# that val2 is greater than val1 and target lies
# between these two.
def getClosest(arr, ind1, ind2, target):
val1 = arr[ind1][0]
val2 = arr[ind2][0]
if (target - val1 >= val2 - target):
return ind2
else:
return ind1
def get_bound(arr, N, s,e):
f1 = get_bound_util(arr, N, s, True)
f2 = get_bound_util(arr, N, e, False)
return f1,f2
def get_bound_util(arr, N, X, is_start):
if is_start:
idx = findClosest(arr, N, X)
# idx = 0
if idx==0:
return np.zeros(60)
else:
return arr[idx-1][1:]
else:
idx = findClosest(arr, arr.shape[0], X)
# idx = N-1
return arr[idx][1:]
if __name__ == '__main__':
gb = get_bound([[4], [5], [10], [12], [18], [20]], 6, 20, True)
print(gb)
|
[
"numpy.zeros"
] |
[((1791, 1803), 'numpy.zeros', 'np.zeros', (['(60)'], {}), '(60)\n', (1799, 1803), True, 'import numpy as np\n')]
|
import numpy as np
import tensorflow as tf
import tfops_short as Z
class model:
def __init__(self, sess, hps, train_iterator, data_init):
# === Define session
self.sess = sess
self.hps = hps
# === Input tensors
with tf.name_scope('input'):
s_shape = [None, hps.n_bins, 1]
self.s_placeholder = tf.compat.v1.placeholder(tf.float32, s_shape, name='spectra')
self.lr_placeholder = tf.compat.v1.placeholder(tf.float32, None, name='learning_rate')
self.train_iterator = train_iterator
z_shape = [None, hps.n_bins/2**(hps.n_levels+1), 4]
self.z_placeholder = tf.compat.v1.placeholder(tf.float32, z_shape, name='latent_rep')
intermediate_z_shapes = [[None, hps.n_bins/2**(i+1), 2] for i in range(1, hps.n_levels)]
self.intermediate_z_placeholders = [
tf.compat.v1.placeholder(tf.float32, shape)
for shape in intermediate_z_shapes
]
# === Loss and optimizer
self.optimizer, self.loss, self.stats = self._create_optimizer()
# === Encoding and decoding
self.z, self.logpx, self.intermediate_zs = self._create_encoder(self.s_placeholder)
self.s = self._create_decoder(self.z_placeholder)
self.s_from_intermediate_zs = self._create_decoder(self.z_placeholder,
self.intermediate_z_placeholders)
# === Initialize
sess.run(tf.compat.v1.global_variables_initializer()) # not sure if more initialization is needed?
# === Saving and restoring
with tf.device('/cpu:0'):
saver = tf.compat.v1.train.Saver()
self.save = lambda path: saver.save(sess, path, write_meta_graph=False)
self.restore = lambda path: saver.restore(sess, path)
def _create_optimizer(self):
'''Set up optimizer to train on input train_iterator and learning rate.'''
_, logpx, _ = self._create_encoder(self.train_iterator)
bits_x = -logpx / (np.log(2.) * self.hps.n_bins) # bits per subpixel
with tf.compat.v1.variable_scope('optimizer', reuse=tf.compat.v1.AUTO_REUSE):
loss = tf.reduce_mean(bits_x)
stats = tf.stack([tf.reduce_mean(loss)])
optimizer = tf.train.AdamOptimizer(learning_rate=self.lr_placeholder).minimize(loss)
return optimizer, loss, stats
def _create_encoder(self, x):
'''Set up encoder tensors to pipe input spectra x to a latent representation
Args:
x: input tensor with shape [?, n_bins, 1], either a placeholder or data stream
Returns:
z: output tensor, contains the fully compressed latent representation
logpx: tensor with shape [?,], the log likelihood of each spectrum
intermediate_zs: list of tensors, the components dropped after splits
'''
logpx = tf.zeros_like(x, dtype='float32')[:, 0, 0] # zeros tensor with shape (batch_size)
intermediate_zs = []
z = Z.squeeze(x - .5, 4) # preprocess the input
with tf.compat.v1.variable_scope('model', reuse=tf.compat.v1.AUTO_REUSE):
for i in range(self.hps.n_levels):
for j in range(self.hps.depth):
z, logpx = self._flow_step('flow-level{}-depth{}'.format(i, j), z, logpx)
if i < self.hps.n_levels - 1:
z1, z2 = Z.split(z)
intermediate_prior = self._create_prior(z2)
logpx += intermediate_prior.logp(z2)
intermediate_zs.append(z2)
z = Z.squeeze(z1, 2)
prior = self._create_prior(z)
logpx += prior.logp(z)
return z, logpx, intermediate_zs
def _create_decoder(self, z, intermediate_zs=None):
'''Set up decoder tensors to generate spectra from latent representation.
Args:
z: tensor where shape matches final latent representation.
intermediate_zs: optional list of tensors, components removed during encoder splits.
Returns:
x: tensor with shape [?, n_bins, 1], spectra constructed from z.
'''
with tf.compat.v1.variable_scope('model', reuse=tf.compat.v1.AUTO_REUSE):
for i in reversed(range(self.hps.n_levels)):
if i < self.hps.n_levels - 1:
z1 = Z.unsqueeze(z, 2)
if intermediate_zs is None:
intermediate_prior = self._create_prior(z1)
z2 = intermediate_prior.sample()
else:
z2 = intermediate_zs[i]
z = Z.unsplit(z1, z2)
for j in reversed(range(self.hps.depth)):
z = self._reverse_flow_step('flow-level{}-depth{}'.format(i, j), z)
x = Z.unsqueeze(z + .5, 4) # post-process spectra
return x
def _flow_step(self, name, z, logdet):
with tf.compat.v1.variable_scope(name):
z, logdet = Z.actnorm('actnorm', z, logdet)
z, logdet = Z.invertible_1x1_conv('invconv', z, logdet, reverse=False)
z1, z2 = Z.split(z)
z2 += Z.f('f', z1, self.hps.width)
z = Z.unsplit(z1, z2)
return z, logdet
def _reverse_flow_step(self, name, z):
with tf.compat.v1.variable_scope(name):
z1, z2 = Z.split(z)
z2 -= Z.f('f', z1, self.hps.width)
z = Z.unsplit(z1, z2)
z, _ = Z.invertible_1x1_conv('invconv', z, 0, reverse=True)
z = Z.actnorm_reverse('actnorm', z)
return z
def _create_prior(self, z):
'''Create a unit normal Gaussian object with same shape as z.'''
mu = tf.zeros_like(z, dtype='float32')
logs = tf.zeros_like(z, dtype='float32')
return Z.gaussian_diag(mu, logs)
def train(self, lr):
'''Run one training batch to optimize the network with learning rate lr.
Returns:
stats: statistics created in _create_optimizer. probably contains loss.
'''
_, stats = self.sess.run([self.optimizer, self.stats], {self.lr_placeholder: lr})
return stats
def encode(self, s):
return self.sess.run([self.z, self.intermediate_zs], {self.s_placeholder: s})
def decode(self, z, intermediate_zs=None):
'''Decode a latent representation with optional intermediate components.
Returns:
spectra, from z and intermediate zs. If no intermediate zs are provided, sample them
randomly from unit normal distributions.
'''
feed_dict = {self.z_placeholder: z}
if intermediate_zs is None:
return self.sess.run(self.s, feed_dict)
else:
for i in range(len(intermediate_zs)):
feed_dict[self.intermediate_z_placeholders[i]] = intermediate_zs[i]
return self.sess.run(self.s_from_intermediate_zs, feed_dict)
def get_likelihood(self, s):
return self.sess.run(self.logpx, {self.s_placeholder: s})
|
[
"tensorflow.zeros_like",
"tfops_short.f",
"tfops_short.squeeze",
"tfops_short.invertible_1x1_conv",
"tfops_short.unsplit",
"tfops_short.gaussian_diag",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.variable_scope",
"tensorflow.compat.v1.placeholder",
"tensorflow.name_scope",
"tfops_short.actnorm",
"tfops_short.split",
"tensorflow.compat.v1.train.Saver",
"tensorflow.reduce_mean",
"tfops_short.actnorm_reverse",
"numpy.log",
"tensorflow.device",
"tfops_short.unsqueeze",
"tensorflow.train.AdamOptimizer"
] |
[((3096, 3117), 'tfops_short.squeeze', 'Z.squeeze', (['(x - 0.5)', '(4)'], {}), '(x - 0.5, 4)\n', (3105, 3117), True, 'import tfops_short as Z\n'), ((5841, 5874), 'tensorflow.zeros_like', 'tf.zeros_like', (['z'], {'dtype': '"""float32"""'}), "(z, dtype='float32')\n", (5854, 5874), True, 'import tensorflow as tf\n'), ((5890, 5923), 'tensorflow.zeros_like', 'tf.zeros_like', (['z'], {'dtype': '"""float32"""'}), "(z, dtype='float32')\n", (5903, 5923), True, 'import tensorflow as tf\n'), ((5939, 5964), 'tfops_short.gaussian_diag', 'Z.gaussian_diag', (['mu', 'logs'], {}), '(mu, logs)\n', (5954, 5964), True, 'import tfops_short as Z\n'), ((263, 285), 'tensorflow.name_scope', 'tf.name_scope', (['"""input"""'], {}), "('input')\n", (276, 285), True, 'import tensorflow as tf\n'), ((364, 425), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['tf.float32', 's_shape'], {'name': '"""spectra"""'}), "(tf.float32, s_shape, name='spectra')\n", (388, 425), True, 'import tensorflow as tf\n'), ((461, 525), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['tf.float32', 'None'], {'name': '"""learning_rate"""'}), "(tf.float32, None, name='learning_rate')\n", (485, 525), True, 'import tensorflow as tf\n'), ((674, 738), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['tf.float32', 'z_shape'], {'name': '"""latent_rep"""'}), "(tf.float32, z_shape, name='latent_rep')\n", (698, 738), True, 'import tensorflow as tf\n'), ((1524, 1567), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (1565, 1567), True, 'import tensorflow as tf\n'), ((1663, 1682), 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), "('/cpu:0')\n", (1672, 1682), True, 'import tensorflow as tf\n'), ((1704, 1730), 'tensorflow.compat.v1.train.Saver', 'tf.compat.v1.train.Saver', ([], {}), '()\n', (1728, 1730), True, 'import tensorflow as tf\n'), ((2154, 2225), 'tensorflow.compat.v1.variable_scope', 'tf.compat.v1.variable_scope', (['"""optimizer"""'], {'reuse': 'tf.compat.v1.AUTO_REUSE'}), "('optimizer', reuse=tf.compat.v1.AUTO_REUSE)\n", (2181, 2225), True, 'import tensorflow as tf\n'), ((2246, 2268), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['bits_x'], {}), '(bits_x)\n', (2260, 2268), True, 'import tensorflow as tf\n'), ((2973, 3006), 'tensorflow.zeros_like', 'tf.zeros_like', (['x'], {'dtype': '"""float32"""'}), "(x, dtype='float32')\n", (2986, 3006), True, 'import tensorflow as tf\n'), ((3153, 3220), 'tensorflow.compat.v1.variable_scope', 'tf.compat.v1.variable_scope', (['"""model"""'], {'reuse': 'tf.compat.v1.AUTO_REUSE'}), "('model', reuse=tf.compat.v1.AUTO_REUSE)\n", (3180, 3220), True, 'import tensorflow as tf\n'), ((4270, 4337), 'tensorflow.compat.v1.variable_scope', 'tf.compat.v1.variable_scope', (['"""model"""'], {'reuse': 'tf.compat.v1.AUTO_REUSE'}), "('model', reuse=tf.compat.v1.AUTO_REUSE)\n", (4297, 4337), True, 'import tensorflow as tf\n'), ((4936, 4959), 'tfops_short.unsqueeze', 'Z.unsqueeze', (['(z + 0.5)', '(4)'], {}), '(z + 0.5, 4)\n', (4947, 4959), True, 'import tfops_short as Z\n'), ((5060, 5093), 'tensorflow.compat.v1.variable_scope', 'tf.compat.v1.variable_scope', (['name'], {}), '(name)\n', (5087, 5093), True, 'import tensorflow as tf\n'), ((5119, 5150), 'tfops_short.actnorm', 'Z.actnorm', (['"""actnorm"""', 'z', 'logdet'], {}), "('actnorm', z, logdet)\n", (5128, 5150), True, 'import tfops_short as Z\n'), ((5175, 5233), 'tfops_short.invertible_1x1_conv', 'Z.invertible_1x1_conv', (['"""invconv"""', 'z', 'logdet'], {'reverse': '(False)'}), "('invconv', z, logdet, reverse=False)\n", (5196, 5233), True, 'import tfops_short as Z\n'), ((5255, 5265), 'tfops_short.split', 'Z.split', (['z'], {}), '(z)\n', (5262, 5265), True, 'import tfops_short as Z\n'), ((5284, 5312), 'tfops_short.f', 'Z.f', (['"""f"""', 'z1', 'self.hps.width'], {}), "('f', z1, self.hps.width)\n", (5287, 5312), True, 'import tfops_short as Z\n'), ((5329, 5346), 'tfops_short.unsplit', 'Z.unsplit', (['z1', 'z2'], {}), '(z1, z2)\n', (5338, 5346), True, 'import tfops_short as Z\n'), ((5433, 5466), 'tensorflow.compat.v1.variable_scope', 'tf.compat.v1.variable_scope', (['name'], {}), '(name)\n', (5460, 5466), True, 'import tensorflow as tf\n'), ((5489, 5499), 'tfops_short.split', 'Z.split', (['z'], {}), '(z)\n', (5496, 5499), True, 'import tfops_short as Z\n'), ((5518, 5546), 'tfops_short.f', 'Z.f', (['"""f"""', 'z1', 'self.hps.width'], {}), "('f', z1, self.hps.width)\n", (5521, 5546), True, 'import tfops_short as Z\n'), ((5563, 5580), 'tfops_short.unsplit', 'Z.unsplit', (['z1', 'z2'], {}), '(z1, z2)\n', (5572, 5580), True, 'import tfops_short as Z\n'), ((5600, 5652), 'tfops_short.invertible_1x1_conv', 'Z.invertible_1x1_conv', (['"""invconv"""', 'z', '(0)'], {'reverse': '(True)'}), "('invconv', z, 0, reverse=True)\n", (5621, 5652), True, 'import tfops_short as Z\n'), ((5669, 5700), 'tfops_short.actnorm_reverse', 'Z.actnorm_reverse', (['"""actnorm"""', 'z'], {}), "('actnorm', z)\n", (5686, 5700), True, 'import tfops_short as Z\n'), ((906, 949), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['tf.float32', 'shape'], {}), '(tf.float32, shape)\n', (930, 949), True, 'import tensorflow as tf\n'), ((2089, 2100), 'numpy.log', 'np.log', (['(2.0)'], {}), '(2.0)\n', (2095, 2100), True, 'import numpy as np\n'), ((2299, 2319), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), '(loss)\n', (2313, 2319), True, 'import tensorflow as tf\n'), ((2346, 2403), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'self.lr_placeholder'}), '(learning_rate=self.lr_placeholder)\n', (2368, 2403), True, 'import tensorflow as tf\n'), ((3486, 3496), 'tfops_short.split', 'Z.split', (['z'], {}), '(z)\n', (3493, 3496), True, 'import tfops_short as Z\n'), ((3689, 3705), 'tfops_short.squeeze', 'Z.squeeze', (['z1', '(2)'], {}), '(z1, 2)\n', (3698, 3705), True, 'import tfops_short as Z\n'), ((4467, 4484), 'tfops_short.unsqueeze', 'Z.unsqueeze', (['z', '(2)'], {}), '(z, 2)\n', (4478, 4484), True, 'import tfops_short as Z\n'), ((4756, 4773), 'tfops_short.unsplit', 'Z.unsplit', (['z1', 'z2'], {}), '(z1, z2)\n', (4765, 4773), True, 'import tfops_short as Z\n')]
|
""" Test Object Tracking
This script receives a .tsv file as input which has already been labelled
and runs the four selected objects tracking algorithm on all videos.
The target object that is being gazed at by the person is presented in blue.
Parameters
----------
tsv_path : str, optional
Path to tsv file containing dataset information (default is "benchmarks/gaze.tsv")
tracker_type : str, optional
Tracking algorithm (default is "CSRT", possible values are ['BOOSTING', 'MIL', 'KCF','TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT'])
use_gpu : bool, optional
Whether to use a gpu (default is False)
write_video : bool, optional
Whether to save the processed video via OpenCV (default is True)
"""
# External imports
from sacred import Experiment
from sacred.observers import FileStorageObserver
from collections import namedtuple
from adam_visual_perception import ObjectTracker
import pandas as pd
import numpy as np
import sys
import os
ex = Experiment()
@ex.config
def my_config():
tsv_path = "benchmarks/gaze.tsv"
tracker_type = "CSRT"
use_gpu = False
write_video = True
@ex.automain
def main(_config):
args = namedtuple('GenericDict', _config.keys())(**_config)
# Setting the random seed
np.random.seed(args.seed)
# Load tsv
if not os.path.isfile(args.tsv_path):
raise Exception("The path to tsv file cannot be found at {}.".format(args.tsv_path))
df = pd.read_csv(args.tsv_path, sep='\t')
# Definea tracker
ot = ObjectTracker(
tracker_type=args.tracker_type,
use_gpu=args.use_gpu,
detect_objects=False,
write_video=args.write_video,
)
for index, row in df.iterrows():
if len(row) == 6:
filename, o1, o2, o3, o4, label = row
print("Started {}".format(filename))
objs = [o1, o2, o3, o4]
bboxes = []
for bbox in objs:
if bbox is np.nan:
print("Skipping {}. No bounding boxes are provided".format(filename))
else:
bbox = tuple(map(int, bbox.strip("()").split(', ')))
bboxes.append(bbox)
ot.get_four_bboxes(filename, bboxes, label, args.write_video)
else:
print("Error: Did you forget to run the object labeling script?")
sys.exit()
print("Done!")
|
[
"numpy.random.seed",
"pandas.read_csv",
"os.path.isfile",
"adam_visual_perception.ObjectTracker",
"sacred.Experiment",
"sys.exit"
] |
[((967, 979), 'sacred.Experiment', 'Experiment', ([], {}), '()\n', (977, 979), False, 'from sacred import Experiment\n'), ((1248, 1273), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (1262, 1273), True, 'import numpy as np\n'), ((1435, 1471), 'pandas.read_csv', 'pd.read_csv', (['args.tsv_path'], {'sep': '"""\t"""'}), "(args.tsv_path, sep='\\t')\n", (1446, 1471), True, 'import pandas as pd\n'), ((1504, 1627), 'adam_visual_perception.ObjectTracker', 'ObjectTracker', ([], {'tracker_type': 'args.tracker_type', 'use_gpu': 'args.use_gpu', 'detect_objects': '(False)', 'write_video': 'args.write_video'}), '(tracker_type=args.tracker_type, use_gpu=args.use_gpu,\n detect_objects=False, write_video=args.write_video)\n', (1517, 1627), False, 'from adam_visual_perception import ObjectTracker\n'), ((1301, 1330), 'os.path.isfile', 'os.path.isfile', (['args.tsv_path'], {}), '(args.tsv_path)\n', (1315, 1330), False, 'import os\n'), ((2355, 2365), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2363, 2365), False, 'import sys\n')]
|
#! /usr/bin/env python
"""
Copyright 2015-2018 <NAME> <<EMAIL>>
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 cv2
import numpy as np
import os
class VideoReader(cv2.VideoCapture):
'''Read a video in batches.
Parameters
----------
path: str
Path to the video file.
batch_size: int, default = 1
Batch size for reading frames
framerate: float, default = None
Video framerate for determining timestamps
for each frame. If None, timestamps will
equal frame number.
gray: bool, default = False
If gray, return only the middle channel
'''
def __init__(self, path, batch_size=1, framerate=None, gray=False):
if isinstance(path, str):
if os.path.exists(path):
super(VideoReader, self).__init__(path)
self.path = path
else:
raise ValueError('file or path does not exist')
else:
raise TypeError('path must be str')
self.batch_size = batch_size
self.n_frames = int(self.get(cv2.CAP_PROP_FRAME_COUNT))
if framerate:
self.timestep = 1. / framerate
else:
self.timestep = 1.
self.idx = 0
self.fps = self.get(cv2.CAP_PROP_FPS)
self.height = self.get(cv2.CAP_PROP_FRAME_HEIGHT)
self.width = self.get(cv2.CAP_PROP_FRAME_WIDTH)
self.shape = (self.height, self.width)
self.finished = False
self.gray = gray
self._read = super(VideoReader, self).read
def read(self):
''' Read one frame
Returns
-------
frame: array
Image is returned of the frame if a frame exists.
Otherwise, return None.
'''
ret, frame = self._read()
if ret:
if self.gray:
frame = frame[..., 1][..., None]
self.idx += 1
return self.idx - 1, frame
else:
self.finished = True
return None
def read_batch(self):
''' Read in a batch of frames.
Returns
-------
frames_idx: array
A batch of frames from the video.
frames: array
A batch of frames from the video.
'''
frames = []
frames_idx = []
for idx in range(self.batch_size):
frame = self.read()
if frame is not None and not self.finished:
frame_idx, frame = frame
frames.append(frame)
frames_idx.append(frame_idx)
empty = len(frames) == 0
if not empty:
frames = np.stack(frames)
frames_idx = np.array(frames_idx)
timestamps = frames_idx * self.timestep
return frames, frames_idx, timestamps
else:
return None
def close(self):
''' Close the VideoReader.
Returns
-------
bool
Returns True if successfully closed.
'''
self.release()
return not self.isOpened()
def __len__(self):
return int(np.ceil(self.n_frames / float(self.batch_size)))
def __getitem__(self, index):
if self.finished:
raise StopIteration
if isinstance(index, (int, np.integer)):
idx0 = index * self.batch_size
if self.idx != idx0:
self.set(cv2.CAP_PROP_POS_FRAMES, idx0 - 1)
self.idx = idx0
else:
raise NotImplementedError
return self.read_batch()
def __next__(self):
if self.finished:
raise StopIteration
else:
return self.read_batch()
def __del__(self):
self.close()
@property
def current_frame(self):
return int(self.get(cv2.CAP_PROP_POS_FRAMES))
@property
def current_time(self):
return self.get(cv2.CAP_PROP_POS_MSEC)
@property
def percent_finished(self):
return self.get(cv2.CAP_PROP_POS_AVI_RATIO) * 100
|
[
"numpy.stack",
"os.path.exists",
"numpy.array"
] |
[((1231, 1251), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (1245, 1251), False, 'import os\n'), ((3132, 3148), 'numpy.stack', 'np.stack', (['frames'], {}), '(frames)\n', (3140, 3148), True, 'import numpy as np\n'), ((3174, 3194), 'numpy.array', 'np.array', (['frames_idx'], {}), '(frames_idx)\n', (3182, 3194), True, 'import numpy as np\n')]
|
from package import redact_ex
from package import solve_explicit_ode
import numpy as np
EXERCISE_01 = """\
Make a program that is able to graphically solve the equation
\u2202T/\u2202t = \u03B1 \u2202\u00B2T/\u2202x\u00B2 = 0 using the Forward in Time, Centered in Space (FTCS)
scheme with Dirichlet boundary conditions u_0 = 0 and u_L = 10.
+ Consider different initial conditions.
+ Consider a new boundary condition: u_L = sin(t/2)
+ Consider null flux boundary conditions.\
"""
redact_ex(EXERCISE_01, 1)
# computation parameters
slices = 20
itern = 1000
plot_frequency = 0.05
# differentiation parameters
deltat = 1e-3
deltax = 1e-1
# problem parameters
alpha = 1
# helper variable
s = alpha*deltat/deltax**2
# grid creation and initial conditions
tprev = np.zeros(slices+1); tpprev = np.zeros(slices+1)
tprev[0] = 0; tpprev[0] = 0
tprev[slices] = 10; tpprev[slices] = 10
initial_conditions = [tprev, tpprev]
# boundary conditions
def boundary_conditions(lap, ngr, grid):
slices = len(grid[0])-1
ngr[0] = 0
ngr[slices] = 10
egrid = [ngr] + [r for r in grid]
return egrid
# differentiation scheme
def ftcs(ngr, grid, s = s):
slices = len(grid[0])-1
for vl in range(1, slices):
ngr[vl] = \
grid[0][vl] + s*(grid[0][vl+1] - 2*grid[0][vl] + grid[0][vl-1])
return ngr
print("Computing...", end='\n\n')
solve_explicit_ode(ftcs, initial_conditions, boundary_conditions,
slices, itern, plot_frequency)
otprev = otpprev = np.zeros(slices+1)
otprev[8:12] = 5; otpprev[8:12] = 5
otprev[0] = 0; otpprev[0] = 0
otprev[slices] = 10; otpprev[slices] = 10
oinitial_conditions = [otprev, otpprev]
print("+ Computing...", end='\n\n')
solve_explicit_ode(ftcs, oinitial_conditions, boundary_conditions,
slices, itern, plot_frequency)
deltat = 1e-2
def oboundary_conditions(lap, ngr, grid, deltat = deltat):
slices = len(grid[0])-1
ngr[0] = 0
ngr[slices] = 10 * abs(np.cos((lap+1)*deltat/2))
egrid = [ngr] + [r for r in grid]
return egrid
# need to re-create the initial_conditions arrays
tprev = np.zeros(slices+1); tpprev = np.zeros(slices+1)
tprev[0] = 0; tpprev[0] = 0
tprev[slices] = 10; tpprev[slices] = 10
initial_conditions = [tprev, tpprev]
print("+ Computing...", end='\n\n')
solve_explicit_ode(ftcs, initial_conditions, oboundary_conditions,
slices, itern, plot_frequency)
deltat = 1e-3
def oboundary_conditions(lap, ngr, grid, deltat = deltat):
slices = len(grid[0])-1
ngr[0] = ngr[1]
ngr[slices] = ngr[slices-1]
egrid = [ngr] + [r for r in grid]
return egrid
otprev = otpprev = np.zeros(slices+1)
otprev[8:12] = 5; otpprev[8:12] = 5
otprev[0] = 0; otpprev[0] = 0
oinitial_conditions = [otprev, otpprev]
print("+ Computing...", end='\n\n')
solve_explicit_ode(ftcs, oinitial_conditions, oboundary_conditions,
slices, itern, plot_frequency)
|
[
"package.solve_explicit_ode",
"package.redact_ex",
"numpy.zeros",
"numpy.cos"
] |
[((487, 512), 'package.redact_ex', 'redact_ex', (['EXERCISE_01', '(1)'], {}), '(EXERCISE_01, 1)\n', (496, 512), False, 'from package import redact_ex\n'), ((772, 792), 'numpy.zeros', 'np.zeros', (['(slices + 1)'], {}), '(slices + 1)\n', (780, 792), True, 'import numpy as np\n'), ((801, 821), 'numpy.zeros', 'np.zeros', (['(slices + 1)'], {}), '(slices + 1)\n', (809, 821), True, 'import numpy as np\n'), ((1377, 1477), 'package.solve_explicit_ode', 'solve_explicit_ode', (['ftcs', 'initial_conditions', 'boundary_conditions', 'slices', 'itern', 'plot_frequency'], {}), '(ftcs, initial_conditions, boundary_conditions, slices,\n itern, plot_frequency)\n', (1395, 1477), False, 'from package import solve_explicit_ode\n'), ((1499, 1519), 'numpy.zeros', 'np.zeros', (['(slices + 1)'], {}), '(slices + 1)\n', (1507, 1519), True, 'import numpy as np\n'), ((1704, 1805), 'package.solve_explicit_ode', 'solve_explicit_ode', (['ftcs', 'oinitial_conditions', 'boundary_conditions', 'slices', 'itern', 'plot_frequency'], {}), '(ftcs, oinitial_conditions, boundary_conditions, slices,\n itern, plot_frequency)\n', (1722, 1805), False, 'from package import solve_explicit_ode\n'), ((2095, 2115), 'numpy.zeros', 'np.zeros', (['(slices + 1)'], {}), '(slices + 1)\n', (2103, 2115), True, 'import numpy as np\n'), ((2124, 2144), 'numpy.zeros', 'np.zeros', (['(slices + 1)'], {}), '(slices + 1)\n', (2132, 2144), True, 'import numpy as np\n'), ((2287, 2388), 'package.solve_explicit_ode', 'solve_explicit_ode', (['ftcs', 'initial_conditions', 'oboundary_conditions', 'slices', 'itern', 'plot_frequency'], {}), '(ftcs, initial_conditions, oboundary_conditions, slices,\n itern, plot_frequency)\n', (2305, 2388), False, 'from package import solve_explicit_ode\n'), ((2623, 2643), 'numpy.zeros', 'np.zeros', (['(slices + 1)'], {}), '(slices + 1)\n', (2631, 2643), True, 'import numpy as np\n'), ((2787, 2889), 'package.solve_explicit_ode', 'solve_explicit_ode', (['ftcs', 'oinitial_conditions', 'oboundary_conditions', 'slices', 'itern', 'plot_frequency'], {}), '(ftcs, oinitial_conditions, oboundary_conditions, slices,\n itern, plot_frequency)\n', (2805, 2889), False, 'from package import solve_explicit_ode\n'), ((1953, 1983), 'numpy.cos', 'np.cos', (['((lap + 1) * deltat / 2)'], {}), '((lap + 1) * deltat / 2)\n', (1959, 1983), True, 'import numpy as np\n')]
|
import itertools
import regex as re
import numpy as np
# seed is fixed for reproducibility
np.random.seed(7)
from tensorflow import set_random_seed
set_random_seed(7)
from unidecode import unidecode
from delft.utilities.Tokenizer import tokenizeAndFilterSimple
from delft.utilities.bert.run_classifier_delft import DataProcessor
import delft.utilities.bert.tokenization as tokenization
from delft.utilities.bert.run_classifier_delft import InputExample
special_character_removal = re.compile(r'[^A-Za-z\.\-\?\!\,\#\@\% ]',re.IGNORECASE)
def to_vector_single(text, embeddings, maxlen=300):
"""
Given a string, tokenize it, then convert it to a sequence of word embedding
vectors with the provided embeddings, introducing <PAD> and <UNK> padding token
vector when appropriate
"""
tokens = tokenizeAndFilterSimple(clean_text(text))
window = tokens[-maxlen:]
# TBD: use better initializers (uniform, etc.)
x = np.zeros((maxlen, embeddings.embed_size), )
# TBD: padding should be left and which vector do we use for padding?
# and what about masking padding later for RNN?
for i, word in enumerate(window):
x[i,:] = embeddings.get_word_vector(word).astype('float32')
return x
def to_vector_elmo(tokens, embeddings, maxlen=300, lowercase=False, num_norm=False):
"""
Given a list of tokens convert it to a sequence of word embedding
vectors based on ELMo contextualized embeddings
"""
subtokens = []
for i in range(0, len(tokens)):
local_tokens = []
for j in range(0, min(len(tokens[i]), maxlen)):
if lowercase:
local_tokens.append(lower(tokens[i][j]))
else:
local_tokens.append(tokens[i][j])
subtokens.append(local_tokens)
return embeddings.get_sentence_vector_only_ELMo(subtokens)
"""
if use_token_dump:
return embeddings.get_sentence_vector_ELMo_with_token_dump(tokens)
"""
def to_vector_bert(tokens, embeddings, maxlen=300, lowercase=False, num_norm=False):
"""
Given a list of tokens convert it to a sequence of word embedding
vectors based on the BERT contextualized embeddings, introducing
padding token when appropriate
"""
subtokens = []
for i in range(0, len(tokens)):
local_tokens = []
for j in range(0, min(len(tokens[i]), maxlen)):
if lowercase:
local_tokens.append(lower(tokens[i][j]))
else:
local_tokens.append(tokens[i][j])
subtokens.append(local_tokens)
vector = embeddings.get_sentence_vector_only_BERT(subtokens)
return vector
def to_vector_simple_with_elmo(tokens, embeddings, maxlen=300, lowercase=False, num_norm=False):
"""
Given a list of tokens convert it to a sequence of word embedding
vectors based on the concatenation of the provided static embeddings and
the ELMo contextualized embeddings, introducing <PAD> and <UNK>
padding token vector when appropriate
"""
subtokens = []
for i in range(0, len(tokens)):
local_tokens = []
for j in range(0, min(len(tokens[i]), maxlen)):
if lowercase:
local_tokens.append(lower(tokens[i][j]))
else:
local_tokens.append(tokens[i][j])
if len(tokens[i]) < maxlen:
for i in range(0, maxlen-len(tokens[i])):
local_tokens.append(" ")
subtokens.append(local_tokens)
return embeddings.get_sentence_vector_with_ELMo(subtokens)
def to_vector_simple_with_bert(tokens, embeddings, maxlen=300, lowercase=False, num_norm=False):
"""
Given a list of tokens convert it to a sequence of word embedding
vectors based on the concatenation of the provided static embeddings and
the BERT contextualized embeddings, introducing padding token vector
when appropriate
"""
subtokens = []
for i in range(0, len(tokens)):
local_tokens = []
for j in range(0, min(len(tokens[i]), maxlen)):
if lowercase:
local_tokens.append(lower(tokens[i][j]))
else:
local_tokens.append(tokens[i][j])
if len(tokens[i]) < maxlen:
for i in range(0, maxlen-len(tokens[i])):
local_tokens.append(" ")
subtokens.append(local_tokens)
return embeddings.get_sentence_vector_with_BERT(subtokens)
def clean_text(text):
x_ascii = unidecode(text)
x_clean = special_character_removal.sub('',x_ascii)
return x_clean
def lower(word):
return word.lower()
def normalize_num(word):
return re.sub(r'[0-90123456789]', r'0', word)
class BERT_classifier_processor(DataProcessor):
"""
BERT data processor for classification
"""
def __init__(self, labels=None, x_train=None, y_train=None, x_test=None, y_test=None):
self.list_classes = labels
self.x_train = x_train
self.y_train = y_train
self.x_test = x_test
self.y_test = y_test
def get_train_examples(self, x_train=None, y_train=None):
"""See base class."""
if x_train is not None:
self.x_train = x_train
if y_train is not None:
self.y_train = y_train
examples, _ = self.create_examples(self.x_train, self.y_train)
return examples
def get_labels(self):
"""See base class."""
return self.list_classes
def get_test_examples(self, x_test=None, y_test=None):
"""See base class."""
if x_test is not None:
self.x_test = x_test
if y_test is not None:
self.y_test = y_test
examples, results = self.create_examples(self.x_test, self.y_test)
return examples, results
def create_examples(self, x_s, y_s=None):
examples = []
valid_classes = np.zeros((y_s.shape[0],len(self.list_classes)))
accumul = 0
for (i, x) in enumerate(x_s):
y = y_s[i]
guid = i
text_a = tokenization.convert_to_unicode(x)
#the_class = self._rewrite_classes(y, i)
ind, = np.where(y == 1)
the_class = self.list_classes[ind[0]]
if the_class is None:
#print(text_a)
continue
if the_class not in self.list_classes:
#the_class = 'other'
continue
label = tokenization.convert_to_unicode(the_class)
examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
valid_classes[accumul] = y
accumul += 1
return examples, valid_classes
def create_inputs(self, x_s, dummy_label='dummy'):
examples = []
# dummy label to avoid breaking the bert base code
label = tokenization.convert_to_unicode(dummy_label)
for (i, x) in enumerate(x_s):
guid = i
text_a = tokenization.convert_to_unicode(x)
examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
return examples
|
[
"unidecode.unidecode",
"numpy.random.seed",
"regex.compile",
"numpy.zeros",
"tensorflow.set_random_seed",
"regex.sub",
"numpy.where",
"delft.utilities.bert.tokenization.convert_to_unicode",
"delft.utilities.bert.run_classifier_delft.InputExample"
] |
[((91, 108), 'numpy.random.seed', 'np.random.seed', (['(7)'], {}), '(7)\n', (105, 108), True, 'import numpy as np\n'), ((148, 166), 'tensorflow.set_random_seed', 'set_random_seed', (['(7)'], {}), '(7)\n', (163, 166), False, 'from tensorflow import set_random_seed\n'), ((483, 546), 'regex.compile', 're.compile', (['"""[^A-Za-z\\\\.\\\\-\\\\?\\\\!\\\\,\\\\#\\\\@\\\\% ]"""', 're.IGNORECASE'], {}), "('[^A-Za-z\\\\.\\\\-\\\\?\\\\!\\\\,\\\\#\\\\@\\\\% ]', re.IGNORECASE)\n", (493, 546), True, 'import regex as re\n'), ((949, 990), 'numpy.zeros', 'np.zeros', (['(maxlen, embeddings.embed_size)'], {}), '((maxlen, embeddings.embed_size))\n', (957, 990), True, 'import numpy as np\n'), ((4468, 4483), 'unidecode.unidecode', 'unidecode', (['text'], {}), '(text)\n', (4477, 4483), False, 'from unidecode import unidecode\n'), ((4641, 4677), 'regex.sub', 're.sub', (['"""[0-90123456789]"""', '"""0"""', 'word'], {}), "('[0-90123456789]', '0', word)\n", (4647, 4677), True, 'import regex as re\n'), ((6829, 6873), 'delft.utilities.bert.tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['dummy_label'], {}), '(dummy_label)\n', (6860, 6873), True, 'import delft.utilities.bert.tokenization as tokenization\n'), ((6037, 6071), 'delft.utilities.bert.tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['x'], {}), '(x)\n', (6068, 6071), True, 'import delft.utilities.bert.tokenization as tokenization\n'), ((6144, 6160), 'numpy.where', 'np.where', (['(y == 1)'], {}), '(y == 1)\n', (6152, 6160), True, 'import numpy as np\n'), ((6434, 6476), 'delft.utilities.bert.tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['the_class'], {}), '(the_class)\n', (6465, 6476), True, 'import delft.utilities.bert.tokenization as tokenization\n'), ((6954, 6988), 'delft.utilities.bert.tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['x'], {}), '(x)\n', (6985, 6988), True, 'import delft.utilities.bert.tokenization as tokenization\n'), ((6505, 6569), 'delft.utilities.bert.run_classifier_delft.InputExample', 'InputExample', ([], {'guid': 'guid', 'text_a': 'text_a', 'text_b': 'None', 'label': 'label'}), '(guid=guid, text_a=text_a, text_b=None, label=label)\n', (6517, 6569), False, 'from delft.utilities.bert.run_classifier_delft import InputExample\n'), ((7018, 7082), 'delft.utilities.bert.run_classifier_delft.InputExample', 'InputExample', ([], {'guid': 'guid', 'text_a': 'text_a', 'text_b': 'None', 'label': 'label'}), '(guid=guid, text_a=text_a, text_b=None, label=label)\n', (7030, 7082), False, 'from delft.utilities.bert.run_classifier_delft import InputExample\n')]
|
# Princeton University licenses this file to You 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.
# ********************************************* Binary Execution Wrappers **************************************************************
from psyneulink.core.globals.utilities import NodeRole
import copy, ctypes
from collections import defaultdict
import numpy as np
from .builder_context import *
from . import helpers, jit_engine
from .debug import debug_env
__all__ = ['CompExecution', 'FuncExecution', 'MechExecution']
def _convert_ctype_to_python(x):
if isinstance(x, ctypes.Structure):
return [_convert_ctype_to_python(getattr(x, field_name)) for field_name, _ in x._fields_]
if isinstance(x, ctypes.Array):
return [_convert_ctype_to_python(num) for num in x]
if isinstance(x, ctypes.c_double):
return x.value
if isinstance(x, (float, int)):
return x
assert False, "Don't know how to convert: {}".format(x)
def _tupleize(x):
try:
return tuple(_tupleize(y) for y in x)
except TypeError:
return x if x is not None else tuple()
class CUDAExecution:
def __init__(self, buffers=['param_struct', 'context_struct']):
for b in buffers:
setattr(self, "_buffer_cuda_" + b, None)
self._uploaded_bytes = 0
self._downloaded_bytes = 0
self.__cuda_out_buf = None
self.__debug_env = debug_env
self.__vo_ty = None
def __del__(self):
if "cuda_data" in self.__debug_env:
try:
name = self._bin_func.name
except:
name = self._composition.name
print("{} CUDA uploaded: {}".format(name, self._uploaded_bytes))
print("{} CUDA downloaded: {}".format(name, self._downloaded_bytes))
@property
def _vo_ty(self):
if self.__vo_ty is None:
self.__vo_ty = self._bin_func.byref_arg_types[3]
if len(self._execution_ids) > 1:
self.__vo_ty = self.__vo_ty * len(self._execution_ids)
return self.__vo_ty
def _get_ctype_bytes(self, data):
# Return dummy buffer. CUDA does not handle 0 size well.
if ctypes.sizeof(data) == 0:
return bytearray(b'aaaa')
return bytearray(data)
def upload_ctype(self, data):
self._uploaded_bytes += ctypes.sizeof(data)
return jit_engine.pycuda.driver.to_device(self._get_ctype_bytes(data))
def download_ctype(self, source, ty):
self._downloaded_bytes += ctypes.sizeof(ty)
out_buf = bytearray(ctypes.sizeof(ty))
jit_engine.pycuda.driver.memcpy_dtoh(out_buf, source)
return ty.from_buffer(out_buf)
def __getattr__(self, attribute):
if not attribute.startswith("_cuda"):
return getattr(super(), attribute)
private_attr = "_buffer" + attribute
if getattr(self, private_attr) is None:
new_buffer = self.upload_ctype(getattr(self, attribute[5:]))
setattr(self, private_attr, new_buffer)
return getattr(self, private_attr)
@property
def _cuda_out_buf(self):
if self.__cuda_out_buf is None:
size = ctypes.sizeof(self._vo_ty)
self.__cuda_out_buf = jit_engine.pycuda.driver.mem_alloc(size)
return self.__cuda_out_buf
def cuda_execute(self, variable):
# Create input parameter
new_var = np.asfarray(variable)
data_in = jit_engine.pycuda.driver.In(new_var)
self._uploaded_bytes += new_var.nbytes
self._bin_func.cuda_call(self._cuda_param_struct,
self._cuda_context_struct,
data_in, self._cuda_out_buf,
threads=len(self._execution_ids))
# Copy the result from the device
ct_res = self.download_ctype(self._cuda_out_buf, self._vo_ty)
return _convert_ctype_to_python(ct_res)
class FuncExecution(CUDAExecution):
def __init__(self, component, execution_ids=[None]):
super().__init__()
self._bin_func = component._llvmBinFunction
self._execution_ids = execution_ids
self._component = component
par_struct_ty, ctx_struct_ty, vi_ty, vo_ty = self._bin_func.byref_arg_types
if len(execution_ids) > 1:
self._bin_multirun = self._bin_func.get_multi_run()
par_struct_ty = par_struct_ty * len(execution_ids)
ctx_struct_ty = ctx_struct_ty * len(execution_ids)
vo_ty = vo_ty * len(execution_ids)
vi_ty = vi_ty * len(execution_ids)
par_initializer = (component._get_param_initializer(ex_id) for ex_id in execution_ids)
ctx_initializer = (component._get_context_initializer(ex_id) for ex_id in execution_ids)
self.__param_struct = par_struct_ty(*par_initializer)
self.__context_struct = ctx_struct_ty(*ctx_initializer)
self._ct_len = ctypes.c_int(len(execution_ids))
self._ct_vo = vo_ty()
self._vi_ty = vi_ty
def _get_compilation_param(self, name, initializer, arg, execution_id):
param = getattr(self._component._compilation_data, name)
struct = param.get(execution_id)
if struct is None:
initializer = getattr(self._component, initializer)(execution_id)
struct_ty = self._bin_func.byref_arg_types[arg]
struct = struct_ty(*initializer)
param.set(struct, execution_context=execution_id)
return struct
@property
def _param_struct(self):
if len(self._execution_ids) > 1:
return self.__param_struct
return self._get_compilation_param('parameter_struct', '_get_param_initializer', 0, self._execution_ids[0])
@property
def _context_struct(self):
if len(self._execution_ids) > 1:
return self.__context_struct
return self._get_compilation_param('context_struct', '_get_context_initializer', 1, self._execution_ids[0])
def execute(self, variable):
new_variable = np.asfarray(variable)
if len(self._execution_ids) > 1:
# wrap_call casts the arguments so we only need contiguaous data
# layout
ct_vi = np.ctypeslib.as_ctypes(new_variable)
self._bin_multirun.wrap_call(self._param_struct,
self._context_struct,
ct_vi, self._ct_vo, self._ct_len)
else:
ct_vi = new_variable.ctypes.data_as(ctypes.POINTER(self._vi_ty))
self._bin_func(ctypes.byref(self._param_struct),
ctypes.byref(self._context_struct),
ct_vi, ctypes.byref(self._ct_vo))
return _convert_ctype_to_python(self._ct_vo)
class MechExecution(FuncExecution):
def execute(self, variable):
# convert to 3d. we always assume that:
# a) the input is vector of input states
# b) input states take vector of projection outputs
# c) projection output is a vector (even 1 element vector)
new_var = np.asfarray([np.atleast_2d(x) for x in variable])
return super().execute(new_var)
class CompExecution(CUDAExecution):
def __init__(self, composition, execution_ids = [None]):
super().__init__(buffers=['context_struct', 'param_struct', 'data_struct', 'conditions'])
self._composition = composition
self._execution_ids = execution_ids
self.__bin_exec_func = None
self.__bin_exec_multi_func = None
self.__bin_func = None
self.__bin_run_func = None
self.__bin_run_multi_func = None
self.__debug_env = debug_env
self.__frozen_vals = None
# TODO: Consolidate these
if len(execution_ids) > 1:
# At least the input_CIM wrapper should be generated
input_cim_fn = composition._get_node_wrapper(composition.input_CIM)._llvm_function
# Input structures
# TODO: Use the compiled version to get these
c_context = _convert_llvm_ir_to_ctype(input_cim_fn.args[0].type.pointee)
c_param = _convert_llvm_ir_to_ctype(input_cim_fn.args[1].type.pointee)
c_data = _convert_llvm_ir_to_ctype(input_cim_fn.args[3].type.pointee)
c_context = c_context * len(execution_ids)
c_param = c_param * len(execution_ids)
c_data = c_data * len(execution_ids)
ctx_initializer = (composition._get_context_initializer(ex_id) for ex_id in execution_ids)
par_initializer = (composition._get_param_initializer(ex_id) for ex_id in execution_ids)
data_initializer = (composition._get_data_initializer(ex_id) for ex_id in execution_ids)
# Instantiate structures
self.__context_struct = c_context(*ctx_initializer)
self.__param_struct = c_param(*par_initializer)
self.__data_struct = c_data(*data_initializer)
self.__conds = None
self._ct_len = ctypes.c_int(len(execution_ids))
@property
def _bin_func(self):
if self.__bin_func is not None:
assert len(self._execution_ids) == 1
return self.__bin_func
if self.__bin_exec_func is not None:
return self.__bin_exec_func
if self.__bin_run_func is not None:
return self.__bin_run_func
assert False, "Binary function not set for execution!"
def _set_bin_node(self, node):
assert node in self._composition._all_nodes
self.__bin_func = self._composition._get_bin_node(node)
@property
def _conditions(self):
if len(self._execution_ids) > 1:
if self.__conds is None:
cond_type = self._bin_func.byref_arg_types[4] * len(self._execution_ids)
gen = helpers.ConditionGenerator(None, self._composition)
cond_initializer = (gen.get_condition_initializer() for _ in self._execution_ids)
self.__conds = cond_type(*cond_initializer)
return self.__conds
conds = self._composition._compilation_data.scheduler_conditions.get(self._execution_ids[0])
if conds is None:
cond_type = self._bin_func.byref_arg_types[4]
gen = helpers.ConditionGenerator(None, self._composition)
cond_initializer = gen.get_condition_initializer()
conds = cond_type(*cond_initializer)
self._composition._compilation_data.scheduler_conditions.set(conds, execution_context=self._execution_ids[0])
return conds
def _get_compilation_param(self, name, initializer, arg, execution_id):
param = getattr(self._composition._compilation_data, name)
struct = param.get(execution_id)
if struct is None:
initializer = getattr(self._composition, initializer)(execution_id)
struct_ty = self._bin_func.byref_arg_types[arg]
struct = struct_ty(*initializer)
param.set(struct, execution_context=execution_id)
return struct
@property
def _param_struct(self):
if len(self._execution_ids) > 1:
return self.__param_struct
return self._get_compilation_param('parameter_struct', '_get_param_initializer', 1, self._execution_ids[0])
@property
def _context_struct(self):
if len(self._execution_ids) > 1:
return self.__context_struct
return self._get_compilation_param('context_struct', '_get_context_initializer', 0, self._execution_ids[0])
@property
def _data_struct(self):
if len(self._execution_ids) > 1:
return self.__data_struct
# Run wrapper changed argument order
arg = 2 if len(self._bin_func.byref_arg_types) > 5 else 3
return self._get_compilation_param('data_struct', '_get_data_initializer', arg, self._execution_ids[0])
@_data_struct.setter
def _data_struct(self, data_struct):
if len(self._execution_ids) > 1:
self.__data_struct = data_struct
else:
self._composition._compilation_data.data_struct.set(data_struct, execution_context = self._execution_ids[0])
def _extract_node_struct(self, node, data):
field = data._fields_[0][0]
res_struct = getattr(data, field)
index = self._composition._get_node_index(node)
field = res_struct._fields_[index][0]
res_struct = getattr(res_struct, field)
return _convert_ctype_to_python(res_struct)
def extract_node_struct(self, node, struct):
if len(self._execution_ids) > 1:
return [self._extract_node_struct(node, struct[i]) for i, _ in enumerate(self._execution_ids)]
else:
return self._extract_node_struct(node, struct)
def extract_frozen_node_output(self, node):
return self.extract_node_struct(node, self.__frozen_vals)
def extract_node_output(self, node):
return self.extract_node_struct(node, self._data_struct)
def extract_node_state(self, node):
return self.extract_node_struct(node, self._context_struct)
def extract_node_params(self, node):
return self.extract_node_struct(node, self._param_struct)
def insert_node_output(self, node, data):
my_field_name = self._data_struct._fields_[0][0]
my_res_struct = getattr(self._data_struct, my_field_name)
index = self._composition._get_node_index(node)
node_field_name = my_res_struct._fields_[index][0]
setattr(my_res_struct, node_field_name, _tupleize(data))
def _get_input_struct(self, inputs):
origins = self._composition.get_nodes_by_role(NodeRole.INPUT)
# Either node execute or composition execute, either way the
# input_CIM should be ready
bin_input_node = self._composition._get_bin_node(self._composition.input_CIM)
c_input = bin_input_node.byref_arg_types[2]
if len(self._execution_ids) > 1:
c_input = c_input * len(self._execution_ids)
# Read provided input data and separate each input state
if len(self._execution_ids) > 1:
input_data = []
for inp in inputs:
input_data.append(([x] for m in origins for x in inp[m]))
else:
input_data = ([x] for m in origins for x in inputs[m])
return c_input(*_tupleize(input_data))
def freeze_values(self):
self.__frozen_vals = copy.deepcopy(self._data_struct)
def execute_node(self, node, inputs = None, execution_id=None):
# We need to reconstruct the inputs here if they were not provided.
# This happens during node execution of nested compositions.
if inputs is None and node is self._composition.input_CIM:
# This assumes origin mechanisms are in the same order as
# CIM input states
origins = (n for n in self._composition.get_nodes_by_role(NodeRole.INPUT) for istate in n.input_states)
input_data = ([proj.parameters.value.get(execution_id) for proj in state.all_afferents] for state in node.input_states)
inputs = defaultdict(list)
for n, d in zip(origins, input_data):
inputs[n].append(d[0])
if inputs is not None:
inputs = self._get_input_struct(inputs)
assert inputs is not None or node is not self._composition.input_CIM
# Set bin node to make sure self._*struct works as expected
self._set_bin_node(node)
if node is not self._composition.input_CIM and self.__frozen_vals is None:
self.freeze_values()
self._bin_func.wrap_call(self._context_struct, self._param_struct,
inputs, self.__frozen_vals, self._data_struct)
if "comp_node_debug" in self.__debug_env:
print("RAN: {}. CTX: {}".format(node, self.extract_node_state(node)))
print("RAN: {}. Params: {}".format(node, self.extract_node_params(node)))
print("RAN: {}. Results: {}".format(node, self.extract_node_output(node)))
@property
def _bin_exec_func(self):
if self.__bin_exec_func is None:
self.__bin_exec_func = self._composition._get_bin_execution()
return self.__bin_exec_func
@property
def _bin_exec_multi_func(self):
if self.__bin_exec_multi_func is None:
self.__bin_exec_multi_func = self._bin_exec_func.get_multi_run()
return self.__bin_exec_multi_func
def execute(self, inputs):
inputs = self._get_input_struct(inputs)
if len(self._execution_ids) > 1:
self._bin_exec_multi_func.wrap_call(self._context_struct, self._param_struct,
inputs, self._data_struct, self._conditions, self._ct_len)
else:
self._bin_exec_func.wrap_call(self._context_struct, self._param_struct,
inputs, self._data_struct, self._conditions)
def cuda_execute(self, inputs):
# Create input buffer
inputs = self._get_input_struct(inputs)
data_in = self.upload_ctype(inputs)
self._bin_exec_func.cuda_call(self._cuda_context_struct, self._cuda_param_struct,
data_in, self._cuda_data_struct, self._cuda_conditions,
threads=len(self._execution_ids))
# Copy the data struct from the device
self._data_struct = self.download_ctype(self._cuda_data_struct, self._vo_ty)
# Methods used to accelerate "Run"
def _get_run_input_struct(self, inputs, num_input_sets):
origins = self._composition.get_nodes_by_role(NodeRole.INPUT)
input_type = self._composition._get_bin_run().byref_arg_types[3]
c_input = input_type * num_input_sets
if len(self._execution_ids) > 1:
c_input = c_input * len(self._execution_ids)
run_inputs = []
for inp in inputs:
run_inps = []
# Extract inputs for each trial
for i in range(num_input_sets):
run_inps.append([])
for m in origins:
run_inps[i] += [[v] for v in inp[m][i]]
run_inputs.append(run_inps)
else:
run_inputs = []
# Extract inputs for each trial
for i in range(num_input_sets):
run_inputs.append([])
for m in origins:
run_inputs[i] += [[v] for v in inputs[m][i]]
return c_input(*_tupleize(run_inputs))
@property
def _bin_run_func(self):
if self.__bin_run_func is None:
self.__bin_run_func = self._composition._get_bin_run()
return self.__bin_run_func
@property
def _bin_run_multi_func(self):
if self.__bin_run_multi_func is None:
self.__bin_run_multi_func = self._bin_run_func.get_multi_run()
return self.__bin_run_multi_func
def run(self, inputs, runs, num_input_sets):
inputs = self._get_run_input_struct(inputs, num_input_sets)
ct_vo = self._bin_run_func.byref_arg_types[4] * runs
if len(self._execution_ids) > 1:
ct_vo = ct_vo * len(self._execution_ids)
outputs = ct_vo()
runs_count = ctypes.c_int(runs)
input_count = ctypes.c_int(num_input_sets)
if len(self._execution_ids) > 1:
self._bin_run_multi_func.wrap_call(self._context_struct, self._param_struct,
self._data_struct, inputs, outputs,
runs_count, input_count, self._ct_len)
else:
self._bin_run_func.wrap_call(self._context_struct, self._param_struct,
self._data_struct, inputs, outputs,
runs_count, input_count)
return _convert_ctype_to_python(outputs)
def cuda_run(self, inputs, runs, num_input_sets):
# Create input buffer
inputs = self._get_run_input_struct(inputs, num_input_sets)
data_in = self.upload_ctype(inputs)
# Create output buffer
output_type = (self._bin_run_func.byref_arg_types[4] * runs)
if len(self._execution_ids) > 1:
output_type = output_type * len(self._execution_ids)
output_size = ctypes.sizeof(output_type)
data_out = jit_engine.pycuda.driver.mem_alloc(output_size)
runs_count = jit_engine.pycuda.driver.In(np.int32(runs))
input_count = jit_engine.pycuda.driver.In(np.int32(num_input_sets))
self._uploaded_bytes += 8 # runs_count + input_count
self._bin_run_func.cuda_call(self._cuda_context_struct,
self._cuda_param_struct,
self._cuda_data_struct,
data_in, data_out, runs_count, input_count,
threads=len(self._execution_ids))
# Copy the data struct from the device
ct_out = self.download_ctype(data_out, output_type)
return _convert_ctype_to_python(ct_out)
|
[
"numpy.atleast_2d",
"copy.deepcopy",
"ctypes.c_int",
"numpy.ctypeslib.as_ctypes",
"ctypes.byref",
"ctypes.sizeof",
"numpy.asfarray",
"collections.defaultdict",
"numpy.int32",
"ctypes.POINTER"
] |
[((2832, 2851), 'ctypes.sizeof', 'ctypes.sizeof', (['data'], {}), '(data)\n', (2845, 2851), False, 'import copy, ctypes\n'), ((3008, 3025), 'ctypes.sizeof', 'ctypes.sizeof', (['ty'], {}), '(ty)\n', (3021, 3025), False, 'import copy, ctypes\n'), ((3899, 3920), 'numpy.asfarray', 'np.asfarray', (['variable'], {}), '(variable)\n', (3910, 3920), True, 'import numpy as np\n'), ((6567, 6588), 'numpy.asfarray', 'np.asfarray', (['variable'], {}), '(variable)\n', (6578, 6588), True, 'import numpy as np\n'), ((15007, 15039), 'copy.deepcopy', 'copy.deepcopy', (['self._data_struct'], {}), '(self._data_struct)\n', (15020, 15039), False, 'import copy, ctypes\n'), ((19847, 19865), 'ctypes.c_int', 'ctypes.c_int', (['runs'], {}), '(runs)\n', (19859, 19865), False, 'import copy, ctypes\n'), ((19888, 19916), 'ctypes.c_int', 'ctypes.c_int', (['num_input_sets'], {}), '(num_input_sets)\n', (19900, 19916), False, 'import copy, ctypes\n'), ((20919, 20945), 'ctypes.sizeof', 'ctypes.sizeof', (['output_type'], {}), '(output_type)\n', (20932, 20945), False, 'import copy, ctypes\n'), ((2670, 2689), 'ctypes.sizeof', 'ctypes.sizeof', (['data'], {}), '(data)\n', (2683, 2689), False, 'import copy, ctypes\n'), ((3054, 3071), 'ctypes.sizeof', 'ctypes.sizeof', (['ty'], {}), '(ty)\n', (3067, 3071), False, 'import copy, ctypes\n'), ((3672, 3698), 'ctypes.sizeof', 'ctypes.sizeof', (['self._vo_ty'], {}), '(self._vo_ty)\n', (3685, 3698), False, 'import copy, ctypes\n'), ((6749, 6785), 'numpy.ctypeslib.as_ctypes', 'np.ctypeslib.as_ctypes', (['new_variable'], {}), '(new_variable)\n', (6771, 6785), True, 'import numpy as np\n'), ((15691, 15708), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (15702, 15708), False, 'from collections import defaultdict\n'), ((21064, 21078), 'numpy.int32', 'np.int32', (['runs'], {}), '(runs)\n', (21072, 21078), True, 'import numpy as np\n'), ((21130, 21154), 'numpy.int32', 'np.int32', (['num_input_sets'], {}), '(num_input_sets)\n', (21138, 21154), True, 'import numpy as np\n'), ((7047, 7074), 'ctypes.POINTER', 'ctypes.POINTER', (['self._vi_ty'], {}), '(self._vi_ty)\n', (7061, 7074), False, 'import copy, ctypes\n'), ((7103, 7135), 'ctypes.byref', 'ctypes.byref', (['self._param_struct'], {}), '(self._param_struct)\n', (7115, 7135), False, 'import copy, ctypes\n'), ((7164, 7198), 'ctypes.byref', 'ctypes.byref', (['self._context_struct'], {}), '(self._context_struct)\n', (7176, 7198), False, 'import copy, ctypes\n'), ((7234, 7259), 'ctypes.byref', 'ctypes.byref', (['self._ct_vo'], {}), '(self._ct_vo)\n', (7246, 7259), False, 'import copy, ctypes\n'), ((7642, 7658), 'numpy.atleast_2d', 'np.atleast_2d', (['x'], {}), '(x)\n', (7655, 7658), True, 'import numpy as np\n')]
|
import dash
import os
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import json
import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
from selenium import webdriver
chrome_exec_shim = "/app/.apt/opt/google/chrome/chrome"
opts = webdriver.ChromeOptions()
opts.binary_location = chrome_exec_shim
opts.add_argument("--no-sandbox");
opts.add_argument("--disable-gpu");
driver = webdriver.Chrome(executable_path=chrome_exec_shim, chrome_options=opts)
import pickle
with open('notebooks/pipeline.pkl', 'rb') as f:
pipeline = pickle.load(f)
from app import app
class Player:
def __init__(self, level, rating, prestige, games_won, qps, medals):
self.level = level
self.rating = rating
self.prestige = prestige
self.qps = qps
self.medals = medals
self.games_won = games_won
class Stats:
def __init__(self, elims=0, dmg_done=0, deaths=0, solo_kills=0):
self.elims = elims
self.dmg_done = dmg_done
self.deaths = deaths
self.solo_kills = solo_kills
class Medals:
def __init__(self, bronze=0, silver=0, gold=0):
self.bronze = bronze
self.silver = silver
self.gold = gold
def create_player(js):
if 'error' in js:
return Player(0,0,0, 0, Stats(), Medals())
if 'quickPlayStats' not in js:
return Player(js['level'],js['rating'],js['prestige'], 0, Stats(), Medals())
if 'careerStats' not in js['quickPlayStats']:
return Player(js['level'],js['rating'],js['prestige'], 0, Stats(), Medals())
if js.get('quickPlayStats',{}).get('careerStats',{}) == None or 'allHeroes' not in js.get('quickPlayStats',{}).get('careerStats',{}):
return Player(js['level'],js['rating'],js['prestige'], 0, Stats(), Medals())
elims = 0
damageDone = 0
deaths = 0
soloKills = 0
if js['quickPlayStats']['careerStats']['allHeroes']['combat'] != None:
if 'eliminations' in js['quickPlayStats']['careerStats']['allHeroes']['combat']:
elims = js['quickPlayStats']['careerStats']['allHeroes']['combat']['eliminations']
if 'damageDone' in js['quickPlayStats']['careerStats']['allHeroes']['combat']:
damageDone = js['quickPlayStats']['careerStats']['allHeroes']['combat']['damageDone']
if 'deaths' in js['quickPlayStats']['careerStats']['allHeroes']['combat']:
deaths = js['quickPlayStats']['careerStats']['allHeroes']['combat']['deaths']
if 'soloKills' in js['quickPlayStats']['careerStats']['allHeroes']['combat']:
soloKills = js['quickPlayStats']['careerStats']['allHeroes']['combat']['soloKills']
qps = Stats(elims,damageDone,deaths,soloKills)
medals = Medals(js['quickPlayStats']['awards'].get('medalsBronze'),
js['quickPlayStats']['awards'].get('medalsSilver'),
js['quickPlayStats']['awards'].get('medalsGold'))
return Player(js['level'],js['rating'],js['prestige'], js['quickPlayStats']['games']['won'], qps, medals)
def df_object(p):
item = [p.level,p.rating,p.prestige,p.games_won,p.qps.elims,p.qps.dmg_done,
p.qps.deaths,p.qps.solo_kills,p.medals.bronze,p.medals.silver,p.medals.gold]
return item
def select_player(username):
url = f"https://ow-api.com/v1/stats/pc/us/{username}/complete"
print(url)
response = requests.get(url)
j = json.loads(response.text)
return create_player(j)
##dataframe setup
columns = ['level','rating','prestige','games_won','qps_elims','qps_dmg_done',
'qps_deaths','qps_solo_kills','medals_bronze','medals_silver','medals_gold']
def predict(data):
kd = [i/(1+sum([data.qps_elims,data.qps_deaths])) for i in [data.qps_elims,data.qps_deaths]]
data['kill_ratio'] = kd[0]
data['death_ratio'] = kd[1]
column0 = []
column1 = []
for col in data.columns:
column0.append(col+str(0))
column1.append(col+str(1))
team1 = data.iloc[0:6].mean(axis=0)
team2 = data.iloc[6:12].mean(axis=0)
t1 = 0
t2 = 0
for col in data.columns:
if 'deaths' in col:
if team1[col] > team2[col]:
t1 = t1 - 1
t2 = t2 + 1
else:
t1 = t1 + 1
t2 = t2 - 1
else:
if team1[col] > team2[col]:
t1 = t1 + 1
t2 = t2 - 1
else:
t1 = t1 - 1
t2 = t2 + 1
data1 = dict(zip(column0,team1))
data2 = dict(zip(column1,team2))
data3 = pd.DataFrame([data1,data2])
data4 = pd.DataFrame(data3.max()).T
if np.random.randint(0,100) >= 90:
t1 = t1 + 10
elif np.random.randint(0,100) <= 10:
t2 = t2 + 10
if t1 > t2:
data4['won'] = 0
elif t2 > t1:
data4['won'] = 1
else:
data4['won'] = 0
data4 = data4.fillna(0)
target = 'won'
X_test = data4.drop(columns=target)
return pipeline.predict(X_test)
amount = 12;
list_col1_inputs = []
list_col1_inputs.append(
html.H2("Enter Teammate Usernames")
)
for i in range(amount):
if(i == 6):
list_col1_inputs.append(html.H2("Enter Enemy Usernames"))
temp = html.Div(className="container",children=[
dcc.Input(
id='username-'+str(i),
className='userinput',
placeholder='Enter Username',
type='text',
value=''
)
]
)
list_col1_inputs.append(temp)
list_col1_inputs.extend([html.Button('Submit' ,id='submit'),html.P(id='username_out')])
column1 = dbc.Col(
list_col1_inputs,
md=5,
)
list_col2_inputs = [html.H2('Select Teammates')]
for i in range(amount):
if(i == 6):
list_col2_inputs.append(html.H2("Select Enemies"))
list_col2_inputs.append(html.Div(id='listofusernames'+str(i)))
list_col2_inputs.append(html.Button("Complete",id='complete'))
column2 = dbc.Col(
list_col2_inputs
)
column3 = dbc.Col(
[
html.Div(id='prediction')
]
)
layout = [dbc.Row([column1, column2]), dbc.Row([column3])]
list_of_username_outputs = []
list_of_username_inputs = []
list_of_username_variables= []
list_of_users_input = []
for i in range(amount):
list_of_username_outputs.append(Output('listofusernames'+str(i),'children'))
list_of_username_inputs.append(State('username-'+str(i), 'value'))
list_of_users_input.append(State('user'+str(i), 'value'))
@app.callback(list_of_username_outputs,
[Input('submit', 'n_clicks')],
state=list_of_username_inputs
)
def search_players(n_clicks,*args):
if n_clicks != None:
dropdowns = []
for i in range(amount):
driver.get(f"https://www.overbuff.com/search?q={args[i]}")
page_source = driver.page_source
soup = BeautifulSoup(page_source)
players = soup.find_all('a', class_="SearchResult", href=True)
userlist = []
for element in players:
if element.find(class_='player-platform').find(class_="fa fa-windows") == None:
continue
players.remove(element)
user = element['href'][12:]
userlist.append({'label':user,'value':user})
dropdowns.append(dcc.Dropdown(
id='user'+str(i),
options=userlist,
placeholder='Select Player',
value=userlist[0]['value']
))
return dropdowns
@app.callback(Output('prediction','children'),
[Input('complete', 'n_clicks')],
state=list_of_users_input
)
def create_teams(n_clicks,*args):
if n_clicks != None:
team1 = []
team2 = []
teams_dataframe = pd.DataFrame(columns=columns)
for i in range(len(args)):
player = select_player(args[i])
teams_dataframe.loc[len(teams_dataframe), :] = df_object(player)
chance = np.random.random()*100
return f'Chances of you winning this game is {chance}%'
|
[
"pandas.DataFrame",
"json.loads",
"dash_html_components.H2",
"dash_bootstrap_components.Row",
"dash_html_components.Div",
"dash_html_components.Button",
"dash.dependencies.Input",
"dash_bootstrap_components.Col",
"dash_html_components.P",
"pickle.load",
"selenium.webdriver.ChromeOptions",
"numpy.random.randint",
"requests.get",
"selenium.webdriver.Chrome",
"bs4.BeautifulSoup",
"numpy.random.random",
"dash.dependencies.Output"
] |
[((377, 402), 'selenium.webdriver.ChromeOptions', 'webdriver.ChromeOptions', ([], {}), '()\n', (400, 402), False, 'from selenium import webdriver\n'), ((523, 594), 'selenium.webdriver.Chrome', 'webdriver.Chrome', ([], {'executable_path': 'chrome_exec_shim', 'chrome_options': 'opts'}), '(executable_path=chrome_exec_shim, chrome_options=opts)\n', (539, 594), False, 'from selenium import webdriver\n'), ((5836, 5867), 'dash_bootstrap_components.Col', 'dbc.Col', (['list_col1_inputs'], {'md': '(5)'}), '(list_col1_inputs, md=5)\n', (5843, 5867), True, 'import dash_bootstrap_components as dbc\n'), ((6170, 6195), 'dash_bootstrap_components.Col', 'dbc.Col', (['list_col2_inputs'], {}), '(list_col2_inputs)\n', (6177, 6195), True, 'import dash_bootstrap_components as dbc\n'), ((673, 687), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (684, 687), False, 'import pickle\n'), ((3520, 3537), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (3532, 3537), False, 'import requests\n'), ((3546, 3571), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (3556, 3571), False, 'import json\n'), ((4725, 4753), 'pandas.DataFrame', 'pd.DataFrame', (['[data1, data2]'], {}), '([data1, data2])\n', (4737, 4753), True, 'import pandas as pd\n'), ((5244, 5279), 'dash_html_components.H2', 'html.H2', (['"""Enter Teammate Usernames"""'], {}), "('Enter Teammate Usernames')\n", (5251, 5279), True, 'import dash_html_components as html\n'), ((5900, 5927), 'dash_html_components.H2', 'html.H2', (['"""Select Teammates"""'], {}), "('Select Teammates')\n", (5907, 5927), True, 'import dash_html_components as html\n'), ((6120, 6158), 'dash_html_components.Button', 'html.Button', (['"""Complete"""'], {'id': '"""complete"""'}), "('Complete', id='complete')\n", (6131, 6158), True, 'import dash_html_components as html\n'), ((6297, 6324), 'dash_bootstrap_components.Row', 'dbc.Row', (['[column1, column2]'], {}), '([column1, column2])\n', (6304, 6324), True, 'import dash_bootstrap_components as dbc\n'), ((6326, 6344), 'dash_bootstrap_components.Row', 'dbc.Row', (['[column3]'], {}), '([column3])\n', (6333, 6344), True, 'import dash_bootstrap_components as dbc\n'), ((7819, 7851), 'dash.dependencies.Output', 'Output', (['"""prediction"""', '"""children"""'], {}), "('prediction', 'children')\n", (7825, 7851), False, 'from dash.dependencies import Input, Output, State\n'), ((4805, 4830), 'numpy.random.randint', 'np.random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (4822, 4830), True, 'import numpy as np\n'), ((5762, 5796), 'dash_html_components.Button', 'html.Button', (['"""Submit"""'], {'id': '"""submit"""'}), "('Submit', id='submit')\n", (5773, 5796), True, 'import dash_html_components as html\n'), ((5797, 5822), 'dash_html_components.P', 'html.P', ([], {'id': '"""username_out"""'}), "(id='username_out')\n", (5803, 5822), True, 'import dash_html_components as html\n'), ((6244, 6269), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""prediction"""'}), "(id='prediction')\n", (6252, 6269), True, 'import dash_html_components as html\n'), ((6754, 6781), 'dash.dependencies.Input', 'Input', (['"""submit"""', '"""n_clicks"""'], {}), "('submit', 'n_clicks')\n", (6759, 6781), False, 'from dash.dependencies import Input, Output, State\n'), ((8062, 8091), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns'}), '(columns=columns)\n', (8074, 8091), True, 'import pandas as pd\n'), ((7867, 7896), 'dash.dependencies.Input', 'Input', (['"""complete"""', '"""n_clicks"""'], {}), "('complete', 'n_clicks')\n", (7872, 7896), False, 'from dash.dependencies import Input, Output, State\n'), ((4867, 4892), 'numpy.random.randint', 'np.random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (4884, 4892), True, 'import numpy as np\n'), ((5355, 5387), 'dash_html_components.H2', 'html.H2', (['"""Enter Enemy Usernames"""'], {}), "('Enter Enemy Usernames')\n", (5362, 5387), True, 'import dash_html_components as html\n'), ((6002, 6027), 'dash_html_components.H2', 'html.H2', (['"""Select Enemies"""'], {}), "('Select Enemies')\n", (6009, 6027), True, 'import dash_html_components as html\n'), ((7085, 7111), 'bs4.BeautifulSoup', 'BeautifulSoup', (['page_source'], {}), '(page_source)\n', (7098, 7111), False, 'from bs4 import BeautifulSoup\n'), ((8265, 8283), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (8281, 8283), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 21:24:37 2019
@author: anilosmantur
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 20:43:41 2019
@author: anilosmantur
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import MinMaxScaler
from sklearn import metrics
from pylab import rcParams
rcParams['figure.figsize'] = 10, 5
n_samples = 30#91
dataNameList = ['attention','meditation','rawValue','delta','theta','lowAlpha','highAlpha',
'lowBeta','highBeta','lowGamma','midGamma','poorSignal']
featureList = ['attention','meditation','rawValue','delta','theta','lowAlpha','highAlpha',
'lowBeta','highBeta','lowGamma','midGamma']
labels = ['focus','relax', 'upWord', 'downWord',
'upColor', 'downColor',
'CyanUP','greenDOWN', 'yellowRIGHT', 'BlackLEFT']#,'blink']
labels = ['relax','upColor','CyanUP']
n_label = len(labels)
#label = labels[2]
#count = 0
trainDataDict = dict()
for data in dataNameList:
trainDataDict[data] = []
testDataDict = dict()
for data in dataNameList:
testDataDict[data] = []
def load_data(dataDict, label, count):
for data in dataNameList:
dataDict[data].append(np.load('dataset/{}/{}/{}.npy'.format(label,count,data))[:100])
#n_samples = 10
test_n_samples = int(n_samples/2)
test_size = n_label * int(n_samples/2)
train_n_samples = round(n_samples/2)
train_size = n_label * round(n_samples/2)
#nums = np.arange(n_samples)*2
nums = np.arange(n_samples)
trainNums = np.concatenate([nums[:5],nums[10:15],nums[20:25]])#,nums[31:41], nums[51:61],nums[71:81]])
#trainNums = nums[:5]
np.random.shuffle(trainNums)
testNums = np.concatenate([nums[5:10],nums[15:20],nums[25:30]])#,nums[41:51], nums[61:71],nums[81:91]])
#testNums = nums[5:10]
np.random.shuffle(testNums)
for label in labels:
for i in trainNums:
load_data(trainDataDict,label, i)
for label in labels:
for i in testNums:
load_data(testDataDict,label, i)
for data in dataNameList:
trainDataDict[data] = np.array(trainDataDict[data])
for data in dataNameList:
testDataDict[data] = np.array(testDataDict[data])
#connect features
trainData = []
for data in featureList:
trainData.append(trainDataDict[data])
trainData = np.array(trainData).transpose(1,0,2)
testData = []
for data in featureList:
testData.append(testDataDict[data])
testData = np.array(testData).transpose(1,0,2)
trainData = trainData.astype('float32')
testData = testData.astype('float32')
## normalization needed
scaler = MinMaxScaler()
print(scaler.fit(trainData.reshape(-1, 1100)))
trainData = scaler.transform(trainData.reshape(-1, 1100))
testData = scaler.transform(testData.reshape(-1, 1100))
trainLabels = []
for i in range(n_label):
trainLabels.append(np.ones(train_n_samples)*i )#,np.ones(15)*2])
trainLabels = np.concatenate(trainLabels)
testLabels = []
for i in range(n_label):
testLabels.append(np.ones(test_n_samples)*i )#,np.ones(15)*2])
testLabels = np.concatenate(testLabels)
from sklearn.model_selection import GridSearchCV
param_grid = {
'n_estimators':[20, 50, 100, 150, 200],
'max_features':['auto', 'sqrt', 'log2'],
'max_depth':[2,3,4],
'criterion':['gini','entropy'],
}
rfc = RandomForestClassifier(random_state=42)
rfc_cv = GridSearchCV(estimator=rfc,param_grid=param_grid,cv=5)
rfc_cv.fit(trainData, trainLabels)
#print('feature : ', dataNameList[i])
print(rfc_cv.best_score_)
print(rfc_cv.best_params_)
preds = np.array(rfc_cv.predict(testData))
scores = metrics.accuracy_score(testLabels, preds)
print('test %: {:6.2f}%'.format(scores*100))
|
[
"sklearn.ensemble.RandomForestClassifier",
"sklearn.model_selection.GridSearchCV",
"numpy.concatenate",
"sklearn.metrics.accuracy_score",
"sklearn.preprocessing.MinMaxScaler",
"numpy.ones",
"numpy.arange",
"numpy.array",
"numpy.random.shuffle"
] |
[((1575, 1595), 'numpy.arange', 'np.arange', (['n_samples'], {}), '(n_samples)\n', (1584, 1595), True, 'import numpy as np\n'), ((1608, 1660), 'numpy.concatenate', 'np.concatenate', (['[nums[:5], nums[10:15], nums[20:25]]'], {}), '([nums[:5], nums[10:15], nums[20:25]])\n', (1622, 1660), True, 'import numpy as np\n'), ((1721, 1749), 'numpy.random.shuffle', 'np.random.shuffle', (['trainNums'], {}), '(trainNums)\n', (1738, 1749), True, 'import numpy as np\n'), ((1761, 1815), 'numpy.concatenate', 'np.concatenate', (['[nums[5:10], nums[15:20], nums[25:30]]'], {}), '([nums[5:10], nums[15:20], nums[25:30]])\n', (1775, 1815), True, 'import numpy as np\n'), ((1877, 1904), 'numpy.random.shuffle', 'np.random.shuffle', (['testNums'], {}), '(testNums)\n', (1894, 1904), True, 'import numpy as np\n'), ((2630, 2644), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (2642, 2644), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((2932, 2959), 'numpy.concatenate', 'np.concatenate', (['trainLabels'], {}), '(trainLabels)\n', (2946, 2959), True, 'import numpy as np\n'), ((3082, 3108), 'numpy.concatenate', 'np.concatenate', (['testLabels'], {}), '(testLabels)\n', (3096, 3108), True, 'import numpy as np\n'), ((3364, 3403), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'random_state': '(42)'}), '(random_state=42)\n', (3386, 3403), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((3413, 3469), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', ([], {'estimator': 'rfc', 'param_grid': 'param_grid', 'cv': '(5)'}), '(estimator=rfc, param_grid=param_grid, cv=5)\n', (3425, 3469), False, 'from sklearn.model_selection import GridSearchCV\n'), ((3648, 3689), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['testLabels', 'preds'], {}), '(testLabels, preds)\n', (3670, 3689), False, 'from sklearn import metrics\n'), ((2132, 2161), 'numpy.array', 'np.array', (['trainDataDict[data]'], {}), '(trainDataDict[data])\n', (2140, 2161), True, 'import numpy as np\n'), ((2213, 2241), 'numpy.array', 'np.array', (['testDataDict[data]'], {}), '(testDataDict[data])\n', (2221, 2241), True, 'import numpy as np\n'), ((2355, 2374), 'numpy.array', 'np.array', (['trainData'], {}), '(trainData)\n', (2363, 2374), True, 'import numpy as np\n'), ((2482, 2500), 'numpy.array', 'np.array', (['testData'], {}), '(testData)\n', (2490, 2500), True, 'import numpy as np\n'), ((2872, 2896), 'numpy.ones', 'np.ones', (['train_n_samples'], {}), '(train_n_samples)\n', (2879, 2896), True, 'import numpy as np\n'), ((3024, 3047), 'numpy.ones', 'np.ones', (['test_n_samples'], {}), '(test_n_samples)\n', (3031, 3047), True, 'import numpy as np\n')]
|
from __future__ import absolute_import, print_function
from numpy.testing import TestCase, dec, assert_, run_module_suite
from scipy.weave import inline_tools
class TestInline(TestCase):
"""These are long running tests...
Would be useful to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert_(result == 4)
## Unfortunately, it is not always possible to catch distutils compiler
## errors, since SystemExit is used. Until that is fixed, these tests
## cannot be run in the same process as the test suite.
## try:
## a = 1
## result = inline_tools.inline(code,['a'])
## assert_(1) # should've thrown a ValueError
## except ValueError:
## pass
## from distutils.errors import DistutilsError, CompileError
## try:
## a = 'string'
## result = inline_tools.inline(code,['a'])
## assert_(1) # should've gotten an error
## except:
## # ?CompileError is the error reported, but catching it doesn't work
## pass
if __name__ == "__main__":
run_module_suite()
|
[
"scipy.weave.inline_tools.inline",
"numpy.testing.assert_",
"numpy.testing.run_module_suite"
] |
[((1475, 1493), 'numpy.testing.run_module_suite', 'run_module_suite', ([], {}), '()\n', (1491, 1493), False, 'from numpy.testing import TestCase, dec, assert_, run_module_suite\n'), ((632, 664), 'scipy.weave.inline_tools.inline', 'inline_tools.inline', (['code', "['a']"], {}), "(code, ['a'])\n", (651, 664), False, 'from scipy.weave import inline_tools\n'), ((672, 692), 'numpy.testing.assert_', 'assert_', (['(result == 4)'], {}), '(result == 4)\n', (679, 692), False, 'from numpy.testing import TestCase, dec, assert_, run_module_suite\n')]
|
from skfda.representation.basis import (
FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor)
import unittest
import numpy as np
class TestBasisEvaluationFourier(unittest.TestCase):
def test_evaluation_simple_fourier(self):
"""Test the evaluation of FDataBasis"""
fourier = Fourier(domain_range=(0, 2), n_basis=5)
coefficients = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]])
f = FDataBasis(fourier, coefficients)
t = np.linspace(0, 2, 11)
# Results in R package fda
res = np.array([[8.71, 9.66, 1.84, -4.71, -2.80, 2.71,
2.45, -3.82, -6.66, -0.30, 8.71],
[22.24, 26.48, 10.57, -4.95, -3.58, 6.24,
5.31, -7.69, -13.32, 1.13, 22.24]])[..., np.newaxis]
np.testing.assert_array_almost_equal(f(t).round(2), res)
np.testing.assert_array_almost_equal(f.evaluate(t).round(2), res)
def test_evaluation_point_fourier(self):
"""Test the evaluation of a single point FDataBasis"""
fourier = Fourier(domain_range=(0, 1), n_basis=3)
coefficients = np.array([[0.00078238, 0.48857741, 0.63971985],
[0.01778079, 0.73440271, 0.20148638]])
f = FDataBasis(fourier, coefficients)
# Test different ways of call f with a point
res = np.array([-0.903918107989282, -0.267163981229459]
).reshape((2, 1, 1)).round(4)
np.testing.assert_array_almost_equal(f([0.5]).round(4), res)
np.testing.assert_array_almost_equal(f((0.5,)).round(4), res)
np.testing.assert_array_almost_equal(f(0.5).round(4), res)
np.testing.assert_array_almost_equal(f(np.array([0.5])).round(4), res)
# Problematic case, should be accepted or no?
#np.testing.assert_array_almost_equal(f(np.array(0.5)).round(4), res)
def test_evaluation_derivative_fourier(self):
"""Test the evaluation of the derivative of a FDataBasis"""
fourier = Fourier(domain_range=(0, 1), n_basis=3)
coefficients = np.array([[0.00078238, 0.48857741, 0.63971985],
[0.01778079, 0.73440271, 0.20148638]])
f = FDataBasis(fourier, coefficients)
t = np.linspace(0, 1, 4)
res = np.array([4.34138447771721, -7.09352774867064, 2.75214327095343,
4.34138447771721, 6.52573053999253,
-4.81336320468984, -1.7123673353027, 6.52573053999253]
).reshape((2, 4, 1)).round(3)
f_deriv = f.derivative()
np.testing.assert_array_almost_equal(
f_deriv(t).round(3), res
)
def test_evaluation_grid_fourier(self):
"""Test the evaluation of FDataBasis with the grid option set to
true. Nothing should be change due to the domain dimension is 1,
but can accept the """
fourier = Fourier(domain_range=(0, 1), n_basis=3)
coefficients = np.array([[0.00078238, 0.48857741, 0.63971985],
[0.01778079, 0.73440271, 0.20148638]])
f = FDataBasis(fourier, coefficients)
t = np.linspace(0, 1, 4)
res_test = f(t)
# Different ways to pass the axes
np.testing.assert_array_almost_equal(f(t, grid=True), res_test)
np.testing.assert_array_almost_equal(f((t,), grid=True), res_test)
np.testing.assert_array_almost_equal(f([t], grid=True), res_test)
np.testing.assert_array_almost_equal(f(np.atleast_2d(t), grid=True),
res_test)
# Number of axis different than the domain dimension (1)
with np.testing.assert_raises(ValueError):
f((t, t), grid=True)
def test_evaluation_composed_fourier(self):
"""Test the evaluation of FDataBasis the a matrix of times instead of
a list of times """
fourier = Fourier(domain_range=(0, 1), n_basis=3)
coefficients = np.array([[0.00078238, 0.48857741, 0.63971985],
[0.01778079, 0.73440271, 0.20148638]])
f = FDataBasis(fourier, coefficients)
t = np.linspace(0, 1, 4)
# Test same result than evaluation standart
np.testing.assert_array_almost_equal(f([1]),
f([[1], [1]],
aligned=False))
np.testing.assert_array_almost_equal(f(t), f(np.vstack((t, t)),
aligned=False))
# Different evaluation times
t_multiple = [[0, 0.5], [0.2, 0.7]]
np.testing.assert_array_almost_equal(f(t_multiple[0])[0],
f(t_multiple,
aligned=False)[0])
np.testing.assert_array_almost_equal(f(t_multiple[1])[1],
f(t_multiple,
aligned=False)[1])
def test_domain_in_list_fourier(self):
"""Test the evaluation of FDataBasis"""
for fourier in (Fourier(domain_range=[(0, 1)], n_basis=3),
Fourier(domain_range=((0, 1),), n_basis=3),
Fourier(domain_range=np.array((0, 1)), n_basis=3),
Fourier(domain_range=np.array([(0, 1)]), n_basis=3)):
coefficients = np.array([[0.00078238, 0.48857741, 0.63971985],
[0.01778079, 0.73440271, 0.20148638]])
f = FDataBasis(fourier, coefficients)
t = np.linspace(0, 1, 4)
res = np.array([0.905, 0.147, -1.05, 0.905, 0.303,
0.775, -1.024, 0.303]).reshape((2, 4, 1))
np.testing.assert_array_almost_equal(f(t).round(3), res)
np.testing.assert_array_almost_equal(f.evaluate(t).round(3), res)
class TestBasisEvaluationBSpline(unittest.TestCase):
def test_evaluation_simple_bspline(self):
"""Test the evaluation of FDataBasis"""
bspline = BSpline(domain_range=(0, 2), n_basis=5)
coefficients = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]])
f = FDataBasis(bspline, coefficients)
t = np.linspace(0, 2, 11)
# Results in R package fda
res = np.array([[1, 1.54, 1.99, 2.37, 2.7, 3,
3.3, 3.63, 4.01, 4.46, 5],
[6, 6.54, 6.99, 7.37, 7.7, 8,
8.3, 8.63, 9.01, 9.46, 10]])[..., np.newaxis]
np.testing.assert_array_almost_equal(f(t).round(2), res)
np.testing.assert_array_almost_equal(f.evaluate(t).round(2), res)
def test_evaluation_point_bspline(self):
"""Test the evaluation of a single point FDataBasis"""
bspline = BSpline(domain_range=(0, 1), n_basis=5, order=3)
coefficients = [[0.00078238, 0.48857741, 0.63971985, 0.23, 0.33],
[0.01778079, 0.73440271, 0.20148638, 0.54, 0.12]]
f = FDataBasis(bspline, coefficients)
# Test different ways of call f with a point
res = np.array([[0.5696], [0.3104]])[..., np.newaxis]
np.testing.assert_array_almost_equal(f([0.5]).round(4), res)
np.testing.assert_array_almost_equal(f((0.5,)).round(4), res)
np.testing.assert_array_almost_equal(f(0.5).round(4), res)
np.testing.assert_array_almost_equal(f(np.array([0.5])).round(4), res)
# Problematic case, should be accepted or no?
#np.testing.assert_array_almost_equal(f(np.array(0.5)).round(4), res)
def test_evaluation_derivative_bspline(self):
"""Test the evaluation of the derivative of a FDataBasis"""
bspline = BSpline(domain_range=(0, 1), n_basis=5, order=3)
coefficients = [[0.00078238, 0.48857741, 0.63971985, 0.23, 0.33],
[0.01778079, 0.73440271, 0.20148638, 0.54, 0.12]]
f = FDataBasis(bspline, coefficients)
t = np.linspace(0, 1, 4)
f_deriv = f.derivative()
np.testing.assert_array_almost_equal(
f_deriv(t).round(3),
np.array([[2.927, 0.453, -1.229, 0.6],
[4.3, -1.599, 1.016, -2.52]])[..., np.newaxis]
)
def test_evaluation_grid_bspline(self):
"""Test the evaluation of FDataBasis with the grid option set to
true. Nothing should be change due to the domain dimension is 1,
but can accept the """
bspline = BSpline(domain_range=(0, 1), n_basis=5, order=3)
coefficients = [[0.00078238, 0.48857741, 0.63971985, 0.23, 0.33],
[0.01778079, 0.73440271, 0.20148638, 0.54, 0.12]]
f = FDataBasis(bspline, coefficients)
t = np.linspace(0, 1, 4)
res_test = f(t)
# Different ways to pass the axes
np.testing.assert_array_almost_equal(f(t, grid=True), res_test)
np.testing.assert_array_almost_equal(f((t,), grid=True), res_test)
np.testing.assert_array_almost_equal(f([t], grid=True), res_test)
np.testing.assert_array_almost_equal(
f(np.atleast_2d(t), grid=True), res_test)
# Number of axis different than the domain dimension (1)
with np.testing.assert_raises(ValueError):
f((t, t), grid=True)
def test_evaluation_composed_bspline(self):
"""Test the evaluation of FDataBasis the a matrix of times instead of
a list of times """
bspline = BSpline(domain_range=(0, 1), n_basis=5, order=3)
coefficients = [[0.00078238, 0.48857741, 0.63971985, 0.23, 0.33],
[0.01778079, 0.73440271, 0.20148638, 0.54, 0.12]]
f = FDataBasis(bspline, coefficients)
t = np.linspace(0, 1, 4)
# Test same result than evaluation standart
np.testing.assert_array_almost_equal(f([1]),
f([[1], [1]],
aligned=False))
np.testing.assert_array_almost_equal(f(t), f(np.vstack((t, t)),
aligned=False))
# Different evaluation times
t_multiple = [[0, 0.5], [0.2, 0.7]]
np.testing.assert_array_almost_equal(f(t_multiple[0])[0],
f(t_multiple,
aligned=False)[0])
np.testing.assert_array_almost_equal(f(t_multiple[1])[1],
f(t_multiple,
aligned=False)[1])
def test_domain_in_list_bspline(self):
"""Test the evaluation of FDataBasis"""
for bspline in (BSpline(domain_range=[(0, 1)], n_basis=5, order=3),
BSpline(domain_range=((0, 1),), n_basis=5, order=3),
BSpline(domain_range=np.array((0, 1)), n_basis=5,
order=3),
BSpline(domain_range=np.array([(0, 1)]), n_basis=5,
order=3)
):
coefficients = [[0.00078238, 0.48857741, 0.63971985, 0.23, 0.33],
[0.01778079, 0.73440271, 0.20148638, 0.54, 0.12]]
f = FDataBasis(bspline, coefficients)
t = np.linspace(0, 1, 4)
res = np.array([[0.001, 0.564, 0.435, 0.33],
[0.018, 0.468, 0.371, 0.12]])[..., np.newaxis]
np.testing.assert_array_almost_equal(f(t).round(3), res)
np.testing.assert_array_almost_equal(f.evaluate(t).round(3), res)
# Check error
with np.testing.assert_raises(ValueError):
BSpline(domain_range=[(0, 1), (0, 1)])
class TestBasisEvaluationMonomial(unittest.TestCase):
def test_evaluation_simple_monomial(self):
"""Test the evaluation of FDataBasis"""
monomial = Monomial(domain_range=(0, 2), n_basis=5)
coefficients = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]])
f = FDataBasis(monomial, coefficients)
t = np.linspace(0, 2, 11)
# Results in R package fda
res = np.array(
[[1.00, 1.56, 2.66, 4.79, 8.62, 15.00,
25.00, 39.86, 61.03, 90.14, 129.00],
[6.00, 7.81, 10.91, 16.32, 25.42, 40.00,
62.21, 94.59, 140.08, 201.98, 284.00]])[..., np.newaxis]
np.testing.assert_array_almost_equal(f(t).round(2), res)
np.testing.assert_array_almost_equal(f.evaluate(t).round(2), res)
def test_evaluation_point_monomial(self):
"""Test the evaluation of a single point FDataBasis"""
monomial = Monomial(domain_range=(0, 1), n_basis=3)
coefficients = [[1, 2, 3], [0.5, 1.4, 1.3]]
f = FDataBasis(monomial, coefficients)
# Test different ways of call f with a point
res = np.array([[2.75], [1.525]])[..., np.newaxis]
np.testing.assert_array_almost_equal(f([0.5]).round(4), res)
np.testing.assert_array_almost_equal(f((0.5,)).round(4), res)
np.testing.assert_array_almost_equal(f(0.5).round(4), res)
np.testing.assert_array_almost_equal(f(np.array([0.5])).round(4), res)
# Problematic case, should be accepted or no?
#np.testing.assert_array_almost_equal(f(np.array(0.5)).round(4), res)
def test_evaluation_derivative_monomial(self):
"""Test the evaluation of the derivative of a FDataBasis"""
monomial = Monomial(domain_range=(0, 1), n_basis=3)
coefficients = [[1, 2, 3], [0.5, 1.4, 1.3]]
f = FDataBasis(monomial, coefficients)
t = np.linspace(0, 1, 4)
f_deriv = f.derivative()
np.testing.assert_array_almost_equal(
f_deriv(t).round(3),
np.array([[2., 4., 6., 8.],
[1.4, 2.267, 3.133, 4.]])[..., np.newaxis]
)
def test_evaluation_grid_monomial(self):
"""Test the evaluation of FDataBasis with the grid option set to
true. Nothing should be change due to the domain dimension is 1,
but can accept the """
monomial = Monomial(domain_range=(0, 1), n_basis=3)
coefficients = [[1, 2, 3], [0.5, 1.4, 1.3]]
f = FDataBasis(monomial, coefficients)
t = np.linspace(0, 1, 4)
res_test = f(t)
# Different ways to pass the axes
np.testing.assert_array_almost_equal(f(t, grid=True), res_test)
np.testing.assert_array_almost_equal(f((t,), grid=True), res_test)
np.testing.assert_array_almost_equal(f([t], grid=True), res_test)
np.testing.assert_array_almost_equal(
f(np.atleast_2d(t), grid=True), res_test)
# Number of axis different than the domain dimension (1)
with np.testing.assert_raises(ValueError):
f((t, t), grid=True)
def test_evaluation_composed_monomial(self):
"""Test the evaluation of FDataBasis the a matrix of times instead of
a list of times """
monomial = Monomial(domain_range=(0, 1), n_basis=3)
coefficients = [[1, 2, 3], [0.5, 1.4, 1.3]]
f = FDataBasis(monomial, coefficients)
t = np.linspace(0, 1, 4)
# Test same result than evaluation standart
np.testing.assert_array_almost_equal(f([1]),
f([[1], [1]],
aligned=False))
np.testing.assert_array_almost_equal(f(t), f(np.vstack((t, t)),
aligned=False))
# Different evaluation times
t_multiple = [[0, 0.5], [0.2, 0.7]]
np.testing.assert_array_almost_equal(f(t_multiple[0])[0],
f(t_multiple,
aligned=False)[0])
np.testing.assert_array_almost_equal(f(t_multiple[1])[1],
f(t_multiple,
aligned=False)[1])
def test_domain_in_list_monomial(self):
"""Test the evaluation of FDataBasis"""
for monomial in (Monomial(domain_range=[(0, 1)], n_basis=3),
Monomial(domain_range=((0, 1),), n_basis=3),
Monomial(domain_range=np.array((0, 1)), n_basis=3),
Monomial(domain_range=np.array([(0, 1)]), n_basis=3)):
coefficients = [[1, 2, 3], [0.5, 1.4, 1.3]]
f = FDataBasis(monomial, coefficients)
t = np.linspace(0, 1, 4)
res = np.array([[1., 2., 3.667, 6.],
[0.5, 1.111, 2.011, 3.2]])[..., np.newaxis]
np.testing.assert_array_almost_equal(f(t).round(3), res)
np.testing.assert_array_almost_equal(f.evaluate(t).round(3), res)
class TestBasisEvaluationVectorValued(unittest.TestCase):
def test_vector_valued_constant(self):
basis_first = Constant()
basis_second = Constant()
basis = VectorValued([basis_first, basis_second])
fd = FDataBasis(basis=basis, coefficients=[[1, 2], [3, 4]])
self.assertEqual(fd.dim_codomain, 2)
res = np.array([[[1, 2]], [[3, 4]]])
np.testing.assert_allclose(fd(0), res)
def test_vector_valued_constant_monomial(self):
basis_first = Constant(domain_range=(0, 5))
basis_second = Monomial(n_basis=3, domain_range=(0, 5))
basis = VectorValued([basis_first, basis_second])
fd = FDataBasis(basis=basis, coefficients=[
[1, 2, 3, 4], [3, 4, 5, 6]])
self.assertEqual(fd.dim_codomain, 2)
np.testing.assert_allclose(fd.domain_range[0], (0, 5))
res = np.array([[[1, 2], [1, 9], [1, 24]],
[[3, 4], [3, 15], [3, 38]]])
np.testing.assert_allclose(fd([0, 1, 2]), res)
class TestBasisEvaluationTensor(unittest.TestCase):
def test_tensor_monomial_constant(self):
basis = Tensor([Monomial(n_basis=2), Constant()])
fd = FDataBasis(basis=basis, coefficients=[1, 1])
self.assertEqual(fd.dim_domain, 2)
self.assertEqual(fd.dim_codomain, 1)
np.testing.assert_allclose(fd([0., 0.]), [[[1.]]])
np.testing.assert_allclose(fd([0.5, 0.5]), [[[1.5]]])
np.testing.assert_allclose(
fd([(0., 0.), (0.5, 0.5)]), [[[1.0], [1.5]]])
fd_grid = fd.to_grid()
fd2 = fd_grid.to_basis(basis)
np.testing.assert_allclose(fd.coefficients, fd2.coefficients)
if __name__ == '__main__':
print()
unittest.main()
|
[
"unittest.main",
"skfda.representation.basis.BSpline",
"numpy.testing.assert_raises",
"skfda.representation.basis.Fourier",
"skfda.representation.basis.Constant",
"skfda.representation.basis.VectorValued",
"numpy.array",
"skfda.representation.basis.Monomial",
"numpy.linspace",
"numpy.testing.assert_allclose",
"skfda.representation.basis.FDataBasis",
"numpy.vstack",
"numpy.atleast_2d"
] |
[((18780, 18795), 'unittest.main', 'unittest.main', ([], {}), '()\n', (18793, 18795), False, 'import unittest\n'), ((322, 361), 'skfda.representation.basis.Fourier', 'Fourier', ([], {'domain_range': '(0, 2)', 'n_basis': '(5)'}), '(domain_range=(0, 2), n_basis=5)\n', (329, 361), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((386, 431), 'numpy.array', 'np.array', (['[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]'], {}), '([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])\n', (394, 431), True, 'import numpy as np\n'), ((485, 518), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['fourier', 'coefficients'], {}), '(fourier, coefficients)\n', (495, 518), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((532, 553), 'numpy.linspace', 'np.linspace', (['(0)', '(2)', '(11)'], {}), '(0, 2, 11)\n', (543, 553), True, 'import numpy as np\n'), ((1128, 1167), 'skfda.representation.basis.Fourier', 'Fourier', ([], {'domain_range': '(0, 1)', 'n_basis': '(3)'}), '(domain_range=(0, 1), n_basis=3)\n', (1135, 1167), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((1192, 1283), 'numpy.array', 'np.array', (['[[0.00078238, 0.48857741, 0.63971985], [0.01778079, 0.73440271, 0.20148638]]'], {}), '([[0.00078238, 0.48857741, 0.63971985], [0.01778079, 0.73440271, \n 0.20148638]])\n', (1200, 1283), True, 'import numpy as np\n'), ((1325, 1358), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['fourier', 'coefficients'], {}), '(fourier, coefficients)\n', (1335, 1358), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((2086, 2125), 'skfda.representation.basis.Fourier', 'Fourier', ([], {'domain_range': '(0, 1)', 'n_basis': '(3)'}), '(domain_range=(0, 1), n_basis=3)\n', (2093, 2125), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((2150, 2241), 'numpy.array', 'np.array', (['[[0.00078238, 0.48857741, 0.63971985], [0.01778079, 0.73440271, 0.20148638]]'], {}), '([[0.00078238, 0.48857741, 0.63971985], [0.01778079, 0.73440271, \n 0.20148638]])\n', (2158, 2241), True, 'import numpy as np\n'), ((2283, 2316), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['fourier', 'coefficients'], {}), '(fourier, coefficients)\n', (2293, 2316), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((2330, 2350), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (2341, 2350), True, 'import numpy as np\n'), ((2998, 3037), 'skfda.representation.basis.Fourier', 'Fourier', ([], {'domain_range': '(0, 1)', 'n_basis': '(3)'}), '(domain_range=(0, 1), n_basis=3)\n', (3005, 3037), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((3062, 3153), 'numpy.array', 'np.array', (['[[0.00078238, 0.48857741, 0.63971985], [0.01778079, 0.73440271, 0.20148638]]'], {}), '([[0.00078238, 0.48857741, 0.63971985], [0.01778079, 0.73440271, \n 0.20148638]])\n', (3070, 3153), True, 'import numpy as np\n'), ((3195, 3228), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['fourier', 'coefficients'], {}), '(fourier, coefficients)\n', (3205, 3228), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((3241, 3261), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (3252, 3261), True, 'import numpy as np\n'), ((4006, 4045), 'skfda.representation.basis.Fourier', 'Fourier', ([], {'domain_range': '(0, 1)', 'n_basis': '(3)'}), '(domain_range=(0, 1), n_basis=3)\n', (4013, 4045), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((4070, 4161), 'numpy.array', 'np.array', (['[[0.00078238, 0.48857741, 0.63971985], [0.01778079, 0.73440271, 0.20148638]]'], {}), '([[0.00078238, 0.48857741, 0.63971985], [0.01778079, 0.73440271, \n 0.20148638]])\n', (4078, 4161), True, 'import numpy as np\n'), ((4203, 4236), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['fourier', 'coefficients'], {}), '(fourier, coefficients)\n', (4213, 4236), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((4249, 4269), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (4260, 4269), True, 'import numpy as np\n'), ((6174, 6213), 'skfda.representation.basis.BSpline', 'BSpline', ([], {'domain_range': '(0, 2)', 'n_basis': '(5)'}), '(domain_range=(0, 2), n_basis=5)\n', (6181, 6213), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((6238, 6283), 'numpy.array', 'np.array', (['[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]'], {}), '([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])\n', (6246, 6283), True, 'import numpy as np\n'), ((6337, 6370), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['bspline', 'coefficients'], {}), '(bspline, coefficients)\n', (6347, 6370), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((6384, 6405), 'numpy.linspace', 'np.linspace', (['(0)', '(2)', '(11)'], {}), '(0, 2, 11)\n', (6395, 6405), True, 'import numpy as np\n'), ((6940, 6988), 'skfda.representation.basis.BSpline', 'BSpline', ([], {'domain_range': '(0, 1)', 'n_basis': '(5)', 'order': '(3)'}), '(domain_range=(0, 1), n_basis=5, order=3)\n', (6947, 6988), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((7151, 7184), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['bspline', 'coefficients'], {}), '(bspline, coefficients)\n', (7161, 7184), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((7857, 7905), 'skfda.representation.basis.BSpline', 'BSpline', ([], {'domain_range': '(0, 1)', 'n_basis': '(5)', 'order': '(3)'}), '(domain_range=(0, 1), n_basis=5, order=3)\n', (7864, 7905), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((8068, 8101), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['bspline', 'coefficients'], {}), '(bspline, coefficients)\n', (8078, 8101), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((8115, 8135), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (8126, 8135), True, 'import numpy as np\n'), ((8630, 8678), 'skfda.representation.basis.BSpline', 'BSpline', ([], {'domain_range': '(0, 1)', 'n_basis': '(5)', 'order': '(3)'}), '(domain_range=(0, 1), n_basis=5, order=3)\n', (8637, 8678), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((8841, 8874), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['bspline', 'coefficients'], {}), '(bspline, coefficients)\n', (8851, 8874), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((8887, 8907), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (8898, 8907), True, 'import numpy as np\n'), ((9620, 9668), 'skfda.representation.basis.BSpline', 'BSpline', ([], {'domain_range': '(0, 1)', 'n_basis': '(5)', 'order': '(3)'}), '(domain_range=(0, 1), n_basis=5, order=3)\n', (9627, 9668), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((9831, 9864), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['bspline', 'coefficients'], {}), '(bspline, coefficients)\n', (9841, 9864), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((9877, 9897), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (9888, 9897), True, 'import numpy as np\n'), ((12061, 12101), 'skfda.representation.basis.Monomial', 'Monomial', ([], {'domain_range': '(0, 2)', 'n_basis': '(5)'}), '(domain_range=(0, 2), n_basis=5)\n', (12069, 12101), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((12126, 12171), 'numpy.array', 'np.array', (['[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]'], {}), '([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])\n', (12134, 12171), True, 'import numpy as np\n'), ((12225, 12259), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['monomial', 'coefficients'], {}), '(monomial, coefficients)\n', (12235, 12259), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((12273, 12294), 'numpy.linspace', 'np.linspace', (['(0)', '(2)', '(11)'], {}), '(0, 2, 11)\n', (12284, 12294), True, 'import numpy as np\n'), ((12851, 12891), 'skfda.representation.basis.Monomial', 'Monomial', ([], {'domain_range': '(0, 1)', 'n_basis': '(3)'}), '(domain_range=(0, 1), n_basis=3)\n', (12859, 12891), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((12958, 12992), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['monomial', 'coefficients'], {}), '(monomial, coefficients)\n', (12968, 12992), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((13664, 13704), 'skfda.representation.basis.Monomial', 'Monomial', ([], {'domain_range': '(0, 1)', 'n_basis': '(3)'}), '(domain_range=(0, 1), n_basis=3)\n', (13672, 13704), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((13771, 13805), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['monomial', 'coefficients'], {}), '(monomial, coefficients)\n', (13781, 13805), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((13819, 13839), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (13830, 13839), True, 'import numpy as np\n'), ((14318, 14358), 'skfda.representation.basis.Monomial', 'Monomial', ([], {'domain_range': '(0, 1)', 'n_basis': '(3)'}), '(domain_range=(0, 1), n_basis=3)\n', (14326, 14358), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((14425, 14459), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['monomial', 'coefficients'], {}), '(monomial, coefficients)\n', (14435, 14459), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((14472, 14492), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (14483, 14492), True, 'import numpy as np\n'), ((15207, 15247), 'skfda.representation.basis.Monomial', 'Monomial', ([], {'domain_range': '(0, 1)', 'n_basis': '(3)'}), '(domain_range=(0, 1), n_basis=3)\n', (15215, 15247), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((15314, 15348), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['monomial', 'coefficients'], {}), '(monomial, coefficients)\n', (15324, 15348), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((15361, 15381), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (15372, 15381), True, 'import numpy as np\n'), ((17149, 17159), 'skfda.representation.basis.Constant', 'Constant', ([], {}), '()\n', (17157, 17159), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((17183, 17193), 'skfda.representation.basis.Constant', 'Constant', ([], {}), '()\n', (17191, 17193), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((17211, 17252), 'skfda.representation.basis.VectorValued', 'VectorValued', (['[basis_first, basis_second]'], {}), '([basis_first, basis_second])\n', (17223, 17252), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((17267, 17321), 'skfda.representation.basis.FDataBasis', 'FDataBasis', ([], {'basis': 'basis', 'coefficients': '[[1, 2], [3, 4]]'}), '(basis=basis, coefficients=[[1, 2], [3, 4]])\n', (17277, 17321), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((17383, 17413), 'numpy.array', 'np.array', (['[[[1, 2]], [[3, 4]]]'], {}), '([[[1, 2]], [[3, 4]]])\n', (17391, 17413), True, 'import numpy as np\n'), ((17538, 17567), 'skfda.representation.basis.Constant', 'Constant', ([], {'domain_range': '(0, 5)'}), '(domain_range=(0, 5))\n', (17546, 17567), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((17591, 17631), 'skfda.representation.basis.Monomial', 'Monomial', ([], {'n_basis': '(3)', 'domain_range': '(0, 5)'}), '(n_basis=3, domain_range=(0, 5))\n', (17599, 17631), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((17649, 17690), 'skfda.representation.basis.VectorValued', 'VectorValued', (['[basis_first, basis_second]'], {}), '([basis_first, basis_second])\n', (17661, 17690), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((17705, 17771), 'skfda.representation.basis.FDataBasis', 'FDataBasis', ([], {'basis': 'basis', 'coefficients': '[[1, 2, 3, 4], [3, 4, 5, 6]]'}), '(basis=basis, coefficients=[[1, 2, 3, 4], [3, 4, 5, 6]])\n', (17715, 17771), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((17852, 17906), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['fd.domain_range[0]', '(0, 5)'], {}), '(fd.domain_range[0], (0, 5))\n', (17878, 17906), True, 'import numpy as np\n'), ((17922, 17987), 'numpy.array', 'np.array', (['[[[1, 2], [1, 9], [1, 24]], [[3, 4], [3, 15], [3, 38]]]'], {}), '([[[1, 2], [1, 9], [1, 24]], [[3, 4], [3, 15], [3, 38]]])\n', (17930, 17987), True, 'import numpy as np\n'), ((18241, 18285), 'skfda.representation.basis.FDataBasis', 'FDataBasis', ([], {'basis': 'basis', 'coefficients': '[1, 1]'}), '(basis=basis, coefficients=[1, 1])\n', (18251, 18285), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((18673, 18734), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['fd.coefficients', 'fd2.coefficients'], {}), '(fd.coefficients, fd2.coefficients)\n', (18699, 18734), True, 'import numpy as np\n'), ((604, 772), 'numpy.array', 'np.array', (['[[8.71, 9.66, 1.84, -4.71, -2.8, 2.71, 2.45, -3.82, -6.66, -0.3, 8.71], [\n 22.24, 26.48, 10.57, -4.95, -3.58, 6.24, 5.31, -7.69, -13.32, 1.13, 22.24]]'], {}), '([[8.71, 9.66, 1.84, -4.71, -2.8, 2.71, 2.45, -3.82, -6.66, -0.3, \n 8.71], [22.24, 26.48, 10.57, -4.95, -3.58, 6.24, 5.31, -7.69, -13.32, \n 1.13, 22.24]])\n', (612, 772), True, 'import numpy as np\n'), ((3762, 3798), 'numpy.testing.assert_raises', 'np.testing.assert_raises', (['ValueError'], {}), '(ValueError)\n', (3786, 3798), True, 'import numpy as np\n'), ((5219, 5260), 'skfda.representation.basis.Fourier', 'Fourier', ([], {'domain_range': '[(0, 1)]', 'n_basis': '(3)'}), '(domain_range=[(0, 1)], n_basis=3)\n', (5226, 5260), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((5286, 5328), 'skfda.representation.basis.Fourier', 'Fourier', ([], {'domain_range': '((0, 1),)', 'n_basis': '(3)'}), '(domain_range=((0, 1),), n_basis=3)\n', (5293, 5328), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((5511, 5602), 'numpy.array', 'np.array', (['[[0.00078238, 0.48857741, 0.63971985], [0.01778079, 0.73440271, 0.20148638]]'], {}), '([[0.00078238, 0.48857741, 0.63971985], [0.01778079, 0.73440271, \n 0.20148638]])\n', (5519, 5602), True, 'import numpy as np\n'), ((5652, 5685), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['fourier', 'coefficients'], {}), '(fourier, coefficients)\n', (5662, 5685), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((5703, 5723), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (5714, 5723), True, 'import numpy as np\n'), ((6456, 6585), 'numpy.array', 'np.array', (['[[1, 1.54, 1.99, 2.37, 2.7, 3, 3.3, 3.63, 4.01, 4.46, 5], [6, 6.54, 6.99, \n 7.37, 7.7, 8, 8.3, 8.63, 9.01, 9.46, 10]]'], {}), '([[1, 1.54, 1.99, 2.37, 2.7, 3, 3.3, 3.63, 4.01, 4.46, 5], [6, 6.54,\n 6.99, 7.37, 7.7, 8, 8.3, 8.63, 9.01, 9.46, 10]])\n', (6464, 6585), True, 'import numpy as np\n'), ((7253, 7283), 'numpy.array', 'np.array', (['[[0.5696], [0.3104]]'], {}), '([[0.5696], [0.3104]])\n', (7261, 7283), True, 'import numpy as np\n'), ((9376, 9412), 'numpy.testing.assert_raises', 'np.testing.assert_raises', (['ValueError'], {}), '(ValueError)\n', (9400, 9412), True, 'import numpy as np\n'), ((10848, 10898), 'skfda.representation.basis.BSpline', 'BSpline', ([], {'domain_range': '[(0, 1)]', 'n_basis': '(5)', 'order': '(3)'}), '(domain_range=[(0, 1)], n_basis=5, order=3)\n', (10855, 10898), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((10924, 10975), 'skfda.representation.basis.BSpline', 'BSpline', ([], {'domain_range': '((0, 1),)', 'n_basis': '(5)', 'order': '(3)'}), '(domain_range=((0, 1),), n_basis=5, order=3)\n', (10931, 10975), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((11411, 11444), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['bspline', 'coefficients'], {}), '(bspline, coefficients)\n', (11421, 11444), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((11462, 11482), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (11473, 11482), True, 'import numpy as np\n'), ((11800, 11836), 'numpy.testing.assert_raises', 'np.testing.assert_raises', (['ValueError'], {}), '(ValueError)\n', (11824, 11836), True, 'import numpy as np\n'), ((11850, 11888), 'skfda.representation.basis.BSpline', 'BSpline', ([], {'domain_range': '[(0, 1), (0, 1)]'}), '(domain_range=[(0, 1), (0, 1)])\n', (11857, 11888), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((12345, 12513), 'numpy.array', 'np.array', (['[[1.0, 1.56, 2.66, 4.79, 8.62, 15.0, 25.0, 39.86, 61.03, 90.14, 129.0], [\n 6.0, 7.81, 10.91, 16.32, 25.42, 40.0, 62.21, 94.59, 140.08, 201.98, 284.0]]'], {}), '([[1.0, 1.56, 2.66, 4.79, 8.62, 15.0, 25.0, 39.86, 61.03, 90.14, \n 129.0], [6.0, 7.81, 10.91, 16.32, 25.42, 40.0, 62.21, 94.59, 140.08, \n 201.98, 284.0]])\n', (12353, 12513), True, 'import numpy as np\n'), ((13061, 13088), 'numpy.array', 'np.array', (['[[2.75], [1.525]]'], {}), '([[2.75], [1.525]])\n', (13069, 13088), True, 'import numpy as np\n'), ((14961, 14997), 'numpy.testing.assert_raises', 'np.testing.assert_raises', (['ValueError'], {}), '(ValueError)\n', (14985, 14997), True, 'import numpy as np\n'), ((16334, 16376), 'skfda.representation.basis.Monomial', 'Monomial', ([], {'domain_range': '[(0, 1)]', 'n_basis': '(3)'}), '(domain_range=[(0, 1)], n_basis=3)\n', (16342, 16376), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((16403, 16446), 'skfda.representation.basis.Monomial', 'Monomial', ([], {'domain_range': '((0, 1),)', 'n_basis': '(3)'}), '(domain_range=((0, 1),), n_basis=3)\n', (16411, 16446), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((16679, 16713), 'skfda.representation.basis.FDataBasis', 'FDataBasis', (['monomial', 'coefficients'], {}), '(monomial, coefficients)\n', (16689, 16713), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((16731, 16751), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(4)'], {}), '(0, 1, 4)\n', (16742, 16751), True, 'import numpy as np\n'), ((3598, 3614), 'numpy.atleast_2d', 'np.atleast_2d', (['t'], {}), '(t)\n', (3611, 3614), True, 'import numpy as np\n'), ((4551, 4568), 'numpy.vstack', 'np.vstack', (['(t, t)'], {}), '((t, t))\n', (4560, 4568), True, 'import numpy as np\n'), ((8261, 8329), 'numpy.array', 'np.array', (['[[2.927, 0.453, -1.229, 0.6], [4.3, -1.599, 1.016, -2.52]]'], {}), '([[2.927, 0.453, -1.229, 0.6], [4.3, -1.599, 1.016, -2.52]])\n', (8269, 8329), True, 'import numpy as np\n'), ((9257, 9273), 'numpy.atleast_2d', 'np.atleast_2d', (['t'], {}), '(t)\n', (9270, 9273), True, 'import numpy as np\n'), ((10179, 10196), 'numpy.vstack', 'np.vstack', (['(t, t)'], {}), '((t, t))\n', (10188, 10196), True, 'import numpy as np\n'), ((11502, 11570), 'numpy.array', 'np.array', (['[[0.001, 0.564, 0.435, 0.33], [0.018, 0.468, 0.371, 0.12]]'], {}), '([[0.001, 0.564, 0.435, 0.33], [0.018, 0.468, 0.371, 0.12]])\n', (11510, 11570), True, 'import numpy as np\n'), ((13965, 14023), 'numpy.array', 'np.array', (['[[2.0, 4.0, 6.0, 8.0], [1.4, 2.267, 3.133, 4.0]]'], {}), '([[2.0, 4.0, 6.0, 8.0], [1.4, 2.267, 3.133, 4.0]])\n', (13973, 14023), True, 'import numpy as np\n'), ((14842, 14858), 'numpy.atleast_2d', 'np.atleast_2d', (['t'], {}), '(t)\n', (14855, 14858), True, 'import numpy as np\n'), ((15663, 15680), 'numpy.vstack', 'np.vstack', (['(t, t)'], {}), '((t, t))\n', (15672, 15680), True, 'import numpy as np\n'), ((16771, 16831), 'numpy.array', 'np.array', (['[[1.0, 2.0, 3.667, 6.0], [0.5, 1.111, 2.011, 3.2]]'], {}), '([[1.0, 2.0, 3.667, 6.0], [0.5, 1.111, 2.011, 3.2]])\n', (16779, 16831), True, 'import numpy as np\n'), ((18193, 18212), 'skfda.representation.basis.Monomial', 'Monomial', ([], {'n_basis': '(2)'}), '(n_basis=2)\n', (18201, 18212), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((18214, 18224), 'skfda.representation.basis.Constant', 'Constant', ([], {}), '()\n', (18222, 18224), False, 'from skfda.representation.basis import FDataBasis, Monomial, BSpline, Fourier, Constant, VectorValued, Tensor\n'), ((5375, 5391), 'numpy.array', 'np.array', (['(0, 1)'], {}), '((0, 1))\n', (5383, 5391), True, 'import numpy as np\n'), ((5450, 5468), 'numpy.array', 'np.array', (['[(0, 1)]'], {}), '([(0, 1)])\n', (5458, 5468), True, 'import numpy as np\n'), ((5743, 5810), 'numpy.array', 'np.array', (['[0.905, 0.147, -1.05, 0.905, 0.303, 0.775, -1.024, 0.303]'], {}), '([0.905, 0.147, -1.05, 0.905, 0.303, 0.775, -1.024, 0.303])\n', (5751, 5810), True, 'import numpy as np\n'), ((11022, 11038), 'numpy.array', 'np.array', (['(0, 1)'], {}), '((0, 1))\n', (11030, 11038), True, 'import numpy as np\n'), ((11138, 11156), 'numpy.array', 'np.array', (['[(0, 1)]'], {}), '([(0, 1)])\n', (11146, 11156), True, 'import numpy as np\n'), ((16495, 16511), 'numpy.array', 'np.array', (['(0, 1)'], {}), '((0, 1))\n', (16503, 16511), True, 'import numpy as np\n'), ((16572, 16590), 'numpy.array', 'np.array', (['[(0, 1)]'], {}), '([(0, 1)])\n', (16580, 16590), True, 'import numpy as np\n'), ((1427, 1477), 'numpy.array', 'np.array', (['[-0.903918107989282, -0.267163981229459]'], {}), '([-0.903918107989282, -0.267163981229459])\n', (1435, 1477), True, 'import numpy as np\n'), ((1784, 1799), 'numpy.array', 'np.array', (['[0.5]'], {}), '([0.5])\n', (1792, 1799), True, 'import numpy as np\n'), ((2366, 2531), 'numpy.array', 'np.array', (['[4.34138447771721, -7.09352774867064, 2.75214327095343, 4.34138447771721, \n 6.52573053999253, -4.81336320468984, -1.7123673353027, 6.52573053999253]'], {}), '([4.34138447771721, -7.09352774867064, 2.75214327095343, \n 4.34138447771721, 6.52573053999253, -4.81336320468984, -1.7123673353027,\n 6.52573053999253])\n', (2374, 2531), True, 'import numpy as np\n'), ((7555, 7570), 'numpy.array', 'np.array', (['[0.5]'], {}), '([0.5])\n', (7563, 7570), True, 'import numpy as np\n'), ((13360, 13375), 'numpy.array', 'np.array', (['[0.5]'], {}), '([0.5])\n', (13368, 13375), True, 'import numpy as np\n')]
|
# Fichier permettant de moduler les differentes methodes de clustering
try:
# Import generaux
import numpy as np
import pylab
import sys
import platform
import matplotlib.pyplot as plt
import re
# Import locaux
import kmeans
import rkde
except:
exit(1)
""" Clustering """
# Clusterise les donnees avec la methode desiree
# Entree :
# - M : la matrice des distances entre les objets
# - methode : une chaine de caractere donnant le nom de la methode (nom de module)
# - params : une liste des parametres requis pour la methode demandee
# - kmeans : params = [k, n_iter]
# - rkde : params = [bandwidth, prob]
# Sortie :
# - assign : un tableau donnant pour chaque entier (objet) son numero de cluster
# - nb_cluster : le nombre de clusters formes
def make_clusters(M, methode, params):
function = methode + ".do"
assign, nb_clusters = eval(function)(M, params[0], params[1])
return assign, nb_clusters
""" Lecture et affichage de donnees """
# Fonction de lecture dans un fichier
# Entree :
# - file_name : une chaine de caracteres donnant le nom du fichier a ouvrir
# - nb_item : nombre de lignes a lire (-1 pour tout lire, defaut a -1)
# Sortie :
# - data : une liste de liste de flottants
def read_data(file_name, nb_item = -1):
f = open(file_name,'r')
data = []
cpt = 0
for line in f:
if (0 <= nb_item and nb_item <= cpt):
break
line = re.split('\s+', line) # '\s' matches whitespace characters
line = [float(x) for x in line if x != '']
data.append(line)
cpt += 1
f.close()
return data
# Fonction d'affichage d'un nuage de points
# Entree :
# - data : un ensemble de points sous la forme d'une matrice de taille n*2
# - assign : un tableau de taille n representant une assignation de [data]
def show(data, assign):
colors = "bgrcmyk"
symbols = ".ov18sp*h+xD_"
nb_clusters = max(assign) + 1
pylab.figure()
mini = min( min(data[:][0]), min(data[:][1]) )
maxi = max( max(data[i][0]), max(data[i][1]) )
pylab.xlim([mini, maxi])
pylab.ylim([mini, maxi])
if (nb_clusters < 8):
for i_k in range(nb_clusters):
pylab.plot([data[i][0] for i in range(len(data)) if assign[i] == i_k],
[data[i][1] for i in range(len(data)) if assign[i] == i_k],
colors[i_k] + ".")
else:
for i_k in range(nb_clusters):
pylab.plot( [data[i][0] for i in range(len(data)) if assign[i] == i_k],
[data[i][1] for i in range(len(data)) if assign[i] == i_k],
colors[i_k % 7]) + symbols[int(i_k / 7)]
pylab.show()
""" Lecture et ecriture d'une assignation """
# Lis un fichier ou est inscrit une assignation.
# Entree :
# - file : adresse et nom du fichier
# Sortie :
# - assign : un vecteur numpy d'entiers
def read_assign(file_name):
f = open(file_name,'r')
assign_tmp = []
i = 0
for line in f:
try:
assign_tmp.append(int(line))
i = i + 1
except ValueError:
continue
f.close()
return np.array(assign_tmp)
# Ecris une assignation dans un fichier
# Entree :
# - file_name : adresse et nom d'un fichier
# - assign : l'assignation a ecrire
# - nb_iter : le nombre d'iterations faites par l'algorithme (-1) s'il n'est pas
# base sur ce principe
# - s : la seed utilisee pour le clustering
def write_cluster(file_name, assign, nb_iter, s):
nb_data = len(assign)
nb_cluster = max(assign) + 1
f = open(file_name, 'w')
f.write('nb_cluster = ' + str(nb_cluster) + '\n')
f.write('nb_iter = ' + str(nb_iter) + '\n')
f.write('nb_data = ' + str(nb_data) + '\n')
f.write('seed = ' + str(s) + '\n')
for i in assign:
f.write(str(i) + '\n')
f.close()
""" Fonctions non encore retravaillees """
# Fonction pour enregistrer des images :
# data_file = fichier contenant les donnees
# assign_file = fichier cree a partir du clustering et contenant la table d'assignation
# file_figure = nom du fichier dans lequel sera enregistre l'image
# format = nom de l'extention du fichier cree (pdf,svg,png...)
# exemple : save('cercles/cercles.txt', 'cercles_kmeans', 'figure_cercles_kmeans', 'pdf')
def save(data_file, assign_file,file_figure,format):
data = read_data(data_file)
assign = read_assign(data,assign_file)
nombre_clusters = numpy.amax(assign) +1
plt.ioff()
fig = plt.figure()
colors = "bgrcmyk"
symbols = ".ov18sp*h+xD_"
mini = min( min([data[i][0] for i in range(len(data))]), min([data[i][1] for i in range(len(data))]) )
maxi = max( max([data[i][0] for i in range(len(data))]), max([data[i][1] for i in range(len(data))]) )
plt.xlim([mini, maxi])
plt.ylim([mini, maxi])
if (nombre_clusters < 8):
for i_k in range(nombre_clusters):
plt.plot([data[i][0] for i in range(len(data)) if assign[i] == i_k],
[data[i][1] for i in range(len(data)) if assign[i] == i_k],
colors[i_k] + ".")
else:
if (nombre_clusters < 85):
for i_k in range(nombre_clusters):
plt.plot( [data[i][0] for i in range(len(data)) if assign[i] == i_k],
[data[i][1] for i in range(len(data)) if assign[i] == i_k],
colors[i_k % 7] + symbols[int(i_k / 7)] )
else:
print("too many clusters")
if (platform.system() == "Windows"):
plt.savefig('C:/users/alex/documents/Alex/Cours/ENS/M1_Cours/Projet/data/Results/'+file_figure+'.'+format)
else:
plt.savefig('../data/Results/'+file_figure+'.'+format)
plt.close(fig)
|
[
"matplotlib.pyplot.xlim",
"pylab.show",
"re.split",
"matplotlib.pyplot.ioff",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"numpy.array",
"pylab.figure",
"pylab.ylim",
"platform.system",
"pylab.xlim",
"matplotlib.pyplot.savefig"
] |
[((2035, 2049), 'pylab.figure', 'pylab.figure', ([], {}), '()\n', (2047, 2049), False, 'import pylab\n'), ((2159, 2183), 'pylab.xlim', 'pylab.xlim', (['[mini, maxi]'], {}), '([mini, maxi])\n', (2169, 2183), False, 'import pylab\n'), ((2189, 2213), 'pylab.ylim', 'pylab.ylim', (['[mini, maxi]'], {}), '([mini, maxi])\n', (2199, 2213), False, 'import pylab\n'), ((2758, 2770), 'pylab.show', 'pylab.show', ([], {}), '()\n', (2768, 2770), False, 'import pylab\n'), ((3256, 3276), 'numpy.array', 'np.array', (['assign_tmp'], {}), '(assign_tmp)\n', (3264, 3276), True, 'import numpy as np\n'), ((4658, 4668), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (4666, 4668), True, 'import matplotlib.pyplot as plt\n'), ((4680, 4692), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4690, 4692), True, 'import matplotlib.pyplot as plt\n'), ((4969, 4991), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[mini, maxi]'], {}), '([mini, maxi])\n', (4977, 4991), True, 'import matplotlib.pyplot as plt\n'), ((4997, 5019), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[mini, maxi]'], {}), '([mini, maxi])\n', (5005, 5019), True, 'import matplotlib.pyplot as plt\n'), ((5915, 5929), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (5924, 5929), True, 'import matplotlib.pyplot as plt\n'), ((1516, 1538), 're.split', 're.split', (['"""\\\\s+"""', 'line'], {}), "('\\\\s+', line)\n", (1524, 1538), False, 'import re\n'), ((5685, 5702), 'platform.system', 'platform.system', ([], {}), '()\n', (5700, 5702), False, 'import platform\n'), ((5727, 5848), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('C:/users/alex/documents/Alex/Cours/ENS/M1_Cours/Projet/data/Results/' +\n file_figure + '.' + format)"], {}), "(\n 'C:/users/alex/documents/Alex/Cours/ENS/M1_Cours/Projet/data/Results/' +\n file_figure + '.' + format)\n", (5738, 5848), True, 'import matplotlib.pyplot as plt\n'), ((5855, 5915), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('../data/Results/' + file_figure + '.' + format)"], {}), "('../data/Results/' + file_figure + '.' + format)\n", (5866, 5915), True, 'import matplotlib.pyplot as plt\n')]
|
# -*- coding: utf-8 -*-
"""
Flatten mesh using conformal mapping
=============================================
Map 3D mesh to a 2D (complex) plane with angle-preserving (conformal) mapping
Based on these course notes
https://www.cs.cmu.edu/~kmcrane/Projects/DDG/
section 7.4.
"""
import numpy as np
from bfieldtools.flatten_mesh import flatten_mesh
from bfieldtools.flatten_mesh import mesh2plane
from bfieldtools.flatten_mesh import plane2mesh
from bfieldtools.utils import load_example_mesh
#%% Determine 2D parameterization and plot coordinate function on the 3D mesh
from mayavi import mlab
from bfieldtools.viz import plot_data_on_vertices, plot_mesh, plot_data_on_faces
mesh = load_example_mesh("meg_helmet", process=False)
u, v, mesh2d = flatten_mesh(mesh, _lambda=0.80)
plot_data_on_vertices(mesh, u, ncolors=15)
plot_data_on_vertices(mesh, v, ncolors=15)
#%% Determine lambda with smallest area distortion
# lls = np.linspace(0.01,1.0, 100)
# mm = []
# for ll in lls:
# u, v, mesh2d = flatten_mesh(mesh, _lambda=ll)
# d = mesh2d.area_faces / mesh.area_faces
# mm.append(np.std(d)/np.mean(d))
# print(np.std(d)/np.mean(d))
# plt.plot(lls, mm)
#%% Plot flattened mesh and area distortion on faces
plot_data_on_faces(mesh2d, mesh2d.area_faces / mesh.area_faces)
#%% Plot gradient of the two coordinate functions and the cosine of the angle between the gradients
from bfieldtools.mesh_calculus import gradient
gx = gradient(u, mesh)
gy = gradient(v, mesh)
cos = np.sum(gx * gy, axis=0) / (
np.linalg.norm(gx, axis=0) * np.linalg.norm(gy, axis=0)
)
plot_data_on_faces(mesh, cos, vmin=-1, vmax=1)
mlab.quiver3d(*mesh.triangles_center.T, *gx, color=(1, 0, 0), mode="arrow")
q = mlab.quiver3d(*mesh.triangles_center.T, *gy, color=(0, 0, 1), mode="arrow")
q.scene.isometric_view()
#%% Map hexagonal grid from 2d to the 3D mesh
d = np.sqrt(3 / 4)
m = np.min((u.min(), v.min()))
mm = np.min((u.max(), v.max()))
xx = np.linspace(m * 1.05, mm * 1.05, 12)
yy = np.linspace(m * 1.05, mm * 1.05, 12) * d
p = np.array(np.meshgrid(xx, yy, 0, indexing="ij"))
p[0, :, ::2] += (xx[1] - xx[0]) * 0.5
p = p.reshape(3, -1).T
pp = plane2mesh(p, mesh, u, v)
plot_data_on_vertices(mesh, u, ncolors=15)
mlab.points3d(*pp.T, scale_factor=0.01)
|
[
"bfieldtools.mesh_calculus.gradient",
"numpy.meshgrid",
"numpy.sum",
"mayavi.mlab.quiver3d",
"bfieldtools.flatten_mesh.flatten_mesh",
"bfieldtools.viz.plot_data_on_faces",
"mayavi.mlab.points3d",
"bfieldtools.utils.load_example_mesh",
"bfieldtools.viz.plot_data_on_vertices",
"numpy.linspace",
"bfieldtools.flatten_mesh.plane2mesh",
"numpy.linalg.norm",
"numpy.sqrt"
] |
[((712, 758), 'bfieldtools.utils.load_example_mesh', 'load_example_mesh', (['"""meg_helmet"""'], {'process': '(False)'}), "('meg_helmet', process=False)\n", (729, 758), False, 'from bfieldtools.utils import load_example_mesh\n'), ((775, 806), 'bfieldtools.flatten_mesh.flatten_mesh', 'flatten_mesh', (['mesh'], {'_lambda': '(0.8)'}), '(mesh, _lambda=0.8)\n', (787, 806), False, 'from bfieldtools.flatten_mesh import flatten_mesh\n'), ((811, 853), 'bfieldtools.viz.plot_data_on_vertices', 'plot_data_on_vertices', (['mesh', 'u'], {'ncolors': '(15)'}), '(mesh, u, ncolors=15)\n', (832, 853), False, 'from bfieldtools.viz import plot_data_on_vertices, plot_mesh, plot_data_on_faces\n'), ((855, 897), 'bfieldtools.viz.plot_data_on_vertices', 'plot_data_on_vertices', (['mesh', 'v'], {'ncolors': '(15)'}), '(mesh, v, ncolors=15)\n', (876, 897), False, 'from bfieldtools.viz import plot_data_on_vertices, plot_mesh, plot_data_on_faces\n'), ((1269, 1332), 'bfieldtools.viz.plot_data_on_faces', 'plot_data_on_faces', (['mesh2d', '(mesh2d.area_faces / mesh.area_faces)'], {}), '(mesh2d, mesh2d.area_faces / mesh.area_faces)\n', (1287, 1332), False, 'from bfieldtools.viz import plot_data_on_vertices, plot_mesh, plot_data_on_faces\n'), ((1492, 1509), 'bfieldtools.mesh_calculus.gradient', 'gradient', (['u', 'mesh'], {}), '(u, mesh)\n', (1500, 1509), False, 'from bfieldtools.mesh_calculus import gradient\n'), ((1516, 1533), 'bfieldtools.mesh_calculus.gradient', 'gradient', (['v', 'mesh'], {}), '(v, mesh)\n', (1524, 1533), False, 'from bfieldtools.mesh_calculus import gradient\n'), ((1634, 1680), 'bfieldtools.viz.plot_data_on_faces', 'plot_data_on_faces', (['mesh', 'cos'], {'vmin': '(-1)', 'vmax': '(1)'}), '(mesh, cos, vmin=-1, vmax=1)\n', (1652, 1680), False, 'from bfieldtools.viz import plot_data_on_vertices, plot_mesh, plot_data_on_faces\n'), ((1682, 1757), 'mayavi.mlab.quiver3d', 'mlab.quiver3d', (['*mesh.triangles_center.T', '*gx'], {'color': '(1, 0, 0)', 'mode': '"""arrow"""'}), "(*mesh.triangles_center.T, *gx, color=(1, 0, 0), mode='arrow')\n", (1695, 1757), False, 'from mayavi import mlab\n'), ((1763, 1838), 'mayavi.mlab.quiver3d', 'mlab.quiver3d', (['*mesh.triangles_center.T', '*gy'], {'color': '(0, 0, 1)', 'mode': '"""arrow"""'}), "(*mesh.triangles_center.T, *gy, color=(0, 0, 1), mode='arrow')\n", (1776, 1838), False, 'from mayavi import mlab\n'), ((1919, 1933), 'numpy.sqrt', 'np.sqrt', (['(3 / 4)'], {}), '(3 / 4)\n', (1926, 1933), True, 'import numpy as np\n'), ((2005, 2041), 'numpy.linspace', 'np.linspace', (['(m * 1.05)', '(mm * 1.05)', '(12)'], {}), '(m * 1.05, mm * 1.05, 12)\n', (2016, 2041), True, 'import numpy as np\n'), ((2215, 2240), 'bfieldtools.flatten_mesh.plane2mesh', 'plane2mesh', (['p', 'mesh', 'u', 'v'], {}), '(p, mesh, u, v)\n', (2225, 2240), False, 'from bfieldtools.flatten_mesh import plane2mesh\n'), ((2244, 2286), 'bfieldtools.viz.plot_data_on_vertices', 'plot_data_on_vertices', (['mesh', 'u'], {'ncolors': '(15)'}), '(mesh, u, ncolors=15)\n', (2265, 2286), False, 'from bfieldtools.viz import plot_data_on_vertices, plot_mesh, plot_data_on_faces\n'), ((2288, 2327), 'mayavi.mlab.points3d', 'mlab.points3d', (['*pp.T'], {'scale_factor': '(0.01)'}), '(*pp.T, scale_factor=0.01)\n', (2301, 2327), False, 'from mayavi import mlab\n'), ((1541, 1564), 'numpy.sum', 'np.sum', (['(gx * gy)'], {'axis': '(0)'}), '(gx * gy, axis=0)\n', (1547, 1564), True, 'import numpy as np\n'), ((2048, 2084), 'numpy.linspace', 'np.linspace', (['(m * 1.05)', '(mm * 1.05)', '(12)'], {}), '(m * 1.05, mm * 1.05, 12)\n', (2059, 2084), True, 'import numpy as np\n'), ((2103, 2140), 'numpy.meshgrid', 'np.meshgrid', (['xx', 'yy', '(0)'], {'indexing': '"""ij"""'}), "(xx, yy, 0, indexing='ij')\n", (2114, 2140), True, 'import numpy as np\n'), ((1574, 1600), 'numpy.linalg.norm', 'np.linalg.norm', (['gx'], {'axis': '(0)'}), '(gx, axis=0)\n', (1588, 1600), True, 'import numpy as np\n'), ((1603, 1629), 'numpy.linalg.norm', 'np.linalg.norm', (['gy'], {'axis': '(0)'}), '(gy, axis=0)\n', (1617, 1629), True, 'import numpy as np\n')]
|
import numpy as np
from tqdm import tqdm
from typing import Dict, Union
import torch
import gtimer as gt
import matplotlib
from matplotlib import pyplot as plt
import self_supervised.utils.typed_dicts as td
from self_supervised.base.data_collector.data_collector import \
PathCollectorSelfSupervised
from self_sup_comb_discrete_skills.data_collector.path_collector_discrete_skills import \
PathCollectorSelfSupervisedDiscreteSkills
from self_supervised.memory.self_sup_replay_buffer import \
SelfSupervisedEnvSequenceReplayBuffer
from self_supervised.env_wrapper.rlkit_wrapper import NormalizedBoxEnvWrapper
from self_supervised.base.algo.algo_base import BaseRLAlgorithmSelfSup
from self_supervised.utils.writer import MyWriterWithActivation
import self_sup_combined.utils.typed_dicts as tdssc
from self_sup_combined.base.writer.diagnostics_writer import DiagnosticsWriter
from self_sup_combined.algo.trainer_sac import SelfSupCombSACTrainer
from self_sup_combined.algo.trainer_mode import ModeTrainer
from self_sup_combined.algo.algorithm import SelfSupCombAlgo
from self_sup_comb_discrete_skills.algo.mode_trainer_discrete_skill import \
ModeTrainerWithDiagnosticsDiscrete
from self_sup_comb_discrete_skills.memory.replay_buffer_discrete_skills import \
SelfSupervisedEnvSequenceReplayBufferDiscreteSkills
import self_sup_comb_discrete_skills.utils.typed_dicts as tdsscds
import rlkit.torch.pytorch_util as ptu
from rlkit.core import logger, eval_util
from rlkit.core.rl_algorithm import _get_epoch_timings
matplotlib.use('Agg')
class SelfSupCombAlgoDiscrete(SelfSupCombAlgo):
def __init__(self,
sac_trainer: SelfSupCombSACTrainer,
mode_trainer: ModeTrainerWithDiagnosticsDiscrete,
exploration_env: NormalizedBoxEnvWrapper,
evaluation_env: NormalizedBoxEnvWrapper,
exploration_data_collector: PathCollectorSelfSupervisedDiscreteSkills,
evaluation_data_collector: PathCollectorSelfSupervisedDiscreteSkills,
replay_buffer: SelfSupervisedEnvSequenceReplayBufferDiscreteSkills,
diangnostic_writer: DiagnosticsWriter,
**kwargs
):
super().__init__(
sac_trainer=sac_trainer,
mode_trainer=mode_trainer,
exploration_env=exploration_env,
evaluation_env=evaluation_env,
exploration_data_collector=exploration_data_collector,
evaluation_data_collector=evaluation_data_collector,
replay_buffer=replay_buffer,
**kwargs
)
self.mode_dim = self.mode_trainer.model.mode_dim
self.num_skills = self.mode_trainer.num_skills
self.skill_idx_now = 0
assert type(self.mode_trainer) == ModeTrainerWithDiagnosticsDiscrete
self.discrete_skills = self.get_grid()
self.diagnostic_writer = diangnostic_writer
def _train_mode(self,
train_data: td.TransitonModeMappingDiscreteSkills
):
self.mode_trainer.train(
data=tdsscds.ModeTrainerDataMappingDiscreteSkills(
skills_gt=ptu.from_numpy(train_data.mode),
obs_seq=ptu.from_numpy(train_data.obs),
skill_id=ptu.from_numpy(train_data.skill_id)
)
)
def set_next_skill(self,
path_collector: PathCollectorSelfSupervisedDiscreteSkills):
assert type(path_collector) is PathCollectorSelfSupervisedDiscreteSkills
skill_idx = np.random.randint(self.num_skills - 1)
skill_vec = self.discrete_skills[skill_idx]
path_collector.set_discrete_skill(
skill_vec=skill_vec,
skill_id=skill_idx,
)
def get_grid(self):
assert type(self.mode_trainer) == ModeTrainerWithDiagnosticsDiscrete
assert self.mode_trainer.num_skills == 10
assert self.mode_trainer.model.mode_dim == 2
# Hard coded for testing
radius1 = 0.75
radius2 = 1.
radius3 = 1.38
grid = np.array([
[0., 0.],
[radius1, 0.],
[0., radius1],
[-radius1, 0.],
[0, -radius1],
[radius2, radius2],
[-radius2, radius2],
[radius2, -radius2],
[-radius2, -radius2],
[0, radius3]
], dtype=np.float)
grid = ptu.from_numpy(grid)
return grid
def _get_paths_mode_influence_test(self):
assert type(self.eval_data_collector) is PathCollectorSelfSupervisedDiscreteSkills
self.eval_data_collector.reset()
for skill_id, discrete_skill in enumerate(self.discrete_skills):
self.eval_data_collector.set_discrete_skill(
skill_vec=discrete_skill,
skill_id=skill_id
)
self.eval_data_collector.collect_new_paths(
seq_len=self.seq_len,
num_seqs=1,
)
mode_influence_eval_paths = self.eval_data_collector.get_epoch_paths()
return mode_influence_eval_paths
def write_mode_influence(self, epoch):
paths = self._get_paths_mode_influence_test()
obs_dim = self.policy.obs_dim
action_dim = self.policy.action_dim
for path in paths:
assert path.obs.shape == (obs_dim, self.seq_len)
assert path.action.shape == (action_dim, self.seq_len)
skill_id = path.skill_id.squeeze()[0]
self.diagnostic_writer.writer.plot_lines(
legend_str=['dim' + str(i) for i in range(obs_dim)],
tb_str="mode influence test: observations/mode {}".format(
skill_id),
#arrays_to_plot=[dim for dim in obs],
arrays_to_plot=path.obs,
step=epoch,
y_lim=[-3, 3]
)
self.diagnostic_writer.writer.plot_lines(
legend_str=["dim {}".format(dim) for dim in range(action_dim)],
tb_str="mode influence test: actions/mode {}".format(
skill_id),
arrays_to_plot=path.action,
step=epoch,
y_lim=[-1.2, 1.2]
)
seq_dim = -1
data_dim = 0
path = path.transpose(seq_dim, data_dim)
rewards = self.trainer.intrinsic_reward_calculator.calc_rewards(
obs_seq=ptu.from_numpy(path.obs).unsqueeze(dim=0),
action_seq=ptu.from_numpy(path.action).unsqueeze(dim=0),
skill_gt=ptu.from_numpy(path.mode).unsqueeze(dim=0)
)
assert rewards.shape == torch.Size((1, self.seq_len, 1))
rewards = rewards.squeeze()
assert rewards.shape == torch.Size((self.seq_len,))
self.diagnostic_writer.writer.plot_lines(
legend_str="skill_id {}".format(skill_id),
tb_str="mode influence test rewards/skill_id {}".format(skill_id),
arrays_to_plot=ptu.get_numpy(rewards),
step=epoch,
y_lim=[-7, 2]
)
def _log_stats(self, epoch):
logger.log("Epoch {} finished".format(epoch), with_timestamp=True)
gt.stamp('logging')
logger.record_dict(_get_epoch_timings())
logger.record_tabular('Epoch', epoch)
logger.dump_tabular(with_prefix=False, with_timestamp=False)
gt.stamp('log outputting')
def _end_epoch(self, epoch):
super()._end_epoch(epoch)
if self.diagnostic_writer.is_log(epoch):
self.write_mode_influence(epoch)
gt.stamp('saving')
self._log_stats(epoch)
|
[
"rlkit.torch.pytorch_util.get_numpy",
"rlkit.core.rl_algorithm._get_epoch_timings",
"rlkit.torch.pytorch_util.from_numpy",
"matplotlib.use",
"numpy.array",
"numpy.random.randint",
"torch.Size",
"gtimer.stamp",
"rlkit.core.logger.record_tabular",
"rlkit.core.logger.dump_tabular"
] |
[((1535, 1556), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (1549, 1556), False, 'import matplotlib\n'), ((3585, 3623), 'numpy.random.randint', 'np.random.randint', (['(self.num_skills - 1)'], {}), '(self.num_skills - 1)\n', (3602, 3623), True, 'import numpy as np\n'), ((4117, 4326), 'numpy.array', 'np.array', (['[[0.0, 0.0], [radius1, 0.0], [0.0, radius1], [-radius1, 0.0], [0, -radius1],\n [radius2, radius2], [-radius2, radius2], [radius2, -radius2], [-radius2,\n -radius2], [0, radius3]]'], {'dtype': 'np.float'}), '([[0.0, 0.0], [radius1, 0.0], [0.0, radius1], [-radius1, 0.0], [0, \n -radius1], [radius2, radius2], [-radius2, radius2], [radius2, -radius2],\n [-radius2, -radius2], [0, radius3]], dtype=np.float)\n', (4125, 4326), True, 'import numpy as np\n'), ((4459, 4479), 'rlkit.torch.pytorch_util.from_numpy', 'ptu.from_numpy', (['grid'], {}), '(grid)\n', (4473, 4479), True, 'import rlkit.torch.pytorch_util as ptu\n'), ((7317, 7336), 'gtimer.stamp', 'gt.stamp', (['"""logging"""'], {}), "('logging')\n", (7325, 7336), True, 'import gtimer as gt\n'), ((7394, 7431), 'rlkit.core.logger.record_tabular', 'logger.record_tabular', (['"""Epoch"""', 'epoch'], {}), "('Epoch', epoch)\n", (7415, 7431), False, 'from rlkit.core import logger, eval_util\n'), ((7440, 7500), 'rlkit.core.logger.dump_tabular', 'logger.dump_tabular', ([], {'with_prefix': '(False)', 'with_timestamp': '(False)'}), '(with_prefix=False, with_timestamp=False)\n', (7459, 7500), False, 'from rlkit.core import logger, eval_util\n'), ((7509, 7535), 'gtimer.stamp', 'gt.stamp', (['"""log outputting"""'], {}), "('log outputting')\n", (7517, 7535), True, 'import gtimer as gt\n'), ((7708, 7726), 'gtimer.stamp', 'gt.stamp', (['"""saving"""'], {}), "('saving')\n", (7716, 7726), True, 'import gtimer as gt\n'), ((7364, 7384), 'rlkit.core.rl_algorithm._get_epoch_timings', '_get_epoch_timings', ([], {}), '()\n', (7382, 7384), False, 'from rlkit.core.rl_algorithm import _get_epoch_timings\n'), ((6738, 6770), 'torch.Size', 'torch.Size', (['(1, self.seq_len, 1)'], {}), '((1, self.seq_len, 1))\n', (6748, 6770), False, 'import torch\n'), ((6847, 6874), 'torch.Size', 'torch.Size', (['(self.seq_len,)'], {}), '((self.seq_len,))\n', (6857, 6874), False, 'import torch\n'), ((7103, 7125), 'rlkit.torch.pytorch_util.get_numpy', 'ptu.get_numpy', (['rewards'], {}), '(rewards)\n', (7116, 7125), True, 'import rlkit.torch.pytorch_util as ptu\n'), ((3196, 3227), 'rlkit.torch.pytorch_util.from_numpy', 'ptu.from_numpy', (['train_data.mode'], {}), '(train_data.mode)\n', (3210, 3227), True, 'import rlkit.torch.pytorch_util as ptu\n'), ((3253, 3283), 'rlkit.torch.pytorch_util.from_numpy', 'ptu.from_numpy', (['train_data.obs'], {}), '(train_data.obs)\n', (3267, 3283), True, 'import rlkit.torch.pytorch_util as ptu\n'), ((3310, 3345), 'rlkit.torch.pytorch_util.from_numpy', 'ptu.from_numpy', (['train_data.skill_id'], {}), '(train_data.skill_id)\n', (3324, 3345), True, 'import rlkit.torch.pytorch_util as ptu\n'), ((6504, 6528), 'rlkit.torch.pytorch_util.from_numpy', 'ptu.from_numpy', (['path.obs'], {}), '(path.obs)\n', (6518, 6528), True, 'import rlkit.torch.pytorch_util as ptu\n'), ((6574, 6601), 'rlkit.torch.pytorch_util.from_numpy', 'ptu.from_numpy', (['path.action'], {}), '(path.action)\n', (6588, 6601), True, 'import rlkit.torch.pytorch_util as ptu\n'), ((6645, 6670), 'rlkit.torch.pytorch_util.from_numpy', 'ptu.from_numpy', (['path.mode'], {}), '(path.mode)\n', (6659, 6670), True, 'import rlkit.torch.pytorch_util as ptu\n')]
|
import cadquery as cq
import numpy as np
from OCP.Standard import Standard_ConstructionError
def linear_milling_vol(cut, start_point, end_point, mill_diameter):
"""creates the volume that gets milled from linear move
Keyword arguments:
start_point -- [x,y,z] toolcentrepoint mm
end_point -- [x,y,z] toolcentrepoint mm
mill_diameter -- tooldiameter mm
Output:
CADquery Object
"""
assert (start_point[2] == end_point[2] != 0)
alpha = np.arctan2(end_point[1] - start_point[1], end_point[0] - start_point[0])
points = [[start_point[0] + mill_diameter / 2 * np.cos(alpha + np.pi / 2),
start_point[1] + mill_diameter / 2 * np.sin(alpha + np.pi / 2)],
[start_point[0] + mill_diameter / 2 * np.cos(alpha + np.pi),
start_point[1] + mill_diameter / 2 * np.sin(alpha + np.pi)],
[start_point[0] + mill_diameter / 2 * np.cos(alpha - np.pi / 2),
start_point[1] + mill_diameter / 2 * np.sin(alpha - np.pi / 2)],
[end_point[0] + mill_diameter / 2 * np.cos(alpha - np.pi / 2),
end_point[1] + mill_diameter / 2 * np.sin(alpha - np.pi / 2)],
[end_point[0] + mill_diameter / 2 * np.cos(alpha), end_point[1] + mill_diameter / 2 * np.sin(alpha)],
[end_point[0] + mill_diameter / 2 * np.cos(alpha + np.pi / 2),
end_point[1] + mill_diameter / 2 * np.sin(alpha + np.pi / 2)]]
cut = cut.moveTo(points[0][0], points[0][1]).threePointArc(points[1], points[2]).lineTo(points[3][0], points[3][1]) \
.threePointArc(points[4], points[5]).close().extrude(end_point[2])
return cut
def circular_milling_vol(cut, start_point, end_point, mill_diameter, arc_centre):
"""creates the volume that gets milled from circular move
Keyword arguments:
start_point -- [x,y,z] toolcentrepoint mm
end_point -- [x,y,z] toolcentrepoint mm
mill_diameter -- tooldiameter mm
arc_centre -- !!! noch nicht sicher!!! entweder radius oder kreismittelpunkt
Output:
CADquery Object
"""
pass # weil grade noch leer, dann löahen
# ...
def draw_and_subtract(moves, workpiece, mill_diameter):
"""gets moves of one timestep
Keyword arguments:
moves -- moves of current timestep
workpiece -- current workpiece
mill_diameter -- Mill Diameter
Output:
intersection -- virtual chip (spahn)
workpiece -- updated workpiece
"""
cut = cq.Workplane("front")
for move in moves:
if len(move) == 2:
cut = linear_milling_vol(cut, move[0], move[1], mill_diameter)
else:
cut = circular_milling_vol(cut, move[0], move[1], move[2], mill_diameter)
try:
intersection = workpiece.intersect(cut)
intersection.largestDimension()
except Standard_ConstructionError:
intersection = None
if intersection is not None:
wp = workpiece.cut(cut)
return intersection, wp
def get_param_for_neural_net(moves, workpiece, mill_diameter):
"""appends cutting-simulation-parameters line at csv list
Keyword arguments:
moves -- moves of current timestep
workpiece -- current workpiece
mill_diameter -- Mill Diameter
Output:
compounded_move -- is move compounded (zusammengestzt)
alpha -- direction angle of movement
b_box -- boundingbox of virtual chip, corresponds to Umschlingungswinkel
vol -- volume of virtual chip
z_hight -- z-hight-information, noch unklar
"""
# inter = intersection
inter, workpiece = draw_and_subtract(moves, workpiece, mill_diameter)
compounded_move = len(moves) - 1 # zum Abfangen wenn stückechen zusammengestzt
# Umschlingungswinkel -in Fahrtrichtung drehen: alpha
alpha = np.arctan2(moves[-1][1][1] - moves[0][0][1], moves[-1][1][0] - moves[0][0][0])
shape = inter.val().rotate((0, 0, 0), (0, 0, 1), alpha)
vol = shape.Volume()
b_box = shape.BoundingBox() # ähnlich zu Umschlingungswinkel -> =Umschlingungswinkel
z_hight = moves[0][0][2] # noch unklar
return [compounded_move, alpha, b_box, vol, z_hight]
|
[
"numpy.sin",
"numpy.arctan2",
"cadquery.Workplane",
"numpy.cos"
] |
[((478, 550), 'numpy.arctan2', 'np.arctan2', (['(end_point[1] - start_point[1])', '(end_point[0] - start_point[0])'], {}), '(end_point[1] - start_point[1], end_point[0] - start_point[0])\n', (488, 550), True, 'import numpy as np\n'), ((2469, 2490), 'cadquery.Workplane', 'cq.Workplane', (['"""front"""'], {}), "('front')\n", (2481, 2490), True, 'import cadquery as cq\n'), ((3768, 3846), 'numpy.arctan2', 'np.arctan2', (['(moves[-1][1][1] - moves[0][0][1])', '(moves[-1][1][0] - moves[0][0][0])'], {}), '(moves[-1][1][1] - moves[0][0][1], moves[-1][1][0] - moves[0][0][0])\n', (3778, 3846), True, 'import numpy as np\n'), ((604, 629), 'numpy.cos', 'np.cos', (['(alpha + np.pi / 2)'], {}), '(alpha + np.pi / 2)\n', (610, 629), True, 'import numpy as np\n'), ((683, 708), 'numpy.sin', 'np.sin', (['(alpha + np.pi / 2)'], {}), '(alpha + np.pi / 2)\n', (689, 708), True, 'import numpy as np\n'), ((763, 784), 'numpy.cos', 'np.cos', (['(alpha + np.pi)'], {}), '(alpha + np.pi)\n', (769, 784), True, 'import numpy as np\n'), ((838, 859), 'numpy.sin', 'np.sin', (['(alpha + np.pi)'], {}), '(alpha + np.pi)\n', (844, 859), True, 'import numpy as np\n'), ((914, 939), 'numpy.cos', 'np.cos', (['(alpha - np.pi / 2)'], {}), '(alpha - np.pi / 2)\n', (920, 939), True, 'import numpy as np\n'), ((993, 1018), 'numpy.sin', 'np.sin', (['(alpha - np.pi / 2)'], {}), '(alpha - np.pi / 2)\n', (999, 1018), True, 'import numpy as np\n'), ((1071, 1096), 'numpy.cos', 'np.cos', (['(alpha - np.pi / 2)'], {}), '(alpha - np.pi / 2)\n', (1077, 1096), True, 'import numpy as np\n'), ((1148, 1173), 'numpy.sin', 'np.sin', (['(alpha - np.pi / 2)'], {}), '(alpha - np.pi / 2)\n', (1154, 1173), True, 'import numpy as np\n'), ((1226, 1239), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (1232, 1239), True, 'import numpy as np\n'), ((1276, 1289), 'numpy.sin', 'np.sin', (['alpha'], {}), '(alpha)\n', (1282, 1289), True, 'import numpy as np\n'), ((1342, 1367), 'numpy.cos', 'np.cos', (['(alpha + np.pi / 2)'], {}), '(alpha + np.pi / 2)\n', (1348, 1367), True, 'import numpy as np\n'), ((1419, 1444), 'numpy.sin', 'np.sin', (['(alpha + np.pi / 2)'], {}), '(alpha + np.pi / 2)\n', (1425, 1444), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""Support Vector Machine (SVM) classification for machine learning.
SVM is a binary classifier. The objective of the SVM is to find the best
separating hyperplane in vector space which is also referred to as the
decision boundary. And it decides what separating hyperplane is the 'best'
because the distance from it and the associating data it is separating is the
greatest at the plane in question.
This is the file where I create use scikit-learn to use the algorithm.
dataset is breast cancer data from: http://archive.ics.uci.edu/ml/datasets.html
Example:
$ python regularSupportVectorMachine.py
Todo:
*
"""
import numpy as np
import pandas as pd
from sklearn import svm
from sklearn.model_selection import train_test_split
df = pd.read_csv('breast-cancer-wisconsin.data')
df.replace('?', -99999, inplace=True) # make missing attribute values outliers
df.drop(['id'], 1, inplace=True) # remove useless column
X = np.array(df.drop(['class'], 1)) # features
y = np.array(df['class']) # labels
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
clf = svm.SVC()
clf.fit(X_train, y_train)
# Could have saved in a pickle, but not a very large data set.
accuracy = clf.score(X_test, y_test)
print(accuracy)
example1 = [4, 2, 1, 1, 1, 2, 3, 2, 1]
example2 = [4, 2, 1, 2, 2, 2, 3, 2, 1]
example_measures = np.array([example1, example2])
example_measures = example_measures.reshape(len(example_measures), -1)
prediction = clf.predict(example_measures)
print(prediction)
|
[
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"numpy.array",
"sklearn.svm.SVC"
] |
[((778, 821), 'pandas.read_csv', 'pd.read_csv', (['"""breast-cancer-wisconsin.data"""'], {}), "('breast-cancer-wisconsin.data')\n", (789, 821), True, 'import pandas as pd\n'), ((1013, 1034), 'numpy.array', 'np.array', (["df['class']"], {}), "(df['class'])\n", (1021, 1034), True, 'import numpy as np\n'), ((1081, 1118), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)'}), '(X, y, test_size=0.2)\n', (1097, 1118), False, 'from sklearn.model_selection import train_test_split\n'), ((1126, 1135), 'sklearn.svm.SVC', 'svm.SVC', ([], {}), '()\n', (1133, 1135), False, 'from sklearn import svm\n'), ((1379, 1409), 'numpy.array', 'np.array', (['[example1, example2]'], {}), '([example1, example2])\n', (1387, 1409), True, 'import numpy as np\n')]
|
import numpy as np
import nudged
from scipy.linalg import eig, sqrtm, norm
from .utils import adjust
def find_linear_projections(X, d, objective, iters=20):
n = X.shape[1]
objective.X = X
XBXT = adjust(objective.XBXT)
sqrtXBXT = np.real(sqrtm(XBXT))
projections = []
selected = []
C = np.zeros((X.shape[0], X.shape[0]))
for i in range(iters):
if i == 0:
XLXT = objective.XLXT
else:
XLXT = objective.XLXT + objective.alpha * C
XLXT = 0.5 * (XLXT + XLXT.T)
XLXT = adjust(XLXT)
ev, eV, *_ = eig(XLXT, XBXT)
ev = np.real(ev)
eV = np.dot(sqrtXBXT, np.real(eV))
if objective.alpha < 0:
ev = -ev
idx = np.argsort(ev)
V = eV[:, idx[0:d]]
for j in range(d):
V[:, j] /= norm(V[:, j])
projections.append(V)
C += V.dot(V.T)
if i == 0 or dissimilar(V, selected, X, objective.threshold):
selected.append(V)
return selected
def dissimilar(V, projections, X, min_threshold, err_threshold=0.8):
VT = V.T
m = 2 - min(map(lambda p: norm(VT.dot(p)), projections))
if m < min_threshold:
return False
Y = X.T.dot(V).tolist()
for p in projections:
Y2 = X.T.dot(p)
affine = nudged.estimate(Y, Y2.tolist())
err = norm(Y2 - np.array(affine.transform(Y))) / norm(Y2)
if err < err_threshold:
return False
return True
|
[
"numpy.zeros",
"scipy.linalg.eig",
"numpy.argsort",
"scipy.linalg.sqrtm",
"scipy.linalg.norm",
"numpy.real"
] |
[((318, 352), 'numpy.zeros', 'np.zeros', (['(X.shape[0], X.shape[0])'], {}), '((X.shape[0], X.shape[0]))\n', (326, 352), True, 'import numpy as np\n'), ((257, 268), 'scipy.linalg.sqrtm', 'sqrtm', (['XBXT'], {}), '(XBXT)\n', (262, 268), False, 'from scipy.linalg import eig, sqrtm, norm\n'), ((594, 609), 'scipy.linalg.eig', 'eig', (['XLXT', 'XBXT'], {}), '(XLXT, XBXT)\n', (597, 609), False, 'from scipy.linalg import eig, sqrtm, norm\n'), ((624, 635), 'numpy.real', 'np.real', (['ev'], {}), '(ev)\n', (631, 635), True, 'import numpy as np\n'), ((747, 761), 'numpy.argsort', 'np.argsort', (['ev'], {}), '(ev)\n', (757, 761), True, 'import numpy as np\n'), ((666, 677), 'numpy.real', 'np.real', (['eV'], {}), '(eV)\n', (673, 677), True, 'import numpy as np\n'), ((841, 854), 'scipy.linalg.norm', 'norm', (['V[:, j]'], {}), '(V[:, j])\n', (845, 854), False, 'from scipy.linalg import eig, sqrtm, norm\n'), ((1409, 1417), 'scipy.linalg.norm', 'norm', (['Y2'], {}), '(Y2)\n', (1413, 1417), False, 'from scipy.linalg import eig, sqrtm, norm\n')]
|
import sys
#print(sys.path)
sys.path.append('/home/pi/.local/lib/python3.7/site-packages')
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import pickle
import numpy as np
from keras.models import load_model
model = load_model('chatbot_model4.h5')
import json
import random
intents = json.loads(open('intents.json').read())
words = pickle.load(open('words.pkl','rb'))
classes = pickle.load(open('classes.pkl','rb'))
from nlip2 import name
def clean_up_sentence(sentence):
# tokenize the pattern - split words into array
sentence_words = nltk.word_tokenize(sentence)
# stem each word - create short form for word
sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]
return sentence_words
# return bag of words array: 0 or 1 for each word in the bag that exists in the sentence
def bow(sentence, words, show_details=True):
# tokenize the pattern
sentence_words = clean_up_sentence(sentence)
# bag of words - matrix of N words, vocabulary matrix
bag = [0]*len(words)
for s in sentence_words:
for i,w in enumerate(words):
if w == s:
# assign 1 if current word is in the vocabulary position
bag[i] = 1
if show_details:
print ("found in bag: %s" % w)
return(np.array(bag))
def predict_class(sentence, model):
# filter out predictions below a threshold
p = bow(sentence, words,show_details=False)
res = model.predict(np.array([p]))[0]
ERROR_THRESHOLD = 0.25
m=[]
k=0
for j in res:
# print(j)
m.append({'intent':k,'prob':j})
k=k+1
o=0
for j in m:
print(j['intent'],j['prob'])
if j['prob'] > o :
o=j['prob']
l=j['intent']
print(o,l)
results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]
# sort by strength of probability
results.sort(key=lambda x: x[1], reverse=True)
return_list = []
return_list.append({"intent": classes[l], "probability": str(o)})
return return_list,o
def getResponse(ints, intents_json):
tag = ints[0]['intent']
list_of_intents = intents_json['intents']
for i in list_of_intents:
if(i['tag']== tag):
result = random.choice(i['responses'])
break
return result
def chatbot_response(text):
ints,o= predict_class(text, model)
i=0
for j in ints:
if j['intent'] =="goodbye":
i=1
res = getResponse(ints, intents)
return res,i,o
from keras.models import load_model
#tezt="are you hungry now"
#k=clean_up_sentence(tezt)
#print(k)
#s=bow(tezt,k)
#print(s)
#p=predict_class(tezt, model)
#print(p)
while True:
tezt=input("user:")
k,s,o=chatbot_response(tezt)
if k=="":
print("your name")
k=name(tezt)
k="nice to meet you "+k
if o < 0.68:
print("browser getting activated")
print("bot:",k)
if s==1:
break
|
[
"sys.path.append",
"keras.models.load_model",
"nltk.stem.WordNetLemmatizer",
"random.choice",
"numpy.array",
"nlip2.name",
"nltk.word_tokenize"
] |
[((30, 92), 'sys.path.append', 'sys.path.append', (['"""/home/pi/.local/lib/python3.7/site-packages"""'], {}), "('/home/pi/.local/lib/python3.7/site-packages')\n", (45, 92), False, 'import sys\n'), ((161, 180), 'nltk.stem.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (178, 180), False, 'from nltk.stem import WordNetLemmatizer\n'), ((262, 293), 'keras.models.load_model', 'load_model', (['"""chatbot_model4.h5"""'], {}), "('chatbot_model4.h5')\n", (272, 293), False, 'from keras.models import load_model\n'), ((602, 630), 'nltk.word_tokenize', 'nltk.word_tokenize', (['sentence'], {}), '(sentence)\n', (620, 630), False, 'import nltk\n'), ((1388, 1401), 'numpy.array', 'np.array', (['bag'], {}), '(bag)\n', (1396, 1401), True, 'import numpy as np\n'), ((2951, 2961), 'nlip2.name', 'name', (['tezt'], {}), '(tezt)\n', (2955, 2961), False, 'from nlip2 import name\n'), ((1562, 1575), 'numpy.array', 'np.array', (['[p]'], {}), '([p])\n', (1570, 1575), True, 'import numpy as np\n'), ((2367, 2396), 'random.choice', 'random.choice', (["i['responses']"], {}), "(i['responses'])\n", (2380, 2396), False, 'import random\n')]
|
import dill
import numpy as np
import tensorflow as tf
from collections import defaultdict
from sklearn.model_selection import train_test_split
with open('motion_capture_20181011-1931.dill', 'rb') as f:
x = dill.load(f)
vec = [l[4] for l in x]
# print(len(vec))
x = map(str, vec)
x = list(x)
#X_train, X_test = train_test_split(x, test_size=0.33, shuffle=False)
corpus = [x]
#restore model for testing
sess = tf.Session()
new_saver = tf.train.import_meta_graph('model.ckpt.meta')
new_saver.restore(sess, tf.train.latest_checkpoint('./'))
all_vars = tf.get_collection('vars')
for v in all_vars:
w1 = sess.run(v)
print(w1)
#generate data for testing
word_counts = defaultdict(int)
for row in corpus:
for word in row:
word_counts[word] += 1
v_count = len(word_counts.keys())
# GENERATE LOOKUP DICTIONARIES
words_list = sorted(list(word_counts.keys()), reverse=False)
word_index = dict((word, i) for i, word in enumerate(words_list))
index_word = dict((i, word) for i, word in enumerate(words_list))
def vec_sim(vec, top_n):
# CYCLE THROUGH VOCAB
word_sim = {}
output = []
for i in range(v_count):
v_w2 = w1[i]
theta_num = np.dot(vec, v_w2)
theta_den = np.linalg.norm(vec) * np.linalg.norm(v_w2)
theta = theta_num / theta_den
word = index_word[i]
word_sim[word] = theta
words_sorted = sorted(word_sim.items(), reverse=True)
# words_sorted = sorted(word_sim.items(), key=lambda word, sim: sim, reverse=True)
for word, sim in words_sorted[:top_n]:
print('vec_sim', word, sim)
output.append(word)
output.append(sim)
return output
corpus = [(1,1)]
output = vec_sim(corpus,1)
print(output)
|
[
"tensorflow.train.import_meta_graph",
"tensorflow.get_collection",
"tensorflow.Session",
"dill.load",
"collections.defaultdict",
"tensorflow.train.latest_checkpoint",
"numpy.linalg.norm",
"numpy.dot"
] |
[((420, 432), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (430, 432), True, 'import tensorflow as tf\n'), ((445, 490), 'tensorflow.train.import_meta_graph', 'tf.train.import_meta_graph', (['"""model.ckpt.meta"""'], {}), "('model.ckpt.meta')\n", (471, 490), True, 'import tensorflow as tf\n'), ((560, 585), 'tensorflow.get_collection', 'tf.get_collection', (['"""vars"""'], {}), "('vars')\n", (577, 585), True, 'import tensorflow as tf\n'), ((682, 698), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (693, 698), False, 'from collections import defaultdict\n'), ((214, 226), 'dill.load', 'dill.load', (['f'], {}), '(f)\n', (223, 226), False, 'import dill\n'), ((515, 547), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['"""./"""'], {}), "('./')\n", (541, 547), True, 'import tensorflow as tf\n'), ((1187, 1204), 'numpy.dot', 'np.dot', (['vec', 'v_w2'], {}), '(vec, v_w2)\n', (1193, 1204), True, 'import numpy as np\n'), ((1225, 1244), 'numpy.linalg.norm', 'np.linalg.norm', (['vec'], {}), '(vec)\n', (1239, 1244), True, 'import numpy as np\n'), ((1247, 1267), 'numpy.linalg.norm', 'np.linalg.norm', (['v_w2'], {}), '(v_w2)\n', (1261, 1267), True, 'import numpy as np\n')]
|
"""
Script to analyze distribution of squared Euclidean distance between gradients.
"""
from math import sqrt
import numpy as np
from scipy import stats
# Set constants.
k_vals = [35, 30, 36]
n_vals = [1, 18, 1]
total_n = sum(n_vals)
sigma = 0.01
start_t = 200
t = 250
num_trials = 100
alpha = 0.05
load = "vecs.np"
reject_probs = []
outlier_count = 0
for m in range(num_trials):
max_k = max(k_vals)
vecs = np.zeros((t, total_n, max_k, 2))
if load is None:
start = 0
for k, n in zip(k_vals, n_vals):
vecs[:, start : start + n, :k, :] = np.random.normal(
scale=sigma, size=(t, n, k, 2)
)
start = start + n
else:
with open(load, "rb") as f:
vecs = np.load(f)
count = 0
for current_t in range(start_t, t):
z = []
start = 0
for k, n in zip(k_vals, n_vals):
# Compute expected distribution of sample means.
length_mu = 2 * k * (sigma ** 2)
length_sigma = 2 * sqrt(2 * k) * (sigma ** 2)
# Compute sample means and z-scores.
diffs = (
vecs[: current_t + 1, start : start + n, :, 0]
- vecs[: current_t + 1, start : start + n, :, 1]
)
lengths = np.linalg.norm(diffs, ord=2, axis=2) ** 2
sample_mean = np.mean(lengths, axis=0)
current_z = (sample_mean - length_mu) / (length_sigma / sqrt(current_t + 1))
z.append(current_z)
start = start + n
z = np.concatenate(z)
# Check sizes.
assert z.shape == (total_n,)
"""
# Compute QQ plot correlation coefficient
baseline = np.random.normal(size=z_sample_size)
sorted_z = np.sort(z)
sorted_baseline = np.sort(baseline)
_, _, r, p, _ = stats.linregress(sorted_z, sorted_baseline)
print("Correlation coefficient: %f" % r)
print("p-value: %f" % p)
print("")
"""
# Compare z-score distribution against standard normal.
s, p = stats.kstest(z, "norm")
if p < alpha:
count += 1
reject_prob = count / (t - start_t)
reject_probs.append(reject_prob)
if count > 0:
outlier_count += 1
"""
for outlier in outliers:
print("Total outliers: %d/%d" % (outlier, (t - start_t)))
"""
avg_reject_prob = sum(reject_probs) / len(reject_probs)
print("reject_probs: %s" % str(reject_probs))
print("avg reject_prob: %f" % avg_reject_prob)
print("num rejects: %d/%d" % (outlier_count, num_trials))
|
[
"scipy.stats.kstest",
"numpy.load",
"math.sqrt",
"numpy.zeros",
"numpy.mean",
"numpy.linalg.norm",
"numpy.random.normal",
"numpy.concatenate"
] |
[((421, 453), 'numpy.zeros', 'np.zeros', (['(t, total_n, max_k, 2)'], {}), '((t, total_n, max_k, 2))\n', (429, 453), True, 'import numpy as np\n'), ((1557, 1574), 'numpy.concatenate', 'np.concatenate', (['z'], {}), '(z)\n', (1571, 1574), True, 'import numpy as np\n'), ((2089, 2112), 'scipy.stats.kstest', 'stats.kstest', (['z', '"""norm"""'], {}), "(z, 'norm')\n", (2101, 2112), False, 'from scipy import stats\n'), ((582, 630), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'sigma', 'size': '(t, n, k, 2)'}), '(scale=sigma, size=(t, n, k, 2))\n', (598, 630), True, 'import numpy as np\n'), ((756, 766), 'numpy.load', 'np.load', (['f'], {}), '(f)\n', (763, 766), True, 'import numpy as np\n'), ((1367, 1391), 'numpy.mean', 'np.mean', (['lengths'], {'axis': '(0)'}), '(lengths, axis=0)\n', (1374, 1391), True, 'import numpy as np\n'), ((1299, 1335), 'numpy.linalg.norm', 'np.linalg.norm', (['diffs'], {'ord': '(2)', 'axis': '(2)'}), '(diffs, ord=2, axis=2)\n', (1313, 1335), True, 'import numpy as np\n'), ((1036, 1047), 'math.sqrt', 'sqrt', (['(2 * k)'], {}), '(2 * k)\n', (1040, 1047), False, 'from math import sqrt\n'), ((1460, 1479), 'math.sqrt', 'sqrt', (['(current_t + 1)'], {}), '(current_t + 1)\n', (1464, 1479), False, 'from math import sqrt\n')]
|
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
import json
import pickle
import numpy as np
import pandas as pd
import azureml.train.automl
from sklearn.externals import joblib
from azureml.core.model import Model
from inference_schema.schema_decorators import input_schema, output_schema
from inference_schema.parameter_types.numpy_parameter_type import NumpyParameterType
from inference_schema.parameter_types.pandas_parameter_type import PandasParameterType
import xgboost as xgb
input_sample = pd.DataFrame(data=[{'winddirabs': 0.34244, 'winddirrel': 0.324235,'windspeedrel':1.3213}])
output_sample = np.array([0])
def init():
global model
# This name is model.id of model that we want to deploy deserialize the model file back
# into a sklearn model
model_path = Model.get_model_path(model_name = 'Model')
model = joblib.load(model_path)
@input_schema('data', PandasParameterType(input_sample))
@output_schema(NumpyParameterType(output_sample))
def run(data):
try:
result = model.predict(data)
return json.dumps({"result": result.tolist()})
except Exception as e:
result = str(e)
return json.dumps({"error": result})
|
[
"pandas.DataFrame",
"azureml.core.model.Model.get_model_path",
"inference_schema.parameter_types.numpy_parameter_type.NumpyParameterType",
"json.dumps",
"inference_schema.parameter_types.pandas_parameter_type.PandasParameterType",
"numpy.array",
"sklearn.externals.joblib.load"
] |
[((633, 729), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "[{'winddirabs': 0.34244, 'winddirrel': 0.324235, 'windspeedrel': 1.3213}]"}), "(data=[{'winddirabs': 0.34244, 'winddirrel': 0.324235,\n 'windspeedrel': 1.3213}])\n", (645, 729), True, 'import pandas as pd\n'), ((740, 753), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (748, 753), True, 'import numpy as np\n'), ((921, 961), 'azureml.core.model.Model.get_model_path', 'Model.get_model_path', ([], {'model_name': '"""Model"""'}), "(model_name='Model')\n", (941, 961), False, 'from azureml.core.model import Model\n'), ((976, 999), 'sklearn.externals.joblib.load', 'joblib.load', (['model_path'], {}), '(model_path)\n', (987, 999), False, 'from sklearn.externals import joblib\n'), ((1024, 1057), 'inference_schema.parameter_types.pandas_parameter_type.PandasParameterType', 'PandasParameterType', (['input_sample'], {}), '(input_sample)\n', (1043, 1057), False, 'from inference_schema.parameter_types.pandas_parameter_type import PandasParameterType\n'), ((1074, 1107), 'inference_schema.parameter_types.numpy_parameter_type.NumpyParameterType', 'NumpyParameterType', (['output_sample'], {}), '(output_sample)\n', (1092, 1107), False, 'from inference_schema.parameter_types.numpy_parameter_type import NumpyParameterType\n'), ((1291, 1320), 'json.dumps', 'json.dumps', (["{'error': result}"], {}), "({'error': result})\n", (1301, 1320), False, 'import json\n')]
|
import re
import numpy as np
#numerical operation
import matplotlib.pyplot as plt
#matploit provides functions that draws graphs or etc.
from sklearn.cluster import MiniBatchKMeans
from sklearn.cluster import KMeans
import array
import numpy as np
def findminmax(dirname, filename):
print('findminmax')
mf = open(dirname+filename,'r')
#TotalInstances = list()
strfreq = ''
intfreq = 0
m = 0
tmpcount=0
minlist = list()
maxlist = list()
firstlineflag = True
numberofinsatnces = 0
numoffeattype = 0
while True:
ch = mf.read(1)
if ch == '':
break
if ch == '(':
AnInstance = list()
strfreq = ''
elif ch == ')':
AnInstance.append(int(strfreq))
numberofinsatnces += 1
numoffeattype = len(AnInstance)
if firstlineflag == True:
for i in range(numoffeattype):
minlist.append(9999)
maxlist.append(-9999)
firstlineflag = False
for i in range(numoffeattype):
if minlist[i]>AnInstance[i]:
minlist[i]=AnInstance[i]
if maxlist[i]<AnInstance[i]:
maxlist[i]=AnInstance[i]
tmpcount+=1
strfreq = ''
elif ch == ',':
AnInstance.append(int(strfreq))
strfreq = ''
elif ch == ' ':
continue
else:
strfreq += ch
mf.close()
fminmax = open(dirname+"Noofinstance_minmax_"+filename,'w')
fminmax.write(str(numberofinsatnces))
fminmax.write(' ')
fminmax.write(str(numoffeattype))
fminmax.write('\n')
for minv in minlist:
fminmax.write(str(minv))
fminmax.write(' ')
fminmax.write('\n')
for maxv in maxlist:
fminmax.write(str(maxv))
fminmax.write(' ')
fminmax.close()
def convertToNormVals(dirname, filename):
print('convertToNormVals')
mf = open(dirname+filename,'r')
fminmax = open(dirname+"Noofinstance_minmax_"+filename,'r')
lines = fminmax.readlines()
minStrlist = lines[1].split()
maxStrlist = lines[2].split()
fminmax.close()
strfreq = ''
minlist = list()
for minstr in minStrlist:
minlist.append(float(minstr))
maxlist = list()
for maxstr in maxStrlist:
maxlist.append(float(maxstr))
fnorm = open(dirname+"Norm_"+filename,'w')
while True:
ch = mf.read(1)
if ch == '':
break
if ch == '(':
AnInstance = list()
strfreq = ''
elif ch == ')':
AnInstance.append(float(strfreq))
strfreq = ''
for i in range(len(AnInstance)):
if minlist[i]>maxlist[i]:
exit()
if minlist[i] == 0 and maxlist[i] == 0:
AnInstance[i] = 0 #should be consided again later...
elif minlist[i] == maxlist[i]:
AnInstance[i] = 0 #should be consided again later...
else:
AnInstance[i] = float(float((AnInstance[i]-minlist[i]))/float((maxlist[i]-minlist[i])))
for i in range(len(AnInstance)):
fnorm.write(str(AnInstance[i]))
fnorm.write(' ')
fnorm.write('\n')
elif ch == ',':
AnInstance.append(float(strfreq))
strfreq = ''
elif ch == ' ':
continue
else:
strfreq += ch
mf.close()
fnorm.close()
def convertToNTemplate(dirname, filename):
print('convertToTemplate')
mf = open(dirname+filename,'r')
strfreq = ''
f = open(dirname+"NewTemp_"+filename,'w')
AllZero = True
noinstances = 0
nofeattype = 0
while True:
ch = mf.read(1)
if ch == '':
break
if ch == '(':
AnInstance = list()
AllZero = True
strfreq = ''
elif ch == ')':
if not float(strfreq) == 0.0:
AllZero = False
AnInstance.append(float(strfreq))
nofeattype = len(AnInstance)
if AllZero == False:
noinstances +=1
strfreq = ''
for i in range(len(AnInstance)):
f.write(str(AnInstance[i]))
f.write(' ')
f.write('\n')
elif ch == ',':
if not float(strfreq) == 0.0:
AllZero = False
AnInstance.append(float(strfreq))
strfreq = ''
elif ch == ' ':
continue
else:
strfreq += ch
mf.close()
f.close()
return noinstances, nofeattype
def readNormInstances(dirname, filename, numberofinsatnces, numoffeattype):
print('readNormInstances')
TotalInstances = np.empty(numberofinsatnces*numoffeattype,dtype='float64')
f = open(dirname+filename,'r')
index = 0
#for line in f:
while True:
line = f.readline()
if line == '':
break
s = line.split()
for ss in s:
TotalInstances[index] = float(ss)
index +=1
TotalInstances = np.reshape(TotalInstances, (numberofinsatnces,numoffeattype))
f.close()
return TotalInstances
def divideIntoTwoSets(TotalInstances, numoffeattypeA, numoffeattypeB):
TotalInstances = np.hsplit(TotalInstances, np.array([numoffeattypeA, numoffeattypeA+numoffeattypeB]))
return TotalInstances[0], TotalInstances[1]
def minikmeanGo(TotalInstances, dirname, filename, nocluster):
np.random.seed(5)
noOfCluster = nocluster
kmeans = MiniBatchKMeans(n_clusters=noOfCluster)
print(kmeans)
kmeans.fit(TotalInstances)
print('fitting done')
centroids = kmeans.cluster_centers_
resultF = open(dirname+filename,'w')
for centroid in centroids:
for v in centroid:
resultF.write(str(v)+' ')
resultF.write('\n')
resultF.close()
def KmeanGo(TotalInstances, dirname, filename, nocluster):
np.random.seed(5)
noOfCluster = nocluster
kmeans = KMeans(n_clusters=noOfCluster, n_jobs=5)
print(kmeans)
kmeans.fit(TotalInstances)
print('fitting done')
centroids = kmeans.cluster_centers_
resultF = open(dirname+filename,'w')
for centroid in centroids:
for v in centroid:
resultF.write(str(v)+' ')
resultF.write('\n')
resultF.close()
#findminmax('./40000TotalSets/','Funcs.txt')
#findminmax('./40000TotalSets/','Methods.txt')
#noinstances, nofeattype = convertToNTemplate('./40000TotalSets/','Funcs.txt')
#t = readNormInstances('./40000TotalSets/', 'NewTemp_Funcs.txt', noinstances, nofeattype)
#minikmeanGo(t, './40000TotalSets/', 'F13_FUNCTIONS_so.txt')
"""
noinstances, nofeattype = convertToNTemplate('./','Funcs.txt')
t = readNormInstances('./', 'NewTemp_Funcs.txt', noinstances, nofeattype)
ta, tb = divideIntoTwoSets(t, 1321, 555)
minikmeanGo(tb, './', 'F13_FUNCTIONS_so_SYS.txt', 200)
minikmeanGo(ta, './', 'F13_FUNCTIONS_so_OP.txt', 2500)
"""
noinstances, nofeattype = convertToNTemplate('./','Methods.txt')
t = readNormInstances('./', 'NewTemp_Methods.txt', noinstances, nofeattype)
ta, tb = divideIntoTwoSets(t, 217, 238)
KmeanGo(tb, './', 'F12_METHOD_smali_API.txt', 1000)
KmeanGo(ta, './', 'F12_METHOD_smali_OP.txt', 5000)
|
[
"sklearn.cluster.MiniBatchKMeans",
"numpy.random.seed",
"numpy.empty",
"sklearn.cluster.KMeans",
"numpy.array",
"numpy.reshape"
] |
[((4919, 4979), 'numpy.empty', 'np.empty', (['(numberofinsatnces * numoffeattype)'], {'dtype': '"""float64"""'}), "(numberofinsatnces * numoffeattype, dtype='float64')\n", (4927, 4979), True, 'import numpy as np\n'), ((5266, 5328), 'numpy.reshape', 'np.reshape', (['TotalInstances', '(numberofinsatnces, numoffeattype)'], {}), '(TotalInstances, (numberofinsatnces, numoffeattype))\n', (5276, 5328), True, 'import numpy as np\n'), ((5663, 5680), 'numpy.random.seed', 'np.random.seed', (['(5)'], {}), '(5)\n', (5677, 5680), True, 'import numpy as np\n'), ((5722, 5761), 'sklearn.cluster.MiniBatchKMeans', 'MiniBatchKMeans', ([], {'n_clusters': 'noOfCluster'}), '(n_clusters=noOfCluster)\n', (5737, 5761), False, 'from sklearn.cluster import MiniBatchKMeans\n'), ((6132, 6149), 'numpy.random.seed', 'np.random.seed', (['(5)'], {}), '(5)\n', (6146, 6149), True, 'import numpy as np\n'), ((6191, 6231), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'noOfCluster', 'n_jobs': '(5)'}), '(n_clusters=noOfCluster, n_jobs=5)\n', (6197, 6231), False, 'from sklearn.cluster import KMeans\n'), ((5488, 5547), 'numpy.array', 'np.array', (['[numoffeattypeA, numoffeattypeA + numoffeattypeB]'], {}), '([numoffeattypeA, numoffeattypeA + numoffeattypeB])\n', (5496, 5547), True, 'import numpy as np\n')]
|
# Author: <NAME>
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.special import logsumexp
'''
z = Wx + µ + E
the equation above represents the latent variable model which
relates a d-dimensional data vector z to a corresponding q-dimensional
latent variables x
with q < d, for isotropic noise E ∼ N (0, σ2I)
z : latent
x : data
W : latent_to_observation matrix
µ : centres_of_clusters
E : var_of_latent
This code is an implementation of generative model of mixture of PPCA
Given the number of clusters, data_dim(D) and latent_dim(L)
we generate the data for every cluster n,
we sample zn from a Gaussian prior and pass it through the
Wk matrix and add noise, where Wk maps from the L-dimensional subspace to the D-dimensional
visible space. Using the expectation maximization algorithm we estimate the parameters
and then we plot the PC vectors
'''
def mixture_ppca_parameter_initialization(data, n_clusters, latent_dim,
n_iterations):
"""
The k-means algorithm is used to determine the centres. The
priors are computed from the proportion of examples belonging to each
cluster. The covariance matrices are calculated as the sample
covariance of the points associated with (i.e. closest to) the
corresponding centres. For a mixture of PPCA model, the PPCA
decomposition is calculated for the points closest to a given centre.
This initialisation can be used as the starting point for training
the model using the EM algorithm.
W : latent_to_observation matrix
µ/mu : centres_of_clusters
pi : proportion of data in each cluster
sigma2 : variance of latent
covars : covariance of the points associated with (i.e. closest to) the
corresponding centres
"""
n_datapts, data_dim = data.shape
# initialization of the centres of clusters
init_centers = np.random.randint(0, n_datapts, n_clusters)
# Randomly choose distinct initial centres for the clusters
while (len(np.unique(init_centers)) != n_clusters):
init_centers = np.random.randint(0, n_datapts, n_clusters)
mu = data[init_centers, :]
distance_square = np.zeros((n_datapts, n_clusters))
clusters = np.zeros(n_datapts, dtype=np.int32)
# Running iterations for K means algorithm to assign centres for clusters
for k in range(n_iterations):
# assign clusters
for c in range(n_clusters):
distance_square[:, c] = np.power(data - mu[c, :], 2).sum(1)
clusters = np.argmin(distance_square, axis=1)
# compute distortion
distmin = distance_square[range(n_datapts), clusters]
# compute new centers
for c in range(n_clusters):
mu[c, :] = data[clusters == c, :].mean(0)
# parameter initialization
pi = np.zeros(n_clusters) # Sum should be equal to 1
W = np.zeros((n_clusters, data_dim, latent_dim))
sigma2 = np.zeros(n_clusters)
for c in range(n_clusters):
W[c, :, :] = np.random.randn(data_dim, latent_dim)
pi[c] = (clusters == c).sum() / n_datapts
sigma2[c] = (distmin[clusters == c]).mean() / data_dim
covars = np.zeros(n_clusters)
for i in range(n_clusters):
covars[i] = (np.var(data[clusters == i, 0]) +
np.var(data[clusters == i, 1])) / 2
return pi, mu, W, sigma2, covars, clusters
def mixture_ppca_expectation_maximization(data, pi, mu, W, sigma2, niter):
'''
we can find the p(latent|data) with the assumption that data is gaussian
z : latent
x : data
W : latent_to_observation matrix
µ/mu : centres_of_clusters
d : data_dimension
q : latent_dimention
σ2/ sigma2 : variance of latent
π/pi : cluster proportion
p(z|x) = (2πσ2)^−d/2 * exp(−1/(2σ2) * ||z − Wx − µ||)
p(z) = ∫p(z|x)p(x)dx
Solving for p(z) and then using the result we can find the p(x|z)
through which we can find
the log likelihood function which is
log_likelihood = −N/2 * (d ln(2π) + ln |Σ| + tr(Σ−1S))
We can develop an iterative EM algorithm for
optimisation of all of the model parameters µ,W and σ2
If Rn,i = p(zn, i) is the posterior responsibility of
mixture i for generating data point zn,given by
Rn,i = (p(zn|i) * πi) / p(zn)
Using EM, the parameter estimates are as follows:
µi = Σ (Rn,i * zn) / Σ Rn,i
Si = 1/(πi*N) * ΣRn,i*(zn − µi)*(zn − µi)'
Using Si we can estimate W and σ2
For more information on EM algorithm for mixture of PPCA
visit Mixtures of Probabilistic Principal Component Analysers
by <NAME> and <NAME>:
page 5-10 of http://www.miketipping.com/papers/met-mppca.pdf
'''
n_datapts, data_dim = data.shape
n_clusters = len(sigma2)
_, latent_dim = W[0].shape
M = np.zeros((n_clusters, latent_dim, latent_dim))
Minv = np.zeros((n_clusters, latent_dim, latent_dim))
Cinv = np.zeros((n_clusters, data_dim, data_dim))
logR = np.zeros((n_datapts, n_clusters))
R = np.zeros((n_datapts, n_clusters))
M[:] = 0.
Minv[:] = 0.
Cinv[:] = 0.
log_likelihood = np.zeros(niter)
for i in range(niter):
print('.', end='')
for c in range(n_clusters):
# M
'''
M = σ2I + WT.W
'''
M[c, :, :] = sigma2[c] * np.eye(latent_dim) + np.dot(W[c, :, :].T, W[c, :, :])
Minv[c, :, :] = np.linalg.inv(M[c, :, :])
# Cinv
Cinv[c, :, :] = (np.eye(data_dim)
- np.dot(np.dot(W[c, :, :], Minv[c, :, :]), W[c, :, :].T)
) / sigma2[c]
# R_ni
deviation_from_center = data - mu[c, :]
logR[:, c] = (np.log(pi[c])
+ 0.5 * np.log(
np.linalg.det(
np.eye(data_dim) - np.dot(np.dot(W[c, :, :],
Minv[c, :, :]), W[c, :, :].T)
)
)
- 0.5 * data_dim * np.log(sigma2[c])
- 0.5 * (deviation_from_center * np.dot(deviation_from_center,
Cinv[c, :, :].T)).sum(1)
)
'''
Using the log-sum-trick, visit Section 2.5.4 in "Probabilistic Machine Learning: An Introduction" by <NAME> for more information
logsumexp(logR - myMax, axis=1) can be replaced by logsumexp(logR, axis=1)
myMax + logsumexp((logR - myMax), axis=0) can be replaced by logsumexp(logR, axis=0)
myMax in the above equations refer to
myMax = logR.max(axis=0) & myMax = logR.max(axis=1).reshape((n_datapts, 1))
'''
log_likelihood[i] = (
(logsumexp(logR, axis=1)).sum(axis=0)
- n_datapts * data_dim * np.log(2 * math.pi) / 2.
)
logR = logR - np.reshape(logsumexp(logR, axis=1),
(n_datapts, 1))
logpi = logsumexp(logR, axis=0) - np.log(n_datapts)
logpi = logpi.T
pi = np.exp(logpi)
R = np.exp(logR)
for c in range(n_clusters):
mu[c, :] = (R[:, c].reshape((n_datapts, 1)) * data).sum(axis=0) / R[:, c].sum()
deviation_from_center = data - mu[c, :].reshape((1, data_dim))
'''
Si = 1/(πi*N) * ΣRn,i*(zn − µi)*(zn − µi)'
Si is used to estimate
'''
Si = ((1 / (pi[c] * n_datapts))
* np.dot((R[:, c].reshape((n_datapts, 1)) * deviation_from_center).T,
np.dot(deviation_from_center, W[c, :, :]))
)
Wnew = np.dot(Si, np.linalg.inv(sigma2[c] * np.eye(latent_dim)
+ np.dot(np.dot(Minv[c, :, :], W[c, :, :].T), Si)))
sigma2[c] = (1 / data_dim) * (
(R[:, c].reshape(n_datapts, 1) * np.power(deviation_from_center, 2)).sum()
/
(n_datapts * pi[c])
-
np.trace(np.dot(np.dot(Si, Minv[c, :, :]), Wnew.T))
)
W[c, :, :] = Wnew
return pi, mu, W, sigma2, log_likelihood
def generate_data():
n = 500
r = np.random.rand(1, n) + 1
theta = np.random.rand(1, n) * (2 * math.pi)
x1 = r * np.sin(theta)
x2 = r * np.cos(theta)
X = np.vstack((x1, x2))
return np.transpose(X)
def mixppcademo(data, n_clusters):
'''
W : latent to observation matrix
mu : centres_of_clusters
pi : proportions of data in each of the cluster
sigma2 : variance of latent
L : log likelihood after each iteration
covars : covariance of the points associated with (i.e. closest to) the
corresponding centres
'''
plt.plot(data[:, 0], data[:, 1], 'o', c='blue', mfc='none')
pi, mu, W, sigma2, covars, clusters = mixture_ppca_parameter_initialization(
data, n_clusters, latent_dim=1, n_iterations=10)
pi, mu, W, sigma2, L = mixture_ppca_expectation_maximization(data, pi, mu,
W, sigma2, 10)
for i in range(n_clusters):
v = W[i, :, :]
#Plotting the pc vectors using 2 standard deviations
start = mu[i].reshape((2, 1)) - (v * 2 * np.sqrt(sigma2[i]))
endpt = mu[i].reshape((2, 1)) + (v * 2 * np.sqrt(sigma2[i]))
linex = [start[0], endpt[0]]
liney = [start[1], endpt[1]]
plt.plot(linex, liney, linewidth=3, c='black')
theta = np.arange(0, 2 * math.pi, 0.02)
#Plotting the confidence interval ellipse using 2 standard deviations
x = 2 * np.sqrt(sigma2[i]) * np.cos(theta)
y = np.sqrt(covars[i]) * np.sin(theta)
rot_matrix = np.vstack((np.hstack((v[0], -v[1])), np.hstack((v[1], v[0]))))
ellipse = np.dot(rot_matrix, np.vstack((x, y)))
ellipse = np.transpose(ellipse)
ellipse = ellipse + np.dot(np.ones((len(theta), 1)), mu[i, :].reshape((1, 2)))
plt.plot(ellipse[:, 0], ellipse[:, 1], c='crimson')
def main():
np.random.seed(61)
data = generate_data()
plt.figure(0)
mixppcademo(data, n_clusters=1)
plt.savefig("mixppca_k-1.png", dpi=300)
np.random.seed(7)
data = generate_data()
plt.figure(1)
mixppcademo(data, n_clusters=10)
plt.savefig("mixppca_k-10.png", dpi=300)
plt.show()
if __name__ == "__main__":
main()
|
[
"numpy.random.seed",
"numpy.argmin",
"matplotlib.pyplot.figure",
"numpy.random.randint",
"numpy.sin",
"numpy.exp",
"numpy.arange",
"scipy.special.logsumexp",
"numpy.unique",
"numpy.random.randn",
"numpy.power",
"numpy.transpose",
"numpy.var",
"matplotlib.pyplot.show",
"numpy.hstack",
"numpy.linalg.inv",
"numpy.cos",
"numpy.dot",
"numpy.vstack",
"numpy.log",
"matplotlib.pyplot.plot",
"numpy.zeros",
"numpy.random.rand",
"numpy.eye",
"matplotlib.pyplot.savefig",
"numpy.sqrt"
] |
[((1916, 1959), 'numpy.random.randint', 'np.random.randint', (['(0)', 'n_datapts', 'n_clusters'], {}), '(0, n_datapts, n_clusters)\n', (1933, 1959), True, 'import numpy as np\n'), ((2205, 2238), 'numpy.zeros', 'np.zeros', (['(n_datapts, n_clusters)'], {}), '((n_datapts, n_clusters))\n', (2213, 2238), True, 'import numpy as np\n'), ((2255, 2290), 'numpy.zeros', 'np.zeros', (['n_datapts'], {'dtype': 'np.int32'}), '(n_datapts, dtype=np.int32)\n', (2263, 2290), True, 'import numpy as np\n'), ((2857, 2877), 'numpy.zeros', 'np.zeros', (['n_clusters'], {}), '(n_clusters)\n', (2865, 2877), True, 'import numpy as np\n'), ((2915, 2959), 'numpy.zeros', 'np.zeros', (['(n_clusters, data_dim, latent_dim)'], {}), '((n_clusters, data_dim, latent_dim))\n', (2923, 2959), True, 'import numpy as np\n'), ((2974, 2994), 'numpy.zeros', 'np.zeros', (['n_clusters'], {}), '(n_clusters)\n', (2982, 2994), True, 'import numpy as np\n'), ((3217, 3237), 'numpy.zeros', 'np.zeros', (['n_clusters'], {}), '(n_clusters)\n', (3225, 3237), True, 'import numpy as np\n'), ((4962, 5008), 'numpy.zeros', 'np.zeros', (['(n_clusters, latent_dim, latent_dim)'], {}), '((n_clusters, latent_dim, latent_dim))\n', (4970, 5008), True, 'import numpy as np\n'), ((5021, 5067), 'numpy.zeros', 'np.zeros', (['(n_clusters, latent_dim, latent_dim)'], {}), '((n_clusters, latent_dim, latent_dim))\n', (5029, 5067), True, 'import numpy as np\n'), ((5080, 5122), 'numpy.zeros', 'np.zeros', (['(n_clusters, data_dim, data_dim)'], {}), '((n_clusters, data_dim, data_dim))\n', (5088, 5122), True, 'import numpy as np\n'), ((5135, 5168), 'numpy.zeros', 'np.zeros', (['(n_datapts, n_clusters)'], {}), '((n_datapts, n_clusters))\n', (5143, 5168), True, 'import numpy as np\n'), ((5178, 5211), 'numpy.zeros', 'np.zeros', (['(n_datapts, n_clusters)'], {}), '((n_datapts, n_clusters))\n', (5186, 5211), True, 'import numpy as np\n'), ((5285, 5300), 'numpy.zeros', 'np.zeros', (['niter'], {}), '(niter)\n', (5293, 5300), True, 'import numpy as np\n'), ((8738, 8757), 'numpy.vstack', 'np.vstack', (['(x1, x2)'], {}), '((x1, x2))\n', (8747, 8757), True, 'import numpy as np\n'), ((8770, 8785), 'numpy.transpose', 'np.transpose', (['X'], {}), '(X)\n', (8782, 8785), True, 'import numpy as np\n'), ((9149, 9208), 'matplotlib.pyplot.plot', 'plt.plot', (['data[:, 0]', 'data[:, 1]', '"""o"""'], {'c': '"""blue"""', 'mfc': '"""none"""'}), "(data[:, 0], data[:, 1], 'o', c='blue', mfc='none')\n", (9157, 9208), True, 'import matplotlib.pyplot as plt\n'), ((10486, 10504), 'numpy.random.seed', 'np.random.seed', (['(61)'], {}), '(61)\n', (10500, 10504), True, 'import numpy as np\n'), ((10538, 10551), 'matplotlib.pyplot.figure', 'plt.figure', (['(0)'], {}), '(0)\n', (10548, 10551), True, 'import matplotlib.pyplot as plt\n'), ((10594, 10633), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""mixppca_k-1.png"""'], {'dpi': '(300)'}), "('mixppca_k-1.png', dpi=300)\n", (10605, 10633), True, 'import matplotlib.pyplot as plt\n'), ((10639, 10656), 'numpy.random.seed', 'np.random.seed', (['(7)'], {}), '(7)\n', (10653, 10656), True, 'import numpy as np\n'), ((10690, 10703), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (10700, 10703), True, 'import matplotlib.pyplot as plt\n'), ((10747, 10787), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""mixppca_k-10.png"""'], {'dpi': '(300)'}), "('mixppca_k-10.png', dpi=300)\n", (10758, 10787), True, 'import matplotlib.pyplot as plt\n'), ((10793, 10803), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10801, 10803), True, 'import matplotlib.pyplot as plt\n'), ((2106, 2149), 'numpy.random.randint', 'np.random.randint', (['(0)', 'n_datapts', 'n_clusters'], {}), '(0, n_datapts, n_clusters)\n', (2123, 2149), True, 'import numpy as np\n'), ((2562, 2596), 'numpy.argmin', 'np.argmin', (['distance_square'], {'axis': '(1)'}), '(distance_square, axis=1)\n', (2571, 2596), True, 'import numpy as np\n'), ((3050, 3087), 'numpy.random.randn', 'np.random.randn', (['data_dim', 'latent_dim'], {}), '(data_dim, latent_dim)\n', (3065, 3087), True, 'import numpy as np\n'), ((7378, 7391), 'numpy.exp', 'np.exp', (['logpi'], {}), '(logpi)\n', (7384, 7391), True, 'import numpy as np\n'), ((7405, 7417), 'numpy.exp', 'np.exp', (['logR'], {}), '(logR)\n', (7411, 7417), True, 'import numpy as np\n'), ((8598, 8618), 'numpy.random.rand', 'np.random.rand', (['(1)', 'n'], {}), '(1, n)\n', (8612, 8618), True, 'import numpy as np\n'), ((8636, 8656), 'numpy.random.rand', 'np.random.rand', (['(1)', 'n'], {}), '(1, n)\n', (8650, 8656), True, 'import numpy as np\n'), ((8687, 8700), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (8693, 8700), True, 'import numpy as np\n'), ((8715, 8728), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (8721, 8728), True, 'import numpy as np\n'), ((9856, 9902), 'matplotlib.pyplot.plot', 'plt.plot', (['linex', 'liney'], {'linewidth': '(3)', 'c': '"""black"""'}), "(linex, liney, linewidth=3, c='black')\n", (9864, 9902), True, 'import matplotlib.pyplot as plt\n'), ((9920, 9951), 'numpy.arange', 'np.arange', (['(0)', '(2 * math.pi)', '(0.02)'], {}), '(0, 2 * math.pi, 0.02)\n', (9929, 9951), True, 'import numpy as np\n'), ((10293, 10314), 'numpy.transpose', 'np.transpose', (['ellipse'], {}), '(ellipse)\n', (10305, 10314), True, 'import numpy as np\n'), ((10412, 10463), 'matplotlib.pyplot.plot', 'plt.plot', (['ellipse[:, 0]', 'ellipse[:, 1]'], {'c': '"""crimson"""'}), "(ellipse[:, 0], ellipse[:, 1], c='crimson')\n", (10420, 10463), True, 'import matplotlib.pyplot as plt\n'), ((2041, 2064), 'numpy.unique', 'np.unique', (['init_centers'], {}), '(init_centers)\n', (2050, 2064), True, 'import numpy as np\n'), ((5599, 5624), 'numpy.linalg.inv', 'np.linalg.inv', (['M[c, :, :]'], {}), '(M[c, :, :])\n', (5612, 5624), True, 'import numpy as np\n'), ((7295, 7318), 'scipy.special.logsumexp', 'logsumexp', (['logR'], {'axis': '(0)'}), '(logR, axis=0)\n', (7304, 7318), False, 'from scipy.special import logsumexp\n'), ((7321, 7338), 'numpy.log', 'np.log', (['n_datapts'], {}), '(n_datapts)\n', (7327, 7338), True, 'import numpy as np\n'), ((10069, 10082), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (10075, 10082), True, 'import numpy as np\n'), ((10096, 10114), 'numpy.sqrt', 'np.sqrt', (['covars[i]'], {}), '(covars[i])\n', (10103, 10114), True, 'import numpy as np\n'), ((10118, 10131), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (10124, 10131), True, 'import numpy as np\n'), ((10255, 10272), 'numpy.vstack', 'np.vstack', (['(x, y)'], {}), '((x, y))\n', (10264, 10272), True, 'import numpy as np\n'), ((3293, 3323), 'numpy.var', 'np.var', (['data[clusters == i, 0]'], {}), '(data[clusters == i, 0])\n', (3299, 3323), True, 'import numpy as np\n'), ((3348, 3378), 'numpy.var', 'np.var', (['data[clusters == i, 1]'], {}), '(data[clusters == i, 1])\n', (3354, 3378), True, 'import numpy as np\n'), ((5535, 5567), 'numpy.dot', 'np.dot', (['W[c, :, :].T', 'W[c, :, :]'], {}), '(W[c, :, :].T, W[c, :, :])\n', (5541, 5567), True, 'import numpy as np\n'), ((7193, 7216), 'scipy.special.logsumexp', 'logsumexp', (['logR'], {'axis': '(1)'}), '(logR, axis=1)\n', (7202, 7216), False, 'from scipy.special import logsumexp\n'), ((9681, 9699), 'numpy.sqrt', 'np.sqrt', (['sigma2[i]'], {}), '(sigma2[i])\n', (9688, 9699), True, 'import numpy as np\n'), ((9751, 9769), 'numpy.sqrt', 'np.sqrt', (['sigma2[i]'], {}), '(sigma2[i])\n', (9758, 9769), True, 'import numpy as np\n'), ((10048, 10066), 'numpy.sqrt', 'np.sqrt', (['sigma2[i]'], {}), '(sigma2[i])\n', (10055, 10066), True, 'import numpy as np\n'), ((10165, 10189), 'numpy.hstack', 'np.hstack', (['(v[0], -v[1])'], {}), '((v[0], -v[1]))\n', (10174, 10189), True, 'import numpy as np\n'), ((10191, 10214), 'numpy.hstack', 'np.hstack', (['(v[1], v[0])'], {}), '((v[1], v[0]))\n', (10200, 10214), True, 'import numpy as np\n'), ((2506, 2534), 'numpy.power', 'np.power', (['(data - mu[c, :])', '(2)'], {}), '(data - mu[c, :], 2)\n', (2514, 2534), True, 'import numpy as np\n'), ((5514, 5532), 'numpy.eye', 'np.eye', (['latent_dim'], {}), '(latent_dim)\n', (5520, 5532), True, 'import numpy as np\n'), ((5677, 5693), 'numpy.eye', 'np.eye', (['data_dim'], {}), '(data_dim)\n', (5683, 5693), True, 'import numpy as np\n'), ((7042, 7065), 'scipy.special.logsumexp', 'logsumexp', (['logR'], {'axis': '(1)'}), '(logR, axis=1)\n', (7051, 7065), False, 'from scipy.special import logsumexp\n'), ((7121, 7140), 'numpy.log', 'np.log', (['(2 * math.pi)'], {}), '(2 * math.pi)\n', (7127, 7140), True, 'import numpy as np\n'), ((7913, 7954), 'numpy.dot', 'np.dot', (['deviation_from_center', 'W[c, :, :]'], {}), '(deviation_from_center, W[c, :, :])\n', (7919, 7954), True, 'import numpy as np\n'), ((5733, 5766), 'numpy.dot', 'np.dot', (['W[c, :, :]', 'Minv[c, :, :]'], {}), '(W[c, :, :], Minv[c, :, :])\n', (5739, 5766), True, 'import numpy as np\n'), ((5928, 5941), 'numpy.log', 'np.log', (['pi[c]'], {}), '(pi[c])\n', (5934, 5941), True, 'import numpy as np\n'), ((6287, 6304), 'numpy.log', 'np.log', (['sigma2[c]'], {}), '(sigma2[c])\n', (6293, 6304), True, 'import numpy as np\n'), ((8036, 8054), 'numpy.eye', 'np.eye', (['latent_dim'], {}), '(latent_dim)\n', (8042, 8054), True, 'import numpy as np\n'), ((8109, 8144), 'numpy.dot', 'np.dot', (['Minv[c, :, :]', 'W[c, :, :].T'], {}), '(Minv[c, :, :], W[c, :, :].T)\n', (8115, 8144), True, 'import numpy as np\n'), ((8418, 8443), 'numpy.dot', 'np.dot', (['Si', 'Minv[c, :, :]'], {}), '(Si, Minv[c, :, :])\n', (8424, 8443), True, 'import numpy as np\n'), ((6365, 6411), 'numpy.dot', 'np.dot', (['deviation_from_center', 'Cinv[c, :, :].T'], {}), '(deviation_from_center, Cinv[c, :, :].T)\n', (6371, 6411), True, 'import numpy as np\n'), ((8252, 8286), 'numpy.power', 'np.power', (['deviation_from_center', '(2)'], {}), '(deviation_from_center, 2)\n', (8260, 8286), True, 'import numpy as np\n'), ((6054, 6070), 'numpy.eye', 'np.eye', (['data_dim'], {}), '(data_dim)\n', (6060, 6070), True, 'import numpy as np\n'), ((6080, 6113), 'numpy.dot', 'np.dot', (['W[c, :, :]', 'Minv[c, :, :]'], {}), '(W[c, :, :], Minv[c, :, :])\n', (6086, 6113), True, 'import numpy as np\n')]
|
"""[summary]
"""
import os
import numpy as np
import tensorflow as tf
from src.utils import evaluation
from src.draw import draw
class GCLSemi:
"""[summary]
"""
def __init__(self, train_relevance_labels, train_features,
test_relevance_labels, test_features, test_query_ids, train_features_u):
"""[summary]
Args:
train_relevance_labels ([type]): [description]
train_features ([type]): [description]
test_relevance_labels ([type]): [description]
test_features ([type]): [description]
test_query_ids ([type]): [description]
train_features_u ([type]): [description]
"""
self.y_labeled2 = train_relevance_labels
self.x_labeled = train_features
self.x_unlabeled = train_features_u
self.y_unlabeled = np.zeros([self.x_unlabeled.shape[0], 1])
self.test_labels = test_relevance_labels
self.test_features = test_features
self.test_ids = test_query_ids
self.n_feature = 0
self.n_samples = 0
x = self.x_labeled
y = self.y_labeled2.reshape(-1, 1)
x_y = np.concatenate((x, y), axis=1)
np.random.seed(1)
np.random.shuffle(x_y)
self.x_labeled = x_y[:, :-1]
self.y_labeled2 = x_y[:, -1].reshape(-1,)
# ------ PARAM -----#
self.n_point = 40
self.seed = 37
self.is_change = False
self.learning_rate = 0.009
self.batch_a = 190 # 200 is for GLOBAL+ 500 is for number of party 4
self.batch_b = 200
self.lamb = 0.5
self.beta = 0.
self.r = 0.2
self.a = 0.0
self.af = 0.001
self.t1 = 0
self.t2 = 200
self.n_iter = 300
# end of param ##
# def fit(self, from_fed, to_fed, DATA_PATH, FEATURE_NUM=16):
def fit(self, from_fed, to_fed, _, feature_num=16):
"""[summary]
Args:
from_fed ([type]): [description]
to_fed ([type]): [description]
DATA_PATH ([type]): [description]
FEATURE_NUM (int, optional): [description]. Defaults to 16.
"""
fed_num = to_fed - from_fed
# initial
ws1 = np.load(os.path.join("/data/ltrdata", "w1%d.npy" % from_fed))
ws2 = np.load(os.path.join("/data/ltrdata", "w2%d.npy" % from_fed))
bs1 = np.load(os.path.join("/data/ltrdata", "b1%d.npy" % from_fed))
bs2 = np.load(os.path.join("/data/ltrdata", "b2%d.npy" % from_fed))
for i in range(from_fed + 1, to_fed):
ws1 += np.load(os.path.join("/data/ltrdata", "w1%d.npy" % i))
ws2 += np.load(os.path.join("/data/ltrdata", "w2%d.npy" % i))
bs1 += np.load(os.path.join("/data/ltrdata", "b1%d.npy" % i))
bs2 += np.load(os.path.join("/data/ltrdata", "b2%d.npy" % i))
ws1 /= fed_num
ws2 /= fed_num
bs1 /= fed_num
bs2 /= fed_num
ws = np.load(os.path.join("/data/ltrdata", "semi_ws%d.npy" % from_fed))
bs = np.load(os.path.join("/data/ltrdata", "semi_bs%d.npy" % from_fed))
for i in range(from_fed + 1, to_fed):
ws += np.load(os.path.join("/data/ltrdata", "semi_ws%d.npy" % i))
bs += np.load(os.path.join("/data/ltrdata", "semi_bs%d.npy" % i))
ws /= fed_num
bs /= fed_num
ws *= 0.1
bs *= 0.1
ws += 0.1 * np.random.randn(ws.shape[0], ws.shape[1])
bs += 0.1 * np.random.randn(bs.shape[0])
x = tf.placeholder(dtype='float', shape=[None, feature_num], name='x')
y = tf.placeholder(dtype='float', shape=[None], name='y')
w = tf.Variable(tf.constant(ws), name='w')
b = tf.Variable(tf.constant(bs), name='b')
pred = tf.transpose(tf.add(tf.matmul(x, w), b))
x_u = tf.placeholder(
dtype='float', shape=[
None, feature_num], name='xu')
pred_u = tf.add(tf.matmul(x_u, w), b)
pred_us = tf.nn.softmax(tf.add(tf.matmul(tf.add(tf.matmul(x_u, ws1), bs1), ws2), bs2))
alpha = tf.placeholder("float",)
pred_pl = tf.placeholder(dtype='float', shape=[None, 1], name='predspl')
cost = tf.add(self.lamb * tf.reduce_mean(tf.square(w)),
tf.add(tf.reduce_mean(tf.square(pred - y) / 2),
alpha * tf.reduce_mean(tf.square(pred_pl - pred_u)) / 2))
opt = tf.train.AdamOptimizer(self.learning_rate).minimize(cost)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
self.y_unlabeled = sess.run(pred_us, feed_dict={x_u: self.x_unlabeled})
y_l2 = []
for each in self.y_unlabeled:
if each[0] > each[1] and each[0] > each[2]:
y_l2.append(0)
elif each[1] > each[0] and each[1] > each[2]:
y_l2.append(1)
else:
y_l2.append(2)
self.y_unlabeled = np.array(y_l2)
auc_iters = []
map_iters = []
ndcg10_iters = []
ndcg_iters = []
err_iters = []
for it in range(self.n_iter):
if it > self.t1: a = min((it - self.t1) / (self.t2 - self.t1) * self.af, self.af)
self.beta /= (1 + 0.5 * it)
loss_one_fed = []
x = self.x_labeled
y = self.y_labeled2.reshape(-1, 1)
left = it * self.batch_a
right = left + self.batch_a
if left >= right or right > len(x):
left = 0
right = left + self.batch_a
batch_x = x[left: right]
batch_y = y[left: right].reshape(-1,)
x_unlabeled = self.x_unlabeled
y_unlabeled = self.y_unlabeled
left = it * self.batch_b
right = left + self.batch_b
if left >= right or right > len(x_unlabeled):
left = 0
right = left + self.batch_b
batch_x_unlabeled = x_unlabeled[left: right]
batch_y_unlabeled = y_unlabeled[left: right].reshape(-1, 1)
if it % (self.n_iter // self.n_point) == 0:
pred_for_testo = sess.run(pred, feed_dict={x: self.test_features})[0]
print(min(pred_for_testo), max(pred_for_testo), np.mean(pred_for_testo))
avg_err, avg_ndcg, avg_full_ndcg, avg_map, avg_auc = \
evaluation(pred_for_testo, self.test_labels, self.test_ids, self.test_features)
err_iters.append(avg_err)
auc_iters.append(avg_auc)
map_iters.append(avg_map)
ndcg10_iters.append(avg_ndcg)
ndcg_iters.append(avg_full_ndcg)
_, loss = sess.run([opt, cost],
feed_dict={x: batch_x, y: batch_y, x_u: batch_x_unlabeled,
pred_pl: batch_y_unlabeled, alpha: a})
loss_one_fed.append(loss)
draw([i for i in range(len(ndcg10_iters))], [ndcg10_iters])
print("%f, %f, %f, %f;" % (err_iters[-1], ndcg10_iters[-1], ndcg_iters[-1], map_iters[-1]))
print("nfed_sol4=", ndcg10_iters, ";")
|
[
"numpy.random.seed",
"numpy.concatenate",
"numpy.random.randn",
"tensorflow.global_variables_initializer",
"numpy.zeros",
"tensorflow.Session",
"tensorflow.constant",
"tensorflow.placeholder",
"tensorflow.matmul",
"numpy.mean",
"numpy.array",
"tensorflow.square",
"tensorflow.train.AdamOptimizer",
"os.path.join",
"numpy.random.shuffle",
"src.utils.evaluation"
] |
[((855, 895), 'numpy.zeros', 'np.zeros', (['[self.x_unlabeled.shape[0], 1]'], {}), '([self.x_unlabeled.shape[0], 1])\n', (863, 895), True, 'import numpy as np\n'), ((1165, 1195), 'numpy.concatenate', 'np.concatenate', (['(x, y)'], {'axis': '(1)'}), '((x, y), axis=1)\n', (1179, 1195), True, 'import numpy as np\n'), ((1204, 1221), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (1218, 1221), True, 'import numpy as np\n'), ((1230, 1252), 'numpy.random.shuffle', 'np.random.shuffle', (['x_y'], {}), '(x_y)\n', (1247, 1252), True, 'import numpy as np\n'), ((3531, 3597), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': '"""float"""', 'shape': '[None, feature_num]', 'name': '"""x"""'}), "(dtype='float', shape=[None, feature_num], name='x')\n", (3545, 3597), True, 'import tensorflow as tf\n'), ((3610, 3663), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': '"""float"""', 'shape': '[None]', 'name': '"""y"""'}), "(dtype='float', shape=[None], name='y')\n", (3624, 3663), True, 'import tensorflow as tf\n'), ((3836, 3903), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': '"""float"""', 'shape': '[None, feature_num]', 'name': '"""xu"""'}), "(dtype='float', shape=[None, feature_num], name='xu')\n", (3850, 3903), True, 'import tensorflow as tf\n'), ((4091, 4114), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""'], {}), "('float')\n", (4105, 4114), True, 'import tensorflow as tf\n'), ((4134, 4196), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': '"""float"""', 'shape': '[None, 1]', 'name': '"""predspl"""'}), "(dtype='float', shape=[None, 1], name='predspl')\n", (4148, 4196), True, 'import tensorflow as tf\n'), ((4505, 4538), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (4536, 4538), True, 'import tensorflow as tf\n'), ((2250, 2302), 'os.path.join', 'os.path.join', (['"""/data/ltrdata"""', "('w1%d.npy' % from_fed)"], {}), "('/data/ltrdata', 'w1%d.npy' % from_fed)\n", (2262, 2302), False, 'import os\n'), ((2326, 2378), 'os.path.join', 'os.path.join', (['"""/data/ltrdata"""', "('w2%d.npy' % from_fed)"], {}), "('/data/ltrdata', 'w2%d.npy' % from_fed)\n", (2338, 2378), False, 'import os\n'), ((2402, 2454), 'os.path.join', 'os.path.join', (['"""/data/ltrdata"""', "('b1%d.npy' % from_fed)"], {}), "('/data/ltrdata', 'b1%d.npy' % from_fed)\n", (2414, 2454), False, 'import os\n'), ((2478, 2530), 'os.path.join', 'os.path.join', (['"""/data/ltrdata"""', "('b2%d.npy' % from_fed)"], {}), "('/data/ltrdata', 'b2%d.npy' % from_fed)\n", (2490, 2530), False, 'import os\n'), ((2987, 3044), 'os.path.join', 'os.path.join', (['"""/data/ltrdata"""', "('semi_ws%d.npy' % from_fed)"], {}), "('/data/ltrdata', 'semi_ws%d.npy' % from_fed)\n", (2999, 3044), False, 'import os\n'), ((3067, 3124), 'os.path.join', 'os.path.join', (['"""/data/ltrdata"""', "('semi_bs%d.npy' % from_fed)"], {}), "('/data/ltrdata', 'semi_bs%d.npy' % from_fed)\n", (3079, 3124), False, 'import os\n'), ((3428, 3469), 'numpy.random.randn', 'np.random.randn', (['ws.shape[0]', 'ws.shape[1]'], {}), '(ws.shape[0], ws.shape[1])\n', (3443, 3469), True, 'import numpy as np\n'), ((3490, 3518), 'numpy.random.randn', 'np.random.randn', (['bs.shape[0]'], {}), '(bs.shape[0])\n', (3505, 3518), True, 'import numpy as np\n'), ((3688, 3703), 'tensorflow.constant', 'tf.constant', (['ws'], {}), '(ws)\n', (3699, 3703), True, 'import tensorflow as tf\n'), ((3739, 3754), 'tensorflow.constant', 'tf.constant', (['bs'], {}), '(bs)\n', (3750, 3754), True, 'import tensorflow as tf\n'), ((3958, 3975), 'tensorflow.matmul', 'tf.matmul', (['x_u', 'w'], {}), '(x_u, w)\n', (3967, 3975), True, 'import tensorflow as tf\n'), ((4552, 4564), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (4562, 4564), True, 'import tensorflow as tf\n'), ((5029, 5043), 'numpy.array', 'np.array', (['y_l2'], {}), '(y_l2)\n', (5037, 5043), True, 'import numpy as np\n'), ((2605, 2650), 'os.path.join', 'os.path.join', (['"""/data/ltrdata"""', "('w1%d.npy' % i)"], {}), "('/data/ltrdata', 'w1%d.npy' % i)\n", (2617, 2650), False, 'import os\n'), ((2679, 2724), 'os.path.join', 'os.path.join', (['"""/data/ltrdata"""', "('w2%d.npy' % i)"], {}), "('/data/ltrdata', 'w2%d.npy' % i)\n", (2691, 2724), False, 'import os\n'), ((2753, 2798), 'os.path.join', 'os.path.join', (['"""/data/ltrdata"""', "('b1%d.npy' % i)"], {}), "('/data/ltrdata', 'b1%d.npy' % i)\n", (2765, 2798), False, 'import os\n'), ((2827, 2872), 'os.path.join', 'os.path.join', (['"""/data/ltrdata"""', "('b2%d.npy' % i)"], {}), "('/data/ltrdata', 'b2%d.npy' % i)\n", (2839, 2872), False, 'import os\n'), ((3198, 3248), 'os.path.join', 'os.path.join', (['"""/data/ltrdata"""', "('semi_ws%d.npy' % i)"], {}), "('/data/ltrdata', 'semi_ws%d.npy' % i)\n", (3210, 3248), False, 'import os\n'), ((3276, 3326), 'os.path.join', 'os.path.join', (['"""/data/ltrdata"""', "('semi_bs%d.npy' % i)"], {}), "('/data/ltrdata', 'semi_bs%d.npy' % i)\n", (3288, 3326), False, 'import os\n'), ((3801, 3816), 'tensorflow.matmul', 'tf.matmul', (['x', 'w'], {}), '(x, w)\n', (3810, 3816), True, 'import tensorflow as tf\n'), ((4432, 4474), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['self.learning_rate'], {}), '(self.learning_rate)\n', (4454, 4474), True, 'import tensorflow as tf\n'), ((4246, 4258), 'tensorflow.square', 'tf.square', (['w'], {}), '(w)\n', (4255, 4258), True, 'import tensorflow as tf\n'), ((6593, 6672), 'src.utils.evaluation', 'evaluation', (['pred_for_testo', 'self.test_labels', 'self.test_ids', 'self.test_features'], {}), '(pred_for_testo, self.test_labels, self.test_ids, self.test_features)\n', (6603, 6672), False, 'from src.utils import evaluation\n'), ((4036, 4055), 'tensorflow.matmul', 'tf.matmul', (['x_u', 'ws1'], {}), '(x_u, ws1)\n', (4045, 4055), True, 'import tensorflow as tf\n'), ((4305, 4324), 'tensorflow.square', 'tf.square', (['(pred - y)'], {}), '(pred - y)\n', (4314, 4324), True, 'import tensorflow as tf\n'), ((6469, 6492), 'numpy.mean', 'np.mean', (['pred_for_testo'], {}), '(pred_for_testo)\n', (6476, 6492), True, 'import numpy as np\n'), ((4383, 4410), 'tensorflow.square', 'tf.square', (['(pred_pl - pred_u)'], {}), '(pred_pl - pred_u)\n', (4392, 4410), True, 'import tensorflow as tf\n')]
|
# -*- coding: utf-8 -*-
import numpy as np
import logging, sys, operator
from matplotlib.colors import Normalize
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.ticker import MaxNLocator
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
from gseapy.parser import unique
class _MidpointNormalize(Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
def zscore(data2d, axis=0):
"""Standardize the mean and variance of the data axis Parameters.
:param data2d: DataFrame to normalize.
:param axis: int, Which axis to normalize across. If 0, normalize across rows,
if 1, normalize across columns. If None, don't change data
:Returns: Normalized DataFrame. Normalized data with a mean of 0 and variance of 1
across the specified axis.
"""
if axis is None:
# normalized to mean and std using entire matrix
# z_scored = (data2d - data2d.values.mean()) / data2d.values.std(ddof=1)
return data2d
assert axis in [0,1]
# if axis == 1:
# z_scored = data2d
# else:
# z_scored = data2d.T
# z_scored = (z_scored - z_scored.mean()) / z_scored.std(ddof=1)
# if axis == 1:
# return z_scored
# else:
# return z_scored.T
z_scored = data2d.apply(lambda x: (x-x.mean())/x.std(ddof=1),
axis=operator.xor(1, axis))
return z_scored
def colorbar(mappable):
ax = mappable.axes
fig = ax.figure
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="2%", pad=0.05)
return fig.colorbar(mappable, cax=cax)
def heatmap(df, z_score=None, title='', figsize=(5,5), cmap='RdBu_r',
xticklabels=True, yticklabels=True, ofname=None, **kwargs):
"""Visualize the dataframe.
:param df: DataFrame from expression table.
:param z_score: z_score axis{0, 1}. If None, don't normalize data.
:param title: gene set name.
:param outdir: path to save heatmap.
:param figsize: heatmap figsize.
:param cmap: matplotlib colormap.
:param ofname: output file name. If None, don't save figure
"""
df = zscore(df, axis=z_score)
df = df.iloc[::-1]
# Get the positions and used label for the ticks
ny, nx = df.shape
xticks = np.arange(0, nx, 1) + .5
yticks = np.arange(0, ny, 1) + .5
# If working on commandline, don't show figure
if hasattr(sys, 'ps1') and (ofname is None):
fig = plt.figure(figsize=figsize)
else:
fig = Figure(figsize=figsize)
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
vmin = np.percentile(df.min(), 2)
vmax = np.percentile(df.max(), 98)
matrix = ax.pcolormesh(df.values, cmap=cmap, vmin=vmin, vmax=vmax)
ax.set_ylim([0,len(df)])
ax.set(xticks=xticks, yticks=yticks)
ax.set_xticklabels(df.columns.values if xticklabels else '', fontsize=14, rotation=90)
ax.set_yticklabels(df.index.values if yticklabels else '', fontsize=14)
ax.set_title("%s\nHeatmap of the Analyzed Geneset"%title, fontsize=20)
ax.tick_params(axis='both', which='both', bottom=False, top=False,
right=False, left=False)
# cax=fig.add_axes([0.93,0.25,0.05,0.20])
# cbar = fig.colorbar(matrix, cax=cax)
cbar = colorbar(matrix)
cbar.ax.tick_params(axis='both', which='both', bottom=False, top=False,
right=False, left=False)
for side in ["top", "right", "left", "bottom"]:
ax.spines[side].set_visible(False)
cbar.ax.spines[side].set_visible(False)
# cbar.ax.set_title('',loc='left')
if ofname is not None:
# canvas.print_figure(ofname, bbox_inches='tight', dpi=300)
fig.savefig(ofname, bbox_inches='tight', dpi=300)
return
def gseaplot(rank_metric, term, hits_indices, nes, pval, fdr, RES,
pheno_pos='', pheno_neg='', figsize=(6,5.5),
cmap='seismic', ofname=None, **kwargs):
"""This is the main function for reproducing the gsea plot.
:param rank_metric: pd.Series for rankings, rank_metric.values.
:param term: gene_set name
:param hits_indices: hits indices of rank_metric.index presented in gene set S.
:param nes: Normalized enrichment scores.
:param pval: nominal p-value.
:param fdr: false discovery rate.
:param RES: running enrichment scores.
:param pheno_pos: phenotype label, positive correlated.
:param pheno_neg: phenotype label, negative correlated.
:param figsize: matplotlib figsize.
:param ofname: output file name. If None, don't save figure
"""
# plt.style.use('classic')
# center color map at midpoint = 0
norm = _MidpointNormalize(midpoint=0)
#dataFrame of ranked matrix scores
x = np.arange(len(rank_metric))
rankings = rank_metric.values
# figsize = (6,6)
phenoP_label = pheno_pos + ' (Positively Correlated)'
phenoN_label = pheno_neg + ' (Negatively Correlated)'
zero_score_ind = np.abs(rankings).argmin()
z_score_label = 'Zero score at ' + str(zero_score_ind)
nes_label = 'NES: '+ "{:.3f}".format(float(nes))
pval_label = 'Pval: '+ "{:.3f}".format(float(pval))
fdr_label = 'FDR: '+ "{:.3f}".format(float(fdr))
im_matrix = np.tile(rankings, (2,1))
# output truetype
plt.rcParams.update({'pdf.fonttype':42,'ps.fonttype':42})
# in most case, we will have many plots, so do not display plots
# It's also usefull to run this script on command line.
# GSEA Plots
gs = plt.GridSpec(16,1)
if hasattr(sys, 'ps1') and (ofname is None):
# working inside python console, show figure
fig = plt.figure(figsize=figsize)
else:
# If working on commandline, don't show figure
fig = Figure(figsize=figsize)
canvas = FigureCanvas(fig)
# Ranked Metric Scores Plot
ax1 = fig.add_subplot(gs[11:])
module = 'tmp' if ofname is None else ofname.split(".")[-2]
if module == 'ssgsea':
nes_label = 'ES: '+ "{:.3f}".format(float(nes))
pval_label='Pval: '
fdr_label='FDR: '
ax1.fill_between(x, y1=np.log(rankings), y2=0, color='#C9D3DB')
ax1.set_ylabel("log ranked metric", fontsize=14)
else:
ax1.fill_between(x, y1=rankings, y2=0, color='#C9D3DB')
ax1.set_ylabel("Ranked list metric", fontsize=14)
ax1.text(.05, .9, phenoP_label, color='red',
horizontalalignment='left', verticalalignment='top',
transform=ax1.transAxes)
ax1.text(.95, .05, phenoN_label, color='Blue',
horizontalalignment='right', verticalalignment='bottom',
transform=ax1.transAxes)
# the x coords of this transformation are data, and the y coord are axes
trans1 = transforms.blended_transform_factory(ax1.transData, ax1.transAxes)
if module != 'ssgsea':
ax1.vlines(zero_score_ind, 0, 1, linewidth=.5, transform=trans1, linestyles='--', color='grey')
ax1.text(zero_score_ind, 0.5, z_score_label,
horizontalalignment='center',
verticalalignment='center',
transform=trans1)
ax1.set_xlabel("Rank in Ordered Dataset", fontsize=14)
ax1.spines['top'].set_visible(False)
ax1.tick_params(axis='both', which='both', top=False, right=False, left=False)
ax1.locator_params(axis='y', nbins=5)
ax1.yaxis.set_major_formatter(plt.FuncFormatter(lambda tick_loc,tick_num : '{:.1f}'.format(tick_loc) ))
# use round method to control float number
# ax1.yaxis.set_major_formatter(plt.FuncFormatter(lambda tick_loc,tick_num : round(tick_loc, 1) ))
# gene hits
ax2 = fig.add_subplot(gs[8:10], sharex=ax1)
# the x coords of this transformation are data, and the y coord are axes
trans2 = transforms.blended_transform_factory(ax2.transData, ax2.transAxes)
ax2.vlines(hits_indices, 0, 1,linewidth=.5,transform=trans2)
ax2.spines['bottom'].set_visible(False)
ax2.tick_params(axis='both', which='both', bottom=False, top=False,
labelbottom=False, right=False, left=False, labelleft=False)
# colormap
ax3 = fig.add_subplot(gs[10], sharex=ax1)
ax3.imshow(im_matrix, aspect='auto', norm=norm, cmap=cmap, interpolation='none') # cm.coolwarm
ax3.spines['bottom'].set_visible(False)
ax3.tick_params(axis='both', which='both', bottom=False, top=False,
labelbottom=False, right=False, left=False,labelleft=False)
# Enrichment score plot
ax4 = fig.add_subplot(gs[:8], sharex=ax1)
ax4.plot(x, RES, linewidth=4, color ='#88C544')
ax4.text(.1, .1, fdr_label, transform=ax4.transAxes)
ax4.text(.1, .2, pval_label, transform=ax4.transAxes)
ax4.text(.1, .3, nes_label, transform=ax4.transAxes)
# the y coords of this transformation are data, and the x coord are axes
trans4 = transforms.blended_transform_factory(ax4.transAxes, ax4.transData)
ax4.hlines(0, 0, 1, linewidth=.5, transform=trans4, color='grey')
ax4.set_ylabel("Enrichment score (ES)", fontsize=14)
ax4.set_xlim(min(x), max(x))
ax4.tick_params(axis='both', which='both', bottom=False, top=False, labelbottom=False, right=False)
ax4.locator_params(axis='y', nbins=5)
# FuncFormatter need two argument, I don't know why. this lambda function used to format yaxis tick labels.
ax4.yaxis.set_major_formatter(plt.FuncFormatter(lambda tick_loc,tick_num : '{:.1f}'.format(tick_loc)) )
# fig adjustment
fig.suptitle(term, fontsize=16, fontweight='bold')
fig.subplots_adjust(hspace=0)
# fig.tight_layout()
if ofname is not None:
# canvas.print_figure(ofname, bbox_inches='tight', dpi=300)
fig.savefig(ofname, bbox_inches='tight', dpi=300)
return
def isfloat(x):
try:
float(x)
except:
return False
else:
return True
def dotplot(df, column='Adjusted P-value', title='', cutoff=0.05, top_term=10,
sizes=None, norm=None, legend=True, figsize=(6, 5.5),
cmap='RdBu_r', ofname=None, **kwargs):
"""Visualize enrichr results.
:param df: GSEApy DataFrame results.
:param column: which column of DataFrame to show. Default: Adjusted P-value
:param title: figure title
:param cutoff: p-adjust cut-off.
:param top_term: number of enriched terms to show.
:param ascending: bool, the order of y axis.
:param sizes: tuple, (min, max) scatter size. Not functional for now
:param norm: maplotlib.colors.Normalize object.
:param legend: bool, whether to show legend.
:param figsize: tuple, figure size.
:param cmap: matplotlib colormap
:param ofname: output file name. If None, don't save figure
"""
colname = column
# sorting the dataframe for better visualization
if colname in ['Adjusted P-value', 'P-value']:
# check if any values in `df[colname]` can't be coerced to floats
can_be_coerced = df[colname].map(isfloat)
if np.sum(~can_be_coerced) > 0:
raise ValueError('some value in %s could not be typecast to `float`'%colname)
else:
df.loc[:, colname] = df[colname].map(float)
df = df[df[colname] <= cutoff]
if len(df) < 1:
msg = "Warning: No enrich terms when cutoff = %s"%cutoff
return msg
df = df.assign(logAP=lambda x: - x[colname].apply(np.log10))
colname='logAP'
df = df.sort_values(by=colname).iloc[-top_term:,:]
#
temp = df['Overlap'].str.split("/", expand=True).astype(int)
df = df.assign(Hits=temp.iloc[:,0], Background=temp.iloc[:,1])
df = df.assign(Hits_ratio=lambda x:x.Hits / x.Background)
# x axis values
x = df.loc[:, colname].values
combined_score = df['Combined Score'].round().astype('int')
# y axis index and values
y = [i for i in range(0,len(df))]
ylabels = df['Term'].values
# Normalise to [0,1]
# b = (df['Count'] - df['Count'].min())/ np.ptp(df['Count'])
# area = 100 * b
# control the size of scatter and legend marker
levels = numbers = np.sort(df.Hits.unique())
if norm is None:
norm = Normalize()
elif isinstance(norm, tuple):
norm = Normalize(*norm)
elif not isinstance(norm, Normalize):
err = ("``size_norm`` must be None, tuple, "
"or Normalize object.")
raise ValueError(err)
min_width, max_width = np.r_[20, 100] * plt.rcParams["lines.linewidth"]
norm.clip = True
if not norm.scaled():
norm(np.asarray(numbers))
size_limits = norm.vmin, norm.vmax
scl = norm(numbers)
widths = np.asarray(min_width + scl * (max_width - min_width))
if scl.mask.any():
widths[scl.mask] = 0
sizes = dict(zip(levels, widths))
df['sizes'] = df.Hits.map(sizes)
area = df['sizes'].values
# creat scatter plot
if hasattr(sys, 'ps1') and (ofname is None):
# working inside python console, show figure
fig, ax = plt.subplots(figsize=figsize)
else:
# If working on commandline, don't show figure
fig = Figure(figsize=figsize)
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
vmin = np.percentile(combined_score.min(), 2)
vmax = np.percentile(combined_score.max(), 98)
sc = ax.scatter(x=x, y=y, s=area, edgecolors='face', c=combined_score,
cmap=cmap, vmin=vmin, vmax=vmax)
if column in ['Adjusted P-value', 'P-value']:
xlabel = "-log$_{10}$(%s)"%column
else:
xlabel = column
ax.set_xlabel(xlabel, fontsize=14, fontweight='bold')
ax.yaxis.set_major_locator(plt.FixedLocator(y))
ax.yaxis.set_major_formatter(plt.FixedFormatter(ylabels))
ax.set_yticklabels(ylabels, fontsize=16)
# ax.set_ylim([-1, len(df)])
ax.grid()
# colorbar
cax=fig.add_axes([0.95,0.20,0.03,0.22])
cbar = fig.colorbar(sc, cax=cax,)
cbar.ax.tick_params(right=True)
cbar.ax.set_title('Combined\nScore',loc='left', fontsize=12)
# for terms less than 3
if len(df) >= 3:
# find the index of the closest value to the median
idx = [area.argmax(), np.abs(area - area.mean()).argmin(), area.argmin()]
idx = unique(idx)
else:
idx = df.index.values
label = df.iloc[idx, df.columns.get_loc('Hits')]
if legend:
handles, _ = ax.get_legend_handles_labels()
legend_markers = []
for ix in idx:
legend_markers.append(ax.scatter([],[], s=area[ix], c='b'))
# artist = ax.scatter([], [], s=size_levels,)
ax.legend(legend_markers, label, title='Hits')
ax.set_title(title, fontsize=20, fontweight='bold')
if ofname is not None:
# canvas.print_figure(ofname, bbox_inches='tight', dpi=300)
fig.savefig(ofname, bbox_inches='tight', dpi=300)
return
return ax
def barplot(df, column='Adjusted P-value', title="", cutoff=0.05, top_term=10,
figsize=(6.5,6), color='salmon', ofname=None, **kwargs):
"""Visualize enrichr results.
:param df: GSEApy DataFrame results.
:param column: which column of DataFrame to show. Default: Adjusted P-value
:param title: figure title.
:param cutoff: cut-off of the cloumn you've chosen.
:param top_term: number of top enriched terms to show.
:param figsize: tuple, matplotlib figsize.
:param color: color for bars.
:param ofname: output file name. If None, don't save figure
"""
colname = column
if colname in ['Adjusted P-value', 'P-value']:
df = df[df[colname] <= cutoff]
if len(df) < 1:
msg = "Warning: No enrich terms using library %s when cutoff = %s"%(title, cutoff)
return msg
df = df.assign(logAP = lambda x: - x[colname].apply(np.log10))
colname = 'logAP'
dd = df.sort_values(by=colname).iloc[-top_term:,:]
# dd = d.head(top_term).sort_values('logAP')
# create bar plot
if hasattr(sys, 'ps1') and (ofname is None):
# working inside python console, show (True) figure
fig = plt.figure(figsize=figsize)
else:
# If working on commandline, don't show figure
fig = Figure(figsize=figsize)
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
bar = dd.plot.barh(x='Term', y=colname, color=color,
alpha=0.75, fontsize=16, ax=ax)
if column in ['Adjusted P-value', 'P-value']:
xlabel = "-log$_{10}$(%s)"%column
else:
xlabel = column
bar.set_xlabel(xlabel, fontsize=16, fontweight='bold')
bar.set_ylabel("")
bar.set_title(title, fontsize=24, fontweight='bold')
bar.xaxis.set_major_locator(MaxNLocator(integer=True))
bar.legend_.remove()
adjust_spines(ax, spines=['left','bottom'])
if ofname is not None:
# canvas.print_figure(ofname, bbox_inches='tight', dpi=300)
fig.savefig(ofname, bbox_inches='tight', dpi=300)
return
return ax
def adjust_spines(ax, spines):
"""function for removing spines and ticks.
:param ax: axes object
:param spines: a list of spines names to keep. e.g [left, right, top, bottom]
if spines = []. remove all spines and ticks.
"""
for loc, spine in ax.spines.items():
if loc in spines:
# spine.set_position(('outward', 10)) # outward by 10 points
# spine.set_smart_bounds(True)
continue
else:
spine.set_color('none') # don't draw spine
# turn off ticks where there is no spine
if 'left' in spines:
ax.yaxis.set_ticks_position('left')
else:
# no yaxis ticks
ax.yaxis.set_ticks([])
if 'bottom' in spines:
ax.xaxis.set_ticks_position('bottom')
else:
# no xaxis ticks
ax.xaxis.set_ticks([])
|
[
"numpy.abs",
"numpy.sum",
"matplotlib.pyplot.FixedFormatter",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.tile",
"numpy.interp",
"matplotlib.colors.Normalize",
"matplotlib.backends.backend_agg.FigureCanvasAgg",
"matplotlib.ticker.MaxNLocator",
"matplotlib.figure.Figure",
"matplotlib.pyplot.rcParams.update",
"matplotlib.transforms.blended_transform_factory",
"operator.xor",
"matplotlib.pyplot.subplots",
"gseapy.parser.unique",
"numpy.asarray",
"mpl_toolkits.axes_grid1.make_axes_locatable",
"matplotlib.colors.Normalize.__init__",
"numpy.log",
"matplotlib.pyplot.GridSpec",
"matplotlib.pyplot.FixedLocator"
] |
[((2042, 2065), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (2061, 2065), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((5790, 5815), 'numpy.tile', 'np.tile', (['rankings', '(2, 1)'], {}), '(rankings, (2, 1))\n', (5797, 5815), True, 'import numpy as np\n'), ((5842, 5902), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'pdf.fonttype': 42, 'ps.fonttype': 42}"], {}), "({'pdf.fonttype': 42, 'ps.fonttype': 42})\n", (5861, 5902), True, 'import matplotlib.pyplot as plt\n'), ((6056, 6075), 'matplotlib.pyplot.GridSpec', 'plt.GridSpec', (['(16)', '(1)'], {}), '(16, 1)\n', (6068, 6075), True, 'import matplotlib.pyplot as plt\n'), ((7290, 7356), 'matplotlib.transforms.blended_transform_factory', 'transforms.blended_transform_factory', (['ax1.transData', 'ax1.transAxes'], {}), '(ax1.transData, ax1.transAxes)\n', (7326, 7356), True, 'import matplotlib.transforms as transforms\n'), ((8310, 8376), 'matplotlib.transforms.blended_transform_factory', 'transforms.blended_transform_factory', (['ax2.transData', 'ax2.transAxes'], {}), '(ax2.transData, ax2.transAxes)\n', (8346, 8376), True, 'import matplotlib.transforms as transforms\n'), ((9386, 9452), 'matplotlib.transforms.blended_transform_factory', 'transforms.blended_transform_factory', (['ax4.transAxes', 'ax4.transData'], {}), '(ax4.transAxes, ax4.transData)\n', (9422, 9452), True, 'import matplotlib.transforms as transforms\n'), ((13172, 13225), 'numpy.asarray', 'np.asarray', (['(min_width + scl * (max_width - min_width))'], {}), '(min_width + scl * (max_width - min_width))\n', (13182, 13225), True, 'import numpy as np\n'), ((587, 629), 'matplotlib.colors.Normalize.__init__', 'Normalize.__init__', (['self', 'vmin', 'vmax', 'clip'], {}), '(self, vmin, vmax, clip)\n', (605, 629), False, 'from matplotlib.colors import Normalize\n'), ((2834, 2853), 'numpy.arange', 'np.arange', (['(0)', 'nx', '(1)'], {}), '(0, nx, 1)\n', (2843, 2853), True, 'import numpy as np\n'), ((2872, 2891), 'numpy.arange', 'np.arange', (['(0)', 'ny', '(1)'], {}), '(0, ny, 1)\n', (2881, 2891), True, 'import numpy as np\n'), ((3013, 3040), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (3023, 3040), True, 'import matplotlib.pyplot as plt\n'), ((3065, 3088), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (3071, 3088), False, 'from matplotlib.figure import Figure\n'), ((3106, 3123), 'matplotlib.backends.backend_agg.FigureCanvasAgg', 'FigureCanvas', (['fig'], {}), '(fig)\n', (3118, 3123), True, 'from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n'), ((6191, 6218), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (6201, 6218), True, 'import matplotlib.pyplot as plt\n'), ((6298, 6321), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (6304, 6321), False, 'from matplotlib.figure import Figure\n'), ((6339, 6356), 'matplotlib.backends.backend_agg.FigureCanvasAgg', 'FigureCanvas', (['fig'], {}), '(fig)\n', (6351, 6356), True, 'from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n'), ((12696, 12707), 'matplotlib.colors.Normalize', 'Normalize', ([], {}), '()\n', (12705, 12707), False, 'from matplotlib.colors import Normalize\n'), ((13529, 13558), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (13541, 13558), True, 'import matplotlib.pyplot as plt\n'), ((13638, 13661), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (13644, 13661), False, 'from matplotlib.figure import Figure\n'), ((13679, 13696), 'matplotlib.backends.backend_agg.FigureCanvasAgg', 'FigureCanvas', (['fig'], {}), '(fig)\n', (13691, 13696), True, 'from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n'), ((14178, 14197), 'matplotlib.pyplot.FixedLocator', 'plt.FixedLocator', (['y'], {}), '(y)\n', (14194, 14197), True, 'import matplotlib.pyplot as plt\n'), ((14232, 14259), 'matplotlib.pyplot.FixedFormatter', 'plt.FixedFormatter', (['ylabels'], {}), '(ylabels)\n', (14250, 14259), True, 'import matplotlib.pyplot as plt\n'), ((14762, 14773), 'gseapy.parser.unique', 'unique', (['idx'], {}), '(idx)\n', (14768, 14773), False, 'from gseapy.parser import unique\n'), ((16637, 16664), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (16647, 16664), True, 'import matplotlib.pyplot as plt\n'), ((16744, 16767), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (16750, 16767), False, 'from matplotlib.figure import Figure\n'), ((16785, 16802), 'matplotlib.backends.backend_agg.FigureCanvasAgg', 'FigureCanvas', (['fig'], {}), '(fig)\n', (16797, 16802), True, 'from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n'), ((17249, 17274), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'integer': '(True)'}), '(integer=True)\n', (17260, 17274), False, 'from matplotlib.ticker import MaxNLocator\n'), ((876, 898), 'numpy.interp', 'np.interp', (['value', 'x', 'y'], {}), '(value, x, y)\n', (885, 898), True, 'import numpy as np\n'), ((1917, 1938), 'operator.xor', 'operator.xor', (['(1)', 'axis'], {}), '(1, axis)\n', (1929, 1938), False, 'import logging, sys, operator\n'), ((5527, 5543), 'numpy.abs', 'np.abs', (['rankings'], {}), '(rankings)\n', (5533, 5543), True, 'import numpy as np\n'), ((11530, 11553), 'numpy.sum', 'np.sum', (['(~can_be_coerced)'], {}), '(~can_be_coerced)\n', (11536, 11553), True, 'import numpy as np\n'), ((12757, 12773), 'matplotlib.colors.Normalize', 'Normalize', (['*norm'], {}), '(*norm)\n', (12766, 12773), False, 'from matplotlib.colors import Normalize\n'), ((13075, 13094), 'numpy.asarray', 'np.asarray', (['numbers'], {}), '(numbers)\n', (13085, 13094), True, 'import numpy as np\n'), ((6658, 6674), 'numpy.log', 'np.log', (['rankings'], {}), '(rankings)\n', (6664, 6674), True, 'import numpy as np\n')]
|
#This is a direct port of x_keckhelio.pro from XIDL
from __future__ import division, print_function
from math import pi
from numpy import cos, sin
import numpy as np
def x_keckhelio(ra, dec, epoch=2000.0, jd=None, tai=None,
longitude=None, latitude=None, altitude=None, obs='keck'):
"""
`ra` and `dec` in degrees
Returns `vcorr`: "Velocity correction term, in km/s, to add to measured
radial velocity to convert it to the heliocentric frame."
but the sign seems to be backwards of what that says:
helio_shift = -1. * x_keckhelio(RA, DEC, 2000.0)
uses barvel and ct2lst functions from idlastro, also ported below
#NOTE: this seems to have some jitter about the IDL version at the .1 km/s level
"""
if longitude is not None and latitude is not None and altitude is not None:
print('using long/lat/alt instead of named observatory')
elif obs == 'keck':
longitude = 360. - 155.47220
latitude = 19.82656886
altitude = 4000. #meters
else:
print('Using observatory', obs)
if obs == 'vlt':
longitude = 360. - 70.40322
latitude = -24.6258
altitude = 2635. #meters
elif obs == 'mmt':
longitude = 360. - 110.88456
latitude = 31.688778
altitude = 2600. #meters
elif obs == 'lick':
longitude = 360. - 121.637222
latitude = 37.343056
altitude = 1283. #meters
else:
raise ValueError('unrecognized observatory' + obs)
if jd is None and tai is not None:
jd = 2400000.5 + tai / (24. * 3600.)
elif tai is None and jd is not None:
pass
else:
raise ValueError('Must specify either JD or TAI')
DRADEG = 180.0 / pi
# ----------
# Compute baryocentric velocity (Accurate only to 1m/s)
dvelh, dvelb = baryvel(jd, epoch)
#Project velocity toward star
vbarycen = dvelb[0]*cos(dec/DRADEG)*cos(ra/DRADEG) + \
dvelb[1]*cos(dec/DRADEG)*sin(ra/DRADEG) + dvelb[2]*sin(dec/DRADEG)
#----------
#Compute rotational velocity of observer on the Earth
#LAT is the latitude in radians.
latrad = latitude / DRADEG
#Reduction of geodetic latitude to geocentric latitude (radians).
#DLAT is in arcseconds.
dlat = -(11. * 60. + 32.743000) * sin(2. * latrad) + \
1.163300 * sin(4. * latrad) -0.002600 * sin(6. * latrad)
latrad = latrad + (dlat / 3600.) / DRADEG
#R is the radius vector from the Earth's center to the observer (meters).
#VC is the corresponding circular velocity
#(meters/sidereal day converted to km / sec).
#(sidereal day = 23.934469591229 hours (1986))
r = 6378160.0 * (0.998327073 + 0.00167643800 * cos(2. * latrad) - \
0.00000351 * cos(4. * latrad) + 0.000000008 * cos(6. * latrad)) \
+ altitude
vc = 2. * pi * (r / 1000.) / (23.934469591229 * 3600.)
#Compute the hour angle, HA, in degrees
LST = 15. * ct2lst(longitude, 'junk', jd) # convert from hours to degrees
HA = LST - ra
#Project the velocity onto the line of sight to the star.
vrotate = vc * cos(latrad) * cos(dec/DRADEG) * sin(HA/DRADEG)
return (-vbarycen + vrotate)
def ct2lst(lng, tz, jd, day=None, mon=None, year=None):
"""
# NAME:
# CT2LST
# PURPOSE:
# To convert from Local Civil Time to Local Mean Sidereal Time.
#
# CALLING SEQUENCE:
# CT2LST, Lst, Lng, Tz, Time, [Day, Mon, Year] #NOT SUPPORTED IN PYTHON PORT!
# or
# CT2LST, Lst, Lng, dummy, JD
#
# INPUTS:
# Lng - The longitude in degrees (east of Greenwich) of the place for
# which the local sidereal time is desired, scalar. The Greenwich
# mean sidereal time (GMST) can be found by setting Lng = 0.
# Tz - The time zone of the site in hours, positive East of the Greenwich
# meridian (ahead of GMT). Use this parameter to easily account
# for Daylight Savings time (e.g. -4=EDT, -5 = EST/CDT), scalar
# This parameter is not needed (and ignored) if Julian date is
# supplied. ***Note that the sign of TZ was changed in July 2008
# to match the standard definition.***
# Time or JD - If more than four parameters are specified, then this is
# the time of day of the specified date in decimal hours. If
# exactly four parameters are specified, then this is the
# Julian date of time in question, scalar or vector
#
# OPTIONAL INPUTS:
# Day - The day of the month (1-31),integer scalar or vector
# Mon - The month, in numerical format (1-12), integer scalar or vector
# Year - The 4 digit year (e.g. 2008), integer scalar or vector
#
# OUTPUTS:
# Lst The Local Sidereal Time for the date/time specified in hours.
#
# RESTRICTIONS:
# If specified, the date should be in numerical form. The year should
# appear as yyyy.
#
# PROCEDURE:
# The Julian date of the day and time is question is used to determine
# the number of days to have passed since 0 Jan 2000. This is used
# in conjunction with the GST of that date to extrapolate to the current
# GST# this is then used to get the LST. See Astronomical Algorithms
# by <NAME>, p. 84 (Eq. 11-4) for the constants used.
#
# EXAMPLE:
# Find the Greenwich mean sidereal time (GMST) on 2008 Jul 30 at 15:53 pm
# in Baltimore, Maryland (longitude=-76.72 degrees). The timezone is
# EDT or tz=-4
#
# IDL> CT2LST, lst, -76.72, -4,ten(15,53), 30, 07, 2008
#
# ==> lst = 11.356505 hours (= 11h 21m 23.418s)
#
# The Web site http://tycho.usno.navy.mil/sidereal.html contains more
# info on sidereal time, as well as an interactive calculator.
# PROCEDURES USED:
# jdcnv - Convert from year, month, day, hour to julian date
#
# MODIFICATION HISTORY:
# Adapted from the FORTRAN program GETSD by <NAME>, STX,
# 27 October 1988.
# Use IAU 1984 constants <NAME>, HSTX, April 1995, results
# differ by about 0.1 seconds
# Longitudes measured *east* of Greenwich <NAME> December 1998
# Time zone now measure positive East of Greenwich <NAME> July 2008
# Remove debugging print statement <NAME> April 2009
"""
# IF N_params() gt 4 THEN BEGIN
# time = tme - tz
# jdcnv, year, mon, day, time, jd
# ENDIF ELSE jd = double(tme)
#
# Useful constants, see Meeus, p.84
#
c = [280.46061837, 360.98564736629, 0.000387933, 38710000.0]
jd2000 = 2451545.0
t0 = jd - jd2000
t = t0 / 36525
#
# Compute GST in seconds.
#
theta = c[0] + (c[1] * t0) + t ** 2 * (c[2] - t / c[3])
#
# Compute LST in hours.
#
lst = np.array((theta + lng) / 15.0)
neg = lst < 0
if np.sum(neg) > 0:
if neg.shape == tuple():
lst = 24. + idl_like_mod(lst, 24.)
else:
lst[neg] = 24. + idl_like_mod(lst[neg], 24.)
return idl_like_mod(lst, 24.)
def baryvel(dje, deq):
#+
# NAME:
# BARYVEL
# PURPOSE:
# Calculates heliocentric and barycentric velocity components of Earth.
#
# EXPLANATION:
# BARYVEL takes into account the Earth-Moon motion, and is useful for
# radial velocity work to an accuracy of ~1 m/s.
#
# CALLING SEQUENCE:
# BARYVEL, dje, deq, dvelh, dvelb, [ JPL = ]
#
# INPUTS:
# DJE - (scalar) Julian ephemeris date.
# DEQ - (scalar) epoch of mean equinox of dvelh and dvelb. If deq=0
# then deq is assumed to be equal to dje.
# OUTPUTS:
# DVELH: (vector(3)) heliocentric velocity component. in km/s
# DVELB: (vector(3)) barycentric velocity component. in km/s
#
# The 3-vectors DVELH and DVELB are given in a right-handed coordinate
# system with the +X axis toward the Vernal Equinox, and +Z axis
# toward the celestial pole.
#
# OPTIONAL KEYWORD SET:
# JPL - if /JPL set, then BARYVEL will call the procedure JPLEPHINTERP
# to compute the Earth velocity using the full JPL ephemeris.
# The JPL ephemeris FITS file JPLEPH.405 must exist in either the
# current directory, or in the directory specified by the
# environment variable ASTRO_DATA. Alternatively, the JPL keyword
# can be set to the full path and name of the ephemeris file.
# A copy of the JPL ephemeris FITS file is available in
# http://idlastro.gsfc.nasa.gov/ftp/data/
# PROCEDURES CALLED:
# Function PREMAT() -- computes precession matrix
# JPLEPHREAD, JPLEPHINTERP, TDB2TDT - if /JPL keyword is set
# NOTES:
# Algorithm taken from FORTRAN program of Stumpff (1980, A&A Suppl, 41,1)
# Stumpf claimed an accuracy of 42 cm/s for the velocity. A
# comparison with the JPL FORTRAN planetary ephemeris program PLEPH
# found agreement to within about 65 cm/s between 1986 and 1994
#
# If /JPL is set (using JPLEPH.405 ephemeris file) then velocities are
# given in the ICRS system# otherwise in the FK4 system.
# EXAMPLE:
# Compute the radial velocity of the Earth toward Altair on 15-Feb-1994
# using both the original Stumpf algorithm and the JPL ephemeris
#
# IDL> jdcnv, 1994, 2, 15, 0, jd #==> JD = 2449398.5
# IDL> baryvel, jd, 2000, vh, vb #Original algorithm
# ==> vh = [-17.07243, -22.81121, -9.889315] #Heliocentric km/s
# ==> vb = [-17.08083, -22.80471, -9.886582] #Barycentric km/s
# IDL> baryvel, jd, 2000, vh, vb, /jpl #JPL ephemeris
# ==> vh = [-17.07236, -22.81126, -9.889419] #Heliocentric km/s
# ==> vb = [-17.08083, -22.80484, -9.886409] #Barycentric km/s
#
# IDL> ra = ten(19,50,46.77)*15/!RADEG #RA in radians
# IDL> dec = ten(08,52,3.5)/!RADEG #Dec in radians
# IDL> v = vb[0]*cos(dec)*cos(ra) + $ #Project velocity toward star
# vb[1]*cos(dec)*sin(ra) + vb[2]*sin(dec)
#
# REVISION HISTORY:
# <NAME>, U.C. Berkeley Translated BARVEL.FOR to IDL.
# <NAME>, Cleaned up program sent by <NAME> (SfSU) June 1994
# Converted to IDL V5.0 <NAME> September 1997
# Added /JPL keyword <NAME> July 2001
# Documentation update W. Landsman Dec 2005
#-
#Define constants
dc2pi = 2* pi
cc2pi = dc2pi
dc1 = 1.0
dcto = 2415020.0
dcjul = 36525.0 #days in Julian year
dcbes = 0.313
dctrop = 365.24219572 #days in tropical year (...572 insig)
dc1900 = 1900.0
AU = 1.4959787e8
#Constants dcfel(i,k) of fast changing elements.
dcfel = [1.7400353e00, 6.2833195099091e02, 5.2796e-6 \
,6.2565836e00, 6.2830194572674e02, -2.6180e-6 \
,4.7199666e00, 8.3997091449254e03, -1.9780e-5 \
,1.9636505e-1, 8.4334662911720e03, -5.6044e-5 \
,4.1547339e00, 5.2993466764997e01, 5.8845e-6 \
,4.6524223e00, 2.1354275911213e01, 5.6797e-6 \
,4.2620486e00, 7.5025342197656e00, 5.5317e-6 \
,1.4740694e00, 3.8377331909193e00, 5.6093e-6 ]
dcfel = np.array(dcfel).reshape(8,3)
#constants dceps and ccsel(i,k) of slowly changing elements.
dceps = [4.093198e-1, -2.271110e-4, -2.860401e-8 ]
ccsel = [1.675104E-2, -4.179579E-5, -1.260516E-7 \
,2.220221E-1, 2.809917E-2, 1.852532E-5 \
,1.589963E00, 3.418075E-2, 1.430200E-5 \
,2.994089E00, 2.590824E-2, 4.155840E-6 \
,8.155457E-1, 2.486352E-2, 6.836840E-6 \
,1.735614E00, 1.763719E-2, 6.370440E-6 \
,1.968564E00, 1.524020E-2, -2.517152E-6 \
,1.282417E00, 8.703393E-3, 2.289292E-5 \
,2.280820E00, 1.918010E-2, 4.484520E-6 \
,4.833473E-2, 1.641773E-4, -4.654200E-7 \
,5.589232E-2, -3.455092E-4, -7.388560E-7 \
,4.634443E-2, -2.658234E-5, 7.757000E-8 \
,8.997041E-3, 6.329728E-6, -1.939256E-9 \
,2.284178E-2, -9.941590E-5, 6.787400E-8 \
,4.350267E-2, -6.839749E-5, -2.714956E-7 \
,1.348204E-2, 1.091504E-5, 6.903760E-7 \
,3.106570E-2, -1.665665E-4, -1.590188E-7 ]
ccsel = np.array(ccsel).reshape(17,3)
#Constants of the arguments of the short-period perturbations.
dcargs = [5.0974222, -7.8604195454652e2 \
,3.9584962, -5.7533848094674e2 \
,1.6338070, -1.1506769618935e3 \
,2.5487111, -3.9302097727326e2 \
,4.9255514, -5.8849265665348e2 \
,1.3363463, -5.5076098609303e2 \
,1.6072053, -5.2237501616674e2 \
,1.3629480, -1.1790629318198e3 \
,5.5657014, -1.0977134971135e3 \
,5.0708205, -1.5774000881978e2 \
,3.9318944, 5.2963464780000e1 \
,4.8989497, 3.9809289073258e1 \
,1.3097446, 7.7540959633708e1 \
,3.5147141, 7.9618578146517e1 \
,3.5413158, -5.4868336758022e2 ]
dcargs = np.array(dcargs).reshape(15,2)
#Amplitudes ccamps(n,k) of the short-period perturbations.
ccamps = \
[-2.279594E-5, 1.407414E-5, 8.273188E-6, 1.340565E-5, -2.490817E-7 \
,-3.494537E-5, 2.860401E-7, 1.289448E-7, 1.627237E-5, -1.823138E-7 \
, 6.593466E-7, 1.322572E-5, 9.258695E-6, -4.674248E-7, -3.646275E-7 \
, 1.140767E-5, -2.049792E-5, -4.747930E-6, -2.638763E-6, -1.245408E-7 \
, 9.516893E-6, -2.748894E-6, -1.319381E-6, -4.549908E-6, -1.864821E-7 \
, 7.310990E-6, -1.924710E-6, -8.772849E-7, -3.334143E-6, -1.745256E-7 \
,-2.603449E-6, 7.359472E-6, 3.168357E-6, 1.119056E-6, -1.655307E-7 \
,-3.228859E-6, 1.308997E-7, 1.013137E-7, 2.403899E-6, -3.736225E-7 \
, 3.442177E-7, 2.671323E-6, 1.832858E-6, -2.394688E-7, -3.478444E-7 \
, 8.702406E-6, -8.421214E-6, -1.372341E-6, -1.455234E-6, -4.998479E-8 \
,-1.488378E-6, -1.251789E-5, 5.226868E-7, -2.049301E-7, 0.E0 \
,-8.043059E-6, -2.991300E-6, 1.473654E-7, -3.154542E-7, 0.E0 \
, 3.699128E-6, -3.316126E-6, 2.901257E-7, 3.407826E-7, 0.E0 \
, 2.550120E-6, -1.241123E-6, 9.901116E-8, 2.210482E-7, 0.E0 \
,-6.351059E-7, 2.341650E-6, 1.061492E-6, 2.878231E-7, 0.E0 ]
ccamps = np.array(ccamps).reshape(15,5)
#Constants csec3 and ccsec(n,k) of the secular perturbations in longitude.
ccsec3 = -7.757020E-8
ccsec = [1.289600E-6, 5.550147E-1, 2.076942E00 \
,3.102810E-5, 4.035027E00, 3.525565E-1 \
,9.124190E-6, 9.990265E-1, 2.622706E00 \
,9.793240E-7, 5.508259E00, 1.559103E01 ]
ccsec = np.array(ccsec).reshape(4,3)
#Sidereal rates.
dcsld = 1.990987e-7 #sidereal rate in longitude
ccsgd = 1.990969E-7 #sidereal rate in mean anomaly
#Constants used in the calculation of the lunar contribution.
cckm = 3.122140E-5
ccmld = 2.661699E-6
ccfdi = 2.399485E-7
#Constants dcargm(i,k) of the arguments of the perturbations of the motion
# of the moon.
dcargm = [5.1679830, 8.3286911095275e3 \
,5.4913150, -7.2140632838100e3 \
,5.9598530, 1.5542754389685e4 ]
dcargm = np.array(dcargm).reshape(3,2)
#Amplitudes ccampm(n,k) of the perturbations of the moon.
ccampm = [ 1.097594E-1, 2.896773E-7, 5.450474E-2, 1.438491E-7 \
,-2.223581E-2, 5.083103E-8, 1.002548E-2, -2.291823E-8 \
, 1.148966E-2, 5.658888E-8, 8.249439E-3, 4.063015E-8 ]
ccampm = np.array(ccampm).reshape(3,4)
#ccpamv(k)=a*m*dl,dt (planets), dc1mme=1-mass(earth+moon)
ccpamv = [8.326827E-11, 1.843484E-11, 1.988712E-12, 1.881276E-12]
dc1mme = 0.99999696
#Time arguments.
dt = (dje - dcto) / dcjul
tvec = np.array([1., dt, dt*dt])
#Values of all elements for the instant(aneous?) dje.
temp = idl_like_mod(idl_like_pound(tvec,dcfel), dc2pi)
#PROBLEM: the mod here is where the 100 m/s error slips in
dml = temp[:,0]
forbel = temp[:,1:8]
g = forbel[:,0] #old fortran equivalence
deps = idl_like_mod(np.sum(tvec*dceps), dc2pi)
sorbel = idl_like_mod(idl_like_pound(tvec, ccsel), dc2pi)
e = sorbel[:, 0] #old fortran equivalence
#Secular perturbations in longitude.
dummy=cos(2.0)
sn = sin(idl_like_mod(idl_like_pound(tvec.ravel()[0:2] , ccsec[:, 1:3]),cc2pi))
#Periodic perturbations of the emb (earth-moon barycenter).
pertl = np.sum(ccsec[:,0] * sn) + dt*ccsec3*sn.ravel()[2]
pertld = 0.0
pertr = 0.0
pertrd = 0.0
for k in range(14):
a = idl_like_mod((dcargs[k,0]+dt*dcargs[k,1]), dc2pi)
cosa = cos(a)
sina = sin(a)
pertl = pertl + ccamps[k,0]*cosa + ccamps[k,1]*sina
pertr = pertr + ccamps[k,2]*cosa + ccamps[k,3]*sina
if k < 11:
pertld = pertld + (ccamps[k,1]*cosa-ccamps[k,0]*sina)*ccamps[k,4]
pertrd = pertrd + (ccamps[k,3]*cosa-ccamps[k,2]*sina)*ccamps[k,4]
#Elliptic part of the motion of the emb.
phi = (e*e/4)*(((8/e)-e)*sin(g) +5*sin(2*g) +(13/3)*e*sin(3*g))
f = g + phi
sinf = sin(f)
cosf = cos(f)
dpsi = (dc1 - e*e) / (dc1 + e*cosf)
phid = 2*e*ccsgd*((1 + 1.5*e*e)*cosf + e*(1.25 - 0.5*sinf*sinf))
psid = ccsgd*e*sinf * (dc1 - e*e)**-0.5
#Perturbed heliocentric motion of the emb.
d1pdro = dc1+pertr
drd = d1pdro * (psid + dpsi*pertrd)
drld = d1pdro*dpsi * (dcsld+phid+pertld)
dtl = idl_like_mod((dml + phi + pertl), dc2pi)
dsinls = sin(dtl)
dcosls = cos(dtl)
dxhd = drd*dcosls - drld*dsinls
dyhd = drd*dsinls + drld*dcosls
#Influence of eccentricity, evection and variation on the geocentric
# motion of the moon.
pertl = 0.0
pertld = 0.0
pertp = 0.0
pertpd = 0.0
for k in range(2):
a = idl_like_mod((dcargm[k,0] + dt*dcargm[k,1]), dc2pi)
sina = sin(a)
cosa = cos(a)
pertl = pertl + ccampm[k,0]*sina
pertld = pertld + ccampm[k,1]*cosa
pertp = pertp + ccampm[k,2]*cosa
pertpd = pertpd - ccampm[k,3]*sina
#Heliocentric motion of the earth.
tl = forbel.ravel()[1] + pertl
sinlm = sin(tl)
coslm = cos(tl)
sigma = cckm / (1.0 + pertp)
a = sigma*(ccmld + pertld)
b = sigma*pertpd
dxhd = dxhd + a*sinlm + b*coslm
dyhd = dyhd - a*coslm + b*sinlm
dzhd= -sigma*ccfdi*cos(forbel.ravel()[2])
#Barycentric motion of the earth.
dxbd = dxhd*dc1mme
dybd = dyhd*dc1mme
dzbd = dzhd*dc1mme
for k in range(3):
plon = forbel.ravel()[k+3]
pomg = sorbel.ravel()[k+1]
pecc = sorbel.ravel()[k+9]
tl = idl_like_mod((plon + 2.0*pecc*sin(plon-pomg)), cc2pi)
dxbd = dxbd + ccpamv[k]*(sin(tl) + pecc*sin(pomg))
dybd = dybd - ccpamv[k]*(cos(tl) + pecc*cos(pomg))
dzbd = dzbd - ccpamv[k]*sorbel.ravel()[k+13]*cos(plon - sorbel.ravel()[k+5])
#Transition to mean equator of date.
dcosep = cos(deps)
dsinep = sin(deps)
dyahd = dcosep*dyhd - dsinep*dzhd
dzahd = dsinep*dyhd + dcosep*dzhd
dyabd = dcosep*dybd - dsinep*dzbd
dzabd = dsinep*dybd + dcosep*dzbd
#Epoch of mean equinox (deq) of zero implies that we should use
# Julian ephemeris date (dje) as epoch of mean equinox.
if deq == 0:
dvelh = AU * ([dxhd, dyahd, dzahd])
dvelb = AU * ([dxbd, dyabd, dzabd])
return dvelh, dvelb
#General precession from epoch dje to deq.
deqdat = (dje-dcto-dcbes) / dctrop + dc1900
prema = premat(deqdat,deq,FK4=True)
dvelh = AU * idl_like_pound( prema, [dxhd, dyahd, dzahd] )
dvelb = AU * idl_like_pound( prema, [dxbd, dyabd, dzabd] )
return dvelh, dvelb
def premat(equinox1, equinox2, FK4=False):
"""
#+
# NAME:
# PREMAT
# PURPOSE:
# Return the precession matrix needed to go from EQUINOX1 to EQUINOX2.
# EXPLANTION:
# This matrix is used by the procedures PRECESS and BARYVEL to precess
# astronomical coordinates
#
# CALLING SEQUENCE:
# matrix = PREMAT( equinox1, equinox2, [ /FK4 ] )
#
# INPUTS:
# EQUINOX1 - Original equinox of coordinates, numeric scalar.
# EQUINOX2 - Equinox of precessed coordinates.
#
# OUTPUT:
# matrix - double precision 3 x 3 precession matrix, used to precess
# equatorial rectangular coordinates
#
# OPTIONAL INPUT KEYWORDS:
# /FK4 - If this keyword is set, the FK4 (B1950.0) system precession
# angles are used to compute the precession matrix. The
# default is to use FK5 (J2000.0) precession angles
#
# EXAMPLES:
# Return the precession matrix from 1950.0 to 1975.0 in the FK4 system
#
# IDL> matrix = PREMAT( 1950.0, 1975.0, /FK4)
#
# PROCEDURE:
# FK4 constants from "Computational Spherical Astronomy" by Taff (1983),
# p. 24. (FK4). FK5 constants from "Astronomical Almanac Explanatory
# Supplement 1992, page 104 Table 3.211.1.
#
# REVISION HISTORY
# Written, <NAME>, HSTX Corporation, June 1994
# Converted to IDL V5.0 <NAME> September 1997
#-
"""
deg_to_rad = pi/180.0
sec_to_rad = deg_to_rad/3600.
T = 0.001 * ( equinox2 - equinox1)
if not FK4: # FK5
ST = 0.001*( equinox1 - 2000.)
# Compute 3 rotation angles
A = sec_to_rad * T * (23062.181 + ST*(139.656 +0.0139*ST) \
+ T*(30.188 - 0.344*ST+17.998*T))
B = sec_to_rad * T * T * (79.280 + 0.410*ST + 0.205*T) + A
C = sec_to_rad * T * (20043.109 - ST*(85.33 + 0.217*ST) \
+ T*(-42.665 - 0.217*ST -41.833*T))
else:
ST = 0.001*( equinox1 - 1900.)
# Compute 3 rotation angles
A = sec_to_rad * T * (23042.53 + ST*(139.75 +0.06*ST) \
+ T*(30.23 - 0.27*ST+18.0*T))
B = sec_to_rad * T * T * (79.27 + 0.66*ST + 0.32*T) + A
C = sec_to_rad * T * (20046.85 - ST*(85.33 + 0.37*ST) \
+ T*(-42.67 - 0.37*ST -41.8*T))
sina = sin(A)
sinb = sin(B)
sinc = sin(C)
cosa = cos(A)
cosb = cos(B)
cosc = cos(C)
r = np.empty([3, 3])
r[:,0] = [ cosa*cosb*cosc-sina*sinb, sina*cosb+cosa*sinb*cosc, cosa*sinc]
r[:,1] = [-cosa*sinb-sina*cosb*cosc, cosa*cosb-sina*sinb*cosc, -sina*sinc]
r[:,2] = [-cosb*sinc, -sinb*sinc, cosc]
return r
def idl_like_pound(a, b):
a = np.array(a, copy=False)
b = np.array(b, copy=False)
if len(a.shape) == 2 and len(b.shape) == 1:
return np.dot(a.T, b)
if len(a.shape) == 1 and len(b.shape) == 2:
res = np.dot(a, b.T)
return res.reshape(1, res.size)
else:
return np.dot(a, b)
def idl_like_mod(a, b):
a = np.array(a, copy=False)
b = np.array(b, copy=False)
res = np.abs(a) % b
if a.shape == tuple():
if a<0:
return -res
else:
return res
else:
res[a<0] *= -1
return res
|
[
"numpy.sum",
"numpy.abs",
"numpy.empty",
"numpy.sin",
"numpy.array",
"numpy.cos",
"numpy.dot"
] |
[((7216, 7246), 'numpy.array', 'np.array', (['((theta + lng) / 15.0)'], {}), '((theta + lng) / 15.0)\n', (7224, 7246), True, 'import numpy as np\n'), ((16178, 16206), 'numpy.array', 'np.array', (['[1.0, dt, dt * dt]'], {}), '([1.0, dt, dt * dt])\n', (16186, 16206), True, 'import numpy as np\n'), ((16735, 16743), 'numpy.cos', 'cos', (['(2.0)'], {}), '(2.0)\n', (16738, 16743), False, 'from numpy import cos, sin\n'), ((17572, 17578), 'numpy.sin', 'sin', (['f'], {}), '(f)\n', (17575, 17578), False, 'from numpy import cos, sin\n'), ((17590, 17596), 'numpy.cos', 'cos', (['f'], {}), '(f)\n', (17593, 17596), False, 'from numpy import cos, sin\n'), ((17970, 17978), 'numpy.sin', 'sin', (['dtl'], {}), '(dtl)\n', (17973, 17978), False, 'from numpy import cos, sin\n'), ((17992, 18000), 'numpy.cos', 'cos', (['dtl'], {}), '(dtl)\n', (17995, 18000), False, 'from numpy import cos, sin\n'), ((18625, 18632), 'numpy.sin', 'sin', (['tl'], {}), '(tl)\n', (18628, 18632), False, 'from numpy import cos, sin\n'), ((18645, 18652), 'numpy.cos', 'cos', (['tl'], {}), '(tl)\n', (18648, 18652), False, 'from numpy import cos, sin\n'), ((19417, 19426), 'numpy.cos', 'cos', (['deps'], {}), '(deps)\n', (19420, 19426), False, 'from numpy import cos, sin\n'), ((19440, 19449), 'numpy.sin', 'sin', (['deps'], {}), '(deps)\n', (19443, 19449), False, 'from numpy import cos, sin\n'), ((22571, 22577), 'numpy.sin', 'sin', (['A'], {}), '(A)\n', (22574, 22577), False, 'from numpy import cos, sin\n'), ((22589, 22595), 'numpy.sin', 'sin', (['B'], {}), '(B)\n', (22592, 22595), False, 'from numpy import cos, sin\n'), ((22607, 22613), 'numpy.sin', 'sin', (['C'], {}), '(C)\n', (22610, 22613), False, 'from numpy import cos, sin\n'), ((22625, 22631), 'numpy.cos', 'cos', (['A'], {}), '(A)\n', (22628, 22631), False, 'from numpy import cos, sin\n'), ((22643, 22649), 'numpy.cos', 'cos', (['B'], {}), '(B)\n', (22646, 22649), False, 'from numpy import cos, sin\n'), ((22661, 22667), 'numpy.cos', 'cos', (['C'], {}), '(C)\n', (22664, 22667), False, 'from numpy import cos, sin\n'), ((22677, 22693), 'numpy.empty', 'np.empty', (['[3, 3]'], {}), '([3, 3])\n', (22685, 22693), True, 'import numpy as np\n'), ((22945, 22968), 'numpy.array', 'np.array', (['a'], {'copy': '(False)'}), '(a, copy=False)\n', (22953, 22968), True, 'import numpy as np\n'), ((22977, 23000), 'numpy.array', 'np.array', (['b'], {'copy': '(False)'}), '(b, copy=False)\n', (22985, 23000), True, 'import numpy as np\n'), ((23268, 23291), 'numpy.array', 'np.array', (['a'], {'copy': '(False)'}), '(a, copy=False)\n', (23276, 23291), True, 'import numpy as np\n'), ((23300, 23323), 'numpy.array', 'np.array', (['b'], {'copy': '(False)'}), '(b, copy=False)\n', (23308, 23323), True, 'import numpy as np\n'), ((3247, 3263), 'numpy.sin', 'sin', (['(HA / DRADEG)'], {}), '(HA / DRADEG)\n', (3250, 3263), False, 'from numpy import cos, sin\n'), ((7272, 7283), 'numpy.sum', 'np.sum', (['neg'], {}), '(neg)\n', (7278, 7283), True, 'import numpy as np\n'), ((16524, 16544), 'numpy.sum', 'np.sum', (['(tvec * dceps)'], {}), '(tvec * dceps)\n', (16530, 16544), True, 'import numpy as np\n'), ((16905, 16929), 'numpy.sum', 'np.sum', (['(ccsec[:, 0] * sn)'], {}), '(ccsec[:, 0] * sn)\n', (16911, 16929), True, 'import numpy as np\n'), ((17107, 17113), 'numpy.cos', 'cos', (['a'], {}), '(a)\n', (17110, 17113), False, 'from numpy import cos, sin\n'), ((17129, 17135), 'numpy.sin', 'sin', (['a'], {}), '(a)\n', (17132, 17135), False, 'from numpy import cos, sin\n'), ((18341, 18347), 'numpy.sin', 'sin', (['a'], {}), '(a)\n', (18344, 18347), False, 'from numpy import cos, sin\n'), ((18363, 18369), 'numpy.cos', 'cos', (['a'], {}), '(a)\n', (18366, 18369), False, 'from numpy import cos, sin\n'), ((23065, 23079), 'numpy.dot', 'np.dot', (['a.T', 'b'], {}), '(a.T, b)\n', (23071, 23079), True, 'import numpy as np\n'), ((23142, 23156), 'numpy.dot', 'np.dot', (['a', 'b.T'], {}), '(a, b.T)\n', (23148, 23156), True, 'import numpy as np\n'), ((23222, 23234), 'numpy.dot', 'np.dot', (['a', 'b'], {}), '(a, b)\n', (23228, 23234), True, 'import numpy as np\n'), ((23334, 23343), 'numpy.abs', 'np.abs', (['a'], {}), '(a)\n', (23340, 23343), True, 'import numpy as np\n'), ((2105, 2122), 'numpy.sin', 'sin', (['(dec / DRADEG)'], {}), '(dec / DRADEG)\n', (2108, 2122), False, 'from numpy import cos, sin\n'), ((2476, 2493), 'numpy.sin', 'sin', (['(6.0 * latrad)'], {}), '(6.0 * latrad)\n', (2479, 2493), False, 'from numpy import cos, sin\n'), ((3229, 3246), 'numpy.cos', 'cos', (['(dec / DRADEG)'], {}), '(dec / DRADEG)\n', (3232, 3246), False, 'from numpy import cos, sin\n'), ((11620, 11635), 'numpy.array', 'np.array', (['dcfel'], {}), '(dcfel)\n', (11628, 11635), True, 'import numpy as np\n'), ((12685, 12700), 'numpy.array', 'np.array', (['ccsel'], {}), '(ccsel)\n', (12693, 12700), True, 'import numpy as np\n'), ((13458, 13474), 'numpy.array', 'np.array', (['dcargs'], {}), '(dcargs)\n', (13466, 13474), True, 'import numpy as np\n'), ((14686, 14702), 'numpy.array', 'np.array', (['ccamps'], {}), '(ccamps)\n', (14694, 14702), True, 'import numpy as np\n'), ((15041, 15056), 'numpy.array', 'np.array', (['ccsec'], {}), '(ccsec)\n', (15049, 15056), True, 'import numpy as np\n'), ((15619, 15635), 'numpy.array', 'np.array', (['dcargm'], {}), '(dcargm)\n', (15627, 15635), True, 'import numpy as np\n'), ((15928, 15944), 'numpy.array', 'np.array', (['ccampm'], {}), '(ccampm)\n', (15936, 15944), True, 'import numpy as np\n'), ((2020, 2036), 'numpy.cos', 'cos', (['(ra / DRADEG)'], {}), '(ra / DRADEG)\n', (2023, 2036), False, 'from numpy import cos, sin\n'), ((2079, 2095), 'numpy.sin', 'sin', (['(ra / DRADEG)'], {}), '(ra / DRADEG)\n', (2082, 2095), False, 'from numpy import cos, sin\n'), ((2403, 2420), 'numpy.sin', 'sin', (['(2.0 * latrad)'], {}), '(2.0 * latrad)\n', (2406, 2420), False, 'from numpy import cos, sin\n'), ((2447, 2464), 'numpy.sin', 'sin', (['(4.0 * latrad)'], {}), '(4.0 * latrad)\n', (2450, 2464), False, 'from numpy import cos, sin\n'), ((3215, 3226), 'numpy.cos', 'cos', (['latrad'], {}), '(latrad)\n', (3218, 3226), False, 'from numpy import cos, sin\n'), ((17535, 17545), 'numpy.sin', 'sin', (['(3 * g)'], {}), '(3 * g)\n', (17538, 17545), False, 'from numpy import cos, sin\n'), ((2004, 2021), 'numpy.cos', 'cos', (['(dec / DRADEG)'], {}), '(dec / DRADEG)\n', (2007, 2021), False, 'from numpy import cos, sin\n'), ((2063, 2080), 'numpy.cos', 'cos', (['(dec / DRADEG)'], {}), '(dec / DRADEG)\n', (2066, 2080), False, 'from numpy import cos, sin\n'), ((2893, 2910), 'numpy.cos', 'cos', (['(6.0 * latrad)'], {}), '(6.0 * latrad)\n', (2896, 2910), False, 'from numpy import cos, sin\n'), ((17506, 17512), 'numpy.sin', 'sin', (['g'], {}), '(g)\n', (17509, 17512), False, 'from numpy import cos, sin\n'), ((17516, 17526), 'numpy.sin', 'sin', (['(2 * g)'], {}), '(2 * g)\n', (17519, 17526), False, 'from numpy import cos, sin\n'), ((19135, 19151), 'numpy.sin', 'sin', (['(plon - pomg)'], {}), '(plon - pomg)\n', (19138, 19151), False, 'from numpy import cos, sin\n'), ((19192, 19199), 'numpy.sin', 'sin', (['tl'], {}), '(tl)\n', (19195, 19199), False, 'from numpy import cos, sin\n'), ((19251, 19258), 'numpy.cos', 'cos', (['tl'], {}), '(tl)\n', (19254, 19258), False, 'from numpy import cos, sin\n'), ((2860, 2877), 'numpy.cos', 'cos', (['(4.0 * latrad)'], {}), '(4.0 * latrad)\n', (2863, 2877), False, 'from numpy import cos, sin\n'), ((19207, 19216), 'numpy.sin', 'sin', (['pomg'], {}), '(pomg)\n', (19210, 19216), False, 'from numpy import cos, sin\n'), ((19266, 19275), 'numpy.cos', 'cos', (['pomg'], {}), '(pomg)\n', (19269, 19275), False, 'from numpy import cos, sin\n'), ((2819, 2836), 'numpy.cos', 'cos', (['(2.0 * latrad)'], {}), '(2.0 * latrad)\n', (2822, 2836), False, 'from numpy import cos, sin\n')]
|
import argparse
import importlib.util
import os
import sys
import chainer
import numpy as np
import six
from PIL import Image
from ..params import ProcessParams
from ..simple import BaseProcessor
PROJECT_DIR = os.path.dirname(__file__)
waifu2x_path = os.path.join(PROJECT_DIR, "waifu2x-chainer")
def import_waifu2x_module(name):
spec = importlib.util.spec_from_file_location(
name,
os.path.join(waifu2x_path, 'lib', ''.join((name, '.py')))
)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
return foo
iproc = import_waifu2x_module("iproc")
reconstruct = import_waifu2x_module("reconstruct")
srcnn = import_waifu2x_module("srcnn")
utils = import_waifu2x_module("utils")
default_model = "UpResNet10"
def debug_print(debug=False, *args, **kwargs):
if debug:
six.print_(file=sys.stderr, *args, **kwargs)
def load_models(cfg: ProcessParams, args: argparse.Namespace):
ch = 3 if cfg.input_pix_fmt.lower() == 'rgb' else 1
if cfg.model:
if os.path.isdir(cfg.model):
model_dir = cfg.model
else:
model_dir = os.path.join(waifu2x_path, f'models/{cfg.model.lower()}')
else:
cfg.model = default_model
model_dir = os.path.join(waifu2x_path, f'models/{default_model.lower()}')
models = {}
flag = False
if args.method == 'noise_scale':
model_name = 'anime_style_noise{}_scale_{}.npz'.format(
cfg.denoise_level, cfg.input_pix_fmt.lower())
model_path = os.path.join(model_dir, model_name)
if os.path.exists(model_path):
models['noise_scale'] = srcnn.archs[cfg.model](ch)
chainer.serializers.load_npz(model_path, models['noise_scale'])
alpha_model_name = 'anime_style_scale_{}.npz'.format(cfg.input_pix_fmt.lower())
alpha_model_path = os.path.join(model_dir, alpha_model_name)
models['alpha'] = srcnn.archs[cfg.model](ch)
chainer.serializers.load_npz(alpha_model_path, models['alpha'])
else:
flag = True
if args.method == 'scale' or flag:
model_name = 'anime_style_scale_{}.npz'.format(cfg.input_pix_fmt.lower())
model_path = os.path.join(model_dir, model_name)
models['scale'] = srcnn.archs[cfg.model](ch)
chainer.serializers.load_npz(model_path, models['scale'])
if args.method == 'noise' or flag:
model_name = 'anime_style_noise{}_{}.npz'.format(
cfg.denoise_level, cfg.input_pix_fmt.lower())
model_path = os.path.join(model_dir, model_name)
if not os.path.exists(model_path):
model_name = 'anime_style_noise{}_scale_{}.npz'.format(
cfg.denoise_level, cfg.input_pix_fmt.lower())
model_path = os.path.join(model_dir, model_name)
models['noise'] = srcnn.archs[cfg.input_pix_fmt.lower()](ch)
chainer.serializers.load_npz(model_path, models['noise'])
if cfg.device_id >= 0:
chainer.backends.cuda.check_cuda_available()
chainer.backends.cuda.get_device(cfg.device_id).use()
for _, model in models.items():
model.to_gpu()
return models
def split_alpha(src, model, debug=False):
alpha = None
if src.mode in ('L', 'RGB', 'P') and isinstance(
src.info.get('transparency'), bytes
):
src = src.convert('RGBA')
rgb = src.convert('RGB')
if src.mode in ('LA', 'RGBA'):
debug_print(debug, 'Splitting alpha channel...', end=' ', flush=True)
alpha = src.split()[-1]
rgb = iproc.alpha_make_border(rgb, alpha, model)
debug_print(debug, 'OK', debug=debug)
return rgb, alpha
def denoise_image(cfg: ProcessParams, args: argparse.Namespace, src, model):
dst, alpha = split_alpha(src, model, cfg.debug)
debug_print(cfg.debug, 'Level {} denoising...'.format(cfg.denoise_level),
end=' ', flush=True)
if cfg.tta_mode:
dst = reconstruct.image_tta(
dst, model, args.tta_level, cfg.tilesize,
args.batch_size)
else:
dst = reconstruct.image(dst, model, cfg.tilesize, args.batch_size)
if model.inner_scale != 1:
dst = dst.resize((src.size[0], src.size[1]), Image.LANCZOS)
debug_print(cfg.debug, 'OK')
if alpha is not None:
dst.putalpha(alpha)
return dst
def upscale_image(cfg: ProcessParams, args: argparse.Namespace, src, scale_model, alpha_model=None):
dst, alpha = split_alpha(src, scale_model, cfg.debug)
log_scale = np.log2(cfg.scale)
for i in range(int(np.ceil(log_scale))):
debug_print(cfg.debug, '2.0x upscaling...', end=' ', flush=True, )
model = alpha_model
if i == 0 or alpha_model is None:
model = scale_model
if model.inner_scale == 1:
dst = iproc.nn_scaling(dst, 2) # Nearest neighbor 2x scaling
alpha = iproc.nn_scaling(alpha, 2) # Nearest neighbor 2x scaling
if cfg.tta_mode:
dst = reconstruct.image_tta(dst, model, args.tta_level, cfg.tilesize, args.batch_size)
else:
dst = reconstruct.image(dst, model, cfg.tilesize, args.batch_size)
if alpha_model is None:
alpha = reconstruct.image(
alpha, scale_model, cfg.tilesize, args.batch_size)
else:
alpha = reconstruct.image(
alpha, alpha_model, cfg.tilesize, args.batch_size)
debug_print(cfg.debug, 'OK')
dst_w = int(np.round(src.size[0] * cfg.scale))
dst_h = int(np.round(src.size[1] * cfg.scale))
if np.round(log_scale % 1.0, 6) != 0 or log_scale <= 0:
debug_print(cfg.debug, 'Resizing...', end=' ', flush=True)
dst = dst.resize((dst_w, dst_h), Image.LANCZOS)
debug_print(cfg.debug, 'OK')
if alpha is not None:
if alpha.size[0] != dst_w or alpha.size[1] != dst_h:
alpha = alpha.resize((dst_w, dst_h), Image.LANCZOS)
dst.putalpha(alpha)
return dst
def get_parser():
p = argparse.ArgumentParser()
p.add_argument('--tta_level', '-T', type=int, default=8,
choices=[2, 4, 8])
p.add_argument('--method', '-m', default='scale',
choices=['noise', 'scale', 'noise_scale'])
p.add_argument('--batch_size', '-b', type=int, default=16)
return p
class Processor(BaseProcessor):
def __init__(self, params: ProcessParams):
p = get_parser()
self.args = p.parse_args(params.additional_args)
if params.model and params.model in srcnn.table:
params.model = srcnn.table[params.model]
self.models = load_models(params, self.args)
self.params = params
if params.tilesize < 32:
params.tilesize = 128
def process(self, im: Image) -> Image:
if 'noise_scale' in self.models:
return upscale_image(self.params, self.args, im, self.models['noise_scale'], self.models['alpha'])
if 'noise' in self.models:
return denoise_image(self.params, self.args, im, self.models['noise'])
if 'scale' in self.models:
return upscale_image(self.params, self.args, im, self.models['scale'])
|
[
"argparse.ArgumentParser",
"chainer.serializers.load_npz",
"numpy.ceil",
"os.path.isdir",
"numpy.log2",
"os.path.dirname",
"chainer.backends.cuda.get_device",
"os.path.exists",
"chainer.backends.cuda.check_cuda_available",
"numpy.round",
"os.path.join",
"six.print_"
] |
[((213, 238), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (228, 238), False, 'import os\n'), ((254, 298), 'os.path.join', 'os.path.join', (['PROJECT_DIR', '"""waifu2x-chainer"""'], {}), "(PROJECT_DIR, 'waifu2x-chainer')\n", (266, 298), False, 'import os\n'), ((4536, 4554), 'numpy.log2', 'np.log2', (['cfg.scale'], {}), '(cfg.scale)\n', (4543, 4554), True, 'import numpy as np\n'), ((6020, 6045), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6043, 6045), False, 'import argparse\n'), ((837, 881), 'six.print_', 'six.print_', (['*args'], {'file': 'sys.stderr'}), '(*args, file=sys.stderr, **kwargs)\n', (847, 881), False, 'import six\n'), ((1032, 1056), 'os.path.isdir', 'os.path.isdir', (['cfg.model'], {}), '(cfg.model)\n', (1045, 1056), False, 'import os\n'), ((1528, 1563), 'os.path.join', 'os.path.join', (['model_dir', 'model_name'], {}), '(model_dir, model_name)\n', (1540, 1563), False, 'import os\n'), ((1575, 1601), 'os.path.exists', 'os.path.exists', (['model_path'], {}), '(model_path)\n', (1589, 1601), False, 'import os\n'), ((2220, 2255), 'os.path.join', 'os.path.join', (['model_dir', 'model_name'], {}), '(model_dir, model_name)\n', (2232, 2255), False, 'import os\n'), ((2317, 2374), 'chainer.serializers.load_npz', 'chainer.serializers.load_npz', (['model_path', "models['scale']"], {}), "(model_path, models['scale'])\n", (2345, 2374), False, 'import chainer\n'), ((2551, 2586), 'os.path.join', 'os.path.join', (['model_dir', 'model_name'], {}), '(model_dir, model_name)\n', (2563, 2586), False, 'import os\n'), ((2898, 2955), 'chainer.serializers.load_npz', 'chainer.serializers.load_npz', (['model_path', "models['noise']"], {}), "(model_path, models['noise'])\n", (2926, 2955), False, 'import chainer\n'), ((2992, 3036), 'chainer.backends.cuda.check_cuda_available', 'chainer.backends.cuda.check_cuda_available', ([], {}), '()\n', (3034, 3036), False, 'import chainer\n'), ((5492, 5525), 'numpy.round', 'np.round', (['(src.size[0] * cfg.scale)'], {}), '(src.size[0] * cfg.scale)\n', (5500, 5525), True, 'import numpy as np\n'), ((5543, 5576), 'numpy.round', 'np.round', (['(src.size[1] * cfg.scale)'], {}), '(src.size[1] * cfg.scale)\n', (5551, 5576), True, 'import numpy as np\n'), ((1678, 1741), 'chainer.serializers.load_npz', 'chainer.serializers.load_npz', (['model_path', "models['noise_scale']"], {}), "(model_path, models['noise_scale'])\n", (1706, 1741), False, 'import chainer\n'), ((1865, 1906), 'os.path.join', 'os.path.join', (['model_dir', 'alpha_model_name'], {}), '(model_dir, alpha_model_name)\n', (1877, 1906), False, 'import os\n'), ((1976, 2039), 'chainer.serializers.load_npz', 'chainer.serializers.load_npz', (['alpha_model_path', "models['alpha']"], {}), "(alpha_model_path, models['alpha'])\n", (2004, 2039), False, 'import chainer\n'), ((2602, 2628), 'os.path.exists', 'os.path.exists', (['model_path'], {}), '(model_path)\n', (2616, 2628), False, 'import os\n'), ((2785, 2820), 'os.path.join', 'os.path.join', (['model_dir', 'model_name'], {}), '(model_dir, model_name)\n', (2797, 2820), False, 'import os\n'), ((4578, 4596), 'numpy.ceil', 'np.ceil', (['log_scale'], {}), '(log_scale)\n', (4585, 4596), True, 'import numpy as np\n'), ((5585, 5613), 'numpy.round', 'np.round', (['(log_scale % 1.0)', '(6)'], {}), '(log_scale % 1.0, 6)\n', (5593, 5613), True, 'import numpy as np\n'), ((3045, 3092), 'chainer.backends.cuda.get_device', 'chainer.backends.cuda.get_device', (['cfg.device_id'], {}), '(cfg.device_id)\n', (3077, 3092), False, 'import chainer\n')]
|
from __future__ import print_function, division
import os
import torch
import numpy as np
import pandas as pd
import math
import re
import pdb
import pickle
from scipy import stats
from torch.utils.data import Dataset
import h5py
from libs.utils.utils import generate_split, nth
def save_splits(split_datasets, column_keys, filename, boolean_style=False):
splits = [split_datasets[i].slide_data['slide_id'] for i in range(len(split_datasets))]
if not boolean_style:
df = pd.concat(splits, ignore_index=True, axis=1)
df.columns = column_keys
else:
df = pd.concat(splits, ignore_index = True, axis=0)
index = df.values.tolist()
one_hot = np.eye(len(split_datasets)).astype(bool)
bool_array = np.repeat(one_hot, [len(dset) for dset in split_datasets], axis=0)
df = pd.DataFrame(bool_array, index=index, columns = ['train', 'val', 'test'])
df.to_csv(filename)
print()
class Generic_WSI_Classification_Dataset(Dataset):
def __init__(self,
csv_path = 'dataset_csv/ccrcc_clean.csv',
shuffle = False,
seed = 7,
print_info = True,
label_dict = {},
ignore=[],
patient_strat=False,
label_col = None,
patient_voting = 'max',
):
"""
Args:
csv_file (string): Path to the csv file with annotations.
shuffle (boolean): Whether to shuffle
seed (int): random seed for shuffling the data
print_info (boolean): Whether to print a summary of the dataset
label_dict (dict): Dictionary with key, value pairs for converting str labels to int
ignore (list): List containing class labels to ignore
"""
self.label_dict = label_dict
self.custom_test_ids = None
self.num_classes=len(self.label_dict)
self.seed = seed
self.print_info = print_info
self.patient_strat = patient_strat
self.train_ids, self.val_ids, self.test_ids = (None, None, None)
self.data_dir = None
if not label_col:
label_col = 'label'
self.label_col = label_col
slide_data = pd.read_csv(csv_path)
slide_data = self.df_prep(slide_data, self.label_dict, ignore, self.label_col)
###shuffle data
if shuffle:
np.random.seed(seed)
np.random.shuffle(slide_data)
self.slide_data = slide_data
patients = np.unique(np.array(slide_data['case_id'])) # get unique patients
patient_labels = []
for p in patients:
locations = slide_data[slide_data['case_id'] == p].index.tolist()
assert len(locations) > 0
label = slide_data['label'][locations].values
if patient_voting == 'max':
label = label.max() # get patient label (MIL convention)
elif patient_voting == 'maj':
label = stats.mode(label)[0]
else:
pass
patient_labels.append(label)
self.patient_data = {'case_id':patients, 'label':np.array(patient_labels)}
# self.patient_data_prep()
self.cls_ids_prep()
if print_info:
self.summarize()
def cls_ids_prep(self):
self.patient_cls_ids = [[] for i in range(self.num_classes)]
for i in range(self.num_classes):
self.patient_cls_ids[i] = np.where(self.patient_data['label'] == i)[0]
self.slide_cls_ids = [[] for i in range(self.num_classes)]
for i in range(self.num_classes):
self.slide_cls_ids[i] = np.where(self.slide_data['label'] == i)[0]
def patient_data_prep(self):
patients = np.unique(np.array(self.slide_data['case_id'])) # get unique patients
patient_labels = []
for p in patients:
locations = self.slide_data[self.slide_data['case_id'] == p].index.tolist()
assert len(locations) > 0
label = self.slide_data['label'][locations[0]] # get patient label
patient_labels.append(label)
self.patient_data = {'case_id':patients, 'label':np.array(patient_labels)}
@staticmethod
def df_prep(data, label_dict, ignore, label_col):
# convert from MIL label
data = data[['study_code', 'target', 'slide']]
data.rename(columns={'study_code': 'case_id', 'target':'label', 'slide':'slide_id'}, inplace=True)
if label_col != 'label':
data['label'] = data[label_col].copy()
mask = data['label'].isin(ignore)
data = data[~mask]
data.reset_index(drop=True, inplace=True)
for i in data.index:
key = data.loc[i, 'label']
data.at[i, 'label'] = label_dict[key]
return data
def __len__(self):
if self.patient_strat:
return len(self.patient_data['case_id'])
else:
return len(self.slide_data)
def summarize(self):
print("label column: {}".format(self.label_col))
print("label dictionary: {}".format(self.label_dict))
print("number of classes: {}".format(self.num_classes))
print("slide-level counts: ", '\n', self.slide_data['label'].value_counts(sort = False))
for i in range(self.num_classes):
print('Patient-LVL; Number of samples registered in class %d: %d' % (i, self.patient_cls_ids[i].shape[0]))
print('Slide-LVL; Number of samples registered in class %d: %d' % (i, self.slide_cls_ids[i].shape[0]))
def create_splits(self, k = 3, val_num = (25, 25), test_num = (40, 40), label_frac = 1.0, custom_test_ids = None):
settings = {
'n_splits' : k,
'val_num' : val_num,
'test_num': test_num,
'label_frac': label_frac,
'seed': self.seed,
'custom_test_ids': self.custom_test_ids
}
if self.patient_strat:
settings.update({'cls_ids' : self.patient_cls_ids, 'samples': len(self.patient_data['case_id'])})
else:
settings.update({'cls_ids' : self.slide_cls_ids, 'samples': len(self.slide_data)})
self.split_gen = generate_split(**settings)
def set_splits(self,start_from=None):
if start_from:
ids = nth(self.split_gen, start_from)
else:
ids = next(self.split_gen)
if self.patient_strat:
slide_ids = [[] for i in range(len(ids))]
for split in range(len(ids)):
for idx in ids[split]:
case_id = self.patient_data['case_id'][idx]
slide_indices = self.slide_data[self.slide_data['case_id'] == case_id].index.tolist()
slide_ids[split].extend(slide_indices)
self.train_ids, self.val_ids, self.test_ids = slide_ids[0], slide_ids[1], slide_ids[2]
else:
self.train_ids, self.val_ids, self.test_ids = ids
def get_split_from_df(self, all_splits, split_key='train'):
split = all_splits[split_key]
split = split.dropna().reset_index(drop=True)
if len(split) > 0:
mask = self.slide_data['slide_id'].isin(split.tolist())
df_slice = self.slide_data[mask].dropna().reset_index(drop=True)
split = Generic_Split(df_slice, data_dir=self.data_dir, num_classes=self.num_classes)
else:
split = None
return split
def get_merged_split_from_df(self, all_splits, split_keys=['train']):
merged_split = []
for split_key in split_keys:
split = all_splits[split_key]
split = split.dropna().reset_index(drop=True).tolist()
merged_split.extend(split)
if len(split) > 0:
mask = self.slide_data['slide_id'].isin(merged_split)
df_slice = self.slide_data[mask].dropna().reset_index(drop=True)
split = Generic_Split(df_slice, data_dir=self.data_dir, num_classes=self.num_classes)
else:
split = None
return split
def return_splits(self, from_id=True, csv_path=None):
if from_id:
if len(self.train_ids) > 0:
train_data = self.slide_data.loc[self.train_ids].reset_index(drop=True)
train_split = Generic_Split(train_data, data_dir=self.data_dir, num_classes=self.num_classes)
else:
train_split = None
if len(self.val_ids) > 0:
val_data = self.slide_data.loc[self.val_ids].reset_index(drop=True)
val_split = Generic_Split(val_data, data_dir=self.data_dir, num_classes=self.num_classes)
else:
val_split = None
if len(self.test_ids) > 0:
test_data = self.slide_data.loc[self.test_ids].reset_index(drop=True)
test_split = Generic_Split(test_data, data_dir=self.data_dir, num_classes=self.num_classes)
else:
test_split = None
else:
assert csv_path
all_splits = pd.read_csv(csv_path)
train_split = self.get_split_from_df(all_splits, 'train')
val_split = self.get_split_from_df(all_splits, 'val')
test_split = self.get_split_from_df(all_splits, 'test')
return train_split, val_split, test_split
def get_list(self, ids):
return self.slide_data['slide_id'][ids]
def getlabel(self, ids):
return self.slide_data['label'][ids]
def __getitem__(self, idx):
return None
def test_split_gen(self, return_descriptor=False):
if return_descriptor:
index = [list(self.label_dict.keys())[list(self.label_dict.values()).index(i)] for i in range(self.num_classes)]
columns = ['train', 'val', 'test']
df = pd.DataFrame(np.full((len(index), len(columns)), 0, dtype=np.int32), index= index,
columns= columns)
count = len(self.train_ids)
print('\nnumber of training samples: {}'.format(count))
labels = self.getlabel(self.train_ids)
unique, counts = np.unique(labels, return_counts=True)
for u in range(len(unique)):
print('number of samples in cls {}: {}'.format(unique[u], counts[u]))
if return_descriptor:
df.loc[index[u], 'train'] = counts[u]
count = len(self.val_ids)
print('\nnumber of val samples: {}'.format(count))
labels = self.getlabel(self.val_ids)
unique, counts = np.unique(labels, return_counts=True)
for u in range(len(unique)):
print('number of samples in cls {}: {}'.format(unique[u], counts[u]))
if return_descriptor:
df.loc[index[u], 'val'] = counts[u]
count = len(self.test_ids)
print('\nnumber of test samples: {}'.format(count))
labels = self.getlabel(self.test_ids)
unique, counts = np.unique(labels, return_counts=True)
for u in range(len(unique)):
print('number of samples in cls {}: {}'.format(unique[u], counts[u]))
if return_descriptor:
df.loc[index[u], 'test'] = counts[u]
assert len(np.intersect1d(self.train_ids, self.test_ids)) == 0
assert len(np.intersect1d(self.train_ids, self.val_ids)) == 0
assert len(np.intersect1d(self.val_ids, self.test_ids)) == 0
if return_descriptor:
return df
def save_split(self, filename):
train_split = self.get_list(self.train_ids)
val_split = self.get_list(self.val_ids)
test_split = self.get_list(self.test_ids)
df_tr = pd.DataFrame({'train': train_split})
df_v = pd.DataFrame({'val': val_split})
df_t = pd.DataFrame({'test': test_split})
df = pd.concat([df_tr, df_v, df_t], axis=1)
df.to_csv(filename, index = False)
class Generic_MIL_Dataset(Generic_WSI_Classification_Dataset):
def __init__(self,
data_dir,
**kwargs):
super(Generic_MIL_Dataset, self).__init__(**kwargs)
self.data_dir = data_dir
self.use_h5 = False
def load_from_h5(self, toggle):
self.use_h5 = toggle
def __getitem__(self, idx):
slide_id = self.slide_data['slide_id'][idx]
label = self.slide_data['label'][idx]
if not self.use_h5:
if self.data_dir:
full_path = os.path.join(self.data_dir,'{}.pt'.format(slide_id))
features = torch.load(full_path)
return features, label
else:
return slide_id, label
else:
full_path = os.path.join(self.data_dir,'{}.h5'.format(slide_id))
with h5py.File(full_path,'r') as hdf5_file:
features = hdf5_file['features'][:]
coords = hdf5_file['coords'][:]
features = torch.from_numpy(features)
return features, label, coords
class Generic_Split(Generic_MIL_Dataset):
def __init__(self, slide_data, data_dir=None, num_classes=2):
self.use_h5 = False
self.slide_data = slide_data
self.data_dir = data_dir
self.num_classes = num_classes
self.slide_cls_ids = [[] for i in range(self.num_classes)]
for i in range(self.num_classes):
self.slide_cls_ids[i] = np.where(self.slide_data['label'] == i)[0]
def __len__(self):
return len(self.slide_data)
|
[
"pandas.DataFrame",
"torch.from_numpy",
"h5py.File",
"numpy.random.seed",
"numpy.random.shuffle",
"libs.utils.utils.generate_split",
"pandas.read_csv",
"scipy.stats.mode",
"torch.load",
"numpy.where",
"numpy.array",
"numpy.intersect1d",
"pandas.concat",
"numpy.unique",
"libs.utils.utils.nth"
] |
[((480, 524), 'pandas.concat', 'pd.concat', (['splits'], {'ignore_index': '(True)', 'axis': '(1)'}), '(splits, ignore_index=True, axis=1)\n', (489, 524), True, 'import pandas as pd\n'), ((566, 610), 'pandas.concat', 'pd.concat', (['splits'], {'ignore_index': '(True)', 'axis': '(0)'}), '(splits, ignore_index=True, axis=0)\n', (575, 610), True, 'import pandas as pd\n'), ((784, 855), 'pandas.DataFrame', 'pd.DataFrame', (['bool_array'], {'index': 'index', 'columns': "['train', 'val', 'test']"}), "(bool_array, index=index, columns=['train', 'val', 'test'])\n", (796, 855), True, 'import pandas as pd\n'), ((1916, 1937), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {}), '(csv_path)\n', (1927, 1937), True, 'import pandas as pd\n'), ((5353, 5379), 'libs.utils.utils.generate_split', 'generate_split', ([], {}), '(**settings)\n', (5367, 5379), False, 'from libs.utils.utils import generate_split, nth\n'), ((8686, 8723), 'numpy.unique', 'np.unique', (['labels'], {'return_counts': '(True)'}), '(labels, return_counts=True)\n', (8695, 8723), True, 'import numpy as np\n'), ((9037, 9074), 'numpy.unique', 'np.unique', (['labels'], {'return_counts': '(True)'}), '(labels, return_counts=True)\n', (9046, 9074), True, 'import numpy as np\n'), ((9387, 9424), 'numpy.unique', 'np.unique', (['labels'], {'return_counts': '(True)'}), '(labels, return_counts=True)\n', (9396, 9424), True, 'import numpy as np\n'), ((10002, 10038), 'pandas.DataFrame', 'pd.DataFrame', (["{'train': train_split}"], {}), "({'train': train_split})\n", (10014, 10038), True, 'import pandas as pd\n'), ((10048, 10080), 'pandas.DataFrame', 'pd.DataFrame', (["{'val': val_split}"], {}), "({'val': val_split})\n", (10060, 10080), True, 'import pandas as pd\n'), ((10090, 10124), 'pandas.DataFrame', 'pd.DataFrame', (["{'test': test_split}"], {}), "({'test': test_split})\n", (10102, 10124), True, 'import pandas as pd\n'), ((10132, 10170), 'pandas.concat', 'pd.concat', (['[df_tr, df_v, df_t]'], {'axis': '(1)'}), '([df_tr, df_v, df_t], axis=1)\n', (10141, 10170), True, 'import pandas as pd\n'), ((2055, 2075), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2069, 2075), True, 'import numpy as np\n'), ((2079, 2108), 'numpy.random.shuffle', 'np.random.shuffle', (['slide_data'], {}), '(slide_data)\n', (2096, 2108), True, 'import numpy as np\n'), ((2165, 2196), 'numpy.array', 'np.array', (["slide_data['case_id']"], {}), "(slide_data['case_id'])\n", (2173, 2196), True, 'import numpy as np\n'), ((2676, 2700), 'numpy.array', 'np.array', (['patient_labels'], {}), '(patient_labels)\n', (2684, 2700), True, 'import numpy as np\n'), ((3215, 3251), 'numpy.array', 'np.array', (["self.slide_data['case_id']"], {}), "(self.slide_data['case_id'])\n", (3223, 3251), True, 'import numpy as np\n'), ((3585, 3609), 'numpy.array', 'np.array', (['patient_labels'], {}), '(patient_labels)\n', (3593, 3609), True, 'import numpy as np\n'), ((5446, 5477), 'libs.utils.utils.nth', 'nth', (['self.split_gen', 'start_from'], {}), '(self.split_gen, start_from)\n', (5449, 5477), False, 'from libs.utils.utils import generate_split, nth\n'), ((7763, 7784), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {}), '(csv_path)\n', (7774, 7784), True, 'import pandas as pd\n'), ((11030, 11056), 'torch.from_numpy', 'torch.from_numpy', (['features'], {}), '(features)\n', (11046, 11056), False, 'import torch\n'), ((2948, 2989), 'numpy.where', 'np.where', (["(self.patient_data['label'] == i)"], {}), "(self.patient_data['label'] == i)\n", (2956, 2989), True, 'import numpy as np\n'), ((3118, 3157), 'numpy.where', 'np.where', (["(self.slide_data['label'] == i)"], {}), "(self.slide_data['label'] == i)\n", (3126, 3157), True, 'import numpy as np\n'), ((9609, 9654), 'numpy.intersect1d', 'np.intersect1d', (['self.train_ids', 'self.test_ids'], {}), '(self.train_ids, self.test_ids)\n', (9623, 9654), True, 'import numpy as np\n'), ((9674, 9718), 'numpy.intersect1d', 'np.intersect1d', (['self.train_ids', 'self.val_ids'], {}), '(self.train_ids, self.val_ids)\n', (9688, 9718), True, 'import numpy as np\n'), ((9738, 9781), 'numpy.intersect1d', 'np.intersect1d', (['self.val_ids', 'self.test_ids'], {}), '(self.val_ids, self.test_ids)\n', (9752, 9781), True, 'import numpy as np\n'), ((10726, 10747), 'torch.load', 'torch.load', (['full_path'], {}), '(full_path)\n', (10736, 10747), False, 'import torch\n'), ((10900, 10925), 'h5py.File', 'h5py.File', (['full_path', '"""r"""'], {}), "(full_path, 'r')\n", (10909, 10925), False, 'import h5py\n'), ((11435, 11474), 'numpy.where', 'np.where', (["(self.slide_data['label'] == i)"], {}), "(self.slide_data['label'] == i)\n", (11443, 11474), True, 'import numpy as np\n'), ((2550, 2567), 'scipy.stats.mode', 'stats.mode', (['label'], {}), '(label)\n', (2560, 2567), False, 'from scipy import stats\n')]
|
import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
from PIL import Image
from mtcnn.mtcnn import MTCNN
train_dir = 'data/train'
valid_dir = 'data/val'
face_detector = MTCNN()
# for i in os.listdir(train_dir):
# print(i)
# my_img = 'data/train/madonna/httpiamediaimdbcomimagesMMVBMTANDQNTAxNDVeQTJeQWpwZBbWUMDIMjQOTYVUXCRALjpg.jpg'
# img = img.convert("RGB")
def extract_faces(filename):
img_path = filename
img = Image.open(img_path)
img = img.convert("RGB")
pixels = np.asarray(img)
results = face_detector.detect_faces(pixels)
x1, y1, width, height = results[0]['box']
x1 = abs(x1)
y1 = abs(y1)
x2,y2 = x1+width, y1+height
face = pixels[y1:y2,x1:x2]
image = Image.fromarray(face)
resized_img = image.resize((160,160))
final_pix = np.asarray(resized_img)
return final_pix
def load_faces(directory):
faces = []
for filename in os.listdir(directory):
path = os.path.join(directory,filename)
face = extract_faces(path)
faces.append(face)
return faces
def load_dataset(directory):
X, y = [], []
for subdir in os.listdir(directory):
path = directory +'/' + subdir + '/'
if not os.path.isdir(path):
continue
faces = load_faces(path)
labels = [subdir for _ in range(len(faces))]
# summarize progress
print('>loaded %d examples for class: %s' % (len(faces), subdir))
# store
X.extend(faces)
y.extend(labels)
return np.asarray(X), np.asarray(y)
# load_dataset(train_dir))
trainX, trainy = load_dataset(train_dir)
print(trainX.shape, trainy.shape)
# load test dataset
testX, testy = load_dataset(valid_dir)
print(testX.shape, testy.shape)
# save arrays to one file in compressed format
# np.savez_compressed('face_test.npz', trainX, trainy, testX, testy)
# plt.imshow(ans)
# plt.show()
|
[
"os.path.isdir",
"numpy.asarray",
"mtcnn.mtcnn.MTCNN",
"PIL.Image.open",
"PIL.Image.fromarray",
"os.path.join",
"os.listdir"
] |
[((194, 201), 'mtcnn.mtcnn.MTCNN', 'MTCNN', ([], {}), '()\n', (199, 201), False, 'from mtcnn.mtcnn import MTCNN\n'), ((447, 467), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (457, 467), False, 'from PIL import Image\n'), ((504, 519), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (514, 519), True, 'import numpy as np\n'), ((704, 725), 'PIL.Image.fromarray', 'Image.fromarray', (['face'], {}), '(face)\n', (719, 725), False, 'from PIL import Image\n'), ((778, 801), 'numpy.asarray', 'np.asarray', (['resized_img'], {}), '(resized_img)\n', (788, 801), True, 'import numpy as np\n'), ((882, 903), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (892, 903), False, 'import os\n'), ((1072, 1093), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (1082, 1093), False, 'import os\n'), ((914, 947), 'os.path.join', 'os.path.join', (['directory', 'filename'], {}), '(directory, filename)\n', (926, 947), False, 'import os\n'), ((1399, 1412), 'numpy.asarray', 'np.asarray', (['X'], {}), '(X)\n', (1409, 1412), True, 'import numpy as np\n'), ((1414, 1427), 'numpy.asarray', 'np.asarray', (['y'], {}), '(y)\n', (1424, 1427), True, 'import numpy as np\n'), ((1145, 1164), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (1158, 1164), False, 'import os\n')]
|
import time
import os
import glob
import gc
import numpy as np
import torch
import torch.optim as optim
import torch.nn as nn
import pytorch_lightning as pl
import pytorch_lightning.loggers as pl_loggers
import pytorch_lightning.callbacks as pl_callbacks
from torch.utils.data import DataLoader
from config_modified import args
from models.video_net import VideoNet
from data.lrs2_dataset import LRS2Pretrain, LRS2Main
from data.utils import collate_fn
from utils.metrics import compute_cer, compute_wer
from utils.decoders import ctc_greedy_decode, ctc_search_decode
class VideoNetDataModule(pl.LightningDataModule):
def __init__(self, data_cfg):
# TODO: Change cfg to regular argument names
super().__init__()
self.data_cfg = data_cfg
self.videoParams = {"videoFPS": self.data_cfg["VIDEO_FPS"]}
self.gpuAvailable = torch.cuda.is_available()
self.data_cls = LRS2Pretrain if self.data_cfg["PRETRAIN"] else LRS2Main
if self.data_cfg["PRETRAIN"]:
self.trainData = LRS2Pretrain("pretrain",
self.data_cfg["DATA_DIRECTORY"],
self.data_cfg["PRETRAIN_NUM_WORDS"],
self.data_cfg["CHAR_TO_INDEX"],
self.data_cfg["STEP_SIZE"],
self.videoParams)
self.valData = LRS2Pretrain("preval",
self.data_cfg["DATA_DIRECTORY"],
self.data_cfg["PRETRAIN_NUM_WORDS"],
self.data_cfg["CHAR_TO_INDEX"],
self.data_cfg["STEP_SIZE"],
self.videoParams)
else:
self.trainData = LRS2Main("train",
self.data_cfg["DATA_DIRECTORY"],
self.data_cfg["MAIN_REQ_INPUT_LENGTH"],
self.data_cfg["CHAR_TO_INDEX"],
self.data_cfg["STEP_SIZE"],
self.videoParams)
self.valData = LRS2Main("val",
self.data_cfg["DATA_DIRECTORY"],
self.data_cfg["MAIN_REQ_INPUT_LENGTH"],
self.data_cfg["CHAR_TO_INDEX"],
self.data_cfg["STEP_SIZE"],
self.videoParams)
def train_dataloader(self) -> DataLoader:
kwargs = {"num_workers": self.data_cfg["NUM_WORKERS"], "pin_memory": True} if self.gpuAvailable else {}
trainLoader = DataLoader(self.trainData,
batch_size=self.data_cfg["BATCH_SIZE"],
collate_fn=collate_fn,
shuffle=True,
**kwargs)
return trainLoader
def val_dataloader(self) -> DataLoader:
kwargs = {"num_workers": self.data_cfg["NUM_WORKERS"], "pin_memory": True} if self.gpuAvailable else {}
valLoader = DataLoader(self.valData,
batch_size=self.data_cfg["BATCH_SIZE"],
collate_fn=collate_fn,
shuffle=True,
**kwargs)
return valLoader
class VideoNetPL(pl.LightningModule):
def __init__(self, net_class, net_cfg, train_cfg):
super().__init__()
self.net_cfg = net_cfg
self.train_cfg = train_cfg
self.loss_fn = nn.CTCLoss(blank=0, zero_infinity=False)
self.model = net_class(**net_cfg)
def forward(self, inputBatch):
outputBatch = self.model(inputBatch)
return outputBatch
def training_step(self, batch, batch_idx):
trainParams = {"spaceIx": args["CHAR_TO_INDEX"][" "],
"eosIx": args["CHAR_TO_INDEX"]["<EOS>"]}
inputBatch, targetBatch, inputLenBatch, targetLenBatch = batch
inputBatch, targetBatch = inputBatch.float(), targetBatch.int()
inputLenBatch, targetLenBatch = inputLenBatch.int(), targetLenBatch.int()
outputBatch = self.model(inputBatch)
with torch.backends.cudnn.flags(enabled=False):
loss = self.loss_fn(outputBatch, targetBatch, inputLenBatch, targetLenBatch)
trainingLoss = loss
predictionBatch, predictionLenBatch = ctc_greedy_decode(outputBatch.detach(),
inputLenBatch,
trainParams["eosIx"])
trainingCER = compute_cer(predictionBatch,
targetBatch,
predictionLenBatch,
targetLenBatch)
trainingWER = compute_wer(predictionBatch,
targetBatch,
predictionLenBatch,
targetLenBatch,
trainParams["spaceIx"])
self.log('train_loss', trainingLoss, prog_bar=True)
self.log('train_wer', trainingWER, prog_bar=True)
self.log('train_cer', trainingCER, prog_bar=True)
return trainingLoss
def validation_step(self, batch, batch_idx):
evalParams = {"decodeScheme": "greedy",
"spaceIx": args["CHAR_TO_INDEX"][" "],
"eosIx": args["CHAR_TO_INDEX"]["<EOS>"]}
inputBatch, targetBatch, inputLenBatch, targetLenBatch = batch
inputBatch, targetBatch = inputBatch.float(), targetBatch.int()
inputLenBatch, targetLenBatch = inputLenBatch.int(), targetLenBatch.int()
outputBatch = self.model(inputBatch)
with torch.backends.cudnn.flags(enabled=False):
loss = self.loss_fn(outputBatch, targetBatch, inputLenBatch, targetLenBatch)
evalLoss = loss
if evalParams["decodeScheme"] == "greedy":
predictionBatch, predictionLenBatch = ctc_greedy_decode(outputBatch,
inputLenBatch,
evalParams["eosIx"])
elif evalParams["decodeScheme"] == "search":
predictionBatch, predictionLenBatch = ctc_search_decode(outputBatch,
inputLenBatch,
evalParams["beamSearchParams"],
evalParams["spaceIx"],
evalParams["eosIx"],
evalParams["lm"])
else:
print("Invalid Decode Scheme")
exit()
evalCER = compute_cer(predictionBatch,
targetBatch,
predictionLenBatch,
targetLenBatch)
evalWER = compute_wer(predictionBatch,
targetBatch,
predictionLenBatch,
targetLenBatch,
evalParams["spaceIx"])
self.log('val_loss', evalLoss, prog_bar=True)
self.log('val_wer', evalWER, prog_bar=True)
self.log('val_cer', evalCER, prog_bar=True)
return evalLoss
def configure_optimizers(self):
optimizer = optim.Adam(self.model.parameters(),
lr=self.train_cfg["INIT_LR"],
betas=(self.train_cfg["MOMENTUM1"], self.train_cfg["MOMENTUM2"]))
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer,
mode="min",
factor=self.train_cfg["LR_SCHEDULER_FACTOR"],
patience=self.train_cfg["LR_SCHEDULER_WAIT"],
threshold=self.train_cfg["LR_SCHEDULER_THRESH"],
threshold_mode="abs",
min_lr=self.train_cfg["FINAL_LR"],
verbose=True)
return {
"optimizer": optimizer,
"lr_scheduler": scheduler,
"monitor": "val_wer"
}
def train_step(args, timestr='', best_ckpt=None):
data_cfg = {
"VIDEO_FPS": args["VIDEO_FPS"],
"DATA_DIRECTORY": args["DATA_DIRECTORY"],
"PRETRAIN_NUM_WORDS": args["PRETRAIN_NUM_WORDS"],
"CHAR_TO_INDEX": args["CHAR_TO_INDEX"],
"STEP_SIZE": args["STEP_SIZE"],
"NUM_WORKERS": args["NUM_WORKERS"],
"BATCH_SIZE": args["BATCH_SIZE"],
"PRETRAIN": args["PRETRAIN"]
}
train_cfg = {
"INIT_LR": args["INIT_LR"],
"MOMENTUM1": args["MOMENTUM1"],
"MOMENTUM2": args["MOMENTUM2"],
"LR_SCHEDULER_FACTOR": args["LR_SCHEDULER_FACTOR"],
"LR_SCHEDULER_WAIT": args["LR_SCHEDULER_WAIT"],
"LR_SCHEDULER_THRESH": args["LR_SCHEDULER_THRESH"],
"FINAL_LR": args["FINAL_LR"],
}
net_cfg = {
"dModel": args["TX_NUM_FEATURES"],
"nHeads": args["TX_ATTENTION_HEADS"],
"numLayers": args["TX_NUM_LAYERS"],
"peMaxLen": args["PE_MAX_LENGTH"],
"fcHiddenSize": args["TX_FEEDFORWARD_DIM"],
"dropout": args["TX_DROPOUT"],
"numClasses": args["NUM_CLASSES"]
}
logger = pl_loggers.NeptuneLogger(
project_name='benso/deep-avsr',
experiment_name=f'video_only_curriculum',
params=args,
tags={'start_date': timestr}
)
model_checkpoint = pl_callbacks.ModelCheckpoint(
filename=args["NUM_WORDS"] + '/{epoch:02d}-{val_wer:.2f}',
save_weights_only=True,
save_top_k=3,
monitor='val_wer',
period=1
)
trainer = pl.Trainer(
logger=logger,
checkpoint_callback=model_checkpoint,
gpus=2,
auto_select_gpus=False,
max_epochs=args["NUM_STEPS"],
accelerator=args["ACCELERATOR"],
resume_from_checkpoint=best_ckpt
)
data = VideoNetDataModule(data_cfg=data_cfg)
network = VideoNetPL(net_class=VideoNet, net_cfg=net_cfg, train_cfg=train_cfg)
trainer.fit(model=network, datamodule=data)
return model_checkpoint.best_model_path
def curriculum(args):
PRETRAIN_NUM_WORDS = [1, 2, 3, 5, 7, 9, 11, 13, 17, 21, 29, 37, 0]
PRETRAIN_CONFIG = {
1: {'PRETRAIN': True, 'PRETRAIN_NUM_WORDS': 1, 'BATCH_SIZE': 32,},
2: {'PRETRAIN': True, 'PRETRAIN_NUM_WORDS': 2, 'BATCH_SIZE': 32},
3: {'PRETRAIN': True, 'PRETRAIN_NUM_WORDS': 3, 'BATCH_SIZE': 32},
5: {'PRETRAIN': True, 'PRETRAIN_NUM_WORDS': 5, 'BATCH_SIZE': 32},
7: {'PRETRAIN': True, 'PRETRAIN_NUM_WORDS': 7, 'BATCH_SIZE': 32},
9: {'PRETRAIN': True, 'PRETRAIN_NUM_WORDS': 9, 'BATCH_SIZE': 32},
11: {'PRETRAIN': True, 'PRETRAIN_NUM_WORDS': 11, 'BATCH_SIZE': 32},
13: {'PRETRAIN': True, 'PRETRAIN_NUM_WORDS': 13, 'BATCH_SIZE': 32},
17: {'PRETRAIN': True, 'PRETRAIN_NUM_WORDS': 17, 'BATCH_SIZE': 32},
21: {'PRETRAIN': True, 'PRETRAIN_NUM_WORDS': 21, 'BATCH_SIZE': 32},
29: {'PRETRAIN': True, 'PRETRAIN_NUM_WORDS': 29, 'BATCH_SIZE': 32},
37: {'PRETRAIN': True, 'PRETRAIN_NUM_WORDS': 37, 'BATCH_SIZE': 32},
0: {'PRETRAIN': False, 'PRETRAIN_NUM_WORDS': 0, 'BATCH_SIZE': 32},
}
# Create parent directory for the checkpoints of this curriculum run
timestr = time.strftime("%Y%m%d-%H%M%S")
# Start curriculum learning loop
best_ckpt = None
for n, num_words in enumerate(PRETRAIN_NUM_WORDS):
train_over = False
while not train_over:
cfg = args.copy()
cfg.update(PRETRAIN_CONFIG[num_words])
try:
best_ckpt = train_step(args=cfg, timestr=timestr, best_ckpt=best_ckpt)
train_over = True
except RuntimeError as e:
print(f"Runtime Error... Trying Again: \n{e}")
PRETRAIN_CONFIG[num_words]['BATCH_SIZE'] //= 2
torch.cuda.empty_cache()
gc.collect()
if __name__ == '__main__':
np.random.seed(args["SEED"])
torch.manual_seed(args["SEED"])
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
curriculum(args)
|
[
"pytorch_lightning.Trainer",
"numpy.random.seed",
"utils.decoders.ctc_search_decode",
"time.strftime",
"gc.collect",
"torch.utils.data.DataLoader",
"data.lrs2_dataset.LRS2Pretrain",
"utils.metrics.compute_wer",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"pytorch_lightning.loggers.NeptuneLogger",
"pytorch_lightning.callbacks.ModelCheckpoint",
"torch.manual_seed",
"utils.decoders.ctc_greedy_decode",
"torch.cuda.is_available",
"torch.nn.CTCLoss",
"utils.metrics.compute_cer",
"data.lrs2_dataset.LRS2Main",
"config_modified.args.copy",
"torch.backends.cudnn.flags",
"torch.cuda.empty_cache"
] |
[((9879, 10025), 'pytorch_lightning.loggers.NeptuneLogger', 'pl_loggers.NeptuneLogger', ([], {'project_name': '"""benso/deep-avsr"""', 'experiment_name': 'f"""video_only_curriculum"""', 'params': 'args', 'tags': "{'start_date': timestr}"}), "(project_name='benso/deep-avsr', experiment_name=\n f'video_only_curriculum', params=args, tags={'start_date': timestr})\n", (9903, 10025), True, 'import pytorch_lightning.loggers as pl_loggers\n'), ((10083, 10245), 'pytorch_lightning.callbacks.ModelCheckpoint', 'pl_callbacks.ModelCheckpoint', ([], {'filename': "(args['NUM_WORDS'] + '/{epoch:02d}-{val_wer:.2f}')", 'save_weights_only': '(True)', 'save_top_k': '(3)', 'monitor': '"""val_wer"""', 'period': '(1)'}), "(filename=args['NUM_WORDS'] +\n '/{epoch:02d}-{val_wer:.2f}', save_weights_only=True, save_top_k=3,\n monitor='val_wer', period=1)\n", (10111, 10245), True, 'import pytorch_lightning.callbacks as pl_callbacks\n'), ((10299, 10500), 'pytorch_lightning.Trainer', 'pl.Trainer', ([], {'logger': 'logger', 'checkpoint_callback': 'model_checkpoint', 'gpus': '(2)', 'auto_select_gpus': '(False)', 'max_epochs': "args['NUM_STEPS']", 'accelerator': "args['ACCELERATOR']", 'resume_from_checkpoint': 'best_ckpt'}), "(logger=logger, checkpoint_callback=model_checkpoint, gpus=2,\n auto_select_gpus=False, max_epochs=args['NUM_STEPS'], accelerator=args[\n 'ACCELERATOR'], resume_from_checkpoint=best_ckpt)\n", (10309, 10500), True, 'import pytorch_lightning as pl\n'), ((11969, 11999), 'time.strftime', 'time.strftime', (['"""%Y%m%d-%H%M%S"""'], {}), "('%Y%m%d-%H%M%S')\n", (11982, 11999), False, 'import time\n'), ((12651, 12679), 'numpy.random.seed', 'np.random.seed', (["args['SEED']"], {}), "(args['SEED'])\n", (12665, 12679), True, 'import numpy as np\n'), ((12684, 12715), 'torch.manual_seed', 'torch.manual_seed', (["args['SEED']"], {}), "(args['SEED'])\n", (12701, 12715), False, 'import torch\n'), ((865, 890), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (888, 890), False, 'import torch\n'), ((2777, 2894), 'torch.utils.data.DataLoader', 'DataLoader', (['self.trainData'], {'batch_size': "self.data_cfg['BATCH_SIZE']", 'collate_fn': 'collate_fn', 'shuffle': '(True)'}), "(self.trainData, batch_size=self.data_cfg['BATCH_SIZE'],\n collate_fn=collate_fn, shuffle=True, **kwargs)\n", (2787, 2894), False, 'from torch.utils.data import DataLoader\n'), ((3227, 3343), 'torch.utils.data.DataLoader', 'DataLoader', (['self.valData'], {'batch_size': "self.data_cfg['BATCH_SIZE']", 'collate_fn': 'collate_fn', 'shuffle': '(True)'}), "(self.valData, batch_size=self.data_cfg['BATCH_SIZE'], collate_fn\n =collate_fn, shuffle=True, **kwargs)\n", (3237, 3343), False, 'from torch.utils.data import DataLoader\n'), ((3699, 3739), 'torch.nn.CTCLoss', 'nn.CTCLoss', ([], {'blank': '(0)', 'zero_infinity': '(False)'}), '(blank=0, zero_infinity=False)\n', (3709, 3739), True, 'import torch.nn as nn\n'), ((4784, 4861), 'utils.metrics.compute_cer', 'compute_cer', (['predictionBatch', 'targetBatch', 'predictionLenBatch', 'targetLenBatch'], {}), '(predictionBatch, targetBatch, predictionLenBatch, targetLenBatch)\n', (4795, 4861), False, 'from utils.metrics import compute_cer, compute_wer\n'), ((4986, 5091), 'utils.metrics.compute_wer', 'compute_wer', (['predictionBatch', 'targetBatch', 'predictionLenBatch', 'targetLenBatch', "trainParams['spaceIx']"], {}), "(predictionBatch, targetBatch, predictionLenBatch,\n targetLenBatch, trainParams['spaceIx'])\n", (4997, 5091), False, 'from utils.metrics import compute_cer, compute_wer\n'), ((7079, 7156), 'utils.metrics.compute_cer', 'compute_cer', (['predictionBatch', 'targetBatch', 'predictionLenBatch', 'targetLenBatch'], {}), '(predictionBatch, targetBatch, predictionLenBatch, targetLenBatch)\n', (7090, 7156), False, 'from utils.metrics import compute_cer, compute_wer\n'), ((7265, 7369), 'utils.metrics.compute_wer', 'compute_wer', (['predictionBatch', 'targetBatch', 'predictionLenBatch', 'targetLenBatch', "evalParams['spaceIx']"], {}), "(predictionBatch, targetBatch, predictionLenBatch,\n targetLenBatch, evalParams['spaceIx'])\n", (7276, 7369), False, 'from utils.metrics import compute_cer, compute_wer\n'), ((7940, 8225), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'optim.lr_scheduler.ReduceLROnPlateau', (['optimizer'], {'mode': '"""min"""', 'factor': "self.train_cfg['LR_SCHEDULER_FACTOR']", 'patience': "self.train_cfg['LR_SCHEDULER_WAIT']", 'threshold': "self.train_cfg['LR_SCHEDULER_THRESH']", 'threshold_mode': '"""abs"""', 'min_lr': "self.train_cfg['FINAL_LR']", 'verbose': '(True)'}), "(optimizer, mode='min', factor=self.\n train_cfg['LR_SCHEDULER_FACTOR'], patience=self.train_cfg[\n 'LR_SCHEDULER_WAIT'], threshold=self.train_cfg['LR_SCHEDULER_THRESH'],\n threshold_mode='abs', min_lr=self.train_cfg['FINAL_LR'], verbose=True)\n", (7976, 8225), True, 'import torch.optim as optim\n'), ((1039, 1221), 'data.lrs2_dataset.LRS2Pretrain', 'LRS2Pretrain', (['"""pretrain"""', "self.data_cfg['DATA_DIRECTORY']", "self.data_cfg['PRETRAIN_NUM_WORDS']", "self.data_cfg['CHAR_TO_INDEX']", "self.data_cfg['STEP_SIZE']", 'self.videoParams'], {}), "('pretrain', self.data_cfg['DATA_DIRECTORY'], self.data_cfg[\n 'PRETRAIN_NUM_WORDS'], self.data_cfg['CHAR_TO_INDEX'], self.data_cfg[\n 'STEP_SIZE'], self.videoParams)\n", (1051, 1221), False, 'from data.lrs2_dataset import LRS2Pretrain, LRS2Main\n'), ((1449, 1629), 'data.lrs2_dataset.LRS2Pretrain', 'LRS2Pretrain', (['"""preval"""', "self.data_cfg['DATA_DIRECTORY']", "self.data_cfg['PRETRAIN_NUM_WORDS']", "self.data_cfg['CHAR_TO_INDEX']", "self.data_cfg['STEP_SIZE']", 'self.videoParams'], {}), "('preval', self.data_cfg['DATA_DIRECTORY'], self.data_cfg[\n 'PRETRAIN_NUM_WORDS'], self.data_cfg['CHAR_TO_INDEX'], self.data_cfg[\n 'STEP_SIZE'], self.videoParams)\n", (1461, 1629), False, 'from data.lrs2_dataset import LRS2Pretrain, LRS2Main\n'), ((1863, 2041), 'data.lrs2_dataset.LRS2Main', 'LRS2Main', (['"""train"""', "self.data_cfg['DATA_DIRECTORY']", "self.data_cfg['MAIN_REQ_INPUT_LENGTH']", "self.data_cfg['CHAR_TO_INDEX']", "self.data_cfg['STEP_SIZE']", 'self.videoParams'], {}), "('train', self.data_cfg['DATA_DIRECTORY'], self.data_cfg[\n 'MAIN_REQ_INPUT_LENGTH'], self.data_cfg['CHAR_TO_INDEX'], self.data_cfg\n ['STEP_SIZE'], self.videoParams)\n", (1871, 2041), False, 'from data.lrs2_dataset import LRS2Pretrain, LRS2Main\n'), ((2249, 2425), 'data.lrs2_dataset.LRS2Main', 'LRS2Main', (['"""val"""', "self.data_cfg['DATA_DIRECTORY']", "self.data_cfg['MAIN_REQ_INPUT_LENGTH']", "self.data_cfg['CHAR_TO_INDEX']", "self.data_cfg['STEP_SIZE']", 'self.videoParams'], {}), "('val', self.data_cfg['DATA_DIRECTORY'], self.data_cfg[\n 'MAIN_REQ_INPUT_LENGTH'], self.data_cfg['CHAR_TO_INDEX'], self.data_cfg\n ['STEP_SIZE'], self.videoParams)\n", (2257, 2425), False, 'from data.lrs2_dataset import LRS2Pretrain, LRS2Main\n'), ((4350, 4391), 'torch.backends.cudnn.flags', 'torch.backends.cudnn.flags', ([], {'enabled': '(False)'}), '(enabled=False)\n', (4376, 4391), False, 'import torch\n'), ((5940, 5981), 'torch.backends.cudnn.flags', 'torch.backends.cudnn.flags', ([], {'enabled': '(False)'}), '(enabled=False)\n', (5966, 5981), False, 'import torch\n'), ((6198, 6264), 'utils.decoders.ctc_greedy_decode', 'ctc_greedy_decode', (['outputBatch', 'inputLenBatch', "evalParams['eosIx']"], {}), "(outputBatch, inputLenBatch, evalParams['eosIx'])\n", (6215, 6264), False, 'from utils.decoders import ctc_greedy_decode, ctc_search_decode\n'), ((12190, 12201), 'config_modified.args.copy', 'args.copy', ([], {}), '()\n', (12199, 12201), False, 'from config_modified import args\n'), ((12568, 12592), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (12590, 12592), False, 'import torch\n'), ((12605, 12617), 'gc.collect', 'gc.collect', ([], {}), '()\n', (12615, 12617), False, 'import gc\n'), ((6504, 6648), 'utils.decoders.ctc_search_decode', 'ctc_search_decode', (['outputBatch', 'inputLenBatch', "evalParams['beamSearchParams']", "evalParams['spaceIx']", "evalParams['eosIx']", "evalParams['lm']"], {}), "(outputBatch, inputLenBatch, evalParams['beamSearchParams'\n ], evalParams['spaceIx'], evalParams['eosIx'], evalParams['lm'])\n", (6521, 6648), False, 'from utils.decoders import ctc_greedy_decode, ctc_search_decode\n')]
|
from __future__ import print_function, division
import os
import torch
import pandas as pd
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from src.data.baseline_transformers import TransformsWrapper
from tqdm import tqdm
# Ignore warnings
import warnings
import torchvision as tv
import pickle
class FinalRNNMCSDataset(Dataset):
def __init__(
self,
test_df: str,
test_df_track_order_df,
test_descriptors_df,
root_dir,
transform=None
):
""" Plan
1. for each track presented form 1 triplet with each of gt images vs one random negative track
and lets work with indices only
"""
self.test_df = pd.read_csv(test_df)
self.test_df_track_order_df = pd.read_csv(test_df_track_order_df)
self.test_descriptors_npy = np.load(test_descriptors_df)
self.samples = list()
# 1 triplet sample for one person
# this takes 10 minutes every run
print('Generating dataset for evaluation')
for track_id in tqdm(self.test_df_track_order_df.track_id.values, total=len(self.test_df_track_order_df)):
track_image_idxs = self.test_df[self.test_df.track_id == track_id].index.values
self.samples.append((track_image_idxs))
self.root_dir = root_dir
self.transform = transform
print(f"Triplets count for final eval is {len(self.samples)}")
# Was Triplets count for train was 57570 when only one negative sample was used
# now it s 1151400 (20 times more)
# with open('train_samples.pkl', 'wb') as outf:
# pickle.dump(self.samples, outf)
def __len__(self):
return len(self.samples)
def __getitem__(self, idx):
pos_images_idxs = self.samples[idx]
# todo: maybe add some scaling on all given descriptors
pos_seq = self.test_descriptors_npy[pos_images_idxs]
pos_seq = [torch.from_numpy(pos_img) for pos_img in pos_seq]
pos_seq = torch.stack(pos_seq, dim=0, out=None)
sample = {'img_seq': pos_seq}
return sample
class RNNMCSDataset(Dataset):
def __init__(
self,
train_df: str,
train_df_descriptors,
train_gt_df,
train_gt_descriptors,
train_df_track_order_df,
root_dir,
is_val=False,
transform=None
):
""" Plan
1. for each track presented form 1 triplet with each of gt images vs one random negative track
and lets work with indices only
"""
self.train_df = pd.read_csv(train_df)
self.train_df_descriptors = np.load(train_df_descriptors)
self.train_gt_df = pd.read_csv(train_gt_df)
self.train_gt_descriptors = np.load(train_gt_descriptors)
self.train_df_track_order_df = pd.read_csv(train_df_track_order_df)
self.train_df_track_order_df = pd.merge(self.train_df_track_order_df,
self.train_df[['person_id', 'is_val']].drop_duplicates(),
on='person_id',
how='left') # [is_val == False]
self.train_df_track_order_df = self.train_df_track_order_df[self.train_df_track_order_df.is_val == is_val]
self.samples = list()
# 1 triplet sample for one person
# this takes 10 minutes every run
if is_val:
n_neg_samples = 1
print(f"Generating samples for {'dev' if is_val else 'train'}")
for id, (track_id, person_id) in tqdm(self.train_df_track_order_df[['track_id', 'person_id']].iterrows(), total=len(self.train_df_track_order_df)):
not_this_person_order_df = self.train_df_track_order_df[self.train_df_track_order_df.person_id != person_id]
track_image_idxs = self.train_df[self.train_df.track_id == track_id].index.values
track_anchors_df = self.train_gt_df[self.train_gt_df.person_id == person_id]
for anchor_idx in track_anchors_df.index.values:
for not_this_person_sampled_track_id in tqdm(not_this_person_order_df.sample(n_neg_samples).track_id.values):
not_this_person_sampled_track_image_idxs = self.train_df[
self.train_df.track_id == not_this_person_sampled_track_id].index.values
self.samples.append((anchor_idx, track_image_idxs, not_this_person_sampled_track_image_idxs))
# if id > 10:
# break
else:
with open('train_samples.pkl', 'rb') as inf:
self.samples = pickle.loads(inf.read())
self.root_dir = root_dir
self.transform = transform
print(f"Triplets count for {'dev' if is_val else 'train'} is {len(self.samples)}")
# Was Triplets count for train was 57570 when only one negative sample was used
# now it s 1151400 (20 times more)
# with open('train_samples.pkl', 'wb') as outf:
# pickle.dump(self.samples, outf)
def __len__(self):
return len(self.samples)
def __getitem__(self, idx):
gt_image_idx, pos_images_idxs, neg_images_idxs = self.samples[idx]
# todo: maybe add some scaling on all given descriptors
gt_descriptor = self.train_gt_descriptors[gt_image_idx]
pos_seq = self.train_df_descriptors[pos_images_idxs]
neg_seq = self.train_df_descriptors[neg_images_idxs]
gt_descriptor = torch.from_numpy(gt_descriptor)
pos_seq = [torch.from_numpy(pos_img) for pos_img in pos_seq]
neg_seq = [torch.from_numpy(neg_img) for neg_img in neg_seq]
pos_seq = torch.stack(pos_seq, dim=0, out=None)
neg_seq = torch.stack(neg_seq, dim=0, out=None)
sample = {'gt_image': gt_descriptor,
'pos_seq': pos_seq,
'neg_seq': neg_seq}
return sample
class FakeRNNMCSDataset(Dataset):
def __init__(
self,
train_df: str,
train_df_descriptors,
train_gt_df,
train_gt_descriptors,
train_df_track_order_df,
root_dir,
is_val=False,
transform=None
):
seq_len = 5
self.samples = [[np.random.randn(512).astype(np.float32),
[np.random.randn(512).astype(np.float32) for i in range(seq_len)],
[np.random.randn(512).astype(np.float32) for i in range(seq_len)]]
for _ in range(100)]
# self.transform = transform
# self.tw = TransformsWrapper(transform)
def __len__(self):
return len(self.samples)
def __getitem__(self, idx):
track_image, pos_seq, neg_seq = self.samples[idx]
# track_image = self.transform(track_image)
track_image = torch.from_numpy(track_image)
pos_seq = [torch.from_numpy(pos_img) for pos_img in pos_seq]
neg_seq = [torch.from_numpy(neg_img) for neg_img in neg_seq]
pos_seq = torch.stack(pos_seq, dim=0, out=None)
neg_seq = torch.stack(neg_seq, dim=0, out=None)
sample = {'gt_image': track_image, 'pos_seq': pos_seq, 'neg_seq': neg_seq}
return sample
# we are going to do train dataset and test dataset separately
def check_data_iteration(iterate_data=False):
is_val = False
# U may use MCSDataset for the training
MEAN = [0.485, 0.456, 0.406]
STD = [0.229, 0.224, 0.225]
preprocessing = tv.transforms.Compose([
tv.transforms.ToPILImage(),
tv.transforms.ToTensor(),
tv.transforms.Normalize(mean=MEAN, std=STD),
])
dataset = RNNMCSDataset(
train_df="../../data/raw/train_df.csv",
train_df_descriptors="../../data/raw/train_df_descriptors.npy",
train_gt_df="../../data/raw/train_gt_df.csv",
train_gt_descriptors="../../data/raw/train_gt_descriptors.npy",
train_df_track_order_df="../../data/raw/train_df_track_order_df.csv",
root_dir='../../data/raw/data',
is_val=False,
transform=None
)
print(f"Total triples in {'test' if is_val else 'train'} dataset is {len(dataset)}")
if iterate_data:
for i in range(len(dataset)):
sample = dataset[i]
# print(sample['track_image'])
print(i, sample['gt_image'].size(), sample['pos_seq'].size(), sample['neg_seq'].size())
# if i == 3:
# break
if __name__ == '__main__':
# example usage
# python -i read_dataset.py check_data_iteration
check_data_iteration(iterate_data=True)
|
[
"numpy.load",
"torch.stack",
"numpy.random.randn",
"pandas.read_csv",
"torchvision.transforms.ToPILImage",
"torchvision.transforms.ToTensor",
"torchvision.transforms.Normalize",
"torch.from_numpy"
] |
[((851, 871), 'pandas.read_csv', 'pd.read_csv', (['test_df'], {}), '(test_df)\n', (862, 871), True, 'import pandas as pd\n'), ((910, 945), 'pandas.read_csv', 'pd.read_csv', (['test_df_track_order_df'], {}), '(test_df_track_order_df)\n', (921, 945), True, 'import pandas as pd\n'), ((982, 1010), 'numpy.load', 'np.load', (['test_descriptors_df'], {}), '(test_descriptors_df)\n', (989, 1010), True, 'import numpy as np\n'), ((2156, 2193), 'torch.stack', 'torch.stack', (['pos_seq'], {'dim': '(0)', 'out': 'None'}), '(pos_seq, dim=0, out=None)\n', (2167, 2193), False, 'import torch\n'), ((2767, 2788), 'pandas.read_csv', 'pd.read_csv', (['train_df'], {}), '(train_df)\n', (2778, 2788), True, 'import pandas as pd\n'), ((2825, 2854), 'numpy.load', 'np.load', (['train_df_descriptors'], {}), '(train_df_descriptors)\n', (2832, 2854), True, 'import numpy as np\n'), ((2882, 2906), 'pandas.read_csv', 'pd.read_csv', (['train_gt_df'], {}), '(train_gt_df)\n', (2893, 2906), True, 'import pandas as pd\n'), ((2943, 2972), 'numpy.load', 'np.load', (['train_gt_descriptors'], {}), '(train_gt_descriptors)\n', (2950, 2972), True, 'import numpy as np\n'), ((3012, 3048), 'pandas.read_csv', 'pd.read_csv', (['train_df_track_order_df'], {}), '(train_df_track_order_df)\n', (3023, 3048), True, 'import pandas as pd\n'), ((5727, 5758), 'torch.from_numpy', 'torch.from_numpy', (['gt_descriptor'], {}), '(gt_descriptor)\n', (5743, 5758), False, 'import torch\n'), ((5917, 5954), 'torch.stack', 'torch.stack', (['pos_seq'], {'dim': '(0)', 'out': 'None'}), '(pos_seq, dim=0, out=None)\n', (5928, 5954), False, 'import torch\n'), ((5973, 6010), 'torch.stack', 'torch.stack', (['neg_seq'], {'dim': '(0)', 'out': 'None'}), '(neg_seq, dim=0, out=None)\n', (5984, 6010), False, 'import torch\n'), ((7092, 7121), 'torch.from_numpy', 'torch.from_numpy', (['track_image'], {}), '(track_image)\n', (7108, 7121), False, 'import torch\n'), ((7279, 7316), 'torch.stack', 'torch.stack', (['pos_seq'], {'dim': '(0)', 'out': 'None'}), '(pos_seq, dim=0, out=None)\n', (7290, 7316), False, 'import torch\n'), ((7335, 7372), 'torch.stack', 'torch.stack', (['neg_seq'], {'dim': '(0)', 'out': 'None'}), '(neg_seq, dim=0, out=None)\n', (7346, 7372), False, 'import torch\n'), ((2087, 2112), 'torch.from_numpy', 'torch.from_numpy', (['pos_img'], {}), '(pos_img)\n', (2103, 2112), False, 'import torch\n'), ((5779, 5804), 'torch.from_numpy', 'torch.from_numpy', (['pos_img'], {}), '(pos_img)\n', (5795, 5804), False, 'import torch\n'), ((5848, 5873), 'torch.from_numpy', 'torch.from_numpy', (['neg_img'], {}), '(neg_img)\n', (5864, 5873), False, 'import torch\n'), ((7141, 7166), 'torch.from_numpy', 'torch.from_numpy', (['pos_img'], {}), '(pos_img)\n', (7157, 7166), False, 'import torch\n'), ((7210, 7235), 'torch.from_numpy', 'torch.from_numpy', (['neg_img'], {}), '(neg_img)\n', (7226, 7235), False, 'import torch\n'), ((7772, 7798), 'torchvision.transforms.ToPILImage', 'tv.transforms.ToPILImage', ([], {}), '()\n', (7796, 7798), True, 'import torchvision as tv\n'), ((7808, 7832), 'torchvision.transforms.ToTensor', 'tv.transforms.ToTensor', ([], {}), '()\n', (7830, 7832), True, 'import torchvision as tv\n'), ((7842, 7885), 'torchvision.transforms.Normalize', 'tv.transforms.Normalize', ([], {'mean': 'MEAN', 'std': 'STD'}), '(mean=MEAN, std=STD)\n', (7865, 7885), True, 'import torchvision as tv\n'), ((6513, 6533), 'numpy.random.randn', 'np.random.randn', (['(512)'], {}), '(512)\n', (6528, 6533), True, 'import numpy as np\n'), ((6580, 6600), 'numpy.random.randn', 'np.random.randn', (['(512)'], {}), '(512)\n', (6595, 6600), True, 'import numpy as np\n'), ((6672, 6692), 'numpy.random.randn', 'np.random.randn', (['(512)'], {}), '(512)\n', (6687, 6692), True, 'import numpy as np\n')]
|
"""
Name: <NAME>
Class: K63K2
MSSV: 18020116
You should understand the code you write.
"""
import numpy as np
import cv2
import argparse
from matplotlib import pyplot as plt
def q_0(input_file, output_file, ):
img = cv2.imread(input_file, cv2.IMREAD_COLOR)
cv2.imshow('Test img', img)
cv2.waitKey(5000)
cv2.imwrite(output_file, img)
def q_1(input_file, output_file):
"""
Convert the image to gray channel of the input image.
"""
img = cv2.imread(input_file, cv2.IMREAD_COLOR)
cv2.imshow('Color', img)
R, G, B = img[:, :, 2], img[:, :, 1], img[:, :, 0]
# Convert image to gray channgel
gray = 0.299 * R + 0.587 * G + 0.114 * B
img_gray = gray.astype(np.uint8)
cv2.imwrite(output_file, img_gray)
cv2.imshow('Gray', img_gray)
cv2.waitKey(0)
# Normalized histogram
def normallizedHistogram(img):
(height, width) = img.shape[:2]
# uint64 works while uint8 doesn't???
# h = np.zeros((256, ), np.uint8) //Wrong?
# h= np.zeros((256,), dtype=int) //Right??
h = [0] * 256
for i in range(height):
for j in range(width):
h[img[i, j]] += 1
return np.array(h) / (height * width)
# Finds cumulative sum of a numpy array, list
def cummulativeSum(normalized_hist):
cummulative_sum = np.zeros_like(normalized_hist, np.float64)
hist_length = len(normalized_hist)
for i in range(hist_length):
cummulative_sum[i] = sum(normalized_hist[:i+1])
return cummulative_sum
def q_2(input_file, output_file):
"""
Performs a histogram equalization on the input image.
"""
img = cv2.imread(input_file, cv2.IMREAD_GRAYSCALE)
(height, width) = img.shape[:2]
# Analysing original image and original histogram
# original_hist = cv2.calcHist([img], [0], None, [256], [0, 256]) # Mask: None, value from 0 - 255
# plt.figure()
# plt.axis("off")
# plt.imshow(img, cmap='gray')
# plt.figure()
# plt.title('Histogram')
# plt.xlabel('Bins')
# plt.ylabel('Number of pixel')
# plt.plot(original_hist)
# plt.xlim([0, 256])
# plt.show()
# Histogram equalization
norm_hist = normallizedHistogram(img)
cumulative_sum = cummulativeSum(norm_hist)
new_hist = np.array(np.rint(255 * cumulative_sum))
# Convert image
img_eq = np.zeros_like(img)
for i in range(height):
for j in range(width):
img_eq[i, j] = new_hist[img[i, j]]
# Check
hist_test = cv2.calcHist([img_eq], [0], None, [256], [0, 256]) # Mask: None, value from 0 - 255
plt.figure()
plt.axis("off")
plt.imshow(img_eq, cmap='gray')
plt.figure()
plt.title('Histogram')
plt.xlabel('Bins')
plt.ylabel('Number of pixel')
plt.plot(hist_test)
plt.xlim([0, 256])
plt.show()
cv2.imwrite(output_file, img_eq)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--input_file", "-i", type=str, help="Path to input image")
parser.add_argument("--output_file", "-o", type=str, help="Path to output image")
parser.add_argument("--question", "-q", type=int, default=0, help="Question number")
args = parser.parse_args()
q_number = args.question
if q_number == 1:
q_1(input_file=args.input_file, output_file=args.output_file)
elif q_number == 2:
q_2(input_file=args.input_file, output_file=args.output_file)
else:
q_0(input_file=args.input_file, output_file=args.output_file)
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"numpy.zeros_like",
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"matplotlib.pyplot.plot",
"cv2.waitKey",
"cv2.imwrite",
"cv2.calcHist",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.axis",
"cv2.imread",
"matplotlib.pyplot.figure",
"numpy.rint",
"numpy.array",
"matplotlib.pyplot.ylabel",
"cv2.imshow",
"matplotlib.pyplot.xlabel"
] |
[((224, 264), 'cv2.imread', 'cv2.imread', (['input_file', 'cv2.IMREAD_COLOR'], {}), '(input_file, cv2.IMREAD_COLOR)\n', (234, 264), False, 'import cv2\n'), ((269, 296), 'cv2.imshow', 'cv2.imshow', (['"""Test img"""', 'img'], {}), "('Test img', img)\n", (279, 296), False, 'import cv2\n'), ((301, 318), 'cv2.waitKey', 'cv2.waitKey', (['(5000)'], {}), '(5000)\n', (312, 318), False, 'import cv2\n'), ((324, 353), 'cv2.imwrite', 'cv2.imwrite', (['output_file', 'img'], {}), '(output_file, img)\n', (335, 353), False, 'import cv2\n'), ((474, 514), 'cv2.imread', 'cv2.imread', (['input_file', 'cv2.IMREAD_COLOR'], {}), '(input_file, cv2.IMREAD_COLOR)\n', (484, 514), False, 'import cv2\n'), ((519, 543), 'cv2.imshow', 'cv2.imshow', (['"""Color"""', 'img'], {}), "('Color', img)\n", (529, 543), False, 'import cv2\n'), ((728, 762), 'cv2.imwrite', 'cv2.imwrite', (['output_file', 'img_gray'], {}), '(output_file, img_gray)\n', (739, 762), False, 'import cv2\n'), ((767, 795), 'cv2.imshow', 'cv2.imshow', (['"""Gray"""', 'img_gray'], {}), "('Gray', img_gray)\n", (777, 795), False, 'import cv2\n'), ((800, 814), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (811, 814), False, 'import cv2\n'), ((1327, 1369), 'numpy.zeros_like', 'np.zeros_like', (['normalized_hist', 'np.float64'], {}), '(normalized_hist, np.float64)\n', (1340, 1369), True, 'import numpy as np\n'), ((1644, 1688), 'cv2.imread', 'cv2.imread', (['input_file', 'cv2.IMREAD_GRAYSCALE'], {}), '(input_file, cv2.IMREAD_GRAYSCALE)\n', (1654, 1688), False, 'import cv2\n'), ((2372, 2390), 'numpy.zeros_like', 'np.zeros_like', (['img'], {}), '(img)\n', (2385, 2390), True, 'import numpy as np\n'), ((2551, 2601), 'cv2.calcHist', 'cv2.calcHist', (['[img_eq]', '[0]', 'None', '[256]', '[0, 256]'], {}), '([img_eq], [0], None, [256], [0, 256])\n', (2563, 2601), False, 'import cv2\n'), ((2647, 2659), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2657, 2659), True, 'from matplotlib import pyplot as plt\n'), ((2664, 2679), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2672, 2679), True, 'from matplotlib import pyplot as plt\n'), ((2684, 2715), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img_eq'], {'cmap': '"""gray"""'}), "(img_eq, cmap='gray')\n", (2694, 2715), True, 'from matplotlib import pyplot as plt\n'), ((2720, 2732), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2730, 2732), True, 'from matplotlib import pyplot as plt\n'), ((2737, 2759), 'matplotlib.pyplot.title', 'plt.title', (['"""Histogram"""'], {}), "('Histogram')\n", (2746, 2759), True, 'from matplotlib import pyplot as plt\n'), ((2764, 2782), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Bins"""'], {}), "('Bins')\n", (2774, 2782), True, 'from matplotlib import pyplot as plt\n'), ((2787, 2816), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of pixel"""'], {}), "('Number of pixel')\n", (2797, 2816), True, 'from matplotlib import pyplot as plt\n'), ((2821, 2840), 'matplotlib.pyplot.plot', 'plt.plot', (['hist_test'], {}), '(hist_test)\n', (2829, 2840), True, 'from matplotlib import pyplot as plt\n'), ((2845, 2863), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, 256]'], {}), '([0, 256])\n', (2853, 2863), True, 'from matplotlib import pyplot as plt\n'), ((2868, 2878), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2876, 2878), True, 'from matplotlib import pyplot as plt\n'), ((2884, 2916), 'cv2.imwrite', 'cv2.imwrite', (['output_file', 'img_eq'], {}), '(output_file, img_eq)\n', (2895, 2916), False, 'import cv2\n'), ((2959, 2984), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2982, 2984), False, 'import argparse\n'), ((1177, 1188), 'numpy.array', 'np.array', (['h'], {}), '(h)\n', (1185, 1188), True, 'import numpy as np\n'), ((2302, 2331), 'numpy.rint', 'np.rint', (['(255 * cumulative_sum)'], {}), '(255 * cumulative_sum)\n', (2309, 2331), True, 'import numpy as np\n')]
|
"""
echopype data model inherited from based class Process for EK80 data.
"""
import os
import datetime as dt
import numpy as np
import xarray as xr
from scipy import signal
from ..utils import uwa
from .processbase import ProcessBase
class ProcessEK80(ProcessBase):
"""Class for manipulating EK80 echo data already converted to netCDF.
"""
def __init__(self, file_path=""):
ProcessBase.__init__(self, file_path)
self._acidity = None
self._salinity = None
self._temperature = None
self._pressure = None
self._ch_ids = None
self._tau_effective = None
self.ytx = []
self.backscatter_compressed = []
self._sound_speed = self.calc_sound_speed()
self._salinity = self.get_salinity()
self._temperature = self.get_temperature()
self._pressure = self.get_pressure()
self._sample_thickness = self.calc_sample_thickness()
self._seawater_absorption = self.calc_seawater_absorption()
self._range = self.calc_range()
@property
def ch_ids(self):
if self._ch_ids is None:
with self._open_dataset(self.file_path, group="Beam") as ds_beam:
self._ch_ids = ds_beam.channel_id.data
return self._ch_ids
@property
def tau_effective(self):
return self._tau_effective
def get_salinity(self):
if self._salinity is None:
with self._open_dataset(self.file_path, group="Environment") as ds_env:
return ds_env.salinity
def get_temperature(self, path=''):
path = path if path else self.file_path
if self._temperature is None:
with self._open_dataset(path, group="Environment") as ds_env:
return ds_env.temperature
def get_pressure(self):
if self._pressure is None:
with self._open_dataset(self.file_path, group="Environment") as ds_env:
return ds_env.depth
def calc_sound_speed(self, src='file'):
"""gets sound speed [m/s] using parameters stored in the .nc file.
Will use a custom path if one is provided
"""
if src == 'file':
with self._open_dataset(self.file_path, group="Environment") as ds_env:
return ds_env.sound_speed_indicative
elif src == 'user':
ss = uwa.calc_sound_speed(salinity=self.salinity,
temperature=self.temperature,
pressure=self.pressure)
return ss * np.ones(self.sound_speed.size)
else:
ValueError('Not sure how to update sound speed!')
def calc_seawater_absorption(self, src='user', path=''):
"""Returns the seawater absorption
Parameters
----------
src : str
'file' will return the seawater absoption recorded in the .nc file
'user' will calculate the seawater absorption. Default (Francois and Garrison, 1982).
Returns
-------
Seawater absorption value
"""
if src == 'user':
path = path if path else self.file_path
with self._open_dataset(path, group='Beam') as ds_beam:
try:
f0 = ds_beam.frequency_start
f1 = ds_beam.frequency_end
f = (f0 + f1) / 2
except AttributeError:
f = ds_beam.frequency
sea_abs = uwa.calc_seawater_absorption(f,
salinity=self.salinity,
temperature=self.temperature,
pressure=self.pressure,
formula_source='FG')
else:
ValueError('Not sure how to update seawater absorption!')
return sea_abs
def calc_sample_thickness(self, path=''):
"""gets sample thickness using parameters stored in the .nc file.
Will use a custom path if one is provided
"""
path = path if path else self.file_path
with self._open_dataset(path, group="Beam") as ds_beam:
sth = self.sound_speed * ds_beam.sample_interval / 2 # sample thickness
return sth
def calc_range(self, range_bins=None, path=''):
"""Calculates range [m] using parameters stored in the .nc file.
Will use a custom path if one is provided
"""
st = self.calc_sample_thickness(path) if path else self.sample_thickness
path = path if path else self.file_path
with self._open_dataset(path, group="Beam") as ds_beam:
if range_bins:
range_bin = np.arange(range_bins)
range_bin = xr.DataArray(range_bin, coords=[('range_bin', range_bin)])
else:
range_bin = ds_beam.range_bin
range_meter = range_bin * st - \
ds_beam.transmit_duration_nominal * self.sound_speed / 2 # DataArray [frequency x range_bin]
range_meter = range_meter.where(range_meter > 0, other=0).transpose()
return range_meter
def calc_transmit_signal(self):
"""Generate transmit signal as replica for pulse compression.
"""
def chirp_linear(t, f0, f1, tau):
beta = (f1 - f0) * (tau ** -1)
return np.cos(2 * np.pi * (beta / 2 * (t ** 2) + f0 * t))
# Retrieve filter coefficients
with self._open_dataset(self.file_path, group="Vendor") as ds_fil, \
self._open_dataset(self.file_path, group="Beam") as ds_beam:
# Get various parameters
Ztrd = 75 # Transducer quadrant nominal impedance [Ohms] (Supplied by Simrad)
delta = 1 / 1.5e6 # Hard-coded EK80 sample interval
tau = ds_beam.transmit_duration_nominal.data
txpower = ds_beam.transmit_power.data
f0 = ds_beam.frequency_start.data
f1 = ds_beam.frequency_end.data
slope = ds_beam.slope[:, 0].data # Use slope of first ping
amp = np.sqrt((txpower / 4) * (2 * Ztrd))
# Create transmit signal
ytx = []
for ch in range(ds_beam.frequency.size):
t = np.arange(0, tau[ch], delta)
nt = len(t)
nwtx = (int(2 * np.floor(slope[ch] * nt)))
wtx_tmp = np.hanning(nwtx)
nwtxh = (int(np.round(nwtx / 2)))
wtx = np.concatenate([wtx_tmp[0:nwtxh], np.ones((nt - nwtx)), wtx_tmp[nwtxh:]])
y_tmp = amp[ch] * chirp_linear(t, f0[ch], f1[ch], tau[ch]) * wtx
# The transmit signal must have a max amplitude of 1
y = (y_tmp / np.max(np.abs(y_tmp)))
# filter and decimation
wbt_fil = ds_fil[self.ch_ids[ch] + "_WBT_filter"].data
pc_fil = ds_fil[self.ch_ids[ch] + "_PC_filter"].data
# if saved as netCDF4, convert compound complex datatype to complex64
if wbt_fil.ndim == 1:
wbt_fil = np.array([complex(n[0], n[1]) for n in wbt_fil], dtype='complex64')
pc_fil = np.array([complex(n[0], n[1]) for n in pc_fil], dtype='complex64')
# Apply WBT filter and downsample
ytx_tmp = np.convolve(y, wbt_fil)
ytx_tmp = ytx_tmp[0::ds_fil.attrs[self.ch_ids[ch] + "_WBT_decimation"]]
# Apply PC filter and downsample
ytx_tmp = np.convolve(ytx_tmp, pc_fil)
ytx_tmp = ytx_tmp[0::ds_fil.attrs[self.ch_ids[ch] + "_PC_decimation"]]
ytx.append(ytx_tmp)
del nwtx, wtx_tmp, nwtxh, wtx, y_tmp, y, ytx_tmp
# TODO: rename ytx into something like 'transmit_signal' and
# also package the sampling interval together with the signal
self.ytx = ytx
def pulse_compression(self):
"""Pulse compression using transmit signal as replica.
"""
with self._open_dataset(self.file_path, group="Beam") as ds_beam:
sample_interval = ds_beam.sample_interval
backscatter = ds_beam.backscatter_r + ds_beam.backscatter_i * 1j # Construct complex backscatter
backscatter_compressed = []
tau_constants = []
# Loop over channels
for ch in range(ds_beam.frequency.size):
# tmp_x = np.fft.fft(backscatter[i].dropna('range_bin'))
# tmp_y = np.fft.fft(np.flipud(np.conj(ytx[i])))
# remove quadrants that are nans across all samples
tmp_b = backscatter[ch].dropna('range_bin', how='all')
# remove samples that are nans across all quadrants
tmp_b = tmp_b.dropna('quadrant', how='all')
# tmp_b = tmp_b[:, 0, :] # 1 ping
tmp_y = np.flipud(np.conj(self.ytx[ch]))
# Convolve tx signal with backscatter. atol=1e-7 between fft and direct convolution
compressed = xr.apply_ufunc(lambda m: np.apply_along_axis(
lambda m: signal.convolve(m, tmp_y), axis=2, arr=m),
tmp_b,
input_core_dims=[['range_bin']],
output_core_dims=[['range_bin']],
exclude_dims={'range_bin'}) / np.linalg.norm(self.ytx[ch]) ** 2
# Average across quadrants
backscatter_compressed.append(compressed)
# Effective pulse length
ptxa = np.square(np.abs(signal.convolve(self.ytx[ch], tmp_y, method='direct') /
np.linalg.norm(self.ytx[ch]) ** 2))
tau_constants.append(np.sum(ptxa) / (np.max(ptxa)))
self._tau_effective = np.array(tau_constants) * sample_interval
# Pad nans so that each channel has the same range_bin length
largest_range_bin = max([bc.shape[2] for bc in backscatter_compressed])
for i, ds in enumerate(backscatter_compressed):
pad_width = largest_range_bin - ds.shape[2]
backscatter_compressed[i] = xr.apply_ufunc(lambda x: np.pad(x, ((0,0), (0,0), (0,pad_width)),
constant_values=np.nan),
ds,
input_core_dims=[['range_bin']],
output_core_dims=[['range_bin']],
exclude_dims={'range_bin'})
self.backscatter_compressed = xr.concat(backscatter_compressed, dim='frequency')
def calibrate(self, mode='Sv', save=False, save_path=None, save_postfix=None):
"""Perform echo-integration to get volume backscattering strength (Sv)
or target strength (TS) from EK80 power data.
Parameters
-----------
mode : str
'Sv' for volume backscattering strength calibration (default)
'TS' for target strength calibration
save : bool, optional
whether to save calibrated output
default to ``False``
save_path : str
Full filename to save to, overwriting the RAWFILENAME_Sv.nc default
save_postfix : str
Filename postfix, default to '_Sv' or '_TS'
"""
ds_beam = self._open_dataset(self.file_path, group="Beam")
# Check for cw data file
split = os.path.splitext(self.file_path)
cw_path = split[0] + '_cw' + split[1]
if save_postfix is None:
save_postfix = '_' + mode
if os.path.exists(cw_path):
self.calibrate_cw(mode, cw_path, save, save_path, save_postfix)
elif 'backscatter_i' not in ds_beam:
self.calibrate_cw(mode, self.file_path, save, save_path, save_postfix)
# Calibrate bb data
if 'backscatter_i' in ds_beam:
Ztrd = 75 # Transducer quadrant nominal impedance [Ohms] (Supplied by Simrad)
Rwbtrx = 1000 # Wideband transceiver impedance [Ohms] (Supplied by Simrad)
self.calc_transmit_signal() # Get transmit signal
self.pulse_compression() # Perform pulse compression
c = self.sound_speed
f_nominal = ds_beam.frequency
f_center = (ds_beam.frequency_start.data + ds_beam.frequency_end.data) / 2
psifc = ds_beam.equivalent_beam_angle + 20 * np.log10(f_nominal / f_center)
la2 = (c / f_center) ** 2
Sv = []
TS = []
# Average accross quadrants and take the absolute value of complex backscatter
prx = np.abs(np.mean(self.backscatter_compressed, axis=1))
prx = prx * prx / 2 * (np.abs(Rwbtrx + Ztrd) / Rwbtrx) ** 2 / np.abs(Ztrd)
# TODO Gfc should be gain interpolated at the center frequency
# Only 1 gain value is given provided per channel
Gfc = ds_beam.gain_correction
ranges = self.calc_range(range_bins=prx.shape[2])
ranges = ranges.where(ranges >= 1, other=1)
if mode == 'Sv':
Sv = (
10 * np.log10(prx) + 20 * np.log10(ranges) +
2 * self.seawater_absorption * ranges -
10 * np.log10(ds_beam.transmit_power * la2 * c / (32 * np.pi * np.pi)) -
2 * Gfc - 10 * np.log10(self.tau_effective) - psifc
)
if mode == 'TS':
TS = (
10 * np.log10(prx) + 40 * np.log10(ranges) +
2 * self.seawater_absorption * ranges -
10 * np.log10(ds_beam.transmit_power * la2 / (16 * np.pi * np.pi)) -
2 * Gfc
)
ds_beam.close() # Close opened dataset
# Save Sv calibrated data
if mode == 'Sv':
Sv.name = 'Sv'
Sv = Sv.to_dataset()
Sv['range'] = (('frequency', 'range_bin'), ranges)
self.Sv = Sv
if save:
self.Sv_path = self.validate_path(save_path, save_postfix)
print('%s saving calibrated Sv to %s' % (dt.datetime.now().strftime('%H:%M:%S'), self.Sv_path))
self._save_dataset(Sv, self.Sv_path, mode="w")
# Save TS calibrated data
elif mode == 'TS':
TS.name = 'TS'
TS = TS.to_dataset()
TS['range'] = (('frequency', 'range_bin'), ranges)
self.TS = TS
if save:
self.TS_path = self.validate_path(save_path, save_postfix)
print('%s saving calibrated TS to %s' % (dt.datetime.now().strftime('%H:%M:%S'), self.TS_path))
self._save_dataset(self.TS, self.TS_path, mode="w")
def calibrate_TS(self, save=False, save_path=None, save_postfix=None):
self.calibrate(mode='TS', save=save, save_path=save_path, save_postfix=save_postfix)
def calibrate_cw(self, mode='Sv', file_path='', save=False, save_path=None, save_postfix=None):
"""Perform echo-integration to get volume backscattering strength (Sv) from EK80 power data.
Parameters
-----------
mode : str
'Sv' for volume backscattering strength (default)
'TS' for target strength
file_path : str
Path to CW data
save : bool, optional
whether to save calibrated Sv output
default to ``False``
save_path : str
Full filename to save to, overwriting the RAWFILENAME_Sv.nc default
save_postfix : str
Filename postfix
"""
# Open data set for and Beam groups
if file_path and os.path.exists(file_path):
ds_beam = self._open_dataset(file_path, group="Beam")
else:
file_path = self.file_path
ds_beam = self._open_dataset(self.file_path, group="Beam")
# Derived params
wavelength = self.sound_speed / ds_beam.frequency # wavelength
# Retrieved params
backscatter_r = ds_beam['backscatter_r'].load()
range_meter = self.calc_range(path=file_path)
sea_abs = self.calc_seawater_absorption(path=file_path)
if mode == 'Sv':
# Calc gain
CSv = 10 * np.log10((ds_beam.transmit_power * (10 ** (ds_beam.gain_correction / 10)) ** 2 *
wavelength ** 2 * self.sound_speed * ds_beam.transmit_duration_nominal *
10 ** (ds_beam.equivalent_beam_angle / 10)) /
(32 * np.pi ** 2))
# Get TVG and absorption
TVG = np.real(20 * np.log10(range_meter.where(range_meter >= 1, other=1)))
ABS = 2 * sea_abs * range_meter
# Calibration and echo integration
Sv = backscatter_r + TVG + ABS - CSv - 2 * ds_beam.sa_correction
Sv.name = 'Sv'
Sv = Sv.to_dataset()
# Attach calculated range into data set
Sv['range'] = (('frequency', 'range_bin'), range_meter)
# Save calibrated data into the calling instance and
# to a separate .nc file in the same directory as the data filef.Sv = Sv
self.Sv = Sv
if save:
if save_postfix is None:
save_postfix = '_' + mode
self.Sv_path = self.validate_path(save_path, save_postfix, file_path)
print('%s saving calibrated Sv to %s' % (dt.datetime.now().strftime('%H:%M:%S'), self.Sv_path))
self._save_dataset(Sv, self.Sv_path, mode="w")
elif mode == 'TS':
CSp = 10 * np.log10((ds_beam.transmit_power * (10 ** (ds_beam.gain_correction / 10)) ** 2 *
wavelength ** 2) / (16 * np.pi ** 2))
TVG = np.real(40 * np.log10(range_meter.where(range_meter >= 1, other=1)))
ABS = 2 * self.seawater_absorption * range_meter
# Calibration and echo integration
TS = backscatter_r + TVG + ABS - CSp
TS.name = 'TS'
TS = TS.to_dataset()
# Attach calculated range into data set
TS['range'] = (('frequency', 'range_bin'), range_meter)
# Save calibrated data into the calling instance and
# to a separate .nc file in the same directory as the data filef.Sv = Sv
self.TS = TS
if save:
self.TS_path = self.validate_path(save_path, save_postfix)
print('%s saving calibrated TS to %s' % (dt.datetime.now().strftime('%H:%M:%S'), self.TS_path))
self._save_dataset(TS, self.TS_path, mode="w")
# Close opened resources
ds_beam.close()
|
[
"numpy.abs",
"numpy.sum",
"numpy.floor",
"numpy.ones",
"numpy.mean",
"numpy.arange",
"numpy.linalg.norm",
"numpy.convolve",
"numpy.round",
"numpy.pad",
"os.path.exists",
"numpy.max",
"numpy.hanning",
"numpy.log10",
"datetime.datetime.now",
"numpy.conj",
"xarray.concat",
"numpy.cos",
"scipy.signal.convolve",
"numpy.array",
"os.path.splitext",
"xarray.DataArray",
"numpy.sqrt"
] |
[((11802, 11834), 'os.path.splitext', 'os.path.splitext', (['self.file_path'], {}), '(self.file_path)\n', (11818, 11834), False, 'import os\n'), ((11963, 11986), 'os.path.exists', 'os.path.exists', (['cw_path'], {}), '(cw_path)\n', (11977, 11986), False, 'import os\n'), ((5434, 5482), 'numpy.cos', 'np.cos', (['(2 * np.pi * (beta / 2 * t ** 2 + f0 * t))'], {}), '(2 * np.pi * (beta / 2 * t ** 2 + f0 * t))\n', (5440, 5482), True, 'import numpy as np\n'), ((6157, 6190), 'numpy.sqrt', 'np.sqrt', (['(txpower / 4 * (2 * Ztrd))'], {}), '(txpower / 4 * (2 * Ztrd))\n', (6164, 6190), True, 'import numpy as np\n'), ((10925, 10975), 'xarray.concat', 'xr.concat', (['backscatter_compressed'], {'dim': '"""frequency"""'}), "(backscatter_compressed, dim='frequency')\n", (10934, 10975), True, 'import xarray as xr\n'), ((16174, 16199), 'os.path.exists', 'os.path.exists', (['file_path'], {}), '(file_path)\n', (16188, 16199), False, 'import os\n'), ((4770, 4791), 'numpy.arange', 'np.arange', (['range_bins'], {}), '(range_bins)\n', (4779, 4791), True, 'import numpy as np\n'), ((4820, 4878), 'xarray.DataArray', 'xr.DataArray', (['range_bin'], {'coords': "[('range_bin', range_bin)]"}), "(range_bin, coords=[('range_bin', range_bin)])\n", (4832, 4878), True, 'import xarray as xr\n'), ((6325, 6353), 'numpy.arange', 'np.arange', (['(0)', 'tau[ch]', 'delta'], {}), '(0, tau[ch], delta)\n', (6334, 6353), True, 'import numpy as np\n'), ((6467, 6483), 'numpy.hanning', 'np.hanning', (['nwtx'], {}), '(nwtx)\n', (6477, 6483), True, 'import numpy as np\n'), ((7408, 7431), 'numpy.convolve', 'np.convolve', (['y', 'wbt_fil'], {}), '(y, wbt_fil)\n', (7419, 7431), True, 'import numpy as np\n'), ((7596, 7624), 'numpy.convolve', 'np.convolve', (['ytx_tmp', 'pc_fil'], {}), '(ytx_tmp, pc_fil)\n', (7607, 7624), True, 'import numpy as np\n'), ((10017, 10040), 'numpy.array', 'np.array', (['tau_constants'], {}), '(tau_constants)\n', (10025, 10040), True, 'import numpy as np\n'), ((13022, 13066), 'numpy.mean', 'np.mean', (['self.backscatter_compressed'], {'axis': '(1)'}), '(self.backscatter_compressed, axis=1)\n', (13029, 13066), True, 'import numpy as np\n'), ((13142, 13154), 'numpy.abs', 'np.abs', (['Ztrd'], {}), '(Ztrd)\n', (13148, 13154), True, 'import numpy as np\n'), ((16764, 16993), 'numpy.log10', 'np.log10', (['(ds_beam.transmit_power * (10 ** (ds_beam.gain_correction / 10)) ** 2 * \n wavelength ** 2 * self.sound_speed * ds_beam.transmit_duration_nominal *\n 10 ** (ds_beam.equivalent_beam_angle / 10) / (32 * np.pi ** 2))'], {}), '(ds_beam.transmit_power * (10 ** (ds_beam.gain_correction / 10)) **\n 2 * wavelength ** 2 * self.sound_speed * ds_beam.\n transmit_duration_nominal * 10 ** (ds_beam.equivalent_beam_angle / 10) /\n (32 * np.pi ** 2))\n', (16772, 16993), True, 'import numpy as np\n'), ((2560, 2590), 'numpy.ones', 'np.ones', (['self.sound_speed.size'], {}), '(self.sound_speed.size)\n', (2567, 2590), True, 'import numpy as np\n'), ((6513, 6531), 'numpy.round', 'np.round', (['(nwtx / 2)'], {}), '(nwtx / 2)\n', (6521, 6531), True, 'import numpy as np\n'), ((8990, 9011), 'numpy.conj', 'np.conj', (['self.ytx[ch]'], {}), '(self.ytx[ch])\n', (8997, 9011), True, 'import numpy as np\n'), ((12796, 12826), 'numpy.log10', 'np.log10', (['(f_nominal / f_center)'], {}), '(f_nominal / f_center)\n', (12804, 12826), True, 'import numpy as np\n'), ((18151, 18271), 'numpy.log10', 'np.log10', (['(ds_beam.transmit_power * (10 ** (ds_beam.gain_correction / 10)) ** 2 * \n wavelength ** 2 / (16 * np.pi ** 2))'], {}), '(ds_beam.transmit_power * (10 ** (ds_beam.gain_correction / 10)) **\n 2 * wavelength ** 2 / (16 * np.pi ** 2))\n', (18159, 18271), True, 'import numpy as np\n'), ((6414, 6438), 'numpy.floor', 'np.floor', (['(slope[ch] * nt)'], {}), '(slope[ch] * nt)\n', (6422, 6438), True, 'import numpy as np\n'), ((6590, 6608), 'numpy.ones', 'np.ones', (['(nt - nwtx)'], {}), '(nt - nwtx)\n', (6597, 6608), True, 'import numpy as np\n'), ((6816, 6829), 'numpy.abs', 'np.abs', (['y_tmp'], {}), '(y_tmp)\n', (6822, 6829), True, 'import numpy as np\n'), ((9566, 9594), 'numpy.linalg.norm', 'np.linalg.norm', (['self.ytx[ch]'], {}), '(self.ytx[ch])\n', (9580, 9594), True, 'import numpy as np\n'), ((9952, 9964), 'numpy.sum', 'np.sum', (['ptxa'], {}), '(ptxa)\n', (9958, 9964), True, 'import numpy as np\n'), ((9968, 9980), 'numpy.max', 'np.max', (['ptxa'], {}), '(ptxa)\n', (9974, 9980), True, 'import numpy as np\n'), ((10406, 10473), 'numpy.pad', 'np.pad', (['x', '((0, 0), (0, 0), (0, pad_width))'], {'constant_values': 'np.nan'}), '(x, ((0, 0), (0, 0), (0, pad_width)), constant_values=np.nan)\n', (10412, 10473), True, 'import numpy as np\n'), ((9783, 9836), 'scipy.signal.convolve', 'signal.convolve', (['self.ytx[ch]', 'tmp_y'], {'method': '"""direct"""'}), "(self.ytx[ch], tmp_y, method='direct')\n", (9798, 9836), False, 'from scipy import signal\n'), ((13103, 13124), 'numpy.abs', 'np.abs', (['(Rwbtrx + Ztrd)'], {}), '(Rwbtrx + Ztrd)\n', (13109, 13124), True, 'import numpy as np\n'), ((13765, 13793), 'numpy.log10', 'np.log10', (['self.tau_effective'], {}), '(self.tau_effective)\n', (13773, 13793), True, 'import numpy as np\n'), ((14028, 14089), 'numpy.log10', 'np.log10', (['(ds_beam.transmit_power * la2 / (16 * np.pi * np.pi))'], {}), '(ds_beam.transmit_power * la2 / (16 * np.pi * np.pi))\n', (14036, 14089), True, 'import numpy as np\n'), ((9879, 9907), 'numpy.linalg.norm', 'np.linalg.norm', (['self.ytx[ch]'], {}), '(self.ytx[ch])\n', (9893, 9907), True, 'import numpy as np\n'), ((9243, 9268), 'scipy.signal.convolve', 'signal.convolve', (['m', 'tmp_y'], {}), '(m, tmp_y)\n', (9258, 9268), False, 'from scipy import signal\n'), ((13660, 13725), 'numpy.log10', 'np.log10', (['(ds_beam.transmit_power * la2 * c / (32 * np.pi * np.pi))'], {}), '(ds_beam.transmit_power * la2 * c / (32 * np.pi * np.pi))\n', (13668, 13725), True, 'import numpy as np\n'), ((13899, 13912), 'numpy.log10', 'np.log10', (['prx'], {}), '(prx)\n', (13907, 13912), True, 'import numpy as np\n'), ((13920, 13936), 'numpy.log10', 'np.log10', (['ranges'], {}), '(ranges)\n', (13928, 13936), True, 'import numpy as np\n'), ((17983, 18000), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (17998, 18000), True, 'import datetime as dt\n'), ((14592, 14609), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (14607, 14609), True, 'import datetime as dt\n'), ((19059, 19076), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (19074, 19076), True, 'import datetime as dt\n'), ((13531, 13544), 'numpy.log10', 'np.log10', (['prx'], {}), '(prx)\n', (13539, 13544), True, 'import numpy as np\n'), ((13552, 13568), 'numpy.log10', 'np.log10', (['ranges'], {}), '(ranges)\n', (13560, 13568), True, 'import numpy as np\n'), ((15113, 15130), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (15128, 15130), True, 'import datetime as dt\n')]
|
"""
Run this script with -h for the help.
It produces for each method for a given dataset all the data needed to compare the methods on the specified dataset.
The strategies being compared are defined after line 88.
"""
from concurrent.futures import wait, ALL_COMPLETED
from concurrent.futures.process import ProcessPoolExecutor
import os
from typing import Callable, Dict, List, Optional, Tuple
import pandas as pd
import numpy as np
from pseas.instance_selection.instance_selection import InstanceSelection
from tqdm import tqdm
from pseas.test_env import ResetChoice, TestEnv
from pseas.strategy import Strategy
from pseas.standard_strategy import StandardStrategy
from pseas.discrimination.subset_baseline import SubsetBaseline
from pseas.discrimination.wilcoxon import Wilcoxon
from pseas.instance_selection.random_baseline import RandomBaseline
from pseas.instance_selection.discrimination_based import DiscriminationBased
from pseas.instance_selection.variance_based import VarianceBased
from pseas.instance_selection.information_based import InformationBased
from pseas.instance_selection.udd import UDD
# =============================================================================
# Argument parsing.
# =============================================================================
import argparse
argument_parser: argparse.ArgumentParser = argparse.ArgumentParser(
description="Produce run data.")
argument_default_values: Dict = {
"output_suffix": '',
"save_every": 5,
"max_workers": None,
"scenario_path": './rundata/kissat_ibm',
"nb_configurations": 10,
"ratio_instances": .1,
"nb_seeds": 10
}
argument_parser.add_argument('-o', '--output-suffix',
type=str,
action='store',
default=argument_default_values['output_suffix'],
help="CSV data filename suffix (default: '[scenario]_[nb configurations]_[ratio instance]')"
)
argument_parser.add_argument('--save-every',
type=int,
action='store',
default=argument_default_values['save_every'],
help="Save data every X time. (default: 5)"
)
argument_parser.add_argument('--max-workers',
type=int,
action='store',
default=argument_default_values['max_workers'],
help="Max number of processes. (default: None)"
)
argument_parser.add_argument('--scenario-path',
type=str,
action='store',
default=argument_default_values['scenario_path'],
help=" (default: './rundata/kissat_ibm')"
)
argument_parser.add_argument('--nb-configurations',
type=int,
action='store',
default=argument_default_values['nb_configurations'],
help=" (default: 10)"
)
argument_parser.add_argument('--nb-seeds',
type=int,
action='store',
default=argument_default_values['nb_seeds'],
help=" (default: 10)"
)
argument_parser.add_argument('--ratio-instances',
type=float,
action='store',
default=argument_default_values['ratio_instances'],
help=" (default: 1)"
)
argument_parser.add_argument('--disc',
action='store_true',
help=" (default: False) instaed of GridSearch for UDD do it for discrimination"
)
parsed_parameters = argument_parser.parse_args()
nb_seeds: int = parsed_parameters.nb_seeds
save_every: int = parsed_parameters.save_every
max_workers: int = parsed_parameters.max_workers
scenario_path: str = parsed_parameters.scenario_path
nb_configurations: int = parsed_parameters.nb_configurations
ratio_instances: float = parsed_parameters.ratio_instances
disc_instead_udd: bool = parsed_parameters.disc
name: str = "discrimination" if disc_instead_udd else "udd"
output_suffix: str = scenario_path.strip('/').split('/')[-1]+'_'+str(nb_configurations)+'_'+str(ratio_instances)+"_"+name
# =============================================================================
# Finished parsing
# =============================================================================
# =============================================================================
# Start Strategy Definition
# =============================================================================
discriminators = [
lambda: Wilcoxon(confidence=101),
]
selectors: List[Callable[[], InstanceSelection]] = []
if not disc_instead_udd:
parameters_1 = np.linspace(.2, 2, num=10).tolist()
parameters_2 = np.linspace(.2, 2, num=10).tolist()
selectors = [UDD(p1, p2) for p1 in parameters_1 for p2 in parameters_2]
else:
parameters = np.linspace(1.01, 2, num=10).tolist()
selectors = [DiscriminationBased(p) for p in parameters]
strategy_makers = [
lambda i, d: StandardStrategy(i, d),
]
# =============================================================================
# End Strategy Definition
# =============================================================================
# Check if file already exists
original_df_general: Optional[pd.DataFrame] = None
original_df_detailed: Optional[pd.DataFrame] = None
if os.path.exists(f"./runs_{output_suffix}.csv"):
original_df_general = pd.read_csv(f"./runs_{output_suffix}.csv")
original_df_general = original_df_general.drop("Unnamed: 0", axis=1)
original_df_detailed = pd.read_csv(
f"./detailed_runs_{output_suffix}.csv")
original_df_detailed = original_df_detailed.drop(
"Unnamed: 0", axis=1)
print("Found existing data, continuing acquisition from save.")
df_general = {
"y_true": [],
"y_pred": [],
"time": [],
"perf_eval": [],
"perf_cmp": [],
"instances": [],
"strategy": [],
"a_new": [],
"a_old": [],
"seed": []
}
df_detailed = {
"strategy": [],
"confidence": [],
"time": [],
"instances": [],
"prediction": [],
"a_new": [],
"a_old": [],
"seed": []
}
def callback(future):
pbar.update(1)
strat_name, runs, dico = future.result()
# Fill detailed dataframe
stats = dico["stats"]
for k, v in stats.items():
for el in v:
df_detailed[k].append(el)
# Save detailed dataframe
if pbar.n % save_every == 0:
df_tmp = pd.DataFrame(df_detailed)
if original_df_detailed is not None:
df_tmp = original_df_detailed.append(df_tmp)
df_tmp.to_csv(f"./detailed_runs_{output_suffix}.csv")
# real data
real = dico["real"]
challengers: List[int] = real["challenger"]
seed = stats["seed"][-1]
# Fill general dataframe
for challenger, incumbent, perf_chall, perf_inc, y_true, _, _, _ in runs:
df_general["y_true"].append(y_true)
df_general["perf_eval"].append(perf_chall)
df_general["perf_cmp"].append(perf_inc)
df_general["strategy"].append(strat_name)
df_general["a_new"].append(challenger)
df_general["a_old"].append(incumbent)
index = challengers.index(challenger)
df_general["time"].append(real["time"][index])
df_general["instances"].append(real["instances"][index])
df_general["y_pred"].append(real["prediction"][index])
df_general["seed"].append(seed)
# Save general dataframe
if pbar.n % save_every == 0:
df_tmp = pd.DataFrame(df_general)
if original_df_general is not None:
df_tmp = original_df_general.append(df_tmp)
df_tmp.to_csv(f"./runs_{output_suffix}.csv")
def evaluate(scenario_path: str, strategy: Strategy, seed: int,
verbose: bool = False, **kwargs) -> Tuple[str, List[Tuple[int, int, float, float, bool, bool, float, int]], Dict]:
env: TestEnv = TestEnv(scenario_path, verbose, seed=seed)
# Select instances
ninstances = round(ratio_instances * env.ninstances)
selected_instances = env.rng.choice(list(range(env.ninstances)), size=ninstances)
for instance in range(env.ninstances):
if instance not in selected_instances:
env.set_enabled(-1, instance, False)
env.set_instance_count_for_eval(instance, False)
# Subset of configurations
known_configurations = env.rng.choice(list(range(env.nconfigurations)), size=nb_configurations)
challenger_list: List[int] = []
for config in range(env.nconfigurations):
if config not in known_configurations:
env.set_enabled(config, -1, False)
challenger_list.append(config)
# Get incumbent that is the fastest
env.fit_model()
incumbent: int = env.reset(ResetChoice.RESET_BEST)[1]["incumbent_configuration"]
env._history.clear()
stats = {
"time": [],
"confidence": [],
"prediction": [],
"strategy": [],
"a_new": [],
"a_old": [],
"instances": [],
"seed": []
}
real = {
"prediction": [],
"time": [],
"challenger": [],
"instances": [],
}
to_ratio = lambda x: int(np.floor(x * 100))
label: str = strategy.name()
for challenger in challenger_list:
state, information, information_has_changed = env.reset((incumbent, challenger))
if information_has_changed:
strategy.ready(**information)
strategy.reset()
strategy.feed(state)
last_time_ratio: float = 0
instances : int = 0
finished: bool = False
while instances < env.ninstances:
state = env.step(strategy.choose_instance())
strategy.feed(state)
instances += 1
# Update if time changed enough
time_ratio: float = env.current_time / env.current_challenger_max_total_time
if to_ratio(last_time_ratio) < to_ratio(time_ratio):
for i in range(to_ratio(last_time_ratio), to_ratio(time_ratio)):
# Update predictions
stats["time"].append(i)
stats["prediction"].append(
strategy.is_better() == env.is_challenger_better)
stats["strategy"].append(label)
stats["a_new"].append(challenger)
stats["a_old"].append(incumbent)
stats["instances"].append(instances)
stats["seed"].append(seed)
# Update confidence
try:
stats["confidence"].append(
strategy.get_current_choice_confidence() * 100)
except AttributeError:
stats["confidence"].append(100)
last_time_ratio = time_ratio
if not finished and strategy.get_current_choice_confidence() >= .95 and not strategy.is_better():
if isinstance(strategy._discrimination, Wilcoxon) and env.current_instances < 5:
continue
finished = True
real["challenger"].append(challenger)
real["prediction"].append(strategy.is_better())
real["time"].append(env.current_time / env.current_challenger_max_total_time)
real["instances"].append(env.current_instances)
env.choose(strategy.is_better())
# Fill in the rest
for i in range(to_ratio(last_time_ratio), 101):
# Update predictions
stats["time"].append(i)
stats["strategy"].append(label)
stats["a_new"].append(challenger)
stats["a_old"].append(incumbent)
stats["instances"].append(instances)
stats["prediction"].append(
strategy.is_better() == env.is_challenger_better)
stats["seed"].append(seed)
# Update confidence
try:
stats["confidence"].append(
strategy.get_current_choice_confidence() * 100)
except AttributeError:
stats["confidence"].append(100)
if not finished:
finished = True
real["challenger"].append(challenger)
real["prediction"].append(strategy.is_better())
real["time"].append(env.current_time / env.current_challenger_max_total_time)
real["instances"].append(env.current_instances)
kwargs["stats"] = stats
kwargs["real"] = real
kwargs["a_old"] = incumbent
return strategy.name(), list(env.runs()), kwargs
def run(scenario_path, max_workers):
print()
env = TestEnv(scenario_path)
n_algos = env.nconfigurations
# Generate strategies
total: int = 0
strategies: List[Tuple[Strategy, Dict]] = []
for discriminator in discriminators:
for selection in selectors:
for strategy_make in strategy_makers:
strat = strategy_make(selection, discriminator())
seeds_done = []
total += nb_seeds
if original_df_general is not None:
tmp = original_df_general[original_df_general["strategy"] == strat.name(
)]
seeds_done = np.unique(
tmp["seed"].values).tolist()
total -= len(seeds_done)
strategies.append([strat, seeds_done])
global pbar
pbar = tqdm(total=total)
futures = []
executor = ProcessPoolExecutor(max_workers)
for strategy, seeds_done in strategies:
for seed in range(nb_seeds):
if seed in seeds_done:
continue
future = executor.submit(evaluate, scenario_path, strategy.clone(), seed)
future.add_done_callback(callback)
futures.append(future)
wait(futures, return_when=ALL_COMPLETED)
pbar.close()
run(scenario_path, max_workers)
# Last save
df_tmp = pd.DataFrame(df_detailed)
if original_df_detailed is not None:
df_tmp = original_df_detailed.append(df_tmp)
df_tmp.to_csv(f"./detailed_runs_{output_suffix}.csv")
df_tmp = pd.DataFrame(df_general)
if original_df_general is not None:
df_tmp = original_df_general.append(df_tmp)
df_tmp.to_csv(f"./runs_{output_suffix}.csv")
|
[
"pandas.DataFrame",
"tqdm.tqdm",
"argparse.ArgumentParser",
"pseas.discrimination.wilcoxon.Wilcoxon",
"pseas.instance_selection.udd.UDD",
"pandas.read_csv",
"numpy.floor",
"pseas.standard_strategy.StandardStrategy",
"os.path.exists",
"pseas.test_env.TestEnv",
"concurrent.futures.process.ProcessPoolExecutor",
"pseas.instance_selection.discrimination_based.DiscriminationBased",
"numpy.linspace",
"concurrent.futures.wait",
"numpy.unique"
] |
[((1356, 1412), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Produce run data."""'}), "(description='Produce run data.')\n", (1379, 1412), False, 'import argparse\n'), ((5860, 5905), 'os.path.exists', 'os.path.exists', (['f"""./runs_{output_suffix}.csv"""'], {}), "(f'./runs_{output_suffix}.csv')\n", (5874, 5905), False, 'import os\n'), ((14656, 14681), 'pandas.DataFrame', 'pd.DataFrame', (['df_detailed'], {}), '(df_detailed)\n', (14668, 14681), True, 'import pandas as pd\n'), ((14831, 14855), 'pandas.DataFrame', 'pd.DataFrame', (['df_general'], {}), '(df_general)\n', (14843, 14855), True, 'import pandas as pd\n'), ((5933, 5975), 'pandas.read_csv', 'pd.read_csv', (['f"""./runs_{output_suffix}.csv"""'], {}), "(f'./runs_{output_suffix}.csv')\n", (5944, 5975), True, 'import pandas as pd\n'), ((6077, 6128), 'pandas.read_csv', 'pd.read_csv', (['f"""./detailed_runs_{output_suffix}.csv"""'], {}), "(f'./detailed_runs_{output_suffix}.csv')\n", (6088, 6128), True, 'import pandas as pd\n'), ((8424, 8466), 'pseas.test_env.TestEnv', 'TestEnv', (['scenario_path', 'verbose'], {'seed': 'seed'}), '(scenario_path, verbose, seed=seed)\n', (8431, 8466), False, 'from pseas.test_env import ResetChoice, TestEnv\n'), ((13338, 13360), 'pseas.test_env.TestEnv', 'TestEnv', (['scenario_path'], {}), '(scenario_path)\n', (13345, 13360), False, 'from pseas.test_env import ResetChoice, TestEnv\n'), ((14147, 14164), 'tqdm.tqdm', 'tqdm', ([], {'total': 'total'}), '(total=total)\n', (14151, 14164), False, 'from tqdm import tqdm\n'), ((14197, 14229), 'concurrent.futures.process.ProcessPoolExecutor', 'ProcessPoolExecutor', (['max_workers'], {}), '(max_workers)\n', (14216, 14229), False, 'from concurrent.futures.process import ProcessPoolExecutor\n'), ((14543, 14583), 'concurrent.futures.wait', 'wait', (['futures'], {'return_when': 'ALL_COMPLETED'}), '(futures, return_when=ALL_COMPLETED)\n', (14547, 14583), False, 'from concurrent.futures import wait, ALL_COMPLETED\n'), ((5058, 5082), 'pseas.discrimination.wilcoxon.Wilcoxon', 'Wilcoxon', ([], {'confidence': '(101)'}), '(confidence=101)\n', (5066, 5082), False, 'from pseas.discrimination.wilcoxon import Wilcoxon\n'), ((5292, 5303), 'pseas.instance_selection.udd.UDD', 'UDD', (['p1', 'p2'], {}), '(p1, p2)\n', (5295, 5303), False, 'from pseas.instance_selection.udd import UDD\n'), ((5429, 5451), 'pseas.instance_selection.discrimination_based.DiscriminationBased', 'DiscriminationBased', (['p'], {}), '(p)\n', (5448, 5451), False, 'from pseas.instance_selection.discrimination_based import DiscriminationBased\n'), ((5510, 5532), 'pseas.standard_strategy.StandardStrategy', 'StandardStrategy', (['i', 'd'], {}), '(i, d)\n', (5526, 5532), False, 'from pseas.standard_strategy import StandardStrategy\n'), ((6978, 7003), 'pandas.DataFrame', 'pd.DataFrame', (['df_detailed'], {}), '(df_detailed)\n', (6990, 7003), True, 'import pandas as pd\n'), ((8029, 8053), 'pandas.DataFrame', 'pd.DataFrame', (['df_general'], {}), '(df_general)\n', (8041, 8053), True, 'import pandas as pd\n'), ((5184, 5211), 'numpy.linspace', 'np.linspace', (['(0.2)', '(2)'], {'num': '(10)'}), '(0.2, 2, num=10)\n', (5195, 5211), True, 'import numpy as np\n'), ((5239, 5266), 'numpy.linspace', 'np.linspace', (['(0.2)', '(2)'], {'num': '(10)'}), '(0.2, 2, num=10)\n', (5250, 5266), True, 'import numpy as np\n'), ((5374, 5402), 'numpy.linspace', 'np.linspace', (['(1.01)', '(2)'], {'num': '(10)'}), '(1.01, 2, num=10)\n', (5385, 5402), True, 'import numpy as np\n'), ((9737, 9754), 'numpy.floor', 'np.floor', (['(x * 100)'], {}), '(x * 100)\n', (9745, 9754), True, 'import numpy as np\n'), ((13954, 13983), 'numpy.unique', 'np.unique', (["tmp['seed'].values"], {}), "(tmp['seed'].values)\n", (13963, 13983), True, 'import numpy as np\n')]
|
import sys
from copy import copy
import numpy as np
from moviepy.audio.io.ffmpeg_audiowriter import ffmpeg_audiowrite
from moviepy.decorators import requires_duration
from moviepy.Clip import Clip
# optimize range in function of Python's version
if sys.version_info < (3,):
range = xrange
class AudioClip(Clip):
"""Base class for audio clips.
See ``SoundClip`` and ``CompositeSoundClip`` for usable classes.
An AudioClip is a Clip with a ``get_frame`` attribute of
the form `` t -> [ f_t ]`` for mono sound and
``t-> [ f1_t, f2_t ]`` for stereo sound (the arrays are Numpy arrays).
The `f_t` are floats between -1 and 1. These bounds can be
trespassed wihtout problems (the program will put the
sound back into the bounds at conversion time, without much impact).
Parameters
-----------
get_frame
A function `t-> frame at time t`. The frame does not mean much
for a sound, it is just a float. What 'makes' the sound are
the variations of that float in the time.
nchannels
Number of channels (one or two for mono or stereo).
Examples
---------
>>> # Plays the note A (a sine wave of frequency 404HZ)
>>> import numpy as np
>>> gf = lambda t : 2*[ np.sin(404 * 2 * np.pi * t) ]
>>> clip = AudioClip().set_get_frame(gf)
>>> clip.set_duration(5).preview()
"""
def __init__(self, get_frame = None):
Clip.__init__(self)
if get_frame:
self.get_frame = get_frame
frame0 = self.get_frame(0)
if hasattr(frame0, '__iter__'):
self.nchannels = len(list(frame0))
else:
self.nchannels = 1
@requires_duration
def to_soundarray(self,tt=None,fps=None, nbytes=2):
"""
Transforms the sound into an array that can be played by pygame
or written in a wav file. See ``AudioClip.preview``.
Parameters
------------
fps
Frame rate of the sound for the conversion.
44100 for top quality.
nbytes
Number of bytes to encode the sound: 1 for 8bit sound,
2 for 16bit, 4 for 32bit sound.
"""
if tt is None:
tt = np.arange(0,self.duration, 1.0/fps)
#print tt.max() - tt.min(), tt.min(), tt.max()
snd_array = self.get_frame(tt)
snd_array = np.maximum(-0.99,
np.minimum(0.99,snd_array))
inttype = {1:'int8',2:'int16', 4:'int32'}[nbytes]
return (2**(8*nbytes-1)*snd_array).astype(inttype)
@requires_duration
def to_audiofile(self,filename, fps=44100, nbytes=2,
buffersize=2000, codec='libvorbis',
bitrate=None, verbose=True):
"""
codecs = { 'libmp3lame': 'mp3',
'libvorbis':'ogg',
'libfdk_aac':'m4a',
'pcm_s16le':'wav',
'pcm_s32le': 'wav'}
"""
return ffmpeg_audiowrite(self,filename, fps, nbytes, buffersize,
codec, bitrate, verbose)
class AudioArrayClip(AudioClip):
"""
An audio clip made from a sound array.
Parameters
-----------
array
A Numpy array representing the sound, of size Nx1 for mono,
Nx2 for stereo.
fps
Frames per second : speed at which the sound is supposed to be
played.
"""
def __init__(self, array, fps):
Clip.__init__(self)
self.array = array
self.fps = fps
self.duration = 1.0 * len(array) / fps
def get_frame(t):
""" complicated, but must be able to handle the case where t
is a list of the form sin(t) """
if isinstance(t, np.ndarray):
array_inds = (self.fps*t).astype(int)
in_array = (array_inds>0) & (array_inds < len(self.array))
result = np.zeros((len(t),2))
result[in_array] = self.array[array_inds[in_array]]
return result
else:
i = int(self.fps * t)
if i < 0 or i >= len(self.array):
return 0*self.array[0]
else:
return self.array[i]
self.get_frame = get_frame
self.nchannels = len(list(self.get_frame(0)))
class CompositeAudioClip(AudioClip):
""" Clip made by composing several AudioClips.
An audio clip made by putting together several audio clips.
Parameters
------------
clips
List of audio clips, which may start playing at different times or
together. If all have their ``duration`` attribute set, the
duration of the composite clip is computed automatically.
"""
def __init__(self, clips):
Clip.__init__(self)
self.clips = clips
ends = [c.end for c in self.clips]
self.nchannels = max([c.nchannels for c in self.clips])
if not any([(e is None) for e in ends]):
self.duration = max(ends)
self.end = max(ends)
def get_frame(t):
# buggy
played_parts = [c.is_playing(t) for c in self.clips]
sounds= [c.get_frame(t - c.start)*np.array([part]).T
for c,part in zip(self.clips, played_parts)
if (part is not False) ]
if isinstance(t,np.ndarray):
zero = np.zeros((len(t),self.nchannels))
else:
zero = np.zeros(self.nchannels)
return zero + sum(sounds)
self.get_frame = get_frame
|
[
"numpy.minimum",
"moviepy.Clip.Clip.__init__",
"numpy.zeros",
"numpy.arange",
"numpy.array",
"moviepy.audio.io.ffmpeg_audiowriter.ffmpeg_audiowrite"
] |
[((1488, 1507), 'moviepy.Clip.Clip.__init__', 'Clip.__init__', (['self'], {}), '(self)\n', (1501, 1507), False, 'from moviepy.Clip import Clip\n'), ((3164, 3251), 'moviepy.audio.io.ffmpeg_audiowriter.ffmpeg_audiowrite', 'ffmpeg_audiowrite', (['self', 'filename', 'fps', 'nbytes', 'buffersize', 'codec', 'bitrate', 'verbose'], {}), '(self, filename, fps, nbytes, buffersize, codec, bitrate,\n verbose)\n', (3181, 3251), False, 'from moviepy.audio.io.ffmpeg_audiowriter import ffmpeg_audiowrite\n'), ((3669, 3688), 'moviepy.Clip.Clip.__init__', 'Clip.__init__', (['self'], {}), '(self)\n', (3682, 3688), False, 'from moviepy.Clip import Clip\n'), ((5063, 5082), 'moviepy.Clip.Clip.__init__', 'Clip.__init__', (['self'], {}), '(self)\n', (5076, 5082), False, 'from moviepy.Clip import Clip\n'), ((2332, 2370), 'numpy.arange', 'np.arange', (['(0)', 'self.duration', '(1.0 / fps)'], {}), '(0, self.duration, 1.0 / fps)\n', (2341, 2370), True, 'import numpy as np\n'), ((2533, 2560), 'numpy.minimum', 'np.minimum', (['(0.99)', 'snd_array'], {}), '(0.99, snd_array)\n', (2543, 2560), True, 'import numpy as np\n'), ((5851, 5875), 'numpy.zeros', 'np.zeros', (['self.nchannels'], {}), '(self.nchannels)\n', (5859, 5875), True, 'import numpy as np\n'), ((5543, 5559), 'numpy.array', 'np.array', (['[part]'], {}), '([part])\n', (5551, 5559), True, 'import numpy as np\n')]
|
import joblib
import numpy as np
import pandas as pd
np.random.seed(0)
df_tracks = pd.read_hdf('df_data/df_tracks.hdf')
df_playlists = pd.read_hdf('df_data/df_playlists.hdf')
df_playlists_info = pd.read_hdf('df_data/df_playlists_info.hdf')
df_playlists_test = pd.read_hdf('df_data/df_playlists_test.hdf')
df_playlists_test_info = pd.read_hdf('df_data/df_playlists_test_info.hdf')
num_tracks = df_playlists_info.groupby('num_tracks').pid.apply(np.array)
validation_playlists = {}
for i, j in df_playlists_test_info.num_tracks.value_counts().reset_index().values:
validation_playlists[i] = np.random.choice(num_tracks.loc[i], 2 * j, replace=False)
val1_playlist = {}
val2_playlist = {}
for i in [0, 1, 5, 10, 25, 100]:
val1_playlist[i] = []
val2_playlist[i] = []
value_counts = df_playlists_test_info.query('num_samples==@i').num_tracks.value_counts()
for j, k in value_counts.reset_index().values:
val1_playlist[i] += list(validation_playlists[j][:k])
validation_playlists[j] = validation_playlists[j][k:]
val2_playlist[i] += list(validation_playlists[j][:k])
validation_playlists[j] = validation_playlists[j][k:]
val1_index = df_playlists.pid.isin(val1_playlist[0])
val2_index = df_playlists.pid.isin(val2_playlist[0])
for i in [1, 5, 10, 25, 100]:
val1_index = val1_index | (df_playlists.pid.isin(val1_playlist[i]) & (df_playlists.pos >= i))
val2_index = val2_index | (df_playlists.pid.isin(val2_playlist[i]) & (df_playlists.pos >= i))
train = df_playlists[~(val1_index | val2_index)]
val1 = df_playlists[val1_index]
val2 = df_playlists[val2_index]
val1_pids = np.hstack([val1_playlist[i] for i in val1_playlist])
val2_pids = np.hstack([val2_playlist[i] for i in val2_playlist])
train = pd.concat([train, df_playlists_test])
train.to_hdf('df_data/train.hdf', key='abc')
val1.to_hdf('df_data/val1.hdf', key='abc')
val2.to_hdf('df_data/val2.hdf', key='abc')
joblib.dump(val1_pids, 'df_data/val1_pids.pkl')
joblib.dump(val2_pids, 'df_data/val2_pids.pkl')
|
[
"numpy.random.seed",
"pandas.read_hdf",
"joblib.dump",
"numpy.hstack",
"numpy.random.choice",
"pandas.concat"
] |
[((54, 71), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (68, 71), True, 'import numpy as np\n'), ((85, 121), 'pandas.read_hdf', 'pd.read_hdf', (['"""df_data/df_tracks.hdf"""'], {}), "('df_data/df_tracks.hdf')\n", (96, 121), True, 'import pandas as pd\n'), ((137, 176), 'pandas.read_hdf', 'pd.read_hdf', (['"""df_data/df_playlists.hdf"""'], {}), "('df_data/df_playlists.hdf')\n", (148, 176), True, 'import pandas as pd\n'), ((197, 241), 'pandas.read_hdf', 'pd.read_hdf', (['"""df_data/df_playlists_info.hdf"""'], {}), "('df_data/df_playlists_info.hdf')\n", (208, 241), True, 'import pandas as pd\n'), ((262, 306), 'pandas.read_hdf', 'pd.read_hdf', (['"""df_data/df_playlists_test.hdf"""'], {}), "('df_data/df_playlists_test.hdf')\n", (273, 306), True, 'import pandas as pd\n'), ((332, 381), 'pandas.read_hdf', 'pd.read_hdf', (['"""df_data/df_playlists_test_info.hdf"""'], {}), "('df_data/df_playlists_test_info.hdf')\n", (343, 381), True, 'import pandas as pd\n'), ((1636, 1688), 'numpy.hstack', 'np.hstack', (['[val1_playlist[i] for i in val1_playlist]'], {}), '([val1_playlist[i] for i in val1_playlist])\n', (1645, 1688), True, 'import numpy as np\n'), ((1701, 1753), 'numpy.hstack', 'np.hstack', (['[val2_playlist[i] for i in val2_playlist]'], {}), '([val2_playlist[i] for i in val2_playlist])\n', (1710, 1753), True, 'import numpy as np\n'), ((1763, 1800), 'pandas.concat', 'pd.concat', (['[train, df_playlists_test]'], {}), '([train, df_playlists_test])\n', (1772, 1800), True, 'import pandas as pd\n'), ((1933, 1980), 'joblib.dump', 'joblib.dump', (['val1_pids', '"""df_data/val1_pids.pkl"""'], {}), "(val1_pids, 'df_data/val1_pids.pkl')\n", (1944, 1980), False, 'import joblib\n'), ((1981, 2028), 'joblib.dump', 'joblib.dump', (['val2_pids', '"""df_data/val2_pids.pkl"""'], {}), "(val2_pids, 'df_data/val2_pids.pkl')\n", (1992, 2028), False, 'import joblib\n'), ((596, 653), 'numpy.random.choice', 'np.random.choice', (['num_tracks.loc[i]', '(2 * j)'], {'replace': '(False)'}), '(num_tracks.loc[i], 2 * j, replace=False)\n', (612, 653), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 8 17:03:07 2018
@author: jeremiasknoblauch
Description: Plots pics from Air Pollution Data London
"""
import csv
import numpy as np
from Evaluation_tool import EvaluationTool
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
import datetime
import matplotlib
#ensure that we have type 1 fonts (for ICML publishing guiedlines)
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
"""""STEP 1: DATA TRANSFOMRATIONS"""""
normalize = True
deseasonalize_2h = True
deseasonalize_day = True #only one of the two deseasonalizations should be chosen
shortened, shortened_to = False, 500
daily_avg = True
if daily_avg:
deseasonalize_2h = False
data_dir = ("//Users//jeremiasknoblauch//Documents//OxWaSP//BOCPDMS//" +
"//Code//SpatialBOCD//Data//AirPollutionData")
cp_type = "CongestionChargeData"
dist_file_road = (data_dir + "//" + cp_type + "//" +
"RoadDistanceMatrix_")
dist_file_euclid = (data_dir + "//" + cp_type + "//" +
"EuclideanDistanceMatrix_")
results_file = ("/Users//jeremiasknoblauch//Documents////OxWaSP//BOCPDMS//Code//" +
"SpatialBOCD//Paper//AirPollutionData//" +
"results_daily.txt")
res_path = ("/Users//jeremiasknoblauch//Documents////OxWaSP//BOCPDMS//Code//" +
"SpatialBOCD//Paper//AirPollutionData//")
frequency = "2h" #2h, daily (=every 15 min),
mode = "bigger" #bigger, smaller (bigger contains more filled-in values)
if mode == "bigger":
stationIDs = ["BT1", "BX1", "BX2", "CR2", "CR4",
"EA1", "EA2", "EN1", "GR4", "GR5",
"HG1", "HG2", "HI0", "HI1", "HR1",
"HS2", "HV1", "HV3", "KC1", "KC2",
"LH2", "MY1", "RB3", "RB4", "TD0",
"TH1", "TH2", "WA2", "WL1"]
elif mode == "smaller":
stationIDs = ["BT1", "BX2", "CR2", "EA2", "EN1", "GR4",
"GR5", "HG1", "HG2", "HI0", "HR1", "HV1",
"HV3", "KC1", "LH2", "RB3", "TD0", "WA2"]
num_stations = len(stationIDs)
"""STEP 1: Read in distances"""
"""STEP 1.1: Read in road distances (as strings)"""
pw_distances_road = []
station_IDs = []
count = 0
with open(dist_file_road + mode + ".csv") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
pw_distances_road += row
"""STEP 1.2: Read in euclidean distances (as strings)"""
pw_distances_euclid = []
station_IDs = []
count = 0
with open(dist_file_euclid + mode + ".csv") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
pw_distances_euclid += row
"""STEP 1.3: Convert both distance lists to floats and matrices"""
pw_d_r, pw_d_e = [], []
for r,e in zip(pw_distances_road, pw_distances_euclid):
pw_d_r.append(float(r))
pw_d_e.append(float(e))
pw_distances_road = np.array(pw_d_r).reshape(num_stations, num_stations)
pw_distances_euclid = np.array(pw_d_e).reshape(num_stations, num_stations)
"""STEP 2: Convert distance matrices to nbhs"""
cutoffs = [0.0, 10.0, 20.0, 30.0, 40.0, 100.0]
num_nbhs = len(cutoffs) - 1
"""STEP 2.1: road distances"""
road_nbhs = []
for location in range(0, num_stations):
location_nbh = []
for i in range(0, num_nbhs):
larger_than, smaller_than = cutoffs[i], cutoffs[i+1]
indices = np.intersect1d(
np.where(pw_distances_road[location,:] > larger_than),
np.where(pw_distances_road[location,:] < smaller_than)).tolist()
location_nbh.append(indices.copy())
road_nbhs.append(location_nbh.copy())
"""STEP 2.2: euclidean distances"""
euclid_nbhs =[]
for location in range(0, num_stations):
location_nbh = []
for i in range(0, num_nbhs):
larger_than, smaller_than = cutoffs[i], cutoffs[i+1]
indices = np.intersect1d(
np.where(pw_distances_euclid[location,:] > larger_than),
np.where(pw_distances_euclid[location,:] < smaller_than)).tolist()
location_nbh.append(indices.copy())
euclid_nbhs.append(location_nbh.copy())
"""STEP 3: Read in station data for each station"""
station_data = []
for id_ in stationIDs:
file_name = (data_dir + "//" + cp_type + "//" +
id_ + "_081702-081703_" + frequency + ".txt")
"""STEP 3.1: Read in raw data"""
#NOTE: Skip the header
data_raw = []
count = 0
with open(file_name) as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if count > 0:
data_raw += row
count += 1
"""STEP 3.2: Convert to floats"""
#NOTE: We have row names, so skip every second
dat = []
for entry in data_raw:
dat += [float(entry)]
"""STEP 3.3: Append to station_data list"""
station_data.append(dat.copy())
"""STEP 4: Format the station data into a matrix"""
T, S1, S2 = len(station_data[0]), num_stations, 1
data = np.zeros((T, num_stations))
for i in range(0, num_stations):
data[:,i] = np.array(station_data[i])
intercept_priors = np.mean(data,axis=0)
hyperpar_opt = "caron"
"""STEP 5: Transformation if necessary"""
if shortened:
T = shortened_to
data = data[:T,:]
if daily_avg:
"""average 12 consecutive values until all have been processed"""
new_data = np.zeros((int(T/12), num_stations))
for station in range(0, num_stations):
new_data[:, station] = np.mean(data[:,station].
reshape(int(T/12), 12),axis=1)
data= new_data
T = data.shape[0]
if deseasonalize_day:
if deseasonalize_2h:
print("CAREFUL! You want to deseasonalize twice, so deseasonalizing " +
"was aborted!")
elif not daily_avg:
mean_day = np.zeros((7, num_stations))
#deseasonalize
for station in range(0, num_stations):
"""get the daily average. Note that we have 12 obs/day for a year"""
for day in range(0, 7):
selection_week = [False]*day + [True]*12 + [False]*(6-day)
selection = (selection_week * int(T/(7*12)) +
selection_week[:(T-int(T/(7*12))*7*12)])
mean_day[day, station] = np.mean(data[selection,station])
data[selection,station] = (data[selection,station] -
mean_day[day, station])
if deseasonalize_day and daily_avg:
mean_day = np.zeros((7, num_stations))
#deseasonalize
for station in range(0, num_stations):
"""get the daily average. Note that we have 12 obs/day for a year"""
#Also note that T will already have changed to the #days
for day in range(0, 7):
selection_week = [False]*day + [True] + [False]*(6-day)
selection = (selection_week * int(T/7) +
selection_week[:(T-int(T/7)*7)])
mean_day[day, station] = np.mean(data[selection,station])
data[selection,station] = (data[selection,station] -
mean_day[day, station])
T = data.shape[0]
if deseasonalize_2h:
if deseasonalize_day:
print("CAREFUL! You want to deseasonalize twice, so deseasonalizing " +
"was aborted!")
else:
mean_2h = np.zeros((12*7, num_stations))
for station in range(0, num_stations):
"""get the average for each 2h-interval for each weekday"""
for _2h in range(0, 12*7):
selection_2h = [False]*_2h + [True] + [False]*(12*7-1-_2h)
selection = (selection_2h * int(T/(7*12)) +
selection_2h[:(T-int(T/(7*12))*7*12)])
mean_2h[_2h, station] = np.mean(data[selection,station])
data[selection,station] = (data[selection,station] -
mean_2h[_2h, station])
if normalize:
data = (data - np.mean(data, axis=0))/np.sqrt(np.var(data,axis=0))
intercept_priors = np.mean(data,axis=0)
"""""STEP 2: READ RESULTS"""""
EvT = EvaluationTool()
EvT.build_EvaluationTool_via_results(results_file)
segmentation = EvT.results[EvT.names.index("MAP CPs")][-2]
model_labels = EvT.results[EvT.names.index("model labels")]
num_models = len(np.union1d(model_labels, model_labels))
relevant_models = np.union1d([seg[1] for seg in segmentation],[seg[1] for seg in segmentation])
#mods = [8,11,13,17,18]
all_models = [e for e in range(0, len(model_labels))] #np.linspace(0, len(model_labels)-1, len(model_labels), dtype = int)
"""Get dates"""
def perdelta(start, end, delta, date_list):
curr = start
while curr < end:
#yield curr
date_list.append(curr)
curr += delta
all_dates = []
#start_year, start_month, start_day, start_hour = 2002, 8, 17, 0
#start_datetime = datetime.datetime(year = 2002, month = 8, day = 17, hour = 0)
#stop_datetime = datetime.datetime(year=2003, month = 8, day = 18, hour = 0)
#perdelta(start_datetime, stop_datetime, datetime.timedelta(hours = 2), all_dates)
start_year, start_month, start_day, start_hour = 2002, 8, 17, 0
start_datetime = datetime.date(year = 2002, month = 8, day = 17)
stop_datetime = datetime.date(year=2003, month = 8, day = 18)
perdelta(start_datetime, stop_datetime, datetime.timedelta(days = 1), all_dates)
"""""STEP 3: Plot"""""
index_selection = [0,5,9,13,17,21,30]
#location, color
true_CPs = [[datetime.date(year = 2003, month = 2, day = 17), "red", 4.0]]
#paper: height_ratio, num_subplots = [4,3,5],3
#poster: height_ratio, num_subplots = [4,3,4],3
height_ratio, num_subplots = [4,3,5],3
#paper: ylabel_coords = [-0.085, 0.5]
#poster: [-0.06, 0.5]
ylabel_coords = [-0.085, 0.5]
#paper: figsize = (8,5) #for poster: 12,5
fig, ax_array = plt.subplots(num_subplots, sharex = True,
gridspec_kw = {'height_ratios':height_ratio},
figsize=(8,5))
plt.subplots_adjust(hspace = .2, left = None, bottom = None, right = None, top = None)
off = 5
time_range = np.linspace(10,T-2, T-2-off,dtype = int)
all_dates = all_dates[-len(time_range):]
fig_1 = EvT.plot_raw_TS(data[-len(time_range):,:].reshape(len(time_range), 29), all_dates = all_dates, ax = ax_array[0],
time_range = time_range,
custom_colors_series = ["black"]*10,
ylab_fontsize = 14,
yticks_fontsize = 14,
ylab = "NOX",
xlab=None,
ylabel_coords = ylabel_coords,
true_CPs = true_CPs)
mod = [17,21]
EvT.plot_model_posterior(indices=mod, #mods, #mods, #relevant_models,
plot_type = "trace", #"MAPVariance1_trace",
#y_axis_labels = [str(e) for e in all_models],#[#"AR(1)",
#"M(5+)", "M(6)",
# "M(6+)",
# "M(7)", "M(7+)"],#relevant_models],
time_range = time_range,
y_axis_labels = [],
log_format=False, aspect = 'auto',
show_MAP_CPs = False,
#start_plot = 2002.75, stop_plot = 2003.75,
custom_colors = ["blue", "orange"], # ["orange"], #custom_colors_models,
ax = ax_array[1] ,#ax_array[1], #None, #ax_array[1],
xlab = None, #ylab = None, #trace",period_time_list = None,
number_offset = 1.0, #datetime.timedelta(days = 1),#0.75,
number_fontsize = 20,
period_line_thickness = 7.0,
xlab_fontsize = 14, ylab_fontsize = 14,
xticks_fontsize = 14, yticks_fontsize = 14,
ylabel_coords = ylabel_coords,
#ylab = None, #"Model posterior max",
#period_time_list = [
# [datetime.datetime(year = 2003, month = 2, day = 17, hour = 0),
# datetime.datetime(year = 2003, month = 2, day = 18, hour = 0)]],
#label_list = [["1"]],
#window_len = int(12*7*1),
period_time_list = None, #[[datetime.datetime(year = 2003, month = 2, day = 17, hour = 0),
#datetime.datetime(year = 2003, month = 2, day = 18, hour = 0)]],
label_list = None, #[["1"]],
SGV = True,
log_det = True,
all_dates = all_dates,
true_CPs = true_CPs)
fig_4 = EvT.plot_model_posterior(indices=mod, #mods, #mods, #relevant_models,
plot_type = "BF", #"MAPVariance1_trace",
#y_axis_labels = [str(e) for e in all_models],#[#"AR(1)",
#"M(5+)", "M(6)",
# "M(6+)",
# "M(7)", "M(7+)"],#relevant_models],
time_range = time_range,
log_format=True, aspect = 'auto',
show_MAP_CPs = False,
#start_plot = 2002.7, stop_plot = 2003.7,
custom_colors = ["green"], #custom_colors_models,
ax = ax_array[2], xlab = None, ylab = "log(BF)", #trace",
period_time_list = None,
label_list =None,
number_offset = 0.75,
number_fontsize = 20,
period_line_thickness = 7.0,
xlab_fontsize = 14, ylab_fontsize = 14,
xticks_fontsize = 14, yticks_fontsize = 14,
ylabel_coords = ylabel_coords,
window_len = int(12*7*2),
SGV = False,
log_det = True,
all_dates = all_dates,
true_CPs = true_CPs
)
fig.savefig(res_path + "APData.pdf")
|
[
"Evaluation_tool.EvaluationTool",
"csv.reader",
"numpy.zeros",
"datetime.date",
"matplotlib.pyplot.subplots",
"numpy.var",
"numpy.mean",
"numpy.array",
"datetime.timedelta",
"numpy.linspace",
"numpy.where",
"matplotlib.pyplot.subplots_adjust",
"numpy.union1d"
] |
[((4958, 4985), 'numpy.zeros', 'np.zeros', (['(T, num_stations)'], {}), '((T, num_stations))\n', (4966, 4985), True, 'import numpy as np\n'), ((5080, 5101), 'numpy.mean', 'np.mean', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (5087, 5101), True, 'import numpy as np\n'), ((8052, 8068), 'Evaluation_tool.EvaluationTool', 'EvaluationTool', ([], {}), '()\n', (8066, 8068), False, 'from Evaluation_tool import EvaluationTool\n'), ((8316, 8394), 'numpy.union1d', 'np.union1d', (['[seg[1] for seg in segmentation]', '[seg[1] for seg in segmentation]'], {}), '([seg[1] for seg in segmentation], [seg[1] for seg in segmentation])\n', (8326, 8394), True, 'import numpy as np\n'), ((9125, 9166), 'datetime.date', 'datetime.date', ([], {'year': '(2002)', 'month': '(8)', 'day': '(17)'}), '(year=2002, month=8, day=17)\n', (9138, 9166), False, 'import datetime\n'), ((9189, 9230), 'datetime.date', 'datetime.date', ([], {'year': '(2003)', 'month': '(8)', 'day': '(18)'}), '(year=2003, month=8, day=18)\n', (9202, 9230), False, 'import datetime\n'), ((9758, 9862), 'matplotlib.pyplot.subplots', 'plt.subplots', (['num_subplots'], {'sharex': '(True)', 'gridspec_kw': "{'height_ratios': height_ratio}", 'figsize': '(8, 5)'}), "(num_subplots, sharex=True, gridspec_kw={'height_ratios':\n height_ratio}, figsize=(8, 5))\n", (9770, 9862), True, 'from matplotlib import pyplot as plt\n'), ((9921, 9998), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'hspace': '(0.2)', 'left': 'None', 'bottom': 'None', 'right': 'None', 'top': 'None'}), '(hspace=0.2, left=None, bottom=None, right=None, top=None)\n', (9940, 9998), True, 'from matplotlib import pyplot as plt\n'), ((10030, 10076), 'numpy.linspace', 'np.linspace', (['(10)', '(T - 2)', '(T - 2 - off)'], {'dtype': 'int'}), '(10, T - 2, T - 2 - off, dtype=int)\n', (10041, 10076), True, 'import numpy as np\n'), ((2320, 2339), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (2330, 2339), False, 'import csv\n'), ((2577, 2596), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (2587, 2596), False, 'import csv\n'), ((5035, 5060), 'numpy.array', 'np.array', (['station_data[i]'], {}), '(station_data[i])\n', (5043, 5060), True, 'import numpy as np\n'), ((6437, 6464), 'numpy.zeros', 'np.zeros', (['(7, num_stations)'], {}), '((7, num_stations))\n', (6445, 6464), True, 'import numpy as np\n'), ((7988, 8009), 'numpy.mean', 'np.mean', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (7995, 8009), True, 'import numpy as np\n'), ((8258, 8296), 'numpy.union1d', 'np.union1d', (['model_labels', 'model_labels'], {}), '(model_labels, model_labels)\n', (8268, 8296), True, 'import numpy as np\n'), ((9275, 9301), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (9293, 9301), False, 'import datetime\n'), ((2879, 2895), 'numpy.array', 'np.array', (['pw_d_r'], {}), '(pw_d_r)\n', (2887, 2895), True, 'import numpy as np\n'), ((2954, 2970), 'numpy.array', 'np.array', (['pw_d_e'], {}), '(pw_d_e)\n', (2962, 2970), True, 'import numpy as np\n'), ((4457, 4476), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (4467, 4476), False, 'import csv\n'), ((7296, 7328), 'numpy.zeros', 'np.zeros', (['(12 * 7, num_stations)'], {}), '((12 * 7, num_stations))\n', (7304, 7328), True, 'import numpy as np\n'), ((9411, 9452), 'datetime.date', 'datetime.date', ([], {'year': '(2003)', 'month': '(2)', 'day': '(17)'}), '(year=2003, month=2, day=17)\n', (9424, 9452), False, 'import datetime\n'), ((5758, 5785), 'numpy.zeros', 'np.zeros', (['(7, num_stations)'], {}), '((7, num_stations))\n', (5766, 5785), True, 'import numpy as np\n'), ((6918, 6951), 'numpy.mean', 'np.mean', (['data[selection, station]'], {}), '(data[selection, station])\n', (6925, 6951), True, 'import numpy as np\n'), ((7913, 7934), 'numpy.mean', 'np.mean', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (7920, 7934), True, 'import numpy as np\n'), ((7944, 7964), 'numpy.var', 'np.var', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (7950, 7964), True, 'import numpy as np\n'), ((7729, 7762), 'numpy.mean', 'np.mean', (['data[selection, station]'], {}), '(data[selection, station])\n', (7736, 7762), True, 'import numpy as np\n'), ((3382, 3436), 'numpy.where', 'np.where', (['(pw_distances_road[location, :] > larger_than)'], {}), '(pw_distances_road[location, :] > larger_than)\n', (3390, 3436), True, 'import numpy as np\n'), ((3449, 3504), 'numpy.where', 'np.where', (['(pw_distances_road[location, :] < smaller_than)'], {}), '(pw_distances_road[location, :] < smaller_than)\n', (3457, 3504), True, 'import numpy as np\n'), ((3864, 3920), 'numpy.where', 'np.where', (['(pw_distances_euclid[location, :] > larger_than)'], {}), '(pw_distances_euclid[location, :] > larger_than)\n', (3872, 3920), True, 'import numpy as np\n'), ((3933, 3990), 'numpy.where', 'np.where', (['(pw_distances_euclid[location, :] < smaller_than)'], {}), '(pw_distances_euclid[location, :] < smaller_than)\n', (3941, 3990), True, 'import numpy as np\n'), ((6222, 6255), 'numpy.mean', 'np.mean', (['data[selection, station]'], {}), '(data[selection, station])\n', (6229, 6255), True, 'import numpy as np\n')]
|
r"""Summary objects at the end of training procedures."""
import numpy as np
import pickle
import torch
class TrainingSummary:
def __init__(self,
model_best,
model_final,
epochs,
epoch_best,
losses_train,
losses_test=None,
identifier=None):
self.identifier = identifier
self.epochs = epochs
self.model_best = model_best
self.model_final = model_final
self.epoch_best = epoch_best
self.losses_train = losses_train
self.losses_test = losses_test
def save(self, path):
summary = {
"identifier": self.identifier,
"best_model": self.model_best,
"final_model": self.model_final,
"epochs": self.epochs,
"best_epoch": self.epoch_best,
"training_losses": self.losses_train,
"testing_losses": self.losses_test}
torch.save(summary, path)
def load(self, path):
summary = torch.load(path)
self.identifier = summary["identifier"]
self.model_best = summary["best_model"]
self.model_final = summary["final_model"]
self.epochs = summary["epochs"]
self.epoch_best = summary["best_epoch"]
self.losses_train = summary["training_losses"]
self.losses_test = summary["testing_losses"]
def test_losses_available(self):
return self.losses_test is not None and len(self.losses_test) > 0
def identifier_available(self):
return self.identifier is not None
def num_epochs(self):
return self.epochs
def best_epoch(self):
return self.epoch_best
def best_model(self):
return self.model_best
def final_model(self):
return self.model_final
def test_losses(self, log=False):
if log:
losses = np.log(self.losses_test)
else:
losses = self.losses_test
return losses
def train_losses(self, log=False):
if log:
losses = np.log(self.losses_train)
else:
losses = self.losses_train
return losses
def __str__(self):
representation = ""
if self.identifier_available():
representation = "Identifier:\t\t{}\n".format(self.identifier)
representation = representation + "Total epochs:\t\t{}\n".format(self.epochs) + \
"Best training loss:\t{}\n".format(self.losses_train.min()) + \
"Final training loss:\t{}".format(self.losses_train[-1])
if self.test_losses_available():
representation = representation + \
"\nBest testing loss:\t{}\n".format(self.losses_test.min()) + \
"Best test epoch:\t{}\n".format(self.epoch_best) + \
"Final test loss:\t{}".format(self.losses_test[-1])
return representation
|
[
"torch.save",
"torch.load",
"numpy.log"
] |
[((927, 952), 'torch.save', 'torch.save', (['summary', 'path'], {}), '(summary, path)\n', (937, 952), False, 'import torch\n'), ((998, 1014), 'torch.load', 'torch.load', (['path'], {}), '(path)\n', (1008, 1014), False, 'import torch\n'), ((1855, 1879), 'numpy.log', 'np.log', (['self.losses_test'], {}), '(self.losses_test)\n', (1861, 1879), True, 'import numpy as np\n'), ((2032, 2057), 'numpy.log', 'np.log', (['self.losses_train'], {}), '(self.losses_train)\n', (2038, 2057), True, 'import numpy as np\n')]
|
from functools import reduce
import scipy.ndimage as nd
import numpy as np
def convert_to_img_frame(img, node_position, mesh, borders, settings):
local_node_pos = np.zeros((2, mesh.element_def.n_nodes), dtype=settings.precision)
# Partition image
image_frame = extract_subframe(img, borders, settings.pad)
# Determine nodal positions in image frame coordinates
local_node_pos[0, :] = node_position[0] + settings.pad - borders[0, :]
local_node_pos[1, :] = node_position[1] + settings.pad - borders[2, :]
return image_frame, local_node_pos
def generate_edge_coordinates(seed):
seeding = np.linspace(0., 1., seed)
es, ns = np.meshgrid(seeding, seeding)
mask = np.ones_like(es, dtype=np.bool)
mask[1:-1, 1:-1] = 0
return es[mask], ns[mask]
def find_element_borders(node_position, mesh, seed=20):
e, n = generate_edge_coordinates(seed)
N_at_borders = mesh.element_def.Nn(e.flatten(), n.flatten())
# Find global coordinates of elements
pixel_x = np.einsum("jk,k->j", N_at_borders, node_position[0])
pixel_y = np.einsum("jk,k->j", N_at_borders, node_position[1])
axis = None
# [Xmin_Xmax,Ymin,Ymax,elm_nr]
borders = np.zeros((4, mesh.n_elms), dtype=np.int)
borders[0, :] = np.min(pixel_x, axis=axis)
borders[1, :] = np.max(pixel_x, axis=axis)
borders[2, :] = np.min(pixel_y, axis=axis)
borders[3, :] = np.max(pixel_y, axis=axis)
return borders
def extract_subframe(img, borders, pad):
return img[borders[2, 0] - pad:borders[3, 0] + pad, borders[0, 0] - pad:borders[1, 0] + pad]
def find_borders(coord):
return int(np.min(np.floor(coord))), int(np.max(np.ceil(coord)))
def find_inconsistent(ep, ny):
rem1 = np.where(ep > 1.)
rem2 = np.where(ep < 0.)
rem3 = np.where(ny > 1.)
rem4 = np.where(ny < 0.)
return reduce(np.union1d, [rem1[0], rem2[0], rem3[0], rem4[0]])
def extract_points_from_image(image, coordinates):
return nd.map_coordinates(image, coordinates, order=3, prefilter=True)
def image_coordinates(image):
xs, ys = np.meshgrid(np.arange(image.shape[0]), np.arange(image.shape[1]))
return xs,ys
|
[
"numpy.meshgrid",
"numpy.ones_like",
"numpy.ceil",
"numpy.floor",
"numpy.zeros",
"numpy.einsum",
"numpy.min",
"numpy.max",
"numpy.where",
"numpy.arange",
"numpy.linspace",
"functools.reduce",
"scipy.ndimage.map_coordinates"
] |
[((169, 234), 'numpy.zeros', 'np.zeros', (['(2, mesh.element_def.n_nodes)'], {'dtype': 'settings.precision'}), '((2, mesh.element_def.n_nodes), dtype=settings.precision)\n', (177, 234), True, 'import numpy as np\n'), ((624, 651), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', 'seed'], {}), '(0.0, 1.0, seed)\n', (635, 651), True, 'import numpy as np\n'), ((663, 692), 'numpy.meshgrid', 'np.meshgrid', (['seeding', 'seeding'], {}), '(seeding, seeding)\n', (674, 692), True, 'import numpy as np\n'), ((704, 735), 'numpy.ones_like', 'np.ones_like', (['es'], {'dtype': 'np.bool'}), '(es, dtype=np.bool)\n', (716, 735), True, 'import numpy as np\n'), ((1014, 1066), 'numpy.einsum', 'np.einsum', (['"""jk,k->j"""', 'N_at_borders', 'node_position[0]'], {}), "('jk,k->j', N_at_borders, node_position[0])\n", (1023, 1066), True, 'import numpy as np\n'), ((1081, 1133), 'numpy.einsum', 'np.einsum', (['"""jk,k->j"""', 'N_at_borders', 'node_position[1]'], {}), "('jk,k->j', N_at_borders, node_position[1])\n", (1090, 1133), True, 'import numpy as np\n'), ((1200, 1240), 'numpy.zeros', 'np.zeros', (['(4, mesh.n_elms)'], {'dtype': 'np.int'}), '((4, mesh.n_elms), dtype=np.int)\n', (1208, 1240), True, 'import numpy as np\n'), ((1261, 1287), 'numpy.min', 'np.min', (['pixel_x'], {'axis': 'axis'}), '(pixel_x, axis=axis)\n', (1267, 1287), True, 'import numpy as np\n'), ((1308, 1334), 'numpy.max', 'np.max', (['pixel_x'], {'axis': 'axis'}), '(pixel_x, axis=axis)\n', (1314, 1334), True, 'import numpy as np\n'), ((1355, 1381), 'numpy.min', 'np.min', (['pixel_y'], {'axis': 'axis'}), '(pixel_y, axis=axis)\n', (1361, 1381), True, 'import numpy as np\n'), ((1402, 1428), 'numpy.max', 'np.max', (['pixel_y'], {'axis': 'axis'}), '(pixel_y, axis=axis)\n', (1408, 1428), True, 'import numpy as np\n'), ((1729, 1747), 'numpy.where', 'np.where', (['(ep > 1.0)'], {}), '(ep > 1.0)\n', (1737, 1747), True, 'import numpy as np\n'), ((1758, 1776), 'numpy.where', 'np.where', (['(ep < 0.0)'], {}), '(ep < 0.0)\n', (1766, 1776), True, 'import numpy as np\n'), ((1787, 1805), 'numpy.where', 'np.where', (['(ny > 1.0)'], {}), '(ny > 1.0)\n', (1795, 1805), True, 'import numpy as np\n'), ((1816, 1834), 'numpy.where', 'np.where', (['(ny < 0.0)'], {}), '(ny < 0.0)\n', (1824, 1834), True, 'import numpy as np\n'), ((1845, 1901), 'functools.reduce', 'reduce', (['np.union1d', '[rem1[0], rem2[0], rem3[0], rem4[0]]'], {}), '(np.union1d, [rem1[0], rem2[0], rem3[0], rem4[0]])\n', (1851, 1901), False, 'from functools import reduce\n'), ((1965, 2028), 'scipy.ndimage.map_coordinates', 'nd.map_coordinates', (['image', 'coordinates'], {'order': '(3)', 'prefilter': '(True)'}), '(image, coordinates, order=3, prefilter=True)\n', (1983, 2028), True, 'import scipy.ndimage as nd\n'), ((2085, 2110), 'numpy.arange', 'np.arange', (['image.shape[0]'], {}), '(image.shape[0])\n', (2094, 2110), True, 'import numpy as np\n'), ((2112, 2137), 'numpy.arange', 'np.arange', (['image.shape[1]'], {}), '(image.shape[1])\n', (2121, 2137), True, 'import numpy as np\n'), ((1638, 1653), 'numpy.floor', 'np.floor', (['coord'], {}), '(coord)\n', (1646, 1653), True, 'import numpy as np\n'), ((1668, 1682), 'numpy.ceil', 'np.ceil', (['coord'], {}), '(coord)\n', (1675, 1682), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
import os
import random
from torch.utils.data import Dataset
from PIL import Image
import numpy as np
from datasets.data_io import get_transform, read_all_lines
from datasets.data_io import *
import torchvision.transforms as transforms
import torch
import torch.nn as nn
class LapaPngPng(Dataset):
def __init__(self, datapath, list_filename, training, crop_h, crop_w, channel):
self.datapath = datapath
self.ori_filenames, self.gt_filenames = self.load_path(list_filename)
self.training = training
self.crop_h = crop_h
self.crop_w = crop_w
self.channel = channel
self.transform_img = transforms.Compose(
[
transforms.Resize(size=(self.crop_h, self.crop_w)), # Resize:尺寸随意变大变小; h, w
]
)
# error:Floating point exception(core dumped)
self.processed_color = transforms.Compose([transforms.ColorJitter(brightness=0.5, contrast=0.5),
transforms.ToTensor(), #transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
def load_path(self, list_filename):
lines = read_all_lines(list_filename)
splits = [line.split() for line in lines]
ori_images = [x[0] for x in splits]
gt_images = [x[1] for x in splits]
return ori_images, gt_images
# load rgb-color
def load_image(self, filename):
if self.channel == 3:
return Image.open(filename).convert('RGB')
elif self.channel == 1:
return Image.open(filename).convert('L')
def load_img(self, filename):
return Image.open(filename).convert('L')
def __len__(self):
return len(self.ori_filenames)
# augmentation
def augment_image_pair(self, left_image):
# randomly shift gamma
random_gamma = torch.rand(1).numpy()[0] * 0.4 + 0.8 # random.uniform(0.8, 1.2)
left_image_aug = left_image ** random_gamma
# randomly shift brightness
random_brightness = torch.rand(1).numpy()[0] * 1.5 + 0.5 # random.uniform(0.5, 2.0)
left_image_aug = left_image_aug * random_brightness
# randomly shift color
if self.channel == 3:
random_colors = (torch.rand(1).numpy()[0] * 0.4 + 0.8, torch.rand(1).numpy()[0] * 0.4 + 0.8,
torch.rand(1).numpy()[0] * 0.4 + 0.8)
white = torch.ones(left_image.shape[1], left_image.shape[2])
color_image = torch.stack((white * random_colors[0], white * random_colors[1], white * random_colors[2]),dim=0)
left_image_aug *= color_image
# saturate
left_image_aug = torch.clamp(left_image_aug, 0, 1)
return left_image_aug
def __getitem__(self, index):
ori_img = self.load_image(os.path.join(self.datapath, self.ori_filenames[index]))
# img_np = np.asarray(ori_img, dtype=float)
# print(img_np.shape)
# print(img_np.dtype)
# ori_img = Image.fromarray(img_np, mode='RGB')
gt_img = self.load_img(os.path.join(self.datapath, self.gt_filenames[index]))
# add -png.name
ori_pathname = self.ori_filenames[index]
if self.training:
w, h = ori_img.size
if w < self.crop_w or h < self.crop_h:
# 图片尺寸比预设的裁剪尺寸小,先同步做resize
ori_img = self.transform_img(ori_img)
gt_img = self.transform_img(gt_img)
# to tensor, normalize --转为tensor归一化
ori_img = self.processed_color(ori_img)
gt_img = np.array(gt_img, dtype='int64')
gt_img = torch.from_numpy(gt_img)
gt_img = torch.squeeze(gt_img).long()
# gt_img = gt_img.squeeze(0) # (h, w)
# randomly images
# do_augment = torch.rand(1).numpy()[0]
# if do_augment > 0.5:
# ori_img = self.augment_image_pair(ori_img)
return {"ori": ori_img,
"gt": gt_img}
# random crop --同步裁剪
x1 = random.randint(0, w - self.crop_w)
y1 = random.randint(0, h - self.crop_h)
ori_img = ori_img.crop((x1, y1, x1 + self.crop_w, y1 + self.crop_h))
gt_img = gt_img.crop((x1, y1, x1 + self.crop_w, y1 + self.crop_h))
# to tensor, normalize --转为tensor
ori_img = self.processed_color(ori_img)
# GT转为tensor时不做归一化
gt_img = np.array(gt_img, dtype='int64')
gt_img = torch.from_numpy(gt_img)
gt_img = torch.squeeze(gt_img).long()
# gt_img = gt_img.squeeze(0) # (h, w)
# randomly images
# do_augment = torch.rand(1).numpy()[0]
# if do_augment > 0.5:
# ori_img = self.augment_image_pair(ori_img)
return {"ori": ori_img,
"gt": gt_img}
else:
w, h = ori_img.size
if w < self.crop_w or h < self.crop_h:
# 图片尺寸比预设的裁剪尺寸小,先同步做resize
ori_img = self.transform_img(ori_img)
gt_img = self.transform_img(gt_img)
# to tensor, normalize --转为tensor归一化
ori_img = self.processed_color(ori_img)
gt_img = np.array(gt_img, dtype='int64')
gt_img = torch.from_numpy(gt_img)
gt_img = torch.squeeze(gt_img).long()
# gt_img = gt_img.squeeze(0) # (h, w)
# randomly images
# do_augment = torch.rand(1).numpy()[0]
# if do_augment > 0.5:
# ori_img = self.augment_image_pair(ori_img)
return {"ori": ori_img,
"gt": gt_img,
"img_name": ori_pathname}
x1 = w - self.crop_w
y1 = h - self.crop_h
ori_img = ori_img.crop((x1, y1, x1 + self.crop_w, y1 + self.crop_h))
gt_img = gt_img.crop((x1, y1, x1 + self.crop_w, y1 + self.crop_h))
# to tensor, normalize --转为tensor
ori_img = self.processed_color(ori_img)
# GT转为tensor时不做归一化
gt_img = np.array(gt_img, dtype='int64')
gt_img = torch.from_numpy(gt_img)
gt_img = torch.squeeze(gt_img).long()
return {"ori": ori_img,
"gt": gt_img,
"img_name": ori_pathname}
|
[
"torchvision.transforms.ColorJitter",
"torch.ones",
"torch.stack",
"random.randint",
"datasets.data_io.read_all_lines",
"torchvision.transforms.ToTensor",
"PIL.Image.open",
"torch.squeeze",
"torch.clamp",
"numpy.array",
"torch.rand",
"torchvision.transforms.Resize",
"os.path.join",
"torch.from_numpy"
] |
[((1218, 1247), 'datasets.data_io.read_all_lines', 'read_all_lines', (['list_filename'], {}), '(list_filename)\n', (1232, 1247), False, 'from datasets.data_io import get_transform, read_all_lines\n'), ((2742, 2775), 'torch.clamp', 'torch.clamp', (['left_image_aug', '(0)', '(1)'], {}), '(left_image_aug, 0, 1)\n', (2753, 2775), False, 'import torch\n'), ((2478, 2530), 'torch.ones', 'torch.ones', (['left_image.shape[1]', 'left_image.shape[2]'], {}), '(left_image.shape[1], left_image.shape[2])\n', (2488, 2530), False, 'import torch\n'), ((2557, 2659), 'torch.stack', 'torch.stack', (['(white * random_colors[0], white * random_colors[1], white * random_colors[2])'], {'dim': '(0)'}), '((white * random_colors[0], white * random_colors[1], white *\n random_colors[2]), dim=0)\n', (2568, 2659), False, 'import torch\n'), ((2877, 2931), 'os.path.join', 'os.path.join', (['self.datapath', 'self.ori_filenames[index]'], {}), '(self.datapath, self.ori_filenames[index])\n', (2889, 2931), False, 'import os\n'), ((3135, 3188), 'os.path.join', 'os.path.join', (['self.datapath', 'self.gt_filenames[index]'], {}), '(self.datapath, self.gt_filenames[index])\n', (3147, 3188), False, 'import os\n'), ((4178, 4212), 'random.randint', 'random.randint', (['(0)', '(w - self.crop_w)'], {}), '(0, w - self.crop_w)\n', (4192, 4212), False, 'import random\n'), ((4230, 4264), 'random.randint', 'random.randint', (['(0)', '(h - self.crop_h)'], {}), '(0, h - self.crop_h)\n', (4244, 4264), False, 'import random\n'), ((4578, 4609), 'numpy.array', 'np.array', (['gt_img'], {'dtype': '"""int64"""'}), "(gt_img, dtype='int64')\n", (4586, 4609), True, 'import numpy as np\n'), ((4631, 4655), 'torch.from_numpy', 'torch.from_numpy', (['gt_img'], {}), '(gt_img)\n', (4647, 4655), False, 'import torch\n'), ((6288, 6319), 'numpy.array', 'np.array', (['gt_img'], {'dtype': '"""int64"""'}), "(gt_img, dtype='int64')\n", (6296, 6319), True, 'import numpy as np\n'), ((6341, 6365), 'torch.from_numpy', 'torch.from_numpy', (['gt_img'], {}), '(gt_img)\n', (6357, 6365), False, 'import torch\n'), ((724, 774), 'torchvision.transforms.Resize', 'transforms.Resize', ([], {'size': '(self.crop_h, self.crop_w)'}), '(size=(self.crop_h, self.crop_w))\n', (741, 774), True, 'import torchvision.transforms as transforms\n'), ((932, 984), 'torchvision.transforms.ColorJitter', 'transforms.ColorJitter', ([], {'brightness': '(0.5)', 'contrast': '(0.5)'}), '(brightness=0.5, contrast=0.5)\n', (954, 984), True, 'import torchvision.transforms as transforms\n'), ((1022, 1043), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1041, 1043), True, 'import torchvision.transforms as transforms\n'), ((1700, 1720), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (1710, 1720), False, 'from PIL import Image\n'), ((3661, 3692), 'numpy.array', 'np.array', (['gt_img'], {'dtype': '"""int64"""'}), "(gt_img, dtype='int64')\n", (3669, 3692), True, 'import numpy as np\n'), ((3718, 3742), 'torch.from_numpy', 'torch.from_numpy', (['gt_img'], {}), '(gt_img)\n', (3734, 3742), False, 'import torch\n'), ((5392, 5423), 'numpy.array', 'np.array', (['gt_img'], {'dtype': '"""int64"""'}), "(gt_img, dtype='int64')\n", (5400, 5423), True, 'import numpy as np\n'), ((5449, 5473), 'torch.from_numpy', 'torch.from_numpy', (['gt_img'], {}), '(gt_img)\n', (5465, 5473), False, 'import torch\n'), ((1529, 1549), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (1539, 1549), False, 'from PIL import Image\n'), ((4677, 4698), 'torch.squeeze', 'torch.squeeze', (['gt_img'], {}), '(gt_img)\n', (4690, 4698), False, 'import torch\n'), ((6387, 6408), 'torch.squeeze', 'torch.squeeze', (['gt_img'], {}), '(gt_img)\n', (6400, 6408), False, 'import torch\n'), ((1616, 1636), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (1626, 1636), False, 'from PIL import Image\n'), ((3768, 3789), 'torch.squeeze', 'torch.squeeze', (['gt_img'], {}), '(gt_img)\n', (3781, 3789), False, 'import torch\n'), ((5499, 5520), 'torch.squeeze', 'torch.squeeze', (['gt_img'], {}), '(gt_img)\n', (5512, 5520), False, 'import torch\n'), ((1917, 1930), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (1927, 1930), False, 'import torch\n'), ((2099, 2112), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (2109, 2112), False, 'import torch\n'), ((2315, 2328), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (2325, 2328), False, 'import torch\n'), ((2353, 2366), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (2363, 2366), False, 'import torch\n'), ((2420, 2433), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (2430, 2433), False, 'import torch\n')]
|
# Confidential, Copyright 2020, Sony Corporation of America, All rights reserved.
from typing import List, Optional, Sequence, Union
import numpy as np
from tqdm import trange
from .setup_sim_env import make_gym_env
from ..data.interfaces import ExperimentDataSaver, StageSchedule
from ..environment import PandemicSimOpts, PandemicSimNonCLIOpts, NoPandemicDone, PandemicRegulation, austin_regulations
from ..utils import shallow_asdict
__all__ = ['experiment_main', 'seeded_experiment_main']
def seeded_experiment_main(exp_id: int,
sim_opts: PandemicSimOpts,
sim_non_cli_opts: PandemicSimNonCLIOpts,
data_saver: ExperimentDataSaver,
pandemic_regulations: Optional[List[PandemicRegulation]] = None,
stages_to_execute: Union[int, Sequence[StageSchedule]] = 0,
enable_warm_up: bool = False,
max_episode_length: int = 120,
random_seed: int = 0) -> bool:
"""A helper that runs an experiment with the given seed and records data"""
rng = np.random.RandomState(random_seed)
env = make_gym_env(sim_opts, sim_non_cli_opts,
pandemic_regulations=pandemic_regulations or austin_regulations,
done_fn=NoPandemicDone(30), numpy_rng=rng)
env.reset()
stages = ([StageSchedule(stage=stages_to_execute, end_day=None)]
if isinstance(stages_to_execute, int) else stages_to_execute)
stage_dict = {f'stage_{i}': (s.stage, s.end_day if s.end_day is not None else -1)
for i, s in enumerate(stages)}
data_saver.begin(env.observation)
stage_idx = 0
warm_up_done = not enable_warm_up
for i in trange(max_episode_length, desc='Simulating day'):
if not env.observation.infection_above_threshold and not warm_up_done:
stage = 0
else:
warm_up_done = True
cur_stage = stages[stage_idx]
stage = cur_stage.stage
if cur_stage.end_day is not None and cur_stage.end_day <= i:
stage_idx += 1
obs, reward, done, aux = env.step(stage)
data_saver.record(obs, reward)
if done:
print('done')
break
return data_saver.finalize(exp_id=exp_id,
seed=random_seed,
num_stages_to_execute=len(stages),
num_persons=sim_non_cli_opts.population_params.num_persons,
**stage_dict,
**shallow_asdict(sim_opts))
def experiment_main(exp_id: int,
sim_opts: PandemicSimOpts,
sim_non_cli_opts: PandemicSimNonCLIOpts,
data_saver: ExperimentDataSaver,
pandemic_regulations: Optional[List[PandemicRegulation]] = None,
stages_to_execute: Union[int, Sequence[StageSchedule]] = 0,
enable_warm_up: bool = False,
max_episode_length: int = 120,
num_random_seeds: int = 5) -> None:
"""A helper that runs multi-seeded experiments and records data."""
rng = np.random.RandomState(seed=0)
num_evaluated_seeds = 0
while num_evaluated_seeds < num_random_seeds:
seed = rng.randint(0, 100000)
print(f'Running experiment seed: {seed} - {num_evaluated_seeds + 1}/{num_random_seeds}')
ret = seeded_experiment_main(exp_id=exp_id,
sim_opts=sim_opts,
sim_non_cli_opts=sim_non_cli_opts,
data_saver=data_saver,
pandemic_regulations=pandemic_regulations,
stages_to_execute=stages_to_execute,
enable_warm_up=enable_warm_up,
max_episode_length=max_episode_length,
random_seed=seed)
if ret:
num_evaluated_seeds += 1
else:
print(f'Experiment with seed {seed} did not succeed. Skipping...')
|
[
"numpy.random.RandomState",
"tqdm.trange"
] |
[((1163, 1197), 'numpy.random.RandomState', 'np.random.RandomState', (['random_seed'], {}), '(random_seed)\n', (1184, 1197), True, 'import numpy as np\n'), ((1810, 1859), 'tqdm.trange', 'trange', (['max_episode_length'], {'desc': '"""Simulating day"""'}), "(max_episode_length, desc='Simulating day')\n", (1816, 1859), False, 'from tqdm import trange\n'), ((3297, 3326), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(0)'}), '(seed=0)\n', (3318, 3326), True, 'import numpy as np\n')]
|
import numpy as np
from math import *
from interpolation import InterpVec
class Target(object):
@classmethod
def get_simple_target(cls, pos, vel):
velocity_vectors = [[0, np.array(vel)]]
vel_interp = InterpVec(velocity_vectors)
target = cls(vel_interp=vel_interp)
parameters_of_target = np.array([pos[0], pos[1], 0])
target.set_init_cond(parameters_of_target=parameters_of_target)
return target
def __init__(self, *args, **kwargs):
self.g = kwargs.get('g', 9.80665)
self.dt = kwargs.get('dt', 0.001)
self.vel_interp = kwargs['vel_interp']
def set_init_cond(self, parameters_of_target=None):
if parameters_of_target is None:
parameters_of_target = self.get_standart_parameters_of_target()
self.state = np.array(parameters_of_target)
self.state_0 = np.array(parameters_of_target)
def reset(self):
self.set_state(self.state_0)
def set_state(self, state):
self.state = np.array(state)
def get_state(self):
return self.state
def get_state_0(self):
return self.state_0
def step(self, tau):
x, y, t = self.state
t_end = t + tau
flag = True
while flag:
if t_end - t > self.dt:
dt = self.dt
else:
dt = t_end - t
flag = False
t += dt
vx, vy = self.vel_interp(t)
x += vx * dt
y += vy * dt
self.set_state([x, y, t])
@property
def pos(self):
return self.state[:2]
@property
def vel(self):
return self.vel_interp(self.t)
@property
def t(self):
return self.state[-1]
@property
def Q(self):
vx, vy = self.vel_interp(self.t)
return np.sqrt(vx ** 2 + vy ** 2)
@property
def v(self):
vx, vy = self.vel_interp(self.t)
return np.sqrt(vx ** 2 + vy ** 2)
@property
def x(self):
return self.pos[0]
@property
def y(self):
return self.pos[1]
def get_summary(self):
return {
't': self.t,
'v': self.v,
'x': self.x,
'y': self.y,
'Q': np.degrees(self.Q)
}
|
[
"interpolation.InterpVec",
"numpy.array",
"numpy.degrees",
"numpy.sqrt"
] |
[((233, 260), 'interpolation.InterpVec', 'InterpVec', (['velocity_vectors'], {}), '(velocity_vectors)\n', (242, 260), False, 'from interpolation import InterpVec\n'), ((336, 365), 'numpy.array', 'np.array', (['[pos[0], pos[1], 0]'], {}), '([pos[0], pos[1], 0])\n', (344, 365), True, 'import numpy as np\n'), ((831, 861), 'numpy.array', 'np.array', (['parameters_of_target'], {}), '(parameters_of_target)\n', (839, 861), True, 'import numpy as np\n'), ((885, 915), 'numpy.array', 'np.array', (['parameters_of_target'], {}), '(parameters_of_target)\n', (893, 915), True, 'import numpy as np\n'), ((1029, 1044), 'numpy.array', 'np.array', (['state'], {}), '(state)\n', (1037, 1044), True, 'import numpy as np\n'), ((1860, 1886), 'numpy.sqrt', 'np.sqrt', (['(vx ** 2 + vy ** 2)'], {}), '(vx ** 2 + vy ** 2)\n', (1867, 1886), True, 'import numpy as np\n'), ((1975, 2001), 'numpy.sqrt', 'np.sqrt', (['(vx ** 2 + vy ** 2)'], {}), '(vx ** 2 + vy ** 2)\n', (1982, 2001), True, 'import numpy as np\n'), ((2283, 2301), 'numpy.degrees', 'np.degrees', (['self.Q'], {}), '(self.Q)\n', (2293, 2301), True, 'import numpy as np\n'), ((196, 209), 'numpy.array', 'np.array', (['vel'], {}), '(vel)\n', (204, 209), True, 'import numpy as np\n')]
|
import os
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import time
from collections import namedtuple
import caffe
from lib import run_net
from lib import score_util
from datasets.pascal_voc import Pascal
PV = Pascal('C:\\ALISURE\\Data\\voc\\VOCdevkit\\VOC2012')
val_set = PV.get_data_set()
def show_demo():
image_name_0 = val_set[0]
im, label = PV.load_image(image_name_0), PV.load_label(image_name_0)
im_t, label_t = PV.make_translated_frames(im, label, shift=32, num_frames=6)
plt.rcParams['image.cmap'] = 'gray'
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['figure.figsize'] = (12, 12)
plt.figure()
for i, im in enumerate(im_t):
plt.subplot(3, len(im_t), i + 1)
plt.imshow(im)
plt.axis('off')
plt.subplot(3, len(label_t), len(im_t) + i + 1)
plt.imshow(PV.palette(label_t[i]))
plt.axis('off')
plt.subplot(3, len(label_t), 2 * len(im_t) + 2)
plt.imshow(PV.palette(label))
plt.axis('off')
plt.subplot(3, len(label_t), 2 * len(im_t) + 5)
plt.imshow(PV.make_boundaries(label, thickness=2))
plt.axis('off')
plt.show()
class_number = len(PV.classes)
num_frames = 6
thickness = 5
shifts = (16, 32)
Method = namedtuple('Method', 'method arch weights infer_func, input_offset')
fcn = Method('fcn', '../nets/voc-fcn8s.prototxt',
'../nets/voc-fcn8s-heavy.caffemodel', run_net.segrun, 2)
baseline_3stage = Method('baseline_3stage', '../nets/voc-fcn-pool3.prototxt',
'../nets/voc-fcn-pool3.caffemodel', run_net.segrun, 2)
baseline_2stage = Method('baseline_2stage', '../nets/voc-fcn-pool4.prototxt',
'../nets/voc-fcn-pool4.caffemodel', run_net.segrun, 2)
pipeline_3stage = Method('pipeline_3stage', '../nets/stage-voc-fcn8s.prototxt',
'../nets/voc-fcn8s-heavy.caffemodel', run_net.pipeline_3stage_forward, 0)
pipeline_2stage = Method('pipeline_2stage', '../nets/stage-voc-fcn8s.prototxt',
'../nets/voc-fcn8s-heavy.caffemodel', run_net.pipeline_2stage_forward, 1)
def score_translations(method, shift, arch, weights, infer, offset):
"""
Score the translated "video" of PASCAL VOC seg11valid images
taking care of the net architecture and weights, the particular inference method,
and the input offset needed to align every frame and pipeline methods.
"""
net = caffe.Net(arch, weights, caffe.TEST)
hist, hist_b = np.zeros((class_number, class_number)), np.zeros((class_number, class_number))
for index, image_name in enumerate(val_set[0: 10]):
print("{} begin {}".format(time.strftime("%H:%M:%S", time.localtime()), index))
im, label = PV.load_image(image_name), PV.load_label(image_name)
im_frames, label_frames = PV.make_translated_frames(im, label, shift=shift, num_frames=num_frames)
im_frames, label_frames = im_frames[offset:], label_frames[offset:]
# prepare pipelines: feed initial inputs then skip accordingly
if method == 'pipeline_3stage':
run_net.pipeline_fill_3stage(net, PV.pre_process(im_frames[0]), PV.pre_process(im_frames[1]))
im_frames, label_frames = im_frames[2:], label_frames[2:]
elif method == 'pipeline_2stage':
run_net.pipeline_fill_2stage(net, PV.pre_process(im_frames[0]))
im_frames, label_frames = im_frames[1:], label_frames[1:]
for im_t, label_t in zip(im_frames, label_frames):
print("{} begin {} .....".format(time.strftime("%H:%M:%S", time.localtime()), index))
out = infer(net, PV.pre_process(im_t))
Image.fromarray(out * 12).convert("L").show()
hist += score_util.score_out_gt(out, label_t, n_cl=class_number)
bdry = PV.make_boundaries(label_t, thickness=thickness)
hist_b += score_util.score_out_gt_bdry(out, label_t, bdry, n_cl=class_number)
pass
for name, h in zip(('seg', 'bdry'), (hist, hist_b)):
accP, cl_accP, mean_iuP, fw_iuP = score_util.get_scores(h)
print('{}: {}, shift {}'.format(method, name, shift))
print('acc\t\t cl acc\t\t mIU\t\t fwIU')
print('{:f}\t {:f}\t {:f}\t {:f}\t'.format(100*accP, 100*cl_accP, 100*mean_iuP, 100*fw_iuP))
for shift in shifts:
for m in (fcn, baseline_3stage, pipeline_3stage, baseline_2stage, pipeline_2stage):
score_translations(m.method, shift, m.arch, m.weights, m.infer_func, m.input_offset)
"""
fcn: seg, shift 16
acc cl acc mIU fwIU
91.974863 82.881608 70.022842 85.902034
fcn: bdry, shift 16
acc cl acc mIU fwIU
63.948030 65.065930 49.555515 53.667815
baseline_3stage: seg, shift 16
acc cl acc mIU fwIU
60.286632 13.705269 4.690409 43.286493
baseline_3stage: bdry, shift 16
acc cl acc mIU fwIU
11.166320 11.496480 1.818804 3.798124
pipeline_3stage: seg, shift 16
acc cl acc mIU fwIU
88.349069 74.970788 55.175040 79.954080
pipeline_3stage: bdry, shift 16
acc cl acc mIU fwIU
56.349989 56.221222 41.709843 46.512476
baseline_2stage: seg, shift 16
acc cl acc mIU fwIU
69.464357 36.060632 13.589065 53.310369
baseline_2stage: bdry, shift 16
acc cl acc mIU fwIU
29.001448 26.982958 8.294242 19.001877
pipeline_2stage: seg, shift 16
acc cl acc mIU fwIU
90.942986 80.925445 67.604536 84.123599
pipeline_2stage: bdry, shift 16
acc cl acc mIU fwIU
61.421430 61.866688 46.878984 51.400744
baseline_3stage: seg, shift 32
acc cl acc mIU fwIU
59.179855 13.635292 4.642013 41.671485
baseline_3stage: bdry, shift 32
acc cl acc mIU fwIU
11.052108 11.406026 1.778673 3.790397
pipeline_3stage: seg, shift 32
acc cl acc mIU fwIU
82.182183 64.902390 49.651163 70.833176
pipeline_3stage: bdry, shift 32
acc cl acc mIU fwIU
50.599466 48.977500 35.428999 41.064723
"""
|
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow",
"numpy.zeros",
"matplotlib.pyplot.axis",
"datasets.pascal_voc.Pascal",
"matplotlib.pyplot.figure",
"lib.score_util.score_out_gt",
"collections.namedtuple",
"lib.score_util.score_out_gt_bdry",
"PIL.Image.fromarray",
"caffe.Net",
"lib.score_util.get_scores",
"time.localtime"
] |
[((243, 295), 'datasets.pascal_voc.Pascal', 'Pascal', (['"""C:\\\\ALISURE\\\\Data\\\\voc\\\\VOCdevkit\\\\VOC2012"""'], {}), "('C:\\\\ALISURE\\\\Data\\\\voc\\\\VOCdevkit\\\\VOC2012')\n", (249, 295), False, 'from datasets.pascal_voc import Pascal\n'), ((1270, 1338), 'collections.namedtuple', 'namedtuple', (['"""Method"""', '"""method arch weights infer_func, input_offset"""'], {}), "('Method', 'method arch weights infer_func, input_offset')\n", (1280, 1338), False, 'from collections import namedtuple\n'), ((671, 683), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (681, 683), True, 'import matplotlib.pyplot as plt\n'), ((1020, 1035), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1028, 1035), True, 'import matplotlib.pyplot as plt\n'), ((1147, 1162), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1155, 1162), True, 'import matplotlib.pyplot as plt\n'), ((1168, 1178), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1176, 1178), True, 'import matplotlib.pyplot as plt\n'), ((2456, 2492), 'caffe.Net', 'caffe.Net', (['arch', 'weights', 'caffe.TEST'], {}), '(arch, weights, caffe.TEST)\n', (2465, 2492), False, 'import caffe\n'), ((767, 781), 'matplotlib.pyplot.imshow', 'plt.imshow', (['im'], {}), '(im)\n', (777, 781), True, 'import matplotlib.pyplot as plt\n'), ((790, 805), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (798, 805), True, 'import matplotlib.pyplot as plt\n'), ((913, 928), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (921, 928), True, 'import matplotlib.pyplot as plt\n'), ((2512, 2550), 'numpy.zeros', 'np.zeros', (['(class_number, class_number)'], {}), '((class_number, class_number))\n', (2520, 2550), True, 'import numpy as np\n'), ((2552, 2590), 'numpy.zeros', 'np.zeros', (['(class_number, class_number)'], {}), '((class_number, class_number))\n', (2560, 2590), True, 'import numpy as np\n'), ((4084, 4108), 'lib.score_util.get_scores', 'score_util.get_scores', (['h'], {}), '(h)\n', (4105, 4108), False, 'from lib import score_util\n'), ((3756, 3812), 'lib.score_util.score_out_gt', 'score_util.score_out_gt', (['out', 'label_t'], {'n_cl': 'class_number'}), '(out, label_t, n_cl=class_number)\n', (3779, 3812), False, 'from lib import score_util\n'), ((3903, 3970), 'lib.score_util.score_out_gt_bdry', 'score_util.score_out_gt_bdry', (['out', 'label_t', 'bdry'], {'n_cl': 'class_number'}), '(out, label_t, bdry, n_cl=class_number)\n', (3931, 3970), False, 'from lib import score_util\n'), ((2708, 2724), 'time.localtime', 'time.localtime', ([], {}), '()\n', (2722, 2724), False, 'import time\n'), ((3599, 3615), 'time.localtime', 'time.localtime', ([], {}), '()\n', (3613, 3615), False, 'import time\n'), ((3689, 3714), 'PIL.Image.fromarray', 'Image.fromarray', (['(out * 12)'], {}), '(out * 12)\n', (3704, 3714), False, 'from PIL import Image\n')]
|
"""camera_fusion CameraCorrected class tests."""
import cv2
import os
import sys
import filecmp
import pytest
import numpy as np
import shutil
import time
import unittest.mock as mock
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import camera_fusion # noqa
class Vc(object):
"""VideoCapture mockup."""
def __init__(self, parent, real_captured_frame=None):
"""Initialize VideoCapture mockup.
Args:
parent(Camera object): parent's Camera.
"""
self.parent = parent
self.real_captured_frame = real_captured_frame
def get(self, setting):
"""Mock VideoCapture's get function only to get width and height."""
if setting == 3:
return 1280
if setting == 4:
return 720
return setting
def isOpened(self):
"""Mock VideoCapture's isOpened function."""
return True
def read(self):
"""Mock VideoCapture's read function."""
time.sleep(0.33)
self.parent.stop = True
print('1 frame')
return (True, self.real_captured_frame)
def set(self, setting0, setting1):
print(setting0, setting1)
# Import tests
def test_import_CameraCorrected():
"""Test CameraCorrected class importation."""
assert camera_fusion.CameraCorrected.__module__ == 'camera_fusion.CameraCorrected' # noqa
# PostureBuffer tests
def test_PostureBuffer():
"""Test PostureBuffer class definition."""
c = camera_fusion.CameraCorrected(0, 11)
assert c.board_post.window_length == 4
def test_PostureBuffer_pop():
"""Test PostureBuffer buffer abilities."""
rvec = np.array([[1], [0], [0]])
tvec = np.array([[1], [0], [0]])
c = camera_fusion.CameraCorrected(0, 11)
frvec, ftvec = c.board_post.update(rvec, tvec)
b_rvecs_shape = c.board_post.buff_rvecs.shape
b_tvecs_shape = c.board_post.buff_tvecs.shape
assert (frvec.shape, ftvec.shape, b_rvecs_shape, b_tvecs_shape) == (
(3,), (3,), (3, 1), (3, 1))
def test_PostureBuffer_filter():
"""Test PostureBuffer filtering."""
rvec = np.array([[0.1], [0.2], [0]])
tvec = np.array([[0.2], [0.1], [0]])
c = camera_fusion.CameraCorrected(0, 0)
frvec, ftvec = c.board_post.update(rvec, tvec)
frvec, ftvec = c.board_post.update(rvec * 0.1, tvec * 0.1)
frvec, ftvec = c.board_post.update(rvec, tvec)
# This should trigger the filter default avg_max_std=0.1 maximal limit
frvec, ftvec = c.board_post.update(rvec * 2, tvec * 2)
frvec, ftvec = c.board_post.update(rvec * 3, tvec * 3)
np.testing.assert_allclose([[0.3], [0.6], [0.0]], frvec)
np.testing.assert_allclose([[0.6], [0.3], [0.]], ftvec)
# Camera tests
def test_calibrate_camera_correction():
"""Test calibrate_camera_correction function."""
c = camera_fusion.CameraCorrected(0, 11)
assert os.path.isdir('./data')
shutil.rmtree('data')
shutil.copytree('./tests/test_CameraCorrected', 'data')
c.calibrate_camera_correction()
assert c.aruco_dict_num == 11
assert c.charuco_square_length == 3.7999999999999999e-02
assert c.charuco_marker_size == 2.9000000000000001e-02
assert c.width == 1280
assert c.height == 720
np.testing.assert_allclose(
[[1.0824122780443031e+03, 0., 6.4165850036653376e+02],
[0., 1.0824122780443031e+03, 3.5960861017399100e+02],
[0., 0., 1.]],
c.camera_matrix)
np.testing.assert_allclose(
[[7.6732549196567842e-02, -4.1976860824194072e-02, 0., 0.,
-1.8028155099783838e-01]], c.dist_coeffs)
shutil.rmtree('data')
def test_detect_markers():
"""Test the detect_markers function."""
c = camera_fusion.CameraCorrected(0, 11)
shutil.rmtree('data')
shutil.copytree('./tests/test_CameraCorrected', 'data')
c.calibrate_camera_correction()
real_captured_frame = np.load('./data/real_captured_frame.npy')
with mock.patch('camera_fusion.CameraCorrected.read',
return_value=real_captured_frame):
frame, corners, ids = c.detect_markers()
np.testing.assert_array_equal(frame, real_captured_frame)
correct_corners = np.array([
[[[1112., 506.], [1111., 374.], [1245., 368.], [1245., 500.]]],
[[[22., 194.], [11., 57.], [144., 51.], [158., 189.]]],
[[[744., 164.], [739., 23.], [878., 17.], [879., 157.]]],
[[[243., 715.], [236., 585.], [366., 580.], [373., 708.]]],
[[[591., 699.], [584., 570.], [714., 565.], [720., 694.]]],
[[[940., 688.], [934., 558.], [1067., 552.], [1072., 684.]]],
[[[57., 549.], [45., 419.], [178., 413.], [189., 543.]]],
[[[407., 534.], [399., 405.], [529., 399.], [538., 528.]]],
[[[757., 519.], [752., 390.], [884., 384.], [888., 514.]]],
[[[220., 367.], [207., 234.], [341., 228.], [351., 362.]]],
[[[573., 353.], [565., 219.], [699., 213.], [705., 347.]]],
[[[930., 337.], [927., 201.], [1062., 195.], [1065., 330.]]],
[[[383., 180.], [372., 42.], [508., 34.], [517., 175.]]]])
np.testing.assert_array_equal(corners, correct_corners)
correct_ids = np.array(
[[15], [1], [11], [2], [7], [12], [0], [5], [10], [3], [8], [13], [6]])
np.testing.assert_array_equal(ids, correct_ids)
shutil.rmtree('data')
def test_draw_fps():
"""Test draw_fps function."""
with mock.patch('time.time', return_value=0):
c = camera_fusion.CameraCorrected(0, 11)
c.width = 1280
c.height = 720
frame = np.load('./tests/test_CameraCorrected/real_captured_frame.npy')
with mock.patch('time.time', return_value=0.03):
frame = c.draw_fps(frame) # 33 fps
np.testing.assert_array_equal(np.load(
'./tests/test_CameraCorrected/real_captured_frame_with_30fps.npy'),
frame)
def test_draw_text():
"""Test draw_text function."""
c = camera_fusion.CameraCorrected(0, 11)
c.width = 1280
c.height = 720
frame = np.load('./tests/test_CameraCorrected/real_captured_frame.npy')
frame = c.draw_text(frame, 'test') # 33 fps
np.save('./tests/test_CameraCorrected/real_captured_frame_withText.npy',
frame)
np.testing.assert_array_equal(
np.load(
'./tests/test_CameraCorrected/real_captured_frame_withText.npy'),
frame)
def test_estimate_markers_posture():
"""Test the estimate_markers_posture function."""
c = camera_fusion.CameraCorrected(0, 11)
shutil.rmtree('data')
shutil.copytree('./tests/test_CameraCorrected', 'data')
c.calibrate_camera_correction()
real_captured_frame = np.load('./data/real_captured_frame.npy')
with mock.patch('camera_fusion.CameraCorrected.read',
return_value=real_captured_frame):
frame = c.estimate_markers_posture()
correct_markers_posture_frame = np.load(
'./data/correct_markers_posture_frame.npy')
np.testing.assert_array_equal(frame, correct_markers_posture_frame)
shutil.rmtree('data')
def test_estimate_board_posture():
"""Test the estimate_board_posture function."""
c = camera_fusion.CameraCorrected(0, 11)
shutil.rmtree('data')
shutil.copytree('./tests/test_CameraCorrected', 'data')
c.calibrate_camera_correction()
real_captured_frame = np.load('./data/real_captured_frame.npy')
with mock.patch('camera_fusion.CameraCorrected.read',
return_value=real_captured_frame):
frame = c.estimate_board_posture()
correct_board_posture_frame = np.load(
'./data/correct_board_posture_frame.npy')
np.testing.assert_array_equal(frame, correct_board_posture_frame)
shutil.rmtree('data')
def test_estimate_board_and_markers_posture():
"""Test the estimate_estimate_board_and_markers_posture function."""
c = camera_fusion.CameraCorrected(0, 11)
shutil.rmtree('data')
shutil.copytree('./tests/test_CameraCorrected', 'data')
c.calibrate_camera_correction()
real_captured_frame = np.load('./data/real_captured_frame.npy')
with mock.patch('camera_fusion.CameraCorrected.read',
return_value=real_captured_frame):
frame = c.estimate_board_and_markers_posture()
np.save(
'./tests/test_CameraCorrected/correct_board_and_markers_posture_frame.npy', # noqa
frame)
np.save('./data/correct_board_and_markers_posture_frame.npy',
frame)
correct_board_and_markers_posture_frame = np.load(
'./data/correct_board_and_markers_posture_frame.npy')
np.testing.assert_array_equal(
frame, correct_board_and_markers_posture_frame)
shutil.rmtree('data')
def test_initialize():
"""Test CameraCorrected's initialize function."""
c = camera_fusion.CameraCorrected(0, 11)
c.settings = [(0, 0), (1, 1), (3, 1280), (4, 720)]
frame = np.load('./tests/test_CameraCorrected/real_captured_frame.npy')
c.current_frame = frame
with mock.patch('cv2.VideoCapture', return_value=Vc(c)):
with mock.patch(
'camera_fusion.CameraCorrected.calibrate_camera_correction'):
with mock.patch('camera_fusion.CameraCorrected.read',
return_value=frame):
c.initialize()
def test_read_undistort():
"""Test the read_undistort function."""
c = camera_fusion.CameraCorrected(0, 11)
shutil.rmtree('data')
shutil.copytree('./tests/test_CameraCorrected', 'data')
c.calibrate_camera_correction()
with mock.patch('camera_fusion.CameraCorrected.read',
return_value=np.load('./data/real_captured_frame.npy')):
frame_undistored = c.read_undistort()
valid_frame_undistored = np.load('./data/real_undistored_frame.npy')
np.testing.assert_array_equal(valid_frame_undistored, frame_undistored)
shutil.rmtree('data')
def test_test_camera():
"""Test the basic camera test."""
shutil.copytree('./tests/test_CameraCorrected', 'data')
c = camera_fusion.CameraCorrected(0, 11)
c.calibrate_camera_correction()
# Testing camera setup
with mock.patch('camera_fusion.CameraCorrected.read',
return_value=np.load(
'./data/real_captured_frame.npy')):
c.test_camera()
shutil.rmtree('data')
def test__update_frame():
"""Test the _update_frame function."""
c = camera_fusion.CameraCorrected(0, 11)
c.stop = False
shutil.rmtree('data')
shutil.copytree('./tests/test_CameraCorrected', 'data')
real_captured_frame = np.load('./data/real_captured_frame.npy')
c.cap = Vc(c, real_captured_frame)
c.calibrate_camera_correction()
# Testing camera frame read and update
c.cap = Vc(c, real_captured_frame)
c._update_frame()
np.testing.assert_array_equal(c.current_frame, real_captured_frame)
shutil.rmtree('data')
# def test_write_defaultConfig():
# """Test write_defaultConfig function."""
# shutil.rmtree('data')
# c = camera_fusion.CameraCorrected(0, 11)
# c.width = 1280
# c.height = 720
# with mock.patch('builtins.input', return_value=0.03):
# c.write_defaultConfig()
# assert os.path.isfile('./data/defaultConfig.xml')
# assert filecmp.cmp(
# './data/defaultConfig.xml',
# './tests/test_CameraCorrected/defaultConfig_assert.xml')
# shutil.rmtree('data')
|
[
"numpy.load",
"numpy.save",
"shutil.copytree",
"shutil.rmtree",
"os.path.isdir",
"numpy.testing.assert_array_equal",
"os.path.dirname",
"time.sleep",
"unittest.mock.patch",
"camera_fusion.CameraCorrected",
"numpy.array",
"numpy.testing.assert_allclose"
] |
[((1520, 1556), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (1549, 1556), False, 'import camera_fusion\n'), ((1690, 1715), 'numpy.array', 'np.array', (['[[1], [0], [0]]'], {}), '([[1], [0], [0]])\n', (1698, 1715), True, 'import numpy as np\n'), ((1727, 1752), 'numpy.array', 'np.array', (['[[1], [0], [0]]'], {}), '([[1], [0], [0]])\n', (1735, 1752), True, 'import numpy as np\n'), ((1761, 1797), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (1790, 1797), False, 'import camera_fusion\n'), ((2146, 2175), 'numpy.array', 'np.array', (['[[0.1], [0.2], [0]]'], {}), '([[0.1], [0.2], [0]])\n', (2154, 2175), True, 'import numpy as np\n'), ((2187, 2216), 'numpy.array', 'np.array', (['[[0.2], [0.1], [0]]'], {}), '([[0.2], [0.1], [0]])\n', (2195, 2216), True, 'import numpy as np\n'), ((2225, 2260), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(0)'], {}), '(0, 0)\n', (2254, 2260), False, 'import camera_fusion\n'), ((2624, 2680), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['[[0.3], [0.6], [0.0]]', 'frvec'], {}), '([[0.3], [0.6], [0.0]], frvec)\n', (2650, 2680), True, 'import numpy as np\n'), ((2685, 2741), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['[[0.6], [0.3], [0.0]]', 'ftvec'], {}), '([[0.6], [0.3], [0.0]], ftvec)\n', (2711, 2741), True, 'import numpy as np\n'), ((2859, 2895), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (2888, 2895), False, 'import camera_fusion\n'), ((2907, 2930), 'os.path.isdir', 'os.path.isdir', (['"""./data"""'], {}), "('./data')\n", (2920, 2930), False, 'import os\n'), ((2935, 2956), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (2948, 2956), False, 'import shutil\n'), ((2961, 3016), 'shutil.copytree', 'shutil.copytree', (['"""./tests/test_CameraCorrected"""', '"""data"""'], {}), "('./tests/test_CameraCorrected', 'data')\n", (2976, 3016), False, 'import shutil\n'), ((3265, 3426), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['[[1082.412278044303, 0.0, 641.6585003665338], [0.0, 1082.412278044303, \n 359.608610173991], [0.0, 0.0, 1.0]]', 'c.camera_matrix'], {}), '([[1082.412278044303, 0.0, 641.6585003665338], [\n 0.0, 1082.412278044303, 359.608610173991], [0.0, 0.0, 1.0]], c.\n camera_matrix)\n', (3291, 3426), True, 'import numpy as np\n'), ((3472, 3596), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['[[0.07673254919656784, -0.04197686082419407, 0.0, 0.0, -0.18028155099783838]]', 'c.dist_coeffs'], {}), '([[0.07673254919656784, -0.04197686082419407, 0.0,\n 0.0, -0.18028155099783838]], c.dist_coeffs)\n', (3498, 3596), True, 'import numpy as np\n'), ((3622, 3643), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (3635, 3643), False, 'import shutil\n'), ((3725, 3761), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (3754, 3761), False, 'import camera_fusion\n'), ((3766, 3787), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (3779, 3787), False, 'import shutil\n'), ((3792, 3847), 'shutil.copytree', 'shutil.copytree', (['"""./tests/test_CameraCorrected"""', '"""data"""'], {}), "('./tests/test_CameraCorrected', 'data')\n", (3807, 3847), False, 'import shutil\n'), ((3910, 3951), 'numpy.load', 'np.load', (['"""./data/real_captured_frame.npy"""'], {}), "('./data/real_captured_frame.npy')\n", (3917, 3951), True, 'import numpy as np\n'), ((4118, 4175), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['frame', 'real_captured_frame'], {}), '(frame, real_captured_frame)\n', (4147, 4175), True, 'import numpy as np\n'), ((4199, 5150), 'numpy.array', 'np.array', (['[[[[1112.0, 506.0], [1111.0, 374.0], [1245.0, 368.0], [1245.0, 500.0]]], [[\n [22.0, 194.0], [11.0, 57.0], [144.0, 51.0], [158.0, 189.0]]], [[[744.0,\n 164.0], [739.0, 23.0], [878.0, 17.0], [879.0, 157.0]]], [[[243.0, 715.0\n ], [236.0, 585.0], [366.0, 580.0], [373.0, 708.0]]], [[[591.0, 699.0],\n [584.0, 570.0], [714.0, 565.0], [720.0, 694.0]]], [[[940.0, 688.0], [\n 934.0, 558.0], [1067.0, 552.0], [1072.0, 684.0]]], [[[57.0, 549.0], [\n 45.0, 419.0], [178.0, 413.0], [189.0, 543.0]]], [[[407.0, 534.0], [\n 399.0, 405.0], [529.0, 399.0], [538.0, 528.0]]], [[[757.0, 519.0], [\n 752.0, 390.0], [884.0, 384.0], [888.0, 514.0]]], [[[220.0, 367.0], [\n 207.0, 234.0], [341.0, 228.0], [351.0, 362.0]]], [[[573.0, 353.0], [\n 565.0, 219.0], [699.0, 213.0], [705.0, 347.0]]], [[[930.0, 337.0], [\n 927.0, 201.0], [1062.0, 195.0], [1065.0, 330.0]]], [[[383.0, 180.0], [\n 372.0, 42.0], [508.0, 34.0], [517.0, 175.0]]]]'], {}), '([[[[1112.0, 506.0], [1111.0, 374.0], [1245.0, 368.0], [1245.0, \n 500.0]]], [[[22.0, 194.0], [11.0, 57.0], [144.0, 51.0], [158.0, 189.0]]\n ], [[[744.0, 164.0], [739.0, 23.0], [878.0, 17.0], [879.0, 157.0]]], [[\n [243.0, 715.0], [236.0, 585.0], [366.0, 580.0], [373.0, 708.0]]], [[[\n 591.0, 699.0], [584.0, 570.0], [714.0, 565.0], [720.0, 694.0]]], [[[\n 940.0, 688.0], [934.0, 558.0], [1067.0, 552.0], [1072.0, 684.0]]], [[[\n 57.0, 549.0], [45.0, 419.0], [178.0, 413.0], [189.0, 543.0]]], [[[407.0,\n 534.0], [399.0, 405.0], [529.0, 399.0], [538.0, 528.0]]], [[[757.0, \n 519.0], [752.0, 390.0], [884.0, 384.0], [888.0, 514.0]]], [[[220.0, \n 367.0], [207.0, 234.0], [341.0, 228.0], [351.0, 362.0]]], [[[573.0, \n 353.0], [565.0, 219.0], [699.0, 213.0], [705.0, 347.0]]], [[[930.0, \n 337.0], [927.0, 201.0], [1062.0, 195.0], [1065.0, 330.0]]], [[[383.0, \n 180.0], [372.0, 42.0], [508.0, 34.0], [517.0, 175.0]]]])\n', (4207, 5150), True, 'import numpy as np\n'), ((5100, 5155), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['corners', 'correct_corners'], {}), '(corners, correct_corners)\n', (5129, 5155), True, 'import numpy as np\n'), ((5175, 5260), 'numpy.array', 'np.array', (['[[15], [1], [11], [2], [7], [12], [0], [5], [10], [3], [8], [13], [6]]'], {}), '([[15], [1], [11], [2], [7], [12], [0], [5], [10], [3], [8], [13], [6]]\n )\n', (5183, 5260), True, 'import numpy as np\n'), ((5269, 5316), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ids', 'correct_ids'], {}), '(ids, correct_ids)\n', (5298, 5316), True, 'import numpy as np\n'), ((5321, 5342), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (5334, 5342), False, 'import shutil\n'), ((5549, 5612), 'numpy.load', 'np.load', (['"""./tests/test_CameraCorrected/real_captured_frame.npy"""'], {}), "('./tests/test_CameraCorrected/real_captured_frame.npy')\n", (5556, 5612), True, 'import numpy as np\n'), ((5911, 5947), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (5940, 5947), False, 'import camera_fusion\n'), ((5998, 6061), 'numpy.load', 'np.load', (['"""./tests/test_CameraCorrected/real_captured_frame.npy"""'], {}), "('./tests/test_CameraCorrected/real_captured_frame.npy')\n", (6005, 6061), True, 'import numpy as np\n'), ((6115, 6194), 'numpy.save', 'np.save', (['"""./tests/test_CameraCorrected/real_captured_frame_withText.npy"""', 'frame'], {}), "('./tests/test_CameraCorrected/real_captured_frame_withText.npy', frame)\n", (6122, 6194), True, 'import numpy as np\n'), ((6453, 6489), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (6482, 6489), False, 'import camera_fusion\n'), ((6494, 6515), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (6507, 6515), False, 'import shutil\n'), ((6520, 6575), 'shutil.copytree', 'shutil.copytree', (['"""./tests/test_CameraCorrected"""', '"""data"""'], {}), "('./tests/test_CameraCorrected', 'data')\n", (6535, 6575), False, 'import shutil\n'), ((6638, 6679), 'numpy.load', 'np.load', (['"""./data/real_captured_frame.npy"""'], {}), "('./data/real_captured_frame.npy')\n", (6645, 6679), True, 'import numpy as np\n'), ((6874, 6925), 'numpy.load', 'np.load', (['"""./data/correct_markers_posture_frame.npy"""'], {}), "('./data/correct_markers_posture_frame.npy')\n", (6881, 6925), True, 'import numpy as np\n'), ((6939, 7006), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['frame', 'correct_markers_posture_frame'], {}), '(frame, correct_markers_posture_frame)\n', (6968, 7006), True, 'import numpy as np\n'), ((7011, 7032), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (7024, 7032), False, 'import shutil\n'), ((7130, 7166), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (7159, 7166), False, 'import camera_fusion\n'), ((7171, 7192), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (7184, 7192), False, 'import shutil\n'), ((7197, 7252), 'shutil.copytree', 'shutil.copytree', (['"""./tests/test_CameraCorrected"""', '"""data"""'], {}), "('./tests/test_CameraCorrected', 'data')\n", (7212, 7252), False, 'import shutil\n'), ((7315, 7356), 'numpy.load', 'np.load', (['"""./data/real_captured_frame.npy"""'], {}), "('./data/real_captured_frame.npy')\n", (7322, 7356), True, 'import numpy as np\n'), ((7547, 7596), 'numpy.load', 'np.load', (['"""./data/correct_board_posture_frame.npy"""'], {}), "('./data/correct_board_posture_frame.npy')\n", (7554, 7596), True, 'import numpy as np\n'), ((7610, 7675), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['frame', 'correct_board_posture_frame'], {}), '(frame, correct_board_posture_frame)\n', (7639, 7675), True, 'import numpy as np\n'), ((7680, 7701), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (7693, 7701), False, 'import shutil\n'), ((7832, 7868), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (7861, 7868), False, 'import camera_fusion\n'), ((7873, 7894), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (7886, 7894), False, 'import shutil\n'), ((7899, 7954), 'shutil.copytree', 'shutil.copytree', (['"""./tests/test_CameraCorrected"""', '"""data"""'], {}), "('./tests/test_CameraCorrected', 'data')\n", (7914, 7954), False, 'import shutil\n'), ((8017, 8058), 'numpy.load', 'np.load', (['"""./data/real_captured_frame.npy"""'], {}), "('./data/real_captured_frame.npy')\n", (8024, 8058), True, 'import numpy as np\n'), ((8231, 8330), 'numpy.save', 'np.save', (['"""./tests/test_CameraCorrected/correct_board_and_markers_posture_frame.npy"""', 'frame'], {}), "(\n './tests/test_CameraCorrected/correct_board_and_markers_posture_frame.npy',\n frame)\n", (8238, 8330), True, 'import numpy as np\n'), ((8351, 8419), 'numpy.save', 'np.save', (['"""./data/correct_board_and_markers_posture_frame.npy"""', 'frame'], {}), "('./data/correct_board_and_markers_posture_frame.npy', frame)\n", (8358, 8419), True, 'import numpy as np\n'), ((8478, 8539), 'numpy.load', 'np.load', (['"""./data/correct_board_and_markers_posture_frame.npy"""'], {}), "('./data/correct_board_and_markers_posture_frame.npy')\n", (8485, 8539), True, 'import numpy as np\n'), ((8553, 8630), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['frame', 'correct_board_and_markers_posture_frame'], {}), '(frame, correct_board_and_markers_posture_frame)\n', (8582, 8630), True, 'import numpy as np\n'), ((8644, 8665), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (8657, 8665), False, 'import shutil\n'), ((8753, 8789), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (8782, 8789), False, 'import camera_fusion\n'), ((8857, 8920), 'numpy.load', 'np.load', (['"""./tests/test_CameraCorrected/real_captured_frame.npy"""'], {}), "('./tests/test_CameraCorrected/real_captured_frame.npy')\n", (8864, 8920), True, 'import numpy as np\n'), ((9340, 9376), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (9369, 9376), False, 'import camera_fusion\n'), ((9381, 9402), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (9394, 9402), False, 'import shutil\n'), ((9407, 9462), 'shutil.copytree', 'shutil.copytree', (['"""./tests/test_CameraCorrected"""', '"""data"""'], {}), "('./tests/test_CameraCorrected', 'data')\n", (9422, 9462), False, 'import shutil\n'), ((9710, 9753), 'numpy.load', 'np.load', (['"""./data/real_undistored_frame.npy"""'], {}), "('./data/real_undistored_frame.npy')\n", (9717, 9753), True, 'import numpy as np\n'), ((9758, 9829), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['valid_frame_undistored', 'frame_undistored'], {}), '(valid_frame_undistored, frame_undistored)\n', (9787, 9829), True, 'import numpy as np\n'), ((9834, 9855), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (9847, 9855), False, 'import shutil\n'), ((9924, 9979), 'shutil.copytree', 'shutil.copytree', (['"""./tests/test_CameraCorrected"""', '"""data"""'], {}), "('./tests/test_CameraCorrected', 'data')\n", (9939, 9979), False, 'import shutil\n'), ((9988, 10024), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (10017, 10024), False, 'import camera_fusion\n'), ((10276, 10297), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (10289, 10297), False, 'import shutil\n'), ((10377, 10413), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (10406, 10413), False, 'import camera_fusion\n'), ((10437, 10458), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (10450, 10458), False, 'import shutil\n'), ((10463, 10518), 'shutil.copytree', 'shutil.copytree', (['"""./tests/test_CameraCorrected"""', '"""data"""'], {}), "('./tests/test_CameraCorrected', 'data')\n", (10478, 10518), False, 'import shutil\n'), ((10545, 10586), 'numpy.load', 'np.load', (['"""./data/real_captured_frame.npy"""'], {}), "('./data/real_captured_frame.npy')\n", (10552, 10586), True, 'import numpy as np\n'), ((10770, 10837), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['c.current_frame', 'real_captured_frame'], {}), '(c.current_frame, real_captured_frame)\n', (10799, 10837), True, 'import numpy as np\n'), ((10842, 10863), 'shutil.rmtree', 'shutil.rmtree', (['"""data"""'], {}), "('data')\n", (10855, 10863), False, 'import shutil\n'), ((1022, 1038), 'time.sleep', 'time.sleep', (['(0.33)'], {}), '(0.33)\n', (1032, 1038), False, 'import time\n'), ((3961, 4048), 'unittest.mock.patch', 'mock.patch', (['"""camera_fusion.CameraCorrected.read"""'], {'return_value': 'real_captured_frame'}), "('camera_fusion.CameraCorrected.read', return_value=\n real_captured_frame)\n", (3971, 4048), True, 'import unittest.mock as mock\n'), ((5409, 5448), 'unittest.mock.patch', 'mock.patch', (['"""time.time"""'], {'return_value': '(0)'}), "('time.time', return_value=0)\n", (5419, 5448), True, 'import unittest.mock as mock\n'), ((5462, 5498), 'camera_fusion.CameraCorrected', 'camera_fusion.CameraCorrected', (['(0)', '(11)'], {}), '(0, 11)\n', (5491, 5498), False, 'import camera_fusion\n'), ((5622, 5664), 'unittest.mock.patch', 'mock.patch', (['"""time.time"""'], {'return_value': '(0.03)'}), "('time.time', return_value=0.03)\n", (5632, 5664), True, 'import unittest.mock as mock\n'), ((5744, 5818), 'numpy.load', 'np.load', (['"""./tests/test_CameraCorrected/real_captured_frame_with_30fps.npy"""'], {}), "('./tests/test_CameraCorrected/real_captured_frame_with_30fps.npy')\n", (5751, 5818), True, 'import numpy as np\n'), ((6250, 6322), 'numpy.load', 'np.load', (['"""./tests/test_CameraCorrected/real_captured_frame_withText.npy"""'], {}), "('./tests/test_CameraCorrected/real_captured_frame_withText.npy')\n", (6257, 6322), True, 'import numpy as np\n'), ((6689, 6776), 'unittest.mock.patch', 'mock.patch', (['"""camera_fusion.CameraCorrected.read"""'], {'return_value': 'real_captured_frame'}), "('camera_fusion.CameraCorrected.read', return_value=\n real_captured_frame)\n", (6699, 6776), True, 'import unittest.mock as mock\n'), ((7366, 7453), 'unittest.mock.patch', 'mock.patch', (['"""camera_fusion.CameraCorrected.read"""'], {'return_value': 'real_captured_frame'}), "('camera_fusion.CameraCorrected.read', return_value=\n real_captured_frame)\n", (7376, 7453), True, 'import unittest.mock as mock\n'), ((8068, 8155), 'unittest.mock.patch', 'mock.patch', (['"""camera_fusion.CameraCorrected.read"""'], {'return_value': 'real_captured_frame'}), "('camera_fusion.CameraCorrected.read', return_value=\n real_captured_frame)\n", (8078, 8155), True, 'import unittest.mock as mock\n'), ((238, 263), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (253, 263), False, 'import os\n'), ((9023, 9094), 'unittest.mock.patch', 'mock.patch', (['"""camera_fusion.CameraCorrected.calibrate_camera_correction"""'], {}), "('camera_fusion.CameraCorrected.calibrate_camera_correction')\n", (9033, 9094), True, 'import unittest.mock as mock\n'), ((9130, 9198), 'unittest.mock.patch', 'mock.patch', (['"""camera_fusion.CameraCorrected.read"""'], {'return_value': 'frame'}), "('camera_fusion.CameraCorrected.read', return_value=frame)\n", (9140, 9198), True, 'import unittest.mock as mock\n'), ((9591, 9632), 'numpy.load', 'np.load', (['"""./data/real_captured_frame.npy"""'], {}), "('./data/real_captured_frame.npy')\n", (9598, 9632), True, 'import numpy as np\n'), ((10179, 10220), 'numpy.load', 'np.load', (['"""./data/real_captured_frame.npy"""'], {}), "('./data/real_captured_frame.npy')\n", (10186, 10220), True, 'import numpy as np\n')]
|
"""
Functions to plot data using the `cartopy` library.
These require the `shapely` and `cartopy` libraries to be installed.
CartoPy is sometimes difficult to install.
"""
import numpy as N
from cartopy import crs, feature
from shapely.geometry import Polygon
from ..error.axes import hyperbolic_axes
from ..stereonet import plane_errors, normal_errors
def fix_stereonet_coords(coords):
coords[:,1] *= -1
return coords
def cartopy_girdle(fit, **kw):
d = hyperbolic_axes(fit,**kw)
cm = N.diag(d)
sheets = {i: N.degrees(plane_errors(fit.axes, cm, sheet=i))
for i in ('upper','lower')}
geom = Polygon(sheets['upper'], [sheets['lower'][::-1]])
geometries = [geom]
return feature.ShapelyFeature(geometries, crs.PlateCarree())
def cartopy_normal(fit, **kw):
d = hyperbolic_axes(fit,**kw)
cm = N.diag(d)
upper = N.degrees(normal_errors(fit.axes, cm))
geom = Polygon(upper)
geometries = [geom]
return feature.ShapelyFeature(geometries, crs.PlateCarree())
|
[
"cartopy.crs.PlateCarree",
"numpy.diag",
"shapely.geometry.Polygon"
] |
[((504, 513), 'numpy.diag', 'N.diag', (['d'], {}), '(d)\n', (510, 513), True, 'import numpy as N\n'), ((625, 674), 'shapely.geometry.Polygon', 'Polygon', (["sheets['upper']", "[sheets['lower'][::-1]]"], {}), "(sheets['upper'], [sheets['lower'][::-1]])\n", (632, 674), False, 'from shapely.geometry import Polygon\n'), ((839, 848), 'numpy.diag', 'N.diag', (['d'], {}), '(d)\n', (845, 848), True, 'import numpy as N\n'), ((911, 925), 'shapely.geometry.Polygon', 'Polygon', (['upper'], {}), '(upper)\n', (918, 925), False, 'from shapely.geometry import Polygon\n'), ((745, 762), 'cartopy.crs.PlateCarree', 'crs.PlateCarree', ([], {}), '()\n', (760, 762), False, 'from cartopy import crs, feature\n'), ((996, 1013), 'cartopy.crs.PlateCarree', 'crs.PlateCarree', ([], {}), '()\n', (1011, 1013), False, 'from cartopy import crs, feature\n')]
|
import matplotlib.pyplot as plot
import numpy as np
#Function to get x and y coordinates from the first 10 clicks, then close the image.
def onclick(event):
x.append(event.xdata)
y.append(event.ydata)
print(len(x))
xval = int(event.xdata)
yval = int(event.ydata)
print(str([xval,yval]))
if len(x) == 10:
event.canvas.mpl_disconnect(cid)
print('DISCONNECT')
plot.close()
'''
This script takes a DEM image as input, and allows the user to click 10 points along the rim. A circle is fit to the
points and the center coordinates are returned
'''
def circlefit(dem):
#define x and y as global list variables
global x,y
x = []
y = []
#show the DEM
plot.imshow(dem)
ax = plot.gca()
fig = plot.gcf()
fig.suptitle('Click 10 points on the crater rim to fit with a circle:')
#Set up to run the function onclick every time the user clicks the image
global cid
cid = fig.canvas.mpl_connect('button_press_event',onclick)
plot.show()
# define coordinates as arrays
x = np.array(x)
y = np.array(y)
# create arrays used in circle calculation
a1 = np.array([x, y, np.ones(np.shape(x))])
a2 = np.array([-(x ** 2 + y ** 2)])
# solve the least squares fit to get the center point
a = np.linalg.lstsq(a1.T, a2.T, rcond=None)[0]
xc = -0.5 * a[0]
yc = -0.5 * a[1]
return xc, yc
|
[
"matplotlib.pyplot.show",
"numpy.linalg.lstsq",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.close",
"numpy.shape",
"numpy.array",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.gcf"
] |
[((723, 739), 'matplotlib.pyplot.imshow', 'plot.imshow', (['dem'], {}), '(dem)\n', (734, 739), True, 'import matplotlib.pyplot as plot\n'), ((749, 759), 'matplotlib.pyplot.gca', 'plot.gca', ([], {}), '()\n', (757, 759), True, 'import matplotlib.pyplot as plot\n'), ((770, 780), 'matplotlib.pyplot.gcf', 'plot.gcf', ([], {}), '()\n', (778, 780), True, 'import matplotlib.pyplot as plot\n'), ((1017, 1028), 'matplotlib.pyplot.show', 'plot.show', ([], {}), '()\n', (1026, 1028), True, 'import matplotlib.pyplot as plot\n'), ((1073, 1084), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1081, 1084), True, 'import numpy as np\n'), ((1093, 1104), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (1101, 1104), True, 'import numpy as np\n'), ((1209, 1239), 'numpy.array', 'np.array', (['[-(x ** 2 + y ** 2)]'], {}), '([-(x ** 2 + y ** 2)])\n', (1217, 1239), True, 'import numpy as np\n'), ((411, 423), 'matplotlib.pyplot.close', 'plot.close', ([], {}), '()\n', (421, 423), True, 'import matplotlib.pyplot as plot\n'), ((1307, 1346), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['a1.T', 'a2.T'], {'rcond': 'None'}), '(a1.T, a2.T, rcond=None)\n', (1322, 1346), True, 'import numpy as np\n'), ((1185, 1196), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (1193, 1196), True, 'import numpy as np\n')]
|
import open3d as o3d
import copy
import numpy as np
# Helper visualization function
def draw_registration_result(source, target, transformation):
source_temp = copy.deepcopy(source)
target_temp = copy.deepcopy(target)
source_temp.paint_uniform_color([1, 0.706, 0])
target_temp.paint_uniform_color([0, 0.651, 0.929])
source_temp.transform(transformation)
o3d.visualization.draw_geometries([source_temp, target_temp])
# input
source = o3d.io.read_point_cloud("../test_data/icp/cloud_bin_0.pcd")
target = o3d.io.read_point_cloud("../test_data/icp/cloud_bin_1.pcd")
trans_init = np.asarray([[0.862, 0.011, -0.507, 0.5],
[-0.139, 0.967, -0.215, 0.7],
[0.487, 0.255, 0.835, -1.4], [0.0, 0.0, 0.0, 1.0]])
draw_registration_result(source, target, trans_init)
# init
print("Initial alignment")
threshold = 0.02
evaluation = o3d.pipelines.registration.evaluate_registration(
source, target, threshold, trans_init)
print(evaluation)
# point-to-point ICP
print("Apply point-to-point ICP")
reg_p2p = o3d.pipelines.registration.registration_icp(
source, target, threshold, trans_init,
o3d.pipelines.registration.TransformationEstimationPointToPoint())
print(reg_p2p)
print("Transformation is:")
print(reg_p2p.transformation)
draw_registration_result(source, target, reg_p2p.transformation)
# point-to-point ICP, max_iteration
reg_p2p = o3d.pipelines.registration.registration_icp(
source, target, threshold, trans_init,
o3d.pipelines.registration.TransformationEstimationPointToPoint(),
o3d.pipelines.registration.ICPConvergenceCriteria(max_iteration=2000))
print(reg_p2p)
print("Transformation is:")
print(reg_p2p.transformation)
draw_registration_result(source, target, reg_p2p.transformation)
# point-to plane ICP
print("Apply point-to-plane ICP")
reg_p2l = o3d.pipelines.registration.registration_icp(
source, target, threshold, trans_init,
o3d.pipelines.registration.TransformationEstimationPointToPlane())
print(reg_p2l)
print("Transformation is:")
print(reg_p2l.transformation)
draw_registration_result(source, target, reg_p2l.transformation)
|
[
"copy.deepcopy",
"numpy.asarray",
"open3d.io.read_point_cloud",
"open3d.visualization.draw_geometries",
"open3d.pipelines.registration.evaluate_registration",
"open3d.pipelines.registration.ICPConvergenceCriteria",
"open3d.pipelines.registration.TransformationEstimationPointToPoint",
"open3d.pipelines.registration.TransformationEstimationPointToPlane"
] |
[((459, 518), 'open3d.io.read_point_cloud', 'o3d.io.read_point_cloud', (['"""../test_data/icp/cloud_bin_0.pcd"""'], {}), "('../test_data/icp/cloud_bin_0.pcd')\n", (482, 518), True, 'import open3d as o3d\n'), ((528, 587), 'open3d.io.read_point_cloud', 'o3d.io.read_point_cloud', (['"""../test_data/icp/cloud_bin_1.pcd"""'], {}), "('../test_data/icp/cloud_bin_1.pcd')\n", (551, 587), True, 'import open3d as o3d\n'), ((602, 729), 'numpy.asarray', 'np.asarray', (['[[0.862, 0.011, -0.507, 0.5], [-0.139, 0.967, -0.215, 0.7], [0.487, 0.255, \n 0.835, -1.4], [0.0, 0.0, 0.0, 1.0]]'], {}), '([[0.862, 0.011, -0.507, 0.5], [-0.139, 0.967, -0.215, 0.7], [\n 0.487, 0.255, 0.835, -1.4], [0.0, 0.0, 0.0, 1.0]])\n', (612, 729), True, 'import numpy as np\n'), ((894, 985), 'open3d.pipelines.registration.evaluate_registration', 'o3d.pipelines.registration.evaluate_registration', (['source', 'target', 'threshold', 'trans_init'], {}), '(source, target, threshold,\n trans_init)\n', (942, 985), True, 'import open3d as o3d\n'), ((165, 186), 'copy.deepcopy', 'copy.deepcopy', (['source'], {}), '(source)\n', (178, 186), False, 'import copy\n'), ((205, 226), 'copy.deepcopy', 'copy.deepcopy', (['target'], {}), '(target)\n', (218, 226), False, 'import copy\n'), ((379, 440), 'open3d.visualization.draw_geometries', 'o3d.visualization.draw_geometries', (['[source_temp, target_temp]'], {}), '([source_temp, target_temp])\n', (412, 440), True, 'import open3d as o3d\n'), ((1163, 1228), 'open3d.pipelines.registration.TransformationEstimationPointToPoint', 'o3d.pipelines.registration.TransformationEstimationPointToPoint', ([], {}), '()\n', (1226, 1228), True, 'import open3d as o3d\n'), ((1507, 1572), 'open3d.pipelines.registration.TransformationEstimationPointToPoint', 'o3d.pipelines.registration.TransformationEstimationPointToPoint', ([], {}), '()\n', (1570, 1572), True, 'import open3d as o3d\n'), ((1578, 1647), 'open3d.pipelines.registration.ICPConvergenceCriteria', 'o3d.pipelines.registration.ICPConvergenceCriteria', ([], {'max_iteration': '(2000)'}), '(max_iteration=2000)\n', (1627, 1647), True, 'import open3d as o3d\n'), ((1945, 2010), 'open3d.pipelines.registration.TransformationEstimationPointToPlane', 'o3d.pipelines.registration.TransformationEstimationPointToPlane', ([], {}), '()\n', (2008, 2010), True, 'import open3d as o3d\n')]
|
"""
pyjs9.py: connects Python and JS9 via the JS9 (back-end) helper
"""
from __future__ import print_function
import time
import json
import base64
import logging
from traceback import format_exc
from threading import Condition
from io import BytesIO
import requests
__all__ = ['JS9', 'js9Globals']
"""
pyjs9.py connects Python and JS9 via the JS9 (back-end) helper
- The JS9 class constructor connects to a single JS9 instance in a web page.
- The JS9 object supports the JS9 Public API and a shorter command-line syntax.
- See: http://js9.si.edu/js9/help/publicapi.html
- Send/retrieve numpy arrays and astropy (or pyfits) hdulists to/from js9.
- Use python-socketio for fast, persistent connections to the JS9 back-end
"""
# pyjs9 version
__version__ = '3.6'
# try to be a little bit neat with global parameters
js9Globals = {}
js9Globals['version'] = __version__
# what sort of fits verification gets done on SetFITS() output?
# see astropy documentation on write method
js9Globals['output_verify'] = 'ignore'
# retrieve image data from JS9 as an array or as base64 encoded string
# in the early days, base64 seemed to be faster
# js9Globals['retrieveAs'] = 'base64'
# array allows us to deal with larger images
js9Globals['retrieveAs'] = 'array'
# load fits, if available
try:
from astropy.io import fits
js9Globals['fits'] = 1
except ImportError:
try:
import pyfits as fits
if fits.__version__ >= '2.2':
js9Globals['fits'] = 2
else:
js9Globals['fits'] = 0
except ImportError:
js9Globals['fits'] = 0
# load numpy, if available
try:
import numpy
js9Globals['numpy'] = 1
except ImportError:
js9Globals['numpy'] = 0
# load socket.io, if available
try:
import socketio
logging.info('set socketio transport')
js9Globals['transport'] = 'socketio'
js9Globals['wait'] = 10
except ImportError:
logging.info('no python-socketio, use html transport')
js9Globals['transport'] = 'html'
js9Globals['wait'] = 0
# utilities
def _decode_list(data):
rv = []
for item in data:
if isinstance(item, list):
item = _decode_list(item)
elif isinstance(item, dict):
item = _decode_dict(item)
rv.append(item)
return rv
def _decode_dict(data):
rv = {}
for key, value in data.items():
if isinstance(value, list):
value = _decode_list(value)
elif isinstance(value, dict):
value = _decode_dict(value)
rv[key] = value
return rv
# numpy-dependent routines
if js9Globals['numpy']:
def _bp2np(bitpix): # pylint: disable=too-many-return-statements
"""
Convert FITS bitpix to numpy datatype
"""
if bitpix == 8:
return numpy.uint8
if bitpix == 16:
return numpy.int16
if bitpix == 32:
return numpy.int32
if bitpix == 64:
return numpy.int64
if bitpix == -32:
return numpy.float32
if bitpix == -64:
return numpy.float64
if bitpix == -16:
return numpy.uint16
raise ValueError('unsupported bitpix: %d' % bitpix)
_NP_TYPE_MAP = (
# pylint: disable=bad-whitespace
(numpy.uint8 , numpy.uint8, ),
(numpy.int8 , numpy.int16, ),
(numpy.uint16 , numpy.uint16, ),
(numpy.int16 , numpy.int16, ),
(numpy.int32 , numpy.int32, ),
(numpy.uint32 , numpy.int64, ),
(numpy.int64 , numpy.int64, ),
(numpy.float16, numpy.float32,),
(numpy.float32, numpy.float32,),
(numpy.float64, numpy.float64,),
)
def _cvt2np(ndarr: numpy.ndarray):
# NOTE cvt2np may be merged into np2bp
dtype = ndarr.dtype
for t in _NP_TYPE_MAP:
if numpy.issubdtype(dtype, t[0]):
return ndarr.astype(t[1])
return ndarr
def _np2bp(dtype): # pylint: disable=too-many-return-statements
"""
Convert numpy datatype to FITS bitpix
"""
if dtype == numpy.uint8:
return 8
if dtype == numpy.int16:
return 16
if dtype == numpy.int32:
return 32
if dtype == numpy.int64:
return 64
if dtype == numpy.float32:
return -32
if dtype == numpy.float64:
return -64
if dtype == numpy.uint16:
return -16
raise ValueError('unsupported dtype: %s' % dtype)
def _bp2py(bitpix): # pylint: disable=too-many-return-statements
"""
Convert FITS bitpix to python datatype
"""
if bitpix == 8:
return 'B'
if bitpix == 16:
return 'h'
if bitpix == 32:
return 'l'
if bitpix == 64:
return 'q'
if bitpix == -32:
return 'f'
if bitpix == -64:
return 'd'
if bitpix == -16:
return 'H'
raise ValueError('unsupported bitpix: %d' % bitpix)
def _im2np(im):
"""
Convert GetImageData object to numpy
"""
w = int(im['width'])
h = int(im['height'])
d = 1
bp = int(im['bitpix'])
dtype = _bp2np(bp)
dlen = h * w * abs(bp) // 8
if js9Globals['retrieveAs'] == 'array':
s = im['data'][0:h*w]
if d > 1:
arr = numpy.array(s, dtype=dtype).reshape((d, h, w))
else:
arr = numpy.array(s, dtype=dtype).reshape((h, w))
elif js9Globals['retrieveAs'] == 'base64':
s = base64.decodebytes(im['data'].encode())[0:dlen]
if d > 1:
arr = numpy.frombuffer(s, dtype=dtype).reshape((d, h, w))
else:
arr = numpy.frombuffer(s, dtype=dtype).reshape((h, w))
else:
raise ValueError('unknown retrieveAs type for GetImageData()')
return arr
class JS9:
"""
The JS9 class supports communication with an instance of JS9 in a web
page, utilizing the JS9 Public API calls as class methods.
JS9's public access library is documented here:
- http://js9.si.edu/js9/help/publicapi.html
In addition, a number of special methods are implemented to facilitate data
access to/from well-known Python objects:
- GetNumpy: retrieve a FITS image or an array into a numpy array
- SetNumpy: send a numpy array to JS9 for display
- GetFITS: retrieve a FITS image into an astropy (or pyfits) HDU list
- SetFITS: send a astropy (or pyfits) HDU list to JS9 for display
"""
def __init__(self, host='http://localhost:2718', id='JS9', maxtries=5, delay=1, debug=False): # pylint: disable=redefined-builtin, too-many-arguments
"""
:param host: host[:port] (def: 'http://localhost:2718')
:param id: the JS9 display id (def: 'JS9')
:rtype: JS9 object connected to a single instance of js9
The JS9() contructor takes its first argument to be the host (and
optional port) on which the back-end js9Helper is running. The default
is 'http://localhost:2718', which generally will be the correct value
for running locally. The default port (2718) will be added if no port
value is found. The string 'http://' will be prefixed to the host if a
URL protocol is not supplied. Thus, to connect to the main JS9 web
site, you can use host='js9.si.edu'.
The second argument is a JS9 display id on the web page. The
default is 'JS9' which is the default JS9 display id. Thus:
>>> JS9 = pyjs9.JS9()
is appropriate for local web pages having only one JS9 display.
"""
self.__dict__['id'] = id
# add default port, if necessary
c = host.rfind(':')
s = host.find('/')
if c <= s:
host += ':2718'
if s < 0:
host = 'http://' + host
self.__dict__['host'] = host
# open socket.io connection, if necessary
if js9Globals['transport'] == 'socketio':
try:
if debug:
self.sockio = socketio.Client(logger=True,
engineio_logger=True)
else:
self.sockio = socketio.Client()
self.sockio.connect(host)
except Exception as e: # pylint: disable=broad-except
logging.warning('socketio connect failed: %s, using html', e)
js9Globals['transport'] = 'html'
self._block_cb = None
# wait for connect be ready, but success doesn't really matter here
tries = 0
while tries < maxtries:
try:
self._alive()
except Exception: # pylint: disable=broad-except
time.sleep(delay)
tries = tries - 1
else:
break
def __setitem__(self, itemname, value):
"""
An internal routine to process some assignments specially
"""
self.__dict__[itemname] = value
if itemname in ('host', 'id',):
self._alive()
def _alive(self):
"""
An internal routine to send a test message to the helper
"""
self.send(None, msg='alive')
def sockioCB(self, *args):
"""
Internal routine
"""
logging.debug('socketio callback, args: %s', args)
self.__dict__['sockioResult'] = args[0]
self._block_cb.acquire()
self._block_cb.notify()
self._block_cb.release()
def send(self, obj, msg='msg'):
"""
:obj: dictionary containing command and args keys
:rtype: returned data or info (in format specified by public api)
examples:
>>> js9 = pyjs9.JS9()
>>> js9.send({'cmd': 'GetColormap'})
{u'bias': 0.5, u'colormap': u'cool', u'contrast': 1}
>>> js9.send({'cmd': 'SetColormap', 'args': ['red']})
'OK'
"""
if obj is None:
obj = {}
obj['id'] = self.__dict__['id']
if js9Globals['transport'] == 'html': # pylint: disable=no-else-return
host = self.__dict__['host']
try:
url = requests.post(host + '/' + msg, json=obj)
except IOError as e:
raise IOError('Cannot connect to {0}: {1}'.format(host, e))
urtn = url.text
if 'ERROR:' in urtn:
raise ValueError(urtn)
try:
# TODO: url.json() decode the json for us:
# http://www.python-requests.org/en/latest/user/quickstart/#json-response-content
# res = url.json()
res = json.loads(urtn, object_hook=_decode_dict)
except ValueError: # not json
res = urtn
if type(res) == str:
res = res.strip()
return res
else:
self.__dict__['sockioResult'] = ''
self._block_cb = Condition()
self._block_cb.acquire()
self.sockio.emit('msg', obj, callback=self.sockioCB)
self._block_cb.wait(timeout=js9Globals['wait'])
self._block_cb.release()
# self.sockio.wait_for_callbacks(seconds=js9Globals['wait'])
if self.__dict__['sockioResult'] and \
isinstance(self.__dict__['sockioResult'], str) and \
'ERROR:' in self.__dict__['sockioResult']:
raise ValueError(self.__dict__['sockioResult'])
return self.__dict__['sockioResult']
def close(self):
"""
Close the socketio connection and disconnect from the server
"""
if js9Globals['transport'] == 'socketio':
try:
self.sockio.disconnect()
except Exception as e: # pylint: disable=broad-except
logging.error('socketio close failed: %s', e)
if js9Globals['fits']:
def GetFITS(self):
"""
:rtype: fits hdulist
To read FITS data or a raw array from js9 into fits, use the
'GetFITS' method. It takes no args and returns an hdu list::
>>> hdul = j.GetFITS()
>>> hdul.info()
Filename: StringIO.StringIO
No. Name Type Cards Dimensions Format
0 PRIMARY PrimaryHDU 24 (1024, 1024) float32
>>> data = hdul[0].data
>>> data.shape
(1024, 1024)
"""
# get image data from JS9
im = self.GetImageData(js9Globals['retrieveAs'])
# if the image is too large, we can back get an empty string
if im == '':
raise ValueError('GetImageData failed: image too large for Python transport?')
# convert to numpy
arr = _im2np(im)
# add fits cards
# create FITS primary hdu from numpy array
hdu = fits.PrimaryHDU(arr)
hdulist = fits.HDUList([hdu])
return hdulist
def SetFITS(self, hdul, name=None):
"""
:param hdul: fits hdulist
:param name: fits file or object name (used as id)
After manipulating or otherwise modifying a fits hdulist (or
making a new one), you can display it in js9 using the 'SetFITS'
method, which takes the hdulist as its sole argument::
>>> j.SetFITS(nhdul)
Note that this routine creates a new image in the JS9 display. If
you want to update the current image, use RefreshImage. In that
case, the hdul's numpy array must be converted to a list:
>>>> j.RefreshImage(hdul[0].data.tolist())
"""
if not js9Globals['fits']:
raise ValueError('SetFITS not defined (fits not found)')
if not isinstance(hdul, fits.HDUList):
if js9Globals['fits'] == 1:
raise ValueError('requires astropy.HDUList as input')
raise ValueError('requires pyfits.HDUList as input')
# in-memory string
memstr = BytesIO()
# write fits to memory string
hdul.writeto(memstr, output_verify=js9Globals['output_verify'])
# get memory string as an encoded string
encstr = base64.b64encode(memstr.getvalue()).decode()
# set up JS9 options
opts = {}
if name:
opts['filename'] = name
# send encoded file to JS9 for display
got = self.Load(encstr, opts)
# finished with memory string
memstr.close()
return got
else:
@staticmethod
def GetFITS():
"""
This method is not defined because fits in not installed.
"""
raise ValueError('GetFITS not defined (astropy.io.fits not found)')
@staticmethod
def SetFITS():
"""
This method is not defined because fits in not installed.
"""
raise ValueError('SetFITS not defined (astropy.io.fits not found)')
if js9Globals['numpy']:
def GetNumpy(self):
"""
:rtype: numpy array
To read a FITS file or an array from js9 into a numpy array, use
the 'GetNumpy' method. It takes no arguments and returns the
np array::
>>> j.get('file')
'/home/eric/data/casa.fits[EVENTS]'
>>> arr = j.GetNumpy()
>>> arr.shape
(1024, 1024)
>>> arr.dtype
dtype('float32')
>>> arr.max()
51.0
"""
# get image data from JS9
im = self.GetImageData(js9Globals['retrieveAs'])
# if the image is too large, we can get back an empty string
if im == '':
raise ValueError('GetImageData failed: image too large for Python transport?')
# convert to numpy
arr = _im2np(im)
return arr
def SetNumpy(self, arr, filename=None, dtype=None):
"""
:param arr: numpy array
:param name: file or object name (used as id)
:param dtype: data type into which to convert array before sending
After manipulating or otherwise modifying a numpy array (or making
a new one), you can display it in js9 using the 'SetNumpy' method,
which takes the array as its first argument::
>>> j.SetNumpy(arr)
An optional second argument specifies a datatype into which the
array will be converted before being sent to js9. This is
important in the case where the array has datatype np.uint64,
which is not recognized by js9::
>>> j.SetNumpy(arru64)
...
ValueError: uint64 is unsupported by JS9 (or FITS)
>>> j.SetNumpy(arru64,dtype=np.float64)
Also note that np.int8 is sent to js9 as int16 data, np.uint32 is
sent as int64 data, and np.float16 is sent as float32 data.
Note that this routine creates a new image in the JS9 display. If
you want to update the current image, use RefreshImage. In that
case, the numpy array must be converted to a list:
>>>> j.RefreshImage(arr.tolist())
"""
if not isinstance(arr, numpy.ndarray):
raise ValueError('requires numpy.ndarray as input')
if dtype and dtype != arr.dtype:
narr = arr.astype(dtype)
else:
narr = _cvt2np(arr)
if not narr.flags['C_CONTIGUOUS']:
narr = numpy.ascontiguousarray(narr)
# parameters to pass back to JS9
bp = _np2bp(narr.dtype)
(h, w) = narr.shape
dmin = narr.min().tolist()
dmax = narr.max().tolist()
# base64-encode numpy array in native format
encarr = base64.b64encode(narr.tostring()).decode()
# create object to send to JS9 containing encoded array
hdu = {'naxis': 2, 'naxis1': w, 'naxis2': h, 'bitpix': bp,
'dmin': dmin, 'dmax': dmax, 'encoding': 'base64',
'image': encarr}
if filename:
hdu['filename'] = filename
# send encoded file to JS9 for display
return self.Load(hdu)
else:
@staticmethod
def GetNumpy():
"""
This method is not defined because numpy in not installed.
"""
raise ValueError('GetNumpy not defined (numpy not found)')
@staticmethod
def SetNumpy():
"""
This method is not defined because numpy in not installed.
"""
raise ValueError('SetNumpy not defined (numpy not found)')
def Load(self, *args):
"""
Load an image into JS9
call:
JS9.Load(url, opts)
where:
- url: url, fits object, or in-memory FITS
- opts: object containing image parameters
NB: In Python, you probably want to call JS9.SetFITS() or
JS9.SetNumpy() to load a local file into JS9.
Load a FITS file or a PNG representation file into JS9. Note that
a relative URL is relative to the JS9 install directory.
You also can pass an in-memory buffer containing a FITS file, or a
string containing a base64-encoded FITS file.
Finally, you can pass a fits object containing the following
properties:
- naxis: number of axes in the image
- axis: array of image dimensions for each axis or ...
- naxis[n] image dimensions of each axis (naxis1, naxis2, ...)
- bitpix: FITS bitpix value
- head: object containing header keywords as properties
- image: list containing image pixels
- dmin: data min (optional)
- dmax: data max (optional)
To override default image parameters, pass the image opts argument:
>>> j.Load('png/m13.png', {'scale':'linear', 'colormap':'sls'})
"""
return self.send({'cmd': 'Load', 'args': args})
def LoadWindow(self, *args):
"""
Load an image into a light window or a new (separate) window
call:
JS9.LoadWindow(url, opts, type, html, winopts)
where:
- url: remote URL image to load
- opts: object containing image parameters
- type: "light" or "new"
- html: html for the new page (def: menubar, image, colorbar)
- winopts: for "light", optional dhtml window options
returns:
- id: the id of the JS9 display div
This routine will load an image into a light-weight window or an
entirely new window. The url and opts arguments are identical to
the standard JS9.Load() call, except that opts can contain:
- id: string specifying the id of the JS9 display being created:
if no id is specified, a unique id is generated
- clone: the id of a display to clone when creating a light window:
the menubar and colorbar will be created if and only if they are
present in the cloned display
The type argument determines whether to create a light-weight
window ("light", the default) or a new separate window ("new").
You can use the html argument to supply different web page elements
for the window. Furthermore, if you create a light window, a default
set of DynamicDrive dhtmlwindow parameters will be used to make the
window the correct size for the default html:
"width=512px,height=542px,center=1,resize=1,scrolling=1"
You can supply your own parameters for the new dhtmlwindow using the
winOpts argument. See the Dynamic Drive web site:
http://www.dynamicdrive.com/dynamicindex8/dhtmlwindow/index.htm
for more information about their light-weight window.
To create a new light window without loading an image, use:
>>>> JS9.LoadWindow("", "", "light");
"""
return self.send({'cmd': 'LoadWindow', 'args': args})
def LoadProxy(self, *args):
"""
Load an FITS image link into JS9 using a proxy server
call:
JS9.LoadProxy(url, opts)
where:
- url: remote URL link to load
- opts: object containing image parameters
Load a FITS file specified by an arbitrary URL into JS9 using
the JS9 back-end helper as a proxy server. Not all back-end
servers support the proxy functionality. The main JS9 web
site does support proxy service, and can be used to view
images from arbitrary URLs.
The JS9.LoadProxy() call takes a URL as its first argument.
This URL will be retrieved using curl or wget and stored on the
back-end server in a directory specifically tied to the web page.
(The directory and its contents will be deleted when the page is
unloaded.) JS9 then will load the file from this directory.
Note that since the file resides on the back-end server, all
back-end analysis defined on that server is available.
To override default image parameters, pass the image opts argument:
>>> j.LoadProxy('http://hea-www.cfa.harvard.edu/~eric/coma.fits',
{'scale':'linear', 'colormap':'sls'})
If an onload callback function is specified in opts, it will be called
after the image is loaded:
>>> j.LoadProxy('http://hea-www.cfa.harvard.edu/~eric/coma.fits',
{'scale': 'linear', 'onload': func})
"""
return self.send({'cmd': 'LoadProxy', 'args': args})
def GetStatus(self, *args):
"""
Get Processing Status
call:
status = JS9.GetStatus(type, id)
where:
- type: the type of status
- id: the id of the file that was loaded into JS9
returns:
- status: status of the processing
This routine returns the status of one of the following specified
asynchronous processing types: "Load", "CreateMosaic",
"DisplaySection", "LoadCatalog", "LoadRegions", "ReprojectData",
"RotateData", "RunAnalysis".
A status of "complete" means that the image is fully processed. Other
statuses include:
- processing: the image is being processed
- loading: the image is in process of loading ("Load" only)
- error: image did not load due to an error
- other: another image is loaded into this display
- none: no image is loaded into this display
"""
return self.send({'cmd': 'GetStatus', 'args': args})
def GetLoadStatus(self, *args):
"""
Get Load Status
call:
status = JS9.GetLoadStatus(id)
where:
- id: the id of the file that was loaded into JS9
returns:
- status: status of the load
This routine returns the status of the load of this image.
Provided for backward compatibility, it simply calls the more general
GetStatus() routine with "Load" as the first argument.
A status of 'complete' means that the image is fully loaded. Other
statuses include:
- loading: the image is in process of loading
- error: image did not load due to an error
- other: another image is loaded into this display
- none: no image is loaded into this display
"""
return self.send({'cmd': 'GetLoadStatus', 'args': args})
def DisplayImage(self, *args):
"""
Display an image
call:
JS9.RefreshImage(step)
where:
- step: starting step to take when displaying the image
The display steps are: "colors" (remake colors when cmap has changed),
"scaled" (rescale data values), "primary" (convert scaled data values
to color values), and "display" (write color values to the web page).
The default step is "primary", which displays the image without
recalculating color data, scaled data, etc. This generally is what you
want, unless you have changed parameter(s) used in a prior step.
"""
return self.send({'cmd': 'DisplayImage', 'args': args})
def RefreshImage(self, *args):
"""
Re-read the image data and re-display
call:
JS9.RefreshImage(input)
where:
- input: python list
This routine can be used, for example, in laboratory settings where
data is being gathered in real-time and the JS9 display needs to be
refreshed periodically. The first input argument can be one of the
following:
- a list containing image pixels (for numpy, use tolist() to convert)
- a two-dimensional list containing image pixels
- a dictionary containing a required image property and any of the
following optional properties:
- naxis: number of axes in the image
- axis: array of image dimensions for each axis or ...
- naxis[n] image dimensions of each axis (naxis1, naxis2, ...)
- bitpix: FITS bitpix value
- head: object containing header keywords as properties
- dmin: data min (optional)
- dmax: data max (optional)
When passing an object as input, the required image property that
contains the image data can be a list or a list of lists containing
data. It also can contain a base64-encoded string containing a list.
This latter can be useful when calling JS9.RefreshImage() via HTTP.
Ordinarily, when refreshing an image, there is no need to specify the
optional axis, bitpix, or header properties. But note that you actually
can change these values on the fly, and JS9 will process the new data
correctly. Also, if you do not pass dmin or dmax, they will be
calculated by JS9.
Note that you can pass a complete FITS file to this routine. It will be
passed to the underlying FITS-handler before being displayed. Thus,
processing time is slightly greater than if you pass the image data
directly.
The main difference between JS9.RefreshImage() and JS9.Load() is
that the former updates the data into an existing image, while the
latter adds a completely new image to the display.
"""
return self.send({'cmd': 'RefreshImage', 'args': args})
def CloseImage(self, *args):
"""
Clear the image from the display and mark resources for release
call:
JS9.CloseImage()
Each loaded image claims a non-trivial amount of memory from a finite
amount of browser heap space. For example, the default 32-bit version
of Google Chrome has a memory limit of approximately 500Mb. If you are
finished viewing an image, closing it tells the browser that the
image's memory can be freed. In principle, this is can help reduce
overall memory usage as successive images are loaded and discarded.
Note, however, that closing an image only provides a hint to the
browser, since this sort of garbage collection is not directly
accessible to JavaScript programming.
Some day, all browsers will support full 64-bit addressing and this
problem will go away ...
"""
return self.send({'cmd': 'CloseImage', 'args': args})
def GetImageData(self, *args):
"""Get image data and auxiliary info for the specified image
call:
imdata = JS9.GetImageData(dflag)
where:
- dflag: specifies whether the data should also be returned
returns:
- imdata: image data object
NB: In Python, you probably want to call JS9.GetFITS() or
JS9.GetNumpy() to retrieve an image.
The image data object contains the following information:
- id: the id of the file that was loaded into JS9
- file: the file or URL that was loaded into JS9
- fits: the FITS file associated with this image
- source: 'fits' if a FITS file was downloaded, 'fits2png' if a
representation file was retrieved
- imtab: 'image' for FITS images and png files, 'table' for FITS
binary tables
- width: x dimension of image
- height: y dimension of image
- bitpix: FITS bits/pixel of each image element (8 for unsigned
char, 16, 32 for signed integer, -32 or -64 for float)
- header: object containing FITS header values
- data: buffer containing raw data values
This call can return raw data for subsequent use in local analysis
tasks. The format of the returned data depends on the exact value of
dflag. If dflag is the boolean value true, an HTML5 typed array
is returned, which translates into a dictionary of pixels values in
Python. While typed arrays are more efficient than ordinary JavaScript
arrays, this is almost certainly not what you want in Python.
If dflag is the string 'array', a Python list of pixel values is
returned. Intuitively, this would seem to what is wanted, but ... it
appears that base64-encoded strings are transferred more quickly
through the JS9 helper than are binary data.
If dflag is the string 'base64', a base64-encoded string is returned.
Oddly, this seems to be the fastest method of transferring
data via socket.io to an external process such as Python, and, in
fact, is the method used by the pyjs9 numpy and fits routines.
The file value can be a FITS file or a representation PNG file. The
fits value will be the path of the FITS file associated with this
image. For a presentation PNG file, the path generally will be relative
to the JS9 install directory. For a normal FITS file, the path usually
is an absolute path to the FITS file.
"""
return self.send({'cmd': 'GetImageData', 'args': args})
def GetDisplayData(self, *args):
"""
Get image data for all images loaded into the specified display
call:
imarr = JS9.GetDisplayData()
returns:
- imarr: array of image data objects
The JS9.GetDisplayData() routine returns an array of image data
objects, one for each images loaded into the specified display.
That is, it returns the same type of information as JS9.GetImageData(),
but does so for each image associated with the display, not just the
current image.
"""
return self.send({'cmd': 'GetDisplayData', 'args': args})
def DisplayPlugin(self, *args):
"""
Display plugin in a light window
call:
JS9.DisplayPlugin(plugin)
where:
- plugin: name of the plugin
Toggle the light-window display of the named plugin, as is done
by the View and Analysis menus. That is, if the plugin is not
visible, make it visible. If the plugin is visible, hide it.
You can supply the full class and plugin name or just the name, using
exact case or lower case, e.g.:
- JS9Panner or panner
- JS9Magnifier or magnifier
- JS9Info or info
- JS9Console or console
- DataSourcesArchivesCatalogs or archivescatalogs
- FitsBinning or binning
- ImExamEncEnergy or encenergy
- ImExamPxTabl or pxtabl
- ImExamRadialProj or radialproj
- ImExamHistogram or histogram
- ImExamRegionStats or regionstats
- ImExamXProj or xproj
- ImExamYProj or yproj
- ImExam3dPlot or 3dplot
- ImExamContours or contours
As with plugins in the View and Analysis menus, this routine does
nothing if the plugin is explicitly defined on the web page.
"""
return self.send({'cmd': 'DisplayPlugin', 'args': args})
def DisplayExtension(self, *args):
"""
Display an extension from a multi-extension FITS file
call:
JS9.DisplayExtension(extid, opts)
where:
- extid: HDU extension number or the HDU's EXTNAME value
- opts: object containing options
This routine allows you to display images and even binary
tables from a multi-extension FITS file. (See, for example,
http://fits.gsfc.nasa.gov/fits_primer.htmlthe FITS Primer
for information about HDUs and multi-extension FITS).
"""
return self.send({'cmd': 'DisplayExtension', 'args': args})
def DisplaySection(self, *args):
"""
Extract and display a section of a FITS file
call:
JS9.DisplaySection(opts)
where:
- opts: object containing options
This routine allows you to extract and display a section of FITS file.
The opts object contains properties specifying how to generate and
display the section:
- xcen: x center of the section in file (physical) coords (required)
- ycen: y center of the section in file (physical) coords (required)
- xdim: x dimension of section to extract before binning
- ydim: y dimension of section to extract before binning
- bin: bin factor to apply after extracting the section
- filter: for tables, row/event filter to apply when extracting a
section
- separate: if true, display as a separate image (def: to update
the current image)
All properties are optional: by default, the routine will extract a bin
1 image from the center of the file.
For example, if an image has dimensions 4096 x 4096, then specifying:
- center: 1024, 1024
- dimensions: 1024, 1024
- bin: 2
will bin the upper left 1024 x 1024 section of the image by 2 to
produce a 512 x 512 image. Note that 0,0 can be used to specify the
file center.
Table filtering allows you to select rows from an FITS binary table
(e.g., an X-ray event list) by checking each row against an expression
involving the columns in the table. When a table is filtered, only
valid rows satisfying these expressions are used to make the image.
A filter expression consists of an arithmetic or logical operation
involving one or more column values from a table. Columns can be
compared to other columns or to numeric constants. Standard JavaScript
math functions can be applied to columns. JavaScript (or C) semantics
are used when constructing expressions, with the usual precedence and
associativity rules holding sway:
Operator Associativity
-------- -------------
() left to right
! (bitwise not) - (unary minus) right to left
* / left to right
+ - left to right
< <= > >= left to right
== != left to right
& (bitwise and) left to right
^ (bitwise exclusive or) left to right
| (bitwise inclusive or) left to right
&& (logical and) left to right
|| (logical or) left to right
= right to left
For example, if energy and pha are columns in a table, then the
following are valid expressions:
pha > 1
energy == pha
pha > 1 && energy <= 2
max(pha,energy) >= 2.5
NB: JS9 uses cfitsio by default (you can, but should not, use the
deprecated fitsy.js), and therefore follows cfitsio filtering
conventions, which are documented in:
https://heasarc.gsfc.nasa.gov/docs/software/fitsio/c/c_user/node97.html
"""
return self.send({'cmd': 'DisplaySection', 'args': args})
def DisplaySlice(self, *args):
"""
Display a slice of a FITS data cube
call:
JS9.DisplaySlice(slice, opts)
where:
- slice: slice description or slice number
- opts: object containing options
This routine allows you to display a 2D slice of a 3D or 4D
FITS data cube, i.e. a FITS image containing 3 or 4 axes.
The slice parameter can either be the numeric value of the
slice in the third (or fourth) image dimension (starting
with 1) or it can be a slice description string: a combination
of asterisks and a numeric value defines the slice axis. Thus, for
example, in a 1024 x 1024 x 16 cube, you can display the sixth slice
along the third axis in one of two ways:
>>> JS9.DisplaySlice(6)
or:
>>> JS9.DisplaySlice("*,*,6")
If the image was organized as 16 x 1024 x 1024, you would use the
string description:
>>> JS9.DisplaySlice("6,*,*")
By default, the new slice replaces the data in the currently displayed
image. You can display the slice as a separate image by supplying
an opts object with its separate property set to true.
For example:
>>> JS9.DisplaySlice("6,*,*", {separate: true})
will display the sixth slice of the first image dimension separately
from the original file, allowing blinking, image blending, etc. between
the two "files". Note that the new id and filename are adjusted to be
the original file's values with the cfitsio image section [6:6,*,*]
appended.
"""
return self.send({'cmd': 'DisplaySlice', 'args': args})
def MoveToDisplay(self, *args):
"""
Move an image to a new JS9 display
call:
JS9.MoveToDisplay(dname)
where:
- dname: name of JS9 display to which the current image will be moved
The JS9.MoveToDisplay() routine moves the current image to the
specified display:
>>> JS9.MoveToDisplay("myJS9")
will move the current image displayed in the "JS9" display window to
the "myJS9" window.
Note that the new JS9 display must already exist. New displays can be
created with the JS9.LoadWindow() public access routine or
the File:new JS9 light window menu option.
"""
return self.send({'cmd': 'MoveToDisplay', 'args': args})
def BlendImage(self, *args):
"""
Blend the image in an image stack using W3C composite/blend modes
call:
JS9.BlendImage(blendMode, opacity)
calling sequences:
JS9.BlendImage() # return current blend params
JS9.BlendImage(true||false) # turn on/off blending
JS9.BlendImage(mode, opacity) # set blend mode and/or opacity
where:
- mode: one of the W3C bend modes
- opacity: the opacity of the blended image (percent from 0 to 1)
Image processing programs such as Adobe Photoshop and Gimp allow you
to blend a stack of images together by mixing the RGB colors. The W3C
has defined a number of composite and blending modes which have been
implemented by Firefox, Chrome, and Safari (what about IE?):
- normal
- multiply
- screen
- overlay
- darken
- lighten
- color-dodge
- color-burn
- hard-light
- soft-light
- difference
- exclusion
- hue
- saturation
- color
- luminosity
In addition, the following Porter-Duff compositing modes are available
(though its unclear how useful they are in JS9 image processing):
- clear
- copy
- source-over
- destination-over
- source-in
- destination-in
- source-out
- destination-out
- source-atop
- destination-atop
- xor
- lighter
Blending and compositing modes are described in detail in:
https://www.w3.org/TR/compositing-1
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing
JS9 allows you to use these modes to blend images together. If
you load two images of the same object into JS9, you can use
the JS9.ReprojectData() routine to align them by WCS. You then
can blend one image into the other by specifying a blend mode
and an optional opacity. For example, if chandra.fits and
spitzer.fits are two aligned images of the same object, and
chandra.fits is currently being displayed, you can blend
spitzer into chandra using the "screen" blend and opacity 0.9
mode this way:
>>> JS9.BlendImage("screen", 0.9)
After the spitzer image is blended, both images will be
displayed as part of the chandra.fits display. However,
changing the colormap, scale, contrast, or bias will only
affect the current chandra image, not the blended spitzer
part. In this way, you can continue to manipulate the current
image and the image blending will update automatically.
Also note that the spitzer image is still available separately
for display and manipulation. You can switch to displaying
spitzer and change colormap, scale, bias, contrast, etc. But
since the images are now blended, changes to spitzer will be
reflected in the spitzer part of the blended chandra
display. Thus, if you change the colormap on the display of
spitzer, and change back to chandra, the blended chandra image
will utilize the new colormap.
This linkage is maintained during zoom and pan operations. If
you display the blended chandra image and then zoom or pan it,
both images will be updated correctly to maintain
alignment. But note that this means when you go back to the
spitzer display, its zoom and/or pan values will have been
updated. In this way, the spitzer image always is correctly
linked to the blended version.
The JS9.BlendImage() call accepts a variable number of
arguments to perform a variety of functions:
JS9.BlendImage() returns an object containing the following properties:
- active: boolean specifying whether this image is to be blended
- mode: string specifying the blend mode
- opacity: opacity value (0 to 1)
>>> JS9.BlendImage() # returns a blend object for the current image
>>> JS9.BlendImage(true||false) # turns on/off blending of
>>> JS9.BlendImage(blend, opacity) # set/modify blend mode or opacity
"""
return self.send({'cmd': 'BlendImage', 'args': args})
def SyncImages(self, *args):
"""
Synchronize operations between two or more images
call:
JS9.SyncImages([ops], [images], [opts]) # set up synchronization
JS9.SyncImages(true||false) # turn on/off synchronization
where:
- ops: array of operations on which to sync
- images: array of images to sync with this image
- opts: options for sync'ing
Synchronize two or more images, so that when an operation is performed
on one image, it also is performed on the other(s). For example, when
the colormap or scale is changed on an image, it also is changed on
the sync'ed images. Or, when a region is created, moved, resized, or
removed on an image, the same happens on the sync'ed images.
When the SyncImages() call is invoked, the current image is
configured to synchronize the specified images. In addition, if
the reciprocate property is set in the opts object (see below),
the other images are also configured to synchronize one another (as
well as the current image). Once configuration is complete, a sync
command is executed immediately. If the current image already
displays one or more regions, these will be created in the target
images.
The operations that can be specified for sync'ing are:
"colormap", "pan", "regions", "scale", "wcs", "zoom", "contrastbias".
If no array is specified, the default array in JS9.globalOpts.syncOps
is used.
Images to synchronize can be specified as an array of image handles or
image ids. If no array is specified, all currently displayed images
are sync'ed.
The optional opts object can contain:
- reciprocate: boolean determining whether images sync one another
- reverse: boolean to reverse this image and target images (def: false)
If the opts object is not specified, the default value of
reciprocate is the value of the JS9.globalOpts.syncReciprocate
property.
Examples:
>>> # the current image will sync all operations for all images
>>> # sync reciprocally, so that changing any image syncs the others
>>> SyncImages()
>>> # current image will sync specified ops for foo1.fits,foo2.fits:
>>> SyncImages(["scale", "colormap"], ["foo1.fits", "foo2.fits"])
>>> # the current image will sync two images with default ops,
>>> # but the two images themselves will not sync images reciprocally
>>> SyncImages(null, ["foo1.fits", "foo2.fits"], {reciprocate: false});
Note that if the pan operation syncs two images having differently
sized fields of view, the smaller image will stop panning when it
reaches its edge, rather than displaying a blank field.
You can turn on/off syncing for a given image by specifying a single
boolean argument:
>>> # turn off sync'ing temporarily
>>> SyncImages(false);
This is different from unsync'ing in that you can turn sync'ing back
on without having to re-sync the images.
"""
return self.send({'cmd': 'SyncImages', 'args': args})
def UnsyncImages(self, *args):
"""
Unsynchronize two or more previously synchronized images
call:
JS9.UnsyncImages([ops], [images], [opts]) # clear synchronization
where:
- ops: array of operations to unsync
- images: array of images to unsync with this image
- opts: options for unsync'ing
Unsynchronize previously sync'ed images.
The operations that can be specified for unsync'ing are:
"colormap", "pan", "regions", "scale", "wcs", "zoom", "contrastbias".
If no array is specified, the default array in JS9.globalOpts.syncOps is
used. Thus, you can turn off sync'ing for specified operations, while
leaving others to be sync'ed.
Images to be unsync'ed can be specified as an array of image handles or
image ids. If no array is specified, all currently displayed images
are unsync'ed.
The optional opts object can contain:
- reciprocate: boolean determining whether images sync one another
- reverse: boolean to reverse this image and target images (def: false)
If the opts object is not specified, the default is to reciprocate based
on the value of the JS9.globalOpts.syncReciprocate property.
Examples:
>>> # this image won't sync on scale for foo1.fits and foo2.fits,
>>> # and they also will stop sync'ing
UnsyncImages(["scale"], ["foo1.fits", "foo2.fits"])
>>> # this image will still sync foo1.fits and foo2.fits, but
>>> # foo1.fits and foo2.fits will no longer sync this image:
UnsyncImages(null, ["foo1.fits", "foo2.fits"],
{reverse: true, reciprocal: false})
"""
return self.send({'cmd': 'UnsyncImages', 'args': args})
def MaskImage(self, *args):
"""
Mask an image using values in another image
call:
JS9.MaskImage(image, opts)
calling sequences:
JS9.MaskImage() # return current mask params
JS9.MaskImage(true||false) # turn on/off masking
JS9.MaskImage(image, opts) # set mask and optionally, its params
JS9.MaskImage(opts) # set mask params
where:
- image: image handle or image id to use as a mask
- opts: optional mask properties
and where the mask properties are:
- mode: "mask", "opacity", or "overlay"
- value: mask value that triggers masking (def: 0) for "mask" mode
- invert: whether to invert the mask (def: false) for "mask" mode
- def: object containing default RGBA values for "overlay" mode
- opacity: opacity when masking (def: 0, range 0 to 1) for both mode
The pixel values in one image can be used to mask the pixels in
another image if the two images have the same image dimensions.
The type of masking depends on the mode: "overlay" (default) or "mask".
For "mask" mode, if the value of a pixel in the mask is less than or
equal to the value property, the opacity of the displayed pixel
is set to the opacity property. You can also invert the mask
using the invert property. In effect, this mode displays only
the image pixels "covered" by a mask.
For "opacity" mode, each image pixel is assigned an opacity equal
to the value of the mask pixel (whose values are assumed to range
from 0 to 1.)
For "overlay" mode, if the mask pixel has a non-zero alpha, its color
is blended with the image pixel using source-atop composition.
Otherwise, the image pixel color alone is used in the display.
This is one way you can display a mask overlay on top of an image.
A static colormap is usually used in conjunction with an overlay
mask, since pixel values not explicitly assigned a color are
transparent. Note that, when blending a mask and image pixel, the
global mask opacity and the individual pixel opacity are multiplied to
get the final pixel opacity.
To set up a mask initially, call the routine with an already-loaded
mask image as the first parameter, and an optional opts object as the
second parameter:
>>> # default is "overlay"
>>> JS9.ImageMask("casa_mask.fits");
>>> JS9.ImageMask("casa_mask.fits", {mode: "overlay"});
>>> # "mask" mode: set lower threshold for masking and masked opacity
>>> JS9.ImageMask("mask.fits",{"mode":"mask","value":5,"opacity":0.2});
You can change the mask parameters at any time:
>>> JS9.ImageMask({value: 2, opacity: 0});
or temporarily turn off and on the mask:
>>> JS9.ImageMask(false);
>>> ...
>>> JS9.ImageMask(true);
"""
return self.send({'cmd': 'MaskImage', 'args': args})
def BlendDisplay(self, *args):
"""
Set global blend mode for specified display
call:
mode = JS9.BlendDisplay(True|False)
returns:
- mode: current image blend mode
This routine will turn on/off the global image blend mode for the
specified display. If no argument is specified, it returns the current
blend mode.
"""
return self.send({'cmd': 'BlendDisplay', 'args': args})
def GetColormap(self, *args):
"""
Get the image colormap
call:
cmap = JS9.GetColormap()
returns:
- cmap: an object containing colormap information.
The returned cmap object will contain the following properties:
- colormap: colormap name
- contrast: contrast value (range: 0 to 10)
- bias: bias value (range 0 to 1)
"""
return self.send({'cmd': 'GetColormap', 'args': args})
def SetColormap(self, *args):
"""
Set the image colormap
call:
JS9.SetColormap(cmap, [contrast, bias])
calling sequences:
JS9.SetColormap(colormap)
JS9.SetColormap(colormap, contrast, bias)
JS9.SetColormap(colormap, staticOpts)
JS9.SetColormap(contrast, bias)
JS9.SetColormap(staticOpts)
where:
- cmap: colormap name
- contrast: contrast value (range: 0 to 10)
- bias: bias value (range 0 to 1)
- staticOpts: static colormap opts
Set the current colormap, contrast/bias, or both. This call takes one
(colormap), two (contrast, bias) or three (colormap, contrast, bias)
arguments. It also takes the following single arguments:
- rgb: toggle RGB mode
- invert: toggle inversion of the colormap
- reset: reset contrast, bias, and invert values
- staticOpts: opts for a static colormap
The staticOpts argument is an array of parameters to change
in a static colormap. Each parameter can take one of two forms:
- [color, min, max]
- [color, opacity|alpha]
- [color, true|false]
The color parameter must match one of the colors specified when
the static colormap was created. The min and max properties replace
the originally specified min and max values. Specifying a number
between 0 and 1 (inclusive) will change the opacity, while specifying
a number greater than 1 will change the alpha (i.e., opacity * 255).
Specifying true or false will set or unset the active flag for that
color, i.e. it will turn on or off use of that color. When turned off,
the pixels in that range will be transparent. For example:
>>> SetColormap '[["red", 0.5], ["green", true], ["blue", false]]'
sets the opacity of red pixels to 0.5, turns on the green pixels,
and turns off the blue pixels in the currently active static colormap.
"""
return self.send({'cmd': 'SetColormap', 'args': args})
def SaveColormap(self, *args):
"""
Save colormap(s)
calling sequences:
JS9.SaveColormap() # save current colormap to "js9.cmap"
JS9.SaveColormap(fname) # save current colormap to fname
JS9.SaveColormap(cmapArray) # save array of ccmaps to "js9.cmap"
JS9.SaveColormap(fname, cmapArray) # save array of cmaps to fname
where:
- fname: output file name
- cmapArray: optional array of colormap names to save
As shown by the calling sequences above, you can use this routine to
save either the current colormap or a list of colormaps taken from the
specified array. You also can choose to save to a particular filename
or the default "js9.cmap":
>>> # save the current colormap in js9.cmap
>>> JS9.SaveColormap()
>>> # save the current colormap in foo.cmap
>>> JS9.SaveColormap("foo.cmap")
>>> # save the foo1 and foo2 colormaps in js9.cmap
>>> JS9.SaveColormap(["foo1", "foo2"])
>>> # save the user-defined foo1 and foo2 colormaps in foo.cmap
>>> JS9.SaveColormap("foo.cmap", ["foo1", "foo2"])
The colormaps are saved in JSON format. Multiple saved colormaps will
be stored in a JSON array, while a single saved colormap will be saved
at the top level.
Don't forget that the file is saved by the browser, in whatever
location you have set up for downloads.
"""
return self.send({'cmd': 'SaveColormap', 'args': args})
def AddColormap(self, *args):
"""
Add a colormap to JS9
call:
JS9.AddColormap(name, aa|rr,gg,bb|obj|json)
where:
- name: colormap name
- aa: an array containing RGB color triplets
- rr,gg,bb: 3 arrays of vertices specifying color changes
- obj: object containing one of the two colormap definition formats
- json: json string containing one of the colormap definition formats
You can add new colormaps to JS9 using one of two formats. The
first is an array of RGB triplets (i.e. an array of 3-D
arrays), where each triplet defines a color. The elements of
the colormap are divided evenly between these 3-D triplets.
For example, the i8 colormap is defined as:
>>> JS9.AddColormap("i8",
[[0,0,0], [0,1,0], [0,0,1], [0,1,1], [1,0,0],
[1,1,0], [1,0,1], [1,1,1]]))
Here, the colormap is divided into 8 sections having the
following colors: black, green, blue, cyan (green + blue),
red, yellow (red + green), purple (red + blue), and white. A
colormap such as sls also utilizes an array of RGB triplets,
but it has 200 entries, leading to much more gradual
transitions between colors.
The second colormap format consists three arrays of vertices
defining the change in intensity of red, green, and blue,
respectively. For each of these three color triplets, the
first coordinate of each vertex is the x-distance along the
colormap axis (scaled from 0 to 1) and the second coordinate
is the y-intensity of the color. Colors are interpolated
between the vertices. For example, consider the following:
>>> JS9.AddColormap("red",
[[0,0],[1,1]], [[0,0], [0,0]], [[0,0],[0,0]])
>>> JS9.AddColormap("blue",
[[0,0],[0,0]], [[0,0], [0,0]], [[0,0],[1,1]])
>>> JS9.AddColormap("purple",
[[0,0],[1,1]], [[0,0], [0,0]],[[0,0],[1,1]])
In the red (blue) colormap, the red (blue) array contains two
vertices, whose color ranges from no intensity (0) to full
intensity (1) over the whole range of the colormap (0 to
1). The same holds true for the purple colormap, except that
both red and blue change from zero to full intensity.
For a more complicated example, consider the a colormap, which is
defined as:
>>> JS9.AddColormap("a",
[[0,0], [0.25,0], [0.5,1], [1,1]],
[[0,0], [0.25,1], [0.5,0], [0.77,0], [1,1]],
[[0,0], [0.125,0], [0.5, 1], [0.64,0.5],
[0.77, 0], [1,0]])
Here we see that red is absent for the first quarter of the
colormap, then gradually increases to full intensity by the
half mark, after which it stays at full intensity to the
end. Green ramps up to full intensity in the first quarter,
then drops to zero by the half and stays that way until a bit
more than three-quarters along, after which it gradually
increases again. Blue starts off at no intensity for an
eighth, then gradually increases to full intensity by the
half-way mark, decreasing gradually to zero by the
three-quarter mark. The result is that you see, for example,
green at the beginning and yellow (red + green) at the end,
with some purple (red + blue) in the middle of the colormap.
As a convenience, you also can pass an object or json string
containing the colormap definition:
# RGB color triplets for the I8 colormap in a "colors" property
{"name":"i8",
"colors":[[0,0,0],[0,1,0],[0,0,1],[0,1,1],
[1,0,0],[1,1,0],[1,0,1],[1,1,1]]}
# all 3 vertex arrays for purple colormap in one "vertices" property
{"name":"purple",
"vertices":[[[0,0],[1,1]],[[0,0],[0,0]],[[0,0],[1,1]]]}
Finally, note that JS9.AddColormap() adds its new colormap to
all JS9 displays on the given page.
"""
return self.send({'cmd': 'AddColormap', 'args': args})
def LoadColormap(self, *args):
"""
Load a colormap file into JS9
LoadColormap(filename)
where:
- filename: input file name or URL
Load the specified colormap file into the web page. The filename,
which must be specified, can be a local file (with absolute path or a
path relative to the displayed web page) or a URL. It should contain a
JSON representation of a colormap, either in RGB color format or in
vertex format (see AddColormap() above):
>>> # RGB color format
>>> {
>>> "name": "purplish",
>>> "colors": [
>>> [0.196, 0.196, 0.196],
>>> [0.475, 0, 0.608],
>>> [0, 0, 0.785],
>>> [0.373, 0.655, 0.925],
>>> [0, 0.596, 0],
>>> [0, 0.965, 0],
>>> [1, 1, 0],
>>> [1, 0.694, 0],
>>> [1, 0, 0]
>>> ]
>>> }
>>> # vertex format
>>> {
>>> "name": "aips0",
>>> "vertices": [
>>> [
>>> [0.203, 0],
>>> [0.236, 0.245],
>>> [0.282, 0.5],
>>> [0.342, 0.706],
>>> [0.411, 0.882],
>>> [0.497, 1]
>>> ],
>>> [
>>> [0.394, 0],
>>> [0.411, 0.196],
>>> [0.464, 0.48],
>>> [0.526, 0.696],
>>> [0.593, 0.882],
>>> [0.673, 1],
>>> [0.94, 1],
>>> [0.94, 0]
>>> ],
>>> [
>>> [0.091, 0],
>>> [0.091, 0.373],
>>> [0.262, 1],
>>> [0.94, 1],
>>> [0.94, 0]
>>> ] ]
>>> }
As with AddColormap(), the new colormap will be available
in all displays.
"""
return self.send({'cmd': 'LoadColormap', 'args': args})
def GetRGBMode(self, *args):
"""
Get RGB mode information
call:
rgbobj = JS9.GetRGBMode()
returns:
- rgbobj: RGB mode information
This routine returns an object containing the following RGB mode
information:
- active: boolean specifying whether RGB mode is active
- rid: image id of "red" image
- gid: image id of "green" image
- bid: image id of "blue" image
"""
return self.send({'cmd': 'GetRGBMode', 'args': args})
def SetRGBMode(self, *args):
"""
call:
JS9.SetRGBMode(mode, [imobj])
where:
- mode: boolean true to activate RGB mode, false to disable
- imobj: optional object specifying three images to set to the
"red", "green", and "blue" colormaps
In RGB mode, three images assigned the "red", "green", and "blue"
colormaps are displayed as a single image. The RGB color of each
displayed pixel is a combination of the "red", "green", and "blue"
pixel value taken from the appropriate image. Note that all three
images are not required: you can display an RGB image using two of
the three colors simply by not assigning the third colormap.
The SetRGBMode() call turns on or off RGB mode. The
boolean mode argument specifies whether to activate or
de-activate RGB mode. The optional imobj object specifies
(already-loaded) images to assign to the three colormaps:
- rid: image id (or handle) to set to the "red" colormap
- gid: image id (or handle) to set to the "green" colormap
- bid: image id (or handle) to set to the "blue" colormap
If imobj is not specified, it is assumed that images have been
assigned the "red", "green", and "blue" colormaps by another means.
(Once again, it is not necessary to assign all three colormaps.)
"""
return self.send({'cmd': 'SetRGBMode', 'args': args})
def GetOpacity(self, *args):
"""
Get the image opacity
call:
opacity = JS9.GetOpacity()
returns:
- opacity: opacity object
The returned opacity object will contain the following properties:
- opacity: opacity value assigned to image pixels
- flooropacity: opacity assigned when the image pixel value is
less than or equal to the floor value (if defined)
- floorvalue: floor value to test image pixel values against
(if defined)
"""
return self.send({'cmd': 'GetOpacity', 'args': args})
def SetOpacity(self, *args):
"""
Set the image opacity
calling sequences:
JS9.SetOpacity(opacity) # set default opacity for all image pixels
JS9.SetOpacity(fvalue, fopacity) # pixels <= fvalue use fopacity
JS9.SetOpacity(opacity, fvalue, fopacity) # set def and floor opacity
JS9.SetOpacity("reset") # reset default opacity to 1
JS9.SetOpacity("resetfloor") # remove opacity floor
JS9.SetOpacity("resetall") # reset def opacity to 1, remove floor
where:
- opacity: opacity value for image pixels
- floorvalue: floor value to test image pixel values against
- flooropacity: floor opacity value to set
Set the current opacity, floor opacity, or both. This call takes one
(opacity), two (floorvalue, flooropacity) or three (opacity,
floorvalue, flooropacity) arguments.
The floor value & opacity option allows you to set the opacity
for pixels whose image value is less then or equal to a specified
floor value. It takes two arguments: the floor pixel value to check,
and the floor opacity to apply. For example, when both arguments are 0,
pixels whose image values are less than or equal to 0
will be transparent. Specifying 5 and 0.5, respectively, means that
pixels whose image values less than or equal to 5 will have an opacity
of 0.5. A useful case is to make the pixels transparent at a
given value, allowing features of one image to be blended into
another, without blending extraneous pixels.
The various reset options allow you to reset the default value,
floor values, or both.
"""
return self.send({'cmd': 'SetOpacity', 'args': args})
def GetZoom(self, *args):
"""
Get the image zoom factor
call:
zoom = JS9.GetZoom()
returns:
- zoom: floating point zoom factor
"""
return self.send({'cmd': 'GetZoom', 'args': args})
def SetZoom(self, *args):
"""
Set the image zoom factor
call:
JS9.SetZoom(zoom)
where:
- zoom: floating or integer zoom factor or zoom directive string
The zoom directives are:
- x[n]|X[n]: multiply the zoom by n (e.g. 'x2')
- /[n]: divide the zoom by n (e.g. '/2')
- in|In: zoom in by a factor of two
- out|Out: zoom out by a factor of two
- toFit|ToFit: zoom to fit image in display
"""
return self.send({'cmd': 'SetZoom', 'args': args})
def GetPan(self, *args):
"""
Get the image pan position
call:
ipos = JS9.GetPan()
returns:
- ipos: object containing image information for pan
The returned ipos object will contain the following properties:
- x: x image coordinate of center
- y: y image coordinate of center
"""
return self.send({'cmd': 'GetPan', 'args': args})
def SetPan(self, *args):
"""
Set the image pan position
call:
JS9.SetPan(x, y)
where:
- x: x image coordinate
- y: y image coordinate
Set the current pan position using image coordinates. Note that you can
use JS9.WCSToPix() and JS9.PixToWCS() to convert between image
and WCS coordinates.
"""
return self.send({'cmd': 'SetPan', 'args': args})
def AlignPanZoom(self, *args):
"""
Align pan and zoom of the current image to a target image
call:
JS9.AlignPanZoom(im)
where:
- im: image containing the WCS used to perform the alignment
This routine changes the pan and zoom of the current image to match a
target image, assuming both have WCS info available. The image is
panned to the RA, Dec at the center of the target image's display. The
zoom is also matched. The pixel size (as specified by the FITS CDELT1
parameter) will be taken into account when zooming, but not the image
rotation or flip. This routine is faster than ReprojectData() for
aligning reasonably similar images.
No attempt is make to keep the images aligned after the call. This
allows you to make adjustments to the current and/or target images and
then re-align as needed.
"""
return self.send({'cmd': 'AlignPanZoom', 'args': args})
def GetScale(self, *args):
"""
Get the image scale
call:
scale = JS9.GetScale()
returns:
- scale: object containing scale information
The returned scale object will contain the following properties:
- scale: scale name
- scalemin: min value for scaling
- scalemax: max value for scaling
"""
return self.send({'cmd': 'GetScale', 'args': args})
def SetScale(self, *args):
"""
Set the image scale
call:
JS9.SetScale(scale, smin, smax)
where:
- scale: scale name
- smin: scale min value
- smax: scale max value
Set the current scale, min/max, or both. This call takes one (scale),
two (smin, max) or three (scale, smin, smax) arguments.
"""
return self.send({'cmd': 'SetScale', 'args': args})
def GetFlip(self, *args):
"""
Get flip state of an image
call:
flip = JS9.GetFlip()
returns:
- flip: current flip state
Possible returned flip states are: "x", "y", "xy", or "none".
"""
return self.send({'cmd': 'GetFlip', 'args': args})
def SetFlip(self, *args):
"""
Flip an image around the x or y axis
call:
JS9.SetFlip(flip)
where:
- flip: "x", "y"
Flip an image around the specified axis. Flipping is relative to the
current state of the display, so flipping by x twice will return you
to the original orientation.
Since this operation is applied to the entire display canvas instead
of the image, image parameters such as the WCS are not affected.
"""
return self.send({'cmd': 'SetFlip', 'args': args})
def GetRotate(self, *args):
"""
Get the rotate state of an image
call:
flip = JS9.GetRotate()
returns:
- rot: current rotation value for this image
Return the current rotation.
"""
return self.send({'cmd': 'GetRotate', 'args': args})
def SetRotate(self, *args):
"""
Rotate an image by a specified number of degrees
call:
JS9.SetRotate(rot)
where:
- rot: rotation in degrees
Set the rotation of an image to the specified number of degrees. The
rotation is performed in terms of an absolute angle: if you rotate by
20 degrees and then do it again, there is no change. Also, setting the
rotation to 0 sets the angle to 0.
Since this operation is applied to the entire display canvas instead
of the image, image parameters such as the WCS are not affected.
"""
return self.send({'cmd': 'SetRotate', 'args': args})
def GetRot90(self, *args):
"""
Get the rotate state of an image
call:
flip = JS9.GetRot90()
returns:
- rot: current rotation value for this image
The returned rotation value will be a multiple of 90, depending on
how many rotations have been executed and in which direction.
"""
return self.send({'cmd': 'GetRot90', 'args': args})
def SetRot90(self, *args):
"""
Rotate an image by +/- 90 degrees
call:
JS9.SetRot90(rot)
where:
- rot: +/- 90
Rotate an image by a multiple of 90 degrees. Rot90 rotations are
relative to the current state of the display, so four rotations will
return you to the original orientation.
Since this operation is applied to the entire display canvas instead
of the image, image parameters such as the WCS are not affected.
"""
return self.send({'cmd': 'SetRot90', 'args': args})
def GetParam(self, *args):
"""
Get an image parameter value
val = GetParam(param)
where:
- param: name of the parameter
returns:
- val: value of the parameter
Return the value of an image parameter. The available parameters are
listed below in the SetParam() section.
"""
return self.send({'cmd': 'GetParam', 'args': args})
def SetParam(self, *args):
"""
Set an image parameter value
ovalue = SetParam(param, value)
where:
- param: name of the parameter
- val: new value of the parameter
returns:
- ovalue: the previous value of the parameter
A number of miscellaneous image parameters are copied from the
JS9.imageOpts object to each image when it is first loaded. You can
use the SetParam() routine to modify these values subsequently.
The available parameters and their current default values are listed
below:
- exp: 1000, default exp value for scaling
- listonchange: false, list regions after a region change?
- opacity: 1.0, image display opacity, between 0 and 1
- nancolor: "#000000", 6-digit #hex color for NaN values
- valpos: true, display value/position?
- wcsalign: true, align image using wcs after reproj?
- xeqonchange: true, xeq an onchange callback after a region change?
- zscalecontrast: 0.25, default zscale value from ds9
- zscalesamples: 600, default zscale value from ds9
- zscaleline: 120, default zscale value from ds9
The routine returns the previous value of the parameter, which can
be useful when temporarily turning off a function. For example:
>>> oval = SetParam("xeqonchange", false);
>>> .... processing ...
>>> SetParam("xeqonchange", oval);
will temporarily disable execution of the previously defined regions
onload callback, resetting it to the old value after processing
is complete.
"""
return self.send({'cmd': 'SetParam', 'args': args})
def GetValPos(self, *args):
"""
Get value/position information
call:
valpos = JS9.GetValPos(ipos)
where:
- ipos: image position object containing x and y image coord values
returns:
- valpos: value/position object
This routine determines the data value at a given image position and
returns an object containing the following information:
- ix: image x coordinate
- iy: image y coordinate
- isys: image system (i.e. 'image')
- px: physical x coordinate
- py: physical y coordinate
- psys: currently selected pixel-based system (i.e. 'image' or
'physical') for the above px, py values
- ra: ra in degrees (if WCS is available)
- dec: dec in degrees (if WCS is available)
- wcssys: wcs system (if WCS is available)
- val: floating point pixel value
- val3: pixel value as a string truncated to 3 decimal digits
- vstr: string containing value and position info
- id: id of the image
- file: filename of the image
- object: object name of the image from the FITS header
"""
return self.send({'cmd': 'GetValPos', 'args': args})
def PixToWCS(self, *args):
"""
Convert image pixel position to WCS position
call:
wcsobj = JS9.PixToWCS(x, y)
where:
- x: x image coordinate
- y: y image coordinate
returns:
- wcsobj: world coordinate system object
The wcs object contains the following properties:
- ra: right ascension in floating point degrees
- dec: declination in floating point degrees
- sys: current world coordinate system being used
- str: string of wcs in current system ('[ra] [dec] [sys]')
"""
return self.send({'cmd': 'PixToWCS', 'args': args})
def WCSToPix(self, *args):
"""
Convert WCS position to image pixel position
call:
pixobj = JS9.WCSToPix(ra, dec)
where:
- ra: right ascension in floating point degrees
- dec: declination in floating point degrees
returns:
- pixobj: pixel object
The pixel object contains the following properties:
- x: x image coordinate
- y: y image coordinate
- str: string of pixel values ('[x]' '[y]')
"""
return self.send({'cmd': 'WCSToPix', 'args': args})
def ImageToDisplayPos(self, *args):
"""
Get the display coordinates from the image coordinates
call:
dpos = JS9.ImageToDisplayPos(ipos)
where:
- ipos: image position object containing x and y image coordinate
values
returns:
- dpos: display position object containing x and y display
coordinate values
Get display (screen) coordinates from image coordinates. Note that
image coordinates are one-indexed, as per FITS conventions, while
display coordinate are 0-indexed.
"""
return self.send({'cmd': 'ImageToDisplayPos', 'args': args})
def DisplayToImagePos(self, *args):
"""
Get the image coordinates from the display coordinates
call:
ipos = JS9.DisplayToImagePos(dpos)
where:
- dpos: display position object containing x and y display
coordinate values
returns:
- ipos: image position object containing x and y image coordinate
values
Note that image coordinates are one-indexed, as per FITS conventions,
while display coordinate are 0-indexed.
"""
return self.send({'cmd': 'DisplayToImagePos', 'args': args})
def ImageToLogicalPos(self, *args):
"""
Get the logical coordinates from the image coordinates
call:
lpos = JS9.ImageToLogicalPos(ipos, lcs)
where:
- ipos: image position object containing x and y image coordinate
values
returns:
- lpos: logical position object containing x and y logical
coordinate values
Logical coordinate systems include: 'physical' (defined by LTM/LTV
keywords in a FITS header), 'detector' (DTM/DTV keywords), and
'amplifier' (ATM/ATV keywords). Physical coordinates are the most
common. In the world of X-ray astronomy, they refer to the 'zoom 1'
coordinates of the data file.
This routine will convert from image to logical coordinates. By
default, the current logical coordinate system is used. You can specify
a different logical coordinate system (assuming the appropriate
keywords have been defined).
"""
return self.send({'cmd': 'ImageToLogicalPos', 'args': args})
def LogicalToImagePos(self, *args):
"""
Get the image coordinates from the logical coordinates
call:
ipos = JS9.LogicalToImagePos(lpos, lcs)
where:
- lpos: logical position object containing x and y logical
coordinate values
returns:
- ipos: image position object containing x and y image coordinate
values
Logical coordinate systems include: 'physical' (defined by LTM/LTV
keywords in a FITS header), 'detector' (DTM/DTV keywords), and
'amplifier' (ATM/ATV keywords). Physical coordinates are the most
common. In the world of X-ray astronomy, they refer to the 'zoom 1'
coordinates of the data file.
This routine will convert from logical to image coordinates. By
default, the current logical coordinate system is used. You can specify
a different logical coordinate system (assuming the appropriate
keywords have been defined).
"""
return self.send({'cmd': 'LogicalToImagePos', 'args': args})
def GetWCSUnits(self, *args):
"""
Get the current WCS units
call:
unitsstr = JS9.GetWCSUnits()
returns:
- unitstr: 'pixels', 'degrees' or 'sexagesimal'
"""
return self.send({'cmd': 'GetWCSUnits', 'args': args})
def SetWCSUnits(self, *args):
"""
Set the current WCS units
call:
JS9.SetWCSUnits(unitsstr)
where:
- unitstr: 'pixels', 'degrees' or 'sexagesimal'
Set the current WCS units.
"""
return self.send({'cmd': 'SetWCSUnits', 'args': args})
def GetWCSSys(self, *args):
"""
Get the current World Coordinate System
call:
sysstr = JS9.GetWCSSys()
returns:
- sysstr: current World Coordinate System ('FK4', 'FK5', 'ICRS',
'galactic', 'ecliptic', 'image', or 'physical')
"""
return self.send({'cmd': 'GetWCSSys', 'args': args})
def SetWCSSys(self, *args):
"""
Set the current World Coordinate System
call:
JS9.SetWCSSys(sysstr)
where:
- sysstr: World Coordinate System ('FK4', 'FK5', 'ICRS',
'galactic', 'ecliptic', 'image', or 'physical')
Set current WCS system. The WCS systems are available only if WCS
information is contained in the FITS header. Also note that 'physical'
coordinates are the coordinates tied to the original file. They are
mainly used in X-ray astronomy where individually detected photon
events are binned into an image, possibly using a blocking factor. For
optical images, image and physical coordinate usually are identical.
"""
return self.send({'cmd': 'SetWCSSys', 'args': args})
def DisplayMessage(self, *args):
"""
Display a text message
call:
JS9.DisplayMessage(which, text)
where:
- which: "info" or "regions"
- text: text to display
The text string is displayed in the "info" area (usually occupied by the
valpos display) or the "region" area (where regions are displayed). The
empty string will clear the previous message.
"""
return self.send({'cmd': 'DisplayMessage', 'args': args})
def DisplayCoordGrid(self, *args):
"""
Display a WCS-based coordinate grid
call:
JS9.DisplayCoordGrid(mode, opts)
where:
- mode: true (display) or false (hide)
- opts: optional object or json string containing grid parameters
A coordinate grid displays lines of constant RA and constant Dec, with
the points of intersection labeled by their RA and Dec values. The
labels are in sexagesimal notation if the WCS units are sexagesimal,
otherwise they are in degrees. When using sexagesimal notation, labels
will be shortened if possible, e.g., if the RA hours are the same in
two successive labels but the minutes are different, only the minutes
are shown in the second label.
If no arguments are supplied, the routine returns true if the
coordinate grid is currently being displayed, false otherwise. A
boolean first argument specifies whether to display the coordinate
grid or not.
The optional second argument is an opts object (or a json-formatted
string) containing properties to override the default JS9.Grid.opts
properties. These properties include:
- raLines: approx. number of RA grid lines
- decLines: approx. number of Dec grid lines
- stride: fineness of grid lines
- margin: edge margin for displaying a line
- lineColor: color of grid lines
- strokeWidth: grid stroke width
- raAngle: rotation for RA label
- decAngle: rotation for Dec label
- labelColor: color of text labels
- labelFontFamily: label font
- labelFontSize: label font size
- labelRAOffx: x offset of RA labels
- labelRAOffy: y offset of RA labels
- labelDecOffx: x offset of Dec labels
- labelDecOffy: y offset of Dec labels
- degPrec: precision for degree labels
- sexaPrec: precision for sexagesimal labels
- reduceDims: reduce lines of smaller image dim?
- cover: grid lines cover: display or image
The strokeWidth property determines the width of the grid
lines. It also serves as a reminder that you can pass other
standard shape properties in the opts object.
JS9's label placement algorithm puts labels close to the
intersection of RA and Dec lines. A number of properties can be
useful in cases where this simple algorithm is not sufficient:
the raAngle and decAngle properties allow you to rotate the
labels with respect to the grid lines. The four
label[RA,Dec]Off[x,y] properties allow you to move the label with
respect to the grid lines. The raSkip and decSkip properties
allow you to skip labelling the first available lines within the
display. It can be useful, for example, on a rotated image, when
the labels are placed in a corner.
The degPrec and sexaPrec properties specify the precision for
degree values and segagesimal values, respectively. Higher
precision will use more digits and take more space along each line.
A number of properties are (more or less) internal but might be
of use: the reduceDims property will reduce the raLines and
decLines properties by the ratio of image dimensions if one
dimension is smaller than the other. This can prevent crowding in
the smaller dimension. The stride property specifies the length
of each line segment that together make up a grid line. A smaller
stride might make the grid lines smoother in some cases, at the
price of more processing time. The cover property determines
whether the grid is drawn over the entire image or just the
displayed part of the image. At the moment, drawing lines over
the displayed part of the image seems to be sufficient.
Note that you can specify global site-wide values for all these
parameters (overriding the JS9.Grid.opts defaults) by supplying them
in a grid object within the globalOpts object in the js9prefs.js file.
Example: display a coordinate grid, specifying the line color:
>>> JS9.DisplayCoordGrid(true, {lineColor: "pink"});
"""
return self.send({'cmd': 'DisplayCoordGrid', 'args': args})
def CountsInRegions(self, *args):
"""
Get background-subtracted counts in regions
call:
JS9.CountsInRegions(sregion, bregion, opts)
where:
- sregion: source region ("$sregions" for displayed source regions)
- bregion: background region ("$bregions" for displayed bkgd regions)
- opts: optional object or json string containing region parameters
The regcnts program (and its predecessor, funcnts) counts photons in
specified source regions and optionally, in specified background
regions. Displayed results include the bkgd-subtracted counts in each
region, as well as the error on the counts, the area in each region,
and the surface brightness (cnts/area**2) calculated for each region.
Regcnts for desktop use is available on GitHub at:
https://github.com/ericmandel/regions.
The regcnts program has been compiled into JS9 using Emscripten.
Using this routine, regcnts can be run on the FITS memory-based file
for the currently displayed image. The first two arguments specify
the source region(s) and background region(s), respectively.
You can pass a standard region specifier as the source
or background region. If the string "$sregions" ("$bregions") is
specified, the source (background) regions are taken from the
currently displayed image.
In keeping with how desktop regcnts works, if no argument or null or a
null string is specified as the source region, the entire field is
used as the source region. If no argument or null or a null string is
explicitly specified as a background region, no regions are used for
the background. In particular, if you pass only the source region
argument, or pass only the source region and opts arguments, no
background region is used. To recap:
>>> # use entire field, no background
>>> JS9.CountsInRegions([opts])
>>> JS9.CountsInRegions("field"||null||""[, opts])
>>> # use displayed source and displayed background
>>> JS9.CountsInRegions("$sregions", "$bregions"[, opts])
>>> # use displayed source, no background
>>> JS9.CountsInRegions("$sregions"[, opts])
>>> # use displayed source and specified background
>>> JS9.CountsInRegions("$sregions", bregions[, opts])
>>> # use specified source, no background
>>> JS9.CountsInRegions(sregions[, opts])
>>> # use specified source and specified background
>>> JS9.CountsInRegions(sregions, bregions[, opts])
>>> # use specified source and displayed background
>>> JS9.CountsInRegions(sregions, "$bregions"[, opts])
>>> # use entire field and specified background
>>> JS9.CountsInRegions("field"||null||"", bregions[, opts])
>>> # use entire field and displayed background
>>> JS9.CountsInRegions("field"||null||"", "$bregions"[, opts])
The third argument allows you to specify options to regcnts:
- cmdswitches: command line switches passed to regcnts
- dim: size of reduced image (def: max of JS9.globalOpts.image.[xy]dim)
- reduce: reduce image size? (def: true)
- lightwin: if true, results displayed in light window
The command line switches that can be specified in cmdswitches are
detailed in https://js9.si.edu/regions/regcnts.html, the regcnts help
page. Aside from switches which control important aspects of the
analysis, the "-j" switch (which returns the output in JSON format)
might be useful in the browser environment. Some examples:
>>> # display results in a light window
>>> JS9.CountsInRegions({lightwin: true})
>>> # return json using maximum precision in output
>>> JS9.CountsInRegions({cmdswitches: "-j -G"})
Results are also returned as a text string.
The regcnts code is memory (and cpu) intensive. In the desktop
environment, this is not typically a problem, but the
memory-constrained browser environment can present a challenge for
large images and binary tables. To avoid running out of memory (and
for large images, to speed up processing considerably), the
CountsInRegions() routine will bin the image to reduce its size,
unless the reduce option is explicitly set to false. The binned
image size can be specified by the dim option, defaulting to
the global value of the image dimension options. When a file is binned
in this manner, the returned resolution value (e.g., arcsec/pixel)
will reflect the applied binning. Note that the number of photons
found inside a binned and unbinned region differ slightly, due to the
difference in the pixel boundaries in the two cases.
The Counts in Regions option of the Analysis -> Client-side
Analysis menu runs regcnts on the source and background regions of
the currently displayed image. The results are displayed in a light
window.
Finally, note that the main JS9 web site at https://js9.si.edu
also offers regcnts as a server-based analysis program in the
Analysis menu. The displayed source and background regions are passed
to the server for processing. Because this version runs the desktop
program, it runs on the original file and does no binning to reduce
the image size (which, by the way, could lengthen the processing
time). But the server-side task also can be useful for
JS9 large file support, which involves displaying a small
representation file associated with a much larger parent
file stored on the server. In this case, you often want to run
the analysis on the larger (original) file.
"""
return self.send({'cmd': 'CountsInRegions', 'args': args})
def GaussBlurData(self, *args):
"""
Gaussian blur of raw data
call:
JS9.GaussBlurData(sigma, opts)
where:
- sigma: sigma of Gaussian function
- opts: options object
This routine creates a new raw data layer called "gaussBlur"
in which the image pixel values are blurred using a Gaussian
function with the specified sigma. The routine uses the fast
Gaussian blur algorithm (approximating a full Gaussian blur
with three passes of a box blur) described in:
http://blog.ivank.net/fastest-gaussian-blur.html.
"""
return self.send({'cmd': 'GaussBlurData', 'args': args})
def ImarithData(self, *args):
"""
Perform image arithmetic on raw data
call:
JS9.ImarithData(op, arg1, opts)
where:
- op: image operation: "add", "sub", "mul", "div",
"min", "max", "reset"
- arg1: image handle, image id or numeric value
- opts: options object
The JS9.ImarithData() routine performs basic arithmetic
(addition, subtraction, multiplication, division, minimum,
maximum, average) between the currently displayed image and
either another image or a constant value. The first op
argument is a string, as detailed above. The second arg1
argument can be a numeric value or an image id. In the former
case, the constant value is applied to each pixel in the
image. In the latter case, the operation is performed between
the corresponding pixels in the two images. For example:
>>> JS9.ImarithData("max", "foo.fits")
will make a new data layer of the currently displayed image, where
each pixel is the larger value from that image and the foo.fits image
(which can be in any display).
This routine creates a new raw data layer called "imarith"
containing the results of the operation. Successive calls to
this routine are cumulative, so that you can build up a more
complex operation from simple ones. For example:
>>> # foo.fits is displayed in the "myJS9" display
>>> myim = JS9.GetImage()
>>> JS9.ImarithData("max", myim)
>>> JS9.ImarithData("add", 2.718)
will make a new data layer where each pixel is the larger value from
the two images, after which an approximation of the irrational number
e is added to each pixel.
The special reset operation deletes the "imarith" raw data
layer, allowing you to start afresh.
The bitpix value of the new "imarith" layer is chosen as follows:
- for operations between two images, bitpix the "larger" of
the two images (where float is "larger" than int).
- for operations between an image and a constant, bitpix of -32
(single float) is chosen unless the image itself has bitpix of -64, in
which case the double float bitpix is chosen.
You can override the choice of bitpix by passing a bitpix property
in the optional opts object.
Finally, note that the two images must have the same dimensions. We
might be able to remove this restriction in the future, although
it is unclear how one lines up images of different dimensions.
"""
return self.send({'cmd': 'ImarithData', 'args': args})
def ShiftData(self, *args):
"""
Shift raw data
call:
JS9.ShiftData(x, y, opts)
where:
- x: number of pixels to shift in the x (width) direction
- y: number of pixels to shift in the y (height) direction
- opts: options object
This routine creates a new raw data layer called "shift" in which
the pixels are shifted from the original image array by the specified
amount in x and/or y. The results of successive shifts are
cumulative. The routine is used by the Harvard-Smithsonian Center for
Astrophysics MicroObservatory project interactively to align images
that are only slightly offset from one another.
"""
return self.send({'cmd': 'ImarithData', 'args': args})
def FilterRGBImage(self, *args):
"""
Apply a filter to the RGB image
call:
JS9.FilterRGBImage(filter, args)
where:
- filter: name of image filter to apply to the RGB data
- args: filter-specific arguments, where applicable
In JS9, you can change the raw data (and hence the displayed
image) using routines such as JS9.GaussBlurData() or the more
general JS9.RawDataLayer(). You also can apply image
processing techniques directly to the displayed RGB image
without changing the underlying raw data, using this
routine. The web has an overwhelming amount of information
about image processing. A good technical article concerning
the use of image filters with Javascript and the HTML5 canvas
is available at:
http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
The JS9.FilterRGBImage() routine supports a number of image
processing routines, which are listed below. To call one of
them using JS9.FilterRGBImage(), supply the filter name,
followed by any filter-specific arguments, e.g.:
>>> JS9.FilterRGBImage("luminance")
>>> JS9.FilterRGBImage("duotone", "g")
>>> JS9.FilterRGBImage("convolve", [-1,-1,-1,-1,8,-1,-1,-1,-1])
You can, of course, use the default arguments where applicable.
Note that the standard JS9 colormaps, scale, contrast and bias
selections are applied to the raw data to regenerate the RGB
image. Thus, if you use any of the image processing techniques
listed below and then change colormap, contrast, bias, or
scale, you will undo the applied image processing. This is a
good way to reset the displayed image. The same thing can be
accomplished programmatically by specifying "reset" as the
filter name:
>>> JS9.FilterRGBImage("reset")
The following simple image processing filters are available:
- luminance():convert to greyscale using the CIE luminance:
0.2126*r + 0.7152*g + 0.0722*b
- greyscale():convert to greyscale using the standard greyscale:
0.3*r + 0.59*g + 0.11*b
- greyscaleAvg():convert to greyscale using averaging:
(r+g+b) / 3
- brighten(val): add const val to each pixel to change the brightness:
[r + val, g + val, b + val]
- noise(v1, v2): add random noise:
pixel += Math.floor((Math.random()*(v2-v1)) - v2),
defaults are v1=-30, v2=30
- duotone("r"|"g"|"b"): remove a color by setting it to
the avg of the two others: r=(g+b)/2, default color is "r"
- invert(): the RGB channels of the image are inverted:
[255-r, 255-g, 255-b, a]
- pixelate(size):make image look coarser by creating a square tiling
effect of the specified size, default size is 2
- sepia(): image takes on shades of brown, like an antique photograph
- contrast(val): change the difference in brightness between the min
and max intensity of a pixel, default val is 2
- threshold(thresh, low, high):create a two-color image in which pixels
less bright than thresh are assigned the low value (default 0 for
black), otherwise the high value (default: 255 for white)
- gamma(gcorr): apply the nonlinear gamma operation, used to code and
decode luminance values in video or still image systems:
out = pow(in, gcorr), default gcorr is 0.2
- posterize(): convert a smooth gradation of tone to regions
of fewer tones, with abrupt changes between them
- scatter(): scatters the colors of a pixel in its neighborhood, akin
to viewing through brittle cracked glass
- solarize(): which image is wholly or partially reversed in
tone. Dark areas appear light or light areas appear dark.
The following image convolutions are available:
- convolve(weights, [opaque]) convolve the image using the
weights array as a square convolution matrix. If opaque is true
(default), the image will have an opaque alpha channel, otherwise the
alpha is convolved as well.
- sobel(): use the Sobel operator to create an image that
emphasizes the edges
- medianFilter(): noise reduction technique that replaces each
pixel with the median of neighboring pixels
- gaussBlur5(): image pixel values are blurred using a 5x5 Gaussian
- edgeDetect(): detect edges using the kernel
[ -1, -1, -1, -1, 8, -1, -1, -1, -1 ]
- sharpen(val): sharpen the image using the kernel
[ 0, -3, 0, -3, val, -3, 0, -3, 0 ]
- blur(): blur the image using the kernel
[ 1, 2, 1, 2, 1, 2, 1, 2, 1 ]
- emboss(val): produce embossing effect using the kernel
[-18, -9, 9, -9, 100 - val, 9, 0, 9, 18 ]
- lighten(val): apply the kernel
[ 0, 0, 0, 0, val, 0, 0, 0, 0 ],
default val of 12/9 lightens the image
- darken(val): apply the kernel
[ 0, 0, 0, 0, val, 0, 0, 0, 0],
default val of 6/9 darkens the image
With no arguments, the routine returns an array of available filters:
>>> JS9.FilterRGBImage()
["convolve", "luminance", ..., "blur", "emboss", "lighten", "darken"]
"""
return self.send({'cmd': 'FilterRGBImage', 'args': args})
def ReprojectData(self, *args):
"""
Reproject an image using a specified WCS
call:
JS9.ReprojectData(wcsim, opts)
where:
- wcsim: image containing the WCS used to perform the reprojection
- opts: options object
JS9.ReprojectData() creates a new raw data layer (with default id of
"reproject") in which the pixels are reprojected using the WCS from
another image. The mProjectPP program from the Montage software suite
is used to perform the reprojection. Please read the documentation on
mProjectPP from the Montage web site, which includes this explanation:
mProjectPP performs a plane-to-plane transform on the input
image, and is an adaptation of the Mopex algorithm and
developed in collaboration with the Spitzer Space
Telescope. It provides a speed increase of approximately a
factor of 30 over the general-purpose mProject. However,
mProjectPP is only suitable for projections which can be
approximated by tangent-plane projections (TAN, SIN, ZEA, STG,
ARC), and is therefore not suited for images covering large
portions of the sky. Also note that it does not directly
support changes in coordinate system (i.e. equatorial to
galactic coordinates), though these changes can be facilitated
by the use of an alternate header.
The wcsim argument is an image id, image filename, or image
object pointing to the WCS image.
The opts object can contain the following reproject-specific props:
- rawid: the id of the raw data layer to create (default: "reproject")
- cmdswitches: a string containing mProjectPP command line switches
The cmdswitches will be prepended to the mProjectPP command line:
{cmdswitches: "-d 1 -z .75"}
will set the mProjectPP debugging and the drizzle factor,
resulting in a command line that looks like this:
mProjectPP -d 1 -z .75 -s statusfile in.fits out.fits template.hdr
See the mProjectPP documentation for more information about
command switches.
Reprojection is an intensive process which can take a
considerable amount of memory and processing time. To avoid
crashes, we currently restrict the WCS image size used for
reprojection to a value defined by JS9.REPROJDIM, currently
2200 x 2200. Even this might be too large for iOS devices
under certain circumstances, although issues regarding memory
are evolving rapidly.
"""
return self.send({'cmd': 'ReprojectData', 'args': args})
def RotateData(self, *args):
"""
Rotate an image around the WCS CRPIX point
call:
JS9.RotateData(angle, opts)
where:
- angle: rotation angle in degrees
- opts: options object
The JS9.RotateData() routine uses JS9.ReprojectData() to rotate
image data by the specified angle (in degrees). If the string
"northup" or "northisup" is specified, the rotation angle is set to 0.
The rotation is performed about the WCS CRPIX1, CRPIX2 point.
The optional opts object is passed directly to the JS9.ReprojectData()
routine. See JS9.ReprojectData() above for more information.
"""
return self.send({'cmd': 'RotateData', 'args': args})
def SaveSession(self, *args):
"""
Save an image session to a file
call:
JS9.SaveSession(session)
where:
- session: name of the file to create when saving this session
This routine saves all essential session information about the
currently displayed image (filename, scaling, colormap, contrast/bias,
zoom, regions, catalogs, etc) in a json-formatted file. You can
subsequently load this file into JS9 to restore the image session.
The session file is a text file and can be edited, subject to the
usual rules of json formatting. For example, you can change the
colormap, scaling, etc. after the fact.
Don't forget that the file is saved by the browser, in whatever
location you have set up for downloads.
The session file contains a file property near the top that
specifies the location of the image. A local file usually will
contain an absolute path or a path relative to the web page
being displayed. However, if the image was originally opened
using drag-and-drop, no pathname information is available, in
accordance with standard web security protocols. In this case,
you must edit the session file to supply the path (either
absolute or relative to the web page) before re-loading the
session.
"""
return self.send({'cmd': 'SaveSession', 'args': args})
def LoadSession(self, *args):
"""
Load a previously saved image session from a file
call:
JS9.LoadSession(session)
where:
- session: name of the session file to load
Restore an image session by loading a json-formatted session file. The
image itself is retrieved and loaded, and all of the saved parameters
and graphics (scale, colormap, regions, catalogs etc) are applied to
the display.
The session file contains a file property near the top that
specifies the location of the image. A local file usually will
contain an absolute path or a path relative to the web page
being displayed. However, if the image was originally opened
using drag-and-drop, no pathname information is available, in
accordance with standard web security protocols. In this case,
you must edit the session file to supply the path (either
absolute or relative to the web page) before re-loading the
session.
Note that the raw data file itself is not saved (only its
pathname), so you must have access to that file in order to
restore a session. However, the data file need not be in the
same location as it was originally: you can adjust the path of
the data file by editing the file property as needed.
"""
return self.send({'cmd': 'LoadSession', 'args': args})
def NewShapeLayer(self, *args):
"""
Create a new shape layer
call:
lid = JS9.NewShapeLayer(layer, opts)
where:
- layer: name of the layer to create
- opts: default options for this layer
returns:
- lid: layer id
This routine creates a new named shape layer. You can then, add,
change, and remove shapes in this layer using the routines below. The
catalogs displayed by the Catalog plugin are examples of separate shape
layers. The optional opts parameter allows you to specify default
options for this layer. You can set a default for any property needed
by your shape layer. See JS9.Regions.opts in js9.js for an example of
the default options for the regions layer.
"""
return self.send({'cmd': 'NewShapeLayer', 'args': args})
def ShowShapeLayer(self, *args):
"""
Show or hide the specified shape layer
call:
JS9.ShowShapeLayer(layer, mode)
where:
- layer: name of layer
- mode: true (show layer) or false (hide layer)
Shape layers can be hidden from display. This could be useful, for
example, if you have several catalogs loaded into a display and want to
view one at a time.
If mode is true, a previously hidden shape layer will be displayed. If
mode is false, a displayed shape layer will be hidden. If the
mode argument is not supplied, the current mode is returned.
"""
return self.send({'cmd': 'ShowShapeLayer', 'args': args})
def ToggleShapeLayers(self, *args):
"""
Toggle display of the active shape layers
call:
JS9.ToggleShapeLayers()
While ShowShapeLayer() allows you to display or hide a single shape
layer, this routine will toggle display of all active layers in the
current image. An active layer is one that has not been turned off
usng the Shape Layers plugin or ShowShapeLayer().
The routine remembers which layers were active at the moment when
layers are hidden and restores only those layers in the next toggle.
Thus, if you have two layers, "regions" and "catalog1", and the
"catalog1" layer has previously been turned off, calling this routine
repeatedly will turn on and off the "regions" layer only.
"""
return self.send({'cmd': 'ToggleShapeLayers', 'args': args})
def ActiveShapeLayer(self, *args):
"""
Make the specified shape layer the active layer
call:
JS9.ActiveShapeLayer(layer)
where:
- layer: name of layer
returns:
- active: the active shape layer (if no args are specified)
For a given image, one shape layer at a time is active, responding to
mouse and touch events. Ordinarily, a shape layer becomes the active
layer when it is first created and shapes are added to it. Thus, the
first time you create a region, the regions layer becomes active. If
you then load a catalog into a layer, that layer becomes active.
If no arguments are supplied, the routine returns the currently active
layer. Specify the name of a layer as the first argument to make it
active. Note that the specified layer must be visible.
"""
return self.send({'cmd': 'ActiveShapeLayer', 'args': args})
def AddShapes(self, *args):
"""
Add one or more shapes to the specified layer
call:
JS9.AddShapes(layer, sarr, opts)
where:
- layer: name of layer
- sarr: a shape string, shape object, or an array of shape objects
- opts: global values to apply to each created shape
returns:
- id: id of last shape created
The sarr argument can be a shape ('annulus', 'box', 'circle',
'ellipse', 'point', 'polygon', 'text'), a single shape object, or an
array of shape objects. Shape objects contain one or more properties,
of which the most important are:
- shape: 'annulus', 'box', 'circle', 'ellipse', 'point', 'polygon',
'text' [REQUIRED]
- x: image x position
- y: image y position
- dx: increment from current image x position
- dy: increment from current image y position
- tags: comma separated list of tag strings
- radii: array of radii for annulus shape
- width: width for box shape
- height: height for box shape
- radius: radius value for circle shape
- r1: x radius for ellipse shape (misnomer noted)
- r2: y radius for ellipse shape (misnomer noted)
- pts: array of objects containing x and y positions, for polygons
- points: array of objects containing x and y offsets from the
specified center, for polygons
- angle: angle in degrees for box and ellipse shapes
- color: shape color (string name or #rrggbb syntax)
- text: text associated with text shape
Other available properties include:
- fixinplace: if true, shape cannot be moved or resized
- lockMovementX: shape cannot be moved in the x direction
- lockMovementY: shape cannot be moved in the y direction
- lockRotation: shape cannot be rotated
- lockScalingX: shape cannot be resized in the x direction
- lockScalingY: shape cannot be resized in the y direction
- fontFamily: font parameter for text shape
- fontSize: font parameter for text shape
- fontStyle: font parameter for text shape
- fontWeight: font parameter for text shape
"""
return self.send({'cmd': 'AddShapes', 'args': args})
def RemoveShapes(self, *args):
"""
Remove one or more shapes from the specified shape layer
call:
JS9.RemoveShapes(layer, shapes)
where:
- layer: name of layer
- shapes: which shapes to remove
If the shapes argument is not specified, it defaults to "all". You
can specify a selector using any of the following:
- all: all shapes not including child text shapes
- All: all shapes including child text shapes
- selected: the selected shape (or shapes in a selected group)
- [color]: shapes of the specified color
- [shape]: shapes of the specified shape
- [wcs]: shapes whose initial wcs matches the specified wcs
- [tag]: shapes having the specified tag
- /[regexp]/: shapes with a tag matching the specified regexp
- child: a child shape (i.e. text child of another shape)
- parent: a shape that has a child (i.e. has a text child)
"""
return self.send({'cmd': 'RemoveShapes', 'args': args})
def GetShapes(self, *args):
"""
Get information about one or more shapes in the specified shape
layer
call:
JS9.GetShapes(layer, shapes)
where:
- layer: name of layer
- shapes: which shapes to retrieve
returns:
- sarr: array of shape objects
Each returned shape object contains the following properties:
- id: numeric region id (assigned by JS9 automatically)
- mode: 'add', 'remove', or 'change'
- shape: region shape ('annulus', 'box', 'circle', 'ellipse',
'point', 'polygon', 'text')
- tags: comma delimited list of region tags (e.g., 'source',
'include')
- color: region color
- x,y: image coordinates of region
- size: object containing width and height for box region
- radius: radius value for circle region
- radii: array of radii for annulus region
- eradius: object containing x and y radii for ellipse regions
- pts: array of objects containing x and y positions, for polygons
- angle: angle in degrees for box and ellipse regions
"""
return self.send({'cmd': 'GetShapes', 'args': args})
def ChangeShapes(self, *args):
"""
Change one or more shapes in the specified layer
call:
JS9.ChangeShapes(layer, shapes, opts)
where:
- layer: name of layer
- shapes: which shapes to change
- opts: object containing options to change in each shape
Change one or more shapes. The opts object can contain the parameters
described in the JS9.AddShapes() section. However, you cannot (yet)
change the shape itself (e.g. from 'box' to 'circle').
If the shapes argument is not specified, it defaults to "all". You
can specify a selector using any of the following:
- all: all shapes not including child text shapes
- All: all shapes including child text shapes
- selected: the selected shape (or shapes in a selected group)
- [color]: shapes of the specified color
- [shape]: shapes of the specified shape
- [wcs]: shapes whose initial wcs matches the specified wcs
- [tag]: shapes having the specified tag
- /[regexp]/: shapes with a tag matching the specified regexp
- child: a child shape (i.e. text child of another shape)
- parent: a shape that has a child (i.e. has a text child)
"""
return self.send({'cmd': 'ChangeShapes', 'args': args})
def CopyShapes(self, *args):
"""
Copy a shape layer to another image
call:
JS9.CopyShapes(to, layer)
where:
- to: image id to which to copy shapes
- layer: shape layer to copy
Copy regions to a different image. If to is "all", then the
regions are copied to all images.
All shapes in the shape layer are copied to the new image.
"""
return self.send({'cmd': 'CopyShapes', 'args': args})
def SelectShapes(self, *args):
"""
Gather Shapes into a Selection
call:
JS9.SelectShapes(layer, shapes)
where:
- layer: shape layer
- shapes: which shapes to select
JS9 has a rich mouse-based interface for selecting shapes: a single
shape is selected by clicking on it. A number of shapes can be
gathered into a group selection by pressing the left mouse button and
dragging the mouse over the desired shapes. To add to an
already-existing selection, shift-click the mouse on a shape.
This routine allows you to create a selection programmatically by
specifying which shapes make up the selection. The first argument
is the shape layer. The second argument is the regions selection.
If not specified, it defaults to "all". The call creates a selection
of shapes which can be moved as one unit.
For example:
>>> j.SelectShapes("myreg", "circle") # select all circles
>>> j.SelectShapes("myreg", "circle&&!foo2") # circles w/o 'foo2' tag
Regions in a selection are processed individually, i.e. a regions
selection will match the regions inside a group. Thus for example,
if you create a selection containing circles, changing the color using
the "circle" specification will also affect the circles within the
selection. You can, of course, process only the regions inside a
selection using the selected specification.
"""
return self.send({'cmd': 'SelectShapes', 'args': args})
def UnselectShapes(self, *args):
"""Remove Shapes From a Selection
call:
JS9.UnselectShapes(layer, shapes)
where:
- layer: shape layer
- shapes: which shapes to select
JS9 has a rich mouse-based interface for selecting shapes: a single
shape is selected by clicking on it. A number of shapes can be
gathered into a group selection by pressing the left mouse button and
dragging the mouse over the desired shapes. To add to an
already-existing selection, shift-click the mouse on a shape.
This routine allows you to remove one or more shapes from a shape
selection programmatically by specifying which shapes to remove.
The first argument is the shape layer. The second argument is the
shape selection. In not specified, or specified as "all" or "selected",
the selection is undone. Otherwise the call will make a new
selection, not containing the unselected shapes, which can be
moved as one unit.
"""
return self.send({'cmd': 'UnselectShapes', 'args': args})
def GroupShapes(self, *args):
"""
Gather Shapes into a Long-lived Group
call:
JS9.GroupShapes(layer, shapes, opts)
where:
- layer: shape layer
- shapes: which shapes to group
- opts: optional object containing grouping options
returns:
- groupid: the group id associated with the newly created group
A shape group can be moved and resized as a single unit. To
first order, it is a long-lived form of a region selection.
The latter gets dissolved when you click the mouse outside the
selection, but a shape group is dissolved only by
calling j.UngroupShapes().
This routine allows you to create a group by specifying the shapes
which will compose it. The first argument is the regions selection.
If not specified, it defaults to either 'selected' or 'all', depending
on whether a shape selection currently exits.
The optional opts argument contains the following properties:
- groupid: the group id to use, if possible (default: 'group_[n]')
- select: if false, the group is not selected upon creation
By default, the groupid will be the string 'group_' followed by
an integer chosen so that the groupid is unique. You can supply your
own groupid, but if it already is associated with an existing group,
an integer value will be appended to make it unique. Also, by default
the newly created group will be 'selected'. You can pass
the select property with a value of false in order to
avoid selecting the group (e.g., if you are creating a number of
groups and do not want to see each of them selected in turn.)
The returned groupid string can be used to select and process all the
shapes in that group. Thus, for example, you can use the groupid to
change the color of all grouped shapes:
>>> gid = j.GroupShapes('myreg', 'circle && foo1');
>>> j.ChangeShapes('myreg', gid, {'color':'red'});
Note however, that unlike the temporary shape selections, shapes
in a group are not available individually, i.e., a regions selection
using a non-groupid does not match shapes inside a group. Thus, for
example, if you have created a group of circles, changing the color
using a 'circle' specification does not affect circles within the group:
>>> gid = j.GroupShapes('myreg', 'circle && foo1');
>>> j.ChangeShapes('myreg', 'circle', {'color':'cyan'}) # no
>>> j.ChangeShapes('myreg', gid, {'color':'red'}); # yes
Furthermore, a given shape can only be part of one group at a
time. In the case where a shape already is part of an existing group,
the globalOpts.regGroupConflict property determines how that shape
is processed. The default is skip, meaning that the shape is
silently skipped over when creating the new group. The alternative
is error, which will throw an error.
"""
return self.send({'cmd': 'GroupShapes', 'args': args})
def UngroupShapes(self, *args):
"""
Dissolve a Group of Shapes
call:
JS9.UngroupShapes(layer, groupid, opts)
where:
- layer: shape layer
- groupid: group id of the group to dissolve
- opts: optional object containing ungrouping options
This routine allows you to dissolve an existing group, so that the
shapes contained therein once again become separate. The first
argument is the groupid, previously returned by the JS9.GroupShapes()
call.
The optional opts argument contains the following properties:
- select: newly separate shapes in the group are 'selected'?
By default, the ungrouped shapes unobtrusively take their place among
other shapes on the display. You can make them be selected by
passing the select: true property in opts. Doing this, for
example, would allow you to remove them easily with the Delete key.
For example:
>>> gid = j.GroupShapes('myreg', 'circle || ellipse')
>>> j.UngroupShapes('myreg', gid)
"""
return self.send({'cmd': 'UngroupShapes', 'args': args})
def AddRegions(self, *args):
"""
Add one or more regions to the regions layer
call:
id = JS9.AddRegions(rarr, opts)
where:
- rarr: a shape string, region object or an array of region objects
- opts: global values to apply to each created region
returns:
- id: id of last region created
The rarr argument can be a region shape ('annulus', 'box', 'circle',
'ellipse', 'point', 'polygon', 'text'), a single region object, or an
array of region objects. Region objects contain one or more properties,
of which the most important are:
- shape: 'annulus', 'box', 'circle', 'ellipse', 'point', 'polygon',
'text' [REQUIRED]
- x: image x position
- y: image y position
- lcs: object containing logical x, y and sys (e.g. 'physical')
- dx: increment from current image x position
- dy: increment from current image y position
- tags: comma separated list of tag strings
- radii: array of radii for annulus region
- width: width for box region
- height: height for box region
- radius: radius value for circle region
- r1: x radius for ellipse region (misnomer noted)
- r2: y radius for ellipse region (misnomer noted)
- pts: array of objects containing x and y positions for polygons
- points: array of objects containing x and y offsets from the
center for polygons
- angle: angle in degrees for box and ellipse regions
- color: region color (string name or #rrggbb syntax)
- text: text associated with text region
Other available properties include:
- fixinplace: if true, region cannot be moved or resized
- lockMovementX: region cannot be moved in the x direction
- lockMovementY: region cannot be moved in the y direction
- lockRotation: region cannot be rotated
- lockScalingX: region cannot be resized in the x direction
- lockScalingY: region cannot be resized in the y direction
- fontFamily: font parameter for text region
- fontSize: font parameter for text region
- fontStyle: font parameter for text region
- fontWeight: font parameter for text region
"""
return self.send({'cmd': 'AddRegions', 'args': args})
def GetRegions(self, *args):
"""
Get information about one or more regions
call:
rarr = JS9.GetRegions(regions)
where:
- regions: which regions to retrieve
returns:
- rarr: array of region objects
If the regions argument is not specified, it defaults to
"selected" if there are selected regions, otherwise "all".
Each returned region object contains the following properties:
- id: numeric region id (assigned by JS9 automatically)
- mode: 'add', 'remove' or 'change'
- shape: region shape ('annulus', 'box', 'circle', 'ellipse',
'point', 'polygon', 'text')
- tags: comma delimited list of region tags (e.g., 'source',
'include')
- color: region color
- x,y: image coordinates of region
- radii: array of radii for annulus region
- width: width for box region
- height: height for box region
- radius: radius value for circle region
- r1: x radius for ellipse region (misnomer noted)
- r2: y radius for ellipse region (misnomer noted)
- pts: array of objects containing x and y positions, for polygons
- points: array of objects containing x and y offsets from the
specified center, for polygons
- angle: angle in degrees for box and ellipse regions
- wcsstr: region string in wcs coordinates
- wcssys: wcs system (e.g. 'FK5')
- imstr: region string in image or physical coordinates
- imsys: image system ('image' or 'physical')
"""
return self.send({'cmd': 'GetRegions', 'args': args})
def ListRegions(self, *args):
"""
List one or more regions
call:
JS9.ListRegions(regions, opts)
where:
- regions: which regions to list
- opts: object containing options
List (and return) the specified regions. By default, a light window
is displayed listing all regions (i.e., as if the list option of the
Regions menu had been selected.) You can also list "selected" regions
or use any of the standard regions specifications.
The opts object supports the following properties:
- mode: display/return mode (1,2,3)
- wcssys: wcs system to use (ICRS, FK5, galactic, physical, etc.)
- wcsunits: units for wcs output (sexagesimal, degrees, pixels)
- includejson: include JSON object
- includecomments: include comments
- layer: which layer to display (def: regions layer)
The mode property accepts the following values:
- 1: no display, return full region string including json, comments
- 2: display and return shortened region string (no json, comments)
- 3: display and return full region string (including json, comments)
"""
return self.send({'cmd': 'ListRegions', 'args': args})
def ListGroups(self, *args):
"""
List one or more region/shape groups
call:
JS9.ListGroups(group, opts)
where:
- group: which group(s) to list
- opts: object containing options
List the specified region/shape group(s) in the specified layer
(default is "regions"). The first argument is the groupid of the
group to list, or "all" to list all groups.
The optional opts object can contain the following properties:
- includeregions: display regions as well as the group name (def: true)
- layer: layer to list (def: "regions")
By default, the display will includes the name of the group and the
regions in the group. To skip the display of regions, supply
an opts object with the includeregions property set to False.
For example:
>>> j.ListGroups("all", {"includeregions": false})
grp1
grp2
grp3
>>> j.ListGroups("grp1")
grp1:
circle(3980.00,4120.00,20.00) # source,include,foo1
ellipse(4090.00,4120.00,25.00,15.00,0.0000) # source,include,foo1
"""
return self.send({'cmd': 'ListGroups', 'args': args})
def EditRegions(self, *args):
"""
Edit one or more regions
call:
JS9.EditRegions()
Edit one or more selected regions using an Edit dialog box. If a
single region has been selected by clicking that region, all of its
properties can be edited via the displayed dialog box. If a group of
regions has been selected using Meta-mousemove to highlight one or
more regions, then properties such as color, stroke width, dash
pattern, and tags can be edited for all of the selected regions using
the displayed dialog box. In the latter case, use shift-click to add
additional regions to the edit group.
"""
return self.send({'cmd': 'EditRegions', 'args': args})
def ChangeRegions(self, *args):
"""
Change one or more regions
call:
JS9.ChangeRegions(regions, opts)
where:
- regions: which regions to change
- opts: object containing options to change in each region
Change one or more regions. The opts object can contain the parameters
described in the JS9.AddRegions() section. However, you cannot (yet)
change the shape itself (e.g. from 'box' to 'circle'). See
js9onchange.html for examples of how to use this routine.
If the regions argument is not specified, it defaults to
"selected" if there are selected regions, otherwise "all".
You can specify a region selector using any of the following:
- all: all regions not including child text regions
- All: all regions including child text regions
- selected: the selected region (or regions in a selected group)
- [color]: regions of the specified color
- [shape]: regions of the specified shape
- [wcs]: regions whose initial wcs matches the specified wcs
- [tag]: regions having the specified tag
- /[regexp]/: regions with a tag matching the specified regexp
- child: a child region (i.e. text child of another region)
- parent: a region that has a child (i.e. has a text child)
"""
return self.send({'cmd': 'ChangeRegions', 'args': args})
def CopyRegions(self, *args):
"""
Copy one or more regions to another image
call:
JS9.CopyRegions(to, regions)
where:
- to: image id to which to copy regions
- regions: which regions to copy
Copy regions to a different image. If to is "all", then the
regions are copied to all images.
If the regions argument is not specified, it defaults to
"selected" if there are selected regions, otherwise "all".
You can specify a region selector using any of the following:
- all: all regions not including child text regions
- All: all regions including child text regions
- selected: the selected region (or regions in a selected group)
- [color]: regions of the specified color
- [shape]: regions of the specified shape
- [wcs]: regions whose initial wcs matches the specified wcs
- [tag]: regions having the specified tag
- /[regexp]/: regions with a tag matching the specified regexp
- child: a child region (i.e. text child of another region)
- parent: a region that has a child (i.e. has a text child)
"""
return self.send({'cmd': 'CopyRegions', 'args': args})
def RemoveRegions(self, *args):
"""
Remove one or more regions from the region layer
call:
JS9.RemoveRegions(regions)
where:
- regions: which regions to remove
If the regions argument is not specified, it defaults to
"selected" if there are selected regions, otherwise "all".
You can specify a region selector using any of the following:
- all: all regions not including child text regions
- All: all regions including child text regions
- selected: the selected region (or regions in a selected group)
- [color]: regions of the specified color
- [shape]: regions of the specified shape
- [wcs]: regions whose initial wcs matches the specified wcs
- [tag]: regions having the specified tag
- /[regexp]/: regions with a tag matching the specified regexp
- child: a child region (i.e. text child of another region)
- parent: a region that has a child (i.e. has a text child)
"""
return self.send({'cmd': 'RemoveRegions', 'args': args})
def UnremoveRegions(self, *args):
"""
Unremove one or more previously removed regions
call:
JS9.RemoveRegions()
If you accidentally remove one or more regions, you can use restore
them using this call. JS9 maintains a stack of removed regions (of
size JS9.globalOpts.unremoveReg, current default is 100). Each
time one or more regions is removed, they are stored as a single entry
on this stack. The UnremoveRegions call pops the last entry off
the stack and calls AddRegions.
"""
return self.send({'cmd': 'UnremoveRegions', 'args': args})
def SaveRegions(self, *args):
"""
Save regions from the current image to a file
call:
JS9.SaveRegions(filename, which, layer)
where:
- filename: output file name
- which: which regions to save (def: "all")
- layer: which layer save (def: "regions")
Save the current regions for the displayed image as JS9 regions file.
If filename is not specified, the file will be saved as "js9.reg".
Don't forget that the file is saved by the browser, in whatever
location you have set up for downloads.
If the which argument is not specified, it defaults to "all". You
can specify "selected" to return information about the selected
regions, or a tag value to save regions having that tag.
If the layer argument is not specified, it defaults to "regions",
i.e. the usual regions layer. You can specify a different layer,
e.g., if you want to save a catalog layer as a region file
(since SaveCatalog() will save the data in table format instead
of as regions).
"""
return self.send({'cmd': 'SaveRegions', 'args': args})
def SelectRegions(self, *args):
"""
Group Regions into a Selection
call:
JS9.SelectRegions(regions)
where:
- regions: which regions to select
JS9 has a rich mouse-based interface for selecting regions: a single
region is selected by clicking on it. A number of regions can be
gathered into a group selection by pressing the left mouse button and
dragging the mouse over the desired regions. To add to an
already-existing selection, shift-click the mouse on a region.
This routine allows you to create a selection programmatically by
specifying which regions make up the selection. The first argument is
the regions selection. If not specified, it defaults to "all".
The call makes a selection of regions which can be moved as one unit.
For example:
>>> j.SelectRegions("circle") # select all circles
>>> j.SelectRegions("circle && !foo2") # all circles without tag 'foo2'
Regions in a selection are processed individually, i.e. a regions
selection will match the regions inside a group. Thus for example,
if you create a selection containing circles, changing the color using
the "circle" specification will also affect the circles within the
selection. You can, of course, process only the regions inside a
selection using the selected specification.
"""
return self.send({'cmd': 'SelectRegions', 'args': args})
def UnselectRegions(self, *args):
"""
Remove Regions From a Selection
call:
JS9.UnselectRegions(regions)
where:
- regions: which regions to select
JS9 has a rich mouse-based interface for selecting regions: a single
region is selected by clicking on it. A number of regions can be
gathered into a group selection by pressing the left mouse button and
dragging the mouse over the desired regions. To add to an
already-existing selection, shift-click the mouse on a region.
This routine allows you to remove one or more regions from a region
selection programmatically by specifying which regions to remove.
The first argument is the regions selection. In not specified,
or specified as "all" or "selected", the selection is undone.
Otherwise the call will make a new selection, not containing
the unselected regions, which can be moved as one unit.
For example:
>>> j.UnselectRegions("circle&&!foo2") # unselect circles w/o tag 'foo2'
"""
return self.send({'cmd': 'UnselectRegions', 'args': args})
def GroupRegions(self, *args):
"""
Gather Regions into a Long-lived Group
call:
JS9.GroupRegions(shapes, opts)
where:
- regions: which regions to group
- opts: optional object containing grouping options
returns:
- groupid: the group id associated with the newly created group
A region group can be moved and resized as a single unit. To
first order, it is a long-lived form of a region selection.
The latter gets dissolved when you click the mouse outside the
selection, but a region group is dissolved only by calling
JS9.UngroupRegions().
This routine allows you to create a group by specifying the regions
which will compose it. The first argument is the regions selection.
If not specified, it defaults to either 'selected' or 'all', depending
on whether a region selection currently exits.
The optional opts argument contains the following properties:
- groupid: the group id to use, if possible (default: 'group_[n]')
- select: if false, the group is not selected upon creation
By default, the groupid will be the string 'group_' followed by
an integer chosen so that the groupid is unique. You can supply your
own groupid, but if it already is associated with an existing group,
an integer value will be appended to make it unique. Also, by default
the newly created group will be 'selected'. You can pass
the select property with a value of false in order to
avoid selecting the group (e.g., if you are creating a number of
groups and do not want to see each of them selected in turn.)
The returned groupid string can be used to select and process all the
regions in that group. Thus, for example, you can use the groupid to
change the color of all grouped regions:
>>> gid = j.GroupRegions('circle && foo1');
>>> j.ChangeRegions(gid, {'color':'red'});
Furthermore, when creating a regions file via JS9.SaveRegions(),
the groupid will be stored in each grouped region's JSON object, and
will be used to reconstitute the group when the file is reloaded.
Note however, that unlike the temporary region selections, regions
in a group are not available individually, i.e., a regions selection
using a non-groupid does not match regions inside a group. Thus, for
example, if you have created a group of circles, changing the color
using a 'circle' specification does not affect circles within the group:
>>> gid = j.GroupRegions('circle && foo1');
>>> j.ChangeRegions('circle', {'color':'cyan'}) # won't change group
>>> j.ChangeRegions(gid, {'color':'red'}); # change regions in group
Furthermore, a given region can only be part of one group at a
time. In the case where a region already is part of an existing group,
the globalOpts.regGroupConflict property determines how that region
is processed. The default is skip, meaning that the region is
silently skipped over when creating the new group. The alternative
is error, which will throw an error.
"""
return self.send({'cmd': 'GroupRegions', 'args': args})
def UngroupRegions(self, *args):
"""
Dissolve a Group of Regions
call:
JS9.UngroupRegions(groupid, opts)
where:
- groupid: group id of the group to dissolve
- opts: optional object containing ungrouping options
This routine allows you to dissolve an existing group, so that the
regions contained therein once again become separate. The first
argument is the groupid, previously returned by the JS9.GroupRegions()
call.
The optional opts argument contains the following properties:
- select: newly separate regions in the group are 'selected'?
By default, the ungrouped regions unobtrusively take their place among
other regions on the display. You can make them be selected by
passing the select: true property in opts. Doing this, for
example, would allow you to remove them easily with the Delete key.
For example:
>>> gid = j.GroupRegions('circle || ellipse')
>>> j.UngroupRegions(gid)
"""
return self.send({'cmd': 'UngroupRegions', 'args': args})
def ChangeRegionTags(self, *args):
"""
Change region tags for the specified image(s)
call:
JS9.ChangeRegionTags(which, addreg, removereg)
where:
- which: which regions to process (def: 'all')
- addreg: array or comma-delimited string of regions to add
- removereg: array or comma-delimited string of regions to remove
While region tags can be changed wholesale using JS9.ChangeRegions(),
this routine allows you to add and/or remove specific tags. The first
argument specifies which regions to change. The second argument is a
list of tags to add, while the third argument is a list of tags to
remove. In each case, the tags argument can be an array of tag strings
or a single string containing a comma-separated list of tags:
>>> JS9.ChangeRegionTags('selected', ['foo1', 'foo2'], ['goo1']);
>>> JS9.ChangeRegionTags('selected', 'foo1,foo2', 'goo1');
"""
return self.send({'cmd': 'ChangeRegionTags', 'args': args})
def ToggleRegionTags(self, *args):
"""
Toggle two region tags for the specified image(s)
call:
JS9.toggleRegionTags(which, tag1, tag2)
where:
- which: which regions to process (def: 'all')
- tag1: tag #1 to toggle
- tag2: tag #2 to toggle
While region tags can be changed wholesale using JS9.ChangeRegions(),
this routine allows you to toggle between two tags, e.g., a source
region and background region, or include and exclude. For example:
>>> JS9.ToggleRegionTags('selected', 'source', 'background');
will change a background region into a source region
or vice-versa, depending on the state of the region, while:
>>> JS9.ToggleRegionTags('selected', 'include', 'exclude');
will toggle between include and exclude.
"""
return self.send({'cmd': 'ToggleRegionTags', 'args': args})
def LoadRegions(self, *args):
"""
Load regions from a file into the current image
call:
JS9.LoadRegions(filename)
where:
- filename: input file name or URL
Load the specified regions file into the displayed image. The filename,
which must be specified, can be a local file (with absolute path or a
path relative to the displayed web page) or a URL.
"""
return self.send({'cmd': 'LoadRegions', 'args': args})
def LoadCatalog(self, *args):
"""
Load an astronomical catalog
call:
JS9.LoadCatalog(layer, table, opts)
where:
- name of shape layer into which to load the catalog
- table: string or blob containing the catalog table
- opts: catalog options
Astronomical catalogs are a special type of shape layer, in which
the shapes have been generated from a tab-delimited text file of
columns, including two columns that contain RA and Dec values. An
astronomical catalog can have a pre-amble of comments, which, by
default, have a '#' character in the first column.
The JS9.LoadCatalog() routine will read a file in this format,
processing the data rows by converting the RA and Dec values into
image position values that will be displayed as shapes in a new
catalog layer.
The first argument to the JS9.LoadCatalog() routine is the name
of the shape layer that will contain the objects in the catalog.
Specifying the name of an existing layer is valid: previous shapes
in that layer will be removed.
The second argument should be a string containing the table
data described above (the result of reading a file, performing
a URL get, etc.)
The third argument is an optional object used to specify
parameters, including:
- xcol: name of the RA column in the table
- ycol: name of the Dec column in the table
- wcssys: wcs system (FK4, FK5, ICRS, galactic, ecliptic)
- shape: shape of catalog object
- color: color of catalog shapes
- width: width of box catalog shapes
- height: height of box catalog shapes
- radius: radius of circle catalog shapes
- r1: r1 of ellipse catalog shapes
- r2: r2 of ellipse catalog shapes
- tooltip: format of tooltip string to display for each object
- skip: comment character in table file
Most of these properties have default values that are stored
in the JS9.globalOpts.catalogs object. The values listed above
also can be changed by users via the Catalog tab in the
Preferences plugin.
"""
return self.send({'cmd': 'LoadCatalog', 'args': args})
def SaveCatalog(self, *args):
"""
Save an astronomical catalog to a file
call:
JS9.SaveCatalog(filename, which)
where:
- filename: output file name
- which: layer containing catalog objects to save
Save the specified catalog layer as a text file. If filename is not
specified, the file will be saved as [layer].cat.
Don't forget that the file is saved by the browser, in whatever
location you have set up for downloads.
If the which argument is not specified, the catalog associated
with the current active layer will be saved. In either case, the
layer to save must be a catalog created from a tab-delimited
file (or URL) of catalog objects (e.g., not the regions layer).
"""
return self.send({'cmd': 'SaveCatalog', 'args': args})
def GetAnalysis(self, *args):
"""
Get server-side analysis task definitions
call:
JS9.GetAnalysis()
The JS9.GetAnalysis() routine returns an array of analysis task
definitions, each containing the following information:
- name: a short identifier string (typically one word)
- title: a longer string that will be displayed in the Analysis menu
- files: a rule that will be matched against to determine whether this
- task is available for the current image
- purl: a URL pointing to a web page containing a user parameter form
- action: the command to execute on the server side
- rtype: return type: text, plot, fits, png, regions, catalog, alert,
none
- hidden: if true, the analysis task is not shown in the Analysis menu
Not every property will be present in every task definition
(e.g., purl is only present when there is a parameter form).
Also note that hidden tasks are not returned by this call.
"""
return self.send({'cmd': 'GetAnalysis', 'args': args})
def RunAnalysis(self, *args):
"""
Run a simple server-side analysis task
call:
JS9.RunAnalysis(name, parr)
where:
- name: name of analysis tool
- parr: optional array of macro-expansion options for command line
The JS9.RunAnalysis() routine is used to execute a server-side analysis
task and return the results for further processing within Python.
NB: Prior to JS9 v1.10, this routine displayed the results on the JS9
web page instead of returning them to Python. If you want to display
the results in JS9, use the "analysis" short-cut routine instead.
The optional parr array of parameters is passed to the JS9 analysis
macro expander so that values can be added to the command line. The
array is in jQuery name/value serialized object format, which is
described here:
http://api.jquery.com/serializeArray/
"""
return self.send({'cmd': 'RunAnalysis', 'args': args})
def SavePNG(self, *args):
"""
Save image as a PNG file
call:
JS9.SavePNG(filename, opts)
where:
- filename: output file name
- opts: optional save parameters
Save the currently displayed image as a PNG file. If filename is not
specified, the file will be saved as "js9.png".
The opts object can specify the following properties:
- layers: save graphical layers (e.g. regions) (def: true)
- source: "image" or "display" (def: "display")
By default, SavePNG() will save all of the 2D graphics in the
shape layers (regions, catalogs, etc.) as well as the image. Set
the layers property to false to save only the image.
Also by default, SavePNG() will save the RGB pixels from the
display. This means, for example, that a blended set of images will
save the blended pixels. If you want to save the RGB pixels from one
of the images in a blended image, you can specify the source
property to the image. For example, in the js9blend.html demo,
you can save the RGB pixels of the Chandra image by specifying use of
the "image" source and specifying the image's id in the display
parameter:
>>> SavePNG("foo.png", {"source":"image"}, {"display":"chandra.fits"});
Don't forget that the file is saved by the browser, in whatever
location you have set up for downloads.
"""
return self.send({'cmd': 'SavePNG', 'args': args})
def SaveJPEG(self, *args):
"""
Save image as a JPEG file
call:
JS9.SaveJPEG(filename, opts)
where:
- filename: output file name
- opts: optional save parameters or a number between 0 and 1
indicating image quality
Save the currently displayed image as a JPEG file. If filename is not
specified, the file will be saved as "js9.png".
The opts object can specify the following properties:
- layers: save graphical layers (e.g. regions) (def: true)
- source: "image" or "display" (def: "display")
- quality: JPEG encoder quality
By default, SaveJPEG() will save all of the 2D graphics in the
shape layers (regions, catalogs, etc.) as well as the image. Set
the layers property to false to save only the image.
Also by default, SaveJPEG() will save the RGB pixels from the
display. This means, for example, that a blended set of images will
save the blended pixels. If you want to save the RGB pixels from one
of the images in a blended image, you can specify the source
property to the image. For example, in the js9blend.html demo,
you can save the RGB pixels of the Chandra image by specifying use of
the "image" source and specifying the image's id in the display
parameter:
>>> SaveJPEG("foo.png", {"source":"image"}, {"display":"chandra.fits"});
If encoder quality parameter is not specified, a suitable default is
used. On FireFox (at least), this default values is 0.95 (I think).
Don't forget that the file is saved by the browser, in whatever
location you have set up for downloads.
"""
return self.send({'cmd': 'SaveJPEG', 'args': args})
def GetToolbar(self, *args):
"""
Get toolbar values from the Toolbar plugin
val = GetToolbar(type)
where:
- type: type of information to retrieve
returns:
- val: array of tool objects (or an argument-dependent return)
The GetToolbar() routine returns global information about the
Toolbar plugin. If the first argument is "showTooltips", the returned
value specifies whether tooltips are currently displayed. Otherwise
an array of tool objects is returned, one for each of the defined
tools in the toolbar.
"""
return self.send({'cmd': 'GetToolbar', 'args': args})
def SetToolbar(self, *args):
"""
Set toolbar values for the Toolbar plugin
SetToolbar(arg1, arg2)
where:
- arg1: a type-dependent id or value to set
- arg2: a type-dependent value to set
The SetToolbar() routine sets global information about the Toolbar
plugin. The following values can be specified as the first argument:
- init: the text "init" triggers a re-initialization of all
display Toolbar plugins, which is useful if you have changed
the JS9.globalOpts.toolBar array to specify a new set of
top-level tools.
- showTooltips: the text "showTooltips" uses the value of the
boolean arg2 to specify whether tooltips are displayed as the mouse
hovers over a tool.
- [text]: other text is assumed to be a JSON-formatted text
containing either a new tool to add to the toolbar, or an array of
tools.
- [object]: an object is assumed to be new tool to add to the toolbar
- [array]: an array is assumed to be an array of new tools to add to
the toolbar
New tools can be added to the toolbar at any time using this routine.
The text properties associated with a tool object are:
- name: name of the tool
- tip: a tooltip to display when the mouse hovers over the tool
- image: url (relative to the install directory) containing a PNG
image file to display as the tool icon
- cmd: name of the JS9 public routine to execute when the tool is
clicked
- args: array of arguments to pass to the JS9 public routine
Only the name and cmd properties are required. If no image is
specified, a button labeled by the name value will be used.
Examples of tool objects:
>>> {
>>> "name": "linear",
>>> "tip": "linear scale",
>>> "image": "images/toolbar/dax_images/lin.png",
>>> "cmd": "SetScale",
>>> "args": ["linear"]
>>> },
>>> {
>>> "name": "histeq",
>>> "tip": "histogram equalization",
>>> "cmd": "SetScale",
>>> "args": ["histeq"]
>>> },
>>> {
>>> "name": "annulus",
>>> "tip": "annulus region",
>>> "image": "images/toolbar/dax_images/annulus.png",
>>> "cmd": "AddRegions",
>>> "args": ["annulus"]
>>> },
>>> {
>>> "name": "remove",
>>> "tip": "remove selected region",
>>> "image": "images/toolbar/dax_images/erase.png",
>>> "cmd": "RemoveRegions",
>>> "args": ["selected"]
>>> },
>>> {
>>> "name": "zoom1",
>>> "tip": "zoom 1",
>>> "image": "images/toolbar/dax_images/mag_one.png",
>>> "cmd": "SetZoom",
>>> "args": [1]
>>> },
>>> {
>>> "name": "magnifier",
>>> "tip": "toggle magnifier display",
>>> "image": "images/toolbar/dax_images/mag.png",
>>> "cmd": "DisplayPlugin",
>>> "args": ["JS9Magnifier"]
>>> }
Each time a tool is added to the list of available tools, the active
Toolbar plugins will be re-initialized to display that tool. By
default, the new tool not be added to the top-level list: you must
also edit the JS9.globalOpts.toolBar array to add the name of the
tool. If this is done after you add the tool, remember to re-initialize
active toolbars by calling:
>>> SetToolbar("init");
"""
return self.send({'cmd': 'SetToolbar', 'args': args})
def UploadFITSFile(self, *args):
"""
Upload the currently displayed FITS file to a proxy server
call:
JS9.UploadFITSFile()
Upload the currently displayed FITS file to the proxy server, so
back-end analysis can be performed. This routine requires that a
Node.js-based JS9 helper is running and that the helper has enabled
the loadProxy property and set up a workDir directory in which to
store the FITS file.
"""
return self.send({'cmd': 'UploadFITSFile', 'args': args})
def GetFITSHeader(self, *args):
"""
Get FITS header as a string
call:
JS9.GetFITSHeader(nlflag)
where:
- nlflag: true if newlines should added to each card
Return the FITS header as a string. By default, the returned string
contains the 80-character FITS cards all concatenated together. If
nlflag is true, each card will have a new-line appended.
Note that the JS9.GetImageData() routine also returns the FITS
header, but as an object whose properties contain the header
values. For example, obj.SIMPLE will usually have a value of
true, obj.BITPIX will have contain the bits/pixel, etc. This
object is more useful for programming tasks, but does not
contain the FITS comments associated with each header card.
"""
return self.send({'cmd': 'GetFITSHeader', 'args': args})
def Print(self, *args):
"""
Print the current image
"""
return self.send({'cmd': 'Print', 'args': args})
def DisplayNextImage(self, *args):
"""
Display the Next (or Previous) Image
call:
JS9.DisplayNextImage(n)
where:
- n: number of images beyond (or prior to) the one currently displayed
The JS9.DisplayNextImage() routine displays the nth image in
the display's image list beyond the currently displayed image. The
default value for n is 1. You can supply a negative number to
display an image prior to the current one in the display's image list.
"""
return self.send({'cmd': 'DisplayNextImage', 'args': args})
def CreateMosaic(self, *args):
"""
Create a Mosaic Image
call:
JS9.CreateMosaic(which, opts)
where:
- which: which images to use in the mosaic
- opts: mosaic options
The JS9.CreateMosaic() creates a mosaic image from the specified
(previously-loaded) FITS images using the mProjectPP and mAdd programs
form the Montage software suite. These Montage programs have been
compiled into JS9 using Emscripten.
Because the browser environment is memory-limited, there are some
restrictions on generating mosaics in JS9. The FITS files must be
well-behaved, i.e. they must have WCS projections which can be
approximated by tangent-plane projections (TAN, SIN, ZEA, STG, ARC).
This precludes creating mosaics from images covering large portions of
the sky. For large sky areas, please use Montage itself on your desktop
to create a mosaic. A simplified js9mosaic script is included in
the JS9 distribution or, for more control, use the Montage programs
directly. Of course, in either case, you must install Montage.
The which parameter determine which images are used in the mosaic:
- "current" or null: the current image in this display
- "all": all images in this display
- im: the image id an image from any display
- [im1, im2, ...]: an array of image ids from any display
Use "current" (or null) if you have loaded a multi-extension
FITS mosaic into JS9. Use "all" if you have loaded several
FITS files into JS9 and want to create a mosaic.
In order to keep the size of the resulting mosaic within memory
limits, JS9 reduces the size of each image before adding them all
together The options parameter determines how the reduction is
performed:
- dim: size of mosaic (def: max of JS9.globalOpts.image.[xdim,ydim])
- reduce: image size reduction technique: "js9" (def) or "shrink"
- verbose: if true, processing output is sent to the javascript console
The "dim" parameter is a target size: the larger of the resulting
mosaic dimensions will be approximately this value, depending on how
Montage processes the images. The "reduce" technique either runs
internal JS9 image sectioning code (to produce smaller internal
images, each of which are reprojected and added together) or runs the
Montage mShrinkHdr code (which reprojects the full images into smaller
files). The former seems to be faster than the latter in most
cases. The "verbose" parameter will display output on the JavaScript
console to let you know that the CreateMosaic() call is running
properly.
The resulting mosaic will be loaded into the specified JS9 display as
a separate image. Because the mosaic is separate from the original
image(s), you can view each of the latter individually (or view each
image extension of a single image using the Extensions plugin).
Internal analysis can be performed on the mosaic but,
of course, no external analysis tasks will be available.
"""
return self.send({'cmd': 'CreateMosaic', 'args': args})
def ResizeDisplay(self, *args):
"""
Change the width and height of the JS9 display
call:
JS9.ResizeDisplay(width, height)
where:
- width: new width of the display in HTML pixels
- height: new height of the display in HTML pixels
- opts: optional object containing resize parameters
You can resize the JS9 display element by supplying new width and
height parameters. The div on the web page will be resized and the
image will be re-centered in the new display. If the display size has
been increased, more of the image will be displayed as needed (up to
the new size of the display). For example, if the original display was
512x512 and you increase it to 1024x1024, a 1024x1024 image will now
be displayed in its entirety.
The opts object can contain the following properties:
- resizeMenubar: change the width of the menubar as well
The default for resizeMenubar is True, so you only need
to pass this property if you do not want to perform the resize.
"""
return self.send({'cmd': 'ResizeDisplay', 'args': args})
def GatherDisplay(self, *args):
"""
Gather other images to this JS9 Display
call:
JS9.GatherDisplay(dname, opts)
where:
- dname: name of JS9 display to which the images will be gathered
- opts: optional object
You can supply an opts object containing the following properties:
- images: array of image handles (or indexes into JS9.images array)
to gather
This routine move all or selected images in other displays to this
display.
"""
return self.send({'cmd': 'GatherDisplay', 'args': args})
def SeparateDisplay(self, *args):
"""
Separate images in this JS9 Display into new displays
call:
JS9.SeparateDisplay(dname, opts)
where:
- dname: name of JS9 display from which the images will be separated
- opts: optional object for layout properties
This routine moves each image in this display to a new display.
You can supply an opts object containing the following properties:
- images: array of image handles (or indexes into JS9.images array)
to separate
- layout: can be "horizontal", "vertical", "auto" (default: "auto")
- leftMargin: margin in pixels between horizontally separated images
- topMargin: margin in pixels between vertically separated images
The "horizontal" layout will generate a single row of images. The
"vertical" layout will generate a single column of images. The "auto"
option will layout the images in one or more rows. Each row will
contain one or more images such that at least one-half of the
right-most image is visible in the browser without the need for
horizontal scrolling.
"""
return self.send({'cmd': 'SeparateDisplay', 'args': args})
def CenterDisplay(self, *args):
"""
Scroll the JS9 display to the center of the viewport
call:
JS9.CenterDisplay()
where:
- dname: name of JS9 display to center
This routine scrolls this display to the center of the viewport.
"""
return self.send({'cmd': 'CenterDisplay', 'args': args})
def CloseDisplay(self, *args):
"""
Close all images in a display
call:
JS9.CloseDisplay(dname)
where:
- dname: name of JS9 display whose images will be closed
This routine closes all images in the specified display.
"""
return self.send({'cmd': 'CloseDisplay', 'args': args})
def RenameDisplay(self, *args):
"""
Rename the id of a JS9 display
calling sequences:
JS9.RenameDisplay(nid) # change default id (usually "JS9") to nid
JS9.RenameDisplay(oid, nid) # change oid to nid
where:
- oid: old name of JS9 display
- nid: new name of JS9 display
This routine is used by the Desktop version of JS9 to implement the
--title (and --renameid) switch(es), which change the id of the
JS9 display(s) to the specified id(s). Once an id has been renamed,
external communication (via the js9 script or pyjs9) should target
the new id instead of the original id.
The original id is still available internally, so Javascript public
API calls on the web page itself can target either the original or
the new id using the {display: "id"} syntax.
"""
return self.send({'cmd': 'RenameDisplay', 'args': args})
def RemoveDisplay(self, *args):
"""
Close all images in a display and remove the display
call:
JS9.RemoveDisplay(dname)
where:
- dname: name of JS9 display to remove
This routine will close all images in the specified display and then
remove the display. It is available for displays contained in
light windows and for displays contained in JS9 Grid Containers. When
removing the display inside a light window, the light window is
immediately closed without a confirmation dialog box (unlike a light
window being closed via its close button.) For a display inside
a JS9 Grid Container, the display is removed from the DOM, so that it
no longer is part of the grid layout. Note, however, that you cannot
remove all displays from a grid container: at least one display must be
left in the container.
"""
return self.send({'cmd': 'RemoveDisplay', 'args': args})
def DisplayHelp(self, *args):
"""
Display help in a light window
call:
JS9.DisplayHelp(name)
where:
- name: name of a help file or url of a web site to display
The help file names are the property names in JS9.helpOpts (e.g.,
'user' for the user page, 'install' for the install page, etc.).
Alternatively, you can specify an arbitrary URL to display (just
because).
"""
return self.send({'cmd': 'DisplayHelp', 'args': args})
def LightWindow(self, *args):
"""
Display content in a light window
call:
JS9.LightWindow(id, type, content, title, opts)
where:
- id: unique id for light window div(default: "lightWindow" + uniqueID)
- type: content type: "inline", "div", "ajax", "iframe" (def: "inline")
- content: content of the light window (default: none)
- title: title (default: "JS9 light window")
- opts: configuration string
(default: "width=830px,height=400px,center=1,resize=1,scrolling=1")
Display arbitrary content inside a light window. There are any number
of light window routines available on the Net. JS9 uses light window
routines developed by Dynamic Drive (http://www.dynamicdrive.com).
Extensive documentation can be found on the Dynamic Drive web
site: http://www.dynamicdrive.com/dynamicindex8/dhtmlwindow.
The content shown inside the window depends on the content parameter:
- iframe: the URL of the page to display (ie: "http://www.google.com")
- inline: the HTML to display (back-slashing any special JavaScript
characters, such as apostrophes)
- ajax: the relative path to the external page to display, relative to
the current page (ie: "../external.htm")
- div: define a DIV element on the page with a unique ID attribute
(probably hidden using style="display:none") and the use the DIV's id
as the content value
JS9 typically uses the inline option. Note that web sites often
do not allow themselves to be embedded in an iframe, so this is an
unreliable option.
The opts parameter specifies options for the light window, such
as its size. This parameter consists of a string with comma-separated
keywords, e.g.:
>>> "width=830px,height=400px,center=1,resize=1,scrolling=1"
The opts keywords, defined in the Dynamic Drive documentation, are:
width, height, left, top, center, resize, and scrolling. The
JS9.lightOpts.dhtml object defines oft-used lightwin configurations,
and the JS9.lightOpts.dhtml.textWin property is used as the
default for this call. You can utilize these properties in your own
call to LightWindow() or make up your own configuration string.
As an extension to the Dynamic Drive light window support, JS9 adds
the ability to double-click the title bar in order to close the window.
"""
return self.send({'cmd': 'LightWindow', 'args': args})
def analysis(self, *args):
"""
run/list analysis for current image
This is a commmand-style routine, easier to type than the full routine
at the expense of some flexibility:
- with no arguments, the getter is called to retrieve current values.
- with arguments, the setter is called to set current values.
Returned results are of type string.
"""
return self.send({'cmd': 'analysis', 'args': args})
def colormap(self, *args):
"""
set/get colormap for current image
This is a commmand-style routine, easier to type than the full routine
at the expense of some flexibility:
- with no arguments, the getter is called to retrieve current values.
- with arguments, the setter is called to set current values.
Returned results are of type string: 'colormap contrast bias'
"""
return self.send({'cmd': 'colormap', 'args': args})
def cmap(self, *args):
"""
set/get colormap for current image (alias)
This is a commmand-style routine, easier to type than the full routine
at the expense of some flexibility:
- with no arguments, the getter is called to retrieve current values.
- with arguments, the setter is called to set current values.
Returned results are of type string: 'colormap contrast bias'
"""
return self.send({'cmd': 'cmap', 'args': args})
def colormaps(self, *args):
"""
get list of available colormaps
No setter routine is provided.
Returned results are of type string: 'grey, red, ...'
"""
return self.send({'cmd': 'colormaps', 'args': args})
def helper(self, *args):
"""
get helper info
"""
return self.send({'cmd': 'helper', 'args': args})
def image(self, *args):
"""
get name of currently loaded image or display specified image
This is a commmand-style routine, easier to type than the full routine
at the expense of some flexibility:
- with no arguments, the getter is called to retrieve current values.
- with arguments, the setter is called to set current values.
Returned results are of type string.
"""
return self.send({'cmd': 'image', 'args': args})
def images(self, *args):
"""
get list of currently loaded images
No setter routine is provided.
Returned results are of type string.
"""
return self.send({'cmd': 'images', 'args': args})
def load(self, *args):
"""
load image(s)
No getter routine is provided.
"""
return self.send({'cmd': 'load', 'args': args})
def pan(self, *args):
"""
set/get pan location for current image
This is a commmand-style routine, easier to type than the full routine
at the expense of some flexibility:
- with no arguments, the getter is called to retrieve current values.
- with arguments, the setter is called to set current values.
Returned results are of type string: 'x y'
"""
return self.send({'cmd': 'pan', 'args': args})
def regcnts(self, *args):
"""
get background-subtracted counts in regions
This is a commmand-style routine, easier to type than the full routine:
- with no arguments, acts as if the Analysis menu option was chosen
- with arguments, acts like the full routine
With arguments, returned results are of type string.
"""
return self.send({'cmd': 'regcnts', 'args': args})
def region(self, *args):
"""
add region to current image or list all regions (alias)
This is a commmand-style routine, easier to type than the full routine
at the expense of some flexibility:
- with no arguments, the getter is called to retrieve current values.
- with arguments, the setter is called to set current values.
Returned results are of type string.
"""
return self.send({'cmd': 'region', 'args': args})
def regions(self, *args):
"""
add region to current image or list all regions
This is a commmand-style routine, easier to type than the full routine
at the expense of some flexibility:
- with no arguments, the getter is called to retrieve current values.
- with arguments, the setter is called to set current values.
Returned results are of type string.
"""
return self.send({'cmd': 'regions', 'args': args})
def resize(self, *args):
"""
set/get size of the JS9 display
This is a commmand-style routine, easier to type than the full routine
at the expense of some flexibility:
- with no arguments, the getter is called to retrieve current values.
- with arguments, the setter is called to set current values.
Returned results are of type string: 'width height'
"""
return self.send({'cmd': 'resize', 'args': args})
def scale(self, *args):
"""
set/get scaling for current image
This is a commmand-style routine, easier to type than the full routine
at the expense of some flexibility:
- with no arguments, the getter is called to retrieve current values.
- with arguments, the setter is called to set current values.
Returned results are of type string: 'scale scalemin scalemax'
"""
return self.send({'cmd': 'scale', 'args': args})
def scales(self, *args):
"""
get list of available scales
No setter routine is provided.
Returned results are of type string: 'linear, log, ...'
"""
return self.send({'cmd': 'scales', 'args': args})
def wcssys(self, *args):
"""
set/get wcs system for current image
This is a commmand-style routine, easier to type than the full routine
at the expense of some flexibility:
- with no arguments, the getter is called to retrieve current values.
- with arguments, the setter is called to set current values.
Returned results are of type string.
"""
return self.send({'cmd': 'wcssys', 'args': args})
def wcsu(self, *args):
"""
set/get wcs units used for current image
This is a commmand-style routine, easier to type than the full routine
at the expense of some flexibility:
- with no arguments, the getter is called to retrieve current values.
- with arguments, the setter is called to set current values.
Returned results are of type string.
"""
return self.send({'cmd': 'wcsu', 'args': args})
def wcssystems(self, *args):
"""
get list of available wcs systems
No setter routine is provided.
Returned results are of type string: 'FK4, FK5, ...'
"""
return self.send({'cmd': 'wcssystems', 'args': args})
def wcsunits(self, *args):
"""
get list of available wcs units
No setter routine is provided.
Returned results are of type string: 'degrees, ...'
"""
return self.send({'cmd': 'wcsunits', 'args': args})
def zoom(self, *args):
"""
set/get zoom for current image
This is a commmand-style routine, easier to type than the full routine
at the expense of some flexibility:
- with no arguments, the getter is called to retrieve current values.
- with arguments, the setter is called to set current values.
Returned results are type integer or float.
"""
return self.send({'cmd': 'zoom', 'args': args})
|
[
"pyfits.HDUList",
"io.BytesIO",
"logging.error",
"logging.debug",
"json.loads",
"socketio.Client",
"logging.warning",
"numpy.frombuffer",
"threading.Condition",
"time.sleep",
"logging.info",
"pyfits.PrimaryHDU",
"numpy.array",
"requests.post",
"numpy.ascontiguousarray",
"numpy.issubdtype"
] |
[((1775, 1813), 'logging.info', 'logging.info', (['"""set socketio transport"""'], {}), "('set socketio transport')\n", (1787, 1813), False, 'import logging\n'), ((1907, 1961), 'logging.info', 'logging.info', (['"""no python-socketio, use html transport"""'], {}), "('no python-socketio, use html transport')\n", (1919, 1961), False, 'import logging\n'), ((9471, 9521), 'logging.debug', 'logging.debug', (['"""socketio callback, args: %s"""', 'args'], {}), "('socketio callback, args: %s', args)\n", (9484, 9521), False, 'import logging\n'), ((3841, 3870), 'numpy.issubdtype', 'numpy.issubdtype', (['dtype', 't[0]'], {}), '(dtype, t[0])\n', (3857, 3870), False, 'import numpy\n'), ((11121, 11132), 'threading.Condition', 'Condition', ([], {}), '()\n', (11130, 11132), False, 'from threading import Condition\n'), ((13117, 13137), 'pyfits.PrimaryHDU', 'fits.PrimaryHDU', (['arr'], {}), '(arr)\n', (13132, 13137), True, 'import pyfits as fits\n'), ((13160, 13179), 'pyfits.HDUList', 'fits.HDUList', (['[hdu]'], {}), '([hdu])\n', (13172, 13179), True, 'import pyfits as fits\n'), ((14324, 14333), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (14331, 14333), False, 'from io import BytesIO\n'), ((10337, 10378), 'requests.post', 'requests.post', (["(host + '/' + msg)"], {'json': 'obj'}), "(host + '/' + msg, json=obj)\n", (10350, 10378), False, 'import requests\n'), ((10819, 10861), 'json.loads', 'json.loads', (['urtn'], {'object_hook': '_decode_dict'}), '(urtn, object_hook=_decode_dict)\n', (10829, 10861), False, 'import json\n'), ((17996, 18025), 'numpy.ascontiguousarray', 'numpy.ascontiguousarray', (['narr'], {}), '(narr)\n', (18019, 18025), False, 'import numpy\n'), ((8209, 8259), 'socketio.Client', 'socketio.Client', ([], {'logger': '(True)', 'engineio_logger': '(True)'}), '(logger=True, engineio_logger=True)\n', (8224, 8259), False, 'import socketio\n'), ((8366, 8383), 'socketio.Client', 'socketio.Client', ([], {}), '()\n', (8381, 8383), False, 'import socketio\n'), ((8509, 8570), 'logging.warning', 'logging.warning', (['"""socketio connect failed: %s, using html"""', 'e'], {}), "('socketio connect failed: %s, using html', e)\n", (8524, 8570), False, 'import logging\n'), ((8900, 8917), 'time.sleep', 'time.sleep', (['delay'], {}), '(delay)\n', (8910, 8917), False, 'import time\n'), ((12000, 12045), 'logging.error', 'logging.error', (['"""socketio close failed: %s"""', 'e'], {}), "('socketio close failed: %s', e)\n", (12013, 12045), False, 'import logging\n'), ((5448, 5475), 'numpy.array', 'numpy.array', (['s'], {'dtype': 'dtype'}), '(s, dtype=dtype)\n', (5459, 5475), False, 'import numpy\n'), ((5535, 5562), 'numpy.array', 'numpy.array', (['s'], {'dtype': 'dtype'}), '(s, dtype=dtype)\n', (5546, 5562), False, 'import numpy\n'), ((5738, 5770), 'numpy.frombuffer', 'numpy.frombuffer', (['s'], {'dtype': 'dtype'}), '(s, dtype=dtype)\n', (5754, 5770), False, 'import numpy\n'), ((5830, 5862), 'numpy.frombuffer', 'numpy.frombuffer', (['s'], {'dtype': 'dtype'}), '(s, dtype=dtype)\n', (5846, 5862), False, 'import numpy\n')]
|
import os
import h5py
import pandas as pd
import logging
import numpy as np
from progress.bar import Bar
from multiprocessing import Pool, cpu_count
from omegaconf import OmegaConf
from tools.utils import io
# from ANCSH_lib.utils import NetworkType
# from tools.visualization import Viewer, ANCSHVisualizer
import utils
from utils import JointType
log = logging.getLogger('proc_stage2')
class ProcStage2Impl:
def __init__(self, cfg):
self.output_path = cfg.output_path
self.input_h5_path = cfg.input_h5_path
self.stage1_tmp_dir = cfg.stage1_tmp_dir
self.tmp_output_dir = cfg.tmp_output_dir
self.rest_state_data_filename = cfg.rest_state_data_filename
self.object_infos_path = cfg.object_infos_path
self.heatmap_threshold = cfg.heatmap_threshold
self.epsilon = 10e-8
self.export = cfg.export
@staticmethod
def get_joint_params(vertices, joint, selected_vertices):
heatmap = -np.ones((vertices.shape[0]))
unitvec = np.zeros((vertices.shape[0], 3))
joint_pos = joint['abs_position']
joint_axis = joint['axis']
joint_axis = joint_axis / np.linalg.norm(joint_axis)
joint_axis = joint_axis.reshape((3, 1))
if joint['type'] == JointType.revolute.value:
vec1 = vertices - joint_pos
# project to joint axis
proj_len = np.dot(vec1, joint_axis)
# np.clip(proj_len, a_min=self.epsilon, a_max=None, out=proj_len)
proj_vec = proj_len * joint_axis.transpose()
orthogonal_vec = - vec1 + proj_vec
tmp_heatmap = np.linalg.norm(orthogonal_vec, axis=1).reshape(-1, 1)
tmp_unitvec = orthogonal_vec / tmp_heatmap
heatmap[selected_vertices] = tmp_heatmap[selected_vertices].reshape(-1)
unitvec[selected_vertices] = tmp_unitvec[selected_vertices]
elif joint['type'] == JointType.prismatic.value:
heatmap[selected_vertices] = 0
unitvec[selected_vertices] = joint_axis.transpose()
else:
log.error(f'Invalid joint type {joint["axis"]}')
heatmap = np.where(heatmap >= 0, heatmap, np.inf)
return heatmap, unitvec
def __call__(self, idx, input_data):
input_h5 = h5py.File(self.input_h5_path, 'r')
object_infos = io.read_json(self.object_infos_path)
output_filepath = os.path.splitext(self.output_path)[0] + f'_{idx}' + os.path.splitext(self.output_path)[-1]
h5file = h5py.File(output_filepath, 'w')
bar = Bar(f'Stage2 Processing chunk {idx}', max=len(input_data))
for index, row in input_data.iterrows():
instance_name = f'{row["objectCat"]}_{row["objectId"]}_{row["articulationId"]}_{row["frameId"]}'
in_h5frame = input_h5[instance_name]
mask = in_h5frame['mask'][:]
points_camera = in_h5frame['points_camera'][:]
points_rest_state = in_h5frame['points_rest_state'][:]
parts_camera2rest_state = in_h5frame['parts_transformation'][:]
camera2base = in_h5frame['base_transformation'][:]
stage1_tmp_data_dir = os.path.join(self.stage1_tmp_dir, row['objectCat'], row['objectId'])
rest_state_data_path = os.path.join(stage1_tmp_data_dir, self.rest_state_data_filename)
rest_state_data = io.read_json(rest_state_data_path)
part_info = object_infos[row['objectCat']][row['objectId']]['part']
num_parts = len(part_info)
# process points related ground truth
object_info = object_infos[row['objectCat']][row['objectId']]['object']
# diagonal axis aligned bounding box length to 1
# (0.5, 0.5, 0.5) centered
naocs_translation = - np.asarray(object_info['center']) + 0.5 * object_info['scale']
naocs_scale = 1.0 / object_info['scale']
naocs = points_rest_state + naocs_translation
naocs *= naocs_scale
naocs_transformation = np.reshape(camera2base, (4, 4), order='F')
naocs_transformation[:3, 3] += naocs_translation
naocs2cam_transformation = np.linalg.inv(naocs_transformation).flatten('F')
naocs2cam_scale = 1.0 / naocs_scale
points_class = np.empty_like(mask)
npcs = np.empty_like(points_rest_state)
parts_npcs2cam_transformation = np.empty_like(parts_camera2rest_state)
parts_npcs2cam_scale = np.empty(num_parts)
parts_min_bounds = np.empty((num_parts, 3))
parts_max_bounds = np.empty((num_parts, 3))
for link_index, link in enumerate(rest_state_data['links']):
if link['virtual']:
continue
link_index_key = str(link_index)
part_points = points_rest_state[mask == link_index]
center = np.asarray(part_info[link_index_key]['center'])
# diagonal axis aligned bounding box length to 1
# (0.5, 0.5, 0.5) centered
npcs_translation = - center + 0.5 * part_info[link_index_key]['scale']
npcs_scale = 1.0 / part_info[link_index_key]['scale']
part_points_norm = part_points + npcs_translation
part_points_norm *= npcs_scale
npcs[mask == link_index] = part_points_norm
part_class = part_info[link_index_key]['part_class']
points_class[mask == link_index] = part_class
npcs_transformation = np.reshape(parts_camera2rest_state[link['part_index']], (4, 4), order='F')
npcs_transformation[:3, 3] += npcs_translation
npcs2cam_transformation = np.linalg.inv(npcs_transformation)
parts_npcs2cam_transformation[part_class] = npcs2cam_transformation.flatten('F')
parts_npcs2cam_scale[part_class] = 1.0 / npcs_scale
parts_min_bounds[part_class] = np.asarray(part_info[link_index_key]['min_bound'])
parts_max_bounds[part_class] = np.asarray(part_info[link_index_key]['max_bound'])
# process joints related ground truth
link_names = [link['name'] for link in rest_state_data['links']]
# transform joints to naocs space
# viewer = Viewer()
naocs_joints = rest_state_data['joints']
for i, joint in enumerate(rest_state_data['joints']):
if not joint:
continue
joint_pose = np.asarray(joint['pose2link']).reshape((4, 4), order='F')
joint_parent = joint['parent']
parent_link = rest_state_data['links'][link_names.index(joint_parent)]
parent_link_abs_pose = np.asarray(parent_link['abs_pose']).reshape((4, 4), order='F')
joint_abs_pose = np.dot(parent_link_abs_pose, joint_pose)
joint_pos = joint_abs_pose[:3, 3]
naocs_joint_pos = joint_pos + naocs_translation
naocs_joint_pos *= naocs_scale
joint_axis = np.dot(joint_abs_pose[:3, :3], joint['axis'])
joint_axis = joint_axis / np.linalg.norm(joint_axis)
naocs_joints[i]['abs_position'] = naocs_joint_pos
naocs_joints[i]['axis'] = joint_axis
joint_child = joint['child']
child_link_class = part_info[str(link_names.index(joint_child))]['part_class']
joint_class = child_link_class
naocs_joints[i]['class'] = joint_class
joint_type = JointType[joint['type']].value
naocs_joints[i]['type'] = joint_type
# if self.export:
# viewer.add_trimesh_arrows([naocs_joint_pos], [joint_axis], color=Viewer.rgba_by_index(joint_class))
# if self.export:
# tmp_data_dir = os.path.join(self.tmp_output_dir, row['objectCat'], row['objectId'],
# row['articulationId'])
# io.ensure_dir_exists(tmp_data_dir)
# viewer.export(os.path.join(tmp_data_dir, instance_name + '_naocs_arrows.ply'))
valid_joints = [joint for joint in naocs_joints if joint if joint['type'] >= 0]
num_valid_joints = len(valid_joints)
tmp_heatmap = np.empty((num_valid_joints, naocs.shape[0]))
tmp_unitvec = np.empty((num_valid_joints, naocs.shape[0], 3))
for i, joint in enumerate(valid_joints):
joint_class = joint['class']
parent_links = [i for i, link in enumerate(rest_state_data['links'])
if link if not link['virtual'] if joint['parent'] == link['name']]
child_links = [i for i, link in enumerate(rest_state_data['links'])
if link if not link['virtual'] if joint['child'] == link['name']]
connected_links = parent_links + child_links
part_classes = [part_info[str(link_index)]['part_class'] for link_index in connected_links]
if joint['type'] == JointType.prismatic.value:
part_classes = [part_class for part_class in part_classes if part_class == joint_class]
selected_vertex_indices = np.isin(points_class, part_classes)
part_heatmap, part_unitvec = ProcStage2Impl.get_joint_params(naocs, joint, selected_vertex_indices)
tmp_heatmap[joint_class - 1] = part_heatmap
tmp_unitvec[joint_class - 1] = part_unitvec
joints_association = tmp_heatmap.argmin(axis=0)
points_heatmap = tmp_heatmap[joints_association, np.arange(naocs.shape[0])]
points_unitvec = tmp_unitvec[joints_association, np.arange(naocs.shape[0])]
points_unitvec[points_heatmap >= self.heatmap_threshold] = np.zeros(3)
joints_association[points_heatmap >= self.heatmap_threshold] = -1
points_heatmap_result = 1.0 - points_heatmap / self.heatmap_threshold
points_heatmap_result[points_heatmap >= self.heatmap_threshold] = -1
# points with no joint association has value 0
joints_association += 1
joints_axis = np.zeros((naocs.shape[0], 3))
joint_types = -np.ones(num_parts)
for joint in naocs_joints:
if joint:
joints_axis[joints_association == joint['class']] = joint['axis']
joint_types[joint['class']] = joint['type']
h5frame = h5file.require_group(instance_name)
h5frame.attrs['objectCat'] = row["objectCat"]
h5frame.attrs['objectId'] = row["objectId"]
h5frame.attrs['articulationId'] = row["articulationId"]
h5frame.attrs['frameId'] = row["frameId"]
h5frame.attrs['numParts'] = num_parts
h5frame.attrs['id'] = instance_name
h5frame.create_dataset("seg_per_point", shape=points_class.shape, data=points_class, compression="gzip")
h5frame.create_dataset("camcs_per_point", shape=points_camera.shape, data=points_camera, compression="gzip")
h5frame.create_dataset("npcs_per_point", shape=npcs.shape, data=npcs, compression="gzip")
h5frame.create_dataset("naocs_per_point", shape=naocs.shape, data=naocs, compression="gzip")
h5frame.create_dataset("heatmap_per_point", shape=points_heatmap_result.shape, data=points_heatmap_result,
compression="gzip")
h5frame.create_dataset("unitvec_per_point", shape=points_unitvec.shape, data=points_unitvec,
compression="gzip")
h5frame.create_dataset("axis_per_point", shape=joints_axis.shape, data=joints_axis,
compression="gzip")
h5frame.create_dataset("joint_cls_per_point", shape=joints_association.shape, data=joints_association,
compression="gzip")
h5frame.create_dataset("joint_type", shape=joint_types.shape, data=joint_types, compression="gzip")
# 6D transformation from npcs to camcs
h5frame.create_dataset("npcs2cam_rt", shape=parts_npcs2cam_transformation.shape,
data=parts_npcs2cam_transformation, compression="gzip")
# scale from npcs to camcs
h5frame.create_dataset("npcs2cam_scale", shape=parts_npcs2cam_scale.shape, data=parts_npcs2cam_scale,
compression="gzip")
h5frame.create_dataset("naocs2cam_rt", shape=naocs2cam_transformation.shape,
data=naocs2cam_transformation, compression="gzip")
h5frame.create_dataset("naocs2cam_scale", shape=(1,), data=naocs2cam_scale,
compression="gzip")
norm_factors = 1.0 / parts_npcs2cam_scale
h5frame.create_dataset("norm_factors", shape=norm_factors.shape, data=norm_factors,
compression="gzip")
# part bounds at rest state
norm_corners = np.stack((parts_min_bounds, parts_max_bounds), axis=1)
h5frame.create_dataset("norm_corners", shape=norm_corners.shape, data=norm_corners,
compression="gzip")
bar.next()
bar.finish()
h5file.close()
input_h5.close()
return output_filepath
class ProcStage2:
def __init__(self, cfg):
self.cfg = cfg
self.input_cfg = self.cfg.paths.preprocess.stage2.input
self.input_h5_path = os.path.join(self.cfg.paths.preprocess.output_dir, self.input_cfg.pcd_data)
self.output_dir = self.cfg.paths.preprocess.output_dir
self.stag1_tmp_output = self.cfg.paths.preprocess.stage1.tmp_output
self.tmp_output = self.cfg.paths.preprocess.stage2.tmp_output
self.split_info = None
self.debug = self.cfg.debug
self.show = self.cfg.show
self.export = self.cfg.export
stage1_input = self.cfg.paths.preprocess.stage1.input
self.part_orders = io.read_json(os.path.join(self.cfg.paths.preprocess.input_dir, stage1_input.part_order_file))
self.heatmap_threshold = self.cfg.params.joint_association_threshold
def split_data(self, train_percent=.6, split_on='objectId', seed=None):
instances = []
visit_groups = lambda name, node: instances.append(name) if isinstance(node, h5py.Group) else None
input_h5 = h5py.File(self.input_h5_path, 'r')
input_h5.visititems(visit_groups)
df_dataset = pd.DataFrame([name.split('_') for name in instances],
columns=['objectCat', 'objectId', 'articulationId', 'frameId'])
df_dataset = df_dataset.drop_duplicates(ignore_index=True)
# select data in config
selected_categories = df_dataset['objectCat'].isin(self.cfg.settings.categories) \
if len(self.cfg.settings.categories) > 0 else df_dataset['objectCat'].astype(bool)
selected_object_ids = df_dataset['objectId'].isin(self.cfg.settings.object_ids) \
if len(self.cfg.settings.object_ids) > 0 else df_dataset['objectId'].astype(bool)
selected_articulation_ids = df_dataset['articulationId'].isin(self.cfg.settings.articulation_ids) \
if len(self.cfg.settings.articulation_ids) > 0 else df_dataset['articulationId'].astype(bool)
df_dataset = df_dataset[selected_categories & selected_object_ids & selected_articulation_ids]
if io.file_exist(self.cfg.paths.preprocess.stage2.input.split_info, ext='.csv'):
input_split_info = pd.read_csv(self.cfg.paths.preprocess.stage2.input.split_info, dtype=object)
split_on_columns = ['objectCat', 'objectId', 'articulationId', 'frameId']
train_set = input_split_info[input_split_info["set"] == "train"]
val_set = input_split_info[input_split_info["set"] == "val"]
test_set = input_split_info[input_split_info["set"] == "test"]
train = train_set.merge(df_dataset, how='left', on=split_on_columns)
val = val_set.merge(df_dataset, how='left', on=split_on_columns)
test = test_set.merge(df_dataset, how='left', on=split_on_columns)
self.split_info = pd.concat([train, val, test], keys=["train", "val", "test"], names=['set', 'index'])
else:
# split to train, val, test
log.info(f'Split on key {split_on}')
if len(df_dataset):
if split_on == 'objectId':
split_on_columns = ['objectCat', 'objectId']
elif split_on == 'articulationId':
split_on_columns = ['objectCat', 'objectId', 'articulationId']
elif split_on == 'frameId':
split_on_columns = ['objectCat', 'objectId', 'articulationId', 'frameId']
else:
split_on_columns = ['objectCat', 'objectId']
log.warning(f'Cannot parse split_on {split_on}, split on objectId by default')
val_end = train_percent + (1.0 - train_percent) / 2.0
split_df = df_dataset[split_on_columns].drop_duplicates()
set_size = len(split_df)
train_set, val_set, test_set = np.split(
split_df.sample(frac=1.0, random_state=seed),
[int(train_percent * set_size), int(val_end * set_size)]
)
train = train_set.merge(df_dataset, how='left', on=split_on_columns)
val = val_set.merge(df_dataset, how='left', on=split_on_columns)
test = test_set.merge(df_dataset, how='left', on=split_on_columns)
self.split_info = pd.concat([train, val, test], keys=["train", "val", "test"], names=['set', 'index'])
else:
log.error('No data to split!')
return
self.split_info.to_csv(os.path.join(self.output_dir, self.cfg.paths.preprocess.stage2.output.split_info))
def process(self):
io.ensure_dir_exists(self.output_dir)
if self.split_info is None or self.split_info.empty:
log.error('No data to process!')
return
train = self.split_info.loc['train']
log.info(f'Stage2 Process Train Set {len(train)} instances')
self.process_set(train, self.output_dir, self.cfg.paths.preprocess.stage2.output.train_data)
val = self.split_info.loc['val']
log.info(f'Stage2 Process Val Set {len(val)} instances')
self.process_set(val, self.output_dir, self.cfg.paths.preprocess.stage2.output.val_data)
test = self.split_info.loc['test']
log.info(f'Stage2 Process Test Set {len(test)} instances')
self.process_set(test, self.output_dir, self.cfg.paths.preprocess.stage2.output.test_data)
def process_set(self, input_data, output_dir, output_filename):
# process object info
object_df = input_data[['objectCat', 'objectId']].drop_duplicates()
object_infos = {}
bar = Bar('Stage2 Parse Object Infos', max=len(object_df))
for index, row in object_df.iterrows():
stage1_tmp_data_dir = os.path.join(self.cfg.paths.preprocess.tmp_dir, self.stag1_tmp_output.folder_name,
row['objectCat'], row['objectId'])
rest_state_data_path = os.path.join(stage1_tmp_data_dir, self.stag1_tmp_output.rest_state_data)
rest_state_data = io.read_json(rest_state_data_path)
object_mesh_path = os.path.join(stage1_tmp_data_dir, self.stag1_tmp_output.rest_state_mesh)
object_dict = utils.get_mesh_info(object_mesh_path)
part_dict = {}
part_order = None
if self.part_orders:
part_order = self.part_orders[row['objectCat']][row['objectId']]
part_index = 0
for link_index, link in enumerate(rest_state_data['links']):
if link['virtual']:
continue
part_mesh_path = os.path.join(stage1_tmp_data_dir,
f'{link["name"]}_{self.stag1_tmp_output.rest_state_mesh}')
part_dict[link_index] = utils.get_mesh_info(part_mesh_path)
if part_order:
part_dict[link_index]['part_class'] = part_order.index(link['part_index'])
else:
part_dict[link_index]['part_class'] = part_index
part_index += 1
if row['objectCat'] in object_infos:
object_infos[row['objectCat']][row['objectId']] = {'object': object_dict, 'part': part_dict}
else:
object_infos[row['objectCat']] = {row['objectId']: {'object': object_dict, 'part': part_dict}}
bar.next()
bar.finish()
tmp_data_dir = os.path.join(self.cfg.paths.preprocess.tmp_dir, self.tmp_output.folder_name)
io.ensure_dir_exists(tmp_data_dir)
object_infos_path = os.path.join(tmp_data_dir, self.tmp_output.object_info)
io.write_json(object_infos, object_infos_path)
num_processes = min(cpu_count(), self.cfg.num_workers)
# calculate the chunk size
chunk_size = max(1, int(input_data.shape[0] / num_processes))
chunks = [input_data.iloc[input_data.index[i:i + chunk_size]] for i in
range(0, input_data.shape[0], chunk_size)]
log.info(f'Stage2 Processing Start with {num_processes} workers and {len(chunks)} chunks')
config = OmegaConf.create()
config.input_h5_path = self.input_h5_path
config.stage1_tmp_dir = os.path.join(self.cfg.paths.preprocess.tmp_dir, self.stag1_tmp_output.folder_name)
config.tmp_output_dir = os.path.join(self.cfg.paths.preprocess.tmp_dir, self.tmp_output.folder_name)
config.output_path = os.path.join(config.tmp_output_dir, output_filename)
config.rest_state_data_filename = self.stag1_tmp_output.rest_state_data
config.object_infos_path = object_infos_path
config.heatmap_threshold = self.heatmap_threshold
config.export = self.cfg.export
with Pool(processes=num_processes) as pool:
proc_impl = ProcStage2Impl(config)
output_filepath_list = pool.starmap(proc_impl, enumerate(chunks))
h5_output_path = os.path.join(output_dir, output_filename)
h5file = h5py.File(h5_output_path, 'w')
for filepath in output_filepath_list:
with h5py.File(filepath, 'r') as h5f:
for key in h5f.keys():
h5f.copy(key, h5file)
h5file.close()
# if self.debug:
# tmp_data_dir = os.path.join(self.cfg.paths.preprocess.tmp_dir, self.tmp_output.folder_name)
# io.ensure_dir_exists(tmp_data_dir)
# with h5py.File(h5_output_path, 'r') as h5file:
# visualizer = ANCSHVisualizer(h5file, NetworkType.ANCSH, gt=True, sampling=20)
# visualizer.point_size = 5
# visualizer.arrow_sampling = 10
# visualizer.prefix = ''
# visualizer.render(show=self.show, export=tmp_data_dir, export_mesh=self.export)
|
[
"numpy.isin",
"pandas.read_csv",
"numpy.empty",
"numpy.ones",
"tools.utils.io.write_json",
"numpy.linalg.norm",
"numpy.arange",
"os.path.join",
"multiprocessing.cpu_count",
"tools.utils.io.file_exist",
"numpy.empty_like",
"numpy.reshape",
"pandas.concat",
"numpy.stack",
"h5py.File",
"numpy.asarray",
"numpy.linalg.inv",
"utils.get_mesh_info",
"multiprocessing.Pool",
"numpy.dot",
"tools.utils.io.ensure_dir_exists",
"numpy.zeros",
"numpy.where",
"omegaconf.OmegaConf.create",
"os.path.splitext",
"tools.utils.io.read_json",
"logging.getLogger"
] |
[((358, 390), 'logging.getLogger', 'logging.getLogger', (['"""proc_stage2"""'], {}), "('proc_stage2')\n", (375, 390), False, 'import logging\n'), ((1020, 1052), 'numpy.zeros', 'np.zeros', (['(vertices.shape[0], 3)'], {}), '((vertices.shape[0], 3))\n', (1028, 1052), True, 'import numpy as np\n'), ((2148, 2187), 'numpy.where', 'np.where', (['(heatmap >= 0)', 'heatmap', 'np.inf'], {}), '(heatmap >= 0, heatmap, np.inf)\n', (2156, 2187), True, 'import numpy as np\n'), ((2281, 2315), 'h5py.File', 'h5py.File', (['self.input_h5_path', '"""r"""'], {}), "(self.input_h5_path, 'r')\n", (2290, 2315), False, 'import h5py\n'), ((2339, 2375), 'tools.utils.io.read_json', 'io.read_json', (['self.object_infos_path'], {}), '(self.object_infos_path)\n', (2351, 2375), False, 'from tools.utils import io\n'), ((2510, 2541), 'h5py.File', 'h5py.File', (['output_filepath', '"""w"""'], {}), "(output_filepath, 'w')\n", (2519, 2541), False, 'import h5py\n'), ((13713, 13788), 'os.path.join', 'os.path.join', (['self.cfg.paths.preprocess.output_dir', 'self.input_cfg.pcd_data'], {}), '(self.cfg.paths.preprocess.output_dir, self.input_cfg.pcd_data)\n', (13725, 13788), False, 'import os\n'), ((14623, 14657), 'h5py.File', 'h5py.File', (['self.input_h5_path', '"""r"""'], {}), "(self.input_h5_path, 'r')\n", (14632, 14657), False, 'import h5py\n'), ((15671, 15747), 'tools.utils.io.file_exist', 'io.file_exist', (['self.cfg.paths.preprocess.stage2.input.split_info'], {'ext': '""".csv"""'}), "(self.cfg.paths.preprocess.stage2.input.split_info, ext='.csv')\n", (15684, 15747), False, 'from tools.utils import io\n'), ((18228, 18265), 'tools.utils.io.ensure_dir_exists', 'io.ensure_dir_exists', (['self.output_dir'], {}), '(self.output_dir)\n', (18248, 18265), False, 'from tools.utils import io\n'), ((21065, 21141), 'os.path.join', 'os.path.join', (['self.cfg.paths.preprocess.tmp_dir', 'self.tmp_output.folder_name'], {}), '(self.cfg.paths.preprocess.tmp_dir, self.tmp_output.folder_name)\n', (21077, 21141), False, 'import os\n'), ((21150, 21184), 'tools.utils.io.ensure_dir_exists', 'io.ensure_dir_exists', (['tmp_data_dir'], {}), '(tmp_data_dir)\n', (21170, 21184), False, 'from tools.utils import io\n'), ((21213, 21268), 'os.path.join', 'os.path.join', (['tmp_data_dir', 'self.tmp_output.object_info'], {}), '(tmp_data_dir, self.tmp_output.object_info)\n', (21225, 21268), False, 'import os\n'), ((21277, 21323), 'tools.utils.io.write_json', 'io.write_json', (['object_infos', 'object_infos_path'], {}), '(object_infos, object_infos_path)\n', (21290, 21323), False, 'from tools.utils import io\n'), ((21750, 21768), 'omegaconf.OmegaConf.create', 'OmegaConf.create', ([], {}), '()\n', (21766, 21768), False, 'from omegaconf import OmegaConf\n'), ((21851, 21938), 'os.path.join', 'os.path.join', (['self.cfg.paths.preprocess.tmp_dir', 'self.stag1_tmp_output.folder_name'], {}), '(self.cfg.paths.preprocess.tmp_dir, self.stag1_tmp_output.\n folder_name)\n', (21863, 21938), False, 'import os\n'), ((21966, 22042), 'os.path.join', 'os.path.join', (['self.cfg.paths.preprocess.tmp_dir', 'self.tmp_output.folder_name'], {}), '(self.cfg.paths.preprocess.tmp_dir, self.tmp_output.folder_name)\n', (21978, 22042), False, 'import os\n'), ((22072, 22124), 'os.path.join', 'os.path.join', (['config.tmp_output_dir', 'output_filename'], {}), '(config.tmp_output_dir, output_filename)\n', (22084, 22124), False, 'import os\n'), ((22560, 22601), 'os.path.join', 'os.path.join', (['output_dir', 'output_filename'], {}), '(output_dir, output_filename)\n', (22572, 22601), False, 'import os\n'), ((22619, 22649), 'h5py.File', 'h5py.File', (['h5_output_path', '"""w"""'], {}), "(h5_output_path, 'w')\n", (22628, 22649), False, 'import h5py\n'), ((973, 999), 'numpy.ones', 'np.ones', (['vertices.shape[0]'], {}), '(vertices.shape[0])\n', (980, 999), True, 'import numpy as np\n'), ((1164, 1190), 'numpy.linalg.norm', 'np.linalg.norm', (['joint_axis'], {}), '(joint_axis)\n', (1178, 1190), True, 'import numpy as np\n'), ((1392, 1416), 'numpy.dot', 'np.dot', (['vec1', 'joint_axis'], {}), '(vec1, joint_axis)\n', (1398, 1416), True, 'import numpy as np\n'), ((3163, 3231), 'os.path.join', 'os.path.join', (['self.stage1_tmp_dir', "row['objectCat']", "row['objectId']"], {}), "(self.stage1_tmp_dir, row['objectCat'], row['objectId'])\n", (3175, 3231), False, 'import os\n'), ((3267, 3331), 'os.path.join', 'os.path.join', (['stage1_tmp_data_dir', 'self.rest_state_data_filename'], {}), '(stage1_tmp_data_dir, self.rest_state_data_filename)\n', (3279, 3331), False, 'import os\n'), ((3362, 3396), 'tools.utils.io.read_json', 'io.read_json', (['rest_state_data_path'], {}), '(rest_state_data_path)\n', (3374, 3396), False, 'from tools.utils import io\n'), ((4029, 4071), 'numpy.reshape', 'np.reshape', (['camera2base', '(4, 4)'], {'order': '"""F"""'}), "(camera2base, (4, 4), order='F')\n", (4039, 4071), True, 'import numpy as np\n'), ((4297, 4316), 'numpy.empty_like', 'np.empty_like', (['mask'], {}), '(mask)\n', (4310, 4316), True, 'import numpy as np\n'), ((4336, 4368), 'numpy.empty_like', 'np.empty_like', (['points_rest_state'], {}), '(points_rest_state)\n', (4349, 4368), True, 'import numpy as np\n'), ((4413, 4451), 'numpy.empty_like', 'np.empty_like', (['parts_camera2rest_state'], {}), '(parts_camera2rest_state)\n', (4426, 4451), True, 'import numpy as np\n'), ((4487, 4506), 'numpy.empty', 'np.empty', (['num_parts'], {}), '(num_parts)\n', (4495, 4506), True, 'import numpy as np\n'), ((4538, 4562), 'numpy.empty', 'np.empty', (['(num_parts, 3)'], {}), '((num_parts, 3))\n', (4546, 4562), True, 'import numpy as np\n'), ((4594, 4618), 'numpy.empty', 'np.empty', (['(num_parts, 3)'], {}), '((num_parts, 3))\n', (4602, 4618), True, 'import numpy as np\n'), ((8371, 8415), 'numpy.empty', 'np.empty', (['(num_valid_joints, naocs.shape[0])'], {}), '((num_valid_joints, naocs.shape[0]))\n', (8379, 8415), True, 'import numpy as np\n'), ((8442, 8489), 'numpy.empty', 'np.empty', (['(num_valid_joints, naocs.shape[0], 3)'], {}), '((num_valid_joints, naocs.shape[0], 3))\n', (8450, 8489), True, 'import numpy as np\n'), ((9916, 9927), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (9924, 9927), True, 'import numpy as np\n'), ((10290, 10319), 'numpy.zeros', 'np.zeros', (['(naocs.shape[0], 3)'], {}), '((naocs.shape[0], 3))\n', (10298, 10319), True, 'import numpy as np\n'), ((13219, 13273), 'numpy.stack', 'np.stack', (['(parts_min_bounds, parts_max_bounds)'], {'axis': '(1)'}), '((parts_min_bounds, parts_max_bounds), axis=1)\n', (13227, 13273), True, 'import numpy as np\n'), ((14239, 14318), 'os.path.join', 'os.path.join', (['self.cfg.paths.preprocess.input_dir', 'stage1_input.part_order_file'], {}), '(self.cfg.paths.preprocess.input_dir, stage1_input.part_order_file)\n', (14251, 14318), False, 'import os\n'), ((15780, 15856), 'pandas.read_csv', 'pd.read_csv', (['self.cfg.paths.preprocess.stage2.input.split_info'], {'dtype': 'object'}), '(self.cfg.paths.preprocess.stage2.input.split_info, dtype=object)\n', (15791, 15856), True, 'import pandas as pd\n'), ((16435, 16523), 'pandas.concat', 'pd.concat', (['[train, val, test]'], {'keys': "['train', 'val', 'test']", 'names': "['set', 'index']"}), "([train, val, test], keys=['train', 'val', 'test'], names=['set',\n 'index'])\n", (16444, 16523), True, 'import pandas as pd\n'), ((18113, 18199), 'os.path.join', 'os.path.join', (['self.output_dir', 'self.cfg.paths.preprocess.stage2.output.split_info'], {}), '(self.output_dir, self.cfg.paths.preprocess.stage2.output.\n split_info)\n', (18125, 18199), False, 'import os\n'), ((19368, 19490), 'os.path.join', 'os.path.join', (['self.cfg.paths.preprocess.tmp_dir', 'self.stag1_tmp_output.folder_name', "row['objectCat']", "row['objectId']"], {}), "(self.cfg.paths.preprocess.tmp_dir, self.stag1_tmp_output.\n folder_name, row['objectCat'], row['objectId'])\n", (19380, 19490), False, 'import os\n'), ((19568, 19640), 'os.path.join', 'os.path.join', (['stage1_tmp_data_dir', 'self.stag1_tmp_output.rest_state_data'], {}), '(stage1_tmp_data_dir, self.stag1_tmp_output.rest_state_data)\n', (19580, 19640), False, 'import os\n'), ((19671, 19705), 'tools.utils.io.read_json', 'io.read_json', (['rest_state_data_path'], {}), '(rest_state_data_path)\n', (19683, 19705), False, 'from tools.utils import io\n'), ((19737, 19809), 'os.path.join', 'os.path.join', (['stage1_tmp_data_dir', 'self.stag1_tmp_output.rest_state_mesh'], {}), '(stage1_tmp_data_dir, self.stag1_tmp_output.rest_state_mesh)\n', (19749, 19809), False, 'import os\n'), ((19836, 19873), 'utils.get_mesh_info', 'utils.get_mesh_info', (['object_mesh_path'], {}), '(object_mesh_path)\n', (19855, 19873), False, 'import utils\n'), ((21353, 21364), 'multiprocessing.cpu_count', 'cpu_count', ([], {}), '()\n', (21362, 21364), False, 'from multiprocessing import Pool, cpu_count\n'), ((22370, 22399), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'num_processes'}), '(processes=num_processes)\n', (22374, 22399), False, 'from multiprocessing import Pool, cpu_count\n'), ((2454, 2488), 'os.path.splitext', 'os.path.splitext', (['self.output_path'], {}), '(self.output_path)\n', (2470, 2488), False, 'import os\n'), ((4899, 4946), 'numpy.asarray', 'np.asarray', (["part_info[link_index_key]['center']"], {}), "(part_info[link_index_key]['center'])\n", (4909, 4946), True, 'import numpy as np\n'), ((5555, 5629), 'numpy.reshape', 'np.reshape', (["parts_camera2rest_state[link['part_index']]", '(4, 4)'], {'order': '"""F"""'}), "(parts_camera2rest_state[link['part_index']], (4, 4), order='F')\n", (5565, 5629), True, 'import numpy as np\n'), ((5735, 5769), 'numpy.linalg.inv', 'np.linalg.inv', (['npcs_transformation'], {}), '(npcs_transformation)\n', (5748, 5769), True, 'import numpy as np\n'), ((5982, 6032), 'numpy.asarray', 'np.asarray', (["part_info[link_index_key]['min_bound']"], {}), "(part_info[link_index_key]['min_bound'])\n", (5992, 6032), True, 'import numpy as np\n'), ((6080, 6130), 'numpy.asarray', 'np.asarray', (["part_info[link_index_key]['max_bound']"], {}), "(part_info[link_index_key]['max_bound'])\n", (6090, 6130), True, 'import numpy as np\n'), ((6871, 6911), 'numpy.dot', 'np.dot', (['parent_link_abs_pose', 'joint_pose'], {}), '(parent_link_abs_pose, joint_pose)\n', (6877, 6911), True, 'import numpy as np\n'), ((7102, 7147), 'numpy.dot', 'np.dot', (['joint_abs_pose[:3, :3]', "joint['axis']"], {}), "(joint_abs_pose[:3, :3], joint['axis'])\n", (7108, 7147), True, 'import numpy as np\n'), ((9335, 9370), 'numpy.isin', 'np.isin', (['points_class', 'part_classes'], {}), '(points_class, part_classes)\n', (9342, 9370), True, 'import numpy as np\n'), ((10347, 10365), 'numpy.ones', 'np.ones', (['num_parts'], {}), '(num_parts)\n', (10354, 10365), True, 'import numpy as np\n'), ((17909, 17997), 'pandas.concat', 'pd.concat', (['[train, val, test]'], {'keys': "['train', 'val', 'test']", 'names': "['set', 'index']"}), "([train, val, test], keys=['train', 'val', 'test'], names=['set',\n 'index'])\n", (17918, 17997), True, 'import pandas as pd\n'), ((20243, 20339), 'os.path.join', 'os.path.join', (['stage1_tmp_data_dir', 'f"""{link[\'name\']}_{self.stag1_tmp_output.rest_state_mesh}"""'], {}), '(stage1_tmp_data_dir,\n f"{link[\'name\']}_{self.stag1_tmp_output.rest_state_mesh}")\n', (20255, 20339), False, 'import os\n'), ((20422, 20457), 'utils.get_mesh_info', 'utils.get_mesh_info', (['part_mesh_path'], {}), '(part_mesh_path)\n', (20441, 20457), False, 'import utils\n'), ((22713, 22737), 'h5py.File', 'h5py.File', (['filepath', '"""r"""'], {}), "(filepath, 'r')\n", (22722, 22737), False, 'import h5py\n'), ((1625, 1663), 'numpy.linalg.norm', 'np.linalg.norm', (['orthogonal_vec'], {'axis': '(1)'}), '(orthogonal_vec, axis=1)\n', (1639, 1663), True, 'import numpy as np\n'), ((2402, 2436), 'os.path.splitext', 'os.path.splitext', (['self.output_path'], {}), '(self.output_path)\n', (2418, 2436), False, 'import os\n'), ((3786, 3819), 'numpy.asarray', 'np.asarray', (["object_info['center']"], {}), "(object_info['center'])\n", (3796, 3819), True, 'import numpy as np\n'), ((4172, 4207), 'numpy.linalg.inv', 'np.linalg.inv', (['naocs_transformation'], {}), '(naocs_transformation)\n', (4185, 4207), True, 'import numpy as np\n'), ((7190, 7216), 'numpy.linalg.norm', 'np.linalg.norm', (['joint_axis'], {}), '(joint_axis)\n', (7204, 7216), True, 'import numpy as np\n'), ((9730, 9755), 'numpy.arange', 'np.arange', (['naocs.shape[0]'], {}), '(naocs.shape[0])\n', (9739, 9755), True, 'import numpy as np\n'), ((9818, 9843), 'numpy.arange', 'np.arange', (['naocs.shape[0]'], {}), '(naocs.shape[0])\n', (9827, 9843), True, 'import numpy as np\n'), ((6544, 6574), 'numpy.asarray', 'np.asarray', (["joint['pose2link']"], {}), "(joint['pose2link'])\n", (6554, 6574), True, 'import numpy as np\n'), ((6775, 6810), 'numpy.asarray', 'np.asarray', (["parent_link['abs_pose']"], {}), "(parent_link['abs_pose'])\n", (6785, 6810), True, 'import numpy as np\n')]
|
import scxx.preprocessing as pp
import scxx.plotting as pl
import scanorama
import os
import numpy as np
import scanpy as sc
from anndata import AnnData
np.random.seed(0)
NAMESPACE = 'mouse_brain'
BATCH_SIZE = 1000
result_dir="./results/1M_mouse_brain/scanorama/"
data_names = [
'data/mouse_brain/nuclei',
'data/mouse_brain/dropviz/Cerebellum_ALT',
'data/mouse_brain/dropviz/Cortex_noRep5_FRONTALonly',
'data/mouse_brain/dropviz/Cortex_noRep5_POSTERIORonly',
'data/mouse_brain/dropviz/EntoPeduncular',
'data/mouse_brain/dropviz/GlobusPallidus',
'data/mouse_brain/dropviz/Hippocampus',
'data/mouse_brain/dropviz/Striatum',
'data/mouse_brain/dropviz/SubstantiaNigra',
'data/mouse_brain/dropviz/Thalamus',
]
import pandas as pd
genelist = pd.read_csv("./data/scanorama_data/data/mouse_brain/genelist_vipcca.txt",header=None,index_col=0).index
datasets=[]
for i in range(len(data_names)):
name=data_names[i]
ann = pp.read_sc_data("./data/scanorama_data/"+name+"/data.h5ad",batch_name=str(i))
ann=ann[:,genelist]
ann.write("./data/scanorama_data/"+name+"/data_subset.h5ad")
datasets.append(ann)
integrated, corrected = scanorama.correct_scanpy(datasets, return_dimred=True, dimred=16)
scanorama_X=integrated[0]
adata_corrected=corrected[0]
adata_corrected.obs=datasets[0].obs
for i in np.arange(1,len(integrated)):
scanorama_X=np.concatenate([scanorama_X,integrated[i]])
adata_i=corrected[i]
adata_i.obs=datasets[i].obs
adata_corrected=adata_corrected.concatenate(adata_i,index_unique=None)
adata_corrected.raw=adata_corrected.copy()
adata_corrected.X=adata_corrected.X.todense()
adata_corrected.obsm["X_scanorama"]=scanorama_X
adata_corrected.obs_names_make_unique()
# 1,094,150
adata_corrected.write(result_dir+"output.h5ad")
|
[
"scanorama.correct_scanpy",
"numpy.random.seed",
"pandas.read_csv",
"numpy.concatenate"
] |
[((154, 171), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (168, 171), True, 'import numpy as np\n'), ((1165, 1230), 'scanorama.correct_scanpy', 'scanorama.correct_scanpy', (['datasets'], {'return_dimred': '(True)', 'dimred': '(16)'}), '(datasets, return_dimred=True, dimred=16)\n', (1189, 1230), False, 'import scanorama\n'), ((779, 882), 'pandas.read_csv', 'pd.read_csv', (['"""./data/scanorama_data/data/mouse_brain/genelist_vipcca.txt"""'], {'header': 'None', 'index_col': '(0)'}), "('./data/scanorama_data/data/mouse_brain/genelist_vipcca.txt',\n header=None, index_col=0)\n", (790, 882), True, 'import pandas as pd\n'), ((1375, 1419), 'numpy.concatenate', 'np.concatenate', (['[scanorama_X, integrated[i]]'], {}), '([scanorama_X, integrated[i]])\n', (1389, 1419), True, 'import numpy as np\n')]
|
import numpy as np
from aura import aura_loader
import os
import time
import random
def break_aura(path, pieces):
"""
Breaks an aura file into smaller chunks. Saves chunks to local folders.
:param path: A string type of the path to the aura file that is being chunked.
:param pieces: An integer type of how many pieces should result
"""
array = aura_loader.read_file(path)
filepath = "../ChunkedAura" + str(time.time())[5:10]
print("Saving to " + filepath)
os.mkdir(filepath)
l, w, n = array.shape
print(array.shape)
chunkSize = int(n / pieces)
print("Chunking into " + str(chunkSize) + " sized pieces.")
chunk = np.zeros((l, w, chunkSize), dtype=np.float16)
for piece in range(pieces):
print("Chunking piece " + str(piece))
print("Extracting " + str(chunkSize * piece) + " to " + str(chunkSize * piece + chunkSize))
for i in range(chunkSize):
chunk[:, :, i] = array[:, :, i + (chunkSize * piece)]
f = filepath + "/{" + str(l) + "x" + str(w) + "x" + str(chunk.shape[2]) + "}Chunk" + str(piece) + ".aura"
print("Saving chunk " + str(piece) + " to " + f + "\n")
chunk.tofile(f)
print("----------------- CHUNKING COMPLETE -----------------")
def percentise_aura(path, percent):
"""
Breaks an aura file into two pieces of percent sizes.
:param path: A string type of the path to the aura file that is being chunked.
:param percent: A float or double type of the percentage that should be in the first chunk.
Example: percent=0.9 would be 90% of data in first chunk, 10% in the second chunk
"""
array = aura_loader.read_file(path).T
random.shuffle(array)
filepath = "../ChunkedAura" + str(time.time())[5:10]
print("Saving to " + filepath)
os.mkdir(filepath)
n, l, w = array.shape
print(array.shape)
print("Chunking into " + str(percent * 100) + "% and " + str((1 - percent) * 100) + "%")
size1 = int(n * percent)
size2 = int(n * (1 - percent))
print("Chunk1 size = " + str(size1))
print("Chunk2 size = " + str(size2))
chunk1 = np.zeros((l, w, size1), dtype=np.float16)
chunk2 = np.zeros((l, w, size2), dtype=np.float16)
print("Chunking piece 1")
for i in range(size1):
chunk1[:, :, i] = array[i]
f1 = filepath + "/{" + str(chunk1.shape[0]) + "x" + str(chunk1.shape[1]) + "x" + str(
chunk1.shape[2]) + "}Chunk1.aura"
print("Saving chunk1 to " + f1 + "\n")
chunk1.tofile(f1)
for i in range(size2):
chunk2[:, :, i] = array[i + (size1)]
f2 = filepath + "/{" + str(chunk2.shape[0]) + "x" + str(chunk2.shape[1]) + "x" + str(
chunk2.shape[2]) + "}Chunk2.aura"
print("Saving chunk1 to " + f2 + "\n")
chunk2.tofile(f2)
print("----------------- CHUNKING COMPLETE -----------------")
|
[
"os.mkdir",
"random.shuffle",
"numpy.zeros",
"time.time",
"aura.aura_loader.read_file"
] |
[((373, 400), 'aura.aura_loader.read_file', 'aura_loader.read_file', (['path'], {}), '(path)\n', (394, 400), False, 'from aura import aura_loader\n'), ((497, 515), 'os.mkdir', 'os.mkdir', (['filepath'], {}), '(filepath)\n', (505, 515), False, 'import os\n'), ((673, 718), 'numpy.zeros', 'np.zeros', (['(l, w, chunkSize)'], {'dtype': 'np.float16'}), '((l, w, chunkSize), dtype=np.float16)\n', (681, 718), True, 'import numpy as np\n'), ((1692, 1713), 'random.shuffle', 'random.shuffle', (['array'], {}), '(array)\n', (1706, 1713), False, 'import random\n'), ((1810, 1828), 'os.mkdir', 'os.mkdir', (['filepath'], {}), '(filepath)\n', (1818, 1828), False, 'import os\n'), ((2132, 2173), 'numpy.zeros', 'np.zeros', (['(l, w, size1)'], {'dtype': 'np.float16'}), '((l, w, size1), dtype=np.float16)\n', (2140, 2173), True, 'import numpy as np\n'), ((2187, 2228), 'numpy.zeros', 'np.zeros', (['(l, w, size2)'], {'dtype': 'np.float16'}), '((l, w, size2), dtype=np.float16)\n', (2195, 2228), True, 'import numpy as np\n'), ((1658, 1685), 'aura.aura_loader.read_file', 'aura_loader.read_file', (['path'], {}), '(path)\n', (1679, 1685), False, 'from aura import aura_loader\n'), ((439, 450), 'time.time', 'time.time', ([], {}), '()\n', (448, 450), False, 'import time\n'), ((1752, 1763), 'time.time', 'time.time', ([], {}), '()\n', (1761, 1763), False, 'import time\n')]
|
import pytest
import numpy as np
from numpy.testing import assert_allclose
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Flatten
from keras.layers.embeddings import Embedding
from keras.constraints import unitnorm
from keras import backend as K
X1 = np.array([[1], [2]], dtype='int32')
W1 = np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]], dtype='float32')
def test_unitnorm_constraint():
lookup = Sequential()
lookup.add(Embedding(3, 2, weights=[W1],
W_constraint=unitnorm(),
input_length=1))
lookup.add(Flatten())
lookup.add(Dense(1))
lookup.add(Activation('sigmoid'))
lookup.compile(loss='binary_crossentropy', optimizer='sgd',
class_mode='binary')
lookup.train_on_batch(X1, np.array([[1], [0]], dtype='int32'))
norm = np.linalg.norm(K.get_value(lookup.trainable_weights[0]), axis=0)
assert_allclose(norm, np.ones_like(norm).astype('float32'), rtol=1e-05)
if __name__ == '__main__':
pytest.main([__file__])
|
[
"keras.layers.core.Dense",
"numpy.ones_like",
"keras.layers.core.Activation",
"pytest.main",
"keras.backend.get_value",
"keras.constraints.unitnorm",
"numpy.array",
"keras.layers.core.Flatten",
"keras.models.Sequential"
] |
[((291, 326), 'numpy.array', 'np.array', (['[[1], [2]]'], {'dtype': '"""int32"""'}), "([[1], [2]], dtype='int32')\n", (299, 326), True, 'import numpy as np\n'), ((332, 395), 'numpy.array', 'np.array', (['[[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]'], {'dtype': '"""float32"""'}), "([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]], dtype='float32')\n", (340, 395), True, 'import numpy as np\n'), ((443, 455), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (453, 455), False, 'from keras.models import Sequential\n'), ((1038, 1061), 'pytest.main', 'pytest.main', (['[__file__]'], {}), '([__file__])\n', (1049, 1061), False, 'import pytest\n'), ((608, 617), 'keras.layers.core.Flatten', 'Flatten', ([], {}), '()\n', (615, 617), False, 'from keras.layers.core import Dense, Activation, Flatten\n'), ((634, 642), 'keras.layers.core.Dense', 'Dense', (['(1)'], {}), '(1)\n', (639, 642), False, 'from keras.layers.core import Dense, Activation, Flatten\n'), ((659, 680), 'keras.layers.core.Activation', 'Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (669, 680), False, 'from keras.layers.core import Dense, Activation, Flatten\n'), ((816, 851), 'numpy.array', 'np.array', (['[[1], [0]]'], {'dtype': '"""int32"""'}), "([[1], [0]], dtype='int32')\n", (824, 851), True, 'import numpy as np\n'), ((879, 919), 'keras.backend.get_value', 'K.get_value', (['lookup.trainable_weights[0]'], {}), '(lookup.trainable_weights[0])\n', (890, 919), True, 'from keras import backend as K\n'), ((539, 549), 'keras.constraints.unitnorm', 'unitnorm', ([], {}), '()\n', (547, 549), False, 'from keras.constraints import unitnorm\n'), ((955, 973), 'numpy.ones_like', 'np.ones_like', (['norm'], {}), '(norm)\n', (967, 973), True, 'import numpy as np\n')]
|
# Copyright (c) 2021 - present / Neuralmagic, Inc. 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.
import os
from typing import List
import numpy
from deepsparse.utils.log import log_init
__all__ = [
"arrays_to_bytes",
"bytes_to_arrays",
"verify_outputs",
]
log = log_init(os.path.basename(__file__))
def arrays_to_bytes(arrays: List[numpy.array]) -> bytearray:
"""
:param arrays: List of numpy arrays to serialize as bytes
:return: bytearray representation of list of numpy arrays
"""
to_return = bytearray()
for arr in arrays:
arr_dtype = bytearray(str(arr.dtype), "utf-8")
arr_shape = bytearray(",".join([str(a) for a in arr.shape]), "utf-8")
sep = bytearray("|", "utf-8")
arr_bytes = arr.ravel().tobytes()
to_return += arr_dtype + sep + arr_shape + sep + arr_bytes
return to_return
def bytes_to_arrays(serialized_arr: bytearray) -> List[numpy.array]:
"""
:param serialized_arr: bytearray representation of list of numpy arrays
:return: List of numpy arrays decoded from input
"""
sep = "|".encode("utf-8")
arrays = []
i_start = 0
while i_start < len(serialized_arr) - 1:
i_0 = serialized_arr.find(sep, i_start)
i_1 = serialized_arr.find(sep, i_0 + 1)
arr_dtype = numpy.dtype(serialized_arr[i_start:i_0].decode("utf-8"))
arr_shape = tuple(
[int(a) for a in serialized_arr[i_0 + 1 : i_1].decode("utf-8").split(",")]
)
arr_num_bytes = numpy.prod(arr_shape) * arr_dtype.itemsize
arr_str = serialized_arr[i_1 + 1 : arr_num_bytes + (i_1 + 1)]
arr = numpy.frombuffer(arr_str, dtype=arr_dtype).reshape(arr_shape)
arrays.append(arr.copy())
i_start = i_1 + arr_num_bytes + 1
return arrays
def verify_outputs(
outputs: List[numpy.array],
gt_outputs: List[numpy.array],
atol: float = 8.0e-4,
rtol: float = 0.0,
) -> List[float]:
"""
Compares two lists of output tensors, checking that they are sufficiently similar
:param outputs: List of numpy arrays, usually model outputs
:param gt_outputs: List of numpy arrays, usually reference outputs
:param atol: Absolute tolerance for allclose
:param rtol: Relative tolerance for allclose
:return: The list of max differences for each pair of outputs
"""
max_diffs = []
if len(outputs) != len(gt_outputs):
raise Exception(
f"number of outputs doesn't match, {len(outputs)} != {len(gt_outputs)}"
)
for i in range(len(gt_outputs)):
gt_output = gt_outputs[i]
output = outputs[i]
if output.shape != gt_output.shape:
raise Exception(
f"output shapes don't match, {output.shape} != {gt_output.shape}"
)
if type(output) != type(gt_output):
raise Exception(
f"output types don't match, {type(output)} != {type(gt_output)}"
)
max_diff = numpy.max(numpy.abs(output - gt_output))
max_diffs.append(max_diff)
log.info(f"output {i}: {output.shape} {gt_output.shape} MAX DIFF: {max_diff}")
if not numpy.allclose(output, gt_output, rtol=rtol, atol=atol):
raise Exception(
"output data doesn't match\n"
f"output {i}: {output.shape} {gt_output.shape} MAX DIFF: {max_diff}\n"
f" mean = {numpy.mean(output):.5f} {numpy.mean(gt_output):.5f}\n"
f" std = {numpy.std(output):.5f} {numpy.std(gt_output):.5f}\n"
f" max = {numpy.max(output):.5f} {numpy.max(gt_output):.5f}\n"
f" min = {numpy.min(output):.5f} {numpy.min(gt_output):.5f}"
)
return max_diffs
|
[
"numpy.abs",
"os.path.basename",
"numpy.std",
"numpy.frombuffer",
"numpy.allclose",
"numpy.max",
"numpy.mean",
"numpy.min",
"numpy.prod"
] |
[((809, 835), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (825, 835), False, 'import os\n'), ((2036, 2057), 'numpy.prod', 'numpy.prod', (['arr_shape'], {}), '(arr_shape)\n', (2046, 2057), False, 'import numpy\n'), ((3524, 3553), 'numpy.abs', 'numpy.abs', (['(output - gt_output)'], {}), '(output - gt_output)\n', (3533, 3553), False, 'import numpy\n'), ((3693, 3748), 'numpy.allclose', 'numpy.allclose', (['output', 'gt_output'], {'rtol': 'rtol', 'atol': 'atol'}), '(output, gt_output, rtol=rtol, atol=atol)\n', (3707, 3748), False, 'import numpy\n'), ((2163, 2205), 'numpy.frombuffer', 'numpy.frombuffer', (['arr_str'], {'dtype': 'arr_dtype'}), '(arr_str, dtype=arr_dtype)\n', (2179, 2205), False, 'import numpy\n'), ((3942, 3960), 'numpy.mean', 'numpy.mean', (['output'], {}), '(output)\n', (3952, 3960), False, 'import numpy\n'), ((3967, 3988), 'numpy.mean', 'numpy.mean', (['gt_output'], {}), '(gt_output)\n', (3977, 3988), False, 'import numpy\n'), ((4027, 4044), 'numpy.std', 'numpy.std', (['output'], {}), '(output)\n', (4036, 4044), False, 'import numpy\n'), ((4051, 4071), 'numpy.std', 'numpy.std', (['gt_output'], {}), '(gt_output)\n', (4060, 4071), False, 'import numpy\n'), ((4110, 4127), 'numpy.max', 'numpy.max', (['output'], {}), '(output)\n', (4119, 4127), False, 'import numpy\n'), ((4134, 4154), 'numpy.max', 'numpy.max', (['gt_output'], {}), '(gt_output)\n', (4143, 4154), False, 'import numpy\n'), ((4193, 4210), 'numpy.min', 'numpy.min', (['output'], {}), '(output)\n', (4202, 4210), False, 'import numpy\n'), ((4217, 4237), 'numpy.min', 'numpy.min', (['gt_output'], {}), '(gt_output)\n', (4226, 4237), False, 'import numpy\n')]
|
from datetime import date
import numpy as np
from matplotlib.lines import Line2D
from _ids import *
import _icons as ico
from utilities import pydate2wxdate, wxdate2pydate, GetAttributes
from properties import SummaryProperty
class VariableManager:
def __init__(self, unit_system):
# simulation dependent -----------------------------------------------------------------------------------------
# times
self._time = Time()
self._date = Date()
# potentials
self._oil_potential = OilPotential(unit_system)
self._gas_potential = GasPotential(unit_system)
self._water_potential = WaterPotential(unit_system)
self._liquid_potential = LiquidPotential(unit_system)
self._lift_gas_potential = LiftGasPotential(unit_system)
self._gas_injection_potential = GasInjectionPotential(unit_system)
self._water_injection_potential = WaterInjectionPotential(unit_system)
self._total_gas_potential = TotalGasPotential(unit_system)
# rates
self._oil_rate = OilRate(unit_system)
self._gas_rate = GasRate(unit_system)
self._water_rate = WaterRate(unit_system)
self._liquid_rate = LiquidRate(unit_system)
self._lift_gas_rate = LiftGasRate(unit_system)
self._gas_injection_rate = GasInjectionRate(unit_system)
self._water_injection_rate = WaterInjectionRate(unit_system)
self._total_gas_rate = TotalGasRate(unit_system)
# cumulatives
self._oil_cumulative = OilCumulative(unit_system)
self._gas_cumulative = GasCumulative(unit_system)
self._water_cumulative = WaterCumulative(unit_system)
self._liquid_cumulative = LiquidCumulative(unit_system)
self._lift_gas_cumulative = LiftGasCumulative(unit_system)
self._gas_injection_cumulative = GasInjectionCumulative(unit_system)
self._water_injection_cumulative = WaterInjectionCumulative(unit_system)
self._total_gas_cumulative = TotalGasCumulative(unit_system)
# ratios
self._water_cut = WaterCut(unit_system)
self._oil_cut = OilCut(unit_system)
self._gas_oil_ratio = GasOilRatio(unit_system)
self._water_oil_ratio = WaterOilRatio(unit_system)
self._gas_liquid_ratio = GasLiquidRatio(unit_system)
self._water_gas_ratio = WaterGasRatio(unit_system)
self._oil_gas_ratio = OilGasRatio(unit_system)
self._total_gas_liquid_ratio = TotalGasLiquidRatio(unit_system)
self._production_uptime = ProductionUptime(unit_system)
self._lift_gas_uptime = LiftGasUptime(unit_system)
self._gas_injection_uptime = GasInjectionUptime(unit_system)
self._water_injection_uptime = WaterInjectionUptime(unit_system)
# user-defined summary variables
self._summaries = {}
# non-simulation dependent -------------------------------------------------------------------------------------
# wells
self._well_spacing = WellSpacing(unit_system)
# reservoir fluids
self._bo = OilFVF(unit_system)
self._bg = GasFVF(unit_system)
self._bw = WaterFVF(unit_system)
self._rs = SolutionGasOilRatio(unit_system)
# injection fluids
self._bg_inj = InjectionGasFVF(unit_system)
self._bw_inj = InjectionWaterFVF(unit_system)
# facilities
self._availability = Availability(unit_system)
self._tglr = TargetGasLiquidRatio(unit_system)
self._wag_cycle = WAGCycleDuration(unit_system)
self._wag_cycles = WAGCycles(unit_system)
self._voidage_ratio = TargetVoidageRatio(unit_system)
# constraints
self._oil_constraint = OilConstraint(unit_system)
self._gas_constraint = GasConstraint(unit_system)
self._water_constraint = WaterConstraint(unit_system)
self._liquid_constraint = LiquidConstraint(unit_system)
self._gas_inj_constraint = InjectionGasConstraint(unit_system)
self._water_inj_constraint = InjectionWaterConstraint(unit_system)
self._gas_lift_constraint = LiftGasConstraint(unit_system)
# volumes
self._stoiip = STOIIP(unit_system)
# risking
self._maturity = Maturity(unit_system)
self._pos = ProbabilityOfSuccess(unit_system)
# scalers
self._s_cum = CumulativeScaler(unit_system)
self._s_rate = RateScaler(unit_system)
self._s_ffw = FFWScaler(unit_system)
self._s_ffg = FFGScaler(unit_system)
self._onset = OnsetScaler(unit_system)
self._wct_ini = InitialWCTScaler(unit_system)
# statics TODO: Change to a dictionary and let user fill with only useful parameters
self._length = CompletedLength(unit_system)
self._hcft = HydrocarbonFeet(unit_system)
self._hcpv = HydrocarbonPoreVolume(unit_system)
self._permeability = Permeability(unit_system)
self._oil_density = OilDensity(unit_system)
# correlation matrix for the scalers and static parameters -----------------------------------------------------
self._correlation_labels = []
self._correlation_matrix = []
self.InitialiseCorrelationMatrix()
def AddCorrelation(self, variable):
if self._correlation_matrix:
for row in self._correlation_matrix:
row.append(0.)
self._correlation_matrix.append([0.] * (len(self._correlation_matrix) + 1))
self._correlation_matrix[-1][-1] = 1.
self._correlation_labels.append(variable.GetMenuLabel())
def AddSummary(self, summary):
id_ = self.GetUniqueSummaryId()
summary.SetId(id_)
self._summaries[id_] = summary
def DeleteSummary(self, id_):
del self._summaries[id_]
def Get(self, type_, id_=None):
if id_ is None:
return list(getattr(self, '_{}'.format(type_)).values())
else:
return getattr(self, '_{}'.format(type_))[id_]
def GetAllVariables(self):
return GetAttributes(self, exclude=('_correlation_labels', '_correlation_matrix'), sort=True)
def GetCorrelationMatrix(self):
return self._correlation_matrix, self._correlation_labels
def GetSummaries(self):
return self._summaries.values()
def GetVariable(self, id_):
attr = '_{}'.format(id_)
if hasattr(self, attr):
return getattr(self, attr)
else:
return self._summaries[id_]
def GetVariables(self, ids):
return [self.GetVariable(id_) for id_ in ids]
def GetUniqueSummaryId(self):
ids = self._summaries.keys()
if not ids:
return 0
else:
return max(ids) + 1
def InitialiseCorrelationMatrix(self):
attrs = GetAttributes(self, exclude=('_summaries', '_correlation_labels', '_correlation_matrix'), attr_only=True, sort=True)
for attr in attrs:
if attr.IsStatic() or attr.IsScaler():
self.AddCorrelation(attr)
def SetCorrelationMatrix(self, correlation_matrix):
self._correlation_matrix = correlation_matrix
# ======================================================================================================================
# Generic Variables
# ======================================================================================================================
class Variable:
def __init__(self):
self._unit = None # subclass of class Unit
self._frame_label = None # label shown on wx.Frames
self._menu_label = None # label shown in treectrls
self._image = None # PyEmbeddedImage shown in trees, etc.
self._choices = None # list of strings, which can be given as input to wx.Choice, etc.
self._choice_images = None # list of PyEmbeddedImage which can be passed to bitmapcombobox
self._client_data_map = None # dictionary of client_data for each index in bitmapcombobox
self._limits = (None, None) # limiting values for input and on plot axis'
# plot options
self._line_options = None # class of LineOptions
self._fitted_options = None # class of FittedDataOptions
self._legend = None # string, used for bar and bubble charts
# axis options (plotting)
self._plot_label = None # label shown in Matplotlib plots
self._is_date = False # required for plotting of dates
# to and from Frame options
self._round_off = None # round-off used for wx.Frame displays of variables (if pytype is float)
self._pytype = None # python-type
# tooltip
self._tooltip = None # str, tooltip to be displayed on hover
# variable management
self._type = None # str
self._id = None # str, allows access to variable_mgr via getattr(self, id_)
self._type_id = None # int, id to test against
self._image_key = None
def FromFrame(self, value):
if self._pytype is not str and value == '':
return None
elif self._pytype is bool:
return value
elif self._pytype is float:
return float(value)
elif self._pytype is int:
return int(value)
elif self._pytype is date:
return wxdate2pydate(value)
elif self._pytype is str:
return str(value)
elif (self._pytype is list) or (self._pytype is tuple):
if value == -1: # default selection in a combobox/choice
return None
else:
return value
elif self._pytype is Pointer:
return value
elif self._pytype is Index:
return value
elif self._pytype is wx.Colour:
return value
def GetAttribute(self):
return '_{}'.format(self._type)
def GetBitmap(self):
if self._image is not None:
return self._image.GetBitmap()
else:
return wx.NullBitmap
def GetImage(self):
return self._image
def GetChoices(self, idx=None):
if idx is None:
return [choice if choice is not None else '' for choice in self._choices]
else:
return self._choices[idx]
def GetChoiceBitmaps(self):
return [image.GetBitmap() if (image is not None) else wx.NullBitmap for image in self._choice_images]
def GetClientDataMap(self):
return self._client_data_map
def GetComboLabel(self):
return self._frame_label
def GetFittedOptions(self):
return self._fitted_options
def GetFrameLabel(self, idx=None):
if isinstance(self._frame_label, tuple) and idx is None:
return ('{}:'.format(l) for l in self._frame_label)
if idx is None:
if self._frame_label is None:
return None
label = self._frame_label
else:
if self._frame_label[idx] is None:
return None
label = self._frame_label[idx]
return '{}:'.format(label)
def GetId(self):
return self._id
def GetImageKey(self):
return self._image_key
def GetLabel(self):
return self._frame_label
def GetLegend(self):
return self._legend
def GetLimits(self):
return self._limits
def GetLineOptions(self):
return self._line_options
def GetMenuLabel(self):
return self._menu_label
def GetPlotLabel(self):
return self._line_options.GetLabel()
def GetToolTip(self):
return self._tooltip
def GetType(self):
return self._type
def GetTypeId(self):
return self._type_id
def GetUnit(self, idx=None):
if idx is None:
unit = self._unit
else:
unit = self._unit[idx]
if unit is None or isinstance(unit, str) or isinstance(unit, tuple):
return unit
else:
return unit.Get()
def GetUnitClass(self):
return self._unit
def GetXLabel(self):
unit = self._unit.Get()
if unit:
if ('^' in unit) or ('_' in unit):
return r'{} [${}$]'.format(self._plot_label, unit)
else:
return r'{} [{}]'.format(self._plot_label, unit)
else:
return r'{}'.format(self._plot_label)
def GetYLabel(self, group_units=False):
if group_units:
label = self._unit.GetLabel()
else:
label = self._plot_label
unit = self._unit.Get()
if ('^' in unit) or ('_' in unit):
unit_label = r'[${}$]'.format(unit)
elif unit == '':
unit_label = r'[-]'
else:
unit_label = r'[{}]'.format(unit)
return r'{} {}'.format(label, unit_label)
def IsDate(self):
return self._is_date
def IsScaler(self):
return self.IsType('scalers')
def IsStatic(self):
return self.IsType('statics')
def IsSummary(self):
return self.IsType('summaries')
def IsType(self, type_):
return self._type == type_
def SetBitmap(self, bitmap):
self._bitmap = bitmap
def SetImage(self, image_key=None):
self._image_key = self._id
def SetUnit(self, unit_system):
pass
def SetUnitClass(self, unit_class):
self._unit = unit_class
def ToFrame(self, value):
if ((self._pytype is float) or (self._pytype is int)) and value is None:
return ''
elif self._pytype is bool:
return value
elif self._pytype is float:
return str(round(value, self._round_off))
elif self._pytype is int:
return str(value)
elif self._pytype is date:
if value is None: # occurs on first load
return wx.DateTime.Now()
else:
return pydate2wxdate(value)
elif self._pytype is str:
if value is None:
return ''
else:
return str(value)
elif (self._pytype is list) or (self._pytype is tuple):
if value is None: # default selection in a combobox/choice
return -1
else:
return value
elif self._pytype is Pointer:
return value
elif self._pytype is Index:
if value is None: # default selection in a RadioBoxes
return 0
else:
return value
elif self._pytype is wx.Colour:
return value
class VariableCollection:
def __init__(self, *variables):
self._variables = []
self.AddVariables(*variables)
def AddVariable(self, variable):
self._variables.append(variable)
def AddVariables(self, *variables):
for variable in variables:
self.AddVariable(variable)
def GetChoiceBitmaps(self):
return [v.GetBitmap() for v in self._variables]
def GetChoices(self):
return [v.GetComboLabel() for v in self._variables]
def GetFrameLabel(self, idx=None):
if idx is None:
return [v.GetFrameLabel() for v in self._variables]
else:
return self._variables[idx].GetFrameLabel()
def GetUnit(self, idx=None):
if idx is None:
return [v.GetUnit() for v in self._variables]
else:
return self._variables[idx].GetUnit()
def GetVariables(self):
return self._variables
class Summary(Variable):
def __init__(self):
super().__init__()
self._image_key = None
self._properties = SummaryProperty() # similar to what Entities have
self._type = 'summaries'
self._type_id = ID_SUMMARY
def Calculate(self, profile, *args):
return self._properties.Calculate(profile, *args)
def GetImageKey(self):
return self._image_key
def GetProperties(self):
return self._properties
def ReplaceInformation(self, variable, image):
self._image = image
self._unit = variable.GetUnitClass()
self._properties = variable.GetProperties()
self._menu_label = variable.GetMenuLabel()
self._plot_label = variable.GetMenuLabel()
self._legend = variable.GetMenuLabel()
def SetId(self, id_):
self._id = id_
def SetImage(self, image_key=None):
self._image_key = image_key
self._image = image_key
def SetLabels(self, label):
self._menu_label = label
self._plot_label = label
self._legend = label
# ======================================================================================================================
# Types used to test against in ToFrame and FromFrame
# ======================================================================================================================
class Pointer:
"""
Used for controls that allow insert via an arrow or other means
"""
def __init__(self):
pass
class Index:
"""
Used for transfer to and from RadioBox (which requires 0 as default, unlike bitmapcombobox which requires -1)
"""
def __init__(self):
pass
# ======================================================================================================================
# Plotting options for plotable variables
# ======================================================================================================================
class LineOptions:
def __init__(self, alpha=None, colour=None, drawstyle='default', fillstyle=None, label=None, linestyle='-',
linewidth=None, marker=None, markersize=None):
self._alpha = alpha # double, [0, 1]
self._colour = colour # (R, G, B) normalized to [0, 1]
self._drawstyle = drawstyle # 'default', 'steps-{pre, mid, post}'
self._fillstyle = fillstyle # 'full', 'none' (additional options available)
self._label = label # string
self._linestyle = linestyle # '-', '--', '-.', ':'
self._linewidth = linewidth # int, primarily set through settings
self._marker = marker # see matplotlib documentation
self._markersize = markersize # int, primarily set through settings
self._picker = 7 # sensitivity to click-events
def Get(self):
# returns all options as **kwargs input to a matplotlib axes.plot function
return {'alpha': self._alpha,
'color': self._colour,
'drawstyle': self._drawstyle,
'fillstyle': self._fillstyle,
'label': self._label,
'linestyle': self._linestyle,
'linewidth': self._linewidth,
'marker': self._marker,
'markersize': self._markersize,
'picker': self._picker}
def GetAlpha(self):
return self._alpha
def GetColour(self):
return self._colour
def GetDrawstyle(self):
"""
Used for transfer to frame
:return:
"""
if self._drawstyle is None:
return -1
elif self._drawstyle == 'default':
return 0
elif self._drawstyle == 'steps-pre':
return 1
elif self._drawstyle == 'steps-mid':
return 2
elif self._drawstyle == 'steps-post':
return 3
def GetLabel(self):
return self._label
def GetLegend(self):
return Line2D([], [], **self.Get())
def GetLinestyle(self):
"""
Used for transfer to frame
:return:
"""
if self._linestyle is None:
return -1
elif self._linestyle == '-':
return 0
elif self._linestyle == '--':
return 1
elif self._linestyle == '-.':
return 2
elif self._linestyle == ':':
return 3
def SetAlpha(self, alpha):
self._alpha = alpha
def SetColour(self, colour):
self._colour = colour
def SetDrawstyle(self, drawstyle):
"""
Used for transfer from frame
:param drawstyle: int, BitmapComboBox index
:return:
"""
if drawstyle == -1:
self._drawstyle = None
elif drawstyle == 0:
self._drawstyle = 'default'
elif drawstyle == 1:
self._drawstyle = 'steps-pre'
elif drawstyle == 2:
self._drawstyle = 'steps-mid'
elif drawstyle == 3:
self._drawstyle = 'steps-post'
def SetFillstyle(self, fillstyle):
self._fillstyle = fillstyle
def SetLabel(self, label):
self._label = label
def SetLinestyle(self, linestyle):
"""
Used for transfer from frame
:param drawstyle: int, BitmapComboBox index
:return:
"""
if linestyle == -1:
self._linestyle = None
elif linestyle == 0:
self._linestyle = '-'
elif linestyle == 1:
self._linestyle = '--'
elif linestyle == 2:
self._linestyle = '-.'
elif linestyle == 3:
self._linestyle = ':'
def SetLinewidth(self, linewidth):
self._linewidth = linewidth
def SetMarker(self, marker):
self._marker = marker
def SetMarkerSize(self, markersize):
self._markersize = markersize
def Highlight(self):
if self._markersize > 0:
self._markersize += 2
else:
self._linewidth += 2
def UnHighlight(self):
if self._markersize > 0:
self._markersize -= 2
else:
self._linewidth -= 2
class FittedDataOptions(LineOptions):
def __init__(self, colour=None):
super().__init__()
self._colour = colour
self._label = 'Fitted data'
self._fillstyle = 'none'
self._linewidth = 0.
self._marker = 'o'
# ======================================================================================================================
# Units
# ======================================================================================================================
class Unit:
def __init__(self, unit_system=None):
self._unit = None
self._label = None # used as label in plotting when units are grouped
def Get(self):
return self._unit
def GetLabel(self):
return self._label
def Set(self, unit_system):
# sub-class
pass
class TimeUnit(Unit):
def __init__(self, unit='days', unit_system=None):
super().__init__()
self._unit = unit
class DateUnit(Unit):
def __init__(self, unit_system=None):
super().__init__()
self._unit = '-'
class LiquidFlowRateUnit(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Liquid Flow Rate'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'Mstb/day'
else: # metric
self._unit = 'm^{3}/day'
class GasFlowRateUnit(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Gas Flow Rate'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'MMscf/day'
else: # metric
self._unit = 'm^{3}/day'
class LiquidVolumeUnit(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Liquid Volume'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'MMstb'
else: # metric
self._unit = 'km^{3}'
class GasVolumeUnit(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Gas Volume'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'Bscf'
else: # metric
self._unit = 'km^{3}'
class GasLiquidRatioUnit(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Gas-Liquid Ratio'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'Mscf/stb'
else: # metric
self._unit = 'sm^{3}/sm^{3}'
class LiquidGasRatioUnit(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Liquid-Gas Ratio'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'stb/Mscf'
else: # metric
self._unit = 'sm^{3}/sm^{3}'
class LiquidLiquidRatioUnit(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Liquid-Liquid Ratio'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'stb/stb'
else: # metric
self._unit = 'sm^{3}/sm^{3}'
class LiquidVolumeRatio(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Liquid Volume Ratio'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'rb/stb'
else: # metric
self._unit = 'rm^{3}/sm^{3}'
class GasVolumeRatio(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Gas Volume Ratio'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'rb/Mscf'
else: # metric
self._unit = 'rm^{3}/sm^{3}'
class ReservoirVolumeRatio(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Reservoir Volume Ratio'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'rb/rb'
else: # metric
self._unit = 'rm^{3}/rm^{3}'
class LengthUnit(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Length'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'ft'
else: # metric
self._unit = 'm'
class AreaUnit(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Area'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'ft^{2}'
else: # metric
self._unit = 'm^{2}'
class VolumeUnit(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Volume'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = 'stb'
else: # metric
self._unit = 'm^{3}'
class PermeabilityUnit(Unit):
def __init__(self, unit_system=None):
super().__init__()
self._label = 'Permeability'
self._unit = 'mD'
class DensityUnit(Unit):
def __init__(self, unit_system):
super().__init__()
self._label = 'Density'
self.Set(unit_system)
def Set(self, unit_system):
if unit_system == ID_UNIT_FIELD:
self._unit = '^{o}API'
else: # metric
self._unit = 'kg/m^{3}'
class FractionUnit(Unit):
def __init__(self, unit_system=None):
super().__init__()
self._label = 'Fraction'
self._unit = '-'
class PercentageUnit(Unit):
def __init__(self, unit_system=None):
super().__init__()
self._label = 'Percentage'
self._unit = '%'
class AmountUnit(Unit):
def __init__(self, unit_system=None):
super().__init__()
self._label = 'Amount'
self._unit = ''
class Unitless(Unit):
def __init__(self, unit_system=None):
super().__init__()
self._label = 'Dimensionless'
self._unit = ''
# ======================================================================================================================
# Time Variables
# ======================================================================================================================
class DurationVariable(Variable):
def __init__(self):
super().__init__()
self._type = 'durations'
class Time(DurationVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = TimeUnit()
self._menu_label = 'Time'
self._plot_label = 'Time'
self._image = ico.time_16x16
self._limits = (0., None)
self._id = 'time'
class Date(DurationVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = DateUnit()
self._menu_label = 'Date'
self._plot_label = 'Dates'
self._image = ico.dates_16x16
self._limits = (None, None)
self._is_date = True
self._id = 'date'
# ======================================================================================================================
# Production Potential Variables
# ======================================================================================================================
class PotentialVariable(Variable):
def __init__(self):
super().__init__()
self._limits = (0., None)
self._type = 'potentials'
self._type_id = ID_POTENTIAL
class OilPotential(PotentialVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._menu_label = 'Oil production potential'
self._image = ico.oil_rate_16x16
self._line_options = LineOptions(label=r'Oil Pot.', colour=np.array([0., 176., 80.]) / 255., linestyle='--')
self._plot_label = r'Oil Production Potential'
self._id = 'oil_potential'
class GasPotential(PotentialVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._menu_label = 'Gas production potential'
self._image = ico.gas_rate_16x16
self._line_options = LineOptions(label=r'Gas Pot.', colour=np.array([255., 0., 0.]) / 255., linestyle='--')
self._plot_label = r'Gas Production Potential'
self._id = 'gas_potential'
class WaterPotential(PotentialVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._menu_label = 'Water production potential'
self._image = ico.water_rate_16x16
self._line_options = LineOptions(label=r'Water Pot.', colour=np.array([91., 155., 213.]) / 255., linestyle='--')
self._plot_label = r'Water Production Potential'
self._id = 'water_potential'
class LiquidPotential(PotentialVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._menu_label = 'Liquid production potential'
self._image = ico.liquid_rate_16x16
self._line_options = LineOptions(label=r'Liquid Pot.', colour=np.array([51., 102., 153.]) / 255., linestyle='--')
self._fitted_options = FittedDataOptions(colour=np.array([255., 0., 0.]) / 255.)
self._plot_label = r'Liquid Production Potential'
self._id = 'liquid_potential'
class LiftGasPotential(PotentialVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._menu_label = 'Lift gas injection potential'
self._image = ico.lift_gas_rate_16x16
self._line_options = LineOptions(label=r'Lift Gas Pot.', colour=np.array([219., 34., 211.]) / 255., linestyle='--')
self._plot_label = r'Lift Gas Injection Potential'
self._id = 'lift_gas_potential'
class GasInjectionPotential(PotentialVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._menu_label = 'Gas injection potential'
self._image = ico.gas_injection_rate_16x16
self._line_options = LineOptions(label=r'Gas Inj. Pot.', colour=np.array([255., 0., 0.]) / 255., linestyle='--')
self._plot_label = r'Gas Injection Potential'
self._id = 'gas_injection_potential'
class WaterInjectionPotential(PotentialVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._menu_label = 'Water injection potential'
self._image = ico.water_injection_rate_16x16
self._line_options = LineOptions(label=r'Water Inj. Pot.', colour=np.array([91., 155., 213.]) / 255., linestyle='--')
self._plot_label = r'Water Injection Potential'
self._id = 'water_injection_potential'
class TotalGasPotential(PotentialVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._menu_label = 'Total gas production potential'
self._image = ico.total_gas_rate_16x16
self._line_options = LineOptions(label=r'Total Gas Pot.', colour=np.array([218., 119., 6.]) / 255., linestyle='--')
self._plot_label = r'Total Gas Production Potential'
self._id = 'total_gas_potential'
# ======================================================================================================================
# Production Rate Variables
# ======================================================================================================================
class RateVariable(Variable):
def __init__(self):
super().__init__()
self._limits = (0., None)
self._type = 'rates'
self._type_id = ID_RATE
class OilRate(RateVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._menu_label = 'Oil production rate'
self._image = ico.oil_rate_16x16
self._line_options = LineOptions(label=r'Oil Rate', colour=np.array([0., 176., 80.]) / 255.)
self._plot_label = r'Oil Production Rate'
self._id = 'oil_rate'
class GasRate(RateVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._menu_label = 'Gas production rate'
self._image = ico.gas_rate_16x16
self._line_options = LineOptions(label=r'Gas Rate', colour=np.array([255., 0., 0.]) / 255.)
self._plot_label = r'Gas Production Rate'
self._id = 'gas_rate'
class WaterRate(RateVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._menu_label = 'Water production rate'
self._image = ico.water_rate_16x16
self._line_options = LineOptions(label=r'Water Rate', colour=np.array([91., 155., 213.]) / 255.)
self._plot_label = r'Water Production Rate'
self._id = 'water_rate'
class LiquidRate(RateVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._menu_label = 'Liquid production rate'
self._image = ico.liquid_rate_16x16
self._line_options = LineOptions(label=r'Liquid Rate', colour=np.array([51., 102., 153.]) / 255.)
self._plot_label = r'Liquid Production Rate'
self._id = 'liquid_rate'
class LiftGasRate(RateVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._menu_label = 'Lift gas injection rate'
self._image = ico.lift_gas_rate_16x16
self._line_options = LineOptions(label=r'Lift Gas Rate', colour=np.array([219., 34., 211.]) / 255.)
self._plot_label = r'Lift Gas Injection Rate'
self._id = 'lift_gas_rate'
class GasInjectionRate(RateVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._menu_label = 'Gas injection rate'
self._image = ico.gas_injection_rate_16x16
self._line_options = LineOptions(label=r'Gas Inj. Rate', colour=np.array([255., 0., 0.]) / 255.)
self._plot_label = r'Gas Injection Rate'
self._id = 'gas_injection_rate'
class WaterInjectionRate(RateVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._menu_label = 'Water injection rate'
self._image = ico.water_injection_rate_16x16
self._line_options = LineOptions(label=r'Water Inj. Rate', colour=np.array([91., 155., 213.]) / 255.)
self._plot_label = r'Water Injection Rate'
self._id = 'water_injection_rate'
class TotalGasRate(RateVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._menu_label = 'Total gas production rate'
self._image = ico.total_gas_rate_16x16
self._line_options = LineOptions(label=r'Total Gas Rate', colour=np.array([218., 119., 6.]) / 255.)
self._plot_label = r'Total Gas Production Rate'
self._id = 'total_gas_rate'
# ======================================================================================================================
# Cumulative Production Variables
# ======================================================================================================================
class CumulativeVariable(Variable):
def __init__(self):
super().__init__()
self._limits = (0., None)
self._type = 'cumulatives'
self._type_id = ID_CUMULATIVE
class OilCumulative(CumulativeVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidVolumeUnit(unit_system)
self._menu_label = 'Cumulative oil production'
self._image = ico.oil_cum_16x16
self._line_options = LineOptions(label=r'Oil Cum.', colour=np.array([0., 134., 61.]) / 255.)
self._plot_label = r'Cumulative Oil Production'
self._id = 'oil_cumulative'
class GasCumulative(CumulativeVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasVolumeUnit(unit_system)
self._menu_label = 'Cumulative gas production'
self._image = ico.gas_cum_16x16
self._line_options = LineOptions(label=r'Gas Cum.', colour=np.array([192., 0., 0.]) / 255.)
self._plot_label = r'Cumulative Gas Production'
self._id = 'gas_cumulative'
class WaterCumulative(CumulativeVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidVolumeUnit(unit_system)
self._menu_label = 'Cumulative water production'
self._image = ico.water_cum_16x16
self._line_options = LineOptions(label=r'Water Cum.', colour=np.array([51., 126., 195.]) / 255.)
self._plot_label = r'Cumulative Water Production'
self._id = 'water_cumulative'
class LiquidCumulative(CumulativeVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = LiquidVolumeUnit(unit_system)
self._menu_label = 'Cumulative liquid production'
self._image = ico.liquid_cum_16x16
self._line_options = LineOptions(label=r'Liquid Cum.', colour=np.array([51., 63., 79.]) / 255.)
self._plot_label = r'Cumulative Liquid Production'
self._id = 'liquid_cumulative'
class LiftGasCumulative(CumulativeVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = GasVolumeUnit(unit_system)
self._menu_label = 'Cumulative lift gas injection'
self._image = ico.lift_gas_cum_16x16
self._line_options = LineOptions(label=r'Lift Gas Cum.', colour=np.array([153., 0., 153.]) / 255.)
self._plot_label = r'Cumulative Lift Gas Injection'
self._id = 'lift_gas_cumulative'
class GasInjectionCumulative(CumulativeVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = GasVolumeUnit(unit_system)
self._menu_label = 'Cumulative gas injection'
self._image = ico.gas_injection_cum_16x16
self._line_options = LineOptions(label=r'Gas Inj. Cum.', colour=np.array([192., 0., 0.]) / 255.)
self._plot_label = r'Cumulative Gas Injection'
self._id = 'gas_injection_cumulative'
class WaterInjectionCumulative(CumulativeVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = LiquidVolumeUnit(unit_system)
self._menu_label = 'Cumulative Water injection'
self._image = ico.water_injection_cum_16x16
self._line_options = LineOptions(label=r'Water Inj. Cum.', colour=np.array([51., 126., 195.]) / 255.)
self._plot_label = r'Cumulative Water Injection'
self._id = 'water_injection_cumulative'
class TotalGasCumulative(CumulativeVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = GasVolumeUnit(unit_system)
self._menu_label = 'Cumulative total gas production'
self._image = ico.total_gas_cum_16x16
self._line_options = LineOptions(label=r'Total Gas Cum.', colour=np.array([218., 119., 6.]) / 255.)
self._plot_label = r'Cumulative Total Gas Production'
self._id = 'total_gas_cumulative'
# ======================================================================================================================
# Ratio Variables
# ======================================================================================================================
class FractionVariable(Variable):
def __init__(self):
super().__init__()
self._limits = (0., 1.)
self._type = 'ratios'
self._type_id = ID_RATIO
class RatioVariable(Variable):
def __init__(self):
super().__init__()
self._limits = (0., None)
self._type = 'ratios'
self._type_id = ID_RATIO
class WaterCut(FractionVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidLiquidRatioUnit(unit_system)
self._menu_label = 'Water-cut'
self._image = ico.water_cut_16x16
self._line_options = LineOptions(label=r'Water-cut', colour=np.array([91., 155., 213.]) / 255.)
self._fitted_options = FittedDataOptions(colour=np.array([217., 83., 25.]) / 255.) # TODO: NOT USED
self._plot_label = r'Water-cut'
self._id = 'water_cut'
class OilCut(FractionVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidLiquidRatioUnit(unit_system)
self._menu_label = 'Oil-cut'
self._image = ico.oil_cut_16x16
self._line_options = LineOptions(label=r'Oil-cut', colour=np.array([0., 176., 80.]) / 255.)
self._fitted_options = FittedDataOptions(colour=np.array([255., 0., 0.]) / 255.)
self._plot_label = r'Oil-cut'
self._id = 'oil_cut'
class GasOilRatio(RatioVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasLiquidRatioUnit(unit_system)
self._menu_label = 'Gas-oil ratio'
self._image = ico.gas_oil_ratio_16x16
self._line_options = LineOptions(label=r'GOR', colour=np.array([255., 0., 0.]) / 255.)
self._fitted_options = FittedDataOptions(colour=np.array([122., 48., 160.]) / 255.)
self._plot_label = r'Gas-Oil Ratio'
self._id = 'gas_oil_ratio'
class WaterOilRatio(RatioVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidLiquidRatioUnit(unit_system)
self._menu_label = 'Water-oil ratio'
self._image = ico.water_oil_ratio_16x16
self._line_options = LineOptions(label=r'WOR', colour=np.array([91., 155., 213.]) / 255.)
self._plot_label = r'Water-Oil Ratio'
self._id = 'water_oil_ratio'
class GasLiquidRatio(RatioVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasLiquidRatioUnit(unit_system)
self._menu_label = 'Gas-liquid ratio'
self._image = ico.gas_liquid_ratio_16x16
self._line_options = LineOptions(label=r'GLR', colour=np.array([255., 0., 0.]) / 255.)
self._plot_label = r'Gas-Liquid Ratio'
self._id = 'gas_liquid_ratio'
class WaterGasRatio(RatioVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidGasRatioUnit(unit_system)
self._menu_label = 'Water-gas ratio'
self._image = ico.water_gas_ratio_16x16
self._line_options = LineOptions(label=r'WGR', colour=np.array([91., 155., 213.]) / 255.)
self._plot_label = r'Water-Gas Ratio'
self._id = 'water_gas_ratio'
class OilGasRatio(RatioVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidGasRatioUnit(unit_system)
self._menu_label = 'Oil-gas ratio'
self._image = ico.oil_gas_ratio_16x16
self._line_options = LineOptions(label=r'WGR', colour=np.array([0., 176., 80.]) / 255.)
self._plot_label = r'Oil-Gas Ratio'
self._id = 'oil_gas_ratio'
class TotalGasLiquidRatio(RatioVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasLiquidRatioUnit(unit_system)
self._menu_label = 'Total gas-liquid ratio'
self._image = ico.total_gas_liquid_ratio_16x16
self._line_options = LineOptions(label=r'TGLR', colour=np.array([218., 119., 6.]) / 255.)
self._plot_label = r'Total Gas-Liquid Ratio'
self._id = 'total_gas_liquid_ratio'
# ======================================================================================================================
# Uptime Variables
# ======================================================================================================================
class UptimeVariable(Variable):
def __init__(self):
super().__init__()
self._limits = (0., 1.)
self._type = 'uptimes'
self._type_id = ID_UPTIME
class ProductionUptime(UptimeVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = FractionUnit()
self._menu_label = 'Production uptime'
self._image = ico.uptime_16x16
self._line_options = LineOptions(label=r'Prod. uptime', colour=np.array([255., 217., 102.]) / 255.)
self._plot_label = r'Production Uptime'
self._id = 'production_uptime'
class LiftGasUptime(UptimeVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = FractionUnit()
self._menu_label = 'Lift gas uptime'
self._image = ico.uptime_16x16
self._line_options = LineOptions(label=r'Lift gas uptime', colour=np.array([255., 217., 102.]) / 255.)
self._plot_label = r'Lift Gas Uptime'
self._id = 'lift_gas_uptime'
class GasInjectionUptime(UptimeVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = FractionUnit()
self._menu_label = 'Gas inj. uptime'
self._image = ico.uptime_16x16
self._line_options = LineOptions(label=r'Gas inj. uptime', colour=np.array([255., 217., 102.]) / 255.)
self._plot_label = r'Gas Injection Uptime'
self._id = 'gas_injection_uptime'
class WaterInjectionUptime(UptimeVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = FractionUnit()
self._menu_label = 'Water inj. uptime'
self._image = ico.uptime_16x16
self._line_options = LineOptions(label=r'Water inj. uptime', colour=np.array([255., 217., 102.]) / 255.)
self._plot_label = r'Water Injection Uptime'
self._id = 'water_injection_uptime'
# ======================================================================================================================
# Summary variables (for use on frames)
# ======================================================================================================================
class SummaryFunction(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Function'
self._choices = ('Point', 'Sum', 'Average')
self._choice_images = (ico.specific_point_16x16, ico.specific_point_16x16, ico.specific_point_16x16)
self._pytype = tuple
self._tooltip = 'Function that reduces a temporal production profile to a scalar.'
class SummaryPoint(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Point'
self._choices = ('First', 'Last', 'Date', 'Time')
self._choice_images = (ico.first_point_16x16, ico.last_point_16x16, ico.dates_16x16, ico.time_16x16)
self._pytype = tuple
self._tooltip = 'The specific summary point of the production profile.'
class SummaryPointDate(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Date'
self._pytype = date
self._tooltip = 'Date at which to extract summary point.'
class SummaryPointTime(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = 'years'
self._frame_label = 'Time'
self._pytype = float
self._tooltip = 'Time at which to extract summary point.'
class SummaryIcon(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Icon'
self._choices = ('Oil rate', 'Gas rate', 'Water rate', 'Liquid rate', 'Lift gas rate', 'Gas injection rate',
'Water injection rate', 'Total gas rate', 'Oil cumulative', 'Gas cumulative',
'Water cumulative', 'Liquid cumulative', 'Lift gas cumulative', 'Gas injection cumulative',
'Water injection cumulative', 'Total gas cumulative', 'Length', 'HCFT', 'HCPV', 'Permeability')
self._choice_images = (ico.oil_rate_16x16, ico.gas_rate_16x16, ico.water_rate_16x16,
ico.liquid_rate_16x16, ico.lift_gas_rate_16x16, ico.gas_injection_rate_16x16,
ico.water_injection_rate_16x16, ico.total_gas_rate_16x16,
ico.oil_cum_16x16, ico.gas_cum_16x16, ico.water_cum_16x16,
ico.liquid_cum_16x16, ico.lift_gas_cum_16x16, ico.gas_injection_cum_16x16,
ico.water_injection_cum_16x16, ico.total_gas_cum_16x16,
ico.completion_16x16, ico.HCFT_16x16, ico.HCPV_16x16, ico.permeability_16x16)
self._client_data_map = {i: bitmap for i, bitmap in enumerate(self._choice_images)}
self._pytype = tuple
class HistogramFrequency(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = AmountUnit()
self._plot_label = 'Frequency'
self._legend = 'Frequency'
self._limits = (0., None)
# ======================================================================================================================
# Concession Variables
# ======================================================================================================================
class License(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'License'
self._pytype = date
self._type = 'concessions'
self._id = 'license'
# ======================================================================================================================
# Plateau Variables
# ======================================================================================================================
class PlateauVariable(Variable):
def __init__(self):
super().__init__()
self._limits = (0., None)
self._round_off = 1
self._pytype = float
self._type = 'plateaus'
class TargetOilPlateau(PlateauVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._frame_label = 'Target oil'
self._menu_label = 'Target oil plateau'
self._image = ico.well_spacing_16x16
self._plot_label = r'Target Oil Plateau'
self._legend = r'Oil Plateau'
self._tooltip = 'Target oil plateau used as constraint in prediction.'
self._id = 'target_oil_plateau'
class TargetGasPlateau(PlateauVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._frame_label = 'Target gas'
self._menu_label = 'Target gas plateau'
self._image = ico.well_spacing_16x16
self._plot_label = r'Target Gas Plateau'
self._legend = r'Gas Plateau'
self._tooltip = 'Target gas plateau used as constraint in prediction.'
self._id = 'target_gas_plateau'
# ======================================================================================================================
# Well Variables
# ======================================================================================================================
class ProductionPhase(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Primary phase'
self._choices = ('Oil', 'Gas')
self._pytype = Index
class InjectionPhase(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Injected phase'
self._choices = ('Water', 'Gas', 'WAG')
self._pytype = Index
class DevelopmentLayout(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Layout'
self._image = ico.well_pair_2_16x16
self._choices = (None, 'Line-drive', 'Radial', '5-spot')
self._choice_images = (None, ico.well_pair_2_16x16, ico.radial_pattern_16x16, ico.five_spot_16x16)
self._tooltip = 'Scaling of well spacing is only done on\n' \
'wells/analogues with similar development scheme.'
self._pytype = tuple
class WellSpacing(Variable):
def __init__(self, unit_system):
super().__init__()
self._unit = LengthUnit(unit_system)
self._frame_label = 'Spacing'
self._menu_label = 'Well spacing'
self._image = ico.well_spacing_16x16
self._limits = (0., None)
self._plot_label = r'Well Spacing'
self._legend = r'Spacing'
self._tooltip = 'Used to scale the rate and cumulative production\n' \
'based on the ratio between the spacing of the\n' \
'producer and an analogue.'
self._pytype = int
self._type = 'well_spacing'
self._id = 'spacing'
class History(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Import'
self._pytype = tuple
self._tooltip = 'Profile of historical data:\n' \
'- Browse: Import profile from external file.'
class HistoryFit(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Import'
self._pytype = tuple
self._tooltip = 'Profile of historical data:\n' \
'- Browse: Import profile from external file\n' \
'- Window: Fit models to historical data for use in prediction.'
class Cultural(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Import'
self._pytype = tuple
self._tooltip = 'Cultural of the entity:\n' \
'- Field, Block, Reservoir, Theme, Polygon: 2D outline (x, y)\n' \
'- Pipeline: 2D trajectory (x, y)\n' \
'- Platform, Processor: Point (x, y)\n' \
'- Producer, Injector, Analogue: 3D trajectory (x, y, z)'
class Prediction(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Prediction'
self._choices = ('Low', 'Mid', 'High')
self._choice_images = (ico.low_chart_16x16, ico.mid_chart_16x16, ico.high_chart_16x16)
self._pytype = tuple
class ProbabilityOfOccurrence(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = PercentageUnit()
self._frame_label = 'Occurrence'
self._limits = (0., 100.)
self._round_off = 1
self._pytype = float
self._tooltip = 'Probability of the currently selected prediction\n' \
'to be sampled during uncertainty modelling'
# ======================================================================================================================
# Pointer Variables
# ======================================================================================================================
class Analogue(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Analogue'
self._pytype = Pointer
self._tooltip = 'Analogue from which to historical data:\n' \
'- Arrow: Insert Analogue from menu\n' \
'- Window: Create function based on models\n' \
' fitted to historical data.'
class Typecurve(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Typecurve'
self._pytype = Pointer
self._tooltip = 'Profile used for prediction:\n' \
'- Arrow: Insert Typecurve from menu\n' \
'- Browse: Import profile from external file\n' \
'- Window: Create function based on models\n' \
' fitted to historical data.'
class Scaling(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Scaling'
self._pytype = Pointer
self._tooltip = 'Scaling evaluation used for transforming\n' \
'static parameters to scalers:\n' \
'- Arrow: Insert Scaling from menu.'
class Scenario(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Scenario'
self._pytype = Pointer
self._tooltip = 'Scenario from which to gather entities, events and dates:\n' \
'- Arrow: Insert Scenario from menu.'
class HistorySimulation(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'History'
self._pytype = Pointer
self._tooltip = 'History simulation to carry into prediction:\n' \
'- Arrow: Insert History from menu.'
# ======================================================================================================================
# Fluid Variables
# ======================================================================================================================
class FluidVariable(Variable):
def __init__(self):
super().__init__()
self._limits = (0., None)
self._round_off = 2
self._pytype = float
class ReservoirFluidVariable(FluidVariable):
def __init__(self):
super().__init__()
self._type = 'res_fluids'
class InjectionFluidVariable(FluidVariable):
def __init__(self):
super().__init__()
self._type = 'inj_fluids'
class OilFVF(ReservoirFluidVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidVolumeRatio(unit_system)
self._frame_label = 'Bo'
self._menu_label = 'Oil FVF'
self._image = ico.Bo_16x16
self._plot_label = r'Oil FVF, $b_o$'
self._legend = r'$b_o$'
self._tooltip = 'Oil formation volume factor.'
self._id = 'bo'
class GasFVF(ReservoirFluidVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasVolumeRatio(unit_system)
self._frame_label = 'Bg'
self._menu_label = 'Gas FVF'
self._image = ico.Bg_16x16
self._plot_label = r'Gas FVF, $b_g$'
self._legend = r'$b_g$'
self._tooltip = 'Gas formation volume factor.'
self._id = 'bg'
class WaterFVF(ReservoirFluidVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidVolumeRatio(unit_system)
self._frame_label = 'Bw'
self._menu_label = 'Water FVF'
self._image = ico.Bw_16x16
self._plot_label = r'Water FVF, $b_w$'
self._legend = r'$b_w$'
self._tooltip = 'Water formation volume factor.'
self._id = 'bw'
class SolutionGasOilRatio(ReservoirFluidVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasLiquidRatioUnit(unit_system)
self._frame_label = 'Rs'
self._menu_label = 'Solution GOR'
self._image = ico.Rs_16x16
self._plot_label = r'Solution Gas-Oil Ratio, $R_s$'
self._legend = r'$R_s$'
self._tooltip = 'Solution gas-oil-ratio.'
self._id = 'rs'
class InjectionGasFVF(InjectionFluidVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasVolumeRatio(unit_system)
self._frame_label = 'Bg inj.'
self._menu_label = 'Gas inj. FVF'
self._image = ico.Bg_inj_16x16
self._plot_label = r'Injection Gas FVF, $b_{g,inj}$'
self._legend = r'$b_{g,inj}$'
self._tooltip = 'Injection gas formation volume factor.'
self._id = 'bg_inj'
class InjectionWaterFVF(InjectionFluidVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidVolumeRatio(unit_system)
self._frame_label = 'Bw inj.'
self._menu_label = 'Water inj. FVF'
self._image = ico.Bw_inj_16x16
self._plot_label = r'Injection Water FVF, $b_{w,inj}$'
self._legend = r'$b_{w,inj}$'
self._tooltip = 'Injection water formation volume factor.'
self._id = 'bw_inj'
# ======================================================================================================================
# Stakes Variables
# ======================================================================================================================
class Maturity(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = Unitless()
self._frame_label = 'Maturity'
self._menu_label = 'Maturity'
self._image = ico.oil_cum_16x16 # TODO: Draw icon
self._limits = (.5, 1.5)
self._plot_label = r'Maturity'
self._legend = r'Maturity'
self._round_off = 2
self._pytype = float
self._tooltip = 'Maturity index between 0.5 to 1.5,\n' \
'low values indicate low maturity and vice versa.'
self._type = 'risking'
self._id = 'maturity'
class ProbabilityOfSuccess(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = PercentageUnit()
self._frame_label = 'PoS'
self._menu_label = 'Probability of success'
self._image = ico.binary_distribution_16x16
self._limits = (0., 100.)
self._plot_label = r'Probability of Success, PoS'
self._legend = r'PoS'
self._round_off = 2
self._pytype = float
self._tooltip = 'Probability of Success is used to include or\n' \
'exclude a well during uncertainty modelling.\n' \
'Weighted average shown for subsurface items.'
self._type = 'risking'
self._id = 'pos'
class STOIIP(Variable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidVolumeUnit(unit_system)
self._frame_label = 'STOIIP'
self._menu_label = 'STOIIP'
self._image = ico.stoiip_16x16
self._limits = (0., None)
self._plot_label = r'STOIIP'
self._legend = r'STOIIP'
self._pytype = int
self._tooltip = 'Stock tank oil initially in place.'
self._type = 'volumes'
self._id = 'stoiip'
# ======================================================================================================================
# Constraint Variables
# ======================================================================================================================
class ConstraintVariable(Variable):
def __init__(self):
super().__init__()
self._limits = (0., None)
self._round_off = 2
self._pytype = float
self._type = 'constraints'
class OilConstraint(ConstraintVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._frame_label = 'Oil flow'
self._menu_label = 'Oil flow con.'
self._image = ico.oil_flow_constraint_16x16
self._plot_label = r'Oil Flow Constraint, $Q_{o,max}$'
self._legend = r'Oil Con.'
self._tooltip = 'Oil flow constraint.'
self._id = 'oil_constraint'
class GasConstraint(ConstraintVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._frame_label = 'Gas flow'
self._menu_label = 'Gas flow con.'
self._image = ico.gas_flow_constraint_16x16
self._plot_label = r'Gas Flow Constraint, $Q_{g,max}$'
self._legend = r'Gas Con.'
self._tooltip = 'Gas flow constraint.'
self._id = 'gas_constraint'
class WaterConstraint(ConstraintVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._frame_label = 'Water flow'
self._menu_label = 'Water flow con.'
self._image = ico.water_flow_constraint_16x16
self._plot_label = r'Water Flow Constraint, $Q_{w,max}$'
self._legend = r'Water Con.'
self._tooltip = 'Water flow constraint.'
self._id = 'water_constraint'
class LiquidConstraint(ConstraintVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._frame_label = 'Liquid flow'
self._menu_label = 'liquid flow con.'
self._image = ico.liquid_flow_constraint_16x16
self._plot_label = r'Liquid Flow Constraint, $Q_{l,max}$'
self._legend = r'Liquid Con.'
self._tooltip = 'Liquid flow constraint.'
self._id = 'liquid_constraint'
class InjectionGasConstraint(ConstraintVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._frame_label = 'Gas-inj. rate'
self._menu_label = 'Gas-inj. con.'
self._image = ico.gas_injection_constraint_16x16
self._plot_label = r'Gas-Injection Constraint, $Q_{g,inj,max}$'
self._legend = r'Gas-Inj. Con.'
self._tooltip = 'Injection gas constraint.'
self._id = 'gas_inj_constraint'
class InjectionWaterConstraint(ConstraintVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._frame_label = 'Water-inj. rate'
self._menu_label = 'Water-inj. con.'
self._image = ico.water_injection_constraint_16x16
self._plot_label = r'Water-Injection Constraint, $Q_{w,inj,max}$'
self._legend = r'Water-Inj. Con.'
self._tooltip = 'Injection water constraint.'
self._id = 'water_inj_constraint'
class LiftGasConstraint(ConstraintVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._frame_label = 'Gas-lift rate'
self._menu_label = 'Gas-lift con.'
self._image = ico.lift_gas_constraint_16x16
self._plot_label = r'Gas-Lift Constraint, $Q_{g,lift,max}$'
self._legend = r'Gas-Lift Con.'
self._tooltip = 'Lift-gas constraint.'
self._id = 'lift_gas_constraint'
# ======================================================================================================================
# Out-flowing Phase Variables
# ======================================================================================================================
class OilInflow(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Oil'
self._pytype = bool
self._tooltip = 'Oil is fed in from the previous node.'
class GasInflow(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Gas'
self._pytype = bool
self._tooltip = 'Gas is fed in from the previous node.\n' \
'This is the total gas, i.e. gas from\n' \
'the reservoir and lift-gas.'
class WaterInflow(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Water'
self._pytype = bool
self._tooltip = 'Water is fed in from the previous node.'
class InjectionGasInflow(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Injection Gas'
self._pytype = bool
self._tooltip = 'Injection gas is fed in from the previous node.'
class InjectionWaterInflow(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Injection Water'
self._pytype = bool
self._tooltip = 'Injection water is fed in from the previous node.'
# ======================================================================================================================
# Flow Split Variables
# ======================================================================================================================
class SplitType(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Split type'
self._choices = ('', 'Fixed', 'Multiphasic spill-over', 'Monophasic spill-over', 'Production to injection')
self._choice_images = (None, ico.oil_cum_16x16, ico.fluids_16x16, ico.liquid_cum_16x16, ico.fluids_injection_16x16)
self._tooltip = 'Defines the split-type used in determining\n' \
'how the phases are split.\n' \
'- Fixed: Sends phases to the two nodes based on the fractions given below.\n' \
'- Multiphasic:...'
self._pytype = tuple
class OilSplit(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = Unitless()
self._frame_label = 'Oil split'
self._limits = (0., 1.)
self._round_off = 2
self._pytype = float
self._tooltip = 'Oil split. Fraction goes to step-parent,\n' \
'1-fraction goes to parent.'
class GasSplit(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = Unitless()
self._frame_label = 'Gas split'
self._limits = (0., 1.)
self._round_off = 2
self._pytype = float
self._tooltip = 'Gas split. Fraction goes to step-parent,\n' \
'1-fraction goes to parent.'
class WaterSplit(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = Unitless()
self._frame_label = 'Water split'
self._limits = (0., 1.)
self._round_off = 2
self._pytype = float
self._tooltip = 'Water split. Fraction goes to step-parent,\n' \
'1-fraction goes to parent.'
class LiftGasSplit(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = Unitless()
self._frame_label = 'Lift-gas split'
self._limits = (0., 1.)
self._round_off = 2
self._pytype = float
self._tooltip = 'Lift-gas split. Fraction goes to step-parent,\n' \
'1-fraction goes to parent.'
class InjectionGasSplit(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = Unitless()
self._frame_label = 'Injection gas split'
self._limits = (0., 1.)
self._round_off = 2
self._pytype = float
self._tooltip = 'Injection gas split. Fraction goes to step-parent,\n' \
'1-fraction goes to parent.'
class InjectionWaterSplit(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = Unitless()
self._frame_label = 'Injection water split'
self._limits = (0., 1.)
self._round_off = 2
self._pytype = float
self._tooltip = 'Injection water split. Fraction goes to step-parent,\n' \
'1-fraction goes to parent.'
# ======================================================================================================================
# Surface Variables
# ======================================================================================================================
class FacilityVariable(Variable):
def __init__(self):
super().__init__()
self._limits = (0., None)
self._type = 'facilities'
class TargetGasLiquidRatio(FacilityVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = GasLiquidRatioUnit(unit_system)
self._frame_label = 'Target TGLR'
self._menu_label = 'Target gas-liquid ratio'
self._image = ico.total_gas_liquid_ratio_16x16
self._plot_label = r'Target Gas-Liquid Rate'
self._legend = r'Target TGLR.'
self._round_off = 2
self._pytype = float
self._tooltip = 'Target total gas-liquid-ration used for\n' \
'calculating lift-gas requirements.'
self._id = 'tglr'
class Availability(FacilityVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = FractionUnit()
self._frame_label = 'Availability'
self._menu_label = 'Availability'
self._image = ico.average_uptime_16x16
self._plot_label = r'Availability'
self._legend = r'Availability'
self._round_off = 3
self._pytype = float
self._tooltip = 'Availability applied to production rates and constraints.\n' \
'Individual entity availability not used in simulation, but\n' \
'kept for export to Phaser. Availability listed in History and Prediction is used\n' \
'as an over-all system availability.'
self._id = 'availability'
class WAGCycleDuration(FacilityVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = TimeUnit('days')
self._frame_label = 'Cycle dur.'
self._menu_label = 'WAG cycle duration'
self._image = ico.wag_cycle_duration_16x16
self._plot_label = r'WAG Cycle Duration'
self._legend = r'WAG Cycle'
self._pytype = int
self._tooltip = 'Duration between each change-over from\n' \
'gas to water injection'
self._id = 'wag_cycle'
class WAGCycles(FacilityVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = AmountUnit()
self._frame_label = '# of cycles'
self._menu_label = 'WAG cycles'
self._image = ico.wag_cycles_16x16
self._plot_label = r'Number of WAG Cycles'
self._legend = r'WAG Cycles'
self._pytype = int
self._tooltip = 'Maximum number of change-overs from\n' \
'gas to water injection. Starting with\n' \
'gas and ending with water'
self._id = 'wag_cycles'
class TargetVoidageRatio(FacilityVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = ReservoirVolumeRatio(unit_system)
self._frame_label = 'Target ratio'
self._menu_label = 'Target voidage ratio'
self._image = ico.wag_voidage_replacement_16x16
self._plot_label = r'Target Voidage Replacement Ratio'
self._legend = r'Target Voidage Ratio'
self._round_off = 2
self._pytype = float
self._tooltip = 'Target voidage replacement ratio:\n' \
'- Spreadsheet: Assign proportion of injection\n' \
' going to each supported producer'
self._id = 'voidage'
class VoidageProportion(FacilityVariable):
# used exclusively on the VoidagePanel in PropertyPanels. TargetVoidageRatio handles menu and plotting
def __init__(self, unit_system):
super().__init__()
self._unit = ReservoirVolumeRatio(unit_system)
self._frame_label = 'Target ratio'
self._image = ico.spreadsheet_16x16
self._round_off = 2
self._pytype = float
class GasInjectionPotentialConstant(FacilityVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = GasFlowRateUnit(unit_system)
self._frame_label = 'Gas inj.'
self._menu_label = 'Constant gas inj.'
self._image = ico.gas_injection_rate_16x16
self._limits = (0., None)
self._plot_label = r'Constant gas injection'
self._legend = r'Con. gas inj.'
self._tooltip = 'Set to provide a constant gas injection potential\n' \
'for the well. If this is not set, the required\n' \
'potential will be calculated based on voidage replacement.'
self._pytype = float
self._round_of = 1
self._id = 'constant_gas_inj'
class WaterInjectionPotentialConstant(FacilityVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = LiquidFlowRateUnit(unit_system)
self._frame_label = 'Water inj.'
self._menu_label = 'Constant water inj.'
self._image = ico.water_injection_rate_16x16
self._limits = (0., None)
self._plot_label = r'Constant water injection'
self._legend = r'Con. water inj.'
self._tooltip = 'Set to provide a constant water injection potential\n' \
'for the well. If this is not set, the required\n' \
'potential will be calculated based on voidage replacement.'
self._pytype = float
self._round_of = 1
self._id = 'constant_water_inj'
# ======================================================================================================================
# Auxiliary Variables
# ======================================================================================================================
class Name(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Name'
self._pytype = str
self._id = 'name'
class ScalerEvaluation(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Evaluation'
self._image = ico.right_arrow_16x16
self._pytype = str
self._tooltip = 'Mathematical expression used to transform\n' \
'static parameters into scaling parameters.'
class SummaryEvaluation(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Multiplier'
self._image = ico.right_arrow_16x16
self._pytype = str
self._tooltip = 'Mathematical expression used to calculate\n' \
'multiplier to the production profile.'
class IncludeModel(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Include model'
self._pytype = bool
class MergeType(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Merge type'
self._choices = ('', 'Smooth', 'Conditional')
self._choice_images = (None, ico.merge_16x16, ico.merge_16x16)
self._pytype = tuple
class MergePoint(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None, None)
self._frame_label = (None, 'Merge at (x-axis)', 'Merge at (y-axis)')
self._round_off = 2
self._pytype = float
class MergeRate(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None, None)
self._frame_label = (None, 'Merge rate', None)
self._round_off = 5
self._pytype = float
class Multiplier(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Multiplier'
self._round_off = 1
self._pytype = float
class Addition(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Addition'
self._round_off = 1
self._pytype = float
class RunFrom(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Run from'
self._choices = (None, 'First point', 'Last point', 'Specific')
self._choice_images = (None, ico.first_point_16x16, ico.last_point_16x16, ico.specific_point_16x16)
self._pytype = tuple
class RunFromSpecific(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Axis'
self._choices = (None, 'x-axis', 'y-axis')
self._choice_images = (None, ico.x_axis_16x16, ico.y_axis_16x16)
self._pytype = tuple
class RunFromValue(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Value'
self._limits = (0., None)
self._round_off = 2
self._pytype = float
class RunTo(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Run to (x-axis)'
self._image = ico.run_16x16
self._round_off = 1
self._pytype = float
class Frequency(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Frequency'
self._choices = ('Yearly', 'Quarterly', 'Monthly', 'Delta')
self._choice_images = (ico.dates_year_16x16, ico.dates_quarter_16x16, ico.dates_16x16, ico.timestep_16x16)
self._pytype = tuple
class TimeDelta(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None, None, TimeUnit('days'))
self._frame_label = (None, None, None, 'Delta')
self._round_off = 1
self._pytype = float
self._tooltip = 'Number of days for each time-step.'
class TimeStep(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = TimeUnit('days')
self._frame_label = 'Time-step'
self._round_off = 1
self._pytype = float
self._tooltip = 'Number of days for each time-step.'
class SaveAllSamples(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Save all samples'
self._pytype = bool
self._tooltip = 'Save all the sampled runs. This allows for\n' \
'- Display distribution shading in Cartesian charts\n' \
'- Display Histograms of summary variables\n' \
'Saved file size is substantially larger.'
class SimulateConstrainted(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Simulate with constraints'
self._pytype = bool
self._tooltip = 'Simulate using voidage replacement\n' \
'assumptions and surface network constraints.\n' \
'Rates will be based on the choke position and\n' \
'potentials will become instantaneous potentials.'
class Samples(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = AmountUnit()
self._frame_label = '# of samples'
self._plot_label = 'Samples'
self._limits = (0., None)
self._pytype = int
self._tooltip = 'Number of stochastic samples to run.'
# ======================================================================================================================
# Scenario and Event Variables
# ======================================================================================================================
class StartDate(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Start'
self._pytype = date
self._tooltip = 'Start date of prediction'
class EndDate(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'End'
self._pytype = date
self._tooltip = 'End date of prediction'
class EventTrigger(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Trigger'
self._choices = ('Scenario', 'Date')
self._choice_images = (ico.scenario_16x16, ico.event_16x16)
self._pytype = tuple
class EventDate(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None)
self._frame_label = (None, 'Date')
self._pytype = date
class OffsetYears(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (TimeUnit('years'), None)
self._frame_label = ('Offset', None)
self._round_off = 2
self._pytype = float
# ======================================================================================================================
# Uncertainty Variables
# ======================================================================================================================
class UncertainValue(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Value'
self._round_off = 2
self._pytype = float
self._tooltip = 'Deterministic value used for sampling.'
class Distribution(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Distribution'
self._choices = ['', 'Swanson', 'Uniform', 'Triangular', 'Normal', 'Lognormal']
self._choice_images = (None, ico.swanson_distribution_16x16, ico.uniform_distribution_16x16,
ico.triangular_distribution_16x16, ico.normal_distribution_16x16,
ico.lognormal_distribution_16x16)
self._pytype = tuple
self._tooltip = 'Probability distribution used for sampling\n' \
'of the properties uncertainty space.'
class DistributionParameter1(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, '+/-%', '+/-%', '+/-%', '+/-%', '+/-%')
self._frame_label = (None, 'Min', 'Min', 'Min', 'Mean', 'Mean')
self._limits = (-100., None)
self._pytype = int
self._tooltip = 'Distribution parameters is calculated\n' \
'as +/- percentage of Value.'
class DistributionParameter2(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, '+/-%', '+/-%', '+/-%', '+% of mean', '+% of mean')
self._frame_label = (None, 'Mode', 'Max', 'Mode', 'St. dev.', 'St. dev.')
self._limits = (-100., None)
self._pytype = int
self._tooltip = 'Distribution parameters is calculated\n' \
'as +/- percentage of Value.'
class DistributionParameter3(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, '+/-%', None, '+/-%', None, None)
self._frame_label = (None, 'Max', None, 'Max', None, None)
self._limits = (-100., None)
self._pytype = int
self._tooltip = 'Distribution parameters is calculated\n' \
'as +/- percentage of Value.'
# ======================================================================================================================
# Analogue Function Variables
# ======================================================================================================================
class PlaceholderMethod(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Method'
self._choices = ('' * 5)
self._choice_images = (None,)
self._pytype = tuple
class PlaceholderInput(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None,)
self._frame_label = ('' * 5)
self._pytype = int
class PlaceholderParameter1(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None,)
self._frame_label = ('' * 5)
self._pytype = int
class PlaceholderParameter2(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None,)
self._frame_label = ('' * 5)
self._pytype = int
class PlaceholderParameter3(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None,)
self._frame_label = ('' * 5)
self._pytype = int
class HistoryMethod(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Method'
self._choices = ('History', 'Moving average')
self._choice_images = (ico.history_fit_16x16, ico.moving_average_fit_16x16)
self._pytype = tuple
class HistoryInput(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None)
self._frame_label = (None, 'n')
self._pytype = int
class HistoryParameter1(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None)
self._frame_label = (None, None)
self._pytype = int
class HistoryParameter2(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None)
self._frame_label = (None, None)
self._pytype = int
class HistoryParameter3(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None)
self._frame_label = (None, None)
self._pytype = int
class CurvefitMethod(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Method'
self._choices = ('Constant', 'Linear', 'Exponential', 'Power', 'Logarithmic')
self._choice_images = (ico.constant_fit_16x16, ico.linear_fit_16x16, ico.exponential_fit_16x16, ico.power_fit_16x16, ico.logarithmic_fit_16x16)
self._pytype = tuple
class CurvefitInput(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None, None, None, None)
self._frame_label = (None, None, None, None, None)
self._pytype = int
class CurvefitParameter1(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None, None, None, None)
self._frame_label = ('con.', 'a', 'a', 'a', 'a')
self._round_off = 3
self._pytype = float
class CurvefitParameter2(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None, None, None, None)
self._frame_label = (None, 'b', 'b', 'b', 'b')
self._round_off = 2
self._pytype = float
class CurvefitParameter3(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None, None, None, None)
self._frame_label = (None, None, 'c', 'c', None)
self._round_off = 2
self._pytype = float
class NonParametricMethod(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Method'
self._choices = ('Bow-wave',)
self._choice_images = (ico.bow_wave_16x16,)
self._pytype = tuple
class NonParametricInput(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None,)
self._frame_label = ('Mid',)
self._round_off = 2
self._pytype = float
class NonParametricParameter1(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None,)
self._frame_label = (None,)
self._pytype = int
class NonParametricParameter2(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None,)
self._frame_label = (None,)
self._pytype = int
class NonParametricParameter3(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None,)
self._frame_label = (None,)
self._pytype = int
class DCAMethod(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Method'
self._choices = ('Exponential', 'Hyperbolic', 'Harmonic')
self._choice_images = (ico.exponential_dca_16x16, ico.hyperbolic_dca_16x16, ico.harmonic_dca_16x16)
self._pytype = tuple
class DCAInput(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None, None)
self._frame_label = (None, 'b', None)
self._round_off = 2
self._pytype = float
class DCAParameter1(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None, None)
self._frame_label = ('q', 'q', 'q')
self._round_off = 2
self._pytype = float
class DCAParameter2(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None, None)
self._frame_label = ('D', 'D', 'D')
self._round_off = 5
self._pytype = float
class DCAParameter3(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = (None, None, None)
self._frame_label = (None, None, None)
self._pytype = int
# ======================================================================================================================
# Scaling Variables
# ======================================================================================================================
class ScalerVariable(Variable):
def __init__(self):
super().__init__()
self._limits = (0., None)
self._round_off = 2
self._pytype = float
self._type = 'scalers'
class CumulativeScaler(ScalerVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = Unitless()
self._frame_label = 'Cum'
self._menu_label = 'Cumulative'
self._image = ico.cum_scaler_16x16
self._plot_label = r'Cumulative Scaler, $S_{cum}$'
self._legend = r'$S_{cum}$'
self._id = 's_cum'
class RateScaler(ScalerVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = Unitless()
self._frame_label = 'Rate'
self._menu_label = 'Rate'
self._image = ico.rate_scaler_16x16
self._plot_label = r'Rate Scaler, $S_{rate}$'
self._legend = r'$S_{rate}$'
self._id = 's_rate'
class FFWScaler(ScalerVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = Unitless()
self._frame_label = 'FFW'
self._menu_label = 'FFW'
self._image = ico.ffw_scaler_16x16
self._plot_label = r'Fractional Flow of Water Scaler, $S_{ffw}$'
self._legend = r'$S_{ffw}$'
self._id = 's_ffw'
class FFGScaler(ScalerVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = Unitless()
self._frame_label = 'FFG'
self._menu_label = 'FFG'
self._image = ico.ffg_scaler_16x16
self._plot_label = r'Fractional Flow of Gas Scaler, $S_{ffg}$'
self._legend = r'$S_{ffg}$'
self._id = 's_ffg'
class OnsetScaler(ScalerVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = TimeUnit('years')
self._frame_label = 'Onset'
self._menu_label = 'Onset'
self._image = ico.time_16x16 # TODO: Draw icon
self._plot_label = r'Fractional Flow Onset, $\Delta$'
self._legend = r'Onset'
self._id = 'onset'
class InitialWCTScaler(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = PercentageUnit()
self._frame_label = 'Ini. WCT'
self._menu_label = 'Initial WCT'
self._image = ico.wct_ini_scaler_16x16
self._limits = (0., 100.)
self._plot_label = r'Initial Water-cut'
self._legend = r'Ini. WCT'
self._pytype = int
self._type = 'scalers'
self._id = 'wct_ini'
class ScalerSelection(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Scaler'
self._choices = ('Cumulative', 'Rate', 'FFW', 'FFG')
self._choice_images = (ico.cum_scaler_16x16, ico.rate_scaler_16x16, ico.ffw_scaler_16x16, ico.ffg_scaler_16x16)
self._pytype = tuple
# ======================================================================================================================
# Selection of possible static parameters used as input to scaling laws
# ======================================================================================================================
class StaticVariable(Variable):
def __init__(self):
super().__init__()
self._limits = (0., None)
self._round_off = 1
self._pytype = float
self._type = 'statics'
class CompletedLength(StaticVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = LengthUnit(unit_system)
self._frame_label = 'Well length'
self._menu_label = 'Well length'
self._image = ico.completion_16x16
self._plot_label = r'Well Length'
self._legend = r'Well length'
self._id = 'length'
class HydrocarbonFeet(StaticVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = AreaUnit(unit_system)
self._frame_label = 'HCFT'
self._menu_label = 'HCFT'
self._image = ico.HCFT_16x16
self._plot_label = r'HCFT'
self._legend = r'HCFT'
self._id = 'hcft'
class HydrocarbonPoreVolume(StaticVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = VolumeUnit(unit_system)
self._frame_label = 'HCPV'
self._menu_label = 'HCPV'
self._image = ico.HCPV_16x16
self._plot_label = r'HCPV'
self._legend = r'HCPV'
self._id = 'hcpv'
class Permeability(StaticVariable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = PermeabilityUnit()
self._frame_label = 'Permeability'
self._menu_label = 'Permeability'
self._image = ico.permeability_16x16
self._plot_label = r'Permeability'
self._legend = r'Permeability'
self._id = 'permeability'
class OilDensity(StaticVariable):
def __init__(self, unit_system):
super().__init__()
self._unit = DensityUnit(unit_system)
self._frame_label = 'Oil density'
self._menu_label = 'Oil density'
self._image = ico.stoiip_16x16
self._plot_label = r'Oil density, $\rho_o$'
self._legend = r'$\rho_o$'
self._id = 'oil_density'
# ======================================================================================================================
# Plot Option Variables
# ======================================================================================================================
class ShowData(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Show data'
self._choices = ('No', 'Yes')
self._choice_images = (None, ico.history_match_16x16)
self._pytype = tuple
class ShowUncertainty(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Show uncertainty'
self._choices = ('No', 'Yes')
self._choice_images = (ico.mid_chart_16x16, ico.prediction_16x16)
self._pytype = tuple
class SplitBy(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Split by'
self._choices = ('None', 'Entity', 'Simulation', 'Variable')
self._choice_images = (None, ico.folder_closed_16x16, ico.project_16x16, ico.grid_properties_16x16)
self._pytype = tuple
class GroupBy(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Group by'
self._choices = ('None', 'Unit')
self._choice_images = (None, None)
self._pytype = tuple
class ColourBy(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Colour by'
self._choices = ('None', 'Entity type') # TODO: Not yet correct
self._choice_images = (None, None)
self._pytype = tuple
# ======================================================================================================================
# Variable plotting option variables (used on frames)
# ======================================================================================================================
class VariableColour(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Colour'
self._tooltip = 'Select colour of line to display in cartesian charts.'
self._pytype = wx.Colour
class VariableDrawstyle(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Drawstyle'
self._choices = ('Default', 'Steps (pre)', 'Steps (mid)', 'Steps (post)')
self._choice_images = (None, None, None, None)
self._pytype = tuple
class VariableLinestyle(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Linestyle'
self._choices = ('Solid', 'Dashed', 'Dash-dot', 'Dotted')
self._choice_images = (None, None, None, None)
self._pytype = tuple
# ======================================================================================================================
# Settings variables
# ======================================================================================================================
class SettingsUnitSystem(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Unit system'
self._choices = ('Field', 'Metric')
self._choice_images = (None, None)
self._pytype = tuple
LINE_SIZES = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10')
TEXT_SIZES = ('6', '8', '10', '12', '14', '16', '18', '20', '22', '24')
TEXT_BITMAPS = (None, None, None, None, None, None, None, None, None, None)
class SettingsLinewidth(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Linewidth'
self._choices = LINE_SIZES
self._choice_images = (ico.linewidth_1_16x16, ico.linewidth_2_16x16, ico.linewidth_3_16x16,
ico.linewidth_4_16x16, ico.linewidth_5_16x16, ico.linewidth_6_16x16,
ico.linewidth_7_16x16, ico.linewidth_8_16x16, ico.linewidth_9_16x16,
ico.linewidth_10_16x16)
self._pytype = tuple
class SettingsMarkerSize(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Marker size'
self._choices = LINE_SIZES
self._choice_images = (ico.markersize_1_16x16, ico.markersize_2_16x16, ico.markersize_3_16x16,
ico.markersize_4_16x16, ico.markersize_5_16x16, ico.markersize_6_16x16,
ico.markersize_7_16x16, ico.markersize_8_16x16, ico.markersize_9_16x16,
ico.markersize_10_16x16)
self._pytype = tuple
class SettingsTickLabelSize(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Tick-label size'
self._choices = TEXT_SIZES
self._choice_images = TEXT_BITMAPS
self._pytype = tuple
class SettingsLabelSize(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Label size'
self._choices = TEXT_SIZES
self._choice_images = TEXT_BITMAPS
self._pytype = tuple
class SettingsLegendSize(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Legend size'
self._choices = TEXT_SIZES
self._choice_images = TEXT_BITMAPS
self._pytype = tuple
PERCENTILE_OPTIONS = ('P05', 'P10', 'P20', 'P25', 'P30', 'P40', 'P50', 'P60', 'P70', 'P75', 'P80', 'P90', 'P95')
PERCENTILE_BITMAPS = (None, None, None, None, None, None, None, None, None, None, None, None, None)
class SettingsLowCase(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Low case'
self._choices = PERCENTILE_OPTIONS
self._choice_images = PERCENTILE_BITMAPS
self._pytype = tuple
class SettingsMidCase(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Mid case'
self._choices = PERCENTILE_OPTIONS
self._choice_images = PERCENTILE_BITMAPS
self._pytype = tuple
class SettingsHighCase(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'High case'
self._choices = PERCENTILE_OPTIONS
self._choice_images = PERCENTILE_BITMAPS
self._pytype = tuple
class SettingsShadingResolution(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Resolution'
self._choices = ('2', '4', '6', '8', '10')
self._choice_images = (None, None, None, None, None)
self._pytype = tuple
class SettingsShadingLow(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Low bound'
self._choices = PERCENTILE_OPTIONS
self._choice_images = PERCENTILE_BITMAPS
self._pytype = tuple
class SettingsShadingHigh(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'High bound'
self._choices = PERCENTILE_OPTIONS
self._choice_images = PERCENTILE_BITMAPS
self._pytype = tuple
# ======================================================================================================================
# Duplicate variables
# ======================================================================================================================
class Duplicates(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._unit = AmountUnit()
self._frame_label = '# of duplicates'
self._pytype = int
self._tooltip = 'Number of duplicates to create.'
class DuplicateAsControlled(Variable):
def __init__(self, unit_system=None):
super().__init__()
self._frame_label = 'Duplicate as controlled'
self._pytype = bool
self._tooltip = 'Duplicated entities will only allow minor\n' \
'configuration. All properties will be determined\n' \
'by the controlling entity (the one duplicated).'
|
[
"utilities.wxdate2pydate",
"utilities.pydate2wxdate",
"numpy.array",
"properties.SummaryProperty",
"utilities.GetAttributes"
] |
[((6204, 6294), 'utilities.GetAttributes', 'GetAttributes', (['self'], {'exclude': "('_correlation_labels', '_correlation_matrix')", 'sort': '(True)'}), "(self, exclude=('_correlation_labels', '_correlation_matrix'),\n sort=True)\n", (6217, 6294), False, 'from utilities import pydate2wxdate, wxdate2pydate, GetAttributes\n'), ((6987, 7107), 'utilities.GetAttributes', 'GetAttributes', (['self'], {'exclude': "('_summaries', '_correlation_labels', '_correlation_matrix')", 'attr_only': '(True)', 'sort': '(True)'}), "(self, exclude=('_summaries', '_correlation_labels',\n '_correlation_matrix'), attr_only=True, sort=True)\n", (7000, 7107), False, 'from utilities import pydate2wxdate, wxdate2pydate, GetAttributes\n'), ((16442, 16459), 'properties.SummaryProperty', 'SummaryProperty', ([], {}), '()\n', (16457, 16459), False, 'from properties import SummaryProperty\n'), ((31450, 31478), 'numpy.array', 'np.array', (['[0.0, 176.0, 80.0]'], {}), '([0.0, 176.0, 80.0])\n', (31458, 31478), True, 'import numpy as np\n'), ((31922, 31949), 'numpy.array', 'np.array', (['[255.0, 0.0, 0.0]'], {}), '([255.0, 0.0, 0.0])\n', (31930, 31949), True, 'import numpy as np\n'), ((32404, 32434), 'numpy.array', 'np.array', (['[91.0, 155.0, 213.0]'], {}), '([91.0, 155.0, 213.0])\n', (32412, 32434), True, 'import numpy as np\n'), ((32897, 32927), 'numpy.array', 'np.array', (['[51.0, 102.0, 153.0]'], {}), '([51.0, 102.0, 153.0])\n', (32905, 32927), True, 'import numpy as np\n'), ((33006, 33033), 'numpy.array', 'np.array', (['[255.0, 0.0, 0.0]'], {}), '([255.0, 0.0, 0.0])\n', (33014, 33033), True, 'import numpy as np\n'), ((33485, 33515), 'numpy.array', 'np.array', (['[219.0, 34.0, 211.0]'], {}), '([219.0, 34.0, 211.0])\n', (33493, 33515), True, 'import numpy as np\n'), ((33991, 34018), 'numpy.array', 'np.array', (['[255.0, 0.0, 0.0]'], {}), '([255.0, 0.0, 0.0])\n', (33999, 34018), True, 'import numpy as np\n'), ((34505, 34535), 'numpy.array', 'np.array', (['[91.0, 155.0, 213.0]'], {}), '([91.0, 155.0, 213.0])\n', (34513, 34535), True, 'import numpy as np\n'), ((35015, 35044), 'numpy.array', 'np.array', (['[218.0, 119.0, 6.0]'], {}), '([218.0, 119.0, 6.0])\n', (35023, 35044), True, 'import numpy as np\n'), ((35949, 35977), 'numpy.array', 'np.array', (['[0.0, 176.0, 80.0]'], {}), '([0.0, 176.0, 80.0])\n', (35957, 35977), True, 'import numpy as np\n'), ((36380, 36407), 'numpy.array', 'np.array', (['[255.0, 0.0, 0.0]'], {}), '([255.0, 0.0, 0.0])\n', (36388, 36407), True, 'import numpy as np\n'), ((36821, 36851), 'numpy.array', 'np.array', (['[91.0, 155.0, 213.0]'], {}), '([91.0, 155.0, 213.0])\n', (36829, 36851), True, 'import numpy as np\n'), ((37273, 37303), 'numpy.array', 'np.array', (['[51.0, 102.0, 153.0]'], {}), '([51.0, 102.0, 153.0])\n', (37281, 37303), True, 'import numpy as np\n'), ((37730, 37760), 'numpy.array', 'np.array', (['[219.0, 34.0, 211.0]'], {}), '([219.0, 34.0, 211.0])\n', (37738, 37760), True, 'import numpy as np\n'), ((38195, 38222), 'numpy.array', 'np.array', (['[255.0, 0.0, 0.0]'], {}), '([255.0, 0.0, 0.0])\n', (38203, 38222), True, 'import numpy as np\n'), ((38668, 38698), 'numpy.array', 'np.array', (['[91.0, 155.0, 213.0]'], {}), '([91.0, 155.0, 213.0])\n', (38676, 38698), True, 'import numpy as np\n'), ((39137, 39166), 'numpy.array', 'np.array', (['[218.0, 119.0, 6.0]'], {}), '([218.0, 119.0, 6.0])\n', (39145, 39166), True, 'import numpy as np\n'), ((40084, 40112), 'numpy.array', 'np.array', (['[0.0, 134.0, 61.0]'], {}), '([0.0, 134.0, 61.0])\n', (40092, 40112), True, 'import numpy as np\n'), ((40542, 40569), 'numpy.array', 'np.array', (['[192.0, 0.0, 0.0]'], {}), '([192.0, 0.0, 0.0])\n', (40550, 40569), True, 'import numpy as np\n'), ((41010, 41040), 'numpy.array', 'np.array', (['[51.0, 126.0, 195.0]'], {}), '([51.0, 126.0, 195.0])\n', (41018, 41040), True, 'import numpy as np\n'), ((41494, 41522), 'numpy.array', 'np.array', (['[51.0, 63.0, 79.0]'], {}), '([51.0, 63.0, 79.0])\n', (41502, 41522), True, 'import numpy as np\n'), ((41981, 42010), 'numpy.array', 'np.array', (['[153.0, 0.0, 153.0]'], {}), '([153.0, 0.0, 153.0])\n', (41989, 42010), True, 'import numpy as np\n'), ((42477, 42504), 'numpy.array', 'np.array', (['[192.0, 0.0, 0.0]'], {}), '([192.0, 0.0, 0.0])\n', (42485, 42504), True, 'import numpy as np\n'), ((42982, 43012), 'numpy.array', 'np.array', (['[51.0, 126.0, 195.0]'], {}), '([51.0, 126.0, 195.0])\n', (42990, 43012), True, 'import numpy as np\n'), ((43483, 43512), 'numpy.array', 'np.array', (['[218.0, 119.0, 6.0]'], {}), '([218.0, 119.0, 6.0])\n', (43491, 43512), True, 'import numpy as np\n'), ((44588, 44618), 'numpy.array', 'np.array', (['[91.0, 155.0, 213.0]'], {}), '([91.0, 155.0, 213.0])\n', (44596, 44618), True, 'import numpy as np\n'), ((44681, 44710), 'numpy.array', 'np.array', (['[217.0, 83.0, 25.0]'], {}), '([217.0, 83.0, 25.0])\n', (44689, 44710), True, 'import numpy as np\n'), ((45117, 45145), 'numpy.array', 'np.array', (['[0.0, 176.0, 80.0]'], {}), '([0.0, 176.0, 80.0])\n', (45125, 45145), True, 'import numpy as np\n'), ((45208, 45235), 'numpy.array', 'np.array', (['[255.0, 0.0, 0.0]'], {}), '([255.0, 0.0, 0.0])\n', (45216, 45235), True, 'import numpy as np\n'), ((45627, 45654), 'numpy.array', 'np.array', (['[255.0, 0.0, 0.0]'], {}), '([255.0, 0.0, 0.0])\n', (45635, 45654), True, 'import numpy as np\n'), ((45717, 45747), 'numpy.array', 'np.array', (['[122.0, 48.0, 160.0]'], {}), '([122.0, 48.0, 160.0])\n', (45725, 45747), True, 'import numpy as np\n'), ((46160, 46190), 'numpy.array', 'np.array', (['[91.0, 155.0, 213.0]'], {}), '([91.0, 155.0, 213.0])\n', (46168, 46190), True, 'import numpy as np\n'), ((46607, 46634), 'numpy.array', 'np.array', (['[255.0, 0.0, 0.0]'], {}), '([255.0, 0.0, 0.0])\n', (46615, 46634), True, 'import numpy as np\n'), ((47050, 47080), 'numpy.array', 'np.array', (['[91.0, 155.0, 213.0]'], {}), '([91.0, 155.0, 213.0])\n', (47058, 47080), True, 'import numpy as np\n'), ((47488, 47516), 'numpy.array', 'np.array', (['[0.0, 176.0, 80.0]'], {}), '([0.0, 176.0, 80.0])\n', (47496, 47516), True, 'import numpy as np\n'), ((47947, 47976), 'numpy.array', 'np.array', (['[218.0, 119.0, 6.0]'], {}), '([218.0, 119.0, 6.0])\n', (47955, 47976), True, 'import numpy as np\n'), ((48854, 48885), 'numpy.array', 'np.array', (['[255.0, 217.0, 102.0]'], {}), '([255.0, 217.0, 102.0])\n', (48862, 48885), True, 'import numpy as np\n'), ((49295, 49326), 'numpy.array', 'np.array', (['[255.0, 217.0, 102.0]'], {}), '([255.0, 217.0, 102.0])\n', (49303, 49326), True, 'import numpy as np\n'), ((49737, 49768), 'numpy.array', 'np.array', (['[255.0, 217.0, 102.0]'], {}), '([255.0, 217.0, 102.0])\n', (49745, 49768), True, 'import numpy as np\n'), ((50195, 50226), 'numpy.array', 'np.array', (['[255.0, 217.0, 102.0]'], {}), '([255.0, 217.0, 102.0])\n', (50203, 50226), True, 'import numpy as np\n'), ((9740, 9760), 'utilities.wxdate2pydate', 'wxdate2pydate', (['value'], {}), '(value)\n', (9753, 9760), False, 'from utilities import pydate2wxdate, wxdate2pydate, GetAttributes\n'), ((14590, 14610), 'utilities.pydate2wxdate', 'pydate2wxdate', (['value'], {}), '(value)\n', (14603, 14610), False, 'from utilities import pydate2wxdate, wxdate2pydate, GetAttributes\n')]
|
import numpy as np
import cmath
from functools import reduce
from math import pi, ceil
from numpy import sin, cos
from scipy.interpolate import interp1d
"""
References:
[Majkrzak2003] <NAME>, <NAME>: Physica B 336 (2003) 27-38
Phase sensitive reflectometry and the unambiguous determination
of scattering length density profiles
"""
def interpolate(x, fx):
return interp1d(x, fx, bounds_error=False, fill_value=0)
def refr_idx(q, sld):
"""
Calculates the refractive index with given SLD [\AA^{-2}] and wavevector transfer q [
\AA^{-1}]. The units can be arbitrary choosen, but they must satisfy that sld/q**2 has
unit [1]. The arguments should not be scaled by any constants.
For example
q = 0.01
sld = 1e-6
The refractive index is complex if q < q_c (being the critical edge) and it is
completely real if q >= q_c.
"""
return cmath.sqrt(1 - 16 * pi * sld / (q ** 2))
def reflection_matrix(q, sld, thickness, as_matrix=False):
"""
Calculates a reflection matrix used for calculating the reflectivity of
a slab of material (sld, thickness) for the wave vector transfer q.
See <NAME>, <NAME>: Physical Review B Vol. 52 Nr 15, 1995:
Exact determination of the phase in neutron reflectometry, Equation (1)
If as_matrix is True, a matrix 2x2 will be returned, if not, then the matrix
indices are returned as a, b, c, d
"""
n = refr_idx(q, sld)
theta = 0.5 * q * n * thickness
a, b, c, d = cos(theta), 1 / n * sin(theta), -n * sin(theta), cos(theta)
if as_matrix:
return np.array([[a, b], [c, d]])
return a, b, c, d
class SLDProfile(object):
def __init__(self):
pass
def as_matrix(self, q):
"""
Returns the matrix coefficients in the abeles formalism.
Returns w, x, y, z corresponding to the matrix [[w, x], [y, z]]
"""
return 0, 0, 0, 0
class ConstantSLDProfile(SLDProfile):
def __init__(self, sld, thickness, sigma=0):
if sld > 15:
raise RuntimeError("SLD seems to be unreasonable high")
self._sld = float(sld)
self._d = float(thickness)
self._r = float(sigma)
if self._r > 0:
raise NotImplementedError("Roughness not implemented yet")
def as_matrix(self, q):
return reflection_matrix(q, self._sld, self._d)
class ConcatSLDProfile(SLDProfile):
"""
The first element in sld_profiles is closest to the substrate
"""
def __init__(self, sld_profiles, reverse=False):
self._slds = sld_profiles
self._reverse = reverse
def as_matrix(self, q):
m = len(self._slds) * [None]
for i in range(0, len(self._slds)):
a, b, c, d = self._slds[i].as_matrix(q)
m[i] = np.array([[a, b], [c, d]])
if self._reverse:
m = list(reversed(m))
m = np.linalg.multi_dot(m)
return m[0][0], m[0][1], m[1][0], m[1][1]
class FunctionSLDProfile(SLDProfile):
def __init__(self, function, support, dx=0.1):
self._f = function
self._supp = support
self._dx = dx
self._xspace = np.linspace(support[0], support[1],
ceil((support[1] - support[0]) * 1 / dx))
self._feval = [self._f(x) for x in self._xspace]
self._m = [ConstantSLDProfile(fx, dx) for fx in self._feval]
self._concat = ConcatSLDProfile(self._m, reverse=False)
def as_matrix(self, q):
return self._concat.as_matrix(q)
class SlabsSLDProfile(SLDProfile):
def __init__(self, z, rho):
self._z = z
self._rho = rho
@classmethod
def from_sample(cls, sample, dz=0.1, dA=1e-4, probe=None):
from refl1d.probe import NeutronProbe
from refl1d.profile import Microslabs
if probe is None:
# The values T and L do not matter for 'just' building the SLD profile
probe = NeutronProbe(T=[1.0], L=[1.0])
slabs = Microslabs(1, dz)
sample.render(probe, slabs)
slabs.finalize(True, dA)
# ignore the imaginary part, this should be zero anyway
z, rho, irho = slabs.smooth_profile(dz)
if any(irho >= 1e-2):
raise RuntimeWarning("Sample contains absorptive SLD (imag >= 1e-2). "
"Reconstruction techniques do not support this.")
# refl1d likes to use SLD * 1e6
return cls(z, rho * 1e-6)
@classmethod
def from_slabs(cls, thickness, sld, roughness, precision=1):
# You should rather use the from_sample method, since its easier to
# understand. This method here is just a kind of 'fallback'
# if you don't wanna have the overhead of building the Stacks in refl1d
# just to put the data in here..
#
# WARNING: from_slabs and from_sample do not create the same slab profile
# they are shifted profiles (by I'd guess 3*roughness[0]?)
from refl1d.profile import build_profile
w = thickness
sld = sld
# Means, the first layer is the substrate and we only have to include
# the roughness effect. To do so, select a proper thickness (> 0) such
# that the convolution with the gaussian kernel is sufficiently approximated
if w[0] == 0:
# refl1d uses 3 sigma usually
# why 3?
# that's 3 sigma and the gaussian smoothing is nearly zero out there
# thus the 'substrate' layer is big enough to be approximated by this
# ofc bigger sigma values (>= 5) are better, but they need more
# computation
w[0] = 3 * roughness[0]
z = np.linspace(0, sum(w) + roughness[-1] * 5, int(precision * sum(w)) + 1)
offsets = np.cumsum(w)
rho = build_profile(z, offsets, roughness, sld)
return cls(z, rho)
def thickness(self):
return max(self._z) - min(self._z)
def plot_profile(self, offset=0, reverse=False):
import pylab
rho = self._rho
if reverse:
rho = list(reversed(self._rho))
pylab.plot(self._z + offset, rho)
def as_matrix(self, q):
# len(dz) = len(self._z) - 1
dz = np.diff(self._z)
m = len(dz) * [None]
for idx in range(0, len(dz)):
m[idx] = reflection_matrix(q, self._rho[idx], dz[idx], as_matrix=True)
# There is still some potential here
# Whats happening here:
# m1 * m2 * m3 * m4 * m5 ... in a sequentially manner
# maybe it's faster if you do something like
# (m1 * m2) * (m3 * m4) * ...
# and redo the grouping in the next step. this should be then O(log n)
# compared to the seq. multiplication which is O(n)....
# BUT: this has to be done in C code, not in a python implementation :/
m = reduce(np.dot, m)
return m[0][0], m[0][1], m[1][0], m[1][1]
class Reflectivity(object):
def __init__(self, sld_profile, fronting, backing):
assert isinstance(sld_profile, SLDProfile)
self._sld = sld_profile
self._f, self._b = fronting, backing
# The input should be of the magnitude 1e-6 ... 1e-5
if any(abs(np.array([fronting, backing])) >= 1e-1):
raise RuntimeWarning("Given fronting/backing SLD values are too high")
def reflection(self, q_space, as_function=True):
r = np.ones(len(q_space), dtype=complex)
for idx, q in enumerate(q_space):
if abs(q) < 1e-10:
continue
# See [Majkrzak2003] equation (17)
f, h = refr_idx(q, self._f), refr_idx(q, self._b)
A, B, C, D = self._sld.as_matrix(q)
r[idx] = (f * h * B + C + 1j * (f * D - h * A)) / \
(f * h * B - C + 1j * (f * D + h * A))
if as_function:
return self.to_function(r, q_space, square=False)
else:
return r
@staticmethod
def to_function(r, q_space, square=False):
real = interpolate(q_space, r.real)
imag = interpolate(q_space, r.imag)
if square:
return lambda q: real(q)**2 + imag(q)**2
else:
return lambda q: real(q) + 1j * imag(q)
def reflectivity(self, q_space):
r = self.reflection(q_space)
return lambda q: abs(r(q)) ** 2
def plot(self, q_space):
import pylab
R = self.reflectivity(q_space)
pylab.plot(q_space, R(q_space))
return R
|
[
"cmath.sqrt",
"math.ceil",
"refl1d.profile.Microslabs",
"refl1d.profile.build_profile",
"refl1d.probe.NeutronProbe",
"numpy.cumsum",
"numpy.diff",
"numpy.array",
"numpy.sin",
"numpy.cos",
"functools.reduce",
"scipy.interpolate.interp1d",
"pylab.plot",
"numpy.linalg.multi_dot"
] |
[((399, 448), 'scipy.interpolate.interp1d', 'interp1d', (['x', 'fx'], {'bounds_error': '(False)', 'fill_value': '(0)'}), '(x, fx, bounds_error=False, fill_value=0)\n', (407, 448), False, 'from scipy.interpolate import interp1d\n'), ((918, 956), 'cmath.sqrt', 'cmath.sqrt', (['(1 - 16 * pi * sld / q ** 2)'], {}), '(1 - 16 * pi * sld / q ** 2)\n', (928, 956), False, 'import cmath\n'), ((1526, 1536), 'numpy.cos', 'cos', (['theta'], {}), '(theta)\n', (1529, 1536), False, 'from numpy import sin, cos\n'), ((1575, 1585), 'numpy.cos', 'cos', (['theta'], {}), '(theta)\n', (1578, 1585), False, 'from numpy import sin, cos\n'), ((1620, 1646), 'numpy.array', 'np.array', (['[[a, b], [c, d]]'], {}), '([[a, b], [c, d]])\n', (1628, 1646), True, 'import numpy as np\n'), ((2929, 2951), 'numpy.linalg.multi_dot', 'np.linalg.multi_dot', (['m'], {}), '(m)\n', (2948, 2951), True, 'import numpy as np\n'), ((4032, 4049), 'refl1d.profile.Microslabs', 'Microslabs', (['(1)', 'dz'], {}), '(1, dz)\n', (4042, 4049), False, 'from refl1d.profile import Microslabs\n'), ((5834, 5846), 'numpy.cumsum', 'np.cumsum', (['w'], {}), '(w)\n', (5843, 5846), True, 'import numpy as np\n'), ((5861, 5902), 'refl1d.profile.build_profile', 'build_profile', (['z', 'offsets', 'roughness', 'sld'], {}), '(z, offsets, roughness, sld)\n', (5874, 5902), False, 'from refl1d.profile import build_profile\n'), ((6174, 6207), 'pylab.plot', 'pylab.plot', (['(self._z + offset)', 'rho'], {}), '(self._z + offset, rho)\n', (6184, 6207), False, 'import pylab\n'), ((6288, 6304), 'numpy.diff', 'np.diff', (['self._z'], {}), '(self._z)\n', (6295, 6304), True, 'import numpy as np\n'), ((6922, 6939), 'functools.reduce', 'reduce', (['np.dot', 'm'], {}), '(np.dot, m)\n', (6928, 6939), False, 'from functools import reduce\n'), ((1546, 1556), 'numpy.sin', 'sin', (['theta'], {}), '(theta)\n', (1549, 1556), False, 'from numpy import sin, cos\n'), ((1563, 1573), 'numpy.sin', 'sin', (['theta'], {}), '(theta)\n', (1566, 1573), False, 'from numpy import sin, cos\n'), ((2828, 2854), 'numpy.array', 'np.array', (['[[a, b], [c, d]]'], {}), '([[a, b], [c, d]])\n', (2836, 2854), True, 'import numpy as np\n'), ((3266, 3306), 'math.ceil', 'ceil', (['((support[1] - support[0]) * 1 / dx)'], {}), '((support[1] - support[0]) * 1 / dx)\n', (3270, 3306), False, 'from math import pi, ceil\n'), ((3984, 4014), 'refl1d.probe.NeutronProbe', 'NeutronProbe', ([], {'T': '[1.0]', 'L': '[1.0]'}), '(T=[1.0], L=[1.0])\n', (3996, 4014), False, 'from refl1d.probe import NeutronProbe\n'), ((7286, 7315), 'numpy.array', 'np.array', (['[fronting, backing]'], {}), '([fronting, backing])\n', (7294, 7315), True, 'import numpy as np\n')]
|
import os
import mitsuba
import numpy as np
import argparse
import utils
mitsuba.set_variant('scalar_spectral')
from mitsuba.core import xml, Thread, ScalarTransform4f, Transform4f, Bitmap, Struct
from mitsuba.python.xml import WriteXML
from enoki.scalar import *
import open3d as o3d
from plyfile import PlyData, PlyElement
from render import gravity_aligned_mobb
def cvt_rgba2float(filename, tmp_out_file):
plydata = PlyData.read(filename)
x = np.asarray(plydata['vertex']['x'])
y = np.asarray(plydata['vertex']['y'])
z = np.asarray(plydata['vertex']['z'])
red = plydata['vertex']['red'].astype('float32') / 255.
green = plydata['vertex']['green'].astype('float32') / 255.
blue = plydata['vertex']['blue'].astype('float32') / 255.
vertices = np.vstack((x, y, z, red, green, blue)).transpose()
ply_vertices = [tuple(x) for x in vertices.tolist()]
ply_vertices = np.array(ply_vertices, dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4'),
('red', 'f4'), ('green', 'f4'), ('blue', 'f4')])
el = PlyElement.describe(ply_vertices, 'vertex')
plydata.elements = [el, plydata['face']]
plydata.write(os.path.join(os.path.dirname(filename), tmp_out_file))
return vertices
def mts_render(filename, vertices, output):
data = {"type": "scene", "./": {"type": "path"}}
shape_dict = {
"type": "ply", 'filename': filename,
"mybsdf": {
"type": "diffuse",
"reflectance": {
"type": "mesh_attribute",
"name": "vertex_color"
# "type": "rgb",
# "value": [231. / 255, 181. / 255, 75. / 255],
}
}
}
emitter_dict = {"type": "constant"}
sensor_dict = {
"type": "perspective",
'fov': 60,
"myfilm": {
"type": "hdrfilm",
"rfilter": {"type": "gaussian"},
"width": 1920,
"height": 1440,
"pixel_format": "rgba"
},
"mysampler": {
"type": "independent",
"sample_count": 64,
}
}
obb_center, obb_size, trans_inv = gravity_aligned_mobb(vertices[:, 0:3], np.array((0.0,1.0,0.0)))
rot = trans_inv
inv_rot = np.linalg.inv(rot)
cam_target = obb_center
cam_translate = Transform4f.translate(cam_target)
cam_un_translate = Transform4f.translate(-cam_target)
world_up = Vector3f(0, 0, -1)
cam_offvec = Vector3f(0, 0, 0)
margin = 1.0
radius = np.linalg.norm(obb_size) / 2.0 + margin
cam_offset = cam_offvec + world_up
cam_offset = rot.dot(cam_offset)
cam_offset = 2 * radius * cam_offset / np.linalg.norm(cam_offset)
cam_origin = cam_target + cam_offset
cam_up = rot.dot(Vector3f(0, 1, 0))
sensor_dict['to_world'] = ScalarTransform4f.look_at(origin=cam_origin, target=cam_target, up=cam_up)
data['myshape'] = shape_dict
data['mysensor'] = sensor_dict
data['myemitter'] = emitter_dict
scene = xml.load_dict(data)
sensor = scene.sensors()[0]
scene.integrator().render(scene, sensor)
film = sensor.film()
film.set_destination_file(os.path.splitext(output)[0]+'.exr')
film.develop()
img = film.bitmap(raw=True).convert(Bitmap.PixelFormat.RGB, Struct.Type.UInt8, srgb_gamma=True)
img.write(output)
# out = WriteXML('./test.xml')
# out.write_dict(data)
def configure(args):
if not utils.file_exist(args.input, '.ply'):
utils.print_e(f'Input file {args.input} not exists')
return False
dir_path = os.path.dirname(args.output)
if not utils.folder_exist(dir_path):
utils.print_e(f'Cannot create file in folder {dir_path}')
return False
return True
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Mitsuba2 Rendering!')
parser.add_argument('-i', '--input', dest='input', type=str, action='store', required=True,
help='Input mesh ply file')
parser.add_argument('-i', '--input', dest='input', type=str, action='store', required=True,
help='Input mesh ply file')
parser.add_argument('-o', '--output', dest='output', type=str, action='store', required=True,
help='Output rendered png file')
args = parser.parse_args()
if not configure(args):
exit(0)
filename = os.path.realpath(args.input)
tmp_out_file = os.path.splitext(filename)[0]+'_temp_rgba_float.ply'
vertices = cvt_rgba2float(filename, tmp_out_file)
mts_render(tmp_out_file, vertices, args.output)
|
[
"plyfile.PlyElement.describe",
"mitsuba.core.xml.load_dict",
"mitsuba.core.Transform4f.translate",
"argparse.ArgumentParser",
"utils.file_exist",
"numpy.asarray",
"mitsuba.set_variant",
"mitsuba.core.ScalarTransform4f.look_at",
"os.path.dirname",
"os.path.realpath",
"utils.print_e",
"numpy.array",
"numpy.linalg.inv",
"numpy.linalg.norm",
"os.path.splitext",
"numpy.vstack",
"plyfile.PlyData.read",
"utils.folder_exist"
] |
[((74, 112), 'mitsuba.set_variant', 'mitsuba.set_variant', (['"""scalar_spectral"""'], {}), "('scalar_spectral')\n", (93, 112), False, 'import mitsuba\n'), ((426, 448), 'plyfile.PlyData.read', 'PlyData.read', (['filename'], {}), '(filename)\n', (438, 448), False, 'from plyfile import PlyData, PlyElement\n'), ((458, 492), 'numpy.asarray', 'np.asarray', (["plydata['vertex']['x']"], {}), "(plydata['vertex']['x'])\n", (468, 492), True, 'import numpy as np\n'), ((501, 535), 'numpy.asarray', 'np.asarray', (["plydata['vertex']['y']"], {}), "(plydata['vertex']['y'])\n", (511, 535), True, 'import numpy as np\n'), ((544, 578), 'numpy.asarray', 'np.asarray', (["plydata['vertex']['z']"], {}), "(plydata['vertex']['z'])\n", (554, 578), True, 'import numpy as np\n'), ((907, 1028), 'numpy.array', 'np.array', (['ply_vertices'], {'dtype': "[('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('red', 'f4'), ('green', 'f4'), (\n 'blue', 'f4')]"}), "(ply_vertices, dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('red',\n 'f4'), ('green', 'f4'), ('blue', 'f4')])\n", (915, 1028), True, 'import numpy as np\n'), ((1070, 1113), 'plyfile.PlyElement.describe', 'PlyElement.describe', (['ply_vertices', '"""vertex"""'], {}), "(ply_vertices, 'vertex')\n", (1089, 1113), False, 'from plyfile import PlyData, PlyElement\n'), ((2254, 2272), 'numpy.linalg.inv', 'np.linalg.inv', (['rot'], {}), '(rot)\n', (2267, 2272), True, 'import numpy as np\n'), ((2321, 2354), 'mitsuba.core.Transform4f.translate', 'Transform4f.translate', (['cam_target'], {}), '(cam_target)\n', (2342, 2354), False, 'from mitsuba.core import xml, Thread, ScalarTransform4f, Transform4f, Bitmap, Struct\n'), ((2378, 2412), 'mitsuba.core.Transform4f.translate', 'Transform4f.translate', (['(-cam_target)'], {}), '(-cam_target)\n', (2399, 2412), False, 'from mitsuba.core import xml, Thread, ScalarTransform4f, Transform4f, Bitmap, Struct\n'), ((2811, 2885), 'mitsuba.core.ScalarTransform4f.look_at', 'ScalarTransform4f.look_at', ([], {'origin': 'cam_origin', 'target': 'cam_target', 'up': 'cam_up'}), '(origin=cam_origin, target=cam_target, up=cam_up)\n', (2836, 2885), False, 'from mitsuba.core import xml, Thread, ScalarTransform4f, Transform4f, Bitmap, Struct\n'), ((3005, 3024), 'mitsuba.core.xml.load_dict', 'xml.load_dict', (['data'], {}), '(data)\n', (3018, 3024), False, 'from mitsuba.core import xml, Thread, ScalarTransform4f, Transform4f, Bitmap, Struct\n'), ((3567, 3595), 'os.path.dirname', 'os.path.dirname', (['args.output'], {}), '(args.output)\n', (3582, 3595), False, 'import os\n'), ((3782, 3840), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Mitsuba2 Rendering!"""'}), "(description='Mitsuba2 Rendering!')\n", (3805, 3840), False, 'import argparse\n'), ((4385, 4413), 'os.path.realpath', 'os.path.realpath', (['args.input'], {}), '(args.input)\n', (4401, 4413), False, 'import os\n'), ((2194, 2219), 'numpy.array', 'np.array', (['(0.0, 1.0, 0.0)'], {}), '((0.0, 1.0, 0.0))\n', (2202, 2219), True, 'import numpy as np\n'), ((2672, 2698), 'numpy.linalg.norm', 'np.linalg.norm', (['cam_offset'], {}), '(cam_offset)\n', (2686, 2698), True, 'import numpy as np\n'), ((3431, 3467), 'utils.file_exist', 'utils.file_exist', (['args.input', '""".ply"""'], {}), "(args.input, '.ply')\n", (3447, 3467), False, 'import utils\n'), ((3477, 3529), 'utils.print_e', 'utils.print_e', (['f"""Input file {args.input} not exists"""'], {}), "(f'Input file {args.input} not exists')\n", (3490, 3529), False, 'import utils\n'), ((3607, 3635), 'utils.folder_exist', 'utils.folder_exist', (['dir_path'], {}), '(dir_path)\n', (3625, 3635), False, 'import utils\n'), ((3645, 3702), 'utils.print_e', 'utils.print_e', (['f"""Cannot create file in folder {dir_path}"""'], {}), "(f'Cannot create file in folder {dir_path}')\n", (3658, 3702), False, 'import utils\n'), ((780, 818), 'numpy.vstack', 'np.vstack', (['(x, y, z, red, green, blue)'], {}), '((x, y, z, red, green, blue))\n', (789, 818), True, 'import numpy as np\n'), ((1190, 1215), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (1205, 1215), False, 'import os\n'), ((2513, 2537), 'numpy.linalg.norm', 'np.linalg.norm', (['obb_size'], {}), '(obb_size)\n', (2527, 2537), True, 'import numpy as np\n'), ((4433, 4459), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (4449, 4459), False, 'import os\n'), ((3157, 3181), 'os.path.splitext', 'os.path.splitext', (['output'], {}), '(output)\n', (3173, 3181), False, 'import os\n')]
|
import numpy as np
from source_ddc.simulation_tools import simulate
from source_ddc.algorithms import NFXP, NPL, CCP
from source_ddc.probability_tools import StateManager, random_ccp
from test.utils.functional_tools import average_out
n_repetitions = 10
def test_nfxp(simple_transition_matrix):
def utility_fn(theta, choices, states):
m_states, m_actions = np.meshgrid(states, choices)
return (theta[0] * np.log(m_states + 1) - theta[1] * m_actions).reshape((len(choices), -1, 1))
true_params = [0.5, 3]
discount_factor = 0.95
n_choices = 2
n_states = 5
state_manager = StateManager(miles=n_states)
@average_out(n_repetitions)
def test():
df, _ = simulate(
500,
100,
n_choices,
state_manager,
true_params,
utility_fn,
discount_factor,
simple_transition_matrix
)
algorithm = NFXP(
df['action'].values,
df['state'].values,
simple_transition_matrix,
utility_fn,
discount_factor,
parameter_names=['variable_cost', 'replacement_cost']
)
return algorithm.estimate(start_params=[-1, -1], method='bfgs')
mean_params = test()
tolerance_levels = np.array([0.05, 0.05])
assert np.all(np.abs(mean_params - true_params) < tolerance_levels)
def test_ccp(simple_transition_matrix):
def utility_fn(theta, choices, states):
m_states, m_actions = np.meshgrid(states, choices)
return (theta[0] * np.log(m_states + 1) - theta[1] * m_actions).reshape((len(choices), -1, 1))
true_params = [0.5, 3]
discount_factor = 0.95
n_choices = 2
n_states = 5
state_manager = StateManager(miles=n_states)
@average_out(n_repetitions)
def test():
df, ccp = simulate(
500,
100,
n_choices,
state_manager,
true_params,
utility_fn,
discount_factor,
simple_transition_matrix
)
algorithm = CCP(
df['action'].values,
df['state'].values,
simple_transition_matrix,
utility_fn,
discount_factor,
initial_p=ccp,
parameter_names=['variable_cost', 'replacement_cost']
)
return algorithm.estimate(start_params=[1, 1], method='bfgs')
mean_params = test()
tolerance_levels = np.array([0.05, 0.05])
assert np.all(np.abs(mean_params - true_params) < tolerance_levels)
def test_npl(simple_transition_matrix):
def utility_fn(theta, choices, states):
m_states, m_actions = np.meshgrid(states, choices)
return (theta[0] * np.log(m_states + 1) - theta[1] * m_actions).reshape((len(choices), -1, 1))
true_params = [0.5, 3]
discount_factor = 0.95
n_choices = 2
n_states = 5
state_manager = StateManager(miles=n_states)
@average_out(n_repetitions)
def test():
df, _ = simulate(
500,
100,
n_choices,
state_manager,
true_params,
utility_fn,
discount_factor,
simple_transition_matrix)
ccp = random_ccp(n_states, n_choices)
algorithm = NPL(
df['action'].values,
df['state'].values,
simple_transition_matrix,
utility_fn,
discount_factor,
initial_p=ccp,
parameter_names=['variable_cost', 'replacement_cost']
)
return algorithm.estimate(start_params=[1, 1], method='bfgs')
mean_params = test()
tolerance_levels = np.array([0.05, 0.05])
assert np.all(np.abs(mean_params - true_params) < tolerance_levels)
def test_npl_relaxation_param(simple_transition_matrix):
def utility_fn(theta, choices, states):
m_states, m_actions = np.meshgrid(states, choices)
return (theta[0] * np.log(m_states + 1) - theta[1] * m_actions).reshape((len(choices), -1, 1))
true_params = [0.5, 3]
discount_factor = 0.95
n_choices = 2
n_states = 5
state_manager = StateManager(miles=n_states)
@average_out(n_repetitions)
def test():
df, _ = simulate(500,
100,
n_choices,
state_manager,
true_params,
utility_fn,
discount_factor,
simple_transition_matrix)
ccp = random_ccp(n_states, n_choices)
algorithm = NPL(
df['action'].values,
df['state'].values,
simple_transition_matrix,
utility_fn,
discount_factor,
initial_p=ccp,
relaxation_param=0.9,
parameter_names=['variable_cost', 'replacement_cost'],
npl_maxiter=50
)
return algorithm.estimate(start_params=[1, 1], method='bfgs')
mean_params = test()
tolerance_levels = np.array([0.05, 0.05])
assert np.all(np.abs(mean_params - true_params) < tolerance_levels)
|
[
"numpy.meshgrid",
"numpy.abs",
"numpy.log",
"source_ddc.probability_tools.StateManager",
"test.utils.functional_tools.average_out",
"source_ddc.algorithms.NPL",
"source_ddc.probability_tools.random_ccp",
"numpy.array",
"source_ddc.simulation_tools.simulate",
"source_ddc.algorithms.CCP",
"source_ddc.algorithms.NFXP"
] |
[((616, 644), 'source_ddc.probability_tools.StateManager', 'StateManager', ([], {'miles': 'n_states'}), '(miles=n_states)\n', (628, 644), False, 'from source_ddc.probability_tools import StateManager, random_ccp\n'), ((651, 677), 'test.utils.functional_tools.average_out', 'average_out', (['n_repetitions'], {}), '(n_repetitions)\n', (662, 677), False, 'from test.utils.functional_tools import average_out\n'), ((1310, 1332), 'numpy.array', 'np.array', (['[0.05, 0.05]'], {}), '([0.05, 0.05])\n', (1318, 1332), True, 'import numpy as np\n'), ((1765, 1793), 'source_ddc.probability_tools.StateManager', 'StateManager', ([], {'miles': 'n_states'}), '(miles=n_states)\n', (1777, 1793), False, 'from source_ddc.probability_tools import StateManager, random_ccp\n'), ((1800, 1826), 'test.utils.functional_tools.average_out', 'average_out', (['n_repetitions'], {}), '(n_repetitions)\n', (1811, 1826), False, 'from test.utils.functional_tools import average_out\n'), ((2485, 2507), 'numpy.array', 'np.array', (['[0.05, 0.05]'], {}), '([0.05, 0.05])\n', (2493, 2507), True, 'import numpy as np\n'), ((2940, 2968), 'source_ddc.probability_tools.StateManager', 'StateManager', ([], {'miles': 'n_states'}), '(miles=n_states)\n', (2952, 2968), False, 'from source_ddc.probability_tools import StateManager, random_ccp\n'), ((2975, 3001), 'test.utils.functional_tools.average_out', 'average_out', (['n_repetitions'], {}), '(n_repetitions)\n', (2986, 3001), False, 'from test.utils.functional_tools import average_out\n'), ((3695, 3717), 'numpy.array', 'np.array', (['[0.05, 0.05]'], {}), '([0.05, 0.05])\n', (3703, 3717), True, 'import numpy as np\n'), ((4167, 4195), 'source_ddc.probability_tools.StateManager', 'StateManager', ([], {'miles': 'n_states'}), '(miles=n_states)\n', (4179, 4195), False, 'from source_ddc.probability_tools import StateManager, random_ccp\n'), ((4202, 4228), 'test.utils.functional_tools.average_out', 'average_out', (['n_repetitions'], {}), '(n_repetitions)\n', (4213, 4228), False, 'from test.utils.functional_tools import average_out\n'), ((5063, 5085), 'numpy.array', 'np.array', (['[0.05, 0.05]'], {}), '([0.05, 0.05])\n', (5071, 5085), True, 'import numpy as np\n'), ((373, 401), 'numpy.meshgrid', 'np.meshgrid', (['states', 'choices'], {}), '(states, choices)\n', (384, 401), True, 'import numpy as np\n'), ((710, 826), 'source_ddc.simulation_tools.simulate', 'simulate', (['(500)', '(100)', 'n_choices', 'state_manager', 'true_params', 'utility_fn', 'discount_factor', 'simple_transition_matrix'], {}), '(500, 100, n_choices, state_manager, true_params, utility_fn,\n discount_factor, simple_transition_matrix)\n', (718, 826), False, 'from source_ddc.simulation_tools import simulate\n'), ((950, 1113), 'source_ddc.algorithms.NFXP', 'NFXP', (["df['action'].values", "df['state'].values", 'simple_transition_matrix', 'utility_fn', 'discount_factor'], {'parameter_names': "['variable_cost', 'replacement_cost']"}), "(df['action'].values, df['state'].values, simple_transition_matrix,\n utility_fn, discount_factor, parameter_names=['variable_cost',\n 'replacement_cost'])\n", (954, 1113), False, 'from source_ddc.algorithms import NFXP, NPL, CCP\n'), ((1522, 1550), 'numpy.meshgrid', 'np.meshgrid', (['states', 'choices'], {}), '(states, choices)\n', (1533, 1550), True, 'import numpy as np\n'), ((1861, 1977), 'source_ddc.simulation_tools.simulate', 'simulate', (['(500)', '(100)', 'n_choices', 'state_manager', 'true_params', 'utility_fn', 'discount_factor', 'simple_transition_matrix'], {}), '(500, 100, n_choices, state_manager, true_params, utility_fn,\n discount_factor, simple_transition_matrix)\n', (1869, 1977), False, 'from source_ddc.simulation_tools import simulate\n'), ((2101, 2279), 'source_ddc.algorithms.CCP', 'CCP', (["df['action'].values", "df['state'].values", 'simple_transition_matrix', 'utility_fn', 'discount_factor'], {'initial_p': 'ccp', 'parameter_names': "['variable_cost', 'replacement_cost']"}), "(df['action'].values, df['state'].values, simple_transition_matrix,\n utility_fn, discount_factor, initial_p=ccp, parameter_names=[\n 'variable_cost', 'replacement_cost'])\n", (2104, 2279), False, 'from source_ddc.algorithms import NFXP, NPL, CCP\n'), ((2697, 2725), 'numpy.meshgrid', 'np.meshgrid', (['states', 'choices'], {}), '(states, choices)\n', (2708, 2725), True, 'import numpy as np\n'), ((3034, 3150), 'source_ddc.simulation_tools.simulate', 'simulate', (['(500)', '(100)', 'n_choices', 'state_manager', 'true_params', 'utility_fn', 'discount_factor', 'simple_transition_matrix'], {}), '(500, 100, n_choices, state_manager, true_params, utility_fn,\n discount_factor, simple_transition_matrix)\n', (3042, 3150), False, 'from source_ddc.simulation_tools import simulate\n'), ((3259, 3290), 'source_ddc.probability_tools.random_ccp', 'random_ccp', (['n_states', 'n_choices'], {}), '(n_states, n_choices)\n', (3269, 3290), False, 'from source_ddc.probability_tools import StateManager, random_ccp\n'), ((3312, 3490), 'source_ddc.algorithms.NPL', 'NPL', (["df['action'].values", "df['state'].values", 'simple_transition_matrix', 'utility_fn', 'discount_factor'], {'initial_p': 'ccp', 'parameter_names': "['variable_cost', 'replacement_cost']"}), "(df['action'].values, df['state'].values, simple_transition_matrix,\n utility_fn, discount_factor, initial_p=ccp, parameter_names=[\n 'variable_cost', 'replacement_cost'])\n", (3315, 3490), False, 'from source_ddc.algorithms import NFXP, NPL, CCP\n'), ((3924, 3952), 'numpy.meshgrid', 'np.meshgrid', (['states', 'choices'], {}), '(states, choices)\n', (3935, 3952), True, 'import numpy as np\n'), ((4261, 4377), 'source_ddc.simulation_tools.simulate', 'simulate', (['(500)', '(100)', 'n_choices', 'state_manager', 'true_params', 'utility_fn', 'discount_factor', 'simple_transition_matrix'], {}), '(500, 100, n_choices, state_manager, true_params, utility_fn,\n discount_factor, simple_transition_matrix)\n', (4269, 4377), False, 'from source_ddc.simulation_tools import simulate\n'), ((4564, 4595), 'source_ddc.probability_tools.random_ccp', 'random_ccp', (['n_states', 'n_choices'], {}), '(n_states, n_choices)\n', (4574, 4595), False, 'from source_ddc.probability_tools import StateManager, random_ccp\n'), ((4617, 4832), 'source_ddc.algorithms.NPL', 'NPL', (["df['action'].values", "df['state'].values", 'simple_transition_matrix', 'utility_fn', 'discount_factor'], {'initial_p': 'ccp', 'relaxation_param': '(0.9)', 'parameter_names': "['variable_cost', 'replacement_cost']", 'npl_maxiter': '(50)'}), "(df['action'].values, df['state'].values, simple_transition_matrix,\n utility_fn, discount_factor, initial_p=ccp, relaxation_param=0.9,\n parameter_names=['variable_cost', 'replacement_cost'], npl_maxiter=50)\n", (4620, 4832), False, 'from source_ddc.algorithms import NFXP, NPL, CCP\n'), ((1351, 1384), 'numpy.abs', 'np.abs', (['(mean_params - true_params)'], {}), '(mean_params - true_params)\n', (1357, 1384), True, 'import numpy as np\n'), ((2526, 2559), 'numpy.abs', 'np.abs', (['(mean_params - true_params)'], {}), '(mean_params - true_params)\n', (2532, 2559), True, 'import numpy as np\n'), ((3736, 3769), 'numpy.abs', 'np.abs', (['(mean_params - true_params)'], {}), '(mean_params - true_params)\n', (3742, 3769), True, 'import numpy as np\n'), ((5104, 5137), 'numpy.abs', 'np.abs', (['(mean_params - true_params)'], {}), '(mean_params - true_params)\n', (5110, 5137), True, 'import numpy as np\n'), ((429, 449), 'numpy.log', 'np.log', (['(m_states + 1)'], {}), '(m_states + 1)\n', (435, 449), True, 'import numpy as np\n'), ((1578, 1598), 'numpy.log', 'np.log', (['(m_states + 1)'], {}), '(m_states + 1)\n', (1584, 1598), True, 'import numpy as np\n'), ((2753, 2773), 'numpy.log', 'np.log', (['(m_states + 1)'], {}), '(m_states + 1)\n', (2759, 2773), True, 'import numpy as np\n'), ((3980, 4000), 'numpy.log', 'np.log', (['(m_states + 1)'], {}), '(m_states + 1)\n', (3986, 4000), True, 'import numpy as np\n')]
|
from typing import Union, List
import numpy as np
from gym import spaces, ActionWrapper
from gym.spaces import flatten_space, flatdim, unflatten, flatten
from sorting_gym import DiscreteParametric
def merge_discrete_spaces(input_spaces: List[Union[spaces.Discrete, spaces.Tuple, spaces.MultiBinary]]) -> spaces.MultiDiscrete:
"""
Merge nested Discrete, and MultiBinary spaces into a single MultiDiscrete space
TODO could also add support for MultiDiscrete
:param input_spaces:
:return:
"""
return spaces.MultiDiscrete(_discrete_dims(input_spaces))
def _discrete_dims(input_spaces: Union[spaces.Discrete, spaces.Tuple, spaces.MultiBinary]):
sizes = []
for space in input_spaces:
if isinstance(space, spaces.Discrete):
sizes.append(space.n)
elif isinstance(space, spaces.MultiBinary):
sizes.extend([2 for _ in range(space.n)])
elif isinstance(space, spaces.MultiDiscrete):
sizes.extend(space.nvec)
elif isinstance(space, spaces.Tuple):
sizes.extend(_discrete_dims(space.spaces))
return sizes
def _discrete_unflatten(argument_space, args):
"""
:param argument_space:
:param args:
:return:
"""
res = []
args = list(args)
while len(args) > 0:
if isinstance(argument_space, spaces.Discrete):
res.append(args.pop(0))
elif isinstance(argument_space, spaces.MultiDiscrete):
res.append(args[:argument_space.shape[0]])
del args[:argument_space.shape[0]]
elif isinstance(argument_space, spaces.MultiBinary):
res.append(args[:argument_space.n])
del args[:argument_space.shape[0]]
elif isinstance(argument_space, spaces.Tuple):
_num_tuple_args = _discrete_dims(argument_space.spaces)
res.append(args[:len(_num_tuple_args)])
del args[:len(_num_tuple_args)]
else:
raise NotImplemented
return res
class DisjointMultiDiscreteActionSpaceWrapper(ActionWrapper):
"""Expose a MultiDiscrete action space for each disjoint action space instead of a more complex nested space.
Wrapping a discrete parametric space with the following disjoint spaces:
Discrete(k),
Tuple([Discrete(k), MultiBinary(1)]),
Tuple([Discrete(k), Discrete(k)]),
should result in output spaces of:
MultiDiscrete([k]),
MultiDiscrete([k, 2]),
MultiDiscrete([k, k]
"""
def __init__(self, env):
assert isinstance(env.action_space, DiscreteParametric), (
"expected DiscreteParametric action space, got {}".format(type(env.action_space)))
super(DisjointMultiDiscreteActionSpaceWrapper, self).__init__(env)
self.parametric_space: DiscreteParametric = env.action_space
# Construct the modified disjoint spaces
self.disjoint_action_spaces = [merge_discrete_spaces([s]) for s in self.parametric_space.disjoint_spaces]
self.action_space = DiscreteParametric(env.action_space.parameter_space.n, self.disjoint_action_spaces)
def action(self, action):
"""
Convert an action using the merged MultiDiscrete disjoint space into a DiscreteParametric action.
"""
assert self.action_space.contains(action), "Given action is not valid in this action space"
# Get the discrete parameter value
parameter = action[0]
# The args should be a valid MultiDiscrete sample for the given parameter. Note
# MultiDiscrete samples are ndarrays of dtype np.int64.
args = action[1:]
assert self.disjoint_action_spaces[parameter].contains(np.array(args, dtype=np.int64))
# TODO the args need to be converted back into their original nested form
#
output_space = self.env.action_space.disjoint_spaces[parameter]
raise NotImplemented
assert self.env.action_space.contains(transformed_action)
return tuple(transformed_action)
class MultiDiscreteActionSpaceWrapper(ActionWrapper):
"""Expose a single MultiDiscrete action space instead of a DiscreteParametric action space.
"""
def __init__(self, env):
assert isinstance(env.action_space, DiscreteParametric), ("expected DiscreteParametric action space, got {}".format(type(env.action_space)))
super(MultiDiscreteActionSpaceWrapper, self).__init__(env)
parametric_space: DiscreteParametric = env.action_space
# Construct a space from the parametric space's parameter_space and disjoint spaces
self.action_space = merge_discrete_spaces([parametric_space.parameter_space] + list(parametric_space.disjoint_spaces))
def action(self, action):
"""Convert a MultiDiscrete action into a DiscreteParametric action."""
# Get the discrete parameter value
parameter = np.argmax(action[0])
argument_space = self.env.action_space[parameter]
# Convert the appropriate args for the disjoint space using the parameter
start_index = 1 + len(_discrete_dims(self.env.action_space.disjoint_spaces[:parameter]))
end_index = 1 + len(_discrete_dims(self.env.action_space.disjoint_spaces[:parameter + 1]))
# Our discrete arguments for the disjoint space
args = action[start_index:end_index]
disjoint_args = _discrete_unflatten(argument_space, args)
# Make the final flat tuple
transformed_action = [parameter]
if isinstance(disjoint_args, (tuple, list)):
transformed_action.extend(disjoint_args)
else:
transformed_action.append(disjoint_args)
assert self.env.action_space.contains(transformed_action)
return tuple(transformed_action)
class BoxActionSpaceWrapper(ActionWrapper):
"""Expose a flat Box action space instead of a parametric action space.
Example::
>>> isinstance(BoxActionSpaceWrapper(env).action_space, Box)
True
Note that sampling from a Box is not the same as flattening samples from a richer
subspace. To draw action space samples from a `SimpleActionSpace` call
`SimpleActionSpace.action_space_sample()`
"""
def __init__(self, env):
assert isinstance(env.action_space, DiscreteParametric), ("expected DiscreteParametric action space, got {}".format(type(env.action_space)))
super(BoxActionSpaceWrapper, self).__init__(env)
parametric_space: DiscreteParametric = env.action_space
# Construct a space from the parametric space's parameter_space and disjoint spaces
self.action_space = flatten_space(spaces.Tuple([parametric_space.parameter_space] +
list(parametric_space.disjoint_spaces)))
self.disjoint_sizes = [flatdim(space) for space in parametric_space.disjoint_spaces]
def action(self, action):
"""Convert a flattened action into a parametric space."""
# Get the discrete parameter value
num_disjoint_spaces = len(self.env.action_space)
parameter = np.argmax(action[:num_disjoint_spaces])
argument_space = self.env.action_space[parameter]
# Now we need to index the appropriate args for the disjoint space using the parameter
start_index = num_disjoint_spaces
start_index += sum(self.disjoint_sizes[:parameter])
end_index = start_index + self.disjoint_sizes[parameter]
# Flattened arguments for the disjoint space
args = action[start_index:end_index]
try:
disjoint_args = unflatten(argument_space, args)
except IndexError as e:
# Very likely the args are invalid for the wrapped space e.g. a Discrete(2) getting all zeros.
msg = "Failed to unflatten arguments to wrapped space of " + str(argument_space)
raise ValueError(msg) from e
# Make the final flat tuple
transformed_action = [parameter]
if isinstance(disjoint_args, tuple):
transformed_action.extend(disjoint_args)
else:
transformed_action.append(disjoint_args)
assert self.env.action_space.contains(transformed_action)
return tuple(transformed_action)
def reverse_action(self, action):
"""Convert a wrapped action (e.g. from a DiscreteParametric) into a flattened action"""
parameter = action[0]
result = np.zeros(self.action_space.shape[0], dtype=self.action_space.dtype)
result[parameter] = 1.0
start_index = len(self.env.action_space)
start_index += sum(self.disjoint_sizes[:parameter])
end_index = start_index + self.disjoint_sizes[parameter]
result[start_index:end_index] = flatten(self.env.action_space[parameter], action[1:])
assert self.action_space.contains(result)
return result
def action_space_sample(self):
rich_sample = self.env.action_space.sample()
assert self.env.action_space.contains(rich_sample)
return self.reverse_action(rich_sample)
|
[
"gym.spaces.flatten",
"numpy.argmax",
"numpy.zeros",
"sorting_gym.DiscreteParametric",
"gym.spaces.flatdim",
"numpy.array",
"gym.spaces.unflatten"
] |
[((3029, 3117), 'sorting_gym.DiscreteParametric', 'DiscreteParametric', (['env.action_space.parameter_space.n', 'self.disjoint_action_spaces'], {}), '(env.action_space.parameter_space.n, self.\n disjoint_action_spaces)\n', (3047, 3117), False, 'from sorting_gym import DiscreteParametric\n'), ((4889, 4909), 'numpy.argmax', 'np.argmax', (['action[0]'], {}), '(action[0])\n', (4898, 4909), True, 'import numpy as np\n'), ((7103, 7142), 'numpy.argmax', 'np.argmax', (['action[:num_disjoint_spaces]'], {}), '(action[:num_disjoint_spaces])\n', (7112, 7142), True, 'import numpy as np\n'), ((8443, 8510), 'numpy.zeros', 'np.zeros', (['self.action_space.shape[0]'], {'dtype': 'self.action_space.dtype'}), '(self.action_space.shape[0], dtype=self.action_space.dtype)\n', (8451, 8510), True, 'import numpy as np\n'), ((8757, 8810), 'gym.spaces.flatten', 'flatten', (['self.env.action_space[parameter]', 'action[1:]'], {}), '(self.env.action_space[parameter], action[1:])\n', (8764, 8810), False, 'from gym.spaces import flatten_space, flatdim, unflatten, flatten\n'), ((3689, 3719), 'numpy.array', 'np.array', (['args'], {'dtype': 'np.int64'}), '(args, dtype=np.int64)\n', (3697, 3719), True, 'import numpy as np\n'), ((6824, 6838), 'gym.spaces.flatdim', 'flatdim', (['space'], {}), '(space)\n', (6831, 6838), False, 'from gym.spaces import flatten_space, flatdim, unflatten, flatten\n'), ((7605, 7636), 'gym.spaces.unflatten', 'unflatten', (['argument_space', 'args'], {}), '(argument_space, args)\n', (7614, 7636), False, 'from gym.spaces import flatten_space, flatdim, unflatten, flatten\n')]
|
"""Tests for the fixes of ACCESS-ESM1-5."""
import unittest.mock
import iris
import numpy as np
import pytest
from esmvalcore.cmor._fixes.cmip6.access_esm1_5 import Cl, Cli, Clw, Hus, Zg
from esmvalcore.cmor._fixes.common import ClFixHybridHeightCoord
from esmvalcore.cmor.fix import Fix
from esmvalcore.cmor.table import get_var_info
B_POINTS = [
0.99771648645401, 0.990881502628326, 0.979542553424835,
0.9637770652771, 0.943695485591888, 0.919438362121582,
0.891178011894226, 0.859118342399597, 0.823493480682373,
0.784570515155792, 0.742646217346191, 0.698050200939178,
0.651142716407776, 0.602314412593842, 0.55198872089386,
0.500619947910309, 0.44869339466095, 0.39672577381134,
0.34526526927948, 0.294891387224197, 0.24621507525444,
0.199878215789795, 0.156554222106934, 0.116947874426842,
0.0817952379584312, 0.0518637150526047, 0.0279368180781603,
0.0107164792716503, 0.00130179093685001,
0, 0, 0, 0, 0, 0, 0, 0, 0,
]
B_BOUNDS = [
[1, 0.994296252727509],
[0.994296252727509, 0.985203862190247],
[0.985203862190247, 0.971644043922424],
[0.971644043922424, 0.953709840774536],
[0.953709840774536, 0.931527435779572],
[0.931527435779572, 0.905253052711487],
[0.905253052711487, 0.875074565410614],
[0.875074565410614, 0.84121161699295],
[0.84121161699295, 0.80391401052475],
[0.80391401052475, 0.763464510440826],
[0.763464510440826, 0.720175802707672],
[0.720175802707672, 0.674392521381378],
[0.674392521381378, 0.626490533351898],
[0.626490533351898, 0.576877355575562],
[0.576877355575562, 0.525990784168243],
[0.525990784168243, 0.474301367998123],
[0.474301367998123, 0.422309905290604],
[0.422309905290604, 0.370548874139786],
[0.370548874139786, 0.3195820748806],
[0.3195820748806, 0.270004868507385],
[0.270004868507385, 0.222443267703056],
[0.222443267703056, 0.177555426955223],
[0.177555426955223, 0.136030226945877],
[0.136030226945877, 0.0985881090164185],
[0.0985881090164185, 0.0659807845950127],
[0.0659807845950127, 0.0389823913574219],
[0.0389823913574219, 0.0183146875351667],
[0.0183146875351667, 0.00487210927531123],
[0.00487210927531123, 0],
[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],
[0, 0], [0, 0],
]
@pytest.fixture
def cl_cubes():
"""``cl`` cubes."""
b_coord = iris.coords.AuxCoord(np.zeros_like(B_POINTS),
bounds=np.zeros_like(B_BOUNDS),
var_name='b')
cube = iris.cube.Cube(
np.ones_like(B_POINTS),
var_name='cl',
standard_name='cloud_area_fraction_in_atmosphere_layer',
units='%',
aux_coords_and_dims=[(b_coord, 0)],
)
return iris.cube.CubeList([cube])
def test_get_cl_fix():
"""Test getting of fix."""
fix = Fix.get_fixes('CMIP6', 'ACCESS-ESM1-5', 'Amon', 'cl')
assert fix == [Cl(None)]
@unittest.mock.patch(
'esmvalcore.cmor._fixes.cmip6.access_esm1_5.ClFixHybridHeightCoord.'
'fix_metadata', autospec=True)
def test_cl_fix_metadata(mock_base_fix_metadata, cl_cubes):
"""Test ``fix_metadata`` for ``cl``."""
mock_base_fix_metadata.side_effect = lambda x, y: y
fix = Cl(None)
out_cube = fix.fix_metadata(cl_cubes)[0]
b_coord = out_cube.coord(var_name='b')
np.testing.assert_allclose(b_coord.points, B_POINTS)
np.testing.assert_allclose(b_coord.bounds, B_BOUNDS)
def test_cl_fix():
"""Test fix for ``cl``."""
assert issubclass(Cl, ClFixHybridHeightCoord)
def test_get_cli_fix():
"""Test getting of fix."""
fix = Fix.get_fixes('CMIP6', 'ACCESS-ESM1-5', 'Amon', 'cli')
assert fix == [Cli(None)]
def test_cli_fix():
"""Test fix for ``cli``."""
assert Cli is Cl
def test_get_clw_fix():
"""Test getting of fix."""
fix = Fix.get_fixes('CMIP6', 'ACCESS-ESM1-5', 'Amon', 'clw')
assert fix == [Clw(None)]
def test_clw_fix():
"""Test fix for ``clw``."""
assert Clw is Cl
@pytest.fixture
def cubes_with_wrong_air_pressure():
"""Cubes with wrong ``air_pressure`` coordinate."""
air_pressure_coord = iris.coords.DimCoord(
[1000.09, 600.6, 200.0],
bounds=[[1200.00001, 800], [800, 400.8], [400.8, 1.9]],
var_name='plev',
standard_name='air_pressure',
units='pa',
)
hus_cube = iris.cube.Cube(
[0.0, 1.0, 2.0],
var_name='hus',
dim_coords_and_dims=[(air_pressure_coord, 0)],
)
zg_cube = hus_cube.copy()
zg_cube.var_name = 'zg'
return iris.cube.CubeList([hus_cube, zg_cube])
def test_get_hus_fix():
"""Test getting of fix."""
fix = Fix.get_fixes('CMIP6', 'ACCESS-ESM1-5', 'Amon', 'hus')
assert fix == [Hus(None)]
def test_hus_fix_metadata(cubes_with_wrong_air_pressure):
"""Test ``fix_metadata`` for ``hus``."""
vardef = get_var_info('CMIP6', 'Amon', 'hus')
fix = Hus(vardef)
out_cubes = fix.fix_metadata(cubes_with_wrong_air_pressure)
assert len(out_cubes) == 2
hus_cube = out_cubes.extract_cube('hus')
zg_cube = out_cubes.extract_cube('zg')
assert hus_cube.var_name == 'hus'
assert zg_cube.var_name == 'zg'
np.testing.assert_allclose(hus_cube.coord('air_pressure').points,
[1000.0, 601.0, 200.0])
np.testing.assert_allclose(hus_cube.coord('air_pressure').bounds,
[[1200.0, 800.0], [800.0, 401.0], [401.0, 2.0]])
np.testing.assert_allclose(zg_cube.coord('air_pressure').points,
[1000.09, 600.6, 200.0])
np.testing.assert_allclose(zg_cube.coord('air_pressure').bounds,
[[1200.00001, 800], [800, 400.8], [400.8, 1.9]])
def test_get_zg_fix():
"""Test getting of fix."""
fix = Fix.get_fixes('CMIP6', 'ACCESS-ESM1-5', 'Amon', 'zg')
assert fix == [Zg(None)]
def test_zg_fix_metadata(cubes_with_wrong_air_pressure):
"""Test ``fix_metadata`` for ``zg``."""
vardef = get_var_info('CMIP6', 'Amon', 'zg')
fix = Zg(vardef)
out_cubes = fix.fix_metadata(cubes_with_wrong_air_pressure)
assert len(out_cubes) == 2
hus_cube = out_cubes.extract_cube('hus')
zg_cube = out_cubes.extract_cube('zg')
assert hus_cube.var_name == 'hus'
assert zg_cube.var_name == 'zg'
np.testing.assert_allclose(hus_cube.coord('air_pressure').points,
[1000.09, 600.6, 200.0])
np.testing.assert_allclose(hus_cube.coord('air_pressure').bounds,
[[1200.00001, 800], [800, 400.8], [400.8, 1.9]])
np.testing.assert_allclose(zg_cube.coord('air_pressure').points,
[1000.0, 601.0, 200.0])
np.testing.assert_allclose(zg_cube.coord('air_pressure').bounds,
[[1200.0, 800.0], [800.0, 401.0], [401.0, 2.0]])
|
[
"esmvalcore.cmor._fixes.cmip6.access_esm1_5.Zg",
"numpy.zeros_like",
"numpy.ones_like",
"esmvalcore.cmor._fixes.cmip6.access_esm1_5.Clw",
"iris.cube.CubeList",
"esmvalcore.cmor._fixes.cmip6.access_esm1_5.Cli",
"esmvalcore.cmor.fix.Fix.get_fixes",
"esmvalcore.cmor._fixes.cmip6.access_esm1_5.Hus",
"iris.coords.DimCoord",
"esmvalcore.cmor._fixes.cmip6.access_esm1_5.Cl",
"iris.cube.Cube",
"esmvalcore.cmor.table.get_var_info",
"numpy.testing.assert_allclose"
] |
[((2777, 2803), 'iris.cube.CubeList', 'iris.cube.CubeList', (['[cube]'], {}), '([cube])\n', (2795, 2803), False, 'import iris\n'), ((2870, 2923), 'esmvalcore.cmor.fix.Fix.get_fixes', 'Fix.get_fixes', (['"""CMIP6"""', '"""ACCESS-ESM1-5"""', '"""Amon"""', '"""cl"""'], {}), "('CMIP6', 'ACCESS-ESM1-5', 'Amon', 'cl')\n", (2883, 2923), False, 'from esmvalcore.cmor.fix import Fix\n'), ((3255, 3263), 'esmvalcore.cmor._fixes.cmip6.access_esm1_5.Cl', 'Cl', (['None'], {}), '(None)\n', (3257, 3263), False, 'from esmvalcore.cmor._fixes.cmip6.access_esm1_5 import Cl, Cli, Clw, Hus, Zg\n'), ((3356, 3408), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['b_coord.points', 'B_POINTS'], {}), '(b_coord.points, B_POINTS)\n', (3382, 3408), True, 'import numpy as np\n'), ((3413, 3465), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['b_coord.bounds', 'B_BOUNDS'], {}), '(b_coord.bounds, B_BOUNDS)\n', (3439, 3465), True, 'import numpy as np\n'), ((3635, 3689), 'esmvalcore.cmor.fix.Fix.get_fixes', 'Fix.get_fixes', (['"""CMIP6"""', '"""ACCESS-ESM1-5"""', '"""Amon"""', '"""cli"""'], {}), "('CMIP6', 'ACCESS-ESM1-5', 'Amon', 'cli')\n", (3648, 3689), False, 'from esmvalcore.cmor.fix import Fix\n'), ((3862, 3916), 'esmvalcore.cmor.fix.Fix.get_fixes', 'Fix.get_fixes', (['"""CMIP6"""', '"""ACCESS-ESM1-5"""', '"""Amon"""', '"""clw"""'], {}), "('CMIP6', 'ACCESS-ESM1-5', 'Amon', 'clw')\n", (3875, 3916), False, 'from esmvalcore.cmor.fix import Fix\n'), ((4158, 4328), 'iris.coords.DimCoord', 'iris.coords.DimCoord', (['[1000.09, 600.6, 200.0]'], {'bounds': '[[1200.00001, 800], [800, 400.8], [400.8, 1.9]]', 'var_name': '"""plev"""', 'standard_name': '"""air_pressure"""', 'units': '"""pa"""'}), "([1000.09, 600.6, 200.0], bounds=[[1200.00001, 800], [\n 800, 400.8], [400.8, 1.9]], var_name='plev', standard_name=\n 'air_pressure', units='pa')\n", (4178, 4328), False, 'import iris\n'), ((4381, 4480), 'iris.cube.Cube', 'iris.cube.Cube', (['[0.0, 1.0, 2.0]'], {'var_name': '"""hus"""', 'dim_coords_and_dims': '[(air_pressure_coord, 0)]'}), "([0.0, 1.0, 2.0], var_name='hus', dim_coords_and_dims=[(\n air_pressure_coord, 0)])\n", (4395, 4480), False, 'import iris\n'), ((4576, 4615), 'iris.cube.CubeList', 'iris.cube.CubeList', (['[hus_cube, zg_cube]'], {}), '([hus_cube, zg_cube])\n', (4594, 4615), False, 'import iris\n'), ((4683, 4737), 'esmvalcore.cmor.fix.Fix.get_fixes', 'Fix.get_fixes', (['"""CMIP6"""', '"""ACCESS-ESM1-5"""', '"""Amon"""', '"""hus"""'], {}), "('CMIP6', 'ACCESS-ESM1-5', 'Amon', 'hus')\n", (4696, 4737), False, 'from esmvalcore.cmor.fix import Fix\n'), ((4886, 4922), 'esmvalcore.cmor.table.get_var_info', 'get_var_info', (['"""CMIP6"""', '"""Amon"""', '"""hus"""'], {}), "('CMIP6', 'Amon', 'hus')\n", (4898, 4922), False, 'from esmvalcore.cmor.table import get_var_info\n'), ((4933, 4944), 'esmvalcore.cmor._fixes.cmip6.access_esm1_5.Hus', 'Hus', (['vardef'], {}), '(vardef)\n', (4936, 4944), False, 'from esmvalcore.cmor._fixes.cmip6.access_esm1_5 import Cl, Cli, Clw, Hus, Zg\n'), ((5817, 5870), 'esmvalcore.cmor.fix.Fix.get_fixes', 'Fix.get_fixes', (['"""CMIP6"""', '"""ACCESS-ESM1-5"""', '"""Amon"""', '"""zg"""'], {}), "('CMIP6', 'ACCESS-ESM1-5', 'Amon', 'zg')\n", (5830, 5870), False, 'from esmvalcore.cmor.fix import Fix\n'), ((6016, 6051), 'esmvalcore.cmor.table.get_var_info', 'get_var_info', (['"""CMIP6"""', '"""Amon"""', '"""zg"""'], {}), "('CMIP6', 'Amon', 'zg')\n", (6028, 6051), False, 'from esmvalcore.cmor.table import get_var_info\n'), ((6062, 6072), 'esmvalcore.cmor._fixes.cmip6.access_esm1_5.Zg', 'Zg', (['vardef'], {}), '(vardef)\n', (6064, 6072), False, 'from esmvalcore.cmor._fixes.cmip6.access_esm1_5 import Cl, Cli, Clw, Hus, Zg\n'), ((2409, 2432), 'numpy.zeros_like', 'np.zeros_like', (['B_POINTS'], {}), '(B_POINTS)\n', (2422, 2432), True, 'import numpy as np\n'), ((2585, 2607), 'numpy.ones_like', 'np.ones_like', (['B_POINTS'], {}), '(B_POINTS)\n', (2597, 2607), True, 'import numpy as np\n'), ((2476, 2499), 'numpy.zeros_like', 'np.zeros_like', (['B_BOUNDS'], {}), '(B_BOUNDS)\n', (2489, 2499), True, 'import numpy as np\n'), ((2943, 2951), 'esmvalcore.cmor._fixes.cmip6.access_esm1_5.Cl', 'Cl', (['None'], {}), '(None)\n', (2945, 2951), False, 'from esmvalcore.cmor._fixes.cmip6.access_esm1_5 import Cl, Cli, Clw, Hus, Zg\n'), ((3709, 3718), 'esmvalcore.cmor._fixes.cmip6.access_esm1_5.Cli', 'Cli', (['None'], {}), '(None)\n', (3712, 3718), False, 'from esmvalcore.cmor._fixes.cmip6.access_esm1_5 import Cl, Cli, Clw, Hus, Zg\n'), ((3936, 3945), 'esmvalcore.cmor._fixes.cmip6.access_esm1_5.Clw', 'Clw', (['None'], {}), '(None)\n', (3939, 3945), False, 'from esmvalcore.cmor._fixes.cmip6.access_esm1_5 import Cl, Cli, Clw, Hus, Zg\n'), ((4757, 4766), 'esmvalcore.cmor._fixes.cmip6.access_esm1_5.Hus', 'Hus', (['None'], {}), '(None)\n', (4760, 4766), False, 'from esmvalcore.cmor._fixes.cmip6.access_esm1_5 import Cl, Cli, Clw, Hus, Zg\n'), ((5890, 5898), 'esmvalcore.cmor._fixes.cmip6.access_esm1_5.Zg', 'Zg', (['None'], {}), '(None)\n', (5892, 5898), False, 'from esmvalcore.cmor._fixes.cmip6.access_esm1_5 import Cl, Cli, Clw, Hus, Zg\n')]
|
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
from builtins import * # NOQA
standard_library.install_aliases() # NOQA
import unittest
from chainer import testing
import numpy as np
import basetest_dqn_like as base
import chainerrl
from chainerrl.agents.dqn import compute_value_loss
from chainerrl.agents.dqn import compute_weighted_value_loss
from chainerrl.agents.dqn import DQN
from basetest_training import _TestBatchTrainingMixin
class TestDQNOnDiscreteABC(
_TestBatchTrainingMixin, base._TestDQNOnDiscreteABC):
def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu):
return DQN(q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer,
replay_start_size=100, target_update_interval=100)
class TestDQNOnDiscreteABCBoltzmann(
_TestBatchTrainingMixin, base._TestDQNOnDiscreteABC):
def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu):
explorer = chainerrl.explorers.Boltzmann()
return DQN(q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer,
replay_start_size=100, target_update_interval=100)
class TestDQNOnContinuousABC(
_TestBatchTrainingMixin, base._TestDQNOnContinuousABC):
def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu):
return DQN(q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer,
replay_start_size=100, target_update_interval=100)
# Batch training with recurrent models is currently not supported
class TestDQNOnDiscretePOABC(base._TestDQNOnDiscretePOABC):
def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu):
return DQN(q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer,
replay_start_size=100, target_update_interval=100,
episodic_update=True)
def _huber_loss_1(a):
if abs(a) < 1:
return 0.5 * a ** 2
else:
return abs(a) - 0.5
@testing.parameterize(
*testing.product({
'batch_accumulator': ['mean', 'sum'],
'clip_delta': [True, False],
})
)
class TestComputeValueLoss(unittest.TestCase):
def setUp(self):
self.y = np.asarray([1.0, 2.0, 3.0, 4.0], dtype='f')
self.t = np.asarray([2.1, 2.2, 2.3, 2.4], dtype='f')
if self.clip_delta:
self.gt_losses = np.asarray(
[_huber_loss_1(a) for a in self.y - self.t])
else:
self.gt_losses = np.asarray(
[0.5 * a ** 2 for a in self.y - self.t])
def test_not_weighted(self):
loss = compute_value_loss(
self.y, self.t, clip_delta=self.clip_delta,
batch_accumulator=self.batch_accumulator).array
if self.batch_accumulator == 'mean':
gt_loss = self.gt_losses.mean()
else:
gt_loss = self.gt_losses.sum()
self.assertAlmostEqual(loss, gt_loss, places=5)
def test_uniformly_weighted(self):
# Uniform weights
w1 = np.ones(self.y.size, dtype='f')
loss_w1 = compute_weighted_value_loss(
self.y, self.t, clip_delta=self.clip_delta,
batch_accumulator=self.batch_accumulator,
weights=w1).array
if self.batch_accumulator == 'mean':
gt_loss = self.gt_losses.mean()
else:
gt_loss = self.gt_losses.sum()
self.assertAlmostEqual(loss_w1, gt_loss, places=5)
def test_randomly_weighted(self):
# Random weights
wu = np.random.uniform(low=0, high=2, size=self.y.size).astype('f')
loss_wu = compute_weighted_value_loss(
self.y, self.t, clip_delta=self.clip_delta,
batch_accumulator=self.batch_accumulator,
weights=wu).array
if self.batch_accumulator == 'mean':
gt_loss = (self.gt_losses * wu).mean()
else:
gt_loss = (self.gt_losses * wu).sum()
self.assertAlmostEqual(loss_wu, gt_loss, places=5)
|
[
"chainerrl.agents.dqn.DQN",
"chainerrl.explorers.Boltzmann",
"chainer.testing.product",
"chainerrl.agents.dqn.compute_value_loss",
"numpy.random.uniform",
"future.standard_library.install_aliases",
"numpy.asarray",
"chainerrl.agents.dqn.compute_weighted_value_loss",
"numpy.ones"
] |
[((216, 250), 'future.standard_library.install_aliases', 'standard_library.install_aliases', ([], {}), '()\n', (248, 250), False, 'from future import standard_library\n'), ((756, 872), 'chainerrl.agents.dqn.DQN', 'DQN', (['q_func', 'opt', 'rbuf'], {'gpu': 'gpu', 'gamma': '(0.9)', 'explorer': 'explorer', 'replay_start_size': '(100)', 'target_update_interval': '(100)'}), '(q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer,\n replay_start_size=100, target_update_interval=100)\n', (759, 872), False, 'from chainerrl.agents.dqn import DQN\n'), ((1078, 1109), 'chainerrl.explorers.Boltzmann', 'chainerrl.explorers.Boltzmann', ([], {}), '()\n', (1107, 1109), False, 'import chainerrl\n'), ((1125, 1241), 'chainerrl.agents.dqn.DQN', 'DQN', (['q_func', 'opt', 'rbuf'], {'gpu': 'gpu', 'gamma': '(0.9)', 'explorer': 'explorer', 'replay_start_size': '(100)', 'target_update_interval': '(100)'}), '(q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer,\n replay_start_size=100, target_update_interval=100)\n', (1128, 1241), False, 'from chainerrl.agents.dqn import DQN\n'), ((1438, 1554), 'chainerrl.agents.dqn.DQN', 'DQN', (['q_func', 'opt', 'rbuf'], {'gpu': 'gpu', 'gamma': '(0.9)', 'explorer': 'explorer', 'replay_start_size': '(100)', 'target_update_interval': '(100)'}), '(q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer,\n replay_start_size=100, target_update_interval=100)\n', (1441, 1554), False, 'from chainerrl.agents.dqn import DQN\n'), ((1783, 1921), 'chainerrl.agents.dqn.DQN', 'DQN', (['q_func', 'opt', 'rbuf'], {'gpu': 'gpu', 'gamma': '(0.9)', 'explorer': 'explorer', 'replay_start_size': '(100)', 'target_update_interval': '(100)', 'episodic_update': '(True)'}), '(q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer,\n replay_start_size=100, target_update_interval=100, episodic_update=True)\n', (1786, 1921), False, 'from chainerrl.agents.dqn import DQN\n'), ((2291, 2334), 'numpy.asarray', 'np.asarray', (['[1.0, 2.0, 3.0, 4.0]'], {'dtype': '"""f"""'}), "([1.0, 2.0, 3.0, 4.0], dtype='f')\n", (2301, 2334), True, 'import numpy as np\n'), ((2352, 2395), 'numpy.asarray', 'np.asarray', (['[2.1, 2.2, 2.3, 2.4]'], {'dtype': '"""f"""'}), "([2.1, 2.2, 2.3, 2.4], dtype='f')\n", (2362, 2395), True, 'import numpy as np\n'), ((3105, 3136), 'numpy.ones', 'np.ones', (['self.y.size'], {'dtype': '"""f"""'}), "(self.y.size, dtype='f')\n", (3112, 3136), True, 'import numpy as np\n'), ((2095, 2183), 'chainer.testing.product', 'testing.product', (["{'batch_accumulator': ['mean', 'sum'], 'clip_delta': [True, False]}"], {}), "({'batch_accumulator': ['mean', 'sum'], 'clip_delta': [True,\n False]})\n", (2110, 2183), False, 'from chainer import testing\n'), ((2569, 2622), 'numpy.asarray', 'np.asarray', (['[(0.5 * a ** 2) for a in self.y - self.t]'], {}), '([(0.5 * a ** 2) for a in self.y - self.t])\n', (2579, 2622), True, 'import numpy as np\n'), ((2687, 2795), 'chainerrl.agents.dqn.compute_value_loss', 'compute_value_loss', (['self.y', 'self.t'], {'clip_delta': 'self.clip_delta', 'batch_accumulator': 'self.batch_accumulator'}), '(self.y, self.t, clip_delta=self.clip_delta,\n batch_accumulator=self.batch_accumulator)\n', (2705, 2795), False, 'from chainerrl.agents.dqn import compute_value_loss\n'), ((3156, 3285), 'chainerrl.agents.dqn.compute_weighted_value_loss', 'compute_weighted_value_loss', (['self.y', 'self.t'], {'clip_delta': 'self.clip_delta', 'batch_accumulator': 'self.batch_accumulator', 'weights': 'w1'}), '(self.y, self.t, clip_delta=self.clip_delta,\n batch_accumulator=self.batch_accumulator, weights=w1)\n', (3183, 3285), False, 'from chainerrl.agents.dqn import compute_weighted_value_loss\n'), ((3690, 3819), 'chainerrl.agents.dqn.compute_weighted_value_loss', 'compute_weighted_value_loss', (['self.y', 'self.t'], {'clip_delta': 'self.clip_delta', 'batch_accumulator': 'self.batch_accumulator', 'weights': 'wu'}), '(self.y, self.t, clip_delta=self.clip_delta,\n batch_accumulator=self.batch_accumulator, weights=wu)\n', (3717, 3819), False, 'from chainerrl.agents.dqn import compute_weighted_value_loss\n'), ((3608, 3658), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0)', 'high': '(2)', 'size': 'self.y.size'}), '(low=0, high=2, size=self.y.size)\n', (3625, 3658), True, 'import numpy as np\n')]
|
import streamlit as st
from streamlit_drawable_canvas import st_canvas
from PIL import Image
import numpy as np
import torch
import torch.nn.functional as F
import torchvision.transforms as transforms
import json
# Specify canvas parameters in application
stroke_width = st.sidebar.slider(
label='Stroke width:',
min_value=1,
max_value=25,
value=3
)
drawing_mode = st.sidebar.selectbox(
label='Drawing tool:',
options=('freedraw', 'line', 'rect', 'circle', 'transform')
)
realtime_update = st.sidebar.checkbox(
label='Update in realtime',
value=True
)
# Create a canvas component
canvas_result = st_canvas(
stroke_width=stroke_width,
stroke_color='black',
update_streamlit=realtime_update,
height=400,
width=400,
drawing_mode=drawing_mode,
key='canvas',
)
@st.cache
def load_model():
model = torch.load(
f='quickdraw/models/model.pt',
map_location=torch.device('cpu')
)
return model
model = load_model()
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.9720, 0.9720, 0.9720),
(0.1559, 0.1559, 0.1559)) # Normalize with the mean and std of the whole dataset
])
# Dictionary to map id to name of the class
with open('quickdraw/categories/id_to_class.json') as file:
id_to_class = json.load(file)
if canvas_result.image_data is not None:
image = canvas_result.image_data
# Convert RGBA image to RGB (PIL doesn't convert as I want)
image_rgb = Image.fromarray(np.uint8(image)).convert(mode='P')
image_rgb = np.array(image_rgb)[:, :, np.newaxis]
image_rgb = np.repeat(image_rgb, repeats=3, axis=2)
# Use the same transformation used in training and add batch dimension
image_rgb = torch.unsqueeze(transform(image_rgb), dim=0)
# Compute logits
y_lgts = model(image_rgb)
# Compute scores
y_prob = F.softmax(y_lgts, dim=1)
# Compute the top 3 predictions
top_3 = torch.topk(y_prob, k=3)
preds = top_3.indices.numpy().flatten()
probs = top_3.values.detach().numpy().flatten()
labels = [id_to_class[str(i)] for i in preds]
predictions = dict(zip(labels, probs))
st.write('**Top 3 predictions:**')
st.write(predictions)
|
[
"streamlit.sidebar.slider",
"streamlit_drawable_canvas.st_canvas",
"json.load",
"torch.topk",
"numpy.uint8",
"streamlit.sidebar.checkbox",
"streamlit.write",
"torch.nn.functional.softmax",
"torchvision.transforms.ToTensor",
"streamlit.sidebar.selectbox",
"numpy.array",
"torch.device",
"torchvision.transforms.Normalize",
"numpy.repeat"
] |
[((275, 351), 'streamlit.sidebar.slider', 'st.sidebar.slider', ([], {'label': '"""Stroke width:"""', 'min_value': '(1)', 'max_value': '(25)', 'value': '(3)'}), "(label='Stroke width:', min_value=1, max_value=25, value=3)\n", (292, 351), True, 'import streamlit as st\n'), ((387, 495), 'streamlit.sidebar.selectbox', 'st.sidebar.selectbox', ([], {'label': '"""Drawing tool:"""', 'options': "('freedraw', 'line', 'rect', 'circle', 'transform')"}), "(label='Drawing tool:', options=('freedraw', 'line',\n 'rect', 'circle', 'transform'))\n", (407, 495), True, 'import streamlit as st\n'), ((521, 580), 'streamlit.sidebar.checkbox', 'st.sidebar.checkbox', ([], {'label': '"""Update in realtime"""', 'value': '(True)'}), "(label='Update in realtime', value=True)\n", (540, 580), True, 'import streamlit as st\n'), ((637, 803), 'streamlit_drawable_canvas.st_canvas', 'st_canvas', ([], {'stroke_width': 'stroke_width', 'stroke_color': '"""black"""', 'update_streamlit': 'realtime_update', 'height': '(400)', 'width': '(400)', 'drawing_mode': 'drawing_mode', 'key': '"""canvas"""'}), "(stroke_width=stroke_width, stroke_color='black', update_streamlit\n =realtime_update, height=400, width=400, drawing_mode=drawing_mode, key\n ='canvas')\n", (646, 803), False, 'from streamlit_drawable_canvas import st_canvas\n'), ((1362, 1377), 'json.load', 'json.load', (['file'], {}), '(file)\n', (1371, 1377), False, 'import json\n'), ((1663, 1702), 'numpy.repeat', 'np.repeat', (['image_rgb'], {'repeats': '(3)', 'axis': '(2)'}), '(image_rgb, repeats=3, axis=2)\n', (1672, 1702), True, 'import numpy as np\n'), ((1925, 1949), 'torch.nn.functional.softmax', 'F.softmax', (['y_lgts'], {'dim': '(1)'}), '(y_lgts, dim=1)\n', (1934, 1949), True, 'import torch.nn.functional as F\n'), ((1998, 2021), 'torch.topk', 'torch.topk', (['y_prob'], {'k': '(3)'}), '(y_prob, k=3)\n', (2008, 2021), False, 'import torch\n'), ((2225, 2259), 'streamlit.write', 'st.write', (['"""**Top 3 predictions:**"""'], {}), "('**Top 3 predictions:**')\n", (2233, 2259), True, 'import streamlit as st\n'), ((2264, 2285), 'streamlit.write', 'st.write', (['predictions'], {}), '(predictions)\n', (2272, 2285), True, 'import streamlit as st\n'), ((1046, 1067), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1065, 1067), True, 'import torchvision.transforms as transforms\n'), ((1078, 1147), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.972, 0.972, 0.972)', '(0.1559, 0.1559, 0.1559)'], {}), '((0.972, 0.972, 0.972), (0.1559, 0.1559, 0.1559))\n', (1098, 1147), True, 'import torchvision.transforms as transforms\n'), ((1609, 1628), 'numpy.array', 'np.array', (['image_rgb'], {}), '(image_rgb)\n', (1617, 1628), True, 'import numpy as np\n'), ((938, 957), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (950, 957), False, 'import torch\n'), ((1558, 1573), 'numpy.uint8', 'np.uint8', (['image'], {}), '(image)\n', (1566, 1573), True, 'import numpy as np\n')]
|
import numpy as np
def float_ndarray_to_dict(arr):
return np_arr_to_dict(arr)
def dict_to_float_ndarray(string):
return dict_to_np_arr(string)
def identity(e):
return e
def float_to_string(num):
return str(num)
def string_to_float(string):
return float(string)
def np_arr_to_dict(arr):
return {'arr': arr.tolist(),
'shape':list(arr.shape),
'dtype':str(arr.dtype)
}
def dict_to_np_arr(data):
arr, shape, dtype = data['arr'], data['shape'], data['dtype']
return np.array(arr, dtype=dtype).reshape(tuple(shape))
|
[
"numpy.array"
] |
[((519, 545), 'numpy.array', 'np.array', (['arr'], {'dtype': 'dtype'}), '(arr, dtype=dtype)\n', (527, 545), True, 'import numpy as np\n')]
|
import math, random, copy
import numpy as np
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
from DGN import DGN
from buffer import ReplayBuffer
from surviving import Surviving
from config import *
USE_CUDA = torch.cuda.is_available()
env = Surviving(n_agent = 100)
n_ant = env.n_agent
observation_space = env.len_obs
n_actions = env.n_action
buff = ReplayBuffer(capacity)
model = DGN(n_ant,observation_space,hidden_dim,n_actions)
model_tar = DGN(n_ant,observation_space,hidden_dim,n_actions)
model = model.cuda()
model_tar = model_tar.cuda()
optimizer = optim.Adam(model.parameters(), lr = 0.0001)
O = np.ones((batch_size,n_ant,observation_space))
Next_O = np.ones((batch_size,n_ant,observation_space))
Matrix = np.ones((batch_size,n_ant,n_ant))
Next_Matrix = np.ones((batch_size,n_ant,n_ant))
f = open('r.txt','w')
while i_episode<n_episode:
if i_episode > 100:
epsilon -= 0.0004
if epsilon < 0.1:
epsilon = 0.1
i_episode+=1
steps = 0
obs, adj = env.reset()
while steps < max_step:
steps+=1
action=[]
q = model(torch.Tensor(np.array([obs])).cuda(), torch.Tensor(adj).cuda())[0]
for i in range(n_ant):
if np.random.rand() < epsilon:
a = np.random.randint(n_actions)
else:
a = q[i].argmax().item()
action.append(a)
next_obs, next_adj, reward, terminated = env.step(action)
buff.add(np.array(obs),action,reward,np.array(next_obs),adj,next_adj,terminated)
obs = next_obs
adj = next_adj
score += sum(reward)
if i_episode%20==0:
print(score/2000)
f.write(str(score/2000)+'\n')
score = 0
if i_episode < 100:
continue
for e in range(n_epoch):
batch = buff.getBatch(batch_size)
for j in range(batch_size):
sample = batch[j]
O[j] = sample[0]
Next_O[j] = sample[3]
Matrix[j] = sample[4]
Next_Matrix[j] = sample[5]
q_values = model(torch.Tensor(O).cuda(), torch.Tensor(Matrix).cuda())
target_q_values = model_tar(torch.Tensor(Next_O).cuda(), torch.Tensor(Next_Matrix).cuda()).max(dim = 2)[0]
target_q_values = np.array(target_q_values.cpu().data)
expected_q = np.array(q_values.cpu().data)
for j in range(batch_size):
sample = batch[j]
for i in range(n_ant):
expected_q[j][i][sample[1][i]] = sample[2][i] + (1-sample[6])*GAMMA*target_q_values[j][i]
loss = (q_values - torch.Tensor(expected_q).cuda()).pow(2).mean()
optimizer.zero_grad()
loss.backward()
optimizer.step()
if i_episode%5 == 0:
model_tar.load_state_dict(model.state_dict())
|
[
"surviving.Surviving",
"numpy.ones",
"DGN.DGN",
"numpy.random.randint",
"torch.cuda.is_available",
"numpy.array",
"torch.Tensor",
"numpy.random.rand",
"buffer.ReplayBuffer"
] |
[((346, 371), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (369, 371), False, 'import torch\n'), ((379, 401), 'surviving.Surviving', 'Surviving', ([], {'n_agent': '(100)'}), '(n_agent=100)\n', (388, 401), False, 'from surviving import Surviving\n'), ((489, 511), 'buffer.ReplayBuffer', 'ReplayBuffer', (['capacity'], {}), '(capacity)\n', (501, 511), False, 'from buffer import ReplayBuffer\n'), ((520, 572), 'DGN.DGN', 'DGN', (['n_ant', 'observation_space', 'hidden_dim', 'n_actions'], {}), '(n_ant, observation_space, hidden_dim, n_actions)\n', (523, 572), False, 'from DGN import DGN\n'), ((582, 634), 'DGN.DGN', 'DGN', (['n_ant', 'observation_space', 'hidden_dim', 'n_actions'], {}), '(n_ant, observation_space, hidden_dim, n_actions)\n', (585, 634), False, 'from DGN import DGN\n'), ((743, 790), 'numpy.ones', 'np.ones', (['(batch_size, n_ant, observation_space)'], {}), '((batch_size, n_ant, observation_space))\n', (750, 790), True, 'import numpy as np\n'), ((798, 845), 'numpy.ones', 'np.ones', (['(batch_size, n_ant, observation_space)'], {}), '((batch_size, n_ant, observation_space))\n', (805, 845), True, 'import numpy as np\n'), ((853, 888), 'numpy.ones', 'np.ones', (['(batch_size, n_ant, n_ant)'], {}), '((batch_size, n_ant, n_ant))\n', (860, 888), True, 'import numpy as np\n'), ((901, 936), 'numpy.ones', 'np.ones', (['(batch_size, n_ant, n_ant)'], {}), '((batch_size, n_ant, n_ant))\n', (908, 936), True, 'import numpy as np\n'), ((1469, 1482), 'numpy.array', 'np.array', (['obs'], {}), '(obs)\n', (1477, 1482), True, 'import numpy as np\n'), ((1497, 1515), 'numpy.array', 'np.array', (['next_obs'], {}), '(next_obs)\n', (1505, 1515), True, 'import numpy as np\n'), ((1273, 1289), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (1287, 1289), True, 'import numpy as np\n'), ((1309, 1337), 'numpy.random.randint', 'np.random.randint', (['n_actions'], {}), '(n_actions)\n', (1326, 1337), True, 'import numpy as np\n'), ((1954, 1969), 'torch.Tensor', 'torch.Tensor', (['O'], {}), '(O)\n', (1966, 1969), False, 'import torch\n'), ((1978, 1998), 'torch.Tensor', 'torch.Tensor', (['Matrix'], {}), '(Matrix)\n', (1990, 1998), False, 'import torch\n'), ((1213, 1230), 'torch.Tensor', 'torch.Tensor', (['adj'], {}), '(adj)\n', (1225, 1230), False, 'import torch\n'), ((1188, 1203), 'numpy.array', 'np.array', (['[obs]'], {}), '([obs])\n', (1196, 1203), True, 'import numpy as np\n'), ((2037, 2057), 'torch.Tensor', 'torch.Tensor', (['Next_O'], {}), '(Next_O)\n', (2049, 2057), False, 'import torch\n'), ((2066, 2091), 'torch.Tensor', 'torch.Tensor', (['Next_Matrix'], {}), '(Next_Matrix)\n', (2078, 2091), False, 'import torch\n'), ((2416, 2440), 'torch.Tensor', 'torch.Tensor', (['expected_q'], {}), '(expected_q)\n', (2428, 2440), False, 'import torch\n')]
|
import gym
from typing import List, Tuple, Dict
import numpy as np
from gym import spaces
from core.simulation import Simulation
from service import global_constants
class JsbsimGymEnvironmentWrapper(gym.Env):
"""Custom Environment that follows gym interface"""
metadata = {'render.modes': ['human']}
def __init__(self, configuration_path: str=global_constants.DEFAULT_CONFIGURATION_PATH):
super(JsbsimGymEnvironmentWrapper, self).__init__()
self.sim = Simulation(configuration_path=configuration_path)
self._dimensions = 1
self.action_space = spaces.Box(
low=-0,
high=1,
shape=(self._dimensions,),
dtype=np.float32
)
self.observation_space = spaces.Box(
low=np.inf,
high=np.inf,
shape=self._getObs().shape, # Passt sich damit automatisch an die Beobachtung an
dtype=np.float32
)
def reset(self):
self.sim.reset_with_initial_condition()
return self._getObs(), self._calcRewards(), self._calcDones(), {}
def step(self, actions: List[np.ndarray]) -> Tuple[np.ndarray, np.ndarray, np.ndarray, Dict]:
self.sim.set_properties('fcs/throttle-cmd-norm', actions[0])
self.sim.run()
return self._getObs(), self._calcRewards(), self._calcDones(), {}
def _getObs(self) -> np.ndarray:
state = self.sim.get_state()
return np.array(list(state.values()))
def _calcRewards(self) -> np.ndarray:
rewAgent0 = 0
return np.array([rewAgent0], dtype=np.float32)
def _calcDones(self) -> np.ndarray:
dones = np.zeros(1)
return dones
def render(self, mode='human'):
pass
def close(self):
pass
def seed(self, seed=None) -> None:
pass
if __name__ == "__main__":
env = JsbsimGymEnvironmentWrapper()
ob = env.reset()
action = env.action_space.sample()
for _ in range(10):
print(env.step(action))
|
[
"numpy.zeros",
"numpy.array",
"gym.spaces.Box",
"core.simulation.Simulation"
] |
[((482, 531), 'core.simulation.Simulation', 'Simulation', ([], {'configuration_path': 'configuration_path'}), '(configuration_path=configuration_path)\n', (492, 531), False, 'from core.simulation import Simulation\n'), ((589, 660), 'gym.spaces.Box', 'spaces.Box', ([], {'low': '(-0)', 'high': '(1)', 'shape': '(self._dimensions,)', 'dtype': 'np.float32'}), '(low=-0, high=1, shape=(self._dimensions,), dtype=np.float32)\n', (599, 660), False, 'from gym import spaces\n'), ((1556, 1595), 'numpy.array', 'np.array', (['[rewAgent0]'], {'dtype': 'np.float32'}), '([rewAgent0], dtype=np.float32)\n', (1564, 1595), True, 'import numpy as np\n'), ((1653, 1664), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (1661, 1664), True, 'import numpy as np\n')]
|
from typing import Any, Optional, Union
import numpy as np
import pandas as pd
from crowdkit.aggregation.base_aggregator import BaseAggregator
from crowdkit.aggregation import MajorityVote
def _check_answers(answers: pd.DataFrame) -> None:
if not isinstance(answers, pd.DataFrame):
raise TypeError('Working only with pandas DataFrame')
assert 'task' in answers, 'There is no "task" column in answers'
assert 'performer' in answers, 'There is no "performer" column in answers'
assert 'label' in answers, 'There is no "label" column in answers'
def _label_probability(row: pd.Series, label: Any, n_labels: int) -> float:
"""Numerator in the Bayes formula"""
return row['skill'] if row['label'] == label else (1.0 - row['skill']) / (n_labels - 1)
def _task_consistency(row: pd.Series) -> float:
"""Posterior probability for a single task"""
return row[row['aggregated_label']] / row['denominator'] if row['denominator'] != 0 else 0.0
def consistency(answers: pd.DataFrame,
performers_skills: Optional[pd.Series] = None,
aggregator: BaseAggregator = MajorityVote(),
by_task: bool = False) -> Union[float, pd.Series]:
"""
Consistency metric: posterior probability of aggregated label given performers skills
calculated using standard Dawid-Skene model.
Args:
answers (pandas.DataFrame): A data frame containing `task`, `performer` and `label` columns.
performers_skills (Optional[pandas.Series]): performers skills e.g. golden set skills. If not provided,
uses aggregator's `performers_skills` attribute.
aggregator (aggregation.BaseAggregator): aggregation method, default: MajorityVote
by_task (bool): if set, returns consistencies for every task in provided data frame.
Returns:
Union[float, pd.Series]
"""
_check_answers(answers)
aggregated = aggregator.fit_predict(answers)
if performers_skills is None and hasattr(aggregator, 'skills_'):
performers_skills = aggregator.skills_
else:
raise AssertionError('This aggregator is not supported. Please, provide performers skills.')
answers = answers.copy(deep=False)
answers.set_index('task', inplace=True)
answers = answers.reset_index().set_index('performer')
answers['skill'] = performers_skills
answers.reset_index(inplace=True)
labels = pd.unique(answers.label)
for label in labels:
answers[label] = answers.apply(lambda row: _label_probability(row, label, len(labels)), axis=1)
labels_proba = answers.groupby('task').prod()
labels_proba['aggregated_label'] = aggregated
labels_proba['denominator'] = labels_proba[list(labels)].sum(axis=1)
consistecies = labels_proba.apply(_task_consistency, axis=1)
if by_task:
return consistecies
else:
return consistecies.mean()
def _task_uncertainty(row, labels):
if row['denominator'] == 0:
row[labels] = 1 / len(labels)
else:
row[labels] /= row['denominator']
softmax = row[labels]
log_softmax = np.log(row[list(labels)])
return -np.sum(softmax * log_softmax)
def uncertainty(answers, performers_skills, by_task: bool = False) -> Union[float, pd.Series]:
"""
Label uncertainty metric: entropy of labels probability distribution.
Args:
answers (pandas.DataFrame): A data frame containing `task`, `performer` and `label` columns.
performers_skills (pandas.Series): performers skills e.g. golden set skills. If not provided,
uses aggregator's `performers_skills` attribute.
by_task (bool): if set, returns consistencies for every task in provided data frame.
Returns:
Union[float, pd.Series]
"""
_check_answers(answers)
answers = answers.copy(deep=False)
answers.set_index('task', inplace=True)
answers = answers.reset_index().set_index('performer')
answers['skill'] = performers_skills
answers.reset_index(inplace=True)
labels = pd.unique(answers.label)
for label in labels:
answers[label] = answers.apply(lambda row: _label_probability(row, label, len(labels)), axis=1)
labels_proba = answers.groupby('task').prod()
labels_proba['denominator'] = labels_proba[list(labels)].sum(axis=1)
uncertainties = labels_proba.apply(lambda row: _task_uncertainty(row, list(labels)), axis=1)
if by_task:
return uncertainties
else:
return uncertainties.mean()
|
[
"crowdkit.aggregation.MajorityVote",
"numpy.sum",
"pandas.unique"
] |
[((1127, 1141), 'crowdkit.aggregation.MajorityVote', 'MajorityVote', ([], {}), '()\n', (1139, 1141), False, 'from crowdkit.aggregation import MajorityVote\n'), ((2446, 2470), 'pandas.unique', 'pd.unique', (['answers.label'], {}), '(answers.label)\n', (2455, 2470), True, 'import pandas as pd\n'), ((4086, 4110), 'pandas.unique', 'pd.unique', (['answers.label'], {}), '(answers.label)\n', (4095, 4110), True, 'import pandas as pd\n'), ((3170, 3199), 'numpy.sum', 'np.sum', (['(softmax * log_softmax)'], {}), '(softmax * log_softmax)\n', (3176, 3199), True, 'import numpy as np\n')]
|
# Copyright 2021 Intel Corporation
#
# 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.
from sklearnex import patch_sklearn
patch_sklearn()
import numpy as np
from sklearn.cluster import DBSCAN
from daal4py.oneapi import sycl_context
X = np.array([[1., 2.], [2., 2.], [2., 3.],
[8., 7.], [8., 8.], [25., 80.]], dtype=np.float32)
with sycl_context("gpu"):
clustering = DBSCAN(eps=3, min_samples=2).fit(X)
print("DBSCAN components: ", clustering.components_, "\nDBSCAN labels: ",clustering.labels_)
resultsDict = {}
resultsDict['X'] = X
resultsDict['labels'] = clustering.labels_
resultsDict['components'] = clustering.components_
import pickle
with open('resultsDict.pkl', 'wb') as handle:
pickle.dump(resultsDict, handle, protocol=pickle.HIGHEST_PROTOCOL)
|
[
"pickle.dump",
"numpy.array",
"daal4py.oneapi.sycl_context",
"sklearnex.patch_sklearn",
"sklearn.cluster.DBSCAN"
] |
[((620, 635), 'sklearnex.patch_sklearn', 'patch_sklearn', ([], {}), '()\n', (633, 635), False, 'from sklearnex import patch_sklearn\n'), ((736, 842), 'numpy.array', 'np.array', (['[[1.0, 2.0], [2.0, 2.0], [2.0, 3.0], [8.0, 7.0], [8.0, 8.0], [25.0, 80.0]]'], {'dtype': 'np.float32'}), '([[1.0, 2.0], [2.0, 2.0], [2.0, 3.0], [8.0, 7.0], [8.0, 8.0], [25.0,\n 80.0]], dtype=np.float32)\n', (744, 842), True, 'import numpy as np\n'), ((844, 863), 'daal4py.oneapi.sycl_context', 'sycl_context', (['"""gpu"""'], {}), "('gpu')\n", (856, 863), False, 'from daal4py.oneapi import sycl_context\n'), ((1208, 1274), 'pickle.dump', 'pickle.dump', (['resultsDict', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(resultsDict, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (1219, 1274), False, 'import pickle\n'), ((882, 910), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {'eps': '(3)', 'min_samples': '(2)'}), '(eps=3, min_samples=2)\n', (888, 910), False, 'from sklearn.cluster import DBSCAN\n')]
|
import numpy as np
import atexit
import sys
aims = sys.modules['soma.aims']
'''
IO formats readers / writers written in python for aims.
Currently:
Numpy format for matrices
'''
class NpyFormat(aims.FileFormat_SparseOrDenseMatrix):
def read(self, filename, obj, context, options=None):
mat = np.load(filename)
# currently we need to perform a full copy of the array because
# we cannot prevent it from deleting (when getting back to the C++
# layer the python wrapper is destroyed and any references it holds
# also disapear.
# Or we should manually increment the ref counter in the numpy PyObject
# but it would never be destroyed then.
#vol = aims.Volume(mat)
#vol._npy = mat
vol = aims.Volume(mat.shape, dtype=mat.dtype)
np.asarray(vol)[:, :, 0, 0] = mat
if isinstance(obj, aims.carto.AllocatorContext):
# return the object variant
options = context
context = obj
obj = aims.SparseOrDenseMatrix()
obj.setMatrix(vol)
return obj
# otherwise fill in obj
obj.setMatrix(vol)
return True
def write(self, filename, obj, options):
mat = np.asarray(obj.asDense())
np.save(filename, mat)
hdr = obj.header()
aims.write(hdr, '%s.minf' % filename)
return True
class NpyFinderFormat(aims.FinderFormat):
def check(self, filename, finder):
if filename.endswith('.npy'):
hdr = {
'file_type': 'NPY',
'object_type': 'SparseMatrix',
'data_type': 'DOUBLE',
}
finder.setHeader(hdr)
finder.setObjectType('SparseMatrix')
finder.setDataType('DOUBLE')
return True
return False
def remove_python_formats():
aims.Finder.unregisterFormat('NUMPY')
aims.FileFormatDictionary_SparseOrDenseMatrix.unregisterFormat('NUMPY')
aims.Finder.registerFormat('NUMPY', NpyFinderFormat(), ['npy'])
aims.FileFormatDictionary_SparseOrDenseMatrix.registerFormat(
'NUMPY', NpyFormat(), ['npy'])
atexit.register(remove_python_formats)
|
[
"atexit.register",
"numpy.load",
"numpy.save",
"numpy.asarray"
] |
[((2154, 2192), 'atexit.register', 'atexit.register', (['remove_python_formats'], {}), '(remove_python_formats)\n', (2169, 2192), False, 'import atexit\n'), ((309, 326), 'numpy.load', 'np.load', (['filename'], {}), '(filename)\n', (316, 326), True, 'import numpy as np\n'), ((1280, 1302), 'numpy.save', 'np.save', (['filename', 'mat'], {}), '(filename, mat)\n', (1287, 1302), True, 'import numpy as np\n'), ((821, 836), 'numpy.asarray', 'np.asarray', (['vol'], {}), '(vol)\n', (831, 836), True, 'import numpy as np\n')]
|
import sys, time, itertools, resource, logging
from multiprocessing import Pool, Process
from util import psutil_process, print_datetime, array2string, PyTorchDType as dtype
import torch
import numpy as np
import gurobipy as grb
from scipy.special import loggamma
from sampleForIntegral import integrateOfExponentialOverSimplexInduction2
def estimateParametersY(self, max_iter=10):
logging.info(f'{print_datetime()}Estimating M and sigma_yx_inv')
As = []
Bs = []
sizes = np.fromiter(map(np.size, self.YTs), dtype=float)
for YT, E, XT in zip(self.YTs, self.Es, self.XTs):
if self.dropout_mode == 'raw':
As.append(YT.T @ XT)
Bs.append(XT.T @ XT)
else:
raise NotImplementedError
m = grb.Model('M')
m.setParam('OutputFlag', False)
m.Params.Threads = 1
if self.M_constraint == 'sum2one':
vM = m.addVars(self.GG, self.K, lb=0.)
m.addConstrs((vM.sum('*', i) == 1 for i in range(self.K)))
else:
raise NotImplementedError
for iiter in range(max_iter):
obj = 0
for beta, YT, sigma_yx_inv, A, B, G, XT in zip(self.betas, self.YTs, self.sigma_yx_invs, As, Bs, self.Gs, self.XTs):
# constant terms
if self.dropout_mode == 'raw':
t = YT.ravel()
else:
raise NotImplementedError
obj += beta * sigma_yx_inv**2 * np.dot(t, t)
# linear terms
t = -2 * beta * sigma_yx_inv**2 * A
obj += grb.quicksum([t[i, j] * vM[i, j] for i in range(G) for j in range(self.K)])
# quadratic terms
if self.dropout_mode == 'raw':
t = beta * sigma_yx_inv**2 * B
t[np.diag_indices(self.K)] += 1e-5
obj += grb.quicksum([t[i, i] * vM[k, i] * vM[k, i] for k in range(G) for i in range(self.K)])
t *= 2
obj += grb.quicksum([t[i, j] * vM[k, i] * vM[k, j] for k in range(G) for i in range(self.K) for j in range(i+1, self.K)])
else:
raise NotImplementedError
del t, beta, YT, A, B, G
kk = 0
if kk != 0:
obj += grb.quicksum([kk/2 * vM[k, i] * vM[k, i] for k in range(self.GG) for i in range(self.K)])
m.setObjective(obj, grb.GRB.MINIMIZE)
m.optimize()
self.M = np.array([[vM[i, j].x for j in range(self.K)] for i in range(self.GG)])
if self.M_constraint in ['sum2one', 'none']:
pass
elif self.M_constraint == 'L1':
self.M /= np.abs(self.M).sum(0, keepdims=True)
elif self.M_constraint == 'L2':
self.M /= np.sqrt((self.M ** 2).sum(0, keepdims=True))
else:
raise NotImplementedError
last_sigma_yx_invs = np.copy(self.sigma_yx_invs)
ds = np.array([
np.dot(YT.ravel(), YT.ravel()) - 2*np.dot(A.ravel(), self.M[:G].ravel()) + np.dot(B.ravel(), (self.M[:G].T @ self.M[:G]).ravel())
for YT, A, B, G in zip(self.YTs, As, Bs, self.Gs)
])
if self.sigma_yx_inv_mode == 'separate':
t = ds / sizes
self.sigma_yx_invs = 1. / np.sqrt(t)
elif self.sigma_yx_inv_mode == 'average':
t = np.dot(self.betas, ds) / np.dot(self.betas, sizes)
self.sigma_yx_invs = np.full(self.num_repli, 1 / (np.sqrt(t) + 1e-20))
elif self.sigma_yx_inv_mode.startswith('average '):
idx = np.array(list(map(int, self.sigma_yx_inv_mode.split(' ')[1:])))
t = np.dot(self.betas[idx], ds[idx]) / np.dot(self.betas[idx], sizes[idx])
self.sigma_yx_invs = np.full(self.num_repli, 1 / (np.sqrt(t) + 1e-20))
else:
raise NotImplementedError
d = self.sigma_yx_invs - last_sigma_yx_invs
logging.info(f"{print_datetime()}At iter {iiter}, σ_yxInv: {array2string(d)} -> {array2string(self.sigma_yx_invs)}")
if (np.abs(d) / self.sigma_yx_invs).max() < 1e-5 or self.num_repli <= 1 or self.sigma_yx_inv_mode.startswith('average'):
break
# emission
Q_Y = -np.dot(self.betas, sizes) / 2
# partition function - Pr [ Y | X, Theta ]
Q_Y -= np.dot(self.betas, sizes) * np.log(2*np.pi) / 2
Q_Y += (sizes * self.betas * np.log(self.sigma_yx_invs)).sum()
return Q_Y
def estimateParametersX(self, iiter):
logging.info(f'{print_datetime()}Estimating Sigma_x_inv and prior_xs')
device = self.PyTorch_device
Bs = []
talphas = []
talpha_es = []
tC = torch.zeros([self.K, self.K], dtype=dtype, device=device)
tnus = []
for YT, E, XT, beta in zip(self.YTs, self.Es, self.XTs, self.betas):
tXT = torch.tensor(XT, dtype=dtype, device=device)
N, G = YT.shape
if self.dropout_mode == 'raw':
Bs.append(XT.T @ XT)
else:
raise NotImplementedError
talphas.append(tXT.sum(0))
talpha_es.append(torch.tensor(list(map(len, E)), dtype=dtype, device=device) @ tXT)
tXT.div_(tXT.sum(1, keepdim=True).add_(1e-30))
tnu = torch.empty([N, self.K], dtype=dtype, device=device)
for tnui, ei in zip(tnu, E):
tnui.copy_(tXT[ei].sum(0))
tnus.append(tnu)
tC.add_(alpha=beta, other=tXT.t() @ tnu)
del tXT
Q_X = 0
if all(prior_x[0] == 'Gaussian' for prior_x in self.prior_xs) and self.pairwise_potential_mode == 'linear':
raise NotImplementedError
elif self.pairwise_potential_mode in ['linear', 'linear w/ shift']:
raise NotImplementedError
elif all(prior_x[0] in ['Exponential shared', 'Exponential shared fixed'] for prior_x in self.prior_xs) and self.pairwise_potential_mode == 'normalized':
prior_xs_old = self.prior_xs
self.prior_xs = []
for N, prior_x, talpha in zip(self.Ns, prior_xs_old, talphas):
if prior_x[0] == 'Exponential shared':
lambda_x, = prior_x[1:]
lambda_x = talpha.mean().div_(N).pow(-1).cpu().data.numpy()
Q_X -= lambda_x * talpha.sum().cpu().data.numpy()
Q_X += N*self.K*np.log(lambda_x) - N*loggamma(self.K)
prior_x = prior_x[:1] + (np.full(self.K, lambda_x), )
self.prior_xs.append(prior_x)
elif prior_x[0] == 'Exponential shared fixed':
lambda_x, = prior_x[1:]
Q_X -= lambda_x.mean() * talpha.sum().cpu().data.numpy()
self.prior_xs.append(prior_x)
else:
raise NotImplementedError
del prior_xs_old
if not all(self.Es_empty):
# valid_diter = 1
# valid_diter = 7
# valid_diter = 31
# valid_diter = 97
valid_diter = 331
# valid_diter = 997
# valid_diter = 3343
# valid_diter = 7177
# valid_diter = 9973
max_iter = 1e4
max_iter = int(max_iter)
batch_sizes = [512, ] * self.num_repli
# requires_grad = True
requires_grad = False
var_list = []
optimizers = []
schedulars = []
tSigma_x_inv = torch.tensor(self.Sigma_x_inv, dtype=dtype, device=device, requires_grad=requires_grad)
var_list += [
tSigma_x_inv,
]
schedular = None
optimizer = torch.optim.Adam([tSigma_x_inv], lr=1e-2)
schedular = torch.optim.lr_scheduler.StepLR(optimizer, valid_diter, gamma=0.98)
optimizers.append(optimizer)
if schedular: schedulars.append(schedular)
del optimizer, schedular
tprior_xs = []
for prior_x in self.prior_xs:
if prior_x[0] in ['Exponential shared', 'Exponential shared fixed']:
lambda_x, = prior_x[1:]
tlambda_x = torch.tensor(lambda_x, dtype=dtype, device=device, requires_grad=requires_grad)
tprior_xs.append((prior_x[0], tlambda_x,))
var_list.append(tlambda_x)
del lambda_x
else:
raise NotImplementedError
for t in var_list: t.grad = torch.zeros_like(t)
tdiagBs = [torch.tensor(np.diag(B).copy(), dtype=dtype, device=device) for B in Bs]
tNus = [tnu.sum(0) for tnu in tnus]
tNu2s = [tnu.t() @ tnu for tnu in tnus]
talpha_e_all = torch.zeros_like(talpha_es[0])
for beta, talpha_e in zip(self.betas, talpha_es): talpha_e_all.add_(alpha=beta, other=talpha_e)
NEs = [sum(map(len, E)) for E in self.Es]
tnEs = [torch.tensor(list(map(len, E)), dtype=dtype, device=device) for E in self.Es]
tZTs = [torch.tensor(XT, dtype=dtype, device=device) for XT in self.XTs]
for tZT in tZTs: tZT.div_(tZT.sum(1, keepdim=True))
# Sigma_x_inv_ub = 1.
# Sigma_x_inv_lb = -1.
Sigma_x_inv_lb = None
Sigma_x_inv_ub = None
Sigma_x_inv_constraint = None # complete matrix
# Sigma_x_inv_constraint = 'diagonal' # diagonal matrix
# Sigma_x_inv_constraint = 'diagonal same' # diagonal matrix, diagonal values are all the same
row_idx, col_idx = np.triu_indices(self.K, 0)
assumption_str = 'mean-field'
# assumption_str = None
# assumption_str = 'independent'
random_flag = assumption_str in [
'independent',
'mean-field',
]
n_samples = 0
regenerate_diter = int(1e10)
tZes = [None] * self.num_repli
nsample4integral = 64
if assumption_str == None:
raise NotImplementedError
elif assumption_str == 'mean-field':
pass
elif assumption_str == 'independent':
raise NotImplementedError
else:
raise NotImplementedError
if assumption_str in [None, 'independent']:
tC.div_(2)
loggamma_K = loggamma(self.K)
__t__, func, last_func = 0, None, torch.empty([], dtype=dtype, device=device).fill_(np.nan)
best_func, best_iter = torch.empty([], dtype=dtype, device=device).fill_(np.nan), -1
tSigma_x_inv_best = None
for __t__ in range(max_iter + 1):
if not requires_grad:
for t in var_list: t.grad.zero_()
else:
for optimizer in optimizers:
optimizer.zero_grad()
assert (tSigma_x_inv - tSigma_x_inv.t()).abs().max() < 1e-15
if Sigma_x_inv_lb is not None:
tSigma_x_inv.clamp_(min=Sigma_x_inv_lb)
if Sigma_x_inv_ub is not None:
tSigma_x_inv.clamp_(max=Sigma_x_inv_ub)
if Sigma_x_inv_constraint in ['diagonal', 'diagonal same']:
tSigma_x_inv.triu_().tril_()
if Sigma_x_inv_constraint in ['diagonal same']:
tSigma_x_inv[(range(self.K), range(self.K))] = tSigma_x_inv[(range(self.K), range(self.K))].mean()
func = torch.zeros([], dtype=dtype, device=device)
# if requires_grad:
func_grad = torch.zeros([], dtype=dtype, device=device, requires_grad=True)
# pairwise potential
tSigma_x_inv.grad.add_(tC)
if requires_grad:
func_grad = func_grad + tC.view(-1) @ tSigma_x_inv.view(-1)
else:
func.add_(tC.view(-1) @ tSigma_x_inv.view(-1))
for N, E_empty, NE, tnE, E, beta, tZT, tZe, talpha, tnu, tNu, tNu2, tdiagB, tprior_x in zip(
self.Ns,
self.Es_empty, NEs, tnEs, self.Es, self.betas, tZTs, tZes,
talphas, tnus, tNus, tNu2s, tdiagBs,
tprior_xs,
):
if E_empty:
continue
if assumption_str == 'mean-field':
if tprior_x[0] in ['Exponential shared', 'Exponential shared fixed']:
if __t__ % valid_diter == 0:
idx = slice(None)
else:
idx = np.random.choice(N, min(nsample4integral, N), replace=False)
tnu = tnu[idx].contiguous()
c = NE / tnE[idx].sum()
# Z_z
teta = tnu @ tSigma_x_inv
teta.grad = torch.zeros_like(teta)
# torch.manual_seed(iiter)
if iiter > 1 or __t__ > 100:
# tlogZ = integrateOfExponentialOverSimplexSampling(teta, requires_grad=requires_grad, seed=iiter*max_iter+__t__)
tlogZ = integrateOfExponentialOverSimplexInduction2(teta, grad=c, requires_grad=requires_grad, device=device)
else:
# tlogZ = integrateOfExponentialOverSimplexSampling(teta, requires_grad=requires_grad, seed=iiter*max_iter+__t__)
tlogZ = integrateOfExponentialOverSimplexInduction2(teta, grad=c, requires_grad=requires_grad, device=device)
if requires_grad:
func_grad = func_grad.add(beta*c, tlogZ.sum())
else:
func.add_(alpha=beta*c, other=tlogZ.sum())
tSigma_x_inv.grad.addmm_(alpha=beta, mat1=tnu.t(), mat2=teta.grad)
else:
raise NotImplementedError
elif assumption_str == None:
raise NotImplementedError
elif assumption_str == 'independent':
raise NotImplementedError
else:
raise NotImplementedError
if requires_grad:
func_grad.backward()
func = func + func_grad
# prior on Σ_x^inv
# num_burnin_iter = 200
# if iiter <= num_burnin_iter:
# kk = 1e-1 * np.dot(betas, list(map(len, Es))) * 1e-1**((num_burnin_iter-iiter+1)/num_burnin_iter)
# else:
# kk = 1e-1 * np.dot(betas, list(map(len, Es)))
kk = self.lambda_SigmaXInv * np.dot(self.betas, NEs)
tSigma_x_inv.grad.add_(kk, tSigma_x_inv)
func.add_(kk / 2, tSigma_x_inv.pow(2).sum())
# normalize gradient by the weighted sizes of data sets
tSigma_x_inv.grad.div_(np.dot(self.betas, NEs))
func.div_(np.dot(self.betas, list(map(len, self.YTs))))
tSigma_x_inv.grad.add_(tSigma_x_inv.grad.clone().t()).div_(2)
if Sigma_x_inv_lb is not None:
tSigma_x_inv.grad[(tSigma_x_inv <= Sigma_x_inv_lb) * (tSigma_x_inv.grad > 0)] = 0
if Sigma_x_inv_ub is not None:
tSigma_x_inv.grad[(tSigma_x_inv >= Sigma_x_inv_ub) * (tSigma_x_inv.grad < 0)] = 0
if Sigma_x_inv_constraint in ['diagonal', 'diagonal same']:
tSigma_x_inv.grad.triu_().tril_()
if Sigma_x_inv_constraint in ['diagonal same']:
tSigma_x_inv.grad[(range(self.K), range(self.K))] = tSigma_x_inv.grad[(range(self.K), range(self.K))].mean()
# setting flags
best_flag = False
if not random_flag or __t__ % valid_diter == 0:
best_flag = not best_func <= func
if best_flag:
best_func, best_iter = func, __t__
tSigma_x_inv_best = tSigma_x_inv.clone().detach()
stop_flag = True
# stop_flag = False
stop_tSigma_x_inv_grad_pseudo = 1e-1
stop_flag &= (tSigma_x_inv.grad.abs() / (tSigma_x_inv.abs() + stop_tSigma_x_inv_grad_pseudo)).abs().max().item() < 1e-2
for tprior_x in tprior_xs:
if tprior_x[0] in ['Exponential shared', ]:
tlambda_x, = tprior_x[1:]
stop_flag &= tlambda_x.grad.abs().max().item() < 1e-4
del tlambda_x
elif tprior_x[0] in ['Exponential shared fixed', ]:
pass
else:
raise NotImplementedError
if random_flag:
stop_flag &= not bool(func <= last_func - 1e-3*valid_diter)
else:
stop_flag &= not bool(func <= last_func - 1e-3)
stop_flag |= random_flag and not __t__ < best_iter + 2*valid_diter
# stop_flag |= best_func == func and __t__ > best_iter + 20
if random_flag and __t__ % valid_diter != 0:
stop_flag = False
if __t__ >= max_iter:
stop_flag = True
warning_flag = bool(func > last_func + 1e-10)
warning_flag &= not random_flag or __t__ % valid_diter == 0
# warning_flag = True
if __t__ % valid_diter == 0 or stop_flag or warning_flag or (regenerate_diter != 1 and (__t__ % regenerate_diter == 0 or (__t__+1) % regenerate_diter == 0)):
print(
f'At iter {__t__},\t'
f'func = {(func - last_func).item():.2e} -> {func.item():.2e}\t'
f'Σ_x^inv: {tSigma_x_inv.max().item():.1e} - {tSigma_x_inv.min().item():.1e} = {tSigma_x_inv.max() - tSigma_x_inv.min():.1e} '
f'grad = {tSigma_x_inv.grad.min().item():.2e} {tSigma_x_inv.grad.max().item():.2e}\t'
f'var/grad = {(tSigma_x_inv.grad.abs()/(tSigma_x_inv.abs() + stop_tSigma_x_inv_grad_pseudo)).abs().max().item():.2e}'
# f'δ_x: {tdelta_x.max().item():.1e} - {tdelta_x.min().item():.1e} = {tdelta_x.max() - tdelta_x.min():.1e} '
# f'grad = {tdelta_x.grad.min().item():.2e} {tdelta_x.grad.max().item():.2e}'
, end=''
)
if warning_flag: print('\tWarning', end='')
if best_flag:
print('\tbest', end='')
print()
sys.stdout.flush()
# stop_flag = True
if not stop_flag:
for optimizer in optimizers: optimizer.step()
for schedular in schedulars: schedular.step()
if stop_flag: break
if not random_flag or __t__ % valid_diter == 0:
last_func = func
tSigma_x_inv = tSigma_x_inv_best
func = best_func
self.Sigma_x_inv = tSigma_x_inv.cpu().data.numpy()
Q_X -= func.mul_(np.dot(self.betas, list(map(len, self.YTs)))).item()
elif all(prior_x[0] == 'Exponential' for prior_x in self.prior_xs) and self.pairwise_potential_mode == 'normalized':
raise NotImplementedError
else:
raise NotImplementedError
return Q_X
|
[
"util.array2string",
"sampleForIntegral.integrateOfExponentialOverSimplexInduction2",
"torch.optim.lr_scheduler.StepLR",
"numpy.abs",
"torch.empty",
"sys.stdout.flush",
"numpy.diag",
"numpy.full",
"scipy.special.loggamma",
"numpy.copy",
"torch.zeros",
"torch.zeros_like",
"util.print_datetime",
"numpy.diag_indices",
"gurobipy.Model",
"numpy.triu_indices",
"torch.optim.Adam",
"numpy.dot",
"numpy.log",
"torch.tensor",
"numpy.sqrt"
] |
[((705, 719), 'gurobipy.Model', 'grb.Model', (['"""M"""'], {}), "('M')\n", (714, 719), True, 'import gurobipy as grb\n'), ((3943, 4000), 'torch.zeros', 'torch.zeros', (['[self.K, self.K]'], {'dtype': 'dtype', 'device': 'device'}), '([self.K, self.K], dtype=dtype, device=device)\n', (3954, 4000), False, 'import torch\n'), ((2396, 2423), 'numpy.copy', 'np.copy', (['self.sigma_yx_invs'], {}), '(self.sigma_yx_invs)\n', (2403, 2423), True, 'import numpy as np\n'), ((4090, 4134), 'torch.tensor', 'torch.tensor', (['XT'], {'dtype': 'dtype', 'device': 'device'}), '(XT, dtype=dtype, device=device)\n', (4102, 4134), False, 'import torch\n'), ((4419, 4471), 'torch.empty', 'torch.empty', (['[N, self.K]'], {'dtype': 'dtype', 'device': 'device'}), '([N, self.K], dtype=dtype, device=device)\n', (4430, 4471), False, 'import torch\n'), ((3547, 3572), 'numpy.dot', 'np.dot', (['self.betas', 'sizes'], {}), '(self.betas, sizes)\n', (3553, 3572), True, 'import numpy as np\n'), ((3629, 3654), 'numpy.dot', 'np.dot', (['self.betas', 'sizes'], {}), '(self.betas, sizes)\n', (3635, 3654), True, 'import numpy as np\n'), ((3657, 3674), 'numpy.log', 'np.log', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (3663, 3674), True, 'import numpy as np\n'), ((403, 419), 'util.print_datetime', 'print_datetime', ([], {}), '()\n', (417, 419), False, 'from util import psutil_process, print_datetime, array2string, PyTorchDType as dtype\n'), ((1256, 1268), 'numpy.dot', 'np.dot', (['t', 't'], {}), '(t, t)\n', (1262, 1268), True, 'import numpy as np\n'), ((2724, 2734), 'numpy.sqrt', 'np.sqrt', (['t'], {}), '(t)\n', (2731, 2734), True, 'import numpy as np\n'), ((3707, 3733), 'numpy.log', 'np.log', (['self.sigma_yx_invs'], {}), '(self.sigma_yx_invs)\n', (3713, 3733), True, 'import numpy as np\n'), ((3811, 3827), 'util.print_datetime', 'print_datetime', ([], {}), '()\n', (3825, 3827), False, 'from util import psutil_process, print_datetime, array2string, PyTorchDType as dtype\n'), ((1508, 1531), 'numpy.diag_indices', 'np.diag_indices', (['self.K'], {}), '(self.K)\n', (1523, 1531), True, 'import numpy as np\n'), ((2786, 2808), 'numpy.dot', 'np.dot', (['self.betas', 'ds'], {}), '(self.betas, ds)\n', (2792, 2808), True, 'import numpy as np\n'), ((2811, 2836), 'numpy.dot', 'np.dot', (['self.betas', 'sizes'], {}), '(self.betas, sizes)\n', (2817, 2836), True, 'import numpy as np\n'), ((3292, 3308), 'util.print_datetime', 'print_datetime', ([], {}), '()\n', (3306, 3308), False, 'from util import psutil_process, print_datetime, array2string, PyTorchDType as dtype\n'), ((3337, 3352), 'util.array2string', 'array2string', (['d'], {}), '(d)\n', (3349, 3352), False, 'from util import psutil_process, print_datetime, array2string, PyTorchDType as dtype\n'), ((3358, 3390), 'util.array2string', 'array2string', (['self.sigma_yx_invs'], {}), '(self.sigma_yx_invs)\n', (3370, 3390), False, 'from util import psutil_process, print_datetime, array2string, PyTorchDType as dtype\n'), ((6136, 6228), 'torch.tensor', 'torch.tensor', (['self.Sigma_x_inv'], {'dtype': 'dtype', 'device': 'device', 'requires_grad': 'requires_grad'}), '(self.Sigma_x_inv, dtype=dtype, device=device, requires_grad=\n requires_grad)\n', (6148, 6228), False, 'import torch\n'), ((6299, 6340), 'torch.optim.Adam', 'torch.optim.Adam', (['[tSigma_x_inv]'], {'lr': '(0.01)'}), '([tSigma_x_inv], lr=0.01)\n', (6315, 6340), False, 'import torch\n'), ((6356, 6423), 'torch.optim.lr_scheduler.StepLR', 'torch.optim.lr_scheduler.StepLR', (['optimizer', 'valid_diter'], {'gamma': '(0.98)'}), '(optimizer, valid_diter, gamma=0.98)\n', (6387, 6423), False, 'import torch\n'), ((7158, 7188), 'torch.zeros_like', 'torch.zeros_like', (['talpha_es[0]'], {}), '(talpha_es[0])\n', (7174, 7188), False, 'import torch\n'), ((7891, 7917), 'numpy.triu_indices', 'np.triu_indices', (['self.K', '(0)'], {}), '(self.K, 0)\n', (7906, 7917), True, 'import numpy as np\n'), ((8502, 8518), 'scipy.special.loggamma', 'loggamma', (['self.K'], {}), '(self.K)\n', (8510, 8518), False, 'from scipy.special import loggamma\n'), ((2206, 2220), 'numpy.abs', 'np.abs', (['self.M'], {}), '(self.M)\n', (2212, 2220), True, 'import numpy as np\n'), ((3045, 3077), 'numpy.dot', 'np.dot', (['self.betas[idx]', 'ds[idx]'], {}), '(self.betas[idx], ds[idx])\n', (3051, 3077), True, 'import numpy as np\n'), ((3080, 3115), 'numpy.dot', 'np.dot', (['self.betas[idx]', 'sizes[idx]'], {}), '(self.betas[idx], sizes[idx])\n', (3086, 3115), True, 'import numpy as np\n'), ((6950, 6969), 'torch.zeros_like', 'torch.zeros_like', (['t'], {}), '(t)\n', (6966, 6969), False, 'import torch\n'), ((7433, 7477), 'torch.tensor', 'torch.tensor', (['XT'], {'dtype': 'dtype', 'device': 'device'}), '(XT, dtype=dtype, device=device)\n', (7445, 7477), False, 'import torch\n'), ((9397, 9440), 'torch.zeros', 'torch.zeros', (['[]'], {'dtype': 'dtype', 'device': 'device'}), '([], dtype=dtype, device=device)\n', (9408, 9440), False, 'import torch\n'), ((9481, 9544), 'torch.zeros', 'torch.zeros', (['[]'], {'dtype': 'dtype', 'device': 'device', 'requires_grad': '(True)'}), '([], dtype=dtype, device=device, requires_grad=True)\n', (9492, 9544), False, 'import torch\n'), ((2890, 2900), 'numpy.sqrt', 'np.sqrt', (['t'], {}), '(t)\n', (2897, 2900), True, 'import numpy as np\n'), ((3400, 3409), 'numpy.abs', 'np.abs', (['d'], {}), '(d)\n', (3406, 3409), True, 'import numpy as np\n'), ((6700, 6779), 'torch.tensor', 'torch.tensor', (['lambda_x'], {'dtype': 'dtype', 'device': 'device', 'requires_grad': 'requires_grad'}), '(lambda_x, dtype=dtype, device=device, requires_grad=requires_grad)\n', (6712, 6779), False, 'import torch\n'), ((11828, 11851), 'numpy.dot', 'np.dot', (['self.betas', 'NEs'], {}), '(self.betas, NEs)\n', (11834, 11851), True, 'import numpy as np\n'), ((12034, 12057), 'numpy.dot', 'np.dot', (['self.betas', 'NEs'], {}), '(self.betas, NEs)\n', (12040, 12057), True, 'import numpy as np\n'), ((14969, 14987), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (14985, 14987), False, 'import sys, time, itertools, resource, logging\n'), ((3169, 3179), 'numpy.sqrt', 'np.sqrt', (['t'], {}), '(t)\n', (3176, 3179), True, 'import numpy as np\n'), ((5330, 5346), 'numpy.log', 'np.log', (['lambda_x'], {}), '(lambda_x)\n', (5336, 5346), True, 'import numpy as np\n'), ((5351, 5367), 'scipy.special.loggamma', 'loggamma', (['self.K'], {}), '(self.K)\n', (5359, 5367), False, 'from scipy.special import loggamma\n'), ((5397, 5422), 'numpy.full', 'np.full', (['self.K', 'lambda_x'], {}), '(self.K, lambda_x)\n', (5404, 5422), True, 'import numpy as np\n'), ((8557, 8600), 'torch.empty', 'torch.empty', (['[]'], {'dtype': 'dtype', 'device': 'device'}), '([], dtype=dtype, device=device)\n', (8568, 8600), False, 'import torch\n'), ((8641, 8684), 'torch.empty', 'torch.empty', (['[]'], {'dtype': 'dtype', 'device': 'device'}), '([], dtype=dtype, device=device)\n', (8652, 8684), False, 'import torch\n'), ((6998, 7008), 'numpy.diag', 'np.diag', (['B'], {}), '(B)\n', (7005, 7008), True, 'import numpy as np\n'), ((10426, 10448), 'torch.zeros_like', 'torch.zeros_like', (['teta'], {}), '(teta)\n', (10442, 10448), False, 'import torch\n'), ((10657, 10763), 'sampleForIntegral.integrateOfExponentialOverSimplexInduction2', 'integrateOfExponentialOverSimplexInduction2', (['teta'], {'grad': 'c', 'requires_grad': 'requires_grad', 'device': 'device'}), '(teta, grad=c, requires_grad=\n requires_grad, device=device)\n', (10700, 10763), False, 'from sampleForIntegral import integrateOfExponentialOverSimplexInduction2\n'), ((10910, 11016), 'sampleForIntegral.integrateOfExponentialOverSimplexInduction2', 'integrateOfExponentialOverSimplexInduction2', (['teta'], {'grad': 'c', 'requires_grad': 'requires_grad', 'device': 'device'}), '(teta, grad=c, requires_grad=\n requires_grad, device=device)\n', (10953, 11016), False, 'from sampleForIntegral import integrateOfExponentialOverSimplexInduction2\n')]
|
# coding: utf-8
# In[1]:
import numpy as np
import cv2
import matplotlib
import matplotlib.pyplot as plt
import matplotlib as mpimg
import numpy as np
from IPython.display import HTML
import os, sys
import glob
import moviepy
from moviepy.editor import VideoFileClip
from moviepy.editor import *
from IPython import display
from IPython.core.display import display
from IPython.display import Image
import pylab
import scipy.misc
# In[2]:
def region_of_interest(img):
mask = np.zeros(img.shape, dtype=np.uint8) #mask image
roi_corners = np.array([[(200,675), (1200,675), (700,430),(500,430)]],
dtype=np.int32) # vertisies seted to form trapezoidal scene
channel_count = 1#img.shape[2] # image channels
ignore_mask_color = (255,)*channel_count
cv2.fillPoly(mask, roi_corners, ignore_mask_color)
masked_image = cv2.bitwise_and(img, mask)
return masked_image
# In[3]:
def ColorThreshold(img): # Threshold Yellow anf White Colos from RGB, HSV, HLS color spaces
HSV = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
# For yellow
yellow = cv2.inRange(HSV, (20, 100, 100), (50, 255, 255))
# For white
sensitivity_1 = 68
white = cv2.inRange(HSV, (0,0,255-sensitivity_1), (255,20,255))
sensitivity_2 = 60
HSL = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
white_2 = cv2.inRange(HSL, (0,255-sensitivity_2,0), (255,255,sensitivity_2))
white_3 = cv2.inRange(img, (200,200,200), (255,255,255))
bit_layer = yellow | white | white_2 | white_3
return bit_layer
# In[4]:
from skimage import morphology
def SobelThr(img): # Sobel edge detection extraction
gray=img
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0,ksize=15)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1,ksize=15)
abs_sobelx = np.absolute(sobelx)
abs_sobely = np.absolute(sobely)
scaled_sobelx = np.uint8(255*abs_sobelx/np.max(abs_sobelx))
scaled_sobely = np.uint8(255*abs_sobely/np.max(abs_sobely))
binary_outputabsx = np.zeros_like(scaled_sobelx)
binary_outputabsx[(scaled_sobelx >= 70) & (scaled_sobelx <= 255)] = 1
binary_outputabsy = np.zeros_like(scaled_sobely)
binary_outputabsy[(scaled_sobely >= 100) & (scaled_sobely <= 150)] = 1
mag_thresh=(100, 200)
gradmag = np.sqrt(sobelx**2 + sobely**2)
scale_factor = np.max(gradmag)/255
gradmag = (gradmag/scale_factor).astype(np.uint8)
binary_outputmag = np.zeros_like(gradmag)
binary_outputmag[(gradmag >= mag_thresh[0]) & (gradmag <= mag_thresh[1])] = 1
combinedS = np.zeros_like(binary_outputabsx)
combinedS[(((binary_outputabsx == 1) | (binary_outputabsy == 1))|(binary_outputmag==1)) ] = 1
return combinedS
# In[5]:
def combinI(b1,b2): ##Combine color threshold + Sobel edge detection
combined = np.zeros_like(b1)
combined[((b1 == 1)|(b2 == 255)) ] = 1
return combined
# In[6]:
def prespectI(img): # Calculate the prespective transform and warp the Image to the eye bird view
src=np.float32([[728,475],
[1058,690],
[242,690],
[565,475]])
dst=np.float32([[1058,20],
[1058,700],
[242,700],
[242,20]])
M = cv2.getPerspectiveTransform(src, dst)
warped = cv2.warpPerspective(img, M, (1280,720), flags=cv2.INTER_LINEAR)
return (warped, M)
# In[7]:
def undistorT(imgorg): # Calculate Undistortion coefficients
nx =9
ny = 6
objpoints = []
imgpoints = []
objp=np.zeros((6*9,3),np.float32)
objp[:,:2]=np.mgrid[0:6,0:9].T.reshape(-1,2)
images=glob.glob('./camera_cal/calibration*.jpg')
for fname in images: # find corner points and Make a list of calibration images
img = cv2.imread(fname)
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (6,9),None)
# If found, draw corners
if ret == True:
imgpoints.append(corners)
objpoints.append(objp)
# Draw and display the corners
#cv2.drawChessboardCorners(img, (nx, ny), corners, ret)
return cv2.calibrateCamera(objpoints,imgpoints,gray.shape[::-1],None,None)
# In[8]:
def undistresult(img, mtx,dist): # undistort frame
undist= cv2.undistort(img, mtx, dist, None, mtx)
return undist
# In[9]:
def LineFitting(wimgun): #Fit Lane Lines
# Set minimum number of pixels found to recenter window
minpix = 20
# Create empty lists to receive left and right lane pixel indices
left_lane_inds = []
right_lane_inds = []
histogram = np.sum(wimgun[350:,:], axis=0)
# Create an output image to draw on and visualize the result
out_img = np.dstack((wimgun, wimgun, wimgun))
# Find the peak of the left and right halves of the histogram
# These will be the starting point for the left and right lines
midpoint = np.int(histogram.shape[0]/2)
leftx_base = np.argmax(histogram[:midpoint])
rightx_base = np.argmax(histogram[midpoint:]) + midpoint
nwindows = 9
# Set height of windows
window_height = np.int(wimgun.shape[0]/nwindows)
# Identify the x and y positions of all nonzero pixels in the image
nonzero = wimgun.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# Current positions to be updated for each window
leftx_current = leftx_base
rightx_current = rightx_base
# Set the width of the windows +/- margin
margin =80
# Step through the windows one by one
for window in range(nwindows):
# Identify window boundaries in x and y (and right and left)
win_y_low = wimgun.shape[0] - (window+1)*window_height
win_y_high = wimgun.shape[0] - window*window_height
win_xleft_low = leftx_current - margin
win_xleft_high = leftx_current + margin
win_xright_low = rightx_current - margin
win_xright_high = rightx_current + margin
# Draw the windows on the visualization image
cv2.rectangle(out_img,(win_xleft_low,win_y_low),(win_xleft_high,win_y_high),(0,255,0), 2)
cv2.rectangle(out_img,(win_xright_low,win_y_low),(win_xright_high,win_y_high),(0,255,0), 2)
# Identify the nonzero pixels in x and y within the window
good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]
good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]
# Append these indices to the lists
left_lane_inds.append(good_left_inds)
right_lane_inds.append(good_right_inds)
# If you found > minpix pixels, recenter next window on their mean position
if len(good_left_inds) > minpix:
leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
if len(good_right_inds) > minpix:
rightx_current = np.int(np.mean(nonzerox[good_right_inds]))
# Concatenate the arrays of indices
left_lane_inds = np.concatenate(left_lane_inds)
right_lane_inds = np.concatenate(right_lane_inds)
# Again, extract left and right line pixel positions
leftx = nonzerox[left_lane_inds]
lefty = nonzeroy[left_lane_inds]
rightx = nonzerox[right_lane_inds]
righty = nonzeroy[right_lane_inds]
# Fit a second order polynomial to each
left_fit = np.polyfit(lefty, leftx, 2)
right_fit = np.polyfit(righty, rightx, 2)
# Generate x and y values for plotting
ploty = np.linspace(0, wimgun.shape[0]-1, wimgun.shape[0] )
left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]
right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]
# Create an image to draw on and an image to show the selection window
# out_img = np.dstack((wimgun, wimgun, wimgun))*255
window_img = np.zeros_like(out_img)
# Color in left and right line pixels
out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]
out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]
# plt.plot(left_fitx, ploty, color='yellow')
# plt.plot(right_fitx, ploty, color='yellow')
# plt.xlim(0, 1280)
# plt.ylim(720, 0)
# plt.imshow(out_img)
# # plt.savefig("./output_images/Window Image"+str(n)+".png")
# plt.show()
# Generate a polygon to illustrate the search window area
# And recast the x and y points into usable format for cv2.fillPoly()
left_line_window1 = np.array([np.transpose(np.vstack([left_fitx-margin, ploty]))])
left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([left_fitx+margin, ploty])))])
left_line_pts = np.hstack((left_line_window1, left_line_window2))
right_line_window1 = np.array([np.transpose(np.vstack([right_fitx-margin, ploty]))])
right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([right_fitx+margin, ploty])))])
right_line_pts = np.hstack((right_line_window1, right_line_window2))
# Draw the lane onto the warped blank image
cv2.fillPoly(window_img, np.int_([left_line_pts]), (0,255, 0))
cv2.fillPoly(window_img, np.int_([right_line_pts]), (0,255, 0))
result = cv2.addWeighted(out_img, 1, window_img, 0.3, 0)
# plt.title("r")
# plt.plot(left_fitx, ploty, color='yellow')
# plt.plot(right_fitx, ploty, color='yellow')
# plt.xlim(0, 1280)
# plt.ylim(720, 0)
# plt.imshow(result)
# # plt.savefig("./output_images/Line Image"+str(n)+".png")
# plt.show()
# Define y-value where we want radius of curvature
# I'll choose the maximum y-value, corresponding to the bottom of the image
y_eval = np.max(ploty)
left_curverad = ((1 + (2*left_fit[0]*y_eval + left_fit[1])**2)**1.5) / np.absolute(2*left_fit[0])
right_curverad = ((1 + (2*right_fit[0]*y_eval + right_fit[1])**2)**1.5) / np.absolute(2*right_fit[0])
#print(left_curverad, right_curverad)
ym_per_pix = 30/720 # meters per pixel in y dimension
xm_per_pix = 3.7/700 # meters per pixel in x dimension
# Fit new polynomials to x,y in world space
left_fit_cr = np.polyfit(ploty*ym_per_pix, left_fitx*xm_per_pix, 2)
right_fit_cr = np.polyfit(ploty*ym_per_pix, right_fitx*xm_per_pix, 2)
# y_eval = np.max(ploty)
# # Calculate the new radias of curvature
left_curverad = ((1 + (2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0])
right_curverad = ((1 + (2*right_fit_cr[0]*y_eval*ym_per_pix + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0])
# # left_curverad = ((1 + (2*left_fit[0]*y_eval + left_fit[1])**2)**1.5) / np.absolute(2*left_fit[0])
# # right_curverad = ((1 + (2*right_fit[0]*y_eval + right_fit[1])**2)**1.5) / np.absolute(2*right_fit[0])
camera_center=wimgun.shape[0]/2
# #lane_center = (right_fitx[719] + left_fitx[719])/2
car_position = (camera_center- (left_fitx[-1]+right_fitx[-1])/2)*xm_per_pix
# print(left_curverad1, right_curverad1, lane_offset)
return (left_fit, ploty,right_fit,left_curverad, right_curverad,car_position)
# Create an image to draw the lines on
def unwrappedframe(img,pm, Minv, left_fit,ploty,right_fit):
left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]
right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]
nonzero = img.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
warp_zero = np.zeros_like(pm).astype(np.uint8)
color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
# Recast the x and y points into usable format for cv2.fillPoly()
pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
pts = np.hstack((pts_left, pts_right))
# Draw the lane onto the warped blank image
cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))
# Warp the blank back to original image space using inverse perspective matrix (Minv)
newwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0]))
# Combine the result with the original image
return cv2.addWeighted(img, 1, newwarp, 0.3, 0)
|
[
"numpy.absolute",
"numpy.sum",
"cv2.bitwise_and",
"numpy.argmax",
"cv2.getPerspectiveTransform",
"numpy.polyfit",
"cv2.fillPoly",
"numpy.mean",
"glob.glob",
"cv2.rectangle",
"cv2.inRange",
"cv2.undistort",
"cv2.warpPerspective",
"numpy.zeros_like",
"numpy.int_",
"cv2.cvtColor",
"numpy.max",
"numpy.int",
"numpy.linspace",
"numpy.dstack",
"numpy.hstack",
"cv2.addWeighted",
"cv2.calibrateCamera",
"cv2.Sobel",
"numpy.concatenate",
"numpy.vstack",
"cv2.findChessboardCorners",
"numpy.float32",
"numpy.zeros",
"cv2.imread",
"numpy.array",
"numpy.sqrt"
] |
[((487, 522), 'numpy.zeros', 'np.zeros', (['img.shape'], {'dtype': 'np.uint8'}), '(img.shape, dtype=np.uint8)\n', (495, 522), True, 'import numpy as np\n'), ((553, 630), 'numpy.array', 'np.array', (['[[(200, 675), (1200, 675), (700, 430), (500, 430)]]'], {'dtype': 'np.int32'}), '([[(200, 675), (1200, 675), (700, 430), (500, 430)]], dtype=np.int32)\n', (561, 630), True, 'import numpy as np\n'), ((800, 850), 'cv2.fillPoly', 'cv2.fillPoly', (['mask', 'roi_corners', 'ignore_mask_color'], {}), '(mask, roi_corners, ignore_mask_color)\n', (812, 850), False, 'import cv2\n'), ((873, 899), 'cv2.bitwise_and', 'cv2.bitwise_and', (['img', 'mask'], {}), '(img, mask)\n', (888, 899), False, 'import cv2\n'), ((1060, 1096), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2HSV'], {}), '(img, cv2.COLOR_RGB2HSV)\n', (1072, 1096), False, 'import cv2\n'), ((1128, 1176), 'cv2.inRange', 'cv2.inRange', (['HSV', '(20, 100, 100)', '(50, 255, 255)'], {}), '(HSV, (20, 100, 100), (50, 255, 255))\n', (1139, 1176), False, 'import cv2\n'), ((1229, 1290), 'cv2.inRange', 'cv2.inRange', (['HSV', '(0, 0, 255 - sensitivity_1)', '(255, 20, 255)'], {}), '(HSV, (0, 0, 255 - sensitivity_1), (255, 20, 255))\n', (1240, 1290), False, 'import cv2\n'), ((1319, 1355), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2HLS'], {}), '(img, cv2.COLOR_RGB2HLS)\n', (1331, 1355), False, 'import cv2\n'), ((1370, 1442), 'cv2.inRange', 'cv2.inRange', (['HSL', '(0, 255 - sensitivity_2, 0)', '(255, 255, sensitivity_2)'], {}), '(HSL, (0, 255 - sensitivity_2, 0), (255, 255, sensitivity_2))\n', (1381, 1442), False, 'import cv2\n'), ((1451, 1501), 'cv2.inRange', 'cv2.inRange', (['img', '(200, 200, 200)', '(255, 255, 255)'], {}), '(img, (200, 200, 200), (255, 255, 255))\n', (1462, 1501), False, 'import cv2\n'), ((1731, 1774), 'cv2.Sobel', 'cv2.Sobel', (['gray', 'cv2.CV_64F', '(1)', '(0)'], {'ksize': '(15)'}), '(gray, cv2.CV_64F, 1, 0, ksize=15)\n', (1740, 1774), False, 'import cv2\n'), ((1787, 1830), 'cv2.Sobel', 'cv2.Sobel', (['gray', 'cv2.CV_64F', '(0)', '(1)'], {'ksize': '(15)'}), '(gray, cv2.CV_64F, 0, 1, ksize=15)\n', (1796, 1830), False, 'import cv2\n'), ((1852, 1871), 'numpy.absolute', 'np.absolute', (['sobelx'], {}), '(sobelx)\n', (1863, 1871), True, 'import numpy as np\n'), ((1889, 1908), 'numpy.absolute', 'np.absolute', (['sobely'], {}), '(sobely)\n', (1900, 1908), True, 'import numpy as np\n'), ((2070, 2098), 'numpy.zeros_like', 'np.zeros_like', (['scaled_sobelx'], {}), '(scaled_sobelx)\n', (2083, 2098), True, 'import numpy as np\n'), ((2211, 2239), 'numpy.zeros_like', 'np.zeros_like', (['scaled_sobely'], {}), '(scaled_sobely)\n', (2224, 2239), True, 'import numpy as np\n'), ((2361, 2395), 'numpy.sqrt', 'np.sqrt', (['(sobelx ** 2 + sobely ** 2)'], {}), '(sobelx ** 2 + sobely ** 2)\n', (2368, 2395), True, 'import numpy as np\n'), ((2514, 2536), 'numpy.zeros_like', 'np.zeros_like', (['gradmag'], {}), '(gradmag)\n', (2527, 2536), True, 'import numpy as np\n'), ((2635, 2667), 'numpy.zeros_like', 'np.zeros_like', (['binary_outputabsx'], {}), '(binary_outputabsx)\n', (2648, 2667), True, 'import numpy as np\n'), ((2893, 2910), 'numpy.zeros_like', 'np.zeros_like', (['b1'], {}), '(b1)\n', (2906, 2910), True, 'import numpy as np\n'), ((3121, 3182), 'numpy.float32', 'np.float32', (['[[728, 475], [1058, 690], [242, 690], [565, 475]]'], {}), '([[728, 475], [1058, 690], [242, 690], [565, 475]])\n', (3131, 3182), True, 'import numpy as np\n'), ((3246, 3306), 'numpy.float32', 'np.float32', (['[[1058, 20], [1058, 700], [242, 700], [242, 20]]'], {}), '([[1058, 20], [1058, 700], [242, 700], [242, 20]])\n', (3256, 3306), True, 'import numpy as np\n'), ((3365, 3402), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['src', 'dst'], {}), '(src, dst)\n', (3392, 3402), False, 'import cv2\n'), ((3416, 3480), 'cv2.warpPerspective', 'cv2.warpPerspective', (['img', 'M', '(1280, 720)'], {'flags': 'cv2.INTER_LINEAR'}), '(img, M, (1280, 720), flags=cv2.INTER_LINEAR)\n', (3435, 3480), False, 'import cv2\n'), ((3664, 3696), 'numpy.zeros', 'np.zeros', (['(6 * 9, 3)', 'np.float32'], {}), '((6 * 9, 3), np.float32)\n', (3672, 3696), True, 'import numpy as np\n'), ((3755, 3797), 'glob.glob', 'glob.glob', (['"""./camera_cal/calibration*.jpg"""'], {}), "('./camera_cal/calibration*.jpg')\n", (3764, 3797), False, 'import glob\n'), ((4422, 4493), 'cv2.calibrateCamera', 'cv2.calibrateCamera', (['objpoints', 'imgpoints', 'gray.shape[::-1]', 'None', 'None'], {}), '(objpoints, imgpoints, gray.shape[::-1], None, None)\n', (4441, 4493), False, 'import cv2\n'), ((4579, 4619), 'cv2.undistort', 'cv2.undistort', (['img', 'mtx', 'dist', 'None', 'mtx'], {}), '(img, mtx, dist, None, mtx)\n', (4592, 4619), False, 'import cv2\n'), ((4936, 4967), 'numpy.sum', 'np.sum', (['wimgun[350:, :]'], {'axis': '(0)'}), '(wimgun[350:, :], axis=0)\n', (4942, 4967), True, 'import numpy as np\n'), ((5047, 5082), 'numpy.dstack', 'np.dstack', (['(wimgun, wimgun, wimgun)'], {}), '((wimgun, wimgun, wimgun))\n', (5056, 5082), True, 'import numpy as np\n'), ((5234, 5264), 'numpy.int', 'np.int', (['(histogram.shape[0] / 2)'], {}), '(histogram.shape[0] / 2)\n', (5240, 5264), True, 'import numpy as np\n'), ((5280, 5311), 'numpy.argmax', 'np.argmax', (['histogram[:midpoint]'], {}), '(histogram[:midpoint])\n', (5289, 5311), True, 'import numpy as np\n'), ((5440, 5474), 'numpy.int', 'np.int', (['(wimgun.shape[0] / nwindows)'], {}), '(wimgun.shape[0] / nwindows)\n', (5446, 5474), True, 'import numpy as np\n'), ((5591, 5611), 'numpy.array', 'np.array', (['nonzero[0]'], {}), '(nonzero[0])\n', (5599, 5611), True, 'import numpy as np\n'), ((5627, 5647), 'numpy.array', 'np.array', (['nonzero[1]'], {}), '(nonzero[1])\n', (5635, 5647), True, 'import numpy as np\n'), ((7437, 7467), 'numpy.concatenate', 'np.concatenate', (['left_lane_inds'], {}), '(left_lane_inds)\n', (7451, 7467), True, 'import numpy as np\n'), ((7490, 7521), 'numpy.concatenate', 'np.concatenate', (['right_lane_inds'], {}), '(right_lane_inds)\n', (7504, 7521), True, 'import numpy as np\n'), ((7793, 7820), 'numpy.polyfit', 'np.polyfit', (['lefty', 'leftx', '(2)'], {}), '(lefty, leftx, 2)\n', (7803, 7820), True, 'import numpy as np\n'), ((7837, 7866), 'numpy.polyfit', 'np.polyfit', (['righty', 'rightx', '(2)'], {}), '(righty, rightx, 2)\n', (7847, 7866), True, 'import numpy as np\n'), ((7922, 7974), 'numpy.linspace', 'np.linspace', (['(0)', '(wimgun.shape[0] - 1)', 'wimgun.shape[0]'], {}), '(0, wimgun.shape[0] - 1, wimgun.shape[0])\n', (7933, 7974), True, 'import numpy as np\n'), ((8269, 8291), 'numpy.zeros_like', 'np.zeros_like', (['out_img'], {}), '(out_img)\n', (8282, 8291), True, 'import numpy as np\n'), ((9099, 9148), 'numpy.hstack', 'np.hstack', (['(left_line_window1, left_line_window2)'], {}), '((left_line_window1, left_line_window2))\n', (9108, 9148), True, 'import numpy as np\n'), ((9359, 9410), 'numpy.hstack', 'np.hstack', (['(right_line_window1, right_line_window2)'], {}), '((right_line_window1, right_line_window2))\n', (9368, 9410), True, 'import numpy as np\n'), ((9608, 9655), 'cv2.addWeighted', 'cv2.addWeighted', (['out_img', '(1)', 'window_img', '(0.3)', '(0)'], {}), '(out_img, 1, window_img, 0.3, 0)\n', (9623, 9655), False, 'import cv2\n'), ((10080, 10093), 'numpy.max', 'np.max', (['ploty'], {}), '(ploty)\n', (10086, 10093), True, 'import numpy as np\n'), ((10529, 10586), 'numpy.polyfit', 'np.polyfit', (['(ploty * ym_per_pix)', '(left_fitx * xm_per_pix)', '(2)'], {}), '(ploty * ym_per_pix, left_fitx * xm_per_pix, 2)\n', (10539, 10586), True, 'import numpy as np\n'), ((10602, 10660), 'numpy.polyfit', 'np.polyfit', (['(ploty * ym_per_pix)', '(right_fitx * xm_per_pix)', '(2)'], {}), '(ploty * ym_per_pix, right_fitx * xm_per_pix, 2)\n', (10612, 10660), True, 'import numpy as np\n'), ((11814, 11834), 'numpy.array', 'np.array', (['nonzero[0]'], {}), '(nonzero[0])\n', (11822, 11834), True, 'import numpy as np\n'), ((11850, 11870), 'numpy.array', 'np.array', (['nonzero[1]'], {}), '(nonzero[1])\n', (11858, 11870), True, 'import numpy as np\n'), ((11949, 11993), 'numpy.dstack', 'np.dstack', (['(warp_zero, warp_zero, warp_zero)'], {}), '((warp_zero, warp_zero, warp_zero))\n', (11958, 11993), True, 'import numpy as np\n'), ((12230, 12262), 'numpy.hstack', 'np.hstack', (['(pts_left, pts_right)'], {}), '((pts_left, pts_right))\n', (12239, 12262), True, 'import numpy as np\n'), ((12474, 12541), 'cv2.warpPerspective', 'cv2.warpPerspective', (['color_warp', 'Minv', '(img.shape[1], img.shape[0])'], {}), '(color_warp, Minv, (img.shape[1], img.shape[0]))\n', (12493, 12541), False, 'import cv2\n'), ((12609, 12649), 'cv2.addWeighted', 'cv2.addWeighted', (['img', '(1)', 'newwarp', '(0.3)', '(0)'], {}), '(img, 1, newwarp, 0.3, 0)\n', (12624, 12649), False, 'import cv2\n'), ((2416, 2431), 'numpy.max', 'np.max', (['gradmag'], {}), '(gradmag)\n', (2422, 2431), True, 'import numpy as np\n'), ((3916, 3933), 'cv2.imread', 'cv2.imread', (['fname'], {}), '(fname)\n', (3926, 3933), False, 'import cv2\n'), ((3988, 4025), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (4000, 4025), False, 'import cv2\n'), ((4095, 4140), 'cv2.findChessboardCorners', 'cv2.findChessboardCorners', (['gray', '(6, 9)', 'None'], {}), '(gray, (6, 9), None)\n', (4120, 4140), False, 'import cv2\n'), ((5331, 5362), 'numpy.argmax', 'np.argmax', (['histogram[midpoint:]'], {}), '(histogram[midpoint:])\n', (5340, 5362), True, 'import numpy as np\n'), ((6356, 6456), 'cv2.rectangle', 'cv2.rectangle', (['out_img', '(win_xleft_low, win_y_low)', '(win_xleft_high, win_y_high)', '(0, 255, 0)', '(2)'], {}), '(out_img, (win_xleft_low, win_y_low), (win_xleft_high,\n win_y_high), (0, 255, 0), 2)\n', (6369, 6456), False, 'import cv2\n'), ((6455, 6557), 'cv2.rectangle', 'cv2.rectangle', (['out_img', '(win_xright_low, win_y_low)', '(win_xright_high, win_y_high)', '(0, 255, 0)', '(2)'], {}), '(out_img, (win_xright_low, win_y_low), (win_xright_high,\n win_y_high), (0, 255, 0), 2)\n', (6468, 6557), False, 'import cv2\n'), ((9489, 9513), 'numpy.int_', 'np.int_', (['[left_line_pts]'], {}), '([left_line_pts])\n', (9496, 9513), True, 'import numpy as np\n'), ((9556, 9581), 'numpy.int_', 'np.int_', (['[right_line_pts]'], {}), '([right_line_pts])\n', (9563, 9581), True, 'import numpy as np\n'), ((10169, 10197), 'numpy.absolute', 'np.absolute', (['(2 * left_fit[0])'], {}), '(2 * left_fit[0])\n', (10180, 10197), True, 'import numpy as np\n'), ((10274, 10303), 'numpy.absolute', 'np.absolute', (['(2 * right_fit[0])'], {}), '(2 * right_fit[0])\n', (10285, 10303), True, 'import numpy as np\n'), ((10825, 10856), 'numpy.absolute', 'np.absolute', (['(2 * left_fit_cr[0])'], {}), '(2 * left_fit_cr[0])\n', (10836, 10856), True, 'import numpy as np\n'), ((10950, 10982), 'numpy.absolute', 'np.absolute', (['(2 * right_fit_cr[0])'], {}), '(2 * right_fit_cr[0])\n', (10961, 10982), True, 'import numpy as np\n'), ((12341, 12355), 'numpy.int_', 'np.int_', (['[pts]'], {}), '([pts])\n', (12348, 12355), True, 'import numpy as np\n'), ((1953, 1971), 'numpy.max', 'np.max', (['abs_sobelx'], {}), '(abs_sobelx)\n', (1959, 1971), True, 'import numpy as np\n'), ((2017, 2035), 'numpy.max', 'np.max', (['abs_sobely'], {}), '(abs_sobely)\n', (2023, 2035), True, 'import numpy as np\n'), ((11897, 11914), 'numpy.zeros_like', 'np.zeros_like', (['pm'], {}), '(pm)\n', (11910, 11914), True, 'import numpy as np\n'), ((7217, 7250), 'numpy.mean', 'np.mean', (['nonzerox[good_left_inds]'], {}), '(nonzerox[good_left_inds])\n', (7224, 7250), True, 'import numpy as np\n'), ((7338, 7372), 'numpy.mean', 'np.mean', (['nonzerox[good_right_inds]'], {}), '(nonzerox[good_right_inds])\n', (7345, 7372), True, 'import numpy as np\n'), ((8941, 8979), 'numpy.vstack', 'np.vstack', (['[left_fitx - margin, ploty]'], {}), '([left_fitx - margin, ploty])\n', (8950, 8979), True, 'import numpy as np\n'), ((9197, 9236), 'numpy.vstack', 'np.vstack', (['[right_fitx - margin, ploty]'], {}), '([right_fitx - margin, ploty])\n', (9206, 9236), True, 'import numpy as np\n'), ((12103, 12132), 'numpy.vstack', 'np.vstack', (['[left_fitx, ploty]'], {}), '([left_fitx, ploty])\n', (12112, 12132), True, 'import numpy as np\n'), ((9038, 9076), 'numpy.vstack', 'np.vstack', (['[left_fitx + margin, ploty]'], {}), '([left_fitx + margin, ploty])\n', (9047, 9076), True, 'import numpy as np\n'), ((9296, 9335), 'numpy.vstack', 'np.vstack', (['[right_fitx + margin, ploty]'], {}), '([right_fitx + margin, ploty])\n', (9305, 9335), True, 'import numpy as np\n'), ((12185, 12215), 'numpy.vstack', 'np.vstack', (['[right_fitx, ploty]'], {}), '([right_fitx, ploty])\n', (12194, 12215), True, 'import numpy as np\n')]
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from .instant_function import data_vars
def create_categorical_onehot(df,category_columns):
category_dataframe = []
for category_column in category_columns:
category_dataframe.append(pd.get_dummies(df[category_column],prefix='col_'+category_column))
category_dataframe_feature = pd.concat(category_dataframe,axis=1)
return category_dataframe_feature
def create_norm_continuos_columns(df, continuos_columns):
df_norm = df[continuos_columns].fillna(0)
norm_continuos_columns = (df_norm[continuos_columns]-df_norm[continuos_columns].mean())/(df_norm[continuos_columns].std())
mean_dict = dict(df[continuos_columns].mean())
std_dict = dict(df[continuos_columns].std())
return norm_continuos_columns, mean_dict, std_dict
def combine_continus_norm_and_categorical_onehot_and_sep_target(df, continuos_columns, category_columns, target_columns):
norm_continuos_columns, mean_dict, std_dict = create_norm_continuos_columns(df, continuos_columns)
category_dataframe_feature = create_categorical_onehot(df,category_columns)
target_df = df[target_columns]
feature_df = pd.concat([norm_continuos_columns, category_dataframe_feature], axis=1)
feature_columns = feature_df.columns
return feature_df, target_df, mean_dict, std_dict, feature_columns
def get_IV(feature_df, target_df):
final_iv, IV = data_vars(feature_df, target_df)
ivs = np.zeros(len(feature_df.columns))
for i,col in enumerate(feature_df.columns):
ivs[i] = IV[IV['VAR_NAME']==col]['IV'].values[0]
return IV, ivs
def norm_mat(x):
return x/(np.sqrt(np.sum(x**2,1))).reshape(-1,1)
def get_pos_feat(feature_df, target_df, ivs):
pos_feat = feature_df.loc[target_df[target_df==1].index].values*ivs
pos_feat_norm = norm_mat(pos_feat)
return pos_feat_norm
def process_test_data(df, continuos_columns, category_columns, mean_dict, std_dict, feature_columns):
df_norm = df[continuos_columns].fillna(0)
norm_continuos_columns = (df[mean_dict] - list(mean_dict.values()))/list(std_dict.values())
category_dataframe = []
for category_column in category_columns:
category_dataframe.append(pd.get_dummies(df[category_column],prefix='col_'+category_column))
category_dataframe_feature = pd.concat(category_dataframe,axis=1)
feature_test = pd.concat([norm_continuos_columns, category_dataframe_feature], axis=1)
non_in_test_columns = list(set(list(feature_columns)) - set(list(feature_test.columns)))
for non_in_test_column in non_in_test_columns:
feature_test[non_in_test_column] = 0
feature_test = feature_test[feature_columns]
return feature_test
|
[
"pandas.get_dummies",
"numpy.sum",
"pandas.concat"
] |
[((377, 414), 'pandas.concat', 'pd.concat', (['category_dataframe'], {'axis': '(1)'}), '(category_dataframe, axis=1)\n', (386, 414), True, 'import pandas as pd\n'), ((1204, 1275), 'pandas.concat', 'pd.concat', (['[norm_continuos_columns, category_dataframe_feature]'], {'axis': '(1)'}), '([norm_continuos_columns, category_dataframe_feature], axis=1)\n', (1213, 1275), True, 'import pandas as pd\n'), ((2364, 2401), 'pandas.concat', 'pd.concat', (['category_dataframe'], {'axis': '(1)'}), '(category_dataframe, axis=1)\n', (2373, 2401), True, 'import pandas as pd\n'), ((2425, 2496), 'pandas.concat', 'pd.concat', (['[norm_continuos_columns, category_dataframe_feature]'], {'axis': '(1)'}), '([norm_continuos_columns, category_dataframe_feature], axis=1)\n', (2434, 2496), True, 'import pandas as pd\n'), ((272, 340), 'pandas.get_dummies', 'pd.get_dummies', (['df[category_column]'], {'prefix': "('col_' + category_column)"}), "(df[category_column], prefix='col_' + category_column)\n", (286, 340), True, 'import pandas as pd\n'), ((2259, 2327), 'pandas.get_dummies', 'pd.get_dummies', (['df[category_column]'], {'prefix': "('col_' + category_column)"}), "(df[category_column], prefix='col_' + category_column)\n", (2273, 2327), True, 'import pandas as pd\n'), ((1687, 1704), 'numpy.sum', 'np.sum', (['(x ** 2)', '(1)'], {}), '(x ** 2, 1)\n', (1693, 1704), True, 'import numpy as np\n')]
|
# -*- coding:utf-8 -*-
# @Time : 2019-12-27 16:11
# @Author : liuqiuxi
# @Email : <EMAIL>
# @File : stockfeedswinddatabase.py
# @Project : datafeeds
# @Software: PyCharm
# @Remark : This is class of stock market
import datetime
import copy
import pandas as pd
import numpy as np
from datafeeds.utils import BarFeedConfig
from datafeeds.winddatabasefeeds import BaseWindDataBase
from datafeeds import logger
class AShareCalendarWindDataBase(BaseWindDataBase):
LOGGER_NAME = "AShareCalendarWindDataBase"
def __init__(self):
super(AShareCalendarWindDataBase, self).__init__()
self.__table_name_dict = {"AShareCalendarWindDataBase": "AShareCalendar"}
def get_calendar(self, begin_datetime, end_datetime):
connect = self.connect()
begin_datetime = begin_datetime.strftime("%Y%m%d")
end_datetime = end_datetime.strftime("%Y%m%d")
table_name = self.__table_name_dict.get(self.LOGGER_NAME)
owner = self.get_oracle_owner(table_name=table_name)
table_parameter = owner + table_name
sqlClause = ("select trade_days as dateTime from " + table_parameter + " where trade_days >= " +
"'" + begin_datetime + "' and trade_days <= '" + end_datetime + "' ")
data = self.get_data_with_sql(sqlClause=sqlClause, connect=connect)
data.rename(columns={"datetime": "dateTime"}, inplace=True)
data.drop_duplicates(subset=["dateTime"], inplace=True)
data.sort_values(by="dateTime", inplace=True)
data.reset_index(inplace=True, drop=True)
data.loc[:, "dateTime"] = data.loc[:, "dateTime"].apply(lambda x: datetime.datetime.strptime(x, "%Y%m%d"))
data = pd.DataFrame(data={"dateTime": data.loc[:, "dateTime"]})
connect.close()
return data
class AShareQuotationWindDataBase(BaseWindDataBase):
LOGGER_NAME = "AShareQuotationWindDataBase"
def __init__(self):
super(AShareQuotationWindDataBase, self).__init__()
self.__need_adjust_columns = ["preClose", "open", "high", "low", "close", "volume", "avgPrice"]
self.__table_name_dict = {"AShareQuotationWindDataBase": "AShareEODPrices"}
def get_quotation(self, securityIds, items, frequency, begin_datetime, end_datetime, adjusted="F"):
limit_numbers = BarFeedConfig.get_wind().get("LimitNumbers")
if len(securityIds) < limit_numbers:
data = self.__get_quotation(securityIds=securityIds, items=items, frequency=frequency,
begin_datetime=begin_datetime, end_datetime=end_datetime, adjusted=adjusted)
else:
data = pd.DataFrame()
for i in range(int(len(securityIds) / limit_numbers) + 1):
data0 = self.__get_quotation(securityIds=securityIds[i*limit_numbers: i*limit_numbers + limit_numbers],
items=items, frequency=frequency, begin_datetime=begin_datetime,
end_datetime=end_datetime, adjusted=adjusted)
data = pd.concat(objs=[data, data0], axis=0, join="outer")
data.sort_values(by=["securityId", "dateTime"], axis=0, ascending=True, inplace=True)
data.reset_index(inplace=True, drop=True)
return data
def __get_quotation(self, securityIds, items, frequency, begin_datetime, end_datetime, adjusted):
connect = self.connect()
begin_datetime = begin_datetime.strftime("%Y%m%d")
end_datetime = end_datetime.strftime("%Y%m%d")
table_name = self.__table_name_dict.get(self.LOGGER_NAME)
owner = self.get_oracle_owner(table_name=table_name)
table_parameter = owner + table_name
if frequency != 86400:
raise BaseException("[%s] we can't supply frequency: %d " % (self.LOGGER_NAME, frequency))
if len(securityIds) == 1:
sqlClause = ("select * from " + table_parameter + " where trade_dt >= '" + begin_datetime + "' " +
"and trade_dt <= '" + end_datetime + "' and s_info_windcode = '" + securityIds[0] + "'")
else:
sqlClause = ("select * from " + table_parameter + " where trade_dt >= '" + begin_datetime + "' and " +
"trade_dt <= '" + end_datetime + "' and s_info_windcode in " + str(tuple(securityIds)) + "")
data = self.get_data_with_sql(sqlClause=sqlClause, connect=connect)
rename_dict = BarFeedConfig.get_wind_database_items().get(self.LOGGER_NAME)
data.rename(columns=rename_dict, inplace=True)
# change some parameters value to normal value
data.loc[:, 'dateTime'] = data.loc[:, 'dateTime'].apply(lambda x: datetime.datetime.strptime(x, "%Y%m%d"))
data.loc[:, "Chg"] = data.loc[:, "Chg"] / 100
data.loc[:, "amount"] = data.loc[:, "amount"] * 1000
# use adjfactor get adj price
if adjusted in ["F", "B"]:
data = data.groupby(by="securityId").apply(lambda x: self.__get_adj_price(DataFrame=x, adjusted=adjusted))
data.reset_index(inplace=True, drop=True)
data.sort_values(by=["securityId", "dateTime"], axis=0, ascending=True, inplace=True)
data.reset_index(inplace=True, drop=True)
# choose items to data
log = logger.get_logger(name=self.LOGGER_NAME)
default_items = list(rename_dict.values())
real_items = []
for item in items:
if item in ["securityId", "dateTime"]:
log.info("There is no need add item: %s to parameters items" % item)
elif item in default_items:
real_items.append(item)
else:
log.warning("item %s not in default items, so we remove this item to data" % item)
data = data.loc[:, ["dateTime", "securityId"] + real_items].copy(deep=True)
connect.close()
return data
def __get_adj_price(self, DataFrame, adjusted):
data = DataFrame.copy(deep=True)
data.sort_values(by="dateTime", axis=0, ascending=True, inplace=True)
data.reset_index(inplace=True, drop=True)
if adjusted == "F":
adjfactor = data.loc[:, "adjfactor"][len(data) - 1]
elif adjusted == "B":
adjfactor = data.loc[:, "adjfactor"][0]
else:
raise ValueError("[%s] adjusted: %s did't support" % (self.LOGGER_NAME, adjusted))
data.loc[:, "adjfactor"] = data.loc[:, "adjfactor"].apply(lambda x: x / adjfactor)
columns = copy.deepcopy(self.__need_adjust_columns)
for column in columns:
data.loc[:, column] = data.loc[:, column] * data.loc[:, "adjfactor"]
return data
class AShareIPOWindDataBase(BaseWindDataBase):
LOGGER_NAME = "AShareIPOWindDataBase"
def __init__(self):
super(AShareIPOWindDataBase, self).__init__()
self.__table_name_dict = {"AShareIPOWindDataBase": "AShareIPO"}
def get_initial_public_offering(self, securityIds):
connect = self.connect()
table_name = self.__table_name_dict.get(self.LOGGER_NAME)
owner = self.get_oracle_owner(table_name=table_name)
table_parameter = owner + table_name
sqlClause = "select * from " + table_parameter + ""
data = self.get_data_with_sql(sqlClause=sqlClause, connect=connect)
default_items = list(BarFeedConfig.get_wind_database_items().get(self.LOGGER_NAME))
drop_items = list(set(data.columns) - set(default_items))
data.drop(labels=drop_items, axis=1, inplace=True)
rename_dict = BarFeedConfig.get_wind_database_items().get(self.LOGGER_NAME)
data.rename(columns=rename_dict, inplace=True)
data0 = pd.DataFrame({"securityId": securityIds})
data = pd.merge(left=data, right=data0, on="securityId", how="right")
# change parameters numbers
data.loc[:, "amount"] = data.loc[:, "amount"] * 10000
data.loc[:, "collection"] = data.loc[:, "collection"] * 10000
data.loc[:, "subDate"] = data.loc[:, "subDate"].apply(
lambda x: datetime.datetime.strptime(x, "%Y%m%d") if isinstance(x, datetime.datetime) else None)
data.loc[:, "listDate"] = data.loc[:, "listDate"].apply(
lambda x: datetime.datetime.strptime(x, "%Y%m%d") if isinstance(x, datetime.datetime) else None)
data.sort_values(by="securityId", axis=0, ascending=True, inplace=True)
data.reset_index(inplace=True, drop=True)
return data
class AShareDayVarsWindDataBase(BaseWindDataBase):
LOGGER_NAME = "AShareDayVarsWindDataBase"
def __init__(self):
super(AShareDayVarsWindDataBase, self).__init__()
self.__table_name_dict = {"AShareDayVarsWindDataBase": ["AShareEODDerivativeIndicator",
"AShareEODPrices",
"AShareST"]}
def get_value(self, date_datetime):
connect = self.connect()
table_name = self.__table_name_dict.get(self.LOGGER_NAME)[0]
owner = self.get_oracle_owner(table_name=table_name)
table_parameter = owner + table_name
date_datetime = date_datetime.strftime("%Y%m%d")
sqlClause = "select * from " + table_parameter + " where trade_dt = "+ date_datetime +""
data = self.get_data_with_sql(sqlClause=sqlClause, connect=connect)
default_items = list(BarFeedConfig.get_wind_database_items().get(self.LOGGER_NAME))
drop_items = list(set(data.columns) - set(default_items))
data.drop(labels=drop_items, axis=1, inplace=True)
rename_dict = BarFeedConfig.get_wind_database_items().get(self.LOGGER_NAME)
data.rename(columns=rename_dict, inplace=True)
# change parameters numbers
data.loc[:, "dateTime"] = data.loc[:, "dateTime"].apply(lambda x: datetime.datetime.strptime(x, "%Y%m%d"))
data.loc[:, "upLimit"] = np.where(data.loc[:, "upOrdown"] == 1, True, False)
data.loc[:, "downLimit"] = np.where(data.loc[:, "upOrdown"] == -1, True, False)
data.loc[:, "turnover"] = data.loc[:, "turnover"] / 100
data.loc[:, "turnover_free"] = data.loc[:, "turnover_free"] / 100
data.loc[:, "totalValue"] = data.loc[:, "totalValue"] * 10000
data.loc[:, "marketValue"] = data.loc[:, "marketValue"] * 10000
data.drop(labels=["upOrdown"], axis=1, inplace=True)
# find stock whether suspend
table_name = self.__table_name_dict.get(self.LOGGER_NAME)[1]
owner = self.get_oracle_owner(table_name=table_name)
table_parameter = owner + table_name
sqlClause = ("select s_info_windcode, trade_dt, s_dq_tradestatus from " + table_parameter + " " \
"where trade_dt = '"+ date_datetime +"'")
data0 = self.get_data_with_sql(sqlClause=sqlClause, connect=connect)
data0.rename(columns=rename_dict, inplace=True)
data0.loc[:, "dateTime"] = data0.loc[:, "dateTime"].apply(lambda x: datetime.datetime.strptime(x, "%Y%m%d"))
data0.loc[:, "isNotSuspended"] = np.where(data0.loc[:, "s_dq_tradestatus"] == "交易", True, False)
data0 = data0.loc[:, ["securityId", "dateTime", "isNotSuspended"]].copy(deep=True)
data = pd.merge(left=data, right=data0, how="outer", on=("dateTime", "securityId"))
# find stock whether ST
table_name = self.__table_name_dict.get(self.LOGGER_NAME)[2]
owner = self.get_oracle_owner(table_name=table_name)
table_parameter = owner + table_name
sqlClause = ("select s_info_windcode, entry_dt, remove_dt, s_type_st from " + table_parameter + " " \
"where entry_dt <= '" + date_datetime + "'")
data0 = self.get_data_with_sql(sqlClause=sqlClause, connect=connect)
data0.rename(columns=rename_dict, inplace=True)
data0.loc[:, "entry_dt"] = data0.loc[:, "entry_dt"].apply(lambda x: datetime.datetime.strptime(x, "%Y%m%d"))
data0.loc[:, "remove_dt"] = data0.loc[:, "remove_dt"].apply(
lambda x: np.nan if x == None else datetime.datetime.strptime(x, "%Y%m%d"))
date_datetime = datetime.datetime.strptime(date_datetime, "%Y%m%d")
data0.loc[:, "isST"] = np.where(pd.isnull(data0.loc[:, "remove_dt"]), True,
np.where(data0.loc[:, "remove_dt"] > date_datetime, True, False))
data0 = data0.loc[data0.loc[:, "isST"] == True, ["securityId", "isST"]].copy(deep=True)
data = pd.merge(left=data, right=data0, how="left", on="securityId")
data.loc[:, "isST"] = np.where(data.loc[:, "isST"] == True, True, False)
return data
|
[
"pandas.DataFrame",
"copy.deepcopy",
"datafeeds.utils.BarFeedConfig.get_wind_database_items",
"datafeeds.utils.BarFeedConfig.get_wind",
"pandas.merge",
"datafeeds.logger.get_logger",
"pandas.isnull",
"datetime.datetime.strptime",
"numpy.where",
"pandas.concat"
] |
[((1741, 1797), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "{'dateTime': data.loc[:, 'dateTime']}"}), "(data={'dateTime': data.loc[:, 'dateTime']})\n", (1753, 1797), True, 'import pandas as pd\n'), ((5383, 5423), 'datafeeds.logger.get_logger', 'logger.get_logger', ([], {'name': 'self.LOGGER_NAME'}), '(name=self.LOGGER_NAME)\n', (5400, 5423), False, 'from datafeeds import logger\n'), ((6626, 6667), 'copy.deepcopy', 'copy.deepcopy', (['self.__need_adjust_columns'], {}), '(self.__need_adjust_columns)\n', (6639, 6667), False, 'import copy\n'), ((7837, 7878), 'pandas.DataFrame', 'pd.DataFrame', (["{'securityId': securityIds}"], {}), "({'securityId': securityIds})\n", (7849, 7878), True, 'import pandas as pd\n'), ((7895, 7957), 'pandas.merge', 'pd.merge', ([], {'left': 'data', 'right': 'data0', 'on': '"""securityId"""', 'how': '"""right"""'}), "(left=data, right=data0, on='securityId', how='right')\n", (7903, 7957), True, 'import pandas as pd\n'), ((10116, 10167), 'numpy.where', 'np.where', (["(data.loc[:, 'upOrdown'] == 1)", '(True)', '(False)'], {}), "(data.loc[:, 'upOrdown'] == 1, True, False)\n", (10124, 10167), True, 'import numpy as np\n'), ((10204, 10256), 'numpy.where', 'np.where', (["(data.loc[:, 'upOrdown'] == -1)", '(True)', '(False)'], {}), "(data.loc[:, 'upOrdown'] == -1, True, False)\n", (10212, 10256), True, 'import numpy as np\n'), ((11284, 11347), 'numpy.where', 'np.where', (["(data0.loc[:, 's_dq_tradestatus'] == '交易')", '(True)', '(False)'], {}), "(data0.loc[:, 's_dq_tradestatus'] == '交易', True, False)\n", (11292, 11347), True, 'import numpy as np\n'), ((11456, 11532), 'pandas.merge', 'pd.merge', ([], {'left': 'data', 'right': 'data0', 'how': '"""outer"""', 'on': "('dateTime', 'securityId')"}), "(left=data, right=data0, how='outer', on=('dateTime', 'securityId'))\n", (11464, 11532), True, 'import pandas as pd\n'), ((12359, 12410), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['date_datetime', '"""%Y%m%d"""'], {}), "(date_datetime, '%Y%m%d')\n", (12385, 12410), False, 'import datetime\n'), ((12716, 12777), 'pandas.merge', 'pd.merge', ([], {'left': 'data', 'right': 'data0', 'how': '"""left"""', 'on': '"""securityId"""'}), "(left=data, right=data0, how='left', on='securityId')\n", (12724, 12777), True, 'import pandas as pd\n'), ((12809, 12859), 'numpy.where', 'np.where', (["(data.loc[:, 'isST'] == True)", '(True)', '(False)'], {}), "(data.loc[:, 'isST'] == True, True, False)\n", (12817, 12859), True, 'import numpy as np\n'), ((2705, 2719), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2717, 2719), True, 'import pandas as pd\n'), ((12452, 12488), 'pandas.isnull', 'pd.isnull', (["data0.loc[:, 'remove_dt']"], {}), "(data0.loc[:, 'remove_dt'])\n", (12461, 12488), True, 'import pandas as pd\n'), ((12537, 12601), 'numpy.where', 'np.where', (["(data0.loc[:, 'remove_dt'] > date_datetime)", '(True)', '(False)'], {}), "(data0.loc[:, 'remove_dt'] > date_datetime, True, False)\n", (12545, 12601), True, 'import numpy as np\n'), ((1684, 1723), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['x', '"""%Y%m%d"""'], {}), "(x, '%Y%m%d')\n", (1710, 1723), False, 'import datetime\n'), ((2361, 2385), 'datafeeds.utils.BarFeedConfig.get_wind', 'BarFeedConfig.get_wind', ([], {}), '()\n', (2383, 2385), False, 'from datafeeds.utils import BarFeedConfig\n'), ((3140, 3191), 'pandas.concat', 'pd.concat', ([], {'objs': '[data, data0]', 'axis': '(0)', 'join': '"""outer"""'}), "(objs=[data, data0], axis=0, join='outer')\n", (3149, 3191), True, 'import pandas as pd\n'), ((4537, 4576), 'datafeeds.utils.BarFeedConfig.get_wind_database_items', 'BarFeedConfig.get_wind_database_items', ([], {}), '()\n', (4574, 4576), False, 'from datafeeds.utils import BarFeedConfig\n'), ((4786, 4825), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['x', '"""%Y%m%d"""'], {}), "(x, '%Y%m%d')\n", (4812, 4825), False, 'import datetime\n'), ((7702, 7741), 'datafeeds.utils.BarFeedConfig.get_wind_database_items', 'BarFeedConfig.get_wind_database_items', ([], {}), '()\n', (7739, 7741), False, 'from datafeeds.utils import BarFeedConfig\n'), ((9811, 9850), 'datafeeds.utils.BarFeedConfig.get_wind_database_items', 'BarFeedConfig.get_wind_database_items', ([], {}), '()\n', (9848, 9850), False, 'from datafeeds.utils import BarFeedConfig\n'), ((10041, 10080), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['x', '"""%Y%m%d"""'], {}), "(x, '%Y%m%d')\n", (10067, 10080), False, 'import datetime\n'), ((11201, 11240), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['x', '"""%Y%m%d"""'], {}), "(x, '%Y%m%d')\n", (11227, 11240), False, 'import datetime\n'), ((12134, 12173), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['x', '"""%Y%m%d"""'], {}), "(x, '%Y%m%d')\n", (12160, 12173), False, 'import datetime\n'), ((7489, 7528), 'datafeeds.utils.BarFeedConfig.get_wind_database_items', 'BarFeedConfig.get_wind_database_items', ([], {}), '()\n', (7526, 7528), False, 'from datafeeds.utils import BarFeedConfig\n'), ((8216, 8255), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['x', '"""%Y%m%d"""'], {}), "(x, '%Y%m%d')\n", (8242, 8255), False, 'import datetime\n'), ((8392, 8431), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['x', '"""%Y%m%d"""'], {}), "(x, '%Y%m%d')\n", (8418, 8431), False, 'import datetime\n'), ((9598, 9637), 'datafeeds.utils.BarFeedConfig.get_wind_database_items', 'BarFeedConfig.get_wind_database_items', ([], {}), '()\n', (9635, 9637), False, 'from datafeeds.utils import BarFeedConfig\n'), ((12293, 12332), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['x', '"""%Y%m%d"""'], {}), "(x, '%Y%m%d')\n", (12319, 12332), False, 'import datetime\n')]
|
import cv2
import tensorflow as tf
import numpy as np
from keras.models import Model
from keras.models import load_model
from numpy import asarray
from PIL import Image, ImageOps
import azure_get_unet as azure_predict
# Since we are using the Azure API, there is not need to save the model to the local filesystem
# model = load_model("/static/model/trees-v1.h5")
# model prediction returns array of prediction
# input is a numpy array
def predict_frame(image):
image = np.expand_dims(image, 0)
result = model.predict(image, batch_size=1)
result = np.squeeze(result, 0)
result = tf.argmax(result, -1)
return result
# for resizing the images after predicting the frames
def resize_frame(arr, shape):
result = Image.fromarray(arr)
result = result.resize(shape)
result = asarray(result)
return result
# change the alpha values of the segmentation masks for overlay
def convert_mask_alpha(image_arr):
img_transparent = Image.fromarray(image_arr)
imga = img_transparent.convert('RGBA')
imga_data = imga.getdata()
newData = []
for item in imga_data:
if (item[0] == 0):
newData.append((0,0,0,0))
else:
# orange transparent mask
newData.append((255,170,0,100))
img_transparent.close()
imga.putdata(newData)
imga = np.array(imga)
return imga
# generate the list for the segmentation frames based on video path
def get_segmentation_frames(video_path):
# Step 1: create the cv2 video capture object
vidObj = cv2.VideoCapture(video_path)
# Step 2: capture the video frames and predict segmentation,
# then append the segmented frames
mask_frames = []
count = 0
success = 1
while (True):
success, image = vidObj.read()
if (success == 0):
break
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Using PIL to get the proper coloration from the cv2 capture
image = Image.fromarray(image)
# 128x128 grayscale for UNet model processing
image = image.resize((128, 128))
image = ImageOps.grayscale(image)
image = asarray(image)
# with the incoming frame, convert to numpy and uint8 dtype
# and resize frames to 1080p values
append = predict_frame(image)
append = np.array(append)
append = append.astype('uint8')
append = resize_frame(append, (480, 270))
# list 1920x1080p numpy arrays
mask_frames.append(append)
# Step 3: convert the lists to numpy, and cast into usable
# black/ white array data for the video writer
mask_frames = np.array(mask_frames)
mask_frames = mask_frames * 255
# just a sanity check for the VideoWriter
mask_frames = mask_frames.astype('uint8')
# return usable arrays for video writing
return mask_frames
# This function will overlay the mask frames with the original video frames
def get_segmentation_frames_compiled(video_path):
# Step 1: retrieve the full sized segmentation frames
print('Generating segmentation frames...')
mask_frames_list = get_segmentation_frames(video_path)
print('Segmentation frames finished')
# Step 2: make a new cv2 video capture object for recycling the image files
vidObj = cv2.VideoCapture(video_path)
compiled_list = []
frame = 0
success = 1
# per frame, compile the values
while (True):
success, image = vidObj.read()
if (success == 0):
break
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = Image.fromarray(image)
image = image.resize((480, 270))
image = image.convert('RGBA')
image = np.array(image)
mask = convert_mask_alpha(mask_frames_list[frame])
add_imgs = cv2.addWeighted(image, 1.0, mask, 0.4, 0.0)
add_imgs = Image.fromarray(add_imgs).convert('RGB')
add_imgs = asarray(add_imgs)
compiled_list.append(add_imgs)
frame += 1
# return the RGBA data list
compiled_list = np.array(compiled_list)
print('Frames are finished compiling')
return compiled_list
# expects uint8, numpy preferrable
def frames_to_video(imput_list, name, isRGB):
out = cv2.VideoWriter(name + '.mp4', cv2.VideoWriter_fourcc(*'MP4V'), 24, (480, 270), isRGB)
for i in range(len(imput_list)):
out.write(imput_list[i])
print('finished')
# input will be a PIL image
def overlay_mask_to_img(original_image):
mask = original_image
mask = mask.resize((128,128))
mask = ImageOps.grayscale(mask)
mask = asarray(mask)
mask = predict_frame(mask)
mask = np.array(mask)
mask = mask.astype('uint8')
mask = convert_mask_alpha(mask)
mask = Image.fromarray(mask)
mask = mask.resize((1200, 600))
original_image = original_image.convert('RGBA')
original_image = asarray(original_image)
original_image = original_image.astype('uint8')
mask = asarray(mask).astype('uint8')
print(original_image.shape)
add_imgs = cv2.addWeighted(original_image, 1.0, mask, 0.4, 0.0)
return add_imgs
|
[
"cv2.VideoWriter_fourcc",
"tensorflow.argmax",
"cv2.cvtColor",
"numpy.asarray",
"numpy.expand_dims",
"PIL.ImageOps.grayscale",
"cv2.addWeighted",
"PIL.Image.fromarray",
"cv2.VideoCapture",
"numpy.array",
"numpy.squeeze"
] |
[((474, 498), 'numpy.expand_dims', 'np.expand_dims', (['image', '(0)'], {}), '(image, 0)\n', (488, 498), True, 'import numpy as np\n'), ((556, 577), 'numpy.squeeze', 'np.squeeze', (['result', '(0)'], {}), '(result, 0)\n', (566, 577), True, 'import numpy as np\n'), ((589, 610), 'tensorflow.argmax', 'tf.argmax', (['result', '(-1)'], {}), '(result, -1)\n', (598, 610), True, 'import tensorflow as tf\n'), ((723, 743), 'PIL.Image.fromarray', 'Image.fromarray', (['arr'], {}), '(arr)\n', (738, 743), False, 'from PIL import Image, ImageOps\n'), ((787, 802), 'numpy.asarray', 'asarray', (['result'], {}), '(result)\n', (794, 802), False, 'from numpy import asarray\n'), ((939, 965), 'PIL.Image.fromarray', 'Image.fromarray', (['image_arr'], {}), '(image_arr)\n', (954, 965), False, 'from PIL import Image, ImageOps\n'), ((1273, 1287), 'numpy.array', 'np.array', (['imga'], {}), '(imga)\n', (1281, 1287), True, 'import numpy as np\n'), ((1476, 1504), 'cv2.VideoCapture', 'cv2.VideoCapture', (['video_path'], {}), '(video_path)\n', (1492, 1504), False, 'import cv2\n'), ((2595, 2616), 'numpy.array', 'np.array', (['mask_frames'], {}), '(mask_frames)\n', (2603, 2616), True, 'import numpy as np\n'), ((3241, 3269), 'cv2.VideoCapture', 'cv2.VideoCapture', (['video_path'], {}), '(video_path)\n', (3257, 3269), False, 'import cv2\n'), ((3997, 4020), 'numpy.array', 'np.array', (['compiled_list'], {}), '(compiled_list)\n', (4005, 4020), True, 'import numpy as np\n'), ((4498, 4522), 'PIL.ImageOps.grayscale', 'ImageOps.grayscale', (['mask'], {}), '(mask)\n', (4516, 4522), False, 'from PIL import Image, ImageOps\n'), ((4532, 4545), 'numpy.asarray', 'asarray', (['mask'], {}), '(mask)\n', (4539, 4545), False, 'from numpy import asarray\n'), ((4584, 4598), 'numpy.array', 'np.array', (['mask'], {}), '(mask)\n', (4592, 4598), True, 'import numpy as np\n'), ((4672, 4693), 'PIL.Image.fromarray', 'Image.fromarray', (['mask'], {}), '(mask)\n', (4687, 4693), False, 'from PIL import Image, ImageOps\n'), ((4797, 4820), 'numpy.asarray', 'asarray', (['original_image'], {}), '(original_image)\n', (4804, 4820), False, 'from numpy import asarray\n'), ((4953, 5005), 'cv2.addWeighted', 'cv2.addWeighted', (['original_image', '(1.0)', 'mask', '(0.4)', '(0.0)'], {}), '(original_image, 1.0, mask, 0.4, 0.0)\n', (4968, 5005), False, 'import cv2\n'), ((1788, 1826), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (1800, 1826), False, 'import cv2\n'), ((1913, 1935), 'PIL.Image.fromarray', 'Image.fromarray', (['image'], {}), '(image)\n', (1928, 1935), False, 'from PIL import Image, ImageOps\n'), ((2048, 2073), 'PIL.ImageOps.grayscale', 'ImageOps.grayscale', (['image'], {}), '(image)\n', (2066, 2073), False, 'from PIL import Image, ImageOps\n'), ((2090, 2104), 'numpy.asarray', 'asarray', (['image'], {}), '(image)\n', (2097, 2104), False, 'from numpy import asarray\n'), ((2272, 2288), 'numpy.array', 'np.array', (['append'], {}), '(append)\n', (2280, 2288), True, 'import numpy as np\n'), ((3479, 3517), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (3491, 3517), False, 'import cv2\n'), ((3534, 3556), 'PIL.Image.fromarray', 'Image.fromarray', (['image'], {}), '(image)\n', (3549, 3556), False, 'from PIL import Image, ImageOps\n'), ((3652, 3667), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (3660, 3667), True, 'import numpy as np\n'), ((3746, 3789), 'cv2.addWeighted', 'cv2.addWeighted', (['image', '(1.0)', 'mask', '(0.4)', '(0.0)'], {}), '(image, 1.0, mask, 0.4, 0.0)\n', (3761, 3789), False, 'import cv2\n'), ((3869, 3886), 'numpy.asarray', 'asarray', (['add_imgs'], {}), '(add_imgs)\n', (3876, 3886), False, 'from numpy import asarray\n'), ((4213, 4244), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'MP4V'"], {}), "(*'MP4V')\n", (4235, 4244), False, 'import cv2\n'), ((4880, 4893), 'numpy.asarray', 'asarray', (['mask'], {}), '(mask)\n', (4887, 4893), False, 'from numpy import asarray\n'), ((3809, 3834), 'PIL.Image.fromarray', 'Image.fromarray', (['add_imgs'], {}), '(add_imgs)\n', (3824, 3834), False, 'from PIL import Image, ImageOps\n')]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.