code
stringlengths 31
1.05M
| apis
list | extract_api
stringlengths 97
1.91M
|
---|---|---|
import cv2, sys, os
import numpy as np
haar_file = 'haarcascade_frontalface_default.xml'
datasets = 'datasets'
print('Recognizing Face Please Be in sufficient Lights...')
(images, lables, names, id) = ([], [], {}, 0)
for (subdirs, dirs, files) in os.walk(datasets):
for subdir in dirs:
names[id] = subdir
subjectpath = os.path.join(datasets, subdir)
for filename in os.listdir(subjectpath):
path = subjectpath + '/' + filename
lable = id
images.append(cv2.imread(path, 0))
lables.append(int(lable))
id += 1
(width, height) = (130, 100)
(images, lables) = [np.array(lis) for lis in [images, lables]]
model = cv2.face.LBPHFaceRecognizer_create()
model.train(images, lables)
face_cascade = cv2.CascadeClassifier(haar_file)
webcam = cv2.VideoCapture(0)
while True:
(_, im) = webcam.read()
(_, im2) = webcam.read()
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
for (x, y, w, h) in faces:
cv2.rectangle(gray, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2)
face = gray[y:y + h, x:x + w]
face_resize = cv2.resize(face, (width, height))
prediction = model.predict(face_resize)
cv2.rectangle(gray, (x, y), (x + w, y + h), (0, 255, 0), 3)
cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 3)
if prediction[1]<100:
cv2.putText(gray, 'The person of % s - %.0f' %(names[prediction[0]], prediction[1]), (x-10, y-10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 2)
cv2.putText(im, 'The person of % s - %.0f' %(names[prediction[0]], prediction[1]), (x-10, y-10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 2)
else:
cv2.putText(gray, 'Not Recognized', (x-10, y-10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 2)
cv2.putText(im, 'Not Recognized', (x-10, y-10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 2)
mask = cv2.inRange(hsv, lower_blue, upper_blue)
cv2.imshow('Window 1', im)
cv2.imshow('Window 2', im2)
cv2.imshow('Window 3', gray)
cv2.imshow('Window 4', mask)
key = cv2.waitKey(10)
if key == 27:
cv2.destroyAllWindows()
break
|
[
"cv2.face.LBPHFaceRecognizer_create",
"os.path.join",
"cv2.putText",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.destroyAllWindows",
"os.walk",
"cv2.VideoCapture",
"cv2.rectangle",
"cv2.imread",
"numpy.array",
"cv2.CascadeClassifier",
"cv2.imshow",
"cv2.inRange",
"os.listdir",
"cv2.resize"
] |
[((252, 269), 'os.walk', 'os.walk', (['datasets'], {}), '(datasets)\n', (259, 269), False, 'import cv2, sys, os\n'), ((645, 681), 'cv2.face.LBPHFaceRecognizer_create', 'cv2.face.LBPHFaceRecognizer_create', ([], {}), '()\n', (679, 681), False, 'import cv2, sys, os\n'), ((727, 759), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['haar_file'], {}), '(haar_file)\n', (748, 759), False, 'import cv2, sys, os\n'), ((770, 789), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (786, 789), False, 'import cv2, sys, os\n'), ((592, 605), 'numpy.array', 'np.array', (['lis'], {}), '(lis)\n', (600, 605), True, 'import numpy as np\n'), ((868, 904), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2GRAY'], {}), '(im, cv2.COLOR_BGR2GRAY)\n', (880, 904), False, 'import cv2, sys, os\n'), ((967, 1002), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2HSV'], {}), '(im, cv2.COLOR_BGR2HSV)\n', (979, 1002), False, 'import cv2, sys, os\n'), ((1017, 1040), 'numpy.array', 'np.array', (['[110, 50, 50]'], {}), '([110, 50, 50])\n', (1025, 1040), True, 'import numpy as np\n'), ((1053, 1078), 'numpy.array', 'np.array', (['[130, 255, 255]'], {}), '([130, 255, 255])\n', (1061, 1078), True, 'import numpy as np\n'), ((2020, 2060), 'cv2.inRange', 'cv2.inRange', (['hsv', 'lower_blue', 'upper_blue'], {}), '(hsv, lower_blue, upper_blue)\n', (2031, 2060), False, 'import cv2, sys, os\n'), ((2063, 2089), 'cv2.imshow', 'cv2.imshow', (['"""Window 1"""', 'im'], {}), "('Window 1', im)\n", (2073, 2089), False, 'import cv2, sys, os\n'), ((2091, 2118), 'cv2.imshow', 'cv2.imshow', (['"""Window 2"""', 'im2'], {}), "('Window 2', im2)\n", (2101, 2118), False, 'import cv2, sys, os\n'), ((2120, 2148), 'cv2.imshow', 'cv2.imshow', (['"""Window 3"""', 'gray'], {}), "('Window 3', gray)\n", (2130, 2148), False, 'import cv2, sys, os\n'), ((2150, 2178), 'cv2.imshow', 'cv2.imshow', (['"""Window 4"""', 'mask'], {}), "('Window 4', mask)\n", (2160, 2178), False, 'import cv2, sys, os\n'), ((2188, 2203), 'cv2.waitKey', 'cv2.waitKey', (['(10)'], {}), '(10)\n', (2199, 2203), False, 'import cv2, sys, os\n'), ((332, 362), 'os.path.join', 'os.path.join', (['datasets', 'subdir'], {}), '(datasets, subdir)\n', (344, 362), False, 'import cv2, sys, os\n'), ((382, 405), 'os.listdir', 'os.listdir', (['subjectpath'], {}), '(subjectpath)\n', (392, 405), False, 'import cv2, sys, os\n'), ((1109, 1168), 'cv2.rectangle', 'cv2.rectangle', (['gray', '(x, y)', '(x + w, y + h)', '(255, 0, 0)', '(2)'], {}), '(gray, (x, y), (x + w, y + h), (255, 0, 0), 2)\n', (1122, 1168), False, 'import cv2, sys, os\n'), ((1172, 1229), 'cv2.rectangle', 'cv2.rectangle', (['im', '(x, y)', '(x + w, y + h)', '(255, 0, 0)', '(2)'], {}), '(im, (x, y), (x + w, y + h), (255, 0, 0), 2)\n', (1185, 1229), False, 'import cv2, sys, os\n'), ((1280, 1313), 'cv2.resize', 'cv2.resize', (['face', '(width, height)'], {}), '(face, (width, height))\n', (1290, 1313), False, 'import cv2, sys, os\n'), ((1363, 1422), 'cv2.rectangle', 'cv2.rectangle', (['gray', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(3)'], {}), '(gray, (x, y), (x + w, y + h), (0, 255, 0), 3)\n', (1376, 1422), False, 'import cv2, sys, os\n'), ((1426, 1483), 'cv2.rectangle', 'cv2.rectangle', (['im', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(3)'], {}), '(im, (x, y), (x + w, y + h), (0, 255, 0), 3)\n', (1439, 1483), False, 'import cv2, sys, os\n'), ((2223, 2246), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2244, 2246), False, 'import cv2, sys, os\n'), ((1516, 1671), 'cv2.putText', 'cv2.putText', (['gray', "('The person of % s - %.0f' % (names[prediction[0]], prediction[1]))", '(x - 10, y - 10)', 'cv2.FONT_HERSHEY_PLAIN', '(1)', '(0, 0, 255)', '(2)'], {}), "(gray, 'The person of % s - %.0f' % (names[prediction[0]],\n prediction[1]), (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 2\n )\n", (1527, 1671), False, 'import cv2, sys, os\n'), ((1665, 1818), 'cv2.putText', 'cv2.putText', (['im', "('The person of % s - %.0f' % (names[prediction[0]], prediction[1]))", '(x - 10, y - 10)', 'cv2.FONT_HERSHEY_PLAIN', '(1)', '(0, 0, 255)', '(2)'], {}), "(im, 'The person of % s - %.0f' % (names[prediction[0]],\n prediction[1]), (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 2\n )\n", (1676, 1818), False, 'import cv2, sys, os\n'), ((1821, 1922), 'cv2.putText', 'cv2.putText', (['gray', '"""Not Recognized"""', '(x - 10, y - 10)', 'cv2.FONT_HERSHEY_PLAIN', '(1)', '(0, 0, 255)', '(2)'], {}), "(gray, 'Not Recognized', (x - 10, y - 10), cv2.\n FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 2)\n", (1832, 1922), False, 'import cv2, sys, os\n'), ((1920, 2018), 'cv2.putText', 'cv2.putText', (['im', '"""Not Recognized"""', '(x - 10, y - 10)', 'cv2.FONT_HERSHEY_PLAIN', '(1)', '(0, 0, 255)', '(2)'], {}), "(im, 'Not Recognized', (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN,\n 1, (0, 0, 255), 2)\n", (1931, 2018), False, 'import cv2, sys, os\n'), ((479, 498), 'cv2.imread', 'cv2.imread', (['path', '(0)'], {}), '(path, 0)\n', (489, 498), False, 'import cv2, sys, os\n')]
|
# -*- coding: utf-8 -*-
from functools import partial
import numpy as np
import pandas as pd
def summarize_results(results):
values = []
for df in results:
values.append(df.pd_dataframe().values)
df = df.pd_dataframe()
columns = df.columns
return (
pd.DataFrame(np.mean(values, axis=0), columns=columns, index=df.index),
pd.DataFrame(np.std(values, axis=0), columns=columns, index=df.index),
)
def _run_backtest(
rep, model, x_test, y_test, start=0.3, stride=1, horizon=4, enable_mc_dropout=True
):
backtest = model.historical_forecasts(
y_test,
past_covariates=x_test,
start=start,
forecast_horizon=horizon,
stride=stride,
retrain=False,
verbose=False,
enable_mc_dropout=enable_mc_dropout,
)
return backtest
def parallelized_inference(
model, x, y, repeats=100, start=0.3, stride=1, horizon=6, enable_mc_dropout=True
):
results = []
backtest_partial = partial(
_run_backtest,
model=model,
x_test=x,
y_test=y,
start=start,
stride=stride,
horizon=horizon,
enable_mc_dropout=enable_mc_dropout,
)
for res in map(backtest_partial, range(repeats)):
results.append(res)
return results
def _run_forcast(_, model, x_full, y_past, future_len, enable_mc_dropout=True):
return model.predict(
future_len, series=y_past, past_covariates=x_full, enable_mc_dropout=enable_mc_dropout
)
def forecast(model, x_full, y_past, future_len, repeats=100, enable_mc_dropout=True):
results = []
backtest_partial = partial(
_run_forcast,
model=model,
x_full=x_full,
y_past=y_past,
future_len=future_len,
enable_mc_dropout=enable_mc_dropout,
)
for res in map(backtest_partial, range(repeats)):
results.append(res)
return results
|
[
"numpy.std",
"functools.partial",
"numpy.mean"
] |
[((1004, 1146), 'functools.partial', 'partial', (['_run_backtest'], {'model': 'model', 'x_test': 'x', 'y_test': 'y', 'start': 'start', 'stride': 'stride', 'horizon': 'horizon', 'enable_mc_dropout': 'enable_mc_dropout'}), '(_run_backtest, model=model, x_test=x, y_test=y, start=start, stride\n =stride, horizon=horizon, enable_mc_dropout=enable_mc_dropout)\n', (1011, 1146), False, 'from functools import partial\n'), ((1655, 1784), 'functools.partial', 'partial', (['_run_forcast'], {'model': 'model', 'x_full': 'x_full', 'y_past': 'y_past', 'future_len': 'future_len', 'enable_mc_dropout': 'enable_mc_dropout'}), '(_run_forcast, model=model, x_full=x_full, y_past=y_past, future_len\n =future_len, enable_mc_dropout=enable_mc_dropout)\n', (1662, 1784), False, 'from functools import partial\n'), ((304, 327), 'numpy.mean', 'np.mean', (['values'], {'axis': '(0)'}), '(values, axis=0)\n', (311, 327), True, 'import numpy as np\n'), ((384, 406), 'numpy.std', 'np.std', (['values'], {'axis': '(0)'}), '(values, axis=0)\n', (390, 406), True, 'import numpy as np\n')]
|
from dataclasses import dataclass
import h5pickle as h5py
import json
import numpy as np
from numpy import ndarray
from pathlib import Path
from typing import List
import random
from robolfd.types import Transition
import robosuite
from robosuite.utils.mjcf_utils import postprocess_model_xml
import itertools
from tqdm import tqdm
from multiprocessing import Pool
@dataclass
class DemoConfig:
obs_keys: dict
max_episodes: int
num_workers: int
def __str__(self) -> str:
return f"demo config - observation keys: {self.obs_keys} max_episodes: {self.max_episodes}, num_workers: {self.num_workers}"
def generate_episode_transitions(demo_info):
f, episode_num, config = demo_info
episodes = list(f["data"].keys())
episode = episodes[episode_num]
env_info = json.loads(f["data"].attrs["env_info"])
env = robosuite.make(
**env_info,
has_renderer=False,
has_offscreen_renderer=False,
ignore_done=True,
use_camera_obs=False,
reward_shaping=True,
control_freq=20,
)
model_xml = f[f"data/{episode}"].attrs["model_file"]
env.reset()
xml = postprocess_model_xml(model_xml)
env.reset_from_xml_string(xml)
env.sim.reset()
all_observations = []
all_actions = []
# TODO: start from state
states = f[f"data/{episode}/states"][()]
actions = np.array(f[f"data/{episode}/actions"][()])
# load the initial state
env.sim.set_state_from_flattened(states[0])
env.sim.forward()
observations = []
action = [0, 0, 0, -1]
observation, _, _, _ = env.step(action)
# observe the current state
observations.append(observation)
used_actions = []
# Fix the order of action, observation sampling problem here
for j, action in enumerate(actions):
action = np.clip(action, -1, 1)
observation, reward, done, misc = env.step(action)
# use when you want to evaluate the environment
# env.render()
used_actions.append(action)
observations.append(observation)
# repeat last action for last observation
used_actions.append(actions[-1])
flat_observations = []
for observation in observations:
flat_observations.append(np.concatenate([observation[key] for key in config.obs_keys]))
# z
all_observations.extend(flat_observations)
all_actions.extend(used_actions)
return list(zip(all_observations, all_actions))
def make_demonstrations(demo_path: Path, config: DemoConfig) -> ndarray:
f = h5py.File(demo_path, "r", skip_cache=False)
episodes = list(f["data"].keys())[-config.max_episodes:]
# TODO: Decide how to batch transitions across episodes
# Dataset is collected in the form of transitions.
pbar = tqdm(total=len(episodes))
with Pool(config.num_workers) as pool:
# simple pool usage
# transitions = pool.map(generate_episode_transitions, [(demo_path, i, config) for i in range(len(episodes))])
# for measuring progress:
res = [pool.apply_async(generate_episode_transitions, args=((f, i, config),),
callback=lambda _: pbar.update(1)) for i in range(len(episodes))]
transitions = [p.get() for p in res]
pool.close()
pool.join()
return transitions
def make_eval_env(demo_path: Path, robot_name="Panda", has_offscreen_renderer = True):
f = h5py.File(demo_path, "r")
env_name = f["data"].attrs["env"]
env_info = json.loads(f["data"].attrs["env_info"])
env_info['robots'] = robot_name
env = robosuite.make(
**env_info,
has_renderer=not has_offscreen_renderer,
has_offscreen_renderer=has_offscreen_renderer,
ignore_done=True,
use_camera_obs=has_offscreen_renderer,
reward_shaping=True,
control_freq=20,
camera_names="frontview",
camera_heights=512,
camera_widths=512,
)
return env
|
[
"robosuite.make",
"json.loads",
"numpy.clip",
"h5pickle.File",
"robosuite.utils.mjcf_utils.postprocess_model_xml",
"numpy.array",
"multiprocessing.Pool",
"numpy.concatenate"
] |
[((802, 841), 'json.loads', 'json.loads', (["f['data'].attrs['env_info']"], {}), "(f['data'].attrs['env_info'])\n", (812, 841), False, 'import json\n'), ((853, 1015), 'robosuite.make', 'robosuite.make', ([], {'has_renderer': '(False)', 'has_offscreen_renderer': '(False)', 'ignore_done': '(True)', 'use_camera_obs': '(False)', 'reward_shaping': '(True)', 'control_freq': '(20)'}), '(**env_info, has_renderer=False, has_offscreen_renderer=False,\n ignore_done=True, use_camera_obs=False, reward_shaping=True,\n control_freq=20)\n', (867, 1015), False, 'import robosuite\n'), ((1155, 1187), 'robosuite.utils.mjcf_utils.postprocess_model_xml', 'postprocess_model_xml', (['model_xml'], {}), '(model_xml)\n', (1176, 1187), False, 'from robosuite.utils.mjcf_utils import postprocess_model_xml\n'), ((1385, 1427), 'numpy.array', 'np.array', (["f[f'data/{episode}/actions'][()]"], {}), "(f[f'data/{episode}/actions'][()])\n", (1393, 1427), True, 'import numpy as np\n'), ((2547, 2590), 'h5pickle.File', 'h5py.File', (['demo_path', '"""r"""'], {'skip_cache': '(False)'}), "(demo_path, 'r', skip_cache=False)\n", (2556, 2590), True, 'import h5pickle as h5py\n'), ((3419, 3444), 'h5pickle.File', 'h5py.File', (['demo_path', '"""r"""'], {}), "(demo_path, 'r')\n", (3428, 3444), True, 'import h5pickle as h5py\n'), ((3498, 3537), 'json.loads', 'json.loads', (["f['data'].attrs['env_info']"], {}), "(f['data'].attrs['env_info'])\n", (3508, 3537), False, 'import json\n'), ((3589, 3879), 'robosuite.make', 'robosuite.make', ([], {'has_renderer': '(not has_offscreen_renderer)', 'has_offscreen_renderer': 'has_offscreen_renderer', 'ignore_done': '(True)', 'use_camera_obs': 'has_offscreen_renderer', 'reward_shaping': '(True)', 'control_freq': '(20)', 'camera_names': '"""frontview"""', 'camera_heights': '(512)', 'camera_widths': '(512)'}), "(**env_info, has_renderer=not has_offscreen_renderer,\n has_offscreen_renderer=has_offscreen_renderer, ignore_done=True,\n use_camera_obs=has_offscreen_renderer, reward_shaping=True,\n control_freq=20, camera_names='frontview', camera_heights=512,\n camera_widths=512)\n", (3603, 3879), False, 'import robosuite\n'), ((1837, 1859), 'numpy.clip', 'np.clip', (['action', '(-1)', '(1)'], {}), '(action, -1, 1)\n', (1844, 1859), True, 'import numpy as np\n'), ((2820, 2844), 'multiprocessing.Pool', 'Pool', (['config.num_workers'], {}), '(config.num_workers)\n', (2824, 2844), False, 'from multiprocessing import Pool\n'), ((2256, 2317), 'numpy.concatenate', 'np.concatenate', (['[observation[key] for key in config.obs_keys]'], {}), '([observation[key] for key in config.obs_keys])\n', (2270, 2317), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 11 18:55:01 2019
@author: kenneth
"""
from __future__ import absolute_import
import numpy as np
from Utils.utils import EvalR
from Utils.Loss import loss
from Utils.kernels import Kernels
class kernelridge(EvalR, loss, Kernels):
def __init__(self, kernel = None, lamda = None):
super().__init__()
if not kernel:
kernel = 'linear'
self.kernel = kernel
else:
self.kernel = kernel
if not lamda:
lamda = 100000
self.lamda = lamda
else:
self.lamda = lamda
return
def kernelize(self, x1, x2):
'''
:params: x1: NxD
:params: x2: NxD
'''
if self.kernel == 'linear':
return Kernels.linear(x1, x2)
elif self.kernel == 'rbf':
return Kernels.rbf(x1, x2)
elif self.kernel == 'sigmoid':
return Kernels.sigmoid(x1, x2)
elif self.kernel == 'polynomial':
return Kernels.polynomial(x1, x2)
elif self.kernel == 'cosine':
return Kernels.cosine(x1, x2)
elif self.kernel == 'correlation':
return Kernels.correlation(x1, x2)
def fit(self, X, y):
'''
:param: X: NxD
:param: Dx1
'''
self.X = X
self.y = y
self.alpha = np.linalg.solve(self.kernelize(self.X, self.X) + self.lamda*np.eye(self.X.shape[0]), self.y)
return self
def predict(self, X):
'''
:param: X: NxD
:return type: Dx1 vector
'''
return np.dot((self.kernelize(self.X, X).T * self.y), self.alpha.T)
#%% Testing
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import Normalizer, StandardScaler
X, y = load_boston().data, load_boston().target
X = StandardScaler().fit_transform(X)
X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size = .3)
kridge = kernelridge().fit(X_train, Y_train)
kridge.predict(X_test)
kridge.summary(X, Y_test, kridge.predict(X_test))
#%%
from sklearn.kernel_ridge import KernelRidge
clf = KernelRidge(alpha=1.0, kernel='linear')
clf.fit(X, y)
kridge.summary(X, Y_test, clf.predict(X_test))
|
[
"sklearn.preprocessing.StandardScaler",
"sklearn.kernel_ridge.KernelRidge",
"sklearn.model_selection.train_test_split",
"Utils.kernels.Kernels.cosine",
"Utils.kernels.Kernels.polynomial",
"sklearn.datasets.load_boston",
"Utils.kernels.Kernels.sigmoid",
"Utils.kernels.Kernels.rbf",
"Utils.kernels.Kernels.correlation",
"numpy.eye",
"Utils.kernels.Kernels.linear"
] |
[((2019, 2056), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.3)'}), '(X, y, test_size=0.3)\n', (2035, 2056), False, 'from sklearn.model_selection import train_test_split\n'), ((2237, 2276), 'sklearn.kernel_ridge.KernelRidge', 'KernelRidge', ([], {'alpha': '(1.0)', 'kernel': '"""linear"""'}), "(alpha=1.0, kernel='linear')\n", (2248, 2276), False, 'from sklearn.kernel_ridge import KernelRidge\n'), ((1905, 1918), 'sklearn.datasets.load_boston', 'load_boston', ([], {}), '()\n', (1916, 1918), False, 'from sklearn.datasets import load_boston\n'), ((1925, 1938), 'sklearn.datasets.load_boston', 'load_boston', ([], {}), '()\n', (1936, 1938), False, 'from sklearn.datasets import load_boston\n'), ((1950, 1966), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (1964, 1966), False, 'from sklearn.preprocessing import Normalizer, StandardScaler\n'), ((822, 844), 'Utils.kernels.Kernels.linear', 'Kernels.linear', (['x1', 'x2'], {}), '(x1, x2)\n', (836, 844), False, 'from Utils.kernels import Kernels\n'), ((899, 918), 'Utils.kernels.Kernels.rbf', 'Kernels.rbf', (['x1', 'x2'], {}), '(x1, x2)\n', (910, 918), False, 'from Utils.kernels import Kernels\n'), ((977, 1000), 'Utils.kernels.Kernels.sigmoid', 'Kernels.sigmoid', (['x1', 'x2'], {}), '(x1, x2)\n', (992, 1000), False, 'from Utils.kernels import Kernels\n'), ((1479, 1502), 'numpy.eye', 'np.eye', (['self.X.shape[0]'], {}), '(self.X.shape[0])\n', (1485, 1502), True, 'import numpy as np\n'), ((1062, 1088), 'Utils.kernels.Kernels.polynomial', 'Kernels.polynomial', (['x1', 'x2'], {}), '(x1, x2)\n', (1080, 1088), False, 'from Utils.kernels import Kernels\n'), ((1146, 1168), 'Utils.kernels.Kernels.cosine', 'Kernels.cosine', (['x1', 'x2'], {}), '(x1, x2)\n', (1160, 1168), False, 'from Utils.kernels import Kernels\n'), ((1231, 1258), 'Utils.kernels.Kernels.correlation', 'Kernels.correlation', (['x1', 'x2'], {}), '(x1, x2)\n', (1250, 1258), False, 'from Utils.kernels import Kernels\n')]
|
"""
Main file
"""
import argparse
import logging
import random
import gym
from tqdm import trange
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from common_definitions import CHECKPOINTS_PATH, TOTAL_EPISODES, TF_LOG_DIR, UNBALANCE_P
from model import Brain
from utils import Tensorboard
if __name__ == "__main__":
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
parser = argparse.ArgumentParser(
prog="Deep Deterministic Policy Gradient (DDPG)",
description="Deep Deterministic Policy Gradient (DDPG) in Tensorflow 2"
)
parser.add_argument('--env', type=str, nargs='?',
default="BipedalWalker-v3",
help='The OpenAI Gym environment to train on, '
'e.g. BipedalWalker-v3, LunarLanderContinuous-v2,'
' Pendulum-v0')
parser.add_argument('--render_env', type=bool, nargs='?', default=True,
help='Render the environment to be visually visible')
parser.add_argument('--train', type=bool, nargs='?', default=True,
help='Train the network on the modified DDPG algorithm')
parser.add_argument('--use_noise', type=bool, nargs='?', default=True,
help='OU Noise will be applied to the policy action')
parser.add_argument('--eps_greedy', type=float, nargs='?', default=0.95,
help="The epsilon for Epsilon-greedy in the policy's action")
parser.add_argument('--warm_up', type=bool, nargs='?', default=1,
help='Following recommendation from OpenAI Spinning Up, the actions in the '
'early epochs can be set random to increase exploration. This warm up '
'defines how many epochs are initially set to do this.')
parser.add_argument('--save_weights', type=bool, nargs='?', default=True,
help='Save the weight of the network in the defined checkpoint file '
'directory.')
args = parser.parse_args()
RL_TASK = args.env
RENDER_ENV = args.render_env
LEARN = args.train
USE_NOISE = args.use_noise
WARM_UP = args.warm_up
SAVE_WEIGHTS = args.save_weights
EPS_GREEDY = args.eps_greedy
# Step 1. create the gym environment
env = gym.make(RL_TASK)
action_space_high = env.action_space.high[0]
action_space_low = env.action_space.low[0]
brain = Brain(env.observation_space.shape[0], env.action_space.shape[0], action_space_high,
action_space_low)
tensorboard = Tensorboard(log_dir=TF_LOG_DIR)
# load weights if available
logging.info("Loading weights from %s*, make sure the folder exists", CHECKPOINTS_PATH)
brain.load_weights(CHECKPOINTS_PATH)
# all the metrics
acc_reward = tf.keras.metrics.Sum('reward', dtype=tf.float32)
actions_squared = tf.keras.metrics.Mean('actions', dtype=tf.float32)
Q_loss = tf.keras.metrics.Mean('Q_loss', dtype=tf.float32)
A_loss = tf.keras.metrics.Mean('A_loss', dtype=tf.float32)
# To store reward history of each episode
ep_reward_list = []
# To store average reward history of last few episodes
avg_reward_list = []
# run iteration
with trange(TOTAL_EPISODES) as t:
for ep in t:
prev_state = env.reset()
acc_reward.reset_states()
actions_squared.reset_states()
Q_loss.reset_states()
A_loss.reset_states()
brain.noise.reset()
for _ in range(2000):
if RENDER_ENV: # render the environment into GUI
env.render()
# Recieve state and reward from environment.
cur_act = brain.act(tf.expand_dims(prev_state, 0), _notrandom=(ep >= WARM_UP) and
(random.random() < EPS_GREEDY+(1-EPS_GREEDY)*ep/TOTAL_EPISODES),
noise=USE_NOISE)
state, reward, done, _ = env.step(cur_act)
brain.remember(prev_state, reward, state, int(done))
# update weights
if LEARN:
c, a = brain.learn(brain.buffer.get_batch(unbalance_p=UNBALANCE_P))
Q_loss(c)
A_loss(a)
# post update for next step
acc_reward(reward)
actions_squared(np.square(cur_act/action_space_high))
prev_state = state
if done:
break
ep_reward_list.append(acc_reward.result().numpy())
# Mean of last 40 episodes
avg_reward = np.mean(ep_reward_list[-40:])
avg_reward_list.append(avg_reward)
# print the average reward
t.set_postfix(r=avg_reward)
tensorboard(ep, acc_reward, actions_squared, Q_loss, A_loss)
# save weights
if ep % 5 == 0 and SAVE_WEIGHTS:
brain.save_weights(CHECKPOINTS_PATH)
env.close()
brain.save_weights(CHECKPOINTS_PATH)
logging.info("Training done...")
# Plotting graph
# Episodes versus Avg. Rewards
plt.plot(avg_reward_list)
plt.xlabel("Episode")
plt.ylabel("Avg. Epsiodic Reward")
plt.show()
|
[
"tensorflow.expand_dims",
"matplotlib.pyplot.show",
"gym.make",
"argparse.ArgumentParser",
"logging.basicConfig",
"tensorflow.keras.metrics.Mean",
"matplotlib.pyplot.plot",
"tqdm.trange",
"numpy.square",
"logging.getLogger",
"logging.info",
"random.random",
"numpy.mean",
"tensorflow.keras.metrics.Sum",
"matplotlib.pyplot.ylabel",
"model.Brain",
"matplotlib.pyplot.xlabel",
"utils.Tensorboard"
] |
[((351, 372), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (370, 372), False, 'import logging\n'), ((434, 584), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""Deep Deterministic Policy Gradient (DDPG)"""', 'description': '"""Deep Deterministic Policy Gradient (DDPG) in Tensorflow 2"""'}), "(prog='Deep Deterministic Policy Gradient (DDPG)',\n description='Deep Deterministic Policy Gradient (DDPG) in Tensorflow 2')\n", (457, 584), False, 'import argparse\n'), ((2392, 2409), 'gym.make', 'gym.make', (['RL_TASK'], {}), '(RL_TASK)\n', (2400, 2409), False, 'import gym\n'), ((2519, 2624), 'model.Brain', 'Brain', (['env.observation_space.shape[0]', 'env.action_space.shape[0]', 'action_space_high', 'action_space_low'], {}), '(env.observation_space.shape[0], env.action_space.shape[0],\n action_space_high, action_space_low)\n', (2524, 2624), False, 'from model import Brain\n'), ((2657, 2688), 'utils.Tensorboard', 'Tensorboard', ([], {'log_dir': 'TF_LOG_DIR'}), '(log_dir=TF_LOG_DIR)\n', (2668, 2688), False, 'from utils import Tensorboard\n'), ((2726, 2817), 'logging.info', 'logging.info', (['"""Loading weights from %s*, make sure the folder exists"""', 'CHECKPOINTS_PATH'], {}), "('Loading weights from %s*, make sure the folder exists',\n CHECKPOINTS_PATH)\n", (2738, 2817), False, 'import logging\n'), ((2895, 2943), 'tensorflow.keras.metrics.Sum', 'tf.keras.metrics.Sum', (['"""reward"""'], {'dtype': 'tf.float32'}), "('reward', dtype=tf.float32)\n", (2915, 2943), True, 'import tensorflow as tf\n'), ((2966, 3016), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', (['"""actions"""'], {'dtype': 'tf.float32'}), "('actions', dtype=tf.float32)\n", (2987, 3016), True, 'import tensorflow as tf\n'), ((3030, 3079), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', (['"""Q_loss"""'], {'dtype': 'tf.float32'}), "('Q_loss', dtype=tf.float32)\n", (3051, 3079), True, 'import tensorflow as tf\n'), ((3093, 3142), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', (['"""A_loss"""'], {'dtype': 'tf.float32'}), "('A_loss', dtype=tf.float32)\n", (3114, 3142), True, 'import tensorflow as tf\n'), ((5164, 5196), 'logging.info', 'logging.info', (['"""Training done..."""'], {}), "('Training done...')\n", (5176, 5196), False, 'import logging\n'), ((5258, 5283), 'matplotlib.pyplot.plot', 'plt.plot', (['avg_reward_list'], {}), '(avg_reward_list)\n', (5266, 5283), True, 'import matplotlib.pyplot as plt\n'), ((5288, 5309), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Episode"""'], {}), "('Episode')\n", (5298, 5309), True, 'import matplotlib.pyplot as plt\n'), ((5314, 5348), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Avg. Epsiodic Reward"""'], {}), "('Avg. Epsiodic Reward')\n", (5324, 5348), True, 'import matplotlib.pyplot as plt\n'), ((5353, 5363), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5361, 5363), True, 'import matplotlib.pyplot as plt\n'), ((3328, 3350), 'tqdm.trange', 'trange', (['TOTAL_EPISODES'], {}), '(TOTAL_EPISODES)\n', (3334, 3350), False, 'from tqdm import trange\n'), ((377, 396), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (394, 396), False, 'import logging\n'), ((4745, 4774), 'numpy.mean', 'np.mean', (['ep_reward_list[-40:]'], {}), '(ep_reward_list[-40:])\n', (4752, 4774), True, 'import numpy as np\n'), ((3828, 3857), 'tensorflow.expand_dims', 'tf.expand_dims', (['prev_state', '(0)'], {}), '(prev_state, 0)\n', (3842, 3857), True, 'import tensorflow as tf\n'), ((4492, 4530), 'numpy.square', 'np.square', (['(cur_act / action_space_high)'], {}), '(cur_act / action_space_high)\n', (4501, 4530), True, 'import numpy as np\n'), ((3927, 3942), 'random.random', 'random.random', ([], {}), '()\n', (3940, 3942), False, 'import random\n')]
|
import tensorflow as tf
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
import argparse
import random
import gym
import sys
from collections import deque
from keras import backend as K
from keras.layers import Input, Dense
from keras.models import Model
from keras.utils import plot_model
env = gym.make('MountainCar-v0')
state_space=env.observation_space.shape[0]
action_s=env.action_space.n
#Hyperparameters
learning_rate=0.001
episodes=1000000
epsilon_start=0.5
epsilon_end=0.05
#decay=(epsilon_start-epsilon_end)/100000
decay = 0.9
batch_size=32
max_steps=200
gamma=1.0
hidden_layer=50
class QNetwork():
def __init__(self,learning_rate,action_space,input_dim):
# self.model= Sequential()
# self.model.add(Dense(units=30,activation='relu',input_dim=state_space,kernel_initializer='he_uniform'))
# self.model.add(Dense(units=30,activation='relu',kernel_initializer='he_uniform'))
# self.model.add(Dense(units=30,activation='relu',kernel_initializer='he_uniform'))
# self.model.add(Dense(units=action_s,activation='linear',kernel_initializer='he_uniform'))
self.input = Input(shape=(input_dim,))
self.x=Dense(hidden_layer,activation='relu')(self.input)
# self.x=keras.layers.BatchNormalization(axis=-1)(self.x)
self.x=Dense(hidden_layer,activation='relu')(self.x)
# self.x=keras.layers.BatchNormalization(axis=-1)(self.x)
self.x=Dense(hidden_layer,activation='relu')(self.x)
self.value= Dense(1,activation='linear',name='value')(self.x)
self.value1=self.value
self.advantage = Dense(action_s,activation='linear',name='advantage')(self.x)
self.advantage_mean = keras.layers.Lambda(lambda x:K.mean(x,axis=-1,keepdims=True))(self.advantage)
self.advantage_mean1 = self.advantage_mean
# self.value=keras.layers.RepeatVector(2)
# print('Value',self.value.shape)
# self.value = keras.layers.Lambda(lambda x:K.equal(x,axis=-1,keepdims=True))(self.value)
i=1
while(i<action_s):
self.value=keras.layers.Lambda(lambda x:K.concatenate(x, axis=-1))([self.value,self.value1])
self.advantage_mean=keras.layers.Lambda(lambda x:K.concatenate(x,axis=-1))([self.advantage_mean1,self.advantage_mean])
i+=1
# print('Adv',self.keras.backend.identity.shape)
# self.advantage_mean=keras.layers.Lambda(lambda x:K.identity(x))(self.advantage_mean)
# print('Val1',self.value1.shape)
self.advantage_subtract_mean = keras.layers.Subtract()([self.advantage,self.advantage_mean])
# print('Adv su',self.advantage_mean.shape)
self.added = keras.layers.Add()([self.advantage_subtract_mean,self.value])
# print("Added",self.added.shape)
# equivalent to added = keras.layers.add([x1, x2])
# self.out = Dense(action_s,activation='linear')(self.added)
# print("out",self.out.shape)
self.optimizer=keras.optimizers.Adam(lr=learning_rate)
self.model = Model(inputs=self.input, outputs=self.added)
self.model.compile(loss='mse',optimizer=self.optimizer)
plot_model(self.model, to_file='Duelling2.png')
def save_model_weights(self, fname):
self.model.save_weights(fname)
def load_model(self, model_file):
self.model.load(model_file)
def load_model_weights(self,fname):
self.model.load_weights(fname)
class DQN_Agent():
# In this class, we will implement functions to do the following.
# (1) Create an instance of the Q Network class.
# (2) Create a function that constructs a policy from the Q values predicted by the Q Network.
# (a) Epsilon Greedy Policy.
# (b) Greedy Policy.
# (3) Create a function to train the Q Network, by interacting with the environment.
# (4) Create a function to test the Q Network's performance on the environment.
# (5) Create a function for Experience Replay.
def __init__(self, environment_name, render=False):
self.env = environment_name
self.net=QNetwork(learning_rate,action_s,state_space)
self.prev_net=QNetwork(learning_rate,action_s,state_space)
self.prev_net.model.set_weights(self.net.model.get_weights())
self.q_values=np.zeros([batch_size,action_s])
self.memory=Replay_Memory()
self.burn_in_memory()
def epsilon_greedy_policy(self, q_values,epsilon):
if (epsilon>np.random.random()):
action=random.randrange(action_s)
else:
action=np.argmax(q_values[0])
return action
def greedy_policy(self, q_values):
action=np.argmax(q_values)
return action
def train(self):
# In this function, we will train our network.
# If training without experience replay_memory, then you will interact with the environment
# in this function, while also updating your network parameters.
# If you are using a replay memory, you should interact with environment here, and store these
# transitions to memory, while also updating your model.
epsilon = epsilon_start
for i in range(1000000):
state = env.reset()
state=np.reshape(state,[1,state_space])
total_reward=0
step=0
while step<max_steps:
env.render()
step+=1
q_values = self.net.model.predict(state)
action=self.epsilon_greedy_policy(q_values,epsilon)
new_state,reward,done, _ = env.step(action)
new_state=np.reshape(new_state,[1,state_space])
self.memory.append([state,action,reward,done,new_state])
minibatch=self.memory.sample_batch()
batch_states=np.zeros((batch_size,state_space))
batch_next_states=np.zeros((batch_size,state_space))
t_int=0
for batch_state, batch_action, batch_reward, batch_done, batch_new_state in minibatch:
batch_states[t_int]=batch_state
batch_next_states[t_int]=batch_new_state
t_int+=1
batch_q_values=self.net.model.predict(batch_states)
batch_prev_q_values=self.prev_net.model.predict(batch_next_states)
t_int=0
for batch_state, batch_action, batch_reward, batch_done, batch_new_state in minibatch:
if batch_done:
temp=0
else:
temp=gamma*(np.amax(batch_prev_q_values[t_int]))
batch_q_values[t_int][batch_action] = batch_reward+temp
t_int+=1
self.net.model.fit(batch_states,batch_q_values,batch_size=batch_size,epochs=1,verbose=0)
epsilon*=decay
if epsilon<epsilon_end:
epsilon = epsilon_end
total_reward+=reward
state=new_state
if done:
break
self.prev_net.model.set_weights(self.net.model.get_weights())
print(i,total_reward)
def test(self, model_file=None):
# Evaluate the performance of your agent over 100 episodes, by calculating cummulative rewards for the 100 episodes.
# Here you need to interact with the environment, irrespective of whether you are using a memory.
pass
def burn_in_memory(self):
state = env.reset()
state=np.reshape(state,[1,state_space])
for i in range(self.memory.burn_in):
action=random.randrange(action_s)
new_state, reward, done, _ = env.step(action)
new_state=np.reshape(new_state,[1,state_space])
self.memory.append([state,action,reward,done,new_state])
state=new_state
if done:
state=env.reset()
state=np.reshape(state,[1,state_space])
class Replay_Memory():
def __init__(self, memory_size=10000, burn_in=5000):
self.transitions =[]
self.memory_size=memory_size
self.burn_in = burn_in
def sample_batch(self, batch_size=32):
return random.sample(self.transitions,batch_size)
def append(self, transition):
if(len(self.transitions)<self.memory_size):
self.transitions.append(transition)
else:
idx=random.randint(1,self.memory_size-1)
# print(idx)
del self.transitions[idx]
self.transitions.append(transition)
def parse_arguments():
parser = argparse.ArgumentParser(description='Linear Q network parser')
parser.add_argument('--env',dest='env',type=str)
parser.add_argument('--render',dest='render',type=int,default=0)
parser.add_argument('--train',dest='train',type=int,default=1)
parser.add_argument('--model',dest='model_file',type=str)
return parser.parse_args()
def main(args):
args = parse_arguments()
environment_name = args.env
# Setting the session to allow growth, so it doesn't allocate all GPU memory.
gpu_ops = tf.GPUOptions(allow_growth=True)
config = tf.ConfigProto(gpu_options=gpu_ops)
sess = tf.Session(config=config)
# Setting this as the default tensorflow session.
keras.backend.tensorflow_backend.set_session(sess)
agent=DQN_Agent(environment_name)
# print(agent)
DQN_Agent.train(agent)
# You want to create an instance of the DQN_Agent class here, and then train / test it.
if __name__ == '__main__':
main(sys.argv)
|
[
"argparse.ArgumentParser",
"numpy.argmax",
"random.sample",
"keras.models.Model",
"tensorflow.ConfigProto",
"keras.layers.Input",
"keras.backend.tensorflow_backend.set_session",
"tensorflow.GPUOptions",
"keras.backend.concatenate",
"random.randint",
"keras.utils.plot_model",
"numpy.reshape",
"tensorflow.Session",
"keras.optimizers.Adam",
"gym.make",
"numpy.zeros",
"keras.layers.Add",
"numpy.amax",
"keras.layers.Dense",
"numpy.random.random",
"random.randrange",
"keras.layers.Subtract",
"keras.backend.mean"
] |
[((360, 386), 'gym.make', 'gym.make', (['"""MountainCar-v0"""'], {}), "('MountainCar-v0')\n", (368, 386), False, 'import gym\n'), ((7552, 7614), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Linear Q network parser"""'}), "(description='Linear Q network parser')\n", (7575, 7614), False, 'import argparse\n'), ((8047, 8079), 'tensorflow.GPUOptions', 'tf.GPUOptions', ([], {'allow_growth': '(True)'}), '(allow_growth=True)\n', (8060, 8079), True, 'import tensorflow as tf\n'), ((8090, 8125), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'gpu_options': 'gpu_ops'}), '(gpu_options=gpu_ops)\n', (8104, 8125), True, 'import tensorflow as tf\n'), ((8134, 8159), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (8144, 8159), True, 'import tensorflow as tf\n'), ((8214, 8264), 'keras.backend.tensorflow_backend.set_session', 'keras.backend.tensorflow_backend.set_session', (['sess'], {}), '(sess)\n', (8258, 8264), False, 'import keras\n'), ((1155, 1180), 'keras.layers.Input', 'Input', ([], {'shape': '(input_dim,)'}), '(shape=(input_dim,))\n', (1160, 1180), False, 'from keras.layers import Input, Dense\n'), ((2818, 2857), 'keras.optimizers.Adam', 'keras.optimizers.Adam', ([], {'lr': 'learning_rate'}), '(lr=learning_rate)\n', (2839, 2857), False, 'import keras\n'), ((2873, 2917), 'keras.models.Model', 'Model', ([], {'inputs': 'self.input', 'outputs': 'self.added'}), '(inputs=self.input, outputs=self.added)\n', (2878, 2917), False, 'from keras.models import Model\n'), ((2978, 3025), 'keras.utils.plot_model', 'plot_model', (['self.model'], {'to_file': '"""Duelling2.png"""'}), "(self.model, to_file='Duelling2.png')\n", (2988, 3025), False, 'from keras.utils import plot_model\n'), ((4024, 4056), 'numpy.zeros', 'np.zeros', (['[batch_size, action_s]'], {}), '([batch_size, action_s])\n', (4032, 4056), True, 'import numpy as np\n'), ((4341, 4360), 'numpy.argmax', 'np.argmax', (['q_values'], {}), '(q_values)\n', (4350, 4360), True, 'import numpy as np\n'), ((6646, 6681), 'numpy.reshape', 'np.reshape', (['state', '[1, state_space]'], {}), '(state, [1, state_space])\n', (6656, 6681), True, 'import numpy as np\n'), ((7221, 7264), 'random.sample', 'random.sample', (['self.transitions', 'batch_size'], {}), '(self.transitions, batch_size)\n', (7234, 7264), False, 'import random\n'), ((1190, 1228), 'keras.layers.Dense', 'Dense', (['hidden_layer'], {'activation': '"""relu"""'}), "(hidden_layer, activation='relu')\n", (1195, 1228), False, 'from keras.layers import Input, Dense\n'), ((1309, 1347), 'keras.layers.Dense', 'Dense', (['hidden_layer'], {'activation': '"""relu"""'}), "(hidden_layer, activation='relu')\n", (1314, 1347), False, 'from keras.layers import Input, Dense\n'), ((1424, 1462), 'keras.layers.Dense', 'Dense', (['hidden_layer'], {'activation': '"""relu"""'}), "(hidden_layer, activation='relu')\n", (1429, 1462), False, 'from keras.layers import Input, Dense\n'), ((1485, 1528), 'keras.layers.Dense', 'Dense', (['(1)'], {'activation': '"""linear"""', 'name': '"""value"""'}), "(1, activation='linear', name='value')\n", (1490, 1528), False, 'from keras.layers import Input, Dense\n'), ((1580, 1634), 'keras.layers.Dense', 'Dense', (['action_s'], {'activation': '"""linear"""', 'name': '"""advantage"""'}), "(action_s, activation='linear', name='advantage')\n", (1585, 1634), False, 'from keras.layers import Input, Dense\n'), ((2429, 2452), 'keras.layers.Subtract', 'keras.layers.Subtract', ([], {}), '()\n', (2450, 2452), False, 'import keras\n'), ((2553, 2571), 'keras.layers.Add', 'keras.layers.Add', ([], {}), '()\n', (2569, 2571), False, 'import keras\n'), ((4178, 4196), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (4194, 4196), True, 'import numpy as np\n'), ((4209, 4235), 'random.randrange', 'random.randrange', (['action_s'], {}), '(action_s)\n', (4225, 4235), False, 'import random\n'), ((4254, 4276), 'numpy.argmax', 'np.argmax', (['q_values[0]'], {}), '(q_values[0])\n', (4263, 4276), True, 'import numpy as np\n'), ((4853, 4888), 'numpy.reshape', 'np.reshape', (['state', '[1, state_space]'], {}), '(state, [1, state_space])\n', (4863, 4888), True, 'import numpy as np\n'), ((6729, 6755), 'random.randrange', 'random.randrange', (['action_s'], {}), '(action_s)\n', (6745, 6755), False, 'import random\n'), ((6818, 6857), 'numpy.reshape', 'np.reshape', (['new_state', '[1, state_space]'], {}), '(new_state, [1, state_space])\n', (6828, 6857), True, 'import numpy as np\n'), ((7396, 7435), 'random.randint', 'random.randint', (['(1)', '(self.memory_size - 1)'], {}), '(1, self.memory_size - 1)\n', (7410, 7435), False, 'import random\n'), ((5139, 5178), 'numpy.reshape', 'np.reshape', (['new_state', '[1, state_space]'], {}), '(new_state, [1, state_space])\n', (5149, 5178), True, 'import numpy as np\n'), ((5297, 5332), 'numpy.zeros', 'np.zeros', (['(batch_size, state_space)'], {}), '((batch_size, state_space))\n', (5305, 5332), True, 'import numpy as np\n'), ((5354, 5389), 'numpy.zeros', 'np.zeros', (['(batch_size, state_space)'], {}), '((batch_size, state_space))\n', (5362, 5389), True, 'import numpy as np\n'), ((6979, 7014), 'numpy.reshape', 'np.reshape', (['state', '[1, state_space]'], {}), '(state, [1, state_space])\n', (6989, 7014), True, 'import numpy as np\n'), ((1697, 1730), 'keras.backend.mean', 'K.mean', (['x'], {'axis': '(-1)', 'keepdims': '(True)'}), '(x, axis=-1, keepdims=True)\n', (1703, 1730), True, 'from keras import backend as K\n'), ((2037, 2062), 'keras.backend.concatenate', 'K.concatenate', (['x'], {'axis': '(-1)'}), '(x, axis=-1)\n', (2050, 2062), True, 'from keras import backend as K\n'), ((2142, 2167), 'keras.backend.concatenate', 'K.concatenate', (['x'], {'axis': '(-1)'}), '(x, axis=-1)\n', (2155, 2167), True, 'from keras import backend as K\n'), ((5885, 5920), 'numpy.amax', 'np.amax', (['batch_prev_q_values[t_int]'], {}), '(batch_prev_q_values[t_int])\n', (5892, 5920), True, 'import numpy as np\n')]
|
from pykinect2 import PyKinectV2
from pykinect2.PyKinectV2 import *
from pykinect2 import PyKinectRuntime
import ctypes
import _ctypes
import pygame
import sys
import numpy as np
import cv2
#if sys.hexversion >= 0x03000000:
# import _thread as thread
#else:
# import thread
class DepthRuntime(object):
def __init__(self):
pygame.init()
# Used to manage how fast the screen updates
self._clock = pygame.time.Clock()
# Loop until the user clicks the close button.
self._done = False
# Used to manage how fast the screen updates
self._clock = pygame.time.Clock()
# Kinect runtime object, we want only color and body frames
self._kinect = PyKinectRuntime.PyKinectRuntime(PyKinectV2.FrameSourceTypes_Depth)
# back buffer surface for getting Kinect depth frames, 8bit grey, width and height equal to the Kinect depth frame size
self._frame_surface = pygame.Surface((self._kinect.depth_frame_desc.Width, self._kinect.depth_frame_desc.Height), 0, 24)
# here we will store skeleton data
self._bodies = None
# Set the width and height of the screen [width, height]
self._infoObject = pygame.display.Info()
self._screen = pygame.display.set_mode((self._kinect.depth_frame_desc.Width, self._kinect.depth_frame_desc.Height), pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE, 32)
pygame.display.set_caption("Kinect for Windows v2 Depth")
#def background_subtraction(self, current_frame, previous_frame):
# previousFrame = [0] * 217088
# return frame
def draw_depth_frame(self, frame, target_surface):
if frame is None: # some usb hub do not provide the infrared image. it works with Kinect studio though
return
target_surface.lock()
f8=np.uint8(frame.clip(1,4000)/16.)
frame8bit=np.dstack((f8,f8,f8))
address = self._kinect.surface_as_array(target_surface.get_buffer())
ctypes.memmove(address, frame8bit.ctypes.data, frame8bit.size)
del address
target_surface.unlock()
def run(self):
# -------- Main Program Loop -----------
frame = [0] * 217088
frames = [frame] * 5
fgbg = cv2.createBackgroundSubtractorKNN()
# fgbg = cv2.createBackgroundSubtractorMOG2()
# print (len(previousFrames))
# print(previousFrames)
while not self._done:
# --- Main event loop
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
self._done = True # Flag that we are done so we exit this loop
elif event.type == pygame.VIDEORESIZE: # window resized
self._screen = pygame.display.set_mode(event.dict['size'], pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE, 32)
# --- Getting frames and drawing
if self._kinect.has_new_depth_frame():
frame = self._kinect.get_last_depth_frame()
fgmask = fgbg.apply(frame)
# flattenMask = []
# for item in fgmask:
# flattenMask.append(item)
flattenMask = [value for element in fgmask for value in element]
# print (type(flattenMask[0]))
flattenMask = np.array(flattenMask)
# flattenMask = np.array(fgmask)
# flattenMask = flattenMask / 255
# print ("flattenMask\n",flattenMask)
frameMask = []
# frameMask = np.array(frameMask)
for val in np.nditer(flattenMask):
# i = 0
if val == 255:
frameMask.append(1)
# val = 1
else:
frameMask.append(0)
# val = 0
# i += 1
frameMask = np.array(frameMask)
# np.set_printoptions(threshold=sys.maxsize)
# print("frame\n",frame)
# print ("flattenMask\n",flattenMask)
# print ("frameMask\n",frameMask)
outputFrame = np.multiply(frame, frameMask)
# frames.append(outputFrame)
# frames.pop(0)
# outputFrame2 = []
# cv2.fastNlMeansDenoisingMulti(frames, 4, 4, outputFrame2)
# outputFrame2 = cv2.fastNlMeansDenoising(outputFrame)
# outputFrame = np.multiply(frame, fgmask)
# cv2.imshow('frame',fgmask)
self.draw_depth_frame(outputFrame, self._frame_surface)
# k = cv2.waitKey(30) & 0xff
# if k == 27:
# break
# frames.append(frame)
# frames.pop(0)
# outputFrame = np.subtract(frames[0], frames[1])
# self.draw_depth_frame(outputFrame, self._frame_surface)
#self.draw_depth_frame(frame, self._frame_surface)
#frame = np.average(np.array([frame, previousFrame]), axis=0)
#np.set_printoptions(threshold=sys.maxsize)
#print(outputFrame)
#print(frame.size)
# outputFrame = (np.array(previousFrames[0]) + np.array(previousFrames[1]) + np.array(previousFrames[2]) + np.array(previousFrames[3]) + np.array(previousFrames[4])) / 5
# self.draw_depth_frame(outputFrame.astype(int), self._frame_surface)
# frame2 = cv.fastNlMeansDenoisingMulti(previousFrames, 2 , 3)
frame = None
outputFrame = None
self._screen.blit(self._frame_surface, (0,0))
pygame.display.update()
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
self._clock.tick(60)
# Close our Kinect sensor, close the window and quit.
self._kinect.close()
pygame.quit()
__main__ = "Kinect v2 Depth"
game =DepthRuntime();
game.run();
|
[
"numpy.dstack",
"pygame.quit",
"numpy.multiply",
"pygame.Surface",
"pygame.event.get",
"pygame.display.set_mode",
"cv2.createBackgroundSubtractorKNN",
"numpy.nditer",
"ctypes.memmove",
"pygame.init",
"pygame.display.flip",
"pykinect2.PyKinectRuntime.PyKinectRuntime",
"pygame.display.update",
"pygame.display.Info",
"numpy.array",
"pygame.display.set_caption",
"pygame.time.Clock"
] |
[((341, 354), 'pygame.init', 'pygame.init', ([], {}), '()\n', (352, 354), False, 'import pygame\n'), ((430, 449), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (447, 449), False, 'import pygame\n'), ((607, 626), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (624, 626), False, 'import pygame\n'), ((719, 785), 'pykinect2.PyKinectRuntime.PyKinectRuntime', 'PyKinectRuntime.PyKinectRuntime', (['PyKinectV2.FrameSourceTypes_Depth'], {}), '(PyKinectV2.FrameSourceTypes_Depth)\n', (750, 785), False, 'from pykinect2 import PyKinectRuntime\n'), ((944, 1047), 'pygame.Surface', 'pygame.Surface', (['(self._kinect.depth_frame_desc.Width, self._kinect.depth_frame_desc.Height)', '(0)', '(24)'], {}), '((self._kinect.depth_frame_desc.Width, self._kinect.\n depth_frame_desc.Height), 0, 24)\n', (958, 1047), False, 'import pygame\n'), ((1207, 1228), 'pygame.display.Info', 'pygame.display.Info', ([], {}), '()\n', (1226, 1228), False, 'import pygame\n'), ((1252, 1422), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(self._kinect.depth_frame_desc.Width, self._kinect.depth_frame_desc.Height)', '(pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.RESIZABLE)', '(32)'], {}), '((self._kinect.depth_frame_desc.Width, self._kinect.\n depth_frame_desc.Height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.\n RESIZABLE, 32)\n', (1275, 1422), False, 'import pygame\n'), ((1417, 1474), 'pygame.display.set_caption', 'pygame.display.set_caption', (['"""Kinect for Windows v2 Depth"""'], {}), "('Kinect for Windows v2 Depth')\n", (1443, 1474), False, 'import pygame\n'), ((1883, 1906), 'numpy.dstack', 'np.dstack', (['(f8, f8, f8)'], {}), '((f8, f8, f8))\n', (1892, 1906), True, 'import numpy as np\n'), ((1990, 2052), 'ctypes.memmove', 'ctypes.memmove', (['address', 'frame8bit.ctypes.data', 'frame8bit.size'], {}), '(address, frame8bit.ctypes.data, frame8bit.size)\n', (2004, 2052), False, 'import ctypes\n'), ((2255, 2290), 'cv2.createBackgroundSubtractorKNN', 'cv2.createBackgroundSubtractorKNN', ([], {}), '()\n', (2288, 2290), False, 'import cv2\n'), ((6101, 6114), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (6112, 6114), False, 'import pygame\n'), ((2504, 2522), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (2520, 2522), False, 'import pygame\n'), ((5791, 5814), 'pygame.display.update', 'pygame.display.update', ([], {}), '()\n', (5812, 5814), False, 'import pygame\n'), ((5899, 5920), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (5918, 5920), False, 'import pygame\n'), ((3383, 3404), 'numpy.array', 'np.array', (['flattenMask'], {}), '(flattenMask)\n', (3391, 3404), True, 'import numpy as np\n'), ((3666, 3688), 'numpy.nditer', 'np.nditer', (['flattenMask'], {}), '(flattenMask)\n', (3675, 3688), True, 'import numpy as np\n'), ((3992, 4011), 'numpy.array', 'np.array', (['frameMask'], {}), '(frameMask)\n', (4000, 4011), True, 'import numpy as np\n'), ((4248, 4277), 'numpy.multiply', 'np.multiply', (['frame', 'frameMask'], {}), '(frame, frameMask)\n', (4259, 4277), True, 'import numpy as np\n'), ((2805, 2913), 'pygame.display.set_mode', 'pygame.display.set_mode', (["event.dict['size']", '(pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.RESIZABLE)', '(32)'], {}), "(event.dict['size'], pygame.HWSURFACE | pygame.\n DOUBLEBUF | pygame.RESIZABLE, 32)\n", (2828, 2913), False, 'import pygame\n')]
|
import numpy as np
from .strategy import Strategy
from sklearn.neighbors import NearestNeighbors
import pickle
from datetime import datetime
class CoreSet(Strategy):
def __init__(self, X, Y, idxs_lb, net, handler, args, tor=1e-4):
super(CoreSet, self).__init__(X, Y, idxs_lb, net, handler, args)
self.tor = tor
def query(self, n):
lb_flag = self.idxs_lb.copy()
embedding = self.get_embedding(self.X, self.Y)
embedding = embedding.numpy()
print('calculate distance matrix')
t_start = datetime.now()
dist_mat = np.matmul(embedding, embedding.transpose())
sq = np.array(dist_mat.diagonal()).reshape(len(self.X), 1)
dist_mat *= -2
dist_mat += sq
dist_mat += sq.transpose()
dist_mat = np.sqrt(dist_mat)
print(datetime.now() - t_start)
print('calculate greedy solution')
t_start = datetime.now()
mat = dist_mat[~lb_flag, :][:, lb_flag]
for i in range(n):
if i%10 == 0:
print('greedy solution {}/{}'.format(i, n))
mat_min = mat.min(axis=1)
q_idx_ = mat_min.argmax()
q_idx = np.arange(self.n_pool)[~lb_flag][q_idx_]
lb_flag[q_idx] = True
mat = np.delete(mat, q_idx_, 0)
mat = np.append(mat, dist_mat[~lb_flag, q_idx][:, None], axis=1)
print(datetime.now() - t_start)
opt = mat.min(axis=1).max()
bound_u = opt
bound_l = opt/2.0
delta = opt
xx, yy = np.where(dist_mat <= opt)
dd = dist_mat[xx, yy]
lb_flag_ = self.idxs_lb.copy()
subset = np.where(lb_flag_==True)[0].tolist()
SEED = 5
pickle.dump((xx.tolist(), yy.tolist(), dd.tolist(), subset, float(opt), n, self.n_pool), open('mip{}.pkl'.format(SEED), 'wb'), 2)
import ipdb
ipdb.set_trace()
# solving MIP
# download Gurobi software from http://www.gurobi.com/
# sh {GUROBI_HOME}/linux64/bin/gurobi.sh < core_set_sovle_solve.py
sols = pickle.load(open('sols{}.pkl'.format(SEED), 'rb'))
if sols is None:
q_idxs = lb_flag
else:
lb_flag_[sols] = True
q_idxs = lb_flag_
print('sum q_idxs = {}'.format(q_idxs.sum()))
return np.arange(self.n_pool)[(self.idxs_lb ^ q_idxs)]
|
[
"ipdb.set_trace",
"numpy.append",
"numpy.where",
"numpy.arange",
"datetime.datetime.now",
"numpy.delete",
"numpy.sqrt"
] |
[((502, 516), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (514, 516), False, 'from datetime import datetime\n'), ((711, 728), 'numpy.sqrt', 'np.sqrt', (['dist_mat'], {}), '(dist_mat)\n', (718, 728), True, 'import numpy as np\n'), ((813, 827), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (825, 827), False, 'from datetime import datetime\n'), ((1323, 1348), 'numpy.where', 'np.where', (['(dist_mat <= opt)'], {}), '(dist_mat <= opt)\n', (1331, 1348), True, 'import numpy as np\n'), ((1617, 1633), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (1631, 1633), False, 'import ipdb\n'), ((1101, 1126), 'numpy.delete', 'np.delete', (['mat', 'q_idx_', '(0)'], {}), '(mat, q_idx_, 0)\n', (1110, 1126), True, 'import numpy as np\n'), ((1136, 1194), 'numpy.append', 'np.append', (['mat', 'dist_mat[~lb_flag, q_idx][:, None]'], {'axis': '(1)'}), '(mat, dist_mat[~lb_flag, q_idx][:, None], axis=1)\n', (1145, 1194), True, 'import numpy as np\n'), ((1989, 2011), 'numpy.arange', 'np.arange', (['self.n_pool'], {}), '(self.n_pool)\n', (1998, 2011), True, 'import numpy as np\n'), ((737, 751), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (749, 751), False, 'from datetime import datetime\n'), ((1204, 1218), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1216, 1218), False, 'from datetime import datetime\n'), ((1026, 1048), 'numpy.arange', 'np.arange', (['self.n_pool'], {}), '(self.n_pool)\n', (1035, 1048), True, 'import numpy as np\n'), ((1418, 1444), 'numpy.where', 'np.where', (['(lb_flag_ == True)'], {}), '(lb_flag_ == True)\n', (1426, 1444), True, 'import numpy as np\n')]
|
#!/usr/bin/python
import os, math
import pandas as pd
import numpy as np
np.random.seed(42)
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.optim as optim
torch.manual_seed(42)
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import ParameterSampler
def doc_mean_thres(df):
doc_mean = df.mean()
df_bin = 1.0 * (df.values > doc_mean.values)
df_bin = pd.DataFrame(df_bin, columns=df.columns, index=df.index)
return df_bin
def load_doc_term_matrix(version=190325, binarize=True):
dtm = pd.read_csv("../../../data/text/dtm_{}.csv.gz".format(version), compression="gzip", index_col=0)
if binarize:
dtm = doc_mean_thres(dtm)
return dtm
def load_coordinates():
atlas_labels = pd.read_csv("../../../data/brain/labels.csv")
activations = pd.read_csv("../../../data/brain/coordinates.csv", index_col=0)
activations = activations[atlas_labels["PREPROCESSED"]]
return activations
def load_raw_domains(k):
list_file = "../../lists/lists_k{:02d}.csv".format(k)
lists = pd.read_csv(list_file, index_col=None)
circuit_file = "../../circuits/circuits_k{:02d}.csv".format(k)
circuits = pd.read_csv(circuit_file, index_col=None)
return lists, circuits
def numpy2torch(data):
inputs, labels = data
inputs = Variable(torch.from_numpy(inputs.T).float())
labels = Variable(torch.from_numpy(labels.T).float())
return inputs, labels
def reset_weights(m):
if isinstance(m, nn.Linear):
m.reset_parameters()
class Net(nn.Module):
def __init__(self, n_input=0, n_output=0, n_hid=100, p_dropout=0.5):
super(Net, self).__init__()
self.fc1 = nn.Linear(n_input, n_hid)
self.bn1 = nn.BatchNorm1d(n_hid)
self.dropout1 = nn.Dropout(p=p_dropout)
self.fc2 = nn.Linear(n_hid, n_hid)
self.bn2 = nn.BatchNorm1d(n_hid)
self.dropout2 = nn.Dropout(p=p_dropout)
self.fc3 = nn.Linear(n_hid, n_hid)
self.bn3 = nn.BatchNorm1d(n_hid)
self.dropout3 = nn.Dropout(p=p_dropout)
self.fc4 = nn.Linear(n_hid, n_hid)
self.bn4 = nn.BatchNorm1d(n_hid)
self.dropout4 = nn.Dropout(p=p_dropout)
self.fc5 = nn.Linear(n_hid, n_hid)
self.bn5 = nn.BatchNorm1d(n_hid)
self.dropout5 = nn.Dropout(p=p_dropout)
self.fc6 = nn.Linear(n_hid, n_hid)
self.bn6 = nn.BatchNorm1d(n_hid)
self.dropout6 = nn.Dropout(p=p_dropout)
self.fc7 = nn.Linear(n_hid, n_hid)
self.bn7 = nn.BatchNorm1d(n_hid)
self.dropout7 = nn.Dropout(p=p_dropout)
self.fc8 = nn.Linear(n_hid, n_output)
# Xavier initialization for weights
for fc in [self.fc1, self.fc2, self.fc3, self.fc4,
self.fc5, self.fc6, self.fc7, self.fc8]:
nn.init.xavier_uniform_(fc.weight)
def forward(self, x):
x = self.dropout1(F.relu(self.bn1(self.fc1(x))))
x = self.dropout2(F.relu(self.bn2(self.fc2(x))))
x = self.dropout3(F.relu(self.bn3(self.fc3(x))))
x = self.dropout4(F.relu(self.bn4(self.fc4(x))))
x = self.dropout5(F.relu(self.bn5(self.fc5(x))))
x = self.dropout6(F.relu(self.bn6(self.fc6(x))))
x = self.dropout7(F.relu(self.bn7(self.fc7(x))))
x = torch.sigmoid(self.fc8(x))
return x
def optimize_hyperparameters(param_list, train_set, val_set, n_epochs=100):
criterion = F.binary_cross_entropy
inputs_val, labels_val = numpy2torch(val_set[0])
op_idx, op_params, op_score_val, op_state_dict, op_loss = 0, 0, 0, 0, 0
for params in param_list:
print("-" * 75)
print(" ".join(["{} {:6.5f}".format(k.upper(), v) for k, v in params.items()]))
print("-" * 75 + "\n")
# Initialize variables for this set of parameters
n_input = train_set[0][0].shape[0]
n_output = train_set[0][1].shape[0]
net = Net(n_input=n_input, n_output=n_output,
n_hid=params["n_hid"], p_dropout=params["p_dropout"])
optimizer = optim.Adam(net.parameters(),
lr=params["lr"], weight_decay=params["weight_decay"])
net.apply(reset_weights)
running_loss = []
# Loop over the dataset multiple times
for epoch in range(n_epochs):
for data in train_set:
# Get the inputs
inputs, labels = numpy2torch(data)
# Zero the parameter gradients
optimizer.zero_grad()
# Forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# Update the running loss
running_loss += [loss.item()]
if epoch % (n_epochs/5) == (n_epochs/5) - 1:
print(" Epoch {:3d}\tLoss {:6.6f}".format(epoch + 1, running_loss[-1] / 100))
# Evaluate on the validation set
with torch.no_grad():
preds_val = net.eval()(inputs_val).float()
score_val = roc_auc_score(labels_val, preds_val, average="macro")
print("\n Validation Set ROC-AUC {:6.4f}\n".format(score_val))
# Update outputs if this model is the best so far
if score_val > op_score_val:
print(" Best so far!\n")
op_score_val = score_val
op_state_dict = net.state_dict()
op_params = params
op_loss = running_loss
return op_score_val
def load_mini_batches(X, Y, split, mini_batch_size=64, seed=0, reshape_labels=False):
np.random.seed(seed)
m = len(split) # Number of training examples
mini_batches = []
# Split the data
X = X.loc[split].T.values
Y = Y.loc[split].T.values
# Shuffle (X, Y)
permutation = list(np.random.permutation(m))
shuffled_X = X[:, permutation]
shuffled_Y = Y[:, permutation]
if reshape_labels:
shuffled_Y = shuffled_Y.reshape((1,m))
# Partition (shuffled_X, shuffled_Y), except the end case
num_complete_minibatches = math.floor(m / mini_batch_size) # Mumber of mini batches of size mini_batch_size in your partitionning
for k in range(0, num_complete_minibatches):
mini_batch_X = shuffled_X[:, k * mini_batch_size : (k+1) * mini_batch_size]
mini_batch_Y = shuffled_Y[:, k * mini_batch_size : (k+1) * mini_batch_size]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
# Handle the end case (last mini-batch < mini_batch_size)
if m % mini_batch_size != 0:
mini_batch_X = shuffled_X[:, -(m % mini_batch_size):]
mini_batch_Y = shuffled_Y[:, -(m % mini_batch_size):]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
return mini_batches
def optimize_list_len(k):
# Load the data splits
splits = {}
for split in ["train", "validation"]:
splits[split] = [int(pmid.strip()) for pmid in open("../../../data/splits/{}.txt".format(split), "r").readlines()]
act_bin = load_coordinates()
dtm_bin = load_doc_term_matrix(version=190325, binarize=True)
lists, circuits = load_raw_domains(k)
# Specify the hyperparameters for the randomized grid search
param_grid = {"lr": [0.001],
"weight_decay": [0.001],
"n_hid": [100],
"p_dropout": [0.1]}
param_list = list(ParameterSampler(param_grid, n_iter=1, random_state=42))
batch_size = 1024
n_epochs = 100
list_lens = range(5, 26)
op_lists = pd.DataFrame()
for circuit in range(1, k+1):
print("-" * 100)
print("Fitting models for domain {:02d}".format(circuit))
forward_scores, reverse_scores = [], []
structures = circuits.loc[circuits["CLUSTER"] == circuit, "STRUCTURE"]
for list_len in list_lens:
print("-" * 85)
print("Fitting models for lists of length {:02d}".format(list_len))
words = lists.loc[lists["CLUSTER"] == circuit, "TOKEN"][:list_len]
# Optimize forward inference classifier
train_set_f = load_mini_batches(dtm_bin[words], act_bin[structures], splits["train"], mini_batch_size=batch_size, seed=42)
val_set_f = load_mini_batches(dtm_bin[words], act_bin[structures], splits["validation"], mini_batch_size=len(splits["validation"]), seed=42)
try:
op_val_f = optimize_hyperparameters(param_list, train_set_f, val_set_f, n_epochs=n_epochs)
except:
op_val_f = 0.0
forward_scores.append(op_val_f)
# Optimize reverse inference classifier
train_set_r = load_mini_batches(act_bin[structures], dtm_bin[words], splits["train"], mini_batch_size=batch_size, seed=42)
val_set_r = load_mini_batches(act_bin[structures], dtm_bin[words], splits["validation"], mini_batch_size=len(splits["validation"]), seed=42)
try:
op_val_r = optimize_hyperparameters(param_list, train_set_r, val_set_r, n_epochs=n_epochs)
except:
op_val_r = 0.0
reverse_scores.append(op_val_r)
scores = [(forward_scores[i] + reverse_scores[i])/2.0 for i in range(len(forward_scores))]
print("-" * 85)
print("Mean ROC-AUC scores: {}".format(scores))
op_len = list_lens[scores.index(max(scores))]
print("-" * 100)
print("\tCircuit {:02d} has {:02d} words".format(circuit, op_len))
op_df = lists.loc[lists["CLUSTER"] == circuit][:op_len]
op_df["ROC_AUC"] = max(scores)
op_lists = op_lists.append(op_df)
op_lists.to_csv("../../lists/lists_k{:02d}_oplen_nn.csv".format(k), index=None)
|
[
"pandas.DataFrame",
"torch.nn.Dropout",
"numpy.random.seed",
"pandas.read_csv",
"torch.manual_seed",
"torch.nn.init.xavier_uniform_",
"torch.nn.BatchNorm1d",
"math.floor",
"sklearn.metrics.roc_auc_score",
"sklearn.model_selection.ParameterSampler",
"torch.nn.Linear",
"numpy.random.permutation",
"torch.no_grad",
"torch.from_numpy"
] |
[((74, 92), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (88, 92), True, 'import numpy as np\n'), ((225, 246), 'torch.manual_seed', 'torch.manual_seed', (['(42)'], {}), '(42)\n', (242, 246), False, 'import torch\n'), ((450, 506), 'pandas.DataFrame', 'pd.DataFrame', (['df_bin'], {'columns': 'df.columns', 'index': 'df.index'}), '(df_bin, columns=df.columns, index=df.index)\n', (462, 506), True, 'import pandas as pd\n'), ((788, 833), 'pandas.read_csv', 'pd.read_csv', (['"""../../../data/brain/labels.csv"""'], {}), "('../../../data/brain/labels.csv')\n", (799, 833), True, 'import pandas as pd\n'), ((850, 913), 'pandas.read_csv', 'pd.read_csv', (['"""../../../data/brain/coordinates.csv"""'], {'index_col': '(0)'}), "('../../../data/brain/coordinates.csv', index_col=0)\n", (861, 913), True, 'import pandas as pd\n'), ((1086, 1124), 'pandas.read_csv', 'pd.read_csv', (['list_file'], {'index_col': 'None'}), '(list_file, index_col=None)\n', (1097, 1124), True, 'import pandas as pd\n'), ((1203, 1244), 'pandas.read_csv', 'pd.read_csv', (['circuit_file'], {'index_col': 'None'}), '(circuit_file, index_col=None)\n', (1214, 1244), True, 'import pandas as pd\n'), ((5266, 5286), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (5280, 5286), True, 'import numpy as np\n'), ((5727, 5758), 'math.floor', 'math.floor', (['(m / mini_batch_size)'], {}), '(m / mini_batch_size)\n', (5737, 5758), False, 'import os, math\n'), ((7197, 7211), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7209, 7211), True, 'import pandas as pd\n'), ((1683, 1708), 'torch.nn.Linear', 'nn.Linear', (['n_input', 'n_hid'], {}), '(n_input, n_hid)\n', (1692, 1708), True, 'import torch.nn as nn\n'), ((1724, 1745), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['n_hid'], {}), '(n_hid)\n', (1738, 1745), True, 'import torch.nn as nn\n'), ((1766, 1789), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'p_dropout'}), '(p=p_dropout)\n', (1776, 1789), True, 'import torch.nn as nn\n'), ((1805, 1828), 'torch.nn.Linear', 'nn.Linear', (['n_hid', 'n_hid'], {}), '(n_hid, n_hid)\n', (1814, 1828), True, 'import torch.nn as nn\n'), ((1844, 1865), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['n_hid'], {}), '(n_hid)\n', (1858, 1865), True, 'import torch.nn as nn\n'), ((1886, 1909), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'p_dropout'}), '(p=p_dropout)\n', (1896, 1909), True, 'import torch.nn as nn\n'), ((1925, 1948), 'torch.nn.Linear', 'nn.Linear', (['n_hid', 'n_hid'], {}), '(n_hid, n_hid)\n', (1934, 1948), True, 'import torch.nn as nn\n'), ((1964, 1985), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['n_hid'], {}), '(n_hid)\n', (1978, 1985), True, 'import torch.nn as nn\n'), ((2006, 2029), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'p_dropout'}), '(p=p_dropout)\n', (2016, 2029), True, 'import torch.nn as nn\n'), ((2045, 2068), 'torch.nn.Linear', 'nn.Linear', (['n_hid', 'n_hid'], {}), '(n_hid, n_hid)\n', (2054, 2068), True, 'import torch.nn as nn\n'), ((2084, 2105), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['n_hid'], {}), '(n_hid)\n', (2098, 2105), True, 'import torch.nn as nn\n'), ((2126, 2149), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'p_dropout'}), '(p=p_dropout)\n', (2136, 2149), True, 'import torch.nn as nn\n'), ((2165, 2188), 'torch.nn.Linear', 'nn.Linear', (['n_hid', 'n_hid'], {}), '(n_hid, n_hid)\n', (2174, 2188), True, 'import torch.nn as nn\n'), ((2204, 2225), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['n_hid'], {}), '(n_hid)\n', (2218, 2225), True, 'import torch.nn as nn\n'), ((2246, 2269), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'p_dropout'}), '(p=p_dropout)\n', (2256, 2269), True, 'import torch.nn as nn\n'), ((2285, 2308), 'torch.nn.Linear', 'nn.Linear', (['n_hid', 'n_hid'], {}), '(n_hid, n_hid)\n', (2294, 2308), True, 'import torch.nn as nn\n'), ((2324, 2345), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['n_hid'], {}), '(n_hid)\n', (2338, 2345), True, 'import torch.nn as nn\n'), ((2366, 2389), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'p_dropout'}), '(p=p_dropout)\n', (2376, 2389), True, 'import torch.nn as nn\n'), ((2405, 2428), 'torch.nn.Linear', 'nn.Linear', (['n_hid', 'n_hid'], {}), '(n_hid, n_hid)\n', (2414, 2428), True, 'import torch.nn as nn\n'), ((2444, 2465), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['n_hid'], {}), '(n_hid)\n', (2458, 2465), True, 'import torch.nn as nn\n'), ((2486, 2509), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'p_dropout'}), '(p=p_dropout)\n', (2496, 2509), True, 'import torch.nn as nn\n'), ((2525, 2551), 'torch.nn.Linear', 'nn.Linear', (['n_hid', 'n_output'], {}), '(n_hid, n_output)\n', (2534, 2551), True, 'import torch.nn as nn\n'), ((4778, 4831), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['labels_val', 'preds_val'], {'average': '"""macro"""'}), "(labels_val, preds_val, average='macro')\n", (4791, 4831), False, 'from sklearn.metrics import roc_auc_score\n'), ((5481, 5505), 'numpy.random.permutation', 'np.random.permutation', (['m'], {}), '(m)\n', (5502, 5505), True, 'import numpy as np\n'), ((7054, 7109), 'sklearn.model_selection.ParameterSampler', 'ParameterSampler', (['param_grid'], {'n_iter': '(1)', 'random_state': '(42)'}), '(param_grid, n_iter=1, random_state=42)\n', (7070, 7109), False, 'from sklearn.model_selection import ParameterSampler\n'), ((2710, 2744), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['fc.weight'], {}), '(fc.weight)\n', (2733, 2744), True, 'import torch.nn as nn\n'), ((4696, 4711), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4709, 4711), False, 'import torch\n'), ((1339, 1365), 'torch.from_numpy', 'torch.from_numpy', (['inputs.T'], {}), '(inputs.T)\n', (1355, 1365), False, 'import torch\n'), ((1395, 1421), 'torch.from_numpy', 'torch.from_numpy', (['labels.T'], {}), '(labels.T)\n', (1411, 1421), False, 'import torch\n')]
|
import explanes as el
import numpy as np
import pandas as pd
np.random.seed(0)
experiment = el.experiment.Experiment()
experiment.project.name = 'example'
experiment.path.output = '/tmp/'+experiment.project.name+'/'
experiment.factor.f1 = [1, 2]
experiment.factor.f2 = [1, 2, 3]
experiment.metric.m1 = ['mean', 'std']
experiment.metric.m2 = ['min', 'argmin']
def process(setting, experiment):
metric1 = setting.f1+setting.f2+np.random.randn(100)
metric2 = setting.f1*setting.f2*np.random.randn(100)
np.save(experiment.path.output+setting.id()+'_m1.npy', metric1)
np.save(experiment.path.output+setting.id()+'_m2.npy', metric2)
experiment.setPath()
experiment.do([], process, progress=False)
(settingDescription, columnHeader, constantSettingDescription, nbColumnFactor) = experiment.metric.reduce(experiment.factor.mask([1]), experiment.path.output, verbose=True)
df = pd.DataFrame(settingDescription, columns=columnHeader)
df[columnHeader[nbColumnFactor:]] = df[columnHeader[nbColumnFactor:]].round(decimals=2)
print(constantSettingDescription)
print(df)
|
[
"explanes.experiment.Experiment",
"numpy.random.seed",
"pandas.DataFrame",
"numpy.random.randn"
] |
[((62, 79), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (76, 79), True, 'import numpy as np\n'), ((94, 120), 'explanes.experiment.Experiment', 'el.experiment.Experiment', ([], {}), '()\n', (118, 120), True, 'import explanes as el\n'), ((883, 937), 'pandas.DataFrame', 'pd.DataFrame', (['settingDescription'], {'columns': 'columnHeader'}), '(settingDescription, columns=columnHeader)\n', (895, 937), True, 'import pandas as pd\n'), ((430, 450), 'numpy.random.randn', 'np.random.randn', (['(100)'], {}), '(100)\n', (445, 450), True, 'import numpy as np\n'), ((485, 505), 'numpy.random.randn', 'np.random.randn', (['(100)'], {}), '(100)\n', (500, 505), True, 'import numpy as np\n')]
|
"""
Generate a golden NPZ file from a dicom ZIP archive.
"""
import argparse
import numpy as np
from dicom_numpy.zip_archive import combined_series_from_zip
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', help='Output golden NPZ file', required=False)
parser.add_argument('input', help="Input DICOM zip archive")
return parser.parse_args()
def generate_golden_values(input_zip, output_path='golden_values'):
"""
Generate a golden NPZ file for a given DICOM zip archive.
"""
voxels, ijk_to_xyz = combined_series_from_zip(input_zip)
np.savez_compressed(output_path, voxels=voxels, ijk_to_xyz=ijk_to_xyz)
if __name__ == '__main__':
args = parse_args()
if args.output:
generate_golden_values(args.input, args.output)
else:
generate_golden_values(args.input)
|
[
"dicom_numpy.zip_archive.combined_series_from_zip",
"numpy.savez_compressed",
"argparse.ArgumentParser"
] |
[((192, 217), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (215, 217), False, 'import argparse\n'), ((576, 611), 'dicom_numpy.zip_archive.combined_series_from_zip', 'combined_series_from_zip', (['input_zip'], {}), '(input_zip)\n', (600, 611), False, 'from dicom_numpy.zip_archive import combined_series_from_zip\n'), ((616, 686), 'numpy.savez_compressed', 'np.savez_compressed', (['output_path'], {'voxels': 'voxels', 'ijk_to_xyz': 'ijk_to_xyz'}), '(output_path, voxels=voxels, ijk_to_xyz=ijk_to_xyz)\n', (635, 686), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 28 00:02:08 2017
@author: kht
"""
import tensorflow as tf
import translate as tl
import numpy as np
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape = shape)
return tf.Variable(initial)
einputs,dinputs,res_logits,all_attens=tl.self_decode()
einputs_t=[]
dinputs_t=[]
res_logits_t=[]
num_exp=len(res_logits)
for i in range(100):
einputs_t.append(einputs[num_exp-i-1])
dinputs_t.append(dinputs[num_exp-i-1])
res_logits_t.append(res_logits[num_exp-i-1])
batch_size=32
maxlen=13
sess = tf.InteractiveSession()
w_fc2 = weight_variable([128, 20])
b_fc2 = bias_variable([20])
x=tf.placeholder(tf.float32,[None,128])
y_=tf.placeholder(tf.float32,[None,20])
y_conv = tf.nn.softmax(tf.matmul(x, w_fc2) + b_fc2)
# train and evaluate the model
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
res=tf.argmax(y_conv, 1)
resreal=tf.argmax(y_, 1)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
init=tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
saver = tf.train.Saver()
saver.restore(sess, "train/NumAdd.ckpt")
for i in range(len(res_logits_t)):
din=dinputs_t[i]
dlogit=res_logits_t[i]
'''
for j in range(batch_size):
batch_x=[]
batch_y=np.zeros([13,20],dtype=np.float32)
for k in range(maxlen):
batch_y[k][din[k][j]]=1
dx=dlogit[k][j]
batch_x.append(dx)
print(sess.run(correct_prediction,feed_dict={x: batch_x, y_: batch_y}))
print('-----------------------------------------------------------------------')
print("**************************************************************************************")
'''
for j in range(batch_size):
batch_x=[]
batch_y=np.zeros([13,20],dtype=np.float32)
for k in range(maxlen):
batch_y[k][din[k][j]]=1
dx=dlogit[k][j]
batch_x.append(dx)
print(sess.run(res,feed_dict={x: batch_x, y_: batch_y}))
print(sess.run(resreal,feed_dict={x: batch_x, y_: batch_y}))
print('-----------------------------------------------------------------------')
|
[
"tensorflow.train.Saver",
"tensorflow.argmax",
"tensorflow.Session",
"numpy.zeros",
"tensorflow.constant",
"tensorflow.placeholder",
"tensorflow.cast",
"tensorflow.Variable",
"tensorflow.matmul",
"translate.self_decode",
"tensorflow.initialize_all_variables",
"tensorflow.log",
"tensorflow.InteractiveSession",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.truncated_normal"
] |
[((410, 426), 'translate.self_decode', 'tl.self_decode', ([], {}), '()\n', (424, 426), True, 'import translate as tl\n'), ((685, 708), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (706, 708), True, 'import tensorflow as tf\n'), ((775, 814), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 128]'], {}), '(tf.float32, [None, 128])\n', (789, 814), True, 'import tensorflow as tf\n'), ((816, 854), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 20]'], {}), '(tf.float32, [None, 20])\n', (830, 854), True, 'import tensorflow as tf\n'), ((1140, 1160), 'tensorflow.argmax', 'tf.argmax', (['y_conv', '(1)'], {}), '(y_conv, 1)\n', (1149, 1160), True, 'import tensorflow as tf\n'), ((1169, 1185), 'tensorflow.argmax', 'tf.argmax', (['y_', '(1)'], {}), '(y_, 1)\n', (1178, 1185), True, 'import tensorflow as tf\n'), ((1256, 1285), 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), '()\n', (1283, 1285), True, 'import tensorflow as tf\n'), ((191, 229), 'tensorflow.truncated_normal', 'tf.truncated_normal', (['shape'], {'stddev': '(0.1)'}), '(shape, stddev=0.1)\n', (210, 229), True, 'import tensorflow as tf\n'), ((241, 261), 'tensorflow.Variable', 'tf.Variable', (['initial'], {}), '(initial)\n', (252, 261), True, 'import tensorflow as tf\n'), ((303, 332), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {'shape': 'shape'}), '(0.1, shape=shape)\n', (314, 332), True, 'import tensorflow as tf\n'), ((346, 366), 'tensorflow.Variable', 'tf.Variable', (['initial'], {}), '(initial)\n', (357, 366), True, 'import tensorflow as tf\n'), ((1096, 1116), 'tensorflow.argmax', 'tf.argmax', (['y_conv', '(1)'], {}), '(y_conv, 1)\n', (1105, 1116), True, 'import tensorflow as tf\n'), ((1118, 1134), 'tensorflow.argmax', 'tf.argmax', (['y_', '(1)'], {}), '(y_, 1)\n', (1127, 1134), True, 'import tensorflow as tf\n'), ((1212, 1248), 'tensorflow.cast', 'tf.cast', (['correct_prediction', '"""float"""'], {}), "(correct_prediction, 'float')\n", (1219, 1248), True, 'import tensorflow as tf\n'), ((1292, 1304), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1302, 1304), True, 'import tensorflow as tf\n'), ((1345, 1361), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1359, 1361), True, 'import tensorflow as tf\n'), ((877, 896), 'tensorflow.matmul', 'tf.matmul', (['x', 'w_fc2'], {}), '(x, w_fc2)\n', (886, 896), True, 'import tensorflow as tf\n'), ((1001, 1040), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['(0.01)'], {}), '(0.01)\n', (1034, 1040), True, 'import tensorflow as tf\n'), ((972, 986), 'tensorflow.log', 'tf.log', (['y_conv'], {}), '(y_conv)\n', (978, 986), True, 'import tensorflow as tf\n'), ((2152, 2188), 'numpy.zeros', 'np.zeros', (['[13, 20]'], {'dtype': 'np.float32'}), '([13, 20], dtype=np.float32)\n', (2160, 2188), True, 'import numpy as np\n')]
|
import torch
from torch import nn
import os.path
import torchvision.transforms as transforms
from EnlightenGAN.data.base_dataset import BaseDataset, get_transform
from EnlightenGAN.data.image_folder import make_dataset
import random
from PIL import Image
import PIL
from pdb import set_trace as st
import numpy as np
from skimage import color, feature
from skimage.filters import gaussian
def pad_tensor(input):
height_org, width_org = input.shape[2], input.shape[3]
divide = 16
if width_org % divide != 0 or height_org % divide != 0:
width_res = width_org % divide
height_res = height_org % divide
if width_res != 0:
width_div = divide - width_res
pad_left = int(width_div / 2)
pad_right = int(width_div - pad_left)
else:
pad_left = 0
pad_right = 0
if height_res != 0:
height_div = divide - height_res
pad_top = int(height_div / 2)
pad_bottom = int(height_div - pad_top)
else:
pad_top = 0
pad_bottom = 0
padding = nn.ReflectionPad2d((pad_left, pad_right, pad_top, pad_bottom))
input = padding(input).data
else:
pad_left = 0
pad_right = 0
pad_top = 0
pad_bottom = 0
height, width = input.shape[2], input.shape[3]
assert width % divide == 0, 'width cant divided by stride'
assert height % divide == 0, 'height cant divided by stride'
return input, pad_left, pad_right, pad_top, pad_bottom
def pad_tensor_back(input, pad_left, pad_right, pad_top, pad_bottom):
height, width = input.shape[2], input.shape[3]
return input[:,:, pad_top: height - pad_bottom, pad_left: width - pad_right]
class UnalignedDataset(BaseDataset):
def _reinit_A_paths(self):
self.A_paths = self.pos_names# + np.random.choice(self.neg_names_all, int(948/(10/1)), replace=False).tolist()
random.shuffle(self.A_paths)
self.B_paths = list(self.A_paths)
self.A_size = len(self.A_paths)
self.B_size = len(self.B_paths)
def initialize(self, opt):
self.opt = opt
self.root = opt.dataroot
##############################
# self.dir_A = os.path.join(opt.dataroot)#, opt.phase + 'A')
# self.dir_B = os.path.join(opt.dataroot)#, opt.phase + 'B')
if not 'images' in self.opt.name:
self.dir_A = os.path.join("/ssd1/chenwy/bdd100k/seg_luminance/0_100/", opt.phase)
self.dir_B = os.path.join("/ssd1/chenwy/bdd100k/seg_luminance/100_255/", opt.phase)
# self.dir_A = os.path.join("/ssd1/chenwy/bdd100k/seg_luminance/0_75/", opt.phase)
# self.dir_B = os.path.join("/ssd1/chenwy/bdd100k/seg_luminance/100_105/", opt.phase)
else:
self.dir_A = os.path.join("/ssd1/chenwy/bdd100k/images_luminance/100k/0_100/", opt.phase)
self.dir_B = os.path.join("/ssd1/chenwy/bdd100k/images_luminance/100k/100_255/", opt.phase)
# self.dir_A = os.path.join("/ssd1/chenwy/bdd100k/images_luminance/100k/0_75/", opt.phase)
# self.dir_B = os.path.join("/ssd1/chenwy/bdd100k/images_luminance/100k/100_105/", opt.phase)
##############################
self.A_paths = make_dataset(self.dir_A)
self.B_paths = make_dataset(self.dir_B)
self.A_paths = sorted(self.A_paths)
self.B_paths = sorted(self.B_paths)
self.A_size = len(self.A_paths)
self.B_size = len(self.B_paths)
self.transform = get_transform(opt)
##### load image2reward to resample dataset ############################
# image2reward = np.load("/home/chenwy/DynamicLightEnlighten/image2reward.npy").item()
# self.pos = []; self.pos_names = []; self.neg_names_all = []
# for k, v in image2reward.items():
# if v > 0:
# self.pos.append(v)
# self.pos_names.append(k)
# elif v < 0:
# self.neg_names_all.append(k)
# self.pos_names = [k for v,k in sorted(zip(self.pos, self.pos_names), reverse=True)]
# self._reinit_A_paths()
#################################
self.low_range = range(55, 70)
self.high_range = range(110, 125)
self.N_TRY = 20
def __getitem__(self, index_A):
A_path = self.A_paths[index_A % self.A_size]
index_B = random.randint(0, self.B_size - 1)
B_path = self.B_paths[index_B % self.B_size]
A_image = Image.open(A_path).convert('RGB')
B_image = Image.open(B_path).convert('RGB')
# A_size = A_img.size
# B_size = B_img.size
# A_size = A_size = (A_size[0]//16*16, A_size[1]//16*16)
# B_size = B_size = (B_size[0]//16*16, B_size[1]//16*16)
# A_img = A_img.resize(A_size, Image.BICUBIC)
# B_img = B_img.resize(B_size, Image.BICUBIC)
# A_gray = A_img.convert('LA')
# A_gray = 255.0-A_gray
w, h = A_image.size
# without luminance selection #####################
# x1 = random.randint(0, w - self.opt.fineSize)
# y1 = random.randint(0, h - self.opt.fineSize)
# A_img = A_image.crop((x1, y1, x1+self.opt.fineSize, y1+self.opt.fineSize))
# B_img = B_image.crop((x1, y1, x1+self.opt.fineSize, y1+self.opt.fineSize))
# A_npy = np.array(A_img)
# B_npy = np.array(B_img)
# r,g,b = A_npy[:, :, 0], A_npy[:, :, 1], A_npy[:, :, 2]
# value_A = (0.299*r+0.587*g+0.114*b) / 255.
# value_A = np.sort(value_A.flatten())
# length = value_A.shape[0]
# value_A = value_A[int(np.round(length * 0.1)) : int(np.round(length * 0.9))].mean()
# if not 'images' in self.opt.name:
# # mask = Image.open(os.path.join("/ssd1/chenwy/bdd100k/seg/labels/", "train", os.path.splitext(A_path.split("/")[-1])[0] + '_train_id.png'))
# mask = Image.open(os.path.join("/ssd1/chenwy/bdd100k/seg/labels/", self.opt.phase, os.path.splitext(A_path.split("/")[-1])[0] + '_train_id.png'))
# mask = np.array(mask.crop((x1, y1, x1+self.opt.fineSize, y1+self.opt.fineSize))).astype('int32') # cropped mask for light_enhance_AB/seg
# mask = self._mask_transform(mask)
# else:
# mask = torch.zeros(1)
###################################################
# patch luminance & mask class diversity selection ###########################
n_try = 0
while n_try < self.N_TRY:
x1 = random.randint(0, w - self.opt.fineSize)
y1 = random.randint(0, h - self.opt.fineSize)
A_img = A_image.crop((x1, y1, x1+self.opt.fineSize, y1+self.opt.fineSize))
B_img = B_image.crop((x1, y1, x1+self.opt.fineSize, y1+self.opt.fineSize))
A_npy = np.array(A_img)
B_npy = np.array(B_img)
r,g,b = A_npy[:, :, 0], A_npy[:, :, 1], A_npy[:, :, 2]
value_A = (0.299*r+0.587*g+0.114*b) / 255.
value_A = np.sort(value_A.flatten())
length = value_A.shape[0]
value_A = value_A[int(np.round(length * 0.1)) : int(np.round(length * 0.9))].mean()
if int(np.round(value_A*255)) not in self.low_range: n_try += 1; continue
r,g,b = B_npy[:, :, 0], B_npy[:, :, 1], B_npy[:, :, 2]
value_B = (0.299*r+0.587*g+0.114*b) / 255.
value_B = np.sort(value_B.flatten())
length = value_B.shape[0]
value_B = value_B[int(np.round(length * 0.1)) : int(np.round(length * 0.9))].mean()
if int(np.round(value_B*255)) not in self.high_range: n_try += 1; continue
if not 'images' in self.opt.name:
# mask = Image.open(os.path.join("/ssd1/chenwy/bdd100k/seg/labels/", "train", os.path.splitext(A_path.split("/")[-1])[0] + '_train_id.png'))
mask = Image.open(os.path.join("/ssd1/chenwy/bdd100k/seg/labels/", self.opt.phase, os.path.splitext(A_path.split("/")[-1])[0] + '_train_id.png'))
mask = np.array(mask.crop((x1, y1, x1+self.opt.fineSize, y1+self.opt.fineSize))).astype('int32') # cropped mask for light_enhance_AB/seg
unique, counts = np.unique(mask, return_counts=True)
if len(unique) < 2 or (counts / counts.sum()).max() > 0.7: n_try += 1; continue
mask = self._mask_transform(mask)
else:
mask = torch.zeros(1)
break
if n_try == self.N_TRY:
# if int(np.round(value_A)) not in self.low_range:
# self.A_paths.pop(index_A % self.A_size)
# self.A_size -= 1
# if int(np.round(value_B)) not in self.high_range:
# self.B_paths.pop(index_B % self.B_size)
# self.B_size -= 1
index_A = random.randint(0, self.__len__())
return self.__getitem__(index_A)
##########################################################################
gray_mask = torch.ones(1, self.opt.fineSize, self.opt.fineSize) * value_A
A_img_border = A_image.crop((x1-self.opt.fineSize//2, y1-self.opt.fineSize//2, x1+2*self.opt.fineSize, y1+2*self.opt.fineSize))
A_Lab = torch.Tensor(color.rgb2lab(A_npy) / 100).permute([2, 0, 1])
A_npy = gaussian(A_npy, sigma=2, multichannel=True)
r,g,b = A_npy[:, :, 0], A_npy[:, :, 1], A_npy[:, :, 2]
A_npy = 0.299*r+0.587*g+0.114*b
edges_A = torch.unsqueeze(torch.from_numpy(feature.canny(A_npy, sigma=2).astype("float32")), 0)
A_img = self.transform(A_img)
A_img_border = self.transform(A_img_border)
B_img = self.transform(B_img)
if self.opt.resize_or_crop == 'no':
r,g,b = A_img[0]+1, A_img[1]+1, A_img[2]+1
A_gray = 1. - (0.299*r+0.587*g+0.114*b)/2.
A_gray = torch.unsqueeze(A_gray, 0)
input_img = A_img
# A_gray = (1./A_gray)/255.
r,g,b = A_img_border[0]+1, A_img_border[1]+1, A_img_border[2]+1
A_gray_border = 1. - (0.299*r+0.587*g+0.114*b)/2.
A_gray_border = torch.unsqueeze(A_gray_border, 0)
else:
w = A_img.size(2)
h = A_img.size(1)
# A_gray = (1./A_gray)/255.
if (not self.opt.no_flip) and random.random() < 0.5:
idx = [i for i in range(A_img.size(2) - 1, -1, -1)]
idx = torch.LongTensor(idx)
A_img = A_img.index_select(2, idx)
B_img = B_img.index_select(2, idx)
if (not self.opt.no_flip) and random.random() < 0.5:
idx = [i for i in range(A_img.size(1) - 1, -1, -1)]
idx = torch.LongTensor(idx)
A_img = A_img.index_select(1, idx)
B_img = B_img.index_select(1, idx)
if self.opt.vary == 1 and (not self.opt.no_flip) and random.random() < 0.5:
times = random.randint(self.opt.low_times,self.opt.high_times)/100.
input_img = (A_img+1)/2./times
input_img = input_img*2-1
else:
input_img = A_img
if self.opt.lighten:
B_img = (B_img + 1)/2.
B_img = (B_img - torch.min(B_img))/(torch.max(B_img) - torch.min(B_img))
B_img = B_img*2. -1
r,g,b = input_img[0]+1, input_img[1]+1, input_img[2]+1
A_gray = 1. - (0.299*r+0.587*g+0.114*b)/2.
A_gray = torch.unsqueeze(A_gray, 0)
return {'A': A_img, 'B': B_img, 'A_gray': A_gray, 'input_img': input_img,
'A_paths': A_path, 'B_paths': B_path, 'mask': mask,
'A_border': A_img_border, 'A_gray_border': A_gray_border,
'A_Lab': A_Lab, 'gray_mask': gray_mask, 'edges_A': edges_A
}
def __len__(self):
return max(self.A_size, self.B_size)
def name(self):
return 'UnalignedDataset'
def _mask_transform(self, mask):
target = np.array(mask).astype('int32')
target[target == 255] = -1
return torch.from_numpy(target).long()
|
[
"random.shuffle",
"EnlightenGAN.data.image_folder.make_dataset",
"numpy.round",
"numpy.unique",
"skimage.color.rgb2lab",
"torch.ones",
"random.randint",
"torch.nn.ReflectionPad2d",
"torch.zeros",
"random.random",
"torch.max",
"torch.unsqueeze",
"skimage.feature.canny",
"torch.min",
"EnlightenGAN.data.base_dataset.get_transform",
"torch.from_numpy",
"torch.LongTensor",
"PIL.Image.open",
"numpy.array",
"skimage.filters.gaussian"
] |
[((1959, 1987), 'random.shuffle', 'random.shuffle', (['self.A_paths'], {}), '(self.A_paths)\n', (1973, 1987), False, 'import random\n'), ((3292, 3316), 'EnlightenGAN.data.image_folder.make_dataset', 'make_dataset', (['self.dir_A'], {}), '(self.dir_A)\n', (3304, 3316), False, 'from EnlightenGAN.data.image_folder import make_dataset\n'), ((3340, 3364), 'EnlightenGAN.data.image_folder.make_dataset', 'make_dataset', (['self.dir_B'], {}), '(self.dir_B)\n', (3352, 3364), False, 'from EnlightenGAN.data.image_folder import make_dataset\n'), ((3568, 3586), 'EnlightenGAN.data.base_dataset.get_transform', 'get_transform', (['opt'], {}), '(opt)\n', (3581, 3586), False, 'from EnlightenGAN.data.base_dataset import BaseDataset, get_transform\n'), ((4438, 4472), 'random.randint', 'random.randint', (['(0)', '(self.B_size - 1)'], {}), '(0, self.B_size - 1)\n', (4452, 4472), False, 'import random\n'), ((9362, 9405), 'skimage.filters.gaussian', 'gaussian', (['A_npy'], {'sigma': '(2)', 'multichannel': '(True)'}), '(A_npy, sigma=2, multichannel=True)\n', (9370, 9405), False, 'from skimage.filters import gaussian\n'), ((1120, 1182), 'torch.nn.ReflectionPad2d', 'nn.ReflectionPad2d', (['(pad_left, pad_right, pad_top, pad_bottom)'], {}), '((pad_left, pad_right, pad_top, pad_bottom))\n', (1138, 1182), False, 'from torch import nn\n'), ((6562, 6602), 'random.randint', 'random.randint', (['(0)', '(w - self.opt.fineSize)'], {}), '(0, w - self.opt.fineSize)\n', (6576, 6602), False, 'import random\n'), ((6620, 6660), 'random.randint', 'random.randint', (['(0)', '(h - self.opt.fineSize)'], {}), '(0, h - self.opt.fineSize)\n', (6634, 6660), False, 'import random\n'), ((6855, 6870), 'numpy.array', 'np.array', (['A_img'], {}), '(A_img)\n', (6863, 6870), True, 'import numpy as np\n'), ((6891, 6906), 'numpy.array', 'np.array', (['B_img'], {}), '(B_img)\n', (6899, 6906), True, 'import numpy as np\n'), ((9072, 9123), 'torch.ones', 'torch.ones', (['(1)', 'self.opt.fineSize', 'self.opt.fineSize'], {}), '(1, self.opt.fineSize, self.opt.fineSize)\n', (9082, 9123), False, 'import torch\n'), ((9918, 9944), 'torch.unsqueeze', 'torch.unsqueeze', (['A_gray', '(0)'], {}), '(A_gray, 0)\n', (9933, 9944), False, 'import torch\n'), ((10182, 10215), 'torch.unsqueeze', 'torch.unsqueeze', (['A_gray_border', '(0)'], {}), '(A_gray_border, 0)\n', (10197, 10215), False, 'import torch\n'), ((11554, 11580), 'torch.unsqueeze', 'torch.unsqueeze', (['A_gray', '(0)'], {}), '(A_gray, 0)\n', (11569, 11580), False, 'import torch\n'), ((4545, 4563), 'PIL.Image.open', 'Image.open', (['A_path'], {}), '(A_path)\n', (4555, 4563), False, 'from PIL import Image\n'), ((4597, 4615), 'PIL.Image.open', 'Image.open', (['B_path'], {}), '(B_path)\n', (4607, 4615), False, 'from PIL import Image\n'), ((8244, 8279), 'numpy.unique', 'np.unique', (['mask'], {'return_counts': '(True)'}), '(mask, return_counts=True)\n', (8253, 8279), True, 'import numpy as np\n'), ((8467, 8481), 'torch.zeros', 'torch.zeros', (['(1)'], {}), '(1)\n', (8478, 8481), False, 'import torch\n'), ((10498, 10519), 'torch.LongTensor', 'torch.LongTensor', (['idx'], {}), '(idx)\n', (10514, 10519), False, 'import torch\n'), ((10777, 10798), 'torch.LongTensor', 'torch.LongTensor', (['idx'], {}), '(idx)\n', (10793, 10798), False, 'import torch\n'), ((12077, 12091), 'numpy.array', 'np.array', (['mask'], {}), '(mask)\n', (12085, 12091), True, 'import numpy as np\n'), ((12158, 12182), 'torch.from_numpy', 'torch.from_numpy', (['target'], {}), '(target)\n', (12174, 12182), False, 'import torch\n'), ((7232, 7255), 'numpy.round', 'np.round', (['(value_A * 255)'], {}), '(value_A * 255)\n', (7240, 7255), True, 'import numpy as np\n'), ((7624, 7647), 'numpy.round', 'np.round', (['(value_B * 255)'], {}), '(value_B * 255)\n', (7632, 7647), True, 'import numpy as np\n'), ((10385, 10400), 'random.random', 'random.random', ([], {}), '()\n', (10398, 10400), False, 'import random\n'), ((10664, 10679), 'random.random', 'random.random', ([], {}), '()\n', (10677, 10679), False, 'import random\n'), ((10966, 10981), 'random.random', 'random.random', ([], {}), '()\n', (10979, 10981), False, 'import random\n'), ((11013, 11068), 'random.randint', 'random.randint', (['self.opt.low_times', 'self.opt.high_times'], {}), '(self.opt.low_times, self.opt.high_times)\n', (11027, 11068), False, 'import random\n'), ((9299, 9319), 'skimage.color.rgb2lab', 'color.rgb2lab', (['A_npy'], {}), '(A_npy)\n', (9312, 9319), False, 'from skimage import color, feature\n'), ((9560, 9589), 'skimage.feature.canny', 'feature.canny', (['A_npy'], {'sigma': '(2)'}), '(A_npy, sigma=2)\n', (9573, 9589), False, 'from skimage import color, feature\n'), ((11319, 11335), 'torch.min', 'torch.min', (['B_img'], {}), '(B_img)\n', (11328, 11335), False, 'import torch\n'), ((11338, 11354), 'torch.max', 'torch.max', (['B_img'], {}), '(B_img)\n', (11347, 11354), False, 'import torch\n'), ((11357, 11373), 'torch.min', 'torch.min', (['B_img'], {}), '(B_img)\n', (11366, 11373), False, 'import torch\n'), ((7151, 7173), 'numpy.round', 'np.round', (['(length * 0.1)'], {}), '(length * 0.1)\n', (7159, 7173), True, 'import numpy as np\n'), ((7181, 7203), 'numpy.round', 'np.round', (['(length * 0.9)'], {}), '(length * 0.9)\n', (7189, 7203), True, 'import numpy as np\n'), ((7543, 7565), 'numpy.round', 'np.round', (['(length * 0.1)'], {}), '(length * 0.1)\n', (7551, 7565), True, 'import numpy as np\n'), ((7573, 7595), 'numpy.round', 'np.round', (['(length * 0.9)'], {}), '(length * 0.9)\n', (7581, 7595), True, 'import numpy as np\n')]
|
from datetime import datetime, date
import math
import numpy as np
import time
import sys
import requests
import re
from ortools.linear_solver import pywraplp
# if len(sys.argv) == 1:
# symbols = ['UPRO', 'TMF']
# else:
# symbols = sys.argv[1].split(',')
# for i in range(len(symbols)):
# symbols[i] = symbols[i].strip().upper()
symbols = ['TMF', 'UPRO']
num_trading_days_per_year = 252
window_size = 20
date_format = "%Y-%m-%d"
end_timestamp = int(time.time())
start_timestamp = int(end_timestamp - (1.4 * (window_size + 1) + 4) * 86400)
def get_volatility_and_performance(symbol,cookie,crumb):
download_url = "https://query1.finance.yahoo.com/v7/finance/download/{}?period1={}&period2={}&interval=1d&events=history".format(symbol, start_timestamp, end_timestamp)
lines = requests.get(
download_url,
headers={
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2866.71 Safari/537.36'
}).text.strip().split('\n')
assert lines[0].split(',')[0] == 'Date'
assert lines[0].split(',')[4] == 'Close'
prices = []
for line in lines[1:]:
prices.append(float(line.split(',')[4]))
prices.reverse()
volatilities_in_window = []
for i in range(window_size):
volatilities_in_window.append(math.log(prices[i] / prices[i+1]))
most_recent_date = datetime.strptime(lines[-1].split(',')[0], date_format).date()
assert (date.today() - most_recent_date).days <= 4, "today is {}, most recent trading day is {}".format(date.today(), most_recent_date)
return np.std(volatilities_in_window, ddof = 1) * np.sqrt(num_trading_days_per_year), prices[0] / prices[window_size] - 1.0, prices[0]
def get_cookie():
url = 'https://finance.yahoo.com/quote/VOO/history?p=VOO'
r = requests.get(url)
txt = r.text
cookie = r.cookies['B']
pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^"]+)"\}')
for line in txt.splitlines():
m = pattern.match(line)
if m is not None:
crumb = m.groupdict()['crumb']
return cookie,crumb
def get_data():
#cookie,crumb=get_cookie()
cookie='9mev4idf68vgk&b=3&s=g9'
crumb='Xpr8Z7BQn4W'
volatilities = []
performances = []
current_prices = []
sum_inverse_volatility = 0.0
for symbol in symbols:
volatility, performance, current_price = get_volatility_and_performance(symbol,cookie,crumb)
sum_inverse_volatility += 1 / volatility
volatilities.append(volatility)
performances.append(performance)
current_prices.append(current_price)
alpha=1/(np.array(volatilities) * sum_inverse_volatility)
print ("Portfolio: {}, as of {} (window size is {} days)".format(str(symbols), date.today().strftime('%Y-%m-%d'), window_size))
for i in range(len(symbols)):
print ('{} allocation ratio: {:.2f}% (anualized volatility: {:.2f}%, performance: {:.2f}%)'.format(symbols[i], 100*(alpha[i]), float(volatilities[i] * 100), float(performances[i] * 100)))
return alpha,current_prices
def create_model(epsilon=0.01):
alpha[0]/alpha[1]
data={}
data['constraint_coeffs']=[
[current_prices[0],-(epsilon+alpha[0]/alpha[1])*current_prices[1],current_prices[0],-(epsilon+alpha[0]/alpha[1])*current_prices[1]],
[current_prices[0],-(alpha[0]/alpha[1]-epsilon)*current_prices[1],current_prices[0],-(alpha[0]/alpha[1]-epsilon)*current_prices[1]],
[current_prices[0],current_prices[1],current_prices[0],current_prices[1]],
[current_prices[0],current_prices[1],0,0],
[0,0,current_prices[0],current_prices[1]],
[1,0,0,0],
[0,1,0,0],
[1,1,1,1]
]
data['lb']=[-np.inf, 0,0,0,0,N_Tax_T,N_Tax_U,1]
data['ub']=[0, np.inf,S,S_Tax,S_IRA,np.inf,np.inf,np.inf]
data['obj_coeffs']=[current_prices[0],current_prices[1],current_prices[0],current_prices[1]]
data['xub']=[np.floor(S_Tax/current_prices[0]),np.floor(S_Tax/current_prices[1]),np.floor(S_IRA/current_prices[0]),np.floor(S_IRA/current_prices[1])]
data['num_vars']=len(data['obj_coeffs'])
data['num_constraints']=len(data['constraint_coeffs'])
return data
def findsol(epsilon=0.01):
data = create_model(epsilon)
solver = pywraplp.Solver.CreateSolver('CBC')
x={}
for j in range(data['num_vars']):
x[j] = solver.IntVar(0, data['xub'][j], 'x[%i]' % j)
for i in range(data['num_constraints']):
constraint = solver.RowConstraint(data['lb'][i], data['ub'][i], '')
for j in range(data['num_vars']):
constraint.SetCoefficient(x[j], data['constraint_coeffs'][i][j])
objective = solver.Objective()
for j in range(data['num_vars']):
objective.SetCoefficient(x[j], data['obj_coeffs'][j])
objective.SetMaximization()
status = solver.Solve()
if status==pywraplp.Solver.OPTIMAL:
sol=[x[i].solution_value() for i in range(4)]
else:
sol=[0,0,0,0]
return sol,status
alpha,current_prices=get_data()
N_Tax_T=float(input("Current shares of "+symbols[0]+" in taxable: "))
N_Tax_U=float(input("Current shares of "+symbols[1]+" in taxable: "))
Tax_C=float(input("Current cash in taxable: "))
N_IRA_T=float(input("Current shares of "+symbols[0]+" in IRA: "))
N_IRA_U=float(input("Current shares of "+symbols[1]+" in IRA: "))
IRA_C=float(input("Current cash in IRA: "))
Tax_T=N_Tax_T*current_prices[0]
Tax_U=N_Tax_U*current_prices[1]
IRA_T=N_IRA_T*current_prices[0]
IRA_U=N_IRA_U*current_prices[1]
S_Tax=Tax_T+Tax_U+Tax_C
S_IRA=IRA_T+IRA_U+IRA_C
S=S_Tax+S_IRA
epsilon=0.01
sol,status=findsol(epsilon)
while status != pywraplp.Solver.OPTIMAL:
epsilon=epsilon+0.01
sol,status=findsol(epsilon)
N_Tax_T2,N_Tax_U2,N_IRA_T2,N_IRA_U2=sol
print('-'*10+'result'+'-'*10)
Tax_C2=S_Tax-N_Tax_T2*current_prices[0]-N_Tax_U2*current_prices[1]
IRA_C2=S_IRA-N_IRA_T2*current_prices[0]-N_IRA_U2*current_prices[1]
S_T2=(N_Tax_T2+N_IRA_T2)*current_prices[0]
S_U2=(N_Tax_U2+N_IRA_U2)*current_prices[1]
print('Cash in Taxable %f' % Tax_C2)
print('Cash in IRA %f' % IRA_C2)
print('Achievable balance of TMF/UPRO: ({:.2f}%/{:.2f}%), target ({:.2f}%/{:.2f}%)'.format(100*S_T2/(S_T2+S_U2),100*S_U2/(S_T2+S_U2),100*alpha[0],100*alpha[1]))
print('-'*10+'action'+'-'*10)
print(('buy'*(N_Tax_T2-N_Tax_T>=0)+'sell'*(N_Tax_T2-N_Tax_T<0))+' TMF in Taxable: '+str(int(abs(N_Tax_T2-N_Tax_T)))+' at price '+str(current_prices[0]))
print(('buy'*(N_Tax_U2-N_Tax_U>=0)+'sell'*(N_Tax_U2-N_Tax_U<0))+' UPRO in Taxable: '+str(int(abs(N_Tax_U2-N_Tax_U)))+' at price '+str(current_prices[1]))
print(('buy'*(N_IRA_T2-N_IRA_T>=0)+'sell'*(N_IRA_T2-N_IRA_T<0))+' TMF in IRA: '+str(int(abs(N_IRA_T2-N_IRA_T)))+' at price '+str(current_prices[0]))
print(('buy'*(N_IRA_U2-N_IRA_U>=0)+'sell'*(N_IRA_U2-N_IRA_U<0))+' UPRO in IRA: '+str(int(abs(N_IRA_U2-N_IRA_U)))+' at price '+str(current_prices[1]))
|
[
"ortools.linear_solver.pywraplp.Solver.CreateSolver",
"numpy.std",
"numpy.floor",
"datetime.date.today",
"time.time",
"numpy.array",
"requests.get",
"math.log",
"numpy.sqrt",
"re.compile"
] |
[((491, 502), 'time.time', 'time.time', ([], {}), '()\n', (500, 502), False, 'import time\n'), ((1902, 1919), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (1914, 1919), False, 'import requests\n'), ((1982, 2043), 're.compile', 're.compile', (['""".*"CrumbStore":\\\\{"crumb":"(?P<crumb>[^"]+)"\\\\}"""'], {}), '(\'.*"CrumbStore":\\\\{"crumb":"(?P<crumb>[^"]+)"\\\\}\')\n', (1992, 2043), False, 'import re\n'), ((4408, 4443), 'ortools.linear_solver.pywraplp.Solver.CreateSolver', 'pywraplp.Solver.CreateSolver', (['"""CBC"""'], {}), "('CBC')\n", (4436, 4443), False, 'from ortools.linear_solver import pywraplp\n'), ((1633, 1645), 'datetime.date.today', 'date.today', ([], {}), '()\n', (1643, 1645), False, 'from datetime import datetime, date\n'), ((4070, 4105), 'numpy.floor', 'np.floor', (['(S_Tax / current_prices[0])'], {}), '(S_Tax / current_prices[0])\n', (4078, 4105), True, 'import numpy as np\n'), ((4104, 4139), 'numpy.floor', 'np.floor', (['(S_Tax / current_prices[1])'], {}), '(S_Tax / current_prices[1])\n', (4112, 4139), True, 'import numpy as np\n'), ((4138, 4173), 'numpy.floor', 'np.floor', (['(S_IRA / current_prices[0])'], {}), '(S_IRA / current_prices[0])\n', (4146, 4173), True, 'import numpy as np\n'), ((4172, 4207), 'numpy.floor', 'np.floor', (['(S_IRA / current_prices[1])'], {}), '(S_IRA / current_prices[1])\n', (4180, 4207), True, 'import numpy as np\n'), ((1400, 1435), 'math.log', 'math.log', (['(prices[i] / prices[i + 1])'], {}), '(prices[i] / prices[i + 1])\n', (1408, 1435), False, 'import math\n'), ((1679, 1717), 'numpy.std', 'np.std', (['volatilities_in_window'], {'ddof': '(1)'}), '(volatilities_in_window, ddof=1)\n', (1685, 1717), True, 'import numpy as np\n'), ((1722, 1756), 'numpy.sqrt', 'np.sqrt', (['num_trading_days_per_year'], {}), '(num_trading_days_per_year)\n', (1729, 1756), True, 'import numpy as np\n'), ((2749, 2771), 'numpy.array', 'np.array', (['volatilities'], {}), '(volatilities)\n', (2757, 2771), True, 'import numpy as np\n'), ((1537, 1549), 'datetime.date.today', 'date.today', ([], {}), '()\n', (1547, 1549), False, 'from datetime import datetime, date\n'), ((2882, 2894), 'datetime.date.today', 'date.today', ([], {}), '()\n', (2892, 2894), False, 'from datetime import datetime, date\n'), ((829, 1011), 'requests.get', 'requests.get', (['download_url'], {'headers': "{'User-Agent':\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2866.71 Safari/537.36'\n }"}), "(download_url, headers={'User-Agent':\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2866.71 Safari/537.36'\n })\n", (841, 1011), False, 'import requests\n')]
|
#!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Test objects and function in the module reweighting.
"""
# =============================================================================
# GLOBAL IMPORTS
# =============================================================================
import os
import tempfile
import numpy as np
from numpy.random import RandomState
import pint
from ..reweighting import DatasetReweighting
# =============================================================================
# GLOBAL VARIABLES
# =============================================================================
# Makes random test cases deterministic.
_random_state = RandomState(0)
_ureg = pint.UnitRegistry()
# =============================================================================
# TEST UTILITIES
# =============================================================================
class DummyStdReweighting(DatasetReweighting):
"""Dummy implementation of standard reweighting for testing."""
U0 = 0.0
def compute_potentials(self, batch_positions):
kJ_mol = _ureg.kJ / _ureg.mol
return (self.U0 + _random_state.rand(len(batch_positions))) * kJ_mol
def get_traj_info(self):
kJ_mol = _ureg.kJ / _ureg.mol
cvs = np.array(range(len(self.dataset)))
reference_potentials = _random_state.rand(len(cvs)) * kJ_mol
metad_rbias = np.zeros(len(cvs)) * kJ_mol
return cvs, reference_potentials, metad_rbias
# =============================================================================
# TESTS
# =============================================================================
def test_standard_reweighting_potentials_cache():
"""Test that DatasetReweighting caches and reuses the potentials correctly."""
import MDAnalysis.coordinates
from ..data import TrajectoryDataset, TrajectorySubset
def _get_potentials(dataset, file_path, u0, indices, batch_size, write_interval):
subset = TrajectorySubset(dataset, indices=indices)
DummyStdReweighting.U0 = u0
reweighting = DummyStdReweighting(
subset, n_bins=len(subset), temperature=300*_ureg.kelvin,
potentials_file_path=file_path)
return reweighting.compute_dataset_potentials(
batch_size=batch_size, write_interval=write_interval)
# Load the test PDB file.
pdb_file_path = os.path.join(os.path.dirname(__file__), 'data', 'chloro-fluoromethane.pdb')
with MDAnalysis.coordinates.PDB.PDBReader(pdb_file_path) as trajectory:
dataset = TrajectoryDataset(trajectory, return_batch_index=True)
# Cache the potentials in a temporary file.
with tempfile.TemporaryDirectory() as tmp_dir:
file_path = os.path.join(tmp_dir, 'potentials.npz')
# Cache a first value for the potentials of some of the frames.
u1 = 10
potentials1 = _get_potentials(dataset, file_path, u1, indices=[0, 2, 4],
batch_size=1, write_interval=2)
assert np.all((0 <= potentials1.magnitude - u1) & (potentials1.magnitude - u1 < 1))
# Check that what we have just computed does not get re-computed.
u2 = 20
potentials2 = _get_potentials(dataset, file_path, u2, indices=[1, 3, 4],
batch_size=5, write_interval=2)
assert potentials1[-1] == potentials2[-1]
assert np.all((0 <= potentials2.magnitude[:-1] - u2) & (potentials2.magnitude[:-1] - u2 < 1))
# The cache should be up-to-date.
times, potentials = DummyStdReweighting.load_cached_potentials_from_file(file_path)
assert not np.isnan(potentials).any()
|
[
"tempfile.TemporaryDirectory",
"pint.UnitRegistry",
"os.path.dirname",
"numpy.random.RandomState",
"numpy.isnan",
"os.path.join",
"numpy.all"
] |
[((825, 839), 'numpy.random.RandomState', 'RandomState', (['(0)'], {}), '(0)\n', (836, 839), False, 'from numpy.random import RandomState\n'), ((849, 868), 'pint.UnitRegistry', 'pint.UnitRegistry', ([], {}), '()\n', (866, 868), False, 'import pint\n'), ((2557, 2582), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2572, 2582), False, 'import os\n'), ((2835, 2864), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (2862, 2864), False, 'import tempfile\n'), ((2901, 2940), 'os.path.join', 'os.path.join', (['tmp_dir', '"""potentials.npz"""'], {}), "(tmp_dir, 'potentials.npz')\n", (2913, 2940), False, 'import os\n'), ((3216, 3292), 'numpy.all', 'np.all', (['((0 <= potentials1.magnitude - u1) & (potentials1.magnitude - u1 < 1))'], {}), '((0 <= potentials1.magnitude - u1) & (potentials1.magnitude - u1 < 1))\n', (3222, 3292), True, 'import numpy as np\n'), ((3625, 3715), 'numpy.all', 'np.all', (['((0 <= potentials2.magnitude[:-1] - u2) & (potentials2.magnitude[:-1] - u2 < 1)\n )'], {}), '((0 <= potentials2.magnitude[:-1] - u2) & (potentials2.magnitude[:-1] -\n u2 < 1))\n', (3631, 3715), True, 'import numpy as np\n'), ((3879, 3899), 'numpy.isnan', 'np.isnan', (['potentials'], {}), '(potentials)\n', (3887, 3899), True, 'import numpy as np\n')]
|
import re
import gzip
import numpy as np
from zipfile import ZipFile
def load_corpus(corpus_file, load_tags=False):
if corpus_file.endswith('.gz'):
corpus = []
with gzip.open(corpus_file, 'r') as f:
for line in f:
corpus.append(line.decode("utf-8").split())
elif corpus_file.endswith('.conllu'):
corpus = read_conllUD_file(corpus_file, load_tags)
return corpus
def read_conllUD_file(location, load_tags):
sentences = []
tokens = []
with open(location) as f:
for l in f:
if not(l.strip().startswith('#')):
s = l.split('\t')
if len(s) == 10 and not('-' in s[0]):
if load_tags:
tokens.append((s[1], s[3]))
else:
tokens.append(s[1])
elif len(l.strip())==0 and len(tokens) > 0:
sentences.append(tokens)
tokens = []
return enforce_unicode(sentences)
def enforce_unicode(sentences):
"""
In Python3 we should check for str class instead of unicode according to
https://stackoverflow.com/questions/19877306/nameerror-global-name-unicode-is-not-defined-in-python-3
"""
if len(sentences) == 0 or type(sentences[0][0][0]) == str: # if the first token is already unicode, there seems nothing to be done
return sentences
return [[(unicode(t[0], "utf8"), unicode(t[1], "utf8")) for t in s] for s in sentences]
def load_embeddings(filename, max_words=-1):
if filename.endswith('.gz'):
lines = gzip.open(filename)
elif filename.endswith('.zip'):
myzip = ZipFile(filename) # we assume only one embedding file to be included in a zip file
lines = myzip.open(myzip.namelist()[0])
else:
lines = open(filename)
data, words = [], []
for counter, line in enumerate(lines):
if len(words) == max_words:
break
if type(line) == bytes:
try:
line = line.decode("utf-8")
except UnicodeDecodeError:
print('Error at line {}: {}'.format(counter, line))
continue
tokens = line.rstrip().split(' ')
if len(words) == 0 and len(tokens) == 2 and re.match('[1-9][0-9]*', tokens[0]):
# the first line might contain the number of embeddings and dimensionality of the vectors
continue
try:
values = [float(i) for i in tokens[1:]]
if sum([v**2 for v in values]) > 0: # only embeddings with non-zero norm are kept
data.append(values)
words.append(tokens[0])
except:
print('Error while parsing input line #{}: {}'.format(counter, line))
i2w = dict(enumerate(words))
return np.array(data), {v:k for k,v in i2w.items()}, i2w
|
[
"numpy.array",
"zipfile.ZipFile",
"gzip.open",
"re.match"
] |
[((1602, 1621), 'gzip.open', 'gzip.open', (['filename'], {}), '(filename)\n', (1611, 1621), False, 'import gzip\n'), ((2824, 2838), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (2832, 2838), True, 'import numpy as np\n'), ((187, 214), 'gzip.open', 'gzip.open', (['corpus_file', '"""r"""'], {}), "(corpus_file, 'r')\n", (196, 214), False, 'import gzip\n'), ((1674, 1691), 'zipfile.ZipFile', 'ZipFile', (['filename'], {}), '(filename)\n', (1681, 1691), False, 'from zipfile import ZipFile\n'), ((2287, 2321), 're.match', 're.match', (['"""[1-9][0-9]*"""', 'tokens[0]'], {}), "('[1-9][0-9]*', tokens[0])\n", (2295, 2321), False, 'import re\n')]
|
"""
Test that data encoded with earlier versions can still be decoded correctly.
"""
from __future__ import absolute_import, division, print_function
import pathlib
import unittest
import numpy as np
import h5py
TEST_DATA_DIR = pathlib.Path(__file__).parent / "data"
OUT_FILE_TEMPLATE = "regression_%s.h5"
VERSIONS = [
"0.1.3",
]
class TestAll(unittest.TestCase):
def test_regression(self):
for version in VERSIONS:
file_name = TEST_DATA_DIR / (OUT_FILE_TEMPLATE % version)
f = h5py.File(file_name, "r")
g_orig = f["origional"]
g_comp = f["compressed"]
for dset_name in g_comp.keys():
self.assertTrue(np.all(g_comp[dset_name][:] == g_orig[dset_name][:]))
if __name__ == "__main__":
unittest.main()
|
[
"unittest.main",
"pathlib.Path",
"h5py.File",
"numpy.all"
] |
[((791, 806), 'unittest.main', 'unittest.main', ([], {}), '()\n', (804, 806), False, 'import unittest\n'), ((234, 256), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (246, 256), False, 'import pathlib\n'), ((528, 553), 'h5py.File', 'h5py.File', (['file_name', '"""r"""'], {}), "(file_name, 'r')\n", (537, 553), False, 'import h5py\n'), ((704, 756), 'numpy.all', 'np.all', (['(g_comp[dset_name][:] == g_orig[dset_name][:])'], {}), '(g_comp[dset_name][:] == g_orig[dset_name][:])\n', (710, 756), True, 'import numpy as np\n')]
|
import pytest
from io import StringIO
import numpy as np
import pandas as pd
import sandy
__author__ = "<NAME>"
#####################
# Test initialization
#####################
def test_from_file_1_column():
vals = '1\n5\n9'
file = StringIO(vals)
with pytest.raises(Exception):
sandy.Pert.from_file(file)
def test_from_file_non_monotonic():
vals = '1 1\n6 5\n5 2\n9 3'
file = StringIO(vals)
with pytest.raises(Exception):
sandy.Pert.from_file(file)
@pytest.fixture(scope="module")
def pert3():
vals = '1 1 5\n5 2 1\n9 3 1'
file = StringIO(vals)
return sandy.Pert.from_file(file)
def test_from_file_3_columns(pert3):
# should try and catch the warning
pass
def test_init_with_series(pert3):
pert = sandy.Pert(pert3.right)
assert pert.data.equals(pert3.data)
def test_init_with_dataframe(pert3):
with pytest.raises(Exception):
sandy.Pert(pert3.right.to_frame())
def test_init_with_intervalindex(pert3):
pert = sandy.Pert(pert3.data)
assert pert.data.equals(pert3.data)
################################
# Test initialization attributes
################################
def test_Pert_type(pert3):
assert isinstance(pert3, sandy.Pert)
def test_Pert_data_index_type(pert3):
assert isinstance(pert3.data.index, pd.IntervalIndex)
def test_Pert_data_index_right_values(pert3):
assert pert3.data.index.right.tolist() == [1, 5, 9]
def test_Pert_data_index_left_values(pert3):
assert pert3.data.index.left.tolist() == [0, 1, 5]
def test_Pert_data_index_float(pert3):
assert pert3.data.index.right.values.dtype == float
def test_Pert_data_values(pert3):
np.testing.assert_array_equal(pert3.data.values, [1,2,3])
def test_Pert_data_values_float(pert3):
assert pert3.data.values.dtype == float
########################
# Test attributes
########################
########################
# Test methods
########################
# def test_Spectrum_selfreshape(spec_const):
# S = spec_const.reshape(spec_const.right.index)
# assert np.allclose(S.data.values,spec_const.data.values)
# @pytest.mark.parametrize("eg, flux",
# [
# ([30], 500),
# ([6e-12], 0.6),
# ([5e-12], 0.5),
# ([4e-12], 0.4),
# ([1e-11], 1),
# ([18.896380829766173], 499),
# ([1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0, 1e1, 20], 500),
# ]
# )
# def test_Spectrum_reshape(spec_const, eg, flux):
# S = spec_const.reshape(eg)
# assert S.right.index.tolist() == eg
# assert S.flux == pytest.approx(flux)
# @pytest.mark.parametrize("eg, err, errtype",
# [
# ([2, 1], True, ValueError),
# ([2, 2], False, None),
# ([-1, 2], True, ValueError),
# ]
# )
# def test_Spectrum_reshape_error(spec_const, eg, err, errtype):
# if err:
# with pytest.raises(errtype):
# spec_const.reshape(eg)
# else:
# spec_const.reshape(eg)
|
[
"sandy.Pert",
"io.StringIO",
"sandy.Pert.from_file",
"numpy.testing.assert_array_equal",
"pytest.fixture",
"pytest.raises"
] |
[((526, 556), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (540, 556), False, 'import pytest\n'), ((260, 274), 'io.StringIO', 'StringIO', (['vals'], {}), '(vals)\n', (268, 274), False, 'from io import StringIO\n'), ((435, 449), 'io.StringIO', 'StringIO', (['vals'], {}), '(vals)\n', (443, 449), False, 'from io import StringIO\n'), ((623, 637), 'io.StringIO', 'StringIO', (['vals'], {}), '(vals)\n', (631, 637), False, 'from io import StringIO\n'), ((650, 676), 'sandy.Pert.from_file', 'sandy.Pert.from_file', (['file'], {}), '(file)\n', (670, 676), False, 'import sandy\n'), ((816, 839), 'sandy.Pert', 'sandy.Pert', (['pert3.right'], {}), '(pert3.right)\n', (826, 839), False, 'import sandy\n'), ((1057, 1079), 'sandy.Pert', 'sandy.Pert', (['pert3.data'], {}), '(pert3.data)\n', (1067, 1079), False, 'import sandy\n'), ((1748, 1807), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['pert3.data.values', '[1, 2, 3]'], {}), '(pert3.data.values, [1, 2, 3])\n', (1777, 1807), True, 'import numpy as np\n'), ((285, 309), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (298, 309), False, 'import pytest\n'), ((320, 346), 'sandy.Pert.from_file', 'sandy.Pert.from_file', (['file'], {}), '(file)\n', (340, 346), False, 'import sandy\n'), ((460, 484), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (473, 484), False, 'import pytest\n'), ((495, 521), 'sandy.Pert.from_file', 'sandy.Pert.from_file', (['file'], {}), '(file)\n', (515, 521), False, 'import sandy\n'), ((931, 955), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (944, 955), False, 'import pytest\n')]
|
#!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. 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.
from functools import reduce
import unittest
import numpy
import scipy.linalg
from pyscf import lib
from pyscf import gto
from pyscf.x2c import sfx2c1e
from pyscf.x2c import sfx2c1e_grad
def _sqrt0(a):
w, v = scipy.linalg.eigh(a)
return numpy.dot(v*numpy.sqrt(w), v.conj().T)
def _invsqrt0(a):
w, v = scipy.linalg.eigh(a)
return numpy.dot(v/numpy.sqrt(w), v.conj().T)
def _sqrt1(a0, a1):
'''Solving first order of x^2 = a'''
w, v = scipy.linalg.eigh(a0)
w = numpy.sqrt(w)
a1 = reduce(numpy.dot, (v.conj().T, a1, v))
x1 = a1 / (w[:,None] + w)
x1 = reduce(numpy.dot, (v, x1, v.conj().T))
return x1
def _invsqrt1(a0, a1):
'''Solving first order of x^2 = a^{-1}'''
w, v = scipy.linalg.eigh(a0)
w = 1./numpy.sqrt(w)
a1 = -reduce(numpy.dot, (v.conj().T, a1, v))
x1 = numpy.einsum('i,ij,j->ij', w**2, a1, w**2) / (w[:,None] + w)
x1 = reduce(numpy.dot, (v, x1, v.conj().T))
return x1
def get_R(mol):
s0 = mol.intor('int1e_ovlp')
t0 = mol.intor('int1e_kin')
s0sqrt = _sqrt0(s0)
s0invsqrt = _invsqrt0(s0)
x0 = get_x0(mol)
c = lib.param.LIGHT_SPEED
stild = s0 + reduce(numpy.dot, (x0.T, t0*(.5/c**2), x0))
R = _invsqrt0(reduce(numpy.dot, (s0invsqrt, stild, s0invsqrt)))
R = reduce(numpy.dot, (s0invsqrt, R, s0sqrt))
return R
def get_r1(mol, atm_id, pos):
# See JCP 135 084114, Eq (34)
c = lib.param.LIGHT_SPEED
aoslices = mol.aoslice_by_atom()
ish0, ish1, p0, p1 = aoslices[atm_id]
s0 = mol.intor('int1e_ovlp')
t0 = mol.intor('int1e_kin')
s1all = mol.intor('int1e_ipovlp', comp=3)
t1all = mol.intor('int1e_ipkin', comp=3)
s1 = numpy.zeros_like(s0)
t1 = numpy.zeros_like(t0)
s1[p0:p1,:] =-s1all[pos][p0:p1]
s1[:,p0:p1] -= s1all[pos][p0:p1].T
t1[p0:p1,:] =-t1all[pos][p0:p1]
t1[:,p0:p1] -= t1all[pos][p0:p1].T
x0 = get_x0(mol)
x1 = get_x1(mol, atm_id)[pos]
sa0 = s0 + reduce(numpy.dot, (x0.T, t0*(.5/c**2), x0))
sa1 = s1 + reduce(numpy.dot, (x0.T, t1*(.5/c**2), x0))
sa1+= reduce(numpy.dot, (x1.T, t0*(.5/c**2), x0))
sa1+= reduce(numpy.dot, (x0.T, t0*(.5/c**2), x1))
s0_sqrt = _sqrt0(s0)
s0_invsqrt = _invsqrt0(s0)
s1_sqrt = _sqrt1(s0, s1)
s1_invsqrt = _invsqrt1(s0, s1)
R0_part = reduce(numpy.dot, (s0_invsqrt, sa0, s0_invsqrt))
R1_part = (reduce(numpy.dot, (s0_invsqrt, sa1, s0_invsqrt)) +
reduce(numpy.dot, (s1_invsqrt, sa0, s0_invsqrt)) +
reduce(numpy.dot, (s0_invsqrt, sa0, s1_invsqrt)))
R1 = reduce(numpy.dot, (s0_invsqrt, _invsqrt1(R0_part, R1_part), s0_sqrt))
R1 += reduce(numpy.dot, (s1_invsqrt, _invsqrt0(R0_part), s0_sqrt))
R1 += reduce(numpy.dot, (s0_invsqrt, _invsqrt0(R0_part), s1_sqrt))
return R1
def get_h0_s0(mol):
s = mol.intor_symmetric('int1e_ovlp')
t = mol.intor_symmetric('int1e_kin')
v = mol.intor_symmetric('int1e_nuc')
w = mol.intor_symmetric('int1e_pnucp')
nao = s.shape[0]
n2 = nao * 2
h = numpy.zeros((n2,n2), dtype=v.dtype)
m = numpy.zeros((n2,n2), dtype=v.dtype)
c = lib.param.LIGHT_SPEED
h[:nao,:nao] = v
h[:nao,nao:] = t
h[nao:,:nao] = t
h[nao:,nao:] = w * (.25/c**2) - t
m[:nao,:nao] = s
m[nao:,nao:] = t * (.5/c**2)
return h, m
def get_h1_s1(mol, ia):
aoslices = mol.aoslice_by_atom()
ish0, ish1, p0, p1 = aoslices[0]
nao = mol.nao_nr()
s1 = mol.intor('int1e_ipovlp', comp=3)
t1 = mol.intor('int1e_ipkin', comp=3)
v1 = mol.intor('int1e_ipnuc', comp=3)
w1 = mol.intor('int1e_ipspnucsp', comp=12).reshape(3,4,nao,nao)[:,3]
with mol.with_rinv_origin(mol.atom_coord(ia)):
rinv1 = -8*mol.intor('int1e_iprinv', comp=3)
prinvp1 = -8*mol.intor('int1e_ipsprinvsp', comp=12).reshape(3,4,nao,nao)[:,3]
n2 = nao * 2
h = numpy.zeros((3,n2,n2), dtype=v1.dtype)
m = numpy.zeros((3,n2,n2), dtype=v1.dtype)
rinv1[:,p0:p1,:] -= v1[:,p0:p1]
rinv1 = rinv1 + rinv1.transpose(0,2,1).conj()
prinvp1[:,p0:p1,:] -= w1[:,p0:p1]
prinvp1 = prinvp1 + prinvp1.transpose(0,2,1).conj()
s1ao = numpy.zeros_like(s1)
t1ao = numpy.zeros_like(t1)
s1ao[:,p0:p1,:] = -s1[:,p0:p1]
s1ao[:,:,p0:p1]+= -s1[:,p0:p1].transpose(0,2,1)
t1ao[:,p0:p1,:] = -t1[:,p0:p1]
t1ao[:,:,p0:p1]+= -t1[:,p0:p1].transpose(0,2,1)
c = lib.param.LIGHT_SPEED
h[:,:nao,:nao] = rinv1
h[:,:nao,nao:] = t1ao
h[:,nao:,:nao] = t1ao
h[:,nao:,nao:] = prinvp1 * (.25/c**2) - t1ao
m[:,:nao,:nao] = s1ao
m[:,nao:,nao:] = t1ao * (.5/c**2)
return h, m
def get_x0(mol):
c = lib.param.LIGHT_SPEED
h0, s0 = get_h0_s0(mol)
e, c = scipy.linalg.eigh(h0, s0)
nao = mol.nao_nr()
cl = c[:nao,nao:]
cs = c[nao:,nao:]
x0 = scipy.linalg.solve(cl.T, cs.T).T
return x0
def get_x1(mol, ia):
h0, s0 = get_h0_s0(mol)
h1, s1 = get_h1_s1(mol, ia)
e0, c0 = scipy.linalg.eigh(h0, s0)
nao = mol.nao_nr()
cl0 = c0[:nao,nao:]
cs0 = c0[nao:,nao:]
x0 = scipy.linalg.solve(cl0.T, cs0.T).T
h1 = numpy.einsum('pi,xpq,qj->xij', c0.conj(), h1, c0[:,nao:])
s1 = numpy.einsum('pi,xpq,qj->xij', c0.conj(), s1, c0[:,nao:])
epi = e0[:,None] - e0[nao:]
degen_mask = abs(epi) < 1e-7
epi[degen_mask] = 1e200
c1 = (h1 - s1 * e0[nao:]) / -epi
c1[:,degen_mask] = -.5 * s1[:,degen_mask]
c1 = numpy.einsum('pq,xqi->xpi', c0, c1)
cl1 = c1[:,:nao]
cs1 = c1[:,nao:]
x1 = [scipy.linalg.solve(cl0.T, (cs1[i] - x0.dot(cl1[i])).T).T
for i in range(3)]
return numpy.asarray(x1)
mol1 = gto.M(
verbose = 0,
atom = [["O" , (0. , 0. , 0.0001)],
[1 , (0. , -0.757 , 0.587)],
[1 , (0. , 0.757 , 0.587)]],
basis = '3-21g',
)
mol2 = gto.M(
verbose = 0,
atom = [["O" , (0. , 0. ,-0.0001)],
[1 , (0. , -0.757 , 0.587)],
[1 , (0. , 0.757 , 0.587)]],
basis = '3-21g',
)
mol = gto.M(
verbose = 0,
atom = [["O" , (0. , 0. , 0. )],
[1 , (0. , -0.757 , 0.587)],
[1 , (0. , 0.757 , 0.587)]],
basis = '3-21g',
)
class KnownValues(unittest.TestCase):
def test_x1(self):
with lib.light_speed(10) as c:
x_1 = get_x0(mol1)
x_2 = get_x0(mol2)
x1_ref = (x_1 - x_2) / 0.0002 * lib.param.BOHR
x1t = get_x1(mol, 0)
self.assertAlmostEqual(abs(x1t[2]-x1_ref).max(), 0, 7)
x0 = get_x0(mol)
h0, s0 = get_h0_s0(mol)
e0, c0 = scipy.linalg.eigh(h0, s0)
get_h1_etc = sfx2c1e_grad._gen_first_order_quantities(mol, e0, c0, x0)
x1 = get_h1_etc(0)[4]
self.assertAlmostEqual(abs(x1-x1t).max(), 0, 9)
def test_R1(self):
with lib.light_speed(10) as c:
R_1 = get_R(mol1)
R_2 = get_R(mol2)
R1_ref = (R_1 - R_2) / 0.0002 * lib.param.BOHR
R1t = get_r1(mol, 0, 2)
self.assertAlmostEqual(abs(R1t-R1_ref).max(), 0, 7)
x0 = get_x0(mol)
h0, s0 = get_h0_s0(mol)
e0, c0 = scipy.linalg.eigh(h0, s0)
get_h1_etc = sfx2c1e_grad._gen_first_order_quantities(mol, e0, c0, x0)
R1 = get_h1_etc(0)[6][2]
self.assertAlmostEqual(abs(R1-R1t).max(), 0, 9)
def test_hfw(self):
with lib.light_speed(10) as c:
x2c_1 = sfx2c1e.SpinFreeX2C(mol1)
x2c_2 = sfx2c1e.SpinFreeX2C(mol2)
x2cobj = sfx2c1e.SpinFreeX2C(mol)
fh_ref = (x2c_1.get_hcore() - x2c_2.get_hcore()) / 0.0002 * lib.param.BOHR
fh = x2cobj.hcore_deriv_generator(deriv=1)
self.assertAlmostEqual(abs(fh(0)[2] - fh_ref).max(), 0, 7)
x2c_1.xuncontract = 0
x2c_2.xuncontract = 0
x2cobj.xuncontract =0
fh_ref = (x2c_1.get_hcore() - x2c_2.get_hcore()) / 0.0002 * lib.param.BOHR
fh = x2cobj.hcore_deriv_generator(deriv=1)
self.assertAlmostEqual(abs(fh(0)[2] - fh_ref).max(), 0, 7)
x2c_1.xuncontract = 1
x2c_2.xuncontract = 1
x2cobj.xuncontract =1
x2c_1.approx = 'ATOM1E'
x2c_2.approx = 'ATOM1E'
x2cobj.approx = 'ATOM1E'
fh_ref = (x2c_1.get_hcore() - x2c_2.get_hcore()) / 0.0002 * lib.param.BOHR
fh = x2cobj.hcore_deriv_generator(deriv=1)
self.assertAlmostEqual(abs(fh(0)[2] - fh_ref).max(), 0, 7)
if __name__ == "__main__":
print("Full Tests for sfx2c1e gradients")
unittest.main()
|
[
"unittest.main",
"numpy.zeros_like",
"pyscf.x2c.sfx2c1e.SpinFreeX2C",
"numpy.asarray",
"numpy.zeros",
"numpy.einsum",
"pyscf.lib.light_speed",
"pyscf.gto.M",
"pyscf.x2c.sfx2c1e_grad._gen_first_order_quantities",
"functools.reduce",
"numpy.sqrt"
] |
[((6199, 6321), 'pyscf.gto.M', 'gto.M', ([], {'verbose': '(0)', 'atom': "[['O', (0.0, 0.0, 0.0001)], [1, (0.0, -0.757, 0.587)], [1, (0.0, 0.757, 0.587)]\n ]", 'basis': '"""3-21g"""'}), "(verbose=0, atom=[['O', (0.0, 0.0, 0.0001)], [1, (0.0, -0.757, 0.587)],\n [1, (0.0, 0.757, 0.587)]], basis='3-21g')\n", (6204, 6321), False, 'from pyscf import gto\n'), ((6385, 6509), 'pyscf.gto.M', 'gto.M', ([], {'verbose': '(0)', 'atom': "[['O', (0.0, 0.0, -0.0001)], [1, (0.0, -0.757, 0.587)], [1, (0.0, 0.757, \n 0.587)]]", 'basis': '"""3-21g"""'}), "(verbose=0, atom=[['O', (0.0, 0.0, -0.0001)], [1, (0.0, -0.757, 0.587)\n ], [1, (0.0, 0.757, 0.587)]], basis='3-21g')\n", (6390, 6509), False, 'from pyscf import gto\n'), ((6570, 6690), 'pyscf.gto.M', 'gto.M', ([], {'verbose': '(0)', 'atom': "[['O', (0.0, 0.0, 0.0)], [1, (0.0, -0.757, 0.587)], [1, (0.0, 0.757, 0.587)]]", 'basis': '"""3-21g"""'}), "(verbose=0, atom=[['O', (0.0, 0.0, 0.0)], [1, (0.0, -0.757, 0.587)], [\n 1, (0.0, 0.757, 0.587)]], basis='3-21g')\n", (6575, 6690), False, 'from pyscf import gto\n'), ((1123, 1136), 'numpy.sqrt', 'numpy.sqrt', (['w'], {}), '(w)\n', (1133, 1136), False, 'import numpy\n'), ((1910, 1951), 'functools.reduce', 'reduce', (['numpy.dot', '(s0invsqrt, R, s0sqrt)'], {}), '(numpy.dot, (s0invsqrt, R, s0sqrt))\n', (1916, 1951), False, 'from functools import reduce\n'), ((2300, 2320), 'numpy.zeros_like', 'numpy.zeros_like', (['s0'], {}), '(s0)\n', (2316, 2320), False, 'import numpy\n'), ((2330, 2350), 'numpy.zeros_like', 'numpy.zeros_like', (['t0'], {}), '(t0)\n', (2346, 2350), False, 'import numpy\n'), ((2686, 2736), 'functools.reduce', 'reduce', (['numpy.dot', '(x1.T, t0 * (0.5 / c ** 2), x0)'], {}), '(numpy.dot, (x1.T, t0 * (0.5 / c ** 2), x0))\n', (2692, 2736), False, 'from functools import reduce\n'), ((2740, 2790), 'functools.reduce', 'reduce', (['numpy.dot', '(x0.T, t0 * (0.5 / c ** 2), x1)'], {}), '(numpy.dot, (x0.T, t0 * (0.5 / c ** 2), x1))\n', (2746, 2790), False, 'from functools import reduce\n'), ((2919, 2967), 'functools.reduce', 'reduce', (['numpy.dot', '(s0_invsqrt, sa0, s0_invsqrt)'], {}), '(numpy.dot, (s0_invsqrt, sa0, s0_invsqrt))\n', (2925, 2967), False, 'from functools import reduce\n'), ((3635, 3671), 'numpy.zeros', 'numpy.zeros', (['(n2, n2)'], {'dtype': 'v.dtype'}), '((n2, n2), dtype=v.dtype)\n', (3646, 3671), False, 'import numpy\n'), ((3679, 3715), 'numpy.zeros', 'numpy.zeros', (['(n2, n2)'], {'dtype': 'v.dtype'}), '((n2, n2), dtype=v.dtype)\n', (3690, 3715), False, 'import numpy\n'), ((4453, 4493), 'numpy.zeros', 'numpy.zeros', (['(3, n2, n2)'], {'dtype': 'v1.dtype'}), '((3, n2, n2), dtype=v1.dtype)\n', (4464, 4493), False, 'import numpy\n'), ((4500, 4540), 'numpy.zeros', 'numpy.zeros', (['(3, n2, n2)'], {'dtype': 'v1.dtype'}), '((3, n2, n2), dtype=v1.dtype)\n', (4511, 4540), False, 'import numpy\n'), ((4731, 4751), 'numpy.zeros_like', 'numpy.zeros_like', (['s1'], {}), '(s1)\n', (4747, 4751), False, 'import numpy\n'), ((4763, 4783), 'numpy.zeros_like', 'numpy.zeros_like', (['t1'], {}), '(t1)\n', (4779, 4783), False, 'import numpy\n'), ((5988, 6023), 'numpy.einsum', 'numpy.einsum', (['"""pq,xqi->xpi"""', 'c0', 'c1'], {}), "('pq,xqi->xpi', c0, c1)\n", (6000, 6023), False, 'import numpy\n'), ((6173, 6190), 'numpy.asarray', 'numpy.asarray', (['x1'], {}), '(x1)\n', (6186, 6190), False, 'import numpy\n'), ((9169, 9184), 'unittest.main', 'unittest.main', ([], {}), '()\n', (9182, 9184), False, 'import unittest\n'), ((1391, 1404), 'numpy.sqrt', 'numpy.sqrt', (['w'], {}), '(w)\n', (1401, 1404), False, 'import numpy\n'), ((1463, 1509), 'numpy.einsum', 'numpy.einsum', (['"""i,ij,j->ij"""', '(w ** 2)', 'a1', '(w ** 2)'], {}), "('i,ij,j->ij', w ** 2, a1, w ** 2)\n", (1475, 1509), False, 'import numpy\n'), ((1790, 1840), 'functools.reduce', 'reduce', (['numpy.dot', '(x0.T, t0 * (0.5 / c ** 2), x0)'], {}), '(numpy.dot, (x0.T, t0 * (0.5 / c ** 2), x0))\n', (1796, 1840), False, 'from functools import reduce\n'), ((1852, 1900), 'functools.reduce', 'reduce', (['numpy.dot', '(s0invsqrt, stild, s0invsqrt)'], {}), '(numpy.dot, (s0invsqrt, stild, s0invsqrt))\n', (1858, 1900), False, 'from functools import reduce\n'), ((2573, 2623), 'functools.reduce', 'reduce', (['numpy.dot', '(x0.T, t0 * (0.5 / c ** 2), x0)'], {}), '(numpy.dot, (x0.T, t0 * (0.5 / c ** 2), x0))\n', (2579, 2623), False, 'from functools import reduce\n'), ((2632, 2682), 'functools.reduce', 'reduce', (['numpy.dot', '(x0.T, t1 * (0.5 / c ** 2), x0)'], {}), '(numpy.dot, (x0.T, t1 * (0.5 / c ** 2), x0))\n', (2638, 2682), False, 'from functools import reduce\n'), ((3115, 3163), 'functools.reduce', 'reduce', (['numpy.dot', '(s0_invsqrt, sa0, s1_invsqrt)'], {}), '(numpy.dot, (s0_invsqrt, sa0, s1_invsqrt))\n', (3121, 3163), False, 'from functools import reduce\n'), ((892, 905), 'numpy.sqrt', 'numpy.sqrt', (['w'], {}), '(w)\n', (902, 905), False, 'import numpy\n'), ((993, 1006), 'numpy.sqrt', 'numpy.sqrt', (['w'], {}), '(w)\n', (1003, 1006), False, 'import numpy\n'), ((2983, 3031), 'functools.reduce', 'reduce', (['numpy.dot', '(s0_invsqrt, sa1, s0_invsqrt)'], {}), '(numpy.dot, (s0_invsqrt, sa1, s0_invsqrt))\n', (2989, 3031), False, 'from functools import reduce\n'), ((3049, 3097), 'functools.reduce', 'reduce', (['numpy.dot', '(s1_invsqrt, sa0, s0_invsqrt)'], {}), '(numpy.dot, (s1_invsqrt, sa0, s0_invsqrt))\n', (3055, 3097), False, 'from functools import reduce\n'), ((6823, 6842), 'pyscf.lib.light_speed', 'lib.light_speed', (['(10)'], {}), '(10)\n', (6838, 6842), False, 'from pyscf import lib\n'), ((7208, 7265), 'pyscf.x2c.sfx2c1e_grad._gen_first_order_quantities', 'sfx2c1e_grad._gen_first_order_quantities', (['mol', 'e0', 'c0', 'x0'], {}), '(mol, e0, c0, x0)\n', (7248, 7265), False, 'from pyscf.x2c import sfx2c1e_grad\n'), ((7397, 7416), 'pyscf.lib.light_speed', 'lib.light_speed', (['(10)'], {}), '(10)\n', (7412, 7416), False, 'from pyscf import lib\n'), ((7780, 7837), 'pyscf.x2c.sfx2c1e_grad._gen_first_order_quantities', 'sfx2c1e_grad._gen_first_order_quantities', (['mol', 'e0', 'c0', 'x0'], {}), '(mol, e0, c0, x0)\n', (7820, 7837), False, 'from pyscf.x2c import sfx2c1e_grad\n'), ((7973, 7992), 'pyscf.lib.light_speed', 'lib.light_speed', (['(10)'], {}), '(10)\n', (7988, 7992), False, 'from pyscf import lib\n'), ((8019, 8044), 'pyscf.x2c.sfx2c1e.SpinFreeX2C', 'sfx2c1e.SpinFreeX2C', (['mol1'], {}), '(mol1)\n', (8038, 8044), False, 'from pyscf.x2c import sfx2c1e\n'), ((8065, 8090), 'pyscf.x2c.sfx2c1e.SpinFreeX2C', 'sfx2c1e.SpinFreeX2C', (['mol2'], {}), '(mol2)\n', (8084, 8090), False, 'from pyscf.x2c import sfx2c1e\n'), ((8112, 8136), 'pyscf.x2c.sfx2c1e.SpinFreeX2C', 'sfx2c1e.SpinFreeX2C', (['mol'], {}), '(mol)\n', (8131, 8136), False, 'from pyscf.x2c import sfx2c1e\n')]
|
from datastack import DataTable, DataColumn, label, col, desc
import pytest
import numpy as np
def test_one():
tbl = (DataTable(a=(1,2,1,2,3,1), b=(4,5,6,3,2,1),c=(6,7,8,1,2,3))
.order_by(desc(label("b")))
)
exp = DataTable(a=(1,2,1,2,3,1), b=(6,5,4,3,2,1), c=(8,7,6,1,2,3))
assert tbl == exp
def test_one_str():
tbl = (DataTable(a=(1,2,1,2,3,1), b=(4,5,6,3,2,1),c=list("abcdef"))
.order_by(label("b"))
)
exp = DataTable(a=(1,3,2,1,2,1), b=(1,2,3,4,5,6), c=list("fedabc"))
assert tbl == exp
def test_two():
tbl = (DataTable(b=(4,5,2,3,2,1),c=(6,7,8,1,2,3),a=(1,2,1,2,3,1))
.order_by(label("b"), desc(label("a")), label("c"), )
)
exp = DataTable( b=(1,2,2,3,4,5), c=(3,2,8,1,6,7),a=(1,3,1,2,1,2))
assert tbl == exp
def test_two_asc():
data = {"col1": np.array((1, 2, 3, 4, 5, 4, 3, 2, 1)),
"col2": np.array(list("abcdeabcd")),
"col3": np.array((10, 11, 9, 8, 7, 2, 12, 100, 1))}
tbl = (DataTable.from_dict(data)
.order_by(label("col1"), label("col2"))
)
exp = DataTable.from_dict({'col1': np.array([1, 1, 2, 2, 3, 3, 4, 4, 5]),
'col2': np.array(['a', 'd', 'b', 'c', 'b', 'c', 'a', 'd', 'e']),
'col3': np.array([10, 1, 11, 100, 12, 9, 2, 8, 7])})
assert tbl == exp
def test_two_asc_desc():
data = {"col1": np.array((1, 2, 3, 4, 5, 4, 3, 2, 1)),
"col2": np.array(list("abcdeabcd")),
"col3": np.array((10, 11, 9, 8, 7, 2, 12, 100, 1))}
tbl = (DataTable.from_dict(data)
.order_by(label("col1"), desc(label("col2")))
)
exp = DataTable.from_dict({'col1': np.array([1, 1, 2, 2, 3, 3, 4, 4, 5]),
'col2': np.array(['d', 'a', 'c', 'b', 'c', 'b', 'd', 'a', 'e']),
'col3': np.array([1, 10, 100, 11, 9, 12, 8, 2, 7])})
assert tbl == exp
|
[
"datastack.DataTable",
"datastack.DataTable.from_dict",
"numpy.array",
"datastack.label"
] |
[((245, 320), 'datastack.DataTable', 'DataTable', ([], {'a': '(1, 2, 1, 2, 3, 1)', 'b': '(6, 5, 4, 3, 2, 1)', 'c': '(8, 7, 6, 1, 2, 3)'}), '(a=(1, 2, 1, 2, 3, 1), b=(6, 5, 4, 3, 2, 1), c=(8, 7, 6, 1, 2, 3))\n', (254, 320), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((732, 807), 'datastack.DataTable', 'DataTable', ([], {'b': '(1, 2, 2, 3, 4, 5)', 'c': '(3, 2, 8, 1, 6, 7)', 'a': '(1, 3, 1, 2, 1, 2)'}), '(b=(1, 2, 2, 3, 4, 5), c=(3, 2, 8, 1, 6, 7), a=(1, 3, 1, 2, 1, 2))\n', (741, 807), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((441, 451), 'datastack.label', 'label', (['"""b"""'], {}), "('b')\n", (446, 451), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((666, 676), 'datastack.label', 'label', (['"""b"""'], {}), "('b')\n", (671, 676), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((696, 706), 'datastack.label', 'label', (['"""c"""'], {}), "('c')\n", (701, 706), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((858, 895), 'numpy.array', 'np.array', (['(1, 2, 3, 4, 5, 4, 3, 2, 1)'], {}), '((1, 2, 3, 4, 5, 4, 3, 2, 1))\n', (866, 895), True, 'import numpy as np\n'), ((958, 1000), 'numpy.array', 'np.array', (['(10, 11, 9, 8, 7, 2, 12, 100, 1)'], {}), '((10, 11, 9, 8, 7, 2, 12, 100, 1))\n', (966, 1000), True, 'import numpy as np\n'), ((1064, 1077), 'datastack.label', 'label', (['"""col1"""'], {}), "('col1')\n", (1069, 1077), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((1079, 1092), 'datastack.label', 'label', (['"""col2"""'], {}), "('col2')\n", (1084, 1092), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((1444, 1481), 'numpy.array', 'np.array', (['(1, 2, 3, 4, 5, 4, 3, 2, 1)'], {}), '((1, 2, 3, 4, 5, 4, 3, 2, 1))\n', (1452, 1481), True, 'import numpy as np\n'), ((1544, 1586), 'numpy.array', 'np.array', (['(10, 11, 9, 8, 7, 2, 12, 100, 1)'], {}), '((10, 11, 9, 8, 7, 2, 12, 100, 1))\n', (1552, 1586), True, 'import numpy as np\n'), ((1650, 1663), 'datastack.label', 'label', (['"""col1"""'], {}), "('col1')\n", (1655, 1663), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((125, 200), 'datastack.DataTable', 'DataTable', ([], {'a': '(1, 2, 1, 2, 3, 1)', 'b': '(4, 5, 6, 3, 2, 1)', 'c': '(6, 7, 8, 1, 2, 3)'}), '(a=(1, 2, 1, 2, 3, 1), b=(4, 5, 6, 3, 2, 1), c=(6, 7, 8, 1, 2, 3))\n', (134, 200), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((210, 220), 'datastack.label', 'label', (['"""b"""'], {}), "('b')\n", (215, 220), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((587, 662), 'datastack.DataTable', 'DataTable', ([], {'b': '(4, 5, 2, 3, 2, 1)', 'c': '(6, 7, 8, 1, 2, 3)', 'a': '(1, 2, 1, 2, 3, 1)'}), '(b=(4, 5, 2, 3, 2, 1), c=(6, 7, 8, 1, 2, 3), a=(1, 2, 1, 2, 3, 1))\n', (596, 662), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((683, 693), 'datastack.label', 'label', (['"""a"""'], {}), "('a')\n", (688, 693), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((1016, 1041), 'datastack.DataTable.from_dict', 'DataTable.from_dict', (['data'], {}), '(data)\n', (1035, 1041), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((1143, 1180), 'numpy.array', 'np.array', (['[1, 1, 2, 2, 3, 3, 4, 4, 5]'], {}), '([1, 1, 2, 2, 3, 3, 4, 4, 5])\n', (1151, 1180), True, 'import numpy as np\n'), ((1226, 1281), 'numpy.array', 'np.array', (["['a', 'd', 'b', 'c', 'b', 'c', 'a', 'd', 'e']"], {}), "(['a', 'd', 'b', 'c', 'b', 'c', 'a', 'd', 'e'])\n", (1234, 1281), True, 'import numpy as np\n'), ((1327, 1369), 'numpy.array', 'np.array', (['[10, 1, 11, 100, 12, 9, 2, 8, 7]'], {}), '([10, 1, 11, 100, 12, 9, 2, 8, 7])\n', (1335, 1369), True, 'import numpy as np\n'), ((1602, 1627), 'datastack.DataTable.from_dict', 'DataTable.from_dict', (['data'], {}), '(data)\n', (1621, 1627), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((1670, 1683), 'datastack.label', 'label', (['"""col2"""'], {}), "('col2')\n", (1675, 1683), False, 'from datastack import DataTable, DataColumn, label, col, desc\n'), ((1735, 1772), 'numpy.array', 'np.array', (['[1, 1, 2, 2, 3, 3, 4, 4, 5]'], {}), '([1, 1, 2, 2, 3, 3, 4, 4, 5])\n', (1743, 1772), True, 'import numpy as np\n'), ((1783, 1838), 'numpy.array', 'np.array', (["['d', 'a', 'c', 'b', 'c', 'b', 'd', 'a', 'e']"], {}), "(['d', 'a', 'c', 'b', 'c', 'b', 'd', 'a', 'e'])\n", (1791, 1838), True, 'import numpy as np\n'), ((1849, 1891), 'numpy.array', 'np.array', (['[1, 10, 100, 11, 9, 12, 8, 2, 7]'], {}), '([1, 10, 100, 11, 9, 12, 8, 2, 7])\n', (1857, 1891), True, 'import numpy as np\n')]
|
import unittest, random
from models.point import Point
from models.segment import Segment
import numpy as np
class TestSegmentMethods(unittest.TestCase):
def test_new(self):
with self.assertRaises(ValueError) as context:
Segment([])
def test_extremums(self):
a = Point(random.randint(0, 100), random.randint(0, 100))
b = Point(random.randint(0, 100), random.randint(0, 100))
c = Point(random.randint(0, 100), random.randint(0, 100))
segment = Segment([a, b, c])
self.assertEqual(segment.start, a)
self.assertEqual(segment.end, c)
def test_getitem(self):
a = Point(10, 20)
b = Point(20, 30)
c = Point(30, 40)
segment = Segment([a, b, c])
self.assertEqual(segment[Point(10, 20)], a) # Access by point
self.assertEqual(segment[20, 30], b) # Access by coordinates
self.assertEqual(segment[2], c) # Access by index
self.assertEqual(segment[100, 100], None) # Accessing a missing point
def test_append(self):
a = Point(10, 20)
b = Point(20, 30)
c = Point(30, 40)
segment = Segment([a, b, c])
segment.append(Point(31, 40))
# Working case
self.assertEqual(segment.end, Point(31, 40))
# Point is too far
with self.assertRaises(ValueError) as context:
segment.append(Point(100, 100))
# Point already exists
with self.assertRaises(ValueError) as context:
segment.append(Point(31, 40))
def test_angle(self):
angle_1 = Segment([Point(0, 0), Point(10, 10)]) # Angle is 45°
angle_2 = Segment([Point(0, 0), Point(10, 20)]) # Angle is arctan(20/10)
angle_half = Segment([Point(0, 0), Point(20, 10)]) # Angle is arctan(10/20)
angle_vertical = Segment([Point(0, 0), Point(10, 0)]) # Angle is 0°
angle_horizontal = Segment([Point(0, 0), Point(0, 10)]) # Angle is 90°
self.assertAlmostEqual(angle_1.angle(radians = True), np.pi / 4)
self.assertAlmostEqual(angle_half.angle(radians = True), np.arctan(2))
self.assertAlmostEqual(angle_horizontal.angle(radians = True), 0)
self.assertAlmostEqual(angle_vertical.angle(radians = True), np.pi / 2)
self.assertAlmostEqual(angle_1.angle(radians = False), 45)
self.assertAlmostEqual(angle_half.angle(radians = False), 63, places = 0)
self.assertAlmostEqual(angle_horizontal.angle(radians = False), 0)
self.assertAlmostEqual(angle_vertical.angle(radians = False), 90)
|
[
"numpy.arctan",
"random.randint",
"models.segment.Segment",
"models.point.Point"
] |
[((509, 527), 'models.segment.Segment', 'Segment', (['[a, b, c]'], {}), '([a, b, c])\n', (516, 527), False, 'from models.segment import Segment\n'), ((654, 667), 'models.point.Point', 'Point', (['(10)', '(20)'], {}), '(10, 20)\n', (659, 667), False, 'from models.point import Point\n'), ((680, 693), 'models.point.Point', 'Point', (['(20)', '(30)'], {}), '(20, 30)\n', (685, 693), False, 'from models.point import Point\n'), ((706, 719), 'models.point.Point', 'Point', (['(30)', '(40)'], {}), '(30, 40)\n', (711, 719), False, 'from models.point import Point\n'), ((739, 757), 'models.segment.Segment', 'Segment', (['[a, b, c]'], {}), '([a, b, c])\n', (746, 757), False, 'from models.segment import Segment\n'), ((1074, 1087), 'models.point.Point', 'Point', (['(10)', '(20)'], {}), '(10, 20)\n', (1079, 1087), False, 'from models.point import Point\n'), ((1100, 1113), 'models.point.Point', 'Point', (['(20)', '(30)'], {}), '(20, 30)\n', (1105, 1113), False, 'from models.point import Point\n'), ((1126, 1139), 'models.point.Point', 'Point', (['(30)', '(40)'], {}), '(30, 40)\n', (1131, 1139), False, 'from models.point import Point\n'), ((1159, 1177), 'models.segment.Segment', 'Segment', (['[a, b, c]'], {}), '([a, b, c])\n', (1166, 1177), False, 'from models.segment import Segment\n'), ((249, 260), 'models.segment.Segment', 'Segment', (['[]'], {}), '([])\n', (256, 260), False, 'from models.segment import Segment\n'), ((310, 332), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (324, 332), False, 'import unittest, random\n'), ((334, 356), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (348, 356), False, 'import unittest, random\n'), ((376, 398), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (390, 398), False, 'import unittest, random\n'), ((400, 422), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (414, 422), False, 'import unittest, random\n'), ((442, 464), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (456, 464), False, 'import unittest, random\n'), ((466, 488), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (480, 488), False, 'import unittest, random\n'), ((1202, 1215), 'models.point.Point', 'Point', (['(31)', '(40)'], {}), '(31, 40)\n', (1207, 1215), False, 'from models.point import Point\n'), ((1279, 1292), 'models.point.Point', 'Point', (['(31)', '(40)'], {}), '(31, 40)\n', (1284, 1292), False, 'from models.point import Point\n'), ((2123, 2135), 'numpy.arctan', 'np.arctan', (['(2)'], {}), '(2)\n', (2132, 2135), True, 'import numpy as np\n'), ((792, 805), 'models.point.Point', 'Point', (['(10)', '(20)'], {}), '(10, 20)\n', (797, 805), False, 'from models.point import Point\n'), ((1412, 1427), 'models.point.Point', 'Point', (['(100)', '(100)'], {}), '(100, 100)\n', (1417, 1427), False, 'from models.point import Point\n'), ((1551, 1564), 'models.point.Point', 'Point', (['(31)', '(40)'], {}), '(31, 40)\n', (1556, 1564), False, 'from models.point import Point\n'), ((1620, 1631), 'models.point.Point', 'Point', (['(0)', '(0)'], {}), '(0, 0)\n', (1625, 1631), False, 'from models.point import Point\n'), ((1633, 1646), 'models.point.Point', 'Point', (['(10)', '(10)'], {}), '(10, 10)\n', (1638, 1646), False, 'from models.point import Point\n'), ((1691, 1702), 'models.point.Point', 'Point', (['(0)', '(0)'], {}), '(0, 0)\n', (1696, 1702), False, 'from models.point import Point\n'), ((1704, 1717), 'models.point.Point', 'Point', (['(10)', '(20)'], {}), '(10, 20)\n', (1709, 1717), False, 'from models.point import Point\n'), ((1775, 1786), 'models.point.Point', 'Point', (['(0)', '(0)'], {}), '(0, 0)\n', (1780, 1786), False, 'from models.point import Point\n'), ((1788, 1801), 'models.point.Point', 'Point', (['(20)', '(10)'], {}), '(20, 10)\n', (1793, 1801), False, 'from models.point import Point\n'), ((1863, 1874), 'models.point.Point', 'Point', (['(0)', '(0)'], {}), '(0, 0)\n', (1868, 1874), False, 'from models.point import Point\n'), ((1876, 1888), 'models.point.Point', 'Point', (['(10)', '(0)'], {}), '(10, 0)\n', (1881, 1888), False, 'from models.point import Point\n'), ((1941, 1952), 'models.point.Point', 'Point', (['(0)', '(0)'], {}), '(0, 0)\n', (1946, 1952), False, 'from models.point import Point\n'), ((1954, 1966), 'models.point.Point', 'Point', (['(0)', '(10)'], {}), '(0, 10)\n', (1959, 1966), False, 'from models.point import Point\n')]
|
# -*- coding: utf-8 -*-
# Copyright 2018 <NAME>
# Distributed under the terms of the Apache License 2.0
"""
Test Aerial Objects
#####################
"""
import six
import json
import uuid
import numpy as np
from itertools import cycle
from dronedirector.aerial import AerialObject, Drone, SinusoidalDrone
class CaliRedwood(AerialObject):
"""Example of subclassing."""
def __init__(self):
super(CaliRedwood, self).__init__(altitude=cycle([100.0]),
latitude=cycle([37.8716]),
longitude=cycle([-122.2727]))
def test_simple_aerial():
"""Test making a simple object on-the-fly."""
tree = AerialObject(altitude=cycle([100.0]),
latitude=cycle([37.8716]),
longitude=cycle([-122.2727]))
msg = tree.message()
assert isinstance(msg, six.string_types)
assert isinstance(json.loads(msg), dict)
def test_subclassing_ao():
"""Test subclassing :class:`~dronedirector.aerial.AerialObject`."""
tree = CaliRedwood()
msg = json.loads(tree.message()) # Tests for valid json
assert isinstance(msg, dict)
assert np.isclose(msg['altitude'], 100.0)
def test_drone():
"""Test basic drone creation."""
uid = uuid.uuid4()
drone = Drone(cycle([1000.0]), cycle([41.0]), region="New York", uid=uid,
longitude=cycle(np.sin(np.arange(0, 2*np.pi, np.pi/360))))
assert drone.region == "New York"
assert drone.uid == uid
msg = json.loads(drone.message())
assert len(msg) == 6
|
[
"uuid.uuid4",
"json.loads",
"numpy.isclose",
"numpy.arange",
"itertools.cycle"
] |
[((1186, 1220), 'numpy.isclose', 'np.isclose', (["msg['altitude']", '(100.0)'], {}), "(msg['altitude'], 100.0)\n", (1196, 1220), True, 'import numpy as np\n'), ((1288, 1300), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (1298, 1300), False, 'import uuid\n'), ((930, 945), 'json.loads', 'json.loads', (['msg'], {}), '(msg)\n', (940, 945), False, 'import json\n'), ((1319, 1334), 'itertools.cycle', 'cycle', (['[1000.0]'], {}), '([1000.0])\n', (1324, 1334), False, 'from itertools import cycle\n'), ((1336, 1349), 'itertools.cycle', 'cycle', (['[41.0]'], {}), '([41.0])\n', (1341, 1349), False, 'from itertools import cycle\n'), ((717, 731), 'itertools.cycle', 'cycle', (['[100.0]'], {}), '([100.0])\n', (722, 731), False, 'from itertools import cycle\n'), ((766, 782), 'itertools.cycle', 'cycle', (['[37.8716]'], {}), '([37.8716])\n', (771, 782), False, 'from itertools import cycle\n'), ((818, 836), 'itertools.cycle', 'cycle', (['[-122.2727]'], {}), '([-122.2727])\n', (823, 836), False, 'from itertools import cycle\n'), ((450, 464), 'itertools.cycle', 'cycle', (['[100.0]'], {}), '([100.0])\n', (455, 464), False, 'from itertools import cycle\n'), ((517, 533), 'itertools.cycle', 'cycle', (['[37.8716]'], {}), '([37.8716])\n', (522, 533), False, 'from itertools import cycle\n'), ((587, 605), 'itertools.cycle', 'cycle', (['[-122.2727]'], {}), '([-122.2727])\n', (592, 605), False, 'from itertools import cycle\n'), ((1420, 1456), 'numpy.arange', 'np.arange', (['(0)', '(2 * np.pi)', '(np.pi / 360)'], {}), '(0, 2 * np.pi, np.pi / 360)\n', (1429, 1456), True, 'import numpy as np\n')]
|
import os
import cv2
import time
import imutils
import pyrebase
import numpy as np
from utils import *
import sys
import dlib
from skimage import io
#################### Initialize ####################
print("Start initializing")
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
emotion_dict = {0: "Angry", 1: "Disgusted", 2: "Fearful",
3: "Happy", 4: "Neutral", 5: "Sad", 6: "Surprised"}
firebase = init_firebase()
storage = firebase.storage()
db = firebase.database()
model, facecasc = init_model()
history_list = []
loop = 0
predictor_path = "./shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
reset_counter = 0
#################### Initialize ####################
print("Start looping")
data = {'cur_emotion': "None"}
db.child("CUR_EMOTION").set(data)
while(1):
print("Loop ======================================================================", loop)
files = storage.list_files()
reset_counter += 1
for file in files:
if (file.name)[0] == "s" and file.name != "screenShot/":
if file.name not in history_list:
reset_counter = 0
history_list.append(file.name)
img_local_name = "imgs/" + os.path.basename(file.name) + ".png"
print(img_local_name)
storage.child(file.name).download(img_local_name)
gray_img = cv2.imread(
img_local_name, cv2.IMREAD_GRAYSCALE)
img = cv2.imread(img_local_name)
dets = detector(img, 1)
vec = np.empty([68, 2], dtype=int)
status = "Not Sleeping"
for k, d in enumerate(dets):
shape = predictor(img, d)
for b in range(68):
vec[b][0] = shape.part(b).x
vec[b][1] = shape.part(b).y
right_ear = compute_EAR(vec[42:48])
left_ear = compute_EAR(vec[36:42])
if (right_ear+left_ear)/2 < 0.2:
status = "sleeping"
print(status)
faces = facecasc.detectMultiScale(
gray_img, scaleFactor=1.3, minNeighbors=5)
for (x, y, w, h) in faces:
print("Detect Face")
roi_gray = gray_img[y:y + h, x:x + w]
cropped_img = np.expand_dims(np.expand_dims(
cv2.resize(roi_gray, (48, 48)), -1), 0)
prediction = model.predict(cropped_img)
maxindex = int(np.argmax(prediction))
if maxindex == 0 or maxindex == 1 or maxindex == 2 or maxindex == 4:
maxindex = 5
print(emotion_dict[maxindex])
if status == "sleeping":
data = {'cur_emotion': "sleeping"}
else:
data = {'cur_emotion': emotion_dict[maxindex]}
db.child("CUR_EMOTION").set(data)
if reset_counter >= 100:
reset_counter = 0
data = {'cur_emotion': "None"}
db.child("CUR_EMOTION").set(data)
loop += 1
# time.sleep(1))
|
[
"os.path.basename",
"numpy.argmax",
"numpy.empty",
"cv2.imread",
"dlib.get_frontal_face_detector",
"dlib.shape_predictor",
"cv2.resize"
] |
[((616, 648), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (646, 648), False, 'import dlib\n'), ((661, 697), 'dlib.shape_predictor', 'dlib.shape_predictor', (['predictor_path'], {}), '(predictor_path)\n', (681, 697), False, 'import dlib\n'), ((1460, 1508), 'cv2.imread', 'cv2.imread', (['img_local_name', 'cv2.IMREAD_GRAYSCALE'], {}), '(img_local_name, cv2.IMREAD_GRAYSCALE)\n', (1470, 1508), False, 'import cv2\n'), ((1552, 1578), 'cv2.imread', 'cv2.imread', (['img_local_name'], {}), '(img_local_name)\n', (1562, 1578), False, 'import cv2\n'), ((1642, 1670), 'numpy.empty', 'np.empty', (['[68, 2]'], {'dtype': 'int'}), '([68, 2], dtype=int)\n', (1650, 1670), True, 'import numpy as np\n'), ((1289, 1316), 'os.path.basename', 'os.path.basename', (['file.name'], {}), '(file.name)\n', (1305, 1316), False, 'import os\n'), ((2678, 2699), 'numpy.argmax', 'np.argmax', (['prediction'], {}), '(prediction)\n', (2687, 2699), True, 'import numpy as np\n'), ((2542, 2572), 'cv2.resize', 'cv2.resize', (['roi_gray', '(48, 48)'], {}), '(roi_gray, (48, 48))\n', (2552, 2572), False, 'import cv2\n')]
|
# laser_path_utils.py
"""Utility functions for working with paths for laser cutting"""
import numpy as np
import svgpathtools.svgpathtools as SVGPT
# it's imporatant to clone and install the repo manually. The pip/pypi version is outdated
from laser_svg_utils import tree_to_tempfile
from laser_clipper import point_on_loops, point_inside_loop
def tempfile_to_paths(temp_svg):
"""open temp SVG file and return a path"""
# temp_svg.seek(0)
paths, attributes = SVGPT.svg2paths(temp_svg.name)
temp_svg.close()
return (paths, attributes)
def tree_to_paths(tree):
"""turns an svg tree into paths list"""
temp_svg = tree_to_tempfile(tree)
paths, _ = tempfile_to_paths(temp_svg)
svg_paths = []
for path in paths:
if not path:
svg_paths.append(path.d())
return svg_paths
def paths_to_loops(paths):
""""Convert a list of paths to a list of points"""
point_loop_list = []
for path_string in paths:
points = path_string_to_points(path_string)
if points is not None:
point_loop_list.append(points)
return point_loop_list
def combine_paths(paths, as_list=True):
"""combines path strings into a single string"""
combined = ""
first = True
for path in paths:
if not first:
combined += " "
combined += path
first = False
if as_list:
return [combined]
else:
return combined
def path_string_to_points(path_string):
"""Convert path string into a list of points"""
path = SVGPT.parse_path(path_string)
empty = SVGPT.Path()
if path == empty:
return None
points = []
for segment in path:
segment_points = subpath_to_points(segment)
for point in segment_points:
if points == [] or point != points[-1]:
points.append(point)
return points
def subpath_to_points(segment):
"""Converts a path segment into a list of points"""
points = []
if isinstance(segment, SVGPT.path.Line): # pylint: disable=maybe-no-member
points = points_from_line(segment)
else:
points = points_from_curve(segment)
return points
def get_start(path_string):
"""returns start point (x, y) of a path string"""
path = SVGPT.parse_path(path_string)
start_xy = complex_to_xy(path.start)
return start_xy
def points_from_line(line):
"""returns endpoints of line"""
points_list = []
start = line.point(0)
end = line.point(1)
points_list.append(complex_to_xy(start))
points_list.append(complex_to_xy(end))
return points_list
def points_from_curve(curve, samples=20):
"""returns poins along a curve"""
points_list = []
for location in range(samples):
fraction = location / (samples-1)
point_on_curve = curve.point(fraction)
points_list.append(complex_to_xy(point_on_curve))
return points_list
def complex_to_xy(complex_point):
"""turns complex point (x+yj) into cartesian point [x,y]"""
xy_point = [complex_point.real, complex_point.imag]
return xy_point
def xy_to_complex(xy_point):
"""turns cartesian point [x,y] into complex point (x+yj)"""
complex_point = xy_point[0] + xy_point[1] * 1j
return complex_point
def loops_to_paths(loops):
"""turns a list of point loops into a list of path strings"""
paths = []
for loop in loops:
path = points_to_path(loop)
paths.append(path)
return paths
def points_to_path(points, closed=True):
"""turn a series of points into a path"""
first = True
data = "M "
for point in points:
if not first:
data += " L "
data += f"{point[0]},{point[1]}"
first = False
if closed:
data += " Z"
return data
def scale_path(path_string, scale):
"""scales a path string by a scale factor (float)"""
path = SVGPT.parse_path(path_string)
scaled_path = path.scaled(scale)
new_path_string = scaled_path.d()
return new_path_string
def move_path(path_string, xy_translation):
"""Takes a path string and xy_translation (x, y), and moves it x units over, and y units down"""
path = SVGPT.parse_path(path_string)
empty = SVGPT.Path()
if path == empty:
return ""
complex_translation = xy_to_complex(xy_translation)
translated_path = path.translated(complex_translation)
translated_string = translated_path.d()
return translated_string
def get_angle(path_string):
"""measures the angle in degrees (CCW) from the path positive X axis (0,0), (0,1)"""
path = SVGPT.parse_path(path_string)
vector = path.point(1) - path.point(0)
angle = np.angle(vector, deg=True)
return angle
def rotate_path(path_string, angle_degrees, xy_point):
"""rotates a path string a given number of degrees (CCW) around point (x, y)"""
path = SVGPT.parse_path(path_string)
empty = SVGPT.Path()
if path == empty:
return ""
complex_point = xy_to_complex(xy_point)
rotated_path = path.rotated(angle_degrees, origin=complex_point)
rotated_string = rotated_path.d()
return rotated_string
def get_length(path_string):
"""returns the length of a path string"""
path = SVGPT.parse_path(path_string)
return path.length()
def get_all_segments(loops):
"""returns all of the segments from all of the loops"""
all_segments = []
for loop in loops:
loop_segments = get_loop_segments(loop)
all_segments = all_segments + loop_segments
return all_segments
def segments_overlap(first, second):
"""returns true if segments share more than a single point"""
first_path_string = points_to_path(first, closed=False)
second_path_string = points_to_path(second, closed=False)
first_path = SVGPT.parse_path(first_path_string)[0]
second_path = SVGPT.parse_path(second_path_string)[0]
overlaps = []
for point in first:
complex_point = xy_to_complex(point)
place_on_path = second_path.point_to_t(complex_point)
if place_on_path is not None:
if point not in overlaps:
overlaps.append(point)
for point in second:
complex_point = xy_to_complex(point)
place_on_path = first_path.point_to_t(complex_point)
if place_on_path is not None:
if point not in overlaps:
overlaps.append(point)
overlap = len(overlaps) >= 2
return overlap
def get_loop_segments(loop):
"""returns a list of segments in a loop"""
segments = []
last_point = None
for this_point in loop:
if last_point is not None:
new_segment = [last_point, this_point]
segments.append(new_segment)
last_point = this_point
return segments
def segments_to_paths(segments):
"""converts list of segments into list of paths"""
paths = []
for segment in segments:
new_path = points_to_path(segment, closed=False)
paths.append(new_path)
return paths
def get_not_overlapping(first, second):
"""returns the segments of the first path that do not overlap with the second."""
output_paths = []
first_loops = paths_to_loops(first)
second_loops = paths_to_loops(second)
for loop in first_loops:
not_overlapping = ""
segment_started = False
last_point = loop[-1]
for point in loop:
if not point_on_loops(point, second_loops):
if not segment_started:
not_overlapping += f" M {last_point[0]},{last_point[1]}"
segment_started = True
if last_point != point:
not_overlapping += f" L {point[0]},{point[1]}"
else: # close the path
if segment_started:
not_overlapping += f" L {point[0]},{point[1]}"
output_paths.append(not_overlapping)
segment_started = False
not_overlapping = ""
last_point = point
if segment_started:
output_paths.append(not_overlapping)
return output_paths
def get_overlapping(first, second):
"""returns the overlapping segments of the first and second path."""
output_paths = []
first_loops = paths_to_loops(first)
second_loops = paths_to_loops(second)
for loop in first_loops:
overlapping = ""
segment_started = False
for point in loop:
if point_on_loops(point, second_loops):
if not segment_started:
overlapping += f" M {point[0]},{point[1]}"
segment_started = True
else:
overlapping += f" L {point[0]},{point[1]}"
else: # skip other points
if segment_started:
output_paths.append(overlapping)
overlapping = ""
segment_started = False
if segment_started:
output_paths.append(overlapping)
return output_paths
def divide_pathstring_parts(pathstring):
"""breaks single path string into substrings at each 'M' returning a list of path strings"""
substring = pathstring.strip()
paths = []
while 'M' in substring[1:]:
m_index = substring.find('M', 1)
if m_index > -1:
subpath = substring[0:m_index].strip()
paths.append(subpath)
substring = substring[m_index:].strip()
paths.append(substring)
return paths
# TODO: split open/closed separation into smaller chunks
def separate_closed_paths(paths):
"""takes a list of path strings
breaks non continuous paths and
joins connecting paths together
to return a list of closed paths """
discrete_paths = []
closed_paths = []
open_paths = []
dead_ends = []
for path in paths:
discrete_paths += divide_pathstring_parts(path)
for path in discrete_paths:
parsed_path = SVGPT.parse_path(path)
if parsed_path.isclosed():
closed_paths.append(path)
else:
open_paths.append(parsed_path)
while open_paths:
path = open_paths.pop()
new_path = None
for other_path in open_paths:
if path.end == other_path.start:
new_path = path.d() + " " + other_path.d().replace('M', 'L')
open_paths.remove(other_path)
break
elif path.start == other_path.end:
new_path = other_path.d() + " " + path.d().replace('M', 'L')
open_paths.remove(other_path)
break
elif path.end == other_path.end:
new_path = path.d() + " " + other_path.reversed().d().replace('M', 'L')
open_paths.remove(other_path)
break
elif path.start == other_path.start:
new_path = path.reversed().d() + " " + other_path.d().replace('M', 'L')
open_paths.remove(other_path)
break
if new_path is not None:
parsed_new_path = SVGPT.parse_path(new_path)
if parsed_new_path.isclosed():
closed_paths.append(new_path)
else:
open_paths.append(parsed_new_path)
else:
dead_ends.append(path.d())
open_paths = dead_ends
return closed_paths, open_paths
def is_inside(path, other_path):
"""checks if path is inside other_path and returns true or false"""
loop = paths_to_loops([path])[0]
other_loop = paths_to_loops([other_path])[0]
for point in loop:
if point_inside_loop(point, other_loop) == 1:
return True
return False
def path_to_segments(path_string):
"""breaks down a path into a list of segments"""
segments = []
path = SVGPT.parse_path(path_string)
for segment in path:
if isinstance(segment, SVGPT.path.Line): # pylint: disable=maybe-no-member
points = points_from_line(segment)
new_path_string = f"M {points[0][0]} {points[0][1]} L {points[1][0]} {points[1][1]}"
segments.append(new_path_string)
return segments
|
[
"svgpathtools.svgpathtools.svg2paths",
"numpy.angle",
"svgpathtools.svgpathtools.parse_path",
"laser_svg_utils.tree_to_tempfile",
"laser_clipper.point_on_loops",
"laser_clipper.point_inside_loop",
"svgpathtools.svgpathtools.Path"
] |
[((476, 506), 'svgpathtools.svgpathtools.svg2paths', 'SVGPT.svg2paths', (['temp_svg.name'], {}), '(temp_svg.name)\n', (491, 506), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((645, 667), 'laser_svg_utils.tree_to_tempfile', 'tree_to_tempfile', (['tree'], {}), '(tree)\n', (661, 667), False, 'from laser_svg_utils import tree_to_tempfile\n'), ((1558, 1587), 'svgpathtools.svgpathtools.parse_path', 'SVGPT.parse_path', (['path_string'], {}), '(path_string)\n', (1574, 1587), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((1601, 1613), 'svgpathtools.svgpathtools.Path', 'SVGPT.Path', ([], {}), '()\n', (1611, 1613), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((2289, 2318), 'svgpathtools.svgpathtools.parse_path', 'SVGPT.parse_path', (['path_string'], {}), '(path_string)\n', (2305, 2318), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((3913, 3942), 'svgpathtools.svgpathtools.parse_path', 'SVGPT.parse_path', (['path_string'], {}), '(path_string)\n', (3929, 3942), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((4204, 4233), 'svgpathtools.svgpathtools.parse_path', 'SVGPT.parse_path', (['path_string'], {}), '(path_string)\n', (4220, 4233), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((4247, 4259), 'svgpathtools.svgpathtools.Path', 'SVGPT.Path', ([], {}), '()\n', (4257, 4259), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((4619, 4648), 'svgpathtools.svgpathtools.parse_path', 'SVGPT.parse_path', (['path_string'], {}), '(path_string)\n', (4635, 4648), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((4704, 4730), 'numpy.angle', 'np.angle', (['vector'], {'deg': '(True)'}), '(vector, deg=True)\n', (4712, 4730), True, 'import numpy as np\n'), ((4900, 4929), 'svgpathtools.svgpathtools.parse_path', 'SVGPT.parse_path', (['path_string'], {}), '(path_string)\n', (4916, 4929), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((4943, 4955), 'svgpathtools.svgpathtools.Path', 'SVGPT.Path', ([], {}), '()\n', (4953, 4955), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((5262, 5291), 'svgpathtools.svgpathtools.parse_path', 'SVGPT.parse_path', (['path_string'], {}), '(path_string)\n', (5278, 5291), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((11861, 11890), 'svgpathtools.svgpathtools.parse_path', 'SVGPT.parse_path', (['path_string'], {}), '(path_string)\n', (11877, 11890), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((5821, 5856), 'svgpathtools.svgpathtools.parse_path', 'SVGPT.parse_path', (['first_path_string'], {}), '(first_path_string)\n', (5837, 5856), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((5878, 5914), 'svgpathtools.svgpathtools.parse_path', 'SVGPT.parse_path', (['second_path_string'], {}), '(second_path_string)\n', (5894, 5914), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((10009, 10031), 'svgpathtools.svgpathtools.parse_path', 'SVGPT.parse_path', (['path'], {}), '(path)\n', (10025, 10031), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((8505, 8540), 'laser_clipper.point_on_loops', 'point_on_loops', (['point', 'second_loops'], {}), '(point, second_loops)\n', (8519, 8540), False, 'from laser_clipper import point_on_loops, point_inside_loop\n'), ((11129, 11155), 'svgpathtools.svgpathtools.parse_path', 'SVGPT.parse_path', (['new_path'], {}), '(new_path)\n', (11145, 11155), True, 'import svgpathtools.svgpathtools as SVGPT\n'), ((11658, 11694), 'laser_clipper.point_inside_loop', 'point_inside_loop', (['point', 'other_loop'], {}), '(point, other_loop)\n', (11675, 11694), False, 'from laser_clipper import point_on_loops, point_inside_loop\n'), ((7444, 7479), 'laser_clipper.point_on_loops', 'point_on_loops', (['point', 'second_loops'], {}), '(point, second_loops)\n', (7458, 7479), False, 'from laser_clipper import point_on_loops, point_inside_loop\n')]
|
from _pytest.mark import param
import pytest
import numpy as np
from bayesian_mmm.sampling.stan_model_generator import StanModelGenerator
from bayesian_mmm.sampling.sampler import Sampler
from bayesian_mmm.sampling.stan_model_wrapper import StanModelWrapper
MAX_LAG = 4
SPENDS = np.array([[10, 20], [0, 8], [1, 30], [5, 40]])
LAGGED_SPENDS = np.array([
[[10, 0, 0, 0], [20, 0, 0, 0]],
[[ 0, 10, 0, 0], [ 8, 20, 0, 0]],
[[ 1, 0, 10, 0], [30, 8, 20, 0]],
[[ 5, 1, 0, 10], [40, 30, 8, 20]]
])
CTRL_VARS = np.array([
[2, 4],
[5, 2],
[6, 4],
[7, 2]
])
REVENUE = np.array([1, 2, 3, 4])
N = 4
NUM_MEDIA = 2
NUM_CTRL = 2
STAN_MODEL = StanModelWrapper
@pytest.mark.parametrize(
"ctrl_vars", [CTRL_VARS, None]
)
def test_create_sampler_input(ctrl_vars):
if type(ctrl_vars) == np.ndarray:
expected_args = {
"N":N,
"Y":REVENUE,
"max_lag":MAX_LAG,
"num_media":NUM_MEDIA,
"X_media":LAGGED_SPENDS,
"num_ctrl":NUM_CTRL,
"X_ctrl":CTRL_VARS
}
else:
expected_args = {
"N":N,
"Y":REVENUE,
"max_lag":MAX_LAG,
"num_media":NUM_MEDIA,
"X_media":LAGGED_SPENDS
}
sampler = Sampler(STAN_MODEL, MAX_LAG)
sampler.create_stan_input(
SPENDS, ctrl_vars, REVENUE
)
obtained_args = sampler._Sampler__args
expected_args_keys = list(expected_args.keys())
expected_args_keys.sort()
obtained_args_keys = list(obtained_args.keys())
obtained_args_keys.sort()
assert obtained_args_keys == expected_args_keys
for key, val in expected_args.items():
if type(val) == np.ndarray:
assert (val == obtained_args[key]).all()
else:
assert val == obtained_args[key]
# slow to run (stan compilation + sampling)
@pytest.mark.parametrize(
"carryover_transfo_nm,diminushing_returns_transfo_nm,with_ctrl_vars",
[
("adstock","hill",True),
("adstock","hill",False),
("adstock","reach",True),
("adstock","reach",False),
("geo_decay","hill",True),
("geo_decay","hill",False),
("geo_decay","reach",True),
("geo_decay","reach",False)
]
)
def test_run_sampling(
carryover_transfo_nm,
diminushing_returns_transfo_nm,
with_ctrl_vars
):
CARRYOVER_TRANSFO_NM_TO_PARAM_NM = {
"geo_decay":["retain_rate"],
"adstock":["retain_rate", "delay"]
}
DIMINUSHING_RETURNS_TRANSFO_NM_TO_PARAM_NM = {
"hill":["ec", "slope"],
"reach":["half_saturation"]
}
WITH_CTRL_VARS_TO_PARAM_NM = {
True:["gamma_ctrl"],
False:[]
}
stan_model_generator = StanModelGenerator(
carryover_transfo_nm,
diminushing_returns_transfo_nm,
with_ctrl_vars
)
stan_model_generator.create_model()
stan_model = stan_model_generator.get_model()
sampler = Sampler(stan_model, MAX_LAG)
if with_ctrl_vars:
ctrl_vars = CTRL_VARS
else:
ctrl_vars = None
sampler.create_stan_input(
SPENDS,
ctrl_vars,
REVENUE
)
obtained_results = sampler.run_sampling(100, 3)
expected_param_nms = (
CARRYOVER_TRANSFO_NM_TO_PARAM_NM[carryover_transfo_nm]
+ DIMINUSHING_RETURNS_TRANSFO_NM_TO_PARAM_NM[diminushing_returns_transfo_nm]
+ WITH_CTRL_VARS_TO_PARAM_NM[with_ctrl_vars]
+ ["beta_medias", "tau"]
)
expected_param_nms.sort()
obtained_params_nms = list(obtained_results.keys())
obtained_params_nms.sort()
assert expected_param_nms == obtained_params_nms
for param_nm, values in obtained_results.items():
if param_nm != "tau":
assert values.shape == (100,2)
else:
assert values.shape == (100,)
|
[
"bayesian_mmm.sampling.stan_model_generator.StanModelGenerator",
"pytest.mark.parametrize",
"numpy.array",
"bayesian_mmm.sampling.sampler.Sampler"
] |
[((281, 327), 'numpy.array', 'np.array', (['[[10, 20], [0, 8], [1, 30], [5, 40]]'], {}), '([[10, 20], [0, 8], [1, 30], [5, 40]])\n', (289, 327), True, 'import numpy as np\n'), ((344, 490), 'numpy.array', 'np.array', (['[[[10, 0, 0, 0], [20, 0, 0, 0]], [[0, 10, 0, 0], [8, 20, 0, 0]], [[1, 0, 10,\n 0], [30, 8, 20, 0]], [[5, 1, 0, 10], [40, 30, 8, 20]]]'], {}), '([[[10, 0, 0, 0], [20, 0, 0, 0]], [[0, 10, 0, 0], [8, 20, 0, 0]], [\n [1, 0, 10, 0], [30, 8, 20, 0]], [[5, 1, 0, 10], [40, 30, 8, 20]]])\n', (352, 490), True, 'import numpy as np\n'), ((525, 567), 'numpy.array', 'np.array', (['[[2, 4], [5, 2], [6, 4], [7, 2]]'], {}), '([[2, 4], [5, 2], [6, 4], [7, 2]])\n', (533, 567), True, 'import numpy as np\n'), ((596, 618), 'numpy.array', 'np.array', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (604, 618), True, 'import numpy as np\n'), ((687, 742), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ctrl_vars"""', '[CTRL_VARS, None]'], {}), "('ctrl_vars', [CTRL_VARS, None])\n", (710, 742), False, 'import pytest\n'), ((1886, 2237), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""carryover_transfo_nm,diminushing_returns_transfo_nm,with_ctrl_vars"""', "[('adstock', 'hill', True), ('adstock', 'hill', False), ('adstock', 'reach',\n True), ('adstock', 'reach', False), ('geo_decay', 'hill', True), (\n 'geo_decay', 'hill', False), ('geo_decay', 'reach', True), ('geo_decay',\n 'reach', False)]"], {}), "(\n 'carryover_transfo_nm,diminushing_returns_transfo_nm,with_ctrl_vars', [\n ('adstock', 'hill', True), ('adstock', 'hill', False), ('adstock',\n 'reach', True), ('adstock', 'reach', False), ('geo_decay', 'hill', True\n ), ('geo_decay', 'hill', False), ('geo_decay', 'reach', True), (\n 'geo_decay', 'reach', False)])\n", (1909, 2237), False, 'import pytest\n'), ((1285, 1313), 'bayesian_mmm.sampling.sampler.Sampler', 'Sampler', (['STAN_MODEL', 'MAX_LAG'], {}), '(STAN_MODEL, MAX_LAG)\n', (1292, 1313), False, 'from bayesian_mmm.sampling.sampler import Sampler\n'), ((2756, 2848), 'bayesian_mmm.sampling.stan_model_generator.StanModelGenerator', 'StanModelGenerator', (['carryover_transfo_nm', 'diminushing_returns_transfo_nm', 'with_ctrl_vars'], {}), '(carryover_transfo_nm, diminushing_returns_transfo_nm,\n with_ctrl_vars)\n', (2774, 2848), False, 'from bayesian_mmm.sampling.stan_model_generator import StanModelGenerator\n'), ((2980, 3008), 'bayesian_mmm.sampling.sampler.Sampler', 'Sampler', (['stan_model', 'MAX_LAG'], {}), '(stan_model, MAX_LAG)\n', (2987, 3008), False, 'from bayesian_mmm.sampling.sampler import Sampler\n')]
|
# Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMomentsDistance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class TestMoments(TestCase):
def setUp(self):
self.dataset1 = dataset1
self.dataset2 = dataset2
def test_moments(self):
self.tester = StatMoments(dataset1["integrated_intensity"][0], 5)
self.tester.run()
assert np.allclose(self.tester.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(self.tester.skewness_hist[1],
computed_data['skewness_val'])
def test_moment_distance(self):
self.tester_dist = \
StatMomentsDistance(dataset1["integrated_intensity"][0],
dataset2["integrated_intensity"][0], 5)
self.tester_dist.distance_metric()
npt.assert_almost_equal(self.tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(self.tester_dist.skewness_distance,
computed_distances['skewness_distance'])
|
[
"numpy.testing.assert_almost_equal",
"numpy.allclose"
] |
[((584, 656), 'numpy.allclose', 'np.allclose', (['self.tester.kurtosis_hist[1]', "computed_data['kurtosis_val']"], {}), "(self.tester.kurtosis_hist[1], computed_data['kurtosis_val'])\n", (595, 656), True, 'import numpy as np\n'), ((699, 771), 'numpy.allclose', 'np.allclose', (['self.tester.skewness_hist[1]', "computed_data['skewness_val']"], {}), "(self.tester.skewness_hist[1], computed_data['skewness_val'])\n", (710, 771), True, 'import numpy as np\n'), ((1057, 1161), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['self.tester_dist.kurtosis_distance', "computed_distances['kurtosis_distance']"], {}), "(self.tester_dist.kurtosis_distance,\n computed_distances['kurtosis_distance'])\n", (1080, 1161), True, 'import numpy.testing as npt\n'), ((1198, 1302), 'numpy.testing.assert_almost_equal', 'npt.assert_almost_equal', (['self.tester_dist.skewness_distance', "computed_distances['skewness_distance']"], {}), "(self.tester_dist.skewness_distance,\n computed_distances['skewness_distance'])\n", (1221, 1302), True, 'import numpy.testing as npt\n')]
|
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Block Scheduling Policy Simulation
#
# context: [build model of computron\-to\-wallclock relationship · Issue \#3459 · Agoric/agoric\-sdk](https://github.com/Agoric/agoric-sdk/issues/3459)
# ## Preface: PyData
import pandas as pd
import numpy as np
dict(pandas=pd.__version__,
numpy=np.__version__)
# ## MySql Access
TOP = __name__ == '__main__'
# +
import logging
from sys import stderr
logging.basicConfig(level=logging.INFO, stream=stderr,
format='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
log = logging.getLogger(__name__)
if TOP:
log.info('notebook start')
# +
from slogdata import mysql_socket, show_times
def _slog4db(database='slog4'):
from sqlalchemy import create_engine
return create_engine(mysql_socket(database, create_engine))
_db4 = _slog4db()
_db4.execute('show tables').fetchall()
# -
# ## Global compute results for agorictest-16
#
# Based on one validator, **Provalidator**.
show_times(pd.read_sql('''
select *
from slog_run
where parent = 'Provalidator'
limit 10
''', _db4), ['time_lo', 'time_hi', 'blockTime_lo', 'blockTime_hi']).iloc[0]
# +
# _db4.execute('''drop table if exists delivery_compute_16''');
# +
def build_consensus_compute(theValidator, db,
table='delivery_compute_16'):
"""We include duration from 1 validator as well.
"""
log.info('creating %s', table)
db.execute(f'''
create table if not exists {table} as
with slog1 as (
select file_id
from file_info
where parent = %(theValidator)s
)
select blockHeight, blockTime, crankNum, vatID, deliveryNum, compute, dur
from j_delivery r
cross join slog1
where r.file_id = slog1.file_id
order by crankNum
''', dict(theValidator=theValidator))
agg = pd.read_sql(f'select count(*) from {table}', db)
log.info('done:\n%s', agg)
return pd.read_sql(f'select * from {table} limit 5', db)
build_consensus_compute('Provalidator', _db4)
# -
_dc16 = pd.read_sql('select * from delivery_compute_16 order by crankNum', _db4, index_col='crankNum')
_dc16.tail()
# `crankNum` goes from 31 to 34; 32 and 33 are missing. Perhaps `create-vat` cranks?
# +
def simulate_run_policy(df, threshold=8e6):
# does 10e6 help with bank update latency?
# only a little: max ~50 rather than ~70
meter = 0
# t_in = t_out = df.blockTime[0]
block_in = block_out = df.blockHeight.values[0]
for crankNum, d in df.iterrows():
if d.blockHeight > block_in:
block_in = d.blockHeight
if block_in > block_out:
block_out = block_in
meter = 0
yield block_out # do the work
meter += d.compute
if meter > threshold:
meter = 0
block_out += 1
df = _dc16[_dc16.blockHeight > _dc16.blockHeight.min()]
_sim16 = df.assign(bkSim=list(simulate_run_policy(df)))
_sim16
# -
_sim16[_sim16.bkSim < _sim16.blockHeight]
# +
def sim_aux_stats(df):
df = _sim16
original = df.groupby('blockHeight')
df = original.apply(lambda g: g.assign(
computeInBlock=g.compute.cumsum(),
durationInBlock=g.dur.cumsum()))
df = df.reset_index(level=0, drop=True)
simulated = df.groupby('bkSim')
df = simulated.apply(lambda g: g.assign(
computeInSimBlk=g.compute.cumsum(),
durationInSimBlk=g.dur.cumsum()))
df = df.reset_index(level=0, drop=True)
return df
df = sim_aux_stats(_sim16)
# -
df[['vatID', 'deliveryNum',
'blockHeight',
'compute', 'computeInBlock', 'computeInSimBlk']].describe()
df[['computeInBlock', 'computeInSimBlk']].plot(figsize=(12, 4));
df[['vatID', 'deliveryNum',
'blockHeight',
'dur', 'durationInBlock', 'durationInSimBlk']].describe()
df[['durationInBlock', 'durationInSimBlk']].plot(figsize=(12, 6));
# ## Computrons go 3.7x faster early in agorictest-16
sim_lo = df[(df.index >= 20000) & (df.index <= 70000)]
sim_lo = sim_lo.reset_index().set_index(['blockHeight', 'crankNum'])
sim_lo = sim_lo.assign(rate=sim_lo.compute / sim_lo.dur)
sim_lo[['durationInBlock', 'durationInSimBlk']].plot(figsize=(12, 4));
sim_lo[['compute', 'computeInBlock', 'computeInSimBlk',
'dur','durationInBlock', 'durationInSimBlk', 'rate']].describe()
sim_hi = df[df.index >= 250000]
sim_hi = sim_hi.reset_index().set_index(['blockHeight', 'crankNum'])
sim_hi = sim_hi.assign(rate=sim_hi.compute / sim_hi.dur)
sim_hi[['durationInBlock', 'durationInSimBlk']].plot(figsize=(12, 4));
sim_hi[['compute', 'computeInBlock', 'computeInSimBlk',
'dur','durationInBlock', 'durationInSimBlk', 'rate']].describe()
# +
rate_lo_median = 1.738564e+06
rate_hi_median = 4.711452e+05
round(rate_lo_median / rate_hi_median, 1)
# -
# ## Latency
df['delay'] = df.bkSim - df.blockHeight
df[['delay']].describe()
df[['durationInBlock', 'durationInSimBlk', 'delay']].plot(figsize=(12, 4))
df.sort_values('delay', ascending=False).head(50)
# ## Zoom in on the X axis
103200 and 105500
# +
_zoom = df.loc[103200:105500]
_zoom = _zoom.reset_index().set_index(['blockHeight', 'crankNum'])
_zoom[['computeInBlock', 'computeInSimBlk']].plot(figsize=(12, 4), rot=-75);
# -
x = _zoom.reset_index()
g = x.groupby('bkSim')
x = pd.concat([
g[['blockHeight']].min(),
g[['compute']].sum(),
g[['dur']].sum()
])
x = x.assign(delay=x.index - x.blockHeight)
x
x[['compute', 'dur', 'delay']].plot(subplots=True, figsize=(15, 9))
_zoom[['durationInBlock', 'durationInSimBlk']].plot(figsize=(12, 4), rot=-75);
(df.bkSim - df.blockHeight).describe()
(df.bkSim - df.blockHeight).hist(figsize=(10, 5), bins=72, log=True)
# ## Elapsed time* on the X axis
#
# *estimated as cumulative crank duration
_zoom = df.loc[103273:104400].copy()
# _zoom = df
_zoom['t'] = _zoom.dur.cumsum()
_zoom.set_index('t')[['durationInBlock', 'durationInSimBlk']].plot(figsize=(12, 4), rot=-75);
# ### Detailed Data
_zoom.groupby('bkSim').apply(lambda g: g.head(10))[50:100][[
'dur', 't', 'durationInSimBlk', 'durationInBlock',
'compute', 'computeInSimBlk', 'computeInBlock',
'blockHeight', 'delay'
]]
df.loc[103200:105500][['delay']].plot()
x = pd.read_sql('''
select *
from j_delivery
where crankNum between 103200 and 105500
and file_id = 3288529541296525
''', _db4)
x
show_times(x[x.index.isin([x.index.min(), x.index.max()])])[['crankNum', 'blockHeight', 'blockTime']]
x.blockHeight.max() - x.blockHeight.min()
x.blockHeight.describe()
x[x.compute > 1000000].groupby('method')[['compute', 'dur']].aggregate(['count', 'median', 'mean'])
x = pd.read_sql('''
select *
from t_delivery
where method = 'fromBridge'
and blockHeight between 68817 and 69707
and file_id = 3288529541296525
''', _db4)
x
_db4.execute('''
create index if not exists slog_entry_bk_ix on slog_entry(blockHeight)
''');
_db4.execute('drop index if exists slog_entry_ty_ix on slog_entry');
# +
def bank_trace(db,
limit=250,
file_id=3288529541296525,
bk_lo=68817,
bk_hi=69707):
df = pd.read_sql(
'''
with d as (
select file_id, run_line_lo
, line
, blockHeight
, blockTime
, time
, crankNum
, cast(substr(json_unquote(json_extract(record, '$.vatID')), 2) as int) vatID
, coalesce(cast(json_extract(record, '$.deliveryNum') as int), -1) deliveryNum
, json_extract(record, '$.kd') kd
from slog_entry e
where blockHeight between %(bk_lo)s and %(bk_hi)s
and file_id = %(file_id)s
and type = 'deliver'
limit %(limit)s
),
detail as (
select d.*
, json_unquote(json_extract(d.kd, '$[0]')) tag
, json_unquote(json_extract(d.kd, '$[1]')) target
, json_unquote(json_extract(d.kd, '$[2].method')) method
, json_length(json_unquote(json_extract(d.kd, '$[2].args.body')), '$[1].updated') updated
from d
)
select blockHeight, blockTime, crankNum, vatID, deliveryNum
, tag
, case when tag = 'message' then target else null end target
, method, updated
, time
-- validator-specific: file_id, run_line_lo, line, time
from detail
-- where method = 'fromBridge'
order by blockHeight, crankNum
''', db, params=dict(limit=limit, file_id=file_id, bk_lo=bk_lo, bk_hi=bk_hi))
return df
# x1 = bank_trace(_db4, bk_hi=68817 + 100)
# x2 = bank_trace(_db4, bk_lo=69707 - 100)
# x = pd.concat([x1, x2])
x = bank_trace(_db4, limit=1000)
show_times(x)
# -
x.updated.describe()
x1 = x[~x.updated.isnull()]
color = np.where(x1.vatID == 1, 'blue', 'red')
show_times(x1).plot.scatter(x='time', y='updated', color=color,
figsize=(10, 4), alpha=0.45,
title='Accounts Updated per delivery');
# +
import json
def notifer_traffic(df):
kd = df.record.apply(lambda txt: json.loads(txt)['kd'])
dt = kd.apply(lambda k: k[0])
method = kd.apply(lambda k: k[2].get('method') if k[0] == 'message' else None)
body = kd.apply(lambda k: k[2].get('args', {}).get('body') if k[0] == 'message' else None)
body = body.apply(lambda v: json.loads(v) if v else None)
updated = body.apply(lambda b: len(b[1].get('updated')) if b else None)
# time = pd.as_datetime(df.time.dt.time)
df = df.assign(dt=dt, method=method, body=body, updated=updated)
dur = df.time.diff()
return df.assign(dur=dur)
notifer_traffic(show_times(x2)).drop(columns=['file_id', 'run_line_lo', 'line', 'record', 'body'])
# -
show_times(x2)
x2.record[0]
len(x2.record[0])
# +
import json
r = json.loads(x2.record[0])
body = r['kd'][2]['args']['body']
x = json.loads(body)
# print(json.dumps(r, indent=2))
len(x[1]['updated'])
# -
x2.record[1]
x2.record[2]
|
[
"json.loads",
"logging.basicConfig",
"slogdata.show_times",
"numpy.where",
"pandas.read_sql",
"logging.getLogger",
"slogdata.mysql_socket"
] |
[((723, 860), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'stream': 'stderr', 'format': '"""%(asctime)s %(levelname)s: %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(level=logging.INFO, stream=stderr, format=\n '%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\n", (742, 860), False, 'import logging\n'), ((883, 910), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (900, 910), False, 'import logging\n'), ((2341, 2439), 'pandas.read_sql', 'pd.read_sql', (['"""select * from delivery_compute_16 order by crankNum"""', '_db4'], {'index_col': '"""crankNum"""'}), "('select * from delivery_compute_16 order by crankNum', _db4,\n index_col='crankNum')\n", (2352, 2439), True, 'import pandas as pd\n'), ((6499, 6632), 'pandas.read_sql', 'pd.read_sql', (['"""\nselect *\nfrom j_delivery\nwhere crankNum between 103200 and 105500\nand file_id = 3288529541296525\n"""', '_db4'], {}), '(\n """\nselect *\nfrom j_delivery\nwhere crankNum between 103200 and 105500\nand file_id = 3288529541296525\n"""\n , _db4)\n', (6510, 6632), True, 'import pandas as pd\n'), ((6903, 7063), 'pandas.read_sql', 'pd.read_sql', (['"""\nselect *\nfrom t_delivery\nwhere method = \'fromBridge\'\nand blockHeight between 68817 and 69707\nand file_id = 3288529541296525\n"""', '_db4'], {}), '(\n """\nselect *\nfrom t_delivery\nwhere method = \'fromBridge\'\nand blockHeight between 68817 and 69707\nand file_id = 3288529541296525\n"""\n , _db4)\n', (6914, 7063), True, 'import pandas as pd\n'), ((8925, 8938), 'slogdata.show_times', 'show_times', (['x'], {}), '(x)\n', (8935, 8938), False, 'from slogdata import mysql_socket, show_times\n'), ((9002, 9040), 'numpy.where', 'np.where', (['(x1.vatID == 1)', '"""blue"""', '"""red"""'], {}), "(x1.vatID == 1, 'blue', 'red')\n", (9010, 9040), True, 'import numpy as np\n'), ((9997, 10011), 'slogdata.show_times', 'show_times', (['x2'], {}), '(x2)\n', (10007, 10011), False, 'from slogdata import mysql_socket, show_times\n'), ((10067, 10091), 'json.loads', 'json.loads', (['x2.record[0]'], {}), '(x2.record[0])\n', (10077, 10091), False, 'import json\n'), ((10130, 10146), 'json.loads', 'json.loads', (['body'], {}), '(body)\n', (10140, 10146), False, 'import json\n'), ((2140, 2188), 'pandas.read_sql', 'pd.read_sql', (['f"""select count(*) from {table}"""', 'db'], {}), "(f'select count(*) from {table}', db)\n", (2151, 2188), True, 'import pandas as pd\n'), ((2231, 2280), 'pandas.read_sql', 'pd.read_sql', (['f"""select * from {table} limit 5"""', 'db'], {}), "(f'select * from {table} limit 5', db)\n", (2242, 2280), True, 'import pandas as pd\n'), ((1100, 1137), 'slogdata.mysql_socket', 'mysql_socket', (['database', 'create_engine'], {}), '(database, create_engine)\n', (1112, 1137), False, 'from slogdata import mysql_socket, show_times\n'), ((1306, 1404), 'pandas.read_sql', 'pd.read_sql', (['"""\nselect *\nfrom slog_run\nwhere parent = \'Provalidator\'\nlimit 10\n"""', '_db4'], {}), '(\n """\nselect *\nfrom slog_run\nwhere parent = \'Provalidator\'\nlimit 10\n""", _db4\n )\n', (1317, 1404), True, 'import pandas as pd\n'), ((9041, 9055), 'slogdata.show_times', 'show_times', (['x1'], {}), '(x1)\n', (9051, 9055), False, 'from slogdata import mysql_socket, show_times\n'), ((9909, 9923), 'slogdata.show_times', 'show_times', (['x2'], {}), '(x2)\n', (9919, 9923), False, 'from slogdata import mysql_socket, show_times\n'), ((9350, 9365), 'json.loads', 'json.loads', (['txt'], {}), '(txt)\n', (9360, 9365), False, 'import json\n'), ((9617, 9630), 'json.loads', 'json.loads', (['v'], {}), '(v)\n', (9627, 9630), False, 'import json\n')]
|
#! /usr/bin/env python3
#
# Copyright 2019 Garmin Ltd. or its subsidiaries
#
# SPDX-License-Identifier: Apache-2.0
import os
import sys
import glob
import re
from scipy import stats
import numpy
THIS_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(THIS_DIR, 'poky', 'scripts', 'lib'))
from buildstats import BuildStats, diff_buildstats, taskdiff_fields, BSVerDiff
ICECREAM_TASKS = ('do_compile', 'do_compile_kernelmodules', 'do_configure', 'do_install')
VALUES = ('cputime', 'walltime')
def sum_task_totals(bs):
d = {}
for recipe_data in bs.values():
for name, bs_task in recipe_data.tasks.items():
for val_type in VALUES:
val = getattr(bs_task, val_type)
key = (name, val_type)
if name not in ICECREAM_TASKS:
key = ('other', val_type)
d.setdefault(key, 0)
d[key] += val
key = ('overall', val_type)
d.setdefault(key, 0)
d[key] += val
return d
def get_elapsed(p):
elapsed = None
cpu = None
with open(os.path.join(p, 'build_stats'), 'r') as f:
for l in f:
m = re.match(r'Elapsed time: (?P<elapsed>[\d.]+) ', l)
if m is not None:
elapsed = float(m.group('elapsed'))
continue
m = re.match(r'CPU usage: (?P<cpu>[\d.]+)%', l)
if m is not None:
cpu = float(m.group('cpu')) / 100
if elapsed is None:
raise Exception('Elapsed time not found for %s' % p)
if cpu is None:
raise Exception('CPU usage not found for %s' % p)
return (elapsed, cpu)
def pooled_stdev(a_std_dev, b_std_dev):
return numpy.sqrt((a_std_dev**2 + b_std_dev**2)/2)
def write_elapsed():
with open(os.path.join(THIS_DIR, 'stats', 'elapsed.csv'), 'w') as f:
f.write('Build,Elapsed without Icecream,Elapsed with Icecream,CPU usage without Icecream,CPU usage with Icecream\n')
elapsed_combined_without = []
elapsed_combined_with = []
cpu_combined_without = []
cpu_combined_with = []
for p in glob.glob(os.path.join(THIS_DIR, 'stats', 'build*')):
without_elapsed, without_cpu = get_elapsed(os.path.join(p, 'without-icecream'))
with_elapsed, with_cpu = get_elapsed(os.path.join(p, 'with-icecream'))
elapsed_combined_without.append(without_elapsed)
elapsed_combined_with.append(with_elapsed)
cpu_combined_without.append(without_cpu)
cpu_combined_with.append(with_cpu)
f.write('%s,%f,%f,%f,%f\n' % (os.path.basename(p), without_elapsed, with_elapsed,
without_cpu, with_cpu))
f.write('\n')
f.write(',Average without Icecream (s),Without Icecream std dev,Average with Icecream (s),With Icecream std dev,p-value,Percent Change,Percent Change std dev\n')
average_without = numpy.average(elapsed_combined_without)
average_with = numpy.average(elapsed_combined_with)
without_std_dev = numpy.std(elapsed_combined_without)
with_std_dev = numpy.std(elapsed_combined_with)
change = (average_with - average_without) / average_without
pooled_std_dev = pooled_stdev(without_std_dev, with_std_dev) / average_without
_, p = stats.ttest_rel(elapsed_combined_without, elapsed_combined_with)
f.write('Elapsed Time,%f,%f,%f,%f,%e,%.2f,%f\n' % (
average_without, without_std_dev,
average_with, with_std_dev, p,
change, pooled_std_dev))
f.write('\n')
f.write(',Average without Icecream,Without Icecream std dev,Average with Icecream,With Icecream std dev,p-value,Delta\n')
average_without = numpy.average(cpu_combined_without)
average_with = numpy.average(cpu_combined_with)
without_std_dev = numpy.std(cpu_combined_without)
with_std_dev = numpy.std(cpu_combined_with)
delta = average_with - average_without
_, p = stats.ttest_rel(cpu_combined_without, cpu_combined_with)
f.write('CPU Usage,%f,%f,%f,%f,%e,%.2f\n' % (
average_without, without_std_dev,
average_with, with_std_dev, p,
delta))
def write_tasks():
with open(os.path.join(THIS_DIR, 'stats', 'raw.csv'), 'w') as f:
combined_with = {}
combined_without = {}
f.write('Task,Attribute,Build,Without Icecream,With Icecream\n')
for p in glob.glob(os.path.join(THIS_DIR, 'stats', 'build*')):
without_stats = BuildStats.from_dir(os.path.join(p, 'without-icecream'))
with_stats = BuildStats.from_dir(os.path.join(p, 'with-icecream'))
without_d = sum_task_totals(without_stats)
with_d = sum_task_totals(with_stats)
for k in without_d.keys():
without_val = without_d[k]
with_val = with_d[k]
f.write("%s,%s,%s,%f,%f\n" % (k[0], k[1], os.path.basename(p), without_val, with_val))
combined_with.setdefault(k, []).append(with_val)
combined_without.setdefault(k, []).append(without_val)
with open(os.path.join(THIS_DIR, 'stats', 'totals.csv'), 'w') as f:
f.write('Task,Attribute,Without Icecream,Without Std dev,With Icecream,With Std dev,p-value,Percent Change,Percent Change Std Dev\n')
for k in combined_without.keys():
without_avg = numpy.average(combined_without[k])
with_avg = numpy.average(combined_with[k])
without_std_dev = numpy.std(combined_without[k])
with_std_dev = numpy.std(combined_with[k])
change = (with_avg - without_avg) / without_avg
pooled_std_dev = pooled_stdev(without_std_dev, with_std_dev) / without_avg
_, p = stats.ttest_rel(combined_without[k], combined_with[k])
f.write("%s,%s,%f,%f,%f,%f,%e,%.2f,%f\n" % (k[0], k[1], without_avg, without_std_dev, with_avg, with_std_dev, p, change, pooled_std_dev))
def main():
write_tasks()
write_elapsed()
if __name__ == "__main__":
main()
# exit on any error and unset variables
#set -u -e -o pipefail
#THIS_DIR="$(readlink -f $(dirname $0))"
#
#TASKS="do_configure do_compile do_install do_package_write_rpm"
#ATTRS="cputime walltime"
#
#echo "Task,Attribute,Build,Without Icecream,With Icecream" > $THIS_DIR/stats/stat.csv
#
#for d in $THIS_DIR/stats/build*; do
# for task in $TASKS; do
# for attr in $ATTRS; do
# VAL="$($THIS_DIR/poky/scripts/buildstats-diff --only-task $task --diff-attr $attr $d/without-icecream $d/with-icecream | tail -1)"
# echo "$task,$attr,$d,$(echo $VAL | sed 's/.*(\([0-9.]\+\)s).*(\([0-9.]\+\)s).*/\1,\2/g')" >> $THIS_DIR/stats/stat.csv
# done
# done
#done
|
[
"numpy.average",
"os.path.basename",
"numpy.std",
"scipy.stats.ttest_rel",
"os.path.realpath",
"re.match",
"os.path.join",
"numpy.sqrt"
] |
[((224, 250), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (240, 250), False, 'import os\n'), ((268, 316), 'os.path.join', 'os.path.join', (['THIS_DIR', '"""poky"""', '"""scripts"""', '"""lib"""'], {}), "(THIS_DIR, 'poky', 'scripts', 'lib')\n", (280, 316), False, 'import os\n'), ((1754, 1803), 'numpy.sqrt', 'numpy.sqrt', (['((a_std_dev ** 2 + b_std_dev ** 2) / 2)'], {}), '((a_std_dev ** 2 + b_std_dev ** 2) / 2)\n', (1764, 1803), False, 'import numpy\n'), ((3007, 3046), 'numpy.average', 'numpy.average', (['elapsed_combined_without'], {}), '(elapsed_combined_without)\n', (3020, 3046), False, 'import numpy\n'), ((3070, 3106), 'numpy.average', 'numpy.average', (['elapsed_combined_with'], {}), '(elapsed_combined_with)\n', (3083, 3106), False, 'import numpy\n'), ((3133, 3168), 'numpy.std', 'numpy.std', (['elapsed_combined_without'], {}), '(elapsed_combined_without)\n', (3142, 3168), False, 'import numpy\n'), ((3192, 3224), 'numpy.std', 'numpy.std', (['elapsed_combined_with'], {}), '(elapsed_combined_with)\n', (3201, 3224), False, 'import numpy\n'), ((3395, 3459), 'scipy.stats.ttest_rel', 'stats.ttest_rel', (['elapsed_combined_without', 'elapsed_combined_with'], {}), '(elapsed_combined_without, elapsed_combined_with)\n', (3410, 3459), False, 'from scipy import stats\n'), ((3825, 3860), 'numpy.average', 'numpy.average', (['cpu_combined_without'], {}), '(cpu_combined_without)\n', (3838, 3860), False, 'import numpy\n'), ((3884, 3916), 'numpy.average', 'numpy.average', (['cpu_combined_with'], {}), '(cpu_combined_with)\n', (3897, 3916), False, 'import numpy\n'), ((3943, 3974), 'numpy.std', 'numpy.std', (['cpu_combined_without'], {}), '(cpu_combined_without)\n', (3952, 3974), False, 'import numpy\n'), ((3998, 4026), 'numpy.std', 'numpy.std', (['cpu_combined_with'], {}), '(cpu_combined_with)\n', (4007, 4026), False, 'import numpy\n'), ((4089, 4145), 'scipy.stats.ttest_rel', 'stats.ttest_rel', (['cpu_combined_without', 'cpu_combined_with'], {}), '(cpu_combined_without, cpu_combined_with)\n', (4104, 4145), False, 'from scipy import stats\n'), ((1132, 1162), 'os.path.join', 'os.path.join', (['p', '"""build_stats"""'], {}), "(p, 'build_stats')\n", (1144, 1162), False, 'import os\n'), ((1211, 1261), 're.match', 're.match', (['"""Elapsed time: (?P<elapsed>[\\\\d.]+) """', 'l'], {}), "('Elapsed time: (?P<elapsed>[\\\\d.]+) ', l)\n", (1219, 1261), False, 'import re\n'), ((1386, 1429), 're.match', 're.match', (['"""CPU usage: (?P<cpu>[\\\\d.]+)%"""', 'l'], {}), "('CPU usage: (?P<cpu>[\\\\d.]+)%', l)\n", (1394, 1429), False, 'import re\n'), ((1834, 1880), 'os.path.join', 'os.path.join', (['THIS_DIR', '"""stats"""', '"""elapsed.csv"""'], {}), "(THIS_DIR, 'stats', 'elapsed.csv')\n", (1846, 1880), False, 'import os\n'), ((2184, 2225), 'os.path.join', 'os.path.join', (['THIS_DIR', '"""stats"""', '"""build*"""'], {}), "(THIS_DIR, 'stats', 'build*')\n", (2196, 2225), False, 'import os\n'), ((4343, 4385), 'os.path.join', 'os.path.join', (['THIS_DIR', '"""stats"""', '"""raw.csv"""'], {}), "(THIS_DIR, 'stats', 'raw.csv')\n", (4355, 4385), False, 'import os\n'), ((4555, 4596), 'os.path.join', 'os.path.join', (['THIS_DIR', '"""stats"""', '"""build*"""'], {}), "(THIS_DIR, 'stats', 'build*')\n", (4567, 4596), False, 'import os\n'), ((5243, 5288), 'os.path.join', 'os.path.join', (['THIS_DIR', '"""stats"""', '"""totals.csv"""'], {}), "(THIS_DIR, 'stats', 'totals.csv')\n", (5255, 5288), False, 'import os\n'), ((5511, 5545), 'numpy.average', 'numpy.average', (['combined_without[k]'], {}), '(combined_without[k])\n', (5524, 5545), False, 'import numpy\n'), ((5569, 5600), 'numpy.average', 'numpy.average', (['combined_with[k]'], {}), '(combined_with[k])\n', (5582, 5600), False, 'import numpy\n'), ((5631, 5661), 'numpy.std', 'numpy.std', (['combined_without[k]'], {}), '(combined_without[k])\n', (5640, 5661), False, 'import numpy\n'), ((5689, 5716), 'numpy.std', 'numpy.std', (['combined_with[k]'], {}), '(combined_with[k])\n', (5698, 5716), False, 'import numpy\n'), ((5883, 5937), 'scipy.stats.ttest_rel', 'stats.ttest_rel', (['combined_without[k]', 'combined_with[k]'], {}), '(combined_without[k], combined_with[k])\n', (5898, 5937), False, 'from scipy import stats\n'), ((2283, 2318), 'os.path.join', 'os.path.join', (['p', '"""without-icecream"""'], {}), "(p, 'without-icecream')\n", (2295, 2318), False, 'import os\n'), ((2369, 2401), 'os.path.join', 'os.path.join', (['p', '"""with-icecream"""'], {}), "(p, 'with-icecream')\n", (2381, 2401), False, 'import os\n'), ((4647, 4682), 'os.path.join', 'os.path.join', (['p', '"""without-icecream"""'], {}), "(p, 'without-icecream')\n", (4659, 4682), False, 'import os\n'), ((4729, 4761), 'os.path.join', 'os.path.join', (['p', '"""with-icecream"""'], {}), "(p, 'with-icecream')\n", (4741, 4761), False, 'import os\n'), ((2664, 2683), 'os.path.basename', 'os.path.basename', (['p'], {}), '(p)\n', (2680, 2683), False, 'import os\n'), ((5046, 5065), 'os.path.basename', 'os.path.basename', (['p'], {}), '(p)\n', (5062, 5065), False, 'import os\n')]
|
import time
import threading
import numpy as np
from common import preprocess_one_image_fn, draw_outputs, load_classes, generate_colors
from yolo_utils import yolo_eval
from priority_queue import PriorityQueue
class YOLOv3Thread(threading.Thread):
def __init__(self, runner: "Runner", deque_input, lock_input,
deque_output, lock_output, thread_name):
super(YOLOv3Thread, self).__init__(name=thread_name)
self.runner = runner
self.deque_input = deque_input
self.lock_input = lock_input
self.deque_output = deque_output
self.lock_output = lock_output
self.class_names = load_classes('./model_data/adas_classes.txt')
self.colors = generate_colors(self.class_names)
def set_input_image(self, input_run, frame, size):
w, h = size
img = preprocess_one_image_fn(frame, w, h)
input_run[0, ...] = img.reshape((h, w, 3))
def run(self):
# Get input/output tensors and dims
inputTensors = self.runner.get_input_tensors()
outputTensors = self.runner.get_output_tensors()
input_ndim = tuple(inputTensors[0].dims) # (1, 256, 512, 3)
result0_ndim = tuple(outputTensors[0].dims) # (1, 8, 16, 40)
result1_ndim = tuple(outputTensors[1].dims) # (1, 16, 32, 40)
result2_ndim = tuple(outputTensors[2].dims) # (1, 32, 64, 40)
result3_ndim = tuple(outputTensors[3].dims) # (1, 64, 126, 40)
# input/output data define
input_data = [np.empty(input_ndim, dtype=np.float32, order="C")]
result0 = np.empty(result0_ndim, dtype=np.float32, order="C")
result1 = np.empty(result1_ndim, dtype=np.float32, order="C")
result2 = np.empty(result2_ndim, dtype=np.float32, order="C")
result3 = np.empty(result3_ndim, dtype=np.float32, order="C")
results = [result0, result1, result2, result3]
# get input width, height for preprocess
input_shape = (input_ndim[2], input_ndim[1])
while True:
self.lock_input.acquire()
# empy
if not self.deque_input:
self.lock_input.release()
continue
else:
# get input frame from input frames queue
data_from_deque = self.deque_input[0]
self.deque_input.popleft()
self.lock_input.release()
# Init input image to input buffers
img = data_from_deque['img']
idx = data_from_deque['idx']
start_time = data_from_deque['time']
self.set_input_image(input_data[0], img, input_shape)
# invoke the running of DPU for yolov3
"""Benchmark DPU FPS performance over Vitis AI APIs `execute_async()` and `wait()`"""
# (self: vart.Runner, arg0: List[buffer], arg1: List[buffer]) -> Tuple[int, int]
job_id = self.runner.execute_async(input_data, results)
self.runner.wait(job_id)
self.post_process(img, results, input_shape)
self.lock_output.acquire()
img_info = PriorityQueue(idx, img, start_time)
self.deque_output.append(img_info)
self.deque_output.sort()
self.lock_output.release()
def post_process(self, image, results, input_ndim):
"""Xilinx ADAS detction model: YOLOv3
Name: yolov3_adas_pruned_0_9
Input shape: (256, 512, 3)
Classe: 3
Anchor: 5, for detail please see `yolo_utils.py`
Outputs: 4
outputs_node: {
"layer81_conv",
"layer93_conv",
"layer105_conv",
"layer117_conv",
}
"""
image_shape = (image.shape[1], image.shape[0]) # (w, h)
scores, boxes, classes = yolo_eval(
results,
image_shape=image_shape,
input_ndim=input_ndim,
classes=3,
score_threshold=0.5,
iou_threshold=0.7)
# print("detection:")
# for i in range(scores.shape[0]):
# print("\t{}, {}, {}".format(
# self.class_names[int(classes[i])], scores[i], boxes[i]
# ))
image = draw_outputs(image, (scores, boxes, classes),
self.class_names, self.colors)
|
[
"common.preprocess_one_image_fn",
"common.draw_outputs",
"yolo_utils.yolo_eval",
"priority_queue.PriorityQueue",
"numpy.empty",
"common.generate_colors",
"common.load_classes"
] |
[((651, 696), 'common.load_classes', 'load_classes', (['"""./model_data/adas_classes.txt"""'], {}), "('./model_data/adas_classes.txt')\n", (663, 696), False, 'from common import preprocess_one_image_fn, draw_outputs, load_classes, generate_colors\n'), ((719, 752), 'common.generate_colors', 'generate_colors', (['self.class_names'], {}), '(self.class_names)\n', (734, 752), False, 'from common import preprocess_one_image_fn, draw_outputs, load_classes, generate_colors\n'), ((843, 879), 'common.preprocess_one_image_fn', 'preprocess_one_image_fn', (['frame', 'w', 'h'], {}), '(frame, w, h)\n', (866, 879), False, 'from common import preprocess_one_image_fn, draw_outputs, load_classes, generate_colors\n'), ((1587, 1638), 'numpy.empty', 'np.empty', (['result0_ndim'], {'dtype': 'np.float32', 'order': '"""C"""'}), "(result0_ndim, dtype=np.float32, order='C')\n", (1595, 1638), True, 'import numpy as np\n'), ((1657, 1708), 'numpy.empty', 'np.empty', (['result1_ndim'], {'dtype': 'np.float32', 'order': '"""C"""'}), "(result1_ndim, dtype=np.float32, order='C')\n", (1665, 1708), True, 'import numpy as np\n'), ((1727, 1778), 'numpy.empty', 'np.empty', (['result2_ndim'], {'dtype': 'np.float32', 'order': '"""C"""'}), "(result2_ndim, dtype=np.float32, order='C')\n", (1735, 1778), True, 'import numpy as np\n'), ((1797, 1848), 'numpy.empty', 'np.empty', (['result3_ndim'], {'dtype': 'np.float32', 'order': '"""C"""'}), "(result3_ndim, dtype=np.float32, order='C')\n", (1805, 1848), True, 'import numpy as np\n'), ((3831, 3953), 'yolo_utils.yolo_eval', 'yolo_eval', (['results'], {'image_shape': 'image_shape', 'input_ndim': 'input_ndim', 'classes': '(3)', 'score_threshold': '(0.5)', 'iou_threshold': '(0.7)'}), '(results, image_shape=image_shape, input_ndim=input_ndim, classes=\n 3, score_threshold=0.5, iou_threshold=0.7)\n', (3840, 3953), False, 'from yolo_utils import yolo_eval\n'), ((4246, 4322), 'common.draw_outputs', 'draw_outputs', (['image', '(scores, boxes, classes)', 'self.class_names', 'self.colors'], {}), '(image, (scores, boxes, classes), self.class_names, self.colors)\n', (4258, 4322), False, 'from common import preprocess_one_image_fn, draw_outputs, load_classes, generate_colors\n'), ((1518, 1567), 'numpy.empty', 'np.empty', (['input_ndim'], {'dtype': 'np.float32', 'order': '"""C"""'}), "(input_ndim, dtype=np.float32, order='C')\n", (1526, 1567), True, 'import numpy as np\n'), ((3120, 3155), 'priority_queue.PriorityQueue', 'PriorityQueue', (['idx', 'img', 'start_time'], {}), '(idx, img, start_time)\n', (3133, 3155), False, 'from priority_queue import PriorityQueue\n')]
|
import warnings
warnings.filterwarnings('ignore')
import tensorflow as tf
from tensorflow.examples.tutorials import mnist
import numpy as np
import os
import random
from scipy import misc
import time
import sys
#from draw import viz_data, x, A, B, read_n, T
#from drawCopy1 import viz_data, x, A, B, read_n, T
#from draw_eric import viz_data, x, A, B, read_n, T
from draw_eric_rewrite_filterbank import viz_data, x, A, B, read_n, T
#import load_input
#import load_trace
sess_config = tf.ConfigProto()
sess_config.gpu_options.allow_growth = True
sess = tf.InteractiveSession(config=sess_config)
saver = tf.train.Saver()
#data = load_trace.TraceData()
#data.get_test(1)
#data = load_input.InputData()
#data.get_test(1)
data = mnist.input_data.read_data_sets("mnist", one_hot=True).test
def random_image():
"""Get a random image from test set."""
num_images = len(data.images)
i = random.randrange(num_images)
image_ar = np.array(data.images[i]).reshape(A, B)
return image_ar#, data.labels[i]
def load_checkpoint(it):
#path = "model_runs/blob_classification"
#saver.restore(sess, "%s/drawmodel_%d.ckpt" % (path, it))
#saver.restore(sess, "trace_draw/drawmodel.ckpt")
saver.restore(sess, "model_runs/rewrite_filterbank/drawmodel.ckpt")
# saver.restore(sess, "model_runs/rewrite_filterbank/drawmodel.ckpt")
last_image = None
def read_img(it, new_image):
batch_size = 1
out = dict()
global last_image
if new_image or last_image is None:
last_image = random_image()
#img, label = last_image
img = last_image
flipped = np.flip(img.reshape(A, B), 0)
out = {
"img": flipped,
#"label": label,
"rects": list(),
"rs": list(),
}
load_checkpoint(it)
cs = sess.run(viz_data, feed_dict={x: img.reshape(batch_size, A*B)})
for i in range(len(cs)):
print('cs[i]["stats"]: ', cs[i]["stats"])
#print(len(cs[i]["r"]))
out["rs"].append(np.flip(cs[i]["r"].reshape(read_n, read_n), 0))
out["rects"].append(stats_to_rect(cs[i]["stats"]))
return out
def read_img2(it, new_image):
"""Read image with rewritten filterbanks."""
batch_size = 1
out = dict()
global last_image
if new_image or last_image is None:
last_image = random_image()
img = last_image
flipped = np.flip(img.reshape(A, B), 0)
out = {
"img": flipped,
"dots": list(),
}
load_checkpoint(it)
cs = sess.run(viz_data, feed_dict={x: img.reshape(batch_size, A*B)})
for i in range(len(cs)):
mu_x = list(cs[i]["r_mu_x"])
mu_y = list(cs[i]["r_mu_y"])
delta = list(cs[i]["r_delta"])
gx_ = cs[i]["r_gx_"]
gy_ = cs[i]["r_gy_"]
# sigma2 = list(cs[i]["r_sigma2"])
# print("glimpse: ", i)
#
print("gx_: ")
print(gx_)
print("gy_: ")
print(gy_)
# print("sigma2: ")
# print(sigma2)
#
print("delta: ")
print(delta)
print("")
out["dots"].append(list_to_dots(mu_x, mu_y))
return out
def write_img(it, new_image):
batch_size = 1
out = dict()
global last_image
if new_image or last_image is None:
last_image = random_image()
#img, label = last_image
img = last_image
flipped = np.flip(img.reshape(A, B), 0)
out = {
#"label": label,
"rects": list(),
"c": list(),
}
load_checkpoint(it)
cs = sess.run(viz_data, feed_dict={x: img.reshape(batch_size, A*B)})
for i in range(len(cs)):
out["c"].append(np.flip(cs[i]["c"].reshape(A, B), 0))
out["rects"].append(stats_to_rect(cs[i]["w_stats"]))
#print('cs[i]["stats"]: ')
#print(cs[i]["stats"])
#print('stats_to_rect[i]["stats"]: ')
#print(stats_to_rect(cs[i]["stats"]))
return out
def write_img2(it, new_image):
"""Write image with rewritten filterbanks."""
batch_size = 1
out = dict()
global last_image
if new_image or last_image is None:
last_image = random_image()
img = last_image
flipped = np.flip(img.reshape(A, B), 0)
out = {
"img": flipped,
"dots": list(),
"c": list(),
}
load_checkpoint(it)
cs = sess.run(viz_data, feed_dict={x: img.reshape(batch_size, A*B)})
for i in range(len(cs)):
out["c"].append(np.flip(cs[i]["c"].reshape(A, B), 0))
mu_x = list(cs[i]["w_mu_x"])
mu_y = list(cs[i]["w_mu_y"])
# delta = list(cs[i]["w_delta"])
out["dots"].append(list_to_dots(mu_x, mu_y))
# gx_ = cs[i]["w_gx_"]
# gy_ = cs[i]["w_gy_"]
# sigma2 = list(cs[i]["w_sigma2"])
#
# print("glimpse: ", i)
#
# print("gx_: ")
# print(gx_)
#
# print("gy_: ")
# print(gy_)
#
# print("sigma2: ")
# print(sigma2)
#
# print("delta: ")
# print(delta)
# print("")
return out
def stats_to_rect(stats):
"""Draw attention window based on gx, gy, and delta."""
gx, gy, delta = stats
minY = A - gy + read_n/2.0 * delta
maxY = B - gy - read_n/2.0 * delta
minX = gx - read_n/2.0 * delta
maxX = gx + read_n/2.0 * delta
if minX < 1:
minX = 1
if maxY < 1:
maxY = 1
if maxX > A - 1:
maxX = A - 1
if minY > B - 1:
minY = B - 1
return dict(top=[int(minY)], bottom=[int(maxY)], left=[int(minX)], right=[int(maxX)])
def list_to_dots(mu_x, mu_y):
"""Draw filterbank based on mu_x and mu_y."""
mu_x_list = mu_x * read_n
mu_y_list = [val for val in mu_y for _ in range(0, read_n)]
return dict(mu_x_list=mu_x_list, mu_y_list=mu_y_list)
|
[
"tensorflow.train.Saver",
"warnings.filterwarnings",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.ConfigProto",
"random.randrange",
"numpy.array",
"tensorflow.InteractiveSession"
] |
[((16, 49), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (39, 49), False, 'import warnings\n'), ((486, 502), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (500, 502), True, 'import tensorflow as tf\n'), ((554, 595), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {'config': 'sess_config'}), '(config=sess_config)\n', (575, 595), True, 'import tensorflow as tf\n'), ((605, 621), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (619, 621), True, 'import tensorflow as tf\n'), ((730, 784), 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'mnist.input_data.read_data_sets', (['"""mnist"""'], {'one_hot': '(True)'}), "('mnist', one_hot=True)\n", (761, 784), False, 'from tensorflow.examples.tutorials import mnist\n'), ((898, 926), 'random.randrange', 'random.randrange', (['num_images'], {}), '(num_images)\n', (914, 926), False, 'import random\n'), ((942, 966), 'numpy.array', 'np.array', (['data.images[i]'], {}), '(data.images[i])\n', (950, 966), True, 'import numpy as np\n')]
|
import numpy as np
import mpnum as mp
import tmps
from tmps.utils import state_reduction_as_ndarray, convert, broadcast_number_ground_state, get_thermal_state
import time
from scipy.special import factorial
import math
def get_spin_initial_state(theta, mpa_type='mps'):
"""
Returns the initial state for the spin impurity:
psi_0 = cos(theta) |1> + sin(theta) |0>
in the desired tensor network form (mps, mpo, pmps)
"""
ground = np.array([0.0, np.sin(theta)])
excited = np.array([np.cos(theta), 0.0])
return convert.to_mparray(ground + excited, mpa_type)
def get_spin_boson_0T_chain_initial_state(theta, bath_local_dim, nof_coefficients):
"""
Returns the full initial state (vacuum state) for 0T chain with nof_coefficients sites and a local dimension of
bath_local_dim.
"""
sys_psi_0 = get_spin_initial_state(theta)
bath_psi_0 = broadcast_number_ground_state(bath_local_dim, nof_coefficients)
return mp.chain([sys_psi_0, bath_psi_0])
def get_spin_boson_0T_star_initial_state(theta, system_index, bath_local_dim, nof_coefficients):
"""
Returns the full initial state (vacuum state) for 0T star with nof_coefficients sites and a local dimension of
bath_local_dim. The impurity is located at system_index.
"""
sys_psi_0 = get_spin_initial_state(theta)
# Initial states of the bath sites left and right of the system:
left_bath_psi_0, right_bath_psi_0 = tmps.utils.broadcast_number_ground_state(bath_local_dim, system_index), \
tmps.utils.broadcast_number_ground_state(bath_local_dim,
nof_coefficients - system_index)
return mp.chain([left_bath_psi_0, sys_psi_0, right_bath_psi_0]
if left_bath_psi_0 is not None else [sys_psi_0, right_bath_psi_0])
def _compute_finiteT_chain_residual(psi_0, mpa_type, dims):
"""
Returns residual of the finite-temperature initial state of the bath. List of populations in
the highest energy state of each mode
"""
res = []
for index, dim in enumerate(dims):
res.append(np.real(state_reduction_as_ndarray(psi_0, mpa_type, startsite=index)[dim - 1, dim - 1]))
return res
def get_spin_boson_finiteT_chain_initial_state(theta, beta, h_site, h_bond, bath_local_dim, nof_coefficients,
mpa_type='pmps',
nof_steps=None, state_compression_kwargs=None,
op_compression_kwargs=None, second_order_trotter=False,
psi_0_compression_kwargs=None, residual=True,
force_pmps_evolution=True, verbose=True):
"""
Computes the initial state for the finite temperature spin_boson model in chain geometry.
The bath state is computed via imaginary time evolution.
:param theta: Spin parameter for psi_0 = cos(theta) |1> + sin(theta) |0>
:param beta: Inverse temperature of the bath
:param h_site: Bath local Hamiltonian list
:param h_bond: Bath nearest neighbor coupling Hamiltonian list
:param bath_local_dim: Local dimension of the bath
:param nof_coefficients: Number of bath sites
:param mpa_type: MPS type of the chain (mps, mpo, pmps)
:param nof_steps: Number of steps for the imaginary time evolution
:param state_compression_kwargs: Keyword args for the imaginary time evolution compression
:param op_compression_kwargs: Keyword args for the imaginary time evolution operator pre-compression
:param second_order_trotter: Set True for second order trotter based imaginary time evolution
:param psi_0_compression_kwargs: Keyword args for the imaginary time evolution initial state compression
:param residual: Set True to compute List of populations in the highest energy state of each bath mode.
:param force_pmps_evolution: Set True to always use pmps for the imaginary time evolution
:param verbose: Set true to make imaginary time evolution verbose
:return: Initial state of system and bath as mps, mpo or pmps, info dict
"""
assert mpa_type == 'mpo' or mpa_type == 'pmps'
if nof_steps is None:
nof_steps = int(beta*100)
t0_wall = time.clock()
t0_proc = time.perf_counter()
if isinstance(bath_local_dim, int):
dims = [bath_local_dim] * nof_coefficients
else:
raise AssertionError('Unsupported data type for fixed_dim')
psi_0, info = tmps.chain.thermal.from_hamiltonian(beta, mpa_type, h_site, h_bond,
nof_steps=nof_steps,
state_compression_kwargs=state_compression_kwargs,
op_compression_kwargs=op_compression_kwargs,
second_order_trotter=second_order_trotter,
psi_0_compression_kwargs=psi_0_compression_kwargs,
force_pmps_evolution=force_pmps_evolution,
verbose=verbose)
tf_proc = time.perf_counter() - t0_proc
tf_wall = time.clock() - t0_wall
info['walltime'] = tf_wall
info['cpu_time'] = tf_proc
info['bath_dims'] = dims
if residual:
res = _compute_finiteT_chain_residual(psi_0, mpa_type, dims)
max_res = np.max(res)
info['res'] = res
info['max_res'] = max_res
else:
info['res'] = None
info['max_res'] = None
print('Finite T ground state residual ', info['res'])
print('Finite T ground state max. residual: ', info['max_res'])
sys_psi_0 = get_spin_initial_state(theta, mpa_type=mpa_type)
return mp.chain([sys_psi_0, psi_0]), info
def get_star_local_dims(beta, xi, fixed_dim=None, high_energy_pop=1e-20, sitewise=False):
"""
Computes the local dimension for the finite temperature star bath for the spin_boson model.
:param beta: Inverse temperature of the bath
:param xi: Star geometry bath energies
:param fixed_dim: Uses this fixed dimension for the star evolution
:param high_energy_pop: Chooses local dimension, such that the population in the highest energy of each bath mode
stays below this threshold
:param sitewise: If set False the local dimension is chosen uniformly for all sites to be the
highest local dimension from the high_energy_pop calculation.
:returns: List of bath dimensions
"""
if fixed_dim is None:
dims = []
for xi_i in xi:
a = 1 / (np.exp(beta * xi_i) - 1)
dims.append(math.ceil(1 / (beta * xi_i) * np.log(1 + 1 / (high_energy_pop * a))))
if sitewise:
return dims
else:
return [np.max(dims)]*len(xi)
else:
if isinstance(fixed_dim, (list, tuple)):
assert len(fixed_dim) == len(xi)
return fixed_dim
elif isinstance(fixed_dim, int):
return [fixed_dim]*len(xi)
else:
raise AssertionError('Unsupported data type for fixed_dim')
def _compute_finite_T_star_residual(beta, xi, dims):
"""
Returns residual of the finite-temperature initial state of the bath. List of populations in
the highest energy state of each mode
"""
res = []
for xi_i, dim in zip(xi, dims):
res.append((np.exp(beta*xi_i) - 1)/(np.exp(beta*xi_i * dim)))
return res
def get_spin_boson_finiteT_star_initial_state(theta, beta, system_index, xi, mpa_type='pmps', fixed_dim=None,
high_energy_pop=1e-20, sitewise=False, residual=True):
"""
Computes the initial state for the finite temperature spin_boson model in star geometry.
The bath state is computed via imaginary time evolution.
:param theta: Spin parameter for psi_0 = cos(theta) |1> + sin(theta) |0>
:param beta: Inverse temperature of the bath
:param system_index: Impurity position in the auxiliary chain
:param xi: Star geometry bath energies
:param mpa_type: Type: mps, mpo or pmps of the initial state
:param fixed_dim: Uses this fixed dimension for the star evolution
:param high_energy_pop: Chooses local dimension, such that the population in the highest energy of each bath mode
stays below this threshold
:param sitewise: If set False the local dimension is chosen uniformly for all sites to be the
highest local dimension from the high_energy_pop calculation.
:param residual: Computes list of populations in the highest energy state of each mode
:return: Initial state of system and bath as mps, mpo or pmps, info dict
"""
assert mpa_type == 'mpo' or mpa_type == 'pmps'
t0_wall = time.clock()
t0_proc = time.perf_counter()
dims = get_star_local_dims(beta, xi, fixed_dim=fixed_dim, high_energy_pop=high_energy_pop, sitewise=sitewise)
ops = [xi[i] * np.arange(dim) for i, dim in enumerate(dims)]
if system_index > 0:
left_state = get_thermal_state(beta, mpa_type, ops[:system_index], to_cform=None)
right_state = get_thermal_state(beta, mpa_type, ops[system_index:], to_cform=None)
else:
left_state = None
right_state = get_thermal_state(beta, mpa_type, ops, to_cform=None)
tf_proc = time.perf_counter() - t0_proc
tf_wall = time.clock() - t0_wall
info = dict()
info['walltime'] = tf_wall
info['cpu_time'] = tf_proc
info['bath_dims'] = dims
if residual:
info['res'] = _compute_finite_T_star_residual(beta, xi, dims)
info['max_res'] = np.max(info['res'])
else:
info['res'] = None
info['max_res'] = None
sys_psi_0 = get_spin_initial_state(theta, mpa_type=mpa_type)
return mp.chain([left_state, sys_psi_0, right_state]) if left_state is not None else \
mp.chain([sys_psi_0, right_state]), info
def get_boson_boson_0T_chain_initial_state(alpha, nof_coefficients, cutoff_dim):
"""
Initial state for the Boson-Boson model in chain geometry (see Sec. 4.4.3 of the thesis)
:param alpha: accuracy alpha for the impurity coherent state
:param nof_coefficients: Number of bath sites
:param cutoff_dim: Local dimension of the system and impurity
:return: Initial state in MPS form
"""
pop = lambda x: np.exp(-np.abs(alpha) ** 2 / 2) * alpha ** x / np.sqrt(factorial(x))
sys_psi_0 = convert.to_mparray(pop(np.arange(cutoff_dim)), 'mps')
bath_psi_0 = broadcast_number_ground_state(cutoff_dim, nof_coefficients)
return mp.chain([sys_psi_0, bath_psi_0])
def get_boson_boson_0T_star_initial_state(alpha, system_index, nof_coefficients, cutoff_dim):
"""
Initial state for the Boson-Boson model in star geometry (see Sec. 4.4.3 of the thesis)
:param alpha: accuracy alpha for the impurity coherent state
:param system_index: Index of the impurity in the auxiliary chain
:param nof_coefficients: Number of bath sites
:param cutoff_dim: Local dimension of the system and impurity
:return: Initial state in MPS form
"""
pop = lambda x: np.exp(-np.abs(alpha) ** 2 / 2) * alpha ** x / np.sqrt(factorial(x, exact=True))
sys_psi_0 = convert.to_mparray(pop(np.arange(cutoff_dim)), 'mps')
# Initial states of the bath sites left and right of the system:
left_bath_psi_0, right_bath_psi_0 = tmps.utils.broadcast_number_ground_state(cutoff_dim, system_index), \
tmps.utils.broadcast_number_ground_state(cutoff_dim,
nof_coefficients - system_index)
return mp.chain([left_bath_psi_0, sys_psi_0, right_bath_psi_0]
if left_bath_psi_0 is not None else [sys_psi_0, right_bath_psi_0])
|
[
"scipy.special.factorial",
"numpy.abs",
"numpy.log",
"tmps.utils.state_reduction_as_ndarray",
"mpnum.chain",
"tmps.utils.convert.to_mparray",
"time.perf_counter",
"time.clock",
"numpy.max",
"tmps.chain.thermal.from_hamiltonian",
"numpy.sin",
"numpy.arange",
"numpy.cos",
"numpy.exp",
"tmps.utils.get_thermal_state",
"tmps.utils.broadcast_number_ground_state"
] |
[((551, 597), 'tmps.utils.convert.to_mparray', 'convert.to_mparray', (['(ground + excited)', 'mpa_type'], {}), '(ground + excited, mpa_type)\n', (569, 597), False, 'from tmps.utils import state_reduction_as_ndarray, convert, broadcast_number_ground_state, get_thermal_state\n'), ((905, 968), 'tmps.utils.broadcast_number_ground_state', 'broadcast_number_ground_state', (['bath_local_dim', 'nof_coefficients'], {}), '(bath_local_dim, nof_coefficients)\n', (934, 968), False, 'from tmps.utils import state_reduction_as_ndarray, convert, broadcast_number_ground_state, get_thermal_state\n'), ((980, 1013), 'mpnum.chain', 'mp.chain', (['[sys_psi_0, bath_psi_0]'], {}), '([sys_psi_0, bath_psi_0])\n', (988, 1013), True, 'import mpnum as mp\n'), ((1762, 1889), 'mpnum.chain', 'mp.chain', (['([left_bath_psi_0, sys_psi_0, right_bath_psi_0] if left_bath_psi_0 is not\n None else [sys_psi_0, right_bath_psi_0])'], {}), '([left_bath_psi_0, sys_psi_0, right_bath_psi_0] if left_bath_psi_0\n is not None else [sys_psi_0, right_bath_psi_0])\n', (1770, 1889), True, 'import mpnum as mp\n'), ((4398, 4410), 'time.clock', 'time.clock', ([], {}), '()\n', (4408, 4410), False, 'import time\n'), ((4425, 4444), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (4442, 4444), False, 'import time\n'), ((4632, 4987), 'tmps.chain.thermal.from_hamiltonian', 'tmps.chain.thermal.from_hamiltonian', (['beta', 'mpa_type', 'h_site', 'h_bond'], {'nof_steps': 'nof_steps', 'state_compression_kwargs': 'state_compression_kwargs', 'op_compression_kwargs': 'op_compression_kwargs', 'second_order_trotter': 'second_order_trotter', 'psi_0_compression_kwargs': 'psi_0_compression_kwargs', 'force_pmps_evolution': 'force_pmps_evolution', 'verbose': 'verbose'}), '(beta, mpa_type, h_site, h_bond,\n nof_steps=nof_steps, state_compression_kwargs=state_compression_kwargs,\n op_compression_kwargs=op_compression_kwargs, second_order_trotter=\n second_order_trotter, psi_0_compression_kwargs=psi_0_compression_kwargs,\n force_pmps_evolution=force_pmps_evolution, verbose=verbose)\n', (4667, 4987), False, 'import tmps\n'), ((9080, 9092), 'time.clock', 'time.clock', ([], {}), '()\n', (9090, 9092), False, 'import time\n'), ((9107, 9126), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (9124, 9126), False, 'import time\n'), ((10812, 10871), 'tmps.utils.broadcast_number_ground_state', 'broadcast_number_ground_state', (['cutoff_dim', 'nof_coefficients'], {}), '(cutoff_dim, nof_coefficients)\n', (10841, 10871), False, 'from tmps.utils import state_reduction_as_ndarray, convert, broadcast_number_ground_state, get_thermal_state\n'), ((10883, 10916), 'mpnum.chain', 'mp.chain', (['[sys_psi_0, bath_psi_0]'], {}), '([sys_psi_0, bath_psi_0])\n', (10891, 10916), True, 'import mpnum as mp\n'), ((11983, 12110), 'mpnum.chain', 'mp.chain', (['([left_bath_psi_0, sys_psi_0, right_bath_psi_0] if left_bath_psi_0 is not\n None else [sys_psi_0, right_bath_psi_0])'], {}), '([left_bath_psi_0, sys_psi_0, right_bath_psi_0] if left_bath_psi_0\n is not None else [sys_psi_0, right_bath_psi_0])\n', (11991, 12110), True, 'import mpnum as mp\n'), ((1466, 1536), 'tmps.utils.broadcast_number_ground_state', 'tmps.utils.broadcast_number_ground_state', (['bath_local_dim', 'system_index'], {}), '(bath_local_dim, system_index)\n', (1506, 1536), False, 'import tmps\n'), ((1580, 1673), 'tmps.utils.broadcast_number_ground_state', 'tmps.utils.broadcast_number_ground_state', (['bath_local_dim', '(nof_coefficients - system_index)'], {}), '(bath_local_dim, nof_coefficients -\n system_index)\n', (1620, 1673), False, 'import tmps\n'), ((5363, 5382), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (5380, 5382), False, 'import time\n'), ((5407, 5419), 'time.clock', 'time.clock', ([], {}), '()\n', (5417, 5419), False, 'import time\n'), ((5625, 5636), 'numpy.max', 'np.max', (['res'], {}), '(res)\n', (5631, 5636), True, 'import numpy as np\n'), ((5967, 5995), 'mpnum.chain', 'mp.chain', (['[sys_psi_0, psi_0]'], {}), '([sys_psi_0, psi_0])\n', (5975, 5995), True, 'import mpnum as mp\n'), ((9352, 9420), 'tmps.utils.get_thermal_state', 'get_thermal_state', (['beta', 'mpa_type', 'ops[:system_index]'], {'to_cform': 'None'}), '(beta, mpa_type, ops[:system_index], to_cform=None)\n', (9369, 9420), False, 'from tmps.utils import state_reduction_as_ndarray, convert, broadcast_number_ground_state, get_thermal_state\n'), ((9443, 9511), 'tmps.utils.get_thermal_state', 'get_thermal_state', (['beta', 'mpa_type', 'ops[system_index:]'], {'to_cform': 'None'}), '(beta, mpa_type, ops[system_index:], to_cform=None)\n', (9460, 9511), False, 'from tmps.utils import state_reduction_as_ndarray, convert, broadcast_number_ground_state, get_thermal_state\n'), ((9570, 9623), 'tmps.utils.get_thermal_state', 'get_thermal_state', (['beta', 'mpa_type', 'ops'], {'to_cform': 'None'}), '(beta, mpa_type, ops, to_cform=None)\n', (9587, 9623), False, 'from tmps.utils import state_reduction_as_ndarray, convert, broadcast_number_ground_state, get_thermal_state\n'), ((9638, 9657), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (9655, 9657), False, 'import time\n'), ((9682, 9694), 'time.clock', 'time.clock', ([], {}), '()\n', (9692, 9694), False, 'import time\n'), ((9927, 9946), 'numpy.max', 'np.max', (["info['res']"], {}), "(info['res'])\n", (9933, 9946), True, 'import numpy as np\n'), ((11695, 11761), 'tmps.utils.broadcast_number_ground_state', 'tmps.utils.broadcast_number_ground_state', (['cutoff_dim', 'system_index'], {}), '(cutoff_dim, system_index)\n', (11735, 11761), False, 'import tmps\n'), ((11805, 11894), 'tmps.utils.broadcast_number_ground_state', 'tmps.utils.broadcast_number_ground_state', (['cutoff_dim', '(nof_coefficients - system_index)'], {}), '(cutoff_dim, nof_coefficients -\n system_index)\n', (11845, 11894), False, 'import tmps\n'), ((479, 492), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (485, 492), True, 'import numpy as np\n'), ((519, 532), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (525, 532), True, 'import numpy as np\n'), ((9260, 9274), 'numpy.arange', 'np.arange', (['dim'], {}), '(dim)\n', (9269, 9274), True, 'import numpy as np\n'), ((10091, 10137), 'mpnum.chain', 'mp.chain', (['[left_state, sys_psi_0, right_state]'], {}), '([left_state, sys_psi_0, right_state])\n', (10099, 10137), True, 'import mpnum as mp\n'), ((10179, 10213), 'mpnum.chain', 'mp.chain', (['[sys_psi_0, right_state]'], {}), '([sys_psi_0, right_state])\n', (10187, 10213), True, 'import mpnum as mp\n'), ((10764, 10785), 'numpy.arange', 'np.arange', (['cutoff_dim'], {}), '(cutoff_dim)\n', (10773, 10785), True, 'import numpy as np\n'), ((11555, 11576), 'numpy.arange', 'np.arange', (['cutoff_dim'], {}), '(cutoff_dim)\n', (11564, 11576), True, 'import numpy as np\n'), ((7684, 7709), 'numpy.exp', 'np.exp', (['(beta * xi_i * dim)'], {}), '(beta * xi_i * dim)\n', (7690, 7709), True, 'import numpy as np\n'), ((10711, 10723), 'scipy.special.factorial', 'factorial', (['x'], {}), '(x)\n', (10720, 10723), False, 'from scipy.special import factorial\n'), ((11490, 11514), 'scipy.special.factorial', 'factorial', (['x'], {'exact': '(True)'}), '(x, exact=True)\n', (11499, 11514), False, 'from scipy.special import factorial\n'), ((2209, 2269), 'tmps.utils.state_reduction_as_ndarray', 'state_reduction_as_ndarray', (['psi_0', 'mpa_type'], {'startsite': 'index'}), '(psi_0, mpa_type, startsite=index)\n', (2235, 2269), False, 'from tmps.utils import state_reduction_as_ndarray, convert, broadcast_number_ground_state, get_thermal_state\n'), ((6854, 6873), 'numpy.exp', 'np.exp', (['(beta * xi_i)'], {}), '(beta * xi_i)\n', (6860, 6873), True, 'import numpy as np\n'), ((7052, 7064), 'numpy.max', 'np.max', (['dims'], {}), '(dims)\n', (7058, 7064), True, 'import numpy as np\n'), ((7660, 7679), 'numpy.exp', 'np.exp', (['(beta * xi_i)'], {}), '(beta * xi_i)\n', (7666, 7679), True, 'import numpy as np\n'), ((6933, 6970), 'numpy.log', 'np.log', (['(1 + 1 / (high_energy_pop * a))'], {}), '(1 + 1 / (high_energy_pop * a))\n', (6939, 6970), True, 'import numpy as np\n'), ((10664, 10677), 'numpy.abs', 'np.abs', (['alpha'], {}), '(alpha)\n', (10670, 10677), True, 'import numpy as np\n'), ((11443, 11456), 'numpy.abs', 'np.abs', (['alpha'], {}), '(alpha)\n', (11449, 11456), True, 'import numpy as np\n')]
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import os
from dataclasses import dataclass, field
from typing import List, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.data.data_utils import compute_mask_indices
from fairseq.dataclass import ChoiceEnum, FairseqDataclass
from fairseq.models import BaseFairseqModel, register_model
from fairseq.modules import (
Fp32GroupNorm,
Fp32LayerNorm,
GradMultiply,
GumbelVectorQuantizer,
LayerNorm,
MultiheadAttention,
SamePad,
TransposeLast,
)
from fairseq.modules.transformer_sentence_encoder import init_bert_params
from fairseq.utils import buffered_arange, index_put, is_xla_tensor
from torchvision.models.resnet import resnet50
EXTRACTOR_MODE_CHOICES = ChoiceEnum(["default", "layer_norm"])
MASKING_DISTRIBUTION_CHOICES = ChoiceEnum(["static", "uniform", "normal", "poisson"])
@dataclass
class MM2VecConfig(FairseqDataclass):
model_stage: int = field(
default=1,
metadata={"help": "model_stage=1 for training visual feature extractor only,"
"model_stage=2 for pretrain on all subnet"
"model_stage=? for fine-tune"},
)
extractor_mode: EXTRACTOR_MODE_CHOICES = field(
default="default",
metadata={
"help": "mode for feature extractor. default has a single group norm with d "
"groups in the first conv block, whereas layer_norm has layer norms in "
"every block (meant to use with normalize=True)"
},
)
encoder_layers: int = field(
default=12, metadata={"help": "num encoder layers in the transformer"}
)
encoder_embed_dim: int = field(
default=768, metadata={"help": "encoder embedding dimension"}
)
encoder_ffn_embed_dim: int = field(
default=3072, metadata={"help": "encoder embedding dimension for FFN"}
)
encoder_attention_heads: int = field(
default=12, metadata={"help": "num encoder attention heads"}
)
activation_fn: ChoiceEnum(utils.get_available_activation_fns()) = field(
default="gelu", metadata={"help": "activation function to use"}
)
# dropouts
dropout: float = field(
default=0.1, metadata={"help": "dropout probability for the transformer"}
)
attention_dropout: float = field(
default=0.1, metadata={"help": "dropout probability for attention weights"}
)
activation_dropout: float = field(
default=0.0, metadata={"help": "dropout probability after activation in FFN"}
)
encoder_layerdrop: float = field(
default=0.0, metadata={"help": "probability of dropping a tarnsformer layer"}
)
dropout_input: float = field(
default=0.0,
metadata={"help": "dropout to apply to the input (after feat extr)"},
)
dropout_features: float = field(
default=0.0,
metadata={"help": "dropout to apply to the features (after feat extr)"},
)
final_dim: int = field(
default=0,
metadata={
"help": "project final representations and targets to this many dimensions."
"set to encoder_embed_dim is <= 0"
},
)
layer_norm_first: bool = field(
default=False, metadata={"help": "apply layernorm first in the transformer"}
)
audio_conv_feature_layers: str = field(
default="[(512, 10, 5, 0)] + [(512, 3, 2, 0)] * 4 + [(512, 2, 2, 0)] + [(512, 2, 2, 0)]",
metadata={
"help": "string describing convolutional feature extraction layers in form of a python list that contains "
"[(dim, kernel_size, stride), ...]"
},
)
conv_bias: bool = field(
default=False, metadata={"help": "include bias in conv encoder"}
)
logit_temp: float = field(
default=0.1, metadata={"help": "temperature to divide logits by"}
)
quantize_targets: bool = field(
default=False, metadata={"help": "use quantized targets"}
)
quantize_input: bool = field(
default=False, metadata={"help": "use quantized inputs"}
)
same_quantizer: bool = field(
default=False, metadata={"help": "use same quantizer for inputs and targets"}
)
target_glu: bool = field(
default=False, metadata={"help": "adds projection + glu to targets"}
)
feature_grad_mult: float = field(
default=1.0, metadata={"help": "multiply feature extractor var grads by this"}
)
quantizer_depth: int = field(
default=1,
metadata={"help": "number of quantizer layers"},
)
quantizer_factor: int = field(
default=3,
metadata={
"help": "dimensionality increase for inner quantizer layers (if depth > 1)"
},
)
latent_vars: int = field(
default=320,
metadata={"help": "number of latent variables V in each group of the codebook"},
)
latent_groups: int = field(
default=2,
metadata={"help": "number of groups G of latent variables in the codebook"},
)
latent_dim: int = field(
default=0,
metadata={
"help": "if > 0, uses this dimensionality for latent variables. "
"otherwise uses final_dim / latent_groups"
},
)
# masking
mask_length: int = field(default=10, metadata={"help": "mask length"})
mask_prob: float = field(
default=0.65, metadata={"help": "probability of replacing a token with mask"}
)
mask_selection: MASKING_DISTRIBUTION_CHOICES = field(
default="static", metadata={"help": "how to choose mask length"}
)
mask_other: float = field(
default=0,
metadata={
"help": "secondary mask argument (used for more complex distributions), "
"see help in compute_mask_indices"
},
)
no_mask_overlap: bool = field(
default=False, metadata={"help": "whether to allow masks to overlap"}
)
mask_min_space: int = field(
default=1,
metadata={"help": "min space between spans (if no overlap is enabled)"},
)
# channel masking
mask_channel_length: int = field(
default=10, metadata={"help": "length of the mask for features (channels)"}
)
mask_channel_prob: float = field(
default=0.0, metadata={"help": "probability of replacing a feature with 0"}
)
mask_channel_before: bool = False
mask_channel_selection: MASKING_DISTRIBUTION_CHOICES = field(
default="static",
metadata={"help": "how to choose mask length for channel masking"},
)
mask_channel_other: float = field(
default=0,
metadata={
"help": "secondary mask argument (used for more complex distributions), "
"see help in compute_mask_indicesh"
},
)
no_mask_channel_overlap: bool = field(
default=False, metadata={"help": "whether to allow channel masks to overlap"}
)
mask_channel_min_space: int = field(
default=1,
metadata={"help": "min space between spans (if no overlap is enabled)"},
)
# negative selection
num_negatives: int = field(
default=100,
metadata={"help": "number of negative examples from the same sample"},
)
negatives_from_everywhere: bool = field(
default=False,
metadata={"help": "sample negatives from everywhere, not just masked states"},
)
cross_sample_negatives: int = field(
default=0, metadata={"help": "number of negative examples from the any sample"}
)
codebook_negatives: int = field(
default=0, metadata={"help": "number of negative examples codebook"}
)
# positional embeddings
conv_pos: int = field(
default=128,
metadata={"help": "number of filters for convolutional positional embeddings"},
)
conv_pos_groups: int = field(
default=16,
metadata={"help": "number of groups for convolutional positional embedding"},
)
latent_temp: Tuple[float, float, float] = field(
default=(2, 0.5, 0.999995),
metadata={
"help": "temperature for latent variable sampling. "
"can be tuple of 3 values (start, end, decay)"
},
)
# Visual Part
visual_conv_feature_layers: str = field(
default="[(512, 11, 1, 5)] * 3 + [(1024, 11, 1, 5)]",
metadata={
"help": "string describing visual-subnet convolutional feature extraction layers in form of a python list that contains "
"[(dim, kernel_size, stride, padding), ...]"
},
)
visual_input_dim: int = field(
default=112,
metadata={"help": "number of dims of visual pictures"},
)
visual_encoder_dim: int = field(
default=2048,
metadata={"help": "number of dims after MoCo"},
)
projection_dim: int = field(
default=512,
metadata={"help": "output dimension of projection head"},
)
# checkpoint part
m2v_path : str = field(
default="./checkpoints-mm-2/",
metadata={
"help": "path to mm2vec stage 1 last model or stage 2 process model"
},
)
# aggregation part
audio_weight: float = field(
default=0.5,
metadata={
"help":"weight for audio_features"
}
)
visual_weight: float = field(
default=0.5,
metadata={
"help":"weight for audio_features"
}
)
remove_quantizer_weight: bool = field(
default=False,
metadata={
"help": "remove quantizer pretrain params"
}
)
unfreeze_quantizer_weight:bool = field(
default=False,
metadata={
"help": "freeze quantizer pretrain params"
}
)
# MoCo
MoCo_replace:bool = field(
default=False,
metadata={"help":"replace first conv2d in MoCo with conv3d"}
)
@register_model("mm2vec", dataclass=MM2VecConfig)
class MM2VecModel(BaseFairseqModel):
def __init__(self, cfg: MM2VecConfig):
super().__init__()
self.cfg = cfg
audio_feature_enc_layers = eval(cfg.audio_conv_feature_layers)
visual_feature_enc_layers = eval(cfg.visual_conv_feature_layers)
self.audio_embed_dim = audio_feature_enc_layers[-1][0] # 512
self.visual_embed_dim = visual_feature_enc_layers[-1][0] # 1024
self.projection_dim = cfg.projection_dim # 512
self.audio_feature_extractor = ConvFeatureExtractionModel(
conv_layers=audio_feature_enc_layers,
dropout=0.0,
mode=cfg.extractor_mode,
conv_bias=cfg.conv_bias,
input_dim=1,
)
self.visual_input_dim = cfg.visual_input_dim # 112
self.MoCo_replace = cfg.MoCo_replace
self.MoCo_extractor = MoCo(replace=self.MoCo_replace)
self.visual_encoder_dim = cfg.visual_encoder_dim # 2048
self.visual_feature_extractor = ConvFeatureExtractionModel(
conv_layers=visual_feature_enc_layers,
dropout=0.0,
mode=cfg.extractor_mode,
conv_bias=cfg.conv_bias,
input_dim=2048,
)
self.post_extract_proj = (
# 512 -> 768
nn.Linear(self.audio_embed_dim, cfg.encoder_embed_dim)
if self.audio_embed_dim != cfg.encoder_embed_dim and not cfg.quantize_input
else None
)
self.projection_head = nn.Sequential(
# 512 -> 512
nn.Linear(int(self.visual_embed_dim / 2), int(self.visual_embed_dim / 2), bias=False),
nn.ReLU(),
# 512 -> 768
nn.Linear(int(self.visual_embed_dim / 2), cfg.encoder_embed_dim, bias=False),
)
""" mask part """
self.mask_prob = cfg.mask_prob
self.mask_selection = cfg.mask_selection
self.mask_other = cfg.mask_other
self.mask_length = cfg.mask_length
self.no_mask_overlap = cfg.no_mask_overlap
self.mask_min_space = cfg.mask_min_space
self.mask_channel_prob = cfg.mask_channel_prob
self.mask_channel_before = cfg.mask_channel_before
self.mask_channel_selection = cfg.mask_channel_selection
self.mask_channel_other = cfg.mask_channel_other
self.mask_channel_length = cfg.mask_channel_length
self.no_mask_channel_overlap = cfg.no_mask_channel_overlap
self.mask_channel_min_space = cfg.mask_channel_min_space
""" mask part """
self.dropout_input = nn.Dropout(cfg.dropout_input)
self.dropout_features = nn.Dropout(cfg.dropout_features)
self.feature_grad_mult = cfg.feature_grad_mult
self.quantizer = None
self.input_quantizer = None
self.n_negatives = cfg.num_negatives
self.cross_sample_negatives = cfg.cross_sample_negatives
self.codebook_negatives = cfg.codebook_negatives
self.negatives_from_everywhere = cfg.negatives_from_everywhere
self.logit_temp = cfg.logit_temp
final_dim = cfg.final_dim if cfg.final_dim > 0 else cfg.encoder_embed_dim
if cfg.quantize_targets:
vq_dim = cfg.latent_dim if cfg.latent_dim > 0 else final_dim
self.quantizer = GumbelVectorQuantizer(
dim=self.audio_embed_dim, # 512
num_vars=cfg.latent_vars, # 320
temp=cfg.latent_temp,
groups=cfg.latent_groups, # 2
combine_groups=False,
vq_dim=vq_dim,
time_first=True,
weight_proj_depth=cfg.quantizer_depth,
weight_proj_factor=cfg.quantizer_factor,
)
self.project_q = nn.Linear(vq_dim, final_dim)
else:
self.project_q = nn.Linear(self.embed, final_dim)
# if cfg.quantize_input:
# if cfg.same_quantizer and self.quantizer is not None:
# vq_dim = final_dim
# self.input_quantizer = self.quantizer
# else:
# vq_dim = cfg.latent_dim if cfg.latent_dim > 0 else cfg.encoder_embed_dim
# self.input_quantizer = GumbelVectorQuantizer(
# dim=self.embed,
# num_vars=cfg.latent_vars,
# temp=cfg.latent_temp,
# groups=cfg.latent_groups,
# combine_groups=False,
# vq_dim=vq_dim,
# time_first=True,
# weight_proj_depth=cfg.quantizer_depth,
# weight_proj_factor=cfg.quantizer_factor,
# )
# self.project_inp = nn.Linear(vq_dim, cfg.encoder_embed_dim)
self.mask_emb = nn.Parameter(
torch.FloatTensor(cfg.encoder_embed_dim).uniform_()
)
self.encoder = TransformerEncoder(cfg)
self.layer_norm = LayerNorm(self.audio_embed_dim)
self.visual_layer_norm = LayerNorm(int(self.visual_embed_dim / 2))
self.target_glu = None
if cfg.target_glu:
self.target_glu = nn.Sequential(
nn.Linear(final_dim, final_dim * 2), nn.GLU()
)
self.final_proj = nn.Linear(cfg.encoder_embed_dim, final_dim)
self.model_stage = cfg.model_stage
self.audio_weight = cfg.audio_weight
self.visual_weight = cfg.visual_weight
def upgrade_state_dict_named(self, state_dict, name):
super().upgrade_state_dict_named(state_dict, name)
"""Upgrade a (possibly old) state dict for new versions of fairseq."""
return state_dict
@classmethod
def build_model(cls, cfg: MM2VecConfig, task=None):
"""Build a new model instance."""
model = cls(cfg)
if cfg.model_stage == 1:
model_dict = model.state_dict()
wav2vec_dict = {k.replace('feature', 'audio_feature'): v for k, v in
torch.load('../pretrain/wav2vec_small.pt')["model"].items()}
moco_dict = {k.replace('module.encoder_q', 'MoCo_extractor.encoder'): v for k, v in
torch.load('../pretrain/moco_v2_800ep_pretrain.pth.tar')["state_dict"].items()}
if cfg.remove_quantizer_weight:
popKeys = ['quantizer.vars', 'quantizer.weight_proj.weight', 'quantizer.weight_proj.bias']
for k in popKeys:
wav2vec_dict.pop(k)
popKeys = ['MoCo_extractor.encoder.fc.0.bias', 'MoCo_extractor.encoder.fc.2.bias',
'MoCo_extractor.encoder.fc.0.weight', 'MoCo_extractor.encoder.fc.2.weight']
if cfg.MoCo_replace:
popKeys.append('MoCo_extractor.encoder.conv1.weight')
for k in popKeys:
moco_dict.pop(k)
model_dict.update(wav2vec_dict)
model_dict.update(moco_dict)
model.load_state_dict(model_dict)
popKeys = ['quantizer.vars', 'quantizer.weight_proj.weight', 'quantizer.weight_proj.bias']
for name, param in model.named_parameters():
# print(name)
if name in wav2vec_dict.keys() or name in moco_dict.keys():
param.requires_grad = False
if name in popKeys and cfg.unfreeze_quantizer_weight:
param.requires_grad = True
elif cfg.model_stage == 2:
model_dict = model.state_dict()
checkpoint_path = os.path.join(cfg.m2v_path, 'checkpoint_last.pt')
checkpoints_dict = torch.load(checkpoint_path)['model']
model_dict.update(checkpoints_dict)
model.load_state_dict(model_dict)
else:
return model
print('num_total_param: {},num_trainable_param: {},num_freezed_param: {}'.format(
sum([params.numel() for params in model.parameters()]),
sum([params.numel() for params in model.parameters() if params.requires_grad]),
sum([params.numel() for params in model.parameters() if not params.requires_grad])))
return model
def apply_mask(
self,
x_audio,
x_visual,
padding_mask,
mask_indices=None,
mask_channel_indices=None,
):
B, T, C = x_audio.shape
# FIXME INFERENCE
if self.mask_channel_prob > 0 and self.mask_channel_before:
mask_channel_indices = compute_mask_indices(
(B, C),
None,
self.mask_channel_prob,
self.mask_channel_length,
self.mask_channel_selection,
self.mask_channel_other,
no_overlap=self.no_mask_channel_overlap,
min_space=self.mask_channel_min_space,
)
mask_channel_indices = (
torch.from_numpy(mask_channel_indices)
.to(x.device)
.unsqueeze(1)
.expand(-1, T, -1)
)
x[mask_channel_indices] = 0
if self.mask_prob > 0:
if mask_indices is None:
mask_indices = compute_mask_indices(
(B, T),
padding_mask,
self.mask_prob,
self.mask_length,
self.mask_selection,
self.mask_other,
min_masks=2,
no_overlap=self.no_mask_overlap,
min_space=self.mask_min_space,
)
mask_indices = torch.from_numpy(mask_indices).to(x_audio.device)
x_audio = index_put(x_audio, mask_indices, self.mask_emb)
x_visual = index_put(x_visual, mask_indices, self.mask_emb)
else:
mask_indices = None
# FIXME INFERENCE
if self.mask_channel_prob > 0 and not self.mask_channel_before:
if mask_channel_indices is None:
mask_channel_indices = compute_mask_indices(
(B, C),
None,
self.mask_channel_prob,
self.mask_channel_length,
self.mask_channel_selection,
self.mask_channel_other,
no_overlap=self.no_mask_channel_overlap,
min_space=self.mask_channel_min_space,
)
mask_channel_indices = (
torch.from_numpy(mask_channel_indices)
.to(x_audio.device)
.unsqueeze(1)
.expand(-1, T, -1)
)
x_audio = index_put(x_audio, mask_channel_indices, 0)
x_visual = index_put(x_visual, mask_channel_indices, 0)
return x_audio, x_visual, mask_indices
def sample_negatives(self, y_audio, y_visual, num, padding_count=None):
#ignore
if self.n_negatives == 0 and self.cross_sample_negatives == 0:
return y.new(0)
bsz, tsz, fsz = y_audio.shape
y_audio = y_audio.view(-1, fsz) # BTC => (BxT)C
y_visual = y_visual.view(-1, fsz)
# FIXME: what happens if padding_count is specified?
cross_high = tsz * bsz
high = tsz - (padding_count or 0)
with torch.no_grad():
assert high > 1, f"{bsz,tsz,fsz}"
if self.n_negatives > 0:
tszs = (
buffered_arange(num)
.unsqueeze(-1)
.expand(-1, self.n_negatives)
.flatten()
)
neg_idxs = torch.randint(
low=0, high=high - 1, size=(bsz, self.n_negatives * num)
)
neg_idxs[neg_idxs >= tszs] += 1
if self.cross_sample_negatives > 0:
tszs = (
buffered_arange(num)
.unsqueeze(-1)
.expand(-1, self.cross_sample_negatives)
.flatten()
)
cross_neg_idxs = torch.randint(
low=0,
high=cross_high - 1,
size=(bsz, self.cross_sample_negatives * num),
)
cross_neg_idxs[cross_neg_idxs >= tszs] += 1
if self.n_negatives > 0:
for i in range(1, bsz):
neg_idxs[i] += i * high
else:
neg_idxs = cross_neg_idxs
if self.cross_sample_negatives > 0 and self.n_negatives > 0:
neg_idxs = torch.cat([neg_idxs, cross_neg_idxs], dim=1)
negs_audio = y_audio[neg_idxs.view(-1)]
negs_audio = negs_audio.view(
bsz, num, self.n_negatives + self.cross_sample_negatives, fsz
).permute(
2, 0, 1, 3
) # to NxBxTxC
negs_visual = y_visual[neg_idxs.view(-1)]
negs_visual = negs_visual.view(
bsz, num, self.n_negatives + self.cross_sample_negatives, fsz
).permute(
2, 0, 1, 3
) # to NxBxTxC
return negs_audio, negs_visual, neg_idxs
def compute_preds(self, x, y, negatives):
neg_is_pos = (y == negatives).all(-1)
y = y.unsqueeze(0)
targets = torch.cat([y, negatives], dim=0)
logits = torch.cosine_similarity(x.float(), targets.float(), dim=-1).type_as(x)
logits = logits / self.logit_temp
if is_xla_tensor(logits) or neg_is_pos.any():
fillval = -float(2 ** 30)
if not hasattr(self, "_inftensor"):
self._inftensor = (
torch.tensor(fillval).to(x.device)
if is_xla_tensor(logits)
else float("-inf")
)
logits[1:] = index_put(logits[1:], neg_is_pos, self._inftensor)
return logits
def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
"""
Computes the output length of the convolutional layers
"""
def _conv_out_length(input_length, kernel_size, stride):
return torch.floor((input_length - kernel_size) / stride + 1)
conv_cfg_list = eval(self.cfg.audio_conv_feature_layers)
for i in range(len(conv_cfg_list)):
input_lengths = _conv_out_length(
input_lengths, conv_cfg_list[i][1], conv_cfg_list[i][2]
)
return input_lengths.to(torch.long)
def compute_visual_length(self,visual_source):
visual_length = list()
max_visual_length = -1
for i in range(len(visual_source)):
length = int(visual_source[i].size(1) / self.visual_input_dim)
if length > max_visual_length:
max_visual_length = length
visual_length.append(length)
return max_visual_length,visual_length
def visual_padding(self,visual_features,visual_length,max_visual_length):
visual_source_new = torch.tensor([], dtype=visual_features.dtype, device=visual_features.device)
start = 0
# 根据visual length数组切分MoCo的输出结果,并padding到最长
visual_source_len = max_visual_length
for l in visual_length:
visual_source_new = torch.cat((visual_source_new, torch.cat(
(visual_features[start:start + l],
torch.zeros((visual_source_len - l, 3,112,112), dtype=visual_features.dtype,
device=visual_features.device)))))
return visual_source_new
def forward(
self,
audio_source,
visual_source,
padding_mask=None,
mask=True,
features_only=False,
layer=None,
mask_indices=None,
mask_channel_indices=None,
padding_count=None,
):
"""
先只管cropping的训练模式,stage1 stage2都是对应好了的 visual 和 audio 长度
batch内不同sample的visual length或者 audio length都是一样的
不需要算长度序列
inference:dataset的pad参数被设置 需要传入padding mask的时候,audio的source才是padding了的
这个时候才需要记录visual length,并在过完moco之后padding
"""
result = {}
# FIXME INFERENCE
if padding_mask is not None:
# compute visual length
max_visual_length, visual_length = self.compute_visual_length(visual_source)
visual_source = torch.cat(visual_source,1)
visual_source = torch.split(visual_source, self.visual_input_dim, 1)
visual_source = torch.cat(visual_source)
visual_source = visual_source.view(-1, self.visual_input_dim, self.visual_input_dim)
visual_source = visual_source.unsqueeze(1).repeat(1, 3, 1, 1)
if self.MoCo_replace:
visual_source = self.visual_padding(visual_source,visual_length,max_visual_length)
visual_source = visual_source.view(len(visual_length),max_visual_length,3,112,112)
visual_source = visual_source.transpose(1,2)
else:
"""
cropping训练,batch内的visual input长度一样
"""
visual_batch_size = len(visual_source)
max_visual_length = int(visual_source[0].size(1)/112)
visual_source = torch.stack(visual_source)
visual_source = torch.split(visual_source, self.visual_input_dim, 1)
visual_source = torch.cat(visual_source)
visual_source = visual_source.view(-1, self.visual_input_dim, self.visual_input_dim)
visual_source = visual_source.unsqueeze(1).repeat(1, 3, 1, 1)
if self.MoCo_replace:
visual_source = visual_source.view(visual_batch_size, max_visual_length, 3, self.visual_input_dim, self.visual_input_dim)
visual_source = visual_source.transpose(1, 2)
"""MoCo input dim:[n_frames,3,112,112]"""
visual_features = self.MoCo_extractor(visual_source)
visual_features = visual_features.view(-1,max_visual_length,self.visual_encoder_dim)
visual_features = visual_features.transpose(1,2)
"""
长度问题到这里应该就结束了,后面不管是padding还是cropping都是align好了的
"""
if self.feature_grad_mult > 0:
# audio: (bsz*sample_length) --> (bsz * feature_dim * frames)
# visual: (bsz*feature_dim * frames) --> (bsz * feature_dim_new * frames)
af_beforeGELU, audio_features = self.audio_feature_extractor(audio_source)
vf_beforeGELU, visual_features = self.visual_feature_extractor(visual_features)
if self.feature_grad_mult != 1.0:
audio_features = GradMultiply.apply(audio_features, self.feature_grad_mult)
visual_features = GradMultiply.apply(visual_features, self.feature_grad_mult)
else:
with torch.no_grad():
af_beforeGELU, audio_features = self.audio_feature_extractor(audio_source)
vf_beforeGELU, visual_features = self.visual_feature_extractor(visual_features)
features_pen = 0 # penalty loss
af_beforeGELU = af_beforeGELU.transpose(1,2)
vf_beforeGELU = vf_beforeGELU.transpose(1,2)
vf_beforeGELU = vf_beforeGELU.reshape(vf_beforeGELU.size(0), -1,int(vf_beforeGELU.size(2) / 2))
vf_beforeGELU = vf_beforeGELU[:, :af_beforeGELU.size(1), :]
af_beforeGELU = self.layer_norm(af_beforeGELU)
vf_beforeGELU = self.visual_layer_norm(vf_beforeGELU)
result["pre_gelu_audio"] = af_beforeGELU
result["pre_gelu_visual"] = vf_beforeGELU
# FIXME:做不做transpose和layer_norm对MSE的影响是啥?过不过GELU的MSE区别是啥?
audio_features = audio_features.transpose(1, 2)
visual_features = visual_features.transpose(1, 2)
visual_features = visual_features.reshape(visual_features.size(0), -1, int(visual_features.size(2) / 2))
visual_features = visual_features[:, :audio_features.size(1), :]
audio_features = self.layer_norm(audio_features) # 512维度上做的layernorm
visual_features = self.visual_layer_norm(visual_features)
result["post_gelu_audio"] = audio_features
result["post_gelu_visual"] = visual_features
unmasked_audio_features = audio_features.clone()
unmasked_visual_features = visual_features.clone()
# FIXME INFERENCE
"""sample维度的padding mask到frame维度的padding mask"""
if padding_mask is not None and padding_mask.any():
input_lengths = (1 - padding_mask.long()).sum(-1)
# apply conv formula to get real output_lengths
output_lengths = self._get_feat_extract_output_lengths(input_lengths)
padding_mask = torch.zeros(
audio_features.shape[:2], dtype=audio_features.dtype, device=audio_features.device
)
# these two operations makes sure that all values
# before the output lengths indices are attended to
padding_mask[
(
torch.arange(padding_mask.shape[0], device=padding_mask.device),
output_lengths - 1,
)
] = 1
padding_mask = (1 - padding_mask.flip([-1]).cumsum(-1).flip([-1])).bool()
else:
padding_mask = None
# 512 -> 768
if self.post_extract_proj is not None:
audio_features = self.post_extract_proj(audio_features)
visual_features = self.post_extract_proj(visual_features)
# if self.projection_head is not None:
# visual_features = self.projection_head(visual_features)
result["features_pen"] = features_pen
audio_features = self.dropout_input(audio_features)
visual_features = self.dropout_input(visual_features)
unmasked_audio_features = self.dropout_features(unmasked_audio_features)
unmasked_visual_features = self.dropout_features(unmasked_visual_features)
num_vars = None
code_ppl = None
prob_ppl = None
curr_temp = None
# if self.input_quantizer:
# q = self.input_quantizer(features, produce_targets=False)
# features = q["x"]
# num_vars = q["num_vars"]
# code_ppl = q["code_perplexity"]
# prob_ppl = q["prob_perplexity"]
# curr_temp = q["temp"]
# features = self.project_inp(features)
if mask:
# inference的时候不计算mask / compute mask indices and set (indices==True) position as self.mask_emb
x_audio, x_visual, mask_indices = self.apply_mask(
audio_features,
visual_features,
padding_mask,
mask_indices=mask_indices,
mask_channel_indices=mask_channel_indices,
)
if not is_xla_tensor(x_audio) and not is_xla_tensor(x_audio) and mask_indices is not None:
# tpu-comment: reducing the size in a dynamic way causes
# too many recompilations on xla.
y_audio = unmasked_audio_features[mask_indices].view(
unmasked_audio_features.size(0), -1, unmasked_audio_features.size(-1)
)
y_visual = unmasked_visual_features[mask_indices].view(
unmasked_visual_features.size(0), -1, unmasked_visual_features.size(-1)
)
else:
# ignore
y_audio = unmasked_audio_features
y_visual = unmasked_visual_features
else:
x_audio = audio_features
x_visual = visual_features
y_audio = unmasked_audio_features
y_visual = unmasked_visual_features
mask_indices = None
"""
mask之后的过transformer
stage 1: 两个模态分别过
stage 2: 两个模态取平均后过
"""
if self.model_stage == 1:
"""
x_audio:Batch * n_frames(with mask_emb) * feature_dim(512)
x_visual:Batch * n_frames(with mask_emb) * feature_dim(512)
x_audio.shape == x_visual.shape
"""
x_audio, layer_results_audio = self.encoder(x_audio, padding_mask=padding_mask, layer=layer)
x_visual, layer_results_visual = self.encoder(x_visual, padding_mask=padding_mask, layer=layer)
elif self.model_stage == 2:
x_cat = (self.audio_weight * x_audio + self.visual_weight * x_visual)
x_cat,layer_results_cat = self.encoder(x_cat, padding_mask=padding_mask, layer=layer)
else:
x_cat = (0.0 * x_audio + 1.0 * x_visual)
x_cat, _ = self.encoder(x_cat, padding_mask=padding_mask, layer=layer)
# FIXME INFERENCE
if features_only:
return {
"x": x_cat,
"padding_mask": padding_mask,
"audio_features": unmasked_audio_features,
"visual_features": unmasked_visual_features,
}
"""
inference时到这儿就结束了
"""
if self.quantizer:
q_visual = self.quantizer(y_visual, produce_targets=False)
y_visual = q_visual["x"]
q_audio = self.quantizer(y_audio, produce_targets=False)
y_audio = q_audio["x"]
if self.model_stage == 1:
"""
只管visual这边的diversity loss
"""
num_vars = q_visual["num_vars"]
code_ppl = [q_visual["code_perplexity"], q_audio["code_perplexity"]]
# 进入码本的比例 = code_ppl/(num_vars*num_latent_groups)
# print("visual_num_vars:",num_vars)
# print("audio_num_vars:", q_audio["num_vars"])
# print("visual_code_ppl:", code_ppl)
# print("audio_code_ppl:", q_audio["code_perplexity"])
prob_ppl = q_visual["prob_perplexity"]
curr_temp = q_visual["temp"]
elif self.model_stage == 2:
num_vars = q_visual["num_vars"]
code_ppl = [q_visual["code_perplexity"], q_audio["code_perplexity"]]
# print("num_vars_va:", num_vars)
# print("code_ppl_va:", code_ppl)
prob_ppl = [q_visual["prob_perplexity"], q_audio["prob_perplexity"]]
curr_temp = [q_visual["temp"], q_audio["temp"]]
y_audio = self.project_q(y_audio)
y_visual = self.project_q(y_visual)
# ignore
if self.negatives_from_everywhere:
# ignore
neg_cands = self.quantizer(unmasked_features, produce_targets=False)[
"x"
]
negs, _ = self.sample_negatives(
neg_cands,
y.size(1),
padding_count=padding_count,
)
negs = self.project_q(negs)
else:
negs_audio,negs_visual, negs_indices = self.sample_negatives(
y_audio,
y_visual,
y_audio.size(1),
padding_count=padding_count,
)
# ignore
if self.codebook_negatives > 0:
cb_negs = self.quantizer.sample_from_codebook(
y.size(0) * y.size(1), self.codebook_negatives
)
cb_negs = cb_negs.view(
self.codebook_negatives, y.size(0), y.size(1), -1
) # order doesnt matter
cb_negs = self.project_q(cb_negs)
negs = torch.cat([negs, cb_negs], dim=0)
else:
y_audio = self.project_q(y_audio)
y_visual = self.project_q(y_visual)
#ignore
if self.negatives_from_everywhere:
negs, _ = self.sample_negatives(
unmasked_features,
y.size(1),
padding_count=padding_count,
)
negs = self.project_q(negs)
else:
negs, _ = self.sample_negatives(
y,
y.size(1),
padding_count=padding_count,
)
if not is_xla_tensor(x_audio) and not is_xla_tensor(x_visual) and self.model_stage == 1:
# tpu-comment: reducing the size in a dynamic way causes
# too many recompilations on xla.
x_audio = x_audio[mask_indices].view(x_audio.size(0), -1, x_audio.size(-1))
x_visual = x_visual[mask_indices].view(x_visual.size(0), -1, x_visual.size(-1))
elif not is_xla_tensor(x_cat) and self.model_stage == 2:
x_cat = x_cat[mask_indices].view(x_cat.size(0), -1, x_cat.size(-1))
# ignore
if self.target_glu:
y = self.target_glu(y)
negs = self.target_glu(negs)
if self.model_stage == 1:
x_audio = self.final_proj(x_audio)
x_audio = self.compute_preds(x_audio, y_audio, negs_audio)
x_visual = self.final_proj(x_visual)
x_visual = self.compute_preds(x_visual, y_visual, negs_visual)
result["x_audio"] = x_audio
result["x_visual"] = x_visual
result["padding_mask"] = padding_mask
elif self.model_stage == 2:
x_cat = self.final_proj(x_cat)
x_audio = self.compute_preds(x_cat, y_audio, negs_audio)
x_visual = self.compute_preds(x_cat, y_visual, negs_visual)
result["x_audio"] =x_audio
result["x_visual"] = x_visual
result["padding_mask"] = padding_mask
if prob_ppl is not None:
result["prob_perplexity"] = prob_ppl
result["code_perplexity"] = code_ppl
result["num_vars"] = num_vars
result["temp"] = curr_temp
result["stage"] = self.model_stage
return result
def quantize(self, x):
assert self.quantizer is not None
x = self.feature_extractor(x)
x = x.transpose(1, 2)
x = self.layer_norm(x)
return self.quantizer.forward_idx(x)
def extract_features(self, audio_source, visual_source, padding_mask, mask=False, layer=None):
res = self.forward(
audio_source,visual_source, padding_mask, mask=mask, features_only=True, layer=layer
)
return res
def get_logits(self, net_output):
logits_audio = net_output["x_audio"]
logits_visual = net_output["x_visual"]
logits_audio = logits_audio.transpose(0, 2)
logits_visual = logits_visual.transpose(0, 2)
logits_audio = logits_audio.reshape(-1, logits_audio.size(-1))
logits_visual = logits_visual.reshape(-1, logits_audio.size(-1))
return logits_audio,logits_visual
def get_targets(self, sample, net_output, expand_steps=True):
x_audio = net_output["x_audio"]
x_visual = net_output["x_visual"]
return x_audio.new_zeros(x_audio.size(1) * x_audio.size(2), dtype=torch.long), x_visual.new_zeros(x_visual.size(1) * x_visual.size(2), dtype=torch.long)
def get_extra_losses(self, net_output):
pen = []
if "prob_perplexity" in net_output:
if self.model_stage == 1:
pen.append(
(net_output["num_vars"] - net_output["prob_perplexity"])
/ net_output["num_vars"]
)
else:
for i in range(2):
# visual audio
pen.append(
(net_output["num_vars"] - net_output["prob_perplexity"][i])
/ net_output["num_vars"]
)
if "features_pen" in net_output:
pen.append(net_output["features_pen"])
return pen
def remove_pretraining_modules(self):
self.quantizer = None
self.project_q = None
self.target_glu = None
self.final_proj = None
class ConvFeatureExtractionModel(nn.Module):
def __init__(
self,
conv_layers: List[Tuple[int, int, int, int]],
dropout: float = 0.0,
mode: str = "default",
conv_bias: bool = False,
input_dim=1,
):
super().__init__()
assert mode in {"default", "layer_norm"}
def block(
n_in,
n_out,
kernel_size,
stride,
padding,
is_layer_norm=False,
is_group_norm=False,
conv_bias=False,
):
def make_conv():
conv = nn.Conv1d(n_in, n_out, kernel_size=kernel_size, stride=stride, padding=padding, bias=conv_bias)
nn.init.kaiming_normal_(conv.weight)
return conv
assert (
is_layer_norm and is_group_norm
) == False, "layer norm and group norm are exclusive"
if is_layer_norm:
return nn.Sequential(
make_conv(),
nn.Dropout(p=dropout),
nn.Sequential(
TransposeLast(),
Fp32LayerNorm(dim, elementwise_affine=True),
TransposeLast(),
),
nn.GELU(),
)
elif is_group_norm:
return nn.Sequential(
make_conv(),
nn.Dropout(p=dropout),
Fp32GroupNorm(dim, dim, affine=True),
nn.GELU(),
)
else:
return nn.Sequential(make_conv(), nn.Dropout(p=dropout), nn.GELU())
in_d = input_dim
self.conv_layers = nn.ModuleList()
for i, cl in enumerate(conv_layers):
assert len(cl) == 4, "invalid conv definition: " + str(cl)
(dim, kernel_size, stride, padding) = cl
self.conv_layers.append(
block(
in_d,
dim,
kernel_size,
stride,
padding,
is_layer_norm=mode == "layer_norm",
is_group_norm=mode == "default" and i == 0,
conv_bias=conv_bias,
)
)
in_d = dim
def forward(self, x):
# BxT -> BxCxT
if len(x.shape) == 2:
x = x.unsqueeze(1)
for conv in self.conv_layers:
if conv == self.conv_layers[-1]:
for name, module in conv.named_children():
if name =="2":
"""
0 Conv1d
1 Dropout
2 GELU
2 means GELU()
"""
before_GELU = x
x = module(x)
else:
x = conv(x)
return before_GELU, x
class TransformerEncoder(nn.Module):
def __init__(self, args):
super().__init__()
self.dropout = args.dropout
self.embedding_dim = args.encoder_embed_dim
self.pos_conv = nn.Conv1d(
self.embedding_dim,
self.embedding_dim,
kernel_size=args.conv_pos,
padding=args.conv_pos // 2,
groups=args.conv_pos_groups,
)
dropout = 0
std = math.sqrt((4 * (1.0 - dropout)) / (args.conv_pos * self.embedding_dim))
nn.init.normal_(self.pos_conv.weight, mean=0, std=std)
nn.init.constant_(self.pos_conv.bias, 0)
self.pos_conv = nn.utils.weight_norm(self.pos_conv, name="weight", dim=2)
self.pos_conv = nn.Sequential(self.pos_conv, SamePad(args.conv_pos), nn.GELU())
self.layers = nn.ModuleList(
[
TransformerSentenceEncoderLayer(
embedding_dim=self.embedding_dim,
ffn_embedding_dim=args.encoder_ffn_embed_dim,
num_attention_heads=args.encoder_attention_heads,
dropout=self.dropout,
attention_dropout=args.attention_dropout,
activation_dropout=args.activation_dropout,
activation_fn=args.activation_fn,
layer_norm_first=args.layer_norm_first,
)
for _ in range(args.encoder_layers)
]
)
self.layer_norm_first = args.layer_norm_first
self.layer_norm = LayerNorm(self.embedding_dim)
self.layerdrop = args.encoder_layerdrop
self.apply(init_bert_params)
def forward(self, x, padding_mask=None, layer=None):
x, layer_results = self.extract_features(x, padding_mask, layer)
if self.layer_norm_first and layer is None:
x = self.layer_norm(x)
return x, layer_results
def extract_features(self, x, padding_mask=None, tgt_layer=None):
if padding_mask is not None:
x = index_put(x, padding_mask, 0)
x_conv = self.pos_conv(x.transpose(1, 2))
x_conv = x_conv.transpose(1, 2)
x = x + x_conv
if not self.layer_norm_first:
x = self.layer_norm(x)
x = F.dropout(x, p=self.dropout, training=self.training)
# B x T x C -> T x B x C
x = x.transpose(0, 1)
layer_results = []
r = None
for i, layer in enumerate(self.layers):
dropout_probability = np.random.random()
if not self.training or (dropout_probability > self.layerdrop):
x, z = layer(x, self_attn_padding_mask=padding_mask, need_weights=False)
if tgt_layer is not None:
layer_results.append((x, z))
if i == tgt_layer:
r = x
break
if r is not None:
x = r
# T x B x C -> B x T x C
x = x.transpose(0, 1)
return x, layer_results
def max_positions(self):
"""Maximum output length supported by the encoder."""
return self.args.max_positions
def upgrade_state_dict_named(self, state_dict, name):
"""Upgrade a (possibly old) state dict for new versions of fairseq."""
return state_dict
class TransformerSentenceEncoderLayer(nn.Module):
"""
Implements a Transformer Encoder Layer used in BERT/XLM style pre-trained
models.
"""
def __init__(
self,
embedding_dim: float = 768,
ffn_embedding_dim: float = 3072,
num_attention_heads: float = 8,
dropout: float = 0.1,
attention_dropout: float = 0.1,
activation_dropout: float = 0.1,
activation_fn: str = "relu",
layer_norm_first: bool = False,
) -> None:
super().__init__()
# Initialize parameters
self.embedding_dim = embedding_dim
self.dropout = dropout
self.activation_dropout = activation_dropout
# Initialize blocks
self.activation_fn = utils.get_activation_fn(activation_fn)
self.self_attn = MultiheadAttention(
self.embedding_dim,
num_attention_heads,
dropout=attention_dropout,
self_attention=True,
)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(self.activation_dropout)
self.dropout3 = nn.Dropout(dropout)
self.layer_norm_first = layer_norm_first
# layer norm associated with the self attention layer
self.self_attn_layer_norm = LayerNorm(self.embedding_dim)
self.fc1 = nn.Linear(self.embedding_dim, ffn_embedding_dim)
self.fc2 = nn.Linear(ffn_embedding_dim, self.embedding_dim)
# layer norm associated with the position wise feed-forward NN
self.final_layer_norm = LayerNorm(self.embedding_dim)
def forward(
self,
x: torch.Tensor,
self_attn_mask: torch.Tensor = None,
self_attn_padding_mask: torch.Tensor = None,
need_weights: bool = False,
att_args=None,
):
"""
LayerNorm is applied either before or after the self-attention/ffn
modules similar to the original Transformer imlementation.
"""
residual = x
if self.layer_norm_first:
x = self.self_attn_layer_norm(x)
x, attn = self.self_attn(
query=x,
key=x,
value=x,
key_padding_mask=self_attn_padding_mask,
attn_mask=self_attn_mask,
)
x = self.dropout1(x)
x = residual + x
residual = x
x = self.final_layer_norm(x)
x = self.activation_fn(self.fc1(x))
x = self.dropout2(x)
x = self.fc2(x)
x = self.dropout3(x)
x = residual + x
else:
x, attn = self.self_attn(
query=x,
key=x,
value=x,
key_padding_mask=self_attn_padding_mask,
)
x = self.dropout1(x)
x = residual + x
x = self.self_attn_layer_norm(x)
residual = x
x = self.activation_fn(self.fc1(x))
x = self.dropout2(x)
x = self.fc2(x)
x = self.dropout3(x)
x = residual + x
x = self.final_layer_norm(x)
return x, attn
class MoCo(nn.Module):
def __init__(self, replace=False):
super(MoCo, self).__init__()
self.encoder = nn.Sequential()
self.replace = replace
for name, module in resnet50().named_children():
"""
name:conv1
name:bn1
name:relu
name:maxpool
name:layer1
name:layer2
name:layer3
name:layer4
name:avgpool
name:fc
"""
if name == 'conv1':
if self.replace:
module = nn.Conv3d(3,64,kernel_size=(7, 7, 7), stride=(1, 2, 2), padding=(3, 3, 3), bias=False)
self.encoder.add_module(name, module)
elif name != 'fc':
self.encoder.add_module(name, module)
# else:
# self.ResNet.append(nn.Linear(in_features=2048, out_features=128, bias=True))
def forward(self, x):
x = self.encoder.conv1(x)
if self.replace:
x = x.transpose(1,2)
x = x.reshape(-1,x.size(2),x.size(3),x.size(4))
x = self.encoder.bn1(x)
x = self.encoder.relu(x)
x = self.encoder.maxpool(x)
x = self.encoder.layer1(x)
x = self.encoder.layer2(x)
x = self.encoder.layer3(x)
x = self.encoder.layer4(x)
x = self.encoder.avgpool(x)
feature = torch.flatten(x, start_dim=1)
return F.normalize(feature, dim=-1)
|
[
"torch.nn.Dropout",
"fairseq.modules.SamePad",
"torch.nn.GLU",
"torch.nn.functional.dropout",
"torch.cat",
"fairseq.modules.Fp32GroupNorm",
"torch.nn.init.constant_",
"torch.arange",
"torch.nn.utils.weight_norm",
"torch.nn.functional.normalize",
"torch.no_grad",
"os.path.join",
"torch.flatten",
"torch.nn.init.kaiming_normal_",
"fairseq.utils.index_put",
"torch.nn.Conv3d",
"torch.load",
"torch.nn.Conv1d",
"fairseq.utils.get_activation_fn",
"torch.FloatTensor",
"fairseq.modules.TransposeLast",
"fairseq.modules.Fp32LayerNorm",
"fairseq.modules.LayerNorm",
"torch.nn.Linear",
"torch.zeros",
"fairseq.data.data_utils.compute_mask_indices",
"torch.randint",
"math.sqrt",
"torch.nn.ModuleList",
"torch.split",
"fairseq.utils.get_available_activation_fns",
"dataclasses.field",
"fairseq.models.register_model",
"torch.nn.GELU",
"torch.floor",
"torchvision.models.resnet.resnet50",
"fairseq.dataclass.ChoiceEnum",
"torch.from_numpy",
"torch.nn.ReLU",
"torch.stack",
"torch.nn.Sequential",
"fairseq.modules.GumbelVectorQuantizer",
"fairseq.modules.MultiheadAttention",
"fairseq.modules.GradMultiply.apply",
"torch.nn.init.normal_",
"numpy.random.random",
"fairseq.utils.is_xla_tensor",
"fairseq.utils.buffered_arange",
"torch.tensor"
] |
[((963, 1000), 'fairseq.dataclass.ChoiceEnum', 'ChoiceEnum', (["['default', 'layer_norm']"], {}), "(['default', 'layer_norm'])\n", (973, 1000), False, 'from fairseq.dataclass import ChoiceEnum, FairseqDataclass\n'), ((1032, 1086), 'fairseq.dataclass.ChoiceEnum', 'ChoiceEnum', (["['static', 'uniform', 'normal', 'poisson']"], {}), "(['static', 'uniform', 'normal', 'poisson'])\n", (1042, 1086), False, 'from fairseq.dataclass import ChoiceEnum, FairseqDataclass\n'), ((10150, 10198), 'fairseq.models.register_model', 'register_model', (['"""mm2vec"""'], {'dataclass': 'MM2VecConfig'}), "('mm2vec', dataclass=MM2VecConfig)\n", (10164, 10198), False, 'from fairseq.models import BaseFairseqModel, register_model\n'), ((1161, 1333), 'dataclasses.field', 'field', ([], {'default': '(1)', 'metadata': "{'help':\n 'model_stage=1 for training visual feature extractor only,model_stage=2 for pretrain on all subnetmodel_stage=? for fine-tune'\n }"}), "(default=1, metadata={'help':\n 'model_stage=1 for training visual feature extractor only,model_stage=2 for pretrain on all subnetmodel_stage=? for fine-tune'\n })\n", (1166, 1333), False, 'from dataclasses import dataclass, field\n'), ((1452, 1691), 'dataclasses.field', 'field', ([], {'default': '"""default"""', 'metadata': "{'help':\n 'mode for feature extractor. default has a single group norm with d groups in the first conv block, whereas layer_norm has layer norms in every block (meant to use with normalize=True)'\n }"}), "(default='default', metadata={'help':\n 'mode for feature extractor. default has a single group norm with d groups in the first conv block, whereas layer_norm has layer norms in every block (meant to use with normalize=True)'\n })\n", (1457, 1691), False, 'from dataclasses import dataclass, field\n'), ((1784, 1861), 'dataclasses.field', 'field', ([], {'default': '(12)', 'metadata': "{'help': 'num encoder layers in the transformer'}"}), "(default=12, metadata={'help': 'num encoder layers in the transformer'})\n", (1789, 1861), False, 'from dataclasses import dataclass, field\n'), ((1905, 1973), 'dataclasses.field', 'field', ([], {'default': '(768)', 'metadata': "{'help': 'encoder embedding dimension'}"}), "(default=768, metadata={'help': 'encoder embedding dimension'})\n", (1910, 1973), False, 'from dataclasses import dataclass, field\n'), ((2021, 2098), 'dataclasses.field', 'field', ([], {'default': '(3072)', 'metadata': "{'help': 'encoder embedding dimension for FFN'}"}), "(default=3072, metadata={'help': 'encoder embedding dimension for FFN'})\n", (2026, 2098), False, 'from dataclasses import dataclass, field\n'), ((2148, 2215), 'dataclasses.field', 'field', ([], {'default': '(12)', 'metadata': "{'help': 'num encoder attention heads'}"}), "(default=12, metadata={'help': 'num encoder attention heads'})\n", (2153, 2215), False, 'from dataclasses import dataclass, field\n'), ((2300, 2370), 'dataclasses.field', 'field', ([], {'default': '"""gelu"""', 'metadata': "{'help': 'activation function to use'}"}), "(default='gelu', metadata={'help': 'activation function to use'})\n", (2305, 2370), False, 'from dataclasses import dataclass, field\n'), ((2422, 2507), 'dataclasses.field', 'field', ([], {'default': '(0.1)', 'metadata': "{'help': 'dropout probability for the transformer'}"}), "(default=0.1, metadata={'help': 'dropout probability for the transformer'}\n )\n", (2427, 2507), False, 'from dataclasses import dataclass, field\n'), ((2548, 2634), 'dataclasses.field', 'field', ([], {'default': '(0.1)', 'metadata': "{'help': 'dropout probability for attention weights'}"}), "(default=0.1, metadata={'help':\n 'dropout probability for attention weights'})\n", (2553, 2634), False, 'from dataclasses import dataclass, field\n'), ((2677, 2765), 'dataclasses.field', 'field', ([], {'default': '(0.0)', 'metadata': "{'help': 'dropout probability after activation in FFN'}"}), "(default=0.0, metadata={'help':\n 'dropout probability after activation in FFN'})\n", (2682, 2765), False, 'from dataclasses import dataclass, field\n'), ((2807, 2895), 'dataclasses.field', 'field', ([], {'default': '(0.0)', 'metadata': "{'help': 'probability of dropping a tarnsformer layer'}"}), "(default=0.0, metadata={'help':\n 'probability of dropping a tarnsformer layer'})\n", (2812, 2895), False, 'from dataclasses import dataclass, field\n'), ((2933, 3025), 'dataclasses.field', 'field', ([], {'default': '(0.0)', 'metadata': "{'help': 'dropout to apply to the input (after feat extr)'}"}), "(default=0.0, metadata={'help':\n 'dropout to apply to the input (after feat extr)'})\n", (2938, 3025), False, 'from dataclasses import dataclass, field\n'), ((3075, 3170), 'dataclasses.field', 'field', ([], {'default': '(0.0)', 'metadata': "{'help': 'dropout to apply to the features (after feat extr)'}"}), "(default=0.0, metadata={'help':\n 'dropout to apply to the features (after feat extr)'})\n", (3080, 3170), False, 'from dataclasses import dataclass, field\n'), ((3212, 3358), 'dataclasses.field', 'field', ([], {'default': '(0)', 'metadata': "{'help':\n 'project final representations and targets to this many dimensions.set to encoder_embed_dim is <= 0'\n }"}), "(default=0, metadata={'help':\n 'project final representations and targets to this many dimensions.set to encoder_embed_dim is <= 0'\n })\n", (3217, 3358), False, 'from dataclasses import dataclass, field\n'), ((3439, 3526), 'dataclasses.field', 'field', ([], {'default': '(False)', 'metadata': "{'help': 'apply layernorm first in the transformer'}"}), "(default=False, metadata={'help':\n 'apply layernorm first in the transformer'})\n", (3444, 3526), False, 'from dataclasses import dataclass, field\n'), ((3574, 3841), 'dataclasses.field', 'field', ([], {'default': '"""[(512, 10, 5, 0)] + [(512, 3, 2, 0)] * 4 + [(512, 2, 2, 0)] + [(512, 2, 2, 0)]"""', 'metadata': "{'help':\n 'string describing convolutional feature extraction layers in form of a python list that contains [(dim, kernel_size, stride), ...]'\n }"}), "(default=\n '[(512, 10, 5, 0)] + [(512, 3, 2, 0)] * 4 + [(512, 2, 2, 0)] + [(512, 2, 2, 0)]'\n , metadata={'help':\n 'string describing convolutional feature extraction layers in form of a python list that contains [(dim, kernel_size, stride), ...]'\n })\n", (3579, 3841), False, 'from dataclasses import dataclass, field\n'), ((3905, 3976), 'dataclasses.field', 'field', ([], {'default': '(False)', 'metadata': "{'help': 'include bias in conv encoder'}"}), "(default=False, metadata={'help': 'include bias in conv encoder'})\n", (3910, 3976), False, 'from dataclasses import dataclass, field\n'), ((4015, 4087), 'dataclasses.field', 'field', ([], {'default': '(0.1)', 'metadata': "{'help': 'temperature to divide logits by'}"}), "(default=0.1, metadata={'help': 'temperature to divide logits by'})\n", (4020, 4087), False, 'from dataclasses import dataclass, field\n'), ((4131, 4195), 'dataclasses.field', 'field', ([], {'default': '(False)', 'metadata': "{'help': 'use quantized targets'}"}), "(default=False, metadata={'help': 'use quantized targets'})\n", (4136, 4195), False, 'from dataclasses import dataclass, field\n'), ((4237, 4300), 'dataclasses.field', 'field', ([], {'default': '(False)', 'metadata': "{'help': 'use quantized inputs'}"}), "(default=False, metadata={'help': 'use quantized inputs'})\n", (4242, 4300), False, 'from dataclasses import dataclass, field\n'), ((4342, 4430), 'dataclasses.field', 'field', ([], {'default': '(False)', 'metadata': "{'help': 'use same quantizer for inputs and targets'}"}), "(default=False, metadata={'help':\n 'use same quantizer for inputs and targets'})\n", (4347, 4430), False, 'from dataclasses import dataclass, field\n'), ((4464, 4539), 'dataclasses.field', 'field', ([], {'default': '(False)', 'metadata': "{'help': 'adds projection + glu to targets'}"}), "(default=False, metadata={'help': 'adds projection + glu to targets'})\n", (4469, 4539), False, 'from dataclasses import dataclass, field\n'), ((4585, 4674), 'dataclasses.field', 'field', ([], {'default': '(1.0)', 'metadata': "{'help': 'multiply feature extractor var grads by this'}"}), "(default=1.0, metadata={'help':\n 'multiply feature extractor var grads by this'})\n", (4590, 4674), False, 'from dataclasses import dataclass, field\n'), ((4712, 4777), 'dataclasses.field', 'field', ([], {'default': '(1)', 'metadata': "{'help': 'number of quantizer layers'}"}), "(default=1, metadata={'help': 'number of quantizer layers'})\n", (4717, 4777), False, 'from dataclasses import dataclass, field\n'), ((4829, 4937), 'dataclasses.field', 'field', ([], {'default': '(3)', 'metadata': "{'help': 'dimensionality increase for inner quantizer layers (if depth > 1)'}"}), "(default=3, metadata={'help':\n 'dimensionality increase for inner quantizer layers (if depth > 1)'})\n", (4834, 4937), False, 'from dataclasses import dataclass, field\n'), ((5002, 5105), 'dataclasses.field', 'field', ([], {'default': '(320)', 'metadata': "{'help': 'number of latent variables V in each group of the codebook'}"}), "(default=320, metadata={'help':\n 'number of latent variables V in each group of the codebook'})\n", (5007, 5105), False, 'from dataclasses import dataclass, field\n'), ((5150, 5247), 'dataclasses.field', 'field', ([], {'default': '(2)', 'metadata': "{'help': 'number of groups G of latent variables in the codebook'}"}), "(default=2, metadata={'help':\n 'number of groups G of latent variables in the codebook'})\n", (5155, 5247), False, 'from dataclasses import dataclass, field\n'), ((5289, 5432), 'dataclasses.field', 'field', ([], {'default': '(0)', 'metadata': "{'help':\n 'if > 0, uses this dimensionality for latent variables. otherwise uses final_dim / latent_groups'\n }"}), "(default=0, metadata={'help':\n 'if > 0, uses this dimensionality for latent variables. otherwise uses final_dim / latent_groups'\n })\n", (5294, 5432), False, 'from dataclasses import dataclass, field\n'), ((5522, 5573), 'dataclasses.field', 'field', ([], {'default': '(10)', 'metadata': "{'help': 'mask length'}"}), "(default=10, metadata={'help': 'mask length'})\n", (5527, 5573), False, 'from dataclasses import dataclass, field\n'), ((5597, 5685), 'dataclasses.field', 'field', ([], {'default': '(0.65)', 'metadata': "{'help': 'probability of replacing a token with mask'}"}), "(default=0.65, metadata={'help':\n 'probability of replacing a token with mask'})\n", (5602, 5685), False, 'from dataclasses import dataclass, field\n'), ((5747, 5818), 'dataclasses.field', 'field', ([], {'default': '"""static"""', 'metadata': "{'help': 'how to choose mask length'}"}), "(default='static', metadata={'help': 'how to choose mask length'})\n", (5752, 5818), False, 'from dataclasses import dataclass, field\n'), ((5857, 6000), 'dataclasses.field', 'field', ([], {'default': '(0)', 'metadata': "{'help':\n 'secondary mask argument (used for more complex distributions), see help in compute_mask_indices'\n }"}), "(default=0, metadata={'help':\n 'secondary mask argument (used for more complex distributions), see help in compute_mask_indices'\n })\n", (5862, 6000), False, 'from dataclasses import dataclass, field\n'), ((6080, 6156), 'dataclasses.field', 'field', ([], {'default': '(False)', 'metadata': "{'help': 'whether to allow masks to overlap'}"}), "(default=False, metadata={'help': 'whether to allow masks to overlap'})\n", (6085, 6156), False, 'from dataclasses import dataclass, field\n'), ((6197, 6290), 'dataclasses.field', 'field', ([], {'default': '(1)', 'metadata': "{'help': 'min space between spans (if no overlap is enabled)'}"}), "(default=1, metadata={'help':\n 'min space between spans (if no overlap is enabled)'})\n", (6202, 6290), False, 'from dataclasses import dataclass, field\n'), ((6364, 6450), 'dataclasses.field', 'field', ([], {'default': '(10)', 'metadata': "{'help': 'length of the mask for features (channels)'}"}), "(default=10, metadata={'help':\n 'length of the mask for features (channels)'})\n", (6369, 6450), False, 'from dataclasses import dataclass, field\n'), ((6492, 6578), 'dataclasses.field', 'field', ([], {'default': '(0.0)', 'metadata': "{'help': 'probability of replacing a feature with 0'}"}), "(default=0.0, metadata={'help':\n 'probability of replacing a feature with 0'})\n", (6497, 6578), False, 'from dataclasses import dataclass, field\n'), ((6686, 6781), 'dataclasses.field', 'field', ([], {'default': '"""static"""', 'metadata': "{'help': 'how to choose mask length for channel masking'}"}), "(default='static', metadata={'help':\n 'how to choose mask length for channel masking'})\n", (6691, 6781), False, 'from dataclasses import dataclass, field\n'), ((6833, 6977), 'dataclasses.field', 'field', ([], {'default': '(0)', 'metadata': "{'help':\n 'secondary mask argument (used for more complex distributions), see help in compute_mask_indicesh'\n }"}), "(default=0, metadata={'help':\n 'secondary mask argument (used for more complex distributions), see help in compute_mask_indicesh'\n })\n", (6838, 6977), False, 'from dataclasses import dataclass, field\n'), ((7065, 7153), 'dataclasses.field', 'field', ([], {'default': '(False)', 'metadata': "{'help': 'whether to allow channel masks to overlap'}"}), "(default=False, metadata={'help':\n 'whether to allow channel masks to overlap'})\n", (7070, 7153), False, 'from dataclasses import dataclass, field\n'), ((7198, 7291), 'dataclasses.field', 'field', ([], {'default': '(1)', 'metadata': "{'help': 'min space between spans (if no overlap is enabled)'}"}), "(default=1, metadata={'help':\n 'min space between spans (if no overlap is enabled)'})\n", (7203, 7291), False, 'from dataclasses import dataclass, field\n'), ((7362, 7455), 'dataclasses.field', 'field', ([], {'default': '(100)', 'metadata': "{'help': 'number of negative examples from the same sample'}"}), "(default=100, metadata={'help':\n 'number of negative examples from the same sample'})\n", (7367, 7455), False, 'from dataclasses import dataclass, field\n'), ((7513, 7616), 'dataclasses.field', 'field', ([], {'default': '(False)', 'metadata': "{'help': 'sample negatives from everywhere, not just masked states'}"}), "(default=False, metadata={'help':\n 'sample negatives from everywhere, not just masked states'})\n", (7518, 7616), False, 'from dataclasses import dataclass, field\n'), ((7670, 7760), 'dataclasses.field', 'field', ([], {'default': '(0)', 'metadata': "{'help': 'number of negative examples from the any sample'}"}), "(default=0, metadata={'help':\n 'number of negative examples from the any sample'})\n", (7675, 7760), False, 'from dataclasses import dataclass, field\n'), ((7801, 7876), 'dataclasses.field', 'field', ([], {'default': '(0)', 'metadata': "{'help': 'number of negative examples codebook'}"}), "(default=0, metadata={'help': 'number of negative examples codebook'})\n", (7806, 7876), False, 'from dataclasses import dataclass, field\n'), ((7940, 8042), 'dataclasses.field', 'field', ([], {'default': '(128)', 'metadata': "{'help': 'number of filters for convolutional positional embeddings'}"}), "(default=128, metadata={'help':\n 'number of filters for convolutional positional embeddings'})\n", (7945, 8042), False, 'from dataclasses import dataclass, field\n'), ((8089, 8188), 'dataclasses.field', 'field', ([], {'default': '(16)', 'metadata': "{'help': 'number of groups for convolutional positional embedding'}"}), "(default=16, metadata={'help':\n 'number of groups for convolutional positional embedding'})\n", (8094, 8188), False, 'from dataclasses import dataclass, field\n'), ((8255, 8406), 'dataclasses.field', 'field', ([], {'default': '(2, 0.5, 0.999995)', 'metadata': "{'help':\n 'temperature for latent variable sampling. can be tuple of 3 values (start, end, decay)'\n }"}), "(default=(2, 0.5, 0.999995), metadata={'help':\n 'temperature for latent variable sampling. can be tuple of 3 values (start, end, decay)'\n })\n", (8260, 8406), False, 'from dataclasses import dataclass, field\n'), ((8515, 8764), 'dataclasses.field', 'field', ([], {'default': '"""[(512, 11, 1, 5)] * 3 + [(1024, 11, 1, 5)]"""', 'metadata': "{'help':\n 'string describing visual-subnet convolutional feature extraction layers in form of a python list that contains [(dim, kernel_size, stride, padding), ...]'\n }"}), "(default='[(512, 11, 1, 5)] * 3 + [(1024, 11, 1, 5)]', metadata={\n 'help':\n 'string describing visual-subnet convolutional feature extraction layers in form of a python list that contains [(dim, kernel_size, stride, padding), ...]'\n })\n", (8520, 8764), False, 'from dataclasses import dataclass, field\n'), ((8847, 8921), 'dataclasses.field', 'field', ([], {'default': '(112)', 'metadata': "{'help': 'number of dims of visual pictures'}"}), "(default=112, metadata={'help': 'number of dims of visual pictures'})\n", (8852, 8921), False, 'from dataclasses import dataclass, field\n'), ((8975, 9042), 'dataclasses.field', 'field', ([], {'default': '(2048)', 'metadata': "{'help': 'number of dims after MoCo'}"}), "(default=2048, metadata={'help': 'number of dims after MoCo'})\n", (8980, 9042), False, 'from dataclasses import dataclass, field\n'), ((9092, 9168), 'dataclasses.field', 'field', ([], {'default': '(512)', 'metadata': "{'help': 'output dimension of projection head'}"}), "(default=512, metadata={'help': 'output dimension of projection head'})\n", (9097, 9168), False, 'from dataclasses import dataclass, field\n'), ((9236, 9357), 'dataclasses.field', 'field', ([], {'default': '"""./checkpoints-mm-2/"""', 'metadata': "{'help': 'path to mm2vec stage 1 last model or stage 2 process model'}"}), "(default='./checkpoints-mm-2/', metadata={'help':\n 'path to mm2vec stage 1 last model or stage 2 process model'})\n", (9241, 9357), False, 'from dataclasses import dataclass, field\n'), ((9448, 9514), 'dataclasses.field', 'field', ([], {'default': '(0.5)', 'metadata': "{'help': 'weight for audio_features'}"}), "(default=0.5, metadata={'help': 'weight for audio_features'})\n", (9453, 9514), False, 'from dataclasses import dataclass, field\n'), ((9585, 9651), 'dataclasses.field', 'field', ([], {'default': '(0.5)', 'metadata': "{'help': 'weight for audio_features'}"}), "(default=0.5, metadata={'help': 'weight for audio_features'})\n", (9590, 9651), False, 'from dataclasses import dataclass, field\n'), ((9731, 9806), 'dataclasses.field', 'field', ([], {'default': '(False)', 'metadata': "{'help': 'remove quantizer pretrain params'}"}), "(default=False, metadata={'help': 'remove quantizer pretrain params'})\n", (9736, 9806), False, 'from dataclasses import dataclass, field\n'), ((9888, 9963), 'dataclasses.field', 'field', ([], {'default': '(False)', 'metadata': "{'help': 'freeze quantizer pretrain params'}"}), "(default=False, metadata={'help': 'freeze quantizer pretrain params'})\n", (9893, 9963), False, 'from dataclasses import dataclass, field\n'), ((10043, 10130), 'dataclasses.field', 'field', ([], {'default': '(False)', 'metadata': "{'help': 'replace first conv2d in MoCo with conv3d'}"}), "(default=False, metadata={'help':\n 'replace first conv2d in MoCo with conv3d'})\n", (10048, 10130), False, 'from dataclasses import dataclass, field\n'), ((2260, 2296), 'fairseq.utils.get_available_activation_fns', 'utils.get_available_activation_fns', ([], {}), '()\n', (2294, 2296), False, 'from fairseq import utils\n'), ((12796, 12825), 'torch.nn.Dropout', 'nn.Dropout', (['cfg.dropout_input'], {}), '(cfg.dropout_input)\n', (12806, 12825), True, 'import torch.nn as nn\n'), ((12858, 12890), 'torch.nn.Dropout', 'nn.Dropout', (['cfg.dropout_features'], {}), '(cfg.dropout_features)\n', (12868, 12890), True, 'import torch.nn as nn\n'), ((15158, 15189), 'fairseq.modules.LayerNorm', 'LayerNorm', (['self.audio_embed_dim'], {}), '(self.audio_embed_dim)\n', (15167, 15189), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((15472, 15515), 'torch.nn.Linear', 'nn.Linear', (['cfg.encoder_embed_dim', 'final_dim'], {}), '(cfg.encoder_embed_dim, final_dim)\n', (15481, 15515), True, 'import torch.nn as nn\n'), ((23459, 23491), 'torch.cat', 'torch.cat', (['[y, negatives]'], {'dim': '(0)'}), '([y, negatives], dim=0)\n', (23468, 23491), False, 'import torch\n'), ((25168, 25244), 'torch.tensor', 'torch.tensor', (['[]'], {'dtype': 'visual_features.dtype', 'device': 'visual_features.device'}), '([], dtype=visual_features.dtype, device=visual_features.device)\n', (25180, 25244), False, 'import torch\n'), ((43875, 43890), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (43888, 43890), True, 'import torch.nn as nn\n'), ((45337, 45474), 'torch.nn.Conv1d', 'nn.Conv1d', (['self.embedding_dim', 'self.embedding_dim'], {'kernel_size': 'args.conv_pos', 'padding': '(args.conv_pos // 2)', 'groups': 'args.conv_pos_groups'}), '(self.embedding_dim, self.embedding_dim, kernel_size=args.conv_pos,\n padding=args.conv_pos // 2, groups=args.conv_pos_groups)\n', (45346, 45474), True, 'import torch.nn as nn\n'), ((45576, 45645), 'math.sqrt', 'math.sqrt', (['(4 * (1.0 - dropout) / (args.conv_pos * self.embedding_dim))'], {}), '(4 * (1.0 - dropout) / (args.conv_pos * self.embedding_dim))\n', (45585, 45645), False, 'import math\n'), ((45656, 45710), 'torch.nn.init.normal_', 'nn.init.normal_', (['self.pos_conv.weight'], {'mean': '(0)', 'std': 'std'}), '(self.pos_conv.weight, mean=0, std=std)\n', (45671, 45710), True, 'import torch.nn as nn\n'), ((45719, 45759), 'torch.nn.init.constant_', 'nn.init.constant_', (['self.pos_conv.bias', '(0)'], {}), '(self.pos_conv.bias, 0)\n', (45736, 45759), True, 'import torch.nn as nn\n'), ((45785, 45842), 'torch.nn.utils.weight_norm', 'nn.utils.weight_norm', (['self.pos_conv'], {'name': '"""weight"""', 'dim': '(2)'}), "(self.pos_conv, name='weight', dim=2)\n", (45805, 45842), True, 'import torch.nn as nn\n'), ((46679, 46708), 'fairseq.modules.LayerNorm', 'LayerNorm', (['self.embedding_dim'], {}), '(self.embedding_dim)\n', (46688, 46708), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((47403, 47455), 'torch.nn.functional.dropout', 'F.dropout', (['x'], {'p': 'self.dropout', 'training': 'self.training'}), '(x, p=self.dropout, training=self.training)\n', (47412, 47455), True, 'import torch.nn.functional as F\n'), ((49190, 49228), 'fairseq.utils.get_activation_fn', 'utils.get_activation_fn', (['activation_fn'], {}), '(activation_fn)\n', (49213, 49228), False, 'from fairseq import utils\n'), ((49254, 49366), 'fairseq.modules.MultiheadAttention', 'MultiheadAttention', (['self.embedding_dim', 'num_attention_heads'], {'dropout': 'attention_dropout', 'self_attention': '(True)'}), '(self.embedding_dim, num_attention_heads, dropout=\n attention_dropout, self_attention=True)\n', (49272, 49366), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((49446, 49465), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (49456, 49465), True, 'import torch.nn as nn\n'), ((49490, 49525), 'torch.nn.Dropout', 'nn.Dropout', (['self.activation_dropout'], {}), '(self.activation_dropout)\n', (49500, 49525), True, 'import torch.nn as nn\n'), ((49550, 49569), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (49560, 49569), True, 'import torch.nn as nn\n'), ((49719, 49748), 'fairseq.modules.LayerNorm', 'LayerNorm', (['self.embedding_dim'], {}), '(self.embedding_dim)\n', (49728, 49748), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((49768, 49816), 'torch.nn.Linear', 'nn.Linear', (['self.embedding_dim', 'ffn_embedding_dim'], {}), '(self.embedding_dim, ffn_embedding_dim)\n', (49777, 49816), True, 'import torch.nn as nn\n'), ((49836, 49884), 'torch.nn.Linear', 'nn.Linear', (['ffn_embedding_dim', 'self.embedding_dim'], {}), '(ffn_embedding_dim, self.embedding_dim)\n', (49845, 49884), True, 'import torch.nn as nn\n'), ((49989, 50018), 'fairseq.modules.LayerNorm', 'LayerNorm', (['self.embedding_dim'], {}), '(self.embedding_dim)\n', (49998, 50018), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((51722, 51737), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (51735, 51737), True, 'import torch.nn as nn\n'), ((53000, 53029), 'torch.flatten', 'torch.flatten', (['x'], {'start_dim': '(1)'}), '(x, start_dim=1)\n', (53013, 53029), False, 'import torch\n'), ((53045, 53073), 'torch.nn.functional.normalize', 'F.normalize', (['feature'], {'dim': '(-1)'}), '(feature, dim=-1)\n', (53056, 53073), True, 'import torch.nn.functional as F\n'), ((11519, 11573), 'torch.nn.Linear', 'nn.Linear', (['self.audio_embed_dim', 'cfg.encoder_embed_dim'], {}), '(self.audio_embed_dim, cfg.encoder_embed_dim)\n', (11528, 11573), True, 'import torch.nn as nn\n'), ((11877, 11886), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (11884, 11886), True, 'import torch.nn as nn\n'), ((13514, 13781), 'fairseq.modules.GumbelVectorQuantizer', 'GumbelVectorQuantizer', ([], {'dim': 'self.audio_embed_dim', 'num_vars': 'cfg.latent_vars', 'temp': 'cfg.latent_temp', 'groups': 'cfg.latent_groups', 'combine_groups': '(False)', 'vq_dim': 'vq_dim', 'time_first': '(True)', 'weight_proj_depth': 'cfg.quantizer_depth', 'weight_proj_factor': 'cfg.quantizer_factor'}), '(dim=self.audio_embed_dim, num_vars=cfg.latent_vars,\n temp=cfg.latent_temp, groups=cfg.latent_groups, combine_groups=False,\n vq_dim=vq_dim, time_first=True, weight_proj_depth=cfg.quantizer_depth,\n weight_proj_factor=cfg.quantizer_factor)\n', (13535, 13781), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((13980, 14008), 'torch.nn.Linear', 'nn.Linear', (['vq_dim', 'final_dim'], {}), '(vq_dim, final_dim)\n', (13989, 14008), True, 'import torch.nn as nn\n'), ((14052, 14084), 'torch.nn.Linear', 'nn.Linear', (['self.embed', 'final_dim'], {}), '(self.embed, final_dim)\n', (14061, 14084), True, 'import torch.nn as nn\n'), ((18668, 18901), 'fairseq.data.data_utils.compute_mask_indices', 'compute_mask_indices', (['(B, C)', 'None', 'self.mask_channel_prob', 'self.mask_channel_length', 'self.mask_channel_selection', 'self.mask_channel_other'], {'no_overlap': 'self.no_mask_channel_overlap', 'min_space': 'self.mask_channel_min_space'}), '((B, C), None, self.mask_channel_prob, self.\n mask_channel_length, self.mask_channel_selection, self.\n mask_channel_other, no_overlap=self.no_mask_channel_overlap, min_space=\n self.mask_channel_min_space)\n', (18688, 18901), False, 'from fairseq.data.data_utils import compute_mask_indices\n'), ((19865, 19912), 'fairseq.utils.index_put', 'index_put', (['x_audio', 'mask_indices', 'self.mask_emb'], {}), '(x_audio, mask_indices, self.mask_emb)\n', (19874, 19912), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((19936, 19984), 'fairseq.utils.index_put', 'index_put', (['x_visual', 'mask_indices', 'self.mask_emb'], {}), '(x_visual, mask_indices, self.mask_emb)\n', (19945, 19984), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((20865, 20908), 'fairseq.utils.index_put', 'index_put', (['x_audio', 'mask_channel_indices', '(0)'], {}), '(x_audio, mask_channel_indices, 0)\n', (20874, 20908), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((20932, 20976), 'fairseq.utils.index_put', 'index_put', (['x_visual', 'mask_channel_indices', '(0)'], {}), '(x_visual, mask_channel_indices, 0)\n', (20941, 20976), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((21504, 21519), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (21517, 21519), False, 'import torch\n'), ((22768, 22812), 'torch.cat', 'torch.cat', (['[neg_idxs, cross_neg_idxs]'], {'dim': '(1)'}), '([neg_idxs, cross_neg_idxs], dim=1)\n', (22777, 22812), False, 'import torch\n'), ((23636, 23657), 'fairseq.utils.is_xla_tensor', 'is_xla_tensor', (['logits'], {}), '(logits)\n', (23649, 23657), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((23983, 24033), 'fairseq.utils.index_put', 'index_put', (['logits[1:]', 'neg_is_pos', 'self._inftensor'], {}), '(logits[1:], neg_is_pos, self._inftensor)\n', (23992, 24033), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((24311, 24365), 'torch.floor', 'torch.floor', (['((input_length - kernel_size) / stride + 1)'], {}), '((input_length - kernel_size) / stride + 1)\n', (24322, 24365), False, 'import torch\n'), ((26504, 26531), 'torch.cat', 'torch.cat', (['visual_source', '(1)'], {}), '(visual_source, 1)\n', (26513, 26531), False, 'import torch\n'), ((26559, 26611), 'torch.split', 'torch.split', (['visual_source', 'self.visual_input_dim', '(1)'], {}), '(visual_source, self.visual_input_dim, 1)\n', (26570, 26611), False, 'import torch\n'), ((26640, 26664), 'torch.cat', 'torch.cat', (['visual_source'], {}), '(visual_source)\n', (26649, 26664), False, 'import torch\n'), ((27368, 27394), 'torch.stack', 'torch.stack', (['visual_source'], {}), '(visual_source)\n', (27379, 27394), False, 'import torch\n'), ((27423, 27475), 'torch.split', 'torch.split', (['visual_source', 'self.visual_input_dim', '(1)'], {}), '(visual_source, self.visual_input_dim, 1)\n', (27434, 27475), False, 'import torch\n'), ((27504, 27528), 'torch.cat', 'torch.cat', (['visual_source'], {}), '(visual_source)\n', (27513, 27528), False, 'import torch\n'), ((30776, 30876), 'torch.zeros', 'torch.zeros', (['audio_features.shape[:2]'], {'dtype': 'audio_features.dtype', 'device': 'audio_features.device'}), '(audio_features.shape[:2], dtype=audio_features.dtype, device=\n audio_features.device)\n', (30787, 30876), False, 'import torch\n'), ((45896, 45918), 'fairseq.modules.SamePad', 'SamePad', (['args.conv_pos'], {}), '(args.conv_pos)\n', (45903, 45918), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((45920, 45929), 'torch.nn.GELU', 'nn.GELU', ([], {}), '()\n', (45927, 45929), True, 'import torch.nn as nn\n'), ((47172, 47201), 'fairseq.utils.index_put', 'index_put', (['x', 'padding_mask', '(0)'], {}), '(x, padding_mask, 0)\n', (47181, 47201), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((47647, 47665), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (47663, 47665), True, 'import numpy as np\n'), ((15385, 15420), 'torch.nn.Linear', 'nn.Linear', (['final_dim', '(final_dim * 2)'], {}), '(final_dim, final_dim * 2)\n', (15394, 15420), True, 'import torch.nn as nn\n'), ((15422, 15430), 'torch.nn.GLU', 'nn.GLU', ([], {}), '()\n', (15428, 15430), True, 'import torch.nn as nn\n'), ((17727, 17775), 'os.path.join', 'os.path.join', (['cfg.m2v_path', '"""checkpoint_last.pt"""'], {}), "(cfg.m2v_path, 'checkpoint_last.pt')\n", (17739, 17775), False, 'import os\n'), ((19371, 19571), 'fairseq.data.data_utils.compute_mask_indices', 'compute_mask_indices', (['(B, T)', 'padding_mask', 'self.mask_prob', 'self.mask_length', 'self.mask_selection', 'self.mask_other'], {'min_masks': '(2)', 'no_overlap': 'self.no_mask_overlap', 'min_space': 'self.mask_min_space'}), '((B, T), padding_mask, self.mask_prob, self.mask_length,\n self.mask_selection, self.mask_other, min_masks=2, no_overlap=self.\n no_mask_overlap, min_space=self.mask_min_space)\n', (19391, 19571), False, 'from fairseq.data.data_utils import compute_mask_indices\n'), ((20214, 20447), 'fairseq.data.data_utils.compute_mask_indices', 'compute_mask_indices', (['(B, C)', 'None', 'self.mask_channel_prob', 'self.mask_channel_length', 'self.mask_channel_selection', 'self.mask_channel_other'], {'no_overlap': 'self.no_mask_channel_overlap', 'min_space': 'self.mask_channel_min_space'}), '((B, C), None, self.mask_channel_prob, self.\n mask_channel_length, self.mask_channel_selection, self.\n mask_channel_other, no_overlap=self.no_mask_channel_overlap, min_space=\n self.mask_channel_min_space)\n', (20234, 20447), False, 'from fairseq.data.data_utils import compute_mask_indices\n'), ((21833, 21904), 'torch.randint', 'torch.randint', ([], {'low': '(0)', 'high': '(high - 1)', 'size': '(bsz, self.n_negatives * num)'}), '(low=0, high=high - 1, size=(bsz, self.n_negatives * num))\n', (21846, 21904), False, 'import torch\n'), ((22285, 22378), 'torch.randint', 'torch.randint', ([], {'low': '(0)', 'high': '(cross_high - 1)', 'size': '(bsz, self.cross_sample_negatives * num)'}), '(low=0, high=cross_high - 1, size=(bsz, self.\n cross_sample_negatives * num))\n', (22298, 22378), False, 'import torch\n'), ((28734, 28792), 'fairseq.modules.GradMultiply.apply', 'GradMultiply.apply', (['audio_features', 'self.feature_grad_mult'], {}), '(audio_features, self.feature_grad_mult)\n', (28752, 28792), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((28827, 28886), 'fairseq.modules.GradMultiply.apply', 'GradMultiply.apply', (['visual_features', 'self.feature_grad_mult'], {}), '(visual_features, self.feature_grad_mult)\n', (28845, 28886), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((28918, 28933), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (28931, 28933), False, 'import torch\n'), ((37669, 37702), 'torch.cat', 'torch.cat', (['[negs, cb_negs]'], {'dim': '(0)'}), '([negs, cb_negs], dim=0)\n', (37678, 37702), False, 'import torch\n'), ((38313, 38335), 'fairseq.utils.is_xla_tensor', 'is_xla_tensor', (['x_audio'], {}), '(x_audio)\n', (38326, 38335), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((38344, 38367), 'fairseq.utils.is_xla_tensor', 'is_xla_tensor', (['x_visual'], {}), '(x_visual)\n', (38357, 38367), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((42733, 42833), 'torch.nn.Conv1d', 'nn.Conv1d', (['n_in', 'n_out'], {'kernel_size': 'kernel_size', 'stride': 'stride', 'padding': 'padding', 'bias': 'conv_bias'}), '(n_in, n_out, kernel_size=kernel_size, stride=stride, padding=\n padding, bias=conv_bias)\n', (42742, 42833), True, 'import torch.nn as nn\n'), ((42845, 42881), 'torch.nn.init.kaiming_normal_', 'nn.init.kaiming_normal_', (['conv.weight'], {}), '(conv.weight)\n', (42868, 42881), True, 'import torch.nn as nn\n'), ((51797, 51807), 'torchvision.models.resnet.resnet50', 'resnet50', ([], {}), '()\n', (51805, 51807), False, 'from torchvision.models.resnet import resnet50\n'), ((15022, 15062), 'torch.FloatTensor', 'torch.FloatTensor', (['cfg.encoder_embed_dim'], {}), '(cfg.encoder_embed_dim)\n', (15039, 15062), False, 'import torch\n'), ((17807, 17834), 'torch.load', 'torch.load', (['checkpoint_path'], {}), '(checkpoint_path)\n', (17817, 17834), False, 'import torch\n'), ((23879, 23900), 'fairseq.utils.is_xla_tensor', 'is_xla_tensor', (['logits'], {}), '(logits)\n', (23892, 23900), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((31093, 31156), 'torch.arange', 'torch.arange', (['padding_mask.shape[0]'], {'device': 'padding_mask.device'}), '(padding_mask.shape[0], device=padding_mask.device)\n', (31105, 31156), False, 'import torch\n'), ((32901, 32923), 'fairseq.utils.is_xla_tensor', 'is_xla_tensor', (['x_audio'], {}), '(x_audio)\n', (32914, 32923), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((32932, 32954), 'fairseq.utils.is_xla_tensor', 'is_xla_tensor', (['x_audio'], {}), '(x_audio)\n', (32945, 32954), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((38707, 38727), 'fairseq.utils.is_xla_tensor', 'is_xla_tensor', (['x_cat'], {}), '(x_cat)\n', (38720, 38727), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((43186, 43207), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout'}), '(p=dropout)\n', (43196, 43207), True, 'import torch.nn as nn\n'), ((43438, 43447), 'torch.nn.GELU', 'nn.GELU', ([], {}), '()\n', (43445, 43447), True, 'import torch.nn as nn\n'), ((52184, 52276), 'torch.nn.Conv3d', 'nn.Conv3d', (['(3)', '(64)'], {'kernel_size': '(7, 7, 7)', 'stride': '(1, 2, 2)', 'padding': '(3, 3, 3)', 'bias': '(False)'}), '(3, 64, kernel_size=(7, 7, 7), stride=(1, 2, 2), padding=(3, 3, 3),\n bias=False)\n', (52193, 52276), True, 'import torch.nn as nn\n'), ((19793, 19823), 'torch.from_numpy', 'torch.from_numpy', (['mask_indices'], {}), '(mask_indices)\n', (19809, 19823), False, 'import torch\n'), ((43268, 43283), 'fairseq.modules.TransposeLast', 'TransposeLast', ([], {}), '()\n', (43281, 43283), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((43309, 43352), 'fairseq.modules.Fp32LayerNorm', 'Fp32LayerNorm', (['dim'], {'elementwise_affine': '(True)'}), '(dim, elementwise_affine=True)\n', (43322, 43352), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((43378, 43393), 'fairseq.modules.TransposeLast', 'TransposeLast', ([], {}), '()\n', (43391, 43393), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((43590, 43611), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout'}), '(p=dropout)\n', (43600, 43611), True, 'import torch.nn as nn\n'), ((43633, 43669), 'fairseq.modules.Fp32GroupNorm', 'Fp32GroupNorm', (['dim', 'dim'], {'affine': '(True)'}), '(dim, dim, affine=True)\n', (43646, 43669), False, 'from fairseq.modules import Fp32GroupNorm, Fp32LayerNorm, GradMultiply, GumbelVectorQuantizer, LayerNorm, MultiheadAttention, SamePad, TransposeLast\n'), ((43691, 43700), 'torch.nn.GELU', 'nn.GELU', ([], {}), '()\n', (43698, 43700), True, 'import torch.nn as nn\n'), ((43788, 43809), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout'}), '(p=dropout)\n', (43798, 43809), True, 'import torch.nn as nn\n'), ((43811, 43820), 'torch.nn.GELU', 'nn.GELU', ([], {}), '()\n', (43818, 43820), True, 'import torch.nn as nn\n'), ((23821, 23842), 'torch.tensor', 'torch.tensor', (['fillval'], {}), '(fillval)\n', (23833, 23842), False, 'import torch\n'), ((25533, 25647), 'torch.zeros', 'torch.zeros', (['(visual_source_len - l, 3, 112, 112)'], {'dtype': 'visual_features.dtype', 'device': 'visual_features.device'}), '((visual_source_len - l, 3, 112, 112), dtype=visual_features.\n dtype, device=visual_features.device)\n', (25544, 25647), False, 'import torch\n'), ((16201, 16243), 'torch.load', 'torch.load', (['"""../pretrain/wav2vec_small.pt"""'], {}), "('../pretrain/wav2vec_small.pt')\n", (16211, 16243), False, 'import torch\n'), ((16383, 16439), 'torch.load', 'torch.load', (['"""../pretrain/moco_v2_800ep_pretrain.pth.tar"""'], {}), "('../pretrain/moco_v2_800ep_pretrain.pth.tar')\n", (16393, 16439), False, 'import torch\n'), ((19083, 19121), 'torch.from_numpy', 'torch.from_numpy', (['mask_channel_indices'], {}), '(mask_channel_indices)\n', (19099, 19121), False, 'import torch\n'), ((20673, 20711), 'torch.from_numpy', 'torch.from_numpy', (['mask_channel_indices'], {}), '(mask_channel_indices)\n', (20689, 20711), False, 'import torch\n'), ((21650, 21670), 'fairseq.utils.buffered_arange', 'buffered_arange', (['num'], {}), '(num)\n', (21665, 21670), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n'), ((22085, 22105), 'fairseq.utils.buffered_arange', 'buffered_arange', (['num'], {}), '(num)\n', (22100, 22105), False, 'from fairseq.utils import buffered_arange, index_put, is_xla_tensor\n')]
|
from keras.models import Sequential
from keras.models import Model
from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda
from keras.layers import concatenate
import numpy as np
import tensorflow as tf
def to_yuv(img, in_cspace='RGB'):
img_float = tf.cast(img, dtype=tf.float32) / 255.
if (in_cspace == 'RGB'):
img_rgb = tf.image.rgb_to_yuv(img_float)
elif (in_cspace == 'BGR'):
img_rgb = tf.image.bgr_to_yuv(img_float)
else:
raise ValueError(f"Unknown value of {in_cspace} for parameter 'in_space.'")
return img_rgb
def nvidia_model(img, crops=((0, 0), (0, 0)) ):
"""
A CNN model based on the NVIDIA paper implemented with Keras
Functional API.
:rtype: keras.models.Model
"""
x = Lambda(to_yuv, name='to_yuv')(img)
x = Lambda(lambda x : x * 2 - 1, name='normalization')(x)
# Add crop layer if crops are specified
if (np.asarray(crops).flatten() > 0).any():
# Crop the input image to the ROI
x = Cropping2D(cropping=crops)(x)
# Convoutional Layers
# Conv 1: 24@30x62 [kernel = 5x5; strides = 2x2]
x = Conv2D(filters=24, kernel_size=5, name='L1_conv')(x)
x = ELU()(x)
x = MaxPool2D(strides=(2,2), name='L1_pool')(x)
x = BatchNormalization()(x)
# Conv 2: 36@13x29 [kernel = 5x5; strides = 2x2]
x = Conv2D(filters=36, kernel_size=5, name='L2_conv')(x)
x = ELU()(x)
x = MaxPool2D(strides=(2,2), name='L2_pool')(x)
x = BatchNormalization()(x)
# Conv 3: 48@5x13 [kernel = 5x5; strides = 2x2]
x = Conv2D(filters=48, kernel_size=5, name='L3_conv')(x)
x = ELU()(x)
x = MaxPool2D(strides=(2,2), name='L3_pool')(x)
x = BatchNormalization()(x)
# Conv 4: 64@3x11 [kernel = 3x3; strides = 1x1]
x = Conv2D(filters=64, kernel_size=3, name='L4_conv')(x)
x = ELU()(x)
x = BatchNormalization()(x)
# Conv 5: 64@1x9 [kernel = 3x3; strides = 1x1]
x = Conv2D(filters=64, kernel_size=3, name='L5_conv')(x)
x = ELU()(x)
x = BatchNormalization()(x)
# 2D -> 1D Flatten to feed into FC layers
flattened = Flatten()(x)
xst = Dense(128, name='FC1_steer')(flattened)
xst = ELU()(xst)
xst = Dropout(rate=0.5)(xst)
xst = Dense(64, name='FC2_steer')(xst)
xst = ELU()(xst)
xst = Dropout(rate=0.5)(xst)
xst = Dense(16, name='FC3_steer')(xst)
xst = ELU()(xst)
xst = Dropout(rate=0.5)(xst)
# Ouyput layer
out_steer = Dense(1, name='OUT_steer')(xst)
model = Model(inputs=img, outputs=out_steer)
return model
|
[
"tensorflow.image.rgb_to_yuv",
"tensorflow.image.bgr_to_yuv",
"keras.layers.Cropping2D",
"keras.layers.Dropout",
"numpy.asarray",
"keras.layers.MaxPool2D",
"keras.layers.Flatten",
"keras.models.Model",
"keras.layers.ELU",
"tensorflow.cast",
"keras.layers.Dense",
"keras.layers.Lambda",
"keras.layers.Conv2D",
"keras.layers.BatchNormalization"
] |
[((2546, 2582), 'keras.models.Model', 'Model', ([], {'inputs': 'img', 'outputs': 'out_steer'}), '(inputs=img, outputs=out_steer)\n', (2551, 2582), False, 'from keras.models import Model\n'), ((312, 342), 'tensorflow.cast', 'tf.cast', (['img'], {'dtype': 'tf.float32'}), '(img, dtype=tf.float32)\n', (319, 342), True, 'import tensorflow as tf\n'), ((398, 428), 'tensorflow.image.rgb_to_yuv', 'tf.image.rgb_to_yuv', (['img_float'], {}), '(img_float)\n', (417, 428), True, 'import tensorflow as tf\n'), ((812, 841), 'keras.layers.Lambda', 'Lambda', (['to_yuv'], {'name': '"""to_yuv"""'}), "(to_yuv, name='to_yuv')\n", (818, 841), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((855, 904), 'keras.layers.Lambda', 'Lambda', (['(lambda x: x * 2 - 1)'], {'name': '"""normalization"""'}), "(lambda x: x * 2 - 1, name='normalization')\n", (861, 904), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1174, 1223), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(24)', 'kernel_size': '(5)', 'name': '"""L1_conv"""'}), "(filters=24, kernel_size=5, name='L1_conv')\n", (1180, 1223), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1235, 1240), 'keras.layers.ELU', 'ELU', ([], {}), '()\n', (1238, 1240), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1252, 1293), 'keras.layers.MaxPool2D', 'MaxPool2D', ([], {'strides': '(2, 2)', 'name': '"""L1_pool"""'}), "(strides=(2, 2), name='L1_pool')\n", (1261, 1293), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1304, 1324), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (1322, 1324), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1390, 1439), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(36)', 'kernel_size': '(5)', 'name': '"""L2_conv"""'}), "(filters=36, kernel_size=5, name='L2_conv')\n", (1396, 1439), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1451, 1456), 'keras.layers.ELU', 'ELU', ([], {}), '()\n', (1454, 1456), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1468, 1509), 'keras.layers.MaxPool2D', 'MaxPool2D', ([], {'strides': '(2, 2)', 'name': '"""L2_pool"""'}), "(strides=(2, 2), name='L2_pool')\n", (1477, 1509), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1520, 1540), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (1538, 1540), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1606, 1655), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(48)', 'kernel_size': '(5)', 'name': '"""L3_conv"""'}), "(filters=48, kernel_size=5, name='L3_conv')\n", (1612, 1655), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1667, 1672), 'keras.layers.ELU', 'ELU', ([], {}), '()\n', (1670, 1672), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1684, 1725), 'keras.layers.MaxPool2D', 'MaxPool2D', ([], {'strides': '(2, 2)', 'name': '"""L3_pool"""'}), "(strides=(2, 2), name='L3_pool')\n", (1693, 1725), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1736, 1756), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (1754, 1756), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1822, 1871), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(64)', 'kernel_size': '(3)', 'name': '"""L4_conv"""'}), "(filters=64, kernel_size=3, name='L4_conv')\n", (1828, 1871), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1883, 1888), 'keras.layers.ELU', 'ELU', ([], {}), '()\n', (1886, 1888), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1900, 1920), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (1918, 1920), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((1984, 2033), 'keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(64)', 'kernel_size': '(3)', 'name': '"""L5_conv"""'}), "(filters=64, kernel_size=3, name='L5_conv')\n", (1990, 2033), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2045, 2050), 'keras.layers.ELU', 'ELU', ([], {}), '()\n', (2048, 2050), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2062, 2082), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (2080, 2082), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2149, 2158), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (2156, 2158), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2172, 2200), 'keras.layers.Dense', 'Dense', (['(128)'], {'name': '"""FC1_steer"""'}), "(128, name='FC1_steer')\n", (2177, 2200), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2222, 2227), 'keras.layers.ELU', 'ELU', ([], {}), '()\n', (2225, 2227), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2243, 2260), 'keras.layers.Dropout', 'Dropout', ([], {'rate': '(0.5)'}), '(rate=0.5)\n', (2250, 2260), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2278, 2305), 'keras.layers.Dense', 'Dense', (['(64)'], {'name': '"""FC2_steer"""'}), "(64, name='FC2_steer')\n", (2283, 2305), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2321, 2326), 'keras.layers.ELU', 'ELU', ([], {}), '()\n', (2324, 2326), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2342, 2359), 'keras.layers.Dropout', 'Dropout', ([], {'rate': '(0.5)'}), '(rate=0.5)\n', (2349, 2359), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2376, 2403), 'keras.layers.Dense', 'Dense', (['(16)'], {'name': '"""FC3_steer"""'}), "(16, name='FC3_steer')\n", (2381, 2403), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2419, 2424), 'keras.layers.ELU', 'ELU', ([], {}), '()\n', (2422, 2424), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2440, 2457), 'keras.layers.Dropout', 'Dropout', ([], {'rate': '(0.5)'}), '(rate=0.5)\n', (2447, 2457), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((2500, 2526), 'keras.layers.Dense', 'Dense', (['(1)'], {'name': '"""OUT_steer"""'}), "(1, name='OUT_steer')\n", (2505, 2526), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((478, 508), 'tensorflow.image.bgr_to_yuv', 'tf.image.bgr_to_yuv', (['img_float'], {}), '(img_float)\n', (497, 508), True, 'import tensorflow as tf\n'), ((1056, 1082), 'keras.layers.Cropping2D', 'Cropping2D', ([], {'cropping': 'crops'}), '(cropping=crops)\n', (1066, 1082), False, 'from keras.layers import Cropping2D, Conv2D, MaxPool2D, Flatten, Dense, Dropout, ELU, BatchNormalization, Lambda\n'), ((962, 979), 'numpy.asarray', 'np.asarray', (['crops'], {}), '(crops)\n', (972, 979), True, 'import numpy as np\n')]
|
import os
import pickle
import cv2
import numpy as np
import streamlit as st
import tensorflow as tf
import grpc
from tensorflow_serving.apis import (
prediction_service_pb2_grpc,
predict_pb2
)
from consts import (
TRAIN_FD,
TRAIN_PKL_FP,
TRAIN_LABEL_FP
)
@st.cache
def load_prec_embs():
with open(TRAIN_PKL_FP, "rb") as f:
train_embs = pickle.load(f)
with open(TRAIN_LABEL_FP, "rb") as f:
train_labels = pickle.load(f)
train_img_fps = wfile(TRAIN_FD)
assert len(train_img_fps) == train_embs.shape[0]
return train_img_fps, train_embs, train_labels
def wfile(root):
img_fps = []
for path, subdirs, files in os.walk(root):
for name in files:
img_fps.append(os.path.join(path, name))
return sorted(img_fps)
class FlowerArc:
def __init__(self,
host="localhost",
port=8500,
model_name="flower",
model_signature="flower_signature",
input_name="input_image",
output_name="emb_pred"):
self.host = host
self.port = port
self.channel = grpc.insecure_channel("{}:{}".format(
self.host, self.port
))
self.stub = prediction_service_pb2_grpc.PredictionServiceStub(
self.channel
)
self.input_name = input_name
self.output_name = output_name
self.request = predict_pb2.PredictRequest()
self.request.model_spec.name = model_name
self.request.model_spec.signature_name = model_signature
def norm_mean_std(self,
img):
img = img / 255
img = img.astype('float32')
mean = np.mean(img, axis=(0, 1, 2))
std = np.std(img, axis=(0, 1, 2))
img = (img - mean) / std
return img
def test_preprocess(self,
img,
img_size=(384, 384),
expand=True):
img = cv2.resize(img, img_size)
# normalize image
img = self.norm_mean_std(img)
if expand:
img = np.expand_dims(img, axis=0)
return img
def predict(self, img):
assert img.ndim == 3
img = self.test_preprocess(img)
self.request.inputs[self.input_name].CopyFrom(
tf.contrib.util.make_tensor_proto(
img,
dtype=tf.float32,
shape=img.shape
)
)
result = self.stub.Predict(self.request, 10.0)
emb_pred = tf.contrib.util.make_ndarray(
result.outputs[self.output_name]
)
return emb_pred
class Saliency:
def __init__(self,
host="localhost",
port=8500,
model_name="saliency",
model_signature="serving_default",
input_name="input_image",
output_name="pred_mask"):
self.host = host
self.port = port
self.channel = grpc.insecure_channel("{}:{}".format(
self.host, self.port
))
self.stub = prediction_service_pb2_grpc.PredictionServiceStub(
self.channel
)
self.input_name = input_name
self.output_name = output_name
self.request = predict_pb2.PredictRequest()
self.request.model_spec.name = model_name
self.request.model_spec.signature_name = model_signature
def test_preprocess(self,
img,
img_size=(320, 240),
expand=True):
img = cv2.resize(img, img_size)
if expand:
img = np.expand_dims(img, axis=0)
return img
def predict(self, img):
assert img.ndim == 3
img = self.test_preprocess(img)
self.request.inputs[self.input_name].CopyFrom(
tf.contrib.util.make_tensor_proto(
img,
dtype=tf.float32,
shape=img.shape
)
)
result = self.stub.Predict(self.request, 10.0)
pred_mask = tf.contrib.util.make_ndarray(
result.outputs[self.output_name]
)
return pred_mask
|
[
"os.path.join",
"tensorflow_serving.apis.predict_pb2.PredictRequest",
"numpy.std",
"os.walk",
"numpy.expand_dims",
"tensorflow_serving.apis.prediction_service_pb2_grpc.PredictionServiceStub",
"pickle.load",
"numpy.mean",
"tensorflow.contrib.util.make_ndarray",
"tensorflow.contrib.util.make_tensor_proto",
"cv2.resize"
] |
[((679, 692), 'os.walk', 'os.walk', (['root'], {}), '(root)\n', (686, 692), False, 'import os\n'), ((373, 387), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (384, 387), False, 'import pickle\n'), ((454, 468), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (465, 468), False, 'import pickle\n'), ((1261, 1324), 'tensorflow_serving.apis.prediction_service_pb2_grpc.PredictionServiceStub', 'prediction_service_pb2_grpc.PredictionServiceStub', (['self.channel'], {}), '(self.channel)\n', (1310, 1324), False, 'from tensorflow_serving.apis import prediction_service_pb2_grpc, predict_pb2\n'), ((1447, 1475), 'tensorflow_serving.apis.predict_pb2.PredictRequest', 'predict_pb2.PredictRequest', ([], {}), '()\n', (1473, 1475), False, 'from tensorflow_serving.apis import prediction_service_pb2_grpc, predict_pb2\n'), ((1725, 1753), 'numpy.mean', 'np.mean', (['img'], {'axis': '(0, 1, 2)'}), '(img, axis=(0, 1, 2))\n', (1732, 1753), True, 'import numpy as np\n'), ((1768, 1795), 'numpy.std', 'np.std', (['img'], {'axis': '(0, 1, 2)'}), '(img, axis=(0, 1, 2))\n', (1774, 1795), True, 'import numpy as np\n'), ((2007, 2032), 'cv2.resize', 'cv2.resize', (['img', 'img_size'], {}), '(img, img_size)\n', (2017, 2032), False, 'import cv2\n'), ((2574, 2636), 'tensorflow.contrib.util.make_ndarray', 'tf.contrib.util.make_ndarray', (['result.outputs[self.output_name]'], {}), '(result.outputs[self.output_name])\n', (2602, 2636), True, 'import tensorflow as tf\n'), ((3143, 3206), 'tensorflow_serving.apis.prediction_service_pb2_grpc.PredictionServiceStub', 'prediction_service_pb2_grpc.PredictionServiceStub', (['self.channel'], {}), '(self.channel)\n', (3192, 3206), False, 'from tensorflow_serving.apis import prediction_service_pb2_grpc, predict_pb2\n'), ((3329, 3357), 'tensorflow_serving.apis.predict_pb2.PredictRequest', 'predict_pb2.PredictRequest', ([], {}), '()\n', (3355, 3357), False, 'from tensorflow_serving.apis import prediction_service_pb2_grpc, predict_pb2\n'), ((3631, 3656), 'cv2.resize', 'cv2.resize', (['img', 'img_size'], {}), '(img, img_size)\n', (3641, 3656), False, 'import cv2\n'), ((4134, 4196), 'tensorflow.contrib.util.make_ndarray', 'tf.contrib.util.make_ndarray', (['result.outputs[self.output_name]'], {}), '(result.outputs[self.output_name])\n', (4162, 4196), True, 'import tensorflow as tf\n'), ((2136, 2163), 'numpy.expand_dims', 'np.expand_dims', (['img'], {'axis': '(0)'}), '(img, axis=0)\n', (2150, 2163), True, 'import numpy as np\n'), ((2352, 2425), 'tensorflow.contrib.util.make_tensor_proto', 'tf.contrib.util.make_tensor_proto', (['img'], {'dtype': 'tf.float32', 'shape': 'img.shape'}), '(img, dtype=tf.float32, shape=img.shape)\n', (2385, 2425), True, 'import tensorflow as tf\n'), ((3695, 3722), 'numpy.expand_dims', 'np.expand_dims', (['img'], {'axis': '(0)'}), '(img, axis=0)\n', (3709, 3722), True, 'import numpy as np\n'), ((3911, 3984), 'tensorflow.contrib.util.make_tensor_proto', 'tf.contrib.util.make_tensor_proto', (['img'], {'dtype': 'tf.float32', 'shape': 'img.shape'}), '(img, dtype=tf.float32, shape=img.shape)\n', (3944, 3984), True, 'import tensorflow as tf\n'), ((748, 772), 'os.path.join', 'os.path.join', (['path', 'name'], {}), '(path, name)\n', (760, 772), False, 'import os\n')]
|
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
# Open the image
img = np.array(Image.open('house.jpg')).astype(np.uint8)
# Apply gray scale
gray_img = np.round(0.299 * img[:, :, 0] +
0.587 * img[:, :, 1] +
0.114 * img[:, :, 2]).astype(np.uint8)
# Prewitt Operator
h, w = gray_img.shape
# define filters
horizontal = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]) # s2
vertical = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]]) # s1
# define images with 0s
newgradientImage = np.zeros((h, w))
# offset by 1
for i in range(1, h - 1):
for j in range(1, w - 1):
horizontalGrad = (horizontal[0, 0] * gray_img[i - 1, j - 1]) + \
(horizontal[0, 1] * gray_img[i - 1, j]) + \
(horizontal[0, 2] * gray_img[i - 1, j + 1]) + \
(horizontal[1, 0] * gray_img[i, j - 1]) + \
(horizontal[1, 1] * gray_img[i, j]) + \
(horizontal[1, 2] * gray_img[i, j + 1]) + \
(horizontal[2, 0] * gray_img[i + 1, j - 1]) + \
(horizontal[2, 1] * gray_img[i + 1, j]) + \
(horizontal[2, 2] * gray_img[i + 1, j + 1])
verticalGrad = (vertical[0, 0] * gray_img[i - 1, j - 1]) + \
(vertical[0, 1] * gray_img[i - 1, j]) + \
(vertical[0, 2] * gray_img[i - 1, j + 1]) + \
(vertical[1, 0] * gray_img[i, j - 1]) + \
(vertical[1, 1] * gray_img[i, j]) + \
(vertical[1, 2] * gray_img[i, j + 1]) + \
(vertical[2, 0] * gray_img[i + 1, j - 1]) + \
(vertical[2, 1] * gray_img[i + 1, j]) + \
(vertical[2, 2] * gray_img[i + 1, j + 1])
# Edge Magnitude
mag = np.sqrt(pow(horizontalGrad, 2.0) + pow(verticalGrad, 2.0))
newgradientImage[i - 1, j - 1] = mag
plt.figure()
plt.title('Prewitt_House')
plt.imsave('prewitt_house.jpg', newgradientImage, cmap='gray')
plt.imshow(newgradientImage, cmap='gray')
plt.show()
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow",
"numpy.zeros",
"PIL.Image.open",
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.pyplot.imsave",
"numpy.round"
] |
[((400, 446), 'numpy.array', 'np.array', (['[[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]'], {}), '([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])\n', (408, 446), True, 'import numpy as np\n'), ((465, 511), 'numpy.array', 'np.array', (['[[-1, -1, -1], [0, 0, 0], [1, 1, 1]]'], {}), '([[-1, -1, -1], [0, 0, 0], [1, 1, 1]])\n', (473, 511), True, 'import numpy as np\n'), ((565, 581), 'numpy.zeros', 'np.zeros', (['(h, w)'], {}), '((h, w))\n', (573, 581), True, 'import numpy as np\n'), ((2052, 2064), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2062, 2064), True, 'import matplotlib.pyplot as plt\n'), ((2066, 2092), 'matplotlib.pyplot.title', 'plt.title', (['"""Prewitt_House"""'], {}), "('Prewitt_House')\n", (2075, 2092), True, 'import matplotlib.pyplot as plt\n'), ((2094, 2156), 'matplotlib.pyplot.imsave', 'plt.imsave', (['"""prewitt_house.jpg"""', 'newgradientImage'], {'cmap': '"""gray"""'}), "('prewitt_house.jpg', newgradientImage, cmap='gray')\n", (2104, 2156), True, 'import matplotlib.pyplot as plt\n'), ((2158, 2199), 'matplotlib.pyplot.imshow', 'plt.imshow', (['newgradientImage'], {'cmap': '"""gray"""'}), "(newgradientImage, cmap='gray')\n", (2168, 2199), True, 'import matplotlib.pyplot as plt\n'), ((2201, 2211), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2209, 2211), True, 'import matplotlib.pyplot as plt\n'), ((187, 263), 'numpy.round', 'np.round', (['(0.299 * img[:, :, 0] + 0.587 * img[:, :, 1] + 0.114 * img[:, :, 2])'], {}), '(0.299 * img[:, :, 0] + 0.587 * img[:, :, 1] + 0.114 * img[:, :, 2])\n', (195, 263), True, 'import numpy as np\n'), ((111, 134), 'PIL.Image.open', 'Image.open', (['"""house.jpg"""'], {}), "('house.jpg')\n", (121, 134), False, 'from PIL import Image\n')]
|
"""
SAVGOL INTERP.
--------------
"""
import argparse
from pathlib import Path
import matplotlib
import numpy as np
from embers.rf_tools.align_data import savgol_interp
from embers.rf_tools.colormaps import spectral
from matplotlib import pyplot as plt
matplotlib.use("Agg")
_spec, _ = spectral()
parser = argparse.ArgumentParser(
description="""
Savgol Interpolation paper plot
"""
)
parser.add_argument(
"--rf_dir",
metavar="\b",
default="../../tiles_data",
help="Directory with raw rf data. Default=.../../tiles_data",
)
parser.add_argument(
"--out_dir",
metavar="\b",
default="../embers_out/paper_plots",
help="Output Directory. Default=./embers_out/paper_plots",
)
args = parser.parse_args()
rf_dir = Path(args.rf_dir)
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
try:
ch = 8
(
ref_ali,
tile_ali,
time_array,
ref_power,
tile_power,
ref_time,
tile_time,
) = savgol_interp(
f"{rf_dir}/rf0XX/2019-09-15/rf0XX_2019-09-15-11:00.txt",
f"{rf_dir}/S06XX/2019-09-15/S06XX_2019-09-15-11:00.txt",
savgol_window_1=11,
savgol_window_2=15,
polyorder=2,
interp_type="cubic",
interp_freq=1,
)
plt.style.use("seaborn")
nice_fonts = {
# Use LaTeX to write all text
# "text.usetex": True,
"font.family": "sans-serif",
# Use 10pt font in plots, to match 10pt font in document
"axes.labelsize": 10,
"font.size": 10,
# Make the legend/label fonts a little smaller
"legend.fontsize": 6,
"xtick.labelsize": 8,
"ytick.labelsize": 8,
}
plt.rcParams.update(nice_fonts)
fig = plt.figure(figsize=(3.6, 2.4))
colors = _spec([0.14, 0.28])
tile_t = tile_time - tile_time[0]
time_array = time_array - time_array[0]
med = np.median(tile_power)
tile_p = tile_power - med
tile_p_aligned = tile_ali - med
plt.plot(
time_array,
tile_p_aligned[::, ch],
linewidth=1,
color=colors[0],
# color="#2c5d63",
alpha=0.9,
label="SavGol",
)
plt.scatter(
tile_t,
tile_p[::, ch],
color=colors[1],
# color="#7fa998",
marker=".",
s=3,
alpha=0.2,
label="AUT raw",
)
leg = plt.legend(loc="upper right", frameon=True, markerscale=4, handlelength=1)
leg.get_frame().set_facecolor("white")
for le in leg.legendHandles:
le.set_alpha(1)
plt.ylabel("Power [dB]")
plt.xlabel("Time [s]")
plt.tight_layout()
plt.savefig(f"{out_dir}/savgol.pdf", bbox_inches="tight")
print(f"SAVGOL INTERP saved to {out_dir}")
except Exception as e:
print(e)
print("Missing input rf files. Check path to rf_dir")
|
[
"argparse.ArgumentParser",
"matplotlib.pyplot.plot",
"numpy.median",
"matplotlib.pyplot.scatter",
"embers.rf_tools.colormaps.spectral",
"matplotlib.pyplot.legend",
"embers.rf_tools.align_data.savgol_interp",
"pathlib.Path",
"matplotlib.use",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.savefig"
] |
[((256, 277), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (270, 277), False, 'import matplotlib\n'), ((289, 299), 'embers.rf_tools.colormaps.spectral', 'spectral', ([], {}), '()\n', (297, 299), False, 'from embers.rf_tools.colormaps import spectral\n'), ((310, 407), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""\n Savgol Interpolation paper plot\n """'}), '(description=\n """\n Savgol Interpolation paper plot\n """)\n', (333, 407), False, 'import argparse\n'), ((765, 782), 'pathlib.Path', 'Path', (['args.rf_dir'], {}), '(args.rf_dir)\n', (769, 782), False, 'from pathlib import Path\n'), ((793, 811), 'pathlib.Path', 'Path', (['args.out_dir'], {}), '(args.out_dir)\n', (797, 811), False, 'from pathlib import Path\n'), ((1018, 1247), 'embers.rf_tools.align_data.savgol_interp', 'savgol_interp', (['f"""{rf_dir}/rf0XX/2019-09-15/rf0XX_2019-09-15-11:00.txt"""', 'f"""{rf_dir}/S06XX/2019-09-15/S06XX_2019-09-15-11:00.txt"""'], {'savgol_window_1': '(11)', 'savgol_window_2': '(15)', 'polyorder': '(2)', 'interp_type': '"""cubic"""', 'interp_freq': '(1)'}), "(f'{rf_dir}/rf0XX/2019-09-15/rf0XX_2019-09-15-11:00.txt',\n f'{rf_dir}/S06XX/2019-09-15/S06XX_2019-09-15-11:00.txt',\n savgol_window_1=11, savgol_window_2=15, polyorder=2, interp_type=\n 'cubic', interp_freq=1)\n", (1031, 1247), False, 'from embers.rf_tools.align_data import savgol_interp\n'), ((1303, 1327), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn"""'], {}), "('seaborn')\n", (1316, 1327), True, 'from matplotlib import pyplot as plt\n'), ((1730, 1761), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (['nice_fonts'], {}), '(nice_fonts)\n', (1749, 1761), True, 'from matplotlib import pyplot as plt\n'), ((1773, 1803), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(3.6, 2.4)'}), '(figsize=(3.6, 2.4))\n', (1783, 1803), True, 'from matplotlib import pyplot as plt\n'), ((1932, 1953), 'numpy.median', 'np.median', (['tile_power'], {}), '(tile_power)\n', (1941, 1953), True, 'import numpy as np\n'), ((2025, 2129), 'matplotlib.pyplot.plot', 'plt.plot', (['time_array', 'tile_p_aligned[:, ch]'], {'linewidth': '(1)', 'color': 'colors[0]', 'alpha': '(0.9)', 'label': '"""SavGol"""'}), "(time_array, tile_p_aligned[:, ch], linewidth=1, color=colors[0],\n alpha=0.9, label='SavGol')\n", (2033, 2129), True, 'from matplotlib import pyplot as plt\n'), ((2214, 2315), 'matplotlib.pyplot.scatter', 'plt.scatter', (['tile_t', 'tile_p[:, ch]'], {'color': 'colors[1]', 'marker': '"""."""', 's': '(3)', 'alpha': '(0.2)', 'label': '"""AUT raw"""'}), "(tile_t, tile_p[:, ch], color=colors[1], marker='.', s=3, alpha=\n 0.2, label='AUT raw')\n", (2225, 2315), True, 'from matplotlib import pyplot as plt\n'), ((2414, 2488), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""', 'frameon': '(True)', 'markerscale': '(4)', 'handlelength': '(1)'}), "(loc='upper right', frameon=True, markerscale=4, handlelength=1)\n", (2424, 2488), True, 'from matplotlib import pyplot as plt\n'), ((2594, 2618), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power [dB]"""'], {}), "('Power [dB]')\n", (2604, 2618), True, 'from matplotlib import pyplot as plt\n'), ((2623, 2645), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time [s]"""'], {}), "('Time [s]')\n", (2633, 2645), True, 'from matplotlib import pyplot as plt\n'), ((2650, 2668), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2666, 2668), True, 'from matplotlib import pyplot as plt\n'), ((2673, 2730), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""{out_dir}/savgol.pdf"""'], {'bbox_inches': '"""tight"""'}), "(f'{out_dir}/savgol.pdf', bbox_inches='tight')\n", (2684, 2730), True, 'from matplotlib import pyplot as plt\n')]
|
import numpy as np
from config import GOPARAMETERS
def stone_features(board_state):
# 16 planes, where every other plane represents the stones of a particular color
# which means we track the stones of the last 8 moves.
features = np.zeros([16, GOPARAMETERS.N, GOPARAMETERS.N], dtype=np.uint8)
num_deltas_avail = board_state.board_deltas.shape[0]
cumulative_deltas = np.cumsum(board_state.board_deltas, axis=0)
last_eight = np.tile(board_state.board, [8, 1, 1])
last_eight[1:num_deltas_avail + 1] -= cumulative_deltas
last_eight[num_deltas_avail +1:] = last_eight[num_deltas_avail].reshape(1, GOPARAMETERS.N, GOPARAMETERS.N)
features[::2] = last_eight == board_state.to_play
features[1::2] = last_eight == -board_state.to_play
return np.rollaxis(features, 0, 3)
def color_to_play_feature(board_state):
# 1 plane representing which color is to play
# The plane is filled with 1's if the color to play is black; 0's otherwise
if board_state.to_play == GOPARAMETERS.BLACK:
return np.ones([GOPARAMETERS.N, GOPARAMETERS.N, 1], dtype=np.uint8)
else:
return np.zeros([GOPARAMETERS.N, GOPARAMETERS.N, 1], dtype=np.uint8)
def extract_features(board_state):
stone_feat = stone_features(board_state=board_state)
turn_feat = color_to_play_feature(board_state=board_state)
all_features = np.concatenate([stone_feat, turn_feat], axis=2)
return all_features
|
[
"numpy.zeros",
"numpy.ones",
"numpy.cumsum",
"numpy.tile",
"numpy.rollaxis",
"numpy.concatenate"
] |
[((245, 307), 'numpy.zeros', 'np.zeros', (['[16, GOPARAMETERS.N, GOPARAMETERS.N]'], {'dtype': 'np.uint8'}), '([16, GOPARAMETERS.N, GOPARAMETERS.N], dtype=np.uint8)\n', (253, 307), True, 'import numpy as np\n'), ((390, 433), 'numpy.cumsum', 'np.cumsum', (['board_state.board_deltas'], {'axis': '(0)'}), '(board_state.board_deltas, axis=0)\n', (399, 433), True, 'import numpy as np\n'), ((451, 488), 'numpy.tile', 'np.tile', (['board_state.board', '[8, 1, 1]'], {}), '(board_state.board, [8, 1, 1])\n', (458, 488), True, 'import numpy as np\n'), ((782, 809), 'numpy.rollaxis', 'np.rollaxis', (['features', '(0)', '(3)'], {}), '(features, 0, 3)\n', (793, 809), True, 'import numpy as np\n'), ((1369, 1416), 'numpy.concatenate', 'np.concatenate', (['[stone_feat, turn_feat]'], {'axis': '(2)'}), '([stone_feat, turn_feat], axis=2)\n', (1383, 1416), True, 'import numpy as np\n'), ((1046, 1106), 'numpy.ones', 'np.ones', (['[GOPARAMETERS.N, GOPARAMETERS.N, 1]'], {'dtype': 'np.uint8'}), '([GOPARAMETERS.N, GOPARAMETERS.N, 1], dtype=np.uint8)\n', (1053, 1106), True, 'import numpy as np\n'), ((1132, 1193), 'numpy.zeros', 'np.zeros', (['[GOPARAMETERS.N, GOPARAMETERS.N, 1]'], {'dtype': 'np.uint8'}), '([GOPARAMETERS.N, GOPARAMETERS.N, 1], dtype=np.uint8)\n', (1140, 1193), True, 'import numpy as np\n')]
|
from numpy import array, copy, concatenate
from torch import Tensor
from botorch.acquisition.multi_objective.monte_carlo import (
qExpectedHypervolumeImprovement, qNoisyExpectedHypervolumeImprovement
)
from botorch.posteriors import GPyTorchPosterior, Posterior, DeterministicPosterior
from gpytorch.distributions import MultitaskMultivariateNormal
from gpytorch.lazy import BlockDiagLazyTensor
import torch
# TODO: replace these with the non-mocked versions once botorch #991 comes in
# will need to update to botorch master
class qDiscreteEHVI(qExpectedHypervolumeImprovement):
def forward(self, X: array) -> Tensor:
# mocks the qEHVI call
# assumes that X is an array of shape batch x q rather than a tensor of shape batch x q x d
posterior = self.model.posterior(X)
samples = self.sampler(posterior)
return self._compute_qehvi(samples=samples)
class qDiscreteNEHVI(qNoisyExpectedHypervolumeImprovement):
# TODO: figure out how to remove
def __init__(
self,
model,
ref_point,
X_baseline,
sampler = None,
objective = None,
constraints = None,
X_pending = None,
eta: float = 1e-3,
prune_baseline: bool = False,
alpha: float = 0.0,
cache_pending: bool = True,
max_iep: int = 0,
incremental_nehvi: bool = True,
**kwargs,
):
model.eval()
mocked_features = model.get_features(X_baseline, model.bs)
# for string kernels
if mocked_features.ndim > 2:
mocked_features = mocked_features[..., 0].to(ref_point) # doint let this fail
super().__init__(
model=model,
ref_point=ref_point,
X_baseline=mocked_features,
sampler=sampler,
objective=objective,
constraints=constraints,
X_pending=X_pending,
eta=eta,
prune_baseline=prune_baseline,
alpha=alpha,
cache_pending=cache_pending,
max_iep=max_iep,
incremental_nehvi=incremental_nehvi,
**kwargs
)
self.X_baseline_string = X_baseline
def forward(self, X: array) -> Tensor:
if isinstance(X, Tensor):
baseline_X = self._X_baseline
baseline_X = baseline_X.expand(*X.shape[:-2], -1, -1)
X_full = torch.cat([baseline_X, X], dim=-2)
else:
baseline_X = copy(self.X_baseline_string) # ensure contiguity
baseline_X.resize(
baseline_X.shape[:-(X.ndim)] + X.shape[:-1] + baseline_X.shape[-1:]
)
X_full = concatenate([baseline_X, X], axis=-1)
# Note: it is important to compute the full posterior over `(X_baseline, X)``
# to ensure that we properly sample `f(X)` from the joint distribution `
# `f(X_baseline, X) ~ P(f | D)` given that we can already fixed the sampled
# function values for `f(X_baseline)`
posterior = self.model.posterior(X_full)
q = X.shape[-2]
self._set_sampler(q=q, posterior=posterior)
samples = self.sampler(posterior)[..., -q:, :]
# add previous nehvi from pending points
return self._compute_qehvi(samples=samples) + self._prev_nehvi
def _cache_root_decomposition(self, posterior: GPyTorchPosterior) -> None:
if posterior.mvn._interleaved:
if hasattr(posterior.mvn.lazy_covariance_matrix, 'base_lazy_tensor'):
posterior_lc_base = posterior.mvn.lazy_covariance_matrix.base_lazy_tensor
else:
posterior_lc_base = posterior.mvn.lazy_covariance_matrix
new_lazy_covariance = BlockDiagLazyTensor(posterior_lc_base)
posterior.mvn = MultitaskMultivariateNormal(posterior.mvn.mean, new_lazy_covariance, interleaved=False)
return super()._cache_root_decomposition(posterior=posterior)
class qMTGPDiscreteNEHVI(qDiscreteNEHVI):
# TODO: remove when botorch #1037 goes in
# this is copied over from that diff
_uses_matheron = True
def __init__(self, *args, **kwargs):
super().__init__(cache_root = False, *args, **kwargs)
def _set_sampler(
self,
q: int,
posterior: Posterior,
) -> None:
r"""Update the sampler to use the original base samples for X_baseline.
Args:
q: the batch size
posterior: the posterior
TODO: refactor some/all of this into the MCSampler.
"""
if self.q != q:
# create new base_samples
base_sample_shape = self.sampler._get_base_sample_shape(posterior=posterior)
self.sampler._construct_base_samples(
posterior=posterior, shape=base_sample_shape
)
if (
self.X_baseline.shape[0] > 0
and self.base_sampler.base_samples is not None
and not isinstance(posterior, DeterministicPosterior)
):
current_base_samples = self.base_sampler.base_samples.detach().clone()
# This is the # of non-`sample_shape` dimensions.
base_ndims = current_base_samples.dim() - 1
# Unsqueeze as many dimensions as needed to match base_sample_shape.
view_shape = (
self.sampler.sample_shape
+ torch.Size(
[1] * (len(base_sample_shape) - current_base_samples.dim())
)
+ current_base_samples.shape[-base_ndims:]
)
expanded_shape = (
base_sample_shape[:-base_ndims]
+ current_base_samples.shape[-base_ndims:]
)
# Use stored base samples:
# Use all base_samples from the current sampler
# this includes the base_samples from the base_sampler
# and any base_samples for the new points in the sampler.
# For example, when using sequential greedy candidate generation
# then generate the new candidate point using last (-1) base_sample
# in sampler. This copies that base sample.
end_idx = current_base_samples.shape[-1 if self._uses_matheron else -2]
expanded_samples = current_base_samples.view(view_shape).expand(
expanded_shape
)
if self._uses_matheron:
self.sampler.base_samples[..., :end_idx] = expanded_samples
else:
self.sampler.base_samples[..., :end_idx, :] = expanded_samples
# update cached subset indices
# Note: this also stores self.q = q
self._cache_q_subset_indices(q=q)
|
[
"numpy.copy",
"gpytorch.lazy.BlockDiagLazyTensor",
"gpytorch.distributions.MultitaskMultivariateNormal",
"torch.cat",
"numpy.concatenate"
] |
[((2408, 2442), 'torch.cat', 'torch.cat', (['[baseline_X, X]'], {'dim': '(-2)'}), '([baseline_X, X], dim=-2)\n', (2417, 2442), False, 'import torch\n'), ((2482, 2510), 'numpy.copy', 'copy', (['self.X_baseline_string'], {}), '(self.X_baseline_string)\n', (2486, 2510), False, 'from numpy import array, copy, concatenate\n'), ((2681, 2718), 'numpy.concatenate', 'concatenate', (['[baseline_X, X]'], {'axis': '(-1)'}), '([baseline_X, X], axis=-1)\n', (2692, 2718), False, 'from numpy import array, copy, concatenate\n'), ((3737, 3775), 'gpytorch.lazy.BlockDiagLazyTensor', 'BlockDiagLazyTensor', (['posterior_lc_base'], {}), '(posterior_lc_base)\n', (3756, 3775), False, 'from gpytorch.lazy import BlockDiagLazyTensor\n'), ((3804, 3895), 'gpytorch.distributions.MultitaskMultivariateNormal', 'MultitaskMultivariateNormal', (['posterior.mvn.mean', 'new_lazy_covariance'], {'interleaved': '(False)'}), '(posterior.mvn.mean, new_lazy_covariance,\n interleaved=False)\n', (3831, 3895), False, 'from gpytorch.distributions import MultitaskMultivariateNormal\n')]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from scipy import linalg
from numpy.testing import assert_almost_equal
from megamix.online import GaussianMixture
from megamix.online.base import _log_normal_matrix
from megamix.online import dist_matrix
from megamix.utils_testing import checking
from scipy.special import logsumexp
import pytest
import h5py
class TestGaussianMixture_full:
def setup(self):
self.n_components = 5
self.dim = 2
self.n_points = 10
self.file_name = 'test'
def teardown(self):
checking.remove(self.file_name + '.h5')
def test_initialize(self,window):
points = np.random.randn(self.n_points,self.dim)
GM = GaussianMixture(self.n_components,window=window)
GM.initialize(points)
checking.verify_covariance(GM.get('cov'),self.n_components,self.dim)
checking.verify_means(GM.get('means'),self.n_components,self.dim)
checking.verify_log_pi(GM.get('log_weights'),self.n_components)
cov_chol = np.empty_like(GM.get('cov'))
for i in range(self.n_components):
cov_chol[i] = linalg.cholesky(GM.get('cov')[i],lower=True)
assert_almost_equal(cov_chol,GM.get('cov_chol'))
assert GM.get('_is_initialized') == True
def test_initialize_cov(self,window,update):
points = np.random.randn(self.n_points,self.dim)
GM = GaussianMixture(self.n_components,window=window)
means = np.random.randn(self.n_components,self.dim)
GM.set('means',means)
GM._initialize_cov(points)
predected_cov = GM.get('cov')
assignements = np.zeros((self.n_points,self.n_components))
M = dist_matrix(points,means)
for i in range(self.n_points):
index_min = np.argmin(M[i]) #the cluster number of the ith point is index_min
if (isinstance(index_min,np.int64)):
assignements[i][index_min] = 1
else: #Happens when two points are equally distant from a cluster mean
assignements[i][index_min[0]] = 1
N = np.sum(assignements,axis=0) + 1e-15
N /= self.n_points
S = np.zeros((self.n_components,self.dim,self.dim))
for i in range(self.n_components):
diff = points - means[i]
diff_weighted = diff * assignements[:,i:i+1]
S[i] = np.dot(diff_weighted.T,diff)
S[i].flat[::self.dim+1] += float(GM.get('reg_covar'))
S /= self.n_points
expected_cov = S / N[:,np.newaxis,np.newaxis]
assert_almost_equal(expected_cov,predected_cov)
def test_step_E(self,window):
points = np.random.randn(self.n_points,self.dim)
GM = GaussianMixture(self.n_components,window=window)
GM.initialize(points)
log_normal_matrix = _log_normal_matrix(points,GM.get('means'),
GM.get('cov_chol'),'full')
log_product = log_normal_matrix + GM.get('log_weights')[:,np.newaxis].T
expected_log_prob_norm = logsumexp(log_product,axis=1)
expected_log_resp = log_product - expected_log_prob_norm[:,np.newaxis]
predected_log_prob_norm, predected_log_resp = GM._step_E(points)
assert_almost_equal(expected_log_prob_norm,predected_log_prob_norm)
assert_almost_equal(expected_log_resp,predected_log_resp)
def test_step_M(self,window,update):
points = np.random.randn(self.n_points,self.dim)
GM = GaussianMixture(self.n_components,window=window,update=update)
GM.initialize(points)
_,log_resp = GM._step_E(points[:GM.get('window'):])
GM._sufficient_statistics(points[:GM.get('window'):],log_resp)
log_weights = np.log(GM.get('N'))
means = GM.get('X') / GM.get('N')[:,np.newaxis]
cov = GM.get('S') / GM.get('N')[:,np.newaxis,np.newaxis]
cov_chol = np.empty_like(cov)
for i in range(self.n_components):
cov_chol[i] = linalg.cholesky(cov[i],lower=True)
GM._step_M()
assert_almost_equal(log_weights,GM.get('log_weights'))
assert_almost_equal(means,GM.get('means'))
assert_almost_equal(cov,GM.get('cov'))
assert_almost_equal(cov_chol,GM.get('cov_chol'))
def test_sufficient_statistics(self,window,update):
points = np.random.randn(self.n_points,self.dim)
GM = GaussianMixture(self.n_components,window=window,update=update)
GM.initialize(points)
_,log_resp = GM._step_E(points[:GM.get('window'):])
points_exp = points[:window:]
resp = np.exp(log_resp)
gamma = 1/((GM.get('iter') + window//2)**GM.get('kappa'))
# New sufficient statistics
N = resp.sum(axis=0) + 10 * np.finfo(resp.dtype).eps
N /= window
X = np.dot(resp.T,points_exp)
X /= window
S = np.zeros((self.n_components,self.dim,self.dim))
for i in range(self.n_components):
diff = points_exp - GM.get('means')[i]
diff_weighted = diff * np.sqrt(resp[:,i:i+1])
S[i] = np.dot(diff_weighted.T,diff_weighted)
S /= window
# Sufficient statistics update
expected_N = (1-gamma)*GM.get('N') + gamma*N
expected_X = (1-gamma)*GM.get('X') + gamma*X
expected_S = (1-gamma)*GM.get('S') + gamma*S
expected_S_chol = np.zeros((self.n_components,self.dim,self.dim))
for i in range(self.n_components):
expected_S_chol[i] = linalg.cholesky(expected_S[i],lower=True)
GM._sufficient_statistics(points_exp,log_resp)
assert_almost_equal(expected_N,GM.get('N'))
assert_almost_equal(expected_X,GM.get('X'))
assert_almost_equal(expected_S,GM.get('S'))
def test_score(self,window,update):
points = np.random.randn(self.n_points,self.dim)
points2 = np.random.randn(self.n_points,self.dim)
GM = GaussianMixture(self.n_components,window=window,update=update)
with pytest.raises(Exception):
GM.score(points)
GM.initialize(points)
GM.fit(points)
score1 = GM.score(points)
score2 = GM.score(points2)
assert score1 > score2
def test_write_and_read(self,update):
points = np.random.randn(self.n_points,self.dim)
GM = GaussianMixture(self.n_components,update=update)
GM.initialize(points)
f = h5py.File(self.file_name + '.h5','w')
grp = f.create_group('init')
GM.write(grp)
f.close()
GM2 = GaussianMixture(self.n_components,update=update)
f = h5py.File(self.file_name + '.h5','r')
grp = f['init']
GM2.read_and_init(grp,points)
f.close()
checking.verify_online_models(GM,GM2)
GM.fit(points)
GM2.fit(points)
checking.verify_online_models(GM,GM2)
def test_predict_log_resp(self,window,update):
points = np.random.randn(self.n_points,self.dim)
GM = GaussianMixture(self.n_components,window=window,update=update)
with pytest.raises(Exception):
GM.predict_log_resp(points)
GM.initialize(points)
predected_log_resp = GM.predict_log_resp(points)
_,expected_log_resp = GM._step_E(points)
assert_almost_equal(predected_log_resp,expected_log_resp)
def test_update(self,window):
points = np.random.randn(self.n_points,self.dim)
GM = GaussianMixture(self.n_components,window=window,update=True)
GM.initialize(points)
GM.fit(points)
expected_cov_chol = np.zeros((self.n_components,self.dim,self.dim))
for i in range(self.n_components):
expected_cov_chol[i] = linalg.cholesky(GM.get('cov')[i],lower=True)
predected_cov_chol = GM.get('cov_chol')
assert_almost_equal(expected_cov_chol,predected_cov_chol)
def test_fit_save(self,window):
points = np.random.randn(self.n_points,self.dim)
GM = GaussianMixture(self.n_components,window=window)
checking.remove(self.file_name + '.h5')
GM.initialize(points)
GM.fit(points,saving='linear',saving_iter=2,
file_name=self.file_name)
f = h5py.File(self.file_name + '.h5','r')
cpt = 0
for name in f:
cpt += 1
assert cpt == self.n_points//(2*window)
checking.remove(self.file_name + '.h5')
GM.fit(points,saving='log',saving_iter=2,
file_name=self.file_name)
f = h5py.File(self.file_name + '.h5','r')
cpt = 0
for name in f:
cpt += 1
assert cpt == 1 + int(np.log(self.n_points/window)/np.log(2))
|
[
"numpy.sum",
"megamix.online.dist_matrix",
"scipy.linalg.cholesky",
"numpy.argmin",
"numpy.exp",
"scipy.special.logsumexp",
"megamix.online.GaussianMixture",
"numpy.random.randn",
"numpy.testing.assert_almost_equal",
"numpy.empty_like",
"numpy.finfo",
"pytest.raises",
"megamix.utils_testing.checking.verify_online_models",
"h5py.File",
"numpy.dot",
"numpy.log",
"numpy.zeros",
"megamix.utils_testing.checking.remove",
"numpy.sqrt"
] |
[((595, 634), 'megamix.utils_testing.checking.remove', 'checking.remove', (["(self.file_name + '.h5')"], {}), "(self.file_name + '.h5')\n", (610, 634), False, 'from megamix.utils_testing import checking\n'), ((699, 739), 'numpy.random.randn', 'np.random.randn', (['self.n_points', 'self.dim'], {}), '(self.n_points, self.dim)\n', (714, 739), True, 'import numpy as np\n'), ((752, 801), 'megamix.online.GaussianMixture', 'GaussianMixture', (['self.n_components'], {'window': 'window'}), '(self.n_components, window=window)\n', (767, 801), False, 'from megamix.online import GaussianMixture\n'), ((1428, 1468), 'numpy.random.randn', 'np.random.randn', (['self.n_points', 'self.dim'], {}), '(self.n_points, self.dim)\n', (1443, 1468), True, 'import numpy as np\n'), ((1481, 1530), 'megamix.online.GaussianMixture', 'GaussianMixture', (['self.n_components'], {'window': 'window'}), '(self.n_components, window=window)\n', (1496, 1530), False, 'from megamix.online import GaussianMixture\n'), ((1546, 1590), 'numpy.random.randn', 'np.random.randn', (['self.n_components', 'self.dim'], {}), '(self.n_components, self.dim)\n', (1561, 1590), True, 'import numpy as np\n'), ((1718, 1762), 'numpy.zeros', 'np.zeros', (['(self.n_points, self.n_components)'], {}), '((self.n_points, self.n_components))\n', (1726, 1762), True, 'import numpy as np\n'), ((1783, 1809), 'megamix.online.dist_matrix', 'dist_matrix', (['points', 'means'], {}), '(points, means)\n', (1794, 1809), False, 'from megamix.online import dist_matrix\n'), ((2272, 2321), 'numpy.zeros', 'np.zeros', (['(self.n_components, self.dim, self.dim)'], {}), '((self.n_components, self.dim, self.dim))\n', (2280, 2321), True, 'import numpy as np\n'), ((2678, 2726), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['expected_cov', 'predected_cov'], {}), '(expected_cov, predected_cov)\n', (2697, 2726), False, 'from numpy.testing import assert_almost_equal\n'), ((2786, 2826), 'numpy.random.randn', 'np.random.randn', (['self.n_points', 'self.dim'], {}), '(self.n_points, self.dim)\n', (2801, 2826), True, 'import numpy as np\n'), ((2839, 2888), 'megamix.online.GaussianMixture', 'GaussianMixture', (['self.n_components'], {'window': 'window'}), '(self.n_components, window=window)\n', (2854, 2888), False, 'from megamix.online import GaussianMixture\n'), ((3185, 3215), 'scipy.special.logsumexp', 'logsumexp', (['log_product'], {'axis': '(1)'}), '(log_product, axis=1)\n', (3194, 3215), False, 'from scipy.special import logsumexp\n'), ((3393, 3461), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['expected_log_prob_norm', 'predected_log_prob_norm'], {}), '(expected_log_prob_norm, predected_log_prob_norm)\n', (3412, 3461), False, 'from numpy.testing import assert_almost_equal\n'), ((3469, 3527), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['expected_log_resp', 'predected_log_resp'], {}), '(expected_log_resp, predected_log_resp)\n', (3488, 3527), False, 'from numpy.testing import assert_almost_equal\n'), ((3594, 3634), 'numpy.random.randn', 'np.random.randn', (['self.n_points', 'self.dim'], {}), '(self.n_points, self.dim)\n', (3609, 3634), True, 'import numpy as np\n'), ((3647, 3711), 'megamix.online.GaussianMixture', 'GaussianMixture', (['self.n_components'], {'window': 'window', 'update': 'update'}), '(self.n_components, window=window, update=update)\n', (3662, 3711), False, 'from megamix.online import GaussianMixture\n'), ((4063, 4081), 'numpy.empty_like', 'np.empty_like', (['cov'], {}), '(cov)\n', (4076, 4081), True, 'import numpy as np\n'), ((4525, 4565), 'numpy.random.randn', 'np.random.randn', (['self.n_points', 'self.dim'], {}), '(self.n_points, self.dim)\n', (4540, 4565), True, 'import numpy as np\n'), ((4578, 4642), 'megamix.online.GaussianMixture', 'GaussianMixture', (['self.n_components'], {'window': 'window', 'update': 'update'}), '(self.n_components, window=window, update=update)\n', (4593, 4642), False, 'from megamix.online import GaussianMixture\n'), ((4811, 4827), 'numpy.exp', 'np.exp', (['log_resp'], {}), '(log_resp)\n', (4817, 4827), True, 'import numpy as np\n'), ((5050, 5076), 'numpy.dot', 'np.dot', (['resp.T', 'points_exp'], {}), '(resp.T, points_exp)\n', (5056, 5076), True, 'import numpy as np\n'), ((5118, 5167), 'numpy.zeros', 'np.zeros', (['(self.n_components, self.dim, self.dim)'], {}), '((self.n_components, self.dim, self.dim))\n', (5126, 5167), True, 'import numpy as np\n'), ((5659, 5708), 'numpy.zeros', 'np.zeros', (['(self.n_components, self.dim, self.dim)'], {}), '((self.n_components, self.dim, self.dim))\n', (5667, 5708), True, 'import numpy as np\n'), ((6114, 6154), 'numpy.random.randn', 'np.random.randn', (['self.n_points', 'self.dim'], {}), '(self.n_points, self.dim)\n', (6129, 6154), True, 'import numpy as np\n'), ((6172, 6212), 'numpy.random.randn', 'np.random.randn', (['self.n_points', 'self.dim'], {}), '(self.n_points, self.dim)\n', (6187, 6212), True, 'import numpy as np\n'), ((6225, 6289), 'megamix.online.GaussianMixture', 'GaussianMixture', (['self.n_components'], {'window': 'window', 'update': 'update'}), '(self.n_components, window=window, update=update)\n', (6240, 6289), False, 'from megamix.online import GaussianMixture\n'), ((6578, 6618), 'numpy.random.randn', 'np.random.randn', (['self.n_points', 'self.dim'], {}), '(self.n_points, self.dim)\n', (6593, 6618), True, 'import numpy as np\n'), ((6631, 6680), 'megamix.online.GaussianMixture', 'GaussianMixture', (['self.n_components'], {'update': 'update'}), '(self.n_components, update=update)\n', (6646, 6680), False, 'from megamix.online import GaussianMixture\n'), ((6731, 6769), 'h5py.File', 'h5py.File', (["(self.file_name + '.h5')", '"""w"""'], {}), "(self.file_name + '.h5', 'w')\n", (6740, 6769), False, 'import h5py\n'), ((6869, 6918), 'megamix.online.GaussianMixture', 'GaussianMixture', (['self.n_components'], {'update': 'update'}), '(self.n_components, update=update)\n', (6884, 6918), False, 'from megamix.online import GaussianMixture\n'), ((6939, 6977), 'h5py.File', 'h5py.File', (["(self.file_name + '.h5')", '"""r"""'], {}), "(self.file_name + '.h5', 'r')\n", (6948, 6977), False, 'import h5py\n'), ((7074, 7112), 'megamix.utils_testing.checking.verify_online_models', 'checking.verify_online_models', (['GM', 'GM2'], {}), '(GM, GM2)\n', (7103, 7112), False, 'from megamix.utils_testing import checking\n'), ((7185, 7223), 'megamix.utils_testing.checking.verify_online_models', 'checking.verify_online_models', (['GM', 'GM2'], {}), '(GM, GM2)\n', (7214, 7223), False, 'from megamix.utils_testing import checking\n'), ((7300, 7340), 'numpy.random.randn', 'np.random.randn', (['self.n_points', 'self.dim'], {}), '(self.n_points, self.dim)\n', (7315, 7340), True, 'import numpy as np\n'), ((7353, 7417), 'megamix.online.GaussianMixture', 'GaussianMixture', (['self.n_components'], {'window': 'window', 'update': 'update'}), '(self.n_components, window=window, update=update)\n', (7368, 7417), False, 'from megamix.online import GaussianMixture\n'), ((7670, 7728), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['predected_log_resp', 'expected_log_resp'], {}), '(predected_log_resp, expected_log_resp)\n', (7689, 7728), False, 'from numpy.testing import assert_almost_equal\n'), ((7788, 7828), 'numpy.random.randn', 'np.random.randn', (['self.n_points', 'self.dim'], {}), '(self.n_points, self.dim)\n', (7803, 7828), True, 'import numpy as np\n'), ((7841, 7903), 'megamix.online.GaussianMixture', 'GaussianMixture', (['self.n_components'], {'window': 'window', 'update': '(True)'}), '(self.n_components, window=window, update=True)\n', (7856, 7903), False, 'from megamix.online import GaussianMixture\n'), ((8001, 8050), 'numpy.zeros', 'np.zeros', (['(self.n_components, self.dim, self.dim)'], {}), '((self.n_components, self.dim, self.dim))\n', (8009, 8050), True, 'import numpy as np\n'), ((8246, 8304), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['expected_cov_chol', 'predected_cov_chol'], {}), '(expected_cov_chol, predected_cov_chol)\n', (8265, 8304), False, 'from numpy.testing import assert_almost_equal\n'), ((8366, 8406), 'numpy.random.randn', 'np.random.randn', (['self.n_points', 'self.dim'], {}), '(self.n_points, self.dim)\n', (8381, 8406), True, 'import numpy as np\n'), ((8419, 8468), 'megamix.online.GaussianMixture', 'GaussianMixture', (['self.n_components'], {'window': 'window'}), '(self.n_components, window=window)\n', (8434, 8468), False, 'from megamix.online import GaussianMixture\n'), ((8485, 8524), 'megamix.utils_testing.checking.remove', 'checking.remove', (["(self.file_name + '.h5')"], {}), "(self.file_name + '.h5')\n", (8500, 8524), False, 'from megamix.utils_testing import checking\n'), ((8661, 8699), 'h5py.File', 'h5py.File', (["(self.file_name + '.h5')", '"""r"""'], {}), "(self.file_name + '.h5', 'r')\n", (8670, 8699), False, 'import h5py\n'), ((8837, 8876), 'megamix.utils_testing.checking.remove', 'checking.remove', (["(self.file_name + '.h5')"], {}), "(self.file_name + '.h5')\n", (8852, 8876), False, 'from megamix.utils_testing import checking\n'), ((8988, 9026), 'h5py.File', 'h5py.File', (["(self.file_name + '.h5')", '"""r"""'], {}), "(self.file_name + '.h5', 'r')\n", (8997, 9026), False, 'import h5py\n'), ((1872, 1887), 'numpy.argmin', 'np.argmin', (['M[i]'], {}), '(M[i])\n', (1881, 1887), True, 'import numpy as np\n'), ((2188, 2216), 'numpy.sum', 'np.sum', (['assignements'], {'axis': '(0)'}), '(assignements, axis=0)\n', (2194, 2216), True, 'import numpy as np\n'), ((2476, 2505), 'numpy.dot', 'np.dot', (['diff_weighted.T', 'diff'], {}), '(diff_weighted.T, diff)\n', (2482, 2505), True, 'import numpy as np\n'), ((4151, 4186), 'scipy.linalg.cholesky', 'linalg.cholesky', (['cov[i]'], {'lower': '(True)'}), '(cov[i], lower=True)\n', (4166, 4186), False, 'from scipy import linalg\n'), ((5337, 5375), 'numpy.dot', 'np.dot', (['diff_weighted.T', 'diff_weighted'], {}), '(diff_weighted.T, diff_weighted)\n', (5343, 5375), True, 'import numpy as np\n'), ((5783, 5825), 'scipy.linalg.cholesky', 'linalg.cholesky', (['expected_S[i]'], {'lower': '(True)'}), '(expected_S[i], lower=True)\n', (5798, 5825), False, 'from scipy import linalg\n'), ((6310, 6334), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (6323, 6334), False, 'import pytest\n'), ((7438, 7462), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (7451, 7462), False, 'import pytest\n'), ((5295, 5320), 'numpy.sqrt', 'np.sqrt', (['resp[:, i:i + 1]'], {}), '(resp[:, i:i + 1])\n', (5302, 5320), True, 'import numpy as np\n'), ((4984, 5004), 'numpy.finfo', 'np.finfo', (['resp.dtype'], {}), '(resp.dtype)\n', (4992, 5004), True, 'import numpy as np\n'), ((9129, 9159), 'numpy.log', 'np.log', (['(self.n_points / window)'], {}), '(self.n_points / window)\n', (9135, 9159), True, 'import numpy as np\n'), ((9158, 9167), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (9164, 9167), True, 'import numpy as np\n')]
|
import numpy as np
import random
from time import time
random.seed(42)
def semi_greedy_construction(window, number_items, weight_max, values_items, weight_items):
efficiency = np.divide(values_items, weight_items)
items = {}
for i in range(number_items):
items[i] = efficiency[i], values_items[i], weight_items[i]
items = sorted(items.values(), reverse=True)
result_final = []
value = 0
weight = 0
aux = items[:]
while len(items) > 0 and weight < weight_max:
if len(items) >= window: tmp_window = window
else: tmp_window = len(items)
index = random.randint(0,tmp_window-1)
value_item = items[index][1]
weight_item = items[index][2]
if weight_item+weight <= weight_max:
result_final.append(items[index][1])
value += value_item
weight += weight_item
del items[index]
solution = np.zeros(number_items,dtype=np.int16)
for item in values_items:
if item in result_final: solution[values_items.index(item)] = 1
return solution, value, weight
def local_search(solution, values_items, weight_items, value, weight, weight_max):
length = len(solution)
neighbor = (solution.copy(), value, weight)
for i in range(length):
new_weight = 0
new_value = 0
if solution[i] == 0:
if weight+weight_items[i] <= weight_max:
if value+values_items[i] > neighbor[1]:
temp = solution.copy()
temp[i] = 1
neighbor = temp, weight+weight_items[i], value+values_items[i]
if value == neighbor[1] :return value
return local_search(neighbor[0], values_items, weight_items, neighbor[1], neighbor[2], weight_max)
def grasp(max_it, window, number_items, weight_max, values_items, weight_items):
best_solution = 0
for i in range(max_it):
solution, value, weight = semi_greedy_construction(window, number_items, weight_max, values_items, weight_items)
solution = local_search(solution, values_items, weight_items, value, weight, weight_max)
if solution > best_solution: best_solution = solution
return best_solution
|
[
"numpy.zeros",
"numpy.divide",
"random.seed",
"random.randint"
] |
[((56, 71), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (67, 71), False, 'import random\n'), ((179, 216), 'numpy.divide', 'np.divide', (['values_items', 'weight_items'], {}), '(values_items, weight_items)\n', (188, 216), True, 'import numpy as np\n'), ((816, 854), 'numpy.zeros', 'np.zeros', (['number_items'], {'dtype': 'np.int16'}), '(number_items, dtype=np.int16)\n', (824, 854), True, 'import numpy as np\n'), ((563, 596), 'random.randint', 'random.randint', (['(0)', '(tmp_window - 1)'], {}), '(0, tmp_window - 1)\n', (577, 596), False, 'import random\n')]
|
import numpy as np
m,n = [int(i) for i in '2 7'.strip().split(' ')]
data1=[
'0.18 0.89 109.85',
'1.0 0.26 155.72',
'0.92 0.11 137.66',
'0.07 0.37 76.17',
'0.85 0.16 139.75',
'0.99 0.41 162.6',
'0.87 0.47 151.77'
]
X = []
Y = []
for item in data1:
data = item.strip().split(' ')
X.append(data[:m])
Y.append(data[m:])
data2 = [
'0.49 0.18',
'0.57 0.83',
'0.56 0.64',
'0.76 0.18'
]
X_new = []
for item in data2:
X_new.append(item.strip().split(' '))
X = np.array(X,float)
Y = np.array(Y,float)
X_new = np.array(X_new,float)
#center
X_R = X-np.mean(X,axis=0)
Y_R = Y-np.mean(Y)
#calculate beta
beta = np.dot(np.linalg.inv(np.dot(X_R.T,X_R)),np.dot(X_R.T,Y_R))
#predict
X_new_R = X_new-np.mean(X,axis=0)
Y_new_R = np.dot(X_new_R,beta)
Y_new = Y_new_R + np.mean(Y)
#print
for i in Y_new:
print(round(float(i),2))
|
[
"numpy.dot",
"numpy.mean",
"numpy.array"
] |
[((467, 485), 'numpy.array', 'np.array', (['X', 'float'], {}), '(X, float)\n', (475, 485), True, 'import numpy as np\n'), ((489, 507), 'numpy.array', 'np.array', (['Y', 'float'], {}), '(Y, float)\n', (497, 507), True, 'import numpy as np\n'), ((515, 537), 'numpy.array', 'np.array', (['X_new', 'float'], {}), '(X_new, float)\n', (523, 537), True, 'import numpy as np\n'), ((728, 749), 'numpy.dot', 'np.dot', (['X_new_R', 'beta'], {}), '(X_new_R, beta)\n', (734, 749), True, 'import numpy as np\n'), ((554, 572), 'numpy.mean', 'np.mean', (['X'], {'axis': '(0)'}), '(X, axis=0)\n', (561, 572), True, 'import numpy as np\n'), ((580, 590), 'numpy.mean', 'np.mean', (['Y'], {}), '(Y)\n', (587, 590), True, 'import numpy as np\n'), ((655, 673), 'numpy.dot', 'np.dot', (['X_R.T', 'Y_R'], {}), '(X_R.T, Y_R)\n', (661, 673), True, 'import numpy as np\n'), ((700, 718), 'numpy.mean', 'np.mean', (['X'], {'axis': '(0)'}), '(X, axis=0)\n', (707, 718), True, 'import numpy as np\n'), ((767, 777), 'numpy.mean', 'np.mean', (['Y'], {}), '(Y)\n', (774, 777), True, 'import numpy as np\n'), ((636, 654), 'numpy.dot', 'np.dot', (['X_R.T', 'X_R'], {}), '(X_R.T, X_R)\n', (642, 654), True, 'import numpy as np\n')]
|
import argparse
import yaml
import os
from glob import glob
import inspect
import sys
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)
import time
import numpy as np
import torch
from torch.utils.data import DataLoader
import skimage.io as io
from segmentation_dataset import RawChromosomeDataset as Dataset
from loss import DiceLoss, evals
from models.UNet import UNet
from models.ResUNet import ResUNet
from models.PreactivationResUNet import PreactResUNet
from models.CENet import CE_Net
from models.Segnet import SegNet
from models.AttentionUnet import AttU_Net
from models.FCN import FCN_ResNet101
from models.Unet_nested import UNet_Nested
from models.DeepLabV3 import Deeplabv3_ResNet101
from models.PSPNet import PSPNet
def main(args):
# args.model = "preactivation_resunet"
# args.model_path = "preactivation_resunet-20210416T1703"
# args.weight_num = 1
# args.images = "./datasets/raw_chromosome_data".format(Dataset.name)
# args.batch_size = 2
# args.test_results = False
if args.model == "unet":
model = UNet(
in_channels=Dataset.in_channels,
num_classes=Dataset.num_classes,
init_features=32,
)
net_name = UNet.net_name
elif args.model == "resunet":
model = ResUNet(
in_channels=Dataset.in_channels,
num_classes=Dataset.num_classes,
init_features=32,
)
net_name = "resunet"
elif args.model == "preactivation_resunet":
model = PreactResUNet(
in_channels=Dataset.in_channels,
num_classes=Dataset.num_classes,
init_features=32,
)
net_name = "preactivation_resunet"
elif args.model == "cenet":
model = CE_Net(in_channels=Dataset.in_channels, num_classes=Dataset.num_classes)
net_name = "cenet"
elif args.model == "segnet":
model = SegNet(in_channels=Dataset.in_channels, num_classes=Dataset.num_classes)
net_name = "segnet"
elif args.model == "nested_unet":
model = UNet_Nested(
in_channels=Dataset.in_channels, num_classes=Dataset.num_classes
)
net_name = "nested_unet"
elif args.model == "attention_unet":
model = AttU_Net(
in_channels=Dataset.in_channels, num_classes=Dataset.num_classes
)
net_name = "attention_unet"
elif args.model == "fcn_resnet101":
model = FCN_ResNet101(in_channels=1, num_classes=3)
net_name = "fcn_resnet101"
elif args.model == "deeplabv3_resnet101":
model = Deeplabv3_ResNet101(in_channels=1, num_classes=3)
net_name = "deeplabv3_resnet101"
elif args.model == "pspnet":
model = PSPNet(
num_classes=Dataset.num_classes, pretrained=False, backend="resnet101"
)
net_name = "pspnet"
device = torch.device("cpu" if not torch.cuda.is_available() else args.device)
model.to(device)
weights_dir = "output/{}/{}/weights".format(Dataset.name, args.model_path)
print(weights_dir)
model_name = glob(weights_dir + "/{}-{}*".format(net_name, args.weight_num))[0]
state_dict = torch.load(model_name, map_location=device)
model.load_state_dict(state_dict)
test_dir = "output/{}/{}/test".format(Dataset.name, args.model_path)
model.eval()
dsc = DiceLoss()
evaluations_np = []
total_dsc_loss = []
loader = data_loaders(args)
loaders = {"test": loader}
start = time.time()
print("clock started")
test_img_num = 1
for i, data in enumerate(loaders["test"], 0):
x, y_true = data
x, y_true = x.to(device, dtype=torch.float), y_true.to(
device, dtype=torch.float
)
with torch.set_grad_enabled(False):
y_pred = model(x)
dsc_loss = dsc(y_pred, y_true)
evaluations_ = evals(y_pred, y_true)
evaluations_np += evaluations_
total_dsc_loss.append(dsc_loss.item())
if args.test_results:
y_pred_np = y_pred.detach().cpu().numpy()
x_np = x.detach().cpu().numpy()
for img_num in range(y_pred_np.shape[0]):
for mask_num in range(y_pred_np.shape[1]):
io.imsave(
os.path.join(
test_dir,
"{}_label{}.png".format(test_img_num, mask_num),
),
y_pred_np[img_num, mask_num, :, :],
)
for mask_num in range(x_np.shape[1]):
io.imsave(
os.path.join(test_dir, "%d_image.png" % test_img_num),
x_np[img_num, mask_num, :, :] * 255,
)
test_img_num += 1
end = time.time()
print("{} seconds past".format(end - start))
evaluations_np = np.array(evaluations_np)
with open(
"output/{}/{}/test-eval.npy".format(Dataset.name, args.model_path), "wb"
) as f:
np.save(f, evaluations_np)
mean_dsc_loss = float(np.mean(total_dsc_loss))
mean_DSC = 1 - mean_dsc_loss
metrics = {
"mean_dsc_loss": mean_dsc_loss,
"mean_DSC": mean_DSC,
}
with open(
"output/{}/{}/metrics.yaml".format(Dataset.name, args.model_path), "w"
) as fp:
yaml.dump(metrics, fp)
print(f"mean dsc loss={mean_dsc_loss}")
print(f"mean DSC={mean_DSC}")
def data_loaders(args):
dataset_test = datasets(args)
return DataLoader(
dataset_test,
batch_size=args.batch_size,
drop_last=False,
num_workers=args.workers,
)
def datasets(args):
return Dataset(
args,
images_dir=args.images,
subset="test",
image_size=args.image_size,
random_sampling=False,
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Semantic segmentation of G-banding chromosome Images"
)
parser.add_argument(
"--model",
type=str,
default="preactivation_resunet",
help="choose model",
)
parser.add_argument(
"--weight-num",
type=int,
default=0,
help="weight number for inference",
)
parser.add_argument(
"--model-path", type=str, default="", help="path to weights file"
)
parser.add_argument(
"--batch-size",
type=int,
default=2,
help="input batch size for training (default: 2)",
)
parser.add_argument(
"--device",
type=str,
default="cuda:0",
help="device for training (default: cuda:0)",
)
parser.add_argument(
"--workers",
type=int,
default=1,
help="number of workers for data loading (default: 1)",
)
parser.add_argument(
"--images",
type=str,
default="./datasets/{}_data/train".format(Dataset.name),
help="root folder with images",
)
parser.add_argument(
"--image-size",
type=int,
default=Dataset.img_size,
help="target input image size (default: 256x256)",
)
parser.add_argument(
"--test-results",
type=bool,
default=False,
help="Do you want to output the test results? (defauld: False)",
)
args = parser.parse_args()
main(args)
|
[
"argparse.ArgumentParser",
"segmentation_dataset.RawChromosomeDataset",
"models.UNet.UNet",
"yaml.dump",
"numpy.mean",
"models.Segnet.SegNet",
"models.AttentionUnet.AttU_Net",
"loss.DiceLoss",
"os.path.join",
"torch.utils.data.DataLoader",
"os.path.dirname",
"torch.load",
"models.FCN.FCN_ResNet101",
"numpy.save",
"models.ResUNet.ResUNet",
"torch.cuda.is_available",
"torch.set_grad_enabled",
"inspect.currentframe",
"models.CENet.CE_Net",
"models.DeepLabV3.Deeplabv3_ResNet101",
"models.PreactivationResUNet.PreactResUNet",
"loss.evals",
"models.Unet_nested.UNet_Nested",
"sys.path.insert",
"time.time",
"numpy.array",
"models.PSPNet.PSPNet"
] |
[((196, 224), 'os.path.dirname', 'os.path.dirname', (['current_dir'], {}), '(current_dir)\n', (211, 224), False, 'import os\n'), ((226, 256), 'sys.path.insert', 'sys.path.insert', (['(0)', 'parent_dir'], {}), '(0, parent_dir)\n', (241, 256), False, 'import sys\n'), ((3355, 3398), 'torch.load', 'torch.load', (['model_name'], {'map_location': 'device'}), '(model_name, map_location=device)\n', (3365, 3398), False, 'import torch\n'), ((3547, 3557), 'loss.DiceLoss', 'DiceLoss', ([], {}), '()\n', (3555, 3557), False, 'from loss import DiceLoss, evals\n'), ((3692, 3703), 'time.time', 'time.time', ([], {}), '()\n', (3701, 3703), False, 'import time\n'), ((5142, 5153), 'time.time', 'time.time', ([], {}), '()\n', (5151, 5153), False, 'import time\n'), ((5228, 5252), 'numpy.array', 'np.array', (['evaluations_np'], {}), '(evaluations_np)\n', (5236, 5252), True, 'import numpy as np\n'), ((5884, 5983), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset_test'], {'batch_size': 'args.batch_size', 'drop_last': '(False)', 'num_workers': 'args.workers'}), '(dataset_test, batch_size=args.batch_size, drop_last=False,\n num_workers=args.workers)\n', (5894, 5983), False, 'from torch.utils.data import DataLoader\n'), ((6061, 6169), 'segmentation_dataset.RawChromosomeDataset', 'Dataset', (['args'], {'images_dir': 'args.images', 'subset': '"""test"""', 'image_size': 'args.image_size', 'random_sampling': '(False)'}), "(args, images_dir=args.images, subset='test', image_size=args.\n image_size, random_sampling=False)\n", (6068, 6169), True, 'from segmentation_dataset import RawChromosomeDataset as Dataset\n'), ((6264, 6360), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Semantic segmentation of G-banding chromosome Images"""'}), "(description=\n 'Semantic segmentation of G-banding chromosome Images')\n", (6287, 6360), False, 'import argparse\n'), ((1212, 1304), 'models.UNet.UNet', 'UNet', ([], {'in_channels': 'Dataset.in_channels', 'num_classes': 'Dataset.num_classes', 'init_features': '(32)'}), '(in_channels=Dataset.in_channels, num_classes=Dataset.num_classes,\n init_features=32)\n', (1216, 1304), False, 'from models.UNet import UNet\n'), ((5373, 5399), 'numpy.save', 'np.save', (['f', 'evaluations_np'], {}), '(f, evaluations_np)\n', (5380, 5399), True, 'import numpy as np\n'), ((5429, 5452), 'numpy.mean', 'np.mean', (['total_dsc_loss'], {}), '(total_dsc_loss)\n', (5436, 5452), True, 'import numpy as np\n'), ((5703, 5725), 'yaml.dump', 'yaml.dump', (['metrics', 'fp'], {}), '(metrics, fp)\n', (5712, 5725), False, 'import yaml\n'), ((156, 178), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (176, 178), False, 'import inspect\n'), ((1438, 1533), 'models.ResUNet.ResUNet', 'ResUNet', ([], {'in_channels': 'Dataset.in_channels', 'num_classes': 'Dataset.num_classes', 'init_features': '(32)'}), '(in_channels=Dataset.in_channels, num_classes=Dataset.num_classes,\n init_features=32)\n', (1445, 1533), False, 'from models.ResUNet import ResUNet\n'), ((3966, 3995), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (3988, 3995), False, 'import torch\n'), ((4102, 4123), 'loss.evals', 'evals', (['y_pred', 'y_true'], {}), '(y_pred, y_true)\n', (4107, 4123), False, 'from loss import DiceLoss, evals\n'), ((1677, 1779), 'models.PreactivationResUNet.PreactResUNet', 'PreactResUNet', ([], {'in_channels': 'Dataset.in_channels', 'num_classes': 'Dataset.num_classes', 'init_features': '(32)'}), '(in_channels=Dataset.in_channels, num_classes=Dataset.\n num_classes, init_features=32)\n', (1690, 1779), False, 'from models.PreactivationResUNet import PreactResUNet\n'), ((3080, 3105), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3103, 3105), False, 'import torch\n'), ((1920, 1992), 'models.CENet.CE_Net', 'CE_Net', ([], {'in_channels': 'Dataset.in_channels', 'num_classes': 'Dataset.num_classes'}), '(in_channels=Dataset.in_channels, num_classes=Dataset.num_classes)\n', (1926, 1992), False, 'from models.CENet import CE_Net\n'), ((2072, 2144), 'models.Segnet.SegNet', 'SegNet', ([], {'in_channels': 'Dataset.in_channels', 'num_classes': 'Dataset.num_classes'}), '(in_channels=Dataset.in_channels, num_classes=Dataset.num_classes)\n', (2078, 2144), False, 'from models.Segnet import SegNet\n'), ((2230, 2307), 'models.Unet_nested.UNet_Nested', 'UNet_Nested', ([], {'in_channels': 'Dataset.in_channels', 'num_classes': 'Dataset.num_classes'}), '(in_channels=Dataset.in_channels, num_classes=Dataset.num_classes)\n', (2241, 2307), False, 'from models.Unet_nested import UNet_Nested\n'), ((4942, 4995), 'os.path.join', 'os.path.join', (['test_dir', "('%d_image.png' % test_img_num)"], {}), "(test_dir, '%d_image.png' % test_img_num)\n", (4954, 4995), False, 'import os\n'), ((2425, 2499), 'models.AttentionUnet.AttU_Net', 'AttU_Net', ([], {'in_channels': 'Dataset.in_channels', 'num_classes': 'Dataset.num_classes'}), '(in_channels=Dataset.in_channels, num_classes=Dataset.num_classes)\n', (2433, 2499), False, 'from models.AttentionUnet import AttU_Net\n'), ((2619, 2662), 'models.FCN.FCN_ResNet101', 'FCN_ResNet101', ([], {'in_channels': '(1)', 'num_classes': '(3)'}), '(in_channels=1, num_classes=3)\n', (2632, 2662), False, 'from models.FCN import FCN_ResNet101\n'), ((2763, 2812), 'models.DeepLabV3.Deeplabv3_ResNet101', 'Deeplabv3_ResNet101', ([], {'in_channels': '(1)', 'num_classes': '(3)'}), '(in_channels=1, num_classes=3)\n', (2782, 2812), False, 'from models.DeepLabV3 import Deeplabv3_ResNet101\n'), ((2906, 2984), 'models.PSPNet.PSPNet', 'PSPNet', ([], {'num_classes': 'Dataset.num_classes', 'pretrained': '(False)', 'backend': '"""resnet101"""'}), "(num_classes=Dataset.num_classes, pretrained=False, backend='resnet101')\n", (2912, 2984), False, 'from models.PSPNet import PSPNet\n')]
|
import os
import struct
import numpy as np
import xarray as xr
import netCDF4 as ds
from pathlib import Path
import matplotlib.pyplot as plt
import struct
import itertools
import Homogenizer_GUI
from enum import Enum
from collections import OrderedDict
import pickle
class UserPrefs(Enum):
ScanFoldersPath = 0
CalculateReconstructedImages = 1
CalculateFieldMaps = 2
CalculateInterpolatedFieldMap = 3
SaveReconstructedImages = 4
SaveFieldMaps = 5
SaveInterpolatedFieldMap = 6
ShowReconstructedImages = 7
ShowFieldMaps = 8
ShowInterpolatedFieldMap = 9
class Homogenizer:
def __init__(self):
self.hGUI = None
self.submit_button = "Submit"
self.gamma = 48.52*10**6
self.te_array = []
self.delta_te = 0.0001 #standard initialization
self.dimensions = np.array([128,128]) #standard initialization
self.scan_folders_path = None
self.save_path = None
self.fids_dict = OrderedDict([])
self.reconstructed_image_dict = OrderedDict([])
self.field_map_dict = OrderedDict([])
self.interpolated_field_map = OrderedDict([])
def get_input(self, user_pref: UserPrefs):
return self.hGUI.user_prefs[user_pref.value]
def display_image(self, image_list, abs_values = False):
'''
Displays given images. mark abs_values as True to get the display images of abs values
'''
for image in image_list:
if abs_values:
image = abs(image)
plt.title("Reconstructed Image")
else:
plt.title("Field Map - B[T] Values as function of location")
plt.xlabel("Location")
plt.ylabel("Location")
plt.imshow(image)
plt.colorbar()
plt.show()
def get_tes(self, folder_path):
'''
Finds the TE value in a specific scan (the information exists in the 'method' file of each scan)
Then creates an array of all TEs
'''
dir_list = os.listdir(folder_path)
for scan_dir in dir_list:
file_path = folder_path + '\\' + scan_dir
if os.path.isdir(file_path):
method_path = self.find_file_by_name(file_path, 'method')
with open(method_path, mode='rb') as file:
method_r = file.read()
f=method_r.find(b'EchoTime=')
te_locked=method_r[f+9:f+12]
te_str=str(te_locked)[2:5]
if (str(te_str).find('n') != -1):
te=int(te_str[0])
else:
te=float(te_str)
self.te_array.append(te*10**-3)
del self.te_array[-1]
self.te_array = np.array(self.te_array)
self.delta_te = self.te_array[1] - self.te_array[0]
def get_dimensions(self, folder_path):
'''
Finds the dimensions of the matrix (the information exists in the 'method' file of each scan)
'''
dir_list = os.listdir(folder_path)
for scan_dir in dir_list:
file_path = folder_path + '\\' + scan_dir
if os.path.isdir(file_path):
method_path = self.find_file_by_name(file_path, 'method')
break
with open(method_path, mode='rb') as file:
method_r = file.read()
f=method_r.find(b'PVM_Matrix=( 2 )\n')
dimension_locked=method_r[f+17:f+24]
arr=np.zeros(2, np.int16)
arr[0]=(str(dimension_locked)[2:5])
arr[0]=int(arr[0])
arr[1]=(str(dimension_locked)[6:9])
arr[1]=int(arr[1])
self.dimensions = arr
pickle.dump(self.dimensions, open("dimensions.dat","wb"))
def find_file_by_name(self, containing_folder, name_string):
'''
Finds and returns the fid file within the given folder
'''
pickle.dump(containing_folder, open("containing_folder.dat","wb"))
pickle.dump(name_string, open("name_string.dat","wb"))
dir_list = os.listdir(containing_folder)
for file_name in dir_list:
if file_name == name_string:
file_path = containing_folder + '\\' + file_name
return file_path
def save_arrays_to_disk(self, save_path, arrays_dictionary: dict, name_prefix: str):
"""
Converts every numpy array in arrays_dictionary to xarray and save it in the given path as a NetCDF file.
"""
if not os.path.exists(save_path):
os.makedirs(save_path)
for key, array in arrays_dictionary.items():
x_arr = xr.DataArray(array)
file_name = name_prefix + str(key)
x_arr.to_netcdf(f'{save_path}\\{file_name}.nc', mode='w')
def reconstruct_images_from_fids(self, fid_dict):
for name_prefix, fid in fid_dict.items():
self.reconstructed_image_dict[name_prefix] = self.reconstruct_image(fid, self.dimensions)
def reconstruct_image(self, fid_arr, dimensions):
'''
Calculates the K space matrix -> calculates the
reconstructed image and returns it
'''
pickle.dump(fid_arr, open("fid_arr.dat","wb"))
real_vals = fid_arr[:-1:2]
imag_vals = fid_arr[1::2]
complex_vals = real_vals + 1j*imag_vals
if (len(fid_arr) == dimensions[0]*dimensions[1]*2):
k_space_scan = np.reshape(complex_vals,(dimensions[0],dimensions[1]))
k_casting = k_space_scan.astype(complex)
img = np.fft.fftshift(np.fft.ifft2(k_casting))
return img
else:
raise IndexError('Fid_arr cannot be reshaped to these dimensions')
def calc_field_maps_from_fids (self, fid_dict, dimension):
''' Gets an ordered dictionary of FID files and calculates dictionary of field maps
by running on pairs of FID files
'''
pickle.dump(fid_dict, open("fid_dict.dat","wb"))
self.reconstruct_images_from_fids(fid_dict)
image_pairs = self.pairwise(self.reconstructed_image_dict.values())
name_index = 0
name_list = list(self.reconstructed_image_dict.keys())
for img1, img2 in image_pairs:
field_map_prefix = name_list[name_index] + name_list[name_index+1]
name_index +=1
self.field_map_dict[field_map_prefix] = self.calc_field_map_from_reconstructed_images(img1,img2)
def calc_field_map_from_reconstructed_images(self, img1,img2):
pickle.dump(img1, open("img1.dat","wb"))
pickle.dump(img2, open("img2.dat","wb"))
phase_map = self.compute_phase(img1,img2)
bmap = phase_map/((2*np.pi*self.gamma*(self.delta_te)))
return bmap
def compute_phase(self, img1,img2):
'''
Gets two reconstructed images and computes one phase image
'''
conj_img2 = np.conj(img2)
if (img1.shape[1] == img2.shape[0]):
multiplic_img1_img2 = conj_img2*img1
phase_map = np.angle(multiplic_img1_img2)
return phase_map
else:
raise IndexError('Size of matrices not suitable for linear multiplication')
def pairwise(self, object_list):
'''
Creates pairs of objects from a list of objects
list_of_fids -> (fid0,fid1), (fid1,fid2), (fid2, fid3), and so forth...
'''
pickle.dump(list(object_list), open("object_list.dat","wb"))
obj1, obj2 = itertools.tee(object_list)
next(obj2, None)
return zip(obj1, obj2)
def interpolate_field_map_from_fids(self, fid_dict):
'''
Gets an ordered dictionary of FID files and calculates one interpolated field map
'''
signals_amount = len(fid_dict)
self.calc_field_maps_from_fids(fid_dict, self.dimensions)
self.interpolate_field_map(list(self.field_map_dict.values()), self.te_array, self.dimensions,signals_amount)
def interpolate_field_map(self, field_maps_list,te_values, dimension, signals_amount):
'''
Calculates one interpolated field map from all the calculated field maps
'''
pickle.dump(field_maps_list, open("field_maps_list.dat","wb"))
pickle.dump(te_values, open("te_values.dat","wb"))
pickle.dump(signals_amount, open("signals_amoung.dat","wb"))
slope=np.zeros((dimension[0],dimension[1]))
value_vec_in_phase_map = np.zeros(len(field_maps_list))
for x in range(dimension[0]-1):
for y in range(dimension[1]-1):
for z in range(signals_amount-1):
value_vec_in_phase_map[z] = field_maps_list[z][x,y]
s,intercept = np.polyfit((te_values[:]),value_vec_in_phase_map,1)
slope[x,y] = (s)
interp_b=slope/self.gamma
self.interpolated_field_map = OrderedDict([('',interp_b)])
def create_fid_dict(self, folder_path):
'''
Creates an ordered dictionary of numpy arrays from fid files
'''
pickle.dump(folder_path, open("folder_path.dat","wb"))
dir_list = os.listdir(folder_path)
for scan_dir in dir_list:
file_path = folder_path + '\\' + scan_dir
if os.path.isdir(file_path):
fid_path = self.find_file_by_name(file_path, 'fid')
if isinstance(fid_path, str):
self.fids_dict[scan_dir] = self.fid_to_nparray(fid_path)
def fid_to_nparray(self, fid_path):
'''
Opens a binary file and inserts it to a numpy array
'''
pickle.dump(fid_path, open("fid_path.dat","wb"))
with open(fid_path, mode='rb') as file: # b is important -> binary
fid_r = file.read()
fid_l = list(struct.unpack("i" * ((len(fid_r) -4) // 4), fid_r[0:-4]))
fid_l.append(struct.unpack("i", fid_r[-4:])[0])
fid_arr = np.array(fid_l)
return fid_arr
def start(self):
'''
Triggers calculations begin with given inputs by the user throughout the GUI.
'''
self.scan_folders_path = self.hGUI.open_main_window()
# Starts job if user had pressed submit:
if self.hGUI.last_button_pressed == self.submit_button:
# Checks if user requested to save any files, and if so pops up a browser to choose path.
if (self.get_input(UserPrefs.SaveReconstructedImages)
or self.get_input(UserPrefs.SaveFieldMaps)
or self.get_input(UserPrefs.SaveInterpolatedFieldMap)
):
self.save_path = self.hGUI.request_save_path()
# Cancels the job if the user had closed the window / pressed "Cancel":
if self.hGUI.last_button_pressed != self.submit_button:
self.start()
return
if self.save_path == self.hGUI.default_folder_expression:
self.save_path = self.scan_folders_path
self.create_fid_dict(self.scan_folders_path)
self.get_dimensions(self.scan_folders_path)
self.get_tes(self.scan_folders_path)
# Checks what calculation the user had requested, and performs them:
if self.get_input(UserPrefs.CalculateReconstructedImages):
self.reconstruct_images_from_fids(self.fids_dict)
else:
if self.get_input(UserPrefs.CalculateFieldMaps):
self.calc_field_maps_from_fids(self.fids_dict, self.dimensions)
else:
self.interpolate_field_map_from_fids(self.fids_dict)
if self.get_input(UserPrefs.SaveInterpolatedFieldMap):
self.save_arrays_to_disk(self.save_path, self.interpolated_field_map,'Interpolated_field_map')
if self.get_input(UserPrefs.ShowInterpolatedFieldMap):
self.display_image(list(self.interpolated_field_map.values()))
if self.get_input(UserPrefs.SaveFieldMaps):
self.save_arrays_to_disk(self.save_path, self.field_map_dict, 'Field_map_')
if self.get_input(UserPrefs.ShowFieldMaps):
self.display_image(list(self.field_map_dict.values()))
if self.get_input(UserPrefs.SaveReconstructedImages):
[real_dict, imaginary_dict] = seperate_complex_values_dict(self.reconstructed_image_dict)
self.save_arrays_to_disk(self.save_path, real_dict, 'Reconstructed_image_real')
self.save_arrays_to_disk(self.save_path, imaginary_dict, 'Reconstructed_image_imaginary')
if self.get_input(UserPrefs.ShowReconstructedImages):
self.display_image(list(self.field_map_dict.values()), True)
def seperate_complex_values_dict(dict):
real_dict = OrderedDict([])
imaginary_dict = OrderedDict([])
for name, complexNum in dict.items():
real_dict[name] = complexNum.real
imaginary_dict[name] = complexNum.imag
return [real_dict, imaginary_dict]
if __name__ == "__main__":
homogenizer = Homogenizer()
homogenizer.hGUI = Homogenizer_GUI.Homogenizer_GUI()
homogenizer.start()
|
[
"matplotlib.pyplot.title",
"Homogenizer_GUI.Homogenizer_GUI",
"numpy.polyfit",
"numpy.angle",
"numpy.fft.ifft2",
"matplotlib.pyplot.imshow",
"os.path.exists",
"matplotlib.pyplot.colorbar",
"numpy.reshape",
"numpy.conj",
"matplotlib.pyplot.show",
"struct.unpack",
"itertools.tee",
"matplotlib.pyplot.ylabel",
"os.listdir",
"os.makedirs",
"os.path.isdir",
"numpy.zeros",
"numpy.array",
"xarray.DataArray",
"collections.OrderedDict",
"matplotlib.pyplot.xlabel"
] |
[((13222, 13237), 'collections.OrderedDict', 'OrderedDict', (['[]'], {}), '([])\n', (13233, 13237), False, 'from collections import OrderedDict\n'), ((13260, 13275), 'collections.OrderedDict', 'OrderedDict', (['[]'], {}), '([])\n', (13271, 13275), False, 'from collections import OrderedDict\n'), ((13545, 13578), 'Homogenizer_GUI.Homogenizer_GUI', 'Homogenizer_GUI.Homogenizer_GUI', ([], {}), '()\n', (13576, 13578), False, 'import Homogenizer_GUI\n'), ((875, 895), 'numpy.array', 'np.array', (['[128, 128]'], {}), '([128, 128])\n', (883, 895), True, 'import numpy as np\n'), ((1016, 1031), 'collections.OrderedDict', 'OrderedDict', (['[]'], {}), '([])\n', (1027, 1031), False, 'from collections import OrderedDict\n'), ((1073, 1088), 'collections.OrderedDict', 'OrderedDict', (['[]'], {}), '([])\n', (1084, 1088), False, 'from collections import OrderedDict\n'), ((1120, 1135), 'collections.OrderedDict', 'OrderedDict', (['[]'], {}), '([])\n', (1131, 1135), False, 'from collections import OrderedDict\n'), ((1175, 1190), 'collections.OrderedDict', 'OrderedDict', (['[]'], {}), '([])\n', (1186, 1190), False, 'from collections import OrderedDict\n'), ((2121, 2144), 'os.listdir', 'os.listdir', (['folder_path'], {}), '(folder_path)\n', (2131, 2144), False, 'import os\n'), ((2838, 2861), 'numpy.array', 'np.array', (['self.te_array'], {}), '(self.te_array)\n', (2846, 2861), True, 'import numpy as np\n'), ((3121, 3144), 'os.listdir', 'os.listdir', (['folder_path'], {}), '(folder_path)\n', (3131, 3144), False, 'import os\n'), ((3581, 3602), 'numpy.zeros', 'np.zeros', (['(2)', 'np.int16'], {}), '(2, np.int16)\n', (3589, 3602), True, 'import numpy as np\n'), ((4171, 4200), 'os.listdir', 'os.listdir', (['containing_folder'], {}), '(containing_folder)\n', (4181, 4200), False, 'import os\n'), ((7123, 7136), 'numpy.conj', 'np.conj', (['img2'], {}), '(img2)\n', (7130, 7136), True, 'import numpy as np\n'), ((7731, 7757), 'itertools.tee', 'itertools.tee', (['object_list'], {}), '(object_list)\n', (7744, 7757), False, 'import itertools\n'), ((8653, 8691), 'numpy.zeros', 'np.zeros', (['(dimension[0], dimension[1])'], {}), '((dimension[0], dimension[1]))\n', (8661, 8691), True, 'import numpy as np\n'), ((9157, 9186), 'collections.OrderedDict', 'OrderedDict', (["[('', interp_b)]"], {}), "([('', interp_b)])\n", (9168, 9186), False, 'from collections import OrderedDict\n'), ((9417, 9440), 'os.listdir', 'os.listdir', (['folder_path'], {}), '(folder_path)\n', (9427, 9440), False, 'import os\n'), ((1740, 1762), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Location"""'], {}), "('Location')\n", (1750, 1762), True, 'import matplotlib.pyplot as plt\n'), ((1776, 1798), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Location"""'], {}), "('Location')\n", (1786, 1798), True, 'import matplotlib.pyplot as plt\n'), ((1812, 1829), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (1822, 1829), True, 'import matplotlib.pyplot as plt\n'), ((1843, 1857), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1855, 1857), True, 'import matplotlib.pyplot as plt\n'), ((1871, 1881), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1879, 1881), True, 'import matplotlib.pyplot as plt\n'), ((2251, 2275), 'os.path.isdir', 'os.path.isdir', (['file_path'], {}), '(file_path)\n', (2264, 2275), False, 'import os\n'), ((3251, 3275), 'os.path.isdir', 'os.path.isdir', (['file_path'], {}), '(file_path)\n', (3264, 3275), False, 'import os\n'), ((4628, 4653), 'os.path.exists', 'os.path.exists', (['save_path'], {}), '(save_path)\n', (4642, 4653), False, 'import os\n'), ((4668, 4690), 'os.makedirs', 'os.makedirs', (['save_path'], {}), '(save_path)\n', (4679, 4690), False, 'import os\n'), ((4766, 4785), 'xarray.DataArray', 'xr.DataArray', (['array'], {}), '(array)\n', (4778, 4785), True, 'import xarray as xr\n'), ((5583, 5639), 'numpy.reshape', 'np.reshape', (['complex_vals', '(dimensions[0], dimensions[1])'], {}), '(complex_vals, (dimensions[0], dimensions[1]))\n', (5593, 5639), True, 'import numpy as np\n'), ((7269, 7298), 'numpy.angle', 'np.angle', (['multiplic_img1_img2'], {}), '(multiplic_img1_img2)\n', (7277, 7298), True, 'import numpy as np\n'), ((9547, 9571), 'os.path.isdir', 'os.path.isdir', (['file_path'], {}), '(file_path)\n', (9560, 9571), False, 'import os\n'), ((10237, 10252), 'numpy.array', 'np.array', (['fid_l'], {}), '(fid_l)\n', (10245, 10252), True, 'import numpy as np\n'), ((1597, 1629), 'matplotlib.pyplot.title', 'plt.title', (['"""Reconstructed Image"""'], {}), "('Reconstructed Image')\n", (1606, 1629), True, 'import matplotlib.pyplot as plt\n'), ((1666, 1726), 'matplotlib.pyplot.title', 'plt.title', (['"""Field Map - B[T] Values as function of location"""'], {}), "('Field Map - B[T] Values as function of location')\n", (1675, 1726), True, 'import matplotlib.pyplot as plt\n'), ((5741, 5764), 'numpy.fft.ifft2', 'np.fft.ifft2', (['k_casting'], {}), '(k_casting)\n', (5753, 5764), True, 'import numpy as np\n'), ((8997, 9048), 'numpy.polyfit', 'np.polyfit', (['te_values[:]', 'value_vec_in_phase_map', '(1)'], {}), '(te_values[:], value_vec_in_phase_map, 1)\n', (9007, 9048), True, 'import numpy as np\n'), ((10179, 10209), 'struct.unpack', 'struct.unpack', (['"""i"""', 'fid_r[-4:]'], {}), "('i', fid_r[-4:])\n", (10192, 10209), False, 'import struct\n')]
|
"""Optimization
* :function:`.single_nested_cvrs`
* :function:`.dual_nested_cvrs`
* :function:`.single_cv`
* :function:`.chi2_test`
"""
# data wrangling
import numpy as np
import pandas as pd
from itertools import product
from scipy import stats
# validation
from sklearn.metrics import balanced_accuracy_score, accuracy_score, f1_score, roc_auc_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import MinMaxScaler
# from scipy import stats
# from pandas import *
# # Store sample sizes and number of errors
# n1 = 1000 # samples
# m1 = 300 # errors
# n2 = 1000 # samples
# m2 = 360 # errors
# # Store errors and correct classifications in a 2x2 table
# perf = DataFrame([[m1, m2], [n1-m1, n2-m2]], index=["Error", "Correct"])
# perf.columns = ["S_1", "S_2"]
# print(perf)
# ##### Chi-2 test for equality of error rates
# pvalue = stats.chi2_contingency(perf)[1]
# print("p-value = ", '{0:.6f}'.format(pvalue))
# ##### Fisher test for equality of error rates
# pvalue = stats.fisher_exact(perf)[1]
# print("p-value = ", ’{0:.6f}’.format(pvalue))
# import pandas as pd
# res = pd.read_csv("Crossval.csv", index_col=0)
# print(res)
# """
# algo1 algo2
# 1 75.05 78.08
# 2 74.24 79.77
# 3 76.20 79.61
# 4 81.35 88.39
# 5 80.96 88.27
# 6 84.22 76.20
# 7 77.68 88.04
# 8 82.10 87.50
# 9 81.35 84.37
# 10 81.80 84.04
# """
# ##### t-student test for equality of error rates
# pvalue = stats.ttest_rel(res[’algo2’], res[’algo1’])[1]
# print("p-value = ", ’{0:.6f}’.format(pvalue))
def nested_single_cv(x_t, y_t, L, grid, k_ext, k_int):
"""
Summary: Help set a hyper-parameters list for a given model before makes
-------- its comparison with others hyper-parameterized models.
Input: - x_t: features train (numpy.arrays)
------ - y_t: labels train (numpy.arrays)
- L: learning algorithm (class method .predict())
- grid: keys as a parameter name; values as the array of the parameter' values (dict)
- K_ext: number of external folds (integer)
- K_int: number of internal folds (integer)
Output: - inner_result_frame: index: [k_ext], columns: [hp_set], values: [v_bcr_(k_int_mean)]
------- - outter_result_frame: index: [k_ext, hp_hat], columns:[t_bcr, v_bcr], values:[t_bcr, v_bcr]
Example: model1= BaggingTrees
-------- grid1 = {'epochs':[1]
, 'n_trees':[100]
, 'criterion': ['entropy']
, 'min_samples_leaf':[0.06] #
, 'max_depth':[3]
, 'min_samples_split':[0.03] #
, 'max_leaf_nodes':[200]
}
K_int, K_ext = 4, 10
outter, inner = nested_single_cv(x_t, y_t, model1, grid1, K_ext, K_int)
outter.groupby('hp_hat').agg({'t_bcr': ['count', 'mean', 'std']
, 'v_bcr': ['mean', 'std']}).reset_index('hp_hat')
"""
hp_set = [v for v in product(*grid.values())]
inner_results = pd.DataFrame(columns = hp_set)
outter_results = pd.DataFrame(columns = ['hp_hat'
, 't_bcr'
, 'v_bcr'
])
# frame pointer
i = 0
# partionate "training rows" into "K_ext" sets
K_ext_folds = KFold(n_splits = k_ext, shuffle=False).split(x_t) # (markers t_i, v_i)
for t_ext_fold, v_ext_fold in K_ext_folds:
# sectioning "train set" between "S_k" into "ext_fold" sets
x_S_k = x_t[t_ext_fold] # training x
y_S_k = y_t[t_ext_fold] # training y
x_ext_fold = x_t[v_ext_fold] # test x
y_ext_fold = y_t[v_ext_fold] # test y
# get hp_hat in the inner loop
hp_dic = {}
for idx, hp in enumerate(hp_set):
hp_dic[idx]=[]
# partionate "S_k training rows" into "K_int" sets
K_int_folds = KFold(n_splits = k_int, shuffle=False).split(x_S_k)
for t_int_fold, v_int_fold in K_int_folds:
# sectioning "S_k" between "Ss_k" into "int_fold" sets
x_Ss_k = x_S_k[t_int_fold] # training x
y_Ss_k = y_S_k[t_int_fold] # training y
x_int_fold = x_S_k[v_int_fold] # test x
y_int_fold = y_S_k[v_int_fold] # test y
# must scaler after partition, for specific a training normalization
min_max_scaler = MinMaxScaler(feature_range=(0, 1))
X_t = min_max_scaler.fit_transform(x_Ss_k)
X_v = min_max_scaler.fit_transform(x_int_fold)
Y_t = y_Ss_k
Y_v = y_int_fold
# Loading and fitting model
model = L(hp)
model.fit(X_t, Y_t)
# prediction
Y_v_predicted = model.predict(X_v)
# validation
v_bcr = balanced_accuracy_score(Y_v, Y_v_predicted)
# append all
hp_dic[idx].append(v_bcr)
# # Averages the k_int iteractions for each hp in hp_set and stores it
inner_results.loc[i] = [sum(arr) / len(arr) for arr in hp_dic.values()]
# avg all hp predictions scores to define hp_hat (the highest) # use t-test?
ixd_max= max([(k,np.mean(v)) for k,v in hp_dic.items()],key=lambda item:item[1])[0]
hp_hat = hp_set[ixd_max]
# must scaler after partition, for specific a training normalization
min_max_scaler = MinMaxScaler(feature_range=(0, 1))
X_t = min_max_scaler.fit_transform(x_S_k)
X_v = min_max_scaler.fit_transform(x_ext_fold)
Y_t = y_S_k
Y_v = y_ext_fold
# Loading and fitting model
model = L(hp)
model.fit(X_t, Y_t)
# prediction
Y_v_predicted = model.predict(X_v)
# training metrics
t_acc = model.acc
t_bcr = model.bcr
t_f1 = model.f1
t_auc = model.auc
# validation metrics
v_acc = accuracy_score(Y_v, Y_v_predicted)
v_bcr = balanced_accuracy_score(Y_v, Y_v_predicted)
v_f1 = f1_score(Y_v, Y_v_predicted, average='macro')
v_auc = roc_auc_score(Y_v, Y_v_predicted, average='macro')
outter_results.loc[i] = [hp_hat
, t_bcr
, v_bcr]
i += 1
return outter_results, inner_results
|
[
"pandas.DataFrame",
"sklearn.metrics.accuracy_score",
"sklearn.preprocessing.MinMaxScaler",
"sklearn.metrics.balanced_accuracy_score",
"sklearn.model_selection.KFold",
"sklearn.metrics.roc_auc_score",
"sklearn.metrics.f1_score",
"numpy.mean"
] |
[((3295, 3323), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'hp_set'}), '(columns=hp_set)\n', (3307, 3323), True, 'import pandas as pd\n'), ((3350, 3400), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['hp_hat', 't_bcr', 'v_bcr']"}), "(columns=['hp_hat', 't_bcr', 'v_bcr'])\n", (3362, 3400), True, 'import pandas as pd\n'), ((5842, 5876), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(0, 1)'}), '(feature_range=(0, 1))\n', (5854, 5876), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((6371, 6405), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['Y_v', 'Y_v_predicted'], {}), '(Y_v, Y_v_predicted)\n', (6385, 6405), False, 'from sklearn.metrics import balanced_accuracy_score, accuracy_score, f1_score, roc_auc_score\n'), ((6423, 6466), 'sklearn.metrics.balanced_accuracy_score', 'balanced_accuracy_score', (['Y_v', 'Y_v_predicted'], {}), '(Y_v, Y_v_predicted)\n', (6446, 6466), False, 'from sklearn.metrics import balanced_accuracy_score, accuracy_score, f1_score, roc_auc_score\n'), ((6483, 6528), 'sklearn.metrics.f1_score', 'f1_score', (['Y_v', 'Y_v_predicted'], {'average': '"""macro"""'}), "(Y_v, Y_v_predicted, average='macro')\n", (6491, 6528), False, 'from sklearn.metrics import balanced_accuracy_score, accuracy_score, f1_score, roc_auc_score\n'), ((6546, 6596), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['Y_v', 'Y_v_predicted'], {'average': '"""macro"""'}), "(Y_v, Y_v_predicted, average='macro')\n", (6559, 6596), False, 'from sklearn.metrics import balanced_accuracy_score, accuracy_score, f1_score, roc_auc_score\n'), ((3634, 3670), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'k_ext', 'shuffle': '(False)'}), '(n_splits=k_ext, shuffle=False)\n', (3639, 3670), False, 'from sklearn.model_selection import KFold\n'), ((4764, 4798), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(0, 1)'}), '(feature_range=(0, 1))\n', (4776, 4798), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((5239, 5282), 'sklearn.metrics.balanced_accuracy_score', 'balanced_accuracy_score', (['Y_v', 'Y_v_predicted'], {}), '(Y_v, Y_v_predicted)\n', (5262, 5282), False, 'from sklearn.metrics import balanced_accuracy_score, accuracy_score, f1_score, roc_auc_score\n'), ((4234, 4270), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'k_int', 'shuffle': '(False)'}), '(n_splits=k_int, shuffle=False)\n', (4239, 4270), False, 'from sklearn.model_selection import KFold\n'), ((5633, 5643), 'numpy.mean', 'np.mean', (['v'], {}), '(v)\n', (5640, 5643), True, 'import numpy as np\n')]
|
from netCDF4 import Dataset
from dataclasses import dataclass, field
import os
import pickle
import sys
import shutil
import numpy as np
from variables import modelvar
@dataclass
class VariableInfo():
nickname: str = ""
dimensions: tuple = field(default_factory=lambda: ())
name: str = ""
units: str = ""
dtype: str = "d"
class NetCDF_tools():
"""
Basic class to create and write NetCDF files
Parameters
----------
filename : str
The file name to be created.
attrs : dict
The global attributes.
dimensions : list[(name, size), ...]
The list of dimensions.
size==None -> unlimited
variables : list[VariableInfo, ...]
The name of variable.dimensions should match one of dimensions.
"""
def __init__(self, filename, attrs, dimensions, variables):
self.filename = filename
self.attrs = attrs
self.dimensions = {dim[0]: dim[1] for dim in dimensions}
self.variables = {var.nickname: var for var in variables}
def create(self):
"""
Create the empty NetCDF file with
- attributes
- dimensions
- variables
"""
with Dataset(self.filename, "w", format='NETCDF4') as nc:
nc.setncatts(self.attrs)
for dim, size in self.dimensions.items():
nc.createDimension(dim, size)
for infos in self.variables.values():
assert isinstance(infos.dimensions, tuple)
v = nc.createVariable(infos.nickname,
infos.dtype,
infos.dimensions)
v.standard_name = infos.name
v.units = infos.units
def write(self, variables, nc_start={}, data_start={}):
"""
Write variables
Parameters
----------
variables : list[(nickname, data), ...]
where data is an ndarray
nc_start : dict{name: (offset, size)}
name : the dimension name
offset : the offset of that dimension in the NetCDF file
size : the size of data in that dimension
If a dimension is not in nc_start it is assumed that
the data has a size that matches the size defined in
the NetCDF.
data_start : dict{name: (offset, size)}
same that nc_start but for the data in variables
"""
with Dataset(self.filename, "r+") as nc:
for nickname, data in variables.items():
ncidx = self._get_idx(nickname, nc_start)
if isinstance(data, np.ndarray):
dataidx = self._get_idx(nickname, data_start)
nc.variables[nickname][ncidx] = data[dataidx]
else:
nc.variables[nickname][ncidx] = data
def _get_idx(self, nickname, nc_start):
"""
Return the tuple of slices
to either slice through nc.variables or through data
"""
infos = self.variables[nickname]
ncidx = []
for dim in infos.dimensions:
if dim in nc_start:
istart, size = nc_start[dim]
else:
istart, size = 0, self.dimensions[dim]
if size is not None:
ncidx += [slice(istart, istart+size)]
return tuple(ncidx)
class Ncio():
"""
Class that handles all the IO for pyRSW
which includes
- creating and writing model snapshots in the history.nc
- creating and writing model bulk diagnostics in the diags.nc
- saving the param.pkl file
- saving the Python experiment script
"""
def __init__(self, param, grid, batchindex=0):
self.param = param
self.grid = grid
self.batchindex = batchindex
self.nprocs = np.prod(grid.procs)
if self.nprocs > 1:
from mpi4py import MPI
self.MPI = MPI
self._create_output_directory()
self.backup_config()
hist_infos = get_hist_infos(param, grid)
self.hist = NetCDF_tools(self.history_file, *hist_infos)
if not self.singlefile or self.master:
self.hist.create()
self.hist_index = 0
self.write_grid()
diag_infos = get_diag_infos(param, grid)
self.diag = NetCDF_tools(self.diag_file, *diag_infos)
self.diag_index = 0
if self.master:
self.diag.create()
def _create_output_directory(self):
if self.master and not os.path.isdir(self.output_directory):
os.makedirs(self.output_directory)
@property
def myrank(self):
return self.grid.myrank
@property
def master(self):
return self.myrank == 0
@property
def expname(self):
return self.param["expname"]
@property
def singlefile(self):
return self.param["singlefile"]
@property
def output_directory(self):
datadir = os.path.expanduser(self.param["datadir"])
return os.path.join(datadir, self.expname)
@property
def history_file(self):
"""
Full path to the NetCDF history file
"""
his = self._add_batchindex("history")
basicname = f"{his}.nc"
mpiname = f"{his}_{self.myrank:02}.nc"
hisname = basicname if self.singlefile else mpiname
return os.path.join(self.output_directory, hisname)
@property
def diag_file(self):
"""
Full path to the NetCDF diagnostic file
"""
diag = self._add_batchindex("diag")
diagname = f"{diag}.nc"
return os.path.join(self.output_directory, diagname)
def _add_batchindex(self, filename):
if self.param.restart:
return filename + f"_{self.batchindex:02}"
else:
return filename
def backup_config(self):
"""
Backup the experiment configuration into the output directory
- save param in the param.pkl
- save the experiment Python script
"""
if self.master and self.batchindex == 0:
dest = f"{self.output_directory}/param.pkl"
with open(dest, "wb") as fid:
pickle.dump(self.param, fid)
python_launch_script = sys.argv[0]
dest = os.path.join(self.output_directory, f"{self.expname}.py")
shutil.copyfile(python_launch_script, dest)
def write_grid(self):
"""
Write the model grid arrays into the NetCDF file (just once)
"""
xc = self.grid.coord.x(0, self.grid.ic)[0]
yc = self.grid.coord.y(self.grid.jc, 0)[:, 0]
xe = self.grid.coord.x(0, self.grid.ie)[0]
ye = self.grid.coord.y(self.grid.je, 0)[:, 0]
layer = np.arange(self.grid.nz)
msk = self.grid.arrays.msk.view("i")
datagrid = {
"x": xc,
"y": yc,
"xe": xe,
"ye": ye,
"layer": layer,
"msk": msk
}
self._history_write_halo_mpi(datagrid)
def write_hist(self, state, time, kt):
"""
Write a model snapshot into the NetCDF file
"""
datahist = {
"time": time,
"iteration": kt,
}
for name in self.param["var_to_save"]:
vartype = modelvar[name]["type"]
if vartype == "vector":
for axis in "xy":
compname = name+axis
var = state.get(compname)
datahist[compname] = var.getproperunits(self.grid)
else:
var = state.get(name)
datahist[name] = var.getproperunits(self.grid)
nc_start = {"time": (self.hist_index, 1)}
self._history_write_halo_mpi(datahist, nc_start=nc_start)
self.hist_index += 1
def _history_write_halo_mpi(self, data, nc_start={}):
"""
Generic function to write data into the history NetCDF file
handle the following special cases
- write the arrays without the halo
- write in a single history file, even if several MPI ranks
"""
data_start = {}
if not self.param.halo_included:
j0, j1, i0, i1 = self.grid.arrays.hb.domainindices
nx = self.param.nx
ny = self.param.ny
data_start["x"] = (i0, nx)
data_start["y"] = (j0, ny)
data_start["xe"] = (i0, nx+1)
data_start["ye"] = (j0, ny+1)
if self.singlefile:
i0 = self.grid.loc[2]*self.param.nx
j0 = self.grid.loc[1]*self.param.ny
nc_start["x"] = (i0, nx)
nc_start["y"] = (j0, ny)
nc_start["xe"] = (i0, nx+1)
nc_start["ye"] = (j0, ny+1)
if self.singlefile and (self.nprocs > 1):
# all MPI ranks write in the same file
for rank in range(self.nprocs):
if rank == self.myrank:
self.hist.write(data,
nc_start=nc_start,
data_start=data_start)
self.MPI.COMM_WORLD.Barrier()
else:
# each rank writes in its own history file
self.hist.write(data, nc_start=nc_start, data_start=data_start)
def write_diags(self, diags, time, kt):
"""
Write the domain integrated diagnostics into the NetCDF file
"""
datadiag = {
"time": time,
"iteration": kt,
"ke": diags["ke"],
"pe": diags["pe"],
"me": diags["me"],
"enstrophy": diags["potenstrophy"],
}
start = {"time": (self.diag_index, 1)}
if self.master:
self.diag.write(datadiag, nc_start=start)
self.diag_index += 1
def get_hist_infos(param, grid):
attrs = {"model": "pyrsw",
"author": "someone"}
if param.halo_included:
ny, nx = grid.xc.shape
else:
ny, nx = param.ny, param.nx
if param.singlefile:
nx *= param.npx
ny *= param.npy
nz = param.nz
dims = [("time", None), ("layer", nz),
("x", nx), ("y", ny),
("xe", nx+1), ("ye", ny+1)]
infos = [
("time", ("time",), "time", "s"),
("iteration", ("time",), "model iteration", "", "i4"),
("x", ("x",), "x coord at center", "m"),
("y", ("y",), "y coord at center", "m"),
("xe", ("xe",), "x coord at edge", "m"),
("ye", ("ye",), "y coord at edge", "m"),
("layer", ("layer",), "layer index", "", "i1"),
("msk", ("y", "x"), "mask at cell centers", "", "i1"),
]
vardims = {
"scalar": ("time", "layer", "y", "x"),
"u": ("time", "layer", "y", "xe"),
"v": ("time", "layer", "ye", "x"),
"vorticity": ("time", "layer", "ye", "xe")
}
for name in param["var_to_save"]:
longname = modelvar[name]["name"]
units = modelvar[name]["unit"]
vartype = modelvar[name]["type"]
if vartype == "vector":
infos += [(name+"x", vardims["u"], longname+" x-component", units)]
infos += [(name+"y", vardims["v"], longname+" y-component", units)]
else:
infos += [(name, vardims[vartype], longname, units)]
varinfos = [VariableInfo(*info) for info in infos]
hist_infos = (attrs, dims, varinfos)
return hist_infos
def get_diag_infos(param, grid):
attrs = {"model": "pyrsw",
"author": "someone"}
dims = [("time", None)]
infos = [
("time", ("time",), "time", "s"),
("iteration", ("time",), "model iteration", "", "i4"),
("ke", ("time",), "kinetic energy", "m^2 s^-2"),
("pe", ("time",), "mean available potential energy", "m^2 s^-2"),
("me", ("time",), "kinetic + potential energy", "m^2 s^-2"),
("enstrophy", ("time",), "mean enstrophy", "s^-2 m^-2"),
]
varinfos = [VariableInfo(*info) for info in infos]
diag_infos = (attrs, dims, varinfos)
return diag_infos
|
[
"netCDF4.Dataset",
"pickle.dump",
"os.path.join",
"os.makedirs",
"os.path.isdir",
"dataclasses.field",
"numpy.arange",
"shutil.copyfile",
"os.path.expanduser",
"numpy.prod"
] |
[((250, 284), 'dataclasses.field', 'field', ([], {'default_factory': '(lambda : ())'}), '(default_factory=lambda : ())\n', (255, 284), False, 'from dataclasses import dataclass, field\n'), ((3871, 3890), 'numpy.prod', 'np.prod', (['grid.procs'], {}), '(grid.procs)\n', (3878, 3890), True, 'import numpy as np\n'), ((5009, 5050), 'os.path.expanduser', 'os.path.expanduser', (["self.param['datadir']"], {}), "(self.param['datadir'])\n", (5027, 5050), False, 'import os\n'), ((5066, 5101), 'os.path.join', 'os.path.join', (['datadir', 'self.expname'], {}), '(datadir, self.expname)\n', (5078, 5101), False, 'import os\n'), ((5415, 5459), 'os.path.join', 'os.path.join', (['self.output_directory', 'hisname'], {}), '(self.output_directory, hisname)\n', (5427, 5459), False, 'import os\n'), ((5663, 5708), 'os.path.join', 'os.path.join', (['self.output_directory', 'diagname'], {}), '(self.output_directory, diagname)\n', (5675, 5708), False, 'import os\n'), ((6805, 6828), 'numpy.arange', 'np.arange', (['self.grid.nz'], {}), '(self.grid.nz)\n', (6814, 6828), True, 'import numpy as np\n'), ((1205, 1250), 'netCDF4.Dataset', 'Dataset', (['self.filename', '"""w"""'], {'format': '"""NETCDF4"""'}), "(self.filename, 'w', format='NETCDF4')\n", (1212, 1250), False, 'from netCDF4 import Dataset\n'), ((2475, 2503), 'netCDF4.Dataset', 'Dataset', (['self.filename', '"""r+"""'], {}), "(self.filename, 'r+')\n", (2482, 2503), False, 'from netCDF4 import Dataset\n'), ((4615, 4649), 'os.makedirs', 'os.makedirs', (['self.output_directory'], {}), '(self.output_directory)\n', (4626, 4649), False, 'import os\n'), ((6345, 6402), 'os.path.join', 'os.path.join', (['self.output_directory', 'f"""{self.expname}.py"""'], {}), "(self.output_directory, f'{self.expname}.py')\n", (6357, 6402), False, 'import os\n'), ((6415, 6458), 'shutil.copyfile', 'shutil.copyfile', (['python_launch_script', 'dest'], {}), '(python_launch_script, dest)\n', (6430, 6458), False, 'import shutil\n'), ((4565, 4601), 'os.path.isdir', 'os.path.isdir', (['self.output_directory'], {}), '(self.output_directory)\n', (4578, 4601), False, 'import os\n'), ((6249, 6277), 'pickle.dump', 'pickle.dump', (['self.param', 'fid'], {}), '(self.param, fid)\n', (6260, 6277), False, 'import pickle\n')]
|
import logging as log
import os
import base64
import json
import numpy as np
from paprika.restraints import DAT_restraint
from parmed.amber import AmberParm
from parmed import Structure
# https://stackoverflow.com/questions/27909658/json-encoder-and-decoder-for-complex-numpy-arrays
# https://stackoverflow.com/a/24375113/901925
# https://stackoverflow.com/questions/3488934/simplejson-and-numpy-array/24375113#24375113
class NumpyEncoder(json.JSONEncoder):
"""Save DAT_restraints as JSON by re-encoding `numpy` arrays."""
def default(self, obj):
"""If input object is an ndarray it will be converted into a dict
holding dtype, shape and the data, base64 encoded.
"""
if isinstance(obj, AmberParm):
log.info("Encountered AmberParm, returning name.")
return obj.name
if isinstance(obj, Structure):
log.warning("Encountered Structure, which does not store filename.")
return ""
if isinstance(obj, np.ndarray):
if obj.flags["C_CONTIGUOUS"]:
obj_data = obj.data
else:
cont_obj = np.ascontiguousarray(obj)
assert cont_obj.flags["C_CONTIGUOUS"]
obj_data = cont_obj.data
data_b64 = base64.b64encode(obj_data)
# obj_data = obj.tolist()
return dict(
__ndarray__=data_b64.decode("utf-8"),
dtype=str(obj.dtype),
shape=obj.shape,
)
elif isinstance(
obj,
(
np.int_,
np.intc,
np.intp,
np.int8,
np.int16,
np.int32,
np.int64,
np.uint8,
np.uint16,
np.uint32,
np.uint64,
),
):
return int(obj)
elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):
return float(obj)
elif isinstance(obj, (np.ndarray,)):
return obj.tolist()
# Let the base class default method raise the TypeError
# return json.JSONEncoder(self, obj)
return super(NumpyEncoder, self).default(obj)
def json_numpy_obj_hook(dct):
"""Decodes a previously encoded numpy ndarray with proper shape and dtype.
:param dct: (dict) json encoded ndarray
:return: (ndarray) if input was an encoded ndarray
"""
if isinstance(dct, dict) and "__ndarray__" in dct:
data = base64.b64decode(dct["__ndarray__"])
return np.frombuffer(data, dct["dtype"]).reshape(dct["shape"])
# return dct['__ndarray__']
return dct
def save_restraints(restraint_list, filepath="restraints.json"):
log.debug("Saving restraint information as JSON.")
with open(os.path.join(filepath), "w") as f:
for restraint in restraint_list:
dumped = json.dumps(restraint.__dict__, cls=NumpyEncoder)
f.write(dumped)
f.write("\n")
def load_restraints(filepath="restraints.json"):
log.debug("Loading restraint information from JSON.")
with open(os.path.join(filepath), "r") as f:
json_data = f.read()
restraint_json = json_data.split("\n")
restraints = []
for restraint in restraint_json:
if restraint == "":
continue
loaded = json.loads(restraint, object_hook=json_numpy_obj_hook)
tmp = DAT_restraint()
tmp.__dict__ = loaded
properties = ["mask1", "mask2", "mask3", "mask4", "topology", "instances", "custom_restraint_values",
"auto_apr", "continuous_apr", "attach", "pull", "release", "amber_index"]
for class_property in properties:
if f"_{class_property}" in tmp.__dict__.keys():
tmp.__dict__[class_property] = tmp.__dict__[f"_{class_property}"]
restraints.append(tmp)
return restraints
|
[
"paprika.restraints.DAT_restraint",
"logging.debug",
"json.loads",
"logging.warning",
"numpy.frombuffer",
"numpy.ascontiguousarray",
"base64.b64decode",
"json.dumps",
"logging.info",
"base64.b64encode",
"os.path.join"
] |
[((2779, 2829), 'logging.debug', 'log.debug', (['"""Saving restraint information as JSON."""'], {}), "('Saving restraint information as JSON.')\n", (2788, 2829), True, 'import logging as log\n'), ((3099, 3152), 'logging.debug', 'log.debug', (['"""Loading restraint information from JSON."""'], {}), "('Loading restraint information from JSON.')\n", (3108, 3152), True, 'import logging as log\n'), ((2549, 2585), 'base64.b64decode', 'base64.b64decode', (["dct['__ndarray__']"], {}), "(dct['__ndarray__'])\n", (2565, 2585), False, 'import base64\n'), ((3397, 3451), 'json.loads', 'json.loads', (['restraint'], {'object_hook': 'json_numpy_obj_hook'}), '(restraint, object_hook=json_numpy_obj_hook)\n', (3407, 3451), False, 'import json\n'), ((3466, 3481), 'paprika.restraints.DAT_restraint', 'DAT_restraint', ([], {}), '()\n', (3479, 3481), False, 'from paprika.restraints import DAT_restraint\n'), ((756, 806), 'logging.info', 'log.info', (['"""Encountered AmberParm, returning name."""'], {}), "('Encountered AmberParm, returning name.')\n", (764, 806), True, 'import logging as log\n'), ((886, 954), 'logging.warning', 'log.warning', (['"""Encountered Structure, which does not store filename."""'], {}), "('Encountered Structure, which does not store filename.')\n", (897, 954), True, 'import logging as log\n'), ((1285, 1311), 'base64.b64encode', 'base64.b64encode', (['obj_data'], {}), '(obj_data)\n', (1301, 1311), False, 'import base64\n'), ((2844, 2866), 'os.path.join', 'os.path.join', (['filepath'], {}), '(filepath)\n', (2856, 2866), False, 'import os\n'), ((2941, 2989), 'json.dumps', 'json.dumps', (['restraint.__dict__'], {'cls': 'NumpyEncoder'}), '(restraint.__dict__, cls=NumpyEncoder)\n', (2951, 2989), False, 'import json\n'), ((3167, 3189), 'os.path.join', 'os.path.join', (['filepath'], {}), '(filepath)\n', (3179, 3189), False, 'import os\n'), ((1141, 1166), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['obj'], {}), '(obj)\n', (1161, 1166), True, 'import numpy as np\n'), ((2601, 2634), 'numpy.frombuffer', 'np.frombuffer', (['data', "dct['dtype']"], {}), "(data, dct['dtype'])\n", (2614, 2634), True, 'import numpy as np\n')]
|
import numpy
from scipy.interpolate import InterpolatedUnivariateSpline as interpolate
from scipy.interpolate import interp1d
from cosmo4d.lab import (UseComplexSpaceOptimizer,
NBodyModel, LPTModel, ZAModel,
LBFGS, ParticleMesh)
#from cosmo4d.lab import mapbias as map
from cosmo4d import lab
from cosmo4d.lab import report, dg, objectives
from abopt.algs.lbfgs import scalar as scalar_diag
from nbodykit.cosmology import Planck15, EHPower, Cosmology
from nbodykit.algorithms.fof import FOF
from nbodykit.lab import KDDensity, BigFileMesh, BigFileCatalog, ArrayCatalog
import sys, os, json, yaml
from solve import solve
from getbiasparams import getbias, eval_bfit
sys.path.append('../')
sys.path.append('../utils/')
import HImodels
#########################################
#Set parameters here
##
cfname = sys.argv[1]
with open(cfname, 'r') as ymlfile: cfg = yaml.load(ymlfile)
for i in cfg['basep'].keys(): locals()[i] = cfg['basep'][i]
h1model = HImodels.ModelA(aa)
truth_pm = ParticleMesh(BoxSize=bs, Nmesh=(nc, nc, nc), dtype='f4')
comm = truth_pm.comm
rank = comm.rank
if numd <= 0: num = -1
else: num = int(bs**3 * numd)
if rank == 0: print('Number of objects : ', num)
objfunc = getattr(objectives, cfg['mods']['objective'])
map = getattr(lab, cfg['mods']['map'])
#
proj = '/project/projectdirs/cosmosim/lbl/chmodi/cosmo4d/'
dfolder = '/global/cscratch1/sd/chmodi/m3127/cm_lowres/%dstepT-B%d/%d-%d-9100-fixed/'%(nsteps, B, bs, nc)
#ofolder = '/global/cscratch1/sd/chmodi/m3127/21cm_cleaning/recon/bias/L%04d-N%04d-T%02d-B%01d/'%(bs, nc, nsteps, B)
ofolder = '/global/cscratch1/sd/chmodi/m3127/21cm_cleaning/recon/L%04d-N%04d/'%(bs, nc)
if pmdisp:
ofolder += 'T%02d-B%01d'%(nsteps, B)
else: ofolder += 'ZA/'
prefix = '_fourier'
if rsdpos: prefix += "_rsdpos"
if masswt:
if h1masswt : fname = 's999_h1massA%s'%prefix
else: fname = 's999_mass%s'%prefix
else: fname = 's999_pos%s'%prefix
optfolder = ofolder + 'opt_%s/'%fname
if truth_pm.comm.rank == 0: print('Output Folder is %s'%optfolder)
for folder in [ofolder, optfolder]:
try: os.makedirs(folder)
except:pass
#########################################
#initiate
klin, plin = numpy.loadtxt('../../data/pklin_1.0000.txt', unpack = True)
ipk = interpolate(klin, plin)
#cosmo = Planck15.clone(Omega_cdm = 0.2685, h = 0.6711, Omega_b = 0.049)
cosmodef = {'omegam':0.309167, 'h':0.677, 'omegab':0.048}
cosmo = Cosmology.from_dict(cosmodef)
data = BigFileCatalog('/global/cscratch1/sd/chmodi/m3127/H1mass/highres/2560-9100-fixed/fastpm_%0.4f/LL-0.200/'%aa)
data = data.gslice(start = 0, stop = num)
data['Mass'] = data['Length']*data.attrs['M0']*1e10
if masswt :
masswt = data['Mass'].copy()
if h1masswt : masswt = h1model.assignhalo(masswt)
else: masswt = data['Mass'].copy()*0 + 1.
hpos, hmass = data['Position'], masswt
rsdfac = 0
if rsdpos:
with open('/global/cscratch1/sd/chmodi/m3127/H1mass/highres/2560-9100-fixed/fastpm_%0.4f/Header/attr-v2'%aa) as ff:
for line in ff.readlines():
if 'RSDFactor' in line: rsdfac = float(line.split()[-2])
hpos = data['Position'] + rsdfac*data['Velocity']*numpy.array([0, 0, 1]).reshape(1, -1)
hlayout = truth_pm.decompose(hpos)
hmesh = truth_pm.paint(hpos, layout=hlayout, mass=hmass)
hmesh /= hmesh.cmean()
hmesh -= 1.
rankweight = sum(masswt.compute())
totweight = comm.allreduce(rankweight)
rankweight = sum((masswt**2).compute())
totweight2 = comm.allreduce(rankweight)
noise = bs**3 / (totweight**2/totweight2)
if rank == 0 : print('Noise : ', noise)
#########################################
#dynamics
stages = numpy.linspace(0.1, aa, nsteps, endpoint=True)
if pmdisp: dynamic_model = NBodyModel(cosmo, truth_pm, B=B, steps=stages)
else: dynamic_model = ZAModel(cosmo, truth_pm, B=B, steps=stages)
if rank == 0: print(dynamic_model)
#noise
#Artifically low noise since the data is constructed from the model
truth_noise_model = map.NoiseModel(truth_pm, None, noisevar*(truth_pm.BoxSize/truth_pm.Nmesh).prod(), 1234)
truth_noise_model = None
#Create and save data if not found
dyn = BigFileCatalog(dfolder + 'fastpm_%0.4f/1'%aa)
s_truth = BigFileMesh(dfolder + 'linear', 'LinearDensityK').paint()
mock_model_setup = map.MockModel(dynamic_model, rsdpos=rsdpos, rsdfac=rsdfac)
fpos, linear, linearsq, shear = mock_model_setup.get_code().compute(['x', 'linear', 'linearsq', 'shear'], init={'parameters': s_truth})
grid = truth_pm.generate_uniform_particle_grid(shift=0.0, dtype='f4')
params, bmod = getbias(truth_pm, hmesh, [linear, linearsq, shear], fpos, grid)
title = ['%0.3f'%i for i in params]
kerror, perror = eval_bfit(hmesh, bmod, optfolder, noise=noise, title=title, fsize=15)
ipkerror = interp1d(kerror, perror, bounds_error=False, fill_value=(perror[0], perror[-1]))
mock_model = map.MockModel(dynamic_model, params=params, rsdpos=rsdpos, rsdfac=rsdfac)
data_p = mock_model.make_observable(s_truth)
data_p.mapp = hmesh.copy()
data_p.save(optfolder+'datap/')
if rank == 0: print('datap saved')
#data_n = truth_noise_model.add_noise(data_p)
#data_n.save(optfolder+'datan/')
#if rank == 0: print('datan saved')
fit_p = mock_model.make_observable(s_truth)
fit_p.save(optfolder+'fitp/')
if rank == 0: print('fitp saved')
##
if rank == 0: print('data_p, data_n created')
################################################
#Optimizer
if cfg['init']['sinit'] is None:
s_init = truth_pm.generate_whitenoise(777, mode='complex')\
.apply(lambda k, v: v * (ipk(sum(ki **2 for ki in k) **0.5) / v.BoxSize.prod()) ** 0.5)\
.c2r()*0.001
sms = [4.0, 2.0, 1.0, 0.5, 0.0]
else:
s_init = BigFileMesh(cfg['init']['sinit'], 's').paint()
sms = cfg['init']['sms']
if sms is None: [4.0, 2.0, 1.0, 0.5, 0.0]
x0 = s_init
N0 = nc
C = x0.BoxSize[0] / x0.Nmesh[0]
for Ns in sms:
if truth_pm.comm.rank == 0: print('\nDo for cell smoothing of %0.2f\n'%(Ns))
sml = C * Ns
rtol = 0.005
run = '%d-%0.2f'%(N0, Ns)
if Ns == sms[0]:
if cfg['init']['sinit'] is not None: run += '-nit_%d-sm_%.2f'%(cfg['init']['nit'], cfg['init']['sml'])
obj = objfunc(mock_model, truth_noise_model, data_p, prior_ps=ipk, error_ps=ipkerror, sml=sml)
x0 = solve(N0, x0, rtol, run, Ns, prefix, mock_model, obj, data_p, truth_pm, optfolder, saveit=20, showit=5, title=None)
#########################################
##def gaussian_smoothing(sm):
## def kernel(k, v):
## return numpy.exp(- 0.5 * sm ** 2 * sum(ki ** 2 for ki in k)) * v
## return kernel
##
#########################################
#optimizer
##
##def solve(Nmesh, x0, rtol, run, Nsm):
##
## pm = truth_pm.resize(Nmesh=(Nmesh, Nmesh, Nmesh))
## atol = pm.Nmesh.prod() * rtol
## x0 = pm.upsample(x0, keep_mean=True)
## #data = data_n.downsample(pm)
## #IDEAL no noise limit
## data = data_p.downsample(pm)
##
## # smooth the data. This breaks the noise model but we don't need it
## # for lower resolution anyways.
## sml = pm.BoxSize[0] / Nmesh * Nsm
##
## #dynamic_model = ZAModel(cosmo, truth_pm, B=B, steps=stages)
## #mock_model = map.MockModel(dynamic_model)
##
## # an approximate noise model, due to smoothing this is correct only at large scale.
## noise_model = truth_noise_model #.downsample(pm)
##
## obj = map.SmoothedObjective(mock_model, noise_model, data, prior_ps=pk, sml=sml)#, noised=noised)
##
## prior, chi2 = obj.get_code().compute(['prior', 'chi2'], init={'parameters': data.s})
## if pm.comm.rank == 0: print('Prior, chi2 : ', prior, chi2) # for 2d chi2 is close to total pixels.
##
## fit_p = mock_model.make_observable(data.s)
## #r = obj.evaluate(fit_p, data)
## r = dg.evaluate(fit_p, data)
##
## try:
## os.makedirs(optfolder + '%s' % run)
## except:
## pass
## try:
## os.makedirs(optfolder + '%s/2pt' % run)
## except:
## pass
## dg.save_report(r, optfolder + "%s/truth.png" % run, pm)
## dg.save_2ptreport(r, optfolder + "%s/2pt/truth.png" % run, pm)
##
##
## optimizer = LBFGS(m=10, diag_update=scalar_diag)
##
## prob = obj.get_problem(atol=atol, precond=UseComplexSpaceOptimizer)
##
## def monitor(state):
## if pm.comm.rank == 0:
## print(state)
## if state.nit % 5 == 0:
## fit_p = mock_model.make_observable(state['x'])
## if state.nit % 20 == 0:
## fit_p.save(optfolder + '%s/%04d/fit_p' % (run, state['nit']))
## r = obj.evaluate(fit_p, data)
## #obj.save_report(r, optfolder + "%s/%s%02d-%04d.png"% (run, prefix, int(Nsm*10), state['nit']))
## dg.save_report(r, optfolder + "%s/%s_N%02d-%04d.png"% (run, prefix, int(Nsm*10), state['nit']), pm)
## dg.save_2ptreport(r, optfolder + "%s/2pt/%s_N%02d-%04d.png"% (run, prefix, int(Nsm*10), state['nit']), pm)
## if pm.comm.rank == 0:
## print('saved')
##
## state = optimizer.minimize(prob, x0=x0, monitor=monitor)
## fit_p = mock_model.make_observable(state['x'])
## fit_p.save(optfolder + '%s/best-fit' % run)
## r = dg.evaluate(fit_p, data)
## dg.save_report(r, optfolder + "%s/%s%02d-best-fit.png" % (run, prefix, int(Nsm*10)), pm)
## dg.save_2ptreport(r, optfolder + "%s/2pt/%s_N%02d-best-fit.png" % (run, prefix, int(Nsm*10)), pm)
## return state.x
##
|
[
"sys.path.append",
"cosmo4d.lab.ParticleMesh",
"nbodykit.lab.BigFileCatalog",
"nbodykit.cosmology.Cosmology.from_dict",
"yaml.load",
"scipy.interpolate.InterpolatedUnivariateSpline",
"solve.solve",
"os.makedirs",
"getbiasparams.eval_bfit",
"nbodykit.lab.BigFileMesh",
"cosmo4d.lab.NBodyModel",
"HImodels.ModelA",
"numpy.loadtxt",
"numpy.linspace",
"cosmo4d.lab.ZAModel",
"getbiasparams.getbias",
"scipy.interpolate.interp1d",
"numpy.array"
] |
[((716, 738), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (731, 738), False, 'import sys, os, json, yaml\n'), ((739, 767), 'sys.path.append', 'sys.path.append', (['"""../utils/"""'], {}), "('../utils/')\n", (754, 767), False, 'import sys, os, json, yaml\n'), ((1003, 1022), 'HImodels.ModelA', 'HImodels.ModelA', (['aa'], {}), '(aa)\n', (1018, 1022), False, 'import HImodels\n'), ((1035, 1091), 'cosmo4d.lab.ParticleMesh', 'ParticleMesh', ([], {'BoxSize': 'bs', 'Nmesh': '(nc, nc, nc)', 'dtype': '"""f4"""'}), "(BoxSize=bs, Nmesh=(nc, nc, nc), dtype='f4')\n", (1047, 1091), False, 'from cosmo4d.lab import UseComplexSpaceOptimizer, NBodyModel, LPTModel, ZAModel, LBFGS, ParticleMesh\n'), ((2221, 2278), 'numpy.loadtxt', 'numpy.loadtxt', (['"""../../data/pklin_1.0000.txt"""'], {'unpack': '(True)'}), "('../../data/pklin_1.0000.txt', unpack=True)\n", (2234, 2278), False, 'import numpy\n'), ((2287, 2310), 'scipy.interpolate.InterpolatedUnivariateSpline', 'interpolate', (['klin', 'plin'], {}), '(klin, plin)\n', (2298, 2310), True, 'from scipy.interpolate import InterpolatedUnivariateSpline as interpolate\n'), ((2450, 2479), 'nbodykit.cosmology.Cosmology.from_dict', 'Cosmology.from_dict', (['cosmodef'], {}), '(cosmodef)\n', (2469, 2479), False, 'from nbodykit.cosmology import Planck15, EHPower, Cosmology\n'), ((2488, 2608), 'nbodykit.lab.BigFileCatalog', 'BigFileCatalog', (["('/global/cscratch1/sd/chmodi/m3127/H1mass/highres/2560-9100-fixed/fastpm_%0.4f/LL-0.200/'\n % aa)"], {}), "(\n '/global/cscratch1/sd/chmodi/m3127/H1mass/highres/2560-9100-fixed/fastpm_%0.4f/LL-0.200/'\n % aa)\n", (2502, 2608), False, 'from nbodykit.lab import KDDensity, BigFileMesh, BigFileCatalog, ArrayCatalog\n'), ((3669, 3715), 'numpy.linspace', 'numpy.linspace', (['(0.1)', 'aa', 'nsteps'], {'endpoint': '(True)'}), '(0.1, aa, nsteps, endpoint=True)\n', (3683, 3715), False, 'import numpy\n'), ((4143, 4190), 'nbodykit.lab.BigFileCatalog', 'BigFileCatalog', (["(dfolder + 'fastpm_%0.4f/1' % aa)"], {}), "(dfolder + 'fastpm_%0.4f/1' % aa)\n", (4157, 4190), False, 'from nbodykit.lab import KDDensity, BigFileMesh, BigFileCatalog, ArrayCatalog\n'), ((4556, 4619), 'getbiasparams.getbias', 'getbias', (['truth_pm', 'hmesh', '[linear, linearsq, shear]', 'fpos', 'grid'], {}), '(truth_pm, hmesh, [linear, linearsq, shear], fpos, grid)\n', (4563, 4619), False, 'from getbiasparams import getbias, eval_bfit\n'), ((4673, 4742), 'getbiasparams.eval_bfit', 'eval_bfit', (['hmesh', 'bmod', 'optfolder'], {'noise': 'noise', 'title': 'title', 'fsize': '(15)'}), '(hmesh, bmod, optfolder, noise=noise, title=title, fsize=15)\n', (4682, 4742), False, 'from getbiasparams import getbias, eval_bfit\n'), ((4754, 4839), 'scipy.interpolate.interp1d', 'interp1d', (['kerror', 'perror'], {'bounds_error': '(False)', 'fill_value': '(perror[0], perror[-1])'}), '(kerror, perror, bounds_error=False, fill_value=(perror[0], perror[-1])\n )\n', (4762, 4839), False, 'from scipy.interpolate import interp1d\n'), ((914, 932), 'yaml.load', 'yaml.load', (['ymlfile'], {}), '(ymlfile)\n', (923, 932), False, 'import sys, os, json, yaml\n'), ((3743, 3789), 'cosmo4d.lab.NBodyModel', 'NBodyModel', (['cosmo', 'truth_pm'], {'B': 'B', 'steps': 'stages'}), '(cosmo, truth_pm, B=B, steps=stages)\n', (3753, 3789), False, 'from cosmo4d.lab import UseComplexSpaceOptimizer, NBodyModel, LPTModel, ZAModel, LBFGS, ParticleMesh\n'), ((3812, 3855), 'cosmo4d.lab.ZAModel', 'ZAModel', (['cosmo', 'truth_pm'], {'B': 'B', 'steps': 'stages'}), '(cosmo, truth_pm, B=B, steps=stages)\n', (3819, 3855), False, 'from cosmo4d.lab import UseComplexSpaceOptimizer, NBodyModel, LPTModel, ZAModel, LBFGS, ParticleMesh\n'), ((6249, 6368), 'solve.solve', 'solve', (['N0', 'x0', 'rtol', 'run', 'Ns', 'prefix', 'mock_model', 'obj', 'data_p', 'truth_pm', 'optfolder'], {'saveit': '(20)', 'showit': '(5)', 'title': 'None'}), '(N0, x0, rtol, run, Ns, prefix, mock_model, obj, data_p, truth_pm,\n optfolder, saveit=20, showit=5, title=None)\n', (6254, 6368), False, 'from solve import solve\n'), ((2118, 2137), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (2129, 2137), False, 'import sys, os, json, yaml\n'), ((4199, 4248), 'nbodykit.lab.BigFileMesh', 'BigFileMesh', (["(dfolder + 'linear')", '"""LinearDensityK"""'], {}), "(dfolder + 'linear', 'LinearDensityK')\n", (4210, 4248), False, 'from nbodykit.lab import KDDensity, BigFileMesh, BigFileCatalog, ArrayCatalog\n'), ((5673, 5711), 'nbodykit.lab.BigFileMesh', 'BigFileMesh', (["cfg['init']['sinit']", '"""s"""'], {}), "(cfg['init']['sinit'], 's')\n", (5684, 5711), False, 'from nbodykit.lab import KDDensity, BigFileMesh, BigFileCatalog, ArrayCatalog\n'), ((3178, 3200), 'numpy.array', 'numpy.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (3189, 3200), False, 'import numpy\n')]
|
from re import L
import sys
from typing import List
from tensorflow.python.ops.gen_array_ops import gather
sys.path.append('.')
import json
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from random import randint, randrange
from environment.base.base import BaseEnvironment
from environment.custom.resource_v3.reward import RewardFactory, ReducedNodeUsage
from environment.custom.resource_v3.misc.utils import compute_remaining_resources, round_half_up
from environment.custom.resource_v3.node import Node as History
from environment.custom.resource_v3.resource import Resource as Request
class ResourceEnvironmentV3(BaseEnvironment):
def __init__(self, name: str, opts: dict):
super(ResourceEnvironmentV3, self).__init__(name)
###########################################
##### PROBLEM CONFIGS FROM JSON FILE ######
###########################################
self.gather_stats: bool = False
self.generate_request_on_the_fly: bool = opts['generate_request_on_the_fly']
self.mask_nodes_in_mha: bool = opts['mask_nodes_in_mha']
self.seed_value: int = opts['seed_value']
self.normalization_factor: int = opts['normalization_factor']
self.decimal_precision: int = opts['decimal_precision']
self.batch_size: int = opts['batch_size']
self.num_features: int = opts['num_features']
self.num_profiles: int = opts['num_profiles']
self.profiles_sample_size: int = opts['profiles_sample_size']
assert self.num_profiles >= self.profiles_sample_size, 'Resource sample size should be less than total number of resources'
self.EOS_CODE: int = opts['EOS_CODE']
self.EOS_BIN = np.full((1, self.num_features), self.EOS_CODE, dtype='float32')
self.node_sample_size: int = opts['node_sample_size'] + 1 # + 1 because of the EOS bin
self.req_min_val: int = opts['req_min_val']
self.req_max_val: int = opts['req_max_val']
self.node_min_val: int = opts['node_min_val']
self.node_max_val: int = opts['node_max_val']
################################################
##### MATERIALIZED VARIABLES FROM CONFIGS ######
################################################
self.decoding_step = self.node_sample_size
self.rewarder = RewardFactory(
opts['reward'],
self.EOS_BIN
)
if isinstance(self.rewarder, ReducedNodeUsage):
self.is_empty = np.zeros((self.batch_size, self.node_sample_size + self.profiles_sample_size, 1), dtype='float32')
# First position is EOS
self.is_empty[:, 0, 0] = self.EOS_BIN[0][0]
else:
self.is_empty = None
# Generate req profiles
self.total_profiles = self.generate_dataset()
# Problem batch
self.batch, self.history = self.generate_batch()
# Default masks
# Will be updated during at each step() call
self.bin_net_mask,\
self.resource_net_mask,\
self.mha_used_mask = self.generate_masks()
def reset(self):
# Reset decoding step
self.decoding_step = self.node_sample_size
if isinstance(self.rewarder, ReducedNodeUsage):
self.is_empty = np.zeros(
(self.batch_size, self.node_sample_size + self.profiles_sample_size, 1), dtype='float32')
# First position is EOS
self.is_empty[:, 0, 0] = self.EOS_BIN[0][0]
self.batch, self.history = self.generate_batch()
self.bin_net_mask,\
self.resource_net_mask,\
self.mha_used_mask = self.generate_masks()
return self.state()
def state(self):
decoder_input = self.batch[:, self.decoding_step]
decoder_input = np.expand_dims(decoder_input, axis=1)
batch = self.batch.copy()
if isinstance(self.rewarder, ReducedNodeUsage):
batch = self.add_is_empty_dim(batch, self.is_empty)
return batch,\
decoder_input,\
self.bin_net_mask.copy(),\
self.mha_used_mask.copy()
def step(self, bin_ids: List[int], feasible_bin_mask):
# Default is not done
isDone = False
req_ids = tf.fill(self.batch_size, self.decoding_step)
batch_size = self.batch.shape[0]
num_elems = self.batch.shape[1]
batch_indices = tf.range(batch_size, dtype='int32')
# Copy the state before updating the values
copy_batch = self.batch.copy()
# Grab the selected nodes and resources
nodes: np.ndarray = self.batch[batch_indices, bin_ids]
reqs: np.ndarray = self.batch[batch_indices, req_ids]
# Compute remaining resources after placing reqs at nodes
remaining_resources = compute_remaining_resources(
nodes, reqs, self.decimal_precision)
# Update the batch state
self.batch[batch_indices, bin_ids] = remaining_resources
# Keep EOS node intact
self.batch[batch_indices, 0] = self.EOS_BIN
# Item taken mask it
self.resource_net_mask[batch_indices, req_ids] = 1
# Update node masks
dominant_resource = tf.reduce_min(remaining_resources, axis=-1)
is_full = tf.cast(tf.equal(dominant_resource, 0), dtype='float32')
# Mask full nodes/bins
self.bin_net_mask[batch_indices, bin_ids] = is_full
self.bin_net_mask[:, 0] = 0 # EOS is always available
# Update the MHA masks
self.mha_used_mask[batch_indices, :, :, req_ids] = 1
if self.mask_nodes_in_mha:
self.mha_used_mask[batch_indices, :, :, bin_ids] = tf.reshape(
is_full, (self.batch_size, 1, 1)
)
# EOS is always available
self.mha_used_mask[batch_indices, :, :, 0] = 0
if np.all(self.resource_net_mask == 1):
isDone = True
# Compute rewards
rewards = self.rewarder.compute_reward(
self.batch, # Already updated values of nodes, i.e., after insertion
copy_batch, # Original values of nodes, i.e., before insertion
self.node_sample_size,
nodes,
reqs,
feasible_bin_mask,
bin_ids,
self.is_empty
)
rewards = tf.reshape(rewards, (batch_size, 1))
#else:
# rewards = tf.zeros((batch_size, 1), dtype='float32')
info = {
'bin_net_mask': self.bin_net_mask.copy(),
'resource_net_mask': self.resource_net_mask.copy(),
'mha_used_mask': self.mha_used_mask.copy(),
# 'num_resource_to_place': self.num_profiles
}
if self.gather_stats:
self.place_reqs(bin_ids, req_ids, reqs)
# Pick next decoder_input
self.decoding_step += 1
if self.decoding_step < self.node_sample_size + self.profiles_sample_size:
decoder_input = self.batch[:, self.decoding_step]
decoder_input = np.expand_dims(decoder_input, axis=1)
else:
# We are done. No need to generate decoder input
decoder_input = np.array([None])
batch = self.batch.copy()
if isinstance(self.rewarder, ReducedNodeUsage):
batch = self.add_is_empty_dim(batch, self.is_empty)
return batch, decoder_input, rewards, isDone, info
def generate_dataset(self):
profiles = tf.random.uniform(
(self.num_profiles, self.num_features),
minval=self.req_min_val,
maxval=self.req_max_val,
dtype='int32',
seed=self.seed_value
) / self.normalization_factor
return tf.cast(profiles, dtype="float32")
def generate_batch(self):
history = []
elem_size = self.node_sample_size + self.profiles_sample_size
batch: np.ndarray = np.zeros(
(self.batch_size, elem_size, self.num_features),
dtype="float32"
)
# Generate nodes states
nodes = tf.random.uniform(
(self.batch_size, self.node_sample_size, self.num_features),
minval=self.node_min_val,
maxval=self.node_max_val,
dtype="int32",
seed=self.seed_value
) / self.normalization_factor
batch[:, :self.node_sample_size, :] = tf.cast(nodes, dtype="float32")
# Replace first position with EOS node
batch[:, 0, :] = self.EOS_BIN
if self.generate_request_on_the_fly:
# Generate reqs
reqs = tf.random.uniform(
(self.batch_size, self.profiles_sample_size, self.num_features),
minval=self.req_min_val,
maxval=self.req_max_val,
dtype="int32",
seed=self.seed_value
) / self.normalization_factor
batch[:, self.node_sample_size:, :] = tf.cast(reqs, dtype="float32")
else:
# Sample profiles and add them to batch instances
for index in range(self.batch_size):
shuffled_profiles = tf.random.shuffle(self.total_profiles)
batch[index, self.node_sample_size:, :] = shuffled_profiles[:self.profiles_sample_size]
# Create node instances that will gather stats
if self.gather_stats:
history = self.build_history(batch)
return batch, history
def generate_masks(self):
elem_size = self.node_sample_size + self.profiles_sample_size
# Represents positions marked as "0" where resource Ptr Net can point
profiles_net_mask = np.zeros((self.batch_size, elem_size), dtype='float32')
# Represents positions marked as "0" where bin Ptr Net can point
nodes_net_mask = np.ones(
(self.batch_size, elem_size), dtype='float32')
# Default mask for resources
#for batch_id in range(self.batch_size):
# for i in range(self.node_sample_size):
# profiles_net_mask[batch_id, i] = 1
profiles_net_mask[:, :self.node_sample_size] = 1
# Default mask for bin
nodes_net_mask = nodes_net_mask - profiles_net_mask
# For Transformer's multi head attention
mha_used_mask = np.zeros_like(profiles_net_mask)
mha_used_mask = mha_used_mask[:, np.newaxis, np.newaxis, :]
return nodes_net_mask, profiles_net_mask, mha_used_mask
def sample_action(self):
batch_indices = tf.range(self.batch.shape[0], dtype='int32')
resource_ids = tf.fill(self.batch_size, self.decoding_step)
# Decode the resources
decoded_resources = self.batch[batch_indices, resource_ids]
decoded_resources = np.expand_dims(decoded_resources, axis=1)
bins_mask = self.build_feasible_mask(self.batch,
decoded_resources,
self.bin_net_mask
)
bins_probs = np.random.uniform(size=self.bin_net_mask.shape)
bins_probs = tf.nn.softmax(bins_probs - (bins_mask*10e6), axis=-1)
dist_bin = tfp.distributions.Categorical(probs = bins_probs)
bin_ids = dist_bin.sample()
return bin_ids, bins_mask
def add_stats_to_agent_config(self, agent_config: dict):
agent_config['num_resources'] = self.profiles_sample_size
agent_config['num_bins'] = self.node_sample_size
agent_config['tensor_size'] = self.node_sample_size + self.profiles_sample_size
agent_config['batch_size'] = self.batch_size
# Init the object
agent_config["encoder_embedding"] = {}
if isinstance(self.rewarder, ReducedNodeUsage):
agent_config["encoder_embedding"]["common"] = False
agent_config["encoder_embedding"]["num_bin_features"] = 4
agent_config["encoder_embedding"]["num_resource_features"] = 3
else:
agent_config["encoder_embedding"]["common"] = True
# If using the same embedding layer these vars are unused
agent_config["encoder_embedding"]["num_bin_features"] = None
agent_config["encoder_embedding"]["num_resource_features"] = None
return agent_config
def set_testing_mode(self,
batch_size,
node_sample_size,
profiles_sample_size,
node_min_val,
node_max_val
) -> None:
self.gather_stats = True
self.batch_size = batch_size
self.node_min_val = node_min_val
self.node_max_val = node_max_val
self.node_sample_size = node_sample_size + 1 # +1 For EOS node
self.profiles_sample_size = profiles_sample_size
def build_history(self, batch):
history = []
for batch_id, instance in enumerate(batch):
nodes = []
for id, bin in enumerate(instance[:self.node_sample_size]):
nodes.append(
History(
batch_id,
id,
bin
)
)
history.append(nodes)
return history
def place_reqs(self, bin_ids: List[int], req_ids: List[int], reqs: np.ndarray):
for batch_index, bin_id in enumerate(bin_ids):
node: History = self.history[batch_index][bin_id]
req_id = req_ids[batch_index]
req = Request(
batch_index,
req_id,
reqs[batch_index]
)
node.insert_req(req)
def build_feasible_mask(self, state, resources, bin_net_mask):
if isinstance(self.rewarder, ReducedNodeUsage):
state = self.remove_is_empty_dim(state)
batch = state.shape[0]
num_elems = state.shape[1]
# Add batch dim to resources
# resource_demands = np.reshape(resources, (batch, 1, self.num_features))
# Tile to match the num elems
resource_demands = tf.tile(resources, [1, num_elems, 1])
# Compute remaining resources after placement
# remaining_resources = state - resource_demands
remaining_resources = compute_remaining_resources(
state, resource_demands, self.decimal_precision
)
dominant_resource = tf.reduce_min(remaining_resources, axis=-1)
# Ensure that it's greater that 0
# i.e., that node is not overloaded
after_place = tf.less(dominant_resource, 0)
after_place = tf.cast(after_place, dtype='float32')
# Can't point to resources positions
feasible_mask = tf.maximum(after_place, bin_net_mask)
feasible_mask = feasible_mask.numpy()
assert np.all(dominant_resource*(1-feasible_mask) >= 0), 'Masking Scheme Is Wrong!'
# EOS is always available for pointing
feasible_mask[:, 0] = 0
# Return as is. At this moment node can be overloaded
return feasible_mask
def add_is_empty_dim(self, batch, is_empty):
batch = np.concatenate([batch, is_empty], axis=-1)
return round_half_up(batch, 2)
def remove_is_empty_dim(self, batch):
batch = batch[:, :, :self.num_features]
return round_half_up(batch, 2)
def print_history(self, print_details = False) -> None: # pragma: no cover
for batch_id in range(self.batch_size):
print('_________________________________')
node: History
for node in self.history[batch_id]:
node.print(print_details)
print('_________________________________')
return
def store_dataset(self, location) -> None:
np.savetxt(location, self.total_profiles)
def load_dataset(self, location):
self.total_profiles = np.loadtxt(location)
if __name__ == "__main__": # pragma: no cover
env_name = 'ResourceEnvironmentV3'
with open(f"configs/ResourceV3.json") as json_file:
params = json.load(json_file)
env_configs = params['env_config']
env_configs['batch_size'] = 2
env = ResourceEnvironmentV3(env_name, env_configs)
state, dec, bin_net_mask, mha_mask = env.state()
# env.print_history()
feasible_net_mask = env.build_feasible_mask(state, dec, bin_net_mask)
bin_ids = [0,1]
resource_ids = None
next, decoder_input, rewards, isDone, info = env.step(bin_ids, feasible_net_mask)
next, decoder_input, rewards, isDone, info = env.step(bin_ids, feasible_net_mask)
env.reset()
next, decoder_input, rewards, isDone, info = env.step(bin_ids, feasible_net_mask)
next, decoder_input, rewards, isDone, info = env.step(bin_ids, feasible_net_mask)
a = 1
|
[
"tensorflow.maximum",
"tensorflow.reshape",
"numpy.ones",
"sys.path.append",
"numpy.full",
"tensorflow.nn.softmax",
"numpy.zeros_like",
"tensorflow.random.uniform",
"environment.custom.resource_v3.resource.Resource",
"tensorflow_probability.distributions.Categorical",
"environment.custom.resource_v3.misc.utils.compute_remaining_resources",
"tensorflow.less",
"numpy.savetxt",
"tensorflow.cast",
"numpy.loadtxt",
"tensorflow.reduce_min",
"tensorflow.equal",
"environment.custom.resource_v3.node.Node",
"tensorflow.range",
"tensorflow.tile",
"numpy.all",
"numpy.concatenate",
"tensorflow.random.shuffle",
"numpy.random.uniform",
"environment.custom.resource_v3.misc.utils.round_half_up",
"json.load",
"environment.custom.resource_v3.reward.RewardFactory",
"numpy.expand_dims",
"numpy.zeros",
"tensorflow.fill",
"numpy.array"
] |
[((109, 129), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (124, 129), False, 'import sys\n'), ((1760, 1823), 'numpy.full', 'np.full', (['(1, self.num_features)', 'self.EOS_CODE'], {'dtype': '"""float32"""'}), "((1, self.num_features), self.EOS_CODE, dtype='float32')\n", (1767, 1823), True, 'import numpy as np\n'), ((2381, 2424), 'environment.custom.resource_v3.reward.RewardFactory', 'RewardFactory', (["opts['reward']", 'self.EOS_BIN'], {}), "(opts['reward'], self.EOS_BIN)\n", (2394, 2424), False, 'from environment.custom.resource_v3.reward import RewardFactory, ReducedNodeUsage\n'), ((3857, 3894), 'numpy.expand_dims', 'np.expand_dims', (['decoder_input'], {'axis': '(1)'}), '(decoder_input, axis=1)\n', (3871, 3894), True, 'import numpy as np\n'), ((4312, 4356), 'tensorflow.fill', 'tf.fill', (['self.batch_size', 'self.decoding_step'], {}), '(self.batch_size, self.decoding_step)\n', (4319, 4356), True, 'import tensorflow as tf\n'), ((4463, 4498), 'tensorflow.range', 'tf.range', (['batch_size'], {'dtype': '"""int32"""'}), "(batch_size, dtype='int32')\n", (4471, 4498), True, 'import tensorflow as tf\n'), ((4870, 4934), 'environment.custom.resource_v3.misc.utils.compute_remaining_resources', 'compute_remaining_resources', (['nodes', 'reqs', 'self.decimal_precision'], {}), '(nodes, reqs, self.decimal_precision)\n', (4897, 4934), False, 'from environment.custom.resource_v3.misc.utils import compute_remaining_resources, round_half_up\n'), ((5296, 5339), 'tensorflow.reduce_min', 'tf.reduce_min', (['remaining_resources'], {'axis': '(-1)'}), '(remaining_resources, axis=-1)\n', (5309, 5339), True, 'import tensorflow as tf\n'), ((5944, 5979), 'numpy.all', 'np.all', (['(self.resource_net_mask == 1)'], {}), '(self.resource_net_mask == 1)\n', (5950, 5979), True, 'import numpy as np\n'), ((6417, 6453), 'tensorflow.reshape', 'tf.reshape', (['rewards', '(batch_size, 1)'], {}), '(rewards, (batch_size, 1))\n', (6427, 6453), True, 'import tensorflow as tf\n'), ((7830, 7864), 'tensorflow.cast', 'tf.cast', (['profiles'], {'dtype': '"""float32"""'}), "(profiles, dtype='float32')\n", (7837, 7864), True, 'import tensorflow as tf\n'), ((8017, 8091), 'numpy.zeros', 'np.zeros', (['(self.batch_size, elem_size, self.num_features)'], {'dtype': '"""float32"""'}), "((self.batch_size, elem_size, self.num_features), dtype='float32')\n", (8025, 8091), True, 'import numpy as np\n'), ((8488, 8519), 'tensorflow.cast', 'tf.cast', (['nodes'], {'dtype': '"""float32"""'}), "(nodes, dtype='float32')\n", (8495, 8519), True, 'import tensorflow as tf\n'), ((9787, 9842), 'numpy.zeros', 'np.zeros', (['(self.batch_size, elem_size)'], {'dtype': '"""float32"""'}), "((self.batch_size, elem_size), dtype='float32')\n", (9795, 9842), True, 'import numpy as np\n'), ((9941, 9995), 'numpy.ones', 'np.ones', (['(self.batch_size, elem_size)'], {'dtype': '"""float32"""'}), "((self.batch_size, elem_size), dtype='float32')\n", (9948, 9995), True, 'import numpy as np\n'), ((10432, 10464), 'numpy.zeros_like', 'np.zeros_like', (['profiles_net_mask'], {}), '(profiles_net_mask)\n', (10445, 10464), True, 'import numpy as np\n'), ((10657, 10701), 'tensorflow.range', 'tf.range', (['self.batch.shape[0]'], {'dtype': '"""int32"""'}), "(self.batch.shape[0], dtype='int32')\n", (10665, 10701), True, 'import tensorflow as tf\n'), ((10726, 10770), 'tensorflow.fill', 'tf.fill', (['self.batch_size', 'self.decoding_step'], {}), '(self.batch_size, self.decoding_step)\n', (10733, 10770), True, 'import tensorflow as tf\n'), ((10910, 10951), 'numpy.expand_dims', 'np.expand_dims', (['decoded_resources'], {'axis': '(1)'}), '(decoded_resources, axis=1)\n', (10924, 10951), True, 'import numpy as np\n'), ((11206, 11253), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'self.bin_net_mask.shape'}), '(size=self.bin_net_mask.shape)\n', (11223, 11253), True, 'import numpy as np\n'), ((11275, 11334), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['(bins_probs - bins_mask * 10000000.0)'], {'axis': '(-1)'}), '(bins_probs - bins_mask * 10000000.0, axis=-1)\n', (11288, 11334), True, 'import tensorflow as tf\n'), ((11349, 11396), 'tensorflow_probability.distributions.Categorical', 'tfp.distributions.Categorical', ([], {'probs': 'bins_probs'}), '(probs=bins_probs)\n', (11378, 11396), True, 'import tensorflow_probability as tfp\n'), ((14290, 14327), 'tensorflow.tile', 'tf.tile', (['resources', '[1, num_elems, 1]'], {}), '(resources, [1, num_elems, 1])\n', (14297, 14327), True, 'import tensorflow as tf\n'), ((14470, 14546), 'environment.custom.resource_v3.misc.utils.compute_remaining_resources', 'compute_remaining_resources', (['state', 'resource_demands', 'self.decimal_precision'], {}), '(state, resource_demands, self.decimal_precision)\n', (14497, 14546), False, 'from environment.custom.resource_v3.misc.utils import compute_remaining_resources, round_half_up\n'), ((14602, 14645), 'tensorflow.reduce_min', 'tf.reduce_min', (['remaining_resources'], {'axis': '(-1)'}), '(remaining_resources, axis=-1)\n', (14615, 14645), True, 'import tensorflow as tf\n'), ((14763, 14792), 'tensorflow.less', 'tf.less', (['dominant_resource', '(0)'], {}), '(dominant_resource, 0)\n', (14770, 14792), True, 'import tensorflow as tf\n'), ((14815, 14852), 'tensorflow.cast', 'tf.cast', (['after_place'], {'dtype': '"""float32"""'}), "(after_place, dtype='float32')\n", (14822, 14852), True, 'import tensorflow as tf\n'), ((14923, 14960), 'tensorflow.maximum', 'tf.maximum', (['after_place', 'bin_net_mask'], {}), '(after_place, bin_net_mask)\n', (14933, 14960), True, 'import tensorflow as tf\n'), ((15031, 15083), 'numpy.all', 'np.all', (['(dominant_resource * (1 - feasible_mask) >= 0)'], {}), '(dominant_resource * (1 - feasible_mask) >= 0)\n', (15037, 15083), True, 'import numpy as np\n'), ((15346, 15388), 'numpy.concatenate', 'np.concatenate', (['[batch, is_empty]'], {'axis': '(-1)'}), '([batch, is_empty], axis=-1)\n', (15360, 15388), True, 'import numpy as np\n'), ((15404, 15427), 'environment.custom.resource_v3.misc.utils.round_half_up', 'round_half_up', (['batch', '(2)'], {}), '(batch, 2)\n', (15417, 15427), False, 'from environment.custom.resource_v3.misc.utils import compute_remaining_resources, round_half_up\n'), ((15538, 15561), 'environment.custom.resource_v3.misc.utils.round_half_up', 'round_half_up', (['batch', '(2)'], {}), '(batch, 2)\n', (15551, 15561), False, 'from environment.custom.resource_v3.misc.utils import compute_remaining_resources, round_half_up\n'), ((15989, 16030), 'numpy.savetxt', 'np.savetxt', (['location', 'self.total_profiles'], {}), '(location, self.total_profiles)\n', (15999, 16030), True, 'import numpy as np\n'), ((16108, 16128), 'numpy.loadtxt', 'np.loadtxt', (['location'], {}), '(location)\n', (16118, 16128), True, 'import numpy as np\n'), ((16294, 16314), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (16303, 16314), False, 'import json\n'), ((2544, 2647), 'numpy.zeros', 'np.zeros', (['(self.batch_size, self.node_sample_size + self.profiles_sample_size, 1)'], {'dtype': '"""float32"""'}), "((self.batch_size, self.node_sample_size + self.\n profiles_sample_size, 1), dtype='float32')\n", (2552, 2647), True, 'import numpy as np\n'), ((3337, 3440), 'numpy.zeros', 'np.zeros', (['(self.batch_size, self.node_sample_size + self.profiles_sample_size, 1)'], {'dtype': '"""float32"""'}), "((self.batch_size, self.node_sample_size + self.\n profiles_sample_size, 1), dtype='float32')\n", (3345, 3440), True, 'import numpy as np\n'), ((5366, 5396), 'tensorflow.equal', 'tf.equal', (['dominant_resource', '(0)'], {}), '(dominant_resource, 0)\n', (5374, 5396), True, 'import tensorflow as tf\n'), ((5759, 5803), 'tensorflow.reshape', 'tf.reshape', (['is_full', '(self.batch_size, 1, 1)'], {}), '(is_full, (self.batch_size, 1, 1))\n', (5769, 5803), True, 'import tensorflow as tf\n'), ((7137, 7174), 'numpy.expand_dims', 'np.expand_dims', (['decoder_input'], {'axis': '(1)'}), '(decoder_input, axis=1)\n', (7151, 7174), True, 'import numpy as np\n'), ((7278, 7294), 'numpy.array', 'np.array', (['[None]'], {}), '([None])\n', (7286, 7294), True, 'import numpy as np\n'), ((7571, 7720), 'tensorflow.random.uniform', 'tf.random.uniform', (['(self.num_profiles, self.num_features)'], {'minval': 'self.req_min_val', 'maxval': 'self.req_max_val', 'dtype': '"""int32"""', 'seed': 'self.seed_value'}), "((self.num_profiles, self.num_features), minval=self.\n req_min_val, maxval=self.req_max_val, dtype='int32', seed=self.seed_value)\n", (7588, 7720), True, 'import tensorflow as tf\n'), ((8175, 8351), 'tensorflow.random.uniform', 'tf.random.uniform', (['(self.batch_size, self.node_sample_size, self.num_features)'], {'minval': 'self.node_min_val', 'maxval': 'self.node_max_val', 'dtype': '"""int32"""', 'seed': 'self.seed_value'}), "((self.batch_size, self.node_sample_size, self.\n num_features), minval=self.node_min_val, maxval=self.node_max_val,\n dtype='int32', seed=self.seed_value)\n", (8192, 8351), True, 'import tensorflow as tf\n'), ((9062, 9092), 'tensorflow.cast', 'tf.cast', (['reqs'], {'dtype': '"""float32"""'}), "(reqs, dtype='float32')\n", (9069, 9092), True, 'import tensorflow as tf\n'), ((13709, 13756), 'environment.custom.resource_v3.resource.Resource', 'Request', (['batch_index', 'req_id', 'reqs[batch_index]'], {}), '(batch_index, req_id, reqs[batch_index])\n', (13716, 13756), True, 'from environment.custom.resource_v3.resource import Resource as Request\n'), ((8707, 8886), 'tensorflow.random.uniform', 'tf.random.uniform', (['(self.batch_size, self.profiles_sample_size, self.num_features)'], {'minval': 'self.req_min_val', 'maxval': 'self.req_max_val', 'dtype': '"""int32"""', 'seed': 'self.seed_value'}), "((self.batch_size, self.profiles_sample_size, self.\n num_features), minval=self.req_min_val, maxval=self.req_max_val, dtype=\n 'int32', seed=self.seed_value)\n", (8724, 8886), True, 'import tensorflow as tf\n'), ((9254, 9292), 'tensorflow.random.shuffle', 'tf.random.shuffle', (['self.total_profiles'], {}), '(self.total_profiles)\n', (9271, 9292), True, 'import tensorflow as tf\n'), ((13215, 13241), 'environment.custom.resource_v3.node.Node', 'History', (['batch_id', 'id', 'bin'], {}), '(batch_id, id, bin)\n', (13222, 13241), True, 'from environment.custom.resource_v3.node import Node as History\n')]
|
import os
import numpy as np
import matplotlib.pyplot as plt
try:
import python_scripts.nalu.io as nalu
except ImportError:
raise ImportError('Download https://github.com/lawsonro3/python_scripts/blob/master/python_scripts/nalu/nalu_functions.py')
if __name__ == '__main__':
root_dir = '/Users/mlawson/GoogleDrive/Work/NREL/Projects/HFM-ECP/nrel_5mw/results/cori_data/'
if os.path.isdir(root_dir) is False:
raise Exception('root_dir does not exist')
####################################
# Load gC data
####################################
file_gC_13 = root_dir+'gCoarse.13/nrel_5mw_gCoarse.log'
th_gC_13,t_gC_13 = nalu.read_log(file_gC_13)
t_gC_13_avg = np.mean(t_gC_13[375:425,:],axis=0)
file_gC_26 = root_dir+'gCoarse.26/nrel_5mw_gCoarse.log'
th_gC_26,t_gC_26 = nalu.read_log(file_gC_26)
t_gC_26_avg = np.mean(t_gC_26[300:350,:],axis=0)
file_gC_52 = root_dir+'gCoarse.52/nrel_5mw_gCoarse.log'
th_gC_52,t_gC_52 = nalu.read_log(file_gC_52)
t_gC_52_avg = np.mean(t_gC_52[500:550,:],axis=0)
file_gC_104 = root_dir+'gCoarse.104/nrel_5mw_gCoarse.log'
th_gC_104,t_gC_104 = nalu.read_log(file_gC_104)
t_gC_104_avg = np.mean(t_gC_104[200:250,:],axis=0)
dofs_gC = 24846302 # num_nodes_gC
nodes_gC = np.array([[13],[26],[52],[104]])
cores_gC = nodes_gC*32
dof_per_core_gC = dofs_gC/cores_gC
t_avg_gC = np.array([t_gC_13_avg,t_gC_26_avg,t_gC_52_avg,t_gC_104_avg])
t_avg_gC = np.append(nodes_gC,t_avg_gC,axis=1)
t_avg_gC = np.append(cores_gC,t_avg_gC,axis=1)
t_avg_gC = np.append(dof_per_core_gC,t_avg_gC,axis=1)
t_avg_headers_gC = ['dof_per_core_gC','cores_gC','nodes_gC']
t_avg_headers_gC = t_avg_headers_gC + th_gC_13
linear_time_gC = t_avg_gC[0,-1]*(cores_gC[0]/cores_gC) # linear scaling
####################################`
# Load g1 data
####################################
file_g1_512 = root_dir+'g1.512/nrel_5mw_g1.log'
th_g1_512,t_g1_512 = nalu.read_log(file_g1_512)
t_g1_512_avg = np.mean(t_g1_512[-50:,:],axis=0)
file_g1_1024 = root_dir+'g1.1024/nrel_5mw_g1.log'
th_g1_1024,t_g1_1024 = nalu.read_log(file_g1_1024)
t_g1_1024_avg = np.mean(t_g1_1024[-50:,:],axis=0)
# file_g1_1536 = root_dir+'g1oarse.52/nrel_5mw_g1oarse.log'
# th_g1_1536,t_g1_1536 = nalu.read_log(file_g1_1536)
# t_g1_1536_avg = np.mean(t_g1_1536[500:550,:],axis=0)
dofs_g1 = 761112205 # num_nodes_g1
nodes_g1 = np.array([[512],[1024]])#,[1536]])
cores_g1 = nodes_g1*32
dof_per_core_g1 = dofs_g1/cores_g1
t_avg_g1 = np.array([t_g1_512_avg,t_g1_1024_avg])#,t_g1_1536_avg])
t_avg_g1 = np.append(nodes_g1,t_avg_g1,axis=1)
t_avg_g1 = np.append(cores_g1,t_avg_g1,axis=1)
t_avg_g1 = np.append(dof_per_core_g1,t_avg_g1,axis=1)
t_avg_headers_g1 = ['dof_per_core_g1','cores_g1','nodes_g1']
t_avg_headers_g1 = t_avg_headers_g1 + th_g1_512
linear_time_g1 = t_avg_g1[0,-1]*(cores_g1[0]/cores_g1) # linear scaling
####################################
## Plots
####################################
fig1 = '24.8 M Nodes (gCoarse) Timing'
fig2 = '761.1 M Nodes (g1) Timing'
fig3 = 'Nalu Scaling on Cori - Cores'
fig4 = 'Nalu Scaling on Cori - DOFs per Core'
####################################
# gC plotting
####################################
caption_text_gC = '* NREL 5 MW on Cori Haswell noodes\n* 32 MPI ranks/node 1 OMP thread\n* Muelu solver stack with the v27.xml settings\n * 24.8 M DOF'
plt.figure(fig1,figsize=[10,10])
plt.title(fig1)
for i in np.arange(1,5,1):
plt.plot(t_gC_13[:,i],label=th_gC_13[i]+' 416 cores_gC')
plt.plot(t_gC_26[:,i],label=th_gC_26[i]+' 832 cores_gC')
plt.plot(t_gC_52[:,i],label=th_gC_52[i]+' 1664 cores_gC')
plt.plot(t_gC_104[:,i],label=th_gC_104[i]+'3328 cores_gC')
plt.legend()
plt.xlabel('Timestep')
plt.ylabel('Time (s)')
plt.text(0, 100,caption_text_gC, fontsize=12)
label = '24.8 M DOF, 32 MPI/node, 1 OMP thread, muelu v27.xml'
plt.figure(fig3,figsize=[10,10])
plt.title(fig3)
plt.loglog(t_avg_gC[:,1],t_avg_gC[:,-1],'ks-',label=label)
plt.loglog(cores_gC,linear_time_gC,'k--',label='Linear')
plt.xlabel('Cores')
plt.ylabel('Mean Time per Timestep (s)')
plt.legend()
plt.figure(fig4,figsize=[10,10])
plt.title(fig4)
plt.loglog(t_avg_gC[:,0],t_avg_gC[:,-1],'ks-',label=label)
plt.loglog(dof_per_core_gC,linear_time_gC,'k--',label='linear')
plt.xlabel('DOFs per Core')
plt.ylabel('Mean Time per Timestep (s)')
plt.legend()
####################################
# g1 plotting
####################################
caption_text_g1 = '* NREL 5 MW on Cori Haswell noodes\n* 32 MPI ranks/node 1 OMP thread\n* Muelu solver stack with the v27.xml settings\n 761.1 M DOF'
color = 'tab:red'
plt.figure(fig2,figsize=[10,10])
plt.title(fig2)
for i in np.arange(1,5,1):
plt.plot(t_g1_512[:,i],label=th_g1_512[i]+' 16,384 cores_g1')
plt.plot(t_g1_1024[:,i],label=th_g1_1024[i]+' 32,768 cores_g1')
#plt.plot(t_g1_1536[:,i],label=th_g1_1536[i]+'49,152 cores_g1')
plt.legend()
plt.xlabel('Timestep')
plt.ylabel('Time (s)')
plt.text(0, 100,caption_text_g1, fontsize=12)
label = '761.1 M DOFs, 32 MPI/node, 1 OMP thread, muelu v27.xml'
plt.figure(fig3,figsize=[10,10])
plt.loglog(t_avg_g1[:,1],t_avg_g1[:,-1],'s-',label=label,color=color)
plt.loglog(cores_g1,linear_time_g1,'--',label='Linear',color=color)
plt.xlabel('Cores')
plt.ylabel('Mean Time per Timestep (s)')
plt.legend()
plt.figure(fig4,figsize=[10,10])
plt.loglog(t_avg_g1[:,0],t_avg_g1[:,-1],'s-',label=label,color=color)
plt.loglog(dof_per_core_g1,linear_time_g1,'--',label='linear',color=color)
plt.xlabel('DOFs per Core')
plt.ylabel('Mean Time per Timestep (s)')
plt.legend()
####################################
# Save plots
####################################
plt.figure(fig1); plt.savefig(root_dir+fig1+'.png',dpi=400)
plt.figure(fig2); plt.savefig(root_dir+fig2+'.png',dpi=400)
plt.figure(fig3); plt.savefig(root_dir+fig3+'.png',dpi=400)
plt.figure(fig4); plt.savefig(root_dir+fig4+'.png',dpi=400)
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.loglog",
"matplotlib.pyplot.plot",
"os.path.isdir",
"python_scripts.nalu.io.read_log",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.text",
"numpy.append",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.array",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig"
] |
[((662, 687), 'python_scripts.nalu.io.read_log', 'nalu.read_log', (['file_gC_13'], {}), '(file_gC_13)\n', (675, 687), True, 'import python_scripts.nalu.io as nalu\n'), ((706, 742), 'numpy.mean', 'np.mean', (['t_gC_13[375:425, :]'], {'axis': '(0)'}), '(t_gC_13[375:425, :], axis=0)\n', (713, 742), True, 'import numpy as np\n'), ((825, 850), 'python_scripts.nalu.io.read_log', 'nalu.read_log', (['file_gC_26'], {}), '(file_gC_26)\n', (838, 850), True, 'import python_scripts.nalu.io as nalu\n'), ((869, 905), 'numpy.mean', 'np.mean', (['t_gC_26[300:350, :]'], {'axis': '(0)'}), '(t_gC_26[300:350, :], axis=0)\n', (876, 905), True, 'import numpy as np\n'), ((988, 1013), 'python_scripts.nalu.io.read_log', 'nalu.read_log', (['file_gC_52'], {}), '(file_gC_52)\n', (1001, 1013), True, 'import python_scripts.nalu.io as nalu\n'), ((1032, 1068), 'numpy.mean', 'np.mean', (['t_gC_52[500:550, :]'], {'axis': '(0)'}), '(t_gC_52[500:550, :], axis=0)\n', (1039, 1068), True, 'import numpy as np\n'), ((1155, 1181), 'python_scripts.nalu.io.read_log', 'nalu.read_log', (['file_gC_104'], {}), '(file_gC_104)\n', (1168, 1181), True, 'import python_scripts.nalu.io as nalu\n'), ((1201, 1238), 'numpy.mean', 'np.mean', (['t_gC_104[200:250, :]'], {'axis': '(0)'}), '(t_gC_104[200:250, :], axis=0)\n', (1208, 1238), True, 'import numpy as np\n'), ((1291, 1326), 'numpy.array', 'np.array', (['[[13], [26], [52], [104]]'], {}), '([[13], [26], [52], [104]])\n', (1299, 1326), True, 'import numpy as np\n'), ((1406, 1469), 'numpy.array', 'np.array', (['[t_gC_13_avg, t_gC_26_avg, t_gC_52_avg, t_gC_104_avg]'], {}), '([t_gC_13_avg, t_gC_26_avg, t_gC_52_avg, t_gC_104_avg])\n', (1414, 1469), True, 'import numpy as np\n'), ((1482, 1519), 'numpy.append', 'np.append', (['nodes_gC', 't_avg_gC'], {'axis': '(1)'}), '(nodes_gC, t_avg_gC, axis=1)\n', (1491, 1519), True, 'import numpy as np\n'), ((1533, 1570), 'numpy.append', 'np.append', (['cores_gC', 't_avg_gC'], {'axis': '(1)'}), '(cores_gC, t_avg_gC, axis=1)\n', (1542, 1570), True, 'import numpy as np\n'), ((1584, 1628), 'numpy.append', 'np.append', (['dof_per_core_gC', 't_avg_gC'], {'axis': '(1)'}), '(dof_per_core_gC, t_avg_gC, axis=1)\n', (1593, 1628), True, 'import numpy as np\n'), ((2000, 2026), 'python_scripts.nalu.io.read_log', 'nalu.read_log', (['file_g1_512'], {}), '(file_g1_512)\n', (2013, 2026), True, 'import python_scripts.nalu.io as nalu\n'), ((2046, 2080), 'numpy.mean', 'np.mean', (['t_g1_512[-50:, :]'], {'axis': '(0)'}), '(t_g1_512[-50:, :], axis=0)\n', (2053, 2080), True, 'import numpy as np\n'), ((2161, 2188), 'python_scripts.nalu.io.read_log', 'nalu.read_log', (['file_g1_1024'], {}), '(file_g1_1024)\n', (2174, 2188), True, 'import python_scripts.nalu.io as nalu\n'), ((2209, 2244), 'numpy.mean', 'np.mean', (['t_g1_1024[-50:, :]'], {'axis': '(0)'}), '(t_g1_1024[-50:, :], axis=0)\n', (2216, 2244), True, 'import numpy as np\n'), ((2480, 2505), 'numpy.array', 'np.array', (['[[512], [1024]]'], {}), '([[512], [1024]])\n', (2488, 2505), True, 'import numpy as np\n'), ((2597, 2636), 'numpy.array', 'np.array', (['[t_g1_512_avg, t_g1_1024_avg]'], {}), '([t_g1_512_avg, t_g1_1024_avg])\n', (2605, 2636), True, 'import numpy as np\n'), ((2668, 2705), 'numpy.append', 'np.append', (['nodes_g1', 't_avg_g1'], {'axis': '(1)'}), '(nodes_g1, t_avg_g1, axis=1)\n', (2677, 2705), True, 'import numpy as np\n'), ((2719, 2756), 'numpy.append', 'np.append', (['cores_g1', 't_avg_g1'], {'axis': '(1)'}), '(cores_g1, t_avg_g1, axis=1)\n', (2728, 2756), True, 'import numpy as np\n'), ((2770, 2814), 'numpy.append', 'np.append', (['dof_per_core_g1', 't_avg_g1'], {'axis': '(1)'}), '(dof_per_core_g1, t_avg_g1, axis=1)\n', (2779, 2814), True, 'import numpy as np\n'), ((3539, 3573), 'matplotlib.pyplot.figure', 'plt.figure', (['fig1'], {'figsize': '[10, 10]'}), '(fig1, figsize=[10, 10])\n', (3549, 3573), True, 'import matplotlib.pyplot as plt\n'), ((3576, 3591), 'matplotlib.pyplot.title', 'plt.title', (['fig1'], {}), '(fig1)\n', (3585, 3591), True, 'import matplotlib.pyplot as plt\n'), ((3605, 3623), 'numpy.arange', 'np.arange', (['(1)', '(5)', '(1)'], {}), '(1, 5, 1)\n', (3614, 3623), True, 'import numpy as np\n'), ((3890, 3902), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3900, 3902), True, 'import matplotlib.pyplot as plt\n'), ((3907, 3929), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Timestep"""'], {}), "('Timestep')\n", (3917, 3929), True, 'import matplotlib.pyplot as plt\n'), ((3934, 3956), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Time (s)"""'], {}), "('Time (s)')\n", (3944, 3956), True, 'import matplotlib.pyplot as plt\n'), ((3961, 4007), 'matplotlib.pyplot.text', 'plt.text', (['(0)', '(100)', 'caption_text_gC'], {'fontsize': '(12)'}), '(0, 100, caption_text_gC, fontsize=12)\n', (3969, 4007), True, 'import matplotlib.pyplot as plt\n'), ((4079, 4113), 'matplotlib.pyplot.figure', 'plt.figure', (['fig3'], {'figsize': '[10, 10]'}), '(fig3, figsize=[10, 10])\n', (4089, 4113), True, 'import matplotlib.pyplot as plt\n'), ((4116, 4131), 'matplotlib.pyplot.title', 'plt.title', (['fig3'], {}), '(fig3)\n', (4125, 4131), True, 'import matplotlib.pyplot as plt\n'), ((4136, 4199), 'matplotlib.pyplot.loglog', 'plt.loglog', (['t_avg_gC[:, 1]', 't_avg_gC[:, -1]', '"""ks-"""'], {'label': 'label'}), "(t_avg_gC[:, 1], t_avg_gC[:, -1], 'ks-', label=label)\n", (4146, 4199), True, 'import matplotlib.pyplot as plt\n'), ((4199, 4258), 'matplotlib.pyplot.loglog', 'plt.loglog', (['cores_gC', 'linear_time_gC', '"""k--"""'], {'label': '"""Linear"""'}), "(cores_gC, linear_time_gC, 'k--', label='Linear')\n", (4209, 4258), True, 'import matplotlib.pyplot as plt\n'), ((4260, 4279), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Cores"""'], {}), "('Cores')\n", (4270, 4279), True, 'import matplotlib.pyplot as plt\n'), ((4284, 4324), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mean Time per Timestep (s)"""'], {}), "('Mean Time per Timestep (s)')\n", (4294, 4324), True, 'import matplotlib.pyplot as plt\n'), ((4329, 4341), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4339, 4341), True, 'import matplotlib.pyplot as plt\n'), ((4347, 4381), 'matplotlib.pyplot.figure', 'plt.figure', (['fig4'], {'figsize': '[10, 10]'}), '(fig4, figsize=[10, 10])\n', (4357, 4381), True, 'import matplotlib.pyplot as plt\n'), ((4384, 4399), 'matplotlib.pyplot.title', 'plt.title', (['fig4'], {}), '(fig4)\n', (4393, 4399), True, 'import matplotlib.pyplot as plt\n'), ((4404, 4467), 'matplotlib.pyplot.loglog', 'plt.loglog', (['t_avg_gC[:, 0]', 't_avg_gC[:, -1]', '"""ks-"""'], {'label': 'label'}), "(t_avg_gC[:, 0], t_avg_gC[:, -1], 'ks-', label=label)\n", (4414, 4467), True, 'import matplotlib.pyplot as plt\n'), ((4467, 4533), 'matplotlib.pyplot.loglog', 'plt.loglog', (['dof_per_core_gC', 'linear_time_gC', '"""k--"""'], {'label': '"""linear"""'}), "(dof_per_core_gC, linear_time_gC, 'k--', label='linear')\n", (4477, 4533), True, 'import matplotlib.pyplot as plt\n'), ((4535, 4562), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""DOFs per Core"""'], {}), "('DOFs per Core')\n", (4545, 4562), True, 'import matplotlib.pyplot as plt\n'), ((4567, 4607), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mean Time per Timestep (s)"""'], {}), "('Mean Time per Timestep (s)')\n", (4577, 4607), True, 'import matplotlib.pyplot as plt\n'), ((4612, 4624), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4622, 4624), True, 'import matplotlib.pyplot as plt\n'), ((4908, 4942), 'matplotlib.pyplot.figure', 'plt.figure', (['fig2'], {'figsize': '[10, 10]'}), '(fig2, figsize=[10, 10])\n', (4918, 4942), True, 'import matplotlib.pyplot as plt\n'), ((4945, 4960), 'matplotlib.pyplot.title', 'plt.title', (['fig2'], {}), '(fig2)\n', (4954, 4960), True, 'import matplotlib.pyplot as plt\n'), ((4974, 4992), 'numpy.arange', 'np.arange', (['(1)', '(5)', '(1)'], {}), '(1, 5, 1)\n', (4983, 4992), True, 'import numpy as np\n'), ((5211, 5223), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (5221, 5223), True, 'import matplotlib.pyplot as plt\n'), ((5228, 5250), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Timestep"""'], {}), "('Timestep')\n", (5238, 5250), True, 'import matplotlib.pyplot as plt\n'), ((5255, 5277), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Time (s)"""'], {}), "('Time (s)')\n", (5265, 5277), True, 'import matplotlib.pyplot as plt\n'), ((5282, 5328), 'matplotlib.pyplot.text', 'plt.text', (['(0)', '(100)', 'caption_text_g1'], {'fontsize': '(12)'}), '(0, 100, caption_text_g1, fontsize=12)\n', (5290, 5328), True, 'import matplotlib.pyplot as plt\n'), ((5402, 5436), 'matplotlib.pyplot.figure', 'plt.figure', (['fig3'], {'figsize': '[10, 10]'}), '(fig3, figsize=[10, 10])\n', (5412, 5436), True, 'import matplotlib.pyplot as plt\n'), ((5439, 5514), 'matplotlib.pyplot.loglog', 'plt.loglog', (['t_avg_g1[:, 1]', 't_avg_g1[:, -1]', '"""s-"""'], {'label': 'label', 'color': 'color'}), "(t_avg_g1[:, 1], t_avg_g1[:, -1], 's-', label=label, color=color)\n", (5449, 5514), True, 'import matplotlib.pyplot as plt\n'), ((5513, 5584), 'matplotlib.pyplot.loglog', 'plt.loglog', (['cores_g1', 'linear_time_g1', '"""--"""'], {'label': '"""Linear"""', 'color': 'color'}), "(cores_g1, linear_time_g1, '--', label='Linear', color=color)\n", (5523, 5584), True, 'import matplotlib.pyplot as plt\n'), ((5585, 5604), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Cores"""'], {}), "('Cores')\n", (5595, 5604), True, 'import matplotlib.pyplot as plt\n'), ((5609, 5649), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mean Time per Timestep (s)"""'], {}), "('Mean Time per Timestep (s)')\n", (5619, 5649), True, 'import matplotlib.pyplot as plt\n'), ((5654, 5666), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (5664, 5666), True, 'import matplotlib.pyplot as plt\n'), ((5672, 5706), 'matplotlib.pyplot.figure', 'plt.figure', (['fig4'], {'figsize': '[10, 10]'}), '(fig4, figsize=[10, 10])\n', (5682, 5706), True, 'import matplotlib.pyplot as plt\n'), ((5709, 5784), 'matplotlib.pyplot.loglog', 'plt.loglog', (['t_avg_g1[:, 0]', 't_avg_g1[:, -1]', '"""s-"""'], {'label': 'label', 'color': 'color'}), "(t_avg_g1[:, 0], t_avg_g1[:, -1], 's-', label=label, color=color)\n", (5719, 5784), True, 'import matplotlib.pyplot as plt\n'), ((5783, 5861), 'matplotlib.pyplot.loglog', 'plt.loglog', (['dof_per_core_g1', 'linear_time_g1', '"""--"""'], {'label': '"""linear"""', 'color': 'color'}), "(dof_per_core_g1, linear_time_g1, '--', label='linear', color=color)\n", (5793, 5861), True, 'import matplotlib.pyplot as plt\n'), ((5862, 5889), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""DOFs per Core"""'], {}), "('DOFs per Core')\n", (5872, 5889), True, 'import matplotlib.pyplot as plt\n'), ((5894, 5934), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mean Time per Timestep (s)"""'], {}), "('Mean Time per Timestep (s)')\n", (5904, 5934), True, 'import matplotlib.pyplot as plt\n'), ((5939, 5951), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (5949, 5951), True, 'import matplotlib.pyplot as plt\n'), ((6056, 6072), 'matplotlib.pyplot.figure', 'plt.figure', (['fig1'], {}), '(fig1)\n', (6066, 6072), True, 'import matplotlib.pyplot as plt\n'), ((6074, 6120), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(root_dir + fig1 + '.png')"], {'dpi': '(400)'}), "(root_dir + fig1 + '.png', dpi=400)\n", (6085, 6120), True, 'import matplotlib.pyplot as plt\n'), ((6120, 6136), 'matplotlib.pyplot.figure', 'plt.figure', (['fig2'], {}), '(fig2)\n', (6130, 6136), True, 'import matplotlib.pyplot as plt\n'), ((6138, 6184), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(root_dir + fig2 + '.png')"], {'dpi': '(400)'}), "(root_dir + fig2 + '.png', dpi=400)\n", (6149, 6184), True, 'import matplotlib.pyplot as plt\n'), ((6184, 6200), 'matplotlib.pyplot.figure', 'plt.figure', (['fig3'], {}), '(fig3)\n', (6194, 6200), True, 'import matplotlib.pyplot as plt\n'), ((6202, 6248), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(root_dir + fig3 + '.png')"], {'dpi': '(400)'}), "(root_dir + fig3 + '.png', dpi=400)\n", (6213, 6248), True, 'import matplotlib.pyplot as plt\n'), ((6248, 6264), 'matplotlib.pyplot.figure', 'plt.figure', (['fig4'], {}), '(fig4)\n', (6258, 6264), True, 'import matplotlib.pyplot as plt\n'), ((6266, 6312), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(root_dir + fig4 + '.png')"], {'dpi': '(400)'}), "(root_dir + fig4 + '.png', dpi=400)\n", (6277, 6312), True, 'import matplotlib.pyplot as plt\n'), ((392, 415), 'os.path.isdir', 'os.path.isdir', (['root_dir'], {}), '(root_dir)\n', (405, 415), False, 'import os\n'), ((3631, 3691), 'matplotlib.pyplot.plot', 'plt.plot', (['t_gC_13[:, i]'], {'label': "(th_gC_13[i] + ' 416 cores_gC')"}), "(t_gC_13[:, i], label=th_gC_13[i] + ' 416 cores_gC')\n", (3639, 3691), True, 'import matplotlib.pyplot as plt\n'), ((3696, 3756), 'matplotlib.pyplot.plot', 'plt.plot', (['t_gC_26[:, i]'], {'label': "(th_gC_26[i] + ' 832 cores_gC')"}), "(t_gC_26[:, i], label=th_gC_26[i] + ' 832 cores_gC')\n", (3704, 3756), True, 'import matplotlib.pyplot as plt\n'), ((3761, 3822), 'matplotlib.pyplot.plot', 'plt.plot', (['t_gC_52[:, i]'], {'label': "(th_gC_52[i] + ' 1664 cores_gC')"}), "(t_gC_52[:, i], label=th_gC_52[i] + ' 1664 cores_gC')\n", (3769, 3822), True, 'import matplotlib.pyplot as plt\n'), ((3827, 3889), 'matplotlib.pyplot.plot', 'plt.plot', (['t_gC_104[:, i]'], {'label': "(th_gC_104[i] + '3328 cores_gC')"}), "(t_gC_104[:, i], label=th_gC_104[i] + '3328 cores_gC')\n", (3835, 3889), True, 'import matplotlib.pyplot as plt\n'), ((5000, 5065), 'matplotlib.pyplot.plot', 'plt.plot', (['t_g1_512[:, i]'], {'label': "(th_g1_512[i] + ' 16,384 cores_g1')"}), "(t_g1_512[:, i], label=th_g1_512[i] + ' 16,384 cores_g1')\n", (5008, 5065), True, 'import matplotlib.pyplot as plt\n'), ((5070, 5137), 'matplotlib.pyplot.plot', 'plt.plot', (['t_g1_1024[:, i]'], {'label': "(th_g1_1024[i] + ' 32,768 cores_g1')"}), "(t_g1_1024[:, i], label=th_g1_1024[i] + ' 32,768 cores_g1')\n", (5078, 5137), True, 'import matplotlib.pyplot as plt\n')]
|
# -*- coding: utf-8 -*-
# COPYRIGHT 2017 <NAME>
# Truth network model analysis
from __future__ import print_function
import numpy as np
import tellurium as te
import antimony
import generate
import util
import clustering
def classify(setup, s_arr, c_arr):
"""
Ground truth classification. Returns initial perturbation response,
perturbation response, classification, and reaction index
:param g_truth: ground truth network matrix
:param s_truth: ground truth species concentrations
:param k_truth: ground truth rate constants
:param num_node: ground truth numbder of nodes
:param num_bound: ground truth numbder of boundary species
:param k_pert: perturbation amount
:param Thres: classification threshold
:rtype: list
"""
antimony.clearPreviousLoads()
# Strip and translate to string
t_s = setup.t_s.astype('str')
t_k = setup.t_k[setup.t_k != np.array(0)].astype('str')
#t_k_count = np.count_nonzero(setup.t_net)
t_ant = generate.generateAntimonyNew(setup.t_net, t_s, t_k, s_arr, c_arr)
#r_ind = np.array(np.where(setup.t_net != np.array(0))).T
r_ind = util.getPersistantOrder(setup.t_net, setup.p_net)
rr = te.loada(t_ant)
rr.reset() # ALWAYS RESET
rr.conservedMoietyAnalysis = True
pert_i = rr.steadyStateNamedArray() # Initial steady state
r_comb = clustering.getListOfCombinations(r_ind)
# Pertubation for rate constants
k_pert_output_i = np.empty([len(r_comb), setup.num_float])
for i in range(len(r_comb)):
k_pert_output_i[i] = util.perturbRate(rr, r_comb[i], setup.k_pert)
# Classification for rate constants
k_class_i = np.empty([len(r_comb), setup.num_float], dtype=int)
for i in range(len(r_comb)):
for j in range(setup.num_float):
k_diff = (k_pert_output_i[i][j] - pert_i[0][j])
if (np.abs(k_diff) > setup.Thres):
if k_diff < 0.:
k_class_i[i][j] = 1
else:
k_class_i[i][j] = 2
else:
k_class_i[i][j] = 0
antimony.clearPreviousLoads()
return pert_i[0], k_pert_output_i, k_class_i
def compareClass(t_analysis, k_class):
"""
Return indices of network matrices that fall into the same category and
those that does not fall into the same category as the result from true
network
:param t_analysis:
:param k_class:
"""
t_net_ind = []
nt_net_ind = []
for i in range(len(k_class)):
if np.array_equal(t_analysis[2], k_class[i]):
t_net_ind.append(i)
else:
nt_net_ind.append(i)
return t_net_ind, nt_net_ind
#@profile
def compareIndClass(t_analysis, k_class_i):
"""
Checks a single instance of classification against the true result. Returns
True if classification is identical and false otherwise
:param t_analysis:
:param k_class:
"""
partial = False
if np.array_equal(t_analysis, k_class_i):
partial = True
return partial
#def compareClass(p_r_ind, t_analysis, k_class, net_ind_group):
# """
# Return indices for network matrices that fall into the same category and
# those that does not fall into the same category as the output of ground
# truth model
#
# :param p_r_ind: persistant index
# :param t_analysis: output of ground truth classification
# :param k_class: classification output resulting from perturbing reaction
# :param net_ind_group: grouped reaction index
# :rtype: list
# """
#
# t_net_ind = []
# nt_net_ind = []
#
# for i in range(len(p_r_ind)):
# row = p_r_ind[i][0]
# col = p_r_ind[i][1]
#
# # Get generated classification from target indices
# t_k_class = sorted_k_class[row][col]
#
# # Get truth classification from target indices
# comp1 = np.array([np.in1d(t_analysis[3].T[0], row),
# np.in1d(t_analysis[3].T[1], col)])
#
# truth_k_class = t_analysis[2][comp1.all(axis=0)]
#
# # Get indices where generated classification and truth
# # classification is the same
# # TODO: Currently this matches all binary values
# ind_id = np.where((t_k_class == truth_k_class).all(axis=1))[0]
#
# # Network matrix indices that match with truth classification
# t_net_ind_i = net_ind_group[row][col][ind_id]
# # Network matrix indices that does not match with truth classification
# nt_net_ind_i = np.setdiff1d(net_ind_group[row][col], t_net_ind_i)
# t_net_ind.append(t_net_ind_i)
# nt_net_ind.append(nt_net_ind_i)
#
# return t_net_ind, nt_net_ind
|
[
"numpy.array_equal",
"numpy.abs",
"util.perturbRate",
"generate.generateAntimonyNew",
"numpy.array",
"antimony.clearPreviousLoads",
"tellurium.loada",
"util.getPersistantOrder",
"clustering.getListOfCombinations"
] |
[((785, 814), 'antimony.clearPreviousLoads', 'antimony.clearPreviousLoads', ([], {}), '()\n', (812, 814), False, 'import antimony\n'), ((1014, 1079), 'generate.generateAntimonyNew', 'generate.generateAntimonyNew', (['setup.t_net', 't_s', 't_k', 's_arr', 'c_arr'], {}), '(setup.t_net, t_s, t_k, s_arr, c_arr)\n', (1042, 1079), False, 'import generate\n'), ((1159, 1208), 'util.getPersistantOrder', 'util.getPersistantOrder', (['setup.t_net', 'setup.p_net'], {}), '(setup.t_net, setup.p_net)\n', (1182, 1208), False, 'import util\n'), ((1218, 1233), 'tellurium.loada', 'te.loada', (['t_ant'], {}), '(t_ant)\n', (1226, 1233), True, 'import tellurium as te\n'), ((1383, 1422), 'clustering.getListOfCombinations', 'clustering.getListOfCombinations', (['r_ind'], {}), '(r_ind)\n', (1415, 1422), False, 'import clustering\n'), ((2133, 2162), 'antimony.clearPreviousLoads', 'antimony.clearPreviousLoads', ([], {}), '()\n', (2160, 2162), False, 'import antimony\n'), ((3034, 3071), 'numpy.array_equal', 'np.array_equal', (['t_analysis', 'k_class_i'], {}), '(t_analysis, k_class_i)\n', (3048, 3071), True, 'import numpy as np\n'), ((1591, 1636), 'util.perturbRate', 'util.perturbRate', (['rr', 'r_comb[i]', 'setup.k_pert'], {}), '(rr, r_comb[i], setup.k_pert)\n', (1607, 1636), False, 'import util\n'), ((2578, 2619), 'numpy.array_equal', 'np.array_equal', (['t_analysis[2]', 'k_class[i]'], {}), '(t_analysis[2], k_class[i])\n', (2592, 2619), True, 'import numpy as np\n'), ((1901, 1915), 'numpy.abs', 'np.abs', (['k_diff'], {}), '(k_diff)\n', (1907, 1915), True, 'import numpy as np\n'), ((923, 934), 'numpy.array', 'np.array', (['(0)'], {}), '(0)\n', (931, 934), True, 'import numpy as np\n')]
|
"""
test_const_ionization.py
Author: <NAME>
Affiliation: University of Colorado at Boulder
Created on: Thu Oct 16 14:46:48 MDT 2014
Description:
"""
import ares
import numpy as np
import matplotlib.pyplot as pl
from ares.physics.CrossSections import PhotoIonizationCrossSection as sigma
s_per_yr = ares.physics.Constants.s_per_yr
pars = \
{
'problem_type': 0,
'grid_cells': 1,
'initial_ionization': [1.-1e-6, 1e-6],
#'initial_temperature': 1e4,# make cold so collisional ionization is negligible
'isothermal': False,
'stop_time': 10.0,
'plane_parallel': True,
'recombination': False, # To match analytical solution
'source_type': 'toy',
'source_qdot': 1e4, # solver fails when this is large (like 1e10)
'source_lifetime': 1e10,
'source_E': [13.60000001],
'source_LE': [1.0],
'secondary_ionization': 0,
'collisional_ionization': 0,
'logdtDataDump': 0.5,
'initial_timestep': 1e-15,
}
def test(rtol=1e-2):
# Numerical solution
sim = ares.simulations.RaySegment(**pars)
sim.run()
t, xHII = sim.CellEvolution(field='h_2')
fig = pl.figure(1, figsize=(8, 12))
ax1 = fig.add_subplot(211); ax2 = fig.add_subplot(212)
ax1.loglog(t / s_per_yr, xHII, color='k', label='numerical')
ax1.set_ylim(1e-8, 5)
ax1.set_ylabel(r'$x_{\mathrm{HII}}$')
# Analytic solution: exponential time evolution
sigma0 = sigma(pars['source_E'][0])
qdot = pars['source_qdot']
Gamma = qdot * sigma0
xi0 = pars['initial_ionization'][1]
C = 1. - xi0
def xi(t, Gamma=Gamma):
return 1. - C * np.exp(-Gamma * t)
xHII_anyl = np.array(list(map(xi, t)))
ax1.scatter(t / s_per_yr, xHII_anyl, color='b', facecolors='none', s=100,
label='analytic')
ax1.legend(loc='upper left', fontsize=14)
# Only test accuracy at somewhat later times
mask = t > 0
err = np.abs(xHII[mask] - xHII_anyl[mask]) / xHII_anyl[mask]
ax2.loglog(t / s_per_yr, err)
ax2.set_xlabel(r'$t \ (\mathrm{yr})$')
ax2.set_ylabel(r'rel. error')
pl.draw()
pl.savefig('{!s}.png'.format(__file__[0:__file__.rfind('.')]))
pl.close()
assert np.allclose(xHII[mask], xHII_anyl[mask], rtol=rtol, atol=0)
if __name__ == '__main__':
test()
|
[
"numpy.abs",
"matplotlib.pyplot.close",
"numpy.allclose",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.figure",
"ares.physics.CrossSections.PhotoIonizationCrossSection",
"numpy.exp",
"ares.simulations.RaySegment"
] |
[((976, 1011), 'ares.simulations.RaySegment', 'ares.simulations.RaySegment', ([], {}), '(**pars)\n', (1003, 1011), False, 'import ares\n'), ((1095, 1124), 'matplotlib.pyplot.figure', 'pl.figure', (['(1)'], {'figsize': '(8, 12)'}), '(1, figsize=(8, 12))\n', (1104, 1124), True, 'import matplotlib.pyplot as pl\n'), ((1392, 1418), 'ares.physics.CrossSections.PhotoIonizationCrossSection', 'sigma', (["pars['source_E'][0]"], {}), "(pars['source_E'][0])\n", (1397, 1418), True, 'from ares.physics.CrossSections import PhotoIonizationCrossSection as sigma\n'), ((2073, 2082), 'matplotlib.pyplot.draw', 'pl.draw', ([], {}), '()\n', (2080, 2082), True, 'import matplotlib.pyplot as pl\n'), ((2154, 2164), 'matplotlib.pyplot.close', 'pl.close', ([], {}), '()\n', (2162, 2164), True, 'import matplotlib.pyplot as pl\n'), ((2185, 2244), 'numpy.allclose', 'np.allclose', (['xHII[mask]', 'xHII_anyl[mask]'], {'rtol': 'rtol', 'atol': '(0)'}), '(xHII[mask], xHII_anyl[mask], rtol=rtol, atol=0)\n', (2196, 2244), True, 'import numpy as np\n'), ((1893, 1929), 'numpy.abs', 'np.abs', (['(xHII[mask] - xHII_anyl[mask])'], {}), '(xHII[mask] - xHII_anyl[mask])\n', (1899, 1929), True, 'import numpy as np\n'), ((1590, 1608), 'numpy.exp', 'np.exp', (['(-Gamma * t)'], {}), '(-Gamma * t)\n', (1596, 1608), True, 'import numpy as np\n')]
|
import scipy.io
import numpy as np
import sys
import os.path
import matplotlib.pyplot as plt
trans = [139.62,119.43,36.48,14.5]
mdata = []
def avgWaveSpeed(data,ampStart,ampEnd,freq,transducers,index1,index2):
total = 0
count = 0
print(data)
zer = highestPoint(data,ampStart,0)[0]
tz = np.arange(ampStart,ampEnd,(1/freq))
for i in tz:
tmp = highestPoint(data,i,zer)
#print(tmp)
print(tmp, " " , index1 , " ", index2)
total = total + (transducers[index2]-transducers[index1])/(tmp[index2+1] -tmp[index1+1])
count = count +1
total = total/count
return abs(total*1000)
def highestPoint(data,val,start):
x = []
x.append(0)
for b in range(start,len(data)):
count = 0
i = data[b]
#print(i," ",count)
for z in i :
if(z[0] > val):
x.append(count)
break
count = count + 1
lowest = 10000
highest = 0
for v in x:
if(v <= lowest):
lowest = v
if(v>= highest):
highest = v
x[0] = lowest
x.append(highest)
return x
def cailbration(data):
high = False
for x in data:
if(x[0]>2):
high = True
break
if(high):
for z in range(0,len(data)):
data[z] = ((data[z]*0.5001 + 1.0032 - 1.01325)*10.1974)+10
else:
for z in range(0,len(data)):
data[z] = ((data[z]*3.1277 - 0.263 - 1.01325)*10.1974)+10
return data
def onclick(event):
print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
('double' if event.dblclick else 'single', event.button,
event.x, event.y, event.xdata, event.ydata))
text = ""
if(os.path.isfile('testfile.txt')):
file2 = open('testfile.txt')
text = file2.read()
file2.close()
file = open('testfile.txt',"w")
file.write(text + str(event.ydata)+'\n')
file.close()
mdata = []
x = open('testfile.txt').read().split('\n')
if(len(x) >2):
#print(x)
mdata.append(float(x[0]))
mdata.append(float(x[1]))
file = open('testfile.txt',"w")
file.write("")
file.close()
#print(avgWaveSpeed(data,mdata[0],mdata[1],10,trans,2,0))
def main(file,idx,x):
fig = plt.figure(x)
gid = 200+(x*10)+idx
#if(x==1):
#fig = plt.figure(3)
#else:
#fig = plt.figure(4)
#location = input('MatLabFile Location\n')
location = file
mat = scipy.io.loadmat(location)
data = []
x = mat.get('VoltageAI0')[0][0][1][0][0]
time = []
for i in range(0,x):
time.append(i/1000)
#print(time)
for i in range(0,10):
tmp = 'VoltageAI'+str(i)
if(mat.get(tmp)==None):
break
else:
data.append(cailbration(mat.get(tmp)[0][0][0]))
colors = ['b','y','m','k','r']
count = 0
#zxcv = avgWaveSpeed(data,29.5,31,10,trans,2,0)
pltinone = True
#zxc = input("All in one? y/n?\n")
zxc = "y"
if(zxc =="n"):
pltinone = False
fig = plt.figure(2)
for i in data:
if(pltinone):
plt.subplot(gid)
line = plt.plot(time,i)
import random
r = lambda: random.randint(0,255)
colorz = ('#%02X%02X%02X' % (r(),r(),r()))
plt.setp(line,'color',colorz,'antialiased',True)
else:
cur = 221 + count
plt.subplot(cur)
plt.ylabel('Bar ( gauge )')
plt.xlabel('Time ( s )')
line = plt.plot(time,i)
plt.setp(line,'color',colors[count],'antialiased',True)
count = count+1
plt.ylabel('Meters of water( m )')
plt.xlabel('Time ( s )')
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.axis([0,8, 25, 35])
fig.canvas.mpl_disconnect(cid)
#return zxcv
return 1
sumx = 0
vals = []
main("D:\\Files\\Documents\\Programming\\PythonFiles\\SUWSS\\TDMS\\24July2018_Intact_1.mat",1,1)
#for i in range(1,2):
# print(i)
# sumx = sumx+(main('\TDMS\24July2018_Intact_'+str(i)+'.mat',i,2))
#print(sumx)
'''
sumy= 0
i = 6
for i in range(6,11):
print(i)
sumy = sumy+(main('LL Pipe Case\\24July2018_LL_'+str(i)+'.mat',240+i-5,2))
sumy = (sumy/5)
'''
#print(abs(sumx-sumy))
plt.show()
|
[
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"random.randint",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.setp",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] |
[((4374, 4384), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4382, 4384), True, 'import matplotlib.pyplot as plt\n'), ((309, 346), 'numpy.arange', 'np.arange', (['ampStart', 'ampEnd', '(1 / freq)'], {}), '(ampStart, ampEnd, 1 / freq)\n', (318, 346), True, 'import numpy as np\n'), ((2359, 2372), 'matplotlib.pyplot.figure', 'plt.figure', (['x'], {}), '(x)\n', (2369, 2372), True, 'import matplotlib.pyplot as plt\n'), ((3735, 3769), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Meters of water( m )"""'], {}), "('Meters of water( m )')\n", (3745, 3769), True, 'import matplotlib.pyplot as plt\n'), ((3774, 3798), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time ( s )"""'], {}), "('Time ( s )')\n", (3784, 3798), True, 'import matplotlib.pyplot as plt\n'), ((3867, 3891), 'matplotlib.pyplot.axis', 'plt.axis', (['[0, 8, 25, 35]'], {}), '([0, 8, 25, 35])\n', (3875, 3891), True, 'import matplotlib.pyplot as plt\n'), ((3144, 3157), 'matplotlib.pyplot.figure', 'plt.figure', (['(2)'], {}), '(2)\n', (3154, 3157), True, 'import matplotlib.pyplot as plt\n'), ((3211, 3227), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gid'], {}), '(gid)\n', (3222, 3227), True, 'import matplotlib.pyplot as plt\n'), ((3247, 3264), 'matplotlib.pyplot.plot', 'plt.plot', (['time', 'i'], {}), '(time, i)\n', (3255, 3264), True, 'import matplotlib.pyplot as plt\n'), ((3403, 3455), 'matplotlib.pyplot.setp', 'plt.setp', (['line', '"""color"""', 'colorz', '"""antialiased"""', '(True)'], {}), "(line, 'color', colorz, 'antialiased', True)\n", (3411, 3455), True, 'import matplotlib.pyplot as plt\n'), ((3508, 3524), 'matplotlib.pyplot.subplot', 'plt.subplot', (['cur'], {}), '(cur)\n', (3519, 3524), True, 'import matplotlib.pyplot as plt\n'), ((3537, 3564), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Bar ( gauge )"""'], {}), "('Bar ( gauge )')\n", (3547, 3564), True, 'import matplotlib.pyplot as plt\n'), ((3577, 3601), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time ( s )"""'], {}), "('Time ( s )')\n", (3587, 3601), True, 'import matplotlib.pyplot as plt\n'), ((3621, 3638), 'matplotlib.pyplot.plot', 'plt.plot', (['time', 'i'], {}), '(time, i)\n', (3629, 3638), True, 'import matplotlib.pyplot as plt\n'), ((3650, 3709), 'matplotlib.pyplot.setp', 'plt.setp', (['line', '"""color"""', 'colors[count]', '"""antialiased"""', '(True)'], {}), "(line, 'color', colors[count], 'antialiased', True)\n", (3658, 3709), True, 'import matplotlib.pyplot as plt\n'), ((3314, 3336), 'random.randint', 'random.randint', (['(0)', '(255)'], {}), '(0, 255)\n', (3328, 3336), False, 'import random\n')]
|
#!/usr/bin/env python
# coding: utf-8
# # Registration 101
#
# Image registration is a critical tool in longitudinal monitoring:
#
# - Estimation of local changes
# - Comparison to same animal (less variance)
# - [3R's](https://www.nc3rs.org.uk/the-3rs)
#
#
#
# ## Goal of tutorial:
# - Introduce the concept of aligning images
# - Demonstrate the use of numerical comparison between images
# - Introduce concept of optimisation
# - Registering images within framework (Thesis: <NAME> & <NAME>)
# ## setting up a responsive enviroment
# In[1]:
# Please do not edit this code, it is important for choosing a compatible rendered for images
# libraries for viewing images
import sys
sys.path.append("reg101_files")
from image_viewing import horizontal_pane, overlay_RGB, overlay_RGB_cost
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# numpy as always
import numpy as np
# In[2]:
# this is a way of finding the fastest image display on your platform
print("Using:", matplotlib.get_backend())
gui_env = ["WXAgg", "TKAgg", "QT5Agg", "GTKAgg", "Qt4Agg"]
for gui in gui_env:
try:
print("testing", gui)
matplotlib.use(gui, warn=False, force=True)
from matplotlib import pyplot as plt
break
except:
continue
print("Using:", matplotlib.get_backend())
# ## What does registration actually do?
#
# In the example bellow there are images from 2 weeks.
#
# The position of the animal in the scanner was different each.
#
# In[3]:
get_ipython().run_line_magic("matplotlib", "notebook")
# this allows the image to be viewed in the notebook with edge
matplotlib.rcParams["figure.figsize"] = (8, 7)
images = [
mpimg.imread("reg101_files/week2.tiff"),
mpimg.imread("reg101_files/week3.tiff"),
]
horizontal_pane(images) # shows images side by side
# How can we interpret these images?
#
# In in vivo studies, it is still common to *dynamic histomorphometry*, where markers are given to the mice at different intervals over the course if a study. These are built into the bone matrix and afterwards can be labeled and visualised in histological sections.
#
# 
#
# In the above image above the green strain was used to mark the surface where bone formed. While the red is marking Osteoid (newly formed un minerlaised bone). The method is limited to purely observation of anabolic events. Resorption of bone removes material and therefore there is nothing which can be stained.
#
# Inspired by these histological images we can create a virtual histology image. In these images we will "stain" the change of mineralisation between the two weeks. Both images are grey-scale (1 -color) , we can emulate the histology by using colour channels. Here we put the *Later* week in *green* and the *Former* week in *red*, both weeks are averaged in the blue channel.
#
# When the images are aligned we see white (R+G+B) when the *Former* week is brighter we see *green* and when the *later* week is brighter we see *red*. This is essentially formation == green and resorption == red. The function bellow does this for use automically.
#
# In[4]:
# puts the images into the Red(week1) and G(week2) channel of an image
overlay_RGB(images)
# These images are clearly not well aligned. We will now discuss how to align the images.
# ## Overlaying an image
#
# Registration involves finding the best set of transormation paramters for overlaying an image.
#
# Run the following cell and try to find the best x,y,theta for aligning the images.
# In[5]:
# manual transform
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
from IPython.display import clear_output, display
from scipy.ndimage import affine_transform
def move_overlay(image1, image2, dx, dy):
T = np.identity(3)
T[0, 2] = dy
T[1, 2] = dx
images = [image1, affine_transform(image2, T)]
overlay_RGB(images)
clear_output(True)
# In[6]:
interactive(
move_overlay,
image1=fixed(images[0]),
image2=fixed(images[1]),
dx=(-50, 50, 0.25),
dy=(-50, 50, 0.25),
)
# In[7]:
class_x = [-4.5, -6.5, -5.0, -4.25, -4, -5, -4.7]
class_y = [-18.5, -22, -20.5, -20, -19, -19, -19.5]
print("Class variance in X: ", np.mean(class_x))
print("Class variance in Y: ", np.mean(class_y))
# ## Cost functions
#
# We have now demonstrated the use of a powerful neural network (you) on finding the best fit. In realitiy the computer is not aware of what the images look like. The registration algorithm needs to numerically determine the goodness of fit, it can then optimize until the correct paramters are found.
#
# Image we have two images X and Y. The lease squared difference would be as follows:
#
# \begin{equation*}
# C^{LS} = \sum \left( X - Y \right)^2
# \end{equation*}
#
# Where this is the pixel-wise sum of both images. In Python it looks like this:
#
#
# ```python
# def least_squared(X,Y):
# delta = X-Y
# square_delta = delta**2
# return np.sum(square_delta)
#
# ```
#
# Another meausure of similarity is the correlations function:
# \begin{equation*}
# C^{cor} = \frac{\sum \left( X \cdot Y \right) }{\sqrt{\sum X^2}.\sqrt{\sum Y^2}}
# \end{equation*}
#
# In python it looks like this:
# ```python
# def correlation(Image1,Image2):
# corr = np.corrcoef(Image1,y=Image2)
# return(corr[0,1])
# ```
#
# ### excercise 2:
# Align the images again, this time try and use the cost function to determine your next move.
#
# In[8]:
# abs diference cost
def least_squared(Image1, Image2):
delta = Image1 - Image2
return np.sum(delta ** 2)
# In[9]:
def correlation(Image1, Image2):
return -1 * np.corrcoef(Image1.flatten(), y=Image2.flatten())[0, 1]
# In[10]:
c_funs = {"correlation": correlation, "least_squared": least_squared}
# In[11]:
cost = {c: [] for c in c_funs}
cost_function_names = [n for n in c_funs]
def move_overlay(image1, image2, dx, dy, cost_history, cost_function, cfuncs):
T = np.identity(3)
T[0, 2] = dy
T[1, 2] = dx
images = [image1, affine_transform(image2, T)]
overlay_RGB_cost(images, cost_history, cost_function, cfuncs, dx, dy)
clear_output(True)
# In[12]:
interactive(
move_overlay,
image1=fixed(images[0]),
image2=fixed(images[1]),
dx=(-60, 60, 0.5),
dy=(-60, 60, 0.5),
cost_history=fixed(cost),
cost_function=cost_function_names,
cfuncs=fixed(c_funs),
)
# In[13]:
comutational_cost = {"correlation": 0, "least_squared": 0, "abs_squared_difference": 0}
for function, v in cost.items():
for pix in v:
comutational_cost[function] += pix[3]
print("The total pixel cost was:", comutational_cost)
# This is quite an intenive task. For each movmement you made every pixel was evaluated to determine the cost function. Ideally we should align the images close so that they need less transformations. This can be done through two ways:
#
# 1. An initial guess
#
# 2. A multi-resolution scheme
#
# A good initial guess is a holy grail in image registration, these could involve calcuating principle axes and centerms of mass. However during fracture healing the changes in the bone are large, the formation of new material can cause priciple axes to flip or swap.
#
# A multi-resolution scheme on the other hand reduces the problem size, progressivly increasing it until the images are comapred at the native resoltuion. This system is "easy" to implement and has an inherent strength over the naive aproach.
#
# Images contain different frequencies. In general flat areas are low frequency whilke edges (and noise) are high frequency. The lower resolution images are predominatnly low frequency information and have comparatively less noise. A pyramid approach is effectivly using a smoothed cost function, avoiding local minima, while the progressive increasing of the resolution adds high frequency correction to the solution.
#
# In[14]:
def split_frequency(frequency, image):
f = np.fft.fft2(image) # forward fft
fshift = np.fft.fftshift(f) # shift to center frequencies
hff = np.copy(fshift)
origin = np.array(hff.shape) * 0.5
y, x = np.ogrid[-origin[0] : origin[0], -origin[1] : origin[1]]
mask = (
x * x + y * y <= frequency * frequency
) # mask for high and low pass filtering
hff[mask] = 0 # high pass filter
lff = np.copy(fshift)
lff[mask != 1] = 0 # low pass filter
hff_ishift = np.fft.ifftshift(hff) # inverse shift
lff_ishift = np.fft.ifftshift(lff) # inverse shift
lff_back = np.fft.ifft2(lff_ishift) # inverse fft
hff_back = np.fft.ifft2(hff_ishift) # inverse fft
hff_back = np.abs(hff_back)
lff_back = np.abs(lff_back)
# contrast adjustment for viewing image
hff_back /= np.percentile(hff_back, 99)
hff_back[hff_back > 1] = 1.0
horizontal_pane([image, (lff_back), hff_back])
# In[15]:
interactive(split_frequency, frequency=(0, 204, 1), image=fixed(images[0]))
# ## Pyrmaid registration
#
# - Frequencies are dependent on the image resolution
# - Easiest way to create a pyramid is to create a stack of rescaled images
# In[16]:
# manual transform
from scipy.ndimage.interpolation import zoom
cost_pyramid = {c: [] for c in c_funs}
def move_overlay_pyramid(
image1, image2, dx, dy, cost_history, cost_function, cfuncs, level, history
):
level = int(level)
level = 2 ** (level - 1)
if level != 1:
i1 = zoom(image1, 1 / level, order=0)
i2 = zoom(image2, 1 / level, order=0)
else:
i1 = image1
i2 = image2
T = np.identity(3)
T[0, 2] = dy * 1 / level
T[1, 2] = dx * 1 / level
if level != 1:
images = [i1, affine_transform(i2, T, order=0)]
else:
images = [i1, affine_transform(i2, T)]
if len(cost_history) > 0:
overlay_RGB_cost(images, cost_history, cost_function, cfuncs, dx, dy, history)
else:
print("Move around to make some history")
clear_output(True)
# In[17]:
interactive(
move_overlay_pyramid,
image1=fixed(images[0]),
image2=fixed(images[1]),
dx=(-60, 60, 0.5),
dy=(-60, 60, 0.5),
cost_history=fixed(cost_pyramid),
cost_function=cost_function_names,
cfuncs=fixed(c_funs),
level=[5, 4, 3, 2, 1],
history=[None, 10, 20, 100],
)
# In[18]:
comutational_cost_pyramid = {"correlation": 0, "least_squared": 0}
for function, v in cost_pyramid.items():
for pix in v:
comutational_cost_pyramid[function] += pix[3]
print("The total pixel cost was:", comutational_cost_pyramid)
# # Automated registration
#
# This is cleary a difficult problem to do by hand. As we have these functions it should be easy to minimise them. Actualy there is a whole field of mathematics and computer science devoted towards this: Optimisation. It is not really "easy" to do.
#
# There are several course at the ETH which can give actually useful information on this:
# - 401-0647-00L Introduction to Mathematical Optimization
# - 227-0707-00L Optimization Methods for Engineers (good for Graeme)
# - 261-5110-00L Optimization for Data Science (Machine learning)
# - 401-3904-00L Convex Optimization (Applied to specific problems where the only minima is the global minimum)
#
# In the bellow example the registration is performed using a [Evolutionary Algorithm](https://en.wikipedia.org/wiki/Evolutionary_algorithm). Simply put a random population of initial guesses are used, the cost function is determined for each and only the fittest X% are mated to create a new set of guesses.
#
# To avoid being captured in local minima *mutations* are introduced, which introduce new paramters values to the increasingly homogenus population.
# In[19]:
# opitimizer with least squared
from scipy.optimize import minimize as ls
from scipy.optimize import differential_evolution
def correlation(x, i1, i2, path):
x = np.array(x)
T = np.identity(3)
T[0, 2] = x[1]
T[1, 2] = x[0]
images = [i1.flatten(), affine_transform(i2, T).flatten()]
delta = -1 * np.corrcoef(images[0], y=images[1])[0, 1]
path.append((x[0], x[1], delta))
return delta
def least_squared(x, i1, i2, path):
x = np.array(x)
T = np.identity(3)
T[0, 2] = x[1]
T[1, 2] = x[0]
images = [i1, affine_transform(i2, T)]
delta = np.sum((images[0] - images[1]) ** 2)
path.append((x[0], x[1], delta))
return delta
path_corralation = []
optimum_c = differential_evolution(
correlation,
[(-60, 30), (-60, 30)],
args=(images[0], images[1], path_corralation),
tol=0.00125,
) # ,method='Powell',options={'eps':0.5})
path_least_squared = []
optimum_ls = differential_evolution(
least_squared,
[(-60, 30), (-60, 30)],
args=(images[0], images[1], path_least_squared),
tol=0.00125,
) # ,method='Powell',options={'eps':0.5})
# We have now searched for the best transform using both cost functions. What do they look like?
# In[20]:
# Using the correlation cost function
x = optimum_c["x"]
T = np.identity(3)
T[0, 2] = x[1]
T[1, 2] = x[0]
overlay_RGB([images[0], affine_transform(images[1], T)])
# In[21]:
# Using the Least squared cost function
x = optimum_ls["x"]
T = np.identity(3)
T[0, 2] = x[1]
T[1, 2] = x[0]
overlay_RGB([images[0], affine_transform(images[1], T)])
# In[22]:
# difference in the images
diff = []
x = optimum_ls["x"]
T = np.identity(3)
T[0, 2] = x[1]
T[1, 2] = x[0]
diff.append(affine_transform(images[1], T))
x = optimum_c["x"]
T = np.identity(3)
T[0, 2] = x[1]
T[1, 2] = x[0]
diff.append(affine_transform(images[1], T))
overlay_RGB(diff)
# In[23]:
print("Difference in the transformation", optimum_ls["x"] - optimum_c["x"])
# In the cell bellow the cost functions are plotted. This can be done as the optimization we used search an entire range of parameters.
#
# In[24]:
p_c = np.array(path_corralation)
p_ls = np.array(path_least_squared)
import matplotlib.tri as mtri
fig = plt.figure()
matplotlib.rcParams["figure.figsize"] = (9, 10)
"""
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(p_c[:,0],p_c[:,1],p_c[:,2],cmap=plt.cm.jet)
ax.set_title("Correlation")
ax.set_xlabel("dx")
ax.set_ylabel("dy")
ax.set_zlabel("cost (-)")
"""
ax = fig.add_subplot(111, projection="3d")
ax.set_title("Least Squared")
ax.set_xlabel("dx")
ax.set_ylabel("dy")
ax.set_zlabel("cost (-)")
ax.plot_trisurf(p_ls[:, 0], p_ls[:, 1], p_ls[:, 2], cmap=plt.cm.jet)
# # Conclusion to part 1
#
# - Image registration is not black magic
# - It is repetitive but simple maths
# - Algorithms are fallible:
# - Local minima in solution
# - Orientation of images
# - Qualitiy of images
# - Understanding your chosen cost function crucial for:
# - Choosing an algorithm
# - Knowing if your data is sufficient
|
[
"numpy.sum",
"numpy.abs",
"matplotlib.pyplot.figure",
"numpy.mean",
"ipywidgets.fixed",
"numpy.fft.ifft2",
"matplotlib.get_backend",
"sys.path.append",
"image_viewing.overlay_RGB",
"numpy.fft.ifftshift",
"numpy.copy",
"numpy.identity",
"image_viewing.horizontal_pane",
"scipy.ndimage.interpolation.zoom",
"scipy.ndimage.affine_transform",
"matplotlib.image.imread",
"numpy.corrcoef",
"scipy.optimize.differential_evolution",
"numpy.percentile",
"numpy.fft.fftshift",
"matplotlib.use",
"numpy.fft.fft2",
"IPython.display.clear_output",
"numpy.array",
"image_viewing.overlay_RGB_cost"
] |
[((688, 719), 'sys.path.append', 'sys.path.append', (['"""reg101_files"""'], {}), "('reg101_files')\n", (703, 719), False, 'import sys\n'), ((1790, 1813), 'image_viewing.horizontal_pane', 'horizontal_pane', (['images'], {}), '(images)\n', (1805, 1813), False, 'from image_viewing import horizontal_pane, overlay_RGB, overlay_RGB_cost\n'), ((3229, 3248), 'image_viewing.overlay_RGB', 'overlay_RGB', (['images'], {}), '(images)\n', (3240, 3248), False, 'from image_viewing import horizontal_pane, overlay_RGB, overlay_RGB_cost\n'), ((12472, 12595), 'scipy.optimize.differential_evolution', 'differential_evolution', (['correlation', '[(-60, 30), (-60, 30)]'], {'args': '(images[0], images[1], path_corralation)', 'tol': '(0.00125)'}), '(correlation, [(-60, 30), (-60, 30)], args=(images[0],\n images[1], path_corralation), tol=0.00125)\n', (12494, 12595), False, 'from scipy.optimize import differential_evolution\n'), ((12690, 12818), 'scipy.optimize.differential_evolution', 'differential_evolution', (['least_squared', '[(-60, 30), (-60, 30)]'], {'args': '(images[0], images[1], path_least_squared)', 'tol': '(0.00125)'}), '(least_squared, [(-60, 30), (-60, 30)], args=(images[\n 0], images[1], path_least_squared), tol=0.00125)\n', (12712, 12818), False, 'from scipy.optimize import differential_evolution\n'), ((13048, 13062), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (13059, 13062), True, 'import numpy as np\n'), ((13228, 13242), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (13239, 13242), True, 'import numpy as np\n'), ((13405, 13419), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (13416, 13419), True, 'import numpy as np\n'), ((13517, 13531), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (13528, 13531), True, 'import numpy as np\n'), ((13606, 13623), 'image_viewing.overlay_RGB', 'overlay_RGB', (['diff'], {}), '(diff)\n', (13617, 13623), False, 'from image_viewing import horizontal_pane, overlay_RGB, overlay_RGB_cost\n'), ((13873, 13899), 'numpy.array', 'np.array', (['path_corralation'], {}), '(path_corralation)\n', (13881, 13899), True, 'import numpy as np\n'), ((13907, 13935), 'numpy.array', 'np.array', (['path_least_squared'], {}), '(path_least_squared)\n', (13915, 13935), True, 'import numpy as np\n'), ((13975, 13987), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (13985, 13987), True, 'from matplotlib import pyplot as plt\n'), ((1013, 1037), 'matplotlib.get_backend', 'matplotlib.get_backend', ([], {}), '()\n', (1035, 1037), False, 'import matplotlib\n'), ((1314, 1338), 'matplotlib.get_backend', 'matplotlib.get_backend', ([], {}), '()\n', (1336, 1338), False, 'import matplotlib\n'), ((1701, 1740), 'matplotlib.image.imread', 'mpimg.imread', (['"""reg101_files/week2.tiff"""'], {}), "('reg101_files/week2.tiff')\n", (1713, 1740), True, 'import matplotlib.image as mpimg\n'), ((1746, 1785), 'matplotlib.image.imread', 'mpimg.imread', (['"""reg101_files/week3.tiff"""'], {}), "('reg101_files/week3.tiff')\n", (1758, 1785), True, 'import matplotlib.image as mpimg\n'), ((3827, 3841), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (3838, 3841), True, 'import numpy as np\n'), ((3931, 3950), 'image_viewing.overlay_RGB', 'overlay_RGB', (['images'], {}), '(images)\n', (3942, 3950), False, 'from image_viewing import horizontal_pane, overlay_RGB, overlay_RGB_cost\n'), ((3955, 3973), 'IPython.display.clear_output', 'clear_output', (['(True)'], {}), '(True)\n', (3967, 3973), False, 'from IPython.display import clear_output, display\n'), ((4273, 4289), 'numpy.mean', 'np.mean', (['class_x'], {}), '(class_x)\n', (4280, 4289), True, 'import numpy as np\n'), ((4322, 4338), 'numpy.mean', 'np.mean', (['class_y'], {}), '(class_y)\n', (4329, 4338), True, 'import numpy as np\n'), ((5618, 5636), 'numpy.sum', 'np.sum', (['(delta ** 2)'], {}), '(delta ** 2)\n', (5624, 5636), True, 'import numpy as np\n'), ((6015, 6029), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (6026, 6029), True, 'import numpy as np\n'), ((6119, 6188), 'image_viewing.overlay_RGB_cost', 'overlay_RGB_cost', (['images', 'cost_history', 'cost_function', 'cfuncs', 'dx', 'dy'], {}), '(images, cost_history, cost_function, cfuncs, dx, dy)\n', (6135, 6188), False, 'from image_viewing import horizontal_pane, overlay_RGB, overlay_RGB_cost\n'), ((6193, 6211), 'IPython.display.clear_output', 'clear_output', (['(True)'], {}), '(True)\n', (6205, 6211), False, 'from IPython.display import clear_output, display\n'), ((8007, 8025), 'numpy.fft.fft2', 'np.fft.fft2', (['image'], {}), '(image)\n', (8018, 8025), True, 'import numpy as np\n'), ((8054, 8072), 'numpy.fft.fftshift', 'np.fft.fftshift', (['f'], {}), '(f)\n', (8069, 8072), True, 'import numpy as np\n'), ((8114, 8129), 'numpy.copy', 'np.copy', (['fshift'], {}), '(fshift)\n', (8121, 8129), True, 'import numpy as np\n'), ((8391, 8406), 'numpy.copy', 'np.copy', (['fshift'], {}), '(fshift)\n', (8398, 8406), True, 'import numpy as np\n'), ((8466, 8487), 'numpy.fft.ifftshift', 'np.fft.ifftshift', (['hff'], {}), '(hff)\n', (8482, 8487), True, 'import numpy as np\n'), ((8522, 8543), 'numpy.fft.ifftshift', 'np.fft.ifftshift', (['lff'], {}), '(lff)\n', (8538, 8543), True, 'import numpy as np\n'), ((8576, 8600), 'numpy.fft.ifft2', 'np.fft.ifft2', (['lff_ishift'], {}), '(lff_ishift)\n', (8588, 8600), True, 'import numpy as np\n'), ((8631, 8655), 'numpy.fft.ifft2', 'np.fft.ifft2', (['hff_ishift'], {}), '(hff_ishift)\n', (8643, 8655), True, 'import numpy as np\n'), ((8686, 8702), 'numpy.abs', 'np.abs', (['hff_back'], {}), '(hff_back)\n', (8692, 8702), True, 'import numpy as np\n'), ((8718, 8734), 'numpy.abs', 'np.abs', (['lff_back'], {}), '(lff_back)\n', (8724, 8734), True, 'import numpy as np\n'), ((8795, 8822), 'numpy.percentile', 'np.percentile', (['hff_back', '(99)'], {}), '(hff_back, 99)\n', (8808, 8822), True, 'import numpy as np\n'), ((8861, 8905), 'image_viewing.horizontal_pane', 'horizontal_pane', (['[image, lff_back, hff_back]'], {}), '([image, lff_back, hff_back])\n', (8876, 8905), False, 'from image_viewing import horizontal_pane, overlay_RGB, overlay_RGB_cost\n'), ((9609, 9623), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (9620, 9623), True, 'import numpy as np\n'), ((9995, 10013), 'IPython.display.clear_output', 'clear_output', (['(True)'], {}), '(True)\n', (10007, 10013), False, 'from IPython.display import clear_output, display\n'), ((11922, 11933), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (11930, 11933), True, 'import numpy as np\n'), ((11942, 11956), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (11953, 11956), True, 'import numpy as np\n'), ((12217, 12228), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (12225, 12228), True, 'import numpy as np\n'), ((12237, 12251), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (12248, 12251), True, 'import numpy as np\n'), ((12345, 12381), 'numpy.sum', 'np.sum', (['((images[0] - images[1]) ** 2)'], {}), '((images[0] - images[1]) ** 2)\n', (12351, 12381), True, 'import numpy as np\n'), ((13462, 13492), 'scipy.ndimage.affine_transform', 'affine_transform', (['images[1]', 'T'], {}), '(images[1], T)\n', (13478, 13492), False, 'from scipy.ndimage import affine_transform\n'), ((13574, 13604), 'scipy.ndimage.affine_transform', 'affine_transform', (['images[1]', 'T'], {}), '(images[1], T)\n', (13590, 13604), False, 'from scipy.ndimage import affine_transform\n'), ((1165, 1208), 'matplotlib.use', 'matplotlib.use', (['gui'], {'warn': '(False)', 'force': '(True)'}), '(gui, warn=False, force=True)\n', (1179, 1208), False, 'import matplotlib\n'), ((3898, 3925), 'scipy.ndimage.affine_transform', 'affine_transform', (['image2', 'T'], {}), '(image2, T)\n', (3914, 3925), False, 'from scipy.ndimage import affine_transform\n'), ((4029, 4045), 'ipywidgets.fixed', 'fixed', (['images[0]'], {}), '(images[0])\n', (4034, 4045), False, 'from ipywidgets import interact, interactive, fixed, interact_manual\n'), ((4058, 4074), 'ipywidgets.fixed', 'fixed', (['images[1]'], {}), '(images[1])\n', (4063, 4074), False, 'from ipywidgets import interact, interactive, fixed, interact_manual\n'), ((6086, 6113), 'scipy.ndimage.affine_transform', 'affine_transform', (['image2', 'T'], {}), '(image2, T)\n', (6102, 6113), False, 'from scipy.ndimage import affine_transform\n'), ((6268, 6284), 'ipywidgets.fixed', 'fixed', (['images[0]'], {}), '(images[0])\n', (6273, 6284), False, 'from ipywidgets import interact, interactive, fixed, interact_manual\n'), ((6297, 6313), 'ipywidgets.fixed', 'fixed', (['images[1]'], {}), '(images[1])\n', (6302, 6313), False, 'from ipywidgets import interact, interactive, fixed, interact_manual\n'), ((6378, 6389), 'ipywidgets.fixed', 'fixed', (['cost'], {}), '(cost)\n', (6383, 6389), False, 'from ipywidgets import interact, interactive, fixed, interact_manual\n'), ((6441, 6454), 'ipywidgets.fixed', 'fixed', (['c_funs'], {}), '(c_funs)\n', (6446, 6454), False, 'from ipywidgets import interact, interactive, fixed, interact_manual\n'), ((8143, 8162), 'numpy.array', 'np.array', (['hff.shape'], {}), '(hff.shape)\n', (8151, 8162), True, 'import numpy as np\n'), ((8980, 8996), 'ipywidgets.fixed', 'fixed', (['images[0]'], {}), '(images[0])\n', (8985, 8996), False, 'from ipywidgets import interact, interactive, fixed, interact_manual\n'), ((9472, 9504), 'scipy.ndimage.interpolation.zoom', 'zoom', (['image1', '(1 / level)'], {'order': '(0)'}), '(image1, 1 / level, order=0)\n', (9476, 9504), False, 'from scipy.ndimage.interpolation import zoom\n'), ((9518, 9550), 'scipy.ndimage.interpolation.zoom', 'zoom', (['image2', '(1 / level)'], {'order': '(0)'}), '(image2, 1 / level, order=0)\n', (9522, 9550), False, 'from scipy.ndimage.interpolation import zoom\n'), ((9852, 9930), 'image_viewing.overlay_RGB_cost', 'overlay_RGB_cost', (['images', 'cost_history', 'cost_function', 'cfuncs', 'dx', 'dy', 'history'], {}), '(images, cost_history, cost_function, cfuncs, dx, dy, history)\n', (9868, 9930), False, 'from image_viewing import horizontal_pane, overlay_RGB, overlay_RGB_cost\n'), ((10078, 10094), 'ipywidgets.fixed', 'fixed', (['images[0]'], {}), '(images[0])\n', (10083, 10094), False, 'from ipywidgets import interact, interactive, fixed, interact_manual\n'), ((10107, 10123), 'ipywidgets.fixed', 'fixed', (['images[1]'], {}), '(images[1])\n', (10112, 10123), False, 'from ipywidgets import interact, interactive, fixed, interact_manual\n'), ((10188, 10207), 'ipywidgets.fixed', 'fixed', (['cost_pyramid'], {}), '(cost_pyramid)\n', (10193, 10207), False, 'from ipywidgets import interact, interactive, fixed, interact_manual\n'), ((10259, 10272), 'ipywidgets.fixed', 'fixed', (['c_funs'], {}), '(c_funs)\n', (10264, 10272), False, 'from ipywidgets import interact, interactive, fixed, interact_manual\n'), ((12308, 12331), 'scipy.ndimage.affine_transform', 'affine_transform', (['i2', 'T'], {}), '(i2, T)\n', (12324, 12331), False, 'from scipy.ndimage import affine_transform\n'), ((13117, 13147), 'scipy.ndimage.affine_transform', 'affine_transform', (['images[1]', 'T'], {}), '(images[1], T)\n', (13133, 13147), False, 'from scipy.ndimage import affine_transform\n'), ((13297, 13327), 'scipy.ndimage.affine_transform', 'affine_transform', (['images[1]', 'T'], {}), '(images[1], T)\n', (13313, 13327), False, 'from scipy.ndimage import affine_transform\n'), ((9723, 9755), 'scipy.ndimage.affine_transform', 'affine_transform', (['i2', 'T'], {'order': '(0)'}), '(i2, T, order=0)\n', (9739, 9755), False, 'from scipy.ndimage import affine_transform\n'), ((9789, 9812), 'scipy.ndimage.affine_transform', 'affine_transform', (['i2', 'T'], {}), '(i2, T)\n', (9805, 9812), False, 'from scipy.ndimage import affine_transform\n'), ((12075, 12110), 'numpy.corrcoef', 'np.corrcoef', (['images[0]'], {'y': 'images[1]'}), '(images[0], y=images[1])\n', (12086, 12110), True, 'import numpy as np\n'), ((12023, 12046), 'scipy.ndimage.affine_transform', 'affine_transform', (['i2', 'T'], {}), '(i2, T)\n', (12039, 12046), False, 'from scipy.ndimage import affine_transform\n')]
|
# Python-bioformats is distributed under the GNU General Public
# License, but this file is licensed under the more permissive BSD
# license. See the accompanying file LICENSE for details.
#
# Copyright (c) 2009-2014 Broad Institute
# All rights reserved.
'''formatwriter.py - mechanism to wrap a bioformats WriterWrapper and ImageWriter
The following file formats can be written using Bio-Formats:
- TIFF (uncompressed or LZW)
- OME-TIFF (uncompressed or LZW)
- JPEG
- PNG
- AVI (uncompressed)
- QuickTime (uncompressed is supported natively; additional codecs use QTJava)
- Encapsulated PostScript (EPS)
Support for OME-XML in the near future.
The writer API (see loci.formats.IFormatWriter) is very similar to the reader
API, in that files are written one plane at time (rather than all at once).
All writers allow the output file to be changed before the last plane has
been written. This allows you to write to any number of output files using
the same writer and output settings (compression, frames per second, etc.),
and is especially useful for formats that do not support multiple images per
file.
'''
from __future__ import absolute_import, print_function, unicode_literals
__version__ = "$Revision$"
import numpy as np
import os
import sys
import javabridge as jutil
from .. import bioformats
import javabridge
from ..bioformats import omexml as ome
def write_image(pathname, pixels, pixel_type,
c = 0, z = 0, t = 0,
size_c = 1, size_z = 1, size_t = 1,
channel_names = None):
"""Write the image using bioformats.
:param filename: save to this filename
:param pixels: the image to save
:param pixel_type: save using this pixel type
:param c: the image's channel index
:param z: the image's `z` index
:param t: the image's `t` index
:param size_c: # of channels in the stack
:param size_z: # of z stacks
:param size_t: # of timepoints in the stack
:param channel_names: names of the channels (make up names if not present).
"""
omexml = ome.OMEXML()
omexml.image(0).Name = os.path.split(pathname)[1]
p = omexml.image(0).Pixels
assert isinstance(p, ome.OMEXML.Pixels)
p.SizeX = pixels.shape[1]
p.SizeY = pixels.shape[0]
p.SizeC = size_c
p.SizeT = size_t
p.SizeZ = size_z
p.DimensionOrder = ome.DO_XYCZT
p.PixelType = pixel_type
index = c + size_c * z + size_c * size_z * t
if pixels.ndim == 3:
p.SizeC = pixels.shape[2]
p.Channel(0).SamplesPerPixel = pixels.shape[2]
omexml.structured_annotations.add_original_metadata(
ome.OM_SAMPLES_PER_PIXEL, str(pixels.shape[2]))
elif size_c > 1:
p.channel_count = size_c
pixel_buffer = convert_pixels_to_buffer(pixels, pixel_type)
xml = omexml.to_xml()
script = """
importClass(Packages.loci.formats.services.OMEXMLService,
Packages.loci.common.services.ServiceFactory,
Packages.loci.formats.ImageWriter);
var service = new ServiceFactory().getInstance(OMEXMLService);
var metadata = service.createOMEXMLMetadata(xml);
var writer = new ImageWriter();
writer.setMetadataRetrieve(metadata);
writer.setId(path);
writer.setInterleaved(true);
writer.saveBytes(index, buffer);
writer.close();
"""
jutil.run_script(script,
dict(path=pathname,
xml=xml,
index=index,
buffer=pixel_buffer))
def convert_pixels_to_buffer(pixels, pixel_type):
'''Convert the pixels in the image into a buffer of the right pixel type
pixels - a 2d monochrome or color image
pixel_type - one of the OME pixel types
returns a 1-d byte array
'''
if pixel_type in (ome.PT_UINT8, ome.PT_INT8, ome.PT_BIT):
as_dtype = np.uint8
elif pixel_type in (ome.PT_UINT16, ome.PT_INT16):
as_dtype = "<u2"
elif pixel_type in (ome.PT_UINT32, ome.PT_INT32):
as_dtype = "<u4"
elif pixel_type == ome.PT_FLOAT:
as_dtype = "<f4"
elif pixel_type == ome.PT_DOUBLE:
as_dtype = "<f8"
else:
raise NotImplementedError("Unsupported pixel type: %d" % pixel_type)
buf = np.frombuffer(np.ascontiguousarray(pixels, as_dtype).data, np.uint8)
env = jutil.get_env()
return env.make_byte_array(buf)
def make_iformat_writer_class(class_name):
'''Bind a Java class that implements IFormatWriter to a Python class
Returns a class that implements IFormatWriter through calls to the
implemented class passed in. The returned class can be subclassed to
provide additional bindings.
'''
class IFormatWriter(object):
'''A wrapper for loci.formats.IFormatWriter
See http://hudson.openmicroscopy.org.uk/job/LOCI/javadoc/loci/formats/ImageWriter.html
'''
canDoStacks = jutil.make_method('canDoStacks', '()Z',
'Reports whether the writer can save multiple images to a single file.')
getColorModel = jutil.make_method('getColorModel', '()Ljava/awt/image/ColorModel;',
'Gets the color model.')
getCompression = jutil.make_method('getCompression', '()Ljava/lang/String;',
'Gets the current compression type.')
getCompressionTypes = jutil.make_method('getCompressionTypes', '()[Ljava/lang/String;',
'Gets the available compression types.')
getFramesPerSecond = jutil.make_method('getFramesPerSecond', '()I',
'Gets the frames per second to use when writing.')
getMetadataRetrieve = jutil.make_method('getMetadataRetrieve', '()Lloci/formats/meta/MetadataRetrieve;',
'Retrieves the current metadata retrieval object for this writer.')
getPixelTypes = jutil.make_method('getPixelTypes', '()[I',
'Gets the supported pixel types.')
# getPixelTypes = jutil.make_method('getPixelTypes', '(Ljava/lang/String;)[I',
# 'Gets the supported pixel types for the given codec.')
isInterleaved = jutil.make_method('isInterleaved', '()Z',
'Gets whether or not the channels in an image are interleaved.')
isSupportedType = jutil.make_method('isSupportedType', '(I)Z',
'Checks if the given pixel type is supported.')
saveBytes = jutil.make_method('saveBytes', '([BZ)V',
'Saves the given byte array to the current file.')
saveBytesIB = jutil.make_method('saveBytes', '(I[B)V',
'Saves bytes, first arg is image #')
# saveBytes = jutil.make_method('saveBytes', '([BIZZ)V',
# 'Saves the given byte array to the given series in the current file.')
savePlane = jutil.make_method('savePlane', '(Ljava/lang/Object;Z)V',
'Saves the given image plane to the current file.')
# savePlane = jutil.make_method('savePlane', '(Ljava/lang/Object;IZZ)V',
# 'Saves the given image plane to the given series in the current file.')
setColorModel = jutil.make_method('setColorModel', '(Ljava/awt/image/ColorModel;)V',
'Sets the color model.')
setCompression = jutil.make_method('setCompression', '(Ljava/lang/String;)V',
'Sets the current compression type.')
setFramesPerSecond = jutil.make_method('setFramesPerSecond', '(I)V',
'Sets the frames per second to use when writing.')
setInterleaved = jutil.make_method('setInterleaved', '(Z)V',
'Sets whether or not the channels in an image are interleaved.')
setMetadataRetrieve = jutil.make_method('setMetadataRetrieve', '(Lloci/formats/meta/MetadataRetrieve;)V',
'Sets the metadata retrieval object from which to retrieve standardized metadata.')
setValidBitsPerPixel = jutil.make_method(
'setValidBitsPerPixel', '(I)V',
'Sets the number of valid bits per pixel')
setSeries = jutil.make_method(
'setSeries', '(I)V',
'''Set the series for the image file
series - the zero-based index of the image stack in the file,
for instance in a multi-image tif.''')
return IFormatWriter
def make_image_writer_class():
'''Return an image writer class for the given Java environment'''
env = jutil.get_env()
class_name = 'loci/formats/ImageWriter'
klass = env.find_class(class_name)
base_klass = env.find_class('loci/formats/IFormatWriter')
IFormatWriter = make_iformat_writer_class(class_name)
#
# This uses the writers.txt file from inside the loci_tools.jar
#
class_list = jutil.make_instance("loci/formats/ClassList",
"(Ljava/lang/String;"
"Ljava/lang/Class;" # base
"Ljava/lang/Class;)V", # location in jar
"writers.txt", base_klass, klass)
class ImageWriter(IFormatWriter):
new_fn = jutil.make_new(class_name, '(Lloci/formats/ClassList;)V')
def __init__(self):
self.new_fn(class_list)
setId = jutil.make_method('setId', '(Ljava/lang/String;)V',
'Sets the current file name.')
addStatusListener = jutil.make_method('addStatusListener', '()Lloci/formats/StatusListener;',
'Adds a listener for status update events.')
close = jutil.make_method('close','()V',
'Closes currently open file(s) and frees allocated memory.')
getFormat = jutil.make_method('getFormat', '()Ljava/lang/String;',
'Gets the name of this file format.')
getNativeDataType = jutil.make_method('getNativeDataType', '()Ljava/lang/Class;',
'Returns the native data type of image planes for this reader, as returned by IFormatReader.openPlane(int, int, int, int, int) or IFormatWriter#saveData.')
getStatusListeners = jutil.make_method('getStatusListeners', '()[Lloci/formats/StatusListener;',
'Gets a list of all registered status update listeners.')
getSuffixes = jutil.make_method('getSuffixes', '()Ljava/lang/String;',
'Gets the default file suffixes for this file format.')
getWriter = jutil.make_method('getWriter', '()Lloci/formats/IFormatWriter;',
'Gets the writer used to save the current file.')
# getWriter = jutil.make_method('getWriter', '(Ljava/lang/Class)Lloci/formats/IFormatWriter;',
# 'Gets the file format writer instance matching the given class.')
# getWriter = jutil.make_method('getWriter', '(Ljava/lang/String;)Lloci/formats/IFormatWriter;',
# 'Gets the writer used to save the given file.')
getWriters = jutil.make_method('getWriters', '()[Lloci/formats/IFormatWriter;',
'Gets all constituent file format writers.')
isThisType = jutil.make_method('isThisType', '(Ljava/lang/String;)Z',
'Checks if the given string is a valid filename for this file format.')
removeStatusListener = jutil.make_method('removeStatusListener', '(Lloci/formats/StatusListener;)V',
'Saves the given byte array to the current file.')
return ImageWriter
def make_ome_tiff_writer_class():
'''Return a class that wraps loci.formats.out.OMETiffWriter'''
class_name = 'loci/formats/out/OMETiffWriter'
IFormatWriter = make_iformat_writer_class(class_name)
class OMETiffWriter(IFormatWriter):
def __init__(self):
self.new_fn = jutil.make_new(self.class_name, '()V')
self.setId = jutil.make_method('setId', '(Ljava/lang/String;)V',
'Sets the current file name.')
self.close = jutil.make_method(
'close','()V',
'Closes currently open file(s) and frees allocated memory.')
self.saveBytesIFD = jutil.make_method(
'saveBytes', '(I[BLloci/formats/tiff/IFD;)V',
'''save a byte array to an image channel
index - image index
bytes - byte array to save
ifd - a loci.formats.tiff.IFD instance that gives all of the
IFD values associated with the channel''')
self.new_fn()
return OMETiffWriter
def make_writer_wrapper_class(class_name):
'''Make an ImageWriter wrapper class
class_name - the name of the wrapper class
You can instantiate an instance of the wrapper class like this:
writer = XXX(ImageWriter())
'''
IFormatWriter = make_iformat_writer_class(class_name)
class WriterWrapper(IFormatWriter):
__doc__ = '''A wrapper for %s
See http://hudson.openmicroscopy.org.uk/job/LOCI/javadoc/loci/formats/ImageWriter.html
'''%class_name
new_fn = jutil.make_new(class_name, '(Lloci/formats/IFormatWriter;)V')
def __init__(self, writer):
self.new_fn(writer)
setId = jutil.make_method('setId', '(Ljava/lang/String;)V',
'Sets the current file name.')
return WriterWrapper
def make_format_writer_class(class_name):
'''Make a FormatWriter wrapper class
class_name - the name of a class that implements loci.formats.FormatWriter
Known names in the loci.formats.out package:
APNGWriter, AVIWriter, EPSWriter, ICSWriter, ImageIOWriter,
JPEG2000Writer, JPEGWriter, LegacyQTWriter, OMETiffWriter,
OMEXMLWriter, QTWriter, TiffWriter
'''
new_fn = jutil.make_new(class_name,
'(Ljava/lang/String;Ljava/lang/String;)V')
class FormatWriter(object):
__doc__ = '''A wrapper for %s implementing loci.formats.FormatWriter
See http://hudson.openmicroscopy.org.uk/job/LOCI/javadoc/loci/formats/FormatWriter'''%class_name
def __init__(self):
self.new_fn()
canDoStacks = jutil.make_method('canDoStacks','()Z',
'Reports whether the writer can save multiple images to a single file')
getColorModel = jutil.make_method('getColorModel',
'()Ljava/awt/image/ColorModel;',
'Gets the color model')
getCompression = jutil.make_method('getCompression',
'()Ljava/lang/String;',
'Gets the current compression type')
getCompressionTypes = jutil.make_method('getCompressionTypes',
'()[Ljava/lang/String;',
'Gets the available compression types')
getFramesPerSecond = jutil.make_method('getFramesPerSecond',
'()I', "Gets the frames per second to use when writing")
getMetadataRetrieve = jutil.make_method('getMetadataRetrieve',
'()Lloci/formats/meta/MetadataRetrieve;',
'Retrieves the current metadata retrieval object for this writer.')
getPixelTypes = jutil.make_method('getPixelTypes',
'()[I')
isInterleaved = jutil.make_method('isInterleaved','()Z',
'Gets whether or not the channels in an image are interleaved')
isSupportedType = jutil.make_method('isSupportedType','(I)Z',
'Checks if the given pixel type is supported')
saveBytes = jutil.make_method('saveBytes', '([BZ)V',
'Saves the given byte array to the current file')
setColorModel = jutil.make_method('setColorModel',
'(Ljava/awt/image/ColorModel;)V',
'Sets the color model')
setCompression = jutil.make_method('setCompression',
'(Ljava/lang/String;)V',
'Sets the current compression type')
setFramesPerSecond = jutil.make_method('setFramesPerSecond',
'(I)V',
'Sets the frames per second to use when writing')
setId = jutil.make_method('setId','(Ljava/lang/String;)V',
'Sets the current file name')
setInterleaved = jutil.make_method('setInterleaved', '(Z)V',
'Sets whether or not the channels in an image are interleaved')
setMetadataRetrieve = jutil.make_method('setMetadataRetrieve',
'(Lloci/formats/meta/MetadataRetrieve;)V',
'Sets the metadata retrieval object from which to retrieve standardized metadata')
return FormatWriter
def getRGBColorSpace():
'''Get a Java object that represents an RGB color space
See java.awt.color.ColorSpace: this returns the linear RGB color space
'''
cs_linear_rgb = jutil.get_static_field('java/awt/color/ColorSpace',
'CS_LINEAR_RGB', 'I')
return jutil.static_call('java/awt/color/ColorSpace', 'getInstance',
'(I)Ljava/awt/color/ColorSpace;',
cs_linear_rgb)
def getGrayColorSpace():
'''Get a Java object that represents an RGB color space
See java.awt.color.ColorSpace: this returns the linear RGB color space
'''
cs_gray = jutil.get_static_field('java/awt/color/ColorSpace',
'CS_GRAY', 'I')
return jutil.static_call('java/awt/color/ColorSpace', 'getInstance',
'(I)Ljava/awt/color/ColorSpace;',
cs_gray)
'''Constant for color model transparency indicating bitmask transparency'''
BITMASK = 'BITMASK'
'''Constant for color model transparency indicting an opaque color model'''
OPAQUE = 'OPAQUE'
'''Constant for color model transparency indicating a transparent color model'''
TRANSPARENT = 'TRANSPARENT'
'''Constant for color model transfer type indicating byte per pixel'''
TYPE_BYTE = 'TYPE_BYTE'
'''Constant for color model transfer type indicating unsigned short per pixel'''
TYPE_USHORT = 'TYPE_USHORT'
'''Constant for color model transfer type indicating integer per pixel'''
TYPE_INT = 'TYPE_INT'
def getColorModel(color_space,
has_alpha=False,
is_alpha_premultiplied = False,
transparency = OPAQUE,
transfer_type = TYPE_BYTE):
'''Return a java.awt.image.ColorModel color model
color_space - a java.awt.color.ColorSpace such as returned by
getGrayColorSpace or getRGBColorSpace
has_alpha - True if alpha channel is specified
is_alpha_premultiplied - True if other channel values have already
been reduced by the alpha multiplier, False if the channel values are
independent of the multiplier.
transparency - one of BITMASK, OPAQUE or TRANSPARENT.
transfer_type - one of TYPE_BYTE, TYPE_USHORT, TYPE_INT
'''
jtransparency = jutil.get_static_field('java/awt/Transparency',
transparency,
'I')
jtransfer_type = jutil.get_static_field('java/awt/image/DataBuffer',
transfer_type, 'I')
return jutil.make_instance('java/awt/image/ComponentColorModel',
'(Ljava/awt/color/ColorSpace;ZZII)V',
color_space, has_alpha, is_alpha_premultiplied,
jtransparency, jtransfer_type)
if __name__ == "__main__":
import wx
import matplotlib.backends.backend_wxagg as mmmm
from .. import bioformats
from .formatreader import *
from .metadatatools import *
app = wx.PySimpleApp()
# dlg = wx.FileDialog(None)
# if dlg.ShowModal()==wx.ID_OK:
# filename = dlg.Path
# else:
# app.Exit()
# sys.exit()
filename = '/Users/afraser/Desktop/cpa_example/images/AS_09125_050116000001_A01f00d0.png'
filename = '/Users/afraser/Desktop/wedding/header.jpg'
out_file = '/Users/afraser/Desktop/test_output.avi'
try:
os.remove(out_file)
print('previous output file deleted')
except:
print('no output file to delete')
env = jutil.attach()
ImageReader = make_image_reader_class()
ChannelSeparator = make_reader_wrapper_class("loci/formats/ChannelSeparator")
FormatTools = make_format_tools_class()
# writer testing
ImageWriter = make_image_writer_class()
writer = ImageWriter()
w = 400
h = 400
c = 3
z = 1
t = 4
images = []
for tt in range(t):
images += [(np.random.rand(w, h, c) * 255).astype('uint8')]
imeta = createOMEXMLMetadata()
meta = wrap_imetadata_object(imeta)
meta.createRoot()
meta.setPixelsBigEndian(True, 0, 0)
meta.setPixelsDimensionOrder('XYCZT', 0, 0)
meta.setPixelsPixelType(FormatTools.getPixelTypeString(FormatTools.UINT8), 0, 0)
meta.setPixelsSizeX(w, 0, 0)
meta.setPixelsSizeY(h, 0, 0)
meta.setPixelsSizeC(c, 0, 0)
meta.setPixelsSizeZ(z, 0, 0)
meta.setPixelsSizeT(t, 0, 0)
meta.setLogicalChannelSamplesPerPixel(c, 0, 0)
print('big endian:', meta.getPixelsBigEndian(0, 0))
print('dim order:', meta.getPixelsDimensionOrder(0, 0))
print('pixel type:', meta.getPixelsPixelType(0, 0))
print('size x:', meta.getPixelsSizeX(0, 0))
print('size y:', meta.getPixelsSizeY(0, 0))
print('size c:', meta.getPixelsSizeC(0, 0))
print('size z:', meta.getPixelsSizeZ(0, 0))
print('size t:', meta.getPixelsSizeT(0, 0))
print('samples per pixel:', meta.getLogicalChannelSamplesPerPixel(0, 0))
writer.setMetadataRetrieve(meta)
writer.setId(out_file)
for image in images:
if len(image.shape)==3 and image.shape[2] == 3:
save_im = np.array([image[:,:,0], image[:,:,1], image[:,:,2]]).astype(np.uint8).flatten()
else:
save_im = image.astype(np.uint8).flatten()
writer.saveBytes(env.make_byte_array(save_im), (image is images[-1]))
writer.close()
print('Done writing image :)')
# import PIL.Image as Image
# im = Image.open(out_file, 'r')
# im.show()
jutil.detach()
app.MainLoop()
|
[
"os.remove",
"javabridge.static_call",
"javabridge.get_env",
"javabridge.get_static_field",
"numpy.random.rand",
"javabridge.make_new",
"javabridge.make_method",
"javabridge.make_instance",
"numpy.array",
"wx.PySimpleApp",
"os.path.split",
"numpy.ascontiguousarray",
"javabridge.detach",
"javabridge.attach"
] |
[((4342, 4357), 'javabridge.get_env', 'jutil.get_env', ([], {}), '()\n', (4355, 4357), True, 'import javabridge as jutil\n'), ((8923, 8938), 'javabridge.get_env', 'jutil.get_env', ([], {}), '()\n', (8936, 8938), True, 'import javabridge as jutil\n'), ((9239, 9385), 'javabridge.make_instance', 'jutil.make_instance', (['"""loci/formats/ClassList"""', '"""(Ljava/lang/String;Ljava/lang/Class;Ljava/lang/Class;)V"""', '"""writers.txt"""', 'base_klass', 'klass'], {}), "('loci/formats/ClassList',\n '(Ljava/lang/String;Ljava/lang/Class;Ljava/lang/Class;)V',\n 'writers.txt', base_klass, klass)\n", (9258, 9385), True, 'import javabridge as jutil\n'), ((14552, 14621), 'javabridge.make_new', 'jutil.make_new', (['class_name', '"""(Ljava/lang/String;Ljava/lang/String;)V"""'], {}), "(class_name, '(Ljava/lang/String;Ljava/lang/String;)V')\n", (14566, 14621), True, 'import javabridge as jutil\n'), ((18217, 18290), 'javabridge.get_static_field', 'jutil.get_static_field', (['"""java/awt/color/ColorSpace"""', '"""CS_LINEAR_RGB"""', '"""I"""'], {}), "('java/awt/color/ColorSpace', 'CS_LINEAR_RGB', 'I')\n", (18239, 18290), True, 'import javabridge as jutil\n'), ((18345, 18459), 'javabridge.static_call', 'jutil.static_call', (['"""java/awt/color/ColorSpace"""', '"""getInstance"""', '"""(I)Ljava/awt/color/ColorSpace;"""', 'cs_linear_rgb'], {}), "('java/awt/color/ColorSpace', 'getInstance',\n '(I)Ljava/awt/color/ColorSpace;', cs_linear_rgb)\n", (18362, 18459), True, 'import javabridge as jutil\n'), ((18698, 18765), 'javabridge.get_static_field', 'jutil.get_static_field', (['"""java/awt/color/ColorSpace"""', '"""CS_GRAY"""', '"""I"""'], {}), "('java/awt/color/ColorSpace', 'CS_GRAY', 'I')\n", (18720, 18765), True, 'import javabridge as jutil\n'), ((18820, 18928), 'javabridge.static_call', 'jutil.static_call', (['"""java/awt/color/ColorSpace"""', '"""getInstance"""', '"""(I)Ljava/awt/color/ColorSpace;"""', 'cs_gray'], {}), "('java/awt/color/ColorSpace', 'getInstance',\n '(I)Ljava/awt/color/ColorSpace;', cs_gray)\n", (18837, 18928), True, 'import javabridge as jutil\n'), ((20331, 20397), 'javabridge.get_static_field', 'jutil.get_static_field', (['"""java/awt/Transparency"""', 'transparency', '"""I"""'], {}), "('java/awt/Transparency', transparency, 'I')\n", (20353, 20397), True, 'import javabridge as jutil\n'), ((20505, 20576), 'javabridge.get_static_field', 'jutil.get_static_field', (['"""java/awt/image/DataBuffer"""', 'transfer_type', '"""I"""'], {}), "('java/awt/image/DataBuffer', transfer_type, 'I')\n", (20527, 20576), True, 'import javabridge as jutil\n'), ((20632, 20814), 'javabridge.make_instance', 'jutil.make_instance', (['"""java/awt/image/ComponentColorModel"""', '"""(Ljava/awt/color/ColorSpace;ZZII)V"""', 'color_space', 'has_alpha', 'is_alpha_premultiplied', 'jtransparency', 'jtransfer_type'], {}), "('java/awt/image/ComponentColorModel',\n '(Ljava/awt/color/ColorSpace;ZZII)V', color_space, has_alpha,\n is_alpha_premultiplied, jtransparency, jtransfer_type)\n", (20651, 20814), True, 'import javabridge as jutil\n'), ((21100, 21116), 'wx.PySimpleApp', 'wx.PySimpleApp', ([], {}), '()\n', (21114, 21116), False, 'import wx\n'), ((21623, 21637), 'javabridge.attach', 'jutil.attach', ([], {}), '()\n', (21635, 21637), True, 'import javabridge as jutil\n'), ((23578, 23592), 'javabridge.detach', 'jutil.detach', ([], {}), '()\n', (23590, 23592), True, 'import javabridge as jutil\n'), ((2112, 2135), 'os.path.split', 'os.path.split', (['pathname'], {}), '(pathname)\n', (2125, 2135), False, 'import os\n'), ((4912, 5028), 'javabridge.make_method', 'jutil.make_method', (['"""canDoStacks"""', '"""()Z"""', '"""Reports whether the writer can save multiple images to a single file."""'], {}), "('canDoStacks', '()Z',\n 'Reports whether the writer can save multiple images to a single file.')\n", (4929, 5028), True, 'import javabridge as jutil\n'), ((5089, 5185), 'javabridge.make_method', 'jutil.make_method', (['"""getColorModel"""', '"""()Ljava/awt/image/ColorModel;"""', '"""Gets the color model."""'], {}), "('getColorModel', '()Ljava/awt/image/ColorModel;',\n 'Gets the color model.')\n", (5106, 5185), True, 'import javabridge as jutil\n'), ((5249, 5350), 'javabridge.make_method', 'jutil.make_method', (['"""getCompression"""', '"""()Ljava/lang/String;"""', '"""Gets the current compression type."""'], {}), "('getCompression', '()Ljava/lang/String;',\n 'Gets the current compression type.')\n", (5266, 5350), True, 'import javabridge as jutil\n'), ((5420, 5530), 'javabridge.make_method', 'jutil.make_method', (['"""getCompressionTypes"""', '"""()[Ljava/lang/String;"""', '"""Gets the available compression types."""'], {}), "('getCompressionTypes', '()[Ljava/lang/String;',\n 'Gets the available compression types.')\n", (5437, 5530), True, 'import javabridge as jutil\n'), ((5604, 5705), 'javabridge.make_method', 'jutil.make_method', (['"""getFramesPerSecond"""', '"""()I"""', '"""Gets the frames per second to use when writing."""'], {}), "('getFramesPerSecond', '()I',\n 'Gets the frames per second to use when writing.')\n", (5621, 5705), True, 'import javabridge as jutil\n'), ((5779, 5937), 'javabridge.make_method', 'jutil.make_method', (['"""getMetadataRetrieve"""', '"""()Lloci/formats/meta/MetadataRetrieve;"""', '"""Retrieves the current metadata retrieval object for this writer."""'], {}), "('getMetadataRetrieve',\n '()Lloci/formats/meta/MetadataRetrieve;',\n 'Retrieves the current metadata retrieval object for this writer.')\n", (5796, 5937), True, 'import javabridge as jutil\n'), ((6002, 6079), 'javabridge.make_method', 'jutil.make_method', (['"""getPixelTypes"""', '"""()[I"""', '"""Gets the supported pixel types."""'], {}), "('getPixelTypes', '()[I', 'Gets the supported pixel types.')\n", (6019, 6079), True, 'import javabridge as jutil\n'), ((6330, 6440), 'javabridge.make_method', 'jutil.make_method', (['"""isInterleaved"""', '"""()Z"""', '"""Gets whether or not the channels in an image are interleaved."""'], {}), "('isInterleaved', '()Z',\n 'Gets whether or not the channels in an image are interleaved.')\n", (6347, 6440), True, 'import javabridge as jutil\n'), ((6505, 6601), 'javabridge.make_method', 'jutil.make_method', (['"""isSupportedType"""', '"""(I)Z"""', '"""Checks if the given pixel type is supported."""'], {}), "('isSupportedType', '(I)Z',\n 'Checks if the given pixel type is supported.')\n", (6522, 6601), True, 'import javabridge as jutil\n'), ((6662, 6757), 'javabridge.make_method', 'jutil.make_method', (['"""saveBytes"""', '"""([BZ)V"""', '"""Saves the given byte array to the current file."""'], {}), "('saveBytes', '([BZ)V',\n 'Saves the given byte array to the current file.')\n", (6679, 6757), True, 'import javabridge as jutil\n'), ((6814, 6891), 'javabridge.make_method', 'jutil.make_method', (['"""saveBytes"""', '"""(I[B)V"""', '"""Saves bytes, first arg is image #"""'], {}), "('saveBytes', '(I[B)V', 'Saves bytes, first arg is image #')\n", (6831, 6891), True, 'import javabridge as jutil\n'), ((7126, 7238), 'javabridge.make_method', 'jutil.make_method', (['"""savePlane"""', '"""(Ljava/lang/Object;Z)V"""', '"""Saves the given image plane to the current file."""'], {}), "('savePlane', '(Ljava/lang/Object;Z)V',\n 'Saves the given image plane to the current file.')\n", (7143, 7238), True, 'import javabridge as jutil\n'), ((7488, 7585), 'javabridge.make_method', 'jutil.make_method', (['"""setColorModel"""', '"""(Ljava/awt/image/ColorModel;)V"""', '"""Sets the color model."""'], {}), "('setColorModel', '(Ljava/awt/image/ColorModel;)V',\n 'Sets the color model.')\n", (7505, 7585), True, 'import javabridge as jutil\n'), ((7649, 7751), 'javabridge.make_method', 'jutil.make_method', (['"""setCompression"""', '"""(Ljava/lang/String;)V"""', '"""Sets the current compression type."""'], {}), "('setCompression', '(Ljava/lang/String;)V',\n 'Sets the current compression type.')\n", (7666, 7751), True, 'import javabridge as jutil\n'), ((7820, 7922), 'javabridge.make_method', 'jutil.make_method', (['"""setFramesPerSecond"""', '"""(I)V"""', '"""Sets the frames per second to use when writing."""'], {}), "('setFramesPerSecond', '(I)V',\n 'Sets the frames per second to use when writing.')\n", (7837, 7922), True, 'import javabridge as jutil\n'), ((7991, 8103), 'javabridge.make_method', 'jutil.make_method', (['"""setInterleaved"""', '"""(Z)V"""', '"""Sets whether or not the channels in an image are interleaved."""'], {}), "('setInterleaved', '(Z)V',\n 'Sets whether or not the channels in an image are interleaved.')\n", (8008, 8103), True, 'import javabridge as jutil\n'), ((8173, 8353), 'javabridge.make_method', 'jutil.make_method', (['"""setMetadataRetrieve"""', '"""(Lloci/formats/meta/MetadataRetrieve;)V"""', '"""Sets the metadata retrieval object from which to retrieve standardized metadata."""'], {}), "('setMetadataRetrieve',\n '(Lloci/formats/meta/MetadataRetrieve;)V',\n 'Sets the metadata retrieval object from which to retrieve standardized metadata.'\n )\n", (8190, 8353), True, 'import javabridge as jutil\n'), ((8420, 8516), 'javabridge.make_method', 'jutil.make_method', (['"""setValidBitsPerPixel"""', '"""(I)V"""', '"""Sets the number of valid bits per pixel"""'], {}), "('setValidBitsPerPixel', '(I)V',\n 'Sets the number of valid bits per pixel')\n", (8437, 8516), True, 'import javabridge as jutil\n'), ((8558, 8768), 'javabridge.make_method', 'jutil.make_method', (['"""setSeries"""', '"""(I)V"""', '"""Set the series for the image file\n\n series - the zero-based index of the image stack in the file,\n for instance in a multi-image tif."""'], {}), '(\'setSeries\', \'(I)V\',\n """Set the series for the image file\n\n series - the zero-based index of the image stack in the file,\n for instance in a multi-image tif."""\n )\n', (8575, 8768), True, 'import javabridge as jutil\n'), ((9612, 9669), 'javabridge.make_new', 'jutil.make_new', (['class_name', '"""(Lloci/formats/ClassList;)V"""'], {}), "(class_name, '(Lloci/formats/ClassList;)V')\n", (9626, 9669), True, 'import javabridge as jutil\n'), ((9751, 9837), 'javabridge.make_method', 'jutil.make_method', (['"""setId"""', '"""(Ljava/lang/String;)V"""', '"""Sets the current file name."""'], {}), "('setId', '(Ljava/lang/String;)V',\n 'Sets the current file name.')\n", (9768, 9837), True, 'import javabridge as jutil\n'), ((9896, 10018), 'javabridge.make_method', 'jutil.make_method', (['"""addStatusListener"""', '"""()Lloci/formats/StatusListener;"""', '"""Adds a listener for status update events."""'], {}), "('addStatusListener', '()Lloci/formats/StatusListener;',\n 'Adds a listener for status update events.')\n", (9913, 10018), True, 'import javabridge as jutil\n'), ((10077, 10175), 'javabridge.make_method', 'jutil.make_method', (['"""close"""', '"""()V"""', '"""Closes currently open file(s) and frees allocated memory."""'], {}), "('close', '()V',\n 'Closes currently open file(s) and frees allocated memory.')\n", (10094, 10175), True, 'import javabridge as jutil\n'), ((10225, 10321), 'javabridge.make_method', 'jutil.make_method', (['"""getFormat"""', '"""()Ljava/lang/String;"""', '"""Gets the name of this file format."""'], {}), "('getFormat', '()Ljava/lang/String;',\n 'Gets the name of this file format.')\n", (10242, 10321), True, 'import javabridge as jutil\n'), ((10384, 10610), 'javabridge.make_method', 'jutil.make_method', (['"""getNativeDataType"""', '"""()Ljava/lang/Class;"""', '"""Returns the native data type of image planes for this reader, as returned by IFormatReader.openPlane(int, int, int, int, int) or IFormatWriter#saveData."""'], {}), "('getNativeDataType', '()Ljava/lang/Class;',\n 'Returns the native data type of image planes for this reader, as returned by IFormatReader.openPlane(int, int, int, int, int) or IFormatWriter#saveData.'\n )\n", (10401, 10610), True, 'import javabridge as jutil\n'), ((10677, 10814), 'javabridge.make_method', 'jutil.make_method', (['"""getStatusListeners"""', '"""()[Lloci/formats/StatusListener;"""', '"""Gets a list of all registered status update listeners."""'], {}), "('getStatusListeners', '()[Lloci/formats/StatusListener;',\n 'Gets a list of all registered status update listeners.')\n", (10694, 10814), True, 'import javabridge as jutil\n'), ((10880, 10996), 'javabridge.make_method', 'jutil.make_method', (['"""getSuffixes"""', '"""()Ljava/lang/String;"""', '"""Gets the default file suffixes for this file format."""'], {}), "('getSuffixes', '()Ljava/lang/String;',\n 'Gets the default file suffixes for this file format.')\n", (10897, 10996), True, 'import javabridge as jutil\n'), ((11053, 11171), 'javabridge.make_method', 'jutil.make_method', (['"""getWriter"""', '"""()Lloci/formats/IFormatWriter;"""', '"""Gets the writer used to save the current file."""'], {}), "('getWriter', '()Lloci/formats/IFormatWriter;',\n 'Gets the writer used to save the current file.')\n", (11070, 11171), True, 'import javabridge as jutil\n'), ((11625, 11740), 'javabridge.make_method', 'jutil.make_method', (['"""getWriters"""', '"""()[Lloci/formats/IFormatWriter;"""', '"""Gets all constituent file format writers."""'], {}), "('getWriters', '()[Lloci/formats/IFormatWriter;',\n 'Gets all constituent file format writers.')\n", (11642, 11740), True, 'import javabridge as jutil\n'), ((11797, 11929), 'javabridge.make_method', 'jutil.make_method', (['"""isThisType"""', '"""(Ljava/lang/String;)Z"""', '"""Checks if the given string is a valid filename for this file format."""'], {}), "('isThisType', '(Ljava/lang/String;)Z',\n 'Checks if the given string is a valid filename for this file format.')\n", (11814, 11929), True, 'import javabridge as jutil\n'), ((11996, 12132), 'javabridge.make_method', 'jutil.make_method', (['"""removeStatusListener"""', '"""(Lloci/formats/StatusListener;)V"""', '"""Saves the given byte array to the current file."""'], {}), "('removeStatusListener',\n '(Lloci/formats/StatusListener;)V',\n 'Saves the given byte array to the current file.')\n", (12013, 12132), True, 'import javabridge as jutil\n'), ((13798, 13859), 'javabridge.make_new', 'jutil.make_new', (['class_name', '"""(Lloci/formats/IFormatWriter;)V"""'], {}), "(class_name, '(Lloci/formats/IFormatWriter;)V')\n", (13812, 13859), True, 'import javabridge as jutil\n'), ((13945, 14031), 'javabridge.make_method', 'jutil.make_method', (['"""setId"""', '"""(Ljava/lang/String;)V"""', '"""Sets the current file name."""'], {}), "('setId', '(Ljava/lang/String;)V',\n 'Sets the current file name.')\n", (13962, 14031), True, 'import javabridge as jutil\n'), ((14941, 15056), 'javabridge.make_method', 'jutil.make_method', (['"""canDoStacks"""', '"""()Z"""', '"""Reports whether the writer can save multiple images to a single file"""'], {}), "('canDoStacks', '()Z',\n 'Reports whether the writer can save multiple images to a single file')\n", (14958, 15056), True, 'import javabridge as jutil\n'), ((15116, 15211), 'javabridge.make_method', 'jutil.make_method', (['"""getColorModel"""', '"""()Ljava/awt/image/ColorModel;"""', '"""Gets the color model"""'], {}), "('getColorModel', '()Ljava/awt/image/ColorModel;',\n 'Gets the color model')\n", (15133, 15211), True, 'import javabridge as jutil\n'), ((15317, 15417), 'javabridge.make_method', 'jutil.make_method', (['"""getCompression"""', '"""()Ljava/lang/String;"""', '"""Gets the current compression type"""'], {}), "('getCompression', '()Ljava/lang/String;',\n 'Gets the current compression type')\n", (15334, 15417), True, 'import javabridge as jutil\n'), ((15530, 15639), 'javabridge.make_method', 'jutil.make_method', (['"""getCompressionTypes"""', '"""()[Ljava/lang/String;"""', '"""Gets the available compression types"""'], {}), "('getCompressionTypes', '()[Ljava/lang/String;',\n 'Gets the available compression types')\n", (15547, 15639), True, 'import javabridge as jutil\n'), ((15761, 15861), 'javabridge.make_method', 'jutil.make_method', (['"""getFramesPerSecond"""', '"""()I"""', '"""Gets the frames per second to use when writing"""'], {}), "('getFramesPerSecond', '()I',\n 'Gets the frames per second to use when writing')\n", (15778, 15861), True, 'import javabridge as jutil\n'), ((15935, 16093), 'javabridge.make_method', 'jutil.make_method', (['"""getMetadataRetrieve"""', '"""()Lloci/formats/meta/MetadataRetrieve;"""', '"""Retrieves the current metadata retrieval object for this writer."""'], {}), "('getMetadataRetrieve',\n '()Lloci/formats/meta/MetadataRetrieve;',\n 'Retrieves the current metadata retrieval object for this writer.')\n", (15952, 16093), True, 'import javabridge as jutil\n'), ((16207, 16249), 'javabridge.make_method', 'jutil.make_method', (['"""getPixelTypes"""', '"""()[I"""'], {}), "('getPixelTypes', '()[I')\n", (16224, 16249), True, 'import javabridge as jutil\n'), ((16316, 16425), 'javabridge.make_method', 'jutil.make_method', (['"""isInterleaved"""', '"""()Z"""', '"""Gets whether or not the channels in an image are interleaved"""'], {}), "('isInterleaved', '()Z',\n 'Gets whether or not the channels in an image are interleaved')\n", (16333, 16425), True, 'import javabridge as jutil\n'), ((16489, 16584), 'javabridge.make_method', 'jutil.make_method', (['"""isSupportedType"""', '"""(I)Z"""', '"""Checks if the given pixel type is supported"""'], {}), "('isSupportedType', '(I)Z',\n 'Checks if the given pixel type is supported')\n", (16506, 16584), True, 'import javabridge as jutil\n'), ((16644, 16738), 'javabridge.make_method', 'jutil.make_method', (['"""saveBytes"""', '"""([BZ)V"""', '"""Saves the given byte array to the current file"""'], {}), "('saveBytes', '([BZ)V',\n 'Saves the given byte array to the current file')\n", (16661, 16738), True, 'import javabridge as jutil\n'), ((16797, 16893), 'javabridge.make_method', 'jutil.make_method', (['"""setColorModel"""', '"""(Ljava/awt/image/ColorModel;)V"""', '"""Sets the color model"""'], {}), "('setColorModel', '(Ljava/awt/image/ColorModel;)V',\n 'Sets the color model')\n", (16814, 16893), True, 'import javabridge as jutil\n'), ((16999, 17100), 'javabridge.make_method', 'jutil.make_method', (['"""setCompression"""', '"""(Ljava/lang/String;)V"""', '"""Sets the current compression type"""'], {}), "('setCompression', '(Ljava/lang/String;)V',\n 'Sets the current compression type')\n", (17016, 17100), True, 'import javabridge as jutil\n'), ((17212, 17313), 'javabridge.make_method', 'jutil.make_method', (['"""setFramesPerSecond"""', '"""(I)V"""', '"""Sets the frames per second to use when writing"""'], {}), "('setFramesPerSecond', '(I)V',\n 'Sets the frames per second to use when writing')\n", (17229, 17313), True, 'import javabridge as jutil\n'), ((17420, 17505), 'javabridge.make_method', 'jutil.make_method', (['"""setId"""', '"""(Ljava/lang/String;)V"""', '"""Sets the current file name"""'], {}), "('setId', '(Ljava/lang/String;)V',\n 'Sets the current file name')\n", (17437, 17505), True, 'import javabridge as jutil\n'), ((17560, 17671), 'javabridge.make_method', 'jutil.make_method', (['"""setInterleaved"""', '"""(Z)V"""', '"""Sets whether or not the channels in an image are interleaved"""'], {}), "('setInterleaved', '(Z)V',\n 'Sets whether or not the channels in an image are interleaved')\n", (17577, 17671), True, 'import javabridge as jutil\n'), ((17741, 17920), 'javabridge.make_method', 'jutil.make_method', (['"""setMetadataRetrieve"""', '"""(Lloci/formats/meta/MetadataRetrieve;)V"""', '"""Sets the metadata retrieval object from which to retrieve standardized metadata"""'], {}), "('setMetadataRetrieve',\n '(Lloci/formats/meta/MetadataRetrieve;)V',\n 'Sets the metadata retrieval object from which to retrieve standardized metadata'\n )\n", (17758, 17920), True, 'import javabridge as jutil\n'), ((21492, 21511), 'os.remove', 'os.remove', (['out_file'], {}), '(out_file)\n', (21501, 21511), False, 'import os\n'), ((4277, 4315), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['pixels', 'as_dtype'], {}), '(pixels, as_dtype)\n', (4297, 4315), True, 'import numpy as np\n'), ((12503, 12541), 'javabridge.make_new', 'jutil.make_new', (['self.class_name', '"""()V"""'], {}), "(self.class_name, '()V')\n", (12517, 12541), True, 'import javabridge as jutil\n'), ((12567, 12653), 'javabridge.make_method', 'jutil.make_method', (['"""setId"""', '"""(Ljava/lang/String;)V"""', '"""Sets the current file name."""'], {}), "('setId', '(Ljava/lang/String;)V',\n 'Sets the current file name.')\n", (12584, 12653), True, 'import javabridge as jutil\n'), ((12718, 12816), 'javabridge.make_method', 'jutil.make_method', (['"""close"""', '"""()V"""', '"""Closes currently open file(s) and frees allocated memory."""'], {}), "('close', '()V',\n 'Closes currently open file(s) and frees allocated memory.')\n", (12735, 12816), True, 'import javabridge as jutil\n'), ((12877, 13206), 'javabridge.make_method', 'jutil.make_method', (['"""saveBytes"""', '"""(I[BLloci/formats/tiff/IFD;)V"""', '"""save a byte array to an image channel\n\n index - image index\n bytes - byte array to save\n ifd - a loci.formats.tiff.IFD instance that gives all of the\n IFD values associated with the channel"""'], {}), '(\'saveBytes\', \'(I[BLloci/formats/tiff/IFD;)V\',\n """save a byte array to an image channel\n\n index - image index\n bytes - byte array to save\n ifd - a loci.formats.tiff.IFD instance that gives all of the\n IFD values associated with the channel"""\n )\n', (12894, 13206), True, 'import javabridge as jutil\n'), ((22016, 22039), 'numpy.random.rand', 'np.random.rand', (['w', 'h', 'c'], {}), '(w, h, c)\n', (22030, 22039), True, 'import numpy as np\n'), ((23209, 23267), 'numpy.array', 'np.array', (['[image[:, :, 0], image[:, :, 1], image[:, :, 2]]'], {}), '([image[:, :, 0], image[:, :, 1], image[:, :, 2]])\n', (23217, 23267), True, 'import numpy as np\n')]
|
# Copyright 2016 <NAME>
#
# 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.
# https://github.com/kmbnw/rank_metrics/blob/master/python/ndcg.py
from __future__ import absolute_import, annotations
import numpy as np
"""
Implementation of normalized discounted cumulative gain.
Handy for testing ranking algorithms.
https://en.wikipedia.org/wiki/Discounted_cumulative_gain
"""
def cum_gain(relevance):
"""
Calculate cumulative gain.
This ignores the position of a result, but may still be generally useful.
@param relevance: Graded relevances of the results.
@type relevance: C{seq} or C{numpy.array}
"""
if relevance is None or len(relevance) < 1:
return 0.0
return np.asarray(relevance).sum()
def dcg(relevance, alternate=True):
"""
Calculate discounted cumulative gain.
@param relevance: Graded and ordered relevances of the results.
@type relevance: C{seq} or C{numpy.array}
@param alternate: True to use the alternate scoring (intended to
place more emphasis on relevant results).
@type alternate: C{bool}
"""
if relevance is None or len(relevance) < 1:
return 0.0
rel = np.asarray(relevance)
p = len(rel)
if alternate:
# from wikipedia: "An alternative formulation of
# DCG[5] places stronger emphasis on retrieving relevant documents"
log2i = np.log2(np.asarray(range(1, p + 1)) + 1)
return ((np.power(2, rel) - 1) / log2i).sum()
else:
log2i = np.log2(range(2, p + 1))
return rel[0] + (rel[1:] / log2i).sum()
def idcg(relevance, alternate=True):
"""
Calculate ideal discounted cumulative gain (maximum possible DCG).
@param relevance: Graded and ordered relevances of the results.
@type relevance: C{seq} or C{numpy.array}
@param alternate: True to use the alternate scoring (intended to
place more emphasis on relevant results).
@type alternate: C{bool}
"""
if relevance is None or len(relevance) < 1:
return 0.0
# guard copy before sort
rel = np.asarray(relevance).copy()
rel.sort()
return dcg(rel[::-1], alternate)
def ndcg(relevance, nranks, alternate=True):
"""
Calculate normalized discounted cumulative gain.
@param relevance: Graded and ordered relevances of the results.
@type relevance: C{seq} or C{numpy.array}
@param nranks: Number of ranks to use when calculating NDCG.
Will be used to rightpad with zeros if len(relevance) is less
than nranks
@type nranks: C{int}
@param alternate: True to use the alternate scoring (intended to
place more emphasis on relevant results).
@type alternate: C{bool}
"""
if relevance is None or len(relevance) < 1:
return 0.0
if nranks < 1:
raise Exception("nranks < 1")
rel = np.asarray(relevance)
pad = max(0, nranks - len(rel))
# pad could be zero in which case this will no-op
rel = np.pad(rel, (0, pad), "constant")
# now slice downto nranks
rel = rel[0 : min(nranks, len(rel))]
ideal_dcg = idcg(rel, alternate)
if ideal_dcg == 0:
return 0.0
return dcg(rel, alternate) / ideal_dcg
|
[
"numpy.pad",
"numpy.power",
"numpy.asarray"
] |
[((1683, 1704), 'numpy.asarray', 'np.asarray', (['relevance'], {}), '(relevance)\n', (1693, 1704), True, 'import numpy as np\n'), ((3342, 3363), 'numpy.asarray', 'np.asarray', (['relevance'], {}), '(relevance)\n', (3352, 3363), True, 'import numpy as np\n'), ((3465, 3498), 'numpy.pad', 'np.pad', (['rel', '(0, pad)', '"""constant"""'], {}), "(rel, (0, pad), 'constant')\n", (3471, 3498), True, 'import numpy as np\n'), ((1221, 1242), 'numpy.asarray', 'np.asarray', (['relevance'], {}), '(relevance)\n', (1231, 1242), True, 'import numpy as np\n'), ((2578, 2599), 'numpy.asarray', 'np.asarray', (['relevance'], {}), '(relevance)\n', (2588, 2599), True, 'import numpy as np\n'), ((1949, 1965), 'numpy.power', 'np.power', (['(2)', 'rel'], {}), '(2, rel)\n', (1957, 1965), True, 'import numpy as np\n')]
|
import nerdle_cfg
import re
import luigi
import d6tflow
import itertools
import pandas as pd
import numpy as np
#helper functions
def check_len_int(nerdle):
nerdle_str = ''.join(nerdle)
try:
return all(len(x)==len(str(int(x))) for x in re.split('\+|\-|\*|\/|==',nerdle_str))
except:
return False
def rt_is_num(nerdle):
rt_arr = nerdle[np.where(np.array(nerdle)=='==')[0][0]+1:]
test_str = ''.join(rt_arr)
return test_str.isnumeric()
def join_elems_of_tups(list_o_tups):
return list(map(lambda x: ''.join(x),list_o_tups))
def test_eval(nerdle):
test_str = ''.join(nerdle)
try:
return eval(test_str)
except:
return False
class buildNerdles(d6tflow.tasks.TaskPqPandas):
nerdle_len = luigi.IntParameter()
def run(self):
nerdle_len = self.nerdle_len
nerdles = list(itertools.combinations_with_replacement(nerdle_cfg.nerd_list,nerdle_len))
#TODO: Optimize second list comprehension using filter if possible
nerdles = list(filter(
lambda nerdle: ('==' in nerdle)&
bool(any(i in nerdle for i in [x for x in nerdle_cfg.nerd_op_list if x!="=="])),nerdles))
nerdle_ser = pd.Series(nerdles)
nerdle_df = pd.DataFrame(nerdle_ser)
nerdle_df.columns=['nerdle_combinations']
#for each nerdle combination create permutations
nerdle_df['perms'] = nerdle_df['nerdle_combinations'].apply(itertools.permutations,nerdle_len)
# can't start or end with an equals sign and turns permutation tuples into a list
nerdle_df['perm_red_stend_equal'] = nerdle_df['perms'].apply(lambda y: filter(lambda x:(list(x)[0]!='==')&(list(x)[-1]!='=='),y))
# equal sign appears only once
nerdle_df['perm_equal_once'] = nerdle_df['perm_red_stend_equal'].apply(lambda y: filter(lambda x: x.count('==')==1,y))
# elements to the right of the equal sign must be a number
nerdle_df['right_equal_must_be_number'] = nerdle_df['perm_equal_once'].apply(lambda y: filter(lambda x: rt_is_num(x),y))
#length of string has to be 9
nerdle_df['len_check'] = nerdle_df['right_equal_must_be_number'].apply(lambda y: filter(lambda x: len(x)==nerdle_len,y))
#check that non operater numbers are of proper length
nerdle_df['non_op_num_check'] = nerdle_df['len_check'].apply(lambda y: filter(lambda x: check_len_int(x),y))
#check that string evals properly
nerdle_df['eval_check'] = nerdle_df['non_op_num_check'].apply(lambda y: filter(lambda x: test_eval(x),y))
self.save(nerdle_df)
|
[
"pandas.DataFrame",
"re.split",
"itertools.combinations_with_replacement",
"numpy.array",
"pandas.Series",
"luigi.IntParameter"
] |
[((762, 782), 'luigi.IntParameter', 'luigi.IntParameter', ([], {}), '()\n', (780, 782), False, 'import luigi\n'), ((1223, 1241), 'pandas.Series', 'pd.Series', (['nerdles'], {}), '(nerdles)\n', (1232, 1241), True, 'import pandas as pd\n'), ((1262, 1286), 'pandas.DataFrame', 'pd.DataFrame', (['nerdle_ser'], {}), '(nerdle_ser)\n', (1274, 1286), True, 'import pandas as pd\n'), ((873, 946), 'itertools.combinations_with_replacement', 'itertools.combinations_with_replacement', (['nerdle_cfg.nerd_list', 'nerdle_len'], {}), '(nerdle_cfg.nerd_list, nerdle_len)\n', (912, 946), False, 'import itertools\n'), ((254, 296), 're.split', 're.split', (['"""\\\\+|\\\\-|\\\\*|\\\\/|=="""', 'nerdle_str'], {}), "('\\\\+|\\\\-|\\\\*|\\\\/|==', nerdle_str)\n", (262, 296), False, 'import re\n'), ((379, 395), 'numpy.array', 'np.array', (['nerdle'], {}), '(nerdle)\n', (387, 395), True, 'import numpy as np\n')]
|
from ..helpers import eos
from ..helpers import alfaFunctions
from ..helpers.eosHelpers import A_fun, B_fun, getCubicCoefficients, getMixFugacity,getMixFugacityCoef, dAdT_fun
from ..solvers.cubicSolver import cubic_solver
from ..helpers import temperatureCorrelations as tempCorr
from ..helpers import mixing_rules
from numpy import log, exp, sqrt,absolute, array,sum
from scipy.optimize import fsolve, newton, root
from scipy.integrate import quad
def solve_eos(t,p,tc,pc,acentric,liq_compositions,vap_compositions,kij,method='pr',alfa_function='alfa_peng_robinson',mixing_rule='van_der_waals',diagram=False,properties=False,heat_capacities=None):
# Vectorization
tc = array(tc)
pc= array(pc)
acentric = array(acentric)
liq_compositions=array(liq_compositions)
vap_compositions = array(vap_compositions)
kij = array(kij)
# Method selection
eos_fun = eos.selector(method)
u,w,omega_a,omega_b,L = eos_fun()
# Alfa function selection
alfa_fun = alfaFunctions.selector(alfa_function)
alfa= alfa_fun(t,tc,acentric)
Ai = A_fun(t,p,tc,pc,acentric,omega_a,alfa)
Bi = B_fun(t,p,tc,pc,omega_b)
# Mixing rules
mixing_rule_used = mixing_rules.selector(mixing_rule)
A_liq,B_liq,A_i_liq,Aij_liq,dAdT_liq = mixing_rule_used(liq_compositions,tc,acentric,kij,Ai,Bi,alfa,alfa_fun,t)
A_vap,B_vap,A_i_vap,Aij_vap,dAdT_vap = mixing_rule_used(vap_compositions,tc,acentric,kij,Ai,Bi,alfa,alfa_fun,t)
coefficients_liq = getCubicCoefficients(A_liq,B_liq,u,w)
coefficients_vap = getCubicCoefficients(A_vap,B_vap,u,w)
z_liq= cubic_solver(coefficients_liq,diagram,B_liq)
z_vap = cubic_solver(coefficients_vap,diagram,B_vap)
z_liq = z_liq[0] if isinstance(z_liq,tuple) else z_liq
z_vap = z_vap[1] if isinstance(z_vap,tuple) else z_vap
liq_fugacity_coef = getMixFugacityCoef(z_liq,A_liq,B_liq,A_i_liq,Bi,L)
vap_fugacity_coef = getMixFugacityCoef(z_vap,A_vap,B_vap,A_i_vap,Bi,L)
if(properties):
liq_fugacity = getMixFugacity(z_liq,A_liq,B_liq,A_i_liq,B_liq,L,liq_compositions,p)
vap_fugacity = getMixFugacity(z_vap,A_vap,B_vap,A_i_vap,B_vap,L,vap_compositions,p)
heat_capacities = array(heat_capacities)
ideal_enthalpies = get_ideal_enthalpy(heat_capacities,t)
ideal_entropies = get_ideal_entropy(heat_capacities,t,p)
dAdt = dAdT_fun(t,p,tc,pc,acentric,omega_a,alfa_fun)
enthalpy_liq = get_real_enthalpy(ideal_enthalpies,t,z_liq,A_liq,dAdt,B_liq,L)
enthalpy_vap = get_real_enthalpy(ideal_enthalpies,t,z_vap,A_vap,dAdt,B_vap,L)
entropy_liq = get_real_entropy(ideal_entropies,z_liq,A_liq,dAdt,B_liq,L)
entropy_vap = get_real_entropy(ideal_entropies,z_vap,A_vap,dAdt,B_vap,L)
response = {
"liq_fugacity":liq_fugacity,
"vap_fugacity":vap_fugacity,
"enthalpy_liq":enthalpy_liq,
"enthalpy_vap":enthalpy_vap,
"entropy_liq":entropy_liq,
"entropy_vap":entropy_vap,
"z_liq":z_liq,
"z_vap":z_vap,
"liq_compositions":liq_compositions,
"vap_compositions":vap_compositions
}
return response
return (liq_fugacity_coef,vap_fugacity_coef)
def bubble_temperature(t,p,tc,pc,acentric,liq_compositions,vap_compositions,kij,delta_t=0.1,method='pr',alfa_function='alfa_peng_robinson',mixing_rule='van_der_waals'):
liq_fugacity_coef,vap_fugacity_coef = solve_eos(t,p,tc,pc,acentric,liq_compositions,vap_compositions,kij,method,alfa_function,mixing_rule)
Ki = liq_fugacity_coef/vap_fugacity_coef
Sy = sum(Ki*liq_compositions)
E = log(Sy)
attempts=0
new_t=t
new_vap_compositions = vap_compositions
while(absolute(E) >= 1e-9):
if(attempts == 500):
return 'Problem can not be solved'
t0 = new_t + delta_t
liq_fugacity_coef0,vap_fugacity_coef0 = solve_eos(t0,p,tc,pc,acentric,liq_compositions,new_vap_compositions,kij,method,alfa_function,mixing_rule)
Ki0 = liq_fugacity_coef0/vap_fugacity_coef0
Sy0 = sum(Ki0*liq_compositions)
E0 = log(Sy0)
new_t = (new_t*t0*(E0-E))/(t0*E0-new_t*E)
Sy = sum(Ki*liq_compositions)
new_vap_compositions = (Ki*liq_compositions)/Sy
liq_fugacity_coef,vap_fugacity_coef = solve_eos(new_t,p,tc,pc,acentric,liq_compositions,new_vap_compositions,kij,method,alfa_function,mixing_rule)
Ki = liq_fugacity_coef/vap_fugacity_coef
Sy = sum(Ki*liq_compositions)
E=log(Sy)
attempts +=1
return(new_t,p,liq_compositions,new_vap_compositions)
def bubble_pressure(t,p,tc,pc,acentric,liq_compositions,vap_compositions,kij,delta_p=0.001,method='pr',alfa_function='alfa_peng_robinson',mixing_rule='van_der_waals'):
liq_fugacity_coef,vap_fugacity_coef = solve_eos(t,p,tc,pc,acentric,liq_compositions,vap_compositions,kij,method,alfa_function,mixing_rule)
Ki = liq_fugacity_coef/vap_fugacity_coef
Sy = sum(Ki*liq_compositions)
E = Sy -1
attempts=0
new_p=p
new_vap_compositions = vap_compositions
while(absolute(E) >= 1e-9):
if(attempts == 100):
return 'Probleam can not be solved'
p0=new_p*(1+delta_p)
liq_fugacity_coef0,vap_fugacity_coef0 = solve_eos(t,p0,tc,pc,acentric,liq_compositions,new_vap_compositions,kij,method,alfa_function,mixing_rule)
Ki0 = liq_fugacity_coef0/vap_fugacity_coef0
Sy0 = sum(Ki0*liq_compositions)
E0=Sy0-1
new_p = (new_p*p0*(E0-E))/(p0*E0-new_p*E)
Sy = sum(Ki*liq_compositions)
new_vap_compositions = (Ki*liq_compositions)/Sy
liq_fugacity_coef,vap_fugacity_coef = solve_eos(t,new_p,tc,pc,acentric,liq_compositions,new_vap_compositions,kij,method,alfa_function,mixing_rule)
Ki = liq_fugacity_coef/vap_fugacity_coef
Sy = sum(Ki*liq_compositions)
E = Sy -1
attempts +=1
return(t,new_p,liq_compositions,new_vap_compositions)
def dew_temperature(t,p,tc,pc,acentric,liq_compositions,vap_compositions,kij,delta_t=0.1,method='pr',alfa_function='alfa_peng_robinson',mixing_rule='van_der_waals'):
liq_fugacity_coef,vap_fugacity_coef = solve_eos(t,p,tc,pc,acentric,liq_compositions,vap_compositions,kij,method,alfa_function,mixing_rule)
Ki = liq_fugacity_coef/vap_fugacity_coef
Sx = sum(vap_compositions/Ki)
E = log(Sx)
attempts=0
new_t=t
new_liq_compositions = liq_compositions
while(absolute(E) >= 1e-9):
if(attempts == 500):
return 'Probleam can not be solved'
t0 = new_t + delta_t
liq_fugacity_coef0,vap_fugacity_coef0 = solve_eos(t0,p,tc,pc,acentric,new_liq_compositions,vap_compositions,kij,method,alfa_function,mixing_rule)
Ki0 = liq_fugacity_coef0/vap_fugacity_coef0
Sx0 = sum(vap_compositions/Ki0)
E0 = log(Sx0)
new_t = (new_t*t0*(E0-E))/(t0*E0-new_t*E)
Sx = sum(vap_compositions/Ki)
new_liq_compositions = vap_compositions/(Ki*Sx)
liq_fugacity_coef,vap_fugacity_coef = solve_eos(new_t,p,tc,pc,acentric,new_liq_compositions,vap_compositions,kij,method,alfa_function,mixing_rule)
Ki = liq_fugacity_coef/vap_fugacity_coef
Sx = sum(vap_compositions/Ki)
E = log(Sx)
attempts +=1
return(new_t,p,new_liq_compositions,vap_compositions)
def dew_pressure(t,p,tc,pc,acentric,liq_compositions,vap_compositions,kij,delta_p=0.001,method='pr',alfa_function='alfa_peng_robinson',mixing_rule='van_der_waals'):
liq_fugacity_coef,vap_fugacity_coef = solve_eos(t,p,tc,pc,acentric,liq_compositions,vap_compositions,kij,method,alfa_function,mixing_rule)
Ki = liq_fugacity_coef/vap_fugacity_coef
Sx = sum(vap_compositions/Ki)
E = Sx -1
attempts=0
new_p=p
new_liq_compositions = liq_compositions
while(absolute(E) >= 1e-9):
if(attempts == 100):
return 'Probleam can not be solved'
p0=new_p*(1+delta_p)
liq_fugacity_coef0,vap_fugacity_coef0 = solve_eos(t,p0,tc,pc,acentric,new_liq_compositions,vap_compositions,kij,method,alfa_function,mixing_rule)
Ki0 = liq_fugacity_coef0/vap_fugacity_coef0
Sx0 = sum(vap_compositions/Ki0)
E0=Sx0-1
new_p = (new_p*p0*(E0-E))/(p0*E0-new_p*E)
Sx = sum(vap_compositions/Ki)
new_liq_compositions = vap_compositions/(Ki*Sx)
liq_fugacity_coef,vap_fugacity_coef = solve_eos(t,new_p,tc,pc,acentric,new_liq_compositions,vap_compositions,kij,method,alfa_function,mixing_rule)
Ki = liq_fugacity_coef/vap_fugacity_coef
Sx = sum(vap_compositions/Ki)
E = Sx -1
attempts +=1
return(t,new_p,new_liq_compositions,vap_compositions)
def flash(t,p,tc,pc,acentric,feed_compositions,liq_compositions,vap_compositions,v_f,kij,delta_p=0.0001,method='pr',alfa_function='alfa_peng_robinson',mixing_rule='van_der_waals'):
tau=1
while(absolute(tau)> 1e-5):
liq_fugacity_coef,vap_fugacity_coef = solve_eos(t,p,tc,pc,acentric,liq_compositions,vap_compositions,kij,method,alfa_function,mixing_rule)
Ki = liq_fugacity_coef/vap_fugacity_coef
S = sum((feed_compositions*(Ki-1))/(1+(v_f*(Ki-1))))
S0 = sum((-feed_compositions*(Ki-1)**2)/(1+v_f*(Ki-1))**2)
v_f = v_f-(S/S0)
liq_compositions0 = feed_compositions/(1+v_f*(Ki-1))
Sx=sum(liq_compositions0)
liq_compositions = liq_compositions0/Sx
vap_compositions0=liq_compositions0*Ki
Sy=sum(vap_compositions0)
vap_compositions=vap_compositions0/Sy
tau=sum(absolute(liq_compositions*liq_fugacity_coef-vap_compositions*vap_fugacity_coef))
return (t,p,feed_compositions,liq_compositions,vap_compositions,v_f)
def get_ideal_enthalpy(heat_capacities,t):
ideal_enthalpies = []
for cp in heat_capacities:
number, constants = cp
heat_capacity_equation = tempCorr.selector(number)
enthalpy,_ = quad(heat_capacity_equation,298,t,args=(constants,))
ideal_enthalpies.append(enthalpy)
return array(ideal_enthalpies)
def get_ideal_entropy(heat_capacities,t,p):
R=8.314
ideal_entropies = []
for cp in heat_capacities:
number,constants = cp
heat_capacity_equation = lambda t,constants :tempCorr.selector(number)(t,constants)/t
I,_ = quad(heat_capacity_equation,298,t,args=(constants,))
entropy = I - R*log(p)
ideal_entropies.append(entropy)
return array(ideal_entropies)
def get_real_enthalpy(ideal_enthalpies,t,z,A,dAdt,B,L):
R=8.314
enthalpies = ideal_enthalpies + R*t*(z-1+((dAdt-A)/B)*L(z,B))
return enthalpies
def get_real_entropy(ideal_entropies,z,A,dAdt,B,L):
R=8.314
entropies = ideal_entropies + R*(log(z-B)+dAdt/B*L(z,B))
return entropies
|
[
"numpy.absolute",
"numpy.sum",
"numpy.log",
"scipy.integrate.quad",
"numpy.array"
] |
[((680, 689), 'numpy.array', 'array', (['tc'], {}), '(tc)\n', (685, 689), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((698, 707), 'numpy.array', 'array', (['pc'], {}), '(pc)\n', (703, 707), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((723, 738), 'numpy.array', 'array', (['acentric'], {}), '(acentric)\n', (728, 738), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((760, 783), 'numpy.array', 'array', (['liq_compositions'], {}), '(liq_compositions)\n', (765, 783), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((807, 830), 'numpy.array', 'array', (['vap_compositions'], {}), '(vap_compositions)\n', (812, 830), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((841, 851), 'numpy.array', 'array', (['kij'], {}), '(kij)\n', (846, 851), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((3638, 3664), 'numpy.sum', 'sum', (['(Ki * liq_compositions)'], {}), '(Ki * liq_compositions)\n', (3641, 3664), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((3671, 3678), 'numpy.log', 'log', (['Sy'], {}), '(Sy)\n', (3674, 3678), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((5039, 5065), 'numpy.sum', 'sum', (['(Ki * liq_compositions)'], {}), '(Ki * liq_compositions)\n', (5042, 5065), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((6406, 6432), 'numpy.sum', 'sum', (['(vap_compositions / Ki)'], {}), '(vap_compositions / Ki)\n', (6409, 6432), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((6439, 6446), 'numpy.log', 'log', (['Sx'], {}), '(Sx)\n', (6442, 6446), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((7779, 7805), 'numpy.sum', 'sum', (['(vap_compositions / Ki)'], {}), '(vap_compositions / Ki)\n', (7782, 7805), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((10130, 10153), 'numpy.array', 'array', (['ideal_enthalpies'], {}), '(ideal_enthalpies)\n', (10135, 10153), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((10545, 10567), 'numpy.array', 'array', (['ideal_entropies'], {}), '(ideal_entropies)\n', (10550, 10567), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((2222, 2244), 'numpy.array', 'array', (['heat_capacities'], {}), '(heat_capacities)\n', (2227, 2244), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((3761, 3772), 'numpy.absolute', 'absolute', (['E'], {}), '(E)\n', (3769, 3772), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((4129, 4156), 'numpy.sum', 'sum', (['(Ki0 * liq_compositions)'], {}), '(Ki0 * liq_compositions)\n', (4132, 4156), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((4168, 4176), 'numpy.log', 'log', (['Sy0'], {}), '(Sy0)\n', (4171, 4176), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((4240, 4266), 'numpy.sum', 'sum', (['(Ki * liq_compositions)'], {}), '(Ki * liq_compositions)\n', (4243, 4266), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((4538, 4564), 'numpy.sum', 'sum', (['(Ki * liq_compositions)'], {}), '(Ki * liq_compositions)\n', (4541, 4564), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((4573, 4580), 'numpy.log', 'log', (['Sy'], {}), '(Sy)\n', (4576, 4580), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((5162, 5173), 'numpy.absolute', 'absolute', (['E'], {}), '(E)\n', (5170, 5173), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((5511, 5538), 'numpy.sum', 'sum', (['(Ki0 * liq_compositions)'], {}), '(Ki0 * liq_compositions)\n', (5514, 5538), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((5617, 5643), 'numpy.sum', 'sum', (['(Ki * liq_compositions)'], {}), '(Ki * liq_compositions)\n', (5620, 5643), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((5915, 5941), 'numpy.sum', 'sum', (['(Ki * liq_compositions)'], {}), '(Ki * liq_compositions)\n', (5918, 5941), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((6529, 6540), 'numpy.absolute', 'absolute', (['E'], {}), '(E)\n', (6537, 6540), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((6878, 6905), 'numpy.sum', 'sum', (['(vap_compositions / Ki0)'], {}), '(vap_compositions / Ki0)\n', (6881, 6905), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((6917, 6925), 'numpy.log', 'log', (['Sx0'], {}), '(Sx0)\n', (6920, 6925), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((6989, 7015), 'numpy.sum', 'sum', (['(vap_compositions / Ki)'], {}), '(vap_compositions / Ki)\n', (6992, 7015), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((7287, 7313), 'numpy.sum', 'sum', (['(vap_compositions / Ki)'], {}), '(vap_compositions / Ki)\n', (7290, 7313), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((7324, 7331), 'numpy.log', 'log', (['Sx'], {}), '(Sx)\n', (7327, 7331), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((7902, 7913), 'numpy.absolute', 'absolute', (['E'], {}), '(E)\n', (7910, 7913), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((8251, 8278), 'numpy.sum', 'sum', (['(vap_compositions / Ki0)'], {}), '(vap_compositions / Ki0)\n', (8254, 8278), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((8357, 8383), 'numpy.sum', 'sum', (['(vap_compositions / Ki)'], {}), '(vap_compositions / Ki)\n', (8360, 8383), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((8655, 8681), 'numpy.sum', 'sum', (['(vap_compositions / Ki)'], {}), '(vap_compositions / Ki)\n', (8658, 8681), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((8991, 9004), 'numpy.absolute', 'absolute', (['tau'], {}), '(tau)\n', (8999, 9004), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((9221, 9277), 'numpy.sum', 'sum', (['(feed_compositions * (Ki - 1) / (1 + v_f * (Ki - 1)))'], {}), '(feed_compositions * (Ki - 1) / (1 + v_f * (Ki - 1)))\n', (9224, 9277), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((9283, 9350), 'numpy.sum', 'sum', (['(-feed_compositions * (Ki - 1) ** 2 / (1 + v_f * (Ki - 1)) ** 2)'], {}), '(-feed_compositions * (Ki - 1) ** 2 / (1 + v_f * (Ki - 1)) ** 2)\n', (9286, 9350), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((9434, 9456), 'numpy.sum', 'sum', (['liq_compositions0'], {}), '(liq_compositions0)\n', (9437, 9456), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((9563, 9585), 'numpy.sum', 'sum', (['vap_compositions0'], {}), '(vap_compositions0)\n', (9566, 9585), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((10023, 10078), 'scipy.integrate.quad', 'quad', (['heat_capacity_equation', '(298)', 't'], {'args': '(constants,)'}), '(heat_capacity_equation, 298, t, args=(constants,))\n', (10027, 10078), False, 'from scipy.integrate import quad\n'), ((10405, 10460), 'scipy.integrate.quad', 'quad', (['heat_capacity_equation', '(298)', 't'], {'args': '(constants,)'}), '(heat_capacity_equation, 298, t, args=(constants,))\n', (10409, 10460), False, 'from scipy.integrate import quad\n'), ((9648, 9737), 'numpy.absolute', 'absolute', (['(liq_compositions * liq_fugacity_coef - vap_compositions * vap_fugacity_coef)'], {}), '(liq_compositions * liq_fugacity_coef - vap_compositions *\n vap_fugacity_coef)\n', (9656, 9737), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((10482, 10488), 'numpy.log', 'log', (['p'], {}), '(p)\n', (10485, 10488), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n'), ((10827, 10837), 'numpy.log', 'log', (['(z - B)'], {}), '(z - B)\n', (10830, 10837), False, 'from numpy import log, exp, sqrt, absolute, array, sum\n')]
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import json
import math
import numpy as np
import tokenization
import six
import tensorflow as tf
from tensorflow import logging
class EvalResults(object):
def __init__(self, capacity):
self.metrics = {}
self.capacity = capacity
def add_dict(self, indict):
for key,value in indict.iteritems():
if key in self.metrics:
if len(self.metrics[key]) == self.capacity:
self.metrics[key].pop(0)
else:
self.metrics[key] = []
if isinstance(value, list):
self.metrics[key].append(value[-1])
else:
self.metrics[key].append(value)
def to_string(self):
res = ["%s:%.2f"%(key, np.mean(self.metrics[key]))
for key in self.metrics.keys()]
return " ".join(res)
class CQAExample(object):
"""A single training/test example."""
def __init__(self,
qas_id,
question_text,
doc_tokens,
orig_answer_text=None,
start_position=None,
end_position=None):
self.qas_id = qas_id
self.question_text = question_text
self.doc_tokens = doc_tokens
self.orig_answer_text = orig_answer_text
self.start_position = start_position
self.end_position = end_position
def __str__(self):
return self.__repr__()
def __repr__(self):
s = ""
s += "qas_id: %s" % (tokenization.printable_text(self.qas_id))
s += ", question_text: %s" % (
tokenization.printable_text(self.question_text))
s += ", doc_tokens: [%s]" % (" ".join(self.doc_tokens))
if self.start_position:
s += ", start_position: %d" % (self.start_position)
if self.start_position:
s += ", end_position: %d" % (self.end_position)
return s
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
Only must be specified for sequence pair tasks.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.text_a = text_a
self.text_b = text_b
self.label = label
class InputPretrainExample(object):
"""A single training/test example for pretrain task."""
def __init__(self, guid, input_ids, input_mask, segment_ids, masked_lm_positions,
masked_lm_ids, masked_lm_weights, next_sentence_labels):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
Only must be specified for sequence pair tasks.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.masked_lm_positions = masked_lm_positions
self.masked_lm_ids = masked_lm_ids
self.masked_lm_weights = masked_lm_weights
self.next_sentence_labels = next_sentence_labels
class InputCQAFeatures(object):
"""A single set of features of data."""
def __init__(self,
unique_id,
example_index,
doc_span_index,
tokens,
token_to_orig_map,
token_is_max_context,
input_ids,
input_mask,
segment_ids,
start_position=None,
end_position=None):
self.unique_id = unique_id
self.example_index = example_index
self.doc_span_index = doc_span_index
self.tokens = tokens
self.token_to_orig_map = token_to_orig_map
self.token_is_max_context = token_is_max_context
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.start_position = start_position
self.end_position = end_position
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, input_ids, input_mask, segment_ids, label_id):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_id = label_id
def read_tsv(input_file, quotechar=None):
"""Reads a tab separated value file."""
import csv
with tf.gfile.Open(input_file, "r") as f:
reader = csv.reader(f, delimiter="\t", quotechar=quotechar)
lines = []
for line in reader:
lines.append(line)
return lines
def read_examples_do_nothing(input_file, is_training):
"""do nothing but just return input_file, reserved for tfrecord data"""
return input_file
def read_textmatch_examples(input_file, is_training):
"""Creates examples for the training and dev sets."""
if is_training:
set_type = 'train'
else:
set_type = 'dev'
examples = []
for (i, line) in enumerate(read_tsv(input_file)):
if i == 0:
continue
guid = "%s-%s" % (set_type, i)
text_a = tokenization.convert_to_unicode(line[3])
text_b = tokenization.convert_to_unicode(line[4])
label = tokenization.convert_to_unicode(line[0])
examples.append(
InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
def read_cikm_examples(input_file, is_training):
"""Creates examples for the training and dev sets."""
if is_training:
set_type = 'train'
else:
set_type = 'dev'
examples = []
lengths = []
for (i, line) in enumerate(read_tsv(input_file)):
if i == 0:
continue
guid = "%s-%s" % (set_type, i)
lengths.append(len(line[1].split()) + len(line[2].split()))
text_a = tokenization.convert_to_unicode(line[1])
text_b = tokenization.convert_to_unicode(line[2])
label = tokenization.convert_to_unicode(line[0])
examples.append(
InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
print('length', np.mean(lengths))
raise Exception
return examples
def read_review_examples(input_file, is_training):
"""Creates examples for the training and dev sets."""
fold_id = 9 # fold 9 for training, the rest for testing
if is_training:
set_type = 'train'
else:
set_type = 'dev'
examples = []
lengths = []
for (i, line) in enumerate(read_tsv(input_file)):
# if is_training:
# if int(line[1]) == fold_id:
# continue
# else:
# if int(line[1]) != fold_id:
# continue
if int(line[1]) != fold_id:
continue
lengths.append(len(line[2].split()))
# guid = "%s-%s" % (set_type, i)
# text_a = tokenization.convert_to_unicode(line[2])
# text_b = None
# label = tokenization.convert_to_unicode(line[0])
# examples.append(
# InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
print('length', np.mean(lengths))
raise Exception
return examples
def read_ae_examples(input_file, is_training):
"""Creates examples for the training and dev sets."""
if is_training:
set_type = 'train'
else:
set_type = 'dev'
examples = []
for (i, line) in enumerate(read_tsv(input_file)):
if i == 0:
continue
guid = "%s-%s" % (set_type, i)
text_a = ' '.join(tokenization.convert_to_unicode(line[0]).split('|'))
text_b = ' '.join(tokenization.convert_to_unicode(line[1]).split('|'))
if float(line[2]) > 0.5:
label = tokenization.convert_to_unicode('1')
else:
label = tokenization.convert_to_unicode('0')
examples.append(
InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
def read_pretrain_examples(input_file, is_training):
"""Creates examples for the training and dev sets."""
fold_id = 9 # fold 9 for training, the rest for testing
if is_training:
set_type = 'train'
else:
set_type = 'dev'
examples = []
for (i, line) in enumerate(read_tsv(input_file)):
tokens = line
if i < 3:
print(i, line)
if len(tokens) != 7:
print(len(tokens))
for (i, token) in enumerate(tokens):
print(i, token)
raise Exception
guid = "%s-%s" % (set_type, i)
# print(len(tokens[0].split(',')), len(tokens[1].split(',')),
# len(tokens[2].split(',')), len(tokens[3].split(',')),
# len(tokens[4].split(',')), len(tokens[5].split(',')),
# len(tokens[6].split(',')))
examples.append(InputPretrainExample(
guid=guid,
input_ids=[int(idx) for idx in tokens[0].split(',')],
input_mask=[int(idx) for idx in tokens[1].split(',')],
segment_ids=[int(idx) for idx in tokens[2].split(',')],
masked_lm_positions=[int(idx) for idx in tokens[3].split(',')],
masked_lm_ids=[int(idx) for idx in tokens[4].split(',')],
masked_lm_weights=[float(idx) for idx in tokens[5].split(',')],
next_sentence_labels=int(tokens[6])))
return examples
# def read_coqa_examples(input_file, is_training):
# """Read a CoQA json file into a list of CQAExample."""
# with tf.gfile.Open(input_file, "r") as reader:
# input_data = json.load(reader)["data"]
#
# def is_whitespace(c):
# if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
# return True
# return False
#
# examples = []
# for entry in input_data[:10]:
# paragraph_text = entry["story"]
# doc_tokens = []
# char_to_word_offset = []
# prev_is_whitespace = True
# for c in paragraph_text:
# if is_whitespace(c):
# prev_is_whitespace = True
# else:
# if prev_is_whitespace:
# doc_tokens.append(c)
# else:
# doc_tokens[-1] += c
# prev_is_whitespace = False
# char_to_word_offset.append(len(doc_tokens) - 1)
#
# ############################################################
# # convert the convasational QAs to squad format, with history
# ############################################################
#
# story_id = entry['id']
# questions = [(item['input_text'], story_id + str(item['turn_id'])) for item in entry['questions']] # [(question, question_id), ()]
# answers = [(item['span_text'], item['span_start']) for item in entry['answers']]
#
# qas = []
# for i, (question, answer) in enumerate(zip(questions, answers)):
# start_index = 0 if i - int(FLAGS.history) < 0 else i - int(FLAGS.history)
# end_index = i
# question_with_histories = ''
# # prepend historical questions and answers
# for each_question, each_answer in zip(questions[start_index: end_index], answers[start_index: end_index]):
# question_with_histories += each_question[0] + ' ' + each_answer[0] + ' '
# # add the current question
# question_with_histories += question[0]
# if answer[1] == -1:
# qas.append({'id': question[1], 'question': question_with_histories, 'answers': [{'answer_start': -1, 'text': "unknown"}]})
# else:
# qas.append({'id': question[1], 'question': question_with_histories, 'answers': [{'answer_start': answer[1], 'text': answer[0]}]})
#
# for qa in qas:
# qas_id = qa["id"]
# question_text = qa["question"]
# start_position = None
# end_position = None
# orig_answer_text = None
#
# # if is_training:
# # we read in the groundtruth answer bothing druing training and predicting, because we need to compute acc and f1 at predicting time.
# if len(qa["answers"]) != 1:
# raise ValueError(
# "For training, each question should have exactly 1 answer.")
# answer = qa["answers"][0]
# orig_answer_text = answer["text"]
# answer_offset = answer["answer_start"]
# answer_length = len(orig_answer_text)
# start_position = char_to_word_offset[answer_offset]
# end_position = char_to_word_offset[answer_offset + answer_length - 1]
# # Only add answers where the text can be exactly recovered from the
# # document. If this CAN'T happen it's likely due to weird Unicode
# # stuff so we will just skip the example.
# #
# # Note that this means for training mode, every example is NOT
# # guaranteed to be preserved.
# actual_text = " ".join(doc_tokens[start_position:(end_position + 1)])
# cleaned_answer_text = " ".join(
# tokenization.whitespace_tokenize(orig_answer_text))
# if actual_text.find(cleaned_answer_text) == -1:
# logging.warning("Could not find answer: '%s' vs. '%s'",
# actual_text, cleaned_answer_text)
# continue
#
# example = CQAExample(
# qas_id=qas_id,
# question_text=question_text,
# doc_tokens=doc_tokens,
# orig_answer_text=orig_answer_text,
# start_position=start_position,
# end_position=end_position)
# examples.append(example)
# return examples
def convert_examples_to_features_do_nothing(examples, tokenizer, max_seq_length,
doc_stride, max_query_length, is_training):
"""do nothing but just return examples, reserved for tfrecord data"""
return examples
def convert_examples_to_features_cqa(examples, tokenizer, max_seq_length,
doc_stride, max_query_length, is_training):
"""Loads a data file into a list of `InputBatch`s."""
unique_id = 1000000000
features = []
for (example_index, example) in enumerate(examples):
query_tokens = tokenizer.tokenize(example.question_text)
if len(query_tokens) > max_query_length:
query_tokens = query_tokens[0:max_query_length]
tok_to_orig_index = []
orig_to_tok_index = []
all_doc_tokens = []
for (i, token) in enumerate(example.doc_tokens):
orig_to_tok_index.append(len(all_doc_tokens))
sub_tokens = tokenizer.tokenize(token)
for sub_token in sub_tokens:
tok_to_orig_index.append(i)
all_doc_tokens.append(sub_token)
tok_start_position = None
tok_end_position = None
# if is_training:
# we do this for both training and predicting, because we need also start/end position at testing time to compute acc and f1
tok_start_position = orig_to_tok_index[example.start_position]
if example.end_position < len(example.doc_tokens) - 1:
tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
else:
tok_end_position = len(all_doc_tokens) - 1
(tok_start_position, tok_end_position) = _improve_answer_span(
all_doc_tokens, tok_start_position, tok_end_position, tokenizer,
example.orig_answer_text)
# The -3 accounts for [CLS], [SEP] and [SEP]
max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
# We can have documents that are longer than the maximum sequence length.
# To deal with this we do a sliding window approach, where we take chunks
# of the up to our max length with a stride of `doc_stride`.
_DocSpan = collections.namedtuple( # pylint: disable=invalid-name
"DocSpan", ["start", "length"])
doc_spans = []
start_offset = 0
while start_offset < len(all_doc_tokens):
length = len(all_doc_tokens) - start_offset
if length > max_tokens_for_doc:
length = max_tokens_for_doc
doc_spans.append(_DocSpan(start=start_offset, length=length))
if start_offset + length == len(all_doc_tokens):
break
start_offset += min(length, doc_stride)
for (doc_span_index, doc_span) in enumerate(doc_spans):
tokens = []
token_to_orig_map = {}
token_is_max_context = {}
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in query_tokens:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
for i in range(doc_span.length):
split_token_index = doc_span.start + i
token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]
is_max_context = _check_is_max_context(doc_spans, doc_span_index,
split_token_index)
token_is_max_context[len(tokens)] = is_max_context
tokens.append(all_doc_tokens[split_token_index])
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
start_position = None
end_position = None
if is_training:
# For training, if our document chunk does not contain an annotation
# we throw it out, since there is nothing to predict.
doc_start = doc_span.start
doc_end = doc_span.start + doc_span.length - 1
if (example.start_position < doc_start or
example.end_position < doc_start or
example.start_position > doc_end or example.end_position > doc_end):
continue
doc_offset = len(query_tokens) + 2
start_position = tok_start_position - doc_start + doc_offset
end_position = tok_end_position - doc_start + doc_offset
else:
# when predicting, we donot throw out any doc span to prevent label leaking
doc_start = doc_span.start
doc_end = doc_span.start + doc_span.length - 1
doc_offset = len(query_tokens) + 2
start_position = tok_start_position - doc_start + doc_offset
end_position = tok_end_position - doc_start + doc_offset
if example_index < 20:
logging.info("*** Example ***")
logging.info("unique_id: %s" % (unique_id))
logging.info("example_index: %s" % (example_index))
logging.info("doc_span_index: %s" % (doc_span_index))
logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
logging.info("token_to_orig_map: %s" % " ".join(
["%d:%d" % (x, y) for (x, y) in six.iteritems(token_to_orig_map)]))
logging.info("token_is_max_context: %s" % " ".join([
"%d:%s" % (x, y) for (x, y) in six.iteritems(token_is_max_context)
]))
logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
logging.info(
"input_mask: %s" % " ".join([str(x) for x in input_mask]))
logging.info(
"segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
if is_training:
answer_text = " ".join(tokens[start_position:(end_position + 1)])
logging.info("start_position: %d" % (start_position))
logging.info("end_position: %d" % (end_position))
logging.info(
"answer: %s" % (tokenization.printable_text(answer_text)))
features.append(
InputFeatures(
unique_id=unique_id,
example_index=example_index,
doc_span_index=doc_span_index,
tokens=tokens,
token_to_orig_map=token_to_orig_map,
token_is_max_context=token_is_max_context,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
start_position=start_position,
end_position=end_position))
unique_id += 1
return features
def convert_examples_to_features(examples, label_list, max_seq_length,
tokenizer, model_type='classification'):
"""Loads a data file into a list of `InputBatch`s."""
label_map = {}
for (i, label) in enumerate(label_list):
label_map[label] = i
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
if tokens_b:
# Modifies `tokens_a` and `tokens_b` in place so that the total
# length is less than the specified length.
# Account for [CLS], [SEP], [SEP] with "- 3"
_truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
else:
# Account for [CLS] and [SEP] with "- 2"
if len(tokens_a) > max_seq_length - 2:
tokens_a = tokens_a[0:(max_seq_length - 2)]
# The convention in BERT is:
# (a) For sequence pairs:
# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
# (b) For single sequences:
# tokens: [CLS] the dog is hairy . [SEP]
# type_ids: 0 0 0 0 0 0 0
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambigiously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the first vector (corresponding to [CLS]) is
# used as as the "sentence vector". Note that this only makes sense because
# the entire model is fine-tuned.
tokens = []
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in tokens_a:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
if tokens_b:
for token in tokens_b:
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
if model_type == 'classification':
label_id = label_map[example.label]
else:
label_id = float(example.label)
if ex_index < 5:
logging.info("*** Example ***")
logging.info("guid: %s" % (example.guid))
logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
logging.info(
"segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
logging.info("label: %s (id = %d)" % (example.label, label_id))
features.append(
InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id))
return features
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,
orig_answer_text):
"""Returns tokenized answer spans that better match the annotated answer."""
# The SQuAD annotations are character based. We first project them to
# whitespace-tokenized words. But then after WordPiece tokenization, we can
# often find a "better match". For example:
#
# Question: What year was <NAME> born?
# Context: The leader was <NAME> (1895-1943).
# Answer: 1895
#
# The original whitespace-tokenized answer will be "(1895-1943).". However
# after tokenization, our tokens will be "( 1895 - 1943 ) .". So we can match
# the exact answer, 1895.
#
# However, this is not always possible. Consider the following:
#
# Question: What country is the top exporter of electornics?
# Context: The Japanese electronics industry is the lagest in the world.
# Answer: Japan
#
# In this case, the annotator chose "Japan" as a character sub-span of
# the word "Japanese". Since our WordPiece tokenizer does not split
# "Japanese", we just use "Japanese" as the annotation. This is fairly rare
# in SQuAD, but does happen.
tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))
for new_start in range(input_start, input_end + 1):
for new_end in range(input_end, new_start - 1, -1):
text_span = " ".join(doc_tokens[new_start:(new_end + 1)])
if text_span == tok_answer_text:
return (new_start, new_end)
return (input_start, input_end)
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# Because of the sliding window approach taken to scoring documents, a single
# token can appear in multiple documents. E.g.
# Doc: the man went to the store and bought a gallon of milk
# Span A: the man went to the
# Span B: to the store and bought
# Span C: and bought a gallon of
# ...
#
# Now the word 'bought' will have two scores from spans B and C. We only
# want to consider the score with "maximum context", which we define as
# the *minimum* of its left and right context (the *sum* of left and
# right context will always be the same, of course).
#
# In the example the maximum context for 'bought' would be span C since
# it has 1 left context and 3 right context, while span B has 4 left context
# and 0 right context.
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span.start + doc_span.length - 1
if position < doc_span.start:
continue
if position > end:
continue
num_left_context = position - doc_span.start
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
def write_predictions(all_examples, all_features, all_results, n_best_size,
max_answer_length, do_lower_case, output_prediction_file,
output_nbest_file):
"""Write final predictions to the json file."""
logging.info("Writing predictions to: %s" % (output_prediction_file))
logging.info("Writing nbest to: %s" % (output_nbest_file))
example_index_to_features = collections.defaultdict(list)
for feature in all_features:
example_index_to_features[feature.example_index].append(feature)
unique_id_to_result = {}
for result in all_results:
unique_id_to_result[result.unique_id] = result
_PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
"PrelimPrediction",
["feature_index", "start_index", "end_index", "start_logit", "end_logit"])
all_predictions = collections.OrderedDict()
all_nbest_json = collections.OrderedDict()
for (example_index, example) in enumerate(all_examples):
features = example_index_to_features[example_index]
prelim_predictions = []
for (feature_index, feature) in enumerate(features):
result = unique_id_to_result[feature.unique_id]
start_indexes = _get_best_indexes(result.start_logits, n_best_size)
end_indexes = _get_best_indexes(result.end_logits, n_best_size)
for start_index in start_indexes:
for end_index in end_indexes:
# We could hypothetically create invalid predictions, e.g., predict
# that the start of the span is in the question. We throw out all
# invalid predictions.
if start_index >= len(feature.tokens):
continue
if end_index >= len(feature.tokens):
continue
if start_index not in feature.token_to_orig_map:
continue
if end_index not in feature.token_to_orig_map:
continue
if not feature.token_is_max_context.get(start_index, False):
continue
if end_index < start_index:
continue
length = end_index - start_index + 1
if length > max_answer_length:
continue
prelim_predictions.append(
_PrelimPrediction(
feature_index=feature_index,
start_index=start_index,
end_index=end_index,
start_logit=result.start_logits[start_index],
end_logit=result.end_logits[end_index]))
prelim_predictions = sorted(
prelim_predictions,
key=lambda x: (x.start_logit + x.end_logit),
reverse=True)
_NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
"NbestPrediction", ["text", "start_logit", "end_logit"])
seen_predictions = {}
nbest = []
for pred in prelim_predictions:
if len(nbest) >= n_best_size:
break
feature = features[pred.feature_index]
tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]
orig_doc_start = feature.token_to_orig_map[pred.start_index]
orig_doc_end = feature.token_to_orig_map[pred.end_index]
orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]
tok_text = " ".join(tok_tokens)
# De-tokenize WordPieces that have been split off.
tok_text = tok_text.replace(" ##", "")
tok_text = tok_text.replace("##", "")
# Clean whitespace
tok_text = tok_text.strip()
tok_text = " ".join(tok_text.split())
orig_text = " ".join(orig_tokens)
final_text = get_final_text(tok_text, orig_text, do_lower_case)
if final_text in seen_predictions:
continue
seen_predictions[final_text] = True
nbest.append(
_NbestPrediction(
text=final_text,
start_logit=pred.start_logit,
end_logit=pred.end_logit))
# In very rare edge cases we could have no valid predictions. So we
# just create a nonce prediction in this case to avoid failure.
if not nbest:
nbest.append(
_NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
assert len(nbest) >= 1
total_scores = []
for entry in nbest:
total_scores.append(entry.start_logit + entry.end_logit)
probs = _compute_softmax(total_scores)
nbest_json = []
for (i, entry) in enumerate(nbest):
output = collections.OrderedDict()
output["text"] = entry.text
output["probability"] = probs[i]
output["start_logit"] = entry.start_logit
output["end_logit"] = entry.end_logit
nbest_json.append(output)
assert len(nbest_json) >= 1
all_predictions[example.qas_id] = nbest_json[0]["text"]
all_nbest_json[example.qas_id] = nbest_json
with tf.gfile.GFile(output_prediction_file, "w") as writer:
writer.write(json.dumps(all_predictions, indent=4) + "\n")
with tf.gfile.GFile(output_nbest_file, "w") as writer:
writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
def get_final_text(pred_text, orig_text, do_lower_case):
"""Project the tokenized prediction back to the original text."""
# When we created the data, we kept track of the alignment between original
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
# now `orig_text` contains the span of our original text corresponding to the
# span that we predicted.
#
# However, `orig_text` may contain extra characters that we don't want in
# our prediction.
#
# For example, let's say:
# pred_text = <NAME>
# orig_text = <NAME>
#
# We don't want to return `orig_text` because it contains the extra "'s".
#
# We don't want to return `pred_text` because it's already been normalized
# (the SQuAD eval script also does punctuation stripping/lower casing but
# our tokenizer does additional normalization like stripping accent
# characters).
#
# What we really want to return is "<NAME>".
#
# Therefore, we have to apply a semi-complicated alignment heruistic between
# `pred_text` and `orig_text` to get a character-to-charcter alignment. This
# can fail in certain cases in which case we just return `orig_text`.
def _strip_spaces(text):
ns_chars = []
ns_to_s_map = collections.OrderedDict()
for (i, c) in enumerate(text):
if c == " ":
continue
ns_to_s_map[len(ns_chars)] = i
ns_chars.append(c)
ns_text = "".join(ns_chars)
return (ns_text, ns_to_s_map)
# We first tokenize `orig_text`, strip whitespace from the result
# and `pred_text`, and check if they are the same length. If they are
# NOT the same length, the heuristic has failed. If they are the same
# length, we assume the characters are one-to-one aligned.
tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case)
tok_text = " ".join(tokenizer.tokenize(orig_text))
start_position = tok_text.find(pred_text)
if start_position == -1:
if FLAGS.verbose_logging:
logging.info(
"Unable to find text: '%s' in '%s'" % (pred_text, orig_text))
return orig_text
end_position = start_position + len(pred_text) - 1
(orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)
(tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)
if len(orig_ns_text) != len(tok_ns_text):
if FLAGS.verbose_logging:
logging.info("Length not equal after stripping spaces: '%s' vs '%s'",
orig_ns_text, tok_ns_text)
return orig_text
# We then project the characters in `pred_text` back to `orig_text` using
# the character-to-character alignment.
tok_s_to_ns_map = {}
for (i, tok_index) in six.iteritems(tok_ns_to_s_map):
tok_s_to_ns_map[tok_index] = i
orig_start_position = None
if start_position in tok_s_to_ns_map:
ns_start_position = tok_s_to_ns_map[start_position]
if ns_start_position in orig_ns_to_s_map:
orig_start_position = orig_ns_to_s_map[ns_start_position]
if orig_start_position is None:
if FLAGS.verbose_logging:
logging.info("Couldn't map start position")
return orig_text
orig_end_position = None
if end_position in tok_s_to_ns_map:
ns_end_position = tok_s_to_ns_map[end_position]
if ns_end_position in orig_ns_to_s_map:
orig_end_position = orig_ns_to_s_map[ns_end_position]
if orig_end_position is None:
if FLAGS.verbose_logging:
logging.info("Couldn't map end position")
return orig_text
output_text = orig_text[orig_start_position:(orig_end_position + 1)]
return output_text
def _get_best_indexes(logits, n_best_size):
"""Get the n-best logits from a list."""
index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
best_indexes = []
for i in range(len(index_and_score)):
if i >= n_best_size:
break
best_indexes.append(index_and_score[i][0])
return best_indexes
def _compute_softmax(scores):
"""Compute softmax probability over raw logits."""
if not scores:
return []
max_score = None
for score in scores:
if max_score is None or score > max_score:
max_score = score
exp_scores = []
total_sum = 0.0
for score in scores:
x = math.exp(score - max_score)
exp_scores.append(x)
total_sum += x
probs = []
for score in exp_scores:
probs.append(score / total_sum)
return probs
def get_dict(train_batch):
b_input_ids = train_batch['input_ids']
b_input_mask = train_batch['input_mask']
b_segment_ids = train_batch['segment_ids']
b_labels = train_batch['label_id']
return b_input_ids,b_input_mask,b_segment_ids,b_labels
|
[
"math.exp",
"tokenization.printable_text",
"csv.reader",
"tensorflow.logging.info",
"json.dumps",
"collections.defaultdict",
"numpy.mean",
"tensorflow.gfile.GFile",
"collections.namedtuple",
"tokenization.BasicTokenizer",
"collections.OrderedDict",
"tokenization.convert_to_unicode",
"six.iteritems",
"tensorflow.gfile.Open"
] |
[((30082, 30149), 'tensorflow.logging.info', 'logging.info', (["('Writing predictions to: %s' % output_prediction_file)"], {}), "('Writing predictions to: %s' % output_prediction_file)\n", (30094, 30149), False, 'from tensorflow import logging\n'), ((30156, 30212), 'tensorflow.logging.info', 'logging.info', (["('Writing nbest to: %s' % output_nbest_file)"], {}), "('Writing nbest to: %s' % output_nbest_file)\n", (30168, 30212), False, 'from tensorflow import logging\n'), ((30248, 30277), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (30271, 30277), False, 'import collections\n'), ((30525, 30646), 'collections.namedtuple', 'collections.namedtuple', (['"""PrelimPrediction"""', "['feature_index', 'start_index', 'end_index', 'start_logit', 'end_logit']"], {}), "('PrelimPrediction', ['feature_index', 'start_index',\n 'end_index', 'start_logit', 'end_logit'])\n", (30547, 30646), False, 'import collections\n'), ((30715, 30740), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (30738, 30740), False, 'import collections\n'), ((30762, 30787), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (30785, 30787), False, 'import collections\n'), ((37322, 37378), 'tokenization.BasicTokenizer', 'tokenization.BasicTokenizer', ([], {'do_lower_case': 'do_lower_case'}), '(do_lower_case=do_lower_case)\n', (37349, 37378), False, 'import tokenization\n'), ((38272, 38302), 'six.iteritems', 'six.iteritems', (['tok_ns_to_s_map'], {}), '(tok_ns_to_s_map)\n', (38285, 38302), False, 'import six\n'), ((5270, 5300), 'tensorflow.gfile.Open', 'tf.gfile.Open', (['input_file', '"""r"""'], {}), "(input_file, 'r')\n", (5283, 5300), True, 'import tensorflow as tf\n'), ((5322, 5372), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '"""\t"""', 'quotechar': 'quotechar'}), "(f, delimiter='\\t', quotechar=quotechar)\n", (5332, 5372), False, 'import csv\n'), ((5981, 6021), 'tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['line[3]'], {}), '(line[3])\n', (6012, 6021), False, 'import tokenization\n'), ((6039, 6079), 'tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['line[4]'], {}), '(line[4])\n', (6070, 6079), False, 'import tokenization\n'), ((6096, 6136), 'tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['line[0]'], {}), '(line[0])\n', (6127, 6136), False, 'import tokenization\n'), ((6707, 6747), 'tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['line[1]'], {}), '(line[1])\n', (6738, 6747), False, 'import tokenization\n'), ((6765, 6805), 'tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['line[2]'], {}), '(line[2])\n', (6796, 6805), False, 'import tokenization\n'), ((6822, 6862), 'tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['line[0]'], {}), '(line[0])\n', (6853, 6862), False, 'import tokenization\n'), ((6989, 7005), 'numpy.mean', 'np.mean', (['lengths'], {}), '(lengths)\n', (6996, 7005), True, 'import numpy as np\n'), ((7989, 8005), 'numpy.mean', 'np.mean', (['lengths'], {}), '(lengths)\n', (7996, 8005), True, 'import numpy as np\n'), ((16921, 16975), 'collections.namedtuple', 'collections.namedtuple', (['"""DocSpan"""', "['start', 'length']"], {}), "('DocSpan', ['start', 'length'])\n", (16943, 16975), False, 'import collections\n'), ((32822, 32901), 'collections.namedtuple', 'collections.namedtuple', (['"""NbestPrediction"""', "['text', 'start_logit', 'end_logit']"], {}), "('NbestPrediction', ['text', 'start_logit', 'end_logit'])\n", (32844, 32901), False, 'import collections\n'), ((35211, 35254), 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['output_prediction_file', '"""w"""'], {}), "(output_prediction_file, 'w')\n", (35225, 35254), True, 'import tensorflow as tf\n'), ((35343, 35381), 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['output_nbest_file', '"""w"""'], {}), "(output_nbest_file, 'w')\n", (35357, 35381), True, 'import tensorflow as tf\n'), ((36761, 36786), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (36784, 36786), False, 'import collections\n'), ((39924, 39951), 'math.exp', 'math.exp', (['(score - max_score)'], {}), '(score - max_score)\n', (39932, 39951), False, 'import math\n'), ((1639, 1679), 'tokenization.printable_text', 'tokenization.printable_text', (['self.qas_id'], {}), '(self.qas_id)\n', (1666, 1679), False, 'import tokenization\n'), ((1732, 1779), 'tokenization.printable_text', 'tokenization.printable_text', (['self.question_text'], {}), '(self.question_text)\n', (1759, 1779), False, 'import tokenization\n'), ((8599, 8635), 'tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['"""1"""'], {}), "('1')\n", (8630, 8635), False, 'import tokenization\n'), ((8670, 8706), 'tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['"""0"""'], {}), "('0')\n", (8701, 8706), False, 'import tokenization\n'), ((25320, 25351), 'tensorflow.logging.info', 'logging.info', (['"""*** Example ***"""'], {}), "('*** Example ***')\n", (25332, 25351), False, 'from tensorflow import logging\n'), ((25358, 25397), 'tensorflow.logging.info', 'logging.info', (["('guid: %s' % example.guid)"], {}), "('guid: %s' % example.guid)\n", (25370, 25397), False, 'from tensorflow import logging\n'), ((25756, 25819), 'tensorflow.logging.info', 'logging.info', (["('label: %s (id = %d)' % (example.label, label_id))"], {}), "('label: %s (id = %d)' % (example.label, label_id))\n", (25768, 25819), False, 'from tensorflow import logging\n'), ((34794, 34819), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (34817, 34819), False, 'import collections\n'), ((37557, 37631), 'tensorflow.logging.info', 'logging.info', (['("Unable to find text: \'%s\' in \'%s\'" % (pred_text, orig_text))'], {}), '("Unable to find text: \'%s\' in \'%s\'" % (pred_text, orig_text))\n', (37569, 37631), False, 'from tensorflow import logging\n'), ((37948, 38048), 'tensorflow.logging.info', 'logging.info', (['"""Length not equal after stripping spaces: \'%s\' vs \'%s\'"""', 'orig_ns_text', 'tok_ns_text'], {}), '("Length not equal after stripping spaces: \'%s\' vs \'%s\'",\n orig_ns_text, tok_ns_text)\n', (37960, 38048), False, 'from tensorflow import logging\n'), ((38680, 38723), 'tensorflow.logging.info', 'logging.info', (['"""Couldn\'t map start position"""'], {}), '("Couldn\'t map start position")\n', (38692, 38723), False, 'from tensorflow import logging\n'), ((39070, 39111), 'tensorflow.logging.info', 'logging.info', (['"""Couldn\'t map end position"""'], {}), '("Couldn\'t map end position")\n', (39082, 39111), False, 'from tensorflow import logging\n'), ((20361, 20392), 'tensorflow.logging.info', 'logging.info', (['"""*** Example ***"""'], {}), "('*** Example ***')\n", (20373, 20392), False, 'from tensorflow import logging\n'), ((20409, 20450), 'tensorflow.logging.info', 'logging.info', (["('unique_id: %s' % unique_id)"], {}), "('unique_id: %s' % unique_id)\n", (20421, 20450), False, 'from tensorflow import logging\n'), ((20469, 20518), 'tensorflow.logging.info', 'logging.info', (["('example_index: %s' % example_index)"], {}), "('example_index: %s' % example_index)\n", (20481, 20518), False, 'from tensorflow import logging\n'), ((20537, 20588), 'tensorflow.logging.info', 'logging.info', (["('doc_span_index: %s' % doc_span_index)"], {}), "('doc_span_index: %s' % doc_span_index)\n", (20549, 20588), False, 'from tensorflow import logging\n'), ((35287, 35324), 'json.dumps', 'json.dumps', (['all_predictions'], {'indent': '(4)'}), '(all_predictions, indent=4)\n', (35297, 35324), False, 'import json\n'), ((35414, 35450), 'json.dumps', 'json.dumps', (['all_nbest_json'], {'indent': '(4)'}), '(all_nbest_json, indent=4)\n', (35424, 35450), False, 'import json\n'), ((872, 898), 'numpy.mean', 'np.mean', (['self.metrics[key]'], {}), '(self.metrics[key])\n', (879, 898), True, 'import numpy as np\n'), ((8414, 8454), 'tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['line[0]'], {}), '(line[0])\n', (8445, 8454), False, 'import tokenization\n'), ((8493, 8533), 'tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['line[1]'], {}), '(line[1])\n', (8524, 8533), False, 'import tokenization\n'), ((21489, 21540), 'tensorflow.logging.info', 'logging.info', (["('start_position: %d' % start_position)"], {}), "('start_position: %d' % start_position)\n", (21501, 21540), False, 'from tensorflow import logging\n'), ((21563, 21610), 'tensorflow.logging.info', 'logging.info', (["('end_position: %d' % end_position)"], {}), "('end_position: %d' % end_position)\n", (21575, 21610), False, 'from tensorflow import logging\n'), ((21687, 21727), 'tokenization.printable_text', 'tokenization.printable_text', (['answer_text'], {}), '(answer_text)\n', (21714, 21727), False, 'import tokenization\n'), ((25455, 25485), 'tokenization.printable_text', 'tokenization.printable_text', (['x'], {}), '(x)\n', (25482, 25485), False, 'import tokenization\n'), ((20666, 20696), 'tokenization.printable_text', 'tokenization.printable_text', (['x'], {}), '(x)\n', (20693, 20696), False, 'import tokenization\n'), ((20833, 20865), 'six.iteritems', 'six.iteritems', (['token_to_orig_map'], {}), '(token_to_orig_map)\n', (20846, 20865), False, 'import six\n'), ((20989, 21024), 'six.iteritems', 'six.iteritems', (['token_is_max_context'], {}), '(token_is_max_context)\n', (21002, 21024), False, 'import six\n')]
|
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import all_call.train
import numpy as np
import json
import sys
import pandas as pd
import re
import os
from glob import glob
from arguments import yaml_reader
# default parameters for inference
DEFAULT_MODEL_PARAMS = (-0.0107736, 0.00244419, 0.0, 0.00440608)
DEFAULT_READ_DROP = (479.596, -21.4382)
DEFAULT_READ_DROP_REL = (1.18332, -0.0475454)
DEFAULT_FIT_FUNCTION = "linear"
# functions for training
fit_functions = {"const": all_call.train.const_rate, "linear": all_call.train.linear_rate, "n2": all_call.train.n2_rate, "exp": all_call.train.exp_rate}
def load_arguments():
"""
Loads all arguments and sets default values.
:return: argparse arguments
"""
parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('dir_structure', type=path_exists, help='Directory with multiple Dante results directories. '
'Each Dante directory has filled "all_profiles.txt" and "all_profiles.true" files.')
# training.add_argument('--model-fig', type=str, default=None, help="File to write .png file with comparison of models and train data. Suffix determines the type of image file.")
# parser.add_argument('--profiles', type=str, required=True, help="TSV file or .npy file with one or more profiles. Required.")
parser.add_argument('--output-params', type=convert_to_absolute, default=None, help="File with parameters of the model to save to. Default: dir_structure/params.txt")
parser.add_argument('--output-profile', type=convert_to_absolute, default=None, help="File, where to collect all the profiles. Default: dir_structure/all_profiles.txt")
parser.add_argument('--output-true', type=convert_to_absolute, default=None, help="File, where to collect all the true values. Default: dir_structure/all_profiles.true")
parser.add_argument('--input-true', type=convert_to_absolute, default=None, help="File, with all the true values. Default: collect from Dante predictions")
parser.add_argument('--config-dir', type=path_exists, default=None, help="Directory, where to save new config files. Default: without saving")
parser.add_argument('--fit-function', choices=fit_functions.keys(), default="linear", help="Function to approximate deletion rate of STRs. Default: linear")
parser.add_argument('-v', '--verbosity-level', type=int, choices=range(3), default=1, help="Level of verbosity, default 1.")
parser.add_argument('-p', '--prepare', action='store_true', help="Only prepare files, do not run training.")
# input_args.add_argument('-l', '--len_repeating', type=int, default=3, help="Length of the STR. Used for read drop modelling.")
args = parser.parse_args()
# check
if args.output_profile is None:
args.output_profile = '%s/all_profiles.txt' % args.dir_structure
if args.output_true is None:
args.output_true = '%s/all_profiles.true' % args.dir_structure
if args.output_params is None:
args.output_params = '%s/params.txt' % args.dir_structure
return args
def convert_to_absolute(path):
"""
Converts to absolute path, do not check if exists.
:param path: str - path
:return: str - absolute path
"""
return os.path.abspath(path)
def path_exists(path):
"""
Checks if the supplied path exists.
:param path: str - path to a file or dir
:return: str - absolute path to a file or dir
"""
try:
path = convert_to_absolute(path)
except Exception:
print('ERROR: %s directory does not exists' % path)
exit(-1)
return path
def crawl_dante(dir_structure):
"""
Crawl Dante dir and collect config, profile, and true_vals files
:param dir_structure: str - directory above the Dante directory structures, here we start the crawl
:return: list(str) x3 - list of paths to configs, profiles, and true values
"""
# read all configs
configs = glob('%s/*/config.yaml' % dir_structure)
good_configs = []
profiles = []
true_vals = []
# check if every config has its profiles and true_vals
for config in configs:
profile = '%s/all_profiles.txt' % os.path.dirname(config)
if not os.path.exists(profile):
print('WARNING: "%s" exists but "%s" does not!!' % (config, profile))
continue
true_val = '%s/all_profiles.true' % os.path.dirname(config)
if not os.path.exists(true_val):
print('WARNING: "%s" exists but "%s" does not!!' % (config, true_val))
continue
# all ok, write them:
good_configs.append(config)
profiles.append(profile)
true_vals.append(true_val)
return good_configs, profiles, true_vals
def get_name(path):
"""
Get directory name from path to config/profile/...
:param path: str - path
:return: str - directory name without blanks
"""
directory = path.split('/')[-2]
directory = directory.replace(' ', '_')
return directory
def update_config(config_path, save_dir, params_file):
"""
Create new config file with inputs from the outputs of Dante.
:param config_path: str - path to the config file
:param save_dir: str - directory where to save the new config
:param save_dir: str - directory where to save the new config
:return: None
"""
# gather inputs:
directory = os.path.dirname(config_path)
inputs = glob('%s/*/annotations*' % directory)
inputs += glob('%s/*/filtered_primer*' % directory)
# read the old config:
config = yaml_reader.load_arguments(config_path)
# update the config with new inputs
config['inputs'] = []
for input in inputs:
config['inputs'].append({'path': input})
# update the config with new params
config['allcall']['param_file'] = params_file
# add "_retrained" to output dirs
config['general']['output_dir'] = '%s_retrained' % config['general']['output_dir']
# write it
name = get_name(config_path)
config_name = '%s/%s_config.yaml' % (save_dir, name)
yaml_reader.save_arguments(config, config_name)
def merge_profiles(profiles, output_file):
"""
Merge all profiles according to the name of dirs and output them.
:param profiles: list(str) - list of paths to profiles
:param output_file: str - output file for merged file
:return: pd.DataFrame - merged DataFrame with all data
"""
if len(profiles) == 0:
return None
# create empty dataframe
all_profiles = pd.DataFrame()
# and fill it
for profile in profiles:
name = get_name(profile)
# get the maximal number of columns:
max_cols = 0
with open(profile) as f:
for line in f:
max_cols = max(max_cols, line.count('\t'))
# write to aggregated file:
current = pd.read_csv(profile, sep='\t', header=None, names=['index'] + range(max_cols), index_col=0, parse_dates=True, engine='python')
current.index = list(map(lambda x: '%s_%s' % (name, x), current.index))
all_profiles = pd.concat([all_profiles, current])
# fill not available data:
all_profiles = all_profiles.fillna(0)
all_profiles = all_profiles.applymap(lambda x: x if type(x) is str else str(int(x)))
all_profiles.sort_index(inplace=True)
# save it:
all_profiles.to_csv(output_file, sep='\t')
# return it
return all_profiles
def read_dante(filename):
"""
Read profiles from CSV from Dante.
:param filename: str - filename to read
:return: Pandas.DataFrame with read profiles or None if no read occurred
"""
# now try to load tsv file:
name = filename.split('/')[-2]
try:
profiles = pd.read_csv(filename, sep="\t", header=None, index_col=None, parse_dates=True)
except Exception:
return None
new_profiles = pd.DataFrame()
max_str = max(profiles.max(0)[1:]) + 2
if profiles is not None:
for column in profiles.columns[1:]:
vals = np.zeros(max_str, dtype=int)
for i, c in enumerate(profiles[column]):
vals[int(c)] += profiles.iloc[i][0]
new_profiles['%s_%d' % (name, column - 1)] = vals
if len(new_profiles.index) > 0:
profiles = new_profiles.transpose()
return profiles
def fix_profile_file(filename):
"""
Fix profile file to be able to read as a tsv.
:param filename: str - filename to fix
"""
# read the file
with open(filename) as f:
lines = f.readlines()
# find separator
sep = '\t' if len(lines[0].split('\t')) >= len(lines[0].split(None)) else None
# count the number of columns:
cols = np.zeros_like(lines, dtype=int)
for i, line in enumerate(lines):
cols[i] = len(line.split(sep))
# print with the highest number
max_cols = max(cols)
with open(filename, 'w') as f:
for i, line in enumerate(lines):
f.write(line.strip())
# append enough zeros
for _ in range(max_cols - cols[i]):
f.write('\t0')
f.write('\n')
def read_profiles(filename):
"""
Read profiles from CSV or from .npy file.
:param filename: str - filename to read
:return: Pandas.DataFrame with read profiles or None if no read occurred
"""
# first try to load numpy array
try:
profiles = np.load(filename)
except IOError:
profiles = None
if profiles is not None:
profiles = pd.DataFrame(data=profiles[np.newaxis], index=[int(filename.split('.')[0].split('/')[-1])])
# now try to load tsv file:
if profiles is None:
try:
fix_profile_file(filename)
profiles = pd.read_csv(filename, sep='\t', header=None, index_col=0, parse_dates=True)
except IOError:
profiles = None
return profiles
def read_true(filename):
"""
Read true values from json file or from .true file.
:param filename: str - json file to read
:return: dict - values read from the json file or None if no read occurred
"""
class WrongCountError(Exception):
pass
true_values = None
try:
with open(filename) as f:
true_values = json.load(f)
except Exception:
pass
if true_values is None:
try:
with open(filename) as f:
true_values = {}
for line in f:
split = line.split()
if len(split) == 3:
m = re.search(r'_\d+$', split[0])
name = split[0]
if m is None:
name += '_1'
true_values[name] = (int(split[1]), int(split[2]))
elif len(split) > 3:
raise WrongCountError("Wrong number of parsed elements (expected 3, got %d)" % len(split))
except Exception as e:
print('ERROR: ', e)
return None
return true_values
def read_params(filename):
"""
Reads all parameters written with write_params(print_all=True)
:param filename: str - filename to read parameters from, if None, load default params
:return: 4-tuple, 2-tuple, function - parameters for model, read count drop, and error function for model distributions
"""
if filename is None:
return DEFAULT_MODEL_PARAMS, DEFAULT_READ_DROP, DEFAULT_READ_DROP_REL, DEFAULT_FIT_FUNCTION
# read 2nd and last line of the file
with open(filename) as f:
lines = f.readlines()
fit_function = lines[1].strip().split()[1]
split = list(map(float, lines[-1].strip().split()))
if len(split) < 8:
print("ERROR: parameters were not read successfully, using defaults!", file=sys.stderr)
return DEFAULT_MODEL_PARAMS, DEFAULT_READ_DROP, DEFAULT_READ_DROP_REL, DEFAULT_FIT_FUNCTION
# extract parameters from last line of file
model_params = tuple(split[0:4])
read_drop_params = tuple(split[4:6])
read_drop_params_rel = tuple(split[6:8])
return model_params, read_drop_params, read_drop_params_rel, fit_function
|
[
"pandas.DataFrame",
"os.path.abspath",
"numpy.zeros_like",
"numpy.load",
"argparse.ArgumentParser",
"json.load",
"pandas.read_csv",
"os.path.dirname",
"arguments.yaml_reader.save_arguments",
"os.path.exists",
"numpy.zeros",
"glob.glob",
"arguments.yaml_reader.load_arguments",
"re.search",
"pandas.concat"
] |
[((757, 816), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'formatter_class': 'RawDescriptionHelpFormatter'}), '(formatter_class=RawDescriptionHelpFormatter)\n', (771, 816), False, 'from argparse import ArgumentParser, RawDescriptionHelpFormatter\n'), ((3315, 3336), 'os.path.abspath', 'os.path.abspath', (['path'], {}), '(path)\n', (3330, 3336), False, 'import os\n'), ((4019, 4059), 'glob.glob', 'glob', (["('%s/*/config.yaml' % dir_structure)"], {}), "('%s/*/config.yaml' % dir_structure)\n", (4023, 4059), False, 'from glob import glob\n'), ((5462, 5490), 'os.path.dirname', 'os.path.dirname', (['config_path'], {}), '(config_path)\n', (5477, 5490), False, 'import os\n'), ((5504, 5541), 'glob.glob', 'glob', (["('%s/*/annotations*' % directory)"], {}), "('%s/*/annotations*' % directory)\n", (5508, 5541), False, 'from glob import glob\n'), ((5556, 5597), 'glob.glob', 'glob', (["('%s/*/filtered_primer*' % directory)"], {}), "('%s/*/filtered_primer*' % directory)\n", (5560, 5597), False, 'from glob import glob\n'), ((5639, 5678), 'arguments.yaml_reader.load_arguments', 'yaml_reader.load_arguments', (['config_path'], {}), '(config_path)\n', (5665, 5678), False, 'from arguments import yaml_reader\n'), ((6147, 6194), 'arguments.yaml_reader.save_arguments', 'yaml_reader.save_arguments', (['config', 'config_name'], {}), '(config, config_name)\n', (6173, 6194), False, 'from arguments import yaml_reader\n'), ((6598, 6612), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (6610, 6612), True, 'import pandas as pd\n'), ((7950, 7964), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7962, 7964), True, 'import pandas as pd\n'), ((8775, 8806), 'numpy.zeros_like', 'np.zeros_like', (['lines'], {'dtype': 'int'}), '(lines, dtype=int)\n', (8788, 8806), True, 'import numpy as np\n'), ((7165, 7199), 'pandas.concat', 'pd.concat', (['[all_profiles, current]'], {}), '([all_profiles, current])\n', (7174, 7199), True, 'import pandas as pd\n'), ((7809, 7887), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'sep': '"""\t"""', 'header': 'None', 'index_col': 'None', 'parse_dates': '(True)'}), "(filename, sep='\\t', header=None, index_col=None, parse_dates=True)\n", (7820, 7887), True, 'import pandas as pd\n'), ((9472, 9489), 'numpy.load', 'np.load', (['filename'], {}), '(filename)\n', (9479, 9489), True, 'import numpy as np\n'), ((4249, 4272), 'os.path.dirname', 'os.path.dirname', (['config'], {}), '(config)\n', (4264, 4272), False, 'import os\n'), ((4288, 4311), 'os.path.exists', 'os.path.exists', (['profile'], {}), '(profile)\n', (4302, 4311), False, 'import os\n'), ((4460, 4483), 'os.path.dirname', 'os.path.dirname', (['config'], {}), '(config)\n', (4475, 4483), False, 'import os\n'), ((4499, 4523), 'os.path.exists', 'os.path.exists', (['true_val'], {}), '(true_val)\n', (4513, 4523), False, 'import os\n'), ((8102, 8130), 'numpy.zeros', 'np.zeros', (['max_str'], {'dtype': 'int'}), '(max_str, dtype=int)\n', (8110, 8130), True, 'import numpy as np\n'), ((9808, 9883), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'sep': '"""\t"""', 'header': 'None', 'index_col': '(0)', 'parse_dates': '(True)'}), "(filename, sep='\\t', header=None, index_col=0, parse_dates=True)\n", (9819, 9883), True, 'import pandas as pd\n'), ((10325, 10337), 'json.load', 'json.load', (['f'], {}), '(f)\n', (10334, 10337), False, 'import json\n'), ((10626, 10655), 're.search', 're.search', (['"""_\\\\d+$"""', 'split[0]'], {}), "('_\\\\d+$', split[0])\n", (10635, 10655), False, 'import re\n')]
|
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
import Transform as Transform
import DiffDriveRobot
class Wheel(object):
"""docstring for Wheel."""
def __init__(self):
super(Wheel, self).__init__()
self.speed = 0
def setSpeed(self, speed):
self.speed = speed
def getSpeed(self):
return self.speed
def getDist(self, dT):
return self.speed * dT
class Robot(object):
"""docstring for Robot."""
def __init__(self, x, y, theta, robot):
super(Robot, self).__init__()
self.polygon = np.array([[-150, -150], [-150, 150], [150, 150], [150, -150], [-150, -150]],dtype =float)
self.x = x
self.y = y
self.theta = theta
self.robot = robot
self.MEntreAxes = 200
self.OEntreAxes = 250
self.xC = x
self.yC = y
self.thetaC = theta
self.XErr = 0
self.YErr = 0
self.ThetaErr = 0
self.DistErr = 0
self.CapErr = 0
self.alpha = []
self.thetaa = []
self.DistErra = []
# mutateurs
def setX(self, x):
self.x = x
def setY(self, y):
self.y = y
def setTheta(self, theta):
self.theta = theta
def setXC(self, xC):
self.xC = xC
def setYC(self, yC):
self.yC = yC
def setThetaC(self, thetaC):
self.thetaC = thetaC
# asscenseurs
def getX(self):
return self.x
def getY(self):
return self.y
def getTheta(self):
return self.theta
#autres methodes
#fonctions traduisant le fonctionment du robot (modèle)
def updateOdometry(self, dT):
dOL = self.robot.getLeftEncoderDist(dT)
dOR = self.robot.getRightEncoderDist(dT)
dXrobot = (dOR + dOL)/2
dTheta = (dOR - dOL)/self.OEntreAxes
self.theta = self.theta + dTheta
if(self.theta <= -np.pi): self.theta = self.theta + 2*np.pi
if(self.theta > np.pi): self.theta = self.theta - 2*np.pi
self.x = self.x + dXrobot*np.cos(self.theta)
self.y = self.y + dXrobot*np.sin(self.theta)
def computeError(self): # Equations 11 & 12
self.XErr = self.xC - self.x
self.YErr = self.yC - self.y
self.ThetaErr = self.thetaC - self.theta #unused
Kp = 1
Kalpha = 5
alpha = np.arctan2(self.YErr, self.XErr)-self.theta
if alpha <= -np.pi: alpha+= 2*np.pi
if alpha > +np.pi: alpha-= 2*np.pi
self.thetaa.append(self.theta)
self.alpha.append(alpha)
self.DistErr = Kp*np.sqrt(self.XErr**2 + self.YErr**2)*np.cos(alpha)
# self.CapErr = Kp*np.sin(alpha)*np.cos(alpha) + Kalpha*alpha
self.CapErr = Kalpha*np.sin(alpha)*np.cos(alpha)
self.DistErra.append(self.DistErr)
def setConsign(self):
V = self.DistErr
Omega = self.CapErr
VMG = (V - Omega * self.MEntreAxes/2)/1 #1 = wheelRadius
VMD = (V + Omega * self.MEntreAxes/2)/1
self.robot.setLeftMotorSpeed(VMG)
self.robot.setRightMotorSpeed(VMD)
def draw(self):
shape2 = np.transpose(Transform.rotate(self.polygon, self.theta))
shape2 = np.transpose(Transform.translate(np.transpose(shape2), self.x, self.y))
plt.plot( shape2[0], shape2[1])
plt.plot( self.xC, self.yC , 'bx')
def update(self, dT):
self.updateOdometry(dT)
self.computeError()
self.setConsign()
if __name__== "__main__":
import main
|
[
"numpy.arctan2",
"matplotlib.pyplot.plot",
"numpy.transpose",
"Transform.rotate",
"numpy.sin",
"numpy.array",
"numpy.cos",
"numpy.sqrt"
] |
[((587, 680), 'numpy.array', 'np.array', (['[[-150, -150], [-150, 150], [150, 150], [150, -150], [-150, -150]]'], {'dtype': 'float'}), '([[-150, -150], [-150, 150], [150, 150], [150, -150], [-150, -150]],\n dtype=float)\n', (595, 680), True, 'import numpy as np\n'), ((3291, 3321), 'matplotlib.pyplot.plot', 'plt.plot', (['shape2[0]', 'shape2[1]'], {}), '(shape2[0], shape2[1])\n', (3299, 3321), True, 'import matplotlib.pyplot as plt\n'), ((3331, 3363), 'matplotlib.pyplot.plot', 'plt.plot', (['self.xC', 'self.yC', '"""bx"""'], {}), "(self.xC, self.yC, 'bx')\n", (3339, 3363), True, 'import matplotlib.pyplot as plt\n'), ((2368, 2400), 'numpy.arctan2', 'np.arctan2', (['self.YErr', 'self.XErr'], {}), '(self.YErr, self.XErr)\n', (2378, 2400), True, 'import numpy as np\n'), ((2635, 2648), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (2641, 2648), True, 'import numpy as np\n'), ((2762, 2775), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (2768, 2775), True, 'import numpy as np\n'), ((3150, 3192), 'Transform.rotate', 'Transform.rotate', (['self.polygon', 'self.theta'], {}), '(self.polygon, self.theta)\n', (3166, 3192), True, 'import Transform as Transform\n'), ((2065, 2083), 'numpy.cos', 'np.cos', (['self.theta'], {}), '(self.theta)\n', (2071, 2083), True, 'import numpy as np\n'), ((2118, 2136), 'numpy.sin', 'np.sin', (['self.theta'], {}), '(self.theta)\n', (2124, 2136), True, 'import numpy as np\n'), ((2598, 2638), 'numpy.sqrt', 'np.sqrt', (['(self.XErr ** 2 + self.YErr ** 2)'], {}), '(self.XErr ** 2 + self.YErr ** 2)\n', (2605, 2638), True, 'import numpy as np\n'), ((2748, 2761), 'numpy.sin', 'np.sin', (['alpha'], {}), '(alpha)\n', (2754, 2761), True, 'import numpy as np\n'), ((3244, 3264), 'numpy.transpose', 'np.transpose', (['shape2'], {}), '(shape2)\n', (3256, 3264), True, 'import numpy as np\n')]
|
"""
Created on 7/17/16 10:08 AM
@author: <NAME>, <NAME>
"""
from __future__ import division, print_function, absolute_import
import numpy as np
import psutil
import joblib
import time as tm
import h5py
import itertools
from numbers import Number
from multiprocessing import cpu_count
try:
from mpi4py import MPI
if MPI.COMM_WORLD.Get_size() == 1:
# mpi4py available but NOT called via mpirun or mpiexec => single node
MPI = None
except ImportError:
# mpi4py not even present! Single node by default:
MPI = None
mpi_serial_warning = False
from pyUSID.io.hdf_utils import check_if_main, check_for_old, get_attributes
from pyUSID.io.usi_data import USIDataset
from pyUSID.io.io_utils import recommend_cpu_cores, get_available_memory, format_time, format_size
"""
For hyperthreaded applications: need to tack on the additional flag as shown below
No need to specify -n 4 or whatever if you want to use all available processors
$ mpirun -use-hwthread-cpus python hello_world.py
Check the number of ranks per socket. If only 1 rank per socket - that rank is allowed to call joblib
Thus this paradigm will span the pure-mpi and mpi+joblib paradigm. Note that this does not prevent some sockets to run
in pure MPI mode while others run in MPI+joblib mode. Eventually, this should allow each rank to use jolib when the
number of ranks in a given socket are noticeably less than the number of logical cores....
The naive approach will be to simply allow all ranks to write data directly to file
Forcing only a single rank within a socket may negate performance benefits
Writing out to separate files and then merging them later on is the most performant option
Look into sub-communication worlds that can create mini worlds instead of the general COMM WORLD
https://stackoverflow.com/questions/50900655/mpi4py-create-multiple-groups-and-scatter-from-each-group
https://www.bu.edu/pasi/files/2011/01/Lisandro-Dalcin-mpi4py.pdf
No work will be necessary to figure out the new ranking within the new communicator / group - automatically assigned
from lowest value
When it is time to write the results chunks back to file.
a. If not master -> send data to master
b. If master -> gather from this smaller world and then write to file once. IF this is too much memory to handle,
then loop over each rank <-- how is this different from just looping over each rank within the new communicator and
asking it to write?:
i. receive
ii. write
iii. repeat.
A copy of the data will be made on Rank 0. ie - Rank 0 will have to hold N ranks worth of data. Meaning that each
rank can hold only around M/(2N) of data where M is the memory per node and N is the number of ranks per socket
http://mpitutorial.com/tutorials/introduction-to-groups-and-communicators/
https://info.gwdg.de/~ceulig/docs-dev/doku.php?id=en:services:application_services:high_performance_computing:mpi4py
https://rabernat.github.io/research_computing/parallel-programming-with-mpi-for-python.html
Create a giant low precision dataset. Instead of storing indices, let each rank set the completed indices to
True. The problem is that the smallest precision is 1 byte and NOT 1 bit. Even boolean = 1 byte!
See - http://docs.h5py.org/en/latest/faq.html#faq
https://support.hdfgroup.org/HDF5/hdf5-quest.html#bool
https://groups.google.com/a/continuum.io/forum/#!topic/anaconda/qFOGRTOxFTM
"""
def group_ranks_by_socket(verbose=False):
"""
Groups MPI ranks in COMM_WORLD by socket. Another way to think about this is that it assigns a master rank for each
rank such that there is a single master rank per socket (CPU). The results from this function can be used to split
MPI communicators based on the socket for intra-node communication.
This is necessary when wanting to carve up the memory for all ranks within a socket.
This is also relevant when trying to bring down the number of ranks that are writing to the HDF5 file.
This is all based on the premise that data analysis involves a fair amount of file writing and writing with
3 ranks is a lot better than writing with 100 ranks. An assumption is made that the communication between the
ranks within each socket would be faster than communicating across nodes / scokets. No assumption is made about the
names of each socket
Parameters
----------
verbose : bool, optional
Whether or not to print debugging statements
Returns
-------
master_ranks : 1D unsigned integer numpy array
Array with values that signify which rank a given rank should consider its master.
"""
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
# Step 1: Gather all the socket names:
sendbuf = MPI.Get_processor_name()
if verbose:
print('Rank: ', rank, ', sendbuf: ', sendbuf)
recvbuf = comm.allgather(sendbuf)
if verbose and rank == 0:
print('Rank: ', rank, ', recvbuf received: ', recvbuf)
# Step 2: Find all unique socket names:
recvbuf = np.array(recvbuf)
unique_sockets = np.unique(recvbuf)
if verbose and rank == 0:
print('Unique sockets: {}'.format(unique_sockets))
master_ranks = np.zeros(size, dtype=np.uint16)
for item in unique_sockets:
temp = np.where(recvbuf == item)[0]
master_ranks[temp] = temp[0]
if verbose and rank == 0:
print('Parent rank for all ranks: {}'.format(master_ranks))
return master_ranks
def to_ranges(iterable):
"""
Converts a sequence of iterables to range tuples
From https://stackoverflow.com/questions/4628333/converting-a-list-of-integers-into-range-in-python
Credits: @juanchopanza and @luca
Parameters
----------
iterable : collections.Iterable object
iterable object like a list
Returns
-------
iterable : generator object
Cast to list or similar to use
"""
iterable = sorted(set(iterable))
for key, group in itertools.groupby(enumerate(iterable),
lambda t: t[1] - t[0]):
group = list(group)
yield group[0][1], group[-1][1]
class Process(object):
"""
Encapsulates the typical steps performed when applying a processing function to a dataset.
"""
def __init__(self, h5_main, cores=None, max_mem_mb=4*1024, verbose=False):
"""
Parameters
----------
h5_main : h5py.Dataset instance
The dataset over which the analysis will be performed. This dataset should be linked to the spectroscopic
indices and values, and position indices and values datasets.
cores : uint, optional
Default - all available cores - 2
How many cores to use for the computation
max_mem_mb : uint, optional
How much memory to use for the computation. Default 1024 Mb
verbose : Boolean, (Optional, default = False)
Whether or not to print debugging statements
"""
if h5_main.file.mode != 'r+':
raise TypeError('Need to ensure that the file is in r+ mode to write results back to the file')
if MPI is not None:
# If we came here then, the user has intentionally asked for multi-node computation
comm = MPI.COMM_WORLD
self.mpi_comm = comm
self.mpi_rank = comm.Get_rank()
self.mpi_size = comm.Get_size()
if verbose:
print("Rank {} of {} on {} sees {} logical cores on the socket".format(comm.Get_rank(), comm.Get_size(),
MPI.Get_processor_name(),
cpu_count()))
# First, ensure that cores=logical cores in node. No point being economical / considerate
cores = psutil.cpu_count()
# It is sufficient if just one rank checks all this.
if self.mpi_rank == 0:
print('Working on {} ranks via MPI'.format(self.mpi_size))
# Ensure that the file is opened in the correct comm or something
if h5_main.file.driver != 'mpio':
raise TypeError('The HDF5 file should have been opened with driver="mpio". Current driver = "{}"'
''.format(h5_main.file.driver))
"""
# Not sure how to check for this correctly
messg = None
try:
if h5_main.file.comm != comm:
messg = 'The HDF5 file should have been opened with comm=MPI.COMM_WORLD. Currently comm={}'
''.format(h5_main.file.comm)
except AttributeError:
messg = 'The HDF5 file should have been opened with comm=MPI.COMM_WORLD'
if messg is not None:
raise TypeError(messg)
"""
else:
print('No mpi4py found or script was not called via mpixexec / mpirun. Assuming single node computation')
self.mpi_comm = None
self.mpi_size = 1
self.mpi_rank = 0
# Checking if dataset is "Main"
if not check_if_main(h5_main, verbose=verbose and self.mpi_rank == 0):
raise ValueError('Provided dataset is not a "Main" dataset with necessary ancillary datasets')
if MPI is not None:
MPI.COMM_WORLD.barrier()
# Not sure if we need a barrier here.
# Saving these as properties of the object:
self.h5_main = USIDataset(h5_main)
self.verbose = verbose
self._cores = None
self.__ranks_on_socket = 1
self.__socket_master_rank = 0
self._max_pos_per_read = None
self._max_mem_mb = None
# Now have to be careful here since the below properties are a function of the MPI rank
self.__start_pos = None
self.__rank_end_pos = None
self.__end_pos = None
self.__pixels_in_batch = None
# Determining the max size of the data that can be put into memory
# all ranks go through this and they need to have this value any
self._set_memory_and_cores(cores=cores, mem=max_mem_mb)
self.duplicate_h5_groups = []
self.partial_h5_groups = []
self.process_name = None # Reset this in the extended classes
self.parms_dict = None
# The name of the HDF5 dataset that should be present to signify which positions have already been computed
self.__status_dset_name = 'completed_positions'
self._results = None
self.h5_results_grp = None
# Check to see if the resuming feature has been implemented:
self.__resume_implemented = False
try:
self._get_existing_datasets()
except NotImplementedError:
if verbose and self.mpi_rank == 0:
print('It appears that this class may not be able to resume computations')
except:
# NameError for variables that don't exist
# AttributeError for self.var_name that don't exist
# TypeError (NoneType) etc.
self.__resume_implemented = True
if self.mpi_rank == 0:
print('Consider calling test() to check results before calling compute() which computes on the entire'
' dataset and writes back to the HDF5 file')
# DON'T check for duplicates since parms_dict has not yet been initialized.
# Sub classes will check by themselves if they are interested.
def __assign_job_indices(self):
"""
Sets the start and end indices for each MPI rank
"""
# First figure out what positions need to be computed
self._compute_jobs = np.where(self._h5_status_dset[()] == 0)[0]
if self.verbose and self.mpi_rank == 0:
print('Among the {} positions in this dataset, the following positions need to be computed: {}'
'.'.format(self.h5_main.shape[0], self._compute_jobs))
pos_per_rank = self._compute_jobs.size // self.mpi_size # integer division
if self.verbose and self.mpi_rank == 0:
print('Each rank is required to work on {} of the {} (remaining) positions in this dataset'
'.'.format(pos_per_rank, self._compute_jobs.size))
# The start and end indices now correspond to the indices in the incomplete jobs rather than the h5 dataset
self.__start_pos = self.mpi_rank * pos_per_rank
self.__rank_end_pos = (self.mpi_rank + 1) * pos_per_rank
self.__end_pos = int(min(self.__rank_end_pos, self.__start_pos + self._max_pos_per_read))
if self.mpi_rank == self.mpi_size - 1:
# Force the last rank to go to the end of the dataset
self.__rank_end_pos = self._compute_jobs.size
if self.verbose:
print('Rank {} will read positions {} to {} of {}'.format(self.mpi_rank, self.__start_pos,
self.__rank_end_pos, self.h5_main.shape[0]))
def _estimate_compute_time_per_pixel(self, *args, **kwargs):
"""
Estimates how long it takes to compute an average pixel's worth of data. This information should be used by the
user to limit the number of pixels that will be processed per batch to make best use of checkpointing. This
function is exposed to the developer of the child classes. An approximate can be derived if it is simpler
Returns
-------
"""
chosen_pos = np.random.randint(0, high=self.h5_main.shape[0]-1, size=5)
t0 = tm.time()
_ = parallel_compute(self.h5_main[chosen_pos, :], self._map_function, cores=1,
lengthy_computation=False, func_args=args, func_kwargs=kwargs, verbose=False)
return (tm.time() - t0) / len(chosen_pos)
def _get_pixels_in_current_batch(self):
"""
Returns the indices of the pixels that will be processed in this batch.
Returns
-------
pixels_in_batch : numpy.ndarray
1D array of unsigned integers denoting the pixels that will be read, processed, and written back to
"""
return self.__pixels_in_batch
def test(self, **kwargs):
"""
Tests the process on a subset (for example a pixel) of the whole data. The class can be reinstantiated with
improved parameters and tested repeatedly until the user is content, at which point the user can call
compute() on the whole dataset. This is not a function that is expected to be called in mpi
Parameters
----------
kwargs - dict, optional
keyword arguments to test the process
Returns
-------
"""
# All children classes should call super() OR ensure that they only work for self.mpi_rank == 0
raise NotImplementedError('test_on_subset has not yet been implemented')
def _check_for_duplicates(self):
"""
Checks for instances where the process was applied to the same dataset with the same parameters
Returns
-------
duplicate_h5_groups : list of h5py.Group objects
List of groups satisfying the above conditions
"""
if self.verbose and self.mpi_rank == 0:
print('Checking for duplicates:')
# This list will contain completed runs only
duplicate_h5_groups = check_for_old(self.h5_main, self.process_name, new_parms=self.parms_dict)
partial_h5_groups = []
# First figure out which ones are partially completed:
if len(duplicate_h5_groups) > 0:
for index, curr_group in enumerate(duplicate_h5_groups):
"""
Earlier, we only checked the 'last_pixel' but to be rigorous we should check self.__status_dset_name
The last_pixel attribute check may be deprecated in the future.
Note that legacy computations did not have this dataset. We can add to partially computed datasets
"""
if self.__status_dset_name in curr_group.keys():
# Case 1: Modern Process results:
status_dset = curr_group[self.__status_dset_name]
if not isinstance(status_dset, h5py.Dataset):
# We should not come here if things were implemented correctly
if self.mpi_rank == 0:
print('Results group: {} contained an object named: {} that should have been a dataset'
'.'.format(curr_group, self.__status_dset_name))
if self.h5_main.shape[0] != status_dset.shape[0] or len(status_dset.shape) > 1 or \
status_dset.dtype != np.uint8:
if self.mpi_rank == 0:
print('Status dataset: {} was not of the expected shape or datatype'.format(status_dset))
# Finally, check how far the computation was completed.
if len(np.where(status_dset[()] == 0)[0]) == 0:
# remove from duplicates and move to partial
partial_h5_groups.append(duplicate_h5_groups.pop(index))
# Let's write the legacy attribute for safety
curr_group.attrs['last_pixel'] = self.h5_main.shape[0]
# No further checks necessary
continue
else:
# Optionally calculate how much was completed:
if self.mpi_rank == 0:
percent_complete = int(100 * len(np.where(status_dset[()] == 0)[0]) / status_dset.shape[0])
print('Group: {}: computation was {}% completed'.format(curr_group, percent_complete))
# Case 2: Legacy results group:
if 'last_pixel' not in curr_group.attrs.keys():
if self.mpi_rank == 0:
# Should not be coming here at all
print('Group: {} had neither the status HDF5 dataset or the legacy attribute: "last_pixel"'
'.'.format(curr_group))
# Not sure what to do with such groups. Don't consider them in the future
duplicate_h5_groups.pop(index)
continue
# Finally, do the legacy test:
if curr_group.attrs['last_pixel'] < self.h5_main.shape[0]:
# Should we create the dataset here, to make the group future-proof?
# remove from duplicates and move to partial
partial_h5_groups.append(duplicate_h5_groups.pop(index))
if len(duplicate_h5_groups) > 0 and self.mpi_rank == 0:
print('Note: ' + self.process_name + ' has already been performed with the same parameters before. '
'These results will be returned by compute() by default. '
'Set override to True to force fresh computation')
print(duplicate_h5_groups)
if len(partial_h5_groups) > 0 and self.mpi_rank == 0:
print('Note: ' + self.process_name + ' has already been performed PARTIALLY with the same parameters. '
'compute() will resuming computation in the last group below. '
'To choose a different group call use_patial_computation()'
'Set override to True to force fresh computation or resume from a '
'data group besides the last in the list.')
print(partial_h5_groups)
return duplicate_h5_groups, partial_h5_groups
def use_partial_computation(self, h5_partial_group=None):
"""
Extracts the necessary parameters from the provided h5 group to resume computation
Parameters
----------
h5_partial_group : h5py.Group object
Group containing partially computed results
"""
# Attempt to automatically take partial results
if h5_partial_group is None:
if len(self.partial_h5_groups) < 1:
raise ValueError('No group was found with partial results and no such group was provided')
h5_partial_group = self.partial_h5_groups[-1]
else:
# Make sure that this group is among the legal ones already discovered:
if h5_partial_group not in self.partial_h5_groups:
raise ValueError('Provided group does not appear to be in the list of discovered groups')
self.parms_dict = get_attributes(h5_partial_group)
self.h5_results_grp = h5_partial_group
def _set_memory_and_cores(self, cores=None, mem=None):
"""
Checks hardware limitations such as memory, # cpus and sets the recommended datachunk sizes and the
number of cores to be used by analysis methods. This function can work with clusters with heterogeneous
memory sizes (e.g. CADES SHPC Condo).
Parameters
----------
cores : uint, optional
Default - 1
How many cores to use for the computation
mem : uint, optional
Default - 1024
The amount a memory in Mb to use in the computation
"""
if MPI is None:
min_free_cores = 1 + int(psutil.cpu_count() > 4)
if cores is None:
self._cores = max(1, psutil.cpu_count() - min_free_cores)
else:
if not isinstance(cores, int):
raise TypeError('cores should be an integer but got: {}'.format(cores))
cores = int(abs(cores))
self._cores = max(1, min(psutil.cpu_count(), cores))
self.__socket_master_rank = 0
self.__ranks_on_socket = 1
else:
# user-provided input cores will simply be ignored in an effort to use the entire CPU
ranks_by_socket = group_ranks_by_socket(verbose=self.verbose)
self.__socket_master_rank = ranks_by_socket[self.mpi_rank]
# which ranks in this socket?
ranks_on_this_socket = np.where(ranks_by_socket == self.__socket_master_rank)[0]
# how many in this socket?
self.__ranks_on_socket = ranks_on_this_socket.size
# Force usage of all available memory
mem = None
self._cores = 1
# Disabling the following line since mpi4py and joblib didn't play well for Bayesian Inference
# self._cores = self.__cores_per_rank = psutil.cpu_count() // self.__ranks_on_socket
# TODO: Convert all to bytes!
_max_mem_mb = get_available_memory() / 1024 ** 2 # in MB
if mem is None:
mem = _max_mem_mb
else:
if not isinstance(mem, int):
raise TypeError('mem must be a whole number')
mem = abs(mem)
self._max_mem_mb = min(_max_mem_mb, mem)
# Remember that multiple processes (either via MPI or joblib) will share this socket
max_data_chunk = self._max_mem_mb / (self._cores * self.__ranks_on_socket)
# Now calculate the number of positions OF RAW DATA ONLY that can be stored in memory in one go PER RANK
mb_per_position = self.h5_main.dtype.itemsize * self.h5_main.shape[1] / 1024 ** 2
self._max_pos_per_read = int(np.floor(max_data_chunk / mb_per_position))
if self.verbose and self.mpi_rank == self.__socket_master_rank:
# expected to be the same for all ranks so just use this.
print('Rank {} - on socket with {} logical cores and {} avail. RAM shared by {} ranks each given {} cores'
'.'.format(self.__socket_master_rank, psutil.cpu_count(), format_size(_max_mem_mb * 1024**2, 2),
self.__ranks_on_socket, self._cores))
print('Allowed to read {} pixels per chunk'.format(self._max_pos_per_read))
@staticmethod
def _map_function(*args, **kwargs):
"""
The function that manipulates the data on a single instance (position). This will be used by _unit_computation()
to process a chunk of data in parallel
Parameters
----------
args : list
arguments to the function in the correct order
kwargs : dictionary
keyword arguments to the function
Returns
-------
object
"""
raise NotImplementedError('Please override the _unit_function specific to your process')
def _read_data_chunk(self):
"""
Reads a chunk of data for the intended computation into memory
"""
if self.__start_pos < self.__rank_end_pos:
self.__end_pos = int(min(self.__rank_end_pos, self.__start_pos + self._max_pos_per_read))
# DON'T DIRECTLY apply the start and end indices anymore to the h5 dataset. Find out what it means first
self.__pixels_in_batch = self._compute_jobs[self.__start_pos: self.__end_pos]
self.data = self.h5_main[self.__pixels_in_batch, :]
if self.verbose:
print('Rank {} - Read positions: {}'.format(self.mpi_rank, self.__pixels_in_batch, self.__rank_end_pos))
# DON'T update the start position
else:
if self.verbose:
print('Rank {} - Finished reading all data!'.format(self.mpi_rank))
self.data = None
def _write_results_chunk(self):
"""
Writes the computed results into appropriate datasets.
This needs to be rewritten since the processed data is expected to be at least as large as the dataset
"""
# Now update the start position
self.__start_pos = self.__end_pos
# This line can remain as is
raise NotImplementedError('Please override the _set_results specific to your process')
def _create_results_datasets(self):
"""
Process specific call that will write the h5 group, guess dataset, corresponding spectroscopic datasets and also
link the guess dataset to the spectroscopic datasets. It is recommended that the ancillary datasets be populated
within this function.
"""
raise NotImplementedError('Please override the _create_results_datasets specific to your process')
def __create_compute_status_dataset(self):
"""
Creates a dataset that keeps track of what pixels / rows have already been computed. Users are not expected to
extend / modify this function.
"""
# TODO: This will fail for Fitter and Image Processing class which will need to run Process twice . Need to allow room for customization
# Check to make sure that such a group doesn't already exist
if self.__status_dset_name in self.h5_results_grp.keys():
self._h5_status_dset = self.h5_results_grp[self.__status_dset_name]
if not isinstance(self._h5_status_dset, h5py.Dataset):
raise ValueError('Provided results group: {} contains an expected object ({}) that is not a dataset'
'.'.format(self.h5_results_grp, self._h5_status_dset))
if self.h5_main.shape[0] != self._h5_status_dset.shape[0] or len(self._h5_status_dset.shape) > 1 or \
self._h5_status_dset.dtype != np.uint8:
if self.mpi_rank == 0:
raise ValueError('Status dataset: {} was not of the expected shape or datatype'
'.'.format(self._h5_status_dset))
else:
self._h5_status_dset = self.h5_results_grp.create_dataset(self.__status_dset_name, dtype=np.uint8,
shape=(self.h5_main.shape[0],))
# Could be fresh computation or resuming from a legacy computation
if 'last_pixel' in self.h5_results_grp.attrs.keys():
completed_pixels = self.h5_results_grp.attrs['last_pixel']
if completed_pixels > 0:
self._h5_status_dset[:completed_pixels] = 1
def _get_existing_datasets(self):
"""
The purpose of this function is to allow processes to resume from partly computed results
Start with self.h5_results_grp
"""
raise NotImplementedError('Please override the _get_existing_datasets specific to your process')
def _unit_computation(self, *args, **kwargs):
"""
The unit computation that is performed per data chunk. This allows room for any data pre / post-processing
as well as multiple calls to parallel_compute if necessary
"""
# TODO: Try to use the functools.partials to preconfigure the map function
# cores = number of processes / rank here
self._results = parallel_compute(self.data, self._map_function, cores=self._cores,
lengthy_computation=False,
func_args=args, func_kwargs=kwargs,
verbose=self.verbose)
def compute(self, override=False, *args, **kwargs):
"""
Creates placeholders for the results, applies the unit computation to chunks of the dataset
Parameters
----------
override : bool, optional. default = False
By default, compute will simply return duplicate results to avoid recomputing or resume computation on a
group with partial results. Set to True to force fresh computation.
args : list
arguments to the mapped function in the correct order
kwargs : dictionary
keyword arguments to the mapped function
Returns
-------
h5_results_grp : h5py.Group object
Group containing all the results
"""
class SimpleFIFO(object):
"""
Simple class that maintains a moving average of some numbers.
"""
def __init__(self, length=5):
"""
Create a SimpleFIFO object
Parameters
----------
length : unsigned integer
Number of values that need to be maintained for the moving average
"""
self.__queue = list()
if not isinstance(length, int):
raise TypeError('length must be a positive integer')
if length <= 0:
raise ValueError('length must be a positive integer')
self.__max_length = length
self.__count = 0
def put(self, item):
"""
Adds the item to the internal queue. If the size of the queue exceeds its capacity, the oldest
item is removed.
Parameters
----------
item : float or int
Any real valued number
"""
if (not isinstance(item, Number)) or isinstance(item, complex):
raise TypeError('Provided item: {} is not a Number'.format(item))
self.__queue.append(item)
self.__count += 1
if len(self.__queue) > self.__max_length:
_ = self.__queue.pop(0)
def get_mean(self):
"""
Returns the average of the elements within the queue
Returns
-------
avg : number.Number
Mean of all elements within the queue
"""
return np.mean(self.__queue)
def get_cycles(self):
"""
Returns the number of items that have been added to the queue in total
Returns
-------
count : int
number of items that have been added to the queue in total
"""
return self.__count
if not override:
if len(self.duplicate_h5_groups) > 0:
if self.mpi_rank == 0:
print('Returned previously computed results at ' + self.duplicate_h5_groups[-1].name)
return self.duplicate_h5_groups[-1]
elif len(self.partial_h5_groups) > 0:
if self.mpi_rank == 0:
print('Resuming computation in group: ' + self.partial_h5_groups[-1].name)
self.use_partial_computation()
resuming = False
if self.h5_results_grp is None:
# starting fresh
if self.verbose and self.mpi_rank == 0:
print('Creating HDF5 group and datasets to hold results')
self._create_results_datasets()
else:
# resuming from previous checkpoint
resuming = True
self._get_existing_datasets()
self.__create_compute_status_dataset()
if resuming and self.mpi_rank == 0:
percent_complete = int(100 * len(np.where(self._h5_status_dset[()] == 0)[0]) /
self._h5_status_dset.shape[0])
print('Resuming computation. {}% completed already'.format(percent_complete))
self.__assign_job_indices()
# Not sure if this is necessary but I don't think it would hurt either
if self.mpi_comm is not None:
self.mpi_comm.barrier()
compute_times = SimpleFIFO(5)
write_times = SimpleFIFO(5)
orig_rank_start = self.__start_pos
if self.mpi_rank == 0 and self.mpi_size == 1:
if self.__resume_implemented:
print('\tThis class (likely) supports interruption and resuming of computations!\n'
'\tIf you are operating in a python console, press Ctrl+C or Cmd+C to abort\n'
'\tIf you are in a Jupyter notebook, click on "Kernel">>"Interrupt"\n'
'\tIf you are operating on a cluster and your job gets killed, re-run the job to resume\n')
else:
print('\tThis class does NOT support interruption and resuming of computations.\n'
'\tIn order to enable this feature, simply implement the _get_existing_datasets() function')
if self.verbose and self.mpi_rank == self.__socket_master_rank:
print('Rank: {} - with nothing loaded has {} free memory'
''.format(self.mpi_rank, format_size(get_available_memory())))
self._read_data_chunk()
if self.mpi_comm is not None:
self.mpi_comm.barrier()
if self.verbose and self.mpi_rank == self.__socket_master_rank:
print('Rank: {} - with only raw data loaded has {} free memory'
''.format(self.mpi_rank, format_size(get_available_memory())))
while self.data is not None:
num_jobs_in_batch = self.__end_pos - self.__start_pos
t_start_1 = tm.time()
self._unit_computation(*args, **kwargs)
comp_time = np.round(tm.time() - t_start_1, decimals=2) # in seconds
time_per_pix = comp_time / num_jobs_in_batch
compute_times.put(time_per_pix)
if self.verbose:
print('Rank {} - computed chunk in {} or {} per pixel. Average: {} per pixel'
'.'.format(self.mpi_rank, format_time(comp_time), format_time(time_per_pix),
format_time(compute_times.get_mean())))
# Ranks can become memory starved. Check memory usage - raw data + results in memory at this point
if self.verbose and self.mpi_rank == self.__socket_master_rank:
print('Rank: {} - now holding onto raw data + results has {} free memory'
''.format(self.mpi_rank, format_size(get_available_memory())))
t_start_2 = tm.time()
self._write_results_chunk()
# NOW, update the positions. Users are NOT allowed to touch start and end pos
self.__start_pos = self.__end_pos
# Leaving in this provision that will allow restarting of processes
if self.mpi_size == 1:
self.h5_results_grp.attrs['last_pixel'] = self.__end_pos
# Child classes don't even have to worry about flushing. Process will do it.
self.h5_main.file.flush()
dump_time = np.round(tm.time() - t_start_2, decimals=2)
write_times.put(dump_time / num_jobs_in_batch)
if self.verbose:
print('Rank {} - wrote its {} pixel chunk in {}'.format(self.mpi_rank,
num_jobs_in_batch,
format_time(dump_time)))
time_remaining = (self.__rank_end_pos - self.__end_pos) * \
(compute_times.get_mean() + write_times.get_mean())
if self.verbose or self.mpi_rank == 0:
percent_complete = int(100 * (self.__end_pos - orig_rank_start) /
(self.__rank_end_pos - orig_rank_start))
print('Rank {} - {}% complete. Time remaining: {}'.format(self.mpi_rank, percent_complete,
format_time(time_remaining)))
# All ranks should mark the pixels for this batch as completed. 'last_pixel' attribute will be updated later
# Setting each section to 1 independently
for section in to_ranges(self.__pixels_in_batch):
self._h5_status_dset[section[0]: section[1]+1] = 1
self._read_data_chunk()
if self.verbose:
print('Rank {} - Finished computing all jobs!'.format(self.mpi_rank))
if self.mpi_comm is not None:
self.mpi_comm.barrier()
if self.mpi_rank == 0:
print('Finished processing the entire dataset!')
# Update the legacy 'last_pixel' attribute here:
if self.mpi_rank == 0:
self.h5_results_grp.attrs['last_pixel'] = self.h5_main.shape[0]
return self.h5_results_grp
def parallel_compute(data, func, cores=1, lengthy_computation=False, func_args=None, func_kwargs=None, verbose=False):
"""
Computes the provided function using multiple cores using the joblib library
Parameters
----------
data : numpy.ndarray
Data to map function to. Function will be mapped to the first axis of data
func : callable
Function to map to data
cores : uint, optional
Number of logical cores to use to compute
Default - 1 (serial computation)
lengthy_computation : bool, optional
Whether or not each computation is expected to take substantial time.
Sometimes the time for adding more cores can outweigh the time per core
Default - False
func_args : list, optional
arguments to be passed to the function
func_kwargs : dict, optional
keyword arguments to be passed onto function
verbose : bool, optional. default = False
Whether or not to print statements that aid in debugging
Returns
-------
results : list
List of computational results
"""
if not callable(func):
raise TypeError('Function argument is not callable')
if not isinstance(data, np.ndarray):
raise TypeError('data must be a numpy array')
if func_args is None:
func_args = list()
else:
if isinstance(func_args, tuple):
func_args = list(func_args)
if not isinstance(func_args, list):
raise TypeError('Arguments to the mapped function should be specified as a list')
if func_kwargs is None:
func_kwargs = dict()
else:
if not isinstance(func_kwargs, dict):
raise TypeError('Keyword arguments to the mapped function should be specified via a dictionary')
req_cores = cores
if MPI is not None:
rank = MPI.COMM_WORLD.Get_rank()
# Was unable to get the MPI + joblib framework to work. Did not compute anything at all. Just froze
cores = 1
else:
rank = 0
cores = recommend_cpu_cores(data.shape[0],
requested_cores=cores,
lengthy_computation=lengthy_computation,
verbose=verbose)
if verbose:
print('Rank {} starting computing on {} cores (requested {} cores)'.format(rank, cores, req_cores))
if cores > 1:
values = [joblib.delayed(func)(x, *func_args, **func_kwargs) for x in data]
results = joblib.Parallel(n_jobs=cores)(values)
# Finished reading the entire data set
print('Rank {} finished parallel computation'.format(rank))
else:
if verbose:
print("Rank {} computing serially ...".format(rank))
# List comprehension vs map vs for loop?
# https://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map
results = [func(vector, *func_args, **func_kwargs) for vector in data]
return results
|
[
"numpy.floor",
"numpy.random.randint",
"numpy.mean",
"pyUSID.io.io_utils.recommend_cpu_cores",
"mpi4py.MPI.COMM_WORLD.barrier",
"numpy.unique",
"psutil.cpu_count",
"multiprocessing.cpu_count",
"mpi4py.MPI.Get_processor_name",
"mpi4py.MPI.COMM_WORLD.Get_size",
"pyUSID.io.io_utils.get_available_memory",
"mpi4py.MPI.COMM_WORLD.Get_rank",
"pyUSID.io.io_utils.format_size",
"pyUSID.io.io_utils.format_time",
"pyUSID.io.usi_data.USIDataset",
"pyUSID.io.hdf_utils.check_if_main",
"numpy.zeros",
"time.time",
"pyUSID.io.hdf_utils.get_attributes",
"pyUSID.io.hdf_utils.check_for_old",
"numpy.array",
"numpy.where",
"joblib.Parallel",
"joblib.delayed"
] |
[((4798, 4822), 'mpi4py.MPI.Get_processor_name', 'MPI.Get_processor_name', ([], {}), '()\n', (4820, 4822), False, 'from mpi4py import MPI\n'), ((5083, 5100), 'numpy.array', 'np.array', (['recvbuf'], {}), '(recvbuf)\n', (5091, 5100), True, 'import numpy as np\n'), ((5122, 5140), 'numpy.unique', 'np.unique', (['recvbuf'], {}), '(recvbuf)\n', (5131, 5140), True, 'import numpy as np\n'), ((5250, 5281), 'numpy.zeros', 'np.zeros', (['size'], {'dtype': 'np.uint16'}), '(size, dtype=np.uint16)\n', (5258, 5281), True, 'import numpy as np\n'), ((326, 351), 'mpi4py.MPI.COMM_WORLD.Get_size', 'MPI.COMM_WORLD.Get_size', ([], {}), '()\n', (349, 351), False, 'from mpi4py import MPI\n'), ((9645, 9664), 'pyUSID.io.usi_data.USIDataset', 'USIDataset', (['h5_main'], {}), '(h5_main)\n', (9655, 9664), False, 'from pyUSID.io.usi_data import USIDataset\n'), ((13685, 13745), 'numpy.random.randint', 'np.random.randint', (['(0)'], {'high': '(self.h5_main.shape[0] - 1)', 'size': '(5)'}), '(0, high=self.h5_main.shape[0] - 1, size=5)\n', (13702, 13745), True, 'import numpy as np\n'), ((13757, 13766), 'time.time', 'tm.time', ([], {}), '()\n', (13764, 13766), True, 'import time as tm\n'), ((15593, 15666), 'pyUSID.io.hdf_utils.check_for_old', 'check_for_old', (['self.h5_main', 'self.process_name'], {'new_parms': 'self.parms_dict'}), '(self.h5_main, self.process_name, new_parms=self.parms_dict)\n', (15606, 15666), False, 'from pyUSID.io.hdf_utils import check_if_main, check_for_old, get_attributes\n'), ((21011, 21043), 'pyUSID.io.hdf_utils.get_attributes', 'get_attributes', (['h5_partial_group'], {}), '(h5_partial_group)\n', (21025, 21043), False, 'from pyUSID.io.hdf_utils import check_if_main, check_for_old, get_attributes\n'), ((40598, 40623), 'mpi4py.MPI.COMM_WORLD.Get_rank', 'MPI.COMM_WORLD.Get_rank', ([], {}), '()\n', (40621, 40623), False, 'from mpi4py import MPI\n'), ((40793, 40912), 'pyUSID.io.io_utils.recommend_cpu_cores', 'recommend_cpu_cores', (['data.shape[0]'], {'requested_cores': 'cores', 'lengthy_computation': 'lengthy_computation', 'verbose': 'verbose'}), '(data.shape[0], requested_cores=cores,\n lengthy_computation=lengthy_computation, verbose=verbose)\n', (40812, 40912), False, 'from pyUSID.io.io_utils import recommend_cpu_cores, get_available_memory, format_time, format_size\n'), ((5330, 5355), 'numpy.where', 'np.where', (['(recvbuf == item)'], {}), '(recvbuf == item)\n', (5338, 5355), True, 'import numpy as np\n'), ((7964, 7982), 'psutil.cpu_count', 'psutil.cpu_count', ([], {}), '()\n', (7980, 7982), False, 'import psutil\n'), ((9286, 9348), 'pyUSID.io.hdf_utils.check_if_main', 'check_if_main', (['h5_main'], {'verbose': '(verbose and self.mpi_rank == 0)'}), '(h5_main, verbose=verbose and self.mpi_rank == 0)\n', (9299, 9348), False, 'from pyUSID.io.hdf_utils import check_if_main, check_for_old, get_attributes\n'), ((9498, 9522), 'mpi4py.MPI.COMM_WORLD.barrier', 'MPI.COMM_WORLD.barrier', ([], {}), '()\n', (9520, 9522), False, 'from mpi4py import MPI\n'), ((11861, 11900), 'numpy.where', 'np.where', (['(self._h5_status_dset[()] == 0)'], {}), '(self._h5_status_dset[()] == 0)\n', (11869, 11900), True, 'import numpy as np\n'), ((23108, 23130), 'pyUSID.io.io_utils.get_available_memory', 'get_available_memory', ([], {}), '()\n', (23128, 23130), False, 'from pyUSID.io.io_utils import recommend_cpu_cores, get_available_memory, format_time, format_size\n'), ((23818, 23860), 'numpy.floor', 'np.floor', (['(max_data_chunk / mb_per_position)'], {}), '(max_data_chunk / mb_per_position)\n', (23826, 23860), True, 'import numpy as np\n'), ((35478, 35487), 'time.time', 'tm.time', ([], {}), '()\n', (35485, 35487), True, 'import time as tm\n'), ((36409, 36418), 'time.time', 'tm.time', ([], {}), '()\n', (36416, 36418), True, 'import time as tm\n'), ((41263, 41292), 'joblib.Parallel', 'joblib.Parallel', ([], {'n_jobs': 'cores'}), '(n_jobs=cores)\n', (41278, 41292), False, 'import joblib\n'), ((13977, 13986), 'time.time', 'tm.time', ([], {}), '()\n', (13984, 13986), True, 'import time as tm\n'), ((22582, 22636), 'numpy.where', 'np.where', (['(ranks_by_socket == self.__socket_master_rank)'], {}), '(ranks_by_socket == self.__socket_master_rank)\n', (22590, 22636), True, 'import numpy as np\n'), ((32123, 32144), 'numpy.mean', 'np.mean', (['self.__queue'], {}), '(self.__queue)\n', (32130, 32144), True, 'import numpy as np\n'), ((41179, 41199), 'joblib.delayed', 'joblib.delayed', (['func'], {}), '(func)\n', (41193, 41199), False, 'import joblib\n'), ((24180, 24198), 'psutil.cpu_count', 'psutil.cpu_count', ([], {}), '()\n', (24196, 24198), False, 'import psutil\n'), ((24200, 24239), 'pyUSID.io.io_utils.format_size', 'format_size', (['(_max_mem_mb * 1024 ** 2)', '(2)'], {}), '(_max_mem_mb * 1024 ** 2, 2)\n', (24211, 24239), False, 'from pyUSID.io.io_utils import recommend_cpu_cores, get_available_memory, format_time, format_size\n'), ((35575, 35584), 'time.time', 'tm.time', ([], {}), '()\n', (35582, 35584), True, 'import time as tm\n'), ((36945, 36954), 'time.time', 'tm.time', ([], {}), '()\n', (36952, 36954), True, 'import time as tm\n'), ((7714, 7738), 'mpi4py.MPI.Get_processor_name', 'MPI.Get_processor_name', ([], {}), '()\n', (7736, 7738), False, 'from mpi4py import MPI\n'), ((7827, 7838), 'multiprocessing.cpu_count', 'cpu_count', ([], {}), '()\n', (7836, 7838), False, 'from multiprocessing import cpu_count\n'), ((21771, 21789), 'psutil.cpu_count', 'psutil.cpu_count', ([], {}), '()\n', (21787, 21789), False, 'import psutil\n'), ((21863, 21881), 'psutil.cpu_count', 'psutil.cpu_count', ([], {}), '()\n', (21879, 21881), False, 'import psutil\n'), ((22138, 22156), 'psutil.cpu_count', 'psutil.cpu_count', ([], {}), '()\n', (22154, 22156), False, 'import psutil\n'), ((34984, 35006), 'pyUSID.io.io_utils.get_available_memory', 'get_available_memory', ([], {}), '()\n', (35004, 35006), False, 'from pyUSID.io.io_utils import recommend_cpu_cores, get_available_memory, format_time, format_size\n'), ((35322, 35344), 'pyUSID.io.io_utils.get_available_memory', 'get_available_memory', ([], {}), '()\n', (35342, 35344), False, 'from pyUSID.io.io_utils import recommend_cpu_cores, get_available_memory, format_time, format_size\n'), ((35897, 35919), 'pyUSID.io.io_utils.format_time', 'format_time', (['comp_time'], {}), '(comp_time)\n', (35908, 35919), False, 'from pyUSID.io.io_utils import recommend_cpu_cores, get_available_memory, format_time, format_size\n'), ((35921, 35946), 'pyUSID.io.io_utils.format_time', 'format_time', (['time_per_pix'], {}), '(time_per_pix)\n', (35932, 35946), False, 'from pyUSID.io.io_utils import recommend_cpu_cores, get_available_memory, format_time, format_size\n'), ((37319, 37341), 'pyUSID.io.io_utils.format_time', 'format_time', (['dump_time'], {}), '(dump_time)\n', (37330, 37341), False, 'from pyUSID.io.io_utils import recommend_cpu_cores, get_available_memory, format_time, format_size\n'), ((37893, 37920), 'pyUSID.io.io_utils.format_time', 'format_time', (['time_remaining'], {}), '(time_remaining)\n', (37904, 37920), False, 'from pyUSID.io.io_utils import recommend_cpu_cores, get_available_memory, format_time, format_size\n'), ((36358, 36380), 'pyUSID.io.io_utils.get_available_memory', 'get_available_memory', ([], {}), '()\n', (36378, 36380), False, 'from pyUSID.io.io_utils import recommend_cpu_cores, get_available_memory, format_time, format_size\n'), ((17247, 17277), 'numpy.where', 'np.where', (['(status_dset[()] == 0)'], {}), '(status_dset[()] == 0)\n', (17255, 17277), True, 'import numpy as np\n'), ((33538, 33577), 'numpy.where', 'np.where', (['(self._h5_status_dset[()] == 0)'], {}), '(self._h5_status_dset[()] == 0)\n', (33546, 33577), True, 'import numpy as np\n'), ((17879, 17909), 'numpy.where', 'np.where', (['(status_dset[()] == 0)'], {}), '(status_dset[()] == 0)\n', (17887, 17909), True, 'import numpy as np\n')]
|
import numpy as np
class TicTacToeGame:
def __init__(self, size):
self.m_SizeSize = size;
self.m_Grid = np.zeros((size, size), np.int8)
self.m_Grid.fill(-1)
self.m_CurentPlayer = 0
def Move(self, player, row, col):
if self.IsMoveAllowed(player, row, col) == True:
self.m_Grid[row][col] = player
def WillMoveWin(self, player, row, col):
if not self.IsMoveAllowed(player, row, col):
return False
# check horizontal
hasWon = True
for i in range(self.m_SizeSize):
colIdx = (col + i) % self.m_SizeSize
hasWon = hasWon and self.m_Grid[row][colIdx] == player
# Check vertical win
if not hasWon:
hasWon = True
for i in range(self.m_SizeSize):
rowIdx = (row + i) % self.m_SizeSize
hasWon = hasWon and self.m_Grid[row][colIdx] == player
if not hasWon and row == 1 and col == 1:
hasWon = True
# Test diagonal from upper left to lower right
for i in range(self.m_SizeSize):
hasWon = hasWon and self.m_Grid[i][i] == player
if hasWon:
return True
# Test diagnol from lower left to upper right
hasWon = True
for i in range(self.m_SizeSize):
hasWon = hasWon and self.m_Grid[2 - i][i] == player
return hasWon
def RankMove(self, player, row, col):
reward = 0
if not self.IsMoveAllowed(player, row, col):
reward = reward + -100
backup = self.m_Grid[row][col]
self.m_Grid[row][col] = player
if self.WillMoveWin(player, row, col):
reward = reward + 1000
self.m_Grid[row][col] = backup
return reward
def IsMoveAllowed(self, player, row, col):
if int(row) in range(self.m_SizeSize) and int(col) in range(self.m_SizeSize):
return self.m_Grid[row][col] == -1
else:
return False
def NoEmptySpaces(self):
for i in range(self.m_SizeSize):
for j in range(self.m_SizeSize):
if self.m_Grid[i][j] == -1:
return False
return True
def Render(self):
# print (self.m_Grid)
print("")
for row in range(self.m_SizeSize):
lineTxt = ""
for col in range(self.m_SizeSize):
if (self.m_Grid[row][col] == 0):
lineTxt += " O"
elif (self.m_Grid[row][col] == 0):
lineTxt += " X"
else:
lineTxt += " _"
print(lineTxt)
|
[
"numpy.zeros"
] |
[((134, 165), 'numpy.zeros', 'np.zeros', (['(size, size)', 'np.int8'], {}), '((size, size), np.int8)\n', (142, 165), True, 'import numpy as np\n')]
|
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import unittest
from unittest import TestCase
import pkgutil
import io
import numpy as np
import pandas as pd
from kats.consts import TimeSeriesData
from kats.models.harmonic_regression import (
HarmonicRegressionModel,
HarmonicRegressionParams,
)
def load_data(file_name):
ROOT = "kats"
if "kats" in os.getcwd().lower():
path = "data/"
else:
path = "kats/data/"
data_object = pkgutil.get_data(ROOT, path + file_name)
return pd.read_csv(io.BytesIO(data_object), encoding="utf8")
class testHarmonicRegression(TestCase):
def setUp(self):
times = pd.to_datetime(
np.arange(start=1576195200, stop=1577836801, step=60 * 60), unit="s"
)
self.series_times = pd.Series(times)
harms = HarmonicRegressionModel.fourier_series(self.series_times, 24, 3)
self.harms_sum = np.sum([1, 1, 1, 1, 1, 1] * harms, axis=1)
self.data = TimeSeriesData(
pd.DataFrame({"time": self.series_times, "values": self.harms_sum})
)
self.params = HarmonicRegressionParams(24, 3)
def test_fit_and_predict(self) -> None:
hrm = HarmonicRegressionModel(self.data, self.params)
hrm.fit()
self.assertIsNotNone(hrm.params)
# pyre-fixme[16]: `HarmonicRegressionModel` has no attribute `harms`.
self.assertIsNotNone(hrm.harms)
# pyre-fixme[6]: Expected `Series` for 1st param but got
# `Union[pd.core.frame.DataFrame, pd.core.series.Series]`.
preds = hrm.predict(self.series_times.head(1))
self.assertAlmostEqual(preds["fcst"][0], self.harms_sum[0], delta=0.0001)
if __name__ == "__main__":
unittest.main()
|
[
"unittest.main",
"pkgutil.get_data",
"io.BytesIO",
"pandas.DataFrame",
"numpy.sum",
"kats.models.harmonic_regression.HarmonicRegressionModel",
"os.getcwd",
"kats.models.harmonic_regression.HarmonicRegressionParams",
"pandas.Series",
"kats.models.harmonic_regression.HarmonicRegressionModel.fourier_series",
"numpy.arange"
] |
[((606, 646), 'pkgutil.get_data', 'pkgutil.get_data', (['ROOT', '(path + file_name)'], {}), '(ROOT, path + file_name)\n', (622, 646), False, 'import pkgutil\n'), ((1861, 1876), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1874, 1876), False, 'import unittest\n'), ((670, 693), 'io.BytesIO', 'io.BytesIO', (['data_object'], {}), '(data_object)\n', (680, 693), False, 'import io\n'), ((926, 942), 'pandas.Series', 'pd.Series', (['times'], {}), '(times)\n', (935, 942), True, 'import pandas as pd\n'), ((959, 1023), 'kats.models.harmonic_regression.HarmonicRegressionModel.fourier_series', 'HarmonicRegressionModel.fourier_series', (['self.series_times', '(24)', '(3)'], {}), '(self.series_times, 24, 3)\n', (997, 1023), False, 'from kats.models.harmonic_regression import HarmonicRegressionModel, HarmonicRegressionParams\n'), ((1049, 1091), 'numpy.sum', 'np.sum', (['([1, 1, 1, 1, 1, 1] * harms)'], {'axis': '(1)'}), '([1, 1, 1, 1, 1, 1] * harms, axis=1)\n', (1055, 1091), True, 'import numpy as np\n'), ((1241, 1272), 'kats.models.harmonic_regression.HarmonicRegressionParams', 'HarmonicRegressionParams', (['(24)', '(3)'], {}), '(24, 3)\n', (1265, 1272), False, 'from kats.models.harmonic_regression import HarmonicRegressionModel, HarmonicRegressionParams\n'), ((1332, 1379), 'kats.models.harmonic_regression.HarmonicRegressionModel', 'HarmonicRegressionModel', (['self.data', 'self.params'], {}), '(self.data, self.params)\n', (1355, 1379), False, 'from kats.models.harmonic_regression import HarmonicRegressionModel, HarmonicRegressionParams\n'), ((819, 877), 'numpy.arange', 'np.arange', ([], {'start': '(1576195200)', 'stop': '(1577836801)', 'step': '(60 * 60)'}), '(start=1576195200, stop=1577836801, step=60 * 60)\n', (828, 877), True, 'import numpy as np\n'), ((1140, 1207), 'pandas.DataFrame', 'pd.DataFrame', (["{'time': self.series_times, 'values': self.harms_sum}"], {}), "({'time': self.series_times, 'values': self.harms_sum})\n", (1152, 1207), True, 'import pandas as pd\n'), ((506, 517), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (515, 517), False, 'import os\n')]
|
import argparse
import torch
import numpy as np
import os
import data
from networks import domain_generator, domain_classifier
from utils import util
def optimize(opt):
dataset_name = 'cifar10'
generator_name = 'stylegan2-cc' # class conditional stylegan
transform = data.get_transform(dataset_name, 'imval')
dset = data.get_dataset(dataset_name, opt.partition,
load_w=False, transform=transform)
total = len(dset)
if opt.indices is None:
start_idx = 0
end_idx = total
else:
start_idx = opt.indices[0]
end_idx = opt.indices[1]
generator = domain_generator.define_generator(
generator_name, dataset_name, load_encoder=False)
util.set_requires_grad(False, generator.generator)
resnet = domain_classifier.define_classifier(dataset_name,
'imageclassifier')
### iterate ###
for i in range(start_idx, end_idx):
img, label = dset[i]
print("Running img %d/%d" % (i, len(dset)))
filename = os.path.join(opt.w_path, '%s_%06d.npy' %
(opt.partition, i))
if os.path.isfile(filename):
print(filename + ' found... skipping')
continue
img = img[None].cuda()
with torch.no_grad():
pred_logit = resnet(img)
_, pred_label = pred_logit.max(1)
pred_label = pred_label.item()
print("True label %d prd label %d" % (label, pred_label))
ckpt, loss = generator.optimize(img, pred_label)
current_z = ckpt['current_z'].detach().cpu().numpy()
np.save(filename, current_z)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--partition', type=str, required=True,
help='specify train, val, or test partition')
parser.add_argument('--w_path', type=str, required=True,
help='directory to save the optimized latents')
parser.add_argument('--indices', type=int, nargs=2,
help='optimize latents for specific image range')
opt = parser.parse_args()
print(opt)
os.makedirs(opt.w_path, exist_ok=True)
optimize(opt)
|
[
"numpy.save",
"argparse.ArgumentParser",
"data.get_dataset",
"os.makedirs",
"networks.domain_classifier.define_classifier",
"data.get_transform",
"os.path.isfile",
"networks.domain_generator.define_generator",
"torch.no_grad",
"os.path.join",
"utils.util.set_requires_grad"
] |
[((283, 324), 'data.get_transform', 'data.get_transform', (['dataset_name', '"""imval"""'], {}), "(dataset_name, 'imval')\n", (301, 324), False, 'import data\n'), ((337, 422), 'data.get_dataset', 'data.get_dataset', (['dataset_name', 'opt.partition'], {'load_w': '(False)', 'transform': 'transform'}), '(dataset_name, opt.partition, load_w=False, transform=transform\n )\n', (353, 422), False, 'import data\n'), ((637, 724), 'networks.domain_generator.define_generator', 'domain_generator.define_generator', (['generator_name', 'dataset_name'], {'load_encoder': '(False)'}), '(generator_name, dataset_name,\n load_encoder=False)\n', (670, 724), False, 'from networks import domain_generator, domain_classifier\n'), ((734, 784), 'utils.util.set_requires_grad', 'util.set_requires_grad', (['(False)', 'generator.generator'], {}), '(False, generator.generator)\n', (756, 784), False, 'from utils import util\n'), ((799, 867), 'networks.domain_classifier.define_classifier', 'domain_classifier.define_classifier', (['dataset_name', '"""imageclassifier"""'], {}), "(dataset_name, 'imageclassifier')\n", (834, 867), False, 'from networks import domain_generator, domain_classifier\n'), ((1733, 1758), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1756, 1758), False, 'import argparse\n'), ((2206, 2244), 'os.makedirs', 'os.makedirs', (['opt.w_path'], {'exist_ok': '(True)'}), '(opt.w_path, exist_ok=True)\n', (2217, 2244), False, 'import os\n'), ((1079, 1139), 'os.path.join', 'os.path.join', (['opt.w_path', "('%s_%06d.npy' % (opt.partition, i))"], {}), "(opt.w_path, '%s_%06d.npy' % (opt.partition, i))\n", (1091, 1139), False, 'import os\n'), ((1183, 1207), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (1197, 1207), False, 'import os\n'), ((1661, 1689), 'numpy.save', 'np.save', (['filename', 'current_z'], {}), '(filename, current_z)\n', (1668, 1689), True, 'import numpy as np\n'), ((1326, 1341), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1339, 1341), False, 'import torch\n')]
|
'''Provide fundamental geometry calculations used by the scheduling.
'''
import math
import numpy as np
import brahe.data_models as bdm
from brahe.utils import fcross
from brahe.constants import RAD2DEG
from brahe.coordinates import sECEFtoENZ, sENZtoAZEL, sECEFtoGEOD, sGEODtoECEF
from brahe.relative_coordinates import rCARTtoRTN
def azelrng(sat_ecef: np.ndarray,
loc_ecef: np.ndarray,
use_degrees: bool = True) -> np.ndarray:
'''Compute satellite azimuth, elevation, and range as viewed from the specified location.
Args:
sat_ecef (:obj:`np.ndarray`): Satellite position in the ECEF frame
loc_ecef (:obj:`np.ndarray`): Location in ECEF (ITRF) frame.
use_degrees (:obj:`bool`, optional): Return output in degrees. Default: `True`
Returns:
np.ndarray: azimuth elevation and range as array [deg, deg, m]
'''
# Ensure np-ness
sat_ecef = np.asarray(sat_ecef)
loc_ecef = np.asarray(loc_ecef)
# Compute Satellite State in ENZ frame
sat_enz = sECEFtoENZ(loc_ecef[0:3], sat_ecef[0:3], conversion='geodetic')
# Compute Satellite Elevation
azelrng = sENZtoAZEL(sat_enz, use_degrees=use_degrees)[0:3]
return azelrng
def azimuth(sat_ecef: np.ndarray,
loc_ecef: np.ndarray,
use_degrees: bool = True) -> np.ndarray:
'''Compute satellite azimuth as viewed from the specified location.
Args:
sat_ecef (:obj:`np.ndarray`): Satellite position in the ECEF frame
loc_ecef (:obj:`np.ndarray`): Location in ECEF (ITRF) frame.
use_degrees (:obj:`bool`, optional): Return output in degrees. Default: `True`
Returns:
float: Azimuth [deg]
'''
return azelrng(sat_ecef, loc_ecef, use_degrees=use_degrees)[0]
def elevation(sat_ecef: np.ndarray,
loc_ecef: np.ndarray,
use_degrees: bool = True) -> np.ndarray:
'''Compute satellite elevation as viewed from the specified location.
Args:
sat_ecef (:obj:`np.ndarray`): Satellite position in the ECEF frame
loc_ecef (:obj:`np.ndarray`): Location in ECEF (ITRF) frame.
use_degrees (:obj:`bool`, optional): Return output in degrees. Default: `True`
Returns:
float: Elevation [deg]
'''
return azelrng(sat_ecef, loc_ecef, use_degrees=use_degrees)[1]
def range(sat_ecef: np.ndarray, loc_ecef: np.ndarray,
use_degrees: bool = True) -> np.ndarray:
'''Compute satellite range from the specified location.
Args:
sat_ecef (:obj:`np.ndarray`): Satellite position in the ECEF frame.
loc_ecef (:obj:`np.ndarray`): Location in ECEF (ITRF) frame.
use_degrees (:obj:`bool`, optional): Return output in degrees. Default: `True`
Returns:
float: Range [m]
'''
return azelrng(sat_ecef, loc_ecef, use_degrees=use_degrees)[2]
def look_angle(sat_ecef: np.ndarray, loc_ecef: np.ndarray, use_degrees: bool = True) -> np.ndarray:
'''Compute the look angle angle between the satellite and the specific location.
Args:
sat_ecef (:obj:`np.ndarray`): Satellite position in the ECEF frame.
loc_ecef (:obj:`np.ndarray`): Location in ECEF (ITRF) frame.
use_degrees (:obj:`bool`, optional): Return output in degrees. Default: `True`
Returns:
float: look angle angle [deg]
'''
# Ensure np-ness
sat_ecef = np.asarray(sat_ecef)
loc_ecef = np.asarray(loc_ecef)
# Satellite state
r_sat = sat_ecef[0:3]
# Geodetic sub-satellte point
sat_geod = sECEFtoGEOD(r_sat)
sub_sat_geod = np.array([sat_geod[0], sat_geod[1], 0.0])
sub_sat_ecef = sGEODtoECEF(sub_sat_geod)
# look angle
nadir_dir = (sub_sat_ecef - r_sat) / np.linalg.norm(sub_sat_ecef - r_sat)
target_dir = (loc_ecef - r_sat) / np.linalg.norm(loc_ecef - r_sat)
look_angle = math.acos(np.dot(nadir_dir, target_dir)) * RAD2DEG
return look_angle
def ascdsc(sat_ecef: np.ndarray) -> bdm.AscendingDescending:
'''Compute whether whether satellite is ascending or descending in current
state.
Args:
sat_ecef (:obj:`np.ndarray`): Satellite position in the ECEF frame.
use_degrees (:obj:`bool`, optional): Return output in degrees. Default: `True`
Returns:
bdm.AscendingDescending: ascending or descending state
'''
# Ensure np-ness
sat_ecef = np.asarray(sat_ecef)
if sat_ecef[5] > 0:
return bdm.AscendingDescending.ascending
elif sat_ecef[5] < 0:
return bdm.AscendingDescending.descending
else:
# Handle unlikely case that satellite is exaclty at 0 Z-velocity
if sat_ecef[2] < 0:
return bdm.AscendingDescending.ascending
else:
return bdm.AscendingDescending.descending
def look_direction(sat_ecef: np.ndarray,
loc_ecef: np.ndarray) -> bdm.LookDirection:
'''Compute the look direction for viewing the startet
Args:
sat_ecef (:obj:`np.ndarray`): Satellite position in the ECEF frame.
loc_ecef (:obj:`np.ndarray`): Location in ECEF (ITRF) frame.\
Returns:
bdm.LookDirection: Look direction. 'left' or 'right'
'''
# Ensure np-ness
sat_ecef = np.asarray(sat_ecef)
loc_ecef = np.asarray(loc_ecef)
# Line of Sight Vector in ECEF Frame
los_ecef = loc_ecef[0:3] - sat_ecef[0:3]
# Apply ECEF to RTN rotation
los_rtn = rCARTtoRTN(sat_ecef) @ los_ecef
# Compute cross product of RTN velocity and RTN LOS
cp = fcross([0, 1, 0], los_rtn)
if np.sign(cp[0]) < 0:
return bdm.LookDirection.right
else:
return bdm.LookDirection.left
|
[
"brahe.coordinates.sENZtoAZEL",
"brahe.relative_coordinates.rCARTtoRTN",
"numpy.asarray",
"brahe.coordinates.sECEFtoGEOD",
"brahe.coordinates.sGEODtoECEF",
"brahe.coordinates.sECEFtoENZ",
"brahe.utils.fcross",
"numpy.array",
"numpy.linalg.norm",
"numpy.sign",
"numpy.dot"
] |
[((923, 943), 'numpy.asarray', 'np.asarray', (['sat_ecef'], {}), '(sat_ecef)\n', (933, 943), True, 'import numpy as np\n'), ((959, 979), 'numpy.asarray', 'np.asarray', (['loc_ecef'], {}), '(loc_ecef)\n', (969, 979), True, 'import numpy as np\n'), ((1038, 1101), 'brahe.coordinates.sECEFtoENZ', 'sECEFtoENZ', (['loc_ecef[0:3]', 'sat_ecef[0:3]'], {'conversion': '"""geodetic"""'}), "(loc_ecef[0:3], sat_ecef[0:3], conversion='geodetic')\n", (1048, 1101), False, 'from brahe.coordinates import sECEFtoENZ, sENZtoAZEL, sECEFtoGEOD, sGEODtoECEF\n'), ((3395, 3415), 'numpy.asarray', 'np.asarray', (['sat_ecef'], {}), '(sat_ecef)\n', (3405, 3415), True, 'import numpy as np\n'), ((3431, 3451), 'numpy.asarray', 'np.asarray', (['loc_ecef'], {}), '(loc_ecef)\n', (3441, 3451), True, 'import numpy as np\n'), ((3551, 3569), 'brahe.coordinates.sECEFtoGEOD', 'sECEFtoGEOD', (['r_sat'], {}), '(r_sat)\n', (3562, 3569), False, 'from brahe.coordinates import sECEFtoENZ, sENZtoAZEL, sECEFtoGEOD, sGEODtoECEF\n'), ((3589, 3630), 'numpy.array', 'np.array', (['[sat_geod[0], sat_geod[1], 0.0]'], {}), '([sat_geod[0], sat_geod[1], 0.0])\n', (3597, 3630), True, 'import numpy as np\n'), ((3650, 3675), 'brahe.coordinates.sGEODtoECEF', 'sGEODtoECEF', (['sub_sat_geod'], {}), '(sub_sat_geod)\n', (3661, 3675), False, 'from brahe.coordinates import sECEFtoENZ, sENZtoAZEL, sECEFtoGEOD, sGEODtoECEF\n'), ((4384, 4404), 'numpy.asarray', 'np.asarray', (['sat_ecef'], {}), '(sat_ecef)\n', (4394, 4404), True, 'import numpy as np\n'), ((5228, 5248), 'numpy.asarray', 'np.asarray', (['sat_ecef'], {}), '(sat_ecef)\n', (5238, 5248), True, 'import numpy as np\n'), ((5264, 5284), 'numpy.asarray', 'np.asarray', (['loc_ecef'], {}), '(loc_ecef)\n', (5274, 5284), True, 'import numpy as np\n'), ((5518, 5544), 'brahe.utils.fcross', 'fcross', (['[0, 1, 0]', 'los_rtn'], {}), '([0, 1, 0], los_rtn)\n', (5524, 5544), False, 'from brahe.utils import fcross\n'), ((1151, 1195), 'brahe.coordinates.sENZtoAZEL', 'sENZtoAZEL', (['sat_enz'], {'use_degrees': 'use_degrees'}), '(sat_enz, use_degrees=use_degrees)\n', (1161, 1195), False, 'from brahe.coordinates import sECEFtoENZ, sENZtoAZEL, sECEFtoGEOD, sGEODtoECEF\n'), ((3735, 3771), 'numpy.linalg.norm', 'np.linalg.norm', (['(sub_sat_ecef - r_sat)'], {}), '(sub_sat_ecef - r_sat)\n', (3749, 3771), True, 'import numpy as np\n'), ((3810, 3842), 'numpy.linalg.norm', 'np.linalg.norm', (['(loc_ecef - r_sat)'], {}), '(loc_ecef - r_sat)\n', (3824, 3842), True, 'import numpy as np\n'), ((5420, 5440), 'brahe.relative_coordinates.rCARTtoRTN', 'rCARTtoRTN', (['sat_ecef'], {}), '(sat_ecef)\n', (5430, 5440), False, 'from brahe.relative_coordinates import rCARTtoRTN\n'), ((5553, 5567), 'numpy.sign', 'np.sign', (['cp[0]'], {}), '(cp[0])\n', (5560, 5567), True, 'import numpy as np\n'), ((3870, 3899), 'numpy.dot', 'np.dot', (['nadir_dir', 'target_dir'], {}), '(nadir_dir, target_dir)\n', (3876, 3899), True, 'import numpy as np\n')]
|
import numpy as np
class LidarTools(object):
'''
Collection of helpers for processing LiDAR point cloud.
'''
def get_bev(self, points, resolution=0.1, pixel_values=None, generate_img=None):
'''
Returns bird's eye view of a LiDAR point cloud for a given resolution.
Optional pixel_values can be used for giving color coded info the point cloud.
Optional generate_img function can be used for creating images.
'''
x = points[:, 0]
y = points[:, 1]
z = points[:, 2]
x_range = -1 * np.ceil(y.max()).astype(np.int), ((y.min()/np.abs(y.min())) * np.floor(y.min())).astype(np.int)
y_range = np.floor(x.min()).astype(np.int), np.ceil(x.max()).astype(np.int)
# Create mapping from a 3D point to a pixel based on resolution
# floor() used to prevent issues with -ve vals rounding upwards causing index out bound error
x_img = (-y / resolution).astype(np.int32) - int(np.floor(x_range[0]/resolution))
y_img = (x / resolution).astype(np.int32) - int(np.floor(y_range[0]/resolution))
img_width = int((x_range[1] - x_range[0])/resolution)
img_height = int((y_range[1] - y_range[0])/resolution)
if pixel_values is None:
pixel_values = (((z - z.min()) / float(z.max() - z.min())) * 255).astype(np.uint8)
if generate_img is None:
img = np.zeros([img_height, img_width], dtype=np.uint8)
img[-y_img, x_img] = pixel_values
return img
return generate_img(img_height, img_width, -y_img, x_img, pixel_values)
def filter_points(self, points, side_range=None, fwd_range=None, \
height_range=None, horizontal_fov=None, vertical_fov=None):
'''
Returns filtered points based on side, forward and height range, and, horizontal and vertical field of view.
'''
x = points[:, 0]
y = points[:, 1]
z = points[:, 2]
r = points[:, 3]
mask = np.full_like(x, True)
if side_range is not None:
side_mask = np.logical_and((y > -side_range[1]), (y < -side_range[0]))
mask = np.logical_and(mask, side_mask)
if fwd_range is not None:
fwd_mask = np.logical_and((x > fwd_range[0]), (x < fwd_range[1]))
mask = np.logical_and(mask, fwd_mask)
if height_range is not None:
height_mask = np.logical_and((z > height_range[0]), (z < height_range[1]))
mask = np.logical_and(mask, height_mask)
if horizontal_fov is not None:
horizontal_fov_mask = np.logical_and(np.arctan2(y, x) > (-horizontal_fov[1] * np.pi / 180), \
np.arctan2(y, x) < (-horizontal_fov[0] * np.pi / 180))
mask = np.logical_and(mask, horizontal_fov_mask)
if vertical_fov is not None:
distance = np.sqrt(x ** 2 + y ** 2 + z ** 2)
vertical_fov_mask = np.logical_and(np.arctan2(z,distance) < (vertical_fov[1] * np.pi / 180), \
np.arctan2(z,distance) > (vertical_fov[0] * np.pi / 180))
mask = np.logical_and(mask, vertical_fov_mask)
indices = np.argwhere(mask).flatten()
return points[indices, :]
|
[
"numpy.full_like",
"numpy.arctan2",
"numpy.logical_and",
"numpy.floor",
"numpy.zeros",
"numpy.argwhere",
"numpy.sqrt"
] |
[((2055, 2076), 'numpy.full_like', 'np.full_like', (['x', '(True)'], {}), '(x, True)\n', (2067, 2076), True, 'import numpy as np\n'), ((1428, 1477), 'numpy.zeros', 'np.zeros', (['[img_height, img_width]'], {'dtype': 'np.uint8'}), '([img_height, img_width], dtype=np.uint8)\n', (1436, 1477), True, 'import numpy as np\n'), ((2145, 2199), 'numpy.logical_and', 'np.logical_and', (['(y > -side_range[1])', '(y < -side_range[0])'], {}), '(y > -side_range[1], y < -side_range[0])\n', (2159, 2199), True, 'import numpy as np\n'), ((2223, 2254), 'numpy.logical_and', 'np.logical_and', (['mask', 'side_mask'], {}), '(mask, side_mask)\n', (2237, 2254), True, 'import numpy as np\n'), ((2313, 2363), 'numpy.logical_and', 'np.logical_and', (['(x > fwd_range[0])', '(x < fwd_range[1])'], {}), '(x > fwd_range[0], x < fwd_range[1])\n', (2327, 2363), True, 'import numpy as np\n'), ((2387, 2417), 'numpy.logical_and', 'np.logical_and', (['mask', 'fwd_mask'], {}), '(mask, fwd_mask)\n', (2401, 2417), True, 'import numpy as np\n'), ((2482, 2538), 'numpy.logical_and', 'np.logical_and', (['(z > height_range[0])', '(z < height_range[1])'], {}), '(z > height_range[0], z < height_range[1])\n', (2496, 2538), True, 'import numpy as np\n'), ((2562, 2595), 'numpy.logical_and', 'np.logical_and', (['mask', 'height_mask'], {}), '(mask, height_mask)\n', (2576, 2595), True, 'import numpy as np\n'), ((2856, 2897), 'numpy.logical_and', 'np.logical_and', (['mask', 'horizontal_fov_mask'], {}), '(mask, horizontal_fov_mask)\n', (2870, 2897), True, 'import numpy as np\n'), ((2967, 3000), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2 + z ** 2)'], {}), '(x ** 2 + y ** 2 + z ** 2)\n', (2974, 3000), True, 'import numpy as np\n'), ((3213, 3252), 'numpy.logical_and', 'np.logical_and', (['mask', 'vertical_fov_mask'], {}), '(mask, vertical_fov_mask)\n', (3227, 3252), True, 'import numpy as np\n'), ((998, 1031), 'numpy.floor', 'np.floor', (['(x_range[0] / resolution)'], {}), '(x_range[0] / resolution)\n', (1006, 1031), True, 'import numpy as np\n'), ((1087, 1120), 'numpy.floor', 'np.floor', (['(y_range[0] / resolution)'], {}), '(y_range[0] / resolution)\n', (1095, 1120), True, 'import numpy as np\n'), ((3272, 3289), 'numpy.argwhere', 'np.argwhere', (['mask'], {}), '(mask)\n', (3283, 3289), True, 'import numpy as np\n'), ((2697, 2713), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (2707, 2713), True, 'import numpy as np\n'), ((2782, 2798), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (2792, 2798), True, 'import numpy as np\n'), ((3048, 3071), 'numpy.arctan2', 'np.arctan2', (['z', 'distance'], {}), '(z, distance)\n', (3058, 3071), True, 'import numpy as np\n'), ((3136, 3159), 'numpy.arctan2', 'np.arctan2', (['z', 'distance'], {}), '(z, distance)\n', (3146, 3159), True, 'import numpy as np\n')]
|
import argparse
import os
import os.path as osp
import pickle
import shutil
import tempfile
import mmcv
import torch
import torch.distributed as dist
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, load_checkpoint
from mmdet.apis import init_dist
from mmdet.core import coco_eval, results2json, wrap_fp16_model, get_classes, tensor2imgs
from mmdet.datasets import build_dataloader, build_dataset
from mmdet.models import build_detector
from DOTA_devkit.ResultMerge_multi_process import mergebypoly_multiprocess
import numpy as np
import os
import cv2
from DOTA_devkit.dota_utils import GetFileFromThisRootDir, custombasename
def draw_bbox(img, bboxes, labels, path, class_names):
img_show = mmcv.image.imread(img)
# bgr
bbox_color = [(0, 255, 0), # green
(255, 0, 0), #深蓝
(255, 255, 0), # 浅蓝,亮
(0, 0, 255), #红
(255, 0, 255), # purple
(255, 128, 0), #天蓝(比浅蓝深一点)
(0, 255, 255), #黄
(207, 203, 211), #white
(128, 255, 0), # 青色
(128, 0, 255), #玫红
(255, 0, 128), # 紫
(0, 128, 255), # 橘色
(0, 255, 128), #草绿
(0, 0, 128), #深红
(128, 0, 0)] #藏蓝
text_color = (255, 0, 0) # green
for bbox, label in zip(bboxes, labels):
bbox_int = bbox.astype(np.int32)
pts = np.array([[bbox_int[0], bbox_int[1]],
[bbox_int[2], bbox_int[3]],
[bbox_int[4], bbox_int[5]],
[bbox_int[6], bbox_int[7]]], dtype=np.int32)
cv2.polylines(img_show, [pts], True, bbox_color[label], thickness=2)
# cv2.polylines(img_show, [pts], True, text_color, thickness=2)
label_text = class_names[
label] if class_names is not None else 'cls {}'.format(label)
font = 0.5
# cv2.putText(img, label_text, (bbox_int[0], bbox_int[1] - 2),
# cv2.FONT_HERSHEY_COMPLEX, font, text_color)
cv2.imwrite(path, img)
def draw_result(data, result, outdir, class_names, score_thr=0.001):
bbox_result = result
img_metas = data['img_meta'][0].data[0]
if not os.path.exists(outdir):
os.makedirs(outdir)
for img_meta in img_metas:
h, w, _ = img_meta['ori_shape']
filename = img_meta['filename']
img = mmcv.imread(filename)
img_show = img[:h, :w, :]
path = os.path.basename(os.path.splitext(img_meta['filename'])[0])
path = os.path.join(outdir, path + '.jpg')
bboxes = np.vstack(bbox_result)
labels = [
np.full(bbox.shape[0], i, dtype=np.int32)
for i, bbox in enumerate(bbox_result)
]
labels = np.concatenate(labels)
if score_thr > 0:
assert bboxes.shape[1] == 9
scores = bboxes[:, -1]
inds = scores > score_thr
bboxes = bboxes[inds, :]
labels = labels[inds]
draw_bbox(img_show, bboxes, labels, path, class_names)
def single_gpu_test(model, data_loader, outdir, show=False):
model.eval()
# model.eval(),让model变成测试模式,对dropout和batch normalization的操作在训练和测试的时候是不一样的
results = []
dataset = data_loader.dataset
prog_bar = mmcv.ProgressBar(len(dataset))
for i, data in enumerate(data_loader):
with torch.no_grad():
result = model(return_loss=False, rescale=not show, **data)
results.append(result)
if show:
draw_result(data, result, osp.join(outdir, 'images'), dataset.CLASSES, score_thr=0.001)
batch_size = data['img'][0].size(0)
for _ in range(batch_size):
prog_bar.update()
return results
def multi_gpu_test(model, data_loader, tmpdir=None, gpu_collect=False):
"""Test model with multiple gpus.
This method tests model with multiple gpus and collects the results
under two different modes: gpu and cpu modes. By setting 'gpu_collect=True'
it encodes results to gpu tensors and use gpu communication for results
collection. On cpu mode it saves the results on different gpus to 'tmpdir'
and collects them by the rank 0 worker.
Args:
model (nn.Module): Model to be tested.
data_loader (nn.Dataloader): Pytorch data loader.
tmpdir (str): Path of directory to save the temporary results from
different gpus under cpu mode.
gpu_collect (bool): Option to use either gpu or cpu to collect results.
Returns:
list: The prediction results.
"""
model.eval()
results = []
dataset = data_loader.dataset
rank, world_size = get_dist_info()
if rank == 0:
prog_bar = mmcv.ProgressBar(len(dataset))
for i, data in enumerate(data_loader):
with torch.no_grad():
result = model(return_loss=False, rescale=True, **data)
results.append(result)
if rank == 0:
batch_size = data['img'][0].size(0)
for _ in range(batch_size * world_size):
prog_bar.update()
# collect results from all ranks
if gpu_collect:
results = collect_results_gpu(results, len(dataset))
else:
results = collect_results_cpu(results, len(dataset), tmpdir)
return results
def collect_results_cpu(result_part, size, tmpdir=None):
rank, world_size = get_dist_info()
# create a tmp dir if it is not specified
if tmpdir is None:
MAX_LEN = 512
# 32 is whitespace
dir_tensor = torch.full((MAX_LEN, ),
32,
dtype=torch.uint8,
device='cuda')
if rank == 0:
tmpdir = tempfile.mkdtemp()
tmpdir = torch.tensor(
bytearray(tmpdir.encode()), dtype=torch.uint8, device='cuda')
dir_tensor[:len(tmpdir)] = tmpdir
dist.broadcast(dir_tensor, 0)
tmpdir = dir_tensor.cpu().numpy().tobytes().decode().rstrip()
else:
mmcv.mkdir_or_exist(tmpdir)
# dump the part result to the dir
mmcv.dump(result_part, osp.join(tmpdir, 'part_{}.pkl'.format(rank)))
dist.barrier()
# collect all parts
if rank != 0:
return None
else:
# load results of all parts from tmp dir
part_list = []
for i in range(world_size):
part_file = osp.join(tmpdir, 'part_{}.pkl'.format(i))
part_list.append(mmcv.load(part_file))
# sort the results
ordered_results = []
for res in zip(*part_list):
ordered_results.extend(list(res))
# the dataloader may pad some samples
ordered_results = ordered_results[:size]
# remove tmp dir
shutil.rmtree(tmpdir)
return ordered_results
def collect_results_gpu(result_part, size):
rank, world_size = get_dist_info()
# dump result part to tensor with pickle
part_tensor = torch.tensor(
bytearray(pickle.dumps(result_part)), dtype=torch.uint8, device='cuda')
# gather all result part tensor shape
shape_tensor = torch.tensor(part_tensor.shape, device='cuda')
shape_list = [shape_tensor.clone() for _ in range(world_size)]
dist.all_gather(shape_list, shape_tensor)
# padding result part tensor to max length
shape_max = torch.tensor(shape_list).max()
part_send = torch.zeros(shape_max, dtype=torch.uint8, device='cuda')
part_send[:shape_tensor[0]] = part_tensor
part_recv_list = [
part_tensor.new_zeros(shape_max) for _ in range(world_size)
]
# gather all result part
dist.all_gather(part_recv_list, part_send)
if rank == 0:
part_list = []
for recv, shape in zip(part_recv_list, shape_list):
part_list.append(
pickle.loads(recv[:shape[0]].cpu().numpy().tobytes()))
# sort the results
ordered_results = []
for res in zip(*part_list):
ordered_results.extend(list(res))
# the dataloader may pad some samples
ordered_results = ordered_results[:size]
return ordered_results
def parse_args():
parser = argparse.ArgumentParser(description='MMDet test detector')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--outdir', help='output dir')
parser.add_argument('--out', help='output result file') # .pkl文件
parser.add_argument(
'--gpu_collect',
action='store_true',
help='whether to use gpu to collect results')
parser.add_argument('--show', action='store_true', help='show results')
parser.add_argument('--tmpdir', help='tmp dir for writing some results')
parser.add_argument(
'--launcher',
choices=['none', 'pytorch', 'slurm', 'mpi'],
default='none',
help='job launcher')
parser.add_argument('--local_rank', type=int, default=0)
args = parser.parse_args()
if 'LOCAL_RANK' not in os.environ:
os.environ['LOCAL_RANK'] = str(args.local_rank)
return args
def write_dota_results(path, boxes, dataset, threshold=0.001):
'''
:param path: output dir path
:param boxes: list(list(ndarray))
:param threshold: 置信度下限,小于此置信度的bbox不输出
:return:
'''
classes = dataset.CLASSES
img_infos = dataset.img_infos
assert len(boxes) == len(img_infos)
print("write no merge results\n")
for i, img_info in enumerate(img_infos):
# print("img {}: {}".format(i, img_info['id']))
img_id = img_info['id']
for j, cls in enumerate(classes):
txt_path = osp.join(path, 'Task1_' + cls + '.txt')
with open(txt_path, 'a') as f:
box = boxes[i][j] # (n, 9)
inds = box[:, 8] > threshold
box = box[inds]
for k in range(box.shape[0]):
# print(cls)
# print('{} {} {} {} {} {} {} {} {} {}\n'.format(
# img_id, box[k, 8],
# int(box[k, 0]), int(box[k, 1]),
# int(box[k, 2]), int(box[k, 3]),
# int(box[k, 4]), int(box[k, 5]),
# int(box[k, 6]), int(box[k, 7])))
f.write('{} {} {} {} {} {} {} {} {} {}\n'.format(
img_id, box[k, 8],
int(box[k, 0]), int(box[k, 1]),
int(box[k, 2]), int(box[k, 3]),
int(box[k, 4]), int(box[k, 5]),
int(box[k, 6]), int(box[k, 7])))
def main():
args = parse_args()
assert args.out , \
('Please specify at least one operation (save or show the results) '
'with the argument "--out"')
if args.out is not None and not args.out.endswith(('.pkl', '.pickle')):
raise ValueError('The output file must be a pkl file.')
cfg = mmcv.Config.fromfile(args.config)
# set cudnn_benchmark
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
cfg.model.pretrained = None
cfg.data.test.test_mode = True
# init distributed env first, since logger depends on the dist info.
if args.launcher == 'none':
distributed = False
else:
distributed = True
init_dist(args.launcher, **cfg.dist_params)
# build the dataloader
# TODO: support multiple images per gpu (only minor changes are needed)
dataset = build_dataset(cfg.data.test)
data_loader = build_dataloader(
dataset,
imgs_per_gpu=1,
workers_per_gpu=cfg.data.workers_per_gpu,
dist=distributed,
shuffle=False)
# build the model and load checkpoint
model = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg)
fp16_cfg = cfg.get('fp16', None)
if fp16_cfg is not None:
wrap_fp16_model(model)
checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu')
# old versions did not save class info in checkpoints, this walkaround is
# for backward compatibility
if 'CLASSES' in checkpoint['meta']:
model.CLASSES = checkpoint['meta']['CLASSES']
else:
model.CLASSES = dataset.CLASSES
if not distributed:
model = MMDataParallel(model, device_ids=[0])
outputs = single_gpu_test(model, data_loader, args.outdir, args.show)
# outputs:list(list(ndarray)),外层list:图片,内层list:类别
else:
model = MMDistributedDataParallel(model.cuda())
outputs = multi_gpu_test(model, data_loader, args.tmpdir,
args.gpu_collect)
rank, _ = get_dist_info()
# 将结果保存到.pkl文件中
if args.out and rank == 0:
print('\nwriting results to {}'.format(args.out))
mmcv.dump(outputs, osp.join(args.outdir, args.out))
if __name__ == '__main__':
# os.environ['CUDA_VISIBLE_DEVICES'] = '0'
main()
|
[
"mmcv.runner.get_dist_info",
"argparse.ArgumentParser",
"mmcv.mkdir_or_exist",
"torch.full",
"torch.distributed.all_gather",
"mmcv.Config.fromfile",
"shutil.rmtree",
"torch.no_grad",
"os.path.join",
"mmcv.imread",
"numpy.full",
"mmdet.models.build_detector",
"cv2.imwrite",
"os.path.exists",
"tempfile.mkdtemp",
"torch.zeros",
"mmdet.apis.init_dist",
"mmdet.datasets.build_dataloader",
"pickle.dumps",
"mmcv.image.imread",
"mmcv.runner.load_checkpoint",
"numpy.vstack",
"numpy.concatenate",
"mmdet.datasets.build_dataset",
"cv2.polylines",
"os.makedirs",
"mmcv.load",
"torch.distributed.barrier",
"mmdet.core.wrap_fp16_model",
"mmcv.parallel.MMDataParallel",
"numpy.array",
"os.path.splitext",
"torch.distributed.broadcast",
"torch.tensor"
] |
[((781, 803), 'mmcv.image.imread', 'mmcv.image.imread', (['img'], {}), '(img)\n', (798, 803), False, 'import mmcv\n'), ((4896, 4911), 'mmcv.runner.get_dist_info', 'get_dist_info', ([], {}), '()\n', (4909, 4911), False, 'from mmcv.runner import get_dist_info, load_checkpoint\n'), ((5631, 5646), 'mmcv.runner.get_dist_info', 'get_dist_info', ([], {}), '()\n', (5644, 5646), False, 'from mmcv.runner import get_dist_info, load_checkpoint\n'), ((6454, 6468), 'torch.distributed.barrier', 'dist.barrier', ([], {}), '()\n', (6466, 6468), True, 'import torch.distributed as dist\n'), ((7176, 7191), 'mmcv.runner.get_dist_info', 'get_dist_info', ([], {}), '()\n', (7189, 7191), False, 'from mmcv.runner import get_dist_info, load_checkpoint\n'), ((7415, 7461), 'torch.tensor', 'torch.tensor', (['part_tensor.shape'], {'device': '"""cuda"""'}), "(part_tensor.shape, device='cuda')\n", (7427, 7461), False, 'import torch\n'), ((7535, 7576), 'torch.distributed.all_gather', 'dist.all_gather', (['shape_list', 'shape_tensor'], {}), '(shape_list, shape_tensor)\n', (7550, 7576), True, 'import torch.distributed as dist\n'), ((7690, 7746), 'torch.zeros', 'torch.zeros', (['shape_max'], {'dtype': 'torch.uint8', 'device': '"""cuda"""'}), "(shape_max, dtype=torch.uint8, device='cuda')\n", (7701, 7746), False, 'import torch\n'), ((7929, 7971), 'torch.distributed.all_gather', 'dist.all_gather', (['part_recv_list', 'part_send'], {}), '(part_recv_list, part_send)\n', (7944, 7971), True, 'import torch.distributed as dist\n'), ((8489, 8547), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""MMDet test detector"""'}), "(description='MMDet test detector')\n", (8512, 8547), False, 'import argparse\n'), ((11352, 11385), 'mmcv.Config.fromfile', 'mmcv.Config.fromfile', (['args.config'], {}), '(args.config)\n', (11372, 11385), False, 'import mmcv\n'), ((11924, 11952), 'mmdet.datasets.build_dataset', 'build_dataset', (['cfg.data.test'], {}), '(cfg.data.test)\n', (11937, 11952), False, 'from mmdet.datasets import build_dataloader, build_dataset\n'), ((11972, 12093), 'mmdet.datasets.build_dataloader', 'build_dataloader', (['dataset'], {'imgs_per_gpu': '(1)', 'workers_per_gpu': 'cfg.data.workers_per_gpu', 'dist': 'distributed', 'shuffle': '(False)'}), '(dataset, imgs_per_gpu=1, workers_per_gpu=cfg.data.\n workers_per_gpu, dist=distributed, shuffle=False)\n', (11988, 12093), False, 'from mmdet.datasets import build_dataloader, build_dataset\n'), ((12193, 12257), 'mmdet.models.build_detector', 'build_detector', (['cfg.model'], {'train_cfg': 'None', 'test_cfg': 'cfg.test_cfg'}), '(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg)\n', (12207, 12257), False, 'from mmdet.models import build_detector\n'), ((12376, 12435), 'mmcv.runner.load_checkpoint', 'load_checkpoint', (['model', 'args.checkpoint'], {'map_location': '"""cpu"""'}), "(model, args.checkpoint, map_location='cpu')\n", (12391, 12435), False, 'from mmcv.runner import get_dist_info, load_checkpoint\n'), ((13121, 13136), 'mmcv.runner.get_dist_info', 'get_dist_info', ([], {}), '()\n', (13134, 13136), False, 'from mmcv.runner import get_dist_info, load_checkpoint\n'), ((1544, 1687), 'numpy.array', 'np.array', (['[[bbox_int[0], bbox_int[1]], [bbox_int[2], bbox_int[3]], [bbox_int[4],\n bbox_int[5]], [bbox_int[6], bbox_int[7]]]'], {'dtype': 'np.int32'}), '([[bbox_int[0], bbox_int[1]], [bbox_int[2], bbox_int[3]], [bbox_int\n [4], bbox_int[5]], [bbox_int[6], bbox_int[7]]], dtype=np.int32)\n', (1552, 1687), True, 'import numpy as np\n'), ((1767, 1835), 'cv2.polylines', 'cv2.polylines', (['img_show', '[pts]', '(True)', 'bbox_color[label]'], {'thickness': '(2)'}), '(img_show, [pts], True, bbox_color[label], thickness=2)\n', (1780, 1835), False, 'import cv2\n'), ((2187, 2209), 'cv2.imwrite', 'cv2.imwrite', (['path', 'img'], {}), '(path, img)\n', (2198, 2209), False, 'import cv2\n'), ((2367, 2389), 'os.path.exists', 'os.path.exists', (['outdir'], {}), '(outdir)\n', (2381, 2389), False, 'import os\n'), ((2400, 2419), 'os.makedirs', 'os.makedirs', (['outdir'], {}), '(outdir)\n', (2411, 2419), False, 'import os\n'), ((2551, 2572), 'mmcv.imread', 'mmcv.imread', (['filename'], {}), '(filename)\n', (2562, 2572), False, 'import mmcv\n'), ((2702, 2737), 'os.path.join', 'os.path.join', (['outdir', "(path + '.jpg')"], {}), "(outdir, path + '.jpg')\n", (2714, 2737), False, 'import os\n'), ((2758, 2780), 'numpy.vstack', 'np.vstack', (['bbox_result'], {}), '(bbox_result)\n', (2767, 2780), True, 'import numpy as np\n'), ((2936, 2958), 'numpy.concatenate', 'np.concatenate', (['labels'], {}), '(labels)\n', (2950, 2958), True, 'import numpy as np\n'), ((5791, 5851), 'torch.full', 'torch.full', (['(MAX_LEN,)', '(32)'], {'dtype': 'torch.uint8', 'device': '"""cuda"""'}), "((MAX_LEN,), 32, dtype=torch.uint8, device='cuda')\n", (5801, 5851), False, 'import torch\n'), ((6187, 6216), 'torch.distributed.broadcast', 'dist.broadcast', (['dir_tensor', '(0)'], {}), '(dir_tensor, 0)\n', (6201, 6216), True, 'import torch.distributed as dist\n'), ((6308, 6335), 'mmcv.mkdir_or_exist', 'mmcv.mkdir_or_exist', (['tmpdir'], {}), '(tmpdir)\n', (6327, 6335), False, 'import mmcv\n'), ((7049, 7070), 'shutil.rmtree', 'shutil.rmtree', (['tmpdir'], {}), '(tmpdir)\n', (7062, 7070), False, 'import shutil\n'), ((11758, 11801), 'mmdet.apis.init_dist', 'init_dist', (['args.launcher'], {}), '(args.launcher, **cfg.dist_params)\n', (11767, 11801), False, 'from mmdet.apis import init_dist\n'), ((12335, 12357), 'mmdet.core.wrap_fp16_model', 'wrap_fp16_model', (['model'], {}), '(model)\n', (12350, 12357), False, 'from mmdet.core import coco_eval, results2json, wrap_fp16_model, get_classes, tensor2imgs\n'), ((12741, 12778), 'mmcv.parallel.MMDataParallel', 'MMDataParallel', (['model'], {'device_ids': '[0]'}), '(model, device_ids=[0])\n', (12755, 12778), False, 'from mmcv.parallel import MMDataParallel, MMDistributedDataParallel\n'), ((2814, 2855), 'numpy.full', 'np.full', (['bbox.shape[0]', 'i'], {'dtype': 'np.int32'}), '(bbox.shape[0], i, dtype=np.int32)\n', (2821, 2855), True, 'import numpy as np\n'), ((3564, 3579), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3577, 3579), False, 'import torch\n'), ((5040, 5055), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5053, 5055), False, 'import torch\n'), ((5997, 6015), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (6013, 6015), False, 'import tempfile\n'), ((7290, 7315), 'pickle.dumps', 'pickle.dumps', (['result_part'], {}), '(result_part)\n', (7302, 7315), False, 'import pickle\n'), ((7642, 7666), 'torch.tensor', 'torch.tensor', (['shape_list'], {}), '(shape_list)\n', (7654, 7666), False, 'import torch\n'), ((10025, 10064), 'os.path.join', 'osp.join', (['path', "('Task1_' + cls + '.txt')"], {}), "(path, 'Task1_' + cls + '.txt')\n", (10033, 10064), True, 'import os.path as osp\n'), ((13277, 13308), 'os.path.join', 'osp.join', (['args.outdir', 'args.out'], {}), '(args.outdir, args.out)\n', (13285, 13308), True, 'import os.path as osp\n'), ((2643, 2681), 'os.path.splitext', 'os.path.splitext', (["img_meta['filename']"], {}), "(img_meta['filename'])\n", (2659, 2681), False, 'import os\n'), ((3745, 3771), 'os.path.join', 'osp.join', (['outdir', '"""images"""'], {}), "(outdir, 'images')\n", (3753, 3771), True, 'import os.path as osp\n'), ((6753, 6773), 'mmcv.load', 'mmcv.load', (['part_file'], {}), '(part_file)\n', (6762, 6773), False, 'import mmcv\n')]
|
import numpy as np
import gym
import torch
import random
from argparse import ArgumentParser
import os
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
from scipy.ndimage.filters import gaussian_filter1d
class Stats():
def __init__(self, num_episodes=20000, num_states = 6, log_dir='./', continuous=False):
self.episode_rewards = np.zeros(num_episodes)
self.episode_lengths = np.zeros(num_episodes)
if not continuous:
self.visitation_count = np.zeros((num_states, num_episodes))
self.target_count = np.zeros((num_states, num_episodes))
self.log_dir = log_dir
def log_data(self, file_name):
save_name = self.log_dir + file_name
np.savez(save_name, reward=self.episode_rewards, step=self.episode_lengths)
def plot_rewards(ax, episodes_ydata, smoothing_window = 100, label="",c='b', alpha=0.5):
#smoothing_window = 100
overall_stats_q_learning = []
for trialdata in episodes_ydata:
overall_stats_q_learning.append(pd.Series(trialdata.episode_rewards).rolling(smoothing_window, min_periods=smoothing_window).mean())
#overall_stats_q_learning.append(pd.Series(trialdata.episode_rewards).rolling(smoothing_window, min_periods=smoothing_window).mean().data)
m_stats_q_learning = np.mean(overall_stats_q_learning, axis=0)
std_stats_q_learning = np.std(overall_stats_q_learning, axis=0)
ax.plot(range(len(m_stats_q_learning)), m_stats_q_learning, label=label, c=c)
ax.fill_between(range(len(std_stats_q_learning)), m_stats_q_learning - std_stats_q_learning, m_stats_q_learning + std_stats_q_learning, alpha=alpha, edgecolor=c, facecolor=c)
#ax.set_ylabel('Score')
#ax.set_xlabel('Episode #')
#ax.grid()
def plot_steps(ax, episodes_ydata, smoothing_window = 100, label="",c='g',alpha=0.5):
#smoothing_window = 100
overall_stats_q_learning = []
for trialdata in episodes_ydata:
overall_stats_q_learning.append(pd.Series(trialdata.episode_lengths).rolling(smoothing_window, min_periods=smoothing_window).mean())
#overall_stats_q_learning.append(pd.Series(trialdata.episode_lengths).rolling(smoothing_window, min_periods=smoothing_window).mean().data)
m_stats_q_learning = np.mean(overall_stats_q_learning, axis=0)
std_stats_q_learning = np.std(overall_stats_q_learning, axis=0)
ax.plot(range(len(m_stats_q_learning)), m_stats_q_learning, label=label, c=c)
ax.fill_between(range(len(std_stats_q_learning)), m_stats_q_learning - std_stats_q_learning, m_stats_q_learning + std_stats_q_learning, alpha=alpha, edgecolor=c, facecolor=c)
#ax.set_ylabel('Steps')
#ax.set_xlabel('Episode #')
#ax.grid()
def plot_visitation_counts(episodes_ydata, smoothing_window = 1000, c=['b', 'g', 'r', 'y', 'k', 'c'], num_states = None):
if not num_states:
num_states = len(episodes_ydata[0].visitation_count)
overall_stats_q_learning = [[] for i in range(num_states)]
for trialdata in episodes_ydata:
for state in range(num_states):
overall_stats_q_learning[state].append(pd.Series(trialdata.visitation_count[state]).rolling(smoothing_window, min_periods=smoothing_window).mean().data)
for state in range(num_states):
m_stats_q_learning = np.mean(overall_stats_q_learning[state], axis=0)
std_stats_q_learning = np.std(overall_stats_q_learning[state], axis=0)
plt.plot(range(len(m_stats_q_learning)), m_stats_q_learning, c=c[state])
plt.fill_between(range(len(std_stats_q_learning)), m_stats_q_learning - std_stats_q_learning, m_stats_q_learning + std_stats_q_learning, alpha=0.5, edgecolor=c[state], facecolor=c[state])
def plot_target_counts(episodes_ydata, smoothing_window = 1000, c=['b', 'g', 'r', 'y', 'k', 'c']):
num_states = len(episodes_ydata[0].target_count)
overall_stats_q_learning = [[] for i in range(num_states)]
for trialdata in episodes_ydata:
for state in range(num_states):
overall_stats_q_learning[state].append(pd.Series(trialdata.target_count[state]).rolling(smoothing_window, min_periods=smoothing_window).mean().data)
for state in range(num_states):
m_stats_q_learning = np.mean(overall_stats_q_learning[state], axis=0)
std_stats_q_learning = np.std(overall_stats_q_learning[state], axis=0)
plt.plot(range(len(m_stats_q_learning)), m_stats_q_learning, c=c[state])
plt.fill_between(range(len(std_stats_q_learning)), m_stats_q_learning - std_stats_q_learning, m_stats_q_learning + std_stats_q_learning, alpha=0.5, edgecolor=c[state], facecolor=c[state])
def plot_q_values(model, observation_space, action_space):
res = 100
test_observations = np.linspace(observation_space.low, observation_space.high, res)
print((action_space.n, res))
q_values = np.zeros((action_space.n, res))
for action in range(action_space.n):
for obs in range(res):
q_values[action, obs] = model.predict(test_observations[obs])[0, action]
plt.plot(test_observations, q_values[action])
def arguments():
parser = ArgumentParser()
parser.add_argument('--env', default = 'BipedalWalker-v3')
return parser.parse_args()
def save(agent, rewards, args):
path = './runs/{}/'.format(args.env)
try:
os.makedirs(path)
except:
pass
torch.save(agent.q.state_dict(), os.path.join(path, 'model_state_dict'))
plt.cla()
plt.plot(rewards, c = 'r', alpha = 0.3)
plt.plot(gaussian_filter1d(rewards, sigma = 5), c = 'r', label = 'Rewards')
plt.xlabel('Episodes')
plt.ylabel('Cumulative reward')
plt.title('Branching DDQN: {}'.format(args.env))
plt.savefig(os.path.join(path, 'reward.png'))
pd.DataFrame(rewards, columns = ['Reward']).to_csv(os.path.join(path, 'rewards.csv'), index = False)
class AgentConfig:
def __init__(self,
epsilon_start = 1.,
epsilon_final = 0.01,
epsilon_decay = 8000,
gamma = 0.99,
lr = 1e-4,
target_net_update_freq = 1000,
memory_size = 100000,
batch_size = 128,
learning_starts = 5000,
max_frames = 10000000):
self.epsilon_start = epsilon_start
self.epsilon_final = epsilon_final
self.epsilon_decay = epsilon_decay
self.epsilon_by_frame = lambda i: self.epsilon_final + (self.epsilon_start - self.epsilon_final) * np.exp(-1. * i / self.epsilon_decay)
self.gamma =gamma
self.lr =lr
self.target_net_update_freq =target_net_update_freq
self.memory_size =memory_size
self.batch_size =batch_size
self.learning_starts = learning_starts
self.max_frames = max_frames
class ExperienceReplayMemory:
def __init__(self, capacity):
self.capacity = capacity
self.memory = []
def push(self, transition):
self.memory.append(transition)
if len(self.memory) > self.capacity:
del self.memory[0]
def sample(self, batch_size):
batch = random.sample(self.memory, batch_size)
states = []
actions = []
rewards = []
next_states = []
dones = []
for b in batch:
states.append(b[0])
actions.append(b[1])
rewards.append(b[2])
next_states.append(b[3])
dones.append(b[4])
return states, actions, rewards, next_states, dones
def __len__(self):
return len(self.memory)
import torch
import collections
import random
class ReplayBuffer():
def __init__(self,buffer_limit,action_space,device):
self.buffer = collections.deque(maxlen=buffer_limit)
self.action_space = action_space
self.device = device
def put(self, transition):
self.buffer.append(transition)
def sample(self, n):
mini_batch = random.sample(self.buffer, n)
state_lst, reward_lst, next_state_lst, done_mask_lst = [], [], [], []
actions_lst = [[] for i in range(self.action_space)]
for transition in mini_batch:
state, actions,reward, next_state, done_mask = transition
state_lst.append(state)
for idx in range(self.action_space):
actions_lst[idx].append(actions[idx])
reward_lst.append([reward])
next_state_lst.append(next_state)
done_mask_lst.append([done_mask])
actions_lst = [torch.tensor(x,dtype= torch.float).to(self.device) for x in actions_lst]
return torch.tensor(state_lst, dtype=torch.float).to(self.device),\
actions_lst ,torch.tensor(reward_lst).to(self.device),\
torch.tensor(next_state_lst, dtype=torch.float).to(self.device),\
torch.tensor(done_mask_lst).to(self.device)
def size(self):
return len(self.buffer)
class TensorEnv(gym.Wrapper):
def __init__(self, env_name):
super().__init__(gym.make(env_name))
def process(self, x):
return torch.tensor(x).reshape(1,-1).float()
def reset(self):
return self.process(super().reset())
def step(self, a):
ns, r, done, infos = super().step(a)
return self.process(ns), r, done, infos
class BranchingTensorEnv(TensorEnv):
def __init__(self, env_name, n):
super().__init__(env_name)
self.n = n
self.discretized = np.linspace(-1.,1., self.n)
def step(self, a):
action = np.array([self.discretized[aa] for aa in a])
return super().step(action)
|
[
"scipy.ndimage.filters.gaussian_filter1d",
"argparse.ArgumentParser",
"random.sample",
"matplotlib.pyplot.style.use",
"numpy.mean",
"numpy.exp",
"os.path.join",
"collections.deque",
"pandas.DataFrame",
"numpy.std",
"matplotlib.pyplot.cla",
"numpy.linspace",
"pandas.Series",
"matplotlib.pyplot.ylabel",
"numpy.savez",
"os.makedirs",
"matplotlib.pyplot.plot",
"gym.make",
"numpy.zeros",
"numpy.array",
"matplotlib.pyplot.xlabel",
"torch.tensor"
] |
[((163, 186), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (176, 186), True, 'import matplotlib.pyplot as plt\n'), ((1243, 1284), 'numpy.mean', 'np.mean', (['overall_stats_q_learning'], {'axis': '(0)'}), '(overall_stats_q_learning, axis=0)\n', (1250, 1284), True, 'import numpy as np\n'), ((1309, 1349), 'numpy.std', 'np.std', (['overall_stats_q_learning'], {'axis': '(0)'}), '(overall_stats_q_learning, axis=0)\n', (1315, 1349), True, 'import numpy as np\n'), ((2149, 2190), 'numpy.mean', 'np.mean', (['overall_stats_q_learning'], {'axis': '(0)'}), '(overall_stats_q_learning, axis=0)\n', (2156, 2190), True, 'import numpy as np\n'), ((2215, 2255), 'numpy.std', 'np.std', (['overall_stats_q_learning'], {'axis': '(0)'}), '(overall_stats_q_learning, axis=0)\n', (2221, 2255), True, 'import numpy as np\n'), ((4601, 4664), 'numpy.linspace', 'np.linspace', (['observation_space.low', 'observation_space.high', 'res'], {}), '(observation_space.low, observation_space.high, res)\n', (4612, 4664), True, 'import numpy as np\n'), ((4718, 4749), 'numpy.zeros', 'np.zeros', (['(action_space.n, res)'], {}), '((action_space.n, res))\n', (4726, 4749), True, 'import numpy as np\n'), ((4996, 5012), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (5010, 5012), False, 'from argparse import ArgumentParser\n'), ((5331, 5340), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (5338, 5340), True, 'import matplotlib.pyplot as plt\n'), ((5345, 5380), 'matplotlib.pyplot.plot', 'plt.plot', (['rewards'], {'c': '"""r"""', 'alpha': '(0.3)'}), "(rewards, c='r', alpha=0.3)\n", (5353, 5380), True, 'import matplotlib.pyplot as plt\n'), ((5469, 5491), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Episodes"""'], {}), "('Episodes')\n", (5479, 5491), True, 'import matplotlib.pyplot as plt\n'), ((5496, 5527), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cumulative reward"""'], {}), "('Cumulative reward')\n", (5506, 5527), True, 'import matplotlib.pyplot as plt\n'), ((371, 393), 'numpy.zeros', 'np.zeros', (['num_episodes'], {}), '(num_episodes)\n', (379, 393), True, 'import numpy as np\n'), ((419, 441), 'numpy.zeros', 'np.zeros', (['num_episodes'], {}), '(num_episodes)\n', (427, 441), True, 'import numpy as np\n'), ((687, 762), 'numpy.savez', 'np.savez', (['save_name'], {'reward': 'self.episode_rewards', 'step': 'self.episode_lengths'}), '(save_name, reward=self.episode_rewards, step=self.episode_lengths)\n', (695, 762), True, 'import numpy as np\n'), ((3163, 3211), 'numpy.mean', 'np.mean', (['overall_stats_q_learning[state]'], {'axis': '(0)'}), '(overall_stats_q_learning[state], axis=0)\n', (3170, 3211), True, 'import numpy as np\n'), ((3243, 3290), 'numpy.std', 'np.std', (['overall_stats_q_learning[state]'], {'axis': '(0)'}), '(overall_stats_q_learning[state], axis=0)\n', (3249, 3290), True, 'import numpy as np\n'), ((4095, 4143), 'numpy.mean', 'np.mean', (['overall_stats_q_learning[state]'], {'axis': '(0)'}), '(overall_stats_q_learning[state], axis=0)\n', (4102, 4143), True, 'import numpy as np\n'), ((4175, 4222), 'numpy.std', 'np.std', (['overall_stats_q_learning[state]'], {'axis': '(0)'}), '(overall_stats_q_learning[state], axis=0)\n', (4181, 4222), True, 'import numpy as np\n'), ((4917, 4962), 'matplotlib.pyplot.plot', 'plt.plot', (['test_observations', 'q_values[action]'], {}), '(test_observations, q_values[action])\n', (4925, 4962), True, 'import matplotlib.pyplot as plt\n'), ((5203, 5220), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (5214, 5220), False, 'import os\n'), ((5286, 5324), 'os.path.join', 'os.path.join', (['path', '"""model_state_dict"""'], {}), "(path, 'model_state_dict')\n", (5298, 5324), False, 'import os\n'), ((5398, 5433), 'scipy.ndimage.filters.gaussian_filter1d', 'gaussian_filter1d', (['rewards'], {'sigma': '(5)'}), '(rewards, sigma=5)\n', (5415, 5433), False, 'from scipy.ndimage.filters import gaussian_filter1d\n'), ((5597, 5629), 'os.path.join', 'os.path.join', (['path', '"""reward.png"""'], {}), "(path, 'reward.png')\n", (5609, 5629), False, 'import os\n'), ((5687, 5720), 'os.path.join', 'os.path.join', (['path', '"""rewards.csv"""'], {}), "(path, 'rewards.csv')\n", (5699, 5720), False, 'import os\n'), ((7043, 7081), 'random.sample', 'random.sample', (['self.memory', 'batch_size'], {}), '(self.memory, batch_size)\n', (7056, 7081), False, 'import random\n'), ((7650, 7688), 'collections.deque', 'collections.deque', ([], {'maxlen': 'buffer_limit'}), '(maxlen=buffer_limit)\n', (7667, 7688), False, 'import collections\n'), ((7880, 7909), 'random.sample', 'random.sample', (['self.buffer', 'n'], {}), '(self.buffer, n)\n', (7893, 7909), False, 'import random\n'), ((9413, 9443), 'numpy.linspace', 'np.linspace', (['(-1.0)', '(1.0)', 'self.n'], {}), '(-1.0, 1.0, self.n)\n', (9424, 9443), True, 'import numpy as np\n'), ((9484, 9528), 'numpy.array', 'np.array', (['[self.discretized[aa] for aa in a]'], {}), '([self.discretized[aa] for aa in a])\n', (9492, 9528), True, 'import numpy as np\n'), ((490, 526), 'numpy.zeros', 'np.zeros', (['(num_states, num_episodes)'], {}), '((num_states, num_episodes))\n', (498, 526), True, 'import numpy as np\n'), ((550, 586), 'numpy.zeros', 'np.zeros', (['(num_states, num_episodes)'], {}), '((num_states, num_episodes))\n', (558, 586), True, 'import numpy as np\n'), ((5636, 5677), 'pandas.DataFrame', 'pd.DataFrame', (['rewards'], {'columns': "['Reward']"}), "(rewards, columns=['Reward'])\n", (5648, 5677), True, 'import pandas as pd\n'), ((8960, 8978), 'gym.make', 'gym.make', (['env_name'], {}), '(env_name)\n', (8968, 8978), False, 'import gym\n'), ((6407, 6444), 'numpy.exp', 'np.exp', (['(-1.0 * i / self.epsilon_decay)'], {}), '(-1.0 * i / self.epsilon_decay)\n', (6413, 6444), True, 'import numpy as np\n'), ((8452, 8486), 'torch.tensor', 'torch.tensor', (['x'], {'dtype': 'torch.float'}), '(x, dtype=torch.float)\n', (8464, 8486), False, 'import torch\n'), ((8540, 8582), 'torch.tensor', 'torch.tensor', (['state_lst'], {'dtype': 'torch.float'}), '(state_lst, dtype=torch.float)\n', (8552, 8582), False, 'import torch\n'), ((8629, 8653), 'torch.tensor', 'torch.tensor', (['reward_lst'], {}), '(reward_lst)\n', (8641, 8653), False, 'import torch\n'), ((8688, 8735), 'torch.tensor', 'torch.tensor', (['next_state_lst'], {'dtype': 'torch.float'}), '(next_state_lst, dtype=torch.float)\n', (8700, 8735), False, 'import torch\n'), ((8769, 8796), 'torch.tensor', 'torch.tensor', (['done_mask_lst'], {}), '(done_mask_lst)\n', (8781, 8796), False, 'import torch\n'), ((9024, 9039), 'torch.tensor', 'torch.tensor', (['x'], {}), '(x)\n', (9036, 9039), False, 'import torch\n'), ((979, 1015), 'pandas.Series', 'pd.Series', (['trialdata.episode_rewards'], {}), '(trialdata.episode_rewards)\n', (988, 1015), True, 'import pandas as pd\n'), ((1885, 1921), 'pandas.Series', 'pd.Series', (['trialdata.episode_lengths'], {}), '(trialdata.episode_lengths)\n', (1894, 1921), True, 'import pandas as pd\n'), ((2979, 3023), 'pandas.Series', 'pd.Series', (['trialdata.visitation_count[state]'], {}), '(trialdata.visitation_count[state])\n', (2988, 3023), True, 'import pandas as pd\n'), ((3915, 3955), 'pandas.Series', 'pd.Series', (['trialdata.target_count[state]'], {}), '(trialdata.target_count[state])\n', (3924, 3955), True, 'import pandas as pd\n')]
|
import os
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import math
import argparse
import math
import h5py
import numpy as np
import tensorflow as tf
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# tf.logging.set_verbosity(tf.logging.ERROR)
import socket
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
sys.path.append(ROOT_DIR)
sys.path.append(os.path.join(ROOT_DIR, 'utils'))
import provider
import tf_util
from model import *
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', type=int, default=0, help='GPU to use [default: GPU 0]')
parser.add_argument('--log_dir', default='log', help='Log dir [default: log]')
parser.add_argument('--num_point', type=int, default=4096, help='Point number [default: 4096]')
parser.add_argument('--max_epoch', type=int, default=50, help='Epoch to run [default: 50]')
parser.add_argument('--batch_size', type=int, default=12, help='Batch Size during training [default: 12]')
parser.add_argument('--learning_rate', type=float, default=0.000001, help='Initial learning rate [default: 0.000001]')
parser.add_argument('--momentum', type=float, default=0.9, help='Initial learning rate [default: 0.9]')
parser.add_argument('--optimizer', default='momentum', help='adam or momentum [default: adam]')
parser.add_argument('--decay_step', type=int, default=300000, help='Decay step for lr decay [default: 300000]')
parser.add_argument('--decay_rate', type=float, default=0.5, help='Decay rate for lr decay [default: 0.5]')
parser.add_argument('--test_recordings', type=str, default='11', help='Which recording numbers to use for test, i.e "1,2", "1", "3", "3,4,5" [default: 11]')
parser.add_argument('--dir_path_h5', type=str, default='data/apollo_sem_seg_hdf5_data', help='directory containing the h5 files')
parser.add_argument('--use_saved_model', type=str, default='no', help='yes or no')
FLAGS = parser.parse_args()
LOAD_FULL_DATA = False
BATCH_SIZE = FLAGS.batch_size
NUM_POINT = FLAGS.num_point
MAX_EPOCH = FLAGS.max_epoch
BASE_LEARNING_RATE = FLAGS.learning_rate
GPU_INDEX = FLAGS.gpu
MOMENTUM = FLAGS.momentum
OPTIMIZER = FLAGS.optimizer
DECAY_STEP = FLAGS.decay_step
DECAY_RATE = FLAGS.decay_rate
LOG_DIR = FLAGS.log_dir
if not os.path.exists(LOG_DIR):
os.mkdir(LOG_DIR)
USE_SAVED_MODEL = False
if FLAGS.use_saved_model == 'yes':
USE_SAVED_MODEL = True
print('using saved model')
elif FLAGS.use_saved_model != 'no':
raise ValueError('use_saved_model param must be eitehr yes or no')
os.system('cp model.py %s' % (LOG_DIR)) # bkp of model def
os.system('cp train.py %s' % (LOG_DIR)) # bkp of train procedure
LOG_FOUT = open(os.path.join(LOG_DIR, 'log_train.txt'), 'w')
LOG_FOUT.write(str(FLAGS)+'\n')
MAX_NUM_POINT = 4096
BN_INIT_DECAY = 0.5
BN_DECAY_DECAY_RATE = 0.5
#BN_DECAY_DECAY_STEP = float(DECAY_STEP * 2)
BN_DECAY_DECAY_STEP = float(DECAY_STEP)
BN_DECAY_CLIP = 0.99
HOSTNAME = socket.gethostname()
# DIR_PATH_H5 = os.path.join(ROOT_DIR, 'data/apollo_sem_seg_hdf5_data_test')
DIR_PATH_H5 = FLAGS.dir_path_h5
if not os.path.exists(DIR_PATH_H5):
raise ValueError('the given h5 directory is invalid')
H5_FILES = [os.path.join(DIR_PATH_H5, file_h5) for file_h5 in os.listdir(DIR_PATH_H5) if file_h5[-2:] == 'h5']
#ALL_FILES = provider.getDataFiles('data/apollo_sem_seg_hdf5_data')
room_filelist = [line.rstrip() for line in open(os.path.join(DIR_PATH_H5, 'room_filelist.txt'))]
classMappings = [line.rstrip() for line in open(os.path.join(DIR_PATH_H5, 'class_mappings.txt'))]
NUM_CLASSES = len(classMappings)
BATCH_SIZE_H5 = provider.loadDataFile(H5_FILES[0])[0].shape[0]
# Load ALL data
# if LOAD_FULL_DATA:
# data_batch_list = []
# label_batch_list = []
# for i,h5_filename in enumerate(H5_FILES):
# if i%10 == 0:
# print("loading h5 file: " , i, h5_filename)
# data_batch, label_batch = provider.loadDataFile(h5_filename)
# data_batch_list.append(data_batch)
# label_batch_list.append(label_batch)
# if LOAD_FULL_DATA:
# print('---all loaded---')
# data_batches = np.concatenate(data_batch_list, 0)
# data_batch_list = None
# label_batches = np.concatenate(label_batch_list, 0)
# label_batch_list = None
# print(data_batches.shape)
# print(label_batches.shape)
data_for_training = np.empty(len(room_filelist), dtype=bool)
test_recordings = [str(int(recording_number)).zfill(3) for recording_number in FLAGS.test_recordings.split(',')]
#test_recordings = 'Area_'+str(FLAGS.test_area)
# if LOAD_FULL_DATA:
# train_idxs = []
# test_idxs = []
total_training_data = 0
total_testing_data = 0
for i,room_name in enumerate(room_filelist):
#remove this
if i%4==0:
total_testing_data += 1
data_for_training[i] = False
#if room_name[6:9] in test_recordings:
# if LOAD_FULL_DATA:
# test_idxs.append(i)
else:
total_training_data += 1
data_for_training[i] = True
# if LOAD_FULL_DATA:
# train_idxs.append(i)
# if LOAD_FULL_DATA:
# train_data = data_batches[train_idxs,...]
# train_label = label_batches[train_idxs]
# test_data = data_batches[test_idxs,...]
# test_label = label_batches[test_idxs]
# data_batches = None
# label_batches = None
# print(train_data.shape, train_label.shape)
# print(test_data.shape, test_label.shape)
current_train_idx = 0
current_test_idx = 0
last_loaded_file_index = None
last_loaded_file_data = None
last_loaded_file_label = None
def reset_train_data():
global current_train_idx
current_train_idx = 0
def reset_test_data():
global current_test_idx
current_test_idx = 0
def can_get_test_data():
global current_test_idx
return current_test_idx < data_for_training.shape[0]
def can_get_train_data():
global current_train_idx
global last_loaded_file_index
global last_loaded_file_data
global last_loaded_file_label
return current_train_idx < data_for_training.shape[0]
# h5_fileindex = int(math.floor( current_train_idx / float(BATCH_SIZE_H5) ))
# if h5_fileindex + 1 < len(H5_FILES):
# return True
# if last_loaded_file_index != h5_fileindex:
# h5_filename = H5_FILES[h5_fileindex]
# last_loaded_file_data, last_loaded_file_label = provider.loadDataFile(h5_filename)
# last_loaded_file_index = h5_fileindex
# start_idx_batch = current_train_idx - (h5_fileindex * BATCH_SIZE_H5)
# h5_remaining_batch_size = BATCH_SIZE_H5 - start_idx_batch
# return h5_remaining_batch_size > 0
def get_train_or_test_data(amount, for_training):
global current_train_idx
global current_test_idx
global last_loaded_file_index
global last_loaded_file_data
global last_loaded_file_label
local_data_batch_list = []
local_label_batch_list = []
total_retrieved = 0
if for_training:
index_for_run = current_train_idx
else:
index_for_run = current_test_idx
while total_retrieved < amount and index_for_run < data_for_training.shape[0]:
#total_retrieved += 1
h5_fileindex = int(math.floor( index_for_run / float(BATCH_SIZE_H5) ))
if last_loaded_file_index != h5_fileindex:
h5_filename = H5_FILES[h5_fileindex]
last_loaded_file_data, last_loaded_file_label = provider.loadDataFile(h5_filename)
last_loaded_file_index = h5_fileindex
amount_to_retrieve = amount - total_retrieved
start_idx_batch = index_for_run - (h5_fileindex * BATCH_SIZE_H5)
h5_remaining_batch_size = BATCH_SIZE_H5 - start_idx_batch
total_remaining_size = data_for_training.shape[0] - start_idx_batch
amount_to_fetch_from_batch = min(amount_to_retrieve, h5_remaining_batch_size, total_remaining_size)
start_idx_total = index_for_run
end_idx_total = start_idx_total + amount_to_fetch_from_batch
end_idx_batch = start_idx_batch + amount_to_fetch_from_batch
if for_training:
data_batch = (last_loaded_file_data[start_idx_batch:end_idx_batch]) [data_for_training[start_idx_total:end_idx_total],:,:]
label_batch = (last_loaded_file_label[start_idx_batch:end_idx_batch]) [data_for_training[start_idx_total:end_idx_total],:]
else:
arr = data_for_training[start_idx_total:end_idx_total] == False
data_batch = (last_loaded_file_data[start_idx_batch:end_idx_batch]) [arr,:,:]
label_batch = (last_loaded_file_label[start_idx_batch:end_idx_batch]) [arr,:]
total_retrieved += data_batch.shape[0]
index_for_run += amount_to_fetch_from_batch
local_data_batch_list.append(data_batch)
local_label_batch_list.append(label_batch)
local_data_batches = np.concatenate(local_data_batch_list, 0)
local_label_batches = np.concatenate(local_label_batch_list, 0)
if for_training:
current_train_idx = index_for_run
else:
current_test_idx = index_for_run
return local_data_batches, local_label_batches
def log_string(out_str):
LOG_FOUT.write(out_str+'\n')
LOG_FOUT.flush()
print(out_str)
def get_learning_rate(batch):
learning_rate = tf.train.exponential_decay(
BASE_LEARNING_RATE, # Base learning rate.
batch * BATCH_SIZE, # Current index into the dataset.
DECAY_STEP, # Decay step.
DECAY_RATE, # Decay rate.
staircase=True)
learning_rate = tf.maximum(learning_rate, 0.00001) # CLIP THE LEARNING RATE!!
return learning_rate
def get_bn_decay(batch):
bn_momentum = tf.train.exponential_decay(
BN_INIT_DECAY,
batch*BATCH_SIZE,
BN_DECAY_DECAY_STEP,
BN_DECAY_DECAY_RATE,
staircase=True)
bn_decay = tf.minimum(BN_DECAY_CLIP, 1 - bn_momentum)
return bn_decay
def train(use_saved_model ):
with tf.Graph().as_default():
with tf.device('/gpu:'+str(GPU_INDEX)):
pointclouds_pl, labels_pl = placeholder_inputs(BATCH_SIZE, NUM_POINT)
is_training_pl = tf.placeholder(tf.bool, shape=())
# Note the global_step=batch parameter to minimize.
# That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.
batch = tf.Variable(0)
bn_decay = get_bn_decay(batch)
tf.summary.scalar('bn_decay', bn_decay)
# Get model and loss
pred = get_model(pointclouds_pl, is_training_pl, bn_decay=bn_decay, num_classes=NUM_CLASSES)
loss = get_loss(pred, labels_pl)
tf.summary.scalar('loss', loss)
correct = tf.equal(tf.argmax(pred, 2), tf.to_int64(labels_pl))
accuracy = tf.reduce_sum(tf.cast(correct, tf.float32)) / float(BATCH_SIZE*NUM_POINT)
tf.summary.scalar('accuracy', accuracy)
# Get training operator
learning_rate = get_learning_rate(batch)
tf.summary.scalar('learning_rate', learning_rate)
if OPTIMIZER == 'momentum':
optimizer = tf.train.MomentumOptimizer(learning_rate, momentum=MOMENTUM)
elif OPTIMIZER == 'adam':
optimizer = tf.train.AdamOptimizer(learning_rate)
train_op = optimizer.minimize(loss, global_step=batch)
# Add ops to save and restore all the variables.
saver = tf.train.Saver()
# Create a session
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.allow_soft_placement = True
config.log_device_placement = False
sess = tf.Session(config=config)
# Init variables
init = tf.global_variables_initializer()
sess.run(init, {is_training_pl:True})
if use_saved_model:
saver.restore(sess, os.path.join(LOG_DIR,'model.ckpt'))
# Add summary writers
merged = tf.summary.merge_all()
train_writer = tf.summary.FileWriter(os.path.join(LOG_DIR, 'train'),
sess.graph)
test_writer = tf.summary.FileWriter(os.path.join(LOG_DIR, 'test'))
ops = {'pointclouds_pl': pointclouds_pl,
'labels_pl': labels_pl,
'is_training_pl': is_training_pl,
'pred': pred,
'loss': loss,
'train_op': train_op,
'merged': merged,
'step': batch}
if use_saved_model:
eval_one_epoch(sess, ops, test_writer)
for epoch in range(MAX_EPOCH):
log_string('**** EPOCH %03d ****' % (epoch))
sys.stdout.flush()
train_one_epoch(sess, ops, train_writer)
save_path = saver.save(sess, os.path.join(LOG_DIR, "model.ckpt"))
log_string("Model saved in file: %s" % save_path)
eval_one_epoch(sess, ops, test_writer)
# # Save the variables to disk.
# if epoch % 1 == 0:
def train_one_epoch(sess, ops, train_writer):
reset_train_data()
""" ops: dict mapping from string to tf ops """
is_training = True
log_string('----')
#checking to confirm get_train_data is functioning correctly
# if LOAD_FULL_DATA:
# current_data = train_data
# current_label = train_label
# file_size = current_data.shape[0]
# num_batches = file_size // BATCH_SIZE
# num_batches = total_training_data / BATCH_SIZE
total_correct = 0
total_seen = 0
loss_sum = 0
batch_idx = -1
# for batch_idx in range(num_batches):
while can_get_train_data():
batch_idx += 1
if batch_idx % 10 == 0:
print('Current batch: %d'%(batch_idx))
start_idx = batch_idx * BATCH_SIZE
end_idx = (batch_idx+1) * BATCH_SIZE
data_for_loop, label_for_loop = get_train_or_test_data(BATCH_SIZE, True)
#this is in case the last batch has insufficient blocks, so we simply bail
if not can_get_train_data():
break;
#checking to confirm get_train_data is functioning correctly
# check_data_for_loop = current_data[start_idx:end_idx, :, :]
# check_label_for_loop = current_label[start_idx:end_idx]
# if sum(sum(sum(data_for_loop == check_data_for_loop))) != 442368:
# z = 32131
# log_string('check data for loop not match what it should be')
# raise ValueError('check data for loop not match what it should be')
#remove below comments
feed_dict = {ops['pointclouds_pl']: data_for_loop,
ops['labels_pl']: label_for_loop,
ops['is_training_pl']: is_training,}
summary, step, _, loss_val, pred_val = sess.run([ops['merged'], ops['step'], ops['train_op'], ops['loss'], ops['pred']],
feed_dict=feed_dict)
train_writer.add_summary(summary, step)
pred_val = np.argmax(pred_val, 2)
correct = np.sum(pred_val == label_for_loop)
total_correct += correct
total_seen += (BATCH_SIZE*NUM_POINT)
loss_sum += loss_val
#remove below comments
# log_string('mean loss: %f' % (loss_sum / float(num_batches)))
# log_string('accuracy: %f' % (total_correct / float(total_seen)))
def eval_one_epoch(sess, ops, test_writer):
reset_test_data()
""" ops: dict mapping from string to tf ops """
is_training = False
total_correct = 0
total_seen = 0
loss_sum = 0
total_seen_class = [0 for _ in range(NUM_CLASSES)]
total_correct_class = [0 for _ in range(NUM_CLASSES)]
log_string('----')
# current_data = test_data[:,0:NUM_POINT,:]
# current_label = np.squeeze(test_label)
# file_size = current_data.shape[0]
# num_batches = file_size // BATCH_SIZE
batch_idx = -1
# for batch_idx in range(num_batches):
while can_get_test_data():
batch_idx += 1
data_for_loop, label_for_loop = get_train_or_test_data(BATCH_SIZE, False)
#this is in case the last batch has insufficient blocks
if not can_get_test_data():
break
start_idx = batch_idx * BATCH_SIZE
end_idx = (batch_idx+1) * BATCH_SIZE
feed_dict = {ops['pointclouds_pl']: data_for_loop,
ops['labels_pl']: label_for_loop,
ops['is_training_pl']: is_training}
summary, step, loss_val, pred_val = sess.run([ops['merged'], ops['step'], ops['loss'], ops['pred']],
feed_dict=feed_dict)
test_writer.add_summary(summary, step)
pred_val = np.argmax(pred_val, 2)
correct = np.sum(pred_val == label_for_loop)
total_correct += correct
total_seen += (BATCH_SIZE*NUM_POINT)
loss_sum += (loss_val*BATCH_SIZE)
for i in range(start_idx, end_idx):
for j in range(NUM_POINT):
try:
l = label_for_loop[i - start_idx, j - start_idx]
total_seen_class[l] += 1
total_correct_class[l] += (pred_val[i-start_idx, j] == l)
except:
l = label_for_loop[i - start_idx, j - start_idx]
total_seen_class[l] += 1
total_correct_class[l] += (pred_val[i-start_idx, j] == l)
log_string('eval mean loss: %f' % (loss_sum / float(total_seen/NUM_POINT)))
log_string('eval accuracy: %f'% (total_correct / float(total_seen)))
log_string('eval avg class acc: %f' % (np.mean(np.array(total_correct_class)/np.array(total_seen_class,dtype=np.float))))
print('total correct class')
print(total_correct_class)
print('total seen class')
print(total_seen_class)
if __name__ == "__main__":
train(USE_SAVED_MODEL)
LOG_FOUT.close()
|
[
"os.mkdir",
"numpy.sum",
"argparse.ArgumentParser",
"numpy.argmax",
"tensorflow.maximum",
"tensorflow.ConfigProto",
"tensorflow.Variable",
"sys.stdout.flush",
"os.path.join",
"provider.loadDataFile",
"sys.path.append",
"os.path.abspath",
"os.path.dirname",
"tensorflow.to_int64",
"os.path.exists",
"tensorflow.minimum",
"socket.gethostname",
"tensorflow.placeholder",
"tensorflow.cast",
"tensorflow.summary.merge_all",
"tensorflow.summary.scalar",
"tensorflow.train.Saver",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"os.system",
"tensorflow.train.MomentumOptimizer",
"tensorflow.Graph",
"tensorflow.train.exponential_decay",
"os.listdir",
"numpy.concatenate",
"tensorflow.argmax",
"numpy.array",
"tensorflow.train.AdamOptimizer"
] |
[((329, 354), 'os.path.dirname', 'os.path.dirname', (['BASE_DIR'], {}), '(BASE_DIR)\n', (344, 354), False, 'import os\n'), ((355, 380), 'sys.path.append', 'sys.path.append', (['BASE_DIR'], {}), '(BASE_DIR)\n', (370, 380), False, 'import sys\n'), ((381, 406), 'sys.path.append', 'sys.path.append', (['ROOT_DIR'], {}), '(ROOT_DIR)\n', (396, 406), False, 'import sys\n'), ((519, 544), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (542, 544), False, 'import argparse\n'), ((2540, 2577), 'os.system', 'os.system', (["('cp model.py %s' % LOG_DIR)"], {}), "('cp model.py %s' % LOG_DIR)\n", (2549, 2577), False, 'import os\n'), ((2599, 2636), 'os.system', 'os.system', (["('cp train.py %s' % LOG_DIR)"], {}), "('cp train.py %s' % LOG_DIR)\n", (2608, 2636), False, 'import os\n'), ((2945, 2965), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (2963, 2965), False, 'import socket\n'), ((291, 316), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (306, 316), False, 'import os\n'), ((423, 454), 'os.path.join', 'os.path.join', (['ROOT_DIR', '"""utils"""'], {}), "(ROOT_DIR, 'utils')\n", (435, 454), False, 'import os\n'), ((2265, 2288), 'os.path.exists', 'os.path.exists', (['LOG_DIR'], {}), '(LOG_DIR)\n', (2279, 2288), False, 'import os\n'), ((2295, 2312), 'os.mkdir', 'os.mkdir', (['LOG_DIR'], {}), '(LOG_DIR)\n', (2303, 2312), False, 'import os\n'), ((2680, 2718), 'os.path.join', 'os.path.join', (['LOG_DIR', '"""log_train.txt"""'], {}), "(LOG_DIR, 'log_train.txt')\n", (2692, 2718), False, 'import os\n'), ((3083, 3110), 'os.path.exists', 'os.path.exists', (['DIR_PATH_H5'], {}), '(DIR_PATH_H5)\n', (3097, 3110), False, 'import os\n'), ((3182, 3216), 'os.path.join', 'os.path.join', (['DIR_PATH_H5', 'file_h5'], {}), '(DIR_PATH_H5, file_h5)\n', (3194, 3216), False, 'import os\n'), ((8878, 8918), 'numpy.concatenate', 'np.concatenate', (['local_data_batch_list', '(0)'], {}), '(local_data_batch_list, 0)\n', (8892, 8918), True, 'import numpy as np\n'), ((8945, 8986), 'numpy.concatenate', 'np.concatenate', (['local_label_batch_list', '(0)'], {}), '(local_label_batch_list, 0)\n', (8959, 8986), True, 'import numpy as np\n'), ((9315, 9425), 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (['BASE_LEARNING_RATE', '(batch * BATCH_SIZE)', 'DECAY_STEP', 'DECAY_RATE'], {'staircase': '(True)'}), '(BASE_LEARNING_RATE, batch * BATCH_SIZE,\n DECAY_STEP, DECAY_RATE, staircase=True)\n', (9341, 9425), True, 'import tensorflow as tf\n'), ((9667, 9699), 'tensorflow.maximum', 'tf.maximum', (['learning_rate', '(1e-05)'], {}), '(learning_rate, 1e-05)\n', (9677, 9699), True, 'import tensorflow as tf\n'), ((9806, 9929), 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (['BN_INIT_DECAY', '(batch * BATCH_SIZE)', 'BN_DECAY_DECAY_STEP', 'BN_DECAY_DECAY_RATE'], {'staircase': '(True)'}), '(BN_INIT_DECAY, batch * BATCH_SIZE,\n BN_DECAY_DECAY_STEP, BN_DECAY_DECAY_RATE, staircase=True)\n', (9832, 9929), True, 'import tensorflow as tf\n'), ((10050, 10092), 'tensorflow.minimum', 'tf.minimum', (['BN_DECAY_CLIP', '(1 - bn_momentum)'], {}), '(BN_DECAY_CLIP, 1 - bn_momentum)\n', (10060, 10092), True, 'import tensorflow as tf\n'), ((3232, 3255), 'os.listdir', 'os.listdir', (['DIR_PATH_H5'], {}), '(DIR_PATH_H5)\n', (3242, 3255), False, 'import os\n'), ((11768, 11784), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (11782, 11784), True, 'import tensorflow as tf\n'), ((11934, 11959), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (11944, 11959), True, 'import tensorflow as tf\n'), ((12003, 12036), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (12034, 12036), True, 'import tensorflow as tf\n'), ((12230, 12252), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), '()\n', (12250, 12252), True, 'import tensorflow as tf\n'), ((15332, 15354), 'numpy.argmax', 'np.argmax', (['pred_val', '(2)'], {}), '(pred_val, 2)\n', (15341, 15354), True, 'import numpy as np\n'), ((15373, 15407), 'numpy.sum', 'np.sum', (['(pred_val == label_for_loop)'], {}), '(pred_val == label_for_loop)\n', (15379, 15407), True, 'import numpy as np\n'), ((17040, 17062), 'numpy.argmax', 'np.argmax', (['pred_val', '(2)'], {}), '(pred_val, 2)\n', (17049, 17062), True, 'import numpy as np\n'), ((17081, 17115), 'numpy.sum', 'np.sum', (['(pred_val == label_for_loop)'], {}), '(pred_val == label_for_loop)\n', (17087, 17115), True, 'import numpy as np\n'), ((3399, 3445), 'os.path.join', 'os.path.join', (['DIR_PATH_H5', '"""room_filelist.txt"""'], {}), "(DIR_PATH_H5, 'room_filelist.txt')\n", (3411, 3445), False, 'import os\n'), ((3496, 3543), 'os.path.join', 'os.path.join', (['DIR_PATH_H5', '"""class_mappings.txt"""'], {}), "(DIR_PATH_H5, 'class_mappings.txt')\n", (3508, 3543), False, 'import os\n'), ((3598, 3632), 'provider.loadDataFile', 'provider.loadDataFile', (['H5_FILES[0]'], {}), '(H5_FILES[0])\n', (3619, 3632), False, 'import provider\n'), ((7426, 7460), 'provider.loadDataFile', 'provider.loadDataFile', (['h5_filename'], {}), '(h5_filename)\n', (7447, 7460), False, 'import provider\n'), ((10336, 10369), 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool'], {'shape': '()'}), '(tf.bool, shape=())\n', (10350, 10369), True, 'import tensorflow as tf\n'), ((10582, 10596), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {}), '(0)\n', (10593, 10596), True, 'import tensorflow as tf\n'), ((10652, 10691), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""bn_decay"""', 'bn_decay'], {}), "('bn_decay', bn_decay)\n", (10669, 10691), True, 'import tensorflow as tf\n'), ((10889, 10920), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""loss"""', 'loss'], {}), "('loss', loss)\n", (10906, 10920), True, 'import tensorflow as tf\n'), ((11106, 11145), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""accuracy"""', 'accuracy'], {}), "('accuracy', accuracy)\n", (11123, 11145), True, 'import tensorflow as tf\n'), ((11248, 11297), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""learning_rate"""', 'learning_rate'], {}), "('learning_rate', learning_rate)\n", (11265, 11297), True, 'import tensorflow as tf\n'), ((11692, 11708), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (11706, 11708), True, 'import tensorflow as tf\n'), ((12298, 12328), 'os.path.join', 'os.path.join', (['LOG_DIR', '"""train"""'], {}), "(LOG_DIR, 'train')\n", (12310, 12328), False, 'import os\n'), ((12420, 12449), 'os.path.join', 'os.path.join', (['LOG_DIR', '"""test"""'], {}), "(LOG_DIR, 'test')\n", (12432, 12449), False, 'import os\n'), ((12937, 12955), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (12953, 12955), False, 'import sys\n'), ((10152, 10162), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (10160, 10162), True, 'import tensorflow as tf\n'), ((10953, 10971), 'tensorflow.argmax', 'tf.argmax', (['pred', '(2)'], {}), '(pred, 2)\n', (10962, 10971), True, 'import tensorflow as tf\n'), ((10973, 10995), 'tensorflow.to_int64', 'tf.to_int64', (['labels_pl'], {}), '(labels_pl)\n', (10984, 10995), True, 'import tensorflow as tf\n'), ((11366, 11426), 'tensorflow.train.MomentumOptimizer', 'tf.train.MomentumOptimizer', (['learning_rate'], {'momentum': 'MOMENTUM'}), '(learning_rate, momentum=MOMENTUM)\n', (11392, 11426), True, 'import tensorflow as tf\n'), ((12146, 12181), 'os.path.join', 'os.path.join', (['LOG_DIR', '"""model.ckpt"""'], {}), "(LOG_DIR, 'model.ckpt')\n", (12158, 12181), False, 'import os\n'), ((13064, 13099), 'os.path.join', 'os.path.join', (['LOG_DIR', '"""model.ckpt"""'], {}), "(LOG_DIR, 'model.ckpt')\n", (13076, 13099), False, 'import os\n'), ((11034, 11062), 'tensorflow.cast', 'tf.cast', (['correct', 'tf.float32'], {}), '(correct, tf.float32)\n', (11041, 11062), True, 'import tensorflow as tf\n'), ((11493, 11530), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['learning_rate'], {}), '(learning_rate)\n', (11515, 11530), True, 'import tensorflow as tf\n'), ((17967, 17996), 'numpy.array', 'np.array', (['total_correct_class'], {}), '(total_correct_class)\n', (17975, 17996), True, 'import numpy as np\n'), ((17997, 18039), 'numpy.array', 'np.array', (['total_seen_class'], {'dtype': 'np.float'}), '(total_seen_class, dtype=np.float)\n', (18005, 18039), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""
201901, Dr. <NAME>, Beijing & Xinglong, NAOC
202101-? Dr. <NAME> & Dr./Prof. <NAME>
Light_Curve_Pipeline
v3 (2021A) Upgrade from former version, remove unused code
"""
import numpy as np
import matplotlib
#matplotlib.use('Agg')
from matplotlib import pyplot as plt
from .JZ_utils import meanclip
def plot_im_star(ini, img, x, y, mag, err, title, filename):
"""
Plot observed image and overplot stars
:param ini:
:param img:
:param x:
:param y:
:param mag:
:param err:
:param title:
:param filename: file to save
:return:
"""
ny, nx = img.shape
fig = plt.figure(figsize=(nx/50.0, ny/50.0))
ax = fig.add_subplot(111)
d_m, d_s = meanclip(img)
ax.imshow(img, cmap="gray",
vmin=d_m - d_s * ini["plot_img_lowsigma"],
vmax=d_m + d_s * ini["plot_img_highsigma"])
ax.set_xlim(0, nx)
ax.set_ylim(0, ny)
ix_g = np.where(err < 0.1)
ix_b = np.where(err >= 0.1)
ms = (25.0 - mag) * 5
ms[mag > 25] = 1.0
# ms[mag < 10] = 15.0
ax.scatter(x[ix_g], y[ix_g], marker="o", s=ms[ix_g], c="", edgecolors="r")
ax.scatter(x[ix_b], y[ix_b], marker="o", s=ms[ix_b], c="", edgecolors="c")
ax.set_title(title)
fig.savefig(filename, bbox_inches='tight')
plt.close()
def plot_magerr(ini, mag, err, title, filename):
"""
Plot mag-err figure
:param ini:
:param mag:
:param err:
:param title:
:param filename: file to save
:return:
"""
fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(111)
ax.plot(mag, err, '.')
ax.set_xlim(10, 25)
ax.set_ylim(-0.001, 1.0)
ax.set_xlabel("Mag (Inst)")
ax.set_ylabel("Error")
ax.set_title(title)
fig.savefig(filename)
plt.close()
def plot_im_target(ini, img,
target_x, target_y,
ref_x, ref_y,
chk_x, chk_y,
title, filename,
target_marker=("s", "r"),
ref_marker=("s", "y"),
chk_marker=("o", "y"),
noplot=False,
):
"""
Plot image and mark target, referenece, and check stars
:param ini:
:param img:
:param target_x:
:param target_y:
:param ref_x:
:param ref_y:
:param chk_x:
:param chk_y:
:param title:
:param filename:
:param target_marker: 2-tuple for marker, marker type and border color
:param ref_marker:
:param chk_marker:
:param noplot:
:return:
"""
ny, nx = img.shape
fig = plt.figure(figsize=(nx / 100.0, ny / 100.0))
ax = fig.add_subplot(111)
fsize = nx / 100 # font size
msize = fsize * 5 # marker size
d_m, d_s = meanclip(img)
ax.imshow(img, cmap="gray",
vmin=d_m - d_s * ini["plot_img_lowsigma"],
vmax=d_m + d_s * ini["plot_img_highsigma"])
ax.set_xlim(0, nx)
ax.set_ylim(0, ny)
if target_x is not None:
ax.scatter(target_x, target_y, marker=target_marker[0], s=msize, c=None, edgecolors=target_marker[1])
if np.isscalar(target_x): target_x = (target_x, )
if np.isscalar(target_y): target_y = (target_y, )
for i in range(len(target_x)):
ax.text(target_x[i]+fsize/2, target_y[i]+fsize/2, "T-{}".format(i),
color=target_marker[1], fontsize=fsize)
if ref_x is not None:
ax.scatter(ref_x, ref_y, marker=ref_marker[0], s=msize, c=None, edgecolors=ref_marker[1])
if np.isscalar(ref_x): ref_x = (ref_x, )
if np.isscalar(ref_y): ref_y = (ref_y, )
for i in range(len(ref_x)):
ax.text(ref_x[i]+fsize/2, ref_y[i]+fsize/2, "R-{}".format(i),
color=ref_marker[1], fontsize=fsize)
if chk_x is not None:
ax.scatter(chk_x, chk_y, marker=chk_marker[0], s=msize, c=None, edgecolors=chk_marker[1])
if np.isscalar(chk_x): chk_x = (chk_x, )
if np.isscalar(chk_y): chk_y = (chk_y, )
for i in range(len(chk_x)):
ax.text(chk_x[i]+fsize/2, chk_y[i]+fsize/2, "C-{}".format(i),
color=chk_marker[1], fontsize=fsize)
ax.set_title(title)
fig.savefig(filename, bbox_inches='tight')
if noplot:
plt.close(fig)
def plot_im_obj(ini, img,
obj_x, obj_y,
title, filename,
target_marker=("s", "r"),
noplot=False,
):
"""
Plot only objects, without using ref or check
:param ini:
:param img:
:param obj_x:
:param obj_y:
:param title:
:param filename:
:param target_marker:
:param noplot:
:return:
"""
plot_im_target(ini, img, obj_x, obj_y,
None, None, None, None,
title, filename,
target_marker,
noplot=noplot,
)
|
[
"numpy.isscalar",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"numpy.where"
] |
[((655, 697), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(nx / 50.0, ny / 50.0)'}), '(figsize=(nx / 50.0, ny / 50.0))\n', (665, 697), True, 'from matplotlib import pyplot as plt\n'), ((959, 978), 'numpy.where', 'np.where', (['(err < 0.1)'], {}), '(err < 0.1)\n', (967, 978), True, 'import numpy as np\n'), ((990, 1010), 'numpy.where', 'np.where', (['(err >= 0.1)'], {}), '(err >= 0.1)\n', (998, 1010), True, 'import numpy as np\n'), ((1321, 1332), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1330, 1332), True, 'from matplotlib import pyplot as plt\n'), ((1548, 1575), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (1558, 1575), True, 'from matplotlib import pyplot as plt\n'), ((1802, 1813), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1811, 1813), True, 'from matplotlib import pyplot as plt\n'), ((2618, 2662), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(nx / 100.0, ny / 100.0)'}), '(figsize=(nx / 100.0, ny / 100.0))\n', (2628, 2662), True, 'from matplotlib import pyplot as plt\n'), ((3139, 3160), 'numpy.isscalar', 'np.isscalar', (['target_x'], {}), '(target_x)\n', (3150, 3160), True, 'import numpy as np\n'), ((3197, 3218), 'numpy.isscalar', 'np.isscalar', (['target_y'], {}), '(target_y)\n', (3208, 3218), True, 'import numpy as np\n'), ((3559, 3577), 'numpy.isscalar', 'np.isscalar', (['ref_x'], {}), '(ref_x)\n', (3570, 3577), True, 'import numpy as np\n'), ((3608, 3626), 'numpy.isscalar', 'np.isscalar', (['ref_y'], {}), '(ref_y)\n', (3619, 3626), True, 'import numpy as np\n'), ((3949, 3967), 'numpy.isscalar', 'np.isscalar', (['chk_x'], {}), '(chk_x)\n', (3960, 3967), True, 'import numpy as np\n'), ((3998, 4016), 'numpy.isscalar', 'np.isscalar', (['chk_y'], {}), '(chk_y)\n', (4009, 4016), True, 'import numpy as np\n'), ((4299, 4313), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (4308, 4313), True, 'from matplotlib import pyplot as plt\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 15 15:16:06 2018
@author: Arpit
"""
import numpy as np
import matplotlib.pyplot as plt
import threading
from settings import charts_folder
class GraphPlot:
lock = threading.Lock()
def __init__(self, name, xCnt=1, yCnt=1, labels=None):
self.name = name
self.xCnt = xCnt
self.yCnt = yCnt
self.labels = labels
self.X = []
self.Ys = np.empty((yCnt,), dtype=object)
for i,v in enumerate(self.Ys): self.Ys[i] = list()
def add(self, X, Y):
self.X.append(X)
for i in range(self.yCnt):
self.Ys[i].append(Y[i])
def save(self):
try:
with self.lock:
fig = plt.figure()
for i in range(self.yCnt):
plt.plot(self.X, self.Ys[i], label=self.labels[i] if self.labels is not None else i)
plt.legend(loc = "best")
plt.savefig(charts_folder + str(self.name) + '.png')
plt.close(fig)
except Exception as e:
print("error: " + str(e))
plt.close()
|
[
"matplotlib.pyplot.plot",
"numpy.empty",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"threading.Lock",
"matplotlib.pyplot.figure"
] |
[((239, 255), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (253, 255), False, 'import threading\n'), ((471, 502), 'numpy.empty', 'np.empty', (['(yCnt,)'], {'dtype': 'object'}), '((yCnt,), dtype=object)\n', (479, 502), True, 'import numpy as np\n'), ((781, 793), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (791, 793), True, 'import matplotlib.pyplot as plt\n'), ((975, 997), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (985, 997), True, 'import matplotlib.pyplot as plt\n'), ((1085, 1099), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (1094, 1099), True, 'import matplotlib.pyplot as plt\n'), ((1198, 1209), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1207, 1209), True, 'import matplotlib.pyplot as plt\n'), ((857, 945), 'matplotlib.pyplot.plot', 'plt.plot', (['self.X', 'self.Ys[i]'], {'label': '(self.labels[i] if self.labels is not None else i)'}), '(self.X, self.Ys[i], label=self.labels[i] if self.labels is not\n None else i)\n', (865, 945), True, 'import matplotlib.pyplot as plt\n')]
|
import os
import random
import numpy as np
from scipy.spatial.distance import cdist
import cv2
import time
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
# import torch.multiprocessing as mp
from torch.utils.data import DataLoader
from torch.optim import Adam, SGD
# from torch.utils.tensorboard import SummaryWriter
from scipy.spatial.distance import cdist
from package.model.cmt import CMT
from package.loss.cmt_loss import _CMT_loss
from package.dataset.data_cmt import *
from package.args.cmt_args import parse_config
from package.dataset.utils import make_logger
from package.model.utils import *
from package.loss.regularization import _Regularization
import numpy as np
from sklearn.neighbors import NearestNeighbors as NN
DEBUG = False
def dr_dec(optimizer, args):
args.lr *= 0.5
args.lr = max(args.lr, 5e-5)
optimizer.param_groups[0]['lr'] = args.lr
def _get_pre_from_matches(matches):
"""
:param matches: A n-by-m matrix. n is number of test samples, m is the top m elements used for evaluation
:return: precision
"""
return np.mean(matches)
def _map_change(inputArr):
dup = np.copy(inputArr)
for idx in range(inputArr.shape[1]):
if idx != 0:
# dup cannot be bool type
dup[:,idx] = dup[:,idx-1] + dup[:,idx]
return np.multiply(dup, inputArr)
def _get_map_from_matches(matches):
"""
mAP's calculation refers to https://github.com/ShivaKrishnaM/ZS-SBIR/blob/master/trainCVAE_pre.py.
:param matches: A n-by-m matrix. n is number of test samples, m is the top m elements used for evaluation
matches[i][j] == 1 indicates the j-th retrieved test image j belongs to the same class as test sketch i,
otherwise, matches[i][j] = 0.
:return: mAP
"""
temp = [np.arange(matches.shape[1]) for _ in range(matches.shape[0])]
mAP_term = 1.0 / (np.stack(temp, axis=0) + 1.0)
precisions = np.multiply(_map_change(matches), mAP_term)
mAP = np.mean(precisions, axis=1)
return np.mean(mAP)
def _eval(feats_labels_sk, feats_labels_im, n=200):
"""
:param feats_labels_sk: a two-element tuple [features_of_sketches, labels_of_sketches]
labels_of_sketches and labels_of_images are scalars(class id).
:param feats_labels_im: a two-element tuple [features_of_images, labels_of_images]
features_of_images and features_of_sketches are used for distance calculation.
:param n: the top n elements used for evaluation
:return: precision@n, mAP@n, mAP@all
"""
nn = NN(n_neighbors=feats_labels_im[0].shape[0], metric='cosine', algorithm='brute').fit(feats_labels_im[0])
_, indices = nn.kneighbors(feats_labels_sk[0])
retrieved_classes = np.array(feats_labels_im[1])[indices]
matches = np.vstack([(retrieved_classes[i] == feats_labels_sk[1][i])
for i in range(retrieved_classes.shape[0])]).astype(np.uint16)
return _get_pre_from_matches(matches[:, :n]), _get_map_from_matches(matches[:, :n])
def _test_and_save(epochs, optimizer, data_test, model, logger, args, loss_sum):
if not hasattr(_test_and_save, 'best_acc'):
_test_and_save.best_acc = 0
n = 200
start_cpu_t = time.time()
feats_labels_sk, feats_labels_im = _extract_feats_sk_im(data=data_test, model=model,
batch_size=args.batch_size)
pre, mAPn = _eval(feats_labels_sk, feats_labels_im, n)
logger.info("Precision@{}: {}, mAP@{}: {}, bestPrecsion: {}".format(n, pre, n, mAPn, max(pre, _test_and_save.best_acc)) +
" " + 'epochs: {}, loss_sk: {}, loss_im: {}, (eval cpu time: {}s)'.
format(epochs, np.mean(loss_sum[SK]), np.mean(loss_sum[IM]), time.time() - start_cpu_t))
if pre > _test_and_save.best_acc:
_test_and_save.best_acc = pre
torch.save({'model': model.state_dict(),
'optimizer': optimizer.state_dict(),
'epochs': epochs,
'args': args},
save_fn(args.save_dir, epochs, pre, mAPn))
torch.cuda.empty_cache()
def save_fn(save_dir, it, pre=0, mAP=0):
return join(mkdir(join(save_dir, 'models')), 'Iter__{}__{}_{}.pkl'.format(it, int(pre * 1000), int(mAP * 1000)))
def _try_load(args, logger, model, optimizer):
if args.start_from is None:
# try to find the latest checkpoint
files = os.listdir(mkdir(join(mkdir(args.save_dir), 'models')))
if len(files) == 0:
logger.info("Cannot find any checkpoint. Start new training.")
return 0
latest = max(files, key=lambda name: int(name.split('\\')[-1].split('/')[-1].split('.')[0].split('__')[1]))
checkpoint = join(args.save_dir, 'models', latest)
else:
try: checkpoint = save_fn(args.save_dir, str(int(args.start_from)))
except: checkpoint = args.start_from
logger.info("Load model from {}".format(checkpoint))
ckpt = torch.load(checkpoint, map_location='cpu')
model.load_state_dict(ckpt['model'])
optimizer.load_state_dict(ckpt['optimizer'])
return ckpt['epochs']
def _extract_feats_sk_im(data, model, batch_size=64):
skip = 1
model.eval()
feats_labels_sk = _extract_feats(data, lambda x: model(sk=x), SK, skip=skip,
batch_size=batch_size)
feats_labels_im = _extract_feats(data, lambda x: model(im=x), IM, skip=skip,
batch_size=batch_size)
model.train()
return feats_labels_sk, feats_labels_im
def _extract_feats(data_test, model, what, skip=1, batch_size=16):
"""
:param data_test: test Dataset
:param model: network model
:param what: SK or IM
:param skip: skip a certain number of image/sketches to reduce computation
:return: a two-element list [extracted_features, extracted_labels]
"""
labels = []
feats = []
for batch_idx, (xs, id) in \
enumerate(data_test.traverse(what, skip=skip, batch_size=batch_size)):
feats.append(model(xs.cuda()).data.cpu().numpy())
# print(type(labels[0]), labels[0].shape)# <class 'numpy.ndarray'> (16, 256)
# print(type(id), id) # <class 'torch.Tensor'> tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
labels.append(id.numpy())
# print(feats[-1][-1][:4])
return np.concatenate(feats), np.concatenate(labels)
def _parse_args_paths(args):
if args.dataset == 'sketchy':
sketch_folder = SKETCH_FOLDER_SKETCHY
im_folder = IMAGE_FOLDER_SKETCHY
path_semantic = PATH_SEMANTIC_SKETCHY
train_class = TRAIN_CLASS_SKETCHY
test_class = TEST_CLASS_SKETCHY
npy_folder = NPY_FOLDER_SKETCHY
elif args.dataset == 'tuberlin':
sketch_folder = SKETCH_FOLDER_TUBERLIN
im_folder = IMAGE_FOLDER_TUBERLIN
path_semantic = PATH_SEMANTIC_TUBERLIN
train_class = TRAIN_CLASS_TUBERLIN
test_class = TEST_CLASS_TUBERLIN
npy_folder = NPY_FOLDER_TUBERLIN
else: raise Exception("dataset args error!")
if args.sketch_dir != '': sketch_folder = args.sketch_dir
if args.image_dir != '': im_folder = args.image_dir
if args.path_semantic != '': im_folder = args.path_semantic
if args.npy_dir == '0': args.npy_dir = npy_folder
elif args.npy_dir == '': args.npy_dir = None
if args.ni_path == '0': args.ni_path = PATH_NAMES
return sketch_folder, im_folder, path_semantic, train_class, test_class
def train(args):
# srun -p gpu --gres=gpu:1 --exclusive --output=san10.out python main_san.py --epochs 50000 --print_every 500 --save_every 2000 --batch_size 96 --dataset sketchy --margin 10 --npy_dir 0 --save_dir san_sketchy10
# srun -p gpu --gres=gpu:1 --exclusive --output=san1.out python main_san.py --epochs 50000 --print_every 500 --save_every 2000 --batch_size 96 --dataset sketchy --margin 1 --npy_dir 0 --save_dir san_sketchy1
# srun -p gpu --gres=gpu:1 --output=san_sketchy03.out python main_san.py --epochs 30000 --print_every 200 --save_every 3000 --batch_size 96 --dataset sketchy --margin 0.3 --npy_dir 0 --save_dir san_sketchy03 --lr 0.0001
sketch_folder, image_folder, path_semantic, train_class, test_class = _parse_args_paths(args)
if DEBUG:
args.back_bone = 'default'
args.npy_dir = NPY_FOLDER_SKETCHY
args.ni_path = PATH_NAMES
args.print_every = 1
args.save_every = 5
args.paired = True
args.epochs = 20000
# args.lr = 0.001
args.sz = 32
# args.l2_reg = 0.0001
args.back_bone = 'default'
args.batch_size = 32
args.h = 500
test_class = train_class[5:7]
train_class = train_class[:5]
logger = make_logger(join(mkdir(args.save_dir), curr_time_str() + '.log'))
data_train = CMT_dataloader(folder_sk=sketch_folder, clss=train_class, folder_nps=args.npy_dir,
path_semantic=path_semantic, paired=args.paired, names=args.ni_path,
folder_im=image_folder, normalize01=False, doaug=False, logger=logger,
sz=None if args.back_bone=='vgg' else args.sz)
dataloader_train = DataLoader(dataset=data_train, batch_size=args.batch_size, shuffle=True)
data_test = CMT_dataloader(folder_sk=sketch_folder, clss=test_class, folder_nps=args.npy_dir,
path_semantic=path_semantic, folder_im=image_folder, normalize01=False, doaug=False,
logger=logger, sz=None if args.back_bone=='vgg' else args.sz)
model = CMT(d=data_train.d(), h=args.h, back_bone=args.back_bone, batch_normalization=args.bn, sz=args.sz)
model.cuda()
if not args.ft:
model.fix_vgg()
optimizer = SGD(params=model.parameters(), lr=args.lr, momentum=0.6)
epochs = _try_load(args, logger, model, optimizer)
logger.info(str(args))
args.epochs += epochs
cmt_loss = _CMT_loss()
model.train()
l2_regularization = _Regularization(model, args.l2_reg, p=2, logger=None)
loss_sum = [[0], [0]]
logger.info("Start training:\n train_classes: {}\n test_classes: {}".format(train_class, test_class))
_test_and_save(epochs=epochs, optimizer=optimizer, data_test=data_test,
model=model, logger=logger, args=args, loss_sum=loss_sum)
while True:
for mode, get_feat in [[IM, lambda data: model(im=data)],
[SK, lambda data: model(sk=data)]]:
data_train.mode = mode
for _, (data, semantics) in enumerate(dataloader_train):
# Skip one-element batch in consideration of batch normalization
if data.shape[0] == 1:
continue
# print(data.shape)
optimizer.zero_grad()
loss = cmt_loss(get_feat(data.cuda()),
semantics.cuda()) \
+ l2_regularization()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
loss_sum[mode].append(float(loss.item()))
epochs += 1
dr_dec(optimizer=optimizer, args=args)
if (epochs + 1) % args.save_every == 0:
_test_and_save(epochs=epochs, optimizer=optimizer, data_test=data_test,
model=model, logger=logger, args=args, loss_sum=loss_sum)
if (epochs + 1) % args.print_every == 0:
logger.info('epochs: {}, loss_sk: {}, loss_im: {},'.
format(epochs, np.mean(loss_sum[SK]), np.mean(loss_sum[IM])))
loss_sum = [[], []]
if epochs >= args.epochs: break
def gen_args(h=500, dataset='sketchy', back_bone='vgg', sz=32, ft=True, paired=False):
ft = int(ft)
paired = int(paired)
return \
"""
###
#!/bin/bash
#SBATCH --job-name=ZXLing
#SBATCH --partition=gpu
#SBATCH --gres=gpu:1
#SBATCH --output=cmt_%j.out
#SBATCH --time=7-00:00:00
module load gcc/7.3.0 anaconda/3 cuda/9.2 cudnn/7.1.4
source activate lzxtc2
python main_cmt.py --npy_dir 0 --dataset {} --save_dir cmts/cmt{}{}_{}_{}_{}_{} --h {} --back_bone {} --sz {} --ft {} --paired {} --ni_path 0
""".format(dataset, int(ft), int(paired) , dataset, h, back_bone, sz if back_bone=='default' else "", h, back_bone, sz, ft, paired)
if __name__ == '__main__':
if False:
print(gen_args(back_bone='vgg', ft=False, paired=True))
print(gen_args(back_bone='vgg', ft=True, paired=False))
print(gen_args(back_bone='vgg', ft=True, paired=True))
print(gen_args(back_bone='vgg', ft=False, paired=False))
print(gen_args(back_bone='default'))
exit()
args = parse_config()
print(str(args))
# train(args)
# srun --gres=gpu:1 --output=cmt_%j.out python main_cmt.py
'''
#!/bin/bash
#SBATCH --job-name=ZXLing
#SBATCH --partition=gpu
#SBATCH --gres=gpu:1
#SBATCH --output=cmt_%j.out
#SBATCH --time=7-00:00:00
module load gcc/7.3.0 anaconda/3 cuda/9.2 cudnn/7.1.4
source activate lzxtc2
python main_cmt.py --npy_dir 0 --dataset sketchy --save_dir cmts/cmt11_sketchy_500_default_32 --h 500 --back_bone default --sz 32 --ft 1 --paired 1 --ni_path 0
python main_cmt.py --npy_dir 0 --dataset sketchy --save_dir cmts/cmt01_sketchy_500_vgg_ --h 500 --back_bone vgg --sz 32 --ft 0 --paired 1 --ni_path 0
python main_cmt.py --npy_dir 0 --dataset sketchy --save_dir cmts/cmt10_sketchy_500_vgg_ --h 500 --back_bone vgg --sz 32 --ft 1 --paired 0 --ni_path 0
python main_cmt.py --npy_dir 0 --dataset sketchy --save_dir cmts/cmt11_sketchy_500_vgg_ --h 500 --back_bone vgg --sz 32 --ft 1 --paired 1 --ni_path 0
python main_cmt.py --npy_dir 0 --dataset sketchy --save_dir cmts/cmt00_sketchy_500_vgg_ --h 500 --back_bone vgg --sz 32 --ft 0 --paired 0 --ni_path 0
python main_cmt.py --npy_dir 0 --dataset sketchy --save_dir cmts/cmt10_sketchy_500_default_32 --h 500 --back_bone default --sz 32 --ft 1 --paired 0 --ni_path 0
'''
|
[
"package.loss.regularization._Regularization",
"numpy.stack",
"numpy.multiply",
"numpy.copy",
"torch.utils.data.DataLoader",
"torch.load",
"time.time",
"numpy.mean",
"package.loss.cmt_loss._CMT_loss",
"package.args.cmt_args.parse_config",
"torch.cuda.empty_cache",
"torch.nn.kneighbors",
"numpy.arange",
"numpy.array",
"sklearn.neighbors.NearestNeighbors",
"numpy.concatenate"
] |
[((1129, 1145), 'numpy.mean', 'np.mean', (['matches'], {}), '(matches)\n', (1136, 1145), True, 'import numpy as np\n'), ((1185, 1202), 'numpy.copy', 'np.copy', (['inputArr'], {}), '(inputArr)\n', (1192, 1202), True, 'import numpy as np\n'), ((1365, 1391), 'numpy.multiply', 'np.multiply', (['dup', 'inputArr'], {}), '(dup, inputArr)\n', (1376, 1391), True, 'import numpy as np\n'), ((2032, 2059), 'numpy.mean', 'np.mean', (['precisions'], {'axis': '(1)'}), '(precisions, axis=1)\n', (2039, 2059), True, 'import numpy as np\n'), ((2071, 2083), 'numpy.mean', 'np.mean', (['mAP'], {}), '(mAP)\n', (2078, 2083), True, 'import numpy as np\n'), ((2718, 2751), 'torch.nn.kneighbors', 'nn.kneighbors', (['feats_labels_sk[0]'], {}), '(feats_labels_sk[0])\n', (2731, 2751), True, 'import torch.nn as nn\n'), ((3258, 3269), 'time.time', 'time.time', ([], {}), '()\n', (3267, 3269), False, 'import time\n'), ((4148, 4172), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (4170, 4172), False, 'import torch\n'), ((5028, 5070), 'torch.load', 'torch.load', (['checkpoint'], {'map_location': '"""cpu"""'}), "(checkpoint, map_location='cpu')\n", (5038, 5070), False, 'import torch\n'), ((9291, 9363), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'data_train', 'batch_size': 'args.batch_size', 'shuffle': '(True)'}), '(dataset=data_train, batch_size=args.batch_size, shuffle=True)\n', (9301, 9363), False, 'from torch.utils.data import DataLoader\n'), ((10043, 10054), 'package.loss.cmt_loss._CMT_loss', '_CMT_loss', ([], {}), '()\n', (10052, 10054), False, 'from package.loss.cmt_loss import _CMT_loss\n'), ((10098, 10151), 'package.loss.regularization._Regularization', '_Regularization', (['model', 'args.l2_reg'], {'p': '(2)', 'logger': 'None'}), '(model, args.l2_reg, p=2, logger=None)\n', (10113, 10151), False, 'from package.loss.regularization import _Regularization\n'), ((12838, 12852), 'package.args.cmt_args.parse_config', 'parse_config', ([], {}), '()\n', (12850, 12852), False, 'from package.args.cmt_args import parse_config\n'), ((1847, 1874), 'numpy.arange', 'np.arange', (['matches.shape[1]'], {}), '(matches.shape[1])\n', (1856, 1874), True, 'import numpy as np\n'), ((2776, 2804), 'numpy.array', 'np.array', (['feats_labels_im[1]'], {}), '(feats_labels_im[1])\n', (2784, 2804), True, 'import numpy as np\n'), ((6431, 6452), 'numpy.concatenate', 'np.concatenate', (['feats'], {}), '(feats)\n', (6445, 6452), True, 'import numpy as np\n'), ((6454, 6476), 'numpy.concatenate', 'np.concatenate', (['labels'], {}), '(labels)\n', (6468, 6476), True, 'import numpy as np\n'), ((1931, 1953), 'numpy.stack', 'np.stack', (['temp'], {'axis': '(0)'}), '(temp, axis=0)\n', (1939, 1953), True, 'import numpy as np\n'), ((2597, 2676), 'sklearn.neighbors.NearestNeighbors', 'NN', ([], {'n_neighbors': 'feats_labels_im[0].shape[0]', 'metric': '"""cosine"""', 'algorithm': '"""brute"""'}), "(n_neighbors=feats_labels_im[0].shape[0], metric='cosine', algorithm='brute')\n", (2599, 2676), True, 'from sklearn.neighbors import NearestNeighbors as NN\n'), ((3753, 3774), 'numpy.mean', 'np.mean', (['loss_sum[SK]'], {}), '(loss_sum[SK])\n', (3760, 3774), True, 'import numpy as np\n'), ((3776, 3797), 'numpy.mean', 'np.mean', (['loss_sum[IM]'], {}), '(loss_sum[IM])\n', (3783, 3797), True, 'import numpy as np\n'), ((3799, 3810), 'time.time', 'time.time', ([], {}), '()\n', (3808, 3810), False, 'import time\n'), ((11702, 11723), 'numpy.mean', 'np.mean', (['loss_sum[SK]'], {}), '(loss_sum[SK])\n', (11709, 11723), True, 'import numpy as np\n'), ((11725, 11746), 'numpy.mean', 'np.mean', (['loss_sum[IM]'], {}), '(loss_sum[IM])\n', (11732, 11746), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
# coding: utf-8
# This software component is licensed by ST under BSD 3-Clause license,
# the "License"; You may not use this file except in compliance with the
# License. You may obtain a copy of the License at:
# https://opensource.org/licenses/BSD-3-Clause
"""
Optimze Full int8 - with reference dataset
Fully quantized model tflite ASC - TF 1.14.0ASC 3CL Training script from Pre calculated features.
"""
import numpy as np
import tensorflow as tf
# load ASC training Set as representative quantization dataset (100 samples)
# reduced 'dummy' data set is provided , a full representative one should be provided instead
x_train_dataset = np.load('Asc_quant_representative_data_dummy.npz')
x_train = x_train_dataset['x_train']
ASC_SHAPE = (30, 32, 1)
N_CLASSES = 3
def representative_dataset_gen():
for i in range(len(x_train)):
# Get sample input data as a numpy array in a method of your choosing.
yield [x_train[i].reshape((-1, ) + ASC_SHAPE)]
converter = tf.lite.TFLiteConverter.from_keras_model_file("Session_keras_mod_93_Model.h5" )
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset_gen
converter.target_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.int8
print("\nConverting the model...", flush=True)
tflite_model = converter.convert()
open('asc_keras_mod_93_to_tflite_int8_xtrain.tflite','wb').write(tflite_model)
|
[
"numpy.load",
"tensorflow.lite.TFLiteConverter.from_keras_model_file"
] |
[((723, 773), 'numpy.load', 'np.load', (['"""Asc_quant_representative_data_dummy.npz"""'], {}), "('Asc_quant_representative_data_dummy.npz')\n", (730, 773), True, 'import numpy as np\n'), ((1075, 1153), 'tensorflow.lite.TFLiteConverter.from_keras_model_file', 'tf.lite.TFLiteConverter.from_keras_model_file', (['"""Session_keras_mod_93_Model.h5"""'], {}), "('Session_keras_mod_93_Model.h5')\n", (1120, 1153), True, 'import tensorflow as tf\n')]
|
import numpy as np
from .utils import Timer
def run(size='large', repeats=3 ):
sizes = {'huge': 28000, 'large': 15000, 'small': 6000, 'tiny': 2000, 'test': 2}
n = sizes[size]
A = np.array(np.random.rand(n,n))
A = [email protected]
num_runs = repeats
print('num_runs =', num_runs)
results = []
for i in range(num_runs):
print("run ", i)
with Timer() as t:
L = np.linalg.cholesky(A)
run_time=t.elapsed
print(f'Time {t.elapsed} seconds from Timer')
ops = 1E-9 * (n**3/3.0)
gflops = ops/run_time
results.append({'run_time': run_time, 'gflops': gflops})
return results
if __name__ == '__main__':
run()
|
[
"numpy.random.rand",
"numpy.linalg.cholesky"
] |
[((208, 228), 'numpy.random.rand', 'np.random.rand', (['n', 'n'], {}), '(n, n)\n', (222, 228), True, 'import numpy as np\n'), ((417, 438), 'numpy.linalg.cholesky', 'np.linalg.cholesky', (['A'], {}), '(A)\n', (435, 438), True, 'import numpy as np\n')]
|
'''Module to load and use GloVe Models.
Code Inspiration from:
https://www.kaggle.com/jhoward/improved-lstm-baseline-glove-dropout
'''
import os
import numpy as np
import pandas as pd
import urllib.request
from zipfile import ZipFile
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.cluster import KMeans
folder = os.path.dirname(os.path.realpath(__file__))
def download(name):
'''Downloads the relevant dataset and extracts it.
Args:
name (str): Name of the model to download (options are: [twitter, wikipedia])
Returns:
True if successful, otherwise False
'''
url = None
if name == 'twitter':
url = 'http://nlp.stanford.edu/data/wordvecs/glove.twitter.27B.zip'
elif name == 'wikipedia':
url = 'http://nlp.stanford.edu/data/wordvecs/glove.840B.300d.zip'
if url is not None:
try:
urllib.request.urlretrieve(url, os.path.join(folder, '{}.zip'.format(name)))
except:
print("download failed")
return False
try:
# Create a ZipFile Object and load sample.zip in it
with ZipFile(os.path.join(folder, '{}.zip'.format(name)), 'r') as zipObj:
# Extract all the contents of zip file in current directory
zipObj.extractall(folder)
return True
except:
print("extraction failed")
return False
return False
class GloveEmbeddings:
'''Class to load embeddings model and generate it for words or sentences.'''
def __init__(self, name, dim=25):
# load data
self.emb = self.load_vectors(name, dim)
self.emb_size = dim
# calculate items for randomization (explicit convert to list to avoid numpy warning)
all_embs = np.stack(list(self.emb.values()))
self.emb_mean,self.emb_std = all_embs.mean(), all_embs.std()
def get_coefs(self, word, *arr):
'''Helper Function to transform the given vector into a float array.'''
return word, np.asarray(arr, dtype='float32')
def load_vectors(self, name, dim):
'''Load the given vector data.'''
# retrieve file name
file = None
if name == 'twitter':
file = os.path.join(folder, 'glove.{}.27B.{}d.txt'.format(name, dim))
elif name == 'wikipedia':
file = os.path.join(folder, 'glove.840B.{}d.txt'.format(dim))
else:
raise ValueError('Unkown model type ({})'.format(name))
# load the embeddings
with open(file, encoding='utf-8') as file:
embeddings_index = [self.get_coefs(*o.strip().split()) for o in file]
embeddings_index = list(filter(lambda x: len(x[1]) == dim, embeddings_index))
return dict(embeddings_index)
def word_vector(self,word):
'''Tries to retrieve the embedding for the given word, otherwise returns random vector.'''
# generate randomness otherwise
vec = self.emb.get(word)
return vec if vec is not None else np.random.normal(self.emb_mean, self.emb_std, (self.emb_size))
def sent_vector(self, sent, use_rand=True):
'''Generates a single embedding vector.
Args:
sent (list): List of tokenized words to use
use_rand (bool): Defines if unkown words should be filled with random vectors (otherwise only use known vectors)
Returns:
Single normalized Vector to be used as embedding
'''
vec = None
vec_count = 0
for word in sent:
wvec = self.emb.get(word)
if wvec is None and use_rand:
wvec = np.random.normal(self.emb_mean, self.emb_std, (self.emb_size))
if wvec is not None:
if vec is None:
vec = wvec
else:
vec += wvec
vec_count += 1
# normalize the vector
if vec is not None and vec_count > 0:
vec = vec / vec_count
# if no word is found return random vector
return vec if vec is not None else np.random.normal(self.emb_mean, self.emb_std, (self.emb_size))
def sent_matrix(self, sent, max_feat, pad, dedub=False):
'''Generates a Matrix of single embeddings for the item.
Args:
sent (list): List of tokenized words
max_feat (int): Number of maximal features to extract
pad (bool): Defines if the resulting matrix should be zero-padded to max_feat
dedub (bool): Defines if the word list should be de-duplicated
Returns:
2-D Matrix with dimensions [max_feat, embedding_size]
'''
# remove duplicates
if dedub:
sent = list(set(sent))
# setup matrix
nb_words = min(max_feat, len(sent))
embedding_matrix = np.random.normal(self.emb_mean, self.emb_std, (nb_words, self.emb_size))
# iterate through all words
for i, word in enumerate(sent):
if i >= max_feat: continue
vec = self.emb.get(word)
if vec is not None: embedding_matrix[i] = vec
# pad the matrix to max features
if pad and nb_words < max_feat:
embedding_matrix = np.pad(embedding_matrix, (max_feat, self.emb_size), 'constant', constant_values=[0])
return embedding_matrix
def centroid_vectors(self, sent, max_feat):
'''Generates a list of `max_feat` vectors to be used as representation.
Args:
sent (list): Tokenized words in the document
max_feat (int): Number of vectors to generate
Returns:
Array of centroid vectors for the given document
'''
# generate list of vectors (use set as order not relevant and to avoid duplicates)
vecs = []
for word in set(sent):
vec = self.emb.get(word)
if vec is not None: vecs.append(vec)
# return random vector if none found
if len(vecs) < max_feat:
return np.array(vecs + [np.random.normal(self.emb_mean, self.emb_std, (self.emb_size)) for i in range(max_feat - len(vecs))])
elif len(vecs) == max_feat:
return np.array(vecs)
# perform clustering
kmeans = KMeans(n_clusters=max_feat).fit(vecs)
# return the centroid vectors
return kmeans.cluster_centers_
class GloVeTransformer(BaseEstimator, TransformerMixin):
'''Transformer for the GloVe Model.'''
def __init__(self, name, dim, type, tokenizer, max_feat=None):
'''Create the Transformer.
Note that the centroid option might be slow.
Args:
name (str): Name of the model
dim (int): Number of dimensions to use
type (str): Type of the transformation (options are: ['word', 'sent', 'sent-matrix', 'centroid'])
tokenizer (fct): Function to tokenize the input data
max_feat (int): Number of maximal feature vectors used per input
'''
# safty checks
if type not in ['word', 'sent', 'sent-matrix', 'centroid']:
raise ValueError("Invalid value for type: ({})".format(type))
if type in ['sent-matrix', 'centroid'] and max_feat is None:
raise ValueError("Required value for max_feat for type ({})".format(type))
# set values
self.glove = GloveEmbeddings(name, dim)
self.type = type
self.tokenizer = tokenizer
self.max_feat = max_feat
def fit(self, x, y=None):
return self
def vectors(self, text):
'''Extracts the specified type of vector for the given input data.'''
# retrieve the vectors
tokens = self.tokenizer(text)
if self.type == 'word':
return np.concat([self.glove.word_vector(tok) for tok in tokens])
elif self.type == 'sent':
return self.glove.sent_vector(tokens)
elif self.type == 'sent-matrix':
# note: use padding to avoid pipeline problems
return self.glove.sent_matrix(tokens, self.max_feat, True).reshape([-1])
elif self.type == 'centroid':
return self.glove.centroid_vectors(tokens, self.max_feat).reshape([-1])
return np.nan
def transform(self, X):
X_tagged = pd.Series(X).apply(lambda x: pd.Series(self.vectors(x)))
df = pd.DataFrame(X_tagged).fillna(0).replace([-np.inf], -1).replace([np.inf], 1)
return df
|
[
"numpy.pad",
"pandas.DataFrame",
"sklearn.cluster.KMeans",
"numpy.asarray",
"os.path.realpath",
"numpy.array",
"pandas.Series",
"numpy.random.normal"
] |
[((354, 380), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (370, 380), False, 'import os\n'), ((4413, 4485), 'numpy.random.normal', 'np.random.normal', (['self.emb_mean', 'self.emb_std', '(nb_words, self.emb_size)'], {}), '(self.emb_mean, self.emb_std, (nb_words, self.emb_size))\n', (4429, 4485), True, 'import numpy as np\n'), ((1890, 1922), 'numpy.asarray', 'np.asarray', (['arr'], {'dtype': '"""float32"""'}), "(arr, dtype='float32')\n", (1900, 1922), True, 'import numpy as np\n'), ((2807, 2867), 'numpy.random.normal', 'np.random.normal', (['self.emb_mean', 'self.emb_std', 'self.emb_size'], {}), '(self.emb_mean, self.emb_std, self.emb_size)\n', (2823, 2867), True, 'import numpy as np\n'), ((3731, 3791), 'numpy.random.normal', 'np.random.normal', (['self.emb_mean', 'self.emb_std', 'self.emb_size'], {}), '(self.emb_mean, self.emb_std, self.emb_size)\n', (3747, 3791), True, 'import numpy as np\n'), ((4768, 4856), 'numpy.pad', 'np.pad', (['embedding_matrix', '(max_feat, self.emb_size)', '"""constant"""'], {'constant_values': '[0]'}), "(embedding_matrix, (max_feat, self.emb_size), 'constant',\n constant_values=[0])\n", (4774, 4856), True, 'import numpy as np\n'), ((3356, 3416), 'numpy.random.normal', 'np.random.normal', (['self.emb_mean', 'self.emb_std', 'self.emb_size'], {}), '(self.emb_mean, self.emb_std, self.emb_size)\n', (3372, 3416), True, 'import numpy as np\n'), ((5645, 5659), 'numpy.array', 'np.array', (['vecs'], {}), '(vecs)\n', (5653, 5659), True, 'import numpy as np\n'), ((5699, 5726), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'max_feat'}), '(n_clusters=max_feat)\n', (5705, 5726), False, 'from sklearn.cluster import KMeans\n'), ((7549, 7561), 'pandas.Series', 'pd.Series', (['X'], {}), '(X)\n', (7558, 7561), True, 'import pandas as pd\n'), ((5498, 5558), 'numpy.random.normal', 'np.random.normal', (['self.emb_mean', 'self.emb_std', 'self.emb_size'], {}), '(self.emb_mean, self.emb_std, self.emb_size)\n', (5514, 5558), True, 'import numpy as np\n'), ((7615, 7637), 'pandas.DataFrame', 'pd.DataFrame', (['X_tagged'], {}), '(X_tagged)\n', (7627, 7637), True, 'import pandas as pd\n')]
|
"""
This file contains a function to generate a single synthetic tree, prepared for
multiprocessing.
"""
import pandas as pd
import numpy as np
# import dill as pickle
# import gzip
from syn_net.data_generation.make_dataset import synthetic_tree_generator
from syn_net.utils.data_utils import ReactionSet
path_reaction_file = '/pool001/whgao/data/synth_net/st_pis/reactions_pis.json.gz'
path_to_building_blocks = '/pool001/whgao/data/synth_net/st_pis/enamine_us_matched.csv.gz'
building_blocks = pd.read_csv(path_to_building_blocks, compression='gzip')['SMILES'].tolist()
r_set = ReactionSet()
r_set.load(path_reaction_file)
rxns = r_set.rxns
# with gzip.open(path_reaction_file, 'rb') as f:
# rxns = pickle.load(f)
print('Finish reading the templates and building blocks list!')
def func(_):
np.random.seed(_)
tree, action = synthetic_tree_generator(building_blocks, rxns, max_step=15)
return tree, action
|
[
"syn_net.utils.data_utils.ReactionSet",
"pandas.read_csv",
"numpy.random.seed",
"syn_net.data_generation.make_dataset.synthetic_tree_generator"
] |
[((584, 597), 'syn_net.utils.data_utils.ReactionSet', 'ReactionSet', ([], {}), '()\n', (595, 597), False, 'from syn_net.utils.data_utils import ReactionSet\n'), ((807, 824), 'numpy.random.seed', 'np.random.seed', (['_'], {}), '(_)\n', (821, 824), True, 'import numpy as np\n'), ((844, 904), 'syn_net.data_generation.make_dataset.synthetic_tree_generator', 'synthetic_tree_generator', (['building_blocks', 'rxns'], {'max_step': '(15)'}), '(building_blocks, rxns, max_step=15)\n', (868, 904), False, 'from syn_net.data_generation.make_dataset import synthetic_tree_generator\n'), ((500, 556), 'pandas.read_csv', 'pd.read_csv', (['path_to_building_blocks'], {'compression': '"""gzip"""'}), "(path_to_building_blocks, compression='gzip')\n", (511, 556), True, 'import pandas as pd\n')]
|
import logging
import numpy as np
import tensorflow as tf
from collections import OrderedDict
import utils
from clf_model_multitask import predict
def get_latest_checkpoint_and_log(logdir, filename):
init_checkpoint_path = utils.get_latest_model_checkpoint_path(logdir, filename)
logging.info('Checkpoint path: %s' % init_checkpoint_path)
last_step = int(init_checkpoint_path.split('/')[-1].split('-')[-1])
logging.info('Latest step was: %d' % last_step)
return init_checkpoint_path
def evaluate_scores(true_labels, prediction, measures_dict):
scores_one_exp = OrderedDict()
for measure_name, measure in measures_dict.items():
logging.info('evaluating ' + measure_name)
logging.info(measure)
scores_one_exp[measure_name] = measure(y_true = np.asarray(true_labels), y_pred = np.asarray(prediction))
return scores_one_exp
def map_labels_to_list(labels, label_list):
# label_list is a python list with the labels
# map labels in range(len(label_list)) to the labels in label_list
# E.g. [0,0,1,1] becomes [0,0,2,2] (if 1 doesnt exist in the data)
# label gets mapped to label_list[label]
label_lookup = tf.constant(np.array(label_list))
return tf.gather(label_lookup, labels)
def build_clf_graph(img_tensor_shape, clf_config, joint=False):
graph_classifier = tf.Graph()
with graph_classifier.as_default():
# image (batch size = 1)
x_clf_pl = tf.placeholder(tf.float32, img_tensor_shape, name='z')
# classification of the real source image and the fake target image
predicted_labels, softmax, age_softmaxs = predict(x_clf_pl, clf_config)
# scope = tf.get_variable_scope()
# scope.reuse_variables()
# map labels in range(len(label_list)) to the labels in label_list
# E.g. [0,0,1,1] becomes [0,0,2,2] (if 1 doesnt exist in the data)
predicted_labels_mapped = map_labels_to_list(predicted_labels, clf_config.label_list)
# Add the variable initializer Op.
init = tf.global_variables_initializer()
# Create a savers for writing training checkpoints.
saver = tf.train.Saver() # disc loss is scaled negative EM distance
predictions = {'label': predicted_labels_mapped, 'diag_softmax': softmax, 'age_softmaxs': age_softmaxs}
return graph_classifier, x_clf_pl, predictions, init, saver
def build_gen_graph(img_tensor_shape, gan_config):
# noise_shape
generator = gan_config.generator
graph_generator = tf.Graph()
with graph_generator.as_default():
# source image (batch size = 1)
xs_pl = tf.placeholder(tf.float32, img_tensor_shape, name='xs_pl')
if gan_config.use_generator_input_noise:
noise_shape = gan_config.generator_input_noise_shape.copy()
# adjust batch size
noise_shape[0] = img_tensor_shape[0]
noise_in_gen_pl = tf.random_uniform(shape=noise_shape, minval=-1, maxval=1)
else:
noise_in_gen_pl = None
# generated fake image batch
xf = generator(xs=xs_pl, z_noise=noise_in_gen_pl, training=False)
# Add the variable initializer Op.
init = tf.global_variables_initializer()
# Create a savers for writing training checkpoints.
saver = tf.train.Saver()
return graph_generator, xs_pl, xf, init, saver
|
[
"tensorflow.random_uniform",
"tensorflow.train.Saver",
"tensorflow.gather",
"tensorflow.global_variables_initializer",
"numpy.asarray",
"logging.info",
"utils.get_latest_model_checkpoint_path",
"tensorflow.placeholder",
"numpy.array",
"clf_model_multitask.predict",
"tensorflow.Graph",
"collections.OrderedDict"
] |
[((231, 287), 'utils.get_latest_model_checkpoint_path', 'utils.get_latest_model_checkpoint_path', (['logdir', 'filename'], {}), '(logdir, filename)\n', (269, 287), False, 'import utils\n'), ((292, 350), 'logging.info', 'logging.info', (["('Checkpoint path: %s' % init_checkpoint_path)"], {}), "('Checkpoint path: %s' % init_checkpoint_path)\n", (304, 350), False, 'import logging\n'), ((427, 474), 'logging.info', 'logging.info', (["('Latest step was: %d' % last_step)"], {}), "('Latest step was: %d' % last_step)\n", (439, 474), False, 'import logging\n'), ((591, 604), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (602, 604), False, 'from collections import OrderedDict\n'), ((1229, 1260), 'tensorflow.gather', 'tf.gather', (['label_lookup', 'labels'], {}), '(label_lookup, labels)\n', (1238, 1260), True, 'import tensorflow as tf\n'), ((1350, 1360), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1358, 1360), True, 'import tensorflow as tf\n'), ((2527, 2537), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (2535, 2537), True, 'import tensorflow as tf\n'), ((669, 711), 'logging.info', 'logging.info', (["('evaluating ' + measure_name)"], {}), "('evaluating ' + measure_name)\n", (681, 711), False, 'import logging\n'), ((720, 741), 'logging.info', 'logging.info', (['measure'], {}), '(measure)\n', (732, 741), False, 'import logging\n'), ((1196, 1216), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (1204, 1216), True, 'import numpy as np\n'), ((1453, 1507), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', 'img_tensor_shape'], {'name': '"""z"""'}), "(tf.float32, img_tensor_shape, name='z')\n", (1467, 1507), True, 'import tensorflow as tf\n'), ((1635, 1664), 'clf_model_multitask.predict', 'predict', (['x_clf_pl', 'clf_config'], {}), '(x_clf_pl, clf_config)\n', (1642, 1664), False, 'from clf_model_multitask import predict\n'), ((2045, 2078), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2076, 2078), True, 'import tensorflow as tf\n'), ((2156, 2172), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (2170, 2172), True, 'import tensorflow as tf\n'), ((2633, 2691), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', 'img_tensor_shape'], {'name': '"""xs_pl"""'}), "(tf.float32, img_tensor_shape, name='xs_pl')\n", (2647, 2691), True, 'import tensorflow as tf\n'), ((3203, 3236), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (3234, 3236), True, 'import tensorflow as tf\n'), ((3314, 3330), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (3328, 3330), True, 'import tensorflow as tf\n'), ((2925, 2982), 'tensorflow.random_uniform', 'tf.random_uniform', ([], {'shape': 'noise_shape', 'minval': '(-1)', 'maxval': '(1)'}), '(shape=noise_shape, minval=-1, maxval=1)\n', (2942, 2982), True, 'import tensorflow as tf\n'), ((798, 821), 'numpy.asarray', 'np.asarray', (['true_labels'], {}), '(true_labels)\n', (808, 821), True, 'import numpy as np\n'), ((832, 854), 'numpy.asarray', 'np.asarray', (['prediction'], {}), '(prediction)\n', (842, 854), True, 'import numpy as np\n')]
|
from simulations import simulation, simulation2
from pandas import DataFrame
from pandas import Series
from pandas import concat
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Bidirectional
from keras.layers import LSTM
from math import sqrt
from matplotlib import pyplot
import numpy
# frame a sequence as a supervised learning problem
def timeseries_to_supervised(data, lag=1):
df = DataFrame(data)
columns = [df.shift(i) for i in range(1, lag + 1)]
columns.append(df)
df = concat(columns, axis=1)
df.fillna(0, inplace=True)
return df
# create a differenced series
def difference(dataset, interval=1):
diff = list()
for i in range(interval, len(dataset)):
value = dataset[i] - dataset[i - interval]
diff.append(value)
return Series(diff)
# invert differenced value
def inverse_difference(history, yhat, interval=1):
return yhat + history[-interval]
# scale train and test data to [-1, 1]
def scale(train, test):
# fit scaler
scaler = MinMaxScaler(feature_range=(-1, 1))
scaler = scaler.fit(train)
# transform train
train = train.reshape(train.shape[0], train.shape[1])
train_scaled = scaler.transform(train)
# transform test
test = test.reshape(test.shape[0], test.shape[1])
test_scaled = scaler.transform(test)
return scaler, train_scaled, test_scaled
# inverse scaling for a forecasted value
def invert_scale(scaler, X, value):
new_row = [x for x in X] + [value]
array = numpy.array(new_row)
array = array.reshape(1, len(array))
inverted = scaler.inverse_transform(array)
return inverted[0, -1]
# fit an LSTM network to training data
def fit_lstm(train, batch_size, nb_epoch):
X, y = train[:, 0:-1], train[:, -1]
X = X.reshape(X.shape[0], 1, X.shape[1])
model = Sequential()
model.add(Bidirectional(LSTM(50, activation='relu'), batch_input_shape=(batch_size, X.shape[1], X.shape[2])))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
for i in range(nb_epoch):
model.fit(X, y, epochs=1, batch_size=batch_size, verbose=0, shuffle=False)
model.reset_states()
print('Epoch {}'.format(i))
return model
# make a one-step forecast
def forecast_lstm(model, batch_size, X):
X = X.reshape(1, 1, len(X))
yhat = model.predict(X, batch_size=batch_size)
return yhat[0, 0]
# load dataset
sim = simulation2.Simulator(50)
sim.simulate()
s = simulation.Simulation([[1, 1]], # to_plot, to_report
[[0.1, [0.2, 0.1], [15, 2], [30, 2]]], # interarrivals, demand, replenishment_lead, expiry
[[70.0, 110.0, 5.0, 30.0, 100.0, 100.0]], # purchase price, sales price, handling, backorder, overflow, recycle
[[50, 35]]) # storage, reorder point
s.simulate()
#raw_values = sim.stats.inventory_vector
raw_values = s.w.products[0].stats.storage
raw_values = raw_values[0::30]
print(len(raw_values))
diff_values = difference(raw_values, 1)
# transform data to be supervised learning
supervised = timeseries_to_supervised(diff_values, 1)
supervised_values = supervised.values
# split data into train and test-sets
train, test = supervised_values[0:-30], supervised_values[-30:]
# transform the scale of the data
scaler, train_scaled, test_scaled = scale(train, test)
# fit the model
lstm_model = fit_lstm(train_scaled, 1, 10)
# forecast the entire training dataset to build up state for forecasting
train_reshaped = train_scaled[:, 0].reshape(len(train_scaled), 1, 1)
#lstm_model.predict(train_reshaped, batch_size=1)
# walk-forward validation on the test data
predictions = list()
for i in range(len(test_scaled)):
# make one-step forecast
X, y = test_scaled[i, 0:-1], test_scaled[i, -1]
yhat = forecast_lstm(lstm_model, 1, X)
# invert scaling
yhat = invert_scale(scaler, X, yhat)
# invert differencing
yhat = inverse_difference(raw_values, yhat, len(test_scaled) + 1 - i)
# store forecast
predictions.append(yhat)
expected = raw_values[len(train) + i + 1]
print('Time=%d, Predicted=%f, Expected=%f' % (i + 1, yhat, expected))
# report performance
mse = mean_squared_error(raw_values[-30:-2], predictions[1:-1])
rmse = sqrt(mse)
ape = []
real_values = raw_values[-30:-2]
raw_value = raw_values[-30:-2]
predictions = predictions[1:-1]
for i in range(len(predictions)):
value = abs(predictions[i]-real_values[i])/real_values[i]
if value < 1:
ape.append(value)
mape = sum(ape)/len(ape)*100
print('Test RMSE: %.3f' % rmse)
print('Test MSE: %.3f' % mse)
print('Mean absolute percentage error: ', round(mape,2), "%")
# plot
pyplot.plot(raw_values[-30:-2], label='simulation')
pyplot.plot(predictions[1:-1], label='predicted by LSTM neural network')
pyplot.xlabel('time')
pyplot.ylabel('inventory level')
pyplot.grid()
pyplot.legend()
pyplot.show()
|
[
"pandas.DataFrame",
"matplotlib.pyplot.show",
"math.sqrt",
"matplotlib.pyplot.plot",
"pandas.concat",
"keras.models.Sequential",
"matplotlib.pyplot.legend",
"sklearn.preprocessing.MinMaxScaler",
"keras.layers.LSTM",
"simulations.simulation.Simulation",
"keras.layers.Dense",
"numpy.array",
"pandas.Series",
"simulations.simulation2.Simulator",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid",
"sklearn.metrics.mean_squared_error"
] |
[((2515, 2540), 'simulations.simulation2.Simulator', 'simulation2.Simulator', (['(50)'], {}), '(50)\n', (2536, 2540), False, 'from simulations import simulation, simulation2\n'), ((2561, 2690), 'simulations.simulation.Simulation', 'simulation.Simulation', (['[[1, 1]]', '[[0.1, [0.2, 0.1], [15, 2], [30, 2]]]', '[[70.0, 110.0, 5.0, 30.0, 100.0, 100.0]]', '[[50, 35]]'], {}), '([[1, 1]], [[0.1, [0.2, 0.1], [15, 2], [30, 2]]], [[\n 70.0, 110.0, 5.0, 30.0, 100.0, 100.0]], [[50, 35]])\n', (2582, 2690), False, 'from simulations import simulation, simulation2\n'), ((4294, 4351), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['raw_values[-30:-2]', 'predictions[1:-1]'], {}), '(raw_values[-30:-2], predictions[1:-1])\n', (4312, 4351), False, 'from sklearn.metrics import mean_squared_error\n'), ((4359, 4368), 'math.sqrt', 'sqrt', (['mse'], {}), '(mse)\n', (4363, 4368), False, 'from math import sqrt\n'), ((4778, 4829), 'matplotlib.pyplot.plot', 'pyplot.plot', (['raw_values[-30:-2]'], {'label': '"""simulation"""'}), "(raw_values[-30:-2], label='simulation')\n", (4789, 4829), False, 'from matplotlib import pyplot\n'), ((4830, 4902), 'matplotlib.pyplot.plot', 'pyplot.plot', (['predictions[1:-1]'], {'label': '"""predicted by LSTM neural network"""'}), "(predictions[1:-1], label='predicted by LSTM neural network')\n", (4841, 4902), False, 'from matplotlib import pyplot\n'), ((4903, 4924), 'matplotlib.pyplot.xlabel', 'pyplot.xlabel', (['"""time"""'], {}), "('time')\n", (4916, 4924), False, 'from matplotlib import pyplot\n'), ((4925, 4957), 'matplotlib.pyplot.ylabel', 'pyplot.ylabel', (['"""inventory level"""'], {}), "('inventory level')\n", (4938, 4957), False, 'from matplotlib import pyplot\n'), ((4958, 4971), 'matplotlib.pyplot.grid', 'pyplot.grid', ([], {}), '()\n', (4969, 4971), False, 'from matplotlib import pyplot\n'), ((4972, 4987), 'matplotlib.pyplot.legend', 'pyplot.legend', ([], {}), '()\n', (4985, 4987), False, 'from matplotlib import pyplot\n'), ((4988, 5001), 'matplotlib.pyplot.show', 'pyplot.show', ([], {}), '()\n', (4999, 5001), False, 'from matplotlib import pyplot\n'), ((507, 522), 'pandas.DataFrame', 'DataFrame', (['data'], {}), '(data)\n', (516, 522), False, 'from pandas import DataFrame\n'), ((610, 633), 'pandas.concat', 'concat', (['columns'], {'axis': '(1)'}), '(columns, axis=1)\n', (616, 633), False, 'from pandas import concat\n'), ((899, 911), 'pandas.Series', 'Series', (['diff'], {}), '(diff)\n', (905, 911), False, 'from pandas import Series\n'), ((1124, 1159), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(-1, 1)'}), '(feature_range=(-1, 1))\n', (1136, 1159), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((1605, 1625), 'numpy.array', 'numpy.array', (['new_row'], {}), '(new_row)\n', (1616, 1625), False, 'import numpy\n'), ((1922, 1934), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1932, 1934), False, 'from keras.models import Sequential\n'), ((2063, 2071), 'keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (2068, 2071), False, 'from keras.layers import Dense, Bidirectional\n'), ((1963, 1990), 'keras.layers.LSTM', 'LSTM', (['(50)'], {'activation': '"""relu"""'}), "(50, activation='relu')\n", (1967, 1990), False, 'from keras.layers import LSTM\n')]
|
# MIT License
#
# Copyright (c) 2017 <NAME> and (c) 2020 Google LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import time
from collections import deque
import gym
import numpy as np
import torch
from third_party.a2c_ppo_acktr import algo, utils
from third_party.a2c_ppo_acktr.arguments import get_args
from third_party.a2c_ppo_acktr.envs import make_vec_envs
from third_party.a2c_ppo_acktr.model import Policy
from third_party.a2c_ppo_acktr.storage import RolloutStorage
from my_pybullet_envs import utils as gan_utils
import logging
import sys
from my_pybullet_envs.laikago import mirror_obs, mirror_action
sys.path.append("third_party")
def main():
args, extra_dict = get_args()
# this file for normal ppo training, sim-gan(gail-dyn) training in main_gail_dyn_ppo.py
assert not args.gail
torch.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed)
if args.cuda and torch.cuda.is_available() and args.cuda_deterministic:
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
log_dir = os.path.expanduser(args.log_dir)
eval_log_dir = log_dir + "_eval"
utils.cleanup_log_dir(log_dir)
utils.cleanup_log_dir(eval_log_dir)
torch.set_num_threads(1)
device = torch.device("cuda:0" if args.cuda else "cpu")
Tensor = torch.cuda.FloatTensor if args.cuda else torch.FloatTensor
envs = make_vec_envs(args.env_name, args.seed, args.num_processes,
args.gamma, args.log_dir, device, False, render=False, **extra_dict)
if args.warm_start == '':
actor_critic = Policy(
envs.observation_space.shape,
envs.action_space,
base_kwargs={'recurrent': args.recurrent_policy, 'hidden_size': args.hidden_size})
actor_critic.to(device)
else:
# TODO: assume no state normalize ob_rms
if args.cuda:
actor_critic, _ = torch.load(args.warm_start)
else:
actor_critic, _ = torch.load(args.warm_start, map_location='cpu')
actor_critic.reset_critic(envs.observation_space.shape)
if args.warm_start_logstd is not None:
actor_critic.reset_variance(envs.action_space, args.warm_start_logstd)
actor_critic.to(device)
dummy = gym.make(args.env_name, render=False, **extra_dict)
save_path = os.path.join(args.save_dir, args.algo)
print("SAVE PATH:")
print(save_path)
try:
os.makedirs(save_path)
except FileExistsError:
print("warning: path existed")
# input("warning: path existed")
except OSError:
exit()
pathname = os.path.join(save_path, "source_test.py")
text_file = open(pathname, "w+")
text_file.write(dummy.getSourceCode())
text_file.close()
print("source file stored")
# input("source file stored press enter")
dummy.reset()
# dummy.close()
log_formatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
file_handler = logging.FileHandler("{0}/{1}.log".format(save_path, "console_output"))
file_handler.setFormatter(log_formatter)
root_logger.addHandler(file_handler)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(log_formatter)
root_logger.addHandler(console_handler)
if args.algo == 'a2c':
agent = algo.A2C_ACKTR(
actor_critic,
args.value_loss_coef,
args.entropy_coef,
lr=args.lr,
eps=args.eps,
alpha=args.alpha,
max_grad_norm=args.max_grad_norm)
elif args.algo == 'ppo':
if args.loss_sym > 0.0:
agent = algo.PPO(
actor_critic,
args.clip_param,
args.ppo_epoch,
args.num_mini_batch,
args.value_loss_coef,
args.entropy_coef,
symmetry_coef=args.loss_sym,
lr=args.lr,
eps=args.eps,
max_grad_norm=args.max_grad_norm,
mirror_act=mirror_action,
mirror_obs=mirror_obs
)
else:
agent = algo.PPO(
actor_critic,
args.clip_param,
args.ppo_epoch,
args.num_mini_batch,
args.value_loss_coef,
args.entropy_coef,
lr=args.lr,
eps=args.eps,
max_grad_norm=args.max_grad_norm)
elif args.algo == 'acktr':
agent = algo.A2C_ACKTR(
actor_critic, args.value_loss_coef, args.entropy_coef, acktr=True)
else:
agent = None
feat_select_func = None
obs = envs.reset()
obs_feat = gan_utils.replace_obs_with_feat(obs, args.cuda, feat_select_func, return_tensor=True)
feat_len = obs_feat.size(1) # TODO: multi-dim obs broken
if args.dup_sym:
buffer_np = args.num_processes * 2
else:
buffer_np = args.num_processes
rollouts = RolloutStorage(args.num_steps, buffer_np,
envs.observation_space.shape, envs.action_space,
actor_critic.recurrent_hidden_state_size,
feat_len)
rollouts.to(device)
if args.dup_sym:
obs_s = gan_utils.mirror_obsact_batch(obs, args.cuda, mirror_obs, augment=True)
obs_feat_s = obs_feat.repeat(2, 1)
rollouts.obs[0].copy_(obs_s)
rollouts.obs_feat[0].copy_(obs_feat_s)
else:
rollouts.obs[0].copy_(obs)
rollouts.obs_feat[0].copy_(obs_feat)
episode_rewards = deque(maxlen=10000)
total_num_episodes = 0
j = 0
max_num_episodes = args.num_episodes if args.num_episodes else np.infty
start = time.time()
num_updates = int(
args.num_env_steps) // args.num_steps // args.num_processes
while j < num_updates and total_num_episodes < max_num_episodes:
if args.use_linear_lr_decay:
# decrease learning rate linearly
utils.update_linear_schedule(
agent.optimizer, j, num_updates,
agent.optimizer.lr if args.algo == "acktr" else args.lr)
for step in range(args.num_steps):
# print(args.num_steps) 300*8
# Sample actions
with torch.no_grad():
value, action, action_log_prob, recurrent_hidden_states = actor_critic.act(
rollouts.obs[step, :args.num_processes, :],
rollouts.recurrent_hidden_states[step, :args.num_processes, :],
rollouts.masks[step, :args.num_processes, :])
# Obser reward and next obs
obs, reward, done, infos = envs.step(action)
obs_feat = gan_utils.replace_obs_with_feat(obs, args.cuda, feat_select_func, return_tensor=True)
for info in infos:
if 'episode' in info.keys():
episode_rewards.append(info['episode']['r'])
# If done then clean the history of observations.
masks = Tensor(
[[0.0] if done_ else [1.0] for done_ in done])
bad_masks = Tensor(
[[0.0] if 'bad_transition' in info.keys() else [1.0]
for info in infos])
if args.dup_sym:
obs_s = gan_utils.mirror_obsact_batch(obs, args.cuda, mirror_obs, augment=True)
action_s = gan_utils.mirror_obsact_batch(action, args.cuda, mirror_action, augment=True)
recurrent_hidden_states_s = recurrent_hidden_states.repeat(2, 1)
action_log_prob_s = action_log_prob.repeat(2, 1)
value_s = value.repeat(2, 1)
reward_s = reward.repeat(2, 1)
masks_s = masks.repeat(2, 1)
bad_masks_s = bad_masks.repeat(2, 1)
obs_feat_s = obs_feat.repeat(2, 1)
rollouts.insert(obs_s, recurrent_hidden_states_s, action_s,
action_log_prob_s, value_s, reward_s, masks_s, bad_masks_s, obs_feat_s)
else:
rollouts.insert(obs, recurrent_hidden_states, action,
action_log_prob, value, reward, masks, bad_masks, obs_feat)
with torch.no_grad():
next_value = actor_critic.get_value(
rollouts.obs[-1], rollouts.recurrent_hidden_states[-1],
rollouts.masks[-1]).detach()
rollouts.compute_returns(next_value, args.use_gae, args.gamma,
args.gae_lambda, not args.no_proper_time_limits)
value_loss, action_loss, dist_entropy = agent.update(rollouts)
rollouts.after_update()
# save for every interval-th episode or for the last epoch
if (j % args.save_interval == 0 or j == num_updates - 1) and args.save_dir != "":
torch.save([
actor_critic,
getattr(utils.get_vec_normalize(envs), 'ob_rms', None)
], os.path.join(save_path, args.env_name + ".pt"))
torch.save([
actor_critic,
getattr(utils.get_vec_normalize(envs), 'ob_rms', None)
], os.path.join(save_path, args.env_name + "_" + str(j) + ".pt"))
if j % args.log_interval == 0 and len(episode_rewards) > 1:
total_num_steps = (j + 1) * args.num_processes * args.num_steps
end = time.time()
root_logger.info(
("Updates {}, num timesteps {}, FPS {} \n Last {} training episodes:" +
" mean/median reward {:.1f}/{:.1f}, min/max reward {:.1f}/{:.1f}, " +
"dist en {}, l_pi {}, l_vf {} \n").format(
j, total_num_steps,
int(total_num_steps / (end - start)),
len(episode_rewards), np.mean(episode_rewards),
np.median(episode_rewards), np.min(episode_rewards),
np.max(episode_rewards), dist_entropy, value_loss,
action_loss
)
)
# actor_critic.dist.logstd._bias,
total_num_episodes += len(episode_rewards)
episode_rewards.clear()
j += 1
if __name__ == "__main__":
main()
|
[
"logging.Formatter",
"torch.set_num_threads",
"numpy.mean",
"third_party.a2c_ppo_acktr.algo.PPO",
"torch.device",
"third_party.a2c_ppo_acktr.algo.A2C_ACKTR",
"third_party.a2c_ppo_acktr.storage.RolloutStorage",
"torch.no_grad",
"os.path.join",
"third_party.a2c_ppo_acktr.utils.get_vec_normalize",
"collections.deque",
"sys.path.append",
"third_party.a2c_ppo_acktr.model.Policy",
"torch.load",
"third_party.a2c_ppo_acktr.utils.cleanup_log_dir",
"numpy.max",
"third_party.a2c_ppo_acktr.utils.update_linear_schedule",
"numpy.median",
"torch.manual_seed",
"logging.StreamHandler",
"numpy.min",
"my_pybullet_envs.utils.replace_obs_with_feat",
"torch.cuda.is_available",
"third_party.a2c_ppo_acktr.arguments.get_args",
"my_pybullet_envs.utils.mirror_obsact_batch",
"third_party.a2c_ppo_acktr.envs.make_vec_envs",
"gym.make",
"os.makedirs",
"time.time",
"torch.cuda.manual_seed_all",
"os.path.expanduser",
"logging.getLogger"
] |
[((1657, 1687), 'sys.path.append', 'sys.path.append', (['"""third_party"""'], {}), "('third_party')\n", (1672, 1687), False, 'import sys\n'), ((1725, 1735), 'third_party.a2c_ppo_acktr.arguments.get_args', 'get_args', ([], {}), '()\n', (1733, 1735), False, 'from third_party.a2c_ppo_acktr.arguments import get_args\n'), ((1859, 1887), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (1876, 1887), False, 'import torch\n'), ((1892, 1929), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['args.seed'], {}), '(args.seed)\n', (1918, 1929), False, 'import torch\n'), ((2119, 2151), 'os.path.expanduser', 'os.path.expanduser', (['args.log_dir'], {}), '(args.log_dir)\n', (2137, 2151), False, 'import os\n'), ((2193, 2223), 'third_party.a2c_ppo_acktr.utils.cleanup_log_dir', 'utils.cleanup_log_dir', (['log_dir'], {}), '(log_dir)\n', (2214, 2223), False, 'from third_party.a2c_ppo_acktr import algo, utils\n'), ((2228, 2263), 'third_party.a2c_ppo_acktr.utils.cleanup_log_dir', 'utils.cleanup_log_dir', (['eval_log_dir'], {}), '(eval_log_dir)\n', (2249, 2263), False, 'from third_party.a2c_ppo_acktr import algo, utils\n'), ((2269, 2293), 'torch.set_num_threads', 'torch.set_num_threads', (['(1)'], {}), '(1)\n', (2290, 2293), False, 'import torch\n'), ((2307, 2353), 'torch.device', 'torch.device', (["('cuda:0' if args.cuda else 'cpu')"], {}), "('cuda:0' if args.cuda else 'cpu')\n", (2319, 2353), False, 'import torch\n'), ((2438, 2570), 'third_party.a2c_ppo_acktr.envs.make_vec_envs', 'make_vec_envs', (['args.env_name', 'args.seed', 'args.num_processes', 'args.gamma', 'args.log_dir', 'device', '(False)'], {'render': '(False)'}), '(args.env_name, args.seed, args.num_processes, args.gamma,\n args.log_dir, device, False, render=False, **extra_dict)\n', (2451, 2570), False, 'from third_party.a2c_ppo_acktr.envs import make_vec_envs\n'), ((3325, 3376), 'gym.make', 'gym.make', (['args.env_name'], {'render': '(False)'}), '(args.env_name, render=False, **extra_dict)\n', (3333, 3376), False, 'import gym\n'), ((3393, 3431), 'os.path.join', 'os.path.join', (['args.save_dir', 'args.algo'], {}), '(args.save_dir, args.algo)\n', (3405, 3431), False, 'import os\n'), ((3675, 3716), 'os.path.join', 'os.path.join', (['save_path', '"""source_test.py"""'], {}), "(save_path, 'source_test.py')\n", (3687, 3716), False, 'import os\n'), ((3957, 4050), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s"""'], {}), "(\n '%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s')\n", (3974, 4050), False, 'import logging\n'), ((4064, 4083), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (4081, 4083), False, 'import logging\n'), ((4323, 4356), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (4344, 4356), False, 'import logging\n'), ((5867, 5956), 'my_pybullet_envs.utils.replace_obs_with_feat', 'gan_utils.replace_obs_with_feat', (['obs', 'args.cuda', 'feat_select_func'], {'return_tensor': '(True)'}), '(obs, args.cuda, feat_select_func,\n return_tensor=True)\n', (5898, 5956), True, 'from my_pybullet_envs import utils as gan_utils\n'), ((6144, 6290), 'third_party.a2c_ppo_acktr.storage.RolloutStorage', 'RolloutStorage', (['args.num_steps', 'buffer_np', 'envs.observation_space.shape', 'envs.action_space', 'actor_critic.recurrent_hidden_state_size', 'feat_len'], {}), '(args.num_steps, buffer_np, envs.observation_space.shape,\n envs.action_space, actor_critic.recurrent_hidden_state_size, feat_len)\n', (6158, 6290), False, 'from third_party.a2c_ppo_acktr.storage import RolloutStorage\n'), ((6751, 6770), 'collections.deque', 'deque', ([], {'maxlen': '(10000)'}), '(maxlen=10000)\n', (6756, 6770), False, 'from collections import deque\n'), ((6897, 6908), 'time.time', 'time.time', ([], {}), '()\n', (6906, 6908), False, 'import time\n'), ((1952, 1977), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1975, 1977), False, 'import torch\n'), ((2646, 2789), 'third_party.a2c_ppo_acktr.model.Policy', 'Policy', (['envs.observation_space.shape', 'envs.action_space'], {'base_kwargs': "{'recurrent': args.recurrent_policy, 'hidden_size': args.hidden_size}"}), "(envs.observation_space.shape, envs.action_space, base_kwargs={\n 'recurrent': args.recurrent_policy, 'hidden_size': args.hidden_size})\n", (2652, 2789), False, 'from third_party.a2c_ppo_acktr.model import Policy\n'), ((3494, 3516), 'os.makedirs', 'os.makedirs', (['save_path'], {}), '(save_path)\n', (3505, 3516), False, 'import os\n'), ((4493, 4645), 'third_party.a2c_ppo_acktr.algo.A2C_ACKTR', 'algo.A2C_ACKTR', (['actor_critic', 'args.value_loss_coef', 'args.entropy_coef'], {'lr': 'args.lr', 'eps': 'args.eps', 'alpha': 'args.alpha', 'max_grad_norm': 'args.max_grad_norm'}), '(actor_critic, args.value_loss_coef, args.entropy_coef, lr=\n args.lr, eps=args.eps, alpha=args.alpha, max_grad_norm=args.max_grad_norm)\n', (4507, 4645), False, 'from third_party.a2c_ppo_acktr import algo, utils\n'), ((6439, 6510), 'my_pybullet_envs.utils.mirror_obsact_batch', 'gan_utils.mirror_obsact_batch', (['obs', 'args.cuda', 'mirror_obs'], {'augment': '(True)'}), '(obs, args.cuda, mirror_obs, augment=True)\n', (6468, 6510), True, 'from my_pybullet_envs import utils as gan_utils\n'), ((2965, 2992), 'torch.load', 'torch.load', (['args.warm_start'], {}), '(args.warm_start)\n', (2975, 2992), False, 'import torch\n'), ((3037, 3084), 'torch.load', 'torch.load', (['args.warm_start'], {'map_location': '"""cpu"""'}), "(args.warm_start, map_location='cpu')\n", (3047, 3084), False, 'import torch\n'), ((7166, 7289), 'third_party.a2c_ppo_acktr.utils.update_linear_schedule', 'utils.update_linear_schedule', (['agent.optimizer', 'j', 'num_updates', "(agent.optimizer.lr if args.algo == 'acktr' else args.lr)"], {}), "(agent.optimizer, j, num_updates, agent.\n optimizer.lr if args.algo == 'acktr' else args.lr)\n", (7194, 7289), False, 'from third_party.a2c_ppo_acktr import algo, utils\n'), ((7894, 7983), 'my_pybullet_envs.utils.replace_obs_with_feat', 'gan_utils.replace_obs_with_feat', (['obs', 'args.cuda', 'feat_select_func'], {'return_tensor': '(True)'}), '(obs, args.cuda, feat_select_func,\n return_tensor=True)\n', (7925, 7983), True, 'from my_pybullet_envs import utils as gan_utils\n'), ((9406, 9421), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (9419, 9421), False, 'import torch\n'), ((10563, 10574), 'time.time', 'time.time', ([], {}), '()\n', (10572, 10574), False, 'import time\n'), ((4807, 5075), 'third_party.a2c_ppo_acktr.algo.PPO', 'algo.PPO', (['actor_critic', 'args.clip_param', 'args.ppo_epoch', 'args.num_mini_batch', 'args.value_loss_coef', 'args.entropy_coef'], {'symmetry_coef': 'args.loss_sym', 'lr': 'args.lr', 'eps': 'args.eps', 'max_grad_norm': 'args.max_grad_norm', 'mirror_act': 'mirror_action', 'mirror_obs': 'mirror_obs'}), '(actor_critic, args.clip_param, args.ppo_epoch, args.num_mini_batch,\n args.value_loss_coef, args.entropy_coef, symmetry_coef=args.loss_sym,\n lr=args.lr, eps=args.eps, max_grad_norm=args.max_grad_norm, mirror_act=\n mirror_action, mirror_obs=mirror_obs)\n', (4815, 5075), False, 'from third_party.a2c_ppo_acktr import algo, utils\n'), ((5303, 5488), 'third_party.a2c_ppo_acktr.algo.PPO', 'algo.PPO', (['actor_critic', 'args.clip_param', 'args.ppo_epoch', 'args.num_mini_batch', 'args.value_loss_coef', 'args.entropy_coef'], {'lr': 'args.lr', 'eps': 'args.eps', 'max_grad_norm': 'args.max_grad_norm'}), '(actor_critic, args.clip_param, args.ppo_epoch, args.num_mini_batch,\n args.value_loss_coef, args.entropy_coef, lr=args.lr, eps=args.eps,\n max_grad_norm=args.max_grad_norm)\n', (5311, 5488), False, 'from third_party.a2c_ppo_acktr import algo, utils\n'), ((5673, 5759), 'third_party.a2c_ppo_acktr.algo.A2C_ACKTR', 'algo.A2C_ACKTR', (['actor_critic', 'args.value_loss_coef', 'args.entropy_coef'], {'acktr': '(True)'}), '(actor_critic, args.value_loss_coef, args.entropy_coef, acktr\n =True)\n', (5687, 5759), False, 'from third_party.a2c_ppo_acktr import algo, utils\n'), ((7450, 7465), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7463, 7465), False, 'import torch\n'), ((8468, 8539), 'my_pybullet_envs.utils.mirror_obsact_batch', 'gan_utils.mirror_obsact_batch', (['obs', 'args.cuda', 'mirror_obs'], {'augment': '(True)'}), '(obs, args.cuda, mirror_obs, augment=True)\n', (8497, 8539), True, 'from my_pybullet_envs import utils as gan_utils\n'), ((8567, 8644), 'my_pybullet_envs.utils.mirror_obsact_batch', 'gan_utils.mirror_obsact_batch', (['action', 'args.cuda', 'mirror_action'], {'augment': '(True)'}), '(action, args.cuda, mirror_action, augment=True)\n', (8596, 8644), True, 'from my_pybullet_envs import utils as gan_utils\n'), ((10147, 10193), 'os.path.join', 'os.path.join', (['save_path', "(args.env_name + '.pt')"], {}), "(save_path, args.env_name + '.pt')\n", (10159, 10193), False, 'import os\n'), ((10980, 11004), 'numpy.mean', 'np.mean', (['episode_rewards'], {}), '(episode_rewards)\n', (10987, 11004), True, 'import numpy as np\n'), ((11026, 11052), 'numpy.median', 'np.median', (['episode_rewards'], {}), '(episode_rewards)\n', (11035, 11052), True, 'import numpy as np\n'), ((11054, 11077), 'numpy.min', 'np.min', (['episode_rewards'], {}), '(episode_rewards)\n', (11060, 11077), True, 'import numpy as np\n'), ((11099, 11122), 'numpy.max', 'np.max', (['episode_rewards'], {}), '(episode_rewards)\n', (11105, 11122), True, 'import numpy as np\n'), ((10085, 10114), 'third_party.a2c_ppo_acktr.utils.get_vec_normalize', 'utils.get_vec_normalize', (['envs'], {}), '(envs)\n', (10108, 10114), False, 'from third_party.a2c_ppo_acktr import algo, utils\n'), ((10275, 10304), 'third_party.a2c_ppo_acktr.utils.get_vec_normalize', 'utils.get_vec_normalize', (['envs'], {}), '(envs)\n', (10298, 10304), False, 'from third_party.a2c_ppo_acktr import algo, utils\n')]
|
import os
import logging
logging.basicConfig(level=logging.INFO)
import numpy as np
import matplotlib.pyplot as plt
from stompy.grid import paver
from stompy.spatial.linestring_utils import upsample_linearring,resample_linearring
from stompy.grid import paver
from stompy.spatial import field,constrained_delaunay,wkb2shp
##
from stompy.grid import exact_delaunay
from stompy.grid import live_dt
from stompy.grid import paver
reload(exact_delaunay)
reload(live_dt)
reload(paver)
##
def test_basic():
# Define a polygon
boundary=np.array([[0,0],[1000,0],[1000,1000],[0,1000]])
island =np.array([[200,200],[600,200],[200,600]])
rings=[boundary,island]
# And the scale:
scale=field.ConstantField(50)
p=paver.Paving(rings=rings,density=scale)
p.pave_all()
##
def test_basic_apollo():
# Define a polygon
boundary=np.array([[0,0],[1000,0],[1000,1000],[0,1000]])
island =np.array([[200,200],[600,200],[200,600]])
rings=[boundary,island]
# And the scale:
scale=field.PyApolloniusField()
scale.insert([50,50],20)
p=paver.Paving(rings=rings,density=scale)
p.pave_all()
return p
##
# A circle - r = 100, C=628, n_points = 628
def test_circle():
r = 100
thetas = np.linspace(0,2*np.pi,200)[:-1]
circle = np.zeros((len(thetas),2),np.float64)
circle[:,0] = r*np.cos(thetas)
circle[:,1] = r*np.sin(thetas)
class CircleDensityField(field.Field):
# horizontally varying, from 5 to 20
def value(self,X):
X = np.array(X)
return 5 + 15 * (X[...,0] + 100) / 200.0
density = CircleDensityField()
p=paver.Paving(circle,density,label='circle')
p.pave_all()
def test_long_channel():
l = 2000
w = 50
long_channel = np.array([[0,0],
[l,0],
[l,w],
[0,w]], np.float64 )
density = field.ConstantField( 19.245 )
p=paver.Paving(long_channel,density)
p.pave_all()
def test_long_channel_rigid():
l = 2000
w = 50
long_channel = np.array([[0,0],
[l,0],
[l,w],
[0,w]], np.float64 )
density = field.ConstantField( 19.245 )
p=paver.Paving(long_channel,density,initial_node_status=paver.Paving.RIGID)
p.pave_all()
def test_narrow_channel():
l = 1000
w = 50
long_channel = np.array([[0,0],
[l,0.375*w],
[l,0.625*w],
[0,w]], np.float64 )
density = field.ConstantField( w/np.sin(60*np.pi/180.) / 4 )
p=paver.Paving(long_channel,density)
p.pave_all()
def test_small_island():
l = 100
square = np.array([[0,0],
[l,0],
[l,l],
[0,l]], np.float64 )
r=10
theta = np.linspace(0,2*np.pi,30)
circle = r/np.sqrt(2) * np.swapaxes( np.array([np.cos(theta), np.sin(theta)]), 0,1)
island1 = circle + np.array([45,45])
island2 = circle + np.array([65,65])
island3 = circle + np.array([20,80])
rings = [square,island1,island2,island3]
density = field.ConstantField( 10 )
p=paver.Paving(rings,density)
p.pave_all()
def test_tight_peanut():
r = 100
thetas = np.linspace(0,2*np.pi,300)
peanut = np.zeros( (len(thetas),2), np.float64)
x = r*np.cos(thetas)
y = r*np.sin(thetas) * (0.9/10000 * x*x + 0.05)
peanut[:,0] = x
peanut[:,1] = y
density = field.ConstantField( 6.0 )
p=paver.Paving(peanut,density,label='tight_peanut')
p.pave_all()
def test_tight_with_island():
# build a peanut first:
r = 100
thetas = np.linspace(0,2*np.pi,250)
peanut = np.zeros( (len(thetas),2), np.float64)
x = r*np.cos(thetas)
y = r*np.sin(thetas) * (0.9/10000 * x*x + 0.05)
peanut[:,0] = x
peanut[:,1] = y
# put two holes into it
thetas = np.linspace(0,2*np.pi,30)
hole1 = np.zeros( (len(thetas),2), np.float64)
hole1[:,0] = 10*np.cos(thetas) - 75
hole1[:,1] = 10*np.sin(thetas)
hole2 = np.zeros( (len(thetas),2), np.float64)
hole2[:,0] = 20*np.cos(thetas) + 75
hole2[:,1] = 20*np.sin(thetas)
rings = [peanut,hole1,hole2]
density = field.ConstantField( 6.0 )
p=paver.Paving(rings,density,label='tight_with_island')
p.pave_all()
def test_peninsula():
r = 100
thetas = np.linspace(0,2*np.pi,1000)
pen = np.zeros( (len(thetas),2), np.float64)
pen[:,0] = r*(0.2+ np.abs(np.sin(2*thetas))**0.2)*np.cos(thetas)
pen[:,1] = r*(0.2+ np.abs(np.sin(2*thetas))**0.2)*np.sin(thetas)
density = field.ConstantField( 10.0 )
pen2 = upsample_linearring(pen,density)
p=paver.Paving(pen2,density,label='peninsula')
p.pave_all()
def test_peanut():
# like a figure 8, or a peanut
r = 100
thetas = np.linspace(0,2*np.pi,1000)
peanut = np.zeros( (len(thetas),2), np.float64)
peanut[:,0] = r*(0.5+0.3*np.cos(2*thetas))*np.cos(thetas)
peanut[:,1] = r*(0.5+0.3*np.cos(2*thetas))*np.sin(thetas)
min_pnt = peanut.min(axis=0)
max_pnt = peanut.max(axis=0)
d_data = np.array([ [min_pnt[0],min_pnt[1], 1.5],
[min_pnt[0],max_pnt[1], 1.5],
[max_pnt[0],min_pnt[1], 8],
[max_pnt[0],max_pnt[1], 8]])
density = field.XYZField(X=d_data[:,:2],F=d_data[:,2])
p=paver.Paving(peanut,density)
p.pave_all()
def test_cul_de_sac():
r=5
theta = np.linspace(-np.pi/2,np.pi/2,20)
cap = r * np.swapaxes( np.array([np.cos(theta), np.sin(theta)]), 0,1)
box = np.array([ [-3*r,r],
[-4*r,-r] ])
ring = np.concatenate((box,cap))
density = field.ConstantField(2*r/(np.sqrt(3)/2))
p=paver.Paving(ring,density,label='cul_de_sac')
p.pave_all()
def test_bow():
x = np.linspace(-100,100,50)
# with /1000 it seems to do okay
# with /500 it still looks okay
y = x**2 / 250.0
bow = np.swapaxes( np.concatenate( (x[None,:],y[None,:]) ), 0,1)
height = np.array([0,20])
ring = np.concatenate( (bow+height,bow[::-1]-height) )
density = field.ConstantField(2)
p=paver.Paving(ring,density,label='bow')
p.pave_all()
def test_ngon(nsides=7):
# hexagon works ok, though a bit of perturbation
# septagon starts to show expansion issues, but never pronounced
# octagon - works fine.
theta = np.linspace(0,2*np.pi,nsides+1)[:-1]
r=100
x = r*np.cos(theta)
y = r*np.sin(theta)
poly = np.swapaxes( np.concatenate( (x[None,:],y[None,:]) ), 0,1)
density = field.ConstantField(6)
p=paver.Paving(poly,density,label='ngon%02d'%nsides)
p.pave_all()
def test_expansion():
# 40: too close to a 120deg angle - always bisect on centerline
# 30: rows alternate with wall and bisect seams
# 35: starts to diverge, but recovers.
# 37: too close to 120.
d = 36
pnts = np.array([[0.,0.],
[100,-d],
[200,0],
[200,100],
[100,100+d],
[0,100]])
density = field.ConstantField(6)
p=paver.Paving([pnts],density,label='expansion')
p.pave_all()
def test_embedded_channel():
# trying out degenerate internal lines - the trick may be mostly in
# how to specify them.
# make a large rectangle, with a sinuous channel in the middle
L = 500.0
W = 300.0
rect = np.array([[0,0],
[L,0],
[L,W],
[0,W]])
x = np.linspace(0.1*L,0.9*L,50)
y = W/2 + 0.1*W*np.cos(4*np.pi*x/L)
shore = np.swapaxes( np.concatenate( (x[None,:],y[None,:]) ), 0,1)
density = field.ConstantField(10)
# this will probably get moved into Paver itself.
# Note closed_ring=0 !
shore = resample_linearring(shore,density,closed_ring=0)
south_shore = shore - np.array([0,0.1*W])
north_shore = shore + np.array([0,0.1*W])
p=paver.Paving([rect],density,degenerates=[north_shore,south_shore])
p.pave_all()
# dumbarton...
def test_dumbarton():
shp=os.path.join( os.path.dirname(__file__), 'data','dumbarton.shp')
features=wkb2shp.shp2geom(shp)
geom = features['geom'][0]
dumbarton = np.array(geom.exterior)
density = field.ConstantField(250.0)
p=paver.Paving(dumbarton, density,label='dumbarton')
p.pave_all()
# #def log_spiral_channel():
# t = linspace(1.0,12*pi,200)
# a = 1 ; b = 0.1
# x = a*exp(b*t)*cos(t)
# y = a*exp(b*t)*sin(t)
# # each 2*pi, the radius gets bigger by exp(2pi*b)
# x2 = a*exp(b*t-b*pi)*cos(t)
# y2 = a*exp(b*t-b*pi)*sin(t)
# cla(); plot(x,y,'b',x2,y2,'r')
##
# This is going to require a fair bit of porting --
# hmm - maybe better just to have a sinusoid channel, then perturb it
# and put some islands in there. having a wide range of scales looks
# nice but isn't going to be a great test.
def gen_sine_sine():
t = np.linspace(1.0,12*np.pi,400)
x1 = 100*t
y1 = 200*np.sin(t)
# each 2*pi, the radius gets bigger by exp(2pi*b)
x2 = x1
y2 = y1+50
# now perturb both sides, but keep amplitude < 20
y1 = y1 + 20*np.sin(10*t)
y2 = y2 + 10*np.cos(5*t)
x = np.concatenate( (x1,x2[::-1]) )
y = np.concatenate( (y1,y2[::-1]) )
shore = np.swapaxes( np.concatenate( (x[None,:],y[None,:]) ), 0,1)
rings = [shore]
# and make some islands:
north_island_shore = 0.4*y1 + 0.6*y2
south_island_shore = 0.6*y1 + 0.4*y2
Nislands = 20
# islands same length as space between islands, so divide
# island shorelines into 2*Nislands blocks
for i in range(Nislands):
i_start = int( (2*i+0.5)*len(t)/(2*Nislands) )
i_stop = int( (2*i+1.5)*len(t)/(2*Nislands) )
north_y = north_island_shore[i_start:i_stop]
south_y = south_island_shore[i_start:i_stop]
north_x = x1[i_start:i_stop]
south_x = x2[i_start:i_stop]
x = np.concatenate( (north_x,south_x[::-1]) )
y = np.concatenate( (north_y,south_y[::-1]) )
island = np.swapaxes( np.concatenate( (x[None,:],y[None,:]) ), 0,1)
rings.append(island)
density = field.ConstantField(25.0)
min_density = field.ConstantField(2.0)
p = paver.Paving(rings,density=density,min_density=min_density)
print("Smoothing to nominal 1.0m")
# mostly just to make sure that long segments are
# sampled well relative to the local feature scale.
p.smooth()
print("Adjusting other densities to local feature size")
p.telescope_rate=1.1
p.adjust_density_by_apollonius()
return p
def test_sine_sine():
p=gen_sine_sine()
p.pave_all()
if 0:
# debugging the issue with sine_sine()
# fails deep inside here, step 512
# lots of crap coming from this one, too.
# at some point, dt_incident_constraints reports only 1 constraint,
# but it should have two, which happens because of a bad slide.
# Tricky to guard against -
# Several avenues to fix this:
# 1. Make the resample_neighbors code (which I'm pretty sure is the culprit)
# more cautious and willing to accept a local maximum in distance instead
# of shoving a node far away. This is a nice but incomplete solution.
# 2. The resample code, which I think is responsible for adding the new node
# that screwed it all up, should check for self-intersections
# this is probably the appropriate thing to do.
# test_sine_sine()
p=gen_sine_sine()
p.pave_all(n_steps=512)
##
p.verbose=3
p.pave_all(n_steps=513)
##
zoom=plt.axis()
plt.figure(1).clf()
p.plot()
p.plot_boundary()
plt.axis('equal')
plt.axis(zoom)
##
# Step 510 really takes the end off an island
# yep.
p.pave_all(n_steps=512)
##
# node is 3626
# to_remove: an edge with nodes 5374, 3626
# pnt2edges: [3626, 5915]
# part of the problem is that there is some sliding around
# at the beginning of step 512 that really wreaks havoc on
# what was already a dicey node.
p.plot_nodes([3626,5374])
|
[
"stompy.spatial.field.PyApolloniusField",
"stompy.spatial.linestring_utils.upsample_linearring",
"logging.basicConfig",
"stompy.grid.paver.Paving",
"os.path.dirname",
"stompy.spatial.field.ConstantField",
"matplotlib.pyplot.axis",
"stompy.spatial.field.XYZField",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.array",
"numpy.linspace",
"numpy.cos",
"stompy.spatial.linestring_utils.resample_linearring",
"numpy.sqrt",
"numpy.concatenate",
"stompy.spatial.wkb2shp.shp2geom"
] |
[((25, 64), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (44, 64), False, 'import logging\n'), ((541, 595), 'numpy.array', 'np.array', (['[[0, 0], [1000, 0], [1000, 1000], [0, 1000]]'], {}), '([[0, 0], [1000, 0], [1000, 1000], [0, 1000]])\n', (549, 595), True, 'import numpy as np\n'), ((602, 648), 'numpy.array', 'np.array', (['[[200, 200], [600, 200], [200, 600]]'], {}), '([[200, 200], [600, 200], [200, 600]])\n', (610, 648), True, 'import numpy as np\n'), ((705, 728), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(50)'], {}), '(50)\n', (724, 728), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((736, 776), 'stompy.grid.paver.Paving', 'paver.Paving', ([], {'rings': 'rings', 'density': 'scale'}), '(rings=rings, density=scale)\n', (748, 776), False, 'from stompy.grid import paver\n'), ((860, 914), 'numpy.array', 'np.array', (['[[0, 0], [1000, 0], [1000, 1000], [0, 1000]]'], {}), '([[0, 0], [1000, 0], [1000, 1000], [0, 1000]])\n', (868, 914), True, 'import numpy as np\n'), ((921, 967), 'numpy.array', 'np.array', (['[[200, 200], [600, 200], [200, 600]]'], {}), '([[200, 200], [600, 200], [200, 600]])\n', (929, 967), True, 'import numpy as np\n'), ((1024, 1049), 'stompy.spatial.field.PyApolloniusField', 'field.PyApolloniusField', ([], {}), '()\n', (1047, 1049), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((1086, 1126), 'stompy.grid.paver.Paving', 'paver.Paving', ([], {'rings': 'rings', 'density': 'scale'}), '(rings=rings, density=scale)\n', (1098, 1126), False, 'from stompy.grid import paver\n'), ((1645, 1690), 'stompy.grid.paver.Paving', 'paver.Paving', (['circle', 'density'], {'label': '"""circle"""'}), "(circle, density, label='circle')\n", (1657, 1690), False, 'from stompy.grid import paver\n'), ((1775, 1829), 'numpy.array', 'np.array', (['[[0, 0], [l, 0], [l, w], [0, w]]', 'np.float64'], {}), '([[0, 0], [l, 0], [l, w], [0, w]], np.float64)\n', (1783, 1829), True, 'import numpy as np\n'), ((1929, 1956), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(19.245)'], {}), '(19.245)\n', (1948, 1956), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((1965, 2000), 'stompy.grid.paver.Paving', 'paver.Paving', (['long_channel', 'density'], {}), '(long_channel, density)\n', (1977, 2000), False, 'from stompy.grid import paver\n'), ((2092, 2146), 'numpy.array', 'np.array', (['[[0, 0], [l, 0], [l, w], [0, w]]', 'np.float64'], {}), '([[0, 0], [l, 0], [l, w], [0, w]], np.float64)\n', (2100, 2146), True, 'import numpy as np\n'), ((2246, 2273), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(19.245)'], {}), '(19.245)\n', (2265, 2273), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((2282, 2357), 'stompy.grid.paver.Paving', 'paver.Paving', (['long_channel', 'density'], {'initial_node_status': 'paver.Paving.RIGID'}), '(long_channel, density, initial_node_status=paver.Paving.RIGID)\n', (2294, 2357), False, 'from stompy.grid import paver\n'), ((2446, 2516), 'numpy.array', 'np.array', (['[[0, 0], [l, 0.375 * w], [l, 0.625 * w], [0, w]]', 'np.float64'], {}), '([[0, 0], [l, 0.375 * w], [l, 0.625 * w], [0, w]], np.float64)\n', (2454, 2516), True, 'import numpy as np\n'), ((2669, 2704), 'stompy.grid.paver.Paving', 'paver.Paving', (['long_channel', 'density'], {}), '(long_channel, density)\n', (2681, 2704), False, 'from stompy.grid import paver\n'), ((2776, 2830), 'numpy.array', 'np.array', (['[[0, 0], [l, 0], [l, l], [0, l]]', 'np.float64'], {}), '([[0, 0], [l, 0], [l, l], [0, l]], np.float64)\n', (2784, 2830), True, 'import numpy as np\n'), ((2919, 2948), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(30)'], {}), '(0, 2 * np.pi, 30)\n', (2930, 2948), True, 'import numpy as np\n'), ((3216, 3239), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(10)'], {}), '(10)\n', (3235, 3239), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((3248, 3276), 'stompy.grid.paver.Paving', 'paver.Paving', (['rings', 'density'], {}), '(rings, density)\n', (3260, 3276), False, 'from stompy.grid import paver\n'), ((3344, 3374), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(300)'], {}), '(0, 2 * np.pi, 300)\n', (3355, 3374), True, 'import numpy as np\n'), ((3554, 3578), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(6.0)'], {}), '(6.0)\n', (3573, 3578), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((3587, 3638), 'stompy.grid.paver.Paving', 'paver.Paving', (['peanut', 'density'], {'label': '"""tight_peanut"""'}), "(peanut, density, label='tight_peanut')\n", (3599, 3638), False, 'from stompy.grid import paver\n'), ((3738, 3768), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(250)'], {}), '(0, 2 * np.pi, 250)\n', (3749, 3768), True, 'import numpy as np\n'), ((3976, 4005), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(30)'], {}), '(0, 2 * np.pi, 30)\n', (3987, 4005), True, 'import numpy as np\n'), ((4305, 4329), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(6.0)'], {}), '(6.0)\n', (4324, 4329), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((4338, 4393), 'stompy.grid.paver.Paving', 'paver.Paving', (['rings', 'density'], {'label': '"""tight_with_island"""'}), "(rings, density, label='tight_with_island')\n", (4350, 4393), False, 'from stompy.grid import paver\n'), ((4457, 4488), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(1000)'], {}), '(0, 2 * np.pi, 1000)\n', (4468, 4488), True, 'import numpy as np\n'), ((4688, 4713), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(10.0)'], {}), '(10.0)\n', (4707, 4713), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((4727, 4760), 'stompy.spatial.linestring_utils.upsample_linearring', 'upsample_linearring', (['pen', 'density'], {}), '(pen, density)\n', (4746, 4760), False, 'from stompy.spatial.linestring_utils import upsample_linearring, resample_linearring\n'), ((4771, 4817), 'stompy.grid.paver.Paving', 'paver.Paving', (['pen2', 'density'], {'label': '"""peninsula"""'}), "(pen2, density, label='peninsula')\n", (4783, 4817), False, 'from stompy.grid import paver\n'), ((4914, 4945), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(1000)'], {}), '(0, 2 * np.pi, 1000)\n', (4925, 4945), True, 'import numpy as np\n'), ((5199, 5334), 'numpy.array', 'np.array', (['[[min_pnt[0], min_pnt[1], 1.5], [min_pnt[0], max_pnt[1], 1.5], [max_pnt[0],\n min_pnt[1], 8], [max_pnt[0], max_pnt[1], 8]]'], {}), '([[min_pnt[0], min_pnt[1], 1.5], [min_pnt[0], max_pnt[1], 1.5], [\n max_pnt[0], min_pnt[1], 8], [max_pnt[0], max_pnt[1], 8]])\n', (5207, 5334), True, 'import numpy as np\n'), ((5413, 5460), 'stompy.spatial.field.XYZField', 'field.XYZField', ([], {'X': 'd_data[:, :2]', 'F': 'd_data[:, 2]'}), '(X=d_data[:, :2], F=d_data[:, 2])\n', (5427, 5460), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((5465, 5494), 'stompy.grid.paver.Paving', 'paver.Paving', (['peanut', 'density'], {}), '(peanut, density)\n', (5477, 5494), False, 'from stompy.grid import paver\n'), ((5555, 5593), 'numpy.linspace', 'np.linspace', (['(-np.pi / 2)', '(np.pi / 2)', '(20)'], {}), '(-np.pi / 2, np.pi / 2, 20)\n', (5566, 5593), True, 'import numpy as np\n'), ((5672, 5709), 'numpy.array', 'np.array', (['[[-3 * r, r], [-4 * r, -r]]'], {}), '([[-3 * r, r], [-4 * r, -r]])\n', (5680, 5709), True, 'import numpy as np\n'), ((5738, 5764), 'numpy.concatenate', 'np.concatenate', (['(box, cap)'], {}), '((box, cap))\n', (5752, 5764), True, 'import numpy as np\n'), ((5825, 5872), 'stompy.grid.paver.Paving', 'paver.Paving', (['ring', 'density'], {'label': '"""cul_de_sac"""'}), "(ring, density, label='cul_de_sac')\n", (5837, 5872), False, 'from stompy.grid import paver\n'), ((5913, 5939), 'numpy.linspace', 'np.linspace', (['(-100)', '(100)', '(50)'], {}), '(-100, 100, 50)\n', (5924, 5939), True, 'import numpy as np\n'), ((6114, 6131), 'numpy.array', 'np.array', (['[0, 20]'], {}), '([0, 20])\n', (6122, 6131), True, 'import numpy as np\n'), ((6142, 6192), 'numpy.concatenate', 'np.concatenate', (['(bow + height, bow[::-1] - height)'], {}), '((bow + height, bow[::-1] - height))\n', (6156, 6192), True, 'import numpy as np\n'), ((6204, 6226), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(2)'], {}), '(2)\n', (6223, 6226), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((6233, 6273), 'stompy.grid.paver.Paving', 'paver.Paving', (['ring', 'density'], {'label': '"""bow"""'}), "(ring, density, label='bow')\n", (6245, 6273), False, 'from stompy.grid import paver\n'), ((6672, 6694), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(6)'], {}), '(6)\n', (6691, 6694), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((6701, 6755), 'stompy.grid.paver.Paving', 'paver.Paving', (['poly', 'density'], {'label': "('ngon%02d' % nsides)"}), "(poly, density, label='ngon%02d' % nsides)\n", (6713, 6755), False, 'from stompy.grid import paver\n'), ((7005, 7091), 'numpy.array', 'np.array', (['[[0.0, 0.0], [100, -d], [200, 0], [200, 100], [100, 100 + d], [0, 100]]'], {}), '([[0.0, 0.0], [100, -d], [200, 0], [200, 100], [100, 100 + d], [0, \n 100]])\n', (7013, 7091), True, 'import numpy as np\n'), ((7197, 7219), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(6)'], {}), '(6)\n', (7216, 7219), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((7226, 7274), 'stompy.grid.paver.Paving', 'paver.Paving', (['[pnts]', 'density'], {'label': '"""expansion"""'}), "([pnts], density, label='expansion')\n", (7238, 7274), False, 'from stompy.grid import paver\n'), ((7530, 7572), 'numpy.array', 'np.array', (['[[0, 0], [L, 0], [L, W], [0, W]]'], {}), '([[0, 0], [L, 0], [L, W], [0, W]])\n', (7538, 7572), True, 'import numpy as np\n'), ((7632, 7665), 'numpy.linspace', 'np.linspace', (['(0.1 * L)', '(0.9 * L)', '(50)'], {}), '(0.1 * L, 0.9 * L, 50)\n', (7643, 7665), True, 'import numpy as np\n'), ((7790, 7813), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(10)'], {}), '(10)\n', (7809, 7813), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((7912, 7962), 'stompy.spatial.linestring_utils.resample_linearring', 'resample_linearring', (['shore', 'density'], {'closed_ring': '(0)'}), '(shore, density, closed_ring=0)\n', (7931, 7962), False, 'from stompy.spatial.linestring_utils import upsample_linearring, resample_linearring\n'), ((8061, 8130), 'stompy.grid.paver.Paving', 'paver.Paving', (['[rect]', 'density'], {'degenerates': '[north_shore, south_shore]'}), '([rect], density, degenerates=[north_shore, south_shore])\n', (8073, 8130), False, 'from stompy.grid import paver\n'), ((8269, 8290), 'stompy.spatial.wkb2shp.shp2geom', 'wkb2shp.shp2geom', (['shp'], {}), '(shp)\n', (8285, 8290), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((8338, 8361), 'numpy.array', 'np.array', (['geom.exterior'], {}), '(geom.exterior)\n', (8346, 8361), True, 'import numpy as np\n'), ((8376, 8402), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(250.0)'], {}), '(250.0)\n', (8395, 8402), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((8409, 8460), 'stompy.grid.paver.Paving', 'paver.Paving', (['dumbarton', 'density'], {'label': '"""dumbarton"""'}), "(dumbarton, density, label='dumbarton')\n", (8421, 8460), False, 'from stompy.grid import paver\n'), ((9018, 9051), 'numpy.linspace', 'np.linspace', (['(1.0)', '(12 * np.pi)', '(400)'], {}), '(1.0, 12 * np.pi, 400)\n', (9029, 9051), True, 'import numpy as np\n'), ((9293, 9323), 'numpy.concatenate', 'np.concatenate', (['(x1, x2[::-1])'], {}), '((x1, x2[::-1]))\n', (9307, 9323), True, 'import numpy as np\n'), ((9333, 9363), 'numpy.concatenate', 'np.concatenate', (['(y1, y2[::-1])'], {}), '((y1, y2[::-1]))\n', (9347, 9363), True, 'import numpy as np\n'), ((10264, 10289), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(25.0)'], {}), '(25.0)\n', (10283, 10289), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((10308, 10332), 'stompy.spatial.field.ConstantField', 'field.ConstantField', (['(2.0)'], {}), '(2.0)\n', (10327, 10332), False, 'from stompy.spatial import field, constrained_delaunay, wkb2shp\n'), ((10341, 10402), 'stompy.grid.paver.Paving', 'paver.Paving', (['rings'], {'density': 'density', 'min_density': 'min_density'}), '(rings, density=density, min_density=min_density)\n', (10353, 10402), False, 'from stompy.grid import paver\n'), ((11719, 11729), 'matplotlib.pyplot.axis', 'plt.axis', ([], {}), '()\n', (11727, 11729), True, 'import matplotlib.pyplot as plt\n'), ((11794, 11811), 'matplotlib.pyplot.axis', 'plt.axis', (['"""equal"""'], {}), "('equal')\n", (11802, 11811), True, 'import matplotlib.pyplot as plt\n'), ((11816, 11830), 'matplotlib.pyplot.axis', 'plt.axis', (['zoom'], {}), '(zoom)\n', (11824, 11830), True, 'import matplotlib.pyplot as plt\n'), ((1256, 1286), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(200)'], {}), '(0, 2 * np.pi, 200)\n', (1267, 1286), True, 'import numpy as np\n'), ((1358, 1372), 'numpy.cos', 'np.cos', (['thetas'], {}), '(thetas)\n', (1364, 1372), True, 'import numpy as np\n'), ((1393, 1407), 'numpy.sin', 'np.sin', (['thetas'], {}), '(thetas)\n', (1399, 1407), True, 'import numpy as np\n'), ((3056, 3074), 'numpy.array', 'np.array', (['[45, 45]'], {}), '([45, 45])\n', (3064, 3074), True, 'import numpy as np\n'), ((3097, 3115), 'numpy.array', 'np.array', (['[65, 65]'], {}), '([65, 65])\n', (3105, 3115), True, 'import numpy as np\n'), ((3138, 3156), 'numpy.array', 'np.array', (['[20, 80]'], {}), '([20, 80])\n', (3146, 3156), True, 'import numpy as np\n'), ((3433, 3447), 'numpy.cos', 'np.cos', (['thetas'], {}), '(thetas)\n', (3439, 3447), True, 'import numpy as np\n'), ((3827, 3841), 'numpy.cos', 'np.cos', (['thetas'], {}), '(thetas)\n', (3833, 3841), True, 'import numpy as np\n'), ((4114, 4128), 'numpy.sin', 'np.sin', (['thetas'], {}), '(thetas)\n', (4120, 4128), True, 'import numpy as np\n'), ((4241, 4255), 'numpy.sin', 'np.sin', (['thetas'], {}), '(thetas)\n', (4247, 4255), True, 'import numpy as np\n'), ((4589, 4603), 'numpy.cos', 'np.cos', (['thetas'], {}), '(thetas)\n', (4595, 4603), True, 'import numpy as np\n'), ((4658, 4672), 'numpy.sin', 'np.sin', (['thetas'], {}), '(thetas)\n', (4664, 4672), True, 'import numpy as np\n'), ((5042, 5056), 'numpy.cos', 'np.cos', (['thetas'], {}), '(thetas)\n', (5048, 5056), True, 'import numpy as np\n'), ((5104, 5118), 'numpy.sin', 'np.sin', (['thetas'], {}), '(thetas)\n', (5110, 5118), True, 'import numpy as np\n'), ((6055, 6095), 'numpy.concatenate', 'np.concatenate', (['(x[None, :], y[None, :])'], {}), '((x[None, :], y[None, :]))\n', (6069, 6095), True, 'import numpy as np\n'), ((6477, 6514), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(nsides + 1)'], {}), '(0, 2 * np.pi, nsides + 1)\n', (6488, 6514), True, 'import numpy as np\n'), ((6540, 6553), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (6546, 6553), True, 'import numpy as np\n'), ((6564, 6577), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6570, 6577), True, 'import numpy as np\n'), ((6607, 6647), 'numpy.concatenate', 'np.concatenate', (['(x[None, :], y[None, :])'], {}), '((x[None, :], y[None, :]))\n', (6621, 6647), True, 'import numpy as np\n'), ((7725, 7765), 'numpy.concatenate', 'np.concatenate', (['(x[None, :], y[None, :])'], {}), '((x[None, :], y[None, :]))\n', (7739, 7765), True, 'import numpy as np\n'), ((7988, 8010), 'numpy.array', 'np.array', (['[0, 0.1 * W]'], {}), '([0, 0.1 * W])\n', (7996, 8010), True, 'import numpy as np\n'), ((8034, 8056), 'numpy.array', 'np.array', (['[0, 0.1 * W]'], {}), '([0, 0.1 * W])\n', (8042, 8056), True, 'import numpy as np\n'), ((8205, 8230), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (8220, 8230), False, 'import os\n'), ((9076, 9085), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (9082, 9085), True, 'import numpy as np\n'), ((9391, 9431), 'numpy.concatenate', 'np.concatenate', (['(x[None, :], y[None, :])'], {}), '((x[None, :], y[None, :]))\n', (9405, 9431), True, 'import numpy as np\n'), ((10047, 10087), 'numpy.concatenate', 'np.concatenate', (['(north_x, south_x[::-1])'], {}), '((north_x, south_x[::-1]))\n', (10061, 10087), True, 'import numpy as np\n'), ((10101, 10141), 'numpy.concatenate', 'np.concatenate', (['(north_y, south_y[::-1])'], {}), '((north_y, south_y[::-1]))\n', (10115, 10141), True, 'import numpy as np\n'), ((1539, 1550), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (1547, 1550), True, 'import numpy as np\n'), ((2960, 2970), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (2967, 2970), True, 'import numpy as np\n'), ((3458, 3472), 'numpy.sin', 'np.sin', (['thetas'], {}), '(thetas)\n', (3464, 3472), True, 'import numpy as np\n'), ((3852, 3866), 'numpy.sin', 'np.sin', (['thetas'], {}), '(thetas)\n', (3858, 3866), True, 'import numpy as np\n'), ((4074, 4088), 'numpy.cos', 'np.cos', (['thetas'], {}), '(thetas)\n', (4080, 4088), True, 'import numpy as np\n'), ((4201, 4215), 'numpy.cos', 'np.cos', (['thetas'], {}), '(thetas)\n', (4207, 4215), True, 'import numpy as np\n'), ((7680, 7705), 'numpy.cos', 'np.cos', (['(4 * np.pi * x / L)'], {}), '(4 * np.pi * x / L)\n', (7686, 7705), True, 'import numpy as np\n'), ((9238, 9252), 'numpy.sin', 'np.sin', (['(10 * t)'], {}), '(10 * t)\n', (9244, 9252), True, 'import numpy as np\n'), ((9268, 9281), 'numpy.cos', 'np.cos', (['(5 * t)'], {}), '(5 * t)\n', (9274, 9281), True, 'import numpy as np\n'), ((10173, 10213), 'numpy.concatenate', 'np.concatenate', (['(x[None, :], y[None, :])'], {}), '((x[None, :], y[None, :]))\n', (10187, 10213), True, 'import numpy as np\n'), ((11735, 11748), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (11745, 11748), True, 'import matplotlib.pyplot as plt\n'), ((2635, 2661), 'numpy.sin', 'np.sin', (['(60 * np.pi / 180.0)'], {}), '(60 * np.pi / 180.0)\n', (2641, 2661), True, 'import numpy as np\n'), ((5804, 5814), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (5811, 5814), True, 'import numpy as np\n'), ((2996, 3009), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (3002, 3009), True, 'import numpy as np\n'), ((3011, 3024), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (3017, 3024), True, 'import numpy as np\n'), ((5024, 5042), 'numpy.cos', 'np.cos', (['(2 * thetas)'], {}), '(2 * thetas)\n', (5030, 5042), True, 'import numpy as np\n'), ((5086, 5104), 'numpy.cos', 'np.cos', (['(2 * thetas)'], {}), '(2 * thetas)\n', (5092, 5104), True, 'import numpy as np\n'), ((5625, 5638), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (5631, 5638), True, 'import numpy as np\n'), ((5640, 5653), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (5646, 5653), True, 'import numpy as np\n'), ((4565, 4583), 'numpy.sin', 'np.sin', (['(2 * thetas)'], {}), '(2 * thetas)\n', (4571, 4583), True, 'import numpy as np\n'), ((4634, 4652), 'numpy.sin', 'np.sin', (['(2 * thetas)'], {}), '(2 * thetas)\n', (4640, 4652), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: <NAME>
from collections import defaultdict
import os
import re
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import numpy as np
from pandas import DataFrame
import scipy.stats
import seaborn as sns
import lda_metrics
N_PROPS_LIST = ['None', 0.001, 0.01, 0.1]
N_FREQS_LIST = [1, 2, 4, 8]
N_TOPICS_LIST = [5, 10, 20, 40, 80, 160, 320]
sns.set(style='whitegrid', context='poster')
to_print_name = {
'reusl-train': 'REUSL 25k',
'reusl-short': 'REUSL 2.5k',
'nyt-train': 'NYT 25k',
'nyt-short': 'NYT 2.5k',
}
def validate_fname(
fname,
extension,
file_prefix=None,
process=None,
n_topics=None,
n_props_list=N_PROPS_LIST,
n_freqs_list=N_FREQS_LIST,
n_topics_list=N_TOPICS_LIST):
if not fname.startswith(file_prefix + '-'):
return None
is_seq_file = (extension == 'txt')
is_exact_duplicate = (len(fname.split('-')) == 6 - int(is_seq_file))
if is_exact_duplicate:
if is_seq_file:
fname_regex = r'[a-z\-]+(?P<proc_id>\d+)-(?P<prop>[\d.]+|None)-(?P<freq>\d+).' + extension
else:
fname_regex = r'[a-z\-]+(?P<proc_id>\d+)-(?P<prop>[\d.]+|None)-(?P<freq>\d+)-(?P<topic_ct>\d+).' + extension
else:
if is_seq_file:
fname_regex = r'[a-z\-]+(?P<proc_id>\d+)-(?P<prop>[\d.]+|None).' + extension
else:
fname_regex = r'[a-z\-]+(?P<proc_id>\d+)-(?P<prop>[\d.]+|None)-(?P<topic_ct>\d+).' + extension
match_obj = re.match(fname_regex, fname)
if match_obj is None:
return None
ret_dict = {}
proc_id = int(match_obj.group('proc_id'))
if process is not None and proc_id != process:
return None
else:
ret_dict['proc_id'] = proc_id
prop = match_obj.group('prop')
if prop != 'None':
prop = float(prop)
if prop not in n_props_list:
return None
else:
ret_dict['prop'] = prop
if not is_seq_file:
topic_ct = int(match_obj.group('topic_ct'))
if not (n_topics is None) and topic_ct != n_topics:
return None
elif not (topic_ct in n_topics_list):
return None
else:
ret_dict['topic_ct'] = topic_ct
if is_exact_duplicate:
freq = int(match_obj.group('freq'))
if freq not in n_freqs_list:
return None
else:
ret_dict['freq'] = freq
return ret_dict
def make_entity_from_fields(n_topics, val, label, fields):
return {
'proportion': fields['prop'],
'c': fields.get('freq', 0),
'K': n_topics,
'process_id': fields['proc_id'],
'value': val,
'label': label
}
def print_significances(entities):
val_collection = defaultdict(list)
for entity in entities:
key = "{} {} {} {}".format(
entity['label'],
entity['proportion'],
entity['k'],
entity['c'])
val_collection[key].append(entity['value'])
for key in sorted(val_collection.keys()):
print(key, np.mean(val_collection[key]), 1.96*scipy.stats.sem(val_collection[key]))
def plot_cmap_from_entity_list(entities, save_file, vmax=1.0, value_name="value"):
plt.figure(figsize=(25, 15))
if not entities:
raise ValueError("No entities in list")
dataf = DataFrame([e for e in entities])
g = sns.FacetGrid(
dataf,
col='k',
row='label')
cbar_ax = g.fig.add_axes([.92, .3, .02, .4])
g.map_dataframe(facet_heatmap, cbar_ax=cbar_ax, vmax=vmax)
g.set_titles(col_template="{col_name} topics", row_template="{row_name}")
g.fig.subplots_adjust(right=.9)
plt.savefig(save_file)
def plot_pplot_from_entity_list(entities, save_file, value_name="value"):
plt.figure(figsize=(25, 15))
if not entities:
raise ValueError("No entities in list")
dataf = DataFrame([e for e in entities])
g = sns.factorplot(
x='c',
y='value',
hue='proportion',
col='k',
row='label',
capsize=.2,
markers='.',
scale=0.5,
data=dataf)
g.set_titles(col_template="{col_name} topics", row_template="{row_name}")
g.set_axis_labels("# copies", value_name)
plt.savefig(save_file)
def print_data_table(entities):
dataf = DataFrame([e for e in entities])
data = dataf.pivot_table(index='proportion', columns='c', values='value')
print(data)
def facet_heatmap(data, color, vmax=1.0, **kws):
data = data.pivot_table(index='proportion', columns='c', values='value')
sns.heatmap(data, cmap='Blues', annot=True, fmt=".2f", vmin=0, vmax=vmax, **kws)
|
[
"pandas.DataFrame",
"seaborn.heatmap",
"seaborn.factorplot",
"re.match",
"collections.defaultdict",
"matplotlib.pyplot.figure",
"matplotlib.use",
"numpy.mean",
"seaborn.set",
"seaborn.FacetGrid",
"matplotlib.pyplot.savefig"
] |
[((138, 159), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (152, 159), False, 'import matplotlib\n'), ((426, 470), 'seaborn.set', 'sns.set', ([], {'style': '"""whitegrid"""', 'context': '"""poster"""'}), "(style='whitegrid', context='poster')\n", (433, 470), True, 'import seaborn as sns\n'), ((1573, 1601), 're.match', 're.match', (['fname_regex', 'fname'], {}), '(fname_regex, fname)\n', (1581, 1601), False, 'import re\n'), ((2827, 2844), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2838, 2844), False, 'from collections import defaultdict\n'), ((3317, 3345), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(25, 15)'}), '(figsize=(25, 15))\n', (3327, 3345), True, 'from matplotlib import pyplot as plt\n'), ((3427, 3459), 'pandas.DataFrame', 'DataFrame', (['[e for e in entities]'], {}), '([e for e in entities])\n', (3436, 3459), False, 'from pandas import DataFrame\n'), ((3468, 3510), 'seaborn.FacetGrid', 'sns.FacetGrid', (['dataf'], {'col': '"""k"""', 'row': '"""label"""'}), "(dataf, col='k', row='label')\n", (3481, 3510), True, 'import seaborn as sns\n'), ((3778, 3800), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_file'], {}), '(save_file)\n', (3789, 3800), True, 'from matplotlib import pyplot as plt\n'), ((3881, 3909), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(25, 15)'}), '(figsize=(25, 15))\n', (3891, 3909), True, 'from matplotlib import pyplot as plt\n'), ((3991, 4023), 'pandas.DataFrame', 'DataFrame', (['[e for e in entities]'], {}), '([e for e in entities])\n', (4000, 4023), False, 'from pandas import DataFrame\n'), ((4032, 4157), 'seaborn.factorplot', 'sns.factorplot', ([], {'x': '"""c"""', 'y': '"""value"""', 'hue': '"""proportion"""', 'col': '"""k"""', 'row': '"""label"""', 'capsize': '(0.2)', 'markers': '"""."""', 'scale': '(0.5)', 'data': 'dataf'}), "(x='c', y='value', hue='proportion', col='k', row='label',\n capsize=0.2, markers='.', scale=0.5, data=dataf)\n", (4046, 4157), True, 'import seaborn as sns\n'), ((4390, 4412), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_file'], {}), '(save_file)\n', (4401, 4412), True, 'from matplotlib import pyplot as plt\n'), ((4459, 4491), 'pandas.DataFrame', 'DataFrame', (['[e for e in entities]'], {}), '([e for e in entities])\n', (4468, 4491), False, 'from pandas import DataFrame\n'), ((4718, 4803), 'seaborn.heatmap', 'sns.heatmap', (['data'], {'cmap': '"""Blues"""', 'annot': '(True)', 'fmt': '""".2f"""', 'vmin': '(0)', 'vmax': 'vmax'}), "(data, cmap='Blues', annot=True, fmt='.2f', vmin=0, vmax=vmax, **kws\n )\n", (4729, 4803), True, 'import seaborn as sns\n'), ((3155, 3183), 'numpy.mean', 'np.mean', (['val_collection[key]'], {}), '(val_collection[key])\n', (3162, 3183), True, 'import numpy as np\n')]
|
from flask import Flask
from flask import request, jsonify
import numpy as np
import torch
from flask_cors import CORS, cross_origin
import socket
import argparse
import random
import json
import re
from tokenize_code import tokenize_code
from serverHelpers import notebook_to_frontend
from gensim.models.doc2vec import Doc2Vec
from model import BertModel, Generator
from RetrievalDB_doc2vec import RetrievalDB_doc2vec, inferenceRNN_doc2vec
from RetrievalDB_CodeBERT import RetrievalDB_CodeBERT, inferenceRNN_CodeBERT
# Get the path to the data
PATH_TO_SLICED_SCRIPTS = '../../yizhi/EDA/kaggle-dataset/sliced-notebooks-full-new'
PATH_TO_NOTEBOOKS = '../../yizhi/EDA/kaggle-dataset/notebooks-full'
PATH_TO_CODEBERT_MODELS = '../../yizhi/EDA/EDA-prediction/'
# retrievalDB_doc2vec = RetrievalDB_doc2vec()
retrievalDB_CodeBERT = RetrievalDB_CodeBERT(PATH_TO_CODEBERT_MODELS)
app = Flask(__name__)
CORS(app)
def randomSublists(someList):
resultList = [] #result container
index = 0 #start at the start of the list
length = len(someList) #and cache the length for performance on large lists
while (index < length):
randomNumber = np.random.randint(1, length-index+1) #get a number between 1 and the remaining choices
resultList.append(someList[index:index+randomNumber]) #append a list starting at index with randomNumber length to it
index = index + randomNumber #increment index by amount of list used
return resultList #return the list of randomized sublists
def create_app():
@app.route("/", methods=["GET"])
def index():
return "SmartEDA API Server"
@app.route("/generate_answer", methods=["GET","POST"])
def generate_answer():
#nl_input = request.form['input']
files_to_read = ['2.ipynb', '11111.ipynb', '8570777.ipynb', '9582250.ipynb', '10269993.ipynb']
store = []
for file_name in files_to_read:
file = open("examples/" + file_name)
line = file.read()
file.close()
store.append(line)
json_parsed = []
for file_content in store:
json_parsed.append(json.loads(file_content))
all_ops = []
all_op_type = []
all_if_demon = []
for notebook in json_parsed:
cells = notebook['cells']
operations = []
one_op_type = []
one_if_demon = []
for a_cell in cells:
# a code cell
if a_cell['cell_type'] == 'code':
for a_line in a_cell['source']:
# a line of code
replaced_line = a_line.replace('"', '@').replace("'", '@')
if replaced_line[-1] != '\n':
operations.append(replaced_line + '\n')
else:
operations.append(replaced_line)
one_op_type.append(np.random.randint(4) + 1)
one_if_demon.append(np.random.randint(2))
all_ops.append(operations)
all_op_type.append(one_op_type)
all_if_demon.append(one_if_demon)
all_keywords = []
for j in range(len(all_if_demon)):
one_notebook = all_if_demon[j]
a_keyword = []
length = len(one_notebook)
i = 0
while i < length:
if one_notebook[i] == 0:
i += 1
# skip
else:
start = i
end = start
while i < length:
if one_notebook[i] == 1:
# no worries, just check if it is the end
if i == length - 1:
# 1 all the way to the end.
end = i
else:
# 0, time to stop
i = i - 1
end = i
break
i = i + 1
try:
a_keyword.append(random.choice(re.sub("[^a-zA-Z]+", " ", ' '.join(all_ops[j][start:end+1])).split()))
except:
a_keyword.append('random_stuff')
i += 1
all_keywords.append(a_keyword)
response = jsonify(all_operation_types=all_op_type,
all_operations=all_ops,
all_if_demonstrated=all_if_demon,
all_kwds=all_keywords)
response.headers.add('Access-Control-Allow-Origin', '*')
return response
@app.route("/predict_next", methods=["POST"])
def predict_next():
if request.method == "POST":
print("Inferring next sequence")
# Axios request body is {notebook: stringified json}
# So we need to access the notebook field and parse it with json.loads
notebookSrc = json.loads(request.get_json()['notebook'])
print("notebooksrc json is", notebookSrc)
print("Notebook is", notebookSrc.keys())
# Do inference
topNotebooks = inferenceRNN_CodeBERT(notebookSrc, retrievalDB_CodeBERT, PATH_TO_CODEBERT_MODELS)
notebook_filepaths = []
# Parse the returned results
for (name, seqNum ) in topNotebooks:
# Name format is "competition\filename_seqNum"
competition = name.split('\\')[0]
filename_and_idx = name.split('\\')[1]
filename = filename_and_idx.split('_')[0]
idx = filename_and_idx.split('_')[1]
filepath = PATH_TO_NOTEBOOKS + '/' + competition + '/' + filename + '.ipynb'
notebook_filepaths.append(filepath)
data_to_frontend = notebook_to_frontend(notebook_filepaths)
response_formatted = jsonify(all_operation_types=data_to_frontend[0],
all_operations=data_to_frontend[1],
all_if_demonstrated=data_to_frontend[2],
all_kwds=data_to_frontend[3])
# Prevent CORS error
response_formatted.headers.add('Access-Control-Allow-Origin', '*')
return response_formatted
# POST /predict_next_doc2vec
@app.route("/predict_next_doc2vec", methods=["POST"])
def predict_next_doc2vec():
if request.method == "POST":
print("Inferring next sequence")
# Axios request body is {notebook: stringified json}
# So we need to access the notebook field and parse it with json.loads
notebookSrc = json.loads(request.get_json()['notebook'])
print("notebooksrc json is", notebookSrc)
print("Notebook is", notebookSrc.keys())
# Do inference
topNotebooks = inferenceRNN_doc2vec(notebookSrc, retrievalDB_doc2vec)
notebook_filepaths = []
# Parse the returned results
for (name, seqNum ) in topNotebooks:
# Name format is "competition\filename_seqNum"
competition = name.split('\\')[0]
filename_and_idx = name.split('\\')[1]
filename = filename_and_idx.split('_')[0]
idx = filename_and_idx.split('_')[1]
filepath = PATH_TO_NOTEBOOKS + '/' + competition + '/' + filename + '.ipynb'
notebook_filepaths.append(filepath)
print("notebooks filepaths is", notebook_filepaths)
response = jsonify(topNotebooks)
data_to_frontend = notebook_to_frontend(notebook_filepaths)
response_formatted = jsonify(all_operation_types=data_to_frontend[0],
all_operations=data_to_frontend[1],
all_if_demonstrated=data_to_frontend[2],
all_kwds=data_to_frontend[3])
# Prevent CORS error
response_formatted.headers.add('Access-Control-Allow-Origin', '*')
return response_formatted
@app.route("/search_by_nl", methods=["POST"])
def search_by_nl():
if request.method == "POST":
return jsonify(hello="world search by nl")
return app
def main(args):
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
print("hostname is", hostname)
print("local ip is", local_ip)
app = create_app()
app.run(host=args.host, debug=True, port=args.port)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="")
parser.add_argument(
"--beam_size", default=10, type=int, help="beam size for beam search"
)
parser.add_argument("--no_cuda", action='store_true', help="Avoid using CUDA when available")
parser.add_argument("--host", type=str, default="0.0.0.0")
parser.add_argument("--port", type=int, default=5000)
args = parser.parse_args()
args.device_name = "cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu"
args.device = torch.device(args.device_name)
args.beam_size = (args.beam_size if torch.cuda.is_available() and not args.no_cuda else 1)
main(args)
|
[
"argparse.ArgumentParser",
"json.loads",
"flask_cors.CORS",
"flask.Flask",
"RetrievalDB_doc2vec.inferenceRNN_doc2vec",
"socket.gethostbyname",
"RetrievalDB_CodeBERT.RetrievalDB_CodeBERT",
"socket.gethostname",
"numpy.random.randint",
"flask.jsonify",
"RetrievalDB_CodeBERT.inferenceRNN_CodeBERT",
"torch.cuda.is_available",
"torch.device",
"serverHelpers.notebook_to_frontend",
"flask.request.get_json"
] |
[((835, 880), 'RetrievalDB_CodeBERT.RetrievalDB_CodeBERT', 'RetrievalDB_CodeBERT', (['PATH_TO_CODEBERT_MODELS'], {}), '(PATH_TO_CODEBERT_MODELS)\n', (855, 880), False, 'from RetrievalDB_CodeBERT import RetrievalDB_CodeBERT, inferenceRNN_CodeBERT\n'), ((887, 902), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (892, 902), False, 'from flask import Flask\n'), ((903, 912), 'flask_cors.CORS', 'CORS', (['app'], {}), '(app)\n', (907, 912), False, 'from flask_cors import CORS, cross_origin\n'), ((8501, 8521), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (8519, 8521), False, 'import socket\n'), ((8537, 8567), 'socket.gethostbyname', 'socket.gethostbyname', (['hostname'], {}), '(hostname)\n', (8557, 8567), False, 'import socket\n'), ((8758, 8797), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '""""""'}), "(description='')\n", (8781, 8797), False, 'import argparse\n'), ((9270, 9300), 'torch.device', 'torch.device', (['args.device_name'], {}), '(args.device_name)\n', (9282, 9300), False, 'import torch\n'), ((1160, 1200), 'numpy.random.randint', 'np.random.randint', (['(1)', '(length - index + 1)'], {}), '(1, length - index + 1)\n', (1177, 1200), True, 'import numpy as np\n'), ((4434, 4559), 'flask.jsonify', 'jsonify', ([], {'all_operation_types': 'all_op_type', 'all_operations': 'all_ops', 'all_if_demonstrated': 'all_if_demon', 'all_kwds': 'all_keywords'}), '(all_operation_types=all_op_type, all_operations=all_ops,\n all_if_demonstrated=all_if_demon, all_kwds=all_keywords)\n', (4441, 4559), False, 'from flask import request, jsonify\n'), ((5243, 5328), 'RetrievalDB_CodeBERT.inferenceRNN_CodeBERT', 'inferenceRNN_CodeBERT', (['notebookSrc', 'retrievalDB_CodeBERT', 'PATH_TO_CODEBERT_MODELS'], {}), '(notebookSrc, retrievalDB_CodeBERT,\n PATH_TO_CODEBERT_MODELS)\n', (5264, 5328), False, 'from RetrievalDB_CodeBERT import RetrievalDB_CodeBERT, inferenceRNN_CodeBERT\n'), ((5916, 5956), 'serverHelpers.notebook_to_frontend', 'notebook_to_frontend', (['notebook_filepaths'], {}), '(notebook_filepaths)\n', (5936, 5956), False, 'from serverHelpers import notebook_to_frontend\n'), ((5991, 6156), 'flask.jsonify', 'jsonify', ([], {'all_operation_types': 'data_to_frontend[0]', 'all_operations': 'data_to_frontend[1]', 'all_if_demonstrated': 'data_to_frontend[2]', 'all_kwds': 'data_to_frontend[3]'}), '(all_operation_types=data_to_frontend[0], all_operations=\n data_to_frontend[1], all_if_demonstrated=data_to_frontend[2], all_kwds=\n data_to_frontend[3])\n', (5998, 6156), False, 'from flask import request, jsonify\n'), ((7017, 7071), 'RetrievalDB_doc2vec.inferenceRNN_doc2vec', 'inferenceRNN_doc2vec', (['notebookSrc', 'retrievalDB_doc2vec'], {}), '(notebookSrc, retrievalDB_doc2vec)\n', (7037, 7071), False, 'from RetrievalDB_doc2vec import RetrievalDB_doc2vec, inferenceRNN_doc2vec\n'), ((7719, 7740), 'flask.jsonify', 'jsonify', (['topNotebooks'], {}), '(topNotebooks)\n', (7726, 7740), False, 'from flask import request, jsonify\n'), ((7773, 7813), 'serverHelpers.notebook_to_frontend', 'notebook_to_frontend', (['notebook_filepaths'], {}), '(notebook_filepaths)\n', (7793, 7813), False, 'from serverHelpers import notebook_to_frontend\n'), ((7848, 8013), 'flask.jsonify', 'jsonify', ([], {'all_operation_types': 'data_to_frontend[0]', 'all_operations': 'data_to_frontend[1]', 'all_if_demonstrated': 'data_to_frontend[2]', 'all_kwds': 'data_to_frontend[3]'}), '(all_operation_types=data_to_frontend[0], all_operations=\n data_to_frontend[1], all_if_demonstrated=data_to_frontend[2], all_kwds=\n data_to_frontend[3])\n', (7855, 8013), False, 'from flask import request, jsonify\n'), ((8418, 8453), 'flask.jsonify', 'jsonify', ([], {'hello': '"""world search by nl"""'}), "(hello='world search by nl')\n", (8425, 8453), False, 'from flask import request, jsonify\n'), ((9194, 9219), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (9217, 9219), False, 'import torch\n'), ((9341, 9366), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (9364, 9366), False, 'import torch\n'), ((2147, 2171), 'json.loads', 'json.loads', (['file_content'], {}), '(file_content)\n', (2157, 2171), False, 'import json\n'), ((5048, 5066), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (5064, 5066), False, 'from flask import request, jsonify\n'), ((6822, 6840), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (6838, 6840), False, 'from flask import request, jsonify\n'), ((3025, 3045), 'numpy.random.randint', 'np.random.randint', (['(2)'], {}), '(2)\n', (3042, 3045), True, 'import numpy as np\n'), ((2955, 2975), 'numpy.random.randint', 'np.random.randint', (['(4)'], {}), '(4)\n', (2972, 2975), True, 'import numpy as np\n')]
|
import pysmurf
#S = pysmurf.SmurfControl(make_logfile=False,setup=False,epics_root='test_epics',cfg_file='/usr/local/controls/Applications/smurf/pysmurf/pysmurf/cfg_files/experiment_fp28_smurfsrv04.cfg')
import numpy as np
import time
Vrange=np.linspace(0,0.195/6.,100)+S.get_tes_bias_bipolar(3)
Vrange=[Vrange,Vrange[::-1]]
Vrange=np.array(Vrange).flatten()
while True:
for Vtes in Vrange:
S.set_tes_bias_bipolar(7,Vtes)
time.sleep(0.005)
|
[
"numpy.array",
"numpy.linspace",
"time.sleep"
] |
[((246, 278), 'numpy.linspace', 'np.linspace', (['(0)', '(0.195 / 6.0)', '(100)'], {}), '(0, 0.195 / 6.0, 100)\n', (257, 278), True, 'import numpy as np\n'), ((336, 352), 'numpy.array', 'np.array', (['Vrange'], {}), '(Vrange)\n', (344, 352), True, 'import numpy as np\n'), ((447, 464), 'time.sleep', 'time.sleep', (['(0.005)'], {}), '(0.005)\n', (457, 464), False, 'import time\n')]
|
# Reference Book: Python Data Science Handbook (page:(70-77))
# Date(13 April, 2019) Day-3, Time = 3:25 PM
# This section covers the use of Boolean masks to examine and manipulate values
# within NumPy arrays.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn; seaborn.set() #set plot style
# use Pandas to extract rainfall inches as a NumPy array
rainfall = pd.read_csv('/media/nahid/New Volume/GitHub/Numpy/Seattle2014.csv')['PRCP'].values
# print(rainfall)
inches = rainfall / 254 #1/10mm -> inches
print(inches.shape) #(365,)
# fig = plt.figure()
# plt.hist(inches, 40)
# print(plt.show())
# fig.savefig('rainfallHistogram.png')
'''
This histogram gives us a general idea of what the data looks like: despite its reputa‐
tion, the vast majority of days in Seattle saw near zero measured rainfall in 2014. But
this doesn’t do a good job of conveying some information we’d like to see: for exam‐
ple, how many rainy days were there in the year? What is the average precipitation on
those rainy days? How many days were there with more than half an inch of rain?
Digging into the data
One approach to this would be to answer these questions by hand: loop through the
data, incrementing a counter each time we see values in some desired range. For rea‐
sons discussed throughout this chapter, such an approach is very inefficient, both
from the standpoint of time writing code and time computing the result. We saw in
“Computation on NumPy Arrays: Universal Functions” on page 50 that NumPy’s
ufuncs can be used in place of loops to do fast element-wise arithmetic operations on
arrays; in the same way, we can use other ufuncs to do element-wise comparisons over
arrays, and we can then manipulate the results to answer the questions we have. We’ll
leave the data aside for right now, and discuss some general tools in NumPy to use
masking to quickly answer these types of questions.
'''
a = np.array([1,2,3,4,5])
print(a < 3) # [ True True False False False]
# check this apply all of others relational operator
# like
print(a != 3) # [ True True False True True]
# It is also possible to do an element-by-element comparison of two arrays, and to
# include compound expressions:
print((2 * a) == (a ** 2)) # [False True False False False]
'''
As in the case of arithmetic operators, the comparison operators are implemented as
ufuncs in NumPy; for example, when you write x < 3 , internally NumPy uses
np.less(x, 3) . A summary of the comparison operators and their equivalent ufunc
is shown here:
Operator Equivalent ufunc
== np.equal
!= np.not_equal
< np.less
<= np.less_equal
> np.greater
>= np.greater_equal
'''
# Just as in the case of arithmetic ufuncs, these will work on arrays of any size and
# shape. Here is a two-dimensional example:
rng = np.random.RandomState(0)
x = rng.randint(10, size=(3,4))
print(x)
print(x < 5)
'''
[[5 0 3 3]
[7 9 3 5]
[2 4 7 6]]
[[False True True True]
[False False True False]
[ True True False False]]
'''
print(np.count_nonzero(x < 6)) # 8
print(np.sum(x < 6)) # 8
# how many values less than 6 in each row?
print(np.sum(x < 6, axis=1)) # [4 2 2]
# If we’re interested in quickly checking whether any or all the values are true, we can
# use(you guessed it) np.any() or np.all():
print(np.any(x < 8)) #True
print(np.any(x < 0)) #False
print(np.all(x < 10)) #True
print(np.all(x == 6)) # False
# np.all() and np.any() can be used along particular axes as well. For example:
print(np.all(x < 8, axis=1)) # [ True False True]
# Here all the elements in the first and third rows are less than 8, while this is not the
# case for the second row.
#Boolean operators
print(np.sum((inches > .5) & (inches < 1))) # 29
#So we see that there are 29 days with rainfall between 0.5 and 1.0 inches.
#Using the equivalence of A AND B and NOT (A OR B)
print(np.sum(~((inches <= 0.5) | (inches >= 1)))) # 29
'''
The following table summarizes the bitwise Boolean operators and their equivalent
ufuncs:
Operator Equivalent ufunc
& np.bitwise_and
| np.bitwise_or
^ np.bitwise_xor
~ np.bitwise_not
'''
print('Number of days without rain :',np.sum(inches == 0))
print('Number of days with rain :',np.sum(inches != 0))
print('Days with more than .5 inches :',np.sum(inches > 0.5))
'''
Number of days without rain : 215
Number of days with rain : 150
Days with more than .5 inches : 37
'''
print(x[x < 5]) # [0 3 3 3 2 4]
# construct a mask of all rainy days
rainy = (inches > 0)
# construct a mask of all summer days (June 21st is the 172nd day)
summer = (np.arange(365) - 172 < 90) & (np.arange(365) - 172 > 0)
print("Median precip on rainy days in 2014 (inches):", np.median(inches[rainy]))
print("Median precip on summer days in 2014 (inches): ",
np.median(inches[summer]))
print("Maximum precip on summer days in 2014 (inches): ",
np.max(inches[summer]))
print("Median precip on non-summer rainy days (inches):",
np.median(inches[rainy & ~summer]))
#Using the Keywords and/or Versus the Operators &/|
print(bool(42), bool(0)) #True False
print(bool(42 and 0)) #False
print(bool(42 or 0)) #True
print(bin(42)) # 0b101010
print(bin(59)) # 0b111011
print(bin(42 | 59)) # 0b111011
a = np.array([1, 0, 1, 0, 1, 0], dtype=bool)
b = np.array([1, 1, 1, 0, 1, 1], dtype=bool)
print(a | b) # [ True True True False True True]
#ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
# print( a or b)
|
[
"numpy.count_nonzero",
"numpy.sum",
"numpy.median",
"pandas.read_csv",
"numpy.random.RandomState",
"numpy.any",
"numpy.max",
"numpy.array",
"numpy.arange",
"seaborn.set",
"numpy.all"
] |
[((302, 315), 'seaborn.set', 'seaborn.set', ([], {}), '()\n', (313, 315), False, 'import seaborn\n'), ((1941, 1966), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5]'], {}), '([1, 2, 3, 4, 5])\n', (1949, 1966), True, 'import numpy as np\n'), ((2867, 2891), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (2888, 2891), True, 'import numpy as np\n'), ((5349, 5389), 'numpy.array', 'np.array', (['[1, 0, 1, 0, 1, 0]'], {'dtype': 'bool'}), '([1, 0, 1, 0, 1, 0], dtype=bool)\n', (5357, 5389), True, 'import numpy as np\n'), ((5394, 5434), 'numpy.array', 'np.array', (['[1, 1, 1, 0, 1, 1]'], {'dtype': 'bool'}), '([1, 1, 1, 0, 1, 1], dtype=bool)\n', (5402, 5434), True, 'import numpy as np\n'), ((3076, 3099), 'numpy.count_nonzero', 'np.count_nonzero', (['(x < 6)'], {}), '(x < 6)\n', (3092, 3099), True, 'import numpy as np\n'), ((3111, 3124), 'numpy.sum', 'np.sum', (['(x < 6)'], {}), '(x < 6)\n', (3117, 3124), True, 'import numpy as np\n'), ((3180, 3201), 'numpy.sum', 'np.sum', (['(x < 6)'], {'axis': '(1)'}), '(x < 6, axis=1)\n', (3186, 3201), True, 'import numpy as np\n'), ((3355, 3368), 'numpy.any', 'np.any', (['(x < 8)'], {}), '(x < 8)\n', (3361, 3368), True, 'import numpy as np\n'), ((3383, 3396), 'numpy.any', 'np.any', (['(x < 0)'], {}), '(x < 0)\n', (3389, 3396), True, 'import numpy as np\n'), ((3412, 3426), 'numpy.all', 'np.all', (['(x < 10)'], {}), '(x < 10)\n', (3418, 3426), True, 'import numpy as np\n'), ((3440, 3454), 'numpy.all', 'np.all', (['(x == 6)'], {}), '(x == 6)\n', (3446, 3454), True, 'import numpy as np\n'), ((3551, 3572), 'numpy.all', 'np.all', (['(x < 8)'], {'axis': '(1)'}), '(x < 8, axis=1)\n', (3557, 3572), True, 'import numpy as np\n'), ((3742, 3779), 'numpy.sum', 'np.sum', (['((inches > 0.5) & (inches < 1))'], {}), '((inches > 0.5) & (inches < 1))\n', (3748, 3779), True, 'import numpy as np\n'), ((3920, 3962), 'numpy.sum', 'np.sum', (['(~((inches <= 0.5) | (inches >= 1)))'], {}), '(~((inches <= 0.5) | (inches >= 1)))\n', (3926, 3962), True, 'import numpy as np\n'), ((4244, 4263), 'numpy.sum', 'np.sum', (['(inches == 0)'], {}), '(inches == 0)\n', (4250, 4263), True, 'import numpy as np\n'), ((4310, 4329), 'numpy.sum', 'np.sum', (['(inches != 0)'], {}), '(inches != 0)\n', (4316, 4329), True, 'import numpy as np\n'), ((4376, 4396), 'numpy.sum', 'np.sum', (['(inches > 0.5)'], {}), '(inches > 0.5)\n', (4382, 4396), True, 'import numpy as np\n'), ((4808, 4832), 'numpy.median', 'np.median', (['inches[rainy]'], {}), '(inches[rainy])\n', (4817, 4832), True, 'import numpy as np\n'), ((4897, 4922), 'numpy.median', 'np.median', (['inches[summer]'], {}), '(inches[summer])\n', (4906, 4922), True, 'import numpy as np\n'), ((4988, 5010), 'numpy.max', 'np.max', (['inches[summer]'], {}), '(inches[summer])\n', (4994, 5010), True, 'import numpy as np\n'), ((5076, 5110), 'numpy.median', 'np.median', (['inches[rainy & ~summer]'], {}), '(inches[rainy & ~summer])\n', (5085, 5110), True, 'import numpy as np\n'), ((401, 468), 'pandas.read_csv', 'pd.read_csv', (['"""/media/nahid/New Volume/GitHub/Numpy/Seattle2014.csv"""'], {}), "('/media/nahid/New Volume/GitHub/Numpy/Seattle2014.csv')\n", (412, 468), True, 'import pandas as pd\n'), ((4697, 4711), 'numpy.arange', 'np.arange', (['(365)'], {}), '(365)\n', (4706, 4711), True, 'import numpy as np\n'), ((4727, 4741), 'numpy.arange', 'np.arange', (['(365)'], {}), '(365)\n', (4736, 4741), True, 'import numpy as np\n')]
|
from numpy.testing._private.utils import assert_allclose
from sysidentpy.polynomial_basis import PolynomialNarmax
from sysidentpy.utils.generate_data import get_miso_data, get_siso_data
import numpy as np
from numpy.testing import assert_almost_equal, assert_array_equal
from numpy.testing import assert_raises
from sysidentpy.polynomial_basis import SimulatePolynomialNarmax
def test_get_index_from_regressor_code():
s = SimulatePolynomialNarmax()
model = np.array(
[
[1001, 0], # y(k-1)
[2001, 1001], # x1(k-1)y(k-1)
[2002, 0], # x1(k-2)
]
)
regressor_space = np.array(
[
[0, 0],
[1001, 0],
[2001, 0],
[2002, 0],
[1001, 1001],
[2001, 1001],
[2002, 1001],
[2001, 2001],
[2002, 2001],
[2002, 2002],
]
)
index = s._get_index_from_regressor_code(
regressor_code=regressor_space, model_code=model
)
assert (index == np.array([1, 3, 5])).all()
def test_list_output_regressor():
s = SimulatePolynomialNarmax()
model = np.array(
[
[1001, 0], # y(k-1)
[2001, 1001], # x1(k-1)y(k-1)
[2002, 0], # x1(k-2)
]
)
y_code = s._list_output_regressor_code(model)
assert (y_code == np.array([1001, 1001])).all()
def test_list_input_regressor():
s = SimulatePolynomialNarmax()
model = np.array(
[
[1001, 0], # y(k-1)
[2001, 1001], # x1(k-1)y(k-1)
[2002, 0], # x1(k-2)
]
)
x_code = s._list_input_regressor_code(model)
assert (x_code == np.array([2001, 2002])).all()
def test_get_lag_from_regressor_code():
s = SimulatePolynomialNarmax()
list_regressor1 = np.array([2001, 2002])
list_regressor2 = np.array([1004, 1002])
max_lag1 = s._get_lag_from_regressor_code(list_regressor1)
max_lag2 = s._get_lag_from_regressor_code(list_regressor2)
assert max_lag1 == 2
assert max_lag2 == 4
def test_simulate():
x_train, x_valid, y_train, y_valid = get_siso_data(
n=1000, colored_noise=False, sigma=0.001, train_percentage=90
)
s = SimulatePolynomialNarmax()
# the model must be a numpy array
model = np.array(
[
[1001, 0], # y(k-1)
[2001, 1001], # x1(k-1)y(k-1)
[2002, 0], # x1(k-2)
]
)
# theta must be a numpy array of shape (n, 1) where n is the number of regressors
theta = np.array([[0.2, 0.9, 0.1]]).T
yhat, results = s.simulate(
X_test=x_valid, y_test=y_valid, model_code=model, theta=theta, plot=False
)
assert yhat.shape == (100, 1)
assert len(results) == 3
def test_simulate_theta():
x_train, x_valid, y_train, y_valid = get_siso_data(
n=1000, colored_noise=False, sigma=0.001, train_percentage=90
)
s = SimulatePolynomialNarmax(estimate_parameter=True)
# the model must be a numpy array
model = np.array(
[
[1001, 0], # y(k-1)
[2001, 1001], # x1(k-1)y(k-1)
[2002, 0], # x1(k-2)
]
)
yhat, results = s.simulate(
X_train=x_train,
y_train=y_train,
X_test=x_valid,
y_test=y_valid,
model_code=model,
plot=False,
)
theta = np.array([[0.2, 0.9, 0.1]]).T
assert_almost_equal(s.theta, theta, decimal=1)
def test_estimate_parameter():
assert_raises(TypeError, SimulatePolynomialNarmax, estimmate_parameter=1)
|
[
"numpy.testing.assert_raises",
"numpy.testing.assert_almost_equal",
"sysidentpy.polynomial_basis.SimulatePolynomialNarmax",
"numpy.array",
"sysidentpy.utils.generate_data.get_siso_data"
] |
[((428, 454), 'sysidentpy.polynomial_basis.SimulatePolynomialNarmax', 'SimulatePolynomialNarmax', ([], {}), '()\n', (452, 454), False, 'from sysidentpy.polynomial_basis import SimulatePolynomialNarmax\n'), ((467, 513), 'numpy.array', 'np.array', (['[[1001, 0], [2001, 1001], [2002, 0]]'], {}), '([[1001, 0], [2001, 1001], [2002, 0]])\n', (475, 513), True, 'import numpy as np\n'), ((636, 776), 'numpy.array', 'np.array', (['[[0, 0], [1001, 0], [2001, 0], [2002, 0], [1001, 1001], [2001, 1001], [2002,\n 1001], [2001, 2001], [2002, 2001], [2002, 2002]]'], {}), '([[0, 0], [1001, 0], [2001, 0], [2002, 0], [1001, 1001], [2001, \n 1001], [2002, 1001], [2001, 2001], [2002, 2001], [2002, 2002]])\n', (644, 776), True, 'import numpy as np\n'), ((1119, 1145), 'sysidentpy.polynomial_basis.SimulatePolynomialNarmax', 'SimulatePolynomialNarmax', ([], {}), '()\n', (1143, 1145), False, 'from sysidentpy.polynomial_basis import SimulatePolynomialNarmax\n'), ((1158, 1204), 'numpy.array', 'np.array', (['[[1001, 0], [2001, 1001], [2002, 0]]'], {}), '([[1001, 0], [2001, 1001], [2002, 0]])\n', (1166, 1204), True, 'import numpy as np\n'), ((1450, 1476), 'sysidentpy.polynomial_basis.SimulatePolynomialNarmax', 'SimulatePolynomialNarmax', ([], {}), '()\n', (1474, 1476), False, 'from sysidentpy.polynomial_basis import SimulatePolynomialNarmax\n'), ((1489, 1535), 'numpy.array', 'np.array', (['[[1001, 0], [2001, 1001], [2002, 0]]'], {}), '([[1001, 0], [2001, 1001], [2002, 0]])\n', (1497, 1535), True, 'import numpy as np\n'), ((1787, 1813), 'sysidentpy.polynomial_basis.SimulatePolynomialNarmax', 'SimulatePolynomialNarmax', ([], {}), '()\n', (1811, 1813), False, 'from sysidentpy.polynomial_basis import SimulatePolynomialNarmax\n'), ((1836, 1858), 'numpy.array', 'np.array', (['[2001, 2002]'], {}), '([2001, 2002])\n', (1844, 1858), True, 'import numpy as np\n'), ((1881, 1903), 'numpy.array', 'np.array', (['[1004, 1002]'], {}), '([1004, 1002])\n', (1889, 1903), True, 'import numpy as np\n'), ((2145, 2221), 'sysidentpy.utils.generate_data.get_siso_data', 'get_siso_data', ([], {'n': '(1000)', 'colored_noise': '(False)', 'sigma': '(0.001)', 'train_percentage': '(90)'}), '(n=1000, colored_noise=False, sigma=0.001, train_percentage=90)\n', (2158, 2221), False, 'from sysidentpy.utils.generate_data import get_miso_data, get_siso_data\n'), ((2245, 2271), 'sysidentpy.polynomial_basis.SimulatePolynomialNarmax', 'SimulatePolynomialNarmax', ([], {}), '()\n', (2269, 2271), False, 'from sysidentpy.polynomial_basis import SimulatePolynomialNarmax\n'), ((2323, 2369), 'numpy.array', 'np.array', (['[[1001, 0], [2001, 1001], [2002, 0]]'], {}), '([[1001, 0], [2001, 1001], [2002, 0]])\n', (2331, 2369), True, 'import numpy as np\n'), ((2851, 2927), 'sysidentpy.utils.generate_data.get_siso_data', 'get_siso_data', ([], {'n': '(1000)', 'colored_noise': '(False)', 'sigma': '(0.001)', 'train_percentage': '(90)'}), '(n=1000, colored_noise=False, sigma=0.001, train_percentage=90)\n', (2864, 2927), False, 'from sysidentpy.utils.generate_data import get_miso_data, get_siso_data\n'), ((2951, 3000), 'sysidentpy.polynomial_basis.SimulatePolynomialNarmax', 'SimulatePolynomialNarmax', ([], {'estimate_parameter': '(True)'}), '(estimate_parameter=True)\n', (2975, 3000), False, 'from sysidentpy.polynomial_basis import SimulatePolynomialNarmax\n'), ((3052, 3098), 'numpy.array', 'np.array', (['[[1001, 0], [2001, 1001], [2002, 0]]'], {}), '([[1001, 0], [2001, 1001], [2002, 0]])\n', (3060, 3098), True, 'import numpy as np\n'), ((3427, 3473), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['s.theta', 'theta'], {'decimal': '(1)'}), '(s.theta, theta, decimal=1)\n', (3446, 3473), False, 'from numpy.testing import assert_almost_equal, assert_array_equal\n'), ((3511, 3584), 'numpy.testing.assert_raises', 'assert_raises', (['TypeError', 'SimulatePolynomialNarmax'], {'estimmate_parameter': '(1)'}), '(TypeError, SimulatePolynomialNarmax, estimmate_parameter=1)\n', (3524, 3584), False, 'from numpy.testing import assert_raises\n'), ((2567, 2594), 'numpy.array', 'np.array', (['[[0.2, 0.9, 0.1]]'], {}), '([[0.2, 0.9, 0.1]])\n', (2575, 2594), True, 'import numpy as np\n'), ((3393, 3420), 'numpy.array', 'np.array', (['[[0.2, 0.9, 0.1]]'], {}), '([[0.2, 0.9, 0.1]])\n', (3401, 3420), True, 'import numpy as np\n'), ((1048, 1067), 'numpy.array', 'np.array', (['[1, 3, 5]'], {}), '([1, 3, 5])\n', (1056, 1067), True, 'import numpy as np\n'), ((1377, 1399), 'numpy.array', 'np.array', (['[1001, 1001]'], {}), '([1001, 1001])\n', (1385, 1399), True, 'import numpy as np\n'), ((1707, 1729), 'numpy.array', 'np.array', (['[2001, 2002]'], {}), '([2001, 2002])\n', (1715, 1729), True, 'import numpy as np\n')]
|
"""
Unit and regression test for the tau_screened_coulomb method.
"""
from ThermoElectric import tau_screened_coulomb
import numpy as np
from pytest import approx
def test_tau_screened_coulomb():
energy = np.array([[0.1]])
e_eff_mass = np.array([[0.23 * 9.109e-31]])
dielectric = 11.7
imp = np.array([[1e23]])
screen_len = np.array([[1e-7]])
expected_tau = 1.8e-10
calculated_tau = tau_screened_coulomb(energy=energy, mass_c=e_eff_mass,
n_imp=imp, dielectric=dielectric, screen_len = screen_len)
assert approx(expected_tau, abs=1e-11) == calculated_tau
|
[
"pytest.approx",
"numpy.array",
"ThermoElectric.tau_screened_coulomb"
] |
[((213, 230), 'numpy.array', 'np.array', (['[[0.1]]'], {}), '([[0.1]])\n', (221, 230), True, 'import numpy as np\n'), ((248, 278), 'numpy.array', 'np.array', (['[[0.23 * 9.109e-31]]'], {}), '([[0.23 * 9.109e-31]])\n', (256, 278), True, 'import numpy as np\n'), ((311, 330), 'numpy.array', 'np.array', (['[[1e+23]]'], {}), '([[1e+23]])\n', (319, 330), True, 'import numpy as np\n'), ((347, 366), 'numpy.array', 'np.array', (['[[1e-07]]'], {}), '([[1e-07]])\n', (355, 366), True, 'import numpy as np\n'), ((415, 530), 'ThermoElectric.tau_screened_coulomb', 'tau_screened_coulomb', ([], {'energy': 'energy', 'mass_c': 'e_eff_mass', 'n_imp': 'imp', 'dielectric': 'dielectric', 'screen_len': 'screen_len'}), '(energy=energy, mass_c=e_eff_mass, n_imp=imp,\n dielectric=dielectric, screen_len=screen_len)\n', (435, 530), False, 'from ThermoElectric import tau_screened_coulomb\n'), ((583, 614), 'pytest.approx', 'approx', (['expected_tau'], {'abs': '(1e-11)'}), '(expected_tau, abs=1e-11)\n', (589, 614), False, 'from pytest import approx\n')]
|
# - * - coding: utf-8 - * -
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches
def ecg_fixpeaks(rpeaks, sampling_rate=1000, iterative=True, show=False):
"""Correct R-peaks location based on their interval (RRi).
Identify erroneous inter-beat-intervals. Lipponen & Tarvainen (2019).
Parameters
----------
rpeaks : dict
The samples at which the R-peak occur. Dict returned by
`ecg_findpeaks()`.
sampling_rate : int
The sampling frequency of the signal that contains the peaks (in Hz,
i.e., samples/second).
iterative : bool
Whether or not to apply the artifact correction repeatedly (results
in superior artifact correction).
show : bool
Whether or not to visualize artifacts and artifact thresholds.
Returns
-------
artifacts : dict
A dictionary containing the indices of artifacts, accessible with the
keys "ectopic", "missed", "extra", and "longshort".
See Also
--------
ecg_clean, ecg_findpeaks, ecg_peaks, ecg_rate, ecg_process, ecg_plot
Examples
--------
>>> import neurokit2 as nk
>>> import matplotlib.pyplot as plt
>>> ecg = nk.ecg_simulate(duration=240, noise=0.1, heart_rate=70,
>>> random_state=41)
>>> rpeaks_uncorrected = nk.ecg_findpeaks(ecg)
>>> artifacts, rpeaks_corrected = nk.ecg_fixpeaks(rpeaks_uncorrected,
>>> iterative=True,
>>> show=True)
>>> rate_corrected = nk.ecg_rate(rpeaks_uncorrected,
>>> desired_length=len(ecg))
>>> rate_uncorrected = nk.ecg_rate(rpeaks, desired_length=len(ecg_signal))
>>>
>>> fig, ax = plt.subplots()
>>> ax.plot(rate_uncorrected, label="heart rate without artifact correction")
>>> ax.plot(rate_corrected, label="heart rate with artifact correction")
>>> ax.legend(loc="upper right")
References
----------
- <NAME>., & <NAME>. (2019). A robust algorithm for heart
rate variability time series artefact correction using novel beat
classification. Journal of medical engineering & technology, 43(3),
173-181. 10.1080/03091902.2019.1640306
"""
# Format input.
rpeaks = rpeaks["ECG_R_Peaks"]
# Get corrected peaks and normal-to-normal intervals.
artifacts, subspaces = _find_artifacts(rpeaks, sampling_rate=sampling_rate)
peaks_clean = _correct_artifacts(artifacts, rpeaks)
if iterative:
# Iteratively apply the artifact correction until the number of artifact
# reaches an equilibrium (i.e., the number of artifacts does not change
# anymore from one iteration to the next).
n_artifacts_previous = np.inf
n_artifacts_current = sum([len(i) for i in artifacts.values()])
previous_diff = 0
while n_artifacts_current - n_artifacts_previous != previous_diff:
previous_diff = n_artifacts_previous - n_artifacts_current
artifacts, subspaces = _find_artifacts(peaks_clean,
sampling_rate=sampling_rate)
peaks_clean = _correct_artifacts(artifacts, peaks_clean)
n_artifacts_previous = n_artifacts_current
n_artifacts_current = sum([len(i) for i in artifacts.values()])
if show:
_plot_artifacts_lipponen2019(artifacts, subspaces)
return artifacts, {"ECG_R_Peaks": peaks_clean}
# =============================================================================
# Lipponen & Tarvainen (2019).
# =============================================================================
def _find_artifacts(rpeaks, c1=0.13, c2=0.17, alpha=5.2, window_width=91,
medfilt_order=11, sampling_rate=1000):
peaks = np.ravel(rpeaks)
# Compute period series (make sure it has same numer of elements as peaks);
# peaks are in samples, convert to seconds.
rr = np.ediff1d(peaks, to_begin=0) / sampling_rate
# For subsequent analysis it is important that the first element has
# a value in a realistic range (e.g., for median filtering).
rr[0] = np.mean(rr[1:])
# Artifact identification #################################################
###########################################################################
# Compute dRRs: time series of differences of consecutive periods (dRRs).
drrs = np.ediff1d(rr, to_begin=0)
drrs[0] = np.mean(drrs[1:])
# Normalize by threshold.
th1 = _compute_threshold(drrs, alpha, window_width)
drrs /= th1
# Cast dRRs to subspace s12.
# Pad drrs with one element.
padding = 2
drrs_pad = np.pad(drrs, padding, "reflect")
s12 = np.zeros(drrs.size)
for d in np.arange(padding, padding + drrs.size):
if drrs_pad[d] > 0:
s12[d - padding] = np.max([drrs_pad[d - 1], drrs_pad[d + 1]])
elif drrs_pad[d] < 0:
s12[d - padding] = np.min([drrs_pad[d - 1], drrs_pad[d + 1]])
# Cast dRRs to subspace s22.
s22 = np.zeros(drrs.size)
for d in np.arange(padding, padding + drrs.size):
if drrs_pad[d] >= 0:
s22[d - padding] = np.min([drrs_pad[d + 1], drrs_pad[d + 2]])
elif drrs_pad[d] < 0:
s22[d - padding] = np.max([drrs_pad[d + 1], drrs_pad[d + 2]])
# Compute mRRs: time series of deviation of RRs from median.
df = pd.DataFrame({'signal': rr})
medrr = df.rolling(medfilt_order, center=True,
min_periods=1).median().signal.to_numpy()
mrrs = rr - medrr
mrrs[mrrs < 0] = mrrs[mrrs < 0] * 2
# Normalize by threshold.
th2 = _compute_threshold(mrrs, alpha, window_width)
mrrs /= th2
# Artifact classification #################################################
###########################################################################
# Artifact classes.
extra_idcs = []
missed_idcs = []
ectopic_idcs = []
longshort_idcs = []
i = 0
while i < rr.size - 2: # The flow control is implemented based on Figure 1
if np.abs(drrs[i]) <= 1: # Figure 1
i += 1
continue
eq1 = np.logical_and(drrs[i] > 1, s12[i] < (-c1 * drrs[i] - c2)) # Figure 2a
eq2 = np.logical_and(drrs[i] < -1, s12[i] > (-c1 * drrs[i] + c2)) # Figure 2a
if np.any([eq1, eq2]):
# If any of the two equations is true.
ectopic_idcs.append(i)
i += 1
continue
# If none of the two equations is true.
if ~np.any([np.abs(drrs[i]) > 1, np.abs(mrrs[i]) > 3]): # Figure 1
i += 1
continue
longshort_candidates = [i]
# Check if the following beat also needs to be evaluated.
if np.abs(drrs[i + 1]) < np.abs(drrs[i + 2]):
longshort_candidates.append(i + 1)
for j in longshort_candidates:
# Long beat.
eq3 = np.logical_and(drrs[j] > 1, s22[j] < -1) # Figure 2b
# Long or short.
eq4 = np.abs(mrrs[j]) > 3 # Figure 1
# Short beat.
eq5 = np.logical_and(drrs[j] < -1, s22[j] > 1) # Figure 2b
if ~np.any([eq3, eq4, eq5]):
# If none of the three equations is true: normal beat.
i += 1
continue
# If any of the three equations is true: check for missing or extra
# peaks.
# Missing.
eq6 = np.abs(rr[j] / 2 - medrr[j]) < th2[j] # Figure 1
# Extra.
eq7 = np.abs(rr[j] + rr[j + 1] - medrr[j]) < th2[j] # Figure 1
# Check if extra.
if np.all([eq5, eq7]):
extra_idcs.append(j)
i += 1
continue
# Check if missing.
if np.all([eq3, eq6]):
missed_idcs.append(j)
i += 1
continue
# If neither classified as extra or missing, classify as "long or
# short".
longshort_idcs.append(j)
i += 1
# Prepare output
artifacts = {"ectopic": ectopic_idcs, "missed": missed_idcs,
"extra": extra_idcs, "longshort": longshort_idcs}
subspaces = {"rr": rr, "drrs": drrs, "mrrs": mrrs, "s12": s12, "s22": s22,
"c1": c1, "c2": c2}
return artifacts, subspaces
def _compute_threshold(signal, alpha, window_width):
df = pd.DataFrame({'signal': np.abs(signal)})
q1 = df.rolling(window_width, center=True,
min_periods=1).quantile(.25).signal.to_numpy()
q3 = df.rolling(window_width, center=True,
min_periods=1).quantile(.75).signal.to_numpy()
th = alpha * ((q3 - q1) / 2)
return th
def _correct_artifacts(artifacts, peaks):
# Artifact correction
#####################
# The integrity of indices must be maintained if peaks are inserted or
# deleted: for each deleted beat, decrease indices following that beat in
# all other index lists by 1. Likewise, for each added beat, increment the
# indices following that beat in all other lists by 1.
extra_idcs = artifacts["extra"]
missed_idcs = artifacts["missed"]
ectopic_idcs = artifacts["ectopic"]
longshort_idcs = artifacts["longshort"]
# Delete extra peaks.
if extra_idcs:
peaks = _correct_extra(extra_idcs, peaks)
# Update remaining indices.
missed_idcs = _update_indices(extra_idcs, missed_idcs, -1)
ectopic_idcs = _update_indices(extra_idcs, ectopic_idcs, -1)
longshort_idcs = _update_indices(extra_idcs, longshort_idcs, -1)
# Add missing peaks.
if missed_idcs:
peaks = _correct_missed(missed_idcs, peaks)
# Update remaining indices.
ectopic_idcs = _update_indices(missed_idcs, ectopic_idcs, 1)
longshort_idcs = _update_indices(missed_idcs, longshort_idcs, 1)
if ectopic_idcs:
peaks = _correct_misaligned(ectopic_idcs, peaks)
if longshort_idcs:
peaks = _correct_misaligned(longshort_idcs, peaks)
return peaks
def _correct_extra(extra_idcs, peaks):
corrected_peaks = peaks.copy()
corrected_peaks = np.delete(corrected_peaks, extra_idcs)
return corrected_peaks
def _correct_missed(missed_idcs, peaks):
corrected_peaks = peaks.copy()
missed_idcs = np.array(missed_idcs)
# Calculate the position(s) of new beat(s). Make sure to not generate
# negative indices. prev_peaks and next_peaks must have the same
# number of elements.
valid_idcs = np.logical_and(missed_idcs > 1,
missed_idcs < len(corrected_peaks))
missed_idcs = missed_idcs[valid_idcs]
prev_peaks = corrected_peaks[[i - 1 for i in missed_idcs]]
next_peaks = corrected_peaks[missed_idcs]
added_peaks = prev_peaks + (next_peaks - prev_peaks) / 2
# Add the new peaks before the missed indices (see numpy docs).
corrected_peaks = np.insert(corrected_peaks, missed_idcs, added_peaks)
return corrected_peaks
def _correct_misaligned(misaligned_idcs, peaks):
corrected_peaks = peaks.copy()
misaligned_idcs = np.array(misaligned_idcs)
# Make sure to not generate negative indices, or indices that exceed
# the total number of peaks. prev_peaks and next_peaks must have the
# same number of elements.
valid_idcs = np.logical_and(misaligned_idcs > 1,
misaligned_idcs < len(corrected_peaks))
misaligned_idcs = misaligned_idcs[valid_idcs]
prev_peaks = corrected_peaks[[i - 1 for i in misaligned_idcs]]
next_peaks = corrected_peaks[[i + 1 for i in misaligned_idcs]]
half_ibi = (next_peaks - prev_peaks) / 2
peaks_interp = prev_peaks + half_ibi
# Shift the R-peaks from the old to the new position.
corrected_peaks = np.delete(corrected_peaks, misaligned_idcs)
corrected_peaks = np.concatenate((corrected_peaks,
peaks_interp)).astype(int)
corrected_peaks.sort(kind="mergesort")
return corrected_peaks
def _update_indices(source_idcs, update_idcs, update):
"""
For every element s in source_idcs, change every element u in update_idcs
according to update, if u is larger than s.
"""
if not update_idcs:
return update_idcs
for s in source_idcs:
update_idcs = [u + update if u > s else u for u in update_idcs]
return update_idcs
def _plot_artifacts_lipponen2019(artifacts, info):
"""
"""
# Extract parameters
longshort_idcs = artifacts["longshort"]
ectopic_idcs = artifacts["ectopic"]
extra_idcs = artifacts["extra"]
missed_idcs = artifacts["missed"]
rr = info["rr"]
drrs = info["drrs"]
mrrs = info["mrrs"]
s12 = info["s12"]
s22 = info["s22"]
c1 = info["c1"]
c2 = info["c2"]
# Visualize artifact type indices.
# Set grids
gs = matplotlib.gridspec.GridSpec(ncols=4, nrows=3,
width_ratios=[1, 2, 2, 2])
fig = plt.figure(constrained_layout=False)
ax0 = fig.add_subplot(gs[0, :-2])
ax1 = fig.add_subplot(gs[1, :-2])
ax2 = fig.add_subplot(gs[2, :-2])
ax3 = fig.add_subplot(gs[:, -1])
ax4 = fig.add_subplot(gs[:, -2])
ax0.set_title("Artifact types", fontweight="bold")
ax0.plot(rr, label="heart period")
ax0.scatter(longshort_idcs, rr[longshort_idcs], marker='x', c='m',
s=100, zorder=3, label="long/short")
ax0.scatter(ectopic_idcs, rr[ectopic_idcs], marker='x', c='g', s=100,
zorder=3, label="ectopic")
ax0.scatter(extra_idcs, rr[extra_idcs], marker='x', c='y', s=100,
zorder=3, label="false positive")
ax0.scatter(missed_idcs, rr[missed_idcs], marker='x', c='r', s=100,
zorder=3, label="false negative")
ax0.legend(loc="upper right")
# Visualize first threshold.
ax1.set_title("Consecutive-difference criterion", fontweight="bold")
ax1.plot(np.abs(drrs), label="difference consecutive heart periods")
ax1.axhline(1, c='r', label="artifact threshold")
ax1.legend(loc="upper right")
# Visualize second threshold.
ax2.set_title("Difference-from-median criterion", fontweight="bold")
ax2.plot(np.abs(mrrs), label="difference from median over 11 periods")
ax2.axhline(3, c="r", label="artifact threshold")
ax2.legend(loc="upper right")
# Visualize subspaces.
ax4.set_title("Subspace 1", fontweight="bold")
ax4.set_xlabel("S11")
ax4.set_ylabel("S12")
ax4.scatter(drrs, s12, marker="x", label="heart periods")
verts0 = [(min(drrs), max(s12)),
(min(drrs), -c1 * min(drrs) + c2),
(-1, -c1 * -1 + c2),
(-1, max(s12))]
poly0 = matplotlib.patches.Polygon(verts0, alpha=0.3, facecolor="r",
edgecolor=None, label="ectopic periods")
ax4.add_patch(poly0)
verts1 = [(1, -c1 * 1 - c2),
(1, min(s12)),
(max(drrs), min(s12)),
(max(drrs), -c1 * max(drrs) - c2)]
poly1 = matplotlib.patches.Polygon(verts1, alpha=0.3, facecolor="r",
edgecolor=None)
ax4.add_patch(poly1)
ax4.legend(loc="upper right")
ax3.set_title("Subspace 2", fontweight="bold")
ax3.set_xlabel("S21")
ax3.set_ylabel("S22")
ax3.scatter(drrs, s22, marker="x", label="heart periods")
verts2 = [(min(drrs), max(s22)),
(min(drrs), 1),
(-1, 1),
(-1, max(s22))]
poly2 = matplotlib.patches.Polygon(verts2, alpha=0.3, facecolor="r",
edgecolor=None, label="short periods")
ax3.add_patch(poly2)
verts3 = [(1, -1),
(1, min(s22)),
(max(drrs), min(s22)),
(max(drrs), -1)]
poly3 = matplotlib.patches.Polygon(verts3, alpha=0.3, facecolor="y",
edgecolor=None, label="long periods")
ax3.add_patch(poly3)
ax3.legend(loc="upper right")
|
[
"numpy.pad",
"pandas.DataFrame",
"numpy.abs",
"numpy.concatenate",
"numpy.logical_and",
"numpy.ravel",
"numpy.zeros",
"numpy.insert",
"numpy.any",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"numpy.array",
"numpy.max",
"numpy.min",
"numpy.delete",
"numpy.all",
"numpy.ediff1d"
] |
[((3895, 3911), 'numpy.ravel', 'np.ravel', (['rpeaks'], {}), '(rpeaks)\n', (3903, 3911), True, 'import numpy as np\n'), ((4246, 4261), 'numpy.mean', 'np.mean', (['rr[1:]'], {}), '(rr[1:])\n', (4253, 4261), True, 'import numpy as np\n'), ((4513, 4539), 'numpy.ediff1d', 'np.ediff1d', (['rr'], {'to_begin': '(0)'}), '(rr, to_begin=0)\n', (4523, 4539), True, 'import numpy as np\n'), ((4554, 4571), 'numpy.mean', 'np.mean', (['drrs[1:]'], {}), '(drrs[1:])\n', (4561, 4571), True, 'import numpy as np\n'), ((4772, 4804), 'numpy.pad', 'np.pad', (['drrs', 'padding', '"""reflect"""'], {}), "(drrs, padding, 'reflect')\n", (4778, 4804), True, 'import numpy as np\n'), ((4816, 4835), 'numpy.zeros', 'np.zeros', (['drrs.size'], {}), '(drrs.size)\n', (4824, 4835), True, 'import numpy as np\n'), ((4849, 4888), 'numpy.arange', 'np.arange', (['padding', '(padding + drrs.size)'], {}), '(padding, padding + drrs.size)\n', (4858, 4888), True, 'import numpy as np\n'), ((5141, 5160), 'numpy.zeros', 'np.zeros', (['drrs.size'], {}), '(drrs.size)\n', (5149, 5160), True, 'import numpy as np\n'), ((5174, 5213), 'numpy.arange', 'np.arange', (['padding', '(padding + drrs.size)'], {}), '(padding, padding + drrs.size)\n', (5183, 5213), True, 'import numpy as np\n'), ((5498, 5526), 'pandas.DataFrame', 'pd.DataFrame', (["{'signal': rr}"], {}), "({'signal': rr})\n", (5510, 5526), True, 'import pandas as pd\n'), ((10327, 10365), 'numpy.delete', 'np.delete', (['corrected_peaks', 'extra_idcs'], {}), '(corrected_peaks, extra_idcs)\n', (10336, 10365), True, 'import numpy as np\n'), ((10491, 10512), 'numpy.array', 'np.array', (['missed_idcs'], {}), '(missed_idcs)\n', (10499, 10512), True, 'import numpy as np\n'), ((11101, 11153), 'numpy.insert', 'np.insert', (['corrected_peaks', 'missed_idcs', 'added_peaks'], {}), '(corrected_peaks, missed_idcs, added_peaks)\n', (11110, 11153), True, 'import numpy as np\n'), ((11291, 11316), 'numpy.array', 'np.array', (['misaligned_idcs'], {}), '(misaligned_idcs)\n', (11299, 11316), True, 'import numpy as np\n'), ((11969, 12012), 'numpy.delete', 'np.delete', (['corrected_peaks', 'misaligned_idcs'], {}), '(corrected_peaks, misaligned_idcs)\n', (11978, 12012), True, 'import numpy as np\n'), ((13170, 13206), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'constrained_layout': '(False)'}), '(constrained_layout=False)\n', (13180, 13206), True, 'import matplotlib.pyplot as plt\n'), ((4050, 4079), 'numpy.ediff1d', 'np.ediff1d', (['peaks'], {'to_begin': '(0)'}), '(peaks, to_begin=0)\n', (4060, 4079), True, 'import numpy as np\n'), ((6275, 6331), 'numpy.logical_and', 'np.logical_and', (['(drrs[i] > 1)', '(s12[i] < -c1 * drrs[i] - c2)'], {}), '(drrs[i] > 1, s12[i] < -c1 * drrs[i] - c2)\n', (6289, 6331), True, 'import numpy as np\n'), ((6363, 6420), 'numpy.logical_and', 'np.logical_and', (['(drrs[i] < -1)', '(s12[i] > -c1 * drrs[i] + c2)'], {}), '(drrs[i] < -1, s12[i] > -c1 * drrs[i] + c2)\n', (6377, 6420), True, 'import numpy as np\n'), ((6450, 6468), 'numpy.any', 'np.any', (['[eq1, eq2]'], {}), '([eq1, eq2])\n', (6456, 6468), True, 'import numpy as np\n'), ((14127, 14139), 'numpy.abs', 'np.abs', (['drrs'], {}), '(drrs)\n', (14133, 14139), True, 'import numpy as np\n'), ((14396, 14408), 'numpy.abs', 'np.abs', (['mrrs'], {}), '(mrrs)\n', (14402, 14408), True, 'import numpy as np\n'), ((4950, 4992), 'numpy.max', 'np.max', (['[drrs_pad[d - 1], drrs_pad[d + 1]]'], {}), '([drrs_pad[d - 1], drrs_pad[d + 1]])\n', (4956, 4992), True, 'import numpy as np\n'), ((5276, 5318), 'numpy.min', 'np.min', (['[drrs_pad[d + 1], drrs_pad[d + 2]]'], {}), '([drrs_pad[d + 1], drrs_pad[d + 2]])\n', (5282, 5318), True, 'import numpy as np\n'), ((6185, 6200), 'numpy.abs', 'np.abs', (['drrs[i]'], {}), '(drrs[i])\n', (6191, 6200), True, 'import numpy as np\n'), ((6874, 6893), 'numpy.abs', 'np.abs', (['drrs[i + 1]'], {}), '(drrs[i + 1])\n', (6880, 6893), True, 'import numpy as np\n'), ((6896, 6915), 'numpy.abs', 'np.abs', (['drrs[i + 2]'], {}), '(drrs[i + 2])\n', (6902, 6915), True, 'import numpy as np\n'), ((7047, 7087), 'numpy.logical_and', 'np.logical_and', (['(drrs[j] > 1)', '(s22[j] < -1)'], {}), '(drrs[j] > 1, s22[j] < -1)\n', (7061, 7087), True, 'import numpy as np\n'), ((7228, 7268), 'numpy.logical_and', 'np.logical_and', (['(drrs[j] < -1)', '(s22[j] > 1)'], {}), '(drrs[j] < -1, s22[j] > 1)\n', (7242, 7268), True, 'import numpy as np\n'), ((7785, 7803), 'numpy.all', 'np.all', (['[eq5, eq7]'], {}), '([eq5, eq7])\n', (7791, 7803), True, 'import numpy as np\n'), ((7937, 7955), 'numpy.all', 'np.all', (['[eq3, eq6]'], {}), '([eq3, eq6])\n', (7943, 7955), True, 'import numpy as np\n'), ((8592, 8606), 'numpy.abs', 'np.abs', (['signal'], {}), '(signal)\n', (8598, 8606), True, 'import numpy as np\n'), ((12035, 12082), 'numpy.concatenate', 'np.concatenate', (['(corrected_peaks, peaks_interp)'], {}), '((corrected_peaks, peaks_interp))\n', (12049, 12082), True, 'import numpy as np\n'), ((5054, 5096), 'numpy.min', 'np.min', (['[drrs_pad[d - 1], drrs_pad[d + 1]]'], {}), '([drrs_pad[d - 1], drrs_pad[d + 1]])\n', (5060, 5096), True, 'import numpy as np\n'), ((5380, 5422), 'numpy.max', 'np.max', (['[drrs_pad[d + 1], drrs_pad[d + 2]]'], {}), '([drrs_pad[d + 1], drrs_pad[d + 2]])\n', (5386, 5422), True, 'import numpy as np\n'), ((7150, 7165), 'numpy.abs', 'np.abs', (['mrrs[j]'], {}), '(mrrs[j])\n', (7156, 7165), True, 'import numpy as np\n'), ((7301, 7324), 'numpy.any', 'np.any', (['[eq3, eq4, eq5]'], {}), '([eq3, eq4, eq5])\n', (7307, 7324), True, 'import numpy as np\n'), ((7588, 7616), 'numpy.abs', 'np.abs', (['(rr[j] / 2 - medrr[j])'], {}), '(rr[j] / 2 - medrr[j])\n', (7594, 7616), True, 'import numpy as np\n'), ((7679, 7715), 'numpy.abs', 'np.abs', (['(rr[j] + rr[j + 1] - medrr[j])'], {}), '(rr[j] + rr[j + 1] - medrr[j])\n', (7685, 7715), True, 'import numpy as np\n'), ((6664, 6679), 'numpy.abs', 'np.abs', (['drrs[i]'], {}), '(drrs[i])\n', (6670, 6679), True, 'import numpy as np\n'), ((6685, 6700), 'numpy.abs', 'np.abs', (['mrrs[i]'], {}), '(mrrs[i])\n', (6691, 6700), True, 'import numpy as np\n')]
|
import numpy as np
import matplotlib.pyplot as plt
import sys
import math
import random
import operator
def euclidean(x, x_p):
return ((x[0] - x_p[0]) ** 2 + (x[1] - x_p[1]) ** 2) ** 0.5
def greatest_euclidean(data, centers):
maxi = {}
for x in centers:
for x_p in data:
euc = euclidean(x, x_p)
if x_p not in maxi:
maxi[x_p] = 0
maxi[x_p] += euc
return max(maxi.items(), key=operator.itemgetter(1))[0]
# Uses a greedy approach, selects a data point at random and assigns this as a center for a classification
# it then finds the furthest data point from this and assigns this as a center and places it in the set
# the next center will be the furthest datapoint from all centers until all regions have a center
def gen_centers(M, data):
centers = []
N = len(data)
rand = random.randint(0, N - 1)
centers.append(data.pop(rand))
center = (0, 0)
classifiers = []
for i in range(M - 1):
center = greatest_euclidean(data, centers)
data.remove(center)
centers.append(center)
for x in data:
num = voronoi(x, centers)
classifiers.append(num)
return centers, classifiers
# Determine the Voronoi region for the data point. This basically just decides how to classify all the data points
# assigning it to the closest center by euclidean distance
def voronoi(x, centers):
order = []
for i in range(len(centers)):
datapoint = centers[i]
# Euclidean to x
order.append((euclidean(x, datapoint), i))
order.sort()
g = order[0][1]
return g
# Generates 10,000 random datapoints with x and y values between 0 and 1
def generate_data():
data = []
for x1_ in range(100):
for x2_ in range(100):
x1 = np.random.uniform(0, 1)
x2 = np.random.uniform(0, 1)
data.append((x1, x2))
return data
def plot(M):
data = generate_data()
centers, classifers = gen_centers(M, data)
unique=set(classifers)
print(unique)
plt.scatter(*zip(*data), c=classifers, cmap='rainbow')
plt.scatter(*zip(*centers), c='black')
plt.title('Greedy with {} Regions'.format(M))
plt.xlabel('x1', color='#1C2833')
plt.ylabel('x2', color='#1C2833')
plt.grid()
plt.show()
if __name__ == "__main__":
# 10 Clusters for users
regions = 10
plot(regions)
# Assumption: Users will be datapoints, users will create a voronoi region and counselors
# will be assigned to their closest associated region.
# Just using greedy. May add in branch and bound.
|
[
"numpy.random.uniform",
"matplotlib.pyplot.show",
"random.randint",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid",
"operator.itemgetter"
] |
[((862, 886), 'random.randint', 'random.randint', (['(0)', '(N - 1)'], {}), '(0, N - 1)\n', (876, 886), False, 'import random\n'), ((2213, 2246), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x1"""'], {'color': '"""#1C2833"""'}), "('x1', color='#1C2833')\n", (2223, 2246), True, 'import matplotlib.pyplot as plt\n'), ((2251, 2284), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""x2"""'], {'color': '"""#1C2833"""'}), "('x2', color='#1C2833')\n", (2261, 2284), True, 'import matplotlib.pyplot as plt\n'), ((2289, 2299), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2297, 2299), True, 'import matplotlib.pyplot as plt\n'), ((2304, 2314), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2312, 2314), True, 'import matplotlib.pyplot as plt\n'), ((1808, 1831), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (1825, 1831), True, 'import numpy as np\n'), ((1849, 1872), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (1866, 1872), True, 'import numpy as np\n'), ((453, 475), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (472, 475), False, 'import operator\n')]
|
# func.py
import numpy as np
from numba import njit, jit, prange
#------------------------ Distance Functions -----------------------#
def corr_dist(A):
return 1 - np.corrcoef(A)
def abs_diff(A):
target_matrix = np.zeros((len(A), len(A)))
mat_dim = target_matrix.shape[0]
for r in range(mat_dim):
for c in range(r, mat_dim):
target_matrix[r,c] = np.absolute(np.subtract(A[r], A[c]))
target_matrix[c,r] = target_matrix[r,c]
return target_matrix
def cond_diff(A):
target_matrix = np.ones((len(A), len(A)), dtype = bool)
mat_dim = target_matrix.shape[0]
for r in range(mat_dim):
for c in range(r, mat_dim):
target_matrix[r,c] = (A[r] == A[c])
target_matrix[c,r] = target_matrix[r,c]
return target_matrix
def len_diff(A):
target_matrix = np.ones((len(A), len(A)), dtype = int)
mat_dim = target_matrix.shape[0]
for r in range(mat_dim):
for c in range(r, mat_dim):
target_matrix[r,c] = np.absolute(np.subtract(len(A[r]), len(A[c])))
target_matrix[c,r] = target_matrix[r,c]
return target_matrix
def levenshtein_dist(A):
target_matrix = np.ones((len(A), len(A)), dtype = int)
mat_dim = target_matrix.shape[0]
for r in range(mat_dim):
for c in range(r, mat_dim):
target_matrix[r,c] = levenshtein(A[r], A[c])
target_matrix[c,r] = target_matrix[r,c]
return target_matrix
def weighted_euclidian(A, weights):
matrices = []
for arr in A:
mat = np.zeros((len(arr), len(arr)))
matrix_iteration(arr, mat, squared_dist)
matrices.append(mat)
weighted_dist = np.zeros((len(arr), len(arr)))
for ind in range(len(weights)):
weighted_dist = weighted_dist + weights[ind] * matrices[ind]
return np.sqrt(weighted_dist)
#------------------------ Transform Functions -----------------------#
def corrcoef_z_transform(A):
A = np.subtract(1, A)
results = np.empty(len(A), dtype = A.dtype)
quick_z_transform(A, results)
return results
def invert_corrcoef(A):
return np.subtract(1, A)
def z_transform(A):
results = np.empty(len(A), dtype = A.dtype)
quick_z_transform(A, results)
return results
@njit(parallel = True)
def quick_z_transform(A, results):
for i in prange(len(A)):
results[i] = np.log((1+A[i])/(1-A[i]))/2
#------------------------ Other Functions -----------------------#
def levenshtein(seq1, seq2):
size_x = len(seq1) + 1
size_y = len(seq2) + 1
matrix = np.zeros((size_x, size_y))
for x in range(size_x):
matrix [x, 0] = x
for y in range(size_y):
matrix [0, y] = y
for x in range(1, size_x):
for y in range(1, size_y):
if seq1[x-1] == seq2[y-1]:
matrix [x,y] = min(
matrix[x-1, y] + 1,
matrix[x-1, y-1],
matrix[x, y-1] + 1
)
else:
matrix [x,y] = min(
matrix[x-1,y] + 1,
matrix[x-1,y-1] + 1,
matrix[x,y-1] + 1
)
return (matrix[size_x - 1, size_y - 1])
|
[
"numpy.subtract",
"numpy.log",
"numpy.corrcoef",
"numba.njit",
"numpy.zeros",
"numpy.sqrt"
] |
[((2052, 2071), 'numba.njit', 'njit', ([], {'parallel': '(True)'}), '(parallel=True)\n', (2056, 2071), False, 'from numba import njit, jit, prange\n'), ((1644, 1666), 'numpy.sqrt', 'np.sqrt', (['weighted_dist'], {}), '(weighted_dist)\n', (1651, 1666), True, 'import numpy as np\n'), ((1776, 1793), 'numpy.subtract', 'np.subtract', (['(1)', 'A'], {}), '(1, A)\n', (1787, 1793), True, 'import numpy as np\n'), ((1919, 1936), 'numpy.subtract', 'np.subtract', (['(1)', 'A'], {}), '(1, A)\n', (1930, 1936), True, 'import numpy as np\n'), ((2346, 2372), 'numpy.zeros', 'np.zeros', (['(size_x, size_y)'], {}), '((size_x, size_y))\n', (2354, 2372), True, 'import numpy as np\n'), ((170, 184), 'numpy.corrcoef', 'np.corrcoef', (['A'], {}), '(A)\n', (181, 184), True, 'import numpy as np\n'), ((2150, 2181), 'numpy.log', 'np.log', (['((1 + A[i]) / (1 - A[i]))'], {}), '((1 + A[i]) / (1 - A[i]))\n', (2156, 2181), True, 'import numpy as np\n'), ((373, 396), 'numpy.subtract', 'np.subtract', (['A[r]', 'A[c]'], {}), '(A[r], A[c])\n', (384, 396), True, 'import numpy as np\n')]
|
import warnings
import biorbd_casadi as biorbd
import numpy as np
from scipy import interpolate
from bioptim import (
OdeSolver,
Node,
OptimalControlProgram,
ConstraintFcn,
DynamicsFcn,
ObjectiveFcn,
QAndQDotBounds,
QAndQDotAndQDDotBounds,
ConstraintList,
ObjectiveList,
DynamicsList,
Bounds,
BoundsList,
InitialGuessList,
ControlType,
Solver,
InitialGuess,
InterpolationType,
PhaseTransitionList,
PhaseTransitionFcn,
RigidBodyDynamics,
)
from ..initial_guess.humanoid_initial_pose import set_initial_pose
class HumanoidOcp:
def __init__(
self,
biorbd_model_path: str = None,
n_shooting: int = 10,
phase_time: float = 0.3,
n_threads: int = 8,
control_type: ControlType = ControlType.CONSTANT,
ode_solver: OdeSolver = OdeSolver.COLLOCATION(),
rigidbody_dynamics: RigidBodyDynamics = RigidBodyDynamics.ODE,
step_length: float = 0.8,
right_foot_location: np.array = np.zeros(3),
use_sx: bool = False,
):
self.biorbd_model_path = biorbd_model_path
self.n_shooting = n_shooting
self.phase_time = phase_time
self.n_threads = n_threads
self.control_type = control_type
self.ode_solver = ode_solver
self.rigidbody_dynamics = rigidbody_dynamics
if biorbd_model_path is not None:
self.biorbd_model = biorbd.Model(biorbd_model_path)
self.n_shooting = n_shooting
self.phase_time = phase_time
self._set_head()
self._set_knee()
self._set_shoulder()
self.n_q = self.biorbd_model.nbQ()
self.n_qdot = self.biorbd_model.nbQdot()
self.n_qddot = self.biorbd_model.nbQddot()
self.n_qdddot = self.n_qddot
self.n_tau = self.biorbd_model.nbGeneralizedTorque()
self.tau_min, self.tau_init, self.tau_max = -500, 0, 500
self.qddot_min, self.qddot_init, self.qddot_max = -1000, 0, 1000
self.qdddot_min, self.qdddot_init, self.qdddot_max = -10000, 0, 10000
self.right_foot_location = right_foot_location
self.step_length = step_length
self.initial_left_foot_location = right_foot_location - np.array([0, step_length / 2, 0])
self.final_left_foot_location = right_foot_location + np.array([0, step_length / 2, 0])
self.dynamics = DynamicsList()
self.constraints = ConstraintList()
self.objective_functions = ObjectiveList()
self.phase_transitions = PhaseTransitionList()
self.x_bounds = BoundsList()
self.u_bounds = BoundsList()
self.initial_states = []
self.x_init = InitialGuessList()
self.u_init = InitialGuessList()
self.control_type = control_type
self.control_nodes = Node.ALL if self.control_type == ControlType.LINEAR_CONTINUOUS else Node.ALL_SHOOTING
self._set_dynamics()
self._set_constraints()
self._set_objective_functions()
self._set_phase_transition()
self._set_boundary_conditions()
self._set_initial_guesses()
self.ocp = OptimalControlProgram(
self.biorbd_model,
self.dynamics,
self.n_shooting,
self.phase_time,
x_init=self.x_init,
x_bounds=self.x_bounds,
u_init=self.u_init,
u_bounds=self.u_bounds,
objective_functions=self.objective_functions,
constraints=self.constraints,
n_threads=n_threads,
control_type=self.control_type,
ode_solver=ode_solver,
use_sx=use_sx,
)
def _set_head(self):
self.has_head = False
for i in range(self.biorbd_model.nbSegment()):
seg = self.biorbd_model.segment(i)
if seg.name().to_string() == "Head":
self.has_head = True
break
def _set_knee(self):
self.has_knee = False
for i in range(self.biorbd_model.nbSegment()):
seg = self.biorbd_model.segment(i)
if seg.name().to_string() == "RShank":
self.has_knee = True
break
def _set_shoulder(self):
self.has_shoulder = False
for i in range(self.biorbd_model.nbSegment()):
seg = self.biorbd_model.segment(i)
if seg.name().to_string() == "RArm":
self.has_shoulder = True
break
def _set_dynamics(self):
# warnings.warn("not implemented under this version of bioptim")
self.dynamics.add(
DynamicsFcn.TORQUE_DRIVEN, rigidbody_dynamics=self.rigidbody_dynamics, with_contact=True, phase=0
)
# self.dynamics.add(DynamicsFcn.TORQUE_DRIVEN, with_contact=True, phase=0)
def _set_objective_functions(self):
# --- Objective function --- #
self.objective_functions.add(ObjectiveFcn.Lagrange.MINIMIZE_CONTROL, key="tau", phase=0)
idx_stability = [0, 1, 2]
if self.has_head:
idx_stability.append(3)
# torso stability
self.objective_functions.add(ObjectiveFcn.Lagrange.MINIMIZE_QDDOT, phase=0, index=idx_stability, weight=0.01)
# head stability
if self.has_head:
self.objective_functions.add(
ObjectiveFcn.Lagrange.MINIMIZE_QDDOT, derivative=True, phase=0, index=3, weight=0.01
)
self.objective_functions.add(
ObjectiveFcn.Lagrange.MINIMIZE_STATE, key="qdot", phase=0, index=3, weight=0.01
)
# keep velocity CoM around 1.5 m/s
self.objective_functions.add(
ObjectiveFcn.Mayer.MINIMIZE_COM_VELOCITY, index=1, target=1.5, node=Node.START, weight=1000
)
self.objective_functions.add(
ObjectiveFcn.Mayer.MINIMIZE_COM_VELOCITY, index=1, target=1.5, node=Node.END, weight=1000
)
# instead of phase transition along z
self.objective_functions.add(ObjectiveFcn.Lagrange.MINIMIZE_COM_VELOCITY, index=2, weight=0.1)
if (
self.rigidbody_dynamics == RigidBodyDynamics.DAE_INVERSE_DYNAMICS_JERK
or self.rigidbody_dynamics == RigidBodyDynamics.DAE_FORWARD_DYNAMICS_JERK
):
self.objective_functions.add(ObjectiveFcn.Lagrange.MINIMIZE_CONTROL, phase=0, key="qdddot", weight=1e-4)
def _set_constraints(self):
# --- Constraints --- #
# Contact force in Z are positive
self.constraints.add(
ConstraintFcn.TRACK_CONTACT_FORCES, min_bound=0, max_bound=np.inf, node=Node.ALL, contact_index=1, phase=0
) # FP0 > 0 en Z
# contact node at zero position and zero speed
# node = Node.ALL if self.implicit_dynamics else Node.START
node = Node.START
self.constraints.add(
ConstraintFcn.TRACK_MARKERS, node=node, target=self.right_foot_location, marker_index="RFoot", phase=0
)
self.constraints.add(ConstraintFcn.TRACK_MARKERS_VELOCITY, node=node, marker_index="RFoot", phase=0)
# node = Node.END
# self.constraints.add(
# ConstraintFcn.TRACK_MARKERS, node=node, target=self.right_foot_location, marker_index="RFoot", phase=0
# )
# self.constraints.add(ConstraintFcn.TRACK_MARKERS_VELOCITY, node=node, marker_index="RFoot", phase=0)
# first and last step constraints
self.constraints.add(
ConstraintFcn.TRACK_MARKERS,
target=self.initial_left_foot_location,
node=Node.START,
marker_index="LFoot",
phase=0,
)
self.constraints.add(
ConstraintFcn.TRACK_MARKERS,
target=self.final_left_foot_location,
node=Node.END,
marker_index="LFoot",
phase=0,
)
# Ensure lift of foot
if self.has_knee:
self.constraints.add(
ConstraintFcn.TRACK_MARKERS,
index=2,
min_bound=0.05,
max_bound=np.inf,
node=Node.MID,
marker_index="LFoot",
phase=0,
)
def _set_phase_transition(self):
idx = [0, 1, 2]
idx = idx.append(3) if self.has_head else idx
self.phase_transitions.add(PhaseTransitionFcn.CYCLIC, index=idx, weight=1000)
def _set_boundary_conditions(self):
self.x_bounds = BoundsList()
self.x_bounds.add(
bounds=QAndQDotAndQDDotBounds(self.biorbd_model)
if self.rigidbody_dynamics == RigidBodyDynamics.DAE_INVERSE_DYNAMICS_JERK
or self.rigidbody_dynamics == RigidBodyDynamics.DAE_FORWARD_DYNAMICS_JERK
else QAndQDotBounds(self.biorbd_model)
)
nq = self.n_q
self.x_bounds[0].max[2, :] = 0 # torso bended forward
if self.has_head:
self.x_bounds[0][nq + 3, 0] = 0 # head velocity zero at the beginning
self.x_bounds[0][nq + 3, -1] = 0 # head velocity zero at the end
if self.has_knee:
self.x_bounds[0].min[nq - 2 : nq, 0] = -np.pi / 8 # driving knees
# Supervised shoulders
if self.has_shoulder:
i = 1 if self.has_head else 0
self.x_bounds[0][5 + i, 0] = -np.pi / 6
self.x_bounds[0][6 + i, 0] = np.pi / 6
self.x_bounds[0][5 + i, -1] = np.pi / 6
self.x_bounds[0][6 + i, -1] = -np.pi / 6
self.x_bounds[0][5 + i + nq, 0] = 0
self.x_bounds[0][5 + i + nq, -1] = 0
self.x_bounds[0][6 + i + nq, 0] = 0
self.x_bounds[0][6 + i + nq, -1] = 0
# Unsupervised arms not working trying another time with cyclic constraints
# x_bounds[0].max[5, 0] = -1e-5 # position is negative at start
# x_bounds[0].min[6, 0] = 1e-5 # position is positive at start
#
# x_bounds[0].min[5, -1] = 1e-5 # position is positive at the end
# x_bounds[0].max[6, -1] = -1e-5 # position is negative at the end
#
# x_bounds[0][n_q + 5, [0, -1]] = 0 # velocity of shoulders zero at begining and end
# x_bounds[0][n_q + 6, [0, -1]] = 0 # velocity of shoulders zero at begining and end
# x_bounds[0].max[n_q + 6, 1] = -1e-5 # velocity of left shoulder negative
# x_bounds[0].min[n_q + 6, 1] = -5 # velocity of left shoulder negative
# x_bounds[0].min[n_q + 5, 1] = 1e-5 # velocity of right shoulder positive
# x_bounds[0].max[n_q + 5, 1] = 5 # velocity of right shoulder positive
if self.rigidbody_dynamics == RigidBodyDynamics.DAE_INVERSE_DYNAMICS:
self.u_bounds.add(
[self.tau_min] * self.n_tau
+ [self.qddot_min] * self.n_qddot
+ [self.qddot_min] * self.biorbd_model.nbContacts(),
[self.tau_max] * self.n_tau
+ [self.qddot_max] * self.n_qddot
+ [self.qddot_max] * self.biorbd_model.nbContacts(),
)
elif self.rigidbody_dynamics == RigidBodyDynamics.DAE_FORWARD_DYNAMICS:
self.u_bounds.add(
[self.tau_min] * self.n_tau + [self.qddot_min] * self.n_qddot,
[self.tau_max] * self.n_tau + [self.qddot_max] * self.n_qddot,
)
elif self.rigidbody_dynamics == RigidBodyDynamics.DAE_INVERSE_DYNAMICS_JERK:
self.u_bounds.add(
[self.tau_min] * self.n_tau
+ [self.qdddot_min] * self.n_qddot
+ [self.qddot_min] * self.biorbd_model.nbContacts(),
[self.tau_max] * self.n_tau
+ [self.qdddot_max] * self.n_qddot
+ [self.qddot_max] * self.biorbd_model.nbContacts(),
)
elif self.rigidbody_dynamics == RigidBodyDynamics.DAE_FORWARD_DYNAMICS_JERK:
self.u_bounds.add(
[self.tau_min] * self.n_tau + [self.qdddot_min] * self.n_qddot,
[self.tau_max] * self.n_tau + [self.qdddot_max] * self.n_qddot,
)
else:
self.u_bounds.add([self.tau_min] * self.n_tau, [self.tau_max] * self.n_tau)
# root is not actuated
self.u_bounds[0][:3, :] = 0
def _set_initial_guesses(self):
"""
Set initial guess for the optimization problem.
"""
# --- Initial guess --- #
q0 = [0] * self.n_q
# Torso over the floor and bent
q0[1] = 0.8
q0[2] = -np.pi / 6
self.q0i = set_initial_pose(
self.biorbd_model_path, np.array(q0), self.right_foot_location, self.initial_left_foot_location
)
self.q0end = set_initial_pose(
self.biorbd_model_path, np.array(q0), self.right_foot_location, self.final_left_foot_location
)
qdot0 = [0] * self.n_qdot
X0i = []
X0i.extend(self.q0i)
X0i.extend(qdot0)
X0end = []
X0end.extend(self.q0end)
X0end.extend(qdot0)
if (
self.rigidbody_dynamics == RigidBodyDynamics.DAE_INVERSE_DYNAMICS_JERK
or self.rigidbody_dynamics == RigidBodyDynamics.DAE_FORWARD_DYNAMICS_JERK
):
X0i.extend([0] * self.n_qddot)
X0end.extend([0] * self.n_qddot)
# X0i.extend([0] * self.n_qddot + [0] * self.biorbd_model.nbContacts())
# X0end.extend([0] * self.n_qddot + [0] * self.biorbd_model.nbContacts())
x = np.linspace(0, self.phase_time, 2)
y = np.array([X0i, X0end]).T
f = interpolate.interp1d(x, y)
x_new = np.linspace(0, self.phase_time, self.n_shooting + 1)
X0 = f(x_new) # use interpolation function returned by `interp1d`
self._set_initial_states(X0)
self._set_initial_controls()
def _set_initial_states(self, X0: np.array = None):
if X0 is None:
self.x_init.add([0] * (self.n_q + self.n_q))
else:
if X0.shape[1] != self.n_shooting + 1:
X0 = self._interpolate_initial_states(X0)
if not self.ode_solver.is_direct_shooting:
n = self.ode_solver.polynomial_degree
X0 = np.repeat(X0, n + 1, axis=1)
X0 = X0[:, :-n]
self.x_init.add(X0, interpolation=InterpolationType.EACH_FRAME)
def _set_initial_controls(self, U0: np.array = None):
if U0 is None:
if self.rigidbody_dynamics == RigidBodyDynamics.DAE_INVERSE_DYNAMICS:
self.u_init.add(
[self.tau_init] * self.n_tau
+ [self.qddot_init] * self.n_qddot
+ [5] * self.biorbd_model.nbContacts()
)
elif self.rigidbody_dynamics == RigidBodyDynamics.DAE_INVERSE_DYNAMICS_JERK:
self.u_init.add(
[self.tau_init] * self.n_tau
+ [self.qdddot_init] * self.n_qdddot
+ [5] * self.biorbd_model.nbContacts()
)
elif self.rigidbody_dynamics == RigidBodyDynamics.DAE_FORWARD_DYNAMICS_JERK:
self.u_init.add([self.tau_init] * self.n_tau + [self.qdddot_init] * self.n_qdddot)
elif self.rigidbody_dynamics == RigidBodyDynamics.DAE_FORWARD_DYNAMICS:
self.u_init.add([self.tau_init] * self.n_tau + [self.qddot_init] * self.n_qddot)
else:
self.u_init.add([self.tau_init] * self.n_tau)
else:
if U0.shape[1] != self.n_shooting:
U0 = self._interpolate_initial_controls(U0)
self.u_init.add(U0, interpolation=InterpolationType.EACH_FRAME)
def _interpolate_initial_states(self, X0: np.array):
print("interpolating initial states to match the number of shooting nodes")
x = np.linspace(0, self.phase_time, X0.shape[1])
y = X0
f = interpolate.interp1d(x, y)
x_new = np.linspace(0, self.phase_time, self.n_shooting + 1)
y_new = f(x_new) # use interpolation function returned by `interp1d`
return y_new
def _interpolate_initial_controls(self, U0: np.array):
print("interpolating initial controls to match the number of shooting nodes")
x = np.linspace(0, self.phase_time, U0.shape[1])
y = U0
f = interpolate.interp1d(x, y)
x_new = np.linspace(0, self.phase_time, self.n_shooting)
y_new = f(x_new) # use interpolation function returned by `interp1d`
return y_new
|
[
"bioptim.BoundsList",
"bioptim.OdeSolver.COLLOCATION",
"bioptim.ObjectiveList",
"bioptim.PhaseTransitionList",
"bioptim.InitialGuessList",
"biorbd_casadi.Model",
"numpy.zeros",
"bioptim.QAndQDotBounds",
"numpy.array",
"bioptim.OptimalControlProgram",
"numpy.linspace",
"bioptim.ConstraintList",
"scipy.interpolate.interp1d",
"bioptim.QAndQDotAndQDDotBounds",
"bioptim.DynamicsList",
"numpy.repeat"
] |
[((864, 887), 'bioptim.OdeSolver.COLLOCATION', 'OdeSolver.COLLOCATION', ([], {}), '()\n', (885, 887), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n'), ((1034, 1045), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (1042, 1045), True, 'import numpy as np\n'), ((8682, 8694), 'bioptim.BoundsList', 'BoundsList', ([], {}), '()\n', (8692, 8694), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n'), ((13751, 13785), 'numpy.linspace', 'np.linspace', (['(0)', 'self.phase_time', '(2)'], {}), '(0, self.phase_time, 2)\n', (13762, 13785), True, 'import numpy as np\n'), ((13835, 13861), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['x', 'y'], {}), '(x, y)\n', (13855, 13861), False, 'from scipy import interpolate\n'), ((13878, 13930), 'numpy.linspace', 'np.linspace', (['(0)', 'self.phase_time', '(self.n_shooting + 1)'], {}), '(0, self.phase_time, self.n_shooting + 1)\n', (13889, 13930), True, 'import numpy as np\n'), ((16093, 16137), 'numpy.linspace', 'np.linspace', (['(0)', 'self.phase_time', 'X0.shape[1]'], {}), '(0, self.phase_time, X0.shape[1])\n', (16104, 16137), True, 'import numpy as np\n'), ((16165, 16191), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['x', 'y'], {}), '(x, y)\n', (16185, 16191), False, 'from scipy import interpolate\n'), ((16208, 16260), 'numpy.linspace', 'np.linspace', (['(0)', 'self.phase_time', '(self.n_shooting + 1)'], {}), '(0, self.phase_time, self.n_shooting + 1)\n', (16219, 16260), True, 'import numpy as np\n'), ((16518, 16562), 'numpy.linspace', 'np.linspace', (['(0)', 'self.phase_time', 'U0.shape[1]'], {}), '(0, self.phase_time, U0.shape[1])\n', (16529, 16562), True, 'import numpy as np\n'), ((16590, 16616), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['x', 'y'], {}), '(x, y)\n', (16610, 16616), False, 'from scipy import interpolate\n'), ((16633, 16681), 'numpy.linspace', 'np.linspace', (['(0)', 'self.phase_time', 'self.n_shooting'], {}), '(0, self.phase_time, self.n_shooting)\n', (16644, 16681), True, 'import numpy as np\n'), ((1450, 1481), 'biorbd_casadi.Model', 'biorbd.Model', (['biorbd_model_path'], {}), '(biorbd_model_path)\n', (1462, 1481), True, 'import biorbd_casadi as biorbd\n'), ((2481, 2495), 'bioptim.DynamicsList', 'DynamicsList', ([], {}), '()\n', (2493, 2495), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n'), ((2527, 2543), 'bioptim.ConstraintList', 'ConstraintList', ([], {}), '()\n', (2541, 2543), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n'), ((2583, 2598), 'bioptim.ObjectiveList', 'ObjectiveList', ([], {}), '()\n', (2596, 2598), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n'), ((2636, 2657), 'bioptim.PhaseTransitionList', 'PhaseTransitionList', ([], {}), '()\n', (2655, 2657), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n'), ((2686, 2698), 'bioptim.BoundsList', 'BoundsList', ([], {}), '()\n', (2696, 2698), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n'), ((2727, 2739), 'bioptim.BoundsList', 'BoundsList', ([], {}), '()\n', (2737, 2739), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n'), ((2803, 2821), 'bioptim.InitialGuessList', 'InitialGuessList', ([], {}), '()\n', (2819, 2821), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n'), ((2848, 2866), 'bioptim.InitialGuessList', 'InitialGuessList', ([], {}), '()\n', (2864, 2866), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n'), ((3296, 3658), 'bioptim.OptimalControlProgram', 'OptimalControlProgram', (['self.biorbd_model', 'self.dynamics', 'self.n_shooting', 'self.phase_time'], {'x_init': 'self.x_init', 'x_bounds': 'self.x_bounds', 'u_init': 'self.u_init', 'u_bounds': 'self.u_bounds', 'objective_functions': 'self.objective_functions', 'constraints': 'self.constraints', 'n_threads': 'n_threads', 'control_type': 'self.control_type', 'ode_solver': 'ode_solver', 'use_sx': 'use_sx'}), '(self.biorbd_model, self.dynamics, self.n_shooting,\n self.phase_time, x_init=self.x_init, x_bounds=self.x_bounds, u_init=\n self.u_init, u_bounds=self.u_bounds, objective_functions=self.\n objective_functions, constraints=self.constraints, n_threads=n_threads,\n control_type=self.control_type, ode_solver=ode_solver, use_sx=use_sx)\n', (3317, 3658), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n'), ((12863, 12875), 'numpy.array', 'np.array', (['q0'], {}), '(q0)\n', (12871, 12875), True, 'import numpy as np\n'), ((13020, 13032), 'numpy.array', 'np.array', (['q0'], {}), '(q0)\n', (13028, 13032), True, 'import numpy as np\n'), ((13798, 13820), 'numpy.array', 'np.array', (['[X0i, X0end]'], {}), '([X0i, X0end])\n', (13806, 13820), True, 'import numpy as np\n'), ((2318, 2351), 'numpy.array', 'np.array', (['[0, step_length / 2, 0]'], {}), '([0, step_length / 2, 0])\n', (2326, 2351), True, 'import numpy as np\n'), ((2418, 2451), 'numpy.array', 'np.array', (['[0, step_length / 2, 0]'], {}), '([0, step_length / 2, 0])\n', (2426, 2451), True, 'import numpy as np\n'), ((14472, 14500), 'numpy.repeat', 'np.repeat', (['X0', '(n + 1)'], {'axis': '(1)'}), '(X0, n + 1, axis=1)\n', (14481, 14500), True, 'import numpy as np\n'), ((8741, 8782), 'bioptim.QAndQDotAndQDDotBounds', 'QAndQDotAndQDDotBounds', (['self.biorbd_model'], {}), '(self.biorbd_model)\n', (8763, 8782), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n'), ((8972, 9005), 'bioptim.QAndQDotBounds', 'QAndQDotBounds', (['self.biorbd_model'], {}), '(self.biorbd_model)\n', (8986, 9005), False, 'from bioptim import OdeSolver, Node, OptimalControlProgram, ConstraintFcn, DynamicsFcn, ObjectiveFcn, QAndQDotBounds, QAndQDotAndQDDotBounds, ConstraintList, ObjectiveList, DynamicsList, Bounds, BoundsList, InitialGuessList, ControlType, Solver, InitialGuess, InterpolationType, PhaseTransitionList, PhaseTransitionFcn, RigidBodyDynamics\n')]
|
import os
from pathlib import Path
import numpy as np
import pandas as pd
import spacy
from spacy.compat import pickle
import lz4.frame
from tqdm import tqdm
from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard, EarlyStopping
from ehr_classification.tokenizer import get_features, get_custom_tokenizer
from ehr_classification.classifier_model import compile_lstm
def run_multiple_models(df,
features,
weights,
word_vectors,
max_note_length=2000,
batch_size=64,
gpu_device='0'
):
'''
Run model on infile, adds columns for predictions and save it to outfile
:param df:
:param features:
:param weights:
:param word_vectors:
:param max_note_length:
:param batch_size:
:param gpu_device:
:return:
'''
# use specified gpu device
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_device)
nlp = get_custom_tokenizer(word_vectors)
embeddings = nlp.vocab.vectors.data
model = compile_lstm(embeddings,
{'nr_hidden': 64, 'max_length': max_note_length, 'nr_class': 4},
{'dropout': 0.5, 'lr': 0.0001})
for target, weight in tqdm(list(weights.items())):
model.load_weights(weight)
print(f'Predicting {target}.')
predictions = model.predict(features, batch_size=batch_size, verbose=True)
print(f'Done predicting {target}.')
df[(target + '_predictions')] = predictions[0]
df[(target + '_raw')] = predictions[1]
return df
def run_multiple_models_pickle(infile,
outfile,
word_vectors,
overwrite=False,
**kwargs
):
# only run when not already there
outfile = Path(outfile)
if not outfile.exists() or overwrite:
outfile.touch()
from .utils import lz4_load
data_dict = lz4_load(infile)
predictions = run_multiple_models(df=data_dict['meta'],
features=data_dict['data'],
word_vectors=word_vectors,
**kwargs)
print('Writing to file')
predictions.to_parquet(outfile)
print('Done writing to file')
def run_multiple_models_parquet(infile,
outfile,
word_vectors,
note_column='NoteTXT',
max_note_length=2000,
**kwargs
):
def select_rows(df): # Remove rows with empty note text
df = pd.DataFrame(df.loc[df[note_column].notnull()])
return df
eval_data = pd.read_parquet(infile)
lz4_file = infile.replace('.parquet', '.pic.lz4')
if Path(lz4_file).exists():
print('Loading features')
with lz4.frame.open(lz4_file, mode='r') as f:
eval_docs = pickle.load(f)
else:
print('Extracting tokens')
tokenizer = get_custom_tokenizer(word_vectors)
note_texts = eval_data[note_column]
tokens = list(tokenizer.pipe(note_texts))
print('Extracting features')
eval_features = get_features(tokens, max_note_length)
eval_data = select_rows(eval_data)
eval_data = run_multiple_models(df=eval_data,
features=eval_features,
word_vectors=word_vectors,
**kwargs)
print('Writing to file')
eval_data.to_parquet(outfile)
print('Done writing to file')
def run_current_models(infile, outfile, classifier_type, input_type='parquet', **kwargs):
# use models and vectors path from environment (or use defaults)
models_path = os.getenv("PREDICT_EHR_MODELS")
if not models_path:
models_path = '/mnt/obi0/phi/ehr/models/'
vectors_path = os.getenv("PREDICT_EHR_VECTORS")
if not vectors_path:
vectors_path = '/mnt/obi0/phi/ehr/word_vectors/filtered_20-05-23.bigram'
if classifier_type == 'event':
weights = {
'Event_PCI': f'{models_path}/Events/PCI/LSTM_CNN_BEST_model.hdf5',
'Event_ACS': f'{models_path}/Events/ACS/LSTM_CNN_BEST_model.hdf5',
'Event_HF': f'{models_path}/Events/HF/LSTM_CNN_BEST_model.hdf5',
'Event_IS': f'{models_path}/Events/IS/LSTM_CNN_BEST_model.hdf5'
}
elif classifier_type == 'history':
weights = {
'History_CAD': f'{models_path}/History/CAD/LSTM_CNN_BEST_model.hdf5',
'History_CAD_UI': f'{models_path}/History/CAD_UI/LSTM_CNN_BEST_model.hdf5',
'History_HF': f'{models_path}/History/HF/LSTM_CNN_BEST_model.hdf5',
'History_HF_UI': f'{models_path}/History/HF_UI/LSTM_CNN_BEST_model.hdf5',
}
else:
raise NotImplementedError
print(f'Predicting using weights: {weights}')
if input_type == 'parquet':
run_multiple_models_parquet(infile=infile,
outfile=outfile,
weights=weights,
word_vectors=vectors_path,
**kwargs)
elif input_type == 'pickle':
run_multiple_models_pickle(infile=infile,
outfile=outfile,
weights=weights,
word_vectors=vectors_path,
**kwargs)
def predict(output_directory,
classifier_type: ('note classifier, `event` or `history`', 'option', 't') = 'event',
gpu: ('gpu to use', 'option', 'g') = 0,
gpu_offset: ('subtract gpu offset', 'option', 's') = 0,
input_type: ('input type, can be `parquet` or `pickle`', 'option', 'i') = 'parquet',
*file_names):
"""Takes one or more parquet files and writes tokenized text to output file.
# set environment variables for models and word vectors
export PREDICT_EHR_VECTORS=en_core_web_lg
export PREDICT_EHR_MODELS=PATH/TO/MODELS
# run predictions for events on one or more parquet files
predict_ehr -t event out_dir text1.parquet
predict_ehr -t event out_dir text1.parquet text2.parquet text3.parquet
# run on multiple files in parallel with 4 gpus, using text that has been tokenized before:
'parallel -j 4 predict_ehr . -t event -g {%} -s 1 -i pickle {} ::: *.pic.lz4'
'parallel -j 4 predict_ehr . -t history -g {%} -s 1 -i pickle {} ::: *.pic.lz4'
"""
print(f'Predicting with the following input files: {file_names}')
for infile in file_names:
input_file = Path(infile)
assert Path(output_directory).exists()
output_file = Path(output_directory) / (input_file.name + '.predictions.pq')
print('Processing', infile)
run_current_models(infile,
str(output_file),
classifier_type=classifier_type,
gpu_device=int(gpu) - int(gpu_offset),
input_type=input_type)
def predict_():
"""Entry point for console_scripts
"""
import plac
plac.call(predict)
def train_model(train_texts,
train_labels,
validation_texts,
validation_labels,
model_name,
output_path='.',
max_note_length=2000,
learning_rate=0.0001,
epochs=150,
batch_size=64,
gpu_device='0',
save_best_only=True,
**kwargs):
"""
Train a model with train_texts and train_labels and validate on validation_texts and validation_labels.
train_texts: array of notes to be used for model training.
train_labels: a binary label to be used for training. The index should correspond to the train_texts
"""
# use specified gpu device
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_device)
# use word vectors from environment variable (or defaults)
vectors_path = os.getenv("PREDICT_EHR_VECTORS")
if not vectors_path:
vectors_path = '/mnt/obi0/phi/ehr/word_vectors/filtered_20-05-23.bigram'
nlp = get_custom_tokenizer(vectors_path)
embeddings = nlp.vocab.vectors.data
print('Parsing texts...')
train_docs = list(nlp.pipe(train_texts, batch_size=2000))
validation_docs = list(nlp.pipe(validation_texts, batch_size=2000))
train_x = get_features(train_docs, max_note_length)
validation_x = get_features(validation_docs, max_note_length)
train_labels = [train_labels, train_labels]
validation_labels = [validation_labels, validation_labels]
model = compile_lstm(embeddings, {'max_length': max_note_length}, {'lr': learning_rate})
# define callbacks
checkpoint_file = model_name + '_{epoch:02d}-{val_loss:.2f}.hdf5'
checkpoint_path = os.path.join(output_path, 'checkpoints', checkpoint_file)
print(f'Saving checkpoints to {checkpoint_path}')
checkpoint_callback = ModelCheckpoint(
filepath=checkpoint_path,
monitor='val_loss', save_best_only=save_best_only, save_weights_only=True
)
tensorboard_path = os.path.join(output_path, 'tensorboard', model_name)
print(f'Writing tensorboard output to {tensorboard_path}')
tensorboard_callback = TensorBoard(
log_dir=tensorboard_path,
write_graph=False, profile_batch=0
)
early_stopping_callback = EarlyStopping(monitor='val_loss', patience=50)
print('Training...')
model.fit(train_x,
train_labels,
validation_data=(validation_x, validation_labels),
epochs=epochs,
batch_size=batch_size,
callbacks=[checkpoint_callback, tensorboard_callback, early_stopping_callback])
return model
def train(labels_path, model_name, output_path,
epochs: ('number of epochs', 'option', 'e') = 150,
gpu: ('gpu to use', 'option', 'g') = 0,
gpu_offset: ('subtract gpu offset', 'option', 's') = 0,
testrun: ('do short testrun on 200 samples', 'flag', 't') = False,
all_checkpoints: ('save all or best checkpoint only', 'flag', 'a') = False):
"""Basic training method that takes parquet file with labeled data, splits into training and validation set
and trains model (with early stopping).
# first configure a spacy model to use as word vector mapping
export PREDICT_EHR_VECTORS=en_core_web_lg
# then train a classifier model given labels
train_ehr --gpu 0 mgb_predictions_event/Event_PCI_labels.parquet Event_PCI mimic_models_event
"""
if not Path(output_path).exists():
Path(output_path).mkdir(parents=True)
print('Processing', labels_path)
labels_df = pd.read_parquet(labels_path)
# shuffle the labels
labels_df = labels_df.sample(frac=1, random_state=42)
if testrun:
labels_df = labels_df.iloc[:100]
# split into two sets for training and validation
train_df, validation_df = np.array_split(labels_df, 2)
print(f'Train data shape: {train_df.shape}')
print(f'Validation data shape: {validation_df.shape}')
print(f'Training model: {model_name}')
model = train_model(train_texts=train_df['NoteTXT'],
train_labels=train_df['label'],
validation_texts=validation_df['NoteTXT'],
validation_labels=validation_df['label'],
model_name=model_name,
output_path=output_path,
epochs=int(epochs),
save_best_only=not all_checkpoints,
gpu_device=int(gpu) - int(gpu_offset))
model.save_weights(os.path.join(output_path, model_name + '.hdf5'))
def train_():
"""Entry point for console_scripts
"""
import plac
plac.call(train)
if __name__ == "__main__":
predict_()
|
[
"ehr_classification.classifier_model.compile_lstm",
"tensorflow.keras.callbacks.TensorBoard",
"plac.call",
"tensorflow.keras.callbacks.ModelCheckpoint",
"ehr_classification.tokenizer.get_custom_tokenizer",
"pathlib.Path",
"tensorflow.keras.callbacks.EarlyStopping",
"pandas.read_parquet",
"numpy.array_split",
"ehr_classification.tokenizer.get_features",
"os.path.join",
"os.getenv",
"spacy.compat.pickle.load"
] |
[((1076, 1110), 'ehr_classification.tokenizer.get_custom_tokenizer', 'get_custom_tokenizer', (['word_vectors'], {}), '(word_vectors)\n', (1096, 1110), False, 'from ehr_classification.tokenizer import get_features, get_custom_tokenizer\n'), ((1163, 1288), 'ehr_classification.classifier_model.compile_lstm', 'compile_lstm', (['embeddings', "{'nr_hidden': 64, 'max_length': max_note_length, 'nr_class': 4}", "{'dropout': 0.5, 'lr': 0.0001}"], {}), "(embeddings, {'nr_hidden': 64, 'max_length': max_note_length,\n 'nr_class': 4}, {'dropout': 0.5, 'lr': 0.0001})\n", (1175, 1288), False, 'from ehr_classification.classifier_model import compile_lstm\n'), ((2008, 2021), 'pathlib.Path', 'Path', (['outfile'], {}), '(outfile)\n', (2012, 2021), False, 'from pathlib import Path\n'), ((2998, 3021), 'pandas.read_parquet', 'pd.read_parquet', (['infile'], {}), '(infile)\n', (3013, 3021), True, 'import pandas as pd\n'), ((4063, 4094), 'os.getenv', 'os.getenv', (['"""PREDICT_EHR_MODELS"""'], {}), "('PREDICT_EHR_MODELS')\n", (4072, 4094), False, 'import os\n'), ((4188, 4220), 'os.getenv', 'os.getenv', (['"""PREDICT_EHR_VECTORS"""'], {}), "('PREDICT_EHR_VECTORS')\n", (4197, 4220), False, 'import os\n'), ((7503, 7521), 'plac.call', 'plac.call', (['predict'], {}), '(predict)\n', (7512, 7521), False, 'import plac\n'), ((8458, 8490), 'os.getenv', 'os.getenv', (['"""PREDICT_EHR_VECTORS"""'], {}), "('PREDICT_EHR_VECTORS')\n", (8467, 8490), False, 'import os\n'), ((8607, 8641), 'ehr_classification.tokenizer.get_custom_tokenizer', 'get_custom_tokenizer', (['vectors_path'], {}), '(vectors_path)\n', (8627, 8641), False, 'from ehr_classification.tokenizer import get_features, get_custom_tokenizer\n'), ((8861, 8902), 'ehr_classification.tokenizer.get_features', 'get_features', (['train_docs', 'max_note_length'], {}), '(train_docs, max_note_length)\n', (8873, 8902), False, 'from ehr_classification.tokenizer import get_features, get_custom_tokenizer\n'), ((8922, 8968), 'ehr_classification.tokenizer.get_features', 'get_features', (['validation_docs', 'max_note_length'], {}), '(validation_docs, max_note_length)\n', (8934, 8968), False, 'from ehr_classification.tokenizer import get_features, get_custom_tokenizer\n'), ((9093, 9178), 'ehr_classification.classifier_model.compile_lstm', 'compile_lstm', (['embeddings', "{'max_length': max_note_length}", "{'lr': learning_rate}"], {}), "(embeddings, {'max_length': max_note_length}, {'lr': learning_rate}\n )\n", (9105, 9178), False, 'from ehr_classification.classifier_model import compile_lstm\n'), ((9291, 9348), 'os.path.join', 'os.path.join', (['output_path', '"""checkpoints"""', 'checkpoint_file'], {}), "(output_path, 'checkpoints', checkpoint_file)\n", (9303, 9348), False, 'import os\n'), ((9429, 9549), 'tensorflow.keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'filepath': 'checkpoint_path', 'monitor': '"""val_loss"""', 'save_best_only': 'save_best_only', 'save_weights_only': '(True)'}), "(filepath=checkpoint_path, monitor='val_loss',\n save_best_only=save_best_only, save_weights_only=True)\n", (9444, 9549), False, 'from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard, EarlyStopping\n'), ((9591, 9643), 'os.path.join', 'os.path.join', (['output_path', '"""tensorboard"""', 'model_name'], {}), "(output_path, 'tensorboard', model_name)\n", (9603, 9643), False, 'import os\n'), ((9734, 9807), 'tensorflow.keras.callbacks.TensorBoard', 'TensorBoard', ([], {'log_dir': 'tensorboard_path', 'write_graph': '(False)', 'profile_batch': '(0)'}), '(log_dir=tensorboard_path, write_graph=False, profile_batch=0)\n', (9745, 9807), False, 'from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard, EarlyStopping\n'), ((9860, 9906), 'tensorflow.keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'patience': '(50)'}), "(monitor='val_loss', patience=50)\n", (9873, 9906), False, 'from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard, EarlyStopping\n'), ((11180, 11208), 'pandas.read_parquet', 'pd.read_parquet', (['labels_path'], {}), '(labels_path)\n', (11195, 11208), True, 'import pandas as pd\n'), ((11433, 11461), 'numpy.array_split', 'np.array_split', (['labels_df', '(2)'], {}), '(labels_df, 2)\n', (11447, 11461), True, 'import numpy as np\n'), ((12277, 12293), 'plac.call', 'plac.call', (['train'], {}), '(train)\n', (12286, 12293), False, 'import plac\n'), ((3300, 3334), 'ehr_classification.tokenizer.get_custom_tokenizer', 'get_custom_tokenizer', (['word_vectors'], {}), '(word_vectors)\n', (3320, 3334), False, 'from ehr_classification.tokenizer import get_features, get_custom_tokenizer\n'), ((3490, 3527), 'ehr_classification.tokenizer.get_features', 'get_features', (['tokens', 'max_note_length'], {}), '(tokens, max_note_length)\n', (3502, 3527), False, 'from ehr_classification.tokenizer import get_features, get_custom_tokenizer\n'), ((6981, 6993), 'pathlib.Path', 'Path', (['infile'], {}), '(infile)\n', (6985, 6993), False, 'from pathlib import Path\n'), ((12145, 12192), 'os.path.join', 'os.path.join', (['output_path', "(model_name + '.hdf5')"], {}), "(output_path, model_name + '.hdf5')\n", (12157, 12192), False, 'import os\n'), ((3083, 3097), 'pathlib.Path', 'Path', (['lz4_file'], {}), '(lz4_file)\n', (3087, 3097), False, 'from pathlib import Path\n'), ((3220, 3234), 'spacy.compat.pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3231, 3234), False, 'from spacy.compat import pickle\n'), ((7063, 7085), 'pathlib.Path', 'Path', (['output_directory'], {}), '(output_directory)\n', (7067, 7085), False, 'from pathlib import Path\n'), ((7009, 7031), 'pathlib.Path', 'Path', (['output_directory'], {}), '(output_directory)\n', (7013, 7031), False, 'from pathlib import Path\n'), ((11053, 11070), 'pathlib.Path', 'Path', (['output_path'], {}), '(output_path)\n', (11057, 11070), False, 'from pathlib import Path\n'), ((11089, 11106), 'pathlib.Path', 'Path', (['output_path'], {}), '(output_path)\n', (11093, 11106), False, 'from pathlib import Path\n')]
|
import math
import warnings
from collections import OrderedDict
from enum import Enum
import efel
import matplotlib.pyplot as plt
import numpy as np
from lib.Model import Model
from lib.NrnModel import NrnModel
class Level(Enum):
HIGH = 0.5
MID = 5.0
LOW = 10.0
VLOW = 50.0
EFEL_NAME_MAP = {
"AP Amplitude": "AP_amplitude",
"AP Height": "AP_height",
"AP Width": "AP_width",
"AHP Absolute Depth": "AHP_depth_abs",
"AHP time from peak": "AHP_time_from_peak",
"Spike Count": "Spikecount",
"Time to First Spike": "time_to_first_spike",
}
EFEL2NAME_MAP = {v: k for k, v in EFEL_NAME_MAP.items()}
def _zero_valued_dict(keys):
return dict.fromkeys(keys, 0)
class EfelMeasurements():
def __init__(self, model:Model , config: dict):
self.cell = model
self.voltage = None
self.t = None
self.delay = None
self.duration = None
self.current_amplitude = None
self.Tstop = None
self.trace = {}
self._setup(config)
def _setup(self, config):
self.voltage, self.t = self.cell.stimulateCell(
float(config["Amplitude"]), float(
config["Duration"]), float(config["Delay"]),
float(
config["T stop"]), config["Stimulus Section"], config["Recording Section"],
clampAt=float(config["Stimulus Position"]), recordAt=float(config["Recording Position"]), init=float(config["Vinit"]))
self.delay = float(config["Delay"])
self.duration = float(config["Duration"])
self.Tstop = float(config["T stop"])
self.current_amplitude = float(config["Amplitude"])
self._initialize()
def _initialize(self):
# start = sorted(self._closeMatches(self.t,delay,0.025),key=lambda x: x[0])[0][0]
# end = sorted(self._closeMatches(self.t,delay+duration,0.025),key=lambda x: x[0])[0][0]
# print(t[2]-t[1])
efel.setDoubleSetting('stimulus_current', self.current_amplitude)
efel.setIntSetting("strict_stiminterval", True)
self.trace['T'] = self.t
self.trace['V'] = self.voltage
# max because delay may be less than 5ms
self.trace['stim_start'] = [max(self.delay-5, 0)]
self.trace['stim_end'] = [self.Tstop]
return self.voltage, self.t
def get_measurements(self, outputDict: dict,featureNames: list):
traces = [self.trace]
efel_feature_names = self._convert_to_efel_names(featureNames)
warnings.filterwarnings("ignore", category=RuntimeWarning)
check_peaks = efel.getFeatureValues(traces, ["Spikecount_stimint"])
if check_peaks[0]["Spikecount_stimint"][0] == 0:
return _zero_valued_dict(featureNames)
amplitudes = efel.getFeatureValues(traces, ["AP_amplitude"])
if (amplitudes[0]["AP_amplitude"] is None):
# print("efel failed",len(traces_results[0]["AP_amplitude"]) , len(traces_results[0]["AP_height"]))
print(f"n spikes are {check_peaks[0]['Spikecount_stimint'][0]}")
return _zero_valued_dict(featureNames)
traces_results = efel.getFeatureValues(traces, efel_feature_names)
warnings.filterwarnings("default", category=RuntimeWarning)
for trace_results in traces_results:
# trace_result is a dictionary, with as keys the requested eFeatures
for feature_name, feature_values in trace_results.items():
if len(feature_values) > 0:
outputDict[EFEL2NAME_MAP[feature_name]
] = np.mean(feature_values)
else:
print(f"{feature_name} failed")
print(f"{feature_name} equals {feature_values}")
outputDict[EFEL2NAME_MAP[feature_name]] = 0
if "Time to First Spike" in list(outputDict.keys()):
if outputDict["Time to First Spike"] !=0:
outputDict["Time to First Spike"] +=self.delay
self.measurements = outputDict
# for name in featureNames:
# if name == "Input Resistance":
# self.measurements[name] = self.inputResistance(-0.5,
# plotting=False, printing=False)
# elif name == "Rheobase":
# self.measurements[name] = self.Rheobase(
# Level.VLOW, 1, plotting=False, printing=False)
# elif name == "Time Constant":
# self.measurements[name] = self.timeConstant(
# -0.5, plotting=False, printing=False)
return self.measurements
def _closeMatches(self, lst: list, findVal, tolerance):
""" find a list of closest matches to a specific value with a spicified tolerance
Args:
:param lst: target list to search into
:param findVal: target value
:param tolerance: accepted error in matches
:return: list of (value,index) pairs
"""
# matches = [(val,index) for index,val in enumerate(lst) if abs(val - findVal) < tolerance]
matches = [(val, index) for index, val in enumerate(lst)
if math.isclose(val, findVal, abs_tol=tolerance)]
return matches
def _convert_to_efel_names(self, regular_feature_names: list):
efel_feature_names = []
for fName in regular_feature_names:
if fName not in list(EFEL_NAME_MAP.keys()):
raise ValueError(
f" Feature: '{fName}' is not availabe in Efel or not spelled well")
efel_feature_names.append(EFEL_NAME_MAP[fName])
return efel_feature_names
if __name__ == '__main__':
fig, ax = plt.subplots()
for i in range(1):
delay = 150 # 150
duration = 1
current = 21
efel.setDoubleSetting('stimulus_current', current)
# efel.setDoubleSetting('interp_step', 0.025)
# efel.setIntSetting("strict_stiminterval", True)
testEFEL = EfelMeasurements()
testEFEL.stimulateCell(current, duration, delay,
testEFEL.iseg, 0.5, 500)
testEFEL.get_measurements(["Spikecount", "time_to_first_spike", "AP_amplitude",
"AP_height", 'AP_width', 'AHP_depth_abs', "AHP_time_from_peak"])
testEFEL.model.graphVolt(
testEFEL.voltage, testEFEL.t, "trace", ax, color=np.random.rand(3,))
# ax.set_color("red")
plt.show()
|
[
"matplotlib.pyplot.show",
"warnings.filterwarnings",
"efel.setDoubleSetting",
"efel.setIntSetting",
"efel.getFeatureValues",
"numpy.mean",
"math.isclose",
"numpy.random.rand",
"matplotlib.pyplot.subplots"
] |
[((5889, 5903), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5901, 5903), True, 'import matplotlib.pyplot as plt\n'), ((6657, 6667), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6665, 6667), True, 'import matplotlib.pyplot as plt\n'), ((2056, 2121), 'efel.setDoubleSetting', 'efel.setDoubleSetting', (['"""stimulus_current"""', 'self.current_amplitude'], {}), "('stimulus_current', self.current_amplitude)\n", (2077, 2121), False, 'import efel\n'), ((2130, 2177), 'efel.setIntSetting', 'efel.setIntSetting', (['"""strict_stiminterval"""', '(True)'], {}), "('strict_stiminterval', True)\n", (2148, 2177), False, 'import efel\n'), ((2619, 2677), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'RuntimeWarning'}), "('ignore', category=RuntimeWarning)\n", (2642, 2677), False, 'import warnings\n'), ((2700, 2753), 'efel.getFeatureValues', 'efel.getFeatureValues', (['traces', "['Spikecount_stimint']"], {}), "(traces, ['Spikecount_stimint'])\n", (2721, 2753), False, 'import efel\n'), ((2884, 2931), 'efel.getFeatureValues', 'efel.getFeatureValues', (['traces', "['AP_amplitude']"], {}), "(traces, ['AP_amplitude'])\n", (2905, 2931), False, 'import efel\n'), ((3251, 3300), 'efel.getFeatureValues', 'efel.getFeatureValues', (['traces', 'efel_feature_names'], {}), '(traces, efel_feature_names)\n', (3272, 3300), False, 'import efel\n'), ((3309, 3368), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""default"""'], {'category': 'RuntimeWarning'}), "('default', category=RuntimeWarning)\n", (3332, 3368), False, 'import warnings\n'), ((6004, 6054), 'efel.setDoubleSetting', 'efel.setDoubleSetting', (['"""stimulus_current"""', 'current'], {}), "('stimulus_current', current)\n", (6025, 6054), False, 'import efel\n'), ((5358, 5403), 'math.isclose', 'math.isclose', (['val', 'findVal'], {'abs_tol': 'tolerance'}), '(val, findVal, abs_tol=tolerance)\n', (5370, 5403), False, 'import math\n'), ((6603, 6620), 'numpy.random.rand', 'np.random.rand', (['(3)'], {}), '(3)\n', (6617, 6620), True, 'import numpy as np\n'), ((3711, 3734), 'numpy.mean', 'np.mean', (['feature_values'], {}), '(feature_values)\n', (3718, 3734), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3.7
import unittest
import numpy
import os
import librosa
import soundfile
import sys
from tempfile import TemporaryDirectory
def main():
dest = "tests/test_1_note_Csharp3.wav"
tone = librosa.tone(138.59, sr=22050, length=44100)
soundfile.write(dest, tone, 22050)
print("Created {0} with note C#3".format(dest))
dest = "tests/test_1_note_E4.wav"
tone = librosa.tone(329.63, sr=22050, length=44100)
soundfile.write(dest, tone, 22050)
print("Created {0} with note E4".format(dest))
dest = "tests/test_2_notes_E2_F3.wav"
tone = numpy.zeros(44100)
tone += librosa.tone(82.41, sr=22050, length=44100)
tone += librosa.tone(174.61, sr=22050, length=44100)
soundfile.write(dest, tone, 22050)
print("Created {0} with notes E2, F3".format(dest))
dest = "tests/test_2_notes_G3_Asharp4.wav"
tone = numpy.zeros(44100)
tone += librosa.tone(196, sr=22050, length=44100)
tone += librosa.tone(466.16, sr=22050, length=44100)
soundfile.write(dest, tone, 22050)
print("Created {0} with notes G3, A#4".format(dest))
dest = "tests/test_3_notes_G2_B2_G#3.wav"
tone = numpy.zeros(44100)
tone += librosa.tone(98, sr=22050, length=44100)
tone += librosa.tone(123.47, sr=22050, length=44100)
tone += librosa.tone(207.65, sr=22050, length=44100)
soundfile.write(dest, tone, 22050)
print("Created {0} with notes G2, B2, G#3".format(dest))
return 0
if __name__ == "__main__":
sys.exit(main())
|
[
"librosa.tone",
"numpy.zeros",
"soundfile.write"
] |
[((216, 260), 'librosa.tone', 'librosa.tone', (['(138.59)'], {'sr': '(22050)', 'length': '(44100)'}), '(138.59, sr=22050, length=44100)\n', (228, 260), False, 'import librosa\n'), ((265, 299), 'soundfile.write', 'soundfile.write', (['dest', 'tone', '(22050)'], {}), '(dest, tone, 22050)\n', (280, 299), False, 'import soundfile\n'), ((402, 446), 'librosa.tone', 'librosa.tone', (['(329.63)'], {'sr': '(22050)', 'length': '(44100)'}), '(329.63, sr=22050, length=44100)\n', (414, 446), False, 'import librosa\n'), ((451, 485), 'soundfile.write', 'soundfile.write', (['dest', 'tone', '(22050)'], {}), '(dest, tone, 22050)\n', (466, 485), False, 'import soundfile\n'), ((591, 609), 'numpy.zeros', 'numpy.zeros', (['(44100)'], {}), '(44100)\n', (602, 609), False, 'import numpy\n'), ((622, 665), 'librosa.tone', 'librosa.tone', (['(82.41)'], {'sr': '(22050)', 'length': '(44100)'}), '(82.41, sr=22050, length=44100)\n', (634, 665), False, 'import librosa\n'), ((678, 722), 'librosa.tone', 'librosa.tone', (['(174.61)'], {'sr': '(22050)', 'length': '(44100)'}), '(174.61, sr=22050, length=44100)\n', (690, 722), False, 'import librosa\n'), ((727, 761), 'soundfile.write', 'soundfile.write', (['dest', 'tone', '(22050)'], {}), '(dest, tone, 22050)\n', (742, 761), False, 'import soundfile\n'), ((877, 895), 'numpy.zeros', 'numpy.zeros', (['(44100)'], {}), '(44100)\n', (888, 895), False, 'import numpy\n'), ((908, 949), 'librosa.tone', 'librosa.tone', (['(196)'], {'sr': '(22050)', 'length': '(44100)'}), '(196, sr=22050, length=44100)\n', (920, 949), False, 'import librosa\n'), ((962, 1006), 'librosa.tone', 'librosa.tone', (['(466.16)'], {'sr': '(22050)', 'length': '(44100)'}), '(466.16, sr=22050, length=44100)\n', (974, 1006), False, 'import librosa\n'), ((1011, 1045), 'soundfile.write', 'soundfile.write', (['dest', 'tone', '(22050)'], {}), '(dest, tone, 22050)\n', (1026, 1045), False, 'import soundfile\n'), ((1161, 1179), 'numpy.zeros', 'numpy.zeros', (['(44100)'], {}), '(44100)\n', (1172, 1179), False, 'import numpy\n'), ((1192, 1232), 'librosa.tone', 'librosa.tone', (['(98)'], {'sr': '(22050)', 'length': '(44100)'}), '(98, sr=22050, length=44100)\n', (1204, 1232), False, 'import librosa\n'), ((1245, 1289), 'librosa.tone', 'librosa.tone', (['(123.47)'], {'sr': '(22050)', 'length': '(44100)'}), '(123.47, sr=22050, length=44100)\n', (1257, 1289), False, 'import librosa\n'), ((1302, 1346), 'librosa.tone', 'librosa.tone', (['(207.65)'], {'sr': '(22050)', 'length': '(44100)'}), '(207.65, sr=22050, length=44100)\n', (1314, 1346), False, 'import librosa\n'), ((1351, 1385), 'soundfile.write', 'soundfile.write', (['dest', 'tone', '(22050)'], {}), '(dest, tone, 22050)\n', (1366, 1385), False, 'import soundfile\n')]
|
import numpy as np
import itertools
from scintillations.stream import modulate as apply_turbulence
from scintillations.stream import transverse_speed
from streaming.stream import Stream, BlockStream
from streaming.signal import *
import streaming.signal
import logging
from acoustics.signal import impulse_response_real_even
import auraliser.tools
logger = auraliser.tools.create_logger(__name__)
def apply_atmospheric_attenuation(signal, fs, distance, nhop, atmosphere, ntaps, inverse=False, distance_reducer=np.mean):
"""Apply atmospheric attenuation to signal.
:param distance: Iterable with distances.
:param fs: Sample frequency.
:param atmosphere: Atmosphere.
:param ntaps: Amount of filter taps.
:param sign: Sign.
:rtype: :class:`streaming.Stream`
Compute and apply the attenuation due to atmospheric absorption.
The attenuation can change with distance. The attenuation is a magnitude-only filter.
We design a linear-phase filter
.. note:: The filter delay is compensated by dropping the first `ntaps//2` samples.
"""
# Partition `distance` into blocks, and reduce with `distance_reducer`.
distance = distance.blocks(nhop).map(distance_reducer)
ir = Stream(atmosphere.impulse_response(d, fs, ntaps=ntaps, inverse=inverse) for d in distance)
signal = convolve_overlap_save(signal, ir, nhop, ntaps)
signal = signal.samples().drop(int(ntaps//2)) # Linear phase, correct for group delay caused by FIR filter.
return signal
def apply_reflection_strength(emission, nhop, spectra, effective, ntaps, force_hard):
"""Apply mirror source strength.
:param signal: Signal.
:param nblock: Amount of samples per block.
:param spectra: Spectrum per block.
:param effective: Whether the source is effective or not.
:param ntaps: Amount of filter taps.
:param force_hard: Whether to force a hard ground.
:returns: Signal with correct strength.
.. warning:: This operation will cause a delay that may vary over time.
"""
if effective is not None:
# We have an effectiveness value for each hop (which is a block of samples)
emission = BlockStream(map(lambda x,y: x *y, emission.blocks(nhop), effective), nblock=nhop)
if force_hard:
logger.info("apply_reflection_strength: Hard ground.")
else:
logger.info("apply_reflection_strength: Soft ground.")
impulse_responses = Stream(impulse_response_real_even(s, ntaps) for s in spectra)
emission = convolve_overlap_save(emission, impulse_responses, nhop, ntaps)
# Filter has a delay we need to correct for.
emission = emission.samples().drop(int(ntaps//2))
return emission
#def apply_ground_reflection(signal, ir, nblock):
#"""Apply ground reflection strength.
#:param signal: Signal before ground reflection strength is applied.
#:param ir: Impulse response per block.
#:param nblock: Amount of samples per block.
#:returns: Signal after reflection strength is applied.
#:type: :class:`streaming.BlockStream`
#"""
#signal = convolve(signal=signal, impulse_responses=ir, nblock=nblock)
def apply_doppler(signal, delay, fs, initial_value=0.0, inverse=False):
"""Apply Doppler shift.
:param signal: Signal before Doppler shift.
:param delay: Propagation delay.
:param fs: Constant sample frequency.
:returns: Doppler-shifted signal.
:rtype: :class:`streaming.Stream`
"""
if inverse:
delay = delay * -1 # Unary operators are not yet implemented in Stream
return vdl(signal, times(1./fs), delay, initial_value=initial_value)
def apply_spherical_spreading(signal, distance, inverse=False):#, nblock):
"""Apply spherical spreading.
:param signal. Signal. Iterable.
:param distance: Distance. Iterable.
:param nblock: Amount of samples in block.
"""
if inverse:
return signal * distance
else:
return signal / distance
#def undo_reflection(signal, nhop, impedance, angle, ntaps, force_hard):
#"""Undo reflection
#:param signal: Signal.
#:param nhop: Hop size.
#:param impedance: Fixed impedance.
#:param angle: Angle per hop.
#:param ntaps: Taps.
#:param force_hard: Whether to assume infinite impedance.
#"""
#if force_hard:
#tf =
#strength = Stream(reflection_factor_plane_wave(impedance, a) for a in angles.samples())
#tf = 1. / (1. + strength)
#impulse_responses = Stream(atmosphere.impulse_response(d, fs, ntaps=ntaps, inverse=inverse) for d in distance)
#signal = convolve_overlap_save(signal, impulse_responses, nhop, ntaps)
def nextpow2(x):
return int(2**np.ceil(np.log2(x)))
|
[
"numpy.log2",
"acoustics.signal.impulse_response_real_even"
] |
[((2442, 2478), 'acoustics.signal.impulse_response_real_even', 'impulse_response_real_even', (['s', 'ntaps'], {}), '(s, ntaps)\n', (2468, 2478), False, 'from acoustics.signal import impulse_response_real_even\n'), ((4702, 4712), 'numpy.log2', 'np.log2', (['x'], {}), '(x)\n', (4709, 4712), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
#Copyright (c) 2014, <NAME> <<EMAIL>>
#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.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ccl_c_dir="ccl_single_pass_c_code/"
import subprocess
import signal
import glob
import os
import re
import numpy as np
import threading
from PIL import Image
from cola import ComponentLabeling as cola
from converter import Img_conv as Img_conv
class CompareCP:
def get_error_cnt (self):
return self.__error_cnt
def get_report (self):
return self.__report
def __init__(self, timeout, max_x, max_y, file_show=None):
self.__timeout = timeout
self.__report = ""
self.__error_cnt = 0
self.__c_box = []
# convert images
try:
os.mkdir(ccl_c_dir + "/img");
except:
None
for files in glob.glob(ccl_c_dir + "/img/*.pbm"):
os.remove(files)
destreg = re.compile(r".*/(.*)$")
file_chk=""
file_cnt=0
if file_show is None:
for files in glob.glob("../img/*.pbm"):
if files != "../img/sim_in.pbm" and files != "../img\\sim_in.pbm":
img = Img_conv(files, max_x, max_y, 0.5)
m = destreg.match(files)
if m.group(1) is not None:
file_cnt+=1
file_chk+="img/" + m.group(1) + "\n"
img.save(ccl_c_dir + "/img/" + m.group(1))
else:
img = Img_conv(file_show, max_x, max_y, 0.5)
m = destreg.match(file_show)
if m.group(1) is not None:
file_cnt+=1
file_chk+="img/" + m.group(1) + "\n"
img.save(ccl_c_dir + "/img/" + m.group(1))
f = open(ccl_c_dir + "/test_batch_01.txt", "w")
f.write(str(file_cnt) + "\n" + file_chk)
f.close()
del f
self.get_c_box()
if file_show is None:
for files in glob.glob("../img/*.pbm"):
if files != "../img/sim_in.pbm" and files != "../img\\sim_in.pbm":
file_cnt+=1
pycola = cola(files, max_x=max_x, max_y=max_y);
self.chk_file(files, pycola)
del pycola
else:
pycola = cola(file_show, max_x=max_x, max_y=max_y);
c_boxes=self.chk_file(file_show, pycola)
print((str(c_boxes)))
pycola.plot_sp_add('Boxes C', None, c_boxes)
def chk_file(self, files, pycola):
self.__report += "Check file: " + files + "\n"
py_boxes = pycola.get_boxes().copy()
c_boxes = {}
box_cnt = 0
for b in py_boxes:
((py_start_x, py_start_y), (py_end_x, py_end_y)) = py_boxes[b]
found = False
for bc in self.__c_box:
(stim_file, c_start_y, c_start_x, c_end_y, c_end_x) = bc
c_end_x -= 1
c_end_y -= 1
c_boxes[str(c_start_x) + str(c_start_y) + str(c_end_x) + str(c_end_y)] = ((c_start_x, c_start_y), (c_end_x, c_end_y))
box_cnt += 1
if stim_file == files[3:] and py_start_x == c_start_x and py_start_y == c_start_y and py_end_x == c_end_x and py_end_y == c_end_y:
found = True
self.__c_box.remove(bc)
break
if not found:
self.__report += "\033[91mError\033[0m" + " Python Box: ((" + str(py_start_x)
self.__report += ", " + str(py_start_y) + "), (" + str(py_end_x) + ", " + str(py_end_y) + ")"
self.__report += " not in C implementation\n"
self.__error_cnt += 1
for bc in self.__c_box:
(stim_file, c_start_y, c_start_x, c_end_y, c_end_x) = bc
c_end_x -= 1
c_end_y -= 1
if stim_file == files[3:]:
self.__report += "\033[91mError\033[0m" + " C Box: ((" + str(c_start_x)
self.__report += ", " + str(c_start_y) + "), (" + str(c_end_x) + ", " + str(c_end_y) + ")"
self.__report += " not in Python implementation\n"
self.__error_cnt += 1
del pycola
return c_boxes
def get_c_box(self):
c_box = C_parser()
c_box.start()
while not c_box.done:
c_box.event.wait(self.__timeout)
if not c_box.event.is_set():
break;
if not c_box.done:
self.__report += "\033[91mError\033[0m" + " Verification with C Code timedout\n"
self.__error_cnt += 1
else:
self.__c_box = c_box.getMessages()
del c_box
class CompareF:
def get_py_lable (self):
return self.__py_lable
def get_hdl_lable (self):
return self.__hdl_lable
def get_hdl_boxes (self):
return self.__hdl_boxes
def get_error_cnt (self):
return self.__error_cnt
def get_report (self):
return self.__report
def get_pycola(self):
return self.__pycola
def __init__(self, stim_file, passone, timeout, wdir, hdl_file, box_only,
resolution, max_x, max_y, continuous, run_only=False):
self.__timeout = timeout
self.__wdir = wdir
self.__max_x__ = max_x
self.__max_y__ = max_y
self.__passone__ = passone
self.__continuous__ = continuous
self.__resolution__ = resolution
self.__hdl_file__ = hdl_file
self.__stim_file__ = stim_file
self.__regmeta = re.compile(r".*metavalue detected.*")
self.__py_colas = {}
self.__py_lables = {}
self.__hdl_lables = {}
self.__px_boxes = {}
self.__hdl_boxes = {}
self.__report = ""
self.__error_cnt=0
if not run_only:
self.__prepare__()
else:
#write stimulus file
j = Image.fromarray(self.__stim_file__.astype(np.uint8))
j.mode = "1";
j.save("../img/sim_in.pbm")
del j
def __prepare__(self):
from cola import ComponentLabeling as cola
self.__pycola = cola(self.__stim_file__, max_x=self.__max_x__,
max_y=self.__max_y__);
#labels of first pass
if self.__passone__:
self.__py_lable = self.__pycola.get_lable_f()
else:
self.__py_lable = self.__pycola.get_lable_s()
#generate empty array to store results of vhdl output
self.__hdl_lable = -1*np.ones(self.__py_lable.shape, dtype=np.int)
if not self.__continuous__:
self.__py_colas[self.__stim_file__] = self.__pycola
self.__py_lables[self.__stim_file__] = self.__py_lable
self.__hdl_lables[self.__stim_file__] = self.__hdl_lable
#write test image file for vhdl
j = Image.fromarray(self.__pycola.get_img().astype(np.uint8))
j.mode = "1";
j.save("../img/sim_in.pbm")
del j
#if stim_file != "../img/sim_in.pbm":
# shutil.copy(stim_file, "../img/sim_in.pbm")
if not box_only:
self.verify_labels(self.__hdl_file__, self.__stim_file__,
self.__resolution__, self.__continuous__)
if not self.__passone__:
if self.__hdl_file__ == "tb_labeling":
self.run_boxes("tb_labeling_box", self.__stim_file__,
self.__resolution__, self.__continuous__)
elif self.__hdl_file__ == "tb_labeling_cont":
self.run_boxes("tb_labeling_box_cont", self.__stim_file__,
self.__resolution__, self.__continuous__)
else:
self.run_boxes(self.__hdl_file__, self.__stim_file__,
self.__resolution__, self.__continuous__)
def verify_labels(self, hdl_file, stim_file, resolution="ns", continuous=False):
vsim = VSIM_parser(hdl_file, "vhdl/", resolution)
vsim.start()
#compile some regex pattern
if continuous:
regline = re.compile(r"File: '([^']+)' Label: ([0-9]+).*")
else:
regline = re.compile(r"(Label:) ([0-9]+).*")
# index of picture
pos_x=0
pos_y=0
while not vsim.done:
vsim.event.wait(self.__timeout)
if not vsim.event.is_set():
break;
messages = vsim.getMessages()
for message in messages:
(time, severity, text) = message
if severity == "Note":
res = regline.match(text)
if res is None:
print(("unparsed text: " + text))
elif res.group(2) is not None:
label = int(res.group(2))
if continuous:
img_file = res.group(1)[3:]
stim_file = img_file
if img_file not in self.__py_lables:
pos_x = 0
pos_y = 0
self.__py_colas[img_file] = cola(stim_file, max_x=self.__max_x__, max_y=self.__max_y__);
self.__py_lables[img_file] = self.__py_colas[img_file].get_lable_s()
self.__hdl_lables[img_file] = -1*np.ones(self.__py_lables[img_file].shape, dtype=np.int)
if pos_y >= len(self.__py_lables[stim_file]):
self.__report += stim_file + ": additional pixel (x=" + str(pos_x) +", y=" + str(pos_y) +")\n"
self.__error_cnt += 1
else:
self.__hdl_lables[stim_file][pos_y][pos_x] = label
if self.__py_lables[stim_file][pos_y][pos_x] != label:
self.__report += ("\033[91mError\033[0m" + " File: "+ stim_file +" at pixel x=" + str(pos_x) + " y=" +
str(pos_y) + " expected: " + str(self.__py_lables[stim_file][pos_y][pos_x]) + " vhdl: " +
str(label) + " at time: " + str(time) + "\n")
self.__error_cnt += 1
pos_x = pos_x + 1
if pos_x == len(self.__py_lable[0]):
pos_y = pos_y + 1
pos_x = 0
elif res.group(2) is not None:
self.__report = "\033[91mError\033[0m" + "Unknown Message: " + text + "\n"
else:
metaval = self.__regmeta.match(text)
if not(severity == "Warning" and metaval is not None):
self.__report += severity + " " + text + "\n"
if severity != "Note" and severity != "Warning":
#self.__error_cnt += 1
None
#TODO report this seperately
if not vsim.done:
self.__report = self.__report + stim_file + ": Output of data reached timeout in 2-pass simulation. Simulation abort\n"
self.__error_cnt += 1
for files in self.__py_lables:
if len(self.__py_lables[files][0]) > pos_y and pos_x != 0:
self.__report = self.__report + files + ": Not all pixels processed. First unprocessed pixel: x=" + str(pos_x+1) + " y=" + str(pos_y+1) + "\n"
self.__error_cnt += 1
del vsim
def run_boxes(self, hdl_file, stim_file, resolution="ns",
continuous=False, compare=True):
vsim = VSIM_parser(hdl_file, self.__wdir, resolution)
vsim.start()
if continuous:
regline = re.compile(r"File: '([^']+)' Box: \(([0-9]+), ([0-9]+)\), \(([0-9]+), ([0-9]+)\).*|Box: (error).*")
else:
regline = re.compile(r"(Box): \(([0-9]+), ([0-9]+)\), \(([0-9]+), ([0-9]+)\).*|Box: (error).*")
cnt={}
if (stim_file not in self.__px_boxes) and compare:
self.__px_boxes[stim_file] = self.__py_colas[stim_file].get_boxes().copy()
self.__hdl_boxes[stim_file] = {}
cnt[stim_file] = 0
elif not compare:
self.__hdl_boxes[stim_file] = {}
cnt[stim_file] = 0
while not vsim.done:
vsim.event.wait(self.__timeout)
if not vsim.event.is_set():
break;
messages = vsim.getMessages()
for message in messages:
(time, severity, text) = message
#print ("test:" + str(message))
if severity == "Note":
res = regline.match(text)
if res is None:
print(("unparsed text: \""+text+ "\""))
elif res.group(6) is not None:
self.__error_cnt += 1
self.__report = "Recognised error with to small heap\n"
elif res.group(2) is not None:
img_file = res.group(1)[3:]
if continuous:
self.__px_boxes[img_file] = self.__px_boxes[stim_file]
self.__hdl_boxes[img_file] = self.__hdl_boxes[stim_file]
cnt[stim_file] = cnt[img_file]
stim_file = img_file
start_x = int(res.group(2))
start_y = int(res.group(3))
end_x = int(res.group(4))
end_y = int(res.group(5))
self.__hdl_boxes[stim_file][cnt[stim_file]] = ((start_x, start_y), (end_x, end_y))
cnt[stim_file] += 1
if compare:
found = False
for b in self.__px_boxes[stim_file]:
((py_start_x, py_start_y), (py_end_x, py_end_y)) = self.__px_boxes[stim_file][b]
if py_start_x == start_x and py_start_y == start_y and py_end_x == end_x and py_end_y == end_y:
found = True
del self.__px_boxes[stim_file][b]
break
if not found:
self.__report += "\033[91mError\033[0m" + " File: '" + stim_file
self.__report += "' VHDL found box ((" + str(start_x) + ", "
self.__report += str(start_y) + "), (" + str(end_x) + ", "
self.__report += str(end_y) + ")) but python not\n"
self.__error_cnt += 1
elif res.group(3) is not None:
self.__report = "\033[91mError\033[0m" + "Unknown Message: " + text
else:
metaval = self.__regmeta.match(text)
if not(severity == "Warning" and metaval is not None):
self.__report += severity + " " + text + "\n"
if severity != "Note" and severity != "Warning":
#self.__error_cnt += 1
#TODO: Report this separatly
None
if compare:
for f in self.__px_boxes:
if self.__px_boxes[f] != {}:
for b in self.__px_boxes[f]:
((start_x, start_y), (end_x, end_y)) = self.__px_boxes[f][b]
self.__report += "\033[91mError\033[0m" + " File: '" + f
self.__report += "' VHDL missing box ((" + str(start_x) + ", "
self.__report += str(start_y) + "), (" + str(end_x) + ", " + str(end_y) + "))\n"
self.__error_cnt += 1
if not vsim.done:
self.__report = self.__report + stim_file + ": Output of data reached timeout in simulation of 2-pass with boundbox calculation. Simulation abort\n"
self.__error_cnt += 1
del vsim
class Exec_parser(threading.Thread):
## Executes a binary file and parses the output
#
# You can use the event.wait to wait for new messages or the done signal
# The boolean done gives you the information if the simulation is done
# @param cmd command to execute
# @param cwd working directory
# @param regex used to parse the output of each line of stdout and
# use the result as parameter to run the eval_line
def __init__(self, cmd, cwd=".", regex = None):
super(Exec_parser, self).__init__()
self.__cmd = cmd;
self.__cwd = cwd
self.event = threading.Event()
self.__sema = threading.Semaphore()
self.__messages = []
self.done = False
self.__stop = False
# store parsed messages
# overwrite this values
self.__regline = re.compile(regex)
print(("Exec: " + str(cmd)))
print(("CWD: " + self.__cwd))
self.__proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=self.__cwd)
def add_message(self, m):
with self.__sema:
self.__messages.append(m)
self.event.set()
## Get all Messages stored in the message queue
def getMessages(self):
with self.__sema:
ret_msg = self.__messages
self.__messages = []
self.event.clear()
return ret_msg
def __del__(self):
self.__stop = True
os.kill(self.__proc.pid, signal.SIGKILL)
## This methode has to evaluate the result of the regex for each line
# you need to overwrite this methode
def eval_line(self, res):
None
def run(self):
line = ' ';
while not self.__stop and line != '':
#apply precompile regex pattern
line = self.__proc.stdout.readline().decode()
res = self.__regline.match(line)
if res is not None:
self.eval_line(res)
# notify the event if done
with self.__sema:
self.event.set()
self.done = True
class VSIM_parser(Exec_parser):
vsim="vsim"
## Executes Modelsim and parses the output
#
# You can use the event.wait to wait for new messages or the done signal
# The boolean done gives you the information if the simulation is done
# @param hdl_entity entity wich should be executed
# @param cwd working directory this has to be the directory where the vlib is stored
def __init__(self, hdl_entity, cwd=".", resolution="ns"):
super(VSIM_parser, self).__init__([self.vsim, "-c", "-do", "run -all;quit", "-t", resolution, hdl_entity], cwd, r"# Time: ([0-9]+ [fpnum]s).*|# \*\* (Note|Warning|Error|Failure): (.*)")
self.__msg = []
## This methode has to evaluate the result of the regex for each line
def eval_line(self, res):
if res.group(1) is not None:
# this is the output of a time info
for m in self.__msg:
(severity, text) = m
self.add_message((res.group(1), severity, text))
self.__msg = []
else:
if res.group(2) is not None:
severity = res.group(2)
if res.group(3) is not None:
self.__msg.append((severity, res.group(3)))
class C_parser(Exec_parser):
## Executes Cpp Code and parses the output
#
# You can use the event.wait to wait for new messages or the done signal
# The boolean done gives you the information if the simulation is done
# @param cwd working directory this has to be the directory where the vlib is stored
def __init__(self, cwd=ccl_c_dir):
super(C_parser, self).__init__(["./ccl"], cwd, r"Processing file '([^']+)' and .*|Completed object:\[([0-9]+), ([0-9]+)\]x\[([0-9]+), ([0-9]+)\].*")
self.__file=""
## This methode has to evaluate the result of the regex for each line
def eval_line(self, res):
if res.group(1) is not None:
# filename of analyzed file
self.__file = res.group(1)
else:
if res.group(2) is not None and res.group(3) is not None and res.group(4) is not None and res.group(5) is not None :
self.add_message((self.__file, int(res.group(2)), int(res.group(3)), int(res.group(4)), int(res.group(5))))
if __name__== "__main__":
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-s", "--sim-file", dest="sim_file",
help="filename for which the simulation should run and the result be visualized")
parser.add_option("-p", "--pass-one", dest="passone", action="store_true",
help="only the first pass will be analyzed otherwise the lables after the second pass and the boundboxes will be analyzed")
parser.add_option("-u", "--uart-tb", dest="uart_tb", action="store_true",
help="Simulates the uart_tb and compare the output with the python implementation")
parser.add_option("-n", "--continuous", dest="continuous", action="store_true",
help="Sends all Pictures in one continuous stream to the DUT")
parser.add_option("-t", "--timeout", dest="timeout", type="float", default=120.0,
help="seconds (as float) how long the time between two outputs before abort the simulation")
parser.add_option("-c", dest="c", action="store_true",
help="Checks the Python boundbox calculation against the cpp")
parser.add_option("-v", "--vhdl-dut", dest="v", action="store_true",
help="Checks the Python boundbox calculation against the vhdl DUT")
parser.add_option("--no-lables", dest="nl", action="store_true",
help="Don't check lables")
parser.add_option("-x", "--max-x", dest="max_x", type="int", default=32,
help="Max width of image send to ccl")
parser.add_option("-y", "--max-y", dest="max_y", type="int", default=32,
help="Max height of image send to ccl")
parser.add_option("-d", "--input-dir", dest="indir" , default="../img/",
help="Input dir used to check all Files")
parser.add_option("-e", "--file-extension", dest="fext", default="pbm",
help="File extension for the input dir run (default \"pbm\")")
(option, args) = parser.parse_args()
fext = option.fext
indir = option.indir
box_only = False
hdl_file = "tb_labeling"
resolution = "ns"
if option.uart_tb:
hdl_file = "tb_com_uart"
resolution = "ps"
box_only = True
if option.passone:
hdl_file = "tb_labeling_p1"
wdir="vhdl/"
if option.v:
wdir="vhdl/ccl_dut/"
box_only = True
if option.nl:
box_only = True
if (not option.c) and option.sim_file:
if option.passone:
comp_first=CompareF(option.sim_file, option.passone, option.timeout, wdir,
hdl_file, box_only, resolution, option.max_x,
option.max_y, False)
comp_first.get_pycola().plot_fp_add('First Pass HDL',
comp_first.get_hdl_lable())
else:
comp_first=CompareF(option.sim_file, False, option.timeout, wdir,
hdl_file, box_only, resolution, option.max_x,
option.max_y, False)
errors = comp_first.get_error_cnt()
print(str(errors) + " errors reported")
print("error report: \n" + comp_first.get_report())
if box_only:
boxes = comp_first.get_hdl_boxes()
if len(boxes) == 1:
for k in boxes:
comp_first.get_pycola().plot_sp_add('Boxes HDL', None, boxes[k])
elif len(boxes) == 0:
comp_first.get_pycola().plot_sp_add('Boxes HDL', None, None)
else:
print ("more outputs received than expected")
print((str(boxes)))
else:
boxes = comp_first.get_hdl_boxes()
if len(boxes) <= 1:
for k in boxes:
comp_first.get_pycola().plot_sp_add('Second Pass HDL',
comp_first.get_hdl_lable(), boxes[k])
elif len(boxes) == 0:
comp_first.get_pycola().plot_sp_add('Second Pass HDL',
comp_first.get_hdl_lable(), None)
else:
print ("more outputs received than expected")
print((str(boxes)))
else:
# run verification of all availible stimuli files and generate a report
# count errors
errors=0
chkdfiles=""
err_by_file={}
report=""
if option.c:
cmp_cp = CompareCP(option.timeout, option.max_x, option.max_y, option.sim_file)
errors = cmp_cp.get_error_cnt()
print((cmp_cp.get_report()))
elif option.continuous:
cnt = 0
filenames = ""
for files in glob.glob(indir + "/*." + option.fext):
if files != indir + "/sim_in." + fext and files != indir + "\\sim_in."+fext:
filenames += "../" + files + "\n"
cnt += 1
f = open("../img/continuous.files", 'w')
f.write(str(cnt) + "\n")
f.write(str(option.max_x) + "\n")
f.write(str(option.max_y) + "\n")
f.write(filenames)
f.close()
hdl_file="tb_labeling_cont"
comp_first=CompareF(files, option.passone, option.timeout, wdir, hdl_file,
box_only, resolution, option.max_x, option.max_y, True)
errors = errors + comp_first.get_error_cnt()
print((comp_first.get_report()))
else:
#run vhdl simulation for each input file
for files in glob.glob(indir + "/*."+fext):
if files != indir + "/sim_in." +fext and files != indir + "\\sim_in." +fext:
print(("\n\nStart verification with input of " + files+"\n"))
chkdfiles = chkdfiles + files +'\n'
comp_first=CompareF(files, option.passone, option.timeout, wdir,
hdl_file, box_only, resolution, option.max_x, option.max_y, False)
errors = errors + comp_first.get_error_cnt()
err_by_file[files] = comp_first.get_error_cnt()
print((comp_first.get_report()))
print("Verification with the following files:")
for filename in err_by_file:
if err_by_file[filename] == 0:
print(("\033[92m" + filename + "\033[0m"))
else:
print(("\033[91m" + filename + " errors: " + str(err_by_file[filename]) + "\033[0m"))
if errors == 0:
print("\033[92mVerification successful\033[0m")
else:
print(report)
print(("\033[91mVerification failed\033[0m with " + str(errors) + " errors"))
if wdir == "vhdl/ccl_dut/":
print(("The verification is only valid if you run ./mk_build.sh in "+wdir))
print("Don't forget to run ./mk_synthesis.sh before a synthesis run")
|
[
"os.mkdir",
"subprocess.Popen",
"os.remove",
"optparse.OptionParser",
"converter.Img_conv",
"numpy.ones",
"os.kill",
"threading.Event",
"glob.glob",
"cola.ComponentLabeling",
"threading.Semaphore",
"re.compile"
] |
[((21936, 21950), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (21948, 21950), False, 'from optparse import OptionParser\n'), ((2045, 2080), 'glob.glob', 'glob.glob', (["(ccl_c_dir + '/img/*.pbm')"], {}), "(ccl_c_dir + '/img/*.pbm')\n", (2054, 2080), False, 'import glob\n'), ((2130, 2152), 're.compile', 're.compile', (['""".*/(.*)$"""'], {}), "('.*/(.*)$')\n", (2140, 2152), False, 'import re\n'), ((6778, 6814), 're.compile', 're.compile', (['""".*metavalue detected.*"""'], {}), "('.*metavalue detected.*')\n", (6788, 6814), False, 'import re\n'), ((7382, 7450), 'cola.ComponentLabeling', 'cola', (['self.__stim_file__'], {'max_x': 'self.__max_x__', 'max_y': 'self.__max_y__'}), '(self.__stim_file__, max_x=self.__max_x__, max_y=self.__max_y__)\n', (7386, 7450), True, 'from cola import ComponentLabeling as cola\n'), ((18098, 18115), 'threading.Event', 'threading.Event', ([], {}), '()\n', (18113, 18115), False, 'import threading\n'), ((18138, 18159), 'threading.Semaphore', 'threading.Semaphore', ([], {}), '()\n', (18157, 18159), False, 'import threading\n'), ((18334, 18351), 're.compile', 're.compile', (['regex'], {}), '(regex)\n', (18344, 18351), False, 'import re\n'), ((18449, 18510), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'stdout': 'subprocess.PIPE', 'cwd': 'self.__cwd'}), '(cmd, stdout=subprocess.PIPE, cwd=self.__cwd)\n', (18465, 18510), False, 'import subprocess\n'), ((18930, 18970), 'os.kill', 'os.kill', (['self.__proc.pid', 'signal.SIGKILL'], {}), '(self.__proc.pid, signal.SIGKILL)\n', (18937, 18970), False, 'import os\n'), ((1960, 1988), 'os.mkdir', 'os.mkdir', (["(ccl_c_dir + '/img')"], {}), "(ccl_c_dir + '/img')\n", (1968, 1988), False, 'import os\n'), ((2094, 2110), 'os.remove', 'os.remove', (['files'], {}), '(files)\n', (2103, 2110), False, 'import os\n'), ((2249, 2274), 'glob.glob', 'glob.glob', (['"""../img/*.pbm"""'], {}), "('../img/*.pbm')\n", (2258, 2274), False, 'import glob\n'), ((2708, 2746), 'converter.Img_conv', 'Img_conv', (['file_show', 'max_x', 'max_y', '(0.5)'], {}), '(file_show, max_x, max_y, 0.5)\n', (2716, 2746), True, 'from converter import Img_conv as Img_conv\n'), ((3188, 3213), 'glob.glob', 'glob.glob', (['"""../img/*.pbm"""'], {}), "('../img/*.pbm')\n", (3197, 3213), False, 'import glob\n'), ((3513, 3554), 'cola.ComponentLabeling', 'cola', (['file_show'], {'max_x': 'max_x', 'max_y': 'max_y'}), '(file_show, max_x=max_x, max_y=max_y)\n', (3517, 3554), True, 'from cola import ComponentLabeling as cola\n'), ((7751, 7795), 'numpy.ones', 'np.ones', (['self.__py_lable.shape'], {'dtype': 'np.int'}), '(self.__py_lable.shape, dtype=np.int)\n', (7758, 7795), True, 'import numpy as np\n'), ((9301, 9348), 're.compile', 're.compile', (['"""File: \'([^\']+)\' Label: ([0-9]+).*"""'], {}), '("File: \'([^\']+)\' Label: ([0-9]+).*")\n', (9311, 9348), False, 'import re\n'), ((9386, 9419), 're.compile', 're.compile', (['"""(Label:) ([0-9]+).*"""'], {}), "('(Label:) ([0-9]+).*')\n", (9396, 9419), False, 'import re\n'), ((13049, 13161), 're.compile', 're.compile', (['"""File: \'([^\']+)\' Box: \\\\(([0-9]+), ([0-9]+)\\\\), \\\\(([0-9]+), ([0-9]+)\\\\).*|Box: (error).*"""'], {}), '(\n "File: \'([^\']+)\' Box: \\\\(([0-9]+), ([0-9]+)\\\\), \\\\(([0-9]+), ([0-9]+)\\\\).*|Box: (error).*"\n )\n', (13059, 13161), False, 'import re\n'), ((13193, 13291), 're.compile', 're.compile', (['"""(Box): \\\\(([0-9]+), ([0-9]+)\\\\), \\\\(([0-9]+), ([0-9]+)\\\\).*|Box: (error).*"""'], {}), "(\n '(Box): \\\\(([0-9]+), ([0-9]+)\\\\), \\\\(([0-9]+), ([0-9]+)\\\\).*|Box: (error).*'\n )\n", (13203, 13291), False, 'import re\n'), ((26581, 26619), 'glob.glob', 'glob.glob', (["(indir + '/*.' + option.fext)"], {}), "(indir + '/*.' + option.fext)\n", (26590, 26619), False, 'import glob\n'), ((27432, 27463), 'glob.glob', 'glob.glob', (["(indir + '/*.' + fext)"], {}), "(indir + '/*.' + fext)\n", (27441, 27463), False, 'import glob\n'), ((2385, 2419), 'converter.Img_conv', 'Img_conv', (['files', 'max_x', 'max_y', '(0.5)'], {}), '(files, max_x, max_y, 0.5)\n', (2393, 2419), True, 'from converter import Img_conv as Img_conv\n'), ((3359, 3396), 'cola.ComponentLabeling', 'cola', (['files'], {'max_x': 'max_x', 'max_y': 'max_y'}), '(files, max_x=max_x, max_y=max_y)\n', (3363, 3396), True, 'from cola import ComponentLabeling as cola\n'), ((10381, 10440), 'cola.ComponentLabeling', 'cola', (['stim_file'], {'max_x': 'self.__max_x__', 'max_y': 'self.__max_y__'}), '(stim_file, max_x=self.__max_x__, max_y=self.__max_y__)\n', (10385, 10440), True, 'from cola import ComponentLabeling as cola\n'), ((10608, 10663), 'numpy.ones', 'np.ones', (['self.__py_lables[img_file].shape'], {'dtype': 'np.int'}), '(self.__py_lables[img_file].shape, dtype=np.int)\n', (10615, 10663), True, 'import numpy as np\n')]
|
"""
Simple audio clustering
1. Get the embeddings - at an interval of 0.5s each
2. Get the VAD - variable interval
3. Get embeddings for a VAD interval -> Take average of the embeddings
4. Get the ground truth for embedding for each speaker - marked 0.5s interval
5. L2 Normalize the embeddings before taking a distance measure
6. Clustering - Speaker Verification Task
1. Fix the ground truth embedding as the centroid for each speaker
2. Cluster all the points to the closest centroid
3. Verify the output
"""
import os
import argparse
import json
import yaml
import pickle
import numpy as np
import pandas as pd
import utils
import isat_diarization as isat_d
import constants
def dist_emb(emb_1, emb_2, dist_type="euclid"):
"""
Distance between two embeddings
"""
dist = None
if dist_type == "euclid":
# Euclidean distance
dist = np.linalg.norm(emb_1 - emb_2)
elif dist_type == "cosine":
# Cosine similarity
dist = np.dot(emb_1, emb_2) / (np.linalg.norm(emb_1) * np.linalg.norm(emb_2))
return dist
def cluster_gt(embeddings, vad, dict_gt_speakers):
dict_clusters = {
val: {
"embedding_id": key,
"embedding_val": embeddings[key],
} for key, val in dict_gt_speakers.items()
}
list_emb = [(dict_gt_speakers[key], embeddings[key]) for key, val in dict_gt_speakers.items()]
labels = []
for emb_index, emb_actual in enumerate(embeddings):
min_dist = np.inf
label = "NoSpeaker"
for speaker, emb_ref in list_emb:
dist = dist_emb(emb_ref, emb_actual)
if min_dist > dist:
min_dist = dist
label = speaker
labels.append(label)
return labels
def normalize_embeddings(embeddings):
"""
https://numpy.org/doc/stable/reference/generated/numpy.linalg.norm.html
"""
l2_norm = np.linalg.norm(embeddings, ord=2)
return embeddings
def get_embeddings(audio_path, dir_target, src="gen"):
"""
:param src: "gen" for generate, "file" for read from file
"""
embeddings = None
if src == "gen":
print(f"Generating embeddings")
embeddings = isat_d.gen_embeddings(audio_path, dir_target)
elif src == "file":
embeddings_path = os.path.join(dir_target, "embeddings.pkl")
with open(embeddings_path, "rb") as fh:
embeddings = pickle.load(fh)
print(f"Loaded embeddings from: {embeddings_path}")
print(f"embeddings: type: {type(embeddings)}")
embeddings_data = embeddings.data
return embeddings_data
def get_vad(vad_path):
with open(vad_path, "rb") as fh:
vad = json.load(fh)
print(f"Loaded vad from: {vad_path}")
print(f"vad: type: {type(vad)}")
return vad
def get_gt_emb():
dict_gt = {
0: "A",
20: "B",
30: "C",
}
return dict_gt
def yml_dump():
import yaml
dict_gt = {
0: {
"audio_path": "x.wav",
"output_path": "../outputs",
"num_speakers": 2,
"ground_truths": [
{
"start": 2.1,
"end": 3.1,
"id": 123,
"name": "Krishna"
},
{
"start": 4.4,
"end": 7.1,
"id": 500,
"name": "Gauranga"
}
]
},
1: {
"audio_path": "y.wav",
"output_path": "../outputs",
"num_speakers": 2,
"ground_truths": [
{
"start": 2.1,
"end": 3.1,
"id": 123,
"name": "Krishna"
},
{
"start": 4.4,
"end": 7.1,
"id": 500,
"name": "Gauranga"
}
]
}
}
with open("../data/spkr_diarization_gt_temp.yml", "w") as fh:
yaml.dump(dict_gt, fh)
def round_off_embedding(start_time, float_embed_width=0.5):
"""Round a number to the closest half integer.
round_off_embedding(1.3)
1.5
round_off_embedding(2.6)
2.5
round_off_embedding(3.0)
3.0
round_off_embedding(4.1)
4.0
round_off_embedding(4.1, 0.25)
4.0
"""
reciprocal = int(1 / float_embed_width)
embed_id = round(start_time * reciprocal) / reciprocal
embed_id = round(start_time * reciprocal)
return embed_id
def get_embed_from_start_end(dict_all_gt):
dict_all_embed_gt = {}
for file_index, dict_gt in dict_all_gt.items():
dict_embed_gt = {
"ground_truths": [],
"audio_path": dict_gt["audio_path"],
"output_path": dict_gt["output_path"],
"num_speakers": dict_gt["num_speakers"]
}
list_ground_truths = []
for spkr_index, dict_spkr in enumerate(dict_gt["ground_truths"]):
start = dict_spkr["start"]
# end = dict_spkr["end"]
# id = dict_spkr["id"]
# name = dict_spkr["name"]
embed_start_id = round_off_embedding(start)
dict_gt = {
"embed_start_id": embed_start_id,
"id": dict_spkr["id"],
"name": dict_spkr["name"]
}
list_ground_truths.append(dict_gt)
dict_embed_gt["ground_truths"] = list_ground_truths
dict_all_embed_gt[file_index] = dict_embed_gt
return dict_all_embed_gt
def cluster_all(gt_yml_fp):
dict_all_embed_gt = read_ground_truths(gt_yml_fp)
status = "Done"
for file_index, dict_gt in dict_all_embed_gt.items():
list_ground_truths = dict_gt["ground_truths"]
audio_path = dict_gt["audio_path"]
output_path = dict_gt["output_path"]
dict_emb_gt = {dict_spkr["embed_start_id"]: dict_spkr["name"] for dict_spkr in list_ground_truths}
# for spkr_index, dict_spkr in enumerate(list_ground_truths):
# dict_emb_gt[dict_spkr["embed_start_id"]] = dict_spkr["name"]
if not os.path.exists(output_path):
os.makedirs(output_path)
run_clustering(audio_path, output_path, dict_emb_gt)
return status
def read_ground_truths(gt_yml_fp):
with open(gt_yml_fp, "r") as fh:
dict_all_gt = yaml.load(fh)
print(dict_all_gt)
dict_all_embed_gt = get_embed_from_start_end(dict_all_gt)
print(dict_all_embed_gt)
return dict_all_embed_gt
def run_clustering(audio_path, output_path, dict_gt):
embeddings = get_embeddings(audio_path, output_path)
# vad_path = os.path.join(output_path, "vad.json")
# vad = get_vad(vad_path)
vad = None
labels = cluster_gt(embeddings, vad, dict_gt)
print(utils.print_list(labels, "Clustered Embeddings"))
df = pd.DataFrame()
df["embed_index"] = [x for x in range(len(labels))]
df["labels"] = labels
out_path = os.path.join(output_path, "cluster_labels.csv")
df.to_csv(out_path, index=False)
return df
def run_yaml(args):
gt_yml_fp = args.get("gt_yml_fp", "../data/spkr_diarization_gt.yml")
cluster_all(gt_yml_fp)
def run(args):
audio_path = args.get("audio_path", "../no/audio")
output_path = args.get("output_path", "../outputs")
dict_gt = get_gt_emb()
run_clustering(audio_path, output_path, dict_gt)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--audio_path",
type=str,
help="audio filepath",
default="../data/panel_discussion_0045_15s.wav")
parser.add_argument("--output_path",
type=str,
help="output_path",
default="../outputs/panel_discussion_0045_15s_5")
parser.add_argument("--gt_yml_fp",
type=str,
help="ground truth yaml file path",
default="../data/spkr_diarization_gt.yml")
parser.add_argument("--config_path",
type=str,
help="config_path",
default="../configs/config_5.yml")
# parser.add_argument("-v", "--verbose", action="store_true",
# help="increase output verbosity")
args = parser.parse_args()
dict_args = vars(args)
dir_output = dict_args.get("output_path", "../outputs")
if not os.path.exists(dir_output):
os.makedirs(dir_output)
else:
print(f"ATTENTION: directory: [{dir_output}] already exists.")
return dict_args
def main():
args = parse_args()
run_yaml(args)
# yml_dump()
# print(round_off_embedding(4.1, 0.25))
# print(round_off_embedding(4.1, 0.35))
# print(round_off_embedding(4.1, 0.5))
# print(round_off_embedding(4.35, 0.25))
# print(round_off_embedding(4.35, 0.35))
# print(round_off_embedding(4.35, 0.5))
# read_ground_truths()
if __name__ == '__main__':
main()
|
[
"pandas.DataFrame",
"yaml.load",
"json.load",
"argparse.ArgumentParser",
"os.makedirs",
"yaml.dump",
"os.path.exists",
"isat_diarization.gen_embeddings",
"utils.print_list",
"pickle.load",
"numpy.linalg.norm",
"numpy.dot",
"os.path.join"
] |
[((1913, 1946), 'numpy.linalg.norm', 'np.linalg.norm', (['embeddings'], {'ord': '(2)'}), '(embeddings, ord=2)\n', (1927, 1946), True, 'import numpy as np\n'), ((6918, 6932), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (6930, 6932), True, 'import pandas as pd\n'), ((7031, 7078), 'os.path.join', 'os.path.join', (['output_path', '"""cluster_labels.csv"""'], {}), "(output_path, 'cluster_labels.csv')\n", (7043, 7078), False, 'import os\n'), ((7495, 7520), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (7518, 7520), False, 'import argparse\n'), ((886, 915), 'numpy.linalg.norm', 'np.linalg.norm', (['(emb_1 - emb_2)'], {}), '(emb_1 - emb_2)\n', (900, 915), True, 'import numpy as np\n'), ((2209, 2254), 'isat_diarization.gen_embeddings', 'isat_d.gen_embeddings', (['audio_path', 'dir_target'], {}), '(audio_path, dir_target)\n', (2230, 2254), True, 'import isat_diarization as isat_d\n'), ((2697, 2710), 'json.load', 'json.load', (['fh'], {}), '(fh)\n', (2706, 2710), False, 'import json\n'), ((4086, 4108), 'yaml.dump', 'yaml.dump', (['dict_gt', 'fh'], {}), '(dict_gt, fh)\n', (4095, 4108), False, 'import yaml\n'), ((6424, 6437), 'yaml.load', 'yaml.load', (['fh'], {}), '(fh)\n', (6433, 6437), False, 'import yaml\n'), ((6858, 6906), 'utils.print_list', 'utils.print_list', (['labels', '"""Clustered Embeddings"""'], {}), "(labels, 'Clustered Embeddings')\n", (6874, 6906), False, 'import utils\n'), ((8544, 8570), 'os.path.exists', 'os.path.exists', (['dir_output'], {}), '(dir_output)\n', (8558, 8570), False, 'import os\n'), ((8580, 8603), 'os.makedirs', 'os.makedirs', (['dir_output'], {}), '(dir_output)\n', (8591, 8603), False, 'import os\n'), ((2306, 2348), 'os.path.join', 'os.path.join', (['dir_target', '"""embeddings.pkl"""'], {}), "(dir_target, 'embeddings.pkl')\n", (2318, 2348), False, 'import os\n'), ((6181, 6208), 'os.path.exists', 'os.path.exists', (['output_path'], {}), '(output_path)\n', (6195, 6208), False, 'import os\n'), ((6222, 6246), 'os.makedirs', 'os.makedirs', (['output_path'], {}), '(output_path)\n', (6233, 6246), False, 'import os\n'), ((992, 1012), 'numpy.dot', 'np.dot', (['emb_1', 'emb_2'], {}), '(emb_1, emb_2)\n', (998, 1012), True, 'import numpy as np\n'), ((2422, 2437), 'pickle.load', 'pickle.load', (['fh'], {}), '(fh)\n', (2433, 2437), False, 'import pickle\n'), ((1016, 1037), 'numpy.linalg.norm', 'np.linalg.norm', (['emb_1'], {}), '(emb_1)\n', (1030, 1037), True, 'import numpy as np\n'), ((1040, 1061), 'numpy.linalg.norm', 'np.linalg.norm', (['emb_2'], {}), '(emb_2)\n', (1054, 1061), True, 'import numpy as np\n')]
|
import numpy as np
from distributions.distribution import Distribution
class NonParametric(Distribution):
"""
Provides functions for a non-parametric forecast distribution.
"""
@staticmethod
def pdf(x, pdf_x, x_eval):
pass
@staticmethod
def cdf(x, cdf_x, x_eval):
"""
Computes the CDF of the non-parametric distribution at x given the CDF at evaluation points,
by linear interpolation.
"""
# Linear interpolation
insertion_points = np.searchsorted(x_eval, x)
r = np.minimum(insertion_points, len(x_eval) - 1)
l = np.maximum(0, insertion_points - 1)
idx = np.arange(len(x))
slope = (cdf_x[r, idx] - cdf_x[l, idx]) / np.maximum(x_eval[r] - x_eval[l], 1e-6)
return cdf_x[l, idx] + slope * (x - x_eval[l])
@staticmethod
def mean(pdf_x, x_eval):
"""
Computes the mean of the non-parametric distribution by integrating the PDF at evaluation points,
using the trapezoidal rule.
"""
return np.trapz(
y=x_eval[:, np.newaxis] * pdf_x,
x=x_eval[:, np.newaxis],
axis=0
)
@staticmethod
def var(pdf_x, x_eval):
"""
Computes the variance of the non-parametric distribution by integrating the PDF at evaluation points,
using the trapezoidal rule.
"""
return np.trapz(
y=x_eval[:, np.newaxis] ** 2 * pdf_x,
x=x_eval[:, np.newaxis],
axis=0
) - np.trapz(
y=x_eval[:, np.newaxis] * pdf_x,
x=x_eval[:, np.newaxis],
axis=0
) ** 2
@staticmethod
def percentile(p, cdf_x, x_eval):
"""
Computes the p-percentile of the non-parametric distribution given the CDF at evaluation points,
by linear interpolation.
"""
# Linear interpolation
insertion_points = []
for i in range(cdf_x.shape[1]):
insertion_points.append(np.searchsorted(cdf_x[:, i], p / 100))
insertion_points = np.array(insertion_points)
r = np.minimum(insertion_points, len(cdf_x) - 1)
l = np.maximum(0, insertion_points - 1)
idx = np.arange(cdf_x.shape[1])
slope = (x_eval[r] - x_eval[l]) / np.maximum(cdf_x[r, idx] - cdf_x[l, idx], 1e-6)
return x_eval[l] + slope * (p / 100 - cdf_x[l, idx])
@staticmethod
def crps(x, cdf_x, x_eval):
"""
Computes the Continuous Ranked Probability Score (CRPS) of the non-parametric distribution with true value x,
using the trapezoidal rule.
"""
return np.trapz(
y=(cdf_x - (x_eval[:, np.newaxis] >= x[np.newaxis, :])) ** 2,
x=x_eval[:, np.newaxis],
axis=0
)
|
[
"numpy.trapz",
"numpy.maximum",
"numpy.searchsorted",
"numpy.array",
"numpy.arange"
] |
[((522, 548), 'numpy.searchsorted', 'np.searchsorted', (['x_eval', 'x'], {}), '(x_eval, x)\n', (537, 548), True, 'import numpy as np\n'), ((619, 654), 'numpy.maximum', 'np.maximum', (['(0)', '(insertion_points - 1)'], {}), '(0, insertion_points - 1)\n', (629, 654), True, 'import numpy as np\n'), ((1061, 1135), 'numpy.trapz', 'np.trapz', ([], {'y': '(x_eval[:, np.newaxis] * pdf_x)', 'x': 'x_eval[:, np.newaxis]', 'axis': '(0)'}), '(y=x_eval[:, np.newaxis] * pdf_x, x=x_eval[:, np.newaxis], axis=0)\n', (1069, 1135), True, 'import numpy as np\n'), ((2091, 2117), 'numpy.array', 'np.array', (['insertion_points'], {}), '(insertion_points)\n', (2099, 2117), True, 'import numpy as np\n'), ((2187, 2222), 'numpy.maximum', 'np.maximum', (['(0)', '(insertion_points - 1)'], {}), '(0, insertion_points - 1)\n', (2197, 2222), True, 'import numpy as np\n'), ((2237, 2262), 'numpy.arange', 'np.arange', (['cdf_x.shape[1]'], {}), '(cdf_x.shape[1])\n', (2246, 2262), True, 'import numpy as np\n'), ((2658, 2766), 'numpy.trapz', 'np.trapz', ([], {'y': '((cdf_x - (x_eval[:, np.newaxis] >= x[np.newaxis, :])) ** 2)', 'x': 'x_eval[:, np.newaxis]', 'axis': '(0)'}), '(y=(cdf_x - (x_eval[:, np.newaxis] >= x[np.newaxis, :])) ** 2, x=\n x_eval[:, np.newaxis], axis=0)\n', (2666, 2766), True, 'import numpy as np\n'), ((737, 777), 'numpy.maximum', 'np.maximum', (['(x_eval[r] - x_eval[l])', '(1e-06)'], {}), '(x_eval[r] - x_eval[l], 1e-06)\n', (747, 777), True, 'import numpy as np\n'), ((1414, 1493), 'numpy.trapz', 'np.trapz', ([], {'y': '(x_eval[:, np.newaxis] ** 2 * pdf_x)', 'x': 'x_eval[:, np.newaxis]', 'axis': '(0)'}), '(y=x_eval[:, np.newaxis] ** 2 * pdf_x, x=x_eval[:, np.newaxis], axis=0)\n', (1422, 1493), True, 'import numpy as np\n'), ((2305, 2353), 'numpy.maximum', 'np.maximum', (['(cdf_x[r, idx] - cdf_x[l, idx])', '(1e-06)'], {}), '(cdf_x[r, idx] - cdf_x[l, idx], 1e-06)\n', (2315, 2353), True, 'import numpy as np\n'), ((1542, 1616), 'numpy.trapz', 'np.trapz', ([], {'y': '(x_eval[:, np.newaxis] * pdf_x)', 'x': 'x_eval[:, np.newaxis]', 'axis': '(0)'}), '(y=x_eval[:, np.newaxis] * pdf_x, x=x_eval[:, np.newaxis], axis=0)\n', (1550, 1616), True, 'import numpy as np\n'), ((2025, 2062), 'numpy.searchsorted', 'np.searchsorted', (['cdf_x[:, i]', '(p / 100)'], {}), '(cdf_x[:, i], p / 100)\n', (2040, 2062), True, 'import numpy as np\n')]
|
import numpy as np
from math import log, sqrt, ceil
import random
import string
from copy import copy
import pyximport
from tabulate import tabulate
pyximport.install()
from ..util import math_functions
import matplotlib.pyplot as plt
import textwrap
from textwrap import dedent
from multiprocessing import Pool
from multiprocessing.pool import ThreadPool
from joblib import Parallel, delayed
class FuzzyNode:
feature = None
is_terminal=None
classification=None
# __slots__ = ['is_terminal',
# 'classification',
# 'feature'
# 'partitioning']
class FuzzyPartitioning:
def __init__(self):
self.partitions = []
self.gain = None
# __slots__ = ['partitions', 'gain']
class FuzzyPartition:
__slots__ = ['f', 'node', 'properties', 'ranges']
class FuzzySetProperties:
__slots__ = ['cardinality',
'entropy',
'data',
'memberships']
# noinspection PyAttributeOutsideInit,PyPropertyAccess,PyUnresolvedReferences
class RandomFuzzyTree:
def __init__(self,
n_jobs=1,
p="sqrt",
terminal_n_threshold=10,
categorical_features=[],
a_cut = 0.5,
test_generation_file=None,
test_indendation_level=1):
self.test_generation_file = test_generation_file
self.test_cases_generated = 0
self.n_jobs = n_jobs
self.p = p
self.is_fit = False
self.terminal_n_threshold = terminal_n_threshold
self.categorical_features = categorical_features
self.a_cut = a_cut
self.test_indentation_level = test_indendation_level
def fit(self, data, ranges, copy_data=False, classes=(1, 2)):
self.classes = classes
if copy_data:
data = np.copy(data)
self.ranges = ranges
self.n_feature = self.count_features(data)
if self.p == "sqrt":
self.p = ceil(sqrt(self.n_feature))
elif self.p == "log":
self.p = ceil(log(self.n_feature, 2))
elif self.p == "all":
self.p = self.n_feature
tree = self.build_tree(data, np.array([1.0 for d in data]))
self.root = tree
self.is_fit = True
def predict(self, x):
assert self.is_fit
memberships = self.predict_memberships(x)
return max(memberships)
def predict_memberships(self, x):
memberships = dict([(c, 0) for c in self.classes])
self.forward_pass(memberships, x, self.root)
return memberships
def score(self, data):
correct = 0
for x in data:
if self.predict(x[:-1]) == x[-1]:
correct += 1
return correct / data.shape[0]
def build_tree(self, data, memberships, lvl=0, ranges=None):
if ranges == None:
ranges = self.ranges
# print("\t\t Bulting tree lvl %d" % (lvl + 1) )
regular_features = self.get_regular_features(data)
if len(regular_features) != 0:
node = self.select_partitioning(data, memberships, regular_features, ranges)
else:
node = self.generate_leaf(data, memberships)
if node.is_terminal or self.is_terminal(node, data, memberships):
node.is_terminal = True
node.classification = self.classification(data, memberships)
else:
for p in node.partitioning.partitions:
next_ranges = copy(ranges)
next_ranges[node.feature] = p.ranges[node.feature]
p.node = self.build_tree(p.properties.data,
p.properties.memberships,
lvl + 1,
next_ranges)
return node
def generate_leaf(self, data, memberships):
node = FuzzyNode()
node.is_terminal = True
node.classification = self.classification(data, memberships)
return node
def select_partitioning(self, data, memberships, regular_features, ranges):
node = FuzzyNode()
features = np.random.choice(regular_features,
min(self.p, len(regular_features)),
replace=False)
feature_partitionings = {}
for feature in features:
feature_partitionings[feature] = \
self.best_partitioning(feature, data, memberships, ranges)
node.feature = max(feature_partitionings,
key=lambda x: feature_partitionings[x].gain)
node.partitioning = feature_partitionings[node.feature]
node.partitioning.gain = self._fuzzy_entropy(data, memberships)# + node.partitioning.gain
return node
def get_regular_features(self, data):
regular_features = []
for i in range(len(self.ranges)):
curr_range = self.ranges[i]
inds = np.logical_and(data[:, i] != curr_range[0], data[:, i] != curr_range[1]).nonzero()[0]
if curr_range[0] != curr_range[1] and inds.shape[0] != 0:
regular_features.append(i)
return regular_features
def is_terminal(self, node, data, memberships):
if memberships.shape[0] == 0:
return True
empty_partitions = 0
for partition in node.partitioning.partitions:
if partition.properties.memberships.shape[0] <= 1:
empty_partitions += 1
if empty_partitions >= 2:
return True
data_classes = data[:, -1]
all_same = True
for i in range(1, data_classes.shape[0]):
if int(data_classes[i]) != int(data_classes[0]):
all_same = False
break
if all_same:
return True
if abs(node.partitioning.gain) <= 0.000001:
return True
else:
return False
def forward_pass(self,
result_memberships,
x,
node,
membership=1):
if node.is_terminal:
for c in self.classes:
result_memberships[c] += node.classification[c] * membership
else:
for partition in node.partitioning.partitions:
next_membership = membership * partition.f(x[node.feature])
next_node = partition.node
self.forward_pass(result_memberships,
x,
next_node,
next_membership)
@staticmethod
def count_features(data):
return data.shape[1] - 1
def classification(self, data, memberships):
classification_val = {}
for c in self.classes:
inds = (data[:, -1] == c).nonzero()[0]
classification_val[c] = np.sum(memberships[inds])
return classification_val
def best_partitioning(self, feature, data, memberships, ranges):
if feature in self.categorical_features:
max_partitioning = FuzzyPartitioning()
max_category = int(self.ranges[feature][1])
min_category = int(self.ranges[feature][0])
for category in range(min_category, max_category + 1):
partition = FuzzyPartition()
partition.properties = FuzzySetProperties()
def f(x):
if int(x) == category:
return 1
else:
return 0
partition.f = f
inds = (data[:, feature] == category).nonzero()[0]
partition.properties.data = data[inds, :]
max_partitioning.partitions.append(partition)
self.set_properties(max_partitioning.partitions,
data,
feature,
memberships)
max_partitioning.gain = \
self.gain(max_partitioning.partitions, memberships)
else:
points = np.unique(data[:, feature])
L, U = self.ranges[feature]
point_partitionings = {}
regular_point_occured = False
last_point = None
meaningful_length = (U - L) / 10
for p in points:
if last_point is None or p - last_point > meaningful_length:
if p != L and p != U:
curr_partitioning = self.partitioning(data, feature, p, memberships, ranges)
if self.count_zero(curr_partitioning) < 2:
regular_point_occured = True
point_partitionings[p] = \
curr_partitioning
last_point = p
if not regular_point_occured:
midpoint = L + (U - L) / 2
max_partitioning = self.partitioning(data,
feature,
midpoint,
memberships,
ranges)
max_partitioning.midpoint = midpoint
else:
max_partitioning_key = max(point_partitionings,
key=lambda x: point_partitionings[x].gain)
max_partitioning = point_partitionings[max_partitioning_key]
max_partitioning.midpoint = max_partitioning_key
self.print_partitioning(max_partitioning, data, feature, ranges)
return max_partitioning
def count_zero(self, partitioning):
cnt = 0
for part in partitioning.partitions:
if part.properties.entropy == 0:
cnt += 1
return cnt
def partitioning(self, data, feature, p, memberships, ranges):
part = FuzzyPartitioning()
L, U = self.ranges[feature]
W_left = 2 * (p - L)
W_middle_left = (p - L)
W_middle_right = (U - p)
W_right = 2 * (U - p)
# TODO: generalize to more
left_partition = FuzzyPartition()
left_partition.f = math_functions.triangular(L,
W_left)
left_partition.ranges = copy(ranges)
left_partition.ranges[feature] = L, p
left_partition.properties = []
middle_partition = FuzzyPartition()
middle_partition.f = \
math_functions.composite_triangular(p,
W_middle_left,
W_middle_right)
middle_partition.ranges = copy(ranges)
middle_partition.ranges[feature] = L, U
middle_partition.properties = []
right_partition = FuzzyPartition()
right_partition.f = math_functions.triangular(U,
W_right)
right_partition.ranges = copy(ranges)
right_partition.ranges[feature] = p, U
right_partition.properties = []
part.partitions = [left_partition,
middle_partition,
right_partition]
self.set_properties(part.partitions, data, feature, memberships)
part.gain = self.gain(part.partitions, memberships)
return part
def print_partitioning(self, partitioning, data, feature, ranges):
rng = ranges[feature]
data = data[data[:, feature].argsort()]
data_table = []
for d in data:
data_arr = [d[-1]]
for partition in partitioning.partitions:
data_arr.append(round(partition.f(d[feature]), 2))
data_table.append(data_arr)
print(tabulate(data_table,
headers=['Class', 'First', 'Second', 'Third'],
tablefmt='orgtbl'))
for partition in partitioning.partitions:
partition_sums = {}
for d in data:
for c in self.classes:
if d[-1] in partition_sums:
if partition.f(d[feature]) >= 0.5:
partition_sums[d[-1]] += partition.f(d[feature])
else:
partition_sums[d[-1]] = 0
print(partition_sums)
print("Gain: ", partitioning.gain)
xs = np.arange(rng[0], rng[1], 0.05).tolist()
for partition in partitioning.partitions:
ys = []
for x in xs:
ys.append(partition.f(x))
plt.plot(xs, ys, color="g")
xs = []
ys = []
zs = []
for d in data:
xs.append(d[feature])
ys.append(0.5)
zs.append(d[-1])
plt.scatter(xs, ys, c=zs)
plt.show()
def set_properties(self, partitions, data, feature, memberships):
for partition in partitions:
prop = self._fuzzy_set_properties(data,
feature,
partition,
memberships)
partition.properties = prop
def gain(self, partitions, memberships):
data_cardinality = np.sum(memberships)
if len(partitions) == 0:
raise ValueError("Empty partitions")
properties = [part.properties for part in partitions]
gain_value = 0
for prop in properties:
gain_value -= (prop.cardinality / data_cardinality) * prop.entropy
return gain_value
def _fuzzy_set_properties(self, data, feature, partition, memberships):
if data.shape.__contains__(0):
raise ValueError("Empty array")
membership_f = np.vectorize(partition.f)
data_at_feature = np.copy(data[:, feature])
set_memberships = membership_f(data_at_feature)
set_memberships = np.multiply(memberships, set_memberships)
non_zero_inds = (set_memberships >= self.a_cut).nonzero()[0]
set_memberships = set_memberships[non_zero_inds]
set_data = data[non_zero_inds, :]
cardinality = np.sum(set_memberships)
entropy = self._fuzzy_entropy(set_data,
set_memberships,
cardinality)
properties = FuzzySetProperties()
properties.cardinality = cardinality
properties.entropy = entropy
non_zero_inds = (set_memberships >= self.a_cut).nonzero()[0]
set_data = data[non_zero_inds, :]
set_memberships = set_memberships[non_zero_inds]
properties.data = set_data
properties.memberships = set_memberships
return properties
def _fuzzy_entropy(self, data, memberships, cardinality=None):
if self.should_generate_tests(data):
self.generate_fuzzy_entropy_test(data,
memberships,
cardinality)
if data.shape.__contains__(0):
return 0
# raise ValueError("Empty array")
entropy = 0
if cardinality is None:
cardinality = np.sum(memberships)
if cardinality != 0:
for c in self.classes:
inds = (data[:, -1] == c).nonzero()[0]
memberships_at_inds = memberships[inds]
proba = np.sum(memberships_at_inds) / cardinality
if proba != 0:
entropy -= proba * log(proba, 2)
return entropy
def should_generate_tests(self, data):
return self.test_generation_file is not None and \
20 < data.shape[0] < 50 and \
self.test_cases_generated < 3
def generate_fuzzy_entropy_test(self, data, memberships, cardinality):
self.test_cases_generated += 1
test_cases_file = open(self.test_generation_file, "a")
print("\t\tGenerating tests")
data = data[:, (-2, -1)].tolist()
memberships = memberships.tolist()
indentation = [" " for i in range(self.test_indentation_level)]
indentation = "".join(indentation)
print("", file=test_cases_file)
test_id = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(5))
print("%sdef testFuzzyEntropy_generated_%s(self):" % (indentation, test_id), file=test_cases_file)
wrapper = textwrap.TextWrapper(initial_indent="%s " % indentation, width=80,
subsequent_indent=' ' * 24)
data_str = "data = np.array(%s)" % (data)
print(wrapper.fill(data_str), file=test_cases_file)
memberships_str = "memberships= np.array(%s)" % (memberships)
print(wrapper.fill(memberships_str), file=test_cases_file)
print("%s cardinality = %s" % (indentation, cardinality), file=test_cases_file)
result = "self.tree._fuzzy_entropy(data, memberships, cardinality)"
print("%s self.assertAlmostEqual(%s, 0, 2)" % (indentation, result), file=test_cases_file)
print("", file=test_cases_file)
test_cases_file.close()
def __str__(self):
raise NotImplementedError()
|
[
"matplotlib.pyplot.show",
"numpy.sum",
"numpy.vectorize",
"numpy.copy",
"numpy.multiply",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.plot",
"math.sqrt",
"copy.copy",
"random.choice",
"numpy.logical_and",
"textwrap.TextWrapper",
"numpy.array",
"tabulate.tabulate",
"numpy.arange",
"math.log",
"pyximport.install",
"numpy.unique"
] |
[((149, 168), 'pyximport.install', 'pyximport.install', ([], {}), '()\n', (166, 168), False, 'import pyximport\n'), ((10474, 10486), 'copy.copy', 'copy', (['ranges'], {}), '(ranges)\n', (10478, 10486), False, 'from copy import copy\n'), ((10860, 10872), 'copy.copy', 'copy', (['ranges'], {}), '(ranges)\n', (10864, 10872), False, 'from copy import copy\n'), ((11159, 11171), 'copy.copy', 'copy', (['ranges'], {}), '(ranges)\n', (11163, 11171), False, 'from copy import copy\n'), ((12980, 13005), 'matplotlib.pyplot.scatter', 'plt.scatter', (['xs', 'ys'], {'c': 'zs'}), '(xs, ys, c=zs)\n', (12991, 13005), True, 'import matplotlib.pyplot as plt\n'), ((13014, 13024), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13022, 13024), True, 'import matplotlib.pyplot as plt\n'), ((13470, 13489), 'numpy.sum', 'np.sum', (['memberships'], {}), '(memberships)\n', (13476, 13489), True, 'import numpy as np\n'), ((13979, 14004), 'numpy.vectorize', 'np.vectorize', (['partition.f'], {}), '(partition.f)\n', (13991, 14004), True, 'import numpy as np\n'), ((14032, 14057), 'numpy.copy', 'np.copy', (['data[:, feature]'], {}), '(data[:, feature])\n', (14039, 14057), True, 'import numpy as np\n'), ((14141, 14182), 'numpy.multiply', 'np.multiply', (['memberships', 'set_memberships'], {}), '(memberships, set_memberships)\n', (14152, 14182), True, 'import numpy as np\n'), ((14375, 14398), 'numpy.sum', 'np.sum', (['set_memberships'], {}), '(set_memberships)\n', (14381, 14398), True, 'import numpy as np\n'), ((16677, 16778), 'textwrap.TextWrapper', 'textwrap.TextWrapper', ([], {'initial_indent': "('%s ' % indentation)", 'width': '(80)', 'subsequent_indent': "(' ' * 24)"}), "(initial_indent='%s ' % indentation, width=80,\n subsequent_indent=' ' * 24)\n", (16697, 16778), False, 'import textwrap\n'), ((1880, 1893), 'numpy.copy', 'np.copy', (['data'], {}), '(data)\n', (1887, 1893), True, 'import numpy as np\n'), ((2237, 2268), 'numpy.array', 'np.array', (['[(1.0) for d in data]'], {}), '([(1.0) for d in data])\n', (2245, 2268), True, 'import numpy as np\n'), ((6951, 6976), 'numpy.sum', 'np.sum', (['memberships[inds]'], {}), '(memberships[inds])\n', (6957, 6976), True, 'import numpy as np\n'), ((8179, 8206), 'numpy.unique', 'np.unique', (['data[:, feature]'], {}), '(data[:, feature])\n', (8188, 8206), True, 'import numpy as np\n'), ((11954, 12044), 'tabulate.tabulate', 'tabulate', (['data_table'], {'headers': "['Class', 'First', 'Second', 'Third']", 'tablefmt': '"""orgtbl"""'}), "(data_table, headers=['Class', 'First', 'Second', 'Third'],\n tablefmt='orgtbl')\n", (11962, 12044), False, 'from tabulate import tabulate\n'), ((12781, 12808), 'matplotlib.pyplot.plot', 'plt.plot', (['xs', 'ys'], {'color': '"""g"""'}), "(xs, ys, color='g')\n", (12789, 12808), True, 'import matplotlib.pyplot as plt\n'), ((15426, 15445), 'numpy.sum', 'np.sum', (['memberships'], {}), '(memberships)\n', (15432, 15445), True, 'import numpy as np\n'), ((2031, 2051), 'math.sqrt', 'sqrt', (['self.n_feature'], {}), '(self.n_feature)\n', (2035, 2051), False, 'from math import log, sqrt, ceil\n'), ((3545, 3557), 'copy.copy', 'copy', (['ranges'], {}), '(ranges)\n', (3549, 3557), False, 'from copy import copy\n'), ((12590, 12621), 'numpy.arange', 'np.arange', (['rng[0]', 'rng[1]', '(0.05)'], {}), '(rng[0], rng[1], 0.05)\n', (12599, 12621), True, 'import numpy as np\n'), ((16478, 16531), 'random.choice', 'random.choice', (['(string.ascii_uppercase + string.digits)'], {}), '(string.ascii_uppercase + string.digits)\n', (16491, 16531), False, 'import random\n'), ((2109, 2131), 'math.log', 'log', (['self.n_feature', '(2)'], {}), '(self.n_feature, 2)\n', (2112, 2131), False, 'from math import log, sqrt, ceil\n'), ((15646, 15673), 'numpy.sum', 'np.sum', (['memberships_at_inds'], {}), '(memberships_at_inds)\n', (15652, 15673), True, 'import numpy as np\n'), ((5027, 5099), 'numpy.logical_and', 'np.logical_and', (['(data[:, i] != curr_range[0])', '(data[:, i] != curr_range[1])'], {}), '(data[:, i] != curr_range[0], data[:, i] != curr_range[1])\n', (5041, 5099), True, 'import numpy as np\n'), ((15758, 15771), 'math.log', 'log', (['proba', '(2)'], {}), '(proba, 2)\n', (15761, 15771), False, 'from math import log, sqrt, ceil\n')]
|
import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6]
])
print("print(a)")
print(a)
print()
print("print(a.T)")
print(a.T)
print()
print("print(a.dot(2))")
print(a.dot(2))
print()
print("print(a.dot(np.array([2, 2, 2])))")
print(a.dot(np.array([2, 2, 2])))
print()
|
[
"numpy.array"
] |
[((24, 56), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6]]'], {}), '([[1, 2, 3], [4, 5, 6]])\n', (32, 56), True, 'import numpy as np\n'), ((250, 269), 'numpy.array', 'np.array', (['[2, 2, 2]'], {}), '([2, 2, 2])\n', (258, 269), True, 'import numpy as np\n')]
|
import random
import numpy
import torch
from backobs.integration import extend as backobs_extend
from backobs.integration import (
extend_with_access_unreduced_loss as backobs_extend_with_access_unreduced_loss,
)
def set_deepobs_seed(seed=0):
"""Set all seeds used by DeepOBS."""
random.seed(seed)
numpy.random.seed(seed)
torch.manual_seed(seed)
def set_up_problem(
tproblem_cls,
batch_size,
force_no_l2_reg=True,
seed=None,
extend=False,
unreduced_loss=False,
):
"""Create problem with neural network, and set to train mode."""
if seed is not None:
set_deepobs_seed(0)
if force_no_l2_reg:
tproblem = tproblem_cls(batch_size, l2_reg=0.0)
else:
tproblem = tproblem_cls(batch_size)
tproblem.set_up()
tproblem.train_init_op()
if unreduced_loss and not extend:
raise ValueError("To use unreduced_loss, enable the extend option.")
if extend:
if unreduced_loss:
backobs_extend_with_access_unreduced_loss(tproblem)
else:
tproblem = backobs_extend(tproblem)
return tproblem
def get_reduction_factor(loss, unreduced_loss):
"""Return the factor used to reduce the individual losses."""
mean_loss = unreduced_loss.flatten().mean()
sum_loss = unreduced_loss.flatten().sum()
if torch.allclose(mean_loss, sum_loss):
raise RuntimeError(
"Cannot determine reduction factor. ",
"Results from 'mean' and 'sum' reduction are identical. ",
f"'mean': {mean_loss}, 'sum': {sum_loss}",
)
if torch.allclose(loss, mean_loss):
factor = 1.0 / unreduced_loss.numel()
elif torch.allclose(loss, sum_loss):
factor = 1.0
else:
raise RuntimeError(
"Reductions 'mean' or 'sum' do not match with loss. ",
f"'mean': {mean_loss}, 'sum': {sum_loss}, loss: {loss}",
)
return factor
atol = 1e-5
rtol = 1e-5
def report_nonclose_values(x, y):
x_numpy = x.data.cpu().numpy().flatten()
y_numpy = y.data.cpu().numpy().flatten()
close = numpy.isclose(x_numpy, y_numpy, atol=atol, rtol=rtol)
where_not_close = numpy.argwhere(numpy.logical_not(close))
for idx in where_not_close:
x, y = x_numpy[idx], y_numpy[idx]
print("{} versus {}. Ratio of {}".format(x, y, y / x))
def check_sizes_and_values(*plists, atol=atol, rtol=rtol):
check_sizes(*plists)
list1, list2 = plists
check_values(list1, list2, atol=atol, rtol=rtol)
def check_sizes(*plists):
for i in range(len(plists) - 1):
assert len(plists[i]) == len(plists[i + 1])
for params in zip(*plists):
for i in range(len(params) - 1):
assert params[i].size() == params[i + 1].size()
def check_values(list1, list2, atol=atol, rtol=rtol):
for i, (g1, g2) in enumerate(zip(list1, list2)):
print(i)
print(g1.size())
report_nonclose_values(g1, g2)
assert torch.allclose(g1, g2, atol=atol, rtol=rtol)
|
[
"numpy.random.seed",
"torch.manual_seed",
"numpy.logical_not",
"numpy.isclose",
"random.seed",
"backobs.integration.extend_with_access_unreduced_loss",
"torch.allclose",
"backobs.integration.extend"
] |
[((296, 313), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (307, 313), False, 'import random\n'), ((318, 341), 'numpy.random.seed', 'numpy.random.seed', (['seed'], {}), '(seed)\n', (335, 341), False, 'import numpy\n'), ((346, 369), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (363, 369), False, 'import torch\n'), ((1348, 1383), 'torch.allclose', 'torch.allclose', (['mean_loss', 'sum_loss'], {}), '(mean_loss, sum_loss)\n', (1362, 1383), False, 'import torch\n'), ((1608, 1639), 'torch.allclose', 'torch.allclose', (['loss', 'mean_loss'], {}), '(loss, mean_loss)\n', (1622, 1639), False, 'import torch\n'), ((2117, 2170), 'numpy.isclose', 'numpy.isclose', (['x_numpy', 'y_numpy'], {'atol': 'atol', 'rtol': 'rtol'}), '(x_numpy, y_numpy, atol=atol, rtol=rtol)\n', (2130, 2170), False, 'import numpy\n'), ((1696, 1726), 'torch.allclose', 'torch.allclose', (['loss', 'sum_loss'], {}), '(loss, sum_loss)\n', (1710, 1726), False, 'import torch\n'), ((2208, 2232), 'numpy.logical_not', 'numpy.logical_not', (['close'], {}), '(close)\n', (2225, 2232), False, 'import numpy\n'), ((2992, 3036), 'torch.allclose', 'torch.allclose', (['g1', 'g2'], {'atol': 'atol', 'rtol': 'rtol'}), '(g1, g2, atol=atol, rtol=rtol)\n', (3006, 3036), False, 'import torch\n'), ((995, 1046), 'backobs.integration.extend_with_access_unreduced_loss', 'backobs_extend_with_access_unreduced_loss', (['tproblem'], {}), '(tproblem)\n', (1036, 1046), True, 'from backobs.integration import extend_with_access_unreduced_loss as backobs_extend_with_access_unreduced_loss\n'), ((1084, 1108), 'backobs.integration.extend', 'backobs_extend', (['tproblem'], {}), '(tproblem)\n', (1098, 1108), True, 'from backobs.integration import extend as backobs_extend\n')]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.